Compare commits

..

1 Commits

Author SHA1 Message Date
679ecfc066 Bumped version to 0.10.5 2021-01-21 14:40:21 +01:00
2635 changed files with 4109 additions and 16036 deletions

View File

@ -1,6 +1,6 @@
version: 2
updates:
- package-ecosystem: "npm"
directory: "examples/signaling-server-nodejs"
directory: "examples/web"
schedule:
interval: "weekly"

3
.gitignore vendored
View File

@ -5,7 +5,6 @@ node_modules/
*.a
*.so
compile_commands.json
/tests
tests
.DS_Store
.idea

2
.gitmodules vendored
View File

@ -1,6 +1,6 @@
[submodule "deps/plog"]
path = deps/plog
url = https://github.com/SergiusTheBest/plog.git
url = https://github.com/paullouisageneau/plog
[submodule "usrsctp"]
path = deps/usrsctp
url = https://github.com/sctplab/usrsctp.git

View File

@ -1,71 +0,0 @@
# libdatachannel - Building instructions
## Clone repository and submodules
```bash
$ git clone https://github.com/paullouisageneau/libdatachannel.git
$ cd libdatachannel
$ git submodule update --init --recursive
```
## Build with CMake
The CMake library targets `libdatachannel` and `libdatachannel-static` respectively correspond to the shared and static libraries. The default target will build tests and examples. The option `USE_GNUTLS` allows to switch between OpenSSL (default) and GnuTLS, and the option `USE_NICE` allows to switch between libjuice as submodule (default) and libnice.
If you only need Data Channels, the option `NO_MEDIA` allows to make the library lighter by removing media support. Similarly, `NO_WEBSOCKET` removes WebSocket support.
### POSIX-compliant operating systems (including Linux and Apple macOS)
```bash
$ cmake -B build -DUSE_GNUTLS=1 -DUSE_NICE=0
$ cd build
$ make -j2
```
### Apple macOS with XCode project
```bash
$ cmake -B "$BUILD_DIR" -DUSE_GNUTLS=0 -DUSE_NICE=0 -G Xcode
```
Xcode project is generated in *build/* directory.
#### Solving **Could NOT find OpenSSL** error
You need to add OpenSSL root directory if your build fails with the following message:
```
Could NOT find OpenSSL, try to set the path to OpenSSL root folder in the
system variable OPENSSL_ROOT_DIR (missing: OPENSSL_CRYPTO_LIBRARY
OPENSSL_INCLUDE_DIR)
```
for example:
```bash
$ cmake -B build -DUSE_GNUTLS=0 -DUSE_NICE=0 -G Xcode -DOPENSSL_ROOT_DIR=/usr/local/Cellar/openssl\@1.1/1.1.1h/
```
### Microsoft Windows with MinGW cross-compilation
```bash
$ cmake -B build -DCMAKE_TOOLCHAIN_FILE=/usr/share/mingw/toolchain-x86_64-w64-mingw32.cmake # replace with your toolchain file
$ cd build
$ make -j2
```
### Microsoft Windows with Microsoft Visual C++
```bash
$ cmake -B build -G "NMake Makefiles"
$ cd build
$ nmake
```
## Build directly with Make (Linux only)
The option `USE_GNUTLS` allows to switch between OpenSSL (default) and GnuTLS, and the option `USE_NICE` allows to switch between libjuice as submodule (default) and libnice.
If you only need Data Channels, the option `NO_MEDIA` removes media support. Similarly, `NO_WEBSOCKET` removes WebSocket support.
```bash
$ make USE_GNUTLS=1 USE_NICE=0
```

View File

@ -1,6 +1,6 @@
cmake_minimum_required(VERSION 3.7)
project(libdatachannel
VERSION 0.13.1
VERSION 0.10.5
LANGUAGES CXX)
set(PROJECT_DESCRIPTION "WebRTC Data Channels Library")
@ -13,8 +13,15 @@ option(NO_MEDIA "Disable media transport support" OFF)
option(NO_EXAMPLES "Disable examples" OFF)
option(NO_TESTS "Disable tests build" OFF)
option(WARNINGS_AS_ERRORS "Treat warnings as errors" OFF)
option(RSA_KEY_BITS_2048 "Use 2048-bit RSA key instead of 3072-bit" OFF)
option(CAPI_STDCALL "Set calling convention of C API callbacks stdcall" OFF)
if(USE_NICE)
option(USE_JUICE "Use libjuice" OFF)
else()
option(USE_JUICE "Use libjuice" ON)
endif()
if(USE_GNUTLS)
option(USE_NETTLE "Use Nettle in libjuice" ON)
else()
@ -39,32 +46,36 @@ endif()
set(LIBDATACHANNEL_SOURCES
${CMAKE_CURRENT_SOURCE_DIR}/src/candidate.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/certificate.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/channel.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/configuration.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/datachannel.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/description.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/global.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/dtlssrtptransport.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/dtlstransport.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/icetransport.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/init.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/log.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/message.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/peerconnection.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/rtcpreceivingsession.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/rtcp.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/sctptransport.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/threadpool.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/tls.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/track.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/websocket.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/rtppacketizationconfig.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/rtcpsrreporter.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/rtppacketizer.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/opusrtppacketizer.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/opuspacketizationhandler.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/h264rtppacketizer.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/nalunit.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/h264packetizationhandler.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/mediachainablehandler.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/mediahandlerelement.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/mediahandlerrootelement.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/rtcpnackresponder.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/rtp.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/processor.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/capi.cpp
)
set(LIBDATACHANNEL_WEBSOCKET_SOURCES
${CMAKE_CURRENT_SOURCE_DIR}/src/base64.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/tcptransport.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/tlstransport.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/verifiedtlstransport.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/websocket.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/wstransport.cpp
)
set(LIBDATACHANNEL_HEADERS
${CMAKE_CURRENT_SOURCE_DIR}/include/rtc/candidate.hpp
${CMAKE_CURRENT_SOURCE_DIR}/include/rtc/channel.hpp
@ -72,85 +83,24 @@ set(LIBDATACHANNEL_HEADERS
${CMAKE_CURRENT_SOURCE_DIR}/include/rtc/configuration.hpp
${CMAKE_CURRENT_SOURCE_DIR}/include/rtc/datachannel.hpp
${CMAKE_CURRENT_SOURCE_DIR}/include/rtc/description.hpp
${CMAKE_CURRENT_SOURCE_DIR}/include/rtc/mediahandler.hpp
${CMAKE_CURRENT_SOURCE_DIR}/include/rtc/rtcpreceivingsession.hpp
${CMAKE_CURRENT_SOURCE_DIR}/include/rtc/common.hpp
${CMAKE_CURRENT_SOURCE_DIR}/include/rtc/global.hpp
${CMAKE_CURRENT_SOURCE_DIR}/include/rtc/rtcp.hpp
${CMAKE_CURRENT_SOURCE_DIR}/include/rtc/include.hpp
${CMAKE_CURRENT_SOURCE_DIR}/include/rtc/init.hpp
${CMAKE_CURRENT_SOURCE_DIR}/include/rtc/log.hpp
${CMAKE_CURRENT_SOURCE_DIR}/include/rtc/message.hpp
${CMAKE_CURRENT_SOURCE_DIR}/include/rtc/peerconnection.hpp
${CMAKE_CURRENT_SOURCE_DIR}/include/rtc/queue.hpp
${CMAKE_CURRENT_SOURCE_DIR}/include/rtc/reliability.hpp
${CMAKE_CURRENT_SOURCE_DIR}/include/rtc/rtc.h
${CMAKE_CURRENT_SOURCE_DIR}/include/rtc/rtc.hpp
${CMAKE_CURRENT_SOURCE_DIR}/include/rtc/rtp.hpp
${CMAKE_CURRENT_SOURCE_DIR}/include/rtc/track.hpp
${CMAKE_CURRENT_SOURCE_DIR}/include/rtc/websocket.hpp
${CMAKE_CURRENT_SOURCE_DIR}/include/rtc/rtppacketizationconfig.hpp
${CMAKE_CURRENT_SOURCE_DIR}/include/rtc/rtcpsrreporter.hpp
${CMAKE_CURRENT_SOURCE_DIR}/include/rtc/rtppacketizer.hpp
${CMAKE_CURRENT_SOURCE_DIR}/include/rtc/opusrtppacketizer.hpp
${CMAKE_CURRENT_SOURCE_DIR}/include/rtc/opuspacketizationhandler.hpp
${CMAKE_CURRENT_SOURCE_DIR}/include/rtc/h264rtppacketizer.hpp
${CMAKE_CURRENT_SOURCE_DIR}/include/rtc/nalunit.hpp
${CMAKE_CURRENT_SOURCE_DIR}/include/rtc/h264packetizationhandler.hpp
${CMAKE_CURRENT_SOURCE_DIR}/include/rtc/mediachainablehandler.hpp
${CMAKE_CURRENT_SOURCE_DIR}/include/rtc/mediahandlerelement.hpp
${CMAKE_CURRENT_SOURCE_DIR}/include/rtc/mediahandlerrootelement.hpp
${CMAKE_CURRENT_SOURCE_DIR}/include/rtc/rtcpnackresponder.hpp
${CMAKE_CURRENT_SOURCE_DIR}/include/rtc/utils.hpp
)
set(LIBDATACHANNEL_IMPL_SOURCES
${CMAKE_CURRENT_SOURCE_DIR}/src/impl/certificate.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/impl/channel.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/impl/datachannel.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/impl/dtlssrtptransport.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/impl/dtlstransport.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/impl/icetransport.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/impl/init.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/impl/peerconnection.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/impl/logcounter.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/impl/sctptransport.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/impl/threadpool.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/impl/tls.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/impl/track.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/impl/processor.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/impl/base64.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/impl/tcptransport.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/impl/tlstransport.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/impl/verifiedtlstransport.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/impl/websocket.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/impl/wstransport.cpp
)
set(LIBDATACHANNEL_IMPL_HEADERS
${CMAKE_CURRENT_SOURCE_DIR}/src/impl/certificate.hpp
${CMAKE_CURRENT_SOURCE_DIR}/src/impl/channel.hpp
${CMAKE_CURRENT_SOURCE_DIR}/src/impl/datachannel.hpp
${CMAKE_CURRENT_SOURCE_DIR}/src/impl/dtlssrtptransport.hpp
${CMAKE_CURRENT_SOURCE_DIR}/src/impl/dtlstransport.hpp
${CMAKE_CURRENT_SOURCE_DIR}/src/impl/icetransport.hpp
${CMAKE_CURRENT_SOURCE_DIR}/src/impl/init.hpp
${CMAKE_CURRENT_SOURCE_DIR}/src/impl/internals.hpp
${CMAKE_CURRENT_SOURCE_DIR}/src/impl/peerconnection.hpp
${CMAKE_CURRENT_SOURCE_DIR}/src/impl/queue.hpp
${CMAKE_CURRENT_SOURCE_DIR}/src/impl/logcounter.hpp
${CMAKE_CURRENT_SOURCE_DIR}/src/impl/sctptransport.hpp
${CMAKE_CURRENT_SOURCE_DIR}/src/impl/threadpool.hpp
${CMAKE_CURRENT_SOURCE_DIR}/src/impl/tls.hpp
${CMAKE_CURRENT_SOURCE_DIR}/src/impl/track.hpp
${CMAKE_CURRENT_SOURCE_DIR}/src/impl/processor.hpp
${CMAKE_CURRENT_SOURCE_DIR}/src/impl/base64.hpp
${CMAKE_CURRENT_SOURCE_DIR}/src/impl/tcptransport.hpp
${CMAKE_CURRENT_SOURCE_DIR}/src/impl/tlstransport.hpp
${CMAKE_CURRENT_SOURCE_DIR}/src/impl/verifiedtlstransport.hpp
${CMAKE_CURRENT_SOURCE_DIR}/src/impl/websocket.hpp
${CMAKE_CURRENT_SOURCE_DIR}/src/impl/wstransport.hpp
)
set(TESTS_SOURCES
${CMAKE_CURRENT_SOURCE_DIR}/test/main.cpp
${CMAKE_CURRENT_SOURCE_DIR}/test/connectivity.cpp
${CMAKE_CURRENT_SOURCE_DIR}/test/turn_connectivity.cpp
${CMAKE_CURRENT_SOURCE_DIR}/test/track.cpp
${CMAKE_CURRENT_SOURCE_DIR}/test/capi_connectivity.cpp
${CMAKE_CURRENT_SOURCE_DIR}/test/capi_track.cpp
@ -158,26 +108,6 @@ set(TESTS_SOURCES
${CMAKE_CURRENT_SOURCE_DIR}/test/benchmark.cpp
)
set(TESTS_UWP_RESOURCES
${CMAKE_CURRENT_SOURCE_DIR}/test/uwp/tests/Logo.png
${CMAKE_CURRENT_SOURCE_DIR}/test/uwp/tests/package.appxManifest
${CMAKE_CURRENT_SOURCE_DIR}/test/uwp/tests/SmallLogo.png
${CMAKE_CURRENT_SOURCE_DIR}/test/uwp/tests/SmallLogo44x44.png
${CMAKE_CURRENT_SOURCE_DIR}/test/uwp/tests/SplashScreen.png
${CMAKE_CURRENT_SOURCE_DIR}/test/uwp/tests/StoreLogo.png
${CMAKE_CURRENT_SOURCE_DIR}/test/uwp/tests/Windows_TemporaryKey.pfx
)
set(BENCHMARK_UWP_RESOURCES
${CMAKE_CURRENT_SOURCE_DIR}/test/uwp/benchmark/Logo.png
${CMAKE_CURRENT_SOURCE_DIR}/test/uwp/benchmark/package.appxManifest
${CMAKE_CURRENT_SOURCE_DIR}/test/uwp/benchmark/SmallLogo.png
${CMAKE_CURRENT_SOURCE_DIR}/test/uwp/benchmark/SmallLogo44x44.png
${CMAKE_CURRENT_SOURCE_DIR}/test/uwp/benchmark/SplashScreen.png
${CMAKE_CURRENT_SOURCE_DIR}/test/uwp/benchmark/StoreLogo.png
${CMAKE_CURRENT_SOURCE_DIR}/test/uwp/benchmark/Windows_TemporaryKey.pfx
)
set(CMAKE_THREAD_PREFER_PTHREAD TRUE)
set(THREADS_PREFER_PTHREAD_FLAG TRUE)
find_package(Threads REQUIRED)
@ -187,7 +117,6 @@ add_subdirectory(deps/plog)
option(sctp_build_programs 0)
option(sctp_build_shared_lib 0)
set(CMAKE_POLICY_DEFAULT_CMP0077 NEW)
add_subdirectory(deps/usrsctp EXCLUDE_FROM_ALL)
if (MSYS OR MINGW)
target_compile_definitions(usrsctp PUBLIC -DSCTP_STDINT_INCLUDE=<stdint.h>)
@ -197,16 +126,23 @@ if (CMAKE_CXX_COMPILER_ID MATCHES "GNU")
endif()
add_library(Usrsctp::Usrsctp ALIAS usrsctp)
add_library(datachannel SHARED
${LIBDATACHANNEL_SOURCES}
${LIBDATACHANNEL_HEADERS}
${LIBDATACHANNEL_IMPL_SOURCES}
${LIBDATACHANNEL_IMPL_HEADERS})
add_library(datachannel-static STATIC EXCLUDE_FROM_ALL
${LIBDATACHANNEL_SOURCES}
${LIBDATACHANNEL_HEADERS}
${LIBDATACHANNEL_IMPL_SOURCES}
${LIBDATACHANNEL_IMPL_HEADERS})
if (NO_WEBSOCKET)
add_library(datachannel SHARED
${LIBDATACHANNEL_SOURCES})
add_library(datachannel-static STATIC EXCLUDE_FROM_ALL
${LIBDATACHANNEL_SOURCES})
target_compile_definitions(datachannel PUBLIC RTC_ENABLE_WEBSOCKET=0)
target_compile_definitions(datachannel-static PUBLIC RTC_ENABLE_WEBSOCKET=0)
else()
add_library(datachannel SHARED
${LIBDATACHANNEL_SOURCES}
${LIBDATACHANNEL_WEBSOCKET_SOURCES})
add_library(datachannel-static STATIC EXCLUDE_FROM_ALL
${LIBDATACHANNEL_SOURCES}
${LIBDATACHANNEL_WEBSOCKET_SOURCES})
target_compile_definitions(datachannel PUBLIC RTC_ENABLE_WEBSOCKET=1)
target_compile_definitions(datachannel-static PUBLIC RTC_ENABLE_WEBSOCKET=1)
endif()
set_target_properties(datachannel PROPERTIES
VERSION ${PROJECT_VERSION}
@ -215,31 +151,23 @@ set_target_properties(datachannel-static PROPERTIES
VERSION ${PROJECT_VERSION}
CXX_STANDARD 17)
target_include_directories(datachannel PUBLIC $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include> $<INSTALL_INTERFACE:include>)
target_include_directories(datachannel PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)
target_include_directories(datachannel PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include/rtc)
target_include_directories(datachannel PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src)
target_link_libraries(datachannel PUBLIC Threads::Threads)
target_link_libraries(datachannel PRIVATE Usrsctp::Usrsctp plog::plog)
target_link_libraries(datachannel PUBLIC Threads::Threads plog::plog)
target_link_libraries(datachannel PRIVATE Usrsctp::Usrsctp)
target_include_directories(datachannel-static PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)
target_include_directories(datachannel-static PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include/rtc)
target_include_directories(datachannel-static PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src)
target_link_libraries(datachannel-static PUBLIC Threads::Threads)
target_link_libraries(datachannel-static PRIVATE Usrsctp::Usrsctp plog::plog)
target_link_libraries(datachannel-static PUBLIC Threads::Threads plog::plog)
target_link_libraries(datachannel-static PRIVATE Usrsctp::Usrsctp)
if(WIN32)
target_link_libraries(datachannel PUBLIC ws2_32) # winsock2
target_link_libraries(datachannel-static PUBLIC ws2_32) # winsock2
endif()
if (NO_WEBSOCKET)
target_compile_definitions(datachannel PUBLIC RTC_ENABLE_WEBSOCKET=0)
target_compile_definitions(datachannel-static PUBLIC RTC_ENABLE_WEBSOCKET=0)
else()
target_compile_definitions(datachannel PUBLIC RTC_ENABLE_WEBSOCKET=1)
target_compile_definitions(datachannel-static PUBLIC RTC_ENABLE_WEBSOCKET=1)
endif()
if(NO_MEDIA)
target_compile_definitions(datachannel PUBLIC RTC_ENABLE_MEDIA=0)
target_compile_definitions(datachannel-static PUBLIC RTC_ENABLE_MEDIA=0)
@ -290,7 +218,7 @@ else()
target_link_libraries(datachannel-static PRIVATE OpenSSL::SSL)
endif()
if (USE_NICE)
if (USE_NICE OR NOT USE_JUICE)
find_package(LibNice REQUIRED)
target_compile_definitions(datachannel PRIVATE USE_NICE=1)
target_compile_definitions(datachannel-static PRIVATE USE_NICE=1)
@ -304,6 +232,11 @@ else()
target_link_libraries(datachannel-static PRIVATE LibJuice::LibJuiceStatic)
endif()
if(RSA_KEY_BITS_2048)
target_compile_definitions(datachannel PUBLIC RSA_KEY_BITS_2048)
target_compile_definitions(datachannel-static PUBLIC RSA_KEY_BITS_2048)
endif()
if(CAPI_STDCALL)
target_compile_definitions(datachannel PUBLIC CAPI_STDCALL)
target_compile_definitions(datachannel-static PUBLIC CAPI_STDCALL)
@ -312,6 +245,9 @@ endif()
add_library(LibDataChannel::LibDataChannel ALIAS datachannel)
add_library(LibDataChannel::LibDataChannelStatic ALIAS datachannel-static)
install(TARGETS datachannel LIBRARY DESTINATION lib)
install(FILES ${LIBDATACHANNEL_HEADERS} DESTINATION include/rtc)
if(NOT MSVC)
target_compile_options(datachannel PRIVATE -Wall -Wextra)
target_compile_options(datachannel-static PRIVATE -Wall -Wextra)
@ -327,64 +263,38 @@ if(WARNINGS_AS_ERRORS)
endif()
endif()
install(TARGETS datachannel EXPORT libdatachannel-config
RUNTIME DESTINATION bin
LIBRARY DESTINATION lib
ARCHIVE DESTINATION lib
)
install(FILES ${LIBDATACHANNEL_HEADERS}
DESTINATION include/rtc
)
install(
EXPORT libdatachannel-config
NAMESPACE LibDatachannel::
DESTINATION share/cmake/libdatachannel
)
# Tests
if(NOT NO_TESTS)
if(CMAKE_SYSTEM_NAME STREQUAL "WindowsStore")
# Add resource files needed for UWP apps.
add_executable(datachannel-tests ${TESTS_SOURCES} ${TESTS_UWP_RESOURCES})
else()
add_executable(datachannel-tests ${TESTS_SOURCES})
endif()
add_executable(datachannel-tests ${TESTS_SOURCES})
set_target_properties(datachannel-tests PROPERTIES
VERSION ${PROJECT_VERSION}
CXX_STANDARD 17)
set_target_properties(datachannel-tests PROPERTIES OUTPUT_NAME tests)
if(NOT CMAKE_SYSTEM_NAME STREQUAL "WindowsStore") # Prevent a bug in manifest generation for UWP
set_target_properties(datachannel-tests PROPERTIES OUTPUT_NAME tests)
endif()
target_include_directories(datachannel-tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src)
target_link_libraries(datachannel-tests datachannel)
# Benchmark
if(CMAKE_SYSTEM_NAME STREQUAL "WindowsStore")
# Add resource files needed for UWP apps.
add_executable(datachannel-benchmark test/benchmark.cpp ${BENCHMARK_UWP_RESOURCES})
else()
add_executable(datachannel-benchmark test/benchmark.cpp)
endif()
add_executable(datachannel-benchmark test/benchmark.cpp)
set_target_properties(datachannel-benchmark PROPERTIES
VERSION ${PROJECT_VERSION}
CXX_STANDARD 17)
set_target_properties(datachannel-benchmark PROPERTIES OUTPUT_NAME benchmark)
if(NOT CMAKE_SYSTEM_NAME STREQUAL "WindowsStore") # Prevent a bug in manifest generation for UWP
set_target_properties(datachannel-benchmark PROPERTIES OUTPUT_NAME benchmark)
endif()
target_compile_definitions(datachannel-benchmark PRIVATE BENCHMARK_MAIN=1)
target_include_directories(datachannel-benchmark PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src)
target_link_libraries(datachannel-benchmark datachannel)
endif()
# Examples
if(NOT NO_EXAMPLES)
if(NOT NO_EXAMPLES AND NOT CMAKE_SYSTEM_NAME STREQUAL "WindowsStore")
set(JSON_BuildTests OFF CACHE INTERNAL "")
add_subdirectory(deps/json)
add_subdirectory(examples/client)
add_subdirectory(examples/client-benchmark)
if(NOT NO_MEDIA)
add_subdirectory(examples/media)
add_subdirectory(examples/sfu-media)
add_subdirectory(examples/streamer)
endif()
add_subdirectory(examples/copy-paste)
add_subdirectory(examples/copy-paste-capi)
endif()

648
DOC.md
View File

@ -1,648 +0,0 @@
# libdatachannel - C API Documentation
The following details the C API of libdatachannel. The C API is available by including the `rtc/rtc.h` header.
### General considerations
Unless stated otherwise, functions return `RTC_ERR_SUCCESS`, defined as `0`, on success.
All functions can return the following negative error codes:
- `RTC_ERR_INVALID`: an invalid argument was provided
- `RTC_ERR_FAILURE`: a runtime error happened
- `RTC_ERR_NOT_AVAIL`: an element is not available at the moment
- `RTC_ERR_TOO_SMALL`: a user-provided buffer is too small
All functions taking pointers as arguments (excepted the opaque user pointer) need the memory to be accessible until the call returns, but it can be safely discarded afterwards.
### Common
#### rtcInitLogger
```
void rtcInitLogger(rtcLogLevel level, rtcLogCallbackFunc cb)
```
Arguments:
- `level`: the log level. It must be one of the following: `RTC_LOG_NONE`, `RTC_LOG_FATAL`, `RTC_LOG_ERROR`, `RTC_LOG_WARNING`, `RTC_LOG_INFO`, `RTC_LOG_DEBUG`, `RTC_LOG_VERBOSE`.
- `cb` (optional): the callback to pass the log lines to. If the callback is already set, it is replaced. If NULL after a callback is set, the callback is unset. If NULL on first call, the library will log to stdout instead.
`cb` must have the following signature:
`void myLogCallback(rtcLogLevel level, const char *message)`
Arguments:
- `level`: the log level for the current message. It will be one of the following: `RTC_LOG_FATAL`, `RTC_LOG_ERROR`, `RTC_LOG_WARNING`, `RTC_LOG_INFO`, `RTC_LOG_DEBUG`, `RTC_LOG_VERBOSE`.
- `message`: a null-terminated string containing the log message
#### rtcPreload
```
void rtcPreload(void)
```
An optional call to `rtcPreload` preloads the global resources used by the library. If it is not called, resources are lazy-loaded when they are required for the first time by a PeerConnection, which for instance prevents from properly timing connection establishment (as the first one will take way more time). The call blocks until preloading is finished. If resources are already loaded, the call has no effect.
#### rtcCleanup
```
void rtcCleanup(void)
```
An optional call to `rtcCleanup` requests unloading of the global resources used by the library. If all created PeerConnections are deleted, unloading will happen immediately and the call will block until unloading is done, otherwise unloading will happen as soon as the last PeerConnection is deleted. If resources are already unloaded, the call has no effect.
#### rtcSetUserPointer
```
void rtcSetUserPointer(int id, void *user_ptr)
```
Sets a opaque user pointer for a Peer Connection, Data Channel, Track, or WebSocket. The user pointer will be passed as last argument in each corresponding callback. It will never be accessed in any way. The initial user pointer of a Peer Connection or WebSocket is `NULL`, and the initial one of a Data Channel or Track is the one of the Peer Connection at the time of creation.
Arguments:
- `id`: the identifier of Peer Connection, Data Channel, Track, or WebSocket
- `user_ptr`: an opaque pointer whose meaning is up to the user
### PeerConnection
#### rtcCreatePeerConnection
```
int rtcCreatePeerConnection(const rtcConfiguration *config)
typedef struct {
const char **iceServers;
int iceServersCount;
rtcCertificateType certificateType;
bool enableIceTcp;
bool disableAutoNegotiation;
uint16_t portRangeBegin;
uint16_t portRangeEnd;
int mtu;
} rtcConfiguration;
```
Creates a Peer Connection.
Arguments:
- `config`: the configuration structure, containing:
- `iceServers` (optional): an array of pointers on null-terminated ice server URIs (NULL if unused)
- `iceServersCount` (optional): number of URLs in the array pointed by `iceServers` (0 if unused)
- `certificateType` (optional): certificate type, either `RTC_CERTIFICATE_ECDSA` or `RTC_CERTIFICATE_RSA` (0 or `RTC_CERTIFICATE_DEFAULT` if default)
- `enableIceTcp`: if true, generate TCP candidates for ICE (ignored with libjuice as ICE backend)
- `disableAutoNegotiation`: if true, the user is responsible for calling `rtcSetLocalDescription` after creating a Data Channel and after setting the remote description
- `portRangeBegin` (optional): first port (included) of the allowed local port range (0 if unused)
- `portRangeEnd` (optional): last port (included) of the allowed local port (0 if unused)
- `mtu` (optional): manually set the Maximum Transfer Unit (MTU) for the connection (0 if automatic)
- `maxMessageSize` (optional): manually set the local maximum message size for Data Channels (0 if default)
Return value: the identifier of the new Peer Connection or a negative error code.
The Peer Connection must be deleted with `rtcDeletePeerConnection`.
The format of each entry in `iceServers` must match the format `[("stun"|"turn"|"turns") ":"][login ":" password "@"]hostname[":" port]["?transport=" ("udp"|"tcp"|"tls")]`. The default scheme is STUN, the default port is 3478 (5349 over TLS), and the default transport is UDP. For instance, a STUN server URI could be `mystunserver.org`, and a TURN server URI could be `turn:myuser:12345678@turnserver.org`. Note transports TCP and TLS are only available for a TURN server with libnice as ICE backend and govern only the TURN control connection, meaning relaying is always performed over UDP.
#### rtcDeletePeerConnection
```
int rtcDeletePeerConnection(int pc)
```
Deletes the specified Peer Connection.
Arguments:
- `pc`: the Peer Connection identifier
Return value: `RTC_ERR_SUCCESS` or a negative error code
After this function has been called, `pc` must not be used in a function call anymore. This function will block until all scheduled callbacks of `pc` return (except the one this function might be called in) and no other callback will be called for `pc` after it returns.
#### rtcSetXCallback
These functions set, change, or unset (if `cb` is `NULL`) the different callbacks of a Peer Connection.
```
int rtcSetLocalDescriptionCallback(int pc, rtcDescriptionCallbackFunc cb)*
```
`cb` must have the following signature: `void myDescriptionCallback(int pc, const char *sdp, const char *type, void *user_ptr)`
```
int rtcSetLocalCandidateCallback(int pc, rtcCandidateCallbackFunc cb)
```
`cb` must have the following signature: `void myCandidateCallback(int pc, const char *cand, const char *mid, void *user_ptr)`
```
int rtcSetStateChangeCallback(int pc, rtcStateChangeCallbackFunc cb)
```
`cb` must have the following signature: `void myStateChangeCallback(int pc, rtcState state, void *user_ptr)`
`state` will be one of the following: `RTC_CONNECTING`, `RTC_CONNECTED`, `RTC_DISCONNECTED`, `RTC_FAILED`, or `RTC_CLOSED`.
```
int rtcSetGatheringStateChangeCallback(int pc, rtcGatheringStateCallbackFunc cb)
```
`void myGatheringStateCallback(int pc, rtcGatheringState state, void *user_ptr)`
`state` will be `RTC_GATHERING_INPROGRESS` or `RTC_GATHERING_COMPLETE`.
```
int rtcSetDataChannelCallback(int pc, rtcDataChannelCallbackFunc cb)
```
`cb` must have the following signature: `void myDataChannelCallback(int pc, int dc, void *user_ptr)`
```
int rtcSetTrackCallback(int pc, rtcTrackCallbackFunc cb)
```
`cb` must have the following signature: `void myTrackCallback(int pc, int tr, void *user_ptr)`
#### rtcSetLocalDescription
```
int rtcSetLocalDescription(int pc, const char *type)
```
Initiates the handshake process. Following this call, the local description callback will be called with the local description, which must be sent to the remote peer by the user's method of choice. Note this call is implicit after `rtcSetRemoteDescription` and `rtcCreateDataChannel` if `disableAutoNegotiation` was not set on Peer Connection creation.
Arguments:
- `pc`: the Peer Connection identifier
- `type` (optional): type of the description ("offer", "answer", "pranswer", or "rollback") or NULL for autodetection.
#### rtcSetRemoteDescription
```
int rtcSetRemoteDescription(int pc, const char *sdp, const char *type)
```
Sets the remote description received from the remote peer by the user's method of choice. The remote description may have candidates or not.
Arguments:
- `pc`: the Peer Connection identifier
- `type` (optional): type of the description ("offer", "answer", "pranswer", or "rollback") or NULL for autodetection.
If the remote description is an offer and `disableAutoNegotiation` was not set in `rtcConfiguration`, the library will automatically answer by calling `rtcSetLocalDescription` internally. Otherwise, the user must call it to answer the remote description.
#### rtcAddRemoteCandidate
```
int rtcAddRemoteCandidate(int pc, const char *cand, const char *mid)
```
Adds a trickled remote candidate received from the remote peer by the user's method of choice.
Arguments:
- `pc`: the Peer Connection identifier
- `cand`: a null-terminated SDP string representing the candidate (with or without the `"a="` prefix)
- `mid` (optional): a null-terminated string representing the mid of the candidate in the remote SDP description or NULL for autodetection
The Peer Connection must have a remote description set.
Return value: `RTC_ERR_SUCCESS` or a negative error code
#### rtcGetLocalDescription
```
int rtcGetLocalDescription(int pc, char *buffer, int size)
```
Retrieves the current local description in SDP format.
Arguments:
- `pc`: the Peer Connection identifier
- `buffer`: a user-supplied buffer to store the description
- `size`: the size of `buffer`
Return value: the length of the string copied in buffer (including the terminating null character) or a negative error code
If `buffer` is `NULL`, the description is not copied but the size is still returned.
#### rtcGetRemoteDescription
```
int rtcGetRemoteDescription(int pc, char *buffer, int size)
```
Retrieves the current remote description in SDP format.
Arguments:
- `pc`: the Peer Connection identifier
- `buffer`: a user-supplied buffer to store the description
- `size`: the size of `buffer`
Return value: the length of the string copied in buffer (including the terminating null character) or a negative error code
If `buffer` is `NULL`, the description is not copied but the size is still returned.
#### rtcGetLocalDescriptionType
```
int rtcGetLocalDescriptionType(int pc, char *buffer, int size)
```
Retrieves the current local description type as string.
Arguments:
- `pc`: the Peer Connection identifier
- `buffer`: a user-supplied buffer to store the type
- `size`: the size of `buffer`
Return value: the length of the string copied in buffer (including the terminating null character) or a negative error code
If `buffer` is `NULL`, the description is not copied but the size is still returned.
#### rtcGetRemoteDescription
```
int rtcGetRemoteDescriptionType(int pc, char *buffer, int size)
```
Retrieves the current remote description type as string.
Arguments:
- `pc`: the Peer Connection identifier
- `buffer`: a user-supplied buffer to store the type
- `size`: the size of `buffer`
Return value: the length of the string copied in buffer (including the terminating null character) or a negative error code
If `buffer` is `NULL`, the description is not copied but the size is still returned.
#### rtcGetLocalAddress
```
int rtcGetLocalAddress(int pc, char *buffer, int size)
```
Retrieves the current local address, i.e. the network address of the currently selected local candidate. The address will have the format `"IP_ADDRESS:PORT"`, where `IP_ADDRESS` may be either IPv4 or IPv6. The call might fail if the PeerConnection is not in state `RTC_CONNECTED`, and the address might change if the state is not `RTC_COMPLETED`.
Arguments:
- `pc`: the Peer Connection identifier
- `buffer`: a user-supplied buffer to store the address
- `size`: the size of `buffer`
Return value: the length of the string copied in buffer (including the terminating null character) or a negative error code
If `buffer` is `NULL`, the address is not copied but the size is still returned.
#### rtcGetRemoteAddress
```
int rtcGetRemoteAddress(int pc, char *buffer, int size)
```
Retrieves the current remote address, i.e. the network address of the currently selected remote candidate. The address will have the format `"IP_ADDRESS:PORT"`, where `IP_ADDRESS` may be either IPv4 or IPv6. The call may fail if the state is not `RTC_CONNECTED`, and the address might change if the state is not `RTC_COMPLETED`.
Arguments:
- `pc`: the Peer Connection identifier
- `buffer`: a user-supplied buffer to store the address
- `size`: the size of `buffer`
Return value: the length of the string copied in buffer (including the terminating null character) or a negative error code
If `buffer` is `NULL`, the address is not copied but the size is still returned.
#### rtcGetSelectedCandidatePair
```
int rtcGetSelectedCandidatePair(int pc, char *local, int localSize, char *remote, int remoteSize)
```
Retrieve the currently selected candidate pair. The call may fail if the state is not `RTC_CONNECTED`, and the selected candidate pair might change if the state is not `RTC_COMPLETED`.
Arguments:
- `pc`: the Peer Connection identifier
- `local`: a user-supplied buffer to store the local candidate
- `localSize`: the size of `local`
- `remote`: a user-supplied buffer to store the remote candidate
- `remoteSize`: the size of `remote`
Return value: the maximun length of strings copied in buffers (including the terminating null character) or a negative error code
If `local`, `remote`, or both, are `NULL`, the corresponding candidate is not copied, but the maximum length is still returned.
### Data Channel
#### rtcCreateDataChannel
```
int rtcCreateDataChannel(int pc, const char *label)
int rtcCreateDataChannelEx(int pc, const char *label, const rtcDataChannelInit *init)
typedef struct {
bool unordered;
bool unreliable;
unsigned int maxPacketLifeTime;
unsigned int maxRetransmits;
} rtcReliability;
typedef struct {
rtcReliability reliability;
const char *protocol;
bool negotiated;
bool manualStream;
uint16_t stream;
} rtcDataChannelInit;
```
Adds a Data Channel on a Peer Connection. The Peer Connection does not need to be connected, however, the Data Channel will be open only when the Peer Connection is connected.
Arguments:
- `pc`: identifier of the PeerConnection on which to add a Data Channel
- `label`: a user-defined UTF-8 string representing the Data Channel name
- `init`: a structure of initialization settings containing:
- `reliability`: a structure of reliability settings containing:
- `bool unordered`: if `true`, the Data Channel will not enforce message ordering, else it will be ordered
- `bool unreliable`: if `true`, the Data Channel will not enforce strict reliability, else it will be reliable
- `unsigned int maxPacketLifeTime`: if unreliable, maximum packet life time in milliseconds
- `unsigned int maxRetransmits`: if unreliable and maxPacketLifeTime is 0, maximum number of retransmissions (0 means no retransmission)
- `protocol` (optional): a user-defined UTF-8 string representing the Data Channel protocol, empty if NULL
- `negotiated`: if `true`, the Data Channel is assumed to be negotiated by the user and won't be negotiated by the WebRTC layer
- `manualStream`: if `true`, the Data Channel will use `stream` as stream ID, else an available id is automatically selected
- `stream` (0-65534): if `manualStream` is `true`, the Data Channel will use it as stream ID, else it is ignored
`rtcDataChannel()` is equivalent to `rtcDataChannelEx()` with settings set to ordered, reliable, non-negotiated, with automatic stream ID selection (all flags set to `false`), and `protocol` set to an empty string.
Return value: the identifier of the new Data Channel or a negative error code.
The Data Channel must be deleted with `rtcDeleteDataChannel`.
If `disableAutoNegotiation` was not set in `rtcConfiguration`, the library will automatically initiate the negotiation by calling `rtcSetLocalDescription` internally. Otherwise, the user must call `rtcSetLocalDescription` to initiate the negotiation after creating the first Data Channel.
#### rtcDeleteDataChannel
```
int rtcDeleteDataChannel(int dc)
```
Deletes a Data Channel.
Arguments:
- `dc`: the Data Channel identifier
After this function has been called, `dc` must not be used in a function call anymore. This function will block until all scheduled callbacks of `dc` return (except the one this function might be called in) and no other callback will be called for `dc` after it returns.
#### rtcGetDataChannelStream
```
int rtcGetDataChannelStream(int dc)
```
Retrieves the stream ID of the Data Channel.
Arguments:
- `dc`: the Data Channel identifier
Return value: the stream ID (0-65534) or a negative error code
#### rtcGetDataChannelLabel
```
int rtcGetDataChannelLabel(int dc, char *buffer, int size)
```
Retrieves the label of a Data Channel.
Arguments:
- `dc`: the Data Channel identifier
- `buffer`: a user-supplied buffer to store the label
- `size`: the size of `buffer`
Return value: the length of the string copied in buffer (including the terminating null character) or a negative error code
If `buffer` is `NULL`, the label is not copied but the size is still returned.
#### rtcGetDataChannelProtocol
```
int rtcGetDataChannelProtocol(int dc, char *buffer, int size)
```
Retrieves the protocol of a Data Channel.
Arguments:
- `dc`: the Data Channel identifier
- `buffer`: a user-supplied buffer to store the protocol
- `size`: the size of `buffer`
Return value: the length of the string copied in buffer (including the terminating null character) or a negative error code
If `buffer` is `NULL`, the protocol is not copied but the size is still returned.
#### rtcGetDataChannelReliability
```
int rtcGetDataChannelReliability(int dc, rtcReliability *reliability)
```
Retrieves the reliability settings of a Data Channel. The function may be called irrelevant of how the Data Channel was created.
Arguments:
- `dc`: the Data Channel identifier
- `reliability` a user-supplied structure to fill
Return value: `RTC_ERR_SUCCESS` or a negative error code
### Track
#### rtcAddTrack
```
int rtcAddTrack(int pc, const char *mediaDescriptionSdp)
```
Adds a new Track on a Peer Connection. The Peer Connection does not need to be connected, however, the Track will be open only when the Peer Connection is connected.
Arguments:
- `pc`: the Peer Connection identifier
- `mediaDescriptionSdp`: a null-terminated string specifying the corresponding media SDP. It must start with a m-line and include a mid parameter.
Return value: the identifier of the new Track or a negative error code
The new track must be deleted with `rtcDeleteTrack`.
The user must call `rtcSetLocalDescription` to negotiate the track.
#### rtcDeleteTrack
```
int rtcDeleteTrack(int tr)
```
Deletes a Track.
Arguments:
- `tr`: the Track identifier
After this function has been called, `tr` must not be used in a function call anymore. This function will block until all scheduled callbacks of `tr` return (except the one this function might be called in) and no other callback will be called for `tr` after it returns.
#### rtcGetTrackDescription
```
int rtcGetTrackDescription(int tr, char *buffer, int size)
```
Retrieves the SDP media description of a Track.
Arguments:
- `dc`: the Track identifier
- `buffer`: a user-supplied buffer to store the description
- `size`: the size of `buffer`
Return value: the length of the string copied in buffer (including the terminating null character) or a negative error code
If `buffer` is `NULL`, the description is not copied but the size is still returned.
### WebSocket
#### rtcCreateWebSocket
```
int rtcCreateWebSocket(const char *url)
int rtcCreateWebSocketEx(const char *url, const rtcWsConfiguration *config)
```
Creates a new client WebSocket.
Arguments:
- `url`: a null-terminated string representing the fully-qualified URL to open.
- `config`: a structure with the following parameters:
- `bool disableTlsVerification`: if true, don't verify the TLS certificate, else try to verify it if possible
Return value: the identifier of the new WebSocket or a negative error code
The new WebSocket must be deleted with `rtcDeleteWebSocket`. The scheme of the URL must be either `ws` or `wss`.
#### rtcDeleteWebSocket
```
int rtcDeleteWebSocket(int ws)
```
Arguments:
- `ws`: the identifier of the WebSocket to delete
Return value: the identifier of the new WebSocket or a negative error code
After this function has been called, `ws` must not be used in a function call anymore. This function will block until all scheduled callbacks of `ws` return (except the one this function might be called in) and no other callback will be called for `ws` after it returns.
### Channel (Data Channel, Track, and WebSocket)
The following common functions might be called with a generic channel identifier. It may be the identifier of either a Data Channel, a Track, or a WebSocket.
#### rtcSetXCallback
These functions set, change, or unset (if `cb` is `NULL`) the different callbacks of a channel.
```
int rtcSetOpenCallback(int id, rtcOpenCallbackFunc cb)
```
`cb` must have the following signature: `void myOpenCallback(int id, void *user_ptr)`
```
int rtcSetClosedCallback(int id, rtcClosedCallbackFunc cb)
```
`cb` must have the following signature: `void myClosedCallback(int id, void *user_ptr)`
```
int rtcSetErrorCallback(int id, rtcErrorCallbackFunc cb)
```
`cb` must have the following signature: `void myErrorCallback(int id, const char *error, void *user_ptr)`
```
int rtcSetMessageCallback(int id, rtcMessageCallbackFunc cb)
```
`cb` must have the following signature: `void myMessageCallback(int id, const char *message, int size, void *user_ptr)`
```
int rtcSetBufferedAmountLowCallback(int id, rtcBufferedAmountLowCallbackFunc cb)
```
`cb` must have the following signature: `void myBufferedAmountLowCallback(int id, void *user_ptr)`
```
int rtcSetAvailableCallback(int id, rtcAvailableCallbackFunc cb)
```
`cb` must have the following signature: `void myAvailableCallback(int id, void *user_ptr)`
#### rtcSendMessage
```
int rtcSendMessage(int id, const char *data, int size)
```
Arguments:
- `id`: the channel identifier
- `data`: the message data
- `size`: if size >= 0, `data` is interpreted as a binary message of length `size`, otherwise it is interpreted as a null-terminated UTF-8 string.
Return value: `RTC_ERR_SUCCESS` or a negative error code
Sends a message immediately if possible.
Data Channel and WebSocket: If the message may not be sent immediately due to flow control or congestion control, it is buffered until it can actually be sent. You can retrieve the current buffered data size with `rtcGetBufferedAmount`.
Tracks are an exception: There is no flow or congestion control, messages are never buffered and `rtcGetBufferedAmount` always returns 0.
#### rtcGetBufferedAmount
```
int rtcGetBufferedAmount(int id)
```
Retrieves the current buffered amount, i.e. the total size of currently buffered messages waiting to be actually sent in the channel. This does not account for the data buffered at the transport level.
Return value: the buffered amount or a negative error code
#### rtcGetBufferedAmountLowThreshold
```
int rtcSetBufferedAmountLowThreshold(int id, int amount)
```
Changes the buffered amount threshold under which `BufferedAmountLowCallback` is called. The callback is called when the buffered amount was strictly superior and gets equal to or lower than the threshold when a message is sent. The initial threshold is 0, meaning the the callback is called each time the buffered amount goes back to zero after being non-zero.
Arguments:
- `id`: the channel identifier
- `amount`: the new buffer level threshold
Return value: the identifier of the new WebSocket or a negative error code
#### rtcReceiveMessage
```
int rtcReceiveMessage(int id, char *buffer, int *size)
```
Receives a pending message if possible. The function may only be called if `MessageCallback` is not set.
Arguments:
- `id`: the channel identifier
- `buffer`: a user-supplied buffer where to write the message data
- `size`: a pointer to a user-supplied int which must be initialized to the size of `buffer`. On success, the function will write the size of the message to it before returning.
Return value: `RTC_ERR_SUCCESS` or a negative error code (In particular, `RTC_ERR_NOT_AVAIL` is returned when there are no pending messages)
If `buffer` is `NULL`, the message is not copied and kept pending but the size is still written to `size`.
#### rtcGetAvailableAmount
```
int rtcGetAvailableAmount(int id)
```
Retrieves the available amount, i.e. the total size of messages pending reception with `rtcReceiveMessage`. The function may only be called if `MessageCallback` is not set.
Arguments:
- `id`: the channel identifier
Return value: the available amount or a negative error code

View File

@ -12,12 +12,9 @@ feature.compose <gnutls>on
lib libdatachannel
: # sources
[ glob ./src/*.cpp ]
[ glob ./src/impl/*.cpp ]
: # requirements
<cxxstd>17
<include>./include
<include>./include/rtc
<include>./src
<define>RTC_ENABLE_MEDIA=0
<define>RTC_ENABLE_WEBSOCKET=0
<define>USE_NICE=0
@ -146,7 +143,7 @@ rule make_libjuice_openssl ( targets * : sources * : properties * )
{
# on macOS, default to pick up openssl from the homebrew installation
# brew install openssl
OPENSSL_INCLUDE = /opt/homebrew/opt/openssl /usr/local/opt/openssl/include ;
OPENSSL_INCLUDE = /usr/local/opt/openssl/include ;
}
if $(OPENSSL_INCLUDE) != ""
@ -194,7 +191,7 @@ rule openssl-lib-path ( properties * )
{
# on macOS, default to pick up openssl from the homebrew installation
# brew install openssl
OPENSSL_LIB = /opt/homebrew/opt/openssl/lib /usr/local/opt/openssl/lib ;
OPENSSL_LIB = /usr/local/opt/openssl/lib ;
}
else if <target-os>windows in $(properties) && $(OPENSSL_LIB) = ""
{
@ -220,7 +217,7 @@ rule openssl-include-path ( properties * )
{
# on macOS, default to pick up openssl from the homebrew installation
# brew install openssl
OPENSSL_INCLUDE = /opt/homebrew/opt/openssl/include /usr/local/opt/openssl/include ;
OPENSSL_INCLUDE = /usr/local/opt/openssl/include ;
}
else if <target-os>windows in $(properties) && $(OPENSSL_INCLUDE) = ""
{

View File

@ -10,11 +10,10 @@ LDFLAGS=-pthread
LIBS=
LOCALLIBS=libusrsctp.a
USRSCTP_DIR=deps/usrsctp
SRTP_DIR=deps/libsrtp
JUICE_DIR=deps/libjuice
PLOG_DIR=deps/plog
INCLUDES=-Isrc -Iinclude/rtc -Iinclude -I$(PLOG_DIR)/include -I$(USRSCTP_DIR)/usrsctplib
INCLUDES=-Iinclude/rtc -I$(PLOG_DIR)/include -I$(USRSCTP_DIR)/usrsctplib
LDLIBS=
USE_GNUTLS ?= 0
@ -39,22 +38,15 @@ ifneq ($(USE_GNUTLS), 0)
endif
endif
NO_MEDIA ?= 0
USE_SYSTEM_SRTP ?= 0
ifeq ($(NO_MEDIA), 0)
USE_SRTP ?= 0
ifneq ($(USE_SRTP), 0)
CPPFLAGS+=-DRTC_ENABLE_MEDIA=1
ifneq ($(USE_SYSTEM_SRTP), 0)
CPPFLAGS+=-DRTC_SYSTEM_SRTP=1
LIBS+=srtp
else
CPPFLAGS+=-DRTC_SYSTEM_SRTP=0
INCLUDES+=-I$(SRTP_DIR)/include
LOCALLIBS+=libsrtp2.a
endif
else
CPPFLAGS+=-DRTC_ENABLE_MEDIA=0
endif
NO_WEBSOCKET ?= 0
ifeq ($(NO_WEBSOCKET), 0)
CPPFLAGS+=-DRTC_ENABLE_WEBSOCKET=1
@ -62,10 +54,10 @@ else
CPPFLAGS+=-DRTC_ENABLE_WEBSOCKET=0
endif
INCLUDES+=$(if $(LIBS),$(shell pkg-config --cflags $(LIBS)),)
LDLIBS+=$(LOCALLIBS) $(if $(LIBS),$(shell pkg-config --libs $(LIBS)),)
INCLUDES+=$(shell pkg-config --cflags $(LIBS))
LDLIBS+=$(LOCALLIBS) $(shell pkg-config --libs $(LIBS))
SRCS=$(shell printf "%s " src/*.cpp src/impl/*.cpp)
SRCS=$(shell printf "%s " src/*.cpp)
OBJS=$(subst .cpp,.o,$(SRCS))
TEST_SRCS=$(shell printf "%s " test/*.cpp)
@ -81,7 +73,7 @@ test/%.o: test/%.cpp
-include $(subst .cpp,.d,$(SRCS))
$(NAME).a: $(LOCALLIBS) $(OBJS)
$(NAME).a: $(OBJS)
$(AR) crf $@ $(OBJS)
$(NAME).so: $(LOCALLIBS) $(OBJS)
@ -105,22 +97,15 @@ dist-clean: clean
-$(RM) src/*~
-$(RM) test/*~
-cd $(USRSCTP_DIR) && make clean
-cd $(SRTP_DIR) && make clean
-cd $(JUICE_DIR) && make clean
libusrsctp.a:
cd $(USRSCTP_DIR) && \
./bootstrap && \
./configure --enable-static --disable-debug CFLAGS="-fPIC" && \
./configure --enable-static --disable-debug CFLAGS="$(CPPFLAGS) -Wno-error=format-truncation" && \
make
cp $(USRSCTP_DIR)/usrsctplib/.libs/libusrsctp.a .
libsrtp2.a:
cd $(SRTP_DIR) && \
./configure && \
make
cp $(SRTP_DIR)/libsrtp2.a .
libjuice.a:
ifneq ($(USE_GNUTLS), 0)
cd $(JUICE_DIR) && make USE_NETTLE=1

318
README.md
View File

@ -1,148 +1,38 @@
# libdatachannel - C/C++ WebRTC Data Channels
libdatachannel is a standalone implementation of WebRTC Data Channels, WebRTC Media Transport, and WebSockets in C++17 with C bindings for POSIX platforms (including GNU/Linux, Android, and Apple macOS) and Microsoft Windows.
The library aims at being both straightforward and lightweight with minimal external dependencies, to enable direct connectivity between native applications and web browsers without the pain of importing Google's bloated [reference library](https://webrtc.googlesource.com/src/). The interface consists of somewhat simplified versions of the JavaScript WebRTC and WebSocket APIs present in browsers, in order to ease the design of cross-environment applications.
libdatachannel is a standalone implementation of WebRTC Data Channels, WebRTC Media Transport, and WebSockets in C++17 with C bindings for POSIX platforms (including GNU/Linux, Android, and Apple macOS) and Microsoft Windows. It enables direct connectivity between native applications and web browsers without the pain of importing the entire WebRTC stack. The interface consists of simplified versions of the JavaScript WebRTC and WebSocket APIs present in browsers, in order to ease the design of cross-environment applications.
It can be compiled with multiple backends:
- The security layer can be provided through [OpenSSL](https://www.openssl.org/) or [GnuTLS](https://www.gnutls.org/).
- The connectivity for WebRTC can be provided through my ad-hoc ICE library [libjuice](https://github.com/paullouisageneau/libjuice) as submodule or through [libnice](https://github.com/libnice/libnice).
The WebRTC stack is fully compatible with Firefox and Chromium, see [Compatibility](#Compatibility) below.
This projet is originally inspired by [librtcdcpp](https://github.com/chadnickbok/librtcdcpp), however it is a complete rewrite from scratch, because the messy architecture of librtcdcpp made solving its implementation issues difficult.
Licensed under LGPLv2, see [LICENSE](https://github.com/paullouisageneau/libdatachannel/blob/master/LICENSE).
## Dependencies
Only [GnuTLS](https://www.gnutls.org/) or [OpenSSL](https://www.openssl.org/) are necessary. Optionally, [libnice](https://nice.freedesktop.org/) can be selected as an alternative ICE backend instead of libjuice.
Submodules:
- libjuice: https://github.com/paullouisageneau/libjuice
- usrsctp: https://github.com/sctplab/usrsctp
- libsrtp: https://github.com/cisco/libsrtp (if compiled with media support)
## Building
See [BUILDING.md](https://github.com/paullouisageneau/libdatachannel/blob/master/BUILDING.md) for building instructions.
## Examples
See [examples](https://github.com/paullouisageneau/libdatachannel/blob/master/examples/) for complete usage examples with signaling server (under GPLv2).
Additionnaly, you might want to have a look at the [C API documentation](https://github.com/paullouisageneau/libdatachannel/blob/master/DOC.md).
### Signal a PeerConnection
```cpp
#include "rtc/rtc.hpp"
```
```cpp
rtc::Configuration config;
config.iceServers.emplace_back("mystunserver.org:3478");
rtc::PeerConection pc(config);
pc.onLocalDescription([](rtc::Description sdp) {
// Send the SDP to the remote peer
MY_SEND_DESCRIPTION_TO_REMOTE(string(sdp));
});
pc.onLocalCandidate([](rtc::Candidate candidate) {
// Send the candidate to the remote peer
MY_SEND_CANDIDATE_TO_REMOTE(candidate.candidate(), candidate.mid());
});
MY_ON_RECV_DESCRIPTION_FROM_REMOTE([&pc](string sdp) {
pc.setRemoteDescription(rtc::Description(sdp));
});
MY_ON_RECV_CANDIDATE_FROM_REMOTE([&pc](string candidate, string mid) {
pc.addRemoteCandidate(rtc::Candidate(candidate, mid));
});
```
### Observe the PeerConnection state
```cpp
pc.onStateChange([](rtc::PeerConnection::State state) {
std::cout << "State: " << state << std::endl;
});
pc.onGatheringStateChange([](rtc::PeerConnection::GatheringState state) {
std::cout << "Gathering state: " << state << std::endl;
});
```
### Create a DataChannel
```cpp
auto dc = pc.createDataChannel("test");
dc->onOpen([]() {
std::cout << "Open" << std::endl;
});
dc->onMessage([](std::variant<binary, string> message) {
if (std::holds_alternative<string>(message)) {
std::cout << "Received: " << get<string>(message) << std::endl;
}
});
```
### Receive a DataChannel
```cpp
std::shared_ptr<rtc::DataChannel> dc;
pc.onDataChannel([&dc](std::shared_ptr<rtc::DataChannel> incoming) {
dc = incoming;
dc->send("Hello world!");
});
```
### Open a WebSocket
```cpp
rtc::WebSocket ws;
ws.onOpen([]() {
std::cout << "WebSocket open" << std::endl;
});
ws.onMessage([](std::variant<binary, string> message) {
if (std::holds_alternative<string>(message)) {
std::cout << "WebSocket received: " << std::get<string>(message) << endl;
}
});
ws.open("wss://my.websocket/service");
```
## Compatibility
The library implements the following communication protocols:
The library aims at implementing the following communication protocols:
### WebRTC Data Channels and Media Transport
The library implements WebRTC Peer Connections with both Data Channels and Media Transport. Media transport is optional and can be disabled at compile time.
The WebRTC stack has been tested to be compatible with Firefox and Chromium.
Protocol stack:
- SCTP-based Data Channels ([RFC8831](https://tools.ietf.org/html/rfc8831))
- SRTP-based Media Transport ([RFC8834](https://tools.ietf.org/html/rfc8834))
- SCTP-based Data Channels ([draft-ietf-rtcweb-data-channel-13](https://tools.ietf.org/html/draft-ietf-rtcweb-data-channel-13))
- SRTP-based Media Transport ([draft-ietf-rtcweb-rtp-usage-26](https://tools.ietf.org/html/draft-ietf-rtcweb-rtp-usage-26))
- DTLS/UDP ([RFC7350](https://tools.ietf.org/html/rfc7350) and [RFC8261](https://tools.ietf.org/html/rfc8261))
- ICE ([RFC8445](https://tools.ietf.org/html/rfc8445)) with STUN ([RFC8489](https://tools.ietf.org/html/rfc8489)) and its extension TURN ([RFC8656](https://tools.ietf.org/html/rfc8656))
- ICE ([RFC8445](https://tools.ietf.org/html/rfc8445)) with STUN ([RFC5389](https://tools.ietf.org/html/rfc5389))
Features:
- Full IPv6 support (as mandated by [RFC8835](https://tools.ietf.org/html/rfc8835))
- Trickle ICE ([RFC8838](https://tools.ietf.org/html/rfc8838))
- JSEP-compatible session establishment with SDP ([RFC8829](https://tools.ietf.org/html/rfc8829))
- SCTP over DTLS with SDP offer/answer ([RFC8841](https://tools.ietf.org/html/rfc8841))
- DTLS with ECDSA or RSA keys ([RFC8824](https://tools.ietf.org/html/rfc8827))
- SRTP and SRTCP key derivation from DTLS ([RFC5764](https://tools.ietf.org/html/rfc5764))
- Full IPv6 support
- Trickle ICE ([draft-ietf-ice-trickle-21](https://tools.ietf.org/html/draft-ietf-ice-trickle-21))
- JSEP compatible ([draft-ietf-rtcweb-jsep-26](https://tools.ietf.org/html/draft-ietf-rtcweb-jsep-26))
- Multicast DNS candidates ([draft-ietf-rtcweb-mdns-ice-candidates-04](https://tools.ietf.org/html/draft-ietf-rtcweb-mdns-ice-candidates-04))
- SRTP and SRTCP key derivation from DTLS ([RFC5764](https://tools.ietf.org/html/rfc5764))
- Differentiated Services QoS ([draft-ietf-tsvwg-rtcweb-qos-18](https://tools.ietf.org/html/draft-ietf-tsvwg-rtcweb-qos-18))
- TURN relaying ([RFC5766](https://tools.ietf.org/html/rfc5766)) with [libnice](https://github.com/libnice/libnice) as ICE backend
Note only SDP BUNDLE mode is supported for media multiplexing ([RFC8843](https://tools.ietf.org/html/rfc8843)). The behavior is equivalent to the JSEP bundle-only policy: the library always negociates one unique network component, where SRTP media streams are multiplexed with SRTCP control packets ([RFC5761](https://tools.ietf.org/html/rfc5761)) and SCTP/DTLS data traffic ([RFC8261](https://tools.ietf.org/html/rfc8261)).
Note only SDP BUNDLE mode is supported for media multiplexing ([draft-ietf-mmusic-sdp-bundle-negotiation-54](https://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-54)). The behavior is equivalent to the JSEP bundle-only policy: the library always negociates one unique network component, where SRTP media streams are multiplexed with SRTCP control packets ([RFC5761](https://tools.ietf.org/html/rfc5761)) and SCTP/DTLS data traffic ([RFC5764](https://tools.ietf.org/html/rfc5764)).
### WebSocket
@ -156,13 +46,187 @@ Features:
- IPv6 and IPv4/IPv6 dual-stack support
- Keepalive with ping/pong
## Dependencies
Dependencies:
- GnuTLS: https://www.gnutls.org/ or OpenSSL: https://www.openssl.org/
Submodules:
- libjuice: https://github.com/paullouisageneau/libjuice
- usrsctp: https://github.com/sctplab/usrsctp
- libsrtp: https://github.com/cisco/libsrtp
Optional dependencies:
- libnice: https://nice.freedesktop.org/ (if selected as ICE backend instead of libjuice)
- libsrtp: https://github.com/cisco/libsrtp (if selected instead of the submodule)
## Building
### Clone repository and submodules
```bash
$ git clone https://github.com/paullouisageneau/libdatachannel.git
$ cd libdatachannel
$ git submodule update --init --recursive
```
### Building with CMake
The CMake library targets `libdatachannel` and `libdatachannel-static` respectively correspond to the shared and static libraries. The default target will build tests and examples. The option `USE_GNUTLS` allows to switch between OpenSSL (default) and GnuTLS, and the option `USE_NICE` allows to switch between libjuice as submodule (default) and libnice.
On Windows, the DLL resulting from the shared library build only exposes the C API, use the static library for the C++ API.
#### POSIX-compliant operating systems (including Linux and Apple macOS)
```bash
$ cmake -B build -DUSE_GNUTLS=1 -DUSE_NICE=0
$ cd build
$ make -j2
```
#### Apple macOS with XCode project
```bash
$ cmake -B "$BUILD_DIR" -DUSE_GNUTLS=0 -DUSE_NICE=0 -G Xcode
```
Xcode project is generated in *build/* directory.
##### Solving **Could NOT find OpenSSL** error
You need to add OpenSSL root directory if your build fails with the following message:
```
Could NOT find OpenSSL, try to set the path to OpenSSL root folder in the
system variable OPENSSL_ROOT_DIR (missing: OPENSSL_CRYPTO_LIBRARY
OPENSSL_INCLUDE_DIR)
```
for example:
```bash
$ cmake -B build -DUSE_GNUTLS=0 -DUSE_NICE=0 -G Xcode -DOPENSSL_ROOT_DIR=/usr/local/Cellar/openssl\@1.1/1.1.1h/
```
#### Microsoft Windows with MinGW cross-compilation
```bash
$ cmake -B build -DCMAKE_TOOLCHAIN_FILE=/usr/share/mingw/toolchain-x86_64-w64-mingw32.cmake # replace with your toolchain file
$ cd build
$ make -j2
```
#### Microsoft Windows with Microsoft Visual C++
```bash
$ cmake -B build -G "NMake Makefiles"
$ cd build
$ nmake
```
### Building directly with Make (Linux only)
The option `USE_GNUTLS` allows to switch between OpenSSL (default) and GnuTLS, and the option `USE_NICE` allows to switch between libjuice as submodule (default) and libnice.
```bash
$ make USE_GNUTLS=1 USE_NICE=0
```
## Examples
See [examples](https://github.com/paullouisageneau/libdatachannel/blob/master/examples/) for a complete usage example with signaling server (under GPLv2).
Additionnaly, you might want to have a look at the [C API](https://github.com/paullouisageneau/libdatachannel/blob/master/include/rtc/rtc.h).
### Signal a PeerConnection
```cpp
#include "rtc/rtc.hpp"
```
```cpp
rtc::Configuration config;
config.iceServers.emplace_back("mystunserver.org:3478");
auto pc = make_shared<rtc::PeerConnection>(config);
pc->onLocalDescription([](rtc::Description sdp) {
// Send the SDP to the remote peer
MY_SEND_DESCRIPTION_TO_REMOTE(string(sdp));
});
pc->onLocalCandidate([](rtc::Candidate candidate) {
// Send the candidate to the remote peer
MY_SEND_CANDIDATE_TO_REMOTE(candidate.candidate(), candidate.mid());
});
MY_ON_RECV_DESCRIPTION_FROM_REMOTE([pc](string sdp) {
pc->setRemoteDescription(rtc::Description(sdp));
});
MY_ON_RECV_CANDIDATE_FROM_REMOTE([pc](string candidate, string mid) {
pc->addRemoteCandidate(rtc::Candidate(candidate, mid));
});
```
### Observe the PeerConnection state
```cpp
pc->onStateChange([](PeerConnection::State state) {
cout << "State: " << state << endl;
});
pc->onGatheringStateChange([](PeerConnection::GatheringState state) {
cout << "Gathering state: " << state << endl;
});
```
### Create a DataChannel
```cpp
auto dc = pc->createDataChannel("test");
dc->onOpen([]() {
cout << "Open" << endl;
});
dc->onMessage([](variant<binary, string> message) {
if (holds_alternative<string>(message)) {
cout << "Received: " << get<string>(message) << endl;
}
});
```
### Receive a DataChannel
```cpp
shared_ptr<rtc::DataChannel> dc;
pc->onDataChannel([&dc](shared_ptr<rtc::DataChannel> incoming) {
dc = incoming;
dc->send("Hello world!");
});
```
### Open a WebSocket
```cpp
auto ws = make_shared<rtc::WebSocket>();
ws->onOpen([]() {
cout << "WebSocket open" << endl;
});
ws->onMessage([](variant<binary, string> message) {
if (holds_alternative<string>(message)) {
cout << "WebSocket received: " << get<string>(message) << endl;
}
});
ws->open("wss://my.websocket/service");
```
## External resources
- Rust wrapper for libdatachannel: [datachannel-rs](https://github.com/lerouxrgd/datachannel-rs)
- Node.js wrapper for libdatachannel: [node-datachannel](https://github.com/murat-dogan/node-datachannel)
- Unity wrapper for Windows 10 and Hololens: [datachannel-unity](https://github.com/hanseuljun/datachannel-unity)
- WebAssembly wrapper compatible with libdatachannel: [datachannel-wasm](https://github.com/paullouisageneau/datachannel-wasm)
## Thanks
Thanks to [Streamr](https://streamr.network/) for sponsoring this work!

2
deps/libjuice vendored

2
deps/plog vendored

Submodule deps/plog updated: d8461e9d47...afb6f6f0e8

2
deps/usrsctp vendored

View File

@ -1,17 +1,13 @@
# libdatachannel - Examples
# Examples for libdatachannel
This directory contains different WebRTC clients and compatible WebSocket + JSON signaling servers.
- [client](client) contains a native client to open Data Channels with WebSocket signaling using libdatachannel
- [client-benchmark](client-benchmark) contains a native client to open Data Channels with WebSocket signaling using libdatachannel and benchmark functionalities. See [client-benchmark/README.md](client-benchmark/README.md) for usage examples.
- [web](web) contains a equivalent JavaScript client for web browsers
- [signaling-server-nodejs](signaling-server-nodejs) contains a signaling server in node.js
- [client](client) uses libdatachannel to implement WebRTC Data Channels with WebSocket signaling
- [web](web) contains an equivalent implementation for web browsers and a node.js signaling server
- [signaling-server-python](signaling-server-python) contains a similar signaling server in Python
- [signaling-server-rust](signaling-server-rust) contains a similar signaling server in Rust (see [lerouxrgd/datachannel-rs](https://github.com/lerouxrgd/datachannel-rs) for Rust wrappers)
- [media](media) is a copy/paste demo to send the webcam from your browser into gstreamer.
- [sfu-media](sfu-media) is a copy/paste SFU demo to relay the webcam between browsers.
- [streamer](streamer) streams h264 and opus samples to web browsers (signaling-server-python is required).
Additionally, it contains two debugging tools for libdatachannel with copy-pasting as signaling:
- [copy-paste](copy-paste) using the C++ API

View File

@ -1,24 +0,0 @@
cmake_minimum_required(VERSION 3.7)
if(POLICY CMP0079)
cmake_policy(SET CMP0079 NEW)
endif()
if(WIN32)
add_executable(datachannel-client-benchmark main.cpp parse_cl.cpp parse_cl.h getopt.cpp getopt.h)
target_compile_definitions(datachannel-client-benchmark PUBLIC STATIC_GETOPT)
else()
add_executable(datachannel-client-benchmark main.cpp parse_cl.cpp parse_cl.h)
endif()
set_target_properties(datachannel-client-benchmark PROPERTIES
CXX_STANDARD 17
OUTPUT_NAME client-benchmark)
target_link_libraries(datachannel-client-benchmark datachannel nlohmann_json)
if(WIN32)
add_custom_command(TARGET datachannel-client-benchmark POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_if_different
"$<TARGET_FILE_DIR:datachannel>/datachannel.dll"
$<TARGET_FILE_DIR:datachannel-client-benchmark>
)
endif()

View File

@ -1,339 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

View File

@ -1,463 +0,0 @@
# libdatachannel - client-benchmark
This directory contains a native client to open Data Channels with WebSocket signaling using libdatachannel and benchmark functionalities. It offers three functionalities;
- Benchmark: Bi-directional data transfer benchmark (Also supports One-Way testing)
- Constant Throughput Set: Send desired amount of data per second
- Multiple Data Channel: Create desried count of data channel
## Start Signaling Server
- Start one of the signaling server from the examples folder. For example start `signaling-server-nodejs` like;
- `cd examples/signaling-server-nodejs/`
- `npm i`
- `npm run start `
## Start `client-benchmark` Applications
Start 2 applications by using example calls below. Then copy one of the client's ID and paste to the other peer's screen to start offering process.
## Usage Examples
### Benchmark for 300 seconds
> `./client-benchmark -d 300`
Example Output (Offering Peer's Output);
```bash
Stun server is stun:stun.l.google.com:19302
The local ID is: H1E3
Url is ws://localhost:8000/H1E3
Waiting for signaling to be connected...
2021-04-10 19:51:31.319 INFO [16449] [rtc::impl::TcpTransport::connect@163] Connected to localhost:8000
2021-04-10 19:51:31.319 INFO [16449] [rtc::impl::TcpTransport::runLoop@331] TCP connected
2021-04-10 19:51:31.321 INFO [16449] [rtc::impl::WsTransport::incoming@118] WebSocket open
WebSocket connected, signaling ready
Enter a remote ID to send an offer:
n790
Offering to n790
Creating DataChannel with label "DC-1"
2021-04-10 19:51:32.464 INFO [16442] [rtc::impl::IceTransport::IceTransport@106] Using STUN server "stun.l.google.com:19302"
2021-04-10 19:51:32.465 INFO [16442] [rtc::impl::PeerConnection::changeSignalingState@1044] Changed signaling state to new
2021-04-10 19:51:32.465 INFO [16442] [rtc::impl::PeerConnection::changeGatheringState@1033] Changed gathering state to in-progress
Gathering State: in-progress
2021-04-10 19:51:32.465 INFO [16442] [rtc::impl::IceTransport::LogCallback@339] juice: agent.c:787: Changing state to gathering
Benchmark will run for 300 seconds
2021-04-10 19:51:32.466 INFO [16450] [rtc::impl::IceTransport::LogCallback@339] juice: agent.c:787: Changing state to connecting
2021-04-10 19:51:32.466 INFO [16450] [rtc::impl::PeerConnection::changeState@1016] Changed state to connecting
State: connecting
2021-04-10 19:51:32.489 INFO [16450] [rtc::impl::IceTransport::LogCallback@339] juice: agent.c:610: Using STUN server stun.l.google.com:19302
2021-04-10 19:51:32.489 INFO [16449] [rtc::impl::PeerConnection::changeSignalingState@1044] Changed signaling state to connecting
2021-04-10 19:51:32.490 INFO [16450] [rtc::impl::IceTransport::LogCallback@339] juice: agent.c:787: Changing state to connected
2021-04-10 19:51:32.491 INFO [16453] [rtc::impl::DtlsTransport::runRecvLoop@503] DTLS handshake finished
2021-04-10 19:51:32.497 INFO [16443] [rtc::impl::SctpTransport::processNotification@713] SCTP connected
2021-04-10 19:51:32.497 INFO [16443] [rtc::impl::PeerConnection::changeState@1016] Changed state to connected
State: connected
DataChannel from n790 open
2021-04-10 19:51:32.542 INFO [16450] [rtc::impl::IceTransport::LogCallback@339] juice: agent.c:1328: STUN server binding successful
2021-04-10 19:51:32.589 INFO [16450] [rtc::impl::IceTransport::LogCallback@339] juice: agent.c:787: Changing state to completed
#1
DC-1 Received: 40789 KB/s Sent: 41180 KB/s BufferSize: 65535
TOTL Received: 40789 KB/s Sent: 41180 KB/s
2021-04-10 19:51:34.039 INFO [16450] [rtc::impl::IceTransport::LogCallback@339] juice: agent.c:843: STUN server binding failed (timeout)
2021-04-10 19:51:34.039 INFO [16450] [rtc::impl::IceTransport::LogCallback@339] juice: agent.c:2206: Candidate gathering done
2021-04-10 19:51:34.039 INFO [16450] [rtc::impl::PeerConnection::changeGatheringState@1033] Changed gathering state to complete
Gathering State: complete
#2
DC-1 Received: 41709 KB/s Sent: 41774 KB/s BufferSize: 65535
TOTL Received: 41709 KB/s Sent: 41774 KB/s
#3
DC-1 Received: 42165 KB/s Sent: 42360 KB/s BufferSize: 65535
TOTL Received: 42165 KB/s Sent: 42360 KB/s
#4
DC-1 Received: 42880 KB/s Sent: 42750 KB/s BufferSize: 65535
TOTL Received: 42880 KB/s Sent: 42750 KB/s
#5
DC-1 Received: 41771 KB/s Sent: 42097 KB/s BufferSize: 65535
TOTL Received: 41771 KB/s Sent: 42097 KB/s
Stats# Received Total: 210 MB Sent Total: 211 MB RTT: 20 ms
#6
DC-1 Received: 46235 KB/s Sent: 30433 KB/s BufferSize: 65535
TOTL Received: 46235 KB/s Sent: 30433 KB/s
#7
DC-1 Received: 47116 KB/s Sent: 28413 KB/s BufferSize: 65535
TOTL Received: 47116 KB/s Sent: 28413 KB/s
#8
DC-1 Received: 46923 KB/s Sent: 32520 KB/s BufferSize: 65535
TOTL Received: 46923 KB/s Sent: 32520 KB/s
#9
DC-1 Received: 44513 KB/s Sent: 34020 KB/s BufferSize: 65535
TOTL Received: 44513 KB/s Sent: 34020 KB/s
#10
DC-1 Received: 41966 KB/s Sent: 36166 KB/s BufferSize: 65535
TOTL Received: 41966 KB/s Sent: 36166 KB/s
Stats# Received Total: 438 MB Sent Total: 373 MB RTT: 19 ms
#11
DC-1 Received: 42617 KB/s Sent: 39619 KB/s BufferSize: 65535
TOTL Received: 42617 KB/s Sent: 39619 KB/s
#12
DC-1 Received: 43792 KB/s Sent: 43338 KB/s BufferSize: 65535
TOTL Received: 43792 KB/s Sent: 43338 KB/s
#13
DC-1 Received: 41715 KB/s Sent: 41585 KB/s BufferSize: 65535
TOTL Received: 41715 KB/s Sent: 41585 KB/s
#14
DC-1 Received: 39860 KB/s Sent: 33822 KB/s BufferSize: 65535
TOTL Received: 39860 KB/s Sent: 33822 KB/s
#15
DC-1 Received: 47576 KB/s Sent: 25352 KB/s BufferSize: 65535
TOTL Received: 47576 KB/s Sent: 25352 KB/s
Stats# Received Total: 655 MB Sent Total: 558 MB RTT: 13 ms
```
### Benchmark for 300 seconds (Only Send, One Way)
Start first peer as;
> `./client-benchmark -d 300 -o`
Start second peer as;
> `./client-benchmark -d 300`
Example Output (Offering Peer's Output);
```bash
Not Sending data. (One way benchmark).
Stun server is stun:stun.l.google.com:19302
The local ID is: 7EaP
Url is ws://localhost:8000/7EaP
Waiting for signaling to be connected...
2021-04-10 19:54:36.857 INFO [16632] [rtc::impl::TcpTransport::connect@163] Connected to localhost:8000
2021-04-10 19:54:36.857 INFO [16632] [rtc::impl::TcpTransport::runLoop@331] TCP connected
2021-04-10 19:54:36.858 INFO [16632] [rtc::impl::WsTransport::incoming@118] WebSocket open
WebSocket connected, signaling ready
Enter a remote ID to send an offer:
UDL4
Offering to UDL4
Creating DataChannel with label "DC-1"
2021-04-10 19:54:53.381 INFO [16625] [rtc::impl::IceTransport::IceTransport@106] Using STUN server "stun.l.google.com:19302"
2021-04-10 19:54:53.382 INFO [16625] [rtc::impl::PeerConnection::changeSignalingState@1044] Changed signaling state to new
2021-04-10 19:54:53.382 INFO [16625] [rtc::impl::PeerConnection::changeGatheringState@1033] Changed gathering state to in-progress
Gathering State: in-progress
2021-04-10 19:54:53.383 INFO [16625] [rtc::impl::IceTransport::LogCallback@339] juice: agent.c:787: Changing state to gathering
Benchmark will run for 300 seconds
2021-04-10 19:54:53.384 INFO [16646] [rtc::impl::IceTransport::LogCallback@339] juice: agent.c:787: Changing state to connecting
2021-04-10 19:54:53.384 INFO [16646] [rtc::impl::PeerConnection::changeState@1016] Changed state to connecting
State: connecting
2021-04-10 19:54:53.475 INFO [16646] [rtc::impl::IceTransport::LogCallback@339] juice: agent.c:610: Using STUN server stun.l.google.com:19302
2021-04-10 19:54:53.475 INFO [16632] [rtc::impl::PeerConnection::changeSignalingState@1044] Changed signaling state to connecting
2021-04-10 19:54:53.527 INFO [16646] [rtc::impl::IceTransport::LogCallback@339] juice: agent.c:1328: STUN server binding successful
2021-04-10 19:54:53.575 INFO [16646] [rtc::impl::IceTransport::LogCallback@339] juice: agent.c:787: Changing state to connected
2021-04-10 19:54:53.625 INFO [16646] [rtc::impl::IceTransport::LogCallback@339] juice: agent.c:787: Changing state to completed
#1
DC-1 Received: 0 KB/s Sent: 0 KB/s BufferSize: 0
TOTL Received: 0 KB/s Sent: 0 KB/s
2021-04-10 19:54:54.481 INFO [16653] [rtc::impl::DtlsTransport::runRecvLoop@503] DTLS handshake finished
2021-04-10 19:54:54.491 INFO [16627] [rtc::impl::SctpTransport::processNotification@713] SCTP connected
2021-04-10 19:54:54.491 INFO [16627] [rtc::impl::PeerConnection::changeState@1016] Changed state to connected
State: connected
DataChannel from UDL4 open
#2
DC-1 Received: 84326 KB/s Sent: 0 KB/s BufferSize: 0
TOTL Received: 84326 KB/s Sent: 0 KB/s
#3
DC-1 Received: 99387 KB/s Sent: 0 KB/s BufferSize: 0
TOTL Received: 99387 KB/s Sent: 0 KB/s
2021-04-10 19:54:57.025 INFO [16646] [rtc::impl::IceTransport::LogCallback@339] juice: agent.c:843: STUN server binding failed (timeout)
2021-04-10 19:54:57.025 INFO [16646] [rtc::impl::IceTransport::LogCallback@339] juice: agent.c:2206: Candidate gathering done
2021-04-10 19:54:57.025 INFO [16646] [rtc::impl::PeerConnection::changeGatheringState@1033] Changed gathering state to complete
Gathering State: complete
#4
DC-1 Received: 94871 KB/s Sent: 0 KB/s BufferSize: 0
TOTL Received: 94871 KB/s Sent: 0 KB/s
#5
DC-1 Received: 96259 KB/s Sent: 0 KB/s BufferSize: 0
TOTL Received: 96259 KB/s Sent: 0 KB/s
Stats# Received Total: 377 MB Sent Total: 0 MB RTT: 2 ms
#6
DC-1 Received: 92873 KB/s Sent: 0 KB/s BufferSize: 0
TOTL Received: 92873 KB/s Sent: 0 KB/s
#7
DC-1 Received: 87724 KB/s Sent: 0 KB/s BufferSize: 0
TOTL Received: 87724 KB/s Sent: 0 KB/s
#8
DC-1 Received: 95123 KB/s Sent: 0 KB/s BufferSize: 0
TOTL Received: 95123 KB/s Sent: 0 KB/s
#9
DC-1 Received: 100022 KB/s Sent: 0 KB/s BufferSize: 0
TOTL Received: 100022 KB/s Sent: 0 KB/s
#10
DC-1 Received: 98124 KB/s Sent: 0 KB/s BufferSize: 0
TOTL Received: 98124 KB/s Sent: 0 KB/s
Stats# Received Total: 853 MB Sent Total: 0 MB RTT: 2 ms
#11
DC-1 Received: 103628 KB/s Sent: 0 KB/s BufferSize: 0
TOTL Received: 103628 KB/s Sent: 0 KB/s
#12
DC-1 Received: 106166 KB/s Sent: 0 KB/s BufferSize: 0
TOTL Received: 106166 KB/s Sent: 0 KB/s
#13
DC-1 Received: 98410 KB/s Sent: 0 KB/s BufferSize: 0
TOTL Received: 98410 KB/s Sent: 0 KB/s
#14
DC-1 Received: 99854 KB/s Sent: 0 KB/s BufferSize: 0
TOTL Received: 99854 KB/s Sent: 0 KB/s
#15
DC-1 Received: 98487 KB/s Sent: 0 KB/s BufferSize: 0
TOTL Received: 98487 KB/s Sent: 0 KB/s
Stats# Received Total: 1362 MB Sent Total: 0 MB RTT: 2 ms
```
### Constant Throughput Set 8000 byte, for 300 seconds, send buffer 10000 byte
> `./client-benchmark -p -d 300 -r 8000 -b 10000`
Example Output (Offering Peer's Output);
```bash
Stun server is stun:stun.l.google.com:19302
The local ID is: 5zkC
Url is ws://localhost:8000/5zkC
Waiting for signaling to be connected...
2021-04-10 19:52:49.788 INFO [16530] [rtc::impl::TcpTransport::connect@163] Connected to localhost:8000
2021-04-10 19:52:49.788 INFO [16530] [rtc::impl::TcpTransport::runLoop@331] TCP connected
2021-04-10 19:52:49.789 INFO [16530] [rtc::impl::WsTransport::incoming@118] WebSocket open
WebSocket connected, signaling ready
Enter a remote ID to send an offer:
WawD
Offering to WawD
Creating DataChannel with label "DC-1"
2021-04-10 19:52:57.720 INFO [16523] [rtc::impl::IceTransport::IceTransport@106] Using STUN server "stun.l.google.com:19302"
2021-04-10 19:52:57.721 INFO [16523] [rtc::impl::PeerConnection::changeSignalingState@1044] Changed signaling state to new
2021-04-10 19:52:57.721 INFO [16523] [rtc::impl::PeerConnection::changeGatheringState@1033] Changed gathering state to in-progress
Gathering State: in-progress
2021-04-10 19:52:57.722 INFO [16523] [rtc::impl::IceTransport::LogCallback@339] juice: agent.c:787: Changing state to gathering
Benchmark will run for 300 seconds
2021-04-10 19:52:57.722 INFO [16533] [rtc::impl::IceTransport::LogCallback@339] juice: agent.c:787: Changing state to connecting
2021-04-10 19:52:57.722 INFO [16533] [rtc::impl::PeerConnection::changeState@1016] Changed state to connecting
State: connecting
2021-04-10 19:52:57.725 INFO [16533] [rtc::impl::IceTransport::LogCallback@339] juice: agent.c:610: Using STUN server stun.l.google.com:19302
2021-04-10 19:52:57.727 INFO [16530] [rtc::impl::PeerConnection::changeSignalingState@1044] Changed signaling state to connecting
2021-04-10 19:52:57.826 INFO [16533] [rtc::impl::IceTransport::LogCallback@339] juice: agent.c:787: Changing state to connected
2021-04-10 19:52:57.828 INFO [16533] [rtc::impl::IceTransport::LogCallback@339] juice: agent.c:787: Changing state to completed
2021-04-10 19:52:57.829 INFO [16533] [rtc::impl::IceTransport::LogCallback@339] juice: agent.c:1328: STUN server binding successful
2021-04-10 19:52:57.884 INFO [16535] [rtc::impl::DtlsTransport::runRecvLoop@503] DTLS handshake finished
2021-04-10 19:52:57.907 INFO [16526] [rtc::impl::SctpTransport::processNotification@713] SCTP connected
2021-04-10 19:52:57.907 INFO [16526] [rtc::impl::PeerConnection::changeState@1016] Changed state to connected
State: connected
DataChannel from WawD open
#1
DC-1 Received: 6515 KB/s Sent: 6577 KB/s BufferSize: 0
TOTL Received: 6515 KB/s Sent: 6577 KB/s
#2
DC-1 Received: 7998 KB/s Sent: 7999 KB/s BufferSize: 0
TOTL Received: 7998 KB/s Sent: 7999 KB/s
#3
DC-1 Received: 7933 KB/s Sent: 7999 KB/s BufferSize: 0
TOTL Received: 7933 KB/s Sent: 7999 KB/s
2021-04-10 19:53:01.275 INFO [16533] [rtc::impl::IceTransport::LogCallback@339] juice: agent.c:843: STUN server binding failed (timeout)
2021-04-10 19:53:01.275 INFO [16533] [rtc::impl::IceTransport::LogCallback@339] juice: agent.c:2206: Candidate gathering done
2021-04-10 19:53:01.275 INFO [16533] [rtc::impl::PeerConnection::changeGatheringState@1033] Changed gathering state to complete
Gathering State: complete
#4
DC-1 Received: 8070 KB/s Sent: 8000 KB/s BufferSize: 0
TOTL Received: 8070 KB/s Sent: 8000 KB/s
#5
DC-1 Received: 7984 KB/s Sent: 8000 KB/s BufferSize: 0
TOTL Received: 7984 KB/s Sent: 8000 KB/s
Stats# Received Total: 39 MB Sent Total: 39 MB RTT: 0 ms
#6
DC-1 Received: 8004 KB/s Sent: 7998 KB/s BufferSize: 0
TOTL Received: 8004 KB/s Sent: 7998 KB/s
#7
DC-1 Received: 7997 KB/s Sent: 8000 KB/s BufferSize: 0
TOTL Received: 7997 KB/s Sent: 8000 KB/s
#8
DC-1 Received: 8008 KB/s Sent: 8000 KB/s BufferSize: 0
TOTL Received: 8008 KB/s Sent: 8000 KB/s
#9
DC-1 Received: 8007 KB/s Sent: 8000 KB/s BufferSize: 0
TOTL Received: 8007 KB/s Sent: 8000 KB/s
#10
DC-1 Received: 7999 KB/s Sent: 7999 KB/s BufferSize: 0
TOTL Received: 7999 KB/s Sent: 7999 KB/s
Stats# Received Total: 81 MB Sent Total: 81 MB RTT: 0 ms
#11
DC-1 Received: 7997 KB/s Sent: 8001 KB/s BufferSize: 0
TOTL Received: 7997 KB/s Sent: 8001 KB/s
#12
DC-1 Received: 7981 KB/s Sent: 7997 KB/s BufferSize: 0
TOTL Received: 7981 KB/s Sent: 7997 KB/s
#13
DC-1 Received: 8024 KB/s Sent: 8000 KB/s BufferSize: 0
TOTL Received: 8024 KB/s Sent: 8000 KB/s
#14
DC-1 Received: 7990 KB/s Sent: 7999 KB/s BufferSize: 0
TOTL Received: 7990 KB/s Sent: 7999 KB/s
#15
DC-1 Received: 8001 KB/s Sent: 8002 KB/s BufferSize: 0
TOTL Received: 8001 KB/s Sent: 8002 KB/s
Stats# Received Total: 122 MB Sent Total: 122 MB RTT: 0 ms
```
### Constant Throughput Set 8000 byte, for 300 seconds, send buffer 10000 byte, 5 Data Channel
> `./client-benchmark -p -d 300 -r 8000 -b 10000 -c 5`
Example Output (Offering Peer's Output);
```bash
Stun server is stun:stun.l.google.com:19302
The local ID is: QZ46
Url is ws://localhost:8000/QZ46
Waiting for signaling to be connected...
2021-04-10 19:57:28.562 INFO [17117] [rtc::impl::TcpTransport::connect@163] Connected to localhost:8000
2021-04-10 19:57:28.562 INFO [17117] [rtc::impl::TcpTransport::runLoop@331] TCP connected
2021-04-10 19:57:28.563 INFO [17117] [rtc::impl::WsTransport::incoming@118] WebSocket open
WebSocket connected, signaling ready
Enter a remote ID to send an offer:
lTZA
Offering to lTZA
Creating DataChannel with label "DC-1"
2021-04-10 19:57:37.371 INFO [17110] [rtc::impl::IceTransport::IceTransport@106] Using STUN server "stun.l.google.com:19302"
2021-04-10 19:57:37.372 INFO [17110] [rtc::impl::PeerConnection::changeSignalingState@1044] Changed signaling state to new
2021-04-10 19:57:37.373 INFO [17110] [rtc::impl::PeerConnection::changeGatheringState@1033] Changed gathering state to in-progress
2021-04-10 19:57:37.373 INFO [17110] [rtc::impl::IceTransport::LogCallback@339] juice: agent.c:787: Changing state to gathering
Gathering State: in-progress
Creating DataChannel with label "DC-2"
2021-04-10 19:57:37.373 INFO [17119] [rtc::impl::IceTransport::LogCallback@339] juice: agent.c:787: Changing state to connecting
Creating DataChannel with label "DC-3"
2021-04-10 19:57:37.374 INFO [17119] [rtc::impl::PeerConnection::changeState@1016] Changed state to connecting
Creating DataChannel with label "DC-4"
Creating DataChannel with label "DC-5"
State: Benchmark will run for connecting300 seconds
2021-04-10 19:57:37.376 INFO [17119] [rtc::impl::IceTransport::LogCallback@339] juice: agent.c:610: Using STUN server stun.l.google.com:19302
2021-04-10 19:57:37.378 INFO [17117] [rtc::impl::PeerConnection::changeSignalingState@1044] Changed signaling state to connecting
2021-04-10 19:57:37.423 INFO [17119] [rtc::impl::IceTransport::LogCallback@339] juice: agent.c:1328: STUN server binding successful
2021-04-10 19:57:37.476 INFO [17119] [rtc::impl::IceTransport::LogCallback@339] juice: agent.c:787: Changing state to connected
2021-04-10 19:57:37.478 INFO [17119] [rtc::impl::IceTransport::LogCallback@339] juice: agent.c:787: Changing state to completed
2021-04-10 19:57:38.383 INFO [17122] [rtc::impl::DtlsTransport::runRecvLoop@503] DTLS handshake finished
2021-04-10 19:57:38.392 INFO [17113] [rtc::impl::SctpTransport::processNotification@713] SCTP connected
2021-04-10 19:57:38.392 INFO [17113] [rtc::impl::PeerConnection::changeState@1016] Changed state to connected
State: connected
DataChannel from lTZA open
DataChannel from lTZA open
#DataChannel from lTZA open
DataChannel from lTZA open
1
DC-5 Received: 0 KB/s Sent: 79 KB/s BufferSize: 0
DC-3 Received: 0 KB/s Sent: 0 KB/s BufferSize: 0
DC-4 Received: 0 KB/s Sent: 79 KB/s BufferSize: 0
DC-2 Received: 0 KB/s Sent: 0 KB/s BufferSize: 0
DC-1 Received: 0 KB/s Sent: 0 KB/s BufferSize: 0
TOTL Received: 0 KB/s Sent: 158 KB/s
DataChannel from lTZA open
#2
DC-5 Received: 7960 KB/s Sent: 8000 KB/s BufferSize: 0
DC-3 Received: 7804 KB/s Sent: 8000 KB/s BufferSize: 0
DC-4 Received: 7883 KB/s Sent: 8000 KB/s BufferSize: 0
DC-2 Received: 7882 KB/s Sent: 8000 KB/s BufferSize: 0
DC-1 Received: 7804 KB/s Sent: 8000 KB/s BufferSize: 0
TOTL Received: 39333 KB/s Sent: 40000 KB/s
#3
DC-5 Received: 7966 KB/s Sent: 7996 KB/s BufferSize: 81504
DC-3 Received: 8047 KB/s Sent: 7996 KB/s BufferSize: 81504
DC-4 Received: 7958 KB/s Sent: 7996 KB/s BufferSize: 81504
DC-2 Received: 7958 KB/s Sent: 7996 KB/s BufferSize: 81504
DC-1 Received: 8067 KB/s Sent: 7996 KB/s BufferSize: 163597
TOTL Received: 39996 KB/s Sent: 39980 KB/s
2021-04-10 19:57:40.926 INFO [17119] [rtc::impl::IceTransport::LogCallback@339] juice: agent.c:843: STUN server binding failed (timeout)
2021-04-10 19:57:40.926 INFO [17119] [rtc::impl::IceTransport::LogCallback@339] juice: agent.c:2206: Candidate gathering done
2021-04-10 19:57:40.926 INFO [17119] [rtc::impl::PeerConnection::changeGatheringState@1033] Changed gathering state to complete
Gathering State: complete
#4
DC-5 Received: 7970 KB/s Sent: 8002 KB/s BufferSize: 0
DC-3 Received: 7957 KB/s Sent: 8002 KB/s BufferSize: 0
DC-4 Received: 7910 KB/s Sent: 8002 KB/s BufferSize: 0
DC-2 Received: 7967 KB/s Sent: 8002 KB/s BufferSize: 0
DC-1 Received: 7957 KB/s Sent: 8002 KB/s BufferSize: 0
TOTL Received: 39761 KB/s Sent: 40010 KB/s
#5
DC-5 Received: 7996 KB/s Sent: 7999 KB/s BufferSize: 0
DC-3 Received: 8006 KB/s Sent: 7999 KB/s BufferSize: 0
DC-4 Received: 8078 KB/s Sent: 7999 KB/s BufferSize: 0
DC-2 Received: 8015 KB/s Sent: 7999 KB/s BufferSize: 0
DC-1 Received: 7928 KB/s Sent: 7999 KB/s BufferSize: 0
TOTL Received: 40023 KB/s Sent: 39995 KB/s
Stats# Received Total: 165 MB Sent Total: 166 MB RTT: 1 ms
#6
DC-5 Received: 7968 KB/s Sent: 7999 KB/s BufferSize: 0
DC-3 Received: 7962 KB/s Sent: 7999 KB/s BufferSize: 0
DC-4 Received: 7965 KB/s Sent: 7999 KB/s BufferSize: 0
DC-2 Received: 7970 KB/s Sent: 7999 KB/s BufferSize: 0
DC-1 Received: 8044 KB/s Sent: 7999 KB/s BufferSize: 0
TOTL Received: 39909 KB/s Sent: 39995 KB/s
#7
DC-5 Received: 6658 KB/s Sent: 8001 KB/s BufferSize: 82228
DC-3 Received: 6584 KB/s Sent: 8001 KB/s BufferSize: 163596
DC-4 Received: 6572 KB/s Sent: 8001 KB/s BufferSize: 163596
DC-2 Received: 6571 KB/s Sent: 8001 KB/s BufferSize: 163596
DC-1 Received: 6492 KB/s Sent: 8001 KB/s BufferSize: 163596
TOTL Received: 32877 KB/s Sent: 40005 KB/s
#8
DC-5 Received: 5773 KB/s Sent: 7997 KB/s BufferSize: 0
DC-3 Received: 6555 KB/s Sent: 7997 KB/s BufferSize: 0
DC-4 Received: 6164 KB/s Sent: 7997 KB/s BufferSize: 0
DC-2 Received: 6241 KB/s Sent: 7997 KB/s BufferSize: 0
DC-1 Received: 5454 KB/s Sent: 7997 KB/s BufferSize: 0
TOTL Received: 30187 KB/s Sent: 39985 KB/s
#9
DC-5 Received: 7442 KB/s Sent: 8002 KB/s BufferSize: 326921
DC-3 Received: 7580 KB/s Sent: 8002 KB/s BufferSize: 326921
DC-4 Received: 7363 KB/s Sent: 8002 KB/s BufferSize: 326921
DC-2 Received: 7524 KB/s Sent: 8002 KB/s BufferSize: 326921
DC-1 Received: 7362 KB/s Sent: 8002 KB/s BufferSize: 408769
TOTL Received: 37271 KB/s Sent: 40010 KB/s
#10
DC-5 Received: 6134 KB/s Sent: 7999 KB/s BufferSize: 244963
DC-3 Received: 8032 KB/s Sent: 7999 KB/s BufferSize: 326286
DC-4 Received: 5897 KB/s Sent: 7999 KB/s BufferSize: 326286
DC-2 Received: 5657 KB/s Sent: 7999 KB/s BufferSize: 326286
DC-1 Received: 5581 KB/s Sent: 7999 KB/s BufferSize: 326286
TOTL Received: 31301 KB/s Sent: 39995 KB/s
Stats# Received Total: 343 MB Sent Total: 372 MB RTT: 16 ms
#11
DC-5 Received: 6117 KB/s Sent: 7998 KB/s BufferSize: 570756
DC-3 Received: 6594 KB/s Sent: 7998 KB/s BufferSize: 570756
DC-4 Received: 6354 KB/s Sent: 7998 KB/s BufferSize: 570756
DC-2 Received: 6116 KB/s Sent: 7998 KB/s BufferSize: 570756
DC-1 Received: 5959 KB/s Sent: 7998 KB/s BufferSize: 570756
TOTL Received: 31140 KB/s Sent: 39990 KB/s
#12
DC-5 Received: 6840 KB/s Sent: 7999 KB/s BufferSize: 0
DC-3 Received: 7468 KB/s Sent: 7999 KB/s BufferSize: 0
DC-4 Received: 7472 KB/s Sent: 7999 KB/s BufferSize: 0
DC-2 Received: 7473 KB/s Sent: 7999 KB/s BufferSize: 0
DC-1 Received: 7236 KB/s Sent: 7999 KB/s BufferSize: 0
TOTL Received: 36489 KB/s Sent: 39995 KB/s
#13
DC-5 Received: 8105 KB/s Sent: 7989 KB/s BufferSize: 0
DC-3 Received: 8020 KB/s Sent: 7989 KB/s BufferSize: 0
DC-4 Received: 8097 KB/s Sent: 7989 KB/s BufferSize: 0
DC-2 Received: 8106 KB/s Sent: 7989 KB/s BufferSize: 0
DC-1 Received: 8018 KB/s Sent: 7989 KB/s BufferSize: 0
TOTL Received: 40346 KB/s Sent: 39945 KB/s
#14
DC-5 Received: 8042 KB/s Sent: 8007 KB/s BufferSize: 0
DC-3 Received: 8029 KB/s Sent: 8007 KB/s BufferSize: 0
DC-4 Received: 8038 KB/s Sent: 8007 KB/s BufferSize: 0
DC-2 Received: 8035 KB/s Sent: 8007 KB/s BufferSize: 0
DC-1 Received: 8036 KB/s Sent: 8007 KB/s BufferSize: 0
TOTL Received: 40180 KB/s Sent: 40035 KB/s
#15
DC-5 Received: 7981 KB/s Sent: 8001 KB/s BufferSize: 0
DC-3 Received: 7987 KB/s Sent: 8001 KB/s BufferSize: 0
DC-4 Received: 7980 KB/s Sent: 8001 KB/s BufferSize: 0
DC-2 Received: 7974 KB/s Sent: 8001 KB/s BufferSize: 0
DC-1 Received: 7972 KB/s Sent: 8001 KB/s BufferSize: 82497
TOTL Received: 39894 KB/s Sent: 40005 KB/s
Stats# Received Total: 538 MB Sent Total: 581 MB RTT: 3 ms
```

View File

@ -1,513 +0,0 @@
/* Getopt for Microsoft C
This code is a modification of the Free Software Foundation, Inc.
Getopt library for parsing command line argument the purpose was
to provide a Microsoft Visual C friendly derivative. This code
provides functionality for both Unicode and Multibyte builds.
Date: 02/03/2011 - Ludvik Jerabek - Initial Release
Version: 1.0
Comment: Supports getopt, getopt_long, and getopt_long_only
and POSIXLY_CORRECT environment flag
License: LGPL
Revisions:
02/03/2011 - Ludvik Jerabek - Initial Release
02/20/2011 - Ludvik Jerabek - Fixed compiler warnings at Level 4
07/05/2011 - Ludvik Jerabek - Added no_argument, required_argument, optional_argument defs
08/03/2011 - Ludvik Jerabek - Fixed non-argument runtime bug which caused runtime exception
08/09/2011 - Ludvik Jerabek - Added code to export functions for DLL and LIB
02/15/2012 - Ludvik Jerabek - Fixed _GETOPT_THROW definition missing in implementation file
08/01/2012 - Ludvik Jerabek - Created separate functions for char and wchar_t characters so single dll can do both unicode and ansi
10/15/2012 - Ludvik Jerabek - Modified to match latest GNU features
06/19/2015 - Ludvik Jerabek - Fixed maximum option limitation caused by option_a (255) and option_w (65535) structure val variable
24/10/2020 - Paul-Louis Ageneau - Removed Unicode version
**DISCLAIMER**
THIS MATERIAL IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING, BUT Not LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE, OR NON-INFRINGEMENT. SOME JURISDICTIONS DO NOT ALLOW THE
EXCLUSION OF IMPLIED WARRANTIES, SO THE ABOVE EXCLUSION MAY NOT
APPLY TO YOU. IN NO EVENT WILL I BE LIABLE TO ANY PARTY FOR ANY
DIRECT, INDIRECT, SPECIAL OR OTHER CONSEQUENTIAL DAMAGES FOR ANY
USE OF THIS MATERIAL INCLUDING, WITHOUT LIMITATION, ANY LOST
PROFITS, BUSINESS INTERRUPTION, LOSS OF PROGRAMS OR OTHER DATA ON
YOUR INFORMATION HANDLING SYSTEM OR OTHERWISE, EVEN If WE ARE
EXPRESSLY ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*/
#ifndef _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>
#include "getopt.h"
#ifdef __cplusplus
#define _GETOPT_THROW throw()
#else
#define _GETOPT_THROW
#endif
int optind = 1;
int opterr = 1;
int optopt = '?';
enum ENUM_ORDERING { REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER };
static struct _getopt_data_a
{
int optind;
int opterr;
int optopt;
char *optarg;
int __initialized;
char *__nextchar;
enum ENUM_ORDERING __ordering;
int __posixly_correct;
int __first_nonopt;
int __last_nonopt;
} getopt_data_a;
char *optarg_a;
static void exchange_a(char **argv, struct _getopt_data_a *d)
{
int bottom = d->__first_nonopt;
int middle = d->__last_nonopt;
int top = d->optind;
char *tem;
while (top > middle && middle > bottom)
{
if (top - middle > middle - bottom)
{
int len = middle - bottom;
int i;
for (i = 0; i < len; i++)
{
tem = argv[bottom + i];
argv[bottom + i] = argv[top - (middle - bottom) + i];
argv[top - (middle - bottom) + i] = tem;
}
top -= len;
}
else
{
int len = top - middle;
int i;
for (i = 0; i < len; i++)
{
tem = argv[bottom + i];
argv[bottom + i] = argv[middle + i];
argv[middle + i] = tem;
}
bottom += len;
}
}
d->__first_nonopt += (d->optind - d->__last_nonopt);
d->__last_nonopt = d->optind;
}
static const char *_getopt_initialize_a (const char *optstring, struct _getopt_data_a *d, int posixly_correct)
{
d->__first_nonopt = d->__last_nonopt = d->optind;
d->__nextchar = NULL;
d->__posixly_correct = posixly_correct | !!getenv("POSIXLY_CORRECT");
if (optstring[0] == '-')
{
d->__ordering = RETURN_IN_ORDER;
++optstring;
}
else if (optstring[0] == '+')
{
d->__ordering = REQUIRE_ORDER;
++optstring;
}
else if (d->__posixly_correct)
d->__ordering = REQUIRE_ORDER;
else
d->__ordering = PERMUTE;
return optstring;
}
int _getopt_internal_r_a (int argc, char *const *argv, const char *optstring, const struct option_a *longopts, int *longind, int long_only, struct _getopt_data_a *d, int posixly_correct)
{
int print_errors = d->opterr;
if (argc < 1)
return -1;
d->optarg = NULL;
if (d->optind == 0 || !d->__initialized)
{
if (d->optind == 0)
d->optind = 1;
optstring = _getopt_initialize_a (optstring, d, posixly_correct);
d->__initialized = 1;
}
else if (optstring[0] == '-' || optstring[0] == '+')
optstring++;
if (optstring[0] == ':')
print_errors = 0;
if (d->__nextchar == NULL || *d->__nextchar == '\0')
{
if (d->__last_nonopt > d->optind)
d->__last_nonopt = d->optind;
if (d->__first_nonopt > d->optind)
d->__first_nonopt = d->optind;
if (d->__ordering == PERMUTE)
{
if (d->__first_nonopt != d->__last_nonopt && d->__last_nonopt != d->optind)
exchange_a ((char **) argv, d);
else if (d->__last_nonopt != d->optind)
d->__first_nonopt = d->optind;
while (d->optind < argc && (argv[d->optind][0] != '-' || argv[d->optind][1] == '\0'))
d->optind++;
d->__last_nonopt = d->optind;
}
if (d->optind != argc && !strcmp(argv[d->optind], "--"))
{
d->optind++;
if (d->__first_nonopt != d->__last_nonopt && d->__last_nonopt != d->optind)
exchange_a((char **) argv, d);
else if (d->__first_nonopt == d->__last_nonopt)
d->__first_nonopt = d->optind;
d->__last_nonopt = argc;
d->optind = argc;
}
if (d->optind == argc)
{
if (d->__first_nonopt != d->__last_nonopt)
d->optind = d->__first_nonopt;
return -1;
}
if ((argv[d->optind][0] != '-' || argv[d->optind][1] == '\0'))
{
if (d->__ordering == REQUIRE_ORDER)
return -1;
d->optarg = argv[d->optind++];
return 1;
}
d->__nextchar = (argv[d->optind] + 1 + (longopts != NULL && argv[d->optind][1] == '-'));
}
if (longopts != NULL && (argv[d->optind][1] == '-' || (long_only && (argv[d->optind][2] || !strchr(optstring, argv[d->optind][1])))))
{
char *nameend;
unsigned int namelen;
const struct option_a *p;
const struct option_a *pfound = NULL;
struct option_list
{
const struct option_a *p;
struct option_list *next;
} *ambig_list = NULL;
int exact = 0;
int indfound = -1;
int option_index;
for (nameend = d->__nextchar; *nameend && *nameend != '='; nameend++);
namelen = (unsigned int)(nameend - d->__nextchar);
for (p = longopts, option_index = 0; p->name; p++, option_index++)
if (!strncmp(p->name, d->__nextchar, namelen))
{
if (namelen == (unsigned int)strlen(p->name))
{
pfound = p;
indfound = option_index;
exact = 1;
break;
}
else if (pfound == NULL)
{
pfound = p;
indfound = option_index;
}
else if (long_only || pfound->has_arg != p->has_arg || pfound->flag != p->flag || pfound->val != p->val)
{
struct option_list *newp = (struct option_list*)alloca(sizeof(*newp));
newp->p = p;
newp->next = ambig_list;
ambig_list = newp;
}
}
if (ambig_list != NULL && !exact)
{
if (print_errors)
{
struct option_list first;
first.p = pfound;
first.next = ambig_list;
ambig_list = &first;
fprintf (stderr, "%s: option '%s' is ambiguous; possibilities:", argv[0], argv[d->optind]);
do
{
fprintf (stderr, " '--%s'", ambig_list->p->name);
ambig_list = ambig_list->next;
}
while (ambig_list != NULL);
fputc ('\n', stderr);
}
d->__nextchar += strlen(d->__nextchar);
d->optind++;
d->optopt = 0;
return '?';
}
if (pfound != NULL)
{
option_index = indfound;
d->optind++;
if (*nameend)
{
if (pfound->has_arg)
d->optarg = nameend + 1;
else
{
if (print_errors)
{
if (argv[d->optind - 1][1] == '-')
{
fprintf(stderr, "%s: option '--%s' doesn't allow an argument\n",argv[0], pfound->name);
}
else
{
fprintf(stderr, "%s: option '%c%s' doesn't allow an argument\n",argv[0], argv[d->optind - 1][0],pfound->name);
}
}
d->__nextchar += strlen(d->__nextchar);
d->optopt = pfound->val;
return '?';
}
}
else if (pfound->has_arg == 1)
{
if (d->optind < argc)
d->optarg = argv[d->optind++];
else
{
if (print_errors)
{
fprintf(stderr,"%s: option '--%s' requires an argument\n",argv[0], pfound->name);
}
d->__nextchar += strlen(d->__nextchar);
d->optopt = pfound->val;
return optstring[0] == ':' ? ':' : '?';
}
}
d->__nextchar += strlen(d->__nextchar);
if (longind != NULL)
*longind = option_index;
if (pfound->flag)
{
*(pfound->flag) = pfound->val;
return 0;
}
return pfound->val;
}
if (!long_only || argv[d->optind][1] == '-' || strchr(optstring, *d->__nextchar) == NULL)
{
if (print_errors)
{
if (argv[d->optind][1] == '-')
{
fprintf(stderr, "%s: unrecognized option '--%s'\n",argv[0], d->__nextchar);
}
else
{
fprintf(stderr, "%s: unrecognized option '%c%s'\n",argv[0], argv[d->optind][0], d->__nextchar);
}
}
d->__nextchar = (char *)"";
d->optind++;
d->optopt = 0;
return '?';
}
}
{
char c = *d->__nextchar++;
char *temp = (char*)strchr(optstring, c);
if (*d->__nextchar == '\0')
++d->optind;
if (temp == NULL || c == ':' || c == ';')
{
if (print_errors)
{
fprintf(stderr, "%s: invalid option -- '%c'\n", argv[0], c);
}
d->optopt = c;
return '?';
}
if (temp[0] == 'W' && temp[1] == ';')
{
char *nameend;
const struct option_a *p;
const struct option_a *pfound = NULL;
int exact = 0;
int ambig = 0;
int indfound = 0;
int option_index;
if (longopts == NULL)
goto no_longs;
if (*d->__nextchar != '\0')
{
d->optarg = d->__nextchar;
d->optind++;
}
else if (d->optind == argc)
{
if (print_errors)
{
fprintf(stderr,"%s: option requires an argument -- '%c'\n",argv[0], c);
}
d->optopt = c;
if (optstring[0] == ':')
c = ':';
else
c = '?';
return c;
}
else
d->optarg = argv[d->optind++];
for (d->__nextchar = nameend = d->optarg; *nameend && *nameend != '='; nameend++);
for (p = longopts, option_index = 0; p->name; p++, option_index++)
if (!strncmp(p->name, d->__nextchar, nameend - d->__nextchar))
{
if ((unsigned int) (nameend - d->__nextchar) == strlen(p->name))
{
pfound = p;
indfound = option_index;
exact = 1;
break;
}
else if (pfound == NULL)
{
pfound = p;
indfound = option_index;
}
else if (long_only || pfound->has_arg != p->has_arg || pfound->flag != p->flag || pfound->val != p->val)
ambig = 1;
}
if (ambig && !exact)
{
if (print_errors)
{
fprintf(stderr, "%s: option '-W %s' is ambiguous\n",argv[0], d->optarg);
}
d->__nextchar += strlen(d->__nextchar);
d->optind++;
return '?';
}
if (pfound != NULL)
{
option_index = indfound;
if (*nameend)
{
if (pfound->has_arg)
d->optarg = nameend + 1;
else
{
if (print_errors)
{
fprintf(stderr, "%s: option '-W %s' doesn't allow an argument\n",argv[0], pfound->name);
}
d->__nextchar += strlen(d->__nextchar);
return '?';
}
}
else if (pfound->has_arg == 1)
{
if (d->optind < argc)
d->optarg = argv[d->optind++];
else
{
if (print_errors)
{
fprintf(stderr, "%s: option '-W %s' requires an argument\n",argv[0], pfound->name);
}
d->__nextchar += strlen(d->__nextchar);
return optstring[0] == ':' ? ':' : '?';
}
}
else
d->optarg = NULL;
d->__nextchar += strlen(d->__nextchar);
if (longind != NULL)
*longind = option_index;
if (pfound->flag)
{
*(pfound->flag) = pfound->val;
return 0;
}
return pfound->val;
}
no_longs:
d->__nextchar = NULL;
return 'W';
}
if (temp[1] == ':')
{
if (temp[2] == ':')
{
if (*d->__nextchar != '\0')
{
d->optarg = d->__nextchar;
d->optind++;
}
else
d->optarg = NULL;
d->__nextchar = NULL;
}
else
{
if (*d->__nextchar != '\0')
{
d->optarg = d->__nextchar;
d->optind++;
}
else if (d->optind == argc)
{
if (print_errors)
{
fprintf(stderr,"%s: option requires an argument -- '%c'\n",argv[0], c);
}
d->optopt = c;
if (optstring[0] == ':')
c = ':';
else
c = '?';
}
else
d->optarg = argv[d->optind++];
d->__nextchar = NULL;
}
}
return c;
}
}
int _getopt_internal_a (int argc, char *const *argv, const char *optstring, const struct option_a *longopts, int *longind, int long_only, int posixly_correct)
{
int result;
getopt_data_a.optind = optind;
getopt_data_a.opterr = opterr;
result = _getopt_internal_r_a (argc, argv, optstring, longopts,longind, long_only, &getopt_data_a,posixly_correct);
optind = getopt_data_a.optind;
optarg_a = getopt_data_a.optarg;
optopt = getopt_data_a.optopt;
return result;
}
int getopt_a (int argc, char *const *argv, const char *optstring) _GETOPT_THROW
{
return _getopt_internal_a (argc, argv, optstring, (const struct option_a *) 0, (int *) 0, 0, 0);
}
int getopt_long_a (int argc, char *const *argv, const char *options, const struct option_a *long_options, int *opt_index) _GETOPT_THROW
{
return _getopt_internal_a (argc, argv, options, long_options, opt_index, 0, 0);
}
int getopt_long_only_a (int argc, char *const *argv, const char *options, const struct option_a *long_options, int *opt_index) _GETOPT_THROW
{
return _getopt_internal_a (argc, argv, options, long_options, opt_index, 1, 0);
}
int _getopt_long_r_a (int argc, char *const *argv, const char *options, const struct option_a *long_options, int *opt_index, struct _getopt_data_a *d)
{
return _getopt_internal_r_a (argc, argv, options, long_options, opt_index,0, d, 0);
}
int _getopt_long_only_r_a (int argc, char *const *argv, const char *options, const struct option_a *long_options, int *opt_index, struct _getopt_data_a *d)
{
return _getopt_internal_r_a (argc, argv, options, long_options, opt_index, 1, d, 0);
}

