Compare commits

..

60 Commits

Author SHA1 Message Date
d465dd3110 CI: Disable VST on Windows
Since master doesn't have the submodule, switching from master to
27.2.4 doesn't download the submodule. We can just disable it
2022-08-02 14:52:49 -07:00
a89f47e720 CI: Force OBS version to 27.2.4
The recent tag messed up CI
2022-08-02 14:43:43 -07:00
952a1f914e base: Update version to 5.0.1 2022-08-02 14:35:13 -07:00
816c1b278b requesthandler: Allow empty object in Set*PrivateSettings requests
Requested by #958

Closes #958
2022-08-02 14:33:35 -07:00
2daba572e8 eventhandler: Provide outputPath on OUTPUT_STARTED too
4.x apparently included this path during output start along with stop.
It appears safe to include this on output start.

Closes #963
2022-08-02 14:33:25 -07:00
02ccd0b76f websocketserver: Validate op field type
Could cause a crash by assuming `op` is always a number.

Closes #965
2022-08-02 14:33:15 -07:00
f95865c2c4 base: Fix MSVC warning about misdeclared Config struct 2022-08-02 14:33:06 -07:00
4dc5229c49 requesthandler: Fix OpenVideoMixProjector program option
It was stuck opening preview regardless of setting.
2022-08-02 14:32:58 -07:00
a25427c7cc base: Final changes before release 2022-07-02 11:08:18 -07:00
99f93c4bdd websocketserver: Log disconnect code and reason on disconnects
No clue why I wasn't doing this before.
2022-07-02 10:53:46 -07:00
6af3af61d5 requesthandler: Add Outputs requests
Co-authored-by: Ruggero Tomaselli <ruggerotomaselli@gmail.com>
Co-authored-by: tt2468 <tt2468@irltoolkit.com>
2022-07-02 10:31:47 -07:00
14a1547e11 docs: Fix lint formatting error 2022-07-02 08:30:02 -07:00
60ade46481 requesthandler: Fix oopsies in OpenVideoMixProjector 2022-07-02 08:27:32 -07:00
7c21e5732e requesthandler: Add projector creation requests
I didn't think I'd be able to make remotely usable requests using OBS'
existing projector API, but I'm actually pretty happy with how it
turned out.

Closes #929

Co-authored-by: Brendan Allan <brendonovich@outlook.com>
2022-07-02 08:23:03 -07:00
f5db53f217 requesthandler: Echo request details in response of CallVendorRequest
I generally don't like to echo data provided to obs-websocket in
requests, but since we do that for the request type in base requests,
this particular case seems fair.

Closes #919
2022-07-02 07:11:44 -07:00
3400f88665 CI: Exclude qr from code format too 2022-07-02 07:03:46 -07:00
ad3cb5dcfd requesthandler, eventhandler: Add outputPath fields when record stops
Closes #934
2022-07-02 07:00:51 -07:00
5ecda806bd requesthandler: Rework and fix a few data consistency checks
Some stuff led to possible crashes, other stuff simply didn't work.
Should be much better now.

Closes #942
2022-07-02 05:57:35 -07:00
af3f29169c utils: Clean up a few iteration functions 2022-07-02 05:57:25 -07:00
af97978841 utils: Move from explicit enum converters to nlohmann macros 2022-07-02 05:57:08 -07:00
4f89378c45 utils: A few casting nitpicks 2022-07-02 05:50:37 -07:00
4fc8a3aecc CI: Fix deps formatting excludes 2022-07-02 05:49:57 -07:00
1626ae5546 Revert "Config, websocketserver: Add feature to bind to loopback (default)"
This reverts commit 1da0214201.
2022-07-02 05:49:02 -07:00
8b7fd3dd46 Revert "forms: Add configuration to enable external access"
This reverts commit 1cd12c1023.
2022-07-02 05:44:08 -07:00
73848a7370 docs: Fix EventSubscription::All subscribes 2022-07-02 05:43:57 -07:00
2e48dd24c4 base: Format code 2022-07-02 05:42:20 -07:00
ad1f28480c base: Update a few files with updated info 2022-07-02 05:36:52 -07:00
91cabe1202 websocketapi: Fix build on Windows 64 bit 2022-05-13 19:16:18 -07:00
f869f3df76 CI: Update to new branch name for release 2022-05-13 18:49:17 -07:00
dd4971b1cc lib: Fix compilation on 32 bit Windows 2022-05-13 18:48:55 -07:00
749ecc976b base, lib: Update plugin API example and tests
Updates the example and tests for the plugin API to include the latest
additions to the plugin API.
2022-05-10 23:04:21 -07:00
d85c86e3a0 base, lib: Add ability to call obs-websocket requests via plugin API
**Increments Plugin API Version**

Adds functions:
- `obs_websocket_get_api_version()` - Gets the current obs-websocket
plugin API version
- `obs_websocket_call_request()` - Calls an obs-websocket request via
the plugin API

Adds structs:
- `obs_websocket_request_response`
2022-05-10 23:04:04 -07:00
3303acfcca requesthandler: Don't require session for Request Handler
Required to call requests in situations where a session is not
relevant.
2022-05-10 22:48:57 -07:00
1cd12c1023 forms: Add configuration to enable external access
After discussion in the Discord server, and some internal discussion,
this was deemed a reasonable patch for various security concerns. This
basically controls whether obs-websocket binds to 127.0.0.1 or 0.0.0.0.

I decided to have obs-websocket bind to 127.0.0.1 by default, since
most users appear to be using obs-websocket on the same machines as
their client software. This will be changed if it poses significant
support-related issues.

Further security solutions have been discussed, but are either a heavy
amount of work, or significantly impact client applications' connect
flows.

One idea that I should mention is like a cookie system, where:
- On first connect, obs-websocket asks the user to approve the
connection.
- After authentication, obs-websocket gives the client a token in the
`Identified` message, which the client stores.
- On future connects, the client uses this token, along with the
password, to authenticate without needing user confirmation.

This system will likely be implemented in a future version of
obs-websocket.

Closes #907
2022-04-26 03:24:26 -07:00
1da0214201 Config, websocketserver: Add feature to bind to loopback (default)
Binds to localhost or 127.0.0.1 by default, since most users don't have
to access obs-websocket externally.
2022-04-25 21:31:52 -07:00
226c81ce78 utils/Platform: Ignore virtualbox interface IP
Somewhat common on systems, so we'll just manually ignore it.

Closes #928
2022-04-25 20:38:26 -07:00
ca34981aae docs(ci): Update generated docs - 828dbde [skip ci] 2022-04-26 03:33:37 +00:00
828dbde75c Merge pull request #879 from dnaka91/docs-formatting
docs: Improve generated docs formatting
2022-04-25 20:33:19 -07:00
ac102de1e8 Merge branch 'master' into docs-formatting 2022-04-25 20:30:25 -07:00
20e654186c docs(ci): Update generated docs - f42cd21 [skip ci] 2022-04-26 03:25:55 +00:00
f42cd2177a Merge pull request #889 from csunday95/feature-csunday95-get-screen-info
Requests: Add GetMonitorList
2022-04-25 20:25:37 -07:00
2479501879 Requests: Add GetMonitorList
Adds a new request `GetMonitorList` that returns a json Array of
objects containing data about connected monitors. See #868
2022-04-25 20:20:45 -07:00
371c414281 Merge pull request #924 from ChrisTallon/ipv4only
Server: Add --websocket_ipv4_only switch
2022-04-25 19:53:42 -07:00
3a5f0d89b9 Server: Add --websocket_ipv4_only switch
Socket listening default changed to IPv4 and IPv6,
overridable to IPv4 only by using the command line switch.
2022-04-25 19:53:15 -07:00
9f68e0166b docs(ci): Update generated docs - 8b85658 [skip ci] 2022-04-26 02:46:24 +00:00
8b85658c61 requesthandler: Add platform info to GetVersion
It can be very useful to know which platform you're connecting to in
the case of things like text input modification, where Windows uses
GDI while unix uses FT2.
2022-04-25 19:43:40 -07:00
a9c9363d4a eventhandler: Fix group remove signals
Like inputs, if a group is ungrouped, the group itself is not removed.
What actually happens is the removal of the last scene item triggers
a destroy, just like with inputs.

This modifies the old signal selection in favor of falling back
to the destroy signal if an object is not explicitly removed.
2022-04-16 19:34:47 -07:00
95df4782f3 docs(ci): Update generated docs - 9d89937 [skip ci] 2022-04-13 09:18:28 +00:00
9d899376a5 requesthandler: Fix docs for SetSourceFilterEnabled 2022-04-13 02:17:27 -07:00
d8c042fe4a requesthandler: Add private scene item settings get/set
Some may need it, similarly to Get/SetSourcePrivateSettings.
2022-04-13 02:13:30 -07:00
c355c72f4b requesthandler, utils: Add search offset to GetSceneItemId
Allows you to select a specific match by offset, or select the
last (top) scene item by specifying `-1`.
2022-04-13 02:01:40 -07:00
e6c48990d6 Merge pull request #925 from t2t2/patch-1
README: Add obs-websocket-js to client libraries
2022-03-26 18:34:53 -07:00
620f11e8a3 Readme: Add obs-websocket-js to client libraries 2022-03-22 20:16:48 +02:00
df13ad30b7 Update lint workflow name 2022-02-19 16:13:59 +09:00
2297432f90 Fix type in SetSourceFilterEnabled docs 2022-02-19 16:13:42 +09:00
be48d0bfe9 Add CI task to lint markdown files 2022-02-19 16:08:18 +09:00
2027394d33 Fix new markdown warnings from latest master 2022-02-19 15:58:42 +09:00
d7de347b37 Merge branch 'master' into docs-formatting 2022-02-19 15:53:39 +09:00
9b879baf38 Make titles uppercase 2021-12-19 16:10:24 +09:00
947f261d17 docs: Improve generated docs formatting 2021-12-17 16:21:07 +09:00
90 changed files with 3762 additions and 2664 deletions

107
.clang-format Normal file
View File

@ -0,0 +1,107 @@
# please use clang-format version 8 or later
Standard: Cpp11
AccessModifierOffset: -8
AlignAfterOpenBracket: Align
AlignConsecutiveAssignments: false
AlignConsecutiveDeclarations: false
AlignEscapedNewlines: Left
AlignOperands: true
AlignTrailingComments: true
#AllowAllArgumentsOnNextLine: false # requires clang-format 9
#AllowAllConstructorInitializersOnNextLine: false # requires clang-format 9
AllowAllParametersOfDeclarationOnNextLine: false
AllowShortBlocksOnASingleLine: false
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: Inline
AllowShortIfStatementsOnASingleLine: false
#AllowShortLambdasOnASingleLine: Inline # requires clang-format 9
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: false
AlwaysBreakTemplateDeclarations: false
BinPackArguments: true
BinPackParameters: true
BraceWrapping:
AfterClass: false
AfterControlStatement: false
AfterEnum: false
AfterFunction: true
AfterNamespace: false
AfterObjCDeclaration: false
AfterStruct: false
AfterUnion: false
AfterExternBlock: false
BeforeCatch: false
BeforeElse: false
IndentBraces: false
SplitEmptyFunction: true
SplitEmptyRecord: true
SplitEmptyNamespace: true
BreakBeforeBinaryOperators: None
BreakBeforeBraces: Custom
BreakBeforeTernaryOperators: true
BreakConstructorInitializers: BeforeColon
BreakStringLiterals: false # apparently unpredictable
ColumnLimit: 132
CompactNamespaces: false
ConstructorInitializerAllOnOneLineOrOnePerLine: true
ConstructorInitializerIndentWidth: 8
ContinuationIndentWidth: 8
Cpp11BracedListStyle: true
DerivePointerAlignment: false
DisableFormat: false
FixNamespaceComments: false
ForEachMacros:
- 'json_object_foreach'
- 'json_object_foreach_safe'
- 'json_array_foreach'
IncludeBlocks: Preserve
IndentCaseLabels: false
IndentPPDirectives: None
IndentWidth: 8
IndentWrappedFunctionNames: false
KeepEmptyLinesAtTheStartOfBlocks: true
MaxEmptyLinesToKeep: 1
NamespaceIndentation: All
#ObjCBinPackProtocolList: Auto # requires clang-format 7
ObjCBlockIndentWidth: 8
ObjCSpaceAfterProperty: true
ObjCSpaceBeforeProtocolList: true
PenaltyBreakAssignment: 10
PenaltyBreakBeforeFirstCallParameter: 30
PenaltyBreakComment: 10
PenaltyBreakFirstLessLess: 0
PenaltyBreakString: 10
PenaltyExcessCharacter: 100
PenaltyReturnTypeOnItsOwnLine: 60
PointerAlignment: Right
ReflowComments: false
SortIncludes: false
SortUsingDeclarations: false
SpaceAfterCStyleCast: false
#SpaceAfterLogicalNot: false # requires clang-format 9
SpaceAfterTemplateKeyword: false
SpaceBeforeAssignmentOperators: true
#SpaceBeforeCtorInitializerColon: true # requires clang-format 7
#SpaceBeforeInheritanceColon: true # requires clang-format 7
SpaceBeforeParens: ControlStatements
#SpaceBeforeRangeBasedForLoopColon: true # requires clang-format 7
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 1
SpacesInAngles: false
SpacesInCStyleCastParentheses: false
SpacesInContainerLiterals: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
#StatementMacros: # requires clang-format 8
# - 'Q_OBJECT'
TabWidth: 8
#TypenameMacros: # requires clang-format 9
# - 'DARRAY'
UseTab: ForContinuationAndIndentation
---
Language: ObjC

View File

@ -27,10 +27,11 @@ body:
- macOS 10.15 - macOS 10.15
- macOS 10.14 - macOS 10.14
- macOS 10.13 - macOS 10.13
- Ubuntu 22.04 LTS
- Ubuntu 21.04 - Ubuntu 21.04
- Ubuntu 20.10 - Ubuntu 20.10
- Ubuntu 20.04 - Ubuntu 20.04 LTS
- Ubuntu 18.04 - Ubuntu 18.04 LTS
- Other - Other
validations: validations:
required: true required: true
@ -48,6 +49,12 @@ body:
label: OBS Studio Version label: OBS Studio Version
description: What version of OBS Studio are you using? description: What version of OBS Studio are you using?
options: options:
- 28.0.0
- 27.2.4
- 27.2.3
- 27.2.2
- 27.2.1
- 27.2.0
- 27.1.3 - 27.1.3
- 27.1.1 - 27.1.1
- 27.1.0 - 27.1.0
@ -69,11 +76,9 @@ body:
label: obs-websocket Version label: obs-websocket Version
description: What version of obs-websocket are you using? description: What version of obs-websocket are you using?
options: options:
- 5.0.1
- 5.0.0
- 5.0.0-beta1 - 5.0.0-beta1
- 5.0.0-alpha3
- 5.0.0-alpha2
- 4.9.1
- 4.9.0
- Git - Git
validations: validations:
required: true required: true

View File

@ -29,6 +29,6 @@ Tested OS(s):
<!--- If you're unsure about any of these, don't hesitate to ask. We're here to help! --> <!--- If you're unsure about any of these, don't hesitate to ask. We're here to help! -->
- [ ] I have read the [Contributing Guidelines](https://github.com/obsproject/obs-websocket/wiki/Contributing-Guidelines). - [ ] I have read the [Contributing Guidelines](https://github.com/obsproject/obs-websocket/wiki/Contributing-Guidelines).
- [ ] All commit messages are properly formatted and commits squashed where appropriate. - [ ] All commit messages are properly formatted and commits squashed where appropriate.
- [ ] My code is not on the `master` branch. - [ ] My code is not on `master` or a `release/*` branch.
- [ ] The code has been tested. - [ ] The code has been tested.
- [ ] I have included updates to all appropriate documentation. - [ ] I have included updates to all appropriate documentation.

View File

@ -5,7 +5,7 @@ on:
paths-ignore: paths-ignore:
- 'docs/generated/**' - 'docs/generated/**'
branches: branches:
- master - release/5.0.0
jobs: jobs:
docs-build: docs-build:

24
.github/workflows/lint.yml vendored Normal file
View File

@ -0,0 +1,24 @@
name: Code Quality
on:
push:
branches:
- release/5.0.0
pull_request:
branches:
- release/5.0.0
jobs:
markdown:
name: Lint Markdown
runs-on: ubuntu-latest
if: contains(github.event.head_commit.message, '[skip ci]') != true
steps:
- name: Checkout repository
uses: actions/checkout@v2
- name: Generate docs
run: cd docs && ./build_docs.sh
- name: Run markdownlint-cli
uses: nosborn/github-action-markdown-cli@v3.0.1
with:
files: .

View File

@ -5,7 +5,7 @@ on:
paths-ignore: paths-ignore:
- 'docs/**' - 'docs/**'
branches: branches:
- master - release/5.0.0
tags: tags:
- '[45].[0-9]+.[0-9]+*' - '[45].[0-9]+.[0-9]+*'
pull_request: pull_request:
@ -13,7 +13,7 @@ on:
- 'docs/**' - 'docs/**'
- '**.md' - '**.md'
branches: branches:
- master - release/5.0.0
jobs: jobs:
windows: windows:
@ -47,7 +47,8 @@ jobs:
run: | run: |
git fetch --prune --unshallow git fetch --prune --unshallow
echo "OBS_GIT_HASH=$(git rev-parse --short HEAD)" >> $GITHUB_ENV echo "OBS_GIT_HASH=$(git rev-parse --short HEAD)" >> $GITHUB_ENV
echo "OBS_GIT_TAG=$(git describe --tags --abbrev=0)" >> $GITHUB_ENV echo "OBS_GIT_TAG=27.2.4" >> $GITHUB_ENV
# echo "OBS_GIT_TAG=$(git describe --tags --abbrev=0)" >> $GITHUB_ENV
- name: 'Checkout last OBS Studio release (${{ env.OBS_GIT_TAG }})' - name: 'Checkout last OBS Studio release (${{ env.OBS_GIT_TAG }})'
shell: bash shell: bash
working-directory: ${{ github.workspace }}/obs-studio working-directory: ${{ github.workspace }}/obs-studio
@ -110,7 +111,7 @@ jobs:
run: | run: |
if(!(Test-Path -Path ".\build32")){New-Item -ItemType directory -Path .\build32} if(!(Test-Path -Path ".\build32")){New-Item -ItemType directory -Path .\build32}
cd .\build32 cd .\build32
cmake -G "${{ env.CMAKE_GENERATOR }}" -A Win32 -DCMAKE_SYSTEM_VERSION="${{ env.CMAKE_SYSTEM_VERSION }}" -DQTDIR="${{ github.workspace }}\cmbuild\QT\${{ env.QT_VERSION }}\msvc2019" -DDepsPath="${{ github.workspace }}\cmbuild\deps\win32" -DCOPIED_DEPENDENCIES=NO -DCOPY_DEPENDENCIES=YES -DBUILD_BROWSER=OFF .. cmake -G "${{ env.CMAKE_GENERATOR }}" -A Win32 -DCMAKE_SYSTEM_VERSION="${{ env.CMAKE_SYSTEM_VERSION }}" -DQTDIR="${{ github.workspace }}\cmbuild\QT\${{ env.QT_VERSION }}\msvc2019" -DDepsPath="${{ github.workspace }}\cmbuild\deps\win32" -DCOPIED_DEPENDENCIES=NO -DCOPY_DEPENDENCIES=YES -DBUILD_BROWSER=OFF -DBUILD_VST=OFF ..
- name: 'Build OBS Studio 32-bit' - name: 'Build OBS Studio 32-bit'
if: steps.build-cache-obs-32.outputs.cache-hit != 'true' if: steps.build-cache-obs-32.outputs.cache-hit != 'true'
working-directory: ${{ github.workspace }}/obs-studio working-directory: ${{ github.workspace }}/obs-studio
@ -131,7 +132,7 @@ jobs:
run: | run: |
if(!(Test-Path -Path ".\build64")){New-Item -ItemType directory -Path .\build64} if(!(Test-Path -Path ".\build64")){New-Item -ItemType directory -Path .\build64}
cd .\build64 cd .\build64
cmake -G "${{ env.CMAKE_GENERATOR }}" -A x64 -DCMAKE_SYSTEM_VERSION="${{ env.CMAKE_SYSTEM_VERSION }}" -DQTDIR="${{ github.workspace }}\cmbuild\QT\${{ env.QT_VERSION }}\msvc2019_64" -DDepsPath="${{ github.workspace }}\cmbuild\deps\win64" -DCOPIED_DEPENDENCIES=NO -DCOPY_DEPENDENCIES=YES -DBUILD_BROWSER=OFF .. cmake -G "${{ env.CMAKE_GENERATOR }}" -A x64 -DCMAKE_SYSTEM_VERSION="${{ env.CMAKE_SYSTEM_VERSION }}" -DQTDIR="${{ github.workspace }}\cmbuild\QT\${{ env.QT_VERSION }}\msvc2019_64" -DDepsPath="${{ github.workspace }}\cmbuild\deps\win64" -DCOPIED_DEPENDENCIES=NO -DCOPY_DEPENDENCIES=YES -DBUILD_BROWSER=OFF -DBUILD_VST=OFF ..
- name: 'Build OBS Studio 64-bit' - name: 'Build OBS Studio 64-bit'
if: steps.build-cache-obs-64.outputs.cache-hit != 'true' if: steps.build-cache-obs-64.outputs.cache-hit != 'true'
working-directory: ${{ github.workspace }}/obs-studio working-directory: ${{ github.workspace }}/obs-studio
@ -201,7 +202,8 @@ jobs:
run: | run: |
git fetch --prune --unshallow git fetch --prune --unshallow
echo "OBS_GIT_HASH=$(git rev-parse --short HEAD)" >> $GITHUB_ENV echo "OBS_GIT_HASH=$(git rev-parse --short HEAD)" >> $GITHUB_ENV
echo "OBS_GIT_TAG=$(git describe --tags --abbrev=0)" >> $GITHUB_ENV echo "OBS_GIT_TAG=27.2.4" >> $GITHUB_ENV
# echo "OBS_GIT_TAG=$(git describe --tags --abbrev=0)" >> $GITHUB_ENV
- name: 'Checkout last OBS Studio release (${{ env.OBS_GIT_TAG }})' - name: 'Checkout last OBS Studio release (${{ env.OBS_GIT_TAG }})'
shell: bash shell: bash
working-directory: ${{ github.workspace }}/obs-studio working-directory: ${{ github.workspace }}/obs-studio
@ -334,9 +336,9 @@ jobs:
cd ./build cd ./build
sudo checkinstall -y --type=debian --fstrans=no -nodoc \ sudo checkinstall -y --type=debian --fstrans=no -nodoc \
--backup=no --deldoc=yes --install=no --pkgname=obs-websocket --pkgversion="$CHECKINSTALL_VERSION" \ --backup=no --deldoc=yes --install=no --pkgname=obs-websocket --pkgversion="$CHECKINSTALL_VERSION" \
--pkglicense="GPLv2.0" --maintainer="${{ github.event.pusher.email }}" --pkggroup="video" \ --pkglicense="GPLv2.0" --maintainer="tt2468@irltoolkit.com" --pkggroup="video" \
--pkgsource="${{ github.event.repository.html_url }}" \ --pkgsource="${{ github.event.repository.html_url }}" \
--requires="obs-studio,libqt5network5,libqt5concurrent5,qt5-image-formats-plugins" \ --requires="obs-studio,libqt5network5,qt5-image-formats-plugins" \
--pakdir="../package" --pakdir="../package"
sudo chmod ao+r ../package/* sudo chmod ao+r ../package/*
sudo mv ../package/* ../package/${{ env.LINUX_FILENAME }} sudo mv ../package/* ../package/${{ env.LINUX_FILENAME }}
@ -388,7 +390,8 @@ jobs:
run: | run: |
git fetch --prune --unshallow git fetch --prune --unshallow
echo "OBS_GIT_HASH=$(git rev-parse --short HEAD)" >> $GITHUB_ENV echo "OBS_GIT_HASH=$(git rev-parse --short HEAD)" >> $GITHUB_ENV
echo "OBS_GIT_TAG=$(git describe --tags --abbrev=0)" >> $GITHUB_ENV echo "OBS_GIT_TAG=27.2.4" >> $GITHUB_ENV
# echo "OBS_GIT_TAG=$(git describe --tags --abbrev=0)" >> $GITHUB_ENV
- name: 'Checkout last OBS Studio release (${{ env.OBS_GIT_TAG }})' - name: 'Checkout last OBS Studio release (${{ env.OBS_GIT_TAG }})'
shell: bash shell: bash
working-directory: ${{ github.workspace }}/obs-studio working-directory: ${{ github.workspace }}/obs-studio

2
.markdownlintignore Normal file
View File

@ -0,0 +1,2 @@
/deps
/docs/comments/node_modules

3
.markdownlintrc Normal file
View File

@ -0,0 +1,3 @@
{
"line-length": false
}

57
CI/check-format.sh Executable file
View File

@ -0,0 +1,57 @@
#!/usr/bin/env bash
# Original source https://github.com/Project-OSRM/osrm-backend/blob/master/scripts/format.sh
set -o errexit
set -o pipefail
set -o nounset
if [ ${#} -eq 1 ]; then
VERBOSITY="--verbose"
else
VERBOSITY=""
fi
# Runs the Clang Formatter in parallel on the code base.
# Return codes:
# - 1 there are files to be formatted
# - 0 everything looks fine
# Get CPU count
OS=$(uname)
NPROC=1
if [[ ${OS} = "Linux" ]] ; then
NPROC=$(nproc)
elif [[ ${OS} = "Darwin" ]] ; then
NPROC=$(sysctl -n hw.physicalcpu)
fi
# Discover clang-format
if type clang-format-12 2> /dev/null ; then
CLANG_FORMAT=clang-format-12
elif type clang-format 2> /dev/null ; then
# Clang format found, but need to check version
CLANG_FORMAT=clang-format
V=$(clang-format --version)
if [[ $V != *"version 12.0"* ]]; then
echo "clang-format is not 12.0 (returned ${V})"
exit 1
fi
else
echo "No appropriate clang-format found (expected clang-format-12.0.0, or clang-format)"
exit 1
fi
find . -type d \( \
-path ./\*build\* -o \
-path ./deps/websocketpp -o \
-path ./deps/asio -o \
-path ./deps/json -o \
-path ./deps/qr \
\) -prune -false -type f -o \
-name '*.h' -or \
-name '*.hpp' -or \
-name '*.m' -or \
-name '*.m,' -or \
-name '*.c' -or \
-name '*.cpp' \
| xargs -L100 -P ${NPROC} ${CLANG_FORMAT} ${VERBOSITY} -i -style=file -fallback-style=none

View File

@ -1,7 +1,7 @@
cmake_minimum_required(VERSION 3.16...3.20) cmake_minimum_required(VERSION 3.16...3.20)
# Version variables # Version variables
project(obs-websocket VERSION 5.0.0) project(obs-websocket VERSION 5.0.1)
set(OBS_WEBSOCKET_RPC_VERSION 1) set(OBS_WEBSOCKET_RPC_VERSION 1)
@ -85,7 +85,7 @@ configure_file(
) )
# Inlude sources # Include sources
set(obs-websocket_SOURCES set(obs-websocket_SOURCES
src/obs-websocket.cpp src/obs-websocket.cpp
src/Config.cpp src/Config.cpp
@ -129,7 +129,6 @@ set(obs-websocket_SOURCES
src/utils/Json.cpp src/utils/Json.cpp
src/utils/Obs.cpp src/utils/Obs.cpp
src/utils/Obs_StringHelper.cpp src/utils/Obs_StringHelper.cpp
src/utils/Obs_EnumHelper.cpp
src/utils/Obs_NumberHelper.cpp src/utils/Obs_NumberHelper.cpp
src/utils/Obs_ArrayHelper.cpp src/utils/Obs_ArrayHelper.cpp
src/utils/Obs_ObjectHelper.cpp src/utils/Obs_ObjectHelper.cpp

View File

@ -1,3 +1,5 @@
<!-- markdownlint-disable no-inline-html -->
# obs-websocket # obs-websocket
<p align="center"> <p align="center">
@ -6,7 +8,6 @@
WebSocket API for OBS Studio. WebSocket API for OBS Studio.
[![CI Multiplatform Build](https://github.com/obsproject/obs-websocket/actions/workflows/main.yml/badge.svg?branch=master)](https://github.com/obsproject/obs-websocket/actions/workflows/main.yml)
[![Discord](https://img.shields.io/discord/715691013825364120.svg?label=&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2)](https://discord.gg/WBaSQ3A) [![Discord](https://img.shields.io/discord/715691013825364120.svg?label=&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2)](https://discord.gg/WBaSQ3A)
[![Financial Contributors on Open Collective](https://opencollective.com/obs-websocket-dev/all/badge.svg?label=financial+contributors)](https://opencollective.com/obs-websocket-dev) [![Financial Contributors on Open Collective](https://opencollective.com/obs-websocket-dev/all/badge.svg?label=financial+contributors)](https://opencollective.com/obs-websocket-dev)
@ -18,7 +19,7 @@ Binaries for Windows, MacOS, and Linux are available in the [Releases](https://g
It is **highly recommended** to protect obs-websocket with a password against unauthorized control. To do this, open the "Websocket server settings" dialog under OBS' "Tools" menu. In the settings dialogs, you can enable or disable authentication and set a password for it. It is **highly recommended** to protect obs-websocket with a password against unauthorized control. To do this, open the "Websocket server settings" dialog under OBS' "Tools" menu. In the settings dialogs, you can enable or disable authentication and set a password for it.
(Psst. You can use `--websocket_port`(value), `--websocket_password`(value), and `--websocket_debug`(flag) on the command line to override the configured values.) (Psst. You can use `--websocket_port`(value), `--websocket_password`(value), `--websocket_debug`(flag) and `--websocket_ipv4_only`(flag) on the command line to override the configured values.)
### Possible use cases ### Possible use cases
@ -27,14 +28,17 @@ It is **highly recommended** to protect obs-websocket with a password against un
- Automate scene switching with a third-party program (e.g. : auto-pilot, foot pedal, ...) - Automate scene switching with a third-party program (e.g. : auto-pilot, foot pedal, ...)
### Client software ### Client software
- (No known clients supporting 5.0.0 at the moment. Ping us in the Discord if you have one!) - (No known clients supporting 5.0.0 at the moment. Ping us in the Discord if you have one!)
### Client libraries (for developers) ### Client libraries (for developers)
Here's a list of available language APIs for obs-websocket: Here's a list of available language APIs for obs-websocket:
- Python 3.7+ (Asyncio): [simpleobsws](https://github.com/IRLToolkit/simpleobsws/tree/master) by IRLToolkit - Python 3.7+ (Asyncio): [simpleobsws](https://github.com/IRLToolkit/simpleobsws/tree/master) by IRLToolkit
- Rust: [obws](https://github.com/dnaka91/obws/tree/v5-api) by dnaka91 - Rust: [obws](https://github.com/dnaka91/obws/tree/v5-api) by dnaka91
- Godot 3.4.x: [obs-websocket-gd](https://github.com/you-win/obs-websocket-gd) by you-win - Godot 3.4.x: [obs-websocket-gd](https://github.com/you-win/obs-websocket-gd) by you-win
- Javascript (Node and web): [obs-websocket-js](https://github.com/obs-websocket-community-projects/obs-websocket-js) by OBS Websocket Community
The 5.x server is a typical WebSocket server running by default on port 4455 (the port number can be changed in the Settings dialog under `Tools`). The 5.x server is a typical WebSocket server running by default on port 4455 (the port number can be changed in the Settings dialog under `Tools`).
The protocol we use is documented in [PROTOCOL.md](docs/generated/protocol.md). The protocol we use is documented in [PROTOCOL.md](docs/generated/protocol.md).

View File

@ -1,11 +1,13 @@
# obs-websocket documentation # obs-websocket documentation
This is the documentation for obs-websocket. Run build_docs.sh to auto generate the latest docs from the `src` directory. There are 3 components to the docs generation: This is the documentation for obs-websocket. Run `build_docs.sh` to auto generate the latest docs from the `src` directory. There are 3 components to the docs generation:
- `comments/comments.js`: Generates the `work/comments.json` file from the code comments in the src directory. - `comments/comments.js`: Generates the `work/comments.json` file from the code comments in the src directory.
- `docs/process_comments.py`: Processes `work/comments.json` to create `generated/protocol.json`, which is a machine-readable documentation format that can be used to create obs-websocket client libraries. - `docs/process_comments.py`: Processes `work/comments.json` to create `generated/protocol.json`, which is a machine-readable documentation format that can be used to create obs-websocket client libraries.
- `docs/generate_md.py`: Processes `generated/protocol.json` to create `generated/protocol.md`, which is the actual human-readable documentation. - `docs/generate_md.py`: Processes `generated/protocol.json` to create `generated/protocol.md`, which is the actual human-readable documentation.
Some notes about documenting: Some notes about documenting:
- The `complexity` comment line is a suggestion to the user about how much knowledge about OBS's inner workings is required to safely use the associated feature. `1` for easy, `5` for megadeath-expert. - The `complexity` comment line is a suggestion to the user about how much knowledge about OBS's inner workings is required to safely use the associated feature. `1` for easy, `5` for megadeath-expert.
- The `rpcVersion` comment line is used to specify the latest available version that the feature is available in. If a feature is deprecated, then the placeholder value of `-1` should be replaced with the last RPC version that the feature will be available in. Manually specifying an RPC version automatically adds the `Deprecated` line to the entry in `generated/protocol.md`. - The `rpcVersion` comment line is used to specify the latest available version that the feature is available in. If a feature is deprecated, then the placeholder value of `-1` should be replaced with the last RPC version that the feature will be available in. Manually specifying an RPC version automatically adds the `Deprecated` line to the entry in `generated/protocol.md`.
- The description can be multiple lines, but must be contained above the first documentation property (the lines starting with `@`). - The description can be multiple lines, but must be contained above the first documentation property (the lines starting with `@`).
@ -13,13 +15,15 @@ Some notes about documenting:
- `Array` types follow this format: `Array<subtype>`, for example `Array<String>` to specify an array of strings. - `Array` types follow this format: `Array<subtype>`, for example `Array<String>` to specify an array of strings.
Formatting notes: Formatting notes:
- Fields should have their columns aligned. So in a request, the columns of all `@requestField`s should be aligned. - Fields should have their columns aligned. So in a request, the columns of all `@requestField`s should be aligned.
- We suggest looking at how other enums/events/requests have been documented before documenting one of your own, to get a general feel of how things have been formatted. - We suggest looking at how other enums/events/requests have been documented before documenting one of your own, to get a general feel of how things have been formatted.
## Creating enum documentation ## Creating enum documentation
Enums follow this code comment format: Enums follow this code comment format:
```
```js
/** /**
* [description] * [description]
* *
@ -33,7 +37,8 @@ Enums follow this code comment format:
``` ```
Example code comment: Example code comment:
```
```js
/** /**
* The initial message sent by obs-websocket to newly connected clients. * The initial message sent by obs-websocket to newly connected clients.
* *
@ -45,12 +50,14 @@ Example code comment:
* @api enums * @api enums
*/ */
``` ```
- This is the documentation for the `WebSocketOpCode::Hello` enum identifier. - This is the documentation for the `WebSocketOpCode::Hello` enum identifier.
## Creating event documentation ## Creating event documentation
Events follow this code comment format: Events follow this code comment format:
```
```js
/** /**
* [description] * [description]
* *
@ -68,7 +75,8 @@ Events follow this code comment format:
``` ```
Example code comment: Example code comment:
```
```js
/** /**
* Studio mode has been enabled or disabled. * Studio mode has been enabled or disabled.
* *
@ -87,7 +95,8 @@ Example code comment:
## Creating request documentation ## Creating request documentation
Requests follow this code comment format: Requests follow this code comment format:
```
```js
/** /**
* [description] * [description]
* *
@ -105,10 +114,12 @@ Requests follow this code comment format:
* @api requests * @api requests
*/ */
``` ```
- The optional flag is a `?` that prefixes the field name, telling the docs processor that the field is optionally specified. - The optional flag is a `?` that prefixes the field name, telling the docs processor that the field is optionally specified.
Example code comment: Example code comment:
```
```js
/** /**
* Gets the value of a "slot" from the selected persistent data realm. * Gets the value of a "slot" from the selected persistent data realm.
* *

View File

@ -30,7 +30,6 @@ categoryOrder = [
] ]
requestFieldHeader = """ requestFieldHeader = """
**Request Fields:** **Request Fields:**
| Name | Type | Description | Value Restrictions | ?Default Behavior | | Name | Type | Description | Value Restrictions | ?Default Behavior |
@ -38,7 +37,6 @@ requestFieldHeader = """
""" """
responseFieldHeader = """ responseFieldHeader = """
**Response Fields:** **Response Fields:**
| Name | Type | Description | | Name | Type | Description |
@ -46,7 +44,6 @@ responseFieldHeader = """
""" """
dataFieldHeader = """ dataFieldHeader = """
**Data Fields:** **Data Fields:**
| Name | Type | Description | | Name | Type | Description |
@ -130,6 +127,8 @@ def get_enums(enums):
ret += '- Added in v{}\n'.format(enumIdentifier['initialVersion']) ret += '- Added in v{}\n'.format(enumIdentifier['initialVersion'])
if enumIdentifier != enum['enumIdentifiers'][-1]: if enumIdentifier != enum['enumIdentifiers'][-1]:
ret += '\n---\n\n' ret += '\n---\n\n'
else:
ret += '\n'
return ret return ret
def get_requests_toc(requests): def get_requests_toc(requests):
@ -143,7 +142,7 @@ def get_requests_toc(requests):
if not len(requestsOut): if not len(requestsOut):
continue continue
categoryFragment = get_fragment(category, False) categoryFragment = get_fragment(category, False)
ret += '- [{}](#{})\n'.format(category, categoryFragment) ret += '- [{} Requests](#{}-requests)\n'.format(category, categoryFragment)
for request in requestsOut: for request in requestsOut:
requestType = request['requestType'] requestType = request['requestType']
requestTypeFragment = get_fragment(requestType, False) requestTypeFragment = get_fragment(requestType, False)
@ -161,7 +160,7 @@ def get_requests(requests):
if not len(requestsOut): if not len(requestsOut):
continue continue
categoryFragment = get_fragment(category) categoryFragment = get_fragment(category)
ret += '\n\n## {}\n\n'.format(category) ret += '## {} Requests\n\n'.format(category)
for request in requestsOut: for request in requestsOut:
requestType = request['requestType'] requestType = request['requestType']
requestTypeFragment = get_fragment(requestType) requestTypeFragment = get_fragment(requestType)
@ -193,6 +192,8 @@ def get_requests(requests):
if request != requestsOut[-1]: if request != requestsOut[-1]:
ret += '\n---\n\n' ret += '\n---\n\n'
else:
ret += '\n'
return ret return ret
def get_events_toc(events): def get_events_toc(events):
@ -206,7 +207,7 @@ def get_events_toc(events):
if not len(eventsOut): if not len(eventsOut):
continue continue
categoryFragment = get_fragment(category, False) categoryFragment = get_fragment(category, False)
ret += '- [{}](#{})\n'.format(category, categoryFragment) ret += '- [{} Events](#{}-events)\n'.format(category, categoryFragment)
for event in eventsOut: for event in eventsOut:
eventType = event['eventType'] eventType = event['eventType']
eventTypeFragment = get_fragment(eventType, False) eventTypeFragment = get_fragment(eventType, False)
@ -224,7 +225,7 @@ def get_events(events):
if not len(eventsOut): if not len(eventsOut):
continue continue
categoryFragment = get_fragment(category) categoryFragment = get_fragment(category)
ret += '## {}\n\n'.format(category) ret += '## {} Events\n\n'.format(category)
for event in eventsOut: for event in eventsOut:
eventType = event['eventType'] eventType = event['eventType']
eventTypeFragment = get_fragment(eventType) eventTypeFragment = get_fragment(eventType)
@ -247,6 +248,8 @@ def get_events(events):
if event != eventsOut[-1]: if event != eventsOut[-1]:
ret += '\n---\n\n' ret += '\n---\n\n'
else:
ret += '\n'
return ret return ret
# Actual code # Actual code
@ -264,40 +267,41 @@ except IOError:
with open('../generated/protocol.json', 'r') as f: with open('../generated/protocol.json', 'r') as f:
protocol = json.load(f) protocol = json.load(f)
output = "<!-- This file was automatically generated. Do not edit directly! -->\n\n" output = "<!-- This file was automatically generated. Do not edit directly! -->\n"
output += "<!-- markdownlint-disable no-bare-urls -->\n"
# Insert introduction partial # Insert introduction partial
output += read_file('partials/introduction.md') output += read_file('partials/introduction.md')
logging.info('Inserted introduction section.') logging.info('Inserted introduction section.')
output += '\n\n' output += '\n'
# Generate enums MD # Generate enums MD
output += read_file('partials/enumsHeader.md') output += read_file('partials/enumsHeader.md')
output += '\n'
output += get_enums_toc(protocol['enums']) output += get_enums_toc(protocol['enums'])
output += '\n\n' output += '\n'
output += get_enums(protocol['enums']) output += get_enums(protocol['enums'])
logging.info('Inserted enums section.') logging.info('Inserted enums section.')
output += '\n\n'
# Generate events MD # Generate events MD
output += read_file('partials/eventsHeader.md') output += read_file('partials/eventsHeader.md')
output += '\n'
output += get_events_toc(protocol['events']) output += get_events_toc(protocol['events'])
output += '\n\n' output += '\n'
output += get_events(protocol['events']) output += get_events(protocol['events'])
logging.info('Inserted events section.') logging.info('Inserted events section.')
output += '\n\n'
# Generate requests MD # Generate requests MD
output += read_file('partials/requestsHeader.md') output += read_file('partials/requestsHeader.md')
output += '\n'
output += get_requests_toc(protocol['requests']) output += get_requests_toc(protocol['requests'])
output += '\n\n' output += '\n'
output += get_requests(protocol['requests']) output += get_requests(protocol['requests'])
logging.info('Inserted requests section.') logging.info('Inserted requests section.')
output += '\n\n' if output.endswith('\n\n'):
output = output[:-1]
# Write new protocol MD # Write new protocol MD
with open('../generated/protocol.md', 'w') as f: with open('../generated/protocol.md', 'w') as f:

View File

@ -1,4 +1,5 @@
# Enums # Enums
These are enumeration declarations, which are referenced throughout obs-websocket's protocol. These are enumeration declarations, which are referenced throughout obs-websocket's protocol.
### Enumerations Table of Contents ## Enumerations Table of Contents

View File

@ -1,3 +1,3 @@
# Events # Events
### Events Table of Contents ## Events Table of Contents

View File

@ -1,28 +1,31 @@
# Main Table of Contents
- [obs-websocket 5.0.0 Protocol](#obs-websocket-500-protocol) # obs-websocket 5.0.1 Protocol
## Main Table of Contents
- [General Intro](#general-intro)
- [Design Goals](#design-goals)
- [Connecting to obs-websocket](#connecting-to-obs-websocket) - [Connecting to obs-websocket](#connecting-to-obs-websocket)
- [Connection steps](#connection-steps) - [Connection steps](#connection-steps)
- [Connection Notes](#connection-notes)
- [Creating an authentication string](#creating-an-authentication-string) - [Creating an authentication string](#creating-an-authentication-string)
- [Base message types](#message-types) - [Message Types (OpCodes)](#message-types-opcodes)
- [OpCode 0 Hello](#hello-opcode-0) - [Hello (OpCode 0)](#hello-opcode-0)
- [OpCode 1 Identify](#identify-opcode-1) - [Identify (OpCode 1)](#identify-opcode-1)
- [OpCode 2 Identified](#identified-opcode-2) - [Identified (OpCode 2)](#identified-opcode-2)
- [OpCode 3 Reidentify](#reidentify-opcode-3) - [Reidentify (OpCode 3)](#reidentify-opcode-3)
- [OpCode 5 Event](#event-opcode-5) - [Event (OpCode 5)](#event-opcode-5)
- [OpCode 6 Request](#request-opcode-6) - [Request (OpCode 6)](#request-opcode-6)
- [OpCode 7 RequestResponse](#requestresponse-opcode-7) - [RequestResponse (OpCode 7)](#requestresponse-opcode-7)
- [OpCode 8 RequestBatch](#requestbatch-opcode-8) - [RequestBatch (OpCode 8)](#requestbatch-opcode-8)
- [OpCode 9 RequestBatchResponse](#requestbatchresponse-opcode-9) - [RequestBatchResponse (OpCode 9)](#requestbatchresponse-opcode-9)
- [Enums](#enums)
- [Events](#events)
- [Requests](#requests)
# obs-websocket 5.0.0 Protocol
## General Intro ## General Intro
obs-websocket provides a feature-rich RPC communication protocol, giving access to much of OBS's feature set. This document contains everything you should know in order to make a connection and use obs-websocket's functionality to the fullest. obs-websocket provides a feature-rich RPC communication protocol, giving access to much of OBS's feature set. This document contains everything you should know in order to make a connection and use obs-websocket's functionality to the fullest.
### Design Goals ### Design Goals
- Abstraction of identification, events, requests, and batch requests into dedicated message types - Abstraction of identification, events, requests, and batch requests into dedicated message types
- Conformity of request naming using similar terms like `Get`, `Set`, `Get[x]List`, `Start[x]`, `Toggle[x]` - Conformity of request naming using similar terms like `Get`, `Set`, `Get[x]List`, `Start[x]`, `Toggle[x]`
- Conformity of OBS data field names like `sourceName`, `sourceKind`, `sourceType`, `sceneName`, `sceneItemName` - Conformity of OBS data field names like `sourceName`, `sourceKind`, `sourceType`, `sceneName`, `sceneItemName`
@ -31,13 +34,14 @@ obs-websocket provides a feature-rich RPC communication protocol, giving access
- PubSub system - Allow clients to specify which events they do or don't want to receive from OBS - PubSub system - Allow clients to specify which events they do or don't want to receive from OBS
- RPC versioning - Client and server negotiate the latest version of the obs-websocket protocol to communicate with. - RPC versioning - Client and server negotiate the latest version of the obs-websocket protocol to communicate with.
## Connecting to obs-websocket ## Connecting to obs-websocket
Here's info on how to connect to obs-websocket Here's info on how to connect to obs-websocket
--- ---
### Connection steps ### Connection steps
These steps should be followed precisely. Failure to connect to the server as instructed will likely result in your client being treated in an undefined way. These steps should be followed precisely. Failure to connect to the server as instructed will likely result in your client being treated in an undefined way.
- Initial HTTP request made to the obs-websocket server. - Initial HTTP request made to the obs-websocket server.
@ -64,6 +68,7 @@ These steps should be followed precisely. Failure to connect to the server as in
- At any time after a client has been identified, it may send an [OpCode 3 `Reidentify`](#reidentify-opcode-3) message to update certain allowed session parameters. The server will respond in the same way it does during initial identification. - At any time after a client has been identified, it may send an [OpCode 3 `Reidentify`](#reidentify-opcode-3) message to update certain allowed session parameters. The server will respond in the same way it does during initial identification.
#### Connection Notes #### Connection Notes
- If a binary frame is received when using the `obswebsocket.json` (default) subprotocol, or a text frame is received while using the `obswebsocket.msgpack` subprotocol, the connection is closed with `WebSocketCloseCode::MessageDecodeError`. - If a binary frame is received when using the `obswebsocket.json` (default) subprotocol, or a text frame is received while using the `obswebsocket.msgpack` subprotocol, the connection is closed with `WebSocketCloseCode::MessageDecodeError`.
- The obs-websocket server listens for any messages containing a `request-type` field in the first level JSON from unidentified clients. If a message matches, the connection is closed with `WebSocketCloseCode::UnsupportedRpcVersion` and a warning is logged. - The obs-websocket server listens for any messages containing a `request-type` field in the first level JSON from unidentified clients. If a message matches, the connection is closed with `WebSocketCloseCode::UnsupportedRpcVersion` and a warning is logged.
- If a message with a `messageType` is not recognized to the obs-websocket server, the connection is closed with `WebSocketCloseCode::UnknownOpCode`. - If a message with a `messageType` is not recognized to the obs-websocket server, the connection is closed with `WebSocketCloseCode::UnknownOpCode`.
@ -72,11 +77,13 @@ These steps should be followed precisely. Failure to connect to the server as in
--- ---
### Creating an authentication string ### Creating an authentication string
obs-websocket uses SHA256 to transmit authentication credentials. The server starts by sending an object in the `authentication` field of its `Hello` message data. The client processes the authentication challenge and responds via the `authentication` string in the `Identify` message data. obs-websocket uses SHA256 to transmit authentication credentials. The server starts by sending an object in the `authentication` field of its `Hello` message data. The client processes the authentication challenge and responds via the `authentication` string in the `Identify` message data.
For this guide, we'll be using `supersecretpassword` as the password. For this guide, we'll be using `supersecretpassword` as the password.
The `authentication` object in `Hello` looks like this (example): The `authentication` object in `Hello` looks like this (example):
```json ```json
{ {
"challenge": "+IxH4CnCiqpX1rM9scsNynZzbOe4KhDeYcTNS3PDaeY=", "challenge": "+IxH4CnCiqpX1rM9scsNynZzbOe4KhDeYcTNS3PDaeY=",
@ -85,6 +92,7 @@ The `authentication` object in `Hello` looks like this (example):
``` ```
To generate the authentication string, follow these steps: To generate the authentication string, follow these steps:
- Concatenate the websocket password with the `salt` provided by the server (`password + salt`) - Concatenate the websocket password with the `salt` provided by the server (`password + salt`)
- Generate an SHA256 binary hash of the result and base64 encode it, known as a base64 secret. - Generate an SHA256 binary hash of the result and base64 encode it, known as a base64 secret.
- Concatenate the base64 secret with the `challenge` sent by the server (`base64_secret + challenge`) - Concatenate the base64 secret with the `challenge` sent by the server (`base64_secret + challenge`)
@ -92,44 +100,50 @@ To generate the authentication string, follow these steps:
For real-world examples of the `authentication` string creation, refer to the obs-websocket client libraries listed on the [README](README.md). For real-world examples of the `authentication` string creation, refer to the obs-websocket client libraries listed on the [README](README.md).
## Message Types (OpCodes) ## Message Types (OpCodes)
The following message types are the low-level message types which may be sent to and from obs-websocket. The following message types are the low-level message types which may be sent to and from obs-websocket.
Messages sent from the obs-websocket server or client may contain these first-level fields, known as the base object: Messages sent from the obs-websocket server or client may contain these first-level fields, known as the base object:
```
```txt
{ {
"op": number, "op": number,
"d": object "d": object
} }
``` ```
- `op` is a `WebSocketOpCode` OpCode. - `op` is a `WebSocketOpCode` OpCode.
- `d` is an object of the data fields associated with the operation. - `d` is an object of the data fields associated with the operation.
--- ---
### Hello (OpCode 0) ### Hello (OpCode 0)
- Sent from: obs-websocket - Sent from: obs-websocket
- Sent to: Freshly connected websocket client - Sent to: Freshly connected websocket client
- Description: First message sent from the server immediately on client connection. Contains authentication information if auth is required. Also contains RPC version for version negotiation. - Description: First message sent from the server immediately on client connection. Contains authentication information if auth is required. Also contains RPC version for version negotiation.
**Data Keys:** **Data Keys:**
```
```txt
{ {
"obsWebSocketVersion": string, "obsWebSocketVersion": string,
"rpcVersion": number, "rpcVersion": number,
"authentication": object(optional) "authentication": object(optional)
} }
``` ```
- `rpcVersion` is a version number which gets incremented on each **breaking change** to the obs-websocket protocol. Its usage in this context is to provide the current rpc version that the server would like to use. - `rpcVersion` is a version number which gets incremented on each **breaking change** to the obs-websocket protocol. Its usage in this context is to provide the current rpc version that the server would like to use.
**Example Messages:** **Example Messages:**
Authentication is required Authentication is required
```json ```json
{ {
"op": 0, "op": 0,
"d": { "d": {
"obsWebSocketVersion": "5.0.0", "obsWebSocketVersion": "5.0.1",
"rpcVersion": 1, "rpcVersion": 1,
"authentication": { "authentication": {
"challenge": "+IxH4CnCiqpX1rM9scsNynZzbOe4KhDeYcTNS3PDaeY=", "challenge": "+IxH4CnCiqpX1rM9scsNynZzbOe4KhDeYcTNS3PDaeY=",
@ -140,11 +154,12 @@ Authentication is required
``` ```
Authentication is not required Authentication is not required
```json ```json
{ {
"op": 0, "op": 0,
"d": { "d": {
"obsWebSocketVersion": "5.0.0", "obsWebSocketVersion": "5.0.1",
"rpcVersion": 1 "rpcVersion": 1
} }
} }
@ -153,22 +168,26 @@ Authentication is not required
--- ---
### Identify (OpCode 1) ### Identify (OpCode 1)
- Sent from: Freshly connected websocket client - Sent from: Freshly connected websocket client
- Sent to: obs-websocket - Sent to: obs-websocket
- Description: Response to `Hello` message, should contain authentication string if authentication is required, along with PubSub subscriptions and other session parameters. - Description: Response to `Hello` message, should contain authentication string if authentication is required, along with PubSub subscriptions and other session parameters.
**Data Keys:** **Data Keys:**
```
```txt
{ {
"rpcVersion": number, "rpcVersion": number,
"authentication": string(optional), "authentication": string(optional),
"eventSubscriptions": number(optional) = (EventSubscription::All) "eventSubscriptions": number(optional) = (EventSubscription::All)
} }
``` ```
- `rpcVersion` is the version number that the client would like the obs-websocket server to use. - `rpcVersion` is the version number that the client would like the obs-websocket server to use.
- `eventSubscriptions` is a bitmask of `EventSubscriptions` items to subscribe to events and event categories at will. By default, all event categories are subscribed, except for events marked as high volume. High volume events must be explicitly subscribed to. - `eventSubscriptions` is a bitmask of `EventSubscriptions` items to subscribe to events and event categories at will. By default, all event categories are subscribed, except for events marked as high volume. High volume events must be explicitly subscribed to.
**Example Message:** **Example Message:**
```json ```json
{ {
"op": 1, "op": 1,
@ -183,19 +202,23 @@ Authentication is not required
--- ---
### Identified (OpCode 2) ### Identified (OpCode 2)
- Sent from: obs-websocket - Sent from: obs-websocket
- Sent to: Freshly identified client - Sent to: Freshly identified client
- Description: The identify request was received and validated, and the connection is now ready for normal operation. - Description: The identify request was received and validated, and the connection is now ready for normal operation.
**Data Keys:** **Data Keys:**
```
```txt
{ {
"negotiatedRpcVersion": number "negotiatedRpcVersion": number
} }
``` ```
- If rpc version negotiation succeeds, the server determines the RPC version to be used and gives it to the client as `negotiatedRpcVersion` - If rpc version negotiation succeeds, the server determines the RPC version to be used and gives it to the client as `negotiatedRpcVersion`
**Example Message:** **Example Message:**
```json ```json
{ {
"op": 2, "op": 2,
@ -208,36 +231,43 @@ Authentication is not required
--- ---
### Reidentify (OpCode 3) ### Reidentify (OpCode 3)
- Sent from: Identified client - Sent from: Identified client
- Sent to: obs-websocket - Sent to: obs-websocket
- Description: Sent at any time after initial identification to update the provided session parameters. - Description: Sent at any time after initial identification to update the provided session parameters.
**Data Keys:** **Data Keys:**
```
```txt
{ {
"eventSubscriptions": number(optional) = (EventSubscription::All) "eventSubscriptions": number(optional) = (EventSubscription::All)
} }
``` ```
- Only the listed parameters may be changed after initial identification. To change a parameter not listed, you must reconnect to the obs-websocket server. - Only the listed parameters may be changed after initial identification. To change a parameter not listed, you must reconnect to the obs-websocket server.
--- ---
### Event (OpCode 5) ### Event (OpCode 5)
- Sent from: obs-websocket - Sent from: obs-websocket
- Sent to: All subscribed and identified clients - Sent to: All subscribed and identified clients
- Description: An event coming from OBS has occured. Eg scene switched, source muted. - Description: An event coming from OBS has occured. Eg scene switched, source muted.
**Data Keys:** **Data Keys:**
```
```txt
{ {
"eventType": string, "eventType": string,
"eventIntent": number, "eventIntent": number,
"eventData": object(optional) "eventData": object(optional)
} }
``` ```
- `eventIntent` is the original intent required to be subscribed to in order to receive the event. - `eventIntent` is the original intent required to be subscribed to in order to receive the event.
**Example Message:** **Example Message:**
```json ```json
{ {
"op": 5, "op": 5,
@ -254,12 +284,14 @@ Authentication is not required
--- ---
### Request (OpCode 6) ### Request (OpCode 6)
- Sent from: Identified client - Sent from: Identified client
- Sent to: obs-websocket - Sent to: obs-websocket
- Description: Client is making a request to obs-websocket. Eg get current scene, create source. - Description: Client is making a request to obs-websocket. Eg get current scene, create source.
**Data Keys:** **Data Keys:**
```
```txt
{ {
"requestType": string, "requestType": string,
"requestId": string, "requestId": string,
@ -269,6 +301,7 @@ Authentication is not required
``` ```
**Example Message:** **Example Message:**
```json ```json
{ {
"op": 6, "op": 6,
@ -285,12 +318,14 @@ Authentication is not required
--- ---
### RequestResponse (OpCode 7) ### RequestResponse (OpCode 7)
- Sent from: obs-websocket - Sent from: obs-websocket
- Sent to: Identified client which made the request - Sent to: Identified client which made the request
- Description: obs-websocket is responding to a request coming from a client. - Description: obs-websocket is responding to a request coming from a client.
**Data Keys:** **Data Keys:**
```
```txt
{ {
"requestType": string, "requestType": string,
"requestId": string, "requestId": string,
@ -298,22 +333,26 @@ Authentication is not required
"responseData": object(optional) "responseData": object(optional)
} }
``` ```
- The `requestType` and `requestId` are simply mirrors of what was sent by the client. - The `requestType` and `requestId` are simply mirrors of what was sent by the client.
`requestStatus` object: `requestStatus` object:
```
```txt
{ {
"result": bool, "result": bool,
"code": number, "code": number,
"comment": string(optional) "comment": string(optional)
} }
``` ```
- `result` is `true` if the request resulted in `RequestStatus::Success`. False if otherwise. - `result` is `true` if the request resulted in `RequestStatus::Success`. False if otherwise.
- `code` is a `RequestStatus` code. - `code` is a `RequestStatus` code.
- `comment` may be provided by the server on errors to offer further details on why a request failed. - `comment` may be provided by the server on errors to offer further details on why a request failed.
**Example Messages:** **Example Messages:**
Successful Response Successful Response
```json ```json
{ {
"op": 7, "op": 7,
@ -329,6 +368,7 @@ Successful Response
``` ```
Failure Response Failure Response
```json ```json
{ {
"op": 7, "op": 7,
@ -347,12 +387,14 @@ Failure Response
--- ---
### RequestBatch (OpCode 8) ### RequestBatch (OpCode 8)
- Sent from: Identified client - Sent from: Identified client
- Sent to: obs-websocket - Sent to: obs-websocket
- Description: Client is making a batch of requests for obs-websocket. Requests are processed serially (in order) by the server. - Description: Client is making a batch of requests for obs-websocket. Requests are processed serially (in order) by the server.
**Data Keys:** **Data Keys:**
```
```txt
{ {
"requestId": string, "requestId": string,
"haltOnFailure": bool(optional) = false, "haltOnFailure": bool(optional) = false,
@ -360,18 +402,21 @@ Failure Response
"requests": array<object> "requests": array<object>
} }
``` ```
- When `haltOnFailure` is `true`, the processing of requests will be halted on first failure. Returns only the processed requests in [`RequestBatchResponse`](#requestbatchresponse-opcode-9). - When `haltOnFailure` is `true`, the processing of requests will be halted on first failure. Returns only the processed requests in [`RequestBatchResponse`](#requestbatchresponse-opcode-9).
- Requests in the `requests` array follow the same structure as the `Request` payload data format, however `requestId` is an optional field. - Requests in the `requests` array follow the same structure as the `Request` payload data format, however `requestId` is an optional field.
--- ---
### RequestBatchResponse (OpCode 9) ### RequestBatchResponse (OpCode 9)
- Sent from: obs-websocket - Sent from: obs-websocket
- Sent to: Identified client which made the request - Sent to: Identified client which made the request
- Description: obs-websocket is responding to a request batch coming from the client. - Description: obs-websocket is responding to a request batch coming from the client.
**Data Keys:** **Data Keys:**
```
```txt
{ {
"requestId": string, "requestId": string,
"results": array<object> "results": array<object>

View File

@ -1,3 +1,3 @@
# Requests # Requests
### Requests Table of Contents ## Requests Table of Contents

View File

@ -1443,6 +1443,42 @@
], ],
"responseFields": [] "responseFields": []
}, },
{
"description": "Sets the enable state of a source filter.",
"requestType": "SetSourceFilterEnabled",
"complexity": 3,
"rpcVersion": "1",
"deprecated": false,
"initialVersion": "5.0.0",
"category": "filters",
"requestFields": [
{
"valueName": "sourceName",
"valueType": "String",
"valueDescription": "Name of the source the filter is on",
"valueRestrictions": null,
"valueOptional": false,
"valueOptionalBehavior": null
},
{
"valueName": "filterName",
"valueType": "String",
"valueDescription": "Name of the filter",
"valueRestrictions": null,
"valueOptional": false,
"valueOptionalBehavior": null
},
{
"valueName": "filterEnabled",
"valueType": "Boolean",
"valueDescription": "New enable state of the filter",
"valueRestrictions": null,
"valueOptional": false,
"valueOptionalBehavior": null
}
],
"responseFields": []
},
{ {
"description": "Gets data about the current plugin and RPC version.", "description": "Gets data about the current plugin and RPC version.",
"requestType": "GetVersion", "requestType": "GetVersion",
@ -1477,6 +1513,16 @@
"valueName": "supportedImageFormats", "valueName": "supportedImageFormats",
"valueType": "Array<String>", "valueType": "Array<String>",
"valueDescription": "Image formats available in `GetSourceScreenshot` and `SaveSourceScreenshot` requests." "valueDescription": "Image formats available in `GetSourceScreenshot` and `SaveSourceScreenshot` requests."
},
{
"valueName": "platform",
"valueType": "String",
"valueDescription": "Name of the platform. Usually `windows`, `macos`, or `ubuntu` (linux flavor). Not guaranteed to be any of those"
},
{
"valueName": "platformDescription",
"valueType": "String",
"valueDescription": "Description of the platform, like `Windows 10 (10.0)`"
} }
] ]
}, },
@ -2283,7 +2329,7 @@
"responseFields": [] "responseFields": []
}, },
{ {
"description": "Gets the audio monitor type of an input.\n\nThe available audio monitor types are:\n- `OBS_MONITORING_TYPE_NONE`\n- `OBS_MONITORING_TYPE_MONITOR_ONLY`\n- `OBS_MONITORING_TYPE_MONITOR_AND_OUTPUT`", "description": "Gets the audio monitor type of an input.\n\nThe available audio monitor types are:\n\n- `OBS_MONITORING_TYPE_NONE`\n- `OBS_MONITORING_TYPE_MONITOR_ONLY`\n- `OBS_MONITORING_TYPE_MONITOR_AND_OUTPUT`",
"requestType": "GetInputAudioMonitorType", "requestType": "GetInputAudioMonitorType",
"complexity": 2, "complexity": 2,
"rpcVersion": "1", "rpcVersion": "1",
@ -2453,7 +2499,7 @@
"responseFields": [] "responseFields": []
}, },
{ {
"description": "Gets the status of a media input.\n\nMedia States:\n- `OBS_MEDIA_STATE_NONE`\n- `OBS_MEDIA_STATE_PLAYING`\n- `OBS_MEDIA_STATE_OPENING`\n- `OBS_MEDIA_STATE_BUFFERING`\n- `OBS_MEDIA_STATE_PAUSED`\n- `OBS_MEDIA_STATE_STOPPED`\n- `OBS_MEDIA_STATE_ENDED`\n- `OBS_MEDIA_STATE_ERROR`", "description": "Gets the status of a media input.\n\nMedia States:\n\n- `OBS_MEDIA_STATE_NONE`\n- `OBS_MEDIA_STATE_PLAYING`\n- `OBS_MEDIA_STATE_OPENING`\n- `OBS_MEDIA_STATE_BUFFERING`\n- `OBS_MEDIA_STATE_PAUSED`\n- `OBS_MEDIA_STATE_STOPPED`\n- `OBS_MEDIA_STATE_ENDED`\n- `OBS_MEDIA_STATE_ERROR`",
"requestType": "GetMediaInputStatus", "requestType": "GetMediaInputStatus",
"complexity": 2, "complexity": 2,
"rpcVersion": "1", "rpcVersion": "1",
@ -2891,6 +2937,14 @@
"valueRestrictions": null, "valueRestrictions": null,
"valueOptional": false, "valueOptional": false,
"valueOptionalBehavior": null "valueOptionalBehavior": null
},
{
"valueName": "searchOffset",
"valueType": "Number",
"valueDescription": "Number of matches to skip during search. >= 0 means first forward. -1 means last (top) item",
"valueRestrictions": ">= -1",
"valueOptional": true,
"valueOptionalBehavior": "0"
} }
], ],
"responseFields": [ "responseFields": [
@ -4183,6 +4237,23 @@
} }
], ],
"responseFields": [] "responseFields": []
},
{
"description": "Gets a list of connected monitors and information about them.",
"requestType": "GetMonitorList",
"complexity": 2,
"rpcVersion": "1",
"deprecated": false,
"initialVersion": "5.0.0",
"category": "ui",
"requestFields": [],
"responseFields": [
{
"valueName": "monitors",
"valueType": "Array<Object>",
"valueDescription": "a list of detected monitors with some information"
}
]
} }
], ],
"events": [ "events": [
@ -4675,7 +4746,7 @@
] ]
}, },
{ {
"description": "The monitor type of an input has changed.\n\nAvailable types are:\n- `OBS_MONITORING_TYPE_NONE`\n- `OBS_MONITORING_TYPE_MONITOR_ONLY`\n- `OBS_MONITORING_TYPE_MONITOR_AND_OUTPUT`", "description": "The monitor type of an input has changed.\n\nAvailable types are:\n\n- `OBS_MONITORING_TYPE_NONE`\n- `OBS_MONITORING_TYPE_MONITOR_ONLY`\n- `OBS_MONITORING_TYPE_MONITOR_AND_OUTPUT`",
"eventType": "InputAudioMonitorTypeChanged", "eventType": "InputAudioMonitorTypeChanged",
"eventSubscription": "Inputs", "eventSubscription": "Inputs",
"complexity": 2, "complexity": 2,

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
#define MyAppName "obs-websocket" #define MyAppName "obs-websocket"
#define MyAppVersion "@OBS_WEBSOCKET_VERSION@" #define MyAppVersion "@OBS_WEBSOCKET_VERSION@"
#define MyAppPublisher "obs-websocket" #define MyAppPublisher "OBS Project"
#define MyAppURL "http://github.com/obsproject/obs-websocket" #define MyAppURL "http://github.com/obsproject/obs-websocket"
[Setup] [Setup]

View File

@ -1,3 +1,24 @@
/*
obs-websocket
Copyright (C) 2020-2021 Kyle Manning <tt2468@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program. If not, see <https://www.gnu.org/licenses/>
*/
// Similar example code can be found in ../../src/obs-websocket.cpp
// You can test that sample code by specifying -DPLUGIN_TESTS=TRUE
#include <obs-module.h> #include <obs-module.h>
#include "../obs-websocket-api.h" #include "../obs-websocket-api.h"
@ -24,6 +45,24 @@ void obs_module_post_load(void)
if (!obs_websocket_vendor_register_request(vendor, "example_request", example_request_cb, NULL)) if (!obs_websocket_vendor_register_request(vendor, "example_request", example_request_cb, NULL))
blog(LOG_ERROR, "Failed to register `example_request` request with obs-websocket."); blog(LOG_ERROR, "Failed to register `example_request` request with obs-websocket.");
uint api_version = obs_websocket_get_api_version();
if (api_version == 0) {
blog(LOG_ERROR, "Unable to fetch obs-websocket plugin API version.");
return;
} else if (api_version == 1) {
blog(LOG_WARNING, "Unsupported obs-websocket plugin API version for calling requests.");
return;
}
struct obs_websocket_request_response *response = obs_websocket_call_request("GetVersion");
if (!response) {
blog(LOG_ERROR, "Failed to call GetVersion due to obs-websocket not being installed.");
return;
}
blog(LOG_INFO, "[obs_module_post_load] Called GetVersion. Status Code: %u | Comment: %s | Response Data: %s",
response->status_code, response->comment, response->response_data);
obs_websocket_request_response_free(response);
} }
void obs_module_unload(void) void obs_module_unload(void)

View File

@ -1,7 +1,7 @@
/* /*
obs-websocket obs-websocket
Copyright (C) 2016-2021 Stephane Lepin <stephane.lepin@gmail.com> Copyright (C) 2016-2021 Stephane Lepin <stephane.lepin@gmail.com>
Copyright (C) 2020-2021 Kyle Manning <tt2468@gmail.com> Copyright (C) 2020-2022 Kyle Manning <tt2468@gmail.com>
This program is free software; you can redistribute it and/or modify This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
@ -22,7 +22,7 @@ with this program. If not, see <https://www.gnu.org/licenses/>
#include <obs.h> #include <obs.h>
#define OBS_WEBSOCKET_API_VERSION 1 #define OBS_WEBSOCKET_API_VERSION 2
#ifdef __cplusplus #ifdef __cplusplus
extern "C" { extern "C" {
@ -31,12 +31,22 @@ extern "C" {
typedef void *obs_websocket_vendor; typedef void *obs_websocket_vendor;
typedef void (*obs_websocket_request_callback_function)(obs_data_t *, obs_data_t *, void *); typedef void (*obs_websocket_request_callback_function)(obs_data_t *, obs_data_t *, void *);
struct obs_websocket_request_response {
unsigned int status_code;
char *comment;
char *response_data; // JSON string, because obs_data_t* only supports array<object>, so conversions would break API.
};
/* ==================== INTERNAL DEFINITIONS ==================== */
struct obs_websocket_request_callback { struct obs_websocket_request_callback {
obs_websocket_request_callback_function callback; obs_websocket_request_callback_function callback;
void *priv_data; void *priv_data;
}; };
inline proc_handler_t *ph; inline proc_handler_t *_ph;
/* ==================== INTERNAL API FUNCTIONS ==================== */
static inline proc_handler_t *obs_websocket_get_ph(void) static inline proc_handler_t *obs_websocket_get_ph(void)
{ {
@ -52,30 +62,98 @@ static inline proc_handler_t *obs_websocket_get_ph(void)
return ret; return ret;
} }
static inline bool obs_websocket_run_simple_proc(obs_websocket_vendor vendor, const char *proc_name, calldata_t *cd) static inline bool obs_websocket_ensure_ph(void)
{ {
if (!ph || !vendor || !proc_name || !strlen(proc_name) || !cd) if (!_ph)
_ph = obs_websocket_get_ph();
return _ph != NULL;
}
static inline bool obs_websocket_vendor_run_simple_proc(obs_websocket_vendor vendor, const char *proc_name, calldata_t *cd)
{
if (!obs_websocket_ensure_ph())
return false;
if (!vendor || !proc_name || !strlen(proc_name) || !cd)
return false; return false;
calldata_set_ptr(cd, "vendor", vendor); calldata_set_ptr(cd, "vendor", vendor);
proc_handler_call(ph, proc_name, cd); proc_handler_call(_ph, proc_name, cd);
return calldata_bool(cd, "success"); return calldata_bool(cd, "success");
} }
// ALWAYS CALL VIA `obs_module_post_load()` CALLBACK! /* ==================== GENERAL API FUNCTIONS ==================== */
// Gets the API version built with the obs-websocket plugin
static inline unsigned int obs_websocket_get_api_version(void)
{
if (!obs_websocket_ensure_ph())
return 0;
calldata_t cd = {0};
if (!proc_handler_call(_ph, "get_api_version", &cd))
return 1; // API v1 does not include get_api_version
unsigned int ret = calldata_int(&cd, "version");
calldata_free(&cd);
return ret;
}
// Calls an obs-websocket request. Free response with `obs_websocket_request_response_free()`
static inline obs_websocket_request_response *obs_websocket_call_request(const char *request_type, obs_data_t *request_data = NULL)
{
if (!obs_websocket_ensure_ph())
return NULL;
const char *request_data_string = NULL;
if (request_data)
request_data_string = obs_data_get_json(request_data);
calldata_t cd = {0};
calldata_set_string(&cd, "request_type", request_type);
calldata_set_string(&cd, "request_data", request_data_string);
proc_handler_call(_ph, "call_request", &cd);
auto ret = (struct obs_websocket_request_response *)calldata_ptr(&cd, "response");
calldata_free(&cd);
return ret;
}
// Free a request response object returned by `obs_websocket_call_request()`
static inline void obs_websocket_request_response_free(struct obs_websocket_request_response *response)
{
if (!response)
return;
if (response->comment)
bfree(response->comment);
if (response->response_data)
bfree(response->response_data);
bfree(response);
}
/* ==================== VENDOR API FUNCTIONS ==================== */
// ALWAYS CALL ONLY VIA `obs_module_post_load()` CALLBACK!
// Registers a new "vendor" (Example: obs-ndi) // Registers a new "vendor" (Example: obs-ndi)
static inline obs_websocket_vendor obs_websocket_register_vendor(const char *vendor_name) static inline obs_websocket_vendor obs_websocket_register_vendor(const char *vendor_name)
{ {
ph = obs_websocket_get_ph(); if (!obs_websocket_ensure_ph())
if (!ph)
return NULL; return NULL;
calldata_t cd = {0}; calldata_t cd = {0};
calldata_set_string(&cd, "name", vendor_name); calldata_set_string(&cd, "name", vendor_name);
proc_handler_call(ph, "vendor_register", &cd); proc_handler_call(_ph, "vendor_register", &cd);
obs_websocket_vendor ret = calldata_ptr(&cd, "vendor"); obs_websocket_vendor ret = calldata_ptr(&cd, "vendor");
calldata_free(&cd); calldata_free(&cd);
@ -83,7 +161,8 @@ static inline obs_websocket_vendor obs_websocket_register_vendor(const char *ven
} }
// Registers a new request for a vendor // Registers a new request for a vendor
static inline bool obs_websocket_vendor_register_request(obs_websocket_vendor vendor, const char *request_type, obs_websocket_request_callback_function request_callback, void* priv_data) static inline bool obs_websocket_vendor_register_request(obs_websocket_vendor vendor, const char *request_type,
obs_websocket_request_callback_function request_callback, void *priv_data)
{ {
calldata_t cd = {0}; calldata_t cd = {0};
@ -94,7 +173,7 @@ static inline bool obs_websocket_vendor_register_request(obs_websocket_vendor ve
calldata_set_string(&cd, "type", request_type); calldata_set_string(&cd, "type", request_type);
calldata_set_ptr(&cd, "callback", &cb); calldata_set_ptr(&cd, "callback", &cb);
bool success = obs_websocket_run_simple_proc(vendor, "vendor_request_register", &cd); bool success = obs_websocket_vendor_run_simple_proc(vendor, "vendor_request_register", &cd);
calldata_free(&cd); calldata_free(&cd);
return success; return success;
@ -107,7 +186,7 @@ static inline bool obs_websocket_vendor_unregister_request(obs_websocket_vendor
calldata_set_string(&cd, "type", request_type); calldata_set_string(&cd, "type", request_type);
bool success = obs_websocket_run_simple_proc(vendor, "vendor_request_unregister", &cd); bool success = obs_websocket_vendor_run_simple_proc(vendor, "vendor_request_unregister", &cd);
calldata_free(&cd); calldata_free(&cd);
return success; return success;
@ -122,12 +201,14 @@ static inline bool obs_websocket_vendor_emit_event(obs_websocket_vendor vendor,
calldata_set_string(&cd, "type", event_name); calldata_set_string(&cd, "type", event_name);
calldata_set_ptr(&cd, "data", (void *)event_data); calldata_set_ptr(&cd, "data", (void *)event_data);
bool success = obs_websocket_run_simple_proc(vendor, "vendor_event_emit", &cd); bool success = obs_websocket_vendor_run_simple_proc(vendor, "vendor_event_emit", &cd);
calldata_free(&cd); calldata_free(&cd);
return success; return success;
} }
/* ==================== END API FUNCTIONS ==================== */
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif

View File

@ -33,15 +33,17 @@ with this program. If not, see <https://www.gnu.org/licenses/>
#define PARAM_PASSWORD "ServerPassword" #define PARAM_PASSWORD "ServerPassword"
#define CMDLINE_WEBSOCKET_PORT "websocket_port" #define CMDLINE_WEBSOCKET_PORT "websocket_port"
#define CMDLINE_WEBSOCKET_IPV4_ONLY "websocket_ipv4_only"
#define CMDLINE_WEBSOCKET_PASSWORD "websocket_password" #define CMDLINE_WEBSOCKET_PASSWORD "websocket_password"
#define CMDLINE_WEBSOCKET_DEBUG "websocket_debug" #define CMDLINE_WEBSOCKET_DEBUG "websocket_debug"
Config::Config() : Config::Config()
PortOverridden(false), : PortOverridden(false),
PasswordOverridden(false), PasswordOverridden(false),
FirstLoad(true), FirstLoad(true),
ServerEnabled(true), ServerEnabled(true),
ServerPort(4455), ServerPort(4455),
Ipv4Only(false),
DebugEnabled(false), DebugEnabled(false),
AlertsEnabled(false), AlertsEnabled(false),
AuthRequired(true), AuthRequired(true),
@ -93,6 +95,12 @@ void Config::Load()
} }
} }
// Process `--websocket_ipv4_only` override
if (Utils::Platform::GetCommandLineFlagSet(CMDLINE_WEBSOCKET_IPV4_ONLY)) {
blog(LOG_INFO, "[Config::Load] --websocket_ipv4_only passed. Binding only to IPv4 interfaces.");
Ipv4Only = true;
}
// Process `--websocket_password` override // Process `--websocket_password` override
QString passwordArgument = Utils::Platform::GetCommandLineArgument(CMDLINE_WEBSOCKET_PASSWORD); QString passwordArgument = Utils::Platform::GetCommandLineArgument(CMDLINE_WEBSOCKET_PASSWORD);
if (passwordArgument != "") { if (passwordArgument != "") {

View File

@ -38,6 +38,7 @@ struct Config {
std::atomic<bool> FirstLoad; std::atomic<bool> FirstLoad;
std::atomic<bool> ServerEnabled; std::atomic<bool> ServerEnabled;
std::atomic<uint16_t> ServerPort; std::atomic<uint16_t> ServerPort;
std::atomic<bool> Ipv4Only;
std::atomic<bool> DebugEnabled; std::atomic<bool> DebugEnabled;
std::atomic<bool> AlertsEnabled; std::atomic<bool> AlertsEnabled;
std::atomic<bool> AuthRequired; std::atomic<bool> AuthRequired;

View File

@ -1,7 +1,13 @@
#include "WebSocketApi.h" #include "WebSocketApi.h"
#include "requesthandler/RequestHandler.h"
#include "obs-websocket.h" #include "obs-websocket.h"
#include "utils/Json.h"
#define RETURN_STATUS(status) { calldata_set_bool(cd, "success", status); return; } #define RETURN_STATUS(status) \
{ \
calldata_set_bool(cd, "success", status); \
return; \
}
#define RETURN_SUCCESS() RETURN_STATUS(true); #define RETURN_SUCCESS() RETURN_STATUS(true);
#define RETURN_FAILURE() RETURN_STATUS(false); #define RETURN_FAILURE() RETURN_STATUS(false);
@ -22,10 +28,16 @@ WebSocketApi::WebSocketApi()
_procHandler = proc_handler_create(); _procHandler = proc_handler_create();
proc_handler_add(_procHandler, "bool get_api_version(out int version)", &get_api_version, nullptr);
proc_handler_add(_procHandler, "bool call_request(in string request_type, in string request_data, out ptr response)",
&call_request, nullptr);
proc_handler_add(_procHandler, "bool vendor_register(in string name, out ptr vendor)", &vendor_register_cb, this); proc_handler_add(_procHandler, "bool vendor_register(in string name, out ptr vendor)", &vendor_register_cb, this);
proc_handler_add(_procHandler, "bool vendor_request_register(in ptr vendor, in string type, in ptr callback)", &vendor_request_register_cb, this); proc_handler_add(_procHandler, "bool vendor_request_register(in ptr vendor, in string type, in ptr callback)",
proc_handler_add(_procHandler, "bool vendor_request_unregister(in ptr vendor, in string type)", &vendor_request_unregister_cb, this); &vendor_request_register_cb, this);
proc_handler_add(_procHandler, "bool vendor_event_emit(in ptr vendor, in string type, in ptr data)", &vendor_event_emit_cb, this); proc_handler_add(_procHandler, "bool vendor_request_unregister(in ptr vendor, in string type)",
&vendor_request_unregister_cb, this);
proc_handler_add(_procHandler, "bool vendor_event_emit(in ptr vendor, in string type, in ptr data)", &vendor_event_emit_cb,
this);
proc_handler_t *ph = obs_get_proc_handler(); proc_handler_t *ph = obs_get_proc_handler();
assert(ph != NULL); assert(ph != NULL);
@ -54,7 +66,8 @@ void WebSocketApi::SetEventCallback(EventCallback cb)
_eventCallback = cb; _eventCallback = cb;
} }
enum WebSocketApi::RequestReturnCode WebSocketApi::PerformVendorRequest(std::string vendorName, std::string requestType, obs_data_t *requestData, obs_data_t *responseData) enum WebSocketApi::RequestReturnCode WebSocketApi::PerformVendorRequest(std::string vendorName, std::string requestType,
obs_data_t *requestData, obs_data_t *responseData)
{ {
std::shared_lock l(_mutex); std::shared_lock l(_mutex);
@ -88,6 +101,49 @@ void WebSocketApi::get_ph_cb(void *priv_data, calldata_t *cd)
RETURN_SUCCESS(); RETURN_SUCCESS();
} }
void WebSocketApi::get_api_version(void *, calldata_t *cd)
{
calldata_set_int(cd, "version", OBS_WEBSOCKET_API_VERSION);
RETURN_SUCCESS();
}
void WebSocketApi::call_request(void *, calldata_t *cd)
{
const char *request_type = calldata_string(cd, "request_type");
const char *request_data = calldata_string(cd, "request_data");
if (!request_type)
RETURN_FAILURE();
auto response = static_cast<obs_websocket_request_response *>(bzalloc(sizeof(struct obs_websocket_request_response)));
if (!response)
RETURN_FAILURE();
json requestData;
if (request_data)
requestData = json::parse(request_data);
RequestHandler requestHandler;
Request request(request_type, requestData);
RequestResult requestResult = requestHandler.ProcessRequest(request);
response->status_code = (unsigned int)requestResult.StatusCode;
if (!requestResult.Comment.empty())
response->comment = bstrdup(requestResult.Comment.c_str());
if (requestResult.ResponseData.is_object()) {
std::string responseData = requestResult.ResponseData.dump();
response->response_data = bstrdup(responseData.c_str());
}
calldata_set_ptr(cd, "response", response);
blog_debug("[WebSocketApi::call_request] Request %s called, response status code is %u", request_type,
response->status_code);
RETURN_SUCCESS();
}
void WebSocketApi::vendor_register_cb(void *priv_data, calldata_t *cd) void WebSocketApi::vendor_register_cb(void *priv_data, calldata_t *cd)
{ {
auto c = static_cast<WebSocketApi *>(priv_data); auto c = static_cast<WebSocketApi *>(priv_data);
@ -102,7 +158,8 @@ void WebSocketApi::vendor_register_cb(void *priv_data, calldata_t *cd)
std::unique_lock l(c->_mutex); std::unique_lock l(c->_mutex);
if (c->_vendors.count(vendorName)) { if (c->_vendors.count(vendorName)) {
blog(LOG_WARNING, "[WebSocketApi::vendor_register_cb] Failed because `%s` is already a registered vendor.", vendorName); blog(LOG_WARNING, "[WebSocketApi::vendor_register_cb] Failed because `%s` is already a registered vendor.",
vendorName);
RETURN_FAILURE(); RETURN_FAILURE();
} }
@ -126,13 +183,17 @@ void WebSocketApi::vendor_request_register_cb(void *, calldata_t *cd)
const char *requestType; const char *requestType;
if (!calldata_get_string(cd, "type", &requestType) || strlen(requestType) == 0) { if (!calldata_get_string(cd, "type", &requestType) || strlen(requestType) == 0) {
blog(LOG_WARNING, "[WebSocketApi::vendor_request_register_cb] [vendorName: %s] Failed due to missing or empty `type` string.", v->_name.c_str()); blog(LOG_WARNING,
"[WebSocketApi::vendor_request_register_cb] [vendorName: %s] Failed due to missing or empty `type` string.",
v->_name.c_str());
RETURN_FAILURE(); RETURN_FAILURE();
} }
void *voidCallback; void *voidCallback;
if (!calldata_get_ptr(cd, "callback", &voidCallback) || !voidCallback) { if (!calldata_get_ptr(cd, "callback", &voidCallback) || !voidCallback) {
blog(LOG_WARNING, "[WebSocketApi::vendor_request_register_cb] [vendorName: %s] Failed due to missing `callback` pointer.", v->_name.c_str()); blog(LOG_WARNING,
"[WebSocketApi::vendor_request_register_cb] [vendorName: %s] Failed due to missing `callback` pointer.",
v->_name.c_str());
RETURN_FAILURE(); RETURN_FAILURE();
} }
@ -141,13 +202,16 @@ void WebSocketApi::vendor_request_register_cb(void *, calldata_t *cd)
std::unique_lock l(v->_mutex); std::unique_lock l(v->_mutex);
if (v->_requests.count(requestType)) { if (v->_requests.count(requestType)) {
blog(LOG_WARNING, "[WebSocketApi::vendor_request_register_cb] [vendorName: %s] Failed because `%s` is already a registered request.", v->_name.c_str(), requestType); blog(LOG_WARNING,
"[WebSocketApi::vendor_request_register_cb] [vendorName: %s] Failed because `%s` is already a registered request.",
v->_name.c_str(), requestType);
RETURN_FAILURE(); RETURN_FAILURE();
} }
v->_requests[requestType] = *cb; v->_requests[requestType] = *cb;
blog_debug("[WebSocketApi::vendor_request_register_cb] [vendorName: %s] Registered new vendor request: %s", v->_name.c_str(), requestType); blog_debug("[WebSocketApi::vendor_request_register_cb] [vendorName: %s] Registered new vendor request: %s",
v->_name.c_str(), requestType);
RETURN_SUCCESS(); RETURN_SUCCESS();
} }
@ -160,20 +224,25 @@ void WebSocketApi::vendor_request_unregister_cb(void *, calldata_t *cd)
const char *requestType; const char *requestType;
if (!calldata_get_string(cd, "type", &requestType) || strlen(requestType) == 0) { if (!calldata_get_string(cd, "type", &requestType) || strlen(requestType) == 0) {
blog(LOG_WARNING, "[WebSocketApi::vendor_request_unregister_cb] [vendorName: %s] Failed due to missing `type` string.", v->_name.c_str()); blog(LOG_WARNING,
"[WebSocketApi::vendor_request_unregister_cb] [vendorName: %s] Failed due to missing `type` string.",
v->_name.c_str());
RETURN_FAILURE(); RETURN_FAILURE();
} }
std::unique_lock l(v->_mutex); std::unique_lock l(v->_mutex);
if (!v->_requests.count(requestType)) { if (!v->_requests.count(requestType)) {
blog(LOG_WARNING, "[WebSocketApi::vendor_request_register_cb] [vendorName: %s] Failed because `%s` is not a registered request.", v->_name.c_str(), requestType); blog(LOG_WARNING,
"[WebSocketApi::vendor_request_register_cb] [vendorName: %s] Failed because `%s` is not a registered request.",
v->_name.c_str(), requestType);
RETURN_FAILURE(); RETURN_FAILURE();
} }
v->_requests.erase(requestType); v->_requests.erase(requestType);
blog_debug("[WebSocketApi::vendor_request_unregister_cb] [vendorName: %s] Unregistered vendor request: %s", v->_name.c_str(), requestType); blog_debug("[WebSocketApi::vendor_request_unregister_cb] [vendorName: %s] Unregistered vendor request: %s",
v->_name.c_str(), requestType);
RETURN_SUCCESS(); RETURN_SUCCESS();
} }
@ -188,13 +257,15 @@ void WebSocketApi::vendor_event_emit_cb(void *priv_data, calldata_t *cd)
const char *eventType; const char *eventType;
if (!calldata_get_string(cd, "type", &eventType) || strlen(eventType) == 0) { if (!calldata_get_string(cd, "type", &eventType) || strlen(eventType) == 0) {
blog(LOG_WARNING, "[WebSocketApi::vendor_event_emit_cb] [vendorName: %s] Failed due to missing `type` string.", v->_name.c_str()); blog(LOG_WARNING, "[WebSocketApi::vendor_event_emit_cb] [vendorName: %s] Failed due to missing `type` string.",
v->_name.c_str());
RETURN_FAILURE(); RETURN_FAILURE();
} }
void *voidEventData; void *voidEventData;
if (!calldata_get_ptr(cd, "data", &voidEventData)) { if (!calldata_get_ptr(cd, "data", &voidEventData)) {
blog(LOG_WARNING, "[WebSocketApi::vendor_event_emit_cb] [vendorName: %s] Failed due to missing `data` pointer.", v->_name.c_str()); blog(LOG_WARNING, "[WebSocketApi::vendor_event_emit_cb] [vendorName: %s] Failed due to missing `data` pointer.",
v->_name.c_str());
RETURN_FAILURE(); RETURN_FAILURE();
} }

View File

@ -30,9 +30,12 @@ class WebSocketApi {
void SetEventCallback(EventCallback cb); void SetEventCallback(EventCallback cb);
enum RequestReturnCode PerformVendorRequest(std::string vendorName, std::string requestName, obs_data_t *requestData, obs_data_t *responseData); enum RequestReturnCode PerformVendorRequest(std::string vendorName, std::string requestName, obs_data_t *requestData,
obs_data_t *responseData);
static void get_ph_cb(void *priv_data, calldata_t *cd); static void get_ph_cb(void *priv_data, calldata_t *cd);
static void get_api_version(void *, calldata_t *cd);
static void call_request(void *, calldata_t *cd);
static void vendor_register_cb(void *priv_data, calldata_t *cd); static void vendor_register_cb(void *priv_data, calldata_t *cd);
static void vendor_request_register_cb(void *priv_data, calldata_t *cd); static void vendor_request_register_cb(void *priv_data, calldata_t *cd);
static void vendor_request_unregister_cb(void *priv_data, calldata_t *cd); static void vendor_request_unregister_cb(void *priv_data, calldata_t *cd);

View File

@ -19,8 +19,8 @@ with this program. If not, see <https://www.gnu.org/licenses/>
#include "EventHandler.h" #include "EventHandler.h"
EventHandler::EventHandler() : EventHandler::EventHandler()
_obsLoaded(false), : _obsLoaded(false),
_inputVolumeMetersRef(0), _inputVolumeMetersRef(0),
_inputActiveStateChangedRef(0), _inputActiveStateChangedRef(0),
_inputShowStateChangedRef(0), _inputShowStateChangedRef(0),
@ -80,7 +80,8 @@ void EventHandler::ProcessSubscription(uint64_t eventSubscriptions)
if (_inputVolumeMetersHandler) if (_inputVolumeMetersHandler)
blog(LOG_WARNING, "[EventHandler::ProcessSubscription] Input volume meter handler already exists!"); blog(LOG_WARNING, "[EventHandler::ProcessSubscription] Input volume meter handler already exists!");
else else
_inputVolumeMetersHandler = std::make_unique<Utils::Obs::VolumeMeter::Handler>(std::bind(&EventHandler::HandleInputVolumeMeters, this, std::placeholders::_1)); _inputVolumeMetersHandler = std::make_unique<Utils::Obs::VolumeMeter::Handler>(
std::bind(&EventHandler::HandleInputVolumeMeters, this, std::placeholders::_1));
} }
} }
if ((eventSubscriptions & EventSubscription::InputActiveStateChanged) != 0) if ((eventSubscriptions & EventSubscription::InputActiveStateChanged) != 0)
@ -266,7 +267,8 @@ void EventHandler::OnFrontendEvent(enum obs_frontend_event event, void *private_
switch (event) { switch (event) {
// General // General
case OBS_FRONTEND_EVENT_FINISHED_LOADING: case OBS_FRONTEND_EVENT_FINISHED_LOADING:
blog_debug("[EventHandler::OnFrontendEvent] OBS has finished loading. Connecting final handlers and enabling events..."); blog_debug(
"[EventHandler::OnFrontendEvent] OBS has finished loading. Connecting final handlers and enabling events...");
// Connect source signals and enable events only after OBS has fully loaded (to reduce extra logging). // Connect source signals and enable events only after OBS has fully loaded (to reduce extra logging).
eventHandler->_obsLoaded.store(true); eventHandler->_obsLoaded.store(true);
@ -359,8 +361,7 @@ void EventHandler::OnFrontendEvent(enum obs_frontend_event event, void *private_
break; break;
// Config // Config
case OBS_FRONTEND_EVENT_SCENE_COLLECTION_CHANGING: case OBS_FRONTEND_EVENT_SCENE_COLLECTION_CHANGING: {
{
obs_frontend_source_list transitions = {}; obs_frontend_source_list transitions = {};
obs_frontend_get_transitions(&transitions); obs_frontend_get_transitions(&transitions);
for (size_t i = 0; i < transitions.sources.num; i++) { for (size_t i = 0; i < transitions.sources.num; i++) {
@ -371,8 +372,7 @@ void EventHandler::OnFrontendEvent(enum obs_frontend_event event, void *private_
} }
eventHandler->HandleCurrentSceneCollectionChanging(); eventHandler->HandleCurrentSceneCollectionChanging();
break; break;
case OBS_FRONTEND_EVENT_SCENE_COLLECTION_CHANGED: case OBS_FRONTEND_EVENT_SCENE_COLLECTION_CHANGED: {
{
obs_frontend_source_list transitions = {}; obs_frontend_source_list transitions = {};
obs_frontend_get_transitions(&transitions); obs_frontend_get_transitions(&transitions);
for (size_t i = 0; i < transitions.sources.num; i++) { for (size_t i = 0; i < transitions.sources.num; i++) {
@ -411,8 +411,7 @@ void EventHandler::OnFrontendEvent(enum obs_frontend_event event, void *private_
case OBS_FRONTEND_EVENT_TRANSITION_CHANGED: case OBS_FRONTEND_EVENT_TRANSITION_CHANGED:
eventHandler->HandleCurrentSceneTransitionChanged(); eventHandler->HandleCurrentSceneTransitionChanged();
break; break;
case OBS_FRONTEND_EVENT_TRANSITION_LIST_CHANGED: case OBS_FRONTEND_EVENT_TRANSITION_LIST_CHANGED: {
{
obs_frontend_source_list transitions = {}; obs_frontend_source_list transitions = {};
obs_frontend_get_transitions(&transitions); obs_frontend_get_transitions(&transitions);
for (size_t i = 0; i < transitions.sources.num; i++) { for (size_t i = 0; i < transitions.sources.num; i++) {
@ -420,8 +419,7 @@ void EventHandler::OnFrontendEvent(enum obs_frontend_event event, void *private_
eventHandler->ConnectSourceSignals(transition); eventHandler->ConnectSourceSignals(transition);
} }
obs_frontend_source_list_free(&transitions); obs_frontend_source_list_free(&transitions);
} } break;
break;
case OBS_FRONTEND_EVENT_TRANSITION_DURATION_CHANGED: case OBS_FRONTEND_EVENT_TRANSITION_DURATION_CHANGED:
eventHandler->HandleCurrentSceneTransitionDurationChanged(); eventHandler->HandleCurrentSceneTransitionDurationChanged();
break; break;
@ -511,7 +509,8 @@ void EventHandler::SourceCreatedMultiHandler(void *param, calldata_t *data)
} }
} }
// Only called for destruction of a public source // Only called for destruction of a public sourcs
// Used as a fallback if an input/scene is not explicitly removed
void EventHandler::SourceDestroyedMultiHandler(void *param, calldata_t *data) void EventHandler::SourceDestroyedMultiHandler(void *param, calldata_t *data)
{ {
auto eventHandler = static_cast<EventHandler *>(param); auto eventHandler = static_cast<EventHandler *>(param);
@ -530,16 +529,22 @@ void EventHandler::SourceDestroyedMultiHandler(void *param, calldata_t *data)
switch (obs_source_get_type(source)) { switch (obs_source_get_type(source)) {
case OBS_SOURCE_TYPE_INPUT: case OBS_SOURCE_TYPE_INPUT:
// We have to call `InputRemoved` with source_destroy because source_removed is not called when an input's last scene item is removed // Only emit removed if the input has not already been removed. This is the case when removing the last scene item of an input.
if (!obs_source_removed(source))
eventHandler->HandleInputRemoved(source); eventHandler->HandleInputRemoved(source);
break; break;
case OBS_SOURCE_TYPE_SCENE: case OBS_SOURCE_TYPE_SCENE:
// Only emit removed if the scene has not already been removed.
if (!obs_source_removed(source))
eventHandler->HandleSceneRemoved(source);
break; break;
default: default:
break; break;
} }
} }
// We prefer remove signals over destroy signals because they are more time-accurate.
// For example, if an input is "removed" but there is a dangling ref, you still want to know that it shouldn't exist, but it's not guaranteed to be destroyed.
void EventHandler::SourceRemovedMultiHandler(void *param, calldata_t *data) void EventHandler::SourceRemovedMultiHandler(void *param, calldata_t *data)
{ {
auto eventHandler = static_cast<EventHandler *>(param); auto eventHandler = static_cast<EventHandler *>(param);
@ -553,9 +558,9 @@ void EventHandler::SourceRemovedMultiHandler(void *param, calldata_t *data)
switch (obs_source_get_type(source)) { switch (obs_source_get_type(source)) {
case OBS_SOURCE_TYPE_INPUT: case OBS_SOURCE_TYPE_INPUT:
eventHandler->HandleInputRemoved(source);
break; break;
case OBS_SOURCE_TYPE_SCENE: case OBS_SOURCE_TYPE_SCENE:
// Scenes emit the `removed` signal when they are removed from OBS, as expected
eventHandler->HandleSceneRemoved(source); eventHandler->HandleSceneRemoved(source);
break; break;
default: default:

View File

@ -29,8 +29,7 @@ with this program. If not, see <https://www.gnu.org/licenses/>
#include "../utils/Obs_VolumeMeter.h" #include "../utils/Obs_VolumeMeter.h"
#include "../plugin-macros.generated.h" #include "../plugin-macros.generated.h"
class EventHandler class EventHandler {
{
public: public:
EventHandler(); EventHandler();
~EventHandler(); ~EventHandler();
@ -77,7 +76,6 @@ class EventHandler
static void SourceMediaNextMultiHandler(void *param, calldata_t *data); static void SourceMediaNextMultiHandler(void *param, calldata_t *data);
static void SourceMediaPreviousMultiHandler(void *param, calldata_t *data); static void SourceMediaPreviousMultiHandler(void *param, calldata_t *data);
// General // General
void HandleExitStarted(); void HandleExitStarted();
void HandleStudioModeStateChanged(bool enabled); void HandleStudioModeStateChanged(bool enabled);

View File

@ -344,6 +344,7 @@ void EventHandler::HandleInputAudioTracksChanged(void *param, calldata_t *data)
* The monitor type of an input has changed. * The monitor type of an input has changed.
* *
* Available types are: * Available types are:
*
* - `OBS_MONITORING_TYPE_NONE` * - `OBS_MONITORING_TYPE_NONE`
* - `OBS_MONITORING_TYPE_MONITOR_ONLY` * - `OBS_MONITORING_TYPE_MONITOR_ONLY`
* - `OBS_MONITORING_TYPE_MONITOR_AND_OUTPUT` * - `OBS_MONITORING_TYPE_MONITOR_AND_OUTPUT`
@ -372,11 +373,9 @@ void EventHandler::HandleInputAudioMonitorTypeChanged(void *param, calldata_t *d
enum obs_monitoring_type monitorType = (obs_monitoring_type)calldata_int(data, "type"); enum obs_monitoring_type monitorType = (obs_monitoring_type)calldata_int(data, "type");
std::string monitorTypeString = Utils::Obs::StringHelper::GetInputMonitorType(monitorType);
json eventData; json eventData;
eventData["inputName"] = obs_source_get_name(source); eventData["inputName"] = obs_source_get_name(source);
eventData["monitorType"] = monitorTypeString; eventData["monitorType"] = monitorType;
eventHandler->BroadcastEvent(EventSubscription::Inputs, "InputAudioMonitorTypeChanged", eventData); eventHandler->BroadcastEvent(EventSubscription::Inputs, "InputAudioMonitorTypeChanged", eventData);
} }

View File

@ -19,9 +19,12 @@ with this program. If not, see <https://www.gnu.org/licenses/>
#include "EventHandler.h" #include "EventHandler.h"
#define CASE(x) case x: return #x; #define CASE(x) \
case x: \
return #x;
std::string GetMediaInputActionString(ObsMediaInputAction action) { std::string GetMediaInputActionString(ObsMediaInputAction action)
{
switch (action) { switch (action) {
default: default:
CASE(OBS_WEBSOCKET_MEDIA_INPUT_ACTION_PAUSE) CASE(OBS_WEBSOCKET_MEDIA_INPUT_ACTION_PAUSE)

View File

@ -19,7 +19,8 @@ with this program. If not, see <https://www.gnu.org/licenses/>
#include "EventHandler.h" #include "EventHandler.h"
static bool GetOutputStateActive(ObsOutputState state) { static bool GetOutputStateActive(ObsOutputState state)
{
switch (state) { switch (state) {
case OBS_WEBSOCKET_OUTPUT_STARTED: case OBS_WEBSOCKET_OUTPUT_STARTED:
case OBS_WEBSOCKET_OUTPUT_RESUMED: case OBS_WEBSOCKET_OUTPUT_RESUMED:
@ -52,7 +53,7 @@ void EventHandler::HandleStreamStateChanged(ObsOutputState state)
{ {
json eventData; json eventData;
eventData["outputActive"] = GetOutputStateActive(state); eventData["outputActive"] = GetOutputStateActive(state);
eventData["outputState"] = Utils::Obs::StringHelper::GetOutputState(state); eventData["outputState"] = state;
BroadcastEvent(EventSubscription::Outputs, "StreamStateChanged", eventData); BroadcastEvent(EventSubscription::Outputs, "StreamStateChanged", eventData);
} }
@ -61,6 +62,7 @@ void EventHandler::HandleStreamStateChanged(ObsOutputState state)
* *
* @dataField outputActive | Boolean | Whether the output is active * @dataField outputActive | Boolean | Whether the output is active
* @dataField outputState | String | The specific state of the output * @dataField outputState | String | The specific state of the output
* @dataField outputPath | String | File name for the saved recording, if record stopped. `null` otherwise
* *
* @eventType RecordStateChanged * @eventType RecordStateChanged
* @eventSubscription Outputs * @eventSubscription Outputs
@ -74,7 +76,12 @@ void EventHandler::HandleRecordStateChanged(ObsOutputState state)
{ {
json eventData; json eventData;
eventData["outputActive"] = GetOutputStateActive(state); eventData["outputActive"] = GetOutputStateActive(state);
eventData["outputState"] = Utils::Obs::StringHelper::GetOutputState(state); eventData["outputState"] = state;
if (state == OBS_WEBSOCKET_OUTPUT_STOPPED || state == OBS_WEBSOCKET_OUTPUT_STARTED) {
eventData["outputPath"] = Utils::Obs::StringHelper::GetLastRecordFileName();
} else {
eventData["outputPath"] = nullptr;
}
BroadcastEvent(EventSubscription::Outputs, "RecordStateChanged", eventData); BroadcastEvent(EventSubscription::Outputs, "RecordStateChanged", eventData);
} }
@ -96,7 +103,7 @@ void EventHandler::HandleReplayBufferStateChanged(ObsOutputState state)
{ {
json eventData; json eventData;
eventData["outputActive"] = GetOutputStateActive(state); eventData["outputActive"] = GetOutputStateActive(state);
eventData["outputState"] = Utils::Obs::StringHelper::GetOutputState(state); eventData["outputState"] = state;
BroadcastEvent(EventSubscription::Outputs, "ReplayBufferStateChanged", eventData); BroadcastEvent(EventSubscription::Outputs, "ReplayBufferStateChanged", eventData);
} }
@ -118,7 +125,7 @@ void EventHandler::HandleVirtualcamStateChanged(ObsOutputState state)
{ {
json eventData; json eventData;
eventData["outputActive"] = GetOutputStateActive(state); eventData["outputActive"] = GetOutputStateActive(state);
eventData["outputState"] = Utils::Obs::StringHelper::GetOutputState(state); eventData["outputState"] = state;
BroadcastEvent(EventSubscription::Outputs, "VirtualcamStateChanged", eventData); BroadcastEvent(EventSubscription::Outputs, "VirtualcamStateChanged", eventData);
} }
@ -138,6 +145,6 @@ void EventHandler::HandleVirtualcamStateChanged(ObsOutputState state)
void EventHandler::HandleReplayBufferSaved() void EventHandler::HandleReplayBufferSaved()
{ {
json eventData; json eventData;
eventData["savedReplayPath"] = Utils::Obs::StringHelper::GetLastReplayBufferFilePath(); eventData["savedReplayPath"] = Utils::Obs::StringHelper::GetLastReplayBufferFileName();
BroadcastEvent(EventSubscription::Outputs, "ReplayBufferSaved", eventData); BroadcastEvent(EventSubscription::Outputs, "ReplayBufferSaved", eventData);
} }

View File

@ -157,13 +157,15 @@ namespace EventSubscription {
* Helper to receive all non-high-volume events. * Helper to receive all non-high-volume events.
* *
* @enumIdentifier All * @enumIdentifier All
* @enumValue (General | Config | Scenes | Inputs | Transitions | Filters | Outputs | SceneItems | MediaInputs | Vendors) * @enumValue (General | Config | Scenes | Inputs | Transitions | Filters | Outputs | SceneItems | MediaInputs | Vendors | Ui)
* @enumType EventSubscription * @enumType EventSubscription
* @rpcVersion -1 * @rpcVersion -1
* @initialVersion 5.0.0 * @initialVersion 5.0.0
* @api enums * @api enums
*/ */
All = (General | Config | Scenes | Inputs | Transitions | Filters | Outputs | SceneItems | MediaInputs | Ui | Vendors), All = (General | Config | Scenes | Inputs | Transitions | Filters | Outputs | SceneItems | MediaInputs | Vendors |
Ui),
/** /**
* Subscription value to receive the `InputVolumeMeters` high-volume event. * Subscription value to receive the `InputVolumeMeters` high-volume event.
* *

View File

@ -28,18 +28,13 @@ with this program. If not, see <https://www.gnu.org/licenses/>
#include "../Config.h" #include "../Config.h"
#include "../utils/Platform.h" #include "../utils/Platform.h"
ConnectInfo::ConnectInfo(QWidget* parent) : ConnectInfo::ConnectInfo(QWidget *parent) : QDialog(parent, Qt::Dialog), ui(new Ui::ConnectInfo)
QDialog(parent, Qt::Dialog),
ui(new Ui::ConnectInfo)
{ {
ui->setupUi(this); ui->setupUi(this);
connect(ui->copyServerIpButton, &QPushButton::clicked, connect(ui->copyServerIpButton, &QPushButton::clicked, this, &ConnectInfo::CopyServerIpButtonClicked);
this, &ConnectInfo::CopyServerIpButtonClicked); connect(ui->copyServerPortButton, &QPushButton::clicked, this, &ConnectInfo::CopyServerPortButtonClicked);
connect(ui->copyServerPortButton, &QPushButton::clicked, connect(ui->copyServerPasswordButton, &QPushButton::clicked, this, &ConnectInfo::CopyServerPasswordButtonClicked);
this, &ConnectInfo::CopyServerPortButtonClicked);
connect(ui->copyServerPasswordButton, &QPushButton::clicked,
this, &ConnectInfo::CopyServerPasswordButtonClicked);
} }
ConnectInfo::~ConnectInfo() ConnectInfo::~ConnectInfo()

View File

@ -25,8 +25,7 @@ with this program. If not, see <https://www.gnu.org/licenses/>
#include "ui_ConnectInfo.h" #include "ui_ConnectInfo.h"
class ConnectInfo : public QDialog class ConnectInfo : public QDialog {
{
Q_OBJECT Q_OBJECT
public: public:

View File

@ -37,8 +37,8 @@ QString GetToolTipIconHtml()
return iconTemplate.arg(iconFile); return iconTemplate.arg(iconFile);
} }
SettingsDialog::SettingsDialog(QWidget* parent) : SettingsDialog::SettingsDialog(QWidget *parent)
QDialog(parent, Qt::Dialog), : QDialog(parent, Qt::Dialog),
ui(new Ui::SettingsDialog), ui(new Ui::SettingsDialog),
connectInfo(new ConnectInfo), connectInfo(new ConnectInfo),
sessionTableTimer(new QTimer), sessionTableTimer(new QTimer),
@ -54,18 +54,13 @@ SettingsDialog::SettingsDialog(QWidget* parent) :
// Set the appropriate tooltip icon for the theme // Set the appropriate tooltip icon for the theme
ui->enableDebugLoggingToolTipLabel->setText(GetToolTipIconHtml()); ui->enableDebugLoggingToolTipLabel->setText(GetToolTipIconHtml());
connect(sessionTableTimer, &QTimer::timeout, connect(sessionTableTimer, &QTimer::timeout, this, &SettingsDialog::FillSessionTable);
this, &SettingsDialog::FillSessionTable); connect(ui->buttonBox, &QDialogButtonBox::clicked, this, &SettingsDialog::DialogButtonClicked);
connect(ui->buttonBox, &QDialogButtonBox::clicked, connect(ui->enableAuthenticationCheckBox, &QCheckBox::stateChanged, this,
this, &SettingsDialog::DialogButtonClicked); &SettingsDialog::EnableAuthenticationCheckBoxChanged);
connect(ui->enableAuthenticationCheckBox, &QCheckBox::stateChanged, connect(ui->generatePasswordButton, &QPushButton::clicked, this, &SettingsDialog::GeneratePasswordButtonClicked);
this, &SettingsDialog::EnableAuthenticationCheckBoxChanged); connect(ui->showConnectInfoButton, &QPushButton::clicked, this, &SettingsDialog::ShowConnectInfoButtonClicked);
connect(ui->generatePasswordButton, &QPushButton::clicked, connect(ui->serverPasswordLineEdit, &QLineEdit::textEdited, this, &SettingsDialog::PasswordEdited);
this, &SettingsDialog::GeneratePasswordButtonClicked);
connect(ui->showConnectInfoButton, &QPushButton::clicked,
this, &SettingsDialog::ShowConnectInfoButtonClicked);
connect(ui->serverPasswordLineEdit, &QLineEdit::textEdited,
this, &SettingsDialog::PasswordEdited);
} }
SettingsDialog::~SettingsDialog() SettingsDialog::~SettingsDialog()
@ -83,18 +78,8 @@ void SettingsDialog::showEvent(QShowEvent *)
return; return;
} }
ui->enableWebSocketServerCheckBox->setChecked(conf->ServerEnabled); if (conf->PortOverridden)
ui->enableSystemTrayAlertsCheckBox->setChecked(conf->AlertsEnabled);
ui->enableDebugLoggingCheckBox->setChecked(conf->DebugEnabled);
ui->enableAuthenticationCheckBox->setChecked(conf->AuthRequired);
ui->serverPasswordLineEdit->setText(conf->ServerPassword);
ui->serverPasswordLineEdit->setEnabled(conf->AuthRequired);
ui->generatePasswordButton->setEnabled(conf->AuthRequired);
ui->serverPortSpinBox->setValue(conf->ServerPort);
if (conf->PortOverridden) {
ui->serverPortSpinBox->setEnabled(false); ui->serverPortSpinBox->setEnabled(false);
}
if (conf->PasswordOverridden) { if (conf->PasswordOverridden) {
ui->enableAuthenticationCheckBox->setEnabled(false); ui->enableAuthenticationCheckBox->setEnabled(false);
@ -104,7 +89,7 @@ void SettingsDialog::showEvent(QShowEvent *)
passwordManuallyEdited = false; passwordManuallyEdited = false;
FillSessionTable(); RefreshData();
sessionTableTimer->start(1000); sessionTableTimer->start(1000);
} }
@ -125,6 +110,27 @@ void SettingsDialog::ToggleShowHide()
setVisible(false); setVisible(false);
} }
void SettingsDialog::RefreshData()
{
auto conf = GetConfig();
if (!conf) {
blog(LOG_ERROR, "[SettingsDialog::RefreshData] Unable to retreive config!");
return;
}
ui->enableWebSocketServerCheckBox->setChecked(conf->ServerEnabled);
ui->enableSystemTrayAlertsCheckBox->setChecked(conf->AlertsEnabled);
ui->enableDebugLoggingCheckBox->setChecked(conf->DebugEnabled);
ui->serverPortSpinBox->setValue(conf->ServerPort);
ui->enableAuthenticationCheckBox->setChecked(conf->AuthRequired);
ui->serverPasswordLineEdit->setText(conf->ServerPassword);
ui->serverPasswordLineEdit->setEnabled(conf->AuthRequired);
ui->generatePasswordButton->setEnabled(conf->AuthRequired);
FillSessionTable();
}
void SettingsDialog::DialogButtonClicked(QAbstractButton *button) void SettingsDialog::DialogButtonClicked(QAbstractButton *button)
{ {
if (button == ui->buttonBox->button(QDialogButtonBox::Ok)) { if (button == ui->buttonBox->button(QDialogButtonBox::Ok)) {
@ -171,19 +177,21 @@ void SettingsDialog::SaveFormData()
} }
} }
bool needsRestart = (conf->ServerEnabled != ui->enableWebSocketServerCheckBox->isChecked()) || bool needsRestart =
(ui->enableAuthenticationCheckBox->isChecked() && conf->ServerPassword != ui->serverPasswordLineEdit->text()) || (conf->ServerEnabled != ui->enableWebSocketServerCheckBox->isChecked()) ||
(conf->ServerPort != ui->serverPortSpinBox->value()); (conf->ServerPort != ui->serverPortSpinBox->value()) ||
(ui->enableAuthenticationCheckBox->isChecked() && conf->ServerPassword != ui->serverPasswordLineEdit->text());
conf->ServerEnabled = ui->enableWebSocketServerCheckBox->isChecked(); conf->ServerEnabled = ui->enableWebSocketServerCheckBox->isChecked();
conf->AlertsEnabled = ui->enableSystemTrayAlertsCheckBox->isChecked(); conf->AlertsEnabled = ui->enableSystemTrayAlertsCheckBox->isChecked();
conf->DebugEnabled = ui->enableDebugLoggingCheckBox->isChecked(); conf->DebugEnabled = ui->enableDebugLoggingCheckBox->isChecked();
conf->ServerPort = ui->serverPortSpinBox->value();
conf->AuthRequired = ui->enableAuthenticationCheckBox->isChecked(); conf->AuthRequired = ui->enableAuthenticationCheckBox->isChecked();
conf->ServerPassword = ui->serverPasswordLineEdit->text(); conf->ServerPassword = ui->serverPasswordLineEdit->text();
conf->ServerPort = ui->serverPortSpinBox->value();
conf->Save(); conf->Save();
RefreshData();
connectInfo->RefreshData(); connectInfo->RefreshData();
if (needsRestart) { if (needsRestart) {
@ -226,7 +234,8 @@ void SettingsDialog::FillSessionTable()
QTableWidgetItem *durationItem = new QTableWidgetItem(QTime(0, 0, sessionDuration).toString("hh:mm:ss")); QTableWidgetItem *durationItem = new QTableWidgetItem(QTime(0, 0, sessionDuration).toString("hh:mm:ss"));
ui->websocketSessionTable->setItem(i, 1, durationItem); ui->websocketSessionTable->setItem(i, 1, durationItem);
QTableWidgetItem *statsItem = new QTableWidgetItem(QString("%1/%2").arg(session.incomingMessages).arg(session.outgoingMessages)); QTableWidgetItem *statsItem =
new QTableWidgetItem(QString("%1/%2").arg(session.incomingMessages).arg(session.outgoingMessages));
ui->websocketSessionTable->setItem(i, 2, statsItem); ui->websocketSessionTable->setItem(i, 2, statsItem);
QLabel *identifiedLabel = new QLabel(); QLabel *identifiedLabel = new QLabel();
@ -246,9 +255,7 @@ void SettingsDialog::FillSessionTable()
invalidateButtonLayout->setContentsMargins(0, 0, 0, 0); invalidateButtonLayout->setContentsMargins(0, 0, 0, 0);
invalidateButtonWidget->setLayout(invalidateButtonLayout); invalidateButtonWidget->setLayout(invalidateButtonLayout);
ui->websocketSessionTable->setCellWidget(i, 4, invalidateButtonWidget); ui->websocketSessionTable->setCellWidget(i, 4, invalidateButtonWidget);
connect(invalidateButton, &QPushButton::clicked, [=]() { connect(invalidateButton, &QPushButton::clicked, [=]() { webSocketServer->InvalidateSession(session.hdl); });
webSocketServer->InvalidateSession(session.hdl);
});
i++; i++;
} }

View File

@ -27,8 +27,7 @@ with this program. If not, see <https://www.gnu.org/licenses/>
#include "ui_SettingsDialog.h" #include "ui_SettingsDialog.h"
class SettingsDialog : public QDialog class SettingsDialog : public QDialog {
{
Q_OBJECT Q_OBJECT
public: public:
@ -37,6 +36,7 @@ public:
void showEvent(QShowEvent *event); void showEvent(QShowEvent *event);
void hideEvent(QHideEvent *event); void hideEvent(QHideEvent *event);
void ToggleShowHide(); void ToggleShowHide();
void RefreshData();
private Q_SLOTS: private Q_SLOTS:
void DialogButtonClicked(QAbstractButton *button); void DialogButtonClicked(QAbstractButton *button);

View File

@ -32,8 +32,14 @@ with this program. If not, see <https://www.gnu.org/licenses/>
OBS_DECLARE_MODULE() OBS_DECLARE_MODULE()
OBS_MODULE_USE_DEFAULT_LOCALE("obs-websocket", "en-US") OBS_MODULE_USE_DEFAULT_LOCALE("obs-websocket", "en-US")
OBS_MODULE_AUTHOR("OBSProject") OBS_MODULE_AUTHOR("OBSProject")
const char *obs_module_name(void) { return "obs-websocket"; } const char *obs_module_name(void)
const char *obs_module_description(void) { return obs_module_text("OBSWebSocket.Plugin.Description"); } {
return "obs-websocket";
}
const char *obs_module_description(void)
{
return obs_module_text("OBSWebSocket.Plugin.Description");
}
os_cpu_usage_info_t *_cpuUsageInfo; os_cpu_usage_info_t *_cpuUsageInfo;
ConfigPtr _config; ConfigPtr _config;
@ -46,7 +52,8 @@ void WebSocketApiEventCallback(std::string vendorName, std::string eventType, ob
bool obs_module_load(void) bool obs_module_load(void)
{ {
blog(LOG_INFO, "[obs_module_load] you can haz websockets (Version: %s | RPC Version: %d)", OBS_WEBSOCKET_VERSION, OBS_WEBSOCKET_RPC_VERSION); blog(LOG_INFO, "[obs_module_load] you can haz websockets (Version: %s | RPC Version: %d)", OBS_WEBSOCKET_VERSION,
OBS_WEBSOCKET_RPC_VERSION);
blog(LOG_INFO, "[obs_module_load] Qt version (compile-time): %s | Qt version (run-time): %s", QT_VERSION_STR, qVersion()); blog(LOG_INFO, "[obs_module_load] Qt version (compile-time): %s | Qt version (run-time): %s", QT_VERSION_STR, qVersion());
blog(LOG_INFO, "[obs_module_load] Linked ASIO Version: %d", ASIO_VERSION); blog(LOG_INFO, "[obs_module_load] Linked ASIO Version: %d", ASIO_VERSION);
@ -190,12 +197,26 @@ void obs_module_post_load()
{ {
blog(LOG_INFO, "[obs_module_post_load] Post load started."); blog(LOG_INFO, "[obs_module_post_load] Post load started.");
// Test plugin API version fetch
uint apiVersion = obs_websocket_get_api_version();
blog(LOG_INFO, "[obs_module_post_load] obs-websocket plugin API version: %u", apiVersion);
// Test calling obs-websocket requests
struct obs_websocket_request_response *response = obs_websocket_call_request("GetVersion");
if (response) {
blog(LOG_INFO, "[obs_module_post_load] Called GetVersion. Status Code: %u | Comment: %s | Response Data: %s",
response->status_code, response->comment, response->response_data);
obs_websocket_request_response_free(response);
}
// Test vendor creation
auto vendor = obs_websocket_register_vendor("obs-websocket-test"); auto vendor = obs_websocket_register_vendor("obs-websocket-test");
if (!vendor) { if (!vendor) {
blog(LOG_WARNING, "[obs_module_post_load] Failed to create vendor!"); blog(LOG_WARNING, "[obs_module_post_load] Failed to create vendor!");
return; return;
} }
// Test vendor request registration
if (!obs_websocket_vendor_register_request(vendor, "TestRequest", test_vendor_request_cb, vendor)) { if (!obs_websocket_vendor_register_request(vendor, "TestRequest", test_vendor_request_cb, vendor)) {
blog(LOG_WARNING, "[obs_module_post_load] Failed to register vendor request!"); blog(LOG_WARNING, "[obs_module_post_load] Failed to register vendor request!");
return; return;

View File

@ -26,7 +26,7 @@ with this program. If not, see <https://www.gnu.org/licenses/>
#include "utils/Obs.h" #include "utils/Obs.h"
#include "plugin-macros.generated.h" #include "plugin-macros.generated.h"
class Config; struct Config;
typedef std::shared_ptr<Config> ConfigPtr; typedef std::shared_ptr<Config> ConfigPtr;
class EventHandler; class EventHandler;

View File

@ -24,8 +24,7 @@ with this program. If not, see <https://www.gnu.org/licenses/>
#include "../utils/Compat.h" #include "../utils/Compat.h"
#include "../obs-websocket.h" #include "../obs-websocket.h"
struct SerialFrameBatch struct SerialFrameBatch {
{
RequestHandler &requestHandler; RequestHandler &requestHandler;
std::queue<RequestBatchRequest> requests; std::queue<RequestBatchRequest> requests;
std::vector<RequestResult> results; std::vector<RequestResult> results;
@ -37,43 +36,46 @@ struct SerialFrameBatch
std::mutex conditionMutex; std::mutex conditionMutex;
std::condition_variable condition; std::condition_variable condition;
SerialFrameBatch(RequestHandler &requestHandler, json &variables, bool haltOnFailure) : SerialFrameBatch(RequestHandler &requestHandler, json &variables, bool haltOnFailure)
requestHandler(requestHandler), : requestHandler(requestHandler),
variables(variables), variables(variables),
haltOnFailure(haltOnFailure), haltOnFailure(haltOnFailure),
frameCount(0), frameCount(0),
sleepUntilFrame(0) sleepUntilFrame(0)
{} {
}
}; };
struct ParallelBatchResults struct ParallelBatchResults {
{
RequestHandler &requestHandler; RequestHandler &requestHandler;
std::vector<RequestResult> results; std::vector<RequestResult> results;
std::mutex conditionMutex; std::mutex conditionMutex;
std::condition_variable condition; std::condition_variable condition;
ParallelBatchResults(RequestHandler &requestHandler) : ParallelBatchResults(RequestHandler &requestHandler) : requestHandler(requestHandler) {}
requestHandler(requestHandler)
{}
}; };
// `{"inputName": "inputNameVariable"}` is essentially `inputName = inputNameVariable` // `{"inputName": "inputNameVariable"}` is essentially `inputName = inputNameVariable`
static void PreProcessVariables(const json &variables, RequestBatchRequest &request) static void PreProcessVariables(const json &variables, RequestBatchRequest &request)
{ {
if (variables.empty() || !request.InputVariables.is_object() || request.InputVariables.empty() || !request.RequestData.is_object()) if (variables.empty() || !request.InputVariables.is_object() || request.InputVariables.empty() ||
!request.RequestData.is_object())
return; return;
for (auto &[key, value] : request.InputVariables.items()) { for (auto &[key, value] : request.InputVariables.items()) {
if (!value.is_string()) { if (!value.is_string()) {
blog_debug("[WebSocketServer::ProcessRequestBatch] Value of field `%s` in `inputVariables `is not a string. Skipping!", key.c_str()); blog_debug(
"[WebSocketServer::ProcessRequestBatch] Value of field `%s` in `inputVariables `is not a string. Skipping!",
key.c_str());
continue; continue;
} }
std::string valueString = value; std::string valueString = value;
if (!variables.contains(valueString)) { if (!variables.contains(valueString)) {
blog_debug("[WebSocketServer::ProcessRequestBatch] `inputVariables` requested variable `%s`, but it does not exist. Skipping!", valueString.c_str()); blog_debug(
"[WebSocketServer::ProcessRequestBatch] `inputVariables` requested variable `%s`, but it does not exist. Skipping!",
valueString.c_str());
continue; continue;
} }
@ -91,13 +93,17 @@ static void PostProcessVariables(json &variables, const RequestBatchRequest &req
for (auto &[key, value] : request.OutputVariables.items()) { for (auto &[key, value] : request.OutputVariables.items()) {
if (!value.is_string()) { if (!value.is_string()) {
blog_debug("[WebSocketServer::ProcessRequestBatch] Value of field `%s` in `outputVariables` is not a string. Skipping!", key.c_str()); blog_debug(
"[WebSocketServer::ProcessRequestBatch] Value of field `%s` in `outputVariables` is not a string. Skipping!",
key.c_str());
continue; continue;
} }
std::string valueString = value; std::string valueString = value;
if (!requestResult.ResponseData.contains(valueString)) { if (!requestResult.ResponseData.contains(valueString)) {
blog_debug("[WebSocketServer::ProcessRequestBatch] `outputVariables` requested responseData field `%s`, but it does not exist. Skipping!", valueString.c_str()); blog_debug(
"[WebSocketServer::ProcessRequestBatch] `outputVariables` requested responseData field `%s`, but it does not exist. Skipping!",
valueString.c_str());
continue; continue;
} }
@ -156,7 +162,10 @@ static void ObsTickCallback(void *param, float)
serialFrameBatch->condition.notify_one(); serialFrameBatch->condition.notify_one();
} }
std::vector<RequestResult> RequestBatchHandler::ProcessRequestBatch(QThreadPool &threadPool, SessionPtr session, RequestBatchExecutionType::RequestBatchExecutionType executionType, std::vector<RequestBatchRequest> &requests, json &variables, bool haltOnFailure) std::vector<RequestResult>
RequestBatchHandler::ProcessRequestBatch(QThreadPool &threadPool, SessionPtr session,
RequestBatchExecutionType::RequestBatchExecutionType executionType,
std::vector<RequestBatchRequest> &requests, json &variables, bool haltOnFailure)
{ {
RequestHandler requestHandler(session); RequestHandler requestHandler(session);
if (executionType == RequestBatchExecutionType::SerialRealtime) { if (executionType == RequestBatchExecutionType::SerialRealtime) {
@ -215,7 +224,9 @@ std::vector<RequestResult> RequestBatchHandler::ProcessRequestBatch(QThreadPool
// Wait for the last request to finish processing // Wait for the last request to finish processing
size_t requestCount = requests.size(); size_t requestCount = requests.size();
parallelResults.condition.wait(lock, [&parallelResults, requestCount]{return parallelResults.results.size() == requestCount;}); parallelResults.condition.wait(lock, [&parallelResults, requestCount] {
return parallelResults.results.size() == requestCount;
});
return parallelResults.results; return parallelResults.results;
} }

View File

@ -24,5 +24,8 @@ with this program. If not, see <https://www.gnu.org/licenses/>
#include "rpc/RequestBatchRequest.h" #include "rpc/RequestBatchRequest.h"
namespace RequestBatchHandler { namespace RequestBatchHandler {
std::vector<RequestResult> ProcessRequestBatch(QThreadPool &threadPool, SessionPtr session, RequestBatchExecutionType::RequestBatchExecutionType executionType, std::vector<RequestBatchRequest> &requests, json &variables, bool haltOnFailure); std::vector<RequestResult> ProcessRequestBatch(QThreadPool &threadPool, SessionPtr session,
RequestBatchExecutionType::RequestBatchExecutionType executionType,
std::vector<RequestBatchRequest> &requests, json &variables,
bool haltOnFailure);
} }

View File

@ -23,8 +23,7 @@ with this program. If not, see <https://www.gnu.org/licenses/>
#include "RequestHandler.h" #include "RequestHandler.h"
const std::unordered_map<std::string, RequestMethodHandler> RequestHandler::_handlerMap const std::unordered_map<std::string, RequestMethodHandler> RequestHandler::_handlerMap{
{
// General // General
{"GetVersion", &RequestHandler::GetVersion}, {"GetVersion", &RequestHandler::GetVersion},
{"GetStats", &RequestHandler::GetStats}, {"GetStats", &RequestHandler::GetStats},
@ -138,6 +137,8 @@ const std::unordered_map<std::string, RequestMethodHandler> RequestHandler::_han
{"SetSceneItemIndex", &RequestHandler::SetSceneItemIndex}, {"SetSceneItemIndex", &RequestHandler::SetSceneItemIndex},
{"GetSceneItemBlendMode", &RequestHandler::GetSceneItemBlendMode}, {"GetSceneItemBlendMode", &RequestHandler::GetSceneItemBlendMode},
{"SetSceneItemBlendMode", &RequestHandler::SetSceneItemBlendMode}, {"SetSceneItemBlendMode", &RequestHandler::SetSceneItemBlendMode},
{"GetSceneItemPrivateSettings", &RequestHandler::GetSceneItemPrivateSettings},
{"SetSceneItemPrivateSettings", &RequestHandler::SetSceneItemPrivateSettings},
// Outputs // Outputs
{"GetVirtualCamStatus", &RequestHandler::GetVirtualCamStatus}, {"GetVirtualCamStatus", &RequestHandler::GetVirtualCamStatus},
@ -150,6 +151,13 @@ const std::unordered_map<std::string, RequestMethodHandler> RequestHandler::_han
{"StopReplayBuffer", &RequestHandler::StopReplayBuffer}, {"StopReplayBuffer", &RequestHandler::StopReplayBuffer},
{"SaveReplayBuffer", &RequestHandler::SaveReplayBuffer}, {"SaveReplayBuffer", &RequestHandler::SaveReplayBuffer},
{"GetLastReplayBufferReplay", &RequestHandler::GetLastReplayBufferReplay}, {"GetLastReplayBufferReplay", &RequestHandler::GetLastReplayBufferReplay},
{"GetOutputList", &RequestHandler::GetOutputList},
{"GetOutputStatus", &RequestHandler::GetOutputStatus},
{"ToggleOutput", &RequestHandler::ToggleOutput},
{"StartOutput", &RequestHandler::StartOutput},
{"StopOutput", &RequestHandler::StopOutput},
{"GetOutputSettings", &RequestHandler::GetOutputSettings},
{"SetOutputSettings", &RequestHandler::SetOutputSettings},
// Stream // Stream
{"GetStreamStatus", &RequestHandler::GetStreamStatus}, {"GetStreamStatus", &RequestHandler::GetStreamStatus},
@ -179,12 +187,12 @@ const std::unordered_map<std::string, RequestMethodHandler> RequestHandler::_han
{"OpenInputPropertiesDialog", &RequestHandler::OpenInputPropertiesDialog}, {"OpenInputPropertiesDialog", &RequestHandler::OpenInputPropertiesDialog},
{"OpenInputFiltersDialog", &RequestHandler::OpenInputFiltersDialog}, {"OpenInputFiltersDialog", &RequestHandler::OpenInputFiltersDialog},
{"OpenInputInteractDialog", &RequestHandler::OpenInputInteractDialog}, {"OpenInputInteractDialog", &RequestHandler::OpenInputInteractDialog},
{"GetMonitorList", &RequestHandler::GetMonitorList},
{"OpenVideoMixProjector", &RequestHandler::OpenVideoMixProjector},
{"OpenSourceProjector", &RequestHandler::OpenSourceProjector},
}; };
RequestHandler::RequestHandler(SessionPtr session) : RequestHandler::RequestHandler(SessionPtr session) : _session(session) {}
_session(session)
{
}
RequestResult RequestHandler::ProcessRequest(const Request &request) RequestResult RequestHandler::ProcessRequest(const Request &request)
{ {
@ -196,7 +204,7 @@ RequestResult RequestHandler::ProcessRequest(const Request& request)
return RequestResult::Error(RequestStatus::InvalidRequestFieldType, "Your request data is not an object."); return RequestResult::Error(RequestStatus::InvalidRequestFieldType, "Your request data is not an object.");
if (request.RequestType.empty()) if (request.RequestType.empty())
return RequestResult::Error(RequestStatus::MissingRequestType, "Your request is missing a `requestType`"); return RequestResult::Error(RequestStatus::MissingRequestType, "Your request's `requestType` may not be empty.");
RequestMethodHandler handler; RequestMethodHandler handler;
try { try {

View File

@ -37,7 +37,7 @@ typedef RequestResult(RequestHandler::*RequestMethodHandler)(const Request&);
class RequestHandler { class RequestHandler {
public: public:
RequestHandler(SessionPtr session); RequestHandler(SessionPtr session = nullptr);
RequestResult ProcessRequest(const Request &request); RequestResult ProcessRequest(const Request &request);
std::vector<std::string> GetRequestList(); std::vector<std::string> GetRequestList();
@ -156,6 +156,8 @@ class RequestHandler {
RequestResult SetSceneItemIndex(const Request &); RequestResult SetSceneItemIndex(const Request &);
RequestResult GetSceneItemBlendMode(const Request &); RequestResult GetSceneItemBlendMode(const Request &);
RequestResult SetSceneItemBlendMode(const Request &); RequestResult SetSceneItemBlendMode(const Request &);
RequestResult GetSceneItemPrivateSettings(const Request &);
RequestResult SetSceneItemPrivateSettings(const Request &);
// Outputs // Outputs
RequestResult GetVirtualCamStatus(const Request &); RequestResult GetVirtualCamStatus(const Request &);
@ -168,6 +170,13 @@ class RequestHandler {
RequestResult StopReplayBuffer(const Request &); RequestResult StopReplayBuffer(const Request &);
RequestResult SaveReplayBuffer(const Request &); RequestResult SaveReplayBuffer(const Request &);
RequestResult GetLastReplayBufferReplay(const Request &); RequestResult GetLastReplayBufferReplay(const Request &);
RequestResult GetOutputList(const Request &);
RequestResult GetOutputStatus(const Request &);
RequestResult ToggleOutput(const Request &);
RequestResult StartOutput(const Request &);
RequestResult StopOutput(const Request &);
RequestResult GetOutputSettings(const Request &);
RequestResult SetOutputSettings(const Request &);
// Stream // Stream
RequestResult GetStreamStatus(const Request &); RequestResult GetStreamStatus(const Request &);
@ -197,6 +206,9 @@ class RequestHandler {
RequestResult OpenInputPropertiesDialog(const Request &); RequestResult OpenInputPropertiesDialog(const Request &);
RequestResult OpenInputFiltersDialog(const Request &); RequestResult OpenInputFiltersDialog(const Request &);
RequestResult OpenInputInteractDialog(const Request &); RequestResult OpenInputInteractDialog(const Request &);
RequestResult GetMonitorList(const Request &);
RequestResult OpenVideoMixProjector(const Request &);
RequestResult OpenSourceProjector(const Request &);
SessionPtr _session; SessionPtr _session;
static const std::unordered_map<std::string, RequestMethodHandler> _handlerMap; static const std::unordered_map<std::string, RequestMethodHandler> _handlerMap;

View File

@ -53,7 +53,8 @@ RequestResult RequestHandler::GetPersistentData(const Request& request)
else if (realm == "OBS_WEBSOCKET_DATA_REALM_PROFILE") else if (realm == "OBS_WEBSOCKET_DATA_REALM_PROFILE")
persistentDataPath += "/obsWebSocketPersistentData.json"; persistentDataPath += "/obsWebSocketPersistentData.json";
else else
return RequestResult::Error(RequestStatus::ResourceNotFound, "You have specified an invalid persistent data realm."); return RequestResult::Error(RequestStatus::ResourceNotFound,
"You have specified an invalid persistent data realm.");
json responseData; json responseData;
json persistentData; json persistentData;
@ -83,7 +84,8 @@ RequestResult RequestHandler::SetPersistentData(const Request& request)
{ {
RequestStatus::RequestStatus statusCode; RequestStatus::RequestStatus statusCode;
std::string comment; std::string comment;
if (!(request.ValidateString("realm", statusCode, comment) && request.ValidateString("slotName", statusCode, comment) && request.ValidateBasic("slotValue", statusCode, comment))) if (!(request.ValidateString("realm", statusCode, comment) && request.ValidateString("slotName", statusCode, comment) &&
request.ValidateBasic("slotValue", statusCode, comment)))
return RequestResult::Error(statusCode, comment); return RequestResult::Error(statusCode, comment);
std::string realm = request.RequestData["realm"]; std::string realm = request.RequestData["realm"];
@ -96,13 +98,15 @@ RequestResult RequestHandler::SetPersistentData(const Request& request)
else if (realm == "OBS_WEBSOCKET_DATA_REALM_PROFILE") else if (realm == "OBS_WEBSOCKET_DATA_REALM_PROFILE")
persistentDataPath += "/obsWebSocketPersistentData.json"; persistentDataPath += "/obsWebSocketPersistentData.json";
else else
return RequestResult::Error(RequestStatus::ResourceNotFound, "You have specified an invalid persistent data realm."); return RequestResult::Error(RequestStatus::ResourceNotFound,
"You have specified an invalid persistent data realm.");
json persistentData = json::object(); json persistentData = json::object();
Utils::Json::GetJsonFileContent(persistentDataPath, persistentData); Utils::Json::GetJsonFileContent(persistentDataPath, persistentData);
persistentData[slotName] = slotValue; persistentData[slotName] = slotValue;
if (!Utils::Json::SetJsonFileContent(persistentDataPath, persistentData)) if (!Utils::Json::SetJsonFileContent(persistentDataPath, persistentData))
return RequestResult::Error(RequestStatus::RequestProcessingFailed, "Unable to write persistent data. No permissions?"); return RequestResult::Error(RequestStatus::RequestProcessingFailed,
"Unable to write persistent data. No permissions?");
return RequestResult::Success(); return RequestResult::Success();
} }
@ -158,9 +162,10 @@ RequestResult RequestHandler::SetCurrentSceneCollection(const Request& request)
std::string currentSceneCollectionName = Utils::Obs::StringHelper::GetCurrentSceneCollection(); std::string currentSceneCollectionName = Utils::Obs::StringHelper::GetCurrentSceneCollection();
// Avoid queueing tasks if nothing will change // Avoid queueing tasks if nothing will change
if (currentSceneCollectionName != sceneCollectionName) { if (currentSceneCollectionName != sceneCollectionName) {
obs_queue_task(OBS_TASK_UI, [](void* param) { obs_queue_task(
obs_frontend_set_current_scene_collection(static_cast<const char*>(param)); OBS_TASK_UI,
}, (void*)sceneCollectionName.c_str(), true); [](void *param) { obs_frontend_set_current_scene_collection(static_cast<const char *>(param)); },
(void *)sceneCollectionName.c_str(), true);
} }
return RequestResult::Success(); return RequestResult::Success();
@ -195,7 +200,8 @@ RequestResult RequestHandler::CreateSceneCollection(const Request& request)
QMainWindow *mainWindow = static_cast<QMainWindow *>(obs_frontend_get_main_window()); QMainWindow *mainWindow = static_cast<QMainWindow *>(obs_frontend_get_main_window());
bool success = false; bool success = false;
QMetaObject::invokeMethod(mainWindow, "AddSceneCollection", Qt::BlockingQueuedConnection, Q_RETURN_ARG(bool, success), Q_ARG(bool, true), Q_ARG(QString, QString::fromStdString(sceneCollectionName))); QMetaObject::invokeMethod(mainWindow, "AddSceneCollection", Qt::BlockingQueuedConnection, Q_RETURN_ARG(bool, success),
Q_ARG(bool, true), Q_ARG(QString, QString::fromStdString(sceneCollectionName)));
if (!success) if (!success)
return RequestResult::Error(RequestStatus::ResourceCreationFailed, "Failed to create the scene collection."); return RequestResult::Error(RequestStatus::ResourceCreationFailed, "Failed to create the scene collection.");
@ -251,9 +257,9 @@ RequestResult RequestHandler::SetCurrentProfile(const Request& request)
std::string currentProfileName = Utils::Obs::StringHelper::GetCurrentProfile(); std::string currentProfileName = Utils::Obs::StringHelper::GetCurrentProfile();
// Avoid queueing tasks if nothing will change // Avoid queueing tasks if nothing will change
if (currentProfileName != profileName) { if (currentProfileName != profileName) {
obs_queue_task(OBS_TASK_UI, [](void* param) { obs_queue_task(
obs_frontend_set_current_profile(static_cast<const char*>(param)); OBS_TASK_UI, [](void *param) { obs_frontend_set_current_profile(static_cast<const char *>(param)); },
}, (void*)profileName.c_str(), true); (void *)profileName.c_str(), true);
} }
return RequestResult::Success(); return RequestResult::Success();
@ -285,7 +291,8 @@ RequestResult RequestHandler::CreateProfile(const Request& request)
return RequestResult::Error(RequestStatus::ResourceAlreadyExists); return RequestResult::Error(RequestStatus::ResourceAlreadyExists);
QMainWindow *mainWindow = static_cast<QMainWindow *>(obs_frontend_get_main_window()); QMainWindow *mainWindow = static_cast<QMainWindow *>(obs_frontend_get_main_window());
QMetaObject::invokeMethod(mainWindow, "NewProfile", Qt::BlockingQueuedConnection, Q_ARG(QString, QString::fromStdString(profileName))); QMetaObject::invokeMethod(mainWindow, "NewProfile", Qt::BlockingQueuedConnection,
Q_ARG(QString, QString::fromStdString(profileName)));
return RequestResult::Success(); return RequestResult::Success();
} }
@ -319,7 +326,8 @@ RequestResult RequestHandler::RemoveProfile(const Request& request)
return RequestResult::Error(RequestStatus::NotEnoughResources); return RequestResult::Error(RequestStatus::NotEnoughResources);
QMainWindow *mainWindow = static_cast<QMainWindow *>(obs_frontend_get_main_window()); QMainWindow *mainWindow = static_cast<QMainWindow *>(obs_frontend_get_main_window());
QMetaObject::invokeMethod(mainWindow, "DeleteProfile", Qt::BlockingQueuedConnection, Q_ARG(QString, QString::fromStdString(profileName))); QMetaObject::invokeMethod(mainWindow, "DeleteProfile", Qt::BlockingQueuedConnection,
Q_ARG(QString, QString::fromStdString(profileName)));
return RequestResult::Success(); return RequestResult::Success();
} }
@ -344,7 +352,8 @@ RequestResult RequestHandler::GetProfileParameter(const Request& request)
{ {
RequestStatus::RequestStatus statusCode; RequestStatus::RequestStatus statusCode;
std::string comment; std::string comment;
if (!(request.ValidateString("parameterCategory", statusCode, comment) && request.ValidateString("parameterName", statusCode, comment))) if (!(request.ValidateString("parameterCategory", statusCode, comment) &&
request.ValidateString("parameterName", statusCode, comment)))
return RequestResult::Error(statusCode, comment); return RequestResult::Error(statusCode, comment);
std::string parameterCategory = request.RequestData["parameterCategory"]; std::string parameterCategory = request.RequestData["parameterCategory"];
@ -358,7 +367,8 @@ RequestResult RequestHandler::GetProfileParameter(const Request& request)
json responseData; json responseData;
if (config_has_default_value(profile, parameterCategory.c_str(), parameterName.c_str())) { if (config_has_default_value(profile, parameterCategory.c_str(), parameterName.c_str())) {
responseData["parameterValue"] = config_get_string(profile, parameterCategory.c_str(), parameterName.c_str()); responseData["parameterValue"] = config_get_string(profile, parameterCategory.c_str(), parameterName.c_str());
responseData["defaultParameterValue"] = config_get_default_string(profile, parameterCategory.c_str(), parameterName.c_str()); responseData["defaultParameterValue"] =
config_get_default_string(profile, parameterCategory.c_str(), parameterName.c_str());
} else if (config_has_user_value(profile, parameterCategory.c_str(), parameterName.c_str())) { } else if (config_has_user_value(profile, parameterCategory.c_str(), parameterName.c_str())) {
responseData["parameterValue"] = config_get_string(profile, parameterCategory.c_str(), parameterName.c_str()); responseData["parameterValue"] = config_get_string(profile, parameterCategory.c_str(), parameterName.c_str());
responseData["defaultParameterValue"] = nullptr; responseData["defaultParameterValue"] = nullptr;
@ -400,7 +410,8 @@ RequestResult RequestHandler::SetProfileParameter(const Request& request)
// Using check helpers here would just make the logic more complicated // Using check helpers here would just make the logic more complicated
if (!request.RequestData.contains("parameterValue") || request.RequestData["parameterValue"].is_null()) { if (!request.RequestData.contains("parameterValue") || request.RequestData["parameterValue"].is_null()) {
if (!config_remove_value(profile, parameterCategory.c_str(), parameterName.c_str())) if (!config_remove_value(profile, parameterCategory.c_str(), parameterName.c_str()))
return RequestResult::Error(RequestStatus::ResourceNotFound, "There are no existing instances of that profile parameter."); return RequestResult::Error(RequestStatus::ResourceNotFound,
"There are no existing instances of that profile parameter.");
} else if (request.RequestData["parameterValue"].is_string()) { } else if (request.RequestData["parameterValue"].is_string()) {
std::string parameterValue = request.RequestData["parameterValue"]; std::string parameterValue = request.RequestData["parameterValue"];
config_set_string(profile, parameterCategory.c_str(), parameterName.c_str(), parameterValue.c_str()); config_set_string(profile, parameterCategory.c_str(), parameterName.c_str(), parameterValue.c_str());
@ -471,20 +482,24 @@ RequestResult RequestHandler::GetVideoSettings(const Request&)
RequestResult RequestHandler::SetVideoSettings(const Request &request) RequestResult RequestHandler::SetVideoSettings(const Request &request)
{ {
if (obs_video_active()) if (obs_video_active())
return RequestResult::Error(RequestStatus::OutputRunning, "Video settings cannot be changed while an output is active."); return RequestResult::Error(RequestStatus::OutputRunning,
"Video settings cannot be changed while an output is active.");
RequestStatus::RequestStatus statusCode = RequestStatus::NoError; RequestStatus::RequestStatus statusCode = RequestStatus::NoError;
std::string comment; std::string comment;
bool changeFps = (request.Contains("fpsNumerator") && request.Contains("fpsDenominator")); bool changeFps = (request.Contains("fpsNumerator") && request.Contains("fpsDenominator"));
if (changeFps && !(request.ValidateOptionalNumber("fpsNumerator", statusCode, comment, 1) && request.ValidateOptionalNumber("fpsDenominator", statusCode, comment, 1))) if (changeFps && !(request.ValidateOptionalNumber("fpsNumerator", statusCode, comment, 1) &&
request.ValidateOptionalNumber("fpsDenominator", statusCode, comment, 1)))
return RequestResult::Error(statusCode, comment); return RequestResult::Error(statusCode, comment);
bool changeBaseRes = (request.Contains("baseWidth") && request.Contains("baseHeight")); bool changeBaseRes = (request.Contains("baseWidth") && request.Contains("baseHeight"));
if (changeBaseRes && !(request.ValidateOptionalNumber("baseWidth", statusCode, comment, 8, 4096) && request.ValidateOptionalNumber("baseHeight", statusCode, comment, 8, 4096))) if (changeBaseRes && !(request.ValidateOptionalNumber("baseWidth", statusCode, comment, 8, 4096) &&
request.ValidateOptionalNumber("baseHeight", statusCode, comment, 8, 4096)))
return RequestResult::Error(statusCode, comment); return RequestResult::Error(statusCode, comment);
bool changeOutputRes = (request.Contains("outputWidth") && request.Contains("outputHeight")); bool changeOutputRes = (request.Contains("outputWidth") && request.Contains("outputHeight"));
if (changeOutputRes && !(request.ValidateOptionalNumber("outputWidth", statusCode, comment, 8, 4096) && request.ValidateOptionalNumber("outputHeight", statusCode, comment, 8, 4096))) if (changeOutputRes && !(request.ValidateOptionalNumber("outputWidth", statusCode, comment, 8, 4096) &&
request.ValidateOptionalNumber("outputHeight", statusCode, comment, 8, 4096)))
return RequestResult::Error(statusCode, comment); return RequestResult::Error(statusCode, comment);
config_t *config = obs_frontend_get_profile_config(); config_t *config = obs_frontend_get_profile_config();
@ -557,18 +572,21 @@ RequestResult RequestHandler::GetStreamServiceSettings(const Request&)
RequestResult RequestHandler::SetStreamServiceSettings(const Request &request) RequestResult RequestHandler::SetStreamServiceSettings(const Request &request)
{ {
if (obs_frontend_streaming_active()) if (obs_frontend_streaming_active())
return RequestResult::Error(RequestStatus::OutputRunning, "You cannot change stream service settings while streaming."); return RequestResult::Error(RequestStatus::OutputRunning,
"You cannot change stream service settings while streaming.");
RequestStatus::RequestStatus statusCode; RequestStatus::RequestStatus statusCode;
std::string comment; std::string comment;
if (!(request.ValidateString("streamServiceType", statusCode, comment) && request.ValidateObject("streamServiceSettings", statusCode, comment))) if (!(request.ValidateString("streamServiceType", statusCode, comment) &&
request.ValidateObject("streamServiceSettings", statusCode, comment)))
return RequestResult::Error(statusCode, comment); return RequestResult::Error(statusCode, comment);
OBSService currentStreamService = obs_frontend_get_streaming_service(); OBSService currentStreamService = obs_frontend_get_streaming_service();
std::string streamServiceType = obs_service_get_type(currentStreamService); std::string streamServiceType = obs_service_get_type(currentStreamService);
std::string requestedStreamServiceType = request.RequestData["streamServiceType"]; std::string requestedStreamServiceType = request.RequestData["streamServiceType"];
OBSDataAutoRelease requestedStreamServiceSettings = Utils::Json::JsonToObsData(request.RequestData["streamServiceSettings"]); OBSDataAutoRelease requestedStreamServiceSettings =
Utils::Json::JsonToObsData(request.RequestData["streamServiceSettings"]);
// Don't create a new service if the current service is the same type. // Don't create a new service if the current service is the same type.
if (streamServiceType == requestedStreamServiceType) { if (streamServiceType == requestedStreamServiceType) {
@ -582,10 +600,13 @@ RequestResult RequestHandler::SetStreamServiceSettings(const Request& request)
obs_service_update(currentStreamService, newStreamServiceSettings); obs_service_update(currentStreamService, newStreamServiceSettings);
} else { } else {
// TODO: This leaks memory. I have no idea why. // TODO: This leaks memory. I have no idea why.
OBSService newStreamService = obs_service_create(requestedStreamServiceType.c_str(), "obs_websocket_custom_service", requestedStreamServiceSettings, nullptr); OBSService newStreamService = obs_service_create(requestedStreamServiceType.c_str(), "obs_websocket_custom_service",
requestedStreamServiceSettings, nullptr);
// TODO: Check service type here, instead of relying on service creation to fail. // TODO: Check service type here, instead of relying on service creation to fail.
if (!newStreamService) if (!newStreamService)
return RequestResult::Error(RequestStatus::ResourceCreationFailed, "Failed to create the stream service with the requested streamServiceType. It may be an invalid type."); return RequestResult::Error(
RequestStatus::ResourceCreationFailed,
"Failed to create the stream service with the requested streamServiceType. It may be an invalid type.");
obs_frontend_set_streaming_service(newStreamService); obs_frontend_set_streaming_service(newStreamService);
} }

View File

@ -103,7 +103,8 @@ RequestResult RequestHandler::CreateSourceFilter(const Request& request)
std::string comment; std::string comment;
OBSSourceAutoRelease source = request.ValidateSource("sourceName", statusCode, comment); OBSSourceAutoRelease source = request.ValidateSource("sourceName", statusCode, comment);
if (!(source && request.ValidateString("filterName", statusCode, comment) && request.ValidateString("filterKind", statusCode, comment))) if (!(source && request.ValidateString("filterName", statusCode, comment) &&
request.ValidateString("filterKind", statusCode, comment)))
return RequestResult::Error(statusCode, comment); return RequestResult::Error(statusCode, comment);
std::string filterName = request.RequestData["filterName"]; std::string filterName = request.RequestData["filterName"];
@ -114,7 +115,9 @@ RequestResult RequestHandler::CreateSourceFilter(const Request& request)
std::string filterKind = request.RequestData["filterKind"]; std::string filterKind = request.RequestData["filterKind"];
auto kinds = Utils::Obs::ArrayHelper::GetFilterKindList(); auto kinds = Utils::Obs::ArrayHelper::GetFilterKindList();
if (std::find(kinds.begin(), kinds.end(), filterKind) == kinds.end()) if (std::find(kinds.begin(), kinds.end(), filterKind) == kinds.end())
return RequestResult::Error(RequestStatus::InvalidFilterKind, "Your specified filter kind is not supported by OBS. Check that any necessary plugins are loaded."); return RequestResult::Error(
RequestStatus::InvalidFilterKind,
"Your specified filter kind is not supported by OBS. Check that any necessary plugins are loaded.");
OBSDataAutoRelease filterSettings = nullptr; OBSDataAutoRelease filterSettings = nullptr;
if (request.Contains("filterSettings")) { if (request.Contains("filterSettings")) {
@ -219,7 +222,8 @@ RequestResult RequestHandler::GetSourceFilter(const Request& request)
json responseData; json responseData;
responseData["filterEnabled"] = obs_source_enabled(pair.filter); responseData["filterEnabled"] = obs_source_enabled(pair.filter);
responseData["filterIndex"] = Utils::Obs::NumberHelper::GetSourceFilterIndex(pair.source, pair.filter); // Todo: Use `GetSourceFilterlist` to select this filter maybe responseData["filterIndex"] = Utils::Obs::NumberHelper::GetSourceFilterIndex(
pair.source, pair.filter); // Todo: Use `GetSourceFilterlist` to select this filter maybe
responseData["filterKind"] = obs_source_get_id(pair.filter); responseData["filterKind"] = obs_source_get_id(pair.filter);
OBSDataAutoRelease filterSettings = obs_source_get_settings(pair.filter); OBSDataAutoRelease filterSettings = obs_source_get_settings(pair.filter);
@ -292,7 +296,8 @@ RequestResult RequestHandler::SetSourceFilterSettings(const Request& request)
OBSDataAutoRelease newSettings = Utils::Json::JsonToObsData(request.RequestData["filterSettings"]); OBSDataAutoRelease newSettings = Utils::Json::JsonToObsData(request.RequestData["filterSettings"]);
if (!newSettings) if (!newSettings)
return RequestResult::Error(RequestStatus::RequestProcessingFailed, "An internal data conversion operation failed. Please report this!"); return RequestResult::Error(RequestStatus::RequestProcessingFailed,
"An internal data conversion operation failed. Please report this!");
if (overlay) if (overlay)
obs_source_update(pair.filter, newSettings); obs_source_update(pair.filter, newSettings);
@ -308,7 +313,7 @@ RequestResult RequestHandler::SetSourceFilterSettings(const Request& request)
* Sets the enable state of a source filter. * Sets the enable state of a source filter.
* *
* @requestField sourceName | String | Name of the source the filter is on * @requestField sourceName | String | Name of the source the filter is on
* @requestField filterName | Number | Name of the filter * @requestField filterName | String | Name of the filter
* @requestField filterEnabled | Boolean | New enable state of the filter * @requestField filterEnabled | Boolean | New enable state of the filter
* *
* @requestType SetSourceFilterEnabled * @requestType SetSourceFilterEnabled

View File

@ -18,6 +18,7 @@ with this program. If not, see <https://www.gnu.org/licenses/>
*/ */
#include <QImageWriter> #include <QImageWriter>
#include <QSysInfo>
#include "RequestHandler.h" #include "RequestHandler.h"
#include "../websocketserver/WebSocketServer.h" #include "../websocketserver/WebSocketServer.h"
@ -25,7 +26,6 @@ with this program. If not, see <https://www.gnu.org/licenses/>
#include "../WebSocketApi.h" #include "../WebSocketApi.h"
#include "../obs-websocket.h" #include "../obs-websocket.h"
/** /**
* Gets data about the current plugin and RPC version. * Gets data about the current plugin and RPC version.
* *
@ -34,6 +34,8 @@ with this program. If not, see <https://www.gnu.org/licenses/>
* @responseField rpcVersion | Number | Current latest obs-websocket RPC version * @responseField rpcVersion | Number | Current latest obs-websocket RPC version
* @responseField availableRequests | Array<String> | Array of available RPC requests for the currently negotiated RPC version * @responseField availableRequests | Array<String> | Array of available RPC requests for the currently negotiated RPC version
* @responseField supportedImageFormats | Array<String> | Image formats available in `GetSourceScreenshot` and `SaveSourceScreenshot` requests. * @responseField supportedImageFormats | Array<String> | Image formats available in `GetSourceScreenshot` and `SaveSourceScreenshot` requests.
* @responseField platform | String | Name of the platform. Usually `windows`, `macos`, or `ubuntu` (linux flavor). Not guaranteed to be any of those
* @responseField platformDescription | String | Description of the platform, like `Windows 10 (10.0)`
* *
* @requestType GetVersion * @requestType GetVersion
* @complexity 1 * @complexity 1
@ -57,6 +59,9 @@ RequestResult RequestHandler::GetVersion(const Request&)
} }
responseData["supportedImageFormats"] = supportedImageFormats; responseData["supportedImageFormats"] = supportedImageFormats;
responseData["platform"] = QSysInfo::productType().toStdString();
responseData["platformDescription"] = QSysInfo::prettyProductName().toStdString();
return RequestResult::Success(responseData); return RequestResult::Success(responseData);
} }
@ -86,8 +91,13 @@ RequestResult RequestHandler::GetStats(const Request&)
{ {
json responseData = Utils::Obs::ObjectHelper::GetStats(); json responseData = Utils::Obs::ObjectHelper::GetStats();
if (_session) {
responseData["webSocketSessionIncomingMessages"] = _session->IncomingMessages(); responseData["webSocketSessionIncomingMessages"] = _session->IncomingMessages();
responseData["webSocketSessionOutgoingMessages"] = _session->OutgoingMessages(); responseData["webSocketSessionOutgoingMessages"] = _session->OutgoingMessages();
} else {
responseData["webSocketSessionIncomingMessages"] = nullptr;
responseData["webSocketSessionOutgoingMessages"] = nullptr;
}
return RequestResult::Success(responseData); return RequestResult::Success(responseData);
} }
@ -130,6 +140,8 @@ RequestResult RequestHandler::BroadcastCustomEvent(const Request& request)
* @requestField requestType | String | The request type to call * @requestField requestType | String | The request type to call
* @requestField ?requestData | Object | Object containing appropriate request data | {} * @requestField ?requestData | Object | Object containing appropriate request data | {}
* *
* @responseField vendorName | String | Echoed of `vendorName`
* @responseField requestType | String | Echoed of `requestType`
* @responseField responseData | Object | Object containing appropriate response data. {} if request does not provide any response data * @responseField responseData | Object | Object containing appropriate response data. {} if request does not provide any response data
* *
* @requestType CallVendorRequest * @requestType CallVendorRequest
@ -143,7 +155,8 @@ RequestResult RequestHandler::CallVendorRequest(const Request& request)
{ {
RequestStatus::RequestStatus statusCode; RequestStatus::RequestStatus statusCode;
std::string comment; std::string comment;
if (!request.ValidateString("vendorName", statusCode, comment) || !request.ValidateString("requestType", statusCode, comment)) if (!request.ValidateString("vendorName", statusCode, comment) ||
!request.ValidateString("requestType", statusCode, comment))
return RequestResult::Error(statusCode, comment); return RequestResult::Error(statusCode, comment);
std::string vendorName = request.RequestData["vendorName"]; std::string vendorName = request.RequestData["vendorName"];
@ -161,7 +174,8 @@ RequestResult RequestHandler::CallVendorRequest(const Request& request)
auto webSocketApi = GetWebSocketApi(); auto webSocketApi = GetWebSocketApi();
if (!webSocketApi) if (!webSocketApi)
return RequestResult::Error(RequestStatus::RequestProcessingFailed, "Unable to call request due to internal error."); return RequestResult::Error(RequestStatus::RequestProcessingFailed,
"Unable to call request due to internal error.");
auto ret = webSocketApi->PerformVendorRequest(vendorName, requestType, requestData, obsResponseData); auto ret = webSocketApi->PerformVendorRequest(vendorName, requestType, requestData, obsResponseData);
switch (ret) { switch (ret) {
@ -175,6 +189,8 @@ RequestResult RequestHandler::CallVendorRequest(const Request& request)
} }
json responseData; json responseData;
responseData["vendorName"] = vendorName;
responseData["requestType"] = requestType;
responseData["responseData"] = Utils::Json::ObsDataToJson(obsResponseData); responseData["responseData"] = Utils::Json::ObsDataToJson(obsResponseData);
return RequestResult::Success(responseData); return RequestResult::Success(responseData);
@ -266,19 +282,23 @@ RequestResult RequestHandler::TriggerHotkeyByKeySequence(const Request& request)
const json keyModifiersJson = request.RequestData["keyModifiers"]; const json keyModifiersJson = request.RequestData["keyModifiers"];
uint32_t keyModifiers = 0; uint32_t keyModifiers = 0;
if (keyModifiersJson.contains("shift") && keyModifiersJson["shift"].is_boolean() && keyModifiersJson["shift"].get<bool>()) if (keyModifiersJson.contains("shift") && keyModifiersJson["shift"].is_boolean() &&
keyModifiersJson["shift"].get<bool>())
keyModifiers |= INTERACT_SHIFT_KEY; keyModifiers |= INTERACT_SHIFT_KEY;
if (keyModifiersJson.contains("control") && keyModifiersJson["control"].is_boolean() && keyModifiersJson["control"].get<bool>()) if (keyModifiersJson.contains("control") && keyModifiersJson["control"].is_boolean() &&
keyModifiersJson["control"].get<bool>())
keyModifiers |= INTERACT_CONTROL_KEY; keyModifiers |= INTERACT_CONTROL_KEY;
if (keyModifiersJson.contains("alt") && keyModifiersJson["alt"].is_boolean() && keyModifiersJson["alt"].get<bool>()) if (keyModifiersJson.contains("alt") && keyModifiersJson["alt"].is_boolean() && keyModifiersJson["alt"].get<bool>())
keyModifiers |= INTERACT_ALT_KEY; keyModifiers |= INTERACT_ALT_KEY;
if (keyModifiersJson.contains("command") && keyModifiersJson["command"].is_boolean() && keyModifiersJson["command"].get<bool>()) if (keyModifiersJson.contains("command") && keyModifiersJson["command"].is_boolean() &&
keyModifiersJson["command"].get<bool>())
keyModifiers |= INTERACT_COMMAND_KEY; keyModifiers |= INTERACT_COMMAND_KEY;
combo.modifiers = keyModifiers; combo.modifiers = keyModifiers;
} }
if (!combo.modifiers && (combo.key == OBS_KEY_NONE || combo.key >= OBS_KEY_LAST_VALUE)) if (!combo.modifiers && (combo.key == OBS_KEY_NONE || combo.key >= OBS_KEY_LAST_VALUE))
return RequestResult::Error(RequestStatus::CannotAct, "Your provided request fields cannot be used to trigger a hotkey."); return RequestResult::Error(RequestStatus::CannotAct,
"Your provided request fields cannot be used to trigger a hotkey.");
// Apparently things break when you don't start by setting the combo to false // Apparently things break when you don't start by setting the combo to false
obs_hotkey_inject_event(combo, false); obs_hotkey_inject_event(combo, false);

View File

@ -143,7 +143,8 @@ RequestResult RequestHandler::CreateInput(const Request& request)
RequestStatus::RequestStatus statusCode; RequestStatus::RequestStatus statusCode;
std::string comment; std::string comment;
OBSSourceAutoRelease sceneSource = request.ValidateScene("sceneName", statusCode, comment); OBSSourceAutoRelease sceneSource = request.ValidateScene("sceneName", statusCode, comment);
if (!(sceneSource && request.ValidateString("inputName", statusCode, comment) && request.ValidateString("inputKind", statusCode, comment))) if (!(sceneSource && request.ValidateString("inputName", statusCode, comment) &&
request.ValidateString("inputKind", statusCode, comment)))
return RequestResult::Error(statusCode, comment); return RequestResult::Error(statusCode, comment);
std::string inputName = request.RequestData["inputName"]; std::string inputName = request.RequestData["inputName"];
@ -154,7 +155,9 @@ RequestResult RequestHandler::CreateInput(const Request& request)
std::string inputKind = request.RequestData["inputKind"]; std::string inputKind = request.RequestData["inputKind"];
auto kinds = Utils::Obs::ArrayHelper::GetInputKindList(); auto kinds = Utils::Obs::ArrayHelper::GetInputKindList();
if (std::find(kinds.begin(), kinds.end(), inputKind) == kinds.end()) if (std::find(kinds.begin(), kinds.end(), inputKind) == kinds.end())
return RequestResult::Error(RequestStatus::InvalidInputKind, "Your specified input kind is not supported by OBS. Check that your specified kind is properly versioned and that any necessary plugins are loaded."); return RequestResult::Error(
RequestStatus::InvalidInputKind,
"Your specified input kind is not supported by OBS. Check that your specified kind is properly versioned and that any necessary plugins are loaded.");
OBSDataAutoRelease inputSettings = nullptr; OBSDataAutoRelease inputSettings = nullptr;
if (request.Contains("inputSettings")) { if (request.Contains("inputSettings")) {
@ -175,7 +178,8 @@ RequestResult RequestHandler::CreateInput(const Request& request)
} }
// Create the input and add it as a scene item to the destination scene // Create the input and add it as a scene item to the destination scene
OBSSceneItemAutoRelease sceneItem = Utils::Obs::ActionHelper::CreateInput(inputName, inputKind, inputSettings, scene, sceneItemEnabled); OBSSceneItemAutoRelease sceneItem =
Utils::Obs::ActionHelper::CreateInput(inputName, inputKind, inputSettings, scene, sceneItemEnabled);
if (!sceneItem) if (!sceneItem)
return RequestResult::Error(RequestStatus::ResourceCreationFailed, "Creation of the input or scene item failed."); return RequestResult::Error(RequestStatus::ResourceCreationFailed, "Creation of the input or scene item failed.");
@ -240,7 +244,8 @@ RequestResult RequestHandler::SetInputName(const Request& request)
OBSSourceAutoRelease existingSource = obs_get_source_by_name(newInputName.c_str()); OBSSourceAutoRelease existingSource = obs_get_source_by_name(newInputName.c_str());
if (existingSource) if (existingSource)
return RequestResult::Error(RequestStatus::ResourceAlreadyExists, "A source already exists by that new input name."); return RequestResult::Error(RequestStatus::ResourceAlreadyExists,
"A source already exists by that new input name.");
obs_source_set_name(input, newInputName.c_str()); obs_source_set_name(input, newInputName.c_str());
@ -349,7 +354,8 @@ RequestResult RequestHandler::SetInputSettings(const Request& request)
OBSDataAutoRelease newSettings = Utils::Json::JsonToObsData(request.RequestData["inputSettings"]); OBSDataAutoRelease newSettings = Utils::Json::JsonToObsData(request.RequestData["inputSettings"]);
if (!newSettings) if (!newSettings)
// This should never happen // This should never happen
return RequestResult::Error(RequestStatus::RequestProcessingFailed, "An internal data conversion operation failed. Please report this!"); return RequestResult::Error(RequestStatus::RequestProcessingFailed,
"An internal data conversion operation failed. Please report this!");
if (overlay) if (overlay)
// Applies the new settings on top of the existing user settings // Applies the new settings on top of the existing user settings
@ -672,6 +678,7 @@ RequestResult RequestHandler::SetInputAudioSyncOffset(const Request& request)
* Gets the audio monitor type of an input. * Gets the audio monitor type of an input.
* *
* The available audio monitor types are: * The available audio monitor types are:
*
* - `OBS_MONITORING_TYPE_NONE` * - `OBS_MONITORING_TYPE_NONE`
* - `OBS_MONITORING_TYPE_MONITOR_ONLY` * - `OBS_MONITORING_TYPE_MONITOR_ONLY`
* - `OBS_MONITORING_TYPE_MONITOR_AND_OUTPUT` * - `OBS_MONITORING_TYPE_MONITOR_AND_OUTPUT`
@ -699,7 +706,7 @@ RequestResult RequestHandler::GetInputAudioMonitorType(const Request& request)
return RequestResult::Error(RequestStatus::InvalidResourceState, "The specified input does not support audio."); return RequestResult::Error(RequestStatus::InvalidResourceState, "The specified input does not support audio.");
json responseData; json responseData;
responseData["monitorType"] = Utils::Obs::StringHelper::GetInputMonitorType(input); responseData["monitorType"] = obs_source_get_monitoring_type(input);
return RequestResult::Success(responseData); return RequestResult::Success(responseData);
} }
@ -729,7 +736,8 @@ RequestResult RequestHandler::SetInputAudioMonitorType(const Request& request)
return RequestResult::Error(RequestStatus::InvalidResourceState, "The specified input does not support audio."); return RequestResult::Error(RequestStatus::InvalidResourceState, "The specified input does not support audio.");
if (!obs_audio_monitoring_available()) if (!obs_audio_monitoring_available())
return RequestResult::Error(RequestStatus::InvalidResourceState, "Audio monitoring is not available on this platform."); return RequestResult::Error(RequestStatus::InvalidResourceState,
"Audio monitoring is not available on this platform.");
enum obs_monitoring_type monitorType; enum obs_monitoring_type monitorType;
std::string monitorTypeString = request.RequestData["monitorType"]; std::string monitorTypeString = request.RequestData["monitorType"];
@ -740,7 +748,8 @@ RequestResult RequestHandler::SetInputAudioMonitorType(const Request& request)
else if (monitorTypeString == "OBS_MONITORING_TYPE_MONITOR_AND_OUTPUT") else if (monitorTypeString == "OBS_MONITORING_TYPE_MONITOR_AND_OUTPUT")
monitorType = OBS_MONITORING_TYPE_MONITOR_AND_OUTPUT; monitorType = OBS_MONITORING_TYPE_MONITOR_AND_OUTPUT;
else else
return RequestResult::Error(RequestStatus::InvalidRequestField, std::string("Unknown monitor type: ") + monitorTypeString); return RequestResult::Error(RequestStatus::InvalidRequestField,
std::string("Unknown monitor type: ") + monitorTypeString);
obs_source_set_monitoring_type(input, monitorType); obs_source_set_monitoring_type(input, monitorType);
@ -820,7 +829,8 @@ RequestResult RequestHandler::SetInputAudioTracks(const Request& request)
continue; continue;
if (!inputAudioTracks[track].is_boolean()) if (!inputAudioTracks[track].is_boolean())
return RequestResult::Error(RequestStatus::InvalidRequestFieldType, "The value of one of your tracks is not a boolean."); return RequestResult::Error(RequestStatus::InvalidRequestFieldType,
"The value of one of your tracks is not a boolean.");
bool enabled = inputAudioTracks[track]; bool enabled = inputAudioTracks[track];

View File

@ -29,6 +29,7 @@ bool IsMediaTimeValid(obs_source_t *input)
* Gets the status of a media input. * Gets the status of a media input.
* *
* Media States: * Media States:
*
* - `OBS_MEDIA_STATE_NONE` * - `OBS_MEDIA_STATE_NONE`
* - `OBS_MEDIA_STATE_PLAYING` * - `OBS_MEDIA_STATE_PLAYING`
* - `OBS_MEDIA_STATE_OPENING` * - `OBS_MEDIA_STATE_OPENING`
@ -60,7 +61,8 @@ RequestResult RequestHandler::GetMediaInputStatus(const Request& request)
return RequestResult::Error(statusCode, comment); return RequestResult::Error(statusCode, comment);
json responseData; json responseData;
responseData["mediaState"] = Utils::Obs::StringHelper::GetMediaInputState(input); responseData["mediaState"] = obs_source_media_get_state(input);
;
if (IsMediaTimeValid(input)) { if (IsMediaTimeValid(input)) {
responseData["mediaDuration"] = obs_source_media_get_duration(input); responseData["mediaDuration"] = obs_source_media_get_duration(input);
@ -97,7 +99,8 @@ RequestResult RequestHandler::SetMediaInputCursor(const Request& request)
return RequestResult::Error(statusCode, comment); return RequestResult::Error(statusCode, comment);
if (!IsMediaTimeValid(input)) if (!IsMediaTimeValid(input))
return RequestResult::Error(RequestStatus::InvalidResourceState, "The media input must be playing or paused in order to set the cursor position."); return RequestResult::Error(RequestStatus::InvalidResourceState,
"The media input must be playing or paused in order to set the cursor position.");
int64_t mediaCursor = request.RequestData["mediaCursor"]; int64_t mediaCursor = request.RequestData["mediaCursor"];
@ -131,7 +134,8 @@ RequestResult RequestHandler::OffsetMediaInputCursor(const Request& request)
return RequestResult::Error(statusCode, comment); return RequestResult::Error(statusCode, comment);
if (!IsMediaTimeValid(input)) if (!IsMediaTimeValid(input))
return RequestResult::Error(RequestStatus::InvalidResourceState, "The media input must be playing or paused in order to set the cursor position."); return RequestResult::Error(RequestStatus::InvalidResourceState,
"The media input must be playing or paused in order to set the cursor position.");
int64_t mediaCursorOffset = request.RequestData["mediaCursorOffset"]; int64_t mediaCursorOffset = request.RequestData["mediaCursorOffset"];
int64_t mediaCursor = obs_source_media_get_time(input) + mediaCursorOffset; int64_t mediaCursor = obs_source_media_get_time(input) + mediaCursorOffset;
@ -165,13 +169,13 @@ RequestResult RequestHandler::TriggerMediaInputAction(const Request& request)
if (!(input && request.ValidateString("mediaAction", statusCode, comment))) if (!(input && request.ValidateString("mediaAction", statusCode, comment)))
return RequestResult::Error(statusCode, comment); return RequestResult::Error(statusCode, comment);
std::string mediaActionString = request.RequestData["mediaAction"]; enum ObsMediaInputAction mediaAction = request.RequestData["mediaAction"];
auto mediaAction = Utils::Obs::EnumHelper::GetMediaInputAction(mediaActionString);
switch (mediaAction) { switch (mediaAction) {
default: default:
case OBS_WEBSOCKET_MEDIA_INPUT_ACTION_NONE: case OBS_WEBSOCKET_MEDIA_INPUT_ACTION_NONE:
return RequestResult::Error(RequestStatus::InvalidRequestField, "You have specified an invalid media input action."); return RequestResult::Error(RequestStatus::InvalidRequestField,
"You have specified an invalid media input action.");
case OBS_WEBSOCKET_MEDIA_INPUT_ACTION_PLAY: case OBS_WEBSOCKET_MEDIA_INPUT_ACTION_PLAY:
// Shoutout to whoever implemented this API call like this // Shoutout to whoever implemented this API call like this
obs_source_media_play_pause(input, false); obs_source_media_play_pause(input, false);

View File

@ -272,6 +272,217 @@ RequestResult RequestHandler::GetLastReplayBufferReplay(const Request&)
return RequestResult::Error(RequestStatus::OutputNotRunning); return RequestResult::Error(RequestStatus::OutputNotRunning);
json responseData; json responseData;
responseData["savedReplayPath"] = Utils::Obs::StringHelper::GetLastReplayBufferFilePath(); responseData["savedReplayPath"] = Utils::Obs::StringHelper::GetLastReplayBufferFileName();
return RequestResult::Success(responseData); return RequestResult::Success(responseData);
} }
/**
* Gets the list of available outputs.
*
* @requestType GetOutputList
* @complexity 4
* @rpcVersion -1
* @initialVersion 5.0.0
* @api requests
* @category outputs
*/
RequestResult RequestHandler::GetOutputList(const Request &)
{
json responseData;
responseData["outputs"] = Utils::Obs::ArrayHelper::GetOutputList();
return RequestResult::Success(responseData);
}
/**
* Gets the status of an output.
*
* @requestField outputName | String | Output name
*
* @responseField outputActive | Boolean | Whether the output is active
* @responseField outputReconnecting | Boolean | Whether the output is reconnecting
* @responseField outputTimecode | String | Current formatted timecode string for the output
* @responseField outputDuration | Number | Current duration in milliseconds for the output
* @responseField outputCongestion | Number | Congestion of the output
* @responseField outputBytes | Number | Number of bytes sent by the output
* @responseField outputSkippedFrames | Number | Number of frames skipped by the output's process
* @responseField outputTotalFrames | Number | Total number of frames delivered by the output's process
*
* @requestType GetOutputStatus
* @complexity 4
* @rpcVersion -1
* @initialVersion 5.0.0
* @api requests
* @category outputs
*/
RequestResult RequestHandler::GetOutputStatus(const Request &request)
{
RequestStatus::RequestStatus statusCode;
std::string comment;
OBSOutputAutoRelease output = request.ValidateOutput("outputName", statusCode, comment);
if (!output)
return RequestResult::Error(statusCode, comment);
uint64_t outputDuration = Utils::Obs::NumberHelper::GetOutputDuration(output);
json responseData;
responseData["outputActive"] = obs_output_active(output);
responseData["outputReconnecting"] = obs_output_reconnecting(output);
responseData["outputTimecode"] = Utils::Obs::StringHelper::DurationToTimecode(outputDuration);
responseData["outputDuration"] = outputDuration;
responseData["outputCongestion"] = obs_output_get_congestion(output);
responseData["outputBytes"] = obs_output_get_total_bytes(output);
responseData["outputSkippedFrames"] = obs_output_get_frames_dropped(output);
responseData["outputTotalFrames"] = obs_output_get_total_frames(output);
return RequestResult::Success(responseData);
}
/**
* Toggles the status of an output.
*
* @requestField outputName | String | Output name
*
* @responseField outputActive | Boolean | Whether the output is active
*
* @requestType ToggleOutput
* @complexity 4
* @rpcVersion -1
* @initialVersion 5.0.0
* @api requests
* @category outputs
*/
RequestResult RequestHandler::ToggleOutput(const Request &request)
{
RequestStatus::RequestStatus statusCode;
std::string comment;
OBSOutputAutoRelease output = request.ValidateOutput("outputName", statusCode, comment);
if (!output)
return RequestResult::Error(statusCode, comment);
bool outputActive = obs_output_active(output);
if (outputActive)
obs_output_stop(output);
else
obs_output_start(output);
json responseData;
responseData["outputActive"] = !outputActive;
return RequestResult::Success(responseData);
}
/**
* Starts an output.
*
* @requestField outputName | String | Output name
*
* @requestType StartOutput
* @complexity 4
* @rpcVersion -1
* @initialVersion 5.0.0
* @api requests
* @category outputs
*/
RequestResult RequestHandler::StartOutput(const Request &request)
{
RequestStatus::RequestStatus statusCode;
std::string comment;
OBSOutputAutoRelease output = request.ValidateOutput("outputName", statusCode, comment);
if (!output)
return RequestResult::Error(statusCode, comment);
if (obs_output_active(output))
return RequestResult::Error(RequestStatus::OutputRunning);
obs_output_start(output);
return RequestResult::Success();
}
/**
* Stops an output.
*
* @requestField outputName | String | Output name
*
* @requestType StopOutput
* @complexity 4
* @rpcVersion -1
* @initialVersion 5.0.0
* @api requests
* @category outputs
*/
RequestResult RequestHandler::StopOutput(const Request &request)
{
RequestStatus::RequestStatus statusCode;
std::string comment;
OBSOutputAutoRelease output = request.ValidateOutput("outputName", statusCode, comment);
if (!output)
return RequestResult::Error(statusCode, comment);
if (!obs_output_active(output))
return RequestResult::Error(RequestStatus::OutputNotRunning);
obs_output_stop(output);
return RequestResult::Success();
}
/**
* Gets the settings of an output.
*
* @requestField outputName | String | Output name
*
* @responseField outputSettings | Object | Output settings
*
* @requestType GetOutputSettings
* @complexity 4
* @rpcVersion -1
* @initialVersion 5.0.0
* @api requests
* @category outputs
*/
RequestResult RequestHandler::GetOutputSettings(const Request &request)
{
RequestStatus::RequestStatus statusCode;
std::string comment;
OBSOutputAutoRelease output = request.ValidateOutput("outputName", statusCode, comment);
if (!output)
return RequestResult::Error(statusCode, comment);
OBSDataAutoRelease outputSettings = obs_output_get_settings(output);
json responseData;
responseData["outputSettings"] = Utils::Json::ObsDataToJson(outputSettings);
return RequestResult::Success(responseData);
}
/**
* Sets the settings of an output.
*
* @requestField outputName | String | Output name
* @requestField outputSettings | Object | Output settings
*
* @requestType SetOutputSettings
* @complexity 4
* @rpcVersion -1
* @initialVersion 5.0.0
* @api requests
* @category outputs
*/
RequestResult RequestHandler::SetOutputSettings(const Request &request)
{
RequestStatus::RequestStatus statusCode;
std::string comment;
OBSOutputAutoRelease output = request.ValidateOutput("outputName", statusCode, comment);
if (!(output && request.ValidateObject("outputSettings", statusCode, comment, true)))
return RequestResult::Error(statusCode, comment);
OBSDataAutoRelease newSettings = Utils::Json::JsonToObsData(request.RequestData["outputSettings"]);
if (!newSettings)
// This should never happen
return RequestResult::Error(RequestStatus::RequestProcessingFailed,
"An internal data conversion operation failed. Please report this!");
obs_output_update(output, newSettings);
return RequestResult::Success();
}

View File

@ -99,6 +99,8 @@ RequestResult RequestHandler::StartRecord(const Request&)
/** /**
* Stops the record output. * Stops the record output.
* *
* @responseField outputPath | String | File name for the saved recording
*
* @requestType StopRecord * @requestType StopRecord
* @complexity 1 * @complexity 1
* @rpcVersion -1 * @rpcVersion -1
@ -114,7 +116,10 @@ RequestResult RequestHandler::StopRecord(const Request&)
// TODO: Call signal directly to perform blocking wait // TODO: Call signal directly to perform blocking wait
obs_frontend_recording_stop(); obs_frontend_recording_stop();
return RequestResult::Success(); json responseData;
responseData["outputPath"] = Utils::Obs::StringHelper::GetLastRecordFileName();
return RequestResult::Success(responseData);
} }
/** /**

View File

@ -88,6 +88,7 @@ RequestResult RequestHandler::GetGroupSceneItemList(const Request& request)
* *
* @requestField sceneName | String | Name of the scene or group to search in * @requestField sceneName | String | Name of the scene or group to search in
* @requestField sourceName | String | Name of the source to find * @requestField sourceName | String | Name of the source to find
* @requestField ?searchOffset | Number | Number of matches to skip during search. >= 0 means first forward. -1 means last (top) item | >= -1 | 0
* *
* @responseField sceneItemId | Number | Numeric ID of the scene item * @responseField sceneItemId | Number | Numeric ID of the scene item
* *
@ -102,15 +103,24 @@ RequestResult RequestHandler::GetSceneItemId(const Request& request)
{ {
RequestStatus::RequestStatus statusCode; RequestStatus::RequestStatus statusCode;
std::string comment; std::string comment;
OBSSceneAutoRelease scene = request.ValidateScene2("sceneName", statusCode, comment, OBS_WEBSOCKET_SCENE_FILTER_SCENE_OR_GROUP); OBSSceneAutoRelease scene =
request.ValidateScene2("sceneName", statusCode, comment, OBS_WEBSOCKET_SCENE_FILTER_SCENE_OR_GROUP);
if (!(scene && request.ValidateString("sourceName", statusCode, comment))) if (!(scene && request.ValidateString("sourceName", statusCode, comment)))
return RequestResult::Error(statusCode, comment); return RequestResult::Error(statusCode, comment);
std::string sourceName = request.RequestData["sourceName"]; std::string sourceName = request.RequestData["sourceName"];
OBSSceneItemAutoRelease item = Utils::Obs::SearchHelper::GetSceneItemByName(scene, sourceName); int offset = 0;
if (request.Contains("searchOffset")) {
if (!request.ValidateOptionalNumber("searchOffset", statusCode, comment, -1))
return RequestResult::Error(statusCode, comment);
offset = request.RequestData["searchOffset"];
}
OBSSceneItemAutoRelease item = Utils::Obs::SearchHelper::GetSceneItemByName(scene, sourceName, offset);
if (!item) if (!item)
return RequestResult::Error(RequestStatus::ResourceNotFound, "No scene items were found in the specified scene by that name."); return RequestResult::Error(RequestStatus::ResourceNotFound,
"No scene items were found in the specified scene by that name or offset.");
json responseData; json responseData;
responseData["sceneItemId"] = obs_sceneitem_get_id(item); responseData["sceneItemId"] = obs_sceneitem_get_id(item);
@ -234,7 +244,8 @@ RequestResult RequestHandler::DuplicateSceneItem(const Request& request)
} else { } else {
destinationScene = obs_scene_get_ref(obs_sceneitem_get_scene(sceneItem)); destinationScene = obs_scene_get_ref(obs_sceneitem_get_scene(sceneItem));
if (!destinationScene) if (!destinationScene)
return RequestResult::Error(RequestStatus::RequestProcessingFailed, "Internal error: Failed to get ref for scene of scene item."); return RequestResult::Error(RequestStatus::RequestProcessingFailed,
"Internal error: Failed to get ref for scene of scene item.");
} }
if (obs_sceneitem_is_group(sceneItem) && obs_sceneitem_get_scene(sceneItem) == destinationScene) { if (obs_sceneitem_is_group(sceneItem) && obs_sceneitem_get_scene(sceneItem) == destinationScene) {
@ -251,7 +262,8 @@ RequestResult RequestHandler::DuplicateSceneItem(const Request& request)
obs_sceneitem_get_crop(sceneItem, &sceneItemCrop); obs_sceneitem_get_crop(sceneItem, &sceneItemCrop);
// Create the new item // Create the new item
OBSSceneItemAutoRelease newSceneItem = Utils::Obs::ActionHelper::CreateSceneItem(sceneItemSource, destinationScene, sceneItemEnabled, &sceneItemTransform, &sceneItemCrop); OBSSceneItemAutoRelease newSceneItem = Utils::Obs::ActionHelper::CreateSceneItem(
sceneItemSource, destinationScene, sceneItemEnabled, &sceneItemTransform, &sceneItemCrop);
obs_scene_release(destinationScene); obs_scene_release(destinationScene);
if (!newSceneItem) if (!newSceneItem)
return RequestResult::Error(RequestStatus::ResourceCreationFailed, "Failed to create the scene item."); return RequestResult::Error(RequestStatus::ResourceCreationFailed, "Failed to create the scene item.");
@ -283,7 +295,8 @@ RequestResult RequestHandler::GetSceneItemTransform(const Request& request)
{ {
RequestStatus::RequestStatus statusCode; RequestStatus::RequestStatus statusCode;
std::string comment; std::string comment;
OBSSceneItemAutoRelease sceneItem = request.ValidateSceneItem("sceneName", "sceneItemId", statusCode, comment, OBS_WEBSOCKET_SCENE_FILTER_SCENE_OR_GROUP); OBSSceneItemAutoRelease sceneItem = request.ValidateSceneItem("sceneName", "sceneItemId", statusCode, comment,
OBS_WEBSOCKET_SCENE_FILTER_SCENE_OR_GROUP);
if (!sceneItem) if (!sceneItem)
return RequestResult::Error(statusCode, comment); return RequestResult::Error(statusCode, comment);
@ -311,7 +324,8 @@ RequestResult RequestHandler::SetSceneItemTransform(const Request& request)
{ {
RequestStatus::RequestStatus statusCode; RequestStatus::RequestStatus statusCode;
std::string comment; std::string comment;
OBSSceneItemAutoRelease sceneItem = request.ValidateSceneItem("sceneName", "sceneItemId", statusCode, comment, OBS_WEBSOCKET_SCENE_FILTER_SCENE_OR_GROUP); OBSSceneItemAutoRelease sceneItem = request.ValidateSceneItem("sceneName", "sceneItemId", statusCode, comment,
OBS_WEBSOCKET_SCENE_FILTER_SCENE_OR_GROUP);
if (!(sceneItem && request.ValidateObject("sceneItemTransform", statusCode, comment))) if (!(sceneItem && request.ValidateObject("sceneItemTransform", statusCode, comment)))
return RequestResult::Error(statusCode, comment); return RequestResult::Error(statusCode, comment);
@ -355,7 +369,8 @@ RequestResult RequestHandler::SetSceneItemTransform(const Request& request)
float scaleX = r.RequestData["scaleX"]; float scaleX = r.RequestData["scaleX"];
float finalWidth = scaleX * sourceWidth; float finalWidth = scaleX * sourceWidth;
if (!(finalWidth > -90001.0 && finalWidth < 90001.0)) if (!(finalWidth > -90001.0 && finalWidth < 90001.0))
return RequestResult::Error(RequestStatus::RequestFieldOutOfRange, "The field scaleX is too small or large for the current source resolution."); return RequestResult::Error(RequestStatus::RequestFieldOutOfRange,
"The field `scaleX` is too small or large for the current source resolution.");
sceneItemTransform.scale.x = scaleX; sceneItemTransform.scale.x = scaleX;
transformChanged = true; transformChanged = true;
} }
@ -365,7 +380,8 @@ RequestResult RequestHandler::SetSceneItemTransform(const Request& request)
float scaleY = r.RequestData["scaleY"]; float scaleY = r.RequestData["scaleY"];
float finalHeight = scaleY * sourceHeight; float finalHeight = scaleY * sourceHeight;
if (!(finalHeight > -90001.0 && finalHeight < 90001.0)) if (!(finalHeight > -90001.0 && finalHeight < 90001.0))
return RequestResult::Error(RequestStatus::RequestFieldOutOfRange, "The field scaleY is too small or large for the current source resolution."); return RequestResult::Error(RequestStatus::RequestFieldOutOfRange,
"The field `scaleY` is too small or large for the current source resolution.");
sceneItemTransform.scale.y = scaleY; sceneItemTransform.scale.y = scaleY;
transformChanged = true; transformChanged = true;
} }
@ -380,10 +396,10 @@ RequestResult RequestHandler::SetSceneItemTransform(const Request& request)
if (r.Contains("boundsType")) { if (r.Contains("boundsType")) {
if (!r.ValidateOptionalString("boundsType", statusCode, comment)) if (!r.ValidateOptionalString("boundsType", statusCode, comment))
return RequestResult::Error(statusCode, comment); return RequestResult::Error(statusCode, comment);
std::string boundsTypeString = r.RequestData["boundsType"]; enum obs_bounds_type boundsType = r.RequestData["boundsType"];
enum obs_bounds_type boundsType = Utils::Obs::EnumHelper::GetSceneItemBoundsType(boundsTypeString); if (boundsType == OBS_BOUNDS_NONE && r.RequestData["boundsType"] != "OBS_BOUNDS_NONE")
if (boundsType == OBS_BOUNDS_NONE && boundsTypeString != "OBS_BOUNDS_NONE") return RequestResult::Error(RequestStatus::InvalidRequestField,
return RequestResult::Error(RequestStatus::InvalidRequestField, "The field boundsType has an invalid value."); "The field `boundsType` has an invalid value.");
sceneItemTransform.bounds_type = boundsType; sceneItemTransform.bounds_type = boundsType;
transformChanged = true; transformChanged = true;
} }
@ -466,7 +482,8 @@ RequestResult RequestHandler::GetSceneItemEnabled(const Request& request)
{ {
RequestStatus::RequestStatus statusCode; RequestStatus::RequestStatus statusCode;
std::string comment; std::string comment;
OBSSceneItemAutoRelease sceneItem = request.ValidateSceneItem("sceneName", "sceneItemId", statusCode, comment, OBS_WEBSOCKET_SCENE_FILTER_SCENE_OR_GROUP); OBSSceneItemAutoRelease sceneItem = request.ValidateSceneItem("sceneName", "sceneItemId", statusCode, comment,
OBS_WEBSOCKET_SCENE_FILTER_SCENE_OR_GROUP);
if (!sceneItem) if (!sceneItem)
return RequestResult::Error(statusCode, comment); return RequestResult::Error(statusCode, comment);
@ -496,7 +513,8 @@ RequestResult RequestHandler::SetSceneItemEnabled(const Request& request)
{ {
RequestStatus::RequestStatus statusCode; RequestStatus::RequestStatus statusCode;
std::string comment; std::string comment;
OBSSceneItemAutoRelease sceneItem = request.ValidateSceneItem("sceneName", "sceneItemId", statusCode, comment, OBS_WEBSOCKET_SCENE_FILTER_SCENE_OR_GROUP); OBSSceneItemAutoRelease sceneItem = request.ValidateSceneItem("sceneName", "sceneItemId", statusCode, comment,
OBS_WEBSOCKET_SCENE_FILTER_SCENE_OR_GROUP);
if (!(sceneItem && request.ValidateBoolean("sceneItemEnabled", statusCode, comment))) if (!(sceneItem && request.ValidateBoolean("sceneItemEnabled", statusCode, comment)))
return RequestResult::Error(statusCode, comment); return RequestResult::Error(statusCode, comment);
@ -528,7 +546,8 @@ RequestResult RequestHandler::GetSceneItemLocked(const Request& request)
{ {
RequestStatus::RequestStatus statusCode; RequestStatus::RequestStatus statusCode;
std::string comment; std::string comment;
OBSSceneItemAutoRelease sceneItem = request.ValidateSceneItem("sceneName", "sceneItemId", statusCode, comment, OBS_WEBSOCKET_SCENE_FILTER_SCENE_OR_GROUP); OBSSceneItemAutoRelease sceneItem = request.ValidateSceneItem("sceneName", "sceneItemId", statusCode, comment,
OBS_WEBSOCKET_SCENE_FILTER_SCENE_OR_GROUP);
if (!sceneItem) if (!sceneItem)
return RequestResult::Error(statusCode, comment); return RequestResult::Error(statusCode, comment);
@ -558,7 +577,8 @@ RequestResult RequestHandler::SetSceneItemLocked(const Request& request)
{ {
RequestStatus::RequestStatus statusCode; RequestStatus::RequestStatus statusCode;
std::string comment; std::string comment;
OBSSceneItemAutoRelease sceneItem = request.ValidateSceneItem("sceneName", "sceneItemId", statusCode, comment, OBS_WEBSOCKET_SCENE_FILTER_SCENE_OR_GROUP); OBSSceneItemAutoRelease sceneItem = request.ValidateSceneItem("sceneName", "sceneItemId", statusCode, comment,
OBS_WEBSOCKET_SCENE_FILTER_SCENE_OR_GROUP);
if (!(sceneItem && request.ValidateBoolean("sceneItemLocked", statusCode, comment))) if (!(sceneItem && request.ValidateBoolean("sceneItemLocked", statusCode, comment)))
return RequestResult::Error(statusCode, comment); return RequestResult::Error(statusCode, comment);
@ -592,7 +612,8 @@ RequestResult RequestHandler::GetSceneItemIndex(const Request& request)
{ {
RequestStatus::RequestStatus statusCode; RequestStatus::RequestStatus statusCode;
std::string comment; std::string comment;
OBSSceneItemAutoRelease sceneItem = request.ValidateSceneItem("sceneName", "sceneItemId", statusCode, comment, OBS_WEBSOCKET_SCENE_FILTER_SCENE_OR_GROUP); OBSSceneItemAutoRelease sceneItem = request.ValidateSceneItem("sceneName", "sceneItemId", statusCode, comment,
OBS_WEBSOCKET_SCENE_FILTER_SCENE_OR_GROUP);
if (!sceneItem) if (!sceneItem)
return RequestResult::Error(statusCode, comment); return RequestResult::Error(statusCode, comment);
@ -622,7 +643,8 @@ RequestResult RequestHandler::SetSceneItemIndex(const Request& request)
{ {
RequestStatus::RequestStatus statusCode; RequestStatus::RequestStatus statusCode;
std::string comment; std::string comment;
OBSSceneItemAutoRelease sceneItem = request.ValidateSceneItem("sceneName", "sceneItemId", statusCode, comment, OBS_WEBSOCKET_SCENE_FILTER_SCENE_OR_GROUP); OBSSceneItemAutoRelease sceneItem = request.ValidateSceneItem("sceneName", "sceneItemId", statusCode, comment,
OBS_WEBSOCKET_SCENE_FILTER_SCENE_OR_GROUP);
if (!(sceneItem && request.ValidateNumber("sceneItemIndex", statusCode, comment, 0, 8192))) if (!(sceneItem && request.ValidateNumber("sceneItemIndex", statusCode, comment, 0, 8192)))
return RequestResult::Error(statusCode, comment); return RequestResult::Error(statusCode, comment);
@ -664,14 +686,15 @@ RequestResult RequestHandler::GetSceneItemBlendMode(const Request& request)
{ {
RequestStatus::RequestStatus statusCode; RequestStatus::RequestStatus statusCode;
std::string comment; std::string comment;
OBSSceneItemAutoRelease sceneItem = request.ValidateSceneItem("sceneName", "sceneItemId", statusCode, comment, OBS_WEBSOCKET_SCENE_FILTER_SCENE_OR_GROUP); OBSSceneItemAutoRelease sceneItem = request.ValidateSceneItem("sceneName", "sceneItemId", statusCode, comment,
OBS_WEBSOCKET_SCENE_FILTER_SCENE_OR_GROUP);
if (!sceneItem) if (!sceneItem)
return RequestResult::Error(statusCode, comment); return RequestResult::Error(statusCode, comment);
auto blendMode = obs_sceneitem_get_blending_mode(sceneItem); auto blendMode = obs_sceneitem_get_blending_mode(sceneItem);
json responseData; json responseData;
responseData["sceneItemBlendMode"] = Utils::Obs::StringHelper::GetSceneItemBlendMode(blendMode); responseData["sceneItemBlendMode"] = blendMode;
return RequestResult::Success(responseData); return RequestResult::Success(responseData);
} }
@ -696,17 +719,55 @@ RequestResult RequestHandler::SetSceneItemBlendMode(const Request& request)
{ {
RequestStatus::RequestStatus statusCode; RequestStatus::RequestStatus statusCode;
std::string comment; std::string comment;
OBSSceneItemAutoRelease sceneItem = request.ValidateSceneItem("sceneName", "sceneItemId", statusCode, comment, OBS_WEBSOCKET_SCENE_FILTER_SCENE_OR_GROUP); OBSSceneItemAutoRelease sceneItem = request.ValidateSceneItem("sceneName", "sceneItemId", statusCode, comment,
OBS_WEBSOCKET_SCENE_FILTER_SCENE_OR_GROUP);
if (!(sceneItem && request.ValidateString("sceneItemBlendMode", statusCode, comment))) if (!(sceneItem && request.ValidateString("sceneItemBlendMode", statusCode, comment)))
return RequestResult::Error(statusCode, comment); return RequestResult::Error(statusCode, comment);
std::string blendModeString = request.RequestData["sceneItemBlendMode"]; enum obs_blending_type blendMode = request.RequestData["sceneItemBlendMode"];
if (blendMode == OBS_BLEND_NORMAL && request.RequestData["sceneItemBlendMode"] != "OBS_BLEND_NORMAL")
auto blendMode = Utils::Obs::EnumHelper::GetSceneItemBlendMode(blendModeString); return RequestResult::Error(RequestStatus::InvalidRequestField,
if (blendMode == OBS_BLEND_NORMAL && blendModeString != "OBS_BLEND_NORMAL") "The field sceneItemBlendMode has an invalid value.");
return RequestResult::Error(RequestStatus::InvalidRequestField, "The field sceneItemBlendMode has an invalid value.");
obs_sceneitem_set_blending_mode(sceneItem, blendMode); obs_sceneitem_set_blending_mode(sceneItem, blendMode);
return RequestResult::Success(); return RequestResult::Success();
} }
// Intentionally undocumented
RequestResult RequestHandler::GetSceneItemPrivateSettings(const Request &request)
{
RequestStatus::RequestStatus statusCode;
std::string comment;
OBSSceneItemAutoRelease sceneItem = request.ValidateSceneItem("sceneName", "sceneItemId", statusCode, comment,
OBS_WEBSOCKET_SCENE_FILTER_SCENE_OR_GROUP);
if (!sceneItem)
return RequestResult::Error(statusCode, comment);
OBSDataAutoRelease privateSettings = obs_sceneitem_get_private_settings(sceneItem);
json responseData;
responseData["sceneItemSettings"] = Utils::Json::ObsDataToJson(privateSettings);
return RequestResult::Success(responseData);
}
// Intentionally undocumented
RequestResult RequestHandler::SetSceneItemPrivateSettings(const Request &request)
{
RequestStatus::RequestStatus statusCode;
std::string comment;
OBSSceneItemAutoRelease sceneItem = request.ValidateSceneItem("sceneName", "sceneItemId", statusCode, comment,
OBS_WEBSOCKET_SCENE_FILTER_SCENE_OR_GROUP);
if (!sceneItem || !request.ValidateObject("sceneItemSettings", statusCode, comment, true))
return RequestResult::Error(statusCode, comment);
OBSDataAutoRelease privateSettings = obs_sceneitem_get_private_settings(sceneItem);
OBSDataAutoRelease newSettings = Utils::Json::JsonToObsData(request.RequestData["sceneItemSettings"]);
// Always overlays to prevent destroying internal source unintentionally
obs_data_apply(privateSettings, newSettings);
return RequestResult::Success();
}

View File

@ -235,7 +235,8 @@ RequestResult RequestHandler::RemoveScene(const Request& request)
return RequestResult::Error(statusCode, comment); return RequestResult::Error(statusCode, comment);
if (Utils::Obs::NumberHelper::GetSceneCount() < 2) if (Utils::Obs::NumberHelper::GetSceneCount() < 2)
return RequestResult::Error(RequestStatus::NotEnoughResources, "You cannot remove the last scene in the collection."); return RequestResult::Error(RequestStatus::NotEnoughResources,
"You cannot remove the last scene in the collection.");
obs_source_remove(scene); obs_source_remove(scene);
@ -267,7 +268,8 @@ RequestResult RequestHandler::SetSceneName(const Request& request)
OBSSourceAutoRelease existingSource = obs_get_source_by_name(newSceneName.c_str()); OBSSourceAutoRelease existingSource = obs_get_source_by_name(newSceneName.c_str());
if (existingSource) if (existingSource)
return RequestResult::Error(RequestStatus::ResourceAlreadyExists, "A source already exists by that new scene name."); return RequestResult::Error(RequestStatus::ResourceAlreadyExists,
"A source already exists by that new scene name.");
obs_source_set_name(scene, newSceneName.c_str()); obs_source_set_name(scene, newSceneName.c_str());
@ -342,7 +344,8 @@ RequestResult RequestHandler::SetSceneSceneTransitionOverride(const Request& req
if (hasName && !request.RequestData["transitionName"].is_null()) { if (hasName && !request.RequestData["transitionName"].is_null()) {
if (!request.ValidateOptionalString("transitionName", statusCode, comment)) if (!request.ValidateOptionalString("transitionName", statusCode, comment))
return RequestResult::Error(statusCode, comment); return RequestResult::Error(statusCode, comment);
OBSSourceAutoRelease transition = Utils::Obs::SearchHelper::GetSceneTransitionByName(request.RequestData["transitionName"]); OBSSourceAutoRelease transition =
Utils::Obs::SearchHelper::GetSceneTransitionByName(request.RequestData["transitionName"]);
if (!transition) if (!transition)
return RequestResult::Error(RequestStatus::ResourceNotFound, "No scene transition was found by that name."); return RequestResult::Error(RequestStatus::ResourceNotFound, "No scene transition was found by that name.");
} }
@ -354,7 +357,8 @@ RequestResult RequestHandler::SetSceneSceneTransitionOverride(const Request& req
} }
if (!hasName && !hasDuration) if (!hasName && !hasDuration)
return RequestResult::Error(RequestStatus::MissingRequestField, "Your request data must include either `transitionName` or `transitionDuration`."); return RequestResult::Error(RequestStatus::MissingRequestField,
"Your request data must include either `transitionName` or `transitionDuration`.");
if (hasName) { if (hasName) {
if (request.RequestData["transitionName"].is_null()) { if (request.RequestData["transitionName"].is_null()) {

View File

@ -180,7 +180,8 @@ RequestResult RequestHandler::GetSourceScreenshot(const Request& request)
std::string imageFormat = request.RequestData["imageFormat"]; std::string imageFormat = request.RequestData["imageFormat"];
if (!IsImageFormatValid(imageFormat)) if (!IsImageFormatValid(imageFormat))
return RequestResult::Error(RequestStatus::InvalidRequestField, "Your specified image format is invalid or not supported by this system."); return RequestResult::Error(RequestStatus::InvalidRequestField,
"Your specified image format is invalid or not supported by this system.");
uint32_t requestedWidth{0}; uint32_t requestedWidth{0};
uint32_t requestedHeight{0}; uint32_t requestedHeight{0};
@ -258,7 +259,8 @@ RequestResult RequestHandler::SaveSourceScreenshot(const Request& request)
RequestStatus::RequestStatus statusCode; RequestStatus::RequestStatus statusCode;
std::string comment; std::string comment;
OBSSourceAutoRelease source = request.ValidateSource("sourceName", statusCode, comment); OBSSourceAutoRelease source = request.ValidateSource("sourceName", statusCode, comment);
if (!(source && request.ValidateString("imageFormat", statusCode, comment) && request.ValidateString("imageFilePath", statusCode, comment))) if (!(source && request.ValidateString("imageFormat", statusCode, comment) &&
request.ValidateString("imageFilePath", statusCode, comment)))
return RequestResult::Error(statusCode, comment); return RequestResult::Error(statusCode, comment);
if (obs_source_get_type(source) != OBS_SOURCE_TYPE_INPUT && obs_source_get_type(source) != OBS_SOURCE_TYPE_SCENE) if (obs_source_get_type(source) != OBS_SOURCE_TYPE_INPUT && obs_source_get_type(source) != OBS_SOURCE_TYPE_SCENE)
@ -268,7 +270,8 @@ RequestResult RequestHandler::SaveSourceScreenshot(const Request& request)
std::string imageFilePath = request.RequestData["imageFilePath"]; std::string imageFilePath = request.RequestData["imageFilePath"];
if (!IsImageFormatValid(imageFormat)) if (!IsImageFormatValid(imageFormat))
return RequestResult::Error(RequestStatus::InvalidRequestField, "Your specified image format is invalid or not supported by this system."); return RequestResult::Error(RequestStatus::InvalidRequestField,
"Your specified image format is invalid or not supported by this system.");
QFileInfo filePathInfo(QString::fromStdString(imageFilePath)); QFileInfo filePathInfo(QString::fromStdString(imageFilePath));
if (!filePathInfo.absoluteDir().exists()) if (!filePathInfo.absoluteDir().exists())
@ -336,7 +339,7 @@ RequestResult RequestHandler::SetSourcePrivateSettings(const Request& request)
RequestStatus::RequestStatus statusCode; RequestStatus::RequestStatus statusCode;
std::string comment; std::string comment;
OBSSourceAutoRelease source = request.ValidateSource("sourceName", statusCode, comment); OBSSourceAutoRelease source = request.ValidateSource("sourceName", statusCode, comment);
if (!source || !request.ValidateObject("sourceSettings", statusCode, comment)) if (!source || !request.ValidateObject("sourceSettings", statusCode, comment, true))
return RequestResult::Error(statusCode, comment); return RequestResult::Error(statusCode, comment);
OBSDataAutoRelease privateSettings = obs_source_get_private_settings(source); OBSDataAutoRelease privateSettings = obs_source_get_private_settings(source);

View File

@ -26,6 +26,7 @@ with this program. If not, see <https://www.gnu.org/licenses/>
* @responseField outputReconnecting | Boolean | Whether the output is currently reconnecting * @responseField outputReconnecting | Boolean | Whether the output is currently reconnecting
* @responseField outputTimecode | String | Current formatted timecode string for the output * @responseField outputTimecode | String | Current formatted timecode string for the output
* @responseField outputDuration | Number | Current duration in milliseconds for the output * @responseField outputDuration | Number | Current duration in milliseconds for the output
* @responseField outputCongestion | Number | Congestion of the output
* @responseField outputBytes | Number | Number of bytes sent by the output * @responseField outputBytes | Number | Number of bytes sent by the output
* @responseField outputSkippedFrames | Number | Number of frames skipped by the output's process * @responseField outputSkippedFrames | Number | Number of frames skipped by the output's process
* @responseField outputTotalFrames | Number | Total number of frames delivered by the output's process * @responseField outputTotalFrames | Number | Total number of frames delivered by the output's process
@ -48,6 +49,7 @@ RequestResult RequestHandler::GetStreamStatus(const Request&)
responseData["outputReconnecting"] = obs_output_reconnecting(streamOutput); responseData["outputReconnecting"] = obs_output_reconnecting(streamOutput);
responseData["outputTimecode"] = Utils::Obs::StringHelper::DurationToTimecode(outputDuration); responseData["outputTimecode"] = Utils::Obs::StringHelper::DurationToTimecode(outputDuration);
responseData["outputDuration"] = outputDuration; responseData["outputDuration"] = outputDuration;
responseData["outputCongestion"] = obs_output_get_congestion(streamOutput);
responseData["outputBytes"] = (uint64_t)obs_output_get_total_bytes(streamOutput); responseData["outputBytes"] = (uint64_t)obs_output_get_total_bytes(streamOutput);
responseData["outputSkippedFrames"] = obs_output_get_frames_dropped(streamOutput); responseData["outputSkippedFrames"] = obs_output_get_frames_dropped(streamOutput);
responseData["outputTotalFrames"] = obs_output_get_total_frames(streamOutput); responseData["outputTotalFrames"] = obs_output_get_total_frames(streamOutput);

View File

@ -95,7 +95,8 @@ RequestResult RequestHandler::GetCurrentSceneTransition(const Request&)
{ {
OBSSourceAutoRelease transition = obs_frontend_get_current_transition(); OBSSourceAutoRelease transition = obs_frontend_get_current_transition();
if (!transition) if (!transition)
return RequestResult::Error(RequestStatus::InvalidResourceState, "OBS does not currently have a scene transition set."); // This should not happen! return RequestResult::Error(RequestStatus::InvalidResourceState,
"OBS does not currently have a scene transition set."); // This should not happen!
json responseData; json responseData;
responseData["transitionName"] = obs_source_get_name(transition); responseData["transitionName"] = obs_source_get_name(transition);
@ -201,10 +202,12 @@ RequestResult RequestHandler::SetCurrentSceneTransitionSettings(const Request& r
OBSSourceAutoRelease transition = obs_frontend_get_current_transition(); OBSSourceAutoRelease transition = obs_frontend_get_current_transition();
if (!transition) if (!transition)
return RequestResult::Error(RequestStatus::InvalidResourceState, "OBS does not currently have a scene transition set."); // This should not happen! return RequestResult::Error(RequestStatus::InvalidResourceState,
"OBS does not currently have a scene transition set."); // This should not happen!
if (!obs_source_configurable(transition)) if (!obs_source_configurable(transition))
return RequestResult::Error(RequestStatus::ResourceNotConfigurable, "The current transition does not support custom settings."); return RequestResult::Error(RequestStatus::ResourceNotConfigurable,
"The current transition does not support custom settings.");
bool overlay = true; bool overlay = true;
if (request.Contains("overlay")) { if (request.Contains("overlay")) {
@ -216,7 +219,8 @@ RequestResult RequestHandler::SetCurrentSceneTransitionSettings(const Request& r
OBSDataAutoRelease newSettings = Utils::Json::JsonToObsData(request.RequestData["transitionSettings"]); OBSDataAutoRelease newSettings = Utils::Json::JsonToObsData(request.RequestData["transitionSettings"]);
if (!newSettings) if (!newSettings)
return RequestResult::Error(RequestStatus::RequestProcessingFailed, "An internal data conversion operation failed. Please report this!"); return RequestResult::Error(RequestStatus::RequestProcessingFailed,
"An internal data conversion operation failed. Please report this!");
if (overlay) if (overlay)
obs_source_update(transition, newSettings); obs_source_update(transition, newSettings);
@ -246,7 +250,8 @@ RequestResult RequestHandler::GetCurrentSceneTransitionCursor(const Request&)
{ {
OBSSourceAutoRelease transition = obs_frontend_get_current_transition(); OBSSourceAutoRelease transition = obs_frontend_get_current_transition();
if (!transition) if (!transition)
return RequestResult::Error(RequestStatus::InvalidResourceState, "OBS does not currently have a scene transition set."); // This should not happen! return RequestResult::Error(RequestStatus::InvalidResourceState,
"OBS does not currently have a scene transition set."); // This should not happen!
json responseData; json responseData;
responseData["transitionCursor"] = obs_transition_get_time(transition); responseData["transitionCursor"] = obs_transition_get_time(transition);
@ -309,7 +314,8 @@ RequestResult RequestHandler::SetTBarPosition(const Request& request)
OBSSourceAutoRelease transition = obs_frontend_get_current_transition(); OBSSourceAutoRelease transition = obs_frontend_get_current_transition();
if (!transition) if (!transition)
return RequestResult::Error(RequestStatus::InvalidResourceState, "OBS does not currently have a scene transition set."); // This should not happen! return RequestResult::Error(RequestStatus::InvalidResourceState,
"OBS does not currently have a scene transition set."); // This should not happen!
float position = request.RequestData["position"]; float position = request.RequestData["position"];

View File

@ -17,6 +17,11 @@ You should have received a copy of the GNU General Public License along
with this program. If not, see <https://www.gnu.org/licenses/> with this program. If not, see <https://www.gnu.org/licenses/>
*/ */
#include <QGuiApplication>
#include <QScreen>
#include <QRect>
#include <sstream>
#include "RequestHandler.h" #include "RequestHandler.h"
/** /**
@ -62,10 +67,13 @@ RequestResult RequestHandler::SetStudioModeEnabled(const Request& request)
// (Bad) Create a boolean then pass it as a reference to the task. Requires `wait` in obs_queue_task() to be true, else undefined behavior // (Bad) Create a boolean then pass it as a reference to the task. Requires `wait` in obs_queue_task() to be true, else undefined behavior
bool studioModeEnabled = request.RequestData["studioModeEnabled"]; bool studioModeEnabled = request.RequestData["studioModeEnabled"];
// Queue the task inside of the UI thread to prevent race conditions // Queue the task inside of the UI thread to prevent race conditions
obs_queue_task(OBS_TASK_UI, [](void* param) { obs_queue_task(
OBS_TASK_UI,
[](void *param) {
auto studioModeEnabled = (bool *)param; auto studioModeEnabled = (bool *)param;
obs_frontend_set_preview_program_mode(*studioModeEnabled); obs_frontend_set_preview_program_mode(*studioModeEnabled);
}, &studioModeEnabled, true); },
&studioModeEnabled, true);
} }
return RequestResult::Success(); return RequestResult::Success();
@ -142,9 +150,155 @@ RequestResult RequestHandler::OpenInputInteractDialog(const Request& request)
return RequestResult::Error(statusCode, comment); return RequestResult::Error(statusCode, comment);
if (!(obs_source_get_output_flags(input) & OBS_SOURCE_INTERACTION)) if (!(obs_source_get_output_flags(input) & OBS_SOURCE_INTERACTION))
return RequestResult::Error(RequestStatus::InvalidResourceState, "The specified input does not support interaction."); return RequestResult::Error(RequestStatus::InvalidResourceState,
"The specified input does not support interaction.");
obs_frontend_open_source_interaction(input); obs_frontend_open_source_interaction(input);
return RequestResult::Success(); return RequestResult::Success();
} }
/**
* Gets a list of connected monitors and information about them.
*
* @responseField monitors | Array<Object> | a list of detected monitors with some information
*
* @requestType GetMonitorList
* @complexity 2
* @rpcVersion -1
* @initialVersion 5.0.0
* @category ui
* @api requests
*/
RequestResult RequestHandler::GetMonitorList(const Request &)
{
json responseData;
std::vector<json> monitorsData;
QList<QScreen *> screensList = QGuiApplication::screens();
for (int screenIndex = 0; screenIndex < screensList.size(); screenIndex++) {
json screenData;
QScreen const *screen = screensList[screenIndex];
std::stringstream nameAndIndex;
nameAndIndex << screen->name().toStdString();
nameAndIndex << '(' << screenIndex << ')';
screenData["monitorName"] = nameAndIndex.str();
screenData["monitorIndex"] = screenIndex;
const QRect screenGeometry = screen->geometry();
screenData["monitorWidth"] = screenGeometry.width();
screenData["monitorHeight"] = screenGeometry.height();
screenData["monitorPositionX"] = screenGeometry.x();
screenData["monitorPositionY"] = screenGeometry.y();
monitorsData.push_back(screenData);
}
responseData["monitors"] = monitorsData;
return RequestResult::Success(responseData);
}
/**
* Opens a projector for a specific output video mix.
*
* Mix types:
*
* - `OBS_WEBSOCKET_VIDEO_MIX_TYPE_PREVIEW`
* - `OBS_WEBSOCKET_VIDEO_MIX_TYPE_PROGRAM`
* - `OBS_WEBSOCKET_VIDEO_MIX_TYPE_MULTIVIEW`
*
* Note: This request serves to provide feature parity with 4.x. It is very likely to be changed/deprecated in a future release.
*
* @requestField videoMixType | String | Type of mix to open
* @requestField ?monitorIndex | Number | Monitor index, use `GetMonitorList` to obtain index | None | -1: Opens projector in windowed mode
* @requestField ?projectorGeometry | String | Size/Position data for a windowed projector, in Qt Base64 encoded format. Mutually exclusive with `monitorIndex` | N/A
*
* @requestType OpenVideoMixProjector
* @complexity 3
* @rpcVersion -1
* @initialVersion 5.0.0
* @category ui
* @api requests
*/
RequestResult RequestHandler::OpenVideoMixProjector(const Request &request)
{
RequestStatus::RequestStatus statusCode;
std::string comment;
if (!request.ValidateString("videoMixType", statusCode, comment))
return RequestResult::Error(statusCode, comment);
std::string videoMixType = request.RequestData["videoMixType"];
const char *projectorType;
if (videoMixType == "OBS_WEBSOCKET_VIDEO_MIX_TYPE_PREVIEW")
projectorType = "Preview";
else if (videoMixType == "OBS_WEBSOCKET_VIDEO_MIX_TYPE_PROGRAM")
projectorType = "StudioProgram";
else if (videoMixType == "OBS_WEBSOCKET_VIDEO_MIX_TYPE_MULTIVIEW")
projectorType = "Multiview";
else
return RequestResult::Error(RequestStatus::InvalidRequestField,
"The field `videoMixType` has an invalid enum value.");
int monitorIndex = -1;
if (request.Contains("monitorIndex")) {
if (!request.ValidateOptionalNumber("monitorIndex", statusCode, comment, -1, 9))
return RequestResult::Error(statusCode, comment);
monitorIndex = request.RequestData["monitorIndex"];
}
std::string projectorGeometry;
if (request.Contains("projectorGeometry")) {
if (!request.ValidateOptionalString("projectorGeometry", statusCode, comment))
return RequestResult::Error(statusCode, comment);
if (monitorIndex != -1)
return RequestResult::Error(RequestStatus::TooManyRequestFields,
"`monitorIndex` and `projectorGeometry` are mutually exclusive.");
projectorGeometry = request.RequestData["projectorGeometry"];
}
obs_frontend_open_projector(projectorType, monitorIndex, projectorGeometry.c_str(), nullptr);
return RequestResult::Success();
}
/**
* Opens a projector for a source.
*
* Note: This request serves to provide feature parity with 4.x. It is very likely to be changed/deprecated in a future release.
*
* @requestField sourceName | String | Name of the source to open a projector for
* @requestField ?monitorIndex | Number | Monitor index, use `GetMonitorList` to obtain index | None | -1: Opens projector in windowed mode
* @requestField ?projectorGeometry | String | Size/Position data for a windowed projector, in Qt Base64 encoded format. Mutually exclusive with `monitorIndex` | N/A
*
* @requestType OpenSourceProjector
* @complexity 3
* @rpcVersion -1
* @initialVersion 5.0.0
* @category ui
* @api requests
*/
RequestResult RequestHandler::OpenSourceProjector(const Request &request)
{
RequestStatus::RequestStatus statusCode;
std::string comment;
OBSSourceAutoRelease source = request.ValidateSource("sourceName", statusCode, comment);
if (!source)
return RequestResult::Error(statusCode, comment);
int monitorIndex = -1;
if (request.Contains("monitorIndex")) {
if (!request.ValidateOptionalNumber("monitorIndex", statusCode, comment, -1, 9))
return RequestResult::Error(statusCode, comment);
monitorIndex = request.RequestData["monitorIndex"];
}
std::string projectorGeometry;
if (request.Contains("projectorGeometry")) {
if (!request.ValidateOptionalString("projectorGeometry", statusCode, comment))
return RequestResult::Error(statusCode, comment);
if (monitorIndex != -1)
return RequestResult::Error(RequestStatus::TooManyRequestFields,
"`monitorIndex` and `projectorGeometry` are mutually exclusive.");
projectorGeometry = request.RequestData["projectorGeometry"];
}
obs_frontend_open_projector("Source", monitorIndex, projectorGeometry.c_str(), obs_source_get_name(source));
return RequestResult::Success();
}

View File

@ -29,8 +29,9 @@ json GetDefaultJsonObject(const json &requestData)
return requestData; return requestData;
} }
Request::Request(const std::string &requestType, const json &requestData, const RequestBatchExecutionType::RequestBatchExecutionType executionType) : Request::Request(const std::string &requestType, const json &requestData,
RequestType(requestType), const RequestBatchExecutionType::RequestBatchExecutionType executionType)
: RequestType(requestType),
HasRequestData(requestData.is_object()), HasRequestData(requestData.is_object()),
RequestData(GetDefaultJsonObject(requestData)), RequestData(GetDefaultJsonObject(requestData)),
ExecutionType(executionType) ExecutionType(executionType)
@ -59,7 +60,8 @@ bool Request::ValidateBasic(const std::string &keyName, RequestStatus::RequestSt
return true; return true;
} }
bool Request::ValidateOptionalNumber(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment, const double minValue, const double maxValue) const bool Request::ValidateOptionalNumber(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment,
const double minValue, const double maxValue) const
{ {
if (!RequestData[keyName].is_number()) { if (!RequestData[keyName].is_number()) {
statusCode = RequestStatus::InvalidRequestFieldType; statusCode = RequestStatus::InvalidRequestFieldType;
@ -70,19 +72,22 @@ bool Request::ValidateOptionalNumber(const std::string &keyName, RequestStatus::
double value = RequestData[keyName]; double value = RequestData[keyName];
if (value < minValue) { if (value < minValue) {
statusCode = RequestStatus::RequestFieldOutOfRange; statusCode = RequestStatus::RequestFieldOutOfRange;
comment = std::string("The field value of `") + keyName + "` is below the minimum of `" + std::to_string(minValue) + "`"; comment = std::string("The field value of `") + keyName + "` is below the minimum of `" + std::to_string(minValue) +
"`";
return false; return false;
} }
if (value > maxValue) { if (value > maxValue) {
statusCode = RequestStatus::RequestFieldOutOfRange; statusCode = RequestStatus::RequestFieldOutOfRange;
comment = std::string("The field value of `") + keyName + "` is above the maximum of `" + std::to_string(maxValue) + "`"; comment = std::string("The field value of `") + keyName + "` is above the maximum of `" + std::to_string(maxValue) +
"`";
return false; return false;
} }
return true; return true;
} }
bool Request::ValidateNumber(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment, const double minValue, const double maxValue) const bool Request::ValidateNumber(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment,
const double minValue, const double maxValue) const
{ {
if (!ValidateBasic(keyName, statusCode, comment)) if (!ValidateBasic(keyName, statusCode, comment))
return false; return false;
@ -93,7 +98,8 @@ bool Request::ValidateNumber(const std::string &keyName, RequestStatus::RequestS
return true; return true;
} }
bool Request::ValidateOptionalString(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment, const bool allowEmpty) const bool Request::ValidateOptionalString(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment,
const bool allowEmpty) const
{ {
if (!RequestData[keyName].is_string()) { if (!RequestData[keyName].is_string()) {
statusCode = RequestStatus::InvalidRequestFieldType; statusCode = RequestStatus::InvalidRequestFieldType;
@ -110,7 +116,8 @@ bool Request::ValidateOptionalString(const std::string &keyName, RequestStatus::
return true; return true;
} }
bool Request::ValidateString(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment, const bool allowEmpty) const bool Request::ValidateString(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment,
const bool allowEmpty) const
{ {
if (!ValidateBasic(keyName, statusCode, comment)) if (!ValidateBasic(keyName, statusCode, comment))
return false; return false;
@ -121,7 +128,8 @@ bool Request::ValidateString(const std::string &keyName, RequestStatus::RequestS
return true; return true;
} }
bool Request::ValidateOptionalBoolean(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment) const bool Request::ValidateOptionalBoolean(const std::string &keyName, RequestStatus::RequestStatus &statusCode,
std::string &comment) const
{ {
if (!RequestData[keyName].is_boolean()) { if (!RequestData[keyName].is_boolean()) {
statusCode = RequestStatus::InvalidRequestFieldType; statusCode = RequestStatus::InvalidRequestFieldType;
@ -143,7 +151,8 @@ bool Request::ValidateBoolean(const std::string &keyName, RequestStatus::Request
return true; return true;
} }
bool Request::ValidateOptionalObject(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment, const bool allowEmpty) const bool Request::ValidateOptionalObject(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment,
const bool allowEmpty) const
{ {
if (!RequestData[keyName].is_object()) { if (!RequestData[keyName].is_object()) {
statusCode = RequestStatus::InvalidRequestFieldType; statusCode = RequestStatus::InvalidRequestFieldType;
@ -160,7 +169,8 @@ bool Request::ValidateOptionalObject(const std::string &keyName, RequestStatus::
return true; return true;
} }
bool Request::ValidateObject(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment, const bool allowEmpty) const bool Request::ValidateObject(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment,
const bool allowEmpty) const
{ {
if (!ValidateBasic(keyName, statusCode, comment)) if (!ValidateBasic(keyName, statusCode, comment))
return false; return false;
@ -171,7 +181,8 @@ bool Request::ValidateObject(const std::string &keyName, RequestStatus::RequestS
return true; return true;
} }
bool Request::ValidateOptionalArray(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment, const bool allowEmpty) const bool Request::ValidateOptionalArray(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment,
const bool allowEmpty) const
{ {
if (!RequestData[keyName].is_array()) { if (!RequestData[keyName].is_array()) {
statusCode = RequestStatus::InvalidRequestFieldType; statusCode = RequestStatus::InvalidRequestFieldType;
@ -188,7 +199,8 @@ bool Request::ValidateOptionalArray(const std::string &keyName, RequestStatus::R
return true; return true;
} }
bool Request::ValidateArray(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment, const bool allowEmpty) const bool Request::ValidateArray(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment,
const bool allowEmpty) const
{ {
if (!ValidateBasic(keyName, statusCode, comment)) if (!ValidateBasic(keyName, statusCode, comment))
return false; return false;
@ -199,7 +211,8 @@ bool Request::ValidateArray(const std::string &keyName, RequestStatus::RequestSt
return true; return true;
} }
obs_source_t *Request::ValidateSource(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment) const obs_source_t *Request::ValidateSource(const std::string &keyName, RequestStatus::RequestStatus &statusCode,
std::string &comment) const
{ {
if (!ValidateString(keyName, statusCode, comment)) if (!ValidateString(keyName, statusCode, comment))
return nullptr; return nullptr;
@ -216,7 +229,8 @@ obs_source_t *Request::ValidateSource(const std::string &keyName, RequestStatus:
return ret; return ret;
} }
obs_source_t *Request::ValidateScene(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment, const ObsWebSocketSceneFilter filter) const obs_source_t *Request::ValidateScene(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment,
const ObsWebSocketSceneFilter filter) const
{ {
obs_source_t *ret = ValidateSource(keyName, statusCode, comment); obs_source_t *ret = ValidateSource(keyName, statusCode, comment);
if (!ret) if (!ret)
@ -245,7 +259,8 @@ obs_source_t *Request::ValidateScene(const std::string &keyName, RequestStatus::
return ret; return ret;
} }
obs_scene_t *Request::ValidateScene2(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment, const ObsWebSocketSceneFilter filter) const obs_scene_t *Request::ValidateScene2(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment,
const ObsWebSocketSceneFilter filter) const
{ {
OBSSourceAutoRelease sceneSource = ValidateSource(keyName, statusCode, comment); OBSSourceAutoRelease sceneSource = ValidateSource(keyName, statusCode, comment);
if (!sceneSource) if (!sceneSource)
@ -275,7 +290,8 @@ obs_scene_t *Request::ValidateScene2(const std::string &keyName, RequestStatus::
} }
} }
obs_source_t *Request::ValidateInput(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment) const obs_source_t *Request::ValidateInput(const std::string &keyName, RequestStatus::RequestStatus &statusCode,
std::string &comment) const
{ {
obs_source_t *ret = ValidateSource(keyName, statusCode, comment); obs_source_t *ret = ValidateSource(keyName, statusCode, comment);
if (!ret) if (!ret)
@ -291,7 +307,8 @@ obs_source_t *Request::ValidateInput(const std::string &keyName, RequestStatus::
return ret; return ret;
} }
FilterPair Request::ValidateFilter(const std::string &sourceKeyName, const std::string &filterKeyName, RequestStatus::RequestStatus &statusCode, std::string &comment) const FilterPair Request::ValidateFilter(const std::string &sourceKeyName, const std::string &filterKeyName,
RequestStatus::RequestStatus &statusCode, std::string &comment) const
{ {
obs_source_t *source = ValidateSource(sourceKeyName, statusCode, comment); obs_source_t *source = ValidateSource(sourceKeyName, statusCode, comment);
if (!source) if (!source)
@ -305,14 +322,17 @@ FilterPair Request::ValidateFilter(const std::string &sourceKeyName, const std::
obs_source_t *filter = obs_source_get_filter_by_name(source, filterName.c_str()); obs_source_t *filter = obs_source_get_filter_by_name(source, filterName.c_str());
if (!filter) { if (!filter) {
statusCode = RequestStatus::ResourceNotFound; statusCode = RequestStatus::ResourceNotFound;
comment = std::string("No filter was found in the source `") + RequestData[sourceKeyName].get<std::string>() + "` with the name `" + filterName + "`."; comment = std::string("No filter was found in the source `") + RequestData[sourceKeyName].get<std::string>() +
"` with the name `" + filterName + "`.";
return FilterPair{source, nullptr}; return FilterPair{source, nullptr};
} }
return FilterPair{source, filter}; return FilterPair{source, filter};
} }
obs_sceneitem_t *Request::ValidateSceneItem(const std::string &sceneKeyName, const std::string &sceneItemIdKeyName, RequestStatus::RequestStatus &statusCode, std::string &comment, const ObsWebSocketSceneFilter filter) const obs_sceneitem_t *Request::ValidateSceneItem(const std::string &sceneKeyName, const std::string &sceneItemIdKeyName,
RequestStatus::RequestStatus &statusCode, std::string &comment,
const ObsWebSocketSceneFilter filter) const
{ {
OBSSceneAutoRelease scene = ValidateScene2(sceneKeyName, statusCode, comment, filter); OBSSceneAutoRelease scene = ValidateScene2(sceneKeyName, statusCode, comment, filter);
if (!scene) if (!scene)
@ -326,10 +346,29 @@ obs_sceneitem_t *Request::ValidateSceneItem(const std::string &sceneKeyName, con
OBSSceneItem sceneItem = obs_scene_find_sceneitem_by_id(scene, sceneItemId); OBSSceneItem sceneItem = obs_scene_find_sceneitem_by_id(scene, sceneItemId);
if (!sceneItem) { if (!sceneItem) {
statusCode = RequestStatus::ResourceNotFound; statusCode = RequestStatus::ResourceNotFound;
comment = std::string("No scene items were found in scene `") + RequestData[sceneKeyName].get<std::string>() + "` with the ID `" + std::to_string(sceneItemId) + "`."; comment = std::string("No scene items were found in scene `") + RequestData[sceneKeyName].get<std::string>() +
"` with the ID `" + std::to_string(sceneItemId) + "`.";
return nullptr; return nullptr;
} }
obs_sceneitem_addref(sceneItem); obs_sceneitem_addref(sceneItem);
return sceneItem; return sceneItem;
} }
obs_output_t *Request::ValidateOutput(const std::string &keyName, RequestStatus::RequestStatus &statusCode,
std::string &comment) const
{
if (!ValidateString(keyName, statusCode, comment))
return nullptr;
std::string outputName = RequestData[keyName];
obs_output_t *ret = obs_get_output_by_name(outputName.c_str());
if (!ret) {
statusCode = RequestStatus::ResourceNotFound;
comment = std::string("No output was found with the name `") + outputName + "`.";
return nullptr;
}
return ret;
}

View File

@ -35,32 +35,50 @@ struct FilterPair {
OBSSourceAutoRelease filter; OBSSourceAutoRelease filter;
}; };
struct Request struct Request {
{ Request(const std::string &requestType, const json &requestData = nullptr,
Request(const std::string &requestType, const json &requestData = nullptr, const RequestBatchExecutionType::RequestBatchExecutionType executionType = RequestBatchExecutionType::None); const RequestBatchExecutionType::RequestBatchExecutionType executionType = RequestBatchExecutionType::None);
// Contains the key and is not null // Contains the key and is not null
bool Contains(const std::string &keyName) const; bool Contains(const std::string &keyName) const;
bool ValidateBasic(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment) const; bool ValidateBasic(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment) const;
bool ValidateOptionalNumber(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment, const double minValue = -INFINITY, const double maxValue = INFINITY) const; bool ValidateOptionalNumber(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment,
bool ValidateNumber(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment, const double minValue = -INFINITY, const double maxValue = INFINITY) const; const double minValue = -INFINITY, const double maxValue = INFINITY) const;
bool ValidateOptionalString(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment, const bool allowEmpty = false) const; bool ValidateNumber(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment,
bool ValidateString(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment, const bool allowEmpty = false) const; const double minValue = -INFINITY, const double maxValue = INFINITY) const;
bool ValidateOptionalBoolean(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment) const; bool ValidateOptionalString(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment,
const bool allowEmpty = false) const;
bool ValidateString(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment,
const bool allowEmpty = false) const;
bool ValidateOptionalBoolean(const std::string &keyName, RequestStatus::RequestStatus &statusCode,
std::string &comment) const;
bool ValidateBoolean(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment) const; bool ValidateBoolean(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment) const;
bool ValidateOptionalObject(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment, const bool allowEmpty = false) const; bool ValidateOptionalObject(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment,
bool ValidateObject(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment, const bool allowEmpty = false) const; const bool allowEmpty = false) const;
bool ValidateOptionalArray(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment, const bool allowEmpty = false) const; bool ValidateObject(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment,
bool ValidateArray(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment, const bool allowEmpty = false) const; const bool allowEmpty = false) const;
bool ValidateOptionalArray(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment,
const bool allowEmpty = false) const;
bool ValidateArray(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment,
const bool allowEmpty = false) const;
// All return values have incremented refcounts // All return values have incremented refcounts
obs_source_t *ValidateSource(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment) const; obs_source_t *ValidateSource(const std::string &keyName, RequestStatus::RequestStatus &statusCode,
obs_source_t *ValidateScene(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment, const ObsWebSocketSceneFilter filter = OBS_WEBSOCKET_SCENE_FILTER_SCENE_ONLY) const; std::string &comment) const;
obs_scene_t *ValidateScene2(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment, const ObsWebSocketSceneFilter filter = OBS_WEBSOCKET_SCENE_FILTER_SCENE_ONLY) const; obs_source_t *ValidateScene(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment,
obs_source_t *ValidateInput(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment) const; const ObsWebSocketSceneFilter filter = OBS_WEBSOCKET_SCENE_FILTER_SCENE_ONLY) const;
FilterPair ValidateFilter(const std::string &sourceKeyName, const std::string &filterKeyName, RequestStatus::RequestStatus &statusCode, std::string &comment) const; obs_scene_t *ValidateScene2(const std::string &keyName, RequestStatus::RequestStatus &statusCode, std::string &comment,
obs_sceneitem_t *ValidateSceneItem(const std::string &sceneKeyName, const std::string &sceneItemIdKeyName, RequestStatus::RequestStatus &statusCode, std::string &comment, const ObsWebSocketSceneFilter filter = OBS_WEBSOCKET_SCENE_FILTER_SCENE_ONLY) const; const ObsWebSocketSceneFilter filter = OBS_WEBSOCKET_SCENE_FILTER_SCENE_ONLY) const;
obs_source_t *ValidateInput(const std::string &keyName, RequestStatus::RequestStatus &statusCode,
std::string &comment) const;
FilterPair ValidateFilter(const std::string &sourceKeyName, const std::string &filterKeyName,
RequestStatus::RequestStatus &statusCode, std::string &comment) const;
obs_sceneitem_t *ValidateSceneItem(const std::string &sceneKeyName, const std::string &sceneItemIdKeyName,
RequestStatus::RequestStatus &statusCode, std::string &comment,
const ObsWebSocketSceneFilter filter = OBS_WEBSOCKET_SCENE_FILTER_SCENE_ONLY) const;
obs_output_t *ValidateOutput(const std::string &keyName, RequestStatus::RequestStatus &statusCode,
std::string &comment) const;
std::string RequestType; std::string RequestType;
bool HasRequestData; bool HasRequestData;

View File

@ -18,9 +18,9 @@ with this program. If not, see <https://www.gnu.org/licenses/>
#include "RequestBatchRequest.h" #include "RequestBatchRequest.h"
RequestBatchRequest::RequestBatchRequest(const std::string &requestType, const json &requestData, RequestBatchExecutionType::RequestBatchExecutionType executionType, const json &inputVariables, const json &outputVariables) : RequestBatchRequest::RequestBatchRequest(const std::string &requestType, const json &requestData,
Request(requestType, requestData, executionType), RequestBatchExecutionType::RequestBatchExecutionType executionType,
InputVariables(inputVariables), const json &inputVariables, const json &outputVariables)
OutputVariables(outputVariables) : Request(requestType, requestData, executionType), InputVariables(inputVariables), OutputVariables(outputVariables)
{ {
} }

View File

@ -21,7 +21,9 @@ with this program. If not, see <https://www.gnu.org/licenses/>
#include "Request.h" #include "Request.h"
struct RequestBatchRequest : Request { struct RequestBatchRequest : Request {
RequestBatchRequest(const std::string &requestType, const json &requestData, RequestBatchExecutionType::RequestBatchExecutionType executionType, const json &inputVariables = nullptr, const json &outputVariables = nullptr); RequestBatchRequest(const std::string &requestType, const json &requestData,
RequestBatchExecutionType::RequestBatchExecutionType executionType,
const json &inputVariables = nullptr, const json &outputVariables = nullptr);
json InputVariables; json InputVariables;
json OutputVariables; json OutputVariables;

View File

@ -19,11 +19,8 @@ with this program. If not, see <https://www.gnu.org/licenses/>
#include "RequestResult.h" #include "RequestResult.h"
RequestResult::RequestResult(RequestStatus::RequestStatus statusCode, json responseData, std::string comment) : RequestResult::RequestResult(RequestStatus::RequestStatus statusCode, json responseData, std::string comment)
StatusCode(statusCode), : StatusCode(statusCode), ResponseData(responseData), Comment(comment), SleepFrames(0)
ResponseData(responseData),
Comment(comment),
SleepFrames(0)
{ {
} }

View File

@ -22,9 +22,9 @@ with this program. If not, see <https://www.gnu.org/licenses/>
#include "../types/RequestStatus.h" #include "../types/RequestStatus.h"
#include "../../utils/Json.h" #include "../../utils/Json.h"
struct RequestResult struct RequestResult {
{ RequestResult(RequestStatus::RequestStatus statusCode = RequestStatus::Success, json responseData = nullptr,
RequestResult(RequestStatus::RequestStatus statusCode = RequestStatus::Success, json responseData = nullptr, std::string comment = ""); std::string comment = "");
static RequestResult Success(json responseData = nullptr); static RequestResult Success(json responseData = nullptr);
static RequestResult Error(RequestStatus::RequestStatus statusCode, std::string comment = ""); static RequestResult Error(RequestStatus::RequestStatus statusCode, std::string comment = "");
RequestStatus::RequestStatus StatusCode; RequestStatus::RequestStatus StatusCode;

View File

@ -77,8 +77,5 @@ namespace RequestBatchExecutionType {
Parallel = 2, Parallel = 2,
}; };
inline bool IsValid(int8_t executionType) inline bool IsValid(int8_t executionType) { return executionType >= None && executionType <= Parallel; }
{
return executionType >= None && executionType <= Parallel;
}
} }

View File

@ -263,7 +263,6 @@ namespace RequestStatus {
*/ */
StudioModeNotActive = 506, StudioModeNotActive = 506,
/** /**
* The resource was not found. * The resource was not found.
* *

View File

@ -19,10 +19,7 @@ with this program. If not, see <https://www.gnu.org/licenses/>
#include "Compat.h" #include "Compat.h"
Utils::Compat::StdFunctionRunnable::StdFunctionRunnable(std::function<void()> func) : Utils::Compat::StdFunctionRunnable::StdFunctionRunnable(std::function<void()> func) : cb(std::move(func)) {}
cb(std::move(func))
{
}
void Utils::Compat::StdFunctionRunnable::run() void Utils::Compat::StdFunctionRunnable::run()
{ {

View File

@ -27,6 +27,7 @@ namespace Utils {
// Reimplement QRunnable for std::function. Retrocompatability for Qt < 5.15 // Reimplement QRunnable for std::function. Retrocompatability for Qt < 5.15
class StdFunctionRunnable : public QRunnable { class StdFunctionRunnable : public QRunnable {
std::function<void()> cb; std::function<void()> cb;
public: public:
StdFunctionRunnable(std::function<void()> func); StdFunctionRunnable(std::function<void()> func);
void run() override; void run() override;

View File

@ -63,10 +63,7 @@ bool Utils::Crypto::CheckAuthenticationString(std::string secret, std::string ch
secretAndChallenge += QString::fromStdString(challenge); secretAndChallenge += QString::fromStdString(challenge);
// Generate a SHA256 hash of secretAndChallenge // Generate a SHA256 hash of secretAndChallenge
auto hash = QCryptographicHash::hash( auto hash = QCryptographicHash::hash(secretAndChallenge.toUtf8(), QCryptographicHash::Algorithm::Sha256);
secretAndChallenge.toUtf8(),
QCryptographicHash::Algorithm::Sha256
);
// Encode the SHA256 hash to Base64 // Encode the SHA256 hash to Base64
std::string expectedAuthenticationString = hash.toBase64().toStdString(); std::string expectedAuthenticationString = hash.toBase64().toStdString();

View File

@ -168,8 +168,7 @@ json Utils::Json::ObsDataToJson(obs_data_t *d, bool includeDefault)
case OBS_DATA_ARRAY: case OBS_DATA_ARRAY:
set_json_array(&j, name, item, includeDefault); set_json_array(&j, name, item, includeDefault);
break; break;
default: default:;
;
} }
} }

View File

@ -25,6 +25,51 @@ with this program. If not, see <https://www.gnu.org/licenses/>
using json = nlohmann::json; using json = nlohmann::json;
NLOHMANN_JSON_SERIALIZE_ENUM(obs_source_type, {
{OBS_SOURCE_TYPE_INPUT, "OBS_SOURCE_TYPE_INPUT"},
{OBS_SOURCE_TYPE_FILTER, "OBS_SOURCE_TYPE_FILTER"},
{OBS_SOURCE_TYPE_TRANSITION, "OBS_SOURCE_TYPE_TRANSITION"},
{OBS_SOURCE_TYPE_SCENE, "OBS_SOURCE_TYPE_SCENE"},
})
NLOHMANN_JSON_SERIALIZE_ENUM(obs_monitoring_type,
{
{OBS_MONITORING_TYPE_NONE, "OBS_MONITORING_TYPE_NONE"},
{OBS_MONITORING_TYPE_MONITOR_ONLY, "OBS_MONITORING_TYPE_MONITOR_ONLY"},
{OBS_MONITORING_TYPE_MONITOR_AND_OUTPUT, "OBS_MONITORING_TYPE_MONITOR_AND_OUTPUT"},
})
NLOHMANN_JSON_SERIALIZE_ENUM(obs_media_state, {
{OBS_MEDIA_STATE_NONE, "OBS_MEDIA_STATE_NONE"},
{OBS_MEDIA_STATE_PLAYING, "OBS_MEDIA_STATE_PLAYING"},
{OBS_MEDIA_STATE_OPENING, "OBS_MEDIA_STATE_OPENING"},
{OBS_MEDIA_STATE_BUFFERING, "OBS_MEDIA_STATE_BUFFERING"},
{OBS_MEDIA_STATE_PAUSED, "OBS_MEDIA_STATE_PAUSED"},
{OBS_MEDIA_STATE_STOPPED, "OBS_MEDIA_STATE_STOPPED"},
{OBS_MEDIA_STATE_ENDED, "OBS_MEDIA_STATE_ENDED"},
{OBS_MEDIA_STATE_ERROR, "OBS_MEDIA_STATE_ERROR"},
})
NLOHMANN_JSON_SERIALIZE_ENUM(obs_bounds_type, {
{OBS_BOUNDS_NONE, "OBS_BOUNDS_NONE"},
{OBS_BOUNDS_STRETCH, "OBS_BOUNDS_STRETCH"},
{OBS_BOUNDS_SCALE_INNER, "OBS_BOUNDS_SCALE_INNER"},
{OBS_BOUNDS_SCALE_OUTER, "OBS_BOUNDS_SCALE_OUTER"},
{OBS_BOUNDS_SCALE_TO_WIDTH, "OBS_BOUNDS_SCALE_TO_WIDTH"},
{OBS_BOUNDS_SCALE_TO_HEIGHT, "OBS_BOUNDS_SCALE_TO_HEIGHT"},
{OBS_BOUNDS_MAX_ONLY, "OBS_BOUNDS_MAX_ONLY"},
})
NLOHMANN_JSON_SERIALIZE_ENUM(obs_blending_type, {
{OBS_BLEND_NORMAL, "OBS_BLEND_NORMAL"},
{OBS_BLEND_ADDITIVE, "OBS_BLEND_ADDITIVE"},
{OBS_BLEND_SUBTRACT, "OBS_BLEND_SUBTRACT"},
{OBS_BLEND_SCREEN, "OBS_BLEND_SCREEN"},
{OBS_BLEND_MULTIPLY, "OBS_BLEND_MULTIPLY"},
{OBS_BLEND_LIGHTEN, "OBS_BLEND_LIGHTEN"},
{OBS_BLEND_DARKEN, "OBS_BLEND_DARKEN"},
})
namespace Utils { namespace Utils {
namespace Json { namespace Json {
bool JsonArrayIsValidObsArray(const json &j); bool JsonArrayIsValidObsArray(const json &j);

View File

@ -59,7 +59,8 @@ using OBSWeakEncoderAutoRelease = OBSRef<obs_weak_encoder_t *, ___weak_encoder_d
using OBSWeakServiceAutoRelease = OBSRef<obs_weak_service_t *, ___weak_service_dummy_addref, obs_weak_service_release>; using OBSWeakServiceAutoRelease = OBSRef<obs_weak_service_t *, ___weak_service_dummy_addref, obs_weak_service_release>;
#endif #endif
template <typename T> T* GetCalldataPointer(const calldata_t *data, const char* name) { template<typename T> T *GetCalldataPointer(const calldata_t *data, const char *name)
{
void *ptr = nullptr; void *ptr = nullptr;
calldata_get_ptr(data, name, &ptr); calldata_get_ptr(data, name, &ptr);
return static_cast<T *>(ptr); return static_cast<T *>(ptr);
@ -76,6 +77,16 @@ enum ObsOutputState {
OBS_WEBSOCKET_OUTPUT_RESUMED, OBS_WEBSOCKET_OUTPUT_RESUMED,
}; };
NLOHMANN_JSON_SERIALIZE_ENUM(ObsOutputState, {
{OBS_WEBSOCKET_OUTPUT_UNKNOWN, "OBS_WEBSOCKET_OUTPUT_UNKNOWN"},
{OBS_WEBSOCKET_OUTPUT_STARTING, "OBS_WEBSOCKET_OUTPUT_STARTING"},
{OBS_WEBSOCKET_OUTPUT_STARTED, "OBS_WEBSOCKET_OUTPUT_STARTED"},
{OBS_WEBSOCKET_OUTPUT_STOPPING, "OBS_WEBSOCKET_OUTPUT_STOPPING"},
{OBS_WEBSOCKET_OUTPUT_STOPPED, "OBS_WEBSOCKET_OUTPUT_STOPPED"},
{OBS_WEBSOCKET_OUTPUT_PAUSED, "OBS_WEBSOCKET_OUTPUT_PAUSED"},
{OBS_WEBSOCKET_OUTPUT_RESUMED, "OBS_WEBSOCKET_OUTPUT_RESUMED"},
})
enum ObsMediaInputAction { enum ObsMediaInputAction {
/** /**
* No action. * No action.
@ -149,6 +160,17 @@ enum ObsMediaInputAction {
OBS_WEBSOCKET_MEDIA_INPUT_ACTION_PREVIOUS, OBS_WEBSOCKET_MEDIA_INPUT_ACTION_PREVIOUS,
}; };
NLOHMANN_JSON_SERIALIZE_ENUM(ObsMediaInputAction,
{
{OBS_WEBSOCKET_MEDIA_INPUT_ACTION_NONE, "OBS_WEBSOCKET_MEDIA_INPUT_ACTION_NONE"},
{OBS_WEBSOCKET_MEDIA_INPUT_ACTION_PLAY, "OBS_WEBSOCKET_MEDIA_INPUT_ACTION_PLAY"},
{OBS_WEBSOCKET_MEDIA_INPUT_ACTION_PAUSE, "OBS_WEBSOCKET_MEDIA_INPUT_ACTION_PAUSE"},
{OBS_WEBSOCKET_MEDIA_INPUT_ACTION_STOP, "OBS_WEBSOCKET_MEDIA_INPUT_ACTION_STOP"},
{OBS_WEBSOCKET_MEDIA_INPUT_ACTION_RESTART, "OBS_WEBSOCKET_MEDIA_INPUT_ACTION_RESTART"},
{OBS_WEBSOCKET_MEDIA_INPUT_ACTION_NEXT, "OBS_WEBSOCKET_MEDIA_INPUT_ACTION_NEXT"},
{OBS_WEBSOCKET_MEDIA_INPUT_ACTION_PREVIOUS, "OBS_WEBSOCKET_MEDIA_INPUT_ACTION_PREVIOUS"},
})
namespace Utils { namespace Utils {
namespace Obs { namespace Obs {
namespace StringHelper { namespace StringHelper {
@ -157,21 +179,9 @@ namespace Utils {
std::string GetCurrentProfile(); std::string GetCurrentProfile();
std::string GetCurrentProfilePath(); std::string GetCurrentProfilePath();
std::string GetCurrentRecordOutputPath(); std::string GetCurrentRecordOutputPath();
std::string GetSourceType(obs_source_t *source); std::string GetLastRecordFileName();
std::string GetInputMonitorType(enum obs_monitoring_type monitorType); std::string GetLastReplayBufferFileName();
std::string GetInputMonitorType(obs_source_t *input);
std::string GetMediaInputState(obs_source_t *input);
std::string GetLastReplayBufferFilePath();
std::string GetSceneItemBoundsType(enum obs_bounds_type type);
std::string GetSceneItemBlendMode(enum obs_blending_type mode);
std::string DurationToTimecode(uint64_t); std::string DurationToTimecode(uint64_t);
std::string GetOutputState(ObsOutputState state);
}
namespace EnumHelper {
enum obs_bounds_type GetSceneItemBoundsType(std::string boundsType);
enum ObsMediaInputAction GetMediaInputAction(std::string mediaAction);
enum obs_blending_type GetSceneItemBlendMode(std::string mode);
} }
namespace NumberHelper { namespace NumberHelper {
@ -195,6 +205,7 @@ namespace Utils {
std::vector<json> GetSceneTransitionList(); std::vector<json> GetSceneTransitionList();
std::vector<json> GetSourceFilterList(obs_source_t *source); std::vector<json> GetSourceFilterList(obs_source_t *source);
std::vector<std::string> GetFilterKindList(); std::vector<std::string> GetFilterKindList();
std::vector<json> GetOutputList();
} }
namespace ObjectHelper { namespace ObjectHelper {
@ -205,13 +216,21 @@ namespace Utils {
namespace SearchHelper { namespace SearchHelper {
obs_hotkey_t *GetHotkeyByName(std::string name); obs_hotkey_t *GetHotkeyByName(std::string name);
obs_source_t *GetSceneTransitionByName(std::string name); // Increments source ref. Use OBSSourceAutoRelease obs_source_t *GetSceneTransitionByName(std::string name); // Increments source ref. Use OBSSourceAutoRelease
obs_sceneitem_t *GetSceneItemByName(obs_scene_t *scene, std::string name); // Increments ref. Use OBSSceneItemAutoRelease obs_sceneitem_t *GetSceneItemByName(obs_scene_t *scene, std::string name,
int offset = 0); // Increments ref. Use OBSSceneItemAutoRelease
} }
namespace ActionHelper { namespace ActionHelper {
obs_sceneitem_t *CreateSceneItem(obs_source_t *source, obs_scene_t *scene, bool sceneItemEnabled = true, obs_transform_info *sceneItemTransform = nullptr, obs_sceneitem_crop *sceneItemCrop = nullptr); // Increments ref. Use OBSSceneItemAutoRelease obs_sceneitem_t *
obs_sceneitem_t *CreateInput(std::string inputName, std::string inputKind, obs_data_t *inputSettings, obs_scene_t *scene, bool sceneItemEnabled = true); // Increments ref. Use OBSSceneItemAutoRelease CreateSceneItem(obs_source_t *source, obs_scene_t *scene, bool sceneItemEnabled = true,
obs_source_t *CreateSourceFilter(obs_source_t *source, std::string filterName, std::string filterKind, obs_data_t *filterSettings); // Increments source ref. Use OBSSourceAutoRelease obs_transform_info *sceneItemTransform = nullptr,
obs_sceneitem_crop *sceneItemCrop = nullptr); // Increments ref. Use OBSSceneItemAutoRelease
obs_sceneitem_t *CreateInput(std::string inputName, std::string inputKind, obs_data_t *inputSettings,
obs_scene_t *scene,
bool sceneItemEnabled = true); // Increments ref. Use OBSSceneItemAutoRelease
obs_source_t *
CreateSourceFilter(obs_source_t *source, std::string filterName, std::string filterKind,
obs_data_t *filterSettings); // Increments source ref. Use OBSSourceAutoRelease
void SetSourceFilterIndex(obs_source_t *source, obs_source_t *filter, size_t index); void SetSourceFilterIndex(obs_source_t *source, obs_source_t *filter, size_t index);
} }
} }

View File

@ -27,7 +27,7 @@ struct CreateSceneItemData {
OBSSceneItem sceneItem; // Out OBSSceneItem sceneItem; // Out
}; };
void CreateSceneItemHelper(void *_data, obs_scene_t *scene) static void CreateSceneItemHelper(void *_data, obs_scene_t *scene)
{ {
auto *data = static_cast<CreateSceneItemData *>(_data); auto *data = static_cast<CreateSceneItemData *>(_data);
data->sceneItem = obs_scene_add(scene, data->source); data->sceneItem = obs_scene_add(scene, data->source);
@ -41,7 +41,9 @@ void CreateSceneItemHelper(void *_data, obs_scene_t *scene)
obs_sceneitem_set_visible(data->sceneItem, data->sceneItemEnabled); obs_sceneitem_set_visible(data->sceneItem, data->sceneItemEnabled);
} }
obs_sceneitem_t *Utils::Obs::ActionHelper::CreateSceneItem(obs_source_t *source, obs_scene_t *scene, bool sceneItemEnabled, obs_transform_info *sceneItemTransform, obs_sceneitem_crop *sceneItemCrop) obs_sceneitem_t *Utils::Obs::ActionHelper::CreateSceneItem(obs_source_t *source, obs_scene_t *scene, bool sceneItemEnabled,
obs_transform_info *sceneItemTransform,
obs_sceneitem_crop *sceneItemCrop)
{ {
// Sanity check for valid scene // Sanity check for valid scene
if (!(source && scene)) if (!(source && scene))
@ -64,7 +66,8 @@ obs_sceneitem_t *Utils::Obs::ActionHelper::CreateSceneItem(obs_source_t *source,
return data.sceneItem; return data.sceneItem;
} }
obs_sceneitem_t *Utils::Obs::ActionHelper::CreateInput(std::string inputName, std::string inputKind, obs_data_t *inputSettings, obs_scene_t *scene, bool sceneItemEnabled) obs_sceneitem_t *Utils::Obs::ActionHelper::CreateInput(std::string inputName, std::string inputKind, obs_data_t *inputSettings,
obs_scene_t *scene, bool sceneItemEnabled)
{ {
// Create the input // Create the input
OBSSourceAutoRelease input = obs_source_create(inputKind.c_str(), inputName.c_str(), inputSettings, nullptr); OBSSourceAutoRelease input = obs_source_create(inputKind.c_str(), inputName.c_str(), inputSettings, nullptr);
@ -88,7 +91,8 @@ obs_sceneitem_t *Utils::Obs::ActionHelper::CreateInput(std::string inputName, st
return ret; return ret;
} }
obs_source_t *Utils::Obs::ActionHelper::CreateSourceFilter(obs_source_t *source, std::string filterName, std::string filterKind, obs_data_t *filterSettings) obs_source_t *Utils::Obs::ActionHelper::CreateSourceFilter(obs_source_t *source, std::string filterName, std::string filterKind,
obs_data_t *filterSettings)
{ {
obs_source_t *filter = obs_source_create_private(filterKind.c_str(), filterName.c_str(), filterSettings); obs_source_t *filter = obs_source_create_private(filterKind.c_str(), filterName.c_str(), filterSettings);

View File

@ -60,13 +60,15 @@ std::vector<obs_hotkey_t *> Utils::Obs::ArrayHelper::GetHotkeyList()
{ {
std::vector<obs_hotkey_t *> ret; std::vector<obs_hotkey_t *> ret;
obs_enum_hotkeys([](void* data, obs_hotkey_id, obs_hotkey_t* hotkey) { auto cb = [](void *data, obs_hotkey_id, obs_hotkey_t *hotkey) {
auto ret = static_cast<std::vector<obs_hotkey_t *> *>(data); auto ret = static_cast<std::vector<obs_hotkey_t *> *>(data);
ret->push_back(hotkey); ret->push_back(hotkey);
return true; return true;
}, &ret); };
obs_enum_hotkeys(cb, &ret);
return ret; return ret;
} }
@ -132,17 +134,23 @@ std::vector<json> Utils::Obs::ArrayHelper::GetSceneItemList(obs_scene_t *scene,
std::pair<std::vector<json>, bool> enumData; std::pair<std::vector<json>, bool> enumData;
enumData.second = basic; enumData.second = basic;
obs_scene_enum_items(scene, [](obs_scene_t*, obs_sceneitem_t* sceneItem, void* param) { auto cb = [](obs_scene_t *, obs_sceneitem_t *sceneItem, void *param) {
auto enumData = static_cast<std::pair<std::vector<json>, bool> *>(param); auto enumData = static_cast<std::pair<std::vector<json>, bool> *>(param);
// TODO: Make ObjectHelper util for scene items
json item; json item;
item["sceneItemId"] = obs_sceneitem_get_id(sceneItem); item["sceneItemId"] = obs_sceneitem_get_id(sceneItem);
// Should be slightly faster than calling obs_sceneitem_get_order_position() item["sceneItemIndex"] =
item["sceneItemIndex"] = enumData->first.size(); enumData->first.size(); // Should be slightly faster than calling obs_sceneitem_get_order_position()
if (!enumData->second) { if (!enumData->second) {
item["sceneItemEnabled"] = obs_sceneitem_visible(sceneItem);
item["sceneItemLocked"] = obs_sceneitem_locked(sceneItem);
item["sceneItemTransform"] = ObjectHelper::GetSceneItemTransform(sceneItem);
item["sceneItemBlendMode"] = obs_sceneitem_get_blending_mode(sceneItem);
OBSSource itemSource = obs_sceneitem_get_source(sceneItem); OBSSource itemSource = obs_sceneitem_get_source(sceneItem);
item["sourceName"] = obs_source_get_name(itemSource); item["sourceName"] = obs_source_get_name(itemSource);
item["sourceType"] = StringHelper::GetSourceType(itemSource); item["sourceType"] = obs_source_get_type(itemSource);
if (obs_source_get_type(itemSource) == OBS_SOURCE_TYPE_INPUT) if (obs_source_get_type(itemSource) == OBS_SOURCE_TYPE_INPUT)
item["inputKind"] = obs_source_get_id(itemSource); item["inputKind"] = obs_source_get_id(itemSource);
else else
@ -156,7 +164,9 @@ std::vector<json> Utils::Obs::ArrayHelper::GetSceneItemList(obs_scene_t *scene,
enumData->first.push_back(item); enumData->first.push_back(item);
return true; return true;
}, &enumData); };
obs_scene_enum_items(scene, cb, &enumData);
return enumData.first; return enumData.first;
} }
@ -171,7 +181,7 @@ std::vector<json> Utils::Obs::ArrayHelper::GetInputList(std::string inputKind)
EnumInputInfo inputInfo; EnumInputInfo inputInfo;
inputInfo.inputKind = inputKind; inputInfo.inputKind = inputKind;
auto inputEnumProc = [](void *param, obs_source_t *input) { auto cb = [](void *param, obs_source_t *input) {
// Sanity check in case the API changes // Sanity check in case the API changes
if (obs_source_get_type(input) != OBS_SOURCE_TYPE_INPUT) if (obs_source_get_type(input) != OBS_SOURCE_TYPE_INPUT)
return true; return true;
@ -191,8 +201,9 @@ std::vector<json> Utils::Obs::ArrayHelper::GetInputList(std::string inputKind)
inputInfo->inputs.push_back(inputJson); inputInfo->inputs.push_back(inputJson);
return true; return true;
}; };
// Actually enumerates only public inputs, despite the name // Actually enumerates only public inputs, despite the name
obs_enum_sources(inputEnumProc, &inputInfo); obs_enum_sources(cb, &inputInfo);
return inputInfo.inputs; return inputInfo.inputs;
} }
@ -297,7 +308,7 @@ std::vector<json> Utils::Obs::ArrayHelper::GetSourceFilterList(obs_source_t *sou
{ {
std::vector<json> filters; std::vector<json> filters;
auto enumFilters = [](obs_source_t *, obs_source_t *filter, void *param) { auto cb = [](obs_source_t *, obs_source_t *filter, void *param) {
auto filters = reinterpret_cast<std::vector<json> *>(param); auto filters = reinterpret_cast<std::vector<json> *>(param);
json filterJson; json filterJson;
@ -311,7 +322,40 @@ std::vector<json> Utils::Obs::ArrayHelper::GetSourceFilterList(obs_source_t *sou
filters->push_back(filterJson); filters->push_back(filterJson);
}; };
obs_source_enum_filters(source, enumFilters, &filters);
obs_source_enum_filters(source, cb, &filters);
return filters; return filters;
} }
std::vector<json> Utils::Obs::ArrayHelper::GetOutputList()
{
std::vector<json> outputs;
auto cb = [](void *param, obs_output_t *output) {
auto outputs = reinterpret_cast<std::vector<json> *>(param);
auto rawFlags = obs_output_get_flags(output);
json flags;
flags["OBS_OUTPUT_AUDIO"] = !!(rawFlags & OBS_OUTPUT_AUDIO);
flags["OBS_OUTPUT_VIDEO"] = !!(rawFlags & OBS_OUTPUT_VIDEO);
flags["OBS_OUTPUT_ENCODED"] = !!(rawFlags & OBS_OUTPUT_ENCODED);
flags["OBS_OUTPUT_MULTI_TRACK"] = !!(rawFlags & OBS_OUTPUT_MULTI_TRACK);
flags["OBS_OUTPUT_SERVICE"] = !!(rawFlags & OBS_OUTPUT_SERVICE);
json outputJson;
outputJson["outputName"] = obs_output_get_name(output);
outputJson["outputKind"] = obs_output_get_id(output);
outputJson["outputWidth"] = obs_output_get_width(output);
outputJson["outputHeight"] = obs_output_get_height(output);
outputJson["outputActive"] = obs_output_active(output);
outputJson["outputFlags"] = flags;
outputs->push_back(outputJson);
return true;
};
obs_enum_outputs(cb, &outputs);
return outputs;
}

View File

@ -1,60 +0,0 @@
/*
obs-websocket
Copyright (C) 2020-2021 Kyle Manning <tt2468@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program. If not, see <https://www.gnu.org/licenses/>
*/
#include "Obs.h"
#include "../plugin-macros.generated.h"
#define RET_COMPARE(str, x) if (str == #x) return x;
enum obs_bounds_type Utils::Obs::EnumHelper::GetSceneItemBoundsType(std::string boundsType)
{
RET_COMPARE(boundsType, OBS_BOUNDS_NONE)
RET_COMPARE(boundsType, OBS_BOUNDS_STRETCH)
RET_COMPARE(boundsType, OBS_BOUNDS_SCALE_INNER)
RET_COMPARE(boundsType, OBS_BOUNDS_SCALE_OUTER)
RET_COMPARE(boundsType, OBS_BOUNDS_SCALE_TO_WIDTH)
RET_COMPARE(boundsType, OBS_BOUNDS_SCALE_TO_HEIGHT)
RET_COMPARE(boundsType, OBS_BOUNDS_MAX_ONLY)
return OBS_BOUNDS_NONE;
}
enum ObsMediaInputAction Utils::Obs::EnumHelper::GetMediaInputAction(std::string mediaAction)
{
RET_COMPARE(mediaAction, OBS_WEBSOCKET_MEDIA_INPUT_ACTION_PLAY)
RET_COMPARE(mediaAction, OBS_WEBSOCKET_MEDIA_INPUT_ACTION_PAUSE)
RET_COMPARE(mediaAction, OBS_WEBSOCKET_MEDIA_INPUT_ACTION_STOP)
RET_COMPARE(mediaAction, OBS_WEBSOCKET_MEDIA_INPUT_ACTION_RESTART)
RET_COMPARE(mediaAction, OBS_WEBSOCKET_MEDIA_INPUT_ACTION_NEXT)
RET_COMPARE(mediaAction, OBS_WEBSOCKET_MEDIA_INPUT_ACTION_PREVIOUS)
return OBS_WEBSOCKET_MEDIA_INPUT_ACTION_NONE;
}
enum obs_blending_type Utils::Obs::EnumHelper::GetSceneItemBlendMode(std::string mode)
{
RET_COMPARE(mode, OBS_BLEND_NORMAL)
RET_COMPARE(mode, OBS_BLEND_ADDITIVE)
RET_COMPARE(mode, OBS_BLEND_SUBTRACT)
RET_COMPARE(mode, OBS_BLEND_SCREEN)
RET_COMPARE(mode, OBS_BLEND_MULTIPLY)
RET_COMPARE(mode, OBS_BLEND_LIGHTEN)
RET_COMPARE(mode, OBS_BLEND_DARKEN)
return OBS_BLEND_NORMAL;
}

View File

@ -54,8 +54,8 @@ json Utils::Obs::ObjectHelper::GetSceneItemTransform(obs_sceneitem_t *item)
obs_sceneitem_get_crop(item, &crop); obs_sceneitem_get_crop(item, &crop);
OBSSource source = obs_sceneitem_get_source(item); OBSSource source = obs_sceneitem_get_source(item);
float sourceWidth = float(obs_source_get_width(source)); float sourceWidth = (float)obs_source_get_width(source);
float sourceHeight = float(obs_source_get_height(source)); float sourceHeight = (float)obs_source_get_height(source);
ret["sourceWidth"] = sourceWidth; ret["sourceWidth"] = sourceWidth;
ret["sourceHeight"] = sourceHeight; ret["sourceHeight"] = sourceHeight;
@ -73,15 +73,15 @@ json Utils::Obs::ObjectHelper::GetSceneItemTransform(obs_sceneitem_t *item)
ret["alignment"] = osi.alignment; ret["alignment"] = osi.alignment;
ret["boundsType"] = StringHelper::GetSceneItemBoundsType(osi.bounds_type); ret["boundsType"] = osi.bounds_type;
ret["boundsAlignment"] = osi.bounds_alignment; ret["boundsAlignment"] = osi.bounds_alignment;
ret["boundsWidth"] = osi.bounds.x; ret["boundsWidth"] = osi.bounds.x;
ret["boundsHeight"] = osi.bounds.y; ret["boundsHeight"] = osi.bounds.y;
ret["cropLeft"] = int(crop.left); ret["cropLeft"] = (int)crop.left;
ret["cropRight"] = int(crop.right); ret["cropRight"] = (int)crop.right;
ret["cropTop"] = int(crop.top); ret["cropTop"] = (int)crop.top;
ret["cropBottom"] = int(crop.bottom); ret["cropBottom"] = (int)crop.bottom;
return ret; return ret;
} }

View File

@ -54,15 +54,44 @@ obs_source_t *Utils::Obs::SearchHelper::GetSceneTransitionByName(std::string nam
return ret; return ret;
} }
struct SceneItemSearchData {
std::string name;
int offset;
obs_sceneitem_t *ret = nullptr;
};
// Increments item ref. Use OBSSceneItemAutoRelease // Increments item ref. Use OBSSceneItemAutoRelease
obs_sceneitem_t *Utils::Obs::SearchHelper::GetSceneItemByName(obs_scene_t *scene, std::string name) obs_sceneitem_t *Utils::Obs::SearchHelper::GetSceneItemByName(obs_scene_t *scene, std::string name, int offset)
{ {
if (name.empty()) if (name.empty())
return nullptr; return nullptr;
// Finds first matching scene item in scene, search starts at index 0 SceneItemSearchData enumData;
OBSSceneItem ret = obs_scene_find_source(scene, name.c_str()); enumData.name = name;
obs_sceneitem_addref(ret); enumData.offset = offset;
return ret; auto cb = [](obs_scene_t *, obs_sceneitem_t *sceneItem, void *param) {
auto enumData = static_cast<SceneItemSearchData *>(param);
OBSSource itemSource = obs_sceneitem_get_source(sceneItem);
std::string sourceName = obs_source_get_name(itemSource);
if (sourceName == enumData->name) {
if (enumData->offset > 0) {
enumData->offset--;
} else {
if (enumData->ret) // Release existing selection in the case of last match selection
obs_sceneitem_release(enumData->ret);
obs_sceneitem_addref(sceneItem);
enumData->ret = sceneItem;
if (enumData->offset == 0) // Only break if in normal selection mode (not offset == -1)
return false;
}
}
return true;
};
obs_scene_enum_items(scene, cb, &enumData);
return enumData.ret;
} }

View File

@ -23,7 +23,9 @@ with this program. If not, see <https://www.gnu.org/licenses/>
#include "Obs.h" #include "Obs.h"
#include "../plugin-macros.generated.h" #include "../plugin-macros.generated.h"
#define CASE(x) case x: return #x; #define CASE(x) \
case x: \
return #x;
std::string Utils::Obs::StringHelper::GetObsVersion() std::string Utils::Obs::StringHelper::GetObsVersion()
{ {
@ -70,54 +72,27 @@ std::string Utils::Obs::StringHelper::GetCurrentRecordOutputPath()
return ret; return ret;
} }
std::string Utils::Obs::StringHelper::GetSourceType(obs_source_t *source) std::string Utils::Obs::StringHelper::GetLastRecordFileName()
{ {
obs_source_type sourceType = obs_source_get_type(source); OBSOutputAutoRelease output = obs_frontend_get_recording_output();
if (!output)
return "";
switch (sourceType) { OBSDataAutoRelease outputSettings = obs_output_get_settings(output);
default:
CASE(OBS_SOURCE_TYPE_INPUT) obs_data_item_t *item = obs_data_item_byname(outputSettings, "url");
CASE(OBS_SOURCE_TYPE_FILTER) if (!item) {
CASE(OBS_SOURCE_TYPE_TRANSITION) item = obs_data_item_byname(outputSettings, "path");
CASE(OBS_SOURCE_TYPE_SCENE) if (!item)
} return "";
} }
std::string Utils::Obs::StringHelper::GetInputMonitorType(enum obs_monitoring_type monitorType) std::string ret = obs_data_item_get_string(item);
{ obs_data_item_release(&item);
switch (monitorType) { return ret;
default:
CASE(OBS_MONITORING_TYPE_NONE)
CASE(OBS_MONITORING_TYPE_MONITOR_ONLY)
CASE(OBS_MONITORING_TYPE_MONITOR_AND_OUTPUT)
}
} }
std::string Utils::Obs::StringHelper::GetInputMonitorType(obs_source_t *input) std::string Utils::Obs::StringHelper::GetLastReplayBufferFileName()
{
obs_monitoring_type monitorType = obs_source_get_monitoring_type(input);
return GetInputMonitorType(monitorType);
}
std::string Utils::Obs::StringHelper::GetMediaInputState(obs_source_t *input)
{
obs_media_state mediaState = obs_source_media_get_state(input);
switch (mediaState) {
default:
CASE(OBS_MEDIA_STATE_NONE)
CASE(OBS_MEDIA_STATE_PLAYING)
CASE(OBS_MEDIA_STATE_OPENING)
CASE(OBS_MEDIA_STATE_BUFFERING)
CASE(OBS_MEDIA_STATE_PAUSED)
CASE(OBS_MEDIA_STATE_STOPPED)
CASE(OBS_MEDIA_STATE_ENDED)
CASE(OBS_MEDIA_STATE_ERROR)
}
}
std::string Utils::Obs::StringHelper::GetLastReplayBufferFilePath()
{ {
OBSOutputAutoRelease output = obs_frontend_get_replay_buffer_output(); OBSOutputAutoRelease output = obs_frontend_get_replay_buffer_output();
if (!output) if (!output)
@ -135,34 +110,6 @@ std::string Utils::Obs::StringHelper::GetLastReplayBufferFilePath()
return savedReplayPath; return savedReplayPath;
} }
std::string Utils::Obs::StringHelper::GetSceneItemBoundsType(enum obs_bounds_type type)
{
switch (type) {
default:
CASE(OBS_BOUNDS_NONE)
CASE(OBS_BOUNDS_STRETCH)
CASE(OBS_BOUNDS_SCALE_INNER)
CASE(OBS_BOUNDS_SCALE_OUTER)
CASE(OBS_BOUNDS_SCALE_TO_WIDTH)
CASE(OBS_BOUNDS_SCALE_TO_HEIGHT)
CASE(OBS_BOUNDS_MAX_ONLY)
}
}
std::string Utils::Obs::StringHelper::GetSceneItemBlendMode(enum obs_blending_type mode)
{
switch (mode) {
default:
CASE(OBS_BLEND_NORMAL)
CASE(OBS_BLEND_ADDITIVE)
CASE(OBS_BLEND_SUBTRACT)
CASE(OBS_BLEND_SCREEN)
CASE(OBS_BLEND_MULTIPLY)
CASE(OBS_BLEND_LIGHTEN)
CASE(OBS_BLEND_DARKEN)
}
}
std::string Utils::Obs::StringHelper::DurationToTimecode(uint64_t ms) std::string Utils::Obs::StringHelper::DurationToTimecode(uint64_t ms)
{ {
uint64_t secs = ms / 1000ULL; uint64_t secs = ms / 1000ULL;
@ -173,20 +120,7 @@ std::string Utils::Obs::StringHelper::DurationToTimecode(uint64_t ms)
uint64_t secsPart = secs % 60ULL; uint64_t secsPart = secs % 60ULL;
uint64_t msPart = ms % 1000ULL; uint64_t msPart = ms % 1000ULL;
QString formatted = QString::asprintf("%02" PRIu64 ":%02" PRIu64 ":%02" PRIu64 ".%03" PRIu64, hoursPart, minutesPart, secsPart, msPart); QString formatted =
QString::asprintf("%02" PRIu64 ":%02" PRIu64 ":%02" PRIu64 ".%03" PRIu64, hoursPart, minutesPart, secsPart, msPart);
return formatted.toStdString(); return formatted.toStdString();
} }
std::string Utils::Obs::StringHelper::GetOutputState(ObsOutputState state)
{
switch (state) {
default:
CASE(OBS_WEBSOCKET_OUTPUT_UNKNOWN)
CASE(OBS_WEBSOCKET_OUTPUT_STARTING)
CASE(OBS_WEBSOCKET_OUTPUT_STARTED)
CASE(OBS_WEBSOCKET_OUTPUT_STOPPING)
CASE(OBS_WEBSOCKET_OUTPUT_STOPPED)
CASE(OBS_WEBSOCKET_OUTPUT_PAUSED)
CASE(OBS_WEBSOCKET_OUTPUT_RESUMED)
}
}

View File

@ -26,8 +26,8 @@ with this program. If not, see <https://www.gnu.org/licenses/>
#include "Obs_VolumeMeter_Helpers.h" #include "Obs_VolumeMeter_Helpers.h"
#include "../obs-websocket.h" #include "../obs-websocket.h"
Utils::Obs::VolumeMeter::Meter::Meter(obs_source_t *input) : Utils::Obs::VolumeMeter::Meter::Meter(obs_source_t *input)
PeakMeterType(SAMPLE_PEAK_METER), : PeakMeterType(SAMPLE_PEAK_METER),
_input(obs_source_get_weak_source(input)), _input(obs_source_get_weak_source(input)),
_channels(0), _channels(0),
_lastUpdate(0), _lastUpdate(0),
@ -45,7 +45,8 @@ Utils::Obs::VolumeMeter::Meter::~Meter()
{ {
OBSSourceAutoRelease input = obs_weak_source_get_source(_input); OBSSourceAutoRelease input = obs_weak_source_get_source(_input);
if (!input) { if (!input) {
blog(LOG_WARNING, "[Utils::Obs::VolumeMeter::Meter::~Meter] Failed to get strong reference to input. Has it been destroyed?"); blog(LOG_WARNING,
"[Utils::Obs::VolumeMeter::Meter::~Meter] Failed to get strong reference to input. Has it been destroyed?");
return; return;
} }
@ -68,7 +69,8 @@ json Utils::Obs::VolumeMeter::Meter::GetMeterData()
OBSSourceAutoRelease input = obs_weak_source_get_source(_input); OBSSourceAutoRelease input = obs_weak_source_get_source(_input);
if (!input) { if (!input) {
blog(LOG_WARNING, "[Utils::Obs::VolumeMeter::Meter::GetMeterData] Failed to get strong reference to input. Has it been destroyed?"); blog(LOG_WARNING,
"[Utils::Obs::VolumeMeter::Meter::GetMeterData] Failed to get strong reference to input. Has it been destroyed?");
return ret; return ret;
} }
@ -212,7 +214,8 @@ void Utils::Obs::VolumeMeter::Meter::ProcessMagnitude(const struct audio_data *d
} }
} }
void Utils::Obs::VolumeMeter::Meter::InputAudioCaptureCallback(void *priv_data, obs_source_t *, const struct audio_data *data, bool muted) void Utils::Obs::VolumeMeter::Meter::InputAudioCaptureCallback(void *priv_data, obs_source_t *, const struct audio_data *data,
bool muted)
{ {
auto c = static_cast<Meter *>(priv_data); auto c = static_cast<Meter *>(priv_data);
@ -233,10 +236,8 @@ void Utils::Obs::VolumeMeter::Meter::InputVolumeCallback(void *priv_data, callda
c->_volume = (float)calldata_float(cd, "volume"); c->_volume = (float)calldata_float(cd, "volume");
} }
Utils::Obs::VolumeMeter::Handler::Handler(UpdateCallback cb, uint64_t updatePeriod) : Utils::Obs::VolumeMeter::Handler::Handler(UpdateCallback cb, uint64_t updatePeriod)
_updateCallback(cb), : _updateCallback(cb), _updatePeriod(updatePeriod), _running(false)
_updatePeriod(updatePeriod),
_running(false)
{ {
signal_handler_t *sh = obs_get_signal_handler(); signal_handler_t *sh = obs_get_signal_handler();
if (!sh) if (!sh)

View File

@ -65,7 +65,8 @@ namespace Utils {
void ProcessPeak(const struct audio_data *data); void ProcessPeak(const struct audio_data *data);
void ProcessMagnitude(const struct audio_data *data); void ProcessMagnitude(const struct audio_data *data);
static void InputAudioCaptureCallback(void *priv_data, obs_source_t *source, const struct audio_data *data, bool muted); static void InputAudioCaptureCallback(void *priv_data, obs_source_t *source,
const struct audio_data *data, bool muted);
static void InputVolumeCallback(void *priv_data, calldata_t *cd); static void InputVolumeCallback(void *priv_data, calldata_t *cd);
}; };

View File

@ -24,8 +24,7 @@ with this program. If not, see <https://www.gnu.org/licenses/>
#define SHIFT_RIGHT_2PS(msb, lsb) \ #define SHIFT_RIGHT_2PS(msb, lsb) \
{ \ { \
__m128 tmp = \ __m128 tmp = _mm_shuffle_ps(lsb, msb, _MM_SHUFFLE(0, 0, 3, 3)); \
_mm_shuffle_ps(lsb, msb, _MM_SHUFFLE(0, 0, 3, 3)); \
lsb = _mm_shuffle_ps(lsb, tmp, _MM_SHUFFLE(2, 1, 2, 1)); \ lsb = _mm_shuffle_ps(lsb, tmp, _MM_SHUFFLE(2, 1, 2, 1)); \
msb = _mm_shuffle_ps(msb, msb, _MM_SHUFFLE(3, 3, 2, 1)); \ msb = _mm_shuffle_ps(msb, msb, _MM_SHUFFLE(3, 3, 2, 1)); \
} }

View File

@ -53,7 +53,11 @@ std::string Utils::Platform::GetLocalAddress()
std::vector<std::pair<QString, uint8_t>> preferredAddresses; std::vector<std::pair<QString, uint8_t>> preferredAddresses;
for (auto address : validAddresses) { for (auto address : validAddresses) {
// Attribute a priority (0 is best) to the address to choose the best picks // Attribute a priority (0 is best) to the address to choose the best picks
if (address.startsWith("192.168.1.") || address.startsWith("192.168.0.")) { // Prefer common consumer router network prefixes if (address.startsWith("192.168.1.") ||
address.startsWith("192.168.0.")) { // Prefer common consumer router network prefixes
if (address.startsWith("192.168.56."))
preferredAddresses.push_back(std::make_pair(address, 255)); // Ignore virtualbox default
else
preferredAddresses.push_back(std::make_pair(address, 0)); preferredAddresses.push_back(std::make_pair(address, 0));
} else if (address.startsWith("172.16.")) { // Slightly less common consumer router network prefixes } else if (address.startsWith("172.16.")) { // Slightly less common consumer router network prefixes
preferredAddresses.push_back(std::make_pair(address, 1)); preferredAddresses.push_back(std::make_pair(address, 1));
@ -65,9 +69,8 @@ std::string Utils::Platform::GetLocalAddress()
} }
// Sort by priority // Sort by priority
std::sort(preferredAddresses.begin(), preferredAddresses.end(), [=](std::pair<QString, uint8_t> a, std::pair<QString, uint8_t> b) { std::sort(preferredAddresses.begin(), preferredAddresses.end(),
return a.second < b.second; [=](std::pair<QString, uint8_t> a, std::pair<QString, uint8_t> b) { return a.second < b.second; });
});
// Return highest priority address // Return highest priority address
return preferredAddresses[0].first.toStdString(); return preferredAddresses[0].first.toStdString();
@ -109,14 +112,17 @@ void Utils::Platform::SendTrayNotification(QSystemTrayIcon::MessageIcon icon, QS
SystemTrayNotification *notification = new SystemTrayNotification{icon, title, body}; SystemTrayNotification *notification = new SystemTrayNotification{icon, title, body};
obs_queue_task(OBS_TASK_UI, [](void* param) { obs_queue_task(
OBS_TASK_UI,
[](void *param) {
void *systemTrayPtr = obs_frontend_get_system_tray(); void *systemTrayPtr = obs_frontend_get_system_tray();
auto systemTray = static_cast<QSystemTrayIcon *>(systemTrayPtr); auto systemTray = static_cast<QSystemTrayIcon *>(systemTrayPtr);
auto notification = static_cast<SystemTrayNotification *>(param); auto notification = static_cast<SystemTrayNotification *>(param);
systemTray->showMessage(notification->title, notification->body, notification->icon); systemTray->showMessage(notification->title, notification->body, notification->icon);
delete notification; delete notification;
}, (void*)notification, false); },
(void *)notification, false);
} }
bool Utils::Platform::GetTextFileContent(std::string fileName, std::string &content) bool Utils::Platform::GetTextFileContent(std::string fileName, std::string &content)

View File

@ -31,9 +31,7 @@ with this program. If not, see <https://www.gnu.org/licenses/>
#include "../utils/Platform.h" #include "../utils/Platform.h"
#include "../utils/Compat.h" #include "../utils/Compat.h"
WebSocketServer::WebSocketServer() : WebSocketServer::WebSocketServer() : QObject(nullptr), _sessions()
QObject(nullptr),
_sessions()
{ {
_server.get_alog().clear_channels(websocketpp::log::alevel::all); _server.get_alog().clear_channels(websocketpp::log::alevel::all);
_server.get_elog().clear_channels(websocketpp::log::elevel::all); _server.get_elog().clear_channels(websocketpp::log::elevel::all);
@ -44,38 +42,17 @@ WebSocketServer::WebSocketServer() :
#endif #endif
_server.set_validate_handler( _server.set_validate_handler(
websocketpp::lib::bind( websocketpp::lib::bind(&WebSocketServer::onValidate, this, websocketpp::lib::placeholders::_1));
&WebSocketServer::onValidate, this, websocketpp::lib::placeholders::_1 _server.set_open_handler(websocketpp::lib::bind(&WebSocketServer::onOpen, this, websocketpp::lib::placeholders::_1));
) _server.set_close_handler(websocketpp::lib::bind(&WebSocketServer::onClose, this, websocketpp::lib::placeholders::_1));
); _server.set_message_handler(websocketpp::lib::bind(&WebSocketServer::onMessage, this, websocketpp::lib::placeholders::_1,
_server.set_open_handler( websocketpp::lib::placeholders::_2));
websocketpp::lib::bind(
&WebSocketServer::onOpen, this, websocketpp::lib::placeholders::_1
)
);
_server.set_close_handler(
websocketpp::lib::bind(
&WebSocketServer::onClose, this, websocketpp::lib::placeholders::_1
)
);
_server.set_message_handler(
websocketpp::lib::bind(
&WebSocketServer::onMessage, this, websocketpp::lib::placeholders::_1, websocketpp::lib::placeholders::_2
)
);
auto eventHandler = GetEventHandler(); auto eventHandler = GetEventHandler();
eventHandler->SetBroadcastCallback( eventHandler->SetBroadcastCallback(std::bind(&WebSocketServer::BroadcastEvent, this, std::placeholders::_1,
std::bind( std::placeholders::_2, std::placeholders::_3, std::placeholders::_4));
&WebSocketServer::BroadcastEvent, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4
)
);
eventHandler->SetObsLoadedCallback( eventHandler->SetObsLoadedCallback(std::bind(&WebSocketServer::onObsLoaded, this));
std::bind(
&WebSocketServer::onObsLoaded, this
)
);
} }
WebSocketServer::~WebSocketServer() WebSocketServer::~WebSocketServer()
@ -118,7 +95,8 @@ void WebSocketServer::Start()
// Set log levels if debug is enabled // Set log levels if debug is enabled
if (IsDebugEnabled()) { if (IsDebugEnabled()) {
_server.get_alog().set_channels(websocketpp::log::alevel::all); _server.get_alog().set_channels(websocketpp::log::alevel::all);
_server.get_alog().clear_channels(websocketpp::log::alevel::frame_header | websocketpp::log::alevel::frame_payload | websocketpp::log::alevel::control); _server.get_alog().clear_channels(websocketpp::log::alevel::frame_header | websocketpp::log::alevel::frame_payload |
websocketpp::log::alevel::control);
_server.get_elog().set_channels(websocketpp::log::elevel::all); _server.get_elog().set_channels(websocketpp::log::elevel::all);
_server.get_alog().clear_channels(websocketpp::log::elevel::devel | websocketpp::log::elevel::library); _server.get_alog().clear_channels(websocketpp::log::elevel::devel | websocketpp::log::elevel::library);
} else { } else {
@ -129,7 +107,13 @@ void WebSocketServer::Start()
_server.reset(); _server.reset();
websocketpp::lib::error_code errorCode; websocketpp::lib::error_code errorCode;
if (conf->Ipv4Only) {
blog(LOG_INFO, "[WebSocketServer::Start] Locked to IPv4 bindings");
_server.listen(websocketpp::lib::asio::ip::tcp::v4(), conf->ServerPort, errorCode); _server.listen(websocketpp::lib::asio::ip::tcp::v4(), conf->ServerPort, errorCode);
} else {
blog(LOG_INFO, "[WebSocketServer::Start] Not locked to IPv4 bindings");
_server.listen(conf->ServerPort, errorCode);
}
if (errorCode) { if (errorCode) {
std::string errorCodeMessage = errorCode.message(); std::string errorCodeMessage = errorCode.message();
@ -141,7 +125,8 @@ void WebSocketServer::Start()
_serverThread = std::thread(&WebSocketServer::ServerRunner, this); _serverThread = std::thread(&WebSocketServer::ServerRunner, this);
blog(LOG_INFO, "[WebSocketServer::Start] Server started successfully on port %d. Possible connect address: %s", conf->ServerPort.load(), Utils::Platform::GetLocalAddress().c_str()); blog(LOG_INFO, "[WebSocketServer::Start] Server started successfully on port %d. Possible connect address: %s",
conf->ServerPort.load(), Utils::Platform::GetLocalAddress().c_str());
} }
void WebSocketServer::Stop() void WebSocketServer::Stop()
@ -212,7 +197,8 @@ std::vector<WebSocketServer::WebSocketSessionState> WebSocketServer::GetWebSocke
std::string remoteAddress = session->RemoteAddress(); std::string remoteAddress = session->RemoteAddress();
bool isIdentified = session->IsIdentified(); bool isIdentified = session->IsIdentified();
webSocketSessions.emplace_back(WebSocketSessionState{hdl, remoteAddress, connectedAt, incomingMessages, outgoingMessages, isIdentified}); webSocketSessions.emplace_back(
WebSocketSessionState{hdl, remoteAddress, connectedAt, incomingMessages, outgoingMessages, isIdentified});
} }
lock.unlock(); lock.unlock();
@ -358,7 +344,8 @@ void WebSocketServer::onClose(websocketpp::connection_hdl hdl)
emit ClientDisconnected(state, conn->get_local_close_code()); emit ClientDisconnected(state, conn->get_local_close_code());
// Log disconnection // Log disconnection
blog(LOG_INFO, "[WebSocketServer::onClose] WebSocket client %s has disconnected", remoteAddress.c_str()); blog(LOG_INFO, "[WebSocketServer::onClose] WebSocket client `%s` has disconnected with code `%d` and reason: %s",
remoteAddress.c_str(), conn->get_local_close_code(), conn->get_local_close_reason().c_str());
// Get config for tray notification // Get config for tray notification
auto conf = GetConfig(); auto conf = GetConfig();
@ -370,12 +357,14 @@ void WebSocketServer::onClose(websocketpp::connection_hdl hdl)
// If previously identified, not going away, and notifications enabled, send a tray notification // If previously identified, not going away, and notifications enabled, send a tray notification
if (isIdentified && (conn->get_local_close_code() != websocketpp::close::status::going_away) && conf->AlertsEnabled) { if (isIdentified && (conn->get_local_close_code() != websocketpp::close::status::going_away) && conf->AlertsEnabled) {
QString title = obs_module_text("OBSWebSocket.TrayNotification.Disconnected.Title"); QString title = obs_module_text("OBSWebSocket.TrayNotification.Disconnected.Title");
QString body = QString(obs_module_text("OBSWebSocket.TrayNotification.Disconnected.Body")).arg(QString::fromStdString(remoteAddress)); QString body = QString(obs_module_text("OBSWebSocket.TrayNotification.Disconnected.Body"))
.arg(QString::fromStdString(remoteAddress));
Utils::Platform::SendTrayNotification(QSystemTrayIcon::Information, title, body); Utils::Platform::SendTrayNotification(QSystemTrayIcon::Information, title, body);
} }
} }
void WebSocketServer::onMessage(websocketpp::connection_hdl hdl, websocketpp::server<websocketpp::config::asio>::message_ptr message) void WebSocketServer::onMessage(websocketpp::connection_hdl hdl,
websocketpp::server<websocketpp::config::asio>::message_ptr message)
{ {
auto opCode = message->get_opcode(); auto opCode = message->get_opcode();
std::string payload = message->get_payload(); std::string payload = message->get_payload();
@ -398,26 +387,32 @@ void WebSocketServer::onMessage(websocketpp::connection_hdl hdl, websocketpp::se
uint8_t sessionEncoding = session->Encoding(); uint8_t sessionEncoding = session->Encoding();
if (sessionEncoding == WebSocketEncoding::Json) { if (sessionEncoding == WebSocketEncoding::Json) {
if (opCode != websocketpp::frame::opcode::text) { if (opCode != websocketpp::frame::opcode::text) {
_server.close(hdl, WebSocketCloseCode::MessageDecodeError, "Your session encoding is set to Json, but a binary message was received.", errorCode); _server.close(hdl, WebSocketCloseCode::MessageDecodeError,
"Your session encoding is set to Json, but a binary message was received.",
errorCode);
return; return;
} }
try { try {
incomingMessage = json::parse(payload); incomingMessage = json::parse(payload);
} catch (json::parse_error &e) { } catch (json::parse_error &e) {
_server.close(hdl, WebSocketCloseCode::MessageDecodeError, std::string("Unable to decode Json: ") + e.what(), errorCode); _server.close(hdl, WebSocketCloseCode::MessageDecodeError,
std::string("Unable to decode Json: ") + e.what(), errorCode);
return; return;
} }
} else if (sessionEncoding == WebSocketEncoding::MsgPack) { } else if (sessionEncoding == WebSocketEncoding::MsgPack) {
if (opCode != websocketpp::frame::opcode::binary) { if (opCode != websocketpp::frame::opcode::binary) {
_server.close(hdl, WebSocketCloseCode::MessageDecodeError, "Your session encoding is set to MsgPack, but a text message was received.", errorCode); _server.close(hdl, WebSocketCloseCode::MessageDecodeError,
"Your session encoding is set to MsgPack, but a text message was received.",
errorCode);
return; return;
} }
try { try {
incomingMessage = json::from_msgpack(payload); incomingMessage = json::from_msgpack(payload);
} catch (json::parse_error &e) { } catch (json::parse_error &e) {
_server.close(hdl, WebSocketCloseCode::MessageDecodeError, std::string("Unable to decode MsgPack: ") + e.what(), errorCode); _server.close(hdl, WebSocketCloseCode::MessageDecodeError,
std::string("Unable to decode MsgPack: ") + e.what(), errorCode);
return; return;
} }
} }
@ -435,9 +430,11 @@ void WebSocketServer::onMessage(websocketpp::connection_hdl hdl, websocketpp::se
// Disconnect client if 4.x protocol is detected // Disconnect client if 4.x protocol is detected
if (!session->IsIdentified() && incomingMessage.contains("request-type")) { if (!session->IsIdentified() && incomingMessage.contains("request-type")) {
blog(LOG_WARNING, "[WebSocketServer::onMessage] Client %s appears to be running a pre-5.0.0 protocol.", session->RemoteAddress().c_str()); blog(LOG_WARNING, "[WebSocketServer::onMessage] Client %s appears to be running a pre-5.0.0 protocol.",
session->RemoteAddress().c_str());
ret.closeCode = WebSocketCloseCode::UnsupportedRpcVersion; ret.closeCode = WebSocketCloseCode::UnsupportedRpcVersion;
ret.closeReason = "You appear to be attempting to connect with the pre-5.0.0 plugin protocol. Check to make sure your client is updated."; ret.closeReason =
"You appear to be attempting to connect with the pre-5.0.0 plugin protocol. Check to make sure your client is updated.";
goto skipProcessing; goto skipProcessing;
} }
@ -448,6 +445,12 @@ void WebSocketServer::onMessage(websocketpp::connection_hdl hdl, websocketpp::se
goto skipProcessing; goto skipProcessing;
} }
if (!incomingMessage["op"].is_number()) {
ret.closeCode = WebSocketCloseCode::UnknownOpCode;
ret.closeReason = "Your `op` is not a number.";
goto skipProcessing;
}
ProcessMessage(session, ret, incomingMessage["op"], incomingMessage["d"]); ProcessMessage(session, ret, incomingMessage["op"], incomingMessage["d"]);
skipProcessing: skipProcessing:
@ -472,7 +475,8 @@ skipProcessing:
blog_debug("[WebSocketServer::onMessage] Outgoing message:\n%s", ret.result.dump(2).c_str()); blog_debug("[WebSocketServer::onMessage] Outgoing message:\n%s", ret.result.dump(2).c_str());
if (errorCode) if (errorCode)
blog(LOG_WARNING, "[WebSocketServer::onMessage] Sending message to client failed: %s", errorCode.message().c_str()); blog(LOG_WARNING, "[WebSocketServer::onMessage] Sending message to client failed: %s",
errorCode.message().c_str());
} }
})); }));
} }

View File

@ -34,15 +34,11 @@ with this program. If not, see <https://www.gnu.org/licenses/>
#include "../requesthandler/rpc/Request.h" #include "../requesthandler/rpc/Request.h"
#include "../plugin-macros.generated.h" #include "../plugin-macros.generated.h"
class WebSocketServer : QObject class WebSocketServer : QObject {
{
Q_OBJECT Q_OBJECT
public: public:
enum WebSocketEncoding { enum WebSocketEncoding { Json, MsgPack };
Json,
MsgPack
};
struct WebSocketSessionState { struct WebSocketSessionState {
websocketpp::connection_hdl hdl; websocketpp::connection_hdl hdl;
@ -59,17 +55,14 @@ class WebSocketServer : QObject
void Start(); void Start();
void Stop(); void Stop();
void InvalidateSession(websocketpp::connection_hdl hdl); void InvalidateSession(websocketpp::connection_hdl hdl);
void BroadcastEvent(uint64_t requiredIntent, const std::string &eventType, const json &eventData = nullptr, uint8_t rpcVersion = 0); void BroadcastEvent(uint64_t requiredIntent, const std::string &eventType, const json &eventData = nullptr,
uint8_t rpcVersion = 0);
bool IsListening() { bool IsListening() { return _server.is_listening(); }
return _server.is_listening();
}
std::vector<WebSocketSessionState> GetWebSocketSessions(); std::vector<WebSocketSessionState> GetWebSocketSessions();
QThreadPool *GetThreadPool() { QThreadPool *GetThreadPool() { return &_threadPool; }
return &_threadPool;
}
signals: signals:
void ClientConnected(WebSocketSessionState state); void ClientConnected(WebSocketSessionState state);

View File

@ -44,10 +44,7 @@ static json ConstructRequestResult(RequestResult requestResult, const json &requ
if (requestJson.contains("requestId") && !requestJson["requestId"].is_null()) if (requestJson.contains("requestId") && !requestJson["requestId"].is_null())
ret["requestId"] = requestJson["requestId"]; ret["requestId"] = requestJson["requestId"];
ret["requestStatus"] = { ret["requestStatus"] = {{"result", requestResult.StatusCode == RequestStatus::Success}, {"code", requestResult.StatusCode}};
{"result", requestResult.StatusCode == RequestStatus::Success},
{"code", requestResult.StatusCode}
};
if (!requestResult.Comment.empty()) if (!requestResult.Comment.empty())
ret["requestStatus"]["comment"] = requestResult.Comment; ret["requestStatus"]["comment"] = requestResult.Comment;
@ -70,7 +67,8 @@ void WebSocketServer::SetSessionParameters(SessionPtr session, ProcessResult &re
} }
} }
void WebSocketServer::ProcessMessage(SessionPtr session, WebSocketServer::ProcessResult &ret, WebSocketOpCode::WebSocketOpCode opCode, json &payloadData) void WebSocketServer::ProcessMessage(SessionPtr session, WebSocketServer::ProcessResult &ret,
WebSocketOpCode::WebSocketOpCode opCode, json &payloadData)
{ {
if (!payloadData.is_object()) { if (!payloadData.is_object()) {
if (payloadData.is_null()) { if (payloadData.is_null()) {
@ -102,14 +100,18 @@ void WebSocketServer::ProcessMessage(SessionPtr session, WebSocketServer::Proces
if (session->AuthenticationRequired()) { if (session->AuthenticationRequired()) {
if (!payloadData.contains("authentication")) { if (!payloadData.contains("authentication")) {
ret.closeCode = WebSocketCloseCode::AuthenticationFailed; ret.closeCode = WebSocketCloseCode::AuthenticationFailed;
ret.closeReason = "Your payload's data is missing an `authentication` string, however authentication is required."; ret.closeReason =
"Your payload's data is missing an `authentication` string, however authentication is required.";
return; return;
} }
if (!Utils::Crypto::CheckAuthenticationString(session->Secret(), session->Challenge(), payloadData["authentication"])) { if (!Utils::Crypto::CheckAuthenticationString(session->Secret(), session->Challenge(),
payloadData["authentication"])) {
auto conf = GetConfig(); auto conf = GetConfig();
if (conf && conf->AlertsEnabled) { if (conf && conf->AlertsEnabled) {
QString title = obs_module_text("OBSWebSocket.TrayNotification.AuthenticationFailed.Title"); QString title = obs_module_text("OBSWebSocket.TrayNotification.AuthenticationFailed.Title");
QString body = QString(obs_module_text("OBSWebSocket.TrayNotification.AuthenticationFailed.Body")).arg(QString::fromStdString(session->RemoteAddress())); QString body =
QString(obs_module_text("OBSWebSocket.TrayNotification.AuthenticationFailed.Body"))
.arg(QString::fromStdString(session->RemoteAddress()));
Utils::Platform::SendTrayNotification(QSystemTrayIcon::Warning, title, body); Utils::Platform::SendTrayNotification(QSystemTrayIcon::Warning, title, body);
} }
ret.closeCode = WebSocketCloseCode::AuthenticationFailed; ret.closeCode = WebSocketCloseCode::AuthenticationFailed;
@ -127,6 +129,7 @@ void WebSocketServer::ProcessMessage(SessionPtr session, WebSocketServer::Proces
if (!payloadData["rpcVersion"].is_number_unsigned()) { if (!payloadData["rpcVersion"].is_number_unsigned()) {
ret.closeCode = WebSocketCloseCode::InvalidDataFieldType; ret.closeCode = WebSocketCloseCode::InvalidDataFieldType;
ret.closeReason = "Your `rpcVersion` is not an unsigned number."; ret.closeReason = "Your `rpcVersion` is not an unsigned number.";
return;
} }
uint8_t requestedRpcVersion = payloadData["rpcVersion"]; uint8_t requestedRpcVersion = payloadData["rpcVersion"];
@ -153,13 +156,15 @@ void WebSocketServer::ProcessMessage(SessionPtr session, WebSocketServer::Proces
auto conf = GetConfig(); auto conf = GetConfig();
if (conf && conf->AlertsEnabled) { if (conf && conf->AlertsEnabled) {
QString title = obs_module_text("OBSWebSocket.TrayNotification.Identified.Title"); QString title = obs_module_text("OBSWebSocket.TrayNotification.Identified.Title");
QString body = QString(obs_module_text("OBSWebSocket.TrayNotification.Identified.Body")).arg(QString::fromStdString(session->RemoteAddress())); QString body = QString(obs_module_text("OBSWebSocket.TrayNotification.Identified.Body"))
.arg(QString::fromStdString(session->RemoteAddress()));
Utils::Platform::SendTrayNotification(QSystemTrayIcon::Information, title, body); Utils::Platform::SendTrayNotification(QSystemTrayIcon::Information, title, body);
} }
ret.result["op"] = WebSocketOpCode::Identified; ret.result["op"] = WebSocketOpCode::Identified;
ret.result["d"]["negotiatedRpcVersion"] = session->RpcVersion(); ret.result["d"]["negotiatedRpcVersion"] = session->RpcVersion();
} return; }
return;
case WebSocketOpCode::Reidentify: { // Reidentify case WebSocketOpCode::Reidentify: { // Reidentify
std::unique_lock<std::mutex> sessionLock(session->OperationMutex); std::unique_lock<std::mutex> sessionLock(session->OperationMutex);
@ -177,7 +182,8 @@ void WebSocketServer::ProcessMessage(SessionPtr session, WebSocketServer::Proces
ret.result["op"] = WebSocketOpCode::Identified; ret.result["op"] = WebSocketOpCode::Identified;
ret.result["d"]["negotiatedRpcVersion"] = session->RpcVersion(); ret.result["d"]["negotiatedRpcVersion"] = session->RpcVersion();
} return; }
return;
case WebSocketOpCode::Request: { // Request case WebSocketOpCode::Request: { // Request
// RequestID checking has to be done here where we are able to close the connection. // RequestID checking has to be done here where we are able to close the connection.
if (!payloadData.contains("requestId")) { if (!payloadData.contains("requestId")) {
@ -186,25 +192,39 @@ void WebSocketServer::ProcessMessage(SessionPtr session, WebSocketServer::Proces
return; return;
} }
if (!payloadData.contains("requestType")) {
ret.closeCode = WebSocketCloseCode::MissingDataField;
ret.closeReason = "Your payload's data is missing an `requestType`.";
return;
}
if (!payloadData["requestType"].is_string()) {
ret.closeCode = WebSocketCloseCode::InvalidDataFieldType;
ret.closeReason = "Your `requestType` is not a string.";
return;
}
RequestHandler requestHandler(session); RequestHandler requestHandler(session);
Request request(payloadData["requestType"], payloadData["requestData"]);
std::string requestType = payloadData["requestType"];
json requestData = payloadData["requestData"];
Request request(requestType, requestData);
RequestResult requestResult = requestHandler.ProcessRequest(request); RequestResult requestResult = requestHandler.ProcessRequest(request);
json resultPayloadData; json resultPayloadData;
resultPayloadData["requestType"] = payloadData["requestType"]; resultPayloadData["requestType"] = requestType;
resultPayloadData["requestId"] = payloadData["requestId"]; resultPayloadData["requestId"] = payloadData["requestId"];
resultPayloadData["requestStatus"] = { resultPayloadData["requestStatus"] = {{"result", requestResult.StatusCode == RequestStatus::Success},
{"result", requestResult.StatusCode == RequestStatus::Success}, {"code", requestResult.StatusCode}};
{"code", requestResult.StatusCode}
};
if (!requestResult.Comment.empty()) if (!requestResult.Comment.empty())
resultPayloadData["requestStatus"]["comment"] = requestResult.Comment; resultPayloadData["requestStatus"]["comment"] = requestResult.Comment;
if (requestResult.ResponseData.is_object()) if (requestResult.ResponseData.is_object())
resultPayloadData["responseData"] = requestResult.ResponseData; resultPayloadData["responseData"] = requestResult.ResponseData;
ret.result["op"] = WebSocketOpCode::RequestResponse; ret.result["op"] = WebSocketOpCode::RequestResponse;
ret.result["d"] = resultPayloadData; ret.result["d"] = resultPayloadData;
} return; }
return;
case WebSocketOpCode::RequestBatch: { // RequestBatch case WebSocketOpCode::RequestBatch: { // RequestBatch
// RequestID checking has to be done here where we are able to close the connection. // RequestID checking has to be done here where we are able to close the connection.
if (!payloadData.contains("requestId")) { if (!payloadData.contains("requestId")) {
@ -213,18 +233,6 @@ void WebSocketServer::ProcessMessage(SessionPtr session, WebSocketServer::Proces
return; return;
} }
if (!payloadData.contains("requests")) {
ret.closeCode = WebSocketCloseCode::MissingDataField;
ret.closeReason = "Your payload data is missing a `requests`.";
return;
}
if (!payloadData["requests"].is_array()) {
ret.closeCode = WebSocketCloseCode::InvalidDataFieldType;
ret.closeReason = "Your `requests` is not an array.";
return;
}
RequestBatchExecutionType::RequestBatchExecutionType executionType = RequestBatchExecutionType::SerialRealtime; RequestBatchExecutionType::RequestBatchExecutionType executionType = RequestBatchExecutionType::SerialRealtime;
if (payloadData.contains("executionType") && !payloadData["executionType"].is_null()) { if (payloadData.contains("executionType") && !payloadData["executionType"].is_null()) {
if (!payloadData["executionType"].is_number_unsigned()) { if (!payloadData["executionType"].is_number_unsigned()) {
@ -234,7 +242,8 @@ void WebSocketServer::ProcessMessage(SessionPtr session, WebSocketServer::Proces
} }
int8_t requestedExecutionType = payloadData["executionType"]; int8_t requestedExecutionType = payloadData["executionType"];
if (!RequestBatchExecutionType::IsValid(requestedExecutionType) || requestedExecutionType == RequestBatchExecutionType::None) { if (!RequestBatchExecutionType::IsValid(requestedExecutionType) ||
requestedExecutionType == RequestBatchExecutionType::None) {
ret.closeCode = WebSocketCloseCode::InvalidDataFieldValue; ret.closeCode = WebSocketCloseCode::InvalidDataFieldValue;
ret.closeReason = "Your `executionType` has an invalid value."; ret.closeReason = "Your `executionType` has an invalid value.";
return; return;
@ -243,7 +252,8 @@ void WebSocketServer::ProcessMessage(SessionPtr session, WebSocketServer::Proces
// The thread pool must support 2 or more threads else parallel requests will deadlock. // The thread pool must support 2 or more threads else parallel requests will deadlock.
if (requestedExecutionType == RequestBatchExecutionType::Parallel && _threadPool.maxThreadCount() < 2) { if (requestedExecutionType == RequestBatchExecutionType::Parallel && _threadPool.maxThreadCount() < 2) {
ret.closeCode = WebSocketCloseCode::UnsupportedFeature; ret.closeCode = WebSocketCloseCode::UnsupportedFeature;
ret.closeReason = "Parallel request batch processing is not available on this system due to limited core count."; ret.closeReason =
"Parallel request batch processing is not available on this system due to limited core count.";
return; return;
} }
@ -275,13 +285,34 @@ void WebSocketServer::ProcessMessage(SessionPtr session, WebSocketServer::Proces
haltOnFailure = payloadData["haltOnFailure"]; haltOnFailure = payloadData["haltOnFailure"];
} }
if (!payloadData.contains("requests")) {
ret.closeCode = WebSocketCloseCode::MissingDataField;
ret.closeReason = "Your payload data is missing a `requests`.";
return;
}
if (!payloadData["requests"].is_array()) {
ret.closeCode = WebSocketCloseCode::InvalidDataFieldType;
ret.closeReason = "Your `requests` is not an array.";
return;
}
std::vector<json> requests = payloadData["requests"]; std::vector<json> requests = payloadData["requests"];
std::vector<RequestBatchRequest> requestsVector; std::vector<RequestBatchRequest> requestsVector;
for (auto &requestJson : requests) for (auto &requestJson : requests) {
requestsVector.emplace_back(requestJson["requestType"], requestJson["requestData"], executionType, requestJson["inputVariables"], requestJson["outputVariables"]); if (!requestJson["requestType"].is_string())
requestJson["requestType"] =
""; // Workaround for what would otherwise be extensive additional logic for a rare edge case
std::string requestType = requestJson["requestType"];
json requestData = requestJson["requestData"];
json inputVariables = requestJson["inputVariables"];
json outputVariables = requestJson["outputVariables"];
requestsVector.emplace_back(requestType, requestData, executionType, inputVariables, outputVariables);
}
auto resultsVector = RequestBatchHandler::ProcessRequestBatch(_threadPool, session, executionType, requestsVector, payloadData["variables"], haltOnFailure); auto resultsVector = RequestBatchHandler::ProcessRequestBatch(_threadPool, session, executionType, requestsVector,
payloadData["variables"], haltOnFailure);
size_t i = 0; size_t i = 0;
std::vector<json> results; std::vector<json> results;
@ -293,7 +324,8 @@ void WebSocketServer::ProcessMessage(SessionPtr session, WebSocketServer::Proces
ret.result["op"] = WebSocketOpCode::RequestBatchResponse; ret.result["op"] = WebSocketOpCode::RequestBatchResponse;
ret.result["d"]["requestId"] = payloadData["requestId"]; ret.result["d"]["requestId"] = payloadData["requestId"];
ret.result["d"]["results"] = results; ret.result["d"]["results"] = results;
} return; }
return;
default: default:
ret.closeCode = WebSocketCloseCode::UnknownOpCode; ret.closeCode = WebSocketCloseCode::UnknownOpCode;
ret.closeReason = std::string("Unknown OpCode: ") + std::to_string(opCode); ret.closeReason = std::string("Unknown OpCode: ") + std::to_string(opCode);
@ -302,7 +334,8 @@ void WebSocketServer::ProcessMessage(SessionPtr session, WebSocketServer::Proces
} }
// It isn't consistent to directly call the WebSocketServer from the events system, but it would also be dumb to make it unnecessarily complicated. // It isn't consistent to directly call the WebSocketServer from the events system, but it would also be dumb to make it unnecessarily complicated.
void WebSocketServer::BroadcastEvent(uint64_t requiredIntent, const std::string &eventType, const json &eventData, uint8_t rpcVersion) void WebSocketServer::BroadcastEvent(uint64_t requiredIntent, const std::string &eventType, const json &eventData,
uint8_t rpcVersion)
{ {
if (!_server.is_listening()) if (!_server.is_listening())
return; return;
@ -336,7 +369,8 @@ void WebSocketServer::BroadcastEvent(uint64_t requiredIntent, const std::string
if (messageJson.empty()) { if (messageJson.empty()) {
messageJson = eventMessage.dump(); messageJson = eventMessage.dump();
} }
_server.send((websocketpp::connection_hdl)it.first, messageJson, websocketpp::frame::opcode::text, errorCode); _server.send((websocketpp::connection_hdl)it.first, messageJson,
websocketpp::frame::opcode::text, errorCode);
it.second->IncrementOutgoingMessages(); it.second->IncrementOutgoingMessages();
break; break;
case WebSocketEncoding::MsgPack: case WebSocketEncoding::MsgPack:
@ -344,12 +378,14 @@ void WebSocketServer::BroadcastEvent(uint64_t requiredIntent, const std::string
auto msgPackData = json::to_msgpack(eventMessage); auto msgPackData = json::to_msgpack(eventMessage);
messageMsgPack = std::string(msgPackData.begin(), msgPackData.end()); messageMsgPack = std::string(msgPackData.begin(), msgPackData.end());
} }
_server.send((websocketpp::connection_hdl)it.first, messageMsgPack, websocketpp::frame::opcode::binary, errorCode); _server.send((websocketpp::connection_hdl)it.first, messageMsgPack,
websocketpp::frame::opcode::binary, errorCode);
it.second->IncrementOutgoingMessages(); it.second->IncrementOutgoingMessages();
break; break;
} }
if (errorCode) if (errorCode)
blog(LOG_ERROR, "[WebSocketServer::BroadcastEvent] Error sending event message: %s", errorCode.message().c_str()); blog(LOG_ERROR, "[WebSocketServer::BroadcastEvent] Error sending event message: %s",
errorCode.message().c_str());
} }
} }
lock.unlock(); lock.unlock();

View File

@ -20,8 +20,8 @@ with this program. If not, see <https://www.gnu.org/licenses/>
#include "WebSocketSession.h" #include "WebSocketSession.h"
#include "../../eventhandler/types/EventSubscription.h" #include "../../eventhandler/types/EventSubscription.h"
WebSocketSession::WebSocketSession() : WebSocketSession::WebSocketSession()
_remoteAddress(""), : _remoteAddress(""),
_connectedAt(0), _connectedAt(0),
_incomingMessages(0), _incomingMessages(0),
_outgoingMessages(0), _outgoingMessages(0),

View File

@ -29,8 +29,7 @@ with this program. If not, see <https://www.gnu.org/licenses/>
class WebSocketSession; class WebSocketSession;
typedef std::shared_ptr<WebSocketSession> SessionPtr; typedef std::shared_ptr<WebSocketSession> SessionPtr;
class WebSocketSession class WebSocketSession {
{
public: public:
WebSocketSession(); WebSocketSession();

View File

@ -122,8 +122,5 @@ namespace WebSocketOpCode {
RequestBatchResponse = 9, RequestBatchResponse = 9,
}; };
inline bool IsValid(uint8_t opCode) inline bool IsValid(uint8_t opCode) { return opCode >= Hello && opCode <= RequestBatchResponse; }
{
return opCode >= Hello && opCode <= RequestBatchResponse;
}
} }