Compare commits

...

21 Commits

Author SHA1 Message Date
Fabio Alessandrelli
8c18112f5d Merge pull request #43 from dsnopek/buffered-amount
Add get_buffered_amount() to WebRTCDataChannel (GDNative)
2021-09-22 23:06:19 +02:00
Fabio Alessandrelli
c37cc530e7 Merge pull request #46 from Faless/issue_template
Add issue templates for reporting bugs.
2021-07-26 15:39:53 +02:00
Fabio Alessandrelli
13ab33af36 Add issue templates for reporting bugs. 2021-07-26 13:19:29 +02:00
David Snopek
3bdf6cdc13 Add get_buffered_amount() to WebRTCDataChannel 2021-07-21 10:48:09 -05:00
Fabio Alessandrelli
072ba5c1d0 Merge pull request #40 from Faless/osx/arm64
Add OSX arm64 build.
2021-07-11 10:51:37 +02:00
Fabio Alessandrelli
7cb6d6c846 Add OSX arm64 build.
Needs a more recent revision of godot-cpp, but can still use
godot-headers from 3.2 . See CI script update for details.
2021-07-11 10:01:55 +02:00
Fabio Alessandrelli
c0b31562f5 Merge pull request #39 from Faless/style/clang_black
Add static checks
2021-07-09 19:43:04 +02:00
Fabio Alessandrelli
69f92fa26c Run clang-format on src/* 2021-07-09 18:55:32 +02:00
Fabio Alessandrelli
d06e536d12 Add copyright headers 2021-07-09 18:55:32 +02:00
Fabio Alessandrelli
68a892d9f3 run black -l 120 on SConstruct. 2021-07-09 18:55:32 +02:00
Fabio Alessandrelli
72b337e32c static checks. 2021-07-09 18:55:32 +02:00
Fabio Alessandrelli
eeabf0a844 Merge pull request #38 from Faless/refactor/signals
Refactor signals and obeserver, fixes answer creation.
2021-07-09 16:24:35 +02:00
Fabio Alessandrelli
04fbae6ce3 Properly wait success callback before creating answers. 2021-07-09 03:46:25 +02:00
Fabio Alessandrelli
ce3f086ec4 Move observers implementations into PeerConnection. 2021-07-09 03:45:45 +02:00
Fabio Alessandrelli
00ac03c8e7 Use a class instead of lambdas for signals. 2021-07-09 00:53:15 +02:00
Fabio Alessandrelli
fa5296a4e4 Merge pull request #37 from Faless/ci/auto
[CI] Use organization's repository for automated builds.
2021-07-08 23:56:42 +02:00
Fabio Alessandrelli
189c353264 [CI] Use organization's repository for automated builds.
Update README.md to reflect new build sources.
2021-07-08 23:04:16 +02:00
Fabio Alessandrelli
e44c42fde8 Merge pull request #36 from Faless/ci/single
Setup CI for Android, iOS, Linux, macOS, Windows.
2021-07-06 16:27:59 +02:00
Fabio Alessandrelli
524fdde8f2 Setup CI for Android, iOS, Linux, macOS, Windows.
Includes all supported architectures:

* Android:
  - arm (neon)
  - arm64
  - x86
  - x64

* iOS:
  - arm
  - arm64
  - x64 (simulator)

* Linux
  - x86
  - x64

* macOS
  - x64

* windows
  - x86
  - x64

Use a single matrix for builds, then an extra step will package for
release.

Artefacts are generated for each platform/arch combination, along for
the 2 zip containing the full `webrtc` and `webrtc_debug` plugin.
2021-07-06 15:57:55 +02:00
Fabio Alessandrelli
673a4c1a1c Merge pull request #34 from Faless/build/optimization_flags
Fix osx, android optimization flags.
2021-07-05 03:17:27 +02:00
Fabio Alessandrelli
cf98eb2e7a Fix osx, android optimization flags.
Will need to be also fixed in upstream godot-cpp.
2021-07-02 21:58:44 +02:00
24 changed files with 1340 additions and 282 deletions

128
.clang-format Normal file
View File

@@ -0,0 +1,128 @@
# Commented out parameters are those with the same value as base LLVM style
# We can uncomment them if we want to change their value, or enforce the
# chosen value in case the base style changes (last sync: Clang 6.0.1).
---
### General config, applies to all languages ###
BasedOnStyle: LLVM
AccessModifierOffset: -4
AlignAfterOpenBracket: DontAlign
# AlignConsecutiveAssignments: false
# AlignConsecutiveDeclarations: false
# AlignEscapedNewlines: Right
# AlignOperands: true
AlignTrailingComments: false
AllowAllParametersOfDeclarationOnNextLine: false
# AllowShortBlocksOnASingleLine: false
# AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: Inline
# AllowShortIfStatementsOnASingleLine: false
# AllowShortLoopsOnASingleLine: false
# AlwaysBreakAfterDefinitionReturnType: None
# AlwaysBreakAfterReturnType: None
# AlwaysBreakBeforeMultilineStrings: false
# AlwaysBreakTemplateDeclarations: false
# BinPackArguments: true
# BinPackParameters: true
# BraceWrapping:
# AfterClass: false
# AfterControlStatement: false
# AfterEnum: false
# AfterFunction: false
# 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: Attach
# BreakBeforeInheritanceComma: false
BreakBeforeTernaryOperators: false
# BreakConstructorInitializersBeforeComma: false
BreakConstructorInitializers: AfterColon
# BreakStringLiterals: true
ColumnLimit: 0
# CommentPragmas: '^ IWYU pragma:'
# CompactNamespaces: false
ConstructorInitializerAllOnOneLineOrOnePerLine: true
ConstructorInitializerIndentWidth: 8
ContinuationIndentWidth: 8
Cpp11BracedListStyle: false
# DerivePointerAlignment: false
# DisableFormat: false
# ExperimentalAutoDetectBinPacking: false
# FixNamespaceComments: true
# ForEachMacros:
# - foreach
# - Q_FOREACH
# - BOOST_FOREACH
# IncludeBlocks: Preserve
IncludeCategories:
- Regex: '".*"'
Priority: 1
- Regex: '^<.*\.h>'
Priority: 2
- Regex: '^<.*'
Priority: 3
# IncludeIsMainRegex: '(Test)?$'
IndentCaseLabels: true
# IndentPPDirectives: None
IndentWidth: 4
# IndentWrappedFunctionNames: false
# JavaScriptQuotes: Leave
# JavaScriptWrapImports: true
KeepEmptyLinesAtTheStartOfBlocks: false
# MacroBlockBegin: ''
# MacroBlockEnd: ''
# MaxEmptyLinesToKeep: 1
# NamespaceIndentation: None
# PenaltyBreakAssignment: 2
# PenaltyBreakBeforeFirstCallParameter: 19
# PenaltyBreakComment: 300
# PenaltyBreakFirstLessLess: 120
# PenaltyBreakString: 1000
# PenaltyExcessCharacter: 1000000
# PenaltyReturnTypeOnItsOwnLine: 60
# PointerAlignment: Right
# RawStringFormats:
# - Delimiter: pb
# Language: TextProto
# BasedOnStyle: google
# ReflowComments: true
# SortIncludes: true
# SortUsingDeclarations: true
# SpaceAfterCStyleCast: false
# SpaceAfterTemplateKeyword: true
# SpaceBeforeAssignmentOperators: true
# SpaceBeforeParens: ControlStatements
# SpaceInEmptyParentheses: false
# SpacesBeforeTrailingComments: 1
# SpacesInAngles: false
# SpacesInContainerLiterals: true
# SpacesInCStyleCastParentheses: false
# SpacesInParentheses: false
# SpacesInSquareBrackets: false
TabWidth: 4
UseTab: Always
---
### C++ specific config ###
Language: Cpp
Standard: Cpp11
---
### ObjC specific config ###
Language: ObjC
Standard: Cpp11
ObjCBlockIndentWidth: 4
# ObjCSpaceAfterProperty: false
# ObjCSpaceBeforeProtocolList: true
---
### Java specific config ###
Language: Java
# BreakAfterJavaFieldAnnotations: false
JavaImportGroups: ['org.godotengine', 'android', 'androidx', 'com.android', 'com.google', 'java', 'javax']
...

64
.github/ISSUE_TEMPLATE/bug_report.yml vendored Normal file
View File

@@ -0,0 +1,64 @@
name: Bug report
description: Report a bug in the WebRTC native plugin.
body:
- type: markdown
attributes:
value: |
- Write a descriptive issue title above.
- Search [open](https://github.com/godotengine/webrtc-native/issues) and [closed](https://github.com/godotengine/webrtc-native/issues?q=is%3Aissue+is%3Aclosed) issues to ensure it has not already been reported.
- Verify that you are using a [supported Godot version](https://docs.godotengine.org/en/stable/about/release_policy.html).
- type: input
attributes:
label: Godot version
description: >
Specify the Git commit hash if using a development or non-official build.
If you use a custom build, please test if your issue is reproducible in official builds too.
placeholder: 3.3.stable, 4.0.dev (3041becc6)
validations:
required: true
- type: input
attributes:
label: Plugin version
description: >
Specify the Git commit hash if using a development or non-official build.
If you use a custom build, please test if your issue is reproducible in official builds too.
placeholder: 0.3, 0.5, 0.6.dev (072ba5c)
validations:
required: true
- type: input
attributes:
label: System information
description: |
Specify the OS version, and when relevant hardware information.
placeholder: Android 10, Fairphone 3+.
validations:
required: true
- type: textarea
attributes:
label: Issue description
description: |
Describe your issue briefly. What doesn't work, and how do you expect it to work instead?
You can include images or videos with drag and drop, and format code blocks or logs with <code>```</code> tags.
validations:
required: true
- type: textarea
attributes:
label: Steps to reproduce
description: |
List of steps or sample code that reproduces the issue. Having reproducible issues is a prerequisite for contributors to be able to solve them.
If you include a minimal reproduction project below, you can detail how to use it here.
validations:
required: true
- type: textarea
attributes:
label: Minimal reproduction project
description: |
A small Godot project which reproduces the issue. Highly recommended to speed up troubleshooting.
Drag and drop a ZIP archive to upload it.

6
.github/ISSUE_TEMPLATE/config.yml vendored Normal file
View File

@@ -0,0 +1,6 @@
blank_issues_enabled: false
contact_links:
- name: Godot proposals
url: https://github.com/godotengine/godot-proposals
about: Please submit feature proposals about the WebRTC exposed API on the Godot proposals repository, not here.

View File

@@ -0,0 +1,51 @@
name: 'Get WebRTC Library'
description: 'Get pre-build statically linked WebRTC library from Faless/webrtc-builds'
inputs:
repo:
description: 'Base repository'
required: true
default: "godotengine/webrtc-actions"
release:
description: 'Release tag'
required: true
default: '4472-33644-92ba70c'
webrtc-base-name:
description: 'The WebRTC version'
required: true
default: "webrtc-33644-92ba70c"
out-dir:
description: 'Directory where to extract the library'
required: true
default: "webrtc"
platform:
description: 'Platform to download'
required: true
archs:
description: 'Space separated list of architecture to fetch'
required: true
runs:
using: "composite"
steps:
- shell: bash
env:
RTC_BASE_URL: https://github.com/${{ inputs.repo }}/releases/download/${{ inputs.release }}/${{ inputs.webrtc-base-name }}
run: |
cd ${{ inputs.out-dir }}
libplat=${{ inputs.platform }}
if [ "${{ inputs.platform }}" = "windows" ]; then
libplat=win
elif [ "${{ inputs.platform }}" = "osx" ]; then
libplat=mac
fi
for arch in ${{ inputs.archs }}
do
echo "Downloading ${{ env.RTC_BASE_URL }}-${{ inputs.platform }}-${arch}.tar.gz"
curl -L ${{ env.RTC_BASE_URL }}-${libplat}-${arch}.tar.gz -o ${arch}.tar.gz
tar -xzf ${arch}.tar.gz
done
mv lib ${{ inputs.platform }}
ls -l
ls -l *

222
.github/workflows/build_release.yml vendored Normal file
View File

@@ -0,0 +1,222 @@
name: 🔧 Build -> Package 📦
on: [push, pull_request]
jobs:
static-checks:
name: 📊 Static Checks (clang-format, black format, file format)
runs-on: ubuntu-20.04
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Install dependencies
run: |
sudo apt-get install -qq dos2unix recode clang-format-11
sudo update-alternatives --remove-all clang-format
sudo update-alternatives --install /usr/bin/clang-format clang-format /usr/bin/clang-format-11 100
sudo pip3 install black==20.8b1 pygments
- name: File formatting checks (file_format.sh)
run: |
bash ./misc/scripts/file_format.sh
- name: Style checks via clang-format (clang_format.sh)
run: |
bash ./misc/scripts/clang_format.sh
- name: Python style checks via black (black_format.sh)
run: |
bash ./misc/scripts/black_format.sh
build:
runs-on: ${{ matrix.os }}
name: 🔧 Build
needs: static-checks
strategy:
matrix:
include:
# Android
- platform: android
arch: 'x86'
sconsflags: 'android_arch=x86'
os: 'ubuntu-20.04'
- platform: android
arch: 'x64'
sconsflags: 'android_arch=x86_64'
os: 'ubuntu-20.04'
- platform: android
arch: 'arm'
sconsflags: 'android_arch=armv7'
os: 'ubuntu-20.04'
- platform: android
arch: 'arm64'
sconsflags: 'android_arch=arm64v8'
os: 'ubuntu-20.04'
# iOS
- platform: ios
arch: 'x64'
sconsflags: 'ios_arch=x86_64 ios_simulator=true'
os: 'macos-latest'
- platform: ios
arch: 'arm'
sconsflags: 'ios_arch=armv7'
os: 'macos-latest'
- platform: ios
arch: 'arm64'
sconsflags: 'ios_arch=arm64'
os: 'macos-latest'
# Linux
- platform: linux
arch: 'x86'
sconsflags: 'bits=32'
os: 'ubuntu-20.04'
- platform: linux
arch: 'x64'
sconsflags: 'bits=64'
os: 'ubuntu-20.04'
# macOS
- platform: osx
arch: 'x64'
sconsflags: 'bits=64'
os: 'macos-latest'
- platform: osx
arch: 'arm64'
sconsflags: 'bits=64 macos_arch=arm64 macos_sdk_path=/Library/Developer/CommandLineTools/SDKs/MacOSX11.1.sdk/'
os: 'macos-10.15'
# Windows
- platform: windows
arch: 'x86'
sconsflags: 'bits=32'
os: 'windows-latest'
msvc_arch: amd64_x86
- platform: windows
arch: 'x64'
sconsflags: 'bits=64'
os: 'windows-latest'
msvc_arch: amd64
env:
SCONSFLAGS: ${{ matrix.sconsflags }} platform=${{ matrix.platform }} --jobs=2
NDK_VERSION: 22b
ANDROID_NDK_ROOT: ${{github.workspace}}/android-ndk-r22b
MSVC_VARS: 'C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\VC\Auxiliary\Build\vcvarsall.bat'
defaults:
run:
shell: bash
steps:
- uses: actions/checkout@v2
with:
submodules: recursive
- name: Cache NDK
id: cache-ndk
if: ${{ matrix.platform == 'android' }}
uses: actions/cache@v2
with:
path: ${{ env.ANDROID_NDK_ROOT }}
key: ndk-${{ env.NDK_VERSION }}
- name: Download NDK
if: ${{ matrix.platform == 'android' && steps.cache-ndk.outputs.cache-hit != 'true' }}
id: setup-ndk
run: |
cd ${{ github.workspace }}
curl -L https://dl.google.com/android/repository/android-ndk-r${{ env.NDK_VERSION }}-linux-x86_64.zip -o ndk.zip
unzip ndk.zip
ls
- name: Setup MSVC build environment for ${{ matrix.msvc_arch }}
if: ${{ matrix.platform == 'windows' }}
run: "'${{ env.MSVC_VARS }}' ${{ matrix.msvc_arch }}"
- name: Install Linux build dependencies
if: ${{ matrix.platform == 'linux' }}
run: |
sudo apt-get install build-essential gcc-multilib wget g++-multilib
- name: Set up Python 3.x
uses: actions/setup-python@v2
with:
python-version: '3.x'
architecture: 'x64'
- name: Configuring Python packages
run: |
python -c "import sys; print(sys.version)"
python -m pip install scons
python --version
scons --version
- name: Get WebRTC package for ${{ matrix.platform }} - ${{ matrix.arch }}
uses: ./.github/actions/webrtc-download
with:
platform: ${{ matrix.platform }}
archs: ${{ matrix.arch }}
- name: Fix godot-cpp revision and file names for OSX arm64 build.
if: ${{ matrix.platform == 'osx' && matrix.arch == 'arm64' }}
run: |
cd godot-cpp
git checkout e08ecdc28c5409cb5366027227e996c342dcee93
rm -rf src/gen/
rm -rf include/gen/
mkdir bin
ln -s libgodot-cpp.osx.debug.64.a bin/libgodot-cpp.osx.debug.arm64.a
ln -s libgodot-cpp.osx.release.64.a bin/libgodot-cpp.osx.release.arm64.a
- name: Compilation ${{ matrix.platform }} - ${{ matrix.arch }} - godot-cpp
run: |
scons -C godot-cpp target=debug generate_bindings=yes
scons -C godot-cpp target=release
- name: Compilation ${{ matrix.platform }} - ${{ matrix.arch }} - webrtc-native
run: |
scons target=debug
scons target=release
- uses: actions/upload-artifact@v2
with:
name: ${{ github.job }}-${{ matrix.platform }}-${{ matrix.arch }}
path: bin/*
package:
name: 📦 Package
needs: build
runs-on: "ubuntu-latest"
steps:
- uses: actions/checkout@v2
- uses: actions/download-artifact@v2
with:
path: artifacts
- name: Package artifacts for release
run: |
mkdir release
cd release
for name in webrtc webrtc_debug
do
mkdir -p ${name}/lib/
find ../artifacts -wholename "*/${name}/lib/*" | xargs cp -t ${name}/lib/
find ../artifacts -wholename "*/${name}/${name}.tres" | head -n 1 | xargs cp -t ${name}/
done
zip -r godot-webrtc-native-release.zip webrtc
zip -r godot-webrtc-native-debug.zip webrtc_debug
ls -R
- uses: actions/upload-artifact@v2
with:
name: godot-webrtc-native-debug.zip
path: release/godot-webrtc-native-debug.zip
- uses: actions/upload-artifact@v2
with:
name: godot-webrtc-native-release.zip
path: release/godot-webrtc-native-release.zip