View File

@ -1,115 +0,0 @@
/* Getopt for Microsoft C
This code is a modification of the Free Software Foundation, Inc.
Getopt library for parsing command line argument the purpose was
to provide a Microsoft Visual C friendly derivative. This code
provides functionality for both Unicode and Multibyte builds.
Date: 02/03/2011 - Ludvik Jerabek - Initial Release
Version: 1.0
Comment: Supports getopt, getopt_long, and getopt_long_only
and POSIXLY_CORRECT environment flag
License: LGPL
Revisions:
02/03/2011 - Ludvik Jerabek - Initial Release
02/20/2011 - Ludvik Jerabek - Fixed compiler warnings at Level 4
07/05/2011 - Ludvik Jerabek - Added no_argument, required_argument, optional_argument defs
08/03/2011 - Ludvik Jerabek - Fixed non-argument runtime bug which caused runtime exception
08/09/2011 - Ludvik Jerabek - Added code to export functions for DLL and LIB
02/15/2012 - Ludvik Jerabek - Fixed _GETOPT_THROW definition missing in implementation file
08/01/2012 - Ludvik Jerabek - Created separate functions for char and wchar_t characters so single dll can do both unicode and ansi
10/15/2012 - Ludvik Jerabek - Modified to match latest GNU features
06/19/2015 - Ludvik Jerabek - Fixed maximum option limitation caused by option_a (255) and option_w (65535) structure val variable
24/10/2020 - Paul-Louis Ageneau - Removed Unicode version
**DISCLAIMER**
THIS MATERIAL IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING, BUT Not LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE, OR NON-INFRINGEMENT. SOME JURISDICTIONS DO NOT ALLOW THE
EXCLUSION OF IMPLIED WARRANTIES, SO THE ABOVE EXCLUSION MAY NOT
APPLY TO YOU. IN NO EVENT WILL I BE LIABLE TO ANY PARTY FOR ANY
DIRECT, INDIRECT, SPECIAL OR OTHER CONSEQUENTIAL DAMAGES FOR ANY
USE OF THIS MATERIAL INCLUDING, WITHOUT LIMITATION, ANY LOST
PROFITS, BUSINESS INTERRUPTION, LOSS OF PROGRAMS OR OTHER DATA ON
YOUR INFORMATION HANDLING SYSTEM OR OTHERWISE, EVEN If WE ARE
EXPRESSLY ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*/
#ifndef __GETOPT_H_
#define __GETOPT_H_
#ifdef _GETOPT_API
#undef _GETOPT_API
#endif
#if defined(EXPORTS_GETOPT) && defined(STATIC_GETOPT)
#error "The preprocessor definitions of EXPORTS_GETOPT and STATIC_GETOPT can only be used individually"
#elif defined(STATIC_GETOPT)
#pragma message("Warning static builds of getopt violate the Lesser GNU Public License")
#define _GETOPT_API
#elif defined(EXPORTS_GETOPT)
#pragma message("Exporting getopt library")
#define _GETOPT_API __declspec(dllexport)
#else
#pragma message("Importing getopt library")
#define _GETOPT_API __declspec(dllimport)
#endif
// Change behavior for C\C++
#ifdef __cplusplus
#define _BEGIN_EXTERN_C extern "C" {
#define _END_EXTERN_C }
#define _GETOPT_THROW throw()
#else
#define _BEGIN_EXTERN_C
#define _END_EXTERN_C
#define _GETOPT_THROW
#endif
// Standard GNU options
#define null_argument 0 /*Argument Null*/
#define no_argument 0 /*Argument Switch Only*/
#define required_argument 1 /*Argument Required*/
#define optional_argument 2 /*Argument Optional*/
// Shorter Options
#define ARG_NULL 0 /*Argument Null*/
#define ARG_NONE 0 /*Argument Switch Only*/
#define ARG_REQ 1 /*Argument Required*/
#define ARG_OPT 2 /*Argument Optional*/
#include <string.h>
_BEGIN_EXTERN_C
extern _GETOPT_API int optind;
extern _GETOPT_API int opterr;
extern _GETOPT_API int optopt;
struct option_a
{
const char* name;
int has_arg;
int *flag;
int val;
};
extern _GETOPT_API char *optarg_a;
extern _GETOPT_API int getopt_a(int argc, char *const *argv, const char *optstring) _GETOPT_THROW;
extern _GETOPT_API int getopt_long_a(int argc, char *const *argv, const char *options, const struct option_a *long_options, int *opt_index) _GETOPT_THROW;
extern _GETOPT_API int getopt_long_only_a(int argc, char *const *argv, const char *options, const struct option_a *long_options, int *opt_index) _GETOPT_THROW;
_END_EXTERN_C
#undef _BEGIN_EXTERN_C
#undef _END_EXTERN_C
#undef _GETOPT_THROW
#undef _GETOPT_API
#define getopt getopt_a
#define getopt_long getopt_long_a
#define getopt_long_only getopt_long_only_a
#define option option_a
#define optarg optarg_a
#endif // __GETOPT_H_

