Compare commits
133 Commits
v0.0.3
...
da7e1a93f6
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
da7e1a93f6 | ||
|
|
334693f28c | ||
|
|
c5fd8e72b4 | ||
|
|
95b4a54326 | ||
|
|
d07ea1f63a | ||
|
|
1ddcf5d621 | ||
|
|
38d729b346 | ||
|
|
4b62627479 | ||
|
|
430cf0733d | ||
|
|
b44504500a | ||
|
|
bc690e2a87 | ||
|
|
9938a6cc26 | ||
|
|
79f7ac6c86 | ||
|
|
44b198b14d | ||
|
|
511b67c9bc | ||
|
|
c0d7e84495 | ||
|
|
4ea829af85 | ||
|
|
e0ca548ef5 | ||
|
|
2531d871e8 | ||
|
|
709d3d3fa4 | ||
|
|
ea31d0ca13 | ||
|
|
f1f4e3421b | ||
|
|
ac729dc2b9 | ||
|
|
bf23cd880a | ||
|
|
9e3412712c | ||
|
|
a434a88108 | ||
|
|
c5cead6003 | ||
|
|
f8adbbe0fe | ||
|
|
0a7954e879 | ||
|
|
f288455709 | ||
|
|
50d5880835 | ||
|
|
52eaf16a8c | ||
|
|
6b0638336a | ||
|
|
0da6ad6802 | ||
|
|
dd3cd6b66c | ||
|
|
1d08dec5fe | ||
|
|
0d57920bc1 | ||
|
|
1629dbc77a | ||
|
|
205c90e52e | ||
|
|
ab38bfad24 | ||
|
|
68503256dc | ||
|
|
a91cc91a21 | ||
|
|
a530325fa1 | ||
|
|
d332dceb5b | ||
|
|
79855d788c | ||
|
|
ff10b66d1d | ||
|
|
fdcc38c6ae | ||
|
|
718e4dcadd | ||
|
|
7740fe209c | ||
|
|
77590f4a62 | ||
|
|
e8a3805fff | ||
|
|
99fd903144 | ||
|
|
761df3b2d0 | ||
|
|
f141d20026 | ||
|
|
bfc32c4a1e | ||
|
|
20476bdf63 | ||
|
|
0ec5a4cfed | ||
|
|
539fcd3351 | ||
|
|
ebc10a9925 | ||
|
|
e5c5920ccd | ||
|
|
3b641dd07a | ||
|
|
e00e2574ed | ||
|
|
e459155d51 | ||
|
|
06f3dd4942 | ||
|
|
0808171677 | ||
|
|
00b6ad4c36 | ||
|
|
d4f6a4a268 | ||
|
|
6e600be112 | ||
|
|
a9b08f7f27 | ||
|
|
ccfc0237fd | ||
|
|
b3705d96cc | ||
|
|
5503ce85a9 | ||
|
|
41677b71ec | ||
|
|
9cbb5d8004 | ||
|
|
cbf1b541dc | ||
|
|
5cbdbd6813 | ||
|
|
b2369c418b | ||
|
|
c4883d3413 | ||
|
|
53e78890a8 | ||
|
|
36b398ea95 | ||
|
|
ba4643dfa3 | ||
|
|
27dbb55f7b | ||
|
|
f6b26bf28b | ||
|
|
861593123d | ||
|
|
34c145e80b | ||
|
|
a24cdc0630 | ||
|
|
120f899b0d | ||
|
|
41075bbc61 | ||
|
|
7f0f60c0e3 | ||
|
|
739231d5a1 | ||
|
|
3629227aa9 | ||
|
|
618831d578 | ||
|
|
c38c22834d | ||
|
|
c8a4bd4c7b | ||
|
|
46129a6044 | ||
|
|
8fcb51d140 | ||
|
|
944773c248 | ||
|
|
7777cfc194 | ||
|
|
198639ae3f | ||
|
|
d7ca42b51b | ||
|
|
f11d531e0c | ||
|
|
a3635b5d31 | ||
|
|
bc9aa6fbad | ||
|
|
0c16665610 | ||
|
|
46f2f1ece5 | ||
|
|
4ffbb97abf | ||
|
|
98f5cbe309 | ||
|
|
93d856b3b6 | ||
| 6ea6971dd6 | |||
| 163d70e9bd | |||
| 8afef5065a | |||
| 27bf2ae45c | |||
| 1ea44ba3ae | |||
| 0af9a72937 | |||
| d650cac857 | |||
| a0cc86f189 | |||
| f322abf79a | |||
| eede6938cb | |||
| ad24a20fdb | |||
| 5ae43513a7 | |||
| cc23e73d51 | |||
| f85abef237 | |||
| 596d370f43 | |||
| 87cb55b80b | |||
| f458eb0130 | |||
| 7d8f9a39d1 | |||
| 5b6e30ad13 | |||
| 07a5c91427 | |||
| 53b980913b | |||
| 4e2ac4a091 | |||
| 3eb5bb5de3 | |||
| ebbc11bb34 | |||
| 6d5a606107 |
@@ -7,6 +7,9 @@ on:
|
|||||||
- master
|
- master
|
||||||
- develop
|
- develop
|
||||||
pull_request:
|
pull_request:
|
||||||
|
schedule:
|
||||||
|
# Nightly build at 14:00 UTC, roughly midnight in Australia/Sydney.
|
||||||
|
- cron: "0 14 * * *"
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
@@ -57,11 +60,11 @@ jobs:
|
|||||||
|
|
||||||
- name: Build Debug
|
- name: Build Debug
|
||||||
shell: powershell
|
shell: powershell
|
||||||
run: cmake --build --preset build-debug
|
run: cmake --build --preset build-debug --parallel
|
||||||
|
|
||||||
- name: Run Native Tests
|
- name: Run Native Tests And Shader Validation
|
||||||
shell: powershell
|
shell: powershell
|
||||||
run: cmake --build --preset build-debug --target RUN_TESTS
|
run: cmake --build --preset build-debug --target RUN_TESTS --parallel
|
||||||
|
|
||||||
ui-ubuntu:
|
ui-ubuntu:
|
||||||
name: React UI Build
|
name: React UI Build
|
||||||
@@ -82,6 +85,7 @@ jobs:
|
|||||||
package-windows:
|
package-windows:
|
||||||
name: Windows Release Package
|
name: Windows Release Package
|
||||||
runs-on: windows-2022
|
runs-on: windows-2022
|
||||||
|
if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch'
|
||||||
needs:
|
needs:
|
||||||
- native-windows
|
- native-windows
|
||||||
- ui-ubuntu
|
- ui-ubuntu
|
||||||
@@ -136,7 +140,7 @@ jobs:
|
|||||||
|
|
||||||
- name: Build Release
|
- name: Build Release
|
||||||
shell: powershell
|
shell: powershell
|
||||||
run: cmake --build --preset build-release
|
run: cmake --build --preset build-release --parallel
|
||||||
|
|
||||||
- name: Install Runtime Package
|
- name: Install Runtime Package
|
||||||
shell: powershell
|
shell: powershell
|
||||||
|
|||||||
90
.vscode/launch.json
vendored
90
.vscode/launch.json
vendored
@@ -9,9 +9,97 @@
|
|||||||
"args": [],
|
"args": [],
|
||||||
"stopAtEntry": false,
|
"stopAtEntry": false,
|
||||||
"cwd": "${workspaceFolder}\\build\\vs2022-x64-debug\\Debug",
|
"cwd": "${workspaceFolder}\\build\\vs2022-x64-debug\\Debug",
|
||||||
"environment": [],
|
"environment": [
|
||||||
|
{
|
||||||
|
"name": "VST_DISABLE_INPUT_CAPTURE",
|
||||||
|
"value": "1"
|
||||||
|
}
|
||||||
|
],
|
||||||
"console": "internalConsole",
|
"console": "internalConsole",
|
||||||
|
"symbolSearchPath": "${workspaceFolder}\\build\\vs2022-x64-debug\\Debug",
|
||||||
|
"requireExactSource": true,
|
||||||
|
"logging": {
|
||||||
|
"moduleLoad": true
|
||||||
|
},
|
||||||
"preLaunchTask": "Build LoopThroughWithOpenGLCompositing Debug x64"
|
"preLaunchTask": "Build LoopThroughWithOpenGLCompositing Debug x64"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Debug LoopThroughWithOpenGLCompositing - sync readback experiment",
|
||||||
|
"type": "cppvsdbg",
|
||||||
|
"request": "launch",
|
||||||
|
"program": "${workspaceFolder}\\build\\vs2022-x64-debug\\Debug\\LoopThroughWithOpenGLCompositing.exe",
|
||||||
|
"args": [],
|
||||||
|
"stopAtEntry": false,
|
||||||
|
"cwd": "${workspaceFolder}\\build\\vs2022-x64-debug\\Debug",
|
||||||
|
"environment": [
|
||||||
|
{
|
||||||
|
"name": "VST_OUTPUT_READBACK_MODE",
|
||||||
|
"value": "sync"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"console": "internalConsole",
|
||||||
|
"symbolSearchPath": "${workspaceFolder}\\build\\vs2022-x64-debug\\Debug",
|
||||||
|
"requireExactSource": true,
|
||||||
|
"logging": {
|
||||||
|
"moduleLoad": true
|
||||||
|
},
|
||||||
|
"preLaunchTask": "Build LoopThroughWithOpenGLCompositing Debug x64"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Debug LoopThroughWithOpenGLCompositing - cached output experiment",
|
||||||
|
"type": "cppvsdbg",
|
||||||
|
"request": "launch",
|
||||||
|
"program": "${workspaceFolder}\\build\\vs2022-x64-debug\\Debug\\LoopThroughWithOpenGLCompositing.exe",
|
||||||
|
"args": [],
|
||||||
|
"stopAtEntry": false,
|
||||||
|
"cwd": "${workspaceFolder}\\build\\vs2022-x64-debug\\Debug",
|
||||||
|
"environment": [
|
||||||
|
{
|
||||||
|
"name": "VST_OUTPUT_READBACK_MODE",
|
||||||
|
"value": "cached_only"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"console": "internalConsole",
|
||||||
|
"symbolSearchPath": "${workspaceFolder}\\build\\vs2022-x64-debug\\Debug",
|
||||||
|
"requireExactSource": true,
|
||||||
|
"logging": {
|
||||||
|
"moduleLoad": true
|
||||||
|
},
|
||||||
|
"preLaunchTask": "Build LoopThroughWithOpenGLCompositing Debug x64"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Debug DeckLinkRenderCadenceProbe",
|
||||||
|
"type": "cppvsdbg",
|
||||||
|
"request": "launch",
|
||||||
|
"program": "${workspaceFolder}\\build\\vs2022-x64-debug\\Debug\\DeckLinkRenderCadenceProbe.exe",
|
||||||
|
"args": [],
|
||||||
|
"stopAtEntry": false,
|
||||||
|
"cwd": "${workspaceFolder}\\build\\vs2022-x64-debug\\Debug",
|
||||||
|
"environment": [],
|
||||||
|
"console": "externalTerminal",
|
||||||
|
"symbolSearchPath": "${workspaceFolder}\\build\\vs2022-x64-debug\\Debug",
|
||||||
|
"requireExactSource": true,
|
||||||
|
"logging": {
|
||||||
|
"moduleLoad": true
|
||||||
|
},
|
||||||
|
"preLaunchTask": "Build DeckLinkRenderCadenceProbe Debug x64"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Debug RenderCadenceCompositor",
|
||||||
|
"type": "cppvsdbg",
|
||||||
|
"request": "launch",
|
||||||
|
"program": "${workspaceFolder}\\build\\vs2022-x64-debug\\Debug\\RenderCadenceCompositor.exe",
|
||||||
|
"args": [],
|
||||||
|
"stopAtEntry": false,
|
||||||
|
"cwd": "${workspaceFolder}\\build\\vs2022-x64-debug\\Debug",
|
||||||
|
"environment": [],
|
||||||
|
"console": "externalTerminal",
|
||||||
|
"symbolSearchPath": "${workspaceFolder}\\build\\vs2022-x64-debug\\Debug",
|
||||||
|
"requireExactSource": true,
|
||||||
|
"logging": {
|
||||||
|
"moduleLoad": true
|
||||||
|
},
|
||||||
|
"preLaunchTask": "Build RenderCadenceCompositor Debug x64"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
38
.vscode/tasks.json
vendored
38
.vscode/tasks.json
vendored
@@ -11,7 +11,8 @@
|
|||||||
"--config",
|
"--config",
|
||||||
"Debug",
|
"Debug",
|
||||||
"--target",
|
"--target",
|
||||||
"LoopThroughWithOpenGLCompositing"
|
"LoopThroughWithOpenGLCompositing",
|
||||||
|
"--parallel"
|
||||||
],
|
],
|
||||||
"group": {
|
"group": {
|
||||||
"kind": "build",
|
"kind": "build",
|
||||||
@@ -29,7 +30,40 @@
|
|||||||
"--config",
|
"--config",
|
||||||
"Release",
|
"Release",
|
||||||
"--target",
|
"--target",
|
||||||
"LoopThroughWithOpenGLCompositing"
|
"LoopThroughWithOpenGLCompositing",
|
||||||
|
"--parallel"
|
||||||
|
],
|
||||||
|
"group": "build",
|
||||||
|
"problemMatcher": "$msCompile"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "Build DeckLinkRenderCadenceProbe Debug x64",
|
||||||
|
"type": "process",
|
||||||
|
"command": "C:\\Program Files\\Microsoft Visual Studio\\2022\\Community\\Common7\\IDE\\CommonExtensions\\Microsoft\\CMake\\CMake\\bin\\cmake.exe",
|
||||||
|
"args": [
|
||||||
|
"--build",
|
||||||
|
"${workspaceFolder}\\build\\vs2022-x64-debug",
|
||||||
|
"--config",
|
||||||
|
"Debug",
|
||||||
|
"--target",
|
||||||
|
"DeckLinkRenderCadenceProbe",
|
||||||
|
"--parallel"
|
||||||
|
],
|
||||||
|
"group": "build",
|
||||||
|
"problemMatcher": "$msCompile"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "Build RenderCadenceCompositor Debug x64",
|
||||||
|
"type": "process",
|
||||||
|
"command": "C:\\Program Files\\Microsoft Visual Studio\\2022\\Community\\Common7\\IDE\\CommonExtensions\\Microsoft\\CMake\\CMake\\bin\\cmake.exe",
|
||||||
|
"args": [
|
||||||
|
"--build",
|
||||||
|
"${workspaceFolder}\\build\\vs2022-x64-debug",
|
||||||
|
"--config",
|
||||||
|
"Debug",
|
||||||
|
"--target",
|
||||||
|
"RenderCadenceCompositor",
|
||||||
|
"--parallel"
|
||||||
],
|
],
|
||||||
"group": "build",
|
"group": "build",
|
||||||
"problemMatcher": "$msCompile"
|
"problemMatcher": "$msCompile"
|
||||||
|
|||||||
898
CMakeLists.txt
898
CMakeLists.txt
File diff suppressed because it is too large
Load Diff
109
OSC/Test.json
109
OSC/Test.json
@@ -36,7 +36,7 @@
|
|||||||
"preArgs": "",
|
"preArgs": "",
|
||||||
"typeTags": "",
|
"typeTags": "",
|
||||||
"decimals": 2,
|
"decimals": 2,
|
||||||
"target": "127.0.0.1:9000",
|
"target": "192.168.1.46:9000",
|
||||||
"ignoreDefaults": false,
|
"ignoreDefaults": false,
|
||||||
"bypass": false,
|
"bypass": false,
|
||||||
"onCreate": "",
|
"onCreate": "",
|
||||||
@@ -53,8 +53,8 @@
|
|||||||
"visible": true,
|
"visible": true,
|
||||||
"interaction": true,
|
"interaction": true,
|
||||||
"comments": "XY control for Fisheye Reproject pan and tilt.",
|
"comments": "XY control for Fisheye Reproject pan and tilt.",
|
||||||
"width": 420,
|
"width": 460,
|
||||||
"height": 420,
|
"height": 250,
|
||||||
"expand": false,
|
"expand": false,
|
||||||
"colorText": "auto",
|
"colorText": "auto",
|
||||||
"colorWidget": "auto",
|
"colorWidget": "auto",
|
||||||
@@ -70,14 +70,14 @@
|
|||||||
"css": "",
|
"css": "",
|
||||||
"pips": true,
|
"pips": true,
|
||||||
"snap": false,
|
"snap": false,
|
||||||
"spring": false,
|
"spring": true,
|
||||||
"rangeX": {
|
"rangeX": {
|
||||||
"min": -60,
|
"min": -1,
|
||||||
"max": 60
|
"max": 1
|
||||||
},
|
},
|
||||||
"rangeY": {
|
"rangeY": {
|
||||||
"min": 45,
|
"min": 1,
|
||||||
"max": -45
|
"max": -1
|
||||||
},
|
},
|
||||||
"logScaleX": false,
|
"logScaleX": false,
|
||||||
"logScaleY": false,
|
"logScaleY": false,
|
||||||
@@ -94,13 +94,13 @@
|
|||||||
"address": "/VideoShaderToys/fisheye-reproject/xy",
|
"address": "/VideoShaderToys/fisheye-reproject/xy",
|
||||||
"preArgs": "",
|
"preArgs": "",
|
||||||
"typeTags": "",
|
"typeTags": "",
|
||||||
"decimals": "2f",
|
"decimals": "3f",
|
||||||
"target": "127.0.0.1:9000",
|
"target": "192.168.1.46:9000",
|
||||||
"ignoreDefaults": false,
|
"ignoreDefaults": false,
|
||||||
"bypass": true,
|
"bypass": true,
|
||||||
"onCreate": "",
|
"onCreate": "var state = globalThis.__fisheyePanTiltStick = globalThis.__fisheyePanTiltStick || {};\nstate.target = '192.168.1.46:9000';\nstate.panAddress = '/VideoShaderToys/fisheye-reproject/panDegrees';\nstate.tiltAddress = '/VideoShaderToys/fisheye-reproject/tiltDegrees';\nstate.minPan = -60;\nstate.maxPan = 60;\nstate.minTilt = -45;\nstate.maxTilt = 45;\nstate.pan = 0;\nstate.tilt = 0;\nstate.stickX = 0;\nstate.stickY = 0;\nstate.tickMs = 16;\nstate.stepPan = 0.75;\nstate.stepTilt = 0.75;\nstate.deadzone = 0.14;\nstate.applyCurve = function(input) {\n var amount = Math.abs(input);\n if (amount <= state.deadzone) {\n return 0;\n }\n var normalized = (amount - state.deadzone) / (1 - state.deadzone);\n var softened = normalized * normalized * (3 - (2 * normalized));\n return (input < 0 ? -1 : 1) * softened;\n};\nif (state.timer) {\n clearInterval(state.timer);\n state.timer = null;\n}",
|
||||||
"onValue": "var pan = Array.isArray(value) ? Number(value[0]) : 0;\nvar tilt = Array.isArray(value) ? Number(value[1]) : 0;\nsend('127.0.0.1:9000', '/VideoShaderToys/fisheye-reproject/panDegrees', {type: 'f', value: pan});\nsend('127.0.0.1:9000', '/VideoShaderToys/fisheye-reproject/tiltDegrees', {type: 'f', value: tilt});",
|
"onValue": "var state = globalThis.__fisheyePanTiltStick = globalThis.__fisheyePanTiltStick || {};\nvar stickX = Array.isArray(value) ? Number(value[0]) : 0;\nvar stickY = Array.isArray(value) ? Number(value[1]) : 0;\nstate.stickX = isFinite(stickX) ? state.applyCurve(stickX) : 0;\nstate.stickY = isFinite(stickY) ? state.applyCurve(stickY) : 0;",
|
||||||
"onTouch": "",
|
"onTouch": "var state = globalThis.__fisheyePanTiltStick = globalThis.__fisheyePanTiltStick || {};\nif (value) {\n if (!state.timer) {\n state.timer = setInterval(function() {\n if (!state.stickX && !state.stickY) {\n return;\n }\n state.pan = Math.max(state.minPan, Math.min(state.maxPan, state.pan + (state.stickX * state.stepPan)));\n state.tilt = Math.max(state.minTilt, Math.min(state.maxTilt, state.tilt + (state.stickY * state.stepTilt)));\n send(state.target, state.panAddress, {type: 'f', value: state.pan});\n send(state.target, state.tiltAddress, {type: 'f', value: state.tilt});\n }, state.tickMs);\n }\n} else {\n state.stickX = 0;\n state.stickY = 0;\n if (state.timer) {\n clearInterval(state.timer);\n state.timer = null;\n }\n}",
|
||||||
"pointSize": 20,
|
"pointSize": 20,
|
||||||
"ephemeral": false,
|
"ephemeral": false,
|
||||||
"label": "",
|
"label": "",
|
||||||
@@ -121,7 +121,7 @@
|
|||||||
"interaction": true,
|
"interaction": true,
|
||||||
"comments": "",
|
"comments": "",
|
||||||
"width": 90,
|
"width": 90,
|
||||||
"height": 420,
|
"height": 250,
|
||||||
"expand": false,
|
"expand": false,
|
||||||
"colorText": "auto",
|
"colorText": "auto",
|
||||||
"colorWidget": "auto",
|
"colorWidget": "auto",
|
||||||
@@ -144,90 +144,29 @@
|
|||||||
"gradient": [],
|
"gradient": [],
|
||||||
"snap": false,
|
"snap": false,
|
||||||
"touchZone": "all",
|
"touchZone": "all",
|
||||||
"spring": false,
|
"spring": true,
|
||||||
"doubleTap": false,
|
"doubleTap": false,
|
||||||
"range": {
|
"range": {
|
||||||
"min": 100,
|
"min": -1,
|
||||||
"max": 10
|
"max": 1
|
||||||
},
|
},
|
||||||
"logScale": false,
|
"logScale": false,
|
||||||
"sensitivity": 1,
|
"sensitivity": 1,
|
||||||
"steps": "",
|
"steps": "",
|
||||||
"origin": "auto",
|
"origin": "auto",
|
||||||
"value": "",
|
"value": 0,
|
||||||
"default": 90,
|
"default": 0,
|
||||||
"linkId": "",
|
"linkId": "",
|
||||||
"address": "/VideoShaderToys/fisheye-reproject/virtualFovDegrees",
|
"address": "/VideoShaderToys/fisheye-reproject/virtualFovDegrees",
|
||||||
"preArgs": "",
|
"preArgs": "",
|
||||||
"typeTags": "",
|
"typeTags": "",
|
||||||
"decimals": 2,
|
"decimals": "3f",
|
||||||
"target": "127.0.0.1:9000",
|
"target": "192.168.1.46:9000",
|
||||||
"ignoreDefaults": false,
|
|
||||||
"bypass": false,
|
|
||||||
"onCreate": "",
|
|
||||||
"onValue": "",
|
|
||||||
"onTouch": ""
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "xy",
|
|
||||||
"top": 700,
|
|
||||||
"left": 190,
|
|
||||||
"lock": false,
|
|
||||||
"id": "Pan Pad",
|
|
||||||
"visible": true,
|
|
||||||
"interaction": true,
|
|
||||||
"comments": "",
|
|
||||||
"width": "auto",
|
|
||||||
"height": "auto",
|
|
||||||
"expand": false,
|
|
||||||
"colorText": "auto",
|
|
||||||
"colorWidget": "auto",
|
|
||||||
"colorStroke": "auto",
|
|
||||||
"colorFill": "auto",
|
|
||||||
"alphaStroke": "auto",
|
|
||||||
"alphaFillOff": "auto",
|
|
||||||
"alphaFillOn": "auto",
|
|
||||||
"lineWidth": "auto",
|
|
||||||
"borderRadius": "auto",
|
|
||||||
"padding": "auto",
|
|
||||||
"html": "",
|
|
||||||
"css": "",
|
|
||||||
"pointSize": 20,
|
|
||||||
"ephemeral": false,
|
|
||||||
"pips": true,
|
|
||||||
"label": "",
|
|
||||||
"snap": false,
|
|
||||||
"spring": false,
|
|
||||||
"rangeX": {
|
|
||||||
"min": -1,
|
|
||||||
"max": 1
|
|
||||||
},
|
|
||||||
"rangeY": {
|
|
||||||
"min": -1,
|
|
||||||
"max": 1
|
|
||||||
},
|
|
||||||
"logScaleX": false,
|
|
||||||
"logScaleY": false,
|
|
||||||
"stepsX": false,
|
|
||||||
"stepsY": false,
|
|
||||||
"clipX": "",
|
|
||||||
"clipY": "",
|
|
||||||
"axisLock": "",
|
|
||||||
"doubleTap": false,
|
|
||||||
"sensitivity": 1,
|
|
||||||
"value": "",
|
|
||||||
"default": "",
|
|
||||||
"linkId": "",
|
|
||||||
"address": "/VideoShaderToys/video-transform/pan",
|
|
||||||
"preArgs": "",
|
|
||||||
"typeTags": "",
|
|
||||||
"decimals": 2,
|
|
||||||
"target": "",
|
|
||||||
"ignoreDefaults": false,
|
"ignoreDefaults": false,
|
||||||
"bypass": true,
|
"bypass": true,
|
||||||
"onCreate": "",
|
"onCreate": "var state = globalThis.__fisheyeFovStick = globalThis.__fisheyeFovStick || {};\nstate.target = '192.168.1.46:9000';\nstate.address = '/VideoShaderToys/fisheye-reproject/virtualFovDegrees';\nstate.minFov = 10;\nstate.maxFov = 100;\nstate.fov = 90;\nstate.stick = 0;\nstate.tickMs = 16;\nstate.stepFov = 0.6;\nstate.deadzone = 0.14;\nstate.applyCurve = function(input) {\n var amount = Math.abs(input);\n if (amount <= state.deadzone) {\n return 0;\n }\n var normalized = (amount - state.deadzone) / (1 - state.deadzone);\n var softened = normalized * normalized * (3 - (2 * normalized));\n return (input < 0 ? -1 : 1) * softened;\n};\nif (state.timer) {\n clearInterval(state.timer);\n state.timer = null;\n}",
|
||||||
"onValue": "var x = Array.isArray(value) ? Number(value[0]) : 0;\nvar y = Array.isArray(value) ? Number(value[1]) : 0;\nsend('127.0.0.1:9000', '/VideoShaderToys/video-transform/pan', {type: 'f', value: x}, {type: 'f', value: y});",
|
"onValue": "var state = globalThis.__fisheyeFovStick = globalThis.__fisheyeFovStick || {};\nvar stick = Number(value);\nstate.stick = isFinite(stick) ? state.applyCurve(stick) : 0;",
|
||||||
"onTouch": ""
|
"onTouch": "var state = globalThis.__fisheyeFovStick = globalThis.__fisheyeFovStick || {};\nif (value) {\n if (!state.timer) {\n state.timer = setInterval(function() {\n if (!state.stick) {\n return;\n }\n state.fov = Math.max(state.minFov, Math.min(state.maxFov, state.fov - (state.stick * state.stepFov)));\n send(state.target, state.address, {type: 'f', value: state.fov});\n }, state.tickMs);\n }\n} else {\n state.stick = 0;\n if (state.timer) {\n clearInterval(state.timer);\n state.timer = null;\n }\n}"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"tabs": []
|
"tabs": []
|
||||||
|
|||||||
71
README.md
71
README.md
@@ -1,8 +1,8 @@
|
|||||||
# Video Shader
|
# Video Shader
|
||||||
|
|
||||||
Native video shader host with an OpenGL/DeckLink render path, Slang shader packages, and a local React control UI.
|
Native video shader host with an OpenGL render path, pluggable video I/O boundary, DeckLink backend, Slang shader packages, and a local React control UI.
|
||||||
|
|
||||||
The app loads shader packages from `shaders/`, compiles Slang to GLSL at runtime, renders a configurable layer stack, and exposes a browser-based control surface over a local HTTP/WebSocket server.
|
The app loads shader packages from `shaders/`, compiles Slang to GLSL at runtime, renders a configurable layer stack, and exposes a browser-based control surface over a local HTTP/WebSocket server. Shader compilation is prepared off the frame path where possible, then committed on the render thread so editing shader files does not block video output for the whole compile.
|
||||||
|
|
||||||
## Repository Layout
|
## Repository Layout
|
||||||
|
|
||||||
@@ -15,12 +15,20 @@ The app loads shader packages from `shaders/`, compiles Slang to GLSL at runtime
|
|||||||
- `tests/`: focused native tests for pure runtime logic.
|
- `tests/`: focused native tests for pure runtime logic.
|
||||||
- `.gitea/workflows/ci.yml`: Gitea Actions CI for Windows native tests and Ubuntu UI build.
|
- `.gitea/workflows/ci.yml`: Gitea Actions CI for Windows native tests and Ubuntu UI build.
|
||||||
|
|
||||||
|
Native app internals are grouped by boundary:
|
||||||
|
|
||||||
|
- `videoio/`: backend-neutral video I/O contracts, formats, and playout timing.
|
||||||
|
- `videoio/decklink/`: DeckLink-specific device adapter, callbacks, and SDK bindings.
|
||||||
|
- `gl/renderer/`: low-level OpenGL resources and extension helpers.
|
||||||
|
- `gl/pipeline/`: frame pipeline, render passes, video I/O bridge, preview/readback, and screenshots.
|
||||||
|
- `gl/shader/`: shader compilation, texture/text assets, UBO packing, and shader program ownership.
|
||||||
|
|
||||||
## Requirements
|
## Requirements
|
||||||
|
|
||||||
- Windows with Visual Studio 2022 C++ tooling.
|
- Windows with Visual Studio 2022 C++ tooling.
|
||||||
- CMake 3.24 or newer.
|
- CMake 3.24 or newer.
|
||||||
- Node.js and npm for the control UI.
|
- Node.js and npm for the control UI.
|
||||||
- Blackmagic Desktop Video drivers and a DeckLink device.
|
- Blackmagic Desktop Video drivers and a DeckLink device for the current production video I/O backend.
|
||||||
- Slang binary release with `slangc.exe`, `slang-compiler.dll`, `slang-glslang.dll`, and `LICENSE`.
|
- Slang binary release with `slangc.exe`, `slang-compiler.dll`, `slang-glslang.dll`, and `LICENSE`.
|
||||||
|
|
||||||
Default expected Slang path:
|
Default expected Slang path:
|
||||||
@@ -41,7 +49,7 @@ Configure and build the native app:
|
|||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
cmake --preset vs2022-x64-debug
|
cmake --preset vs2022-x64-debug
|
||||||
cmake --build --preset build-debug
|
cmake --build --preset build-debug --parallel
|
||||||
```
|
```
|
||||||
|
|
||||||
Build the React control UI:
|
Build the React control UI:
|
||||||
@@ -54,6 +62,14 @@ npm run build
|
|||||||
|
|
||||||
The native app serves `ui/dist` when it exists, otherwise it falls back to the source UI directory during development.
|
The native app serves `ui/dist` when it exists, otherwise it falls back to the source UI directory during development.
|
||||||
|
|
||||||
|
The control UI provides:
|
||||||
|
|
||||||
|
- A searchable shader library for adding layers.
|
||||||
|
- Compact parameter rows with inline descriptions and OSC copy controls.
|
||||||
|
- Stack save/recall presets.
|
||||||
|
- Manual shader reload.
|
||||||
|
- Screenshot capture from the final output render target.
|
||||||
|
|
||||||
## Package
|
## Package
|
||||||
|
|
||||||
Build the UI, build the native Release target, then install into a portable runtime folder:
|
Build the UI, build the native Release target, then install into a portable runtime folder:
|
||||||
@@ -64,7 +80,7 @@ npm ci
|
|||||||
npm run build
|
npm run build
|
||||||
cd ..
|
cd ..
|
||||||
cmake --preset vs2022-x64-release
|
cmake --preset vs2022-x64-release
|
||||||
cmake --build --preset build-release
|
cmake --build --preset build-release --parallel
|
||||||
cmake --install build/vs2022-x64-release --config Release --prefix dist/VideoShader
|
cmake --install build/vs2022-x64-release --config Release --prefix dist/VideoShader
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -77,6 +93,8 @@ dist/VideoShader/
|
|||||||
shaders/
|
shaders/
|
||||||
3rdParty/slang/bin/
|
3rdParty/slang/bin/
|
||||||
ui/dist/
|
ui/dist/
|
||||||
|
docs/
|
||||||
|
SHADER_CONTRACT.md
|
||||||
runtime/templates/
|
runtime/templates/
|
||||||
third_party_notices/
|
third_party_notices/
|
||||||
```
|
```
|
||||||
@@ -96,7 +114,7 @@ Compress-Archive -Path dist/VideoShader/* -DestinationPath dist/VideoShader.zip
|
|||||||
Run native tests:
|
Run native tests:
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
cmake --build --preset build-debug --target RUN_TESTS
|
cmake --build --preset build-debug --target RUN_TESTS --parallel
|
||||||
```
|
```
|
||||||
|
|
||||||
Run the UI production build check:
|
Run the UI production build check:
|
||||||
@@ -111,6 +129,9 @@ Current native test coverage includes:
|
|||||||
- JSON parsing and serialization.
|
- JSON parsing and serialization.
|
||||||
- Parameter normalization and preset filename safety.
|
- Parameter normalization and preset filename safety.
|
||||||
- Shader manifest parsing, temporal manifest validation, and package registry scanning.
|
- Shader manifest parsing, temporal manifest validation, and package registry scanning.
|
||||||
|
- Video I/O format helpers, v210/Ay10 row-byte math, v210 pack/unpack math, playout scheduler timing, and fake backend contract coverage.
|
||||||
|
- OSC packet parsing.
|
||||||
|
- Slang validation for every available shader package.
|
||||||
|
|
||||||
## Runtime Configuration
|
## Runtime Configuration
|
||||||
|
|
||||||
@@ -120,7 +141,9 @@ Current native test coverage includes:
|
|||||||
{
|
{
|
||||||
"shaderLibrary": "shaders",
|
"shaderLibrary": "shaders",
|
||||||
"serverPort": 8080,
|
"serverPort": 8080,
|
||||||
|
"oscBindAddress": "127.0.0.1",
|
||||||
"oscPort": 9000,
|
"oscPort": 9000,
|
||||||
|
"oscSmoothing": 0.18,
|
||||||
"inputVideoFormat": "1080p",
|
"inputVideoFormat": "1080p",
|
||||||
"inputFrameRate": "59.94",
|
"inputFrameRate": "59.94",
|
||||||
"outputVideoFormat": "1080p",
|
"outputVideoFormat": "1080p",
|
||||||
@@ -131,7 +154,7 @@ Current native test coverage includes:
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
`inputVideoFormat`/`inputFrameRate` select the DeckLink capture mode. `outputVideoFormat`/`outputFrameRate` select the playout mode. The shader stack runs at input resolution and the final rendered frame is scaled once into the configured output mode. Common examples include `720p`/`50`, `720p`/`59.94`, `1080i`/`50`, `1080i`/`59.94`, `1080p`/`25`, `1080p`/`50`, `1080p`/`59.94`, and `2160p`/`59.94`, depending on card support.
|
`inputVideoFormat`/`inputFrameRate` select the video capture mode. `outputVideoFormat`/`outputFrameRate` select the playout mode. With the current DeckLink backend, supported modes depend on the installed card and driver. The shader stack runs at input resolution and the final rendered frame is scaled once into the configured output mode. Common examples include `720p`/`50`, `720p`/`59.94`, `1080i`/`50`, `1080i`/`59.94`, `1080p`/`25`, `1080p`/`50`, `1080p`/`59.94`, and `2160p`/`59.94`.
|
||||||
|
|
||||||
Legacy `videoFormat` and `frameRate` keys are still accepted and apply to both input and output unless the explicit input/output keys are present.
|
Legacy `videoFormat` and `frameRate` keys are still accepted and apply to both input and output unless the explicit input/output keys are present.
|
||||||
|
|
||||||
@@ -170,7 +193,11 @@ http://127.0.0.1:<serverPort>/docs
|
|||||||
|
|
||||||
Use those docs to inspect the `/api/state`, layer control, stack preset, and reload endpoints. Live state updates are also sent over the `/ws` WebSocket.
|
Use those docs to inspect the `/api/state`, layer control, stack preset, and reload endpoints. Live state updates are also sent over the `/ws` WebSocket.
|
||||||
|
|
||||||
The control UI also has a Screenshot button. It queues a capture of the final output render target and writes a PNG under:
|
The control UI has a **Reload shaders** button. It rescans `shaders/`, re-reads manifests, queues shader compilation, refreshes shader availability/errors, and keeps the previous working shader stack running if a changed shader fails to compile.
|
||||||
|
|
||||||
|
Each parameter row also includes a small **OSC** button. Clicking it copies that parameter's OSC route to the clipboard.
|
||||||
|
|
||||||
|
The control UI also has a **Screenshot** button. It queues a capture of the final output render target and writes a PNG under:
|
||||||
|
|
||||||
```text
|
```text
|
||||||
runtime/screenshots/
|
runtime/screenshots/
|
||||||
@@ -178,13 +205,13 @@ runtime/screenshots/
|
|||||||
|
|
||||||
## OSC Control
|
## OSC Control
|
||||||
|
|
||||||
The native host also listens for local OSC parameter control on the configured `oscPort`:
|
The native host also listens for OSC parameter control on the configured `oscBindAddress` and `oscPort`:
|
||||||
|
|
||||||
```text
|
```text
|
||||||
/VideoShaderToys/{LayerNameOrID}/{ParameterNameOrID}
|
/VideoShaderToys/{LayerNameOrID}/{ParameterNameOrID}
|
||||||
```
|
```
|
||||||
|
|
||||||
For example, `/VideoShaderToys/VHS/intensity` updates the `intensity` parameter on the first matching `VHS` layer. The listener accepts float, integer, string, and boolean OSC values, and validates them through the same shader parameter path as the REST API. See `docs/OSC_CONTROL.md` for details.
|
For example, `/VideoShaderToys/VHS/intensity` updates the `intensity` parameter on the first matching `VHS` layer. The listener accepts float, integer, string, and boolean OSC values, and validates them through the same shader parameter path as the REST API. OSC updates are coalesced and applied once per render tick, UI state broadcasts are throttled, and OSC-driven parameter changes are not autosaved to `runtime/runtime_state.json`. `oscSmoothing` adds a small per-frame easing amount for numeric OSC controls such as floats, `vec2`, and `color`, while booleans, enums, text, and triggers stay immediate. The default bind address is `127.0.0.1`; set `oscBindAddress` to `0.0.0.0` to accept OSC on all IPv4 interfaces. See `docs/OSC_CONTROL.md` for details.
|
||||||
|
|
||||||
## Shader Packages
|
## Shader Packages
|
||||||
|
|
||||||
@@ -194,10 +221,11 @@ Each shader package lives under:
|
|||||||
shaders/<id>/
|
shaders/<id>/
|
||||||
shader.json
|
shader.json
|
||||||
shader.slang
|
shader.slang
|
||||||
|
optional-extra-pass.slang
|
||||||
optional-font-or-texture-assets
|
optional-font-or-texture-assets
|
||||||
```
|
```
|
||||||
|
|
||||||
See `SHADER_CONTRACT.md` for the manifest schema, parameter types, texture assets, font/text assets, temporal history support, and the Slang entry point contract. `shaders/text-overlay/` is the reference live text package and bundles Roboto Regular with its OFL license.
|
See `SHADER_CONTRACT.md` for the manifest schema, parameter types, texture assets, font/text assets, temporal history support, optional render-pass declarations, and the Slang entry point contract. `shaders/text-overlay/` is the reference live text package and bundles Roboto Regular with its OFL license. Broken shader packages are shown as unavailable in the selector with their error text instead of preventing the app from launching.
|
||||||
|
|
||||||
## Generated Files
|
## Generated Files
|
||||||
|
|
||||||
@@ -208,6 +236,7 @@ Runtime-generated files are intentionally ignored:
|
|||||||
- `runtime/shader_cache/active_shader.frag`
|
- `runtime/shader_cache/active_shader.frag`
|
||||||
- `runtime/runtime_state.json` autosaved latest stack and parameter state.
|
- `runtime/runtime_state.json` autosaved latest stack and parameter state.
|
||||||
- `runtime/stack_presets/*.json`
|
- `runtime/stack_presets/*.json`
|
||||||
|
- `runtime/screenshots/*.png` screenshots captured from the final output render target.
|
||||||
|
|
||||||
Only `runtime/templates/` and `runtime/README.md` are tracked.
|
Only `runtime/templates/` and `runtime/README.md` are tracked.
|
||||||
|
|
||||||
@@ -236,16 +265,16 @@ If `SLANG_ROOT` is not set, the workflow falls back to the repo-local default un
|
|||||||
|
|
||||||
- Audio.
|
- Audio.
|
||||||
- Genlock.
|
- Genlock.
|
||||||
- Find a better UI library for react.
|
|
||||||
- Logs.
|
- Logs.
|
||||||
- Continue source cleanup/refactoring. Pass 2 done
|
- Add more video I/O backends now that the DeckLink path is behind `videoio/`.
|
||||||
- Support a separate sound shader `.slang` file in shader packages. (https://www.shadertoy.com/view/XsBXWt)
|
- Support a separate sound shader `.slang` file in shader packages. (https://www.shadertoy.com/view/XsBXWt)
|
||||||
- Add WebView2
|
- Add WebView2 for an embedded native control surface.
|
||||||
- move to MSDF, typography rasterisation
|
- MSDF typography rasterisation
|
||||||
- better shader search UI, pass 1
|
- More shader-library organisation and filtering as the built-in library grows.
|
||||||
- More comprehensive greenscreen shader
|
- Optional linear-light compositing mode.
|
||||||
- linear compositing?
|
- compute shaders or a small 1x1 or nx1 RGBA16f render target for arbitrary data storage
|
||||||
- compute shaders or a small 1x1 or nx1 RGBA16f render target for abritary data store
|
|
||||||
- allow shaders to read other shaders data store based on name? or output over OSC
|
- allow shaders to read other shaders data store based on name? or output over OSC
|
||||||
- Mipmappong for shader declared textures
|
- Mipmapping for shader-declared textures
|
||||||
- unwrap a fish eyelens and mirror it and map it to equirectangulr for environmnet map purposes
|
- Anotate included shaders
|
||||||
|
- allow 3 vector exposed controls
|
||||||
|
- add nearest sampling to the extra shader pass
|
||||||
|
|||||||
920
apps/DeckLinkRenderCadenceProbe/DeckLinkRenderCadenceProbe.cpp
Normal file
920
apps/DeckLinkRenderCadenceProbe/DeckLinkRenderCadenceProbe.cpp
Normal file
@@ -0,0 +1,920 @@
|
|||||||
|
#include "DeckLinkSession.h"
|
||||||
|
#include "GLExtensions.h"
|
||||||
|
#include "VideoIOFormat.h"
|
||||||
|
#include "VideoPlayoutPolicy.h"
|
||||||
|
|
||||||
|
#include <windows.h>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <atomic>
|
||||||
|
#include <chrono>
|
||||||
|
#include <cmath>
|
||||||
|
#include <condition_variable>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <deque>
|
||||||
|
#include <iomanip>
|
||||||
|
#include <iostream>
|
||||||
|
#include <mutex>
|
||||||
|
#include <sstream>
|
||||||
|
#include <string>
|
||||||
|
#include <thread>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
constexpr unsigned kDefaultWidth = 1920;
|
||||||
|
constexpr unsigned kDefaultHeight = 1080;
|
||||||
|
constexpr std::size_t kSystemFrameSlots = 12;
|
||||||
|
constexpr std::size_t kPboDepth = 6;
|
||||||
|
constexpr std::size_t kWarmupFrames = 4;
|
||||||
|
constexpr std::size_t kDeckLinkTargetBufferedFrames = 4;
|
||||||
|
|
||||||
|
enum class ProbeSlotState
|
||||||
|
{
|
||||||
|
Free,
|
||||||
|
Rendering,
|
||||||
|
Completed,
|
||||||
|
Scheduled
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ProbeFrame
|
||||||
|
{
|
||||||
|
void* bytes = nullptr;
|
||||||
|
long rowBytes = 0;
|
||||||
|
unsigned width = 0;
|
||||||
|
unsigned height = 0;
|
||||||
|
VideoIOPixelFormat pixelFormat = VideoIOPixelFormat::Bgra8;
|
||||||
|
std::size_t index = 0;
|
||||||
|
uint64_t generation = 0;
|
||||||
|
uint64_t frameIndex = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ProbeMetrics
|
||||||
|
{
|
||||||
|
uint64_t renderedFrames = 0;
|
||||||
|
uint64_t completedFrames = 0;
|
||||||
|
uint64_t scheduledFrames = 0;
|
||||||
|
uint64_t completedDrops = 0;
|
||||||
|
uint64_t acquireMisses = 0;
|
||||||
|
uint64_t scheduleUnderruns = 0;
|
||||||
|
uint64_t pboQueueMisses = 0;
|
||||||
|
std::size_t freeCount = 0;
|
||||||
|
std::size_t renderingCount = 0;
|
||||||
|
std::size_t completedCount = 0;
|
||||||
|
std::size_t scheduledCount = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
class LatestFrameStore
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
LatestFrameStore(unsigned width, unsigned height, std::size_t capacity) :
|
||||||
|
mWidth(width),
|
||||||
|
mHeight(height),
|
||||||
|
mRowBytes(VideoIORowBytes(VideoIOPixelFormat::Bgra8, width))
|
||||||
|
{
|
||||||
|
mSlots.resize(capacity);
|
||||||
|
const std::size_t byteCount = static_cast<std::size_t>(mRowBytes) * static_cast<std::size_t>(mHeight);
|
||||||
|
for (Slot& slot : mSlots)
|
||||||
|
{
|
||||||
|
slot.bytes.resize(byteCount);
|
||||||
|
slot.generation = 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool AcquireForRender(ProbeFrame& frame)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
|
if (!AcquireFreeLocked(frame))
|
||||||
|
{
|
||||||
|
if (!DropOldestCompletedLocked() || !AcquireFreeLocked(frame))
|
||||||
|
{
|
||||||
|
++mMetrics.acquireMisses;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool PublishCompleted(const ProbeFrame& frame)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
|
if (!IsValidLocked(frame))
|
||||||
|
return false;
|
||||||
|
Slot& slot = mSlots[frame.index];
|
||||||
|
if (slot.state != ProbeSlotState::Rendering)
|
||||||
|
return false;
|
||||||
|
slot.state = ProbeSlotState::Completed;
|
||||||
|
slot.frameIndex = frame.frameIndex;
|
||||||
|
mCompletedIndices.push_back(frame.index);
|
||||||
|
++mMetrics.completedFrames;
|
||||||
|
mCondition.notify_all();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ConsumeCompleted(ProbeFrame& frame)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
|
while (!mCompletedIndices.empty())
|
||||||
|
{
|
||||||
|
const std::size_t index = mCompletedIndices.front();
|
||||||
|
mCompletedIndices.pop_front();
|
||||||
|
if (index >= mSlots.size() || mSlots[index].state != ProbeSlotState::Completed)
|
||||||
|
continue;
|
||||||
|
mSlots[index].state = ProbeSlotState::Scheduled;
|
||||||
|
FillFrameLocked(index, frame);
|
||||||
|
++mMetrics.scheduledFrames;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
++mMetrics.scheduleUnderruns;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ReleaseByBytes(void* bytes)
|
||||||
|
{
|
||||||
|
if (bytes == nullptr)
|
||||||
|
return false;
|
||||||
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
|
for (std::size_t index = 0; index < mSlots.size(); ++index)
|
||||||
|
{
|
||||||
|
if (mSlots[index].bytes.data() != bytes)
|
||||||
|
continue;
|
||||||
|
mSlots[index].state = ProbeSlotState::Free;
|
||||||
|
++mSlots[index].generation;
|
||||||
|
RemoveCompletedIndexLocked(index);
|
||||||
|
mCondition.notify_all();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool WaitForCompletedDepth(std::size_t targetDepth, std::chrono::milliseconds timeout)
|
||||||
|
{
|
||||||
|
std::unique_lock<std::mutex> lock(mMutex);
|
||||||
|
return mCondition.wait_for(lock, timeout, [&]() {
|
||||||
|
return CompletedCountLocked() >= targetDepth;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
ProbeMetrics Metrics() const
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
|
ProbeMetrics metrics = mMetrics;
|
||||||
|
for (const Slot& slot : mSlots)
|
||||||
|
{
|
||||||
|
switch (slot.state)
|
||||||
|
{
|
||||||
|
case ProbeSlotState::Free:
|
||||||
|
++metrics.freeCount;
|
||||||
|
break;
|
||||||
|
case ProbeSlotState::Rendering:
|
||||||
|
++metrics.renderingCount;
|
||||||
|
break;
|
||||||
|
case ProbeSlotState::Completed:
|
||||||
|
++metrics.completedCount;
|
||||||
|
break;
|
||||||
|
case ProbeSlotState::Scheduled:
|
||||||
|
++metrics.scheduledCount;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return metrics;
|
||||||
|
}
|
||||||
|
|
||||||
|
void CountRenderedFrame()
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
|
++mMetrics.renderedFrames;
|
||||||
|
}
|
||||||
|
|
||||||
|
void CountPboQueueMiss()
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
|
++mMetrics.pboQueueMisses;
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
struct Slot
|
||||||
|
{
|
||||||
|
std::vector<unsigned char> bytes;
|
||||||
|
ProbeSlotState state = ProbeSlotState::Free;
|
||||||
|
uint64_t generation = 1;
|
||||||
|
uint64_t frameIndex = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
bool AcquireFreeLocked(ProbeFrame& frame)
|
||||||
|
{
|
||||||
|
for (std::size_t index = 0; index < mSlots.size(); ++index)
|
||||||
|
{
|
||||||
|
if (mSlots[index].state != ProbeSlotState::Free)
|
||||||
|
continue;
|
||||||
|
mSlots[index].state = ProbeSlotState::Rendering;
|
||||||
|
++mSlots[index].generation;
|
||||||
|
FillFrameLocked(index, frame);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool DropOldestCompletedLocked()
|
||||||
|
{
|
||||||
|
while (!mCompletedIndices.empty())
|
||||||
|
{
|
||||||
|
const std::size_t index = mCompletedIndices.front();
|
||||||
|
mCompletedIndices.pop_front();
|
||||||
|
if (index >= mSlots.size() || mSlots[index].state != ProbeSlotState::Completed)
|
||||||
|
continue;
|
||||||
|
mSlots[index].state = ProbeSlotState::Free;
|
||||||
|
++mSlots[index].generation;
|
||||||
|
++mMetrics.completedDrops;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
void FillFrameLocked(std::size_t index, ProbeFrame& frame) const
|
||||||
|
{
|
||||||
|
const Slot& slot = mSlots[index];
|
||||||
|
frame.bytes = const_cast<unsigned char*>(slot.bytes.data());
|
||||||
|
frame.rowBytes = static_cast<long>(mRowBytes);
|
||||||
|
frame.width = mWidth;
|
||||||
|
frame.height = mHeight;
|
||||||
|
frame.pixelFormat = VideoIOPixelFormat::Bgra8;
|
||||||
|
frame.index = index;
|
||||||
|
frame.generation = slot.generation;
|
||||||
|
frame.frameIndex = slot.frameIndex;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool IsValidLocked(const ProbeFrame& frame) const
|
||||||
|
{
|
||||||
|
return frame.index < mSlots.size() && mSlots[frame.index].generation == frame.generation;
|
||||||
|
}
|
||||||
|
|
||||||
|
void RemoveCompletedIndexLocked(std::size_t index)
|
||||||
|
{
|
||||||
|
mCompletedIndices.erase(std::remove(mCompletedIndices.begin(), mCompletedIndices.end(), index), mCompletedIndices.end());
|
||||||
|
}
|
||||||
|
|
||||||
|
std::size_t CompletedCountLocked() const
|
||||||
|
{
|
||||||
|
std::size_t count = 0;
|
||||||
|
for (const Slot& slot : mSlots)
|
||||||
|
{
|
||||||
|
if (slot.state == ProbeSlotState::Completed)
|
||||||
|
++count;
|
||||||
|
}
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
|
||||||
|
unsigned mWidth = 0;
|
||||||
|
unsigned mHeight = 0;
|
||||||
|
unsigned mRowBytes = 0;
|
||||||
|
std::vector<Slot> mSlots;
|
||||||
|
std::deque<std::size_t> mCompletedIndices;
|
||||||
|
mutable std::mutex mMutex;
|
||||||
|
std::condition_variable mCondition;
|
||||||
|
ProbeMetrics mMetrics;
|
||||||
|
};
|
||||||
|
|
||||||
|
LRESULT CALLBACK ProbeWindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
|
||||||
|
{
|
||||||
|
return DefWindowProc(hwnd, message, wParam, lParam);
|
||||||
|
}
|
||||||
|
|
||||||
|
class HiddenOpenGLContext
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
~HiddenOpenGLContext()
|
||||||
|
{
|
||||||
|
Destroy();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Create(unsigned width, unsigned height, std::string& error)
|
||||||
|
{
|
||||||
|
mInstance = GetModuleHandle(nullptr);
|
||||||
|
WNDCLASSA wc = {};
|
||||||
|
wc.style = CS_OWNDC;
|
||||||
|
wc.lpfnWndProc = ProbeWindowProc;
|
||||||
|
wc.hInstance = mInstance;
|
||||||
|
wc.lpszClassName = "DeckLinkRenderCadenceProbeWindow";
|
||||||
|
RegisterClassA(&wc);
|
||||||
|
|
||||||
|
mWindow = CreateWindowA(
|
||||||
|
wc.lpszClassName,
|
||||||
|
"DeckLink Render Cadence Probe",
|
||||||
|
WS_OVERLAPPEDWINDOW,
|
||||||
|
CW_USEDEFAULT,
|
||||||
|
CW_USEDEFAULT,
|
||||||
|
static_cast<int>(width),
|
||||||
|
static_cast<int>(height),
|
||||||
|
nullptr,
|
||||||
|
nullptr,
|
||||||
|
mInstance,
|
||||||
|
nullptr);
|
||||||
|
if (!mWindow)
|
||||||
|
{
|
||||||
|
error = "CreateWindowA failed.";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
mDc = GetDC(mWindow);
|
||||||
|
if (!mDc)
|
||||||
|
{
|
||||||
|
error = "GetDC failed.";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
PIXELFORMATDESCRIPTOR pfd = {};
|
||||||
|
pfd.nSize = sizeof(pfd);
|
||||||
|
pfd.nVersion = 1;
|
||||||
|
pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
|
||||||
|
pfd.iPixelType = PFD_TYPE_RGBA;
|
||||||
|
pfd.cColorBits = 32;
|
||||||
|
pfd.cDepthBits = 0;
|
||||||
|
pfd.iLayerType = PFD_MAIN_PLANE;
|
||||||
|
|
||||||
|
const int pixelFormat = ChoosePixelFormat(mDc, &pfd);
|
||||||
|
if (pixelFormat == 0 || !SetPixelFormat(mDc, pixelFormat, &pfd))
|
||||||
|
{
|
||||||
|
error = "Could not choose/set a pixel format.";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
mGlrc = wglCreateContext(mDc);
|
||||||
|
if (!mGlrc)
|
||||||
|
{
|
||||||
|
error = "wglCreateContext failed.";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool MakeCurrent()
|
||||||
|
{
|
||||||
|
return mDc && mGlrc && wglMakeCurrent(mDc, mGlrc);
|
||||||
|
}
|
||||||
|
|
||||||
|
void ClearCurrent()
|
||||||
|
{
|
||||||
|
wglMakeCurrent(nullptr, nullptr);
|
||||||
|
}
|
||||||
|
|
||||||
|
void Destroy()
|
||||||
|
{
|
||||||
|
ClearCurrent();
|
||||||
|
if (mGlrc)
|
||||||
|
{
|
||||||
|
wglDeleteContext(mGlrc);
|
||||||
|
mGlrc = nullptr;
|
||||||
|
}
|
||||||
|
if (mWindow && mDc)
|
||||||
|
{
|
||||||
|
ReleaseDC(mWindow, mDc);
|
||||||
|
mDc = nullptr;
|
||||||
|
}
|
||||||
|
if (mWindow)
|
||||||
|
{
|
||||||
|
DestroyWindow(mWindow);
|
||||||
|
mWindow = nullptr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
HINSTANCE mInstance = nullptr;
|
||||||
|
HWND mWindow = nullptr;
|
||||||
|
HDC mDc = nullptr;
|
||||||
|
HGLRC mGlrc = nullptr;
|
||||||
|
};
|
||||||
|
|
||||||
|
class RenderCadenceProbe
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
RenderCadenceProbe(LatestFrameStore& frameStore, unsigned width, unsigned height, double frameDurationMs) :
|
||||||
|
mFrameStore(frameStore),
|
||||||
|
mWidth(width),
|
||||||
|
mHeight(height),
|
||||||
|
mFrameDuration(std::chrono::duration_cast<Clock::duration>(std::chrono::duration<double, std::milli>(frameDurationMs)))
|
||||||
|
{
|
||||||
|
if (mFrameDuration <= Clock::duration::zero())
|
||||||
|
mFrameDuration = std::chrono::milliseconds(16);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Start(std::string& error)
|
||||||
|
{
|
||||||
|
mStopping = false;
|
||||||
|
mThread = std::thread([this]() { ThreadMain(); });
|
||||||
|
std::unique_lock<std::mutex> lock(mStartupMutex);
|
||||||
|
if (!mStartupCondition.wait_for(lock, std::chrono::seconds(3), [this]() { return mStarted || !mStartupError.empty(); }))
|
||||||
|
{
|
||||||
|
error = "Timed out starting render thread.";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (!mStartupError.empty())
|
||||||
|
{
|
||||||
|
error = mStartupError;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Stop()
|
||||||
|
{
|
||||||
|
mStopping = true;
|
||||||
|
if (mThread.joinable())
|
||||||
|
mThread.join();
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
struct PboSlot
|
||||||
|
{
|
||||||
|
GLuint pbo = 0;
|
||||||
|
GLsync fence = nullptr;
|
||||||
|
bool inFlight = false;
|
||||||
|
uint64_t frameIndex = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
using Clock = std::chrono::steady_clock;
|
||||||
|
|
||||||
|
void ThreadMain()
|
||||||
|
{
|
||||||
|
std::string error;
|
||||||
|
HiddenOpenGLContext context;
|
||||||
|
if (!context.Create(mWidth, mHeight, error) || !context.MakeCurrent())
|
||||||
|
{
|
||||||
|
SignalStartupFailure(error.empty() ? "OpenGL context creation failed." : error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!ResolveGLExtensions())
|
||||||
|
{
|
||||||
|
SignalStartupFailure("OpenGL extension resolution failed.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!CreateRenderTargets())
|
||||||
|
{
|
||||||
|
SignalStartupFailure("OpenGL render target creation failed.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
CreatePbos();
|
||||||
|
SignalStarted();
|
||||||
|
|
||||||
|
auto nextRenderTime = Clock::now();
|
||||||
|
while (!mStopping)
|
||||||
|
{
|
||||||
|
ConsumeCompletedPbos();
|
||||||
|
|
||||||
|
const auto now = Clock::now();
|
||||||
|
if (now < nextRenderTime)
|
||||||
|
{
|
||||||
|
std::this_thread::sleep_for((std::min)(std::chrono::milliseconds(1), std::chrono::duration_cast<std::chrono::milliseconds>(nextRenderTime - now)));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
RenderPattern(mFrameIndex);
|
||||||
|
if (!QueueReadback(mFrameIndex))
|
||||||
|
mFrameStore.CountPboQueueMiss();
|
||||||
|
mFrameStore.CountRenderedFrame();
|
||||||
|
++mFrameIndex;
|
||||||
|
nextRenderTime += mFrameDuration;
|
||||||
|
if (Clock::now() - nextRenderTime > mFrameDuration * 4)
|
||||||
|
nextRenderTime = Clock::now() + mFrameDuration;
|
||||||
|
}
|
||||||
|
|
||||||
|
FlushPbos();
|
||||||
|
DestroyPbos();
|
||||||
|
DestroyRenderTargets();
|
||||||
|
context.ClearCurrent();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool CreateRenderTargets()
|
||||||
|
{
|
||||||
|
glGenFramebuffers(1, &mFramebuffer);
|
||||||
|
glBindFramebuffer(GL_FRAMEBUFFER, mFramebuffer);
|
||||||
|
glGenTextures(1, &mTexture);
|
||||||
|
glBindTexture(GL_TEXTURE_2D, mTexture);
|
||||||
|
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
|
||||||
|
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
|
||||||
|
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
|
||||||
|
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
|
||||||
|
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, static_cast<GLsizei>(mWidth), static_cast<GLsizei>(mHeight), 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, nullptr);
|
||||||
|
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, mTexture, 0);
|
||||||
|
const bool complete = glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE;
|
||||||
|
glBindTexture(GL_TEXTURE_2D, 0);
|
||||||
|
glBindFramebuffer(GL_FRAMEBUFFER, 0);
|
||||||
|
return complete;
|
||||||
|
}
|
||||||
|
|
||||||
|
void DestroyRenderTargets()
|
||||||
|
{
|
||||||
|
if (mFramebuffer != 0)
|
||||||
|
glDeleteFramebuffers(1, &mFramebuffer);
|
||||||
|
if (mTexture != 0)
|
||||||
|
glDeleteTextures(1, &mTexture);
|
||||||
|
mFramebuffer = 0;
|
||||||
|
mTexture = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
void CreatePbos()
|
||||||
|
{
|
||||||
|
mPbos.resize(kPboDepth);
|
||||||
|
const std::size_t byteCount = static_cast<std::size_t>(VideoIORowBytes(VideoIOPixelFormat::Bgra8, mWidth)) * mHeight;
|
||||||
|
for (PboSlot& slot : mPbos)
|
||||||
|
{
|
||||||
|
glGenBuffers(1, &slot.pbo);
|
||||||
|
glBindBuffer(GL_PIXEL_PACK_BUFFER, slot.pbo);
|
||||||
|
glBufferData(GL_PIXEL_PACK_BUFFER, static_cast<GLsizeiptr>(byteCount), nullptr, GL_STREAM_READ);
|
||||||
|
}
|
||||||
|
glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
void DestroyPbos()
|
||||||
|
{
|
||||||
|
for (PboSlot& slot : mPbos)
|
||||||
|
{
|
||||||
|
if (slot.fence)
|
||||||
|
glDeleteSync(slot.fence);
|
||||||
|
if (slot.pbo != 0)
|
||||||
|
glDeleteBuffers(1, &slot.pbo);
|
||||||
|
slot = {};
|
||||||
|
}
|
||||||
|
mPbos.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
void FlushPbos()
|
||||||
|
{
|
||||||
|
for (std::size_t i = 0; i < mPbos.size() * 2; ++i)
|
||||||
|
ConsumeCompletedPbos();
|
||||||
|
}
|
||||||
|
|
||||||
|
void RenderPattern(uint64_t frameIndex)
|
||||||
|
{
|
||||||
|
const float t = static_cast<float>(frameIndex) / 60.0f;
|
||||||
|
const float red = 0.1f + 0.4f * (0.5f + 0.5f * std::sin(t));
|
||||||
|
const float green = 0.1f + 0.4f * (0.5f + 0.5f * std::sin(t * 0.73f + 1.0f));
|
||||||
|
const float blue = 0.15f + 0.3f * (0.5f + 0.5f * std::sin(t * 0.41f + 2.0f));
|
||||||
|
|
||||||
|
glBindFramebuffer(GL_FRAMEBUFFER, mFramebuffer);
|
||||||
|
glViewport(0, 0, static_cast<GLsizei>(mWidth), static_cast<GLsizei>(mHeight));
|
||||||
|
glDisable(GL_SCISSOR_TEST);
|
||||||
|
glClearColor(red, green, blue, 1.0f);
|
||||||
|
glClear(GL_COLOR_BUFFER_BIT);
|
||||||
|
|
||||||
|
const int boxWidth = static_cast<int>(mWidth / 6);
|
||||||
|
const int boxHeight = static_cast<int>(mHeight / 5);
|
||||||
|
const float phase = 0.5f + 0.5f * std::sin(t * 1.7f);
|
||||||
|
const int x = static_cast<int>(phase * static_cast<float>(mWidth - boxWidth));
|
||||||
|
const int y = static_cast<int>((0.5f + 0.5f * std::sin(t * 1.1f + 0.8f)) * static_cast<float>(mHeight - boxHeight));
|
||||||
|
|
||||||
|
glEnable(GL_SCISSOR_TEST);
|
||||||
|
glScissor(x, y, boxWidth, boxHeight);
|
||||||
|
glClearColor(1.0f - red, 0.85f, 0.15f + blue, 1.0f);
|
||||||
|
glClear(GL_COLOR_BUFFER_BIT);
|
||||||
|
glDisable(GL_SCISSOR_TEST);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool QueueReadback(uint64_t frameIndex)
|
||||||
|
{
|
||||||
|
if (mPbos.empty())
|
||||||
|
return false;
|
||||||
|
|
||||||
|
PboSlot& slot = mPbos[mWriteIndex];
|
||||||
|
if (slot.inFlight)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
const std::size_t byteCount = static_cast<std::size_t>(VideoIORowBytes(VideoIOPixelFormat::Bgra8, mWidth)) * mHeight;
|
||||||
|
glBindFramebuffer(GL_READ_FRAMEBUFFER, mFramebuffer);
|
||||||
|
glPixelStorei(GL_PACK_ALIGNMENT, 4);
|
||||||
|
glPixelStorei(GL_PACK_ROW_LENGTH, 0);
|
||||||
|
glBindBuffer(GL_PIXEL_PACK_BUFFER, slot.pbo);
|
||||||
|
glBufferData(GL_PIXEL_PACK_BUFFER, static_cast<GLsizeiptr>(byteCount), nullptr, GL_STREAM_READ);
|
||||||
|
glReadPixels(0, 0, static_cast<GLsizei>(mWidth), static_cast<GLsizei>(mHeight), GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, nullptr);
|
||||||
|
slot.fence = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
|
||||||
|
slot.inFlight = slot.fence != nullptr;
|
||||||
|
slot.frameIndex = frameIndex;
|
||||||
|
glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
|
||||||
|
mWriteIndex = (mWriteIndex + 1) % mPbos.size();
|
||||||
|
return slot.inFlight;
|
||||||
|
}
|
||||||
|
|
||||||
|
void ConsumeCompletedPbos()
|
||||||
|
{
|
||||||
|
for (std::size_t checked = 0; checked < mPbos.size(); ++checked)
|
||||||
|
{
|
||||||
|
PboSlot& slot = mPbos[mReadIndex];
|
||||||
|
if (!slot.inFlight || slot.fence == nullptr)
|
||||||
|
{
|
||||||
|
mReadIndex = (mReadIndex + 1) % mPbos.size();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const GLenum waitResult = glClientWaitSync(slot.fence, 0, 0);
|
||||||
|
if (waitResult != GL_ALREADY_SIGNALED && waitResult != GL_CONDITION_SATISFIED)
|
||||||
|
return;
|
||||||
|
|
||||||
|
ProbeFrame frame;
|
||||||
|
if (mFrameStore.AcquireForRender(frame))
|
||||||
|
{
|
||||||
|
glBindBuffer(GL_PIXEL_PACK_BUFFER, slot.pbo);
|
||||||
|
void* mapped = glMapBuffer(GL_PIXEL_PACK_BUFFER, GL_READ_ONLY);
|
||||||
|
if (mapped)
|
||||||
|
{
|
||||||
|
const std::size_t byteCount = static_cast<std::size_t>(frame.rowBytes) * frame.height;
|
||||||
|
std::memcpy(frame.bytes, mapped, byteCount);
|
||||||
|
glUnmapBuffer(GL_PIXEL_PACK_BUFFER);
|
||||||
|
frame.frameIndex = slot.frameIndex;
|
||||||
|
mFrameStore.PublishCompleted(frame);
|
||||||
|
}
|
||||||
|
glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
glDeleteSync(slot.fence);
|
||||||
|
slot.fence = nullptr;
|
||||||
|
slot.inFlight = false;
|
||||||
|
mReadIndex = (mReadIndex + 1) % mPbos.size();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void SignalStarted()
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mStartupMutex);
|
||||||
|
mStarted = true;
|
||||||
|
mStartupCondition.notify_all();
|
||||||
|
}
|
||||||
|
|
||||||
|
void SignalStartupFailure(const std::string& error)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mStartupMutex);
|
||||||
|
mStartupError = error;
|
||||||
|
mStartupCondition.notify_all();
|
||||||
|
}
|
||||||
|
|
||||||
|
LatestFrameStore& mFrameStore;
|
||||||
|
unsigned mWidth = 0;
|
||||||
|
unsigned mHeight = 0;
|
||||||
|
Clock::duration mFrameDuration;
|
||||||
|
std::thread mThread;
|
||||||
|
std::atomic<bool> mStopping{ false };
|
||||||
|
std::mutex mStartupMutex;
|
||||||
|
std::condition_variable mStartupCondition;
|
||||||
|
bool mStarted = false;
|
||||||
|
std::string mStartupError;
|
||||||
|
GLuint mFramebuffer = 0;
|
||||||
|
GLuint mTexture = 0;
|
||||||
|
std::vector<PboSlot> mPbos;
|
||||||
|
std::size_t mWriteIndex = 0;
|
||||||
|
std::size_t mReadIndex = 0;
|
||||||
|
uint64_t mFrameIndex = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
class DeckLinkProbePlayout
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
DeckLinkProbePlayout(DeckLinkSession& session, LatestFrameStore& frameStore) :
|
||||||
|
mSession(session),
|
||||||
|
mFrameStore(frameStore)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Start()
|
||||||
|
{
|
||||||
|
mStopping = false;
|
||||||
|
mThread = std::thread([this]() { ThreadMain(); });
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Stop()
|
||||||
|
{
|
||||||
|
mStopping = true;
|
||||||
|
if (mThread.joinable())
|
||||||
|
mThread.join();
|
||||||
|
}
|
||||||
|
|
||||||
|
void ThreadMain()
|
||||||
|
{
|
||||||
|
while (!mStopping)
|
||||||
|
{
|
||||||
|
const ProbeMetrics metrics = mFrameStore.Metrics();
|
||||||
|
if (metrics.scheduledCount >= kDeckLinkTargetBufferedFrames)
|
||||||
|
{
|
||||||
|
std::this_thread::sleep_for(std::chrono::milliseconds(1));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
ProbeFrame frame;
|
||||||
|
if (!mFrameStore.ConsumeCompleted(frame))
|
||||||
|
{
|
||||||
|
std::this_thread::sleep_for(std::chrono::milliseconds(1));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
VideoIOOutputFrame outputFrame;
|
||||||
|
outputFrame.bytes = frame.bytes;
|
||||||
|
outputFrame.nativeBuffer = frame.bytes;
|
||||||
|
outputFrame.rowBytes = frame.rowBytes;
|
||||||
|
outputFrame.width = frame.width;
|
||||||
|
outputFrame.height = frame.height;
|
||||||
|
outputFrame.pixelFormat = frame.pixelFormat;
|
||||||
|
|
||||||
|
if (!mSession.ScheduleOutputFrame(outputFrame))
|
||||||
|
{
|
||||||
|
mFrameStore.ReleaseByBytes(frame.bytes);
|
||||||
|
std::this_thread::sleep_for(std::chrono::milliseconds(1));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
DeckLinkSession& mSession;
|
||||||
|
LatestFrameStore& mFrameStore;
|
||||||
|
std::thread mThread;
|
||||||
|
std::atomic<bool> mStopping{ false };
|
||||||
|
};
|
||||||
|
|
||||||
|
std::string CompletionResultToString(VideoIOCompletionResult result)
|
||||||
|
{
|
||||||
|
switch (result)
|
||||||
|
{
|
||||||
|
case VideoIOCompletionResult::Completed:
|
||||||
|
return "completed";
|
||||||
|
case VideoIOCompletionResult::DisplayedLate:
|
||||||
|
return "late";
|
||||||
|
case VideoIOCompletionResult::Dropped:
|
||||||
|
return "dropped";
|
||||||
|
case VideoIOCompletionResult::Flushed:
|
||||||
|
return "flushed";
|
||||||
|
case VideoIOCompletionResult::Unknown:
|
||||||
|
default:
|
||||||
|
return "unknown";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void PrintUsage()
|
||||||
|
{
|
||||||
|
std::cout << "DeckLinkRenderCadenceProbe\n"
|
||||||
|
<< " Renders a simple OpenGL BGRA8 motion pattern on one GL thread,\n"
|
||||||
|
<< " copies completed PBO readbacks into latest-N system memory slots,\n"
|
||||||
|
<< " warms up rendered frames, then feeds DeckLink scheduled playback.\n\n"
|
||||||
|
<< "Press Enter to stop.\n";
|
||||||
|
}
|
||||||
|
|
||||||
|
class ComInitGuard
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
~ComInitGuard()
|
||||||
|
{
|
||||||
|
if (mInitialized)
|
||||||
|
CoUninitialize();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Initialize()
|
||||||
|
{
|
||||||
|
const HRESULT result = CoInitialize(nullptr);
|
||||||
|
mInitialized = SUCCEEDED(result);
|
||||||
|
mResult = result;
|
||||||
|
return mInitialized;
|
||||||
|
}
|
||||||
|
|
||||||
|
HRESULT Result() const { return mResult; }
|
||||||
|
|
||||||
|
private:
|
||||||
|
bool mInitialized = false;
|
||||||
|
HRESULT mResult = S_OK;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
int main()
|
||||||
|
{
|
||||||
|
PrintUsage();
|
||||||
|
|
||||||
|
ComInitGuard com;
|
||||||
|
if (!com.Initialize())
|
||||||
|
{
|
||||||
|
std::cerr << "COM initialization failed: 0x" << std::hex << com.Result() << std::dec << "\n";
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
LatestFrameStore frameStore(kDefaultWidth, kDefaultHeight, kSystemFrameSlots);
|
||||||
|
DeckLinkSession deckLink;
|
||||||
|
std::atomic<uint64_t> completions{ 0 };
|
||||||
|
std::atomic<uint64_t> late{ 0 };
|
||||||
|
std::atomic<uint64_t> dropped{ 0 };
|
||||||
|
|
||||||
|
VideoFormatSelection formats;
|
||||||
|
std::string error;
|
||||||
|
if (!deckLink.DiscoverDevicesAndModes(formats, error))
|
||||||
|
{
|
||||||
|
std::cerr << "DeckLink discovery failed: " << error << "\n";
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
if (!deckLink.SelectPreferredFormats(formats, false, error))
|
||||||
|
{
|
||||||
|
std::cerr << "DeckLink format selection failed: " << error << "\n";
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
if (!deckLink.ConfigureOutput(
|
||||||
|
[&](const VideoIOCompletion& completion) {
|
||||||
|
frameStore.ReleaseByBytes(completion.outputFrameBuffer);
|
||||||
|
++completions;
|
||||||
|
if (completion.result == VideoIOCompletionResult::DisplayedLate)
|
||||||
|
++late;
|
||||||
|
else if (completion.result == VideoIOCompletionResult::Dropped)
|
||||||
|
++dropped;
|
||||||
|
},
|
||||||
|
formats.output,
|
||||||
|
false,
|
||||||
|
error))
|
||||||
|
{
|
||||||
|
std::cerr << "DeckLink output configuration failed: " << error << "\n";
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
if (!deckLink.PrepareOutputSchedule())
|
||||||
|
{
|
||||||
|
std::cerr << "DeckLink schedule preparation failed.\n";
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
const VideoIOState& state = deckLink.State();
|
||||||
|
if (state.outputFrameSize.width != kDefaultWidth || state.outputFrameSize.height != kDefaultHeight)
|
||||||
|
{
|
||||||
|
std::cerr << "This probe currently expects 1920x1080 output. Selected mode is "
|
||||||
|
<< state.outputFrameSize.width << "x" << state.outputFrameSize.height << ".\n";
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
RenderCadenceProbe renderer(frameStore, state.outputFrameSize.width, state.outputFrameSize.height, state.frameBudgetMilliseconds);
|
||||||
|
if (!renderer.Start(error))
|
||||||
|
{
|
||||||
|
std::cerr << "Render thread start failed: " << error << "\n";
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::cout << "Warming up " << kWarmupFrames << " rendered frames at cadence...\n";
|
||||||
|
if (!frameStore.WaitForCompletedDepth(kWarmupFrames, std::chrono::seconds(3)))
|
||||||
|
{
|
||||||
|
std::cerr << "Timed out waiting for rendered warmup frames.\n";
|
||||||
|
renderer.Stop();
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
DeckLinkProbePlayout playout(deckLink, frameStore);
|
||||||
|
playout.Start();
|
||||||
|
|
||||||
|
const auto prerollDeadline = std::chrono::steady_clock::now() + std::chrono::seconds(3);
|
||||||
|
while (std::chrono::steady_clock::now() < prerollDeadline)
|
||||||
|
{
|
||||||
|
if (frameStore.Metrics().scheduledCount >= kDeckLinkTargetBufferedFrames)
|
||||||
|
break;
|
||||||
|
std::this_thread::sleep_for(std::chrono::milliseconds(2));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!deckLink.StartScheduledPlayback())
|
||||||
|
{
|
||||||
|
std::cerr << "DeckLink scheduled playback failed to start.\n";
|
||||||
|
playout.Stop();
|
||||||
|
renderer.Stop();
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::atomic<bool> metricsStopping{ false };
|
||||||
|
std::thread metricsThread([&]() {
|
||||||
|
uint64_t lastRendered = 0;
|
||||||
|
uint64_t lastScheduled = 0;
|
||||||
|
auto lastTime = std::chrono::steady_clock::now();
|
||||||
|
while (!metricsStopping)
|
||||||
|
{
|
||||||
|
std::this_thread::sleep_for(std::chrono::seconds(1));
|
||||||
|
const auto now = std::chrono::steady_clock::now();
|
||||||
|
const double seconds = std::chrono::duration_cast<std::chrono::duration<double>>(now - lastTime).count();
|
||||||
|
const ProbeMetrics metrics = frameStore.Metrics();
|
||||||
|
const double renderFps = seconds > 0.0 ? static_cast<double>(metrics.renderedFrames - lastRendered) / seconds : 0.0;
|
||||||
|
const double scheduleFps = seconds > 0.0 ? static_cast<double>(metrics.scheduledFrames - lastScheduled) / seconds : 0.0;
|
||||||
|
lastRendered = metrics.renderedFrames;
|
||||||
|
lastScheduled = metrics.scheduledFrames;
|
||||||
|
lastTime = now;
|
||||||
|
|
||||||
|
std::cout << std::fixed << std::setprecision(1)
|
||||||
|
<< "renderFps=" << renderFps
|
||||||
|
<< " scheduleFps=" << scheduleFps
|
||||||
|
<< " free=" << metrics.freeCount
|
||||||
|
<< " completed=" << metrics.completedCount
|
||||||
|
<< " scheduled=" << metrics.scheduledCount
|
||||||
|
<< " drops=" << metrics.completedDrops
|
||||||
|
<< " pboMiss=" << metrics.pboQueueMisses
|
||||||
|
<< " completions=" << completions.load()
|
||||||
|
<< " late=" << late.load()
|
||||||
|
<< " dropped=" << dropped.load()
|
||||||
|
<< " decklinkBuffered=" << deckLink.State().actualDeckLinkBufferedFrames
|
||||||
|
<< "\n";
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
std::string line;
|
||||||
|
std::getline(std::cin, line);
|
||||||
|
|
||||||
|
metricsStopping = true;
|
||||||
|
if (metricsThread.joinable())
|
||||||
|
metricsThread.join();
|
||||||
|
playout.Stop();
|
||||||
|
deckLink.Stop();
|
||||||
|
renderer.Stop();
|
||||||
|
deckLink.ReleaseResources();
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
113
apps/DeckLinkRenderCadenceProbe/README.md
Normal file
113
apps/DeckLinkRenderCadenceProbe/README.md
Normal file
@@ -0,0 +1,113 @@
|
|||||||
|
# DeckLink Render Cadence Probe
|
||||||
|
|
||||||
|
This is a deliberately small architecture probe for the Phase 7.7 playout model.
|
||||||
|
|
||||||
|
It is not the main app and does not use the main runtime, shader stack, preview path, input upload path, or render engine.
|
||||||
|
|
||||||
|
## What It Tests
|
||||||
|
|
||||||
|
The probe validates the clean playout spine:
|
||||||
|
|
||||||
|
```text
|
||||||
|
single OpenGL render thread
|
||||||
|
owns its own hidden GL context
|
||||||
|
renders a simple moving BGRA8 pattern at output cadence
|
||||||
|
queues GPU readback through a PBO ring
|
||||||
|
copies completed readbacks into latest-N system-memory slots
|
||||||
|
|
||||||
|
system-memory frame store
|
||||||
|
owns free / rendering / completed / scheduled slots
|
||||||
|
drops old completed unscheduled frames when render cadence needs space
|
||||||
|
protects scheduled frames until DeckLink completion
|
||||||
|
|
||||||
|
DeckLink playout thread
|
||||||
|
consumes completed system-memory frames
|
||||||
|
keeps a small scheduled buffer filled
|
||||||
|
does not render
|
||||||
|
```
|
||||||
|
|
||||||
|
Startup warms up rendered frames before starting DeckLink scheduled playback.
|
||||||
|
|
||||||
|
## How To Build
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
cmake --build --preset build-debug --target DeckLinkRenderCadenceProbe -- /m:1
|
||||||
|
```
|
||||||
|
|
||||||
|
The executable is:
|
||||||
|
|
||||||
|
```text
|
||||||
|
build\vs2022-x64-debug\Debug\DeckLinkRenderCadenceProbe.exe
|
||||||
|
```
|
||||||
|
|
||||||
|
## How To Run
|
||||||
|
|
||||||
|
Run it from a terminal so you can see the telemetry:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
build\vs2022-x64-debug\Debug\DeckLinkRenderCadenceProbe.exe
|
||||||
|
```
|
||||||
|
|
||||||
|
Press Enter to stop.
|
||||||
|
|
||||||
|
The first version assumes `1080p59.94` / `1920x1080` output and BGRA8 system-memory frames.
|
||||||
|
|
||||||
|
## What To Watch
|
||||||
|
|
||||||
|
The probe prints one line per second:
|
||||||
|
|
||||||
|
- `renderFps`: cadence render throughput
|
||||||
|
- `scheduleFps`: DeckLink scheduling throughput
|
||||||
|
- `free`: free system-memory slots
|
||||||
|
- `completed`: rendered, unscheduled slots
|
||||||
|
- `scheduled`: slots currently owned by DeckLink
|
||||||
|
- `drops`: old completed unscheduled frames recycled by the latest-N cache
|
||||||
|
- `pboMiss`: PBO ring was full when trying to queue readback
|
||||||
|
- `late`: DeckLink displayed-late completions
|
||||||
|
- `dropped`: DeckLink dropped completions
|
||||||
|
- `decklinkBuffered`: actual DeckLink buffered-frame count when available
|
||||||
|
|
||||||
|
For a healthy architecture proof, expect:
|
||||||
|
|
||||||
|
- `renderFps` close to the selected output cadence
|
||||||
|
- `scheduleFps` close to the selected output cadence after warmup
|
||||||
|
- `scheduled` hovering near the target buffer depth
|
||||||
|
- `late` and `dropped` not increasing continuously
|
||||||
|
- visible motion that is smooth on the DeckLink output
|
||||||
|
|
||||||
|
## Interpretation
|
||||||
|
|
||||||
|
If this probe is smooth at 59.94/60, the broad architecture is viable and the main app's remaining stutters are likely caused by integration details such as input upload, shared render-thread work, preview/screenshot work, or runtime/render-state coupling.
|
||||||
|
|
||||||
|
If this probe is not smooth, the problem is lower level: DeckLink scheduling, OpenGL readback, Windows scheduling, or hardware/driver behavior.
|
||||||
|
|
||||||
|
## Initial Result
|
||||||
|
|
||||||
|
Date: 2026-05-12
|
||||||
|
|
||||||
|
User-visible result:
|
||||||
|
|
||||||
|
- output looked smooth
|
||||||
|
|
||||||
|
Representative telemetry:
|
||||||
|
|
||||||
|
```text
|
||||||
|
renderFps=59.9 scheduleFps=59.9 free=7 completed=1 scheduled=4 drops=0 pboMiss=0 completions=119 late=0 dropped=0 decklinkBuffered=4
|
||||||
|
renderFps=59.9 scheduleFps=59.9 free=7 completed=1 scheduled=4 drops=0 pboMiss=0 completions=179 late=0 dropped=0 decklinkBuffered=4
|
||||||
|
renderFps=59.8 scheduleFps=59.8 free=7 completed=1 scheduled=4 drops=0 pboMiss=0 completions=239 late=0 dropped=0 decklinkBuffered=4
|
||||||
|
renderFps=60.8 scheduleFps=59.8 free=7 completed=1 scheduled=4 drops=0 pboMiss=0 completions=299 late=0 dropped=0 decklinkBuffered=4
|
||||||
|
renderFps=59.9 scheduleFps=59.9 free=7 completed=1 scheduled=4 drops=0 pboMiss=0 completions=360 late=0 dropped=0 decklinkBuffered=4
|
||||||
|
renderFps=59.8 scheduleFps=60.8 free=8 completed=0 scheduled=4 drops=0 pboMiss=0 completions=420 late=0 dropped=0 decklinkBuffered=4
|
||||||
|
```
|
||||||
|
|
||||||
|
Read:
|
||||||
|
|
||||||
|
- the clean architecture can sustain the selected output cadence on the test machine
|
||||||
|
- BGRA8 PBO readback is viable when isolated from the main app's other render-thread work
|
||||||
|
- latest-N system-memory buffering stayed stable
|
||||||
|
- DeckLink actual buffered depth stayed at 4
|
||||||
|
- there were no late frames, dropped frames, completed-frame drops, or PBO misses in the sampled output
|
||||||
|
|
||||||
|
Implication:
|
||||||
|
|
||||||
|
The main app's remaining stutters are likely integration/ownership issues rather than a fundamental DeckLink/OpenGL/BGRA8 readback limit. The highest-value suspects are input upload before output render, shared render-thread queue contention, preview/screenshot work, and runtime/render-state work on the output path.
|
||||||
@@ -1,47 +1,3 @@
|
|||||||
/* -LICENSE-START-
|
|
||||||
** Copyright (c) 2012 Blackmagic Design
|
|
||||||
**
|
|
||||||
** Permission is hereby granted, free of charge, to any person or organization
|
|
||||||
** obtaining a copy of the software and accompanying documentation (the
|
|
||||||
** "Software") to use, reproduce, display, distribute, sub-license, execute,
|
|
||||||
** and transmit the Software, and to prepare derivative works of the Software,
|
|
||||||
** and to permit third-parties to whom the Software is furnished to do so, in
|
|
||||||
** accordance with:
|
|
||||||
**
|
|
||||||
** (1) if the Software is obtained from Blackmagic Design, the End User License
|
|
||||||
** Agreement for the Software Development Kit ("EULA") available at
|
|
||||||
** https://www.blackmagicdesign.com/EULA/DeckLinkSDK; or
|
|
||||||
**
|
|
||||||
** (2) if the Software is obtained from any third party, such licensing terms
|
|
||||||
** as notified by that third party,
|
|
||||||
**
|
|
||||||
** and all subject to the following:
|
|
||||||
**
|
|
||||||
** (3) the copyright notices in the Software and this entire statement,
|
|
||||||
** including the above license grant, this restriction and the following
|
|
||||||
** disclaimer, must be included in all copies of the Software, in whole or in
|
|
||||||
** part, and all derivative works of the Software, unless such copies or
|
|
||||||
** derivative works are solely in the form of machine-executable object code
|
|
||||||
** generated by a source language processor.
|
|
||||||
**
|
|
||||||
** (4) THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
|
|
||||||
** OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
||||||
** FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
|
|
||||||
** SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
|
|
||||||
** FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
|
|
||||||
** ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
|
||||||
** DEALINGS IN THE SOFTWARE.
|
|
||||||
**
|
|
||||||
** A copy of the Software is available free of charge at
|
|
||||||
** https://www.blackmagicdesign.com/desktopvideo_sdk under the EULA.
|
|
||||||
**
|
|
||||||
** -LICENSE-END-
|
|
||||||
*/
|
|
||||||
//
|
|
||||||
// LoopThroughWithOpenGLCompositing.cpp
|
|
||||||
// LoopThroughWithOpenGLCompositing
|
|
||||||
//
|
|
||||||
|
|
||||||
#include "stdafx.h"
|
#include "stdafx.h"
|
||||||
#include "resource.h"
|
#include "resource.h"
|
||||||
#include "OpenGLComposite.h"
|
#include "OpenGLComposite.h"
|
||||||
@@ -478,7 +434,7 @@ LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Deselect the current rendering context and delete it
|
// Deselect the current rendering context and delete it
|
||||||
wglMakeCurrent(hDC, NULL);
|
wglMakeCurrent(NULL, NULL);
|
||||||
wglDeleteContext(hRC);
|
wglDeleteContext(hRC);
|
||||||
|
|
||||||
// Tell the application to terminate after the window is gone
|
// Tell the application to terminate after the window is gone
|
||||||
@@ -530,15 +486,12 @@ LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
|
|||||||
|
|
||||||
if (!sInteractiveResize && pOpenGLComposite)
|
if (!sInteractiveResize && pOpenGLComposite)
|
||||||
{
|
{
|
||||||
wglMakeCurrent(hDC, hRC);
|
pOpenGLComposite->paintGL(true);
|
||||||
pOpenGLComposite->paintGL();
|
|
||||||
wglMakeCurrent( NULL, NULL );
|
|
||||||
RaiseStatusControls(sStatusStrip);
|
RaiseStatusControls(sStatusStrip);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (...)
|
catch (...)
|
||||||
{
|
{
|
||||||
wglMakeCurrent( NULL, NULL );
|
|
||||||
ShowUnhandledExceptionMessage("Paint failed inside the OpenGL runtime.");
|
ShowUnhandledExceptionMessage("Paint failed inside the OpenGL runtime.");
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
|||||||
@@ -1,47 +1,3 @@
|
|||||||
/* -LICENSE-START-
|
|
||||||
** Copyright (c) 2012 Blackmagic Design
|
|
||||||
**
|
|
||||||
** Permission is hereby granted, free of charge, to any person or organization
|
|
||||||
** obtaining a copy of the software and accompanying documentation (the
|
|
||||||
** "Software") to use, reproduce, display, distribute, sub-license, execute,
|
|
||||||
** and transmit the Software, and to prepare derivative works of the Software,
|
|
||||||
** and to permit third-parties to whom the Software is furnished to do so, in
|
|
||||||
** accordance with:
|
|
||||||
**
|
|
||||||
** (1) if the Software is obtained from Blackmagic Design, the End User License
|
|
||||||
** Agreement for the Software Development Kit ("EULA") available at
|
|
||||||
** https://www.blackmagicdesign.com/EULA/DeckLinkSDK; or
|
|
||||||
**
|
|
||||||
** (2) if the Software is obtained from any third party, such licensing terms
|
|
||||||
** as notified by that third party,
|
|
||||||
**
|
|
||||||
** and all subject to the following:
|
|
||||||
**
|
|
||||||
** (3) the copyright notices in the Software and this entire statement,
|
|
||||||
** including the above license grant, this restriction and the following
|
|
||||||
** disclaimer, must be included in all copies of the Software, in whole or in
|
|
||||||
** part, and all derivative works of the Software, unless such copies or
|
|
||||||
** derivative works are solely in the form of machine-executable object code
|
|
||||||
** generated by a source language processor.
|
|
||||||
**
|
|
||||||
** (4) THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
|
|
||||||
** OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
||||||
** FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
|
|
||||||
** SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
|
|
||||||
** FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
|
|
||||||
** ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
|
||||||
** DEALINGS IN THE SOFTWARE.
|
|
||||||
**
|
|
||||||
** A copy of the Software is available free of charge at
|
|
||||||
** https://www.blackmagicdesign.com/desktopvideo_sdk under the EULA.
|
|
||||||
**
|
|
||||||
** -LICENSE-END-
|
|
||||||
*/
|
|
||||||
//
|
|
||||||
// LoopThroughWithOpenGLCompositing.h
|
|
||||||
// LoopThroughWithOpenGLCompositing
|
|
||||||
//
|
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include "resource.h"
|
#include "resource.h"
|
||||||
|
|||||||
@@ -1,28 +0,0 @@
|
|||||||
|
|
||||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
|
||||||
# Visual Studio 2013
|
|
||||||
VisualStudioVersion = 12.0.21005.1
|
|
||||||
MinimumVisualStudioVersion = 10.0.40219.1
|
|
||||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LoopThroughWithOpenGLCompositing", "LoopThroughWithOpenGLCompositing.vcxproj", "{92C79085-CA51-4008-95DB-5403D2E19885}"
|
|
||||||
EndProject
|
|
||||||
Global
|
|
||||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
|
||||||
Debug|Win32 = Debug|Win32
|
|
||||||
Debug|x64 = Debug|x64
|
|
||||||
Release|Win32 = Release|Win32
|
|
||||||
Release|x64 = Release|x64
|
|
||||||
EndGlobalSection
|
|
||||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
|
||||||
{92C79085-CA51-4008-95DB-5403D2E19885}.Debug|Win32.ActiveCfg = Debug|Win32
|
|
||||||
{92C79085-CA51-4008-95DB-5403D2E19885}.Debug|Win32.Build.0 = Debug|Win32
|
|
||||||
{92C79085-CA51-4008-95DB-5403D2E19885}.Debug|x64.ActiveCfg = Debug|x64
|
|
||||||
{92C79085-CA51-4008-95DB-5403D2E19885}.Debug|x64.Build.0 = Debug|x64
|
|
||||||
{92C79085-CA51-4008-95DB-5403D2E19885}.Release|Win32.ActiveCfg = Release|Win32
|
|
||||||
{92C79085-CA51-4008-95DB-5403D2E19885}.Release|Win32.Build.0 = Release|Win32
|
|
||||||
{92C79085-CA51-4008-95DB-5403D2E19885}.Release|x64.ActiveCfg = Release|x64
|
|
||||||
{92C79085-CA51-4008-95DB-5403D2E19885}.Release|x64.Build.0 = Release|x64
|
|
||||||
EndGlobalSection
|
|
||||||
GlobalSection(SolutionProperties) = preSolution
|
|
||||||
HideSolutionNode = FALSE
|
|
||||||
EndGlobalSection
|
|
||||||
EndGlobal
|
|
||||||
@@ -1,233 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
|
||||||
<ItemGroup Label="ProjectConfigurations">
|
|
||||||
<ProjectConfiguration Include="Debug|Win32">
|
|
||||||
<Configuration>Debug</Configuration>
|
|
||||||
<Platform>Win32</Platform>
|
|
||||||
</ProjectConfiguration>
|
|
||||||
<ProjectConfiguration Include="Debug|x64">
|
|
||||||
<Configuration>Debug</Configuration>
|
|
||||||
<Platform>x64</Platform>
|
|
||||||
</ProjectConfiguration>
|
|
||||||
<ProjectConfiguration Include="Release|Win32">
|
|
||||||
<Configuration>Release</Configuration>
|
|
||||||
<Platform>Win32</Platform>
|
|
||||||
</ProjectConfiguration>
|
|
||||||
<ProjectConfiguration Include="Release|x64">
|
|
||||||
<Configuration>Release</Configuration>
|
|
||||||
<Platform>x64</Platform>
|
|
||||||
</ProjectConfiguration>
|
|
||||||
</ItemGroup>
|
|
||||||
<PropertyGroup Label="Globals">
|
|
||||||
<ProjectGuid>{92C79085-CA51-4008-95DB-5403D2E19885}</ProjectGuid>
|
|
||||||
<RootNamespace>LoopThroughWithOpenGLCompositing</RootNamespace>
|
|
||||||
<Keyword>Win32Proj</Keyword>
|
|
||||||
<WindowsTargetPlatformVersion>10.0.26100.0</WindowsTargetPlatformVersion>
|
|
||||||
</PropertyGroup>
|
|
||||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
|
|
||||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
|
|
||||||
<ConfigurationType>Application</ConfigurationType>
|
|
||||||
<PlatformToolset>v143</PlatformToolset>
|
|
||||||
<CharacterSet>MultiByte</CharacterSet>
|
|
||||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
|
||||||
</PropertyGroup>
|
|
||||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
|
|
||||||
<ConfigurationType>Application</ConfigurationType>
|
|
||||||
<PlatformToolset>v143</PlatformToolset>
|
|
||||||
<CharacterSet>MultiByte</CharacterSet>
|
|
||||||
</PropertyGroup>
|
|
||||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
|
|
||||||
<ConfigurationType>Application</ConfigurationType>
|
|
||||||
<PlatformToolset>v143</PlatformToolset>
|
|
||||||
<CharacterSet>MultiByte</CharacterSet>
|
|
||||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
|
||||||
</PropertyGroup>
|
|
||||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
|
|
||||||
<ConfigurationType>Application</ConfigurationType>
|
|
||||||
<PlatformToolset>v143</PlatformToolset>
|
|
||||||
<CharacterSet>MultiByte</CharacterSet>
|
|
||||||
</PropertyGroup>
|
|
||||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
|
|
||||||
<ImportGroup Label="ExtensionSettings">
|
|
||||||
</ImportGroup>
|
|
||||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
|
|
||||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
|
||||||
</ImportGroup>
|
|
||||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
|
|
||||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
|
||||||
</ImportGroup>
|
|
||||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
|
|
||||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
|
||||||
</ImportGroup>
|
|
||||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
|
|
||||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
|
||||||
</ImportGroup>
|
|
||||||
<PropertyGroup Label="UserMacros" />
|
|
||||||
<PropertyGroup>
|
|
||||||
<_ProjectFileVersion>12.0.21005.1</_ProjectFileVersion>
|
|
||||||
</PropertyGroup>
|
|
||||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
|
|
||||||
<OutDir>$(SolutionDir)$(Configuration)\</OutDir>
|
|
||||||
<IntDir>$(Configuration)\</IntDir>
|
|
||||||
<LinkIncremental>true</LinkIncremental>
|
|
||||||
</PropertyGroup>
|
|
||||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
|
|
||||||
<OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir>
|
|
||||||
<IntDir>$(Platform)\$(Configuration)\</IntDir>
|
|
||||||
<LinkIncremental>true</LinkIncremental>
|
|
||||||
</PropertyGroup>
|
|
||||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
|
||||||
<OutDir>$(SolutionDir)$(Configuration)\</OutDir>
|
|
||||||
<IntDir>$(Configuration)\</IntDir>
|
|
||||||
<LinkIncremental>false</LinkIncremental>
|
|
||||||
</PropertyGroup>
|
|
||||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
|
|
||||||
<OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir>
|
|
||||||
<IntDir>$(Platform)\$(Configuration)\</IntDir>
|
|
||||||
<LinkIncremental>false</LinkIncremental>
|
|
||||||
</PropertyGroup>
|
|
||||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
|
|
||||||
<ClCompile>
|
|
||||||
<Optimization>Disabled</Optimization>
|
|
||||||
<AdditionalIncludeDirectories>.;control;decklink;gl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
|
||||||
<PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
|
||||||
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
|
|
||||||
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
|
|
||||||
<PrecompiledHeader />
|
|
||||||
<WarningLevel>Level3</WarningLevel>
|
|
||||||
<DebugInformationFormat>EditAndContinue</DebugInformationFormat>
|
|
||||||
<LanguageStandard>stdcpp17</LanguageStandard>
|
|
||||||
</ClCompile>
|
|
||||||
<Link>
|
|
||||||
<AdditionalDependencies>opengl32.lib;Glu32.lib;Windowscodecs.lib;Ole32.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
|
||||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
|
||||||
<SubSystem>Windows</SubSystem>
|
|
||||||
<TargetMachine>MachineX86</TargetMachine>
|
|
||||||
</Link>
|
|
||||||
</ItemDefinitionGroup>
|
|
||||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
|
|
||||||
<Midl>
|
|
||||||
<TargetEnvironment>X64</TargetEnvironment>
|
|
||||||
</Midl>
|
|
||||||
<ClCompile>
|
|
||||||
<Optimization>Disabled</Optimization>
|
|
||||||
<AdditionalIncludeDirectories>.;control;decklink;gl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
|
||||||
<PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
|
||||||
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
|
|
||||||
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
|
|
||||||
<PrecompiledHeader />
|
|
||||||
<WarningLevel>Level3</WarningLevel>
|
|
||||||
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
|
|
||||||
<LanguageStandard>stdcpp17</LanguageStandard>
|
|
||||||
</ClCompile>
|
|
||||||
<Link>
|
|
||||||
<AdditionalDependencies>opengl32.lib;Glu32.lib;Windowscodecs.lib;Ole32.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
|
||||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
|
||||||
<SubSystem>Windows</SubSystem>
|
|
||||||
<TargetMachine>MachineX64</TargetMachine>
|
|
||||||
</Link>
|
|
||||||
</ItemDefinitionGroup>
|
|
||||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
|
||||||
<ClCompile>
|
|
||||||
<Optimization>MaxSpeed</Optimization>
|
|
||||||
<IntrinsicFunctions>true</IntrinsicFunctions>
|
|
||||||
<AdditionalIncludeDirectories>.;control;decklink;gl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
|
||||||
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
|
||||||
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
|
|
||||||
<FunctionLevelLinking>true</FunctionLevelLinking>
|
|
||||||
<PrecompiledHeader />
|
|
||||||
<WarningLevel>Level3</WarningLevel>
|
|
||||||
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
|
|
||||||
<LanguageStandard>stdcpp17</LanguageStandard>
|
|
||||||
</ClCompile>
|
|
||||||
<Link>
|
|
||||||
<AdditionalDependencies>opengl32.lib;Glu32.lib;Windowscodecs.lib;Ole32.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
|
||||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
|
||||||
<SubSystem>Windows</SubSystem>
|
|
||||||
<OptimizeReferences>true</OptimizeReferences>
|
|
||||||
<EnableCOMDATFolding>true</EnableCOMDATFolding>
|
|
||||||
<TargetMachine>MachineX86</TargetMachine>
|
|
||||||
</Link>
|
|
||||||
</ItemDefinitionGroup>
|
|
||||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
|
|
||||||
<Midl>
|
|
||||||
<TargetEnvironment>X64</TargetEnvironment>
|
|
||||||
</Midl>
|
|
||||||
<ClCompile>
|
|
||||||
<Optimization>MaxSpeed</Optimization>
|
|
||||||
<IntrinsicFunctions>true</IntrinsicFunctions>
|
|
||||||
<AdditionalIncludeDirectories>.;control;decklink;gl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
|
||||||
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
|
||||||
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
|
|
||||||
<FunctionLevelLinking>true</FunctionLevelLinking>
|
|
||||||
<PrecompiledHeader />
|
|
||||||
<WarningLevel>Level3</WarningLevel>
|
|
||||||
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
|
|
||||||
<LanguageStandard>stdcpp17</LanguageStandard>
|
|
||||||
</ClCompile>
|
|
||||||
<Link>
|
|
||||||
<AdditionalDependencies>opengl32.lib;Glu32.lib;Windowscodecs.lib;Ole32.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
|
||||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
|
||||||
<SubSystem>Windows</SubSystem>
|
|
||||||
<OptimizeReferences>true</OptimizeReferences>
|
|
||||||
<EnableCOMDATFolding>true</EnableCOMDATFolding>
|
|
||||||
<TargetMachine>MachineX64</TargetMachine>
|
|
||||||
</Link>
|
|
||||||
</ItemDefinitionGroup>
|
|
||||||
<ItemGroup>
|
|
||||||
<ClCompile Include="gl\GLExtensions.cpp" />
|
|
||||||
<ClCompile Include="LoopThroughWithOpenGLCompositing.cpp" />
|
|
||||||
<ClCompile Include="gl\OpenGLComposite.cpp" />
|
|
||||||
<ClCompile Include="gl\OpenGLRenderPass.cpp" />
|
|
||||||
<ClCompile Include="gl\OpenGLRenderer.cpp" />
|
|
||||||
<ClCompile Include="gl\OpenGLShaderPrograms.cpp" />
|
|
||||||
<ClCompile Include="gl\PngScreenshotWriter.cpp" />
|
|
||||||
<ClCompile Include="gl\ShaderBuildQueue.cpp" />
|
|
||||||
<ClCompile Include="gl\TemporalHistoryBuffers.cpp" />
|
|
||||||
<ClCompile Include="stdafx.cpp">
|
|
||||||
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Create</PrecompiledHeader>
|
|
||||||
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Create</PrecompiledHeader>
|
|
||||||
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Create</PrecompiledHeader>
|
|
||||||
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Create</PrecompiledHeader>
|
|
||||||
</ClCompile>
|
|
||||||
<ClCompile Include="DeckLinkAPI_i.c" />
|
|
||||||
<ClCompile Include="control\RuntimeServices.cpp" />
|
|
||||||
<ClCompile Include="decklink\DeckLinkSession.cpp" />
|
|
||||||
<ClCompile Include="decklink\VideoIOFormat.cpp" />
|
|
||||||
<ClCompile Include="runtime\RuntimeClock.cpp" />
|
|
||||||
</ItemGroup>
|
|
||||||
<ItemGroup>
|
|
||||||
<ClInclude Include="gl\GLExtensions.h" />
|
|
||||||
<ClInclude Include="LoopThroughWithOpenGLCompositing.h" />
|
|
||||||
<ClInclude Include="gl\OpenGLComposite.h" />
|
|
||||||
<ClInclude Include="gl\OpenGLRenderPass.h" />
|
|
||||||
<ClInclude Include="gl\OpenGLRenderer.h" />
|
|
||||||
<ClInclude Include="gl\OpenGLShaderPrograms.h" />
|
|
||||||
<ClInclude Include="gl\PngScreenshotWriter.h" />
|
|
||||||
<ClInclude Include="gl\ShaderBuildQueue.h" />
|
|
||||||
<ClInclude Include="gl\TemporalHistoryBuffers.h" />
|
|
||||||
<ClInclude Include="resource.h" />
|
|
||||||
<ClInclude Include="stdafx.h" />
|
|
||||||
<ClInclude Include="targetver.h" />
|
|
||||||
<ClInclude Include="control\RuntimeServices.h" />
|
|
||||||
<ClInclude Include="decklink\DeckLinkSession.h" />
|
|
||||||
<ClInclude Include="decklink\VideoIOFormat.h" />
|
|
||||||
<ClInclude Include="runtime\RuntimeClock.h" />
|
|
||||||
</ItemGroup>
|
|
||||||
<ItemGroup>
|
|
||||||
<Image Include="LoopThroughWithOpenGLCompositing.ico" />
|
|
||||||
<Image Include="small.ico" />
|
|
||||||
</ItemGroup>
|
|
||||||
<ItemGroup>
|
|
||||||
<None Include="video_effect.slang" />
|
|
||||||
</ItemGroup>
|
|
||||||
<ItemGroup>
|
|
||||||
<ResourceCompile Include="LoopThroughWithOpenGLCompositing.rc" />
|
|
||||||
</ItemGroup>
|
|
||||||
<ItemGroup>
|
|
||||||
<Midl Include="..\..\3rdParty\Blackmagic DeckLink SDK 16.0\Win\include\DeckLinkAPI.idl" />
|
|
||||||
</ItemGroup>
|
|
||||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
|
||||||
<ImportGroup Label="ExtensionTargets">
|
|
||||||
</ImportGroup>
|
|
||||||
</Project>
|
|
||||||
@@ -1,140 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
|
||||||
<ItemGroup>
|
|
||||||
<Filter Include="Source Files">
|
|
||||||
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
|
|
||||||
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
|
|
||||||
</Filter>
|
|
||||||
<Filter Include="Header Files">
|
|
||||||
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
|
|
||||||
<Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
|
|
||||||
</Filter>
|
|
||||||
<Filter Include="Resource Files">
|
|
||||||
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
|
|
||||||
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav</Extensions>
|
|
||||||
</Filter>
|
|
||||||
<Filter Include="DeckLink API">
|
|
||||||
<UniqueIdentifier>{1eab21d6-58f8-49e0-929b-8a4482e04756}</UniqueIdentifier>
|
|
||||||
</Filter>
|
|
||||||
</ItemGroup>
|
|
||||||
<ItemGroup>
|
|
||||||
<ClCompile Include="gl\GLExtensions.cpp">
|
|
||||||
<Filter>Source Files</Filter>
|
|
||||||
</ClCompile>
|
|
||||||
<ClCompile Include="LoopThroughWithOpenGLCompositing.cpp">
|
|
||||||
<Filter>Source Files</Filter>
|
|
||||||
</ClCompile>
|
|
||||||
<ClCompile Include="gl\OpenGLComposite.cpp">
|
|
||||||
<Filter>Source Files</Filter>
|
|
||||||
</ClCompile>
|
|
||||||
<ClCompile Include="gl\OpenGLRenderPass.cpp">
|
|
||||||
<Filter>Source Files</Filter>
|
|
||||||
</ClCompile>
|
|
||||||
<ClCompile Include="gl\OpenGLRenderer.cpp">
|
|
||||||
<Filter>Source Files</Filter>
|
|
||||||
</ClCompile>
|
|
||||||
<ClCompile Include="gl\OpenGLShaderPrograms.cpp">
|
|
||||||
<Filter>Source Files</Filter>
|
|
||||||
</ClCompile>
|
|
||||||
<ClCompile Include="gl\PngScreenshotWriter.cpp">
|
|
||||||
<Filter>Source Files</Filter>
|
|
||||||
</ClCompile>
|
|
||||||
<ClCompile Include="gl\ShaderBuildQueue.cpp">
|
|
||||||
<Filter>Source Files</Filter>
|
|
||||||
</ClCompile>
|
|
||||||
<ClCompile Include="gl\TemporalHistoryBuffers.cpp">
|
|
||||||
<Filter>Source Files</Filter>
|
|
||||||
</ClCompile>
|
|
||||||
<ClCompile Include="stdafx.cpp">
|
|
||||||
<Filter>Source Files</Filter>
|
|
||||||
</ClCompile>
|
|
||||||
<ClCompile Include="DeckLinkAPI_i.c">
|
|
||||||
<Filter>DeckLink API</Filter>
|
|
||||||
</ClCompile>
|
|
||||||
<ClCompile Include="control\RuntimeServices.cpp">
|
|
||||||
<Filter>Source Files</Filter>
|
|
||||||
</ClCompile>
|
|
||||||
<ClCompile Include="decklink\DeckLinkSession.cpp">
|
|
||||||
<Filter>Source Files</Filter>
|
|
||||||
</ClCompile>
|
|
||||||
<ClCompile Include="decklink\VideoIOFormat.cpp">
|
|
||||||
<Filter>Source Files</Filter>
|
|
||||||
</ClCompile>
|
|
||||||
<ClCompile Include="runtime\RuntimeClock.cpp">
|
|
||||||
<Filter>Source Files</Filter>
|
|
||||||
</ClCompile>
|
|
||||||
</ItemGroup>
|
|
||||||
<ItemGroup>
|
|
||||||
<ClInclude Include="gl\GLExtensions.h">
|
|
||||||
<Filter>Header Files</Filter>
|
|
||||||
</ClInclude>
|
|
||||||
<ClInclude Include="LoopThroughWithOpenGLCompositing.h">
|
|
||||||
<Filter>Header Files</Filter>
|
|
||||||
</ClInclude>
|
|
||||||
<ClInclude Include="gl\OpenGLComposite.h">
|
|
||||||
<Filter>Header Files</Filter>
|
|
||||||
</ClInclude>
|
|
||||||
<ClInclude Include="gl\OpenGLRenderPass.h">
|
|
||||||
<Filter>Header Files</Filter>
|
|
||||||
</ClInclude>
|
|
||||||
<ClInclude Include="gl\OpenGLRenderer.h">
|
|
||||||
<Filter>Header Files</Filter>
|
|
||||||
</ClInclude>
|
|
||||||
<ClInclude Include="gl\OpenGLShaderPrograms.h">
|
|
||||||
<Filter>Header Files</Filter>
|
|
||||||
</ClInclude>
|
|
||||||
<ClInclude Include="gl\PngScreenshotWriter.h">
|
|
||||||
<Filter>Header Files</Filter>
|
|
||||||
</ClInclude>
|
|
||||||
<ClInclude Include="gl\ShaderBuildQueue.h">
|
|
||||||
<Filter>Header Files</Filter>
|
|
||||||
</ClInclude>
|
|
||||||
<ClInclude Include="gl\TemporalHistoryBuffers.h">
|
|
||||||
<Filter>Header Files</Filter>
|
|
||||||
</ClInclude>
|
|
||||||
<ClInclude Include="resource.h">
|
|
||||||
<Filter>Header Files</Filter>
|
|
||||||
</ClInclude>
|
|
||||||
<ClInclude Include="stdafx.h">
|
|
||||||
<Filter>Header Files</Filter>
|
|
||||||
</ClInclude>
|
|
||||||
<ClInclude Include="targetver.h">
|
|
||||||
<Filter>Header Files</Filter>
|
|
||||||
</ClInclude>
|
|
||||||
<ClInclude Include="control\RuntimeServices.h">
|
|
||||||
<Filter>Header Files</Filter>
|
|
||||||
</ClInclude>
|
|
||||||
<ClInclude Include="decklink\DeckLinkSession.h">
|
|
||||||
<Filter>Header Files</Filter>
|
|
||||||
</ClInclude>
|
|
||||||
<ClInclude Include="decklink\VideoIOFormat.h">
|
|
||||||
<Filter>Header Files</Filter>
|
|
||||||
</ClInclude>
|
|
||||||
<ClInclude Include="runtime\RuntimeClock.h">
|
|
||||||
<Filter>Header Files</Filter>
|
|
||||||
</ClInclude>
|
|
||||||
</ItemGroup>
|
|
||||||
<ItemGroup>
|
|
||||||
<Image Include="LoopThroughWithOpenGLCompositing.ico">
|
|
||||||
<Filter>Resource Files</Filter>
|
|
||||||
</Image>
|
|
||||||
<Image Include="small.ico">
|
|
||||||
<Filter>Resource Files</Filter>
|
|
||||||
</Image>
|
|
||||||
</ItemGroup>
|
|
||||||
<ItemGroup>
|
|
||||||
<ResourceCompile Include="LoopThroughWithOpenGLCompositing.rc">
|
|
||||||
<Filter>Resource Files</Filter>
|
|
||||||
</ResourceCompile>
|
|
||||||
</ItemGroup>
|
|
||||||
<ItemGroup>
|
|
||||||
<Midl Include="..\..\include\DeckLinkAPI.idl">
|
|
||||||
<Filter>DeckLink API</Filter>
|
|
||||||
</Midl>
|
|
||||||
</ItemGroup>
|
|
||||||
<ItemGroup>
|
|
||||||
<None Include="video_effect.slang">
|
|
||||||
<Filter>Resource Files</Filter>
|
|
||||||
</None>
|
|
||||||
</ItemGroup>
|
|
||||||
</Project>
|
|
||||||
@@ -17,6 +17,7 @@
|
|||||||
namespace
|
namespace
|
||||||
{
|
{
|
||||||
constexpr DWORD kStateBroadcastIntervalMs = 250;
|
constexpr DWORD kStateBroadcastIntervalMs = 250;
|
||||||
|
constexpr DWORD kStateBroadcastThrottleMs = 50;
|
||||||
|
|
||||||
bool InitializeWinsock(std::string& error)
|
bool InitializeWinsock(std::string& error)
|
||||||
{
|
{
|
||||||
@@ -75,7 +76,7 @@ std::string GuessContentType(const std::filesystem::path& assetPath)
|
|||||||
}
|
}
|
||||||
|
|
||||||
ControlServer::ControlServer()
|
ControlServer::ControlServer()
|
||||||
: mPort(0), mRunning(false)
|
: mPort(0), mRunning(false), mBroadcastPending(false)
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -161,10 +162,16 @@ void ControlServer::Stop()
|
|||||||
|
|
||||||
void ControlServer::BroadcastState()
|
void ControlServer::BroadcastState()
|
||||||
{
|
{
|
||||||
|
mBroadcastPending = false;
|
||||||
std::lock_guard<std::mutex> lock(mMutex);
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
BroadcastStateLocked();
|
BroadcastStateLocked();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void ControlServer::RequestBroadcastState()
|
||||||
|
{
|
||||||
|
mBroadcastPending = true;
|
||||||
|
}
|
||||||
|
|
||||||
void ControlServer::ServerLoop()
|
void ControlServer::ServerLoop()
|
||||||
{
|
{
|
||||||
DWORD lastStateBroadcastMs = GetTickCount();
|
DWORD lastStateBroadcastMs = GetTickCount();
|
||||||
@@ -173,7 +180,12 @@ void ControlServer::ServerLoop()
|
|||||||
TryAcceptClient();
|
TryAcceptClient();
|
||||||
|
|
||||||
const DWORD nowMs = GetTickCount();
|
const DWORD nowMs = GetTickCount();
|
||||||
if (nowMs - lastStateBroadcastMs >= kStateBroadcastIntervalMs)
|
if (mBroadcastPending && nowMs - lastStateBroadcastMs >= kStateBroadcastThrottleMs)
|
||||||
|
{
|
||||||
|
BroadcastState();
|
||||||
|
lastStateBroadcastMs = nowMs;
|
||||||
|
}
|
||||||
|
else if (nowMs - lastStateBroadcastMs >= kStateBroadcastIntervalMs)
|
||||||
{
|
{
|
||||||
BroadcastState();
|
BroadcastState();
|
||||||
lastStateBroadcastMs = nowMs;
|
lastStateBroadcastMs = nowMs;
|
||||||
@@ -469,6 +481,7 @@ bool ControlServer::HandleWebSocketUpgrade(UniqueSocket clientSocket, const Http
|
|||||||
client.socket.reset(clientSocket.release());
|
client.socket.reset(clientSocket.release());
|
||||||
client.websocket = true;
|
client.websocket = true;
|
||||||
mClients.push_back(std::move(client));
|
mClients.push_back(std::move(client));
|
||||||
|
mBroadcastPending = false;
|
||||||
BroadcastStateLocked();
|
BroadcastStateLocked();
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
@@ -501,6 +514,9 @@ bool ControlServer::SendWebSocketText(SOCKET clientSocket, const std::string& pa
|
|||||||
|
|
||||||
void ControlServer::BroadcastStateLocked()
|
void ControlServer::BroadcastStateLocked()
|
||||||
{
|
{
|
||||||
|
if (mClients.empty())
|
||||||
|
return;
|
||||||
|
|
||||||
const std::string stateMessage = mCallbacks.getStateJson ? mCallbacks.getStateJson() : "{}";
|
const std::string stateMessage = mCallbacks.getStateJson ? mCallbacks.getStateJson() : "{}";
|
||||||
for (auto it = mClients.begin(); it != mClients.end();)
|
for (auto it = mClients.begin(); it != mClients.end();)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ public:
|
|||||||
bool Start(const std::filesystem::path& uiRoot, const std::filesystem::path& docsRoot, unsigned short preferredPort, const Callbacks& callbacks, std::string& error);
|
bool Start(const std::filesystem::path& uiRoot, const std::filesystem::path& docsRoot, unsigned short preferredPort, const Callbacks& callbacks, std::string& error);
|
||||||
void Stop();
|
void Stop();
|
||||||
void BroadcastState();
|
void BroadcastState();
|
||||||
|
void RequestBroadcastState();
|
||||||
|
|
||||||
unsigned short GetPort() const { return mPort; }
|
unsigned short GetPort() const { return mPort; }
|
||||||
|
|
||||||
@@ -100,6 +101,7 @@ private:
|
|||||||
unsigned short mPort;
|
unsigned short mPort;
|
||||||
std::thread mThread;
|
std::thread mThread;
|
||||||
std::atomic<bool> mRunning;
|
std::atomic<bool> mRunning;
|
||||||
|
std::atomic<bool> mBroadcastPending;
|
||||||
mutable std::mutex mMutex;
|
mutable std::mutex mMutex;
|
||||||
std::vector<ClientConnection> mClients;
|
std::vector<ClientConnection> mClients;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,343 @@
|
|||||||
|
#include "ControlServices.h"
|
||||||
|
|
||||||
|
#include "ControlServer.h"
|
||||||
|
#include "OscServer.h"
|
||||||
|
#include "RuntimeControlBridge.h"
|
||||||
|
#include "RuntimeEventDispatcher.h"
|
||||||
|
#include "RuntimeStore.h"
|
||||||
|
#include <windows.h>
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
constexpr auto kCompatibilityPollFallbackInterval = std::chrono::milliseconds(250);
|
||||||
|
}
|
||||||
|
|
||||||
|
ControlServices::ControlServices(RuntimeEventDispatcher& runtimeEventDispatcher) :
|
||||||
|
mControlServer(std::make_unique<ControlServer>()),
|
||||||
|
mOscServer(std::make_unique<OscServer>()),
|
||||||
|
mRuntimeEventDispatcher(runtimeEventDispatcher),
|
||||||
|
mPollRunning(false)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
ControlServices::~ControlServices()
|
||||||
|
{
|
||||||
|
Stop();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ControlServices::Start(OpenGLComposite& composite, RuntimeStore& runtimeStore, std::string& error)
|
||||||
|
{
|
||||||
|
Stop();
|
||||||
|
|
||||||
|
if (!StartControlServicesBoundary(composite, runtimeStore, *this, *mControlServer, *mOscServer, error))
|
||||||
|
{
|
||||||
|
Stop();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void ControlServices::BeginPolling(RuntimeCoordinator& runtimeCoordinator)
|
||||||
|
{
|
||||||
|
StartPolling(runtimeCoordinator);
|
||||||
|
}
|
||||||
|
|
||||||
|
void ControlServices::Stop()
|
||||||
|
{
|
||||||
|
StopPolling();
|
||||||
|
|
||||||
|
if (mOscServer)
|
||||||
|
mOscServer->Stop();
|
||||||
|
|
||||||
|
if (mControlServer)
|
||||||
|
mControlServer->Stop();
|
||||||
|
}
|
||||||
|
|
||||||
|
void ControlServices::BroadcastState()
|
||||||
|
{
|
||||||
|
if (mControlServer)
|
||||||
|
mControlServer->BroadcastState();
|
||||||
|
}
|
||||||
|
|
||||||
|
void ControlServices::RequestBroadcastState()
|
||||||
|
{
|
||||||
|
PublishRuntimeStateBroadcastRequested("control-service-request");
|
||||||
|
|
||||||
|
if (mControlServer)
|
||||||
|
mControlServer->RequestBroadcastState();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ControlServices::QueueOscUpdate(const std::string& layerKey, const std::string& parameterKey, const std::string& valueJson, std::string& error)
|
||||||
|
{
|
||||||
|
(void)error;
|
||||||
|
|
||||||
|
PendingOscUpdate update;
|
||||||
|
update.layerKey = layerKey;
|
||||||
|
update.parameterKey = parameterKey;
|
||||||
|
update.valueJson = valueJson;
|
||||||
|
|
||||||
|
const std::string routeKey = layerKey + "\n" + parameterKey;
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mPendingOscMutex);
|
||||||
|
mPendingOscUpdates[routeKey] = std::move(update);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ControlServices::ApplyPendingOscUpdates(std::vector<AppliedOscUpdate>& appliedUpdates, std::string& error)
|
||||||
|
{
|
||||||
|
appliedUpdates.clear();
|
||||||
|
|
||||||
|
std::map<std::string, PendingOscUpdate> pending;
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mPendingOscMutex);
|
||||||
|
if (mPendingOscUpdates.empty())
|
||||||
|
return true;
|
||||||
|
pending.swap(mPendingOscUpdates);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const auto& entry : pending)
|
||||||
|
{
|
||||||
|
JsonValue targetValue;
|
||||||
|
std::string parseError;
|
||||||
|
if (!ParseJson(entry.second.valueJson, targetValue, parseError))
|
||||||
|
{
|
||||||
|
OutputDebugStringA(("OSC queued value parse failed: " + parseError + "\n").c_str());
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
AppliedOscUpdate appliedUpdate;
|
||||||
|
appliedUpdate.routeKey = entry.first;
|
||||||
|
appliedUpdate.layerKey = entry.second.layerKey;
|
||||||
|
appliedUpdate.parameterKey = entry.second.parameterKey;
|
||||||
|
appliedUpdate.targetValue = targetValue;
|
||||||
|
appliedUpdates.push_back(std::move(appliedUpdate));
|
||||||
|
PublishOscValueReceived(entry.second, entry.first);
|
||||||
|
}
|
||||||
|
|
||||||
|
(void)error;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ControlServices::QueueOscCommit(const std::string& routeKey, const std::string& layerKey, const std::string& parameterKey, const JsonValue& value, uint64_t generation, std::string& error)
|
||||||
|
{
|
||||||
|
(void)error;
|
||||||
|
|
||||||
|
PendingOscCommit commit;
|
||||||
|
commit.routeKey = routeKey;
|
||||||
|
commit.layerKey = layerKey;
|
||||||
|
commit.parameterKey = parameterKey;
|
||||||
|
commit.value = value;
|
||||||
|
commit.generation = generation;
|
||||||
|
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mPendingOscCommitMutex);
|
||||||
|
mPendingOscCommits[routeKey] = std::move(commit);
|
||||||
|
}
|
||||||
|
WakePolling();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void ControlServices::ClearOscState()
|
||||||
|
{
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mPendingOscMutex);
|
||||||
|
mPendingOscUpdates.clear();
|
||||||
|
}
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mPendingOscCommitMutex);
|
||||||
|
mPendingOscCommits.clear();
|
||||||
|
}
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mCompletedOscCommitMutex);
|
||||||
|
mCompletedOscCommits.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void ControlServices::ClearOscStateForLayerKey(const std::string& layerKey)
|
||||||
|
{
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mPendingOscMutex);
|
||||||
|
for (auto it = mPendingOscUpdates.begin(); it != mPendingOscUpdates.end();)
|
||||||
|
{
|
||||||
|
if (it->second.layerKey == layerKey)
|
||||||
|
it = mPendingOscUpdates.erase(it);
|
||||||
|
else
|
||||||
|
++it;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mPendingOscCommitMutex);
|
||||||
|
for (auto it = mPendingOscCommits.begin(); it != mPendingOscCommits.end();)
|
||||||
|
{
|
||||||
|
if (it->second.layerKey == layerKey)
|
||||||
|
it = mPendingOscCommits.erase(it);
|
||||||
|
else
|
||||||
|
++it;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mCompletedOscCommitMutex);
|
||||||
|
for (auto it = mCompletedOscCommits.begin(); it != mCompletedOscCommits.end();)
|
||||||
|
{
|
||||||
|
if (it->routeKey.rfind(layerKey + "\n", 0) == 0)
|
||||||
|
it = mCompletedOscCommits.erase(it);
|
||||||
|
else
|
||||||
|
++it;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void ControlServices::ConsumeCompletedOscCommits(std::vector<CompletedOscCommit>& completedCommits)
|
||||||
|
{
|
||||||
|
completedCommits.clear();
|
||||||
|
|
||||||
|
std::lock_guard<std::mutex> lock(mCompletedOscCommitMutex);
|
||||||
|
if (mCompletedOscCommits.empty())
|
||||||
|
return;
|
||||||
|
|
||||||
|
completedCommits.swap(mCompletedOscCommits);
|
||||||
|
}
|
||||||
|
|
||||||
|
void ControlServices::StartPolling(RuntimeCoordinator& runtimeCoordinator)
|
||||||
|
{
|
||||||
|
if (mPollRunning.exchange(true))
|
||||||
|
return;
|
||||||
|
|
||||||
|
mPollThread = std::thread([this, &runtimeCoordinator]() { PollLoop(runtimeCoordinator); });
|
||||||
|
}
|
||||||
|
|
||||||
|
void ControlServices::StopPolling()
|
||||||
|
{
|
||||||
|
if (!mPollRunning.exchange(false))
|
||||||
|
return;
|
||||||
|
|
||||||
|
WakePolling();
|
||||||
|
if (mPollThread.joinable())
|
||||||
|
mPollThread.join();
|
||||||
|
}
|
||||||
|
|
||||||
|
void ControlServices::PollLoop(RuntimeCoordinator& runtimeCoordinator)
|
||||||
|
{
|
||||||
|
while (mPollRunning)
|
||||||
|
{
|
||||||
|
std::map<std::string, PendingOscCommit> pendingCommits;
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mPendingOscCommitMutex);
|
||||||
|
pendingCommits.swap(mPendingOscCommits);
|
||||||
|
}
|
||||||
|
for (const auto& entry : pendingCommits)
|
||||||
|
{
|
||||||
|
PublishOscCommitRequested(entry.second);
|
||||||
|
const RuntimeCoordinatorResult result = runtimeCoordinator.CommitOscParameterByControlKey(
|
||||||
|
entry.second.layerKey,
|
||||||
|
entry.second.parameterKey,
|
||||||
|
entry.second.value);
|
||||||
|
if (result.accepted)
|
||||||
|
{
|
||||||
|
CompletedOscCommit completedCommit;
|
||||||
|
completedCommit.routeKey = entry.second.routeKey;
|
||||||
|
completedCommit.generation = entry.second.generation;
|
||||||
|
std::lock_guard<std::mutex> lock(mCompletedOscCommitMutex);
|
||||||
|
mCompletedOscCommits.push_back(std::move(completedCommit));
|
||||||
|
PublishOscOverlaySettled(entry.second);
|
||||||
|
}
|
||||||
|
else if (!result.errorMessage.empty())
|
||||||
|
{
|
||||||
|
OutputDebugStringA(("OSC commit failed: " + result.errorMessage + "\n").c_str());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool registryChanged = false;
|
||||||
|
const RuntimeCoordinatorResult pollResult = runtimeCoordinator.PollRuntimeStoreChanges(registryChanged);
|
||||||
|
if (pollResult.compileStatusChanged && !pollResult.compileStatusSucceeded && !pollResult.compileStatusMessage.empty())
|
||||||
|
OutputDebugStringA(("Runtime poll failed: " + pollResult.compileStatusMessage + "\n").c_str());
|
||||||
|
|
||||||
|
std::unique_lock<std::mutex> wakeLock(mPollWakeMutex);
|
||||||
|
mPollWakeCondition.wait_for(wakeLock, kCompatibilityPollFallbackInterval, [this]() {
|
||||||
|
return !mPollRunning.load() || mPollWakeRequested;
|
||||||
|
});
|
||||||
|
mPollWakeRequested = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void ControlServices::WakePolling()
|
||||||
|
{
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mPollWakeMutex);
|
||||||
|
mPollWakeRequested = true;
|
||||||
|
}
|
||||||
|
mPollWakeCondition.notify_one();
|
||||||
|
}
|
||||||
|
|
||||||
|
void ControlServices::PublishRuntimeStateBroadcastRequested(const std::string& reason)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
RuntimeStateBroadcastRequestedEvent event;
|
||||||
|
event.reason = reason;
|
||||||
|
if (!mRuntimeEventDispatcher.PublishPayload(event, "ControlServices"))
|
||||||
|
OutputDebugStringA("RuntimeStateBroadcastRequested event publish failed.\n");
|
||||||
|
}
|
||||||
|
catch (...)
|
||||||
|
{
|
||||||
|
OutputDebugStringA("RuntimeStateBroadcastRequested event publish threw.\n");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void ControlServices::PublishOscValueReceived(const PendingOscUpdate& update, const std::string& routeKey)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
OscValueReceivedEvent event;
|
||||||
|
event.routeKey = routeKey;
|
||||||
|
event.layerKey = update.layerKey;
|
||||||
|
event.parameterKey = update.parameterKey;
|
||||||
|
event.valueJson = update.valueJson;
|
||||||
|
if (!mRuntimeEventDispatcher.PublishPayload(event, "ControlServices"))
|
||||||
|
OutputDebugStringA("OscValueReceived event publish failed.\n");
|
||||||
|
}
|
||||||
|
catch (...)
|
||||||
|
{
|
||||||
|
OutputDebugStringA("OscValueReceived event publish threw.\n");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void ControlServices::PublishOscCommitRequested(const PendingOscCommit& commit)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
OscCommitRequestedEvent event;
|
||||||
|
event.routeKey = commit.routeKey;
|
||||||
|
event.layerKey = commit.layerKey;
|
||||||
|
event.parameterKey = commit.parameterKey;
|
||||||
|
event.valueJson = SerializeJson(commit.value, false);
|
||||||
|
event.generation = commit.generation;
|
||||||
|
if (!mRuntimeEventDispatcher.PublishPayload(event, "ControlServices"))
|
||||||
|
OutputDebugStringA("OscCommitRequested event publish failed.\n");
|
||||||
|
}
|
||||||
|
catch (...)
|
||||||
|
{
|
||||||
|
OutputDebugStringA("OscCommitRequested event publish threw.\n");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void ControlServices::PublishOscOverlaySettled(const PendingOscCommit& commit)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
OscOverlayEvent event;
|
||||||
|
event.routeKey = commit.routeKey;
|
||||||
|
event.layerKey = commit.layerKey;
|
||||||
|
event.parameterKey = commit.parameterKey;
|
||||||
|
event.generation = commit.generation;
|
||||||
|
event.settled = true;
|
||||||
|
if (!mRuntimeEventDispatcher.PublishPayload(event, "ControlServices"))
|
||||||
|
OutputDebugStringA("OscOverlaySettled event publish failed.\n");
|
||||||
|
}
|
||||||
|
catch (...)
|
||||||
|
{
|
||||||
|
OutputDebugStringA("OscOverlaySettled event publish threw.\n");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "RuntimeJson.h"
|
||||||
|
#include "RuntimeCoordinator.h"
|
||||||
|
#include "ShaderTypes.h"
|
||||||
|
|
||||||
|
#include <atomic>
|
||||||
|
#include <condition_variable>
|
||||||
|
#include <chrono>
|
||||||
|
#include <map>
|
||||||
|
#include <memory>
|
||||||
|
#include <mutex>
|
||||||
|
#include <string>
|
||||||
|
#include <thread>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
class ControlServer;
|
||||||
|
class OpenGLComposite;
|
||||||
|
class OscServer;
|
||||||
|
class RuntimeEventDispatcher;
|
||||||
|
class RuntimeStore;
|
||||||
|
|
||||||
|
class ControlServices
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
struct AppliedOscUpdate
|
||||||
|
{
|
||||||
|
std::string routeKey;
|
||||||
|
std::string layerKey;
|
||||||
|
std::string parameterKey;
|
||||||
|
JsonValue targetValue;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct CompletedOscCommit
|
||||||
|
{
|
||||||
|
std::string routeKey;
|
||||||
|
uint64_t generation = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
explicit ControlServices(RuntimeEventDispatcher& runtimeEventDispatcher);
|
||||||
|
~ControlServices();
|
||||||
|
|
||||||
|
bool Start(OpenGLComposite& composite, RuntimeStore& runtimeStore, std::string& error);
|
||||||
|
void BeginPolling(RuntimeCoordinator& runtimeCoordinator);
|
||||||
|
void Stop();
|
||||||
|
void BroadcastState();
|
||||||
|
void RequestBroadcastState();
|
||||||
|
bool QueueOscUpdate(const std::string& layerKey, const std::string& parameterKey, const std::string& valueJson, std::string& error);
|
||||||
|
bool ApplyPendingOscUpdates(std::vector<AppliedOscUpdate>& appliedUpdates, std::string& error);
|
||||||
|
bool QueueOscCommit(const std::string& routeKey, const std::string& layerKey, const std::string& parameterKey, const JsonValue& value, uint64_t generation, std::string& error);
|
||||||
|
void ClearOscState();
|
||||||
|
void ClearOscStateForLayerKey(const std::string& layerKey);
|
||||||
|
void ConsumeCompletedOscCommits(std::vector<CompletedOscCommit>& completedCommits);
|
||||||
|
|
||||||
|
private:
|
||||||
|
struct PendingOscUpdate
|
||||||
|
{
|
||||||
|
std::string layerKey;
|
||||||
|
std::string parameterKey;
|
||||||
|
std::string valueJson;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct PendingOscCommit
|
||||||
|
{
|
||||||
|
std::string routeKey;
|
||||||
|
std::string layerKey;
|
||||||
|
std::string parameterKey;
|
||||||
|
JsonValue value;
|
||||||
|
uint64_t generation = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
void StartPolling(RuntimeCoordinator& runtimeCoordinator);
|
||||||
|
void StopPolling();
|
||||||
|
void PollLoop(RuntimeCoordinator& runtimeCoordinator);
|
||||||
|
void WakePolling();
|
||||||
|
void PublishRuntimeStateBroadcastRequested(const std::string& reason);
|
||||||
|
void PublishOscValueReceived(const PendingOscUpdate& update, const std::string& routeKey);
|
||||||
|
void PublishOscCommitRequested(const PendingOscCommit& commit);
|
||||||
|
void PublishOscOverlaySettled(const PendingOscCommit& commit);
|
||||||
|
|
||||||
|
std::unique_ptr<ControlServer> mControlServer;
|
||||||
|
std::unique_ptr<OscServer> mOscServer;
|
||||||
|
RuntimeEventDispatcher& mRuntimeEventDispatcher;
|
||||||
|
std::thread mPollThread;
|
||||||
|
std::atomic<bool> mPollRunning;
|
||||||
|
std::mutex mPollWakeMutex;
|
||||||
|
std::condition_variable mPollWakeCondition;
|
||||||
|
bool mPollWakeRequested = false;
|
||||||
|
std::mutex mPendingOscMutex;
|
||||||
|
std::map<std::string, PendingOscUpdate> mPendingOscUpdates;
|
||||||
|
std::mutex mPendingOscCommitMutex;
|
||||||
|
std::map<std::string, PendingOscCommit> mPendingOscCommits;
|
||||||
|
std::mutex mCompletedOscCommitMutex;
|
||||||
|
std::vector<CompletedOscCommit> mCompletedOscCommits;
|
||||||
|
};
|
||||||
@@ -55,7 +55,7 @@ OscServer::~OscServer()
|
|||||||
Stop();
|
Stop();
|
||||||
}
|
}
|
||||||
|
|
||||||
bool OscServer::Start(unsigned short port, const Callbacks& callbacks, std::string& error)
|
bool OscServer::Start(const std::string& bindAddress, unsigned short port, const Callbacks& callbacks, std::string& error)
|
||||||
{
|
{
|
||||||
if (port == 0)
|
if (port == 0)
|
||||||
return true;
|
return true;
|
||||||
@@ -78,11 +78,15 @@ bool OscServer::Start(unsigned short port, const Callbacks& callbacks, std::stri
|
|||||||
|
|
||||||
sockaddr_in address = {};
|
sockaddr_in address = {};
|
||||||
address.sin_family = AF_INET;
|
address.sin_family = AF_INET;
|
||||||
address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
|
if (!TryParseBindAddress(bindAddress, address.sin_addr, error))
|
||||||
|
{
|
||||||
|
mSocket.reset();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
address.sin_port = htons(static_cast<u_short>(port));
|
address.sin_port = htons(static_cast<u_short>(port));
|
||||||
if (bind(mSocket.get(), reinterpret_cast<sockaddr*>(&address), sizeof(address)) != 0)
|
if (bind(mSocket.get(), reinterpret_cast<sockaddr*>(&address), sizeof(address)) != 0)
|
||||||
{
|
{
|
||||||
error = "Could not bind OSC listener to UDP port " + std::to_string(port) + ".";
|
error = "Could not bind OSC listener to " + bindAddress + ":" + std::to_string(port) + ".";
|
||||||
mSocket.reset();
|
mSocket.reset();
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -92,6 +96,24 @@ bool OscServer::Start(unsigned short port, const Callbacks& callbacks, std::stri
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
bool OscServer::TryParseBindAddress(const std::string& bindAddress, in_addr& address, std::string& error)
|
||||||
|
{
|
||||||
|
if (bindAddress.empty())
|
||||||
|
{
|
||||||
|
error = "OSC bind address must not be empty.";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
address = {};
|
||||||
|
if (InetPtonA(AF_INET, bindAddress.c_str(), &address) != 1)
|
||||||
|
{
|
||||||
|
error = "Invalid OSC bind address '" + bindAddress + "'. Use an IPv4 address such as 127.0.0.1 or 0.0.0.0.";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
void OscServer::Stop()
|
void OscServer::Stop()
|
||||||
{
|
{
|
||||||
mRunning = false;
|
mRunning = false;
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ public:
|
|||||||
OscServer();
|
OscServer();
|
||||||
~OscServer();
|
~OscServer();
|
||||||
|
|
||||||
bool Start(unsigned short port, const Callbacks& callbacks, std::string& error);
|
bool Start(const std::string& bindAddress, unsigned short port, const Callbacks& callbacks, std::string& error);
|
||||||
void Stop();
|
void Stop();
|
||||||
|
|
||||||
unsigned short GetPort() const { return mPort; }
|
unsigned short GetPort() const { return mPort; }
|
||||||
@@ -37,6 +37,7 @@ private:
|
|||||||
void ServerLoop();
|
void ServerLoop();
|
||||||
bool DecodeMessage(const char* data, int byteCount, OscMessage& message, std::string& error) const;
|
bool DecodeMessage(const char* data, int byteCount, OscMessage& message, std::string& error) const;
|
||||||
bool DispatchMessage(const OscMessage& message, std::string& error) const;
|
bool DispatchMessage(const OscMessage& message, std::string& error) const;
|
||||||
|
static bool TryParseBindAddress(const std::string& bindAddress, in_addr& address, std::string& error);
|
||||||
static bool DecodeArgument(const char* data, int byteCount, int& offset, char valueType, std::string& valueJson);
|
static bool DecodeArgument(const char* data, int byteCount, int& offset, char valueType, std::string& valueJson);
|
||||||
static bool ReadPaddedString(const char* data, int byteCount, int& offset, std::string& value);
|
static bool ReadPaddedString(const char* data, int byteCount, int& offset, std::string& value);
|
||||||
static bool ReadInt32(const char* data, int byteCount, int& offset, int& value);
|
static bool ReadInt32(const char* data, int byteCount, int& offset, int& value);
|
||||||
|
|||||||
@@ -1,13 +1,15 @@
|
|||||||
#include "RuntimeControlBridge.h"
|
#include "RuntimeControlBridge.h"
|
||||||
|
|
||||||
|
#include "ControlServices.h"
|
||||||
#include "ControlServer.h"
|
#include "ControlServer.h"
|
||||||
#include "OpenGLComposite.h"
|
#include "OpenGLComposite.h"
|
||||||
#include "OscServer.h"
|
#include "OscServer.h"
|
||||||
#include "RuntimeHost.h"
|
#include "RuntimeStore.h"
|
||||||
|
|
||||||
bool StartRuntimeControlServices(
|
bool StartControlServicesBoundary(
|
||||||
OpenGLComposite& composite,
|
OpenGLComposite& composite,
|
||||||
RuntimeHost& runtimeHost,
|
RuntimeStore& runtimeStore,
|
||||||
|
ControlServices& controlServices,
|
||||||
ControlServer& controlServer,
|
ControlServer& controlServer,
|
||||||
OscServer& oscServer,
|
OscServer& oscServer,
|
||||||
std::string& error)
|
std::string& error)
|
||||||
@@ -36,15 +38,16 @@ bool StartRuntimeControlServices(
|
|||||||
return true;
|
return true;
|
||||||
};
|
};
|
||||||
|
|
||||||
if (!controlServer.Start(runtimeHost.GetUiRoot(), runtimeHost.GetDocsRoot(), runtimeHost.GetServerPort(), callbacks, error))
|
if (!controlServer.Start(runtimeStore.GetRuntimeUiRoot(), runtimeStore.GetRuntimeDocsRoot(), runtimeStore.GetConfiguredControlServerPort(), callbacks, error))
|
||||||
return false;
|
return false;
|
||||||
runtimeHost.SetServerPort(controlServer.GetPort());
|
runtimeStore.SetBoundControlServerPort(controlServer.GetPort());
|
||||||
|
|
||||||
OscServer::Callbacks oscCallbacks;
|
OscServer::Callbacks oscCallbacks;
|
||||||
oscCallbacks.updateParameter = [&composite](const std::string& layerKey, const std::string& parameterKey, const std::string& valueJson, std::string& actionError) {
|
oscCallbacks.updateParameter = [&controlServices](const std::string& layerKey, const std::string& parameterKey, const std::string& valueJson, std::string& actionError) {
|
||||||
return composite.UpdateLayerParameterByControlKeyJson(layerKey, parameterKey, valueJson, actionError);
|
return controlServices.QueueOscUpdate(layerKey, parameterKey, valueJson, actionError);
|
||||||
};
|
};
|
||||||
if (runtimeHost.GetOscPort() > 0 && !oscServer.Start(runtimeHost.GetOscPort(), oscCallbacks, error))
|
if (runtimeStore.GetConfiguredOscPort() > 0 &&
|
||||||
|
!oscServer.Start(runtimeStore.GetConfiguredOscBindAddress(), runtimeStore.GetConfiguredOscPort(), oscCallbacks, error))
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
|
|||||||
@@ -3,13 +3,15 @@
|
|||||||
#include <string>
|
#include <string>
|
||||||
|
|
||||||
class ControlServer;
|
class ControlServer;
|
||||||
|
class ControlServices;
|
||||||
class OpenGLComposite;
|
class OpenGLComposite;
|
||||||
class OscServer;
|
class OscServer;
|
||||||
class RuntimeHost;
|
class RuntimeStore;
|
||||||
|
|
||||||
bool StartRuntimeControlServices(
|
bool StartControlServicesBoundary(
|
||||||
OpenGLComposite& composite,
|
OpenGLComposite& composite,
|
||||||
RuntimeHost& runtimeHost,
|
RuntimeStore& runtimeStore,
|
||||||
|
ControlServices& controlServices,
|
||||||
ControlServer& controlServer,
|
ControlServer& controlServer,
|
||||||
OscServer& oscServer,
|
OscServer& oscServer,
|
||||||
std::string& error);
|
std::string& error);
|
||||||
|
|||||||
@@ -0,0 +1,72 @@
|
|||||||
|
#include "RuntimeServiceLiveBridge.h"
|
||||||
|
|
||||||
|
#include "RenderEngine.h"
|
||||||
|
#include "RuntimeServices.h"
|
||||||
|
|
||||||
|
#include <windows.h>
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
void DrainServiceEvents(RuntimeServices& runtimeServices, RenderEngine& renderEngine)
|
||||||
|
{
|
||||||
|
std::vector<RuntimeServices::AppliedOscUpdate> appliedOscUpdates;
|
||||||
|
std::vector<RuntimeServices::CompletedOscCommit> completedOscCommits;
|
||||||
|
|
||||||
|
std::string oscError;
|
||||||
|
if (!runtimeServices.ApplyPendingOscUpdates(appliedOscUpdates, oscError) && !oscError.empty())
|
||||||
|
OutputDebugStringA(("OSC apply failed: " + oscError + "\n").c_str());
|
||||||
|
runtimeServices.ConsumeCompletedOscCommits(completedOscCommits);
|
||||||
|
|
||||||
|
std::vector<RenderEngine::OscOverlayUpdate> overlayUpdates;
|
||||||
|
overlayUpdates.reserve(appliedOscUpdates.size());
|
||||||
|
for (const RuntimeServices::AppliedOscUpdate& update : appliedOscUpdates)
|
||||||
|
{
|
||||||
|
overlayUpdates.push_back({ update.routeKey, update.layerKey, update.parameterKey, update.targetValue });
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<RenderEngine::OscOverlayCommitCompletion> overlayCommitCompletions;
|
||||||
|
overlayCommitCompletions.reserve(completedOscCommits.size());
|
||||||
|
for (const RuntimeServices::CompletedOscCommit& completedCommit : completedOscCommits)
|
||||||
|
{
|
||||||
|
overlayCommitCompletions.push_back({ completedCommit.routeKey, completedCommit.generation });
|
||||||
|
}
|
||||||
|
|
||||||
|
renderEngine.UpdateOscOverlayState(overlayUpdates, overlayCommitCompletions);
|
||||||
|
}
|
||||||
|
|
||||||
|
void QueueServiceCommitRequests(
|
||||||
|
RuntimeServices& runtimeServices,
|
||||||
|
const std::vector<RenderEngine::OscOverlayCommitRequest>& commitRequests)
|
||||||
|
{
|
||||||
|
for (const RenderEngine::OscOverlayCommitRequest& commitRequest : commitRequests)
|
||||||
|
{
|
||||||
|
std::string commitError;
|
||||||
|
if (!runtimeServices.QueueOscCommit(
|
||||||
|
commitRequest.routeKey,
|
||||||
|
commitRequest.layerKey,
|
||||||
|
commitRequest.parameterKey,
|
||||||
|
commitRequest.value,
|
||||||
|
commitRequest.generation,
|
||||||
|
commitError) &&
|
||||||
|
!commitError.empty())
|
||||||
|
{
|
||||||
|
OutputDebugStringA(("OSC commit queue failed: " + commitError + "\n").c_str());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool RuntimeServiceLiveBridge::PrepareLiveRenderFrameState(
|
||||||
|
RuntimeServices& runtimeServices,
|
||||||
|
RenderEngine& renderEngine,
|
||||||
|
const RenderFrameInput& input,
|
||||||
|
RenderFrameState& frameState)
|
||||||
|
{
|
||||||
|
DrainServiceEvents(runtimeServices, renderEngine);
|
||||||
|
|
||||||
|
std::vector<RenderEngine::OscOverlayCommitRequest> commitRequests;
|
||||||
|
const bool resolved = renderEngine.ResolveRenderFrameState(input, &commitRequests, frameState);
|
||||||
|
|
||||||
|
QueueServiceCommitRequests(runtimeServices, commitRequests);
|
||||||
|
return resolved;
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "RenderFrameState.h"
|
||||||
|
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
class RenderEngine;
|
||||||
|
class RuntimeServices;
|
||||||
|
|
||||||
|
class RuntimeServiceLiveBridge
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
static bool PrepareLiveRenderFrameState(
|
||||||
|
RuntimeServices& runtimeServices,
|
||||||
|
RenderEngine& renderEngine,
|
||||||
|
const RenderFrameInput& input,
|
||||||
|
RenderFrameState& frameState);
|
||||||
|
};
|
||||||
@@ -1,19 +1,9 @@
|
|||||||
#include "RuntimeServices.h"
|
#include "RuntimeServices.h"
|
||||||
|
|
||||||
#include "ControlServer.h"
|
#include "RuntimeStore.h"
|
||||||
#include "OscServer.h"
|
|
||||||
#include "RuntimeControlBridge.h"
|
|
||||||
#include "RuntimeHost.h"
|
|
||||||
|
|
||||||
#include <windows.h>
|
RuntimeServices::RuntimeServices(RuntimeEventDispatcher& runtimeEventDispatcher) :
|
||||||
|
mControlServices(std::make_unique<ControlServices>(runtimeEventDispatcher))
|
||||||
RuntimeServices::RuntimeServices() :
|
|
||||||
mControlServer(std::make_unique<ControlServer>()),
|
|
||||||
mOscServer(std::make_unique<OscServer>()),
|
|
||||||
mPollRunning(false),
|
|
||||||
mRegistryChanged(false),
|
|
||||||
mReloadRequested(false),
|
|
||||||
mPollFailed(false)
|
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -22,98 +12,75 @@ RuntimeServices::~RuntimeServices()
|
|||||||
Stop();
|
Stop();
|
||||||
}
|
}
|
||||||
|
|
||||||
bool RuntimeServices::Start(OpenGLComposite& composite, RuntimeHost& runtimeHost, std::string& error)
|
bool RuntimeServices::Start(OpenGLComposite& composite, RuntimeStore& runtimeStore, std::string& error)
|
||||||
{
|
{
|
||||||
Stop();
|
return mControlServices && mControlServices->Start(composite, runtimeStore, error);
|
||||||
|
|
||||||
if (!StartRuntimeControlServices(composite, runtimeHost, *mControlServer, *mOscServer, error))
|
|
||||||
{
|
|
||||||
Stop();
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void RuntimeServices::BeginPolling(RuntimeHost& runtimeHost)
|
void RuntimeServices::BeginPolling(RuntimeCoordinator& runtimeCoordinator)
|
||||||
{
|
{
|
||||||
StartPolling(runtimeHost);
|
if (mControlServices)
|
||||||
|
mControlServices->BeginPolling(runtimeCoordinator);
|
||||||
}
|
}
|
||||||
|
|
||||||
void RuntimeServices::Stop()
|
void RuntimeServices::Stop()
|
||||||
{
|
{
|
||||||
StopPolling();
|
if (mControlServices)
|
||||||
|
mControlServices->Stop();
|
||||||
if (mOscServer)
|
|
||||||
mOscServer->Stop();
|
|
||||||
|
|
||||||
if (mControlServer)
|
|
||||||
mControlServer->Stop();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void RuntimeServices::BroadcastState()
|
void RuntimeServices::BroadcastState()
|
||||||
{
|
{
|
||||||
if (mControlServer)
|
if (mControlServices)
|
||||||
mControlServer->BroadcastState();
|
mControlServices->BroadcastState();
|
||||||
}
|
}
|
||||||
|
|
||||||
RuntimePollEvents RuntimeServices::ConsumePollEvents()
|
void RuntimeServices::RequestBroadcastState()
|
||||||
{
|
{
|
||||||
RuntimePollEvents events;
|
if (mControlServices)
|
||||||
events.registryChanged = mRegistryChanged.exchange(false);
|
mControlServices->RequestBroadcastState();
|
||||||
events.reloadRequested = mReloadRequested.exchange(false);
|
}
|
||||||
events.failed = mPollFailed.exchange(false);
|
|
||||||
|
|
||||||
if (events.failed)
|
bool RuntimeServices::QueueOscUpdate(const std::string& layerKey, const std::string& parameterKey, const std::string& valueJson, std::string& error)
|
||||||
|
{
|
||||||
|
return mControlServices && mControlServices->QueueOscUpdate(layerKey, parameterKey, valueJson, error);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool RuntimeServices::ApplyPendingOscUpdates(std::vector<AppliedOscUpdate>& appliedUpdates, std::string& error)
|
||||||
|
{
|
||||||
|
if (!mControlServices)
|
||||||
{
|
{
|
||||||
std::lock_guard<std::mutex> lock(mPollErrorMutex);
|
appliedUpdates.clear();
|
||||||
events.error = mPollError;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
return events;
|
return mControlServices->ApplyPendingOscUpdates(appliedUpdates, error);
|
||||||
}
|
}
|
||||||
|
|
||||||
void RuntimeServices::StartPolling(RuntimeHost& runtimeHost)
|
bool RuntimeServices::QueueOscCommit(const std::string& routeKey, const std::string& layerKey, const std::string& parameterKey, const JsonValue& value, uint64_t generation, std::string& error)
|
||||||
{
|
{
|
||||||
if (mPollRunning.exchange(true))
|
return mControlServices && mControlServices->QueueOscCommit(routeKey, layerKey, parameterKey, value, generation, error);
|
||||||
return;
|
|
||||||
|
|
||||||
mPollThread = std::thread([this, &runtimeHost]() { PollLoop(runtimeHost); });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void RuntimeServices::StopPolling()
|
void RuntimeServices::ClearOscState()
|
||||||
{
|
{
|
||||||
if (!mPollRunning.exchange(false))
|
if (mControlServices)
|
||||||
return;
|
mControlServices->ClearOscState();
|
||||||
|
|
||||||
if (mPollThread.joinable())
|
|
||||||
mPollThread.join();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void RuntimeServices::PollLoop(RuntimeHost& runtimeHost)
|
void RuntimeServices::ClearOscStateForLayerKey(const std::string& layerKey)
|
||||||
{
|
{
|
||||||
while (mPollRunning)
|
if (mControlServices)
|
||||||
|
mControlServices->ClearOscStateForLayerKey(layerKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
void RuntimeServices::ConsumeCompletedOscCommits(std::vector<CompletedOscCommit>& completedCommits)
|
||||||
|
{
|
||||||
|
if (!mControlServices)
|
||||||
{
|
{
|
||||||
bool registryChanged = false;
|
completedCommits.clear();
|
||||||
bool reloadRequested = false;
|
return;
|
||||||
std::string runtimeError;
|
|
||||||
if (!runtimeHost.PollFileChanges(registryChanged, reloadRequested, runtimeError))
|
|
||||||
{
|
|
||||||
{
|
|
||||||
std::lock_guard<std::mutex> lock(mPollErrorMutex);
|
|
||||||
mPollError = runtimeError;
|
|
||||||
}
|
|
||||||
mPollFailed = true;
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
if (registryChanged)
|
|
||||||
mRegistryChanged = true;
|
|
||||||
if (reloadRequested)
|
|
||||||
mReloadRequested = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (int i = 0; i < 25 && mPollRunning; ++i)
|
|
||||||
Sleep(10);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
mControlServices->ConsumeCompletedOscCommits(completedCommits);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,48 +1,35 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <atomic>
|
#include "ControlServices.h"
|
||||||
|
|
||||||
#include <memory>
|
#include <memory>
|
||||||
#include <mutex>
|
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <thread>
|
|
||||||
|
|
||||||
class ControlServer;
|
|
||||||
class OpenGLComposite;
|
class OpenGLComposite;
|
||||||
class OscServer;
|
class RuntimeCoordinator;
|
||||||
class RuntimeHost;
|
class RuntimeEventDispatcher;
|
||||||
|
class RuntimeStore;
|
||||||
struct RuntimePollEvents
|
|
||||||
{
|
|
||||||
bool registryChanged = false;
|
|
||||||
bool reloadRequested = false;
|
|
||||||
bool failed = false;
|
|
||||||
std::string error;
|
|
||||||
};
|
|
||||||
|
|
||||||
class RuntimeServices
|
class RuntimeServices
|
||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
RuntimeServices();
|
using AppliedOscUpdate = ControlServices::AppliedOscUpdate;
|
||||||
|
using CompletedOscCommit = ControlServices::CompletedOscCommit;
|
||||||
|
|
||||||
|
explicit RuntimeServices(RuntimeEventDispatcher& runtimeEventDispatcher);
|
||||||
~RuntimeServices();
|
~RuntimeServices();
|
||||||
|
|
||||||
bool Start(OpenGLComposite& composite, RuntimeHost& runtimeHost, std::string& error);
|
bool Start(OpenGLComposite& composite, RuntimeStore& runtimeStore, std::string& error);
|
||||||
void BeginPolling(RuntimeHost& runtimeHost);
|
void BeginPolling(RuntimeCoordinator& runtimeCoordinator);
|
||||||
void Stop();
|
void Stop();
|
||||||
void BroadcastState();
|
void BroadcastState();
|
||||||
RuntimePollEvents ConsumePollEvents();
|
void RequestBroadcastState();
|
||||||
|
bool QueueOscUpdate(const std::string& layerKey, const std::string& parameterKey, const std::string& valueJson, std::string& error);
|
||||||
|
bool ApplyPendingOscUpdates(std::vector<AppliedOscUpdate>& appliedUpdates, std::string& error);
|
||||||
|
bool QueueOscCommit(const std::string& routeKey, const std::string& layerKey, const std::string& parameterKey, const JsonValue& value, uint64_t generation, std::string& error);
|
||||||
|
void ClearOscState();
|
||||||
|
void ClearOscStateForLayerKey(const std::string& layerKey);
|
||||||
|
void ConsumeCompletedOscCommits(std::vector<CompletedOscCommit>& completedCommits);
|
||||||
|
|
||||||
private:
|
private:
|
||||||
void StartPolling(RuntimeHost& runtimeHost);
|
std::unique_ptr<ControlServices> mControlServices;
|
||||||
void StopPolling();
|
|
||||||
void PollLoop(RuntimeHost& runtimeHost);
|
|
||||||
|
|
||||||
std::unique_ptr<ControlServer> mControlServer;
|
|
||||||
std::unique_ptr<OscServer> mOscServer;
|
|
||||||
std::thread mPollThread;
|
|
||||||
std::atomic<bool> mPollRunning;
|
|
||||||
std::atomic<bool> mRegistryChanged;
|
|
||||||
std::atomic<bool> mReloadRequested;
|
|
||||||
std::atomic<bool> mPollFailed;
|
|
||||||
std::mutex mPollErrorMutex;
|
|
||||||
std::string mPollError;
|
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,518 +0,0 @@
|
|||||||
#include "DeckLinkSession.h"
|
|
||||||
|
|
||||||
#include "GlRenderConstants.h"
|
|
||||||
|
|
||||||
#include <atlbase.h>
|
|
||||||
#include <cstdio>
|
|
||||||
#include <cstring>
|
|
||||||
#include <new>
|
|
||||||
#include <sstream>
|
|
||||||
#include <vector>
|
|
||||||
|
|
||||||
namespace
|
|
||||||
{
|
|
||||||
std::string BstrToUtf8(BSTR value)
|
|
||||||
{
|
|
||||||
if (value == nullptr)
|
|
||||||
return std::string();
|
|
||||||
|
|
||||||
const int requiredBytes = WideCharToMultiByte(CP_UTF8, 0, value, -1, NULL, 0, NULL, NULL);
|
|
||||||
if (requiredBytes <= 1)
|
|
||||||
return std::string();
|
|
||||||
|
|
||||||
std::vector<char> utf8Name(static_cast<std::size_t>(requiredBytes), '\0');
|
|
||||||
if (WideCharToMultiByte(CP_UTF8, 0, value, -1, utf8Name.data(), requiredBytes, NULL, NULL) <= 0)
|
|
||||||
return std::string();
|
|
||||||
|
|
||||||
return std::string(utf8Name.data());
|
|
||||||
}
|
|
||||||
|
|
||||||
bool InputSupportsFormat(IDeckLinkInput* input, BMDDisplayMode displayMode, BMDPixelFormat pixelFormat)
|
|
||||||
{
|
|
||||||
if (input == nullptr)
|
|
||||||
return false;
|
|
||||||
|
|
||||||
BOOL supported = FALSE;
|
|
||||||
BMDDisplayMode actualMode = bmdModeUnknown;
|
|
||||||
const HRESULT result = input->DoesSupportVideoMode(
|
|
||||||
bmdVideoConnectionUnspecified,
|
|
||||||
displayMode,
|
|
||||||
pixelFormat,
|
|
||||||
bmdNoVideoInputConversion,
|
|
||||||
bmdSupportedVideoModeDefault,
|
|
||||||
&actualMode,
|
|
||||||
&supported);
|
|
||||||
return result == S_OK && supported != FALSE;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool OutputSupportsFormat(IDeckLinkOutput* output, BMDDisplayMode displayMode, BMDPixelFormat pixelFormat)
|
|
||||||
{
|
|
||||||
if (output == nullptr)
|
|
||||||
return false;
|
|
||||||
|
|
||||||
BOOL supported = FALSE;
|
|
||||||
BMDDisplayMode actualMode = bmdModeUnknown;
|
|
||||||
const HRESULT result = output->DoesSupportVideoMode(
|
|
||||||
bmdVideoConnectionUnspecified,
|
|
||||||
displayMode,
|
|
||||||
pixelFormat,
|
|
||||||
bmdNoVideoOutputConversion,
|
|
||||||
bmdSupportedVideoModeDefault,
|
|
||||||
&actualMode,
|
|
||||||
&supported);
|
|
||||||
return result == S_OK && supported != FALSE;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
DeckLinkSession::~DeckLinkSession()
|
|
||||||
{
|
|
||||||
ReleaseResources();
|
|
||||||
}
|
|
||||||
|
|
||||||
void DeckLinkSession::ReleaseResources()
|
|
||||||
{
|
|
||||||
if (input != nullptr)
|
|
||||||
input->SetCallback(nullptr);
|
|
||||||
captureDelegate.Release();
|
|
||||||
input.Release();
|
|
||||||
|
|
||||||
if (output != nullptr)
|
|
||||||
output->SetScheduledFrameCompletionCallback(nullptr);
|
|
||||||
|
|
||||||
if (keyer != nullptr)
|
|
||||||
{
|
|
||||||
keyer->Disable();
|
|
||||||
externalKeyingActive = false;
|
|
||||||
}
|
|
||||||
keyer.Release();
|
|
||||||
|
|
||||||
playoutDelegate.Release();
|
|
||||||
outputVideoFrameQueue.clear();
|
|
||||||
output.Release();
|
|
||||||
}
|
|
||||||
|
|
||||||
bool DeckLinkSession::DiscoverDevicesAndModes(const VideoFormatSelection& videoModes, std::string& error)
|
|
||||||
{
|
|
||||||
CComPtr<IDeckLinkIterator> deckLinkIterator;
|
|
||||||
CComPtr<IDeckLinkDisplayMode> inputMode;
|
|
||||||
CComPtr<IDeckLinkDisplayMode> outputMode;
|
|
||||||
|
|
||||||
inputDisplayModeName = videoModes.input.displayName;
|
|
||||||
outputDisplayModeName = videoModes.output.displayName;
|
|
||||||
|
|
||||||
HRESULT result = CoCreateInstance(CLSID_CDeckLinkIterator, nullptr, CLSCTX_ALL, IID_IDeckLinkIterator, reinterpret_cast<void**>(&deckLinkIterator));
|
|
||||||
if (FAILED(result))
|
|
||||||
{
|
|
||||||
error = "Please install the Blackmagic DeckLink drivers to use the features of this application.";
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
CComPtr<IDeckLink> deckLink;
|
|
||||||
while (deckLinkIterator->Next(&deckLink) == S_OK)
|
|
||||||
{
|
|
||||||
int64_t duplexMode;
|
|
||||||
bool deviceSupportsInternalKeying = false;
|
|
||||||
bool deviceSupportsExternalKeying = false;
|
|
||||||
std::string modelName;
|
|
||||||
CComPtr<IDeckLinkProfileAttributes> deckLinkAttributes;
|
|
||||||
|
|
||||||
if (deckLink->QueryInterface(IID_IDeckLinkProfileAttributes, (void**)&deckLinkAttributes) != S_OK)
|
|
||||||
{
|
|
||||||
printf("Could not obtain the IDeckLinkProfileAttributes interface\n");
|
|
||||||
deckLink.Release();
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
result = deckLinkAttributes->GetInt(BMDDeckLinkDuplex, &duplexMode);
|
|
||||||
BOOL attributeFlag = FALSE;
|
|
||||||
if (deckLinkAttributes->GetFlag(BMDDeckLinkSupportsInternalKeying, &attributeFlag) == S_OK)
|
|
||||||
deviceSupportsInternalKeying = (attributeFlag != FALSE);
|
|
||||||
attributeFlag = FALSE;
|
|
||||||
if (deckLinkAttributes->GetFlag(BMDDeckLinkSupportsExternalKeying, &attributeFlag) == S_OK)
|
|
||||||
deviceSupportsExternalKeying = (attributeFlag != FALSE);
|
|
||||||
CComBSTR modelNameBstr;
|
|
||||||
if (deckLinkAttributes->GetString(BMDDeckLinkModelName, &modelNameBstr) == S_OK)
|
|
||||||
modelName = BstrToUtf8(modelNameBstr);
|
|
||||||
|
|
||||||
if (result != S_OK || duplexMode == bmdDuplexInactive)
|
|
||||||
{
|
|
||||||
deckLink.Release();
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool inputUsed = false;
|
|
||||||
if (!input && deckLink->QueryInterface(IID_IDeckLinkInput, (void**)&input) == S_OK)
|
|
||||||
inputUsed = true;
|
|
||||||
|
|
||||||
if (!output && (!inputUsed || (duplexMode == bmdDuplexFull)))
|
|
||||||
{
|
|
||||||
if (deckLink->QueryInterface(IID_IDeckLinkOutput, (void**)&output) != S_OK)
|
|
||||||
output.Release();
|
|
||||||
else
|
|
||||||
{
|
|
||||||
outputModelName = modelName;
|
|
||||||
supportsInternalKeying = deviceSupportsInternalKeying;
|
|
||||||
supportsExternalKeying = deviceSupportsExternalKeying;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
deckLink.Release();
|
|
||||||
|
|
||||||
if (output && input)
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!output)
|
|
||||||
{
|
|
||||||
error = "Expected an Output DeckLink device";
|
|
||||||
ReleaseResources();
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
CComPtr<IDeckLinkDisplayModeIterator> inputDisplayModeIterator;
|
|
||||||
if (input && input->GetDisplayModeIterator(&inputDisplayModeIterator) != S_OK)
|
|
||||||
{
|
|
||||||
error = "Cannot get input Display Mode Iterator.";
|
|
||||||
ReleaseResources();
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (input && !FindDeckLinkDisplayMode(inputDisplayModeIterator, videoModes.input.displayMode, &inputMode))
|
|
||||||
{
|
|
||||||
error = "Cannot get specified input BMDDisplayMode for configured mode: " + videoModes.input.displayName;
|
|
||||||
ReleaseResources();
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
inputDisplayModeIterator.Release();
|
|
||||||
|
|
||||||
CComPtr<IDeckLinkDisplayModeIterator> outputDisplayModeIterator;
|
|
||||||
if (output->GetDisplayModeIterator(&outputDisplayModeIterator) != S_OK)
|
|
||||||
{
|
|
||||||
error = "Cannot get output Display Mode Iterator.";
|
|
||||||
ReleaseResources();
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!FindDeckLinkDisplayMode(outputDisplayModeIterator, videoModes.output.displayMode, &outputMode))
|
|
||||||
{
|
|
||||||
error = "Cannot get specified output BMDDisplayMode for configured mode: " + videoModes.output.displayName;
|
|
||||||
ReleaseResources();
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
outputFrameSize = { static_cast<unsigned>(outputMode->GetWidth()), static_cast<unsigned>(outputMode->GetHeight()) };
|
|
||||||
inputFrameSize = inputMode
|
|
||||||
? FrameSize{ static_cast<unsigned>(inputMode->GetWidth()), static_cast<unsigned>(inputMode->GetHeight()) }
|
|
||||||
: outputFrameSize;
|
|
||||||
if (!input)
|
|
||||||
inputDisplayModeName = "No input - black frame";
|
|
||||||
outputMode->GetFrameRate(&frameDuration, &frameTimescale);
|
|
||||||
|
|
||||||
inputFrameRowBytes = inputFrameSize.width * 2u;
|
|
||||||
outputFrameRowBytes = outputFrameSize.width * 4u;
|
|
||||||
captureTextureWidth = inputFrameSize.width / 2u;
|
|
||||||
outputPackTextureWidth = outputFrameSize.width;
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool DeckLinkSession::SelectPreferredFormats(const VideoFormatSelection& videoModes, std::string& error)
|
|
||||||
{
|
|
||||||
if (!output)
|
|
||||||
{
|
|
||||||
error = "Expected an Output DeckLink device";
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
formatStatusMessage.clear();
|
|
||||||
|
|
||||||
const bool inputTenBitSupported = input != nullptr && InputSupportsFormat(input, videoModes.input.displayMode, bmdFormat10BitYUV);
|
|
||||||
inputPixelFormat = input != nullptr ? ChoosePreferredVideoIOFormat(inputTenBitSupported) : VideoIOPixelFormat::Uyvy8;
|
|
||||||
if (input != nullptr && !inputTenBitSupported)
|
|
||||||
formatStatusMessage += "DeckLink input does not report 10-bit YUV support for the configured mode; using 8-bit capture. ";
|
|
||||||
|
|
||||||
const bool outputTenBitSupported = OutputSupportsFormat(output, videoModes.output.displayMode, bmdFormat10BitYUV);
|
|
||||||
outputPixelFormat = ChoosePreferredVideoIOFormat(outputTenBitSupported);
|
|
||||||
if (!outputTenBitSupported)
|
|
||||||
formatStatusMessage += "DeckLink output does not report 10-bit YUV support for the configured mode; using 8-bit BGRA output. ";
|
|
||||||
|
|
||||||
int deckLinkOutputRowBytes = 0;
|
|
||||||
if (output->RowBytesForPixelFormat(OutputIsTenBit() ? bmdFormat10BitYUV : bmdFormat8BitBGRA, outputFrameSize.width, &deckLinkOutputRowBytes) != S_OK)
|
|
||||||
{
|
|
||||||
error = "DeckLink output setup failed while calculating output row bytes.";
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
outputFrameRowBytes = static_cast<unsigned>(deckLinkOutputRowBytes);
|
|
||||||
outputPackTextureWidth = OutputIsTenBit()
|
|
||||||
? PackedTextureWidthFromRowBytes(outputFrameRowBytes)
|
|
||||||
: outputFrameSize.width;
|
|
||||||
|
|
||||||
if (InputIsTenBit())
|
|
||||||
{
|
|
||||||
int deckLinkInputRowBytes = 0;
|
|
||||||
if (output->RowBytesForPixelFormat(bmdFormat10BitYUV, inputFrameSize.width, &deckLinkInputRowBytes) == S_OK)
|
|
||||||
inputFrameRowBytes = static_cast<unsigned>(deckLinkInputRowBytes);
|
|
||||||
else
|
|
||||||
inputFrameRowBytes = MinimumV210RowBytes(inputFrameSize.width);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
inputFrameRowBytes = inputFrameSize.width * 2u;
|
|
||||||
}
|
|
||||||
captureTextureWidth = InputIsTenBit()
|
|
||||||
? PackedTextureWidthFromRowBytes(inputFrameRowBytes)
|
|
||||||
: inputFrameSize.width / 2u;
|
|
||||||
|
|
||||||
std::ostringstream status;
|
|
||||||
status << "DeckLink formats: capture " << (input ? VideoIOPixelFormatName(inputPixelFormat) : "none")
|
|
||||||
<< ", output " << (OutputIsTenBit() ? "10-bit YUV v210" : "8-bit BGRA") << ".";
|
|
||||||
if (!formatStatusMessage.empty())
|
|
||||||
status << " " << formatStatusMessage;
|
|
||||||
formatStatusMessage = status.str();
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool DeckLinkSession::ConfigureInput(OpenGLComposite* owner, HDC hdc, HGLRC hglrc, const VideoFormat& inputVideoMode, std::string& error)
|
|
||||||
{
|
|
||||||
(void)hdc;
|
|
||||||
(void)hglrc;
|
|
||||||
|
|
||||||
if (!input)
|
|
||||||
{
|
|
||||||
hasNoInputSource = true;
|
|
||||||
inputDisplayModeName = "No input - black frame";
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
const BMDPixelFormat deckLinkInputPixelFormat = DeckLinkPixelFormatForVideoIO(inputPixelFormat);
|
|
||||||
if (input->EnableVideoInput(inputVideoMode.displayMode, deckLinkInputPixelFormat, bmdVideoInputFlagDefault) != S_OK)
|
|
||||||
{
|
|
||||||
if (inputPixelFormat == VideoIOPixelFormat::V210)
|
|
||||||
{
|
|
||||||
OutputDebugStringA("DeckLink 10-bit input could not be enabled; falling back to 8-bit capture.\n");
|
|
||||||
inputPixelFormat = VideoIOPixelFormat::Uyvy8;
|
|
||||||
inputFrameRowBytes = inputFrameSize.width * 2u;
|
|
||||||
captureTextureWidth = inputFrameSize.width / 2u;
|
|
||||||
if (input->EnableVideoInput(inputVideoMode.displayMode, bmdFormat8BitYUV, bmdVideoInputFlagDefault) == S_OK)
|
|
||||||
{
|
|
||||||
std::ostringstream status;
|
|
||||||
status << "DeckLink formats: capture " << VideoIOPixelFormatName(inputPixelFormat)
|
|
||||||
<< ", output " << (OutputIsTenBit() ? "10-bit YUV v210" : "8-bit BGRA")
|
|
||||||
<< ". DeckLink 10-bit input enable failed; using 8-bit capture.";
|
|
||||||
formatStatusMessage = status.str();
|
|
||||||
goto input_enabled;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
OutputDebugStringA("DeckLink input could not be enabled; continuing in output-only black-frame mode.\n");
|
|
||||||
input.Release();
|
|
||||||
hasNoInputSource = true;
|
|
||||||
inputDisplayModeName = "No input - black frame";
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
input_enabled:
|
|
||||||
captureDelegate.Attach(new (std::nothrow) CaptureDelegate(owner));
|
|
||||||
if (captureDelegate == nullptr)
|
|
||||||
{
|
|
||||||
error = "DeckLink input setup failed while creating the capture callback.";
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if (input->SetCallback(captureDelegate) != S_OK)
|
|
||||||
{
|
|
||||||
error = "DeckLink input setup failed while installing the capture callback.";
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool DeckLinkSession::ConfigureOutput(OpenGLComposite* owner, HDC hdc, HGLRC hglrc, const VideoFormat& outputVideoMode, bool externalKeyingEnabled, std::string& error)
|
|
||||||
{
|
|
||||||
(void)hdc;
|
|
||||||
(void)hglrc;
|
|
||||||
|
|
||||||
if (output->EnableVideoOutput(outputVideoMode.displayMode, bmdVideoOutputFlagDefault) != S_OK)
|
|
||||||
{
|
|
||||||
error = "DeckLink output setup failed while enabling video output.";
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (output->QueryInterface(IID_IDeckLinkKeyer, (void**)&keyer) == S_OK && keyer != NULL)
|
|
||||||
keyerInterfaceAvailable = true;
|
|
||||||
|
|
||||||
if (externalKeyingEnabled)
|
|
||||||
{
|
|
||||||
if (!supportsExternalKeying)
|
|
||||||
{
|
|
||||||
statusMessage = "External keying was requested, but the selected DeckLink output does not report external keying support.";
|
|
||||||
}
|
|
||||||
else if (!keyerInterfaceAvailable)
|
|
||||||
{
|
|
||||||
statusMessage = "External keying was requested, but the selected DeckLink output does not expose the IDeckLinkKeyer interface.";
|
|
||||||
}
|
|
||||||
else if (keyer->Enable(TRUE) != S_OK || keyer->SetLevel(255) != S_OK)
|
|
||||||
{
|
|
||||||
statusMessage = "External keying was requested, but enabling the DeckLink keyer failed.";
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
externalKeyingActive = true;
|
|
||||||
statusMessage = "External keying is active on the selected DeckLink output.";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else if (supportsExternalKeying)
|
|
||||||
{
|
|
||||||
statusMessage = "Selected DeckLink output supports external keying. Set enableExternalKeying to true in runtime-host.json to request it.";
|
|
||||||
}
|
|
||||||
|
|
||||||
for (int i = 0; i < 10; i++)
|
|
||||||
{
|
|
||||||
CComPtr<IDeckLinkMutableVideoFrame> outputFrame;
|
|
||||||
|
|
||||||
const BMDPixelFormat deckLinkOutputPixelFormat = OutputIsTenBit() ? bmdFormat10BitYUV : bmdFormat8BitBGRA;
|
|
||||||
if (output->CreateVideoFrame(outputFrameSize.width, outputFrameSize.height, outputFrameRowBytes, deckLinkOutputPixelFormat, bmdFrameFlagFlipVertical, &outputFrame) != S_OK)
|
|
||||||
{
|
|
||||||
error = "DeckLink output setup failed while creating an output video frame.";
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
outputVideoFrameQueue.push_back(outputFrame);
|
|
||||||
}
|
|
||||||
|
|
||||||
playoutDelegate.Attach(new (std::nothrow) PlayoutDelegate(owner));
|
|
||||||
if (playoutDelegate == nullptr)
|
|
||||||
{
|
|
||||||
error = "DeckLink output setup failed while creating the playout callback.";
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (output->SetScheduledFrameCompletionCallback(playoutDelegate) != S_OK)
|
|
||||||
{
|
|
||||||
error = "DeckLink output setup failed while installing the scheduled-frame callback.";
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!formatStatusMessage.empty())
|
|
||||||
statusMessage = statusMessage.empty() ? formatStatusMessage : formatStatusMessage + " " + statusMessage;
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
double DeckLinkSession::FrameBudgetMilliseconds() const
|
|
||||||
{
|
|
||||||
return frameTimescale != 0
|
|
||||||
? (static_cast<double>(frameDuration) * 1000.0) / static_cast<double>(frameTimescale)
|
|
||||||
: 0.0;
|
|
||||||
}
|
|
||||||
|
|
||||||
IDeckLinkMutableVideoFrame* DeckLinkSession::RotateOutputFrame()
|
|
||||||
{
|
|
||||||
CComPtr<IDeckLinkMutableVideoFrame> outputVideoFrame = outputVideoFrameQueue.front();
|
|
||||||
outputVideoFrameQueue.push_back(outputVideoFrame);
|
|
||||||
outputVideoFrameQueue.pop_front();
|
|
||||||
return outputVideoFrame.p;
|
|
||||||
}
|
|
||||||
|
|
||||||
void DeckLinkSession::AccountForCompletionResult(BMDOutputFrameCompletionResult completionResult)
|
|
||||||
{
|
|
||||||
if (completionResult == bmdOutputFrameDisplayedLate || completionResult == bmdOutputFrameDropped)
|
|
||||||
totalPlayoutFrames += 2;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool DeckLinkSession::ScheduleOutputFrame(IDeckLinkMutableVideoFrame* outputVideoFrame)
|
|
||||||
{
|
|
||||||
if (output->ScheduleVideoFrame(outputVideoFrame, (totalPlayoutFrames * frameDuration), frameDuration, frameTimescale) != S_OK)
|
|
||||||
return false;
|
|
||||||
|
|
||||||
totalPlayoutFrames++;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool DeckLinkSession::Start()
|
|
||||||
{
|
|
||||||
totalPlayoutFrames = 0;
|
|
||||||
if (!output)
|
|
||||||
{
|
|
||||||
MessageBoxA(NULL, "Cannot start playout because no DeckLink output device is available.", "DeckLink start failed", MB_OK | MB_ICONERROR);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if (outputVideoFrameQueue.empty())
|
|
||||||
{
|
|
||||||
MessageBoxA(NULL, "Cannot start playout because the output frame queue is empty.", "DeckLink start failed", MB_OK | MB_ICONERROR);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (unsigned i = 0; i < kPrerollFrameCount; i++)
|
|
||||||
{
|
|
||||||
CComPtr<IDeckLinkMutableVideoFrame> outputVideoFrame = outputVideoFrameQueue.front();
|
|
||||||
outputVideoFrameQueue.push_back(outputVideoFrame);
|
|
||||||
outputVideoFrameQueue.pop_front();
|
|
||||||
|
|
||||||
CComPtr<IDeckLinkVideoBuffer> outputVideoFrameBuffer;
|
|
||||||
if (outputVideoFrame->QueryInterface(IID_IDeckLinkVideoBuffer, (void**)&outputVideoFrameBuffer) != S_OK)
|
|
||||||
{
|
|
||||||
MessageBoxA(NULL, "Could not query the preroll output frame buffer.", "DeckLink start failed", MB_OK | MB_ICONERROR);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (outputVideoFrameBuffer->StartAccess(bmdBufferAccessWrite) != S_OK)
|
|
||||||
{
|
|
||||||
MessageBoxA(NULL, "Could not write to the preroll output frame buffer.", "DeckLink start failed", MB_OK | MB_ICONERROR);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
void* pFrame;
|
|
||||||
outputVideoFrameBuffer->GetBytes((void**)&pFrame);
|
|
||||||
memset(pFrame, 0, outputVideoFrame->GetRowBytes() * outputFrameSize.height);
|
|
||||||
|
|
||||||
outputVideoFrameBuffer->EndAccess(bmdBufferAccessWrite);
|
|
||||||
|
|
||||||
if (output->ScheduleVideoFrame(outputVideoFrame, (totalPlayoutFrames * frameDuration), frameDuration, frameTimescale) != S_OK)
|
|
||||||
{
|
|
||||||
MessageBoxA(NULL, "Could not schedule a preroll output frame.", "DeckLink start failed", MB_OK | MB_ICONERROR);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
totalPlayoutFrames++;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (input)
|
|
||||||
{
|
|
||||||
if (input->StartStreams() != S_OK)
|
|
||||||
{
|
|
||||||
MessageBoxA(NULL, "Could not start the DeckLink input stream.", "DeckLink start failed", MB_OK | MB_ICONERROR);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (output->StartScheduledPlayback(0, frameTimescale, 1.0) != S_OK)
|
|
||||||
{
|
|
||||||
MessageBoxA(NULL, "Could not start DeckLink scheduled playback.", "DeckLink start failed", MB_OK | MB_ICONERROR);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool DeckLinkSession::Stop()
|
|
||||||
{
|
|
||||||
if (keyer != nullptr)
|
|
||||||
{
|
|
||||||
keyer->Disable();
|
|
||||||
externalKeyingActive = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (input)
|
|
||||||
{
|
|
||||||
input->StopStreams();
|
|
||||||
input->DisableVideoInput();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (output)
|
|
||||||
{
|
|
||||||
output->StopScheduledPlayback(0, NULL, 0);
|
|
||||||
output->DisableVideoOutput();
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
@@ -1,88 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
|
|
||||||
#include "DeckLinkAPI_h.h"
|
|
||||||
#include "DeckLinkDisplayMode.h"
|
|
||||||
#include "DeckLinkFrameTransfer.h"
|
|
||||||
#include "VideoIOFormat.h"
|
|
||||||
|
|
||||||
#include <atlbase.h>
|
|
||||||
#include <deque>
|
|
||||||
#include <string>
|
|
||||||
|
|
||||||
class OpenGLComposite;
|
|
||||||
|
|
||||||
class DeckLinkSession
|
|
||||||
{
|
|
||||||
public:
|
|
||||||
DeckLinkSession() = default;
|
|
||||||
~DeckLinkSession();
|
|
||||||
|
|
||||||
void ReleaseResources();
|
|
||||||
bool DiscoverDevicesAndModes(const VideoFormatSelection& videoModes, std::string& error);
|
|
||||||
bool SelectPreferredFormats(const VideoFormatSelection& videoModes, std::string& error);
|
|
||||||
bool ConfigureInput(OpenGLComposite* owner, HDC hdc, HGLRC hglrc, const VideoFormat& inputVideoMode, std::string& error);
|
|
||||||
bool ConfigureOutput(OpenGLComposite* owner, HDC hdc, HGLRC hglrc, const VideoFormat& outputVideoMode, bool externalKeyingEnabled, std::string& error);
|
|
||||||
bool Start();
|
|
||||||
bool Stop();
|
|
||||||
|
|
||||||
bool HasInputDevice() const { return input != nullptr; }
|
|
||||||
bool HasInputSource() const { return !hasNoInputSource; }
|
|
||||||
void SetInputSourceMissing(bool missing) { hasNoInputSource = missing; }
|
|
||||||
bool InputOutputDimensionsDiffer() const { return inputFrameSize != outputFrameSize; }
|
|
||||||
const FrameSize& InputFrameSize() const { return inputFrameSize; }
|
|
||||||
const FrameSize& OutputFrameSize() const { return outputFrameSize; }
|
|
||||||
unsigned InputFrameWidth() const { return inputFrameSize.width; }
|
|
||||||
unsigned InputFrameHeight() const { return inputFrameSize.height; }
|
|
||||||
unsigned OutputFrameWidth() const { return outputFrameSize.width; }
|
|
||||||
unsigned OutputFrameHeight() const { return outputFrameSize.height; }
|
|
||||||
VideoIOPixelFormat InputPixelFormat() const { return inputPixelFormat; }
|
|
||||||
VideoIOPixelFormat OutputPixelFormat() const { return outputPixelFormat; }
|
|
||||||
bool InputIsTenBit() const { return VideoIOPixelFormatIsTenBit(inputPixelFormat); }
|
|
||||||
bool OutputIsTenBit() const { return VideoIOPixelFormatIsTenBit(outputPixelFormat); }
|
|
||||||
unsigned InputFrameRowBytes() const { return inputFrameRowBytes; }
|
|
||||||
unsigned OutputFrameRowBytes() const { return outputFrameRowBytes; }
|
|
||||||
unsigned CaptureTextureWidth() const { return captureTextureWidth; }
|
|
||||||
unsigned OutputPackTextureWidth() const { return outputPackTextureWidth; }
|
|
||||||
const std::string& FormatStatusMessage() const { return formatStatusMessage; }
|
|
||||||
const std::string& InputDisplayModeName() const { return inputDisplayModeName; }
|
|
||||||
const std::string& OutputModelName() const { return outputModelName; }
|
|
||||||
bool SupportsInternalKeying() const { return supportsInternalKeying; }
|
|
||||||
bool SupportsExternalKeying() const { return supportsExternalKeying; }
|
|
||||||
bool KeyerInterfaceAvailable() const { return keyerInterfaceAvailable; }
|
|
||||||
bool ExternalKeyingActive() const { return externalKeyingActive; }
|
|
||||||
const std::string& StatusMessage() const { return statusMessage; }
|
|
||||||
void SetStatusMessage(const std::string& message) { statusMessage = message; }
|
|
||||||
double FrameBudgetMilliseconds() const;
|
|
||||||
IDeckLinkMutableVideoFrame* RotateOutputFrame();
|
|
||||||
void AccountForCompletionResult(BMDOutputFrameCompletionResult completionResult);
|
|
||||||
bool ScheduleOutputFrame(IDeckLinkMutableVideoFrame* outputVideoFrame);
|
|
||||||
|
|
||||||
private:
|
|
||||||
CComPtr<CaptureDelegate> captureDelegate;
|
|
||||||
CComPtr<PlayoutDelegate> playoutDelegate;
|
|
||||||
CComPtr<IDeckLinkInput> input;
|
|
||||||
CComPtr<IDeckLinkOutput> output;
|
|
||||||
CComPtr<IDeckLinkKeyer> keyer;
|
|
||||||
std::deque<CComPtr<IDeckLinkMutableVideoFrame>> outputVideoFrameQueue;
|
|
||||||
BMDTimeValue frameDuration = 0;
|
|
||||||
BMDTimeScale frameTimescale = 0;
|
|
||||||
unsigned totalPlayoutFrames = 0;
|
|
||||||
FrameSize inputFrameSize;
|
|
||||||
FrameSize outputFrameSize;
|
|
||||||
VideoIOPixelFormat inputPixelFormat = VideoIOPixelFormat::Uyvy8;
|
|
||||||
VideoIOPixelFormat outputPixelFormat = VideoIOPixelFormat::Uyvy8;
|
|
||||||
unsigned inputFrameRowBytes = 0;
|
|
||||||
unsigned outputFrameRowBytes = 0;
|
|
||||||
unsigned captureTextureWidth = 0;
|
|
||||||
unsigned outputPackTextureWidth = 0;
|
|
||||||
std::string inputDisplayModeName = "1080p59.94";
|
|
||||||
std::string outputDisplayModeName = "1080p59.94";
|
|
||||||
bool hasNoInputSource = true;
|
|
||||||
std::string outputModelName;
|
|
||||||
bool supportsInternalKeying = false;
|
|
||||||
bool supportsExternalKeying = false;
|
|
||||||
bool keyerInterfaceAvailable = false;
|
|
||||||
bool externalKeyingActive = false;
|
|
||||||
std::string statusMessage;
|
|
||||||
std::string formatStatusMessage;
|
|
||||||
};
|
|
||||||
@@ -1,479 +0,0 @@
|
|||||||
#include "DeckLinkDisplayMode.h"
|
|
||||||
#include "DeckLinkSession.h"
|
|
||||||
#include "OpenGLComposite.h"
|
|
||||||
#include "GLExtensions.h"
|
|
||||||
#include "GlRenderConstants.h"
|
|
||||||
#include "OpenGLDeckLinkBridge.h"
|
|
||||||
#include "OpenGLRenderPass.h"
|
|
||||||
#include "OpenGLShaderPrograms.h"
|
|
||||||
#include "PngScreenshotWriter.h"
|
|
||||||
#include "RuntimeServices.h"
|
|
||||||
#include "ShaderBuildQueue.h"
|
|
||||||
|
|
||||||
#include <algorithm>
|
|
||||||
#include <chrono>
|
|
||||||
#include <ctime>
|
|
||||||
#include <filesystem>
|
|
||||||
#include <iomanip>
|
|
||||||
#include <memory>
|
|
||||||
#include <sstream>
|
|
||||||
#include <string>
|
|
||||||
#include <vector>
|
|
||||||
|
|
||||||
OpenGLComposite::OpenGLComposite(HWND hWnd, HDC hDC, HGLRC hRC) :
|
|
||||||
hGLWnd(hWnd), hGLDC(hDC), hGLRC(hRC),
|
|
||||||
mDeckLink(std::make_unique<DeckLinkSession>()),
|
|
||||||
mRenderer(std::make_unique<OpenGLRenderer>()),
|
|
||||||
mUseCommittedLayerStates(false),
|
|
||||||
mScreenshotRequested(false)
|
|
||||||
{
|
|
||||||
InitializeCriticalSection(&pMutex);
|
|
||||||
mRuntimeHost = std::make_unique<RuntimeHost>();
|
|
||||||
mDeckLinkBridge = std::make_unique<OpenGLDeckLinkBridge>(
|
|
||||||
*mDeckLink,
|
|
||||||
*mRenderer,
|
|
||||||
*mRuntimeHost,
|
|
||||||
pMutex,
|
|
||||||
hGLDC,
|
|
||||||
hGLRC,
|
|
||||||
[this]() { renderEffect(); },
|
|
||||||
[this]() { ProcessScreenshotRequest(); },
|
|
||||||
[this]() { paintGL(); });
|
|
||||||
mRenderPass = std::make_unique<OpenGLRenderPass>(*mRenderer);
|
|
||||||
mShaderPrograms = std::make_unique<OpenGLShaderPrograms>(*mRenderer, *mRuntimeHost);
|
|
||||||
mShaderBuildQueue = std::make_unique<ShaderBuildQueue>(*mRuntimeHost);
|
|
||||||
mRuntimeServices = std::make_unique<RuntimeServices>();
|
|
||||||
}
|
|
||||||
|
|
||||||
OpenGLComposite::~OpenGLComposite()
|
|
||||||
{
|
|
||||||
if (mRuntimeServices)
|
|
||||||
mRuntimeServices->Stop();
|
|
||||||
if (mShaderBuildQueue)
|
|
||||||
mShaderBuildQueue->Stop();
|
|
||||||
mDeckLink->ReleaseResources();
|
|
||||||
mRenderer->DestroyResources();
|
|
||||||
|
|
||||||
DeleteCriticalSection(&pMutex);
|
|
||||||
}
|
|
||||||
|
|
||||||
bool OpenGLComposite::InitDeckLink()
|
|
||||||
{
|
|
||||||
VideoFormatSelection videoModes;
|
|
||||||
std::string initFailureReason;
|
|
||||||
|
|
||||||
if (mRuntimeHost && mRuntimeHost->GetRepoRoot().empty())
|
|
||||||
{
|
|
||||||
std::string runtimeError;
|
|
||||||
if (!mRuntimeHost->Initialize(runtimeError))
|
|
||||||
{
|
|
||||||
MessageBoxA(NULL, runtimeError.c_str(), "Runtime host failed to initialize", MB_OK);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (mRuntimeHost)
|
|
||||||
{
|
|
||||||
if (!ResolveConfiguredVideoFormats(
|
|
||||||
mRuntimeHost->GetInputVideoFormat(),
|
|
||||||
mRuntimeHost->GetInputFrameRate(),
|
|
||||||
mRuntimeHost->GetOutputVideoFormat(),
|
|
||||||
mRuntimeHost->GetOutputFrameRate(),
|
|
||||||
videoModes,
|
|
||||||
initFailureReason))
|
|
||||||
{
|
|
||||||
MessageBoxA(NULL, initFailureReason.c_str(), "DeckLink mode configuration error", MB_OK);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!mDeckLink->DiscoverDevicesAndModes(videoModes, initFailureReason))
|
|
||||||
{
|
|
||||||
const char* title = initFailureReason == "Please install the Blackmagic DeckLink drivers to use the features of this application."
|
|
||||||
? "This application requires the DeckLink drivers installed."
|
|
||||||
: "DeckLink initialization failed";
|
|
||||||
MessageBoxA(NULL, initFailureReason.c_str(), title, MB_OK | MB_ICONERROR);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if (!mDeckLink->SelectPreferredFormats(videoModes, initFailureReason))
|
|
||||||
goto error;
|
|
||||||
|
|
||||||
if (! CheckOpenGLExtensions())
|
|
||||||
{
|
|
||||||
initFailureReason = "OpenGL extension checks failed.";
|
|
||||||
goto error;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (! InitOpenGLState())
|
|
||||||
{
|
|
||||||
initFailureReason = "OpenGL state initialization failed.";
|
|
||||||
goto error;
|
|
||||||
}
|
|
||||||
|
|
||||||
PublishDeckLinkOutputStatus(mDeckLink->OutputModelName().empty()
|
|
||||||
? "DeckLink output device selected."
|
|
||||||
: ("Selected output device: " + mDeckLink->OutputModelName()));
|
|
||||||
|
|
||||||
// Resize window to match output video frame, but scale large formats down by half for viewing.
|
|
||||||
if (mDeckLink->OutputFrameWidth() < 1920)
|
|
||||||
resizeWindow(mDeckLink->OutputFrameWidth(), mDeckLink->OutputFrameHeight());
|
|
||||||
else
|
|
||||||
resizeWindow(mDeckLink->OutputFrameWidth() / 2, mDeckLink->OutputFrameHeight() / 2);
|
|
||||||
|
|
||||||
if (!mDeckLink->ConfigureInput(this, hGLDC, hGLRC, videoModes.input, initFailureReason))
|
|
||||||
{
|
|
||||||
goto error;
|
|
||||||
}
|
|
||||||
if (!mDeckLink->HasInputDevice() && mRuntimeHost)
|
|
||||||
{
|
|
||||||
mRuntimeHost->SetSignalStatus(false, mDeckLink->InputFrameWidth(), mDeckLink->InputFrameHeight(), mDeckLink->InputDisplayModeName());
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!mDeckLink->ConfigureOutput(this, hGLDC, hGLRC, videoModes.output, mRuntimeHost && mRuntimeHost->ExternalKeyingEnabled(), initFailureReason))
|
|
||||||
{
|
|
||||||
goto error;
|
|
||||||
}
|
|
||||||
|
|
||||||
PublishDeckLinkOutputStatus(mDeckLink->StatusMessage());
|
|
||||||
|
|
||||||
return true;
|
|
||||||
|
|
||||||
error:
|
|
||||||
if (!initFailureReason.empty())
|
|
||||||
MessageBoxA(NULL, initFailureReason.c_str(), "DeckLink initialization failed", MB_OK | MB_ICONERROR);
|
|
||||||
mDeckLink->ReleaseResources();
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
void OpenGLComposite::paintGL()
|
|
||||||
{
|
|
||||||
if (!TryEnterCriticalSection(&pMutex))
|
|
||||||
{
|
|
||||||
ValidateRect(hGLWnd, NULL);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
mRenderer->PresentToWindow(hGLDC, mDeckLink->OutputFrameWidth(), mDeckLink->OutputFrameHeight());
|
|
||||||
ValidateRect(hGLWnd, NULL);
|
|
||||||
LeaveCriticalSection(&pMutex);
|
|
||||||
}
|
|
||||||
|
|
||||||
void OpenGLComposite::resizeGL(WORD width, WORD height)
|
|
||||||
{
|
|
||||||
// We don't set the project or model matrices here since the window data is copied directly from
|
|
||||||
// an off-screen FBO in paintGL(). Just save the width and height for use in paintGL().
|
|
||||||
mRenderer->ResizeView(width, height);
|
|
||||||
}
|
|
||||||
|
|
||||||
void OpenGLComposite::resizeWindow(int width, int height)
|
|
||||||
{
|
|
||||||
RECT r;
|
|
||||||
if (GetWindowRect(hGLWnd, &r))
|
|
||||||
{
|
|
||||||
SetWindowPos(hGLWnd, HWND_TOP, r.left, r.top, r.left + width, r.top + height, 0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void OpenGLComposite::PublishDeckLinkOutputStatus(const std::string& statusMessage)
|
|
||||||
{
|
|
||||||
if (!mRuntimeHost)
|
|
||||||
return;
|
|
||||||
|
|
||||||
if (!statusMessage.empty())
|
|
||||||
mDeckLink->SetStatusMessage(statusMessage);
|
|
||||||
|
|
||||||
mRuntimeHost->SetDeckLinkOutputStatus(
|
|
||||||
mDeckLink->OutputModelName(),
|
|
||||||
mDeckLink->SupportsInternalKeying(),
|
|
||||||
mDeckLink->SupportsExternalKeying(),
|
|
||||||
mDeckLink->KeyerInterfaceAvailable(),
|
|
||||||
mRuntimeHost->ExternalKeyingEnabled(),
|
|
||||||
mDeckLink->ExternalKeyingActive(),
|
|
||||||
mDeckLink->StatusMessage());
|
|
||||||
}
|
|
||||||
|
|
||||||
bool OpenGLComposite::InitOpenGLState()
|
|
||||||
{
|
|
||||||
if (! ResolveGLExtensions())
|
|
||||||
return false;
|
|
||||||
|
|
||||||
std::string runtimeError;
|
|
||||||
if (mRuntimeHost->GetRepoRoot().empty() && !mRuntimeHost->Initialize(runtimeError))
|
|
||||||
{
|
|
||||||
MessageBoxA(NULL, runtimeError.c_str(), "Runtime host failed to initialize", MB_OK);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!mRuntimeServices->Start(*this, *mRuntimeHost, runtimeError))
|
|
||||||
{
|
|
||||||
MessageBoxA(NULL, runtimeError.c_str(), "Runtime control services failed to start", MB_OK);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Prepare the runtime shader program generated from the active shader package.
|
|
||||||
char compilerErrorMessage[1024];
|
|
||||||
if (!mShaderPrograms->CompileDecodeShader(sizeof(compilerErrorMessage), compilerErrorMessage))
|
|
||||||
{
|
|
||||||
MessageBoxA(NULL, compilerErrorMessage, "OpenGL decode shader failed to load or compile", MB_OK);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if (!mShaderPrograms->CompileOutputPackShader(sizeof(compilerErrorMessage), compilerErrorMessage))
|
|
||||||
{
|
|
||||||
MessageBoxA(NULL, compilerErrorMessage, "OpenGL output pack shader failed to load or compile", MB_OK);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!mShaderPrograms->CompileLayerPrograms(mDeckLink->InputFrameWidth(), mDeckLink->InputFrameHeight(), sizeof(compilerErrorMessage), compilerErrorMessage))
|
|
||||||
{
|
|
||||||
MessageBoxA(NULL, compilerErrorMessage, "OpenGL shader failed to load or compile", MB_OK);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
mCachedLayerRenderStates = mShaderPrograms->CommittedLayerStates();
|
|
||||||
mUseCommittedLayerStates = false;
|
|
||||||
mShaderPrograms->ResetTemporalHistoryState();
|
|
||||||
|
|
||||||
std::string rendererError;
|
|
||||||
if (!mRenderer->InitializeResources(
|
|
||||||
mDeckLink->InputFrameWidth(),
|
|
||||||
mDeckLink->InputFrameHeight(),
|
|
||||||
mDeckLink->CaptureTextureWidth(),
|
|
||||||
mDeckLink->OutputFrameWidth(),
|
|
||||||
mDeckLink->OutputFrameHeight(),
|
|
||||||
mDeckLink->OutputPackTextureWidth(),
|
|
||||||
rendererError))
|
|
||||||
{
|
|
||||||
MessageBoxA(NULL, rendererError.c_str(), "OpenGL initialization error.", MB_OK);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
broadcastRuntimeState();
|
|
||||||
mRuntimeServices->BeginPolling(*mRuntimeHost);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
// DeckLink delegates still target OpenGLComposite; the bridge owns the per-frame work.
|
|
||||||
void OpenGLComposite::VideoFrameArrived(IDeckLinkVideoInputFrame* inputFrame, bool hasNoInputSource)
|
|
||||||
{
|
|
||||||
mDeckLinkBridge->VideoFrameArrived(inputFrame, hasNoInputSource);
|
|
||||||
}
|
|
||||||
|
|
||||||
void OpenGLComposite::PlayoutFrameCompleted(IDeckLinkVideoFrame* completedFrame, BMDOutputFrameCompletionResult completionResult)
|
|
||||||
{
|
|
||||||
mDeckLinkBridge->PlayoutFrameCompleted(completedFrame, completionResult);
|
|
||||||
}
|
|
||||||
|
|
||||||
bool OpenGLComposite::Start()
|
|
||||||
{
|
|
||||||
return mDeckLink->Start();
|
|
||||||
}
|
|
||||||
|
|
||||||
bool OpenGLComposite::Stop()
|
|
||||||
{
|
|
||||||
if (mRuntimeServices)
|
|
||||||
mRuntimeServices->Stop();
|
|
||||||
|
|
||||||
const bool wasExternalKeyingActive = mDeckLink->ExternalKeyingActive();
|
|
||||||
mDeckLink->Stop();
|
|
||||||
if (wasExternalKeyingActive)
|
|
||||||
PublishDeckLinkOutputStatus("External keying has been disabled.");
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool OpenGLComposite::ReloadShader()
|
|
||||||
{
|
|
||||||
if (mRuntimeHost)
|
|
||||||
{
|
|
||||||
mRuntimeHost->SetCompileStatus(true, "Shader rebuild queued.");
|
|
||||||
mRuntimeHost->ClearReloadRequest();
|
|
||||||
}
|
|
||||||
RequestShaderBuild();
|
|
||||||
broadcastRuntimeState();
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool OpenGLComposite::RequestScreenshot(std::string& error)
|
|
||||||
{
|
|
||||||
(void)error;
|
|
||||||
mScreenshotRequested.store(true);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
void OpenGLComposite::renderEffect()
|
|
||||||
{
|
|
||||||
ProcessRuntimePollResults();
|
|
||||||
|
|
||||||
const bool hasInputSource = mDeckLink->HasInputSource();
|
|
||||||
std::vector<RuntimeRenderState> layerStates;
|
|
||||||
if (mUseCommittedLayerStates)
|
|
||||||
{
|
|
||||||
layerStates = mShaderPrograms->CommittedLayerStates();
|
|
||||||
if (mRuntimeHost)
|
|
||||||
mRuntimeHost->RefreshDynamicRenderStateFields(layerStates);
|
|
||||||
}
|
|
||||||
else if (mRuntimeHost)
|
|
||||||
{
|
|
||||||
if (mRuntimeHost->TryGetLayerRenderStates(mDeckLink->InputFrameWidth(), mDeckLink->InputFrameHeight(), layerStates))
|
|
||||||
{
|
|
||||||
mCachedLayerRenderStates = layerStates;
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
layerStates = mCachedLayerRenderStates;
|
|
||||||
mRuntimeHost->RefreshDynamicRenderStateFields(layerStates);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const unsigned historyCap = mRuntimeHost ? mRuntimeHost->GetMaxTemporalHistoryFrames() : 0;
|
|
||||||
mRenderPass->Render(
|
|
||||||
hasInputSource,
|
|
||||||
layerStates,
|
|
||||||
mDeckLink->InputFrameWidth(),
|
|
||||||
mDeckLink->InputFrameHeight(),
|
|
||||||
mDeckLink->CaptureTextureWidth(),
|
|
||||||
mDeckLink->InputPixelFormat(),
|
|
||||||
historyCap,
|
|
||||||
[this](const RuntimeRenderState& state, LayerProgram::TextBinding& textBinding, std::string& error) {
|
|
||||||
return mShaderPrograms->UpdateTextBindingTexture(state, textBinding, error);
|
|
||||||
},
|
|
||||||
[this](const RuntimeRenderState& state, unsigned availableSourceHistoryLength, unsigned availableTemporalHistoryLength) {
|
|
||||||
return mShaderPrograms->UpdateGlobalParamsBuffer(state, availableSourceHistoryLength, availableTemporalHistoryLength);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
void OpenGLComposite::ProcessScreenshotRequest()
|
|
||||||
{
|
|
||||||
if (!mScreenshotRequested.exchange(false))
|
|
||||||
return;
|
|
||||||
|
|
||||||
const unsigned width = mDeckLink ? mDeckLink->OutputFrameWidth() : 0;
|
|
||||||
const unsigned height = mDeckLink ? mDeckLink->OutputFrameHeight() : 0;
|
|
||||||
if (width == 0 || height == 0)
|
|
||||||
return;
|
|
||||||
|
|
||||||
std::vector<unsigned char> bottomUpPixels(static_cast<std::size_t>(width) * height * 4);
|
|
||||||
std::vector<unsigned char> topDownPixels(bottomUpPixels.size());
|
|
||||||
|
|
||||||
glBindFramebuffer(GL_READ_FRAMEBUFFER, mRenderer->OutputFramebuffer());
|
|
||||||
glReadBuffer(GL_COLOR_ATTACHMENT0);
|
|
||||||
glPixelStorei(GL_PACK_ALIGNMENT, 1);
|
|
||||||
glPixelStorei(GL_PACK_ROW_LENGTH, 0);
|
|
||||||
glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, bottomUpPixels.data());
|
|
||||||
glPixelStorei(GL_PACK_ALIGNMENT, 4);
|
|
||||||
|
|
||||||
const std::size_t rowBytes = static_cast<std::size_t>(width) * 4;
|
|
||||||
for (unsigned y = 0; y < height; ++y)
|
|
||||||
{
|
|
||||||
const unsigned sourceY = height - 1 - y;
|
|
||||||
std::copy(
|
|
||||||
bottomUpPixels.begin() + static_cast<std::ptrdiff_t>(sourceY * rowBytes),
|
|
||||||
bottomUpPixels.begin() + static_cast<std::ptrdiff_t>((sourceY + 1) * rowBytes),
|
|
||||||
topDownPixels.begin() + static_cast<std::ptrdiff_t>(y * rowBytes));
|
|
||||||
}
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
const std::filesystem::path outputPath = BuildScreenshotPath();
|
|
||||||
std::filesystem::create_directories(outputPath.parent_path());
|
|
||||||
WritePngFileAsync(outputPath, width, height, std::move(topDownPixels));
|
|
||||||
}
|
|
||||||
catch (const std::exception& exception)
|
|
||||||
{
|
|
||||||
OutputDebugStringA((std::string("Screenshot request failed: ") + exception.what() + "\n").c_str());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
std::filesystem::path OpenGLComposite::BuildScreenshotPath() const
|
|
||||||
{
|
|
||||||
const std::filesystem::path root = mRuntimeHost && !mRuntimeHost->GetRuntimeRoot().empty()
|
|
||||||
? mRuntimeHost->GetRuntimeRoot()
|
|
||||||
: std::filesystem::current_path();
|
|
||||||
|
|
||||||
const auto now = std::chrono::system_clock::now();
|
|
||||||
const auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()) % 1000;
|
|
||||||
const std::time_t nowTime = std::chrono::system_clock::to_time_t(now);
|
|
||||||
std::tm localTime = {};
|
|
||||||
localtime_s(&localTime, &nowTime);
|
|
||||||
|
|
||||||
std::ostringstream filename;
|
|
||||||
filename << "video-shader-toys-"
|
|
||||||
<< std::put_time(&localTime, "%Y%m%d-%H%M%S")
|
|
||||||
<< "-" << std::setw(3) << std::setfill('0') << milliseconds.count()
|
|
||||||
<< ".png";
|
|
||||||
|
|
||||||
return root / "screenshots" / filename.str();
|
|
||||||
}
|
|
||||||
|
|
||||||
bool OpenGLComposite::ProcessRuntimePollResults()
|
|
||||||
{
|
|
||||||
if (!mRuntimeHost || !mRuntimeServices)
|
|
||||||
return true;
|
|
||||||
|
|
||||||
const RuntimePollEvents events = mRuntimeServices->ConsumePollEvents();
|
|
||||||
if (events.failed)
|
|
||||||
{
|
|
||||||
mRuntimeHost->SetCompileStatus(false, events.error);
|
|
||||||
broadcastRuntimeState();
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (events.registryChanged)
|
|
||||||
broadcastRuntimeState();
|
|
||||||
|
|
||||||
if (!events.reloadRequested)
|
|
||||||
{
|
|
||||||
PreparedShaderBuild readyBuild;
|
|
||||||
if (!mShaderBuildQueue || !mShaderBuildQueue->TryConsumeReadyBuild(readyBuild))
|
|
||||||
return true;
|
|
||||||
|
|
||||||
char compilerErrorMessage[1024] = {};
|
|
||||||
if (!mShaderPrograms->CommitPreparedLayerPrograms(readyBuild, mDeckLink->InputFrameWidth(), mDeckLink->InputFrameHeight(), sizeof(compilerErrorMessage), compilerErrorMessage))
|
|
||||||
{
|
|
||||||
mRuntimeHost->SetCompileStatus(false, compilerErrorMessage);
|
|
||||||
mUseCommittedLayerStates = true;
|
|
||||||
broadcastRuntimeState();
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
mUseCommittedLayerStates = false;
|
|
||||||
mCachedLayerRenderStates = mShaderPrograms->CommittedLayerStates();
|
|
||||||
mShaderPrograms->ResetTemporalHistoryState();
|
|
||||||
broadcastRuntimeState();
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
mRuntimeHost->SetCompileStatus(true, "Shader rebuild queued.");
|
|
||||||
RequestShaderBuild();
|
|
||||||
broadcastRuntimeState();
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
void OpenGLComposite::RequestShaderBuild()
|
|
||||||
{
|
|
||||||
if (!mShaderBuildQueue || !mDeckLink)
|
|
||||||
return;
|
|
||||||
|
|
||||||
mUseCommittedLayerStates = true;
|
|
||||||
if (mRuntimeHost)
|
|
||||||
mRuntimeHost->ClearReloadRequest();
|
|
||||||
mShaderBuildQueue->RequestBuild(mDeckLink->InputFrameWidth(), mDeckLink->InputFrameHeight());
|
|
||||||
}
|
|
||||||
|
|
||||||
void OpenGLComposite::broadcastRuntimeState()
|
|
||||||
{
|
|
||||||
if (mRuntimeServices)
|
|
||||||
mRuntimeServices->BroadcastState();
|
|
||||||
}
|
|
||||||
|
|
||||||
void OpenGLComposite::resetTemporalHistoryState()
|
|
||||||
{
|
|
||||||
mShaderPrograms->ResetTemporalHistoryState();
|
|
||||||
}
|
|
||||||
|
|
||||||
bool OpenGLComposite::CheckOpenGLExtensions()
|
|
||||||
{
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
////////////////////////////////////////////
|
|
||||||
|
|
||||||
|
|
||||||
@@ -1,145 +0,0 @@
|
|||||||
#include "OpenGLComposite.h"
|
|
||||||
|
|
||||||
std::string OpenGLComposite::GetRuntimeStateJson() const
|
|
||||||
{
|
|
||||||
return mRuntimeHost ? mRuntimeHost->BuildStateJson() : "{}";
|
|
||||||
}
|
|
||||||
|
|
||||||
unsigned short OpenGLComposite::GetControlServerPort() const
|
|
||||||
{
|
|
||||||
return mRuntimeHost ? mRuntimeHost->GetServerPort() : 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
unsigned short OpenGLComposite::GetOscPort() const
|
|
||||||
{
|
|
||||||
return mRuntimeHost ? mRuntimeHost->GetOscPort() : 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string OpenGLComposite::GetControlUrl() const
|
|
||||||
{
|
|
||||||
return "http://127.0.0.1:" + std::to_string(GetControlServerPort()) + "/";
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string OpenGLComposite::GetDocsUrl() const
|
|
||||||
{
|
|
||||||
return "http://127.0.0.1:" + std::to_string(GetControlServerPort()) + "/docs";
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string OpenGLComposite::GetOscAddress() const
|
|
||||||
{
|
|
||||||
return "udp://127.0.0.1:" + std::to_string(GetOscPort()) + " /VideoShaderToys/{Layer}/{Parameter}";
|
|
||||||
}
|
|
||||||
|
|
||||||
bool OpenGLComposite::AddLayer(const std::string& shaderId, std::string& error)
|
|
||||||
{
|
|
||||||
if (!mRuntimeHost->AddLayer(shaderId, error))
|
|
||||||
return false;
|
|
||||||
|
|
||||||
ReloadShader();
|
|
||||||
broadcastRuntimeState();
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool OpenGLComposite::RemoveLayer(const std::string& layerId, std::string& error)
|
|
||||||
{
|
|
||||||
if (!mRuntimeHost->RemoveLayer(layerId, error))
|
|
||||||
return false;
|
|
||||||
|
|
||||||
ReloadShader();
|
|
||||||
broadcastRuntimeState();
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool OpenGLComposite::MoveLayer(const std::string& layerId, int direction, std::string& error)
|
|
||||||
{
|
|
||||||
if (!mRuntimeHost->MoveLayer(layerId, direction, error))
|
|
||||||
return false;
|
|
||||||
|
|
||||||
ReloadShader();
|
|
||||||
broadcastRuntimeState();
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool OpenGLComposite::MoveLayerToIndex(const std::string& layerId, std::size_t targetIndex, std::string& error)
|
|
||||||
{
|
|
||||||
if (!mRuntimeHost->MoveLayerToIndex(layerId, targetIndex, error))
|
|
||||||
return false;
|
|
||||||
|
|
||||||
ReloadShader();
|
|
||||||
broadcastRuntimeState();
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool OpenGLComposite::SetLayerBypass(const std::string& layerId, bool bypassed, std::string& error)
|
|
||||||
{
|
|
||||||
if (!mRuntimeHost->SetLayerBypass(layerId, bypassed, error))
|
|
||||||
return false;
|
|
||||||
|
|
||||||
ReloadShader();
|
|
||||||
broadcastRuntimeState();
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool OpenGLComposite::SetLayerShader(const std::string& layerId, const std::string& shaderId, std::string& error)
|
|
||||||
{
|
|
||||||
if (!mRuntimeHost->SetLayerShader(layerId, shaderId, error))
|
|
||||||
return false;
|
|
||||||
|
|
||||||
ReloadShader();
|
|
||||||
broadcastRuntimeState();
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool OpenGLComposite::UpdateLayerParameterJson(const std::string& layerId, const std::string& parameterId, const std::string& valueJson, std::string& error)
|
|
||||||
{
|
|
||||||
JsonValue parsedValue;
|
|
||||||
if (!ParseJson(valueJson, parsedValue, error))
|
|
||||||
return false;
|
|
||||||
|
|
||||||
if (!mRuntimeHost->UpdateLayerParameter(layerId, parameterId, parsedValue, error))
|
|
||||||
return false;
|
|
||||||
|
|
||||||
broadcastRuntimeState();
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool OpenGLComposite::UpdateLayerParameterByControlKeyJson(const std::string& layerKey, const std::string& parameterKey, const std::string& valueJson, std::string& error)
|
|
||||||
{
|
|
||||||
JsonValue parsedValue;
|
|
||||||
if (!ParseJson(valueJson, parsedValue, error))
|
|
||||||
return false;
|
|
||||||
|
|
||||||
if (!mRuntimeHost->UpdateLayerParameterByControlKey(layerKey, parameterKey, parsedValue, error))
|
|
||||||
return false;
|
|
||||||
|
|
||||||
broadcastRuntimeState();
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool OpenGLComposite::ResetLayerParameters(const std::string& layerId, std::string& error)
|
|
||||||
{
|
|
||||||
if (!mRuntimeHost->ResetLayerParameters(layerId, error))
|
|
||||||
return false;
|
|
||||||
|
|
||||||
broadcastRuntimeState();
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool OpenGLComposite::SaveStackPreset(const std::string& presetName, std::string& error)
|
|
||||||
{
|
|
||||||
if (!mRuntimeHost->SaveStackPreset(presetName, error))
|
|
||||||
return false;
|
|
||||||
|
|
||||||
broadcastRuntimeState();
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool OpenGLComposite::LoadStackPreset(const std::string& presetName, std::string& error)
|
|
||||||
{
|
|
||||||
if (!mRuntimeHost->LoadStackPreset(presetName, error))
|
|
||||||
return false;
|
|
||||||
|
|
||||||
ReloadShader();
|
|
||||||
broadcastRuntimeState();
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
@@ -1,209 +0,0 @@
|
|||||||
#include "OpenGLDeckLinkBridge.h"
|
|
||||||
|
|
||||||
#include "DeckLinkSession.h"
|
|
||||||
#include "OpenGLRenderer.h"
|
|
||||||
#include "RuntimeHost.h"
|
|
||||||
|
|
||||||
#include <chrono>
|
|
||||||
#include <gl/gl.h>
|
|
||||||
|
|
||||||
OpenGLDeckLinkBridge::OpenGLDeckLinkBridge(
|
|
||||||
DeckLinkSession& deckLink,
|
|
||||||
OpenGLRenderer& renderer,
|
|
||||||
RuntimeHost& runtimeHost,
|
|
||||||
CRITICAL_SECTION& mutex,
|
|
||||||
HDC hdc,
|
|
||||||
HGLRC hglrc,
|
|
||||||
RenderEffectCallback renderEffect,
|
|
||||||
OutputReadyCallback outputReady,
|
|
||||||
PaintCallback paint) :
|
|
||||||
mDeckLink(deckLink),
|
|
||||||
mRenderer(renderer),
|
|
||||||
mRuntimeHost(runtimeHost),
|
|
||||||
mMutex(mutex),
|
|
||||||
mHdc(hdc),
|
|
||||||
mHglrc(hglrc),
|
|
||||||
mRenderEffect(renderEffect),
|
|
||||||
mOutputReady(outputReady),
|
|
||||||
mPaint(paint)
|
|
||||||
{
|
|
||||||
}
|
|
||||||
|
|
||||||
void OpenGLDeckLinkBridge::RecordFramePacing(BMDOutputFrameCompletionResult completionResult)
|
|
||||||
{
|
|
||||||
const auto now = std::chrono::steady_clock::now();
|
|
||||||
if (mLastPlayoutCompletionTime != std::chrono::steady_clock::time_point())
|
|
||||||
{
|
|
||||||
mCompletionIntervalMilliseconds = std::chrono::duration_cast<std::chrono::duration<double, std::milli>>(now - mLastPlayoutCompletionTime).count();
|
|
||||||
if (mSmoothedCompletionIntervalMilliseconds <= 0.0)
|
|
||||||
mSmoothedCompletionIntervalMilliseconds = mCompletionIntervalMilliseconds;
|
|
||||||
else
|
|
||||||
mSmoothedCompletionIntervalMilliseconds = mSmoothedCompletionIntervalMilliseconds * 0.9 + mCompletionIntervalMilliseconds * 0.1;
|
|
||||||
if (mCompletionIntervalMilliseconds > mMaxCompletionIntervalMilliseconds)
|
|
||||||
mMaxCompletionIntervalMilliseconds = mCompletionIntervalMilliseconds;
|
|
||||||
}
|
|
||||||
mLastPlayoutCompletionTime = now;
|
|
||||||
|
|
||||||
if (completionResult == bmdOutputFrameDisplayedLate)
|
|
||||||
++mLateFrameCount;
|
|
||||||
else if (completionResult == bmdOutputFrameDropped)
|
|
||||||
++mDroppedFrameCount;
|
|
||||||
else if (completionResult == bmdOutputFrameFlushed)
|
|
||||||
++mFlushedFrameCount;
|
|
||||||
|
|
||||||
mRuntimeHost.TrySetFramePacingStats(
|
|
||||||
mCompletionIntervalMilliseconds,
|
|
||||||
mSmoothedCompletionIntervalMilliseconds,
|
|
||||||
mMaxCompletionIntervalMilliseconds,
|
|
||||||
mLateFrameCount,
|
|
||||||
mDroppedFrameCount,
|
|
||||||
mFlushedFrameCount);
|
|
||||||
}
|
|
||||||
|
|
||||||
void OpenGLDeckLinkBridge::VideoFrameArrived(IDeckLinkVideoInputFrame* inputFrame, bool hasNoInputSource)
|
|
||||||
{
|
|
||||||
mDeckLink.SetInputSourceMissing(hasNoInputSource);
|
|
||||||
mRuntimeHost.TrySetSignalStatus(!hasNoInputSource, mDeckLink.InputFrameWidth(), mDeckLink.InputFrameHeight(), mDeckLink.InputDisplayModeName());
|
|
||||||
|
|
||||||
if (!mDeckLink.HasInputSource())
|
|
||||||
return; // don't transfer texture when there's no input
|
|
||||||
|
|
||||||
long textureSize = inputFrame->GetRowBytes() * inputFrame->GetHeight();
|
|
||||||
IDeckLinkVideoBuffer* inputFrameBuffer = NULL;
|
|
||||||
void* videoPixels;
|
|
||||||
|
|
||||||
if (inputFrame->QueryInterface(IID_IDeckLinkVideoBuffer, (void**)&inputFrameBuffer) != S_OK)
|
|
||||||
return;
|
|
||||||
|
|
||||||
if (inputFrameBuffer->StartAccess(bmdBufferAccessRead) != S_OK)
|
|
||||||
{
|
|
||||||
inputFrameBuffer->Release();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
inputFrameBuffer->GetBytes(&videoPixels);
|
|
||||||
|
|
||||||
EnterCriticalSection(&mMutex);
|
|
||||||
|
|
||||||
wglMakeCurrent(mHdc, mHglrc); // make OpenGL context current in this thread
|
|
||||||
|
|
||||||
glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
|
|
||||||
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
|
|
||||||
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, mRenderer.TextureUploadBuffer());
|
|
||||||
glBufferData(GL_PIXEL_UNPACK_BUFFER, textureSize, videoPixels, GL_DYNAMIC_DRAW);
|
|
||||||
glBindTexture(GL_TEXTURE_2D, mRenderer.CaptureTexture());
|
|
||||||
|
|
||||||
// NULL for last arg indicates use current GL_PIXEL_UNPACK_BUFFER target as texture data.
|
|
||||||
if (mDeckLink.InputPixelFormat() == VideoIOPixelFormat::V210)
|
|
||||||
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, mDeckLink.CaptureTextureWidth(), mDeckLink.InputFrameHeight(), GL_RGBA, GL_UNSIGNED_BYTE, NULL);
|
|
||||||
else
|
|
||||||
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, mDeckLink.CaptureTextureWidth(), mDeckLink.InputFrameHeight(), GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, NULL);
|
|
||||||
|
|
||||||
glBindTexture(GL_TEXTURE_2D, 0);
|
|
||||||
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
|
|
||||||
|
|
||||||
wglMakeCurrent(NULL, NULL);
|
|
||||||
|
|
||||||
LeaveCriticalSection(&mMutex);
|
|
||||||
|
|
||||||
inputFrameBuffer->EndAccess(bmdBufferAccessRead);
|
|
||||||
inputFrameBuffer->Release();
|
|
||||||
}
|
|
||||||
|
|
||||||
void OpenGLDeckLinkBridge::PlayoutFrameCompleted(IDeckLinkVideoFrame* completedFrame, BMDOutputFrameCompletionResult completionResult)
|
|
||||||
{
|
|
||||||
(void)completedFrame;
|
|
||||||
|
|
||||||
RecordFramePacing(completionResult);
|
|
||||||
|
|
||||||
EnterCriticalSection(&mMutex);
|
|
||||||
|
|
||||||
// Get the first frame from the queue
|
|
||||||
IDeckLinkMutableVideoFrame* outputVideoFrame = mDeckLink.RotateOutputFrame();
|
|
||||||
|
|
||||||
// make GL context current in this thread
|
|
||||||
wglMakeCurrent(mHdc, mHglrc);
|
|
||||||
|
|
||||||
// Draw the effect output to the off-screen framebuffer.
|
|
||||||
const auto renderStartTime = std::chrono::steady_clock::now();
|
|
||||||
glBindFramebuffer(GL_FRAMEBUFFER, mRenderer.CompositeFramebuffer());
|
|
||||||
mRenderEffect();
|
|
||||||
glBindFramebuffer(GL_READ_FRAMEBUFFER, mRenderer.CompositeFramebuffer());
|
|
||||||
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, mRenderer.OutputFramebuffer());
|
|
||||||
glBlitFramebuffer(0, 0, mDeckLink.InputFrameWidth(), mDeckLink.InputFrameHeight(), 0, 0, mDeckLink.OutputFrameWidth(), mDeckLink.OutputFrameHeight(), GL_COLOR_BUFFER_BIT, GL_LINEAR);
|
|
||||||
glBindFramebuffer(GL_FRAMEBUFFER, mRenderer.OutputFramebuffer());
|
|
||||||
if (mOutputReady)
|
|
||||||
mOutputReady();
|
|
||||||
if (mDeckLink.OutputIsTenBit())
|
|
||||||
{
|
|
||||||
glBindFramebuffer(GL_FRAMEBUFFER, mRenderer.OutputPackFramebuffer());
|
|
||||||
glViewport(0, 0, mDeckLink.OutputPackTextureWidth(), mDeckLink.OutputFrameHeight());
|
|
||||||
glDisable(GL_SCISSOR_TEST);
|
|
||||||
glDisable(GL_BLEND);
|
|
||||||
glDisable(GL_DEPTH_TEST);
|
|
||||||
glActiveTexture(GL_TEXTURE0);
|
|
||||||
glBindTexture(GL_TEXTURE_2D, mRenderer.OutputTexture());
|
|
||||||
glBindVertexArray(mRenderer.FullscreenVertexArray());
|
|
||||||
glUseProgram(mRenderer.OutputPackProgram());
|
|
||||||
const GLint outputResolutionLocation = glGetUniformLocation(mRenderer.OutputPackProgram(), "uOutputVideoResolution");
|
|
||||||
const GLint activeWordsLocation = glGetUniformLocation(mRenderer.OutputPackProgram(), "uActiveV210Words");
|
|
||||||
if (outputResolutionLocation >= 0)
|
|
||||||
glUniform2f(outputResolutionLocation, static_cast<float>(mDeckLink.OutputFrameWidth()), static_cast<float>(mDeckLink.OutputFrameHeight()));
|
|
||||||
if (activeWordsLocation >= 0)
|
|
||||||
glUniform1f(activeWordsLocation, static_cast<float>(ActiveV210WordsForWidth(mDeckLink.OutputFrameWidth())));
|
|
||||||
glDrawArrays(GL_TRIANGLES, 0, 3);
|
|
||||||
glUseProgram(0);
|
|
||||||
glBindVertexArray(0);
|
|
||||||
glBindTexture(GL_TEXTURE_2D, 0);
|
|
||||||
}
|
|
||||||
glFlush();
|
|
||||||
const auto renderEndTime = std::chrono::steady_clock::now();
|
|
||||||
const double frameBudgetMilliseconds = mDeckLink.FrameBudgetMilliseconds();
|
|
||||||
const double renderMilliseconds = std::chrono::duration_cast<std::chrono::duration<double, std::milli>>(renderEndTime - renderStartTime).count();
|
|
||||||
mRuntimeHost.TrySetPerformanceStats(frameBudgetMilliseconds, renderMilliseconds);
|
|
||||||
mRuntimeHost.TryAdvanceFrame();
|
|
||||||
|
|
||||||
IDeckLinkVideoBuffer* outputVideoFrameBuffer;
|
|
||||||
if (outputVideoFrame->QueryInterface(IID_IDeckLinkVideoBuffer, (void**)&outputVideoFrameBuffer) != S_OK)
|
|
||||||
{
|
|
||||||
wglMakeCurrent(NULL, NULL);
|
|
||||||
LeaveCriticalSection(&mMutex);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (outputVideoFrameBuffer->StartAccess(bmdBufferAccessWrite) != S_OK)
|
|
||||||
{
|
|
||||||
outputVideoFrameBuffer->Release();
|
|
||||||
wglMakeCurrent(NULL, NULL);
|
|
||||||
LeaveCriticalSection(&mMutex);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
void* pFrame;
|
|
||||||
outputVideoFrameBuffer->GetBytes(&pFrame);
|
|
||||||
|
|
||||||
glPixelStorei(GL_PACK_ALIGNMENT, 4);
|
|
||||||
glPixelStorei(GL_PACK_ROW_LENGTH, 0);
|
|
||||||
if (mDeckLink.OutputIsTenBit())
|
|
||||||
{
|
|
||||||
glBindFramebuffer(GL_READ_FRAMEBUFFER, mRenderer.OutputPackFramebuffer());
|
|
||||||
glReadPixels(0, 0, mDeckLink.OutputPackTextureWidth(), mDeckLink.OutputFrameHeight(), GL_RGBA, GL_UNSIGNED_BYTE, pFrame);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
glBindFramebuffer(GL_READ_FRAMEBUFFER, mRenderer.OutputFramebuffer());
|
|
||||||
glReadPixels(0, 0, mDeckLink.OutputFrameWidth(), mDeckLink.OutputFrameHeight(), GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, pFrame);
|
|
||||||
}
|
|
||||||
mPaint();
|
|
||||||
|
|
||||||
outputVideoFrameBuffer->EndAccess(bmdBufferAccessWrite);
|
|
||||||
outputVideoFrameBuffer->Release();
|
|
||||||
|
|
||||||
mDeckLink.AccountForCompletionResult(completionResult);
|
|
||||||
|
|
||||||
// Schedule the next frame for playout
|
|
||||||
mDeckLink.ScheduleOutputFrame(outputVideoFrame);
|
|
||||||
|
|
||||||
wglMakeCurrent(NULL, NULL);
|
|
||||||
|
|
||||||
LeaveCriticalSection(&mMutex);
|
|
||||||
}
|
|
||||||
@@ -1,55 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
|
|
||||||
#include "DeckLinkAPI_h.h"
|
|
||||||
|
|
||||||
#include <windows.h>
|
|
||||||
|
|
||||||
#include <chrono>
|
|
||||||
#include <functional>
|
|
||||||
#include <cstdint>
|
|
||||||
|
|
||||||
class DeckLinkSession;
|
|
||||||
class OpenGLRenderer;
|
|
||||||
class RuntimeHost;
|
|
||||||
|
|
||||||
class OpenGLDeckLinkBridge
|
|
||||||
{
|
|
||||||
public:
|
|
||||||
using RenderEffectCallback = std::function<void()>;
|
|
||||||
using OutputReadyCallback = std::function<void()>;
|
|
||||||
using PaintCallback = std::function<void()>;
|
|
||||||
|
|
||||||
OpenGLDeckLinkBridge(
|
|
||||||
DeckLinkSession& deckLink,
|
|
||||||
OpenGLRenderer& renderer,
|
|
||||||
RuntimeHost& runtimeHost,
|
|
||||||
CRITICAL_SECTION& mutex,
|
|
||||||
HDC hdc,
|
|
||||||
HGLRC hglrc,
|
|
||||||
RenderEffectCallback renderEffect,
|
|
||||||
OutputReadyCallback outputReady,
|
|
||||||
PaintCallback paint);
|
|
||||||
|
|
||||||
void VideoFrameArrived(IDeckLinkVideoInputFrame* inputFrame, bool hasNoInputSource);
|
|
||||||
void PlayoutFrameCompleted(IDeckLinkVideoFrame* completedFrame, BMDOutputFrameCompletionResult completionResult);
|
|
||||||
|
|
||||||
private:
|
|
||||||
void RecordFramePacing(BMDOutputFrameCompletionResult completionResult);
|
|
||||||
|
|
||||||
DeckLinkSession& mDeckLink;
|
|
||||||
OpenGLRenderer& mRenderer;
|
|
||||||
RuntimeHost& mRuntimeHost;
|
|
||||||
CRITICAL_SECTION& mMutex;
|
|
||||||
HDC mHdc;
|
|
||||||
HGLRC mHglrc;
|
|
||||||
RenderEffectCallback mRenderEffect;
|
|
||||||
OutputReadyCallback mOutputReady;
|
|
||||||
PaintCallback mPaint;
|
|
||||||
std::chrono::steady_clock::time_point mLastPlayoutCompletionTime;
|
|
||||||
double mCompletionIntervalMilliseconds = 0.0;
|
|
||||||
double mSmoothedCompletionIntervalMilliseconds = 0.0;
|
|
||||||
double mMaxCompletionIntervalMilliseconds = 0.0;
|
|
||||||
uint64_t mLateFrameCount = 0;
|
|
||||||
uint64_t mDroppedFrameCount = 0;
|
|
||||||
uint64_t mFlushedFrameCount = 0;
|
|
||||||
};
|
|
||||||
@@ -1,169 +0,0 @@
|
|||||||
#include "OpenGLRenderPass.h"
|
|
||||||
|
|
||||||
#include "GlRenderConstants.h"
|
|
||||||
|
|
||||||
OpenGLRenderPass::OpenGLRenderPass(OpenGLRenderer& renderer) :
|
|
||||||
mRenderer(renderer)
|
|
||||||
{
|
|
||||||
}
|
|
||||||
|
|
||||||
void OpenGLRenderPass::Render(
|
|
||||||
bool hasInputSource,
|
|
||||||
const std::vector<RuntimeRenderState>& layerStates,
|
|
||||||
unsigned inputFrameWidth,
|
|
||||||
unsigned inputFrameHeight,
|
|
||||||
unsigned captureTextureWidth,
|
|
||||||
VideoIOPixelFormat inputPixelFormat,
|
|
||||||
unsigned historyCap,
|
|
||||||
const TextBindingUpdater& updateTextBinding,
|
|
||||||
const GlobalParamsUpdater& updateGlobalParams)
|
|
||||||
{
|
|
||||||
glDisable(GL_SCISSOR_TEST);
|
|
||||||
glDisable(GL_BLEND);
|
|
||||||
glDisable(GL_DEPTH_TEST);
|
|
||||||
if (hasInputSource)
|
|
||||||
{
|
|
||||||
RenderDecodePass(inputFrameWidth, inputFrameHeight, captureTextureWidth, inputPixelFormat);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
glBindFramebuffer(GL_FRAMEBUFFER, mRenderer.DecodeFramebuffer());
|
|
||||||
glViewport(0, 0, inputFrameWidth, inputFrameHeight);
|
|
||||||
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
|
|
||||||
glClear(GL_COLOR_BUFFER_BIT);
|
|
||||||
}
|
|
||||||
|
|
||||||
std::vector<LayerProgram>& layerPrograms = mRenderer.LayerPrograms();
|
|
||||||
if (layerStates.empty() || layerPrograms.empty())
|
|
||||||
{
|
|
||||||
glBindFramebuffer(GL_READ_FRAMEBUFFER, mRenderer.DecodeFramebuffer());
|
|
||||||
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, mRenderer.CompositeFramebuffer());
|
|
||||||
glBlitFramebuffer(0, 0, inputFrameWidth, inputFrameHeight, 0, 0, inputFrameWidth, inputFrameHeight, GL_COLOR_BUFFER_BIT, GL_LINEAR);
|
|
||||||
glBindFramebuffer(GL_FRAMEBUFFER, mRenderer.CompositeFramebuffer());
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
GLuint sourceTexture = mRenderer.DecodedTexture();
|
|
||||||
GLuint sourceFrameBuffer = mRenderer.DecodeFramebuffer();
|
|
||||||
for (std::size_t index = 0; index < layerStates.size() && index < layerPrograms.size(); ++index)
|
|
||||||
{
|
|
||||||
const std::size_t remaining = layerStates.size() - index;
|
|
||||||
const bool writeToMain = (remaining % 2) == 1;
|
|
||||||
RenderShaderProgram(
|
|
||||||
sourceTexture,
|
|
||||||
writeToMain ? mRenderer.CompositeFramebuffer() : mRenderer.LayerTempFramebuffer(),
|
|
||||||
layerPrograms[index],
|
|
||||||
layerStates[index],
|
|
||||||
inputFrameWidth,
|
|
||||||
inputFrameHeight,
|
|
||||||
historyCap,
|
|
||||||
updateTextBinding,
|
|
||||||
updateGlobalParams);
|
|
||||||
if (layerStates[index].temporalHistorySource == TemporalHistorySource::PreLayerInput)
|
|
||||||
mRenderer.TemporalHistory().PushPreLayerFramebuffer(layerStates[index].layerId, sourceFrameBuffer, inputFrameWidth, inputFrameHeight);
|
|
||||||
sourceTexture = writeToMain ? mRenderer.CompositeTexture() : mRenderer.LayerTempTexture();
|
|
||||||
sourceFrameBuffer = writeToMain ? mRenderer.CompositeFramebuffer() : mRenderer.LayerTempFramebuffer();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
mRenderer.TemporalHistory().PushSourceFramebuffer(mRenderer.DecodeFramebuffer(), inputFrameWidth, inputFrameHeight);
|
|
||||||
}
|
|
||||||
|
|
||||||
void OpenGLRenderPass::RenderDecodePass(unsigned inputFrameWidth, unsigned inputFrameHeight, unsigned captureTextureWidth, VideoIOPixelFormat inputPixelFormat)
|
|
||||||
{
|
|
||||||
glBindFramebuffer(GL_FRAMEBUFFER, mRenderer.DecodeFramebuffer());
|
|
||||||
glViewport(0, 0, inputFrameWidth, inputFrameHeight);
|
|
||||||
glClear(GL_COLOR_BUFFER_BIT);
|
|
||||||
glActiveTexture(GL_TEXTURE0 + kPackedVideoTextureUnit);
|
|
||||||
glBindTexture(GL_TEXTURE_2D, mRenderer.CaptureTexture());
|
|
||||||
glBindVertexArray(mRenderer.FullscreenVertexArray());
|
|
||||||
glUseProgram(mRenderer.DecodeProgram());
|
|
||||||
|
|
||||||
const GLint packedResolutionLocation = glGetUniformLocation(mRenderer.DecodeProgram(), "uPackedVideoResolution");
|
|
||||||
const GLint decodedResolutionLocation = glGetUniformLocation(mRenderer.DecodeProgram(), "uDecodedVideoResolution");
|
|
||||||
const GLint inputPixelFormatLocation = glGetUniformLocation(mRenderer.DecodeProgram(), "uInputPixelFormat");
|
|
||||||
if (packedResolutionLocation >= 0)
|
|
||||||
glUniform2f(packedResolutionLocation, static_cast<float>(captureTextureWidth), static_cast<float>(inputFrameHeight));
|
|
||||||
if (decodedResolutionLocation >= 0)
|
|
||||||
glUniform2f(decodedResolutionLocation, static_cast<float>(inputFrameWidth), static_cast<float>(inputFrameHeight));
|
|
||||||
if (inputPixelFormatLocation >= 0)
|
|
||||||
glUniform1i(inputPixelFormatLocation, inputPixelFormat == VideoIOPixelFormat::V210 ? 1 : 0);
|
|
||||||
|
|
||||||
glDrawArrays(GL_TRIANGLES, 0, 3);
|
|
||||||
|
|
||||||
glUseProgram(0);
|
|
||||||
glBindVertexArray(0);
|
|
||||||
glBindTexture(GL_TEXTURE_2D, 0);
|
|
||||||
glActiveTexture(GL_TEXTURE0);
|
|
||||||
}
|
|
||||||
|
|
||||||
void OpenGLRenderPass::RenderShaderProgram(
|
|
||||||
GLuint sourceTexture,
|
|
||||||
GLuint destinationFrameBuffer,
|
|
||||||
LayerProgram& layerProgram,
|
|
||||||
const RuntimeRenderState& state,
|
|
||||||
unsigned inputFrameWidth,
|
|
||||||
unsigned inputFrameHeight,
|
|
||||||
unsigned historyCap,
|
|
||||||
const TextBindingUpdater& updateTextBinding,
|
|
||||||
const GlobalParamsUpdater& updateGlobalParams)
|
|
||||||
{
|
|
||||||
for (LayerProgram::TextBinding& textBinding : layerProgram.textBindings)
|
|
||||||
{
|
|
||||||
std::string textError;
|
|
||||||
if (!updateTextBinding(state, textBinding, textError))
|
|
||||||
OutputDebugStringA((textError + "\n").c_str());
|
|
||||||
}
|
|
||||||
|
|
||||||
glBindFramebuffer(GL_FRAMEBUFFER, destinationFrameBuffer);
|
|
||||||
glViewport(0, 0, inputFrameWidth, inputFrameHeight);
|
|
||||||
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
|
|
||||||
glActiveTexture(GL_TEXTURE0 + kDecodedVideoTextureUnit);
|
|
||||||
glBindTexture(GL_TEXTURE_2D, sourceTexture);
|
|
||||||
mRenderer.TemporalHistory().BindSamplers(state, sourceTexture, historyCap);
|
|
||||||
BindLayerTextureAssets(layerProgram);
|
|
||||||
glBindVertexArray(mRenderer.FullscreenVertexArray());
|
|
||||||
glUseProgram(layerProgram.program);
|
|
||||||
updateGlobalParams(state, mRenderer.TemporalHistory().SourceAvailableCount(), mRenderer.TemporalHistory().AvailableCountForLayer(state.layerId));
|
|
||||||
glDrawArrays(GL_TRIANGLES, 0, 3);
|
|
||||||
glUseProgram(0);
|
|
||||||
glBindVertexArray(0);
|
|
||||||
UnbindLayerTextureAssets(layerProgram, historyCap);
|
|
||||||
}
|
|
||||||
|
|
||||||
void OpenGLRenderPass::BindLayerTextureAssets(const LayerProgram& layerProgram)
|
|
||||||
{
|
|
||||||
const GLuint shaderTextureBase = layerProgram.shaderTextureBase != 0 ? layerProgram.shaderTextureBase : kSourceHistoryTextureUnitBase;
|
|
||||||
for (std::size_t index = 0; index < layerProgram.textureBindings.size(); ++index)
|
|
||||||
{
|
|
||||||
glActiveTexture(GL_TEXTURE0 + shaderTextureBase + static_cast<GLuint>(index));
|
|
||||||
glBindTexture(GL_TEXTURE_2D, layerProgram.textureBindings[index].texture);
|
|
||||||
}
|
|
||||||
const GLuint textTextureBase = shaderTextureBase + static_cast<GLuint>(layerProgram.textureBindings.size());
|
|
||||||
for (std::size_t index = 0; index < layerProgram.textBindings.size(); ++index)
|
|
||||||
{
|
|
||||||
glActiveTexture(GL_TEXTURE0 + textTextureBase + static_cast<GLuint>(index));
|
|
||||||
glBindTexture(GL_TEXTURE_2D, layerProgram.textBindings[index].texture);
|
|
||||||
}
|
|
||||||
glActiveTexture(GL_TEXTURE0);
|
|
||||||
}
|
|
||||||
|
|
||||||
void OpenGLRenderPass::UnbindLayerTextureAssets(const LayerProgram& layerProgram, unsigned historyCap)
|
|
||||||
{
|
|
||||||
for (unsigned index = 0; index < historyCap; ++index)
|
|
||||||
{
|
|
||||||
glActiveTexture(GL_TEXTURE0 + kSourceHistoryTextureUnitBase + index);
|
|
||||||
glBindTexture(GL_TEXTURE_2D, 0);
|
|
||||||
glActiveTexture(GL_TEXTURE0 + kSourceHistoryTextureUnitBase + historyCap + index);
|
|
||||||
glBindTexture(GL_TEXTURE_2D, 0);
|
|
||||||
}
|
|
||||||
const GLuint shaderTextureBase = layerProgram.shaderTextureBase != 0 ? layerProgram.shaderTextureBase : kSourceHistoryTextureUnitBase;
|
|
||||||
for (std::size_t index = 0; index < layerProgram.textureBindings.size() + layerProgram.textBindings.size(); ++index)
|
|
||||||
{
|
|
||||||
glActiveTexture(GL_TEXTURE0 + shaderTextureBase + static_cast<GLuint>(index));
|
|
||||||
glBindTexture(GL_TEXTURE_2D, 0);
|
|
||||||
}
|
|
||||||
glActiveTexture(GL_TEXTURE0 + kDecodedVideoTextureUnit);
|
|
||||||
glBindTexture(GL_TEXTURE_2D, 0);
|
|
||||||
glActiveTexture(GL_TEXTURE0);
|
|
||||||
}
|
|
||||||
668
apps/LoopThroughWithOpenGLCompositing/gl/RenderEngine.cpp
Normal file
668
apps/LoopThroughWithOpenGLCompositing/gl/RenderEngine.cpp
Normal file
@@ -0,0 +1,668 @@
|
|||||||
|
#include "RenderEngine.h"
|
||||||
|
|
||||||
|
#include <gl/gl.h>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <cstring>
|
||||||
|
#include <sstream>
|
||||||
|
|
||||||
|
RenderEngine::RenderEngine(
|
||||||
|
RuntimeSnapshotProvider& runtimeSnapshotProvider,
|
||||||
|
HealthTelemetry& healthTelemetry,
|
||||||
|
HDC hdc,
|
||||||
|
HGLRC hglrc,
|
||||||
|
RenderEffectCallback renderEffect,
|
||||||
|
ScreenshotCallback screenshotReady,
|
||||||
|
PreviewPaintCallback previewPaint) :
|
||||||
|
mRenderer(),
|
||||||
|
mRenderPass(mRenderer),
|
||||||
|
mRenderPipeline(mRenderer, runtimeSnapshotProvider, healthTelemetry, std::move(renderEffect), std::move(screenshotReady), std::move(previewPaint)),
|
||||||
|
mShaderPrograms(mRenderer, runtimeSnapshotProvider),
|
||||||
|
mHealthTelemetry(healthTelemetry),
|
||||||
|
mHdc(hdc),
|
||||||
|
mHglrc(hglrc),
|
||||||
|
mFrameStateResolver(runtimeSnapshotProvider)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
RenderEngine::~RenderEngine()
|
||||||
|
{
|
||||||
|
StopRenderThread();
|
||||||
|
if (!mResourcesDestroyed)
|
||||||
|
{
|
||||||
|
mRenderer.DestroyResources();
|
||||||
|
mResourcesDestroyed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool RenderEngine::StartRenderThread()
|
||||||
|
{
|
||||||
|
if (mRenderThreadRunning)
|
||||||
|
return true;
|
||||||
|
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mRenderThreadMutex);
|
||||||
|
mRenderThreadStopping = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::promise<bool> ready;
|
||||||
|
std::future<bool> readyResult = ready.get_future();
|
||||||
|
mRenderThread = std::thread(&RenderEngine::RenderThreadMain, this, std::move(ready));
|
||||||
|
if (!readyResult.get())
|
||||||
|
{
|
||||||
|
if (mRenderThread.joinable())
|
||||||
|
mRenderThread.join();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void RenderEngine::StopRenderThread()
|
||||||
|
{
|
||||||
|
if (mRenderThreadRunning)
|
||||||
|
{
|
||||||
|
InvokeOnRenderThread([this]() {
|
||||||
|
if (!mResourcesDestroyed)
|
||||||
|
{
|
||||||
|
mRenderer.DestroyResources();
|
||||||
|
mResourcesDestroyed = true;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mRenderThreadMutex);
|
||||||
|
mRenderThreadStopping = true;
|
||||||
|
}
|
||||||
|
mRenderThreadCondition.notify_one();
|
||||||
|
|
||||||
|
if (mRenderThread.joinable())
|
||||||
|
mRenderThread.join();
|
||||||
|
}
|
||||||
|
|
||||||
|
void RenderEngine::RenderThreadMain(std::promise<bool> ready)
|
||||||
|
{
|
||||||
|
mRenderThreadId = GetCurrentThreadId();
|
||||||
|
if (!wglMakeCurrent(mHdc, mHglrc))
|
||||||
|
{
|
||||||
|
mRenderThreadId = 0;
|
||||||
|
ready.set_value(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
mRenderThreadRunning = true;
|
||||||
|
ready.set_value(true);
|
||||||
|
|
||||||
|
for (;;)
|
||||||
|
{
|
||||||
|
std::function<void()> task;
|
||||||
|
{
|
||||||
|
std::unique_lock<std::mutex> lock(mRenderThreadMutex);
|
||||||
|
mRenderThreadCondition.wait(lock, [this]() {
|
||||||
|
return mRenderThreadStopping || !mRenderThreadTasks.empty();
|
||||||
|
});
|
||||||
|
|
||||||
|
if (mRenderThreadStopping && mRenderThreadTasks.empty())
|
||||||
|
break;
|
||||||
|
|
||||||
|
task = std::move(mRenderThreadTasks.front());
|
||||||
|
mRenderThreadTasks.pop();
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
task();
|
||||||
|
}
|
||||||
|
catch (...)
|
||||||
|
{
|
||||||
|
OutputDebugStringA("Render thread task failed with an unhandled exception.\n");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
wglMakeCurrent(NULL, NULL);
|
||||||
|
mRenderThreadRunning = false;
|
||||||
|
mRenderThreadId = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
void RenderEngine::ReportRenderThreadRequestFailure(const char* operationName, const char* reason)
|
||||||
|
{
|
||||||
|
std::ostringstream message;
|
||||||
|
message << "Render thread request failed";
|
||||||
|
if (operationName && operationName[0] != '\0')
|
||||||
|
message << " [" << operationName << "]";
|
||||||
|
if (reason && reason[0] != '\0')
|
||||||
|
message << ": " << reason;
|
||||||
|
message << ".\n";
|
||||||
|
OutputDebugStringA(message.str().c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
bool RenderEngine::IsRenderThreadAccessExpected() const
|
||||||
|
{
|
||||||
|
return !mRenderThreadRunning || GetCurrentThreadId() == mRenderThreadId;
|
||||||
|
}
|
||||||
|
|
||||||
|
void RenderEngine::ReportWrongThreadRenderAccess(const char* operationName) const
|
||||||
|
{
|
||||||
|
if (IsRenderThreadAccessExpected())
|
||||||
|
return;
|
||||||
|
|
||||||
|
std::ostringstream message;
|
||||||
|
message << "Wrong-thread render access detected";
|
||||||
|
if (operationName && operationName[0] != '\0')
|
||||||
|
message << " [" << operationName << "]";
|
||||||
|
message << ".\n";
|
||||||
|
OutputDebugStringA(message.str().c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
bool RenderEngine::CompileDecodeShader(int errorMessageSize, char* errorMessage)
|
||||||
|
{
|
||||||
|
return InvokeOnRenderThread([this, errorMessageSize, errorMessage]() {
|
||||||
|
return mShaderPrograms.CompileDecodeShader(errorMessageSize, errorMessage);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
bool RenderEngine::CompileOutputPackShader(int errorMessageSize, char* errorMessage)
|
||||||
|
{
|
||||||
|
return InvokeOnRenderThread([this, errorMessageSize, errorMessage]() {
|
||||||
|
return mShaderPrograms.CompileOutputPackShader(errorMessageSize, errorMessage);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
bool RenderEngine::InitializeResources(
|
||||||
|
unsigned inputFrameWidth,
|
||||||
|
unsigned inputFrameHeight,
|
||||||
|
unsigned captureTextureWidth,
|
||||||
|
unsigned outputFrameWidth,
|
||||||
|
unsigned outputFrameHeight,
|
||||||
|
unsigned outputPackTextureWidth,
|
||||||
|
std::string& error)
|
||||||
|
{
|
||||||
|
return InvokeOnRenderThread([this, inputFrameWidth, inputFrameHeight, captureTextureWidth, outputFrameWidth, outputFrameHeight, outputPackTextureWidth, &error]() {
|
||||||
|
return mRenderer.InitializeResources(
|
||||||
|
inputFrameWidth,
|
||||||
|
inputFrameHeight,
|
||||||
|
captureTextureWidth,
|
||||||
|
outputFrameWidth,
|
||||||
|
outputFrameHeight,
|
||||||
|
outputPackTextureWidth,
|
||||||
|
error);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
bool RenderEngine::CompileLayerPrograms(unsigned inputFrameWidth, unsigned inputFrameHeight, int errorMessageSize, char* errorMessage)
|
||||||
|
{
|
||||||
|
return InvokeOnRenderThread([this, inputFrameWidth, inputFrameHeight, errorMessageSize, errorMessage]() {
|
||||||
|
return mShaderPrograms.CompileLayerPrograms(inputFrameWidth, inputFrameHeight, errorMessageSize, errorMessage);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
bool RenderEngine::CommitPreparedLayerPrograms(const PreparedShaderBuild& preparedBuild, unsigned inputFrameWidth, unsigned inputFrameHeight, int errorMessageSize, char* errorMessage)
|
||||||
|
{
|
||||||
|
return InvokeOnRenderThread([this, &preparedBuild, inputFrameWidth, inputFrameHeight, errorMessageSize, errorMessage]() {
|
||||||
|
return mShaderPrograms.CommitPreparedLayerPrograms(preparedBuild, inputFrameWidth, inputFrameHeight, errorMessageSize, errorMessage);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
bool RenderEngine::ApplyPreparedShaderBuild(
|
||||||
|
const PreparedShaderBuild& preparedBuild,
|
||||||
|
unsigned inputFrameWidth,
|
||||||
|
unsigned inputFrameHeight,
|
||||||
|
bool preserveFeedbackState,
|
||||||
|
int errorMessageSize,
|
||||||
|
char* errorMessage)
|
||||||
|
{
|
||||||
|
if (!CommitPreparedLayerPrograms(preparedBuild, inputFrameWidth, inputFrameHeight, errorMessageSize, errorMessage))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
mFrameStateResolver.StoreCommittedSnapshot(preparedBuild.renderSnapshot, mShaderPrograms.CommittedLayerStates());
|
||||||
|
ResetTemporalHistoryState();
|
||||||
|
if (!preserveFeedbackState)
|
||||||
|
ResetShaderFeedbackState();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void RenderEngine::ResetTemporalHistoryState()
|
||||||
|
{
|
||||||
|
InvokeOnRenderThread([this]() {
|
||||||
|
mRenderCommandQueue.RequestRenderReset(RenderCommandResetScope::TemporalHistoryOnly);
|
||||||
|
ProcessRenderResetCommandsOnRenderThread();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
void RenderEngine::ResetShaderFeedbackState()
|
||||||
|
{
|
||||||
|
InvokeOnRenderThread([this]() {
|
||||||
|
mRenderCommandQueue.RequestRenderReset(RenderCommandResetScope::ShaderFeedbackOnly);
|
||||||
|
ProcessRenderResetCommandsOnRenderThread();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
void RenderEngine::ApplyRuntimeCoordinatorRenderReset(RuntimeCoordinatorRenderResetScope resetScope)
|
||||||
|
{
|
||||||
|
InvokeOnRenderThread([this, resetScope]() {
|
||||||
|
switch (resetScope)
|
||||||
|
{
|
||||||
|
case RuntimeCoordinatorRenderResetScope::TemporalHistoryOnly:
|
||||||
|
mRenderCommandQueue.RequestRenderReset(RenderCommandResetScope::TemporalHistoryOnly);
|
||||||
|
ProcessRenderResetCommandsOnRenderThread();
|
||||||
|
break;
|
||||||
|
case RuntimeCoordinatorRenderResetScope::TemporalHistoryAndFeedback:
|
||||||
|
mRenderCommandQueue.RequestRenderReset(RenderCommandResetScope::TemporalHistoryAndFeedback);
|
||||||
|
ProcessRenderResetCommandsOnRenderThread();
|
||||||
|
break;
|
||||||
|
case RuntimeCoordinatorRenderResetScope::None:
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
void RenderEngine::ResetTemporalHistoryStateOnRenderThread()
|
||||||
|
{
|
||||||
|
ReportWrongThreadRenderAccess("reset-temporal-history");
|
||||||
|
mShaderPrograms.ResetTemporalHistoryState();
|
||||||
|
}
|
||||||
|
|
||||||
|
void RenderEngine::ResetShaderFeedbackStateOnRenderThread()
|
||||||
|
{
|
||||||
|
ReportWrongThreadRenderAccess("reset-shader-feedback");
|
||||||
|
mShaderPrograms.ResetShaderFeedbackState();
|
||||||
|
}
|
||||||
|
|
||||||
|
void RenderEngine::ApplyRenderResetOnRenderThread(RenderCommandResetScope resetScope)
|
||||||
|
{
|
||||||
|
switch (resetScope)
|
||||||
|
{
|
||||||
|
case RenderCommandResetScope::ShaderFeedbackOnly:
|
||||||
|
ResetShaderFeedbackStateOnRenderThread();
|
||||||
|
break;
|
||||||
|
case RenderCommandResetScope::TemporalHistoryOnly:
|
||||||
|
ResetTemporalHistoryStateOnRenderThread();
|
||||||
|
break;
|
||||||
|
case RenderCommandResetScope::TemporalHistoryAndFeedback:
|
||||||
|
ResetTemporalHistoryStateOnRenderThread();
|
||||||
|
ResetShaderFeedbackStateOnRenderThread();
|
||||||
|
break;
|
||||||
|
case RenderCommandResetScope::None:
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void RenderEngine::ProcessRenderResetCommandsOnRenderThread()
|
||||||
|
{
|
||||||
|
RenderCommandResetScope resetScope = RenderCommandResetScope::None;
|
||||||
|
while (mRenderCommandQueue.TryTakeRenderReset(resetScope))
|
||||||
|
ApplyRenderResetOnRenderThread(resetScope);
|
||||||
|
}
|
||||||
|
|
||||||
|
void RenderEngine::EnqueuePreviewPresentWake()
|
||||||
|
{
|
||||||
|
if (!mRenderThreadRunning)
|
||||||
|
return;
|
||||||
|
|
||||||
|
bool shouldNotify = false;
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mRenderThreadMutex);
|
||||||
|
if (!mRenderThreadStopping && !mPreviewPresentWakePending)
|
||||||
|
{
|
||||||
|
mPreviewPresentWakePending = true;
|
||||||
|
mRenderThreadTasks.push([this]() {
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mRenderThreadMutex);
|
||||||
|
mPreviewPresentWakePending = false;
|
||||||
|
}
|
||||||
|
ProcessPreviewPresentCommandsOnRenderThread();
|
||||||
|
});
|
||||||
|
shouldNotify = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (shouldNotify)
|
||||||
|
mRenderThreadCondition.notify_one();
|
||||||
|
}
|
||||||
|
|
||||||
|
void RenderEngine::ProcessPreviewPresentCommandsOnRenderThread()
|
||||||
|
{
|
||||||
|
RenderPreviewPresentRequest request;
|
||||||
|
if (mRenderCommandQueue.TryTakePreviewPresent(request))
|
||||||
|
PresentPreviewOnRenderThread(request.outputFrameWidth, request.outputFrameHeight);
|
||||||
|
}
|
||||||
|
|
||||||
|
void RenderEngine::EnqueueInputUploadWake()
|
||||||
|
{
|
||||||
|
if (!mRenderThreadRunning || GetCurrentThreadId() == mRenderThreadId)
|
||||||
|
return;
|
||||||
|
|
||||||
|
bool shouldNotify = false;
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mRenderThreadMutex);
|
||||||
|
if (!mRenderThreadStopping && !mInputUploadWakePending)
|
||||||
|
{
|
||||||
|
mInputUploadWakePending = true;
|
||||||
|
mRenderThreadTasks.push([this]() {
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mRenderThreadMutex);
|
||||||
|
mInputUploadWakePending = false;
|
||||||
|
}
|
||||||
|
ProcessInputUploadCommandsOnRenderThread();
|
||||||
|
});
|
||||||
|
shouldNotify = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (shouldNotify)
|
||||||
|
mRenderThreadCondition.notify_one();
|
||||||
|
}
|
||||||
|
|
||||||
|
void RenderEngine::ProcessInputUploadCommandsOnRenderThread()
|
||||||
|
{
|
||||||
|
RenderInputUploadRequest request;
|
||||||
|
while (mRenderCommandQueue.TryTakeInputUpload(request))
|
||||||
|
{
|
||||||
|
if (request.ownedBytes.empty())
|
||||||
|
continue;
|
||||||
|
|
||||||
|
request.inputFrame.bytes = request.ownedBytes.data();
|
||||||
|
UploadInputFrameOnRenderThread(request.inputFrame, request.videoState);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void RenderEngine::EnqueueScreenshotCaptureWake()
|
||||||
|
{
|
||||||
|
if (!mRenderThreadRunning || GetCurrentThreadId() == mRenderThreadId)
|
||||||
|
return;
|
||||||
|
|
||||||
|
bool shouldNotify = false;
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mRenderThreadMutex);
|
||||||
|
if (!mRenderThreadStopping && !mScreenshotCaptureWakePending)
|
||||||
|
{
|
||||||
|
mScreenshotCaptureWakePending = true;
|
||||||
|
mRenderThreadTasks.push([this]() {
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mRenderThreadMutex);
|
||||||
|
mScreenshotCaptureWakePending = false;
|
||||||
|
}
|
||||||
|
ProcessScreenshotCaptureCommandsOnRenderThread();
|
||||||
|
});
|
||||||
|
shouldNotify = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (shouldNotify)
|
||||||
|
mRenderThreadCondition.notify_one();
|
||||||
|
}
|
||||||
|
|
||||||
|
void RenderEngine::ProcessScreenshotCaptureCommandsOnRenderThread()
|
||||||
|
{
|
||||||
|
RenderScreenshotCaptureRequest request;
|
||||||
|
ScreenshotCaptureCallback completion;
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mRenderThreadMutex);
|
||||||
|
completion = mScreenshotCaptureCompletion;
|
||||||
|
}
|
||||||
|
|
||||||
|
while (mRenderCommandQueue.TryTakeScreenshotCapture(request))
|
||||||
|
{
|
||||||
|
if (!completion)
|
||||||
|
continue;
|
||||||
|
|
||||||
|
std::vector<unsigned char> topDownPixels;
|
||||||
|
if (CaptureOutputFrameRgbaTopDownOnRenderThread(request.width, request.height, topDownPixels))
|
||||||
|
completion(request.width, request.height, std::move(topDownPixels));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void RenderEngine::ClearOscOverlayState()
|
||||||
|
{
|
||||||
|
InvokeOnRenderThread([this]() {
|
||||||
|
mRuntimeLiveState.Clear();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
void RenderEngine::ClearOscOverlayStateForLayerKey(const std::string& layerKey)
|
||||||
|
{
|
||||||
|
InvokeOnRenderThread([this, layerKey]() {
|
||||||
|
mRuntimeLiveState.ClearForLayerKey(layerKey);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
void RenderEngine::UpdateOscOverlayState(
|
||||||
|
const std::vector<OscOverlayUpdate>& updates,
|
||||||
|
const std::vector<OscOverlayCommitCompletion>& completedCommits)
|
||||||
|
{
|
||||||
|
std::vector<RuntimeLiveOscCommitCompletion> liveCompletions;
|
||||||
|
liveCompletions.reserve(completedCommits.size());
|
||||||
|
for (const OscOverlayCommitCompletion& completedCommit : completedCommits)
|
||||||
|
liveCompletions.push_back({ completedCommit.routeKey, completedCommit.generation });
|
||||||
|
mRuntimeLiveState.ApplyOscCommitCompletions(liveCompletions);
|
||||||
|
|
||||||
|
std::vector<RuntimeLiveOscUpdate> liveUpdates;
|
||||||
|
liveUpdates.reserve(updates.size());
|
||||||
|
for (const OscOverlayUpdate& update : updates)
|
||||||
|
liveUpdates.push_back({ update.routeKey, update.layerKey, update.parameterKey, update.targetValue });
|
||||||
|
mRuntimeLiveState.ApplyOscUpdates(liveUpdates);
|
||||||
|
}
|
||||||
|
|
||||||
|
void RenderEngine::ResizeView(int width, int height)
|
||||||
|
{
|
||||||
|
InvokeOnRenderThread([this, width, height]() {
|
||||||
|
mRenderer.ResizeView(width, height);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
bool RenderEngine::TryPresentPreview(bool force, unsigned previewFps, unsigned outputFrameWidth, unsigned outputFrameHeight)
|
||||||
|
{
|
||||||
|
if (!force)
|
||||||
|
{
|
||||||
|
if (previewFps == 0)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
const auto now = std::chrono::steady_clock::now();
|
||||||
|
const auto minimumInterval = std::chrono::microseconds(1000000 / (previewFps == 0 ? 1u : previewFps));
|
||||||
|
if (mLastPreviewPresentTime != std::chrono::steady_clock::time_point() &&
|
||||||
|
now - mLastPreviewPresentTime < minimumInterval)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mRenderThreadRunning)
|
||||||
|
{
|
||||||
|
mRenderCommandQueue.RequestPreviewPresent({ outputFrameWidth, outputFrameHeight });
|
||||||
|
EnqueuePreviewPresentWake();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
ReportRenderThreadRequestFailure("preview-present", "render thread is not running");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool RenderEngine::PresentPreviewOnRenderThread(unsigned outputFrameWidth, unsigned outputFrameHeight)
|
||||||
|
{
|
||||||
|
ReportWrongThreadRenderAccess("preview-present");
|
||||||
|
mRenderer.PresentToWindow(mHdc, outputFrameWidth, outputFrameHeight);
|
||||||
|
mLastPreviewPresentTime = std::chrono::steady_clock::now();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool RenderEngine::RequestScreenshotCapture(unsigned width, unsigned height, ScreenshotCaptureCallback completion)
|
||||||
|
{
|
||||||
|
if (width == 0 || height == 0 || !completion)
|
||||||
|
return false;
|
||||||
|
if (!mRenderThreadRunning)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mRenderThreadMutex);
|
||||||
|
mScreenshotCaptureCompletion = std::move(completion);
|
||||||
|
}
|
||||||
|
mRenderCommandQueue.RequestScreenshotCapture({ width, height });
|
||||||
|
EnqueueScreenshotCaptureWake();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool RenderEngine::QueueInputFrame(const VideoIOFrame& inputFrame, const VideoIOState& videoState)
|
||||||
|
{
|
||||||
|
if (inputFrame.hasNoInputSource || inputFrame.bytes == nullptr)
|
||||||
|
return true;
|
||||||
|
if (inputFrame.rowBytes <= 0 || inputFrame.height == 0)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
const std::size_t byteCount = static_cast<std::size_t>(inputFrame.rowBytes) * inputFrame.height;
|
||||||
|
RenderInputUploadRequest request;
|
||||||
|
request.inputFrame = inputFrame;
|
||||||
|
request.videoState = videoState;
|
||||||
|
request.ownedBytes.resize(byteCount);
|
||||||
|
std::memcpy(request.ownedBytes.data(), inputFrame.bytes, byteCount);
|
||||||
|
request.inputFrame.bytes = nullptr;
|
||||||
|
|
||||||
|
mRenderCommandQueue.RequestInputUpload(request);
|
||||||
|
EnqueueInputUploadWake();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool RenderEngine::UploadInputFrameOnRenderThread(const VideoIOFrame& inputFrame, const VideoIOState& videoState)
|
||||||
|
{
|
||||||
|
ReportWrongThreadRenderAccess("input-upload");
|
||||||
|
const long textureSize = inputFrame.rowBytes * static_cast<long>(inputFrame.height);
|
||||||
|
glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
|
||||||
|
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
|
||||||
|
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, mRenderer.TextureUploadBuffer());
|
||||||
|
glBufferData(GL_PIXEL_UNPACK_BUFFER, textureSize, inputFrame.bytes, GL_DYNAMIC_DRAW);
|
||||||
|
glBindTexture(GL_TEXTURE_2D, mRenderer.CaptureTexture());
|
||||||
|
if (inputFrame.pixelFormat == VideoIOPixelFormat::V210)
|
||||||
|
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, videoState.captureTextureWidth, videoState.inputFrameSize.height, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
|
||||||
|
else
|
||||||
|
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, videoState.captureTextureWidth, videoState.inputFrameSize.height, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, NULL);
|
||||||
|
glBindTexture(GL_TEXTURE_2D, 0);
|
||||||
|
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool RenderEngine::RequestOutputFrame(const RenderPipelineFrameContext& context, VideoIOOutputFrame& outputFrame)
|
||||||
|
{
|
||||||
|
if (mRenderThreadRunning)
|
||||||
|
{
|
||||||
|
const auto queuedAt = std::chrono::steady_clock::now();
|
||||||
|
return TryInvokeOnRenderThread("output-render", [this, &context, &outputFrame, queuedAt]() {
|
||||||
|
const auto startedAt = std::chrono::steady_clock::now();
|
||||||
|
const double queueWaitMilliseconds = std::chrono::duration_cast<std::chrono::duration<double, std::milli>>(startedAt - queuedAt).count();
|
||||||
|
mHealthTelemetry.TryRecordOutputRenderQueueWait(queueWaitMilliseconds);
|
||||||
|
mRenderCommandQueue.RequestOutputFrame({ context.videoState, context.completion });
|
||||||
|
RenderOutputFrameRequest request;
|
||||||
|
return mRenderCommandQueue.TryTakeOutputFrame(request) &&
|
||||||
|
RenderOutputFrameOnRenderThread({ request.videoState, request.completion }, outputFrame);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
ReportRenderThreadRequestFailure("output-render", "render thread is not running");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool RenderEngine::RenderOutputFrameOnRenderThread(const RenderPipelineFrameContext& context, VideoIOOutputFrame& outputFrame)
|
||||||
|
{
|
||||||
|
ReportWrongThreadRenderAccess("output-render");
|
||||||
|
ProcessRenderResetCommandsOnRenderThread();
|
||||||
|
ProcessInputUploadCommandsOnRenderThread();
|
||||||
|
return mRenderPipeline.RenderFrame(context, outputFrame);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool RenderEngine::ResolveRenderFrameState(
|
||||||
|
const RenderFrameInput& input,
|
||||||
|
std::vector<OscOverlayCommitRequest>* commitRequests,
|
||||||
|
RenderFrameState& frameState)
|
||||||
|
{
|
||||||
|
std::vector<RuntimeLiveOscCommitRequest> liveCommitRequests;
|
||||||
|
const bool resolved = mFrameStateResolver.Resolve(
|
||||||
|
input,
|
||||||
|
mShaderPrograms.CommittedLayerStates(),
|
||||||
|
mRuntimeLiveState,
|
||||||
|
commitRequests ? &liveCommitRequests : nullptr,
|
||||||
|
frameState);
|
||||||
|
|
||||||
|
if (commitRequests)
|
||||||
|
{
|
||||||
|
for (const RuntimeLiveOscCommitRequest& request : liveCommitRequests)
|
||||||
|
commitRequests->push_back({ request.routeKey, request.layerKey, request.parameterKey, request.value, request.generation });
|
||||||
|
}
|
||||||
|
return resolved;
|
||||||
|
}
|
||||||
|
|
||||||
|
void RenderEngine::RenderPreparedFrame(const RenderFrameState& frameState)
|
||||||
|
{
|
||||||
|
RenderLayerStack(
|
||||||
|
frameState.hasInputSource,
|
||||||
|
frameState.layerStates,
|
||||||
|
frameState.inputFrameWidth,
|
||||||
|
frameState.inputFrameHeight,
|
||||||
|
frameState.captureTextureWidth,
|
||||||
|
frameState.inputPixelFormat,
|
||||||
|
frameState.historyCap);
|
||||||
|
}
|
||||||
|
|
||||||
|
void RenderEngine::RenderLayerStack(
|
||||||
|
bool hasInputSource,
|
||||||
|
const std::vector<RuntimeRenderState>& layerStates,
|
||||||
|
unsigned inputFrameWidth,
|
||||||
|
unsigned inputFrameHeight,
|
||||||
|
unsigned captureTextureWidth,
|
||||||
|
VideoIOPixelFormat inputPixelFormat,
|
||||||
|
unsigned historyCap)
|
||||||
|
{
|
||||||
|
ReportWrongThreadRenderAccess("render-layer-stack");
|
||||||
|
mRenderPass.Render(
|
||||||
|
hasInputSource,
|
||||||
|
layerStates,
|
||||||
|
inputFrameWidth,
|
||||||
|
inputFrameHeight,
|
||||||
|
captureTextureWidth,
|
||||||
|
inputPixelFormat,
|
||||||
|
historyCap,
|
||||||
|
[this](const RuntimeRenderState& state, OpenGLRenderer::LayerProgram::TextBinding& textBinding, std::string& error) {
|
||||||
|
return mShaderPrograms.UpdateTextBindingTexture(state, textBinding, error);
|
||||||
|
},
|
||||||
|
[this](const RuntimeRenderState& state, unsigned availableSourceHistoryLength, unsigned availableTemporalHistoryLength, bool feedbackAvailable) {
|
||||||
|
return mShaderPrograms.UpdateGlobalParamsBuffer(state, availableSourceHistoryLength, availableTemporalHistoryLength, feedbackAvailable);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
bool RenderEngine::ReadOutputFrameRgbaOnRenderThread(unsigned width, unsigned height, std::vector<unsigned char>& bottomUpPixels)
|
||||||
|
{
|
||||||
|
ReportWrongThreadRenderAccess("read-output-frame-rgba");
|
||||||
|
if (width == 0 || height == 0)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
bottomUpPixels.resize(static_cast<std::size_t>(width) * height * 4);
|
||||||
|
glBindFramebuffer(GL_READ_FRAMEBUFFER, mRenderer.OutputFramebuffer());
|
||||||
|
glReadBuffer(GL_COLOR_ATTACHMENT0);
|
||||||
|
glPixelStorei(GL_PACK_ALIGNMENT, 1);
|
||||||
|
glPixelStorei(GL_PACK_ROW_LENGTH, 0);
|
||||||
|
glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, bottomUpPixels.data());
|
||||||
|
glPixelStorei(GL_PACK_ALIGNMENT, 4);
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool RenderEngine::CaptureOutputFrameRgbaTopDownOnRenderThread(unsigned width, unsigned height, std::vector<unsigned char>& topDownPixels)
|
||||||
|
{
|
||||||
|
std::vector<unsigned char> bottomUpPixels;
|
||||||
|
if (!ReadOutputFrameRgbaOnRenderThread(width, height, bottomUpPixels))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
topDownPixels.resize(bottomUpPixels.size());
|
||||||
|
const std::size_t rowBytes = static_cast<std::size_t>(width) * 4;
|
||||||
|
for (unsigned y = 0; y < height; ++y)
|
||||||
|
{
|
||||||
|
const unsigned sourceY = height - 1 - y;
|
||||||
|
std::copy(
|
||||||
|
bottomUpPixels.begin() + static_cast<std::ptrdiff_t>(sourceY * rowBytes),
|
||||||
|
bottomUpPixels.begin() + static_cast<std::ptrdiff_t>((sourceY + 1) * rowBytes),
|
||||||
|
topDownPixels.begin() + static_cast<std::ptrdiff_t>(y * rowBytes));
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
232
apps/LoopThroughWithOpenGLCompositing/gl/RenderEngine.h
Normal file
232
apps/LoopThroughWithOpenGLCompositing/gl/RenderEngine.h
Normal file
@@ -0,0 +1,232 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "OpenGLRenderPass.h"
|
||||||
|
#include "OpenGLRenderPipeline.h"
|
||||||
|
#include "OpenGLRenderer.h"
|
||||||
|
#include "OpenGLShaderPrograms.h"
|
||||||
|
#include "RenderCommandQueue.h"
|
||||||
|
#include "RenderFrameState.h"
|
||||||
|
#include "RenderFrameStateResolver.h"
|
||||||
|
#include "HealthTelemetry.h"
|
||||||
|
#include "RuntimeCoordinator.h"
|
||||||
|
#include "RuntimeSnapshotProvider.h"
|
||||||
|
|
||||||
|
#include <windows.h>
|
||||||
|
|
||||||
|
#include <atomic>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <chrono>
|
||||||
|
#include <condition_variable>
|
||||||
|
#include <functional>
|
||||||
|
#include <future>
|
||||||
|
#include <memory>
|
||||||
|
#include <mutex>
|
||||||
|
#include <queue>
|
||||||
|
#include <string>
|
||||||
|
#include <thread>
|
||||||
|
#include <utility>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
class RenderEngine
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
using RenderEffectCallback = std::function<void()>;
|
||||||
|
using ScreenshotCallback = std::function<void()>;
|
||||||
|
using ScreenshotCaptureCallback = std::function<void(unsigned, unsigned, std::vector<unsigned char>)>;
|
||||||
|
using PreviewPaintCallback = std::function<void()>;
|
||||||
|
|
||||||
|
struct OscOverlayUpdate
|
||||||
|
{
|
||||||
|
std::string routeKey;
|
||||||
|
std::string layerKey;
|
||||||
|
std::string parameterKey;
|
||||||
|
JsonValue targetValue;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct OscOverlayCommitCompletion
|
||||||
|
{
|
||||||
|
std::string routeKey;
|
||||||
|
uint64_t generation = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct OscOverlayCommitRequest
|
||||||
|
{
|
||||||
|
std::string routeKey;
|
||||||
|
std::string layerKey;
|
||||||
|
std::string parameterKey;
|
||||||
|
JsonValue value;
|
||||||
|
uint64_t generation = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
RenderEngine(
|
||||||
|
RuntimeSnapshotProvider& runtimeSnapshotProvider,
|
||||||
|
HealthTelemetry& healthTelemetry,
|
||||||
|
HDC hdc,
|
||||||
|
HGLRC hglrc,
|
||||||
|
RenderEffectCallback renderEffect,
|
||||||
|
ScreenshotCallback screenshotReady,
|
||||||
|
PreviewPaintCallback previewPaint);
|
||||||
|
~RenderEngine();
|
||||||
|
|
||||||
|
bool StartRenderThread();
|
||||||
|
void StopRenderThread();
|
||||||
|
|
||||||
|
bool CompileDecodeShader(int errorMessageSize, char* errorMessage);
|
||||||
|
bool CompileOutputPackShader(int errorMessageSize, char* errorMessage);
|
||||||
|
bool InitializeResources(
|
||||||
|
unsigned inputFrameWidth,
|
||||||
|
unsigned inputFrameHeight,
|
||||||
|
unsigned captureTextureWidth,
|
||||||
|
unsigned outputFrameWidth,
|
||||||
|
unsigned outputFrameHeight,
|
||||||
|
unsigned outputPackTextureWidth,
|
||||||
|
std::string& error);
|
||||||
|
bool CompileLayerPrograms(unsigned inputFrameWidth, unsigned inputFrameHeight, int errorMessageSize, char* errorMessage);
|
||||||
|
bool ApplyPreparedShaderBuild(
|
||||||
|
const PreparedShaderBuild& preparedBuild,
|
||||||
|
unsigned inputFrameWidth,
|
||||||
|
unsigned inputFrameHeight,
|
||||||
|
bool preserveFeedbackState,
|
||||||
|
int errorMessageSize,
|
||||||
|
char* errorMessage);
|
||||||
|
|
||||||
|
void ResetTemporalHistoryState();
|
||||||
|
void ResetShaderFeedbackState();
|
||||||
|
void ApplyRuntimeCoordinatorRenderReset(RuntimeCoordinatorRenderResetScope resetScope);
|
||||||
|
void ClearOscOverlayState();
|
||||||
|
void ClearOscOverlayStateForLayerKey(const std::string& layerKey);
|
||||||
|
void UpdateOscOverlayState(
|
||||||
|
const std::vector<OscOverlayUpdate>& updates,
|
||||||
|
const std::vector<OscOverlayCommitCompletion>& completedCommits);
|
||||||
|
void ResizeView(int width, int height);
|
||||||
|
bool TryPresentPreview(bool force, unsigned previewFps, unsigned outputFrameWidth, unsigned outputFrameHeight);
|
||||||
|
bool RequestScreenshotCapture(unsigned width, unsigned height, ScreenshotCaptureCallback completion);
|
||||||
|
bool QueueInputFrame(const VideoIOFrame& inputFrame, const VideoIOState& videoState);
|
||||||
|
bool RequestOutputFrame(const RenderPipelineFrameContext& context, VideoIOOutputFrame& outputFrame);
|
||||||
|
bool ResolveRenderFrameState(
|
||||||
|
const RenderFrameInput& input,
|
||||||
|
std::vector<OscOverlayCommitRequest>* commitRequests,
|
||||||
|
RenderFrameState& frameState);
|
||||||
|
void RenderPreparedFrame(const RenderFrameState& frameState);
|
||||||
|
|
||||||
|
private:
|
||||||
|
static constexpr std::chrono::milliseconds kRenderThreadRequestTimeout{ 250 };
|
||||||
|
|
||||||
|
struct RenderThreadTaskState
|
||||||
|
{
|
||||||
|
std::atomic<bool> started = false;
|
||||||
|
std::atomic<bool> cancelled = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
template<typename Func>
|
||||||
|
auto InvokeOnRenderThread(Func&& func) -> decltype(func())
|
||||||
|
{
|
||||||
|
using Result = decltype(func());
|
||||||
|
if (!mRenderThreadRunning || GetCurrentThreadId() == mRenderThreadId)
|
||||||
|
return func();
|
||||||
|
|
||||||
|
auto task = std::make_shared<std::packaged_task<Result()>>(std::forward<Func>(func));
|
||||||
|
std::future<Result> result = task->get_future();
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mRenderThreadMutex);
|
||||||
|
mRenderThreadTasks.push([task]() { (*task)(); });
|
||||||
|
}
|
||||||
|
mRenderThreadCondition.notify_one();
|
||||||
|
return result.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
template<typename Func>
|
||||||
|
bool TryInvokeOnRenderThread(const char* operationName, Func&& func)
|
||||||
|
{
|
||||||
|
if (!mRenderThreadRunning || GetCurrentThreadId() == mRenderThreadId)
|
||||||
|
return func();
|
||||||
|
|
||||||
|
auto state = std::make_shared<RenderThreadTaskState>();
|
||||||
|
auto task = std::make_shared<std::packaged_task<bool()>>(
|
||||||
|
[state, func = std::forward<Func>(func)]() mutable {
|
||||||
|
state->started = true;
|
||||||
|
if (state->cancelled)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
return func();
|
||||||
|
});
|
||||||
|
std::future<bool> result = task->get_future();
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mRenderThreadMutex);
|
||||||
|
if (mRenderThreadStopping)
|
||||||
|
{
|
||||||
|
ReportRenderThreadRequestFailure(operationName, "render thread is stopping");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
mRenderThreadTasks.push([task]() { (*task)(); });
|
||||||
|
}
|
||||||
|
mRenderThreadCondition.notify_one();
|
||||||
|
|
||||||
|
if (result.wait_for(kRenderThreadRequestTimeout) == std::future_status::ready)
|
||||||
|
return result.get();
|
||||||
|
|
||||||
|
if (!state->started)
|
||||||
|
{
|
||||||
|
state->cancelled = true;
|
||||||
|
ReportRenderThreadRequestFailure(operationName, "timed out before execution");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
ReportRenderThreadRequestFailure(operationName, "exceeded timeout while executing; waiting for safe completion");
|
||||||
|
return result.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
void RenderThreadMain(std::promise<bool> ready);
|
||||||
|
void ReportRenderThreadRequestFailure(const char* operationName, const char* reason);
|
||||||
|
bool IsRenderThreadAccessExpected() const;
|
||||||
|
void ReportWrongThreadRenderAccess(const char* operationName) const;
|
||||||
|
bool CommitPreparedLayerPrograms(const PreparedShaderBuild& preparedBuild, unsigned inputFrameWidth, unsigned inputFrameHeight, int errorMessageSize, char* errorMessage);
|
||||||
|
void RenderLayerStack(
|
||||||
|
bool hasInputSource,
|
||||||
|
const std::vector<RuntimeRenderState>& layerStates,
|
||||||
|
unsigned inputFrameWidth,
|
||||||
|
unsigned inputFrameHeight,
|
||||||
|
unsigned captureTextureWidth,
|
||||||
|
VideoIOPixelFormat inputPixelFormat,
|
||||||
|
unsigned historyCap);
|
||||||
|
void ResetTemporalHistoryStateOnRenderThread();
|
||||||
|
void ResetShaderFeedbackStateOnRenderThread();
|
||||||
|
void ApplyRenderResetOnRenderThread(RenderCommandResetScope resetScope);
|
||||||
|
void ProcessRenderResetCommandsOnRenderThread();
|
||||||
|
void EnqueuePreviewPresentWake();
|
||||||
|
void ProcessPreviewPresentCommandsOnRenderThread();
|
||||||
|
void EnqueueInputUploadWake();
|
||||||
|
void ProcessInputUploadCommandsOnRenderThread();
|
||||||
|
void EnqueueScreenshotCaptureWake();
|
||||||
|
void ProcessScreenshotCaptureCommandsOnRenderThread();
|
||||||
|
bool PresentPreviewOnRenderThread(unsigned outputFrameWidth, unsigned outputFrameHeight);
|
||||||
|
bool UploadInputFrameOnRenderThread(const VideoIOFrame& inputFrame, const VideoIOState& videoState);
|
||||||
|
bool RenderOutputFrameOnRenderThread(const RenderPipelineFrameContext& context, VideoIOOutputFrame& outputFrame);
|
||||||
|
bool ReadOutputFrameRgbaOnRenderThread(unsigned width, unsigned height, std::vector<unsigned char>& bottomUpPixels);
|
||||||
|
bool CaptureOutputFrameRgbaTopDownOnRenderThread(unsigned width, unsigned height, std::vector<unsigned char>& topDownPixels);
|
||||||
|
|
||||||
|
OpenGLRenderer mRenderer;
|
||||||
|
OpenGLRenderPass mRenderPass;
|
||||||
|
OpenGLRenderPipeline mRenderPipeline;
|
||||||
|
OpenGLShaderPrograms mShaderPrograms;
|
||||||
|
HealthTelemetry& mHealthTelemetry;
|
||||||
|
HDC mHdc;
|
||||||
|
HGLRC mHglrc;
|
||||||
|
|
||||||
|
std::chrono::steady_clock::time_point mLastPreviewPresentTime;
|
||||||
|
RenderCommandQueue mRenderCommandQueue;
|
||||||
|
RenderFrameStateResolver mFrameStateResolver;
|
||||||
|
RuntimeLiveState mRuntimeLiveState;
|
||||||
|
std::thread mRenderThread;
|
||||||
|
std::atomic<DWORD> mRenderThreadId = 0;
|
||||||
|
std::mutex mRenderThreadMutex;
|
||||||
|
std::condition_variable mRenderThreadCondition;
|
||||||
|
std::queue<std::function<void()>> mRenderThreadTasks;
|
||||||
|
std::atomic<bool> mRenderThreadRunning = false;
|
||||||
|
bool mRenderThreadStopping = false;
|
||||||
|
bool mPreviewPresentWakePending = false;
|
||||||
|
bool mInputUploadWakePending = false;
|
||||||
|
bool mScreenshotCaptureWakePending = false;
|
||||||
|
ScreenshotCaptureCallback mScreenshotCaptureCompletion;
|
||||||
|
bool mResourcesDestroyed = false;
|
||||||
|
};
|
||||||
@@ -1,244 +0,0 @@
|
|||||||
#include "ShaderProgramCompiler.h"
|
|
||||||
|
|
||||||
#include "GlRenderConstants.h"
|
|
||||||
#include "GlScopedObjects.h"
|
|
||||||
#include "GlShaderSources.h"
|
|
||||||
|
|
||||||
#include <cstring>
|
|
||||||
#include <vector>
|
|
||||||
|
|
||||||
namespace
|
|
||||||
{
|
|
||||||
void CopyErrorMessage(const std::string& message, int errorMessageSize, char* errorMessage)
|
|
||||||
{
|
|
||||||
if (!errorMessage || errorMessageSize <= 0)
|
|
||||||
return;
|
|
||||||
|
|
||||||
strncpy_s(errorMessage, errorMessageSize, message.c_str(), _TRUNCATE);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
ShaderProgramCompiler::ShaderProgramCompiler(OpenGLRenderer& renderer, RuntimeHost& runtimeHost, ShaderTextureBindings& textureBindings) :
|
|
||||||
mRenderer(renderer),
|
|
||||||
mRuntimeHost(runtimeHost),
|
|
||||||
mTextureBindings(textureBindings)
|
|
||||||
{
|
|
||||||
}
|
|
||||||
|
|
||||||
bool ShaderProgramCompiler::CompileLayerProgram(const RuntimeRenderState& state, LayerProgram& layerProgram, int errorMessageSize, char* errorMessage)
|
|
||||||
{
|
|
||||||
std::string fragmentShaderSource;
|
|
||||||
std::string loadError;
|
|
||||||
|
|
||||||
if (!mRuntimeHost.BuildLayerFragmentShaderSource(state.layerId, fragmentShaderSource, loadError))
|
|
||||||
{
|
|
||||||
CopyErrorMessage(loadError, errorMessageSize, errorMessage);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return CompilePreparedLayerProgram(state, fragmentShaderSource, layerProgram, errorMessageSize, errorMessage);
|
|
||||||
}
|
|
||||||
|
|
||||||
bool ShaderProgramCompiler::CompilePreparedLayerProgram(const RuntimeRenderState& state, const std::string& fragmentShaderSource, LayerProgram& layerProgram, int errorMessageSize, char* errorMessage)
|
|
||||||
{
|
|
||||||
GLsizei errorBufferSize = 0;
|
|
||||||
GLint compileResult = GL_FALSE;
|
|
||||||
GLint linkResult = GL_FALSE;
|
|
||||||
std::string loadError;
|
|
||||||
std::vector<LayerProgram::TextureBinding> textureBindings;
|
|
||||||
const char* vertexSource = kFullscreenTriangleVertexShaderSource;
|
|
||||||
const char* fragmentSource = fragmentShaderSource.c_str();
|
|
||||||
|
|
||||||
ScopedGlShader newVertexShader(glCreateShader(GL_VERTEX_SHADER));
|
|
||||||
glShaderSource(newVertexShader.get(), 1, (const GLchar**)&vertexSource, NULL);
|
|
||||||
glCompileShader(newVertexShader.get());
|
|
||||||
glGetShaderiv(newVertexShader.get(), GL_COMPILE_STATUS, &compileResult);
|
|
||||||
if (compileResult == GL_FALSE)
|
|
||||||
{
|
|
||||||
glGetShaderInfoLog(newVertexShader.get(), errorMessageSize, &errorBufferSize, errorMessage);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
ScopedGlShader newFragmentShader(glCreateShader(GL_FRAGMENT_SHADER));
|
|
||||||
glShaderSource(newFragmentShader.get(), 1, (const GLchar**)&fragmentSource, NULL);
|
|
||||||
glCompileShader(newFragmentShader.get());
|
|
||||||
glGetShaderiv(newFragmentShader.get(), GL_COMPILE_STATUS, &compileResult);
|
|
||||||
if (compileResult == GL_FALSE)
|
|
||||||
{
|
|
||||||
glGetShaderInfoLog(newFragmentShader.get(), errorMessageSize, &errorBufferSize, errorMessage);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
ScopedGlProgram newProgram(glCreateProgram());
|
|
||||||
glAttachShader(newProgram.get(), newVertexShader.get());
|
|
||||||
glAttachShader(newProgram.get(), newFragmentShader.get());
|
|
||||||
glLinkProgram(newProgram.get());
|
|
||||||
glGetProgramiv(newProgram.get(), GL_LINK_STATUS, &linkResult);
|
|
||||||
if (linkResult == GL_FALSE)
|
|
||||||
{
|
|
||||||
glGetProgramInfoLog(newProgram.get(), errorMessageSize, &errorBufferSize, errorMessage);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const ShaderTextureAsset& textureAsset : state.textureAssets)
|
|
||||||
{
|
|
||||||
LayerProgram::TextureBinding textureBinding;
|
|
||||||
textureBinding.samplerName = textureAsset.id;
|
|
||||||
textureBinding.sourcePath = textureAsset.path;
|
|
||||||
if (!mTextureBindings.LoadTextureAsset(textureAsset, textureBinding.texture, loadError))
|
|
||||||
{
|
|
||||||
for (LayerProgram::TextureBinding& loadedTexture : textureBindings)
|
|
||||||
{
|
|
||||||
if (loadedTexture.texture != 0)
|
|
||||||
glDeleteTextures(1, &loadedTexture.texture);
|
|
||||||
}
|
|
||||||
CopyErrorMessage(loadError, errorMessageSize, errorMessage);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
textureBindings.push_back(textureBinding);
|
|
||||||
}
|
|
||||||
|
|
||||||
std::vector<LayerProgram::TextBinding> textBindings;
|
|
||||||
mTextureBindings.CreateTextBindings(state, textBindings);
|
|
||||||
|
|
||||||
const GLuint globalParamsIndex = glGetUniformBlockIndex(newProgram.get(), "GlobalParams");
|
|
||||||
if (globalParamsIndex != GL_INVALID_INDEX)
|
|
||||||
glUniformBlockBinding(newProgram.get(), globalParamsIndex, kGlobalParamsBindingPoint);
|
|
||||||
|
|
||||||
const unsigned historyCap = mRuntimeHost.GetMaxTemporalHistoryFrames();
|
|
||||||
const GLuint shaderTextureBase = state.isTemporal ? kSourceHistoryTextureUnitBase + historyCap + historyCap : kSourceHistoryTextureUnitBase;
|
|
||||||
glUseProgram(newProgram.get());
|
|
||||||
const GLint videoInputLocation = glGetUniformLocation(newProgram.get(), "gVideoInput");
|
|
||||||
if (videoInputLocation >= 0)
|
|
||||||
glUniform1i(videoInputLocation, static_cast<GLint>(kDecodedVideoTextureUnit));
|
|
||||||
for (unsigned index = 0; index < historyCap; ++index)
|
|
||||||
{
|
|
||||||
const std::string sourceSamplerName = "gSourceHistory" + std::to_string(index);
|
|
||||||
const GLint sourceSamplerLocation = glGetUniformLocation(newProgram.get(), sourceSamplerName.c_str());
|
|
||||||
if (sourceSamplerLocation >= 0)
|
|
||||||
glUniform1i(sourceSamplerLocation, static_cast<GLint>(kSourceHistoryTextureUnitBase + index));
|
|
||||||
|
|
||||||
const std::string temporalSamplerName = "gTemporalHistory" + std::to_string(index);
|
|
||||||
const GLint temporalSamplerLocation = glGetUniformLocation(newProgram.get(), temporalSamplerName.c_str());
|
|
||||||
if (temporalSamplerLocation >= 0)
|
|
||||||
glUniform1i(temporalSamplerLocation, static_cast<GLint>(kSourceHistoryTextureUnitBase + historyCap + index));
|
|
||||||
}
|
|
||||||
for (std::size_t index = 0; index < textureBindings.size(); ++index)
|
|
||||||
{
|
|
||||||
const GLint textureSamplerLocation = mTextureBindings.FindSamplerUniformLocation(newProgram.get(), textureBindings[index].samplerName);
|
|
||||||
if (textureSamplerLocation >= 0)
|
|
||||||
glUniform1i(textureSamplerLocation, static_cast<GLint>(shaderTextureBase + static_cast<GLuint>(index)));
|
|
||||||
}
|
|
||||||
const GLuint textTextureBase = shaderTextureBase + static_cast<GLuint>(textureBindings.size());
|
|
||||||
for (std::size_t index = 0; index < textBindings.size(); ++index)
|
|
||||||
{
|
|
||||||
const GLint textSamplerLocation = mTextureBindings.FindSamplerUniformLocation(newProgram.get(), textBindings[index].samplerName);
|
|
||||||
if (textSamplerLocation >= 0)
|
|
||||||
glUniform1i(textSamplerLocation, static_cast<GLint>(textTextureBase + static_cast<GLuint>(index)));
|
|
||||||
}
|
|
||||||
glUseProgram(0);
|
|
||||||
|
|
||||||
layerProgram.layerId = state.layerId;
|
|
||||||
layerProgram.shaderId = state.shaderId;
|
|
||||||
layerProgram.shaderTextureBase = shaderTextureBase;
|
|
||||||
layerProgram.program = newProgram.release();
|
|
||||||
layerProgram.vertexShader = newVertexShader.release();
|
|
||||||
layerProgram.fragmentShader = newFragmentShader.release();
|
|
||||||
layerProgram.textureBindings.swap(textureBindings);
|
|
||||||
layerProgram.textBindings.swap(textBindings);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool ShaderProgramCompiler::CompileDecodeShader(int errorMessageSize, char* errorMessage)
|
|
||||||
{
|
|
||||||
GLsizei errorBufferSize = 0;
|
|
||||||
GLint compileResult = GL_FALSE;
|
|
||||||
GLint linkResult = GL_FALSE;
|
|
||||||
const char* vertexSource = kFullscreenTriangleVertexShaderSource;
|
|
||||||
const char* fragmentSource = kDecodeFragmentShaderSource;
|
|
||||||
|
|
||||||
ScopedGlShader newVertexShader(glCreateShader(GL_VERTEX_SHADER));
|
|
||||||
glShaderSource(newVertexShader.get(), 1, (const GLchar**)&vertexSource, NULL);
|
|
||||||
glCompileShader(newVertexShader.get());
|
|
||||||
glGetShaderiv(newVertexShader.get(), GL_COMPILE_STATUS, &compileResult);
|
|
||||||
if (compileResult == GL_FALSE)
|
|
||||||
{
|
|
||||||
glGetShaderInfoLog(newVertexShader.get(), errorMessageSize, &errorBufferSize, errorMessage);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
ScopedGlShader newFragmentShader(glCreateShader(GL_FRAGMENT_SHADER));
|
|
||||||
glShaderSource(newFragmentShader.get(), 1, (const GLchar**)&fragmentSource, NULL);
|
|
||||||
glCompileShader(newFragmentShader.get());
|
|
||||||
glGetShaderiv(newFragmentShader.get(), GL_COMPILE_STATUS, &compileResult);
|
|
||||||
if (compileResult == GL_FALSE)
|
|
||||||
{
|
|
||||||
glGetShaderInfoLog(newFragmentShader.get(), errorMessageSize, &errorBufferSize, errorMessage);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
ScopedGlProgram newProgram(glCreateProgram());
|
|
||||||
glAttachShader(newProgram.get(), newVertexShader.get());
|
|
||||||
glAttachShader(newProgram.get(), newFragmentShader.get());
|
|
||||||
glLinkProgram(newProgram.get());
|
|
||||||
glGetProgramiv(newProgram.get(), GL_LINK_STATUS, &linkResult);
|
|
||||||
if (linkResult == GL_FALSE)
|
|
||||||
{
|
|
||||||
glGetProgramInfoLog(newProgram.get(), errorMessageSize, &errorBufferSize, errorMessage);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
mRenderer.DestroyDecodeShaderProgram();
|
|
||||||
mRenderer.SetDecodeShaderProgram(newProgram.release(), newVertexShader.release(), newFragmentShader.release());
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool ShaderProgramCompiler::CompileOutputPackShader(int errorMessageSize, char* errorMessage)
|
|
||||||
{
|
|
||||||
GLsizei errorBufferSize = 0;
|
|
||||||
GLint compileResult = GL_FALSE;
|
|
||||||
GLint linkResult = GL_FALSE;
|
|
||||||
const char* vertexSource = kFullscreenTriangleVertexShaderSource;
|
|
||||||
const char* fragmentSource = kOutputPackFragmentShaderSource;
|
|
||||||
|
|
||||||
ScopedGlShader newVertexShader(glCreateShader(GL_VERTEX_SHADER));
|
|
||||||
glShaderSource(newVertexShader.get(), 1, (const GLchar**)&vertexSource, NULL);
|
|
||||||
glCompileShader(newVertexShader.get());
|
|
||||||
glGetShaderiv(newVertexShader.get(), GL_COMPILE_STATUS, &compileResult);
|
|
||||||
if (compileResult == GL_FALSE)
|
|
||||||
{
|
|
||||||
glGetShaderInfoLog(newVertexShader.get(), errorMessageSize, &errorBufferSize, errorMessage);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
ScopedGlShader newFragmentShader(glCreateShader(GL_FRAGMENT_SHADER));
|
|
||||||
glShaderSource(newFragmentShader.get(), 1, (const GLchar**)&fragmentSource, NULL);
|
|
||||||
glCompileShader(newFragmentShader.get());
|
|
||||||
glGetShaderiv(newFragmentShader.get(), GL_COMPILE_STATUS, &compileResult);
|
|
||||||
if (compileResult == GL_FALSE)
|
|
||||||
{
|
|
||||||
glGetShaderInfoLog(newFragmentShader.get(), errorMessageSize, &errorBufferSize, errorMessage);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
ScopedGlProgram newProgram(glCreateProgram());
|
|
||||||
glAttachShader(newProgram.get(), newVertexShader.get());
|
|
||||||
glAttachShader(newProgram.get(), newFragmentShader.get());
|
|
||||||
glLinkProgram(newProgram.get());
|
|
||||||
glGetProgramiv(newProgram.get(), GL_LINK_STATUS, &linkResult);
|
|
||||||
if (linkResult == GL_FALSE)
|
|
||||||
{
|
|
||||||
glGetProgramInfoLog(newProgram.get(), errorMessageSize, &errorBufferSize, errorMessage);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
glUseProgram(newProgram.get());
|
|
||||||
const GLint outputSamplerLocation = glGetUniformLocation(newProgram.get(), "uOutputRgb");
|
|
||||||
if (outputSamplerLocation >= 0)
|
|
||||||
glUniform1i(outputSamplerLocation, 0);
|
|
||||||
glUseProgram(0);
|
|
||||||
|
|
||||||
mRenderer.DestroyOutputPackShaderProgram();
|
|
||||||
mRenderer.SetOutputPackShaderProgram(newProgram.release(), newVertexShader.release(), newFragmentShader.release());
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
@@ -1,104 +0,0 @@
|
|||||||
#include "ShaderTextureBindings.h"
|
|
||||||
|
|
||||||
#include "GlRenderConstants.h"
|
|
||||||
#include "TextRasterizer.h"
|
|
||||||
#include "TextureAssetLoader.h"
|
|
||||||
|
|
||||||
#include <algorithm>
|
|
||||||
#include <filesystem>
|
|
||||||
|
|
||||||
namespace
|
|
||||||
{
|
|
||||||
std::string TextValueForBinding(const RuntimeRenderState& state, const std::string& parameterId)
|
|
||||||
{
|
|
||||||
auto valueIt = state.parameterValues.find(parameterId);
|
|
||||||
return valueIt == state.parameterValues.end() ? std::string() : valueIt->second.textValue;
|
|
||||||
}
|
|
||||||
|
|
||||||
const ShaderFontAsset* FindFontAssetForParameter(const RuntimeRenderState& state, const ShaderParameterDefinition& definition)
|
|
||||||
{
|
|
||||||
if (!definition.fontId.empty())
|
|
||||||
{
|
|
||||||
for (const ShaderFontAsset& fontAsset : state.fontAssets)
|
|
||||||
{
|
|
||||||
if (fontAsset.id == definition.fontId)
|
|
||||||
return &fontAsset;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return state.fontAssets.empty() ? nullptr : &state.fontAssets.front();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
bool ShaderTextureBindings::LoadTextureAsset(const ShaderTextureAsset& textureAsset, GLuint& textureId, std::string& error)
|
|
||||||
{
|
|
||||||
return ::LoadTextureAsset(textureAsset, textureId, error);
|
|
||||||
}
|
|
||||||
|
|
||||||
void ShaderTextureBindings::CreateTextBindings(const RuntimeRenderState& state, std::vector<LayerProgram::TextBinding>& textBindings)
|
|
||||||
{
|
|
||||||
for (const ShaderParameterDefinition& definition : state.parameterDefinitions)
|
|
||||||
{
|
|
||||||
if (definition.type != ShaderParameterType::Text)
|
|
||||||
continue;
|
|
||||||
LayerProgram::TextBinding textBinding;
|
|
||||||
textBinding.parameterId = definition.id;
|
|
||||||
textBinding.samplerName = definition.id + "Texture";
|
|
||||||
textBinding.fontId = definition.fontId;
|
|
||||||
glGenTextures(1, &textBinding.texture);
|
|
||||||
glBindTexture(GL_TEXTURE_2D, textBinding.texture);
|
|
||||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
|
|
||||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
|
|
||||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
|
|
||||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
|
|
||||||
std::vector<unsigned char> empty(static_cast<std::size_t>(kTextTextureWidth) * kTextTextureHeight * 4, 0);
|
|
||||||
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, kTextTextureWidth, kTextTextureHeight, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, empty.data());
|
|
||||||
glBindTexture(GL_TEXTURE_2D, 0);
|
|
||||||
textBindings.push_back(textBinding);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
bool ShaderTextureBindings::UpdateTextBindingTexture(const RuntimeRenderState& state, LayerProgram::TextBinding& textBinding, std::string& error)
|
|
||||||
{
|
|
||||||
const std::string text = TextValueForBinding(state, textBinding.parameterId);
|
|
||||||
if (text == textBinding.renderedText && textBinding.renderedWidth == kTextTextureWidth && textBinding.renderedHeight == kTextTextureHeight)
|
|
||||||
return true;
|
|
||||||
|
|
||||||
auto definitionIt = std::find_if(state.parameterDefinitions.begin(), state.parameterDefinitions.end(),
|
|
||||||
[&textBinding](const ShaderParameterDefinition& definition) { return definition.id == textBinding.parameterId; });
|
|
||||||
if (definitionIt == state.parameterDefinitions.end())
|
|
||||||
return true;
|
|
||||||
|
|
||||||
const ShaderFontAsset* fontAsset = FindFontAssetForParameter(state, *definitionIt);
|
|
||||||
std::filesystem::path fontPath;
|
|
||||||
if (fontAsset)
|
|
||||||
fontPath = fontAsset->path;
|
|
||||||
|
|
||||||
std::vector<unsigned char> sdf;
|
|
||||||
if (!RasterizeTextSdf(text, fontPath, sdf, error))
|
|
||||||
return false;
|
|
||||||
|
|
||||||
GLint previousActiveTexture = 0;
|
|
||||||
GLint previousUnpackBuffer = 0;
|
|
||||||
glGetIntegerv(GL_ACTIVE_TEXTURE, &previousActiveTexture);
|
|
||||||
glGetIntegerv(GL_PIXEL_UNPACK_BUFFER_BINDING, &previousUnpackBuffer);
|
|
||||||
glActiveTexture(GL_TEXTURE0);
|
|
||||||
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
|
|
||||||
glBindTexture(GL_TEXTURE_2D, textBinding.texture);
|
|
||||||
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, kTextTextureWidth, kTextTextureHeight, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, sdf.data());
|
|
||||||
glBindTexture(GL_TEXTURE_2D, 0);
|
|
||||||
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, static_cast<GLuint>(previousUnpackBuffer));
|
|
||||||
glActiveTexture(static_cast<GLenum>(previousActiveTexture));
|
|
||||||
|
|
||||||
textBinding.renderedText = text;
|
|
||||||
textBinding.renderedWidth = kTextTextureWidth;
|
|
||||||
textBinding.renderedHeight = kTextTextureHeight;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
GLint ShaderTextureBindings::FindSamplerUniformLocation(GLuint program, const std::string& samplerName) const
|
|
||||||
{
|
|
||||||
GLint location = glGetUniformLocation(program, samplerName.c_str());
|
|
||||||
if (location >= 0)
|
|
||||||
return location;
|
|
||||||
return glGetUniformLocation(program, (samplerName + "_0").c_str());
|
|
||||||
}
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
|
|
||||||
#include "OpenGLRenderer.h"
|
|
||||||
#include "ShaderTypes.h"
|
|
||||||
|
|
||||||
#include <string>
|
|
||||||
#include <vector>
|
|
||||||
|
|
||||||
class ShaderTextureBindings
|
|
||||||
{
|
|
||||||
public:
|
|
||||||
using LayerProgram = OpenGLRenderer::LayerProgram;
|
|
||||||
|
|
||||||
bool LoadTextureAsset(const ShaderTextureAsset& textureAsset, GLuint& textureId, std::string& error);
|
|
||||||
void CreateTextBindings(const RuntimeRenderState& state, std::vector<LayerProgram::TextBinding>& textBindings);
|
|
||||||
bool UpdateTextBindingTexture(const RuntimeRenderState& state, LayerProgram::TextBinding& textBinding, std::string& error);
|
|
||||||
GLint FindSamplerUniformLocation(GLuint program, const std::string& samplerName) const;
|
|
||||||
};
|
|
||||||
@@ -0,0 +1,428 @@
|
|||||||
|
#include "DeckLinkDisplayMode.h"
|
||||||
|
#include "OpenGLComposite.h"
|
||||||
|
#include "GLExtensions.h"
|
||||||
|
#include "PngScreenshotWriter.h"
|
||||||
|
#include "RenderEngine.h"
|
||||||
|
#include "RuntimeCoordinator.h"
|
||||||
|
#include "RuntimeEventDispatcher.h"
|
||||||
|
#include "RuntimeServiceLiveBridge.h"
|
||||||
|
#include "RuntimeServices.h"
|
||||||
|
#include "RuntimeSnapshotProvider.h"
|
||||||
|
#include "RuntimeStore.h"
|
||||||
|
#include "RuntimeUpdateController.h"
|
||||||
|
#include "ShaderBuildQueue.h"
|
||||||
|
#include "VideoBackend.h"
|
||||||
|
|
||||||
|
#include <chrono>
|
||||||
|
#include <ctime>
|
||||||
|
#include <filesystem>
|
||||||
|
#include <iomanip>
|
||||||
|
#include <memory>
|
||||||
|
#include <sstream>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
OpenGLComposite::OpenGLComposite(HWND hWnd, HDC hDC, HGLRC hRC) :
|
||||||
|
hGLWnd(hWnd), hGLDC(hDC), hGLRC(hRC)
|
||||||
|
{
|
||||||
|
mRuntimeStore = std::make_unique<RuntimeStore>();
|
||||||
|
mRuntimeEventDispatcher = std::make_unique<RuntimeEventDispatcher>();
|
||||||
|
mRuntimeSnapshotProvider = std::make_unique<RuntimeSnapshotProvider>(mRuntimeStore->GetRenderSnapshotBuilder(), *mRuntimeEventDispatcher);
|
||||||
|
mRuntimeCoordinator = std::make_unique<RuntimeCoordinator>(*mRuntimeStore, *mRuntimeEventDispatcher);
|
||||||
|
mRenderEngine = std::make_unique<RenderEngine>(
|
||||||
|
*mRuntimeSnapshotProvider,
|
||||||
|
mRuntimeStore->GetHealthTelemetry(),
|
||||||
|
hGLDC,
|
||||||
|
hGLRC,
|
||||||
|
[this]() { renderEffect(); },
|
||||||
|
[]() {},
|
||||||
|
[this]() { paintGL(false); });
|
||||||
|
mVideoBackend = std::make_unique<VideoBackend>(*mRenderEngine, mRuntimeStore->GetHealthTelemetry(), *mRuntimeEventDispatcher);
|
||||||
|
mShaderBuildQueue = std::make_unique<ShaderBuildQueue>(*mRuntimeSnapshotProvider, *mRuntimeEventDispatcher);
|
||||||
|
mRuntimeServices = std::make_unique<RuntimeServices>(*mRuntimeEventDispatcher);
|
||||||
|
mRuntimeUpdateController = std::make_unique<RuntimeUpdateController>(
|
||||||
|
*mRuntimeStore,
|
||||||
|
*mRuntimeCoordinator,
|
||||||
|
*mRuntimeEventDispatcher,
|
||||||
|
*mRuntimeServices,
|
||||||
|
*mRenderEngine,
|
||||||
|
*mShaderBuildQueue,
|
||||||
|
*mVideoBackend);
|
||||||
|
}
|
||||||
|
|
||||||
|
OpenGLComposite::~OpenGLComposite()
|
||||||
|
{
|
||||||
|
if (mRuntimeServices)
|
||||||
|
mRuntimeServices->Stop();
|
||||||
|
if (mShaderBuildQueue)
|
||||||
|
mShaderBuildQueue->Stop();
|
||||||
|
if (mVideoBackend)
|
||||||
|
mVideoBackend->ReleaseResources();
|
||||||
|
if (mRuntimeStore)
|
||||||
|
{
|
||||||
|
std::string persistenceError;
|
||||||
|
if (!mRuntimeStore->FlushPersistenceForShutdown(std::chrono::seconds(2), persistenceError))
|
||||||
|
OutputDebugStringA((std::string("Persistence shutdown flush failed: ") + persistenceError + "\n").c_str());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool OpenGLComposite::InitDeckLink()
|
||||||
|
{
|
||||||
|
return InitVideoIO();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool OpenGLComposite::InitVideoIO()
|
||||||
|
{
|
||||||
|
VideoFormatSelection videoModes;
|
||||||
|
std::string initFailureReason;
|
||||||
|
|
||||||
|
if (mRuntimeStore && mRuntimeStore->GetRuntimeRepositoryRoot().empty())
|
||||||
|
{
|
||||||
|
std::string runtimeError;
|
||||||
|
if (!mRuntimeStore->InitializeStore(runtimeError))
|
||||||
|
{
|
||||||
|
MessageBoxA(NULL, runtimeError.c_str(), "Runtime host failed to initialize", MB_OK);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mRuntimeStore)
|
||||||
|
{
|
||||||
|
if (!ResolveConfiguredVideoFormats(
|
||||||
|
mRuntimeStore->GetConfiguredInputVideoFormat(),
|
||||||
|
mRuntimeStore->GetConfiguredInputFrameRate(),
|
||||||
|
mRuntimeStore->GetConfiguredOutputVideoFormat(),
|
||||||
|
mRuntimeStore->GetConfiguredOutputFrameRate(),
|
||||||
|
videoModes,
|
||||||
|
initFailureReason))
|
||||||
|
{
|
||||||
|
MessageBoxA(NULL, initFailureReason.c_str(), "DeckLink mode configuration error", MB_OK);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!mVideoBackend->DiscoverDevicesAndModes(videoModes, initFailureReason))
|
||||||
|
{
|
||||||
|
const char* title = initFailureReason == "Please install the Blackmagic DeckLink drivers to use the features of this application."
|
||||||
|
? "This application requires the DeckLink drivers installed."
|
||||||
|
: "DeckLink initialization failed";
|
||||||
|
MessageBoxA(NULL, initFailureReason.c_str(), title, MB_OK | MB_ICONERROR);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const bool outputAlphaRequired = mRuntimeStore && mRuntimeStore->IsExternalKeyingConfigured();
|
||||||
|
if (!mVideoBackend->SelectPreferredFormats(videoModes, outputAlphaRequired, initFailureReason))
|
||||||
|
goto error;
|
||||||
|
|
||||||
|
if (! CheckOpenGLExtensions())
|
||||||
|
{
|
||||||
|
initFailureReason = "OpenGL extension checks failed.";
|
||||||
|
goto error;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! InitOpenGLState())
|
||||||
|
{
|
||||||
|
initFailureReason = "OpenGL state initialization failed.";
|
||||||
|
goto error;
|
||||||
|
}
|
||||||
|
|
||||||
|
mVideoBackend->PublishStatus(
|
||||||
|
mRuntimeStore && mRuntimeStore->IsExternalKeyingConfigured(),
|
||||||
|
mVideoBackend->OutputModelName().empty()
|
||||||
|
? "DeckLink output device selected."
|
||||||
|
: ("Selected output device: " + mVideoBackend->OutputModelName()));
|
||||||
|
|
||||||
|
// Resize window to match output video frame, but scale large formats down by half for viewing.
|
||||||
|
if (mVideoBackend->OutputFrameWidth() < 1920)
|
||||||
|
resizeWindow(mVideoBackend->OutputFrameWidth(), mVideoBackend->OutputFrameHeight());
|
||||||
|
else
|
||||||
|
resizeWindow(mVideoBackend->OutputFrameWidth() / 2, mVideoBackend->OutputFrameHeight() / 2);
|
||||||
|
|
||||||
|
if (!mVideoBackend->ConfigureInput(videoModes.input, initFailureReason))
|
||||||
|
{
|
||||||
|
goto error;
|
||||||
|
}
|
||||||
|
if (!mVideoBackend->HasInputDevice())
|
||||||
|
mVideoBackend->ReportNoInputDeviceSignalStatus();
|
||||||
|
|
||||||
|
if (!mVideoBackend->ConfigureOutput(videoModes.output, mRuntimeStore && mRuntimeStore->IsExternalKeyingConfigured(), initFailureReason))
|
||||||
|
{
|
||||||
|
goto error;
|
||||||
|
}
|
||||||
|
|
||||||
|
mVideoBackend->PublishStatus(
|
||||||
|
mRuntimeStore && mRuntimeStore->IsExternalKeyingConfigured(),
|
||||||
|
mVideoBackend->StatusMessage());
|
||||||
|
|
||||||
|
return true;
|
||||||
|
|
||||||
|
error:
|
||||||
|
if (!initFailureReason.empty())
|
||||||
|
MessageBoxA(NULL, initFailureReason.c_str(), "DeckLink initialization failed", MB_OK | MB_ICONERROR);
|
||||||
|
mVideoBackend->ReleaseResources();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
void OpenGLComposite::paintGL(bool force)
|
||||||
|
{
|
||||||
|
if (mRuntimeUpdateController)
|
||||||
|
mRuntimeUpdateController->ProcessRuntimeWork();
|
||||||
|
|
||||||
|
if (!force)
|
||||||
|
{
|
||||||
|
if (IsIconic(hGLWnd))
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const unsigned previewFps = mRuntimeStore ? mRuntimeStore->GetConfiguredPreviewFps() : 30u;
|
||||||
|
if (!force && mVideoBackend && mVideoBackend->ShouldPrioritizeOutputOverPreview())
|
||||||
|
{
|
||||||
|
ValidateRect(hGLWnd, NULL);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!mRenderEngine->TryPresentPreview(force, previewFps, mVideoBackend->OutputFrameWidth(), mVideoBackend->OutputFrameHeight()))
|
||||||
|
{
|
||||||
|
ValidateRect(hGLWnd, NULL);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
ValidateRect(hGLWnd, NULL);
|
||||||
|
}
|
||||||
|
|
||||||
|
void OpenGLComposite::resizeGL(WORD width, WORD height)
|
||||||
|
{
|
||||||
|
// We don't set the project or model matrices here since the window data is copied directly from
|
||||||
|
// an off-screen FBO in paintGL(). Just save the width and height for use in paintGL().
|
||||||
|
mRenderEngine->ResizeView(width, height);
|
||||||
|
}
|
||||||
|
|
||||||
|
void OpenGLComposite::resizeWindow(int width, int height)
|
||||||
|
{
|
||||||
|
RECT r;
|
||||||
|
if (GetWindowRect(hGLWnd, &r))
|
||||||
|
{
|
||||||
|
SetWindowPos(hGLWnd, HWND_TOP, r.left, r.top, r.left + width, r.top + height, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool OpenGLComposite::InitOpenGLState()
|
||||||
|
{
|
||||||
|
if (! ResolveGLExtensions())
|
||||||
|
return false;
|
||||||
|
|
||||||
|
std::string runtimeError;
|
||||||
|
if (mRuntimeStore->GetRuntimeRepositoryRoot().empty() && !mRuntimeStore->InitializeStore(runtimeError))
|
||||||
|
{
|
||||||
|
MessageBoxA(NULL, runtimeError.c_str(), "Runtime host failed to initialize", MB_OK);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!mRuntimeServices->Start(*this, *mRuntimeStore, runtimeError))
|
||||||
|
{
|
||||||
|
MessageBoxA(NULL, runtimeError.c_str(), "Runtime control services failed to start", MB_OK);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Prepare the runtime shader program generated from the active shader package.
|
||||||
|
char compilerErrorMessage[1024];
|
||||||
|
if (!mRenderEngine->CompileDecodeShader(sizeof(compilerErrorMessage), compilerErrorMessage))
|
||||||
|
{
|
||||||
|
MessageBoxA(NULL, compilerErrorMessage, "OpenGL decode shader failed to load or compile", MB_OK);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (!mRenderEngine->CompileOutputPackShader(sizeof(compilerErrorMessage), compilerErrorMessage))
|
||||||
|
{
|
||||||
|
MessageBoxA(NULL, compilerErrorMessage, "OpenGL output pack shader failed to load or compile", MB_OK);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string rendererError;
|
||||||
|
if (!mRenderEngine->InitializeResources(
|
||||||
|
mVideoBackend->InputFrameWidth(),
|
||||||
|
mVideoBackend->InputFrameHeight(),
|
||||||
|
mVideoBackend->CaptureTextureWidth(),
|
||||||
|
mVideoBackend->OutputFrameWidth(),
|
||||||
|
mVideoBackend->OutputFrameHeight(),
|
||||||
|
mVideoBackend->OutputPackTextureWidth(),
|
||||||
|
rendererError))
|
||||||
|
{
|
||||||
|
MessageBoxA(NULL, rendererError.c_str(), "OpenGL initialization error.", MB_OK);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!mRenderEngine->CompileLayerPrograms(mVideoBackend->InputFrameWidth(), mVideoBackend->InputFrameHeight(), sizeof(compilerErrorMessage), compilerErrorMessage))
|
||||||
|
{
|
||||||
|
MessageBoxA(NULL, compilerErrorMessage, "OpenGL shader failed to load or compile", MB_OK);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
mRuntimeStore->SetCompileStatus(true, "Shader layers compiled successfully.");
|
||||||
|
|
||||||
|
mRenderEngine->ResetTemporalHistoryState();
|
||||||
|
mRenderEngine->ResetShaderFeedbackState();
|
||||||
|
|
||||||
|
mRuntimeUpdateController->BroadcastRuntimeState();
|
||||||
|
mRuntimeServices->BeginPolling(*mRuntimeCoordinator);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool OpenGLComposite::Start()
|
||||||
|
{
|
||||||
|
if (!mRenderEngine->StartRenderThread())
|
||||||
|
return false;
|
||||||
|
|
||||||
|
if (mRuntimeUpdateController)
|
||||||
|
mRuntimeUpdateController->ProcessRuntimeWork();
|
||||||
|
|
||||||
|
if (mVideoBackend->Start())
|
||||||
|
return true;
|
||||||
|
|
||||||
|
mRenderEngine->StopRenderThread();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool OpenGLComposite::Stop()
|
||||||
|
{
|
||||||
|
if (mRuntimeServices)
|
||||||
|
mRuntimeServices->Stop();
|
||||||
|
|
||||||
|
const bool wasExternalKeyingActive = mVideoBackend->ExternalKeyingActive();
|
||||||
|
mVideoBackend->Stop();
|
||||||
|
if (wasExternalKeyingActive)
|
||||||
|
mVideoBackend->PublishStatus(
|
||||||
|
mRuntimeStore && mRuntimeStore->IsExternalKeyingConfigured(),
|
||||||
|
"External keying has been disabled.");
|
||||||
|
|
||||||
|
if (mRenderEngine)
|
||||||
|
mRenderEngine->StopRenderThread();
|
||||||
|
|
||||||
|
if (mRuntimeStore)
|
||||||
|
{
|
||||||
|
std::string persistenceError;
|
||||||
|
if (!mRuntimeStore->FlushPersistenceForShutdown(std::chrono::seconds(2), persistenceError))
|
||||||
|
OutputDebugStringA((std::string("Persistence shutdown flush failed: ") + persistenceError + "\n").c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool OpenGLComposite::ReloadShader(bool preserveFeedbackState)
|
||||||
|
{
|
||||||
|
return mRuntimeCoordinator &&
|
||||||
|
mRuntimeUpdateController &&
|
||||||
|
mRuntimeUpdateController->ApplyRuntimeCoordinatorResult(mRuntimeCoordinator->RequestShaderReload(preserveFeedbackState));
|
||||||
|
}
|
||||||
|
|
||||||
|
bool OpenGLComposite::RequestScreenshot(std::string& error)
|
||||||
|
{
|
||||||
|
if (!mRenderEngine || !mVideoBackend)
|
||||||
|
{
|
||||||
|
error = "The render engine is not ready.";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const unsigned width = mVideoBackend->OutputFrameWidth();
|
||||||
|
const unsigned height = mVideoBackend->OutputFrameHeight();
|
||||||
|
if (width == 0 || height == 0)
|
||||||
|
{
|
||||||
|
error = "The output frame size is not available.";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::filesystem::path outputPath;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
outputPath = BuildScreenshotPath();
|
||||||
|
std::filesystem::create_directories(outputPath.parent_path());
|
||||||
|
}
|
||||||
|
catch (const std::exception& exception)
|
||||||
|
{
|
||||||
|
error = exception.what();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!mRenderEngine->RequestScreenshotCapture(
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
[outputPath](unsigned captureWidth, unsigned captureHeight, std::vector<unsigned char> topDownPixels) {
|
||||||
|
try
|
||||||
|
{
|
||||||
|
WritePngFileAsync(outputPath, captureWidth, captureHeight, std::move(topDownPixels));
|
||||||
|
}
|
||||||
|
catch (const std::exception& exception)
|
||||||
|
{
|
||||||
|
OutputDebugStringA((std::string("Screenshot request failed: ") + exception.what() + "\n").c_str());
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
{
|
||||||
|
error = "Screenshot capture request failed.";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void OpenGLComposite::renderEffect()
|
||||||
|
{
|
||||||
|
const RenderFrameInput frameInput = BuildRenderFrameInput();
|
||||||
|
RenderFrame(frameInput);
|
||||||
|
}
|
||||||
|
|
||||||
|
RenderFrameInput OpenGLComposite::BuildRenderFrameInput() const
|
||||||
|
{
|
||||||
|
RenderFrameInput frameInput;
|
||||||
|
frameInput.useCommittedLayerStates = mRuntimeCoordinator && mRuntimeCoordinator->UseCommittedLayerStates();
|
||||||
|
frameInput.hasInputSource = mVideoBackend->HasInputSource();
|
||||||
|
frameInput.renderWidth = mVideoBackend->InputFrameWidth();
|
||||||
|
frameInput.renderHeight = mVideoBackend->InputFrameHeight();
|
||||||
|
frameInput.inputFrameWidth = mVideoBackend->InputFrameWidth();
|
||||||
|
frameInput.inputFrameHeight = mVideoBackend->InputFrameHeight();
|
||||||
|
frameInput.captureTextureWidth = mVideoBackend->CaptureTextureWidth();
|
||||||
|
frameInput.inputPixelFormat = mVideoBackend->InputPixelFormat();
|
||||||
|
frameInput.historyCap = mRuntimeStore ? mRuntimeStore->GetConfiguredMaxTemporalHistoryFrames() : 0;
|
||||||
|
frameInput.oscSmoothing = mRuntimeStore ? mRuntimeStore->GetConfiguredOscSmoothing() : 0.0;
|
||||||
|
return frameInput;
|
||||||
|
}
|
||||||
|
|
||||||
|
void OpenGLComposite::RenderFrame(const RenderFrameInput& frameInput)
|
||||||
|
{
|
||||||
|
RenderFrameState frameState;
|
||||||
|
if (mRuntimeServices)
|
||||||
|
{
|
||||||
|
RuntimeServiceLiveBridge::PrepareLiveRenderFrameState(
|
||||||
|
*mRuntimeServices,
|
||||||
|
*mRenderEngine,
|
||||||
|
frameInput,
|
||||||
|
frameState);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
mRenderEngine->ResolveRenderFrameState(frameInput, nullptr, frameState);
|
||||||
|
}
|
||||||
|
mRenderEngine->RenderPreparedFrame(frameState);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::filesystem::path OpenGLComposite::BuildScreenshotPath() const
|
||||||
|
{
|
||||||
|
const std::filesystem::path root = mRuntimeStore && !mRuntimeStore->GetRuntimeDataRoot().empty()
|
||||||
|
? mRuntimeStore->GetRuntimeDataRoot()
|
||||||
|
: std::filesystem::current_path();
|
||||||
|
|
||||||
|
const auto now = std::chrono::system_clock::now();
|
||||||
|
const auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()) % 1000;
|
||||||
|
const std::time_t nowTime = std::chrono::system_clock::to_time_t(now);
|
||||||
|
std::tm localTime = {};
|
||||||
|
localtime_s(&localTime, &nowTime);
|
||||||
|
|
||||||
|
std::ostringstream filename;
|
||||||
|
filename << "video-shader-toys-"
|
||||||
|
<< std::put_time(&localTime, "%Y%m%d-%H%M%S")
|
||||||
|
<< "-" << std::setw(3) << std::setfill('0') << milliseconds.count()
|
||||||
|
<< ".png";
|
||||||
|
|
||||||
|
return root / "screenshots" / filename.str();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool OpenGLComposite::CheckOpenGLExtensions()
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
@@ -2,35 +2,23 @@
|
|||||||
#define __OPENGL_COMPOSITE_H__
|
#define __OPENGL_COMPOSITE_H__
|
||||||
|
|
||||||
#include <windows.h>
|
#include <windows.h>
|
||||||
#include <process.h>
|
|
||||||
#include <tchar.h>
|
|
||||||
#include <gl/gl.h>
|
|
||||||
#include <gl/glu.h>
|
|
||||||
|
|
||||||
#include <objbase.h>
|
#include <objbase.h>
|
||||||
#include <atlbase.h>
|
|
||||||
#include <comutil.h>
|
|
||||||
#include "DeckLinkAPI_h.h"
|
|
||||||
|
|
||||||
#include "GLExtensions.h"
|
#include "RenderFrameState.h"
|
||||||
#include "OpenGLRenderer.h"
|
|
||||||
#include "RuntimeHost.h"
|
|
||||||
|
|
||||||
#include <functional>
|
|
||||||
#include <atomic>
|
|
||||||
#include <filesystem>
|
#include <filesystem>
|
||||||
#include <map>
|
|
||||||
#include <memory>
|
#include <memory>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <vector>
|
|
||||||
#include <deque>
|
|
||||||
|
|
||||||
class DeckLinkSession;
|
class RenderEngine;
|
||||||
class OpenGLDeckLinkBridge;
|
class RuntimeCoordinator;
|
||||||
class OpenGLRenderPass;
|
class RuntimeEventDispatcher;
|
||||||
class OpenGLShaderPrograms;
|
class RuntimeSnapshotProvider;
|
||||||
class RuntimeServices;
|
class RuntimeServices;
|
||||||
|
class RuntimeStore;
|
||||||
|
class RuntimeUpdateController;
|
||||||
class ShaderBuildQueue;
|
class ShaderBuildQueue;
|
||||||
|
class VideoBackend;
|
||||||
|
|
||||||
|
|
||||||
class OpenGLComposite
|
class OpenGLComposite
|
||||||
@@ -40,9 +28,10 @@ public:
|
|||||||
~OpenGLComposite();
|
~OpenGLComposite();
|
||||||
|
|
||||||
bool InitDeckLink();
|
bool InitDeckLink();
|
||||||
|
bool InitVideoIO();
|
||||||
bool Start();
|
bool Start();
|
||||||
bool Stop();
|
bool Stop();
|
||||||
bool ReloadShader();
|
bool ReloadShader(bool preserveFeedbackState = false);
|
||||||
std::string GetRuntimeStateJson() const;
|
std::string GetRuntimeStateJson() const;
|
||||||
bool AddLayer(const std::string& shaderId, std::string& error);
|
bool AddLayer(const std::string& shaderId, std::string& error);
|
||||||
bool RemoveLayer(const std::string& layerId, std::string& error);
|
bool RemoveLayer(const std::string& layerId, std::string& error);
|
||||||
@@ -58,47 +47,37 @@ public:
|
|||||||
bool RequestScreenshot(std::string& error);
|
bool RequestScreenshot(std::string& error);
|
||||||
unsigned short GetControlServerPort() const;
|
unsigned short GetControlServerPort() const;
|
||||||
unsigned short GetOscPort() const;
|
unsigned short GetOscPort() const;
|
||||||
|
std::string GetOscBindAddress() const;
|
||||||
std::string GetControlUrl() const;
|
std::string GetControlUrl() const;
|
||||||
std::string GetDocsUrl() const;
|
std::string GetDocsUrl() const;
|
||||||
std::string GetOscAddress() const;
|
std::string GetOscAddress() const;
|
||||||
|
|
||||||
void resizeGL(WORD width, WORD height);
|
void resizeGL(WORD width, WORD height);
|
||||||
void paintGL();
|
void paintGL(bool force = false);
|
||||||
|
|
||||||
void VideoFrameArrived(IDeckLinkVideoInputFrame* inputFrame, bool hasNoInputSource);
|
|
||||||
void PlayoutFrameCompleted(IDeckLinkVideoFrame* completedFrame, BMDOutputFrameCompletionResult result);
|
|
||||||
|
|
||||||
private:
|
private:
|
||||||
void resizeWindow(int width, int height);
|
void resizeWindow(int width, int height);
|
||||||
bool CheckOpenGLExtensions();
|
bool CheckOpenGLExtensions();
|
||||||
void PublishDeckLinkOutputStatus(const std::string& statusMessage);
|
|
||||||
using LayerProgram = OpenGLRenderer::LayerProgram;
|
|
||||||
|
|
||||||
HWND hGLWnd;
|
HWND hGLWnd;
|
||||||
HDC hGLDC;
|
HDC hGLDC;
|
||||||
HGLRC hGLRC;
|
HGLRC hGLRC;
|
||||||
CRITICAL_SECTION pMutex;
|
|
||||||
|
|
||||||
std::unique_ptr<DeckLinkSession> mDeckLink;
|
std::unique_ptr<RuntimeStore> mRuntimeStore;
|
||||||
std::unique_ptr<OpenGLRenderer> mRenderer;
|
std::unique_ptr<RuntimeCoordinator> mRuntimeCoordinator;
|
||||||
std::unique_ptr<RuntimeHost> mRuntimeHost;
|
std::unique_ptr<RuntimeSnapshotProvider> mRuntimeSnapshotProvider;
|
||||||
std::unique_ptr<OpenGLDeckLinkBridge> mDeckLinkBridge;
|
std::unique_ptr<RuntimeEventDispatcher> mRuntimeEventDispatcher;
|
||||||
std::unique_ptr<OpenGLRenderPass> mRenderPass;
|
std::unique_ptr<RenderEngine> mRenderEngine;
|
||||||
std::unique_ptr<OpenGLShaderPrograms> mShaderPrograms;
|
|
||||||
std::unique_ptr<ShaderBuildQueue> mShaderBuildQueue;
|
std::unique_ptr<ShaderBuildQueue> mShaderBuildQueue;
|
||||||
std::unique_ptr<RuntimeServices> mRuntimeServices;
|
std::unique_ptr<RuntimeServices> mRuntimeServices;
|
||||||
std::vector<RuntimeRenderState> mCachedLayerRenderStates;
|
std::unique_ptr<RuntimeUpdateController> mRuntimeUpdateController;
|
||||||
std::atomic<bool> mUseCommittedLayerStates;
|
std::unique_ptr<VideoBackend> mVideoBackend;
|
||||||
std::atomic<bool> mScreenshotRequested;
|
|
||||||
|
|
||||||
bool InitOpenGLState();
|
bool InitOpenGLState();
|
||||||
void renderEffect();
|
void renderEffect();
|
||||||
bool ProcessRuntimePollResults();
|
RenderFrameInput BuildRenderFrameInput() const;
|
||||||
void RequestShaderBuild();
|
void RenderFrame(const RenderFrameInput& frameInput);
|
||||||
void ProcessScreenshotRequest();
|
|
||||||
std::filesystem::path BuildScreenshotPath() const;
|
std::filesystem::path BuildScreenshotPath() const;
|
||||||
void broadcastRuntimeState();
|
|
||||||
void resetTemporalHistoryState();
|
|
||||||
};
|
};
|
||||||
|
|
||||||
#endif // __OPENGL_COMPOSITE_H__
|
#endif // __OPENGL_COMPOSITE_H__
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
#include "OpenGLComposite.h"
|
||||||
|
#include "RuntimeCoordinator.h"
|
||||||
|
#include "RuntimeJson.h"
|
||||||
|
#include "RuntimeServices.h"
|
||||||
|
#include "RuntimeStore.h"
|
||||||
|
#include "RuntimeUpdateController.h"
|
||||||
|
|
||||||
|
std::string OpenGLComposite::GetRuntimeStateJson() const
|
||||||
|
{
|
||||||
|
return mRuntimeStore ? mRuntimeStore->BuildPersistentStateJson() : "{}";
|
||||||
|
}
|
||||||
|
|
||||||
|
unsigned short OpenGLComposite::GetControlServerPort() const
|
||||||
|
{
|
||||||
|
return mRuntimeStore ? mRuntimeStore->GetConfiguredControlServerPort() : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
unsigned short OpenGLComposite::GetOscPort() const
|
||||||
|
{
|
||||||
|
return mRuntimeStore ? mRuntimeStore->GetConfiguredOscPort() : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string OpenGLComposite::GetOscBindAddress() const
|
||||||
|
{
|
||||||
|
return mRuntimeStore ? mRuntimeStore->GetConfiguredOscBindAddress() : "127.0.0.1";
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string OpenGLComposite::GetControlUrl() const
|
||||||
|
{
|
||||||
|
return "http://127.0.0.1:" + std::to_string(GetControlServerPort()) + "/";
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string OpenGLComposite::GetDocsUrl() const
|
||||||
|
{
|
||||||
|
return "http://127.0.0.1:" + std::to_string(GetControlServerPort()) + "/docs";
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string OpenGLComposite::GetOscAddress() const
|
||||||
|
{
|
||||||
|
return "udp://" + GetOscBindAddress() + ":" + std::to_string(GetOscPort()) + " /VideoShaderToys/{Layer}/{Parameter}";
|
||||||
|
}
|
||||||
|
|
||||||
|
bool OpenGLComposite::AddLayer(const std::string& shaderId, std::string& error)
|
||||||
|
{
|
||||||
|
return mRuntimeCoordinator &&
|
||||||
|
mRuntimeUpdateController &&
|
||||||
|
mRuntimeUpdateController->ApplyRuntimeCoordinatorResult(mRuntimeCoordinator->AddLayer(shaderId), &error);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool OpenGLComposite::RemoveLayer(const std::string& layerId, std::string& error)
|
||||||
|
{
|
||||||
|
return mRuntimeCoordinator &&
|
||||||
|
mRuntimeUpdateController &&
|
||||||
|
mRuntimeUpdateController->ApplyRuntimeCoordinatorResult(mRuntimeCoordinator->RemoveLayer(layerId), &error);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool OpenGLComposite::MoveLayer(const std::string& layerId, int direction, std::string& error)
|
||||||
|
{
|
||||||
|
return mRuntimeCoordinator &&
|
||||||
|
mRuntimeUpdateController &&
|
||||||
|
mRuntimeUpdateController->ApplyRuntimeCoordinatorResult(mRuntimeCoordinator->MoveLayer(layerId, direction), &error);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool OpenGLComposite::MoveLayerToIndex(const std::string& layerId, std::size_t targetIndex, std::string& error)
|
||||||
|
{
|
||||||
|
return mRuntimeCoordinator &&
|
||||||
|
mRuntimeUpdateController &&
|
||||||
|
mRuntimeUpdateController->ApplyRuntimeCoordinatorResult(mRuntimeCoordinator->MoveLayerToIndex(layerId, targetIndex), &error);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool OpenGLComposite::SetLayerBypass(const std::string& layerId, bool bypassed, std::string& error)
|
||||||
|
{
|
||||||
|
return mRuntimeCoordinator &&
|
||||||
|
mRuntimeUpdateController &&
|
||||||
|
mRuntimeUpdateController->ApplyRuntimeCoordinatorResult(mRuntimeCoordinator->SetLayerBypass(layerId, bypassed), &error);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool OpenGLComposite::SetLayerShader(const std::string& layerId, const std::string& shaderId, std::string& error)
|
||||||
|
{
|
||||||
|
return mRuntimeCoordinator &&
|
||||||
|
mRuntimeUpdateController &&
|
||||||
|
mRuntimeUpdateController->ApplyRuntimeCoordinatorResult(mRuntimeCoordinator->SetLayerShader(layerId, shaderId), &error);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool OpenGLComposite::UpdateLayerParameterJson(const std::string& layerId, const std::string& parameterId, const std::string& valueJson, std::string& error)
|
||||||
|
{
|
||||||
|
JsonValue parsedValue;
|
||||||
|
if (!ParseJson(valueJson, parsedValue, error))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
return mRuntimeCoordinator &&
|
||||||
|
mRuntimeUpdateController &&
|
||||||
|
mRuntimeUpdateController->ApplyRuntimeCoordinatorResult(mRuntimeCoordinator->UpdateLayerParameter(layerId, parameterId, parsedValue), &error);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool OpenGLComposite::UpdateLayerParameterByControlKeyJson(const std::string& layerKey, const std::string& parameterKey, const std::string& valueJson, std::string& error)
|
||||||
|
{
|
||||||
|
JsonValue parsedValue;
|
||||||
|
if (!ParseJson(valueJson, parsedValue, error))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
return mRuntimeCoordinator &&
|
||||||
|
mRuntimeUpdateController &&
|
||||||
|
mRuntimeUpdateController->ApplyRuntimeCoordinatorResult(mRuntimeCoordinator->UpdateLayerParameterByControlKey(layerKey, parameterKey, parsedValue), &error);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool OpenGLComposite::ResetLayerParameters(const std::string& layerId, std::string& error)
|
||||||
|
{
|
||||||
|
return mRuntimeCoordinator &&
|
||||||
|
mRuntimeUpdateController &&
|
||||||
|
mRuntimeUpdateController->ApplyRuntimeCoordinatorResult(mRuntimeCoordinator->ResetLayerParameters(layerId), &error);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool OpenGLComposite::SaveStackPreset(const std::string& presetName, std::string& error)
|
||||||
|
{
|
||||||
|
return mRuntimeCoordinator &&
|
||||||
|
mRuntimeUpdateController &&
|
||||||
|
mRuntimeUpdateController->ApplyRuntimeCoordinatorResult(mRuntimeCoordinator->SaveStackPreset(presetName), &error);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool OpenGLComposite::LoadStackPreset(const std::string& presetName, std::string& error)
|
||||||
|
{
|
||||||
|
return mRuntimeCoordinator &&
|
||||||
|
mRuntimeUpdateController &&
|
||||||
|
mRuntimeUpdateController->ApplyRuntimeCoordinatorResult(mRuntimeCoordinator->LoadStackPreset(presetName), &error);
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "ShaderTypes.h"
|
||||||
|
#include "VideoIOTypes.h"
|
||||||
|
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
struct RenderFrameInput
|
||||||
|
{
|
||||||
|
bool useCommittedLayerStates = false;
|
||||||
|
bool hasInputSource = false;
|
||||||
|
unsigned renderWidth = 0;
|
||||||
|
unsigned renderHeight = 0;
|
||||||
|
unsigned inputFrameWidth = 0;
|
||||||
|
unsigned inputFrameHeight = 0;
|
||||||
|
unsigned captureTextureWidth = 0;
|
||||||
|
VideoIOPixelFormat inputPixelFormat = VideoIOPixelFormat::Uyvy8;
|
||||||
|
unsigned historyCap = 0;
|
||||||
|
double oscSmoothing = 0.0;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct RenderFrameState
|
||||||
|
{
|
||||||
|
bool hasInputSource = false;
|
||||||
|
unsigned inputFrameWidth = 0;
|
||||||
|
unsigned inputFrameHeight = 0;
|
||||||
|
unsigned captureTextureWidth = 0;
|
||||||
|
VideoIOPixelFormat inputPixelFormat = VideoIOPixelFormat::Uyvy8;
|
||||||
|
unsigned historyCap = 0;
|
||||||
|
std::vector<RuntimeRenderState> layerStates;
|
||||||
|
};
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
#include "RenderFrameStateResolver.h"
|
||||||
|
|
||||||
|
#include <chrono>
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
constexpr auto kOscOverlayCommitDelay = std::chrono::milliseconds(150);
|
||||||
|
}
|
||||||
|
|
||||||
|
RenderFrameStateResolver::RenderFrameStateResolver(RuntimeSnapshotProvider& runtimeSnapshotProvider) :
|
||||||
|
mRuntimeSnapshotProvider(runtimeSnapshotProvider)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
void RenderFrameStateResolver::StoreCommittedSnapshot(
|
||||||
|
const RuntimeRenderStateSnapshot& snapshot,
|
||||||
|
const std::vector<RuntimeRenderState>& committedLayerStates)
|
||||||
|
{
|
||||||
|
mCachedLayerRenderStates = committedLayerStates;
|
||||||
|
mCachedRenderStateVersion = snapshot.versions.renderStateVersion;
|
||||||
|
mCachedParameterStateVersion = snapshot.versions.parameterStateVersion;
|
||||||
|
mCachedRenderStateWidth = snapshot.outputWidth;
|
||||||
|
mCachedRenderStateHeight = snapshot.outputHeight;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool RenderFrameStateResolver::Resolve(
|
||||||
|
const RenderFrameInput& input,
|
||||||
|
const std::vector<RuntimeRenderState>& committedLayerStates,
|
||||||
|
RuntimeLiveState& liveState,
|
||||||
|
std::vector<RuntimeLiveOscCommitRequest>* commitRequests,
|
||||||
|
RenderFrameState& frameState)
|
||||||
|
{
|
||||||
|
frameState.hasInputSource = input.hasInputSource;
|
||||||
|
frameState.inputFrameWidth = input.inputFrameWidth;
|
||||||
|
frameState.inputFrameHeight = input.inputFrameHeight;
|
||||||
|
frameState.captureTextureWidth = input.captureTextureWidth;
|
||||||
|
frameState.inputPixelFormat = input.inputPixelFormat;
|
||||||
|
frameState.historyCap = input.historyCap;
|
||||||
|
frameState.layerStates.clear();
|
||||||
|
|
||||||
|
if (input.useCommittedLayerStates)
|
||||||
|
{
|
||||||
|
frameState.layerStates = ComposeLayerStates(committedLayerStates, liveState, false, input.oscSmoothing, commitRequests);
|
||||||
|
mRuntimeSnapshotProvider.RefreshDynamicRenderStateFields(frameState.layerStates);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
const RuntimeSnapshotVersions versions = mRuntimeSnapshotProvider.GetVersions();
|
||||||
|
const bool renderStateCacheValid =
|
||||||
|
!mCachedLayerRenderStates.empty() &&
|
||||||
|
mCachedRenderStateVersion == versions.renderStateVersion &&
|
||||||
|
mCachedRenderStateWidth == input.renderWidth &&
|
||||||
|
mCachedRenderStateHeight == input.renderHeight;
|
||||||
|
|
||||||
|
if (renderStateCacheValid)
|
||||||
|
{
|
||||||
|
RuntimeRenderStateSnapshot renderSnapshot;
|
||||||
|
renderSnapshot.outputWidth = input.renderWidth;
|
||||||
|
renderSnapshot.outputHeight = input.renderHeight;
|
||||||
|
renderSnapshot.versions.renderStateVersion = mCachedRenderStateVersion;
|
||||||
|
renderSnapshot.versions.parameterStateVersion = mCachedParameterStateVersion;
|
||||||
|
renderSnapshot.states = mCachedLayerRenderStates;
|
||||||
|
|
||||||
|
renderSnapshot.states = ComposeLayerStates(renderSnapshot.states, liveState, true, input.oscSmoothing, commitRequests);
|
||||||
|
if (mCachedParameterStateVersion != versions.parameterStateVersion &&
|
||||||
|
mRuntimeSnapshotProvider.TryRefreshPublishedSnapshotParameters(renderSnapshot))
|
||||||
|
{
|
||||||
|
mCachedParameterStateVersion = renderSnapshot.versions.parameterStateVersion;
|
||||||
|
renderSnapshot.states = ComposeLayerStates(renderSnapshot.states, liveState, true, input.oscSmoothing, commitRequests);
|
||||||
|
}
|
||||||
|
|
||||||
|
mCachedLayerRenderStates = renderSnapshot.states;
|
||||||
|
frameState.layerStates = renderSnapshot.states;
|
||||||
|
mRuntimeSnapshotProvider.RefreshDynamicRenderStateFields(frameState.layerStates);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
RuntimeRenderStateSnapshot renderSnapshot;
|
||||||
|
if (mRuntimeSnapshotProvider.TryPublishRenderStateSnapshot(input.renderWidth, input.renderHeight, renderSnapshot))
|
||||||
|
{
|
||||||
|
mCachedLayerRenderStates = renderSnapshot.states;
|
||||||
|
mCachedRenderStateVersion = renderSnapshot.versions.renderStateVersion;
|
||||||
|
mCachedParameterStateVersion = renderSnapshot.versions.parameterStateVersion;
|
||||||
|
mCachedRenderStateWidth = renderSnapshot.outputWidth;
|
||||||
|
mCachedRenderStateHeight = renderSnapshot.outputHeight;
|
||||||
|
mCachedLayerRenderStates = ComposeLayerStates(mCachedLayerRenderStates, liveState, true, input.oscSmoothing, commitRequests);
|
||||||
|
frameState.layerStates = mCachedLayerRenderStates;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
frameState.layerStates = ComposeLayerStates(mCachedLayerRenderStates, liveState, true, input.oscSmoothing, commitRequests);
|
||||||
|
mRuntimeSnapshotProvider.RefreshDynamicRenderStateFields(frameState.layerStates);
|
||||||
|
return !frameState.layerStates.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<RuntimeRenderState> RenderFrameStateResolver::ComposeLayerStates(
|
||||||
|
const std::vector<RuntimeRenderState>& baseStates,
|
||||||
|
RuntimeLiveState& liveState,
|
||||||
|
bool allowCommit,
|
||||||
|
double smoothing,
|
||||||
|
std::vector<RuntimeLiveOscCommitRequest>* commitRequests) const
|
||||||
|
{
|
||||||
|
LayeredRenderStateInput input;
|
||||||
|
input.committedLiveLayerStates = &baseStates;
|
||||||
|
input.transientAutomationOverlay = &liveState;
|
||||||
|
input.allowTransientAutomationCommits = allowCommit;
|
||||||
|
input.collectTransientAutomationCommitRequests = commitRequests != nullptr;
|
||||||
|
input.transientAutomationSmoothing = smoothing;
|
||||||
|
input.transientAutomationCommitDelay = kOscOverlayCommitDelay;
|
||||||
|
input.now = std::chrono::steady_clock::now();
|
||||||
|
const RenderStateCompositionResult result = mRenderStateComposer.BuildFrameState(input);
|
||||||
|
|
||||||
|
if (commitRequests)
|
||||||
|
{
|
||||||
|
for (const RuntimeLiveOscCommitRequest& request : result.commitRequests)
|
||||||
|
commitRequests->push_back(request);
|
||||||
|
}
|
||||||
|
return result.layerStates;
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "RenderFrameState.h"
|
||||||
|
#include "RenderStateComposer.h"
|
||||||
|
#include "RuntimeSnapshotProvider.h"
|
||||||
|
|
||||||
|
#include <cstdint>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
class RenderFrameStateResolver
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
explicit RenderFrameStateResolver(RuntimeSnapshotProvider& runtimeSnapshotProvider);
|
||||||
|
|
||||||
|
void StoreCommittedSnapshot(
|
||||||
|
const RuntimeRenderStateSnapshot& snapshot,
|
||||||
|
const std::vector<RuntimeRenderState>& committedLayerStates);
|
||||||
|
bool Resolve(
|
||||||
|
const RenderFrameInput& input,
|
||||||
|
const std::vector<RuntimeRenderState>& committedLayerStates,
|
||||||
|
RuntimeLiveState& liveState,
|
||||||
|
std::vector<RuntimeLiveOscCommitRequest>* commitRequests,
|
||||||
|
RenderFrameState& frameState);
|
||||||
|
|
||||||
|
private:
|
||||||
|
std::vector<RuntimeRenderState> ComposeLayerStates(
|
||||||
|
const std::vector<RuntimeRenderState>& baseStates,
|
||||||
|
RuntimeLiveState& liveState,
|
||||||
|
bool allowCommit,
|
||||||
|
double smoothing,
|
||||||
|
std::vector<RuntimeLiveOscCommitRequest>* commitRequests) const;
|
||||||
|
|
||||||
|
RuntimeSnapshotProvider& mRuntimeSnapshotProvider;
|
||||||
|
RenderStateComposer mRenderStateComposer;
|
||||||
|
std::vector<RuntimeRenderState> mCachedLayerRenderStates;
|
||||||
|
uint64_t mCachedRenderStateVersion = 0;
|
||||||
|
uint64_t mCachedParameterStateVersion = 0;
|
||||||
|
unsigned mCachedRenderStateWidth = 0;
|
||||||
|
unsigned mCachedRenderStateHeight = 0;
|
||||||
|
};
|
||||||
@@ -0,0 +1,378 @@
|
|||||||
|
#include "RuntimeUpdateController.h"
|
||||||
|
|
||||||
|
#include "RenderEngine.h"
|
||||||
|
#include "RuntimeEventDispatcher.h"
|
||||||
|
#include "RuntimeServices.h"
|
||||||
|
#include "RuntimeStore.h"
|
||||||
|
#include "ShaderBuildQueue.h"
|
||||||
|
#include "VideoBackend.h"
|
||||||
|
|
||||||
|
#include <variant>
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
RuntimeCoordinatorRenderResetScope ToRuntimeCoordinatorRenderResetScope(RuntimeEventRenderResetScope scope)
|
||||||
|
{
|
||||||
|
switch (scope)
|
||||||
|
{
|
||||||
|
case RuntimeEventRenderResetScope::TemporalHistoryOnly:
|
||||||
|
return RuntimeCoordinatorRenderResetScope::TemporalHistoryOnly;
|
||||||
|
case RuntimeEventRenderResetScope::TemporalHistoryAndFeedback:
|
||||||
|
return RuntimeCoordinatorRenderResetScope::TemporalHistoryAndFeedback;
|
||||||
|
case RuntimeEventRenderResetScope::None:
|
||||||
|
default:
|
||||||
|
return RuntimeCoordinatorRenderResetScope::None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
RuntimeUpdateController::RuntimeUpdateController(
|
||||||
|
RuntimeStore& runtimeStore,
|
||||||
|
RuntimeCoordinator& runtimeCoordinator,
|
||||||
|
RuntimeEventDispatcher& runtimeEventDispatcher,
|
||||||
|
RuntimeServices& runtimeServices,
|
||||||
|
RenderEngine& renderEngine,
|
||||||
|
ShaderBuildQueue& shaderBuildQueue,
|
||||||
|
VideoBackend& videoBackend) :
|
||||||
|
mRuntimeStore(runtimeStore),
|
||||||
|
mRuntimeCoordinator(runtimeCoordinator),
|
||||||
|
mRuntimeEventDispatcher(runtimeEventDispatcher),
|
||||||
|
mRuntimeServices(runtimeServices),
|
||||||
|
mRenderEngine(renderEngine),
|
||||||
|
mShaderBuildQueue(shaderBuildQueue),
|
||||||
|
mVideoBackend(videoBackend)
|
||||||
|
{
|
||||||
|
mRuntimeEventDispatcher.Subscribe(
|
||||||
|
RuntimeEventType::RuntimeStateBroadcastRequested,
|
||||||
|
[this](const RuntimeEvent& event) { HandleRuntimeStateBroadcastRequested(event); });
|
||||||
|
mRuntimeEventDispatcher.Subscribe(
|
||||||
|
RuntimeEventType::RuntimeReloadRequested,
|
||||||
|
[this](const RuntimeEvent& event) { HandleRuntimeReloadRequested(event); });
|
||||||
|
mRuntimeEventDispatcher.Subscribe(
|
||||||
|
RuntimeEventType::RuntimePersistenceRequested,
|
||||||
|
[this](const RuntimeEvent& event) { HandleRuntimePersistenceRequested(event); });
|
||||||
|
mRuntimeEventDispatcher.Subscribe(
|
||||||
|
RuntimeEventType::ShaderBuildRequested,
|
||||||
|
[this](const RuntimeEvent& event) { HandleShaderBuildRequested(event); });
|
||||||
|
mRuntimeEventDispatcher.Subscribe(
|
||||||
|
RuntimeEventType::ShaderBuildPrepared,
|
||||||
|
[this](const RuntimeEvent& event) { HandleShaderBuildPrepared(event); });
|
||||||
|
mRuntimeEventDispatcher.Subscribe(
|
||||||
|
RuntimeEventType::ShaderBuildFailed,
|
||||||
|
[this](const RuntimeEvent& event) { HandleShaderBuildFailed(event); });
|
||||||
|
mRuntimeEventDispatcher.Subscribe(
|
||||||
|
RuntimeEventType::CompileStatusChanged,
|
||||||
|
[this](const RuntimeEvent& event) { HandleCompileStatusChanged(event); });
|
||||||
|
mRuntimeEventDispatcher.Subscribe(
|
||||||
|
RuntimeEventType::RenderResetRequested,
|
||||||
|
[this](const RuntimeEvent& event) { HandleRenderResetRequested(event); });
|
||||||
|
}
|
||||||
|
|
||||||
|
bool RuntimeUpdateController::ApplyRuntimeCoordinatorResult(const RuntimeCoordinatorResult& result, std::string* error)
|
||||||
|
{
|
||||||
|
if (!result.accepted)
|
||||||
|
{
|
||||||
|
if (error)
|
||||||
|
*error = result.errorMessage;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result.compileStatusChanged)
|
||||||
|
{
|
||||||
|
mRuntimeStore.SetCompileStatus(result.compileStatusSucceeded, result.compileStatusMessage);
|
||||||
|
++mPendingCoordinatorCompileStatusEvents;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result.clearReloadRequest)
|
||||||
|
mRuntimeStore.ClearReloadRequest();
|
||||||
|
|
||||||
|
mRuntimeCoordinator.ApplyCommittedStateMode(result.committedStateMode);
|
||||||
|
|
||||||
|
switch (result.transientOscInvalidation)
|
||||||
|
{
|
||||||
|
case RuntimeCoordinatorTransientOscInvalidation::All:
|
||||||
|
mRenderEngine.ClearOscOverlayState();
|
||||||
|
mRuntimeServices.ClearOscState();
|
||||||
|
break;
|
||||||
|
case RuntimeCoordinatorTransientOscInvalidation::Layer:
|
||||||
|
mRenderEngine.ClearOscOverlayStateForLayerKey(result.transientOscLayerKey);
|
||||||
|
mRuntimeServices.ClearOscStateForLayerKey(result.transientOscLayerKey);
|
||||||
|
break;
|
||||||
|
case RuntimeCoordinatorTransientOscInvalidation::None:
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
mRenderEngine.ApplyRuntimeCoordinatorRenderReset(result.renderResetScope);
|
||||||
|
if (result.renderResetScope != RuntimeCoordinatorRenderResetScope::None)
|
||||||
|
++mPendingCoordinatorRenderResetEvents;
|
||||||
|
|
||||||
|
if (result.shaderBuildRequested)
|
||||||
|
{
|
||||||
|
RequestShaderBuild();
|
||||||
|
++mPendingCoordinatorShaderBuildEvents;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result.runtimeStateBroadcastRequired)
|
||||||
|
BroadcastRuntimeState();
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool RuntimeUpdateController::ProcessRuntimeWork()
|
||||||
|
{
|
||||||
|
DispatchRuntimeEvents();
|
||||||
|
|
||||||
|
return ConsumeReadyShaderBuild(0, true, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
void RuntimeUpdateController::RequestShaderBuild()
|
||||||
|
{
|
||||||
|
mShaderBuildQueue.RequestBuild(mVideoBackend.InputFrameWidth(), mVideoBackend.InputFrameHeight());
|
||||||
|
}
|
||||||
|
|
||||||
|
void RuntimeUpdateController::BroadcastRuntimeState()
|
||||||
|
{
|
||||||
|
RuntimeStateBroadcastRequestedEvent event;
|
||||||
|
event.reason = "runtime-state-changed";
|
||||||
|
if (!mRuntimeEventDispatcher.PublishPayload(event, "RuntimeUpdateController"))
|
||||||
|
{
|
||||||
|
mRuntimeServices.BroadcastState();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
DispatchRuntimeEvents();
|
||||||
|
}
|
||||||
|
|
||||||
|
void RuntimeUpdateController::HandleRuntimeStateBroadcastRequested(const RuntimeEvent& event)
|
||||||
|
{
|
||||||
|
if (event.source == "ControlServices")
|
||||||
|
return;
|
||||||
|
|
||||||
|
mRuntimeServices.BroadcastState();
|
||||||
|
}
|
||||||
|
|
||||||
|
void RuntimeUpdateController::HandleRuntimeReloadRequested(const RuntimeEvent& event)
|
||||||
|
{
|
||||||
|
const RuntimeReloadRequestedEvent* payload = std::get_if<RuntimeReloadRequestedEvent>(&event.payload);
|
||||||
|
if (!payload)
|
||||||
|
return;
|
||||||
|
|
||||||
|
mRuntimeStore.ClearReloadRequest();
|
||||||
|
}
|
||||||
|
|
||||||
|
void RuntimeUpdateController::HandleRuntimePersistenceRequested(const RuntimeEvent& event)
|
||||||
|
{
|
||||||
|
const RuntimePersistenceRequestedEvent* payload = std::get_if<RuntimePersistenceRequestedEvent>(&event.payload);
|
||||||
|
if (!payload)
|
||||||
|
return;
|
||||||
|
|
||||||
|
std::string error;
|
||||||
|
mRuntimeStore.RequestPersistence(payload->request, error);
|
||||||
|
}
|
||||||
|
|
||||||
|
void RuntimeUpdateController::HandleShaderBuildRequested(const RuntimeEvent& event)
|
||||||
|
{
|
||||||
|
const ShaderBuildEvent* payload = std::get_if<ShaderBuildEvent>(&event.payload);
|
||||||
|
if (!payload || payload->phase != RuntimeEventShaderBuildPhase::Requested)
|
||||||
|
return;
|
||||||
|
if (ShouldSuppressCoordinatorFollowUp(event, mPendingCoordinatorShaderBuildEvents))
|
||||||
|
return;
|
||||||
|
|
||||||
|
RequestShaderBuild();
|
||||||
|
}
|
||||||
|
|
||||||
|
void RuntimeUpdateController::HandleShaderBuildPrepared(const RuntimeEvent& event)
|
||||||
|
{
|
||||||
|
const ShaderBuildEvent* payload = std::get_if<ShaderBuildEvent>(&event.payload);
|
||||||
|
if (!payload || payload->phase != RuntimeEventShaderBuildPhase::Prepared)
|
||||||
|
return;
|
||||||
|
|
||||||
|
ConsumeReadyShaderBuild(payload->generation, false, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
void RuntimeUpdateController::HandleShaderBuildFailed(const RuntimeEvent& event)
|
||||||
|
{
|
||||||
|
const ShaderBuildEvent* payload = std::get_if<ShaderBuildEvent>(&event.payload);
|
||||||
|
if (!payload || payload->phase != RuntimeEventShaderBuildPhase::Failed)
|
||||||
|
return;
|
||||||
|
|
||||||
|
ConsumeReadyShaderBuild(payload->generation, false, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
void RuntimeUpdateController::HandleCompileStatusChanged(const RuntimeEvent& event)
|
||||||
|
{
|
||||||
|
const CompileStatusChangedEvent* payload = std::get_if<CompileStatusChangedEvent>(&event.payload);
|
||||||
|
if (!payload)
|
||||||
|
return;
|
||||||
|
if (ShouldSuppressCoordinatorFollowUp(event, mPendingCoordinatorCompileStatusEvents))
|
||||||
|
return;
|
||||||
|
|
||||||
|
mRuntimeStore.SetCompileStatus(payload->succeeded, payload->message);
|
||||||
|
}
|
||||||
|
|
||||||
|
void RuntimeUpdateController::HandleRenderResetRequested(const RuntimeEvent& event)
|
||||||
|
{
|
||||||
|
const RenderResetEvent* payload = std::get_if<RenderResetEvent>(&event.payload);
|
||||||
|
if (!payload || payload->applied)
|
||||||
|
return;
|
||||||
|
if (ShouldSuppressCoordinatorFollowUp(event, mPendingCoordinatorRenderResetEvents))
|
||||||
|
return;
|
||||||
|
|
||||||
|
mRenderEngine.ApplyRuntimeCoordinatorRenderReset(ToRuntimeCoordinatorRenderResetScope(payload->scope));
|
||||||
|
}
|
||||||
|
|
||||||
|
bool RuntimeUpdateController::ConsumeReadyShaderBuild(uint64_t expectedGeneration, bool publishPreparedEvent, bool publishFailureEvent)
|
||||||
|
{
|
||||||
|
PreparedShaderBuild readyBuild;
|
||||||
|
const bool consumed = expectedGeneration == 0
|
||||||
|
? mShaderBuildQueue.TryConsumeReadyBuild(readyBuild)
|
||||||
|
: mShaderBuildQueue.TryConsumeReadyBuild(expectedGeneration, readyBuild);
|
||||||
|
if (!consumed)
|
||||||
|
return true;
|
||||||
|
|
||||||
|
const unsigned inputWidth = mVideoBackend.InputFrameWidth();
|
||||||
|
const unsigned inputHeight = mVideoBackend.InputFrameHeight();
|
||||||
|
if (!readyBuild.succeeded)
|
||||||
|
{
|
||||||
|
if (publishFailureEvent)
|
||||||
|
{
|
||||||
|
PublishShaderBuildLifecycleEvent(
|
||||||
|
RuntimeEventShaderBuildPhase::Failed,
|
||||||
|
readyBuild.generation,
|
||||||
|
inputWidth,
|
||||||
|
inputHeight,
|
||||||
|
false,
|
||||||
|
readyBuild.message);
|
||||||
|
DispatchRuntimeEvents();
|
||||||
|
}
|
||||||
|
ApplyRuntimeCoordinatorResult(mRuntimeCoordinator.HandlePreparedShaderBuildFailure(readyBuild.message));
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (publishPreparedEvent)
|
||||||
|
{
|
||||||
|
PublishShaderBuildLifecycleEvent(
|
||||||
|
RuntimeEventShaderBuildPhase::Prepared,
|
||||||
|
readyBuild.generation,
|
||||||
|
inputWidth,
|
||||||
|
inputHeight,
|
||||||
|
true,
|
||||||
|
readyBuild.message);
|
||||||
|
DispatchRuntimeEvents();
|
||||||
|
}
|
||||||
|
|
||||||
|
char compilerErrorMessage[1024] = {};
|
||||||
|
if (!mRenderEngine.ApplyPreparedShaderBuild(
|
||||||
|
readyBuild,
|
||||||
|
inputWidth,
|
||||||
|
inputHeight,
|
||||||
|
mRuntimeCoordinator.PreserveFeedbackOnNextShaderBuild(),
|
||||||
|
sizeof(compilerErrorMessage),
|
||||||
|
compilerErrorMessage))
|
||||||
|
{
|
||||||
|
const std::string errorMessage = compilerErrorMessage;
|
||||||
|
if (publishFailureEvent)
|
||||||
|
{
|
||||||
|
PublishShaderBuildLifecycleEvent(
|
||||||
|
RuntimeEventShaderBuildPhase::Failed,
|
||||||
|
readyBuild.generation,
|
||||||
|
inputWidth,
|
||||||
|
inputHeight,
|
||||||
|
false,
|
||||||
|
errorMessage);
|
||||||
|
DispatchRuntimeEvents();
|
||||||
|
}
|
||||||
|
ApplyRuntimeCoordinatorResult(mRuntimeCoordinator.HandlePreparedShaderBuildFailure(errorMessage));
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
PublishShaderBuildLifecycleEvent(
|
||||||
|
RuntimeEventShaderBuildPhase::Applied,
|
||||||
|
readyBuild.generation,
|
||||||
|
inputWidth,
|
||||||
|
inputHeight,
|
||||||
|
true,
|
||||||
|
"Shader layers applied successfully.");
|
||||||
|
ApplyRuntimeCoordinatorResult(mRuntimeCoordinator.HandlePreparedShaderBuildSuccess());
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void RuntimeUpdateController::PublishShaderBuildLifecycleEvent(
|
||||||
|
RuntimeEventShaderBuildPhase phase,
|
||||||
|
uint64_t generation,
|
||||||
|
unsigned inputWidth,
|
||||||
|
unsigned inputHeight,
|
||||||
|
bool succeeded,
|
||||||
|
const std::string& message)
|
||||||
|
{
|
||||||
|
ShaderBuildEvent event;
|
||||||
|
event.phase = phase;
|
||||||
|
event.generation = generation;
|
||||||
|
event.inputWidth = inputWidth;
|
||||||
|
event.inputHeight = inputHeight;
|
||||||
|
event.preserveFeedbackState = mRuntimeCoordinator.PreserveFeedbackOnNextShaderBuild();
|
||||||
|
event.succeeded = succeeded;
|
||||||
|
event.message = message;
|
||||||
|
mRuntimeEventDispatcher.PublishPayload(event, "RuntimeUpdateController");
|
||||||
|
}
|
||||||
|
|
||||||
|
bool RuntimeUpdateController::ShouldSuppressCoordinatorFollowUp(const RuntimeEvent& event, std::size_t& pendingSuppressions)
|
||||||
|
{
|
||||||
|
if (event.source != "RuntimeCoordinator")
|
||||||
|
return false;
|
||||||
|
|
||||||
|
if (pendingSuppressions > 0)
|
||||||
|
--pendingSuppressions;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
RuntimeEventDispatchResult RuntimeUpdateController::DispatchRuntimeEvents(std::size_t maxEvents)
|
||||||
|
{
|
||||||
|
RuntimeEventDispatchResult result = mRuntimeEventDispatcher.DispatchPending(maxEvents);
|
||||||
|
const RuntimeEventQueueMetrics queueMetrics = mRuntimeEventDispatcher.GetQueueMetrics();
|
||||||
|
HealthTelemetry& telemetry = mRuntimeStore.GetHealthTelemetry();
|
||||||
|
telemetry.TryRecordRuntimeEventDispatchStats(
|
||||||
|
result.dispatchedEvents,
|
||||||
|
result.handlerInvocations,
|
||||||
|
result.handlerFailures,
|
||||||
|
result.dispatchDurationMilliseconds);
|
||||||
|
telemetry.TryRecordRuntimeEventQueueMetrics(
|
||||||
|
"runtime-events",
|
||||||
|
queueMetrics.depth,
|
||||||
|
queueMetrics.capacity,
|
||||||
|
static_cast<uint64_t>(queueMetrics.droppedCount),
|
||||||
|
queueMetrics.oldestEventAgeMilliseconds);
|
||||||
|
PublishRuntimeEventHealthObservations(result);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
void RuntimeUpdateController::PublishRuntimeEventHealthObservations(const RuntimeEventDispatchResult& result)
|
||||||
|
{
|
||||||
|
const RuntimeEventQueueMetrics queueMetrics = mRuntimeEventDispatcher.GetQueueMetrics();
|
||||||
|
if (queueMetrics.depth != mLastReportedRuntimeEventQueueDepth ||
|
||||||
|
queueMetrics.droppedCount != mLastReportedRuntimeEventDroppedCount ||
|
||||||
|
queueMetrics.coalescedCount != mLastReportedRuntimeEventCoalescedCount)
|
||||||
|
{
|
||||||
|
QueueDepthChangedEvent queueDepth;
|
||||||
|
queueDepth.queueName = "runtime-events";
|
||||||
|
queueDepth.depth = queueMetrics.depth;
|
||||||
|
queueDepth.capacity = queueMetrics.capacity;
|
||||||
|
queueDepth.droppedCount = queueMetrics.droppedCount;
|
||||||
|
queueDepth.coalescedCount = queueMetrics.coalescedCount;
|
||||||
|
mRuntimeEventDispatcher.PublishPayload(queueDepth, "HealthTelemetry");
|
||||||
|
mLastReportedRuntimeEventQueueDepth = queueMetrics.depth;
|
||||||
|
mLastReportedRuntimeEventDroppedCount = queueMetrics.droppedCount;
|
||||||
|
mLastReportedRuntimeEventCoalescedCount = queueMetrics.coalescedCount;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result.handlerInvocations == 0 && result.handlerFailures == 0)
|
||||||
|
return;
|
||||||
|
|
||||||
|
TimingSampleRecordedEvent timing;
|
||||||
|
timing.subsystem = "RuntimeEventDispatcher";
|
||||||
|
timing.metric = "dispatchDuration";
|
||||||
|
timing.value = result.dispatchDurationMilliseconds;
|
||||||
|
timing.unit = "ms";
|
||||||
|
mRuntimeEventDispatcher.PublishPayload(timing, "HealthTelemetry");
|
||||||
|
}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "RuntimeCoordinator.h"
|
||||||
|
#include "RuntimeEventPayloads.h"
|
||||||
|
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
class RenderEngine;
|
||||||
|
struct RuntimeEvent;
|
||||||
|
struct RuntimeEventDispatchResult;
|
||||||
|
class RuntimeEventDispatcher;
|
||||||
|
class RuntimeServices;
|
||||||
|
class RuntimeStore;
|
||||||
|
class ShaderBuildQueue;
|
||||||
|
class VideoBackend;
|
||||||
|
|
||||||
|
class RuntimeUpdateController
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
RuntimeUpdateController(
|
||||||
|
RuntimeStore& runtimeStore,
|
||||||
|
RuntimeCoordinator& runtimeCoordinator,
|
||||||
|
RuntimeEventDispatcher& runtimeEventDispatcher,
|
||||||
|
RuntimeServices& runtimeServices,
|
||||||
|
RenderEngine& renderEngine,
|
||||||
|
ShaderBuildQueue& shaderBuildQueue,
|
||||||
|
VideoBackend& videoBackend);
|
||||||
|
|
||||||
|
bool ApplyRuntimeCoordinatorResult(const RuntimeCoordinatorResult& result, std::string* error = nullptr);
|
||||||
|
bool ProcessRuntimeWork();
|
||||||
|
void RequestShaderBuild();
|
||||||
|
void BroadcastRuntimeState();
|
||||||
|
|
||||||
|
private:
|
||||||
|
void HandleRuntimeStateBroadcastRequested(const RuntimeEvent& event);
|
||||||
|
void HandleRuntimeReloadRequested(const RuntimeEvent& event);
|
||||||
|
void HandleRuntimePersistenceRequested(const RuntimeEvent& event);
|
||||||
|
void HandleShaderBuildRequested(const RuntimeEvent& event);
|
||||||
|
void HandleShaderBuildPrepared(const RuntimeEvent& event);
|
||||||
|
void HandleShaderBuildFailed(const RuntimeEvent& event);
|
||||||
|
void HandleCompileStatusChanged(const RuntimeEvent& event);
|
||||||
|
void HandleRenderResetRequested(const RuntimeEvent& event);
|
||||||
|
bool ConsumeReadyShaderBuild(uint64_t expectedGeneration, bool publishPreparedEvent, bool publishFailureEvent);
|
||||||
|
void PublishShaderBuildLifecycleEvent(
|
||||||
|
RuntimeEventShaderBuildPhase phase,
|
||||||
|
uint64_t generation,
|
||||||
|
unsigned inputWidth,
|
||||||
|
unsigned inputHeight,
|
||||||
|
bool succeeded,
|
||||||
|
const std::string& message);
|
||||||
|
bool ShouldSuppressCoordinatorFollowUp(const RuntimeEvent& event, std::size_t& pendingSuppressions);
|
||||||
|
RuntimeEventDispatchResult DispatchRuntimeEvents(std::size_t maxEvents = 0);
|
||||||
|
void PublishRuntimeEventHealthObservations(const RuntimeEventDispatchResult& result);
|
||||||
|
|
||||||
|
RuntimeStore& mRuntimeStore;
|
||||||
|
RuntimeCoordinator& mRuntimeCoordinator;
|
||||||
|
RuntimeEventDispatcher& mRuntimeEventDispatcher;
|
||||||
|
RuntimeServices& mRuntimeServices;
|
||||||
|
RenderEngine& mRenderEngine;
|
||||||
|
ShaderBuildQueue& mShaderBuildQueue;
|
||||||
|
VideoBackend& mVideoBackend;
|
||||||
|
std::size_t mPendingCoordinatorShaderBuildEvents = 0;
|
||||||
|
std::size_t mPendingCoordinatorCompileStatusEvents = 0;
|
||||||
|
std::size_t mPendingCoordinatorRenderResetEvents = 0;
|
||||||
|
std::size_t mLastReportedRuntimeEventQueueDepth = static_cast<std::size_t>(-1);
|
||||||
|
std::size_t mLastReportedRuntimeEventDroppedCount = static_cast<std::size_t>(-1);
|
||||||
|
std::size_t mLastReportedRuntimeEventCoalescedCount = static_cast<std::size_t>(-1);
|
||||||
|
};
|
||||||
@@ -0,0 +1,288 @@
|
|||||||
|
#include "OpenGLRenderPass.h"
|
||||||
|
|
||||||
|
#include "GlRenderConstants.h"
|
||||||
|
|
||||||
|
#include <map>
|
||||||
|
|
||||||
|
OpenGLRenderPass::OpenGLRenderPass(OpenGLRenderer& renderer) :
|
||||||
|
mRenderer(renderer)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
void OpenGLRenderPass::Render(
|
||||||
|
bool hasInputSource,
|
||||||
|
const std::vector<RuntimeRenderState>& layerStates,
|
||||||
|
unsigned inputFrameWidth,
|
||||||
|
unsigned inputFrameHeight,
|
||||||
|
unsigned captureTextureWidth,
|
||||||
|
VideoIOPixelFormat inputPixelFormat,
|
||||||
|
unsigned historyCap,
|
||||||
|
const TextBindingUpdater& updateTextBinding,
|
||||||
|
const GlobalParamsUpdater& updateGlobalParams)
|
||||||
|
{
|
||||||
|
glDisable(GL_SCISSOR_TEST);
|
||||||
|
glDisable(GL_BLEND);
|
||||||
|
glDisable(GL_DEPTH_TEST);
|
||||||
|
if (hasInputSource)
|
||||||
|
{
|
||||||
|
RenderDecodePass(inputFrameWidth, inputFrameHeight, captureTextureWidth, inputPixelFormat);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
glBindFramebuffer(GL_FRAMEBUFFER, mRenderer.DecodeFramebuffer());
|
||||||
|
glViewport(0, 0, inputFrameWidth, inputFrameHeight);
|
||||||
|
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
|
||||||
|
glClear(GL_COLOR_BUFFER_BIT);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<LayerProgram>& layerPrograms = mRenderer.LayerPrograms();
|
||||||
|
if (layerStates.empty() || layerPrograms.empty())
|
||||||
|
{
|
||||||
|
glBindFramebuffer(GL_READ_FRAMEBUFFER, mRenderer.DecodeFramebuffer());
|
||||||
|
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, mRenderer.CompositeFramebuffer());
|
||||||
|
glBlitFramebuffer(0, 0, inputFrameWidth, inputFrameHeight, 0, 0, inputFrameWidth, inputFrameHeight, GL_COLOR_BUFFER_BIT, GL_LINEAR);
|
||||||
|
glBindFramebuffer(GL_FRAMEBUFFER, mRenderer.CompositeFramebuffer());
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
const std::vector<RenderPassDescriptor>& passes = BuildLayerPassDescriptors(layerStates, layerPrograms);
|
||||||
|
for (const RenderPassDescriptor& pass : passes)
|
||||||
|
{
|
||||||
|
RenderLayerPass(
|
||||||
|
pass,
|
||||||
|
inputFrameWidth,
|
||||||
|
inputFrameHeight,
|
||||||
|
historyCap,
|
||||||
|
updateTextBinding,
|
||||||
|
updateGlobalParams);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
mRenderer.TemporalHistory().PushSourceFramebuffer(mRenderer.DecodeFramebuffer(), inputFrameWidth, inputFrameHeight);
|
||||||
|
mRenderer.FeedbackBuffers().FinalizeFrame();
|
||||||
|
}
|
||||||
|
|
||||||
|
void OpenGLRenderPass::RenderDecodePass(unsigned inputFrameWidth, unsigned inputFrameHeight, unsigned captureTextureWidth, VideoIOPixelFormat inputPixelFormat)
|
||||||
|
{
|
||||||
|
glBindFramebuffer(GL_FRAMEBUFFER, mRenderer.DecodeFramebuffer());
|
||||||
|
glViewport(0, 0, inputFrameWidth, inputFrameHeight);
|
||||||
|
glClear(GL_COLOR_BUFFER_BIT);
|
||||||
|
glActiveTexture(GL_TEXTURE0 + kPackedVideoTextureUnit);
|
||||||
|
glBindTexture(GL_TEXTURE_2D, mRenderer.CaptureTexture());
|
||||||
|
glBindVertexArray(mRenderer.FullscreenVertexArray());
|
||||||
|
glUseProgram(mRenderer.DecodeProgram());
|
||||||
|
|
||||||
|
const GLint packedResolutionLocation = mRenderer.DecodePackedResolutionLocation();
|
||||||
|
const GLint decodedResolutionLocation = mRenderer.DecodeDecodedResolutionLocation();
|
||||||
|
const GLint inputPixelFormatLocation = mRenderer.DecodeInputPixelFormatLocation();
|
||||||
|
if (packedResolutionLocation >= 0)
|
||||||
|
glUniform2f(packedResolutionLocation, static_cast<float>(captureTextureWidth), static_cast<float>(inputFrameHeight));
|
||||||
|
if (decodedResolutionLocation >= 0)
|
||||||
|
glUniform2f(decodedResolutionLocation, static_cast<float>(inputFrameWidth), static_cast<float>(inputFrameHeight));
|
||||||
|
if (inputPixelFormatLocation >= 0)
|
||||||
|
glUniform1i(inputPixelFormatLocation, inputPixelFormat == VideoIOPixelFormat::V210 ? 1 : 0);
|
||||||
|
|
||||||
|
glDrawArrays(GL_TRIANGLES, 0, 3);
|
||||||
|
|
||||||
|
glUseProgram(0);
|
||||||
|
glBindVertexArray(0);
|
||||||
|
glBindTexture(GL_TEXTURE_2D, 0);
|
||||||
|
glActiveTexture(GL_TEXTURE0);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<RenderPassDescriptor> OpenGLRenderPass::BuildLayerPassDescriptors(
|
||||||
|
const std::vector<RuntimeRenderState>& layerStates,
|
||||||
|
std::vector<LayerProgram>& layerPrograms) const
|
||||||
|
{
|
||||||
|
// Flatten the layer stack into concrete GL passes. A layer may now contain
|
||||||
|
// several shader passes, but the outer stack still sees one visible output
|
||||||
|
// per layer.
|
||||||
|
std::vector<RenderPassDescriptor>& passes = mPassScratch;
|
||||||
|
passes.clear();
|
||||||
|
const std::size_t passCount = layerStates.size() < layerPrograms.size() ? layerStates.size() : layerPrograms.size();
|
||||||
|
std::size_t descriptorCount = 0;
|
||||||
|
for (std::size_t index = 0; index < passCount; ++index)
|
||||||
|
descriptorCount += layerPrograms[index].passes.size();
|
||||||
|
passes.reserve(descriptorCount);
|
||||||
|
|
||||||
|
GLuint sourceTexture = mRenderer.DecodedTexture();
|
||||||
|
GLuint sourceFramebuffer = mRenderer.DecodeFramebuffer();
|
||||||
|
for (std::size_t index = 0; index < passCount; ++index)
|
||||||
|
{
|
||||||
|
const RuntimeRenderState& state = layerStates[index];
|
||||||
|
LayerProgram& layerProgram = layerPrograms[index];
|
||||||
|
if (layerProgram.passes.empty())
|
||||||
|
continue;
|
||||||
|
|
||||||
|
// Preserve the original two-target layer ping-pong. Intermediate passes
|
||||||
|
// inside this layer are routed through pooled temporary targets instead.
|
||||||
|
const std::size_t remaining = layerStates.size() - index;
|
||||||
|
const bool writeToMain = (remaining % 2) == 1;
|
||||||
|
const GLuint layerOutputTexture = writeToMain ? mRenderer.CompositeTexture() : mRenderer.LayerTempTexture();
|
||||||
|
const GLuint layerOutputFramebuffer = writeToMain ? mRenderer.CompositeFramebuffer() : mRenderer.LayerTempFramebuffer();
|
||||||
|
const RenderPassOutputTarget layerOutputTarget = writeToMain ? RenderPassOutputTarget::Composite : RenderPassOutputTarget::LayerTemp;
|
||||||
|
|
||||||
|
const GLuint layerInputTexture = sourceTexture;
|
||||||
|
const GLuint layerInputFramebuffer = sourceFramebuffer;
|
||||||
|
GLuint previousPassTexture = layerInputTexture;
|
||||||
|
GLuint previousPassFramebuffer = layerInputFramebuffer;
|
||||||
|
std::map<std::string, std::pair<GLuint, GLuint>> namedOutputs;
|
||||||
|
std::size_t temporaryTargetIndex = 0;
|
||||||
|
|
||||||
|
for (std::size_t passIndex = 0; passIndex < layerProgram.passes.size(); ++passIndex)
|
||||||
|
{
|
||||||
|
PassProgram& passProgram = layerProgram.passes[passIndex];
|
||||||
|
const bool lastPassForLayer = passIndex + 1 == layerProgram.passes.size();
|
||||||
|
const std::string outputName = passProgram.outputName.empty() ? passProgram.passId : passProgram.outputName;
|
||||||
|
const bool writesLayerOutput = outputName == "layerOutput" || lastPassForLayer;
|
||||||
|
|
||||||
|
GLuint passSourceTexture = previousPassTexture;
|
||||||
|
GLuint passSourceFramebuffer = previousPassFramebuffer;
|
||||||
|
if (!passProgram.inputNames.empty())
|
||||||
|
{
|
||||||
|
// v1 multipass uses the first declared input as gVideoInput.
|
||||||
|
// Later inputs are parsed for forward compatibility.
|
||||||
|
const std::string& inputName = passProgram.inputNames.front();
|
||||||
|
if (inputName == "layerInput")
|
||||||
|
{
|
||||||
|
passSourceTexture = layerInputTexture;
|
||||||
|
passSourceFramebuffer = layerInputFramebuffer;
|
||||||
|
}
|
||||||
|
else if (inputName == "previousPass")
|
||||||
|
{
|
||||||
|
passSourceTexture = previousPassTexture;
|
||||||
|
passSourceFramebuffer = previousPassFramebuffer;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
auto namedOutputIt = namedOutputs.find(inputName);
|
||||||
|
if (namedOutputIt != namedOutputs.end())
|
||||||
|
{
|
||||||
|
passSourceTexture = namedOutputIt->second.first;
|
||||||
|
passSourceFramebuffer = namedOutputIt->second.second;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
GLuint passDestinationTexture = layerOutputTexture;
|
||||||
|
GLuint passDestinationFramebuffer = layerOutputFramebuffer;
|
||||||
|
RenderPassOutputTarget outputTarget = layerOutputTarget;
|
||||||
|
if (!writesLayerOutput)
|
||||||
|
{
|
||||||
|
// Temporary targets are reserved when the shader stack is
|
||||||
|
// committed, avoiding texture allocation during playback.
|
||||||
|
if (temporaryTargetIndex < mRenderer.TemporaryRenderTargetCount())
|
||||||
|
{
|
||||||
|
const RenderTarget& temporaryTarget = mRenderer.TemporaryRenderTarget(temporaryTargetIndex);
|
||||||
|
++temporaryTargetIndex;
|
||||||
|
passDestinationTexture = temporaryTarget.texture;
|
||||||
|
passDestinationFramebuffer = temporaryTarget.framebuffer;
|
||||||
|
outputTarget = RenderPassOutputTarget::Temporary;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
RenderPassDescriptor pass;
|
||||||
|
pass.kind = RenderPassKind::LayerEffect;
|
||||||
|
pass.outputTarget = outputTarget;
|
||||||
|
pass.passIndex = passes.size();
|
||||||
|
pass.passId = passProgram.passId;
|
||||||
|
pass.layerId = state.layerId;
|
||||||
|
pass.shaderId = state.shaderId;
|
||||||
|
pass.layerInputTexture = layerInputTexture;
|
||||||
|
pass.sourceTexture = passSourceTexture;
|
||||||
|
pass.sourceFramebuffer = passIndex == 0 ? layerInputFramebuffer : passSourceFramebuffer;
|
||||||
|
pass.destinationTexture = passDestinationTexture;
|
||||||
|
pass.destinationFramebuffer = passDestinationFramebuffer;
|
||||||
|
pass.layerProgram = &layerProgram;
|
||||||
|
pass.passProgram = &passProgram;
|
||||||
|
pass.layerState = &state;
|
||||||
|
pass.capturePreLayerHistory = passIndex == 0 && state.temporalHistorySource == TemporalHistorySource::PreLayerInput;
|
||||||
|
pass.captureFeedbackWrite = state.feedback.enabled && passProgram.passId == state.feedback.writePassId;
|
||||||
|
passes.push_back(pass);
|
||||||
|
|
||||||
|
// A later pass can reference either the explicit output name or the
|
||||||
|
// pass id, which keeps small manifests pleasant to write.
|
||||||
|
namedOutputs[outputName] = std::make_pair(passDestinationTexture, passDestinationFramebuffer);
|
||||||
|
namedOutputs[passProgram.passId] = std::make_pair(passDestinationTexture, passDestinationFramebuffer);
|
||||||
|
previousPassTexture = passDestinationTexture;
|
||||||
|
previousPassFramebuffer = passDestinationFramebuffer;
|
||||||
|
}
|
||||||
|
|
||||||
|
sourceTexture = layerOutputTexture;
|
||||||
|
sourceFramebuffer = layerOutputFramebuffer;
|
||||||
|
}
|
||||||
|
|
||||||
|
return passes;
|
||||||
|
}
|
||||||
|
|
||||||
|
void OpenGLRenderPass::RenderLayerPass(
|
||||||
|
const RenderPassDescriptor& pass,
|
||||||
|
unsigned inputFrameWidth,
|
||||||
|
unsigned inputFrameHeight,
|
||||||
|
unsigned historyCap,
|
||||||
|
const TextBindingUpdater& updateTextBinding,
|
||||||
|
const GlobalParamsUpdater& updateGlobalParams)
|
||||||
|
{
|
||||||
|
if (pass.passProgram == nullptr || pass.layerState == nullptr)
|
||||||
|
return;
|
||||||
|
|
||||||
|
RenderShaderProgram(
|
||||||
|
pass.layerInputTexture,
|
||||||
|
pass.sourceTexture,
|
||||||
|
pass.destinationFramebuffer,
|
||||||
|
*pass.passProgram,
|
||||||
|
*pass.layerState,
|
||||||
|
inputFrameWidth,
|
||||||
|
inputFrameHeight,
|
||||||
|
historyCap,
|
||||||
|
updateTextBinding,
|
||||||
|
updateGlobalParams);
|
||||||
|
|
||||||
|
if (pass.capturePreLayerHistory)
|
||||||
|
mRenderer.TemporalHistory().PushPreLayerFramebuffer(pass.layerId, pass.sourceFramebuffer, inputFrameWidth, inputFrameHeight);
|
||||||
|
if (pass.captureFeedbackWrite)
|
||||||
|
mRenderer.FeedbackBuffers().CaptureFeedbackFramebuffer(pass.layerId, pass.destinationFramebuffer, inputFrameWidth, inputFrameHeight);
|
||||||
|
}
|
||||||
|
|
||||||
|
void OpenGLRenderPass::RenderShaderProgram(
|
||||||
|
GLuint layerInputTexture,
|
||||||
|
GLuint sourceTexture,
|
||||||
|
GLuint destinationFrameBuffer,
|
||||||
|
PassProgram& passProgram,
|
||||||
|
const RuntimeRenderState& state,
|
||||||
|
unsigned inputFrameWidth,
|
||||||
|
unsigned inputFrameHeight,
|
||||||
|
unsigned historyCap,
|
||||||
|
const TextBindingUpdater& updateTextBinding,
|
||||||
|
const GlobalParamsUpdater& updateGlobalParams)
|
||||||
|
{
|
||||||
|
for (LayerProgram::TextBinding& textBinding : passProgram.textBindings)
|
||||||
|
{
|
||||||
|
std::string textError;
|
||||||
|
if (!updateTextBinding(state, textBinding, textError))
|
||||||
|
OutputDebugStringA((textError + "\n").c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
glBindFramebuffer(GL_FRAMEBUFFER, destinationFrameBuffer);
|
||||||
|
glViewport(0, 0, inputFrameWidth, inputFrameHeight);
|
||||||
|
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
|
||||||
|
const std::vector<GLuint> sourceHistoryTextures = mRenderer.TemporalHistory().ResolveSourceHistoryTextures(sourceTexture, state.isTemporal ? historyCap : 0);
|
||||||
|
const std::vector<GLuint> temporalHistoryTextures = mRenderer.TemporalHistory().ResolveTemporalHistoryTextures(state, sourceTexture, state.isTemporal ? historyCap : 0);
|
||||||
|
const GLuint feedbackTexture = mRenderer.FeedbackBuffers().ResolveReadTexture(state);
|
||||||
|
const ShaderTextureBindings::RuntimeTextureBindingPlan texturePlan =
|
||||||
|
mTextureBindings.BuildLayerRuntimeBindingPlan(passProgram, sourceTexture, layerInputTexture, state, feedbackTexture, sourceHistoryTextures, temporalHistoryTextures);
|
||||||
|
mTextureBindings.BindRuntimeTexturePlan(texturePlan);
|
||||||
|
glBindVertexArray(mRenderer.FullscreenVertexArray());
|
||||||
|
glUseProgram(passProgram.program);
|
||||||
|
// The UBO is shared by every pass in a layer; texture routing is what
|
||||||
|
// changes from pass to pass.
|
||||||
|
updateGlobalParams(
|
||||||
|
state,
|
||||||
|
mRenderer.TemporalHistory().SourceAvailableCount(),
|
||||||
|
mRenderer.TemporalHistory().AvailableCountForLayer(state.layerId),
|
||||||
|
mRenderer.FeedbackBuffers().FeedbackAvailable(state));
|
||||||
|
glDrawArrays(GL_TRIANGLES, 0, 3);
|
||||||
|
glUseProgram(0);
|
||||||
|
glBindVertexArray(0);
|
||||||
|
mTextureBindings.UnbindRuntimeTexturePlan(texturePlan);
|
||||||
|
}
|
||||||
@@ -1,6 +1,8 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include "OpenGLRenderer.h"
|
#include "OpenGLRenderer.h"
|
||||||
|
#include "RenderPassDescriptor.h"
|
||||||
|
#include "ShaderTextureBindings.h"
|
||||||
#include "ShaderTypes.h"
|
#include "ShaderTypes.h"
|
||||||
#include "VideoIOFormat.h"
|
#include "VideoIOFormat.h"
|
||||||
|
|
||||||
@@ -12,8 +14,9 @@ class OpenGLRenderPass
|
|||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
using LayerProgram = OpenGLRenderer::LayerProgram;
|
using LayerProgram = OpenGLRenderer::LayerProgram;
|
||||||
|
using PassProgram = OpenGLRenderer::LayerProgram::PassProgram;
|
||||||
using TextBindingUpdater = std::function<bool(const RuntimeRenderState&, LayerProgram::TextBinding&, std::string&)>;
|
using TextBindingUpdater = std::function<bool(const RuntimeRenderState&, LayerProgram::TextBinding&, std::string&)>;
|
||||||
using GlobalParamsUpdater = std::function<bool(const RuntimeRenderState&, unsigned, unsigned)>;
|
using GlobalParamsUpdater = std::function<bool(const RuntimeRenderState&, unsigned, unsigned, bool)>;
|
||||||
|
|
||||||
explicit OpenGLRenderPass(OpenGLRenderer& renderer);
|
explicit OpenGLRenderPass(OpenGLRenderer& renderer);
|
||||||
|
|
||||||
@@ -30,18 +33,29 @@ public:
|
|||||||
|
|
||||||
private:
|
private:
|
||||||
void RenderDecodePass(unsigned inputFrameWidth, unsigned inputFrameHeight, unsigned captureTextureWidth, VideoIOPixelFormat inputPixelFormat);
|
void RenderDecodePass(unsigned inputFrameWidth, unsigned inputFrameHeight, unsigned captureTextureWidth, VideoIOPixelFormat inputPixelFormat);
|
||||||
|
std::vector<RenderPassDescriptor> BuildLayerPassDescriptors(
|
||||||
|
const std::vector<RuntimeRenderState>& layerStates,
|
||||||
|
std::vector<LayerProgram>& layerPrograms) const;
|
||||||
|
void RenderLayerPass(
|
||||||
|
const RenderPassDescriptor& pass,
|
||||||
|
unsigned inputFrameWidth,
|
||||||
|
unsigned inputFrameHeight,
|
||||||
|
unsigned historyCap,
|
||||||
|
const TextBindingUpdater& updateTextBinding,
|
||||||
|
const GlobalParamsUpdater& updateGlobalParams);
|
||||||
void RenderShaderProgram(
|
void RenderShaderProgram(
|
||||||
|
GLuint layerInputTexture,
|
||||||
GLuint sourceTexture,
|
GLuint sourceTexture,
|
||||||
GLuint destinationFrameBuffer,
|
GLuint destinationFrameBuffer,
|
||||||
LayerProgram& layerProgram,
|
PassProgram& passProgram,
|
||||||
const RuntimeRenderState& state,
|
const RuntimeRenderState& state,
|
||||||
unsigned inputFrameWidth,
|
unsigned inputFrameWidth,
|
||||||
unsigned inputFrameHeight,
|
unsigned inputFrameHeight,
|
||||||
unsigned historyCap,
|
unsigned historyCap,
|
||||||
const TextBindingUpdater& updateTextBinding,
|
const TextBindingUpdater& updateTextBinding,
|
||||||
const GlobalParamsUpdater& updateGlobalParams);
|
const GlobalParamsUpdater& updateGlobalParams);
|
||||||
void BindLayerTextureAssets(const LayerProgram& layerProgram);
|
|
||||||
void UnbindLayerTextureAssets(const LayerProgram& layerProgram, unsigned historyCap);
|
|
||||||
|
|
||||||
OpenGLRenderer& mRenderer;
|
OpenGLRenderer& mRenderer;
|
||||||
|
ShaderTextureBindings mTextureBindings;
|
||||||
|
mutable std::vector<RenderPassDescriptor> mPassScratch;
|
||||||
};
|
};
|
||||||
@@ -0,0 +1,479 @@
|
|||||||
|
#include "OpenGLRenderPipeline.h"
|
||||||
|
|
||||||
|
#include "HealthTelemetry.h"
|
||||||
|
#include "OpenGLRenderer.h"
|
||||||
|
#include "RuntimeSnapshotProvider.h"
|
||||||
|
#include "VideoIOFormat.h"
|
||||||
|
|
||||||
|
#include <cstring>
|
||||||
|
|
||||||
|
#include <chrono>
|
||||||
|
#include <cstdlib>
|
||||||
|
#include <gl/gl.h>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
OpenGLRenderPipeline::OpenGLRenderPipeline(
|
||||||
|
OpenGLRenderer& renderer,
|
||||||
|
RuntimeSnapshotProvider& runtimeSnapshotProvider,
|
||||||
|
HealthTelemetry& healthTelemetry,
|
||||||
|
RenderEffectCallback renderEffect,
|
||||||
|
OutputReadyCallback outputReady,
|
||||||
|
PaintCallback paint) :
|
||||||
|
mRenderer(renderer),
|
||||||
|
mRuntimeSnapshotProvider(runtimeSnapshotProvider),
|
||||||
|
mHealthTelemetry(healthTelemetry),
|
||||||
|
mRenderEffect(renderEffect),
|
||||||
|
mOutputReady(outputReady),
|
||||||
|
mPaint(paint),
|
||||||
|
mOutputReadbackMode(ReadOutputReadbackModeFromEnvironment()),
|
||||||
|
mAsyncReadbackDepth(ReadAsyncReadbackDepthFromEnvironment())
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
OpenGLRenderPipeline::~OpenGLRenderPipeline()
|
||||||
|
{
|
||||||
|
ResetAsyncReadbackState();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool OpenGLRenderPipeline::RenderFrame(const RenderPipelineFrameContext& context, VideoIOOutputFrame& outputFrame)
|
||||||
|
{
|
||||||
|
const VideoIOState& state = context.videoState;
|
||||||
|
|
||||||
|
const auto renderStartTime = std::chrono::steady_clock::now();
|
||||||
|
glBindFramebuffer(GL_FRAMEBUFFER, mRenderer.CompositeFramebuffer());
|
||||||
|
mRenderEffect();
|
||||||
|
glBindFramebuffer(GL_READ_FRAMEBUFFER, mRenderer.CompositeFramebuffer());
|
||||||
|
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, mRenderer.OutputFramebuffer());
|
||||||
|
glBlitFramebuffer(0, 0, state.inputFrameSize.width, state.inputFrameSize.height, 0, 0, state.outputFrameSize.width, state.outputFrameSize.height, GL_COLOR_BUFFER_BIT, GL_LINEAR);
|
||||||
|
glBindFramebuffer(GL_FRAMEBUFFER, mRenderer.OutputFramebuffer());
|
||||||
|
if (mOutputReady)
|
||||||
|
mOutputReady();
|
||||||
|
if (state.outputPixelFormat == VideoIOPixelFormat::Bgra8)
|
||||||
|
PackOutputForBgra8(state);
|
||||||
|
else if (state.outputPixelFormat == VideoIOPixelFormat::V210 || state.outputPixelFormat == VideoIOPixelFormat::Yuva10)
|
||||||
|
PackOutputFor10Bit(state);
|
||||||
|
glFlush();
|
||||||
|
|
||||||
|
const auto renderEndTime = std::chrono::steady_clock::now();
|
||||||
|
const double renderMilliseconds = std::chrono::duration_cast<std::chrono::duration<double, std::milli>>(renderEndTime - renderStartTime).count();
|
||||||
|
mHealthTelemetry.TryRecordPerformanceStats(state.frameBudgetMilliseconds, renderMilliseconds);
|
||||||
|
mRuntimeSnapshotProvider.AdvanceFrame();
|
||||||
|
|
||||||
|
OutputReadbackTiming readbackTiming = ReadOutputFrame(state, outputFrame);
|
||||||
|
mHealthTelemetry.TryRecordOutputRenderPipelineTiming(
|
||||||
|
renderMilliseconds,
|
||||||
|
readbackTiming.fenceWaitMilliseconds,
|
||||||
|
readbackTiming.mapMilliseconds,
|
||||||
|
readbackTiming.copyMilliseconds,
|
||||||
|
readbackTiming.cachedCopyMilliseconds,
|
||||||
|
readbackTiming.asyncQueueMilliseconds,
|
||||||
|
readbackTiming.asyncQueueBufferMilliseconds,
|
||||||
|
readbackTiming.asyncQueueSetupMilliseconds,
|
||||||
|
readbackTiming.asyncQueueReadPixelsMilliseconds,
|
||||||
|
readbackTiming.asyncQueueFenceMilliseconds,
|
||||||
|
readbackTiming.syncReadMilliseconds,
|
||||||
|
readbackTiming.asyncReadbackMissed,
|
||||||
|
readbackTiming.cachedFallbackUsed,
|
||||||
|
readbackTiming.syncFallbackUsed);
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void OpenGLRenderPipeline::PackOutputForBgra8(const VideoIOState& state)
|
||||||
|
{
|
||||||
|
glBindFramebuffer(GL_READ_FRAMEBUFFER, mRenderer.OutputFramebuffer());
|
||||||
|
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, mRenderer.OutputPackFramebuffer());
|
||||||
|
glBlitFramebuffer(
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
state.outputFrameSize.width,
|
||||||
|
state.outputFrameSize.height,
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
state.outputFrameSize.width,
|
||||||
|
state.outputFrameSize.height,
|
||||||
|
GL_COLOR_BUFFER_BIT,
|
||||||
|
GL_NEAREST);
|
||||||
|
glBindFramebuffer(GL_FRAMEBUFFER, mRenderer.OutputPackFramebuffer());
|
||||||
|
}
|
||||||
|
|
||||||
|
void OpenGLRenderPipeline::PackOutputFor10Bit(const VideoIOState& state)
|
||||||
|
{
|
||||||
|
glBindFramebuffer(GL_FRAMEBUFFER, mRenderer.OutputPackFramebuffer());
|
||||||
|
glViewport(0, 0, state.outputPackTextureWidth, state.outputFrameSize.height);
|
||||||
|
glDisable(GL_SCISSOR_TEST);
|
||||||
|
glDisable(GL_BLEND);
|
||||||
|
glDisable(GL_DEPTH_TEST);
|
||||||
|
glActiveTexture(GL_TEXTURE0);
|
||||||
|
glBindTexture(GL_TEXTURE_2D, mRenderer.OutputTexture());
|
||||||
|
glBindVertexArray(mRenderer.FullscreenVertexArray());
|
||||||
|
glUseProgram(mRenderer.OutputPackProgram());
|
||||||
|
|
||||||
|
const GLint outputResolutionLocation = mRenderer.OutputPackResolutionLocation();
|
||||||
|
const GLint activeWordsLocation = mRenderer.OutputPackActiveWordsLocation();
|
||||||
|
const GLint packFormatLocation = mRenderer.OutputPackFormatLocation();
|
||||||
|
if (outputResolutionLocation >= 0)
|
||||||
|
glUniform2f(outputResolutionLocation, static_cast<float>(state.outputFrameSize.width), static_cast<float>(state.outputFrameSize.height));
|
||||||
|
if (activeWordsLocation >= 0)
|
||||||
|
glUniform1f(activeWordsLocation, static_cast<float>(ActiveV210WordsForWidth(state.outputFrameSize.width)));
|
||||||
|
if (packFormatLocation >= 0)
|
||||||
|
glUniform1i(packFormatLocation, state.outputPixelFormat == VideoIOPixelFormat::Yuva10 ? 2 : 1);
|
||||||
|
|
||||||
|
glDrawArrays(GL_TRIANGLES, 0, 3);
|
||||||
|
glUseProgram(0);
|
||||||
|
glBindVertexArray(0);
|
||||||
|
glBindTexture(GL_TEXTURE_2D, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool OpenGLRenderPipeline::EnsureAsyncReadbackBuffers(std::size_t requiredBytes)
|
||||||
|
{
|
||||||
|
if (requiredBytes == 0)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
if (mAsyncReadbackBytes == requiredBytes &&
|
||||||
|
mAsyncReadbackSlots.size() == mAsyncReadbackDepth &&
|
||||||
|
!mAsyncReadbackSlots.empty() &&
|
||||||
|
mAsyncReadbackSlots[0].pixelPackBuffer != 0)
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
ResetAsyncReadbackState();
|
||||||
|
mAsyncReadbackBytes = requiredBytes;
|
||||||
|
mAsyncReadbackSlots.resize(mAsyncReadbackDepth);
|
||||||
|
for (AsyncReadbackSlot& slot : mAsyncReadbackSlots)
|
||||||
|
{
|
||||||
|
glGenBuffers(1, &slot.pixelPackBuffer);
|
||||||
|
glBindBuffer(GL_PIXEL_PACK_BUFFER, slot.pixelPackBuffer);
|
||||||
|
glBufferData(GL_PIXEL_PACK_BUFFER, static_cast<GLsizeiptr>(requiredBytes), nullptr, GL_STREAM_READ);
|
||||||
|
slot.sizeBytes = requiredBytes;
|
||||||
|
slot.inFlight = false;
|
||||||
|
}
|
||||||
|
glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
|
||||||
|
mAsyncReadbackWriteIndex = 0;
|
||||||
|
mAsyncReadbackReadIndex = 0;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void OpenGLRenderPipeline::ResetAsyncReadbackState()
|
||||||
|
{
|
||||||
|
FlushAsyncReadbackPipeline();
|
||||||
|
for (AsyncReadbackSlot& slot : mAsyncReadbackSlots)
|
||||||
|
slot.sizeBytes = 0;
|
||||||
|
|
||||||
|
if (!mAsyncReadbackSlots.empty() && mAsyncReadbackSlots[0].pixelPackBuffer != 0)
|
||||||
|
{
|
||||||
|
for (AsyncReadbackSlot& slot : mAsyncReadbackSlots)
|
||||||
|
{
|
||||||
|
if (slot.pixelPackBuffer != 0)
|
||||||
|
{
|
||||||
|
glDeleteBuffers(1, &slot.pixelPackBuffer);
|
||||||
|
slot.pixelPackBuffer = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
mAsyncReadbackWriteIndex = 0;
|
||||||
|
mAsyncReadbackReadIndex = 0;
|
||||||
|
mAsyncReadbackBytes = 0;
|
||||||
|
mAsyncReadbackSlots.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
void OpenGLRenderPipeline::FlushAsyncReadbackPipeline()
|
||||||
|
{
|
||||||
|
for (AsyncReadbackSlot& slot : mAsyncReadbackSlots)
|
||||||
|
{
|
||||||
|
if (slot.fence != nullptr)
|
||||||
|
{
|
||||||
|
glDeleteSync(slot.fence);
|
||||||
|
slot.fence = nullptr;
|
||||||
|
}
|
||||||
|
slot.inFlight = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
mAsyncReadbackWriteIndex = 0;
|
||||||
|
mAsyncReadbackReadIndex = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool OpenGLRenderPipeline::QueueAsyncReadback(const VideoIOState& state, OutputReadbackTiming& timing)
|
||||||
|
{
|
||||||
|
const auto queueStartTime = std::chrono::steady_clock::now();
|
||||||
|
const bool useTenBitPackedOutput = state.outputPixelFormat == VideoIOPixelFormat::V210 ||
|
||||||
|
state.outputPixelFormat == VideoIOPixelFormat::Yuva10;
|
||||||
|
const bool usePackFramebuffer = state.outputPixelFormat == VideoIOPixelFormat::Bgra8 || useTenBitPackedOutput;
|
||||||
|
const std::size_t requiredBytes = static_cast<std::size_t>(state.outputFrameRowBytes) * state.outputFrameSize.height;
|
||||||
|
const GLenum format = useTenBitPackedOutput ? GL_RGBA : GL_BGRA;
|
||||||
|
const GLenum type = useTenBitPackedOutput ? GL_UNSIGNED_BYTE : GL_UNSIGNED_INT_8_8_8_8_REV;
|
||||||
|
const GLuint framebuffer = usePackFramebuffer ? mRenderer.OutputPackFramebuffer() : mRenderer.OutputFramebuffer();
|
||||||
|
const GLsizei readWidth = static_cast<GLsizei>(useTenBitPackedOutput ? state.outputPackTextureWidth : state.outputFrameSize.width);
|
||||||
|
const GLsizei readHeight = static_cast<GLsizei>(state.outputFrameSize.height);
|
||||||
|
|
||||||
|
const auto finishTiming = [&timing, queueStartTime]() {
|
||||||
|
const auto queueEndTime = std::chrono::steady_clock::now();
|
||||||
|
timing.asyncQueueMilliseconds += std::chrono::duration_cast<std::chrono::duration<double, std::milli>>(queueEndTime - queueStartTime).count();
|
||||||
|
};
|
||||||
|
|
||||||
|
if (requiredBytes == 0)
|
||||||
|
{
|
||||||
|
finishTiming();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mAsyncReadbackBytes != requiredBytes
|
||||||
|
|| mAsyncReadbackFormat != format
|
||||||
|
|| mAsyncReadbackType != type
|
||||||
|
|| mAsyncReadbackFramebuffer != framebuffer)
|
||||||
|
{
|
||||||
|
mAsyncReadbackFormat = format;
|
||||||
|
mAsyncReadbackType = type;
|
||||||
|
mAsyncReadbackFramebuffer = framebuffer;
|
||||||
|
if (!EnsureAsyncReadbackBuffers(requiredBytes))
|
||||||
|
{
|
||||||
|
finishTiming();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mAsyncReadbackSlots.empty())
|
||||||
|
{
|
||||||
|
finishTiming();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
AsyncReadbackSlot& slot = mAsyncReadbackSlots[mAsyncReadbackWriteIndex];
|
||||||
|
if (slot.inFlight)
|
||||||
|
{
|
||||||
|
finishTiming();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
auto stageStartTime = std::chrono::steady_clock::now();
|
||||||
|
glPixelStorei(GL_PACK_ALIGNMENT, 4);
|
||||||
|
glPixelStorei(GL_PACK_ROW_LENGTH, 0);
|
||||||
|
glBindFramebuffer(GL_READ_FRAMEBUFFER, framebuffer);
|
||||||
|
glBindBuffer(GL_PIXEL_PACK_BUFFER, slot.pixelPackBuffer);
|
||||||
|
auto stageEndTime = std::chrono::steady_clock::now();
|
||||||
|
timing.asyncQueueSetupMilliseconds += std::chrono::duration_cast<std::chrono::duration<double, std::milli>>(stageEndTime - stageStartTime).count();
|
||||||
|
|
||||||
|
stageStartTime = std::chrono::steady_clock::now();
|
||||||
|
glBufferData(GL_PIXEL_PACK_BUFFER, static_cast<GLsizeiptr>(requiredBytes), nullptr, GL_STREAM_READ);
|
||||||
|
stageEndTime = std::chrono::steady_clock::now();
|
||||||
|
timing.asyncQueueBufferMilliseconds += std::chrono::duration_cast<std::chrono::duration<double, std::milli>>(stageEndTime - stageStartTime).count();
|
||||||
|
|
||||||
|
stageStartTime = std::chrono::steady_clock::now();
|
||||||
|
glReadPixels(0, 0, readWidth, readHeight, format, type, nullptr);
|
||||||
|
stageEndTime = std::chrono::steady_clock::now();
|
||||||
|
timing.asyncQueueReadPixelsMilliseconds += std::chrono::duration_cast<std::chrono::duration<double, std::milli>>(stageEndTime - stageStartTime).count();
|
||||||
|
|
||||||
|
stageStartTime = std::chrono::steady_clock::now();
|
||||||
|
slot.fence = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
|
||||||
|
stageEndTime = std::chrono::steady_clock::now();
|
||||||
|
timing.asyncQueueFenceMilliseconds += std::chrono::duration_cast<std::chrono::duration<double, std::milli>>(stageEndTime - stageStartTime).count();
|
||||||
|
slot.inFlight = slot.fence != nullptr;
|
||||||
|
glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
|
||||||
|
|
||||||
|
mAsyncReadbackWriteIndex = (mAsyncReadbackWriteIndex + 1) % mAsyncReadbackSlots.size();
|
||||||
|
finishTiming();
|
||||||
|
return slot.inFlight;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool OpenGLRenderPipeline::TryConsumeAsyncReadback(VideoIOOutputFrame& outputFrame, GLuint64 timeoutNanoseconds, OutputReadbackTiming& timing)
|
||||||
|
{
|
||||||
|
if (mAsyncReadbackBytes == 0 || outputFrame.bytes == nullptr)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
AsyncReadbackSlot& slot = mAsyncReadbackSlots[mAsyncReadbackReadIndex];
|
||||||
|
if (!slot.inFlight || slot.fence == nullptr || slot.pixelPackBuffer == 0)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
const GLenum waitFlags = timeoutNanoseconds > 0 ? GL_SYNC_FLUSH_COMMANDS_BIT : 0;
|
||||||
|
const auto waitStartTime = std::chrono::steady_clock::now();
|
||||||
|
const GLenum waitResult = glClientWaitSync(slot.fence, waitFlags, timeoutNanoseconds);
|
||||||
|
const auto waitEndTime = std::chrono::steady_clock::now();
|
||||||
|
timing.fenceWaitMilliseconds += std::chrono::duration_cast<std::chrono::duration<double, std::milli>>(waitEndTime - waitStartTime).count();
|
||||||
|
if (waitResult != GL_ALREADY_SIGNALED && waitResult != GL_CONDITION_SATISFIED)
|
||||||
|
{
|
||||||
|
timing.asyncReadbackMissed = true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
glDeleteSync(slot.fence);
|
||||||
|
slot.fence = nullptr;
|
||||||
|
|
||||||
|
glBindBuffer(GL_PIXEL_PACK_BUFFER, slot.pixelPackBuffer);
|
||||||
|
const auto mapStartTime = std::chrono::steady_clock::now();
|
||||||
|
void* mappedBytes = glMapBuffer(GL_PIXEL_PACK_BUFFER, GL_READ_ONLY);
|
||||||
|
const auto mapEndTime = std::chrono::steady_clock::now();
|
||||||
|
timing.mapMilliseconds += std::chrono::duration_cast<std::chrono::duration<double, std::milli>>(mapEndTime - mapStartTime).count();
|
||||||
|
if (mappedBytes == nullptr)
|
||||||
|
{
|
||||||
|
glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
|
||||||
|
slot.inFlight = false;
|
||||||
|
mAsyncReadbackReadIndex = (mAsyncReadbackReadIndex + 1) % mAsyncReadbackSlots.size();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto copyStartTime = std::chrono::steady_clock::now();
|
||||||
|
std::memcpy(outputFrame.bytes, mappedBytes, slot.sizeBytes);
|
||||||
|
const auto copyEndTime = std::chrono::steady_clock::now();
|
||||||
|
timing.copyMilliseconds += std::chrono::duration_cast<std::chrono::duration<double, std::milli>>(copyEndTime - copyStartTime).count();
|
||||||
|
glUnmapBuffer(GL_PIXEL_PACK_BUFFER);
|
||||||
|
glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
|
||||||
|
|
||||||
|
slot.inFlight = false;
|
||||||
|
mAsyncReadbackReadIndex = (mAsyncReadbackReadIndex + 1) % mAsyncReadbackSlots.size();
|
||||||
|
CacheOutputFrame(outputFrame);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void OpenGLRenderPipeline::CacheOutputFrame(const VideoIOOutputFrame& outputFrame)
|
||||||
|
{
|
||||||
|
if (outputFrame.bytes == nullptr || outputFrame.height == 0 || outputFrame.rowBytes <= 0)
|
||||||
|
return;
|
||||||
|
|
||||||
|
const std::size_t byteCount = static_cast<std::size_t>(outputFrame.rowBytes) * outputFrame.height;
|
||||||
|
mCachedOutputFrame.resize(byteCount);
|
||||||
|
std::memcpy(mCachedOutputFrame.data(), outputFrame.bytes, byteCount);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool OpenGLRenderPipeline::TryCopyCachedOutputFrame(VideoIOOutputFrame& outputFrame, OutputReadbackTiming& timing) const
|
||||||
|
{
|
||||||
|
if (outputFrame.bytes == nullptr || outputFrame.height == 0 || outputFrame.rowBytes <= 0)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
const std::size_t byteCount = static_cast<std::size_t>(outputFrame.rowBytes) * outputFrame.height;
|
||||||
|
if (mCachedOutputFrame.size() != byteCount)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
const auto copyStartTime = std::chrono::steady_clock::now();
|
||||||
|
std::memcpy(outputFrame.bytes, mCachedOutputFrame.data(), byteCount);
|
||||||
|
const auto copyEndTime = std::chrono::steady_clock::now();
|
||||||
|
timing.cachedCopyMilliseconds += std::chrono::duration_cast<std::chrono::duration<double, std::milli>>(copyEndTime - copyStartTime).count();
|
||||||
|
timing.cachedFallbackUsed = true;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void OpenGLRenderPipeline::ReadOutputFrameSynchronously(const VideoIOState& state, void* destinationBytes, OutputReadbackTiming& timing)
|
||||||
|
{
|
||||||
|
const auto readStartTime = std::chrono::steady_clock::now();
|
||||||
|
const bool usePackedOutput = state.outputPixelFormat == VideoIOPixelFormat::V210 || state.outputPixelFormat == VideoIOPixelFormat::Yuva10;
|
||||||
|
const bool usePackFramebuffer = state.outputPixelFormat == VideoIOPixelFormat::Bgra8 || usePackedOutput;
|
||||||
|
|
||||||
|
glPixelStorei(GL_PACK_ALIGNMENT, 4);
|
||||||
|
glPixelStorei(GL_PACK_ROW_LENGTH, 0);
|
||||||
|
if (usePackFramebuffer)
|
||||||
|
{
|
||||||
|
glBindFramebuffer(GL_READ_FRAMEBUFFER, mRenderer.OutputPackFramebuffer());
|
||||||
|
if (usePackedOutput)
|
||||||
|
glReadPixels(0, 0, state.outputPackTextureWidth, state.outputFrameSize.height, GL_RGBA, GL_UNSIGNED_BYTE, destinationBytes);
|
||||||
|
else
|
||||||
|
glReadPixels(0, 0, state.outputFrameSize.width, state.outputFrameSize.height, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, destinationBytes);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
glBindFramebuffer(GL_READ_FRAMEBUFFER, mRenderer.OutputFramebuffer());
|
||||||
|
glReadPixels(0, 0, state.outputFrameSize.width, state.outputFrameSize.height, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, destinationBytes);
|
||||||
|
}
|
||||||
|
const auto readEndTime = std::chrono::steady_clock::now();
|
||||||
|
timing.syncReadMilliseconds += std::chrono::duration_cast<std::chrono::duration<double, std::milli>>(readEndTime - readStartTime).count();
|
||||||
|
timing.syncFallbackUsed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
OpenGLRenderPipeline::OutputReadbackTiming OpenGLRenderPipeline::ReadOutputFrame(const VideoIOState& state, VideoIOOutputFrame& outputFrame)
|
||||||
|
{
|
||||||
|
OutputReadbackTiming timing;
|
||||||
|
|
||||||
|
if (mOutputReadbackMode == OutputReadbackMode::Synchronous)
|
||||||
|
{
|
||||||
|
if (outputFrame.bytes != nullptr)
|
||||||
|
{
|
||||||
|
ReadOutputFrameSynchronously(state, outputFrame.bytes, timing);
|
||||||
|
CacheOutputFrame(outputFrame);
|
||||||
|
}
|
||||||
|
return timing;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mOutputReadbackMode == OutputReadbackMode::CachedOnly)
|
||||||
|
{
|
||||||
|
if (TryCopyCachedOutputFrame(outputFrame, timing))
|
||||||
|
return timing;
|
||||||
|
|
||||||
|
if (outputFrame.bytes != nullptr)
|
||||||
|
{
|
||||||
|
ReadOutputFrameSynchronously(state, outputFrame.bytes, timing);
|
||||||
|
CacheOutputFrame(outputFrame);
|
||||||
|
}
|
||||||
|
return timing;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (TryConsumeAsyncReadback(outputFrame, 0, timing))
|
||||||
|
{
|
||||||
|
(void)QueueAsyncReadback(state, timing);
|
||||||
|
return timing;
|
||||||
|
}
|
||||||
|
|
||||||
|
const bool queued = QueueAsyncReadback(state, timing);
|
||||||
|
|
||||||
|
if (queued && TryConsumeAsyncReadback(outputFrame, 0, timing))
|
||||||
|
return timing;
|
||||||
|
|
||||||
|
if (TryCopyCachedOutputFrame(outputFrame, timing))
|
||||||
|
{
|
||||||
|
return timing;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bootstrap only: until the first async readback has produced cached output,
|
||||||
|
// use one synchronous readback so DeckLink has a valid frame to schedule.
|
||||||
|
if (outputFrame.bytes != nullptr && mCachedOutputFrame.empty())
|
||||||
|
{
|
||||||
|
ReadOutputFrameSynchronously(state, outputFrame.bytes, timing);
|
||||||
|
CacheOutputFrame(outputFrame);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!queued)
|
||||||
|
(void)QueueAsyncReadback(state, timing);
|
||||||
|
return timing;
|
||||||
|
}
|
||||||
|
|
||||||
|
OpenGLRenderPipeline::OutputReadbackMode OpenGLRenderPipeline::ReadOutputReadbackModeFromEnvironment()
|
||||||
|
{
|
||||||
|
char* mode = nullptr;
|
||||||
|
std::size_t modeSize = 0;
|
||||||
|
if (_dupenv_s(&mode, &modeSize, "VST_OUTPUT_READBACK_MODE") != 0 || mode == nullptr)
|
||||||
|
return OutputReadbackMode::AsyncPbo;
|
||||||
|
|
||||||
|
const std::string modeValue(mode);
|
||||||
|
std::free(mode);
|
||||||
|
if (modeValue == "async_pbo")
|
||||||
|
return OutputReadbackMode::AsyncPbo;
|
||||||
|
if (modeValue == "sync")
|
||||||
|
return OutputReadbackMode::Synchronous;
|
||||||
|
if (modeValue == "cached_only")
|
||||||
|
return OutputReadbackMode::CachedOnly;
|
||||||
|
|
||||||
|
return OutputReadbackMode::AsyncPbo;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::size_t OpenGLRenderPipeline::ReadAsyncReadbackDepthFromEnvironment()
|
||||||
|
{
|
||||||
|
char* depthValue = nullptr;
|
||||||
|
std::size_t depthValueSize = 0;
|
||||||
|
if (_dupenv_s(&depthValue, &depthValueSize, "VST_OUTPUT_READBACK_DEPTH") != 0 || depthValue == nullptr)
|
||||||
|
return 6;
|
||||||
|
|
||||||
|
const std::string value(depthValue);
|
||||||
|
std::free(depthValue);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
const unsigned long requestedDepth = std::stoul(value);
|
||||||
|
if (requestedDepth < 3)
|
||||||
|
return 3;
|
||||||
|
if (requestedDepth > 12)
|
||||||
|
return 12;
|
||||||
|
return static_cast<std::size_t>(requestedDepth);
|
||||||
|
}
|
||||||
|
catch (...)
|
||||||
|
{
|
||||||
|
return 6;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "GLExtensions.h"
|
||||||
|
#include "VideoIOTypes.h"
|
||||||
|
|
||||||
|
#include <functional>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
class OpenGLRenderer;
|
||||||
|
class HealthTelemetry;
|
||||||
|
class RuntimeSnapshotProvider;
|
||||||
|
|
||||||
|
struct RenderPipelineFrameContext
|
||||||
|
{
|
||||||
|
VideoIOState videoState;
|
||||||
|
VideoIOCompletion completion;
|
||||||
|
};
|
||||||
|
|
||||||
|
class OpenGLRenderPipeline
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
using RenderEffectCallback = std::function<void()>;
|
||||||
|
using OutputReadyCallback = std::function<void()>;
|
||||||
|
using PaintCallback = std::function<void()>;
|
||||||
|
|
||||||
|
OpenGLRenderPipeline(
|
||||||
|
OpenGLRenderer& renderer,
|
||||||
|
RuntimeSnapshotProvider& runtimeSnapshotProvider,
|
||||||
|
HealthTelemetry& healthTelemetry,
|
||||||
|
RenderEffectCallback renderEffect,
|
||||||
|
OutputReadyCallback outputReady,
|
||||||
|
PaintCallback paint);
|
||||||
|
~OpenGLRenderPipeline();
|
||||||
|
|
||||||
|
bool RenderFrame(const RenderPipelineFrameContext& context, VideoIOOutputFrame& outputFrame);
|
||||||
|
|
||||||
|
private:
|
||||||
|
enum class OutputReadbackMode
|
||||||
|
{
|
||||||
|
AsyncPbo,
|
||||||
|
Synchronous,
|
||||||
|
CachedOnly
|
||||||
|
};
|
||||||
|
|
||||||
|
struct AsyncReadbackSlot
|
||||||
|
{
|
||||||
|
GLuint pixelPackBuffer = 0;
|
||||||
|
GLsync fence = nullptr;
|
||||||
|
std::size_t sizeBytes = 0;
|
||||||
|
bool inFlight = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct OutputReadbackTiming
|
||||||
|
{
|
||||||
|
double fenceWaitMilliseconds = 0.0;
|
||||||
|
double mapMilliseconds = 0.0;
|
||||||
|
double copyMilliseconds = 0.0;
|
||||||
|
double cachedCopyMilliseconds = 0.0;
|
||||||
|
double asyncQueueMilliseconds = 0.0;
|
||||||
|
double asyncQueueBufferMilliseconds = 0.0;
|
||||||
|
double asyncQueueSetupMilliseconds = 0.0;
|
||||||
|
double asyncQueueReadPixelsMilliseconds = 0.0;
|
||||||
|
double asyncQueueFenceMilliseconds = 0.0;
|
||||||
|
double syncReadMilliseconds = 0.0;
|
||||||
|
bool asyncReadbackMissed = false;
|
||||||
|
bool cachedFallbackUsed = false;
|
||||||
|
bool syncFallbackUsed = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
bool EnsureAsyncReadbackBuffers(std::size_t requiredBytes);
|
||||||
|
void ResetAsyncReadbackState();
|
||||||
|
void FlushAsyncReadbackPipeline();
|
||||||
|
bool QueueAsyncReadback(const VideoIOState& state, OutputReadbackTiming& timing);
|
||||||
|
bool TryConsumeAsyncReadback(VideoIOOutputFrame& outputFrame, GLuint64 timeoutNanoseconds, OutputReadbackTiming& timing);
|
||||||
|
void CacheOutputFrame(const VideoIOOutputFrame& outputFrame);
|
||||||
|
bool TryCopyCachedOutputFrame(VideoIOOutputFrame& outputFrame, OutputReadbackTiming& timing) const;
|
||||||
|
void ReadOutputFrameSynchronously(const VideoIOState& state, void* destinationBytes, OutputReadbackTiming& timing);
|
||||||
|
void PackOutputForBgra8(const VideoIOState& state);
|
||||||
|
void PackOutputFor10Bit(const VideoIOState& state);
|
||||||
|
OutputReadbackTiming ReadOutputFrame(const VideoIOState& state, VideoIOOutputFrame& outputFrame);
|
||||||
|
static OutputReadbackMode ReadOutputReadbackModeFromEnvironment();
|
||||||
|
static std::size_t ReadAsyncReadbackDepthFromEnvironment();
|
||||||
|
|
||||||
|
OpenGLRenderer& mRenderer;
|
||||||
|
RuntimeSnapshotProvider& mRuntimeSnapshotProvider;
|
||||||
|
HealthTelemetry& mHealthTelemetry;
|
||||||
|
RenderEffectCallback mRenderEffect;
|
||||||
|
OutputReadyCallback mOutputReady;
|
||||||
|
PaintCallback mPaint;
|
||||||
|
OutputReadbackMode mOutputReadbackMode = OutputReadbackMode::AsyncPbo;
|
||||||
|
std::vector<AsyncReadbackSlot> mAsyncReadbackSlots;
|
||||||
|
std::size_t mAsyncReadbackDepth = 0;
|
||||||
|
std::size_t mAsyncReadbackWriteIndex = 0;
|
||||||
|
std::size_t mAsyncReadbackReadIndex = 0;
|
||||||
|
std::size_t mAsyncReadbackBytes = 0;
|
||||||
|
GLenum mAsyncReadbackFormat = GL_BGRA;
|
||||||
|
GLenum mAsyncReadbackType = GL_UNSIGNED_INT_8_8_8_8_REV;
|
||||||
|
GLuint mAsyncReadbackFramebuffer = 0;
|
||||||
|
std::vector<unsigned char> mCachedOutputFrame;
|
||||||
|
};
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
#include "OpenGLVideoIOBridge.h"
|
||||||
|
|
||||||
|
#include "RenderEngine.h"
|
||||||
|
|
||||||
|
OpenGLVideoIOBridge::OpenGLVideoIOBridge(RenderEngine& renderEngine) :
|
||||||
|
mRenderEngine(renderEngine)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
void OpenGLVideoIOBridge::UploadInputFrame(const VideoIOFrame& inputFrame, const VideoIOState& state)
|
||||||
|
{
|
||||||
|
if (inputFrame.hasNoInputSource || inputFrame.bytes == nullptr)
|
||||||
|
return; // don't transfer texture when there's no input
|
||||||
|
|
||||||
|
mRenderEngine.QueueInputFrame(inputFrame, state);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool OpenGLVideoIOBridge::RenderScheduledFrame(const VideoIOState& state, const VideoIOCompletion& completion, VideoIOOutputFrame& outputFrame)
|
||||||
|
{
|
||||||
|
RenderPipelineFrameContext frameContext;
|
||||||
|
frameContext.videoState = state;
|
||||||
|
frameContext.completion = completion;
|
||||||
|
|
||||||
|
return mRenderEngine.RequestOutputFrame(frameContext, outputFrame);
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "OpenGLRenderPipeline.h"
|
||||||
|
|
||||||
|
class RenderEngine;
|
||||||
|
|
||||||
|
class OpenGLVideoIOBridge
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
explicit OpenGLVideoIOBridge(RenderEngine& renderEngine);
|
||||||
|
|
||||||
|
void UploadInputFrame(const VideoIOFrame& inputFrame, const VideoIOState& state);
|
||||||
|
bool RenderScheduledFrame(const VideoIOState& state, const VideoIOCompletion& completion, VideoIOOutputFrame& outputFrame);
|
||||||
|
|
||||||
|
private:
|
||||||
|
RenderEngine& mRenderEngine;
|
||||||
|
};
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "OpenGLRenderer.h"
|
||||||
|
#include "ShaderTypes.h"
|
||||||
|
|
||||||
|
#include <gl/gl.h>
|
||||||
|
|
||||||
|
#include <cstddef>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
enum class RenderPassKind
|
||||||
|
{
|
||||||
|
LayerEffect
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class RenderPassOutputTarget
|
||||||
|
{
|
||||||
|
Temporary,
|
||||||
|
LayerTemp,
|
||||||
|
Composite
|
||||||
|
};
|
||||||
|
|
||||||
|
struct RenderPassDescriptor
|
||||||
|
{
|
||||||
|
RenderPassKind kind = RenderPassKind::LayerEffect;
|
||||||
|
RenderPassOutputTarget outputTarget = RenderPassOutputTarget::Composite;
|
||||||
|
std::size_t passIndex = 0;
|
||||||
|
std::string passId;
|
||||||
|
std::string layerId;
|
||||||
|
std::string shaderId;
|
||||||
|
GLuint layerInputTexture = 0;
|
||||||
|
GLuint sourceTexture = 0;
|
||||||
|
GLuint sourceFramebuffer = 0;
|
||||||
|
GLuint destinationTexture = 0;
|
||||||
|
GLuint destinationFramebuffer = 0;
|
||||||
|
OpenGLRenderer::LayerProgram* layerProgram = nullptr;
|
||||||
|
OpenGLRenderer::LayerProgram::PassProgram* passProgram = nullptr;
|
||||||
|
const RuntimeRenderState* layerState = nullptr;
|
||||||
|
bool capturePreLayerHistory = false;
|
||||||
|
bool captureFeedbackWrite = false;
|
||||||
|
};
|
||||||
@@ -0,0 +1,202 @@
|
|||||||
|
#include "ShaderFeedbackBuffers.h"
|
||||||
|
|
||||||
|
#include <set>
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
void ConfigureFeedbackTexture(unsigned frameWidth, unsigned frameHeight)
|
||||||
|
{
|
||||||
|
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
|
||||||
|
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
|
||||||
|
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
|
||||||
|
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
|
||||||
|
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, frameWidth, frameHeight, 0, GL_RGBA, GL_FLOAT, NULL);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ShaderFeedbackBuffers::EnsureResources(const std::vector<RuntimeRenderState>& layerStates, unsigned frameWidth, unsigned frameHeight, std::string& error)
|
||||||
|
{
|
||||||
|
if (!EnsureZeroTexture())
|
||||||
|
{
|
||||||
|
error = "Failed to initialize shader feedback fallback texture.";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::set<std::string> requiredLayerIds;
|
||||||
|
for (const RuntimeRenderState& state : layerStates)
|
||||||
|
{
|
||||||
|
if (!state.feedback.enabled)
|
||||||
|
continue;
|
||||||
|
|
||||||
|
requiredLayerIds.insert(state.layerId);
|
||||||
|
auto surfaceIt = mSurfacesByLayerId.find(state.layerId);
|
||||||
|
if (surfaceIt == mSurfacesByLayerId.end() ||
|
||||||
|
surfaceIt->second.width != frameWidth ||
|
||||||
|
surfaceIt->second.height != frameHeight)
|
||||||
|
{
|
||||||
|
Surface replacement;
|
||||||
|
if (!CreateSurface(replacement, frameWidth, frameHeight, error))
|
||||||
|
return false;
|
||||||
|
mSurfacesByLayerId[state.layerId] = std::move(replacement);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (auto it = mSurfacesByLayerId.begin(); it != mSurfacesByLayerId.end();)
|
||||||
|
{
|
||||||
|
if (requiredLayerIds.find(it->first) == requiredLayerIds.end())
|
||||||
|
{
|
||||||
|
DestroySurface(it->second);
|
||||||
|
it = mSurfacesByLayerId.erase(it);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
++it;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void ShaderFeedbackBuffers::DestroyResources()
|
||||||
|
{
|
||||||
|
for (auto& entry : mSurfacesByLayerId)
|
||||||
|
DestroySurface(entry.second);
|
||||||
|
mSurfacesByLayerId.clear();
|
||||||
|
|
||||||
|
if (mZeroTexture != 0)
|
||||||
|
{
|
||||||
|
glDeleteTextures(1, &mZeroTexture);
|
||||||
|
mZeroTexture = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void ShaderFeedbackBuffers::ResetState()
|
||||||
|
{
|
||||||
|
for (auto& entry : mSurfacesByLayerId)
|
||||||
|
ClearSurfaceState(entry.second);
|
||||||
|
}
|
||||||
|
|
||||||
|
GLuint ShaderFeedbackBuffers::ResolveReadTexture(const RuntimeRenderState& state) const
|
||||||
|
{
|
||||||
|
if (!state.feedback.enabled)
|
||||||
|
return mZeroTexture;
|
||||||
|
|
||||||
|
auto surfaceIt = mSurfacesByLayerId.find(state.layerId);
|
||||||
|
if (surfaceIt == mSurfacesByLayerId.end() || !surfaceIt->second.hasData)
|
||||||
|
return mZeroTexture;
|
||||||
|
|
||||||
|
return surfaceIt->second.slots[surfaceIt->second.readIndex].texture != 0
|
||||||
|
? surfaceIt->second.slots[surfaceIt->second.readIndex].texture
|
||||||
|
: mZeroTexture;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ShaderFeedbackBuffers::FeedbackAvailable(const RuntimeRenderState& state) const
|
||||||
|
{
|
||||||
|
if (!state.feedback.enabled)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
auto surfaceIt = mSurfacesByLayerId.find(state.layerId);
|
||||||
|
return surfaceIt != mSurfacesByLayerId.end() && surfaceIt->second.hasData;
|
||||||
|
}
|
||||||
|
|
||||||
|
void ShaderFeedbackBuffers::CaptureFeedbackFramebuffer(const std::string& layerId, GLuint sourceFramebuffer, unsigned frameWidth, unsigned frameHeight)
|
||||||
|
{
|
||||||
|
auto surfaceIt = mSurfacesByLayerId.find(layerId);
|
||||||
|
if (surfaceIt == mSurfacesByLayerId.end())
|
||||||
|
return;
|
||||||
|
|
||||||
|
Surface& surface = surfaceIt->second;
|
||||||
|
const unsigned writeIndex = 1u - surface.readIndex;
|
||||||
|
glBindFramebuffer(GL_READ_FRAMEBUFFER, sourceFramebuffer);
|
||||||
|
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, surface.slots[writeIndex].framebuffer);
|
||||||
|
glBlitFramebuffer(0, 0, frameWidth, frameHeight, 0, 0, frameWidth, frameHeight, GL_COLOR_BUFFER_BIT, GL_LINEAR);
|
||||||
|
surface.pendingWrite = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void ShaderFeedbackBuffers::FinalizeFrame()
|
||||||
|
{
|
||||||
|
for (auto& entry : mSurfacesByLayerId)
|
||||||
|
{
|
||||||
|
Surface& surface = entry.second;
|
||||||
|
if (!surface.pendingWrite)
|
||||||
|
continue;
|
||||||
|
|
||||||
|
surface.readIndex = 1u - surface.readIndex;
|
||||||
|
surface.hasData = true;
|
||||||
|
surface.pendingWrite = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ShaderFeedbackBuffers::EnsureZeroTexture()
|
||||||
|
{
|
||||||
|
if (mZeroTexture != 0)
|
||||||
|
return true;
|
||||||
|
|
||||||
|
glGenTextures(1, &mZeroTexture);
|
||||||
|
glBindTexture(GL_TEXTURE_2D, mZeroTexture);
|
||||||
|
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
|
||||||
|
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
|
||||||
|
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
|
||||||
|
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
|
||||||
|
const float zeroPixel[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
|
||||||
|
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, 1, 1, 0, GL_RGBA, GL_FLOAT, zeroPixel);
|
||||||
|
glBindTexture(GL_TEXTURE_2D, 0);
|
||||||
|
return mZeroTexture != 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ShaderFeedbackBuffers::CreateSurface(Surface& surface, unsigned frameWidth, unsigned frameHeight, std::string& error)
|
||||||
|
{
|
||||||
|
DestroySurface(surface);
|
||||||
|
|
||||||
|
surface.width = frameWidth;
|
||||||
|
surface.height = frameHeight;
|
||||||
|
for (Slot& slot : surface.slots)
|
||||||
|
{
|
||||||
|
glGenTextures(1, &slot.texture);
|
||||||
|
glBindTexture(GL_TEXTURE_2D, slot.texture);
|
||||||
|
ConfigureFeedbackTexture(frameWidth, frameHeight);
|
||||||
|
|
||||||
|
glGenFramebuffers(1, &slot.framebuffer);
|
||||||
|
glBindFramebuffer(GL_FRAMEBUFFER, slot.framebuffer);
|
||||||
|
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, slot.texture, 0);
|
||||||
|
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
|
||||||
|
{
|
||||||
|
error = "Failed to initialize a shader feedback framebuffer.";
|
||||||
|
glBindFramebuffer(GL_FRAMEBUFFER, 0);
|
||||||
|
glBindTexture(GL_TEXTURE_2D, 0);
|
||||||
|
DestroySurface(surface);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
glBindFramebuffer(GL_FRAMEBUFFER, 0);
|
||||||
|
glBindTexture(GL_TEXTURE_2D, 0);
|
||||||
|
ClearSurfaceState(surface);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void ShaderFeedbackBuffers::DestroySurface(Surface& surface)
|
||||||
|
{
|
||||||
|
for (Slot& slot : surface.slots)
|
||||||
|
{
|
||||||
|
if (slot.framebuffer != 0)
|
||||||
|
glDeleteFramebuffers(1, &slot.framebuffer);
|
||||||
|
if (slot.texture != 0)
|
||||||
|
glDeleteTextures(1, &slot.texture);
|
||||||
|
slot.framebuffer = 0;
|
||||||
|
slot.texture = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
surface.width = 0;
|
||||||
|
surface.height = 0;
|
||||||
|
surface.readIndex = 0;
|
||||||
|
surface.hasData = false;
|
||||||
|
surface.pendingWrite = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
void ShaderFeedbackBuffers::ClearSurfaceState(Surface& surface)
|
||||||
|
{
|
||||||
|
surface.readIndex = 0;
|
||||||
|
surface.hasData = false;
|
||||||
|
surface.pendingWrite = false;
|
||||||
|
}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "GLExtensions.h"
|
||||||
|
#include "ShaderTypes.h"
|
||||||
|
|
||||||
|
#include <map>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
class ShaderFeedbackBuffers
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
struct Slot
|
||||||
|
{
|
||||||
|
GLuint texture = 0;
|
||||||
|
GLuint framebuffer = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Surface
|
||||||
|
{
|
||||||
|
Slot slots[2];
|
||||||
|
unsigned width = 0;
|
||||||
|
unsigned height = 0;
|
||||||
|
unsigned readIndex = 0;
|
||||||
|
bool hasData = false;
|
||||||
|
bool pendingWrite = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
bool EnsureResources(const std::vector<RuntimeRenderState>& layerStates, unsigned frameWidth, unsigned frameHeight, std::string& error);
|
||||||
|
void DestroyResources();
|
||||||
|
void ResetState();
|
||||||
|
GLuint ResolveReadTexture(const RuntimeRenderState& state) const;
|
||||||
|
bool FeedbackAvailable(const RuntimeRenderState& state) const;
|
||||||
|
void CaptureFeedbackFramebuffer(const std::string& layerId, GLuint sourceFramebuffer, unsigned frameWidth, unsigned frameHeight);
|
||||||
|
void FinalizeFrame();
|
||||||
|
|
||||||
|
private:
|
||||||
|
bool EnsureZeroTexture();
|
||||||
|
bool CreateSurface(Surface& surface, unsigned frameWidth, unsigned frameHeight, std::string& error);
|
||||||
|
void DestroySurface(Surface& surface);
|
||||||
|
void ClearSurfaceState(Surface& surface);
|
||||||
|
|
||||||
|
private:
|
||||||
|
std::map<std::string, Surface> mSurfacesByLayerId;
|
||||||
|
GLuint mZeroTexture = 0;
|
||||||
|
};
|
||||||
@@ -19,7 +19,8 @@ bool TemporalHistoryBuffers::ValidateTextureUnitBudget(const std::vector<Runtime
|
|||||||
++textTextureCount;
|
++textTextureCount;
|
||||||
}
|
}
|
||||||
const unsigned totalShaderTextures = static_cast<unsigned>(state.textureAssets.size()) + textTextureCount;
|
const unsigned totalShaderTextures = static_cast<unsigned>(state.textureAssets.size()) + textTextureCount;
|
||||||
const unsigned layerRequiredUnits = kSourceHistoryTextureUnitBase + (state.isTemporal ? historyCap + historyCap : 0u) + totalShaderTextures;
|
const unsigned feedbackTextureCount = state.feedback.enabled ? 1u : 0u;
|
||||||
|
const unsigned layerRequiredUnits = kSourceHistoryTextureUnitBase + (state.isTemporal ? historyCap + historyCap : 0u) + feedbackTextureCount + totalShaderTextures;
|
||||||
if (layerRequiredUnits > requiredUnits)
|
if (layerRequiredUnits > requiredUnits)
|
||||||
requiredUnits = layerRequiredUnits;
|
requiredUnits = layerRequiredUnits;
|
||||||
}
|
}
|
||||||
@@ -212,6 +213,29 @@ void TemporalHistoryBuffers::BindSamplers(const RuntimeRenderState& state, GLuin
|
|||||||
glActiveTexture(GL_TEXTURE0);
|
glActiveTexture(GL_TEXTURE0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
std::vector<GLuint> TemporalHistoryBuffers::ResolveSourceHistoryTextures(GLuint fallbackTexture, unsigned historyCap) const
|
||||||
|
{
|
||||||
|
std::vector<GLuint> textures;
|
||||||
|
textures.reserve(historyCap);
|
||||||
|
for (unsigned index = 0; index < historyCap; ++index)
|
||||||
|
textures.push_back(ResolveTexture(sourceHistoryRing, fallbackTexture, index));
|
||||||
|
return textures;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<GLuint> TemporalHistoryBuffers::ResolveTemporalHistoryTextures(const RuntimeRenderState& state, GLuint fallbackTexture, unsigned historyCap) const
|
||||||
|
{
|
||||||
|
const Ring* temporalRing = nullptr;
|
||||||
|
auto it = preLayerHistoryByLayerId.find(state.layerId);
|
||||||
|
if (it != preLayerHistoryByLayerId.end())
|
||||||
|
temporalRing = &it->second;
|
||||||
|
|
||||||
|
std::vector<GLuint> textures;
|
||||||
|
textures.reserve(historyCap);
|
||||||
|
for (unsigned index = 0; index < historyCap; ++index)
|
||||||
|
textures.push_back(temporalRing ? ResolveTexture(*temporalRing, fallbackTexture, index) : fallbackTexture);
|
||||||
|
return textures;
|
||||||
|
}
|
||||||
|
|
||||||
GLuint TemporalHistoryBuffers::ResolveTexture(const Ring& ring, GLuint fallbackTexture, std::size_t framesAgo) const
|
GLuint TemporalHistoryBuffers::ResolveTexture(const Ring& ring, GLuint fallbackTexture, std::size_t framesAgo) const
|
||||||
{
|
{
|
||||||
if (ring.filledCount == 0 || ring.slots.empty())
|
if (ring.filledCount == 0 || ring.slots.empty())
|
||||||
@@ -40,6 +40,8 @@ public:
|
|||||||
void PushSourceFramebuffer(GLuint sourceFramebuffer, unsigned frameWidth, unsigned frameHeight);
|
void PushSourceFramebuffer(GLuint sourceFramebuffer, unsigned frameWidth, unsigned frameHeight);
|
||||||
void PushPreLayerFramebuffer(const std::string& layerId, GLuint sourceFramebuffer, unsigned frameWidth, unsigned frameHeight);
|
void PushPreLayerFramebuffer(const std::string& layerId, GLuint sourceFramebuffer, unsigned frameWidth, unsigned frameHeight);
|
||||||
void BindSamplers(const RuntimeRenderState& state, GLuint currentSourceTexture, unsigned historyCap);
|
void BindSamplers(const RuntimeRenderState& state, GLuint currentSourceTexture, unsigned historyCap);
|
||||||
|
std::vector<GLuint> ResolveSourceHistoryTextures(GLuint fallbackTexture, unsigned historyCap) const;
|
||||||
|
std::vector<GLuint> ResolveTemporalHistoryTextures(const RuntimeRenderState& state, GLuint fallbackTexture, unsigned historyCap) const;
|
||||||
GLuint ResolveTexture(const Ring& ring, GLuint fallbackTexture, std::size_t framesAgo) const;
|
GLuint ResolveTexture(const Ring& ring, GLuint fallbackTexture, std::size_t framesAgo) const;
|
||||||
unsigned SourceAvailableCount() const;
|
unsigned SourceAvailableCount() const;
|
||||||
unsigned AvailableCountForLayer(const std::string& layerId) const;
|
unsigned AvailableCountForLayer(const std::string& layerId) const;
|
||||||
@@ -62,6 +62,8 @@ PFNGLGENBUFFERSPROC glGenBuffers;
|
|||||||
PFNGLDELETEBUFFERSPROC glDeleteBuffers;
|
PFNGLDELETEBUFFERSPROC glDeleteBuffers;
|
||||||
PFNGLBINDBUFFERPROC glBindBuffer;
|
PFNGLBINDBUFFERPROC glBindBuffer;
|
||||||
PFNGLBUFFERDATAPROC glBufferData;
|
PFNGLBUFFERDATAPROC glBufferData;
|
||||||
|
PFNGLMAPBUFFERPROC glMapBuffer;
|
||||||
|
PFNGLUNMAPBUFFERPROC glUnmapBuffer;
|
||||||
PFNGLBUFFERSUBDATAPROC glBufferSubData;
|
PFNGLBUFFERSUBDATAPROC glBufferSubData;
|
||||||
PFNGLBINDBUFFERBASEPROC glBindBufferBase;
|
PFNGLBINDBUFFERBASEPROC glBindBufferBase;
|
||||||
PFNGLACTIVETEXTUREPROC glActiveTexture;
|
PFNGLACTIVETEXTUREPROC glActiveTexture;
|
||||||
@@ -131,6 +133,8 @@ bool ResolveGLExtensions()
|
|||||||
glDeleteBuffers = (PFNGLDELETEBUFFERSPROC) wglGetProcAddress("glDeleteBuffers");
|
glDeleteBuffers = (PFNGLDELETEBUFFERSPROC) wglGetProcAddress("glDeleteBuffers");
|
||||||
glBindBuffer = (PFNGLBINDBUFFERPROC) wglGetProcAddress("glBindBuffer");
|
glBindBuffer = (PFNGLBINDBUFFERPROC) wglGetProcAddress("glBindBuffer");
|
||||||
glBufferData = (PFNGLBUFFERDATAPROC) wglGetProcAddress("glBufferData");
|
glBufferData = (PFNGLBUFFERDATAPROC) wglGetProcAddress("glBufferData");
|
||||||
|
glMapBuffer = (PFNGLMAPBUFFERPROC) wglGetProcAddress("glMapBuffer");
|
||||||
|
glUnmapBuffer = (PFNGLUNMAPBUFFERPROC) wglGetProcAddress("glUnmapBuffer");
|
||||||
glBufferSubData = (PFNGLBUFFERSUBDATAPROC) wglGetProcAddress("glBufferSubData");
|
glBufferSubData = (PFNGLBUFFERSUBDATAPROC) wglGetProcAddress("glBufferSubData");
|
||||||
glBindBufferBase = (PFNGLBINDBUFFERBASEPROC) wglGetProcAddress("glBindBufferBase");
|
glBindBufferBase = (PFNGLBINDBUFFERBASEPROC) wglGetProcAddress("glBindBufferBase");
|
||||||
glActiveTexture = (PFNGLACTIVETEXTUREPROC) wglGetProcAddress("glActiveTexture");
|
glActiveTexture = (PFNGLACTIVETEXTUREPROC) wglGetProcAddress("glActiveTexture");
|
||||||
@@ -176,6 +180,8 @@ bool ResolveGLExtensions()
|
|||||||
&& glDeleteBuffers
|
&& glDeleteBuffers
|
||||||
&& glBindBuffer
|
&& glBindBuffer
|
||||||
&& glBufferData
|
&& glBufferData
|
||||||
|
&& glMapBuffer
|
||||||
|
&& glUnmapBuffer
|
||||||
&& glBufferSubData
|
&& glBufferSubData
|
||||||
&& glBindBufferBase
|
&& glBindBufferBase
|
||||||
&& glActiveTexture
|
&& glActiveTexture
|
||||||
@@ -89,6 +89,11 @@
|
|||||||
#define GL_EXTERNAL_VIRTUAL_MEMORY_BUFFER_AMD 0x9160
|
#define GL_EXTERNAL_VIRTUAL_MEMORY_BUFFER_AMD 0x9160
|
||||||
#define GL_SYNC_GPU_COMMANDS_COMPLETE 0x9117
|
#define GL_SYNC_GPU_COMMANDS_COMPLETE 0x9117
|
||||||
#define GL_SYNC_FLUSH_COMMANDS_BIT 0x00000001
|
#define GL_SYNC_FLUSH_COMMANDS_BIT 0x00000001
|
||||||
|
#define GL_ALREADY_SIGNALED 0x911A
|
||||||
|
#define GL_TIMEOUT_EXPIRED 0x911B
|
||||||
|
#define GL_CONDITION_SATISFIED 0x911C
|
||||||
|
#define GL_WAIT_FAILED 0x911D
|
||||||
|
#define GL_READ_ONLY 0x88B8
|
||||||
|
|
||||||
typedef struct __GLsync *GLsync;
|
typedef struct __GLsync *GLsync;
|
||||||
typedef unsigned __int64 GLuint64;
|
typedef unsigned __int64 GLuint64;
|
||||||
@@ -100,6 +105,8 @@ typedef void (APIENTRYP PFNGLBINDBUFFERPROC) (GLenum target, GLuint buffer);
|
|||||||
typedef void (APIENTRYP PFNGLDELETEBUFFERSPROC) (GLsizei n, const GLuint *buffers);
|
typedef void (APIENTRYP PFNGLDELETEBUFFERSPROC) (GLsizei n, const GLuint *buffers);
|
||||||
typedef void (APIENTRYP PFNGLGENBUFFERSPROC) (GLsizei n, GLuint *buffers);
|
typedef void (APIENTRYP PFNGLGENBUFFERSPROC) (GLsizei n, GLuint *buffers);
|
||||||
typedef void (APIENTRYP PFNGLBUFFERDATAPROC) (GLenum target, GLsizeiptr size, const GLvoid *data, GLenum usage);
|
typedef void (APIENTRYP PFNGLBUFFERDATAPROC) (GLenum target, GLsizeiptr size, const GLvoid *data, GLenum usage);
|
||||||
|
typedef GLvoid* (APIENTRYP PFNGLMAPBUFFERPROC) (GLenum target, GLenum access);
|
||||||
|
typedef GLboolean (APIENTRYP PFNGLUNMAPBUFFERPROC) (GLenum target);
|
||||||
typedef void (APIENTRYP PFNGLATTACHSHADERPROC) (GLuint program, GLuint shader);
|
typedef void (APIENTRYP PFNGLATTACHSHADERPROC) (GLuint program, GLuint shader);
|
||||||
typedef void (APIENTRYP PFNGLCOMPILESHADERPROC) (GLuint shader);
|
typedef void (APIENTRYP PFNGLCOMPILESHADERPROC) (GLuint shader);
|
||||||
typedef GLuint (APIENTRYP PFNGLCREATEPROGRAMPROC) (void);
|
typedef GLuint (APIENTRYP PFNGLCREATEPROGRAMPROC) (void);
|
||||||
@@ -159,6 +166,8 @@ extern PFNGLGENBUFFERSPROC glGenBuffers;
|
|||||||
extern PFNGLDELETEBUFFERSPROC glDeleteBuffers;
|
extern PFNGLDELETEBUFFERSPROC glDeleteBuffers;
|
||||||
extern PFNGLBINDBUFFERPROC glBindBuffer;
|
extern PFNGLBINDBUFFERPROC glBindBuffer;
|
||||||
extern PFNGLBUFFERDATAPROC glBufferData;
|
extern PFNGLBUFFERDATAPROC glBufferData;
|
||||||
|
extern PFNGLMAPBUFFERPROC glMapBuffer;
|
||||||
|
extern PFNGLUNMAPBUFFERPROC glUnmapBuffer;
|
||||||
extern PFNGLBUFFERSUBDATAPROC glBufferSubData;
|
extern PFNGLBUFFERSUBDATAPROC glBufferSubData;
|
||||||
extern PFNGLBINDBUFFERBASEPROC glBindBufferBase;
|
extern PFNGLBINDBUFFERBASEPROC glBindBufferBase;
|
||||||
extern PFNGLACTIVETEXTUREPROC glActiveTexture;
|
extern PFNGLACTIVETEXTUREPROC glActiveTexture;
|
||||||
@@ -2,8 +2,8 @@
|
|||||||
|
|
||||||
#include <gl/gl.h>
|
#include <gl/gl.h>
|
||||||
|
|
||||||
|
constexpr GLuint kLayerInputTextureUnit = 0;
|
||||||
constexpr GLuint kDecodedVideoTextureUnit = 1;
|
constexpr GLuint kDecodedVideoTextureUnit = 1;
|
||||||
constexpr GLuint kSourceHistoryTextureUnitBase = 2;
|
constexpr GLuint kSourceHistoryTextureUnitBase = 2;
|
||||||
constexpr GLuint kPackedVideoTextureUnit = 2;
|
constexpr GLuint kPackedVideoTextureUnit = 2;
|
||||||
constexpr GLuint kGlobalParamsBindingPoint = 0;
|
constexpr GLuint kGlobalParamsBindingPoint = 0;
|
||||||
constexpr unsigned kPrerollFrameCount = 8;
|
|
||||||
@@ -12,15 +12,6 @@ namespace
|
|||||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
|
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
|
||||||
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
|
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
|
||||||
}
|
}
|
||||||
|
|
||||||
void ConfigureDisplayFrameTexture(unsigned width, unsigned height)
|
|
||||||
{
|
|
||||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
|
|
||||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
|
|
||||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
|
|
||||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
|
|
||||||
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, width, height, 0, GL_RGBA, GL_FLOAT, NULL);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
bool OpenGLRenderer::InitializeResources(unsigned inputFrameWidth, unsigned inputFrameHeight, unsigned captureTextureWidth, unsigned outputFrameWidth, unsigned outputFrameHeight, unsigned outputPackTextureWidth, std::string& error)
|
bool OpenGLRenderer::InitializeResources(unsigned inputFrameWidth, unsigned inputFrameHeight, unsigned captureTextureWidth, unsigned outputFrameWidth, unsigned outputFrameHeight, unsigned outputPackTextureWidth, std::string& error)
|
||||||
@@ -35,80 +26,32 @@ bool OpenGLRenderer::InitializeResources(unsigned inputFrameWidth, unsigned inpu
|
|||||||
ConfigureByteFrameTexture(captureTextureWidth, inputFrameHeight);
|
ConfigureByteFrameTexture(captureTextureWidth, inputFrameHeight);
|
||||||
glBindTexture(GL_TEXTURE_2D, 0);
|
glBindTexture(GL_TEXTURE_2D, 0);
|
||||||
|
|
||||||
glGenTextures(1, &mDecodedTexture);
|
|
||||||
glBindTexture(GL_TEXTURE_2D, mDecodedTexture);
|
|
||||||
ConfigureDisplayFrameTexture(inputFrameWidth, inputFrameHeight);
|
|
||||||
glBindTexture(GL_TEXTURE_2D, 0);
|
|
||||||
|
|
||||||
glGenTextures(1, &mLayerTempTexture);
|
|
||||||
glBindTexture(GL_TEXTURE_2D, mLayerTempTexture);
|
|
||||||
ConfigureDisplayFrameTexture(inputFrameWidth, inputFrameHeight);
|
|
||||||
glBindTexture(GL_TEXTURE_2D, 0);
|
|
||||||
|
|
||||||
glGenFramebuffers(1, &mDecodeFrameBuf);
|
|
||||||
glGenFramebuffers(1, &mLayerTempFrameBuf);
|
|
||||||
glGenFramebuffers(1, &mIdFrameBuf);
|
|
||||||
glGenFramebuffers(1, &mOutputFrameBuf);
|
|
||||||
glGenFramebuffers(1, &mOutputPackFrameBuf);
|
|
||||||
glGenRenderbuffers(1, &mIdColorBuf);
|
glGenRenderbuffers(1, &mIdColorBuf);
|
||||||
glGenRenderbuffers(1, &mIdDepthBuf);
|
glGenRenderbuffers(1, &mIdDepthBuf);
|
||||||
glGenVertexArrays(1, &mFullscreenVAO);
|
glGenVertexArrays(1, &mFullscreenVAO);
|
||||||
glGenBuffers(1, &mGlobalParamsUBO);
|
glGenBuffers(1, &mGlobalParamsUBO);
|
||||||
|
|
||||||
glBindFramebuffer(GL_FRAMEBUFFER, mDecodeFrameBuf);
|
if (!mRenderTargets.Create(RenderTargetId::Decoded, inputFrameWidth, inputFrameHeight, GL_RGBA16F, GL_RGBA, GL_FLOAT, "decode", error))
|
||||||
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, mDecodedTexture, 0);
|
|
||||||
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
|
|
||||||
{
|
|
||||||
error = "Cannot initialize decode framebuffer.";
|
|
||||||
return false;
|
return false;
|
||||||
}
|
if (!mRenderTargets.Create(RenderTargetId::LayerTemp, inputFrameWidth, inputFrameHeight, GL_RGBA16F, GL_RGBA, GL_FLOAT, "layer", error))
|
||||||
|
return false;
|
||||||
glBindFramebuffer(GL_FRAMEBUFFER, mLayerTempFrameBuf);
|
if (!mRenderTargets.Create(RenderTargetId::Composite, inputFrameWidth, inputFrameHeight, GL_RGBA16F, GL_RGBA, GL_FLOAT, "composite", error))
|
||||||
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, mLayerTempTexture, 0);
|
|
||||||
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
|
|
||||||
{
|
|
||||||
error = "Cannot initialize layer framebuffer.";
|
|
||||||
return false;
|
return false;
|
||||||
}
|
|
||||||
|
|
||||||
glBindFramebuffer(GL_FRAMEBUFFER, mIdFrameBuf);
|
|
||||||
glGenTextures(1, &mFBOTexture);
|
|
||||||
glBindTexture(GL_TEXTURE_2D, mFBOTexture);
|
|
||||||
ConfigureDisplayFrameTexture(inputFrameWidth, inputFrameHeight);
|
|
||||||
|
|
||||||
|
glBindFramebuffer(GL_FRAMEBUFFER, CompositeFramebuffer());
|
||||||
glBindRenderbuffer(GL_RENDERBUFFER, mIdDepthBuf);
|
glBindRenderbuffer(GL_RENDERBUFFER, mIdDepthBuf);
|
||||||
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, inputFrameWidth, inputFrameHeight);
|
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, inputFrameWidth, inputFrameHeight);
|
||||||
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER, mIdDepthBuf);
|
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER, mIdDepthBuf);
|
||||||
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, mFBOTexture, 0);
|
|
||||||
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
|
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
|
||||||
{
|
{
|
||||||
error = "Cannot initialize framebuffer.";
|
error = "Cannot initialize framebuffer.";
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
glGenTextures(1, &mOutputTexture);
|
if (!mRenderTargets.Create(RenderTargetId::Output, outputFrameWidth, outputFrameHeight, GL_RGBA16F, GL_RGBA, GL_FLOAT, "output", error))
|
||||||
glBindTexture(GL_TEXTURE_2D, mOutputTexture);
|
|
||||||
ConfigureDisplayFrameTexture(outputFrameWidth, outputFrameHeight);
|
|
||||||
|
|
||||||
glBindFramebuffer(GL_FRAMEBUFFER, mOutputFrameBuf);
|
|
||||||
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, mOutputTexture, 0);
|
|
||||||
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
|
|
||||||
{
|
|
||||||
error = "Cannot initialize output framebuffer.";
|
|
||||||
return false;
|
return false;
|
||||||
}
|
if (!mRenderTargets.Create(RenderTargetId::OutputPack, outputPackTextureWidth, outputFrameHeight, GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, "output pack", error))
|
||||||
|
|
||||||
glGenTextures(1, &mOutputPackTexture);
|
|
||||||
glBindTexture(GL_TEXTURE_2D, mOutputPackTexture);
|
|
||||||
ConfigureByteFrameTexture(outputPackTextureWidth, outputFrameHeight);
|
|
||||||
|
|
||||||
glBindFramebuffer(GL_FRAMEBUFFER, mOutputPackFrameBuf);
|
|
||||||
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, mOutputPackTexture, 0);
|
|
||||||
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
|
|
||||||
{
|
|
||||||
error = "Cannot initialize output pack framebuffer.";
|
|
||||||
return false;
|
return false;
|
||||||
}
|
|
||||||
|
|
||||||
glBindTexture(GL_TEXTURE_2D, 0);
|
glBindTexture(GL_TEXTURE_2D, 0);
|
||||||
glBindRenderbuffer(GL_RENDERBUFFER, 0);
|
glBindRenderbuffer(GL_RENDERBUFFER, 0);
|
||||||
@@ -120,6 +63,7 @@ bool OpenGLRenderer::InitializeResources(unsigned inputFrameWidth, unsigned inpu
|
|||||||
glBindBufferBase(GL_UNIFORM_BUFFER, kGlobalParamsBindingPoint, mGlobalParamsUBO);
|
glBindBufferBase(GL_UNIFORM_BUFFER, kGlobalParamsBindingPoint, mGlobalParamsUBO);
|
||||||
glBindBuffer(GL_UNIFORM_BUFFER, 0);
|
glBindBuffer(GL_UNIFORM_BUFFER, 0);
|
||||||
|
|
||||||
|
mResourcesInitialized = true;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -128,6 +72,9 @@ void OpenGLRenderer::SetDecodeShaderProgram(GLuint program, GLuint vertexShader,
|
|||||||
mDecodeProgram = program;
|
mDecodeProgram = program;
|
||||||
mDecodeVertexShader = vertexShader;
|
mDecodeVertexShader = vertexShader;
|
||||||
mDecodeFragmentShader = fragmentShader;
|
mDecodeFragmentShader = fragmentShader;
|
||||||
|
mDecodePackedResolutionLocation = program != 0 ? glGetUniformLocation(program, "uPackedVideoResolution") : -1;
|
||||||
|
mDecodeDecodedResolutionLocation = program != 0 ? glGetUniformLocation(program, "uDecodedVideoResolution") : -1;
|
||||||
|
mDecodeInputPixelFormatLocation = program != 0 ? glGetUniformLocation(program, "uInputPixelFormat") : -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
void OpenGLRenderer::SetOutputPackShaderProgram(GLuint program, GLuint vertexShader, GLuint fragmentShader)
|
void OpenGLRenderer::SetOutputPackShaderProgram(GLuint program, GLuint vertexShader, GLuint fragmentShader)
|
||||||
@@ -135,6 +82,14 @@ void OpenGLRenderer::SetOutputPackShaderProgram(GLuint program, GLuint vertexSha
|
|||||||
mOutputPackProgram = program;
|
mOutputPackProgram = program;
|
||||||
mOutputPackVertexShader = vertexShader;
|
mOutputPackVertexShader = vertexShader;
|
||||||
mOutputPackFragmentShader = fragmentShader;
|
mOutputPackFragmentShader = fragmentShader;
|
||||||
|
mOutputPackResolutionLocation = program != 0 ? glGetUniformLocation(program, "uOutputVideoResolution") : -1;
|
||||||
|
mOutputPackActiveWordsLocation = program != 0 ? glGetUniformLocation(program, "uActiveV210Words") : -1;
|
||||||
|
mOutputPackFormatLocation = program != 0 ? glGetUniformLocation(program, "uOutputPackFormat") : -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool OpenGLRenderer::ReserveTemporaryRenderTargets(std::size_t count, unsigned width, unsigned height, std::string& error)
|
||||||
|
{
|
||||||
|
return mRenderTargets.ReserveTemporaryTargets(count, width, height, GL_RGBA16F, GL_RGBA, GL_FLOAT, error);
|
||||||
}
|
}
|
||||||
|
|
||||||
void OpenGLRenderer::ResizeView(int width, int height)
|
void OpenGLRenderer::ResizeView(int width, int height)
|
||||||
@@ -169,7 +124,7 @@ void OpenGLRenderer::PresentToWindow(HDC hdc, unsigned outputFrameWidth, unsigne
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
glBindFramebuffer(GL_READ_FRAMEBUFFER, mOutputFrameBuf);
|
glBindFramebuffer(GL_READ_FRAMEBUFFER, OutputFramebuffer());
|
||||||
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
|
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
|
||||||
glDisable(GL_SCISSOR_TEST);
|
glDisable(GL_SCISSOR_TEST);
|
||||||
glViewport(0, 0, mViewWidth, mViewHeight);
|
glViewport(0, 0, mViewWidth, mViewHeight);
|
||||||
@@ -186,54 +141,27 @@ void OpenGLRenderer::DestroyResources()
|
|||||||
glDeleteVertexArrays(1, &mFullscreenVAO);
|
glDeleteVertexArrays(1, &mFullscreenVAO);
|
||||||
if (mGlobalParamsUBO != 0)
|
if (mGlobalParamsUBO != 0)
|
||||||
glDeleteBuffers(1, &mGlobalParamsUBO);
|
glDeleteBuffers(1, &mGlobalParamsUBO);
|
||||||
if (mDecodeFrameBuf != 0)
|
|
||||||
glDeleteFramebuffers(1, &mDecodeFrameBuf);
|
|
||||||
if (mLayerTempFrameBuf != 0)
|
|
||||||
glDeleteFramebuffers(1, &mLayerTempFrameBuf);
|
|
||||||
if (mIdFrameBuf != 0)
|
|
||||||
glDeleteFramebuffers(1, &mIdFrameBuf);
|
|
||||||
if (mOutputFrameBuf != 0)
|
|
||||||
glDeleteFramebuffers(1, &mOutputFrameBuf);
|
|
||||||
if (mOutputPackFrameBuf != 0)
|
|
||||||
glDeleteFramebuffers(1, &mOutputPackFrameBuf);
|
|
||||||
if (mIdColorBuf != 0)
|
if (mIdColorBuf != 0)
|
||||||
glDeleteRenderbuffers(1, &mIdColorBuf);
|
glDeleteRenderbuffers(1, &mIdColorBuf);
|
||||||
if (mIdDepthBuf != 0)
|
if (mIdDepthBuf != 0)
|
||||||
glDeleteRenderbuffers(1, &mIdDepthBuf);
|
glDeleteRenderbuffers(1, &mIdDepthBuf);
|
||||||
if (mCaptureTexture != 0)
|
if (mCaptureTexture != 0)
|
||||||
glDeleteTextures(1, &mCaptureTexture);
|
glDeleteTextures(1, &mCaptureTexture);
|
||||||
if (mDecodedTexture != 0)
|
|
||||||
glDeleteTextures(1, &mDecodedTexture);
|
|
||||||
if (mLayerTempTexture != 0)
|
|
||||||
glDeleteTextures(1, &mLayerTempTexture);
|
|
||||||
if (mFBOTexture != 0)
|
|
||||||
glDeleteTextures(1, &mFBOTexture);
|
|
||||||
if (mOutputTexture != 0)
|
|
||||||
glDeleteTextures(1, &mOutputTexture);
|
|
||||||
if (mOutputPackTexture != 0)
|
|
||||||
glDeleteTextures(1, &mOutputPackTexture);
|
|
||||||
if (mTextureUploadBuffer != 0)
|
if (mTextureUploadBuffer != 0)
|
||||||
glDeleteBuffers(1, &mTextureUploadBuffer);
|
glDeleteBuffers(1, &mTextureUploadBuffer);
|
||||||
|
mRenderTargets.Destroy();
|
||||||
|
|
||||||
mFullscreenVAO = 0;
|
mFullscreenVAO = 0;
|
||||||
mGlobalParamsUBO = 0;
|
mGlobalParamsUBO = 0;
|
||||||
mDecodeFrameBuf = 0;
|
|
||||||
mLayerTempFrameBuf = 0;
|
|
||||||
mIdFrameBuf = 0;
|
|
||||||
mOutputFrameBuf = 0;
|
|
||||||
mOutputPackFrameBuf = 0;
|
|
||||||
mIdColorBuf = 0;
|
mIdColorBuf = 0;
|
||||||
mIdDepthBuf = 0;
|
mIdDepthBuf = 0;
|
||||||
mCaptureTexture = 0;
|
mCaptureTexture = 0;
|
||||||
mDecodedTexture = 0;
|
|
||||||
mLayerTempTexture = 0;
|
|
||||||
mFBOTexture = 0;
|
|
||||||
mOutputTexture = 0;
|
|
||||||
mOutputPackTexture = 0;
|
|
||||||
mTextureUploadBuffer = 0;
|
mTextureUploadBuffer = 0;
|
||||||
mGlobalParamsUBOSize = 0;
|
mGlobalParamsUBOSize = 0;
|
||||||
|
mResourcesInitialized = false;
|
||||||
|
|
||||||
mTemporalHistory.DestroyResources();
|
mTemporalHistory.DestroyResources();
|
||||||
|
mFeedbackBuffers.DestroyResources();
|
||||||
DestroyLayerPrograms();
|
DestroyLayerPrograms();
|
||||||
DestroyDecodeShaderProgram();
|
DestroyDecodeShaderProgram();
|
||||||
DestroyOutputPackShaderProgram();
|
DestroyOutputPackShaderProgram();
|
||||||
@@ -241,43 +169,47 @@ void OpenGLRenderer::DestroyResources()
|
|||||||
|
|
||||||
void OpenGLRenderer::DestroySingleLayerProgram(LayerProgram& layerProgram)
|
void OpenGLRenderer::DestroySingleLayerProgram(LayerProgram& layerProgram)
|
||||||
{
|
{
|
||||||
for (LayerProgram::TextureBinding& binding : layerProgram.textureBindings)
|
for (LayerProgram::PassProgram& passProgram : layerProgram.passes)
|
||||||
{
|
{
|
||||||
if (binding.texture != 0)
|
for (LayerProgram::TextureBinding& binding : passProgram.textureBindings)
|
||||||
{
|
{
|
||||||
glDeleteTextures(1, &binding.texture);
|
if (binding.texture != 0)
|
||||||
binding.texture = 0;
|
{
|
||||||
|
glDeleteTextures(1, &binding.texture);
|
||||||
|
binding.texture = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
passProgram.textureBindings.clear();
|
||||||
|
|
||||||
|
for (LayerProgram::TextBinding& binding : passProgram.textBindings)
|
||||||
|
{
|
||||||
|
if (binding.texture != 0)
|
||||||
|
{
|
||||||
|
glDeleteTextures(1, &binding.texture);
|
||||||
|
binding.texture = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
passProgram.textBindings.clear();
|
||||||
|
|
||||||
|
if (passProgram.program != 0)
|
||||||
|
{
|
||||||
|
glDeleteProgram(passProgram.program);
|
||||||
|
passProgram.program = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (passProgram.fragmentShader != 0)
|
||||||
|
{
|
||||||
|
glDeleteShader(passProgram.fragmentShader);
|
||||||
|
passProgram.fragmentShader = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (passProgram.vertexShader != 0)
|
||||||
|
{
|
||||||
|
glDeleteShader(passProgram.vertexShader);
|
||||||
|
passProgram.vertexShader = 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
layerProgram.textureBindings.clear();
|
layerProgram.passes.clear();
|
||||||
|
|
||||||
for (LayerProgram::TextBinding& binding : layerProgram.textBindings)
|
|
||||||
{
|
|
||||||
if (binding.texture != 0)
|
|
||||||
{
|
|
||||||
glDeleteTextures(1, &binding.texture);
|
|
||||||
binding.texture = 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
layerProgram.textBindings.clear();
|
|
||||||
|
|
||||||
if (layerProgram.program != 0)
|
|
||||||
{
|
|
||||||
glDeleteProgram(layerProgram.program);
|
|
||||||
layerProgram.program = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (layerProgram.fragmentShader != 0)
|
|
||||||
{
|
|
||||||
glDeleteShader(layerProgram.fragmentShader);
|
|
||||||
layerProgram.fragmentShader = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (layerProgram.vertexShader != 0)
|
|
||||||
{
|
|
||||||
glDeleteShader(layerProgram.vertexShader);
|
|
||||||
layerProgram.vertexShader = 0;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void OpenGLRenderer::DestroyLayerPrograms()
|
void OpenGLRenderer::DestroyLayerPrograms()
|
||||||
@@ -294,6 +226,9 @@ void OpenGLRenderer::DestroyDecodeShaderProgram()
|
|||||||
glDeleteProgram(mDecodeProgram);
|
glDeleteProgram(mDecodeProgram);
|
||||||
mDecodeProgram = 0;
|
mDecodeProgram = 0;
|
||||||
}
|
}
|
||||||
|
mDecodePackedResolutionLocation = -1;
|
||||||
|
mDecodeDecodedResolutionLocation = -1;
|
||||||
|
mDecodeInputPixelFormatLocation = -1;
|
||||||
|
|
||||||
if (mDecodeFragmentShader != 0)
|
if (mDecodeFragmentShader != 0)
|
||||||
{
|
{
|
||||||
@@ -315,6 +250,9 @@ void OpenGLRenderer::DestroyOutputPackShaderProgram()
|
|||||||
glDeleteProgram(mOutputPackProgram);
|
glDeleteProgram(mOutputPackProgram);
|
||||||
mOutputPackProgram = 0;
|
mOutputPackProgram = 0;
|
||||||
}
|
}
|
||||||
|
mOutputPackResolutionLocation = -1;
|
||||||
|
mOutputPackActiveWordsLocation = -1;
|
||||||
|
mOutputPackFormatLocation = -1;
|
||||||
|
|
||||||
if (mOutputPackFragmentShader != 0)
|
if (mOutputPackFragmentShader != 0)
|
||||||
{
|
{
|
||||||
@@ -1,6 +1,8 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include "GLExtensions.h"
|
#include "GLExtensions.h"
|
||||||
|
#include "RenderTargetPool.h"
|
||||||
|
#include "ShaderFeedbackBuffers.h"
|
||||||
#include "ShaderTypes.h"
|
#include "ShaderTypes.h"
|
||||||
#include "TemporalHistoryBuffers.h"
|
#include "TemporalHistoryBuffers.h"
|
||||||
|
|
||||||
@@ -36,37 +38,58 @@ public:
|
|||||||
|
|
||||||
std::string layerId;
|
std::string layerId;
|
||||||
std::string shaderId;
|
std::string shaderId;
|
||||||
GLuint shaderTextureBase = 0;
|
|
||||||
GLuint program = 0;
|
struct PassProgram
|
||||||
GLuint vertexShader = 0;
|
{
|
||||||
GLuint fragmentShader = 0;
|
std::string passId;
|
||||||
std::vector<TextureBinding> textureBindings;
|
std::vector<std::string> inputNames;
|
||||||
std::vector<TextBinding> textBindings;
|
std::string outputName;
|
||||||
|
GLuint shaderTextureBase = 0;
|
||||||
|
GLuint program = 0;
|
||||||
|
GLuint vertexShader = 0;
|
||||||
|
GLuint fragmentShader = 0;
|
||||||
|
std::vector<TextureBinding> textureBindings;
|
||||||
|
std::vector<TextBinding> textBindings;
|
||||||
|
};
|
||||||
|
|
||||||
|
std::vector<PassProgram> passes;
|
||||||
};
|
};
|
||||||
|
|
||||||
GLuint CaptureTexture() const { return mCaptureTexture; }
|
GLuint CaptureTexture() const { return mCaptureTexture; }
|
||||||
GLuint DecodedTexture() const { return mDecodedTexture; }
|
GLuint DecodedTexture() const { return mRenderTargets.Texture(RenderTargetId::Decoded); }
|
||||||
GLuint LayerTempTexture() const { return mLayerTempTexture; }
|
GLuint LayerTempTexture() const { return mRenderTargets.Texture(RenderTargetId::LayerTemp); }
|
||||||
GLuint CompositeTexture() const { return mFBOTexture; }
|
GLuint CompositeTexture() const { return mRenderTargets.Texture(RenderTargetId::Composite); }
|
||||||
GLuint OutputTexture() const { return mOutputTexture; }
|
GLuint OutputTexture() const { return mRenderTargets.Texture(RenderTargetId::Output); }
|
||||||
GLuint OutputPackTexture() const { return mOutputPackTexture; }
|
GLuint OutputPackTexture() const { return mRenderTargets.Texture(RenderTargetId::OutputPack); }
|
||||||
GLuint TextureUploadBuffer() const { return mTextureUploadBuffer; }
|
GLuint TextureUploadBuffer() const { return mTextureUploadBuffer; }
|
||||||
GLuint DecodeFramebuffer() const { return mDecodeFrameBuf; }
|
GLuint DecodeFramebuffer() const { return mRenderTargets.Framebuffer(RenderTargetId::Decoded); }
|
||||||
GLuint LayerTempFramebuffer() const { return mLayerTempFrameBuf; }
|
GLuint LayerTempFramebuffer() const { return mRenderTargets.Framebuffer(RenderTargetId::LayerTemp); }
|
||||||
GLuint CompositeFramebuffer() const { return mIdFrameBuf; }
|
GLuint CompositeFramebuffer() const { return mRenderTargets.Framebuffer(RenderTargetId::Composite); }
|
||||||
GLuint OutputFramebuffer() const { return mOutputFrameBuf; }
|
GLuint OutputFramebuffer() const { return mRenderTargets.Framebuffer(RenderTargetId::Output); }
|
||||||
GLuint OutputPackFramebuffer() const { return mOutputPackFrameBuf; }
|
GLuint OutputPackFramebuffer() const { return mRenderTargets.Framebuffer(RenderTargetId::OutputPack); }
|
||||||
GLuint FullscreenVertexArray() const { return mFullscreenVAO; }
|
GLuint FullscreenVertexArray() const { return mFullscreenVAO; }
|
||||||
GLuint GlobalParamsUBO() const { return mGlobalParamsUBO; }
|
GLuint GlobalParamsUBO() const { return mGlobalParamsUBO; }
|
||||||
GLuint DecodeProgram() const { return mDecodeProgram; }
|
GLuint DecodeProgram() const { return mDecodeProgram; }
|
||||||
GLuint OutputPackProgram() const { return mOutputPackProgram; }
|
GLuint OutputPackProgram() const { return mOutputPackProgram; }
|
||||||
|
GLint DecodePackedResolutionLocation() const { return mDecodePackedResolutionLocation; }
|
||||||
|
GLint DecodeDecodedResolutionLocation() const { return mDecodeDecodedResolutionLocation; }
|
||||||
|
GLint DecodeInputPixelFormatLocation() const { return mDecodeInputPixelFormatLocation; }
|
||||||
|
GLint OutputPackResolutionLocation() const { return mOutputPackResolutionLocation; }
|
||||||
|
GLint OutputPackActiveWordsLocation() const { return mOutputPackActiveWordsLocation; }
|
||||||
|
GLint OutputPackFormatLocation() const { return mOutputPackFormatLocation; }
|
||||||
GLsizeiptr GlobalParamsUBOSize() const { return mGlobalParamsUBOSize; }
|
GLsizeiptr GlobalParamsUBOSize() const { return mGlobalParamsUBOSize; }
|
||||||
void SetGlobalParamsUBOSize(GLsizeiptr size) { mGlobalParamsUBOSize = size; }
|
void SetGlobalParamsUBOSize(GLsizeiptr size) { mGlobalParamsUBOSize = size; }
|
||||||
|
bool ResourcesInitialized() const { return mResourcesInitialized; }
|
||||||
void ReplaceLayerPrograms(std::vector<LayerProgram>& newPrograms) { mLayerPrograms.swap(newPrograms); }
|
void ReplaceLayerPrograms(std::vector<LayerProgram>& newPrograms) { mLayerPrograms.swap(newPrograms); }
|
||||||
std::vector<LayerProgram>& LayerPrograms() { return mLayerPrograms; }
|
std::vector<LayerProgram>& LayerPrograms() { return mLayerPrograms; }
|
||||||
const std::vector<LayerProgram>& LayerPrograms() const { return mLayerPrograms; }
|
const std::vector<LayerProgram>& LayerPrograms() const { return mLayerPrograms; }
|
||||||
|
bool ReserveTemporaryRenderTargets(std::size_t count, unsigned width, unsigned height, std::string& error);
|
||||||
|
const RenderTarget& TemporaryRenderTarget(std::size_t index) const { return mRenderTargets.TemporaryTarget(index); }
|
||||||
|
std::size_t TemporaryRenderTargetCount() const { return mRenderTargets.TemporaryTargetCount(); }
|
||||||
TemporalHistoryBuffers& TemporalHistory() { return mTemporalHistory; }
|
TemporalHistoryBuffers& TemporalHistory() { return mTemporalHistory; }
|
||||||
const TemporalHistoryBuffers& TemporalHistory() const { return mTemporalHistory; }
|
const TemporalHistoryBuffers& TemporalHistory() const { return mTemporalHistory; }
|
||||||
|
ShaderFeedbackBuffers& FeedbackBuffers() { return mFeedbackBuffers; }
|
||||||
|
const ShaderFeedbackBuffers& FeedbackBuffers() const { return mFeedbackBuffers; }
|
||||||
void SetDecodeShaderProgram(GLuint program, GLuint vertexShader, GLuint fragmentShader);
|
void SetDecodeShaderProgram(GLuint program, GLuint vertexShader, GLuint fragmentShader);
|
||||||
void SetOutputPackShaderProgram(GLuint program, GLuint vertexShader, GLuint fragmentShader);
|
void SetOutputPackShaderProgram(GLuint program, GLuint vertexShader, GLuint fragmentShader);
|
||||||
bool InitializeResources(unsigned inputFrameWidth, unsigned inputFrameHeight, unsigned captureTextureWidth, unsigned outputFrameWidth, unsigned outputFrameHeight, unsigned outputPackTextureWidth, std::string& error);
|
bool InitializeResources(unsigned inputFrameWidth, unsigned inputFrameHeight, unsigned captureTextureWidth, unsigned outputFrameWidth, unsigned outputFrameHeight, unsigned outputPackTextureWidth, std::string& error);
|
||||||
@@ -80,17 +103,7 @@ public:
|
|||||||
|
|
||||||
private:
|
private:
|
||||||
GLuint mCaptureTexture = 0;
|
GLuint mCaptureTexture = 0;
|
||||||
GLuint mDecodedTexture = 0;
|
|
||||||
GLuint mLayerTempTexture = 0;
|
|
||||||
GLuint mFBOTexture = 0;
|
|
||||||
GLuint mOutputTexture = 0;
|
|
||||||
GLuint mOutputPackTexture = 0;
|
|
||||||
GLuint mTextureUploadBuffer = 0;
|
GLuint mTextureUploadBuffer = 0;
|
||||||
GLuint mDecodeFrameBuf = 0;
|
|
||||||
GLuint mLayerTempFrameBuf = 0;
|
|
||||||
GLuint mIdFrameBuf = 0;
|
|
||||||
GLuint mOutputFrameBuf = 0;
|
|
||||||
GLuint mOutputPackFrameBuf = 0;
|
|
||||||
GLuint mIdColorBuf = 0;
|
GLuint mIdColorBuf = 0;
|
||||||
GLuint mIdDepthBuf = 0;
|
GLuint mIdDepthBuf = 0;
|
||||||
GLuint mFullscreenVAO = 0;
|
GLuint mFullscreenVAO = 0;
|
||||||
@@ -98,12 +111,21 @@ private:
|
|||||||
GLuint mDecodeProgram = 0;
|
GLuint mDecodeProgram = 0;
|
||||||
GLuint mDecodeVertexShader = 0;
|
GLuint mDecodeVertexShader = 0;
|
||||||
GLuint mDecodeFragmentShader = 0;
|
GLuint mDecodeFragmentShader = 0;
|
||||||
|
GLint mDecodePackedResolutionLocation = -1;
|
||||||
|
GLint mDecodeDecodedResolutionLocation = -1;
|
||||||
|
GLint mDecodeInputPixelFormatLocation = -1;
|
||||||
GLuint mOutputPackProgram = 0;
|
GLuint mOutputPackProgram = 0;
|
||||||
GLuint mOutputPackVertexShader = 0;
|
GLuint mOutputPackVertexShader = 0;
|
||||||
GLuint mOutputPackFragmentShader = 0;
|
GLuint mOutputPackFragmentShader = 0;
|
||||||
|
GLint mOutputPackResolutionLocation = -1;
|
||||||
|
GLint mOutputPackActiveWordsLocation = -1;
|
||||||
|
GLint mOutputPackFormatLocation = -1;
|
||||||
GLsizeiptr mGlobalParamsUBOSize = 0;
|
GLsizeiptr mGlobalParamsUBOSize = 0;
|
||||||
|
bool mResourcesInitialized = false;
|
||||||
int mViewWidth = 0;
|
int mViewWidth = 0;
|
||||||
int mViewHeight = 0;
|
int mViewHeight = 0;
|
||||||
std::vector<LayerProgram> mLayerPrograms;
|
std::vector<LayerProgram> mLayerPrograms;
|
||||||
|
RenderTargetPool mRenderTargets;
|
||||||
TemporalHistoryBuffers mTemporalHistory;
|
TemporalHistoryBuffers mTemporalHistory;
|
||||||
|
ShaderFeedbackBuffers mFeedbackBuffers;
|
||||||
};
|
};
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
#include "RenderTargetPool.h"
|
||||||
|
|
||||||
|
#include <cstddef>
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
void ConfigureRenderTargetTexture(
|
||||||
|
unsigned width,
|
||||||
|
unsigned height,
|
||||||
|
GLenum internalFormat,
|
||||||
|
GLenum pixelFormat,
|
||||||
|
GLenum pixelType)
|
||||||
|
{
|
||||||
|
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
|
||||||
|
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
|
||||||
|
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
|
||||||
|
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
|
||||||
|
glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, width, height, 0, pixelFormat, pixelType, NULL);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool RenderTargetPool::Create(
|
||||||
|
RenderTargetId id,
|
||||||
|
unsigned width,
|
||||||
|
unsigned height,
|
||||||
|
GLenum internalFormat,
|
||||||
|
GLenum pixelFormat,
|
||||||
|
GLenum pixelType,
|
||||||
|
const char* errorPrefix,
|
||||||
|
std::string& error)
|
||||||
|
{
|
||||||
|
RenderTarget& target = mTargets[TargetIndex(id)];
|
||||||
|
if (target.texture != 0 || target.framebuffer != 0)
|
||||||
|
{
|
||||||
|
error = std::string(errorPrefix) + " render target was already initialized.";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
glGenTextures(1, &target.texture);
|
||||||
|
glBindTexture(GL_TEXTURE_2D, target.texture);
|
||||||
|
ConfigureRenderTargetTexture(width, height, internalFormat, pixelFormat, pixelType);
|
||||||
|
glBindTexture(GL_TEXTURE_2D, 0);
|
||||||
|
|
||||||
|
glGenFramebuffers(1, &target.framebuffer);
|
||||||
|
glBindFramebuffer(GL_FRAMEBUFFER, target.framebuffer);
|
||||||
|
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, target.texture, 0);
|
||||||
|
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
|
||||||
|
{
|
||||||
|
error = std::string("Cannot initialize ") + errorPrefix + " framebuffer.";
|
||||||
|
glBindFramebuffer(GL_FRAMEBUFFER, 0);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
glBindFramebuffer(GL_FRAMEBUFFER, 0);
|
||||||
|
target.width = width;
|
||||||
|
target.height = height;
|
||||||
|
target.internalFormat = internalFormat;
|
||||||
|
target.pixelFormat = pixelFormat;
|
||||||
|
target.pixelType = pixelType;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool RenderTargetPool::ReserveTemporaryTargets(
|
||||||
|
std::size_t count,
|
||||||
|
unsigned width,
|
||||||
|
unsigned height,
|
||||||
|
GLenum internalFormat,
|
||||||
|
GLenum pixelFormat,
|
||||||
|
GLenum pixelType,
|
||||||
|
std::string& error)
|
||||||
|
{
|
||||||
|
if (mTemporaryTargets.size() == count)
|
||||||
|
return true;
|
||||||
|
|
||||||
|
DestroyTemporaryTargets();
|
||||||
|
|
||||||
|
mTemporaryTargets.resize(count);
|
||||||
|
for (std::size_t index = 0; index < mTemporaryTargets.size(); ++index)
|
||||||
|
{
|
||||||
|
RenderTarget& target = mTemporaryTargets[index];
|
||||||
|
glGenTextures(1, &target.texture);
|
||||||
|
glBindTexture(GL_TEXTURE_2D, target.texture);
|
||||||
|
ConfigureRenderTargetTexture(width, height, internalFormat, pixelFormat, pixelType);
|
||||||
|
glBindTexture(GL_TEXTURE_2D, 0);
|
||||||
|
|
||||||
|
glGenFramebuffers(1, &target.framebuffer);
|
||||||
|
glBindFramebuffer(GL_FRAMEBUFFER, target.framebuffer);
|
||||||
|
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, target.texture, 0);
|
||||||
|
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
|
||||||
|
{
|
||||||
|
error = "Cannot initialize temporary render target.";
|
||||||
|
glBindFramebuffer(GL_FRAMEBUFFER, 0);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
target.width = width;
|
||||||
|
target.height = height;
|
||||||
|
target.internalFormat = internalFormat;
|
||||||
|
target.pixelFormat = pixelFormat;
|
||||||
|
target.pixelType = pixelType;
|
||||||
|
}
|
||||||
|
|
||||||
|
glBindFramebuffer(GL_FRAMEBUFFER, 0);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void RenderTargetPool::DestroyTemporaryTargets()
|
||||||
|
{
|
||||||
|
for (RenderTarget& target : mTemporaryTargets)
|
||||||
|
{
|
||||||
|
if (target.framebuffer != 0)
|
||||||
|
glDeleteFramebuffers(1, &target.framebuffer);
|
||||||
|
if (target.texture != 0)
|
||||||
|
glDeleteTextures(1, &target.texture);
|
||||||
|
}
|
||||||
|
mTemporaryTargets.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
void RenderTargetPool::Destroy()
|
||||||
|
{
|
||||||
|
for (RenderTarget& target : mTargets)
|
||||||
|
{
|
||||||
|
if (target.framebuffer != 0)
|
||||||
|
glDeleteFramebuffers(1, &target.framebuffer);
|
||||||
|
if (target.texture != 0)
|
||||||
|
glDeleteTextures(1, &target.texture);
|
||||||
|
target = RenderTarget();
|
||||||
|
}
|
||||||
|
|
||||||
|
DestroyTemporaryTargets();
|
||||||
|
}
|
||||||
|
|
||||||
|
const RenderTarget& RenderTargetPool::Target(RenderTargetId id) const
|
||||||
|
{
|
||||||
|
return mTargets[TargetIndex(id)];
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "GLExtensions.h"
|
||||||
|
|
||||||
|
#include <array>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
enum class RenderTargetId
|
||||||
|
{
|
||||||
|
Decoded,
|
||||||
|
LayerTemp,
|
||||||
|
Composite,
|
||||||
|
Output,
|
||||||
|
OutputPack,
|
||||||
|
Count
|
||||||
|
};
|
||||||
|
|
||||||
|
struct RenderTarget
|
||||||
|
{
|
||||||
|
GLuint texture = 0;
|
||||||
|
GLuint framebuffer = 0;
|
||||||
|
unsigned width = 0;
|
||||||
|
unsigned height = 0;
|
||||||
|
GLenum internalFormat = GL_RGBA8;
|
||||||
|
GLenum pixelFormat = GL_RGBA;
|
||||||
|
GLenum pixelType = GL_UNSIGNED_BYTE;
|
||||||
|
};
|
||||||
|
|
||||||
|
class RenderTargetPool
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
bool Create(
|
||||||
|
RenderTargetId id,
|
||||||
|
unsigned width,
|
||||||
|
unsigned height,
|
||||||
|
GLenum internalFormat,
|
||||||
|
GLenum pixelFormat,
|
||||||
|
GLenum pixelType,
|
||||||
|
const char* errorPrefix,
|
||||||
|
std::string& error);
|
||||||
|
bool ReserveTemporaryTargets(
|
||||||
|
std::size_t count,
|
||||||
|
unsigned width,
|
||||||
|
unsigned height,
|
||||||
|
GLenum internalFormat,
|
||||||
|
GLenum pixelFormat,
|
||||||
|
GLenum pixelType,
|
||||||
|
std::string& error);
|
||||||
|
void DestroyTemporaryTargets();
|
||||||
|
void Destroy();
|
||||||
|
|
||||||
|
GLuint Texture(RenderTargetId id) const { return Target(id).texture; }
|
||||||
|
GLuint Framebuffer(RenderTargetId id) const { return Target(id).framebuffer; }
|
||||||
|
const RenderTarget& Target(RenderTargetId id) const;
|
||||||
|
const RenderTarget& TemporaryTarget(std::size_t index) const { return mTemporaryTargets[index]; }
|
||||||
|
std::size_t TemporaryTargetCount() const { return mTemporaryTargets.size(); }
|
||||||
|
|
||||||
|
private:
|
||||||
|
static std::size_t TargetIndex(RenderTargetId id) { return static_cast<std::size_t>(id); }
|
||||||
|
|
||||||
|
std::array<RenderTarget, static_cast<std::size_t>(RenderTargetId::Count)> mTargets;
|
||||||
|
std::vector<RenderTarget> mTemporaryTargets;
|
||||||
|
};
|
||||||
@@ -90,12 +90,17 @@ const char* kOutputPackFragmentShaderSource =
|
|||||||
"layout(binding = 0) uniform sampler2D uOutputRgb;\n"
|
"layout(binding = 0) uniform sampler2D uOutputRgb;\n"
|
||||||
"uniform vec2 uOutputVideoResolution;\n"
|
"uniform vec2 uOutputVideoResolution;\n"
|
||||||
"uniform float uActiveV210Words;\n"
|
"uniform float uActiveV210Words;\n"
|
||||||
|
"uniform int uOutputPackFormat;\n"
|
||||||
"in vec2 vTexCoord;\n"
|
"in vec2 vTexCoord;\n"
|
||||||
"layout(location = 0) out vec4 fragColor;\n"
|
"layout(location = 0) out vec4 fragColor;\n"
|
||||||
"vec3 rgbAt(int x, int y)\n"
|
"vec4 rgbaAt(int x, int y)\n"
|
||||||
"{\n"
|
"{\n"
|
||||||
" ivec2 size = ivec2(max(uOutputVideoResolution, vec2(1.0, 1.0)));\n"
|
" ivec2 size = ivec2(max(uOutputVideoResolution, vec2(1.0, 1.0)));\n"
|
||||||
" return clamp(texelFetch(uOutputRgb, ivec2(clamp(x, 0, size.x - 1), clamp(y, 0, size.y - 1)), 0).rgb, vec3(0.0), vec3(1.0));\n"
|
" return clamp(texelFetch(uOutputRgb, ivec2(clamp(x, 0, size.x - 1), clamp(y, 0, size.y - 1)), 0), vec4(0.0), vec4(1.0));\n"
|
||||||
|
"}\n"
|
||||||
|
"vec3 rgbAt(int x, int y)\n"
|
||||||
|
"{\n"
|
||||||
|
" return rgbaAt(x, y).rgb;\n"
|
||||||
"}\n"
|
"}\n"
|
||||||
"vec3 rgbToLegalYcbcr10(vec3 rgb)\n"
|
"vec3 rgbToLegalYcbcr10(vec3 rgb)\n"
|
||||||
"{\n"
|
"{\n"
|
||||||
@@ -112,9 +117,35 @@ const char* kOutputPackFragmentShaderSource =
|
|||||||
"{\n"
|
"{\n"
|
||||||
" return vec4(float(word & 255u), float((word >> 8) & 255u), float((word >> 16) & 255u), float((word >> 24) & 255u)) / 255.0;\n"
|
" return vec4(float(word & 255u), float((word >> 8) & 255u), float((word >> 16) & 255u), float((word >> 24) & 255u)) / 255.0;\n"
|
||||||
"}\n"
|
"}\n"
|
||||||
|
"vec4 bigEndianWordToBytes(uint word)\n"
|
||||||
|
"{\n"
|
||||||
|
" return vec4(float((word >> 24) & 255u), float((word >> 16) & 255u), float((word >> 8) & 255u), float(word & 255u)) / 255.0;\n"
|
||||||
|
"}\n"
|
||||||
|
"vec4 packAy10Word(ivec2 outCoord)\n"
|
||||||
|
"{\n"
|
||||||
|
" ivec2 size = ivec2(max(uOutputVideoResolution, vec2(1.0, 1.0)));\n"
|
||||||
|
" if (outCoord.x >= size.x)\n"
|
||||||
|
" return vec4(0.0);\n"
|
||||||
|
" int pixelBase = (outCoord.x / 2) * 2;\n"
|
||||||
|
" int y = outCoord.y;\n"
|
||||||
|
" vec4 rgba0 = rgbaAt(pixelBase + 0, y);\n"
|
||||||
|
" vec4 rgba1 = rgbaAt(pixelBase + 1, y);\n"
|
||||||
|
" vec3 c0 = rgbToLegalYcbcr10(rgba0.rgb);\n"
|
||||||
|
" vec3 c1 = rgbToLegalYcbcr10(rgba1.rgb);\n"
|
||||||
|
" float chroma = (outCoord.x & 1) == 0 ? round((c0.y + c1.y) * 0.5) : round((c0.z + c1.z) * 0.5);\n"
|
||||||
|
" float alpha = round(clamp(((outCoord.x & 1) == 0 ? rgba0.a : rgba1.a), 0.0, 1.0) * 1023.0);\n"
|
||||||
|
" float luma = (outCoord.x & 1) == 0 ? c0.x : c1.x;\n"
|
||||||
|
" uint word = ((uint(luma) & 1023u) << 22) | ((uint(chroma) & 1023u) << 12) | ((uint(alpha) & 1023u) << 2);\n"
|
||||||
|
" return bigEndianWordToBytes(word);\n"
|
||||||
|
"}\n"
|
||||||
"void main()\n"
|
"void main()\n"
|
||||||
"{\n"
|
"{\n"
|
||||||
" ivec2 outCoord = ivec2(gl_FragCoord.xy);\n"
|
" ivec2 outCoord = ivec2(gl_FragCoord.xy);\n"
|
||||||
|
" if (uOutputPackFormat == 2)\n"
|
||||||
|
" {\n"
|
||||||
|
" fragColor = packAy10Word(outCoord);\n"
|
||||||
|
" return;\n"
|
||||||
|
" }\n"
|
||||||
" if (float(outCoord.x) >= uActiveV210Words)\n"
|
" if (float(outCoord.x) >= uActiveV210Words)\n"
|
||||||
" {\n"
|
" {\n"
|
||||||
" fragColor = vec4(0.0);\n"
|
" fragColor = vec4(0.0);\n"
|
||||||
@@ -10,9 +10,10 @@ GlobalParamsBuffer::GlobalParamsBuffer(OpenGLRenderer& renderer) :
|
|||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
bool GlobalParamsBuffer::Update(const RuntimeRenderState& state, unsigned availableSourceHistoryLength, unsigned availableTemporalHistoryLength)
|
bool GlobalParamsBuffer::Update(const RuntimeRenderState& state, unsigned availableSourceHistoryLength, unsigned availableTemporalHistoryLength, bool feedbackAvailable)
|
||||||
{
|
{
|
||||||
std::vector<unsigned char> buffer;
|
std::vector<unsigned char>& buffer = mScratchBuffer;
|
||||||
|
buffer.clear();
|
||||||
buffer.reserve(512);
|
buffer.reserve(512);
|
||||||
|
|
||||||
AppendStd140Float(buffer, static_cast<float>(state.timeSeconds));
|
AppendStd140Float(buffer, static_cast<float>(state.timeSeconds));
|
||||||
@@ -32,6 +33,7 @@ bool GlobalParamsBuffer::Update(const RuntimeRenderState& state, unsigned availa
|
|||||||
: 0u;
|
: 0u;
|
||||||
AppendStd140Int(buffer, static_cast<int>(effectiveSourceHistoryLength));
|
AppendStd140Int(buffer, static_cast<int>(effectiveSourceHistoryLength));
|
||||||
AppendStd140Int(buffer, static_cast<int>(effectiveTemporalHistoryLength));
|
AppendStd140Int(buffer, static_cast<int>(effectiveTemporalHistoryLength));
|
||||||
|
AppendStd140Int(buffer, feedbackAvailable ? 1 : 0);
|
||||||
|
|
||||||
for (const ShaderParameterDefinition& definition : state.parameterDefinitions)
|
for (const ShaderParameterDefinition& definition : state.parameterDefinitions)
|
||||||
{
|
{
|
||||||
@@ -3,13 +3,16 @@
|
|||||||
#include "OpenGLRenderer.h"
|
#include "OpenGLRenderer.h"
|
||||||
#include "ShaderTypes.h"
|
#include "ShaderTypes.h"
|
||||||
|
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
class GlobalParamsBuffer
|
class GlobalParamsBuffer
|
||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
explicit GlobalParamsBuffer(OpenGLRenderer& renderer);
|
explicit GlobalParamsBuffer(OpenGLRenderer& renderer);
|
||||||
|
|
||||||
bool Update(const RuntimeRenderState& state, unsigned availableSourceHistoryLength, unsigned availableTemporalHistoryLength);
|
bool Update(const RuntimeRenderState& state, unsigned availableSourceHistoryLength, unsigned availableTemporalHistoryLength, bool feedbackAvailable);
|
||||||
|
|
||||||
private:
|
private:
|
||||||
OpenGLRenderer& mRenderer;
|
OpenGLRenderer& mRenderer;
|
||||||
|
std::vector<unsigned char> mScratchBuffer;
|
||||||
};
|
};
|
||||||
@@ -13,21 +13,37 @@ void CopyErrorMessage(const std::string& message, int errorMessageSize, char* er
|
|||||||
|
|
||||||
strncpy_s(errorMessage, errorMessageSize, message.c_str(), _TRUNCATE);
|
strncpy_s(errorMessage, errorMessageSize, message.c_str(), _TRUNCATE);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
std::size_t RequiredTemporaryRenderTargets(const std::vector<OpenGLRenderer::LayerProgram>& layerPrograms)
|
||||||
|
{
|
||||||
|
// Only one layer renders at a time, so the pool needs to cover the widest
|
||||||
|
// layer, not the sum of every intermediate pass in the stack.
|
||||||
|
std::size_t requiredTargets = 0;
|
||||||
|
for (const OpenGLRenderer::LayerProgram& layerProgram : layerPrograms)
|
||||||
|
{
|
||||||
|
const std::size_t internalPasses = layerProgram.passes.size() > 0 ? layerProgram.passes.size() - 1 : 0;
|
||||||
|
if (internalPasses > requiredTargets)
|
||||||
|
requiredTargets = internalPasses;
|
||||||
|
}
|
||||||
|
return requiredTargets;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
OpenGLShaderPrograms::OpenGLShaderPrograms(OpenGLRenderer& renderer, RuntimeHost& runtimeHost) :
|
OpenGLShaderPrograms::OpenGLShaderPrograms(OpenGLRenderer& renderer, RuntimeSnapshotProvider& runtimeSnapshotProvider) :
|
||||||
mRenderer(renderer),
|
mRenderer(renderer),
|
||||||
mRuntimeHost(runtimeHost),
|
mRuntimeSnapshotProvider(runtimeSnapshotProvider),
|
||||||
mGlobalParamsBuffer(renderer),
|
mGlobalParamsBuffer(renderer),
|
||||||
mCompiler(renderer, runtimeHost, mTextureBindings)
|
mCompiler(renderer, runtimeSnapshotProvider, mTextureBindings)
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
bool OpenGLShaderPrograms::CompileLayerPrograms(unsigned inputFrameWidth, unsigned inputFrameHeight, int errorMessageSize, char* errorMessage)
|
bool OpenGLShaderPrograms::CompileLayerPrograms(unsigned inputFrameWidth, unsigned inputFrameHeight, int errorMessageSize, char* errorMessage)
|
||||||
{
|
{
|
||||||
const std::vector<RuntimeRenderState> layerStates = mRuntimeHost.GetLayerRenderStates(inputFrameWidth, inputFrameHeight);
|
const RuntimeRenderStateSnapshot renderSnapshot =
|
||||||
|
mRuntimeSnapshotProvider.PublishRenderStateSnapshot(inputFrameWidth, inputFrameHeight);
|
||||||
|
const std::vector<RuntimeRenderState>& layerStates = renderSnapshot.states;
|
||||||
std::string temporalError;
|
std::string temporalError;
|
||||||
const unsigned historyCap = mRuntimeHost.GetMaxTemporalHistoryFrames();
|
const unsigned historyCap = mRuntimeSnapshotProvider.GetMaxTemporalHistoryFrames();
|
||||||
if (!mRenderer.TemporalHistory().ValidateTextureUnitBudget(layerStates, historyCap, temporalError))
|
if (!mRenderer.TemporalHistory().ValidateTextureUnitBudget(layerStates, historyCap, temporalError))
|
||||||
{
|
{
|
||||||
CopyErrorMessage(temporalError, errorMessageSize, errorMessage);
|
CopyErrorMessage(temporalError, errorMessageSize, errorMessage);
|
||||||
@@ -38,7 +54,15 @@ bool OpenGLShaderPrograms::CompileLayerPrograms(unsigned inputFrameWidth, unsign
|
|||||||
CopyErrorMessage(temporalError, errorMessageSize, errorMessage);
|
CopyErrorMessage(temporalError, errorMessageSize, errorMessage);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
if (mRenderer.ResourcesInitialized() &&
|
||||||
|
!mRenderer.FeedbackBuffers().EnsureResources(layerStates, inputFrameWidth, inputFrameHeight, temporalError))
|
||||||
|
{
|
||||||
|
CopyErrorMessage(temporalError, errorMessageSize, errorMessage);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Initial startup still compiles synchronously; auto-reload uses the build
|
||||||
|
// queue so Slang/file work stays off the playback path.
|
||||||
std::vector<LayerProgram> newPrograms;
|
std::vector<LayerProgram> newPrograms;
|
||||||
newPrograms.reserve(layerStates.size());
|
newPrograms.reserve(layerStates.size());
|
||||||
|
|
||||||
@@ -54,12 +78,18 @@ bool OpenGLShaderPrograms::CompileLayerPrograms(unsigned inputFrameWidth, unsign
|
|||||||
newPrograms.push_back(layerProgram);
|
newPrograms.push_back(layerProgram);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
std::string targetError;
|
||||||
|
if (!mRenderer.ReserveTemporaryRenderTargets(RequiredTemporaryRenderTargets(newPrograms), inputFrameWidth, inputFrameHeight, targetError))
|
||||||
|
{
|
||||||
|
for (LayerProgram& program : newPrograms)
|
||||||
|
DestroySingleLayerProgram(program);
|
||||||
|
CopyErrorMessage(targetError, errorMessageSize, errorMessage);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
DestroyLayerPrograms();
|
DestroyLayerPrograms();
|
||||||
mRenderer.ReplaceLayerPrograms(newPrograms);
|
mRenderer.ReplaceLayerPrograms(newPrograms);
|
||||||
mCommittedLayerStates = layerStates;
|
mCommittedLayerStates = renderSnapshot.states;
|
||||||
|
|
||||||
mRuntimeHost.SetCompileStatus(true, "Shader layers compiled successfully.");
|
|
||||||
mRuntimeHost.ClearReloadRequest();
|
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -73,25 +103,33 @@ bool OpenGLShaderPrograms::CommitPreparedLayerPrograms(const PreparedShaderBuild
|
|||||||
}
|
}
|
||||||
|
|
||||||
std::string temporalError;
|
std::string temporalError;
|
||||||
const unsigned historyCap = mRuntimeHost.GetMaxTemporalHistoryFrames();
|
const unsigned historyCap = mRuntimeSnapshotProvider.GetMaxTemporalHistoryFrames();
|
||||||
if (!mRenderer.TemporalHistory().ValidateTextureUnitBudget(preparedBuild.layerStates, historyCap, temporalError))
|
if (!mRenderer.TemporalHistory().ValidateTextureUnitBudget(preparedBuild.renderSnapshot.states, historyCap, temporalError))
|
||||||
{
|
{
|
||||||
CopyErrorMessage(temporalError, errorMessageSize, errorMessage);
|
CopyErrorMessage(temporalError, errorMessageSize, errorMessage);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
if (!mRenderer.TemporalHistory().EnsureResources(preparedBuild.layerStates, historyCap, inputFrameWidth, inputFrameHeight, temporalError))
|
if (!mRenderer.TemporalHistory().EnsureResources(preparedBuild.renderSnapshot.states, historyCap, inputFrameWidth, inputFrameHeight, temporalError))
|
||||||
|
{
|
||||||
|
CopyErrorMessage(temporalError, errorMessageSize, errorMessage);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (mRenderer.ResourcesInitialized() &&
|
||||||
|
!mRenderer.FeedbackBuffers().EnsureResources(preparedBuild.renderSnapshot.states, inputFrameWidth, inputFrameHeight, temporalError))
|
||||||
{
|
{
|
||||||
CopyErrorMessage(temporalError, errorMessageSize, errorMessage);
|
CopyErrorMessage(temporalError, errorMessageSize, errorMessage);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The prepared build already contains GLSL text for each pass. This commit
|
||||||
|
// step performs the short GL work on the render thread.
|
||||||
std::vector<LayerProgram> newPrograms;
|
std::vector<LayerProgram> newPrograms;
|
||||||
newPrograms.reserve(preparedBuild.layers.size());
|
newPrograms.reserve(preparedBuild.layers.size());
|
||||||
|
|
||||||
for (const PreparedLayerShader& preparedLayer : preparedBuild.layers)
|
for (const PreparedLayerShader& preparedLayer : preparedBuild.layers)
|
||||||
{
|
{
|
||||||
LayerProgram layerProgram;
|
LayerProgram layerProgram;
|
||||||
if (!mCompiler.CompilePreparedLayerProgram(preparedLayer.state, preparedLayer.fragmentShaderSource, layerProgram, errorMessageSize, errorMessage))
|
if (!mCompiler.CompilePreparedLayerProgram(preparedLayer.state, preparedLayer.passes, layerProgram, errorMessageSize, errorMessage))
|
||||||
{
|
{
|
||||||
for (LayerProgram& program : newPrograms)
|
for (LayerProgram& program : newPrograms)
|
||||||
DestroySingleLayerProgram(program);
|
DestroySingleLayerProgram(program);
|
||||||
@@ -100,12 +138,18 @@ bool OpenGLShaderPrograms::CommitPreparedLayerPrograms(const PreparedShaderBuild
|
|||||||
newPrograms.push_back(layerProgram);
|
newPrograms.push_back(layerProgram);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
std::string targetError;
|
||||||
|
if (!mRenderer.ReserveTemporaryRenderTargets(RequiredTemporaryRenderTargets(newPrograms), inputFrameWidth, inputFrameHeight, targetError))
|
||||||
|
{
|
||||||
|
for (LayerProgram& program : newPrograms)
|
||||||
|
DestroySingleLayerProgram(program);
|
||||||
|
CopyErrorMessage(targetError, errorMessageSize, errorMessage);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
DestroyLayerPrograms();
|
DestroyLayerPrograms();
|
||||||
mRenderer.ReplaceLayerPrograms(newPrograms);
|
mRenderer.ReplaceLayerPrograms(newPrograms);
|
||||||
mCommittedLayerStates = preparedBuild.layerStates;
|
mCommittedLayerStates = preparedBuild.renderSnapshot.states;
|
||||||
|
|
||||||
mRuntimeHost.SetCompileStatus(true, "Shader layers compiled successfully.");
|
|
||||||
mRuntimeHost.ClearReloadRequest();
|
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -140,12 +184,17 @@ void OpenGLShaderPrograms::ResetTemporalHistoryState()
|
|||||||
mRenderer.TemporalHistory().ResetState();
|
mRenderer.TemporalHistory().ResetState();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void OpenGLShaderPrograms::ResetShaderFeedbackState()
|
||||||
|
{
|
||||||
|
mRenderer.FeedbackBuffers().ResetState();
|
||||||
|
}
|
||||||
|
|
||||||
bool OpenGLShaderPrograms::UpdateTextBindingTexture(const RuntimeRenderState& state, LayerProgram::TextBinding& textBinding, std::string& error)
|
bool OpenGLShaderPrograms::UpdateTextBindingTexture(const RuntimeRenderState& state, LayerProgram::TextBinding& textBinding, std::string& error)
|
||||||
{
|
{
|
||||||
return mTextureBindings.UpdateTextBindingTexture(state, textBinding, error);
|
return mTextureBindings.UpdateTextBindingTexture(state, textBinding, error);
|
||||||
}
|
}
|
||||||
|
|
||||||
bool OpenGLShaderPrograms::UpdateGlobalParamsBuffer(const RuntimeRenderState& state, unsigned availableSourceHistoryLength, unsigned availableTemporalHistoryLength)
|
bool OpenGLShaderPrograms::UpdateGlobalParamsBuffer(const RuntimeRenderState& state, unsigned availableSourceHistoryLength, unsigned availableTemporalHistoryLength, bool feedbackAvailable)
|
||||||
{
|
{
|
||||||
return mGlobalParamsBuffer.Update(state, availableSourceHistoryLength, availableTemporalHistoryLength);
|
return mGlobalParamsBuffer.Update(state, availableSourceHistoryLength, availableTemporalHistoryLength, feedbackAvailable);
|
||||||
}
|
}
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
#include "GlobalParamsBuffer.h"
|
#include "GlobalParamsBuffer.h"
|
||||||
#include "OpenGLRenderer.h"
|
#include "OpenGLRenderer.h"
|
||||||
#include "RuntimeHost.h"
|
#include "RuntimeSnapshotProvider.h"
|
||||||
#include "ShaderBuildQueue.h"
|
#include "ShaderBuildQueue.h"
|
||||||
#include "ShaderTypes.h"
|
#include "ShaderTypes.h"
|
||||||
#include "ShaderProgramCompiler.h"
|
#include "ShaderProgramCompiler.h"
|
||||||
@@ -15,7 +15,7 @@ class OpenGLShaderPrograms
|
|||||||
public:
|
public:
|
||||||
using LayerProgram = OpenGLRenderer::LayerProgram;
|
using LayerProgram = OpenGLRenderer::LayerProgram;
|
||||||
|
|
||||||
OpenGLShaderPrograms(OpenGLRenderer& renderer, RuntimeHost& runtimeHost);
|
OpenGLShaderPrograms(OpenGLRenderer& renderer, RuntimeSnapshotProvider& runtimeSnapshotProvider);
|
||||||
|
|
||||||
bool CompileLayerPrograms(unsigned inputFrameWidth, unsigned inputFrameHeight, int errorMessageSize, char* errorMessage);
|
bool CompileLayerPrograms(unsigned inputFrameWidth, unsigned inputFrameHeight, int errorMessageSize, char* errorMessage);
|
||||||
bool CommitPreparedLayerPrograms(const PreparedShaderBuild& preparedBuild, unsigned inputFrameWidth, unsigned inputFrameHeight, int errorMessageSize, char* errorMessage);
|
bool CommitPreparedLayerPrograms(const PreparedShaderBuild& preparedBuild, unsigned inputFrameWidth, unsigned inputFrameHeight, int errorMessageSize, char* errorMessage);
|
||||||
@@ -25,13 +25,14 @@ public:
|
|||||||
void DestroySingleLayerProgram(LayerProgram& layerProgram);
|
void DestroySingleLayerProgram(LayerProgram& layerProgram);
|
||||||
void DestroyDecodeShaderProgram();
|
void DestroyDecodeShaderProgram();
|
||||||
void ResetTemporalHistoryState();
|
void ResetTemporalHistoryState();
|
||||||
|
void ResetShaderFeedbackState();
|
||||||
const std::vector<RuntimeRenderState>& CommittedLayerStates() const { return mCommittedLayerStates; }
|
const std::vector<RuntimeRenderState>& CommittedLayerStates() const { return mCommittedLayerStates; }
|
||||||
bool UpdateTextBindingTexture(const RuntimeRenderState& state, LayerProgram::TextBinding& textBinding, std::string& error);
|
bool UpdateTextBindingTexture(const RuntimeRenderState& state, LayerProgram::TextBinding& textBinding, std::string& error);
|
||||||
bool UpdateGlobalParamsBuffer(const RuntimeRenderState& state, unsigned availableSourceHistoryLength, unsigned availableTemporalHistoryLength);
|
bool UpdateGlobalParamsBuffer(const RuntimeRenderState& state, unsigned availableSourceHistoryLength, unsigned availableTemporalHistoryLength, bool feedbackAvailable);
|
||||||
|
|
||||||
private:
|
private:
|
||||||
OpenGLRenderer& mRenderer;
|
OpenGLRenderer& mRenderer;
|
||||||
RuntimeHost& mRuntimeHost;
|
RuntimeSnapshotProvider& mRuntimeSnapshotProvider;
|
||||||
ShaderTextureBindings mTextureBindings;
|
ShaderTextureBindings mTextureBindings;
|
||||||
GlobalParamsBuffer mGlobalParamsBuffer;
|
GlobalParamsBuffer mGlobalParamsBuffer;
|
||||||
ShaderProgramCompiler mCompiler;
|
ShaderProgramCompiler mCompiler;
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
#include "ShaderBuildQueue.h"
|
#include "ShaderBuildQueue.h"
|
||||||
|
|
||||||
#include "RuntimeHost.h"
|
#include "RuntimeEventDispatcher.h"
|
||||||
|
|
||||||
#include <chrono>
|
#include <chrono>
|
||||||
#include <utility>
|
#include <utility>
|
||||||
@@ -10,8 +10,9 @@ namespace
|
|||||||
constexpr auto kShaderBuildDebounce = std::chrono::milliseconds(400);
|
constexpr auto kShaderBuildDebounce = std::chrono::milliseconds(400);
|
||||||
}
|
}
|
||||||
|
|
||||||
ShaderBuildQueue::ShaderBuildQueue(RuntimeHost& runtimeHost) :
|
ShaderBuildQueue::ShaderBuildQueue(RuntimeSnapshotProvider& runtimeSnapshotProvider, RuntimeEventDispatcher& runtimeEventDispatcher) :
|
||||||
mRuntimeHost(runtimeHost),
|
mRuntimeSnapshotProvider(runtimeSnapshotProvider),
|
||||||
|
mRuntimeEventDispatcher(runtimeEventDispatcher),
|
||||||
mWorkerThread([this]() { WorkerLoop(); })
|
mWorkerThread([this]() { WorkerLoop(); })
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
@@ -46,6 +47,18 @@ bool ShaderBuildQueue::TryConsumeReadyBuild(PreparedShaderBuild& build)
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
bool ShaderBuildQueue::TryConsumeReadyBuild(uint64_t expectedGeneration, PreparedShaderBuild& build)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
|
if (!mHasReadyBuild || mReadyBuild.generation != expectedGeneration)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
build = std::move(mReadyBuild);
|
||||||
|
mReadyBuild = PreparedShaderBuild();
|
||||||
|
mHasReadyBuild = false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
void ShaderBuildQueue::Stop()
|
void ShaderBuildQueue::Stop()
|
||||||
{
|
{
|
||||||
{
|
{
|
||||||
@@ -99,13 +112,20 @@ void ShaderBuildQueue::WorkerLoop()
|
|||||||
|
|
||||||
PreparedShaderBuild build = Build(generation, outputWidth, outputHeight);
|
PreparedShaderBuild build = Build(generation, outputWidth, outputHeight);
|
||||||
|
|
||||||
std::lock_guard<std::mutex> lock(mMutex);
|
bool shouldPublish = false;
|
||||||
if (mStopping)
|
{
|
||||||
return;
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
if (generation != mRequestedGeneration)
|
if (mStopping)
|
||||||
continue;
|
return;
|
||||||
mReadyBuild = std::move(build);
|
if (generation != mRequestedGeneration)
|
||||||
mHasReadyBuild = true;
|
continue;
|
||||||
|
mReadyBuild = build;
|
||||||
|
mHasReadyBuild = true;
|
||||||
|
shouldPublish = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (shouldPublish)
|
||||||
|
PublishBuildLifecycleEvent(build, outputWidth, outputHeight);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -113,14 +133,14 @@ PreparedShaderBuild ShaderBuildQueue::Build(uint64_t generation, unsigned output
|
|||||||
{
|
{
|
||||||
PreparedShaderBuild build;
|
PreparedShaderBuild build;
|
||||||
build.generation = generation;
|
build.generation = generation;
|
||||||
build.layerStates = mRuntimeHost.GetLayerRenderStates(outputWidth, outputHeight);
|
build.renderSnapshot = mRuntimeSnapshotProvider.PublishRenderStateSnapshot(outputWidth, outputHeight);
|
||||||
build.layers.reserve(build.layerStates.size());
|
build.layers.reserve(build.renderSnapshot.states.size());
|
||||||
|
|
||||||
for (const RuntimeRenderState& state : build.layerStates)
|
for (const RuntimeRenderState& state : build.renderSnapshot.states)
|
||||||
{
|
{
|
||||||
PreparedLayerShader layer;
|
PreparedLayerShader layer;
|
||||||
layer.state = state;
|
layer.state = state;
|
||||||
if (!mRuntimeHost.BuildLayerFragmentShaderSource(state.layerId, layer.fragmentShaderSource, build.message))
|
if (!mRuntimeSnapshotProvider.BuildLayerPassFragmentShaderSources(state.layerId, layer.passes, build.message))
|
||||||
{
|
{
|
||||||
build.succeeded = false;
|
build.succeeded = false;
|
||||||
return build;
|
return build;
|
||||||
@@ -132,3 +152,15 @@ PreparedShaderBuild ShaderBuildQueue::Build(uint64_t generation, unsigned output
|
|||||||
build.message = "Shader layers prepared successfully.";
|
build.message = "Shader layers prepared successfully.";
|
||||||
return build;
|
return build;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void ShaderBuildQueue::PublishBuildLifecycleEvent(const PreparedShaderBuild& build, unsigned outputWidth, unsigned outputHeight) const
|
||||||
|
{
|
||||||
|
ShaderBuildEvent event;
|
||||||
|
event.phase = build.succeeded ? RuntimeEventShaderBuildPhase::Prepared : RuntimeEventShaderBuildPhase::Failed;
|
||||||
|
event.generation = build.generation;
|
||||||
|
event.inputWidth = outputWidth;
|
||||||
|
event.inputHeight = outputHeight;
|
||||||
|
event.succeeded = build.succeeded;
|
||||||
|
event.message = build.message;
|
||||||
|
mRuntimeEventDispatcher.PublishPayload(event, "ShaderBuildQueue");
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
|
#include "RuntimeSnapshotProvider.h"
|
||||||
#include "ShaderTypes.h"
|
#include "ShaderTypes.h"
|
||||||
|
|
||||||
#include <condition_variable>
|
#include <condition_variable>
|
||||||
@@ -9,12 +10,12 @@
|
|||||||
#include <thread>
|
#include <thread>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
class RuntimeHost;
|
class RuntimeEventDispatcher;
|
||||||
|
|
||||||
struct PreparedLayerShader
|
struct PreparedLayerShader
|
||||||
{
|
{
|
||||||
RuntimeRenderState state;
|
RuntimeRenderState state;
|
||||||
std::string fragmentShaderSource;
|
std::vector<ShaderPassBuildSource> passes;
|
||||||
};
|
};
|
||||||
|
|
||||||
struct PreparedShaderBuild
|
struct PreparedShaderBuild
|
||||||
@@ -22,14 +23,14 @@ struct PreparedShaderBuild
|
|||||||
uint64_t generation = 0;
|
uint64_t generation = 0;
|
||||||
bool succeeded = false;
|
bool succeeded = false;
|
||||||
std::string message;
|
std::string message;
|
||||||
std::vector<RuntimeRenderState> layerStates;
|
RuntimeRenderStateSnapshot renderSnapshot;
|
||||||
std::vector<PreparedLayerShader> layers;
|
std::vector<PreparedLayerShader> layers;
|
||||||
};
|
};
|
||||||
|
|
||||||
class ShaderBuildQueue
|
class ShaderBuildQueue
|
||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
explicit ShaderBuildQueue(RuntimeHost& runtimeHost);
|
ShaderBuildQueue(RuntimeSnapshotProvider& runtimeSnapshotProvider, RuntimeEventDispatcher& runtimeEventDispatcher);
|
||||||
~ShaderBuildQueue();
|
~ShaderBuildQueue();
|
||||||
|
|
||||||
ShaderBuildQueue(const ShaderBuildQueue&) = delete;
|
ShaderBuildQueue(const ShaderBuildQueue&) = delete;
|
||||||
@@ -37,13 +38,16 @@ public:
|
|||||||
|
|
||||||
void RequestBuild(unsigned outputWidth, unsigned outputHeight);
|
void RequestBuild(unsigned outputWidth, unsigned outputHeight);
|
||||||
bool TryConsumeReadyBuild(PreparedShaderBuild& build);
|
bool TryConsumeReadyBuild(PreparedShaderBuild& build);
|
||||||
|
bool TryConsumeReadyBuild(uint64_t expectedGeneration, PreparedShaderBuild& build);
|
||||||
void Stop();
|
void Stop();
|
||||||
|
|
||||||
private:
|
private:
|
||||||
void WorkerLoop();
|
void WorkerLoop();
|
||||||
PreparedShaderBuild Build(uint64_t generation, unsigned outputWidth, unsigned outputHeight);
|
PreparedShaderBuild Build(uint64_t generation, unsigned outputWidth, unsigned outputHeight);
|
||||||
|
void PublishBuildLifecycleEvent(const PreparedShaderBuild& build, unsigned outputWidth, unsigned outputHeight) const;
|
||||||
|
|
||||||
RuntimeHost& mRuntimeHost;
|
RuntimeSnapshotProvider& mRuntimeSnapshotProvider;
|
||||||
|
RuntimeEventDispatcher& mRuntimeEventDispatcher;
|
||||||
std::thread mWorkerThread;
|
std::thread mWorkerThread;
|
||||||
std::mutex mMutex;
|
std::mutex mMutex;
|
||||||
std::condition_variable mCondition;
|
std::condition_variable mCondition;
|
||||||
@@ -0,0 +1,233 @@
|
|||||||
|
#include "ShaderProgramCompiler.h"
|
||||||
|
|
||||||
|
#include "GlRenderConstants.h"
|
||||||
|
#include "GlScopedObjects.h"
|
||||||
|
#include "GlShaderSources.h"
|
||||||
|
|
||||||
|
#include <cstring>
|
||||||
|
#include <utility>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
void CopyErrorMessage(const std::string& message, int errorMessageSize, char* errorMessage)
|
||||||
|
{
|
||||||
|
if (!errorMessage || errorMessageSize <= 0)
|
||||||
|
return;
|
||||||
|
|
||||||
|
strncpy_s(errorMessage, errorMessageSize, message.c_str(), _TRUNCATE);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ShaderProgramCompiler::ShaderProgramCompiler(OpenGLRenderer& renderer, RuntimeSnapshotProvider& runtimeSnapshotProvider, ShaderTextureBindings& textureBindings) :
|
||||||
|
mRenderer(renderer),
|
||||||
|
mRuntimeSnapshotProvider(runtimeSnapshotProvider),
|
||||||
|
mTextureBindings(textureBindings)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ShaderProgramCompiler::CompileLayerProgram(const RuntimeRenderState& state, LayerProgram& layerProgram, int errorMessageSize, char* errorMessage)
|
||||||
|
{
|
||||||
|
std::vector<ShaderPassBuildSource> passSources;
|
||||||
|
std::string loadError;
|
||||||
|
|
||||||
|
if (!mRuntimeSnapshotProvider.BuildLayerPassFragmentShaderSources(state.layerId, passSources, loadError))
|
||||||
|
{
|
||||||
|
CopyErrorMessage(loadError, errorMessageSize, errorMessage);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return CompilePreparedLayerProgram(state, passSources, layerProgram, errorMessageSize, errorMessage);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ShaderProgramCompiler::CompilePreparedLayerProgram(const RuntimeRenderState& state, const std::vector<ShaderPassBuildSource>& passSources, LayerProgram& layerProgram, int errorMessageSize, char* errorMessage)
|
||||||
|
{
|
||||||
|
GLsizei errorBufferSize = 0;
|
||||||
|
std::string loadError;
|
||||||
|
const char* vertexSource = kFullscreenTriangleVertexShaderSource;
|
||||||
|
|
||||||
|
layerProgram.layerId = state.layerId;
|
||||||
|
layerProgram.shaderId = state.shaderId;
|
||||||
|
layerProgram.passes.clear();
|
||||||
|
|
||||||
|
for (const auto& passSource : passSources)
|
||||||
|
{
|
||||||
|
GLint compileResult = GL_FALSE;
|
||||||
|
GLint linkResult = GL_FALSE;
|
||||||
|
const char* fragmentSource = passSource.fragmentShaderSource.c_str();
|
||||||
|
|
||||||
|
ScopedGlShader newVertexShader(glCreateShader(GL_VERTEX_SHADER));
|
||||||
|
glShaderSource(newVertexShader.get(), 1, (const GLchar**)&vertexSource, NULL);
|
||||||
|
glCompileShader(newVertexShader.get());
|
||||||
|
glGetShaderiv(newVertexShader.get(), GL_COMPILE_STATUS, &compileResult);
|
||||||
|
if (compileResult == GL_FALSE)
|
||||||
|
{
|
||||||
|
glGetShaderInfoLog(newVertexShader.get(), errorMessageSize, &errorBufferSize, errorMessage);
|
||||||
|
mRenderer.DestroySingleLayerProgram(layerProgram);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
ScopedGlShader newFragmentShader(glCreateShader(GL_FRAGMENT_SHADER));
|
||||||
|
glShaderSource(newFragmentShader.get(), 1, (const GLchar**)&fragmentSource, NULL);
|
||||||
|
glCompileShader(newFragmentShader.get());
|
||||||
|
glGetShaderiv(newFragmentShader.get(), GL_COMPILE_STATUS, &compileResult);
|
||||||
|
if (compileResult == GL_FALSE)
|
||||||
|
{
|
||||||
|
glGetShaderInfoLog(newFragmentShader.get(), errorMessageSize, &errorBufferSize, errorMessage);
|
||||||
|
mRenderer.DestroySingleLayerProgram(layerProgram);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
ScopedGlProgram newProgram(glCreateProgram());
|
||||||
|
glAttachShader(newProgram.get(), newVertexShader.get());
|
||||||
|
glAttachShader(newProgram.get(), newFragmentShader.get());
|
||||||
|
glLinkProgram(newProgram.get());
|
||||||
|
glGetProgramiv(newProgram.get(), GL_LINK_STATUS, &linkResult);
|
||||||
|
if (linkResult == GL_FALSE)
|
||||||
|
{
|
||||||
|
glGetProgramInfoLog(newProgram.get(), errorMessageSize, &errorBufferSize, errorMessage);
|
||||||
|
mRenderer.DestroySingleLayerProgram(layerProgram);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<LayerProgram::TextureBinding> textureBindings;
|
||||||
|
for (const ShaderTextureAsset& textureAsset : state.textureAssets)
|
||||||
|
{
|
||||||
|
LayerProgram::TextureBinding textureBinding;
|
||||||
|
textureBinding.samplerName = textureAsset.id;
|
||||||
|
textureBinding.sourcePath = textureAsset.path;
|
||||||
|
if (!mTextureBindings.LoadTextureAsset(textureAsset, textureBinding.texture, loadError))
|
||||||
|
{
|
||||||
|
for (LayerProgram::TextureBinding& loadedTexture : textureBindings)
|
||||||
|
{
|
||||||
|
if (loadedTexture.texture != 0)
|
||||||
|
glDeleteTextures(1, &loadedTexture.texture);
|
||||||
|
}
|
||||||
|
CopyErrorMessage(loadError, errorMessageSize, errorMessage);
|
||||||
|
mRenderer.DestroySingleLayerProgram(layerProgram);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
textureBindings.push_back(textureBinding);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<LayerProgram::TextBinding> textBindings;
|
||||||
|
mTextureBindings.CreateTextBindings(state, textBindings);
|
||||||
|
|
||||||
|
PassProgram passProgram;
|
||||||
|
passProgram.passId = passSource.passId;
|
||||||
|
passProgram.inputNames = passSource.inputNames;
|
||||||
|
passProgram.outputName = passSource.outputName;
|
||||||
|
passProgram.shaderTextureBase = mTextureBindings.ResolveShaderTextureBase(state, mRuntimeSnapshotProvider.GetMaxTemporalHistoryFrames());
|
||||||
|
passProgram.textureBindings.swap(textureBindings);
|
||||||
|
passProgram.textBindings.swap(textBindings);
|
||||||
|
|
||||||
|
const GLuint globalParamsIndex = glGetUniformBlockIndex(newProgram.get(), "GlobalParams");
|
||||||
|
if (globalParamsIndex != GL_INVALID_INDEX)
|
||||||
|
glUniformBlockBinding(newProgram.get(), globalParamsIndex, kGlobalParamsBindingPoint);
|
||||||
|
|
||||||
|
const unsigned historyCap = mRuntimeSnapshotProvider.GetMaxTemporalHistoryFrames();
|
||||||
|
glUseProgram(newProgram.get());
|
||||||
|
mTextureBindings.AssignLayerSamplerUniforms(newProgram.get(), state, passProgram, historyCap);
|
||||||
|
glUseProgram(0);
|
||||||
|
|
||||||
|
passProgram.program = newProgram.release();
|
||||||
|
passProgram.vertexShader = newVertexShader.release();
|
||||||
|
passProgram.fragmentShader = newFragmentShader.release();
|
||||||
|
layerProgram.passes.push_back(std::move(passProgram));
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ShaderProgramCompiler::CompileDecodeShader(int errorMessageSize, char* errorMessage)
|
||||||
|
{
|
||||||
|
GLsizei errorBufferSize = 0;
|
||||||
|
GLint compileResult = GL_FALSE;
|
||||||
|
GLint linkResult = GL_FALSE;
|
||||||
|
const char* vertexSource = kFullscreenTriangleVertexShaderSource;
|
||||||
|
const char* fragmentSource = kDecodeFragmentShaderSource;
|
||||||
|
|
||||||
|
ScopedGlShader newVertexShader(glCreateShader(GL_VERTEX_SHADER));
|
||||||
|
glShaderSource(newVertexShader.get(), 1, (const GLchar**)&vertexSource, NULL);
|
||||||
|
glCompileShader(newVertexShader.get());
|
||||||
|
glGetShaderiv(newVertexShader.get(), GL_COMPILE_STATUS, &compileResult);
|
||||||
|
if (compileResult == GL_FALSE)
|
||||||
|
{
|
||||||
|
glGetShaderInfoLog(newVertexShader.get(), errorMessageSize, &errorBufferSize, errorMessage);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
ScopedGlShader newFragmentShader(glCreateShader(GL_FRAGMENT_SHADER));
|
||||||
|
glShaderSource(newFragmentShader.get(), 1, (const GLchar**)&fragmentSource, NULL);
|
||||||
|
glCompileShader(newFragmentShader.get());
|
||||||
|
glGetShaderiv(newFragmentShader.get(), GL_COMPILE_STATUS, &compileResult);
|
||||||
|
if (compileResult == GL_FALSE)
|
||||||
|
{
|
||||||
|
glGetShaderInfoLog(newFragmentShader.get(), errorMessageSize, &errorBufferSize, errorMessage);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
ScopedGlProgram newProgram(glCreateProgram());
|
||||||
|
glAttachShader(newProgram.get(), newVertexShader.get());
|
||||||
|
glAttachShader(newProgram.get(), newFragmentShader.get());
|
||||||
|
glLinkProgram(newProgram.get());
|
||||||
|
glGetProgramiv(newProgram.get(), GL_LINK_STATUS, &linkResult);
|
||||||
|
if (linkResult == GL_FALSE)
|
||||||
|
{
|
||||||
|
glGetProgramInfoLog(newProgram.get(), errorMessageSize, &errorBufferSize, errorMessage);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
mRenderer.DestroyDecodeShaderProgram();
|
||||||
|
mRenderer.SetDecodeShaderProgram(newProgram.release(), newVertexShader.release(), newFragmentShader.release());
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ShaderProgramCompiler::CompileOutputPackShader(int errorMessageSize, char* errorMessage)
|
||||||
|
{
|
||||||
|
GLsizei errorBufferSize = 0;
|
||||||
|
GLint compileResult = GL_FALSE;
|
||||||
|
GLint linkResult = GL_FALSE;
|
||||||
|
const char* vertexSource = kFullscreenTriangleVertexShaderSource;
|
||||||
|
const char* fragmentSource = kOutputPackFragmentShaderSource;
|
||||||
|
|
||||||
|
ScopedGlShader newVertexShader(glCreateShader(GL_VERTEX_SHADER));
|
||||||
|
glShaderSource(newVertexShader.get(), 1, (const GLchar**)&vertexSource, NULL);
|
||||||
|
glCompileShader(newVertexShader.get());
|
||||||
|
glGetShaderiv(newVertexShader.get(), GL_COMPILE_STATUS, &compileResult);
|
||||||
|
if (compileResult == GL_FALSE)
|
||||||
|
{
|
||||||
|
glGetShaderInfoLog(newVertexShader.get(), errorMessageSize, &errorBufferSize, errorMessage);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
ScopedGlShader newFragmentShader(glCreateShader(GL_FRAGMENT_SHADER));
|
||||||
|
glShaderSource(newFragmentShader.get(), 1, (const GLchar**)&fragmentSource, NULL);
|
||||||
|
glCompileShader(newFragmentShader.get());
|
||||||
|
glGetShaderiv(newFragmentShader.get(), GL_COMPILE_STATUS, &compileResult);
|
||||||
|
if (compileResult == GL_FALSE)
|
||||||
|
{
|
||||||
|
glGetShaderInfoLog(newFragmentShader.get(), errorMessageSize, &errorBufferSize, errorMessage);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
ScopedGlProgram newProgram(glCreateProgram());
|
||||||
|
glAttachShader(newProgram.get(), newVertexShader.get());
|
||||||
|
glAttachShader(newProgram.get(), newFragmentShader.get());
|
||||||
|
glLinkProgram(newProgram.get());
|
||||||
|
glGetProgramiv(newProgram.get(), GL_LINK_STATUS, &linkResult);
|
||||||
|
if (linkResult == GL_FALSE)
|
||||||
|
{
|
||||||
|
glGetProgramInfoLog(newProgram.get(), errorMessageSize, &errorBufferSize, errorMessage);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
glUseProgram(newProgram.get());
|
||||||
|
const GLint outputSamplerLocation = glGetUniformLocation(newProgram.get(), "uOutputRgb");
|
||||||
|
if (outputSamplerLocation >= 0)
|
||||||
|
glUniform1i(outputSamplerLocation, 0);
|
||||||
|
glUseProgram(0);
|
||||||
|
|
||||||
|
mRenderer.DestroyOutputPackShaderProgram();
|
||||||
|
mRenderer.SetOutputPackShaderProgram(newProgram.release(), newVertexShader.release(), newFragmentShader.release());
|
||||||
|
return true;
|
||||||
|
}
|
||||||
@@ -1,25 +1,27 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include "OpenGLRenderer.h"
|
#include "OpenGLRenderer.h"
|
||||||
#include "RuntimeHost.h"
|
#include "RuntimeSnapshotProvider.h"
|
||||||
#include "ShaderTextureBindings.h"
|
#include "ShaderTextureBindings.h"
|
||||||
|
|
||||||
#include <string>
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
class ShaderProgramCompiler
|
class ShaderProgramCompiler
|
||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
using LayerProgram = OpenGLRenderer::LayerProgram;
|
using LayerProgram = OpenGLRenderer::LayerProgram;
|
||||||
|
using PassProgram = OpenGLRenderer::LayerProgram::PassProgram;
|
||||||
|
|
||||||
ShaderProgramCompiler(OpenGLRenderer& renderer, RuntimeHost& runtimeHost, ShaderTextureBindings& textureBindings);
|
ShaderProgramCompiler(OpenGLRenderer& renderer, RuntimeSnapshotProvider& runtimeSnapshotProvider, ShaderTextureBindings& textureBindings);
|
||||||
|
|
||||||
bool CompileLayerProgram(const RuntimeRenderState& state, LayerProgram& layerProgram, int errorMessageSize, char* errorMessage);
|
bool CompileLayerProgram(const RuntimeRenderState& state, LayerProgram& layerProgram, int errorMessageSize, char* errorMessage);
|
||||||
bool CompilePreparedLayerProgram(const RuntimeRenderState& state, const std::string& fragmentShaderSource, LayerProgram& layerProgram, int errorMessageSize, char* errorMessage);
|
bool CompilePreparedLayerProgram(const RuntimeRenderState& state, const std::vector<ShaderPassBuildSource>& passSources, LayerProgram& layerProgram, int errorMessageSize, char* errorMessage);
|
||||||
bool CompileDecodeShader(int errorMessageSize, char* errorMessage);
|
bool CompileDecodeShader(int errorMessageSize, char* errorMessage);
|
||||||
bool CompileOutputPackShader(int errorMessageSize, char* errorMessage);
|
bool CompileOutputPackShader(int errorMessageSize, char* errorMessage);
|
||||||
|
|
||||||
private:
|
private:
|
||||||
OpenGLRenderer& mRenderer;
|
OpenGLRenderer& mRenderer;
|
||||||
RuntimeHost& mRuntimeHost;
|
RuntimeSnapshotProvider& mRuntimeSnapshotProvider;
|
||||||
ShaderTextureBindings& mTextureBindings;
|
ShaderTextureBindings& mTextureBindings;
|
||||||
};
|
};
|
||||||
@@ -0,0 +1,256 @@
|
|||||||
|
#include "ShaderTextureBindings.h"
|
||||||
|
|
||||||
|
#include "GlRenderConstants.h"
|
||||||
|
#include "TextRasterizer.h"
|
||||||
|
#include "TextureAssetLoader.h"
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <filesystem>
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
std::string TextValueForBinding(const RuntimeRenderState& state, const std::string& parameterId)
|
||||||
|
{
|
||||||
|
auto valueIt = state.parameterValues.find(parameterId);
|
||||||
|
return valueIt == state.parameterValues.end() ? std::string() : valueIt->second.textValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ShaderFontAsset* FindFontAssetForParameter(const RuntimeRenderState& state, const ShaderParameterDefinition& definition)
|
||||||
|
{
|
||||||
|
if (!definition.fontId.empty())
|
||||||
|
{
|
||||||
|
for (const ShaderFontAsset& fontAsset : state.fontAssets)
|
||||||
|
{
|
||||||
|
if (fontAsset.id == definition.fontId)
|
||||||
|
return &fontAsset;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return state.fontAssets.empty() ? nullptr : &state.fontAssets.front();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ShaderTextureBindings::LoadTextureAsset(const ShaderTextureAsset& textureAsset, GLuint& textureId, std::string& error)
|
||||||
|
{
|
||||||
|
return ::LoadTextureAsset(textureAsset, textureId, error);
|
||||||
|
}
|
||||||
|
|
||||||
|
void ShaderTextureBindings::CreateTextBindings(const RuntimeRenderState& state, std::vector<LayerProgram::TextBinding>& textBindings)
|
||||||
|
{
|
||||||
|
for (const ShaderParameterDefinition& definition : state.parameterDefinitions)
|
||||||
|
{
|
||||||
|
if (definition.type != ShaderParameterType::Text)
|
||||||
|
continue;
|
||||||
|
LayerProgram::TextBinding textBinding;
|
||||||
|
textBinding.parameterId = definition.id;
|
||||||
|
textBinding.samplerName = definition.id + "Texture";
|
||||||
|
textBinding.fontId = definition.fontId;
|
||||||
|
glGenTextures(1, &textBinding.texture);
|
||||||
|
glBindTexture(GL_TEXTURE_2D, textBinding.texture);
|
||||||
|
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
|
||||||
|
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
|
||||||
|
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
|
||||||
|
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
|
||||||
|
std::vector<unsigned char> empty(static_cast<std::size_t>(kTextTextureWidth) * kTextTextureHeight * 4, 0);
|
||||||
|
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, kTextTextureWidth, kTextTextureHeight, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, empty.data());
|
||||||
|
glBindTexture(GL_TEXTURE_2D, 0);
|
||||||
|
textBindings.push_back(textBinding);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ShaderTextureBindings::UpdateTextBindingTexture(const RuntimeRenderState& state, LayerProgram::TextBinding& textBinding, std::string& error)
|
||||||
|
{
|
||||||
|
const std::string text = TextValueForBinding(state, textBinding.parameterId);
|
||||||
|
if (text == textBinding.renderedText && textBinding.renderedWidth == kTextTextureWidth && textBinding.renderedHeight == kTextTextureHeight)
|
||||||
|
return true;
|
||||||
|
|
||||||
|
auto definitionIt = std::find_if(state.parameterDefinitions.begin(), state.parameterDefinitions.end(),
|
||||||
|
[&textBinding](const ShaderParameterDefinition& definition) { return definition.id == textBinding.parameterId; });
|
||||||
|
if (definitionIt == state.parameterDefinitions.end())
|
||||||
|
return true;
|
||||||
|
|
||||||
|
const ShaderFontAsset* fontAsset = FindFontAssetForParameter(state, *definitionIt);
|
||||||
|
std::filesystem::path fontPath;
|
||||||
|
if (fontAsset)
|
||||||
|
fontPath = fontAsset->path;
|
||||||
|
|
||||||
|
std::vector<unsigned char> sdf;
|
||||||
|
if (!RasterizeTextSdf(text, fontPath, sdf, error))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
GLint previousActiveTexture = 0;
|
||||||
|
GLint previousUnpackBuffer = 0;
|
||||||
|
glGetIntegerv(GL_ACTIVE_TEXTURE, &previousActiveTexture);
|
||||||
|
glGetIntegerv(GL_PIXEL_UNPACK_BUFFER_BINDING, &previousUnpackBuffer);
|
||||||
|
glActiveTexture(GL_TEXTURE0);
|
||||||
|
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
|
||||||
|
glBindTexture(GL_TEXTURE_2D, textBinding.texture);
|
||||||
|
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, kTextTextureWidth, kTextTextureHeight, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, sdf.data());
|
||||||
|
glBindTexture(GL_TEXTURE_2D, 0);
|
||||||
|
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, static_cast<GLuint>(previousUnpackBuffer));
|
||||||
|
glActiveTexture(static_cast<GLenum>(previousActiveTexture));
|
||||||
|
|
||||||
|
textBinding.renderedText = text;
|
||||||
|
textBinding.renderedWidth = kTextTextureWidth;
|
||||||
|
textBinding.renderedHeight = kTextTextureHeight;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
GLint ShaderTextureBindings::FindSamplerUniformLocation(GLuint program, const std::string& samplerName) const
|
||||||
|
{
|
||||||
|
GLint location = glGetUniformLocation(program, samplerName.c_str());
|
||||||
|
if (location >= 0)
|
||||||
|
return location;
|
||||||
|
return glGetUniformLocation(program, (samplerName + "_0").c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
GLuint ShaderTextureBindings::ResolveFeedbackTextureUnit(const RuntimeRenderState& state, unsigned historyCap) const
|
||||||
|
{
|
||||||
|
return state.isTemporal ? kSourceHistoryTextureUnitBase + historyCap + historyCap : kSourceHistoryTextureUnitBase;
|
||||||
|
}
|
||||||
|
|
||||||
|
GLuint ShaderTextureBindings::ResolveShaderTextureBase(const RuntimeRenderState& state, unsigned historyCap) const
|
||||||
|
{
|
||||||
|
return ResolveFeedbackTextureUnit(state, historyCap) + (state.feedback.enabled ? 1u : 0u);
|
||||||
|
}
|
||||||
|
|
||||||
|
void ShaderTextureBindings::AssignLayerSamplerUniforms(GLuint program, const RuntimeRenderState& state, const PassProgram& passProgram, unsigned historyCap) const
|
||||||
|
{
|
||||||
|
const GLuint shaderTextureBase = ResolveShaderTextureBase(state, historyCap);
|
||||||
|
|
||||||
|
const GLint layerInputLocation = FindSamplerUniformLocation(program, "gLayerInput");
|
||||||
|
if (layerInputLocation >= 0)
|
||||||
|
glUniform1i(layerInputLocation, static_cast<GLint>(kLayerInputTextureUnit));
|
||||||
|
|
||||||
|
const GLint videoInputLocation = FindSamplerUniformLocation(program, "gVideoInput");
|
||||||
|
if (videoInputLocation >= 0)
|
||||||
|
glUniform1i(videoInputLocation, static_cast<GLint>(kDecodedVideoTextureUnit));
|
||||||
|
|
||||||
|
for (unsigned index = 0; index < historyCap; ++index)
|
||||||
|
{
|
||||||
|
const std::string sourceSamplerName = "gSourceHistory" + std::to_string(index);
|
||||||
|
const GLint sourceSamplerLocation = glGetUniformLocation(program, sourceSamplerName.c_str());
|
||||||
|
if (sourceSamplerLocation >= 0)
|
||||||
|
glUniform1i(sourceSamplerLocation, static_cast<GLint>(kSourceHistoryTextureUnitBase + index));
|
||||||
|
|
||||||
|
const std::string temporalSamplerName = "gTemporalHistory" + std::to_string(index);
|
||||||
|
const GLint temporalSamplerLocation = glGetUniformLocation(program, temporalSamplerName.c_str());
|
||||||
|
if (temporalSamplerLocation >= 0)
|
||||||
|
glUniform1i(temporalSamplerLocation, static_cast<GLint>(kSourceHistoryTextureUnitBase + historyCap + index));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (state.feedback.enabled)
|
||||||
|
{
|
||||||
|
const GLint feedbackSamplerLocation = FindSamplerUniformLocation(program, "gFeedbackState");
|
||||||
|
if (feedbackSamplerLocation >= 0)
|
||||||
|
glUniform1i(feedbackSamplerLocation, static_cast<GLint>(ResolveFeedbackTextureUnit(state, historyCap)));
|
||||||
|
}
|
||||||
|
|
||||||
|
for (std::size_t index = 0; index < passProgram.textureBindings.size(); ++index)
|
||||||
|
{
|
||||||
|
const GLint textureSamplerLocation = FindSamplerUniformLocation(program, passProgram.textureBindings[index].samplerName);
|
||||||
|
if (textureSamplerLocation >= 0)
|
||||||
|
glUniform1i(textureSamplerLocation, static_cast<GLint>(shaderTextureBase + static_cast<GLuint>(index)));
|
||||||
|
}
|
||||||
|
|
||||||
|
const GLuint textTextureBase = shaderTextureBase + static_cast<GLuint>(passProgram.textureBindings.size());
|
||||||
|
for (std::size_t index = 0; index < passProgram.textBindings.size(); ++index)
|
||||||
|
{
|
||||||
|
const GLint textSamplerLocation = FindSamplerUniformLocation(program, passProgram.textBindings[index].samplerName);
|
||||||
|
if (textSamplerLocation >= 0)
|
||||||
|
glUniform1i(textSamplerLocation, static_cast<GLint>(textTextureBase + static_cast<GLuint>(index)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ShaderTextureBindings::RuntimeTextureBindingPlan ShaderTextureBindings::BuildLayerRuntimeBindingPlan(
|
||||||
|
const PassProgram& passProgram,
|
||||||
|
GLuint layerInputTexture,
|
||||||
|
GLuint originalLayerInputTexture,
|
||||||
|
const RuntimeRenderState& state,
|
||||||
|
GLuint feedbackTexture,
|
||||||
|
const std::vector<GLuint>& sourceHistoryTextures,
|
||||||
|
const std::vector<GLuint>& temporalHistoryTextures) const
|
||||||
|
{
|
||||||
|
RuntimeTextureBindingPlan plan;
|
||||||
|
plan.bindings.push_back({ "originalLayerInput", "gLayerInput", originalLayerInputTexture, kLayerInputTextureUnit });
|
||||||
|
plan.bindings.push_back({ "layerInput", "gVideoInput", layerInputTexture, kDecodedVideoTextureUnit });
|
||||||
|
|
||||||
|
for (std::size_t index = 0; index < sourceHistoryTextures.size(); ++index)
|
||||||
|
{
|
||||||
|
plan.bindings.push_back({
|
||||||
|
"sourceHistory",
|
||||||
|
"gSourceHistory" + std::to_string(index),
|
||||||
|
sourceHistoryTextures[index],
|
||||||
|
kSourceHistoryTextureUnitBase + static_cast<GLuint>(index)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const GLuint temporalBase = kSourceHistoryTextureUnitBase + static_cast<GLuint>(sourceHistoryTextures.size());
|
||||||
|
for (std::size_t index = 0; index < temporalHistoryTextures.size(); ++index)
|
||||||
|
{
|
||||||
|
plan.bindings.push_back({
|
||||||
|
"temporalHistory",
|
||||||
|
"gTemporalHistory" + std::to_string(index),
|
||||||
|
temporalHistoryTextures[index],
|
||||||
|
temporalBase + static_cast<GLuint>(index)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const GLuint feedbackTextureUnit = ResolveFeedbackTextureUnit(state, static_cast<unsigned>(sourceHistoryTextures.size()));
|
||||||
|
if (state.feedback.enabled)
|
||||||
|
{
|
||||||
|
plan.bindings.push_back({
|
||||||
|
"feedbackState",
|
||||||
|
"gFeedbackState",
|
||||||
|
feedbackTexture,
|
||||||
|
feedbackTextureUnit
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const GLuint shaderTextureBase = passProgram.shaderTextureBase != 0
|
||||||
|
? passProgram.shaderTextureBase
|
||||||
|
: feedbackTextureUnit + (state.feedback.enabled ? 1u : 0u);
|
||||||
|
for (std::size_t index = 0; index < passProgram.textureBindings.size(); ++index)
|
||||||
|
{
|
||||||
|
const LayerProgram::TextureBinding& textureBinding = passProgram.textureBindings[index];
|
||||||
|
plan.bindings.push_back({
|
||||||
|
"shaderTexture",
|
||||||
|
textureBinding.samplerName,
|
||||||
|
textureBinding.texture,
|
||||||
|
shaderTextureBase + static_cast<GLuint>(index)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const GLuint textTextureBase = shaderTextureBase + static_cast<GLuint>(passProgram.textureBindings.size());
|
||||||
|
for (std::size_t index = 0; index < passProgram.textBindings.size(); ++index)
|
||||||
|
{
|
||||||
|
const LayerProgram::TextBinding& textBinding = passProgram.textBindings[index];
|
||||||
|
plan.bindings.push_back({
|
||||||
|
"textTexture",
|
||||||
|
textBinding.samplerName,
|
||||||
|
textBinding.texture,
|
||||||
|
textTextureBase + static_cast<GLuint>(index)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return plan;
|
||||||
|
}
|
||||||
|
|
||||||
|
void ShaderTextureBindings::BindRuntimeTexturePlan(const RuntimeTextureBindingPlan& plan) const
|
||||||
|
{
|
||||||
|
for (const RuntimeTextureBinding& binding : plan.bindings)
|
||||||
|
{
|
||||||
|
glActiveTexture(GL_TEXTURE0 + binding.textureUnit);
|
||||||
|
glBindTexture(GL_TEXTURE_2D, binding.texture);
|
||||||
|
}
|
||||||
|
glActiveTexture(GL_TEXTURE0);
|
||||||
|
}
|
||||||
|
|
||||||
|
void ShaderTextureBindings::UnbindRuntimeTexturePlan(const RuntimeTextureBindingPlan& plan) const
|
||||||
|
{
|
||||||
|
for (const RuntimeTextureBinding& binding : plan.bindings)
|
||||||
|
{
|
||||||
|
glActiveTexture(GL_TEXTURE0 + binding.textureUnit);
|
||||||
|
glBindTexture(GL_TEXTURE_2D, 0);
|
||||||
|
}
|
||||||
|
glActiveTexture(GL_TEXTURE0);
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "OpenGLRenderer.h"
|
||||||
|
#include "ShaderTypes.h"
|
||||||
|
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
class ShaderTextureBindings
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
using LayerProgram = OpenGLRenderer::LayerProgram;
|
||||||
|
using PassProgram = OpenGLRenderer::LayerProgram::PassProgram;
|
||||||
|
|
||||||
|
struct RuntimeTextureBinding
|
||||||
|
{
|
||||||
|
std::string semanticName;
|
||||||
|
std::string samplerName;
|
||||||
|
GLuint texture = 0;
|
||||||
|
GLuint textureUnit = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct RuntimeTextureBindingPlan
|
||||||
|
{
|
||||||
|
std::vector<RuntimeTextureBinding> bindings;
|
||||||
|
};
|
||||||
|
|
||||||
|
bool LoadTextureAsset(const ShaderTextureAsset& textureAsset, GLuint& textureId, std::string& error);
|
||||||
|
void CreateTextBindings(const RuntimeRenderState& state, std::vector<LayerProgram::TextBinding>& textBindings);
|
||||||
|
bool UpdateTextBindingTexture(const RuntimeRenderState& state, LayerProgram::TextBinding& textBinding, std::string& error);
|
||||||
|
GLint FindSamplerUniformLocation(GLuint program, const std::string& samplerName) const;
|
||||||
|
GLuint ResolveFeedbackTextureUnit(const RuntimeRenderState& state, unsigned historyCap) const;
|
||||||
|
GLuint ResolveShaderTextureBase(const RuntimeRenderState& state, unsigned historyCap) const;
|
||||||
|
void AssignLayerSamplerUniforms(GLuint program, const RuntimeRenderState& state, const PassProgram& passProgram, unsigned historyCap) const;
|
||||||
|
RuntimeTextureBindingPlan BuildLayerRuntimeBindingPlan(
|
||||||
|
const PassProgram& passProgram,
|
||||||
|
GLuint layerInputTexture,
|
||||||
|
GLuint originalLayerInputTexture,
|
||||||
|
const RuntimeRenderState& state,
|
||||||
|
GLuint feedbackTexture,
|
||||||
|
const std::vector<GLuint>& sourceHistoryTextures,
|
||||||
|
const std::vector<GLuint>& temporalHistoryTextures) const;
|
||||||
|
void BindRuntimeTexturePlan(const RuntimeTextureBindingPlan& plan) const;
|
||||||
|
void UnbindRuntimeTexturePlan(const RuntimeTextureBindingPlan& plan) const;
|
||||||
|
};
|
||||||
@@ -0,0 +1,160 @@
|
|||||||
|
#include "RenderCommandQueue.h"
|
||||||
|
|
||||||
|
void RenderCommandQueue::RequestPreviewPresent(const RenderPreviewPresentRequest& request)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
|
if (mHasPreviewPresentRequest)
|
||||||
|
++mCoalescedCount;
|
||||||
|
else
|
||||||
|
++mEnqueuedCount;
|
||||||
|
|
||||||
|
mPreviewPresentRequest = request;
|
||||||
|
mHasPreviewPresentRequest = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool RenderCommandQueue::TryTakePreviewPresent(RenderPreviewPresentRequest& request)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
|
if (!mHasPreviewPresentRequest)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
request = mPreviewPresentRequest;
|
||||||
|
mPreviewPresentRequest = {};
|
||||||
|
mHasPreviewPresentRequest = false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void RenderCommandQueue::RequestScreenshotCapture(const RenderScreenshotCaptureRequest& request)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
|
if (mHasScreenshotCaptureRequest)
|
||||||
|
++mCoalescedCount;
|
||||||
|
else
|
||||||
|
++mEnqueuedCount;
|
||||||
|
|
||||||
|
mScreenshotCaptureRequest = request;
|
||||||
|
mHasScreenshotCaptureRequest = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool RenderCommandQueue::TryTakeScreenshotCapture(RenderScreenshotCaptureRequest& request)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
|
if (!mHasScreenshotCaptureRequest)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
request = mScreenshotCaptureRequest;
|
||||||
|
mScreenshotCaptureRequest = {};
|
||||||
|
mHasScreenshotCaptureRequest = false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void RenderCommandQueue::RequestInputUpload(const RenderInputUploadRequest& request)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
|
if (mHasInputUploadRequest)
|
||||||
|
++mCoalescedCount;
|
||||||
|
else
|
||||||
|
++mEnqueuedCount;
|
||||||
|
|
||||||
|
mInputUploadRequest = request;
|
||||||
|
mHasInputUploadRequest = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool RenderCommandQueue::TryTakeInputUpload(RenderInputUploadRequest& request)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
|
if (!mHasInputUploadRequest)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
request = mInputUploadRequest;
|
||||||
|
mInputUploadRequest = {};
|
||||||
|
mHasInputUploadRequest = false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void RenderCommandQueue::RequestOutputFrame(const RenderOutputFrameRequest& request)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
|
mOutputFrameRequests.push_back(request);
|
||||||
|
++mEnqueuedCount;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool RenderCommandQueue::TryTakeOutputFrame(RenderOutputFrameRequest& request)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
|
if (mOutputFrameRequests.empty())
|
||||||
|
return false;
|
||||||
|
|
||||||
|
request = mOutputFrameRequests.front();
|
||||||
|
mOutputFrameRequests.pop_front();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void RenderCommandQueue::RequestRenderReset(RenderCommandResetScope scope)
|
||||||
|
{
|
||||||
|
if (scope == RenderCommandResetScope::None)
|
||||||
|
return;
|
||||||
|
|
||||||
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
|
if (mRenderResetScope != RenderCommandResetScope::None)
|
||||||
|
++mCoalescedCount;
|
||||||
|
else
|
||||||
|
++mEnqueuedCount;
|
||||||
|
|
||||||
|
mRenderResetScope = MergeResetScopes(mRenderResetScope, scope);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool RenderCommandQueue::TryTakeRenderReset(RenderCommandResetScope& scope)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
|
if (mRenderResetScope == RenderCommandResetScope::None)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
scope = mRenderResetScope;
|
||||||
|
mRenderResetScope = RenderCommandResetScope::None;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
RenderCommandQueueMetrics RenderCommandQueue::GetMetrics() const
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
|
RenderCommandQueueMetrics metrics;
|
||||||
|
metrics.depth =
|
||||||
|
(mHasPreviewPresentRequest ? 1u : 0u) +
|
||||||
|
(mHasScreenshotCaptureRequest ? 1u : 0u) +
|
||||||
|
(mHasInputUploadRequest ? 1u : 0u) +
|
||||||
|
mOutputFrameRequests.size() +
|
||||||
|
(mRenderResetScope != RenderCommandResetScope::None ? 1u : 0u);
|
||||||
|
metrics.enqueuedCount = mEnqueuedCount;
|
||||||
|
metrics.coalescedCount = mCoalescedCount;
|
||||||
|
return metrics;
|
||||||
|
}
|
||||||
|
|
||||||
|
RenderCommandResetScope RenderCommandQueue::MergeResetScopes(RenderCommandResetScope current, RenderCommandResetScope requested)
|
||||||
|
{
|
||||||
|
if (current == RenderCommandResetScope::TemporalHistoryAndFeedback ||
|
||||||
|
requested == RenderCommandResetScope::TemporalHistoryAndFeedback)
|
||||||
|
{
|
||||||
|
return RenderCommandResetScope::TemporalHistoryAndFeedback;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ((current == RenderCommandResetScope::TemporalHistoryOnly && requested == RenderCommandResetScope::ShaderFeedbackOnly) ||
|
||||||
|
(current == RenderCommandResetScope::ShaderFeedbackOnly && requested == RenderCommandResetScope::TemporalHistoryOnly))
|
||||||
|
{
|
||||||
|
return RenderCommandResetScope::TemporalHistoryAndFeedback;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (current == RenderCommandResetScope::TemporalHistoryOnly ||
|
||||||
|
requested == RenderCommandResetScope::TemporalHistoryOnly)
|
||||||
|
{
|
||||||
|
return RenderCommandResetScope::TemporalHistoryOnly;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (current == RenderCommandResetScope::ShaderFeedbackOnly ||
|
||||||
|
requested == RenderCommandResetScope::ShaderFeedbackOnly)
|
||||||
|
{
|
||||||
|
return RenderCommandResetScope::ShaderFeedbackOnly;
|
||||||
|
}
|
||||||
|
|
||||||
|
return RenderCommandResetScope::None;
|
||||||
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "VideoIOTypes.h"
|
||||||
|
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <deque>
|
||||||
|
#include <mutex>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
enum class RenderCommandResetScope
|
||||||
|
{
|
||||||
|
None,
|
||||||
|
ShaderFeedbackOnly,
|
||||||
|
TemporalHistoryOnly,
|
||||||
|
TemporalHistoryAndFeedback
|
||||||
|
};
|
||||||
|
|
||||||
|
struct RenderPreviewPresentRequest
|
||||||
|
{
|
||||||
|
unsigned outputFrameWidth = 0;
|
||||||
|
unsigned outputFrameHeight = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct RenderScreenshotCaptureRequest
|
||||||
|
{
|
||||||
|
unsigned width = 0;
|
||||||
|
unsigned height = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct RenderInputUploadRequest
|
||||||
|
{
|
||||||
|
VideoIOFrame inputFrame;
|
||||||
|
VideoIOState videoState;
|
||||||
|
std::vector<unsigned char> ownedBytes;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct RenderOutputFrameRequest
|
||||||
|
{
|
||||||
|
VideoIOState videoState;
|
||||||
|
VideoIOCompletion completion;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct RenderCommandQueueMetrics
|
||||||
|
{
|
||||||
|
std::size_t depth = 0;
|
||||||
|
uint64_t enqueuedCount = 0;
|
||||||
|
uint64_t coalescedCount = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
class RenderCommandQueue
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
void RequestPreviewPresent(const RenderPreviewPresentRequest& request);
|
||||||
|
bool TryTakePreviewPresent(RenderPreviewPresentRequest& request);
|
||||||
|
|
||||||
|
void RequestScreenshotCapture(const RenderScreenshotCaptureRequest& request);
|
||||||
|
bool TryTakeScreenshotCapture(RenderScreenshotCaptureRequest& request);
|
||||||
|
|
||||||
|
void RequestInputUpload(const RenderInputUploadRequest& request);
|
||||||
|
bool TryTakeInputUpload(RenderInputUploadRequest& request);
|
||||||
|
|
||||||
|
void RequestOutputFrame(const RenderOutputFrameRequest& request);
|
||||||
|
bool TryTakeOutputFrame(RenderOutputFrameRequest& request);
|
||||||
|
|
||||||
|
void RequestRenderReset(RenderCommandResetScope scope);
|
||||||
|
bool TryTakeRenderReset(RenderCommandResetScope& scope);
|
||||||
|
|
||||||
|
RenderCommandQueueMetrics GetMetrics() const;
|
||||||
|
|
||||||
|
private:
|
||||||
|
static RenderCommandResetScope MergeResetScopes(RenderCommandResetScope current, RenderCommandResetScope requested);
|
||||||
|
|
||||||
|
mutable std::mutex mMutex;
|
||||||
|
bool mHasPreviewPresentRequest = false;
|
||||||
|
RenderPreviewPresentRequest mPreviewPresentRequest;
|
||||||
|
bool mHasScreenshotCaptureRequest = false;
|
||||||
|
RenderScreenshotCaptureRequest mScreenshotCaptureRequest;
|
||||||
|
bool mHasInputUploadRequest = false;
|
||||||
|
RenderInputUploadRequest mInputUploadRequest;
|
||||||
|
std::deque<RenderOutputFrameRequest> mOutputFrameRequests;
|
||||||
|
RenderCommandResetScope mRenderResetScope = RenderCommandResetScope::None;
|
||||||
|
uint64_t mEnqueuedCount = 0;
|
||||||
|
uint64_t mCoalescedCount = 0;
|
||||||
|
};
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -1,181 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
|
|
||||||
#include "RuntimeJson.h"
|
|
||||||
#include "ShaderTypes.h"
|
|
||||||
|
|
||||||
#include <atomic>
|
|
||||||
#include <chrono>
|
|
||||||
#include <filesystem>
|
|
||||||
#include <map>
|
|
||||||
#include <mutex>
|
|
||||||
#include <string>
|
|
||||||
#include <vector>
|
|
||||||
|
|
||||||
class RuntimeHost
|
|
||||||
{
|
|
||||||
public:
|
|
||||||
RuntimeHost();
|
|
||||||
|
|
||||||
bool Initialize(std::string& error);
|
|
||||||
|
|
||||||
bool PollFileChanges(bool& registryChanged, bool& reloadRequested, std::string& error);
|
|
||||||
bool ManualReloadRequested();
|
|
||||||
void ClearReloadRequest();
|
|
||||||
|
|
||||||
bool AddLayer(const std::string& shaderId, std::string& error);
|
|
||||||
bool RemoveLayer(const std::string& layerId, std::string& error);
|
|
||||||
bool MoveLayer(const std::string& layerId, int direction, std::string& error);
|
|
||||||
bool MoveLayerToIndex(const std::string& layerId, std::size_t targetIndex, std::string& error);
|
|
||||||
bool SetLayerBypass(const std::string& layerId, bool bypassed, std::string& error);
|
|
||||||
bool SetLayerShader(const std::string& layerId, const std::string& shaderId, std::string& error);
|
|
||||||
bool UpdateLayerParameter(const std::string& layerId, const std::string& parameterId, const JsonValue& newValue, std::string& error);
|
|
||||||
bool UpdateLayerParameterByControlKey(const std::string& layerKey, const std::string& parameterKey, const JsonValue& newValue, std::string& error);
|
|
||||||
bool ResetLayerParameters(const std::string& layerId, std::string& error);
|
|
||||||
bool SaveStackPreset(const std::string& presetName, std::string& error) const;
|
|
||||||
bool LoadStackPreset(const std::string& presetName, std::string& error);
|
|
||||||
|
|
||||||
void SetCompileStatus(bool succeeded, const std::string& message);
|
|
||||||
void SetSignalStatus(bool hasSignal, unsigned width, unsigned height, const std::string& modeName);
|
|
||||||
bool TrySetSignalStatus(bool hasSignal, unsigned width, unsigned height, const std::string& modeName);
|
|
||||||
void SetDeckLinkOutputStatus(const std::string& modelName, bool supportsInternalKeying, bool supportsExternalKeying,
|
|
||||||
bool keyerInterfaceAvailable, bool externalKeyingRequested, bool externalKeyingActive, const std::string& statusMessage);
|
|
||||||
void SetPerformanceStats(double frameBudgetMilliseconds, double renderMilliseconds);
|
|
||||||
bool TrySetPerformanceStats(double frameBudgetMilliseconds, double renderMilliseconds);
|
|
||||||
void SetFramePacingStats(double completionIntervalMilliseconds, double smoothedCompletionIntervalMilliseconds,
|
|
||||||
double maxCompletionIntervalMilliseconds, uint64_t lateFrameCount, uint64_t droppedFrameCount, uint64_t flushedFrameCount);
|
|
||||||
bool TrySetFramePacingStats(double completionIntervalMilliseconds, double smoothedCompletionIntervalMilliseconds,
|
|
||||||
double maxCompletionIntervalMilliseconds, uint64_t lateFrameCount, uint64_t droppedFrameCount, uint64_t flushedFrameCount);
|
|
||||||
void AdvanceFrame();
|
|
||||||
bool TryAdvanceFrame();
|
|
||||||
|
|
||||||
bool BuildLayerFragmentShaderSource(const std::string& layerId, std::string& fragmentShaderSource, std::string& error);
|
|
||||||
std::vector<RuntimeRenderState> GetLayerRenderStates(unsigned outputWidth, unsigned outputHeight) const;
|
|
||||||
bool TryGetLayerRenderStates(unsigned outputWidth, unsigned outputHeight, std::vector<RuntimeRenderState>& states) const;
|
|
||||||
void RefreshDynamicRenderStateFields(std::vector<RuntimeRenderState>& states) const;
|
|
||||||
std::string BuildStateJson() const;
|
|
||||||
|
|
||||||
const std::filesystem::path& GetRepoRoot() const { return mRepoRoot; }
|
|
||||||
const std::filesystem::path& GetUiRoot() const { return mUiRoot; }
|
|
||||||
const std::filesystem::path& GetDocsRoot() const { return mDocsRoot; }
|
|
||||||
const std::filesystem::path& GetRuntimeRoot() const { return mRuntimeRoot; }
|
|
||||||
unsigned short GetServerPort() const { return mServerPort; }
|
|
||||||
unsigned short GetOscPort() const { return mConfig.oscPort; }
|
|
||||||
unsigned GetMaxTemporalHistoryFrames() const { return mConfig.maxTemporalHistoryFrames; }
|
|
||||||
bool ExternalKeyingEnabled() const { return mConfig.enableExternalKeying; }
|
|
||||||
const std::string& GetInputVideoFormat() const { return mConfig.inputVideoFormat; }
|
|
||||||
const std::string& GetInputFrameRate() const { return mConfig.inputFrameRate; }
|
|
||||||
const std::string& GetOutputVideoFormat() const { return mConfig.outputVideoFormat; }
|
|
||||||
const std::string& GetOutputFrameRate() const { return mConfig.outputFrameRate; }
|
|
||||||
void SetServerPort(unsigned short port);
|
|
||||||
bool AutoReloadEnabled() const { return mAutoReloadEnabled; }
|
|
||||||
|
|
||||||
private:
|
|
||||||
struct AppConfig
|
|
||||||
{
|
|
||||||
std::string shaderLibrary = "shaders";
|
|
||||||
unsigned short serverPort = 8080;
|
|
||||||
unsigned short oscPort = 9000;
|
|
||||||
bool autoReload = true;
|
|
||||||
unsigned maxTemporalHistoryFrames = 4;
|
|
||||||
bool enableExternalKeying = false;
|
|
||||||
std::string inputVideoFormat = "1080p";
|
|
||||||
std::string inputFrameRate = "59.94";
|
|
||||||
std::string outputVideoFormat = "1080p";
|
|
||||||
std::string outputFrameRate = "59.94";
|
|
||||||
};
|
|
||||||
|
|
||||||
struct DeckLinkOutputStatus
|
|
||||||
{
|
|
||||||
std::string modelName;
|
|
||||||
bool supportsInternalKeying = false;
|
|
||||||
bool supportsExternalKeying = false;
|
|
||||||
bool keyerInterfaceAvailable = false;
|
|
||||||
bool externalKeyingRequested = false;
|
|
||||||
bool externalKeyingActive = false;
|
|
||||||
std::string statusMessage;
|
|
||||||
};
|
|
||||||
|
|
||||||
struct LayerPersistentState
|
|
||||||
{
|
|
||||||
std::string id;
|
|
||||||
std::string shaderId;
|
|
||||||
bool bypass = false;
|
|
||||||
std::map<std::string, ShaderParameterValue> parameterValues;
|
|
||||||
};
|
|
||||||
|
|
||||||
struct PersistentState
|
|
||||||
{
|
|
||||||
std::vector<LayerPersistentState> layers;
|
|
||||||
};
|
|
||||||
|
|
||||||
bool LoadConfig(std::string& error);
|
|
||||||
bool LoadPersistentState(std::string& error);
|
|
||||||
bool SavePersistentState(std::string& error) const;
|
|
||||||
bool ScanShaderPackages(std::string& error);
|
|
||||||
bool ParseShaderManifest(const std::filesystem::path& manifestPath, ShaderPackage& shaderPackage, std::string& error) const;
|
|
||||||
bool NormalizeAndValidateValue(const ShaderParameterDefinition& definition, const JsonValue& value, ShaderParameterValue& normalizedValue, std::string& error) const;
|
|
||||||
ShaderParameterValue DefaultValueForDefinition(const ShaderParameterDefinition& definition) const;
|
|
||||||
void EnsureLayerDefaultsLocked(LayerPersistentState& layerState, const ShaderPackage& shaderPackage) const;
|
|
||||||
std::string ReadTextFile(const std::filesystem::path& path, std::string& error) const;
|
|
||||||
bool WriteTextFile(const std::filesystem::path& path, const std::string& contents, std::string& error) const;
|
|
||||||
bool ResolvePaths(std::string& error);
|
|
||||||
void BuildLayerRenderStatesLocked(unsigned outputWidth, unsigned outputHeight, std::vector<RuntimeRenderState>& states) const;
|
|
||||||
JsonValue BuildStateValue() const;
|
|
||||||
JsonValue SerializeLayerStackLocked() const;
|
|
||||||
bool DeserializeLayerStackLocked(const JsonValue& layersValue, std::vector<LayerPersistentState>& layers, std::string& error);
|
|
||||||
void NormalizePersistentLayerIdsLocked();
|
|
||||||
std::vector<std::string> GetStackPresetNamesLocked() const;
|
|
||||||
std::string MakeSafePresetFileStem(const std::string& presetName) const;
|
|
||||||
JsonValue SerializeParameterValue(const ShaderParameterDefinition& definition, const ShaderParameterValue& value) const;
|
|
||||||
std::string TemporalHistorySourceToString(TemporalHistorySource source) const;
|
|
||||||
LayerPersistentState* FindLayerById(const std::string& layerId);
|
|
||||||
const LayerPersistentState* FindLayerById(const std::string& layerId) const;
|
|
||||||
std::string GenerateLayerId();
|
|
||||||
void SetSignalStatusLocked(bool hasSignal, unsigned width, unsigned height, const std::string& modeName);
|
|
||||||
void SetPerformanceStatsLocked(double frameBudgetMilliseconds, double renderMilliseconds);
|
|
||||||
void SetFramePacingStatsLocked(double completionIntervalMilliseconds, double smoothedCompletionIntervalMilliseconds,
|
|
||||||
double maxCompletionIntervalMilliseconds, uint64_t lateFrameCount, uint64_t droppedFrameCount, uint64_t flushedFrameCount);
|
|
||||||
|
|
||||||
private:
|
|
||||||
mutable std::mutex mMutex;
|
|
||||||
AppConfig mConfig;
|
|
||||||
PersistentState mPersistentState;
|
|
||||||
std::filesystem::path mRepoRoot;
|
|
||||||
std::filesystem::path mUiRoot;
|
|
||||||
std::filesystem::path mDocsRoot;
|
|
||||||
std::filesystem::path mShaderRoot;
|
|
||||||
std::filesystem::path mRuntimeRoot;
|
|
||||||
std::filesystem::path mPresetRoot;
|
|
||||||
std::filesystem::path mRuntimeStatePath;
|
|
||||||
std::filesystem::path mConfigPath;
|
|
||||||
std::filesystem::path mWrapperPath;
|
|
||||||
std::filesystem::path mGeneratedGlslPath;
|
|
||||||
std::filesystem::path mPatchedGlslPath;
|
|
||||||
std::map<std::string, ShaderPackage> mPackagesById;
|
|
||||||
std::vector<std::string> mPackageOrder;
|
|
||||||
std::vector<ShaderPackageStatus> mPackageStatuses;
|
|
||||||
bool mReloadRequested;
|
|
||||||
bool mCompileSucceeded;
|
|
||||||
std::string mCompileMessage;
|
|
||||||
bool mHasSignal;
|
|
||||||
unsigned mSignalWidth;
|
|
||||||
unsigned mSignalHeight;
|
|
||||||
std::string mSignalModeName;
|
|
||||||
double mFrameBudgetMilliseconds;
|
|
||||||
double mRenderMilliseconds;
|
|
||||||
double mSmoothedRenderMilliseconds;
|
|
||||||
double mCompletionIntervalMilliseconds;
|
|
||||||
double mSmoothedCompletionIntervalMilliseconds;
|
|
||||||
double mMaxCompletionIntervalMilliseconds;
|
|
||||||
double mStartupRandom;
|
|
||||||
uint64_t mLateFrameCount;
|
|
||||||
uint64_t mDroppedFrameCount;
|
|
||||||
uint64_t mFlushedFrameCount;
|
|
||||||
DeckLinkOutputStatus mDeckLinkOutputStatus;
|
|
||||||
unsigned short mServerPort;
|
|
||||||
bool mAutoReloadEnabled;
|
|
||||||
std::chrono::steady_clock::time_point mStartTime;
|
|
||||||
std::chrono::steady_clock::time_point mLastScanTime;
|
|
||||||
std::atomic<uint64_t> mFrameCounter;
|
|
||||||
uint64_t mNextLayerId;
|
|
||||||
};
|
|
||||||
@@ -0,0 +1,613 @@
|
|||||||
|
#include "RuntimeCoordinator.h"
|
||||||
|
|
||||||
|
#include "RuntimeEventDispatcher.h"
|
||||||
|
#include "RuntimeEventPayloads.h"
|
||||||
|
#include "RuntimeParameterUtils.h"
|
||||||
|
#include "RuntimeStore.h"
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
RuntimeEventRenderResetScope ToRuntimeEventRenderResetScope(RuntimeCoordinatorRenderResetScope scope)
|
||||||
|
{
|
||||||
|
switch (scope)
|
||||||
|
{
|
||||||
|
case RuntimeCoordinatorRenderResetScope::TemporalHistoryOnly:
|
||||||
|
return RuntimeEventRenderResetScope::TemporalHistoryOnly;
|
||||||
|
case RuntimeCoordinatorRenderResetScope::TemporalHistoryAndFeedback:
|
||||||
|
return RuntimeEventRenderResetScope::TemporalHistoryAndFeedback;
|
||||||
|
case RuntimeCoordinatorRenderResetScope::None:
|
||||||
|
default:
|
||||||
|
return RuntimeEventRenderResetScope::None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
RuntimeCoordinator::RuntimeCoordinator(RuntimeStore& runtimeStore, RuntimeEventDispatcher& runtimeEventDispatcher) :
|
||||||
|
mRuntimeStore(runtimeStore),
|
||||||
|
mRuntimeEventDispatcher(runtimeEventDispatcher)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
RuntimeCoordinatorResult RuntimeCoordinator::AddLayer(const std::string& shaderId)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
|
std::string error;
|
||||||
|
if (!ValidateShaderExists(shaderId, error))
|
||||||
|
{
|
||||||
|
RuntimeCoordinatorResult result = ApplyStoreMutation(false, error, false, false, false);
|
||||||
|
PublishCoordinatorResult("AddLayer", result);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
RuntimeCoordinatorResult result = ApplyStoreMutation(mRuntimeStore.CreateStoredLayer(shaderId, error), error, true, true, true);
|
||||||
|
PublishCoordinatorResult("AddLayer", result);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
RuntimeCoordinatorResult RuntimeCoordinator::RemoveLayer(const std::string& layerId)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
|
std::string error;
|
||||||
|
if (!ValidateLayerExists(layerId, error))
|
||||||
|
{
|
||||||
|
RuntimeCoordinatorResult result = ApplyStoreMutation(false, error, false, false, false);
|
||||||
|
PublishCoordinatorResult("RemoveLayer", result);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
RuntimeCoordinatorResult result = ApplyStoreMutation(mRuntimeStore.DeleteStoredLayer(layerId, error), error, true, true, true);
|
||||||
|
if (result.accepted)
|
||||||
|
{
|
||||||
|
result.transientOscInvalidation = RuntimeCoordinatorTransientOscInvalidation::Layer;
|
||||||
|
result.transientOscLayerKey = layerId;
|
||||||
|
}
|
||||||
|
PublishCoordinatorResult("RemoveLayer", result);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
RuntimeCoordinatorResult RuntimeCoordinator::MoveLayer(const std::string& layerId, int direction)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
|
std::string error;
|
||||||
|
bool shouldMove = false;
|
||||||
|
if (!ResolveLayerMove(layerId, direction, shouldMove, error))
|
||||||
|
{
|
||||||
|
RuntimeCoordinatorResult result = ApplyStoreMutation(false, error, false, false, false);
|
||||||
|
PublishCoordinatorResult("MoveLayer", result);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
if (!shouldMove)
|
||||||
|
{
|
||||||
|
RuntimeCoordinatorResult result = BuildAcceptedNoReloadResult();
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
RuntimeCoordinatorResult result = ApplyStoreMutation(mRuntimeStore.MoveStoredLayer(layerId, direction, error), error, true, true, true);
|
||||||
|
PublishCoordinatorResult("MoveLayer", result);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
RuntimeCoordinatorResult RuntimeCoordinator::MoveLayerToIndex(const std::string& layerId, std::size_t targetIndex)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
|
std::string error;
|
||||||
|
bool shouldMove = false;
|
||||||
|
if (!ResolveLayerMoveToIndex(layerId, targetIndex, shouldMove, error))
|
||||||
|
{
|
||||||
|
RuntimeCoordinatorResult result = ApplyStoreMutation(false, error, false, false, false);
|
||||||
|
PublishCoordinatorResult("MoveLayerToIndex", result);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
if (!shouldMove)
|
||||||
|
{
|
||||||
|
RuntimeCoordinatorResult result = BuildAcceptedNoReloadResult();
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
RuntimeCoordinatorResult result = ApplyStoreMutation(mRuntimeStore.MoveStoredLayerToIndex(layerId, targetIndex, error), error, true, true, true);
|
||||||
|
PublishCoordinatorResult("MoveLayerToIndex", result);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
RuntimeCoordinatorResult RuntimeCoordinator::SetLayerBypass(const std::string& layerId, bool bypassed)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
|
std::string error;
|
||||||
|
if (!ValidateLayerExists(layerId, error))
|
||||||
|
{
|
||||||
|
RuntimeCoordinatorResult result = ApplyStoreMutation(false, error, false, false, false);
|
||||||
|
PublishCoordinatorResult("SetLayerBypass", result);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
RuntimeCoordinatorResult result = ApplyStoreMutation(mRuntimeStore.SetStoredLayerBypassState(layerId, bypassed, error), error, true, false, true);
|
||||||
|
PublishCoordinatorResult("SetLayerBypass", result);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
RuntimeCoordinatorResult RuntimeCoordinator::SetLayerShader(const std::string& layerId, const std::string& shaderId)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
|
std::string error;
|
||||||
|
if (!ValidateLayerExists(layerId, error) || !ValidateShaderExists(shaderId, error))
|
||||||
|
{
|
||||||
|
RuntimeCoordinatorResult result = ApplyStoreMutation(false, error, false, false, false);
|
||||||
|
PublishCoordinatorResult("SetLayerShader", result);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
RuntimeCoordinatorResult result = ApplyStoreMutation(mRuntimeStore.SetStoredLayerShaderSelection(layerId, shaderId, error), error, true, false, true);
|
||||||
|
PublishCoordinatorResult("SetLayerShader", result);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
RuntimeCoordinatorResult RuntimeCoordinator::UpdateLayerParameter(const std::string& layerId, const std::string& parameterId, const JsonValue& newValue)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
|
std::string error;
|
||||||
|
ResolvedParameterMutation mutation;
|
||||||
|
if (!BuildParameterMutationById(layerId, parameterId, newValue, true, mutation, error))
|
||||||
|
{
|
||||||
|
RuntimeCoordinatorResult result = ApplyStoreMutation(false, error, false, false, false);
|
||||||
|
PublishCoordinatorResult("UpdateLayerParameter", result);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
RuntimeCoordinatorResult result = ApplyStoreMutation(mRuntimeStore.SetStoredParameterValue(mutation.layerId, mutation.parameterId, mutation.value, mutation.persistState, error), error, false, false, mutation.persistState);
|
||||||
|
PublishCoordinatorResult("UpdateLayerParameter", result);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
RuntimeCoordinatorResult RuntimeCoordinator::UpdateLayerParameterByControlKey(const std::string& layerKey, const std::string& parameterKey, const JsonValue& newValue)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
|
std::string error;
|
||||||
|
ResolvedParameterMutation mutation;
|
||||||
|
if (!BuildParameterMutationByControlKey(layerKey, parameterKey, newValue, true, mutation, error))
|
||||||
|
{
|
||||||
|
RuntimeCoordinatorResult result = ApplyStoreMutation(false, error, false, false, false);
|
||||||
|
PublishCoordinatorResult("UpdateLayerParameterByControlKey", result);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
RuntimeCoordinatorResult result = ApplyStoreMutation(mRuntimeStore.SetStoredParameterValue(mutation.layerId, mutation.parameterId, mutation.value, mutation.persistState, error), error, false, false, mutation.persistState);
|
||||||
|
PublishCoordinatorResult("UpdateLayerParameterByControlKey", result);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
RuntimeCoordinatorResult RuntimeCoordinator::CommitOscParameterByControlKey(const std::string& layerKey, const std::string& parameterKey, const JsonValue& newValue)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
|
constexpr RuntimeCoordinatorOscCommitPersistence kDefaultOscCommitPersistence =
|
||||||
|
RuntimeCoordinatorOscCommitPersistence::SessionOnly;
|
||||||
|
constexpr bool kPersistSettledOscCommits =
|
||||||
|
kDefaultOscCommitPersistence == RuntimeCoordinatorOscCommitPersistence::Persistent;
|
||||||
|
|
||||||
|
std::string error;
|
||||||
|
ResolvedParameterMutation mutation;
|
||||||
|
if (!BuildParameterMutationByControlKey(layerKey, parameterKey, newValue, kPersistSettledOscCommits, mutation, error))
|
||||||
|
{
|
||||||
|
RuntimeCoordinatorResult result = ApplyStoreMutation(false, error, false, false, false);
|
||||||
|
PublishCoordinatorResult("CommitOscParameterByControlKey", result);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
RuntimeCoordinatorResult result = ApplyStoreMutation(mRuntimeStore.SetStoredParameterValue(mutation.layerId, mutation.parameterId, mutation.value, mutation.persistState, error), error, false, false, mutation.persistState);
|
||||||
|
PublishCoordinatorResult("CommitOscParameterByControlKey", result);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
RuntimeCoordinatorResult RuntimeCoordinator::ResetLayerParameters(const std::string& layerId)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
|
std::string error;
|
||||||
|
if (!ValidateLayerExists(layerId, error))
|
||||||
|
{
|
||||||
|
RuntimeCoordinatorResult result = ApplyStoreMutation(false, error, false, false, false);
|
||||||
|
PublishCoordinatorResult("ResetLayerParameters", result);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
RuntimeCoordinatorResult result = ApplyStoreMutation(mRuntimeStore.ResetStoredLayerParameterValues(layerId, error), error, false, false, true);
|
||||||
|
if (!result.accepted)
|
||||||
|
{
|
||||||
|
PublishCoordinatorResult("ResetLayerParameters", result);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
result.transientOscInvalidation = RuntimeCoordinatorTransientOscInvalidation::Layer;
|
||||||
|
result.transientOscLayerKey = layerId;
|
||||||
|
result.renderResetScope = RuntimeCoordinatorRenderResetScope::TemporalHistoryAndFeedback;
|
||||||
|
PublishCoordinatorResult("ResetLayerParameters", result);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
RuntimeCoordinatorResult RuntimeCoordinator::SaveStackPreset(const std::string& presetName)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
|
std::string error;
|
||||||
|
if (!ValidatePresetName(presetName, error))
|
||||||
|
{
|
||||||
|
RuntimeCoordinatorResult result = ApplyStoreMutation(false, error, false, false, false);
|
||||||
|
PublishCoordinatorResult("SaveStackPreset", result);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
RuntimeCoordinatorResult result = ApplyStoreMutation(mRuntimeStore.SaveStackPresetSnapshot(presetName, error), error, false, false, true);
|
||||||
|
PublishCoordinatorResult("SaveStackPreset", result);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
RuntimeCoordinatorResult RuntimeCoordinator::LoadStackPreset(const std::string& presetName)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
|
std::string error;
|
||||||
|
if (!ValidatePresetName(presetName, error))
|
||||||
|
{
|
||||||
|
RuntimeCoordinatorResult result = ApplyStoreMutation(false, error, false, false, false);
|
||||||
|
PublishCoordinatorResult("LoadStackPreset", result);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
RuntimeCoordinatorResult result = ApplyStoreMutation(mRuntimeStore.LoadStackPresetSnapshot(presetName, error), error, true, false, true);
|
||||||
|
PublishCoordinatorResult("LoadStackPreset", result);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
RuntimeCoordinatorResult RuntimeCoordinator::RequestShaderReload(bool preserveFeedbackState)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
|
PublishManualReloadRequested(preserveFeedbackState, "RequestShaderReload");
|
||||||
|
RuntimeCoordinatorResult result = BuildQueuedReloadResult(preserveFeedbackState);
|
||||||
|
PublishCoordinatorFollowUpEvents("RequestShaderReload", result);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
RuntimeCoordinatorResult RuntimeCoordinator::PollRuntimeStoreChanges(bool& registryChanged)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
|
|
||||||
|
registryChanged = false;
|
||||||
|
bool reloadRequested = false;
|
||||||
|
std::string error;
|
||||||
|
if (!mRuntimeStore.PollStoredFileChanges(registryChanged, reloadRequested, error))
|
||||||
|
{
|
||||||
|
RuntimeCoordinatorResult result = HandleRuntimePollFailure(error);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (reloadRequested)
|
||||||
|
{
|
||||||
|
PublishFileChangeDetected("PollRuntimeStoreChanges", registryChanged, reloadRequested);
|
||||||
|
RuntimeCoordinatorResult result = BuildQueuedReloadResult(false);
|
||||||
|
PublishCoordinatorFollowUpEvents("PollRuntimeStoreChanges", result);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (registryChanged)
|
||||||
|
{
|
||||||
|
PublishFileChangeDetected("PollRuntimeStoreChanges", registryChanged, reloadRequested);
|
||||||
|
RuntimeCoordinatorResult result = BuildAcceptedNoReloadResult();
|
||||||
|
PublishCoordinatorFollowUpEvents("PollRuntimeStoreChanges", result);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
RuntimeCoordinatorResult result;
|
||||||
|
result.accepted = true;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
RuntimeCoordinatorResult RuntimeCoordinator::HandleRuntimePollFailure(const std::string& error)
|
||||||
|
{
|
||||||
|
RuntimeCoordinatorResult result;
|
||||||
|
result.accepted = true;
|
||||||
|
result.runtimeStateBroadcastRequired = true;
|
||||||
|
result.compileStatusChanged = true;
|
||||||
|
result.compileStatusSucceeded = false;
|
||||||
|
result.compileStatusMessage = error;
|
||||||
|
PublishCoordinatorFollowUpEvents("HandleRuntimePollFailure", result);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
RuntimeCoordinatorResult RuntimeCoordinator::HandlePreparedShaderBuildFailure(const std::string& error)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
|
mPreserveFeedbackOnNextShaderBuild = false;
|
||||||
|
mUseCommittedLayerStates = true;
|
||||||
|
|
||||||
|
RuntimeCoordinatorResult result;
|
||||||
|
result.accepted = true;
|
||||||
|
result.runtimeStateBroadcastRequired = true;
|
||||||
|
result.compileStatusChanged = true;
|
||||||
|
result.compileStatusSucceeded = false;
|
||||||
|
result.compileStatusMessage = error;
|
||||||
|
result.committedStateMode = RuntimeCoordinatorCommittedStateMode::UseCommittedStates;
|
||||||
|
PublishCoordinatorFollowUpEvents("HandlePreparedShaderBuildFailure", result);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
RuntimeCoordinatorResult RuntimeCoordinator::HandlePreparedShaderBuildSuccess()
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
|
mUseCommittedLayerStates = false;
|
||||||
|
|
||||||
|
RuntimeCoordinatorResult result;
|
||||||
|
result.accepted = true;
|
||||||
|
result.runtimeStateBroadcastRequired = true;
|
||||||
|
result.compileStatusChanged = true;
|
||||||
|
result.compileStatusSucceeded = true;
|
||||||
|
result.compileStatusMessage = "Shader layers compiled successfully.";
|
||||||
|
result.committedStateMode = RuntimeCoordinatorCommittedStateMode::UseLiveSnapshots;
|
||||||
|
mPreserveFeedbackOnNextShaderBuild = false;
|
||||||
|
PublishCoordinatorFollowUpEvents("HandlePreparedShaderBuildSuccess", result);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
RuntimeCoordinatorResult RuntimeCoordinator::HandleRuntimeReloadRequest()
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
|
PublishManualReloadRequested(false, "HandleRuntimeReloadRequest");
|
||||||
|
RuntimeCoordinatorResult result = BuildQueuedReloadResult(false);
|
||||||
|
PublishCoordinatorFollowUpEvents("HandleRuntimeReloadRequest", result);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
void RuntimeCoordinator::ApplyCommittedStateMode(RuntimeCoordinatorCommittedStateMode mode)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
|
switch (mode)
|
||||||
|
{
|
||||||
|
case RuntimeCoordinatorCommittedStateMode::UseCommittedStates:
|
||||||
|
mUseCommittedLayerStates = true;
|
||||||
|
break;
|
||||||
|
case RuntimeCoordinatorCommittedStateMode::UseLiveSnapshots:
|
||||||
|
mUseCommittedLayerStates = false;
|
||||||
|
break;
|
||||||
|
case RuntimeCoordinatorCommittedStateMode::Unchanged:
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool RuntimeCoordinator::UseCommittedLayerStates() const
|
||||||
|
{
|
||||||
|
return mUseCommittedLayerStates.load();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool RuntimeCoordinator::PreserveFeedbackOnNextShaderBuild() const
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
|
return mPreserveFeedbackOnNextShaderBuild;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool RuntimeCoordinator::BuildParameterMutationById(const std::string& layerId, const std::string& parameterId, const JsonValue& newValue,
|
||||||
|
bool persistState, ResolvedParameterMutation& mutation, std::string& error) const
|
||||||
|
{
|
||||||
|
RuntimeStore::StoredParameterSnapshot snapshot;
|
||||||
|
if (!mRuntimeStore.TryGetStoredParameterById(layerId, parameterId, snapshot, error))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
return BuildParameterMutationFromSnapshot(snapshot.layerId, snapshot.definition, snapshot.currentValue, snapshot.hasCurrentValue,
|
||||||
|
newValue, persistState, mutation, error);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool RuntimeCoordinator::BuildParameterMutationByControlKey(const std::string& layerKey, const std::string& parameterKey, const JsonValue& newValue,
|
||||||
|
bool persistState, ResolvedParameterMutation& mutation, std::string& error) const
|
||||||
|
{
|
||||||
|
RuntimeStore::StoredParameterSnapshot snapshot;
|
||||||
|
if (!mRuntimeStore.TryGetStoredParameterByControlKey(layerKey, parameterKey, snapshot, error))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
return BuildParameterMutationFromSnapshot(snapshot.layerId, snapshot.definition, snapshot.currentValue, snapshot.hasCurrentValue,
|
||||||
|
newValue, persistState, mutation, error);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool RuntimeCoordinator::BuildParameterMutationFromSnapshot(const std::string& layerId, const ShaderParameterDefinition& definition,
|
||||||
|
const ShaderParameterValue& currentValue, bool hasCurrentValue, const JsonValue& newValue,
|
||||||
|
bool persistState, ResolvedParameterMutation& mutation, std::string& error) const
|
||||||
|
{
|
||||||
|
mutation.layerId = layerId;
|
||||||
|
mutation.parameterId = definition.id;
|
||||||
|
mutation.persistState = persistState;
|
||||||
|
|
||||||
|
if (definition.type == ShaderParameterType::Trigger)
|
||||||
|
{
|
||||||
|
const double previousCount = !hasCurrentValue || currentValue.numberValues.empty()
|
||||||
|
? 0.0
|
||||||
|
: currentValue.numberValues[0];
|
||||||
|
const double triggerTime = mRuntimeStore.GetRuntimeElapsedSeconds();
|
||||||
|
mutation.value.numberValues = { previousCount + 1.0, triggerTime };
|
||||||
|
mutation.persistState = false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return NormalizeAndValidateParameterValue(definition, newValue, mutation.value, error);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool RuntimeCoordinator::ValidateLayerExists(const std::string& layerId, std::string& error) const
|
||||||
|
{
|
||||||
|
if (mRuntimeStore.HasStoredLayer(layerId))
|
||||||
|
return true;
|
||||||
|
|
||||||
|
error = "Unknown layer id: " + layerId;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool RuntimeCoordinator::ValidateShaderExists(const std::string& shaderId, std::string& error) const
|
||||||
|
{
|
||||||
|
if (mRuntimeStore.HasStoredShader(shaderId))
|
||||||
|
return true;
|
||||||
|
|
||||||
|
error = "Unknown shader id: " + shaderId;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool RuntimeCoordinator::ResolveLayerMove(const std::string& layerId, int direction, bool& shouldMove, std::string& error) const
|
||||||
|
{
|
||||||
|
return mRuntimeStore.ResolveStoredLayerMove(layerId, direction, shouldMove, error);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool RuntimeCoordinator::ResolveLayerMoveToIndex(const std::string& layerId, std::size_t targetIndex, bool& shouldMove, std::string& error) const
|
||||||
|
{
|
||||||
|
return mRuntimeStore.ResolveStoredLayerMoveToIndex(layerId, targetIndex, shouldMove, error);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool RuntimeCoordinator::ValidatePresetName(const std::string& presetName, std::string& error) const
|
||||||
|
{
|
||||||
|
if (mRuntimeStore.IsValidStackPresetName(presetName))
|
||||||
|
return true;
|
||||||
|
|
||||||
|
error = "Preset name must include at least one letter or number.";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
RuntimeCoordinatorResult RuntimeCoordinator::ApplyStoreMutation(bool succeeded, const std::string& errorMessage, bool reloadRequired, bool preserveFeedbackState, bool persistenceRequested)
|
||||||
|
{
|
||||||
|
if (!succeeded)
|
||||||
|
{
|
||||||
|
RuntimeCoordinatorResult result;
|
||||||
|
result.accepted = false;
|
||||||
|
result.errorMessage = errorMessage;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (reloadRequired)
|
||||||
|
{
|
||||||
|
RuntimeCoordinatorResult result = BuildQueuedReloadResult(preserveFeedbackState);
|
||||||
|
result.persistenceRequested = persistenceRequested;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
RuntimeCoordinatorResult result = BuildAcceptedNoReloadResult();
|
||||||
|
result.persistenceRequested = persistenceRequested;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
RuntimeCoordinatorResult RuntimeCoordinator::BuildQueuedReloadResult(bool preserveFeedbackState)
|
||||||
|
{
|
||||||
|
mPreserveFeedbackOnNextShaderBuild = preserveFeedbackState;
|
||||||
|
mUseCommittedLayerStates = true;
|
||||||
|
|
||||||
|
RuntimeCoordinatorResult result;
|
||||||
|
result.accepted = true;
|
||||||
|
result.runtimeStateBroadcastRequired = true;
|
||||||
|
result.shaderBuildRequested = true;
|
||||||
|
result.compileStatusChanged = true;
|
||||||
|
result.compileStatusSucceeded = true;
|
||||||
|
result.compileStatusMessage = "Shader rebuild queued.";
|
||||||
|
result.clearReloadRequest = true;
|
||||||
|
result.committedStateMode = RuntimeCoordinatorCommittedStateMode::UseCommittedStates;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
RuntimeCoordinatorResult RuntimeCoordinator::BuildAcceptedNoReloadResult() const
|
||||||
|
{
|
||||||
|
RuntimeCoordinatorResult result;
|
||||||
|
result.accepted = true;
|
||||||
|
result.runtimeStateBroadcastRequired = true;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
void RuntimeCoordinator::PublishFileChangeDetected(const std::string& reason, bool registryChanged, bool reloadRequested) const
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
FileChangeDetectedEvent event;
|
||||||
|
event.path = reason;
|
||||||
|
event.shaderPackageCandidate = registryChanged || reloadRequested;
|
||||||
|
event.runtimeConfigCandidate = false;
|
||||||
|
event.presetCandidate = false;
|
||||||
|
mRuntimeEventDispatcher.PublishPayload(event, "RuntimeCoordinator");
|
||||||
|
}
|
||||||
|
catch (...)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void RuntimeCoordinator::PublishManualReloadRequested(bool preserveFeedbackState, const std::string& reason) const
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
ManualReloadRequestedEvent event;
|
||||||
|
event.preserveFeedbackState = preserveFeedbackState;
|
||||||
|
event.reason = reason;
|
||||||
|
mRuntimeEventDispatcher.PublishPayload(event, "RuntimeCoordinator");
|
||||||
|
}
|
||||||
|
catch (...)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void RuntimeCoordinator::PublishCoordinatorResult(const std::string& action, const RuntimeCoordinatorResult& result) const
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
RuntimeMutationEvent mutation;
|
||||||
|
mutation.action = action;
|
||||||
|
mutation.accepted = result.accepted;
|
||||||
|
mutation.runtimeStateChanged = result.accepted && result.runtimeStateBroadcastRequired;
|
||||||
|
mutation.runtimeStateBroadcastRequired = result.runtimeStateBroadcastRequired;
|
||||||
|
mutation.shaderBuildRequested = result.shaderBuildRequested;
|
||||||
|
mutation.persistenceRequested = result.persistenceRequested;
|
||||||
|
mutation.clearTransientOscState = result.transientOscInvalidation != RuntimeCoordinatorTransientOscInvalidation::None;
|
||||||
|
mutation.renderResetScope = ToRuntimeEventRenderResetScope(result.renderResetScope);
|
||||||
|
mutation.errorMessage = result.errorMessage;
|
||||||
|
mRuntimeEventDispatcher.PublishPayload(mutation, "RuntimeCoordinator");
|
||||||
|
|
||||||
|
PublishCoordinatorFollowUpEvents(action, result);
|
||||||
|
}
|
||||||
|
catch (...)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void RuntimeCoordinator::PublishCoordinatorFollowUpEvents(const std::string& action, const RuntimeCoordinatorResult& result) const
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (!result.accepted)
|
||||||
|
return;
|
||||||
|
|
||||||
|
if (result.runtimeStateBroadcastRequired)
|
||||||
|
{
|
||||||
|
RuntimeStateChangedEvent stateChanged;
|
||||||
|
stateChanged.reason = action;
|
||||||
|
stateChanged.renderVisible = result.renderResetScope != RuntimeCoordinatorRenderResetScope::None;
|
||||||
|
stateChanged.persistenceRequested = result.persistenceRequested;
|
||||||
|
mRuntimeEventDispatcher.PublishPayload(stateChanged, "RuntimeCoordinator");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result.persistenceRequested)
|
||||||
|
{
|
||||||
|
RuntimePersistenceRequestedEvent persistenceRequested;
|
||||||
|
persistenceRequested.request = PersistenceRequest::RuntimeStateRequest(action);
|
||||||
|
mRuntimeEventDispatcher.PublishPayload(persistenceRequested, "RuntimeCoordinator");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result.shaderBuildRequested)
|
||||||
|
{
|
||||||
|
RuntimeReloadRequestedEvent reloadRequested;
|
||||||
|
reloadRequested.preserveFeedbackState = mPreserveFeedbackOnNextShaderBuild;
|
||||||
|
reloadRequested.reason = action;
|
||||||
|
mRuntimeEventDispatcher.PublishPayload(reloadRequested, "RuntimeCoordinator");
|
||||||
|
|
||||||
|
ShaderBuildEvent shaderBuild;
|
||||||
|
shaderBuild.phase = RuntimeEventShaderBuildPhase::Requested;
|
||||||
|
shaderBuild.preserveFeedbackState = mPreserveFeedbackOnNextShaderBuild;
|
||||||
|
shaderBuild.succeeded = true;
|
||||||
|
shaderBuild.message = result.compileStatusMessage;
|
||||||
|
mRuntimeEventDispatcher.PublishPayload(shaderBuild, "RuntimeCoordinator");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result.compileStatusChanged)
|
||||||
|
{
|
||||||
|
CompileStatusChangedEvent compileStatus;
|
||||||
|
compileStatus.succeeded = result.compileStatusSucceeded;
|
||||||
|
compileStatus.message = result.compileStatusMessage;
|
||||||
|
mRuntimeEventDispatcher.PublishPayload(compileStatus, "RuntimeCoordinator");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (...)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "RuntimeJson.h"
|
||||||
|
#include "ShaderTypes.h"
|
||||||
|
|
||||||
|
#include <atomic>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <mutex>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
class RuntimeStore;
|
||||||
|
class RuntimeEventDispatcher;
|
||||||
|
|
||||||
|
enum class RuntimeCoordinatorCommittedStateMode
|
||||||
|
{
|
||||||
|
Unchanged,
|
||||||
|
UseCommittedStates,
|
||||||
|
UseLiveSnapshots
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class RuntimeCoordinatorRenderResetScope
|
||||||
|
{
|
||||||
|
None,
|
||||||
|
TemporalHistoryOnly,
|
||||||
|
TemporalHistoryAndFeedback
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class RuntimeCoordinatorTransientOscInvalidation
|
||||||
|
{
|
||||||
|
None,
|
||||||
|
Layer,
|
||||||
|
All
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class RuntimeCoordinatorOscCommitPersistence
|
||||||
|
{
|
||||||
|
SessionOnly,
|
||||||
|
Persistent
|
||||||
|
};
|
||||||
|
|
||||||
|
struct RuntimeCoordinatorResult
|
||||||
|
{
|
||||||
|
bool accepted = false;
|
||||||
|
bool runtimeStateBroadcastRequired = false;
|
||||||
|
bool shaderBuildRequested = false;
|
||||||
|
bool persistenceRequested = false;
|
||||||
|
bool compileStatusChanged = false;
|
||||||
|
bool compileStatusSucceeded = false;
|
||||||
|
bool clearReloadRequest = false;
|
||||||
|
RuntimeCoordinatorCommittedStateMode committedStateMode = RuntimeCoordinatorCommittedStateMode::Unchanged;
|
||||||
|
RuntimeCoordinatorRenderResetScope renderResetScope = RuntimeCoordinatorRenderResetScope::None;
|
||||||
|
RuntimeCoordinatorTransientOscInvalidation transientOscInvalidation = RuntimeCoordinatorTransientOscInvalidation::None;
|
||||||
|
std::string transientOscLayerKey;
|
||||||
|
std::string compileStatusMessage;
|
||||||
|
std::string errorMessage;
|
||||||
|
};
|
||||||
|
|
||||||
|
class RuntimeCoordinator
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
RuntimeCoordinator(RuntimeStore& runtimeStore, RuntimeEventDispatcher& runtimeEventDispatcher);
|
||||||
|
|
||||||
|
RuntimeCoordinatorResult AddLayer(const std::string& shaderId);
|
||||||
|
RuntimeCoordinatorResult RemoveLayer(const std::string& layerId);
|
||||||
|
RuntimeCoordinatorResult MoveLayer(const std::string& layerId, int direction);
|
||||||
|
RuntimeCoordinatorResult MoveLayerToIndex(const std::string& layerId, std::size_t targetIndex);
|
||||||
|
RuntimeCoordinatorResult SetLayerBypass(const std::string& layerId, bool bypassed);
|
||||||
|
RuntimeCoordinatorResult SetLayerShader(const std::string& layerId, const std::string& shaderId);
|
||||||
|
RuntimeCoordinatorResult UpdateLayerParameter(const std::string& layerId, const std::string& parameterId, const JsonValue& newValue);
|
||||||
|
RuntimeCoordinatorResult UpdateLayerParameterByControlKey(const std::string& layerKey, const std::string& parameterKey, const JsonValue& newValue);
|
||||||
|
RuntimeCoordinatorResult CommitOscParameterByControlKey(const std::string& layerKey, const std::string& parameterKey, const JsonValue& newValue);
|
||||||
|
RuntimeCoordinatorResult ResetLayerParameters(const std::string& layerId);
|
||||||
|
RuntimeCoordinatorResult SaveStackPreset(const std::string& presetName);
|
||||||
|
RuntimeCoordinatorResult LoadStackPreset(const std::string& presetName);
|
||||||
|
|
||||||
|
RuntimeCoordinatorResult RequestShaderReload(bool preserveFeedbackState = false);
|
||||||
|
RuntimeCoordinatorResult PollRuntimeStoreChanges(bool& registryChanged);
|
||||||
|
RuntimeCoordinatorResult HandleRuntimePollFailure(const std::string& error);
|
||||||
|
RuntimeCoordinatorResult HandlePreparedShaderBuildFailure(const std::string& error);
|
||||||
|
RuntimeCoordinatorResult HandlePreparedShaderBuildSuccess();
|
||||||
|
RuntimeCoordinatorResult HandleRuntimeReloadRequest();
|
||||||
|
void ApplyCommittedStateMode(RuntimeCoordinatorCommittedStateMode mode);
|
||||||
|
bool UseCommittedLayerStates() const;
|
||||||
|
bool PreserveFeedbackOnNextShaderBuild() const;
|
||||||
|
|
||||||
|
private:
|
||||||
|
struct ResolvedParameterMutation
|
||||||
|
{
|
||||||
|
std::string layerId;
|
||||||
|
std::string parameterId;
|
||||||
|
ShaderParameterValue value;
|
||||||
|
bool persistState = true;
|
||||||
|
};
|
||||||
|
|
||||||
|
bool BuildParameterMutationById(const std::string& layerId, const std::string& parameterId, const JsonValue& newValue,
|
||||||
|
bool persistState, ResolvedParameterMutation& mutation, std::string& error) const;
|
||||||
|
bool BuildParameterMutationByControlKey(const std::string& layerKey, const std::string& parameterKey, const JsonValue& newValue,
|
||||||
|
bool persistState, ResolvedParameterMutation& mutation, std::string& error) const;
|
||||||
|
bool BuildParameterMutationFromSnapshot(const std::string& layerId, const ShaderParameterDefinition& definition,
|
||||||
|
const ShaderParameterValue& currentValue, bool hasCurrentValue, const JsonValue& newValue,
|
||||||
|
bool persistState, ResolvedParameterMutation& mutation, std::string& error) const;
|
||||||
|
bool ValidateLayerExists(const std::string& layerId, std::string& error) const;
|
||||||
|
bool ValidateShaderExists(const std::string& shaderId, std::string& error) const;
|
||||||
|
bool ResolveLayerMove(const std::string& layerId, int direction, bool& shouldMove, std::string& error) const;
|
||||||
|
bool ResolveLayerMoveToIndex(const std::string& layerId, std::size_t targetIndex, bool& shouldMove, std::string& error) const;
|
||||||
|
bool ValidatePresetName(const std::string& presetName, std::string& error) const;
|
||||||
|
RuntimeCoordinatorResult ApplyStoreMutation(bool succeeded, const std::string& errorMessage, bool reloadRequired, bool preserveFeedbackState, bool persistenceRequested);
|
||||||
|
RuntimeCoordinatorResult BuildQueuedReloadResult(bool preserveFeedbackState);
|
||||||
|
RuntimeCoordinatorResult BuildAcceptedNoReloadResult() const;
|
||||||
|
void PublishFileChangeDetected(const std::string& reason, bool registryChanged, bool reloadRequested) const;
|
||||||
|
void PublishManualReloadRequested(bool preserveFeedbackState, const std::string& reason) const;
|
||||||
|
void PublishCoordinatorResult(const std::string& action, const RuntimeCoordinatorResult& result) const;
|
||||||
|
void PublishCoordinatorFollowUpEvents(const std::string& action, const RuntimeCoordinatorResult& result) const;
|
||||||
|
|
||||||
|
RuntimeStore& mRuntimeStore;
|
||||||
|
RuntimeEventDispatcher& mRuntimeEventDispatcher;
|
||||||
|
mutable std::mutex mMutex;
|
||||||
|
bool mPreserveFeedbackOnNextShaderBuild = false;
|
||||||
|
std::atomic<bool> mUseCommittedLayerStates{ false };
|
||||||
|
};
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "RuntimeEventPayloads.h"
|
||||||
|
|
||||||
|
#include <chrono>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <string>
|
||||||
|
#include <type_traits>
|
||||||
|
#include <utility>
|
||||||
|
#include <variant>
|
||||||
|
|
||||||
|
using RuntimeEventPayload = std::variant<
|
||||||
|
std::monostate,
|
||||||
|
OscValueReceivedEvent,
|
||||||
|
OscValueCoalescedEvent,
|
||||||
|
OscCommitRequestedEvent,
|
||||||
|
HttpControlMutationRequestedEvent,
|
||||||
|
WebSocketClientConnectedEvent,
|
||||||
|
RuntimeStateBroadcastRequestedEvent,
|
||||||
|
FileChangeDetectedEvent,
|
||||||
|
ManualReloadRequestedEvent,
|
||||||
|
RuntimeMutationEvent,
|
||||||
|
RuntimeStateChangedEvent,
|
||||||
|
RuntimePersistenceRequestedEvent,
|
||||||
|
RuntimeReloadRequestedEvent,
|
||||||
|
ShaderPackagesChangedEvent,
|
||||||
|
RenderSnapshotPublishRequestedEvent,
|
||||||
|
RuntimeStatePresentationChangedEvent,
|
||||||
|
ShaderBuildEvent,
|
||||||
|
CompileStatusChangedEvent,
|
||||||
|
RenderSnapshotPublishedEvent,
|
||||||
|
RenderResetEvent,
|
||||||
|
OscOverlayEvent,
|
||||||
|
FrameRenderedEvent,
|
||||||
|
PreviewFrameAvailableEvent,
|
||||||
|
InputSignalChangedEvent,
|
||||||
|
InputFrameArrivedEvent,
|
||||||
|
OutputFrameScheduledEvent,
|
||||||
|
OutputFrameCompletedEvent,
|
||||||
|
BackendStateChangedEvent,
|
||||||
|
SubsystemWarningEvent,
|
||||||
|
SubsystemRecoveredEvent,
|
||||||
|
TimingSampleRecordedEvent,
|
||||||
|
QueueDepthChangedEvent>;
|
||||||
|
|
||||||
|
inline RuntimeEventType RuntimeEventPayloadType(const RuntimeEventPayload& payload)
|
||||||
|
{
|
||||||
|
return std::visit([](const auto& value) -> RuntimeEventType {
|
||||||
|
using PayloadType = std::decay_t<decltype(value)>;
|
||||||
|
if constexpr (std::is_same_v<PayloadType, std::monostate>)
|
||||||
|
return RuntimeEventType::Unknown;
|
||||||
|
else
|
||||||
|
return RuntimeEventPayloadType(value);
|
||||||
|
}, payload);
|
||||||
|
}
|
||||||
|
|
||||||
|
struct RuntimeEvent
|
||||||
|
{
|
||||||
|
RuntimeEventType type = RuntimeEventType::Unknown;
|
||||||
|
uint64_t sequence = 0;
|
||||||
|
std::chrono::steady_clock::time_point createdAt = std::chrono::steady_clock::now();
|
||||||
|
std::string source;
|
||||||
|
RuntimeEventPayload payload;
|
||||||
|
|
||||||
|
bool HasPayload() const
|
||||||
|
{
|
||||||
|
return !std::holds_alternative<std::monostate>(payload);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool PayloadMatchesType() const
|
||||||
|
{
|
||||||
|
return RuntimeEventPayloadType(payload) == type;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
template <typename Payload>
|
||||||
|
RuntimeEvent MakeRuntimeEvent(Payload payload, std::string source = {}, uint64_t sequence = 0,
|
||||||
|
std::chrono::steady_clock::time_point createdAt = std::chrono::steady_clock::now())
|
||||||
|
{
|
||||||
|
RuntimeEvent event;
|
||||||
|
event.type = RuntimeEventPayloadType(payload);
|
||||||
|
event.sequence = sequence;
|
||||||
|
event.createdAt = createdAt;
|
||||||
|
event.source = std::move(source);
|
||||||
|
event.payload = std::move(payload);
|
||||||
|
return event;
|
||||||
|
}
|
||||||
@@ -0,0 +1,158 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "RuntimeEvent.h"
|
||||||
|
|
||||||
|
#include <chrono>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <deque>
|
||||||
|
#include <functional>
|
||||||
|
#include <map>
|
||||||
|
#include <mutex>
|
||||||
|
#include <string>
|
||||||
|
#include <utility>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
struct RuntimeEventCoalescingQueueMetrics
|
||||||
|
{
|
||||||
|
std::size_t depth = 0;
|
||||||
|
std::size_t capacity = 0;
|
||||||
|
std::size_t droppedCount = 0;
|
||||||
|
std::size_t coalescedCount = 0;
|
||||||
|
double oldestEventAgeMilliseconds = 0.0;
|
||||||
|
};
|
||||||
|
|
||||||
|
inline std::string RuntimeEventDefaultCoalescingKey(const RuntimeEvent& event)
|
||||||
|
{
|
||||||
|
if (const auto* payload = std::get_if<OscValueReceivedEvent>(&event.payload))
|
||||||
|
return std::string(RuntimeEventTypeName(event.type)) + ":" + payload->routeKey;
|
||||||
|
if (const auto* payload = std::get_if<OscCommitRequestedEvent>(&event.payload))
|
||||||
|
return std::string(RuntimeEventTypeName(event.type)) + ":" + payload->routeKey;
|
||||||
|
if (const auto* payload = std::get_if<FileChangeDetectedEvent>(&event.payload))
|
||||||
|
return std::string(RuntimeEventTypeName(event.type)) + ":" + payload->path;
|
||||||
|
if (const auto* payload = std::get_if<ShaderBuildEvent>(&event.payload))
|
||||||
|
return std::string(RuntimeEventTypeName(event.type)) + ":" +
|
||||||
|
std::to_string(payload->inputWidth) + "x" +
|
||||||
|
std::to_string(payload->inputHeight) + ":" +
|
||||||
|
(payload->preserveFeedbackState ? "preserve" : "reset");
|
||||||
|
if (const auto* payload = std::get_if<RenderSnapshotPublishRequestedEvent>(&event.payload))
|
||||||
|
return std::string(RuntimeEventTypeName(event.type)) + ":" +
|
||||||
|
std::to_string(payload->outputWidth) + "x" +
|
||||||
|
std::to_string(payload->outputHeight);
|
||||||
|
if (const auto* payload = std::get_if<TimingSampleRecordedEvent>(&event.payload))
|
||||||
|
return std::string(RuntimeEventTypeName(event.type)) + ":" + payload->subsystem + ":" + payload->metric;
|
||||||
|
if (const auto* payload = std::get_if<QueueDepthChangedEvent>(&event.payload))
|
||||||
|
return std::string(RuntimeEventTypeName(event.type)) + ":" + payload->queueName;
|
||||||
|
|
||||||
|
return std::string(RuntimeEventTypeName(event.type));
|
||||||
|
}
|
||||||
|
|
||||||
|
class RuntimeEventCoalescingQueue
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
using KeySelector = std::function<std::string(const RuntimeEvent&)>;
|
||||||
|
|
||||||
|
explicit RuntimeEventCoalescingQueue(std::size_t capacity = 256, KeySelector keySelector = RuntimeEventDefaultCoalescingKey) :
|
||||||
|
mCapacity(capacity),
|
||||||
|
mKeySelector(std::move(keySelector))
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Push(RuntimeEvent event)
|
||||||
|
{
|
||||||
|
const std::string key = mKeySelector(event);
|
||||||
|
if (key.empty())
|
||||||
|
return false;
|
||||||
|
|
||||||
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
|
auto found = mEntries.find(key);
|
||||||
|
if (found != mEntries.end())
|
||||||
|
{
|
||||||
|
const auto firstCreatedAt = found->second.event.createdAt;
|
||||||
|
found->second.event = std::move(event);
|
||||||
|
found->second.event.createdAt = firstCreatedAt;
|
||||||
|
++found->second.coalescedCount;
|
||||||
|
++mCoalescedCount;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mEntries.size() >= mCapacity)
|
||||||
|
{
|
||||||
|
++mDroppedCount;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
mOrder.push_back(key);
|
||||||
|
Entry entry;
|
||||||
|
entry.event = std::move(event);
|
||||||
|
mEntries.emplace(key, std::move(entry));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<RuntimeEvent> Drain(std::size_t maxEvents = 0)
|
||||||
|
{
|
||||||
|
std::vector<RuntimeEvent> events;
|
||||||
|
|
||||||
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
|
const std::size_t count = maxEvents == 0 || maxEvents > mOrder.size() ? mOrder.size() : maxEvents;
|
||||||
|
events.reserve(count);
|
||||||
|
|
||||||
|
for (std::size_t index = 0; index < count; ++index)
|
||||||
|
{
|
||||||
|
const std::string key = std::move(mOrder.front());
|
||||||
|
mOrder.pop_front();
|
||||||
|
|
||||||
|
auto found = mEntries.find(key);
|
||||||
|
if (found == mEntries.end())
|
||||||
|
continue;
|
||||||
|
|
||||||
|
events.push_back(std::move(found->second.event));
|
||||||
|
mEntries.erase(found);
|
||||||
|
}
|
||||||
|
|
||||||
|
return events;
|
||||||
|
}
|
||||||
|
|
||||||
|
RuntimeEventCoalescingQueueMetrics GetMetrics(std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now()) const
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
|
|
||||||
|
RuntimeEventCoalescingQueueMetrics metrics;
|
||||||
|
metrics.depth = mEntries.size();
|
||||||
|
metrics.capacity = mCapacity;
|
||||||
|
metrics.droppedCount = mDroppedCount;
|
||||||
|
metrics.coalescedCount = mCoalescedCount;
|
||||||
|
|
||||||
|
if (!mOrder.empty())
|
||||||
|
{
|
||||||
|
const auto found = mEntries.find(mOrder.front());
|
||||||
|
if (found != mEntries.end())
|
||||||
|
{
|
||||||
|
const auto age = now - found->second.event.createdAt;
|
||||||
|
metrics.oldestEventAgeMilliseconds = std::chrono::duration<double, std::milli>(age).count();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return metrics;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::size_t Depth() const
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
|
return mEntries.size();
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
struct Entry
|
||||||
|
{
|
||||||
|
RuntimeEvent event;
|
||||||
|
std::size_t coalescedCount = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
mutable std::mutex mMutex;
|
||||||
|
std::size_t mCapacity = 0;
|
||||||
|
KeySelector mKeySelector;
|
||||||
|
std::deque<std::string> mOrder;
|
||||||
|
std::map<std::string, Entry> mEntries;
|
||||||
|
std::size_t mDroppedCount = 0;
|
||||||
|
std::size_t mCoalescedCount = 0;
|
||||||
|
};
|
||||||
@@ -0,0 +1,170 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "RuntimeEventCoalescingQueue.h"
|
||||||
|
#include "RuntimeEventQueue.h"
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <atomic>
|
||||||
|
#include <functional>
|
||||||
|
#include <map>
|
||||||
|
#include <mutex>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
struct RuntimeEventDispatchResult
|
||||||
|
{
|
||||||
|
std::size_t dispatchedEvents = 0;
|
||||||
|
std::size_t handlerInvocations = 0;
|
||||||
|
std::size_t handlerFailures = 0;
|
||||||
|
double dispatchDurationMilliseconds = 0.0;
|
||||||
|
};
|
||||||
|
|
||||||
|
class RuntimeEventDispatcher
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
using Handler = std::function<void(const RuntimeEvent&)>;
|
||||||
|
|
||||||
|
explicit RuntimeEventDispatcher(std::size_t queueCapacity = 1024) :
|
||||||
|
mQueue(queueCapacity),
|
||||||
|
mCoalescingQueue(queueCapacity)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Publish(RuntimeEvent event)
|
||||||
|
{
|
||||||
|
if (!event.PayloadMatchesType())
|
||||||
|
return false;
|
||||||
|
|
||||||
|
if (event.sequence == 0)
|
||||||
|
event.sequence = mNextSequence.fetch_add(1);
|
||||||
|
|
||||||
|
if (ShouldCoalesce(event))
|
||||||
|
return mCoalescingQueue.Push(std::move(event));
|
||||||
|
|
||||||
|
return mQueue.Push(std::move(event));
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename Payload>
|
||||||
|
bool PublishPayload(Payload payload, std::string source = {})
|
||||||
|
{
|
||||||
|
return Publish(MakeRuntimeEvent(std::move(payload), std::move(source)));
|
||||||
|
}
|
||||||
|
|
||||||
|
void Subscribe(RuntimeEventType type, Handler handler)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mHandlerMutex);
|
||||||
|
mHandlers[type].push_back(std::move(handler));
|
||||||
|
}
|
||||||
|
|
||||||
|
void SubscribeAll(Handler handler)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mHandlerMutex);
|
||||||
|
mAllHandlers.push_back(std::move(handler));
|
||||||
|
}
|
||||||
|
|
||||||
|
RuntimeEventDispatchResult DispatchPending(std::size_t maxEvents = 0)
|
||||||
|
{
|
||||||
|
const auto startedAt = std::chrono::steady_clock::now();
|
||||||
|
RuntimeEventDispatchResult result;
|
||||||
|
FlushCoalescedToFifo(maxEvents);
|
||||||
|
std::vector<RuntimeEvent> events = mQueue.Drain(maxEvents);
|
||||||
|
result.dispatchedEvents = events.size();
|
||||||
|
|
||||||
|
for (const RuntimeEvent& event : events)
|
||||||
|
{
|
||||||
|
std::vector<Handler> handlers = HandlersFor(event.type);
|
||||||
|
result.handlerInvocations += handlers.size();
|
||||||
|
|
||||||
|
for (const Handler& handler : handlers)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
handler(event);
|
||||||
|
}
|
||||||
|
catch (...)
|
||||||
|
{
|
||||||
|
++result.handlerFailures;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
result.dispatchDurationMilliseconds =
|
||||||
|
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - startedAt).count();
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool TryPop(RuntimeEvent& event)
|
||||||
|
{
|
||||||
|
return mQueue.TryPop(event);
|
||||||
|
}
|
||||||
|
|
||||||
|
RuntimeEventQueueMetrics GetQueueMetrics(std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now()) const
|
||||||
|
{
|
||||||
|
RuntimeEventQueueMetrics metrics = mQueue.GetMetrics(now);
|
||||||
|
const RuntimeEventCoalescingQueueMetrics coalescingMetrics = mCoalescingQueue.GetMetrics(now);
|
||||||
|
if (metrics.depth == 0)
|
||||||
|
metrics.oldestEventAgeMilliseconds = coalescingMetrics.oldestEventAgeMilliseconds;
|
||||||
|
else if (coalescingMetrics.depth > 0)
|
||||||
|
metrics.oldestEventAgeMilliseconds = (std::max)(metrics.oldestEventAgeMilliseconds, coalescingMetrics.oldestEventAgeMilliseconds);
|
||||||
|
metrics.depth += coalescingMetrics.depth;
|
||||||
|
metrics.capacity += coalescingMetrics.capacity;
|
||||||
|
metrics.droppedCount += coalescingMetrics.droppedCount;
|
||||||
|
metrics.coalescedCount = coalescingMetrics.coalescedCount;
|
||||||
|
return metrics;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::size_t QueueDepth() const
|
||||||
|
{
|
||||||
|
return mQueue.Depth() + mCoalescingQueue.Depth();
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
static bool ShouldCoalesce(const RuntimeEvent& event)
|
||||||
|
{
|
||||||
|
switch (event.type)
|
||||||
|
{
|
||||||
|
case RuntimeEventType::OscValueReceived:
|
||||||
|
case RuntimeEventType::OscCommitRequested:
|
||||||
|
case RuntimeEventType::RuntimeStateBroadcastRequested:
|
||||||
|
case RuntimeEventType::FileChangeDetected:
|
||||||
|
case RuntimeEventType::RuntimeReloadRequested:
|
||||||
|
case RuntimeEventType::ShaderBuildRequested:
|
||||||
|
case RuntimeEventType::RenderSnapshotPublishRequested:
|
||||||
|
case RuntimeEventType::TimingSampleRecorded:
|
||||||
|
case RuntimeEventType::QueueDepthChanged:
|
||||||
|
return true;
|
||||||
|
default:
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void FlushCoalescedToFifo(std::size_t maxEvents)
|
||||||
|
{
|
||||||
|
const std::size_t fifoDepth = mQueue.Depth();
|
||||||
|
if (maxEvents != 0 && fifoDepth >= maxEvents)
|
||||||
|
return;
|
||||||
|
|
||||||
|
const std::size_t flushLimit = maxEvents == 0 ? 0 : maxEvents - fifoDepth;
|
||||||
|
std::vector<RuntimeEvent> events = mCoalescingQueue.Drain(flushLimit);
|
||||||
|
for (RuntimeEvent& event : events)
|
||||||
|
mQueue.Push(std::move(event));
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<Handler> HandlersFor(RuntimeEventType type) const
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mHandlerMutex);
|
||||||
|
std::vector<Handler> handlers = mAllHandlers;
|
||||||
|
|
||||||
|
const auto found = mHandlers.find(type);
|
||||||
|
if (found != mHandlers.end())
|
||||||
|
handlers.insert(handlers.end(), found->second.begin(), found->second.end());
|
||||||
|
|
||||||
|
return handlers;
|
||||||
|
}
|
||||||
|
|
||||||
|
RuntimeEventQueue mQueue;
|
||||||
|
RuntimeEventCoalescingQueue mCoalescingQueue;
|
||||||
|
std::atomic<uint64_t> mNextSequence{ 1 };
|
||||||
|
mutable std::mutex mHandlerMutex;
|
||||||
|
std::map<RuntimeEventType, std::vector<Handler>> mHandlers;
|
||||||
|
std::vector<Handler> mAllHandlers;
|
||||||
|
};
|
||||||
@@ -0,0 +1,442 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "RuntimeEventType.h"
|
||||||
|
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include "PersistenceRequest.h"
|
||||||
|
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
enum class RuntimeEventSeverity
|
||||||
|
{
|
||||||
|
Debug,
|
||||||
|
Info,
|
||||||
|
Warning,
|
||||||
|
Error
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class RuntimeEventRenderResetScope
|
||||||
|
{
|
||||||
|
None,
|
||||||
|
TemporalHistoryOnly,
|
||||||
|
TemporalHistoryAndFeedback
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class RuntimeEventShaderBuildPhase
|
||||||
|
{
|
||||||
|
Requested,
|
||||||
|
Prepared,
|
||||||
|
Applied,
|
||||||
|
Failed
|
||||||
|
};
|
||||||
|
|
||||||
|
struct OscValueReceivedEvent
|
||||||
|
{
|
||||||
|
std::string routeKey;
|
||||||
|
std::string layerKey;
|
||||||
|
std::string parameterKey;
|
||||||
|
std::string valueJson;
|
||||||
|
uint64_t generation = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct OscValueCoalescedEvent
|
||||||
|
{
|
||||||
|
std::string routeKey;
|
||||||
|
std::size_t coalescedCount = 0;
|
||||||
|
uint64_t latestGeneration = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct OscCommitRequestedEvent
|
||||||
|
{
|
||||||
|
std::string routeKey;
|
||||||
|
std::string layerKey;
|
||||||
|
std::string parameterKey;
|
||||||
|
std::string valueJson;
|
||||||
|
uint64_t generation = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct HttpControlMutationRequestedEvent
|
||||||
|
{
|
||||||
|
std::string method;
|
||||||
|
std::string path;
|
||||||
|
std::string bodyJson;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct WebSocketClientConnectedEvent
|
||||||
|
{
|
||||||
|
std::string clientId;
|
||||||
|
std::size_t connectedClientCount = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct RuntimeStateBroadcastRequestedEvent
|
||||||
|
{
|
||||||
|
std::string reason;
|
||||||
|
bool coalescable = true;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct FileChangeDetectedEvent
|
||||||
|
{
|
||||||
|
std::string path;
|
||||||
|
bool shaderPackageCandidate = false;
|
||||||
|
bool runtimeConfigCandidate = false;
|
||||||
|
bool presetCandidate = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ManualReloadRequestedEvent
|
||||||
|
{
|
||||||
|
bool preserveFeedbackState = false;
|
||||||
|
std::string reason;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct RuntimeMutationEvent
|
||||||
|
{
|
||||||
|
std::string action;
|
||||||
|
bool accepted = false;
|
||||||
|
bool runtimeStateChanged = false;
|
||||||
|
bool runtimeStateBroadcastRequired = false;
|
||||||
|
bool shaderBuildRequested = false;
|
||||||
|
bool persistenceRequested = false;
|
||||||
|
bool clearTransientOscState = false;
|
||||||
|
RuntimeEventRenderResetScope renderResetScope = RuntimeEventRenderResetScope::None;
|
||||||
|
std::string errorMessage;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct RuntimeStateChangedEvent
|
||||||
|
{
|
||||||
|
std::string reason;
|
||||||
|
bool renderVisible = false;
|
||||||
|
bool persistenceRequested = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct RuntimePersistenceRequestedEvent
|
||||||
|
{
|
||||||
|
PersistenceRequest request;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct RuntimeReloadRequestedEvent
|
||||||
|
{
|
||||||
|
bool preserveFeedbackState = false;
|
||||||
|
std::string reason;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ShaderPackagesChangedEvent
|
||||||
|
{
|
||||||
|
bool registryChanged = false;
|
||||||
|
std::size_t packageCount = 0;
|
||||||
|
std::string reason;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct RenderSnapshotPublishRequestedEvent
|
||||||
|
{
|
||||||
|
unsigned inputWidth = 0;
|
||||||
|
unsigned inputHeight = 0;
|
||||||
|
unsigned outputWidth = 0;
|
||||||
|
unsigned outputHeight = 0;
|
||||||
|
std::string reason;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct RuntimeStatePresentationChangedEvent
|
||||||
|
{
|
||||||
|
std::string reason;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ShaderBuildEvent
|
||||||
|
{
|
||||||
|
RuntimeEventShaderBuildPhase phase = RuntimeEventShaderBuildPhase::Requested;
|
||||||
|
uint64_t generation = 0;
|
||||||
|
unsigned inputWidth = 0;
|
||||||
|
unsigned inputHeight = 0;
|
||||||
|
bool preserveFeedbackState = false;
|
||||||
|
bool succeeded = false;
|
||||||
|
std::string message;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct CompileStatusChangedEvent
|
||||||
|
{
|
||||||
|
bool succeeded = false;
|
||||||
|
std::string message;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct RenderSnapshotPublishedEvent
|
||||||
|
{
|
||||||
|
uint64_t snapshotVersion = 0;
|
||||||
|
uint64_t structureVersion = 0;
|
||||||
|
uint64_t parameterVersion = 0;
|
||||||
|
uint64_t packageVersion = 0;
|
||||||
|
unsigned outputWidth = 0;
|
||||||
|
unsigned outputHeight = 0;
|
||||||
|
std::size_t layerCount = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct RenderResetEvent
|
||||||
|
{
|
||||||
|
RuntimeEventRenderResetScope scope = RuntimeEventRenderResetScope::None;
|
||||||
|
bool applied = false;
|
||||||
|
std::string reason;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct OscOverlayEvent
|
||||||
|
{
|
||||||
|
std::string routeKey;
|
||||||
|
std::string layerKey;
|
||||||
|
std::string parameterKey;
|
||||||
|
uint64_t generation = 0;
|
||||||
|
bool settled = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct FrameRenderedEvent
|
||||||
|
{
|
||||||
|
uint64_t frameIndex = 0;
|
||||||
|
double renderMilliseconds = 0.0;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct PreviewFrameAvailableEvent
|
||||||
|
{
|
||||||
|
uint64_t frameIndex = 0;
|
||||||
|
unsigned width = 0;
|
||||||
|
unsigned height = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct InputSignalChangedEvent
|
||||||
|
{
|
||||||
|
bool hasSignal = false;
|
||||||
|
unsigned width = 0;
|
||||||
|
unsigned height = 0;
|
||||||
|
std::string modeName;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct InputFrameArrivedEvent
|
||||||
|
{
|
||||||
|
uint64_t frameIndex = 0;
|
||||||
|
unsigned width = 0;
|
||||||
|
unsigned height = 0;
|
||||||
|
long rowBytes = 0;
|
||||||
|
std::string pixelFormat;
|
||||||
|
bool hasNoInputSource = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct OutputFrameScheduledEvent
|
||||||
|
{
|
||||||
|
uint64_t frameIndex = 0;
|
||||||
|
int64_t streamTime = 0;
|
||||||
|
int64_t duration = 0;
|
||||||
|
int64_t timeScale = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct OutputFrameCompletedEvent
|
||||||
|
{
|
||||||
|
uint64_t frameIndex = 0;
|
||||||
|
std::string result;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct BackendStateChangedEvent
|
||||||
|
{
|
||||||
|
std::string backendName;
|
||||||
|
std::string state;
|
||||||
|
std::string message;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct SubsystemWarningEvent
|
||||||
|
{
|
||||||
|
std::string subsystem;
|
||||||
|
std::string warningKey;
|
||||||
|
RuntimeEventSeverity severity = RuntimeEventSeverity::Warning;
|
||||||
|
std::string message;
|
||||||
|
bool cleared = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct SubsystemRecoveredEvent
|
||||||
|
{
|
||||||
|
std::string subsystem;
|
||||||
|
std::string recoveryKey;
|
||||||
|
std::string message;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct TimingSampleRecordedEvent
|
||||||
|
{
|
||||||
|
std::string subsystem;
|
||||||
|
std::string metric;
|
||||||
|
double value = 0.0;
|
||||||
|
std::string unit;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct QueueDepthChangedEvent
|
||||||
|
{
|
||||||
|
std::string queueName;
|
||||||
|
std::size_t depth = 0;
|
||||||
|
std::size_t capacity = 0;
|
||||||
|
std::size_t droppedCount = 0;
|
||||||
|
std::size_t coalescedCount = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
constexpr RuntimeEventType RuntimeEventPayloadType(const OscValueReceivedEvent&)
|
||||||
|
{
|
||||||
|
return RuntimeEventType::OscValueReceived;
|
||||||
|
}
|
||||||
|
|
||||||
|
constexpr RuntimeEventType RuntimeEventPayloadType(const OscValueCoalescedEvent&)
|
||||||
|
{
|
||||||
|
return RuntimeEventType::OscValueCoalesced;
|
||||||
|
}
|
||||||
|
|
||||||
|
constexpr RuntimeEventType RuntimeEventPayloadType(const OscCommitRequestedEvent&)
|
||||||
|
{
|
||||||
|
return RuntimeEventType::OscCommitRequested;
|
||||||
|
}
|
||||||
|
|
||||||
|
constexpr RuntimeEventType RuntimeEventPayloadType(const HttpControlMutationRequestedEvent&)
|
||||||
|
{
|
||||||
|
return RuntimeEventType::HttpControlMutationRequested;
|
||||||
|
}
|
||||||
|
|
||||||
|
constexpr RuntimeEventType RuntimeEventPayloadType(const WebSocketClientConnectedEvent&)
|
||||||
|
{
|
||||||
|
return RuntimeEventType::WebSocketClientConnected;
|
||||||
|
}
|
||||||
|
|
||||||
|
constexpr RuntimeEventType RuntimeEventPayloadType(const RuntimeStateBroadcastRequestedEvent&)
|
||||||
|
{
|
||||||
|
return RuntimeEventType::RuntimeStateBroadcastRequested;
|
||||||
|
}
|
||||||
|
|
||||||
|
constexpr RuntimeEventType RuntimeEventPayloadType(const FileChangeDetectedEvent&)
|
||||||
|
{
|
||||||
|
return RuntimeEventType::FileChangeDetected;
|
||||||
|
}
|
||||||
|
|
||||||
|
constexpr RuntimeEventType RuntimeEventPayloadType(const ManualReloadRequestedEvent&)
|
||||||
|
{
|
||||||
|
return RuntimeEventType::ManualReloadRequested;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline RuntimeEventType RuntimeEventPayloadType(const RuntimeMutationEvent& event)
|
||||||
|
{
|
||||||
|
return event.accepted ? RuntimeEventType::RuntimeMutationAccepted : RuntimeEventType::RuntimeMutationRejected;
|
||||||
|
}
|
||||||
|
|
||||||
|
constexpr RuntimeEventType RuntimeEventPayloadType(const RuntimeStateChangedEvent&)
|
||||||
|
{
|
||||||
|
return RuntimeEventType::RuntimeStateChanged;
|
||||||
|
}
|
||||||
|
|
||||||
|
constexpr RuntimeEventType RuntimeEventPayloadType(const RuntimePersistenceRequestedEvent&)
|
||||||
|
{
|
||||||
|
return RuntimeEventType::RuntimePersistenceRequested;
|
||||||
|
}
|
||||||
|
|
||||||
|
constexpr RuntimeEventType RuntimeEventPayloadType(const RuntimeReloadRequestedEvent&)
|
||||||
|
{
|
||||||
|
return RuntimeEventType::RuntimeReloadRequested;
|
||||||
|
}
|
||||||
|
|
||||||
|
constexpr RuntimeEventType RuntimeEventPayloadType(const ShaderPackagesChangedEvent&)
|
||||||
|
{
|
||||||
|
return RuntimeEventType::ShaderPackagesChanged;
|
||||||
|
}
|
||||||
|
|
||||||
|
constexpr RuntimeEventType RuntimeEventPayloadType(const RenderSnapshotPublishRequestedEvent&)
|
||||||
|
{
|
||||||
|
return RuntimeEventType::RenderSnapshotPublishRequested;
|
||||||
|
}
|
||||||
|
|
||||||
|
constexpr RuntimeEventType RuntimeEventPayloadType(const RuntimeStatePresentationChangedEvent&)
|
||||||
|
{
|
||||||
|
return RuntimeEventType::RuntimeStatePresentationChanged;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline RuntimeEventType RuntimeEventPayloadType(const ShaderBuildEvent& event)
|
||||||
|
{
|
||||||
|
switch (event.phase)
|
||||||
|
{
|
||||||
|
case RuntimeEventShaderBuildPhase::Requested:
|
||||||
|
return RuntimeEventType::ShaderBuildRequested;
|
||||||
|
case RuntimeEventShaderBuildPhase::Prepared:
|
||||||
|
return RuntimeEventType::ShaderBuildPrepared;
|
||||||
|
case RuntimeEventShaderBuildPhase::Applied:
|
||||||
|
return RuntimeEventType::ShaderBuildApplied;
|
||||||
|
case RuntimeEventShaderBuildPhase::Failed:
|
||||||
|
return RuntimeEventType::ShaderBuildFailed;
|
||||||
|
}
|
||||||
|
|
||||||
|
return RuntimeEventType::ShaderBuildRequested;
|
||||||
|
}
|
||||||
|
|
||||||
|
constexpr RuntimeEventType RuntimeEventPayloadType(const CompileStatusChangedEvent&)
|
||||||
|
{
|
||||||
|
return RuntimeEventType::CompileStatusChanged;
|
||||||
|
}
|
||||||
|
|
||||||
|
constexpr RuntimeEventType RuntimeEventPayloadType(const RenderSnapshotPublishedEvent&)
|
||||||
|
{
|
||||||
|
return RuntimeEventType::RenderSnapshotPublished;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline RuntimeEventType RuntimeEventPayloadType(const RenderResetEvent& event)
|
||||||
|
{
|
||||||
|
return event.applied ? RuntimeEventType::RenderResetApplied : RuntimeEventType::RenderResetRequested;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline RuntimeEventType RuntimeEventPayloadType(const OscOverlayEvent& event)
|
||||||
|
{
|
||||||
|
return event.settled ? RuntimeEventType::OscOverlaySettled : RuntimeEventType::OscOverlayApplied;
|
||||||
|
}
|
||||||
|
|
||||||
|
constexpr RuntimeEventType RuntimeEventPayloadType(const FrameRenderedEvent&)
|
||||||
|
{
|
||||||
|
return RuntimeEventType::FrameRendered;
|
||||||
|
}
|
||||||
|
|
||||||
|
constexpr RuntimeEventType RuntimeEventPayloadType(const PreviewFrameAvailableEvent&)
|
||||||
|
{
|
||||||
|
return RuntimeEventType::PreviewFrameAvailable;
|
||||||
|
}
|
||||||
|
|
||||||
|
constexpr RuntimeEventType RuntimeEventPayloadType(const InputSignalChangedEvent&)
|
||||||
|
{
|
||||||
|
return RuntimeEventType::InputSignalChanged;
|
||||||
|
}
|
||||||
|
|
||||||
|
constexpr RuntimeEventType RuntimeEventPayloadType(const InputFrameArrivedEvent&)
|
||||||
|
{
|
||||||
|
return RuntimeEventType::InputFrameArrived;
|
||||||
|
}
|
||||||
|
|
||||||
|
constexpr RuntimeEventType RuntimeEventPayloadType(const OutputFrameScheduledEvent&)
|
||||||
|
{
|
||||||
|
return RuntimeEventType::OutputFrameScheduled;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline RuntimeEventType RuntimeEventPayloadType(const OutputFrameCompletedEvent& event)
|
||||||
|
{
|
||||||
|
if (event.result == "DisplayedLate")
|
||||||
|
return RuntimeEventType::OutputLateFrameDetected;
|
||||||
|
if (event.result == "Dropped")
|
||||||
|
return RuntimeEventType::OutputDroppedFrameDetected;
|
||||||
|
return RuntimeEventType::OutputFrameCompleted;
|
||||||
|
}
|
||||||
|
|
||||||
|
constexpr RuntimeEventType RuntimeEventPayloadType(const BackendStateChangedEvent&)
|
||||||
|
{
|
||||||
|
return RuntimeEventType::BackendStateChanged;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline RuntimeEventType RuntimeEventPayloadType(const SubsystemWarningEvent& event)
|
||||||
|
{
|
||||||
|
return event.cleared ? RuntimeEventType::SubsystemWarningCleared : RuntimeEventType::SubsystemWarningRaised;
|
||||||
|
}
|
||||||
|
|
||||||
|
constexpr RuntimeEventType RuntimeEventPayloadType(const SubsystemRecoveredEvent&)
|
||||||
|
{
|
||||||
|
return RuntimeEventType::SubsystemRecovered;
|
||||||
|
}
|
||||||
|
|
||||||
|
constexpr RuntimeEventType RuntimeEventPayloadType(const TimingSampleRecordedEvent&)
|
||||||
|
{
|
||||||
|
return RuntimeEventType::TimingSampleRecorded;
|
||||||
|
}
|
||||||
|
|
||||||
|
constexpr RuntimeEventType RuntimeEventPayloadType(const QueueDepthChangedEvent&)
|
||||||
|
{
|
||||||
|
return RuntimeEventType::QueueDepthChanged;
|
||||||
|
}
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "RuntimeEvent.h"
|
||||||
|
|
||||||
|
#include <chrono>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <deque>
|
||||||
|
#include <mutex>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
struct RuntimeEventQueueMetrics
|
||||||
|
{
|
||||||
|
std::size_t depth = 0;
|
||||||
|
std::size_t capacity = 0;
|
||||||
|
std::size_t droppedCount = 0;
|
||||||
|
std::size_t coalescedCount = 0;
|
||||||
|
double oldestEventAgeMilliseconds = 0.0;
|
||||||
|
};
|
||||||
|
|
||||||
|
class RuntimeEventQueue
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
explicit RuntimeEventQueue(std::size_t capacity = 1024) :
|
||||||
|
mCapacity(capacity)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Push(RuntimeEvent event)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
|
if (mEvents.size() >= mCapacity)
|
||||||
|
{
|
||||||
|
++mDroppedCount;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
mEvents.push_back(std::move(event));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool TryPop(RuntimeEvent& event)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
|
if (mEvents.empty())
|
||||||
|
return false;
|
||||||
|
|
||||||
|
event = std::move(mEvents.front());
|
||||||
|
mEvents.pop_front();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<RuntimeEvent> Drain(std::size_t maxEvents = 0)
|
||||||
|
{
|
||||||
|
std::vector<RuntimeEvent> events;
|
||||||
|
|
||||||
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
|
const std::size_t count = maxEvents == 0 || maxEvents > mEvents.size() ? mEvents.size() : maxEvents;
|
||||||
|
events.reserve(count);
|
||||||
|
for (std::size_t index = 0; index < count; ++index)
|
||||||
|
{
|
||||||
|
events.push_back(std::move(mEvents.front()));
|
||||||
|
mEvents.pop_front();
|
||||||
|
}
|
||||||
|
|
||||||
|
return events;
|
||||||
|
}
|
||||||
|
|
||||||
|
RuntimeEventQueueMetrics GetMetrics(std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now()) const
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
|
|
||||||
|
RuntimeEventQueueMetrics metrics;
|
||||||
|
metrics.depth = mEvents.size();
|
||||||
|
metrics.capacity = mCapacity;
|
||||||
|
metrics.droppedCount = mDroppedCount;
|
||||||
|
if (!mEvents.empty())
|
||||||
|
{
|
||||||
|
const auto age = now - mEvents.front().createdAt;
|
||||||
|
metrics.oldestEventAgeMilliseconds = std::chrono::duration<double, std::milli>(age).count();
|
||||||
|
}
|
||||||
|
return metrics;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::size_t Depth() const
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mMutex);
|
||||||
|
return mEvents.size();
|
||||||
|
}
|
||||||
|
|
||||||
|
std::size_t Capacity() const
|
||||||
|
{
|
||||||
|
return mCapacity;
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
mutable std::mutex mMutex;
|
||||||
|
std::deque<RuntimeEvent> mEvents;
|
||||||
|
std::size_t mCapacity = 0;
|
||||||
|
std::size_t mDroppedCount = 0;
|
||||||
|
};
|
||||||
@@ -0,0 +1,151 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <string_view>
|
||||||
|
|
||||||
|
enum class RuntimeEventType
|
||||||
|
{
|
||||||
|
Unknown = 0,
|
||||||
|
|
||||||
|
// Control ingress.
|
||||||
|
OscValueReceived,
|
||||||
|
OscValueCoalesced,
|
||||||
|
OscCommitRequested,
|
||||||
|
HttpControlMutationRequested,
|
||||||
|
WebSocketClientConnected,
|
||||||
|
RuntimeStateBroadcastRequested,
|
||||||
|
FileChangeDetected,
|
||||||
|
ManualReloadRequested,
|
||||||
|
|
||||||
|
// Runtime policy and state.
|
||||||
|
RuntimeMutationAccepted,
|
||||||
|
RuntimeMutationRejected,
|
||||||
|
RuntimeStateChanged,
|
||||||
|
RuntimePersistenceRequested,
|
||||||
|
RuntimeReloadRequested,
|
||||||
|
ShaderPackagesChanged,
|
||||||
|
RenderSnapshotPublishRequested,
|
||||||
|
RuntimeStatePresentationChanged,
|
||||||
|
|
||||||
|
// Shader build lifecycle.
|
||||||
|
ShaderBuildRequested,
|
||||||
|
ShaderBuildPrepared,
|
||||||
|
ShaderBuildApplied,
|
||||||
|
ShaderBuildFailed,
|
||||||
|
CompileStatusChanged,
|
||||||
|
|
||||||
|
// Render lifecycle.
|
||||||
|
RenderSnapshotPublished,
|
||||||
|
RenderResetRequested,
|
||||||
|
RenderResetApplied,
|
||||||
|
OscOverlayApplied,
|
||||||
|
OscOverlaySettled,
|
||||||
|
FrameRendered,
|
||||||
|
PreviewFrameAvailable,
|
||||||
|
|
||||||
|
// Video backend lifecycle.
|
||||||
|
InputSignalChanged,
|
||||||
|
InputFrameArrived,
|
||||||
|
OutputFrameScheduled,
|
||||||
|
OutputFrameCompleted,
|
||||||
|
OutputLateFrameDetected,
|
||||||
|
OutputDroppedFrameDetected,
|
||||||
|
BackendStateChanged,
|
||||||
|
|
||||||
|
// Health and telemetry.
|
||||||
|
SubsystemWarningRaised,
|
||||||
|
SubsystemWarningCleared,
|
||||||
|
SubsystemRecovered,
|
||||||
|
TimingSampleRecorded,
|
||||||
|
QueueDepthChanged
|
||||||
|
};
|
||||||
|
|
||||||
|
constexpr std::string_view RuntimeEventTypeName(RuntimeEventType type)
|
||||||
|
{
|
||||||
|
switch (type)
|
||||||
|
{
|
||||||
|
case RuntimeEventType::Unknown:
|
||||||
|
return "Unknown";
|
||||||
|
case RuntimeEventType::OscValueReceived:
|
||||||
|
return "OscValueReceived";
|
||||||
|
case RuntimeEventType::OscValueCoalesced:
|
||||||
|
return "OscValueCoalesced";
|
||||||
|
case RuntimeEventType::OscCommitRequested:
|
||||||
|
return "OscCommitRequested";
|
||||||
|
case RuntimeEventType::HttpControlMutationRequested:
|
||||||
|
return "HttpControlMutationRequested";
|
||||||
|
case RuntimeEventType::WebSocketClientConnected:
|
||||||
|
return "WebSocketClientConnected";
|
||||||
|
case RuntimeEventType::RuntimeStateBroadcastRequested:
|
||||||
|
return "RuntimeStateBroadcastRequested";
|
||||||
|
case RuntimeEventType::FileChangeDetected:
|
||||||
|
return "FileChangeDetected";
|
||||||
|
case RuntimeEventType::ManualReloadRequested:
|
||||||
|
return "ManualReloadRequested";
|
||||||
|
case RuntimeEventType::RuntimeMutationAccepted:
|
||||||
|
return "RuntimeMutationAccepted";
|
||||||
|
case RuntimeEventType::RuntimeMutationRejected:
|
||||||
|
return "RuntimeMutationRejected";
|
||||||
|
case RuntimeEventType::RuntimeStateChanged:
|
||||||
|
return "RuntimeStateChanged";
|
||||||
|
case RuntimeEventType::RuntimePersistenceRequested:
|
||||||
|
return "RuntimePersistenceRequested";
|
||||||
|
case RuntimeEventType::RuntimeReloadRequested:
|
||||||
|
return "RuntimeReloadRequested";
|
||||||
|
case RuntimeEventType::ShaderPackagesChanged:
|
||||||
|
return "ShaderPackagesChanged";
|
||||||
|
case RuntimeEventType::RenderSnapshotPublishRequested:
|
||||||
|
return "RenderSnapshotPublishRequested";
|
||||||
|
case RuntimeEventType::RuntimeStatePresentationChanged:
|
||||||
|
return "RuntimeStatePresentationChanged";
|
||||||
|
case RuntimeEventType::ShaderBuildRequested:
|
||||||
|
return "ShaderBuildRequested";
|
||||||
|
case RuntimeEventType::ShaderBuildPrepared:
|
||||||
|
return "ShaderBuildPrepared";
|
||||||
|
case RuntimeEventType::ShaderBuildApplied:
|
||||||
|
return "ShaderBuildApplied";
|
||||||
|
case RuntimeEventType::ShaderBuildFailed:
|
||||||
|
return "ShaderBuildFailed";
|
||||||
|
case RuntimeEventType::CompileStatusChanged:
|
||||||
|
return "CompileStatusChanged";
|
||||||
|
case RuntimeEventType::RenderSnapshotPublished:
|
||||||
|
return "RenderSnapshotPublished";
|
||||||
|
case RuntimeEventType::RenderResetRequested:
|
||||||
|
return "RenderResetRequested";
|
||||||
|
case RuntimeEventType::RenderResetApplied:
|
||||||
|
return "RenderResetApplied";
|
||||||
|
case RuntimeEventType::OscOverlayApplied:
|
||||||
|
return "OscOverlayApplied";
|
||||||
|
case RuntimeEventType::OscOverlaySettled:
|
||||||
|
return "OscOverlaySettled";
|
||||||
|
case RuntimeEventType::FrameRendered:
|
||||||
|
return "FrameRendered";
|
||||||
|
case RuntimeEventType::PreviewFrameAvailable:
|
||||||
|
return "PreviewFrameAvailable";
|
||||||
|
case RuntimeEventType::InputSignalChanged:
|
||||||
|
return "InputSignalChanged";
|
||||||
|
case RuntimeEventType::InputFrameArrived:
|
||||||
|
return "InputFrameArrived";
|
||||||
|
case RuntimeEventType::OutputFrameScheduled:
|
||||||
|
return "OutputFrameScheduled";
|
||||||
|
case RuntimeEventType::OutputFrameCompleted:
|
||||||
|
return "OutputFrameCompleted";
|
||||||
|
case RuntimeEventType::OutputLateFrameDetected:
|
||||||
|
return "OutputLateFrameDetected";
|
||||||
|
case RuntimeEventType::OutputDroppedFrameDetected:
|
||||||
|
return "OutputDroppedFrameDetected";
|
||||||
|
case RuntimeEventType::BackendStateChanged:
|
||||||
|
return "BackendStateChanged";
|
||||||
|
case RuntimeEventType::SubsystemWarningRaised:
|
||||||
|
return "SubsystemWarningRaised";
|
||||||
|
case RuntimeEventType::SubsystemWarningCleared:
|
||||||
|
return "SubsystemWarningCleared";
|
||||||
|
case RuntimeEventType::SubsystemRecovered:
|
||||||
|
return "SubsystemRecovered";
|
||||||
|
case RuntimeEventType::TimingSampleRecorded:
|
||||||
|
return "TimingSampleRecorded";
|
||||||
|
case RuntimeEventType::QueueDepthChanged:
|
||||||
|
return "QueueDepthChanged";
|
||||||
|
}
|
||||||
|
|
||||||
|
return "Unknown";
|
||||||
|
}
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
#include "CommittedLiveState.h"
|
||||||
|
|
||||||
|
bool CommittedLiveState::LoadPersistentStateValue(const JsonValue& root)
|
||||||
|
{
|
||||||
|
return mLayerStack.LoadPersistentStateValue(root);
|
||||||
|
}
|
||||||
|
|
||||||
|
JsonValue CommittedLiveState::BuildPersistentStateValue(const ShaderPackageCatalog& shaderCatalog) const
|
||||||
|
{
|
||||||
|
return mLayerStack.BuildPersistentStateValue(shaderCatalog);
|
||||||
|
}
|
||||||
|
|
||||||
|
void CommittedLiveState::NormalizeLayerIds()
|
||||||
|
{
|
||||||
|
mLayerStack.NormalizeLayerIds();
|
||||||
|
}
|
||||||
|
|
||||||
|
void CommittedLiveState::EnsureDefaultsForAllLayers(const ShaderPackageCatalog& shaderCatalog)
|
||||||
|
{
|
||||||
|
mLayerStack.EnsureDefaultsForAllLayers(shaderCatalog);
|
||||||
|
}
|
||||||
|
|
||||||
|
void CommittedLiveState::EnsureDefaultLayer(const ShaderPackageCatalog& shaderCatalog)
|
||||||
|
{
|
||||||
|
mLayerStack.EnsureDefaultLayer(shaderCatalog);
|
||||||
|
}
|
||||||
|
|
||||||
|
void CommittedLiveState::RemoveLayersWithMissingPackages(const ShaderPackageCatalog& shaderCatalog)
|
||||||
|
{
|
||||||
|
mLayerStack.RemoveLayersWithMissingPackages(shaderCatalog);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool CommittedLiveState::CreateLayer(const ShaderPackageCatalog& shaderCatalog, const std::string& shaderId, std::string& error)
|
||||||
|
{
|
||||||
|
return mLayerStack.CreateLayer(shaderCatalog, shaderId, error);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool CommittedLiveState::DeleteLayer(const std::string& layerId, std::string& error)
|
||||||
|
{
|
||||||
|
return mLayerStack.DeleteLayer(layerId, error);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool CommittedLiveState::MoveLayer(const std::string& layerId, int direction, std::string& error)
|
||||||
|
{
|
||||||
|
return mLayerStack.MoveLayer(layerId, direction, error);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool CommittedLiveState::MoveLayerToIndex(const std::string& layerId, std::size_t targetIndex, std::string& error)
|
||||||
|
{
|
||||||
|
return mLayerStack.MoveLayerToIndex(layerId, targetIndex, error);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool CommittedLiveState::SetLayerBypassState(const std::string& layerId, bool bypassed, std::string& error)
|
||||||
|
{
|
||||||
|
return mLayerStack.SetLayerBypassState(layerId, bypassed, error);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool CommittedLiveState::SetLayerShaderSelection(const ShaderPackageCatalog& shaderCatalog, const std::string& layerId, const std::string& shaderId, std::string& error)
|
||||||
|
{
|
||||||
|
return mLayerStack.SetLayerShaderSelection(shaderCatalog, layerId, shaderId, error);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool CommittedLiveState::SetParameterValue(const std::string& layerId, const std::string& parameterId, const ShaderParameterValue& value, std::string& error)
|
||||||
|
{
|
||||||
|
return mLayerStack.SetParameterValue(layerId, parameterId, value, error);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool CommittedLiveState::ResetLayerParameterValues(const ShaderPackageCatalog& shaderCatalog, const std::string& layerId, std::string& error)
|
||||||
|
{
|
||||||
|
return mLayerStack.ResetLayerParameterValues(shaderCatalog, layerId, error);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool CommittedLiveState::HasLayer(const std::string& layerId) const
|
||||||
|
{
|
||||||
|
return mLayerStack.HasLayer(layerId);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool CommittedLiveState::TryGetParameterById(const ShaderPackageCatalog& shaderCatalog, const std::string& layerId, const std::string& parameterId, StoredParameterSnapshot& snapshot, std::string& error) const
|
||||||
|
{
|
||||||
|
return mLayerStack.TryGetParameterById(shaderCatalog, layerId, parameterId, snapshot, error);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool CommittedLiveState::TryGetParameterByControlKey(const ShaderPackageCatalog& shaderCatalog, const std::string& layerKey, const std::string& parameterKey, StoredParameterSnapshot& snapshot, std::string& error) const
|
||||||
|
{
|
||||||
|
return mLayerStack.TryGetParameterByControlKey(shaderCatalog, layerKey, parameterKey, snapshot, error);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool CommittedLiveState::ResolveLayerMove(const std::string& layerId, int direction, bool& shouldMove, std::string& error) const
|
||||||
|
{
|
||||||
|
return mLayerStack.ResolveLayerMove(layerId, direction, shouldMove, error);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool CommittedLiveState::ResolveLayerMoveToIndex(const std::string& layerId, std::size_t targetIndex, bool& shouldMove, std::string& error) const
|
||||||
|
{
|
||||||
|
return mLayerStack.ResolveLayerMoveToIndex(layerId, targetIndex, shouldMove, error);
|
||||||
|
}
|
||||||
|
|
||||||
|
JsonValue CommittedLiveState::BuildStackPresetValue(const ShaderPackageCatalog& shaderCatalog, const std::string& presetName) const
|
||||||
|
{
|
||||||
|
return mLayerStack.BuildStackPresetValue(shaderCatalog, presetName);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool CommittedLiveState::LoadStackPresetValue(const ShaderPackageCatalog& shaderCatalog, const JsonValue& root, std::string& error)
|
||||||
|
{
|
||||||
|
return mLayerStack.LoadStackPresetValue(shaderCatalog, root, error);
|
||||||
|
}
|
||||||
|
|
||||||
|
CommittedLiveStateReadModel CommittedLiveState::BuildReadModel(const ShaderPackageCatalog& shaderCatalog) const
|
||||||
|
{
|
||||||
|
CommittedLiveStateReadModel model;
|
||||||
|
model.layers = mLayerStack.Layers();
|
||||||
|
model.packagesById = shaderCatalog.CaptureSnapshot().packagesById;
|
||||||
|
return model;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<CommittedLiveState::LayerPersistentState> CommittedLiveState::CopyLayerStates() const
|
||||||
|
{
|
||||||
|
return mLayerStack.Layers();
|
||||||
|
}
|
||||||
|
|
||||||
|
const std::vector<CommittedLiveState::LayerPersistentState>& CommittedLiveState::Layers() const
|
||||||
|
{
|
||||||
|
return mLayerStack.Layers();
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<CommittedLiveState::LayerPersistentState>& CommittedLiveState::Layers()
|
||||||
|
{
|
||||||
|
return mLayerStack.Layers();
|
||||||
|
}
|
||||||
|
|
||||||
|
const CommittedLiveState::LayerPersistentState* CommittedLiveState::FindLayerById(const std::string& layerId) const
|
||||||
|
{
|
||||||
|
return mLayerStack.FindLayerById(layerId);
|
||||||
|
}
|
||||||
|
|
||||||
|
const LayerStackStore& CommittedLiveState::LayerStack() const
|
||||||
|
{
|
||||||
|
return mLayerStack;
|
||||||
|
}
|
||||||
|
|
||||||
|
LayerStackStore& CommittedLiveState::LayerStack()
|
||||||
|
{
|
||||||
|
return mLayerStack;
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "LayerStackStore.h"
|
||||||
|
#include "RuntimeStoreReadModels.h"
|
||||||
|
#include "ShaderPackageCatalog.h"
|
||||||
|
|
||||||
|
#include <cstddef>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
class CommittedLiveState
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
using LayerPersistentState = LayerStackStore::LayerPersistentState;
|
||||||
|
using StoredParameterSnapshot = LayerStackStore::StoredParameterSnapshot;
|
||||||
|
|
||||||
|
bool LoadPersistentStateValue(const JsonValue& root);
|
||||||
|
JsonValue BuildPersistentStateValue(const ShaderPackageCatalog& shaderCatalog) const;
|
||||||
|
void NormalizeLayerIds();
|
||||||
|
void EnsureDefaultsForAllLayers(const ShaderPackageCatalog& shaderCatalog);
|
||||||
|
void EnsureDefaultLayer(const ShaderPackageCatalog& shaderCatalog);
|
||||||
|
void RemoveLayersWithMissingPackages(const ShaderPackageCatalog& shaderCatalog);
|
||||||
|
|
||||||
|
bool CreateLayer(const ShaderPackageCatalog& shaderCatalog, const std::string& shaderId, std::string& error);
|
||||||
|
bool DeleteLayer(const std::string& layerId, std::string& error);
|
||||||
|
bool MoveLayer(const std::string& layerId, int direction, std::string& error);
|
||||||
|
bool MoveLayerToIndex(const std::string& layerId, std::size_t targetIndex, std::string& error);
|
||||||
|
bool SetLayerBypassState(const std::string& layerId, bool bypassed, std::string& error);
|
||||||
|
bool SetLayerShaderSelection(const ShaderPackageCatalog& shaderCatalog, const std::string& layerId, const std::string& shaderId, std::string& error);
|
||||||
|
bool SetParameterValue(const std::string& layerId, const std::string& parameterId, const ShaderParameterValue& value, std::string& error);
|
||||||
|
bool ResetLayerParameterValues(const ShaderPackageCatalog& shaderCatalog, const std::string& layerId, std::string& error);
|
||||||
|
|
||||||
|
bool HasLayer(const std::string& layerId) const;
|
||||||
|
bool TryGetParameterById(const ShaderPackageCatalog& shaderCatalog, const std::string& layerId, const std::string& parameterId, StoredParameterSnapshot& snapshot, std::string& error) const;
|
||||||
|
bool TryGetParameterByControlKey(const ShaderPackageCatalog& shaderCatalog, const std::string& layerKey, const std::string& parameterKey, StoredParameterSnapshot& snapshot, std::string& error) const;
|
||||||
|
bool ResolveLayerMove(const std::string& layerId, int direction, bool& shouldMove, std::string& error) const;
|
||||||
|
bool ResolveLayerMoveToIndex(const std::string& layerId, std::size_t targetIndex, bool& shouldMove, std::string& error) const;
|
||||||
|
|
||||||
|
JsonValue BuildStackPresetValue(const ShaderPackageCatalog& shaderCatalog, const std::string& presetName) const;
|
||||||
|
bool LoadStackPresetValue(const ShaderPackageCatalog& shaderCatalog, const JsonValue& root, std::string& error);
|
||||||
|
|
||||||
|
CommittedLiveStateReadModel BuildReadModel(const ShaderPackageCatalog& shaderCatalog) const;
|
||||||
|
std::vector<LayerPersistentState> CopyLayerStates() const;
|
||||||
|
const std::vector<LayerPersistentState>& Layers() const;
|
||||||
|
std::vector<LayerPersistentState>& Layers();
|
||||||
|
const LayerPersistentState* FindLayerById(const std::string& layerId) const;
|
||||||
|
const LayerStackStore& LayerStack() const;
|
||||||
|
LayerStackStore& LayerStack();
|
||||||
|
|
||||||
|
private:
|
||||||
|
LayerStackStore mLayerStack;
|
||||||
|
};
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
#include "RenderStateComposer.h"
|
||||||
|
|
||||||
|
RenderStateCompositionResult RenderStateComposer::BuildFrameState(const LayeredRenderStateInput& input) const
|
||||||
|
{
|
||||||
|
RenderStateCompositionResult result;
|
||||||
|
const std::vector<RuntimeRenderState>* layerStates =
|
||||||
|
input.committedLiveLayerStates ? input.committedLiveLayerStates : input.basePersistedLayerStates;
|
||||||
|
if (!layerStates)
|
||||||
|
return result;
|
||||||
|
|
||||||
|
result.layerStates = *layerStates;
|
||||||
|
result.hasLayerStates = !result.layerStates.empty();
|
||||||
|
if (input.transientAutomationOverlay)
|
||||||
|
{
|
||||||
|
RuntimeLiveStateApplyOptions options;
|
||||||
|
options.allowCommit = input.allowTransientAutomationCommits;
|
||||||
|
options.smoothing = input.transientAutomationSmoothing;
|
||||||
|
options.commitDelay = input.transientAutomationCommitDelay;
|
||||||
|
options.now = input.now;
|
||||||
|
input.transientAutomationOverlay->ApplyToLayerStates(
|
||||||
|
result.layerStates,
|
||||||
|
options,
|
||||||
|
input.collectTransientAutomationCommitRequests ? &result.commitRequests : nullptr);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "RuntimeLiveState.h"
|
||||||
|
|
||||||
|
#include <chrono>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
struct LayeredRenderStateInput
|
||||||
|
{
|
||||||
|
const std::vector<RuntimeRenderState>* basePersistedLayerStates = nullptr;
|
||||||
|
const std::vector<RuntimeRenderState>* committedLiveLayerStates = nullptr;
|
||||||
|
RuntimeLiveState* transientAutomationOverlay = nullptr;
|
||||||
|
bool allowTransientAutomationCommits = false;
|
||||||
|
bool collectTransientAutomationCommitRequests = true;
|
||||||
|
double transientAutomationSmoothing = 0.0;
|
||||||
|
std::chrono::milliseconds transientAutomationCommitDelay = std::chrono::milliseconds(150);
|
||||||
|
std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
|
||||||
|
};
|
||||||
|
|
||||||
|
struct RenderStateCompositionResult
|
||||||
|
{
|
||||||
|
std::vector<RuntimeRenderState> layerStates;
|
||||||
|
std::vector<RuntimeLiveOscCommitRequest> commitRequests;
|
||||||
|
bool hasLayerStates = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
class RenderStateComposer
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
RenderStateCompositionResult BuildFrameState(const LayeredRenderStateInput& input) const;
|
||||||
|
};
|
||||||
@@ -0,0 +1,329 @@
|
|||||||
|
#include "RuntimeLiveState.h"
|
||||||
|
|
||||||
|
#include "RuntimeParameterUtils.h"
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <cctype>
|
||||||
|
#include <cmath>
|
||||||
|
#include <cstddef>
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
constexpr double kOscSmoothingReferenceFps = 60.0;
|
||||||
|
constexpr double kOscSmoothingMaxStepSeconds = 0.25;
|
||||||
|
|
||||||
|
std::string SimplifyOscControlKey(const std::string& text)
|
||||||
|
{
|
||||||
|
std::string simplified;
|
||||||
|
for (unsigned char ch : text)
|
||||||
|
{
|
||||||
|
if (std::isalnum(ch))
|
||||||
|
simplified.push_back(static_cast<char>(std::tolower(ch)));
|
||||||
|
}
|
||||||
|
return simplified;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool MatchesOscControlKey(const std::string& candidate, const std::string& key)
|
||||||
|
{
|
||||||
|
return candidate == key || SimplifyOscControlKey(candidate) == SimplifyOscControlKey(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
double ClampOscAlpha(double value)
|
||||||
|
{
|
||||||
|
return (std::max)(0.0, (std::min)(1.0, value));
|
||||||
|
}
|
||||||
|
|
||||||
|
double ComputeTimeBasedOscAlpha(double smoothing, double deltaSeconds)
|
||||||
|
{
|
||||||
|
const double clampedSmoothing = ClampOscAlpha(smoothing);
|
||||||
|
if (clampedSmoothing <= 0.0)
|
||||||
|
return 0.0;
|
||||||
|
if (clampedSmoothing >= 1.0)
|
||||||
|
return 1.0;
|
||||||
|
|
||||||
|
const double clampedDeltaSeconds = (std::max)(0.0, (std::min)(kOscSmoothingMaxStepSeconds, deltaSeconds));
|
||||||
|
if (clampedDeltaSeconds <= 0.0)
|
||||||
|
return 0.0;
|
||||||
|
|
||||||
|
const double frameScale = clampedDeltaSeconds * kOscSmoothingReferenceFps;
|
||||||
|
return ClampOscAlpha(1.0 - std::pow(1.0 - clampedSmoothing, frameScale));
|
||||||
|
}
|
||||||
|
|
||||||
|
JsonValue BuildOscCommitValue(const ShaderParameterDefinition& definition, const ShaderParameterValue& value)
|
||||||
|
{
|
||||||
|
switch (definition.type)
|
||||||
|
{
|
||||||
|
case ShaderParameterType::Boolean:
|
||||||
|
return JsonValue(value.booleanValue);
|
||||||
|
case ShaderParameterType::Enum:
|
||||||
|
return JsonValue(value.enumValue);
|
||||||
|
case ShaderParameterType::Text:
|
||||||
|
return JsonValue(value.textValue);
|
||||||
|
case ShaderParameterType::Trigger:
|
||||||
|
case ShaderParameterType::Float:
|
||||||
|
return JsonValue(value.numberValues.empty() ? 0.0 : value.numberValues.front());
|
||||||
|
case ShaderParameterType::Vec2:
|
||||||
|
case ShaderParameterType::Color:
|
||||||
|
{
|
||||||
|
JsonValue array = JsonValue::MakeArray();
|
||||||
|
for (double number : value.numberValues)
|
||||||
|
array.pushBack(JsonValue(number));
|
||||||
|
return array;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return JsonValue();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
void RuntimeLiveState::Clear()
|
||||||
|
{
|
||||||
|
mOscOverlayStates.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
void RuntimeLiveState::ClearForLayerKey(const std::string& layerKey)
|
||||||
|
{
|
||||||
|
for (auto it = mOscOverlayStates.begin(); it != mOscOverlayStates.end();)
|
||||||
|
{
|
||||||
|
if (OverlayMatchesLayerKey(it->second, layerKey))
|
||||||
|
it = mOscOverlayStates.erase(it);
|
||||||
|
else
|
||||||
|
++it;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool RuntimeLiveState::OverlayMatchesLayerKey(const OscOverlayState& overlay, const std::string& layerKey)
|
||||||
|
{
|
||||||
|
return MatchesOscControlKey(overlay.layerKey, layerKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool RuntimeLiveState::TryResolveOverlayTarget(
|
||||||
|
const OscOverlayState& overlay,
|
||||||
|
const std::vector<RuntimeRenderState>& states,
|
||||||
|
std::vector<RuntimeRenderState>::const_iterator& stateIt,
|
||||||
|
std::vector<ShaderParameterDefinition>::const_iterator& definitionIt)
|
||||||
|
{
|
||||||
|
stateIt = std::find_if(states.begin(), states.end(),
|
||||||
|
[&overlay](const RuntimeRenderState& state)
|
||||||
|
{
|
||||||
|
return MatchesOscControlKey(state.layerId, overlay.layerKey) ||
|
||||||
|
MatchesOscControlKey(state.shaderId, overlay.layerKey) ||
|
||||||
|
MatchesOscControlKey(state.shaderName, overlay.layerKey);
|
||||||
|
});
|
||||||
|
if (stateIt == states.end())
|
||||||
|
return false;
|
||||||
|
|
||||||
|
definitionIt = std::find_if(stateIt->parameterDefinitions.begin(), stateIt->parameterDefinitions.end(),
|
||||||
|
[&overlay](const ShaderParameterDefinition& definition)
|
||||||
|
{
|
||||||
|
return MatchesOscControlKey(definition.id, overlay.parameterKey) ||
|
||||||
|
MatchesOscControlKey(definition.label, overlay.parameterKey);
|
||||||
|
});
|
||||||
|
return definitionIt != stateIt->parameterDefinitions.end();
|
||||||
|
}
|
||||||
|
|
||||||
|
std::size_t RuntimeLiveState::OverlayCount() const
|
||||||
|
{
|
||||||
|
return mOscOverlayStates.size();
|
||||||
|
}
|
||||||
|
|
||||||
|
void RuntimeLiveState::ApplyOscUpdates(const std::vector<RuntimeLiveOscUpdate>& updates)
|
||||||
|
{
|
||||||
|
const auto now = std::chrono::steady_clock::now();
|
||||||
|
for (const RuntimeLiveOscUpdate& update : updates)
|
||||||
|
{
|
||||||
|
auto overlayIt = mOscOverlayStates.find(update.routeKey);
|
||||||
|
if (overlayIt == mOscOverlayStates.end())
|
||||||
|
{
|
||||||
|
OscOverlayState overlay;
|
||||||
|
overlay.layerKey = update.layerKey;
|
||||||
|
overlay.parameterKey = update.parameterKey;
|
||||||
|
overlay.targetValue = update.targetValue;
|
||||||
|
overlay.lastUpdatedTime = now;
|
||||||
|
overlay.lastAppliedTime = now;
|
||||||
|
overlay.generation = 1;
|
||||||
|
mOscOverlayStates[update.routeKey] = std::move(overlay);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
overlayIt->second.targetValue = update.targetValue;
|
||||||
|
overlayIt->second.lastUpdatedTime = now;
|
||||||
|
overlayIt->second.generation += 1;
|
||||||
|
overlayIt->second.commitQueued = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void RuntimeLiveState::ApplyOscCommitCompletions(const std::vector<RuntimeLiveOscCommitCompletion>& completedCommits)
|
||||||
|
{
|
||||||
|
for (const RuntimeLiveOscCommitCompletion& completedCommit : completedCommits)
|
||||||
|
{
|
||||||
|
auto overlayIt = mOscOverlayStates.find(completedCommit.routeKey);
|
||||||
|
if (overlayIt == mOscOverlayStates.end())
|
||||||
|
continue;
|
||||||
|
|
||||||
|
OscOverlayState& overlay = overlayIt->second;
|
||||||
|
if (overlay.commitQueued &&
|
||||||
|
overlay.pendingCommitGeneration == completedCommit.generation &&
|
||||||
|
overlay.generation == completedCommit.generation)
|
||||||
|
{
|
||||||
|
mOscOverlayStates.erase(overlayIt);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void RuntimeLiveState::PruneIncompatibleOverlays(const std::vector<RuntimeRenderState>& states)
|
||||||
|
{
|
||||||
|
for (auto it = mOscOverlayStates.begin(); it != mOscOverlayStates.end();)
|
||||||
|
{
|
||||||
|
std::vector<RuntimeRenderState>::const_iterator stateIt;
|
||||||
|
std::vector<ShaderParameterDefinition>::const_iterator definitionIt;
|
||||||
|
if (TryResolveOverlayTarget(it->second, states, stateIt, definitionIt))
|
||||||
|
{
|
||||||
|
ShaderParameterValue targetValue;
|
||||||
|
std::string normalizeError;
|
||||||
|
if (NormalizeAndValidateParameterValue(*definitionIt, it->second.targetValue, targetValue, normalizeError))
|
||||||
|
{
|
||||||
|
++it;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
it = mOscOverlayStates.erase(it);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void RuntimeLiveState::ApplyToLayerStates(
|
||||||
|
std::vector<RuntimeRenderState>& states,
|
||||||
|
const RuntimeLiveStateApplyOptions& options,
|
||||||
|
std::vector<RuntimeLiveOscCommitRequest>* commitRequests)
|
||||||
|
{
|
||||||
|
if (states.empty() || mOscOverlayStates.empty())
|
||||||
|
return;
|
||||||
|
|
||||||
|
PruneIncompatibleOverlays(states);
|
||||||
|
if (mOscOverlayStates.empty())
|
||||||
|
return;
|
||||||
|
|
||||||
|
const auto now = options.now;
|
||||||
|
const double clampedSmoothing = ClampOscAlpha(options.smoothing);
|
||||||
|
std::vector<std::string> overlayKeysToRemove;
|
||||||
|
|
||||||
|
for (auto& item : mOscOverlayStates)
|
||||||
|
{
|
||||||
|
const std::string& routeKey = item.first;
|
||||||
|
OscOverlayState& overlay = item.second;
|
||||||
|
auto stateIt = std::find_if(states.begin(), states.end(),
|
||||||
|
[&overlay](const RuntimeRenderState& state)
|
||||||
|
{
|
||||||
|
return MatchesOscControlKey(state.layerId, overlay.layerKey) ||
|
||||||
|
MatchesOscControlKey(state.shaderId, overlay.layerKey) ||
|
||||||
|
MatchesOscControlKey(state.shaderName, overlay.layerKey);
|
||||||
|
});
|
||||||
|
if (stateIt == states.end())
|
||||||
|
continue;
|
||||||
|
|
||||||
|
auto definitionIt = std::find_if(stateIt->parameterDefinitions.begin(), stateIt->parameterDefinitions.end(),
|
||||||
|
[&overlay](const ShaderParameterDefinition& definition)
|
||||||
|
{
|
||||||
|
return MatchesOscControlKey(definition.id, overlay.parameterKey) ||
|
||||||
|
MatchesOscControlKey(definition.label, overlay.parameterKey);
|
||||||
|
});
|
||||||
|
if (definitionIt == stateIt->parameterDefinitions.end())
|
||||||
|
continue;
|
||||||
|
|
||||||
|
ShaderParameterValue targetValue;
|
||||||
|
std::string normalizeError;
|
||||||
|
if (!NormalizeAndValidateParameterValue(*definitionIt, overlay.targetValue, targetValue, normalizeError))
|
||||||
|
continue;
|
||||||
|
|
||||||
|
if (definitionIt->type == ShaderParameterType::Trigger)
|
||||||
|
{
|
||||||
|
ShaderParameterValue& value = stateIt->parameterValues[definitionIt->id];
|
||||||
|
const double previousCount = value.numberValues.empty() ? 0.0 : value.numberValues[0];
|
||||||
|
const double triggerTime = stateIt->timeSeconds;
|
||||||
|
value.numberValues = { previousCount + 1.0, triggerTime };
|
||||||
|
overlayKeysToRemove.push_back(routeKey);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const bool smoothable =
|
||||||
|
clampedSmoothing > 0.0 &&
|
||||||
|
(definitionIt->type == ShaderParameterType::Float ||
|
||||||
|
definitionIt->type == ShaderParameterType::Vec2 ||
|
||||||
|
definitionIt->type == ShaderParameterType::Color);
|
||||||
|
if (!smoothable)
|
||||||
|
{
|
||||||
|
overlay.currentValue = targetValue;
|
||||||
|
overlay.hasCurrentValue = true;
|
||||||
|
stateIt->parameterValues[definitionIt->id] = overlay.currentValue;
|
||||||
|
if (options.allowCommit &&
|
||||||
|
!overlay.commitQueued &&
|
||||||
|
now - overlay.lastUpdatedTime >= options.commitDelay &&
|
||||||
|
commitRequests)
|
||||||
|
{
|
||||||
|
commitRequests->push_back({ routeKey, overlay.layerKey, overlay.parameterKey, overlay.targetValue, overlay.generation });
|
||||||
|
overlay.pendingCommitGeneration = overlay.generation;
|
||||||
|
overlay.commitQueued = true;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!overlay.hasCurrentValue)
|
||||||
|
{
|
||||||
|
overlay.currentValue = DefaultValueForDefinition(*definitionIt);
|
||||||
|
auto currentIt = stateIt->parameterValues.find(definitionIt->id);
|
||||||
|
if (currentIt != stateIt->parameterValues.end())
|
||||||
|
overlay.currentValue = currentIt->second;
|
||||||
|
overlay.hasCurrentValue = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (overlay.currentValue.numberValues.size() != targetValue.numberValues.size())
|
||||||
|
overlay.currentValue.numberValues = targetValue.numberValues;
|
||||||
|
|
||||||
|
double smoothingAlpha = clampedSmoothing;
|
||||||
|
if (overlay.lastAppliedTime != std::chrono::steady_clock::time_point())
|
||||||
|
{
|
||||||
|
const double deltaSeconds =
|
||||||
|
std::chrono::duration_cast<std::chrono::duration<double>>(now - overlay.lastAppliedTime).count();
|
||||||
|
smoothingAlpha = ComputeTimeBasedOscAlpha(clampedSmoothing, deltaSeconds);
|
||||||
|
}
|
||||||
|
overlay.lastAppliedTime = now;
|
||||||
|
|
||||||
|
ShaderParameterValue nextValue = targetValue;
|
||||||
|
bool converged = true;
|
||||||
|
for (std::size_t index = 0; index < targetValue.numberValues.size(); ++index)
|
||||||
|
{
|
||||||
|
const double currentNumber = overlay.currentValue.numberValues[index];
|
||||||
|
const double targetNumber = targetValue.numberValues[index];
|
||||||
|
const double delta = targetNumber - currentNumber;
|
||||||
|
double nextNumber = currentNumber + delta * smoothingAlpha;
|
||||||
|
if (std::fabs(delta) <= 0.0005)
|
||||||
|
nextNumber = targetNumber;
|
||||||
|
else
|
||||||
|
converged = false;
|
||||||
|
nextValue.numberValues[index] = nextNumber;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (converged)
|
||||||
|
nextValue.numberValues = targetValue.numberValues;
|
||||||
|
|
||||||
|
overlay.currentValue = nextValue;
|
||||||
|
overlay.hasCurrentValue = true;
|
||||||
|
stateIt->parameterValues[definitionIt->id] = overlay.currentValue;
|
||||||
|
if (options.allowCommit &&
|
||||||
|
converged &&
|
||||||
|
!overlay.commitQueued &&
|
||||||
|
now - overlay.lastUpdatedTime >= options.commitDelay &&
|
||||||
|
commitRequests)
|
||||||
|
{
|
||||||
|
commitRequests->push_back({ routeKey, overlay.layerKey, overlay.parameterKey, BuildOscCommitValue(*definitionIt, overlay.currentValue), overlay.generation });
|
||||||
|
overlay.pendingCommitGeneration = overlay.generation;
|
||||||
|
overlay.commitQueued = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const std::string& overlayKey : overlayKeysToRemove)
|
||||||
|
mOscOverlayStates.erase(overlayKey);
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user