View File

@@ -7,15 +7,15 @@
### Compiling
Clone this repository with the following command to checkout both [godot-cpp](https://github.com/GodotNativeTools/godot-cpp) and [godot_headers](https://github.com/GodotNativeTools/godot_headers) dependencies.
Clone this repository with the following command to checkout both [godot-cpp](https://github.com/godotengine/godot-cpp) and [godot-headers](https://github.com/godotengine/godot-headers) dependencies.
```
$ git clone --recurse-submodules git@github.com:godotengine/webrtc-native.git
$ git clone --recurse-submodules https://github.com/godotengine/webrtc-native.git
```
Note that if you wish to use a specific branch, add the -b option to the clone command:
```
$ git clone --recurse-submodules -b 3.2 git@github.com:godotengine/webrtc-native.git
$ git clone --recurse-submodules -b 3.2 https://github.com/godotengine/webrtc-native.git
```
If you already checked out the branch use the following commands to update the dependencies:
@@ -29,7 +29,7 @@ Right now our directory structure should look like this:
webrtc-native/
├─bin/
├─godot-cpp/
| └─godot_headers/
| └─godot-headers/
├─src/
└─webrtc/
```
@@ -54,7 +54,12 @@ $ cd ..
### Building WebRTC
Use [this script](https://github.com/Faless/webrtc-builds) to build and package the WebRTCLibrary (`branch-heads/68`), or [**download latest pre-compiled binaries**](https://github.com/Faless/webrtc-builds/releases)
Building WebRTC is quite a complex task, involves huge downloads and long build times, and produces multiple output libraries that needs to bundled together.
To make things easier, a set of [GitHub Actions](https://docs.github.com/en/actions) are used to generate the library for this plugin, [available in this repository](https://github.com/godotengine/webrtc-actions).
Alternatively, [**download the latest pre-compiled libraries**](https://github.com/godotengine/webrtc-actions/releases).
Extract content of `include` into `webrtc/include` and content of `bin` into `webrtc/<your platform>`
### Compiling the plugin.
@@ -63,4 +68,4 @@ Extract content of `include` into `webrtc/include` and content of `bin` into `we
$ scons platform=<your platform> target=<your target>
```
The generated library and associated `gdns` will be placed in `bin/webrtc/` or `bin/webrtc_debug/` according to the desired target. You simply need to copy that folder into your project.
The generated library and associated `tres` will be placed in `bin/webrtc/` or `bin/webrtc_debug/` according to the desired target. You simply need to copy that folder to the root folder of your project.

View File

@@ -3,216 +3,222 @@
import os, sys, platform, json, subprocess
if sys.version_info < (3,):
def decode_utf8(x):
return x
else:
import codecs
def decode_utf8(x):
return codecs.utf_8_decode(x)[0]
def add_sources(sources, dirpath, extension):
for f in os.listdir(dirpath):
if f.endswith('.' + extension):
sources.append(dirpath + '/' + f)
for f in os.listdir(dirpath):
if f.endswith("." + extension):
sources.append(dirpath + "/" + f)
def gen_gdnative_lib(target, source, env):
for t in target:
with open(t.srcnode().path, 'w') as w:
w.write(decode_utf8(source[0].get_contents()).replace('{GDNATIVE_PATH}', os.path.splitext(t.name)[0]).replace('{TARGET}', env['target']))
with open(t.srcnode().path, "w") as w:
w.write(
decode_utf8(source[0].get_contents())
.replace("{GDNATIVE_PATH}", os.path.splitext(t.name)[0])
.replace("{TARGET}", env["target"])
)
env = Environment()
target_arch = ARGUMENTS.get('b', ARGUMENTS.get('bits', '64'))
target_platform = ARGUMENTS.get('p', ARGUMENTS.get('platform', 'linux'))
if target_platform == 'windows':
target_arch = ARGUMENTS.get("b", ARGUMENTS.get("bits", "64"))
target_platform = ARGUMENTS.get("p", ARGUMENTS.get("platform", "linux"))
if target_platform == "windows":
# This makes sure to keep the session environment variables on windows,
# that way you can run scons in a vs 2017 prompt and it will find all the required tools
if (target_arch == '64'):
env = Environment(ENV = os.environ, TARGET_ARCH='amd64')
if target_arch == "64":
env = Environment(ENV=os.environ, TARGET_ARCH="amd64")
else:
env = Environment(ENV = os.environ, TARGET_ARCH='x86')
env = Environment(ENV=os.environ, TARGET_ARCH="x86")
env.Append(BUILDERS={'GDNativeLibBuilder': Builder(action=gen_gdnative_lib)})
env.Append(BUILDERS={"GDNativeLibBuilder": Builder(action=gen_gdnative_lib)})
customs = ['custom.py']
customs = ["custom.py"]
opts = Variables(customs, ARGUMENTS)
opts.Add(BoolVariable('use_llvm', 'Use the LLVM compiler', False))
opts.Add(EnumVariable('target', "Compilation target", 'debug', ('debug', 'release')))
opts.Add(BoolVariable("use_llvm", "Use the LLVM compiler", False))
opts.Add(EnumVariable("target", "Compilation target", "debug", ("debug", "release")))
opts.Add(EnumVariable(
'android_arch',
'Target Android architecture',
'armv7',
['armv7','arm64v8', 'x86', 'x86_64']
))
opts.Add(EnumVariable("android_arch", "Target Android architecture", "armv7", ["armv7", "arm64v8", "x86", "x86_64"]))
opts.Add(
'android_api_level',
'Target Android API level',
'18' if ARGUMENTS.get("android_arch", 'armv7') in ['armv7', 'x86'] else '21'
"android_api_level",
"Target Android API level",
"18" if ARGUMENTS.get("android_arch", "armv7") in ["armv7", "x86"] else "21",
)
opts.Add(
'ANDROID_NDK_ROOT',
'Path to your Android NDK installation. By default, uses ANDROID_NDK_ROOT from your defined environment variables.',
os.environ.get("ANDROID_NDK_ROOT", None)
"ANDROID_NDK_ROOT",
"Path to your Android NDK installation. By default, uses ANDROID_NDK_ROOT from your defined environment variables.",
os.environ.get("ANDROID_NDK_ROOT", None),
)
opts.Add(EnumVariable(
'ios_arch',
'Target iOS architecture',
'arm64',
['armv7', 'arm64', 'x86_64']
))
opts.Add(BoolVariable(
'ios_simulator',
'Target iOS Simulator',
False
))
opts.Add(EnumVariable("ios_arch", "Target iOS architecture", "arm64", ["armv7", "arm64", "x86_64"]))
opts.Add(BoolVariable("ios_simulator", "Target iOS Simulator", False))
opts.Add(
'IPHONEPATH',
'Path to iPhone toolchain',
'/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain',
"IPHONEPATH",
"Path to iPhone toolchain",
"/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain",
)
opts.Add("macos_sdk_path", "macOS SDK path", "")
opts.Add(EnumVariable("macos_arch", "Target macOS architecture", "x86_64", ["x86_64", "arm64"]))
# Update environment (parse options)
opts.Update(env)
target = env['target']
target = env["target"]
if target_platform == 'android':
target_arch = env['android_arch']
elif target_platform == 'ios':
target_arch = env['ios_arch']
if target_platform == "android":
target_arch = env["android_arch"]
elif target_platform == "ios":
target_arch = env["ios_arch"]
host_platform = platform.system()
# Local dependency paths, adapt them to your setup
godot_headers = ARGUMENTS.get('headers', 'godot-cpp/godot-headers')
godot_cpp_headers = ARGUMENTS.get('godot_cpp_headers', 'godot-cpp/include')
godot_cpp_lib_dir = ARGUMENTS.get('godot_cpp_lib_dir', 'godot-cpp/bin')
result_path = os.path.join('bin', 'webrtc' if env['target'] == 'release' else 'webrtc_debug', 'lib')
godot_headers = ARGUMENTS.get("headers", "godot-cpp/godot-headers")
godot_cpp_headers = ARGUMENTS.get("godot_cpp_headers", "godot-cpp/include")
godot_cpp_lib_dir = ARGUMENTS.get("godot_cpp_lib_dir", "godot-cpp/bin")
result_path = os.path.join("bin", "webrtc" if env["target"] == "release" else "webrtc_debug", "lib")
lib_prefix = ""
# Convenience check to enforce the use_llvm overrides when CXX is clang(++)
if 'CXX' in env and 'clang' in os.path.basename(env['CXX']):
env['use_llvm'] = True
if "CXX" in env and "clang" in os.path.basename(env["CXX"]):
env["use_llvm"] = True
if target_platform == 'linux':
env['CXX']='g++'
if target_platform == "linux":
env["CXX"] = "g++"
# LLVM
if env['use_llvm']:
if ('clang++' not in os.path.basename(env['CXX'])):
env['CC'] = 'clang'
if env["use_llvm"]:
if "clang++" not in os.path.basename(env["CXX"]):
env["CC"] = "clang"
env["CXX"] = "clang++"
env["LINK"] = "clang++"
if (env["target"] == "debug"):
env.Prepend(CCFLAGS=['-g3'])
env.Append(LINKFLAGS=['-rdynamic'])
if env["target"] == "debug":
env.Prepend(CCFLAGS=["-g3"])
env.Append(LINKFLAGS=["-rdynamic"])
else:
env.Prepend(CCFLAGS=['-O3'])
env.Prepend(CCFLAGS=["-O3"])
env.Append(CCFLAGS=['-fPIC', '-std=c++14'])
env.Append(CCFLAGS=["-fPIC", "-std=c++14"])
if target_arch == '32':
env.Append(CCFLAGS = [ '-m32' ])
env.Append(LINKFLAGS = [ '-m32' ])
elif target_arch == '64':
env.Append(CCFLAGS = [ '-m64' ])
env.Append(LINKFLAGS = [ '-m64' ])
if target_arch == "32":
env.Append(CCFLAGS=["-m32"])
env.Append(LINKFLAGS=["-m32"])
elif target_arch == "64":
env.Append(CCFLAGS=["-m64"])
env.Append(LINKFLAGS=["-m64"])
# i386 does not like static libstdc++
env.Append(LINKFLAGS=['-static-libgcc', '-static-libstdc++'])
env.Append(LINKFLAGS=["-static-libgcc", "-static-libstdc++"])
elif target_platform == 'windows':
if host_platform == 'Windows':
elif target_platform == "windows":
if host_platform == "Windows":
lib_prefix = "lib"
env.Append(LINKFLAGS = [ '/WX' ])
if target == 'debug':
env.Append(CCFLAGS = ['/EHsc', '/D_DEBUG', '/MDd' ])
env.Append(LINKFLAGS=["/WX"])
if target == "debug":
env.Append(CCFLAGS=["/EHsc", "/D_DEBUG", "/MDd"])
else:
env.Append(CCFLAGS = ['/O2', '/EHsc', '/DNDEBUG', '/MD' ])
env.Append(CCFLAGS=["/O2", "/EHsc", "/DNDEBUG", "/MD"])
else:
if target_arch == '32':
env['CXX']='i686-w64-mingw32-g++'
elif target_arch == '64':
env['CXX']='x86_64-w64-mingw32-g++'
if target_arch == "32":
env["CXX"] = "i686-w64-mingw32-g++"
elif target_arch == "64":
env["CXX"] = "x86_64-w64-mingw32-g++"
env.Append(CCFLAGS = [ '-g', '-O3', '-std=c++14', '-Wwrite-strings' ])
env.Append(LINKFLAGS = [ '--static', '-Wl,--no-undefined', '-static-libgcc', '-static-libstdc++' ])
if env["target"] == "debug":
env.Append(CCFLAGS=["-Og", "-g"])
elif env["target"] == "release":
env.Append(CCFLAGS=["-O3"])
elif target_platform == 'osx':
if env['use_llvm']:
env['CXX'] = 'clang++'
env.Append(CCFLAGS=["-std=c++14", "-Wwrite-strings"])
env.Append(LINKFLAGS=["--static", "-Wl,--no-undefined", "-static-libgcc", "-static-libstdc++"])
elif target_platform == "osx":
if env["use_llvm"]:
env["CXX"] = "clang++"
# Only 64-bits is supported for OS X
target_arch = '64'
target_arch = "64"
if env["macos_arch"] != "x86_64":
target_arch = "arm64"
env.Append(CCFLAGS = [ '-g','-O3', '-std=c++14', '-arch', 'x86_64' ])
env.Append(LINKFLAGS = [ '-arch', 'x86_64', '-framework', 'Cocoa', '-Wl,-undefined,dynamic_lookup' ])
env.Append(CCFLAGS=["-std=c++14", "-arch", env["macos_arch"]])
env.Append(LINKFLAGS=["-arch", env["macos_arch"], "-framework", "Cocoa", "-Wl,-undefined,dynamic_lookup"])
if env['target'] == 'debug':
env.Append(CCFLAGS=['-Og', '-g'])
elif env['target'] == 'release':
env.Append(CCFLAGS=['-O3'])
if env["macos_sdk_path"]:
env.Append(CCFLAGS=["-isysroot", env["macos_sdk_path"]])
env.Append(LINKFLAGS=["-isysroot", env["macos_sdk_path"]])
elif target_platform == 'ios':
if env['ios_simulator']:
sdk_name = 'iphonesimulator'
env.Append(CCFLAGS=['-mios-simulator-version-min=10.0'])
env['LIBSUFFIX'] = ".simulator" + env['LIBSUFFIX']
if env["target"] == "debug":
env.Append(CCFLAGS=["-Og", "-g"])
elif env["target"] == "release":
env.Append(CCFLAGS=["-O3"])
elif target_platform == "ios":
if env["ios_simulator"]:
sdk_name = "iphonesimulator"
env.Append(CCFLAGS=["-mios-simulator-version-min=10.0"])
env["LIBSUFFIX"] = ".simulator" + env["LIBSUFFIX"]
else:
sdk_name = 'iphoneos'
env.Append(CCFLAGS=['-miphoneos-version-min=10.0'])
sdk_name = "iphoneos"
env.Append(CCFLAGS=["-miphoneos-version-min=10.0"])
try:
sdk_path = decode_utf8(subprocess.check_output(['xcrun', '--sdk', sdk_name, '--show-sdk-path']).strip())
sdk_path = decode_utf8(subprocess.check_output(["xcrun", "--sdk", sdk_name, "--show-sdk-path"]).strip())
except (subprocess.CalledProcessError, OSError):
raise ValueError("Failed to find SDK path while running xcrun --sdk {} --show-sdk-path.".format(sdk_name))
compiler_path = env['IPHONEPATH'] + '/usr/bin/'
env['ENV']['PATH'] = env['IPHONEPATH'] + "/Developer/usr/bin/:" + env['ENV']['PATH']
compiler_path = env["IPHONEPATH"] + "/usr/bin/"
env["ENV"]["PATH"] = env["IPHONEPATH"] + "/Developer/usr/bin/:" + env["ENV"]["PATH"]
env['CC'] = compiler_path + 'clang'
env['CXX'] = compiler_path + 'clang++'
env['AR'] = compiler_path + 'ar'
env['RANLIB'] = compiler_path + 'ranlib'
env["CC"] = compiler_path + "clang"
env["CXX"] = compiler_path + "clang++"
env["AR"] = compiler_path + "ar"
env["RANLIB"] = compiler_path + "ranlib"
env.Append(CCFLAGS=['-std=c++14', '-arch', env['ios_arch'], '-isysroot', sdk_path])
env.Append(LINKFLAGS=[
'-arch',
env['ios_arch'],
'-Wl,-undefined,dynamic_lookup',
'-isysroot', sdk_path,
'-F' + sdk_path
])
env.Append(CCFLAGS=["-std=c++14", "-arch", env["ios_arch"], "-isysroot", sdk_path])
env.Append(
LINKFLAGS=["-arch", env["ios_arch"], "-Wl,-undefined,dynamic_lookup", "-isysroot", sdk_path, "-F" + sdk_path]
)
if env['target'] == 'debug':
env.Append(CCFLAGS=['-Og', '-g'])
elif env['target'] == 'release':
env.Append(CCFLAGS=['-O3'])
if env["target"] == "debug":
env.Append(CCFLAGS=["-Og", "-g"])
elif env["target"] == "release":
env.Append(CCFLAGS=["-O3"])
elif target_platform == 'android':
elif target_platform == "android":
# Verify NDK root
if not 'ANDROID_NDK_ROOT' in env:
raise ValueError("To build for Android, ANDROID_NDK_ROOT must be defined. Please set ANDROID_NDK_ROOT to the root folder of your Android NDK installation.")
if not "ANDROID_NDK_ROOT" in env:
raise ValueError(
"To build for Android, ANDROID_NDK_ROOT must be defined. Please set ANDROID_NDK_ROOT to the root folder of your Android NDK installation."
)
# Validate API level
api_level = int(env['android_api_level'])
if target_arch in ['arm64v8', 'x86_64'] and api_level < 21:
api_level = int(env["android_api_level"])
if target_arch in ["arm64v8", "x86_64"] and api_level < 21:
print("WARN: 64-bit Android architectures require an API level of at least 21; setting android_api_level=21")
env['android_api_level'] = '21'
env["android_api_level"] = "21"
api_level = 21
# Setup toolchain
toolchain = env['ANDROID_NDK_ROOT'] + "/toolchains/llvm/prebuilt/"
toolchain = env["ANDROID_NDK_ROOT"] + "/toolchains/llvm/prebuilt/"
if host_platform == "Windows":
toolchain += "windows"
import platform as pltfm
if pltfm.machine().endswith("64"):
toolchain += "-x86_64"
elif host_platform == "Linux":
@@ -222,31 +228,51 @@ elif target_platform == 'android':
# Get architecture info
arch_info_table = {
"armv7" : {
"march":"armv7-a", "target":"armv7a-linux-androideabi", "tool_path":"arm-linux-androideabi", "compiler_path":"armv7a-linux-androideabi",
"ccflags" : ['-mfpu=neon']
},
"arm64v8" : {
"march":"armv8-a", "target":"aarch64-linux-android", "tool_path":"aarch64-linux-android", "compiler_path":"aarch64-linux-android",
"ccflags" : []
},
"x86" : {
"march":"i686", "target":"i686-linux-android", "tool_path":"i686-linux-android", "compiler_path":"i686-linux-android",
"ccflags" : ['-mstackrealign']
},
"x86_64" : {"march":"x86-64", "target":"x86_64-linux-android", "tool_path":"x86_64-linux-android", "compiler_path":"x86_64-linux-android",
"ccflags" : []
}
"armv7": {
"march": "armv7-a",
"target": "armv7a-linux-androideabi",
"tool_path": "arm-linux-androideabi",
"compiler_path": "armv7a-linux-androideabi",
"ccflags": ["-mfpu=neon"],
},
"arm64v8": {
"march": "armv8-a",
"target": "aarch64-linux-android",
"tool_path": "aarch64-linux-android",
"compiler_path": "aarch64-linux-android",
"ccflags": [],
},
"x86": {
"march": "i686",
"target": "i686-linux-android",
"tool_path": "i686-linux-android",
"compiler_path": "i686-linux-android",
"ccflags": ["-mstackrealign"],
},
"x86_64": {
"march": "x86-64",
"target": "x86_64-linux-android",
"tool_path": "x86_64-linux-android",
"compiler_path": "x86_64-linux-android",
"ccflags": [],
},
}
arch_info = arch_info_table[target_arch]
# Setup tools
env['CC'] = toolchain + "/bin/clang"
env['CXX'] = toolchain + "/bin/clang++"
env["CC"] = toolchain + "/bin/clang"
env["CXX"] = toolchain + "/bin/clang++"
env.Append(CCFLAGS=['--target=' + arch_info['target'] + env['android_api_level'], '-march=' + arch_info['march'], '-fPIC'])
env.Append(CCFLAGS=arch_info['ccflags'])
env.Append(LINKFLAGS=['--target=' + arch_info['target'] + env['android_api_level'], '-march=' + arch_info['march']])
env.Append(
CCFLAGS=["--target=" + arch_info["target"] + env["android_api_level"], "-march=" + arch_info["march"], "-fPIC"]
)
env.Append(CCFLAGS=arch_info["ccflags"])
env.Append(LINKFLAGS=["--target=" + arch_info["target"] + env["android_api_level"], "-march=" + arch_info["march"]])
if env["target"] == "debug":
env.Append(CCFLAGS=["-Og", "-g"])
elif env["target"] == "release":
env.Append(CCFLAGS=["-O3"])
else:
print("No valid target platform selected.")
@@ -254,34 +280,41 @@ else:
# Godot CPP bindings
env.Append(CPPPATH=[godot_headers])
env.Append(CPPPATH=[godot_cpp_headers, godot_cpp_headers + '/core', godot_cpp_headers + '/gen'])
env.Append(CPPPATH=[godot_cpp_headers, godot_cpp_headers + "/core", godot_cpp_headers + "/gen"])
env.Append(LIBPATH=[godot_cpp_lib_dir])
env.Append(LIBS=['%sgodot-cpp.%s.%s.%s%s' % (lib_prefix, target_platform, target, target_arch, ".simulator" if env["ios_simulator"] else "")])
env.Append(
LIBS=[
"%sgodot-cpp.%s.%s.%s%s"
% (lib_prefix, target_platform, target, target_arch, ".simulator" if env["ios_simulator"] else "")
]
)
# WebRTC stuff
webrtc_dir = "webrtc"
lib_name = 'libwebrtc_full'
lib_name = "libwebrtc_full"
lib_path = os.path.join(webrtc_dir, target_platform)
lib_path += {'32': '/x86',
'64': '/x64',
'armv7': '/arm',
'arm64v8': '/arm64',
'arm64': '/arm64',
'x86': '/x86',
'x86_64': '/x64'}[target_arch]
lib_path += {
"32": "/x86",
"64": "/x64",
"armv7": "/arm",
"arm64v8": "/arm64",
"arm64": "/arm64",
"x86": "/x86",
"x86_64": "/x64",
}[target_arch]
if target == 'debug':
lib_path += '/Debug'
if target == "debug":
lib_path += "/Debug"
else:
lib_path += '/Release'
lib_path += "/Release"
env.Append(CPPPATH=[webrtc_dir + "/include", webrtc_dir + "/include/third_party/abseil-cpp"])
if target_platform == "linux":
env.Append(LIBS=[lib_name, "atomic"])
env.Append(LIBPATH=[lib_path])
#env.Append(CCFLAGS=["-std=c++11"])
# env.Append(CCFLAGS=["-std=c++11"])
env.Append(CCFLAGS=["-DWEBRTC_POSIX", "-DWEBRTC_LINUX"])
env.Append(CCFLAGS=["-DRTC_UNUSED=''", "-DNO_RETURN=''"])
@@ -293,7 +326,17 @@ elif target_platform == "windows":
env.Append(LIBPATH=[lib_path])
# Mostly "gcc"
else:
env.Append(CCFLAGS=["-DWINVER=0x0603", "-D_WIN32_WINNT=0x0603", "-DWEBRTC_WIN", "-DWIN32_LEAN_AND_MEAN", "-DNOMINMAX", "-DRTC_UNUSED=", "-DNO_RETURN="])
env.Append(
CCFLAGS=[
"-DWINVER=0x0603",
"-D_WIN32_WINNT=0x0603",
"-DWEBRTC_WIN",
"-DWIN32_LEAN_AND_MEAN",
"-DNOMINMAX",
"-DRTC_UNUSED=",
"-DNO_RETURN=",
]
)
env.Append(LINKFLAGS=[p + env["LIBSUFFIX"] for p in ["secur32", "advapi32", "winmm", lib_name]])
env.Append(LIBPATH=[lib_path])
@@ -303,42 +346,42 @@ elif target_platform == "osx":
env.Append(CCFLAGS=["-DWEBRTC_POSIX", "-DWEBRTC_MAC"])
env.Append(CCFLAGS=["-DRTC_UNUSED=''", "-DNO_RETURN=''"])
elif target_platform == 'ios':
elif target_platform == "ios":
env.Append(LIBS=[lib_name])
env.Append(LIBPATH=[lib_path])
env.Append(CCFLAGS=["-DWEBRTC_POSIX", "-DWEBRTC_MAC", "-DWEBRTC_IOS"])
env.Append(CCFLAGS=["-DRTC_UNUSED=''", "-DNO_RETURN=''"])
elif target_platform == "android":
env.Append(LIBS=['log'])
env.Append(LIBS=["log"])
env.Append(LIBS=[lib_name])
env.Append(LIBPATH=[lib_path])
env.Append(CCFLAGS=["-DWEBRTC_POSIX", "-DWEBRTC_LINUX", "-DWEBRTC_ANDROID"])
env.Append(CCFLAGS=["-DRTC_UNUSED=''", "-DNO_RETURN=''"])
if target_arch == 'arm64v8':
if target_arch == "arm64v8":
env.Append(CCFLAGS=["-DWEBRTC_ARCH_ARM64", "-DWEBRTC_HAS_NEON"])
elif target_arch == 'armv7':
elif target_arch == "armv7":
env.Append(CCFLAGS=["-DWEBRTC_ARCH_ARM", "-DWEBRTC_ARCH_ARM_V7", "-DWEBRTC_HAS_NEON"])
# Our includes and sources
env.Append(CPPPATH=['src/'])
env.Append(CPPPATH=["src/"])
sources = []
add_sources(sources, 'src/', 'cpp')
add_sources(sources, 'src/net/', 'cpp')
add_sources(sources, "src/", "cpp")
add_sources(sources, "src/net/", "cpp")
# Suffix
suffix = '.%s.%s' % (target, target_arch)
suffix = ".%s.%s" % (target, target_arch)
env["SHOBJSUFFIX"] = suffix + env["SHOBJSUFFIX"]
# Make the shared library
result_name = 'webrtc_native.%s.%s.%s' % (target_platform, target, target_arch) + env["SHLIBSUFFIX"]
result_name = "webrtc_native.%s.%s.%s" % (target_platform, target, target_arch) + env["SHLIBSUFFIX"]
library = env.SharedLibrary(target=os.path.join(result_path, result_name), source=sources)
Default(library)
# GDNativeLibrary
gdnlib = 'webrtc'
if target != 'release':
gdnlib += '_debug'
Default(env.GDNativeLibBuilder([os.path.join('bin', gdnlib, gdnlib + '.tres')], ['misc/gdnlib.tres']))
gdnlib = "webrtc"
if target != "release":
gdnlib += "_debug"
Default(env.GDNativeLibBuilder([os.path.join("bin", gdnlib, gdnlib + ".tres")], ["misc/gdnlib.tres"]))

34
misc/scripts/black_format.sh Executable file
View File

@@ -0,0 +1,34 @@
#!/usr/bin/env bash
# This script runs black on all Python files in the repo.
set -uo pipefail
# Apply black.
echo -e "Formatting Python files..."
PY_FILES=$(find \( -path "./.git" \
-o -path "./webrtc" \
-o -path "./godot-cpp" \
\) -prune \
-o \( -name "SConstruct" \
-o -name "SCsub" \
-o -name "*.py" \
\) -print)
black -l 120 $PY_FILES
git diff > patch.patch
# If no patch has been generated all is OK, clean up, and exit.
if [ ! -s patch.patch ] ; then
printf "Files in this commit comply with the black style rules.\n"
rm -f patch.patch
exit 0
fi
# A patch has been created, notify the user, clean up, and exit.
printf "\n*** The following differences were found between the code "
printf "and the formatting rules:\n\n"
cat patch.patch
printf "\n*** Aborting, please fix your commit(s) with 'git commit --amend' or 'git rebase -i <hash>'\n"
rm -f patch.patch
exit 1

58
misc/scripts/clang_format.sh Executable file
View File

@@ -0,0 +1,58 @@
#!/usr/bin/env bash
# This script runs clang-format and fixes copyright headers on all relevant files in the repo.
# This is the primary script responsible for fixing style violations.
set -uo pipefail
IFS=$'\n\t'
CLANG_FORMAT_FILE_EXTS=(".c" ".h" ".cpp" ".hpp" ".cc" ".hh" ".cxx" ".m" ".mm" ".inc" ".java" ".glsl")
# Loops through all text files tracked by Git.
git grep -zIl '' |
while IFS= read -rd '' f; do
# Exclude some files.
if [[ "$f" == "thirdparty"* ]]; then
continue
elif [[ "$f" == "platform/android/java/lib/src/com/google"* ]]; then
continue
elif [[ "$f" == *"-so_wrap."* ]]; then
continue
fi
for extension in ${CLANG_FORMAT_FILE_EXTS[@]}; do
if [[ "$f" == *"$extension" ]]; then
# Run clang-format.
clang-format -i "$f"
# Fix copyright headers, but not all files get them.
if [[ "$f" == *"inc" ]]; then
continue 2
elif [[ "$f" == *"glsl" ]]; then
continue 2
elif [[ "$f" == *"theme_data.h" ]]; then
continue 2
elif [[ "$f" == "platform/android/java/lib/src/org/godotengine/godot/input/InputManager"* ]]; then
continue 2
fi
python misc/scripts/copyright_headers.py "$f"
continue 2
fi
done
done
git diff > patch.patch
# If no patch has been generated all is OK, clean up, and exit.
if [ ! -s patch.patch ] ; then
printf "Files in this commit comply with the clang-format style rules.\n"
rm -f patch.patch
exit 0
fi
# A patch has been created, notify the user, clean up, and exit.
printf "\n*** The following differences were found between the code "
printf "and the formatting rules:\n\n"
cat patch.patch
printf "\n*** Aborting, please fix your commit(s) with 'git commit --amend' or 'git rebase -i <hash>'\n"
rm -f patch.patch
exit 1

View File

@@ -0,0 +1,95 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
header = """\
/*************************************************************************/
/* $filename */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
"""
fname = sys.argv[1]
# Handle replacing $filename with actual filename and keep alignment
fsingle = fname.strip()
if fsingle.find("/") != -1:
fsingle = fsingle[fsingle.rfind("/") + 1 :]
rep_fl = "$filename"
rep_fi = fsingle
len_fl = len(rep_fl)
len_fi = len(rep_fi)
# Pad with spaces to keep alignment
if len_fi < len_fl:
for x in range(len_fl - len_fi):
rep_fi += " "
elif len_fl < len_fi:
for x in range(len_fi - len_fl):
rep_fl += " "
if header.find(rep_fl) != -1:
text = header.replace(rep_fl, rep_fi)
else:
text = header.replace("$filename", fsingle)
text += "\n"
# We now have the proper header, so we want to ignore the one in the original file
# and potentially empty lines and badly formatted lines, while keeping comments that
# come after the header, and then keep everything non-header unchanged.
# To do so, we skip empty lines that may be at the top in a first pass.
# In a second pass, we skip all consecutive comment lines starting with "/*",
# then we can append the rest (step 2).
fileread = open(fname.strip(), "r")
line = fileread.readline()
header_done = False
while line.strip() == "": # Skip empty lines at the top
line = fileread.readline()
if line.find("/**********") == -1: # Godot header starts this way
# Maybe starting with a non-Godot comment, abort header magic
header_done = True
while not header_done: # Handle header now
if line.find("/*") != 0: # No more starting with a comment
header_done = True
if line.strip() != "":
text += line
line = fileread.readline()
while line != "": # Dump everything until EOF
text += line
line = fileread.readline()
fileread.close()
# Write
filewrite = open(fname.strip(), "w")
filewrite.write(text)
filewrite.close()

48
misc/scripts/file_format.sh Executable file
View File

@@ -0,0 +1,48 @@
#!/usr/bin/env bash
# This script ensures proper POSIX text file formatting and a few other things.
# This is supplementary to clang_format.sh and black_format.sh, but should be
# run before them.
# We need dos2unix and recode.
if [ ! -x "$(command -v dos2unix)" -o ! -x "$(command -v recode)" ]; then
printf "Install 'dos2unix' and 'recode' to use this script.\n"
fi
set -uo pipefail
IFS=$'\n\t'
# Loops through all text files tracked by Git.
git grep -zIl '' |
while IFS= read -rd '' f; do
# Exclude some types of files.
if [[ "$f" == "webrtc"* ]]; then
continue
elif [[ "$f" == "godot-cpp"* ]]; then
continue
fi
# Ensure that files are UTF-8 formatted.
recode UTF-8 "$f" 2> /dev/null
# Ensure that files have LF line endings and do not contain a BOM.
dos2unix "$f" 2> /dev/null
# Remove trailing space characters and ensures that files end
# with newline characters. -l option handles newlines conveniently.
perl -i -ple 's/\s*$//g' "$f"
done
git diff > patch.patch
# If no patch has been generated all is OK, clean up, and exit.
if [ ! -s patch.patch ] ; then
printf "Files in this commit comply with the formatting rules.\n"
rm -f patch.patch
exit 0
fi
# A patch has been created, notify the user, clean up, and exit.
printf "\n*** The following differences were found between the code "
printf "and the formatting rules:\n\n"
cat patch.patch
printf "\n*** Aborting, please fix your commit(s) with 'git commit --amend' or 'git rebase -i <hash>'\n"
rm -f patch.patch
exit 1

View File

@@ -1,3 +1,33 @@
/*************************************************************************/
/* WebRTCLibDataChannel.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "WebRTCLibDataChannel.hpp"
#include "GDNativeLibrary.hpp"
@@ -40,7 +70,6 @@ WebRTCLibDataChannel *WebRTCLibDataChannel::new_data_channel(rtc::scoped_refptr<
return tmp;
}
void WebRTCLibDataChannel::bind_channel(rtc::scoped_refptr<webrtc::DataChannelInterface> p_channel) {
ERR_FAIL_COND(p_channel.get() == nullptr);
@@ -115,12 +144,17 @@ bool WebRTCLibDataChannel::is_negotiated() const {
return channel->negotiated();
}
int WebRTCLibDataChannel::get_buffered_amount() const {
ERR_FAIL_COND_V(channel.get() == nullptr, 0);
return channel->buffered_amount();
}
godot_error WebRTCLibDataChannel::poll() {
return GODOT_OK;
}
void WebRTCLibDataChannel::close() {
if(channel.get() != nullptr) {
if (channel.get() != nullptr) {
channel->Close();
channel->UnregisterObserver();
}
@@ -167,7 +201,8 @@ void WebRTCLibDataChannel::_init() {
register_interface(&interface);
}
WebRTCLibDataChannel::WebRTCLibDataChannel() : observer(this) {
WebRTCLibDataChannel::WebRTCLibDataChannel() :
observer(this) {
mutex = new std::mutex;
}

View File

@@ -1,3 +1,33 @@
/*************************************************************************/
/* WebRTCLibDataChannel.hpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#ifndef WEBRTC_DATA_CHANNEL_H
#define WEBRTC_DATA_CHANNEL_H
@@ -6,8 +36,8 @@
#include "api/peer_connection_interface.h" // interface for all things needed from WebRTC
#include "media/base/media_engine.h" // needed for CreateModularPeerConnectionFactory
#include "net/WebRTCDataChannelNative.hpp"
#include "PoolArrays.hpp"
#include "net/WebRTCDataChannelNative.hpp"
#include <mutex>
namespace godot_webrtc {
@@ -57,6 +87,7 @@ public:
int get_max_retransmits() const;
const char *get_protocol() const;
bool is_negotiated() const;
int get_buffered_amount() const;
godot_error poll();
void close();

View File

@@ -1,53 +0,0 @@
#include "WebRTCLibDataChannel.hpp"
#include "WebRTCLibPeerConnection.hpp"
using namespace godot_webrtc;
// CreateSessionObseerver
WebRTCLibPeerConnection::GodotCSDO::GodotCSDO(WebRTCLibPeerConnection *parent) {
this->parent = parent;
}
void WebRTCLibPeerConnection::GodotCSDO::OnSuccess(webrtc::SessionDescriptionInterface *desc) {
// serialize this offer and send it to the remote peer:
std::string sdp; // sdp = session description protocol
desc->ToString(&sdp);
parent->queue_signal("session_description_created", 2, desc->type().c_str(), sdp.c_str());
};
void WebRTCLibPeerConnection::GodotCSDO::OnFailure(webrtc::RTCError error){};
// SetSessionObseerver
WebRTCLibPeerConnection::GodotSSDO::GodotSSDO(WebRTCLibPeerConnection *parent) {
this->parent = parent;
}
void WebRTCLibPeerConnection::GodotSSDO::OnSuccess(){};
void WebRTCLibPeerConnection::GodotSSDO::OnFailure(webrtc::RTCError error){};
// PeerConnectionObserver
WebRTCLibPeerConnection::GodotPCO::GodotPCO(WebRTCLibPeerConnection *parent) {
this->parent = parent;
}
void WebRTCLibPeerConnection::GodotPCO::OnDataChannel(rtc::scoped_refptr<webrtc::DataChannelInterface> data_channel) {
parent->queue_signal("data_channel_received", 1, WebRTCLibDataChannel::new_data_channel(data_channel));
}
void WebRTCLibPeerConnection::GodotPCO::OnIceCandidate(const webrtc::IceCandidateInterface *candidate) {
godot::Dictionary candidateSDP;
godot::String candidateSdpMidName = candidate->sdp_mid().c_str();
int candidateSdpMlineIndexName = candidate->sdp_mline_index();
std::string sdp;
candidate->ToString(&sdp);
godot::String candidateSdpName = sdp.c_str();
parent->queue_signal("ice_candidate_created", 3, candidateSdpMidName, candidateSdpMlineIndexName, candidateSdpName);
}
void WebRTCLibPeerConnection::GodotPCO::OnSignalingChange(webrtc::PeerConnectionInterface::SignalingState new_state) {}
void WebRTCLibPeerConnection::GodotPCO::OnAddStream(rtc::scoped_refptr<webrtc::MediaStreamInterface> stream) {}
void WebRTCLibPeerConnection::GodotPCO::OnRemoveStream(rtc::scoped_refptr<webrtc::MediaStreamInterface> stream) {}
void WebRTCLibPeerConnection::GodotPCO::OnRenegotiationNeeded() {}
void WebRTCLibPeerConnection::GodotPCO::OnIceConnectionChange(webrtc::PeerConnectionInterface::IceConnectionState new_state) {}
void WebRTCLibPeerConnection::GodotPCO::OnIceGatheringChange(webrtc::PeerConnectionInterface::IceGatheringState new_state) {}

View File

@@ -1,12 +1,69 @@
/*************************************************************************/
/* WebRTCLibPeerConnection.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "WebRTCLibPeerConnection.hpp"
#include "WebRTCDataChannel.hpp"
#include "WebRTCDataChannelGDNative.hpp"
#include "WebRTCLibPeerConnection.hpp"
#include "WebRTCLibDataChannel.hpp"
using namespace godot_webrtc;
std::unique_ptr<rtc::Thread> WebRTCLibPeerConnection::signaling_thread = nullptr;
// PeerConnectionObserver
void WebRTCLibPeerConnection::GodotPCO::OnIceCandidate(const webrtc::IceCandidateInterface *candidate) {
godot::Dictionary candidateSDP;
godot::String candidateSdpMidName = candidate->sdp_mid().c_str();
int candidateSdpMlineIndexName = candidate->sdp_mline_index();
std::string sdp;
candidate->ToString(&sdp);
godot::String candidateSdpName = sdp.c_str();
parent->queue_signal("ice_candidate_created", 3, candidateSdpMidName, candidateSdpMlineIndexName, candidateSdpName);
}
// SetSessionDescriptionObserver
void WebRTCLibPeerConnection::GodotSSDO::OnSuccess() {
if (make_offer) {
make_offer = false;
parent->peer_connection->CreateAnswer(parent->ptr_csdo, webrtc::PeerConnectionInterface::RTCOfferAnswerOptions());
}
}
// CreateSessionDescriptionObserver
void WebRTCLibPeerConnection::GodotCSDO::OnSuccess(webrtc::SessionDescriptionInterface *desc) {
// serialize this offer and send it to the remote peer:
std::string sdp;
desc->ToString(&sdp);
parent->queue_signal("session_description_created", 2, desc->type().c_str(), sdp.c_str());
}
void WebRTCLibPeerConnection::initialize_signaling() {
if (signaling_thread.get() == nullptr) {
signaling_thread = rtc::Thread::Create();
@@ -57,7 +114,12 @@ godot_error _parse_ice_server(webrtc::PeerConnectionInterface::RTCConfiguration
godot_error _parse_channel_config(webrtc::DataChannelInit &r_config, godot::Dictionary p_dict) {
godot::Variant v;
#define _SET_N(PROP, PNAME, TYPE) if (p_dict.has(#PROP)) { v = p_dict[#PROP]; if(v.get_type() == godot::Variant::TYPE) r_config.PNAME = v; }
#define _SET_N(PROP, PNAME, TYPE) \
if (p_dict.has(#PROP)) { \
v = p_dict[#PROP]; \
if (v.get_type() == godot::Variant::TYPE) \
r_config.PNAME = v; \
}
#define _SET(PROP, TYPE) _SET_N(PROP, PROP, TYPE)
_SET(negotiated, BOOL);
_SET(id, INT);
@@ -80,7 +142,7 @@ WebRTCLibPeerConnection::ConnectionState WebRTCLibPeerConnection::get_connection
ERR_FAIL_COND_V(peer_connection.get() == nullptr, STATE_CLOSED);
webrtc::PeerConnectionInterface::IceConnectionState state = peer_connection->ice_connection_state();
switch(state) {
switch (state) {
case webrtc::PeerConnectionInterface::kIceConnectionNew:
return STATE_NEW;
case webrtc::PeerConnectionInterface::kIceConnectionChecking:
@@ -142,8 +204,10 @@ godot_error WebRTCLibPeerConnection::create_offer() {
godot_error WebRTCLibPeerConnection::set_remote_description(const char *type, const char *sdp) {
ERR_FAIL_COND_V(peer_connection.get() == nullptr, GODOT_ERR_UNCONFIGURED);
std::unique_ptr<webrtc::SessionDescriptionInterface> desc = _MAKE_DESC(type, sdp);
if (desc->GetType() == webrtc::SdpType::kOffer) {
ptr_ssdo->make_offer = true;
}
peer_connection->SetRemoteDescription(ptr_ssdo, desc.release());
peer_connection->CreateAnswer(ptr_csdo, webrtc::PeerConnectionInterface::RTCOfferAnswerOptions());
return GODOT_OK;
}
@@ -174,14 +238,12 @@ godot_error WebRTCLibPeerConnection::add_ice_candidate(const char *sdpMidName, i
godot_error WebRTCLibPeerConnection::poll() {
ERR_FAIL_COND_V(peer_connection.get() == nullptr, GODOT_ERR_UNCONFIGURED);
std::function<void()> signal;
while (!signal_queue.empty()) {
mutex_signal_queue->lock();
signal = signal_queue.front();
Signal signal = signal_queue.front();
signal_queue.pop();
mutex_signal_queue->unlock();
signal();
signal.emit(this);
}
return GODOT_OK;
}
@@ -191,7 +253,7 @@ void WebRTCLibPeerConnection::close() {
peer_connection->Close();
}
peer_connection = nullptr;
while(!signal_queue.empty()) {
while (!signal_queue.empty()) {
signal_queue.pop();
}
}
@@ -244,15 +306,7 @@ WebRTCLibPeerConnection::~WebRTCLibPeerConnection() {
void WebRTCLibPeerConnection::queue_signal(godot::String p_name, int p_argc, const godot::Variant &p_arg1, const godot::Variant &p_arg2, const godot::Variant &p_arg3) {
mutex_signal_queue->lock();
signal_queue.push(
[this, p_name, p_argc, p_arg1, p_arg2, p_arg3] {
if (p_argc == 1) {
emit_signal(p_name, p_arg1);
} else if (p_argc == 2) {
emit_signal(p_name, p_arg1, p_arg2);
} else {
emit_signal(p_name, p_arg1, p_arg2, p_arg3);
}
});
const godot::Variant argv[3] = { p_arg1, p_arg2, p_arg3 };
signal_queue.push(Signal(p_name, p_argc, argv));
mutex_signal_queue->unlock();
}

View File

@@ -1,3 +1,33 @@
/*************************************************************************/
/* WebRTCLibPeerConnection.hpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#ifndef WEBRTC_PEER_H
#define WEBRTC_PEER_H
@@ -5,8 +35,7 @@
#include "api/peer_connection_interface.h" // interface for all things needed from WebRTC
#include "media/base/media_engine.h" // needed for CreateModularPeerConnectionFactory
#include <functional> // std::function
#include <mutex> // mutex @TODO replace std::mutex with Godot mutex
#include <mutex>
#include "net/WebRTCPeerConnectionNative.hpp"
@@ -19,6 +48,7 @@ private:
godot_error _create_pc(webrtc::PeerConnectionInterface::RTCConfiguration &config);
static std::unique_ptr<rtc::Thread> signaling_thread;
public:
static void _register_methods();
static void initialize_signaling();
@@ -41,9 +71,8 @@ public:
~WebRTCLibPeerConnection();
/* helper functions */
private:
void queue_signal(godot::String p_name, int p_argc, const godot::Variant &p_arg1 = godot::Variant(), const godot::Variant &p_arg2 = godot::Variant(), const godot::Variant &p_arg3 = godot::Variant());
// void queue_signal(godot::StringName p_name, Variant_ARG_LIST);
void queue_packet(uint8_t *, int);
/** PeerConnectionObserver callback functions **/
@@ -51,35 +80,75 @@ public:
public:
WebRTCLibPeerConnection *parent;
GodotPCO(WebRTCLibPeerConnection *parent);
void OnSignalingChange(webrtc::PeerConnectionInterface::SignalingState new_state) override;
void OnAddStream(rtc::scoped_refptr<webrtc::MediaStreamInterface> stream) override;
void OnRemoveStream(rtc::scoped_refptr<webrtc::MediaStreamInterface> stream) override;
void OnDataChannel(rtc::scoped_refptr<webrtc::DataChannelInterface> data_channel) override;
void OnRenegotiationNeeded() override;
void OnIceConnectionChange(webrtc::PeerConnectionInterface::IceConnectionState new_state) override;
void OnIceGatheringChange(webrtc::PeerConnectionInterface::IceGatheringState new_state) override;
GodotPCO(WebRTCLibPeerConnection *p_parent) {
parent = p_parent;
}
void OnIceCandidate(const webrtc::IceCandidateInterface *candidate) override;
void OnSignalingChange(webrtc::PeerConnectionInterface::SignalingState new_state) override {}
void OnAddStream(rtc::scoped_refptr<webrtc::MediaStreamInterface> stream) override {}
void OnRemoveStream(rtc::scoped_refptr<webrtc::MediaStreamInterface> stream) override {}
void OnDataChannel(rtc::scoped_refptr<webrtc::DataChannelInterface> data_channel) override {}
void OnRenegotiationNeeded() override {}
void OnIceConnectionChange(webrtc::PeerConnectionInterface::IceConnectionState new_state) override {}
void OnIceGatheringChange(webrtc::PeerConnectionInterface::IceGatheringState new_state) override {}
};
/** CreateSessionDescriptionObserver callback functions **/
class GodotCSDO : public webrtc::CreateSessionDescriptionObserver {
public:
WebRTCLibPeerConnection *parent;
WebRTCLibPeerConnection *parent = nullptr;
GodotCSDO(WebRTCLibPeerConnection *parent);
GodotCSDO(WebRTCLibPeerConnection *p_parent) {
parent = p_parent;
}
void OnSuccess(webrtc::SessionDescriptionInterface *desc) override;
void OnFailure(webrtc::RTCError error) override;
void OnFailure(webrtc::RTCError error) override {
ERR_PRINT(godot::String(error.message()));
}
};
/** SetSessionDescriptionObserver callback functions **/
class GodotSSDO : public webrtc::SetSessionDescriptionObserver {
public:
WebRTCLibPeerConnection *parent;
WebRTCLibPeerConnection *parent = nullptr;
bool make_offer = false;
GodotSSDO(WebRTCLibPeerConnection *parent);
GodotSSDO(WebRTCLibPeerConnection *p_parent) {
parent = p_parent;
}
void OnSuccess() override;
void OnFailure(webrtc::RTCError error) override;
void OnFailure(webrtc::RTCError error) override {
make_offer = false;
ERR_PRINT(godot::String(error.message()));
}
};
class Signal {
godot::String method;
godot::Variant argv[3];
int argc = 0;
public:
Signal(godot::String p_method, int p_argc, const godot::Variant *p_argv) {
method = p_method;
argc = p_argc;
for (int i = 0; i < argc; i++) {
argv[i] = p_argv[i];
}
}
void emit(godot::Object *p_object) {
if (argc == 0) {
p_object->emit_signal(method);
} else if (argc == 1) {
p_object->emit_signal(method, argv[0]);
} else if (argc == 2) {
p_object->emit_signal(method, argv[0], argv[1]);
} else if (argc == 3) {
p_object->emit_signal(method, argv[0], argv[1], argv[2]);
}
}
};
GodotPCO pco;
@@ -87,7 +156,7 @@ public:
rtc::scoped_refptr<GodotCSDO> ptr_csdo;
std::mutex *mutex_signal_queue = nullptr;
std::queue<std::function<void()> > signal_queue;
std::queue<Signal> signal_queue;
rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface> pc_factory;
rtc::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection;

View File

@@ -1,3 +1,33 @@
/*************************************************************************/
/* init.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "WebRTCLibDataChannel.hpp"
#include "WebRTCLibPeerConnection.hpp"
#include "net/WebRTCPeerConnectionNative.hpp"
@@ -34,14 +64,14 @@ godot_error create_peer_connection_wp(godot_object *out) {
_singleton_api->godot_string_destroy(&s);
// Bind script to Object
const void *args3[] = { (void *)script };
const void *args3[] = { (void *)script };
_singleton_api->godot_method_bind_ptrcall(_set_script_mb, out, args3, nullptr);
return GODOT_OK;
}
godot_net_webrtc_library library = {
{3, 2},
{ 3, 2 },
&unregistered,
&create_peer_connection_wp,
NULL,
@@ -72,7 +102,6 @@ extern "C" void GDN_EXPORT godot_gdnative_singleton() {
extern "C" void GDN_EXPORT godot_gdnative_init(godot_gdnative_init_options *o) {
const godot_gdnative_core_api_struct *api = o->api_struct;
for (int i = 0; i < api->num_extensions; i++) {
if (api->extensions[i]->type != GDNATIVE_EXT_NET)
continue;

View File

@@ -1,3 +1,33 @@
/*************************************************************************/
/* WebRTCDataChannelNative.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "WebRTCDataChannelNative.hpp"
#include "net/WebRTCPeerConnectionNative.hpp"
@@ -83,6 +113,10 @@ bool is_negotiated_wdc(const void *user) {
return ((WebRTCDataChannelNative *)user)->is_negotiated();
}
int get_buffered_amount_wdc(const void *user) {
return ((WebRTCDataChannelNative *)user)->get_buffered_amount();
}
godot_error poll_wdc(void *user) {
return ((WebRTCDataChannelNative *)user)->poll();
}

View File

@@ -1,3 +1,33 @@
/*************************************************************************/
/* WebRTCDataChannelNative.hpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#ifndef WEBRTC_DATA_CHANNEL_NATIVE
#define WEBRTC_DATA_CHANNEL_NATIVE
@@ -24,13 +54,30 @@ int get_max_packet_life_time_wdc(const void *);
int get_max_retransmits_wdc(const void *);
const char *get_protocol_wdc(const void *);
bool is_negotiated_wdc(const void *);
int get_buffered_amount_wdc(const void *);
godot_error poll_wdc(void *);
void close_wdc(void *);
#if GODOT_NET_WEBRTC_API_MAJOR == 3 && GODOT_NET_WEBRTC_API_MINOR < 4
extern "C" {
/* Extensions to WebRTCDataChannel */
typedef struct {
int (*get_buffered_amount)(const void *);
void *next; /* For extension? */
} godot_net_webrtc_data_channel_ext;
}
#endif
class WebRTCDataChannelNative : public godot::WebRTCDataChannelGDNative {
GODOT_CLASS(WebRTCDataChannelNative, godot::WebRTCDataChannelGDNative);
protected:
godot_net_webrtc_data_channel_ext interface_ext = {
&get_buffered_amount_wdc,
NULL,
};
godot_net_webrtc_data_channel interface = {
{ 3, 1 },
this,
@@ -54,7 +101,7 @@ protected:
&poll_wdc,
&close_wdc,
NULL,
&interface_ext,
};
public:
@@ -75,6 +122,7 @@ public:
virtual int get_max_retransmits() const = 0;
virtual const char *get_protocol() const = 0;
virtual bool is_negotiated() const = 0;
virtual int get_buffered_amount() const = 0;
virtual godot_error poll() = 0;
virtual void close() = 0;

View File

@@ -1,3 +1,33 @@
/*************************************************************************/
/* WebRTCPeerConnectionNative.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "WebRTCPeerConnectionNative.hpp"
const godot_gdnative_ext_net_3_2_api_struct *WebRTCPeerConnectionNative::_net_api = NULL;

View File

@@ -1,3 +1,33 @@
/*************************************************************************/
/* WebRTCPeerConnectionNative.hpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#ifndef WEBRTC_PEER_NATIVE
#define WEBRTC_PEER_NATIVE

3
webrtc/.gitignore vendored
View File

@@ -1 +1,2 @@
include/
*
!.gitignore

View File

@@ -1,2 +0,0 @@
*
!.gitignore

View File

@@ -1,2 +0,0 @@
*
!.gitignore