View File

@ -1,484 +0,0 @@
/*
* libdatachannel client-benchmark example
* Copyright (c) 2019-2020 Paul-Louis Ageneau
* Copyright (c) 2019-2021 Murat Dogan
* Copyright (c) 2020 Will Munn
* Copyright (c) 2020 Nico Chatzi
* Copyright (c) 2020 Lara Mackey
* Copyright (c) 2020 Erik Cota-Robles
*
* 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 <http://www.gnu.org/licenses/>.
*/
#include "rtc/rtc.hpp"
#include "parse_cl.h"
#include <nlohmann/json.hpp>
#include <algorithm>
#include <atomic>
#include <chrono>
#include <future>
#include <iomanip>
#include <iostream>
#include <memory>
#include <random>
#include <stdexcept>
#include <thread>
#include <unordered_map>
using namespace rtc;
using namespace std;
using namespace std::chrono_literals;
using chrono::milliseconds;
using chrono::steady_clock;
using json = nlohmann::json;
template <class T> weak_ptr<T> make_weak_ptr(shared_ptr<T> ptr) { return ptr; }
unordered_map<string, shared_ptr<PeerConnection>> peerConnectionMap;
unordered_map<string, shared_ptr<DataChannel>> dataChannelMap;
string localId;
shared_ptr<PeerConnection> createPeerConnection(const Configuration &config,
weak_ptr<WebSocket> wws, string id);
string randomId(size_t length);
// Benchmark
const size_t messageSize = 65535;
binary messageData(messageSize);
unordered_map<string, atomic<size_t>> receivedSizeMap;
unordered_map<string, atomic<size_t>> sentSizeMap;
bool noSend = false;
// Benchmark - enableThroughputSet params
bool enableThroughputSet;
int throughtputSetAsKB;
int bufferSize;
const float STEP_COUNT_FOR_1_SEC = 100.0;
const int stepDurationInMs = int(1000 / STEP_COUNT_FOR_1_SEC);
int main(int argc, char **argv) try {
Cmdline params(argc, argv);
rtc::InitLogger(LogLevel::Info);
// Benchmark - construct message to send
fill(messageData.begin(), messageData.end(), std::byte(0xFF));
// Benchmark - enableThroughputSet params
enableThroughputSet = params.enableThroughputSet();
throughtputSetAsKB = params.throughtputSetAsKB();
bufferSize = params.bufferSize();
// No Send option
noSend = params.noSend();
if (noSend)
cout << "Not Sending data. (One way benchmark)." << endl;
Configuration config;
string stunServer = "";
if (params.noStun()) {
cout << "No STUN server is configured. Only local hosts and public IP addresses supported."
<< endl;
} else {
if (params.stunServer().substr(0, 5).compare("stun:") != 0) {
stunServer = "stun:";
}
stunServer += params.stunServer() + ":" + to_string(params.stunPort());
cout << "Stun server is " << stunServer << endl;
config.iceServers.emplace_back(stunServer);
}
localId = randomId(4);
cout << "The local ID is: " << localId << endl;
auto ws = make_shared<WebSocket>();
std::promise<void> wsPromise;
auto wsFuture = wsPromise.get_future();
ws->onOpen([&wsPromise]() {
cout << "WebSocket connected, signaling ready" << endl;
wsPromise.set_value();
});
ws->onError([&wsPromise](string s) {
cout << "WebSocket error" << endl;
wsPromise.set_exception(std::make_exception_ptr(std::runtime_error(s)));
});
ws->onClosed([]() { cout << "WebSocket closed" << endl; });
ws->onMessage([&](variant<binary, string> data) {
if (!holds_alternative<string>(data))
return;
json message = json::parse(get<string>(data));
auto it = message.find("id");
if (it == message.end())
return;
string id = it->get<string>();
it = message.find("type");
if (it == message.end())
return;
string type = it->get<string>();
shared_ptr<PeerConnection> pc;
if (auto jt = peerConnectionMap.find(id); jt != peerConnectionMap.end()) {
pc = jt->second;
} else if (type == "offer") {
cout << "Answering to " + id << endl;
pc = createPeerConnection(config, ws, id);
} else {
return;
}
if (type == "offer" || type == "answer") {
auto sdp = message["description"].get<string>();
pc->setRemoteDescription(Description(sdp, type));
} else if (type == "candidate") {
auto sdp = message["candidate"].get<string>();
auto mid = message["mid"].get<string>();
pc->addRemoteCandidate(Candidate(sdp, mid));
}
});
string wsPrefix = "";
if (params.webSocketServer().substr(0, 5).compare("ws://") != 0) {
wsPrefix = "ws://";
}
const string url = wsPrefix + params.webSocketServer() + ":" +
to_string(params.webSocketPort()) + "/" + localId;
cout << "Url is " << url << endl;
ws->open(url);
cout << "Waiting for signaling to be connected..." << endl;
wsFuture.get();
string id;
cout << "Enter a remote ID to send an offer:" << endl;
cin >> id;
cin.ignore();
if (id.empty()) {
// Nothing to do
return 0;
}
if (id == localId) {
cout << "Invalid remote ID (This is my local ID). Exiting..." << endl;
return 0;
}
cout << "Offering to " + id << endl;
auto pc = createPeerConnection(config, ws, id);
// We are the offerer, so create a data channel to initiate the process
for (int i = 1; i <= params.dataChannelCount(); i++) {
const string label = "DC-" + std::to_string(i);
cout << "Creating DataChannel with label \"" << label << "\"" << endl;
auto dc = pc->createDataChannel(label);
receivedSizeMap.emplace(label, 0);
sentSizeMap.emplace(label, 0);
// Set Buffer Size
dc->setBufferedAmountLowThreshold(bufferSize);
dc->onOpen([id, wdc = make_weak_ptr(dc), label]() {
cout << "DataChannel from " << id << " open" << endl;
if (noSend)
return;
if (enableThroughputSet)
return;
if (auto dcLocked = wdc.lock()) {
try {
while (dcLocked->bufferedAmount() <= bufferSize) {
dcLocked->send(messageData);
sentSizeMap.at(label) += messageData.size();
}
} catch (const std::exception &e) {
std::cout << "Send failed: " << e.what() << std::endl;
}
}
});
dc->onBufferedAmountLow([wdc = make_weak_ptr(dc), label]() {
if (noSend)
return;
if (enableThroughputSet)
return;
auto dcLocked = wdc.lock();
if (!dcLocked)
return;
// Continue sending
try {
while (dcLocked->isOpen() && dcLocked->bufferedAmount() <= bufferSize) {
dcLocked->send(messageData);
sentSizeMap.at(label) += messageData.size();
}
} catch (const std::exception &e) {
std::cout << "Send failed: " << e.what() << std::endl;
}
});
dc->onClosed([id]() { cout << "DataChannel from " << id << " closed" << endl; });
dc->onMessage([id, wdc = make_weak_ptr(dc), label](variant<binary, string> data) {
if (holds_alternative<binary>(data))
receivedSizeMap.at(label) += get<binary>(data).size();
});
dataChannelMap.emplace(label, dc);
}
const int duration = params.durationInSec() > 0 ? params.durationInSec() : INT32_MAX;
cout << "Benchmark will run for " << duration << " seconds" << endl;
int printCounter = 0;
int printStatCounter = 0;
steady_clock::time_point printTime = steady_clock::now();
steady_clock::time_point stepTime = steady_clock::now();
// Byte count to send for every loop
int byteToSendOnEveryLoop = throughtputSetAsKB * stepDurationInMs;
for (int i = 1; i <= duration * STEP_COUNT_FOR_1_SEC; ++i) {
this_thread::sleep_for(milliseconds(stepDurationInMs));
printCounter++;
if (enableThroughputSet) {
const double elapsedTimeInSecs =
std::chrono::duration<double>(steady_clock::now() - stepTime).count();
stepTime = steady_clock::now();
int byteToSendThisLoop = static_cast<int>(
byteToSendOnEveryLoop * ((elapsedTimeInSecs * 1000.0) / stepDurationInMs));
binary tempMessageData(byteToSendThisLoop);
fill(tempMessageData.begin(), tempMessageData.end(), std::byte(0xFF));
for (const auto &[label, dc] : dataChannelMap) {
if (dc->isOpen() && dc->bufferedAmount() <= bufferSize * byteToSendOnEveryLoop) {
dc->send(tempMessageData);
sentSizeMap.at(label) += tempMessageData.size();
}
}
}
if (printCounter >= STEP_COUNT_FOR_1_SEC) {
const double elapsedTimeInSecs =
std::chrono::duration<double>(steady_clock::now() - printTime).count();
printTime = steady_clock::now();
unsigned long receiveSpeedTotal = 0;
unsigned long sendSpeedTotal = 0;
cout << "#" << i / STEP_COUNT_FOR_1_SEC << endl;
for (const auto &[label, dc] : dataChannelMap) {
unsigned long channelReceiveSpeed = static_cast<int>(
receivedSizeMap[label].exchange(0) / (elapsedTimeInSecs * 1000));
unsigned long channelSendSpeed =
static_cast<int>(sentSizeMap[label].exchange(0) / (elapsedTimeInSecs * 1000));
cout << std::setw(10) << label << " Received: " << channelReceiveSpeed << " KB/s"
<< " Sent: " << channelSendSpeed << " KB/s"
<< " BufferSize: " << dc->bufferedAmount() << endl;
receiveSpeedTotal += channelReceiveSpeed;
sendSpeedTotal += channelSendSpeed;
}
cout << std::setw(10) << "TOTL"
<< " Received: " << receiveSpeedTotal << " KB/s"
<< " Sent: " << sendSpeedTotal << " KB/s" << endl;
printStatCounter++;
printCounter = 0;
}
if (printStatCounter >= 5) {
cout << "Stats# "
<< "Received Total: " << pc->bytesReceived() / (1000 * 1000) << " MB"
<< " Sent Total: " << pc->bytesSent() / (1000 * 1000) << " MB"
<< " RTT: " << pc->rtt().value_or(0ms).count() << " ms" << endl;
cout << endl;
printStatCounter = 0;
}
}
cout << "Cleaning up..." << endl;
dataChannelMap.clear();
peerConnectionMap.clear();
receivedSizeMap.clear();
sentSizeMap.clear();
return 0;
} catch (const std::exception &e) {
std::cout << "Error: " << e.what() << std::endl;
dataChannelMap.clear();
peerConnectionMap.clear();
receivedSizeMap.clear();
sentSizeMap.clear();
return -1;
}
// Create and setup a PeerConnection
shared_ptr<PeerConnection> createPeerConnection(const Configuration &config,
weak_ptr<WebSocket> wws, string id) {
auto pc = make_shared<PeerConnection>(config);
pc->onStateChange([](PeerConnection::State state) { cout << "State: " << state << endl; });
pc->onGatheringStateChange(
[](PeerConnection::GatheringState state) { cout << "Gathering State: " << state << endl; });
pc->onLocalDescription([wws, id](Description description) {
json message = {
{"id", id}, {"type", description.typeString()}, {"description", string(description)}};
if (auto ws = wws.lock())
ws->send(message.dump());
});
pc->onLocalCandidate([wws, id](Candidate candidate) {
json message = {{"id", id},
{"type", "candidate"},
{"candidate", string(candidate)},
{"mid", candidate.mid()}};
if (auto ws = wws.lock())
ws->send(message.dump());
});
pc->onDataChannel([id](shared_ptr<DataChannel> dc) {
const string label = dc->label();
cout << "DataChannel from " << id << " received with label \"" << label << "\"" << endl;
cout << "###########################################" << endl;
cout << "### Check other peer's screen for stats ###" << endl;
cout << "###########################################" << endl;
receivedSizeMap.emplace(dc->label(), 0);
sentSizeMap.emplace(dc->label(), 0);
// Set Buffer Size
dc->setBufferedAmountLowThreshold(bufferSize);
if (!noSend && !enableThroughputSet) {
try {
while (dc->bufferedAmount() <= bufferSize) {
dc->send(messageData);
sentSizeMap.at(label) += messageData.size();
}
} catch (const std::exception &e) {
std::cout << "Send failed: " << e.what() << std::endl;
}
}
if (!noSend && enableThroughputSet) {
// Create Send Data Thread
// Thread will join when data channel destroyed or closed
std::thread([wdc = make_weak_ptr(dc), label]() {
steady_clock::time_point stepTime = steady_clock::now();
// Byte count to send for every loop
int byteToSendOnEveryLoop = throughtputSetAsKB * stepDurationInMs;
while (true) {
this_thread::sleep_for(milliseconds(stepDurationInMs));
auto dcLocked = wdc.lock();
if (!dcLocked)
break;
if (!dcLocked->isOpen())
break;
try {
const double elapsedTimeInSecs =
std::chrono::duration<double>(steady_clock::now() - stepTime).count();
stepTime = steady_clock::now();
int byteToSendThisLoop =
static_cast<int>(byteToSendOnEveryLoop *
((elapsedTimeInSecs * 1000.0) / stepDurationInMs));
binary tempMessageData(byteToSendThisLoop);
fill(tempMessageData.begin(), tempMessageData.end(), std::byte(0xFF));
if (dcLocked->bufferedAmount() <= bufferSize) {
dcLocked->send(tempMessageData);
sentSizeMap.at(label) += tempMessageData.size();
}
} catch (const std::exception &e) {
std::cout << "Send failed: " << e.what() << std::endl;
}
}
cout << "Send Data Thread exiting..." << endl;
}).detach();
}
dc->onBufferedAmountLow([wdc = make_weak_ptr(dc), label]() {
if (noSend)
return;
if (enableThroughputSet)
return;
auto dcLocked = wdc.lock();
if (!dcLocked)
return;
// Continue sending
try {
while (dcLocked->isOpen() && dcLocked->bufferedAmount() <= bufferSize) {
dcLocked->send(messageData);
sentSizeMap.at(label) += messageData.size();
}
} catch (const std::exception &e) {
std::cout << "Send failed: " << e.what() << std::endl;
}
});
dc->onClosed([id]() { cout << "DataChannel from " << id << " closed" << endl; });
dc->onMessage([id, wdc = make_weak_ptr(dc), label](variant<binary, string> data) {
if (holds_alternative<binary>(data))
receivedSizeMap.at(label) += get<binary>(data).size();
});
dataChannelMap.emplace(label, dc);
});
peerConnectionMap.emplace(id, pc);
return pc;
};
// Helper function to generate a random ID
string randomId(size_t length) {
static const string characters(
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
string id(length, '0');
default_random_engine rng(random_device{}());
uniform_int_distribution<int> dist(0, int(characters.size() - 1));
generate(id.begin(), id.end(), [&]() { return characters.at(dist(rng)); });
return id;
}

View File

@ -1,216 +0,0 @@
/******************************************************************************
**
** parse_cl.cpp
**
** Thu Aug 6 19:42:25 2020
** Linux 5.4.0-42-generic (#46-Ubuntu SMP Fri Jul 10 00:24:02 UTC 2020) x86_64
** cerik@Erik-VBox-Ubuntu (Erik Cota-Robles)
**
** Copyright (c) 2020 Erik Cota-Robles
**
** Definition of command line parser class
**
** Automatically created by genparse v0.9.3
**
** See http://genparse.sourceforge.net for details and updates
**
**
******************************************************************************/
#include <stdlib.h>
#if defined(_WIN32) || defined(WIN32)
#include "getopt.h"
#else
#include <getopt.h>
#endif
#include "parse_cl.h"
/*----------------------------------------------------------------------------
**
** Cmdline::Cmdline ()
**
** Constructor method.
**
**--------------------------------------------------------------------------*/
Cmdline::Cmdline(int argc, char *argv[]) // ISO C++17 not allowed: throw (std::string )
{
extern char *optarg;
extern int optind;
int c;
static struct option long_options[] = {{"noStun", no_argument, NULL, 'n'},
{"stunServer", required_argument, NULL, 's'},
{"stunPort", required_argument, NULL, 't'},
{"webSocketServer", required_argument, NULL, 'w'},
{"webSocketPort", required_argument, NULL, 'x'},
{"durationInSec", required_argument, NULL, 'd'},
{"noSend", no_argument, NULL, 'o'},
{"enableThroughputSet", no_argument, NULL, 'p'},
{"throughtputSetAsKB", required_argument, NULL, 'r'},
{"bufferSize", required_argument, NULL, 'b'},
{"dataChannelCount", required_argument, NULL, 'c'},
{"help", no_argument, NULL, 'h'},
{NULL, 0, NULL, 0}};
_program_name += argv[0];
/* default values */
_n = false;
_s = "stun.l.google.com";
_t = 19302;
_w = "localhost";
_x = 8000;
_h = false;
_d = 300;
_o = false;
_p = false;
_r = 300;
_b = 0;
_c = 1;
optind = 0;
while ((c = getopt_long(argc, argv, "s:t:w:x:d:r:b:c:enhvop", long_options, &optind)) != -1) {
switch (c) {
case 'n':
_n = true;
break;
case 's':
_s = optarg;
break;
case 't':
_t = atoi(optarg);
if (_t < 0) {
std::string err;
err += "parameter range error: t must be >= 0";
throw(std::range_error(err));
}
if (_t > 65535) {
std::string err;
err += "parameter range error: t must be <= 65535";
throw(std::range_error(err));
}
break;
case 'w':
_w = optarg;
break;
case 'x':
_x = atoi(optarg);
if (_x < 0) {
std::string err;
err += "parameter range error: x must be >= 0";
throw(std::range_error(err));
}
if (_x > 65535) {
std::string err;
err += "parameter range error: x must be <= 65535";
throw(std::range_error(err));
}
break;
case 'd':
_d = atoi(optarg);
if (_d < 0) {
std::string err;
err += "parameter range error: d must be >= 0";
throw(std::range_error(err));
}
break;
case 'o':
_o = true;
break;
case 'b':
_b = atoi(optarg);
if (_b < 0) {
std::string err;
err += "parameter range error: b must be >= 0";
throw(std::range_error(err));
}
break;
case 'p':
_p = true;
break;
case 'r':
_r = atoi(optarg);
if (_r <= 0) {
std::string err;
err += "parameter range error: r must be > 0";
throw(std::range_error(err));
}
break;
case 'c':
_c = atoi(optarg);
if (_c <= 0) {
std::string err;
err += "parameter range error: c must be > 0";
throw(std::range_error(err));
}
break;
case 'h':
_h = true;
this->usage(EXIT_SUCCESS);
break;
default:
this->usage(EXIT_FAILURE);
}
} /* while */
_optind = optind;
}
/*----------------------------------------------------------------------------
**
** Cmdline::usage () and version()
**
** Print out usage (or version) information, then exit.
**
**--------------------------------------------------------------------------*/
void Cmdline::usage(int status) {
if (status != EXIT_SUCCESS)
std::cerr << "Try `" << _program_name << " --help' for more information.\n";
else {
std::cout << "\
usage: " << _program_name
<< " [ -enstwxdobprhv ] \n\
libdatachannel client implementing WebRTC Data Channels with WebSocket signaling\n\
[ -n ] [ --noStun ] (type=FLAG)\n\
Do NOT use a stun server (overrides -s and -t).\n\
[ -s ] [ --stunServer ] (type=STRING, default=stun.l.google.com)\n\
Stun server URL or IP address.\n\
[ -t ] [ --stunPort ] (type=INTEGER, range=0...65535, default=19302)\n\
Stun server port.\n\
[ -w ] [ --webSocketServer ] (type=STRING, default=localhost)\n\
Web socket server URL or IP address.\n\
[ -x ] [ --webSocketPort ] (type=INTEGER, range=0...65535, default=8000)\n\
Web socket server port.\n\
[ -d ] [ --durationInSec ] (type=INTEGER, range>=0...INT32_MAX, 0:infinite(INT32_MAX), Valid only for offering client, default=300)\n\
Benchmark duration in seconds.\n\
[ -o ] [ --noSend ] (type=FLAG)\n\
Do NOT send message (Only Receive, for one-way testing purposes).\n\
[ -b ] [ --bufferSize ] (type=INTEGER, range>0...INT_MAX, default=0)\n\
Set internal buffer size .\n\
[ -p ] [ --enableThroughputSet ] (type=FLAG)\n\
Send a constant data per second (KB). See throughtputSetAsKB params.\n\
[ -r ] [ --throughtputSetAsKB ] (type=INTEGER, range>0...INT_MAX, default=300)\n\
Send constant data per second (KB).\n\
[ -c ] [ --dataChannelCount ] (type=INTEGER, range>0...INT_MAX, default=1)\n\
Dat Channel count to create.\n\
[ -h ] [ --help ] (type=FLAG)\n\
Display this help and exit.\n";
}
exit(status);
}

View File

@ -1,79 +0,0 @@
/******************************************************************************
**
** parse_cl.h
**
** Thu Aug 6 19:42:25 2020
** Linux 5.4.0-42-generic (#46-Ubuntu SMP Fri Jul 10 00:24:02 UTC 2020) x86_64
** cerik@Erik-VBox-Ubuntu (Erik Cota-Robles)
**
** Copyright (c) 2020 Erik Cota-Robles
**
** Header file for command line parser class
**
** Automatically created by genparse v0.9.3
**
** See http://genparse.sourceforge.net for details and updates
**
******************************************************************************/
#ifndef CMDLINE_H
#define CMDLINE_H
#include <iostream>
#include <string>
/*----------------------------------------------------------------------------
**
** class Cmdline
**
** command line parser class
**
**--------------------------------------------------------------------------*/
class Cmdline
{
private:
/* parameters */
bool _n;
std::string _s;
int _t;
std::string _w;
int _x;
bool _h;
int _d;
bool _o;
bool _p;
int _r;
int _b;
int _c;
/* other stuff to keep track of */
std::string _program_name;
int _optind;
public:
/* constructor and destructor */
Cmdline (int, char **); // ISO C++17 not allowed: throw (std::string);
~Cmdline (){}
/* usage function */
void usage (int status);
/* return next (non-option) parameter */
int next_param () { return _optind; }
bool noStun () const { return _n; }
std::string stunServer () const { return _s; }
int stunPort () const { return _t; }
std::string webSocketServer () const { return _w; }
int webSocketPort () const { return _x; }
bool h () const { return _h; }
int durationInSec () const { return _d; }
bool noSend () const { return _o; }
int bufferSize() const { return _b; }
bool enableThroughputSet () const { return _p; }
int throughtputSetAsKB() const { return _r; }
int dataChannelCount() const { return _c; }
};
#endif

View File

@ -3,25 +3,11 @@ if(POLICY CMP0079)
cmake_policy(SET CMP0079 NEW)
endif()
set(CLIENT_UWP_RESOURCES
uwp/Logo.png
uwp/package.appxManifest
uwp/SmallLogo.png
uwp/SmallLogo44x44.png
uwp/SplashScreen.png
uwp/StoreLogo.png
uwp/Windows_TemporaryKey.pfx
)
if(WIN32)
if(CMAKE_SYSTEM_NAME STREQUAL "WindowsStore")
add_executable(datachannel-client main.cpp parse_cl.cpp parse_cl.h getopt.cpp getopt.h ${CLIENT_UWP_RESOURCES})
else()
add_executable(datachannel-client main.cpp parse_cl.cpp parse_cl.h getopt.cpp getopt.h)
endif()
target_compile_definitions(datachannel-client PUBLIC STATIC_GETOPT)
add_executable(datachannel-client main.cpp parse_cl.cpp parse_cl.h getopt.cpp getopt.h)
target_compile_definitions(datachannel-client PUBLIC STATIC_GETOPT)
else()
add_executable(datachannel-client main.cpp parse_cl.cpp parse_cl.h)
add_executable(datachannel-client main.cpp parse_cl.cpp parse_cl.h)
endif()
set_target_properties(datachannel-client PROPERTIES
@ -29,10 +15,3 @@ set_target_properties(datachannel-client PROPERTIES
OUTPUT_NAME client)
target_link_libraries(datachannel-client datachannel nlohmann_json)
if(WIN32)
add_custom_command(TARGET datachannel-client POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_if_different
"$<TARGET_FILE_DIR:datachannel>/datachannel.dll"
$<TARGET_FILE_DIR:datachannel-client>
)
endif()

View File

@ -54,20 +54,20 @@ shared_ptr<PeerConnection> createPeerConnection(const Configuration &config,
string randomId(size_t length);
int main(int argc, char **argv) try {
Cmdline params(argc, argv);
auto params = std::make_unique<Cmdline>(argc, argv);
rtc::InitLogger(LogLevel::Info);
Configuration config;
string stunServer = "";
if (params.noStun()) {
if (params->noStun()) {
cout << "No STUN server is configured. Only local hosts and public IP addresses supported."
<< endl;
} else {
if (params.stunServer().substr(0, 5).compare("stun:") != 0) {
if (params->stunServer().substr(0, 5).compare("stun:") != 0) {
stunServer = "stun:";
}
stunServer += params.stunServer() + ":" + to_string(params.stunPort());
stunServer += params->stunServer() + ":" + to_string(params->stunPort());
cout << "Stun server is " << stunServer << endl;
config.iceServers.emplace_back(stunServer);
}
@ -129,11 +129,11 @@ int main(int argc, char **argv) try {
});
string wsPrefix = "";
if (params.webSocketServer().substr(0, 5).compare("ws://") != 0) {
if (params->webSocketServer().substr(0, 5).compare("ws://") != 0) {
wsPrefix = "ws://";
}
const string url = wsPrefix + params.webSocketServer() + ":" +
to_string(params.webSocketPort()) + "/" + localId;
const string url = wsPrefix + params->webSocketServer() + ":" +
to_string(params->webSocketPort()) + "/" + localId;
cout << "Url is " << url << endl;
ws->open(url);
@ -222,14 +222,9 @@ shared_ptr<PeerConnection> createPeerConnection(const Configuration &config,
cout << "DataChannel from " << id << " received with label \"" << dc->label() << "\""
<< endl;
dc->onOpen([wdc = make_weak_ptr(dc)]() {
if (auto dc = wdc.lock())
dc->send("Hello from " + localId);
});
dc->onClosed([id]() { cout << "DataChannel from " << id << " closed" << endl; });
dc->onMessage([id](variant<binary, string> data) {
dc->onMessage([id, wdc = make_weak_ptr(dc)](variant<binary, string> data) {
if (holds_alternative<string>(data))
cout << "Message from " << id << " received: " << get<string>(data) << endl;
else
@ -237,6 +232,8 @@ shared_ptr<PeerConnection> createPeerConnection(const Configuration &config,
<< " received, size=" << get<binary>(data).size() << endl;
});
dc->send("Hello from " + localId);
dataChannelMap.emplace(id, dc);
});

Binary file not shown.

Before

Width:  |  Height:  |  Size: 488 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 167 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 265 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 909 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 227 B

View File

@ -1,42 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Package
xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest"
xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"
xmlns:desktop4="http://schemas.microsoft.com/appx/manifest/desktop/windows10/4"
xmlns:iot2="http://schemas.microsoft.com/appx/manifest/iot/windows10/2"
IgnorableNamespaces="uap mp">
<Identity Name="274EF42C-A3FB-3D6C-B127-E39C508A4F0E" Publisher="CN=CMake" Version="1.0.0.0" />
<mp:PhoneIdentity PhoneProductId="274EF42C-A3FB-3D6C-B127-E39C508A4F0E" PhonePublisherId="00000000-0000-0000-0000-000000000000"/>
<Properties>
<DisplayName>datachannel-client</DisplayName>
<PublisherDisplayName>CMake</PublisherDisplayName>
<Logo>StoreLogo.png</Logo>
</Properties>
<Dependencies>
<TargetDeviceFamily Name="Windows.Universal" MinVersion="10.0.0.0" MaxVersionTested="10.0.0.0" />
</Dependencies>
<Resources>
<Resource Language="x-generate" />
</Resources>
<Applications>
<Application
Id="App"
Executable="client.exe"
EntryPoint="datachannel-client.App"
desktop4:Subsystem="console"
desktop4:SupportsMultipleInstances="true"
iot2:Subsystem="console"
iot2:SupportsMultipleInstances="true">
<uap:VisualElements
DisplayName="datachannel-client"
Description="datachannel-client"
BackgroundColor="#336699"
Square150x150Logo="Logo.png"
Square44x44Logo="SmallLogo44x44.png">
<uap:SplashScreen Image="SplashScreen.png" />
</uap:VisualElements>
</Application>
</Applications>
</Package>

View File

@ -3,53 +3,13 @@ project(offerer C)
set(CMAKE_C_STANDARD 11)
set(OFFERER_UWP_RESOURCES
uwp/offerer/Logo.png
uwp/offerer/package.appxManifest
uwp/offerer/SmallLogo.png
uwp/offerer/SmallLogo44x44.png
uwp/offerer/SplashScreen.png
uwp/offerer/StoreLogo.png
uwp/offerer/Windows_TemporaryKey.pfx
)
set(ANSWERER_UWP_RESOURCES
uwp/answerer/Logo.png
uwp/answerer/package.appxManifest
uwp/answerer/SmallLogo.png
uwp/answerer/SmallLogo44x44.png
uwp/answerer/SplashScreen.png
uwp/answerer/StoreLogo.png
uwp/answerer/Windows_TemporaryKey.pfx
)
if(CMAKE_SYSTEM_NAME STREQUAL "WindowsStore")
add_executable(datachannel-copy-paste-capi-offerer offerer.c ${OFFERER_UWP_RESOURCES})
else()
add_executable(datachannel-copy-paste-capi-offerer offerer.c)
endif()
add_executable(datachannel-copy-paste-capi-offerer offerer.c)
set_target_properties(datachannel-copy-paste-capi-offerer PROPERTIES
OUTPUT_NAME offerer)
target_link_libraries(datachannel-copy-paste-capi-offerer datachannel)
if(CMAKE_SYSTEM_NAME STREQUAL "WindowsStore")
add_executable(datachannel-copy-paste-capi-answerer answerer.c ${ANSWERER_UWP_RESOURCES})
else()
add_executable(datachannel-copy-paste-capi-answerer answerer.c)
endif()
add_executable(datachannel-copy-paste-capi-answerer answerer.c)
set_target_properties(datachannel-copy-paste-capi-answerer PROPERTIES
OUTPUT_NAME answerer)
target_link_libraries(datachannel-copy-paste-capi-answerer datachannel)
if(WIN32)
add_custom_command(TARGET datachannel-copy-paste-capi-offerer POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_if_different
"$<TARGET_FILE_DIR:datachannel>/datachannel.dll"
$<TARGET_FILE_DIR:datachannel-copy-paste-capi-offerer>
)
add_custom_command(TARGET datachannel-copy-paste-capi-answerer POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_if_different
"$<TARGET_FILE_DIR:datachannel>/datachannel.dll"
$<TARGET_FILE_DIR:datachannel-copy-paste-capi-answerer>
)
endif()

Binary file not shown.

Before

Width:  |  Height:  |  Size: 488 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 167 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 265 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 909 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 227 B

View File

@ -1,42 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Package
xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest"
xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"
xmlns:desktop4="http://schemas.microsoft.com/appx/manifest/desktop/windows10/4"
xmlns:iot2="http://schemas.microsoft.com/appx/manifest/iot/windows10/2"
IgnorableNamespaces="uap mp">
<Identity Name="9751ACA6-5428-3AF2-AED6-2DDA8D2FD777" Publisher="CN=CMake" Version="1.0.0.0" />
<mp:PhoneIdentity PhoneProductId="9751ACA6-5428-3AF2-AED6-2DDA8D2FD777" PhonePublisherId="00000000-0000-0000-0000-000000000000"/>
<Properties>
<DisplayName>datachannel-copy-paste-capi-answerer</DisplayName>
<PublisherDisplayName>CMake</PublisherDisplayName>
<Logo>StoreLogo.png</Logo>
</Properties>
<Dependencies>
<TargetDeviceFamily Name="Windows.Universal" MinVersion="10.0.0.0" MaxVersionTested="10.0.0.0" />
</Dependencies>
<Resources>
<Resource Language="x-generate" />
</Resources>
<Applications>
<Application
Id="App"
Executable="answerer.exe"
EntryPoint="datachannel-copy-paste-capi-answerer.App"
desktop4:Subsystem="console"
desktop4:SupportsMultipleInstances="true"
iot2:Subsystem="console"
iot2:SupportsMultipleInstances="true">
<uap:VisualElements
DisplayName="datachannel-copy-paste-capi-answerer"
Description="datachannel-copy-paste-capi-answerer"
BackgroundColor="#336699"
Square150x150Logo="Logo.png"
Square44x44Logo="SmallLogo44x44.png">
<uap:SplashScreen Image="SplashScreen.png" />
</uap:VisualElements>
</Application>
</Applications>
</Package>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 488 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 167 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 265 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 909 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 227 B

View File

@ -1,42 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Package
xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest"
xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"
xmlns:desktop4="http://schemas.microsoft.com/appx/manifest/desktop/windows10/4"
xmlns:iot2="http://schemas.microsoft.com/appx/manifest/iot/windows10/2"
IgnorableNamespaces="uap mp">
<Identity Name="D63472B9-2085-3CA0-96B2-895D164F4155" Publisher="CN=CMake" Version="1.0.0.0" />
<mp:PhoneIdentity PhoneProductId="D63472B9-2085-3CA0-96B2-895D164F4155" PhonePublisherId="00000000-0000-0000-0000-000000000000"/>
<Properties>
<DisplayName>datachannel-copy-paste-capi-offerer</DisplayName>
<PublisherDisplayName>CMake</PublisherDisplayName>
<Logo>StoreLogo.png</Logo>
</Properties>
<Dependencies>
<TargetDeviceFamily Name="Windows.Universal" MinVersion="10.0.0.0" MaxVersionTested="10.0.0.0" />
</Dependencies>
<Resources>
<Resource Language="x-generate" />
</Resources>
<Applications>
<Application
Id="App"
Executable="offerer.exe"
EntryPoint="datachannel-copy-paste-capi-offerer.App"
desktop4:Subsystem="console"
desktop4:SupportsMultipleInstances="true"
iot2:Subsystem="console"
iot2:SupportsMultipleInstances="true">
<uap:VisualElements
DisplayName="datachannel-copy-paste-capi-offerer"
Description="datachannel-copy-paste-capi-offerer"
BackgroundColor="#336699"
Square150x150Logo="Logo.png"
Square44x44Logo="SmallLogo44x44.png">
<uap:SplashScreen Image="SplashScreen.png" />
</uap:VisualElements>
</Application>
</Applications>
</Package>

View File

@ -1,54 +1,14 @@
cmake_minimum_required(VERSION 3.7)
set(OFFERER_UWP_RESOURCES
uwp/offerer/Logo.png
uwp/offerer/package.appxManifest
uwp/offerer/SmallLogo.png
uwp/offerer/SmallLogo44x44.png
uwp/offerer/SplashScreen.png
uwp/offerer/StoreLogo.png
uwp/offerer/Windows_TemporaryKey.pfx
)
set(ANSWERER_UWP_RESOURCES
uwp/answerer/Logo.png
uwp/answerer/package.appxManifest
uwp/answerer/SmallLogo.png
uwp/answerer/SmallLogo44x44.png
uwp/answerer/SplashScreen.png
uwp/answerer/StoreLogo.png
uwp/answerer/Windows_TemporaryKey.pfx
)
if(CMAKE_SYSTEM_NAME STREQUAL "WindowsStore")
add_executable(datachannel-copy-paste-offerer offerer.cpp ${OFFERER_UWP_RESOURCES})
else()
add_executable(datachannel-copy-paste-offerer offerer.cpp)
endif()
add_executable(datachannel-copy-paste-offerer offerer.cpp)
set_target_properties(datachannel-copy-paste-offerer PROPERTIES
CXX_STANDARD 17
OUTPUT_NAME offerer)
target_link_libraries(datachannel-copy-paste-offerer datachannel)
if(CMAKE_SYSTEM_NAME STREQUAL "WindowsStore")
add_executable(datachannel-copy-paste-answerer answerer.cpp ${ANSWERER_UWP_RESOURCES})
else()
add_executable(datachannel-copy-paste-answerer answerer.cpp)
endif()
add_executable(datachannel-copy-paste-answerer answerer.cpp)
set_target_properties(datachannel-copy-paste-answerer PROPERTIES
CXX_STANDARD 17
OUTPUT_NAME answerer)
target_link_libraries(datachannel-copy-paste-answerer datachannel)
if(WIN32)
add_custom_command(TARGET datachannel-copy-paste-offerer POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_if_different
"$<TARGET_FILE_DIR:datachannel>/datachannel.dll"
$<TARGET_FILE_DIR:datachannel-copy-paste-offerer>
)
add_custom_command(TARGET datachannel-copy-paste-answerer POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_if_different
"$<TARGET_FILE_DIR:datachannel>/datachannel.dll"
$<TARGET_FILE_DIR:datachannel-copy-paste-answerer>
)
endif()

Binary file not shown.

Before

Width:  |  Height:  |  Size: 488 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 167 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 265 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 909 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 227 B

View File

@ -1,42 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Package
xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest"
xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"
xmlns:desktop4="http://schemas.microsoft.com/appx/manifest/desktop/windows10/4"
xmlns:iot2="http://schemas.microsoft.com/appx/manifest/iot/windows10/2"
IgnorableNamespaces="uap mp">
<Identity Name="86FAC2A3-40CD-393F-9F55-52A30E0D3B8F" Publisher="CN=CMake" Version="1.0.0.0" />
<mp:PhoneIdentity PhoneProductId="86FAC2A3-40CD-393F-9F55-52A30E0D3B8F" PhonePublisherId="00000000-0000-0000-0000-000000000000"/>
<Properties>
<DisplayName>datachannel-copy-paste-answerer</DisplayName>
<PublisherDisplayName>CMake</PublisherDisplayName>
<Logo>StoreLogo.png</Logo>
</Properties>
<Dependencies>
<TargetDeviceFamily Name="Windows.Universal" MinVersion="10.0.0.0" MaxVersionTested="10.0.0.0" />
</Dependencies>
<Resources>
<Resource Language="x-generate" />
</Resources>
<Applications>
<Application
Id="App"
Executable="answerer.exe"
EntryPoint="datachannel-copy-paste-answerer.App"
desktop4:Subsystem="console"
desktop4:SupportsMultipleInstances="true"
iot2:Subsystem="console"
iot2:SupportsMultipleInstances="true">
<uap:VisualElements
DisplayName="datachannel-copy-paste-answerer"
Description="datachannel-copy-paste-answerer"
BackgroundColor="#336699"
Square150x150Logo="Logo.png"
Square44x44Logo="SmallLogo44x44.png">
<uap:SplashScreen Image="SplashScreen.png" />
</uap:VisualElements>
</Application>
</Applications>
</Package>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 488 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 167 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 265 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 909 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 227 B

View File

@ -1,42 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Package
xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest"
xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"
xmlns:desktop4="http://schemas.microsoft.com/appx/manifest/desktop/windows10/4"
xmlns:iot2="http://schemas.microsoft.com/appx/manifest/iot/windows10/2"
IgnorableNamespaces="uap mp">
<Identity Name="68160929-CE5F-3FC1-A120-BCB1C223FC2F" Publisher="CN=CMake" Version="1.0.0.0" />
<mp:PhoneIdentity PhoneProductId="68160929-CE5F-3FC1-A120-BCB1C223FC2F" PhonePublisherId="00000000-0000-0000-0000-000000000000"/>
<Properties>
<DisplayName>datachannel-copy-paste-offerer</DisplayName>
<PublisherDisplayName>CMake</PublisherDisplayName>
<Logo>StoreLogo.png</Logo>
</Properties>
<Dependencies>
<TargetDeviceFamily Name="Windows.Universal" MinVersion="10.0.0.0" MaxVersionTested="10.0.0.0" />
</Dependencies>
<Resources>
<Resource Language="x-generate" />
</Resources>
<Applications>
<Application
Id="App"
Executable="offerer.exe"
EntryPoint="datachannel-copy-paste-offerer.App"
desktop4:Subsystem="console"
desktop4:SupportsMultipleInstances="true"
iot2:Subsystem="console"
iot2:SupportsMultipleInstances="true">
<uap:VisualElements
DisplayName="datachannel-copy-paste-offerer"
Description="datachannel-copy-paste-offerer"
BackgroundColor="#336699"
Square150x150Logo="Logo.png"
Square44x44Logo="SmallLogo44x44.png">
<uap:SplashScreen Image="SplashScreen.png" />
</uap:VisualElements>
</Application>
</Applications>
</Package>

View File

@ -1,29 +1,8 @@
cmake_minimum_required(VERSION 3.7)
set(MEDIA_UWP_RESOURCES
uwp/Logo.png
uwp/package.appxManifest
uwp/SmallLogo.png
uwp/SmallLogo44x44.png
uwp/SplashScreen.png
uwp/StoreLogo.png
uwp/Windows_TemporaryKey.pfx
)
if(CMAKE_SYSTEM_NAME STREQUAL "WindowsStore")
add_executable(datachannel-media main.cpp ${MEDIA_UWP_RESOURCES})
else()
add_executable(datachannel-media main.cpp)
endif()
add_executable(datachannel-media main.cpp)
set_target_properties(datachannel-media PROPERTIES
CXX_STANDARD 17
OUTPUT_NAME media)
target_link_libraries(datachannel-media datachannel nlohmann_json)
if(WIN32)
add_custom_command(TARGET datachannel-media POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_if_different
"$<TARGET_FILE_DIR:datachannel>/datachannel.dll"
$<TARGET_FILE_DIR:datachannel-media>
)
endif()

View File

@ -68,7 +68,7 @@ int main() {
auto track = pc->addTrack(media);
auto session = std::make_shared<rtc::RtcpReceivingSession>();
track->setMediaHandler(session);
track->setRtcpHandler(session);
track->onMessage(
[session, sock, addr](rtc::binary message) {

Binary file not shown.

Before

Width:  |  Height:  |  Size: 488 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 167 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 265 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 909 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 227 B

View File

@ -1,42 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Package
xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest"
xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"
xmlns:desktop4="http://schemas.microsoft.com/appx/manifest/desktop/windows10/4"
xmlns:iot2="http://schemas.microsoft.com/appx/manifest/iot/windows10/2"
IgnorableNamespaces="uap mp">
<Identity Name="6597869B-290B-3EC7-AC50-87D2B9B408A2" Publisher="CN=CMake" Version="1.0.0.0" />
<mp:PhoneIdentity PhoneProductId="6597869B-290B-3EC7-AC50-87D2B9B408A2" PhonePublisherId="00000000-0000-0000-0000-000000000000"/>
<Properties>
<DisplayName>datachannel-media</DisplayName>
<PublisherDisplayName>CMake</PublisherDisplayName>
<Logo>StoreLogo.png</Logo>
</Properties>
<Dependencies>
<TargetDeviceFamily Name="Windows.Universal" MinVersion="10.0.0.0" MaxVersionTested="10.0.0.0" />
</Dependencies>
<Resources>
<Resource Language="x-generate" />
</Resources>
<Applications>
<Application
Id="App"
Executable="media.exe"
EntryPoint="datachannel-media.App"
desktop4:Subsystem="console"
desktop4:SupportsMultipleInstances="true"
iot2:Subsystem="console"
iot2:SupportsMultipleInstances="true">
<uap:VisualElements
DisplayName="datachannel-media"
Description="datachannel-media"
BackgroundColor="#336699"
Square150x150Logo="Logo.png"
Square44x44Logo="SmallLogo44x44.png">
<uap:SplashScreen Image="SplashScreen.png" />
</uap:VisualElements>
</Application>
</Applications>
</Package>

View File

@ -1,29 +1,8 @@
cmake_minimum_required(VERSION 3.7)
set(SFU_MEDIA_UWP_RESOURCES
uwp/Logo.png
uwp/package.appxManifest
uwp/SmallLogo.png
uwp/SmallLogo44x44.png
uwp/SplashScreen.png
uwp/StoreLogo.png
uwp/Windows_TemporaryKey.pfx
)
if(CMAKE_SYSTEM_NAME STREQUAL "WindowsStore")
add_executable(datachannel-sfu-media main.cpp ${SFU_MEDIA_UWP_RESOURCES})
else()
add_executable(datachannel-sfu-media main.cpp)
endif()
add_executable(datachannel-sfu-media main.cpp)
set_target_properties(datachannel-sfu-media PROPERTIES
CXX_STANDARD 17
OUTPUT_NAME sfu-media)
target_link_libraries(datachannel-sfu-media datachannel nlohmann_json)
if(WIN32)
add_custom_command(TARGET datachannel-sfu-media POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_if_different
"$<TARGET_FILE_DIR:datachannel>/datachannel.dll"
$<TARGET_FILE_DIR:datachannel-sfu-media>
)
endif()

View File

@ -60,7 +60,7 @@ int main() {
pc->setLocalDescription();
auto session = std::make_shared<rtc::RtcpReceivingSession>();
track->setMediaHandler(session);
track->setRtcpHandler(session);
const rtc::SSRC targetSSRC = 4;

Binary file not shown.

Before

Width:  |  Height:  |  Size: 488 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 167 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 265 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 909 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 227 B

View File

@ -1,42 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Package
xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest"
xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"
xmlns:desktop4="http://schemas.microsoft.com/appx/manifest/desktop/windows10/4"
xmlns:iot2="http://schemas.microsoft.com/appx/manifest/iot/windows10/2"
IgnorableNamespaces="uap mp">
<Identity Name="A2137F64-F4DB-39E1-8A6E-19BF1A64645A" Publisher="CN=CMake" Version="1.0.0.0" />
<mp:PhoneIdentity PhoneProductId="A2137F64-F4DB-39E1-8A6E-19BF1A64645A" PhonePublisherId="00000000-0000-0000-0000-000000000000"/>
<Properties>
<DisplayName>datachannel-sfu-media</DisplayName>
<PublisherDisplayName>CMake</PublisherDisplayName>
<Logo>StoreLogo.png</Logo>
</Properties>
<Dependencies>
<TargetDeviceFamily Name="Windows.Universal" MinVersion="10.0.0.0" MaxVersionTested="10.0.0.0" />
</Dependencies>
<Resources>
<Resource Language="x-generate" />
</Resources>
<Applications>
<Application
Id="App"
Executable="sfu-media.exe"
EntryPoint="datachannel-sfu-media.App"
desktop4:Subsystem="console"
desktop4:SupportsMultipleInstances="true"
iot2:Subsystem="console"
iot2:SupportsMultipleInstances="true">
<uap:VisualElements
DisplayName="datachannel-sfu-media"
Description="datachannel-sfu-media"
BackgroundColor="#336699"
Square150x150Logo="Logo.png"
Square44x44Logo="SmallLogo44x44.png">
<uap:SplashScreen Image="SplashScreen.png" />
</uap:VisualElements>
</Application>
</Applications>
</Package>

View File

@ -1,339 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

View File

@ -1,285 +0,0 @@
{
"name": "libdatachannel-signaling-server",
"version": "0.1.0",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "libdatachannel-signaling-server",
"version": "0.1.0",
"license": "GPL-2.0",
"dependencies": {
"websocket": "^1.0.34"
}
},
"node_modules/bufferutil": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/bufferutil/-/bufferutil-4.0.2.tgz",
"integrity": "sha512-AtnG3W6M8B2n4xDQ5R+70EXvOpnXsFYg/AK2yTZd+HQ/oxAdz+GI+DvjmhBw3L0ole+LJ0ngqY4JMbDzkfNzhA==",
"hasInstallScript": true,
"dependencies": {
"node-gyp-build": "^4.2.0"
}
},
"node_modules/d": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/d/-/d-1.0.1.tgz",
"integrity": "sha512-m62ShEObQ39CfralilEQRjH6oAMtNCV1xJyEx5LpRYUVN+EviphDgUc/F3hnYbADmkiNs67Y+3ylmlG7Lnu+FA==",
"dependencies": {
"es5-ext": "^0.10.50",
"type": "^1.0.1"
}
},
"node_modules/debug": {
"version": "2.6.9",
"resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
"integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
"dependencies": {
"ms": "2.0.0"
}
},
"node_modules/es5-ext": {
"version": "0.10.53",
"resolved": "https://registry.npmjs.org/es5-ext/-/es5-ext-0.10.53.tgz",
"integrity": "sha512-Xs2Stw6NiNHWypzRTY1MtaG/uJlwCk8kH81920ma8mvN8Xq1gsfhZvpkImLQArw8AHnv8MT2I45J3c0R8slE+Q==",
"dependencies": {
"es6-iterator": "~2.0.3",
"es6-symbol": "~3.1.3",
"next-tick": "~1.0.0"
}
},
"node_modules/es6-iterator": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/es6-iterator/-/es6-iterator-2.0.3.tgz",
"integrity": "sha1-p96IkUGgWpSwhUQDstCg+/qY87c=",
"dependencies": {
"d": "1",
"es5-ext": "^0.10.35",
"es6-symbol": "^3.1.1"
}
},
"node_modules/es6-symbol": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/es6-symbol/-/es6-symbol-3.1.3.tgz",
"integrity": "sha512-NJ6Yn3FuDinBaBRWl/q5X/s4koRHBrgKAu+yGI6JCBeiu3qrcbJhwT2GeR/EXVfylRk8dpQVJoLEFhK+Mu31NA==",
"dependencies": {
"d": "^1.0.1",
"ext": "^1.1.2"
}
},
"node_modules/ext": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/ext/-/ext-1.4.0.tgz",
"integrity": "sha512-Key5NIsUxdqKg3vIsdw9dSuXpPCQ297y6wBjL30edxwPgt2E44WcWBZey/ZvUc6sERLTxKdyCu4gZFmUbk1Q7A==",
"dependencies": {
"type": "^2.0.0"
}
},
"node_modules/ext/node_modules/type": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/type/-/type-2.1.0.tgz",
"integrity": "sha512-G9absDWvhAWCV2gmF1zKud3OyC61nZDwWvBL2DApaVFogI07CprggiQAOOjvp2NRjYWFzPyu7vwtDrQFq8jeSA=="
},
"node_modules/is-typedarray": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz",
"integrity": "sha1-5HnICFjfDBsR3dppQPlgEfzaSpo="
},
"node_modules/ms": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g="
},
"node_modules/next-tick": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/next-tick/-/next-tick-1.0.0.tgz",
"integrity": "sha1-yobR/ogoFpsBICCOPchCS524NCw="
},
"node_modules/node-gyp-build": {
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.2.3.tgz",
"integrity": "sha512-MN6ZpzmfNCRM+3t57PTJHgHyw/h4OWnZ6mR8P5j/uZtqQr46RRuDE/P+g3n0YR/AiYXeWixZZzaip77gdICfRg==",
"bin": {
"node-gyp-build": "bin.js",
"node-gyp-build-optional": "optional.js",
"node-gyp-build-test": "build-test.js"
}
},
"node_modules/type": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/type/-/type-1.2.0.tgz",
"integrity": "sha512-+5nt5AAniqsCnu2cEQQdpzCAh33kVx8n0VoFidKpB1dVVLAN/F+bgVOqOJqOnEnrhp222clB5p3vUlD+1QAnfg=="
},
"node_modules/typedarray-to-buffer": {
"version": "3.1.5",
"resolved": "https://registry.npmjs.org/typedarray-to-buffer/-/typedarray-to-buffer-3.1.5.tgz",
"integrity": "sha512-zdu8XMNEDepKKR+XYOXAVPtWui0ly0NtohUscw+UmaHiAWT8hrV1rr//H6V+0DvJ3OQ19S979M0laLfX8rm82Q==",
"dependencies": {
"is-typedarray": "^1.0.0"
}
},
"node_modules/utf-8-validate": {
"version": "5.0.3",
"resolved": "https://registry.npmjs.org/utf-8-validate/-/utf-8-validate-5.0.3.tgz",
"integrity": "sha512-jtJM6fpGv8C1SoH4PtG22pGto6x+Y8uPprW0tw3//gGFhDDTiuksgradgFN6yRayDP4SyZZa6ZMGHLIa17+M8A==",
"hasInstallScript": true,
"dependencies": {
"node-gyp-build": "^4.2.0"
}
},
"node_modules/websocket": {
"version": "1.0.34",
"resolved": "https://registry.npmjs.org/websocket/-/websocket-1.0.34.tgz",
"integrity": "sha512-PRDso2sGwF6kM75QykIesBijKSVceR6jL2G8NGYyq2XrItNC2P5/qL5XeR056GhA+Ly7JMFvJb9I312mJfmqnQ==",
"dependencies": {
"bufferutil": "^4.0.1",
"debug": "^2.2.0",
"es5-ext": "^0.10.50",
"typedarray-to-buffer": "^3.1.5",
"utf-8-validate": "^5.0.2",
"yaeti": "^0.0.6"
},
"engines": {
"node": ">=4.0.0"
}
},
"node_modules/yaeti": {
"version": "0.0.6",
"resolved": "https://registry.npmjs.org/yaeti/-/yaeti-0.0.6.tgz",
"integrity": "sha1-8m9ITXJoTPQr7ft2lwqhYI+/lXc=",
"engines": {
"node": ">=0.10.32"
}
}
},
"dependencies": {
"bufferutil": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/bufferutil/-/bufferutil-4.0.2.tgz",
"integrity": "sha512-AtnG3W6M8B2n4xDQ5R+70EXvOpnXsFYg/AK2yTZd+HQ/oxAdz+GI+DvjmhBw3L0ole+LJ0ngqY4JMbDzkfNzhA==",
"requires": {
"node-gyp-build": "^4.2.0"
}
},
"d": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/d/-/d-1.0.1.tgz",
"integrity": "sha512-m62ShEObQ39CfralilEQRjH6oAMtNCV1xJyEx5LpRYUVN+EviphDgUc/F3hnYbADmkiNs67Y+3ylmlG7Lnu+FA==",
"requires": {
"es5-ext": "^0.10.50",
"type": "^1.0.1"
}
},
"debug": {
"version": "2.6.9",
"resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
"integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
"requires": {
"ms": "2.0.0"
}
},
"es5-ext": {
"version": "0.10.53",
"resolved": "https://registry.npmjs.org/es5-ext/-/es5-ext-0.10.53.tgz",
"integrity": "sha512-Xs2Stw6NiNHWypzRTY1MtaG/uJlwCk8kH81920ma8mvN8Xq1gsfhZvpkImLQArw8AHnv8MT2I45J3c0R8slE+Q==",
"requires": {
"es6-iterator": "~2.0.3",
"es6-symbol": "~3.1.3",
"next-tick": "~1.0.0"
}
},
"es6-iterator": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/es6-iterator/-/es6-iterator-2.0.3.tgz",
"integrity": "sha1-p96IkUGgWpSwhUQDstCg+/qY87c=",
"requires": {
"d": "1",
"es5-ext": "^0.10.35",
"es6-symbol": "^3.1.1"
}
},
"es6-symbol": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/es6-symbol/-/es6-symbol-3.1.3.tgz",
"integrity": "sha512-NJ6Yn3FuDinBaBRWl/q5X/s4koRHBrgKAu+yGI6JCBeiu3qrcbJhwT2GeR/EXVfylRk8dpQVJoLEFhK+Mu31NA==",
"requires": {
"d": "^1.0.1",
"ext": "^1.1.2"
}
},
"ext": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/ext/-/ext-1.4.0.tgz",
"integrity": "sha512-Key5NIsUxdqKg3vIsdw9dSuXpPCQ297y6wBjL30edxwPgt2E44WcWBZey/ZvUc6sERLTxKdyCu4gZFmUbk1Q7A==",
"requires": {
"type": "^2.0.0"
},
"dependencies": {
"type": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/type/-/type-2.1.0.tgz",
"integrity": "sha512-G9absDWvhAWCV2gmF1zKud3OyC61nZDwWvBL2DApaVFogI07CprggiQAOOjvp2NRjYWFzPyu7vwtDrQFq8jeSA=="
}
}
},
"is-typedarray": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz",
"integrity": "sha1-5HnICFjfDBsR3dppQPlgEfzaSpo="
},
"ms": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g="
},
"next-tick": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/next-tick/-/next-tick-1.0.0.tgz",
"integrity": "sha1-yobR/ogoFpsBICCOPchCS524NCw="
},
"node-gyp-build": {
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.2.3.tgz",
"integrity": "sha512-MN6ZpzmfNCRM+3t57PTJHgHyw/h4OWnZ6mR8P5j/uZtqQr46RRuDE/P+g3n0YR/AiYXeWixZZzaip77gdICfRg=="
},
"type": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/type/-/type-1.2.0.tgz",
"integrity": "sha512-+5nt5AAniqsCnu2cEQQdpzCAh33kVx8n0VoFidKpB1dVVLAN/F+bgVOqOJqOnEnrhp222clB5p3vUlD+1QAnfg=="
},
"typedarray-to-buffer": {
"version": "3.1.5",
"resolved": "https://registry.npmjs.org/typedarray-to-buffer/-/typedarray-to-buffer-3.1.5.tgz",
"integrity": "sha512-zdu8XMNEDepKKR+XYOXAVPtWui0ly0NtohUscw+UmaHiAWT8hrV1rr//H6V+0DvJ3OQ19S979M0laLfX8rm82Q==",
"requires": {
"is-typedarray": "^1.0.0"
}
},
"utf-8-validate": {
"version": "5.0.3",
"resolved": "https://registry.npmjs.org/utf-8-validate/-/utf-8-validate-5.0.3.tgz",
"integrity": "sha512-jtJM6fpGv8C1SoH4PtG22pGto6x+Y8uPprW0tw3//gGFhDDTiuksgradgFN6yRayDP4SyZZa6ZMGHLIa17+M8A==",
"requires": {
"node-gyp-build": "^4.2.0"
}
},
"websocket": {
"version": "1.0.34",
"resolved": "https://registry.npmjs.org/websocket/-/websocket-1.0.34.tgz",
"integrity": "sha512-PRDso2sGwF6kM75QykIesBijKSVceR6jL2G8NGYyq2XrItNC2P5/qL5XeR056GhA+Ly7JMFvJb9I312mJfmqnQ==",
"requires": {
"bufferutil": "^4.0.1",
"debug": "^2.2.0",
"es5-ext": "^0.10.50",
"typedarray-to-buffer": "^3.1.5",
"utf-8-validate": "^5.0.2",
"yaeti": "^0.0.6"
}
},
"yaeti": {
"version": "0.0.6",
"resolved": "https://registry.npmjs.org/yaeti/-/yaeti-0.0.6.tgz",
"integrity": "sha1-8m9ITXJoTPQr7ft2lwqhYI+/lXc="
}
}
}

View File

@ -1,75 +0,0 @@
/*
* libdatachannel streamer example
* Copyright (c) 2020 Filip Klembara (in2core)
*
* 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 <http://www.gnu.org/licenses/>.
*/
#include "ArgParser.hpp"
#include <iostream>
ArgParser::ArgParser(std::vector<std::pair<std::string, std::string>> options, std::vector<std::pair<std::string, std::string>> flags) {
for(auto option: options) {
this->options.insert(option.first);
this->options.insert(option.second);
shortToLongMap.emplace(option.first, option.second);
shortToLongMap.emplace(option.second, option.second);
}
for(auto flag: flags) {
this->flags.insert(flag.first);
this->flags.insert(flag.second);
shortToLongMap.emplace(flag.first, flag.second);
shortToLongMap.emplace(flag.second, flag.second);
}
}
std::optional<std::string> ArgParser::toKey(std::string prefixedKey) {
if (prefixedKey.find("--") == 0) {
return prefixedKey.substr(2, prefixedKey.length());
} else if (prefixedKey.find("-") == 0) {
return prefixedKey.substr(1, prefixedKey.length());
} else {
return std::nullopt;
}
}
bool ArgParser::parse(int argc, char **argv, std::function<bool (std::string, std::string)> onOption, std::function<bool (std::string)> onFlag) {
std::optional<std::string> currentOption = std::nullopt;
for(int i = 1; i < argc; i++) {
std::string current = argv[i];
auto optKey = toKey(current);
if (!currentOption.has_value() && optKey.has_value() && flags.find(optKey.value()) != flags.end()) {
auto check = onFlag(shortToLongMap.at(optKey.value()));
if (!check) {
return false;
}
} else if (!currentOption.has_value() && optKey.has_value() && options.find(optKey.value()) != options.end()) {
currentOption = optKey.value();
} else if (currentOption.has_value()) {
auto check = onOption(shortToLongMap.at(currentOption.value()), current);
if (!check) {
return false;
}
currentOption = std::nullopt;
} else {
std::cerr << "Unrecognized option " << current << std::endl;
return false;
}
}
if (currentOption.has_value()) {
std::cerr << "Missing value for " << currentOption.value() << std::endl;
return false;
}
return true;
}

View File

@ -1,41 +0,0 @@
/*
* libdatachannel streamer example
* Copyright (c) 2020 Filip Klembara (in2core)
*
* 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 <http://www.gnu.org/licenses/>.
*/
#ifndef ArgParser_hpp
#define ArgParser_hpp
#include <functional>
#include <vector>
#include <utility>
#include <string>
#include <set>
#include <unordered_map>
#include <optional>
struct ArgParser {
private:
std::set<std::string> options{};
std::set<std::string> flags{};
std::unordered_map<std::string, std::string> shortToLongMap{};
public:
ArgParser(std::vector<std::pair<std::string, std::string>> options, std::vector<std::pair<std::string, std::string>> flags);
std::optional<std::string> toKey(std::string prefixedKey);
bool parse(int argc, char **argv, std::function<bool (std::string, std::string)> onOption, std::function<bool (std::string)> onFlag);
};
#endif /* ArgParser_hpp */

View File

@ -1,56 +0,0 @@
cmake_minimum_required(VERSION 3.7)
if(POLICY CMP0079)
cmake_policy(SET CMP0079 NEW)
endif()
set(STREAMER_SOURCES
main.cpp
dispatchqueue.cpp
dispatchqueue.hpp
h264fileparser.cpp
h264fileparser.hpp
helpers.cpp
helpers.hpp
opusfileparser.cpp
opusfileparser.hpp
fileparser.cpp
fileparser.hpp
stream.cpp
stream.hpp
ArgParser.cpp
ArgParser.hpp
)
set(STREAMER_UWP_RESOURCES
uwp/Logo.png
uwp/package.appxManifest
uwp/SmallLogo.png
uwp/SmallLogo44x44.png
uwp/SplashScreen.png
uwp/StoreLogo.png
uwp/Windows_TemporaryKey.pfx
)
if(CMAKE_SYSTEM_NAME STREQUAL "WindowsStore")
add_executable(streamer ${STREAMER_SOURCES} ${STREAMER_UWP_RESOURCES})
else()
add_executable(streamer ${STREAMER_SOURCES})
endif()
if(WIN32)
target_compile_definitions(streamer PUBLIC STATIC_GETOPT)
endif()
set_target_properties(streamer PROPERTIES
CXX_STANDARD 17
OUTPUT_NAME streamer)
target_link_libraries(streamer datachannel nlohmann_json)
if(WIN32)
add_custom_command(TARGET streamer POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_if_different
"$<TARGET_FILE_DIR:datachannel>/datachannel.dll"
$<TARGET_FILE_DIR:streamer>
)
endif()

View File

@ -1,32 +0,0 @@
# Streaming H264 and opus
This example streams H264 and opus<sup id="a1">[1](#f1)</sup> samples to the connected browser client.
## Start a signaling server
```sh
$ python3 ../signaling-server-python/signaling-server.py
```
## Start a web server
```sh
$ python3 -m http.server --bind 127.0.0.1 8080
```
Now you can open the demo at [http://127.0.0.1:8080](http://127.0.0.1:8080).
## Arguments
- `-a` Directory with OPUS samples (default: *../../../../examples/streamer/samples/opus/*).
- `-b` Directory with H264 samples (default: *../../../../examples/streamer/samples/h264/*).
- `-d` Signaling server IP address (default: 127.0.0.1).
- `-p` Signaling server port (default: 8000).
- `-v` Enable debug logs.
- `-h` Print this help and exit.
## Generating H264 and Opus samples
You can generate H264 and Opus sample with *samples/generate_h264.py* and *samples/generate_opus.py* respectively. This require ffmpeg, python3 and kaitaistruct library to be installed. Use `-h`/`--help` to learn more about arguments.
<b id="f1">1</b> Opus samples are generated from music downloaded at [bensound](https://www.bensound.com). [](#a1)

View File

@ -1,207 +0,0 @@
/** @type {RTCPeerConnection} */
let rtc;
const iceConnectionLog = document.getElementById('ice-connection-state'),
iceGatheringLog = document.getElementById('ice-gathering-state'),
signalingLog = document.getElementById('signaling-state'),
dataChannelLog = document.getElementById('data-channel');
function randomString(len) {
const charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let randomString = '';
for (let i = 0; i < len; i++) {
const randomPoz = Math.floor(Math.random() * charSet.length);
randomString += charSet.substring(randomPoz, randomPoz + 1);
}
return randomString;
}
const receiveID = randomString(10);
const websocket = new WebSocket('ws://127.0.0.1:8000/' + receiveID);
websocket.onopen = function () {
document.getElementById('start').disabled = false;
}
// data channel
let dc = null, dcTimeout = null;
function createPeerConnection() {
const config = {
sdpSemantics: 'unified-plan',
bundlePolicy: "max-bundle",
};
if (document.getElementById('use-stun').checked) {
config.iceServers = [{urls: ['stun:stun.l.google.com:19302']}];
}
let pc = new RTCPeerConnection(config);
// register some listeners to help debugging
pc.addEventListener('icegatheringstatechange', function () {
iceGatheringLog.textContent += ' -> ' + pc.iceGatheringState;
}, false);
iceGatheringLog.textContent = pc.iceGatheringState;
pc.addEventListener('iceconnectionstatechange', function () {
iceConnectionLog.textContent += ' -> ' + pc.iceConnectionState;
}, false);
iceConnectionLog.textContent = pc.iceConnectionState;
pc.addEventListener('signalingstatechange', function () {
signalingLog.textContent += ' -> ' + pc.signalingState;
}, false);
signalingLog.textContent = pc.signalingState;
// connect audio / video
pc.addEventListener('track', function (evt) {
document.getElementById('media').style.display = 'block';
const videoTag = document.getElementById('video');
videoTag.srcObject = evt.streams[0];
videoTag.play();
});
let time_start = null;
function current_stamp() {
if (time_start === null) {
time_start = new Date().getTime();
return 0;
} else {
return new Date().getTime() - time_start;
}
}
pc.ondatachannel = function (event) {
dc = event.channel;
dc.onopen = function () {
dataChannelLog.textContent += '- open\n';
dataChannelLog.scrollTop = dataChannelLog.scrollHeight;
};
dc.onmessage = function (evt) {
dataChannelLog.textContent += '< ' + evt.data + '\n';
dataChannelLog.scrollTop = dataChannelLog.scrollHeight;
dcTimeout = setTimeout(function () {
if (dc == null && dcTimeout != null) {
dcTimeout = null;
return
}
const message = 'Pong ' + current_stamp();
dataChannelLog.textContent += '> ' + message + '\n';
dataChannelLog.scrollTop = dataChannelLog.scrollHeight;
dc.send(message);
}, 1000);
}
dc.onclose = function () {
clearTimeout(dcTimeout);
dcTimeout = null;
dataChannelLog.textContent += '- close\n';
dataChannelLog.scrollTop = dataChannelLog.scrollHeight;
};
}
return pc;
}
function sendAnswer(pc) {
return pc.createAnswer()
.then((answer) => rtc.setLocalDescription(answer))
.then(function () {
// wait for ICE gathering to complete
return new Promise(function (resolve) {
if (pc.iceGatheringState === 'complete') {
resolve();
} else {
function checkState() {
if (pc.iceGatheringState === 'complete') {
pc.removeEventListener('icegatheringstatechange', checkState);
resolve();
}
}
pc.addEventListener('icegatheringstatechange', checkState);
}
});
}).then(function () {
const answer = pc.localDescription;
document.getElementById('answer-sdp').textContent = answer.sdp;
return websocket.send(JSON.stringify(
{
id: "server",
type: answer.type,
sdp: answer.sdp,
}));
}).catch(function (e) {
alert(e);
});
}
function handleOffer(offer) {
rtc = createPeerConnection();
return rtc.setRemoteDescription(offer)
.then(() => sendAnswer(rtc));
}
function sendStreamRequest() {
websocket.send(JSON.stringify(
{
id: "server",
type: "streamRequest",
receiver: receiveID,
}));
}
async function start() {
document.getElementById('start').style.display = 'none';
document.getElementById('stop').style.display = 'inline-block';
document.getElementById('media').style.display = 'block';
sendStreamRequest();
}
function stop() {
document.getElementById('stop').style.display = 'none';
document.getElementById('media').style.display = 'none';
document.getElementById('start').style.display = 'inline-block';
// close data channel
if (dc) {
dc.close();
dc = null;
}
// close transceivers
if (rtc.getTransceivers) {
rtc.getTransceivers().forEach(function (transceiver) {
if (transceiver.stop) {
transceiver.stop();
}
});
}
// close local audio / video
rtc.getSenders().forEach(function (sender) {
const track = sender.track;
if (track !== null) {
sender.track.stop();
}
});
// close peer connection
setTimeout(function () {
rtc.close();
rtc = null;
}, 500);
}
websocket.onmessage = async function (evt) {
const received_msg = evt.data;
const object = JSON.parse(received_msg);
if (object.type == "offer") {
document.getElementById('offer-sdp').textContent = object.sdp;
await handleOffer(object)
}
}

View File

@ -1,94 +0,0 @@
/*
* libdatachannel streamer example
* Copyright (c) 2020 Filip Klembara (in2core)
*
* 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 <http://www.gnu.org/licenses/>.
*/
#include "dispatchqueue.hpp"
DispatchQueue::DispatchQueue(std::string name, size_t threadCount) :
name{std::move(name)}, threads(threadCount) {
for(size_t i = 0; i < threads.size(); i++)
{
threads[i] = std::thread(&DispatchQueue::dispatchThreadHandler, this);
}
}
DispatchQueue::~DispatchQueue() {
// Signal to dispatch threads that it's time to wrap up
std::unique_lock<std::mutex> lock(lockMutex);
quit = true;
lock.unlock();
condition.notify_all();
// Wait for threads to finish before we exit
for(size_t i = 0; i < threads.size(); i++)
{
if(threads[i].joinable())
{
threads[i].join();
}
}
}
void DispatchQueue::removePending() {
std::unique_lock<std::mutex> lock(lockMutex);
queue = {};
}
void DispatchQueue::dispatch(const fp_t& op) {
std::unique_lock<std::mutex> lock(lockMutex);
queue.push(op);
// Manual unlocking is done before notifying, to avoid waking up
// the waiting thread only to block again (see notify_one for details)
lock.unlock();
condition.notify_one();
}
void DispatchQueue::dispatch(fp_t&& op) {
std::unique_lock<std::mutex> lock(lockMutex);
queue.push(std::move(op));
// Manual unlocking is done before notifying, to avoid waking up
// the waiting thread only to block again (see notify_one for details)
lock.unlock();
condition.notify_one();
}
void DispatchQueue::dispatchThreadHandler(void) {
std::unique_lock<std::mutex> lock(lockMutex);
do {
//Wait until we have data or a quit signal
condition.wait(lock, [this]{
return (queue.size() || quit);
});
//after wait, we own the lock
if(!quit && queue.size())
{
auto op = std::move(queue.front());
queue.pop();
//unlock now that we're done messing with the queue
lock.unlock();
op();
lock.lock();
}
} while (!quit);
}

View File

@ -1,59 +0,0 @@
/*
* libdatachannel streamer example
* Copyright (c) 2020 Filip Klembara (in2core)
*
* 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 <http://www.gnu.org/licenses/>.
*/
#ifndef dispatchqueue_hpp
#define dispatchqueue_hpp
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
#include <functional>
class DispatchQueue {
typedef std::function<void(void)> fp_t;
public:
DispatchQueue(std::string name, size_t threadCount = 1);
~DispatchQueue();
// dispatch and copy
void dispatch(const fp_t& op);
// dispatch and move
void dispatch(fp_t&& op);
void removePending();
// Deleted operations
DispatchQueue(const DispatchQueue& rhs) = delete;
DispatchQueue& operator=(const DispatchQueue& rhs) = delete;
DispatchQueue(DispatchQueue&& rhs) = delete;
DispatchQueue& operator=(DispatchQueue&& rhs) = delete;
private:
std::string name;
std::mutex lockMutex;
std::vector<std::thread> threads;
std::queue<fp_t> queue;
std::condition_variable condition;
bool quit = false;
void dispatchThreadHandler(void);
};
#endif /* dispatchqueue_hpp */

View File

@ -1,59 +0,0 @@
/*
* libdatachannel streamer example
* Copyright (c) 2020 Filip Klembara (in2core)
*
* 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 <http://www.gnu.org/licenses/>.
*/
#include "fileparser.hpp"
#include <fstream>
using namespace std;
FileParser::FileParser(string directory, string extension, uint32_t samplesPerSecond, bool loop): sampleDuration_us(1000 * 1000 / samplesPerSecond), StreamSource() {
this->directory = directory;
this->extension = extension;
this->loop = loop;
}
void FileParser::start() {
sampleTime_us = std::numeric_limits<uint64_t>::max() - sampleDuration_us + 1;
loadNextSample();
}
void FileParser::stop() {
StreamSource::stop();
counter = -1;
}
void FileParser::loadNextSample() {
string frame_id = to_string(++counter);
string url = directory + "/sample-" + frame_id + extension;
ifstream source(url, ios_base::binary);
if (!source) {
if (loop && counter > 0) {
loopTimestampOffset = sampleTime_us;
counter = -1;
loadNextSample();
return;
}
sample = {};
return;
}
vector<uint8_t> fileContents((std::istreambuf_iterator<char>(source)), std::istreambuf_iterator<char>());
sample = *reinterpret_cast<vector<byte> *>(&fileContents);
sampleTime_us += sampleDuration_us;
}

View File

@ -1,40 +0,0 @@
/*
* libdatachannel streamer example
* Copyright (c) 2020 Filip Klembara (in2core)
*
* 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 <http://www.gnu.org/licenses/>.
*/
#ifndef fileparser_hpp
#define fileparser_hpp
#include <string>
#include <vector>
#include "stream.hpp"
class FileParser: public StreamSource {
std::string directory;
std::string extension;
uint32_t counter = -1;
bool loop;
uint64_t loopTimestampOffset = 0;
public:
const uint64_t sampleDuration_us;
virtual void start();
virtual void stop();
FileParser(std::string directory, std::string extension, uint32_t samplesPerSecond, bool loop);
virtual void loadNextSample();
};
#endif /* fileparser_hpp */

View File

@ -1,77 +0,0 @@
/*
* libdatachannel streamer example
* Copyright (c) 2020 Filip Klembara (in2core)
*
* 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 <http://www.gnu.org/licenses/>.
*/
#include "h264fileparser.hpp"
#include "rtc/rtc.hpp"
#include <fstream>
#ifdef _WIN32
#include <winsock2.h>
#else
#include <arpa/inet.h>
#endif
using namespace std;
H264FileParser::H264FileParser(string directory, uint32_t fps, bool loop): FileParser(directory, ".h264", fps, loop) { }
void H264FileParser::loadNextSample() {
FileParser::loadNextSample();
unsigned long long i = 0;
while (i < sample.size()) {
assert(i + 4 < sample.size());
auto lengthPtr = (uint32_t *) (sample.data() + i);
uint32_t length = ntohl(*lengthPtr);
auto naluStartIndex = i + 4;
auto naluEndIndex = naluStartIndex + length;
assert(naluEndIndex <= sample.size());
auto header = reinterpret_cast<rtc::NalUnitHeader *>(sample.data() + naluStartIndex);
auto type = header->unitType();
switch (type) {
case 7:
previousUnitType7 = {sample.begin() + i, sample.begin() + naluEndIndex};
break;
case 8:
previousUnitType8 = {sample.begin() + i, sample.begin() + naluEndIndex};;
break;
case 5:
previousUnitType5 = {sample.begin() + i, sample.begin() + naluEndIndex};;
break;
}
i = naluEndIndex;
}
}
vector<byte> H264FileParser::initialNALUS() {
vector<byte> units{};
if (previousUnitType7.has_value()) {
auto nalu = previousUnitType7.value();
units.insert(units.end(), nalu.begin(), nalu.end());
}
if (previousUnitType8.has_value()) {
auto nalu = previousUnitType8.value();
units.insert(units.end(), nalu.begin(), nalu.end());
}
if (previousUnitType5.has_value()) {
auto nalu = previousUnitType5.value();
units.insert(units.end(), nalu.begin(), nalu.end());
}
return units;
}

View File

@ -1,36 +0,0 @@
/*
* libdatachannel streamer example
* Copyright (c) 2020 Filip Klembara (in2core)
*
* 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 <http://www.gnu.org/licenses/>.
*/
#ifndef h264fileparser_hpp
#define h264fileparser_hpp
#include "fileparser.hpp"
#include <optional>
class H264FileParser: public FileParser {
std::optional<std::vector<std::byte>> previousUnitType5 = std::nullopt;
std::optional<std::vector<std::byte>> previousUnitType7 = std::nullopt;
std::optional<std::vector<std::byte>> previousUnitType8 = std::nullopt;
public:
H264FileParser(std::string directory, uint32_t fps, bool loop);
void loadNextSample() override;
std::vector<std::byte> initialNALUS();
};
#endif /* h264fileparser_hpp */

View File

@ -1,89 +0,0 @@
/*
* libdatachannel streamer example
* Copyright (c) 2020 Filip Klembara (in2core)
*
* 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 <http://www.gnu.org/licenses/>.
*/
#include "helpers.hpp"
#include <ctime>
#ifdef _WIN32
// taken from https://stackoverflow.com/questions/10905892/equivalent-of-gettimeday-for-windows
#include <windows.h>
#include <winsock2.h> // for struct timeval
struct timezone {
int tz_minuteswest;
int tz_dsttime;
};
int gettimeofday(struct timeval *tv, struct timezone *tz)
{
if (tv) {
FILETIME filetime; /* 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601 00:00 UTC */
ULARGE_INTEGER x;
ULONGLONG usec;
static const ULONGLONG epoch_offset_us = 11644473600000000ULL; /* microseconds betweeen Jan 1,1601 and Jan 1,1970 */
#if _WIN32_WINNT >= _WIN32_WINNT_WIN8
GetSystemTimePreciseAsFileTime(&filetime);
#else
GetSystemTimeAsFileTime(&filetime);
#endif
x.LowPart = filetime.dwLowDateTime;
x.HighPart = filetime.dwHighDateTime;
usec = x.QuadPart / 10 - epoch_offset_us;
tv->tv_sec = (time_t)(usec / 1000000ULL);
tv->tv_usec = (long)(usec % 1000000ULL);
}
if (tz) {
TIME_ZONE_INFORMATION timezone;
GetTimeZoneInformation(&timezone);
tz->tz_minuteswest = timezone.Bias;
tz->tz_dsttime = 0;
}
return 0;
}
#else
#include <sys/time.h>
#endif
using namespace std;
using namespace rtc;
ClientTrackData::ClientTrackData(shared_ptr<Track> track, shared_ptr<RtcpSrReporter> sender) {
this->track = track;
this->sender = sender;
}
void Client::setState(State state) {
std::unique_lock lock(_mutex);
this->state = state;
}
Client::State Client::getState() {
std::shared_lock lock(_mutex);
return state;
}
ClientTrack::ClientTrack(string id, shared_ptr<ClientTrackData> trackData) {
this->id = id;
this->trackData = trackData;
}
uint64_t currentTimeInMicroSeconds() {
struct timeval time;
gettimeofday(&time, NULL);
return uint64_t(time.tv_sec) * 1000 * 1000 + time.tv_usec;
}

View File

@ -1,63 +0,0 @@
/*
* libdatachannel streamer example
* Copyright (c) 2020 Filip Klembara (in2core)
*
* 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 <http://www.gnu.org/licenses/>.
*/
#ifndef helpers_hpp
#define helpers_hpp
#include "rtc/rtc.hpp"
struct ClientTrackData {
std::shared_ptr<rtc::Track> track;
std::shared_ptr<rtc::RtcpSrReporter> sender;
ClientTrackData(std::shared_ptr<rtc::Track> track, std::shared_ptr<rtc::RtcpSrReporter> sender);
};
struct Client {
enum class State {
Waiting,
WaitingForVideo,
WaitingForAudio,
Ready
};
const std::shared_ptr<rtc::PeerConnection> & peerConnection = _peerConnection;
Client(std::shared_ptr<rtc::PeerConnection> pc) {
_peerConnection = pc;
}
std::optional<std::shared_ptr<ClientTrackData>> video;
std::optional<std::shared_ptr<ClientTrackData>> audio;
std::optional<std::shared_ptr<rtc::DataChannel>> dataChannel{};
void setState(State state);
State getState();
private:
std::shared_mutex _mutex;
State state = State::Waiting;
std::string id;
std::shared_ptr<rtc::PeerConnection> _peerConnection;
};
struct ClientTrack {
std::string id;
std::shared_ptr<ClientTrackData> trackData;
ClientTrack(std::string id, std::shared_ptr<ClientTrackData> trackData);
};
uint64_t currentTimeInMicroSeconds();
#endif /* helpers_hpp */

View File

@ -1,72 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>libdatachannel media example</title>
<style>
button {
padding: 8px 16px;
}
pre {
overflow-x: hidden;
overflow-y: auto;
}
video {
width: 100%;
}
.option {
margin-bottom: 8px;
}
#media {
max-width: 1280px;
}
</style>
</head>
<body>
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
<h2>Options</h2>
<div class="option">
<input id="use-stun" type="checkbox"/>
<label for="use-stun">Use STUN server</label>
</div>
<button id="start" onclick="start()" disabled>Start</button>
<button id="stop" style="display: none" onclick="stop()">Stop</button>
<h2>State</h2>
<p>
ICE gathering state: <span id="ice-gathering-state"></span>
</p>
<p>
ICE connection state: <span id="ice-connection-state"></span>
</p>
<p>
Signaling state: <span id="signaling-state"></span>
</p>
<div id="media" style="display: none">
<h2>Media</h2>
<video id="video" autoplay playsinline></video>
</div>
<h2>Data channel</h2>
<pre id="data-channel" style="height: 200px;"></pre>
<h2>SDP</h2>
<h3>Offer</h3>
<pre id="offer-sdp"></pre>
<h3>Answer</h3>
<pre id="answer-sdp"></pre>
<script src="client.js"></script>
</body>
</html>

View File

@ -1,480 +0,0 @@
/*
* libdatachannel client example
* Copyright (c) 2019-2020 Paul-Louis Ageneau
* Copyright (c) 2019 Murat Dogan
* Copyright (c) 2020 Will Munn
* Copyright (c) 2020 Nico Chatzi
* Copyright (c) 2020 Lara Mackey
* Copyright (c) 2020 Erik Cota-Robles
* Copyright (c) 2020 Filip Klembara (in2core)
*
* 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 <http://www.gnu.org/licenses/>.
*/
#include "nlohmann/json.hpp"
#include "h264fileparser.hpp"
#include "opusfileparser.hpp"
#include "helpers.hpp"
#include "ArgParser.hpp"
using namespace rtc;
using namespace std;
using namespace std::chrono_literals;
using json = nlohmann::json;
template <class T> weak_ptr<T> make_weak_ptr(shared_ptr<T> ptr) { return ptr; }
/// all connected clients
unordered_map<string, shared_ptr<Client>> clients{};
/// Creates peer connection and client representation
/// @param config Configuration
/// @param wws Websocket for signaling
/// @param id Client ID
/// @returns Client
shared_ptr<Client> createPeerConnection(const Configuration &config,
weak_ptr<WebSocket> wws,
string id);
/// Creates stream
/// @param h264Samples Directory with H264 samples
/// @param fps Video FPS
/// @param opusSamples Directory with opus samples
/// @returns Stream object
shared_ptr<Stream> createStream(const string h264Samples, const unsigned fps, const string opusSamples);
/// Add client to stream
/// @param client Client
/// @param adding_video True if adding video
void addToStream(shared_ptr<Client> client, bool isAddingVideo);
/// Start stream
void startStream();
/// Main dispatch queue
DispatchQueue MainThread("Main");
/// Audio and video stream
optional<shared_ptr<Stream>> avStream = nullopt;
const string defaultRootDirectory = "../../../examples/streamer/samples/";
const string defaultH264SamplesDirectory = defaultRootDirectory + "h264/";
string h264SamplesDirectory = defaultH264SamplesDirectory;
const string defaultOpusSamplesDirectory = defaultRootDirectory + "opus/";
string opusSamplesDirectory = defaultOpusSamplesDirectory;
const string defaultIPAddress = "127.0.0.1";
const uint16_t defaultPort = 8000;
string ip_address = defaultIPAddress;
uint16_t port = defaultPort;
/// Incomming message handler for websocket
/// @param message Incommint message
/// @param config Configuration
/// @param ws Websocket
void wsOnMessage(json message, Configuration config, shared_ptr<WebSocket> ws) {
auto it = message.find("id");
if (it == message.end())
return;
string id = it->get<string>();
it = message.find("type");
if (it == message.end())
return;
string type = it->get<string>();
if (type == "streamRequest") {
shared_ptr<Client> c = createPeerConnection(config, make_weak_ptr(ws), id);
clients.emplace(id, c);
} else if (type == "answer") {
shared_ptr<Client> c;
if (auto jt = clients.find(id); jt != clients.end()) {
auto pc = clients.at(id)->peerConnection;
auto sdp = message["sdp"].get<string>();
auto description = Description(sdp, type);
pc->setRemoteDescription(description);
}
}
}
int main(int argc, char **argv) try {
bool enableDebugLogs = false;
bool printHelp = false;
int c = 0;
auto parser = ArgParser({{"a", "audio"}, {"b", "video"}, {"d", "ip"}, {"p","port"}}, {{"h", "help"}, {"v", "verbose"}});
auto parsingResult = parser.parse(argc, argv, [](string key, string value) {
if (key == "audio") {
opusSamplesDirectory = value + "/";
} else if (key == "video") {
h264SamplesDirectory = value + "/";
} else if (key == "ip") {
ip_address = value;
} else if (key == "port") {
port = atoi(value.data());
} else {
cerr << "Invalid option --" << key << " with value " << value << endl;
return false;
}
return true;
}, [&enableDebugLogs, &printHelp](string flag){
if (flag == "verbose") {
enableDebugLogs = true;
} else if (flag == "help") {
printHelp = true;
} else {
cerr << "Invalid flag --" << flag << endl;
return false;
}
return true;
});
if (!parsingResult) {
return 1;
}
if (printHelp) {
cout << "usage: stream-h264 [-a opus_samples_folder] [-b h264_samples_folder] [-d ip_address] [-p port] [-v] [-h]" << endl
<< "Arguments:" << endl
<< "\t -a " << "Directory with opus samples (default: " << defaultOpusSamplesDirectory << ")." << endl
<< "\t -b " << "Directory with H264 samples (default: " << defaultH264SamplesDirectory << ")." << endl
<< "\t -d " << "Signaling server IP address (default: " << defaultIPAddress << ")." << endl
<< "\t -p " << "Signaling server port (default: " << defaultPort << ")." << endl
<< "\t -v " << "Enable debug logs." << endl
<< "\t -h " << "Print this help and exit." << endl;
return 0;
}
if (enableDebugLogs) {
InitLogger(LogLevel::Debug);
}
Configuration config;
string stunServer = "stun:stun.l.google.com:19302";
cout << "Stun server is " << stunServer << endl;
config.iceServers.emplace_back(stunServer);
config.disableAutoNegotiation = true;
string localId = "server";
cout << "The local ID is: " << localId << endl;
auto ws = make_shared<WebSocket>();
ws->onOpen([]() { cout << "WebSocket connected, signaling ready" << endl; });
ws->onClosed([]() { cout << "WebSocket closed" << endl; });
ws->onError([](const string &error) { cout << "WebSocket failed: " << error << endl; });
ws->onMessage([&](variant<binary, string> data) {
if (!holds_alternative<string>(data))
return;
json message = json::parse(get<string>(data));
MainThread.dispatch([message, config, ws]() {
wsOnMessage(message, config, ws);
});
});
const string url = "ws://" + ip_address + ":" + to_string(port) + "/" + localId;
cout << "Url is " << url << endl;
ws->open(url);
cout << "Waiting for signaling to be connected..." << endl;
while (!ws->isOpen()) {
if (ws->isClosed())
return 1;
this_thread::sleep_for(100ms);
}
while (true) {
string id;
cout << "Enter to exit" << endl;
cin >> id;
cin.ignore();
cout << "exiting" << endl;
break;
}
cout << "Cleaning up..." << endl;
return 0;
} catch (const std::exception &e) {
std::cout << "Error: " << e.what() << std::endl;
return -1;
}
shared_ptr<ClientTrackData> addVideo(const shared_ptr<PeerConnection> pc, const uint8_t payloadType, const uint32_t ssrc, const string cname, const string msid, const function<void (void)> onOpen) {
auto video = Description::Video(cname);
video.addH264Codec(payloadType);
video.addSSRC(ssrc, cname, msid, cname);
auto track = pc->addTrack(video);
// create RTP configuration
auto rtpConfig = make_shared<RtpPacketizationConfig>(ssrc, cname, payloadType, H264RtpPacketizer::defaultClockRate);
// create packetizer
auto packetizer = make_shared<H264RtpPacketizer>(H264RtpPacketizer::Separator::Length, rtpConfig);
// create H264 handler
auto h264Handler = make_shared<H264PacketizationHandler>(packetizer);
// add RTCP SR handler
auto srReporter = make_shared<RtcpSrReporter>(rtpConfig);
h264Handler->addToChain(srReporter);
// add RTCP NACK handler
auto nackResponder = make_shared<RtcpNackResponder>();
h264Handler->addToChain(nackResponder);
// set handler
track->setMediaHandler(h264Handler);
track->onOpen(onOpen);
auto trackData = make_shared<ClientTrackData>(track, srReporter);
return trackData;
}
shared_ptr<ClientTrackData> addAudio(const shared_ptr<PeerConnection> pc, const uint8_t payloadType, const uint32_t ssrc, const string cname, const string msid, const function<void (void)> onOpen) {
auto audio = Description::Audio(cname);
audio.addOpusCodec(payloadType);
audio.addSSRC(ssrc, cname, msid, cname);
auto track = pc->addTrack(audio);
// create RTP configuration
auto rtpConfig = make_shared<RtpPacketizationConfig>(ssrc, cname, payloadType, OpusRtpPacketizer::defaultClockRate);
// create packetizer
auto packetizer = make_shared<OpusRtpPacketizer>(rtpConfig);
// create opus handler
auto opusHandler = make_shared<OpusPacketizationHandler>(packetizer);
// add RTCP SR handler
auto srReporter = make_shared<RtcpSrReporter>(rtpConfig);
opusHandler->addToChain(srReporter);
// add RTCP NACK handler
auto nackResponder = make_shared<RtcpNackResponder>();
opusHandler->addToChain(nackResponder);
// set handler
track->setMediaHandler(opusHandler);
track->onOpen(onOpen);
auto trackData = make_shared<ClientTrackData>(track, srReporter);
return trackData;
}
// Create and setup a PeerConnection
shared_ptr<Client> createPeerConnection(const Configuration &config,
weak_ptr<WebSocket> wws,
string id) {
auto pc = make_shared<PeerConnection>(config);
auto client = make_shared<Client>(pc);
pc->onStateChange([id](PeerConnection::State state) {
cout << "State: " << state << endl;
if (state == PeerConnection::State::Disconnected ||
state == PeerConnection::State::Failed ||
state == PeerConnection::State::Closed) {
// remove disconnected client
MainThread.dispatch([id]() {
clients.erase(id);
});
}
});
pc->onGatheringStateChange(
[wpc = make_weak_ptr(pc), id, wws](PeerConnection::GatheringState state) {
cout << "Gathering State: " << state << endl;
if (state == PeerConnection::GatheringState::Complete) {
if(auto pc = wpc.lock()) {
auto description = pc->localDescription();
json message = {
{"id", id},
{"type", description->typeString()},
{"sdp", string(description.value())}
};
// Gathering complete, send answer
if (auto ws = wws.lock()) {
ws->send(message.dump());
}
}
}
});
client->video = addVideo(pc, 102, 1, "video-stream", "stream1", [id, wc = make_weak_ptr(client)]() {
MainThread.dispatch([wc]() {
if (auto c = wc.lock()) {
addToStream(c, true);
}
});
cout << "Video from " << id << " opened" << endl;
});
client->audio = addAudio(pc, 111, 2, "audio-stream", "stream1", [id, wc = make_weak_ptr(client)]() {
MainThread.dispatch([wc]() {
if (auto c = wc.lock()) {
addToStream(c, false);
}
});
cout << "Audio from " << id << " opened" << endl;
});
auto dc = pc->createDataChannel("ping-pong");
dc->onOpen([id, wdc = make_weak_ptr(dc)]() {
if (auto dc = wdc.lock()) {
dc->send("Ping");
}
});
dc->onMessage(nullptr, [id, wdc = make_weak_ptr(dc)](string msg) {
cout << "Message from " << id << " received: " << msg << endl;
if (auto dc = wdc.lock()) {
dc->send("Ping");
}
});
client->dataChannel = dc;
pc->setLocalDescription();
return client;
};
/// Create stream
shared_ptr<Stream> createStream(const string h264Samples, const unsigned fps, const string opusSamples) {
// video source
auto video = make_shared<H264FileParser>(h264Samples, fps, true);
// audio source
auto audio = make_shared<OPUSFileParser>(opusSamples, true);
auto stream = make_shared<Stream>(video, audio);
// set callback responsible for sample sending
stream->onSample([ws = make_weak_ptr(stream)](Stream::StreamSourceType type, uint64_t sampleTime, rtc::binary sample) {
vector<ClientTrack> tracks{};
string streamType = type == Stream::StreamSourceType::Video ? "video" : "audio";
// get track for given type
function<optional<shared_ptr<ClientTrackData>> (shared_ptr<Client>)> getTrackData = [type](shared_ptr<Client> client) {
return type == Stream::StreamSourceType::Video ? client->video : client->audio;
};
// get all clients with Ready state
for(auto id_client: clients) {
auto id = id_client.first;
auto client = id_client.second;
auto optTrackData = getTrackData(client);
if (client->getState() == Client::State::Ready && optTrackData.has_value()) {
auto trackData = optTrackData.value();
tracks.push_back(ClientTrack(id, trackData));
}
}
if (!tracks.empty()) {
auto message = make_message(move(sample));
for (auto clientTrack: tracks) {
auto client = clientTrack.id;
auto trackData = clientTrack.trackData;
// sample time is in us, we need to convert it to seconds
auto elapsedSeconds = double(sampleTime) / (1000 * 1000);
auto rtpConfig = trackData->sender->rtpConfig;
// get elapsed time in clock rate
uint32_t elapsedTimestamp = rtpConfig->secondsToTimestamp(elapsedSeconds);
// set new timestamp
rtpConfig->timestamp = rtpConfig->startTimestamp + elapsedTimestamp;
// get elapsed time in clock rate from last RTCP sender report
auto reportElapsedTimestamp = rtpConfig->timestamp - trackData->sender->previousReportedTimestamp;
// check if last report was at least 1 second ago
if (rtpConfig->timestampToSeconds(reportElapsedTimestamp) > 1) {
trackData->sender->setNeedsToReport();
}
cout << "Sending " << streamType << " sample with size: " << to_string(message->size()) << " to " << client << endl;
bool send = false;
try {
// send sample
send = trackData->track->send(*message);
} catch (...) {
send = false;
}
if (!send) {
cerr << "Unable to send "<< streamType << " packet" << endl;
break;
}
}
}
MainThread.dispatch([ws]() {
if (clients.empty()) {
// we have no clients, stop the stream
if (auto stream = ws.lock()) {
stream->stop();
}
}
});
});
return stream;
}
/// Start stream
void startStream() {
shared_ptr<Stream> stream;
if (avStream.has_value()) {
stream = avStream.value();
if (stream->isRunning) {
// stream is already running
return;
}
} else {
stream = createStream(h264SamplesDirectory, 30, opusSamplesDirectory);
avStream = stream;
}
stream->start();
}
/// Send previous key frame so browser can show something to user
/// @param stream Stream
/// @param video Video track data
void sendInitialNalus(shared_ptr<Stream> stream, shared_ptr<ClientTrackData> video) {
auto h264 = dynamic_cast<H264FileParser *>(stream->video.get());
auto initialNalus = h264->initialNALUS();
// send previous NALU key frame so users don't have to wait to see stream works
if (!initialNalus.empty()) {
const double frameDuration_s = double(h264->sampleDuration_us) / (1000 * 1000);
const uint32_t frameTimestampDuration = video->sender->rtpConfig->secondsToTimestamp(frameDuration_s);
video->sender->rtpConfig->timestamp = video->sender->rtpConfig->startTimestamp - frameTimestampDuration * 2;
video->track->send(initialNalus);
video->sender->rtpConfig->timestamp += frameTimestampDuration;
// Send initial NAL units again to start stream in firefox browser
video->track->send(initialNalus);
}
}
/// Add client to stream
/// @param client Client
/// @param adding_video True if adding video
void addToStream(shared_ptr<Client> client, bool isAddingVideo) {
if (client->getState() == Client::State::Waiting) {
client->setState(isAddingVideo ? Client::State::WaitingForAudio : Client::State::WaitingForVideo);
} else if ((client->getState() == Client::State::WaitingForAudio && !isAddingVideo)
|| (client->getState() == Client::State::WaitingForVideo && isAddingVideo)) {
// Audio and video tracks are collected now
assert(client->video.has_value() && client->audio.has_value());
auto video = client->video.value();
auto audio = client->audio.value();
auto currentTime_us = double(currentTimeInMicroSeconds());
auto currentTime_s = currentTime_us / (1000 * 1000);
// set start time of stream
video->sender->rtpConfig->setStartTime(currentTime_s, RtpPacketizationConfig::EpochStart::T1970);
audio->sender->rtpConfig->setStartTime(currentTime_s, RtpPacketizationConfig::EpochStart::T1970);
// start stat recording of RTCP SR
video->sender->startRecording();
audio->sender->startRecording();
if (avStream.has_value()) {
sendInitialNalus(avStream.value(), video);
}
client->setState(Client::State::Ready);
}
if (client->getState() == Client::State::Ready) {
startStream();
}
}

View File

@ -1,23 +0,0 @@
/*
* libdatachannel streamer example
* Copyright (c) 2020 Filip Klembara (in2core)
*
* 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 <http://www.gnu.org/licenses/>.
*/
#include "opusfileparser.hpp"
using namespace std;
OPUSFileParser::OPUSFileParser(string directory, bool loop, uint32_t samplesPerSecond): FileParser(directory, ".opus", samplesPerSecond, loop) { }

View File

@ -1,32 +0,0 @@
/*
* libdatachannel streamer example
* Copyright (c) 2020 Filip Klembara (in2core)
*
* 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 <http://www.gnu.org/licenses/>.
*/
#ifndef opusfileparser_hpp
#define opusfileparser_hpp
#include "fileparser.hpp"
class OPUSFileParser: public FileParser {
static const uint32_t defaultSamplesPerSecond = 50;
public:
OPUSFileParser(std::string directory, bool loop, uint32_t samplesPerSecond = OPUSFileParser::defaultSamplesPerSecond);
};
#endif /* opusfileparser_hpp */

Binary file not shown.

View File

@ -1,115 +0,0 @@
#!/usr/bin/env python3
import os
import getopt
import sys
import glob
from functools import reduce
from typing import Optional, List
class H264ByteStream:
@staticmethod
def nalu_type(nalu: bytes) -> int:
return nalu[0] & 0x1F
@staticmethod
def merge_sample(sample: List[bytes]) -> bytes:
result = bytes()
for nalu in sample:
result += len(nalu).to_bytes(4, byteorder='big') + nalu
return result
@staticmethod
def reduce_nalus_to_samples(samples: List[List[bytes]], current: bytes) -> List[List[bytes]]:
last_nalus = samples[-1]
samples[-1] = last_nalus + [current]
if H264ByteStream.nalu_type(current) in [1, 5]:
samples.append([])
return samples
def __init__(self, file_name: str):
with open(file_name, "rb") as file:
byte_stream = file.read()
long_split = byte_stream.split(b"\x00\x00\x00\x01")
splits = reduce(lambda acc, x: acc + x.split(b"\x00\x00\x01"), long_split, [])
nalus = filter(lambda x: len(x) > 0, splits)
self.samples = list(
filter(lambda x: len(x) > 0, reduce(H264ByteStream.reduce_nalus_to_samples, nalus, [[]])))
def generate(input_file: str, output_dir: str, max_samples: Optional[int], fps: Optional[int]):
if output_dir[-1] != "/":
output_dir += "/"
if os.path.isdir(output_dir):
files_to_delete = glob.glob(output_dir + "*.h264")
if len(files_to_delete) > 0:
print("Remove following files?")
for file in files_to_delete:
print(file)
response = input("Remove files? [y/n] ").lower()
if response != "y" and response != "yes":
print("Cancelling...")
return
print("Removing files")
for file in files_to_delete:
os.remove(file)
else:
os.makedirs(output_dir, exist_ok=True)
video_stream_file = "_video_stream.h264"
if os.path.isfile(video_stream_file):
os.remove(video_stream_file)
fps_line = "" if fps is None else "-filter:v fps=fps={} ".format(fps)
command = 'ffmpeg -i {} -an -vcodec libx264 -preset slow -profile baseline {}{}'.format(input_file, fps_line,
video_stream_file)
os.system(command)
data = H264ByteStream(video_stream_file)
index = 0
for sample in data.samples[:max_samples]:
name = "{}sample-{}.h264".format(output_dir, index)
index += 1
with open(name, 'wb') as file:
merged_sample = H264ByteStream.merge_sample(sample)
file.write(merged_sample)
os.remove(video_stream_file)
def main(argv):
input_file = None
default_output_dir = "h264/"
output_dir = default_output_dir
max_samples = None
fps = None
try:
opts, args = getopt.getopt(argv, "hi:o:m:f:", ["help", "ifile=", "odir=", "max=", "fps"])
except getopt.GetoptError:
print('generate_h264.py -i <input_files> [-o <output_files>] [-m <max_samples>] [-f <fps>] [-h]')
sys.exit(2)
for opt, arg in opts:
if opt in ("-h", "--help"):
print("Usage: generate_h264.py -i <input_files> [-o <output_files>] [-m <max_samples>] [-f <fps>] [-h]")
print("Arguments:")
print("\t-i,--ifile: Input file")
print("\t-o,--odir: Output directory (default: " + default_output_dir + ")")
print("\t-m,--max: Maximum generated samples")
print("\t-f,--fps: Output fps")
print("\t-h,--help: Print this help and exit")
sys.exit()
elif opt in ("-i", "--ifile"):
input_file = arg
elif opt in ("-o", "--ofile"):
output_dir = arg
elif opt in ("-m", "--max"):
max_samples = int(arg)
elif opt in ("-f", "--fps"):
fps = int(arg)
if input_file is None:
print("Missing argument -i")
sys.exit(2)
generate(input_file, output_dir, max_samples, fps)
if __name__ == "__main__":
main(sys.argv[1:])

Some files were not shown because too many files have changed in this diff Show More