diff --git a/.gitignore b/.gitignore index 1b46b6b3b..ee9fdc88e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,78 +1,31 @@ -# OSX -# -.DS_Store +.tmp/ +build/ # Xcode -# -build/ -*.pbxuser -!default.pbxuser -*.mode1v3 -!default.mode1v3 -*.mode2v3 -!default.mode2v3 -*.perspectivev3 -!default.perspectivev3 -#xcuserdata -*.xccheckout -*.moved-aside -DerivedData -*.hmap -*.ipa -#*.xcuserstate -#project.xcworkspace +project.xcworkspace/ +xcuserdata/ +Pods/ +Podfile.lock -# Android/IntelliJ -# -build/ -.idea -.gradle +# Android/IntelliJ/VSCode +.idea/ +.gradle/ +gradle/ local.properties *.iml +.vscode/ +android/app/.settings/ +android/.settings/ +android/app/.classpath +android/app/.project +android/.project +typings/ +typings.json # node.js -# node_modules/ -npm-debug.log -yarn-error.log - -# BUCK -buck-out/ -\.buckd/ -*.keystore - -# fastlane -# -# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the -# screenshots whenever they are needed. -# For more information about the recommended setup visit: -# https://github.com/fastlane/fastlane/blob/master/fastlane/docs/Gitignore.md - -fastlane/report.xml -fastlane/Preview.html -fastlane/screenshots -android/src/main/res/drawable/ -**/*.*~ -**/*.swp -**/*.~ -.project -.settings -.classpath -.jest/ -xcuserdata -*.pbxproj -*.xcworkspace -*.zip -.byebug_history -Untitled* -Pods -**/*~ -xcuserdata* -**/*/xcuserdata* -.vscode -samples/**/package-lock.json -*.iml -android/bin +__tests__/ yarn.lock +npm-debug.log +npm-lock.json package-lock.json -docs/api diff --git a/.npmignore b/.npmignore index 379b823c4..c9138b08c 100644 --- a/.npmignore +++ b/.npmignore @@ -1,40 +1,6 @@ -*.*~ -**/*.*~ -*.md -*.MD -.DS_Store -samples -__tests__ -docs -.*.swp -._* -.DS_Store -.git -.hg -.npmrc -.lock-wscript -.svn -.wafpickle-* -config.gypi -CVS -npm-debug.log -node_modules -ios/Pods -ios/Podfile* -xcuserdata* -**/*/xcuserdata* -src/**/*.ts -src/**/*.tsx -!android/src/ -!android/build.gradle -**/*.iml -**/*.properties -.project -proguard-rules.pro -.gradle -.idea -.settings -.vscode -package-lock.json -android/bin +.idea/ +docs/ lib/**/*.map +lib/**/*.tsbuildinfo +samples/ +src/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 1e1b9e017..ec3821603 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,58 @@ ## THE CHANGELOG +#### 3.0.1-rc.1 + - prerelease 3.0.1-rc.1 + +#### 3.0.1-beta.9 + - add `constructor` for typescript + - fix Android `mapToChannelMediaInfo` crash + - fix iOS `switchChannel` `sendMetadata` crash + +#### 3.0.1-beta.8 + - fix iOS event warn + - fix ts array declare error + +#### 3.0.1-beta.7 + - fix lib ignore bug + +#### 3.0.1-beta.6 + - support 3.0.1.1 native sdk + - fix iOS `RtcChannelEvent` `NetworkQuality` crash + +#### 3.0.1-beta.5 + - fix lib ignore bug + +#### 3.0.1-beta.4 + - fix android `setCameraCapturerConfiguration` bug + +#### 3.0.1-beta.3 + - fix iOS `mirrorMode` bug + +#### 3.0.1-beta.2 + - fix `createWithAreaCode` bug + - fix render black screen bug + +#### 3.0.1-beta.1 + - support 3.0.1 native sdk + +#### 3.0.0-beta.6 + - fix iOS link bug + +#### 3.0.0-beta.5 + - optimize doc + +#### 3.0.0-beta.4 + - optimize code + +#### 3.0.0-beta.3 + - optimize doc + +#### 3.0.0-beta.2 + - optimize + +#### 3.0.0-beta.1 + - support 3.0.0 native sdk + #### 2.9.1-alpha.7 - fix `setBeautyEffectOptions` bugs @@ -75,7 +128,7 @@ 6. Add event `rtmpStreamingStateChanged` for rtmp streaming troubleshooting 7. Add event `audioCodecProfile` on `liveTranscoding` interface. 8. Add event `networkTypeChanged` for network troubleshooting. - 9. Add method `registerMediaMetadataObserver` method, this method enables you to add synchronized metadata in the video stream for more diversified live broadcast interactions, such as sending shopping links, digital coupons, and online quizzes. note: Call this method before the joinChannel method. and applies to `channelProfile` with 1. + 9. Add method `registerMediaMetadataObserver` method, this method enables you to add synchronized metadata in the video stream for more diversified live broadcast interactions, such as sending shopping links, digital coupons, and online quizzes. note: Call this method before the joinChannel method. and applies to `channelProfile` with 1. 10. Add method `sendMediaData`, this method enables you send media data under the live broadcast mode (`channelProfile` = 1) note: call this method after the `registerMediaMetadataObserver` method. 11. Add event `audioMixingStateChanged` and Deprecate event 'localAudioMixingFinish`. 11. Add `firstRemoteAudioDecoded` event you can get more detail [here](https://docs.agora.io/en/Interactive%20Broadcast/release_android_video?platform=Android#v241) @@ -85,7 +138,7 @@ - support 2.4.0-alpha.2 using 0.55.1 as peerDependency and support typescript - support 2.4.0-alpha.3 bugfix iOS receiveStreamMessage data is null - support 2.4.0-alpha.4 bugfix iOS videoSizeChanged field rotation typo -- support 2.4.0-alpha.5 bugfix Android & iOS side not support fit mode and hidden mode. +- support 2.4.0-alpha.5 bugfix Android & iOS side not support fit mode and hidden mode. 1. Deprecate & Remove: setupLocalVideo & setupRemoteVideo 2. rename iOS side constants ``` diff --git a/LICENSE b/LICENSE index 09fd0b91c..22cb860e5 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ -MIT License +The MIT License (MIT) -Copyright (c) 2018 syanbo +Copyright (c) 2020 luxuhui Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -18,4 +18,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file +SOFTWARE. diff --git a/README.md b/README.md index 797b26add..f95ef826e 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,3 @@ -##### 有任何问题欢迎加入 QQ 群进行反馈 471757030 - -## [for 3.0.0 beta version](https://github.com/syanbo/react-native-agora/tree/beta/3.0.0) -### We suggest you use the beta version and welcome to communicate with us by creating issues. -## [for 1.x old version](README.old.md) - # react-native-agora [![npm](https://img.shields.io/npm/v/react-native-agora.svg)](https://www.npmjs.com/package/react-native-agora) @@ -12,60 +6,163 @@ [![npm](https://img.shields.io/npm/l/react-native-agora.svg)](https://github.com/syanbo/react-native-agora/blob/master/LICENSE) [![join chat](https://img.shields.io/badge/gitter-join%20chat-brightgreen.svg)](https://gitter.im/react-native-agora/community) -## Description +The *react-native-agora* is an open-source wrapper for React Native developers. -The react-native-agora is an open-source wrapper for react-native developers. This SDK takes advantage of React Native and Agora RTC Video SDKs on Android/iOS. +This SDK takes advantage of React Native and Agora RTC Video SDK on Android && iOS. -## Compatibility +## Installation -- `>= react native 0.55.x` -- `iOS SDK 8.0+` -- `Android 5.0+ x86 arm64 armv7a` +### Installing (React Native >= 0.60.0) -## [quick start](https://github.com/AgoraIO-Community/Agora-RN-Quickstart) +Install `react-native-agora`(^3.0.0): -## Installation +```shell script +yarn add react-native-agora +``` +or +```shell script +npm i --save react-native-agora +``` + +Go to your ios folder and run: + +```shell script +cd ios +pod install +``` + +**_ IMPORTANT _** + +[Native Modules are now Autolinked.](https://github.com/react-native-community/cli/blob/master/docs/autolinking.md) + +### Installing (React Native == 0.59.x) + +Install `react-native-agora`(^3.0.0): + +```shell script +yarn add react-native-agora +``` +or +```shell script +npm i --save react-native-agora +``` + +**_ IMPORTANT _** + +[Android Installation](./docs/v3/installation.android.md) + +[iOS Installation](./docs/v3/installation.ios.md) + +### Installing (React Native <= 0.58.x) + +**_ IMPORTANT _** + +We no longer support, you can try the older version. + +[Install `react-native-agora`(^1.0.0)](./docs/v1/README.md) + +[Install `react-native-agora`(^2.0.0)](./docs/v2/README.md) + +## General Usage + +```javascript +import RtcEngine from 'react-native-agora'; +RtcEngine.create('YOUR APP ID'); +``` +or +```javascript +const RtcEngine = require('react-native-agora'); +RtcEngine.create('YOUR APP ID'); +``` + +## Using TypeScript + +We suggest you use TypeScript to develop, or use TypeScript eslint to lint your code. + +* [Getting Started with TypeScript](https://reactnative.dev/docs/typescript#getting-started-with-typescript) +* [Adding TypeScript to an Existing Project](https://reactnative.dev/docs/typescript#adding-typescript-to-an-existing-project) + +## Troubleshooting -Install with npm: +### Pod install failed (React Native >= 0.62.0) -`npm install --save react-native-agora` +The error log: -Or, install with yarn: +``` +[!] The 'xxx' target has libraries with conflicting names: libcrypto.a. +``` -`yarn add react-native-agora` +You should disable Flipper, you can found it in the Podfile, and comment the code about Flipper in AppDelegate -If you're on `react-native` < 0.60, you must manually link the project, like below. Otherwise, [Autolinking](https://github.com/react-native-community/cli/blob/master/docs/autolinking.md) is enabled for this project for both Android and iOS. +``` + # Enables Flipper. + # + # Note that if you have use_frameworks! enabled, Flipper will not work and + # you should disable these next few lines. + add_flipper_pods! + post_install do |installer| + flipper_post_install(installer) + end +``` -### For React Native < 0.60 +### RCT_EXTERN_MODULE Swift modules broken in Xcode 10.2 -`react-native link react-native-agora` +The error log: -#### iOS Installation +``` +Swift class extensions and categories on Swift classes are not allowed to have +load methods +``` -[中文](https://github.com/syanbo/react-native-agora/tree/master/docs/IOS_INSTALLATION.zh.md) -[English](https://github.com/syanbo/react-native-agora/tree/master/docs/IOS_INSTALLATION.md) +Fixed in React Native 0.59.3. -#### Android Installation +Source: https://github.com/facebook/react-native/issues/24139 -[中文](https://github.com/syanbo/react-native-agora/tree/master/docs/ANDROID_INSTALLATION.zh.md) -[English](https://github.com/syanbo/react-native-agora/tree/master/docs/ANDROID_INSTALLATION.md) +### XCode 11 Beta App Launch Crash -## Agora Native API Documentation +The error log: -### Android +``` +Exception '*** -[__NSArrayM objectAtIndexedSubscript:]: index 1 beyond bounds [0 .. 0]' was thrown while invoking getCurrentAppState on target AppState with params ( +2, +3 +) +``` -[中文](https://docs.agora.io/cn/Video/API%20Reference/java/index.html) -[English](https://docs.agora.io/en/Video/API%20Reference/java/index.html) +Fixed in React Native 0.59.9. -## iOS +Source: https://github.com/facebook/react-native/issues/25154 -[中文](https://docs.agora.io/cn/Video/API%20Reference/oc/docs/headers/Agora-Objective-C-API-Overview.html) -[English](https://docs.agora.io/en/Video/API%20Reference/oc/docs/headers/Agora-Objective-C-API-Overview.html) +## API -## [API DOCS](https://syanbo.github.io/react-native-agora/globals.html) +* [React Native API](https://syanbo.github.io/react-native-agora/globals.html) +* [Android API](https://docs.agora.io/en/Video/API%20Reference/java/index.html) +* [iOS API](https://docs.agora.io/en/Video/API%20Reference/oc/docs/headers/Agora-Objective-C-API-Overview.html) ## Resources -- Complete [API documentation](https://docs.agora.io/en/) at the Developer Center -- [File bugs about this sample](https://github.com/syanbo/react-native-agora/issues) -- [React Native Getting Started](https://facebook.github.io/react-native/docs/getting-started.html) +* Complete [API Doc](https://docs.agora.io/en/) at the Developer Center +* [File bugs about this sample](https://github.com/syanbo/react-native-agora/issues) +* [React Native Getting Started](https://facebook.github.io/react-native/docs/getting-started.html) + +License +-------- + + Copyright (c) 2020 luxuhui + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. diff --git a/android/CMakeLists.txt b/android/CMakeLists.txt deleted file mode 100644 index d9786cea2..000000000 --- a/android/CMakeLists.txt +++ /dev/null @@ -1,44 +0,0 @@ -# For more information about using CMake with Android Studio, read the -# documentation: https://d.android.com/studio/projects/add-native-code.html - -# Sets the minimum version of CMake required to build the native library. - -cmake_minimum_required(VERSION 3.4.1) - -# Creates and names a library, sets it as either STATIC -# or SHARED, and provides the relative paths to its source code. -# You can define multiple libraries, and CMake builds them for you. -# Gradle automatically packages shared libraries with your APK. - -add_library( # Sets the name of the library. - apm-plugin-raw-data-api-java - - # Sets the library as a shared library. - SHARED - - # Provides a relative path to your source file(s). - src/main/cpp/src/agora_media_pre_processing.cpp ) - -# Searches for a specified prebuilt library and stores the path as a -# variable. Because CMake includes system libraries in the search path by -# default, you only need to specify the name of the public NDK library -# you want to add. CMake verifies that the library exists before -# completing its build. - -find_library( # Sets the name of the path variable. - log-lib - - # Specifies the name of the NDK library that - # you want CMake to locate. - log ) - -# Specifies libraries CMake should link to your target library. You -# can link multiple libraries, such as libraries you define in this -# build script, prebuilt third-party libraries, or system libraries. - -target_link_libraries( # Specifies the target library. - apm-plugin-raw-data-api-java - - # Links the target library to the log library - # included in the NDK. - ${log-lib} ) \ No newline at end of file diff --git a/android/build.gradle b/android/build.gradle index 7abd87f98..85e122430 100644 --- a/android/build.gradle +++ b/android/build.gradle @@ -1,78 +1,37 @@ -apply plugin: 'com.android.library' - -allprojects { - gradle.projectsEvaluated { - tasks.withType(JavaCompile) { - options.encoding = 'utf-8' - options.compilerArgs << "-Xlint:deprecation" - } - } +def safeExtGet(prop, fallback) { + rootProject.ext.has(prop) ? rootProject.ext.get(prop) : fallback } buildscript { + def kotlin_version = rootProject.ext.has('kotlin_version') ? rootProject.ext.get('kotlin_version') : '1.3.72' + repositories { google() jcenter() } dependencies { - classpath 'com.android.tools.build:gradle:3.1.2' + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } } -def DEFAULT_COMPILE_SDK_VERSION = 27 -def DEFAULT_BUILD_TOOLS_VERSION = "27.0.3" -def DEFAULT_TARGET_SDK_VERSION = 27 -def DEFAULT_ANDROID_SUPPORT_VERSION = "27.1.0" +apply plugin: 'com.android.library' +apply plugin: 'kotlin-android' +apply plugin: 'kotlin-android-extensions' android { - compileSdkVersion rootProject.hasProperty('compileSdkVersion') ? rootProject.compileSdkVersion : DEFAULT_COMPILE_SDK_VERSION - buildToolsVersion rootProject.hasProperty('buildToolsVersion') ? rootProject.buildToolsVersion : DEFAULT_BUILD_TOOLS_VERSION + compileSdkVersion safeExtGet('compileSdkVersion', 28) + buildToolsVersion safeExtGet('buildToolsVersion', '28.0.3') defaultConfig { - minSdkVersion 16 - targetSdkVersion rootProject.hasProperty('targetSdkVersion') ? rootProject.targetSdkVersion : DEFAULT_TARGET_SDK_VERSION - versionCode 1 - versionName "1.0" - - testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" + minSdkVersion safeExtGet('minSdkVersion', 16) + targetSdkVersion safeExtGet('targetSdkVersion', 28) - } - buildTypes { - release { - minifyEnabled false - proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' - } - } - - splits { - abi { - enable true - - reset() - - include "armeabi-v7a", "arm64-v8a", "x86", "x86_64" - // Specify that we do not want an additional universal SDK - universalApk false - } + consumerProguardFiles 'consumer-rules.pro' } } dependencies { - def androidSupportVersion = rootProject.hasProperty("androidSupportVersion") ? rootProject.androidSupportVersion : DEFAULT_ANDROID_SUPPORT_VERSION - // from internet - implementation "com.android.support:appcompat-v7:$androidSupportVersion" - implementation "io.agora.rtc:full-sdk:2.9.4" - // from node_modules implementation "com.facebook.react:react-native:+" + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:${safeExtGet('kotlin_version', '1.3.72')}" + implementation "io.agora.rtc:full-sdk:3.0.1.1" } - -repositories { - mavenCentral() - mavenLocal() - maven { - url "$rootDir/../node_modules/react-native-agora/android" - } - jcenter() - google() -} - diff --git a/android/consumer-rules.pro b/android/consumer-rules.pro new file mode 100644 index 000000000..c3b392b4d --- /dev/null +++ b/android/consumer-rules.pro @@ -0,0 +1 @@ +-keep class io.agora.**{*;} diff --git a/android/gradle/wrapper/gradle-wrapper.jar b/android/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index f6b961fd5..000000000 Binary files a/android/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index 9a4163a4f..000000000 --- a/android/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,5 +0,0 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-all.zip -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists diff --git a/android/gradlew b/android/gradlew deleted file mode 100755 index cccdd3d51..000000000 --- a/android/gradlew +++ /dev/null @@ -1,172 +0,0 @@ -#!/usr/bin/env sh - -############################################################################## -## -## Gradle start up script for UN*X -## -############################################################################## - -# Attempt to set APP_HOME -# Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi -done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null - -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS="" - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" - -warn () { - echo "$*" -} - -die () { - echo - echo "$*" - echo - exit 1 -} - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; -esac - -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar - -# Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." -fi - -# Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi -fi - -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi - -# For Cygwin, switch paths to Windows format before running java -if $cygwin ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi - # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" - fi - i=$((i+1)) - done - case $i in - (0) set -- ;; - (1) set -- "$args0" ;; - (2) set -- "$args0" "$args1" ;; - (3) set -- "$args0" "$args1" "$args2" ;; - (4) set -- "$args0" "$args1" "$args2" "$args3" ;; - (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac -fi - -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=$(save "$@") - -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" - -# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong -if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then - cd "$(dirname "$0")" -fi - -exec "$JAVACMD" "$@" diff --git a/android/gradlew.bat b/android/gradlew.bat deleted file mode 100755 index e95643d6a..000000000 --- a/android/gradlew.bat +++ /dev/null @@ -1,84 +0,0 @@ -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega diff --git a/android/proguard-rules.pro b/android/proguard-rules.pro deleted file mode 100644 index 7ea4004ea..000000000 --- a/android/proguard-rules.pro +++ /dev/null @@ -1,17 +0,0 @@ -# Add project specific ProGuard rules here. -# By default, the flags in this file are appended to flags specified -# in /Users/DB/Library/Android/sdk/tools/proguard/proguard-android.txt -# You can edit the include path and order by changing the proguardFiles -# directive in build.gradle. -# -# For more details, see -# http://developer.android.com/guide/developing/tools/proguard.html - -# Add any project specific keep options here: - -# If your project uses WebView with JS, uncomment the following -# and specify the fully qualified class name to the JavaScript interface -# class: -#-keepclassmembers class fqcn.of.javascript.interface.for.webview { -# public *; -#} diff --git a/android/src/main/AndroidManifest.xml b/android/src/main/AndroidManifest.xml index 866ac5378..c78e0b7c9 100644 --- a/android/src/main/AndroidManifest.xml +++ b/android/src/main/AndroidManifest.xml @@ -1,17 +1,18 @@ - + + - - - - - - + + + diff --git a/android/src/main/cpp/include/AgoraBase.h b/android/src/main/cpp/include/AgoraBase.h deleted file mode 100644 index a4b6ab96a..000000000 --- a/android/src/main/cpp/include/AgoraBase.h +++ /dev/null @@ -1,781 +0,0 @@ -// Agora Engine SDK -// -// Copyright (c) 2019 Agora.io. All rights reserved. -// - -#ifndef AGORA_BASE_H -#define AGORA_BASE_H - -#include -#include -#include - -#if defined(_WIN32) -#define WIN32_LEAN_AND_MEAN -#include -#define AGORA_CALL __cdecl -#if defined(AGORARTC_EXPORT) -#define AGORA_API extern "C" __declspec(dllexport) -#else -#define AGORA_API extern "C" __declspec(dllimport) -#endif -#elif defined(__APPLE__) -#include -#define AGORA_API __attribute__((visibility("default"))) extern "C" -#define AGORA_CALL -#elif defined(__ANDROID__) || defined(__linux__) -#define AGORA_API extern "C" __attribute__((visibility("default"))) -#define AGORA_CALL -#else -#define AGORA_API extern "C" -#define AGORA_CALL -#endif - -namespace agora { -namespace util { - -template -class AutoPtr { - typedef T value_type; - typedef T* pointer_type; -public: - AutoPtr(pointer_type p=0) - :ptr_(p) - {} - ~AutoPtr() { - if (ptr_) - ptr_->release(); - } - operator bool() const { return ptr_ != (pointer_type)0; } - value_type& operator*() const { - return *get(); - } - - pointer_type operator->() const { - return get(); - } - - pointer_type get() const { - return ptr_; - } - - pointer_type release() { - pointer_type tmp = ptr_; - ptr_ = 0; - return tmp; - } - - void reset(pointer_type ptr = 0) { - if (ptr != ptr_ && ptr_) - ptr_->release(); - ptr_ = ptr; - } - template - bool queryInterface(C1* c, C2 iid) { - pointer_type p = NULL; - if (c && !c->queryInterface(iid, (void**)&p)) - { - reset(p); - } - return p != NULL; - } -private: - AutoPtr(const AutoPtr&); - AutoPtr& operator=(const AutoPtr&); -private: - pointer_type ptr_; -}; -class IString { -protected: - virtual ~IString(){} -public: - virtual bool empty() const = 0; - virtual const char* c_str() = 0; - virtual const char* data() = 0; - virtual size_t length() = 0; - virtual void release() = 0; -}; -typedef AutoPtr AString; - -}//namespace util - -enum INTERFACE_ID_TYPE -{ - AGORA_IID_AUDIO_DEVICE_MANAGER = 1, - AGORA_IID_VIDEO_DEVICE_MANAGER = 2, - AGORA_IID_RTC_ENGINE_PARAMETER = 3, - AGORA_IID_MEDIA_ENGINE = 4, - AGORA_IID_SIGNALING_ENGINE = 8, -}; - - /** Warning code. - */ -enum WARN_CODE_TYPE -{ - /** 8: The specified view is invalid. Specify a view when using the video call function. - */ - WARN_INVALID_VIEW = 8, - /** 16: Failed to initialize the video function, possibly caused by a lack of resources. The users cannot see the video while the voice communication is not affected. - */ - WARN_INIT_VIDEO = 16, - /** 20: The request is pending, usually due to some module not being ready, and the SDK postponed processing the request. - */ - WARN_PENDING = 20, - /** 103: No channel resources are available. Maybe because the server cannot allocate any channel resource. - */ - WARN_NO_AVAILABLE_CHANNEL = 103, - /** 104: A timeout occurs when looking up the channel. When joining a channel, the SDK looks up the specified channel. This warning usually occurs when the network condition is too poor for the SDK to connect to the server. - */ - WARN_LOOKUP_CHANNEL_TIMEOUT = 104, - /** **DEPRECATED** 105: The server rejects the request to look up the channel. The server cannot process this request or the request is illegal. - - Deprecated as of v2.4.1. Use CONNECTION_CHANGED_REJECTED_BY_SERVER(10) in the \ref agora::rtc::IRtcEngineEventHandler::onConnectionStateChanged "onConnectionStateChanged" callback instead. - */ - WARN_LOOKUP_CHANNEL_REJECTED = 105, - /** 106: A timeout occurs when opening the channel. Once the specific channel is found, the SDK opens the channel. This warning usually occurs when the network condition is too poor for the SDK to connect to the server. - */ - WARN_OPEN_CHANNEL_TIMEOUT = 106, - /** 107: The server rejects the request to open the channel. The server cannot process this request or the request is illegal. - */ - WARN_OPEN_CHANNEL_REJECTED = 107, - - // sdk: 100~1000 - /** 111: A timeout occurs when switching to the live video. - */ - WARN_SWITCH_LIVE_VIDEO_TIMEOUT = 111, - /** 118: A timeout occurs when setting the client role in the live broadcast profile. - */ - WARN_SET_CLIENT_ROLE_TIMEOUT = 118, - /** 121: The ticket to open the channel is invalid. - */ - WARN_OPEN_CHANNEL_INVALID_TICKET = 121, - /** 122: Try connecting to another server. - */ - WARN_OPEN_CHANNEL_TRY_NEXT_VOS = 122, - WARN_CHANNEL_CONNECTION_UNRECOVERABLE = 131, - WARN_CHANNEL_CONNECTION_IP_CHANGED = 132, - WARN_CHANNEL_CONNECTION_PORT_CHANGED = 133, - /** 701: An error occurs in opening the audio mixing file. - */ - WARN_AUDIO_MIXING_OPEN_ERROR = 701, - /** 1014: Audio Device Module: a warning occurs in the playback device. - */ - WARN_ADM_RUNTIME_PLAYOUT_WARNING = 1014, - /** 1016: Audio Device Module: a warning occurs in the recording device. - */ - WARN_ADM_RUNTIME_RECORDING_WARNING = 1016, - /** 1019: Audio Device Module: no valid audio data is collected. - */ - WARN_ADM_RECORD_AUDIO_SILENCE = 1019, - /** 1020: Audio Device Module: the playback device fails. - */ - WARN_ADM_PLAYOUT_MALFUNCTION = 1020, - /** 1021: Audio Device Module: the recording device fails. - */ - WARN_ADM_RECORD_MALFUNCTION = 1021, - /** 1029: During a call, the audio session category should be set to - * AVAudioSessionCategoryPlayAndRecord, and RtcEngine monitors this value. - * If the audio session category is set to other values, this warning code - * is triggered and RtcEngine will forcefully set it back to - * AVAudioSessionCategoryPlayAndRecord. - */ - WARN_ADM_IOS_CATEGORY_NOT_PLAYANDRECORD = 1029, - /** - */ - WARN_ADM_IOS_SAMPLERATE_CHANGE = 1030, - /** 1031: Audio Device Module: the recorded audio voice is too low. - */ - WARN_ADM_RECORD_AUDIO_LOWLEVEL = 1031, - /** 1032: Audio Device Module: the playback audio voice is too low. - */ - WARN_ADM_PLAYOUT_AUDIO_LOWLEVEL = 1032, - /** 1040: Audio device module: An exception occurs with the audio drive. - * Solutions: - * - Disable or re-enable the audio device. - * - Re-enable your device. - * - Update the sound card drive. - */ - WARN_ADM_WINDOWS_NO_DATA_READY_EVENT = 1040, - /** 1051: Audio Device Module: howling is detected. - */ - WARN_APM_HOWLING = 1051, - /** 1052: Audio Device Module: the device is in the glitch state. - */ - WARN_ADM_GLITCH_STATE = 1052, - /** 1053: Audio Device Module: the underlying audio settings have changed. - */ - WARN_ADM_IMPROPER_SETTINGS = 1053, - /** - */ - WARN_ADM_WIN_CORE_NO_RECORDING_DEVICE = 1322, - /** 1323: Audio device module: No available playback device. - * Solution: Plug in the audio device. - */ - WARN_ADM_WIN_CORE_NO_PLAYOUT_DEVICE = 1323, - /** Audio device module: The capture device is released improperly. - * Solutions: - * - Disable or re-enable the audio device. - * - Re-enable your device. - * - Update the sound card drive. - */ - WARN_ADM_WIN_CORE_IMPROPER_CAPTURE_RELEASE = 1324, - /** 1610: Super-resolution warning: the original video dimensions of the remote user exceed 640 × 480. - */ - WARN_SUPER_RESOLUTION_STREAM_OVER_LIMITATION = 1610, - /** 1611: Super-resolution warning: another user is using super resolution. - */ - WARN_SUPER_RESOLUTION_USER_COUNT_OVER_LIMITATION = 1611, - /** 1612: The device is not supported. - */ - WARN_SUPER_RESOLUTION_DEVICE_NOT_SUPPORTED = 1612, - - WARN_RTM_LOGIN_TIMEOUT = 2005, - WARN_RTM_KEEP_ALIVE_TIMEOUT = 2009 -}; - -/** Error code. -*/ -enum ERROR_CODE_TYPE -{ - /** 0: No error occurs. - */ - ERR_OK = 0, - //1~1000 - /** 1: A general error occurs (no specified reason). - */ - ERR_FAILED = 1, - /** 2: An invalid parameter is used. For example, the specific channel name includes illegal characters. - */ - ERR_INVALID_ARGUMENT = 2, - /** 3: The SDK module is not ready. Possible solutions: - - - Check the audio device. - - Check the completeness of the application. - - Re-initialize the RTC engine. - */ - ERR_NOT_READY = 3, - /** 4: The SDK does not support this function. - */ - ERR_NOT_SUPPORTED = 4, - /** 5: The request is rejected. This is for internal SDK use only, and it does not return to the application through any method or callback. - */ - ERR_REFUSED = 5, - /** 6: The buffer size is not big enough to store the returned data. - */ - ERR_BUFFER_TOO_SMALL = 6, - /** 7: The SDK is not initialized before calling this method. - */ - ERR_NOT_INITIALIZED = 7, - /** 9: No permission exists. This is for internal SDK use only, and it does not return to the application through any method or callback. - */ - ERR_NO_PERMISSION = 9, - /** 10: An API method timeout occurs. Some API methods require the SDK to return the execution result, and this error occurs if the request takes too long (more than 10 seconds) for the SDK to process. - */ - ERR_TIMEDOUT = 10, - /** 11: The request is canceled. This is for internal SDK use only, and it does not return to the application through any method or callback. - */ - ERR_CANCELED = 11, - /** 12: The method is called too often. This is for internal SDK use only, and it does not return to the application through any method or callback. - */ - ERR_TOO_OFTEN = 12, - /** 13: The SDK fails to bind to the network socket. This is for internal SDK use only, and it does not return to the application through any method or callback. - */ - ERR_BIND_SOCKET = 13, - /** 14: The network is unavailable. This is for internal SDK use only, and it does not return to the application through any method or callback. - */ - ERR_NET_DOWN = 14, - /** 15: No network buffers are available. This is for internal SDK internal use only, and it does not return to the application through any method or callback. - */ - ERR_NET_NOBUFS = 15, - /** 17: The request to join the channel is rejected. This error usually occurs when the user is already in the channel, and still calls the method to join the channel, for example, \ref agora::rtc::IRtcEngine::joinChannel "joinChannel". - */ - ERR_JOIN_CHANNEL_REJECTED = 17, - /** 18: The request to leave the channel is rejected. - - This error usually occurs: - - - When the user has left the channel and still calls \ref agora::rtc::IRtcEngine::leaveChannel "leaveChannel" to leave the channel. In this case, stop calling \ref agora::rtc::IRtcEngine::leaveChannel "leaveChannel". - - When the user has not joined the channel and still calls \ref agora::rtc::IRtcEngine::leaveChannel "leaveChannel" to leave the channel. In this case, no extra operation is needed. - */ - ERR_LEAVE_CHANNEL_REJECTED = 18, - /** 19: Resources are occupied and cannot be reused. - */ - ERR_ALREADY_IN_USE = 19, - /** 20: The SDK gives up the request due to too many requests. - */ - ERR_ABORTED = 20, - /** 21: In Windows, specific firewall settings can cause the SDK to fail to initialize and crash. - */ - ERR_INIT_NET_ENGINE = 21, - /** 22: The application uses too much of the system resources and the SDK fails to allocate the resources. - */ - ERR_RESOURCE_LIMITED = 22, - /** 101: The specified App ID is invalid. Please try to rejoin the channel with a valid App ID. - */ - ERR_INVALID_APP_ID = 101, - /** 102: The specified channel name is invalid. Please try to rejoin the channel with a valid channel name. - */ - ERR_INVALID_CHANNEL_NAME = 102, - /** **DEPRECATED** 109: Deprecated as of v2.4.1. Use CONNECTION_CHANGED_TOKEN_EXPIRED(9) in the \ref agora::rtc::IRtcEngineEventHandler::onConnectionStateChanged "onConnectionStateChanged" callback instead. - - The token expired due to one of the following reasons: - - - Authorized Timestamp expired: The timestamp is represented by the number of seconds elapsed since 1/1/1970. The user can use the Token to access the Agora service within five minutes after the Token is generated. If the user does not access the Agora service after five minutes, this Token is no longer valid. - - Call Expiration Timestamp expired: The timestamp is the exact time when a user can no longer use the Agora service (for example, when a user is forced to leave an ongoing call). When a value is set for the Call Expiration Timestamp, it does not mean that the token will expire, but that the user will be banned from the channel. - */ - ERR_TOKEN_EXPIRED = 109, - /** **DEPRECATED** 110: Deprecated as of v2.4.1. Use CONNECTION_CHANGED_INVALID_TOKEN(8) in the \ref agora::rtc::IRtcEngineEventHandler::onConnectionStateChanged "onConnectionStateChanged" callback instead. - - The token is invalid due to one of the following reasons: - - - The App Certificate for the project is enabled in Dashboard, but the user is still using the App ID. Once the App Certificate is enabled, the user must use a token. - - The uid is mandatory, and users must set the same uid as the one set in the \ref agora::rtc::IRtcEngine::joinChannel "joinChannel" method. - */ - ERR_INVALID_TOKEN = 110, - /** 111: The internet connection is interrupted. This applies to the Agora Web SDK only. - */ - ERR_CONNECTION_INTERRUPTED = 111, // only used in web sdk - /** 112: The internet connection is lost. This applies to the Agora Web SDK only. - */ - ERR_CONNECTION_LOST = 112, // only used in web sdk - /** 113: The user is not in the channel when calling the \ref agora::rtc::IRtcEngine::sendStreamMessage "sendStreamMessage" or \ref agora::rtc::IRtcEngine::getUserInfoByUserAccount "getUserInfoByUserAccount" method. - */ - ERR_NOT_IN_CHANNEL = 113, - /** 114: The size of the sent data is over 1024 bytes when the user calls the \ref agora::rtc::IRtcEngine::sendStreamMessage "sendStreamMessage" method. - */ - ERR_SIZE_TOO_LARGE = 114, - /** 115: The bitrate of the sent data exceeds the limit of 6 Kbps when the user calls the \ref agora::rtc::IRtcEngine::sendStreamMessage "sendStreamMessage" method. - */ - ERR_BITRATE_LIMIT = 115, - /** 116: Too many data streams (over 5 streams) are created when the user calls the \ref agora::rtc::IRtcEngine::createDataStream "createDataStream" method. - */ - ERR_TOO_MANY_DATA_STREAMS = 116, - /** 117: The data stream transmission timed out. - */ - ERR_STREAM_MESSAGE_TIMEOUT = 117, - /** 119: Switching roles fail. Please try to rejoin the channel. - */ - ERR_SET_CLIENT_ROLE_NOT_AUTHORIZED = 119, - /** 120: Decryption fails. The user may have used a different encryption password to join the channel. Check your settings or try rejoining the channel. - */ - ERR_DECRYPTION_FAILED = 120, - /** 123: The client is banned by the server. - */ - ERR_CLIENT_IS_BANNED_BY_SERVER = 123, - /** 124: Incorrect watermark file parameter. - */ - ERR_WATERMARK_PARAM = 124, - /** 125: Incorrect watermark file path. - */ - ERR_WATERMARK_PATH = 125, - /** 126: Incorrect watermark file format. - */ - ERR_WATERMARK_PNG = 126, - /** 127: Incorrect watermark file information. - */ - ERR_WATERMARKR_INFO = 127, - /** 128: Incorrect watermark file data format. - */ - ERR_WATERMARK_ARGB = 128, - /** 129: An error occurs in reading the watermark file. - */ - ERR_WATERMARK_READ = 129, - /** 130: Encryption is enabled when the user calls the \ref agora::rtc::IRtcEngine::addPublishStreamUrl "addPublishStreamUrl" method (CDN live streaming does not support encrypted streams). - */ - ERR_ENCRYPTED_STREAM_NOT_ALLOWED_PUBLISH = 130, - /** 134: The user account is invalid. */ - ERR_INVALID_USER_ACCOUNT = 134, - - /** 151: CDN related errors. Remove the original URL address and add a new one by calling the \ref agora::rtc::IRtcEngine::removePublishStreamUrl "removePublishStreamUrl" and \ref agora::rtc::IRtcEngine::addPublishStreamUrl "addPublishStreamUrl" methods. - */ - ERR_PUBLISH_STREAM_CDN_ERROR = 151, - /** 152: The host publishes more than 10 URLs. Delete the unnecessary URLs before adding new ones. - */ - ERR_PUBLISH_STREAM_NUM_REACH_LIMIT = 152, - /** 153: The host manipulates other hosts' URLs. Check your app logic. - */ - ERR_PUBLISH_STREAM_NOT_AUTHORIZED = 153, - /** 154: An error occurs in Agora's streaming server. Call the addPublishStreamUrl method to publish the streaming again. - */ - ERR_PUBLISH_STREAM_INTERNAL_SERVER_ERROR = 154, - /** 155: The server fails to find the stream. - */ - ERR_PUBLISH_STREAM_NOT_FOUND = 155, - /** 156: The format of the RTMP stream URL is not supported. Check whether the URL format is correct. - */ - ERR_PUBLISH_STREAM_FORMAT_NOT_SUPPORTED = 156, - - //signaling: 400~600 - /** - */ - ERR_LOGOUT_OTHER = 400, // - /** 401: The user logged out. - */ - ERR_LOGOUT_USER = 401, // logout by user - /** 402: Network failure. - */ - ERR_LOGOUT_NET = 402, // network failure - /** 403: Logged in another device. - */ - ERR_LOGOUT_KICKED = 403, // login in other device - /** - */ - ERR_LOGOUT_PACKET = 404, // - /** 405: The token expired. - */ - ERR_LOGOUT_TOKEN_EXPIRED = 405, // token expired - /** - */ - ERR_LOGOUT_OLDVERSION = 406, // - /** - */ - ERR_LOGOUT_TOKEN_WRONG = 407, - /** - */ - ERR_LOGOUT_ALREADY_LOGOUT = 408, - /** - */ - ERR_LOGIN_OTHER = 420, - /** - */ - ERR_LOGIN_NET = 421, - /** - */ - ERR_LOGIN_FAILED = 422, - /** - */ - ERR_LOGIN_CANCELED = 423, - /** - */ - ERR_LOGIN_TOKEN_EXPIRED = 424, - /** - */ - ERR_LOGIN_OLD_VERSION = 425, - /** - */ - ERR_LOGIN_TOKEN_WRONG = 426, - /** - */ - ERR_LOGIN_TOKEN_KICKED = 427, - /** - */ - ERR_LOGIN_ALREADY_LOGIN = 428, - /** - */ - ERR_JOIN_CHANNEL_OTHER = 440, - /** - */ - ERR_SEND_MESSAGE_OTHER = 440, - /** - */ - ERR_SEND_MESSAGE_TIMEOUT = 441, - /** - */ - ERR_QUERY_USERNUM_OTHER = 450, - /** - */ - ERR_QUERY_USERNUM_TIMEOUT = 451, - /** - */ - ERR_QUERY_USERNUM_BYUSER = 452, - /** - */ - ERR_LEAVE_CHANNEL_OTHER = 460, - /** - */ - ERR_LEAVE_CHANNEL_KICKED = 461, - /** - */ - ERR_LEAVE_CHANNEL_BYUSER = 462, - /** - */ - ERR_LEAVE_CHANNEL_LOGOUT = 463, - /** - */ - ERR_LEAVE_CHANNEL_DISCONNECTED = 464, - /** - */ - ERR_INVITE_OTHER = 470, - /** - */ - ERR_INVITE_REINVITE = 471, - /** - */ - ERR_INVITE_NET = 472, - /** - */ - ERR_INVITE_PEER_OFFLINE = 473, - ERR_INVITE_TIMEOUT = 474, - ERR_INVITE_CANT_RECV = 475, - - - //1001~2000 - /** 1001: Fails to load the media engine. - */ - ERR_LOAD_MEDIA_ENGINE = 1001, - /** 1002: Fails to start the call after enabling the media engine. - */ - ERR_START_CALL = 1002, - /** **DEPRECATED** 1003: Fails to start the camera. - - Deprecated as of v2.4.1. Use LOCAL_VIDEO_STREAM_ERROR_CAPTURE_FAILURE(4) in the \ref agora::rtc::IRtcEngineEventHandler::onConnectionStateChanged "onConnectionStateChanged" callback instead. - */ - ERR_START_CAMERA = 1003, - /** 1004: Fails to start the video rendering module. - */ - ERR_START_VIDEO_RENDER = 1004, - /** 1005: A general error occurs in the Audio Device Module (no specified reason). Check if the audio device is used by another application, or try rejoining the channel. - */ - ERR_ADM_GENERAL_ERROR = 1005, - /** 1006: Audio Device Module: An error occurs in using the Java resources. - */ - ERR_ADM_JAVA_RESOURCE = 1006, - /** 1007: Audio Device Module: An error occurs in setting the sampling frequency. - */ - ERR_ADM_SAMPLE_RATE = 1007, - /** 1008: Audio Device Module: An error occurs in initializing the playback device. - */ - ERR_ADM_INIT_PLAYOUT = 1008, - /** 1009: Audio Device Module: An error occurs in starting the playback device. - */ - ERR_ADM_START_PLAYOUT = 1009, - /** 1010: Audio Device Module: An error occurs in stopping the playback device. - */ - ERR_ADM_STOP_PLAYOUT = 1010, - /** 1011: Audio Device Module: An error occurs in initializing the recording device. - */ - ERR_ADM_INIT_RECORDING = 1011, - /** 1012: Audio Device Module: An error occurs in starting the recording device. - */ - ERR_ADM_START_RECORDING = 1012, - /** 1013: Audio Device Module: An error occurs in stopping the recording device. - */ - ERR_ADM_STOP_RECORDING = 1013, - /** 1015: Audio Device Module: A playback error occurs. Check your playback device and try rejoining the channel. - */ - ERR_ADM_RUNTIME_PLAYOUT_ERROR = 1015, - /** 1017: Audio Device Module: A recording error occurs. - */ - ERR_ADM_RUNTIME_RECORDING_ERROR = 1017, - /** 1018: Audio Device Module: Fails to record. - */ - ERR_ADM_RECORD_AUDIO_FAILED = 1018, - /** 1022: Audio Device Module: An error occurs in initializing the - * loopback device. - */ - ERR_ADM_INIT_LOOPBACK = 1022, - /** 1023: Audio Device Module: An error occurs in starting the loopback - * device. - */ - ERR_ADM_START_LOOPBACK = 1023, - /** 1027: Audio Device Module: No recording permission exists. Check if the - * recording permission is granted. - */ - ERR_ADM_NO_PERMISSION = 1027, - /** 1033: Audio device module: The device is occupied. - */ - ERR_ADM_RECORD_AUDIO_IS_ACTIVE = 1033, - /** 1101: Audio device module: A fatal exception occurs. - */ - ERR_ADM_ANDROID_JNI_JAVA_RESOURCE = 1101, - /** 1108: Audio device module: The recording frequency is lower than 50. - * 0 indicates that the recording is not yet started. We recommend - * checking your recording permission. - */ - ERR_ADM_ANDROID_JNI_NO_RECORD_FREQUENCY = 1108, - /** 1109: The playback frequency is lower than 50. 0 indicates that the - * playback is not yet started. We recommend checking if you have created - * too many AudioTrack instances. - */ - ERR_ADM_ANDROID_JNI_NO_PLAYBACK_FREQUENCY = 1109, - /** 1111: Audio device module: AudioRecord fails to start up. A ROM system - * error occurs. We recommend the following options to debug: - * - Restart your App. - * - Restart your cellphone. - * - Check your recording permission. - */ - ERR_ADM_ANDROID_JNI_JAVA_START_RECORD = 1111, - /** 1112: Audio device module: AudioTrack fails to start up. A ROM system - * error occurs. We recommend the following options to debug: - * - Restart your App. - * - Restart your cellphone. - * - Check your playback permission. - */ - ERR_ADM_ANDROID_JNI_JAVA_START_PLAYBACK = 1112, - /** 1115: Audio device module: AudioRecord returns error. The SDK will - * automatically restart AudioRecord. */ - ERR_ADM_ANDROID_JNI_JAVA_RECORD_ERROR = 1115, - /** **DEPRECATED** */ - ERR_ADM_ANDROID_OPENSL_CREATE_ENGINE = 1151, - /** **DEPRECATED** */ - ERR_ADM_ANDROID_OPENSL_CREATE_AUDIO_RECORDER = 1153, - /** **DEPRECATED** */ - ERR_ADM_ANDROID_OPENSL_START_RECORDER_THREAD = 1156, - /** **DEPRECATED** */ - ERR_ADM_ANDROID_OPENSL_CREATE_AUDIO_PLAYER = 1157, - /** **DEPRECATED** */ - ERR_ADM_ANDROID_OPENSL_START_PLAYER_THREAD = 1160, - /** 1201: Audio device module: The current device does not support audio - * input, possibly because you have mistakenly configured the audio session - * category, or because some other app is occupying the input device. We - * recommend terminating all background apps and re-joining the channel. */ - ERR_ADM_IOS_INPUT_NOT_AVAILABLE = 1201, - /** 1206: Audio device module: Cannot activate the Audio Session.*/ - ERR_ADM_IOS_ACTIVATE_SESSION_FAIL = 1206, - /** 1210: Audio device module: Fails to initialize the audio device, - * normally because the audio device parameters are wrongly set.*/ - ERR_ADM_IOS_VPIO_INIT_FAIL = 1210, - /** 1213: Audio device module: Fails to re-initialize the audio device, - * normally because the audio device parameters are wrongly set.*/ - ERR_ADM_IOS_VPIO_REINIT_FAIL = 1213, - /** 1214: Fails to re-start up the Audio Unit, possibly because the audio - * session category is not compatible with the settings of the Audio Unit. - */ - ERR_ADM_IOS_VPIO_RESTART_FAIL = 1214, - ERR_ADM_IOS_SET_RENDER_CALLBACK_FAIL = 1219, - /** **DEPRECATED** */ - ERR_ADM_IOS_SESSION_SAMPLERATR_ZERO = 1221, - /** 1301: Audio device module: An audio driver abnomality or a - * compatibility issue occurs. Solutions: Disable and restart the audio - * device, or reboot the system.*/ - ERR_ADM_WIN_CORE_INIT = 1301, - /** 1303: Audio device module: A recording driver abnomality or a - * compatibility issue occurs. Solutions: Disable and restart the audio - * device, or reboot the system. */ - ERR_ADM_WIN_CORE_INIT_RECORDING = 1303, - /** 1306: Audio device module: A playout driver abnomality or a - * compatibility issue occurs. Solutions: Disable and restart the audio - * device, or reboot the system. */ - ERR_ADM_WIN_CORE_INIT_PLAYOUT = 1306, - /** 1307: Audio device module: No audio device is available. Solutions: - * Plug in a proper audio device. */ - ERR_ADM_WIN_CORE_INIT_PLAYOUT_NULL = 1307, - /** 1309: Audio device module: An audio driver abnomality or a - * compatibility issue occurs. Solutions: Disable and restart the audio - * device, or reboot the system. */ - ERR_ADM_WIN_CORE_START_RECORDING = 1309, - /** 1311: Audio device module: Insufficient system memory or poor device - * performance. Solutions: Reboot the system or replace the device. - */ - ERR_ADM_WIN_CORE_CREATE_REC_THREAD = 1311, - /** 1314: Audio device module: An audio driver abnormality occurs. - * Solutions: - * - Disable and then re-enable the audio device. - * - Reboot the system. - * - Upgrade your audio card driver.*/ - ERR_ADM_WIN_CORE_CAPTURE_NOT_STARTUP = 1314, - /** 1319: Audio device module: Insufficient system memory or poor device - * performance. Solutions: Reboot the system or replace the device. */ - ERR_ADM_WIN_CORE_CREATE_RENDER_THREAD = 1319, - /** 1320: Audio device module: An audio driver abnormality occurs. - * Solutions: - * - Disable and then re-enable the audio device. - * - Reboot the system. - * - Replace the device. */ - ERR_ADM_WIN_CORE_RENDER_NOT_STARTUP = 1320, - /** 1322: Audio device module: No audio sampling device is available. - * Solutions: Plug in a proper recording device. */ - ERR_ADM_WIN_CORE_NO_RECORDING_DEVICE = 1322, - /** 1323: Audio device module: No audio playout device is available. - * Solutions: Plug in a proper playback device.*/ - ERR_ADM_WIN_CORE_NO_PLAYOUT_DEVICE = 1323, - /** 1351: Audio device module: An audio driver abnormality or a - * compatibility issue occurs. Solutions: - * - Disable and then re-enable the audio device. - * - Reboot the system. - * - Upgrade your audio card driver. */ - ERR_ADM_WIN_WAVE_INIT = 1351, - /** 1353: Audio device module: An audio driver abnormality occurs. - * Solutions: - * - Disable and then re-enable the audio device. - * - Reboot the system. - * - Upgrade your audio card driver. */ - ERR_ADM_WIN_WAVE_INIT_RECORDING = 1353, - /** 1354: Audio device module: An audio driver abnormality occurs. - * Solutions: - * - Disable and then re-enable the audio device. - * - Reboot the system. - * - Upgrade your audio card driver. */ - ERR_ADM_WIN_WAVE_INIT_MICROPHONE = 1354, - /** 1355: Audio device module: An audio driver abnormality occurs. - * Solutions: - * - Disable and then re-enable the audio device. - * - Reboot the system. - * - Upgrade your audio card driver. */ - ERR_ADM_WIN_WAVE_INIT_PLAYOUT = 1355, - /** 1356: Audio device module: An audio driver abnormality occurs. - * Solutions: - * - Disable and then re-enable the audio device. - * - Reboot the system. - * - Upgrade your audio card driver. */ - ERR_ADM_WIN_WAVE_INIT_SPEAKER = 1356, - /** 1357: Audio device module: An audio driver abnormality occurs. - * Solutions: - * - Disable and then re-enable the audio device. - * - Reboot the system. - * - Upgrade your audio card driver. */ - ERR_ADM_WIN_WAVE_START_RECORDING = 1357, - /** 1358: Audio device module: An audio driver abnormality occurs. - * Solutions: - * - Disable and then re-enable the audio device. - * - Reboot the system. - * - Upgrade your audio card driver.*/ - ERR_ADM_WIN_WAVE_START_PLAYOUT = 1358, - /** 1359: Audio Device Module: No recording device exists. - */ - ERR_ADM_NO_RECORDING_DEVICE = 1359, - /** 1360: Audio Device Module: No playback device exists. - */ - ERR_ADM_NO_PLAYOUT_DEVICE = 1360, - - // VDM error code starts from 1500 - /** 1501: Video Device Module: The camera is unauthorized. - */ - ERR_VDM_CAMERA_NOT_AUTHORIZED = 1501, - - // VDM error code starts from 1500 - /** **DEPRECATED** 1502: Video Device Module: The camera in use. - - Deprecated as of v2.4.1. Use LOCAL_VIDEO_STREAM_ERROR_DEVICE_BUSY(3) in the \ref agora::rtc::IRtcEngineEventHandler::onConnectionStateChanged "onConnectionStateChanged" callback instead. - */ - ERR_VDM_WIN_DEVICE_IN_USE = 1502, - - // VCM error code starts from 1600 - /** 1600: Video Device Module: An unknown error occurs. - */ - ERR_VCM_UNKNOWN_ERROR = 1600, - /** 1601: Video Device Module: An error occurs in initializing the video encoder. - */ - ERR_VCM_ENCODER_INIT_ERROR = 1601, - /** 1602: Video Device Module: An error occurs in encoding. - */ - ERR_VCM_ENCODER_ENCODE_ERROR = 1602, - /** 1603: Video Device Module: An error occurs in setting the video encoder. - */ - ERR_VCM_ENCODER_SET_ERROR = 1603, -}; - - /** Output log filter level. */ -enum LOG_FILTER_TYPE -{ -/** 0: Do not output any log information. */ - LOG_FILTER_OFF = 0, - /** 0x080f: Output all log information. - Set your log filter as debug if you want to get the most complete log file. */ - LOG_FILTER_DEBUG = 0x080f, - /** 0x000f: Output CRITICAL, ERROR, WARNING, and INFO level log information. - We recommend setting your log filter as this level. - */ - LOG_FILTER_INFO = 0x000f, - /** 0x000e: Outputs CRITICAL, ERROR, and WARNING level log information. - */ - LOG_FILTER_WARN = 0x000e, - /** 0x000c: Outputs CRITICAL and ERROR level log information. */ - LOG_FILTER_ERROR = 0x000c, - /** 0x0008: Outputs CRITICAL level log information. */ - LOG_FILTER_CRITICAL = 0x0008, - LOG_FILTER_MASK = 0x80f, -}; -} // namespace agora - -#endif diff --git a/android/src/main/cpp/include/IAgoraMediaEngine.h b/android/src/main/cpp/include/IAgoraMediaEngine.h deleted file mode 100644 index b86ab5c5d..000000000 --- a/android/src/main/cpp/include/IAgoraMediaEngine.h +++ /dev/null @@ -1,215 +0,0 @@ -#ifndef AGORA_MEDIA_ENGINE_H -#define AGORA_MEDIA_ENGINE_H -#if defined _WIN32 || defined __CYGWIN__ -typedef __int64 int64_t; -typedef unsigned __int64 uint64_t; -#else -#include -#endif - -namespace agora -{ -namespace media -{ - -enum MEDIA_SOURCE_TYPE { - AUDIO_PLAYOUT_SOURCE = 0, - AUDIO_RECORDING_SOURCE = 1, -}; - -class IAudioFrameObserver -{ -public: - enum AUDIO_FRAME_TYPE { - FRAME_TYPE_PCM16 = 0, //PCM 16bit little endian - }; - struct AudioFrame { - AUDIO_FRAME_TYPE type; - int samples; //number of samples in this frame - int bytesPerSample; //number of bytes per sample: 2 for PCM16 - int channels; //number of channels (data are interleaved if stereo) - int samplesPerSec; //sampling rate - void* buffer; //data buffer - int64_t renderTimeMs; - int avsync_type; - }; -public: - virtual bool onRecordAudioFrame(AudioFrame& audioFrame) = 0; - virtual bool onPlaybackAudioFrame(AudioFrame& audioFrame) = 0; - virtual bool onMixedAudioFrame(AudioFrame& audioFrame) = 0; - virtual bool onPlaybackAudioFrameBeforeMixing(unsigned int uid, AudioFrame& audioFrame) = 0; -}; - -class IVideoFrameObserver -{ -public: - enum VIDEO_FRAME_TYPE { - FRAME_TYPE_YUV420 = 0, //YUV 420 format - }; - struct VideoFrame { - VIDEO_FRAME_TYPE type; - int width; //width of video frame - int height; //height of video frame - int yStride; //stride of Y data buffer - int uStride; //stride of U data buffer - int vStride; //stride of V data buffer - void* yBuffer; //Y data buffer - void* uBuffer; //U data buffer - void* vBuffer; //V data buffer - int rotation; // rotation of this frame (0, 90, 180, 270) - int64_t renderTimeMs; - int avsync_type; - }; -public: - virtual bool onCaptureVideoFrame(VideoFrame& videoFrame) = 0; - virtual bool onRenderVideoFrame(unsigned int uid, VideoFrame& videoFrame) = 0; -}; - -class IVideoFrame -{ -public: - enum PLANE_TYPE { - Y_PLANE = 0, - U_PLANE = 1, - V_PLANE = 2, - NUM_OF_PLANES = 3 - }; - enum VIDEO_TYPE { - VIDEO_TYPE_UNKNOWN = 0, - VIDEO_TYPE_I420 = 1, - VIDEO_TYPE_IYUV = 2, - VIDEO_TYPE_RGB24 = 3, - VIDEO_TYPE_ABGR = 4, - VIDEO_TYPE_ARGB = 5, - VIDEO_TYPE_ARGB4444 = 6, - VIDEO_TYPE_RGB565 = 7, - VIDEO_TYPE_ARGB1555 = 8, - VIDEO_TYPE_YUY2 = 9, - VIDEO_TYPE_YV12 = 10, - VIDEO_TYPE_UYVY = 11, - VIDEO_TYPE_MJPG = 12, - VIDEO_TYPE_NV21 = 13, - VIDEO_TYPE_NV12 = 14, - VIDEO_TYPE_BGRA = 15, - VIDEO_TYPE_RGBA = 16, - }; - virtual void release() = 0; - virtual const unsigned char* buffer(PLANE_TYPE type) const = 0; - - // Copy frame: If required size is bigger than allocated one, new buffers of - // adequate size will be allocated. - // Return value: 0 on success ,-1 on error. - virtual int copyFrame(IVideoFrame** dest_frame) const = 0; - - // Convert frame - // Input: - // - src_frame : Reference to a source frame. - // - dst_video_type : Type of output video. - // - dst_sample_size : Required only for the parsing of MJPG. - // - dst_frame : Pointer to a destination frame. - // Return value: 0 if OK, < 0 otherwise. - // It is assumed that source and destination have equal height. - virtual int convertFrame(VIDEO_TYPE dst_video_type, int dst_sample_size, unsigned char* dst_frame) const = 0; - - // Get allocated size per plane. - virtual int allocated_size(PLANE_TYPE type) const = 0; - - // Get allocated stride per plane. - virtual int stride(PLANE_TYPE type) const = 0; - - // Get frame width. - virtual int width() const = 0; - - // Get frame height. - virtual int height() const = 0; - - // Get frame timestamp (90kHz). - virtual unsigned int timestamp() const = 0; - - // Get render time in milliseconds. - virtual int64_t render_time_ms() const = 0; - - // Return true if underlying plane buffers are of zero size, false if not. - virtual bool IsZeroSize() const = 0; -}; - -class IExternalVideoRenderCallback -{ -public: - virtual void onViewSizeChanged(int width, int height) = 0; - virtual void onViewDestroyed() = 0; -}; - -struct ExternalVideoRenerContext -{ - IExternalVideoRenderCallback* renderCallback; - void* view; - int renderMode; - int zOrder; - float left; - float top; - float right; - float bottom; -}; - -class IExternalVideoRender -{ -public: - virtual void release() = 0; - virtual int initialize() = 0; - virtual int deliverFrame(const IVideoFrame& videoFrame, int rotation, bool mirrored) = 0; -}; - -class IExternalVideoRenderFactory -{ -public: - virtual IExternalVideoRender* createRenderInstance(const ExternalVideoRenerContext& context) = 0; -}; - -struct ExternalVideoFrame -{ - enum VIDEO_BUFFER_TYPE - { - VIDEO_BUFFER_RAW_DATA = 1, - }; - - enum VIDEO_PIXEL_FORMAT - { - VIDEO_PIXEL_UNKNOWN = 0, - VIDEO_PIXEL_I420 = 1, - VIDEO_PIXEL_BGRA = 2, - VIDEO_PIXEL_NV12 = 8, - }; - - VIDEO_BUFFER_TYPE type; - VIDEO_PIXEL_FORMAT format; - void* buffer; - int stride; - int height; - int cropLeft; - int cropTop; - int cropRight; - int cropBottom; - int rotation; - long long timestamp; -}; - -class IMediaEngine { -public: - virtual void release() = 0; - virtual int registerAudioFrameObserver(IAudioFrameObserver* observer) = 0; - virtual int registerVideoFrameObserver(IVideoFrameObserver* observer) = 0; - virtual int registerVideoRenderFactory(IExternalVideoRenderFactory* factory) = 0; - virtual int pushAudioFrame(MEDIA_SOURCE_TYPE type, IAudioFrameObserver::AudioFrame *frame, bool wrap) = 0; - virtual int pushAudioFrame(IAudioFrameObserver::AudioFrame *frame) = 0; - virtual int pullAudioFrame(IAudioFrameObserver::AudioFrame *frame) = 0; - - virtual int setExternalVideoSource(bool enable, bool useTexture) = 0; - virtual int pushVideoFrame(ExternalVideoFrame *frame) = 0; -}; - -} //media - -} //agora - -#endif //AGORA_MEDIA_ENGINE_H diff --git a/android/src/main/cpp/include/IAgoraRtcEngine.h b/android/src/main/cpp/include/IAgoraRtcEngine.h deleted file mode 100755 index d0aeee818..000000000 --- a/android/src/main/cpp/include/IAgoraRtcEngine.h +++ /dev/null @@ -1,7473 +0,0 @@ -// -// AgoraRtcEngine SDK -// -// Copyright (c) 2019 Agora.io. All rights reserved. -// - -/** - @defgroup createAgoraRtcEngine Create an AgoraRtcEngine - */ - -#ifndef AGORA_RTC_ENGINE_H -#define AGORA_RTC_ENGINE_H -#include "AgoraBase.h" -#include "IAgoraService.h" - -namespace agora { -namespace rtc { - typedef unsigned int uid_t; - typedef void* view_t; -/** Maximum length of the device ID. -*/ -enum MAX_DEVICE_ID_LENGTH_TYEP -{ - /** The maximum length of the device ID is 512 bytes. - */ - MAX_DEVICE_ID_LENGTH = 512 -}; -/** Maximum length of user account. - */ -enum MAX_USER_ACCOUNT_LENGTH_TYPE -{ - /** The maximum length of user account is 255 bytes. - */ - MAX_USER_ACCOUNT_LENGTH = 256 -}; -/** Formats of the quality report. -*/ -enum QUALITY_REPORT_FORMAT_TYPE -{ - /** 0: The quality report in JSON format, - */ - QUALITY_REPORT_JSON = 0, - /** 1: The quality report in HTML format. - */ - QUALITY_REPORT_HTML = 1, -}; - -enum MEDIA_ENGINE_EVENT_CODE_TYPE -{ - /** 0: For internal use only. - */ - MEDIA_ENGINE_RECORDING_ERROR = 0, - /** 1: For internal use only. - */ - MEDIA_ENGINE_PLAYOUT_ERROR = 1, - /** 2: For internal use only. - */ - MEDIA_ENGINE_RECORDING_WARNING = 2, - /** 3: For internal use only. - */ - MEDIA_ENGINE_PLAYOUT_WARNING = 3, - /** 10: For internal use only. - */ - MEDIA_ENGINE_AUDIO_FILE_MIX_FINISH = 10, - /** 12: For internal use only. - */ - MEDIA_ENGINE_AUDIO_FAREND_MUSIC_BEGINS = 12, - /** 13: For internal use only. - */ - MEDIA_ENGINE_AUDIO_FAREND_MUSIC_ENDS = 13, - /** 14: For internal use only. - */ - MEDIA_ENGINE_LOCAL_AUDIO_RECORD_ENABLED = 14, - /** 15: For internal use only. - */ - MEDIA_ENGINE_LOCAL_AUDIO_RECORD_DISABLED = 15, - // media engine role changed - /** 20: For internal use only. - */ - MEDIA_ENGINE_ROLE_BROADCASTER_SOLO = 20, - /** 21: For internal use only. - */ - MEDIA_ENGINE_ROLE_BROADCASTER_INTERACTIVE = 21, - /** 22: For internal use only. - */ - MEDIA_ENGINE_ROLE_AUDIENCE = 22, - /** 23: For internal use only. - */ - MEDIA_ENGINE_ROLE_COMM_PEER = 23, - /** 24: For internal use only. - */ - MEDIA_ENGINE_ROLE_GAME_PEER = 24, - // iOS adm sample rate changed - /** 110: For internal use only. - */ - MEDIA_ENGINE_AUDIO_ADM_REQUIRE_RESTART = 110, - /** 111: For internal use only. - */ - MEDIA_ENGINE_AUDIO_ADM_SPECIAL_RESTART = 111, - /** 112: For internal use only. - */ - MEDIA_ENGINE_AUDIO_ADM_USING_COMM_PARAMS = 112, - /** 113: For internal use only. - */ - MEDIA_ENGINE_AUDIO_ADM_USING_NORM_PARAMS = 113, - // audio mix state - /** 710: For internal use only. - */ - MEDIA_ENGINE_AUDIO_EVENT_MIXING_PLAY = 710, - /** 711: For internal use only. - */ - MEDIA_ENGINE_AUDIO_EVENT_MIXING_PAUSED = 711, - /** 712: For internal use only. - */ - MEDIA_ENGINE_AUDIO_EVENT_MIXING_RESTART = 712, - /** 713: For internal use only. - */ - MEDIA_ENGINE_AUDIO_EVENT_MIXING_STOPPED = 713, - /** 714: For internal use only. - */ - MEDIA_ENGINE_AUDIO_EVENT_MIXING_ERROR = 714, - //Mixing error codes - /** 701: For internal use only. - */ - MEDIA_ENGINE_AUDIO_ERROR_MIXING_OPEN = 701, - /** 702: For internal use only. - */ - MEDIA_ENGINE_AUDIO_ERROR_MIXING_TOO_FREQUENT = 702, - /** 703: The audio mixing file playback is interrupted. For internal use only. - */ - MEDIA_ENGINE_AUDIO_ERROR_MIXING_INTERRUPTED_EOF = 703, - /** 0: For internal use only. - */ - MEDIA_ENGINE_AUDIO_ERROR_MIXING_NO_ERROR = 0, -}; - -/** The states of the local user's audio mixing file. -*/ -enum AUDIO_MIXING_STATE_TYPE{ - /** 710: The audio mixing file is playing. - */ - AUDIO_MIXING_STATE_PLAYING = 710, - /** 711: The audio mixing file pauses playing. - */ - AUDIO_MIXING_STATE_PAUSED = 711, - /** 713: The audio mixing file stops playing. - */ - AUDIO_MIXING_STATE_STOPPED = 713, - /** 714: An exception occurs when playing the audio mixing file. See #AUDIO_MIXING_ERROR_TYPE. - */ - AUDIO_MIXING_STATE_FAILED = 714, -}; - -/** The error codes of the local user's audio mixing file. -*/ -enum AUDIO_MIXING_ERROR_TYPE{ - /** 701: The SDK cannot open the audio mixing file. - */ - AUDIO_MIXING_ERROR_CAN_NOT_OPEN = 701, - /** 702: The SDK opens the audio mixing file too frequently. - */ - AUDIO_MIXING_ERROR_TOO_FREQUENT_CALL = 702, - /** 703: The audio mixing file playback is interrupted. - */ - AUDIO_MIXING_ERROR_INTERRUPTED_EOF = 703, - /** 0: The SDK can open the audio mixing file. - */ - AUDIO_MIXING_ERROR_OK = 0, -}; - -/** Media device states. - */ -enum MEDIA_DEVICE_STATE_TYPE -{ - /** 1: The device is active. - */ - MEDIA_DEVICE_STATE_ACTIVE = 1, - /** 2: The device is disabled. - */ - MEDIA_DEVICE_STATE_DISABLED = 2, - /** 4: The device is not present. - */ - MEDIA_DEVICE_STATE_NOT_PRESENT = 4, - /** 8: The device is unplugged. - */ - MEDIA_DEVICE_STATE_UNPLUGGED = 8 -}; - -/** Media device types. - */ -enum MEDIA_DEVICE_TYPE -{ - /** -1: Unknown device type. - */ - UNKNOWN_AUDIO_DEVICE = -1, - /** 0: Audio playback device. - */ - AUDIO_PLAYOUT_DEVICE = 0, - /** 1: Audio recording device. - */ - AUDIO_RECORDING_DEVICE = 1, - /** 2: Video renderer. - */ - VIDEO_RENDER_DEVICE = 2, - /** 3: Video capturer. - */ - VIDEO_CAPTURE_DEVICE = 3, - /** 4: Application audio playback device. - */ - AUDIO_APPLICATION_PLAYOUT_DEVICE = 4, -}; - -/** Local video state types - */ -enum LOCAL_VIDEO_STREAM_STATE -{ - /** Initial state */ - LOCAL_VIDEO_STREAM_STATE_STOPPED = 0, - /** The capturer starts successfully. */ - LOCAL_VIDEO_STREAM_STATE_CAPTURING = 1, - /** The first video frame is successfully encoded. */ - LOCAL_VIDEO_STREAM_STATE_ENCODING = 2, - /** The local video fails to start. */ - LOCAL_VIDEO_STREAM_STATE_FAILED = 3 -}; - -/** Local video state error codes - */ -enum LOCAL_VIDEO_STREAM_ERROR { - /** The local video is normal. */ - LOCAL_VIDEO_STREAM_ERROR_OK = 0, - /** No specified reason for the local video failure. */ - LOCAL_VIDEO_STREAM_ERROR_FAILURE = 1, - /** No permission to use the local video device. */ - LOCAL_VIDEO_STREAM_ERROR_DEVICE_NO_PERMISSION = 2, - /** The local video capturer is in use. */ - LOCAL_VIDEO_STREAM_ERROR_DEVICE_BUSY = 3, - /** The local video capture fails. Check whether the capturer is working properly. */ - LOCAL_VIDEO_STREAM_ERROR_CAPTURE_FAILURE = 4, - /** The local video encoding fails. */ - LOCAL_VIDEO_STREAM_ERROR_ENCODE_FAILURE = 5 -}; - -/** Local audio state types. - */ -enum LOCAL_AUDIO_STREAM_STATE -{ - /** 0: The local audio is in the initial state. - */ - LOCAL_AUDIO_STREAM_STATE_STOPPED = 0, - /** 1: The recording device starts successfully. - */ - LOCAL_AUDIO_STREAM_STATE_RECORDING = 1, - /** 2: The first audio frame encodes successfully. - */ - LOCAL_AUDIO_STREAM_STATE_ENCODING = 2, - /** 3: The local audio fails to start. - */ - LOCAL_AUDIO_STREAM_STATE_FAILED = 3 -}; - -/** Local audio state error codes. - */ -enum LOCAL_AUDIO_STREAM_ERROR -{ - /** 0: The local audio is normal. - */ - LOCAL_AUDIO_STREAM_ERROR_OK = 0, - /** 1: No specified reason for the local audio failure. - */ - LOCAL_AUDIO_STREAM_ERROR_FAILURE = 1, - /** 2: No permission to use the local audio device. - */ - LOCAL_AUDIO_STREAM_ERROR_DEVICE_NO_PERMISSION = 2, - /** 3: The microphone is in use. - */ - LOCAL_AUDIO_STREAM_ERROR_DEVICE_BUSY = 3, - /** 4: The local audio recording fails. Check whether the recording device - * is working properly. - */ - LOCAL_AUDIO_STREAM_ERROR_RECORD_FAILURE = 4, - /** 5: The local audio encoding fails. - */ - LOCAL_AUDIO_STREAM_ERROR_ENCODE_FAILURE = 5 -}; - -/** Audio recording qualities. -*/ -enum AUDIO_RECORDING_QUALITY_TYPE -{ - /** 0: Low quality. The sample rate is 32 kHz, and the file size is around - * 1.2 MB after 10 minutes of recording. - */ - AUDIO_RECORDING_QUALITY_LOW = 0, - /** 1: Medium quality. The sample rate is 32 kHz, and the file size is - * around 2 MB after 10 minutes of recording. - */ - AUDIO_RECORDING_QUALITY_MEDIUM = 1, - /** 2: High quality. The sample rate is 32 kHz, and the file size is - * around 3.75 MB after 10 minutes of recording. - */ - AUDIO_RECORDING_QUALITY_HIGH = 2, -}; - -/** Network quality types. */ -enum QUALITY_TYPE -{ - /** 0: The network quality is unknown. */ - QUALITY_UNKNOWN = 0, - /** 1: The network quality is excellent. */ - QUALITY_EXCELLENT = 1, - /** 2: The network quality is quite good, but the bitrate may be slightly lower than excellent. */ - QUALITY_GOOD = 2, - /** 3: Users can feel the communication slightly impaired. */ - QUALITY_POOR = 3, - /** 4: Users cannot communicate smoothly. */ - QUALITY_BAD = 4, - /** 5: The network is so bad that users can barely communicate. */ - QUALITY_VBAD = 5, - /** 6: The network is down and users cannot communicate at all. */ - QUALITY_DOWN = 6, - /** 7: Users cannot detect the network quality. (Not in use.) */ - QUALITY_UNSUPPORTED = 7, - /** 8: Detecting the network quality. */ - QUALITY_DETECTING = 8, -}; - -/** Video display modes. */ -enum RENDER_MODE_TYPE -{ - /** -1: Uniformly scale the video until it fills the visible boundaries (cropped). One dimension of the video may have clipped contents. - */ - RENDER_MODE_HIDDEN = 1, - /** -2: Uniformly scale the video until one of its dimension fits the boundary (zoomed to fit). Areas that are not filled due to disparity in the aspect ratio are filled with black. - */ - RENDER_MODE_FIT = 2, - /** **DEPRECATED** 3: This mode is deprecated. - */ - RENDER_MODE_ADAPTIVE = 3, -}; - -/** Video mirror modes. */ -enum VIDEO_MIRROR_MODE_TYPE -{ - /** 0: The default mirror mode is determined by the SDK. */ - VIDEO_MIRROR_MODE_AUTO = 0,//determined by SDK - /** 1: Enable mirror mode. */ - VIDEO_MIRROR_MODE_ENABLED = 1,//enabled mirror - /** 2: Disable mirror mode. */ - VIDEO_MIRROR_MODE_DISABLED = 2,//disable mirror -}; - -/** **DEPRECATED** Video profiles. */ -enum VIDEO_PROFILE_TYPE -{ - /** 0: 160 × 120, frame rate 15 fps, bitrate 65 Kbps. */ - VIDEO_PROFILE_LANDSCAPE_120P = 0, - /** 2: 120 × 120, frame rate 15 fps, bitrate 50 Kbps. */ - VIDEO_PROFILE_LANDSCAPE_120P_3 = 2, - /** 10: 320×180, frame rate 15 fps, bitrate 140 Kbps. */ - VIDEO_PROFILE_LANDSCAPE_180P = 10, - /** 12: 180 × 180, frame rate 15 fps, bitrate 100 Kbps. */ - VIDEO_PROFILE_LANDSCAPE_180P_3 = 12, - /** 13: 240 × 180, frame rate 15 fps, bitrate 120 Kbps. */ - VIDEO_PROFILE_LANDSCAPE_180P_4 = 13, - /** 20: 320 × 240, frame rate 15 fps, bitrate 200 Kbps. */ - VIDEO_PROFILE_LANDSCAPE_240P = 20, - /** 22: 240 × 240, frame rate 15 fps, bitrate 140 Kbps. */ - VIDEO_PROFILE_LANDSCAPE_240P_3 = 22, - /** 23: 424 × 240, frame rate 15 fps, bitrate 220 Kbps. */ - VIDEO_PROFILE_LANDSCAPE_240P_4 = 23, - /** 30: 640 × 360, frame rate 15 fps, bitrate 400 Kbps. */ - VIDEO_PROFILE_LANDSCAPE_360P = 30, - /** 32: 360 × 360, frame rate 15 fps, bitrate 260 Kbps. */ - VIDEO_PROFILE_LANDSCAPE_360P_3 = 32, - /** 33: 640 × 360, frame rate 30 fps, bitrate 600 Kbps. */ - VIDEO_PROFILE_LANDSCAPE_360P_4 = 33, - /** 35: 360 × 360, frame rate 30 fps, bitrate 400 Kbps. */ - VIDEO_PROFILE_LANDSCAPE_360P_6 = 35, - /** 36: 480 × 360, frame rate 15 fps, bitrate 320 Kbps. */ - VIDEO_PROFILE_LANDSCAPE_360P_7 = 36, - /** 37: 480 × 360, frame rate 30 fps, bitrate 490 Kbps. */ - VIDEO_PROFILE_LANDSCAPE_360P_8 = 37, - /** 38: 640 × 360, frame rate 15 fps, bitrate 800 Kbps. - @note Live broadcast profile only. - */ - VIDEO_PROFILE_LANDSCAPE_360P_9 = 38, - /** 39: 640 × 360, frame rate 24 fps, bitrate 800 Kbps. - @note Live broadcast profile only. - */ - VIDEO_PROFILE_LANDSCAPE_360P_10 = 39, - /** 100: 640 × 360, frame rate 24 fps, bitrate 1000 Kbps. - @note Live broadcast profile only. - */ - VIDEO_PROFILE_LANDSCAPE_360P_11 = 100, - /** 40: 640 × 480, frame rate 15 fps, bitrate 500 Kbps. */ - VIDEO_PROFILE_LANDSCAPE_480P = 40, - /** 42: 480 × 480, frame rate 15 fps, bitrate 400 Kbps. */ - VIDEO_PROFILE_LANDSCAPE_480P_3 = 42, - /** 43: 640 × 480, frame rate 30 fps, bitrate 750 Kbps. */ - VIDEO_PROFILE_LANDSCAPE_480P_4 = 43, - /** 45: 480 × 480, frame rate 30 fps, bitrate 600 Kbps. */ - VIDEO_PROFILE_LANDSCAPE_480P_6 = 45, - /** 47: 848 × 480, frame rate 15 fps, bitrate 610 Kbps. */ - VIDEO_PROFILE_LANDSCAPE_480P_8 = 47, - /** 48: 848 × 480, frame rate 30 fps, bitrate 930 Kbps. */ - VIDEO_PROFILE_LANDSCAPE_480P_9 = 48, - /** 49: 640 × 480, frame rate 10 fps, bitrate 400 Kbps. */ - VIDEO_PROFILE_LANDSCAPE_480P_10 = 49, - /** 50: 1280 × 720, frame rate 15 fps, bitrate 1130 Kbps. */ - VIDEO_PROFILE_LANDSCAPE_720P = 50, - /** 52: 1280 × 720, frame rate 30 fps, bitrate 1710 Kbps. */ - VIDEO_PROFILE_LANDSCAPE_720P_3 = 52, - /** 54: 960 × 720, frame rate 15 fps, bitrate 910 Kbps. */ - VIDEO_PROFILE_LANDSCAPE_720P_5 = 54, - /** 55: 960 × 720, frame rate 30 fps, bitrate 1380 Kbps. */ - VIDEO_PROFILE_LANDSCAPE_720P_6 = 55, - /** 60: 1920 × 1080, frame rate 15 fps, bitrate 2080 Kbps. */ - VIDEO_PROFILE_LANDSCAPE_1080P = 60, - /** 62: 1920 × 1080, frame rate 30 fps, bitrate 3150 Kbps. */ - VIDEO_PROFILE_LANDSCAPE_1080P_3 = 62, - /** 64: 1920 × 1080, frame rate 60 fps, bitrate 4780 Kbps. */ - VIDEO_PROFILE_LANDSCAPE_1080P_5 = 64, - /** 66: 2560 × 1440, frame rate 30 fps, bitrate 4850 Kbps. */ - VIDEO_PROFILE_LANDSCAPE_1440P = 66, - /** 67: 2560 × 1440, frame rate 60 fps, bitrate 6500 Kbps. */ - VIDEO_PROFILE_LANDSCAPE_1440P_2 = 67, - /** 70: 3840 × 2160, frame rate 30 fps, bitrate 6500 Kbps. */ - VIDEO_PROFILE_LANDSCAPE_4K = 70, - /** 72: 3840 × 2160, frame rate 60 fps, bitrate 6500 Kbps. */ - VIDEO_PROFILE_LANDSCAPE_4K_3 = 72, - /** 1000: 120 × 160, frame rate 15 fps, bitrate 65 Kbps. */ - VIDEO_PROFILE_PORTRAIT_120P = 1000, - /** 1002: 120 × 120, frame rate 15 fps, bitrate 50 Kbps. */ - VIDEO_PROFILE_PORTRAIT_120P_3 = 1002, - /** 1010: 180 × 320, frame rate 15 fps, bitrate 140 Kbps. */ - VIDEO_PROFILE_PORTRAIT_180P = 1010, - /** 1012: 180 × 180, frame rate 15 fps, bitrate 100 Kbps. */ - VIDEO_PROFILE_PORTRAIT_180P_3 = 1012, - /** 1013: 180 × 240, frame rate 15 fps, bitrate 120 Kbps. */ - VIDEO_PROFILE_PORTRAIT_180P_4 = 1013, - /** 1020: 240 × 320, frame rate 15 fps, bitrate 200 Kbps. */ - VIDEO_PROFILE_PORTRAIT_240P = 1020, - /** 1022: 240 × 240, frame rate 15 fps, bitrate 140 Kbps. */ - VIDEO_PROFILE_PORTRAIT_240P_3 = 1022, - /** 1023: 240 × 424, frame rate 15 fps, bitrate 220 Kbps. */ - VIDEO_PROFILE_PORTRAIT_240P_4 = 1023, - /** 1030: 360 × 640, frame rate 15 fps, bitrate 400 Kbps. */ - VIDEO_PROFILE_PORTRAIT_360P = 1030, - /** 1032: 360 × 360, frame rate 15 fps, bitrate 260 Kbps. */ - VIDEO_PROFILE_PORTRAIT_360P_3 = 1032, - /** 1033: 360 × 640, frame rate 30 fps, bitrate 600 Kbps. */ - VIDEO_PROFILE_PORTRAIT_360P_4 = 1033, - /** 1035: 360 × 360, frame rate 30 fps, bitrate 400 Kbps. */ - VIDEO_PROFILE_PORTRAIT_360P_6 = 1035, - /** 1036: 360 × 480, frame rate 15 fps, bitrate 320 Kbps. */ - VIDEO_PROFILE_PORTRAIT_360P_7 = 1036, - /** 1037: 360 × 480, frame rate 30 fps, bitrate 490 Kbps. */ - VIDEO_PROFILE_PORTRAIT_360P_8 = 1037, - /** 1038: 360 × 640, frame rate 15 fps, bitrate 800 Kbps. - @note Live broadcast profile only. - */ - VIDEO_PROFILE_PORTRAIT_360P_9 = 1038, - /** 1039: 360 × 640, frame rate 24 fps, bitrate 800 Kbps. - @note Live broadcast profile only. - */ - VIDEO_PROFILE_PORTRAIT_360P_10 = 1039, - /** 1100: 360 × 640, frame rate 24 fps, bitrate 1000 Kbps. - @note Live broadcast profile only. - */ - VIDEO_PROFILE_PORTRAIT_360P_11 = 1100, - /** 1040: 480 × 640, frame rate 15 fps, bitrate 500 Kbps. */ - VIDEO_PROFILE_PORTRAIT_480P = 1040, - /** 1042: 480 × 480, frame rate 15 fps, bitrate 400 Kbps. */ - VIDEO_PROFILE_PORTRAIT_480P_3 = 1042, - /** 1043: 480 × 640, frame rate 30 fps, bitrate 750 Kbps. */ - VIDEO_PROFILE_PORTRAIT_480P_4 = 1043, - /** 1045: 480 × 480, frame rate 30 fps, bitrate 600 Kbps. */ - VIDEO_PROFILE_PORTRAIT_480P_6 = 1045, - /** 1047: 480 × 848, frame rate 15 fps, bitrate 610 Kbps. */ - VIDEO_PROFILE_PORTRAIT_480P_8 = 1047, - /** 1048: 480 × 848, frame rate 30 fps, bitrate 930 Kbps. */ - VIDEO_PROFILE_PORTRAIT_480P_9 = 1048, - /** 1049: 480 × 640, frame rate 10 fps, bitrate 400 Kbps. */ - VIDEO_PROFILE_PORTRAIT_480P_10 = 1049, - /** 1050: 720 × 1280, frame rate 15 fps, bitrate 1130 Kbps. */ - VIDEO_PROFILE_PORTRAIT_720P = 1050, - /** 1052: 720 × 1280, frame rate 30 fps, bitrate 1710 Kbps. */ - VIDEO_PROFILE_PORTRAIT_720P_3 = 1052, - /** 1054: 720 × 960, frame rate 15 fps, bitrate 910 Kbps. */ - VIDEO_PROFILE_PORTRAIT_720P_5 = 1054, - /** 1055: 720 × 960, frame rate 30 fps, bitrate 1380 Kbps. */ - VIDEO_PROFILE_PORTRAIT_720P_6 = 1055, - /** 1060: 1080 × 1920, frame rate 15 fps, bitrate 2080 Kbps. */ - VIDEO_PROFILE_PORTRAIT_1080P = 1060, - /** 1062: 1080 × 1920, frame rate 30 fps, bitrate 3150 Kbps. */ - VIDEO_PROFILE_PORTRAIT_1080P_3 = 1062, - /** 1064: 1080 × 1920, frame rate 60 fps, bitrate 4780 Kbps. */ - VIDEO_PROFILE_PORTRAIT_1080P_5 = 1064, - /** 1066: 1440 × 2560, frame rate 30 fps, bitrate 4850 Kbps. */ - VIDEO_PROFILE_PORTRAIT_1440P = 1066, - /** 1067: 1440 × 2560, frame rate 60 fps, bitrate 6500 Kbps. */ - VIDEO_PROFILE_PORTRAIT_1440P_2 = 1067, - /** 1070: 2160 × 3840, frame rate 30 fps, bitrate 6500 Kbps. */ - VIDEO_PROFILE_PORTRAIT_4K = 1070, - /** 1072: 2160 × 3840, frame rate 60 fps, bitrate 6500 Kbps. */ - VIDEO_PROFILE_PORTRAIT_4K_3 = 1072, - /** Default 640 × 360, frame rate 15 fps, bitrate 400 Kbps. */ - VIDEO_PROFILE_DEFAULT = VIDEO_PROFILE_LANDSCAPE_360P, -}; - -/** Audio profiles. - -Sets the sample rate, bitrate, encoding mode, and the number of channels:*/ -enum AUDIO_PROFILE_TYPE // sample rate, bit rate, mono/stereo, speech/music codec -{ - /** - 0: Default audio profile. - - - In the Communication profile, the default value is #AUDIO_PROFILE_SPEECH_STANDARD; - - In the Live-broadcast profile, the default value is #AUDIO_PROFILE_MUSIC_STANDARD. - */ - AUDIO_PROFILE_DEFAULT = 0, // use default settings - /** - 1: A sample rate of 32 kHz, audio encoding, mono, and a bitrate of up to 18 Kbps. - */ - AUDIO_PROFILE_SPEECH_STANDARD = 1, // 32Khz, 18Kbps, mono, speech - /** - 2: A sample rate of 48 kHz, music encoding, mono, and a bitrate of up to 48 Kbps. - */ - AUDIO_PROFILE_MUSIC_STANDARD = 2, // 48Khz, 48Kbps, mono, music - /** - 3: A sample rate of 48 kHz, music encoding, stereo, and a bitrate of up to 56 Kbps. - */ - AUDIO_PROFILE_MUSIC_STANDARD_STEREO = 3, // 48Khz, 56Kbps, stereo, music - /** - 4: A sample rate of 48 kHz, music encoding, mono, and a bitrate of up to 128 Kbps. - */ - AUDIO_PROFILE_MUSIC_HIGH_QUALITY = 4, // 48Khz, 128Kbps, mono, music - /** - 5: A sample rate of 48 kHz, music encoding, stereo, and a bitrate of up to 192 Kbps. - */ - AUDIO_PROFILE_MUSIC_HIGH_QUALITY_STEREO = 5, // 48Khz, 192Kbps, stereo, music - /** - 6: A sample rate of 16 kHz, audio encoding, mono, and Acoustic Echo Cancellation (AES) enabled. - */ - AUDIO_PROFILE_IOT = 6, - AUDIO_PROFILE_NUM = 7, -}; - -/** Audio application scenarios. -*/ -enum AUDIO_SCENARIO_TYPE // set a suitable scenario for your app type -{ - /** 0: Default. */ - AUDIO_SCENARIO_DEFAULT = 0, - /** 1: Entertainment scenario, supporting voice during gameplay. */ - AUDIO_SCENARIO_CHATROOM_ENTERTAINMENT = 1, - /** 2: Education scenario, prioritizing smoothness and stability. */ - AUDIO_SCENARIO_EDUCATION = 2, - /** 3: Live gaming scenario, enabling the gaming audio effects in the speaker mode in a live broadcast scenario. Choose this scenario for high-fidelity music playback. */ - AUDIO_SCENARIO_GAME_STREAMING = 3, - /** 4: Showroom scenario, optimizing the audio quality with external professional equipment. */ - AUDIO_SCENARIO_SHOWROOM = 4, - /** 5: Gaming scenario. */ - AUDIO_SCENARIO_CHATROOM_GAMING = 5, - /** 6: Applicable to the IoT scenario. */ - AUDIO_SCENARIO_IOT = 6, - AUDIO_SCENARIO_NUM = 7, -}; - - /** Channel profiles. - */ -enum CHANNEL_PROFILE_TYPE -{ - /** 0: Communication. - - This is used in one-on-one calls or group calls, where all users in the channel can talk freely. - */ - CHANNEL_PROFILE_COMMUNICATION = 0, - /** 1: Live Broadcast. - - Host and audience roles that can be set by calling the \ref IRtcEngine::setClientRole "setClientRole" method. The host sends and receives voice, while the audience receives voice only with the sending function disabled. - */ - CHANNEL_PROFILE_LIVE_BROADCASTING = 1, - /** 2: Gaming. - - @note This profile applies to the Agora Gaming SDK only. - - Any user in the channel can talk freely. This mode uses the codec with low-power consumption and low bitrate by default. - */ - CHANNEL_PROFILE_GAME = 2, -}; - -/** Client roles in a live broadcast. */ -enum CLIENT_ROLE_TYPE -{ - /** 1: Host */ - CLIENT_ROLE_BROADCASTER = 1, - /** 2: Audience */ - CLIENT_ROLE_AUDIENCE = 2, -}; - -/** Reasons for a user being offline. */ -enum USER_OFFLINE_REASON_TYPE -{ - /** 0: The user quits the call. */ - USER_OFFLINE_QUIT = 0, - /** 1: The SDK times out and the user drops offline because no data packet is received within a certain period of time. If the user quits the call and the message is not passed to the SDK (due to an unreliable channel), the SDK assumes the user dropped offline. */ - USER_OFFLINE_DROPPED = 1, - /** 2: (Live broadcast only.) The client role switched from the host to the audience. */ - USER_OFFLINE_BECOME_AUDIENCE = 2, -}; -/** - States of the RTMP streaming. - */ -enum RTMP_STREAM_PUBLISH_STATE -{ - /** The RTMP streaming has not started or has ended. This state is also triggered after you remove an RTMP address from the CDN by calling removePublishStreamUrl. - */ - RTMP_STREAM_PUBLISH_STATE_IDLE = 0, - /** The SDK is connecting to Agora's streaming server and the RTMP server. This state is triggered after you call the \ref IRtcEngine::addPublishStreamUrl "addPublishStreamUrl" method. - */ - RTMP_STREAM_PUBLISH_STATE_CONNECTING = 1, - /** The RTMP streaming publishes. The SDK successfully publishes the RTMP streaming and returns this state. - */ - RTMP_STREAM_PUBLISH_STATE_RUNNING = 2, - /** The RTMP streaming is recovering. When exceptions occur to the CDN, or the streaming is interrupted, the SDK tries to resume RTMP streaming and returns this state. - - - If the SDK successfully resumes the streaming, #RTMP_STREAM_PUBLISH_STATE_RUNNING (2) returns. - - If the streaming does not resume within 60 seconds or server errors occur, #RTMP_STREAM_PUBLISH_STATE_FAILURE (4) returns. You can also reconnect to the server by calling the \ref IRtcEngine::removePublishStreamUrl "removePublishStreamUrl" and \ref IRtcEngine::addPublishStreamUrl "addPublishStreamUrl" methods. - */ - RTMP_STREAM_PUBLISH_STATE_RECOVERING = 3, - /** The RTMP streaming fails. See the errCode parameter for the detailed error information. You can also call the \ref IRtcEngine::addPublishStreamUrl "addPublishStreamUrl" method to publish the RTMP streaming again. - */ - RTMP_STREAM_PUBLISH_STATE_FAILURE = 4, -}; - -/** - Error codes of the RTMP streaming. - */ -enum RTMP_STREAM_PUBLISH_ERROR -{ - /** The RTMP streaming publishes successfully. */ - RTMP_STREAM_PUBLISH_ERROR_OK = 0, - /** Invalid argument used. If, for example, you do not call the \ref IRtcEngine::setLiveTranscoding "setLiveTranscoding" method to configure the LiveTranscoding parameters before calling the addPublishStreamUrl method, the SDK returns this error. Check whether you set the parameters in the *setLiveTranscoding* method properly. */ - RTMP_STREAM_PUBLISH_ERROR_INVALID_ARGUMENT = 1, - /** The RTMP streaming is encrypted and cannot be published. */ - RTMP_STREAM_PUBLISH_ERROR_ENCRYPTED_STREAM_NOT_ALLOWED = 2, - /** Timeout for the RTMP streaming. Call the \ref IRtcEngine::addPublishStreamUrl "addPublishStreamUrl" method to publish the streaming again. */ - RTMP_STREAM_PUBLISH_ERROR_CONNECTION_TIMEOUT = 3, - /** An error occurs in Agora's streaming server. Call the addPublishStreamUrl method to publish the streaming again. */ - RTMP_STREAM_PUBLISH_ERROR_INTERNAL_SERVER_ERROR = 4, - /** An error occurs in the RTMP server. */ - RTMP_STREAM_PUBLISH_ERROR_RTMP_SERVER_ERROR = 5, - /** The RTMP streaming publishes too frequently. */ - RTMP_STREAM_PUBLISH_ERROR_TOO_OFTEN = 6, - /** The host publishes more than 10 URLs. Delete the unnecessary URLs before adding new ones. */ - RTMP_STREAM_PUBLISH_ERROR_REACH_LIMIT = 7, - /** The host manipulates other hosts' URLs. Check your app logic. */ - RTMP_STREAM_PUBLISH_ERROR_NOT_AUTHORIZED = 8, - /** Agora's server fails to find the RTMP streaming. */ - RTMP_STREAM_PUBLISH_ERROR_STREAM_NOT_FOUND = 9, - /** The format of the RTMP streaming URL is not supported. Check whether the URL format is correct. */ - RTMP_STREAM_PUBLISH_ERROR_FORMAT_NOT_SUPPORTED = 10, -}; - -/** States of importing an external video stream in a live broadcast. */ -enum INJECT_STREAM_STATUS -{ - /** 0: The external video stream imported successfully. */ - INJECT_STREAM_STATUS_START_SUCCESS = 0, - /** 1: The external video stream already exists. */ - INJECT_STREAM_STATUS_START_ALREADY_EXISTS = 1, - /** 2: The external video stream to be imported is unauthorized. */ - INJECT_STREAM_STATUS_START_UNAUTHORIZED = 2, - /** 3: Import external video stream timeout. */ - INJECT_STREAM_STATUS_START_TIMEDOUT = 3, - /** 4: Import external video stream failed. */ - INJECT_STREAM_STATUS_START_FAILED = 4, - /** 5: The external video stream stopped importing successfully. */ - INJECT_STREAM_STATUS_STOP_SUCCESS = 5, - /** 6: No external video stream is found. */ - INJECT_STREAM_STATUS_STOP_NOT_FOUND = 6, - /** 7: The external video stream to be stopped importing is unauthorized. */ - INJECT_STREAM_STATUS_STOP_UNAUTHORIZED = 7, - /** 8: Stop importing external video stream timeout. */ - INJECT_STREAM_STATUS_STOP_TIMEDOUT = 8, - /** 9: Stop importing external video stream failed. */ - INJECT_STREAM_STATUS_STOP_FAILED = 9, - /** 10: The external video stream is corrupted. */ - INJECT_STREAM_STATUS_BROKEN = 10, -}; -/** Remote video stream types. */ -enum REMOTE_VIDEO_STREAM_TYPE -{ - /** 0: High-stream video. */ - REMOTE_VIDEO_STREAM_HIGH = 0, - /** 1: Low-stream video. */ - REMOTE_VIDEO_STREAM_LOW = 1, -}; - -/** Use modes of the \ref media::IAudioFrameObserver::onRecordAudioFrame "onRecordAudioFrame" callback. */ -enum RAW_AUDIO_FRAME_OP_MODE_TYPE -{ - /** 0: Read-only mode: Users only read the \ref agora::media::IAudioFrameObserver::AudioFrame "AudioFrame" data without modifying anything. For example, when users acquire the data with the Agora SDK, then push the RTMP streams. */ - RAW_AUDIO_FRAME_OP_MODE_READ_ONLY = 0, - /** 1: Write-only mode: Users replace the \ref agora::media::IAudioFrameObserver::AudioFrame "AudioFrame" data with their own data and pass the data to the SDK for encoding. For example, when users acquire the data. */ - RAW_AUDIO_FRAME_OP_MODE_WRITE_ONLY = 1, - /** 2: Read and write mode: Users read the data from \ref agora::media::IAudioFrameObserver::AudioFrame "AudioFrame", modify it, and then play it. For example, when users have their own sound-effect processing module and perform some voice pre-processing, such as a voice change. */ - RAW_AUDIO_FRAME_OP_MODE_READ_WRITE = 2, -}; - -/** Audio-sample rates. */ -enum AUDIO_SAMPLE_RATE_TYPE -{ - /** 32000: 32 kHz */ - AUDIO_SAMPLE_RATE_32000 = 32000, - /** 44100: 44.1 kHz */ - AUDIO_SAMPLE_RATE_44100 = 44100, - /** 48000: 48 kHz */ - AUDIO_SAMPLE_RATE_48000 = 48000, -}; - -/** Video codec profile types. */ -enum VIDEO_CODEC_PROFILE_TYPE -{ /** 66: Baseline video codec profile. Generally used in video calls on mobile phones. */ - VIDEO_CODEC_PROFILE_BASELINE = 66, - /** 77: Main video codec profile. Generally used in mainstream electronics such as MP4 players, portable video players, PSP, and iPads. */ - VIDEO_CODEC_PROFILE_MAIN = 77, - /** 100: (Default) High video codec profile. Generally used in high-resolution broadcasts or television. */ - VIDEO_CODEC_PROFILE_HIGH = 100, -}; - -/** Video codec types */ -enum VIDEO_CODEC_TYPE { - /** Standard VP8 */ - VIDEO_CODEC_VP8 = 1, - /** Standard H264 */ - VIDEO_CODEC_H264 = 2, - /** Enhanced VP8 */ - VIDEO_CODEC_EVP = 3, - /** Enhanced H264 */ - VIDEO_CODEC_E264 = 4, -}; - -/** Audio equalization band frequencies. */ -enum AUDIO_EQUALIZATION_BAND_FREQUENCY -{ - /** 0: 31 Hz */ - AUDIO_EQUALIZATION_BAND_31 = 0, - /** 1: 62 Hz */ - AUDIO_EQUALIZATION_BAND_62 = 1, - /** 2: 125 Hz */ - AUDIO_EQUALIZATION_BAND_125 = 2, - /** 3: 250 Hz */ - AUDIO_EQUALIZATION_BAND_250 = 3, - /** 4: 500 Hz */ - AUDIO_EQUALIZATION_BAND_500 = 4, - /** 5: 1 kHz */ - AUDIO_EQUALIZATION_BAND_1K = 5, - /** 6: 2 kHz */ - AUDIO_EQUALIZATION_BAND_2K = 6, - /** 7: 4 kHz */ - AUDIO_EQUALIZATION_BAND_4K = 7, - /** 8: 8 kHz */ - AUDIO_EQUALIZATION_BAND_8K = 8, - /** 9: 16 kHz */ - AUDIO_EQUALIZATION_BAND_16K = 9, -}; - -/** Audio reverberation types. */ -enum AUDIO_REVERB_TYPE -{ - /** 0: The level of the dry signal (db). The value is between -20 and 10. */ - AUDIO_REVERB_DRY_LEVEL = 0, // (dB, [-20,10]), the level of the dry signal - /** 1: The level of the early reflection signal (wet signal) (dB). The value is between -20 and 10. */ - AUDIO_REVERB_WET_LEVEL = 1, // (dB, [-20,10]), the level of the early reflection signal (wet signal) - /** 2: The room size of the reflection. The value is between 0 and 100. */ - AUDIO_REVERB_ROOM_SIZE = 2, // ([0,100]), the room size of the reflection - /** 3: The length of the initial delay of the wet signal (ms). The value is between 0 and 200. */ - AUDIO_REVERB_WET_DELAY = 3, // (ms, [0,200]), the length of the initial delay of the wet signal in ms - /** 4: The reverberation strength. The value is between 0 and 100. */ - AUDIO_REVERB_STRENGTH = 4, // ([0,100]), the strength of the reverberation -}; - -/** Local voice changer options. */ -enum VOICE_CHANGER_PRESET { - /** 0: The original voice (no local voice change). - */ - VOICE_CHANGER_OFF = 0, //Turn off the voice changer - /** 1: An old man's voice. - */ - VOICE_CHANGER_OLDMAN = 1, - /** 2: A little boy's voice. - */ - VOICE_CHANGER_BABYBOY = 2, - /** 3: A little girl's voice. - */ - VOICE_CHANGER_BABYGIRL = 3, - /** 4: The voice of a growling bear. - */ - VOICE_CHANGER_ZHUBAJIE = 4, - /** 5: Ethereal vocal effects. - */ - VOICE_CHANGER_ETHEREAL = 5, - /** 6: Hulk's voice. - */ - VOICE_CHANGER_HULK = 6 -}; - -/** Local voice reverberation presets. */ -enum AUDIO_REVERB_PRESET { - /** 0: The original voice (no local voice reverberation). - */ - AUDIO_REVERB_OFF = 0, // Turn off audio reverb - /** 1: Pop music. - */ - AUDIO_REVERB_POPULAR = 1, - /** 2: R&B. - */ - AUDIO_REVERB_RNB = 2, - /** 3: Rock music. - */ - AUDIO_REVERB_ROCK = 3, - /** 4: Hip-hop. - */ - AUDIO_REVERB_HIPHOP = 4, - /** 5: Pop concert. - */ - AUDIO_REVERB_VOCAL_CONCERT = 5, - /** 6: Karaoke. - */ - AUDIO_REVERB_KTV = 6, - /** 7: Recording studio. - */ - AUDIO_REVERB_STUDIO = 7 -}; -/** Audio codec profile types. The default value is LC_ACC. */ -enum AUDIO_CODEC_PROFILE_TYPE -{ - /** 0: LC-AAC, which is the low-complexity audio codec type. */ - AUDIO_CODEC_PROFILE_LC_AAC = 0, - /** 1: HE-AAC, which is the high-efficiency audio codec type. */ - AUDIO_CODEC_PROFILE_HE_AAC = 1, -}; - -/** Remote audio states. - */ -enum REMOTE_AUDIO_STATE -{ - /** 0: The remote audio is in the default state, probably due to - * #REMOTE_AUDIO_REASON_LOCAL_MUTED (3), - * #REMOTE_AUDIO_REASON_REMOTE_MUTED (5), or - * #REMOTE_AUDIO_REASON_REMOTE_OFFLINE (7). - */ - REMOTE_AUDIO_STATE_STOPPED = 0, // Default state, audio is started or remote user disabled/muted audio stream - /** 1: The first remote audio packet is received. - */ - REMOTE_AUDIO_STATE_STARTING = 1, // The first audio frame packet has been received - /** 2: The remote audio stream is decoded and plays normally, probably - * due to #REMOTE_AUDIO_REASON_NETWORK_RECOVERY (2), - * #REMOTE_AUDIO_REASON_LOCAL_UNMUTED (4), or - * #REMOTE_AUDIO_REASON_REMOTE_UNMUTED (6). - */ - REMOTE_AUDIO_STATE_DECODING = 2, // The first remote audio frame has been decoded or fronzen state ends - /** 3: The remote audio is frozen, probably due to - * #REMOTE_AUDIO_REASON_NETWORK_CONGESTION (1). - */ - REMOTE_AUDIO_STATE_FROZEN = 3, // Remote audio is frozen, probably due to network issue - /** 4: The remote audio fails to start, probably due to - * #REMOTE_AUDIO_REASON_INTERNAL (0). - */ - REMOTE_AUDIO_STATE_FAILED = 4, // Remote audio play failed -}; - -/** Remote audio state reasons. - */ -enum REMOTE_AUDIO_STATE_REASON -{ - /** 0: Internal reasons. - */ - REMOTE_AUDIO_REASON_INTERNAL = 0, - /** 1: Network congestion. - */ - REMOTE_AUDIO_REASON_NETWORK_CONGESTION = 1, - /** 2: Network recovery. - */ - REMOTE_AUDIO_REASON_NETWORK_RECOVERY = 2, - /** 3: The local user stops receiving the remote audio stream or - * disables the audio module. - */ - REMOTE_AUDIO_REASON_LOCAL_MUTED = 3, - /** 4: The local user resumes receiving the remote audio stream or - * enables the audio module. - */ - REMOTE_AUDIO_REASON_LOCAL_UNMUTED = 4, - /** 5: The remote user stops sending the audio stream or disables the - * audio module. - */ - REMOTE_AUDIO_REASON_REMOTE_MUTED = 5, - /** 6: The remote user resumes sending the audio stream or enables the - * audio module. - */ - REMOTE_AUDIO_REASON_REMOTE_UNMUTED = 6, - /** 7: The remote user leaves the channel. - */ - REMOTE_AUDIO_REASON_REMOTE_OFFLINE = 7, -}; - -/** Remote video states. */ -// enum REMOTE_VIDEO_STATE -// { -// // REMOTE_VIDEO_STATE_STOPPED is not used at this version. Ignore this value. -// // REMOTE_VIDEO_STATE_STOPPED = 0, // Default state, video is started or remote user disabled/muted video stream -// /** 1: The remote video is playing. */ -// REMOTE_VIDEO_STATE_RUNNING = 1, // Running state, remote video can be displayed normally -// /** 2: The remote video is frozen. */ -// REMOTE_VIDEO_STATE_FROZEN = 2, // Remote video is frozen, probably due to network issue. -// }; - -/** The state of the remote video. */ -enum REMOTE_VIDEO_STATE { - /** 0: The remote video is in the default state, probably due to #REMOTE_VIDEO_STATE_REASON_LOCAL_MUTED (3), #REMOTE_VIDEO_STATE_REASON_REMOTE_MUTED (5), or #REMOTE_VIDEO_STATE_REASON_REMOTE_OFFLINE (7). - */ - REMOTE_VIDEO_STATE_STOPPED = 0, - - /** 1: The first remote video packet is received. - */ - REMOTE_VIDEO_STATE_STARTING = 1, - - /** 2: The remote video stream is decoded and plays normally, probably due to #REMOTE_VIDEO_STATE_REASON_NETWORK_RECOVERY (2), #REMOTE_VIDEO_STATE_REASON_LOCAL_UNMUTED (4), #REMOTE_VIDEO_STATE_REASON_REMOTE_UNMUTED (6), or #REMOTE_VIDEO_STATE_REASON_AUDIO_FALLBACK_RECOVERY (9). - */ - REMOTE_VIDEO_STATE_DECODING = 2, - - /** 3: The remote video is frozen, probably due to #REMOTE_VIDEO_STATE_REASON_NETWORK_CONGESTION (1) or #REMOTE_VIDEO_STATE_REASON_AUDIO_FALLBACK (8). - */ - REMOTE_VIDEO_STATE_FROZEN = 3, - - /** 4: The remote video fails to start, probably due to #REMOTE_VIDEO_STATE_REASON_INTERNAL (0). - */ - REMOTE_VIDEO_STATE_FAILED = 4 -}; - -/** The reason of the remote video state change. */ -enum REMOTE_VIDEO_STATE_REASON { - /** 0: Internal reasons. - */ - REMOTE_VIDEO_STATE_REASON_INTERNAL = 0, - - /** 1: Network congestion. - */ - REMOTE_VIDEO_STATE_REASON_NETWORK_CONGESTION = 1, - - /** 2: Network recovery. - */ - REMOTE_VIDEO_STATE_REASON_NETWORK_RECOVERY = 2, - - /** 3: The local user stops receiving the remote video stream or disables the video module. - */ - REMOTE_VIDEO_STATE_REASON_LOCAL_MUTED = 3, - - /** 4: The local user resumes receiving the remote video stream or enables the video module. - */ - REMOTE_VIDEO_STATE_REASON_LOCAL_UNMUTED = 4, - - /** 5: The remote user stops sending the video stream or disables the video module. - */ - REMOTE_VIDEO_STATE_REASON_REMOTE_MUTED = 5, - - /** 6: The remote user resumes sending the video stream or enables the video module. - */ - REMOTE_VIDEO_STATE_REASON_REMOTE_UNMUTED = 6, - - /** 7: The remote user leaves the channel. - */ - REMOTE_VIDEO_STATE_REASON_REMOTE_OFFLINE = 7, - - /** 8: The remote media stream falls back to the audio-only stream due to poor network conditions. - */ - REMOTE_VIDEO_STATE_REASON_AUDIO_FALLBACK = 8, - - /** 9: The remote media stream switches back to the video stream after the network conditions improve. - */ - REMOTE_VIDEO_STATE_REASON_AUDIO_FALLBACK_RECOVERY = 9 - -}; - -/** Video frame rates. */ -enum FRAME_RATE -{ - /** 1: 1 fps */ - FRAME_RATE_FPS_1 = 1, - /** 7: 7 fps */ - FRAME_RATE_FPS_7 = 7, - /** 10: 10 fps */ - FRAME_RATE_FPS_10 = 10, - /** 15: 15 fps */ - FRAME_RATE_FPS_15 = 15, - /** 24: 24 fps */ - FRAME_RATE_FPS_24 = 24, - /** 30: 30 fps */ - FRAME_RATE_FPS_30 = 30, - /** 60: 60 fps (Windows and macOS only) */ - FRAME_RATE_FPS_60 = 60, -}; - -/** Video output orientation modes. - */ -enum ORIENTATION_MODE { - /** 0: (Default) Adaptive mode. - - The video encoder adapts to the orientation mode of the video input device. - - - If the width of the captured video from the SDK is greater than the height, the encoder sends the video in landscape mode. The encoder also sends the rotational information of the video, and the receiver uses the rotational information to rotate the received video. - - When you use a custom video source, the output video from the encoder inherits the orientation of the original video. If the original video is in portrait mode, the output video from the encoder is also in portrait mode. The encoder also sends the rotational information of the video to the receiver. - */ - ORIENTATION_MODE_ADAPTIVE = 0, - /** 1: Landscape mode. - - The video encoder always sends the video in landscape mode. The video encoder rotates the original video before sending it and the rotational infomation is 0. This mode applies to scenarios involving CDN live streaming. - */ - ORIENTATION_MODE_FIXED_LANDSCAPE = 1, - /** 2: Portrait mode. - - The video encoder always sends the video in portrait mode. The video encoder rotates the original video before sending it and the rotational infomation is 0. This mode applies to scenarios involving CDN live streaming. - */ - ORIENTATION_MODE_FIXED_PORTRAIT = 2, -}; - -/** Video degradation preferences when the bandwidth is a constraint. */ -enum DEGRADATION_PREFERENCE { - /** 0: (Default) Degrade the frame rate in order to maintain the video quality. */ - MAINTAIN_QUALITY = 0, - /** 1: Degrade the video quality in order to maintain the frame rate. */ - MAINTAIN_FRAMERATE = 1, - /** 2: (For future use) Maintain a balance between the frame rate and video quality. */ - MAINTAIN_BALANCED = 2, -}; - -/** Stream fallback options. */ -enum STREAM_FALLBACK_OPTIONS -{ - /** 0: No fallback behavior for the local/remote video stream when the uplink/downlink network conditions are poor. The quality of the stream is not guaranteed. */ - STREAM_FALLBACK_OPTION_DISABLED = 0, - /** 1: Under poor downlink network conditions, the remote video stream, to which you subscribe, falls back to the low-stream (low resolution and low bitrate) video. You can set this option only in the \ref IRtcEngine::setRemoteSubscribeFallbackOption "setRemoteSubscribeFallbackOption" method. Nothing happens when you set this in the \ref IRtcEngine::setLocalPublishFallbackOption "setLocalPublishFallbackOption" method. */ - STREAM_FALLBACK_OPTION_VIDEO_STREAM_LOW = 1, - /** 2: Under poor uplink network conditions, the locally published video stream falls back to audio only. - - Under poor downlink network conditions, the remote video stream, to which you subscribe, first falls back to the low-stream (low resolution and low bitrate) video; and then to an audio-only stream if the network conditions worsen.*/ - STREAM_FALLBACK_OPTION_AUDIO_ONLY = 2, -}; - - /** Camera capturer configuration. - */ - enum CAPTURER_OUTPUT_PREFERENCE - { - /** 0: (Default) self-adapts the camera output parameters to the system performance and network conditions to balance CPU consumption and video preview quality. - */ - CAPTURER_OUTPUT_PREFERENCE_AUTO = 0, - /** 2: Prioritizes the system performance. The SDK chooses the dimension and frame rate of the local camera capture closest to those set by \ref IRtcEngine::setVideoEncoderConfiguration "setVideoEncoderConfiguration". - */ - CAPTURER_OUTPUT_PREFERENCE_PERFORMANCE = 1, - /** 2: Prioritizes the local preview quality. The SDK chooses higher camera output parameters to improve the local video preview quality. This option requires extra CPU and RAM usage for video pre-processing. - */ - CAPTURER_OUTPUT_PREFERENCE_PREVIEW = 2, - }; - -/** The priority of the remote user. - */ -enum PRIORITY_TYPE -{ - /** 50: The user's priority is high. - */ - PRIORITY_HIGH = 50, - /** 100: (Default) The user's priority is normal. - */ - PRIORITY_NORMAL = 100, -}; - -/** Connection states. */ -enum CONNECTION_STATE_TYPE -{ - /** 1: The SDK is disconnected from Agora's edge server. - - - This is the initial state before calling the \ref agora::rtc::IRtcEngine::joinChannel "joinChannel" method. - - The SDK also enters this state when the application calls the \ref agora::rtc::IRtcEngine::leaveChannel "leaveChannel" method. - */ - CONNECTION_STATE_DISCONNECTED = 1, - /** 2: The SDK is connecting to Agora's edge server. - - - When the application calls the \ref agora::rtc::IRtcEngine::joinChannel "joinChannel" method, the SDK starts to establish a connection to the specified channel, triggers the \ref agora::rtc::IRtcEngineEventHandler::onConnectionStateChanged "onConnectionStateChanged" callback, and switches to the #CONNECTION_STATE_CONNECTING state. - - When the SDK successfully joins the channel, it triggers the \ref agora::rtc::IRtcEngineEventHandler::onConnectionStateChanged "onConnectionStateChanged" callback and switches to the #CONNECTION_STATE_CONNECTED state. - - After the SDK joins the channel and when it finishes initializing the media engine, the SDK triggers the \ref agora::rtc::IRtcEngineEventHandler::onJoinChannelSuccess "onJoinChannelSuccess" callback. - */ - CONNECTION_STATE_CONNECTING = 2, - /** 3: The SDK is connected to Agora's edge server and has joined a channel. You can now publish or subscribe to a media stream in the channel. - - If the connection to the channel is lost because, for example, if the network is down or switched, the SDK automatically tries to reconnect and triggers: - - The \ref agora::rtc::IRtcEngineEventHandler::onConnectionInterrupted "onConnectionInterrupted" callback (deprecated). - - The \ref agora::rtc::IRtcEngineEventHandler::onConnectionStateChanged "onConnectionStateChanged" callback and switches to the #CONNECTION_STATE_RECONNECTING state. - */ - CONNECTION_STATE_CONNECTED = 3, - /** 4: The SDK keeps rejoining the channel after being disconnected from a joined channel because of network issues. - - - If the SDK cannot rejoin the channel within 10 seconds after being disconnected from Agora's edge server, the SDK triggers the \ref agora::rtc::IRtcEngineEventHandler::onConnectionLost "onConnectionLost" callback, stays in the #CONNECTION_STATE_RECONNECTING state, and keeps rejoining the channel. - - If the SDK fails to rejoin the channel 20 minutes after being disconnected from Agora's edge server, the SDK triggers the \ref agora::rtc::IRtcEngineEventHandler::onConnectionStateChanged "onConnectionStateChanged" callback, switches to the #CONNECTION_STATE_FAILED state, and stops rejoining the channel. - */ - CONNECTION_STATE_RECONNECTING = 4, - /** 5: The SDK fails to connect to Agora's edge server or join the channel. - - You must call the \ref agora::rtc::IRtcEngine::leaveChannel "leaveChannel" method to leave this state, and call the \ref agora::rtc::IRtcEngine::joinChannel "joinChannel" method again to rejoin the channel. - - If the SDK is banned from joining the channel by Agora's edge server (through the RESTful API), the SDK triggers the \ref agora::rtc::IRtcEngineEventHandler::onConnectionBanned "onConnectionBanned" (deprecated) and \ref agora::rtc::IRtcEngineEventHandler::onConnectionStateChanged "onConnectionStateChanged" callbacks. - */ - CONNECTION_STATE_FAILED = 5, -}; - -/** Reasons for a connection state change. */ -enum CONNECTION_CHANGED_REASON_TYPE -{ - /** 0: The SDK is connecting to Agora's edge server. */ - CONNECTION_CHANGED_CONNECTING = 0, - /** 1: The SDK has joined the channel successfully. */ - CONNECTION_CHANGED_JOIN_SUCCESS = 1, - /** 2: The connection between the SDK and Agora's edge server is interrupted. */ - CONNECTION_CHANGED_INTERRUPTED = 2, - /** 3: The connection between the SDK and Agora's edge server is banned by Agora's edge server. */ - CONNECTION_CHANGED_BANNED_BY_SERVER = 3, - /** 4: The SDK fails to join the channel for more than 20 minutes and stops reconnecting to the channel. */ - CONNECTION_CHANGED_JOIN_FAILED = 4, - /** 5: The SDK has left the channel. */ - CONNECTION_CHANGED_LEAVE_CHANNEL = 5, - /** 6: The connection failed since Appid is not valid. */ - CONNECTION_CHANGED_INVALID_APP_ID = 6, - /** 7: The connection failed since channel name is not valid. */ - CONNECTION_CHANGED_INVALID_CHANNEL_NAME = 7, - /** 8: The connection failed since token is not valid, possibly because: - - - The App Certificate for the project is enabled in Dashboard, but you do not use Token when joining the channel. If you enable the App Certificate, you must use a token to join the channel. - - The uid that you specify in the \ref agora::rtc::IRtcEngine::joinChannel "joinChannel" method is different from the uid that you pass for generating the token. - */ - CONNECTION_CHANGED_INVALID_TOKEN = 8, - /** 9: The connection failed since token is expired. */ - CONNECTION_CHANGED_TOKEN_EXPIRED = 9, - /** 10: The connection is rejected by server. */ - CONNECTION_CHANGED_REJECTED_BY_SERVER = 10, - /** 11: The connection changed to reconnecting since SDK has set a proxy server. */ - CONNECTION_CHANGED_SETTING_PROXY_SERVER = 11, - /** 12: When SDK is in connection failed, the renew token operation will make it connecting. */ - CONNECTION_CHANGED_RENEW_TOKEN = 12, - /** 13: The IP Address of SDK client has changed. i.e., Network type or IP/Port changed by network operator might change client IP address. */ - CONNECTION_CHANGED_CLIENT_IP_ADDRESS_CHANGED = 13, - /** 14: Timeout for the keep-alive of the connection between the SDK and Agora's edge server. The connection state changes to CONNECTION_STATE_RECONNECTING(4). */ - CONNECTION_CHANGED_KEEP_ALIVE_TIMEOUT = 14, -}; - -/** Network type. */ -enum NETWORK_TYPE -{ - /** -1: The network type is unknown. */ - NETWORK_TYPE_UNKNOWN = -1, - /** 0: The SDK disconnects from the network. */ - NETWORK_TYPE_DISCONNECTED = 0, - /** 1: The network type is LAN. */ - NETWORK_TYPE_LAN = 1, - /** 2: The network type is Wi-Fi(including hotspots). */ - NETWORK_TYPE_WIFI = 2, - /** 3: The network type is mobile 2G. */ - NETWORK_TYPE_MOBILE_2G = 3, - /** 4: The network type is mobile 3G. */ - NETWORK_TYPE_MOBILE_3G = 4, - /** 5: The network type is mobile 4G. */ - NETWORK_TYPE_MOBILE_4G = 5, -}; - -/** States of the last-mile network probe test. */ -enum LASTMILE_PROBE_RESULT_STATE { - /** 1: The last-mile network probe test is complete. */ - LASTMILE_PROBE_RESULT_COMPLETE = 1, - /** 2: The last-mile network probe test is incomplete and the bandwidth estimation is not available, probably due to limited test resources. */ - LASTMILE_PROBE_RESULT_INCOMPLETE_NO_BWE = 2, - /** 3: The last-mile network probe test is not carried out, probably due to poor network conditions. */ - LASTMILE_PROBE_RESULT_UNAVAILABLE = 3 -}; -/** Audio output routing. */ -enum AUDIO_ROUTE_TYPE { - /** Default. - */ - AUDIO_ROUTE_DEFAULT = -1, - /** Headset. - */ - AUDIO_ROUTE_HEADSET = 0, - /** Earpiece. - */ - AUDIO_ROUTE_EARPIECE = 1, - /** Headset with no microphone. - */ - AUDIO_ROUTE_HEADSET_NO_MIC = 2, - /** Speakerphone. - */ - AUDIO_ROUTE_SPEAKERPHONE = 3, - /** Loudspeaker. - */ - AUDIO_ROUTE_LOUDSPEAKER = 4, - /** Bluetooth headset. - */ - AUDIO_ROUTE_BLUETOOTH = 5 -}; - -#if (defined(__APPLE__) && TARGET_OS_IOS) -/** Audio session restriction. */ -enum AUDIO_SESSION_OPERATION_RESTRICTION { - /** No restriction, the SDK has full control of the audio session operations. */ - AUDIO_SESSION_OPERATION_RESTRICTION_NONE = 0, - /** The SDK does not change the audio session category. */ - AUDIO_SESSION_OPERATION_RESTRICTION_SET_CATEGORY = 1, - /** The SDK does not change any setting of the audio session (category, mode, categoryOptions). */ - AUDIO_SESSION_OPERATION_RESTRICTION_CONFIGURE_SESSION = 1 << 1, - /** The SDK keeps the audio session active when leaving a channel. */ - AUDIO_SESSION_OPERATION_RESTRICTION_DEACTIVATE_SESSION = 1 << 2, - /** The SDK does not configure the audio session anymore. */ - AUDIO_SESSION_OPERATION_RESTRICTION_ALL = 1 << 7, -}; -#endif - -/** The uplink or downlink last-mile network probe test result. */ -struct LastmileProbeOneWayResult { - /** The packet loss rate (%). */ - unsigned int packetLossRate; - /** The network jitter (ms). */ - unsigned int jitter; - /* The estimated available bandwidth (Kbps). */ - unsigned int availableBandwidth; -}; - -/** The uplink and downlink last-mile network probe test result. */ -struct LastmileProbeResult{ - /** The state of the probe test. */ - LASTMILE_PROBE_RESULT_STATE state; - /** The uplink last-mile network probe test result. */ - LastmileProbeOneWayResult uplinkReport; - /** The downlink last-mile network probe test result. */ - LastmileProbeOneWayResult downlinkReport; - /** The round-trip delay time (ms). */ - unsigned int rtt; -}; - -/** Configurations of the last-mile network probe test. */ -struct LastmileProbeConfig { - /** Sets whether or not to test the uplink network. Some users, for example, the audience in a Live-broadcast channel, do not need such a test: - - true: test. - - false: do not test. */ - bool probeUplink; - /** Sets whether or not to test the downlink network: - - true: test. - - false: do not test. */ - bool probeDownlink; - /** The expected maximum sending bitrate (Kbps) of the local user. The value ranges between 100 and 5000. We recommend setting this parameter according to the bitrate value set by \ref IRtcEngine::setVideoEncoderConfiguration "setVideoEncoderConfiguration". */ - unsigned int expectedUplinkBitrate; - /** The expected maximum receiving bitrate (Kbps) of the local user. The value ranges between 100 and 5000. */ - unsigned int expectedDownlinkBitrate; -}; - -/** Properties of the audio volume information. - - An array containing the user ID and volume information for each speaker. - */ -struct AudioVolumeInfo -{ - /** - User ID of the speaker. The uid of the local user is 0. - */ - uid_t uid; - /** The volume of the speaker. The volume ranges between 0 (lowest volume) and 255 (highest volume). - */ - unsigned int volume; -}; - -/** Statistics of the channel. - */ -struct RtcStats -{ - /** - Call duration (s), represented by an aggregate value. - */ - unsigned int duration; - /** - Total number of bytes transmitted, represented by an aggregate value. - */ - unsigned int txBytes; - /** - Total number of bytes received, represented by an aggregate value. - */ - unsigned int rxBytes; - /** Total number of audio bytes sent (bytes), represented - * by an aggregate value. - */ - unsigned int txAudioBytes; - /** Total number of video bytes sent (bytes), represented - * by an aggregate value. - */ - unsigned int txVideoBytes; - /** Total number of audio bytes received (bytes) before - * network countermeasures, represented by an aggregate value. - */ - unsigned int rxAudioBytes; - /** Total number of video bytes received (bytes), - * represented by an aggregate value. - */ - unsigned int rxVideoBytes; - - /** - Transmission bitrate (Kbps), represented by an instantaneous value. - */ - unsigned short txKBitRate; - /** - Receive bitrate (Kbps), represented by an instantaneous value. - */ - unsigned short rxKBitRate; - /** - Audio receive bitrate (Kbps), represented by an instantaneous value. - */ - unsigned short rxAudioKBitRate; - /** - Audio transmission bitrate (Kbps), represented by an instantaneous value. - */ - unsigned short txAudioKBitRate; - /** - Video receive bitrate (Kbps), represented by an instantaneous value. - */ - unsigned short rxVideoKBitRate; - /** - Video transmission bitrate (Kbps), represented by an instantaneous value. - */ - unsigned short txVideoKBitRate; - /** Client-server latency (ms) - */ - unsigned short lastmileDelay; - /** The packet loss rate (%) from the local client to Agora's edge server, - * before network countermeasures. - */ - unsigned short txPacketLossRate; - /** The packet loss rate (%) from Agora's edge server to the local client, - * before network countermeasures. - */ - unsigned short rxPacketLossRate; - /** Number of users in the channel. - - - Communication profile: The number of users in the channel. - - Live broadcast profile: - - - If the local user is an audience: The number of users in the channel = The number of hosts in the channel + 1. - - If the user is a host: The number of users in the channel = The number of hosts in the channel. - */ - unsigned int userCount; - /** - Application CPU usage (%). - */ - double cpuAppUsage; - /** - System CPU usage (%). - */ - double cpuTotalUsage; - RtcStats() - : duration(0) - , txBytes(0) - , rxBytes(0) - , txAudioBytes(0) - , txVideoBytes(0) - , rxAudioBytes(0) - , rxVideoBytes(0) - , txKBitRate(0) - , rxKBitRate(0) - , rxAudioKBitRate(0) - , txAudioKBitRate(0) - , rxVideoKBitRate(0) - , txVideoKBitRate(0) - , lastmileDelay(0) - , txPacketLossRate(0) - , rxPacketLossRate(0) - , userCount(0) - , cpuAppUsage(0) - , cpuTotalUsage(0) {} -}; - -/** Quality change of the local video in terms of target frame rate and target bit rate since last count. - */ -enum QUALITY_ADAPT_INDICATION { - /** The quality of the local video stays the same. */ - ADAPT_NONE = 0, - /** The quality improves because the network bandwidth increases. */ - ADAPT_UP_BANDWIDTH = 1, - /** The quality worsens because the network bandwidth decreases. */ - ADAPT_DOWN_BANDWIDTH = 2, -}; - - -enum CHANNEL_MEDIA_RELAY_ERROR { - /** 0: The state is normal. - */ - RELAY_OK = 0, - /** 1: An error occurs in the server response. - */ - RELAY_ERROR_SERVER_ERROR_RESPONSE = 1, - /** 2: No server response. You can call the - * \ref agora::rtc::IRtcEngine::leaveChannel "leaveChannel" method to - * leave the channel. - */ - RELAY_ERROR_SERVER_NO_RESPONSE = 2, - /** 3: The SDK fails to access the service, probably due to limited - * resources of the server. - */ - RELAY_ERROR_NO_RESOURCE_AVAILABLE = 3, - /** 4: The server fails to join the source channel. - */ - RELAY_ERROR_FAILED_JOIN_SRC = 4, - /** 5: The server fails to join the destination channel. - */ - RELAY_ERROR_FAILED_JOIN_DEST = 5, - /** 6: The server fails to receive the data from the source channel. - */ - RELAY_ERROR_FAILED_PACKET_RECEIVED_FROM_SRC = 6, - /** 7: The source channel fails to transmit data. - */ - RELAY_ERROR_FAILED_PACKET_SENT_TO_DEST = 7, - /** 8: The SDK disconnects from the server due to poor network - * connections. You can call the \ref agora::rtc::IRtcEngine::leaveChannel - * "leaveChannel" method to leave the channel. - */ - RELAY_ERROR_SERVER_CONNECTION_LOST = 8, - /** 9: An internal error occurs in the server. - */ - RELAY_ERROR_INTERNAL_ERROR = 9, - /** 10: The token of the source channel has expired. - */ - RELAY_ERROR_SRC_TOKEN_EXPIRED = 10, - /** 11: The token of the destination channel has expired. - */ - RELAY_ERROR_DEST_TOKEN_EXPIRED = 11, -}; - -enum CHANNEL_MEDIA_RELAY_EVENT { - /** 0: The user disconnects from the server due to poor network - * connections. - */ - RELAY_EVENT_NETWORK_DISCONNECTED = 0, - /** 1: The network reconnects. - */ - RELAY_EVENT_NETWORK_CONNECTED = 1, - /** 2: The user joins the source channel. - */ - RELAY_EVENT_PACKET_JOINED_SRC_CHANNEL = 2, - /** 3: The user joins the destination channel. - */ - RELAY_EVENT_PACKET_JOINED_DEST_CHANNEL = 3, - /** 4: The SDK starts relaying the media stream to the destination channel. - */ - RELAY_EVENT_PACKET_SENT_TO_DEST_CHANNEL = 4, - /** 5: The server receives the video stream from the source channel. - */ - RELAY_EVENT_PACKET_RECEIVED_VIDEO_FROM_SRC = 5, - /** 6: The server receives the audio stream from the source channel. - */ - RELAY_EVENT_PACKET_RECEIVED_AUDIO_FROM_SRC = 6, - /** 7: The destination channel is updated. - */ - RELAY_EVENT_PACKET_UPDATE_DEST_CHANNEL = 7, - /** 8: The destination channel update fails due to internal reasons. - */ - RELAY_EVENT_PACKET_UPDATE_DEST_CHANNEL_REFUSED = 8, - /** 9: The destination channel does not change, which means that the - * destination channel fails to be updated. - */ - RELAY_EVENT_PACKET_UPDATE_DEST_CHANNEL_NOT_CHANGE = 9, - /** 10: The destination channel name is NULL. - */ - RELAY_EVENT_PACKET_UPDATE_DEST_CHANNEL_IS_NULL = 10, - /** 11: The video profile is sent to the server. - */ - RELAY_EVENT_VIDEO_PROFILE_UPDATE = 11, -}; - -enum CHANNEL_MEDIA_RELAY_STATE { - /** 0: The SDK is initializing. - */ - RELAY_STATE_IDLE = 0, - /** 1: The SDK tries to relay the media stream to the destination channel. - */ - RELAY_STATE_CONNECTING = 1, - /** 2: The SDK successfully relays the media stream to the destination - * channel. - */ - RELAY_STATE_RUNNING = 2, - /** 3: A failure occurs. See the details in code. - */ - RELAY_STATE_FAILURE = 3, -}; - -/** Statistics of the local video stream. - */ -struct LocalVideoStats -{ - /** Bitrate (Kbps) sent in the reported interval, which does not include - * the bitrate of the re-transmission video after packet loss. - */ - int sentBitrate; - /** Frame rate (fps) sent in the reported interval, which does not include - * the frame rate of the re-transmission video after packet loss. - */ - int sentFrameRate; - /** The encoder output frame rate (fps) of the local video. - */ - int encoderOutputFrameRate; - /** The render output frame rate (fps) of the local video. - */ - int rendererOutputFrameRate; - /** The target bitrate (Kbps) of the current encoder. This value is estimated by the SDK based on the current network conditions. - */ - int targetBitrate; - /** The target frame rate (fps) of the current encoder. - */ - int targetFrameRate; - /** Quality change of the local video in terms of target frame rate and - * target bit rate in this reported interval. See #QUALITY_ADAPT_INDICATION. - */ - QUALITY_ADAPT_INDICATION qualityAdaptIndication; - /** The encoding bitrate (Kbps), which does not include the bitrate of the - * re-transmission video after packet loss. - */ - int encodedBitrate; - /** The width of the encoding frame (px). - */ - int encodedFrameWidth; - /** The height of the encoding frame (px). - */ - int encodedFrameHeight; - /** The value of the sent frame rate, represented by an aggregate value. - */ - int encodedFrameCount; - /** The codec type of the local video: - * - VIDEO_CODEC_VP8 = 1: VP8. - * - VIDEO_CODEC_H264 = 2: (Default) H.264. - */ - VIDEO_CODEC_TYPE codecType; -}; - -/** Statistics of the remote video stream. - */ -struct RemoteVideoStats -{ - /** - User ID of the remote user sending the video streams. - */ - uid_t uid; - /** **DEPRECATED** Time delay (ms). - */ - int delay; -/** - Width (pixels) of the video stream. - */ - int width; - /** - Height (pixels) of the video stream. - */ - int height; - /** - Bitrate (Kbps) received since the last count. - */ - int receivedBitrate; - /** The decoder output frame rate (fps) of the remote video. - */ - int decoderOutputFrameRate; - /** The render output frame rate (fps) of the remote video. - */ - int rendererOutputFrameRate; - /** Packet loss rate (%) of the remote video stream after network - * countermeasures. - */ - int packetLossRate; - REMOTE_VIDEO_STREAM_TYPE rxStreamType; - /** - The total freeze time (ms) of the remote video stream after the remote user joins the channel. - In a video session where the frame rate is set to no less than 5 fps, video freeze occurs when - the time interval between two adjacent renderable video frames is more than 500 ms. - */ - int totalFrozenTime; - /** - The total video freeze time as a percentage (%) of the total time when the video is available. - */ - int frozenRate; -}; - -/** Audio statistics of the local user */ -struct LocalAudioStats -{ - /** The number of channels. - */ - int numChannels; - /** The sample rate (Hz). - */ - int sentSampleRate; - /** The average sending bitrate (Kbps). - */ - int sentBitrate; -}; - -/** Audio statistics of a remote user */ -struct RemoteAudioStats -{ - /** User ID of the remote user sending the audio streams. - * - */ - uid_t uid; - /** Audio quality received by the user: #QUALITY_TYPE. - */ - int quality; - /** Network delay (ms) from the sender to the receiver. - */ - int networkTransportDelay; - /** Network delay (ms) from the receiver to the jitter buffer. - */ - int jitterBufferDelay; - /** Packet loss rate in the reported interval. - */ - int audioLossRate; - /** The number of channels. - */ - int numChannels; - /** The sample rate (Hz) of the received audio stream in the reported - * interval. - */ - int receivedSampleRate; - /** The average bitrate (Kbps) of the received audio stream in the - * reported interval. */ - int receivedBitrate; - /** The total freeze time (ms) of the remote audio stream after the remote user joins the channel. In a session, audio freeze occurs when the audio frame loss rate reaches 4%. - * Agora uses 2 seconds as an audio piece unit to calculate the audio freeze time. The total audio freeze time = The audio freeze number × 2 seconds - */ - int totalFrozenTime; - /** The total audio freeze time as a percentage (%) of the total time when the audio is available. */ - int frozenRate; -}; - -/** - * Video dimensions. - */ -struct VideoDimensions { - /** Width (pixels) of the video. */ - int width; - /** Height (pixels) of the video. */ - int height; - VideoDimensions() - : width(640), height(480) - {} - VideoDimensions(int w, int h) - : width(w), height(h) - {} -}; - -/** (Recommended) The standard bitrate set in the \ref IRtcEngine::setVideoEncoderConfiguration "setVideoEncoderConfiguration" method. - - In this mode, the bitrates differ between the live broadcast and communication profiles: - - - Communication profile: The video bitrate is the same as the base bitrate. - - Live broadcast profile: The video bitrate is twice the base bitrate. - - */ -const int STANDARD_BITRATE = 0; - -/** The compatible bitrate set in the \ref IRtcEngine::setVideoEncoderConfiguration "setVideoEncoderConfiguration" method. - - The bitrate remains the same regardless of the channel profile. If you choose this mode in the Live-broadcast profile, the video frame rate may be lower than the set value. - */ -const int COMPATIBLE_BITRATE = -1; - -/** Use the default minimum bitrate. - */ -const int DEFAULT_MIN_BITRATE = -1; - -/** Video encoder configurations. - */ -struct VideoEncoderConfiguration { - /** The video frame dimensions (px) used to specify the video quality and measured by the total number of pixels along a frame's width and height: VideoDimensions. The default value is 640 x 360. - */ - VideoDimensions dimensions; - /** The frame rate of the video: #FRAME_RATE. The default value is 15. - - Note that we do not recommend setting this to a value greater than 30. - */ - FRAME_RATE frameRate; - /** The minimum frame rate of the video. The default value is -1. - */ - int minFrameRate; - /** The video encoding bitrate (Kbps). - - Choose one of the following options: - - - #STANDARD_BITRATE: (Recommended) The standard bitrate. - - The Communication profile: the encoding bitrate equals the base bitrate. - - The Live-broadcast profile: the encoding bitrate is twice the base bitrate. - - #COMPATIBLE_BITRATE: The compatible bitrate: the bitrate stays the same regardless of the profile. - - The Communication profile prioritizes smoothness, while the Live-broadcast profile prioritizes video quality (requiring a higher bitrate). We recommend setting the bitrate mode as #STANDARD_BITRATE to address this difference. - - The following table lists the recommended video encoder configurations, where the base bitrate applies to the Communication profile. Set your bitrate based on this table. If you set a bitrate beyond the proper range, the SDK automatically sets it to within the range. - - | Resolution | Frame Rate (fps) | Base Bitrate (Kbps, for Communication) | Live Bitrate (Kbps, for Live Broadcast)| - |------------------------|------------------|----------------------------------------|----------------------------------------| - | 160 × 120 | 15 | 65 | 130 | - | 120 × 120 | 15 | 50 | 100 | - | 320 × 180 | 15 | 140 | 280 | - | 180 × 180 | 15 | 100 | 200 | - | 240 × 180 | 15 | 120 | 240 | - | 320 × 240 | 15 | 200 | 400 | - | 240 × 240 | 15 | 140 | 280 | - | 424 × 240 | 15 | 220 | 440 | - | 640 × 360 | 15 | 400 | 800 | - | 360 × 360 | 15 | 260 | 520 | - | 640 × 360 | 30 | 600 | 1200 | - | 360 × 360 | 30 | 400 | 800 | - | 480 × 360 | 15 | 320 | 640 | - | 480 × 360 | 30 | 490 | 980 | - | 640 × 480 | 15 | 500 | 1000 | - | 480 × 480 | 15 | 400 | 800 | - | 640 × 480 | 30 | 750 | 1500 | - | 480 × 480 | 30 | 600 | 1200 | - | 848 × 480 | 15 | 610 | 1220 | - | 848 × 480 | 30 | 930 | 1860 | - | 640 × 480 | 10 | 400 | 800 | - | 1280 × 720 | 15 | 1130 | 2260 | - | 1280 × 720 | 30 | 1710 | 3420 | - | 960 × 720 | 15 | 910 | 1820 | - | 960 × 720 | 30 | 1380 | 2760 | - | 1920 × 1080 | 15 | 2080 | 4160 | - | 1920 × 1080 | 30 | 3150 | 6300 | - | 1920 × 1080 | 60 | 4780 | 6500 | - | 2560 × 1440 | 30 | 4850 | 6500 | - | 2560 × 1440 | 60 | 6500 | 6500 | - | 3840 × 2160 | 30 | 6500 | 6500 | - | 3840 × 2160 | 60 | 6500 | 6500 | - - */ - int bitrate; - /** The minimum encoding bitrate (Kbps). - - The SDK automatically adjusts the encoding bitrate to adapt to the network conditions. Using a value greater than the default value forces the video encoder to output high-quality images but may cause more packet loss and hence sacrifice the smoothness of the video transmission. That said, unless you have special requirements for image quality, Agora does not recommend changing this value. - - @note This parameter applies only to the Live-broadcast profile. - */ - int minBitrate; - /** The video orientation mode of the video: #ORIENTATION_MODE. - */ - ORIENTATION_MODE orientationMode; - /** the video encoding degradation preference under limited bandwidth: #DEGRADATION_PREFERENCE. - */ - DEGRADATION_PREFERENCE degradationPreference; - - VideoEncoderConfiguration( - const VideoDimensions& d, FRAME_RATE f, - int b, ORIENTATION_MODE m) - : dimensions(d), frameRate(f), minFrameRate(-1), bitrate(b), - minBitrate(DEFAULT_MIN_BITRATE), orientationMode(m), - degradationPreference(MAINTAIN_QUALITY) - {} - VideoEncoderConfiguration( - int width, int height, FRAME_RATE f, - int b, ORIENTATION_MODE m) - : dimensions(width, height), frameRate(f), - minFrameRate(-1), bitrate(b), - minBitrate(DEFAULT_MIN_BITRATE), orientationMode(m), - degradationPreference(MAINTAIN_QUALITY) - {} - VideoEncoderConfiguration() - : dimensions(640, 480) - , frameRate(FRAME_RATE_FPS_15) - , minFrameRate(-1) - , bitrate(STANDARD_BITRATE) - , minBitrate(DEFAULT_MIN_BITRATE) - , orientationMode(ORIENTATION_MODE_ADAPTIVE) - , degradationPreference(MAINTAIN_QUALITY) - {} -}; - -/** The video properties of the user displaying the video in the CDN live. Agora supports a maximum of 17 transcoding users in a CDN streaming channel. -*/ -typedef struct TranscodingUser { - /** User ID of the user displaying the video in the CDN live. - */ - uid_t uid; - -/** Horizontal position from the top left corner of the video frame. -*/ - int x; - /** Vertical position from the top left corner of the video frame. - */ - int y; - /** Width of the video frame. The default value is 360. - */ - int width; - /** Height of the video frame. The default value is 640. - */ - int height; - - /** Layer position of the video frame. The value ranges between 0 and 100. - - - 0: (Default) Lowest - - 100: Highest - - @note - - If zOrder is beyond this range, the SDK reports #ERR_INVALID_ARGUMENT. - - As of v2.3, the SDK supports zOrder = 0. - */ - int zOrder; - /** Transparency of the video frame in CDN live. The value ranges between 0 and 1.0: - - - 0: Completely transparent - - 1.0: (Default) Opaque - */ - double alpha; - /** The audio channel of the sound. The default value is 0: - - - 0: (Default) Supports dual channels at most, depending on the upstream of the broadcaster. - - 1: The audio stream of the broadcaster uses the FL audio channel. If the upstream of the broadcaster uses multiple audio channels, these channels are mixed into mono first. - - 2: The audio stream of the broadcaster uses the FC audio channel. If the upstream of the broadcaster uses multiple audio channels, these channels are mixed into mono first. - - 3: The audio stream of the broadcaster uses the FR audio channel. If the upstream of the broadcaster uses multiple audio channels, these channels are mixed into mono first. - - 4: The audio stream of the broadcaster uses the BL audio channel. If the upstream of the broadcaster uses multiple audio channels, these channels are mixed into mono first. - - 5: The audio stream of the broadcaster uses the BR audio channel. If the upstream of the broadcaster uses multiple audio channels, these channels are mixed into mono first. - - @note If your setting is not 0, you may need a specialized player. - */ - int audioChannel; - TranscodingUser() - : uid(0) - , x(0) - , y(0) - , width(0) - , height(0) - , zOrder(0) - , alpha(1.0) - , audioChannel(0) - {} - -} TranscodingUser; - -/** Image properties. - - The properties of the watermark and background images. - */ -typedef struct RtcImage { - RtcImage() : - url(NULL), - x(0), - y(0), - width(0), - height(0) - {} - /** HTTP/HTTPS URL address of the image on the broadcasting video. The maximum length of this parameter is 1024 bytes. */ - const char* url; - /** Horizontal position of the image from the upper left of the broadcasting video. */ - int x; - /** Vertical position of the image from the upper left of the broadcasting video. */ - int y; - /** Width of the image on the broadcasting video. */ - int width; - /** Height of the image on the broadcasting video. */ - int height; -} RtcImage; - -/** A struct for managing CDN live audio/video transcoding settings. -*/ -typedef struct LiveTranscoding { - /** Width of the video. The default value is 360. The minimum value of width × height is 16 × 16. - */ - int width; - /** Height of the video. The default value is 640. The minimum value of width × height is 16 × 16. - */ - int height; - /** Bitrate of the CDN live output video stream. The default value is 400 Kbps. - - Set this parameter according to the Video Bitrate Table. If you set a bitrate beyond the proper range, the SDK automatically adapts it to a value within the range. - */ - int videoBitrate; - /** Frame rate of the output video stream set for the CDN live broadcast. The default value is 15 fps. - - @note Agora adjusts all values over 30 to 30. - */ - int videoFramerate; - - /** **DEPRECATED** Latency mode: - - - true: Low latency with unassured quality. - - false: (Default) High latency with assured quality. - */ - bool lowLatency; - - /** Video GOP in frames. The default value is 30 fps. - */ - int videoGop; - /** Self-defined video codec profile: #VIDEO_CODEC_PROFILE_TYPE. - - @note If you set this parameter to other values, Agora adjusts it to the default value of 100. - */ - VIDEO_CODEC_PROFILE_TYPE videoCodecProfile; - /** The background color in RGB hex value. Value only, do not include a #. For example, 0xFFB6C1 (light pink). The default value is 0x000000 (black). - */ - unsigned int backgroundColor; - /** The number of users in the live broadcast. - */ - unsigned int userCount; - /** TranscodingUser - */ - TranscodingUser *transcodingUsers; - /** Reserved property. Extra user-defined information to send SEI for the H.264/H.265 video stream to the CDN live client. Maximum length: 4096 Bytes. - - For more information on SEI frame, see [SEI-related questions](https://docs.agora.io/cn/Agora%20Platform/live_related_faq?platform=%E7%9B%B4%E6%92%AD%E7%9B%B8%E5%85%B3#sei). - */ - const char *transcodingExtraInfo; - - /** **DEPRECATED** The metadata sent to the CDN live client defined by the RTMP or FLV metadata. - */ - const char *metadata; - /** The watermark image added to the CDN live publishing stream. - - Ensure that the format of the image is PNG. Once a watermark image is added, the audience of the CDN live publishing stream can see the watermark image. See RtcImage. - */ - RtcImage* watermark; - /** The background image added to the CDN live publishing stream. - - Once a background image is added, the audience of the CDN live publishing stream can see the background image. See RtcImage. - */ - RtcImage* backgroundImage; - /** Self-defined audio-sample rate: #AUDIO_SAMPLE_RATE_TYPE. - */ - AUDIO_SAMPLE_RATE_TYPE audioSampleRate; - /** Bitrate of the CDN live audio output stream. The default value is 48 Kbps, and the highest value is 128. - */ - int audioBitrate; - /** Agora's self-defined audio-channel types. We recommend choosing option 1 or 2. A special player is required if you choose option 3, 4, or 5: - - - 1: (Default) Mono - - 2: Two-channel stereo - - 3: Three-channel stereo - - 4: Four-channel stereo - - 5: Five-channel stereo - */ - int audioChannels; - /** Self-defined audio codec profile: #AUDIO_CODEC_PROFILE_TYPE. - */ - - AUDIO_CODEC_PROFILE_TYPE audioCodecProfile; - - - LiveTranscoding() - : width(360) - , height(640) - , videoBitrate(400) - , videoFramerate(15) - , lowLatency(false) - , videoGop(30) - , videoCodecProfile(VIDEO_CODEC_PROFILE_HIGH) - , backgroundColor(0x000000) - , userCount(0) - , transcodingUsers(NULL) - , transcodingExtraInfo(NULL) - , metadata(NULL) - , watermark(NULL) - , backgroundImage(NULL) - , audioSampleRate(AUDIO_SAMPLE_RATE_48000) - , audioBitrate(48) - , audioChannels(1) - , audioCodecProfile(AUDIO_CODEC_PROFILE_LC_AAC) - {} -} LiveTranscoding; - - /** Camera capturer configuration. - */ - struct CameraCapturerConfiguration{ - - /** Camera capturer preference settings.See: #CAPTURER_OUTPUT_PREFERENCE. */ - CAPTURER_OUTPUT_PREFERENCE preference; - }; - -/** Configuration of the imported live broadcast voice or video stream. - */ -struct InjectStreamConfig { - /** Width of the added stream in the live broadcast. The default value is 0 (same width as the original stream). - */ - int width; - /** Height of the added stream in the live broadcast. The default value is 0 (same height as the original stream). - */ - int height; - /** Video GOP of the added stream in the live broadcast in frames. The default value is 30 fps. - */ - int videoGop; - /** Video frame rate of the added stream in the live broadcast. The default value is 15 fps. - */ - int videoFramerate; - /** Video bitrate of the added stream in the live broadcast. The default value is 400 Kbps. - - @note The setting of the video bitrate is closely linked to the resolution. If the video bitrate you set is beyond a reasonable range, the SDK sets it within a reasonable range. - */ - int videoBitrate; - /** Audio-sample rate of the added stream in the live broadcast: #AUDIO_SAMPLE_RATE_TYPE. The default value is 48000 Hz. - - @note We recommend setting the default value. - */ - AUDIO_SAMPLE_RATE_TYPE audioSampleRate; - /** Audio bitrate of the added stream in the live broadcast. The default value is 48. - - @note We recommend setting the default value. - */ - int audioBitrate; - /** Audio channels in the live broadcast. - - - 1: (Default) Mono - - 2: Two-channel stereo - - @note We recommend setting the default value. - */ - int audioChannels; - - // width / height default set to 0 means pull the stream with its original resolution - InjectStreamConfig() - : width(0) - , height(0) - , videoGop(30) - , videoFramerate(15) - , videoBitrate(400) - , audioSampleRate(AUDIO_SAMPLE_RATE_48000) - , audioBitrate(48) - , audioChannels(1) - {} -}; -/** The definition of ChannelMediaInfo. - */ -struct ChannelMediaInfo { - /** The channel name. The default value is NULL, which means that the SDK - * applies the current channel name. - */ - const char* channelName; - /** The token that enables the user to join the channel. The default value - * is NULL, which means that the SDK applies the current token. - */ - const char* token; - /** The user ID. - * - * @note - * String user accounts are not supported in media stream relay. - */ - uid_t uid; -}; - -/** The definition of ChannelMediaRelayConfiguration. - */ -struct ChannelMediaRelayConfiguration { - /** Pointer to the source channel: ChannelMediaInfo. - * - * @note - * - `uid`: ID of the user whose media stream you want to relay. We - * recommend setting it as 0, which means that the SDK relays the media - * stream of the current broadcaster. - * - If you do not use a token, we recommend using the default values of - * the parameters in ChannelMediaInfo. - * - If you use a token, set uid as 0, and ensure that the token is - * generated with the uid set as 0. - */ - ChannelMediaInfo *srcInfo; - /** Pointer to the destination channel: ChannelMediaInfo. If you want to - * relay the media stream to multiple channels, define as many - * ChannelMediaInfo structs (at most four). - * - * @note `uid`: ID of the user who is in the source channel. - */ - ChannelMediaInfo *destInfos; - /** The number of destination channels. The default value is 0, and the - * value range is [0,4). Ensure that the value of this parameter - * corresponds to the number of ChannelMediaInfo structs you define in - * `destInfos`. - */ - int destCount; - - ChannelMediaRelayConfiguration() - : srcInfo(nullptr) - , destInfos(nullptr) - , destCount(0) - {} -}; - -/** **DEPRECATED** Lifecycle of the CDN live video stream. -*/ -enum RTMP_STREAM_LIFE_CYCLE_TYPE -{ - /** Bind to the channel lifecycle. If all hosts leave the channel, the CDN live streaming stops after 30 seconds. - */ - RTMP_STREAM_LIFE_CYCLE_BIND2CHANNEL = 1, - /** Bind to the owner of the RTMP stream. If the owner leaves the channel, the CDN live streaming stops immediately. - */ - RTMP_STREAM_LIFE_CYCLE_BIND2OWNER = 2, -}; - -/** Content hints for screen sharing. -*/ -enum VideoContentHint -{ - /** (Default) No content hint. - */ - CONTENT_HINT_NONE, - /** Motion-intensive content. Choose this option if you prefer smoothness or when you are sharing a video clip, movie, or video game. - */ - CONTENT_HINT_MOTION, - /** Motionless content. Choose this option if you prefer sharpness or when you are sharing a picture, PowerPoint slide, or text. - */ - CONTENT_HINT_DETAILS -}; - - /** The relative location of the region to the screen or window. - */ -struct Rectangle -{ - /** The horizontal offset from the top-left corner. - */ - int x; - /** The vertical offset from the top-left corner. - */ - int y; - /** The width of the region. - */ - int width; - /** The height of the region. - */ - int height; - - Rectangle(): x(0), y(0), width(0), height(0) {} - Rectangle(int xx, int yy, int ww, int hh): x(xx), y(yy), width(ww), height(hh) {} -}; - -/** **DEPRECATED** Definition of the rectangular region. */ -typedef struct Rect { - /** Y-axis of the top line. - */ - int top; - /** X-axis of the left line. - */ - int left; - /** Y-axis of the bottom line. - */ - int bottom; - /** X-axis of the right line. - */ - int right; - - Rect(): top(0), left(0), bottom(0), right(0) {} - Rect(int t, int l, int b, int r): top(t), left(l), bottom(b), right(r) {} -} Rect; - -/** Screen sharing encoding parameters. -*/ -struct ScreenCaptureParameters -{ - /** The maximum encoding dimensions of the shared region in terms of width × height. - - The default value is 1920 × 1080 pixels, that is, 2073600 pixels. Agora uses the value of this parameter to calculate the charges. - - If the aspect ratio is different between the encoding dimensions and screen dimensions, Agora applies the following algorithms for encoding. Suppose the encoding dimensions are 1920 x 1080: - - - If the value of the screen dimensions is lower than that of the encoding dimensions, for example, 1000 × 1000, the SDK uses 1000 × 1000 for encoding. - - If the value of the screen dimensions is higher than that of the encoding dimensions, for example, 2000 × 1500, the SDK uses the maximum value under 1920 × 1080 with the aspect ratio of the screen dimension (4:3) for encoding, that is, 1440 × 1080. - */ - VideoDimensions dimensions; - /** The frame rate (fps) of the shared region. - - The default value is 5. We do not recommend setting this to a value greater than 15. - */ - int frameRate; - /** The bitrate (Kbps) of the shared region. - - The default value is 0 (the SDK works out a bitrate according to the dimensions of the current screen). - */ - int bitrate; - /** Sets whether or not to capture the mouse for screen sharing: - - - true: (Default) Capture the mouse. - - false: Do not capture the mouse. - */ - bool captureMouseCursor; - - ScreenCaptureParameters() : dimensions(1920, 1080), frameRate(5), bitrate(STANDARD_BITRATE), captureMouseCursor(true) {} - ScreenCaptureParameters(const VideoDimensions& d, int f, int b, bool c) : dimensions(d), frameRate(f), bitrate(b), captureMouseCursor(c) {} - ScreenCaptureParameters(int width, int height, int f, int b, bool c) : dimensions(width, height), frameRate(f), bitrate(b), captureMouseCursor(c) {} -}; - -/** Video display settings of the VideoCanvas class. -*/ -struct VideoCanvas -{ - /** Video display window (view). - */ - view_t view; - /** Video display mode: #RENDER_MODE_TYPE. - */ - int renderMode; - uid_t uid; - void *priv; // private data (underlying video engine denotes it) - - VideoCanvas() - : view(NULL) - , renderMode(RENDER_MODE_HIDDEN) - , uid(0) - , priv(NULL) - {} - VideoCanvas(view_t v, int m, uid_t u) - : view(v) - , renderMode(m) - , uid(u) - , priv(NULL) - {} -}; - -/** Image enhancement options. -*/ -struct BeautyOptions { - /** The contrast level, used with the @p lightening parameter. - */ - enum LIGHTENING_CONTRAST_LEVEL - { - /** Low contrast level. */ - LIGHTENING_CONTRAST_LOW = 0, - /** (Default) Normal contrast level. */ - LIGHTENING_CONTRAST_NORMAL, - /** High contrast level. */ - LIGHTENING_CONTRAST_HIGH - }; - -/** The contrast level, used with the @p lightening parameter. -*/ -LIGHTENING_CONTRAST_LEVEL lighteningContrastLevel; - -/** The brightness level. The value ranges from 0.0 (original) to 1.0. */ -float lighteningLevel; - -/** The sharpness level. The value ranges between 0 (original) and 1. This parameter is usually used to remove blemishes. - */ -float smoothnessLevel; - -/** The redness level. The value ranges between 0 (original) and 1. This parameter adjusts the red saturation level. -*/ -float rednessLevel; - -BeautyOptions(LIGHTENING_CONTRAST_LEVEL contrastLevel, float lightening, float smoothness, float redness) - : lighteningLevel(lightening), - smoothnessLevel(smoothness), - rednessLevel(redness), - lighteningContrastLevel(contrastLevel) {} - -BeautyOptions() - : lighteningLevel(0), - smoothnessLevel(0), - rednessLevel(0), - lighteningContrastLevel(LIGHTENING_CONTRAST_NORMAL) {} -}; - -struct UserInfo { - uid_t uid; - char userAccount[MAX_USER_ACCOUNT_LENGTH]; - UserInfo() - : uid(0) { - userAccount[0] = '\0'; - } -}; - -/** Definition of IPacketObserver. -*/ -class IPacketObserver -{ -public: -/** Definition of Packet. - */ - struct Packet - { - /** Buffer address of the sent or received data. - */ - const unsigned char* buffer; - /** Buffer size of the sent or received data. - */ - unsigned int size; - }; - /** Occurs when the local user sends an audio packet. - - @param packet The sent audio packet. See Packet. - @return - - true: The audio packet is sent successfully. - - false: The audio packet is discarded. - */ - virtual bool onSendAudioPacket(Packet& packet) = 0; - /** Occurs when the local user sends a video packet. - - @param packet The sent video packet. See Packet. - @return - - true: The video packet is sent successfully. - - false: The video packet is discarded. - */ - virtual bool onSendVideoPacket(Packet& packet) = 0; - /** Occurs when the local user receives an audio packet. - - @param packet The received audio packet. See Packet. - @return - - true: The audio packet is received successfully. - - false: The audio packet is discarded. - */ - virtual bool onReceiveAudioPacket(Packet& packet) = 0; - /** Occurs when the local user receives a video packet. - - @param packet The received video packet. See Packet. - @return - - true: The video packet is received successfully. - - false: The video packet is discarded. - */ - virtual bool onReceiveVideoPacket(Packet& packet) = 0; -}; - - -/** The SDK uses the IRtcEngineEventHandler interface class to send callbacks to the application. The application inherits the methods of this interface class to retrieve these callbacks. - - All methods in this interface class have default (empty) implementations. Therefore, the application can only inherit some required events. In the callbacks, avoid time-consuming tasks or calling blocking APIs, such as the SendMessage method. Otherwise, the SDK may not work properly. - */ -class IRtcEngineEventHandler -{ -public: - virtual ~IRtcEngineEventHandler() {} - - /** Reports a warning during SDK runtime. - - In most cases, the application can ignore the warning reported by the SDK because the SDK can usually fix the issue and resume running. For example, when losing connection with the server, the SDK may report #WARN_LOOKUP_CHANNEL_TIMEOUT and automatically try to reconnect. - - @param warn Warning code: #WARN_CODE_TYPE. - @param msg Pointer to the warning message. - */ - virtual void onWarning(int warn, const char* msg) { - (void)warn; - (void)msg; - } - - /** Reports an error during SDK runtime. - - In most cases, the SDK cannot fix the issue and resume running. The SDK requires the application to take action or informs the user about the issue. - - For example, the SDK reports an #ERR_START_CALL error when failing to initialize a call. The application informs the user that the call initialization failed and invokes the \ref IRtcEngine::leaveChannel "leaveChannel" method to leave the channel. - - @param err Error code: #ERROR_CODE_TYPE. - @param msg Pointer to the error message. - */ - virtual void onError(int err, const char* msg) { - (void)err; - (void)msg; - } - - /** Occurs when a user joins a specified channel. - - This callback notifies the application that a user joins a specified channel when the application calls the \ref IRtcEngine::joinChannel "joinChannel" method. - - The channel name assignment is based on @p channelName specified in the \ref IRtcEngine::joinChannel "joinChannel" method. - - If the @p uid is not specified in the *joinChannel* method, the server automatically assigns a @p uid. - - @param channel Pointer to the channel name. - @param uid User ID of the user joining the channel. - @param elapsed Time elapsed (ms) from the user calling the \ref IRtcEngine::joinChannel "joinChannel" method until the SDK triggers this callback. - */ - virtual void onJoinChannelSuccess(const char* channel, uid_t uid, int elapsed) { - (void)channel; - (void)uid; - (void)elapsed; - } - - /** Occurs when a user rejoins the channel after disconnection due to network problems. - - When a user loses connection with the server because of network problems, the SDK automatically tries to reconnect and triggers this callback upon reconnection. - - @param channel Pointer to the channel name. - @param uid User ID of the user rejoining the channel. - @param elapsed Time elapsed (ms) from starting to reconnect until the SDK triggers this callback. - */ - virtual void onRejoinChannelSuccess(const char* channel, uid_t uid, int elapsed) { - (void)channel; - (void)uid; - (void)elapsed; - } - - /** Occurs when a user leaves the channel. - - This callback notifies the application that a user leaves the channel when the application calls the \ref IRtcEngine::leaveChannel "leaveChannel" method. - - The application retrieves information, such as the call duration and statistics. - - @param stats Pointer to the statistics of the call: RtcStats. - */ - virtual void onLeaveChannel(const RtcStats& stats) { - (void)stats; - } - - /** Occurs when the user role switches in a live broadcast. For example, from a host to an audience or vice versa. - - This callback notifies the application of a user role switch when the application calls the \ref IRtcEngine::setClientRole "setClientRole" method. - - The SDK triggers this callback when the local user switches the user role by calling the \ref agora::rtc::IRtcEngine::setClientRole "setClientRole" method after joining the channel. - @param oldRole Role that the user switches from: #CLIENT_ROLE_TYPE. - @param newRole Role that the user switches to: #CLIENT_ROLE_TYPE. - */ - virtual void onClientRoleChanged(CLIENT_ROLE_TYPE oldRole, CLIENT_ROLE_TYPE newRole) { - } - - /** Occurs when a user or host joins the channel. - - - Communication profile: This callback notifies the application that another user joins the channel. If other users are already in the channel, the SDK also reports to the application on the existing users. - - Live-broadcast profile: This callback notifies the application that the host joins the channel. If other hosts are already in the channel, the SDK also reports to the application on the existing hosts. We recommend limiting the number of hosts to 17. - - The SDK triggers this callback under one of the following circumstances: - - A remote user/host joins the channel by calling the \ref agora::rtc::IRtcEngine::joinChannel "joinChannel" method. - - A remote user switches the user role to the host by calling the \ref agora::rtc::IRtcEngine::setClientRole "setClientRole" method after joining the channel. - - A remote user/host rejoins the channel after a network interruption. - - The host injects an online media stream into the channel by calling the \ref agora::rtc::IRtcEngine::addInjectStreamUrl "addInjectStreamUrl" method. - - @note In the Live-broadcast profile: - - The host receives this callback when another host joins the channel. - - The audience in the channel receives this callback when a new host joins the channel. - - When a web application joins the channel, the SDK triggers this callback as long as the web application publishes streams. - - @param uid User ID of the user or host joining the channel. - @param elapsed Time delay (ms) from the local user calling the \ref IRtcEngine::joinChannel "joinChannel" method until the SDK triggers this callback. - */ - virtual void onUserJoined(uid_t uid, int elapsed) { - (void)uid; - (void)elapsed; - } - - /** Occurs when a remote user (Communication)/host (Live Broadcast) leaves the channel. - - Reasons why the user is offline: - - - Leave the channel: When the user/host leaves the channel, the user/host sends a goodbye message. When the message is received, the SDK assumes that the user/host leaves the channel. - - Drop offline: When no data packet of the user or host is received for a certain period of time (20 seconds for the Communication profile, and more for the Live-broadcast profile), the SDK assumes that the user/host drops offline. Unreliable network connections may lead to false detections, so we recommend using a signaling system for more reliable offline detection. - - @param uid User ID of the user leaving the channel or going offline. - @param reason Reason why the user is offline: #USER_OFFLINE_REASON_TYPE. - */ - virtual void onUserOffline(uid_t uid, USER_OFFLINE_REASON_TYPE reason) { - (void)uid; - (void)reason; - } - - /** Reports the last mile network quality of the local user once every two seconds before the user joins the channel. - - Last mile refers to the connection between the local device and Agora's edge server. After the application calls the \ref IRtcEngine::enableLastmileTest "enableLastmileTest" method, this callback reports once every two seconds the uplink and downlink last mile network conditions of the local user before the user joins the channel. - - @param quality The last mile network quality: #QUALITY_TYPE. - */ - virtual void onLastmileQuality(int quality) { - (void)quality; - } - - /** Reports the last-mile network probe result. - - The SDK triggers this callback within 30 seconds after the app calls the \ref agora::rtc::IRtcEngine::startLastmileProbeTest "startLastmileProbeTest" method. - - @param result The uplink and downlink last-mile network probe test result. See LastmileProbeResult. - */ - virtual void onLastmileProbeResult(const LastmileProbeResult& result) { - (void)result; - } - - /** **DEPRECATED** Occurs when the connection between the SDK and the server is interrupted. - - Deprecated as of v2.3.2. Replaced by the \ref agora::rtc::IRtcEngineEventHandler::onConnectionStateChanged "onConnectionStateChanged(CONNECTION_STATE_RECONNECTING, CONNECTION_CHANGED_INTERRUPTED)" callback. - - The SDK triggers this callback when it loses connection with the server for more than four seconds after the connection is established. - - After triggering this callback, the SDK tries reconnecting to the server. You can use this callback to implement pop-up reminders. - - This callback is different from \ref agora::rtc::IRtcEngineEventHandler::onConnectionLost "onConnectionLost": - - The SDK triggers the \ref agora::rtc::IRtcEngineEventHandler::onConnectionInterrupted "onConnectionInterrupted" callback when it loses connection with the server for more than four seconds after it successfully joins the channel. - - The SDK triggers the \ref agora::rtc::IRtcEngineEventHandler::onConnectionLost "onConnectionLost" callback when it loses connection with the server for more than 10 seconds, whether or not it joins the channel. - - For both callbacks, the SDK tries to reconnect to the server until the application calls the \ref IRtcEngine::leaveChannel "leaveChannel" method. - - */ - virtual void onConnectionInterrupted() {} - - /** Occurs when the SDK cannot reconnect to Agora's edge server 10 seconds after its connection to the server is interrupted. - - The SDK triggers this callback when it cannot connect to the server 10 seconds after calling the \ref IRtcEngine::joinChannel "joinChannel" method, whether or not it is in the channel. - - This callback is different from \ref agora::rtc::IRtcEngineEventHandler::onConnectionInterrupted "onConnectionInterrupted": - - - The SDK triggers the \ref agora::rtc::IRtcEngineEventHandler::onConnectionInterrupted "onConnectionInterrupted" callback when it loses connection with the server for more than four seconds after it successfully joins the channel. - - The SDK triggers the \ref agora::rtc::IRtcEngineEventHandler::onConnectionLost "onConnectionLost" callback when it loses connection with the server for more than 10 seconds, whether or not it joins the channel. - - For both callbacks, the SDK tries to reconnect to the server until the application calls the \ref IRtcEngine::leaveChannel "leaveChannel" method. - - */ - virtual void onConnectionLost() {} - - /** **DEPRECATED** Deprecated as of v2.3.2. Replaced by the \ref agora::rtc::IRtcEngineEventHandler::onConnectionStateChanged "onConnectionStateChanged(CONNECTION_STATE_FAILED, CONNECTION_CHANGED_BANNED_BY_SERVER)" callback. - - Occurs when your connection is banned by the Agora Server. - */ - virtual void onConnectionBanned() {} - - /** Occurs when a method is executed by the SDK. - - @param err The error code (#ERROR_CODE_TYPE) returned by the SDK when a method call fails. If the SDK returns 0, then the method call is successful. - @param api Pointer to the method executed by the SDK. - @param result Pointer to the result of the method call. - */ - virtual void onApiCallExecuted(int err, const char* api, const char* result) { - (void)err; - (void)api; - (void)result; - } - - /** Occurs when the token expires. - - After a token is specified by calling the \ref IRtcEngine::joinChannel "joinChannel" method, if the SDK losses connection with the Agora server due to network issues, the token may expire after a certain period of time and a new token may be required to reconnect to the server. - - This callback notifies the application to generate a new token. Call the \ref IRtcEngine::renewToken "renewToken" method to renew the token. - */ - virtual void onRequestToken() { - } - - /** Occurs when the token expires in 30 seconds. - - The user becomes offline if the token used in the \ref IRtcEngine::joinChannel "joinChannel" method expires. The SDK triggers this callback 30 seconds before the token expires to remind the application to get a new token. Upon receiving this callback, generate a new token on the server and call the \ref IRtcEngine::renewToken "renewToken" method to pass the new token to the SDK. - - @param token Pointer to the token that expires in 30 seconds. - */ - virtual void onTokenPrivilegeWillExpire(const char* token) { - (void)token; - } - - /** **DEPRECATED** Reports the statistics of the audio stream from each remote user/host. - - Deprecated as of v2.3.2. Use the \ref agora::rtc::IRtcEngineEventHandler::onRemoteAudioStats "onRemoteAudioStats" callback instead. - - The SDK triggers this callback once every two seconds to report the audio quality of each remote user/host sending an audio stream. If a channel has multiple users/hosts sending audio streams, the SDK triggers this callback as many times. - - @param uid User ID of the speaker. - @param quality Audio quality of the user: #QUALITY_TYPE. - @param delay Time delay (ms) of sending the audio packet from the sender to the receiver, including the time delay of audio sampling pre-processing, transmission, and the jitter buffer. - @param lost Packet loss rate (%) of the audio packet sent from the sender to the receiver. - */ - virtual void onAudioQuality(uid_t uid, int quality, unsigned short delay, unsigned short lost) { - (void)uid; - (void)quality; - (void)delay; - (void)lost; - } - - /** Reports the statistics of the current call session once every two - * seconds. - * - * @param stats Pointer to the RTC engine statistics: RtcStats. - */ - virtual void onRtcStats(const RtcStats& stats) { - (void)stats; - } - - /** Reports the last mile network quality of each user in the channel once every two seconds. - - Last mile refers to the connection between the local device and Agora's edge server. This callback reports once every two seconds the last mile network conditions of each user in the channel. If a channel includes multiple users, the SDK triggers this callback as many times. - - @param uid User ID. The network quality of the user with this @p uid is reported. If @p uid is 0, the local network quality is reported. - @param txQuality Uplink transmission quality rating of the user in terms of the transmission bitrate, packet loss rate, average RTT (Round-Trip Time), and jitter of the uplink network. @p txQuality is a quality rating helping you understand how well the current uplink network conditions can support the selected VideoEncoderConfiguration. For example, a 1000 Kbps uplink network may be adequate for video frames with a resolution of 640 × 480 and a frame rate of 15 fps in the Live-broadcast profile, but may be inadequate for resolutions higher than 1280 × 720. See #QUALITY_TYPE. - @param rxQuality Downlink network quality rating of the user in terms of the packet loss rate, average RTT, and jitter of the downlink network. See #QUALITY_TYPE. - */ - virtual void onNetworkQuality(uid_t uid, int txQuality, int rxQuality) { - (void)uid; - (void)txQuality; - (void)rxQuality; - } - - /** Reports the statistics of the local video streams. - * - * The SDK triggers this callback once every two seconds for each - * user/host. If there are multiple users/hosts in the channel, the SDK - * triggers this callback as many times. - * - * @note - * If you have called the \ref agora::rtc::IRtcEngine::enableDualStream - * "enableDualStream" method, the \ref onLocalVideoStats() - * "onLocalVideoStats" callback reports the statistics of the high-video - * stream (high bitrate, and high-resolution video stream). - * - * @param stats Statistics of the local video stream. See LocalVideoStats. - */ - virtual void onLocalVideoStats(const LocalVideoStats& stats) { - (void)stats; - } - - /** Reports the statistics of the video stream from each remote user/host. - * - * The SDK triggers this callback once every two seconds for each remote - * user/host. If a channel includes multiple remote users, the SDK - * triggers this callback as many times. - * - * @param stats Statistics of the remote video stream. See - * RemoteVideoStats. - */ - virtual void onRemoteVideoStats(const RemoteVideoStats& stats) { - (void)stats; - } - - /** Reports the statistics of the local audio stream. - * - * The SDK triggers this callback once every two seconds. - * - * @param stats The statistics of the local audio stream. - * See LocalAudioStats. - */ - virtual void onLocalAudioStats(const LocalAudioStats& stats) { - (void)stats; - } - - /** Reports the statistics of the audio stream from each remote user/host. - - This callback replaces the \ref agora::rtc::IRtcEngineEventHandler::onAudioQuality "onAudioQuality" callback. - - The SDK triggers this callback once every two seconds for each remote user/host. If a channel includes multiple remote users, the SDK triggers this callback as many times. - - @param stats Pointer to the statistics of the received remote audio streams. See RemoteAudioStats. - */ - virtual void onRemoteAudioStats(const RemoteAudioStats& stats) { - (void)stats; - } - - /** Occurs when the local audio state changes. - * - * This callback indicates the state change of the local audio stream, - * including the state of the audio recording and encoding, and allows - * you to troubleshoot issues when exceptions occur. - * - * @note - * When the state is #LOCAL_AUDIO_STREAM_STATE_FAILED (3), see the `error` - * parameter for details. - * - * @param state State of the local audio. See #LOCAL_AUDIO_STREAM_STATE. - * @param error The error information of the local audio. - * See #LOCAL_AUDIO_STREAM_ERROR. - */ - virtual void onLocalAudioStateChanged(LOCAL_AUDIO_STREAM_STATE state, LOCAL_AUDIO_STREAM_ERROR error) { - (void)state; - (void)error; - } - - /** Occurs when the remote audio state changes. - * - * This callback indicates the state change of the remote audio stream. - * - * @param uid ID of the remote user whose audio state changes. - * @param state State of the remote audio. See #REMOTE_AUDIO_STATE. - * @param reason The reason of the remote audio state change. - * See #REMOTE_AUDIO_STATE_REASON. - * @param elapsed Time elapsed (ms) from the local user calling the - * \ref IRtcEngine::joinChannel "joinChannel" method until the SDK - * triggers this callback. - */ - virtual void onRemoteAudioStateChanged(uid_t uid, REMOTE_AUDIO_STATE state, REMOTE_AUDIO_STATE_REASON reason, int elapsed) { - (void)uid; - (void)state; - (void)reason; - (void)elapsed; - } - - /** Reports which users are speaking and the speakers' volume. - - This callback reports the ID and volume of the loudest speakers at the moment in the channel. - - This callback is disabled by default and can be enabled by the \ref IRtcEngine::enableAudioVolumeIndication "enableAudioVolumeIndication" method. - - The local user has a dedicated *onAudioVolumeIndication* callback; all remote speakers share a separate *onAudioVolumeIndication* callback. - - For the local user's callback, the @p speakers array has @p uid = 0 and @p volume = @p totalVolume. @p speakerNumber = 1 whether or not the local user speaks. - - For the remote speakers' callback, the @p speakers array includes the user ID and volume of the loudest speakers in the channel. - - The audio volume returned in this callback includes the voice volume and audio-mixing volume of the remote user. - - @note - - Calling the \ref agora::rtc::IRtcEngine::muteLocalAudioStream "muteLocalAudioStream" method affects the SDK's behavior: - - If the local user calls the \ref agora::rtc::IRtcEngine::muteLocalAudioStream "muteLocalAudioStream" method, the SDK stops triggering the local user's callback. - - 15 seconds after a remote speaker calls the *muteLocalAudioStream* method, the remote speakers' callback excludes this remote user's information; 15 seconds after all remote users call the *muteLocalAudioStream* method, the SDK stops triggering the remote speakers' callback. - - An empty @p speakers array in the *onAudioVolumeIndication* callback suggests that no remote user is speaking at the moment. - - @param speakers A pointer to AudioVolumeInfo, a struct containing each speaker's user ID and volume information. - @param speakerNumber Total number of speakers. - @param totalVolume Total volume after audio mixing. The value ranges between 0 (lowest volume) and 255 (highest volume). - */ - virtual void onAudioVolumeIndication(const AudioVolumeInfo* speakers, unsigned int speakerNumber, int totalVolume) { - (void)speakers; - (void)speakerNumber; - (void)totalVolume; - } - - /** Reports which user is the loudest speaker. - - If the user enables the audio volume indication by calling the \ref IRtcEngine::enableAudioVolumeIndication "enableAudioVolumeIndication" method, this callback returns the @p uid of the active speaker detected by the audio volume detection module of the SDK. - - @note - - To receive this callback, you need to call the \ref IRtcEngine::enableAudioVolumeIndication "enableAudioVolumeIndication" method. - - This callback returns the user ID of the user with the highest voice volume during a period of time, instead of at the moment. - - @param uid User ID of the active speaker. A @p uid of 0 represents the local user. - */ - virtual void onActiveSpeaker(uid_t uid) { - (void)uid; - } - - /** **DEPRECATED** Occurs when the video stops playing. - - The application can use this callback to change the configuration of the view (for example, displaying other pictures in the view) after the video stops playing. - - Deprecated as of v2.4.1. Use LOCAL_VIDEO_STREAM_STATE_STOPPED(0) in the agora::rtc::IRtcEngineEventHandler::onLocalVideoStateChanged "onLocalVideoStateChanged" callback instead. - */ - virtual void onVideoStopped() {} - - /** Occurs when the engine receives and renders the first local video frame on the video window. - - @param width Width (pixels) of the first local video frame. - @param height Height (pixels) of the first local video frame. - @param elapsed Time elapsed (ms) from the local user calling the \ref IRtcEngine::joinChannel "joinChannel" method until the SDK triggers this callback. - If you call the \ref IRtcEngine::startPreview "startPreview" method before calling the *joinChannel* method, then @p elapsed is the time elapsed from calling the *startPreview* method until the SDK triggers this callback. - */ - virtual void onFirstLocalVideoFrame(int width, int height, int elapsed) { - (void)width; - (void)height; - (void)elapsed; - } - - /** Occurs when the first remote video frame is received and decoded. - * - * @deprecated - * This callback is deprecated and replaced by the - * \ref onRemoteVideoStateChanged() "onRemoteVideoStateChanged" callback - * with the following parameters: - * - #REMOTE_VIDEO_STATE_STARTING (1) - * - #REMOTE_VIDEO_STATE_DECODING (2) - * - * This callback is triggered in either of the following scenarios: - * - * - The remote user joins the channel and sends the video stream. - * - The remote user stops sending the video stream and re-sends it after - * 15 seconds. Reasons for such an interruption include: - * - The remote user leaves the channel. - * - The remote user drops offline. - * - The remote user calls the - * \ref agora::rtc::IRtcEngine::muteLocalVideoStream "muteLocalVideoStream" - * method to stop sending the video stream. - * - The remote user calls the - * \ref agora::rtc::IRtcEngine::disableVideo "disableVideo" method to - * disable video. - * - * The application can configure the user view settings in this callback. - * - * @param uid User ID of the remote user sending the video stream. - * @param width Width (pixels) of the video stream. - * @param height Height (pixels) of the video stream. - * @param elapsed Time elapsed (ms) from the local user calling the - * \ref IRtcEngine::joinChannel "joinChannel" method until the SDK - * triggers this callback. - */ - virtual void onFirstRemoteVideoDecoded(uid_t uid, int width, int height, int elapsed) { - (void)uid; - (void)width; - (void)height; - (void)elapsed; - } - - /** Occurs when the first remote video frame is rendered. - - The SDK triggers this callback when the first frame of the remote video is displayed in the user's video window. The application can retrieve the time elapsed from a user joining the channel until the first video frame is displayed. - - @param uid User ID of the remote user sending the video stream. - @param width Width (pixels) of the video frame. - @param height Height (pixels) of the video stream. - @param elapsed Time elapsed (ms) from the local user calling the \ref IRtcEngine::joinChannel "joinChannel" method until the SDK triggers this callback. - */ - virtual void onFirstRemoteVideoFrame(uid_t uid, int width, int height, int elapsed) { - (void)uid; - (void)width; - (void)height; - (void)elapsed; - } - - /** Occurs when a remote user's audio stream is muted/unmuted. - - The SDK triggers this callback when the remote user stops or resumes sending the audio stream by calling the \ref agora::rtc::IRtcEngine::muteLocalAudioStream "muteLocalAudioStream" method. - @note This callback returns invalid when the number of users in a channel exceeds 20. - - @param uid User ID of the remote user. - @param muted Whether the remote user's audio stream is muted/unmuted: - - true: Muted. - - false: Unmuted. - */ - virtual void onUserMuteAudio(uid_t uid, bool muted) { - (void)uid; - (void)muted; - } - - /** Occurs when a remote user's video stream playback pauses/resumes. - * - * @deprecated - * This callback is deprecated and replaced by the - * \ref onRemoteVideoStateChanged() "onRemoteVideoStateChanged" callback - * with the following parameters: - * - #REMOTE_VIDEO_STATE_STOPPED (0) and - * #REMOTE_VIDEO_STATE_REASON_REMOTE_MUTED (5). - * - #REMOTE_VIDEO_STATE_DECODING (2) and - * #REMOTE_VIDEO_STATE_REASON_REMOTE_UNMUTED (6). - * - * The SDK triggers this callback when the remote user stops or resumes - * sending the video stream by calling the - * \ref agora::rtc::IRtcEngine::muteLocalVideoStream - * "muteLocalVideoStream" method. - * - * @note This callback returns invalid when the number of users in a - * channel exceeds 20. - * - * @param uid User ID of the remote user. - * @param muted Whether the remote user's video stream playback is - * paused/resumed: - * - true: Paused. - * - false: Resumed. - */ - virtual void onUserMuteVideo(uid_t uid, bool muted) { - (void)uid; - (void)muted; - } - - /** Occurs when a specific remote user enables/disables the video - * module. - * - * @deprecated - * This callback is deprecated and replaced by the - * \ref onRemoteVideoStateChanged() "onRemoteVideoStateChanged" callback - * with the following parameters: - * - #REMOTE_VIDEO_STATE_STOPPED (0) and - * #REMOTE_VIDEO_STATE_REASON_REMOTE_MUTED (5). - * - #REMOTE_VIDEO_STATE_DECODING (2) and - * #REMOTE_VIDEO_STATE_REASON_REMOTE_UNMUTED (6). - * - * Once the video module is disabled, the remote user can only use a - * voice call. The remote user cannot send or receive any video from - * other users. - * - * The SDK triggers this callback when the remote user enables or disables - * the video module by calling the - * \ref agora::rtc::IRtcEngine::enableVideo "enableVideo" or - * \ref agora::rtc::IRtcEngine::disableVideo "disableVideo" method. - * - * @note This callback returns invalid when the number of users in a - * channel exceeds 20. - * - * @param uid User ID of the remote user. - * @param enabled Whether the remote user enables/disables the video - * module: - * - true: Enable. The remote user can enter a video session. - * - false: Disable. The remote user can only enter a voice session, and - * cannot send or receive any video stream. - */ - virtual void onUserEnableVideo(uid_t uid, bool enabled) { - (void)uid; - (void)enabled; - } - - /** Occurs when the audio device state changes. - - This callback notifies the application that the system's audio device state is changed. For example, a headset is unplugged from the device. - - @param deviceId Pointer to the device ID. - @param deviceType Device type: #MEDIA_DEVICE_TYPE. - @param deviceState Device state: #MEDIA_DEVICE_STATE_TYPE. - */ - virtual void onAudioDeviceStateChanged(const char* deviceId, int deviceType, int deviceState) { - (void)deviceId; - (void)deviceType; - (void)deviceState; - } - - /** Occurs when the volume of the playback device, microphone, or application changes. - - @param deviceType Device type: #MEDIA_DEVICE_TYPE. - @param volume Volume of the device. The value ranges between 0 and 255. - @param muted - - true: The audio device is muted. - - false: The audio device is not muted. - */ - virtual void onAudioDeviceVolumeChanged(MEDIA_DEVICE_TYPE deviceType, int volume, bool muted) { - (void)deviceType; - (void)volume; - (void)muted; - } - - /** **DEPRECATED** Occurs when the camera turns on and is ready to capture the video. - - If the camera fails to turn on, fix the error reported in the \ref IRtcEngineEventHandler::onError "onError" callback. - - Deprecated as of v2.4.1. Use LOCAL_VIDEO_STREAM_STATE_CAPTURING(1) in the agora::rtc::IRtcEngineEventHandler::onLocalVideoStateChanged "onLocalVideoStateChanged" callback instead. - */ - virtual void onCameraReady() {} - - /** Occurs when the camera focus area changes. - - The SDK triggers this callback when the local user changes the camera focus position by calling the setCameraFocusPositionInPreview method. - @param x x coordinate of the changed camera focus area. - @param y y coordinate of the changed camera focus area. - @param width Width of the changed camera focus area. - @param height Height of the changed camera focus area. - */ - virtual void onCameraFocusAreaChanged(int x, int y, int width, int height) { - (void)x; - (void)y; - (void)width; - (void)height; - } - - /** Occurs when the camera exposure area changes. - - The SDK triggers this callback when the local user changes the camera exposure position by calling the setCameraExposurePosition method. - @param x x coordinate of the changed camera exposure area. - @param y y coordinate of the changed camera exposure area. - @param width Width of the changed camera exposure area. - @param height Height of the changed camera exposure area. - */ - virtual void onCameraExposureAreaChanged(int x, int y, int width, int height) { - (void)x; - (void)y; - (void)width; - (void)height; - } - - /** Occurs when the audio mixing file playback finishes. - - **DEPRECATED** use onAudioMixingStateChanged instead. - - You can start an audio mixing file playback by calling the \ref IRtcEngine::startAudioMixing "startAudioMixing" method. The SDK triggers this callback when the audio mixing file playback finishes. - - If the *startAudioMixing* method call fails, an error code returns in the \ref IRtcEngineEventHandler::onError "onError" callback. - - */ - virtual void onAudioMixingFinished() { - } - - /** Occurs when the state of the local user's audio mixing file changes. - - - When the audio mixing file plays, pauses playing, or stops playing, this callback returns 710, 711, or 713 in @p state, and 0 in @p errorCode. - - When exceptions occur during playback, this callback returns 714 in @p state and an error in @p errorCode. - - If the local audio mixing file does not exist, or if the SDK does not support the file format or cannot access the music file URL, the SDK returns WARN_AUDIO_MIXING_OPEN_ERROR = 701. - - @param state The state code. See #AUDIO_MIXING_STATE_TYPE. - @param errorCode The error code. See #AUDIO_MIXING_ERROR_TYPE. - */ - virtual void onAudioMixingStateChanged(AUDIO_MIXING_STATE_TYPE state, AUDIO_MIXING_ERROR_TYPE errorCode){ - } - /** Occurs when a remote user starts audio mixing. - - When a remote user calls \ref IRtcEngine::startAudioMixing "startAudioMixing" to play the background music, the SDK reports this callback. - */ - virtual void onRemoteAudioMixingBegin() { - } - /** Occurs when a remote user finishes audio mixing. - */ - virtual void onRemoteAudioMixingEnd() { - } - - /** Occurs when the local audio effect playback finishes. - - The SDK triggers this callback when the local audio effect file playback finishes. - - @param soundId ID of the local audio effect. Each local audio effect has a unique ID. - */ - virtual void onAudioEffectFinished(int soundId) { - } - - - /** - Occurs when the SDK decodes the first remote audio frame for playback. - - This callback is triggered in either of the following scenarios: - - - The remote user joins the channel and sends the audio stream. - - The remote user stops sending the audio stream and re-sends it after 15 seconds. Reasons for such an interruption include: - - The remote user leaves channel. - - The remote user drops offline. - - The remote user calls the \ref agora::rtc::IRtcEngine::muteLocalAudioStream "muteLocalAudioStream" method to stop sending the local audio stream. - - The remote user calls the \ref agora::rtc::IRtcEngine::disableAudio "disableAudio" method to disable audio. - - @param uid User ID of the remote user sending the audio stream. - @param elapsed Time elapsed (ms) from the local user calling the \ref IRtcEngine::joinChannel "joinChannel" method until the SDK triggers this callback. - */ - virtual void onFirstRemoteAudioDecoded(uid_t uid, int elapsed) { - (void)uid; - (void)elapsed; - } - - /** Occurs when the video device state changes. - - @note On a Windows device with an external camera for video capturing, the video disables once the external camera is unplugged. - - @param deviceId Pointer to the device ID of the video device that changes state. - @param deviceType Device type: #MEDIA_DEVICE_TYPE. - @param deviceState Device state: #MEDIA_DEVICE_STATE_TYPE. - */ - virtual void onVideoDeviceStateChanged(const char* deviceId, int deviceType, int deviceState) { - (void)deviceId; - (void)deviceType; - (void)deviceState; - } - - /** Occurs when the local video stream state changes. - - @note This callback indicates the state of the local video stream, including camera capturing and video encoding, and allows you to troubleshoot issues when exceptions occur. - - @param localVideoState State type #LOCAL_VIDEO_STREAM_STATE. When the state is LOCAL_VIDEO_STREAM_STATE_FAILED (3), see the *error* parameter for details. - @param error The detailed error information. code #LOCAL_VIDEO_STREAM_ERROR. - */ - virtual void onLocalVideoStateChanged(LOCAL_VIDEO_STREAM_STATE localVideoState, LOCAL_VIDEO_STREAM_ERROR error) { - (void)localVideoState; - (void)error; - } - - /** Occurs when the video size or rotation of a specified user changes. - - @param uid User ID of the remote user or local user (0) whose video size or rotation changes. - @param width New width (pixels) of the video. - @param height New height (pixels) of the video. - @param rotation New rotation of the video [0 to 360). - */ - virtual void onVideoSizeChanged(uid_t uid, int width, int height, int rotation) { - (void)uid; - (void)width; - (void)height; - (void)rotation; - } - /** Occurs when the remote video state changes. - * - * @param uid ID of the remote user whose video state changes. - * @param state State of the remote video. See #REMOTE_VIDEO_STATE. - * @param reason The reason of the remote video state change. See - * #REMOTE_VIDEO_STATE_REASON. - * @param elapsed Time elapsed (ms) from the local user calling the - * \ref agora::rtc::IRtcEngine::joinChannel "joinChannel" method until the - * SDK triggers this callback. - */ - virtual void onRemoteVideoStateChanged(uid_t uid, REMOTE_VIDEO_STATE state, REMOTE_VIDEO_STATE_REASON reason, int elapsed) { - (void)uid; - (void)state; - (void)reason; - (void)elapsed; - } - - /** Occurs when a specified remote user enables/disables the local video - * capturing function. - * - * @deprecated - * This callback is deprecated and replaced by the - * \ref onRemoteVideoStateChanged() "onRemoteVideoStateChanged" callback - * with the following parameters: - * - #REMOTE_VIDEO_STATE_STOPPED (0) and - * #REMOTE_VIDEO_STATE_REASON_REMOTE_MUTED (5). - * - #REMOTE_VIDEO_STATE_DECODING (2) and - * #REMOTE_VIDEO_STATE_REASON_REMOTE_UNMUTED (6). - * - * This callback is only applicable to the scenario when the user only - * wants to watch the remote video without sending any video stream to the - * other user. - * - * The SDK triggers this callback when the remote user resumes or stops - * capturing the video stream by calling the - * \ref agora::rtc::IRtcEngine::enableLocalVideo "enableLocalVideo" method. - * - * @param uid User ID of the remote user. - * @param enabled Whether the specified remote user enables/disables the - * local video capturing function: - * - true: Enable. Other users in the channel can see the video of this - * remote user. - * - false: Disable. Other users in the channel can no longer receive the - * video stream from this remote user, while this remote user can still - * receive the video streams from other users. - */ - virtual void onUserEnableLocalVideo(uid_t uid, bool enabled) { - (void)uid; - (void)enabled; - } - -// virtual void onStreamError(int streamId, int code, int parameter, const char* message, size_t length) {} - /** Occurs when the local user receives the data stream from the remote user within five seconds. - - The SDK triggers this callback when the local user receives the stream message that the remote user sends by calling the \ref agora::rtc::IRtcEngine::sendStreamMessage "sendStreamMessage" method. - @param uid User ID of the remote user sending the message. - @param streamId Stream ID. - @param data Pointer to the data received by the local user. - @param length Length of the data in bytes. - */ - virtual void onStreamMessage(uid_t uid, int streamId, const char* data, size_t length) { - (void)uid; - (void)streamId; - (void)data; - (void)length; - } - - /** Occurs when the local user does not receive the data stream from the remote user within five seconds. - - The SDK triggers this callback when the local user fails to receive the stream message that the remote user sends by calling the \ref agora::rtc::IRtcEngine::sendStreamMessage "sendStreamMessage" method. - @param uid User ID of the remote user sending the message. - @param streamId Stream ID. - @param code Error code: #ERROR_CODE_TYPE. - @param missed Number of lost messages. - @param cached Number of incoming cached messages when the data stream is interrupted. - */ - virtual void onStreamMessageError(uid_t uid, int streamId, int code, int missed, int cached) { - (void)uid; - (void)streamId; - (void)code; - (void)missed; - (void)cached; - } - - /** Occurs when the media engine loads.*/ - virtual void onMediaEngineLoadSuccess() { - } - /** Occurs when the media engine call starts.*/ - virtual void onMediaEngineStartCallSuccess() { - } - - /** Occurs when the state of the media stream relay changes. - * - * The SDK returns the state of the current media relay with any error - * message. - * - * @param state The state code in #CHANNEL_MEDIA_RELAY_STATE. - * @param code The error code in #CHANNEL_MEDIA_RELAY_ERROR. - */ - virtual void onChannelMediaRelayStateChanged(CHANNEL_MEDIA_RELAY_STATE state,CHANNEL_MEDIA_RELAY_ERROR code) { - } - - /** Reports events during the media stream relay. - * - * @param code The event code in #CHANNEL_MEDIA_RELAY_EVENT. - */ - virtual void onChannelMediaRelayEvent(CHANNEL_MEDIA_RELAY_EVENT code) { - } - - /** Occurs when the engine sends the first local audio frame. - - @param elapsed Time elapsed (ms) from the local user calling \ref IRtcEngine::joinChannel "joinChannel" until the SDK triggers this callback. - */ - virtual void onFirstLocalAudioFrame(int elapsed) { - (void)elapsed; - } - - /** Occurs when the engine receives the first audio frame from a specific remote user. - - @param uid User ID of the remote user. - @param elapsed Time elapsed (ms) from the remote user calling \ref IRtcEngine::joinChannel "joinChannel" until the SDK triggers this callback. - */ - virtual void onFirstRemoteAudioFrame(uid_t uid, int elapsed) { - (void)uid; - (void)elapsed; - } - - /** - Occurs when the state of the RTMP streaming changes. - - The SDK triggers this callback to report the result of the local user calling the \ref agora::rtc::IRtcEngine::addPublishStreamUrl "addPublishStreamUrl" or \ref agora::rtc::IRtcEngine::removePublishStreamUrl "removePublishStreamUrl" method. - - This callback indicates the state of the RTMP streaming. When exceptions occur, you can troubleshoot issues by referring to the detailed error descriptions in the *errCode* parameter. - - @param url The RTMP URL address. - @param state The RTMP streaming state. See: #RTMP_STREAM_PUBLISH_STATE. - @param errCode The detailed error information for streaming. See: #RTMP_STREAM_PUBLISH_ERROR. - */ - virtual void onRtmpStreamingStateChanged(const char *url, RTMP_STREAM_PUBLISH_STATE state, RTMP_STREAM_PUBLISH_ERROR errCode) { - (void) url; - (RTMP_STREAM_PUBLISH_STATE) state; - (RTMP_STREAM_PUBLISH_ERROR) errCode; - } - - /** Reports the result of calling the \ref IRtcEngine::addPublishStreamUrl "addPublishStreamUrl" method. (CDN live only.) - - @param url The RTMP URL address. - @param error Error code: #ERROR_CODE_TYPE. Main errors include: - - #ERR_OK (0): The publishing succeeds. - - #ERR_FAILED (1): The publishing fails. - - #ERR_INVALID_ARGUMENT (2): Invalid argument used. If, for example, you did not call \ref agora::rtc::IRtcEngine::setLiveTranscoding "setLiveTranscoding" to configure LiveTranscoding before calling \ref agora::rtc::IRtcEngine::addPublishStreamUrl "addPublishStreamUrl", the SDK reports #ERR_INVALID_ARGUMENT. - - #ERR_TIMEDOUT (10): The publishing timed out. - - #ERR_ALREADY_IN_USE (19): The chosen URL address is already in use for CDN live streaming. - - #ERR_RESOURCE_LIMITED (22): The backend system does not have enough resources for the CDN live streaming. - - #ERR_ENCRYPTED_STREAM_NOT_ALLOWED_PUBLISH (130): You cannot publish an encrypted stream. - - #ERR_PUBLISH_STREAM_CDN_ERROR (151) - - #ERR_PUBLISH_STREAM_NUM_REACH_LIMIT (152) - - #ERR_PUBLISH_STREAM_NOT_AUTHORIZED (153) - - #ERR_PUBLISH_STREAM_INTERNAL_SERVER_ERROR (154) - - #ERR_PUBLISH_STREAM_FORMAT_NOT_SUPPORTED (156) - */ - virtual void onStreamPublished(const char *url, int error) { - (void)url; - (void)error; - } - /** Reports the result of calling the \ref agora::rtc::IRtcEngine::removePublishStreamUrl "removePublishStreamUrl" method. (CDN live only.) - - This callback indicates whether you have successfully removed an RTMP stream from the CDN. - - @param url The RTMP URL address. - */ - virtual void onStreamUnpublished(const char *url) { - (void)url; - } -/** Occurs when the publisher's transcoding is updated. */ - virtual void onTranscodingUpdated() { - } - /** Occurs when a voice or video stream URL address is added to a live broadcast. - - @param url Pointer to the URL address of the externally injected stream. - @param uid User ID. - @param status State of the externally injected stream: #INJECT_STREAM_STATUS. - */ - virtual void onStreamInjectedStatus(const char* url, uid_t uid, int status) { - (void)url; - (void)uid; - (void)status; - } - - /** Occurs when the local audio route changes. - - The SDK triggers this callback when the local audio route switches to an earpiece, speakerphone, headset, or Bluetooth device. - - @note This callback is for Android and iOS only. - - @param routing Audio output routing. See: #AUDIO_ROUTE_TYPE. - */ - virtual void onAudioRouteChanged(AUDIO_ROUTE_TYPE routing) { - (void)routing; - } - - /** Occurs when the locally published media stream falls back to an audio-only stream due to poor network conditions or switches back to the video after the network conditions improve. - - If you call \ref IRtcEngine::setLocalPublishFallbackOption "setLocalPublishFallbackOption" and set *option* as #STREAM_FALLBACK_OPTION_AUDIO_ONLY, the SDK triggers this callback when the locally published stream falls back to audio-only mode due to poor uplink conditions, or when the audio stream switches back to the video after the uplink network condition improves. - - @param isFallbackOrRecover Whether the locally published stream falls back to audio-only or switches back to the video: - - true: The locally published stream falls back to audio-only due to poor network conditions. - - false: The locally published stream switches back to the video after the network conditions improve. - */ - virtual void onLocalPublishFallbackToAudioOnly(bool isFallbackOrRecover) { - (void)isFallbackOrRecover; - } - - /** Occurs when the remote media stream falls back to audio-only stream - * due to poor network conditions or switches back to the video stream - * after the network conditions improve. - * - * If you call - * \ref IRtcEngine::setRemoteSubscribeFallbackOption - * "setRemoteSubscribeFallbackOption" and set - * @p option as #STREAM_FALLBACK_OPTION_AUDIO_ONLY, the SDK triggers this - * callback when the remote media stream falls back to audio-only mode due - * to poor uplink conditions, or when the remote media stream switches - * back to the video after the uplink network condition improves. - * - * @note Once the remote media stream switches to the low stream due to - * poor network conditions, you can monitor the stream switch between a - * high and low stream in the RemoteVideoStats callback. - * - * @param uid ID of the remote user sending the stream. - * @param isFallbackOrRecover Whether the remotely subscribed media stream - * falls back to audio-only or switches back to the video: - * - true: The remotely subscribed media stream falls back to audio-only - * due to poor network conditions. - * - false: The remotely subscribed media stream switches back to the - * video stream after the network conditions improved. - */ - virtual void onRemoteSubscribeFallbackToAudioOnly(uid_t uid, bool isFallbackOrRecover) { - (void)uid; - (void)isFallbackOrRecover; - } - - /** Reports the transport-layer statistics of each remote audio stream. - * - * @deprecated - * This callback is deprecated and replaced by the - * \ref onRemoteAudioStats() "onRemoteAudioStats" callback. - * - * This callback reports the transport-layer statistics, such as the - * packet loss rate and network time delay, once every two seconds after - * the local user receives an audio packet from a remote user. - * - * @param uid User ID of the remote user sending the audio packet. - * @param delay Network time delay (ms) from the remote user sending the - * audio packet to the local user. - * @param lost Packet loss rate (%) of the audio packet sent from the - * remote user. - * @param rxKBitRate Received bitrate (Kbps) of the audio packet sent - * from the remote user. - */ - virtual void onRemoteAudioTransportStats( - uid_t uid, unsigned short delay, unsigned short lost, - unsigned short rxKBitRate) { - (void)uid; - (void)delay; - (void)lost; - (void)rxKBitRate; - } - - /** Reports the transport-layer statistics of each remote video stream. - * - * @deprecated - * This callback is deprecated and replaced by the - * \ref onRemoteVideoStats() "onRemoteVideoStats" callback. - * - * This callback reports the transport-layer statistics, such as the - * packet loss rate and network time delay, once every two seconds after - * the local user receives a video packet from a remote user. - * - * @param uid User ID of the remote user sending the video packet. - * @param delay Network time delay (ms) from the remote user sending the - * video packet to the local user. - * @param lost Packet loss rate (%) of the video packet sent from the - * remote user. - * @param rxKBitRate Received bitrate (Kbps) of the video packet sent - * from the remote user. - */ - virtual void onRemoteVideoTransportStats( - uid_t uid, unsigned short delay, unsigned short lost, - unsigned short rxKBitRate) { - (void)uid; - (void)delay; - (void)lost; - (void)rxKBitRate; - } - - /** **DEPRECATED** Occurs when the microphone is enabled/disabled. - * - * The \ref onMicrophoneEnabled() "onMicrophoneEnabled" callback is - * deprecated. Use #LOCAL_AUDIO_STREAM_STATE_STOPPED (0) or - * #LOCAL_AUDIO_STREAM_STATE_RECORDING (1) in the - * \ref onLocalAudioStateChanged() "onLocalAudioStateChanged" callback - * instead. - * - * The SDK triggers this callback when the local user resumes or stops - * capturing the local audio stream by calling the - * \ref agora::rtc::IRtcEngine::enableLocalAudio "enbaleLocalAudio" method. - * - * @param enabled Whether the microphone is enabled/disabled: - * - true: Enabled. - * - false: Disabled. - */ - virtual void onMicrophoneEnabled(bool enabled) { - (void)enabled; - } - /** Occurs when the connection state between the SDK and the server changes. - - @param state See #CONNECTION_STATE_TYPE. - @param reason See #CONNECTION_CHANGED_REASON_TYPE. - */ - virtual void onConnectionStateChanged( - CONNECTION_STATE_TYPE state, CONNECTION_CHANGED_REASON_TYPE reason) { - (void)state; - (void)reason; - } - - /** Occurs when the local network type changes. - - When the network connection is interrupted, this callback indicates whether the interruption is caused by a network type change or poor network conditions. - - @param type See #NETWORK_TYPE. - */ - virtual void onNetworkTypeChanged(NETWORK_TYPE type) { - (void)type; - } - /** Occurs when the local user successfully registers a user account by calling the \ref agora::rtc::IRtcEngine::registerLocalUserAccount "registerLocalUserAccount" method or joins a channel by calling the \ref agora::rtc::IRtcEngine::joinChannelWithUserAccount "joinChannelWithUserAccount" method.This callback reports the user ID and user account of the local user. - - @param uid The ID of the local user. - @param userAccount The user account of the local user. - */ - virtual void onLocalUserRegistered(uid_t uid, const char* userAccount) { - (void)uid; - (void)userAccount; - } - /** Occurs when the SDK gets the user ID and user account of the remote user. - - After a remote user joins the channel, the SDK gets the UID and user account of the remote user, - caches them in a mapping table object (`userInfo`), and triggers this callback on the local client. - - @param uid The ID of the remote user. - @param info The `UserInfo` object that contains the user ID and user account of the remote user. - */ - virtual void onUserInfoUpdated(uid_t uid, const UserInfo& info) { - (void)uid; - (void)info; - } -}; - -/** -* Video device collection methods. - - The IVideoDeviceCollection interface class retrieves the video device information. -*/ -class IVideoDeviceCollection -{ -protected: - virtual ~IVideoDeviceCollection(){} -public: - /** Retrieves the total number of the indexed video devices in the system. - - @return Total number of the indexed video devices: - */ - virtual int getCount() = 0; - - /** Retrieves a specified piece of information about an indexed video device. - - @param index The specified index of the video device that must be less than the return value of \ref IVideoDeviceCollection::getCount "getCount". - @param deviceName Pointer to the video device name. - @param deviceId Pointer to the video device ID. - @return - - 0: Success. - - < 0: Failure. - */ - virtual int getDevice(int index, char deviceName[MAX_DEVICE_ID_LENGTH], char deviceId[MAX_DEVICE_ID_LENGTH]) = 0; - - /** Sets the device with the device ID. - - @param deviceId Device ID of the device. - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setDevice(const char deviceId[MAX_DEVICE_ID_LENGTH]) = 0; - - /** Releases all IVideoDeviceCollection resources. - */ - virtual void release() = 0; -}; - -/** Video device management methods. - - The IVideoDeviceManager interface class tests the video device interfaces. Instantiate an AVideoDeviceManager class to retrieve an IVideoDeviceManager interface. -*/ -class IVideoDeviceManager -{ -protected: - virtual ~IVideoDeviceManager(){} -public: - - /** Enumerates the video devices. - - This method returns an IVideoDeviceCollection object including all video devices in the system. With the IVideoDeviceCollection object, the application can enumerate the video devices. The application must call the \ref IVideoDeviceCollection::release "release" method to release the returned object after using it. - - @return - - An IVideoDeviceCollection object including all video devices in the system: Success. - - NULL: Failure. - */ - virtual IVideoDeviceCollection* enumerateVideoDevices() = 0; - - /** Starts the video-capture device test. - - This method tests whether the video-capture device works properly. Before calling this method, ensure that you have already called the \ref IRtcEngine::enableVideo "enableVideo" method, and the window handle (*hwnd*) parameter is valid. - - @param hwnd The window handle used to display the screen. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int startDeviceTest(view_t hwnd) = 0; - - /** Stops the video-capture device test. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int stopDeviceTest() = 0; - - /** Sets a device with the device ID. - - @param deviceId Pointer to the video-capture device ID. Call the \ref IVideoDeviceManager::enumerateVideoDevices "enumerateVideoDevices" method to retrieve it. - - @note Plugging or unplugging the device does not change the device ID. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setDevice(const char deviceId[MAX_DEVICE_ID_LENGTH]) = 0; - - /** Retrieves the video-capture device that is in use. - - @param deviceId Pointer to the video-capture device ID. - @return - - 0: Success. - - < 0: Failure. - */ - virtual int getDevice(char deviceId[MAX_DEVICE_ID_LENGTH]) = 0; - - /** Releases all IVideoDeviceManager resources. - */ - virtual void release() = 0; -}; - -/** Audio device collection methods. - -The IAudioDeviceCollection interface class retrieves device-related information. -*/ -class IAudioDeviceCollection -{ -protected: - virtual ~IAudioDeviceCollection(){} -public: - - /** Retrieves the total number of audio playback or audio recording devices. - - @note You must first call the \ref IAudioDeviceManager::enumeratePlaybackDevices "enumeratePlaybackDevices" or \ref IAudioDeviceManager::enumerateRecordingDevices "enumerateRecordingDevices" method before calling this method to return the number of audio playback or audio recording devices. - - @return Number of audio playback or audio recording devices. - */ - virtual int getCount() = 0; - - /** Retrieves a specified piece of information about an indexed audio device. - - @param index The specified index that must be less than the return value of \ref IAudioDeviceCollection::getCount "getCount". - @param deviceName Pointer to the audio device name. - @param deviceId Pointer to the audio device ID. - @return - - 0: Success. - - < 0: Failure. - */ - virtual int getDevice(int index, char deviceName[MAX_DEVICE_ID_LENGTH], char deviceId[MAX_DEVICE_ID_LENGTH]) = 0; - - /** Specifies a device with the device ID. - - @param deviceId Pointer to the device ID of the device. - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setDevice(const char deviceId[MAX_DEVICE_ID_LENGTH]) = 0; - - /** Sets the volume of the application. - - @param volume Application volume. The value ranges between 0 (lowest volume) and 255 (highest volume). - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setApplicationVolume(int volume) = 0; - - /** Retrieves the volume of the application. - - @param volume Pointer to the application volume. The volume value ranges between 0 (lowest volume) and 255 (highest volume). - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int getApplicationVolume(int& volume) = 0; - - /** Mutes the application. - - @param mute Sets whether to mute/unmute the application: - - true: Mute the application. - - false: Unmute the application. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setApplicationMute(bool mute) = 0; - /** Retrieves the mute status of the application. - - @param mute Pointer to whether the application is muted/unmuted. - - true: The application is muted. - - false: The application is not muted. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int isApplicationMute(bool& mute) = 0; - - /** Releases all IAudioDeviceCollection resources. - */ - virtual void release() = 0; -}; -/** Audio device management methods. - - The IAudioDeviceManager interface class allows for audio device interface testing. Instantiate an AAudioDeviceManager class to retrieve the IAudioDeviceManager interface. -*/ -class IAudioDeviceManager -{ -protected: - virtual ~IAudioDeviceManager(){} -public: - - /** Enumerates the audio playback devices. - - This method returns an IAudioDeviceCollection object that includes all audio playback devices in the system. With the IAudioDeviceCollection object, the application can enumerate the audio playback devices. - - @note The application must call the \ref IAudioDeviceCollection::release "release" method to release the returned object after using it. - - @return - - Success: Returns an IAudioDeviceCollection object that includes all audio playback devices in the system. For wireless Bluetooth headset devices with master and slave headsets, the master headset is the playback device. - - Returns NULL: Failure. - */ - virtual IAudioDeviceCollection* enumeratePlaybackDevices() = 0; - - /** Enumerates the audio recording devices. - - This method returns an IAudioDeviceCollection object that includes all audio recording devices in the system. With the IAudioDeviceCollection object, the application can enumerate the audio recording devices. - - @note The application needs to call the \ref IAudioDeviceCollection::release "release" method to release the returned object after using it. - - @return - - Returns an IAudioDeviceCollection object that includes all audio recording devices in the system: Success. - - Returns NULL: Failure. - */ - virtual IAudioDeviceCollection* enumerateRecordingDevices() = 0; - - /** Sets the audio playback device using the device ID. - - @note Plugging or unplugging the audio device does not change the device ID. - - @param deviceId Device ID of the audio playback device, retrieved by calling the \ref IAudioDeviceManager::enumeratePlaybackDevices "enumeratePlaybackDevices" method. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setPlaybackDevice(const char deviceId[MAX_DEVICE_ID_LENGTH]) = 0; - - /** Sets the audio recording device using the device ID. - - @param deviceId Device ID of the audio recording device, retrieved by calling the \ref IAudioDeviceManager::enumerateRecordingDevices "enumerateRecordingDevices" method. - - @note Plugging or unplugging the audio device does not change the device ID. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setRecordingDevice(const char deviceId[MAX_DEVICE_ID_LENGTH]) = 0; - - /** Starts the audio playback device test. - - This method tests if the playback device works properly. In the test, the SDK plays an audio file specified by the user. If the user can hear the audio, the playback device works properly. - - @param testAudioFilePath Pointer to the path of the audio file for the audio playback device test in UTF-8: - - Supported file formats: wav, mp3, m4a, and aac. - - Supported file sample rates: 8000, 16000, 32000, 44100, and 48000 Hz. - - @return - - 0: Success, and you can hear the sound of the specified audio file. - - < 0: Failure. - */ - virtual int startPlaybackDeviceTest(const char* testAudioFilePath) = 0; - - /** Stops the audio playback device test. - - This method stops testing the audio playback device. You must call this method to stop the test after calling the \ref IAudioDeviceManager::startPlaybackDeviceTest "startPlaybackDeviceTest" method. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int stopPlaybackDeviceTest() = 0; - - /** Sets the volume of the audio playback device. - - @param volume Sets the volume of the audio playback device. The value ranges between 0 (lowest volume) and 255 (highest volume). - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setPlaybackDeviceVolume(int volume) = 0; - - /** Retrieves the volume of the audio playback device. - - @param volume Pointer to the audio playback device volume. The volume value ranges between 0 (lowest volume) and 255 (highest volume). - @return - - 0: Success. - - < 0: Failure. - */ - virtual int getPlaybackDeviceVolume(int *volume) = 0; - - /** Sets the volume of the microphone. - - @param volume Sets the volume of the microphone. The value ranges between 0 (lowest volume) and 255 (highest volume). - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setRecordingDeviceVolume(int volume) = 0; - - /** Retrieves the volume of the microphone. - - @param volume Pointer to the microphone volume. The volume value ranges between 0 (lowest volume) and 255 (highest volume). - @return - - 0: Success. - - < 0: Failure. - */ - virtual int getRecordingDeviceVolume(int *volume) = 0; - - /** Mutes the audio playback device. - - @param mute Sets whether to mute/unmute the audio playback device: - - true: Mutes. - - false: Unmutes. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setPlaybackDeviceMute(bool mute) = 0; - /** Retrieves the mute status of the audio playback device. - - @param mute Pointer to whether the audio playback device is muted/unmuted. - - true: Muted. - - false: Unmuted. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int getPlaybackDeviceMute(bool *mute) = 0; - /** Mutes/Unmutes the microphone. - - @param mute Sets whether to mute/unmute the microphone: - - true: Mutes. - - false: Unmutes. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setRecordingDeviceMute(bool mute) = 0; - - /** Retrieves the microphone's mute status. - - @param mute Pointer to whether the microphone is muted/unmuted. - - true: Muted. - - false: Unmuted. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int getRecordingDeviceMute(bool *mute) = 0; - - /** Starts the microphone test. - - This method tests whether the microphone works properly. Once the test starts, the SDK uses the \ref IRtcEngineEventHandler::onAudioVolumeIndication "onAudioVolumeIndication" callback to notify the application with the volume information. - - @param indicationInterval Interval period (ms) of the \ref IRtcEngineEventHandler::onAudioVolumeIndication "onAudioVolumeIndication" callback cycle. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int startRecordingDeviceTest(int indicationInterval) = 0; - - /** Stops the microphone test. - - This method stops the microphone test. You must call this method to stop the test after calling the \ref IAudioDeviceManager::startRecordingDeviceTest "startRecordingDeviceTest" method. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int stopRecordingDeviceTest() = 0; - - /** Retrieves the audio playback device associated with the device ID. - - @param deviceId Pointer to the ID of the audio playback device. - @return - - 0: Success. - - < 0: Failure. - */ - virtual int getPlaybackDevice(char deviceId[MAX_DEVICE_ID_LENGTH]) = 0; - - /** Retrieves the audio playback device information associated with the device ID and device name. - - @param deviceId Pointer to the device ID of the audio playback device. - @param deviceName Pointer to the device name of the audio playback device. - @return - - 0: Success. - - < 0: Failure. - */ - virtual int getPlaybackDeviceInfo(char deviceId[MAX_DEVICE_ID_LENGTH], char deviceName[MAX_DEVICE_ID_LENGTH]) = 0; - - /** Retrieves the audio recording device associated with the device ID. - - @param deviceId Pointer to the device ID of the audio recording device. - @return - - 0: Success. - - < 0: Failure. - */ - virtual int getRecordingDevice(char deviceId[MAX_DEVICE_ID_LENGTH]) = 0; - - /** Retrieves the audio recording device information associated with the device ID and device name. - - @param deviceId Pointer to the device ID of the recording audio device. - @param deviceName Pointer to the device name of the recording audio device. - @return - - 0: Success. - - < 0: Failure. - */ - virtual int getRecordingDeviceInfo(char deviceId[MAX_DEVICE_ID_LENGTH], char deviceName[MAX_DEVICE_ID_LENGTH]) = 0; - - /** Starts the audio device loopback test. - - This method tests whether the local audio devices are working properly. After calling this method, the microphone captures the local audio and plays it through the speaker. The \ref IRtcEngineEventHandler::onAudioVolumeIndication "onAudioVolumeIndication" callback returns the local audio volume information at the set interval. - - @note This method tests the local audio devices and does not report the network conditions. - - @param indicationInterval The time interval (ms) at which the \ref IRtcEngineEventHandler::onAudioVolumeIndication "onAudioVolumeIndication" callback returns. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int startAudioDeviceLoopbackTest(int indicationInterval) = 0; - - /** Stops the audio device loopback test. - - @note Ensure that you call this method to stop the loopback test after calling the \ref IAudioDeviceManager::startAudioDeviceLoopbackTest "startAudioDeviceLoopbackTest" method. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int stopAudioDeviceLoopbackTest() = 0; - - /** Releases all IAudioDeviceManager resources. - */ - virtual void release() = 0; -}; - -/** Definition of RtcEngineContext. -*/ -struct RtcEngineContext -{ - IRtcEngineEventHandler* eventHandler; - /** App ID issued to you by Agora. Apply for a new App ID from Agora if - * it is missing from your kit. - */ - const char* appId; - // For android, it the context(Activity or Application - // for windows,Video hot plug device - void* context; - RtcEngineContext() - /** The IRtcEngineEventHandler object. - */ - :eventHandler(NULL) - /** The App ID issued to your project by Agora. - */ - ,appId(NULL) - /** The video window handle. Once set, this parameter enables you to plug - * or unplug the video devices while they are powered. - */ - ,context(NULL) - {} -}; - -/** Definition of IMetadataObserver -*/ -class IMetadataObserver -{ -public: - /** Metadata type of the observer. - @note We only support video metadata for now. - */ - enum METADATA_TYPE - { - /** -1: the metadata type is unknown. - */ - UNKNOWN_METADATA = -1, - /** 0: the metadata type is video. - */ - VIDEO_METADATA = 0, - }; - - struct Metadata - { - /** The User ID. - - - For the receiver: the ID of the user who sent the metadata. - - For the sender: ignore it. - */ - unsigned int uid; - /** Buffer size of the sent or received Metadata. - */ - unsigned int size; - /** Buffer address of the sent or received Metadata. - */ - unsigned char *buffer; - /** Time statmp of the frame following the metadata. - */ - long long timeStampMs; - }; - - virtual ~IMetadataObserver() {}; - - /** Occurs when the SDK requests the maximum size of the Metadata. - - The metadata includes the following parameters: - - `uid`: ID of the user who sends the metadata. - - `size`: The size of the sent or received metadata. - - `buffer`: The sent or received metadata. - - `timeStampMs`: The timestamp of the metadata. - - The SDK triggers this callback after you successfully call the \ref agora::rtc::IRtcEngine::registerMediaMetadataObserver "registerMediaMetadataObserver" method. You need to specify the maximum size of the metadata in the return value of this callback. - - @return The maximum size of the buffer of the metadata that you want to use. The highest value is 1024 bytes. Ensure that you set the return value. - */ - virtual int getMaxMetadataSize() = 0; - - /** Occurs when the SDK is ready to receive and send metadata. - - @note Ensure that the size of the metadata does not exceed the value set in the \ref agora::rtc::IMetadataObserver::getMaxMetadataSize "getMaxMetadataSize" callback. - - @param metadata The Metadata to be sent. - @return - - true: Send. - - false: Do not send. - */ - virtual bool onReadyToSendMetadata(Metadata &metadata) = 0; - - /** Occurs when the local user receives the metadata. - - @param metadata The received Metadata. - */ - virtual void onMetadataReceived(const Metadata &metadata) = 0; -}; - - -/** IRtcEngine is the base interface class of the Agora SDK that provides the main Agora SDK methods invoked by your application. - -Enable the Agora SDK's communication functionality through the creation of an IRtcEngine object, then call the methods of this object. - */ -class IRtcEngine -{ -protected: - virtual ~IRtcEngine() {} -public: - - /** Initializes the Agora SDK service. - * - * Ensure that you call the - * \ref agora::rtc::IRtcEngine::createAgoraRtcEngine - * "createAgoraRtcEngine" and \ref agora::rtc::IRtcEngine::initialize - * "initialize" methods before calling any other API. - * - * @param context Pointer to the RTC engine context. See RtcEngineContext. - * - * @return - * - 0: Success. - * - < 0: Failure. - */ - virtual int initialize(const RtcEngineContext& context) = 0; - - /** Releases all IRtcEngine resources. - - @param sync - - true: (Synchronous call) The result returns after the IRtcEngine resources are released. The application should not call this method in the SDK generated callbacks. Otherwise, the SDK must wait for the callbacks to return to recover the associated IRtcEngine resources, resulting in a deadlock. The SDK automatically detects the deadlock and converts this method into an asynchronous call, causing the test to take additional time. - - false: (Asynchronous call) The result returns immediately, even when the IRtcEngine resources have not been released. The SDK releases all resources. - - @note Do not immediately uninstall the SDK's dynamic library after the call, or it may cause a crash due to the SDK clean-up thread not quitting. - */ - virtual void release(bool sync=false) = 0; - - /** Sets the channel profile. - - The SDK needs to know the application scenario to set the appropriate channel profile to apply different optimization methods. - - @note - - Users in the same channel must use the same channel profile. - - Before calling this method to set a new channel profile, \ref IRtcEngine::release "release" the current engine and create a new engine using createAgoraRtcEngine() and \ref IRtcEngine::initialize "initialize". - - Call this method before a user \ref IRtcEngine::joinChannel "joins a channel" because you cannot configure the channel profile when the channel is in use. - - In the Communication profile, the Agora SDK supports encoding only in raw data, not in texture. - - @param profile Sets the channel profile. See #CHANNEL_PROFILE_TYPE. - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setChannelProfile(CHANNEL_PROFILE_TYPE profile) = 0; - - /** Sets the role of the user, such as a host or an audience (default), before joining a channel in a live broadcast. - - This method can be used to switch the user role in a live broadcast after the user joins a channel. - - In the Live Broadcast profile, when a user switches user roles after joining a channel, a successful \ref agora::rtc::IRtcEngine::setClientRole "setClientRole" method call triggers the following callbacks: - - The local client: \ref agora::rtc::IRtcEngineEventHandler::onClientRoleChanged "onClientRoleChanged" - - The remote client: \ref agora::rtc::IRtcEngineEventHandler::onUserJoined "onUserJoined" or \ref agora::rtc::IRtcEngineEventHandler::onUserOffline "onUserOffline" (BECOME_AUDIENCE) - - @param role Sets the role of the user. See #CLIENT_ROLE_TYPE. - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setClientRole(CLIENT_ROLE_TYPE role) = 0; - - /** Allows a user to join a channel. - - Users in the same channel can talk to each other, and multiple users in the same channel can start a group chat. Users with different App IDs cannot call each other. - - - You must call the \ref IRtcEngine::leaveChannel "leaveChannel" method to exit the current call before entering another channel. - - A successful \ref agora::rtc::IRtcEngine::joinChannel "joinChannel" method call triggers the following callbacks: - - The local client: \ref agora::rtc::IRtcEngineEventHandler::onJoinChannelSuccess "onJoinChannelSuccess" - - The remote client: \ref agora::rtc::IRtcEngineEventHandler::onUserJoined "onUserJoined" , if the user joining the channel is in the Communication profile, or is a BROADCASTER in the Live Broadcast profile. - - When the connection between the client and Agora's server is interrupted due to poor network conditions, the SDK tries reconnecting to the server. When the local client successfully rejoins the channel, the SDK triggers the \ref agora::rtc::IRtcEngineEventHandler::onRejoinChannelSuccess "onRejoinChannelSuccess" callback on the local client. - - @note A channel does not accept duplicate uids, such as two users with the same @p uid. If you set @p uid as 0, the system automatically assigns a @p uid. If you want to join a channel from different devices, ensure that each device has a different uid. - @warning Ensure that the App ID used for creating the token is the same App ID used by the \ref IRtcEngine::initialize "initialize" method for initializing the RTC engine. Otherwise, the CDN live streaming may fail. - - @param token Pointer to the token generated by the application server. In most circumstances, a static App ID suffices. For added security, use a Channel Key. - - If the user uses a static App ID, *token* is optional and can be set as NULL. - - If the user uses a Channel Key, Agora issues an additional App Certificate for you to generate a user key based on the algorithm and App Certificate for user authentication on the server. - @param channelId Pointer to the unique channel name for the Agora RTC session in the string format smaller than 64 bytes. Supported characters: - - The 26 lowercase English letters: a to z - - The 26 uppercase English letters: A to Z - - The 10 numbers: 0 to 9 - - The space - - "!", "#", "$", "%", "&", "(", ")", "+", "-", ":", ";", "<", "=", ".", ">", "?", "@", "[", "]", "^", "_", " {", "}", "|", "~", "," - @param info (Optional) Pointer to additional information about the channel. This parameter can be set to NULL or contain channel related information. Other users in the channel will not receive this message. - @param uid (Optional) User ID. A 32-bit unsigned integer with a value ranging from 1 to 232-1. The @p uid must be unique. If a @p uid is not assigned (or set to 0), the SDK assigns and returns a @p uid in the \ref IRtcEngineEventHandler::onJoinChannelSuccess "onJoinChannelSuccess" callback. Your application must record and maintain the returned *uid* since the SDK does not do so. - - @return - - 0: Success. - - < 0: Failure. - - #ERR_INVALID_ARGUMENT (-2) - - #ERR_NOT_READY (-3) - - #ERR_REFUSED (-5) - */ - virtual int joinChannel(const char* token, const char* channelId, const char* info, uid_t uid) = 0; - /** Switches to a different channel. - * - * This method allows the audience of a Live-broadcast channel to switch - * to a different channel. - * - * After the user successfully switches to another channel, the - * \ref agora::rtc::IRtcEngineEventHandler::onLeaveChannel "onLeaveChannel" - * and \ref agora::rtc::IRtcEngineEventHandler::onJoinChannelSuccess - * "onJoinChannelSuccess" callbacks are triggered to indicate that the - * user has left the original channel and joined a new one. - * - * @note - * This method applies to the audience role in a Live-broadcast channel - * only. - * - * @param token The token generated at your server: - * - For low-security requirements: You can use the temporary token - * generated in Dashboard. For details, see - * [Get a temporary token](https://docs.agora.io/en/Agora%20Platform/token?platfor%20*%20m=All%20Platforms#get-a-temporary-token). - * - For high-security requirements: Use the token generated at your - * server. For details, see - * [Get a token](https://docs.agora.io/en/Agora%20Platform/token?platfor%20*%20m=All%20Platforms#get-a-token). - * @param channelId Unique channel name for the AgoraRTC session in the - * string format. The string length must be less than 64 bytes. Supported - * character scopes are: - * - The 26 lowercase English letters: a to z. - * - The 26 uppercase English letters: A to Z. - * - The 10 numbers: 0 to 9. - * - The space. - * - "!", "#", "$", "%", "&", "(", ")", "+", "-", ":", ";", "<", "=", ".", - * ">", "?", "@", "[", "]", "^", "_", " {", "}", "|", "~", ",". - * - * @return - * - 0: Success. - * - <0: Failure. - */ - virtual int switchChannel(const char* token, const char* channelId) = 0; - - /** Allows a user to leave a channel, such as hanging up or exiting a call. - - After joining a channel, the user must call the *leaveChannel* method to end the call before joining another channel. - - This method returns 0 if the user leaves the channel and releases all resources related to the call. - - This method call is asynchronous, and the user has not left the channel when the method call returns. Once the user leaves the channel, the SDK triggers the \ref IRtcEngineEventHandler::onLeaveChannel "onLeaveChannel" callback. - - A successful \ref agora::rtc::IRtcEngine::leaveChannel "leaveChannel" method call triggers the following callbacks: - - The local client: \ref agora::rtc::IRtcEngineEventHandler::onLeaveChannel "onLeaveChannel" - - The remote client: \ref agora::rtc::IRtcEngineEventHandler::onUserOffline "onUserOffline" , if the user leaving the channel is in the Communication channel, or is a BROADCASTER in the Live Broadcast profile. - - @note - - If you call the \ref IRtcEngine::release "release" method immediately after the *leaveChannel* method, the *leaveChannel* process interrupts, and the \ref IRtcEngineEventHandler::onLeaveChannel "onLeaveChannel" callback is not triggered. - - If you call the *leaveChannel* method during a CDN live streaming, the SDK triggers the \ref IRtcEngine::removePublishStreamUrl "removePublishStreamUrl" method. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int leaveChannel() = 0; - - /** Gets a new token when the current token expires after a period of time. - - The *token* expires after a period of time once the token schema is enabled when: - - - The SDK triggers the \ref IRtcEngineEventHandler::onTokenPrivilegeWillExpire "onTokenPrivilegeWillExpire" callback, or - - The \ref IRtcEngineEventHandler::onConnectionStateChanged "onConnectionStateChanged" reports CONNECTION_CHANGED_TOKEN_EXPIRED(9). - - The application should call this method to get the new *token*. Failure to do so will result in the SDK disconnecting from the server. - - @param token Pointer to the new token. - @return - - 0: Success. - - < 0: Failure. - */ - virtual int renewToken(const char* token) = 0; - - /** Retrieves the pointer to the device manager object. - - @param iid ID of the interface. - @param inter Pointer to the *DeviceManager* object. - @return - - 0: Success. - - < 0: Failure. - */ - virtual int queryInterface(INTERFACE_ID_TYPE iid, void** inter) = 0; - - /** Registers a user account. - - Once registered, the user account can be used to identify the local user when the user joins the channel. - After the user successfully registers a user account, the SDK triggers the \ref agora::rtc::IRtcEngineEventHandler::onLocalUserRegistered "onLocalUserRegistered" callback on the local client, - reporting the user ID and user account of the local user. - - To join a channel with a user account, you can choose either of the following: - - - Call the \ref agora::rtc::IRtcEngine::registerLocalUserAccount "registerLocalUserAccount" method to create a user account, and then the \ref agora::rtc::IRtcEngine::joinChannelWithUserAccount "joinChannelWithUserAccount" method to join the channel. - - Call the \ref agora::rtc::IRtcEngine::joinChannelWithUserAccount "joinChannelWithUserAccount" method to join the channel. - - The difference between the two is that for the former, the time elapsed between calling the \ref agora::rtc::IRtcEngine::joinChannelWithUserAccount "joinChannelWithUserAccount" method - and joining the channel is shorter than the latter. - - @note - - Ensure that you set the `userAccount` parameter. Otherwise, this method does not take effect. - - Ensure that the value of the `userAccount` parameter is unique in the channel. - - To ensure smooth communication, use the same parameter type to identify the user. For example, if a user joins the channel with a user ID, then ensure all the other users use the user ID too. The same applies to the user account. If a user joins the channel with the Agora Web SDK, ensure that the uid of the user is set to the same parameter type. - - @param appId The App ID of your project. - @param userAccount The user account. The maximum length of this parameter is 255 bytes. Ensure that you set this parameter and do not set it as null. Supported character scopes are: - - The 26 lowercase English letters: a to z. - - The 26 uppercase English letters: A to Z. - - The 10 numbers: 0 to 9. - - The space. - - "!", "#", "$", "%", "&", "(", ")", "+", "-", ":", ";", "<", "=", ".", ">", "?", "@", "[", "]", "^", "_", " {", "}", "|", "~", ",". - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int registerLocalUserAccount( - const char* appId, const char* userAccount) = 0; - /** Joins the channel with a user account. - - After the user successfully joins the channel, the SDK triggers the following callbacks: - - - The local client: \ref agora::rtc::IRtcEngineEventHandler::onLocalUserRegistered "onLocalUserRegistered" and \ref agora::rtc::IRtcEngineEventHandler::onJoinChannelSuccess "onJoinChannelSuccess" . - The remote client: \ref agora::rtc::IRtcEngineEventHandler::onUserJoined "onUserJoined" and \ref agora::rtc::IRtcEngineEventHandler::onUserInfoUpdated "onUserInfoUpdated" , if the user joining the channel is in the Communication profile, or is a BROADCASTER in the Live Broadcast profile. - - @note To ensure smooth communication, use the same parameter type to identify the user. For example, if a user joins the channel with a user ID, then ensure all the other users use the user ID too. The same applies to the user account. - If a user joins the channel with the Agora Web SDK, ensure that the uid of the user is set to the same parameter type. - - @param token The token generated at your server: - - For low-security requirements: You can use the temporary token generated at Dashboard. For details, see [Get a temporary toke](https://docs.agora.io/en/Voice/token?platform=All%20Platforms#get-a-temporary-token). - - For high-security requirements: Set it as the token generated at your server. For details, see [Get a token](https://docs.agora.io/en/Voice/token?platform=All%20Platforms#get-a-token). - @param channelId The channel name. The maximum length of this parameter is 64 bytes. Supported character scopes are: - The 26 lowercase English letters: a to z. - - The 26 uppercase English letters: A to Z. - - The 10 numbers: 0 to 9. - - The space. - - "!", "#", "$", "%", "&", "(", ")", "+", "-", ":", ";", "<", "=", ".", ">", "?", "@", "[", "]", "^", "_", " {", "}", "|", "~", ",". - @param userAccount The user account. The maximum length of this parameter is 255 bytes. Ensure that you set this parameter and do not set it as null. Supported character scopes are: - - The 26 lowercase English letters: a to z. - - The 26 uppercase English letters: A to Z. - - The 10 numbers: 0 to 9. - - The space. - - "!", "#", "$", "%", "&", "(", ")", "+", "-", ":", ";", "<", "=", ".", ">", "?", "@", "[", "]", "^", "_", " {", "}", "|", "~", ",". - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int joinChannelWithUserAccount( - const char* token, const char* channelId, const char* userAccount) = 0; - /** Gets the user information by passing in the user account. - - After a remote user joins the channel, the SDK gets the user ID and user account of the remote user, caches them - in a mapping table object (`userInfo`), and triggers the \ref agora::rtc::IRtcEngineEventHandler::onUserInfoUpdated "onUserInfoUpdated" callback on the local client. - - After receiving the o\ref agora::rtc::IRtcEngineEventHandler::onUserInfoUpdated "onUserInfoUpdated" callback, you can call this method to get the user ID of the - remote user from the `userInfo` object by passing in the user account. - - @param userAccount The user account of the user. Ensure that you set this parameter. - @param[in/out] userInfo A userInfo object that identifies the user: - - Input: A userInfo object. - - Output: A userInfo object that contains the user account and user ID of the user. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int getUserInfoByUserAccount(const char* userAccount, UserInfo* userInfo) = 0; - /** Gets the user information by passing in the user ID. - - After a remote user joins the channel, the SDK gets the user ID and user account of the remote user, - caches them in a mapping table object (`userInfo`), and triggers the \ref agora::rtc::IRtcEngineEventHandler::onUserInfoUpdated "onUserInfoUpdated" callback on the local client. - - After receiving the \ref agora::rtc::IRtcEngineEventHandler::onUserInfoUpdated "onUserInfoUpdated" callback, you can call this method to get the user account of the remote user - from the `userInfo` object by passing in the user ID. - - @param uid The user ID of the remote user. Ensure that you set this parameter. - @param[in/out] userInfo A userInfo object that identifies the user: - - Input: A userInfo object. - - Output: A userInfo object that contains the user account and user ID of the user. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int getUserInfoByUid(uid_t uid, UserInfo* userInfo) = 0; - - /** **DEPRECATED** Starts an audio call test. - - This method is deprecated as of v2.4.0. - - This method starts an audio call test to check whether the audio devices (for example, headset and speaker) and the network connection are working properly. - - To conduct the test: - - - The user speaks and the recording is played back within 10 seconds. - - If the user can hear the recording within 10 seconds, the audio devices and network connection are working properly. - - @note - - After calling this method, always call the \ref IRtcEngine::stopEchoTest "stopEchoTest" method to end the test. Otherwise, the application cannot run the next echo test. - - In the Live-broadcast profile, only the hosts can call this method. If the user switches from the Communication to Live-broadcast profile, the user must call the \ref IRtcEngine::setClientRole "setClientRole" method to change the user role from the audience (default) to the host before calling this method. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int startEchoTest() = 0; - - /** Starts an audio call test. - - This method starts an audio call test to determine whether the audio devices (for example, headset and speaker) and the network connection are working properly. - - In the audio call test, you record your voice. If the recording plays back within the set time interval, the audio devices and the network connection are working properly. - - @note - - Call this method before joining a channel. - - After calling this method, call the \ref IRtcEngine::stopEchoTest "stopEchoTest" method to end the test. Otherwise, the app cannot run the next echo test, or call the \ref IRtcEngine::joinChannel "joinChannel" method. - - In the Live-broadcast profile, only a host can call this method. - @param intervalInSeconds The time interval (s) between when you speak and when the recording plays back. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int startEchoTest(int intervalInSeconds) = 0; - - /** Stops the audio call test. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int stopEchoTest() = 0; - - /** Enables the video module. - - Call this method either before joining a channel or during a call. If this method is called before joining a channel, the call starts in the video mode. If this method is called during an audio call, the audio mode switches to the video mode. To disable the video module, call the \ref IRtcEngine::disableVideo "disableVideo" method. - - A successful \ref agora::rtc::IRtcEngine::enableVideo "enableVideo" method call triggers the \ref agora::rtc::IRtcEngineEventHandler::onUserEnableVideo "onUserEnableVideo" (true) callback on the remote client. - @note - - This method affects the internal engine and can be called after the \ref agora::rtc::IRtcEngine::leaveChannel "leaveChannel" method. - - This method resets the internal engine and takes some time to take effect. We recommend using the following API methods to control the video engine modules separately: - - \ref IRtcEngine::enableLocalVideo "enableLocalVideo": Whether to enable the camera to create the local video stream. - - \ref IRtcEngine::muteLocalVideoStream "muteLocalVideoStream": Whether to publish the local video stream. - - \ref IRtcEngine::muteRemoteVideoStream "muteRemoteVideoStream": Whether to subscribe to and play the remote video stream. - - \ref IRtcEngine::muteAllRemoteVideoStreams "muteAllRemoteVideoStreams": Whether to subscribe to and play all remote video streams. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int enableVideo() = 0; - - /** Disables the video module. - - This method can be called before joining a channel or during a call. If this method is called before joining a channel, the call starts in audio mode. If this method is called during a video call, the video mode switches to the audio mode. To enable the video module, call the \ref IRtcEngine::enableVideo "enableVideo" method. - - A successful \ref agora::rtc::IRtcEngine::disableVideo "disableVideo" method call triggers the \ref agora::rtc::IRtcEngineEventHandler::onUserEnableVideo "onUserEnableVideo" (false) callback on the remote client. - @note - - This method affects the internal engine and can be called after the \ref agora::rtc::IRtcEngine::leaveChannel "leaveChannel" method. - - This method resets the internal engine and takes some time to take effect. We recommend using the following API methods to control the video engine modules separately: - - \ref IRtcEngine::enableLocalVideo "enableLocalVideo": Whether to enable the camera to create the local video stream. - - \ref IRtcEngine::muteLocalVideoStream "muteLocalVideoStream": Whether to publish the local video stream. - - \ref IRtcEngine::muteRemoteVideoStream "muteRemoteVideoStream": Whether to subscribe to and play the remote video stream. - - \ref IRtcEngine::muteAllRemoteVideoStreams "muteAllRemoteVideoStreams": Whether to subscribe to and play all remote video streams. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int disableVideo() = 0; - - /** **DEPRECATED** Sets the video profile. - - This method is deprecated as of v2.3. Use the \ref IRtcEngine::setVideoEncoderConfiguration "setVideoEncoderConfiguration" method instead. - - Each video profile includes a set of parameters, such as the resolution, frame rate, and bitrate. If the camera device does not support the specified resolution, the SDK automatically chooses a suitable camera resolution, keeping the encoder resolution specified by the *setVideoProfile* method. - - @note - - If you do not need to set the video profile after joining the channel, call this method before the \ref IRtcEngine::enableVideo "enableVideo" method to reduce the render time of the first video frame. - - Always set the video profile before calling the \ref IRtcEngine::joinChannel "joinChannel" or \ref IRtcEngine::startPreview "startPreview" method. - - @param profile Sets the video profile. See #VIDEO_PROFILE_TYPE. - @param swapWidthAndHeight Sets whether to swap the width and height of the video stream: - - true: Swap the width and height. - - false: (Default) Do not swap the width and height. - The width and height of the output video are consistent with the set video profile. - @note Since the landscape or portrait mode of the output video can be decided directly by the video profile, We recommend setting *swapWidthAndHeight* to *false* (default). - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setVideoProfile(VIDEO_PROFILE_TYPE profile, bool swapWidthAndHeight) = 0; - - /** Sets the video encoder configuration. - - Each video encoder configuration corresponds to a set of video parameters, including the resolution, frame rate, bitrate, and video orientation. - - The parameters specified in this method are the maximum values under ideal network conditions. If the video engine cannot render the video using the specified parameters due to poor network conditions, the parameters further down the list are considered until a successful configuration is found. - - @note If you do not need to set the video encoder configuration after joining the channel, you can call this method before the \ref IRtcEngine::enableVideo "enableVideo" method to reduce the render time of the first video frame. - - @param config Sets the local video encoder configuration. See VideoEncoderConfiguration. - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setVideoEncoderConfiguration(const VideoEncoderConfiguration& config) = 0; - /** Sets the camera capture configuration. - - For a video call or live broadcast, generally the SDK controls the camera output parameters. When the default camera capturer settings do not meet special requirements or cause performance problems, we recommend using this method to set the camera capturer configuration: - - - If the resolution or frame rate of the captured raw video data are higher than those set by \ref IRtcEngine::setVideoEncoderConfiguration "setVideoEncoderConfiguration", processing video frames requires extra CPU and RAM usage and degrades performance. We recommend setting config as CAPTURER_OUTPUT_PREFERENCE_PERFORMANCE = 1 to avoid such problems. - - If you do not need local video preview or are willing to sacrifice preview quality, we recommend setting config as CAPTURER_OUTPUT_PREFERENCE_PERFORMANCE = 1 to optimize CPU and RAM usage. - - If you want better quality for the local video preview, we recommend setting config as CAPTURER_OUTPUT_PREFERENCE_PREVIEW = 2. - - @note Call this method before enabling the local camera. That said, you can call this method before calling \ref agora::rtc::IRtcEngine::joinChannel "joinChannel", \ref agora::rtc::IRtcEngine::enableVideo "enableVideo", or \ref IRtcEngine::enableLocalVideo "enableLocalVideo", depending on which method you use to turn on your local camera. - - @param config Sets the camera capturer configuration. See CameraCapturerConfiguration. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setCameraCapturerConfiguration(const CameraCapturerConfiguration& config) = 0; - - /** Sets the local video view and configures the video display settings on the local machine. - - The application calls this method to bind each video window (view) of the local video streams and configures the video display settings. Call this method after initialization to configure the local video display settings before joining a channel. The binding is still valid after the user leaves the channel, which means that the window still displays. To unbind the view, set the *view* in VideoCanvas to NULL. - - @param canvas Pointer to the local video view and settings. See VideoCanvas. - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setupLocalVideo(const VideoCanvas& canvas) = 0; - - /** Sets the remote video view. - - This method binds the remote user to the video display window (sets the view for the remote user by the specified uid in VideoCanvas). - - The application specifies the uid of the remote video in this method before the remote user joins the channel. - - If the remote uid is unknown to the application, set it after the application receives the \ref IRtcEngineEventHandler::onUserJoined "onUserJoined" callback. - - If the Video Recording function is enabled, the Video Recording Service joins the channel as a dummy client, causing other clients to also receive the \ref IRtcEngineEventHandler::onUserJoined "onUserJoined" callback. Do not bind the dummy client to the application view because the dummy client does not send any video streams. If your application does not recognize the dummy client, bind the remote user to the view when the SDK triggers the \ref IRtcEngineEventHandler::onFirstRemoteVideoDecoded "onFirstRemoteVideoDecoded" callback. - - To unbind the remote user from the view, set the view in VideoCanvas to NULL. Once the remote user leaves the channel, the SDK unbinds the remote user. - - @param canvas Pointer to the remote video view and settings. See VideoCanvas. - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setupRemoteVideo(const VideoCanvas& canvas) = 0; - - /** Starts the local video preview before joining the channel. - - Before calling this method, you must: - - - Call the \ref IRtcEngine::setupLocalVideo "setupLocalVideo" method to set up the local preview window and configure the attributes. - - Call the \ref IRtcEngine::enableVideo "enableVideo" method to enable video. - - @note Once the startPreview method is called to start the local video preview, if you leave the channel by calling the \ref IRtcEngine::leaveChannel "leaveChannel" method, the local video preview remains until you call the \ref IRtcEngine::stopPreview "stopPreview" method to disable it. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int startPreview() = 0; - - /** Prioritizes a remote user's stream. - - Use this method with the \ref IRtcEngine::setRemoteSubscribeFallbackOption "setRemoteSubscribeFallbackOption" method. If the fallback function is enabled for a subscribed stream, the SDK ensures the high-priority user gets the best possible stream quality. - - @note The Agora SDK supports setting @p userPriority as high for one user only. - - @param uid The ID of the remote user. - @param userPriority Sets the priority of the remote user. See #PRIORITY_TYPE. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setRemoteUserPriority(uid_t uid, PRIORITY_TYPE userPriority) = 0; - - /** Stops the local video preview and disables video. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int stopPreview() = 0; - - /** Enables the audio module. - - The audio mode is enabled by default. - - @note - - This method affects the internal engine and can be called after the \ref agora::rtc::IRtcEngine::leaveChannel "leaveChannel" method. You can call this method either before or after joining a channel. - - This method resets the internal engine and takes some time to take effect. We recommend using the following API methods to control the audio engine modules separately: - - \ref IRtcEngine::enableLocalAudio "enableLocalAudio": Whether to enable the microphone to create the local audio stream. - - \ref IRtcEngine::muteLocalAudioStream "muteLocalAudioStream": Whether to publish the local audio stream. - - \ref IRtcEngine::muteRemoteAudioStream "muteRemoteAudioStream": Whether to subscribe to and play the remote audio stream. - - \ref IRtcEngine::muteAllRemoteAudioStreams "muteAllRemoteAudioStreams": Whether to subscribe to and play all remote audio streams. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int enableAudio() = 0; - - /** Disables/Re-enables the local audio function. - - The audio function is enabled by default. This method disables or re-enables the local audio function, that is, to stop or restart local audio capturing. - - This method does not affect receiving or playing the remote audio streams,and enableLocalAudio(false) is applicable to scenarios where the user wants to receive remote audio streams without sending any audio stream to other users in the channel. - - The SDK triggers the \ref IRtcEngineEventHandler::onMicrophoneEnabled "onMicrophoneEnabled" callback once the local audio function is disabled or enabled. - - @note - - Call this method after the \ref IRtcEngine::joinChannel "joinChannel" method. - - This method is different from the \ref agora::rtc::IRtcEngine::muteLocalAudioStream "muteLocalAudioStream" method: - - - \ref agora::rtc::IRtcEngine::enableLocalAudio "enableLocalAudio": Disables/Re-enables the local audio capturing and processing. - - \ref agora::rtc::IRtcEngine::muteLocalAudioStream "muteLocalAudioStream": Sends/Stops sending the local audio streams. - - @param enabled Sets whether to disable/re-enable the local audio function: - - true: (Default) Re-enable the local audio function, that is, to start the local audio capturing device (for example, the microphone). - - false: Disable the local audio function, that is, to stop local audio capturing. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int enableLocalAudio(bool enabled) = 0; - - /** Disables the audio module. - - @note - - This method affects the internal engine and can be called after the \ref agora::rtc::IRtcEngine::leaveChannel "leaveChannel" method. You can call this method either before or after joining a channel. - - This method resets the internal engine and takes some time to take effect. We recommend using the \ref agora::rtc::IRtcEngine::enableLocalAudio "enableLocalAudio" and \ref agora::rtc::IRtcEngine::muteLocalAudioStream "muteLocalAudioStream" methods to capture, process, and send the local audio streams. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int disableAudio() = 0; - - /** Sets the audio parameters and application scenarios. - - @note - - The *setAudioProfile* method must be called before the \ref IRtcEngine::joinChannel "joinChannel" method. - - In the Communication and Live-broadcast profiles, the bitrate may be different from your settings due to network self-adaptation. - - In scenarios involving music education, we recommend setting profile as #AUDIO_PROFILE_MUSIC_HIGH_QUALITY (4) and scenario as #AUDIO_SCENARIO_GAME_STREAMING (3). - - @param profile Sets the sample rate, bitrate, encoding mode, and the number of channels. See #AUDIO_PROFILE_TYPE. - @param scenario Sets the audio application scenario. See #AUDIO_SCENARIO_TYPE. Under different audio scenarios, the device uses different volume tracks, i.e. either the in-call volume or the media volume. For details, see [What is the difference between the in-call volume and the media volume?](https://docs.agora.io/en/faq/system_volume). - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setAudioProfile(AUDIO_PROFILE_TYPE profile, AUDIO_SCENARIO_TYPE scenario) = 0; - /** Stops/Resumes sending the local audio stream. - - A successful \ref agora::rtc::IRtcEngine::muteLocalAudioStream "muteLocalAudioStream" method call triggers the \ref agora::rtc::IRtcEngineEventHandler::onUserMuteAudio "onUserMuteAudio" callback on the remote client. - @note When @p mute is set as @p true, this method does not disable the microphone, which does not affect any ongoing recording. - - @param mute Sets whether to send/stop sending the local audio stream: - - true: Stops sending the local audio stream. - - false: (Default) Sends the local audio stream. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int muteLocalAudioStream(bool mute) = 0; - /** Stops/Resumes receiving all remote users' audio streams. - - @param mute Sets whether to receive/stop receiving all remote users' audio streams. - - true: Stops receiving all remote users' audio streams. - - false: (Default) Receives all remote users' audio streams. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int muteAllRemoteAudioStreams(bool mute) = 0; - /** Stops/Resumes receiving all remote users' audio streams by default. - - @param mute Sets whether to receive/stop receiving all remote users' audio streams by default: - - true: Stops receiving all remote users' audio streams by default. - - false: (Default) Receives all remote users' audio streams by default. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setDefaultMuteAllRemoteAudioStreams(bool mute) = 0; - /** Stops/Resumes receiving a specified remote user's audio stream. - - @note If you called the \ref agora::rtc::IRtcEngine::muteAllRemoteAudioStreams "muteAllRemoteAudioStreams" method and set @p mute as @p true to stop receiving all remote users' audio streams, call the *muteAllRemoteAudioStreams* method and set @p mute as @p false before calling this method. The *muteAllRemoteAudioStreams* method sets all remote audio streams, while the *muteRemoteAudioStream* method sets a specified remote audio stream. - - @param userId User ID of the specified remote user sending the audio. - @param mute Sets whether to receive/stop receiving a specified remote user's audio stream: - - true: Stops receiving the specified remote user's audio stream. - - false: (Default) Receives the specified remote user's audio stream. - - @return - - 0: Success. - - < 0: Failure. - - */ - virtual int muteRemoteAudioStream(uid_t userId, bool mute) = 0; - /** Stops/Resumes sending the local video stream. - - A successful \ref agora::rtc::IRtcEngine::muteLocalVideoStream "muteLocalVideoStream" method call triggers the \ref agora::rtc::IRtcEngineEventHandler::onUserMuteVideo "onUserMuteVideo" callback on the remote client. - @note When set to *true*, this method does not disable the camera which does not affect the retrieval of the local video streams. This method executes faster than the \ref agora::rtc::IRtcEngine::enableLocalVideo "enableLocalVideo" method which controls the sending of the local video stream. - - @param mute Sets whether to send/stop sending the local video stream: - - true: Stop sending the local video stream. - - false: (Default) Send the local video stream. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int muteLocalVideoStream(bool mute) = 0; - /** Disables/Re-enables the local video. - - This method disables/re-enables the local video and enableLocalVideo(false) is only applicable when the user wants to watch the remote video without sending any video stream to the other user. - - Call this method after calling the \ref agora::rtc::IRtcEngine::enableVideo "enableVideo" method. Otherwise, this method may not work properly. - - After the *enableVideo* method is called, the local video is enabled by default. This method is used to disable/re-enable the local video while the remote video remains unaffected. - - A successful \ref agora::rtc::IRtcEngine::enableLocalVideo "enableLocalVideo" method call triggers the \ref agora::rtc::IRtcEngineEventHandler::onUserEnableLocalVideo "onUserEnableLocalVideo" callback on the remote client. - @note This method affects the internal engine and can be called after the \ref agora::rtc::IRtcEngine::leaveChannel "leaveChannel" method. - - @param enabled Sets whether to disable/re-enable the local video, including the capturer, renderer, and sender: - - true: (Default) Re-enable the local video. - - false: Disable the local video. Once the local video is disabled, the remote users can no longer receive the video stream of this user, while this user can still receive the video streams of the other remote users. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int enableLocalVideo(bool enabled) = 0; - /** Stops/Resumes receiving all remote users' video streams. - - @param mute Sets whether to receive/stop receiving all remote users' video streams: - - true: Stop receiving all remote users' video streams. - - false: (Default) Receive all remote users' video streams. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int muteAllRemoteVideoStreams(bool mute) = 0; - /** Stops/Resumes receiving all remote users' video streams by default. - - @param mute Sets whether to receive/stop receiving all remote users' video streams by default: - - true: Stop receiving all remote users' video streams by default. - - false: (Default) Receive all remote users' video streams by default. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setDefaultMuteAllRemoteVideoStreams(bool mute) = 0; - /** Stops/Resumes receiving a specified remote user's video stream. - - @note If you called the \ref agora::rtc::IRtcEngine::muteAllRemoteVideoStreams "muteAllRemoteVideoStreams" method and set @p mute as @p true to stop receiving all remote video streams, call the *muteAllRemoteVideoStreams* method and set @p mute as @p false before calling this method. - - @param userId User ID of the specified remote user. - @param mute Sets whether to receive/stop receiving the specified remote user's video stream: - - true: Stop receiving the specified remote user's video stream. - - false: (Default) Receive the specified remote user's video stream. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int muteRemoteVideoStream(uid_t userId, bool mute) = 0; - /** Sets the remote user's video stream type received by the local user when the remote user sends dual streams. - - This method allows the application to adjust the corresponding video-stream type based on the size of the video window to reduce the bandwidth and resources. - - - If the remote user enables the dual-stream mode by calling the \ref agora::rtc::IRtcEngine::enableDualStreamMode "enableDualStreamMode" method, the SDK receives the high-stream video by default. - - If the dual-stream mode is not enabled, the SDK receives the high-stream video by default. - - The method result returns in the \ref agora::rtc::IRtcEngineEventHandler::onApiCallExecuted "onApiCallExecuted" callback. The SDK receives the high-stream video by default to reduce the bandwidth. If needed, users may use this method to switch to the low-stream video. - By default, the aspect ratio of the low-stream video is the same as the high-stream video. Once the resolution of the high-stream video is set, the system automatically sets the resolution, frame rate, and bitrate of the low-stream video. - - @param userId ID of the remote user sending the video stream. - @param streamType Sets the video-stream type. See #REMOTE_VIDEO_STREAM_TYPE. - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setRemoteVideoStreamType(uid_t userId, REMOTE_VIDEO_STREAM_TYPE streamType) = 0; - /** Sets the default video-stream type for the video received by the local user when the remote user sends dual streams. - - - If the dual-stream mode is enabled by calling the \ref agora::rtc::IRtcEngine::enableDualStreamMode "enableDualStreamMode" method, the user receives the high-stream video by default. The @p setRemoteDefaultVideoStreamType method allows the application to adjust the corresponding video-stream type according to the size of the video window, reducing the bandwidth and resources. - - If the dual-stream mode is not enabled, the user receives the high-stream video by default. - - The result after calling this method is returned in the \ref agora::rtc::IRtcEngineEventHandler::onApiCallExecuted "onApiCallExecuted" callback. The Agora SDK receives the high-stream video by default to reduce the bandwidth. If needed, users can switch to the low-stream video through this method. - - @param streamType Sets the default video-stream type. See #REMOTE_VIDEO_STREAM_TYPE. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setRemoteDefaultVideoStreamType(REMOTE_VIDEO_STREAM_TYPE streamType) = 0; - - /** Enables the \ref agora::rtc::IRtcEngineEventHandler::onAudioVolumeIndication "onAudioVolumeIndication" callback at a set time interval to report on which users are speaking and the speakers' volume. - - Once this method is enabled, the SDK returns the volume indication in the \ref agora::rtc::IRtcEngineEventHandler::onAudioVolumeIndication "onAudioVolumeIndication" callback at the set time interval, whether or not any user is speaking in the channel. - - @param interval Sets the time interval between two consecutive volume indications: - - ≤ 0: Disables the volume indication. - - > 0: Time interval (ms) between two consecutive volume indications. We recommend setting @p interval > 200 ms. Do not set @p interval < 10 ms, or the *onAudioVolumeIndication* callback will not be triggered. - @param smooth Smoothing factor sets the sensitivity of the audio volume indicator. The value ranges between 0 and 10. The greater the value, the more sensitive the indicator. The recommended value is 3. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int enableAudioVolumeIndication(int interval, int smooth) = 0; - /** Starts an audio recording. - - The SDK allows recording during a call. Supported formats: - - - .wav: Large file size with high fidelity. - - .aac: Small file size with low fidelity. - - Ensure that the directory to save the recording file exists and is writable. - This method is usually called after the \ref agora::rtc::IRtcEngine::joinChannel "joinChannel" method. - The recording automatically stops when the \ref agora::rtc::IRtcEngine::leaveChannel "leaveChannel" method is called. - - @param filePath Pointer to the absolute file path of the recording file. The string of the file name is in UTF-8. - @param quality Sets the audio recording quality. See #AUDIO_RECORDING_QUALITY_TYPE. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int startAudioRecording(const char* filePath, AUDIO_RECORDING_QUALITY_TYPE quality) = 0; - /** Stops an audio recording on the client. - - You can call this method before calling the \ref agora::rtc::IRtcEngine::leaveChannel "leaveChannel" method else, the recording automatically stops when the \ref agora::rtc::IRtcEngine::leaveChannel "leaveChannel" method is called. - - @return - - 0: Success - - < 0: Failure. - */ - virtual int stopAudioRecording() = 0; - /** Starts playing and mixing the music file. - - This method mixes the specified local audio file with the audio stream from the microphone, or replaces the microphone's audio stream with the specified local audio file. You can choose whether the other user can hear the local audio playback and specify the number of playback loops. This method also supports online music playback. - - When the audio mixing file playback finishes after calling this method, the SDK triggers the \ref agora::rtc::IRtcEngineEventHandler::onAudioMixingFinished "onAudioMixingFinished" callback. - - A successful \ref agora::rtc::IRtcEngine::startAudioMixing "startAudioMixing" method call triggers the \ref agora::rtc::IRtcEngineEventHandler::onAudioMixingStateChanged "onAudioMixingStateChanged" (PLAY) callback on the local client. - - When the audio mixing file playback finishes, the SDK triggers the \ref agora::rtc::IRtcEngineEventHandler::onAudioMixingStateChanged "onAudioMixingStateChanged" (STOPPED) callback on the local client. - @note - - Call this method when you are in a channel. - - If the local audio mixing file does not exist, or if the SDK does not support the file format or cannot access the music file URL, the SDK returns WARN_AUDIO_MIXING_OPEN_ERROR = 701. - - @param filePath Pointer to the absolute path of the local or online audio file to mix. Supported audio formats: 3GP, ASF, ADTS, AVI, MP3, MPEG-4, SAMI, and WAVE. For more information, see [Supported Media Formats in Media Foundation](https://docs.microsoft.com/en-us/windows/desktop/medfound/supported-media-formats-in-media-foundation). - @param loopback Sets which user can hear the audio mixing: - - true: Only the local user can hear the audio mixing. - - false: Both users can hear the audio mixing. - @param replace Sets the audio mixing content: - - true: Only the specified audio file is published; the audio stream received by the microphone is not published. - - false: The local audio file is mixed with the audio stream from the microphone. - @param cycle Sets the number of playback loops: - - Positive integer: Number of playback loops. - - -1: Infinite playback loops. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int startAudioMixing(const char* filePath, bool loopback, bool replace, int cycle) = 0; - /** Stops playing and mixing the music file. - - Call this method when you are in a channel. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int stopAudioMixing() = 0; - /** Pauses playing and mixing the music file. - - Call this method when you are in a channel. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int pauseAudioMixing() = 0; - /** Resumes playing and mixing the music file. - - Call this method when you are in a channel. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int resumeAudioMixing() = 0; - /** Adjusts the volume during audio mixing. - - Call this method when you are in a channel. - - @param volume Audio mixing volume. The value ranges between 0 and 100 (default). - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int adjustAudioMixingVolume(int volume) = 0; - /** Adjusts the audio mixing volume for local playback. - - @note Call this method when you are in a channel. - - @param volume Audio mixing volume for local playback. The value ranges between 0 and 100 (default). - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int adjustAudioMixingPlayoutVolume(int volume) = 0; - /** Retrieves the audio mixing volume for local playback. - - This method helps troubleshoot audio volume related issues. - - @note Call this method when you are in a channel. - - @return - - ≥ 0: The audio mixing volume, if this method call succeeds. The value range is [0,100]. - - < 0: Failure. - */ - virtual int getAudioMixingPlayoutVolume() = 0; - /** Adjusts the audio mixing volume for publishing (for remote users). - - @note Call this method when you are in a channel. - - @param volume Audio mixing volume for publishing. The value ranges between 0 and 100 (default). - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int adjustAudioMixingPublishVolume(int volume) = 0; - /** Retrieves the audio mixing volume for publishing. - - This method helps troubleshoot audio volume related issues. - - @note Call this method when you are in a channel. - - @return - - ≥ 0: The audio mixing volume for publishing, if this method call succeeds. The value range is [0,100]. - - < 0: Failure. - */ - virtual int getAudioMixingPublishVolume() = 0; - - /** Retrieves the duration (ms) of the music file. - - Call this method when you are in a channel. - - @return - - ≥ 0: The audio mixing duration, if this method call succeeds. - - < 0: Failure. - */ - virtual int getAudioMixingDuration() = 0; - /** Retrieves the playback position (ms) of the music file. - - Call this method when you are in a channel. - - @return - - ≥ 0: The current playback position of the audio mixing, if this method call succeeds. - - < 0: Failure. - */ - virtual int getAudioMixingCurrentPosition() = 0; - /** Sets the playback position of the music file to a different starting position (the default plays from the beginning). - - @param pos The playback starting position (ms) of the music file. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setAudioMixingPosition(int pos /*in ms*/) = 0; - /** Retrieves the volume of the audio effects. - - The value ranges between 0.0 and 100.0. - - @return - - ≥ 0: Volume of the audio effects, if this method call succeeds. - - - < 0: Failure. - */ - virtual int getEffectsVolume() = 0; - /** Sets the volume of the audio effects. - - @param volume Sets the volume of the audio effects. The value ranges between 0 and 100 (default). - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setEffectsVolume(int volume) = 0; - /** Sets the volume of a specified audio effect. - - @param soundId ID of the audio effect. Each audio effect has a unique ID. - @param volume Sets the volume of the specified audio effect. The value ranges between 0 and 100 (default). - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setVolumeOfEffect(int soundId, int volume) = 0; - - /** Plays a specified local or online audio effect file. - - This method allows you to set the loop count, pitch, pan, and gain of the audio effect file, as well as whether the remote user can hear the audio effect. - - To play multiple audio effect files simultaneously, call this method multiple times with different soundIds and filePaths. We recommend playing no more than three audio effect files at the same time. - - @param soundId ID of the specified audio effect. Each audio effect has a unique ID. - - @note - - If the audio effect is preloaded into the memory through the \ref IRtcEngine::preloadEffect "preloadEffect" method, the value of @p soundID must be the same as that in the *preloadEffect* method. - - Playing multiple online audio effect files simultaneously is not supported on macOS and Windows. - - @param filePath The absolute path to the local audio effect file or the URL of the online audio effect file. - @param loopCount Sets the number of times the audio effect loops: - - 0: Play the audio effect once. - - 1: Play the audio effect twice. - - -1: Play the audio effect in an indefinite loop until the \ref IRtcEngine::stopEffect "stopEffect" or \ref IRtcEngine::stopAllEffects "stopAllEffects" method is called. - @param pitch Sets the pitch of the audio effect. The value ranges between 0.5 and 2. The default value is 1 (no change to the pitch). The lower the value, the lower the pitch. - @param pan Sets the spatial position of the audio effect. The value ranges between -1.0 and 1.0: - - 0.0: The audio effect displays ahead. - - 1.0: The audio effect displays to the right. - - -1.0: The audio effect displays to the left. - @param gain Sets the volume of the audio effect. The value ranges between 0 and 100 (default). The lower the value, the lower the volume of the audio effect. - @param publish Sets whether or not to publish the specified audio effect to the remote stream: - - true: The locally played audio effect is published to the Agora Cloud and the remote users can hear it. - - false: The locally played audio effect is not published to the Agora Cloud and the remote users cannot hear it. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int playEffect(int soundId, const char* filePath, int loopCount, double pitch, double pan, int gain, bool publish = false) = 0; - /** Stops playing a specified audio effect. - - @param soundId ID of the audio effect to stop playing. Each audio effect has a unique ID. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int stopEffect(int soundId) = 0; - /** Stops playing all audio effects. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int stopAllEffects() = 0; - - /** Preloads a specified audio effect file into the memory. - - @note This method does not support online audio effect files. - - To ensure smooth communication, limit the size of the audio effect file. We recommend using this method to preload the audio effect before calling the \ref IRtcEngine::joinChannel "joinChannel" method. - - Supported audio formats: mp3, aac, m4a, 3gp, and wav. - - @param soundId ID of the audio effect. Each audio effect has a unique ID. - @param filePath Pointer to the absolute path of the audio effect file. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int preloadEffect(int soundId, const char* filePath) = 0; - /** Releases a specified preloaded audio effect from the memory. - - @param soundId ID of the audio effect. Each audio effect has a unique ID. - @return - - 0: Success. - - < 0: Failure. - */ - virtual int unloadEffect(int soundId) = 0; - /** Pauses a specified audio effect. - - @param soundId ID of the audio effect. Each audio effect has a unique ID. - @return - - 0: Success. - - < 0: Failure. - */ - virtual int pauseEffect(int soundId) = 0; - /** Pauses all audio effects. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int pauseAllEffects() = 0; - /** Resumes playing a specified audio effect. - - @param soundId ID of the audio effect. Each audio effect has a unique ID. - @return - - 0: Success. - - < 0: Failure. - */ - virtual int resumeEffect(int soundId) = 0; - /** Resumes playing all audio effects. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int resumeAllEffects() = 0; - /** Enables/Disables stereo panning for remote users. - - Ensure that you call this method before joinChannel to enable stereo panning for remote users so that the local user can track the position of a remote user by calling \ref agora::rtc::IRtcEngine::setRemoteVoicePosition "setRemoteVoicePosition". - - @param enabled Sets whether or not to enable stereo panning for remote users: - - true: enables stereo panning. - - false: disables stereo panning. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int enableSoundPositionIndication(bool enabled) = 0; - /** Sets the sound position and gain of a remote user. - - When the local user calls this method to set the sound position of a remote user, the sound difference between the left and right channels allows the local user to track the real-time position of the remote user, creating a real sense of space. This method applies to massively multiplayer online games, such as Battle Royale games. - - @note - - For this method to work, enable stereo panning for remote users by calling the \ref agora::rtc::IRtcEngine::enableSoundPositionIndication "enableSoundPositionIndication" method before joining a channel. - - This method requires hardware support. For the best sound positioning, we recommend using a stereo speaker. - - @param uid The ID of the remote user. - @param pan The sound position of the remote user. The value ranges from -1.0 to 1.0: - - 0.0: the remote sound comes from the front. - - -1.0: the remote sound comes from the left. - - 1.0: the remote sound comes from the right. - @param gain Gain of the remote user. The value ranges from 0.0 to 100.0. The default value is 100.0 (the original gain of the remote user). The smaller the value, the less the gain. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setRemoteVoicePosition(int uid, double pan, double gain) = 0; - - /** Changes the voice pitch of the local speaker. - - @param pitch Sets the voice pitch. The value ranges between 0.5 and 2.0. The lower the value, the lower the voice pitch. The default value is 1.0 (no change to the local voice pitch). - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setLocalVoicePitch(double pitch) = 0; - /** Sets the local voice equalization effect. - - @param bandFrequency Sets the band frequency. The value ranges between 0 and 9, representing the respective 10-band center frequencies of the voice effects, including 31, 62, 125, 500, 1k, 2k, 4k, 8k, and 16k Hz. See #AUDIO_EQUALIZATION_BAND_FREQUENCY. - @param bandGain Sets the gain of each band in dB. The value ranges between -15 and 15. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setLocalVoiceEqualization(AUDIO_EQUALIZATION_BAND_FREQUENCY bandFrequency, int bandGain) = 0; - /** Sets the local voice reverberation. - - v2.4.0 adds the \ref agora::rtc::IRtcEngine::setLocalVoiceReverbPreset "setLocalVoiceReverbPreset" method, a more user-friendly method for setting the local voice reverberation. You can use this method to set the local reverberation effect, such as pop music, R&B, rock music, and hip-hop. - - @param reverbKey Sets the reverberation key. See #AUDIO_REVERB_TYPE. - @param value Sets the value of the reverberation key. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setLocalVoiceReverb(AUDIO_REVERB_TYPE reverbKey, int value) = 0; - /** Sets the local voice changer option. - - @note Do not use this method together with the \ref agora::rtc::IRtcEngine::setLocalVoiceReverbPreset "setLocalVoiceReverbPreset" method, because the method called later overrides the one called earlier. - - @param voiceChanger Sets the local voice changer option. See #VOICE_CHANGER_PRESET. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setLocalVoiceChanger(VOICE_CHANGER_PRESET voiceChanger) = 0; - /** Sets the preset local voice reverberation effect. - - @note - - Do not use this method together with \ref agora::rtc::IRtcEngine::setLocalVoiceReverb "setLocalVoiceReverb". - - Do not use this method together with the \ref agora::rtc::IRtcEngine::setLocalVoiceChanger "setLocalVoiceChanger" method, because the method called later overrides the one called earlier. - - @param reverbPreset Sets the preset audio reverberation configuration. See #AUDIO_REVERB_PRESET. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setLocalVoiceReverbPreset(AUDIO_REVERB_PRESET reverbPreset) = 0; - - /** Specifies an SDK output log file. - - The log file records all SDK operations during runtime. If it does not exist, the SDK creates one. - - @note - - The default log file is located at: C:\Users\\AppData\Local\Agora\. - - Ensure that you call this method immediately after calling the \ref agora::rtc::IRtcEngine::initialize "initialize" method, otherwise the output log may not be complete. - - @param filePath File path of the log file. The string of the log file is in UTF-8. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setLogFile(const char* filePath) = 0; - /** Sets the output log level of the SDK. - - You can use one or a combination of the log filter levels. The log level follows the sequence of OFF, CRITICAL, ERROR, WARNING, INFO, and DEBUG. Choose a level to see the logs preceding that level. - - If you set the log level to WARNING, you see the logs within levels CRITICAL, ERROR, and WARNING. - - @param filter Sets the log filter level. See #LOG_FILTER_TYPE. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setLogFilter(unsigned int filter) = 0; - /** Sets the log file size (KB). - - The SDK has two log files, each with a default size of 512 KB. If you set @p fileSizeInBytes as 1024 KB, the SDK outputs log files with a total maximum size of 2 MB. If the total size of the log files exceed the set value, the new output log files overwrite the old output log files. - - @param fileSizeInKBytes The SDK log file size (KB). - @return - - 0: Success. - - <0: Failure. - */ - virtual int setLogFileSize(unsigned int fileSizeInKBytes) = 0; - /** Sets the local video display mode. - - This method can be called multiple times during a call to change the display mode. - - @param renderMode Sets the local video display mode. See #RENDER_MODE_TYPE. - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setLocalRenderMode(RENDER_MODE_TYPE renderMode) = 0; - /** Sets the video display mode of a specified remote user. - - This method can be called multiple times during a call to change the display mode. - - @param userId ID of the remote user. - @param renderMode Sets the video display mode. See #RENDER_MODE_TYPE. - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setRemoteRenderMode(uid_t userId, RENDER_MODE_TYPE renderMode) = 0; - /** Sets the local video mirror mode. - - You must call this method before calling the \ref agora::rtc::IRtcEngine::startPreview "startPreview" method, otherwise the mirror mode will not work. - - @param mirrorMode Sets the local video mirror mode. See #VIDEO_MIRROR_MODE_TYPE. - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setLocalVideoMirrorMode(VIDEO_MIRROR_MODE_TYPE mirrorMode) = 0; - /** Sets the stream mode to the single-stream (default) or dual-stream mode. (Live broadcast only.) - - If the dual-stream mode is enabled, the receiver can choose to receive the high stream (high-resolution and high-bitrate video stream), or the low stream (low-resolution and low-bitrate video stream). - - @param enabled Sets the stream mode: - - true: Dual-stream mode. - - false: (Default) Single-stream mode. - */ - virtual int enableDualStreamMode(bool enabled) = 0; - /** Sets the external audio source. Please call this method before \ref agora::rtc::IRtcEngine::joinChannel "joinChannel". - - @param enabled Sets whether to enable/disable the external audio source: - - true: Enables the external audio source. - - false: (Default) Disables the external audio source. - @param sampleRate Sets the sample rate of the external audio source, which can be set as 8000, 16000, 32000, 44100, or 48000 Hz. - @param channels Sets the audio channels of the external audio source (two channels maximum). - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setExternalAudioSource(bool enabled, int sampleRate, int channels) = 0; - /** Sets the external audio sink. - * This method applies to scenarios where you want to use external audio - * data for playback. After enabling the external audio sink, you can call - * the \ref agora::media::IMediaEngine::pullAudioFrame "pullAudioFrame" method to pull the remote audio data, process - * it, and play it with the audio effects that you want. - * - * @note - * Once you enable the external audio sink, the app will not retrieve any - * audio data from the - * \ref agora::media::IAudioFrameObserver::onPlaybackAudioFrame "onPlaybackAudioFrame" callback. - * - * @param enabled - * - true: Enables the external audio sink. - * - false: (Default) Disables the external audio sink. - * @param sampleRate Sets the sample rate of the external audio sink. You - * can set this parameter as 8000, 16000, 32000, 44100 or 48000. - * @param channels Sets the number of audio channels of the external - * audio sink: - * - 1: Mono. - * - 2: Stereo. - * - * @return - * - 0: Success. - * - < 0: Failure. - */ - virtual int setExternalAudioSink(bool enabled, int sampleRate, int channels) = 0; - /** Sets the audio recording format for the \ref agora::media::IAudioFrameObserver::onRecordAudioFrame "onRecordAudioFrame" callback. - - @param sampleRate Sets the sample rate (@p samplesPerSec) returned in the *onRecordAudioFrame* callback, which can be set as 8000, 16000, 32000, 44100, or 48000 Hz. - @param channel Sets the number of audio channels (@p channels) returned in the *onRecordAudioFrame* callback: - - 1: Mono - - 2: Stereo - @param mode Sets the use mode (see #RAW_AUDIO_FRAME_OP_MODE_TYPE) of the *onRecordAudioFrame* callback. - @param samplesPerCall Sets the sample points (@p samples) returned in the *onRecordAudioFrame* callback. @p samplesPerCall is usually set as 1024 for stream pushing. - - samplesPerCall = (int)(samplesPerSec × sampleInterval × numChannels), where sampleInterval ≥ 0.01 in seconds. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setRecordingAudioFrameParameters(int sampleRate, int channel, RAW_AUDIO_FRAME_OP_MODE_TYPE mode, int samplesPerCall) = 0; - /** Sets the audio playback format for the \ref agora::media::IAudioFrameObserver::onPlaybackAudioFrame "onPlaybackAudioFrame" callback. - - @param sampleRate Sets the sample rate (@p samplesPerSec) returned in the *onPlaybackAudioFrame* callback, which can be set as 8000, 16000, 32000, 44100, or 48000 Hz. - @param channel Sets the number of channels (@p channels) returned in the *onPlaybackAudioFrame* callback: - - 1: Mono - - 2: Stereo - @param mode Sets the use mode (see #RAW_AUDIO_FRAME_OP_MODE_TYPE) of the *onPlaybackAudioFrame* callback. - @param samplesPerCall Sets the sample points (*samples*) returned in the *onPlaybackAudioFrame* callback. @p samplesPerCall is usually set as 1024 for stream pushing. - - samplesPerCall = (int)(samplesPerSec × sampleInterval × numChannels), where sampleInterval ≥ 0.01 in seconds. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setPlaybackAudioFrameParameters(int sampleRate, int channel, RAW_AUDIO_FRAME_OP_MODE_TYPE mode, int samplesPerCall) = 0; - /** Sets the mixed audio format for the \ref agora::media::IAudioFrameObserver::onMixedAudioFrame "onMixedAudioFrame" callback. - - @param sampleRate Sets the sample rate (@p samplesPerSec) returned in the *onMixedAudioFrame* callback, which can be set as 8000, 16000, 32000, 44100, or 48000 Hz. - @param samplesPerCall Sets the sample points (@p samples) returned in the *onMixedAudioFrame* callback. @p samplesPerCall is usually set as 1024 for stream pushing. - - samplesPerCall = (int)(samplesPerSec × sampleInterval × numChannels), where sampleInterval ≥ 0.01 in seconds. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setMixedAudioFrameParameters(int sampleRate, int samplesPerCall) = 0; - /** Adjusts the recording volume. - - @param volume Recording volume. The value ranges between 0 and 400: - - 0: Mute. - - 100: Original volume. - - 400: (Maximum) Four times the original volume with signal clipping protection. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int adjustRecordingSignalVolume(int volume) = 0; - /** Adjusts the playback volume. - - @param volume Playback volume. The value ranges between 0 and 400: - - 0: Mute. - - 100: Original volume. - - 400: (Maximum) Four times the original volume with signal clipping protection. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int adjustPlaybackSignalVolume(int volume) = 0; - - /** Enables interoperability with the Agora Web SDK. - - @note This method applies only to the Live-broadcast profile. In the Communication profile, interoperability with the Agora Web SDK is enabled by default. - - @param enabled Sets whether to enable/disable interoperability with the Agora Web SDK: - - true: Enable. - - false: (Default) Disable. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int enableWebSdkInteroperability(bool enabled) = 0; - /** Sets the fallback option for the locally published video stream based on the network conditions. - - The default setting for @p option is #STREAM_FALLBACK_OPTION_DISABLED, where there is no fallback behavior for the locally published video stream when the uplink network conditions are poor. - - If *option* is set as #STREAM_FALLBACK_OPTION_AUDIO_ONLY, the SDK will: - - - Disable the upstream video but enable audio only when the network conditions worsen and cannot support both video and audio. - - Re-enable the video when the network conditions improve. - - When the locally published video stream falls back to audio only or when the audio-only stream switches back to the video, the SDK triggers the \ref agora::rtc::IRtcEngineEventHandler::onLocalPublishFallbackToAudioOnly "onLocalPublishFallbackToAudioOnly" callback. - - @note Agora does not recommend using this method for CDN live streaming, because the remote CDN live user will have a noticeable lag when the locally publish stream falls back to audio-only. - - @param option Sets the fallback option for the locally published video stream. See #STREAM_FALLBACK_OPTIONS. - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setLocalPublishFallbackOption(STREAM_FALLBACK_OPTIONS option) = 0; - /** Sets the fallback option for the remotely subscribed video stream based on the network conditions. - - The default setting for @p option is #STREAM_FALLBACK_OPTION_VIDEO_STREAM_LOW, where the remotely subscribed video stream falls back to the low-stream video (low resolution and low bitrate) under poor downlink network conditions. - - If *option* is set as #STREAM_FALLBACK_OPTION_AUDIO_ONLY, the SDK automatically switches the video from a high-stream to a low-stream, or disables the video when the downlink network conditions cannot support both audio and video to guarantee the quality of the audio. The SDK monitors the network quality and restores the video stream when the network conditions improve. - - When the remotely subscribed video stream falls back to audio only or when the audio-only stream switches back to the video stream, the SDK triggers the \ref agora::rtc::IRtcEngineEventHandler::onRemoteSubscribeFallbackToAudioOnly "onRemoteSubscribeFallbackToAudioOnly" callback. - - @param option Sets the fallback option for the remotely subscribed video stream. See #STREAM_FALLBACK_OPTIONS. - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setRemoteSubscribeFallbackOption(STREAM_FALLBACK_OPTIONS option) = 0; - -#if defined(__ANDROID__) || (defined(__APPLE__) && TARGET_OS_IOS) - /** Switches between front and rear cameras. - - @note This method is for Android and iOS only. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int switchCamera() = 0; - /** Sets the default audio playback route. - - This method sets whether the received audio is routed to the earpiece or speakerphone by default before joining a channel. - If a user does not call this method, the audio is routed to the earpiece by default. If you need to change the default audio route after joining a channel, call the \ref IRtcEngine::setEnableSpeakerphone "setEnableSpeakerphone" method. - - The default setting for each mode: - - Voice: Earpiece. - - Video: Speakerphone. If a user who is in the Communication profile calls the \ref IRtcEngine::disableVideo "disableVideo" method or if the user calls the \ref IRtcEngine::muteLocalVideoStream "muteLocalVideoStream" and \ref IRtcEngine::muteAllRemoteVideoStreams "muteAllRemoteVideoStreams" methods, the default audio route switches back to the earpiece automatically. - - Live Broadcast: Speakerphone. - - Gaming Voice: Speakerphone. - - @note - - This method is for Android and iOS only. - - This method only works in audio mode. - - Call this method before calling the \ref IRtcEngine::joinChannel "joinChannel" method. - - Regardless of whether the audio is routed to the speakerphone or earpiece by default, once a headset is plugged in or Bluetooth device is connected, the default audio route changes. The default audio route switches to the earpiece once removing the headset or disconnecting the Bluetooth device. - - @param defaultToSpeaker Sets the default audio route: - - true: Speakerphone. - - false: (Default) Earpiece. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setDefaultAudioRouteToSpeakerphone(bool defaultToSpeaker) = 0; - /** Enables/Disables the audio playback route to the speakerphone. - - This method sets whether the audio is routed to the speakerphone or earpiece. - - See the default audio route explanation in the \ref IRtcEngine::setDefaultAudioRouteToSpeakerphone "setDefaultAudioRouteToSpeakerphone" method and check whether it is necessary to call this method. - - @note - - This method is for Android and iOS only. - - Ensure that you have successfully called the \ref IRtcEngine::joinChannel "joinChannel" method before calling this method. - - After calling this method, the SDK returns the \ref IRtcEngineEventHandler::onAudioRouteChanged "onAudioRouteChanged" callback to indicate the changes. - - This method does not take effect if a headset is used. - - @param speakerOn Sets whether to route the audio to the speakerphone or earpiece: - - true: Route the audio to the speakerphone. - - false: Route the audio to the earpiece. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setEnableSpeakerphone(bool speakerOn) = 0; - /** Sets the volume of the in-ear monitor. - - @param volume Sets the volume of the in-ear monitor. The value ranges between 0 and 100 (default). - - @note This method is for Android and iOS only. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setInEarMonitoringVolume(int volume) = 0; - /** Checks whether the speakerphone is enabled. - - @note This method is for Android and iOS only. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual bool isSpeakerphoneEnabled() = 0; -#endif - -#if (defined(__APPLE__) && TARGET_OS_IOS) - /** Sets the audio session’s operational restriction. - - The SDK and the app can both configure the audio session by default. The app may occasionally use other apps or third-party components to manipulate the audio session and restrict the SDK from doing so. This method allows the app to restrict the SDK’s manipulation of the audio session. - - You can call this method at any time to return the control of the audio sessions to the SDK. - - @note - - This method is for iOS only. - - This method restricts the SDK’s manipulation of the audio session. Any operation to the audio session relies solely on the app, other apps, or third-party components. - - @param restriction The operational restriction (bit mask) of the SDK on the audio session. See #AUDIO_SESSION_OPERATION_RESTRICTION. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setAudioSessionOperationRestriction(AUDIO_SESSION_OPERATION_RESTRICTION restriction) = 0; -#endif - -#if (defined(__APPLE__) && TARGET_OS_MAC && !TARGET_OS_IPHONE) || defined(_WIN32) - /** Enables loopback recording. - - If you enable loopback recording, the output of the sound card is mixed into the audio stream sent to the other end. - - @param enabled Sets whether to enable/disable loopback recording. - - true: Enable loopback recording. - - false: (Default) Disable loopback recording. - @param deviceName Pointer to the device name of the sound card. The default value is NULL (the default sound card). - - @note - - This method is for macOS and Windows only. - - macOS does not support loopback recording of the default sound card. If you need to use this method, please use a virtual sound card and pass its name to the deviceName parameter. Agora has tested and recommends using soundflower. - - */ - virtual int enableLoopbackRecording(bool enabled, const char* deviceName = NULL) = 0; - -#if (defined(__APPLE__) && TARGET_OS_MAC && !TARGET_OS_IPHONE) - /** Shares the whole or part of a screen by specifying the display ID. - - @note This method is for macOS and Windows only. - - @param displayId The display ID of the screen to be shared. This parameter specifies which screen you want to share. - @param regionRect (Optional) Sets the relative location of the region to the screen. NIL means sharing the whole screen. See Rectangle. If the specified region overruns the screen, the SDK shares only the region within it; if you set width or height as 0, the SDK shares the whole screen. - @param captureParams Sets the screen sharing encoding parameters. See ScreenCaptureParameters. - - - @return - - 0: Success. - - < 0: Failure: - - ERR_INVALID_STATE: the screen sharing state is invalid, probably because another screen or window is being shared. Call \ref IRtcEngine::stopScreenCapture "stopScreenCapture" to stop the current screen sharing. - - ERR_INVALID_ARGUMENT: the argument is invalid. - */ - virtual int startScreenCaptureByDisplayId(unsigned int displayId, const Rectangle& regionRect, const ScreenCaptureParameters& captureParams) = 0; -#endif - -#if defined(_WIN32) - /** Shares the whole or part of a screen by specifying the screen rect. - - @param screenRect Sets the relative location of the screen to the virtual screen. For information on how to get screenRect, see [Share the Screen]. - @param regionRect (Optional) Sets the relative location of the region to the screen. NULL means sharing the whole screen. See Rectangle. If the specified region overruns the screen, the SDK shares only the region within it; if you set width or height as 0, the SDK shares the whole screen. - @param captureParams Sets the screen sharing encoding parameters. See ScreenCaptureParameters. - - @return - - 0: Success. - - < 0: Failure: - - ERR_INVALID_STATE: the screen sharing state is invalid, probably because another screen or window is being shared. Call stopScreenCapture to stop the current screen sharing. - - ERR_INVALID_ARGUMENT: the argument is invalid. - */ - virtual int startScreenCaptureByScreenRect(const Rectangle& screenRect, const Rectangle& regionRect, const ScreenCaptureParameters& captureParams) = 0; -#endif - - /** Shares the whole or part of a window by specifying the window ID. - - @param windowId The ID of the window to be shared. For information on how to get the windowId, see [Share the Window]. - @param regionRect (Optional) The relative location of the region to the window. NULL/NIL means sharing the whole window. See Rectangle. If the specified region overruns the window, the SDK shares only the region within it; if you set width or height as 0, the SDK shares the whole window. - @param captureParams Window sharing encoding parameters. See ScreenCaptureParameters. - - @return - - 0: Success. - - < 0: Failure: - - ERR_INVALID_STATE: the window sharing state is invalid, probably because another screen or window is being shared. Call stopScreenCapture to stop sharing the current window. - - ERR_INVALID_ARGUMENT: the argument is invalid. - */ - virtual int startScreenCaptureByWindowId(view_t windowId, const Rectangle& regionRect, const ScreenCaptureParameters& captureParams) = 0; - - /** Sets the content hint for screen sharing. - - A content hint suggests the type of the content being shared, so that the SDK applies different optimization algorithm to different types of content. - - @param contentHint Sets the content hint for screen sharing. See VideoContentHint. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setScreenCaptureContentHint(VideoContentHint contentHint) = 0; - - /** Updates the screen sharing parameters. - - @param captureParams Sets the screen sharing encoding parameters. See ScreenCaptureParameters. - - @return - - 0: Success. - - < 0: Failure: - - ERR_NOT_READY: no screen or windows is being shared. - */ - virtual int updateScreenCaptureParameters(const ScreenCaptureParameters& captureParams) = 0; - - /** Updates the screen sharing region. - - @param regionRect Sets the relative location of the region to the screen or window. NULL means sharing the whole screen or window. See Rectangle. If the specified region overruns the screen or window, the SDK shares only the region within it; if you set width or height as 0, the SDK shares the whole screen or window. - - @return - - 0: Success. - - < 0: Failure: - - ERR_NOT_READY: no screen or window is being shared. - */ - virtual int updateScreenCaptureRegion(const Rectangle& regionRect) = 0; - - /** Stop screen sharing. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int stopScreenCapture() = 0; - -#if defined(__APPLE__) - typedef unsigned int WindowIDType; -#elif defined(_WIN32) - typedef HWND WindowIDType; -#endif - - /** **DEPRECATED** Starts screen sharing. - - This method is deprecated as of v2.4.0. See the following methods instead: - - - \ref agora::rtc::IRtcEngine::startScreenCaptureByDisplayId "startScreenCaptureByDisplayId" - - \ref agora::rtc::IRtcEngine::startScreenCaptureByScreenRect "startScreenCaptureByScreenRect" - - \ref agora::rtc::IRtcEngine::startScreenCaptureByWindowId "startScreenCaptureByWindowId" - - This method shares the whole screen, specified window, or specified region: - - - Whole screen: Set @p windowId as 0 and @p rect as NULL. - - Specified window: Set @p windowId as a value other than 0. Each window has a @p windowId that is not 0. - - Specified region: Set @p windowId as 0 and @p rect not as NULL. In this case, you can share the specified region, for example by dragging the mouse or implementing your own logic. - - @note The specified region is a region on the whole screen. Currently, sharing a specified region in a specific window is not supported. - *captureFreq* is the captured frame rate once the screen-sharing function is enabled. The mandatory value ranges between 1 fps and 15 fps. - - @param windowId Sets the screen sharing area. See WindowIDType. - @param captureFreq (Mandatory) The captured frame rate. The value ranges between 1 fps and 15 fps. - @param rect Specifies the screen-sharing region. @p rect is valid when @p windowsId is set as 0. When @p rect is set as NULL, the whole screen is shared. - @param bitrate The captured bitrate. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int startScreenCapture(WindowIDType windowId, int captureFreq, const Rect *rect, int bitrate) = 0; - - /** **DEPRECATED** Updates the screen capture region. - - @param rect Specifies the required region inside the screen or window. - @return - - 0: Success. - - < 0: Failure. - */ - virtual int updateScreenCaptureRegion(const Rect *rect) = 0; -#endif - - /** Retrieves the current call ID. - - When a user joins a channel on a client, a @p callId is generated to identify the call from the client. Feedback methods, such as \ref IRtcEngine::rate "rate" and \ref IRtcEngine::complain "complain", must be called after the call ends to submit feedback to the SDK. - - The \ref IRtcEngine::rate "rate" and \ref IRtcEngine::complain "complain" methods require the @p callId parameter retrieved from the *getCallId* method during a call. @p callId is passed as an argument into the \ref IRtcEngine::rate "rate" and \ref IRtcEngine::complain "complain" methods after the call ends. - - @param callId Pointer to the current call ID. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int getCallId(agora::util::AString& callId) = 0; - - /** Allows a user to rate a call after the call ends. - - @param callId Pointer to the ID of the call, retrieved from the \ref IRtcEngine::getCallId "getCallId" method. - @param rating Rating of the call. The value is between 1 (lowest score) and 5 (highest score). If you set a value out of this range, the #ERR_INVALID_ARGUMENT (2) error returns. - @param description (Optional) Pointer to the description of the rating, with a string length of less than 800 bytes. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int rate(const char* callId, int rating, const char* description) = 0; - - /** Allows a user to complain about the call quality after a call ends. - - @param callId Pointer to the ID of the call, retrieved from the \ref IRtcEngine::getCallId "getCallId" method. - @param description (Optional) Pointer to the description of the complaint, with a string length of less than 800 bytes. - - @return - - 0: Success. - - < 0: Failure. - - */ - virtual int complain(const char* callId, const char* description) = 0; - - /** Retrieves the SDK version number. - - @param build Pointer to the build number. - @return The version of the current SDK in the string format. For example, 2.3.1. - */ - virtual const char* getVersion(int* build) = 0; - - /** Enables the network connection quality test. - - This method tests the quality of the users' network connections and is disabled by default. - - Before a user joins a channel or before an audience switches to a host, call this method to check the uplink network quality. - - This method consumes additional network traffic, and hence may affect communication quality. - - Call the \ref IRtcEngine::disableLastmileTest "disableLastmileTest" method to disable this test after receiving the \ref IRtcEngineEventHandler::onLastmileQuality "onLastmileQuality" callback, and before joining a channel. - - @note - - Do not call any other methods before receiving the \ref IRtcEngineEventHandler::onLastmileQuality "onLastmileQuality" callback. Otherwise, the callback may be interrupted by other methods, and hence may not be triggered. - - A host should not call this method after joining a channel (when in a call). - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int enableLastmileTest() = 0; - - /** Disables the network connection quality test. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int disableLastmileTest() = 0; - - /** Starts the last-mile network probe test. - - This method starts the last-mile network probe test before joining a channel to get the uplink and downlink last-mile network statistics, including the bandwidth, packet loss, jitter, and round-trip time (RTT). - - Call this method to check the uplink network quality before users join a channel or before an audience switches to a host. - Once this method is enabled, the SDK returns the following callbacks: - - \ref IRtcEngineEventHandler::onLastmileQuality "onLastmileQuality": the SDK triggers this callback within two seconds depending on the network conditions. This callback rates the network conditions and is more closely linked to the user experience. - - \ref IRtcEngineEventHandler::onLastmileProbeResult "onLastmileProbeResult": the SDK triggers this callback within 30 seconds depending on the network conditions. This callback returns the real-time statistics of the network conditions and is more objective. - - @note - - This method consumes extra network traffic and may affect communication quality. We do not recommend calling this method together with enableLastmileTest. - - Do not call other methods before receiving the \ref IRtcEngineEventHandler::onLastmileQuality "onLastmileQuality" and \ref IRtcEngineEventHandler::onLastmileProbeResult "onLastmileProbeResult" callbacks. Otherwise, the callbacks may be interrupted. - - In the Live-broadcast profile, a host should not call this method after joining a channel. - - @param config Sets the configurations of the last-mile network probe test. See LastmileProbeConfig. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int startLastmileProbeTest(const LastmileProbeConfig& config) = 0; - - /** Stops the last-mile network probe test. */ - virtual int stopLastmileProbeTest() = 0; - - /** Retrieves the warning or error description. - - @return code #WARN_CODE_TYPE or #ERROR_CODE_TYPE returned in the \ref IRtcEngineEventHandler::onWarning "onWarning" or \ref IRtcEngineEventHandler::onError "onError" callback. - */ - virtual const char* getErrorDescription(int code) = 0; - - /** Enables built-in encryption with an encryption password before users join a channel. - - All users in a channel must use the same encryption password. The encryption password is automatically cleared once a user leaves the channel. - - If an encryption password is not specified, the encryption functionality will be disabled. - - @note - - Do not use this method for CDN live streaming. - - For optimal transmission, ensure that the encrypted data size does not exceed the original data size + 16 bytes. 16 bytes is the maximum padding size for AES encryption. - - @param secret Pointer to the encryption password. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setEncryptionSecret(const char* secret) = 0; - - /** Sets the built-in encryption mode. - - The Agora SDK supports built-in encryption, which is set to the @p aes-128-xts mode by default. Call this method to use other encryption modes. - - All users in the same channel must use the same encryption mode and password. - - Refer to the information related to the AES encryption algorithm on the differences between the encryption modes. - - @note Call the \ref IRtcEngine::setEncryptionSecret "setEncryptionSecret" method to enable the built-in encryption function before calling this method. - - @param encryptionMode Pointer to the set encryption mode: - - "aes-128-xts": (Default) 128-bit AES encryption, XTS mode. - - "aes-128-ecb": 128-bit AES encryption, ECB mode. - - "aes-256-xts": 256-bit AES encryption, XTS mode. - - "": When encryptionMode is set as NULL, the encryption mode is set as "aes-128-xts" by default. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setEncryptionMode(const char* encryptionMode) = 0; - - /** Registers a packet observer. - - The Agora SDK allows your application to register a packet observer to receive callbacks for voice or video packet transmission. - - @param observer Pointer to the registered packet observer. See IPacketObserver. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int registerPacketObserver(IPacketObserver* observer) = 0; - - /** Creates a data stream. - - Each user can create up to five data streams during the lifecycle of the RtcEngine. - - @note Set both the @p reliable and @p ordered parameters to true or false. Do not set one as true and the other as false. - - @param streamId Pointer to the ID of the created data stream. - @param reliable Sets whether or not the recipients are guaranteed to receive the data stream from the sender within five seconds: - - true: The recipients receive the data stream from the sender within five seconds. If the recipient does not receive the data stream within five seconds, an error is reported to the application. - - false: There is no guarantee that the recipients receive the data stream within five seconds and no error message is reported for any delay or missing data stream. - @param ordered Sets whether or not the recipients receive the data stream in the sent order: - - true: The recipients receive the data stream in the sent order. - - false: The recipients do not receive the data stream in the sent order. - - @return - - Returns 0: Success. - - < 0: Failure. - */ - virtual int createDataStream(int* streamId, bool reliable, bool ordered) = 0; - - /** Sends data stream messages to all users in a channel. - - The SDK has the following restrictions on this method: - - Up to 30 packets can be sent per second in a channel with each packet having a maximum size of 1 kB. - - Each client can send up to 6 kB of data per second. - - Each user can have up to five data streams simultaneously. - - A successful \ref agora::rtc::IRtcEngine::sendStreamMessage "sendStreamMessage" method call triggers the \ref agora::rtc::IRtcEngineEventHandler::onStreamMessage "onStreamMessage" callback on the remote client, from which the remote user gets the stream message. - - A failed \ref agora::rtc::IRtcEngine::sendStreamMessage "sendStreamMessage" method call triggers the \ref agora::rtc::IRtcEngineEventHandler::onStreamMessageError "onStreamMessage" callback on the remote client. - @note This method applies only to the Communication profile or to the hosts in the Live-broadcast profile. If an audience in the Live-broadcast profile calls this method, the audience may be switched to a host. - - @param streamId ID of the sent data stream, returned in the \ref IRtcEngine::createDataStream "createDataStream" method. - @param data Pointer to the sent data. - @param length Length of the sent data. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int sendStreamMessage(int streamId, const char* data, size_t length) = 0; - - /** Publishes the local stream to a specified CDN live RTMP address. (CDN live only.) - - The SDK returns the result of this method call in the \ref IRtcEngineEventHandler::onStreamPublished "onStreamPublished" callback. - - The \ref agora::rtc::IRtcEngine::addPublishStreamUrl "addPublishStreamUrl" method call triggers the \ref agora::rtc::IRtcEngineEventHandler::onRtmpStreamingStateChanged "onRtmpStreamingStateChanged" callback on the local client to report the state of adding a local stream to the CDN. - @note - - Ensure that the user joins the channel before calling this method. - - This method adds only one stream RTMP URL address each time it is called. - - The RTMP URL address must not contain special characters, such as Chinese language characters. - - This method applies to Live Broadcast only. - - @param url The CDN streaming URL in the RTMP format. The maximum length of this parameter is 1024 bytes. - @param transcodingEnabled Sets whether transcoding is enabled/disabled: - - true: Enable transcoding. To [transcode](https://docs.agora.io/en/Agora%20Platform/terms?platform=All%20Platforms#transcoding) the audio or video streams when publishing them to CDN live, often used for combining the audio and video streams of multiple hosts in CDN live. - - false: Disable transcoding. - - @return - - 0: Success. - - < 0: Failure. - - #ERR_INVALID_ARGUMENT (2): The RTMP URL address is NULL or has a string length of 0. - - #ERR_NOT_INITIALIZED (7): You have not initialized the RTC engine when publishing the stream. - */ - virtual int addPublishStreamUrl(const char *url, bool transcodingEnabled) = 0; - - /** Removes an RTMP stream from the CDN. (CDN live only.) - - This method removes the RTMP URL address (added by the \ref IRtcEngine::addPublishStreamUrl "addPublishStreamUrl" method) from a CDN live stream. The SDK returns the result of this method call in the \ref IRtcEngineEventHandler::onStreamUnpublished "onStreamUnpublished" callback. - - The \ref agora::rtc::IRtcEngine::removePublishStreamUrl "removePublishStreamUrl" method call triggers the \ref agora::rtc::IRtcEngineEventHandler::onRtmpStreamingStateChanged "onRtmpStreamingStateChanged" callback on the local client to report the state of removing an RTMP stream from the CDN. - @note - - This method removes only one RTMP URL address each time it is called. - - The RTMP URL address must not contain special characters, such as Chinese language characters. - - This method applies to Live Broadcast only. - - @param url The RTMP URL address to be removed. The maximum length of this parameter is 1024 bytes. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int removePublishStreamUrl(const char *url) = 0; - - /** Sets the video layout and audio settings for CDN live. (CDN live only.) - @note This method applies to Live Broadcast only. - - @param transcoding Sets the CDN live audio/video transcoding settings. See LiveTranscoding. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setLiveTranscoding(const LiveTranscoding &transcoding) = 0; - - /** Adds a watermark image to the local video or CDN live stream. - - This method adds a PNG watermark image to the local video stream for the recording device, channel audience, and CDN live audience to view and capture. - - To add the PNG file to the CDN live publishing stream, see the \ref IRtcEngine::setLiveTranscoding "setLiveTranscoding" method. - - @param watermark Pointer to the watermark image to be added to the local video stream. See RtcImage. - - @note - - The URL descriptions are different for the local video and CDN live streams: - - In a local video stream, @p url in RtcImage refers to the absolute path of the added watermark image file in the local video stream. - - In a CDN live stream, @p url in RtcImage refers to the URL address of the added watermark image in the CDN live broadcast. - - The source file of the watermark image must be in the PNG file format. If the width and height of the PNG file differ from your settings in this method, the PNG file will be cropped to conform to your settings. - - The Agora SDK supports adding only one watermark image onto a local video or CDN live stream. The newly added watermark image replaces the previous one. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int addVideoWatermark(const RtcImage& watermark) = 0; - - /** Removes the watermark image from the video stream added by the \ref IRtcEngine::addVideoWatermark "addVideoWatermark" method. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int clearVideoWatermarks() = 0; - - /** **Supports Android and iOS only!** Enables/Disables image enhancement and sets the options. - - @param enabled Sets whether or not to enable image enhancement: - - true: enables image enhancement. - - false: disables image enhancement. - @param options Sets the image enhancement option. See BeautyOptions. - */ - virtual int setBeautyEffectOptions(bool enabled, BeautyOptions options) = 0; - - /** Adds a voice or video stream URL address to a live broadcast. - - The \ref IRtcEngineEventHandler::onStreamPublished "onStreamPublished" callback returns the inject status. If this method call is successful, the server pulls the voice or video stream and injects it into a live channel. This is applicable to scenarios where all audience members in the channel can watch a live show and interact with each other. - - @note - - Contact support@agora.io to enable the CDN streaming function before calling this method. - - This method applies to the Native SDK v2.4.1 and later. - - The \ref agora::rtc::IRtcEngine::addInjectStreamUrl "addInjectStreamUrl" method call triggers the following callbacks: - - The local client: - - \ref agora::rtc::IRtcEngineEventHandler::onStreamInjectedStatus "onStreamInjectedStatus" , with the state of the injecting the online stream. - - \ref agora::rtc::IRtcEngineEventHandler::onUserJoined "onUserJoined" (uid: 666), if the method call is successful and the online media stream is injected into the channel. - - The remote client: - - \ref agora::rtc::IRtcEngineEventHandler::onUserJoined "onUserJoined" (uid: 666), if the method call is successful and the online media stream is injected into the channel. - - @param url Pointer to the URL address to be added to the ongoing live broadcast. Valid protocols are RTMP, HLS, and FLV. - - Supported FLV audio codec type: AAC. - - Supported FLV video codec type: H264 (AVC). - @param config Pointer to the InjectStreamConfig object that contains the configuration of the added voice or video stream. - - @return - - 0: Success. - - < 0: Failure. - - #ERR_INVALID_ARGUMENT (2): The injected URL does not exist. Call this method again to inject the stream and ensure that the URL is valid. - - #ERR_NOT_READY (3): The user is not in the channel. - - #ERR_NOT_SUPPORTED (4): The channel profile is not live broadcast. Call the \ref agora::rtc::IRtcEngine::setChannelProfile "setChannelProfile" method and set the channel profile to live broadcast before calling this method. - - #ERR_NOT_INITIALIZED (7): The SDK is not initialized. Ensure that the IRtcEngine object is initialized before calling this method. - */ - virtual int addInjectStreamUrl(const char* url, const InjectStreamConfig& config) = 0; - /** Starts to relay media streams across channels. - * - * After a successful method call, the SDK triggers the - * \ref agora::rtc::IRtcEngineEventHandler::onChannelMediaRelayStateChanged - * "onChannelMediaRelayStateChanged" and - * \ref agora::rtc::IRtcEngineEventHandler::onChannelMediaRelayEvent - * "onChannelMediaRelayEvent" callbacks, and these callbacks return the - * state and events of the media stream relay. - * - If the - * \ref agora::rtc::IRtcEngineEventHandler::onChannelMediaRelayStateChanged - * "onChannelMediaRelayStateChanged" callback returns - * #RELAY_STATE_RUNNING (1) and #RELAY_OK (0), and the - * \ref agora::rtc::IRtcEngineEventHandler::onChannelMediaRelayEvent - * "onChannelMediaRelayEvent" callback returns - * #RELAY_EVENT_PACKET_SENT_TO_DEST_CHANNEL (4), the broadcaster starts - * sending data to the destination channel. - * - If the - * \ref agora::rtc::IRtcEngineEventHandler::onChannelMediaRelayStateChanged - * "onChannelMediaRelayStateChanged" callback returns - * #RELAY_STATE_FAILURE (3), an exception occurs during the media stream - * relay. - * - * @note - * - Call this method after the \ref joinChannel() "joinChannel" method. - * - This method takes effect only when you are a broadcaster in a - * Live-broadcast channel. - * - After a successful method call, if you want to call this method - * again, ensure that you call the - * \ref stopChannelMediaRelay() "stopChannelMediaRelay" method to quit the - * current relay. - * - * @param configuration The configuration of the media stream relay: - * ChannelMediaRelayConfiguration. - * - * @return - * - 0: Success. - * - < 0: Failure. - */ - virtual int startChannelMediaRelay(const ChannelMediaRelayConfiguration &configuration) = 0; - /** Updates the channels for media stream relay. After a successful - * \ref startChannelMediaRelay() "startChannelMediaRelay" method call, if - * you want to relay the media stream to more channels, or leave the - * current relay channel, you can call the - * \ref updateChannelMediaRelay() "updateChannelMediaRelay" method. - * - * After a successful method call, the SDK triggers the - * \ref agora::rtc::IRtcEngineEventHandler::onChannelMediaRelayStateChanged - * "onChannelMediaRelayStateChanged" callback with the - * #RELAY_EVENT_PACKET_UPDATE_DEST_CHANNEL (7) state code. - * - * @note - * Call this method after the - * \ref startChannelMediaRelay() "startChannelMediaRelay" method to update - * the destination channel. - * - * @param configuration The media stream relay configuration: - * ChannelMediaRelayConfiguration. - * - * @return - * - 0: Success. - * - < 0: Failure. - */ - virtual int updateChannelMediaRelay(const ChannelMediaRelayConfiguration &configuration) = 0; - /** Stops the media stream relay. - * - * Once the relay stops, the broadcaster quits all the destination - * channels. - * - * After a successful method call, the SDK triggers the - * \ref agora::rtc::IRtcEngineEventHandler::onChannelMediaRelayStateChanged - * "onChannelMediaRelayStateChanged" callback. If the callback returns - * #RELAY_STATE_IDLE (0) and #RELAY_OK (0), the broadcaster successfully - * stops the relay. - * - * @note - * If the method call fails, the SDK triggers the - * \ref agora::rtc::IRtcEngineEventHandler::onChannelMediaRelayStateChanged - * "onChannelMediaRelayStateChanged" callback with the - * #RELAY_ERROR_SERVER_NO_RESPONSE (2) or - * #RELAY_ERROR_SERVER_CONNECTION_LOST (8) state code. You can leave the - * channel by calling the \ref leaveChannel() "leaveChannel" method, and - * the media stream relay automatically stops. - * - * @return - * - 0: Success. - * - < 0: Failure. - */ - virtual int stopChannelMediaRelay() = 0; - - /** Removes the voice or video stream URL address from a live broadcast. - - This method removes the URL address (added by the \ref IRtcEngine::addInjectStreamUrl "addInjectStreamUrl" method) from the live broadcast. - - @note If this method is called successfully, the SDK triggers the \ref IRtcEngineEventHandler::onUserOffline "onUserOffline" callback and returns a stream uid of 666. - - @param url Pointer to the URL address of the added stream to be removed. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int removeInjectStreamUrl(const char* url) = 0; - - virtual bool registerEventHandler(IRtcEngineEventHandler *eventHandler) = 0; - virtual bool unregisterEventHandler(IRtcEngineEventHandler *eventHandler) = 0; - /** Gets the connection state of the SDK. - - @return #CONNECTION_STATE_TYPE. - */ - virtual CONNECTION_STATE_TYPE getConnectionState() = 0; - - /** Registers the metadata observer. - - Registers the metadata observer. You need to implement the IMetadataObserver class and specify the metadata type in this method. A successful call of this method triggers the \ref agora::rtc::IMetadataObserver::getMaxMetadataSize "getMaxMetadataSize" callback. - This method enables you to add synchronized metadata in the video stream for more diversified live broadcast interactions, such as sending shopping links, digital coupons, and online quizzes. - - @note - - Call this method before the joinChannel method. - - This method applies to the Live-broadcast channel profile. - - @param observer The IMetadataObserver class. See the definition of IMetadataObserver for details. - @param type See \ref IMetadataObserver::METADATA_TYPE "METADATA_TYPE". The SDK supports VIDEO_METADATA (0) only for now. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int registerMediaMetadataObserver(IMetadataObserver *observer, IMetadataObserver::METADATA_TYPE type) = 0; -}; - - -class IRtcEngineParameter -{ -public: - /** - * Releases all IRtcEngineParameter resources. - */ - virtual void release() = 0; - - /** Sets the bool value of a specified key in the JSON format. - - @param key Pointer to the name of the key. - @param value Sets the value. - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setBool(const char* key, bool value) = 0; - - /** Sets the int value of a specified key in the JSON format. - - @param key Pointer to the name of the key. - @param value Sets the value. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setInt(const char* key, int value) = 0; - - /** Sets the unsigned int value of a specified key in the JSON format. - - @param key Pointer to the name of the key. - @param value Sets the value. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setUInt(const char* key, unsigned int value) = 0; - - /** Sets the double value of a specified key in the JSON format. - - @param key Pointer to the name of the key. - @param value Sets the value. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setNumber(const char* key, double value) = 0; - - /** Sets the string value of a specified key in the JSON format. - - @param key Pointer to the name of the key. - @param value Pointer to the set value. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setString(const char* key, const char* value) = 0; - - /** Sets the object value of a specified key in the JSON format. - - @param key Pointer to the name of the key. - @param value Pointer to the set value. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setObject(const char* key, const char* value) = 0; - - /** Retrieves the bool value of a specified key in the JSON format. - - @param key Pointer to the name of the key. - @param value Pointer to the retrieved value. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int getBool(const char* key, bool& value) = 0; - - /** Retrieves the int value of the JSON format. - - @param key Pointer to the name of the key. - @param value Pointer to the retrieved value. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int getInt(const char* key, int& value) = 0; - - /** Retrieves the unsigned int value of a specified key in the JSON format. - - @param key Pointer to the name of the key. - @param value Pointer to the retrieved value. - @return - - 0: Success. - - < 0: Failure. - */ - virtual int getUInt(const char* key, unsigned int& value) = 0; - - /** Retrieves the double value of a specified key in the JSON format. - - @param key Pointer to the name of the key. - @param value Pointer to the retrieved value. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int getNumber(const char* key, double& value) = 0; - - /** Retrieves the string value of a specified key in the JSON format. - - @param key Pointer to the name of the key. - @param value Pointer to the retrieved value. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int getString(const char* key, agora::util::AString& value) = 0; - - /** Retrieves a child object value of a specified key in the JSON format. - - @param key Pointer to the name of the key. - @param value Pointer to the retrieved value. - @return - - 0: Success. - - < 0: Failure. - */ - virtual int getObject(const char* key, agora::util::AString& value) = 0; - - /** Retrieves the array value of a specified key in the JSON format. - - @param key Pointer to the name of the key. - @param value Pointer to the retrieved value. - @return - - 0: Success. - - < 0: Failure. - */ - virtual int getArray(const char* key, agora::util::AString& value) = 0; - - /** Provides the technical preview functionalities or special customizations by configuring the SDK with JSON options. - - @param parameters Pointer to the set parameters in a JSON string. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setParameters(const char* parameters) = 0; - - /** Sets the profile to control the RTC engine. - - @param profile Pointer to the set profile. - @param merge Sets whether to merge the profile data with the original value: - - true: Merge the profile data with the original value. - - false: Do not merge the profile data with the original value. - - @return - - 0: Success. - - < 0: Failure. - */ - virtual int setProfile(const char* profile, bool merge) = 0; - - virtual int convertPath(const char* filePath, agora::util::AString& value) = 0; -}; - -class AAudioDeviceManager : public agora::util::AutoPtr -{ -public: - AAudioDeviceManager(IRtcEngine* engine) - { - queryInterface(engine, AGORA_IID_AUDIO_DEVICE_MANAGER); - } -}; - -class AVideoDeviceManager : public agora::util::AutoPtr -{ -public: - AVideoDeviceManager(IRtcEngine* engine) - { - queryInterface(engine, AGORA_IID_VIDEO_DEVICE_MANAGER); - } -}; - -class AParameter : public agora::util::AutoPtr -{ -public: - AParameter(IRtcEngine& engine) { initialize(&engine); } - AParameter(IRtcEngine* engine) { initialize(engine); } - AParameter(IRtcEngineParameter* p) :agora::util::AutoPtr(p) {} -private: - bool initialize(IRtcEngine* engine) - { - IRtcEngineParameter* p = NULL; - if (engine && !engine->queryInterface(AGORA_IID_RTC_ENGINE_PARAMETER, (void**)&p)) - reset(p); - return p != NULL; - } -}; -/** The RtcEngineParameters class is an auxiliary class setting parameters for the SDK. - -*/ -class RtcEngineParameters -{ -public: - RtcEngineParameters(IRtcEngine& engine) - :m_parameter(&engine){} - RtcEngineParameters(IRtcEngine* engine) - :m_parameter(engine){} - - /** Disables/Re-enables the local video. - - This method is only applicable when the user wants to watch the remote video without sending any video stream to the other user. - - Call this method after calling the \ref agora::rtc::IRtcEngine::enableVideo "enableVideo" method. Otherwise, this method may not work properly. - - After the *enableVideo* method is called, the local video is enabled by default. This method is used to disable/re-enable the local video while the remote video remains unaffected. - - @note This method affects the internal engine and can be called after the \ref agora::rtc::IRtcEngine::leaveChannel "leaveChannel" method. - - @param enabled Sets whether to disable/re-enable the local video, including the capturer, renderer, and sender: - - true: (Default) Re-enable the local video. - - false: Disable the local video. Once the local video is disabled, the remote users can no longer receive the video stream of this user, while this user can still receive the video streams of the other remote users. - - @return - - 0: Success. - - < 0: Failure. - */ - int enableLocalVideo(bool enabled) { - return setParameters("{\"rtc.video.capture\":%s,\"che.video.local.capture\":%s,\"che.video.local.render\":%s,\"che.video.local.send\":%s}", enabled ? "true" : "false", enabled ? "true" : "false", enabled ? "true" : "false", enabled ? "true" : "false"); - } - - - /** Stops/Resumes sending the local video stream. - - @note When set to *true*, this method does not disable the camera which does not affect the retrieval of the local video streams. This method executes faster than the \ref agora::rtc::IRtcEngine::enableLocalVideo "enableLocalVideo" method which controls the sending of the local video stream. - - @param mute Sets whether to send/stop sending the local video stream: - - true: Stop sending the local video stream. - - false: (Default) Send the local video stream. - - @return - - 0: Success. - - < 0: Failure. - */ - int muteLocalVideoStream(bool mute) { - return setParameters("{\"rtc.video.mute_me\":%s,\"che.video.local.send\":%s}", mute ? "true" : "false", mute ? "false" : "true"); - } - - /** Stops/Resumes receiving all remote users' video streams. - - @param mute Sets whether to receive/stop receiving all remote users' video streams: - - true: Stop receiving all remote users' video streams. - - false: (Default) Receive all remote users' video streams. - - @return - - 0: Success. - - < 0: Failure. - */ - int muteAllRemoteVideoStreams(bool mute) { - return m_parameter ? m_parameter->setBool("rtc.video.mute_peers", mute) : -ERR_NOT_INITIALIZED; - } - - - /** Stops/Resumes receiving all remote users' video streams by default. - - @param mute Sets whether to receive/stop receiving all remote users' video streams by default: - - true: Stop receiving all remote users' video streams by default. - - false: (Default) Receive all remote users' video streams by default. - - @return - - 0: Success. - - < 0: Failure. - */ - int setDefaultMuteAllRemoteVideoStreams(bool mute) { - return m_parameter ? m_parameter->setBool("rtc.video.set_default_mute_peers", mute) : -ERR_NOT_INITIALIZED; - } - - /** Stops/Resumes receiving a specified remote user's video stream. - - @note If you called the \ref agora::rtc::IRtcEngine::muteAllRemoteVideoStreams "muteAllRemoteVideoStreams" method and set @p mute as @p true to stop receiving all remote video streams, call the *muteAllRemoteVideoStreams* method and set @p mute as @p false before calling this method. - - @param uid User ID of the specified remote user. - @param mute Sets whether to receive/stop receiving the specified remote user's video stream: - - true: Stop receiving the specified remote user's video stream. - - false: (Default) Receive the specified remote user's video stream. - - @return - - 0: Success. - - < 0: Failure. - */ - int muteRemoteVideoStream(uid_t uid, bool mute) { - return setObject("rtc.video.mute_peer", "{\"uid\":%u,\"mute\":%s}", uid, mute ? "true" : "false"); - } - - /** **DEPRECATED** Use \ref agora::rtc::IAudioDeviceManager::setPlaybackDeviceVolume "setPlaybackDeviceVolume" instead. Sets the playback device volume. - - @param volume Sets the volume of the playback device. The value ranges between 0 and 255. - - @return - - 0: Success. - - < 0: Failure. - */ - int setPlaybackDeviceVolume(int volume) {// [0,255] - return m_parameter ? m_parameter->setInt("che.audio.output.volume", volume) : -ERR_NOT_INITIALIZED; - } - - /** Starts an audio recording. - - The SDK allows recording during a call. Supported formats: - - - .wav: Large file size with high fidelity. - - .aac: Small file size with low fidelity. - - Ensure that the directory to save the recording file exists and is writable. - This method is usually called after the \ref agora::rtc::IRtcEngine::joinChannel "joinChannel" method. - The recording automatically stops when the \ref agora::rtc::IRtcEngine::leaveChannel "leaveChannel" method is called. - - @param filePath Pointer to the absolute file path of the recording file. The string of the file name is in UTF-8. - @param quality Sets the audio recording quality. See #AUDIO_RECORDING_QUALITY_TYPE. - - @return - - 0: Success. - - < 0: Failure. - */ - int startAudioRecording(const char* filePath, AUDIO_RECORDING_QUALITY_TYPE quality) { - if (!m_parameter) return -ERR_NOT_INITIALIZED; -#if defined(_WIN32) - util::AString path; - if (!m_parameter->convertPath(filePath, path)) - filePath = path->c_str(); - else - return -ERR_INVALID_ARGUMENT; -#endif - return setObject("che.audio.start_recording", "{\"filePath\":\"%s\",\"quality\":%d}", filePath, quality); - } - - /** Stops an audio recording on the client. - - You can call this method before calling the \ref agora::rtc::IRtcEngine::leaveChannel "leaveChannel" method else, the recording automatically stops when the \ref agora::rtc::IRtcEngine::leaveChannel "leaveChannel" method is called. - - @return - - 0: Success - - < 0: Failure. - */ - int stopAudioRecording() { - return m_parameter ? m_parameter->setBool("che.audio.stop_recording", true) : -ERR_NOT_INITIALIZED; - } - - /** Starts playing and mixing the music file. - - This method mixes the specified local audio file with the audio stream from the microphone, or replaces the microphone's audio stream with the specified local audio file. You can choose whether the other user can hear the local audio playback and specify the number of playback loops. This method also supports online music playback. - - When the audio mixing file playback finishes after calling this method, the SDK triggers the \ref agora::rtc::IRtcEngineEventHandler::onAudioMixingFinished "onAudioMixingFinished" callback. - - @note - - Call this method when you are in a channel. - - If the local audio mixing file does not exist, or if the SDK does not support the file format or cannot access the music file URL, the SDK returns WARN_AUDIO_MIXING_OPEN_ERROR = 701. - - @param filePath Pointer to the absolute path of the local or online audio file to mix. Supported audio formats: 3GP, ASF, ADTS, AVI, MP3, MPEG-4, SAMI, and WAVE. For more information, see [Supported Media Formats in Media Foundation](https://docs.microsoft.com/en-us/windows/desktop/medfound/supported-media-formats-in-media-foundation). - @param loopback Sets which user can hear the audio mixing: - - true: Only the local user can hear the audio mixing. - - false: Both users can hear the audio mixing. - @param replace Sets the audio mixing content: - - true: Only the specified audio file is published; the audio stream received by the microphone is not published. - - false: The local audio file is mixed with the audio stream from the microphone. - @param cycle Sets the number of playback loops: - - Positive integer: Number of playback loops. - - -1: Infinite playback loops. - - @return - - 0: Success. - - < 0: Failure. - */ - int startAudioMixing(const char* filePath, bool loopback, bool replace, int cycle) { - if (!m_parameter) return -ERR_NOT_INITIALIZED; -#if defined(_WIN32) - util::AString path; - if (!m_parameter->convertPath(filePath, path)) - filePath = path->c_str(); - else - return -ERR_INVALID_ARGUMENT; -#endif - return setObject("che.audio.start_file_as_playout", "{\"filePath\":\"%s\",\"loopback\":%s,\"replace\":%s,\"cycle\":%d}", - filePath, - loopback?"true":"false", - replace?"true":"false", - cycle); - } - - /** Stops playing and mixing the music file. - - Call this method when you are in a channel. - - @return - - 0: Success. - - < 0: Failure. - */ - int stopAudioMixing() { - return m_parameter ? m_parameter->setBool("che.audio.stop_file_as_playout", true) : -ERR_NOT_INITIALIZED; - } - - /** Pauses playing and mixing the music file. - - Call this method when you are in a channel. - - @return - - 0: Success. - - < 0: Failure. - */ - int pauseAudioMixing() { - return m_parameter ? m_parameter->setBool("che.audio.pause_file_as_playout", true) : -ERR_NOT_INITIALIZED; - } - - /** Resumes playing and mixing the music file. - - Call this method when you are in a channel. - - @return - - 0: Success. - - < 0: Failure. - */ - int resumeAudioMixing() { - return m_parameter ? m_parameter->setBool("che.audio.pause_file_as_playout", false) : -ERR_NOT_INITIALIZED; - } - - /** Adjusts the volume during audio mixing. - - Call this method when you are in a channel. - - @param volume Audio mixing volume. The value ranges between 0 and 100 (default). - - @return - - 0: Success. - - < 0: Failure. - */ - int adjustAudioMixingVolume(int volume) { - int ret = adjustAudioMixingPlayoutVolume(volume); - if (ret == 0) { - adjustAudioMixingPublishVolume(volume); - } - return ret; - } - - /** Adjusts the audio mixing volume for local playback. - - @note Call this method when you are in a channel. - - @param volume Audio mixing volume for local playback. The value ranges between 0 and 100 (default). - - @return - - 0: Success. - - < 0: Failure. - */ - int adjustAudioMixingPlayoutVolume(int volume) { - return m_parameter ? m_parameter->setInt("che.audio.set_file_as_playout_volume", volume) : -ERR_NOT_INITIALIZED; - } - - /** Retrieves the audio mixing volume for local playback. - - This method helps troubleshoot audio volume related issues. - - @note Call this method when you are in a channel. - - @return - - ≥ 0: The audio mixing volume, if this method call succeeds. The value range is [0,100]. - - < 0: Failure. - */ - int getAudioMixingPlayoutVolume() { - int volume = 0; - int r = m_parameter ? m_parameter->getInt("che.audio.get_file_as_playout_volume", volume) : -ERR_NOT_INITIALIZED; - if (r == 0) - r = volume; - return r; - } - - /** Adjusts the audio mixing volume for publishing (for remote users). - - @note Call this method when you are in a channel. - - @param volume Audio mixing volume for publishing. The value ranges between 0 and 100 (default). - - @return - - 0: Success. - - < 0: Failure. - */ - int adjustAudioMixingPublishVolume(int volume) { - return m_parameter ? m_parameter->setInt("che.audio.set_file_as_playout_publish_volume", volume) : -ERR_NOT_INITIALIZED; - } - - /** Retrieves the audio mixing volume for publishing. - - This method helps troubleshoot audio volume related issues. - - @note Call this method when you are in a channel. - - @return - - ≥ 0: The audio mixing volume for publishing, if this method call succeeds. The value range is [0,100]. - - < 0: Failure. - */ - int getAudioMixingPublishVolume() { - int volume = 0; - int r = m_parameter ? m_parameter->getInt("che.audio.get_file_as_playout_publish_volume", volume) : -ERR_NOT_INITIALIZED; - if (r == 0) - r = volume; - return r; - } - - /** Retrieves the duration (ms) of the music file. - - Call this method when you are in a channel. - - @return - - ≥ 0: The audio mixing duration, if this method call succeeds. - - < 0: Failure. - */ - int getAudioMixingDuration() { - int duration = 0; - int r = m_parameter ? m_parameter->getInt("che.audio.get_mixing_file_length_ms", duration) : -ERR_NOT_INITIALIZED; - if (r == 0) - r = duration; - return r; - } - - /** Retrieves the playback position (ms) of the music file. - - Call this method when you are in a channel. - - @return - - ≥ 0: The current playback position of the audio mixing, if this method call succeeds. - - < 0: Failure. - */ - int getAudioMixingCurrentPosition() { - if (!m_parameter) return -ERR_NOT_INITIALIZED; - int pos = 0; - int r = m_parameter->getInt("che.audio.get_mixing_file_played_ms", pos); - if (r == 0) - r = pos; - return r; - } - /** Sets the playback position of the music file to a different starting position (the default plays from the beginning). - - @param pos The playback starting position (ms) of the music file. - - @return - - 0: Success. - - < 0: Failure. - */ - int setAudioMixingPosition(int pos /*in ms*/) { - return m_parameter ? m_parameter->setInt("che.audio.mixing.file.position", pos) : -ERR_NOT_INITIALIZED; - } - - /** Retrieves the volume of the audio effects. - - The value ranges between 0.0 and 100.0. - - @return - - ≥ 0: Volume of the audio effects, if this method call succeeds. - - - < 0: Failure. - */ - int getEffectsVolume() { - if (!m_parameter) return -ERR_NOT_INITIALIZED; - int volume = 0; - int r = m_parameter->getInt("che.audio.game_get_effects_volume", volume); - if (r == 0) - r = volume; - return r; - } - - /** Sets the volume of the audio effects. - - @param volume Sets the volume of the audio effects. The value ranges between 0 and 100 (default). - - @return - - 0: Success. - - < 0: Failure. - */ - int setEffectsVolume(int volume) { - return m_parameter ? m_parameter->setInt("che.audio.game_set_effects_volume", volume) : -ERR_NOT_INITIALIZED; - } - - /** Sets the volume of a specified audio effect. - - @param soundId ID of the audio effect. Each audio effect has a unique ID. - @param volume Sets the volume of the specified audio effect. The value ranges between 0.0 and 100.0 (default). - - @return - - 0: Success. - - < 0: Failure. - */ - int setVolumeOfEffect(int soundId, int volume) { - return setObject( - "che.audio.game_adjust_effect_volume", - "{\"soundId\":%d,\"gain\":%d}", - soundId, volume); - } - - /** Plays a specified local or online audio effect file. - - This method allows you to set the loop count, pitch, pan, and gain of the audio effect file, as well as whether the remote user can hear the audio effect. - - To play multiple audio effect files simultaneously, call this method multiple times with different soundIds and filePaths. We recommend playing no more than three audio effect files at the same time. - - When the audio effect file playback finishes, the SDK returns the \ref IRtcEngineEventHandler::onAudioEffectFinished "onAudioEffectFinished" callback. - - @param soundId ID of the specified audio effect. Each audio effect has a unique ID. - - @note - - If the audio effect is preloaded into the memory through the \ref IRtcEngine::preloadEffect "preloadEffect" method, the value of @p soundID must be the same as that in the *preloadEffect* method. - - Playing multiple online audio effect files simultaneously is not supported on macOS and Windows. - - @param filePath The absolute path to the local audio effect file or the URL of the online audio effect file. - @param loopCount Sets the number of times the audio effect loops: - - 0: Play the audio effect once. - - 1: Play the audio effect twice. - - -1: Play the audio effect in an indefinite loop until the \ref IRtcEngine::stopEffect "stopEffect" or \ref IRtcEngine::stopAllEffects "stopAllEffects" method is called. - @param pitch Sets the pitch of the audio effect. The value ranges between 0.5 and 2. The default value is 1 (no change to the pitch). The lower the value, the lower the pitch. - @param pan Sets the spatial position of the audio effect. The value ranges between -1.0 and 1.0: - - 0.0: The audio effect displays ahead. - - 1.0: The audio effect displays to the right. - - -1.0: The audio effect displays to the left. - @param gain Sets the volume of the audio effect. The value ranges between 0.0 and 100.0 (default). The lower the value, the lower the volume of the audio effect. - @param publish Sets whether or not to publish the specified audio effect to the remote stream: - - true: The locally played audio effect is published to the Agora Cloud and the remote users can hear it. - - false: The locally played audio effect is not published to the Agora Cloud and the remote users cannot hear it. - - @return - - 0: Success. - - < 0: Failure. - */ - int playEffect(int soundId, const char* filePath, int loopCount, double pitch, double pan, int gain, bool publish = false) { -#if defined(_WIN32) - util::AString path; - if (!m_parameter->convertPath(filePath, path)) - filePath = path->c_str(); - else if (!filePath) - filePath = ""; -#endif - return setObject( - "che.audio.game_play_effect", - "{\"soundId\":%d,\"filePath\":\"%s\",\"loopCount\":%d, \"pitch\":%lf,\"pan\":%lf,\"gain\":%d, \"send2far\":%d}", - soundId, filePath, loopCount, pitch, pan, gain, publish); - } - - /** Stops playing a specified audio effect. - - @param soundId ID of the audio effect to stop playing. Each audio effect has a unique ID. - - @return - - 0: Success. - - < 0: Failure. - */ - int stopEffect(int soundId) { - return m_parameter ? m_parameter->setInt( - "che.audio.game_stop_effect", soundId) : -ERR_NOT_INITIALIZED; - } - - /** Stops playing all audio effects. - - @return - - 0: Success. - - < 0: Failure. - */ - int stopAllEffects() { - return m_parameter ? m_parameter->setBool( - "che.audio.game_stop_all_effects", true) : -ERR_NOT_INITIALIZED; - } - - /** Preloads a specified audio effect file into the memory. - - @note This method does not support online audio effect files. - - To ensure smooth communication, limit the size of the audio effect file. We recommend using this method to preload the audio effect before calling the \ref IRtcEngine::joinChannel "joinChannel" method. - - Supported audio formats: mp3, aac, m4a, 3gp, and wav. - - @param soundId ID of the audio effect. Each audio effect has a unique ID. - @param filePath Pointer to the absolute path of the audio effect file. - - @return - - 0: Success. - - < 0: Failure. - */ - int preloadEffect(int soundId, char* filePath) { - return setObject( - "che.audio.game_preload_effect", - "{\"soundId\":%d,\"filePath\":\"%s\"}", - soundId, filePath); - } - - /** Releases a specified preloaded audio effect from the memory. - - @param soundId ID of the audio effect. Each audio effect has a unique ID. - @return - - 0: Success. - - < 0: Failure. - */ - int unloadEffect(int soundId) { - return m_parameter ? m_parameter->setInt( - "che.audio.game_unload_effect", soundId) : -ERR_NOT_INITIALIZED; - } - - /** Pauses a specified audio effect. - - @param soundId ID of the audio effect. Each audio effect has a unique ID. - @return - - 0: Success. - - < 0: Failure. - */ - int pauseEffect(int soundId) { - return m_parameter ? m_parameter->setInt( - "che.audio.game_pause_effect", soundId) : -ERR_NOT_INITIALIZED; - } - - /** Pauses all audio effects. - - @return - - 0: Success. - - < 0: Failure. - */ - int pauseAllEffects() { - return m_parameter ? m_parameter->setBool( - "che.audio.game_pause_all_effects", true) : -ERR_NOT_INITIALIZED; - } - - /** Resumes playing a specified audio effect. - - @param soundId ID of the audio effect. Each audio effect has a unique ID. - @return - - 0: Success. - - < 0: Failure. - */ - int resumeEffect(int soundId) { - return m_parameter ? m_parameter->setInt( - "che.audio.game_resume_effect", soundId) : -ERR_NOT_INITIALIZED; - } - - /** Resumes playing all audio effects. - - @return - - 0: Success. - - < 0: Failure. - */ - int resumeAllEffects() { - return m_parameter ? m_parameter->setBool( - "che.audio.game_resume_all_effects", true) : -ERR_NOT_INITIALIZED; - } - - /** Enables/Disables stereo panning for remote users. - - Ensure that you call this method before joinChannel to enable stereo panning for remote users so that the local user can track the position of a remote user by calling \ref agora::rtc::IRtcEngine::setRemoteVoicePosition "setRemoteVoicePosition". - - @param enabled Sets whether or not to enable stereo panning for remote users: - - true: enables stereo panning. - - false: disables stereo panning. - - @return - - 0: Success. - - < 0: Failure. - */ - int enableSoundPositionIndication(bool enabled) { - return m_parameter ? m_parameter->setBool( - "che.audio.enable_sound_position", enabled) : -ERR_NOT_INITIALIZED; - } - - /** Sets the sound position and gain of a remote user. - - When the local user calls this method to set the sound position of a remote user, the sound difference between the left and right channels allows the local user to track the real-time position of the remote user, creating a real sense of space. This method applies to massively multiplayer online games, such as Battle Royale games. - - @note - - For this method to work, enable stereo panning for remote users by calling enableSoundPositionIndication before joining a channel. - - This method requires hardware support. For the best sound positioning, we recommend using a stereo speaker. - - @param uid The ID of the remote user. - @param pan The sound position of the remote user. The value ranges from -1.0 to 1.0: - - 0.0: the remote sound comes from the front. - - -1.0: the remote sound comes from the left. - - 1.0: the remote sound comes from the right. - @param gain Gain of the remote user. The value ranges from 0.0 to 100.0. The default value is 100.0 (the original gain of the remote user). The smaller the value, the less the gain. - - @return - - 0: Success. - - < 0: Failure. - */ - int setRemoteVoicePosition(int uid, double pan, double gain) { - return setObject("che.audio.game_place_sound_position", "{\"uid\":%d,\"pan\":%lf,\"gain\":%lf}", uid, pan, gain); - } - - /** Changes the voice pitch of the local speaker. - - @param pitch Sets the voice pitch. The value ranges between 0.5 and 2.0. The lower the value, the lower the voice pitch. The default value is 1.0 (no change to the local voice pitch). - @return - - 0: Success. - - < 0: Failure. - */ - int setLocalVoicePitch(double pitch) { - return m_parameter ? m_parameter->setInt( - "che.audio.morph.pitch_shift", - static_cast(pitch * 100)) : -ERR_NOT_INITIALIZED; - } - /** Sets the local voice equalization effect. - - @param bandFrequency Sets the band frequency. The value ranges between 0 and 9, representing the respective 10-band center frequencies of the voice effects, including 31, 62, 125, 500, 1k, 2k, 4k, 8k, and 16k Hz. See #AUDIO_EQUALIZATION_BAND_FREQUENCY. - @param bandGain Sets the gain of each band in dB. The value ranges between -15 and 15. - - @return - - 0: Success. - - < 0: Failure. - */ - int setLocalVoiceEqualization(AUDIO_EQUALIZATION_BAND_FREQUENCY bandFrequency, int bandGain) { - return setObject( - "che.audio.morph.equalization", - "{\"index\":%d,\"gain\":%d}", - static_cast(bandFrequency), bandGain); - } - /** Sets the local voice reverberation. - - v2.4.0 adds the \ref agora::rtc::IRtcEngine::setLocalVoiceReverbPreset "setLocalVoiceReverbPreset" method, a more user-friendly method for setting the local voice reverberation. You can use this method to set the local reverberation effect, such as pop music, R&B, rock music, and hip-hop. - - @param reverbKey Sets the reverberation key. See #AUDIO_REVERB_TYPE. - @param value Sets the value of the reverberation key. - - @return - - 0: Success. - - < 0: Failure. - */ - int setLocalVoiceReverb(AUDIO_REVERB_TYPE reverbKey, int value) { - return setObject( - "che.audio.morph.reverb", - "{\"key\":%d,\"value\":%d}", - static_cast(reverbKey), value); - } - - /** Sets the local voice changer option. - - @note Do not use this method together with the \ref agora::rtc::IRtcEngine::setLocalVoiceReverbPreset "setLocalVoiceReverbPreset" method, because the method called later overrides the one called earlier. - - - @param voiceChanger Sets the local voice changer option. See #VOICE_CHANGER_PRESET. - - @return - - 0: Success. - - < 0: Failure. - */ - int setLocalVoiceChanger(VOICE_CHANGER_PRESET voiceChanger) { - return m_parameter ? m_parameter->setInt("che.audio.morph.voice_changer", static_cast(voiceChanger)) : -ERR_NOT_INITIALIZED; - } - - /** Sets the preset local voice reverberation effect. - - @note - - Do not use this method together with \ref agora::rtc::IRtcEngine::setLocalVoiceReverb "setLocalVoiceReverb". - - Do not use this method together with the \ref agora::rtc::IRtcEngine::setLocalVoiceChanger "setLocalVoiceChanger" method, because the method called later overrides the one called earlier. - - - @param reverbPreset Sets the preset audio reverberation configuration. See #AUDIO_REVERB_PRESET. - - @return - - 0: Success. - - < 0: Failure. - */ - int setLocalVoiceReverbPreset(AUDIO_REVERB_PRESET reverbPreset) { - return m_parameter ? m_parameter->setInt("che.audio.morph.reverb_preset", static_cast(reverbPreset)) : -ERR_NOT_INITIALIZED; - } - - - /** **DEPRECATED** Use \ref IRtcEngine::disableAudio "disableAudio" instead. Disables the audio function in the channel. - - @return - - 0: Success. - - < 0: Failure. - */ - int pauseAudio() { - return m_parameter ? m_parameter->setBool("che.pause.audio", true) : -ERR_NOT_INITIALIZED; - } - - /** **DEPRECATED** Use the \ref IRtcEngine::enableAudio "enableAudio" method instead. - - Resumes playing the audio in the channel. - @return - - 0: Success. - - < 0: Failure. - */ - int resumeAudio() { - return m_parameter ? m_parameter->setBool("che.pause.audio", false) : -ERR_NOT_INITIALIZED; - } - - /** **DEPRECATED** Agora does not recommend using this method. - - Sets the high-quality audio preferences. Call this method and set all parameters before joining a channel. - - Do not call this method again after joining a channel. - - @param fullband Sets whether to enable/disable full-band codec (48-kHz sample rate). Not compatible with SDK versions before v1.7.4: - - true: Enable full-band codec. - - false: Disable full-band codec. - @param stereo Sets whether to enable/disable stereo codec. Not compatible with SDK versions before v1.7.4: - - true: Enable stereo codec. - - false: Disable stereo codec. - @param fullBitrate Sets whether to enable/disable high-bitrate mode. Recommended in voice-only mode: - - true: Enable high-bitrate mode. - - false: Disable high-bitrate mode. - - @return - - 0: Success. - - < 0: Failure. - */ - int setHighQualityAudioParameters(bool fullband, bool stereo, bool fullBitrate) { - return setObject("che.audio.codec.hq", "{\"fullband\":%s,\"stereo\":%s,\"fullBitrate\":%s}", fullband ? "true" : "false", stereo ? "true" : "false", fullBitrate ? "true" : "false"); - } - - /** Adjusts the recording volume. - - @param volume Recording volume. The value ranges between 0 and 400: - - 0: Mute. - - 100: Original volume. - - 400: (Maximum) Four times the original volume with signal clipping protection. - - @return - - 0: Success. - - < 0: Failure. - */ - int adjustRecordingSignalVolume(int volume) {//[0, 400]: e.g. 50~0.5x 100~1x 400~4x - if (volume < 0) - volume = 0; - else if (volume > 400) - volume = 400; - return m_parameter ? m_parameter->setInt("che.audio.record.signal.volume", volume) : -ERR_NOT_INITIALIZED; - } - - /** Adjusts the playback volume. - - @param volume Playback volume. The value ranges between 0 and 400: - - 0: Mute. - - 100: Original volume. - - 400: (Maximum) Four times the original volume with signal clipping protection. - - @return - - 0: Success. - - < 0: Failure. - */ - int adjustPlaybackSignalVolume(int volume) {//[0, 400] - if (volume < 0) - volume = 0; - else if (volume > 400) - volume = 400; - return m_parameter ? m_parameter->setInt("che.audio.playout.signal.volume", volume) : -ERR_NOT_INITIALIZED; - } - - /** Enables the \ref agora::rtc::IRtcEngineEventHandler::onAudioVolumeIndication "onAudioVolumeIndication" callback at a set time interval to report on which users are speaking and the speakers' volume. - - Once this method is enabled, the SDK returns the volume indication in the \ref agora::rtc::IRtcEngineEventHandler::onAudioVolumeIndication "onAudioVolumeIndication" callback at the set time interval, whether or not any user is speaking in the channel. - - @param interval Sets the time interval between two consecutive volume indications: - - ≤ 0: Disables the volume indication. - - > 0: Time interval (ms) between two consecutive volume indications. We recommend setting @p interval > 200 ms. Do not set @p interval < 10 ms, or the *onAudioVolumeIndication* callback will not be triggered. - @param smooth Smoothing factor sets the sensitivity of the audio volume indicator. The value ranges between 0 and 10. The greater the value, the more sensitive the indicator. The recommended value is 3. - - @return - - 0: Success. - - < 0: Failure. - */ - int enableAudioVolumeIndication(int interval, int smooth) { // in ms: <= 0: disable, > 0: enable, interval in ms - if (interval < 0) - interval = 0; - return setObject("che.audio.volume_indication", "{\"interval\":%d,\"smooth\":%d}", interval, smooth); - } - - /** Stops/Resumes sending the local audio stream. - - @note When @p mute is set as @p true, this method does not disable the microphone, which does not affect any ongoing recording. - - @param mute Sets whether to send/stop sending the local audio stream: - - true: Stops sending the local audio stream. - - false: (Default) Sends the local audio stream. - - @return - - 0: Success. - - < 0: Failure. - */ - int muteLocalAudioStream(bool mute) { - return setParameters("{\"rtc.audio.mute_me\":%s,\"che.audio.mute_me\":%s}", mute ? "true" : "false", mute ? "true" : "false"); - } - // mute/unmute all peers. unmute will clear all muted peers specified mutePeer() interface - - /** Stops/Resumes receiving a specified remote user's audio stream. - - @note If you called the \ref agora::rtc::IRtcEngine::muteAllRemoteAudioStreams "muteAllRemoteAudioStreams" method and set @p mute as @p true to stop receiving all remote users' audio streams, call the *muteAllRemoteAudioStreams* method and set @p mute as @p false before calling this method. The *muteAllRemoteAudioStreams* method sets all remote audio streams, while the *muteRemoteAudioStream* method sets a specified remote audio stream. - - @param uid User ID of the specified remote user sending the audio. - @param mute Sets whether to receive/stop receiving a specified remote user's audio stream: - - true: Stops receiving the specified remote user's audio stream. - - false: (Default) Receives the specified remote user's audio stream. - - @return - - 0: Success. - - < 0: Failure. - - */ - int muteRemoteAudioStream(uid_t uid, bool mute) { - return setObject("rtc.audio.mute_peer", "{\"uid\":%u,\"mute\":%s}", uid, mute?"true":"false"); - } - - /** Stops/Resumes receiving all remote users' audio streams. - - @param mute Sets whether to receive/stop receiving all remote users' audio streams. - - true: Stops receiving all remote users' audio streams. - - false: (Default) Receives all remote users' audio streams. - - @return - - 0: Success. - - < 0: Failure. - */ - int muteAllRemoteAudioStreams(bool mute) { - return m_parameter ? m_parameter->setBool("rtc.audio.mute_peers", mute) : -ERR_NOT_INITIALIZED; - } - - /** Stops/Resumes receiving all remote users' audio streams by default. - - @param mute Sets whether to receive/stop receiving all remote users' audio streams by default: - - true: Stops receiving all remote users' audio streams by default. - - false: (Default) Receives all remote users' audio streams by default. - - @return - - 0: Success. - - < 0: Failure. - */ - int setDefaultMuteAllRemoteAudioStreams(bool mute) { - return m_parameter ? m_parameter->setBool("rtc.audio.set_default_mute_peers", mute) : -ERR_NOT_INITIALIZED; - } - - /** Sets the external audio source. - - @param enabled Sets whether to enable/disable the external audio source: - - true: Enables the external audio source. - - false: (Default) Disables the external audio source. - @param sampleRate Sets the sample rate of the external audio source, which can be set as 8000, 16000, 32000, 44100, or 48000 Hz. - @param channels Sets the audio channels of the external audio source (two channels maximum). - @return - - 0: Success. - - < 0: Failure. - */ - int setExternalAudioSource(bool enabled, int sampleRate, int channels) { - if (enabled) - return setParameters("{\"che.audio.external_capture\":true,\"che.audio.external_capture.push\":true,\"che.audio.set_capture_raw_audio_format\":{\"sampleRate\":%d,\"channelCnt\":%d,\"mode\":%d}}", sampleRate, channels, RAW_AUDIO_FRAME_OP_MODE_TYPE::RAW_AUDIO_FRAME_OP_MODE_READ_WRITE); - else - return setParameters("{\"che.audio.external_capture\":false,\"che.audio.external_capture.push\":false}"); - } - - /** Sets the external audio sink. - - If you enable the external audio sink, you can pull the audio frame by periodically calling the \ref agora::media::IMediaEngine::pullAudioFrame "pullAudioFrame" method. - - @param enabled - - true: Enables the external audio sink. - - false: Disables the external audio sink. - @param sampleRate Sets the sample rate of the external audio sink, which can be set as 8000, 16000, 32000, 44100, or 48000 Hz. - @param channels Sets the audio channels of the external audio sink (two channels maximum). - - @note Enabling the external audio sink disables the "Raw Audio Data" method, and the application will not retrieve the audio frame from the \ref agora::media::IAudioFrameObserver::onPlaybackAudioFrame "onPlaybackAudioFrame" callback. - @return - - 0: Success. - - < 0: Failure. - */ - int setExternalAudioSink(bool enabled, int sampleRate, int channels) { - if (enabled) - return setParameters("{\"che.audio.external_render\":true,\"che.audio.external_render.pull\":true,\"che.audio.set_render_raw_audio_format\":{\"sampleRate\":%d,\"channelCnt\":%d,\"mode\":%d}}", sampleRate, channels, RAW_AUDIO_FRAME_OP_MODE_TYPE::RAW_AUDIO_FRAME_OP_MODE_READ_ONLY); - else - return setParameters("{\"che.audio.external_render\":false,\"che.audio.external_render.pull\":false}"); - } - - /** Specifies an SDK output log file. - - The log file records all SDK operations during runtime. If it does not exist, the SDK creates one. - - @note - - The default log file is located at: C:\Users\\AppData\Local\Agora\. - - Ensure that you call this method immediately after calling the \ref agora::rtc::IRtcEngine::initialize "initialize" method, otherwise the output log may not be complete. - - @param filePath File path of the log file. The string of the log file is in UTF-8. - - @return - - 0: Success. - - < 0: Failure. - */ - int setLogFile(const char* filePath) { - if (!m_parameter) return -ERR_NOT_INITIALIZED; -#if defined(_WIN32) - util::AString path; - if (!m_parameter->convertPath(filePath, path)) - filePath = path->c_str(); - else if (!filePath) - filePath = ""; -#endif - return m_parameter->setString("rtc.log_file", filePath); - } - - /** Sets the output log level of the SDK. - - You can use one or a combination of the log filter levels. The log level follows the sequence of OFF, CRITICAL, ERROR, WARNING, INFO, and DEBUG. Choose a level to see the logs preceding that level. - - If you set the log level to WARNING, you see the logs within levels CRITICAL, ERROR, and WARNING. - - @param filter Sets the log filter level. See #LOG_FILTER_TYPE. - - @return - - 0: Success. - - < 0: Failure. - */ - int setLogFilter(unsigned int filter) { - return m_parameter ? m_parameter->setUInt("rtc.log_filter", filter&LOG_FILTER_MASK) : -ERR_NOT_INITIALIZED; - } - - /** Sets the log file size (KB). - - The SDK has two log files, each with a default size of 512 KB. If you set @p fileSizeInBytes as 1024 KB, the SDK outputs log files with a total maximum size of 2 MB. If the total size of the log files exceed the set value, the new output log files overwrite the old output log files. - - @param fileSizeInKBytes The SDK log file size (KB). - @return - - 0: Success. - - <0: Failure. - */ - int setLogFileSize(unsigned int fileSizeInKBytes) { - return m_parameter ? m_parameter->setUInt("rtc.log_size", fileSizeInKBytes) : -ERR_NOT_INITIALIZED; - } - - /** Sets the local video display mode. - - This method can be called multiple times during a call to change the display mode. - - @param renderMode Sets the local video display mode. See #RENDER_MODE_TYPE. - @return - - 0: Success. - - < 0: Failure. - */ - int setLocalRenderMode(RENDER_MODE_TYPE renderMode) { - return setRemoteRenderMode(0, renderMode); - } - - /** Sets the video display mode of a specified remote user. - - This method can be called multiple times during a call to change the display mode. - - @param uid ID of the remote user. - @param renderMode Sets the video display mode. See #RENDER_MODE_TYPE. - @return - - 0: Success. - - < 0: Failure. - */ - int setRemoteRenderMode(uid_t uid, RENDER_MODE_TYPE renderMode) { - return setObject("che.video.render_mode", "{\"uid\":%u,\"mode\":%d}", uid, renderMode); - } - - /** Sets the camera capturer configuration. - - For a video call or live broadcast, generally the SDK controls the camera output parameters. When the default camera capturer settings do not meet special requirements or cause performance problems, we recommend using this method to set the camera capturer configuration: - - - If the resolution or frame rate of the captured raw video data are higher than those set by \ref IRtcEngine::setVideoEncoderConfiguration "setVideoEncoderConfiguration", processing video frames requires extra CPU and RAM usage and degrades performance. We recommend setting config as CAPTURER_OUTPUT_PREFERENCE_PERFORMANCE = 1 to avoid such problems. - - If you do not need local video preview or are willing to sacrifice preview quality, we recommend setting config as CAPTURER_OUTPUT_PREFERENCE_PERFORMANCE = 1 to optimize CPU and RAM usage. - - If you want better quality for the local video preview, we recommend setting config as CAPTURER_OUTPUT_PREFERENCE_PREVIEW = 2. - - @note Call this method before enabling the local camera. That said, you can call this method before calling \ref agora::rtc::IRtcEngine::joinChannel "joinChannel", \ref agora::rtc::IRtcEngine::enableVideo "enableVideo", or \ref IRtcEngine::enableLocalVideo "enableLocalVideo", depending on which method you use to turn on your local camera. - - @param config Sets the camera capturer configuration. See CameraCapturerConfiguration. - - @return - - 0: Success. - - < 0: Failure. - */ - int setCameraCapturerConfiguration(const CameraCapturerConfiguration& config) { - if (!m_parameter) return -ERR_NOT_INITIALIZED; - return m_parameter->setInt("che.video.camera_capture_mode", (int)config.preference); - } - - /** Sets the stream mode to the single-stream (default) or dual-stream mode. (Live broadcast only.) - - If the dual-stream mode is enabled, the receiver can choose to receive the high stream (high-resolution and high-bitrate video stream), or the low stream (low-resolution and low-bitrate video stream). - - @param enabled Sets the stream mode: - - true: Dual-stream mode. - - false: (Default) Single-stream mode. - */ - int enableDualStreamMode(bool enabled) { - return setParameters("{\"rtc.dual_stream_mode\":%s,\"che.video.enableLowBitRateStream\":%d}", enabled ? "true" : "false", enabled ? 1 : 0); - } - - /** Sets the remote user's video stream type received by the local user when the remote user sends dual streams. - - This method allows the application to adjust the corresponding video-stream type based on the size of the video window to reduce the bandwidth and resources. - - - If the remote user enables the dual-stream mode by calling the \ref agora::rtc::IRtcEngine::enableDualStreamMode "enableDualStreamMode" method, the SDK receives the high-stream video by default. - - If the dual-stream mode is not enabled, the SDK receives the high-stream video by default. - - The method result returns in the \ref agora::rtc::IRtcEngineEventHandler::onApiCallExecuted "onApiCallExecuted" callback. The Agora SDK receives the high-stream video by default to reduce the bandwidth. If needed, users may use this method to switch to the low-stream video. - By default, the aspect ratio of the low-stream video is the same as the high-stream video. Once the resolution of the high-stream video is set, the system automatically sets the resolution, frame rate, and bitrate of the low-stream video. - - @param uid ID of the remote user sending the video stream. - @param streamType Sets the video-stream type. See #REMOTE_VIDEO_STREAM_TYPE. - @return - - 0: Success. - - < 0: Failure. - */ - int setRemoteVideoStreamType(uid_t uid, REMOTE_VIDEO_STREAM_TYPE streamType) { - return setParameters("{\"rtc.video.set_remote_video_stream\":{\"uid\":%u,\"stream\":%d}, \"che.video.setstream\":{\"uid\":%u,\"stream\":%d}}", uid, streamType, uid, streamType); -// return setObject("rtc.video.set_remote_video_stream", "{\"uid\":%u,\"stream\":%d}", uid, streamType); - } - - /** Sets the default video-stream type for the video received by the local user when the remote user sends dual streams. - - - If the dual-stream mode is enabled by calling the \ref agora::rtc::IRtcEngine::enableDualStreamMode "enableDualStreamMode" method, the user receives the high-stream video by default. The @p setRemoteDefaultVideoStreamType method allows the application to adjust the corresponding video-stream type according to the size of the video window, reducing the bandwidth and resources. - - If the dual-stream mode is not enabled, the user receives the high-stream video by default. - - The result after calling this method is returned in the \ref agora::rtc::IRtcEngineEventHandler::onApiCallExecuted "onApiCallExecuted" callback. The Agora SDK receives the high-stream video by default to reduce the bandwidth. If needed, users can switch to the low-stream video through this method. - - @param streamType Sets the default video-stream type. See #REMOTE_VIDEO_STREAM_TYPE. - - @return - - 0: Success. - - < 0: Failure. - */ - int setRemoteDefaultVideoStreamType(REMOTE_VIDEO_STREAM_TYPE streamType) { - return m_parameter ? m_parameter->setInt("rtc.video.set_remote_default_video_stream_type", streamType) : -ERR_NOT_INITIALIZED; - } - - /** Sets the audio recording format for the \ref agora::media::IAudioFrameObserver::onRecordAudioFrame "onRecordAudioFrame" callback. - - @param sampleRate Sets the sample rate (@p samplesPerSec) returned in the *onRecordAudioFrame* callback, which can be set as 8000, 16000, 32000, 44100, or 48000 Hz. - @param channel Sets the number of audio channels (@p channels) returned in the *onRecordAudioFrame* callback: - - 1: Mono - - 2: Stereo - @param mode Sets the use mode (see #RAW_AUDIO_FRAME_OP_MODE_TYPE) of the *onRecordAudioFrame* callback. - @param samplesPerCall Sets the sample points (@p samples) returned in the *onRecordAudioFrame* callback. @p samplesPerCall is usually set as 1024 for stream pushing. - - samplesPerCall = (int)(sampleRate × sampleInterval), where sampleInterval ≥ 0.01 in seconds. - - @return - - 0: Success. - - < 0: Failure. - */ - int setRecordingAudioFrameParameters(int sampleRate, int channel, RAW_AUDIO_FRAME_OP_MODE_TYPE mode, int samplesPerCall) { - return setObject("che.audio.set_capture_raw_audio_format", "{\"sampleRate\":%d,\"channelCnt\":%d,\"mode\":%d,\"samplesPerCall\":%d}", sampleRate, channel, mode, samplesPerCall); - } - /** Sets the audio playback format for the \ref agora::media::IAudioFrameObserver::onPlaybackAudioFrame "onPlaybackAudioFrame" callback. - - @param sampleRate Sets the sample rate (@p samplesPerSec) returned in the *onPlaybackAudioFrame* callback, which can be set as 8000, 16000, 32000, 44100, or 48000 Hz. - @param channel Sets the number of channels (@p channels) returned in the *onPlaybackAudioFrame* callback: - - 1: Mono - - 2: Stereo - @param mode Sets the use mode (see #RAW_AUDIO_FRAME_OP_MODE_TYPE) of the *onPlaybackAudioFrame* callback. - @param samplesPerCall Sets the sample points (*samples*) returned in the *onPlaybackAudioFrame* callback. @p samplesPerCall is usually set as 1024 for stream pushing. - - samplesPerCall = (int)(sampleRate × sampleInterval), where sampleInterval ≥ 0.01 in seconds. - - @return - - 0: Success. - - < 0: Failure. - */ - int setPlaybackAudioFrameParameters(int sampleRate, int channel, RAW_AUDIO_FRAME_OP_MODE_TYPE mode, int samplesPerCall) { - return setObject("che.audio.set_render_raw_audio_format", "{\"sampleRate\":%d,\"channelCnt\":%d,\"mode\":%d,\"samplesPerCall\":%d}", sampleRate, channel, mode, samplesPerCall); - } - /** Sets the mixed audio format for the \ref agora::media::IAudioFrameObserver::onMixedAudioFrame "onMixedAudioFrame" callback. - - @param sampleRate Sets the sample rate (@p samplesPerSec) returned in the *onMixedAudioFrame* callback, which can be set as 8000, 16000, 32000, 44100, or 48000 Hz. - @param samplesPerCall Sets the sample points (@p samples) returned in the *onMixedAudioFrame* callback. @p samplesPerCall is usually set as 1024 for stream pushing. - - samplesPerCall = (int)(sampleRate × sampleInterval), where sampleInterval ≥ 0.01 in seconds. - - @return - - 0: Success. - - < 0: Failure. - */ - int setMixedAudioFrameParameters(int sampleRate, int samplesPerCall) { - return setObject("che.audio.set_mixed_raw_audio_format", "{\"sampleRate\":%d,\"samplesPerCall\":%d}", sampleRate, samplesPerCall); - } - - /** Enables interoperability with the Agora Web SDK. - - @note This method applies only to the Live-broadcast profile. In the Communication profile, interoperability with the Agora Web SDK is enabled by default. - - @param enabled Sets whether to enable/disable interoperability with the Agora Web SDK: - - true: Enable. - - false: (Default) Disable. - - @return - - 0: Success. - - < 0: Failure. - */ - int enableWebSdkInteroperability(bool enabled) {//enable interoperability with zero-plugin web sdk - return setParameters("{\"rtc.video.web_h264_interop_enable\":%s,\"che.video.web_h264_interop_enable\":%s}", enabled ? "true" : "false", enabled ? "true" : "false"); - } - - //only for live broadcast - /** **DEPRECATED** Sets the preferences for the high-quality video. (Live broadcast only). - - This method is deprecated as of v2.4.0. - - @param preferFrameRateOverImageQuality Sets the video quality preference: - - true: Frame rate over image quality. - - false: (Default) Image quality over frame rate. - - @return - - 0: Success. - - < 0: Failure. - */ - int setVideoQualityParameters(bool preferFrameRateOverImageQuality) { - return setParameters("{\"rtc.video.prefer_frame_rate\":%s,\"che.video.prefer_frame_rate\":%s}", preferFrameRateOverImageQuality ? "true" : "false", preferFrameRateOverImageQuality ? "true" : "false"); - } - - /** Sets the local video mirror mode. - - You must call this method before calling the \ref agora::rtc::IRtcEngine::startPreview "startPreview" method, otherwise the mirror mode will not work. - - @param mirrorMode Sets the local video mirror mode. See #VIDEO_MIRROR_MODE_TYPE. - @return - - 0: Success. - - < 0: Failure. - */ - int setLocalVideoMirrorMode(VIDEO_MIRROR_MODE_TYPE mirrorMode) { - if (!m_parameter) return -ERR_NOT_INITIALIZED; - const char *value; - switch (mirrorMode) { - case VIDEO_MIRROR_MODE_AUTO: - value = "default"; - break; - case VIDEO_MIRROR_MODE_ENABLED: - value = "forceMirror"; - break; - case VIDEO_MIRROR_MODE_DISABLED: - value = "disableMirror"; - break; - default: - return -ERR_INVALID_ARGUMENT; - } - return m_parameter->setString("che.video.localViewMirrorSetting", value); - } - - /** Sets the fallback option for the locally published video stream based on the network conditions. - - The default setting for @p option is #STREAM_FALLBACK_OPTION_DISABLED, where there is no fallback behavior for the locally published video stream when the uplink network conditions are poor. - - If *option* is set as #STREAM_FALLBACK_OPTION_AUDIO_ONLY, the SDK will: - - - Disable the upstream video but enable audio only when the network conditions worsen and cannot support both video and audio. - - Re-enable the video when the network conditions improve. - - When the locally published video stream falls back to audio only or when the audio-only stream switches back to the video, the SDK triggers the \ref agora::rtc::IRtcEngineEventHandler::onLocalPublishFallbackToAudioOnly "onLocalPublishFallbackToAudioOnly" callback. - - @note Agora does not recommend using this method for CDN live streaming, because the remote CDN live user will have a noticeable lag when the locally publish stream falls back to audio-only. - - @param option Sets the fallback option for the locally published video stream. See #STREAM_FALLBACK_OPTIONS. - @return - - 0: Success. - - < 0: Failure. - */ - int setLocalPublishFallbackOption(STREAM_FALLBACK_OPTIONS option) { - return m_parameter ? m_parameter->setInt("rtc.local_publish_fallback_option", option) : -ERR_NOT_INITIALIZED; - } - - /** Sets the fallback option for the remotely subscribed video stream based on the network conditions. - - The default setting for @p option is #STREAM_FALLBACK_OPTION_VIDEO_STREAM_LOW, where the remotely subscribed video stream falls back to the low-stream video (low resolution and low bitrate) under poor downlink network conditions. - - If *option* is set as #STREAM_FALLBACK_OPTION_AUDIO_ONLY, the SDK automatically switches the video from a high-stream to a low-stream, or disables the video when the downlink network conditions cannot support both audio and video to guarantee the quality of the audio. The SDK monitors the network quality and restores the video stream when the network conditions improve. - - When the remotely subscribed video stream falls back to audio only or when the audio-only stream switches back to the video stream, the SDK triggers the \ref agora::rtc::IRtcEngineEventHandler::onRemoteSubscribeFallbackToAudioOnly "onRemoteSubscribeFallbackToAudioOnly" callback. - - @param option Sets the fallback option for the remotely subscribed video stream. See #STREAM_FALLBACK_OPTIONS. - @return - - 0: Success. - - < 0: Failure. - */ - int setRemoteSubscribeFallbackOption(STREAM_FALLBACK_OPTIONS option) { - return m_parameter ? m_parameter->setInt("rtc.remote_subscribe_fallback_option", option) : -ERR_NOT_INITIALIZED; - } - -#if (defined(__APPLE__) && TARGET_OS_MAC && !TARGET_OS_IPHONE) || defined(_WIN32) - /** Enables loopback recording. - - @param enabled Sets whether to enable/disable loopback recording: - - true: Enables loopback recording. - - false: (Default) Disables loopback recording. - @param deviceName Pointer to the device name of the sound card. The default value is NULL (the default sound card). - If you use a virtual sound card like "Soundflower", set this parameter as the name of the sound card, "Soundflower", and the SDK will find the corresponding sound card and start capturing. - @return - - 0: Success. - - < 0: Failure. - */ - int enableLoopbackRecording(bool enabled, const char* deviceName = NULL) { - if (!deviceName) { - return setParameters("{\"che.audio.loopback.recording\":%s}", enabled ? "true" : "false"); - } - else { - return setParameters("{\"che.audio.loopback.deviceName\":\"%s\",\"che.audio.loopback.recording\":%s}", deviceName, enabled ? "true" : "false"); - } - } -#endif - - /** Sets the volume of the in-ear monitor. - - @param volume Sets the volume of the in-ear monitor. The value ranges between 0 and 100 (default). - - @return - - 0: Success. - - < 0: Failure. - */ - int setInEarMonitoringVolume(int volume) { - return m_parameter ? m_parameter->setInt("che.audio.headset.monitoring.parameter", volume) : -ERR_NOT_INITIALIZED; - } - -protected: - AParameter& parameter() { - return m_parameter; - } - int setParameters(const char* format, ...) { - char buf[512]; - va_list args; - va_start(args, format); - vsnprintf(buf, sizeof(buf)-1, format, args); - va_end(args); - return m_parameter ? m_parameter->setParameters(buf) : -ERR_NOT_INITIALIZED; - } - int setObject(const char* key, const char* format, ...) { - char buf[512]; - va_list args; - va_start(args, format); - vsnprintf(buf, sizeof(buf)-1, format, args); - va_end(args); - return m_parameter ? m_parameter->setObject(key, buf) : -ERR_NOT_INITIALIZED; - } - int stopAllRemoteVideo() { - return m_parameter ? m_parameter->setBool("che.video.peer.stop_render", true) : -ERR_NOT_INITIALIZED; - } -private: - AParameter m_parameter; -}; - -} //namespace rtc -} // namespace agora - -/** Retrieves the SDK version number. - - @param build Build number of the Agora SDK. - @return String of the SDK version. - */ -#define getAgoraRtcEngineVersion getAgoraSdkVersion - -//////////////////////////////////////////////////////// -/** \addtogroup createAgoraRtcEngine - @{ - */ -//////////////////////////////////////////////////////// - -/** Creates the RtcEngine object and returns the pointer. - - @return Pointer to the RtcEngine object. - */ -AGORA_API agora::rtc::IRtcEngine* AGORA_CALL createAgoraRtcEngine(); - -//////////////////////////////////////////////////////// -/** @} */ -//////////////////////////////////////////////////////// - -#define getAgoraRtcEngineErrorDescription getAgoraSdkErrorDescription -#define setAgoraRtcEngineExternalSymbolLoader setAgoraSdkExternalSymbolLoader - -#endif diff --git a/android/src/main/cpp/include/IAgoraService.h b/android/src/main/cpp/include/IAgoraService.h deleted file mode 100644 index a607ed311..000000000 --- a/android/src/main/cpp/include/IAgoraService.h +++ /dev/null @@ -1,76 +0,0 @@ -// Agora SDK -// -// Copyright (c) 2019 Agora.io. All rights reserved. -// - -#ifndef AGORA_SERVICE_H -#define AGORA_SERVICE_H -#include "AgoraBase.h" - -namespace agora { - namespace rtc { - class IRtcEngine; - } - namespace rtm { - class IRtmService; - } -namespace base { - -struct AgoraServiceContext -{ -}; - - -class IAgoraService -{ -protected: - virtual ~IAgoraService(){} -public: - virtual void release() = 0; - - /** Initializes the engine. - - @param context RtcEngine context. - @return - - 0: Success. - - < 0: Failure. - */ - virtual int initialize(const AgoraServiceContext& context) = 0; - - /** Retrieves the SDK version number. - * @param build Build number. - * @return The current SDK version in the string format. For example, 2.4.0 - */ - virtual const char* getVersion(int* build) = 0; - - virtual rtm::IRtmService* createRtmService() = 0; -}; - -} //namespace base -} // namespace agora - -/** Gets the SDK version number. - - @param build Build number of the Agora SDK. - @return - - 0: Success. - - < 0: Failure. -*/ -AGORA_API const char* AGORA_CALL getAgoraSdkVersion(int* build); - -/** -* Creates the RtcEngine object and returns the pointer. -* @param err Error code -* @return returns Description of the error code -*/ -AGORA_API const char* AGORA_CALL getAgoraSdkErrorDescription(int err); - -/** -* Creates the Agora Service object and returns the pointer. -* @return returns Pointer of the Agora Service object -*/ -AGORA_API agora::base::IAgoraService* AGORA_CALL createAgoraService(); - -AGORA_API int AGORA_CALL setAgoraSdkExternalSymbolLoader(void* (*func)(const char* symname)); - -#endif diff --git a/android/src/main/cpp/include/VMUtil.h b/android/src/main/cpp/include/VMUtil.h deleted file mode 100644 index 4adb4c9cc..000000000 --- a/android/src/main/cpp/include/VMUtil.h +++ /dev/null @@ -1,53 +0,0 @@ -#ifndef __VM_UTIL_H__ -#define __VM_UTIL_H__ - -#include -#include - -#include - -#include -#include - -#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, "AG_EX_AV", __VA_ARGS__) -#define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, "AG_EX_AV", __VA_ARGS__) -#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, "AG_EX_AV", __VA_ARGS__) -#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, "AG_EX_AV", __VA_ARGS__) - -#define TRUE true -#define FALSE false - -#define CHECK_POINTER(pValue, rValue, ...) if (NULL == pValue) { \ - LOGE(__VA_ARGS__); \ - return rValue; } - -class AttachThreadScoped -{ -public: - explicit AttachThreadScoped(JavaVM* jvm) - : attached_(false), jvm_(jvm), env_(nullptr) { - jint ret_val = jvm->GetEnv(reinterpret_cast(&env_), - JNI_VERSION_1_6); - if (ret_val == JNI_EDETACHED) { - // Attach the thread to the Java VM. - ret_val = jvm_->AttachCurrentThread(&env_, nullptr); - attached_ = ret_val >= 0; - assert(attached_); - } - } - - ~AttachThreadScoped() { - if (attached_ && (jvm_->DetachCurrentThread() < 0)) { - assert(false); - } - } - - JNIEnv* env() { return env_; } - -private: - bool attached_; - JavaVM* jvm_; - JNIEnv* env_; -}; - -#endif // __VM_UTIL_H__ \ No newline at end of file diff --git a/android/src/main/cpp/src/agora_media_pre_processing.cpp b/android/src/main/cpp/src/agora_media_pre_processing.cpp deleted file mode 100644 index 9489d3ab4..000000000 --- a/android/src/main/cpp/src/agora_media_pre_processing.cpp +++ /dev/null @@ -1,327 +0,0 @@ -// -// Created by LY on 2019-08-21. -// - -#include -#include -#include -#include "../include/IAgoraMediaEngine.h" - -#include "../include/IAgoraRtcEngine.h" -#include -#include "agora_media_pre_processing.h" -#include "../include/VMUtil.h" - -#include - -using namespace std; - -jobject gCallBack = nullptr; -jclass gCallbackClass = nullptr; -jmethodID recordAudioMethodId = nullptr; -jmethodID playbackAudioMethodId = nullptr; -jmethodID playBeforeMixAudioMethodId = nullptr; -jmethodID mixAudioMethodId = nullptr; -jmethodID captureVideoMethodId = nullptr; -jmethodID renderVideoMethodId = nullptr; -void *_javaDirectPlayBufferCapture = nullptr; -void *_javaDirectPlayBufferRecordAudio = nullptr; -void *_javaDirectPlayBufferPlayAudio = nullptr; -void *_javaDirectPlayBufferBeforeMixAudio = nullptr; -void *_javaDirectPlayBufferMixAudio = nullptr; -map decodeBufferMap; - -static JavaVM *gJVM = nullptr; - -class AgoraVideoFrameObserver : public agora::media::IVideoFrameObserver { - -public: - AgoraVideoFrameObserver() { - - } - - ~AgoraVideoFrameObserver() { - - } - - void - getVideoFrame(VideoFrame &videoFrame, _jmethodID *jmethodID, void *_byteBufferObject, unsigned int uid) { - - if (_byteBufferObject) { - int width = videoFrame.width; - int height = videoFrame.height; - size_t widthAndHeight = (size_t) videoFrame.yStride * height; - size_t length = widthAndHeight * 3 / 2; - - AttachThreadScoped ats(gJVM); - JNIEnv *env = ats.env(); - - memcpy(_byteBufferObject, videoFrame.yBuffer, widthAndHeight); - memcpy((uint8_t *) _byteBufferObject + widthAndHeight, videoFrame.uBuffer, - widthAndHeight / 4); - memcpy((uint8_t *) _byteBufferObject + widthAndHeight * 5 / 4, videoFrame.vBuffer, - widthAndHeight / 4); - - if (uid == 0) { - env->CallVoidMethod(gCallBack, jmethodID, videoFrame.type, width, height, length, - videoFrame.yStride, videoFrame.uStride, - videoFrame.vStride, videoFrame.rotation, - videoFrame.renderTimeMs); - } else { - env->CallVoidMethod(gCallBack, jmethodID, uid, videoFrame.type, width, height, - length, - videoFrame.yStride, videoFrame.uStride, - videoFrame.vStride, videoFrame.rotation, - videoFrame.renderTimeMs); - } - } - - } - - void writebackVideoFrame(VideoFrame &videoFrame, void *byteBuffer) { - if (byteBuffer == nullptr) { - return; - } - - int width = videoFrame.width; - int height = videoFrame.height; - size_t widthAndHeight = (size_t) videoFrame.yStride * height; - - memcpy(videoFrame.yBuffer, byteBuffer, widthAndHeight); - memcpy(videoFrame.uBuffer, (uint8_t *) byteBuffer + widthAndHeight, widthAndHeight / 4); - memcpy(videoFrame.vBuffer, (uint8_t *) byteBuffer + widthAndHeight * 5 / 4, - widthAndHeight / 4); - } - -public: - virtual bool onCaptureVideoFrame(VideoFrame &videoFrame) override { - getVideoFrame(videoFrame, captureVideoMethodId, _javaDirectPlayBufferCapture, 0); - writebackVideoFrame(videoFrame, _javaDirectPlayBufferCapture); - return true; - } - - virtual bool onRenderVideoFrame(unsigned int uid, VideoFrame &videoFrame) override { - map::iterator it_find; - it_find = decodeBufferMap.find(uid); - - if (it_find != decodeBufferMap.end()) { - if (it_find->second != nullptr) { - getVideoFrame(videoFrame, renderVideoMethodId, it_find->second, uid); - writebackVideoFrame(videoFrame, it_find->second); - } - } - - return true; - } - -}; - - -class AgoraAudioFrameObserver : public agora::media::IAudioFrameObserver { - -public: - AgoraAudioFrameObserver() { - gCallBack = nullptr; - } - - ~AgoraAudioFrameObserver() { - } - - void getAudioFrame(AudioFrame &audioFrame, _jmethodID *jmethodID, void *_byteBufferObject, unsigned int uid) { - if (_byteBufferObject) { - AttachThreadScoped ats(gJVM); - JNIEnv *env = ats.env(); - if (env == nullptr) { - return; - } - int len = audioFrame.samples * audioFrame.bytesPerSample; - memcpy(_byteBufferObject, audioFrame.buffer, (size_t) len); // * sizeof(int16_t) - - if (uid == 0) { - env->CallVoidMethod(gCallBack, jmethodID, audioFrame.type, audioFrame.samples, - audioFrame.bytesPerSample, - audioFrame.channels, audioFrame.samplesPerSec, - audioFrame.renderTimeMs, len); - } else { - env->CallVoidMethod(gCallBack, jmethodID, uid, audioFrame.type, audioFrame.samples, - audioFrame.bytesPerSample, - audioFrame.channels, audioFrame.samplesPerSec, - audioFrame.renderTimeMs, len); - } - } - - } - - void writebackAudioFrame(AudioFrame &audioFrame, void *byteBuffer) { - if (byteBuffer == nullptr) { - return; - } - - int len = audioFrame.samples * audioFrame.bytesPerSample; - memcpy(audioFrame.buffer, byteBuffer, (size_t) len); - } - -public: - virtual bool onRecordAudioFrame(AudioFrame &audioFrame) override { - getAudioFrame(audioFrame, recordAudioMethodId, _javaDirectPlayBufferRecordAudio, 0); - writebackAudioFrame(audioFrame, _javaDirectPlayBufferRecordAudio); - return true; - } - - virtual bool onPlaybackAudioFrame(AudioFrame &audioFrame) override { - getAudioFrame(audioFrame, playbackAudioMethodId, _javaDirectPlayBufferPlayAudio, 0); - writebackAudioFrame(audioFrame, _javaDirectPlayBufferPlayAudio); - return true; - } - - virtual bool - onPlaybackAudioFrameBeforeMixing(unsigned int uid, AudioFrame &audioFrame) override { - getAudioFrame(audioFrame, playBeforeMixAudioMethodId, _javaDirectPlayBufferBeforeMixAudio, uid); - writebackAudioFrame(audioFrame, _javaDirectPlayBufferBeforeMixAudio); - return true; - } - - virtual bool onMixedAudioFrame(AudioFrame &audioFrame) override { - getAudioFrame(audioFrame, mixAudioMethodId, _javaDirectPlayBufferMixAudio, 0); - writebackAudioFrame(audioFrame, _javaDirectPlayBufferMixAudio); - return true; - } -}; - - -static AgoraAudioFrameObserver s_audioFrameObserver; - -static AgoraVideoFrameObserver s_videoFrameObserver; -static agora::rtc::IRtcEngine *rtcEngine = nullptr; - -#ifdef __cplusplus -extern "C" { -#endif - -int __attribute__((visibility("default"))) -loadAgoraRtcEnginePlugin(agora::rtc::IRtcEngine *engine) { - __android_log_print(ANDROID_LOG_DEBUG, "agora-raw-data-plugin", "loadAgoraRtcEnginePlugin"); - rtcEngine = engine; - return 0; -} - -void __attribute__((visibility("default"))) -unloadAgoraRtcEnginePlugin(agora::rtc::IRtcEngine *engine) { - __android_log_print(ANDROID_LOG_DEBUG, "agora-raw-data-plugin", "unloadAgoraRtcEnginePlugin"); - - rtcEngine = nullptr; -} - -JNIEXPORT void JNICALL -Java_com_syan_agora_media_MediaPreProcessing_setCallback(JNIEnv *env, jclass obj, - jobject callback) { - if (!rtcEngine) return; - - env->GetJavaVM(&gJVM); - - agora::util::AutoPtr mediaEngine; - mediaEngine.queryInterface(rtcEngine, agora::INTERFACE_ID_TYPE::AGORA_IID_MEDIA_ENGINE); - if (mediaEngine) { - mediaEngine->registerVideoFrameObserver(&s_videoFrameObserver); - mediaEngine->registerAudioFrameObserver(&s_audioFrameObserver); - } - - if (gCallBack == nullptr) { - gCallBack = env->NewGlobalRef(callback); - gCallbackClass = env->GetObjectClass(gCallBack); - - recordAudioMethodId = env->GetMethodID(gCallbackClass, "onRecordAudioFrame", "(IIIIIJI)V"); - playbackAudioMethodId = env->GetMethodID(gCallbackClass, "onPlaybackAudioFrame", - "(IIIIIJI)V"); - playBeforeMixAudioMethodId = env->GetMethodID(gCallbackClass, - "onPlaybackAudioFrameBeforeMixing", - "(IIIIIIJI)V"); - mixAudioMethodId = env->GetMethodID(gCallbackClass, "onMixedAudioFrame", "(IIIIIJI)V"); - - captureVideoMethodId = env->GetMethodID(gCallbackClass, "onCaptureVideoFrame", - "(IIIIIIIIJ)V"); - renderVideoMethodId = env->GetMethodID(gCallbackClass, "onRenderVideoFrame", - "(IIIIIIIIIJ)V"); - - __android_log_print(ANDROID_LOG_DEBUG, "setCallback", "setCallback done successfully"); - } -} - -JNIEXPORT void JNICALL Java_com_syan_agora_media_MediaPreProcessing_setVideoCaptureByteBuffer - (JNIEnv *env, jclass obj, jobject bytebuffer) { - _javaDirectPlayBufferCapture = env->GetDirectBufferAddress(bytebuffer); -} - -JNIEXPORT void JNICALL Java_com_syan_agora_media_MediaPreProcessing_setAudioRecordByteBuffer - (JNIEnv *env, jclass obj, jobject bytebuffer) { - _javaDirectPlayBufferRecordAudio = env->GetDirectBufferAddress(bytebuffer); -} - -JNIEXPORT void JNICALL Java_com_syan_agora_media_MediaPreProcessing_setAudioPlayByteBuffer - (JNIEnv *env, jclass obj, jobject bytebuffer) { - _javaDirectPlayBufferPlayAudio = env->GetDirectBufferAddress(bytebuffer); -} - -JNIEXPORT void JNICALL -Java_com_syan_agora_media_MediaPreProcessing_setBeforeAudioMixByteBuffer - (JNIEnv *env, jclass obj, jobject bytebuffer) { - _javaDirectPlayBufferBeforeMixAudio = env->GetDirectBufferAddress(bytebuffer); -} - -JNIEXPORT void JNICALL Java_com_syan_agora_media_MediaPreProcessing_setAudioMixByteBuffer - (JNIEnv *env, jclass obj, jobject bytebuffer) { - _javaDirectPlayBufferMixAudio = env->GetDirectBufferAddress(bytebuffer); -} - -JNIEXPORT void JNICALL -Java_com_syan_agora_media_MediaPreProcessing_setVideoDecodeByteBuffer(JNIEnv *env, - jclass type, - jint uid, - jobject byteBuffer) { - if (byteBuffer == nullptr) { - decodeBufferMap.erase(uid); - } else { - void *_javaDirectDecodeBuffer = env->GetDirectBufferAddress(byteBuffer); - decodeBufferMap.insert(make_pair(uid, _javaDirectDecodeBuffer)); - __android_log_print(ANDROID_LOG_DEBUG, "agora-raw-data-plugin", - "setVideoDecodeByteBuffer uid: %u, _javaDirectDecodeBuffer: %p", - uid, _javaDirectDecodeBuffer); - } -} - -JNIEXPORT void JNICALL -Java_com_syan_agora_media_MediaPreProcessing_releasePoint(JNIEnv *env, jclass type) { - agora::util::AutoPtr mediaEngine; - mediaEngine.queryInterface(rtcEngine, agora::INTERFACE_ID_TYPE::AGORA_IID_MEDIA_ENGINE); - - if (mediaEngine) { - mediaEngine->registerVideoFrameObserver(NULL); - mediaEngine->registerAudioFrameObserver(NULL); - } - - if (gCallBack != nullptr) { - env->DeleteGlobalRef(gCallBack); - gCallBack = nullptr; - } - gCallbackClass = nullptr; - - recordAudioMethodId = nullptr; - playbackAudioMethodId = nullptr; - playBeforeMixAudioMethodId = nullptr; - mixAudioMethodId = nullptr; - captureVideoMethodId = nullptr; - renderVideoMethodId = nullptr; - - _javaDirectPlayBufferCapture = nullptr; - _javaDirectPlayBufferRecordAudio = nullptr; - _javaDirectPlayBufferPlayAudio = nullptr; - _javaDirectPlayBufferBeforeMixAudio = nullptr; - _javaDirectPlayBufferMixAudio = nullptr; - - decodeBufferMap.clear(); -} - - -#ifdef __cplusplus -} -#endif \ No newline at end of file diff --git a/android/src/main/cpp/src/agora_media_pre_processing.h b/android/src/main/cpp/src/agora_media_pre_processing.h deleted file mode 100644 index c758184ac..000000000 --- a/android/src/main/cpp/src/agora_media_pre_processing.h +++ /dev/null @@ -1,77 +0,0 @@ -/* DO NOT EDIT THIS FILE - it is machine generated */ -#include -/* Header for class com_syan_agora_media_MediaPreProcessing */ - -#ifndef _Included_com_syan_agora_media_MediaPreProcessing -#define _Included_com_syan_agora_media_MediaPreProcessing -#ifdef __cplusplus -extern "C" { -#endif -/* - * Class: com_syan_agora_media_MediaPreProcessing - * Method: setCallback - * Signature: (Lcom/syan/agora/media/MediaPreProcessing/ProgressCallback;)V - */ -JNIEXPORT void JNICALL Java_com_syan_agora_media_MediaPreProcessing_setCallback - (JNIEnv *, jclass, jobject); - -/* - * Class: com_syan_agora_media_MediaPreProcessing - * Method: setVideoCaptureByteBuffer - * Signature: (Ljava/nio/ByteBuffer;)V - */ -JNIEXPORT void JNICALL Java_com_syan_agora_media_MediaPreProcessing_setVideoCaptureByteBuffer - (JNIEnv *, jclass, jobject); - -/* - * Class: com_syan_agora_media_MediaPreProcessing - * Method: setAudioRecordByteBuffer - * Signature: (Ljava/nio/ByteBuffer;)V - */ -JNIEXPORT void JNICALL Java_com_syan_agora_media_MediaPreProcessing_setAudioRecordByteBuffer - (JNIEnv *, jclass, jobject); - -/* - * Class: com_syan_agora_media_MediaPreProcessing - * Method: setAudioPlayByteBuffer - * Signature: (Ljava/nio/ByteBuffer;)V - */ -JNIEXPORT void JNICALL Java_com_syan_agora_media_MediaPreProcessing_setAudioPlayByteBuffer - (JNIEnv *, jclass, jobject); - -/* - * Class: com_syan_agora_media_MediaPreProcessing - * Method: setBeforeAudioMixByteBuffer - * Signature: (Ljava/nio/ByteBuffer;)V - */ -JNIEXPORT void JNICALL Java_com_syan_agora_media_MediaPreProcessing_setBeforeAudioMixByteBuffer - (JNIEnv *, jclass, jobject); - -/* - * Class: com_syan_agora_media_MediaPreProcessing - * Method: setAudioMixByteBuffer - * Signature: (Ljava/nio/ByteBuffer;)V - */ -JNIEXPORT void JNICALL Java_com_syan_agora_media_MediaPreProcessing_setAudioMixByteBuffer - (JNIEnv *, jclass, jobject); - -/* - * Class: com_syan_agora_media_MediaPreProcessing - * Method: setVideoDecodeByteBuffer - * Signature: (ILjava/nio/ByteBuffer;)V - */ -JNIEXPORT void JNICALL Java_com_syan_agora_media_MediaPreProcessing_setVideoDecodeByteBuffer - (JNIEnv *, jclass, jint, jobject); - -/* - * Class: com_syan_agora_media_MediaPreProcessing - * Method: releasePoint - * Signature: ()V - */ -JNIEXPORT void JNICALL Java_com_syan_agora_media_MediaPreProcessing_releasePoint - (JNIEnv *, jclass); - -#ifdef __cplusplus -} -#endif -#endif diff --git a/android/src/main/java/com/syan/agora/AgoraConst.java b/android/src/main/java/com/syan/agora/AgoraConst.java deleted file mode 100644 index 4d27d1a7c..000000000 --- a/android/src/main/java/com/syan/agora/AgoraConst.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.syan.agora; - -public class AgoraConst { - - public final static String AG_PREFIX = "ag_rtc"; - public final static String AGWarning = "warning"; - public final static String AGError = "error"; - public final static String AGApiCallExecute = "apiCallExecute"; - public final static String AGJoinChannelSuccess = "joinChannelSuccess"; - public final static String AGRejoinChannelSuccess = "rejoinChannelSuccess"; - public final static String AGLeaveChannel = "leaveChannel"; - public final static String AGClientRoleChanged = "clientRoleChanged"; - public final static String AGLocalUserRegistered = "localUserRegistered"; - public final static String AGUserInfoUpdated = "userInfoUpdated"; - public final static String AGUserJoined = "userJoined"; - public final static String AGUserOffline = "userOffline"; - public final static String AGConnectionStateChanged = "connectionStateChanged"; - public final static String AGConnectionLost = "connectionLost"; - public final static String AGTokenPrivilegeWillExpire = "tokenPrivilegeWillExpire"; - public final static String AGRequestToken = "requestToken"; - - public final static String AGAudioVolumeIndication = "audioVolumeIndication"; - public final static String AGActiveSpeaker = "activeSpeaker"; - public final static String AGFirstLocalAudioFrame = "firstLocalAudioFrame"; - public final static String AGFirstRemoteAudioFrame = "firstRemoteAudioFrame"; - public final static String AGFirstLocalVideoFrame = "firstLocalVideoFrame"; - public final static String AGFirstRemoteVideoFrame = "firstRemoteVideoFrame"; - public final static String AGUserMuteAudio = "userMuteAudio"; - public final static String AGVideoSizeChanged = "videoSizeChanged"; - public final static String AGRtmpStreamingStateChanged = "rtmpStreamingStateChanged"; - public final static String AGNetworkTypeChanged = "networkTypeChanged"; - public final static String AGFirstRemoteAudioDecoded = "firstRemoteAudioDecoded"; - public final static String AGMediaMetaDataReceived = "mediaMetaDataReceived"; - public final static String AGLocalVideoChanged = "localVideoChanged"; - public final static String AGRemoteVideoStateChanged = "remoteVideoStateChanged"; - public final static String AGLocalPublishFallbackToAudioOnly = "localPublishFallbackToAudioOnly"; - public final static String AGRemoteSubscribeFallbackToAudioOnly = "remoteSubscribeFallbackToAudioOnly"; - - public final static String AGAudioRouteChanged = "audioRouteChanged"; - public final static String AGCameraFocusAreaChanged = "cameraFocusAreaChanged"; - public final static String AGCameraExposureAreaChanged = "cameraExposureAreaChanged"; - public final static String AGRemoteAudioStateChanged = "remoteAudioStateChanged"; - public final static String AGLocalAudioStateChanged = "localAudioStateChanged"; - public final static String AGLocalAudioStats = "localAudioStats"; - public final static String AGMediaRelayStateChanged = "mediaRelayStateChanged"; - public final static String AGReceivedChannelMediaRelay = "receivedChannelMediaRelay"; - - public final static String AGRtcStats = "rtcStats"; - public final static String AGLastmileQuality = "lastmileQuality"; - public final static String AGNetworkQuality = "networkQuality"; - public final static String AGLocalVideoStats = "localVideoStats"; - public final static String AGRemoteVideoStats = "remoteVideoStats"; - public final static String AGRemoteAudioStats = "remoteAudioStats"; - - public final static String AGRemoteAudioMixingStart = "remoteAudioMixingStart"; - public final static String AGRemoteAudioMixingFinish = "remoteAudioMixingFinish"; - public final static String AGAudioEffectFinish = "audioEffectFinish"; - public final static String AGAudioMixingStateChanged = "audioMixingStateChanged"; - - public final static String AGStreamPublished = "streamPublished"; - public final static String AGStreamUnpublish = "streamUnpublish"; - public final static String AGTranscodingUpdate = "transcodingUpdate"; - - public final static String AGStreamInjectedStatus = "streamInjectedStatus"; - - public final static String AGReceiveStreamMessage = "receiveStreamMessage"; - public final static String AGOccurStreamMessageError = "occurStreamMessageError"; - - public final static String AGMediaEngineLoaded = "mediaEngineLoaded"; - public final static String AGMediaEngineStartCall = "mediaEngineStartCall"; - public final static String AGLastmileProbeResult = "lastmileProbeTestResult"; -} diff --git a/android/src/main/java/com/syan/agora/AgoraManager.java b/android/src/main/java/com/syan/agora/AgoraManager.java deleted file mode 100755 index 2cb177d7f..000000000 --- a/android/src/main/java/com/syan/agora/AgoraManager.java +++ /dev/null @@ -1,298 +0,0 @@ -package com.syan.agora; - -import android.content.Context; -import android.support.v7.widget.LinearLayoutCompat; -import android.util.Log; -import android.util.SparseArray; -import android.view.SurfaceView; - -import com.facebook.react.bridge.ReadableMap; -import com.facebook.react.bridge.WritableMap; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import io.agora.rtc.IMetadataObserver; -import io.agora.rtc.IRtcEngineEventHandler; -import io.agora.rtc.RtcEngine; -import io.agora.rtc.RtcEngineEx; -import io.agora.rtc.video.BeautyOptions; -import io.agora.rtc.video.VideoCanvas; -import io.agora.rtc.video.VideoEncoderConfiguration; - -import static io.agora.rtc.video.VideoEncoderConfiguration.*; - - -/** - * Created by Leon on 2017/4/9. - */ - -public class AgoraManager { - - public static AgoraManager sAgoraManager; - - public RtcEngineEx mRtcEngine; - - private Context context; - - private int mLocalUid = 0; - - private AgoraManager() { - mSurfaceViews = new SparseArray(); - } - - private SparseArray mSurfaceViews; - - public static AgoraManager getInstance() { - if (sAgoraManager == null) { - synchronized (AgoraManager.class) { - if (sAgoraManager == null) { - sAgoraManager = new AgoraManager(); - } - } - } - return sAgoraManager; - } - - private FRAME_RATE getVideoEncoderEnum (int val) { - FRAME_RATE type = FRAME_RATE.FRAME_RATE_FPS_1; - switch (val) { - case 1: - type = FRAME_RATE.FRAME_RATE_FPS_1; - break; - case 7: - type = FRAME_RATE.FRAME_RATE_FPS_7; - break; - case 10: - type = FRAME_RATE.FRAME_RATE_FPS_10; - break; - case 15: - type = FRAME_RATE.FRAME_RATE_FPS_15; - break; - case 24: - type = FRAME_RATE.FRAME_RATE_FPS_24; - break; - case 30: - type = FRAME_RATE.FRAME_RATE_FPS_30; - break; - } - return type; - } - - private ORIENTATION_MODE getOrientationModeEnum (int val) { - ORIENTATION_MODE type = ORIENTATION_MODE.ORIENTATION_MODE_ADAPTIVE; - switch (val) { - case 0: - type = ORIENTATION_MODE.ORIENTATION_MODE_ADAPTIVE; - break; - case 1: - type = ORIENTATION_MODE.ORIENTATION_MODE_FIXED_LANDSCAPE; - break; - case 2: - type = ORIENTATION_MODE.ORIENTATION_MODE_FIXED_PORTRAIT; - break; - } - return type; - } - - /** - * initialize rtc engine - */ - public int init(Context context, IRtcEngineEventHandler mRtcEventHandler, ReadableMap options) { - //create rtcEngine instance and setup rtcEngine eventHandler - try { - this.context = context; - this.mRtcEngine = (RtcEngineEx) RtcEngineEx.create(context, options.getString("appid"), mRtcEventHandler); - this.mRtcEngine.setAppType(8); - if (options.hasKey("secret") && null != options.getString("secret")) { - mRtcEngine.setEncryptionSecret(options.getString("secret")); - if (options.hasKey("secretMode") && null != options.getString("secretMode")) { - mRtcEngine.setEncryptionMode(options.getString("secretMode")); - } - } - if (options.hasKey("channelProfile")) { - mRtcEngine.setChannelProfile(options.getInt("channelProfile")); - } - if (options.hasKey("dualStream")) { - mRtcEngine.enableDualStreamMode(options.getBoolean("dualStream")); - } - if (options.hasKey("mode")) { - Integer mode = options.getInt("mode"); - switch (mode) { - case 0: { - mRtcEngine.enableAudio(); - mRtcEngine.disableVideo(); - break; - } - case 1: { - mRtcEngine.enableVideo(); - mRtcEngine.disableAudio(); - break; - } - } - } else { - mRtcEngine.enableVideo(); - mRtcEngine.enableAudio(); - } - - if (options.hasKey("beauty") && null != options.getMap("beauty")) { - ReadableMap beauty = options.getMap("beauty"); - BeautyOptions beautyOption = new BeautyOptions(); - beautyOption.lighteningContrastLevel = beauty.getInt("lighteningContrastLevel"); - beautyOption.lighteningLevel = (float) beauty.getDouble("lighteningLevel"); - beautyOption.smoothnessLevel = (float) beauty.getDouble("smoothnessLevel"); - beautyOption.rednessLevel = (float) beauty.getDouble("rednessLevel"); - mRtcEngine.setBeautyEffectOptions(true, beautyOption); - } - - if (options.hasKey("voice") && null != options.getMap("voice")) { - ReadableMap voice = options.getMap("voice"); - final String voiceType = voice.getString("type"); - final Integer voiceValue = voice.getInt("value"); - if (voiceType.equals("changer")) { - mRtcEngine.setLocalVoiceChanger(voiceValue); - } - if (voiceType.equals("reverbPreset")) { - mRtcEngine.setLocalVoiceReverbPreset(voiceValue); - } - } - - if (options.hasKey("videoEncoderConfig") && null != options.getMap("videoEncoderConfig")) { - ReadableMap config = options.getMap("videoEncoderConfig"); - VideoEncoderConfiguration encoderConfig = new VideoEncoderConfiguration( - config.getInt("width"), - config.getInt("height"), - getVideoEncoderEnum(config.getInt("frameRate")), - config.getInt("bitrate"), - getOrientationModeEnum(config.getInt("orientationMode")) - ); - mRtcEngine.setVideoEncoderConfiguration(encoderConfig); - } - - if (options.hasKey("audioProfile") && - options.hasKey("audioScenario")) { - mRtcEngine.setAudioProfile(options.getInt("audioProfile"), options.getInt("audioScenario")); - } - - if (options.hasKey("clientRole")) { - mRtcEngine.setClientRole(options.getInt("clientRole")); - } - return mRtcEngine.enableWebSdkInteroperability(true); - } catch (Exception e) { - throw new RuntimeException("create rtc engine failed\n" + Log.getStackTraceString(e)); - } - } - - /** - * setupLocalVideo will render video from local side capture into ui layout - */ - public int setupLocalVideo(Integer mode) { - SurfaceView surfaceView = RtcEngine.CreateRendererView(context); - mSurfaceViews.put(mLocalUid, surfaceView); - return mRtcEngine.setupLocalVideo(new VideoCanvas(surfaceView, mode, mLocalUid)); - } - - /** - * setupRemoteVideo will render video from remote side capture into ui layout - */ - public int setupRemoteVideo(final int uid, final Integer mode) { - SurfaceView surfaceView = RtcEngine.CreateRendererView(context); - mSurfaceViews.put(uid, surfaceView); - return mRtcEngine.setupRemoteVideo(new VideoCanvas(surfaceView, mode, uid)); - } - - /** - * set local video render mode - * @param renderMode Integer - * @return result state - */ - public int setLocalRenderMode(final Integer renderMode) { - return mRtcEngine.setLocalRenderMode(renderMode); - } - - /** - * set remote video render mode - * @param Integer uid - * @param Integer renderMode - * @return result state - */ - public int setRemoteRenderMode(final Integer uid, final Integer renderMode) { - return mRtcEngine.setRemoteRenderMode(uid, renderMode); - } - - public int setEnableSpeakerphone(boolean enabled) { - return mRtcEngine.setEnableSpeakerphone(enabled); - } - - public int setDefaultAudioRouteToSpeakerphone(boolean enabled) { - return mRtcEngine.setDefaultAudioRoutetoSpeakerphone(enabled); - } - - public int renewToken(String token) { - return mRtcEngine.renewToken(token); - } - - public int setClientRole(int role) { - return mRtcEngine.setClientRole(role); - } - - public int enableWebSdkInteroperability(boolean enabled) { - return mRtcEngine.enableWebSdkInteroperability(enabled); - } - - public int getConnectionState() { - return mRtcEngine.getConnectionState(); - } - public int joinChannel(ReadableMap options) { - String token = options.hasKey("token") ? options.getString("token") : null; - String channelName = options.hasKey("channelName") ? options.getString("channelName") : null; - String optionalInfo = options.hasKey("optionalInfo") ? options.getString("optionalInfo") : null; - int uid = options.hasKey("uid") ? options.getInt("uid") : 0; - this.mLocalUid = uid; - return mRtcEngine.joinChannel(token, channelName, optionalInfo, uid); - } - - public int enableLastmileTest() { - return mRtcEngine.enableLastmileTest(); - } - - public int disableLastmileTest() { - return mRtcEngine.disableLastmileTest(); - } - - public int startPreview() { - return mRtcEngine.startPreview(); - } - - public int stopPreview() { - return mRtcEngine.stopPreview(); - } - - public int leaveChannel() { - return mRtcEngine.leaveChannel(); - } - - public void removeSurfaceView(int uid) { - mSurfaceViews.remove(uid); - } - - public List getSurfaceViews() { - List list = new ArrayList(); - for (int i = 0; i < mSurfaceViews.size(); i++) { - SurfaceView surfaceView = mSurfaceViews.valueAt(i); - list.add(surfaceView); - } - return list; - } - - public SurfaceView getLocalSurfaceView() { - return mSurfaceViews.get(mLocalUid); - } - - public SurfaceView getSurfaceView(int uid) { - return mSurfaceViews.get(uid); - } - - -} diff --git a/android/src/main/java/com/syan/agora/AgoraModule.java b/android/src/main/java/com/syan/agora/AgoraModule.java deleted file mode 100644 index e5bdec0a7..000000000 --- a/android/src/main/java/com/syan/agora/AgoraModule.java +++ /dev/null @@ -1,2721 +0,0 @@ -package com.syan.agora; - -import android.graphics.Rect; -import android.support.annotation.Nullable; -import android.view.SurfaceView; - -import com.facebook.react.bridge.Arguments; -import com.facebook.react.bridge.Callback; -import com.facebook.react.bridge.Promise; -import com.facebook.react.bridge.ReactApplicationContext; -import com.facebook.react.bridge.ReactContext; -import com.facebook.react.bridge.ReactContextBaseJavaModule; -import com.facebook.react.bridge.ReactMethod; -import com.facebook.react.bridge.ReadableArray; -import com.facebook.react.bridge.ReadableMap; -import com.facebook.react.bridge.WritableArray; -import com.facebook.react.bridge.WritableMap; -import com.facebook.react.modules.core.DeviceEventManagerModule; - - -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; - -import io.agora.rtc.Constants; -import io.agora.rtc.IAudioEffectManager; -import io.agora.rtc.IMetadataObserver; -import io.agora.rtc.IRtcEngineEventHandler; -import io.agora.rtc.RtcEngine; -import io.agora.rtc.RtcEngineEx; -import io.agora.rtc.internal.LastmileProbeConfig; -import io.agora.rtc.live.LiveInjectStreamConfig; -import io.agora.rtc.live.LiveTranscoding; -import io.agora.rtc.models.UserInfo; -import io.agora.rtc.video.AgoraImage; -import io.agora.rtc.video.BeautyOptions; -import io.agora.rtc.video.CameraCapturerConfiguration; -import io.agora.rtc.video.ChannelMediaInfo; -import io.agora.rtc.video.ChannelMediaRelayConfiguration; -import io.agora.rtc.video.VideoEncoderConfiguration; -import io.agora.rtc.video.WatermarkOptions; - -import static com.facebook.react.bridge.UiThreadUtil.runOnUiThread; -import static com.syan.agora.AgoraConst.*; - -public class AgoraModule extends ReactContextBaseJavaModule { - - private static final String FPS1 = "FPS1"; - private static final String FPS7 = "FPS7"; - private static final String FPS10 = "FPS10"; - private static final String FPS15 = "FPS15"; - private static final String FPS24 = "FPS24"; - private static final String FPS30 = "FPS30"; - private static final String FPS60 = "FPS60"; - private static final String Adaptative = "Adaptative"; - private static final String FixedLandscape = "FixedLandscape"; - private static final String FixedPortrait = "FixedPortrait"; - private static final String Host = "Host"; - private static final String Audience = "Audience"; - private static final String UserOfflineReasonQuit = "UserOfflineReasonQuit"; - private static final String UserOfflineReasonDropped = "UserOfflineReasonDropped"; - private static final String UserOfflineReasonBecomeAudience = "UserOfflineReasonBecomeAudience"; - private static final String AudioSampleRateType32000 = "AudioSampleRateType32000"; - private static final String AudioSampleRateType44100 = "AudioSampleRateType44100"; - private static final String AudioSampleRateType48000 = "AudioSampleRateType48000"; - private static final String CodecTypeBaseLine = "CodecTypeBaseLine"; - private static final String CodecTypeMain = "CodecTypeMain"; - private static final String CodecTypeHigh = "CodecTypeHigh"; - private static final String QualityLow = "QualityLow"; - private static final String QualityMedium = "QualityMedium"; - private static final String QualityHigh = "QualityHigh"; - private static final String Disconnected = "Disconnected"; - private static final String Connecting = "Connecting"; - private static final String Connected = "Connected"; - private static final String Reconnecting = "Reconnecting"; - private static final String ConnectionFailed = "ConnectionFailed"; - private static final String ConnectionChangedConnecting = "ConnectionChangedConnecting"; - private static final String ConnectionChangedJoinSuccess = "ConnectionChangedJoinSuccess"; - private static final String ConnectionChangedInterrupted = "ConnectionChangedInterrupted"; - private static final String ConnectionChangedBannedByServer = "ConnectionChangedBannedByServer"; - private static final String ConnectionChangedJoinFailed = "ConnectionChangedJoinFailed"; - private static final String ConnectionChangedLeaveChannel = "ConnectionChangedLeaveChannel"; - private static final String AudioOutputRoutingDefault = "AudioOutputRoutingDefault"; - private static final String AudioOutputRoutingHeadset = "AudioOutputRoutingHeadset"; - private static final String AudioOutputRoutingEarpiece = "AudioOutputRoutingEarpiece"; - private static final String AudioOutputRoutingHeadsetNoMic = "AudioOutputRoutingHeadsetNoMic"; - private static final String AudioOutputRoutingSpeakerphone = "AudioOutputRoutingSpeakerphone"; - private static final String AudioOutputRoutingLoudspeaker = "AudioOutputRoutingLoudspeaker"; - private static final String AudioOutputRoutingHeadsetBluetooth = "AudioOutputRoutingHeadsetBluetooth"; - private static final String NetworkQualityUnknown = "NetworkQualityUnknown"; - private static final String NetworkQualityExcellent = "NetworkQualityExcellent"; - private static final String NetworkQualityGood = "NetworkQualityGood"; - private static final String NetworkQualityPoor = "NetworkQualityPoor"; - private static final String NetworkQualityBad = "NetworkQualityBad"; - private static final String NetworkQualityVBad = "NetworkQualityVBad"; - private static final String NetworkQualityDown = "NetworkQualityDown"; - private static final String AudioProfileDefault = "AudioProfileDefault"; - private static final String AudioProfileSpeechStandard = "AudioProfileSpeechStandard"; - private static final String AudioProfileMusicStandard = "AudioProfileMusicStandard"; - private static final String AgoraAudioProfileMusicStandardStereo = "AudioProfileMusicStandardStereo"; - private static final String AudioProfileMusicHighQuality = "AudioProfileMusicHighQuality"; - private static final String AudioProfileMusicHighQualityStereo = "AudioProfileMusicHighQualityStereo"; - private static final String AudioScenarioDefault = "AudioScenarioDefault"; - private static final String AudioScenarioChatRoomEntertainment = "AudioScenarioChatRoomEntertainment"; - private static final String AudioScenarioEducation = "AudioScenarioEducation"; - private static final String AudioScenarioGameStreaming = "AudioScenarioGameStreaming"; - private static final String AudioScenarioShowRoom = "AudioScenarioShowRoom"; - private static final String AudioScenarioChatRoomGaming = "AudioScenarioChatRoomGaming"; - private static final String AudioEqualizationBand31 = "AudioEqualizationBand31"; - private static final String AudioEqualizationBand62 = "AudioEqualizationBand62"; - private static final String AudioEqualizationBand125 = "AudioEqualizationBand125"; - private static final String AudioEqualizationBand250 = "AudioEqualizationBand250"; - private static final String AudioEqualizationBand500 = "AudioEqualizationBand500"; - private static final String AudioEqualizationBand1K = "AudioEqualizationBand1K"; - private static final String AudioEqualizationBand2K = "AudioEqualizationBand2K"; - private static final String AudioEqualizationBand4K = "AudioEqualizationBand4K"; - private static final String AudioEqualizationBand8K = "AudioEqualizationBand8K"; - private static final String AudioEqualizationBand16K = "AudioEqualizationBand16K"; - private static final String AudioRawFrameOperationModeReadOnly = "AudioRawFrameOperationModeReadOnly"; - private static final String AudioRawFrameOperationModeWriteOnly = "AudioRawFrameOperationModeWriteOnly"; - private static final String AudioRawFrameOperationModeReadWrite = "AudioRawFrameOperationModeReadWrite"; - private static final String VideoStreamTypeHigh = "VideoStreamTypeHigh"; - private static final String VideoStreamTypeLow = "VideoStreamTypeLow"; - private static final String VideoMirrorModeAuto = "VideoMirrorModeAuto"; - private static final String VideoMirrorModeEnabled = "VideoMirrorModeEnabled"; - private static final String VideoMirrorModeDisabled = "VideoMirrorModeDisabled"; - private static final String ChannelProfileCommunication = "ChannelProfileCommunication"; - private static final String ChannelProfileLiveBroadcasting = "ChannelProfileLiveBroadcasting"; - private static final String ChannelProfileGame = "ChannelProfileGame"; - private static final String ErrorCodeNoError = "ErrorCodeNoError"; - private static final String ErrorCodeFailed = "ErrorCodeFailed"; - private static final String ErrorCodeInvalidArgument = "ErrorCodeInvalidArgument"; - private static final String ErrorCodeTimedOut = "ErrorCodeTimedOut"; - private static final String ErrorCodeAlreadyInUse = "ErrorCodeAlreadyInUse"; - private static final String ErrorCodeEncryptedStreamNotAllowedPublished = "ErrorCodeEncryptedStreamNotAllowedPublished"; - private static final String InjectStreamStatusStartSuccess = "InjectStreamStatusStartSuccess"; - private static final String InjectStreamStatusStartAlreadyExist = "InjectStreamStatusStartAlreadyExist"; - private static final String InjectStreamStatusStartUnauthorized = "InjectStreamStatusStartUnauthorized"; - private static final String InjectStreamStatusStartTimeout = "InjectStreamStatusStartTimeout"; - private static final String InjectStreamStatusStartFailed = "InjectStreamStatusStartFailed"; - private static final String InjectStreamStatusStopSuccess = "InjectStreamStatusStopSuccess"; - private static final String InjectStreamStatusStopNotFound = "InjectStreamStatusStopNotFound"; - private static final String InjectStreamStatusStopUnauthorized = "InjectStreamStatusStopUnauthorized"; - private static final String InjectStreamStatusStopTimeout = "InjectStreamStatusStopTimeout"; - private static final String InjectStreamStatusStopFailed = "InjectStreamStatusStopFailed"; - private static final String InjectStreamStatusBroken = "InjectStreamStatusBroken"; - private static final String AgoraAudioMode = "AudioMode"; - private static final String AgoraVideoMode = "VideoMode"; - - private RtcEngine rtcEngine; - private String appId; - - public AgoraModule(ReactApplicationContext context) { - super(context); - } - - @Override - public String getName() { - return "RCTAgora"; - } - - @Override - public Map getConstants() { - final Map constants = new HashMap<>(); - - constants.put(Adaptative, VideoEncoderConfiguration.ORIENTATION_MODE.ORIENTATION_MODE_ADAPTIVE.getValue()); - constants.put(FixedLandscape, VideoEncoderConfiguration.ORIENTATION_MODE.ORIENTATION_MODE_FIXED_LANDSCAPE.getValue()); - constants.put(FixedPortrait, VideoEncoderConfiguration.ORIENTATION_MODE.ORIENTATION_MODE_FIXED_PORTRAIT.getValue()); - constants.put(Host, IRtcEngineEventHandler.ClientRole.CLIENT_ROLE_BROADCASTER); - constants.put(Audience, IRtcEngineEventHandler.ClientRole.CLIENT_ROLE_AUDIENCE); - constants.put(ChannelProfileCommunication, Constants.CHANNEL_PROFILE_COMMUNICATION); - constants.put(ChannelProfileLiveBroadcasting, Constants.CHANNEL_PROFILE_LIVE_BROADCASTING); - constants.put(ChannelProfileGame, Constants.CHANNEL_PROFILE_GAME); - constants.put(UserOfflineReasonQuit, Constants.USER_OFFLINE_QUIT); - constants.put(UserOfflineReasonDropped, Constants.USER_OFFLINE_DROPPED); - constants.put(UserOfflineReasonBecomeAudience, Constants.USER_OFFLINE_BECOME_AUDIENCE); - constants.put(Disconnected, Constants.CONNECTION_STATE_DISCONNECTED); - constants.put(Connecting, Constants.CONNECTION_STATE_CONNECTING); - constants.put(Connected, Constants.CONNECTION_STATE_CONNECTED); - constants.put(Reconnecting, Constants.CONNECTION_STATE_RECONNECTING); - constants.put(ConnectionFailed, Constants.CONNECTION_STATE_FAILED); - constants.put(ConnectionChangedConnecting, Constants.CONNECTION_CHANGED_CONNECTING); - constants.put(ConnectionChangedJoinSuccess, Constants.CONNECTION_CHANGED_JOIN_SUCCESS); - constants.put(ConnectionChangedInterrupted, Constants.CONNECTION_CHANGED_INTERRUPTED); - constants.put(ConnectionChangedBannedByServer, Constants.CONNECTION_CHANGED_BANNED_BY_SERVER); - constants.put(ConnectionChangedJoinFailed, Constants.CONNECTION_CHANGED_JOIN_FAILED); - constants.put(ConnectionChangedLeaveChannel, Constants.CONNECTION_CHANGED_LEAVE_CHANNEL); - constants.put(AudioOutputRoutingDefault, Constants.AUDIO_ROUTE_DEFAULT); - constants.put(AudioOutputRoutingHeadset, Constants.AUDIO_ROUTE_HEADSET); - constants.put(AudioOutputRoutingEarpiece, Constants.AUDIO_ROUTE_EARPIECE); - constants.put(AudioOutputRoutingHeadsetNoMic, Constants.AUDIO_ROUTE_HEADSETNOMIC); - constants.put(AudioOutputRoutingSpeakerphone, Constants.AUDIO_ROUTE_SPEAKERPHONE); - constants.put(AudioOutputRoutingLoudspeaker, Constants.AUDIO_ROUTE_LOUDSPEAKER); - constants.put(AudioOutputRoutingHeadsetBluetooth, Constants.AUDIO_ROUTE_HEADSETBLUETOOTH); - constants.put(NetworkQualityUnknown, Constants.QUALITY_UNKNOWN); - constants.put(NetworkQualityExcellent, Constants.QUALITY_EXCELLENT); - constants.put(NetworkQualityGood, Constants.QUALITY_GOOD); - constants.put(NetworkQualityPoor, Constants.QUALITY_POOR); - constants.put(NetworkQualityBad, Constants.QUALITY_BAD); - constants.put(NetworkQualityVBad, Constants.QUALITY_VBAD); - constants.put(NetworkQualityDown, Constants.QUALITY_DOWN); - constants.put(ErrorCodeNoError, Constants.ERR_OK); - constants.put(ErrorCodeFailed, Constants.ERR_FAILED); - constants.put(ErrorCodeInvalidArgument, Constants.ERR_INVALID_ARGUMENT); - constants.put(ErrorCodeTimedOut, Constants.ERR_TIMEDOUT); - constants.put(ErrorCodeAlreadyInUse, Constants.ERR_ALREADY_IN_USE); - constants.put(ErrorCodeEncryptedStreamNotAllowedPublished, Constants.ERR_ENCRYPTED_STREAM_NOT_ALLOWED_PUBLISHED); - constants.put(InjectStreamStatusStartSuccess, Constants.INJECT_STREAM_STATUS_START_SUCCESS); - constants.put(InjectStreamStatusStartAlreadyExist, Constants.INJECT_STREAM_STATUS_START_ALREADY_EXISTS); - constants.put(InjectStreamStatusStartUnauthorized, Constants.INJECT_STREAM_STATUS_START_UNAUTHORIZED); - constants.put(InjectStreamStatusStartTimeout, Constants.INJECT_STREAM_STATUS_START_TIMEDOUT); - constants.put(InjectStreamStatusStartFailed, Constants.INJECT_STREAM_STATUS_START_FAILED); - constants.put(InjectStreamStatusStopSuccess, Constants.INJECT_STREAM_STATUS_STOP_SUCCESS); - constants.put(InjectStreamStatusStopNotFound, Constants.INJECT_STREAM_STATUS_STOP_NOT_FOUND); - constants.put(InjectStreamStatusStopUnauthorized, Constants.INJECT_STREAM_STATUS_STOP_UNAUTHORIZED); - constants.put(InjectStreamStatusStopTimeout, Constants.INJECT_STREAM_STATUS_STOP_TIMEDOUT); - constants.put(InjectStreamStatusStopFailed, Constants.INJECT_STREAM_STATUS_STOP_FAILED); - constants.put(InjectStreamStatusBroken, Constants.INJECT_STREAM_STATUS_BROKEN); - constants.put(AudioSampleRateType32000, 32000); - constants.put(AudioSampleRateType44100, 44100); - constants.put(AudioSampleRateType48000, 48000); - constants.put(FPS1, VideoEncoderConfiguration.FRAME_RATE.FRAME_RATE_FPS_1.getValue()); - constants.put(FPS7, VideoEncoderConfiguration.FRAME_RATE.FRAME_RATE_FPS_7.getValue()); - constants.put(FPS10, VideoEncoderConfiguration.FRAME_RATE.FRAME_RATE_FPS_10.getValue()); - constants.put(FPS15, VideoEncoderConfiguration.FRAME_RATE.FRAME_RATE_FPS_15.getValue()); - constants.put(FPS24, VideoEncoderConfiguration.FRAME_RATE.FRAME_RATE_FPS_24.getValue()); - constants.put(FPS30, VideoEncoderConfiguration.FRAME_RATE.FRAME_RATE_FPS_30.getValue()); - constants.put(AudioProfileDefault, Constants.AUDIO_PROFILE_DEFAULT); - constants.put(AudioProfileSpeechStandard, Constants.AUDIO_PROFILE_SPEECH_STANDARD); - constants.put(AudioProfileMusicStandard, Constants.AUDIO_PROFILE_MUSIC_STANDARD); - constants.put(AgoraAudioProfileMusicStandardStereo, Constants.AUDIO_PROFILE_MUSIC_STANDARD_STEREO); - constants.put(AudioProfileMusicHighQuality, Constants.AUDIO_PROFILE_MUSIC_HIGH_QUALITY); - constants.put(AudioProfileMusicHighQualityStereo, Constants.AUDIO_PROFILE_MUSIC_HIGH_QUALITY_STEREO); - constants.put(AudioScenarioDefault, Constants.AUDIO_SCENARIO_DEFAULT); - constants.put(AudioScenarioChatRoomEntertainment, Constants.AUDIO_SCENARIO_CHATROOM_ENTERTAINMENT); - constants.put(AudioScenarioEducation, Constants.AUDIO_SCENARIO_EDUCATION); - constants.put(AudioScenarioGameStreaming, Constants.AUDIO_SCENARIO_GAME_STREAMING); - constants.put(AudioScenarioShowRoom, Constants.AUDIO_SCENARIO_SHOWROOM); - constants.put(AudioScenarioChatRoomGaming, Constants.AUDIO_SCENARIO_CHATROOM_GAMING); - constants.put(AudioEqualizationBand31, Constants.AUDIO_EQUALIZATION_BAND_31); - constants.put(AudioEqualizationBand62, Constants.AUDIO_EQUALIZATION_BAND_62); - constants.put(AudioEqualizationBand125, Constants.AUDIO_EQUALIZATION_BAND_125); - constants.put(AudioEqualizationBand250, Constants.AUDIO_EQUALIZATION_BAND_250); - constants.put(AudioEqualizationBand500, Constants.AUDIO_EQUALIZATION_BAND_500); - constants.put(AudioEqualizationBand1K, Constants.AUDIO_EQUALIZATION_BAND_1K); - constants.put(AudioEqualizationBand2K, Constants.AUDIO_EQUALIZATION_BAND_2K); - constants.put(AudioEqualizationBand4K, Constants.AUDIO_EQUALIZATION_BAND_4K); - constants.put(AudioEqualizationBand8K, Constants.AUDIO_EQUALIZATION_BAND_8K); - constants.put(AudioEqualizationBand16K, Constants.AUDIO_EQUALIZATION_BAND_16K); - constants.put(AudioRawFrameOperationModeReadOnly, Constants.RAW_AUDIO_FRAME_OP_MODE_READ_ONLY); - constants.put(AudioRawFrameOperationModeWriteOnly, Constants.RAW_AUDIO_FRAME_OP_MODE_WRITE_ONLY); - constants.put(AudioRawFrameOperationModeReadWrite, Constants.RAW_AUDIO_FRAME_OP_MODE_READ_WRITE); - constants.put(VideoStreamTypeHigh, Constants.VIDEO_STREAM_HIGH); - constants.put(VideoStreamTypeLow, Constants.VIDEO_STREAM_LOW); - constants.put(VideoMirrorModeAuto, Constants.VIDEO_MIRROR_MODE_AUTO); - constants.put(VideoMirrorModeEnabled, Constants.VIDEO_MIRROR_MODE_ENABLED); - constants.put(VideoMirrorModeDisabled, Constants.VIDEO_MIRROR_MODE_DISABLED); - constants.put(CodecTypeBaseLine, 66); - constants.put(CodecTypeMain, 77); - constants.put(CodecTypeHigh, 100); - constants.put(QualityLow, Constants.AUDIO_RECORDING_QUALITY_LOW); - constants.put(QualityMedium, Constants.AUDIO_RECORDING_QUALITY_MEDIUM); - constants.put(QualityHigh, Constants.AUDIO_RECORDING_QUALITY_HIGH); - constants.put(AgoraAudioMode, 0); - constants.put(AgoraVideoMode, 1); - return constants; - } - - -// private final static String AGIntervalTest = "startEchoTestWithInterval"; - - private MediaObserver mediaObserver = null; - - private IRtcEngineEventHandler mRtcEventHandler = new IRtcEngineEventHandler() { - - @Override - public void onWarning(final int code) { - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap map = Arguments.createMap(); - map.putString("message", "AgoraWarning"); - map.putInt("errorCode", code); - sendEvent(getReactApplicationContext(), AGWarning, map); - } - }); - } - - @Override - public void onError(final int code) { - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap map = Arguments.createMap(); - map.putString("message", "AgoraError"); - map.putInt("errorCode", code); - sendEvent(getReactApplicationContext(), AGError, map); - } - }); - } - - @Override - public void onApiCallExecuted(final int code, final String api, final String result) { - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap map = Arguments.createMap(); - map.putInt("errorCode", code); - map.putString("api", api); - map.putString("result", result); - if (code != 0) { - sendEvent(getReactApplicationContext(), AGError, map); - } else { - sendEvent(getReactApplicationContext(), AGApiCallExecute, map); - } - } - }); - } - - @Override - public void onJoinChannelSuccess(final String channel, final int uid, final int elapsed) { - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap map = Arguments.createMap(); - map.putString("channel", channel); - map.putInt("uid", uid); - map.putInt("elapsed", elapsed); - sendEvent(getReactApplicationContext(), AGJoinChannelSuccess, map); - } - }); - } - - @Override - public void onRejoinChannelSuccess(final String channel, final int uid, final int elapsed) { - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap map = Arguments.createMap(); - map.putString("channel", channel); - map.putInt("uid", uid); - map.putInt("elapsed", elapsed); - sendEvent(getReactApplicationContext(), AGRejoinChannelSuccess, map); - } - }); - } - - @Override - public void onLeaveChannel(final RtcStats stats) { - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap statsMap = Arguments.createMap(); - statsMap.putInt("duration", stats.totalDuration); - statsMap.putInt("txBytes", stats.txBytes); - statsMap.putInt("rxBytes", stats.rxBytes); - statsMap.putInt("txAudioBytes", stats.txAudioBytes); - statsMap.putInt("txVideoBytes", stats.txVideoBytes); - statsMap.putInt("rxAudioBytes", stats.rxAudioBytes); - statsMap.putInt("rxVideoBytes", stats.rxVideoBytes); - statsMap.putInt("txKBitRate", stats.txKBitRate); - statsMap.putInt("rxKBitRate", stats.rxKBitRate); - statsMap.putInt("txAudioKBitRate", stats.txAudioKBitRate); - statsMap.putInt("rxAudioKBitRate", stats.rxAudioKBitRate); - statsMap.putInt("txVideoKBitRate", stats.txVideoKBitRate); - statsMap.putInt("rxVideoKBitRate", stats.rxVideoKBitRate); - statsMap.putInt("lastmileDelay", stats.lastmileDelay); - statsMap.putInt("userCount", stats.users); - statsMap.putDouble("cpuAppUsage", stats.cpuAppUsage); - statsMap.putDouble("cpuTotalUsage", stats.cpuTotalUsage); - statsMap.putInt("txPacketLossRate", stats.txPacketLossRate); - statsMap.putInt("rxPacketLossRate", stats.rxPacketLossRate); - - WritableMap map = Arguments.createMap(); - map.putMap("stats", statsMap); - sendEvent(getReactApplicationContext(), AGLeaveChannel, map); - } - }); - } - - @Override - public void onClientRoleChanged(final int oldRole, final int newRole) { - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap map = Arguments.createMap(); - map.putInt("oldRole", oldRole); - map.putInt("newRole", newRole); - sendEvent(getReactApplicationContext(), AGClientRoleChanged, map); - } - }); - } - - @Override - public void onLocalUserRegistered(final int uid, final String userAccount) { - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap map = Arguments.createMap(); - map.putInt("uid", uid); - map.putString("userAccount", userAccount); - sendEvent(getReactApplicationContext(), AGLocalUserRegistered, map); - } - }); - } - - @Override - public void onUserInfoUpdated(final int uid, final UserInfo peer) { - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap map = Arguments.createMap(); - map.putInt("uid", uid); - WritableMap peerInfo = Arguments.createMap(); - peerInfo.putInt("uid", peer.uid); - peerInfo.putString("userAccount", peer.userAccount); - map.putMap("peer", peerInfo); - sendEvent(getReactApplicationContext(), AGUserInfoUpdated, map); - } - }); - } - - @Override - public void onUserJoined(final int uid, final int elapsed) { - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap map = Arguments.createMap(); - map.putInt("uid", uid); - map.putInt("elapsed", elapsed); - sendEvent(getReactApplicationContext(), AGUserJoined, map); - } - }); - } - - @Override - public void onUserOffline(final int uid, final int reason) { - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap map = Arguments.createMap(); - map.putInt("uid", uid); - map.putInt("reason", reason); - sendEvent(getReactApplicationContext(), AGUserOffline, map); - } - }); - } - - @Override - public void onConnectionStateChanged(final int state, final int reason) { - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap map = Arguments.createMap(); - map.putInt("state", state); - map.putInt("reason", reason); - sendEvent(getReactApplicationContext(), AGConnectionStateChanged, map); - } - }); - } - - - @Override - public void onConnectionLost() { - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap map = Arguments.createMap(); - map.putString("message", "connectionLost"); - sendEvent(getReactApplicationContext(), AGConnectionLost, map); - } - }); - } - - @Override - public void onTokenPrivilegeWillExpire(final String token) { - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap map = Arguments.createMap(); - map.putString("token", token); - sendEvent(getReactApplicationContext(), AGTokenPrivilegeWillExpire, map); - } - }); - } - - @Override - public void onRequestToken() { - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap map = Arguments.createMap(); - map.putString("message", "RequestToken"); - sendEvent(getReactApplicationContext(), AGRequestToken, map); - } - }); - } - - @Override - public void onAudioVolumeIndication(final AudioVolumeInfo [] speakers, final int totalVolume) { - runOnUiThread(new Runnable() { - @Override - public void run() { - - WritableArray arr = Arguments.createArray(); - for (int i = 0; i < speakers.length; i++) { - WritableMap obj = Arguments.createMap(); - obj.putInt("uid", speakers[i].uid); - obj.putInt("volume", speakers[i].volume); - obj.putInt("vad", speakers[i].vad); - arr.pushMap(obj); - } - - WritableMap map = Arguments.createMap(); - map.putArray("speakers", arr); - map.putInt("totalVolume", totalVolume); - sendEvent(getReactApplicationContext(), AGAudioVolumeIndication, map); - } - }); - } - - @Override - public void onActiveSpeaker(final int uid) { - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap map = Arguments.createMap(); - map.putInt("uid", uid); - sendEvent(getReactApplicationContext(), AGActiveSpeaker, map); - } - }); - } - - @Override - public void onFirstLocalAudioFrame(final int elapsed) { - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap map = Arguments.createMap(); - map.putInt("elapsed", elapsed); - sendEvent(getReactApplicationContext(), AGFirstLocalAudioFrame, map); - } - }); - } - - @Override - public void onFirstRemoteAudioFrame(final int uid, final int elapsed) { - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap map = Arguments.createMap(); - map.putInt("uid", uid); - map.putInt("elapsed", elapsed); - sendEvent(getReactApplicationContext(), AGFirstRemoteAudioFrame, map); - } - }); - } - - @Override - public void onFirstLocalVideoFrame(final int width, final int height, final int elapsed) { - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap map = Arguments.createMap(); - map.putInt("width", width); - map.putInt("height", height); - map.putInt("elapsed", elapsed); - sendEvent(getReactApplicationContext(), AGFirstLocalVideoFrame, map); - } - }); - } - - @Override - public void onFirstRemoteVideoFrame(final int uid, final int width, final int height, final int elapsed) { - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap map = Arguments.createMap(); - map.putInt("uid", uid); - map.putInt("width", width); - map.putInt("height", height); - map.putInt("elapsed", elapsed); - sendEvent(getReactApplicationContext(), AGFirstRemoteVideoFrame, map); - } - }); - } - - @Override - public void onUserMuteAudio(final int uid, final boolean muted) { - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap map = Arguments.createMap(); - map.putBoolean("muted", muted); - map.putInt("uid", uid); - sendEvent(getReactApplicationContext(), AGUserMuteAudio, map); - } - }); - } - - @Override - public void onVideoSizeChanged(final int uid, final int width, final int height, final int rotation) { - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap map = Arguments.createMap(); - map.putInt("uid", uid); - map.putInt("width", width); - map.putInt("height", height); - map.putInt("rotation", rotation); - sendEvent(getReactApplicationContext(), AGVideoSizeChanged, map); - } - }); - } - - @Override - public void onRtmpStreamingStateChanged(final String url, final int state, final int errCode) { - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap map = Arguments.createMap(); - map.putString("url", url); - map.putInt("state", state); - map.putInt("errorCode", errCode); - sendEvent(getReactApplicationContext(), AGRtmpStreamingStateChanged, map); - } - }); - } - - @Override - public void onNetworkTypeChanged(final int type) { - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap map = Arguments.createMap(); - map.putInt("type", type); - sendEvent(getReactApplicationContext(), AGNetworkTypeChanged, map); - } - }); - } - - - @Override - public void onLocalAudioStateChanged(final int state, final int errCode) { - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap map = Arguments.createMap(); - map.putInt("state", state); - map.putInt("errorCode", errCode); - sendEvent(getReactApplicationContext(), AGLocalAudioStateChanged, map); - } - }); - } - @Override - public void onRemoteAudioStateChanged(final int uid, - final int state, - final int reason, - final int elapsed) { - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap map = Arguments.createMap(); - map.putInt("uid", uid); - map.putInt("state", state); - map.putInt("reason", reason); - map.putInt("elapsed", elapsed); - sendEvent(getReactApplicationContext(), AGRemoteAudioStateChanged, map); - } - }); - } - - @Override - public void onFirstRemoteAudioDecoded(final int uid, final int elapsed) { - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap map = Arguments.createMap(); - map.putInt("uid", uid); - map.putInt("elapsed", elapsed); - sendEvent(getReactApplicationContext(), AGFirstRemoteAudioDecoded, map); - } - }); - } - - @Override - public void onRemoteVideoStateChanged(final int uid, - final int state, - final int reason, - final int elapsed) { - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap map = Arguments.createMap(); - map.putInt("uid", uid); - map.putInt("state", state); - map.putInt("reason", reason); - map.putInt("elapsed", elapsed); - sendEvent(getReactApplicationContext(), AGRemoteVideoStateChanged, map); - } - }); - } - - @Override - public void onLocalPublishFallbackToAudioOnly(final boolean isFallbackOrRecover) { - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap map = Arguments.createMap(); - map.putBoolean("isFallbackOrRecover", isFallbackOrRecover); - sendEvent(getReactApplicationContext(), AGLocalPublishFallbackToAudioOnly, map); - } - }); - } - - @Override - public void onRemoteSubscribeFallbackToAudioOnly(final int uid, final boolean isFallbackOrRecover) { - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap map = Arguments.createMap(); - map.putBoolean("isFallbackOrRecover", isFallbackOrRecover); - map.putInt("uid", uid); - sendEvent(getReactApplicationContext(), AGRemoteSubscribeFallbackToAudioOnly, map); - } - }); - } - - @Override - public void onAudioRouteChanged(final int routing) { - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap map = Arguments.createMap(); - map.putInt("routing", routing); - sendEvent(getReactApplicationContext(), AGAudioRouteChanged, map); - } - }); - } - - @Override - public void onCameraFocusAreaChanged(final Rect rect) { - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap rectMap = Arguments.createMap(); - rectMap.putInt("top", rect.top); - rectMap.putInt("right", rect.right); - rectMap.putInt("bottom", rect.bottom); - rectMap.putInt("left", rect.left); - WritableMap map = Arguments.createMap(); - map.putMap("rect", rectMap); - sendEvent(getReactApplicationContext(), AGCameraFocusAreaChanged, map); - } - }); - } - - @Override - public void onCameraExposureAreaChanged(final Rect rect) { - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap rectMap = Arguments.createMap(); - rectMap.putInt("top", rect.top); - rectMap.putInt("right", rect.right); - rectMap.putInt("bottom", rect.bottom); - rectMap.putInt("left", rect.left); - WritableMap map = Arguments.createMap(); - map.putMap("rect", rectMap); - sendEvent(getReactApplicationContext(), AGCameraExposureAreaChanged, map); - } - }); - } - - @Override - public void onRemoteAudioStats(final RemoteAudioStats stats) { - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap statsMap = Arguments.createMap(); - statsMap.putInt("uid", stats.uid); - statsMap.putInt("quality", stats.quality); - statsMap.putInt("networkTransportDelay", stats.networkTransportDelay); - statsMap.putInt("jitterBufferDelay", stats.jitterBufferDelay); - statsMap.putInt("audioLossRate", stats.audioLossRate); - statsMap.putInt("totalFrozenTime", stats.totalFrozenTime); - statsMap.putInt("frozenRate", stats.frozenRate); - statsMap.putInt("numChannels", stats.numChannels); - statsMap.putInt("receivedSampleRate", stats.receivedSampleRate); - statsMap.putInt("receivedBitrate", stats.receivedBitrate); - WritableMap map = Arguments.createMap(); - map.putMap("stats", statsMap); - sendEvent(getReactApplicationContext(), AGRemoteAudioStats, map); - } - }); - } - - @Override - public void onRtcStats(final RtcStats stats) { - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap statsMap = Arguments.createMap(); - statsMap.putInt("duration", stats.totalDuration); - statsMap.putInt("txBytes", stats.txBytes); - statsMap.putInt("rxBytes", stats.rxBytes); - statsMap.putInt("txAudioBytes", stats.txAudioBytes); - statsMap.putInt("txVideoBytes", stats.txVideoBytes); - statsMap.putInt("rxAudioBytes", stats.rxAudioBytes); - statsMap.putInt("rxVideoBytes", stats.rxVideoBytes); - statsMap.putInt("txKBitRate", stats.txKBitRate); - statsMap.putInt("rxKBitRate", stats.rxKBitRate); - statsMap.putInt("txAudioKBitRate", stats.txAudioKBitRate); - statsMap.putInt("rxAudioKBitRate", stats.rxAudioKBitRate); - statsMap.putInt("txVideoKBitRate", stats.txVideoKBitRate); - statsMap.putInt("rxVideoKBitRate", stats.rxVideoKBitRate); - statsMap.putInt("lastmileDelay", stats.lastmileDelay); - statsMap.putInt("userCount", stats.users); - statsMap.putDouble("cpuAppUsage", stats.cpuAppUsage); - statsMap.putDouble("cpuTotalUsage", stats.cpuTotalUsage); - statsMap.putInt("txPacketLossRate", stats.txPacketLossRate); - statsMap.putInt("rxPacketLossRate", stats.rxPacketLossRate); - - WritableMap map = Arguments.createMap(); - map.putMap("stats", statsMap); - sendEvent(getReactApplicationContext(), AGRtcStats, map); - } - }); - } - - @Override - public void onLastmileQuality(final int quality) { - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap map = Arguments.createMap(); - map.putInt("quality", quality); - sendEvent(getReactApplicationContext(), AGLastmileQuality, map); - } - }); - } - - @Override - public void onNetworkQuality(final int uid, final int txQuality, final int rxQuality) { - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap map = Arguments.createMap(); - map.putInt("uid", uid); - map.putInt("txQuality", txQuality); - map.putInt("rxQuality", rxQuality); - sendEvent(getReactApplicationContext(), AGNetworkQuality, map); - } - }); - } - - - @Override - public void onLocalVideoStats(final LocalVideoStats stats) { - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap statsMap = Arguments.createMap(); - statsMap.putInt("sentBitrate", stats.sentBitrate); - statsMap.putInt("sentFrameRate", stats.sentFrameRate); - statsMap.putInt("encoderOutputFrameRate", stats.encoderOutputFrameRate); - statsMap.putInt("rendererOutputFrameRate", stats.rendererOutputFrameRate); - statsMap.putInt("targetBitrate", stats.targetBitrate); - statsMap.putInt("targetFrameRate", stats.targetFrameRate); - statsMap.putInt("qualityAdaptIndication", stats.qualityAdaptIndication); - statsMap.putInt("encodedBitrate", stats.encodedBitrate); - statsMap.putInt("encodedFrameWidth", stats.encodedFrameWidth); - statsMap.putInt("encodedFrameHeight", stats.encodedFrameHeight); - statsMap.putInt("encodedFrameCount", stats.encodedFrameCount); - statsMap.putInt("codecType", stats.codecType); - WritableMap map = Arguments.createMap(); - map.putMap("stats", statsMap); - sendEvent(getReactApplicationContext(), AGLocalVideoStats, map); - } - }); - } - - @Override - public void onRemoteVideoStats(final RemoteVideoStats stats) { - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap statsMap = Arguments.createMap(); - statsMap.putInt("uid", stats.uid); - statsMap.putInt("width", stats.width); - statsMap.putInt("height", stats.height); - statsMap.putInt("receivedBitrate", stats.receivedBitrate); - statsMap.putInt("decoderOutputFrameRate", stats.decoderOutputFrameRate); - statsMap.putInt("rendererOutputFrameRate", stats.rendererOutputFrameRate); - statsMap.putInt("packetLossRate", stats.packetLossRate); - statsMap.putInt("rxStreamType", stats.rxStreamType); - statsMap.putInt("totalFrozenTime", stats.totalFrozenTime); - statsMap.putInt("frozenRate", stats.frozenRate); - WritableMap map = Arguments.createMap(); - map.putMap("stats", statsMap); - sendEvent(getReactApplicationContext(), AGRemoteVideoStats, map); - } - }); - } - - @Override - public void onAudioMixingStateChanged(final int state, final int errorCode) { - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap map = Arguments.createMap(); - map.putInt("state", state); - map.putInt("errorCode", errorCode); - sendEvent(getReactApplicationContext(), AGAudioMixingStateChanged, map); - } - }); - } - - @Override - public void onAudioEffectFinished(final int soundId) { - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap map = Arguments.createMap(); - map.putInt("soundid", soundId); - sendEvent(getReactApplicationContext(), AGAudioEffectFinish, map); - } - }); - } - - @Override - public void onStreamPublished(final String url, final int errorCode) { - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap map = Arguments.createMap(); - map.putString("url", url); - map.putInt("errorCode", errorCode); - sendEvent(getReactApplicationContext(), AGStreamPublished, map); - } - }); - } - - @Override - public void onStreamUnpublished(final String url) { - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap map = Arguments.createMap(); - map.putString("url", url); - sendEvent(getReactApplicationContext(), AGStreamUnpublish, map); - } - }); - } - - @Override - public void onTranscodingUpdated() { - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap map = Arguments.createMap(); - map.putString("message", "AGTranscodingUpdate"); - sendEvent(getReactApplicationContext(), AGTranscodingUpdate, map); - } - }); - } - - @Override - public void onStreamInjectedStatus(final String url, final int uid, final int status) { - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap map = Arguments.createMap(); - map.putInt("uid", uid); - map.putString("url", url); - map.putInt("status", status); - sendEvent(getReactApplicationContext(), AGStreamInjectedStatus, map); - } - }); - } - - /** - * onStreamMessage - */ - @Override - public void onStreamMessage(final int uid, final int streamId, final byte[] data) { - runOnUiThread(new Runnable() { - @Override - public void run() { - String msg = new String(data, Charset.forName("UTF-8")); - WritableMap map = Arguments.createMap(); - map.putInt("uid", uid); - map.putInt("streamId", streamId); - map.putString("data", msg); - sendEvent(getReactApplicationContext(), AGReceiveStreamMessage, map); - } - }); - } - - @Override - public void onStreamMessageError(final int uid, final int streamId, final int error, final int missed, final int cached) { - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap map = Arguments.createMap(); - map.putInt("uid", uid); - map.putInt("streamId", streamId); - map.putInt("errorCode", error); - map.putInt("missed", missed); - map.putInt("cached", cached); - sendEvent(getReactApplicationContext(), AGOccurStreamMessageError, map); - } - }); - } - - @Override - public void onMediaEngineLoadSuccess() { - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap map = Arguments.createMap(); - map.putString("message", "MediaEngineLoaded"); - sendEvent(getReactApplicationContext(), AGMediaEngineLoaded, map); - } - }); - } - - @Override - public void onMediaEngineStartCallSuccess() { - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap map = Arguments.createMap(); - map.putString("message", "MediaEngineStartCall"); - sendEvent(getReactApplicationContext(), AGMediaEngineStartCall, map); - } - }); - } - - @Override - public void onLastmileProbeResult(LastmileProbeResult result) { - super.onLastmileProbeResult(result); - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap map = Arguments.createMap(); - map.putString("message", "LastmileProbeTestResult"); - sendEvent(getReactApplicationContext(), AGLastmileProbeResult, map); - } - }); - } - - @Override - public void onLocalVideoStateChanged(final int localVideoState, final int error) { - super.onLocalVideoStateChanged(localVideoState, error); - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap map = Arguments.createMap(); - map.putString("message", "LocalVideoChanged"); - map.putInt("state", localVideoState); - sendEvent(getReactApplicationContext(), AGLocalVideoChanged, map); - } - }); - } - - @Override - public void onChannelMediaRelayEvent(final int code) { - super.onChannelMediaRelayEvent(code); - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap map = Arguments.createMap(); - map.putInt("errorCode", code); - sendEvent(getReactApplicationContext(), AGReceivedChannelMediaRelay, map); - } - }); - } - - @Override - public void onChannelMediaRelayStateChanged(final int state, final int code) { - super.onChannelMediaRelayStateChanged(state, code); - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap map = Arguments.createMap(); - map.putInt("state", state); - map.putInt("errorCode", code); - sendEvent(getReactApplicationContext(), AGMediaRelayStateChanged, map); - } - }); - } - - @Override - public void onLocalAudioStats(final LocalAudioStats rtcStats) { - super.onLocalAudioStats(rtcStats); - runOnUiThread(new Runnable() { - @Override - public void run() { - WritableMap map = Arguments.createMap(); - map.putInt("numChannels", rtcStats.numChannels); - map.putInt("sentSampleRate", rtcStats.sentSampleRate); - map.putInt("sentBitrate", rtcStats.sentBitrate); - sendEvent(getReactApplicationContext(), AGLocalAudioStats, map); - } - }); - } - }; - - public void setAppType(RtcEngineEx engineEx) { - engineEx.setAppType(8); - } - - @ReactMethod - public void init(ReadableMap options) { - AgoraManager.getInstance().init(getReactApplicationContext(), mRtcEventHandler, options); - appId = options.getString("appid"); - rtcEngine = AgoraManager.getInstance().mRtcEngine; - setAppType((RtcEngineEx) rtcEngine); - } - - @ReactMethod - public void renewToken(String token, - Promise promise) { - Integer res = AgoraManager.getInstance().renewToken(token); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void enableWebSdkInteroperability(boolean enabled, Promise promise) { - Integer res = AgoraManager.getInstance().enableWebSdkInteroperability(enabled); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void getConnectionState(Promise promise) { - Integer res = AgoraManager.getInstance().getConnectionState(); - WritableMap map = Arguments.createMap(); - map.putInt("state", res); - promise.resolve(map); - } - - @ReactMethod - public void setClientRole(int role, Promise promise) { - Integer res = AgoraManager.getInstance().setClientRole(role); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - private String channelName = null; - - @ReactMethod - public void joinChannel(ReadableMap options, Promise promise) { - Integer res = AgoraManager.getInstance().joinChannel(options); - if (res == 0) { - String channelName = options.getString("channelName"); - this.channelName = channelName; - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void registerLocalUserAccount(ReadableMap options, Promise promise) { - Integer res = rtcEngine.registerLocalUserAccount(appId, options.getString("userAccount")); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void joinChannelWithUserAccount(ReadableMap options, Promise promise) { - String token = null; - if (options.hasKey("token")) { - token = options.getString("token"); - } - String channelName = options.getString("channelName"); - Integer res = rtcEngine.joinChannelWithUserAccount(token, options.getString("channelName"), options.getString("userAccount")); - if (res == 0) { - this.channelName = channelName; - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void getUserInfoByUid(Integer uid, Promise promise) { - UserInfo info = new UserInfo(); - Integer res = rtcEngine.getUserInfoByUid(uid, info); - if (res == 0) { - WritableMap map = Arguments.createMap(); - map.putInt("uid", info.uid); - map.putString("userAccount", info.userAccount); - promise.resolve(map); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void getUserInfoByUserAccount(String userAccount, Promise promise) { - UserInfo info = new UserInfo(); - Integer res = rtcEngine.getUserInfoByUserAccount(userAccount, info); - if (res == 0) { - WritableMap map = Arguments.createMap(); - map.putInt("uid", info.uid); - map.putString("userAccount", info.userAccount); - promise.resolve(map); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void switchChannel(ReadableMap options, Promise promise) { - String token = null; - String channel = null; - if (options.hasKey("token")) { - token = options.getString("token"); - } - if (options.hasKey("channelName")) { - channel = options.getString("channelName"); - } - Integer res = AgoraManager.getInstance().mRtcEngine.switchChannel(token, channel); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void leaveChannel(Promise promise) { - Integer res = AgoraManager.getInstance().leaveChannel(); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void destroy() { - RtcEngine.destroy(); - } - - @ReactMethod - public void startChannelMediaRelay(ReadableMap options, Promise promise) { - ChannelMediaRelayConfiguration config = new ChannelMediaRelayConfiguration(); - ChannelMediaInfo src = config.getSrcChannelMediaInfo(); - if (options.hasKey("src")) { - ReadableMap srcOption = options.getMap("src"); - if (srcOption.hasKey("token")) { - src.token = srcOption.getString("token"); - } - if (srcOption.hasKey("channelName")) { - src.channelName = srcOption.getString("channelName"); - } - } - ReadableArray dstMediaInfo = options.getArray("channels"); - for (int i = 0; i < dstMediaInfo.size(); i++) { - ReadableMap dst = dstMediaInfo.getMap(i); - String channelName = null; - String token = null; - Integer uid = 0; - if (dst.hasKey("token")) { - token = token; - } - if (dst.hasKey("channelName")) { - channelName = dst.getString("channelName"); - } - if (dst.hasKey("uid")) { - uid = dst.getInt("uid"); - } - config.setDestChannelInfo(channelName, new ChannelMediaInfo(channelName, token, uid)); - } - Integer res = AgoraManager.getInstance().mRtcEngine.startChannelMediaRelay(config); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void removeChannelMediaRelay(ReadableMap options, Promise promise) { - ChannelMediaRelayConfiguration config = new ChannelMediaRelayConfiguration(); - ChannelMediaInfo src = config.getSrcChannelMediaInfo(); - if (options.hasKey("src")) { - ReadableMap srcOption = options.getMap("src"); - if (srcOption.hasKey("token")) { - src.token = srcOption.getString("token"); - } - if (srcOption.hasKey("channelName")) { - src.channelName = srcOption.getString("channelName"); - } - } - ReadableArray dstMediaInfo = options.getArray("channels"); - for (int i = 0; i < dstMediaInfo.size(); i++) { - ReadableMap dst = dstMediaInfo.getMap(i); - if (dst.hasKey("channelName")) { - channelName = dst.getString("channelName"); - config.removeDestChannelInfo(channelName); - } - } - Integer res = AgoraManager.getInstance().mRtcEngine.updateChannelMediaRelay(config); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void updateChannelMediaRelay(ReadableMap options, Promise promise) { - ChannelMediaRelayConfiguration config = new ChannelMediaRelayConfiguration(); - ChannelMediaInfo src = config.getSrcChannelMediaInfo(); - if (options.hasKey("src")) { - ReadableMap srcOption = options.getMap("src"); - if (srcOption.hasKey("token")) { - src.token = srcOption.getString("token"); - } - if (srcOption.hasKey("channelName")) { - src.channelName = srcOption.getString("channelName"); - } - } - ReadableArray dstMediaInfo = options.getArray("channels"); - for (int i = 0; i < dstMediaInfo.size(); i++) { - ReadableMap dst = dstMediaInfo.getMap(i); - String channelName = null; - String token = null; - Integer uid = 0; - if (dst.hasKey("token")) { - token = token; - } - if (dst.hasKey("channelName")) { - channelName = dst.getString("channelName"); - } - if (dst.hasKey("uid")) { - uid = dst.getInt("uid"); - } - config.setDestChannelInfo(src.channelName, new ChannelMediaInfo(channelName, token, uid)); - } - Integer res = AgoraManager.getInstance().mRtcEngine.updateChannelMediaRelay(config); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void stopChannelMediaRelay(Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.stopChannelMediaRelay(); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void startPreview(Promise promise) { - Integer res = AgoraManager.getInstance().startPreview(); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void stopPreview(Promise promise) { - Integer res = AgoraManager.getInstance().stopPreview(); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void setEnableSpeakerphone(boolean enabled, Promise promise) { - Integer res = AgoraManager.getInstance().setEnableSpeakerphone(enabled); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void setDefaultAudioRouteToSpeakerphone(boolean enabled, Promise promise) { - Integer res = AgoraManager.getInstance().setDefaultAudioRouteToSpeakerphone(enabled); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void enableVideo(Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.enableVideo(); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void disableVideo(Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.disableVideo(); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void enableLocalVideo(boolean enabled, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.enableLocalVideo(enabled); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void muteLocalVideoStream(boolean muted, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.muteLocalVideoStream(muted); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void muteAllRemoteVideoStreams(boolean muted, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.muteAllRemoteVideoStreams(muted); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void muteRemoteVideoStream(int uid, boolean muted, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.muteRemoteVideoStream(uid, muted); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - @ReactMethod - public void setDefaultMuteAllRemoteVideoStreams(boolean muted, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.setDefaultMuteAllRemoteVideoStreams(muted); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void switchCamera(Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.switchCamera(); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void getCameraInfo(Promise promise) { - WritableMap map = Arguments.createMap(); - WritableMap supportMap = Arguments.createMap(); - supportMap.putBoolean("zoom", AgoraManager.getInstance().mRtcEngine.isCameraZoomSupported()); - supportMap.putBoolean("torch", AgoraManager.getInstance().mRtcEngine.isCameraTorchSupported()); - supportMap.putBoolean("focusPositionInPreview", AgoraManager.getInstance().mRtcEngine.isCameraTorchSupported()); - supportMap.putBoolean("exposurePosition", AgoraManager.getInstance().mRtcEngine.isCameraTorchSupported()); - supportMap.putBoolean("autoFocusFaceMode", AgoraManager.getInstance().mRtcEngine.isCameraAutoFocusFaceModeSupported()); -// supportMap.putDouble("maxZoomFactor", AgoraManager.getInstance().mRtcEngine.getCameraMaxZoomFactor()); - map.putMap("support", supportMap); - promise.resolve(map); - } - - @ReactMethod - public void setCameraZoomFactor(float factor, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.setCameraZoomFactor(factor); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void setCameraFocusPositionInPreview(ReadableMap options, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.setCameraFocusPositionInPreview( - (float)options.getDouble("x"), - (float)options.getDouble("y") - ); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void setCameraExposurePosition(ReadableMap options, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.setCameraExposurePosition( - (float)options.getDouble("x"), - (float)options.getDouble("y") - ); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void setCameraTorchOn(boolean isOn, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.setCameraTorchOn(isOn); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void setCameraAutoFocusFaceModeEnabled(boolean enabled, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.setCameraAutoFocusFaceModeEnabled(enabled); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void getCallId(Promise promise) { - String res = AgoraManager.getInstance().mRtcEngine.getCallId(); - WritableMap map = Arguments.createMap(); - map.putString("id", res); - promise.resolve(map); - } - - @ReactMethod - public void setLog(String filePath, int level, int size, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.setLogFileSize(size); - if (res < 0) { - promise.reject("-1", res.toString()); - return; - } - res = AgoraManager.getInstance().mRtcEngine.setLogFilter(level); - if (res < 0) { - promise.reject("-1", res.toString()); - return; - } - res = AgoraManager.getInstance().mRtcEngine.setLogFile(filePath); - if (res < 0) { - promise.reject("-1", res.toString()); - return; - } - promise.resolve(null); - } - - - @ReactMethod - public void enableAudio(Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.enableAudio(); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void disableAudio(Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.disableAudio(); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void muteAllRemoteAudioStreams(boolean muted, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.muteAllRemoteAudioStreams(muted); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void muteRemoteAudioStream(int uid, boolean muted, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.muteRemoteAudioStream(uid, muted); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void setDefaultMuteAllRemoteAudioStreams(boolean muted, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.setDefaultMuteAllRemoteAudioStreams(muted); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void adjustRecordingSignalVolume(int volume, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.adjustRecordingSignalVolume(volume); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void adjustPlaybackSignalVolume(int volume, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.adjustPlaybackSignalVolume(volume); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void enableAudioVolumeIndication(int interval, int smooth, boolean vad, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.enableAudioVolumeIndication(interval, smooth, vad); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void enableLocalAudio(boolean enabled, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.enableLocalAudio(enabled); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void muteLocalAudioStream(boolean enabled, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.muteLocalAudioStream(enabled); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void createDataStream(ReadableMap options, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine - .createDataStream( - options.getBoolean("ordered"), - options.getBoolean("reliable") - ); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void isSpeakerphoneEnabled(Callback callback) { - WritableMap map = Arguments.createMap(); - map.putBoolean("status", AgoraManager.getInstance().mRtcEngine.isSpeakerphoneEnabled()); - callback.invoke(map); - } - - @ReactMethod - public void enableInEarMonitoring(boolean enabled, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.enableInEarMonitoring(enabled); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void setInEarMonitoringVolume(int volume, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.setInEarMonitoringVolume(volume); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void setLocalVoicePitch(double pitch, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.setLocalVoicePitch(pitch); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void setLocalVoiceEqualization(int band, int gain, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.setLocalVoiceEqualization(band, gain); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void setLocalVoiceReverb(int reverb, int value, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.setLocalVoiceReverb(reverb, value); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void startAudioMixing(ReadableMap options, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.startAudioMixing( - options.getString("filepath"), - options.getBoolean("loopback"), - options.getBoolean("replace"), - options.getInt("cycle") - ); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void stopAudioMixing(Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.stopAudioMixing(); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void pauseAudioMixing(Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.pauseAudioMixing(); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void resumeAudioMixing(Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.resumeAudioMixing(); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void adjustAudioMixingVolume(int volume, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.adjustAudioMixingVolume(volume); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void adjustAudioMixingPlayoutVolume(int volume, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.adjustAudioMixingPlayoutVolume(volume); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void adjustAudioMixingPublishVolume(int volume, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.adjustAudioMixingPublishVolume(volume); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void getAudioMixingPlayoutVolume(Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.getAudioMixingPlayoutVolume(); - if (res >= 0) { - promise.resolve(res); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void getAudioMixingPublishVolume(Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.getAudioMixingPublishVolume(); - if (res >= 0) { - promise.resolve(res); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void getAudioMixingDuration(Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.getAudioMixingDuration(); - if (res >= 0) { - promise.resolve(res); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void getAudioMixingCurrentPosition(Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.getAudioMixingCurrentPosition(); - if (res >= 0) { - promise.resolve(res); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void setAudioMixingPosition(int pos, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.setAudioMixingPosition(pos); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void startAudioRecording(ReadableMap options, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine - .startAudioRecording( - options.getString("filepath"), - options.getInt("sampleRate"), - options.getInt("quality") - ); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void stopAudioRecording(Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine - .stopAudioRecording(); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void stopEchoTest(Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine - .stopEchoTest(); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void enableLastmileTest(Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine - .enableLastmileTest(); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void disableLastmileTest(Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine - .disableLastmileTest(); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void setRecordingAudioFrameParameters(ReadableMap options, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine - .setRecordingAudioFrameParameters( - options.getInt("sampleRate"), - options.getInt("channel"), - options.getInt("mode"), - options.getInt("samplesPerCall") - ); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void setPlaybackAudioFrameParameters(ReadableMap options, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine - .setPlaybackAudioFrameParameters( - options.getInt("sampleRate"), - options.getInt("channel"), - options.getInt("mode"), - options.getInt("samplesPerCall") - ); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void setMixedAudioFrameParameters(WritableMap options, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine - .setMixedAudioFrameParameters( - options.getInt("sampleRate"), - options.getInt("samplesPerCall") - ); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - public AgoraImage createAgoraImage(ReadableMap options) { - AgoraImage image = new AgoraImage(); - image.url = options.getString("url"); - image.height = options.getInt("height"); - image.width = options.getInt("width"); - image.x = options.getInt("x"); - image.y = options.getInt("y"); - return image; - } - - @ReactMethod - public void addVideoWatermark(ReadableMap options, Promise promise) { - String url = options.getString("url"); - ReadableMap watermarkOptions = options.getMap("options"); - ReadableMap positionLandscapeOptions = watermarkOptions.getMap("positionInPortraitMode"); - WatermarkOptions watermarkOpts = new WatermarkOptions(); - WatermarkOptions.Rectangle landscapePosition = new WatermarkOptions.Rectangle(); - landscapePosition.height = positionLandscapeOptions.getInt("height"); - landscapePosition.width = positionLandscapeOptions.getInt("width"); - landscapePosition.x = positionLandscapeOptions.getInt("x"); - landscapePosition.y = positionLandscapeOptions.getInt("y"); - - ReadableMap positionPortraitOptions = watermarkOptions.getMap("positionInPortraitMode"); - WatermarkOptions.Rectangle portraitPosition = new WatermarkOptions.Rectangle(); - portraitPosition.height = positionPortraitOptions.getInt("height"); - portraitPosition.width = positionPortraitOptions.getInt("width"); - portraitPosition.x = positionPortraitOptions.getInt("x"); - portraitPosition.y = positionPortraitOptions.getInt("y"); - - watermarkOpts.positionInLandscapeMode = landscapePosition; - watermarkOpts.visibleInPreview = watermarkOptions.getBoolean("visibleInPreview"); - watermarkOpts.positionInPortraitMode = portraitPosition; - Integer res = AgoraManager.getInstance().mRtcEngine - .addVideoWatermark(url, watermarkOpts); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void clearVideoWatermarks(Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine - .clearVideoWatermarks(); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void setLocalPublishFallbackOption(int option, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine - .setLocalPublishFallbackOption(option); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void setRemoteSubscribeFallbackOption(int option, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine - .setRemoteSubscribeFallbackOption(option); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void enableDualStreamMode(boolean enabled, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine - .enableDualStreamMode(enabled); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - - @ReactMethod - public void setRemoteVideoStreamType(ReadableMap options, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine - .setRemoteVideoStreamType( - options.getInt("uid"), - options.getInt("streamType") - ); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void setRemoteDefaultVideoStreamType(ReadableMap options, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine - .setRemoteDefaultVideoStreamType( - options.getInt("streamType") - ); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void sendMediaData(String data, final Promise promise) { - if (null == mediaObserver) { - promise.reject("-1", "-1"); - } else { - mediaObserver.setMetadata(data.getBytes(Charset.forName("UTF-8"))); - promise.resolve(null); - } - } - - @ReactMethod - public void registerMediaMetadataObserver(final Promise promise) { - mediaObserver = new MediaObserver(getReactApplicationContext()); - Integer res = AgoraManager.getInstance().mRtcEngine - .registerMediaMetadataObserver(mediaObserver, IMetadataObserver.VIDEO_METADATA); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - private static boolean recording = false; - - // TODO: need implementation - @ReactMethod - public void startAVRecording(final ReadableMap option, final Promise promise) { - String path = option.getString("path"); - Integer uid = option.getInt("uid"); - String format = option.getString("format"); - if (true == recording) { - promise.reject("-1", "recording already started"); - } - SurfaceView view = AgoraManager.getInstance().getSurfaceView(uid); - if (null == view) { - promise.reject("-1", "recording already started"); - } - } - - // TODO: need implementation - @ReactMethod - public void stopAVRecording(final Promise promise) { - if (false == recording) { - promise.reject("-1", "recording didn't start"); - } else { - promise.resolve(null); - } - } - - public LiveInjectStreamConfig.AudioSampleRateType getAudioSampleRateEnum (int val) { - LiveInjectStreamConfig.AudioSampleRateType type = LiveInjectStreamConfig.AudioSampleRateType.TYPE_32000; - switch (Integer.valueOf(val)) { - case 32000: - type = LiveInjectStreamConfig.AudioSampleRateType.TYPE_32000; - break; - case 44100: - type = LiveInjectStreamConfig.AudioSampleRateType.TYPE_44100; - break; - case 48000: - type = LiveInjectStreamConfig.AudioSampleRateType.TYPE_48000; - break; - } - return type; - } - - public LiveTranscoding.AudioSampleRateType getLiveTranscodingAudioSampleRateEnum (int val) { - LiveTranscoding.AudioSampleRateType type = LiveTranscoding.AudioSampleRateType.TYPE_32000; - switch (Integer.valueOf(val)) { - case 32000: - type = LiveTranscoding.AudioSampleRateType.TYPE_32000; - break; - case 44100: - type = LiveTranscoding.AudioSampleRateType.TYPE_44100; - break; - case 48000: - type = LiveTranscoding.AudioSampleRateType.TYPE_48000; - break; - } - return type; - } - - - public LiveTranscoding.VideoCodecProfileType getLiveTranscodingVideoCodecProfileEnum (int val) { - LiveTranscoding.VideoCodecProfileType type = LiveTranscoding.VideoCodecProfileType.BASELINE; - switch (Integer.valueOf(val)) { - case 66: - type = LiveTranscoding.VideoCodecProfileType.BASELINE; - break; - case 77: - type = LiveTranscoding.VideoCodecProfileType.MAIN; - break; - case 100: - type = LiveTranscoding.VideoCodecProfileType.HIGH; - break; - } - return type; - } - - public LiveTranscoding.AudioCodecProfileType getLiveTranscodingAudioCodecProfileEnum (int val) { - LiveTranscoding.AudioCodecProfileType type = LiveTranscoding.AudioCodecProfileType.LC_AAC; - switch (Integer.valueOf(val)) { - case 0: - type = LiveTranscoding.AudioCodecProfileType.LC_AAC; - break; - case 1: - type = LiveTranscoding.AudioCodecProfileType.HE_AAC; - break; - } - return type; - } - - - - @ReactMethod - public void addInjectStreamUrl(ReadableMap options, Promise promise) { - LiveInjectStreamConfig injectstream = new LiveInjectStreamConfig(); - ReadableMap config = options.getMap("config"); - ReadableMap size = config.getMap("size"); - injectstream.width = size.getInt("width"); - injectstream.height = size.getInt("height"); - injectstream.videoGop = config.getInt("videoGop"); - injectstream.videoBitrate = config.getInt("videoBitrate"); - injectstream.videoFramerate = config.getInt("videoFramerate"); - injectstream.audioBitrate = config.getInt("audioBitrate"); - injectstream.audioSampleRate = getAudioSampleRateEnum(config.getInt("audioSampleRate")); - injectstream.audioChannels = config.getInt("audioChannels"); - - Integer res = AgoraManager.getInstance().mRtcEngine - .addInjectStreamUrl( - options.getString("url"), - injectstream - ); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void removeInjectStreamUrl(ReadableMap options, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine - .removeInjectStreamUrl(options.getString("url")); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void addPublishStreamUrl(ReadableMap options, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine - .addPublishStreamUrl( - options.getString("url"), - options.getBoolean("enable") - ); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void removePublishStreamUrl(ReadableMap options, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine - .removePublishStreamUrl(options.getString("url")); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void setLiveTranscoding(ReadableMap options, Promise promise) { - LiveTranscoding transcoding = new LiveTranscoding(); - if (options.hasKey("size")) { - ReadableMap size = options.getMap("size"); - transcoding.width = size.getInt("width"); - transcoding.height = size.getInt("height"); - } - if (options.hasKey("videoBitrate")) { - transcoding.videoBitrate = options.getInt("videoBitrate"); - } - if (options.hasKey("videoFramerate")) { - transcoding.videoFramerate = options.getInt("videoFramerate"); - } - if (options.hasKey("videoGop")) { - transcoding.videoGop = options.getInt("videoGop"); - } - if (options.hasKey("videoCodecProfile")) { - transcoding.videoCodecProfile = getLiveTranscodingVideoCodecProfileEnum(options.getInt("videoCodecProfile")); - } - if (options.hasKey("audioCodecProfile")) { - transcoding.audioCodecProfile = getLiveTranscodingAudioCodecProfileEnum(options.getInt("audioCodecProfile")); - } - if (options.hasKey("audioSampleRate")) { - transcoding.audioSampleRate = getLiveTranscodingAudioSampleRateEnum(options.getInt("audioSampleRate")); - } - if (options.hasKey("watermark")) { - ReadableMap watermark = options.getMap("watermark"); - WritableMap map = Arguments.createMap(); - map.putString("url", watermark.getString("url")); - map.putInt("x", watermark.getInt("x")); - map.putInt("y", watermark.getInt("y")); - map.putInt("width", watermark.getInt("width")); - map.putInt("height", watermark.getInt("height")); - transcoding.watermark = createAgoraImage(map); - } - if (options.hasKey("backgroundImage")) { - ReadableMap image = options.getMap("backgroundImage"); - WritableMap map = Arguments.createMap(); - map.putString("url", image.getString("url")); - map.putInt("x", image.getInt("x")); - map.putInt("y", image.getInt("y")); - map.putInt("width", image.getInt("width")); - map.putInt("height", image.getInt("height")); - transcoding.backgroundImage = createAgoraImage(map); - } - if (options.hasKey("backgroundColor")) { - transcoding.setBackgroundColor(options.getInt("backgroundColor")); - } - if (options.hasKey("audioBitrate")) { - transcoding.audioBitrate = options.getInt("audioBitrate"); - } - if (options.hasKey("audioChannels")) { - transcoding.audioChannels = options.getInt("audioChannels"); - } - if (options.hasKey("transcodingUsers")) { - ArrayList users = new ArrayList(); - ReadableArray transcodingUsers = options.getArray("transcodingUsers"); - for (int i = 0; i < transcodingUsers.size(); i++) { - ReadableMap optionUser = transcodingUsers.getMap(i); - LiveTranscoding.TranscodingUser user = new LiveTranscoding.TranscodingUser(); - user.uid = optionUser.getInt("uid"); - user.x = optionUser.getInt("x"); - user.y = optionUser.getInt("y"); - user.width = optionUser.getInt("width"); - user.height = optionUser.getInt("height"); - user.zOrder = optionUser.getInt("zOrder"); - user.alpha = (float) optionUser.getDouble("alpha"); - user.audioChannel = optionUser.getInt("audioChannel"); - users.add(user); - } - transcoding.setUsers(users); - } - if (options.hasKey("transcodingExtraInfo")) { - transcoding.userConfigExtraInfo = options.getString("transcodingExtraInfo"); - } - Integer res = AgoraManager.getInstance().mRtcEngine.setLiveTranscoding(transcoding); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void getEffectsVolume(Promise promise) { - IAudioEffectManager manager = AgoraManager.getInstance().mRtcEngine.getAudioEffectManager(); - Double res = manager.getEffectsVolume(); - if (res >= 0) { - promise.resolve(res); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void setEffectsVolume(double volume, Promise promise) { - IAudioEffectManager manager = AgoraManager.getInstance().mRtcEngine.getAudioEffectManager(); - Integer res = manager.setEffectsVolume(volume); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - - @ReactMethod - public void setVolumeOfEffect(int soundId, double volume, Promise promise) { - IAudioEffectManager manager = AgoraManager.getInstance().mRtcEngine.getAudioEffectManager(); - Integer res = manager.setVolumeOfEffect(soundId, volume); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void playEffect(ReadableMap options, Promise promise) { - IAudioEffectManager manager = AgoraManager.getInstance().mRtcEngine.getAudioEffectManager(); - Integer res = manager.playEffect( - options.getInt("soundid"), - options.getString("filepath"), - options.getInt("loopcount"), - options.getDouble("pitch"), - options.getDouble("pan"), - options.getDouble("gain"), - options.getBoolean("publish") - ); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - - @ReactMethod - public void stopEffect(int soundId, Promise promise) { - IAudioEffectManager manager = AgoraManager.getInstance().mRtcEngine.getAudioEffectManager(); - Integer res = manager.stopEffect(soundId); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void stopAllEffects(Promise promise) { - IAudioEffectManager manager = AgoraManager.getInstance().mRtcEngine.getAudioEffectManager(); - Integer res = manager.stopAllEffects(); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void preloadEffect(int soundId, String filePath, Promise promise) { - IAudioEffectManager manager = AgoraManager.getInstance().mRtcEngine.getAudioEffectManager(); - Integer res = manager.preloadEffect(soundId, filePath); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void unloadEffect(int soundId, Promise promise) { - IAudioEffectManager manager = AgoraManager.getInstance().mRtcEngine.getAudioEffectManager(); - Integer res = manager.unloadEffect(soundId); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void pauseEffect(int soundId, Promise promise) { - IAudioEffectManager manager = AgoraManager.getInstance().mRtcEngine.getAudioEffectManager(); - Integer res = manager.pauseEffect(soundId); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void pauseAllEffects(Promise promise) { - IAudioEffectManager manager = AgoraManager.getInstance().mRtcEngine.getAudioEffectManager(); - Integer res = manager.pauseAllEffects(); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void resumeEffect(int soundId, Promise promise) { - IAudioEffectManager manager = AgoraManager.getInstance().mRtcEngine.getAudioEffectManager(); - Integer res = manager.resumeEffect(soundId); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void resumeAllEffects(int soundId, Promise promise) { - IAudioEffectManager manager = AgoraManager.getInstance().mRtcEngine.getAudioEffectManager(); - Integer res = manager.resumeAllEffects(); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - // set local video render mode - @ReactMethod - public void setLocalRenderMode(int mode, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.setLocalRenderMode(mode); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - // set remote video render mode - @ReactMethod - public void setRemoteRenderMode(int uid, int mode, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.setRemoteRenderMode(uid, mode); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void getSdkVersion(Promise promise) { - try { - String res = AgoraManager.getInstance().mRtcEngine.getSdkVersion(); - promise.resolve(res); - } catch (Exception e) { - promise.reject(e); - } - } - - @ReactMethod - public void setLocalVideoMirrorMode(int mode, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.setLocalVideoMirrorMode(mode); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void setBeautyEffectOptions(boolean enabled, ReadableMap options, Promise promise) { - BeautyOptions beautyOption = new BeautyOptions(); - beautyOption.lighteningContrastLevel = options.getInt("lighteningContrastLevel"); - beautyOption.lighteningLevel = (float) options.getDouble("lighteningLevel"); - beautyOption.smoothnessLevel = (float) options.getDouble("smoothnessLevel"); - beautyOption.rednessLevel = (float) options.getDouble("rednessLevel"); - Integer res = AgoraManager.getInstance().mRtcEngine.setBeautyEffectOptions(enabled, beautyOption); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void setLocalVoiceChanger(int voiceChanger, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.setLocalVoiceChanger(voiceChanger); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void setLocalVoiceReverbPreset(int preset, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.setLocalVoiceReverbPreset(preset); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void enableSoundPositionIndication(boolean enabled, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.enableSoundPositionIndication(enabled); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void setRemoteVoicePosition(int uid, int pan, int gain, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.setRemoteVoicePosition(uid, pan, gain); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void startLastmileProbeTest(ReadableMap config, Promise promise) { - LastmileProbeConfig probeConfig = new LastmileProbeConfig(); - probeConfig.probeUplink = config.getBoolean("probeUplink"); - probeConfig.probeDownlink = config.getBoolean("probeDownlink"); - probeConfig.expectedDownlinkBitrate = config.getInt("expectedDownlinkBitrate"); - probeConfig.expectedUplinkBitrate = config.getInt("expectedUplinkBitrate"); - Integer res = AgoraManager.getInstance().mRtcEngine.startLastmileProbeTest(probeConfig); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void stopLastmileProbeTest(Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.stopLastmileProbeTest(); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void setRemoteUserPriority(int uid, int userPrority, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.setRemoteUserPriority(uid, userPrority); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void startEchoTestWithInterval(int interval, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.startEchoTest(interval); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void setCameraCapturerConfiguration(ReadableMap options, Promise promise) { - CameraCapturerConfiguration.CAPTURER_OUTPUT_PREFERENCE preference = CameraCapturerConfiguration.CAPTURER_OUTPUT_PREFERENCE.CAPTURER_OUTPUT_PREFERENCE_AUTO; - switch (options.getInt("preference")) { - case 0: { - preference = CameraCapturerConfiguration.CAPTURER_OUTPUT_PREFERENCE.CAPTURER_OUTPUT_PREFERENCE_AUTO; - break; - } - case 1: { - preference = CameraCapturerConfiguration.CAPTURER_OUTPUT_PREFERENCE.CAPTURER_OUTPUT_PREFERENCE_PERFORMANCE; - break; - } - case 2: { - preference = CameraCapturerConfiguration.CAPTURER_OUTPUT_PREFERENCE.CAPTURER_OUTPUT_PREFERENCE_PREVIEW; - break; - } - } - CameraCapturerConfiguration.CAMERA_DIRECTION cameraDirection = CameraCapturerConfiguration.CAMERA_DIRECTION.CAMERA_REAR; - switch (options.getInt("cameraDirection")) { - case 0: { - cameraDirection = CameraCapturerConfiguration.CAMERA_DIRECTION.CAMERA_REAR; - break; - } - case 1: { - cameraDirection = CameraCapturerConfiguration.CAMERA_DIRECTION.CAMERA_FRONT; - break; - } - } - CameraCapturerConfiguration config = new CameraCapturerConfiguration(preference, cameraDirection); - Integer res = AgoraManager.getInstance().mRtcEngine.setCameraCapturerConfiguration(config); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void setParameters(String paramStr, Promise promise) { - Integer res = AgoraManager.getInstance().mRtcEngine.setParameters(paramStr); - if (res == 0) { - promise.resolve(null); - } else { - promise.reject("-1", res.toString()); - } - } - - @ReactMethod - public void getParameter(String paramStr, String args, Promise promise) { - String res = AgoraManager.getInstance().mRtcEngine.getParameter(paramStr, args); - promise.resolve(res); - } - - @ReactMethod - public void getParameters(String str, Promise promise) { - String res = AgoraManager.getInstance().mRtcEngine.getParameters(str); - promise.resolve(res); - } - - private void sendEvent(ReactContext reactContext, - String eventName, - @Nullable WritableMap params) { - StringBuffer agoraEvtName = new StringBuffer(AG_PREFIX); - agoraEvtName.append(eventName); - reactContext - .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) - .emit(agoraEvtName.toString(), params); - } -} diff --git a/android/src/main/java/com/syan/agora/AgoraPackage.java b/android/src/main/java/com/syan/agora/AgoraPackage.java deleted file mode 100644 index 3190f3127..000000000 --- a/android/src/main/java/com/syan/agora/AgoraPackage.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.syan.agora; - -import com.facebook.react.ReactPackage; -import com.facebook.react.bridge.JavaScriptModule; -import com.facebook.react.bridge.NativeModule; -import com.facebook.react.bridge.ReactApplicationContext; -import com.facebook.react.uimanager.ViewManager; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -public class AgoraPackage implements ReactPackage { - - @Override - public List createNativeModules(ReactApplicationContext reactContext) { - return Arrays.asList(new NativeModule[]{ - new AgoraModule(reactContext), - }); - } - - public List> createJSModules() { - return Collections.emptyList(); - } - - @Override - public List createViewManagers(ReactApplicationContext reactContext) { - return Arrays.asList( - new AgoraViewManager() - ); - } -} diff --git a/android/src/main/java/com/syan/agora/AgoraVideoView.java b/android/src/main/java/com/syan/agora/AgoraVideoView.java deleted file mode 100644 index 8bc226fe5..000000000 --- a/android/src/main/java/com/syan/agora/AgoraVideoView.java +++ /dev/null @@ -1,126 +0,0 @@ -package com.syan.agora; - -import android.content.Context; -import android.media.MediaCodec; -import android.media.MediaCodecInfo; -import android.media.MediaCodecList; -import android.media.MediaFormat; -import android.media.MediaMuxer; -import android.os.Build; -import android.support.annotation.RequiresApi; -import android.util.AttributeSet; -import android.util.Log; -import android.view.View; -import android.widget.LinearLayout; - -import com.syan.agora.media.MediaDataAudioObserver; -import com.syan.agora.media.MediaDataVideoObserver; - -import java.io.IOException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; - -import static android.media.MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420SemiPlanar; -import static android.media.MediaFormat.KEY_BIT_RATE; -import static android.media.MediaFormat.KEY_COLOR_FORMAT; -import static android.media.MediaFormat.KEY_FRAME_RATE; -import static android.media.MediaFormat.KEY_I_FRAME_INTERVAL; - -/** - * Created by DB on 2017/6/27. - */ - -public class AgoraVideoView extends LinearLayout implements MediaDataAudioObserver, MediaDataVideoObserver { - - public boolean isShowLocalVideo() { - return showLocalVideo; - } - - public void setShowLocalVideo(boolean showLocalVideo) { - this.showLocalVideo = showLocalVideo; - } - - public Integer getRenderMode() { - return renderMode; - } - - public void setRenderMode(Integer renderMode) { - this.renderMode = renderMode; - } - - public Integer getRemoteUid() { - return remoteUid; - } - - public void setRemoteUid(Integer remoteUid) { - this.remoteUid = remoteUid; - } - - public boolean getZOrderMediaOverlay() { - return zOrderMediaOverlay; - } - - public void setZOrderMediaOverlay(boolean zOrderMediaOverlay) { - this.zOrderMediaOverlay = zOrderMediaOverlay; - } - - private boolean showLocalVideo; - private Integer renderMode = 1; - private Integer remoteUid; - private boolean zOrderMediaOverlay; - - public AgoraVideoView(Context context) { - super(context); - } - - public AgoraVideoView(Context context, AttributeSet attrs) { - super(context, attrs); - } - - - public AgoraVideoView(Context context, AttributeSet attrs, int defStyleAttr) { - super(context, attrs, defStyleAttr); - } - - protected void onVisibilityChanged(View changedView, int visibility) { - super.onVisibilityChanged(changedView, visibility); - if (changedView == this) { - if (null != remoteUid) { - AgoraManager.getInstance().setRemoteRenderMode(remoteUid, renderMode); - } else { - AgoraManager.getInstance().setLocalRenderMode(renderMode); - } - } - } - - @Override - public void onRecordAudioFrame(byte[] data, int audioFrameType, int samples, int bytesPerSample, int channels, int samplesPerSec, long renderTimeMs, int bufferLength) { - - } - - @Override - public void onPlaybackAudioFrame(byte[] data, int audioFrameType, int samples, int bytesPerSample, int channels, int samplesPerSec, long renderTimeMs, int bufferLength) { - - } - - @Override - public void onPlaybackAudioFrameBeforeMixing(int uid, byte[] data, int audioFrameType, int samples, int bytesPerSample, int channels, int samplesPerSec, long renderTimeMs, int bufferLength) { - - } - - @Override - public void onMixedAudioFrame(byte[] data, int audioFrameType, int samples, int bytesPerSample, int channels, int samplesPerSec, long renderTimeMs, int bufferLength) { - - } - - @Override - public void onCaptureVideoFrame(byte[] data, int frameType, int width, int height, int bufferLength, int yStride, int uStride, int vStride, int rotation, long renderTimeMs) { - - } - - @Override - public void onRenderVideoFrame(int uid, byte[] data, int frameType, int width, int height, int bufferLength, int yStride, int uStride, int vStride, int rotation, long renderTimeMs) { - - } -} diff --git a/android/src/main/java/com/syan/agora/AgoraViewManager.java b/android/src/main/java/com/syan/agora/AgoraViewManager.java deleted file mode 100644 index 6944b1eee..000000000 --- a/android/src/main/java/com/syan/agora/AgoraViewManager.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.syan.agora; - -import android.view.SurfaceView; - -import com.facebook.react.uimanager.SimpleViewManager; -import com.facebook.react.uimanager.ThemedReactContext; -import com.facebook.react.uimanager.annotations.ReactProp; - -/** - * Created by DB on 2017/6/23. - */ - -public class AgoraViewManager extends SimpleViewManager { - - public static final String REACT_CLASS = "RCTAgoraVideoView"; - - public SurfaceView surfaceView; - - @Override - public String getName() { - return REACT_CLASS; - } - - @Override - protected AgoraVideoView createViewInstance(ThemedReactContext reactContext) { - return new AgoraVideoView(reactContext); - } - - @ReactProp(name = "mode") - public void setRenderMode(final AgoraVideoView agoraVideoView, Integer renderMode) { - agoraVideoView.setRenderMode(renderMode); - } - - @ReactProp(name = "showLocalVideo") - public void setShowLocalVideo(final AgoraVideoView agoraVideoView, boolean showLocalVideo) { - agoraVideoView.setShowLocalVideo(showLocalVideo); - if (showLocalVideo) { - AgoraManager.getInstance().setupLocalVideo(agoraVideoView.getRenderMode()); - surfaceView = AgoraManager.getInstance().getLocalSurfaceView(); - surfaceView.setZOrderMediaOverlay(agoraVideoView.getZOrderMediaOverlay()); - agoraVideoView.addView(surfaceView); - } - } - - @ReactProp(name = "zOrderMediaOverlay") - public void setZOrderMediaOverlay(final AgoraVideoView agoraVideoView, boolean zOrderMediaOverlay) { - if (surfaceView != null) { - surfaceView.setZOrderMediaOverlay(zOrderMediaOverlay); - } else { - agoraVideoView.setZOrderMediaOverlay(zOrderMediaOverlay); - } - } - - @ReactProp(name = "remoteUid") - public void setRemoteUid(final AgoraVideoView agoraVideoView, final int remoteUid) { - agoraVideoView.setRemoteUid(remoteUid); - if (remoteUid != 0) { - AgoraManager.getInstance().setupRemoteVideo(remoteUid, agoraVideoView.getRenderMode()); - surfaceView = AgoraManager.getInstance().getSurfaceView(remoteUid); - surfaceView.setZOrderMediaOverlay(agoraVideoView.getZOrderMediaOverlay()); - agoraVideoView.addView(surfaceView); - } - } - -} diff --git a/android/src/main/java/com/syan/agora/MediaObserver.java b/android/src/main/java/com/syan/agora/MediaObserver.java deleted file mode 100644 index fda9ecb87..000000000 --- a/android/src/main/java/com/syan/agora/MediaObserver.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.syan.agora; - -import com.facebook.react.bridge.Arguments; -import com.facebook.react.bridge.ReactContext; -import com.facebook.react.bridge.WritableMap; -import com.facebook.react.modules.core.DeviceEventManagerModule; - -import java.nio.charset.Charset; - -import io.agora.rtc.IMetadataObserver; - -public class MediaObserver implements IMetadataObserver { - - private static final Integer MAX_DATA_LENGT = 1024; - - private ReactContext reactCtx; - - public byte[] getMetadata() { - return metadata; - } - - public void setMetadata(byte[] metadata) { - this.metadata = metadata; - } - - private byte[] metadata = null; - - public MediaObserver(ReactContext reactCtx) { - this.reactCtx = reactCtx; - } - - @Override - public int getMaxMetadataSize() { - return MAX_DATA_LENGT; - } - - @Override - public byte[] onReadyToSendMetadata(long timeStampMs) { - if (metadata == null) { - return null; - } - byte[] toSend = metadata; - if (toSend.length > MAX_DATA_LENGT) { - return null; - } - metadata = null; - return toSend; - } - - @Override - public void onMetadataReceived(byte[] buffer, int uid, long timeStampMs) { - WritableMap map = Arguments.createMap(); - map.putString("data", new String(buffer, Charset.forName("UTF-8"))); - map.putString("uid", Integer.toString(uid)); - map.putString("ts", Long.toString(timeStampMs)); - reactCtx.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) - .emit(AgoraConst.AGMediaMetaDataReceived, map); - } -} diff --git a/android/src/main/java/com/syan/agora/media/DecodeDataBuffer.java b/android/src/main/java/com/syan/agora/media/DecodeDataBuffer.java deleted file mode 100644 index 064051e9d..000000000 --- a/android/src/main/java/com/syan/agora/media/DecodeDataBuffer.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.syan.agora.media; - -import java.nio.ByteBuffer; - -public class DecodeDataBuffer { - private int uid; - private ByteBuffer byteBuffer; - - public DecodeDataBuffer(int uid, ByteBuffer byteBuffer) { - this.uid = uid; - this.byteBuffer = byteBuffer; - } - - public int getUid() { - return uid; - } - - public void setUid(int uid) { - this.uid = uid; - } - - public ByteBuffer getByteBuffer() { - return byteBuffer; - } - - public void setByteBuffer(ByteBuffer byteBuffer) { - this.byteBuffer = byteBuffer; - } -} diff --git a/android/src/main/java/com/syan/agora/media/MediaDataAudioObserver.java b/android/src/main/java/com/syan/agora/media/MediaDataAudioObserver.java deleted file mode 100644 index cdfe5a112..000000000 --- a/android/src/main/java/com/syan/agora/media/MediaDataAudioObserver.java +++ /dev/null @@ -1,13 +0,0 @@ - -package com.syan.agora.media; - -public interface MediaDataAudioObserver { - - void onRecordAudioFrame(byte[] data, int audioFrameType, int samples, int bytesPerSample, int channels, int samplesPerSec, long renderTimeMs, int bufferLength); - - void onPlaybackAudioFrame(byte[] data, int audioFrameType, int samples, int bytesPerSample, int channels, int samplesPerSec, long renderTimeMs, int bufferLength); - - void onPlaybackAudioFrameBeforeMixing(int uid, byte[] data,int audioFrameType, int samples, int bytesPerSample, int channels, int samplesPerSec, long renderTimeMs, int bufferLength); - - void onMixedAudioFrame(byte[] data,int audioFrameType, int samples, int bytesPerSample, int channels, int samplesPerSec, long renderTimeMs, int bufferLength); -} \ No newline at end of file diff --git a/android/src/main/java/com/syan/agora/media/MediaDataObserverPlugin.java b/android/src/main/java/com/syan/agora/media/MediaDataObserverPlugin.java deleted file mode 100644 index f79dfefb1..000000000 --- a/android/src/main/java/com/syan/agora/media/MediaDataObserverPlugin.java +++ /dev/null @@ -1,297 +0,0 @@ -package com.syan.agora.media; - -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -import android.graphics.ImageFormat; -import android.graphics.Matrix; -import android.graphics.Rect; -import android.graphics.YuvImage; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.concurrent.CopyOnWriteArrayList; - -public class MediaDataObserverPlugin implements MediaPreProcessing.ProgressCallback { - - private final CopyOnWriteArrayList videoObserverList = new CopyOnWriteArrayList<>(); - private final CopyOnWriteArrayList audioObserverList = new CopyOnWriteArrayList<>(); - - private static final int VIDEO_DEFAULT_BUFFER_SIZE = 3240 * 1080; // default maximum video size Full HD+ - private static final int AUDIO_DEFAULT_BUFFER_SIZE = 2048; - - public ByteBuffer byteBufferCapture = ByteBuffer.allocateDirect(VIDEO_DEFAULT_BUFFER_SIZE); - public ByteBuffer byteBufferRender = ByteBuffer.allocateDirect(VIDEO_DEFAULT_BUFFER_SIZE); - public ByteBuffer byteBufferAudioRecord = ByteBuffer.allocateDirect(AUDIO_DEFAULT_BUFFER_SIZE); - public ByteBuffer byteBufferAudioPlay = ByteBuffer.allocateDirect(AUDIO_DEFAULT_BUFFER_SIZE); - public ByteBuffer byteBufferBeforeAudioMix = ByteBuffer.allocateDirect(AUDIO_DEFAULT_BUFFER_SIZE); - public ByteBuffer byteBufferAudioMix = ByteBuffer.allocateDirect(AUDIO_DEFAULT_BUFFER_SIZE); - - private final ArrayList decodeBufferList = new ArrayList<>(); - - private static MediaDataObserverPlugin myAgent = null; - - private boolean beCaptureVideoShot = false; - private boolean beRenderVideoShot = false; - private String captureFilePath = null; - private String renderFilePath = null; - private int renderVideoShotUid; - - public static MediaDataObserverPlugin the() { - if (myAgent == null) { - synchronized (MediaDataObserverPlugin.class) { - if (myAgent == null) - myAgent = new MediaDataObserverPlugin(); - } - } - return myAgent; - } - - public void addVideoObserver(MediaDataVideoObserver observer) { - videoObserverList.add(observer); - } - - public void removeVideoObserver(MediaDataVideoObserver observer) { - videoObserverList.remove(observer); - } - - public void addAudioObserver(MediaDataAudioObserver observer) { - audioObserverList.add(observer); - } - - public void removeAudioObserver(MediaDataAudioObserver observer) { - audioObserverList.remove(observer); - } - - public void saveCaptureVideoSnapshot(String filePath) { - beCaptureVideoShot = true; - captureFilePath = filePath; - } - - public void saveRenderVideoSnapshot(String filePath, int uid) { - beRenderVideoShot = true; - renderFilePath = filePath; - renderVideoShotUid = uid; - } - - public void addDecodeBuffer(int uid) { - ByteBuffer byteBuffer = ByteBuffer.allocateDirect(VIDEO_DEFAULT_BUFFER_SIZE); - decodeBufferList.add(new DecodeDataBuffer(uid, byteBuffer)); - MediaPreProcessing.setVideoDecodeByteBuffer(uid, byteBuffer); - } - - public void removeDecodeBuffer(int uid) { - Iterator it = decodeBufferList.iterator(); - while (it.hasNext()) { - DecodeDataBuffer buffer = it.next(); - if (buffer.getUid() == uid) { - it.remove(); - } - } - - MediaPreProcessing.setVideoDecodeByteBuffer(uid, null); - } - - public void removeAllBuffer() { - decodeBufferList.removeAll(decodeBufferList); - releaseBuffer(); - } - - @Override - public void onCaptureVideoFrame(int videoFrameType, int width, int height, int bufferLength, int yStride, int uStride, int vStride, int rotation, long renderTimeMs) { - - byte[] buf = new byte[bufferLength]; - byteBufferCapture.limit(bufferLength); - byteBufferCapture.get(buf); - byteBufferCapture.flip(); - - for (MediaDataVideoObserver observer : videoObserverList) { - observer.onCaptureVideoFrame(buf, videoFrameType, width, height, bufferLength, yStride, uStride, vStride, rotation, renderTimeMs); - } - - byteBufferCapture.put(buf); - byteBufferCapture.flip(); - - if (beCaptureVideoShot) { - beCaptureVideoShot = false; - - getVideoSnapshot(width, height, rotation, bufferLength, buf, captureFilePath, yStride, uStride, vStride); - } - } - - @Override - public void onRenderVideoFrame(int uid, int videoFrameType, int width, int height, int bufferLength, int yStride, int uStride, int vStride, int rotation, long renderTimeMs) { - - for (MediaDataVideoObserver observer : videoObserverList) { - Iterator it = decodeBufferList.iterator(); - while (it.hasNext()) { - DecodeDataBuffer tmp = it.next(); - if (tmp.getUid() == uid) { - byte[] buf = new byte[bufferLength]; - tmp.getByteBuffer().limit(bufferLength); - tmp.getByteBuffer().get(buf); - tmp.getByteBuffer().flip(); - - observer.onRenderVideoFrame(uid, buf, videoFrameType, width, height, bufferLength, yStride, uStride, vStride, rotation, renderTimeMs); - - tmp.getByteBuffer().put(buf); - tmp.getByteBuffer().flip(); - - if (beRenderVideoShot) { - if (uid == renderVideoShotUid) { - beRenderVideoShot = false; - - getVideoSnapshot(width, height, rotation, bufferLength, buf, renderFilePath, yStride, uStride, vStride); - } - } - } - } - } - } - - @Override - public void onRecordAudioFrame(int audioFrameType, int samples, int bytesPerSample, int channels, int samplesPerSec, long renderTimeMs, int bufferLength) { - byte[] buf = new byte[bufferLength]; - byteBufferAudioRecord.limit(bufferLength); - byteBufferAudioRecord.get(buf); - byteBufferAudioRecord.flip(); - - for (MediaDataAudioObserver observer : audioObserverList) { - observer.onRecordAudioFrame(buf, audioFrameType, samples, bytesPerSample, channels, samplesPerSec, renderTimeMs, bufferLength); - } - - byteBufferAudioRecord.put(buf); - byteBufferAudioRecord.flip(); - } - - @Override - public void onPlaybackAudioFrame(int audioFrameType, int samples, int bytesPerSample, int channels, int samplesPerSec, long renderTimeMs, int bufferLength) { - byte[] buf = new byte[bufferLength]; - byteBufferAudioPlay.limit(bufferLength); - byteBufferAudioPlay.get(buf); - byteBufferAudioPlay.flip(); - - for (MediaDataAudioObserver observer : audioObserverList) { - observer.onPlaybackAudioFrame(buf, audioFrameType, samples, bytesPerSample, channels, samplesPerSec, renderTimeMs, bufferLength); - } - - byteBufferAudioPlay.put(buf); - byteBufferAudioPlay.flip(); - } - - @Override - public void onPlaybackAudioFrameBeforeMixing(int uid, int audioFrameType, int samples, int bytesPerSample, int channels, int samplesPerSec, long renderTimeMs, int bufferLength) { - byte[] buf = new byte[bufferLength]; - byteBufferBeforeAudioMix.limit(bufferLength); - byteBufferBeforeAudioMix.get(buf); - byteBufferBeforeAudioMix.flip(); - - for (MediaDataAudioObserver observer : audioObserverList) { - observer.onPlaybackAudioFrameBeforeMixing(uid, buf, audioFrameType, samples, bytesPerSample, channels, samplesPerSec, renderTimeMs, bufferLength); - } - - byteBufferBeforeAudioMix.put(buf); - byteBufferBeforeAudioMix.flip(); - } - - @Override - public void onMixedAudioFrame(int audioFrameType, int samples, int bytesPerSample, int channels, int samplesPerSec, long renderTimeMs, int bufferLength) { - byte[] buf = new byte[bufferLength]; - byteBufferAudioMix.limit(bufferLength); - byteBufferAudioMix.get(buf); - byteBufferAudioMix.flip(); - - for (MediaDataAudioObserver observer : audioObserverList) { - observer.onMixedAudioFrame(buf, audioFrameType, samples, bytesPerSample, channels, samplesPerSec, renderTimeMs, bufferLength); - } - - byteBufferAudioMix.put(buf); - byteBufferAudioMix.flip(); - } - - private void getVideoSnapshot(int width, int height, int rotation, int bufferLength, byte[] buffer, String filePath, int yStride, int uStride, int vStride) { - File file = new File(filePath); - - byte[] NV21 = new byte[bufferLength]; - swapYU12toYUV420SemiPlanar(buffer, NV21, width, height, yStride, uStride, vStride); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - - int[] strides = {yStride, yStride}; - YuvImage image = new YuvImage(NV21, ImageFormat.NV21, width, height, strides); - - image.compressToJpeg( - new Rect(0, 0, image.getWidth(), image.getHeight()), - 100, baos); - - // rotate picture when saving to file - Matrix matrix = new Matrix(); - matrix.postRotate(rotation); - byte[] bytes = baos.toByteArray(); - try { - baos.close(); - } catch (IOException e) { - e.printStackTrace(); - } - Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); - Bitmap target = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); - - File fileParent = file.getParentFile(); - if (!fileParent.exists()) { - fileParent.mkdirs(); - } - if (file.exists()) { - file.delete(); - } - - try { - file.createNewFile(); - } catch (IOException e) { - e.printStackTrace(); - } - - FileOutputStream fos = null; - try { - fos = new FileOutputStream(file); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } - - target.compress(Bitmap.CompressFormat.JPEG, 100, fos); - - target.recycle(); - bitmap.recycle(); - - try { - fos.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - private void swapYU12toYUV420SemiPlanar(byte[] yu12bytes, byte[] i420bytes, int width, int height, int yStride, int uStride, int vStride) { - System.arraycopy(yu12bytes, 0, i420bytes, 0, yStride * height); - int startPos = yStride * height; - int yv_start_pos_u = startPos; - int yv_start_pos_v = startPos + startPos / 4; - for (int i = 0; i < startPos / 4; i++) { - i420bytes[startPos + 2 * i + 0] = yu12bytes[yv_start_pos_v + i]; - i420bytes[startPos + 2 * i + 1] = yu12bytes[yv_start_pos_u + i]; - } - } - - public void releaseBuffer() { - byteBufferCapture.clear(); - byteBufferRender.clear(); - byteBufferAudioRecord.clear(); - byteBufferAudioPlay.clear(); - byteBufferBeforeAudioMix.clear(); - byteBufferAudioMix.clear(); - } - -} \ No newline at end of file diff --git a/android/src/main/java/com/syan/agora/media/MediaDataVideoObserver.java b/android/src/main/java/com/syan/agora/media/MediaDataVideoObserver.java deleted file mode 100644 index 68cf25d50..000000000 --- a/android/src/main/java/com/syan/agora/media/MediaDataVideoObserver.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.syan.agora.media; - -public interface MediaDataVideoObserver { - - void onCaptureVideoFrame(byte[] data, int frameType, int width, int height, int bufferLength, int yStride, int uStride, int vStride, int rotation, long renderTimeMs); - - void onRenderVideoFrame(int uid, byte[] data, int frameType, int width, int height, int bufferLength, int yStride, int uStride, int vStride, int rotation, long renderTimeMs); -} \ No newline at end of file diff --git a/android/src/main/java/com/syan/agora/media/MediaPreProcessing.java b/android/src/main/java/com/syan/agora/media/MediaPreProcessing.java deleted file mode 100644 index 7327dd34a..000000000 --- a/android/src/main/java/com/syan/agora/media/MediaPreProcessing.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.syan.agora.media; - -import java.nio.ByteBuffer; - -public class MediaPreProcessing { - static { - System.loadLibrary("apm-plugin-raw-data-api-java"); - } - - public interface ProgressCallback { - void onCaptureVideoFrame(int videoFrameType, int width, int height, int bufferLength, int yStride, int uStride, int vStride, int rotation, long renderTimeMs); - - void onRenderVideoFrame(int uid, int videoFrameType, int width, int height, int bufferLength, int yStride, int uStride, int vStride, int rotation, long renderTimeMs); - - void onRecordAudioFrame(int audioFrameType, int samples, int bytesPerSample, int channels, int samplesPerSec, long renderTimeMs, int bufferLength); - - void onPlaybackAudioFrame(int audioFrameType, int samples, int bytesPerSample, int channels, int samplesPerSec, long renderTimeMs, int bufferLength); - - void onPlaybackAudioFrameBeforeMixing(int uid, int audioFrameType, int samples, int bytesPerSample, int channels, int samplesPerSec, long renderTimeMs, int bufferLength); - - void onMixedAudioFrame(int audioFrameType, int samples, int bytesPerSample, int channels, int samplesPerSec, long renderTimeMs, int bufferLength); - } - - public static native void setCallback(ProgressCallback callback); - - public static native void setVideoCaptureByteBuffer(ByteBuffer byteBuffer); - - public static native void setAudioRecordByteBuffer(ByteBuffer byteBuffer); - - public static native void setAudioPlayByteBuffer(ByteBuffer byteBuffer); - - public static native void setBeforeAudioMixByteBuffer(ByteBuffer byteBuffer); - - public static native void setAudioMixByteBuffer(ByteBuffer byteBuffer); - - public static native void setVideoDecodeByteBuffer(int uid, ByteBuffer byteBuffer); - - public static native void releasePoint(); -} \ No newline at end of file diff --git a/android/src/main/java/io/agora/rtc/base/Annotations.java b/android/src/main/java/io/agora/rtc/base/Annotations.java new file mode 100644 index 000000000..d1e6fd652 --- /dev/null +++ b/android/src/main/java/io/agora/rtc/base/Annotations.java @@ -0,0 +1,780 @@ +package io.agora.rtc.base; + +import androidx.annotation.IntDef; +import androidx.annotation.StringDef; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +import io.agora.rtc.Constants; +import io.agora.rtc.IMetadataObserver; +import io.agora.rtc.video.BeautyOptions; +import io.agora.rtc.video.VideoCanvas; + +public class Annotations { + + @IntDef({ + AgoraRtcAppType.NATIVE, + AgoraRtcAppType.COCOS, + AgoraRtcAppType.UNITY, + AgoraRtcAppType.ELECTRON, + AgoraRtcAppType.FLUTTER, + AgoraRtcAppType.UNREAL, + AgoraRtcAppType.XAMARIN, + AgoraRtcAppType.APICLOUD, + AgoraRtcAppType.REACTNATIVE, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraRtcAppType { + int NATIVE = 0; + int COCOS = 1; + int UNITY = 2; + int ELECTRON = 3; + int FLUTTER = 4; + int UNREAL = 5; + int XAMARIN = 6; + int APICLOUD = 7; + int REACTNATIVE = 8; + } + + @IntDef({ + AgoraAudioCodecProfileType.LC_AAC, + AgoraAudioCodecProfileType.HE_AAC, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraAudioCodecProfileType { + int LC_AAC = 0; + int HE_AAC = 1; + } + + @IntDef({ + Constants.AUDIO_EQUALIZATION_BAND_31, + Constants.AUDIO_EQUALIZATION_BAND_62, + Constants.AUDIO_EQUALIZATION_BAND_125, + Constants.AUDIO_EQUALIZATION_BAND_250, + Constants.AUDIO_EQUALIZATION_BAND_500, + Constants.AUDIO_EQUALIZATION_BAND_1K, + Constants.AUDIO_EQUALIZATION_BAND_2K, + Constants.AUDIO_EQUALIZATION_BAND_4K, + Constants.AUDIO_EQUALIZATION_BAND_8K, + Constants.AUDIO_EQUALIZATION_BAND_16K, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraAudioEqualizationBandFrequency { + } + + @IntDef({ + Constants.LOCAL_AUDIO_STREAM_ERROR_OK, + Constants.LOCAL_AUDIO_STREAM_ERROR_FAILURE, + Constants.LOCAL_AUDIO_STREAM_ERROR_DEVICE_NO_PERMISSION, + Constants.LOCAL_AUDIO_STREAM_ERROR_DEVICE_BUSY, + Constants.LOCAL_AUDIO_STREAM_ERROR_CAPTURE_FAILURE, + Constants.LOCAL_AUDIO_STREAM_ERROR_ENCODE_FAILURE, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraAudioLocalError { + } + + @IntDef({ + Constants.LOCAL_AUDIO_STREAM_STATE_STOPPED, + Constants.LOCAL_AUDIO_STREAM_STATE_CAPTURING, + Constants.LOCAL_AUDIO_STREAM_STATE_ENCODING, + Constants.LOCAL_AUDIO_STREAM_STATE_FAILED, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraAudioLocalState { + } + + @IntDef({ + Constants.MEDIA_ENGINE_AUDIO_ERROR_MIXING_OPEN, + Constants.MEDIA_ENGINE_AUDIO_ERROR_MIXING_TOO_FREQUENT, + Constants.MEDIA_ENGINE_AUDIO_EVENT_MIXING_INTERRUPTED_EOF, + AgoraAudioMixingErrorCode.MEDIA_ENGINE_AUDIO_ERROR_OK, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraAudioMixingErrorCode { + int MEDIA_ENGINE_AUDIO_ERROR_OK = 0; + } + + @IntDef({ + Constants.MEDIA_ENGINE_AUDIO_EVENT_MIXING_PLAY, + Constants.MEDIA_ENGINE_AUDIO_EVENT_MIXING_PAUSED, + Constants.MEDIA_ENGINE_AUDIO_EVENT_MIXING_STOPPED, + Constants.MEDIA_ENGINE_AUDIO_EVENT_MIXING_ERROR, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraAudioMixingStateCode { + } + + @IntDef({ + Constants.AUDIO_ROUTE_DEFAULT, + Constants.AUDIO_ROUTE_HEADSET, + Constants.AUDIO_ROUTE_EARPIECE, + Constants.AUDIO_ROUTE_HEADSETNOMIC, + Constants.AUDIO_ROUTE_SPEAKERPHONE, + Constants.AUDIO_ROUTE_LOUDSPEAKER, + Constants.AUDIO_ROUTE_HEADSETBLUETOOTH, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraAudioOutputRouting { + } + + @IntDef({ + Constants.AUDIO_PROFILE_DEFAULT, + Constants.AUDIO_PROFILE_SPEECH_STANDARD, + Constants.AUDIO_PROFILE_MUSIC_STANDARD, + Constants.AUDIO_PROFILE_MUSIC_STANDARD_STEREO, + Constants.AUDIO_PROFILE_MUSIC_HIGH_QUALITY, + Constants.AUDIO_PROFILE_MUSIC_HIGH_QUALITY_STEREO, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraAudioProfile { + } + + @IntDef({ + Constants.RAW_AUDIO_FRAME_OP_MODE_READ_ONLY, + Constants.RAW_AUDIO_FRAME_OP_MODE_WRITE_ONLY, + Constants.RAW_AUDIO_FRAME_OP_MODE_READ_WRITE, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraAudioRawFrameOperationMode { + } + + @IntDef({ + Constants.AUDIO_RECORDING_QUALITY_LOW, + Constants.AUDIO_RECORDING_QUALITY_MEDIUM, + Constants.AUDIO_RECORDING_QUALITY_HIGH, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraAudioRecordingQuality { + } + + @IntDef({ + Constants.REMOTE_AUDIO_STATE_STOPPED, + Constants.REMOTE_AUDIO_STATE_STARTING, + Constants.REMOTE_AUDIO_STATE_DECODING, + Constants.REMOTE_AUDIO_STATE_FROZEN, + Constants.REMOTE_AUDIO_STATE_FAILED, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraAudioRemoteState { + } + + @IntDef({ + Constants.REMOTE_AUDIO_REASON_INTERNAL, + Constants.REMOTE_AUDIO_REASON_NETWORK_CONGESTION, + Constants.REMOTE_AUDIO_REASON_NETWORK_RECOVERY, + Constants.REMOTE_AUDIO_REASON_LOCAL_MUTED, + Constants.REMOTE_AUDIO_REASON_LOCAL_UNMUTED, + Constants.REMOTE_AUDIO_REASON_REMOTE_MUTED, + Constants.REMOTE_AUDIO_REASON_REMOTE_UNMUTED, + Constants.REMOTE_AUDIO_REASON_REMOTE_OFFLINE, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraAudioRemoteStateReason { + } + + @IntDef({ + Constants.AUDIO_REVERB_OFF, + Constants.AUDIO_REVERB_POPULAR, + Constants.AUDIO_REVERB_RNB, + Constants.AUDIO_REVERB_ROCK, + Constants.AUDIO_REVERB_HIPHOP, + Constants.AUDIO_REVERB_VOCAL_CONCERT, + Constants.AUDIO_REVERB_KTV, + Constants.AUDIO_REVERB_STUDIO, + Constants.AUDIO_REVERB_FX_KTV, + Constants.AUDIO_REVERB_FX_VOCAL_CONCERT, + Constants.AUDIO_REVERB_FX_UNCLE, + Constants.AUDIO_REVERB_FX_SISTER, + Constants.AUDIO_REVERB_FX_STUDIO, + Constants.AUDIO_REVERB_FX_POPULAR, + Constants.AUDIO_REVERB_FX_RNB, + Constants.AUDIO_REVERB_FX_PHONOGRAPH, + Constants.AUDIO_VIRTUAL_STEREO, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraAudioReverbPreset { + } + + @IntDef({ + Constants.AUDIO_REVERB_DRY_LEVEL, + Constants.AUDIO_REVERB_WET_LEVEL, + Constants.AUDIO_REVERB_ROOM_SIZE, + Constants.AUDIO_REVERB_WET_DELAY, + Constants.AUDIO_REVERB_STRENGTH, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraAudioReverbType { + } + + @IntDef({ + AgoraAudioSampleRateType.TYPE_32000, + AgoraAudioSampleRateType.TYPE_44100, + AgoraAudioSampleRateType.TYPE_48000, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraAudioSampleRateType { + int TYPE_32000 = 32000; + int TYPE_44100 = 44100; + int TYPE_48000 = 48000; + } + + @IntDef({ + Constants.AUDIO_SCENARIO_DEFAULT, + Constants.AUDIO_SCENARIO_CHATROOM_ENTERTAINMENT, + Constants.AUDIO_SCENARIO_EDUCATION, + Constants.AUDIO_SCENARIO_GAME_STREAMING, + Constants.AUDIO_SCENARIO_SHOWROOM, + Constants.AUDIO_SCENARIO_CHATROOM_GAMING, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraAudioScenario { + } + + @IntDef({ + Constants.VOICE_CHANGER_OFF, + Constants.VOICE_CHANGER_OLDMAN, + Constants.VOICE_CHANGER_BABYBOY, + Constants.VOICE_CHANGER_BABYGIRL, + Constants.VOICE_CHANGER_ZHUBAJIE, + Constants.VOICE_CHANGER_ETHEREAL, + Constants.VOICE_CHANGER_HULK, + Constants.VOICE_BEAUTY_VIGOROUS, + Constants.VOICE_BEAUTY_DEEP, + Constants.VOICE_BEAUTY_MELLOW, + Constants.VOICE_BEAUTY_FALSETTO, + Constants.VOICE_BEAUTY_FULL, + Constants.VOICE_BEAUTY_CLEAR, + Constants.VOICE_BEAUTY_RESOUNDING, + Constants.VOICE_BEAUTY_RINGING, + Constants.VOICE_BEAUTY_SPACIAL, + Constants.GENERAL_BEAUTY_VOICE_MALE_MAGNETIC, + Constants.GENERAL_BEAUTY_VOICE_FEMALE_FRESH, + Constants.GENERAL_BEAUTY_VOICE_FEMALE_VITALITY, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraAudioVoiceChanger { + } + + @IntDef({ + AgoraCameraCaptureOutputPreference.CAPTURER_OUTPUT_PREFERENCE_AUTO, + AgoraCameraCaptureOutputPreference.CAPTURER_OUTPUT_PREFERENCE_PERFORMANCE, + AgoraCameraCaptureOutputPreference.CAPTURER_OUTPUT_PREFERENCE_PREVIEW, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraCameraCaptureOutputPreference { + int CAPTURER_OUTPUT_PREFERENCE_AUTO = 0; + int CAPTURER_OUTPUT_PREFERENCE_PERFORMANCE = 1; + int CAPTURER_OUTPUT_PREFERENCE_PREVIEW = 2; + } + + @IntDef({ + AgoraCameraDirection.CAMERA_REAR, + AgoraCameraDirection.CAMERA_FRONT, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraCameraDirection { + int CAMERA_REAR = 0; + int CAMERA_FRONT = 1; + } + + @IntDef({ + Constants.RELAY_OK, + Constants.RELAY_ERROR_SERVER_ERROR_RESPONSE, + Constants.RELAY_ERROR_SERVER_NO_RESPONSE, + Constants.RELAY_ERROR_NO_RESOURCE_AVAILABLE, + Constants.RELAY_ERROR_FAILED_JOIN_SRC, + Constants.RELAY_ERROR_FAILED_JOIN_DEST, + Constants.RELAY_ERROR_FAILED_PACKET_RECEIVED_FROM_SRC, + Constants.RELAY_ERROR_FAILED_PACKET_SENT_TO_DEST, + Constants.RELAY_ERROR_SERVER_CONNECTION_LOST, + Constants.RELAY_ERROR_INTERNAL_ERROR, + Constants.RELAY_ERROR_SRC_TOKEN_EXPIRED, + Constants.RELAY_ERROR_DEST_TOKEN_EXPIRED, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraChannelMediaRelayError { + } + + @IntDef({ + Constants.RELAY_EVENT_NETWORK_DISCONNECTED, + Constants.RELAY_EVENT_NETWORK_CONNECTED, + Constants.RELAY_EVENT_PACKET_JOINED_SRC_CHANNEL, + Constants.RELAY_EVENT_PACKET_JOINED_DEST_CHANNEL, + Constants.RELAY_EVENT_PACKET_SENT_TO_DEST_CHANNEL, + Constants.RELAY_EVENT_PACKET_RECEIVED_VIDEO_FROM_SRC, + Constants.RELAY_EVENT_PACKET_RECEIVED_AUDIO_FROM_SRC, + Constants.RELAY_EVENT_PACKET_UPDATE_DEST_CHANNEL, + Constants.RELAY_EVENT_PACKET_UPDATE_DEST_CHANNEL_REFUSED, + Constants.RELAY_EVENT_PACKET_UPDATE_DEST_CHANNEL_NOT_CHANGE, + Constants.RELAY_EVENT_PACKET_UPDATE_DEST_CHANNEL_IS_NULL, + Constants.RELAY_EVENT_VIDEO_PROFILE_UPDATE, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraChannelMediaRelayEvent { + } + + @IntDef({ + Constants.RELAY_STATE_IDLE, + Constants.RELAY_STATE_CONNECTING, + Constants.RELAY_STATE_RUNNING, + Constants.RELAY_STATE_FAILURE, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraChannelMediaRelayState { + } + + @IntDef({ + Constants.CHANNEL_PROFILE_COMMUNICATION, + Constants.CHANNEL_PROFILE_LIVE_BROADCASTING, + Constants.CHANNEL_PROFILE_GAME, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraChannelProfile { + } + + @IntDef({ + Constants.CLIENT_ROLE_BROADCASTER, + Constants.CLIENT_ROLE_AUDIENCE, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraClientRole { + } + + @IntDef({ + Constants.CONNECTION_CHANGED_CONNECTING, + Constants.CONNECTION_CHANGED_JOIN_SUCCESS, + Constants.CONNECTION_CHANGED_INTERRUPTED, + Constants.CONNECTION_CHANGED_BANNED_BY_SERVER, + Constants.CONNECTION_CHANGED_JOIN_FAILED, + Constants.CONNECTION_CHANGED_LEAVE_CHANNEL, + Constants.CONNECTION_CHANGED_INVALID_APP_ID, + Constants.CONNECTION_CHANGED_INVALID_CHANNEL_NAME, + Constants.CONNECTION_CHANGED_INVALID_TOKEN, + Constants.CONNECTION_CHANGED_TOKEN_EXPIRED, + Constants.CONNECTION_CHANGED_REJECTED_BY_SERVER, + Constants.CONNECTION_CHANGED_SETTING_PROXY_SERVER, + Constants.CONNECTION_CHANGED_RENEW_TOKEN, + Constants.CONNECTION_CHANGED_CLIENT_IP_ADDRESS_CHANGED, + Constants.CONNECTION_CHANGED_KEEP_ALIVE_TIMEOUT, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraConnectionChangedReason { + } + + @IntDef({ + Constants.CONNECTION_STATE_DISCONNECTED, + Constants.CONNECTION_STATE_CONNECTING, + Constants.CONNECTION_STATE_CONNECTED, + Constants.CONNECTION_STATE_RECONNECTING, + Constants.CONNECTION_STATE_FAILED, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraConnectionStateType { + } + + @IntDef({ + AgoraDegradationPreference.MAINTAIN_QUALITY, + AgoraDegradationPreference.MAINTAIN_FRAMERATE, + AgoraDegradationPreference.MAINTAIN_BALANCED, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraDegradationPreference { + int MAINTAIN_QUALITY = 0; + int MAINTAIN_FRAMERATE = 1; + int MAINTAIN_BALANCED = 2; + } + + @StringDef({ + AgoraEncryptionMode.AES128XTS, + AgoraEncryptionMode.AES256XTS, + AgoraEncryptionMode.AES128ECB, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraEncryptionMode { + String AES128XTS = "aes-128-xts"; + String AES256XTS = "aes-256-xts"; + String AES128ECB = "aes-128-ecb"; + } + + @IntDef({ + Constants.ERR_OK, + Constants.ERR_FAILED, + Constants.ERR_INVALID_ARGUMENT, + Constants.ERR_NOT_READY, + Constants.ERR_NOT_SUPPORTED, + Constants.ERR_REFUSED, + Constants.ERR_BUFFER_TOO_SMALL, + Constants.ERR_NOT_INITIALIZED, + Constants.ERR_NO_PERMISSION, + Constants.ERR_TIMEDOUT, + Constants.ERR_CANCELED, + Constants.ERR_TOO_OFTEN, + Constants.ERR_BIND_SOCKET, + Constants.ERR_NET_DOWN, + Constants.ERR_NET_NOBUFS, + Constants.ERR_JOIN_CHANNEL_REJECTED, + Constants.ERR_LEAVE_CHANNEL_REJECTED, + Constants.ERR_ALREADY_IN_USE, + Constants.ERR_INVALID_APP_ID, + Constants.ERR_INVALID_CHANNEL_NAME, + Constants.ERR_TOKEN_EXPIRED, + Constants.ERR_INVALID_TOKEN, + Constants.ERR_CONNECTION_INTERRUPTED, + Constants.ERR_CONNECTION_LOST, + Constants.ERR_NOT_IN_CHANNEL, + Constants.ERR_SIZE_TOO_LARGE, + Constants.ERR_BITRATE_LIMIT, + Constants.ERR_TOO_MANY_DATA_STREAMS, + Constants.ERR_DECRYPTION_FAILED, + Constants.ERR_CLIENT_IS_BANNED_BY_SERVER, + Constants.ERR_WATERMARK_PARAM, + Constants.ERR_WATERMARK_PATH, + Constants.ERR_WATERMARK_PNG, + Constants.ERR_WATERMARKR_INFO, + Constants.ERR_WATERMARK_ARGB, + Constants.ERR_WATERMARK_READ, + Constants.ERR_ENCRYPTED_STREAM_NOT_ALLOWED_PUBLISHED, + Constants.ERR_INVALID_USER_ACCOUNT, + Constants.ERR_PUBLISH_STREAM_CDN_ERROR, + Constants.ERR_PUBLISH_STREAM_NUM_REACH_LIMIT, + Constants.ERR_PUBLISH_STREAM_NOT_AUTHORIZED, + Constants.ERR_PUBLISH_STREAM_INTERNAL_SERVER_ERROR, + Constants.ERR_PUBLISH_STREAM_NOT_FOUND, + Constants.ERR_PUBLISH_STREAM_FORMAT_NOT_SUPPORTED, + Constants.ERR_LOAD_MEDIA_ENGINE, + Constants.ERR_START_CALL, + Constants.ERR_START_CAMERA, + Constants.ERR_START_VIDEO_RENDER, + Constants.ERR_ADM_GENERAL_ERROR, + Constants.ERR_ADM_JAVA_RESOURCE, + Constants.ERR_ADM_SAMPLE_RATE, + Constants.ERR_ADM_INIT_PLAYOUT, + Constants.ERR_ADM_START_PLAYOUT, + Constants.ERR_ADM_STOP_PLAYOUT, + Constants.ERR_ADM_INIT_RECORDING, + Constants.ERR_ADM_START_RECORDING, + Constants.ERR_ADM_STOP_RECORDING, + Constants.ERR_ADM_RUNTIME_PLAYOUT_ERROR, + Constants.ERR_ADM_RUNTIME_RECORDING_ERROR, + Constants.ERR_ADM_RECORD_AUDIO_FAILED, + Constants.ERR_ADM_INIT_LOOPBACK, + Constants.ERR_ADM_START_LOOPBACK, + Constants.ERR_AUDIO_BT_SCO_FAILED, + Constants.ERR_ADM_NO_RECORDING_DEVICE, + Constants.ERR_ADM_NO_PLAYOUT_DEVICE, + Constants.ERR_VDM_CAMERA_NOT_AUTHORIZED, + Constants.ERR_VCM_UNKNOWN_ERROR, + Constants.ERR_VCM_ENCODER_INIT_ERROR, + Constants.ERR_VCM_ENCODER_ENCODE_ERROR, + Constants.ERR_VCM_ENCODER_SET_ERROR, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraErrorCode { + } + + @IntDef({ + Constants.INJECT_STREAM_STATUS_START_SUCCESS, + Constants.INJECT_STREAM_STATUS_START_ALREADY_EXISTS, + Constants.INJECT_STREAM_STATUS_START_UNAUTHORIZED, + Constants.INJECT_STREAM_STATUS_START_TIMEDOUT, + Constants.INJECT_STREAM_STATUS_START_FAILED, + Constants.INJECT_STREAM_STATUS_STOP_SUCCESS, + Constants.INJECT_STREAM_STATUS_STOP_NOT_FOUND, + Constants.INJECT_STREAM_STATUS_STOP_UNAUTHORIZED, + Constants.INJECT_STREAM_STATUS_STOP_TIMEDOUT, + Constants.INJECT_STREAM_STATUS_STOP_FAILED, + Constants.INJECT_STREAM_STATUS_BROKEN, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraInjectStreamStatus { + } + + @IntDef({ + Constants.LASTMILE_PROBE_RESULT_COMPLETE, + Constants.LASTMILE_PROBE_RESULT_INCOMPLETE_NO_BWE, + Constants.LASTMILE_PROBE_RESULT_UNAVAILABLE, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraLastmileProbeResultState { + } + + @IntDef({ + BeautyOptions.LIGHTENING_CONTRAST_LOW, + BeautyOptions.LIGHTENING_CONTRAST_NORMAL, + BeautyOptions.LIGHTENING_CONTRAST_HIGH, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraLighteningContrastLevel { + } + + @IntDef({ + Constants.LOCAL_VIDEO_STREAM_ERROR_OK, + Constants.LOCAL_VIDEO_STREAM_ERROR_FAILURE, + Constants.LOCAL_VIDEO_STREAM_ERROR_DEVICE_NO_PERMISSION, + Constants.LOCAL_VIDEO_STREAM_ERROR_DEVICE_BUSY, + Constants.LOCAL_VIDEO_STREAM_ERROR_CAPTURE_FAILURE, + Constants.LOCAL_VIDEO_STREAM_ERROR_ENCODE_FAILURE, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraLocalVideoStreamError { + } + + @IntDef({ + Constants.LOCAL_VIDEO_STREAM_STATE_STOPPED, + Constants.LOCAL_VIDEO_STREAM_STATE_CAPTURING, + Constants.LOCAL_VIDEO_STREAM_STATE_ENCODING, + Constants.LOCAL_VIDEO_STREAM_STATE_FAILED, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraLocalVideoStreamState { + } + + @IntDef({ + Constants.LOG_FILTER_OFF, + Constants.LOG_FILTER_DEBUG, + Constants.LOG_FILTER_INFO, + Constants.LOG_FILTER_WARNING, + Constants.LOG_FILTER_ERROR, + Constants.LOG_FILTER_CRITICAL, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraLogFilter { + } + + @IntDef({ + Constants.MEDIA_TYPE_NONE, + Constants.MEDIA_TYPE_AUDIO_ONLY, + Constants.MEDIA_TYPE_VIDEO_ONLY, + Constants.MEDIA_TYPE_AUDIO_AND_VIDEO, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraMediaType { + } + + @IntDef({ + IMetadataObserver.UNKNOWN_METADATA, + IMetadataObserver.VIDEO_METADATA, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraMetadataType { + } + + @IntDef({ + Constants.QUALITY_UNKNOWN, + Constants.QUALITY_EXCELLENT, + Constants.QUALITY_GOOD, + Constants.QUALITY_POOR, + Constants.QUALITY_BAD, + Constants.QUALITY_VBAD, + Constants.QUALITY_DOWN, + Constants.QUALITY_UNSUPPORTED, + Constants.QUALITY_DETECTING, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraNetworkQuality { + } + + @IntDef({ + Constants.NETWORK_TYPE_UNKNOWN, + Constants.NETWORK_TYPE_DISCONNECTED, + Constants.NETWORK_TYPE_LAN, + Constants.NETWORK_TYPE_WIFI, + Constants.NETWORK_TYPE_MOBILE_2G, + Constants.NETWORK_TYPE_MOBILE_3G, + Constants.NETWORK_TYPE_MOBILE_4G, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraNetworkType { + } + + @IntDef({ + Constants.RTMP_STREAM_PUBLISH_ERROR_OK, + Constants.RTMP_STREAM_PUBLISH_ERROR_INVALID_ARGUMENT, + Constants.RTMP_STREAM_PUBLISH_ERROR_ENCRYPTED_STREAM_NOT_ALLOWED, + Constants.RTMP_STREAM_PUBLISH_ERROR_CONNECTION_TIMEOUT, + Constants.RTMP_STREAM_PUBLISH_ERROR_INTERNAL_SERVER_ERROR, + Constants.RTMP_STREAM_PUBLISH_ERROR_RTMP_SERVER_ERROR, + Constants.RTMP_STREAM_PUBLISH_ERROR_TOO_OFTEN, + Constants.RTMP_STREAM_PUBLISH_ERROR_REACH_LIMIT, + Constants.RTMP_STREAM_PUBLISH_ERROR_NOT_AUTHORIZED, + Constants.RTMP_STREAM_PUBLISH_ERROR_STREAM_NOT_FOUND, + Constants.RTMP_STREAM_PUBLISH_ERROR_FORMAT_NOT_SUPPORTED, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraRtmpStreamingErrorCode { + } + + @IntDef({ + Constants.RTMP_STREAM_PUBLISH_STATE_IDLE, + Constants.RTMP_STREAM_PUBLISH_STATE_CONNECTING, + Constants.RTMP_STREAM_PUBLISH_STATE_RUNNING, + Constants.RTMP_STREAM_PUBLISH_STATE_RECOVERING, + Constants.RTMP_STREAM_PUBLISH_STATE_FAILURE, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraRtmpStreamingState { + } + + @IntDef({ + Constants.STREAM_FALLBACK_OPTION_DISABLED, + Constants.STREAM_FALLBACK_OPTION_VIDEO_STREAM_LOW, + Constants.STREAM_FALLBACK_OPTION_AUDIO_ONLY, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraStreamFallbackOptions { + } + + @IntDef({ + Constants.USER_OFFLINE_QUIT, + Constants.USER_OFFLINE_DROPPED, + Constants.USER_OFFLINE_BECOME_AUDIENCE, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraUserOfflineReason { + } + + @IntDef({ + Constants.USER_PRIORITY_HIGH, + Constants.USER_PRIORITY_NORANL, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraUserPriority { + } + + @IntDef({ + AgoraVideoCodecProfileType.BASELINE, + AgoraVideoCodecProfileType.MAIN, + AgoraVideoCodecProfileType.HIGH, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraVideoCodecProfileType { + int BASELINE = 66; + int MAIN = 77; + int HIGH = 100; + } + + @IntDef({ + AgoraVideoFrameRate.FRAME_RATE_FPS_1, + AgoraVideoFrameRate.FRAME_RATE_FPS_7, + AgoraVideoFrameRate.FRAME_RATE_FPS_10, + AgoraVideoFrameRate.FRAME_RATE_FPS_15, + AgoraVideoFrameRate.FRAME_RATE_FPS_24, + AgoraVideoFrameRate.FRAME_RATE_FPS_30, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraVideoFrameRate { + int FRAME_RATE_FPS_1 = 1; + int FRAME_RATE_FPS_7 = 7; + int FRAME_RATE_FPS_10 = 10; + int FRAME_RATE_FPS_15 = 15; + int FRAME_RATE_FPS_24 = 24; + int FRAME_RATE_FPS_30 = 30; + } + + @IntDef({ + Constants.VIDEO_MIRROR_MODE_AUTO, + Constants.VIDEO_MIRROR_MODE_ENABLED, + Constants.VIDEO_MIRROR_MODE_DISABLED, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraVideoMirrorMode { + } + + @IntDef({ + AgoraVideoOutputOrientationMode.ORIENTATION_MODE_ADAPTIVE, + AgoraVideoOutputOrientationMode.ORIENTATION_MODE_FIXED_LANDSCAPE, + AgoraVideoOutputOrientationMode.ORIENTATION_MODE_FIXED_PORTRAIT, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraVideoOutputOrientationMode { + int ORIENTATION_MODE_ADAPTIVE = 0; + int ORIENTATION_MODE_FIXED_LANDSCAPE = 1; + int ORIENTATION_MODE_FIXED_PORTRAIT = 2; + } + + @IntDef({ + Constants.ADAPT_NONE, + Constants.ADAPT_UP_BANDWIDTH, + Constants.ADAPT_DOWN_BANDWIDTH, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraVideoQualityAdaptIndication { + } + + @IntDef({ + Constants.REMOTE_VIDEO_STATE_STOPPED, + Constants.REMOTE_VIDEO_STATE_STARTING, + Constants.REMOTE_VIDEO_STATE_DECODING, + Constants.REMOTE_VIDEO_STATE_FROZEN, + Constants.REMOTE_VIDEO_STATE_FAILED, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraVideoRemoteState { + } + + @IntDef({ + Constants.REMOTE_VIDEO_STATE_REASON_INTERNAL, + Constants.REMOTE_VIDEO_STATE_REASON_NETWORK_CONGESTION, + Constants.REMOTE_VIDEO_STATE_REASON_NETWORK_RECOVERY, + Constants.REMOTE_VIDEO_STATE_REASON_LOCAL_MUTED, + Constants.REMOTE_VIDEO_STATE_REASON_LOCAL_UNMUTED, + Constants.REMOTE_VIDEO_STATE_REASON_REMOTE_MUTED, + Constants.REMOTE_VIDEO_STATE_REASON_REMOTE_UNMUTED, + Constants.REMOTE_VIDEO_STATE_REASON_REMOTE_OFFLINE, + Constants.REMOTE_VIDEO_STATE_REASON_AUDIO_FALLBACK, + Constants.REMOTE_VIDEO_STATE_REASON_AUDIO_FALLBACK_RECOVERY, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraVideoRemoteStateReason { + } + + @IntDef({ + VideoCanvas.RENDER_MODE_HIDDEN, + VideoCanvas.RENDER_MODE_FIT, + VideoCanvas.RENDER_MODE_ADAPTIVE, + VideoCanvas.RENDER_MODE_FILL, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraVideoRenderMode { + } + + @IntDef({ + Constants.VIDEO_STREAM_HIGH, + Constants.VIDEO_STREAM_LOW, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraVideoStreamType { + } + + @IntDef({ + Constants.WARN_INVALID_VIEW, + Constants.WARN_INIT_VIDEO, + Constants.WARN_PENDING, + Constants.WARN_NO_AVAILABLE_CHANNEL, + Constants.WARN_LOOKUP_CHANNEL_TIMEOUT, + Constants.WARN_LOOKUP_CHANNEL_REJECTED, + Constants.WARN_OPEN_CHANNEL_TIMEOUT, + Constants.WARN_OPEN_CHANNEL_REJECTED, + Constants.WARN_SWITCH_LIVE_VIDEO_TIMEOUT, + Constants.WARN_SET_CLIENT_ROLE_TIMEOUT, + Constants.WARN_SET_CLIENT_ROLE_NOT_AUTHORIZED, + Constants.WARN_OPEN_CHANNEL_INVALID_TICKET, + Constants.WARN_OPEN_CHANNEL_TRY_NEXT_VOS, + Constants.WARN_AUDIO_MIXING_OPEN_ERROR, + Constants.WARN_ADM_RUNTIME_PLAYOUT_WARNING, + Constants.WARN_ADM_RUNTIME_RECORDING_WARNING, + Constants.WARN_ADM_RECORD_AUDIO_SILENCE, + Constants.WARN_ADM_CALL_INTERRUPTION, + Constants.WARN_ADM_RECORD_AUDIO_LOWLEVEL, + Constants.WARN_ADM_PLAYOUT_AUDIO_LOWLEVEL, + Constants.WARN_ADM_RECORD_IS_OCCUPIED, + Constants.WARN_APM_HOWLING, + Constants.WARN_ADM_GLITCH_STATE, + Constants.WARN_ADM_IMPROPER_SETTINGS, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface AgoraWarningCode { + } +} diff --git a/android/src/main/java/io/agora/rtc/base/BeanCovertor.kt b/android/src/main/java/io/agora/rtc/base/BeanCovertor.kt new file mode 100644 index 000000000..978eff655 --- /dev/null +++ b/android/src/main/java/io/agora/rtc/base/BeanCovertor.kt @@ -0,0 +1,171 @@ +package io.agora.rtc.base + +import android.graphics.Color +import io.agora.rtc.internal.LastmileProbeConfig +import io.agora.rtc.live.LiveInjectStreamConfig +import io.agora.rtc.live.LiveTranscoding +import io.agora.rtc.live.LiveTranscoding.TranscodingUser +import io.agora.rtc.models.ChannelMediaOptions +import io.agora.rtc.video.* + +fun mapToVideoDimensions(map: Map<*, *>): VideoEncoderConfiguration.VideoDimensions { + return VideoEncoderConfiguration.VideoDimensions().apply { + (map["width"] as? Number)?.let { width = it.toInt() } + (map["height"] as? Number)?.let { height = it.toInt() } + } +} + +fun mapToVideoEncoderConfiguration(map: Map<*, *>): VideoEncoderConfiguration { + return VideoEncoderConfiguration().apply { + (map["dimensions"] as? Map<*, *>)?.let { dimensions = mapToVideoDimensions(it) } + (map["frameRate"] as? Number)?.let { frameRate = it.toInt() } + (map["minFrameRate"] as? Number)?.let { minFrameRate = it.toInt() } + (map["bitrate"] as? Number)?.let { bitrate = it.toInt() } + (map["minBitrate"] as? Number)?.let { minBitrate = it.toInt() } + (map["orientationMode"] as? Number)?.let { orientationMode = intToOrientationMode(it.toInt()) } + (map["degradationPrefer"] as? Number)?.let { degradationPrefer = intToDegradationPreference(it.toInt()) } + (map["mirrorMode"] as? Number)?.let { mirrorMode = it.toInt() } + } +} + +fun mapToBeautyOptions(map: Map<*, *>): BeautyOptions { + return BeautyOptions().apply { + (map["lighteningContrastLevel"] as? Number)?.let { lighteningContrastLevel = it.toInt() } + (map["lighteningLevel"] as? Number)?.let { lighteningLevel = it.toFloat() } + (map["smoothnessLevel"] as? Number)?.let { smoothnessLevel = it.toFloat() } + (map["rednessLevel"] as? Number)?.let { rednessLevel = it.toFloat() } + } +} + +fun mapToAgoraImage(map: Map<*, *>): AgoraImage { + return AgoraImage().apply { + (map["url"] as? String)?.let { url = it } + (map["x"] as? Number)?.let { x = it.toInt() } + (map["y"] as? Number)?.let { y = it.toInt() } + (map["width"] as? Number)?.let { width = it.toInt() } + (map["height"] as? Number)?.let { height = it.toInt() } + } +} + +fun mapToTranscodingUser(map: Map<*, *>): TranscodingUser { + return TranscodingUser().apply { + (map["uid"] as? Number)?.let { uid = it.toInt() } + (map["x"] as? Number)?.let { x = it.toInt() } + (map["y"] as? Number)?.let { y = it.toInt() } + (map["width"] as? Number)?.let { width = it.toInt() } + (map["height"] as? Number)?.let { height = it.toInt() } + (map["zOrder"] as? Number)?.let { zOrder = it.toInt() } + (map["alpha"] as? Number)?.let { alpha = it.toFloat() } + (map["audioChannel"] as? Number)?.let { audioChannel = it.toInt() } + } +} + +fun mapToColor(map: Map<*, *>): Int { + return Color.rgb( + (map["red"] as Number).toInt(), + (map["green"] as Number).toInt(), + (map["blue"] as Number).toInt() + ) +} + +fun mapToLiveTranscoding(map: Map<*, *>): LiveTranscoding { + return LiveTranscoding().apply { + (map["width"] as? Number)?.let { width = it.toInt() } + (map["height"] as? Number)?.let { height = it.toInt() } + (map["videoBitrate"] as? Number)?.let { videoBitrate = it.toInt() } + (map["videoFramerate"] as? Number)?.let { videoFramerate = it.toInt() } + (map["lowLatency"] as? Boolean)?.let { lowLatency = it } + (map["videoGop"] as? Number)?.let { videoGop = it.toInt() } + (map["watermark"] as? Map<*, *>)?.let { watermark = mapToAgoraImage(it) } + (map["backgroundImage"] as? Map<*, *>)?.let { backgroundImage = mapToAgoraImage(it) } + (map["audioSampleRate"] as? Number)?.let { audioSampleRate = intToLiveTranscodingAudioSampleRate(it.toInt()) } + (map["audioBitrate"] as? Number)?.let { audioBitrate = it.toInt() } + (map["audioChannels"] as? Number)?.let { audioChannels = it.toInt() } + (map["audioCodecProfile"] as? Number)?.let { audioCodecProfile = intToAudioCodecProfile(it.toInt()) } + (map["videoCodecProfile"] as? Number)?.let { videoCodecProfile = intToVideoCodecProfile(it.toInt()) } + (map["backgroundColor"] as? Map<*, *>)?.let { backgroundColor = mapToColor(it) } + (map["userConfigExtraInfo"] as? String)?.let { userConfigExtraInfo = it } + (map["transcodingUsers"] as? List<*>)?.let { list -> + list.forEach { item -> + (item as? Map<*, *>)?.let { + addUser(mapToTranscodingUser(it)) + } + } + } + } +} + +fun mapToChannelMediaInfo(map: Map<*, *>): ChannelMediaInfo { + return ChannelMediaInfo( + map["channelName"] as? String, + map["token"] as? String, + (map["uid"] as Number).toInt() + ) +} + +fun mapToChannelMediaRelayConfiguration(map: Map<*, *>): ChannelMediaRelayConfiguration { + return ChannelMediaRelayConfiguration().apply { + (map["srcInfo"] as? Map<*, *>)?.let { setSrcChannelInfo(mapToChannelMediaInfo(it)) } + (map["destInfos"] as? List<*>)?.let { list -> + list.forEach { item -> + (item as? Map<*, *>)?.let { + val info = mapToChannelMediaInfo(it) + setDestChannelInfo(info.channelName, info) + } + } + } + } +} + +fun mapToLastmileProbeConfig(map: Map<*, *>): LastmileProbeConfig { + return LastmileProbeConfig().apply { + (map["probeUplink"] as? Boolean)?.let { probeUplink = it } + (map["probeDownlink"] as? Boolean)?.let { probeDownlink = it } + (map["expectedUplinkBitrate"] as? Number)?.let { expectedUplinkBitrate = it.toInt() } + (map["expectedDownlinkBitrate"] as? Number)?.let { expectedUplinkBitrate = it.toInt() } + } +} + +fun mapToRectangle(map: Map<*, *>): WatermarkOptions.Rectangle { + return WatermarkOptions.Rectangle().apply { + (map["x"] as? Number)?.let { x = it.toInt() } + (map["y"] as? Number)?.let { y = it.toInt() } + (map["width"] as? Number)?.let { width = it.toInt() } + (map["height"] as? Number)?.let { height = it.toInt() } + } +} + +fun mapToWatermarkOptions(map: Map<*, *>): WatermarkOptions { + return WatermarkOptions().apply { + (map["visibleInPreview"] as? Boolean)?.let { visibleInPreview = it } + (map["positionInLandscapeMode"] as? Map<*, *>)?.let { positionInLandscapeMode = mapToRectangle(it) } + (map["positionInPortraitMode"] as? Map<*, *>)?.let { positionInPortraitMode = mapToRectangle(it) } + } +} + +fun mapToLiveInjectStreamConfig(map: Map<*, *>): LiveInjectStreamConfig { + return LiveInjectStreamConfig().apply { + (map["width"] as? Number)?.let { width = it.toInt() } + (map["height"] as? Number)?.let { height = it.toInt() } + (map["videoGop"] as? Number)?.let { videoGop = it.toInt() } + (map["videoFramerate"] as? Number)?.let { videoFramerate = it.toInt() } + (map["videoBitrate"] as? Number)?.let { videoBitrate = it.toInt() } + (map["audioSampleRate"] as? Number)?.let { audioSampleRate = intToLiveInjectStreamConfigAudioSampleRate(it.toInt()) } + (map["audioBitrate"] as? Number)?.let { audioBitrate = it.toInt() } + (map["audioChannels"] as? Number)?.let { audioChannels = it.toInt() } + } +} + +fun mapToCameraCapturerConfiguration(map: Map<*, *>): CameraCapturerConfiguration { + return CameraCapturerConfiguration( + intToCapturerOutputPreference((map["preference"] as Number).toInt()), + intToCameraDirection((map["cameraDirection"] as Number).toInt()) + ) +} + +fun mapToChannelMediaOptions(map: Map<*, *>): ChannelMediaOptions { + return ChannelMediaOptions().apply { + (map["autoSubscribeAudio"] as? Boolean)?.let { autoSubscribeAudio = it } + (map["autoSubscribeVideo"] as? Boolean)?.let { autoSubscribeVideo = it } + } +} diff --git a/android/src/main/java/io/agora/rtc/base/Callback.kt b/android/src/main/java/io/agora/rtc/base/Callback.kt new file mode 100644 index 000000000..3394d8303 --- /dev/null +++ b/android/src/main/java/io/agora/rtc/base/Callback.kt @@ -0,0 +1,41 @@ +package io.agora.rtc.base + +import io.agora.rtc.Constants +import io.agora.rtc.RtcEngine +import kotlin.math.abs + +abstract class Callback { + fun code(code: Int?, runnable: ((Int) -> Any?)? = null) { + if (code == null || code < 0) { + val newCode = abs(code ?: Constants.ERR_NOT_INITIALIZED) + failure(newCode.toString(), RtcEngine.getErrorDescription(newCode)) + return + } + + val res = if (runnable != null) runnable(code) else Unit + if (res is Unit) { + success(null) + } else { + success(res) + } + } + + fun resolve(source: T?, runnable: (T) -> Any?) { + if (source == null) { + val code = Constants.ERR_NOT_INITIALIZED + failure(code.toString(), RtcEngine.getErrorDescription(code)) + return + } + + val res = runnable(source) + if (res is Unit) { + success(null) + } else { + success(res) + } + } + + abstract fun success(data: Any?) + + abstract fun failure(code: String, message: String) +} diff --git a/android/src/main/java/io/agora/rtc/base/EnumCovertor.kt b/android/src/main/java/io/agora/rtc/base/EnumCovertor.kt new file mode 100644 index 000000000..b44665390 --- /dev/null +++ b/android/src/main/java/io/agora/rtc/base/EnumCovertor.kt @@ -0,0 +1,87 @@ +package io.agora.rtc.base + +import io.agora.rtc.live.LiveInjectStreamConfig +import io.agora.rtc.live.LiveTranscoding +import io.agora.rtc.video.CameraCapturerConfiguration +import io.agora.rtc.video.VideoEncoderConfiguration + +fun intToFrameRate(@Annotations.AgoraVideoFrameRate intValue: Int): VideoEncoderConfiguration.FRAME_RATE { + for (value in VideoEncoderConfiguration.FRAME_RATE.values()) { + if (value.value == intValue) { + return value + } + } + throw RuntimeException("VideoEncoderConfiguration.FRAME_RATE not contains $intValue") +} + +fun intToOrientationMode(@Annotations.AgoraVideoOutputOrientationMode intValue: Int): VideoEncoderConfiguration.ORIENTATION_MODE { + for (value in VideoEncoderConfiguration.ORIENTATION_MODE.values()) { + if (value.value == intValue) { + return value + } + } + throw RuntimeException("VideoEncoderConfiguration.ORIENTATION_MODE not contains $intValue") +} + +fun intToDegradationPreference(@Annotations.AgoraDegradationPreference intValue: Int): VideoEncoderConfiguration.DEGRADATION_PREFERENCE { + for (value in VideoEncoderConfiguration.DEGRADATION_PREFERENCE.values()) { + if (value.value == intValue) { + return value + } + } + throw RuntimeException("VideoEncoderConfiguration.DEGRADATION_PREFERENCE not contains $intValue") +} + +fun intToLiveTranscodingAudioSampleRate(@Annotations.AgoraAudioSampleRateType intValue: Int): LiveTranscoding.AudioSampleRateType { + for (value in LiveTranscoding.AudioSampleRateType.values()) { + if (LiveTranscoding.AudioSampleRateType.getValue(value) == intValue) { + return value + } + } + throw RuntimeException("LiveTranscoding.AudioSampleRateType not contains $intValue") +} + +fun intToLiveInjectStreamConfigAudioSampleRate(@Annotations.AgoraAudioSampleRateType intValue: Int): LiveInjectStreamConfig.AudioSampleRateType { + for (value in LiveInjectStreamConfig.AudioSampleRateType.values()) { + if (LiveInjectStreamConfig.AudioSampleRateType.getValue(value) == intValue) { + return value + } + } + throw RuntimeException("LiveInjectStreamConfig.AudioSampleRateType not contains $intValue") +} + +fun intToAudioCodecProfile(@Annotations.AgoraAudioCodecProfileType intValue: Int): LiveTranscoding.AudioCodecProfileType { + for (value in LiveTranscoding.AudioCodecProfileType.values()) { + if (LiveTranscoding.AudioCodecProfileType.getValue(value) == intValue) { + return value + } + } + throw RuntimeException("LiveTranscoding.AudioCodecProfileType not contains $intValue") +} + +fun intToVideoCodecProfile(@Annotations.AgoraVideoCodecProfileType intValue: Int): LiveTranscoding.VideoCodecProfileType { + for (value in LiveTranscoding.VideoCodecProfileType.values()) { + if (LiveTranscoding.VideoCodecProfileType.getValue(value) == intValue) { + return value + } + } + throw RuntimeException("LiveTranscoding.VideoCodecProfileType not contains $intValue") +} + +fun intToCapturerOutputPreference(@Annotations.AgoraCameraCaptureOutputPreference intValue: Int): CameraCapturerConfiguration.CAPTURER_OUTPUT_PREFERENCE { + for (value in CameraCapturerConfiguration.CAPTURER_OUTPUT_PREFERENCE.values()) { + if (value.value == intValue) { + return value + } + } + throw RuntimeException("CameraCapturerConfiguration.CAPTURER_OUTPUT_PREFERENCE not contains $intValue") +} + +fun intToCameraDirection(@Annotations.AgoraCameraDirection intValue: Int): CameraCapturerConfiguration.CAMERA_DIRECTION { + for (value in CameraCapturerConfiguration.CAMERA_DIRECTION.values()) { + if (value.value == intValue) { + return value + } + } + throw RuntimeException("CameraCapturerConfiguration.CAMERA_DIRECTION not contains $intValue") +} diff --git a/android/src/main/java/io/agora/rtc/base/Extensions.kt b/android/src/main/java/io/agora/rtc/base/Extensions.kt new file mode 100644 index 000000000..472f5ca71 --- /dev/null +++ b/android/src/main/java/io/agora/rtc/base/Extensions.kt @@ -0,0 +1,151 @@ +package io.agora.rtc.base + +import android.graphics.Rect +import io.agora.rtc.IRtcEngineEventHandler.* +import io.agora.rtc.models.UserInfo + +fun UserInfo.toMap(): Map { + return hashMapOf( + "uid" to uid, + "userAccount" to userAccount + ) +} + +fun LocalAudioStats.toMap(): Map { + return hashMapOf( + "numChannels" to numChannels, + "sentSampleRate" to sentSampleRate, + "sentBitrate" to sentBitrate + ) +} + +fun RtcStats.toMap(): Map { + return hashMapOf( + "totalDuration" to totalDuration, + "txBytes" to txBytes, + "rxBytes" to rxBytes, + "txAudioBytes" to txAudioBytes, + "txVideoBytes" to txVideoBytes, + "rxAudioBytes" to rxAudioBytes, + "rxVideoBytes" to rxVideoBytes, + "txKBitRate" to txKBitRate, + "rxKBitRate" to rxKBitRate, + "txAudioKBitRate" to txAudioKBitRate, + "rxAudioKBitRate" to rxAudioKBitRate, + "txVideoKBitRate" to txVideoKBitRate, + "rxVideoKBitRate" to rxVideoKBitRate, + "users" to users, + "lastmileDelay" to lastmileDelay, + "txPacketLossRate" to txPacketLossRate, + "rxPacketLossRate" to rxPacketLossRate, + "cpuTotalUsage" to cpuTotalUsage, + "cpuAppUsage" to cpuAppUsage, + "gatewayRtt" to gatewayRtt, + "memoryAppUsageRatio" to memoryAppUsageRatio, + "memoryTotalUsageRatio" to memoryTotalUsageRatio, + "memoryAppUsageInKbytes" to memoryAppUsageInKbytes + ) +} + +fun Rect.toMap(): Map { + return hashMapOf( + "left" to left, + "top" to top, + "right" to right, + "bottom" to bottom + ) +} + +fun RemoteAudioStats.toMap(): Map { + return hashMapOf( + "uid" to uid, + "quality" to quality, + "networkTransportDelay" to networkTransportDelay, + "jitterBufferDelay" to jitterBufferDelay, + "audioLossRate" to audioLossRate, + "numChannels" to numChannels, + "receivedSampleRate" to receivedSampleRate, + "receivedBitrate" to receivedBitrate, + "totalFrozenTime" to totalFrozenTime, + "frozenRate" to frozenRate, + "totalActiveTime" to totalActiveTime + ) +} + +fun LocalVideoStats.toMap(): Map { + return hashMapOf( + "sentBitrate" to sentBitrate, + "sentFrameRate" to sentFrameRate, + "encoderOutputFrameRate" to encoderOutputFrameRate, + "rendererOutputFrameRate" to rendererOutputFrameRate, + "targetBitrate" to targetBitrate, + "targetFrameRate" to targetFrameRate, + "qualityAdaptIndication" to qualityAdaptIndication, + "encodedBitrate" to encodedBitrate, + "encodedFrameWidth" to encodedFrameWidth, + "encodedFrameHeight" to encodedFrameHeight, + "encodedFrameCount" to encodedFrameCount, + "codecType" to codecType + ) +} + +fun RemoteVideoStats.toMap(): Map { + return hashMapOf( + "uid" to uid, + "delay" to delay, + "width" to width, + "height" to height, + "receivedBitrate" to receivedBitrate, + "decoderOutputFrameRate" to decoderOutputFrameRate, + "rendererOutputFrameRate" to rendererOutputFrameRate, + "packetLossRate" to packetLossRate, + "rxStreamType" to rxStreamType, + "totalFrozenTime" to totalFrozenTime, + "frozenRate" to frozenRate, + "totalActiveTime" to totalActiveTime + ) +} + +fun AudioVolumeInfo.toMap(): Map { + return hashMapOf( + "uid" to uid, + "volume" to volume, + "vad" to vad, + "channelId" to channelId + ) +} + +fun Array.toMapList(): List> { + return List(size) { this[it].toMap() } +} + +fun LastmileProbeResult.LastmileProbeOneWayResult.toMap(): Map { + return hashMapOf( + "packetLossRate" to packetLossRate, + "jitter" to jitter, + "availableBandwidth" to availableBandwidth + ) +} + +fun LastmileProbeResult.toMap(): Map { + return hashMapOf( + "state" to state, + "rtt" to rtt, + "uplinkReport" to uplinkReport.toMap(), + "downlinkReport" to downlinkReport.toMap() + ) +} + +fun AgoraFacePositionInfo.toMap(): Map { + return hashMapOf( + "x" to x, + "y" to y, + "width" to width, + "height" to height, + "distance" to distance + ) +} + +fun Array.toMapList(): List> { + return List(size) { this[it].toMap() } +} diff --git a/android/src/main/java/io/agora/rtc/base/MediaObserver.kt b/android/src/main/java/io/agora/rtc/base/MediaObserver.kt new file mode 100644 index 000000000..729d7e57f --- /dev/null +++ b/android/src/main/java/io/agora/rtc/base/MediaObserver.kt @@ -0,0 +1,40 @@ +package io.agora.rtc.base + +import androidx.annotation.IntRange +import io.agora.rtc.IMetadataObserver +import java.util.* +import java.util.concurrent.atomic.AtomicInteger + +class MediaObserver( + private val emit: (data: Map?) -> Unit +) : IMetadataObserver { + private var maxMetadataSize = AtomicInteger(0) + private var metadataList = Collections.synchronizedList(mutableListOf()) + + fun addMetadata(metadata: String) { + metadataList.add(metadata) + } + + fun setMaxMetadataSize(@IntRange(from = 0, to = 1024) size: Int) { + maxMetadataSize.set(size) + } + + override fun onReadyToSendMetadata(timeStampMs: Long): ByteArray? { + if (metadataList.size > 0) { + return metadataList.removeAt(0).toByteArray() + } + return null + } + + override fun getMaxMetadataSize(): Int { + return maxMetadataSize.get() + } + + override fun onMetadataReceived(buffer: ByteArray, uid: Int, timeStampMs: Long) { + emit(hashMapOf( + "buffer" to String(buffer), + "uid" to uid, + "timeStampMs" to timeStampMs + )) + } +} diff --git a/android/src/main/java/io/agora/rtc/base/RtcChannel.kt b/android/src/main/java/io/agora/rtc/base/RtcChannel.kt new file mode 100644 index 000000000..be3a45cb1 --- /dev/null +++ b/android/src/main/java/io/agora/rtc/base/RtcChannel.kt @@ -0,0 +1,202 @@ +package io.agora.rtc.base + +import androidx.annotation.FloatRange +import androidx.annotation.IntRange +import io.agora.rtc.Constants +import io.agora.rtc.IMetadataObserver +import io.agora.rtc.RtcChannel +import io.agora.rtc.RtcEngine +import java.util.* + +interface RtcChannelInterface : + RtcChannelManager.RtcAudioInterface, + RtcChannelManager.RtcVideoInterface, + RtcChannelManager.RtcVoicePositionInterface, + RtcChannelManager.RtcPublishStreamInterface, + RtcChannelManager.RtcMediaRelayInterface, + RtcChannelManager.RtcDualStreamInterface, + RtcChannelManager.RtcFallbackInterface, + RtcChannelManager.RtcMediaMetadataInterface, + RtcChannelManager.RtcEncryptionInterface, + RtcChannelManager.RtcInjectStreamInterface, + RtcChannelManager.RtcStreamMessageInterface { + fun create(channelId: String, callback: Callback?) + + fun destroy(channelId: String, callback: Callback?) + + fun setClientRole(channelId: String, @Annotations.AgoraClientRole role: Int, callback: Callback?) + + fun joinChannel(channelId: String, token: String?, optionalInfo: String?, optionalUid: Int, options: Map, callback: Callback?) + + fun joinChannelWithUserAccount(channelId: String, token: String?, userAccount: String, options: Map, callback: Callback?) + + fun leaveChannel(channelId: String, callback: Callback?) + + fun renewToken(channelId: String, token: String, callback: Callback?) + + fun getConnectionState(channelId: String, callback: Callback?) + + fun publish(channelId: String, callback: Callback?) + + fun unpublish(channelId: String, callback: Callback?) + + fun getCallId(channelId: String, callback: Callback?) +} + +class RtcChannelManager { + private val rtcChannelMap = Collections.synchronizedMap(mutableMapOf()) + private val mediaObserverMap = Collections.synchronizedMap(mutableMapOf()) + + fun create(engine: RtcEngine, channelId: String, emit: (methodName: String, data: Map?) -> Unit) { + engine.createRtcChannel(channelId)?.let { + it.setRtcChannelEventHandler(RtcChannelEventHandler { methodName, data -> emit(methodName, data) }) + rtcChannelMap[channelId] = it + } + } + + fun destroy(channelId: String): Int { + this[channelId]?.let { + val res = it.destroy() + if (res == 0) rtcChannelMap.remove(channelId) + return@destroy res + } + return Constants.ERR_NOT_INITIALIZED + } + + fun release() { + rtcChannelMap.forEach { it.value.destroy() } + rtcChannelMap.clear() + mediaObserverMap.clear() + } + + operator fun get(channelId: String): RtcChannel? { + return rtcChannelMap[channelId] + } + + fun registerMediaMetadataObserver(channelId: String, emit: (methodName: String, data: Map?) -> Unit): Int { + this[channelId]?.let { + val mediaObserver = MediaObserver { data -> + emit(RtcChannelEvents.MetadataReceived, data?.toMutableMap()?.apply { put("channelId", channelId) }) + } + val res = it.registerMediaMetadataObserver(mediaObserver, IMetadataObserver.VIDEO_METADATA) + if (res == 0) mediaObserverMap[channelId] = mediaObserver + return@registerMediaMetadataObserver res + } + return Constants.ERR_NOT_INITIALIZED + } + + fun unregisterMediaMetadataObserver(channelId: String): Int { + this[channelId]?.let { + val res = it.registerMediaMetadataObserver(null, IMetadataObserver.VIDEO_METADATA) + if (res == 0) mediaObserverMap.remove(channelId) + return@unregisterMediaMetadataObserver res + } + return Constants.ERR_NOT_INITIALIZED + } + + fun setMaxMetadataSize(channelId: String, @IntRange(from = 0, to = 1024) size: Int): Int { + mediaObserverMap[channelId]?.let { + it.maxMetadataSize = size + return@setMaxMetadataSize 0 + } + return Constants.ERR_NOT_INITIALIZED + } + + fun addMetadata(channelId: String, metadata: String): Int { + mediaObserverMap[channelId]?.let { + it.addMetadata(metadata) + return@addMetadata 0 + } + return Constants.ERR_NOT_INITIALIZED + } + + fun createDataStream(channelId: String, reliable: Boolean, ordered: Boolean): Int { + this[channelId]?.let { + return@createDataStream it.createDataStream(reliable, ordered) + } + return Constants.ERR_NOT_INITIALIZED + } + + fun sendStreamMessage(channelId: String, streamId: Int, message: String): Int { + this[channelId]?.let { + return@sendStreamMessage it.sendStreamMessage(streamId, message.toByteArray()) + } + return Constants.ERR_NOT_INITIALIZED + } + + interface RtcAudioInterface { + fun adjustUserPlaybackSignalVolume(channelId: String, uid: Int, @IntRange(from = 0, to = 100) volume: Int, callback: Callback?) + + fun muteRemoteAudioStream(channelId: String, uid: Int, muted: Boolean, callback: Callback?) + + fun muteAllRemoteAudioStreams(channelId: String, muted: Boolean, callback: Callback?) + + fun setDefaultMuteAllRemoteAudioStreams(channelId: String, muted: Boolean, callback: Callback?) + } + + interface RtcVideoInterface { + fun muteRemoteVideoStream(channelId: String, uid: Int, muted: Boolean, callback: Callback?) + + fun muteAllRemoteVideoStreams(channelId: String, muted: Boolean, callback: Callback?) + + fun setDefaultMuteAllRemoteVideoStreams(channelId: String, muted: Boolean, callback: Callback?) + } + + interface RtcVoicePositionInterface { + fun setRemoteVoicePosition(channelId: String, uid: Int, @FloatRange(from = -1.0, to = 1.0) pan: Double, @FloatRange(from = 0.0, to = 100.0) gain: Double, callback: Callback?) + } + + interface RtcPublishStreamInterface { + fun setLiveTranscoding(channelId: String, transcoding: Map, callback: Callback?) + + fun addPublishStreamUrl(channelId: String, url: String, transcodingEnabled: Boolean, callback: Callback?) + + fun removePublishStreamUrl(channelId: String, url: String, callback: Callback?) + } + + interface RtcMediaRelayInterface { + fun startChannelMediaRelay(channelId: String, channelMediaRelayConfiguration: Map, callback: Callback?) + + fun updateChannelMediaRelay(channelId: String, channelMediaRelayConfiguration: Map, callback: Callback?) + + fun stopChannelMediaRelay(channelId: String, callback: Callback?) + } + + interface RtcDualStreamInterface { + fun setRemoteVideoStreamType(channelId: String, uid: Int, @Annotations.AgoraVideoStreamType streamType: Int, callback: Callback?) + + fun setRemoteDefaultVideoStreamType(channelId: String, @Annotations.AgoraVideoStreamType streamType: Int, callback: Callback?) + } + + interface RtcFallbackInterface { + fun setRemoteUserPriority(channelId: String, uid: Int, @Annotations.AgoraUserPriority userPriority: Int, callback: Callback?) + } + + interface RtcMediaMetadataInterface { + fun registerMediaMetadataObserver(channelId: String, callback: Callback?) + + fun unregisterMediaMetadataObserver(channelId: String, callback: Callback?) + + fun setMaxMetadataSize(channelId: String, @IntRange(from = 0, to = 1024) size: Int, callback: Callback?) + + fun sendMetadata(channelId: String, metadata: String, callback: Callback?) + } + + interface RtcEncryptionInterface { + fun setEncryptionSecret(channelId: String, secret: String, callback: Callback?) + + fun setEncryptionMode(channelId: String, @Annotations.AgoraEncryptionMode encryptionMode: String, callback: Callback?) + } + + interface RtcInjectStreamInterface { + fun addInjectStreamUrl(channelId: String, url: String, config: Map, callback: Callback?) + + fun removeInjectStreamUrl(channelId: String, url: String, callback: Callback?) + } + + interface RtcStreamMessageInterface { + fun createDataStream(channelId: String, reliable: Boolean, ordered: Boolean, callback: Callback?) + + fun sendStreamMessage(channelId: String, streamId: Int, message: String, callback: Callback?) + } +} diff --git a/android/src/main/java/io/agora/rtc/base/RtcChannelEvent.kt b/android/src/main/java/io/agora/rtc/base/RtcChannelEvent.kt new file mode 100644 index 000000000..2b471ac45 --- /dev/null +++ b/android/src/main/java/io/agora/rtc/base/RtcChannelEvent.kt @@ -0,0 +1,209 @@ +package io.agora.rtc.base + +import androidx.annotation.IntRange +import io.agora.rtc.IRtcChannelEventHandler +import io.agora.rtc.IRtcEngineEventHandler +import io.agora.rtc.RtcChannel + +class RtcChannelEvents { + companion object { + const val Warning = "Warning" + const val Error = "Error" + const val JoinChannelSuccess = "JoinChannelSuccess" + const val RejoinChannelSuccess = "RejoinChannelSuccess" + const val LeaveChannel = "LeaveChannel" + const val ClientRoleChanged = "ClientRoleChanged" + const val UserJoined = "UserJoined" + const val UserOffline = "UserOffline" + const val ConnectionStateChanged = "ConnectionStateChanged" + const val ConnectionLost = "ConnectionLost" + const val TokenPrivilegeWillExpire = "TokenPrivilegeWillExpire" + const val RequestToken = "RequestToken" + const val ActiveSpeaker = "ActiveSpeaker" + const val VideoSizeChanged = "VideoSizeChanged" + const val RemoteVideoStateChanged = "RemoteVideoStateChanged" + const val RemoteAudioStateChanged = "RemoteAudioStateChanged" + const val LocalPublishFallbackToAudioOnly = "LocalPublishFallbackToAudioOnly" + const val RemoteSubscribeFallbackToAudioOnly = "RemoteSubscribeFallbackToAudioOnly" + const val RtcStats = "RtcStats" + const val NetworkQuality = "NetworkQuality" + const val RemoteVideoStats = "RemoteVideoStats" + const val RemoteAudioStats = "RemoteAudioStats" + const val RtmpStreamingStateChanged = "RtmpStreamingStateChanged" + const val TranscodingUpdated = "TranscodingUpdated" + const val StreamInjectedStatus = "StreamInjectedStatus" + const val StreamMessage = "StreamMessage" + const val StreamMessageError = "StreamMessageError" + const val ChannelMediaRelayStateChanged = "ChannelMediaRelayStateChanged" + const val ChannelMediaRelayEvent = "ChannelMediaRelayEvent" + const val MetadataReceived = "MetadataReceived" + + fun toMap(): Map { + return hashMapOf( + "Warning" to Warning, + "Error" to Error, + "JoinChannelSuccess" to JoinChannelSuccess, + "RejoinChannelSuccess" to RejoinChannelSuccess, + "LeaveChannel" to LeaveChannel, + "ClientRoleChanged" to ClientRoleChanged, + "UserJoined" to UserJoined, + "UserOffline" to UserOffline, + "ConnectionStateChanged" to ConnectionStateChanged, + "ConnectionLost" to ConnectionLost, + "TokenPrivilegeWillExpire" to TokenPrivilegeWillExpire, + "RequestToken" to RequestToken, + "ActiveSpeaker" to ActiveSpeaker, + "VideoSizeChanged" to VideoSizeChanged, + "RemoteVideoStateChanged" to RemoteVideoStateChanged, + "RemoteAudioStateChanged" to RemoteAudioStateChanged, + "LocalPublishFallbackToAudioOnly" to LocalPublishFallbackToAudioOnly, + "RemoteSubscribeFallbackToAudioOnly" to RemoteSubscribeFallbackToAudioOnly, + "RtcStats" to RtcStats, + "NetworkQuality" to NetworkQuality, + "RemoteVideoStats" to RemoteVideoStats, + "RemoteAudioStats" to RemoteAudioStats, + "RtmpStreamingStateChanged" to RtmpStreamingStateChanged, + "TranscodingUpdated" to TranscodingUpdated, + "StreamInjectedStatus" to StreamInjectedStatus, + "StreamMessage" to StreamMessage, + "StreamMessageError" to StreamMessageError, + "ChannelMediaRelayStateChanged" to ChannelMediaRelayStateChanged, + "ChannelMediaRelayEvent" to ChannelMediaRelayEvent, + "MetadataReceived" to MetadataReceived + ) + } + } +} + +class RtcChannelEventHandler( + private val emitter: (methodName: String, data: Map?) -> Unit +) : IRtcChannelEventHandler() { + companion object { + const val PREFIX = "io.agora.rtc." + } + + private fun callback(methodName: String, channel: RtcChannel?, vararg data: Any?) { + channel?.let { + emitter(methodName, hashMapOf( + "channelId" to it.channelId(), + "data" to data.toList() + )) + } + } + + override fun onChannelWarning(rtcChannel: RtcChannel?, @Annotations.AgoraWarningCode warn: Int) { + callback(RtcChannelEvents.Warning, rtcChannel, warn) + } + + override fun onChannelError(rtcChannel: RtcChannel?, @Annotations.AgoraErrorCode err: Int) { + callback(RtcChannelEvents.Error, rtcChannel, err) + } + + override fun onJoinChannelSuccess(rtcChannel: RtcChannel?, uid: Int, elapsed: Int) { + callback(RtcChannelEvents.JoinChannelSuccess, rtcChannel, uid, elapsed) + } + + override fun onRejoinChannelSuccess(rtcChannel: RtcChannel?, uid: Int, elapsed: Int) { + callback(RtcChannelEvents.RejoinChannelSuccess, rtcChannel, uid, elapsed) + } + + override fun onLeaveChannel(rtcChannel: RtcChannel?, stats: IRtcEngineEventHandler.RtcStats?) { + callback(RtcChannelEvents.LeaveChannel, rtcChannel, stats?.toMap()) + } + + override fun onClientRoleChanged(rtcChannel: RtcChannel?, @Annotations.AgoraClientRole oldRole: Int, @Annotations.AgoraClientRole newRole: Int) { + callback(RtcChannelEvents.ClientRoleChanged, rtcChannel, oldRole, newRole) + } + + override fun onUserJoined(rtcChannel: RtcChannel?, uid: Int, elapsed: Int) { + callback(RtcChannelEvents.UserJoined, rtcChannel, uid, elapsed) + } + + override fun onUserOffline(rtcChannel: RtcChannel?, uid: Int, @Annotations.AgoraUserOfflineReason reason: Int) { + callback(RtcChannelEvents.UserOffline, rtcChannel, uid, reason) + } + + override fun onConnectionStateChanged(rtcChannel: RtcChannel?, @Annotations.AgoraConnectionStateType state: Int, @Annotations.AgoraConnectionChangedReason reason: Int) { + callback(RtcChannelEvents.ConnectionStateChanged, rtcChannel, state, reason) + } + + override fun onConnectionLost(rtcChannel: RtcChannel?) { + callback(RtcChannelEvents.ConnectionLost, rtcChannel) + } + + override fun onTokenPrivilegeWillExpire(rtcChannel: RtcChannel?, token: String?) { + callback(RtcChannelEvents.TokenPrivilegeWillExpire, rtcChannel, token) + } + + override fun onRequestToken(rtcChannel: RtcChannel?) { + callback(RtcChannelEvents.RequestToken, rtcChannel) + } + + override fun onActiveSpeaker(rtcChannel: RtcChannel?, uid: Int) { + callback(RtcChannelEvents.ActiveSpeaker, rtcChannel, uid) + } + + override fun onVideoSizeChanged(rtcChannel: RtcChannel?, uid: Int, width: Int, height: Int, @IntRange(from = 0, to = 360) rotation: Int) { + callback(RtcChannelEvents.VideoSizeChanged, rtcChannel, uid, width, height, rotation) + } + + override fun onRemoteVideoStateChanged(rtcChannel: RtcChannel?, uid: Int, @Annotations.AgoraVideoRemoteState state: Int, @Annotations.AgoraVideoRemoteStateReason reason: Int, elapsed: Int) { + callback(RtcChannelEvents.RemoteVideoStateChanged, rtcChannel, uid, state, reason, elapsed) + } + + override fun onRemoteAudioStateChanged(rtcChannel: RtcChannel?, uid: Int, @Annotations.AgoraAudioRemoteState state: Int, @Annotations.AgoraAudioRemoteStateReason reason: Int, elapsed: Int) { + callback(RtcChannelEvents.RemoteAudioStateChanged, rtcChannel, uid, state, reason, elapsed) + } + + override fun onLocalPublishFallbackToAudioOnly(rtcChannel: RtcChannel?, isFallbackOrRecover: Boolean) { + callback(RtcChannelEvents.LocalPublishFallbackToAudioOnly, rtcChannel, isFallbackOrRecover) + } + + override fun onRemoteSubscribeFallbackToAudioOnly(rtcChannel: RtcChannel?, uid: Int, isFallbackOrRecover: Boolean) { + callback(RtcChannelEvents.RemoteSubscribeFallbackToAudioOnly, rtcChannel, uid, isFallbackOrRecover) + } + + override fun onRtcStats(rtcChannel: RtcChannel?, stats: IRtcEngineEventHandler.RtcStats?) { + callback(RtcChannelEvents.RtcStats, rtcChannel, stats?.toMap()) + } + + override fun onNetworkQuality(rtcChannel: RtcChannel?, uid: Int, @Annotations.AgoraNetworkQuality txQuality: Int, @Annotations.AgoraNetworkQuality rxQuality: Int) { + callback(RtcChannelEvents.NetworkQuality, rtcChannel, uid, txQuality, rxQuality) + } + + override fun onRemoteVideoStats(rtcChannel: RtcChannel?, stats: IRtcEngineEventHandler.RemoteVideoStats?) { + callback(RtcChannelEvents.RemoteVideoStats, rtcChannel, stats?.toMap()) + } + + override fun onRemoteAudioStats(rtcChannel: RtcChannel?, stats: IRtcEngineEventHandler.RemoteAudioStats?) { + callback(RtcChannelEvents.RemoteAudioStats, rtcChannel, stats?.toMap()) + } + + override fun onRtmpStreamingStateChanged(rtcChannel: RtcChannel?, url: String?, @Annotations.AgoraRtmpStreamingState state: Int, @Annotations.AgoraRtmpStreamingErrorCode errCode: Int) { + callback(RtcChannelEvents.RtmpStreamingStateChanged, rtcChannel, url, state, errCode) + } + + override fun onTranscodingUpdated(rtcChannel: RtcChannel?) { + callback(RtcChannelEvents.TranscodingUpdated, rtcChannel) + } + + override fun onStreamInjectedStatus(rtcChannel: RtcChannel?, url: String?, uid: Int, @Annotations.AgoraInjectStreamStatus status: Int) { + callback(RtcChannelEvents.StreamInjectedStatus, rtcChannel, url, uid, status) + } + + override fun onStreamMessage(rtcChannel: RtcChannel?, uid: Int, streamId: Int, data: ByteArray?) { + callback(RtcChannelEvents.StreamMessage, rtcChannel, uid, streamId, data?.let { String(it, Charsets.UTF_8) }) + } + + override fun onStreamMessageError(rtcChannel: RtcChannel?, uid: Int, streamId: Int, @Annotations.AgoraErrorCode error: Int, missed: Int, cached: Int) { + callback(RtcChannelEvents.StreamMessageError, rtcChannel, uid, streamId, error, missed, cached) + } + + override fun onChannelMediaRelayStateChanged(rtcChannel: RtcChannel?, @Annotations.AgoraChannelMediaRelayState state: Int, @Annotations.AgoraChannelMediaRelayError code: Int) { + callback(RtcChannelEvents.ChannelMediaRelayStateChanged, rtcChannel, state, code) + } + + override fun onChannelMediaRelayEvent(rtcChannel: RtcChannel?, @Annotations.AgoraChannelMediaRelayEvent code: Int) { + callback(RtcChannelEvents.ChannelMediaRelayEvent, rtcChannel, code) + } +} diff --git a/android/src/main/java/io/agora/rtc/base/RtcEngine.kt b/android/src/main/java/io/agora/rtc/base/RtcEngine.kt new file mode 100644 index 000000000..e24f74724 --- /dev/null +++ b/android/src/main/java/io/agora/rtc/base/RtcEngine.kt @@ -0,0 +1,423 @@ +package io.agora.rtc.base + +import android.content.Context +import androidx.annotation.FloatRange +import androidx.annotation.IntRange +import io.agora.rtc.* +import io.agora.rtc.models.UserInfo + +interface RtcEngineInterface : + RtcEngineManager.RtcUserInfoInterface, + RtcEngineManager.RtcAudioInterface, + RtcEngineManager.RtcVideoInterface, + RtcEngineManager.RtcAudioMixingInterface, + RtcEngineManager.RtcAudioEffectInterface, + RtcEngineManager.RtcVoiceChangerInterface, + RtcEngineManager.RtcVoicePositionInterface, + RtcEngineManager.RtcPublishStreamInterface, + RtcEngineManager.RtcMediaRelayInterface, + RtcEngineManager.RtcAudioRouteInterface, + RtcEngineManager.RtcEarMonitoringInterface, + RtcEngineManager.RtcDualStreamInterface, + RtcEngineManager.RtcFallbackInterface, + RtcEngineManager.RtcTestInterface, + RtcEngineManager.RtcMediaMetadataInterface, + RtcEngineManager.RtcWatermarkInterface, + RtcEngineManager.RtcEncryptionInterface, + RtcEngineManager.RtcAudioRecorderInterface, + RtcEngineManager.RtcInjectStreamInterface, + RtcEngineManager.RtcCameraInterface, + RtcEngineManager.RtcStreamMessageInterface { + fun create(appId: String, areaCode: Int, callback: Callback?) + + fun destroy(callback: Callback?) + + fun setChannelProfile(@Annotations.AgoraChannelProfile profile: Int, callback: Callback?) + + fun setClientRole(@Annotations.AgoraClientRole role: Int, callback: Callback?) + + fun joinChannel(token: String?, channelName: String, optionalInfo: String?, optionalUid: Int, callback: Callback?) + + fun switchChannel(token: String?, channelName: String, callback: Callback?) + + fun leaveChannel(callback: Callback?) + + fun renewToken(token: String, callback: Callback?) + + @Deprecated("") + fun enableWebSdkInteroperability(enabled: Boolean, callback: Callback?) + + fun getConnectionState(callback: Callback?) + + fun getCallId(callback: Callback?) + + fun rate(callId: String, @IntRange(from = 1, to = 5) rating: Int, description: String?, callback: Callback?) + + fun complain(callId: String, description: String, callback: Callback?) + + fun setLogFile(filePath: String, callback: Callback?) + + fun setLogFilter(@Annotations.AgoraLogFilter filter: Int, callback: Callback?) + + fun setLogFileSize(fileSizeInKBytes: Int, callback: Callback?) + + fun setParameters(parameters: String, callback: Callback?) +} + +class RtcEngineManager { + private var engine: RtcEngine? = null + private var mediaObserver: MediaObserver? = null + + fun create(context: Context, appId: String, areaCode: Int, @Annotations.AgoraRtcAppType appType: Int, emit: (methodName: String, data: Map?) -> Unit) { + engine = RtcEngineEx.create(RtcEngineConfig().apply { + mContext = context + mAppId = appId + mAreaCode = areaCode + mEventHandler = RtcEngineEventHandler { methodName, data -> + emit(methodName, data) + } + }) + (engine as? RtcEngineEx)?.setAppType(appType) + } + + fun destroy() { + RtcEngine.destroy() + engine = null + } + + fun release() { + destroy() + mediaObserver = null + } + + fun engine(): RtcEngine? { + return engine + } + + fun getUserInfoByUserAccount(userAccount: String): Map? { + engine?.let { + val userInfo = UserInfo() + it.getUserInfoByUserAccount(userAccount, userInfo) + return@getUserInfoByUserAccount userInfo.toMap() + } + return null + } + + fun getUserInfoByUid(uid: Int): Map? { + engine?.let { + val userInfo = UserInfo() + it.getUserInfoByUid(uid, userInfo) + return@getUserInfoByUid userInfo.toMap() + } + return null + } + + fun registerMediaMetadataObserver(emit: (methodName: String, data: Map?) -> Unit): Int { + engine?.let { + val mediaObserver = MediaObserver { data -> + emit(RtcEngineEvents.MetadataReceived, data) + } + val res = it.registerMediaMetadataObserver(mediaObserver, IMetadataObserver.VIDEO_METADATA) + if (res == 0) this.mediaObserver = mediaObserver + return@registerMediaMetadataObserver res + } + return Constants.ERR_NOT_INITIALIZED + } + + fun unregisterMediaMetadataObserver(): Int { + engine?.let { + val res = it.registerMediaMetadataObserver(null, IMetadataObserver.VIDEO_METADATA) + if (res == 0) mediaObserver = null + return@unregisterMediaMetadataObserver res + } + return Constants.ERR_NOT_INITIALIZED + } + + fun setMaxMetadataSize(@IntRange(from = 0, to = 1024) size: Int): Int { + mediaObserver?.let { + it.maxMetadataSize = size + return@setMaxMetadataSize 0 + } + return Constants.ERR_NOT_INITIALIZED + } + + fun addMetadata(metadata: String): Int { + mediaObserver?.let { + it.addMetadata(metadata) + return@addMetadata 0 + } + return Constants.ERR_NOT_INITIALIZED + } + + fun createDataStream(reliable: Boolean, ordered: Boolean): Int { + engine?.let { + return@createDataStream it.createDataStream(reliable, ordered) + } + return Constants.ERR_NOT_INITIALIZED + } + + fun sendStreamMessage(streamId: Int, message: String): Int { + engine?.let { + return@sendStreamMessage it.sendStreamMessage(streamId, message.toByteArray()) + } + return Constants.ERR_NOT_INITIALIZED + } + + interface RtcUserInfoInterface { + fun registerLocalUserAccount(appId: String, userAccount: String, callback: Callback?) + + fun joinChannelWithUserAccount(token: String?, channelName: String, userAccount: String, callback: Callback?) + + fun getUserInfoByUserAccount(userAccount: String, callback: Callback?) + + fun getUserInfoByUid(uid: Int, callback: Callback?) + } + + interface RtcAudioInterface { + fun enableAudio(callback: Callback?) + + fun disableAudio(callback: Callback?) + + fun setAudioProfile(@Annotations.AgoraAudioProfile profile: Int, @Annotations.AgoraAudioScenario scenario: Int, callback: Callback?) + + fun adjustRecordingSignalVolume(@IntRange(from = 0, to = 400) volume: Int, callback: Callback?) + + fun adjustUserPlaybackSignalVolume(uid: Int, @IntRange(from = 0, to = 100) volume: Int, callback: Callback?) + + fun adjustPlaybackSignalVolume(@IntRange(from = 0, to = 400) volume: Int, callback: Callback?) + + fun enableLocalAudio(enabled: Boolean, callback: Callback?) + + fun muteLocalAudioStream(muted: Boolean, callback: Callback?) + + fun muteRemoteAudioStream(uid: Int, muted: Boolean, callback: Callback?) + + fun muteAllRemoteAudioStreams(muted: Boolean, callback: Callback?) + + fun setDefaultMuteAllRemoteAudioStreams(muted: Boolean, callback: Callback?) + + fun enableAudioVolumeIndication(interval: Int, @IntRange(from = 0, to = 10) smooth: Int, report_vad: Boolean, callback: Callback?) + } + + interface RtcVideoInterface { + fun enableVideo(callback: Callback?) + + fun disableVideo(callback: Callback?) + + fun setVideoEncoderConfiguration(config: Map, callback: Callback?) + + fun enableLocalVideo(enabled: Boolean, callback: Callback?) + + fun muteLocalVideoStream(muted: Boolean, callback: Callback?) + + fun muteRemoteVideoStream(uid: Int, muted: Boolean, callback: Callback?) + + fun muteAllRemoteVideoStreams(muted: Boolean, callback: Callback?) + + fun setDefaultMuteAllRemoteVideoStreams(muted: Boolean, callback: Callback?) + + fun setBeautyEffectOptions(enabled: Boolean, options: Map, callback: Callback?) + } + + interface RtcAudioMixingInterface { + fun startAudioMixing(filePath: String, loopback: Boolean, replace: Boolean, cycle: Int, callback: Callback?) + + fun stopAudioMixing(callback: Callback?) + + fun pauseAudioMixing(callback: Callback?) + + fun resumeAudioMixing(callback: Callback?) + + fun adjustAudioMixingVolume(@IntRange(from = 0, to = 100) volume: Int, callback: Callback?) + + fun adjustAudioMixingPlayoutVolume(@IntRange(from = 0, to = 400) volume: Int, callback: Callback?) + + fun adjustAudioMixingPublishVolume(@IntRange(from = 0, to = 100) volume: Int, callback: Callback?) + + fun getAudioMixingPlayoutVolume(callback: Callback?) + + fun getAudioMixingPublishVolume(callback: Callback?) + + fun getAudioMixingDuration(callback: Callback?) + + fun getAudioMixingCurrentPosition(callback: Callback?) + + fun setAudioMixingPosition(pos: Int, callback: Callback?) + + fun setAudioMixingPitch(@IntRange(from = -12, to = 12) pitch: Int, callback: Callback?) + } + + interface RtcAudioEffectInterface { + fun getEffectsVolume(callback: Callback?) + + fun setEffectsVolume(@FloatRange(from = 0.0, to = 100.0) volume: Double, callback: Callback?) + + fun setVolumeOfEffect(soundId: Int, @FloatRange(from = 0.0, to = 100.0) volume: Double, callback: Callback?) + + fun playEffect(soundId: Int, filePath: String, loopCount: Int, @FloatRange(from = 0.5, to = 2.0) pitch: Double, @FloatRange(from = -1.0, to = 1.0) pan: Double, @FloatRange(from = 0.0, to = 100.0) gain: Double, publish: Boolean, callback: Callback?) + + fun stopEffect(soundId: Int, callback: Callback?) + + fun stopAllEffects(callback: Callback?) + + fun preloadEffect(soundId: Int, filePath: String, callback: Callback?) + + fun unloadEffect(soundId: Int, callback: Callback?) + + fun pauseEffect(soundId: Int, callback: Callback?) + + fun pauseAllEffects(callback: Callback?) + + fun resumeEffect(soundId: Int, callback: Callback?) + + fun resumeAllEffects(callback: Callback?) + } + + interface RtcVoiceChangerInterface { + fun setLocalVoiceChanger(@Annotations.AgoraAudioVoiceChanger voiceChanger: Int, callback: Callback?) + + fun setLocalVoiceReverbPreset(@Annotations.AgoraAudioReverbPreset preset: Int, callback: Callback?) + + fun setLocalVoicePitch(@FloatRange(from = 0.5, to = 2.0) pitch: Double, callback: Callback?) + + fun setLocalVoiceEqualization(@IntRange(from = 0, to = 9) bandFrequency: Int, @IntRange(from = -15, to = 15) bandGain: Int, callback: Callback?) + + fun setLocalVoiceReverb(@Annotations.AgoraAudioReverbType reverbKey: Int, value: Int, callback: Callback?) + } + + interface RtcVoicePositionInterface { + fun enableSoundPositionIndication(enabled: Boolean, callback: Callback?) + + fun setRemoteVoicePosition(uid: Int, @FloatRange(from = -1.0, to = 1.0) pan: Double, @FloatRange(from = 0.0, to = 100.0) gain: Double, callback: Callback?) + } + + interface RtcPublishStreamInterface { + fun setLiveTranscoding(transcoding: Map, callback: Callback?) + + fun addPublishStreamUrl(url: String, transcodingEnabled: Boolean, callback: Callback?) + + fun removePublishStreamUrl(url: String, callback: Callback?) + } + + interface RtcMediaRelayInterface { + fun startChannelMediaRelay(channelMediaRelayConfiguration: Map, callback: Callback?) + + fun updateChannelMediaRelay(channelMediaRelayConfiguration: Map, callback: Callback?) + + fun stopChannelMediaRelay(callback: Callback?) + } + + interface RtcAudioRouteInterface { + fun setDefaultAudioRoutetoSpeakerphone(defaultToSpeaker: Boolean, callback: Callback?) + + fun setEnableSpeakerphone(enabled: Boolean, callback: Callback?) + + fun isSpeakerphoneEnabled(callback: Callback?) + } + + interface RtcEarMonitoringInterface { + fun enableInEarMonitoring(enabled: Boolean, callback: Callback?) + + fun setInEarMonitoringVolume(@IntRange(from = 0, to = 100) volume: Int, callback: Callback?) + } + + interface RtcDualStreamInterface { + fun enableDualStreamMode(enabled: Boolean, callback: Callback?) + + fun setRemoteVideoStreamType(uid: Int, @Annotations.AgoraVideoStreamType streamType: Int, callback: Callback?) + + fun setRemoteDefaultVideoStreamType(@Annotations.AgoraVideoStreamType streamType: Int, callback: Callback?) + } + + interface RtcFallbackInterface { + fun setLocalPublishFallbackOption(@Annotations.AgoraStreamFallbackOptions option: Int, callback: Callback?) + + fun setRemoteSubscribeFallbackOption(@Annotations.AgoraStreamFallbackOptions option: Int, callback: Callback?) + + fun setRemoteUserPriority(uid: Int, @Annotations.AgoraUserPriority userPriority: Int, callback: Callback?) + } + + interface RtcTestInterface { + fun startEchoTest(@IntRange(from = 2, to = 10) intervalInSeconds: Int, callback: Callback?) + + fun stopEchoTest(callback: Callback?) + + fun enableLastmileTest(callback: Callback?) + + fun disableLastmileTest(callback: Callback?) + + fun startLastmileProbeTest(config: Map, callback: Callback?) + + fun stopLastmileProbeTest(callback: Callback?) + } + + interface RtcMediaMetadataInterface { + fun registerMediaMetadataObserver(callback: Callback?) + + fun unregisterMediaMetadataObserver(callback: Callback?) + + fun setMaxMetadataSize(@IntRange(from = 0, to = 1024) size: Int, callback: Callback?) + + fun sendMetadata(metadata: String, callback: Callback?) + } + + interface RtcWatermarkInterface { + fun addVideoWatermark(watermarkUrl: String, options: Map, callback: Callback?) + + fun clearVideoWatermarks(callback: Callback?) + } + + interface RtcEncryptionInterface { + fun setEncryptionSecret(secret: String, callback: Callback?) + + fun setEncryptionMode(@Annotations.AgoraEncryptionMode encryptionMode: String, callback: Callback?) + } + + interface RtcAudioRecorderInterface { + fun startAudioRecording(filePath: String, sampleRate: Int, @Annotations.AgoraAudioRecordingQuality quality: Int, callback: Callback?) + + fun stopAudioRecording(callback: Callback?) + } + + interface RtcInjectStreamInterface { + fun addInjectStreamUrl(url: String, config: Map, callback: Callback?) + + fun removeInjectStreamUrl(url: String, callback: Callback?) + } + + interface RtcCameraInterface { + fun switchCamera(callback: Callback?) + + fun isCameraZoomSupported(callback: Callback?) + + fun isCameraTorchSupported(callback: Callback?) + + fun isCameraFocusSupported(callback: Callback?) + + fun isCameraExposurePositionSupported(callback: Callback?) + + fun isCameraAutoFocusFaceModeSupported(callback: Callback?) + + fun setCameraZoomFactor(@FloatRange(from = 1.0) factor: Float, callback: Callback?) + + fun getCameraMaxZoomFactor(callback: Callback?) + + fun setCameraFocusPositionInPreview(positionX: Float, positionY: Float, callback: Callback?) + + fun setCameraExposurePosition(positionXinView: Float, positionYinView: Float, callback: Callback?) + + fun enableFaceDetection(enable: Boolean, callback: Callback?) + + fun setCameraTorchOn(isOn: Boolean, callback: Callback?) + + fun setCameraAutoFocusFaceModeEnabled(enabled: Boolean, callback: Callback?) + + fun setCameraCapturerConfiguration(config: Map, callback: Callback?) + } + + interface RtcStreamMessageInterface { + fun createDataStream(reliable: Boolean, ordered: Boolean, callback: Callback?) + + fun sendStreamMessage(streamId: Int, message: String, callback: Callback?) + } +} diff --git a/android/src/main/java/io/agora/rtc/base/RtcEngineEvent.kt b/android/src/main/java/io/agora/rtc/base/RtcEngineEvent.kt new file mode 100644 index 000000000..00aaaf42e --- /dev/null +++ b/android/src/main/java/io/agora/rtc/base/RtcEngineEvent.kt @@ -0,0 +1,473 @@ +package io.agora.rtc.base + +import android.graphics.Rect +import androidx.annotation.IntRange +import io.agora.rtc.IRtcEngineEventHandler +import io.agora.rtc.models.UserInfo + +class RtcEngineEvents { + companion object { + const val Warning = "Warning" + const val Error = "Error" + const val ApiCallExecuted = "ApiCallExecuted" + const val JoinChannelSuccess = "JoinChannelSuccess" + const val RejoinChannelSuccess = "RejoinChannelSuccess" + const val LeaveChannel = "LeaveChannel" + const val LocalUserRegistered = "LocalUserRegistered" + const val UserInfoUpdated = "UserInfoUpdated" + const val ClientRoleChanged = "ClientRoleChanged" + const val UserJoined = "UserJoined" + const val UserOffline = "UserOffline" + const val ConnectionStateChanged = "ConnectionStateChanged" + const val NetworkTypeChanged = "NetworkTypeChanged" + const val ConnectionLost = "ConnectionLost" + const val TokenPrivilegeWillExpire = "TokenPrivilegeWillExpire" + const val RequestToken = "RequestToken" + const val AudioVolumeIndication = "AudioVolumeIndication" + const val ActiveSpeaker = "ActiveSpeaker" + const val FirstLocalAudioFrame = "FirstLocalAudioFrame" + const val FirstLocalVideoFrame = "FirstLocalVideoFrame" + const val UserMuteVideo = "UserMuteVideo" + const val VideoSizeChanged = "VideoSizeChanged" + const val RemoteVideoStateChanged = "RemoteVideoStateChanged" + const val LocalVideoStateChanged = "LocalVideoStateChanged" + const val RemoteAudioStateChanged = "RemoteAudioStateChanged" + const val LocalAudioStateChanged = "LocalAudioStateChanged" + const val LocalPublishFallbackToAudioOnly = "LocalPublishFallbackToAudioOnly" + const val RemoteSubscribeFallbackToAudioOnly = "RemoteSubscribeFallbackToAudioOnly" + const val AudioRouteChanged = "AudioRouteChanged" + const val CameraFocusAreaChanged = "CameraFocusAreaChanged" + const val CameraExposureAreaChanged = "CameraExposureAreaChanged" + const val FacePositionChanged = "FacePositionChanged" + const val RtcStats = "RtcStats" + const val LastmileQuality = "LastmileQuality" + const val NetworkQuality = "NetworkQuality" + const val LastmileProbeResult = "LastmileProbeResult" + const val LocalVideoStats = "LocalVideoStats" + const val LocalAudioStats = "LocalAudioStats" + const val RemoteVideoStats = "RemoteVideoStats" + const val RemoteAudioStats = "RemoteAudioStats" + const val AudioMixingFinished = "AudioMixingFinished" + const val AudioMixingStateChanged = "AudioMixingStateChanged" + const val AudioEffectFinished = "AudioEffectFinished" + const val RtmpStreamingStateChanged = "RtmpStreamingStateChanged" + const val TranscodingUpdated = "TranscodingUpdated" + const val StreamInjectedStatus = "StreamInjectedStatus" + const val StreamMessage = "StreamMessage" + const val StreamMessageError = "StreamMessageError" + const val MediaEngineLoadSuccess = "MediaEngineLoadSuccess" + const val MediaEngineStartCallSuccess = "MediaEngineStartCallSuccess" + const val ChannelMediaRelayStateChanged = "ChannelMediaRelayStateChanged" + const val ChannelMediaRelayEvent = "ChannelMediaRelayEvent" + const val FirstRemoteVideoFrame = "FirstRemoteVideoFrame" + const val FirstRemoteAudioFrame = "FirstRemoteAudioFrame" + const val FirstRemoteAudioDecoded = "FirstRemoteAudioDecoded" + const val UserMuteAudio = "UserMuteAudio" + const val StreamPublished = "StreamPublished" + const val StreamUnpublished = "StreamUnpublished" + const val RemoteAudioTransportStats = "RemoteAudioTransportStats" + const val RemoteVideoTransportStats = "RemoteVideoTransportStats" + const val UserEnableVideo = "UserEnableVideo" + const val UserEnableLocalVideo = "UserEnableLocalVideo" + const val FirstRemoteVideoDecoded = "FirstRemoteVideoDecoded" + const val MicrophoneEnabled = "MicrophoneEnabled" + const val ConnectionInterrupted = "ConnectionInterrupted" + const val ConnectionBanned = "ConnectionBanned" + const val AudioQuality = "AudioQuality" + const val CameraReady = "CameraReady" + const val VideoStopped = "VideoStopped" + const val MetadataReceived = "MetadataReceived" + + fun toMap(): Map { + return hashMapOf( + "Warning" to Warning, + "Error" to Error, + "ApiCallExecuted" to ApiCallExecuted, + "JoinChannelSuccess" to JoinChannelSuccess, + "RejoinChannelSuccess" to RejoinChannelSuccess, + "LeaveChannel" to LeaveChannel, + "LocalUserRegistered" to LocalUserRegistered, + "UserInfoUpdated" to UserInfoUpdated, + "ClientRoleChanged" to ClientRoleChanged, + "UserJoined" to UserJoined, + "UserOffline" to UserOffline, + "ConnectionStateChanged" to ConnectionStateChanged, + "NetworkTypeChanged" to NetworkTypeChanged, + "ConnectionLost" to ConnectionLost, + "TokenPrivilegeWillExpire" to TokenPrivilegeWillExpire, + "RequestToken" to RequestToken, + "AudioVolumeIndication" to AudioVolumeIndication, + "ActiveSpeaker" to ActiveSpeaker, + "FirstLocalAudioFrame" to FirstLocalAudioFrame, + "FirstLocalVideoFrame" to FirstLocalVideoFrame, + "UserMuteVideo" to UserMuteVideo, + "VideoSizeChanged" to VideoSizeChanged, + "RemoteVideoStateChanged" to RemoteVideoStateChanged, + "LocalVideoStateChanged" to LocalVideoStateChanged, + "RemoteAudioStateChanged" to RemoteAudioStateChanged, + "LocalAudioStateChanged" to LocalAudioStateChanged, + "LocalPublishFallbackToAudioOnly" to LocalPublishFallbackToAudioOnly, + "RemoteSubscribeFallbackToAudioOnly" to RemoteSubscribeFallbackToAudioOnly, + "AudioRouteChanged" to AudioRouteChanged, + "CameraFocusAreaChanged" to CameraFocusAreaChanged, + "CameraExposureAreaChanged" to CameraExposureAreaChanged, + "FacePositionChanged" to FacePositionChanged, + "RtcStats" to RtcStats, + "LastmileQuality" to LastmileQuality, + "NetworkQuality" to NetworkQuality, + "LastmileProbeResult" to LastmileProbeResult, + "LocalVideoStats" to LocalVideoStats, + "LocalAudioStats" to LocalAudioStats, + "RemoteVideoStats" to RemoteVideoStats, + "RemoteAudioStats" to RemoteAudioStats, + "AudioMixingFinished" to AudioMixingFinished, + "AudioMixingStateChanged" to AudioMixingStateChanged, + "AudioEffectFinished" to AudioEffectFinished, + "RtmpStreamingStateChanged" to RtmpStreamingStateChanged, + "TranscodingUpdated" to TranscodingUpdated, + "StreamInjectedStatus" to StreamInjectedStatus, + "StreamMessage" to StreamMessage, + "StreamMessageError" to StreamMessageError, + "MediaEngineLoadSuccess" to MediaEngineLoadSuccess, + "MediaEngineStartCallSuccess" to MediaEngineStartCallSuccess, + "ChannelMediaRelayStateChanged" to ChannelMediaRelayStateChanged, + "ChannelMediaRelayEvent" to ChannelMediaRelayEvent, + "FirstRemoteVideoFrame" to FirstRemoteVideoFrame, + "FirstRemoteAudioFrame" to FirstRemoteAudioFrame, + "FirstRemoteAudioDecoded" to FirstRemoteAudioDecoded, + "UserMuteAudio" to UserMuteAudio, + "StreamPublished" to StreamPublished, + "StreamUnpublished" to StreamUnpublished, + "RemoteAudioTransportStats" to RemoteAudioTransportStats, + "RemoteVideoTransportStats" to RemoteVideoTransportStats, + "UserEnableVideo" to UserEnableVideo, + "UserEnableLocalVideo" to UserEnableLocalVideo, + "FirstRemoteVideoDecoded" to FirstRemoteVideoDecoded, + "MicrophoneEnabled" to MicrophoneEnabled, + "ConnectionInterrupted" to ConnectionInterrupted, + "ConnectionBanned" to ConnectionBanned, + "AudioQuality" to AudioQuality, + "CameraReady" to CameraReady, + "VideoStopped" to VideoStopped, + "MetadataReceived" to MetadataReceived + ) + } + } +} + +class RtcEngineEventHandler( + private val emitter: (methodName: String, data: Map?) -> Unit +) : IRtcEngineEventHandler() { + companion object { + const val PREFIX = "io.agora.rtc." + } + + private fun callback(methodName: String, vararg data: Any?) { + emitter(methodName, hashMapOf("data" to data.toList())) + } + + override fun onWarning(@Annotations.AgoraWarningCode warn: Int) { + callback(RtcEngineEvents.Warning, warn) + } + + override fun onError(@Annotations.AgoraErrorCode err: Int) { + callback(RtcEngineEvents.Error, err) + } + + override fun onApiCallExecuted(@Annotations.AgoraErrorCode error: Int, api: String?, result: String?) { + callback(RtcEngineEvents.ApiCallExecuted, error, api, result) + } + + override fun onJoinChannelSuccess(channel: String?, uid: Int, elapsed: Int) { + callback(RtcEngineEvents.JoinChannelSuccess, channel, uid, elapsed) + } + + override fun onRejoinChannelSuccess(channel: String?, uid: Int, elapsed: Int) { + callback(RtcEngineEvents.RejoinChannelSuccess, uid, elapsed) + } + + override fun onLeaveChannel(stats: RtcStats?) { + callback(RtcEngineEvents.LeaveChannel, stats?.toMap()) + } + + override fun onLocalUserRegistered(uid: Int, userAccount: String?) { + callback(RtcEngineEvents.LocalUserRegistered, uid, userAccount) + } + + override fun onUserInfoUpdated(uid: Int, userInfo: UserInfo?) { + callback(RtcEngineEvents.UserInfoUpdated, uid, userInfo?.toMap()) + } + + override fun onClientRoleChanged(@Annotations.AgoraClientRole oldRole: Int, @Annotations.AgoraClientRole newRole: Int) { + callback(RtcEngineEvents.ClientRoleChanged, oldRole, newRole) + } + + override fun onUserJoined(uid: Int, elapsed: Int) { + callback(RtcEngineEvents.UserJoined, uid, elapsed) + } + + override fun onUserOffline(uid: Int, @Annotations.AgoraUserOfflineReason reason: Int) { + callback(RtcEngineEvents.UserOffline, uid, reason) + } + + override fun onConnectionStateChanged(@Annotations.AgoraConnectionStateType state: Int, @Annotations.AgoraConnectionChangedReason reason: Int) { + callback(RtcEngineEvents.ConnectionStateChanged, state, reason) + } + + override fun onNetworkTypeChanged(@Annotations.AgoraNetworkType type: Int) { + callback(RtcEngineEvents.NetworkTypeChanged, type) + } + + override fun onConnectionLost() { + callback(RtcEngineEvents.ConnectionLost) + } + + override fun onTokenPrivilegeWillExpire(token: String?) { + callback(RtcEngineEvents.TokenPrivilegeWillExpire, token) + } + + override fun onRequestToken() { + callback(RtcEngineEvents.RequestToken) + } + + override fun onAudioVolumeIndication(speakers: Array?, @IntRange(from = 0, to = 255) totalVolume: Int) { + callback(RtcEngineEvents.AudioVolumeIndication, speakers?.toMapList(), totalVolume) + } + + override fun onActiveSpeaker(uid: Int) { + callback(RtcEngineEvents.ActiveSpeaker, uid) + } + + override fun onFirstLocalAudioFrame(elapsed: Int) { + callback(RtcEngineEvents.FirstLocalAudioFrame, elapsed) + } + + override fun onFirstLocalVideoFrame(width: Int, height: Int, elapsed: Int) { + callback(RtcEngineEvents.FirstLocalVideoFrame, width, height, elapsed) + } + + @Deprecated("", ReplaceWith("onRemoteVideoStateChanged")) + override fun onUserMuteVideo(uid: Int, muted: Boolean) { + callback(RtcEngineEvents.UserMuteVideo, uid, muted) + } + + override fun onVideoSizeChanged(uid: Int, width: Int, height: Int, @IntRange(from = 0, to = 360) rotation: Int) { + callback(RtcEngineEvents.VideoSizeChanged, uid, width, height, rotation) + } + + override fun onRemoteVideoStateChanged(uid: Int, @Annotations.AgoraVideoRemoteState state: Int, @Annotations.AgoraVideoRemoteStateReason reason: Int, elapsed: Int) { + callback(RtcEngineEvents.RemoteVideoStateChanged, uid, state, reason, elapsed) + } + + override fun onLocalVideoStateChanged(@Annotations.AgoraLocalVideoStreamState localVideoState: Int, @Annotations.AgoraLocalVideoStreamError error: Int) { + callback(RtcEngineEvents.LocalVideoStateChanged, localVideoState, error) + } + + override fun onRemoteAudioStateChanged(uid: Int, @Annotations.AgoraAudioRemoteState state: Int, @Annotations.AgoraAudioRemoteStateReason reason: Int, elapsed: Int) { + callback(RtcEngineEvents.RemoteAudioStateChanged, uid, state, reason, elapsed) + } + + override fun onLocalAudioStateChanged(@Annotations.AgoraAudioLocalState state: Int, @Annotations.AgoraAudioLocalError error: Int) { + callback(RtcEngineEvents.LocalAudioStateChanged, state, error) + } + + override fun onLocalPublishFallbackToAudioOnly(isFallbackOrRecover: Boolean) { + callback(RtcEngineEvents.LocalPublishFallbackToAudioOnly, isFallbackOrRecover) + } + + override fun onRemoteSubscribeFallbackToAudioOnly(uid: Int, isFallbackOrRecover: Boolean) { + callback(RtcEngineEvents.RemoteSubscribeFallbackToAudioOnly, uid, isFallbackOrRecover) + } + + override fun onAudioRouteChanged(@Annotations.AgoraAudioOutputRouting routing: Int) { + callback(RtcEngineEvents.AudioRouteChanged, routing) + } + + override fun onCameraFocusAreaChanged(rect: Rect?) { + callback(RtcEngineEvents.CameraFocusAreaChanged, rect?.toMap()) + } + + override fun onCameraExposureAreaChanged(rect: Rect?) { + callback(RtcEngineEvents.CameraExposureAreaChanged, rect?.toMap()) + } + + override fun onFacePositionChanged(imageWidth: Int, imageHeight: Int, faces: Array?) { + callback(RtcEngineEvents.FacePositionChanged, imageWidth, imageHeight, faces?.toMapList()) + } + + override fun onRtcStats(stats: RtcStats?) { + callback(RtcEngineEvents.RtcStats, stats?.toMap()) + } + + override fun onLastmileQuality(@Annotations.AgoraNetworkQuality quality: Int) { + callback(RtcEngineEvents.LastmileQuality, quality) + } + + override fun onNetworkQuality(uid: Int, @Annotations.AgoraNetworkQuality txQuality: Int, @Annotations.AgoraNetworkQuality rxQuality: Int) { + callback(RtcEngineEvents.NetworkQuality, uid, txQuality, rxQuality) + } + + override fun onLastmileProbeResult(result: LastmileProbeResult?) { + callback(RtcEngineEvents.LastmileProbeResult, result?.toMap()) + } + + @Deprecated("", ReplaceWith("onLocalVideoStats")) + override fun onLocalVideoStat(sentBitrate: Int, sentFrameRate: Int) { + // TODO Not in iOS + } + + override fun onLocalVideoStats(stats: LocalVideoStats?) { + callback(RtcEngineEvents.LocalVideoStats, stats?.toMap()) + } + + override fun onLocalAudioStats(stats: LocalAudioStats?) { + callback(RtcEngineEvents.LocalAudioStats, stats?.toMap()) + } + + @Deprecated("", ReplaceWith("onRemoteVideoStats")) + override fun onRemoteVideoStat(uid: Int, delay: Int, receivedBitrate: Int, receivedFrameRate: Int) { + // TODO Not in iOS + } + + override fun onRemoteVideoStats(stats: RemoteVideoStats?) { + callback(RtcEngineEvents.RemoteVideoStats, stats?.toMap()) + } + + override fun onRemoteAudioStats(stats: RemoteAudioStats?) { + callback(RtcEngineEvents.RemoteAudioStats, stats?.toMap()) + } + + @Deprecated("", ReplaceWith("onAudioMixingStateChanged")) + override fun onAudioMixingFinished() { + callback(RtcEngineEvents.AudioMixingFinished) + } + + override fun onAudioMixingStateChanged(@Annotations.AgoraAudioMixingStateCode state: Int, @Annotations.AgoraAudioMixingErrorCode errorCode: Int) { + callback(RtcEngineEvents.AudioMixingStateChanged, state, errorCode) + } + + override fun onAudioEffectFinished(soundId: Int) { + callback(RtcEngineEvents.AudioEffectFinished, soundId) + } + + override fun onRtmpStreamingStateChanged(url: String?, @Annotations.AgoraRtmpStreamingState state: Int, @Annotations.AgoraRtmpStreamingErrorCode errCode: Int) { + callback(RtcEngineEvents.RtmpStreamingStateChanged, url, state, errCode) + } + + override fun onTranscodingUpdated() { + callback(RtcEngineEvents.TranscodingUpdated) + } + + override fun onStreamInjectedStatus(url: String?, uid: Int, @Annotations.AgoraInjectStreamStatus status: Int) { + callback(RtcEngineEvents.StreamInjectedStatus, url, uid, status) + } + + override fun onStreamMessage(uid: Int, streamId: Int, data: ByteArray?) { + callback(RtcEngineEvents.StreamMessage, uid, streamId, data?.let { String(it, Charsets.UTF_8) }) + } + + override fun onStreamMessageError(uid: Int, streamId: Int, @Annotations.AgoraErrorCode error: Int, missed: Int, cached: Int) { + callback(RtcEngineEvents.StreamMessageError, uid, streamId, error, missed, cached) + } + + override fun onMediaEngineLoadSuccess() { + callback(RtcEngineEvents.MediaEngineLoadSuccess) + } + + override fun onMediaEngineStartCallSuccess() { + callback(RtcEngineEvents.MediaEngineStartCallSuccess) + } + + override fun onChannelMediaRelayStateChanged(@Annotations.AgoraChannelMediaRelayState state: Int, @Annotations.AgoraChannelMediaRelayError code: Int) { + callback(RtcEngineEvents.ChannelMediaRelayStateChanged, state, code) + } + + override fun onChannelMediaRelayEvent(@Annotations.AgoraChannelMediaRelayEvent code: Int) { + callback(RtcEngineEvents.ChannelMediaRelayEvent, code) + } + + @Deprecated("", ReplaceWith("onRemoteVideoStateChanged")) + override fun onFirstRemoteVideoFrame(uid: Int, width: Int, height: Int, elapsed: Int) { + callback(RtcEngineEvents.FirstRemoteVideoFrame, uid, width, height, elapsed) + } + + @Deprecated("", ReplaceWith("onRemoteAudioStateChanged")) + override fun onFirstRemoteAudioFrame(uid: Int, elapsed: Int) { + callback(RtcEngineEvents.FirstRemoteAudioFrame, uid, elapsed) + } + + @Deprecated("", ReplaceWith("onRemoteAudioStateChanged")) + override fun onFirstRemoteAudioDecoded(uid: Int, elapsed: Int) { + callback(RtcEngineEvents.FirstRemoteAudioDecoded, uid, elapsed) + } + + @Deprecated("", ReplaceWith("onRemoteAudioStateChanged")) + override fun onUserMuteAudio(uid: Int, muted: Boolean) { + callback(RtcEngineEvents.UserMuteAudio, uid, muted) + } + + @Deprecated("", ReplaceWith("onRtmpStreamingStateChanged")) + override fun onStreamPublished(url: String?, @Annotations.AgoraErrorCode error: Int) { + callback(RtcEngineEvents.StreamPublished, url, error) + } + + @Deprecated("", ReplaceWith("onRtmpStreamingStateChanged")) + override fun onStreamUnpublished(url: String?) { + callback(RtcEngineEvents.StreamUnpublished, url) + } + + @Deprecated("", ReplaceWith("onRemoteAudioStats")) + override fun onRemoteAudioTransportStats(uid: Int, delay: Int, lost: Int, rxKBitRate: Int) { + callback(RtcEngineEvents.RemoteAudioTransportStats, uid, delay, lost, rxKBitRate) + } + + @Deprecated("", ReplaceWith("onRemoteVideoStats")) + override fun onRemoteVideoTransportStats(uid: Int, delay: Int, lost: Int, rxKBitRate: Int) { + callback(RtcEngineEvents.RemoteVideoTransportStats, uid, delay, lost, rxKBitRate) + } + + @Deprecated("", ReplaceWith("onRemoteVideoStateChanged")) + override fun onUserEnableVideo(uid: Int, enabled: Boolean) { + callback(RtcEngineEvents.UserEnableVideo, uid, enabled) + } + + @Deprecated("", ReplaceWith("onRemoteVideoStateChanged")) + override fun onUserEnableLocalVideo(uid: Int, enabled: Boolean) { + callback(RtcEngineEvents.UserEnableLocalVideo, uid, enabled) + } + + @Deprecated("", ReplaceWith("onRemoteVideoStateChanged")) + override fun onFirstRemoteVideoDecoded(uid: Int, width: Int, height: Int, elapsed: Int) { + callback(RtcEngineEvents.FirstRemoteVideoDecoded, uid, width, height, elapsed) + } + + @Deprecated("", ReplaceWith("onLocalAudioStateChanged")) + override fun onMicrophoneEnabled(enabled: Boolean) { + callback(RtcEngineEvents.MicrophoneEnabled, enabled) + } + + @Deprecated("", ReplaceWith("onConnectionStateChanged")) + override fun onConnectionInterrupted() { + callback(RtcEngineEvents.ConnectionInterrupted) + } + + @Deprecated("", ReplaceWith("onConnectionStateChanged")) + override fun onConnectionBanned() { + callback(RtcEngineEvents.ConnectionBanned) + } + + @Deprecated("", ReplaceWith("onRemoteAudioStats")) + override fun onAudioQuality(uid: Int, @Annotations.AgoraNetworkQuality quality: Int, delay: Short, lost: Short) { + callback(RtcEngineEvents.AudioQuality, uid, quality, delay, lost) + } + + @Deprecated("", ReplaceWith("onLocalVideoStateChanged")) + override fun onCameraReady() { + callback(RtcEngineEvents.CameraReady) + } + + @Deprecated("", ReplaceWith("onLocalVideoStateChanged")) + override fun onVideoStopped() { + callback(RtcEngineEvents.VideoStopped) + } +} diff --git a/android/src/main/java/io/agora/rtc/base/RtcSurfaceView.kt b/android/src/main/java/io/agora/rtc/base/RtcSurfaceView.kt new file mode 100644 index 000000000..891a0c7b2 --- /dev/null +++ b/android/src/main/java/io/agora/rtc/base/RtcSurfaceView.kt @@ -0,0 +1,96 @@ +package io.agora.rtc.base + +import android.content.Context +import android.view.SurfaceView +import android.widget.FrameLayout +import io.agora.rtc.RtcChannel +import io.agora.rtc.RtcEngine +import io.agora.rtc.video.VideoCanvas +import java.lang.ref.WeakReference + +class RtcSurfaceView( + context: Context +) : FrameLayout(context) { + private var surface: SurfaceView + private var canvas: VideoCanvas + private var channel: WeakReference? = null + + init { + try { + surface = RtcEngine.CreateRendererView(context) + } catch (e: UnsatisfiedLinkError) { + surface = SurfaceView(context) + e.printStackTrace() + } + canvas = VideoCanvas(surface) + addView(surface) + } + + fun setZOrderMediaOverlay(isMediaOverlay: Boolean) { + try { + removeView(surface) + surface.setZOrderMediaOverlay(isMediaOverlay) + addView(surface) + } catch (e: Exception) { + e.printStackTrace() + } + } + + fun setZOrderOnTop(onTop: Boolean) { + try { + removeView(surface) + surface.setZOrderOnTop(onTop) + addView(surface) + } catch (e: Exception) { + e.printStackTrace() + } + } + + fun setRenderMode(engine: RtcEngine, @Annotations.AgoraVideoRenderMode renderMode: Int) { + canvas.renderMode = renderMode + setupRenderMode(engine) + } + + fun setChannel(engine: RtcEngine, channel: RtcChannel?) { + this.channel = if (channel != null) WeakReference(channel) else null + canvas.channelId = channel?.channelId() + if (canvas.uid == 0) { + engine.setupLocalVideo(canvas) + } else { + engine.setupRemoteVideo(canvas) + } + } + + fun setMirrorMode(engine: RtcEngine, @Annotations.AgoraVideoMirrorMode mirrorMode: Int) { + canvas.mirrorMode = mirrorMode + setupRenderMode(engine) + } + + fun setUid(engine: RtcEngine, uid: Int) { + canvas.uid = uid + if (canvas.uid == 0) { + engine.setupLocalVideo(canvas) + } else { + engine.setupRemoteVideo(canvas) + } + } + + private fun setupRenderMode(engine: RtcEngine) { + if (canvas.uid == 0) { + engine.setLocalRenderMode(canvas.renderMode, canvas.mirrorMode) + } else { + channel?.get()?.let { + it.setRemoteRenderMode(canvas.uid, canvas.renderMode, canvas.mirrorMode) + return@setupRenderMode + } + engine.setRemoteRenderMode(canvas.uid, canvas.renderMode, canvas.mirrorMode) + } + } + + override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { + val width: Int = MeasureSpec.getSize(widthMeasureSpec) + val height: Int = MeasureSpec.getSize(heightMeasureSpec) + surface.layout(0, 0, width, height) + super.onMeasure(widthMeasureSpec, heightMeasureSpec) + } +} diff --git a/android/src/main/java/io/agora/rtc/base/RtcTextureView.kt b/android/src/main/java/io/agora/rtc/base/RtcTextureView.kt new file mode 100644 index 000000000..e028b55c4 --- /dev/null +++ b/android/src/main/java/io/agora/rtc/base/RtcTextureView.kt @@ -0,0 +1,61 @@ +package io.agora.rtc.base + +import android.content.Context +import android.widget.FrameLayout +import io.agora.rtc.RtcChannel +import io.agora.rtc.RtcEngine +import io.agora.rtc.mediaio.AgoraTextureView +import io.agora.rtc.mediaio.MediaIO +import java.lang.ref.WeakReference + +class RtcTextureView( + context: Context +) : FrameLayout(context) { + private var texture: AgoraTextureView = AgoraTextureView(context) + private var uid: Int = 0 + private var channel: WeakReference? = null + + init { + texture.init(null) + texture.setBufferType(MediaIO.BufferType.BYTE_ARRAY) + texture.setPixelFormat(MediaIO.PixelFormat.I420) + addView(texture) + } + + fun setChannel(engine: RtcEngine, channel: RtcChannel?) { + this.channel = if (channel != null) WeakReference(channel) else null + setupVideoRenderer(engine) + } + + fun setMirror(engine: RtcEngine, mirror: Boolean) { + texture.setMirror(mirror) + setupVideoRenderer(engine) + } + + fun setUid(engine: RtcEngine, uid: Int) { + this.uid = uid + setupVideoRenderer(engine) + } + + private fun setupVideoRenderer(engine: RtcEngine) { + if (uid == 0) { + engine.setLocalVideoRenderer(null) + engine.setLocalVideoRenderer(texture) + } else { + channel?.get()?.let { + it.setRemoteVideoRenderer(uid, null) + it.setRemoteVideoRenderer(uid, texture) + return@setupVideoRenderer + } + engine.setRemoteVideoRenderer(uid, null) + engine.setRemoteVideoRenderer(uid, texture) + } + } + + override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { + val width: Int = MeasureSpec.getSize(widthMeasureSpec) + val height: Int = MeasureSpec.getSize(heightMeasureSpec) + texture.layout(0, 0, width, height) + super.onMeasure(widthMeasureSpec, heightMeasureSpec) + } +} diff --git a/android/src/main/java/io/agora/rtc/react/PromiseCallback.kt b/android/src/main/java/io/agora/rtc/react/PromiseCallback.kt new file mode 100644 index 000000000..642d7a842 --- /dev/null +++ b/android/src/main/java/io/agora/rtc/react/PromiseCallback.kt @@ -0,0 +1,27 @@ +package io.agora.rtc.react + +import com.facebook.react.bridge.Arguments +import com.facebook.react.bridge.Promise +import io.agora.rtc.base.Callback + +class PromiseCallback( + private val promise: Promise? +) : Callback() { + override fun success(data: Any?) { + if (data is Map<*, *>) { + val map = mutableMapOf() + data.forEach { + if (it.key is String) { + map[it.key as String] = it.value + } + } + promise?.resolve(Arguments.makeNativeMap(map)) + } else { + promise?.resolve(data) + } + } + + override fun failure(code: String, message: String) { + promise?.reject(code, message) + } +} diff --git a/android/src/main/java/io/agora/rtc/react/RCTAgoraRtcChannelModule.kt b/android/src/main/java/io/agora/rtc/react/RCTAgoraRtcChannelModule.kt new file mode 100644 index 000000000..6bcbbec9e --- /dev/null +++ b/android/src/main/java/io/agora/rtc/react/RCTAgoraRtcChannelModule.kt @@ -0,0 +1,243 @@ +package io.agora.rtc.react + +import com.facebook.react.bridge.* +import com.facebook.react.module.annotations.ReactModule +import com.facebook.react.modules.core.DeviceEventManagerModule +import io.agora.rtc.RtcChannel +import io.agora.rtc.RtcEngine +import io.agora.rtc.base.* +import io.agora.rtc.react.RCTAgoraRtcChannelModule.Companion.REACT_CLASS + +@ReactModule(name = REACT_CLASS) +class RCTAgoraRtcChannelModule( + reactContext: ReactApplicationContext +) : ReactContextBaseJavaModule(reactContext), + RtcChannelInterface { + companion object { + const val REACT_CLASS = "RCTAgoraRtcChannelModule" + } + + private val manager = RtcChannelManager() + + override fun getName(): String { + return REACT_CLASS + } + + override fun getConstants(): MutableMap { + return mutableMapOf( + "prefix" to RtcChannelEventHandler.PREFIX + ) + } + + override fun onCatalystInstanceDestroy() { + super.onCatalystInstanceDestroy() + manager.release() + } + + private fun emit(methodName: String, data: Map?) { + reactApplicationContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java) + .emit("${RtcChannelEventHandler.PREFIX}$methodName", Arguments.makeNativeMap(data)) + } + + private fun engine(): RtcEngine? { + return reactApplicationContext.getNativeModule(RCTAgoraRtcEngineModule::class.java).engine() + } + + fun channel(channelId: String): RtcChannel? { + return manager[channelId] + } + + @ReactMethod + override fun create(channelId: String, callback: Promise?) { + PromiseCallback(callback).resolve(engine()) { + manager.create(it, channelId) { methodName, data -> + emit(methodName, data) + } + } + } + + @ReactMethod + override fun destroy(channelId: String, callback: Promise?) { + PromiseCallback(callback).code(manager.destroy(channelId)) + } + + @ReactMethod + override fun setClientRole(channelId: String, role: Int, callback: Promise?) { + PromiseCallback(callback).code(manager[channelId]?.setClientRole(role)) + } + + @ReactMethod + override fun joinChannel(channelId: String, token: String?, optionalInfo: String?, optionalUid: Int, options: ReadableMap, callback: Promise?) { + PromiseCallback(callback).code(channel(channelId)?.joinChannel(token, optionalInfo, optionalUid, mapToChannelMediaOptions(options.toHashMap()))) + } + + @ReactMethod + override fun joinChannelWithUserAccount(channelId: String, token: String?, userAccount: String, options: ReadableMap, callback: Promise?) { + PromiseCallback(callback).code(channel(channelId)?.joinChannelWithUserAccount(token, userAccount, mapToChannelMediaOptions(options.toHashMap()))) + } + + @ReactMethod + override fun leaveChannel(channelId: String, callback: Promise?) { + PromiseCallback(callback).code(channel(channelId)?.leaveChannel()) + } + + @ReactMethod + override fun renewToken(channelId: String, token: String, callback: Promise?) { + PromiseCallback(callback).code(channel(channelId)?.renewToken(token)) + } + + @ReactMethod + override fun getConnectionState(channelId: String, callback: Promise?) { + PromiseCallback(callback).resolve(channel(channelId)) { it.connectionState } + } + + @ReactMethod + override fun publish(channelId: String, callback: Promise?) { + PromiseCallback(callback).code(channel(channelId)?.publish()) + } + + @ReactMethod + override fun unpublish(channelId: String, callback: Promise?) { + PromiseCallback(callback).code(channel(channelId)?.unpublish()) + } + + @ReactMethod + override fun getCallId(channelId: String, callback: Promise?) { + PromiseCallback(callback).resolve(channel(channelId)) { it.callId } + } + + @ReactMethod + override fun setLiveTranscoding(channelId: String, transcoding: ReadableMap, callback: Promise?) { + PromiseCallback(callback).code(channel(channelId)?.setLiveTranscoding(mapToLiveTranscoding(transcoding.toHashMap()))) + } + + @ReactMethod + override fun addPublishStreamUrl(channelId: String, url: String, transcodingEnabled: Boolean, callback: Promise?) { + PromiseCallback(callback).code(channel(channelId)?.addPublishStreamUrl(url, transcodingEnabled)) + } + + @ReactMethod + override fun removePublishStreamUrl(channelId: String, url: String, callback: Promise?) { + PromiseCallback(callback).code(channel(channelId)?.removePublishStreamUrl(url)) + } + + @ReactMethod + override fun startChannelMediaRelay(channelId: String, channelMediaRelayConfiguration: ReadableMap, callback: Promise?) { + PromiseCallback(callback).code(channel(channelId)?.startChannelMediaRelay(mapToChannelMediaRelayConfiguration(channelMediaRelayConfiguration.toHashMap()))) + } + + @ReactMethod + override fun updateChannelMediaRelay(channelId: String, channelMediaRelayConfiguration: ReadableMap, callback: Promise?) { + PromiseCallback(callback).code(channel(channelId)?.updateChannelMediaRelay(mapToChannelMediaRelayConfiguration(channelMediaRelayConfiguration.toHashMap()))) + } + + @ReactMethod + override fun stopChannelMediaRelay(channelId: String, callback: Promise?) { + PromiseCallback(callback).code(channel(channelId)?.stopChannelMediaRelay()) + } + + @ReactMethod + override fun registerMediaMetadataObserver(channelId: String, callback: Promise?) { + PromiseCallback(callback).code(manager.registerMediaMetadataObserver(channelId) { methodName, data -> emit(methodName, data) }) + } + + @ReactMethod + override fun unregisterMediaMetadataObserver(channelId: String, callback: Promise?) { + PromiseCallback(callback).code(manager.unregisterMediaMetadataObserver(channelId)) + } + + @ReactMethod + override fun setMaxMetadataSize(channelId: String, size: Int, callback: Promise?) { + PromiseCallback(callback).code(manager.setMaxMetadataSize(channelId, size)) + } + + @ReactMethod + override fun sendMetadata(channelId: String, metadata: String, callback: Promise?) { + PromiseCallback(callback).code(manager.addMetadata(channelId, metadata)) + } + + @ReactMethod + override fun setEncryptionSecret(channelId: String, secret: String, callback: Promise?) { + PromiseCallback(callback).code(channel(channelId)?.setEncryptionSecret(secret)) + } + + @ReactMethod + override fun setEncryptionMode(channelId: String, encryptionMode: String, callback: Promise?) { + PromiseCallback(callback).code(channel(channelId)?.setEncryptionMode(encryptionMode)) + } + + @ReactMethod + override fun addInjectStreamUrl(channelId: String, url: String, config: ReadableMap, callback: Promise?) { + PromiseCallback(callback).code(channel(channelId)?.addInjectStreamUrl(url, mapToLiveInjectStreamConfig(config.toHashMap()))) + } + + @ReactMethod + override fun removeInjectStreamUrl(channelId: String, url: String, callback: Promise?) { + PromiseCallback(callback).code(channel(channelId)?.removeInjectStreamUrl(url)) + } + + @ReactMethod + override fun createDataStream(channelId: String, reliable: Boolean, ordered: Boolean, callback: Promise?) { + PromiseCallback(callback).code(manager.createDataStream(channelId, reliable, ordered)) { it } + } + + @ReactMethod + override fun sendStreamMessage(channelId: String, streamId: Int, message: String, callback: Promise?) { + PromiseCallback(callback).code(manager.sendStreamMessage(channelId, streamId, message)) + } + + @ReactMethod + override fun adjustUserPlaybackSignalVolume(channelId: String, uid: Int, volume: Int, callback: Promise?) { + PromiseCallback(callback).code(channel(channelId)?.adjustUserPlaybackSignalVolume(uid, volume)) + } + + @ReactMethod + override fun muteRemoteAudioStream(channelId: String, uid: Int, muted: Boolean, callback: Promise?) { + PromiseCallback(callback).code(channel(channelId)?.muteRemoteAudioStream(uid, muted)) + } + + @ReactMethod + override fun muteAllRemoteAudioStreams(channelId: String, muted: Boolean, callback: Promise?) { + PromiseCallback(callback).code(channel(channelId)?.muteAllRemoteAudioStreams(muted)) + } + + @ReactMethod + override fun setDefaultMuteAllRemoteAudioStreams(channelId: String, muted: Boolean, callback: Promise?) { + PromiseCallback(callback).code(channel(channelId)?.setDefaultMuteAllRemoteAudioStreams(muted)) + } + + @ReactMethod + override fun muteRemoteVideoStream(channelId: String, uid: Int, muted: Boolean, callback: Promise?) { + PromiseCallback(callback).code(channel(channelId)?.muteRemoteVideoStream(uid, muted)) + } + + @ReactMethod + override fun muteAllRemoteVideoStreams(channelId: String, muted: Boolean, callback: Promise?) { + PromiseCallback(callback).code(channel(channelId)?.muteAllRemoteVideoStreams(muted)) + } + + @ReactMethod + override fun setDefaultMuteAllRemoteVideoStreams(channelId: String, muted: Boolean, callback: Promise?) { + PromiseCallback(callback).code(channel(channelId)?.setDefaultMuteAllRemoteVideoStreams(muted)) + } + + @ReactMethod + override fun setRemoteVoicePosition(channelId: String, uid: Int, pan: Double, gain: Double, callback: Promise?) { + PromiseCallback(callback).code(channel(channelId)?.setRemoteVoicePosition(uid, pan, gain)) + } + + @ReactMethod + override fun setRemoteVideoStreamType(channelId: String, uid: Int, streamType: Int, callback: Promise?) { + PromiseCallback(callback).code(channel(channelId)?.setRemoteVideoStreamType(uid, streamType)) + } + + @ReactMethod + override fun setRemoteDefaultVideoStreamType(channelId: String, streamType: Int, callback: Promise?) { + PromiseCallback(callback).code(channel(channelId)?.setRemoteDefaultVideoStreamType(streamType)) + } + + @ReactMethod + override fun setRemoteUserPriority(channelId: String, uid: Int, userPriority: Int, callback: Promise?) { + PromiseCallback(callback).code(channel(channelId)?.setRemoteUserPriority(uid, userPriority)) + } +} diff --git a/android/src/main/java/io/agora/rtc/react/RCTAgoraRtcEngineModule.kt b/android/src/main/java/io/agora/rtc/react/RCTAgoraRtcEngineModule.kt new file mode 100644 index 000000000..feed366dc --- /dev/null +++ b/android/src/main/java/io/agora/rtc/react/RCTAgoraRtcEngineModule.kt @@ -0,0 +1,672 @@ +package io.agora.rtc.react + +import com.facebook.react.bridge.* +import com.facebook.react.module.annotations.ReactModule +import com.facebook.react.modules.core.DeviceEventManagerModule +import io.agora.rtc.RtcEngine +import io.agora.rtc.base.* +import io.agora.rtc.react.RCTAgoraRtcEngineModule.Companion.REACT_CLASS + +@ReactModule(name = REACT_CLASS) +class RCTAgoraRtcEngineModule( + reactContext: ReactApplicationContext +) : ReactContextBaseJavaModule(reactContext), + RtcEngineInterface { + companion object { + const val REACT_CLASS = "RCTAgoraRtcEngineModule" + } + + private val manager = RtcEngineManager() + + override fun getName(): String { + return REACT_CLASS + } + + override fun getConstants(): MutableMap { + return mutableMapOf( + "prefix" to RtcEngineEventHandler.PREFIX + ) + } + + override fun onCatalystInstanceDestroy() { + super.onCatalystInstanceDestroy() + manager.release() + } + + private fun emit(methodName: String, data: Map?) { + reactApplicationContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java) + .emit("${RtcEngineEventHandler.PREFIX}$methodName", Arguments.makeNativeMap(data)) + } + + fun engine(): RtcEngine? { + return manager.engine() + } + + @ReactMethod + override fun create(appId: String, areaCode: Int, callback: Promise?) { + manager.create(reactApplicationContext.applicationContext, appId, areaCode, Annotations.AgoraRtcAppType.REACTNATIVE) { methodName, data -> + emit(methodName, data) + } + PromiseCallback(callback).resolve(engine()) {} + } + + @ReactMethod + override fun destroy(callback: Promise?) { + PromiseCallback(callback).resolve(engine()) { manager.destroy() } + } + + @ReactMethod + override fun setChannelProfile(profile: Int, callback: Promise?) { + PromiseCallback(callback).code(engine()?.setChannelProfile(profile)) + } + + @ReactMethod + override fun setClientRole(role: Int, callback: Promise?) { + PromiseCallback(callback).code(engine()?.setClientRole(role)) + } + + @ReactMethod + override fun joinChannel(token: String?, channelName: String, optionalInfo: String?, optionalUid: Int, callback: Promise?) { + PromiseCallback(callback).code(engine()?.joinChannel(token, channelName, optionalInfo, optionalUid)) + } + + @ReactMethod + override fun switchChannel(token: String?, channelName: String, callback: Promise?) { + PromiseCallback(callback).code(engine()?.switchChannel(token, channelName)) + } + + @ReactMethod + override fun leaveChannel(callback: Promise?) { + PromiseCallback(callback).code(engine()?.leaveChannel()) + } + + @ReactMethod + override fun renewToken(token: String, callback: Promise?) { + PromiseCallback(callback).code(engine()?.renewToken(token)) + } + + @ReactMethod + override fun getConnectionState(callback: Promise?) { + PromiseCallback(callback).resolve(engine()) { it.connectionState } + } + + @ReactMethod + override fun getCallId(callback: Promise?) { + PromiseCallback(callback).resolve(engine()) { it.callId } + } + + @ReactMethod + override fun rate(callId: String, rating: Int, description: String?, callback: Promise?) { + PromiseCallback(callback).code(engine()?.rate(callId, rating, description)) + } + + @ReactMethod + override fun complain(callId: String, description: String, callback: Promise?) { + PromiseCallback(callback).code(engine()?.complain(callId, description)) + } + + @ReactMethod + override fun setLogFile(filePath: String, callback: Promise?) { + PromiseCallback(callback).code(engine()?.setLogFile(filePath)) + } + + @ReactMethod + override fun setLogFilter(filter: Int, callback: Promise?) { + PromiseCallback(callback).code(engine()?.setLogFilter(filter)) + } + + @ReactMethod + override fun setLogFileSize(fileSizeInKBytes: Int, callback: Promise?) { + PromiseCallback(callback).code(engine()?.setLogFileSize(fileSizeInKBytes)) + } + + @ReactMethod + override fun setParameters(parameters: String, callback: Promise?) { + PromiseCallback(callback).code(engine()?.setParameters(parameters)) + } + + @ReactMethod + override fun enableWebSdkInteroperability(enabled: Boolean, callback: Promise?) { + PromiseCallback(callback).code(engine()?.enableWebSdkInteroperability(enabled)) + } + + @ReactMethod + override fun registerLocalUserAccount(appId: String, userAccount: String, callback: Promise?) { + PromiseCallback(callback).code(engine()?.registerLocalUserAccount(appId, userAccount)) + } + + @ReactMethod + override fun joinChannelWithUserAccount(token: String?, channelName: String, userAccount: String, callback: Promise?) { + PromiseCallback(callback).code(engine()?.joinChannelWithUserAccount(token, channelName, userAccount)) + } + + @ReactMethod + override fun getUserInfoByUserAccount(userAccount: String, callback: Promise?) { + PromiseCallback(callback).resolve(engine()) { manager.getUserInfoByUserAccount(userAccount) } + } + + @ReactMethod + override fun getUserInfoByUid(uid: Int, callback: Promise?) { + PromiseCallback(callback).resolve(engine()) { manager.getUserInfoByUid(uid) } + } + + @ReactMethod + override fun enableAudio(callback: Promise?) { + PromiseCallback(callback).code(engine()?.enableAudio()) + } + + @ReactMethod + override fun disableAudio(callback: Promise?) { + PromiseCallback(callback).code(engine()?.disableAudio()) + } + + @ReactMethod + override fun setAudioProfile(profile: Int, scenario: Int, callback: Promise?) { + PromiseCallback(callback).code(engine()?.setAudioProfile(profile, scenario)) + } + + @ReactMethod + override fun adjustRecordingSignalVolume(volume: Int, callback: Promise?) { + PromiseCallback(callback).code(engine()?.adjustRecordingSignalVolume(volume)) + } + + @ReactMethod + override fun adjustUserPlaybackSignalVolume(uid: Int, volume: Int, callback: Promise?) { + PromiseCallback(callback).code(engine()?.adjustUserPlaybackSignalVolume(uid, volume)) + } + + @ReactMethod + override fun adjustPlaybackSignalVolume(volume: Int, callback: Promise?) { + PromiseCallback(callback).code(engine()?.adjustPlaybackSignalVolume(volume)) + } + + @ReactMethod + override fun enableLocalAudio(enabled: Boolean, callback: Promise?) { + PromiseCallback(callback).code(engine()?.enableLocalAudio(enabled)) + } + + @ReactMethod + override fun muteLocalAudioStream(muted: Boolean, callback: Promise?) { + PromiseCallback(callback).code(engine()?.muteLocalAudioStream(muted)) + } + + @ReactMethod + override fun muteRemoteAudioStream(uid: Int, muted: Boolean, callback: Promise?) { + PromiseCallback(callback).code(engine()?.muteRemoteAudioStream(uid, muted)) + } + + @ReactMethod + override fun muteAllRemoteAudioStreams(muted: Boolean, callback: Promise?) { + PromiseCallback(callback).code(engine()?.muteAllRemoteAudioStreams(muted)) + } + + @ReactMethod + override fun setDefaultMuteAllRemoteAudioStreams(muted: Boolean, callback: Promise?) { + PromiseCallback(callback).code(engine()?.setDefaultMuteAllRemoteAudioStreams(muted)) + } + + @ReactMethod + override fun enableAudioVolumeIndication(interval: Int, smooth: Int, report_vad: Boolean, callback: Promise?) { + PromiseCallback(callback).code(engine()?.enableAudioVolumeIndication(interval, smooth, report_vad)) + } + + @ReactMethod + override fun enableVideo(callback: Promise?) { + PromiseCallback(callback).code(engine()?.enableVideo()) + } + + @ReactMethod + override fun disableVideo(callback: Promise?) { + PromiseCallback(callback).code(engine()?.disableVideo()) + } + + @ReactMethod + override fun setVideoEncoderConfiguration(config: ReadableMap, callback: Promise?) { + PromiseCallback(callback).code(engine()?.setVideoEncoderConfiguration(mapToVideoEncoderConfiguration(config.toHashMap()))) + } + + @ReactMethod + override fun enableLocalVideo(enabled: Boolean, callback: Promise?) { + PromiseCallback(callback).code(engine()?.enableLocalVideo(enabled)) + } + + @ReactMethod + override fun muteLocalVideoStream(muted: Boolean, callback: Promise?) { + PromiseCallback(callback).code(engine()?.muteLocalVideoStream(muted)) + } + + @ReactMethod + override fun muteRemoteVideoStream(uid: Int, muted: Boolean, callback: Promise?) { + PromiseCallback(callback).code(engine()?.muteRemoteVideoStream(uid, muted)) + } + + @ReactMethod + override fun muteAllRemoteVideoStreams(muted: Boolean, callback: Promise?) { + PromiseCallback(callback).code(engine()?.muteAllRemoteVideoStreams(muted)) + } + + @ReactMethod + override fun setDefaultMuteAllRemoteVideoStreams(muted: Boolean, callback: Promise?) { + PromiseCallback(callback).code(engine()?.setDefaultMuteAllRemoteVideoStreams(muted)) + } + + @ReactMethod + override fun setBeautyEffectOptions(enabled: Boolean, options: ReadableMap, callback: Promise?) { + PromiseCallback(callback).code(engine()?.setBeautyEffectOptions(enabled, mapToBeautyOptions(options.toHashMap()))) + } + + @ReactMethod + override fun startAudioMixing(filePath: String, loopback: Boolean, replace: Boolean, cycle: Int, callback: Promise?) { + PromiseCallback(callback).code(engine()?.startAudioMixing(filePath, loopback, replace, cycle)) + } + + @ReactMethod + override fun stopAudioMixing(callback: Promise?) { + PromiseCallback(callback).code(engine()?.stopAudioMixing()) + } + + @ReactMethod + override fun pauseAudioMixing(callback: Promise?) { + PromiseCallback(callback).code(engine()?.pauseAudioMixing()) + } + + @ReactMethod + override fun resumeAudioMixing(callback: Promise?) { + PromiseCallback(callback).code(engine()?.resumeAudioMixing()) + } + + @ReactMethod + override fun adjustAudioMixingVolume(volume: Int, callback: Promise?) { + PromiseCallback(callback).code(engine()?.adjustAudioMixingVolume(volume)) + } + + @ReactMethod + override fun adjustAudioMixingPlayoutVolume(volume: Int, callback: Promise?) { + PromiseCallback(callback).code(engine()?.adjustAudioMixingPlayoutVolume(volume)) + } + + @ReactMethod + override fun adjustAudioMixingPublishVolume(volume: Int, callback: Promise?) { + PromiseCallback(callback).code(engine()?.adjustAudioMixingPublishVolume(volume)) + } + + @ReactMethod + override fun getAudioMixingPlayoutVolume(callback: Promise?) { + PromiseCallback(callback).code(engine()?.audioMixingPlayoutVolume) { it } + } + + @ReactMethod + override fun getAudioMixingPublishVolume(callback: Promise?) { + PromiseCallback(callback).code(engine()?.audioMixingPublishVolume) { it } + } + + @ReactMethod + override fun getAudioMixingDuration(callback: Promise?) { + PromiseCallback(callback).code(engine()?.audioMixingDuration) { it } + } + + @ReactMethod + override fun getAudioMixingCurrentPosition(callback: Promise?) { + PromiseCallback(callback).code(engine()?.audioMixingCurrentPosition) { it } + } + + @ReactMethod + override fun setAudioMixingPosition(pos: Int, callback: Promise?) { + PromiseCallback(callback).code(engine()?.setAudioMixingPosition(pos)) + } + + @ReactMethod + override fun setAudioMixingPitch(pitch: Int, callback: Promise?) { + PromiseCallback(callback).code(engine()?.setAudioMixingPitch(pitch)) + } + + @ReactMethod + override fun getEffectsVolume(callback: Promise?) { + PromiseCallback(callback).resolve(engine()) { it.audioEffectManager.effectsVolume } + } + + @ReactMethod + override fun setEffectsVolume(volume: Double, callback: Promise?) { + PromiseCallback(callback).code(engine()?.audioEffectManager?.setEffectsVolume(volume)) + } + + @ReactMethod + override fun setVolumeOfEffect(soundId: Int, volume: Double, callback: Promise?) { + PromiseCallback(callback).code(engine()?.audioEffectManager?.setVolumeOfEffect(soundId, volume)) + } + + @ReactMethod + override fun playEffect(soundId: Int, filePath: String, loopCount: Int, pitch: Double, pan: Double, gain: Double, publish: Boolean, callback: Promise?) { + PromiseCallback(callback).code(engine()?.audioEffectManager?.playEffect(soundId, filePath, loopCount, pitch, pan, gain, publish)) + } + + @ReactMethod + override fun stopEffect(soundId: Int, callback: Promise?) { + PromiseCallback(callback).code(engine()?.audioEffectManager?.stopEffect(soundId)) + } + + @ReactMethod + override fun stopAllEffects(callback: Promise?) { + PromiseCallback(callback).code(engine()?.audioEffectManager?.stopAllEffects()) + } + + @ReactMethod + override fun preloadEffect(soundId: Int, filePath: String, callback: Promise?) { + PromiseCallback(callback).code(engine()?.audioEffectManager?.preloadEffect(soundId, filePath)) + } + + @ReactMethod + override fun unloadEffect(soundId: Int, callback: Promise?) { + PromiseCallback(callback).code(engine()?.audioEffectManager?.unloadEffect(soundId)) + } + + @ReactMethod + override fun pauseEffect(soundId: Int, callback: Promise?) { + PromiseCallback(callback).code(engine()?.audioEffectManager?.pauseEffect(soundId)) + } + + @ReactMethod + override fun pauseAllEffects(callback: Promise?) { + PromiseCallback(callback).code(engine()?.audioEffectManager?.pauseAllEffects()) + } + + @ReactMethod + override fun resumeEffect(soundId: Int, callback: Promise?) { + PromiseCallback(callback).code(engine()?.audioEffectManager?.resumeEffect(soundId)) + } + + @ReactMethod + override fun resumeAllEffects(callback: Promise?) { + PromiseCallback(callback).code(engine()?.audioEffectManager?.resumeAllEffects()) + } + + @ReactMethod + override fun setLocalVoiceChanger(voiceChanger: Int, callback: Promise?) { + PromiseCallback(callback).code(engine()?.setLocalVoiceChanger(voiceChanger)) + } + + @ReactMethod + override fun setLocalVoiceReverbPreset(preset: Int, callback: Promise?) { + PromiseCallback(callback).code(engine()?.setLocalVoiceReverbPreset(preset)) + } + + @ReactMethod + override fun setLocalVoicePitch(pitch: Double, callback: Promise?) { + PromiseCallback(callback).code(engine()?.setLocalVoicePitch(pitch)) + } + + @ReactMethod + override fun setLocalVoiceEqualization(bandFrequency: Int, bandGain: Int, callback: Promise?) { + PromiseCallback(callback).code(engine()?.setLocalVoiceEqualization(bandFrequency, bandGain)) + } + + @ReactMethod + override fun setLocalVoiceReverb(reverbKey: Int, value: Int, callback: Promise?) { + PromiseCallback(callback).code(engine()?.setLocalVoiceReverb(reverbKey, value)) + } + + @ReactMethod + override fun enableSoundPositionIndication(enabled: Boolean, callback: Promise?) { + PromiseCallback(callback).code(engine()?.enableSoundPositionIndication(enabled)) + } + + @ReactMethod + override fun setRemoteVoicePosition(uid: Int, pan: Double, gain: Double, callback: Promise?) { + PromiseCallback(callback).code(engine()?.setRemoteVoicePosition(uid, pan, gain)) + } + + @ReactMethod + override fun setLiveTranscoding(transcoding: ReadableMap, callback: Promise?) { + PromiseCallback(callback).code(engine()?.setLiveTranscoding(mapToLiveTranscoding(transcoding.toHashMap()))) + } + + @ReactMethod + override fun addPublishStreamUrl(url: String, transcodingEnabled: Boolean, callback: Promise?) { + PromiseCallback(callback).code(engine()?.addPublishStreamUrl(url, transcodingEnabled)) + } + + @ReactMethod + override fun removePublishStreamUrl(url: String, callback: Promise?) { + PromiseCallback(callback).code(engine()?.removePublishStreamUrl(url)) + } + + @ReactMethod + override fun startChannelMediaRelay(channelMediaRelayConfiguration: ReadableMap, callback: Promise?) { + PromiseCallback(callback).code(engine()?.startChannelMediaRelay(mapToChannelMediaRelayConfiguration(channelMediaRelayConfiguration.toHashMap()))) + } + + @ReactMethod + override fun updateChannelMediaRelay(channelMediaRelayConfiguration: ReadableMap, callback: Promise?) { + PromiseCallback(callback).code(engine()?.updateChannelMediaRelay(mapToChannelMediaRelayConfiguration(channelMediaRelayConfiguration.toHashMap()))) + } + + @ReactMethod + override fun stopChannelMediaRelay(callback: Promise?) { + PromiseCallback(callback).code(engine()?.stopChannelMediaRelay()) + } + + @ReactMethod + override fun setDefaultAudioRoutetoSpeakerphone(defaultToSpeaker: Boolean, callback: Promise?) { + PromiseCallback(callback).code(engine()?.setDefaultAudioRoutetoSpeakerphone(defaultToSpeaker)) + } + + @ReactMethod + override fun setEnableSpeakerphone(enabled: Boolean, callback: Promise?) { + PromiseCallback(callback).code(engine()?.setEnableSpeakerphone(enabled)) + } + + @ReactMethod + override fun isSpeakerphoneEnabled(callback: Promise?) { + PromiseCallback(callback).resolve(engine()) { it.isSpeakerphoneEnabled } + } + + @ReactMethod + override fun enableInEarMonitoring(enabled: Boolean, callback: Promise?) { + PromiseCallback(callback).code(engine()?.enableInEarMonitoring(enabled)) + } + + @ReactMethod + override fun setInEarMonitoringVolume(volume: Int, callback: Promise?) { + PromiseCallback(callback).code(engine()?.setInEarMonitoringVolume(volume)) + } + + @ReactMethod + override fun enableDualStreamMode(enabled: Boolean, callback: Promise?) { + PromiseCallback(callback).code(engine()?.enableDualStreamMode(enabled)) + } + + @ReactMethod + override fun setRemoteVideoStreamType(uid: Int, streamType: Int, callback: Promise?) { + PromiseCallback(callback).code(engine()?.setRemoteVideoStreamType(uid, streamType)) + } + + @ReactMethod + override fun setRemoteDefaultVideoStreamType(streamType: Int, callback: Promise?) { + PromiseCallback(callback).code(engine()?.setRemoteDefaultVideoStreamType(streamType)) + } + + @ReactMethod + override fun setLocalPublishFallbackOption(option: Int, callback: Promise?) { + PromiseCallback(callback).code(engine()?.setLocalPublishFallbackOption(option)) + } + + @ReactMethod + override fun setRemoteSubscribeFallbackOption(option: Int, callback: Promise?) { + PromiseCallback(callback).code(engine()?.setRemoteSubscribeFallbackOption(option)) + } + + @ReactMethod + override fun setRemoteUserPriority(uid: Int, userPriority: Int, callback: Promise?) { + PromiseCallback(callback).code(engine()?.setRemoteUserPriority(uid, userPriority)) + } + + @ReactMethod + override fun startEchoTest(intervalInSeconds: Int, callback: Promise?) { + PromiseCallback(callback).code(engine()?.startEchoTest(intervalInSeconds)) + } + + @ReactMethod + override fun stopEchoTest(callback: Promise?) { + PromiseCallback(callback).code(engine()?.stopEchoTest()) + } + + @ReactMethod + override fun enableLastmileTest(callback: Promise?) { + PromiseCallback(callback).code(engine()?.enableLastmileTest()) + } + + @ReactMethod + override fun disableLastmileTest(callback: Promise?) { + PromiseCallback(callback).code(engine()?.disableLastmileTest()) + } + + @ReactMethod + override fun startLastmileProbeTest(config: ReadableMap, callback: Promise?) { + PromiseCallback(callback).code(engine()?.startLastmileProbeTest(mapToLastmileProbeConfig(config.toHashMap()))) + } + + @ReactMethod + override fun stopLastmileProbeTest(callback: Promise?) { + PromiseCallback(callback).code(engine()?.stopLastmileProbeTest()) + } + + @ReactMethod + override fun registerMediaMetadataObserver(callback: Promise?) { + PromiseCallback(callback).code(manager.registerMediaMetadataObserver { methodName, data -> emit(methodName, data) }) + } + + @ReactMethod + override fun unregisterMediaMetadataObserver(callback: Promise?) { + PromiseCallback(callback).code(manager.unregisterMediaMetadataObserver()) + } + + @ReactMethod + override fun setMaxMetadataSize(size: Int, callback: Promise?) { + PromiseCallback(callback).code(manager.setMaxMetadataSize(size)) + } + + @ReactMethod + override fun sendMetadata(metadata: String, callback: Promise?) { + PromiseCallback(callback).code(manager.addMetadata(metadata)) + } + + @ReactMethod + override fun addVideoWatermark(watermarkUrl: String, options: ReadableMap, callback: Promise?) { + PromiseCallback(callback).code(engine()?.addVideoWatermark(watermarkUrl, mapToWatermarkOptions(options.toHashMap()))) + } + + @ReactMethod + override fun clearVideoWatermarks(callback: Promise?) { + PromiseCallback(callback).code(engine()?.clearVideoWatermarks()) + } + + @ReactMethod + override fun setEncryptionSecret(secret: String, callback: Promise?) { + PromiseCallback(callback).code(engine()?.setEncryptionSecret(secret)) + } + + @ReactMethod + override fun setEncryptionMode(encryptionMode: String, callback: Promise?) { + PromiseCallback(callback).code(engine()?.setEncryptionMode(encryptionMode)) + } + + @ReactMethod + override fun startAudioRecording(filePath: String, sampleRate: Int, quality: Int, callback: Promise?) { + PromiseCallback(callback).code(engine()?.startAudioRecording(filePath, sampleRate, quality)) + } + + @ReactMethod + override fun stopAudioRecording(callback: Promise?) { + PromiseCallback(callback).code(engine()?.stopAudioRecording()) + } + + @ReactMethod + override fun addInjectStreamUrl(url: String, config: ReadableMap, callback: Promise?) { + PromiseCallback(callback).code(engine()?.addInjectStreamUrl(url, mapToLiveInjectStreamConfig(config.toHashMap()))) + } + + @ReactMethod + override fun removeInjectStreamUrl(url: String, callback: Promise?) { + PromiseCallback(callback).code(engine()?.removeInjectStreamUrl(url)) + } + + @ReactMethod + override fun switchCamera(callback: Promise?) { + PromiseCallback(callback).code(engine()?.switchCamera()) + } + + @ReactMethod + override fun isCameraZoomSupported(callback: Promise?) { + PromiseCallback(callback).resolve(engine()) { it.isCameraZoomSupported } + } + + @ReactMethod + override fun isCameraTorchSupported(callback: Promise?) { + PromiseCallback(callback).resolve(engine()) { it.isCameraTorchSupported } + } + + @ReactMethod + override fun isCameraFocusSupported(callback: Promise?) { + PromiseCallback(callback).resolve(engine()) { it.isCameraFocusSupported } + } + + @ReactMethod + override fun isCameraExposurePositionSupported(callback: Promise?) { + PromiseCallback(callback).resolve(engine()) { it.isCameraExposurePositionSupported } + } + + @ReactMethod + override fun isCameraAutoFocusFaceModeSupported(callback: Promise?) { + PromiseCallback(callback).resolve(engine()) { it.isCameraAutoFocusFaceModeSupported } + } + + @ReactMethod + override fun setCameraZoomFactor(factor: Float, callback: Promise?) { + PromiseCallback(callback).code(engine()?.setCameraZoomFactor(factor)) + } + + @ReactMethod + override fun getCameraMaxZoomFactor(callback: Promise?) { + PromiseCallback(callback).resolve(engine()) { it.cameraMaxZoomFactor } + } + + @ReactMethod + override fun setCameraFocusPositionInPreview(positionX: Float, positionY: Float, callback: Promise?) { + PromiseCallback(callback).code(engine()?.setCameraFocusPositionInPreview(positionX, positionY)) + } + + @ReactMethod + override fun setCameraExposurePosition(positionXinView: Float, positionYinView: Float, callback: Promise?) { + PromiseCallback(callback).code(engine()?.setCameraExposurePosition(positionXinView, positionYinView)) + } + + @ReactMethod + override fun enableFaceDetection(enable: Boolean, callback: Promise?) { + PromiseCallback(callback).code(engine()?.enableFaceDetection(enable)) + } + + @ReactMethod + override fun setCameraTorchOn(isOn: Boolean, callback: Promise?) { + PromiseCallback(callback).code(engine()?.setCameraTorchOn(isOn)) + } + + @ReactMethod + override fun setCameraAutoFocusFaceModeEnabled(enabled: Boolean, callback: Promise?) { + PromiseCallback(callback).code(engine()?.setCameraAutoFocusFaceModeEnabled(enabled)) + } + + @ReactMethod + override fun setCameraCapturerConfiguration(config: ReadableMap, callback: Promise?) { + PromiseCallback(callback).code(engine()?.setCameraCapturerConfiguration(mapToCameraCapturerConfiguration(config.toHashMap()))) + } + + @ReactMethod + override fun createDataStream(reliable: Boolean, ordered: Boolean, callback: Promise?) { + PromiseCallback(callback).code(manager.createDataStream(reliable, ordered)) { it } + } + + @ReactMethod + override fun sendStreamMessage(streamId: Int, message: String, callback: Promise?) { + PromiseCallback(callback).code(manager.sendStreamMessage(streamId, message)) + } +} diff --git a/android/src/main/java/io/agora/rtc/react/RCTAgoraRtcPackage.kt b/android/src/main/java/io/agora/rtc/react/RCTAgoraRtcPackage.kt new file mode 100644 index 000000000..a0748ef30 --- /dev/null +++ b/android/src/main/java/io/agora/rtc/react/RCTAgoraRtcPackage.kt @@ -0,0 +1,28 @@ +package io.agora.rtc.react + +import com.facebook.react.ReactPackage +import com.facebook.react.bridge.JavaScriptModule +import com.facebook.react.bridge.NativeModule +import com.facebook.react.bridge.ReactApplicationContext +import com.facebook.react.uimanager.ViewManager + +class RCTAgoraRtcPackage : ReactPackage { + override fun createNativeModules(reactContext: ReactApplicationContext): List { + return listOf( + RCTAgoraRtcEngineModule(reactContext), + RCTAgoraRtcChannelModule(reactContext) + ) + } + + // Deprecated in RN 0.47 + fun createJSModules(): List> { + return emptyList() + } + + override fun createViewManagers(reactContext: ReactApplicationContext): List> { + return listOf( + RCTAgoraRtcSurfaceViewManager(), + RCTAgoraRtcTextureViewManager() + ) + } +} diff --git a/android/src/main/java/io/agora/rtc/react/RCTAgoraRtcSurfaceViewManager.kt b/android/src/main/java/io/agora/rtc/react/RCTAgoraRtcSurfaceViewManager.kt new file mode 100644 index 000000000..587ebcb1a --- /dev/null +++ b/android/src/main/java/io/agora/rtc/react/RCTAgoraRtcSurfaceViewManager.kt @@ -0,0 +1,63 @@ +package io.agora.rtc.react + +import com.facebook.react.uimanager.SimpleViewManager +import com.facebook.react.uimanager.ThemedReactContext +import com.facebook.react.uimanager.annotations.ReactProp +import io.agora.rtc.RtcChannel +import io.agora.rtc.RtcEngine +import io.agora.rtc.base.RtcSurfaceView + +class RCTAgoraRtcSurfaceViewManager : SimpleViewManager() { + companion object { + const val REACT_CLASS = "RCTAgoraRtcSurfaceView" + } + + private var reactContext: ThemedReactContext? = null + + override fun createViewInstance(reactContext: ThemedReactContext): RtcSurfaceView { + this.reactContext = reactContext + return RtcSurfaceView(reactContext) + } + + override fun getName(): String { + return REACT_CLASS + } + + @ReactProp(name = "zOrderMediaOverlay") + fun setZOrderMediaOverlay(view: RtcSurfaceView, isMediaOverlay: Boolean) { + view.setZOrderMediaOverlay(isMediaOverlay) + } + + @ReactProp(name = "zOrderOnTop") + fun setZOrderOnTop(view: RtcSurfaceView, onTop: Boolean) { + view.setZOrderOnTop(onTop) + } + + @ReactProp(name = "renderMode") + fun setRenderMode(view: RtcSurfaceView, renderMode: Int) { + getEngine()?.let { view.setRenderMode(it, renderMode) } + } + + @ReactProp(name = "channelId") + fun setChannelId(view: RtcSurfaceView, channelId: String) { + getEngine()?.let { view.setChannel(it, getChannel(channelId)) } + } + + @ReactProp(name = "mirrorMode") + fun setMirrorMode(view: RtcSurfaceView, mirrorMode: Int) { + getEngine()?.let { view.setMirrorMode(it, mirrorMode) } + } + + @ReactProp(name = "uid") + fun setUid(view: RtcSurfaceView, uid: Int) { + getEngine()?.let { view.setUid(it, uid) } + } + + private fun getEngine(): RtcEngine? { + return reactContext?.getNativeModule(RCTAgoraRtcEngineModule::class.java)?.engine() + } + + private fun getChannel(channelId: String): RtcChannel? { + return reactContext?.getNativeModule(RCTAgoraRtcChannelModule::class.java)?.channel(channelId) + } +} diff --git a/android/src/main/java/io/agora/rtc/react/RCTAgoraRtcTextureViewManager.kt b/android/src/main/java/io/agora/rtc/react/RCTAgoraRtcTextureViewManager.kt new file mode 100644 index 000000000..10290f7f8 --- /dev/null +++ b/android/src/main/java/io/agora/rtc/react/RCTAgoraRtcTextureViewManager.kt @@ -0,0 +1,50 @@ +package io.agora.rtc.react + +import com.facebook.react.uimanager.SimpleViewManager +import com.facebook.react.uimanager.ThemedReactContext +import com.facebook.react.uimanager.annotations.ReactProp +import io.agora.rtc.RtcChannel +import io.agora.rtc.RtcEngine +import io.agora.rtc.base.RtcTextureView + +class RCTAgoraRtcTextureViewManager : SimpleViewManager() { + companion object { + const val REACT_CLASS = "RCTAgoraRtcTextureView" + } + + private var reactContext: ThemedReactContext? = null + + override fun createViewInstance(reactContext: ThemedReactContext): RtcTextureView { + this.reactContext = reactContext + return RtcTextureView(reactContext) + } + + override fun getName(): String { + return REACT_CLASS + } + + @ReactProp(name = "channelId") + fun setChannelId(view: RtcTextureView, channelId: String) { + getEngine()?.let { + view.setChannel(it, getChannel(channelId)) + } + } + + @ReactProp(name = "mirror") + fun setMirror(view: RtcTextureView, mirror: Boolean) { + getEngine()?.let { view.setMirror(it, mirror) } + } + + @ReactProp(name = "uid") + fun setUid(view: RtcTextureView, uid: Int) { + getEngine()?.let { view.setUid(it, uid) } + } + + private fun getEngine(): RtcEngine? { + return reactContext?.getNativeModule(RCTAgoraRtcEngineModule::class.java)?.engine() + } + + private fun getChannel(channelId: String): RtcChannel? { + return reactContext?.getNativeModule(RCTAgoraRtcChannelModule::class.java)?.channel(channelId) + } +} diff --git a/android/src/main/res/values/strings.xml b/android/src/main/res/values/strings.xml deleted file mode 100644 index caf5fca7e..000000000 --- a/android/src/main/res/values/strings.xml +++ /dev/null @@ -1,3 +0,0 @@ - - react-native-agora - diff --git a/docs/.keeps b/docs/.keeps deleted file mode 100644 index e69de29bb..000000000 diff --git a/docs/ANDROID_INSTALLATION.md b/docs/ANDROID_INSTALLATION.md deleted file mode 100644 index 449b757e3..000000000 --- a/docs/ANDROID_INSTALLATION.md +++ /dev/null @@ -1,4 +0,0 @@ -# [Android old setup for v 1.x](./v1/android.md) - - -# [Android latest version setup](./v2/android.md) diff --git a/docs/ANDROID_INSTALLATION.zh.md b/docs/ANDROID_INSTALLATION.zh.md deleted file mode 100644 index e8009c386..000000000 --- a/docs/ANDROID_INSTALLATION.zh.md +++ /dev/null @@ -1,4 +0,0 @@ -# [Android 1.x 版本构建步骤](./v1/android.zh.md) - - -# [Android 最新版本构建步骤](./v2/android.zh.md) diff --git a/docs/IOS_INSTALLATION.md b/docs/IOS_INSTALLATION.md deleted file mode 100644 index 382c682a8..000000000 --- a/docs/IOS_INSTALLATION.md +++ /dev/null @@ -1,4 +0,0 @@ -# [iOS old setup for v 1.x](./v1/ios.md) - - -# [iOS latest version setup](./v2/ios.md) diff --git a/docs/IOS_INSTALLATION.zh.md b/docs/IOS_INSTALLATION.zh.md deleted file mode 100644 index 7a566fc71..000000000 --- a/docs/IOS_INSTALLATION.zh.md +++ /dev/null @@ -1,4 +0,0 @@ -# [iOS 1.x 版本构建步骤](./v1/ios.zh.md) - - -# [iOS 最新版本构建步骤](./v2/ios.zh.md) diff --git a/README.old.md b/docs/v1/README.md similarity index 96% rename from README.old.md rename to docs/v1/README.md index d6d6e6e14..5ed218da0 100644 --- a/README.old.md +++ b/docs/v1/README.md @@ -27,11 +27,11 @@ Either way, then link with: `react-native link react-native-agora` -### [iOS Installation](docs/IOS_INSTALLATION.md) -### [iOS 开发环境安装指南](docs/IOS_INSTALLATION.zh.md) +### [iOS Installation](installation.ios.md) +### [iOS 开发环境安装指南](installation.ios.zh.md) -### [Android Installation](docs/ANDROID_INSTALLATION.md) -### [Android 开发环境安装指南](docs/ANDROID_INSTALLATION.zh.md) +### [Android Installation](installation.android.md) +### [Android 开发环境安装指南](installation.android.zh.md) ## Documentation @@ -116,7 +116,7 @@ RtcEngine.eventEmitter({ - 更新示例 React-Native为0.51 - 优化代码 -[Samples](./samples/README.md) +[Samples](../../samples/README.md) ## 更新信息 diff --git a/docs/v1/IOS_INSTALLATION/1.1_Open_iOS_ProjectFile.png b/docs/v1/imgs/1.1_Open_iOS_ProjectFile.png similarity index 100% rename from docs/v1/IOS_INSTALLATION/1.1_Open_iOS_ProjectFile.png rename to docs/v1/imgs/1.1_Open_iOS_ProjectFile.png diff --git a/docs/v1/IOS_INSTALLATION/1.2_LinkBinaryWithLibraries.png b/docs/v1/imgs/1.2_LinkBinaryWithLibraries.png similarity index 100% rename from docs/v1/IOS_INSTALLATION/1.2_LinkBinaryWithLibraries.png rename to docs/v1/imgs/1.2_LinkBinaryWithLibraries.png diff --git a/docs/v1/IOS_INSTALLATION/1.3_Add_Other_Libraries.png b/docs/v1/imgs/1.3_Add_Other_Libraries.png similarity index 100% rename from docs/v1/IOS_INSTALLATION/1.3_Add_Other_Libraries.png rename to docs/v1/imgs/1.3_Add_Other_Libraries.png diff --git a/docs/v1/IOS_INSTALLATION/1.4_Add_Framework_Search_Paths.png b/docs/v1/imgs/1.4_Add_Framework_Search_Paths.png similarity index 100% rename from docs/v1/IOS_INSTALLATION/1.4_Add_Framework_Search_Paths.png rename to docs/v1/imgs/1.4_Add_Framework_Search_Paths.png diff --git a/docs/v1/IOS_INSTALLATION/1.5_Add_Library_Search_Paths.png b/docs/v1/imgs/1.5_Add_Library_Search_Paths.png similarity index 100% rename from docs/v1/IOS_INSTALLATION/1.5_Add_Library_Search_Paths.png rename to docs/v1/imgs/1.5_Add_Library_Search_Paths.png diff --git a/docs/v1/IOS_INSTALLATION/1.6_Set_Build_Settings_Enable_Bitcode_No.png b/docs/v1/imgs/1.6_Set_Build_Settings_Enable_Bitcode_No.png similarity index 100% rename from docs/v1/IOS_INSTALLATION/1.6_Set_Build_Settings_Enable_Bitcode_No.png rename to docs/v1/imgs/1.6_Set_Build_Settings_Enable_Bitcode_No.png diff --git a/docs/v1/IOS_INSTALLATION/1.7_Set_Capabilities_Background_Modes.png b/docs/v1/imgs/1.7_Set_Capabilities_Background_Modes.png similarity index 100% rename from docs/v1/IOS_INSTALLATION/1.7_Set_Capabilities_Background_Modes.png rename to docs/v1/imgs/1.7_Set_Capabilities_Background_Modes.png diff --git a/docs/v1/IOS_INSTALLATION/1.8.1_Set_info_plist.png b/docs/v1/imgs/1.8.1_Set_info_plist.png similarity index 100% rename from docs/v1/IOS_INSTALLATION/1.8.1_Set_info_plist.png rename to docs/v1/imgs/1.8.1_Set_info_plist.png diff --git a/docs/v1/IOS_INSTALLATION/1.8.2_Set_camera_and_microphone.png b/docs/v1/imgs/1.8.2_Set_camera_and_microphone.png similarity index 100% rename from docs/v1/IOS_INSTALLATION/1.8.2_Set_camera_and_microphone.png rename to docs/v1/imgs/1.8.2_Set_camera_and_microphone.png diff --git a/docs/v1/android.md b/docs/v1/installation.android.md similarity index 93% rename from docs/v1/android.md rename to docs/v1/installation.android.md index a0142e7a7..1a444a288 100644 --- a/docs/v1/android.md +++ b/docs/v1/installation.android.md @@ -1,4 +1,4 @@ -# Android Installation +# Android Installation v1 # Prerequisites * Android SDK @@ -15,4 +15,4 @@ # Obfuscation Code Edit `android/proguard-rules.pro` ```java -keep class io.agora.**{*;} -``` \ No newline at end of file +``` diff --git a/docs/v1/android.zh.md b/docs/v1/installation.android.zh.md similarity index 93% rename from docs/v1/android.zh.md rename to docs/v1/installation.android.zh.md index 3d149960e..5c5d5e75e 100644 --- a/docs/v1/android.zh.md +++ b/docs/v1/installation.android.zh.md @@ -1,4 +1,4 @@ -# Android 开发搭建指南 +# Android 开发搭建指南 v1 # 环境准备 * Android SDK @@ -15,4 +15,4 @@ # 当您在写混淆代码时,请在``添加以下代码: ```script -keep class io.agora.**{*;} -``` \ No newline at end of file +``` diff --git a/docs/v1/ios.md b/docs/v1/installation.ios.md similarity index 71% rename from docs/v1/ios.md rename to docs/v1/installation.ios.md index 104e36e96..543430085 100644 --- a/docs/v1/ios.md +++ b/docs/v1/installation.ios.md @@ -1,4 +1,4 @@ -# iOS Installation +# iOS Installation v1 # Prerequisites * You should installed and linked `react-native-agora` @@ -6,10 +6,10 @@ # Step 1. Open Project in Xcode Open `ios/projectName.xcodeproj` with XCode -![Step 1](./IOS_INSTALLATION/1.1_Open_iOS_ProjectFile.png) +![Step 1](imgs/1.1_Open_iOS_ProjectFile.png) # Step 2. Add Link Binary With Libraries Build Phases -> Link Binary With Libraries -> + -![Step 2](./IOS_INSTALLATION/1.2_LinkBinaryWithLibraries.png) +![Step 2](imgs/1.2_LinkBinaryWithLibraries.png) libresolv.tbd libc++.tbd @@ -23,7 +23,7 @@ Build Phases -> Link Binary With Libraries -> + # Step 3. Add Other Link Binary With Libraries From `node_modules` Build Phases -> Link Binary With Libraries -> + -> Add Other -![Step 3](./IOS_INSTALLATION/1.3_Add_Other_Libraries.png) +![Step 3](imgs/1.3_Add_Other_Libraries.png) node_modules/react-native-agora/ios/RCTAgora/libs/libcrypto.a node_modules/react-native-agora/ios/RCTAgora/libs/AgoraRtcCryptoLoader.framework @@ -32,33 +32,33 @@ Build Phases -> Link Binary With Libraries -> + -> Add Other # Step 4. Add Framework Search Paths Build Settings -> Framework Search Paths -> + -![Step 4](./IOS_INSTALLATION/1.4_Add_Framework_Search_Paths.png) +![Step 4](imgs/1.4_Add_Framework_Search_Paths.png) "$(SRCROOT)/../node_modules/react-native-agora/ios/RCTAgora/libs" # Step 5. Add Library Search Paths Build Settings -> Library Search Paths -> + -![Step 5](./IOS_INSTALLATION/1.5_Add_Library_Search_Paths.png) +![Step 5](imgs/1.5_Add_Library_Search_Paths.png) "$(SRCROOT)/../node_modules/react-native-agora/ios/RCTAgora/libs" # Step 6. Set Build Settings Enable Bitcode No Build Settings -> Enable Bitcode -> ... -![Step 6](./IOS_INSTALLATION/1.6_Set_Build_Settings_Enable_Bitcode_No.png) +![Step 6](imgs/1.6_Set_Build_Settings_Enable_Bitcode_No.png) # Step 7. Set Capabilities Background Modes Capabilities -> Background Modes -> Audio, Airplay, and Picture in Picture -![Step 7](./IOS_INSTALLATION/1.7_Set_Capabilities_Background_Modes.png) +![Step 7](imgs/1.7_Set_Capabilities_Background_Modes.png) # Step 8.1 Set info.plist Change info.plist "Privacy - Camera Usage Description":"use camera to start video call" "Privacy - Microphone Usage Description":"use microphone to start video call" -![Step 8.1](./IOS_INSTALLATION/1.8.1_Set_info_plist.png) +![Step 8.1](imgs/1.8.1_Set_info_plist.png) -![Step 8.2](./IOS_INSTALLATION/1.8.2_Set_camera_and_microphone.png) +![Step 8.2](imgs/1.8.2_Set_camera_and_microphone.png) # Step 9 build -`react-native run-ios` \ No newline at end of file +`react-native run-ios` diff --git a/docs/v1/ios.zh.md b/docs/v1/installation.ios.zh.md similarity index 73% rename from docs/v1/ios.zh.md rename to docs/v1/installation.ios.zh.md index 445229491..ebe24c7d8 100644 --- a/docs/v1/ios.zh.md +++ b/docs/v1/installation.ios.zh.md @@ -1,4 +1,4 @@ -# iOS 开发搭建指南 +# iOS 开发搭建指南 v1 # 环境 * 请先在项目里安装 `react-native-agora` & `react-native link react-native-agora` @@ -6,10 +6,10 @@ # Step 1. 使用Xcode打开ios项目 用Xcode打开RN项目里的`ios/RN项目.xcodeproj`文件 -![Step 1](./IOS_INSTALLATION/1.1_Open_iOS_ProjectFile.png) +![Step 1](imgs/1.1_Open_iOS_ProjectFile.png) # Step 2. 添加如下的链接库到Xcode工程 选择 Build Phases -> Link Binary With Libraries -> + -![Step 2](./IOS_INSTALLATION/1.2_LinkBinaryWithLibraries.png) +![Step 2](imgs/1.2_LinkBinaryWithLibraries.png) libresolv.tbd libc++.tbd @@ -21,7 +21,7 @@ CoreTelephony.framework # Step 3. 添加node_modules库到Xcode工程 选择 Build Phases-> Link Binary With Libaries中点击“+”按钮,在弹出的窗口中点击“Add Other”按钮,选择 -![Step 3](./IOS_INSTALLATION/1.3_Add_Other_Libraries.png) +![Step 3](imgs/1.3_Add_Other_Libraries.png) node_modules/react-native-agora/ios/RCTAgora/libs/libcrypto.a node_modules/react-native-agora/ios/RCTAgora/libs/AgoraRtcCryptoLoader.framework @@ -30,21 +30,21 @@ # Step 4. 添加Framework Search Paths 选择 Build Settings->Search Paths->Framework Search Paths添加 "$(SRCROOT)/../node_modules/react-native-agora/ios/RCTAgora/libs" -![Step 4](./IOS_INSTALLATION/1.4_Add_Framework_Search_Paths.png) +![Step 4](imgs/1.4_Add_Framework_Search_Paths.png) # Step 5. 添加Library Search Paths 选择 Build Settings->Search Paths->Library Search Paths添加 "$(SRCROOT)/../node_modules/react-native-agora/ios/RCTAgora/libs" -![Step 5](./IOS_INSTALLATION/1.5_Add_Library_Search_Paths.png) +![Step 5](imgs/1.5_Add_Library_Search_Paths.png) # Step 6. 设置Build Settings Enable Bitcode No 选择 Build Settings->Enable Bitcode设置为No -![Step 6](./IOS_INSTALLATION/1.6_Set_Build_Settings_Enable_Bitcode_No.png) +![Step 6](imgs/1.6_Set_Build_Settings_Enable_Bitcode_No.png) # Step 7. 设置Capabilities Background Modes 选择 Capabilities->Background Modes->Modes勾选Audio,AirPlay,and Picture In Picture -![Step 7](./IOS_INSTALLATION/1.7_Set_Capabilities_Background_Modes.png) +![Step 7](imgs/1.7_Set_Capabilities_Background_Modes.png) # Step 8.1 设置info.plist 修改info.plist @@ -52,9 +52,9 @@ "Privacy - Camera Usage Description":"use camera to start video call" "Privacy - Microphone Usage Description":"use microphone to start video call" -![Step 8.1](./IOS_INSTALLATION/1.8.1_Set_info_plist.png) +![Step 8.1](imgs/1.8.1_Set_info_plist.png) -![Step 8.2](./IOS_INSTALLATION/1.8.2_Set_camera_and_microphone.png) +![Step 8.2](imgs/1.8.2_Set_camera_and_microphone.png) # Step 9 编译 -`react-native run-ios` \ No newline at end of file +`react-native run-ios` diff --git a/docs/v2/README.md b/docs/v2/README.md new file mode 100644 index 000000000..7f12d057e --- /dev/null +++ b/docs/v2/README.md @@ -0,0 +1,60 @@ +##### 有任何问题欢迎加入QQ群进行反馈 471757030 + +## [for 1.x old version](../v1/README.md) + +# react-native-agora +[![npm](https://img.shields.io/npm/v/react-native-agora.svg)](https://www.npmjs.com/package/react-native-agora) +[![npm](https://img.shields.io/npm/dm/react-native-agora.svg)](https://www.npmjs.com/package/react-native-agora) +[![npm](https://img.shields.io/npm/dt/react-native-agora.svg)](https://www.npmjs.com/package/react-native-agora) +[![npm](https://img.shields.io/npm/l/react-native-agora.svg)](https://github.com/syanbo/react-native-agora/blob/master/LICENSE) +[![join chat](https://img.shields.io/badge/gitter-join%20chat-brightgreen.svg)](https://gitter.im/react-native-agora/community) + +## Description + +The react-native-agora is an open-source wrapper for react-native developers. This SDK takes advantage of React Native and Agora RTC Video SDKs on Android/iOS. + +## Compatibility + * `>= react native 0.59.9` + * `iOS SDK 8.0+` + * `Android 5.0+ x86 arm64 armv7a` + +## [quick start](https://github.com/AgoraIO-Community/Agora-RN-Quickstart) + +## Installation + +Install with npm: + + `npm i react-native-agora --save` + +Or, install with yarn: + + `yarn add react-native-agora` + +Either way, then link with: + + `react-native link react-native-agora` + +### iOS Installation + [中文](installation.ios.zh.md) + [English](installation.ios.md) + +### Android Installation + [中文](installation.android.zh.md) + [English](installation.android.md) + +## Agora Native API Documentation + +### Android + [中文](https://docs.agora.io/cn/Video/API%20Reference/java/index.html) + [English](https://docs.agora.io/en/Video/API%20Reference/java/index.html) + +## iOS + [中文](https://docs.agora.io/cn/Video/API%20Reference/oc/docs/headers/Agora-Objective-C-API-Overview.html) + [English](https://docs.agora.io/en/Video/API%20Reference/oc/docs/headers/Agora-Objective-C-API-Overview.html) + +## [API DOCS](https://syanbo.github.io/react-native-agora/globals.html) + +## Resources +* Complete [API documentation](https://docs.agora.io/en/) at the Developer Center +* [File bugs about this sample](https://github.com/syanbo/react-native-agora/issues) +* [React Native Getting Started](https://facebook.github.io/react-native/docs/getting-started.html) diff --git a/docs/v2/IOS_INSTALLATION/05.png b/docs/v2/imgs/05.png similarity index 100% rename from docs/v2/IOS_INSTALLATION/05.png rename to docs/v2/imgs/05.png diff --git a/docs/v2/IOS_INSTALLATION/05a.png b/docs/v2/imgs/05a.png similarity index 100% rename from docs/v2/IOS_INSTALLATION/05a.png rename to docs/v2/imgs/05a.png diff --git a/docs/v2/IOS_INSTALLATION/05b.png b/docs/v2/imgs/05b.png similarity index 100% rename from docs/v2/IOS_INSTALLATION/05b.png rename to docs/v2/imgs/05b.png diff --git a/docs/v2/IOS_INSTALLATION/05c.png b/docs/v2/imgs/05c.png similarity index 100% rename from docs/v2/IOS_INSTALLATION/05c.png rename to docs/v2/imgs/05c.png diff --git a/docs/v2/IOS_INSTALLATION/06.png b/docs/v2/imgs/06.png similarity index 100% rename from docs/v2/IOS_INSTALLATION/06.png rename to docs/v2/imgs/06.png diff --git a/docs/v2/IOS_INSTALLATION/07.png b/docs/v2/imgs/07.png similarity index 100% rename from docs/v2/IOS_INSTALLATION/07.png rename to docs/v2/imgs/07.png diff --git a/docs/v2/IOS_INSTALLATION/08a.png b/docs/v2/imgs/08a.png similarity index 100% rename from docs/v2/IOS_INSTALLATION/08a.png rename to docs/v2/imgs/08a.png diff --git a/docs/v2/IOS_INSTALLATION/08b.png b/docs/v2/imgs/08b.png similarity index 100% rename from docs/v2/IOS_INSTALLATION/08b.png rename to docs/v2/imgs/08b.png diff --git a/docs/v2/IOS_INSTALLATION/08c.png b/docs/v2/imgs/08c.png similarity index 100% rename from docs/v2/IOS_INSTALLATION/08c.png rename to docs/v2/imgs/08c.png diff --git a/docs/v2/IOS_INSTALLATION/1.2_OpenProject.png b/docs/v2/imgs/1.2_OpenProject.png similarity index 100% rename from docs/v2/IOS_INSTALLATION/1.2_OpenProject.png rename to docs/v2/imgs/1.2_OpenProject.png diff --git a/docs/v2/IOS_INSTALLATION/1.3.1_RCTAgora.png b/docs/v2/imgs/1.3.1_RCTAgora.png similarity index 100% rename from docs/v2/IOS_INSTALLATION/1.3.1_RCTAgora.png rename to docs/v2/imgs/1.3.1_RCTAgora.png diff --git a/docs/v2/IOS_INSTALLATION/1.3.3_UPDATE_RCTAgora_AgoraRtcEngineKit_Framework.png b/docs/v2/imgs/1.3.3_UPDATE_RCTAgora_AgoraRtcEngineKit_Framework.png similarity index 100% rename from docs/v2/IOS_INSTALLATION/1.3.3_UPDATE_RCTAgora_AgoraRtcEngineKit_Framework.png rename to docs/v2/imgs/1.3.3_UPDATE_RCTAgora_AgoraRtcEngineKit_Framework.png diff --git a/docs/v2/IOS_INSTALLATION/1.3.4_SELECT_AgoraRtcEngineKit_from_iOS_Pods_folder.png b/docs/v2/imgs/1.3.4_SELECT_AgoraRtcEngineKit_from_iOS_Pods_folder.png similarity index 100% rename from docs/v2/IOS_INSTALLATION/1.3.4_SELECT_AgoraRtcEngineKit_from_iOS_Pods_folder.png rename to docs/v2/imgs/1.3.4_SELECT_AgoraRtcEngineKit_from_iOS_Pods_folder.png diff --git a/docs/v2/IOS_INSTALLATION/1.3.5_DRAG_IT_INTO_Link_Binary_With_Libraries.png b/docs/v2/imgs/1.3.5_DRAG_IT_INTO_Link_Binary_With_Libraries.png similarity index 100% rename from docs/v2/IOS_INSTALLATION/1.3.5_DRAG_IT_INTO_Link_Binary_With_Libraries.png rename to docs/v2/imgs/1.3.5_DRAG_IT_INTO_Link_Binary_With_Libraries.png diff --git a/docs/v2/IOS_INSTALLATION/1.3_Add_Files_To_Project.png b/docs/v2/imgs/1.3_Add_Files_To_Project.png similarity index 100% rename from docs/v2/IOS_INSTALLATION/1.3_Add_Files_To_Project.png rename to docs/v2/imgs/1.3_Add_Files_To_Project.png diff --git a/docs/v2/IOS_INSTALLATION/1.4.1_SET_RCTAgora.a.png b/docs/v2/imgs/1.4.1_SET_RCTAgora.a.png similarity index 100% rename from docs/v2/IOS_INSTALLATION/1.4.1_SET_RCTAgora.a.png rename to docs/v2/imgs/1.4.1_SET_RCTAgora.a.png diff --git a/docs/v2/IOS_INSTALLATION/10a.png b/docs/v2/imgs/10a.png similarity index 100% rename from docs/v2/IOS_INSTALLATION/10a.png rename to docs/v2/imgs/10a.png diff --git a/docs/v2/IOS_INSTALLATION/10b.png b/docs/v2/imgs/10b.png similarity index 100% rename from docs/v2/IOS_INSTALLATION/10b.png rename to docs/v2/imgs/10b.png diff --git a/docs/v2/IOS_INSTALLATION/9a.png b/docs/v2/imgs/9a.png similarity index 100% rename from docs/v2/IOS_INSTALLATION/9a.png rename to docs/v2/imgs/9a.png diff --git a/docs/v2/IOS_INSTALLATION/9b.png b/docs/v2/imgs/9b.png similarity index 100% rename from docs/v2/IOS_INSTALLATION/9b.png rename to docs/v2/imgs/9b.png diff --git a/docs/v2/IOS_INSTALLATION/9c.png b/docs/v2/imgs/9c.png similarity index 100% rename from docs/v2/IOS_INSTALLATION/9c.png rename to docs/v2/imgs/9c.png diff --git a/docs/v2/IOS_INSTALLATION/9d.png b/docs/v2/imgs/9d.png similarity index 100% rename from docs/v2/IOS_INSTALLATION/9d.png rename to docs/v2/imgs/9d.png diff --git a/docs/v2/IOS_INSTALLATION/9e.png b/docs/v2/imgs/9e.png similarity index 100% rename from docs/v2/IOS_INSTALLATION/9e.png rename to docs/v2/imgs/9e.png diff --git a/docs/v2/IOS_INSTALLATION/t01.png b/docs/v2/imgs/t01.png similarity index 100% rename from docs/v2/IOS_INSTALLATION/t01.png rename to docs/v2/imgs/t01.png diff --git a/docs/v2/IOS_INSTALLATION/t02.png b/docs/v2/imgs/t02.png similarity index 100% rename from docs/v2/IOS_INSTALLATION/t02.png rename to docs/v2/imgs/t02.png diff --git a/docs/v2/IOS_INSTALLATION/t03.png b/docs/v2/imgs/t03.png similarity index 100% rename from docs/v2/IOS_INSTALLATION/t03.png rename to docs/v2/imgs/t03.png diff --git a/docs/v2/IOS_INSTALLATION/t04.png b/docs/v2/imgs/t04.png similarity index 100% rename from docs/v2/IOS_INSTALLATION/t04.png rename to docs/v2/imgs/t04.png diff --git a/docs/v2/IOS_INSTALLATION/t05.png b/docs/v2/imgs/t05.png similarity index 100% rename from docs/v2/IOS_INSTALLATION/t05.png rename to docs/v2/imgs/t05.png diff --git a/docs/v2/android.md b/docs/v2/installation.android.md similarity index 97% rename from docs/v2/android.md rename to docs/v2/installation.android.md index 4b2667bdb..32e3d80e5 100644 --- a/docs/v2/android.md +++ b/docs/v2/installation.android.md @@ -1,4 +1,4 @@ -# Android Installation +# Android Installation v2 # Prerequisites * Android SDK @@ -44,4 +44,4 @@ curl "localhost:8081/index.bundle?platform=android&dev=false&minify=true" -o "an cd android ./gradlew assembleRelease -``` \ No newline at end of file +``` diff --git a/docs/v2/android.zh.md b/docs/v2/installation.android.zh.md similarity index 97% rename from docs/v2/android.zh.md rename to docs/v2/installation.android.zh.md index 5b55b7522..279bcc002 100644 --- a/docs/v2/android.zh.md +++ b/docs/v2/installation.android.zh.md @@ -1,4 +1,4 @@ -# Android 开发搭建指南 +# Android 开发搭建指南 v2 # Prerequisites * Android SDK @@ -43,4 +43,4 @@ curl "localhost:8081/index.bundle?platform=android&dev=false&minify=true" -o "an cd android ./gradlew assembleRelease -``` \ No newline at end of file +``` diff --git a/docs/v2/ios.md b/docs/v2/installation.ios.md similarity index 81% rename from docs/v2/ios.md rename to docs/v2/installation.ios.md index 6ebd97b69..08f6004bc 100644 --- a/docs/v2/ios.md +++ b/docs/v2/installation.ios.md @@ -1,4 +1,5 @@ -# React native Agora iOS Installation +# React native Agora iOS Installation v2 + #### Minimum compatibility * >= React native 0.55.x * iOS SDK 8.0+ @@ -49,14 +50,14 @@ and then we need to install the pods $ pod install ``` if you get a error from CocoaPods saying something like this : -![Step 5](./IOS_INSTALLATION/05.png) +![Step 5](imgs/05.png) then you need to open up your `Podfile` and remove the part that is blue marked in the picture below #### *before* -![Step 5](./IOS_INSTALLATION/05a.png) +![Step 5](imgs/05a.png) #### *after* -![Step 5](./IOS_INSTALLATION/05b.png) +![Step 5](imgs/05b.png) we need to add this code at the bottom to our `Podfile` ```sh @@ -79,68 +80,68 @@ post_install do |installer| end ``` This is how your podfile should look like -![Step 5](./IOS_INSTALLATION/05c.png) +![Step 5](imgs/05c.png) after that you can run this command again ```sh $ pod install ``` #### 6. Open up your Xcode project *[project name].xcworkspace* inside in ios folder -![Step 6](./IOS_INSTALLATION/06.png) +![Step 6](imgs/06.png) #### 7. expand your project folder and right click on the *"Libraries"* folder and choose *"add files to [project name]"* -![Step 7](./IOS_INSTALLATION/07.png) +![Step 7](imgs/07.png) #### 8. follow the image below to find the RCTAgora lib -![Step 8](./IOS_INSTALLATION/08a.png) +![Step 8](imgs/08a.png) the path is node_modules => react-native-agora => ios => RCTAgora.xcodeproj make sure you check so that those are checked -![Step 8](./IOS_INSTALLATION/08b.png) +![Step 8](imgs/08b.png) If the file is greyed out it means you already have it inside of you library folder. Check so that RCTAgora.xcodeproj are inside of your "Libraries" folder -![Step 8](./IOS_INSTALLATION/08c.png) +![Step 8](imgs/08c.png) #### 9. we need to add the framework expand your "Frameworks" folder and you should see the "AgoraRtcEngineKit.framework" are red. -![Step 9](./IOS_INSTALLATION/9a.png) +![Step 9](imgs/9a.png) right click and delete that Left click on your "RCTAgora.xcodeproj" and click on "Build Phases" -![Step 9](./IOS_INSTALLATION/9b.png) +![Step 9](imgs/9b.png) left click on the "AgoraRtcEngineKit.framework" in the list and click on the "-"(minus sign) to remove it from the list. -![Step 9](./IOS_INSTALLATION/9c.png) +![Step 9](imgs/9c.png) then click on the "+"(plus sign) so that we can add the framework. Click on the "Add other..." button -![Step 9](./IOS_INSTALLATION/9d.png) +![Step 9](imgs/9d.png) then we need to navigate and find our framwork -![Step 9](./IOS_INSTALLATION/9e.png) +![Step 9](imgs/9e.png) the path is : ios => Pods => AgoraRtcEngine_iOS => AgoraRtcEngineKit.framework and click on "add" #### 10. at last we need to link the library click on your project on the left and then click on "Build Phases" and then expand "Link Binary With Libraries" and then click on the "+"(plus sign) -![Step 10](./IOS_INSTALLATION/10a.png) +![Step 10](imgs/10a.png) Search for libRCTAgora and click on add -![Step 10](./IOS_INSTALLATION/10b.png) +![Step 10](imgs/10b.png) if you cant find it in your list check so that you dont already have it ---------------------------------------------- ### Troubleshooting if you get some errors like the pictures below -![Step t1](./IOS_INSTALLATION/t01.png) -![Step t2](./IOS_INSTALLATION/t02.png) +![Step t1](imgs/t01.png) +![Step t2](imgs/t02.png) the chances are that you have some framework that already have imported time.h something like firestore. Expand your "Libraries" and then click on "RCTAgora.xcodeproj". Then click on "Build settings" and search for "Header search paths" -![Step t3](./IOS_INSTALLATION/t03.png) +![Step t3](imgs/t03.png) Doubble click on the path -![Step t4](./IOS_INSTALLATION/t04.png) +![Step t4](imgs/t04.png) and change the Pods path from "recursive" to non-recursive -![Step t5](./IOS_INSTALLATION/t05.png) +![Step t5](imgs/t05.png) diff --git a/docs/v2/ios.zh.md b/docs/v2/installation.ios.zh.md similarity index 82% rename from docs/v2/ios.zh.md rename to docs/v2/installation.ios.zh.md index d223fb5a0..8c99a71ec 100644 --- a/docs/v2/ios.zh.md +++ b/docs/v2/installation.ios.zh.md @@ -1,4 +1,5 @@ -# iOS 开发搭建指南 +# iOS 开发搭建指南 v2 + #### 最低兼容 * >= React Native 0.55.x * iOS SDK 8.0+ @@ -46,14 +47,14 @@ $ pod init $ pod install ``` 当你在安装pod过程中,遇到问题如下的报错时: -![Step 5](./IOS_INSTALLATION/05.png) +![Step 5](imgs/05.png) 你需要打开`Podfile`并且如下图所示的蓝色部分。 #### *选中这部分* -![Step 5](./IOS_INSTALLATION/05a.png) +![Step 5](imgs/05a.png) #### *删除后* -![Step 5](./IOS_INSTALLATION/05b.png) +![Step 5](imgs/05b.png) 在`Podfile`底部加入以下代码: ```sh @@ -76,66 +77,66 @@ post_install do |installer| end ``` 这是最终修改好的`Podfile`,如图所示。 -![Step 5](./IOS_INSTALLATION/05c.png) +![Step 5](imgs/05c.png) 之后你就可以执行安装命令: ``` $ pod install ``` #### 6. 在你项目的ios目录里,打开Xcode工程文件 *[项目名].xcworkspace -![Step 6](./IOS_INSTALLATION/06.png) +![Step 6](imgs/06.png) #### 7. 展开你的项目目录,并且右键点击*"Libraries"* 目录并且选择*"add file to [project name]"* -![Step 7](./IOS_INSTALLATION/07.png) +![Step 7](imgs/07.png) #### 8. 按照下图去找到RCTAgora lib -![Step 8](./IOS_INSTALLATION/08a.png) +![Step 8](imgs/08a.png) 你可以沿路径找到:node_modules => react-native-agora => ios => RCTAgora.xcodeproj 请按照如图所示的方式确认你已经配好编译环境 -![Step 8](./IOS_INSTALLATION/08b.png) +![Step 8](imgs/08b.png) 如果下图所示的文件是灰色的,请确保它的路径是在你的目录里的。 请检查`RCTAgora.xcodeproj`是否在`Libraries`目录中。 -![Step 8](./IOS_INSTALLATION/08c.png) +![Step 8](imgs/08c.png) #### 9. 检查你的Framework是否已经成功设置 展开你的 "Frameworks" 目录,如果看到红色的 "AgoraRtcEngineKit.framework",你需要按照以下步骤重新把它载入到编译环境。 -![Step 9](./IOS_INSTALLATION/9a.png) +![Step 9](imgs/9a.png) 单击右键并删除。 单击左键 "RCTAgora.xcodeproj" 找到并点击 "Build Phases" -![Step 9](./IOS_INSTALLATION/9b.png) +![Step 9](imgs/9b.png) 在列表里找到 "AgoraRtcEngineKit.framework" 单击左键 找到 "-"(减号按钮) 把它从列表里删除。 -![Step 9](./IOS_INSTALLATION/9c.png) +![Step 9](imgs/9c.png) 然后点击"+"(加号按钮) 点击"Add other..."按钮。 -![Step 9](./IOS_INSTALLATION/9d.png) +![Step 9](imgs/9d.png) 按照图下方式,找到"AgoraRtcEngineKit.framework" -![Step 9](./IOS_INSTALLATION/9e.png) +![Step 9](imgs/9e.png) 你可以沿路径找到: ios => Pods => AgoraRtcEngine_iOS => AgoraRtcEngineKit.framework 并且点击 "add" #### 10. 最后我们需要连接Library 点击你的项目左侧,并且点击"Build Phases"然后展开"Link Binary With Libraries"接着点击"+"(加号按钮) click on your project on the left and then click on "Build Phases" and then expand "Link Binary With Libraries" and then click on the "+"(plug sign) -![Step 10](./IOS_INSTALLATION/10a.png) +![Step 10](imgs/10a.png) 找到 libRCTAgora 并且点击"add" -![Step 10](./IOS_INSTALLATION/10b.png) +![Step 10](imgs/10b.png) 如果你无法在列表里找到它,表明你还没安装它。 ---------------------------------------------- ### 常见故障排除 如果你遇到类似的报错: -![Step t1](./IOS_INSTALLATION/t01.png) -![Step t2](./IOS_INSTALLATION/t02.png) +![Step t1](imgs/t01.png) +![Step t2](imgs/t02.png) 可能是因为你有一些框架已经导入了相同的头文件,例如firestore库也会引入time.h, 展开你项目里的"Libraries" 并且点击"RCTAgora.xcodeproj"。然后点击"Build settings" 并且找到"Header search paths",按照以下方法设置。 -![Step t3](./IOS_INSTALLATION/t03.png) +![Step t3](imgs/t03.png) 双击当前选中的路径 -![Step t4](./IOS_INSTALLATION/t04.png) +![Step t4](imgs/t04.png) 把路径里的"recursive"修改成"non-recursive" -![Step t5](./IOS_INSTALLATION/t05.png) +![Step t5](imgs/t05.png) diff --git a/docs/v3/installation.android.md b/docs/v3/installation.android.md new file mode 100644 index 000000000..aa2dd9022 --- /dev/null +++ b/docs/v3/installation.android.md @@ -0,0 +1,104 @@ +# Android Installation v3 + +## Prerequisites + +* Android SDK 28+ +* Android Studio +* Kotlin + +## Step 1. Migrating to AndroidX. + +We use Kotlin and AndroidX in the native module. + +Android Studio -> Refactor -> Migrate to AndroidX... -> Migrate + +[Google Official Doc](https://developer.android.com/jetpack/androidx/migrate) + +## Step 2. Link the library. + +### Automatic + +Use `react-native link` to add the library to your project: + +```shell script +react-native link react-native-agora +``` + +### Manual + +Define the `react-native-agora` project in `android/settings.gradle`: + +```groovy +... +include ':react-native-agora' +project(':react-native-agora').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-agora/android') +``` + +Add the `react-native-agora` as a dependency of your app in `android/app/build.gradle`: + +```groovy +... +dependencies { + ... + implementation project(':react-native-agora') +} +``` + +Add `import io.agora.rtc.react.RCTAgoraRtcPackage;` and `new RCTAgoraRtcPackage()` in your `MainApplication.java`: + +```java +import io.agora.rtc.react.RCTAgoraRtcPackage; +... + @Override + protected List getPackages() { + return Arrays.asList( + new MainReactPackage(), + new RCTAgoraRtcPackage() + ); + } +``` + +## Step 3. Add ext Config. (**recommended**) + +If you've defined *[project-wide properties](https://developer.android.com/studio/build/gradle-tips.html)* in your root `build.gradle`, this library will detect the presence of the following properties: + +```groovy +buildscript {...} +allprojects {...} + +/** + * Project-wide Gradle configuration properties + */ +ext { + compileSdkVersion = 28 + buildToolsVersion = "28.0.3" + minSdkVersion = 16 + targetSdkVersion = 28 + kotlin_version = "1.3.72" +} +``` +or do +```groovy +buildscript { + ext { + compileSdkVersion = 28 + buildToolsVersion = "28.0.3" + minSdkVersion = 16 + targetSdkVersion = 28 + kotlin_version = "1.3.72" + } +} +... +``` + +## Step 4. Add Network Security Config. + +Add `android:networkSecurityConfig` to your manifest file (`android/app/src/main/AndroidManifest.xml`): + +```xml + +... + +``` + +[Google Official Doc](https://developer.android.com/training/articles/security-config) diff --git a/docs/v3/installation.ios.md b/docs/v3/installation.ios.md new file mode 100644 index 000000000..bcf64fe1c --- /dev/null +++ b/docs/v3/installation.ios.md @@ -0,0 +1,110 @@ +# iOS Installation v3 + +## Prerequisites + +* iOS SDK 9.0+ +* Xcode +* Swift + +## Step 1. Migrating to Swift. + +We use Swift in the native module. + +You should **create a swift file by Xcode** to make your project support swift. + +[Apple Official Doc](https://developer.apple.com/documentation/swift/migrating_your_objective-c_code_to_swift) + +## Step 2. Link the library. + +### Using without CocoaPods. + +Use `react-native link` to add the library to your project: + +```shell script +react-native link react-native-agora +cd node_modules/react-native-agora +sh ./install.sh +``` + +Embedding the frameworks because they are dynamic libraries. The framework's path at: + +```shell script +node_modules/react-native-agora/ios/RCTAgora/Libs/*.framework +``` + +[Apple Official Doc](https://developer.apple.com/library/archive/technotes/tn2435/_index.html#//apple_ref/doc/uid/DTS40017543-CH1-EMBED_IN_APP_SECTION) + +### Using with CocoaPods. (**recommended**) + +Install CocoaPods. + +[CocoaPods Official Doc](https://guides.cocoapods.org/using/getting-started.html) + +```shell script +cd ios +pod init +``` + +Setup your `Podfile` (found at `ios/Podfile` as below, replacing all references to `_YOUR_PROJECT_TARGET_` with your project target (it's the same as project name by default). + +[CocoaPods Official Doc](https://guides.cocoapods.org/using/using-cocoapods.html) + +```ruby +# Uncomment the next line to define a global platform for your project +# platform :ios, '9.0' + +target '_YOUR_PROJECT_TARGET_' do + # Comment the next line if you don't want to use dynamic frameworks + + # https://reactnative.dev/docs/0.59/integration-with-existing-apps#configuring-cocoapods-dependencies + # Your 'node_modules' directory is probably in the root of your project, + # but if not, adjust the `:path` accordingly + pod 'React', :path => '../node_modules/react-native', :subspecs => [ + 'Core', + 'CxxBridge', # Include this for RN >= 0.47 + 'DevSupport', # Include this to enable In-App Devmenu if RN >= 0.43 + 'RCTText', + 'RCTNetwork', + 'RCTWebSocket', # needed for debugging + # Add any other subspecs you want to use in your project + 'RCTActionSheet', + 'RCTAnimation', + 'RCTBlob', + 'RCTCameraRoll', + 'RCTGeolocation', + 'RCTImage', + 'RCTPushNotification', + 'RCTSettings', + 'RCTVibration', + 'RCTLinkingIOS', + ], :modular_headers => true + # Explicitly include Yoga if you are using RN >= 0.42.0 + pod "yoga", :path => "../node_modules/react-native/ReactCommon/yoga", :modular_headers => true + + # Third party deps podspec link + pod 'DoubleConversion', :podspec => '../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec', :modular_headers => false + pod 'glog', :podspec => '../node_modules/react-native/third-party-podspecs/glog.podspec', :modular_headers => false + pod 'Folly', :podspec => '../node_modules/react-native/third-party-podspecs/Folly.podspec', :modular_headers => false + + # Pods for _YOUR_PROJECT_TARGET_ +end + +``` + +Use `react-native link` to add the library to your project: + +```shell script +react-native link react-native-agora +``` + +Then run in the `ios` folder: + +```shell script +pod install +``` + +Open the produced workspace file (`.xcworkspace`) in XCode to build your project. + +## Step 3. App store submission. + +The app's `Info.plist` file must contain `Privacy - Microphone Usage Description` and `Privacy - Camera Usage Description` with a user-facing purpose string explaining clearly and completely why your app needs the permission, otherwise Apple will reject your app submission. diff --git a/install.sh b/install.sh new file mode 100644 index 000000000..a2bde9705 --- /dev/null +++ b/install.sh @@ -0,0 +1,35 @@ +zipName="AgoraRtcSDK" +temp="/var/tmp" +libs="ios/RCTAgora/Libs" + +mkdir -p $temp + +version=$(grep "AgoraRtcEngine_iOS_Crypto" react-native-agora.podspec | grep -o '\d.\d.\d' | sed 's/\./_/g') +echo $zipName "$version" + +if [ ! -f $temp/$zipName"$version".zip ]; then + echo "the zip file not exists, start downloading..." + curl -o $temp/$zipName"$version".zip "https://download.agora.io/sdk/release/Agora_Native_SDK_for_iOS_v${version}_FULL.zip" +fi + +echo "start unzip SDK..." +unzip -o -q $temp/$zipName"$version".zip "**/*_Dynamic.zip" -d $temp/$zipName"$version" +if [ $? -ne 0 ]; then + echo "unzip SDK failed, retry..." + unzip -o -q $temp/$zipName"$version".zip "**/ALL_ARCHITECTURE/*" -d $temp/$zipName"$version" +else + echo "unzip SDK success, start unzip dynamic framework..." + for zip in $(find $temp/$zipName"$version" -maxdepth 5 -iname '*_Dynamic.zip'); do + unzip -o -q "$zip" "**/ALL_ARCHITECTURE/*" -d $temp/$zipName"$version" + done +fi + +echo "start transfer dynamic framework to $libs..." +rm -rf $libs +mkdir -p $libs + +for framework in $(find $temp/$zipName"$version" -maxdepth 5 -iname '*.framework'); do + mv -f "$framework" $libs +done + +echo "install finished" diff --git a/ios/RCTAgora.xcodeproj/project.pbxproj b/ios/RCTAgora.xcodeproj/project.pbxproj index 91adb75a4..c99c1b460 100644 --- a/ios/RCTAgora.xcodeproj/project.pbxproj +++ b/ios/RCTAgora.xcodeproj/project.pbxproj @@ -7,38 +7,64 @@ objects = { /* Begin PBXBuildFile section */ - 08B28CF72211239F00E57CEB /* AgoraRtcEngineKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 08B28CF62211239F00E57CEB /* AgoraRtcEngineKit.framework */; }; - 23AF28211EEFECD800D771AB /* RCTAgora.m in Sources */ = {isa = PBXBuildFile; fileRef = 23AF28201EEFECD800D771AB /* RCTAgora.m */; }; - 23AF28221EEFECD800D771AB /* RCTAgora.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 23AF281F1EEFECD800D771AB /* RCTAgora.h */; }; - 23C20DD11F0A6ED80095F60C /* AgoraConst.m in Sources */ = {isa = PBXBuildFile; fileRef = 23C20DCC1F0A6ED80095F60C /* AgoraConst.m */; }; - 23C20DD21F0A6ED80095F60C /* RCTAgoraVideoView.m in Sources */ = {isa = PBXBuildFile; fileRef = 23C20DCE1F0A6ED80095F60C /* RCTAgoraVideoView.m */; }; - 23C20DD31F0A6ED80095F60C /* RCTAgoraViewManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 23C20DD01F0A6ED80095F60C /* RCTAgoraViewManager.m */; }; + 1A45C83BB272B3DBD0CDD4F5 /* RtcChannel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1A45C4ECABE114F83C0B3FFA /* RtcChannel.swift */; }; + 1A45C8C8FA7B421E2B2EDBAE /* RtcEngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1A45C12DB8F4B671C19B2C2F /* RtcEngine.swift */; }; + F52A357C243F33060059123E /* Callback.swift in Sources */ = {isa = PBXBuildFile; fileRef = F52A357B243F33060059123E /* Callback.swift */; }; + F52A357E244060460059123E /* Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = F52A357D244060460059123E /* Extensions.swift */; }; + F52A3580244066090059123E /* MediaObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = F52A357F244066090059123E /* MediaObserver.swift */; }; + F532DED724445E0400715966 /* BeanCovertor.swift in Sources */ = {isa = PBXBuildFile; fileRef = F532DED624445E0400715966 /* BeanCovertor.swift */; }; + F532E03D2446FB6D00715966 /* RtcSurfaceView.swift in Sources */ = {isa = PBXBuildFile; fileRef = F532E03C2446FB6D00715966 /* RtcSurfaceView.swift */; }; + F562CBE22487CA3B006DDED8 /* AgoraRtcCryptoLoader.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F562CBE02487CA3B006DDED8 /* AgoraRtcCryptoLoader.framework */; }; + F562CBE32487CA3C006DDED8 /* AgoraRtcKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F562CBE12487CA3B006DDED8 /* AgoraRtcKit.framework */; }; + F562CBE42487CA4A006DDED8 /* AgoraRtcCryptoLoader.framework in CopyFiles */ = {isa = PBXBuildFile; fileRef = F562CBE02487CA3B006DDED8 /* AgoraRtcCryptoLoader.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; + F562CBE52487CA4A006DDED8 /* AgoraRtcKit.framework in CopyFiles */ = {isa = PBXBuildFile; fileRef = F562CBE12487CA3B006DDED8 /* AgoraRtcKit.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; + F5B39EB72493D19100853FEF /* RtcChannelEvent.swift in Sources */ = {isa = PBXBuildFile; fileRef = F5B39EB52493D19100853FEF /* RtcChannelEvent.swift */; }; + F5B39EB82493D19100853FEF /* RtcEngineEvent.swift in Sources */ = {isa = PBXBuildFile; fileRef = F5B39EB62493D19100853FEF /* RtcEngineEvent.swift */; }; + F5C34DF4245042E500C6ED53 /* RCTAgoraRtcChannelModule.swift in Sources */ = {isa = PBXBuildFile; fileRef = F5C34DEC245042E500C6ED53 /* RCTAgoraRtcChannelModule.swift */; }; + F5C34DF5245042E500C6ED53 /* PromiseCallback.swift in Sources */ = {isa = PBXBuildFile; fileRef = F5C34DEE245042E500C6ED53 /* PromiseCallback.swift */; }; + F5C34DF6245042E500C6ED53 /* RCTAgoraRtcEngineModule.swift in Sources */ = {isa = PBXBuildFile; fileRef = F5C34DEF245042E500C6ED53 /* RCTAgoraRtcEngineModule.swift */; }; + F5C34DF7245042E500C6ED53 /* RCTAgoraRtcSurfaceViewManagerBridge.m in Sources */ = {isa = PBXBuildFile; fileRef = F5C34DF0245042E500C6ED53 /* RCTAgoraRtcSurfaceViewManagerBridge.m */; }; + F5C34DF8245042E500C6ED53 /* RCTAgoraRtcChannelModuleBridge.m in Sources */ = {isa = PBXBuildFile; fileRef = F5C34DF1245042E500C6ED53 /* RCTAgoraRtcChannelModuleBridge.m */; }; + F5C34DF9245042E500C6ED53 /* RCTAgoraRtcEngineModuleBridge.m in Sources */ = {isa = PBXBuildFile; fileRef = F5C34DF2245042E500C6ED53 /* RCTAgoraRtcEngineModuleBridge.m */; }; + F5C34DFA245042E500C6ED53 /* RCTAgoraRtcSurfaceViewManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = F5C34DF3245042E500C6ED53 /* RCTAgoraRtcSurfaceViewManager.swift */; }; /* End PBXBuildFile section */ /* Begin PBXCopyFilesBuildPhase section */ 23AF281A1EEFECD800D771AB /* CopyFiles */ = { isa = PBXCopyFilesBuildPhase; buildActionMask = 2147483647; - dstPath = "include/$(PRODUCT_NAME)"; - dstSubfolderSpec = 16; + dstPath = ""; + dstSubfolderSpec = 10; files = ( - 23AF28221EEFECD800D771AB /* RCTAgora.h in CopyFiles */, + F562CBE42487CA4A006DDED8 /* AgoraRtcCryptoLoader.framework in CopyFiles */, + F562CBE52487CA4A006DDED8 /* AgoraRtcKit.framework in CopyFiles */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ - 08B28CF62211239F00E57CEB /* AgoraRtcEngineKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AgoraRtcEngineKit.framework; path = ../samples/simpleDemo/ios/Pods/AgoraRtcEngine_iOS/AgoraRtcEngineKit.framework; sourceTree = ""; }; + 1A45C12DB8F4B671C19B2C2F /* RtcEngine.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RtcEngine.swift; sourceTree = ""; }; + 1A45C4ECABE114F83C0B3FFA /* RtcChannel.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RtcChannel.swift; sourceTree = ""; }; 23AF281C1EEFECD800D771AB /* libRCTAgora.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libRCTAgora.a; sourceTree = BUILT_PRODUCTS_DIR; }; - 23AF281F1EEFECD800D771AB /* RCTAgora.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = RCTAgora.h; sourceTree = ""; }; - 23AF28201EEFECD800D771AB /* RCTAgora.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = RCTAgora.m; sourceTree = ""; }; - 23C20DCB1F0A6ED80095F60C /* AgoraConst.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AgoraConst.h; sourceTree = ""; }; - 23C20DCC1F0A6ED80095F60C /* AgoraConst.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AgoraConst.m; sourceTree = ""; }; - 23C20DCD1F0A6ED80095F60C /* RCTAgoraVideoView.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RCTAgoraVideoView.h; sourceTree = ""; }; - 23C20DCE1F0A6ED80095F60C /* RCTAgoraVideoView.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = RCTAgoraVideoView.m; sourceTree = ""; }; - 23C20DCF1F0A6ED80095F60C /* RCTAgoraViewManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RCTAgoraViewManager.h; sourceTree = ""; }; - 23C20DD01F0A6ED80095F60C /* RCTAgoraViewManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = RCTAgoraViewManager.m; sourceTree = ""; }; + F52A357B243F33060059123E /* Callback.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Callback.swift; sourceTree = ""; }; + F52A357D244060460059123E /* Extensions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Extensions.swift; sourceTree = ""; }; + F52A357F244066090059123E /* MediaObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MediaObserver.swift; sourceTree = ""; }; + F532DED624445E0400715966 /* BeanCovertor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BeanCovertor.swift; sourceTree = ""; }; + F532E03C2446FB6D00715966 /* RtcSurfaceView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RtcSurfaceView.swift; sourceTree = ""; }; + F562CBE02487CA3B006DDED8 /* AgoraRtcCryptoLoader.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; path = AgoraRtcCryptoLoader.framework; sourceTree = ""; }; + F562CBE12487CA3B006DDED8 /* AgoraRtcKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; path = AgoraRtcKit.framework; sourceTree = ""; }; + F5B39EB52493D19100853FEF /* RtcChannelEvent.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RtcChannelEvent.swift; sourceTree = ""; }; + F5B39EB62493D19100853FEF /* RtcEngineEvent.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RtcEngineEvent.swift; sourceTree = ""; }; + F5C34DEC245042E500C6ED53 /* RCTAgoraRtcChannelModule.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RCTAgoraRtcChannelModule.swift; sourceTree = ""; }; + F5C34DED245042E500C6ED53 /* RCTAgora-bridging-header.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "RCTAgora-bridging-header.h"; sourceTree = ""; }; + F5C34DEE245042E500C6ED53 /* PromiseCallback.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PromiseCallback.swift; sourceTree = ""; }; + F5C34DEF245042E500C6ED53 /* RCTAgoraRtcEngineModule.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RCTAgoraRtcEngineModule.swift; sourceTree = ""; }; + F5C34DF0245042E500C6ED53 /* RCTAgoraRtcSurfaceViewManagerBridge.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = RCTAgoraRtcSurfaceViewManagerBridge.m; sourceTree = ""; }; + F5C34DF1245042E500C6ED53 /* RCTAgoraRtcChannelModuleBridge.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = RCTAgoraRtcChannelModuleBridge.m; sourceTree = ""; }; + F5C34DF2245042E500C6ED53 /* RCTAgoraRtcEngineModuleBridge.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = RCTAgoraRtcEngineModuleBridge.m; sourceTree = ""; }; + F5C34DF3245042E500C6ED53 /* RCTAgoraRtcSurfaceViewManager.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RCTAgoraRtcSurfaceViewManager.swift; sourceTree = ""; }; + F5C34DFB24505ADD00C6ED53 /* AgoraRtcEngineKit.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AgoraRtcEngineKit.h; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -46,7 +72,8 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 08B28CF72211239F00E57CEB /* AgoraRtcEngineKit.framework in Frameworks */, + F562CBE32487CA3C006DDED8 /* AgoraRtcKit.framework in Frameworks */, + F562CBE22487CA3B006DDED8 /* AgoraRtcCryptoLoader.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -56,11 +83,25 @@ 08B28CF52211239F00E57CEB /* Frameworks */ = { isa = PBXGroup; children = ( - 08B28CF62211239F00E57CEB /* AgoraRtcEngineKit.framework */, ); name = Frameworks; sourceTree = ""; }; + 1A45C5B4F6A3DDAC155D26E5 /* React */ = { + isa = PBXGroup; + children = ( + F5C34DEE245042E500C6ED53 /* PromiseCallback.swift */, + F5C34DED245042E500C6ED53 /* RCTAgora-bridging-header.h */, + F5C34DEC245042E500C6ED53 /* RCTAgoraRtcChannelModule.swift */, + F5C34DF1245042E500C6ED53 /* RCTAgoraRtcChannelModuleBridge.m */, + F5C34DEF245042E500C6ED53 /* RCTAgoraRtcEngineModule.swift */, + F5C34DF2245042E500C6ED53 /* RCTAgoraRtcEngineModuleBridge.m */, + F5C34DF3245042E500C6ED53 /* RCTAgoraRtcSurfaceViewManager.swift */, + F5C34DF0245042E500C6ED53 /* RCTAgoraRtcSurfaceViewManagerBridge.m */, + ); + path = React; + sourceTree = ""; + }; 23AF28131EEFECD800D771AB = { isa = PBXGroup; children = ( @@ -81,18 +122,39 @@ 23AF281E1EEFECD800D771AB /* RCTAgora */ = { isa = PBXGroup; children = ( - 23C20DCB1F0A6ED80095F60C /* AgoraConst.h */, - 23C20DCC1F0A6ED80095F60C /* AgoraConst.m */, - 23C20DCD1F0A6ED80095F60C /* RCTAgoraVideoView.h */, - 23C20DCE1F0A6ED80095F60C /* RCTAgoraVideoView.m */, - 23C20DCF1F0A6ED80095F60C /* RCTAgoraViewManager.h */, - 23C20DD01F0A6ED80095F60C /* RCTAgoraViewManager.m */, - 23AF281F1EEFECD800D771AB /* RCTAgora.h */, - 23AF28201EEFECD800D771AB /* RCTAgora.m */, + F562CBDF2487CA3B006DDED8 /* Libs */, + F52A3574243EFBB40059123E /* Base */, + 1A45C5B4F6A3DDAC155D26E5 /* React */, ); path = RCTAgora; sourceTree = ""; }; + F52A3574243EFBB40059123E /* Base */ = { + isa = PBXGroup; + children = ( + F532DED624445E0400715966 /* BeanCovertor.swift */, + F52A357B243F33060059123E /* Callback.swift */, + F52A357D244060460059123E /* Extensions.swift */, + F52A357F244066090059123E /* MediaObserver.swift */, + 1A45C4ECABE114F83C0B3FFA /* RtcChannel.swift */, + F5B39EB52493D19100853FEF /* RtcChannelEvent.swift */, + 1A45C12DB8F4B671C19B2C2F /* RtcEngine.swift */, + F5B39EB62493D19100853FEF /* RtcEngineEvent.swift */, + F532E03C2446FB6D00715966 /* RtcSurfaceView.swift */, + F5C34DFB24505ADD00C6ED53 /* AgoraRtcEngineKit.h */, + ); + path = Base; + sourceTree = ""; + }; + F562CBDF2487CA3B006DDED8 /* Libs */ = { + isa = PBXGroup; + children = ( + F562CBE02487CA3B006DDED8 /* AgoraRtcCryptoLoader.framework */, + F562CBE12487CA3B006DDED8 /* AgoraRtcKit.framework */, + ); + path = Libs; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -125,6 +187,7 @@ 23AF281B1EEFECD800D771AB = { CreatedOnToolsVersion = 8.3.2; DevelopmentTeam = 342K4Q49RK; + LastSwiftMigration = 1140; ProvisioningStyle = Automatic; }; }; @@ -152,10 +215,22 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - 23C20DD21F0A6ED80095F60C /* RCTAgoraVideoView.m in Sources */, - 23C20DD31F0A6ED80095F60C /* RCTAgoraViewManager.m in Sources */, - 23C20DD11F0A6ED80095F60C /* AgoraConst.m in Sources */, - 23AF28211EEFECD800D771AB /* RCTAgora.m in Sources */, + F5B39EB82493D19100853FEF /* RtcEngineEvent.swift in Sources */, + F5C34DF6245042E500C6ED53 /* RCTAgoraRtcEngineModule.swift in Sources */, + F5C34DFA245042E500C6ED53 /* RCTAgoraRtcSurfaceViewManager.swift in Sources */, + F5C34DF5245042E500C6ED53 /* PromiseCallback.swift in Sources */, + F5C34DF8245042E500C6ED53 /* RCTAgoraRtcChannelModuleBridge.m in Sources */, + F52A357C243F33060059123E /* Callback.swift in Sources */, + F5C34DF7245042E500C6ED53 /* RCTAgoraRtcSurfaceViewManagerBridge.m in Sources */, + F5B39EB72493D19100853FEF /* RtcChannelEvent.swift in Sources */, + F5C34DF9245042E500C6ED53 /* RCTAgoraRtcEngineModuleBridge.m in Sources */, + F5C34DF4245042E500C6ED53 /* RCTAgoraRtcChannelModule.swift in Sources */, + F532E03D2446FB6D00715966 /* RtcSurfaceView.swift in Sources */, + F52A3580244066090059123E /* MediaObserver.swift in Sources */, + F52A357E244060460059123E /* Extensions.swift in Sources */, + F532DED724445E0400715966 /* BeanCovertor.swift in Sources */, + 1A45C83BB272B3DBD0CDD4F5 /* RtcChannel.swift in Sources */, + 1A45C8C8FA7B421E2B2EDBAE /* RtcEngine.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -273,56 +348,53 @@ 23AF28261EEFECD800D771AB /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { + CLANG_ENABLE_MODULES = YES; DEVELOPMENT_TEAM = 342K4Q49RK; ENABLE_BITCODE = YES; FRAMEWORK_SEARCH_PATHS = ( "$(inherited)", - "$(SRCROOT)/../../../ios/Pods/**", - "$(PROJECT_DIR)/RCTAgora/libs/**", + "$(PROJECT_DIR)/RCTAgora/Libs", ); HEADER_SEARCH_PATHS = ( "$(inherited)", - "\"$(SRCROOT)/../../react-native/React\"/**", - "\"$(SRCROOT)/../../react-native/Libraries\"/**", - "$(SRCROOT)/../../../ios/Pods/**", - ); - LIBRARY_SEARCH_PATHS = ( - "$(inherited)", - "$(PROJECT_DIR)", + "$(SRCROOT)/../../react-native/React/**", + "$(SRCROOT)/../../react-native/Libraries/**", "$(SRCROOT)/../../../ios/Pods/**", - "$(PROJECT_DIR)/RCTAgora/libs/**", ); + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LIBRARY_SEARCH_PATHS = "$(inherited)"; OTHER_LDFLAGS = "-ObjC"; PRODUCT_NAME = "$(TARGET_NAME)"; SKIP_INSTALL = YES; + SWIFT_OBJC_BRIDGING_HEADER = "RCTAgora/React/RCTAgora-Bridging-Header.h"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; }; name = Debug; }; 23AF28271EEFECD800D771AB /* Release */ = { isa = XCBuildConfiguration; buildSettings = { + CLANG_ENABLE_MODULES = YES; DEVELOPMENT_TEAM = 342K4Q49RK; ENABLE_BITCODE = YES; FRAMEWORK_SEARCH_PATHS = ( "$(inherited)", - "$(SRCROOT)/../../../ios/Pods/**", - "$(PROJECT_DIR)/RCTAgora/libs/**", + "$(PROJECT_DIR)/RCTAgora/Libs", ); HEADER_SEARCH_PATHS = ( "$(inherited)", - "\"$(SRCROOT)/../../react-native/React\"/**", - "\"$(SRCROOT)/../../react-native/Libraries\"/**", - "$(SRCROOT)/../../../ios/Pods/**", - ); - LIBRARY_SEARCH_PATHS = ( - "$(inherited)", - "$(PROJECT_DIR)", + "$(SRCROOT)/../../react-native/React/**", + "$(SRCROOT)/../../react-native/Libraries/**", "$(SRCROOT)/../../../ios/Pods/**", - "$(PROJECT_DIR)/RCTAgora/libs/**", ); + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LIBRARY_SEARCH_PATHS = "$(inherited)"; OTHER_LDFLAGS = "-ObjC"; PRODUCT_NAME = "$(TARGET_NAME)"; SKIP_INSTALL = YES; + SWIFT_OBJC_BRIDGING_HEADER = "RCTAgora/React/RCTAgora-Bridging-Header.h"; + SWIFT_VERSION = 5.0; }; name = Release; }; diff --git a/ios/RCTAgora.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/ios/RCTAgora.xcodeproj/project.xcworkspace/contents.xcworkspacedata deleted file mode 100644 index bdda2f4ce..000000000 --- a/ios/RCTAgora.xcodeproj/project.xcworkspace/contents.xcworkspacedata +++ /dev/null @@ -1,7 +0,0 @@ - - - - - diff --git a/ios/RCTAgora.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/ios/RCTAgora.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist deleted file mode 100644 index 18d981003..000000000 --- a/ios/RCTAgora.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist +++ /dev/null @@ -1,8 +0,0 @@ - - - - - IDEDidComputeMac32BitWarning - - - diff --git a/ios/RCTAgora.xcodeproj/project.xcworkspace/xcuserdata/DB.xcuserdatad/UserInterfaceState.xcuserstate b/ios/RCTAgora.xcodeproj/project.xcworkspace/xcuserdata/DB.xcuserdatad/UserInterfaceState.xcuserstate deleted file mode 100644 index 31adb7604..000000000 Binary files a/ios/RCTAgora.xcodeproj/project.xcworkspace/xcuserdata/DB.xcuserdatad/UserInterfaceState.xcuserstate and /dev/null differ diff --git a/ios/RCTAgora.xcodeproj/xcuserdata/DB.xcuserdatad/xcschemes/RCTAgora.xcscheme b/ios/RCTAgora.xcodeproj/xcuserdata/DB.xcuserdatad/xcschemes/RCTAgora.xcscheme deleted file mode 100644 index 0965e55f5..000000000 --- a/ios/RCTAgora.xcodeproj/xcuserdata/DB.xcuserdatad/xcschemes/RCTAgora.xcscheme +++ /dev/null @@ -1,80 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/ios/RCTAgora.xcodeproj/xcuserdata/DB.xcuserdatad/xcschemes/xcschememanagement.plist b/ios/RCTAgora.xcodeproj/xcuserdata/DB.xcuserdatad/xcschemes/xcschememanagement.plist deleted file mode 100644 index 619f673f2..000000000 --- a/ios/RCTAgora.xcodeproj/xcuserdata/DB.xcuserdatad/xcschemes/xcschememanagement.plist +++ /dev/null @@ -1,22 +0,0 @@ - - - - - SchemeUserState - - RCTAgora.xcscheme - - orderHint - 0 - - - SuppressBuildableAutocreation - - 23AF281B1EEFECD800D771AB - - primary - - - - - diff --git a/ios/RCTAgora/AgoraConst.h b/ios/RCTAgora/AgoraConst.h deleted file mode 100644 index d0855c32e..000000000 --- a/ios/RCTAgora/AgoraConst.h +++ /dev/null @@ -1,203 +0,0 @@ -// -// MyAgoraRtcEngineKit.h -// RCTAgora -// -// Created by 邓博 on 2017/6/30. -// Copyright © 2017年 Syan. All rights reserved. -// - -#import - -typedef NS_ENUM(NSUInteger, AgoraRtcQualityReportFormat) { - AgoraRtc_QualityReportFormat_Json = 0, - AgoraRtc_QualityReportFormat_Html = 1, -}; - -typedef NS_ENUM(NSUInteger, AgoraRtcAppType) { - AgoraRtc_APP_TYPE_NATIVE = 0, - AgoraRtc_APP_TYPE_COCOS = 1, - AgoraRtc_APP_TYPE_UNITY = 2, - AgoraRtc_APP_TYPE_ELECTRON = 3, - AgoraRtc_APP_TYPE_FLUTTER = 4, - AgoraRtc_APP_TYPE_UNREAL = 5, - AgoraRtc_APP_TYPE_XAMARIN = 6, - AgoraRtc_APP_TYPE_APICLOUD = 7, - AgoraRtc_APP_TYPE_REACTNATIVE = 8 -}; - - -@protocol AgoraRtcEngineExtensionDelegate -@optional -- (void)rtcEngine:(AgoraRtcEngineKit * _Nonnull)engine audioTransportQualityOfUid:(NSUInteger)uid delay:(NSUInteger)delay lost:(NSUInteger)lost; -- (void)rtcEngine:(AgoraRtcEngineKit * _Nonnull)engine videoTransportQualityOfUid:(NSUInteger)uid delay:(NSUInteger)delay lost:(NSUInteger)lost; -@end - - -@interface AgoraRtcEngineKit (AgoraExtension) - -+ (instancetype _Nonnull)sharedEngineWithAppId:(NSString * _Nonnull)appId - extensionDelegate:(id _Nullable)delegate; - -/** Sets the profile to control the RTC engine. - * - * @param profile SDK profile in JSON format. - * @param merge Whether to merge the profile data with the original value. - */ -- (int)setProfile:(NSString * _Nonnull)profile - merge:(BOOL)merge; - -/** Set wrapper frame type by language wrapper. - * - * @param appType wrapper frame type. - */ -- (int)setAppType:(AgoraRtcAppType)appType; - -/** END OF COMMON METHODS */ - -/** BEGIN OF AUDIO METHODS */ - - -/** - * Enable recap - * - * @param interval ≤ 0: Disabled, > 0: Interval in ms. - */ -- (int)enableRecap:(NSInteger)interval; - -/** - * Start playing recap conversation - * - */ -- (int)playRecap; - -- (int)enableAudioQualityIndication:(BOOL)enabled; -- (int)enableTransportQualityIndication:(BOOL)enabled; - -- (int)setVideoProfileEx:(NSInteger)width - andHeight:(NSInteger)height - andFrameRate:(NSInteger)frameRate - andBitrate:(NSInteger)andBitrate; - -- (int)sendReportData:(NSData * _Nonnull)data - type:(NSInteger)type; -/** END OF AUDIO METHODS */ - -/** Queries internal states - * @param parameters - * json string, array type - * @return a json string - */ -- (NSString * _Nullable)getParameters:(NSString * _Nonnull)parameters; - -/** - * Generates a URL linking to the call quality reports. @param channel The channel name specified in the joinChannel method. - * @param listenerUid The uid of the listener. - * @param speakerUid The uid of the speaker. - * @param reportFormat The format of the report. - AgoraRtc_QualityReportFormat_Json (0): JSON.: Returns the quality report data in Json. - AgoraRtc_QualityReportFormat_Html (1): HTML.: Returns a report in HTML format, displayed on a web browser or WebVIEW components. - * - * @return 0 when executed successfully. return minus value when failed. return AgoraRtc_Error_Invalid_Argument (-2):Invalid argument. return AgoraRtc_Error_Buffer_Too_Small (-6):The buffer length is too small. - */ -- (NSString * _Nullable)makeQualityReportUrl:(NSString * _Nonnull) channel - listenerUid:(NSUInteger)listenerUid - speakerrUid:(NSUInteger)speakerUid - reportFormat:(AgoraRtcQualityReportFormat)reportFormat; - -/********************************************************* - * Large group conference call (experiment) - END - *********************************************************/ -@end - -static NSString *AG_PREFIX = @"ag_rtc"; - -static NSString *RCTAgoraErrorDomain = @"RCTAgoraErrorDomain"; - -static NSString *AGWarning = @"warning"; -static NSString *AGError = @"error"; -static NSString *AGApiCallExecute = @"apiCallExecute"; -static NSString *AGJoinChannelSuccess = @"joinChannelSuccess"; -static NSString *AGRejoinChannelSuccess = @"rejoinChannelSuccess"; -static NSString *AGLeaveChannel = @"leaveChannel"; -static NSString *AGClientRoleChanged = @"clientRoleChanged"; -static NSString *AGLocalUserRegistered = @"localUserRegistered"; -static NSString *AGUserInfoUpdated = @"userInfoUpdated"; -static NSString *AGUserJoined = @"userJoined"; -static NSString *AGUserOffline = @"userOffline"; -static NSString *AGConnectionStateChanged = @"connectionStateChanged"; -static NSString *AGConnectionLost = @"connectionLost"; -static NSString *AGTokenPrivilegeWillExpire = @"tokenPrivilegeWillExpire"; -static NSString *AGRequestToken = @"requestToken"; - -static NSString *AGLocalAudioStateChanged = @"localAudioStateChanged"; -static NSString *AGRemoteAudioStateChanged = @"remoteAudioStateChanged"; -static NSString *AGLocalAudioStats = @"localAudioStats"; -static NSString *AGAudioVolumeIndication = @"audioVolumeIndication"; -static NSString *AGActiveSpeaker = @"activeSpeaker"; -static NSString *AGFirstLocalAudioFrame = @"firstLocalAudioFrame"; -static NSString *AGFirstRemoteAudioFrame = @"firstRemoteAudioFrame"; -static NSString *AGFirstRemoteAudioDecoded = @"firstRemoteAudioDecoded"; -static NSString *AGFirstLocalVideoFrame = @"firstLocalVideoFrame"; -static NSString *AGFirstRemoteVideoFrame = @"firstRemoteVideoFrame"; -static NSString *AGUserMuteAudio = @"userMuteAudio"; -static NSString *AGVideoSizeChanged = @"videoSizeChanged"; -static NSString *AGRemoteVideoStateChanged = @"remoteVideoStateChanged"; -static NSString *AGLocalPublishFallbackToAudioOnly = @"localPublishFallbackToAudioOnly"; -static NSString *AGRemoteSubscribeFallbackToAudioOnly = @"remoteSubscribeFallbackToAudioOnly"; - -static NSString *AGAudioRouteChanged = @"audioRouteChanged"; -static NSString *AGCameraFocusAreaChanged = @"cameraFocusAreaChanged"; -static NSString *AGCameraExposureAreaChanged = @"cameraExposureAreaChanged"; - -static NSString *AGRtcStats = @"rtcStats"; -static NSString *AGLastmileQuality = @"lastmileQuality"; -static NSString *AGNetworkQuality = @"networkQuality"; -static NSString *AGLocalVideoStats = @"localVideoStats"; -static NSString *AGRemoteVideoStats = @"remoteVideoStats"; -static NSString *AGRemoteAudioStats = @"remoteAudioStats"; - -static NSString *AGRemoteAudioMixingStart = @"remoteAudioMixingStart"; -static NSString *AGRemoteAudioMixingFinish = @"remoteAudioMixingFinish"; -static NSString *AGAudioEffectFinish = @"audioEffectFinish"; - -static NSString *AGStreamPublished = @"streamPublished"; -static NSString *AGStreamUnpublish = @"streamUnpublish"; -static NSString *AGTranscodingUpdate = @"transcodingUpdate"; - -static NSString *AGStreamInjectedStatus = @"streamInjectedStatus"; - -static NSString *AGReceiveStreamMessage = @"receiveStreamMessage"; -static NSString *AGOccurStreamMessageError = @"occurStreamMessageError"; - -static NSString *AGReceivedChannelMediaRelay = @"receivedChannelMediaRelay"; -static NSString *AGMediaRelayStateChanged = @"mediaRelayStateChanged"; - -static NSString *AGMediaEngineLoaded = @"mediaEngineLoaded"; -static NSString *AGMediaEngineStartCall = @"mediaEngineStartCall"; - -static NSString *AGIntervalTest = @"startEchoTestWithInterval"; -static NSString *AGAudioMixingStateChanged = @"audioMixingStateChanged"; -static NSString *AGLastmileProbeTestResult = @"lastmileProbeTestResult"; - -static NSString *AGRtmpStreamingStateChanged = @"rtmpStreamingStateChanged"; -static NSString *AGLocalVideoChanged = @"localVideoChanged"; -static NSString *AGNetworkTypeChanged = @"networkTypeChanged"; -static NSString *AGMediaMetaDataReceived = @"mediaMetaDataReceived"; - -typedef NS_ENUM(NSInteger, AgoraModeType) { - AgoraAudioMode, - AgoraVideoMode -}; - -@interface AgoraConst : NSObject - -@property (nonatomic, copy) NSString *appid; - -@property (nonatomic, assign) NSInteger localUid; - -@property (strong, nonatomic) AgoraRtcEngineKit *rtcEngine; - -+ (instancetype)share; - -+ (NSArray *) supportEvents; -@end diff --git a/ios/RCTAgora/AgoraConst.m b/ios/RCTAgora/AgoraConst.m deleted file mode 100644 index 82bbbad76..000000000 --- a/ios/RCTAgora/AgoraConst.m +++ /dev/null @@ -1,112 +0,0 @@ -// -// MyAgoraRtcEngineKit.m -// RCTAgora -// -// Created by 邓博 on 2017/6/30. -// Copyright © 2017年 Syan. All rights reserved. -// - -#import "AgoraConst.h" - -@implementation AgoraConst - -static AgoraConst *_person; -+ (instancetype)allocWithZone:(struct _NSZone *)zone{ - static dispatch_once_t predicate; - dispatch_once(&predicate, ^{ - _person = [super allocWithZone:zone]; - }); - return _person; -} - -+ (instancetype)share { - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - _person = [[self alloc]init]; - }); - return _person; -} - -+ (NSArray*) supportEvents { - NSArray* array = @[AGWarning, - AGError, - AGApiCallExecute, - AGJoinChannelSuccess, - AGRejoinChannelSuccess, - AGLeaveChannel, - AGClientRoleChanged, - AGLocalUserRegistered, - AGUserInfoUpdated, - AGUserJoined, - AGUserOffline, - AGConnectionStateChanged, - AGConnectionLost, - AGTokenPrivilegeWillExpire, - AGRequestToken, - - AGAudioVolumeIndication, - AGActiveSpeaker, - AGFirstLocalAudioFrame, - AGFirstRemoteAudioFrame, - AGFirstRemoteAudioDecoded, - AGFirstLocalVideoFrame, - AGFirstRemoteVideoFrame, - AGUserMuteAudio, - AGVideoSizeChanged, - AGRemoteVideoStateChanged, - AGLocalPublishFallbackToAudioOnly, - AGRemoteSubscribeFallbackToAudioOnly, - - AGAudioRouteChanged, - AGCameraFocusAreaChanged, - AGCameraExposureAreaChanged, - - AGRtcStats, - AGLastmileQuality, - AGNetworkQuality, - AGLocalVideoStats, - AGRemoteVideoStats, - AGRemoteAudioStats, - AGLocalAudioStateChanged, - AGRemoteAudioStateChanged, - AGLocalAudioStats, - AGMediaRelayStateChanged, - AGReceivedChannelMediaRelay, - - AGAudioMixingStateChanged, - AGRemoteAudioMixingStart, - AGRemoteAudioMixingFinish, - AGAudioEffectFinish, - - AGStreamPublished, - AGStreamUnpublish, - AGTranscodingUpdate, - - AGStreamInjectedStatus, - - AGReceiveStreamMessage, - AGOccurStreamMessageError, - - AGMediaEngineLoaded, - AGMediaEngineStartCall, - AGIntervalTest, - AGLastmileProbeTestResult, - AGRtmpStreamingStateChanged, - AGLocalVideoChanged, - AGNetworkTypeChanged, - AGFirstRemoteAudioFrame, - AGMediaMetaDataReceived]; - - NSMutableArray *eventList = [NSMutableArray arrayWithCapacity:[array count]]; - [array enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { - id mapObj = [NSString stringWithFormat:@"%@%@", AG_PREFIX, obj]; - [eventList addObject:mapObj]; - }]; - return eventList; -} - -- (id)copyWithZone:(NSZone *)zone { - return _person; -} - -@end diff --git a/ios/RCTAgora/Base/AgoraRtcEngineKit.h b/ios/RCTAgora/Base/AgoraRtcEngineKit.h new file mode 100644 index 000000000..7af94d48b --- /dev/null +++ b/ios/RCTAgora/Base/AgoraRtcEngineKit.h @@ -0,0 +1,108 @@ +// +// AgoraRtcEngineKit.h +// RCTAgora +// +// Created by LXH on 2020/4/22. +// Copyright © 2020 Syan. All rights reserved. +// + +#import + +typedef NS_ENUM(NSUInteger, AgoraRtcQualityReportFormat) { + AgoraRtc_QualityReportFormat_Json = 0, + AgoraRtc_QualityReportFormat_Html = 1, +}; + +typedef NS_ENUM(NSUInteger, AgoraRtcAppType) { + AgoraRtc_APP_TYPE_NATIVE = 0, + AgoraRtc_APP_TYPE_COCOS = 1, + AgoraRtc_APP_TYPE_UNITY = 2, + AgoraRtc_APP_TYPE_ELECTRON = 3, + AgoraRtc_APP_TYPE_FLUTTER = 4, + AgoraRtc_APP_TYPE_UNREAL = 5, + AgoraRtc_APP_TYPE_XAMARIN = 6, + AgoraRtc_APP_TYPE_APICLOUD = 7, + AgoraRtc_APP_TYPE_REACTNATIVE = 8 +}; + +@protocol AgoraRtcEngineExtensionDelegate +@optional +- (void)rtcEngine:(AgoraRtcEngineKit * _Nonnull)engine audioTransportQualityOfUid:(NSUInteger)uid delay:(NSUInteger)delay lost:(NSUInteger)lost; +- (void)rtcEngine:(AgoraRtcEngineKit * _Nonnull)engine videoTransportQualityOfUid:(NSUInteger)uid delay:(NSUInteger)delay lost:(NSUInteger)lost; +@end + +@interface AgoraRtcEngineKit (AgoraExtension) + ++ (instancetype _Nonnull)sharedEngineWithAppId:(NSString * _Nonnull)appId + extensionDelegate:(id _Nullable)delegate; + +/** Sets the profile to control the RTC engine. + * + * @param profile SDK profile in JSON format. + * @param merge Whether to merge the profile data with the original value. + */ +- (int)setProfile:(NSString * _Nonnull)profile + merge:(BOOL)merge; + +/** Set wrapper frame type by language wrapper. + * + * @param appType wrapper frame type. + */ +- (int)setAppType:(AgoraRtcAppType)appType; + +/** END OF COMMON METHODS */ + +/** BEGIN OF AUDIO METHODS */ + + +/** + * Enable recap + * + * @param interval ≤ 0: Disabled, > 0: Interval in ms. + */ +- (int)enableRecap:(NSInteger)interval; + +/** + * Start playing recap conversation + * + */ +- (int)playRecap; + +- (int)enableAudioQualityIndication:(BOOL)enabled; +- (int)enableTransportQualityIndication:(BOOL)enabled; + +- (int)setVideoProfileEx:(NSInteger)width + andHeight:(NSInteger)height + andFrameRate:(NSInteger)frameRate + andBitrate:(NSInteger)andBitrate; + +- (int)sendReportData:(NSData * _Nonnull)data + type:(NSInteger)type; +/** END OF AUDIO METHODS */ + +/** Queries internal states + * @param parameters + * json string, array type + * @return a json string + */ +- (NSString * _Nullable)getParameters:(NSString * _Nonnull)parameters; + +/** + * Generates a URL linking to the call quality reports. @param channel The channel name specified in the joinChannel method. + * @param listenerUid The uid of the listener. + * @param speakerUid The uid of the speaker. + * @param reportFormat The format of the report. + AgoraRtc_QualityReportFormat_Json (0): JSON.: Returns the quality report data in Json. + AgoraRtc_QualityReportFormat_Html (1): HTML.: Returns a report in HTML format, displayed on a web browser or WebVIEW components. + * + * @return 0 when executed successfully. return minus value when failed. return AgoraRtc_Error_Invalid_Argument (-2):Invalid argument. return AgoraRtc_Error_Buffer_Too_Small (-6):The buffer length is too small. + */ +- (NSString * _Nullable)makeQualityReportUrl:(NSString * _Nonnull) channel + listenerUid:(NSUInteger)listenerUid + speakerrUid:(NSUInteger)speakerUid + reportFormat:(AgoraRtcQualityReportFormat)reportFormat; + +/********************************************************* + * Large group conference call (experiment) - END + *********************************************************/ +@end diff --git a/ios/RCTAgora/Base/BeanCovertor.swift b/ios/RCTAgora/Base/BeanCovertor.swift new file mode 100644 index 000000000..07f0ab278 --- /dev/null +++ b/ios/RCTAgora/Base/BeanCovertor.swift @@ -0,0 +1,294 @@ +// +// BeanCovertor.swift +// RCTAgora +// +// Created by LXH on 2020/4/9. +// Copyright © 2020 Syan. All rights reserved. +// + +import Foundation +import AgoraRtcKit + +func mapToPoint(_ map: Dictionary) -> CGPoint { + var point = CGPoint() + if let x = map["x"] as? Int { + point.x = CGFloat(x) + } + if let y = map["y"] as? Int { + point.y = CGFloat(y) + } + return point +} + +func mapToSize(_ map: Dictionary) -> CGSize { + var size = CGSize() + if let width = map["width"] as? Int { + size.width = CGFloat(width) + } + if let height = map["height"] as? Int { + size.height = CGFloat(height) + } + return size +} + +func mapToRect(_ map: Dictionary) -> CGRect { + CGRect( + origin: mapToPoint(map), + size: mapToSize(map) + ) +} + +func mapToVideoEncoderConfiguration(_ map: Dictionary) -> AgoraVideoEncoderConfiguration { + let config = AgoraVideoEncoderConfiguration() + if let dimensions = map["dimensions"] as? Dictionary { + config.dimensions = mapToSize(dimensions) + } + if let frameRate = map["frameRate"] as? Int { + config.frameRate = frameRate + } + if let minFrameRate = map["minFrameRate"] as? Int { + config.minFrameRate = minFrameRate + } + if let bitrate = map["bitrate"] as? Int { + config.bitrate = bitrate + } + if let minBitrate = map["minBitrate"] as? Int { + config.minBitrate = minBitrate + } + if let orientationMode = map["orientationMode"] as? Int { + if let orientationMode = AgoraVideoOutputOrientationMode(rawValue: orientationMode) { + config.orientationMode = orientationMode + } + } + if let degradationPreference = map["degradationPrefer"] as? Int { + if let degradationPreference = AgoraDegradationPreference(rawValue: degradationPreference) { + config.degradationPreference = degradationPreference + } + } + if let mirrorMode = map["mirrorMode"] as? Int { + if let mirrorMode = AgoraVideoMirrorMode(rawValue: UInt(mirrorMode)) { + config.mirrorMode = mirrorMode + } + } + return config +} + +func mapToBeautyOptions(_ map: Dictionary) -> AgoraBeautyOptions { + let options = AgoraBeautyOptions() + if let lighteningContrastLevel = map["lighteningContrastLevel"] as? Int { + if let lighteningContrastLevel = AgoraLighteningContrastLevel(rawValue: UInt(lighteningContrastLevel)) { + options.lighteningContrastLevel = lighteningContrastLevel + } + } + if let lighteningLevel = map["lighteningLevel"] as? Float { + options.lighteningLevel = lighteningLevel + } + if let smoothnessLevel = map["smoothnessLevel"] as? Float { + options.smoothnessLevel = smoothnessLevel + } + if let rednessLevel = map["rednessLevel"] as? Float { + options.rednessLevel = rednessLevel + } + return options +} + +func mapToAgoraImage(_ map: Dictionary) -> AgoraImage { + let image = AgoraImage() + if let url = map["url"] as? String { + if let url = URL(string: url) { + image.url = url + } + } + image.rect = mapToRect(map) + return image +} + +func mapToTranscodingUser(_ map: Dictionary) -> AgoraLiveTranscodingUser { + let user = AgoraLiveTranscodingUser() + if let uid = map["uid"] as? Int { + user.uid = UInt(uid) + } + user.rect = mapToRect(map) + if let zOrder = map["zOrder"] as? Int { + user.zOrder = zOrder + } + if let alpha = map["alpha"] as? Double { + user.alpha = alpha + } + if let audioChannel = map["audioChannel"] as? Int { + user.audioChannel = audioChannel + } + return user +} + +func mapToColor(_ map: Dictionary) -> UIColor { + UIColor( + red: CGFloat(map["red"] as! Int), + green: CGFloat(map["green"] as! Int), + blue: CGFloat(map["blue"] as! Int), + alpha: 1.0 + ) +} + +func mapToLiveTranscoding(_ map: Dictionary) -> AgoraLiveTranscoding { + let transcoding = AgoraLiveTranscoding.default() + transcoding.size = mapToSize(map) + if let videoBitrate = map["videoBitrate"] as? Int { + transcoding.videoBitrate = videoBitrate + } + if let videoFramerate = map["videoFramerate"] as? Int { + transcoding.videoFramerate = videoFramerate + } + if let lowLatency = map["lowLatency"] as? Bool { + transcoding.lowLatency = lowLatency + } + if let videoGop = map["videoGop"] as? Int { + transcoding.videoGop = videoGop + } + if let watermark = map["watermark"] as? Dictionary { + transcoding.watermark = mapToAgoraImage(watermark) + } + if let backgroundImage = map["backgroundImage"] as? Dictionary { + transcoding.backgroundImage = mapToAgoraImage(backgroundImage) + } + if let audioSampleRate = map["audioSampleRate"] as? Int { + if let audioSampleRate = AgoraAudioSampleRateType(rawValue: audioSampleRate) { + transcoding.audioSampleRate = audioSampleRate + } + } + if let audioBitrate = map["audioBitrate"] as? Int { + transcoding.audioBitrate = audioBitrate + } + if let audioChannels = map["audioChannels"] as? Int { + transcoding.audioChannels = audioChannels + } + if let audioCodecProfile = map["audioCodecProfile"] as? Int { + if let audioCodecProfile = AgoraAudioCodecProfileType(rawValue: audioCodecProfile) { + transcoding.audioCodecProfile = audioCodecProfile + } + } + if let videoCodecProfile = map["videoCodecProfile"] as? Int { + if let videoCodecProfile = AgoraVideoCodecProfileType(rawValue: videoCodecProfile) { + transcoding.videoCodecProfile = videoCodecProfile + } + } + if let backgroundColor = map["backgroundColor"] as? Dictionary { + transcoding.backgroundColor = mapToColor(backgroundColor) + } + if let userConfigExtraInfo = map["userConfigExtraInfo"] as? String { + transcoding.transcodingExtraInfo = userConfigExtraInfo + } + if let transcodingUsers = map["transcodingUsers"] as? Array { + transcodingUsers.forEach { (item) in + if let item = item as? Dictionary { + transcoding.add(mapToTranscodingUser(item)) + } + } + } + return transcoding +} + +func mapToChannelMediaInfo(_ map: Dictionary) -> AgoraChannelMediaRelayInfo { + let info = AgoraChannelMediaRelayInfo() + if let channelName = map["channelName"] as? String { + info.channelName = channelName + } + if let token = map["token"] as? String { + info.token = token + } + if let uid = map["uid"] as? UInt { + info.uid = uid + } + return info +} + +func mapToChannelMediaRelayConfiguration(_ map: Dictionary) -> AgoraChannelMediaRelayConfiguration { + let config = AgoraChannelMediaRelayConfiguration() + if let srcInfo = map["srcInfo"] as? Dictionary { + config.sourceInfo = mapToChannelMediaInfo(srcInfo) + } + if let destInfos = map["destInfos"] as? Array { + destInfos.forEach { (item) in + if let item = item as? Dictionary { + let info = mapToChannelMediaInfo(item) + config.setDestinationInfo(info, forChannelName: info.channelName ?? "") + } + } + } + return config +} + +func mapToLastmileProbeConfig(_ map: Dictionary) -> AgoraLastmileProbeConfig { + let config = AgoraLastmileProbeConfig() + if let probeUplink = map["probeUplink"] as? Bool { + config.probeUplink = probeUplink + } + if let probeDownlink = map["probeDownlink"] as? Bool { + config.probeDownlink = probeDownlink + } + if let expectedUplinkBitrate = map["expectedUplinkBitrate"] as? Int { + config.expectedUplinkBitrate = UInt(expectedUplinkBitrate) + } + if let expectedDownlinkBitrate = map["expectedDownlinkBitrate"] as? Int { + config.expectedDownlinkBitrate = UInt(expectedDownlinkBitrate) + } + return config +} + +func mapToWatermarkOptions(_ map: Dictionary) -> WatermarkOptions { + let options = WatermarkOptions() + if let visibleInPreview = map["visibleInPreview"] as? Bool { + options.visibleInPreview = visibleInPreview + } + if let positionInLandscapeMode = map["positionInLandscapeMode"] as? Dictionary { + options.positionInLandscapeMode = mapToRect(positionInLandscapeMode) + } + if let positionInPortraitMode = map["positionInPortraitMode"] as? Dictionary { + options.positionInPortraitMode = mapToRect(positionInPortraitMode) + } + return options +} + +func mapToLiveInjectStreamConfig(_ map: Dictionary) -> AgoraLiveInjectStreamConfig { + let config = AgoraLiveInjectStreamConfig.default() + config.size = mapToSize(map) + if let videoGop = map["videoGop"] as? Int { + config.videoGop = videoGop + } + if let videoFramerate = map["videoFramerate"] as? Int { + config.videoFramerate = videoFramerate + } + if let videoBitrate = map["videoBitrate"] as? Int { + config.videoBitrate = videoBitrate + } + if let audioSampleRate = map["audioSampleRate"] as? Int { + if let audioSampleRate = AgoraAudioSampleRateType(rawValue: audioSampleRate) { + config.audioSampleRate = audioSampleRate + } + } + if let audioBitrate = map["audioBitrate"] as? Int { + config.audioBitrate = audioBitrate + } + if let audioChannels = map["audioChannels"] as? Int { + config.audioChannels = audioChannels + } + return config +} + +func mapToCameraCapturerConfiguration(_ map: Dictionary) -> AgoraCameraCapturerConfiguration { + let config = AgoraCameraCapturerConfiguration() + config.preference = AgoraCameraCaptureOutputPreference(rawValue: map["preference"] as! Int)! + config.cameraDirection = AgoraCameraDirection(rawValue: map["cameraDirection"] as! Int)! + return config +} + +func mapToChannelMediaOptions(_ map: Dictionary) -> AgoraRtcChannelMediaOptions { + let options = AgoraRtcChannelMediaOptions() + if let autoSubscribeAudio = map["autoSubscribeAudio"] as? Bool { + options.autoSubscribeAudio = autoSubscribeAudio + } + if let autoSubscribeVideo = map["autoSubscribeVideo"] as? Bool { + options.autoSubscribeVideo = autoSubscribeVideo + } + return options +} diff --git a/ios/RCTAgora/Base/Callback.swift b/ios/RCTAgora/Base/Callback.swift new file mode 100644 index 000000000..9d2a22d6f --- /dev/null +++ b/ios/RCTAgora/Base/Callback.swift @@ -0,0 +1,48 @@ +// +// Callback.swift +// RCTAgora +// +// Created by LXH on 2020/4/9. +// Copyright © 2020 Syan. All rights reserved. +// + +import Foundation +import AgoraRtcKit + +protocol Callback: class { + func success(_ data: Any?) + + func failure(_ code: String, _ message: String) +} + +extension Callback { + func code(_ code: Int32?, _ runnable: ((Int32) -> Any?)? = nil) { + if code == nil || code! < 0 { + let newCode = abs(Int(code ?? Int32(AgoraErrorCode.notInitialized.rawValue))) + failure(String(newCode), AgoraRtcEngineKit.getErrorDescription(newCode) ?? "") + return + } + + let res = runnable?(code!) + if res is Void { + success(nil) + } else { + success(res) + } + } + + func resolve(_ source: T?, _ runnable: (T) -> Any?) { + guard let `source` = source else { + let code = AgoraErrorCode.notInitialized.rawValue + failure(String(code), AgoraRtcEngineKit.getErrorDescription(code) ?? "") + return + } + + let res = runnable(source) + if res is Void { + success(nil) + } else { + success(res) + } + } +} diff --git a/ios/RCTAgora/Base/Extensions.swift b/ios/RCTAgora/Base/Extensions.swift new file mode 100644 index 000000000..07885f344 --- /dev/null +++ b/ios/RCTAgora/Base/Extensions.swift @@ -0,0 +1,194 @@ +// +// Extensions.swift +// RCTAgora +// +// Created by LXH on 2020/4/10. +// Copyright © 2020 Syan. All rights reserved. +// + +import Foundation +import AgoraRtcKit + +extension AgoraUserInfo { + func toMap() -> Dictionary { + [ + "uid": uid, + "userAccount": userAccount + ] + } +} + +extension AgoraRtcLocalAudioStats { + func toMap() -> Dictionary { + [ + "numChannels": numChannels, + "sentSampleRate": sentSampleRate, + "sentBitrate": sentBitrate + ] + } +} + +extension AgoraChannelStats { + func toMap() -> Dictionary { + [ + "totalDuration": duration, + "txBytes": txBytes, + "rxBytes": rxBytes, + "txAudioBytes": txAudioBytes, + "txVideoBytes": txVideoBytes, + "rxAudioBytes": rxAudioBytes, + "rxVideoBytes": rxVideoBytes, + "txKBitRate": txKBitrate, + "rxKBitRate": rxKBitrate, + "txAudioKBitRate": txAudioKBitrate, + "rxAudioKBitRate": rxAudioKBitrate, + "txVideoKBitRate": txVideoKBitrate, + "rxVideoKBitRate": rxVideoKBitrate, + "users": userCount, + "lastmileDelay": lastmileDelay, + "txPacketLossRate": txPacketLossRate, + "rxPacketLossRate": rxPacketLossRate, + "cpuTotalUsage": cpuTotalUsage, + "cpuAppUsage": cpuAppUsage, + "gatewayRtt": gatewayRtt, + "memoryAppUsageRatio": memoryAppUsageRatio, + "memoryTotalUsageRatio": memoryTotalUsageRatio, + "memoryAppUsageInKbytes": memoryAppUsageInKbytes + ] + } +} + +extension CGRect { + func toMap() -> Dictionary { + [ + "left": origin.x, + "top": origin.y, + "right": origin.x + size.width, + "bottom": origin.y + size.height + ] + } +} + +extension AgoraRtcRemoteAudioStats { + func toMap() -> Dictionary { + [ + "uid": uid, + "quality": quality, + "networkTransportDelay": networkTransportDelay, + "jitterBufferDelay": jitterBufferDelay, + "audioLossRate": audioLossRate, + "numChannels": numChannels, + "receivedSampleRate": receivedSampleRate, + "receivedBitrate": receivedBitrate, + "totalFrozenTime": totalFrozenTime, + "frozenRate": frozenRate, + "totalActiveTime": totalActiveTime + ] + } +} + +extension AgoraRtcLocalVideoStats { + func toMap() -> Dictionary { + [ + "sentBitrate": sentBitrate, + "sentFrameRate": sentFrameRate, + "encoderOutputFrameRate": encoderOutputFrameRate, + "rendererOutputFrameRate": rendererOutputFrameRate, + "targetBitrate": sentTargetBitrate, + "targetFrameRate": sentTargetFrameRate, + "qualityAdaptIndication": qualityAdaptIndication.rawValue, + "encodedBitrate": encodedBitrate, + "encodedFrameWidth": encodedFrameWidth, + "encodedFrameHeight": encodedFrameHeight, + "encodedFrameCount": encodedFrameCount, + "codecType": codecType.rawValue + ] + } +} + +extension AgoraRtcRemoteVideoStats { + func toMap() -> Dictionary { + [ + "uid": uid, + "delay": delay, + "width": width, + "height": height, + "receivedBitrate": receivedBitrate, + "decoderOutputFrameRate": decoderOutputFrameRate, + "rendererOutputFrameRate": rendererOutputFrameRate, + "packetLossRate": packetLossRate, + "rxStreamType": rxStreamType.rawValue, + "totalFrozenTime": totalFrozenTime, + "frozenRate": frozenRate, + "totalActiveTime": totalActiveTime + ] + } +} + +extension AgoraRtcAudioVolumeInfo { + func toMap() -> Dictionary { + [ + "uid": uid, + "volume": volume, + "vad": vad, + "channelId": channelId + ] + } +} + +typealias AudioVolumeArray = Array + +extension AudioVolumeArray { + func toMapList() -> Array> { + var list = [Dictionary]() + forEach { (item) in + list.append(item.toMap()) + } + return list + } +} + +extension AgoraLastmileProbeOneWayResult { + func toMap() -> Dictionary { + [ + "packetLossRate": packetLossRate, + "jitter": jitter, + "availableBandwidth": availableBandwidth + ] + } +} + +extension AgoraLastmileProbeResult { + func toMap() -> Dictionary { + [ + "state": state.rawValue, + "rtt": rtt, + "uplinkReport": uplinkReport.toMap(), + "downlinkReport": downlinkReport.toMap() + ] + } +} + +extension AgoraFacePositionInfo { + func toMap() -> Dictionary { + [ + "x": x, + "y": y, + "width": width, + "height": height, + "distance": distance + ] + } +} + +typealias FacePositionInfoArray = Array + +extension FacePositionInfoArray { + func toMapList() -> Array> { + var list = [Dictionary]() + forEach { (item) in + list.append(item.toMap()) + } + return list + } +} diff --git a/ios/RCTAgora/Base/MediaObserver.swift b/ios/RCTAgora/Base/MediaObserver.swift new file mode 100644 index 000000000..cec16f744 --- /dev/null +++ b/ios/RCTAgora/Base/MediaObserver.swift @@ -0,0 +1,51 @@ +// +// MediaObserver.swift +// RCTAgora +// +// Created by LXH on 2020/4/10. +// Copyright © 2020 Syan. All rights reserved. +// + +import Foundation +import AgoraRtcKit + +class MediaObserver: NSObject { + private var emitter: (_ data: Dictionary?) -> Void + private var maxMetadataSize = 0 + private var metadataList = [String]() + + init(_ emitter: @escaping (_ data: Dictionary?) -> Void) { + self.emitter = emitter + } + + func addMetadata(_ metadata: String) { + metadataList.append(metadata) + } + + func setMaxMetadataSize(_ size: Int) { + maxMetadataSize = size + } +} + +extension MediaObserver: AgoraMediaMetadataDataSource { + func metadataMaxSize() -> Int { + maxMetadataSize + } + + func readyToSendMetadata(atTimestamp timestamp: TimeInterval) -> Data? { + if metadataList.count > 0 { + return metadataList.remove(at: 0).data(using: .utf8) + } + return nil + } +} + +extension MediaObserver: AgoraMediaMetadataDelegate { + func receiveMetadata(_ data: Data, fromUser uid: Int, atTimestamp timestamp: TimeInterval) { + emitter([ + "buffer": String(data: data, encoding: .utf8), + "uid": uid, + "timeStampMs": timestamp + ]) + } +} diff --git a/ios/RCTAgora/Base/RtcChannel.swift b/ios/RCTAgora/Base/RtcChannel.swift new file mode 100644 index 000000000..68d4ff4f2 --- /dev/null +++ b/ios/RCTAgora/Base/RtcChannel.swift @@ -0,0 +1,259 @@ +// +// RtcChannel.swift +// RCTAgora +// +// Created by LXH on 2020/4/13. +// Copyright (c) 2020 Syan. All rights reserved. +// + +import Foundation +import AgoraRtcKit + +protocol RtcChannelInterface: + RtcChannelAudioInterface, + RtcChannelVideoInterface, + RtcChannelVoicePositionInterface, + RtcChannelPublishStreamInterface, + RtcChannelMediaRelayInterface, + RtcChannelDualStreamInterface, + RtcChannelFallbackInterface, + RtcChannelMediaMetadataInterface, + RtcChannelEncryptionInterface, + RtcChannelInjectStreamInterface, + RtcChannelStreamMessageInterface { + associatedtype Map + associatedtype Callback + + func create(_ channelId: String, _ callback: Callback?) + + func destroy(_ channelId: String, _ callback: Callback?) + + func setClientRole(_ channelId: String, _ role: Int, _ callback: Callback?) + + func joinChannel(_ channelId: String, _ token: String?, _ optionalInfo: String?, _ optionalUid: Int, _ options: Map, _ callback: Callback?) + + func joinChannelWithUserAccount(_ channelId: String, _ token: String?, _ userAccount: String, _ options: Map, _ callback: Callback?) + + func leaveChannel(_ channelId: String, _ callback: Callback?) + + func renewToken(_ channelId: String, _ token: String, _ callback: Callback?) + + func getConnectionState(_ channelId: String, _ callback: Callback?) + + func publish(_ channelId: String, _ callback: Callback?) + + func unpublish(_ channelId: String, _ callback: Callback?) + + func getCallId(_ channelId: String, _ callback: Callback?) +} + +class RtcChannelManager { + private var rtcChannelMap = [String: AgoraRtcChannel]() + private var rtcChannelDelegateMap = [String: RtcChannelEventHandler]() + private var mediaObserverMap = [String: MediaObserver]() + + func create(_ engine: AgoraRtcEngineKit, _ channelId: String, _ emit: @escaping (_ methodName: String, _ data: Dictionary?) -> Void) { + if let rtcChannel = engine.createRtcChannel(channelId) { + let delegate = RtcChannelEventHandler() { methodName, data in + emit(methodName, data) + } + rtcChannel.setRtcChannelDelegate(delegate) + rtcChannelMap[channelId] = rtcChannel + rtcChannelDelegateMap[channelId] = delegate + } + } + + func destroy(_ channelId: String) -> Int32 { + if let rtcChannel = self[channelId] { + let res = rtcChannel.destroy() + if (res == 0) { + rtcChannelMap.removeValue(forKey: channelId) + rtcChannelDelegateMap.removeValue(forKey: channelId) + } + return res + } + return Int32(AgoraErrorCode.notInitialized.rawValue) + } + + func release() { + rtcChannelMap.forEach { key, value in + value.destroy() + } + rtcChannelMap.removeAll() + rtcChannelDelegateMap.removeAll() + mediaObserverMap.removeAll() + } + + subscript(channelId: String) -> AgoraRtcChannel? { + get { + rtcChannelMap[channelId] + } + } + + func registerMediaMetadataObserver(_ channelId: String, _ emit: @escaping (_ methodName: String, _ data: Dictionary?) -> Void) -> Int32 { + if let rtcChannel = self[channelId] { + let mediaObserver = MediaObserver() { data in + if var `data` = data { + data["channelId"] = channelId + emit(RtcChannelEvents.MetadataReceived, data) + } + } + let res = rtcChannel.setMediaMetadataDelegate(mediaObserver, with: .video) + if res { + mediaObserverMap[channelId] = mediaObserver + return 0 + } + } + return Int32(AgoraErrorCode.notInitialized.rawValue) + } + + func unregisterMediaMetadataObserver(_ channelId: String) -> Int32 { + if let rtcChannel = self[channelId] { + let res = rtcChannel.setMediaMetadataDelegate(nil, with: .video) + if res { + mediaObserverMap.removeValue(forKey: channelId) + return 0 + } + } + return Int32(AgoraErrorCode.notInitialized.rawValue) + } + + func setMaxMetadataSize(_ channelId: String, _ size: Int) -> Int32 { + if let observer = mediaObserverMap[channelId] { + observer.setMaxMetadataSize(size) + return 0 + } + return Int32(AgoraErrorCode.notInitialized.rawValue) + } + + func addMetadata(_ channelId: String, _ metadata: String) -> Int32 { + if let observer = mediaObserverMap[channelId] { + observer.addMetadata(metadata) + return 0 + } + return Int32(AgoraErrorCode.notInitialized.rawValue) + } + + func createDataStream(_ channelId: String, _ reliable: Bool, _ ordered: Bool) -> Int32 { + if let rtcChannel = self[channelId] { + var streamId = 0 + let res = rtcChannel.createDataStream(&streamId, reliable: reliable, ordered: ordered) + if res == 0 { + return Int32(streamId) + } + return res + } + return Int32(AgoraErrorCode.notInitialized.rawValue) + } + + func sendStreamMessage(_ channelId: String, _ streamId: Int, _ message: String) -> Int32 { + if let rtcChannel = self[channelId] { + if let data = message.data(using: .utf8) { + return rtcChannel.sendStreamMessage(streamId, data: data) + } + return Int32(AgoraErrorCode.invalidArgument.rawValue) + } + return Int32(AgoraErrorCode.notInitialized.rawValue) + } +} + +protocol RtcChannelAudioInterface { + associatedtype Callback + + func adjustUserPlaybackSignalVolume(_ channelId: String, _ uid: Int, _ volume: Int, _ callback: Callback?) + + func muteRemoteAudioStream(_ channelId: String, _ uid: Int, _ muted: Bool, _ callback: Callback?) + + func muteAllRemoteAudioStreams(_ channelId: String, _ muted: Bool, _ callback: Callback?) + + func setDefaultMuteAllRemoteAudioStreams(_ channelId: String, _ muted: Bool, _ callback: Callback?) +} + +protocol RtcChannelVideoInterface { + associatedtype Callback + + func muteRemoteVideoStream(_ channelId: String, _ uid: Int, _ muted: Bool, _ callback: Callback?) + + func muteAllRemoteVideoStreams(_ channelId: String, _ muted: Bool, _ callback: Callback?) + + func setDefaultMuteAllRemoteVideoStreams(_ channelId: String, _ muted: Bool, _ callback: Callback?) +} + +protocol RtcChannelVoicePositionInterface { + associatedtype Callback + + func setRemoteVoicePosition(_ channelId: String, _ uid: Int, _ pan: Double, _ gain: Double, _ callback: Callback?) +} + +protocol RtcChannelPublishStreamInterface { + associatedtype Map + associatedtype Callback + + func setLiveTranscoding(_ channelId: String, _ transcoding: Map, _ callback: Callback?) + + func addPublishStreamUrl(_ channelId: String, _ url: String, _ transcodingEnabled: Bool, _ callback: Callback?) + + func removePublishStreamUrl(_ channelId: String, _ url: String, _ callback: Callback?) +} + +protocol RtcChannelMediaRelayInterface { + associatedtype Map + associatedtype Callback + + func startChannelMediaRelay(_ channelId: String, _ channelMediaRelayConfiguration: Map, _ callback: Callback?) + + func updateChannelMediaRelay(_ channelId: String, _ channelMediaRelayConfiguration: Map, _ callback: Callback?) + + func stopChannelMediaRelay(_ channelId: String, _ callback: Callback?) +} + +protocol RtcChannelDualStreamInterface { + associatedtype Callback + + func setRemoteVideoStreamType(_ channelId: String, _ uid: Int, _ streamType: Int, _ callback: Callback?) + + func setRemoteDefaultVideoStreamType(_ channelId: String, _ streamType: Int, _ callback: Callback?) +} + +protocol RtcChannelFallbackInterface { + associatedtype Callback + + func setRemoteUserPriority(_ channelId: String, _ uid: Int, _ userPriority: Int, _ callback: Callback?) +} + +protocol RtcChannelMediaMetadataInterface { + associatedtype Callback + + func registerMediaMetadataObserver(_ channelId: String, _ callback: Callback?) + + func unregisterMediaMetadataObserver(_ channelId: String, _ callback: Callback?) + + func setMaxMetadataSize(_ channelId: String, _ size: Int, _ callback: Callback?) + + func sendMetadata(_ channelId: String, _ metadata: String, _ callback: Callback?) +} + +protocol RtcChannelEncryptionInterface { + associatedtype Callback + + func setEncryptionSecret(_ channelId: String, _ secret: String, _ callback: Callback?) + + func setEncryptionMode(_ channelId: String, _ encryptionMode: String, _ callback: Callback?) +} + +protocol RtcChannelInjectStreamInterface { + associatedtype Map + associatedtype Callback + + func addInjectStreamUrl(_ channelId: String, _ url: String, _ config: Map, _ callback: Callback?) + + func removeInjectStreamUrl(_ channelId: String, _ url: String, _ callback: Callback?) +} + +protocol RtcChannelStreamMessageInterface { + associatedtype Callback + + func createDataStream(_ channelId: String, _ reliable: Bool, _ ordered: Bool, _ callback: Callback?) + + func sendStreamMessage(_ channelId: String, _ streamId: Int, _ message: String, _ callback: Callback?) +} diff --git a/ios/RCTAgora/Base/RtcChannelEvent.swift b/ios/RCTAgora/Base/RtcChannelEvent.swift new file mode 100644 index 000000000..5e45b317e --- /dev/null +++ b/ios/RCTAgora/Base/RtcChannelEvent.swift @@ -0,0 +1,213 @@ +// +// RtcChannelEvent.swift +// RCTAgora +// +// Created by LXH on 2020/4/10. +// Copyright © 2020 Syan. All rights reserved. +// + +import Foundation +import AgoraRtcKit + +class RtcChannelEvents { + static let Warning = "Warning" + static let Error = "Error" + static let JoinChannelSuccess = "JoinChannelSuccess" + static let RejoinChannelSuccess = "RejoinChannelSuccess" + static let LeaveChannel = "LeaveChannel" + static let ClientRoleChanged = "ClientRoleChanged" + static let UserJoined = "UserJoined" + static let UserOffline = "UserOffline" + static let ConnectionStateChanged = "ConnectionStateChanged" + static let ConnectionLost = "ConnectionLost" + static let TokenPrivilegeWillExpire = "TokenPrivilegeWillExpire" + static let RequestToken = "RequestToken" + static let ActiveSpeaker = "ActiveSpeaker" + static let VideoSizeChanged = "VideoSizeChanged" + static let RemoteVideoStateChanged = "RemoteVideoStateChanged" + static let RemoteAudioStateChanged = "RemoteAudioStateChanged" + static let LocalPublishFallbackToAudioOnly = "LocalPublishFallbackToAudioOnly" + static let RemoteSubscribeFallbackToAudioOnly = "RemoteSubscribeFallbackToAudioOnly" + static let RtcStats = "RtcStats" + static let NetworkQuality = "NetworkQuality" + static let RemoteVideoStats = "RemoteVideoStats" + static let RemoteAudioStats = "RemoteAudioStats" + static let RtmpStreamingStateChanged = "RtmpStreamingStateChanged" + static let TranscodingUpdated = "TranscodingUpdated" + static let StreamInjectedStatus = "StreamInjectedStatus" + static let StreamMessage = "StreamMessage" + static let StreamMessageError = "StreamMessageError" + static let ChannelMediaRelayStateChanged = "ChannelMediaRelayStateChanged" + static let ChannelMediaRelayEvent = "ChannelMediaRelayEvent" + static let MetadataReceived = "MetadataReceived" + + static func toMap() -> Dictionary { + return [ + "Warning": Warning, + "Error": Error, + "JoinChannelSuccess": JoinChannelSuccess, + "RejoinChannelSuccess": RejoinChannelSuccess, + "LeaveChannel": LeaveChannel, + "ClientRoleChanged": ClientRoleChanged, + "UserJoined": UserJoined, + "UserOffline": UserOffline, + "ConnectionStateChanged": ConnectionStateChanged, + "ConnectionLost": ConnectionLost, + "TokenPrivilegeWillExpire": TokenPrivilegeWillExpire, + "RequestToken": RequestToken, + "ActiveSpeaker": ActiveSpeaker, + "VideoSizeChanged": VideoSizeChanged, + "RemoteVideoStateChanged": RemoteVideoStateChanged, + "RemoteAudioStateChanged": RemoteAudioStateChanged, + "LocalPublishFallbackToAudioOnly": LocalPublishFallbackToAudioOnly, + "RemoteSubscribeFallbackToAudioOnly": RemoteSubscribeFallbackToAudioOnly, + "RtcStats": RtcStats, + "NetworkQuality": NetworkQuality, + "RemoteVideoStats": RemoteVideoStats, + "RemoteAudioStats": RemoteAudioStats, + "RtmpStreamingStateChanged": RtmpStreamingStateChanged, + "TranscodingUpdated": TranscodingUpdated, + "StreamInjectedStatus": StreamInjectedStatus, + "StreamMessage": StreamMessage, + "StreamMessageError": StreamMessageError, + "ChannelMediaRelayStateChanged": ChannelMediaRelayStateChanged, + "ChannelMediaRelayEvent": ChannelMediaRelayEvent, + "MetadataReceived": MetadataReceived, + ] + } +} + +class RtcChannelEventHandler: NSObject { + static let PREFIX = "io.agora.rtc." + + var emitter: (_ methodName: String, _ data: Dictionary?) -> Void + + init(_ emitter: @escaping (_ methodName: String, _ data: Dictionary?) -> Void) { + self.emitter = emitter + } + + private func callback(_ methodName: String, _ channel: AgoraRtcChannel, _ data: Any?...) { + emitter(methodName, [ + "channelId": channel.getId(), + "data": data + ]) + } +} + +extension RtcChannelEventHandler: AgoraRtcChannelDelegate { + public func rtcChannel(_ rtcChannel: AgoraRtcChannel, didOccurWarning warningCode: AgoraWarningCode) { + callback(RtcChannelEvents.Warning, rtcChannel, warningCode.rawValue) + } + + public func rtcChannel(_ rtcChannel: AgoraRtcChannel, didOccurError errorCode: AgoraErrorCode) { + callback(RtcChannelEvents.Error, rtcChannel, errorCode.rawValue) + } + + public func rtcChannelDidJoin(_ rtcChannel: AgoraRtcChannel, withUid uid: UInt, elapsed: Int) { + callback(RtcChannelEvents.JoinChannelSuccess, rtcChannel, uid, elapsed) + } + + public func rtcChannelDidRejoin(_ rtcChannel: AgoraRtcChannel, withUid uid: UInt, elapsed: Int) { + callback(RtcChannelEvents.RejoinChannelSuccess, rtcChannel, uid, elapsed) + } + + public func rtcChannelDidLeave(_ rtcChannel: AgoraRtcChannel, with stats: AgoraChannelStats) { + callback(RtcChannelEvents.LeaveChannel, rtcChannel, stats.toMap()) + } + + public func rtcChannel(_ rtcChannel: AgoraRtcChannel, didClientRoleChanged oldRole: AgoraClientRole, newRole: AgoraClientRole) { + callback(RtcChannelEvents.ClientRoleChanged, rtcChannel, oldRole.rawValue, newRole.rawValue) + } + + public func rtcChannel(_ rtcChannel: AgoraRtcChannel, didJoinedOfUid uid: UInt, elapsed: Int) { + callback(RtcChannelEvents.UserJoined, rtcChannel, uid, elapsed) + } + + public func rtcChannel(_ rtcChannel: AgoraRtcChannel, didOfflineOfUid uid: UInt, reason: AgoraUserOfflineReason) { + callback(RtcChannelEvents.UserOffline, rtcChannel, uid, reason.rawValue) + } + + public func rtcChannel(_ rtcChannel: AgoraRtcChannel, connectionChangedTo state: AgoraConnectionStateType, reason: AgoraConnectionChangedReason) { + callback(RtcChannelEvents.ConnectionStateChanged, rtcChannel, state.rawValue, reason.rawValue) + } + + public func rtcChannelDidLost(_ rtcChannel: AgoraRtcChannel) { + callback(RtcChannelEvents.ConnectionLost, rtcChannel) + } + + public func rtcChannel(_ rtcChannel: AgoraRtcChannel, tokenPrivilegeWillExpire token: String) { + callback(RtcChannelEvents.TokenPrivilegeWillExpire, rtcChannel, token) + } + + public func rtcChannelRequestToken(_ rtcChannel: AgoraRtcChannel) { + callback(RtcChannelEvents.RequestToken, rtcChannel) + } + + public func rtcChannel(_ rtcChannel: AgoraRtcChannel, activeSpeaker speakerUid: UInt) { + callback(RtcChannelEvents.ActiveSpeaker, rtcChannel, speakerUid) + } + + public func rtcChannel(_ rtcChannel: AgoraRtcChannel, videoSizeChangedOfUid uid: UInt, size: CGSize, rotation: Int) { + callback(RtcChannelEvents.VideoSizeChanged, rtcChannel, uid, size.width, size.height, rotation) + } + + public func rtcChannel(_ rtcChannel: AgoraRtcChannel, remoteVideoStateChangedOfUid uid: UInt, state: AgoraVideoRemoteState, reason: AgoraVideoRemoteStateReason, elapsed: Int) { + callback(RtcChannelEvents.RemoteVideoStateChanged, rtcChannel, uid, state.rawValue, reason.rawValue, elapsed) + } + + public func rtcChannel(_ rtcChannel: AgoraRtcChannel, remoteAudioStateChangedOfUid uid: UInt, state: AgoraAudioRemoteState, reason: AgoraAudioRemoteStateReason, elapsed: Int) { + callback(RtcChannelEvents.RemoteAudioStateChanged, rtcChannel, uid, state.rawValue, reason.rawValue, elapsed) + } + + public func rtcChannel(_ rtcChannel: AgoraRtcChannel, didLocalPublishFallbackToAudioOnly isFallbackOrRecover: Bool) { + callback(RtcChannelEvents.LocalPublishFallbackToAudioOnly, rtcChannel, isFallbackOrRecover) + } + + public func rtcChannel(_ rtcChannel: AgoraRtcChannel, didRemoteSubscribeFallbackToAudioOnly isFallbackOrRecover: Bool, byUid uid: UInt) { + callback(RtcChannelEvents.RemoteSubscribeFallbackToAudioOnly, rtcChannel, uid, isFallbackOrRecover) + } + + public func rtcChannel(_ rtcChannel: AgoraRtcChannel, reportRtcStats stats: AgoraChannelStats) { + callback(RtcChannelEvents.RtcStats, rtcChannel, stats.toMap()) + } + + public func rtcChannel(_ rtcChannel: AgoraRtcChannel, networkQuality uid: UInt, txQuality: AgoraNetworkQuality, rxQuality: AgoraNetworkQuality) { + callback(RtcChannelEvents.NetworkQuality, rtcChannel, uid, txQuality.rawValue, rxQuality.rawValue) + } + + public func rtcChannel(_ rtcChannel: AgoraRtcChannel, remoteVideoStats stats: AgoraRtcRemoteVideoStats) { + callback(RtcChannelEvents.RemoteVideoStats, rtcChannel, stats.toMap()) + } + + public func rtcChannel(_ rtcChannel: AgoraRtcChannel, remoteAudioStats stats: AgoraRtcRemoteAudioStats) { + callback(RtcChannelEvents.RemoteAudioStats, rtcChannel, stats.toMap()) + } + + public func rtcChannel(_ rtcChannel: AgoraRtcChannel, rtmpStreamingChangedToState url: String, state: AgoraRtmpStreamingState, errorCode: AgoraRtmpStreamingErrorCode) { + callback(RtcChannelEvents.RtmpStreamingStateChanged, rtcChannel, url, state.rawValue, errorCode.rawValue) + } + + public func rtcChannelTranscodingUpdated(_ rtcChannel: AgoraRtcChannel) { + callback(RtcChannelEvents.TranscodingUpdated, rtcChannel) + } + + public func rtcChannel(_ rtcChannel: AgoraRtcChannel, streamInjectedStatusOfUrl url: String, uid: UInt, status: AgoraInjectStreamStatus) { + callback(RtcChannelEvents.StreamInjectedStatus, rtcChannel, url, uid, status.rawValue) + } + + public func rtcChannel(_ rtcChannel: AgoraRtcChannel, receiveStreamMessageFromUid uid: UInt, streamId: Int, data: Data) { + callback(RtcChannelEvents.StreamMessage, rtcChannel, uid, streamId, String(data: data, encoding: .utf8)) + } + + public func rtcChannel(_ rtcChannel: AgoraRtcChannel, didOccurStreamMessageErrorFromUid uid: UInt, streamId: Int, error: Int, missed: Int, cached: Int) { + callback(RtcChannelEvents.StreamMessageError, rtcChannel, uid, streamId, error, missed, cached) + } + + public func rtcChannel(_ rtcChannel: AgoraRtcChannel, channelMediaRelayStateDidChange state: AgoraChannelMediaRelayState, error: AgoraChannelMediaRelayError) { + callback(RtcChannelEvents.ChannelMediaRelayStateChanged, rtcChannel, state.rawValue, error.rawValue) + } + + public func rtcChannel(_ rtcChannel: AgoraRtcChannel, didReceive event: AgoraChannelMediaRelayEvent) { + callback(RtcChannelEvents.ChannelMediaRelayEvent, rtcChannel, event.rawValue) + } +} diff --git a/ios/RCTAgora/Base/RtcEngine.swift b/ios/RCTAgora/Base/RtcEngine.swift new file mode 100644 index 000000000..a3476c02b --- /dev/null +++ b/ios/RCTAgora/Base/RtcEngine.swift @@ -0,0 +1,493 @@ +// +// RtcEngine.swift +// RCTAgora +// +// Created by LXH on 2020/4/13. +// Copyright (c) 2020 Syan. All rights reserved. +// + +import Foundation +import AgoraRtcKit + +protocol RtcEngineInterface: + RtcEngineUserInfoInterface, + RtcEngineAudioInterface, + RtcEngineVideoInterface, + RtcEngineAudioMixingInterface, + RtcEngineAudioEffectInterface, + RtcEngineVoiceChangerInterface, + RtcEngineVoicePositionInterface, + RtcEnginePublishStreamInterface, + RtcEngineMediaRelayInterface, + RtcEngineAudioRouteInterface, + RtcEngineEarMonitoringInterface, + RtcEngineDualStreamInterface, + RtcEngineFallbackInterface, + RtcEngineTestInterface, + RtcEngineMediaMetadataInterface, + RtcEngineWatermarkInterface, + RtcEngineEncryptionInterface, + RtcEngineAudioRecorderInterface, + RtcEngineInjectStreamInterface, + RtcEngineCameraInterface, + RtcEngineStreamMessageInterface { + associatedtype Map + associatedtype Callback + + func create(_ appId: String, _ areaCode: Int, _ callback: Callback?) + + func destroy(_ callback: Callback?) + + func setChannelProfile(_ profile: Int, _ callback: Callback?) + + func setClientRole(_ role: Int, _ callback: Callback?) + + func joinChannel(_ token: String?, _ channelName: String, _ optionalInfo: String?, _ optionalUid: Int, _ callback: Callback?) + + func switchChannel(_ token: String?, _ channelName: String, _ callback: Callback?) + + func leaveChannel(_ callback: Callback?) + + func renewToken(_ token: String, _ callback: Callback?) + + @available(*, deprecated) + func enableWebSdkInteroperability(_ enabled: Bool, _ callback: Callback?) + + func getConnectionState(_ callback: Callback?) + + func getCallId(_ callback: Callback?) + + func rate(_ callId: String, _ rating: Int, _ description: String?, _ callback: Callback?) + + func complain(_ callId: String, _ description: String, _ callback: Callback?) + + func setLogFile(_ filePath: String, _ callback: Callback?) + + func setLogFilter(_ filter: Int, _ callback: Callback?) + + func setLogFileSize(_ fileSizeInKBytes: Int, _ callback: Callback?) + + func setParameters(_ parameters: String, _ callback: Callback?) +} + +class RtcEngineManager { + private var _engine: AgoraRtcEngineKit? + private var delegate: RtcEngineEventHandler? + private var mediaObserver: MediaObserver? + + func create(_ appId: String, _ areaCode: Int32, _ appType: AgoraRtcAppType, _ emit: @escaping (_ methodName: String, _ data: Dictionary?) -> Void) { + delegate = RtcEngineEventHandler() { methodName, data in + emit(methodName, data) + } + let config = AgoraRtcEngineConfig() + config.appId = appId + config.areaCode = areaCode + _engine = AgoraRtcEngineKit.sharedEngine(with: config, delegate: delegate) + _engine?.setAppType(appType) + } + + func destroy() { + AgoraRtcEngineKit.destroy() + _engine = nil + delegate = nil + } + + func release() { + destroy() + mediaObserver = nil + } + + var engine: AgoraRtcEngineKit? { + return _engine + } + + func getUserInfoByUserAccount(_ userAccount: String) -> Dictionary? { + if let engine = _engine { + let userInfo = engine.getUserInfo(byUserAccount: userAccount, withError: nil) + return userInfo?.toMap() + } + return nil + } + + func getUserInfoByUid(_ uid: Int) -> Dictionary? { + if let engine = _engine { + let userInfo = engine.getUserInfo(byUid: UInt(uid), withError: nil) + return userInfo?.toMap() + } + return nil + } + + func registerMediaMetadataObserver(_ emit: @escaping (_ methodName: String, _ data: Dictionary?) -> Void) -> Int32 { + if let engine = _engine { + let mediaObserver = MediaObserver() { data in + emit(RtcEngineEvents.MetadataReceived, data) + } + let res = engine.setMediaMetadataDelegate(mediaObserver, with: .video) + if res { + self.mediaObserver = mediaObserver + return 0 + } else { + return Int32(AgoraErrorCode.noPermission.rawValue) + } + } + return Int32(AgoraErrorCode.notInitialized.rawValue) + } + + func unregisterMediaMetadataObserver() -> Int32 { + if let engine = _engine { + let res = engine.setMediaMetadataDelegate(nil, with: .video) + if res { + mediaObserver = nil + return 0 + } else { + return Int32(AgoraErrorCode.noPermission.rawValue) + } + } + return Int32(AgoraErrorCode.notInitialized.rawValue) + } + + func setMaxMetadataSize(_ size: Int) -> Int32 { + if let observer = mediaObserver { + observer.setMaxMetadataSize(size) + return 0 + } + return Int32(AgoraErrorCode.notInitialized.rawValue) + } + + func addMetadata(_ metadata: String) -> Int32 { + if let observer = mediaObserver { + observer.addMetadata(metadata) + return 0 + } + return Int32(AgoraErrorCode.notInitialized.rawValue) + } + + func createDataStream(_ reliable: Bool, _ ordered: Bool) -> Int32 { + if let engine = _engine { + var streamId = 0 + let res = engine.createDataStream(&streamId, reliable: reliable, ordered: ordered) + if res == 0 { + return Int32(streamId) + } + return res + } + return Int32(AgoraErrorCode.notInitialized.rawValue) + } + + func sendStreamMessage(_ streamId: Int, _ message: String) -> Int32 { + if let engine = _engine { + if let data = message.data(using: .utf8) { + return engine.sendStreamMessage(streamId, data: data) + } + return Int32(AgoraErrorCode.invalidArgument.rawValue) + } + return Int32(AgoraErrorCode.notInitialized.rawValue) + } +} + +protocol RtcEngineUserInfoInterface { + associatedtype Callback + + func registerLocalUserAccount(_ appId: String, _ userAccount: String, _ callback: Callback?) + + func joinChannelWithUserAccount(_ token: String?, _ channelName: String, _ userAccount: String, _ callback: Callback?) + + func getUserInfoByUserAccount(_ userAccount: String, _ callback: Callback?) + + func getUserInfoByUid(_ uid: Int, _ callback: Callback?) +} + +protocol RtcEngineAudioInterface { + associatedtype Callback + + func enableAudio(_ callback: Callback?) + + func disableAudio(_ callback: Callback?) + + func setAudioProfile(_ profile: Int, _ scenario: Int, _ callback: Callback?) + + func adjustRecordingSignalVolume(_ volume: Int, _ callback: Callback?) + + func adjustUserPlaybackSignalVolume(_ uid: Int, _ volume: Int, _ callback: Callback?) + + func adjustPlaybackSignalVolume(_ volume: Int, _ callback: Callback?) + + func enableLocalAudio(_ enabled: Bool, _ callback: Callback?) + + func muteLocalAudioStream(_ muted: Bool, _ callback: Callback?) + + func muteRemoteAudioStream(_ uid: Int, _ muted: Bool, _ callback: Callback?) + + func muteAllRemoteAudioStreams(_ muted: Bool, _ callback: Callback?) + + func setDefaultMuteAllRemoteAudioStreams(_ muted: Bool, _ callback: Callback?) + + func enableAudioVolumeIndication(_ interval: Int, _ smooth: Int, _ report_vad: Bool, _ callback: Callback?) +} + +protocol RtcEngineVideoInterface { + associatedtype Map + associatedtype Callback + + func enableVideo(_ callback: Callback?) + + func disableVideo(_ callback: Callback?) + + func setVideoEncoderConfiguration(_ config: Map, _ callback: Callback?) + + func enableLocalVideo(_ enabled: Bool, _ callback: Callback?) + + func muteLocalVideoStream(_ muted: Bool, _ callback: Callback?) + + func muteRemoteVideoStream(_ uid: Int, _ muted: Bool, _ callback: Callback?) + + func muteAllRemoteVideoStreams(_ muted: Bool, _ callback: Callback?) + + func setDefaultMuteAllRemoteVideoStreams(_ muted: Bool, _ callback: Callback?) + + func setBeautyEffectOptions(_ enabled: Bool, _ options: Map, _ callback: Callback?) +} + +protocol RtcEngineAudioMixingInterface { + associatedtype Callback + + func startAudioMixing(_ filePath: String, _ loopback: Bool, _ replace: Bool, _ cycle: Int, _ callback: Callback?) + + func stopAudioMixing(_ callback: Callback?) + + func pauseAudioMixing(_ callback: Callback?) + + func resumeAudioMixing(_ callback: Callback?) + + func adjustAudioMixingVolume(_ volume: Int, _ callback: Callback?) + + func adjustAudioMixingPlayoutVolume(_ volume: Int, _ callback: Callback?) + + func adjustAudioMixingPublishVolume(_ volume: Int, _ callback: Callback?) + + func getAudioMixingPlayoutVolume(_ callback: Callback?) + + func getAudioMixingPublishVolume(_ callback: Callback?) + + func getAudioMixingDuration(_ callback: Callback?) + + func getAudioMixingCurrentPosition(_ callback: Callback?) + + func setAudioMixingPosition(_ pos: Int, _ callback: Callback?) + + func setAudioMixingPitch(_ pitch: Int, _ callback: Callback?) +} + +protocol RtcEngineAudioEffectInterface { + associatedtype Callback + + func getEffectsVolume(_ callback: Callback?) + + func setEffectsVolume(_ volume: Double, _ callback: Callback?) + + func setVolumeOfEffect(_ soundId: Int, _ volume: Double, _ callback: Callback?) + + func playEffect(_ soundId: Int, _ filePath: String, _ loopCount: Int, _ pitch: Double, _ pan: Double, _ gain: Double, _ publish: Bool, _ callback: Callback?) + + func stopEffect(_ soundId: Int, _ callback: Callback?) + + func stopAllEffects(_ callback: Callback?) + + func preloadEffect(_ soundId: Int, _ filePath: String, _ callback: Callback?) + + func unloadEffect(_ soundId: Int, _ callback: Callback?) + + func pauseEffect(_ soundId: Int, _ callback: Callback?) + + func pauseAllEffects(_ callback: Callback?) + + func resumeEffect(_ soundId: Int, _ callback: Callback?) + + func resumeAllEffects(_ callback: Callback?) +} + +protocol RtcEngineVoiceChangerInterface { + associatedtype Callback + + func setLocalVoiceChanger(_ voiceChanger: Int, _ callback: Callback?) + + func setLocalVoiceReverbPreset(_ preset: Int, _ callback: Callback?) + + func setLocalVoicePitch(_ pitch: Double, _ callback: Callback?) + + func setLocalVoiceEqualization(_ bandFrequency: Int, _ bandGain: Int, _ callback: Callback?) + + func setLocalVoiceReverb(_ reverbKey: Int, _ value: Int, _ callback: Callback?) +} + +protocol RtcEngineVoicePositionInterface { + associatedtype Callback + + func enableSoundPositionIndication(_ enabled: Bool, _ callback: Callback?) + + func setRemoteVoicePosition(_ uid: Int, _ pan: Double, _ gain: Double, _ callback: Callback?) +} + +protocol RtcEnginePublishStreamInterface { + associatedtype Map + associatedtype Callback + + func setLiveTranscoding(_ transcoding: Map, _ callback: Callback?) + + func addPublishStreamUrl(_ url: String, _ transcodingEnabled: Bool, _ callback: Callback?) + + func removePublishStreamUrl(_ url: String, _ callback: Callback?) +} + +protocol RtcEngineMediaRelayInterface { + associatedtype Map + associatedtype Callback + + func startChannelMediaRelay(_ channelMediaRelayConfiguration: Map, _ callback: Callback?) + + func updateChannelMediaRelay(_ channelMediaRelayConfiguration: Map, _ callback: Callback?) + + func stopChannelMediaRelay(_ callback: Callback?) +} + +protocol RtcEngineAudioRouteInterface { + associatedtype Callback + + func setDefaultAudioRoutetoSpeakerphone(_ defaultToSpeaker: Bool, _ callback: Callback?) + + func setEnableSpeakerphone(_ enabled: Bool, _ callback: Callback?) + + func isSpeakerphoneEnabled(_ callback: Callback?) +} + +protocol RtcEngineEarMonitoringInterface { + associatedtype Callback + + func enableInEarMonitoring(_ enabled: Bool, _ callback: Callback?) + + func setInEarMonitoringVolume(_ volume: Int, _ callback: Callback?) +} + +protocol RtcEngineDualStreamInterface { + associatedtype Callback + + func enableDualStreamMode(_ enabled: Bool, _ callback: Callback?) + + func setRemoteVideoStreamType(_ uid: Int, _ streamType: Int, _ callback: Callback?) + + func setRemoteDefaultVideoStreamType(_ streamType: Int, _ callback: Callback?) +} + +protocol RtcEngineFallbackInterface { + associatedtype Callback + + func setLocalPublishFallbackOption(_ option: Int, _ callback: Callback?) + + func setRemoteSubscribeFallbackOption(_ option: Int, _ callback: Callback?) + + func setRemoteUserPriority(_ uid: Int, _ userPriority: Int, _ callback: Callback?) +} + +protocol RtcEngineTestInterface { + associatedtype Map + associatedtype Callback + + func startEchoTest(_ intervalInSeconds: Int, _ callback: Callback?) + + func stopEchoTest(_ callback: Callback?) + + func enableLastmileTest(_ callback: Callback?) + + func disableLastmileTest(_ callback: Callback?) + + func startLastmileProbeTest(_ config: Map, _ callback: Callback?) + + func stopLastmileProbeTest(_ callback: Callback?) +} + +protocol RtcEngineMediaMetadataInterface { + associatedtype Callback + + func registerMediaMetadataObserver(_ callback: Callback?) + + func unregisterMediaMetadataObserver(_ callback: Callback?) + + func setMaxMetadataSize(_ size: Int, _ callback: Callback?) + + func sendMetadata(_ metadata: String, _ callback: Callback?) +} + +protocol RtcEngineWatermarkInterface { + associatedtype Map + associatedtype Callback + + func addVideoWatermark(_ watermarkUrl: String, _ options: Map, _ callback: Callback?) + + func clearVideoWatermarks(_ callback: Callback?) +} + +protocol RtcEngineEncryptionInterface { + associatedtype Callback + + func setEncryptionSecret(_ secret: String, _ callback: Callback?) + + func setEncryptionMode(_ encryptionMode: String, _ callback: Callback?) +} + +protocol RtcEngineAudioRecorderInterface { + associatedtype Callback + + func startAudioRecording(_ filePath: String, _ sampleRate: Int, _ quality: Int, _ callback: Callback?) + + func stopAudioRecording(_ callback: Callback?) +} + +protocol RtcEngineInjectStreamInterface { + associatedtype Map + associatedtype Callback + + func addInjectStreamUrl(_ url: String, _ config: Map, _ callback: Callback?) + + func removeInjectStreamUrl(_ url: String, _ callback: Callback?) +} + +protocol RtcEngineCameraInterface { + associatedtype Map + associatedtype Callback + + func switchCamera(_ callback: Callback?) + + func isCameraZoomSupported(_ callback: Callback?) + + func isCameraTorchSupported(_ callback: Callback?) + + func isCameraFocusSupported(_ callback: Callback?) + + func isCameraExposurePositionSupported(_ callback: Callback?) + + func isCameraAutoFocusFaceModeSupported(_ callback: Callback?) + + func setCameraZoomFactor(_ factor: Float, _ callback: Callback?) + + func getCameraMaxZoomFactor(_ callback: Callback?) + + func setCameraFocusPositionInPreview(_ positionX: Float, _ positionY: Float, _ callback: Callback?) + + func setCameraExposurePosition(_ positionXinView: Float, _ positionYinView: Float, _ callback: Callback?) + + func enableFaceDetection(_ enable: Bool, _ callback: Callback?) + + func setCameraTorchOn(_ isOn: Bool, _ callback: Callback?) + + func setCameraAutoFocusFaceModeEnabled(_ enabled: Bool, _ callback: Callback?) + + func setCameraCapturerConfiguration(_ config: Map, _ callback: Callback?) +} + +protocol RtcEngineStreamMessageInterface { + associatedtype Callback + + func createDataStream(_ reliable: Bool, _ ordered: Bool, _ callback: Callback?) + + func sendStreamMessage(_ streamId: Int, _ message: String, _ callback: Callback?) +} diff --git a/ios/RCTAgora/Base/RtcEngineEvent.swift b/ios/RCTAgora/Base/RtcEngineEvent.swift new file mode 100644 index 000000000..9e0b1c5f4 --- /dev/null +++ b/ios/RCTAgora/Base/RtcEngineEvent.swift @@ -0,0 +1,458 @@ +// +// RtcEngineEvent.swift +// RCTAgora +// +// Created by LXH on 2020/4/13. +// Copyright (c) 2020 Syan. All rights reserved. +// + +import Foundation +import AgoraRtcKit + +class RtcEngineEvents { + static let Warning = "Warning" + static let Error = "Error" + static let ApiCallExecuted = "ApiCallExecuted" + static let JoinChannelSuccess = "JoinChannelSuccess" + static let RejoinChannelSuccess = "RejoinChannelSuccess" + static let LeaveChannel = "LeaveChannel" + static let LocalUserRegistered = "LocalUserRegistered" + static let UserInfoUpdated = "UserInfoUpdated" + static let ClientRoleChanged = "ClientRoleChanged" + static let UserJoined = "UserJoined" + static let UserOffline = "UserOffline" + static let ConnectionStateChanged = "ConnectionStateChanged" + static let NetworkTypeChanged = "NetworkTypeChanged" + static let ConnectionLost = "ConnectionLost" + static let TokenPrivilegeWillExpire = "TokenPrivilegeWillExpire" + static let RequestToken = "RequestToken" + static let AudioVolumeIndication = "AudioVolumeIndication" + static let ActiveSpeaker = "ActiveSpeaker" + static let FirstLocalAudioFrame = "FirstLocalAudioFrame" + static let FirstLocalVideoFrame = "FirstLocalVideoFrame" + static let UserMuteVideo = "UserMuteVideo" + static let VideoSizeChanged = "VideoSizeChanged" + static let RemoteVideoStateChanged = "RemoteVideoStateChanged" + static let LocalVideoStateChanged = "LocalVideoStateChanged" + static let RemoteAudioStateChanged = "RemoteAudioStateChanged" + static let LocalAudioStateChanged = "LocalAudioStateChanged" + static let LocalPublishFallbackToAudioOnly = "LocalPublishFallbackToAudioOnly" + static let RemoteSubscribeFallbackToAudioOnly = "RemoteSubscribeFallbackToAudioOnly" + static let AudioRouteChanged = "AudioRouteChanged" + static let CameraFocusAreaChanged = "CameraFocusAreaChanged" + static let CameraExposureAreaChanged = "CameraExposureAreaChanged" + static let FacePositionChanged = "FacePositionChanged" + static let RtcStats = "RtcStats" + static let LastmileQuality = "LastmileQuality" + static let NetworkQuality = "NetworkQuality" + static let LastmileProbeResult = "LastmileProbeResult" + static let LocalVideoStats = "LocalVideoStats" + static let LocalAudioStats = "LocalAudioStats" + static let RemoteVideoStats = "RemoteVideoStats" + static let RemoteAudioStats = "RemoteAudioStats" + static let AudioMixingFinished = "AudioMixingFinished" + static let AudioMixingStateChanged = "AudioMixingStateChanged" + static let AudioEffectFinished = "AudioEffectFinished" + static let RtmpStreamingStateChanged = "RtmpStreamingStateChanged" + static let TranscodingUpdated = "TranscodingUpdated" + static let StreamInjectedStatus = "StreamInjectedStatus" + static let StreamMessage = "StreamMessage" + static let StreamMessageError = "StreamMessageError" + static let MediaEngineLoadSuccess = "MediaEngineLoadSuccess" + static let MediaEngineStartCallSuccess = "MediaEngineStartCallSuccess" + static let ChannelMediaRelayStateChanged = "ChannelMediaRelayStateChanged" + static let ChannelMediaRelayEvent = "ChannelMediaRelayEvent" + static let FirstRemoteVideoFrame = "FirstRemoteVideoFrame" + static let FirstRemoteAudioFrame = "FirstRemoteAudioFrame" + static let FirstRemoteAudioDecoded = "FirstRemoteAudioDecoded" + static let UserMuteAudio = "UserMuteAudio" + static let StreamPublished = "StreamPublished" + static let StreamUnpublished = "StreamUnpublished" + static let RemoteAudioTransportStats = "RemoteAudioTransportStats" + static let RemoteVideoTransportStats = "RemoteVideoTransportStats" + static let UserEnableVideo = "UserEnableVideo" + static let UserEnableLocalVideo = "UserEnableLocalVideo" + static let FirstRemoteVideoDecoded = "FirstRemoteVideoDecoded" + static let MicrophoneEnabled = "MicrophoneEnabled" + static let ConnectionInterrupted = "ConnectionInterrupted" + static let ConnectionBanned = "ConnectionBanned" + static let AudioQuality = "AudioQuality" + static let CameraReady = "CameraReady" + static let VideoStopped = "VideoStopped" + static let MetadataReceived = "MetadataReceived" + + static func toMap() -> Dictionary { + return [ + "Warning": Warning, + "Error": Error, + "ApiCallExecuted": ApiCallExecuted, + "JoinChannelSuccess": JoinChannelSuccess, + "RejoinChannelSuccess": RejoinChannelSuccess, + "LeaveChannel": LeaveChannel, + "LocalUserRegistered": LocalUserRegistered, + "UserInfoUpdated": UserInfoUpdated, + "ClientRoleChanged": ClientRoleChanged, + "UserJoined": UserJoined, + "UserOffline": UserOffline, + "ConnectionStateChanged": ConnectionStateChanged, + "NetworkTypeChanged": NetworkTypeChanged, + "ConnectionLost": ConnectionLost, + "TokenPrivilegeWillExpire": TokenPrivilegeWillExpire, + "RequestToken": RequestToken, + "AudioVolumeIndication": AudioVolumeIndication, + "ActiveSpeaker": ActiveSpeaker, + "FirstLocalAudioFrame": FirstLocalAudioFrame, + "FirstLocalVideoFrame": FirstLocalVideoFrame, + "UserMuteVideo": UserMuteVideo, + "VideoSizeChanged": VideoSizeChanged, + "RemoteVideoStateChanged": RemoteVideoStateChanged, + "LocalVideoStateChanged": LocalVideoStateChanged, + "RemoteAudioStateChanged": RemoteAudioStateChanged, + "LocalAudioStateChanged": LocalAudioStateChanged, + "LocalPublishFallbackToAudioOnly": LocalPublishFallbackToAudioOnly, + "RemoteSubscribeFallbackToAudioOnly": RemoteSubscribeFallbackToAudioOnly, + "AudioRouteChanged": AudioRouteChanged, + "CameraFocusAreaChanged": CameraFocusAreaChanged, + "CameraExposureAreaChanged": CameraExposureAreaChanged, + "FacePositionChanged": FacePositionChanged, + "RtcStats": RtcStats, + "LastmileQuality": LastmileQuality, + "NetworkQuality": NetworkQuality, + "LastmileProbeResult": LastmileProbeResult, + "LocalVideoStats": LocalVideoStats, + "LocalAudioStats": LocalAudioStats, + "RemoteVideoStats": RemoteVideoStats, + "RemoteAudioStats": RemoteAudioStats, + "AudioMixingFinished": AudioMixingFinished, + "AudioMixingStateChanged": AudioMixingStateChanged, + "AudioEffectFinished": AudioEffectFinished, + "RtmpStreamingStateChanged": RtmpStreamingStateChanged, + "TranscodingUpdated": TranscodingUpdated, + "StreamInjectedStatus": StreamInjectedStatus, + "StreamMessage": StreamMessage, + "StreamMessageError": StreamMessageError, + "MediaEngineLoadSuccess": MediaEngineLoadSuccess, + "MediaEngineStartCallSuccess": MediaEngineStartCallSuccess, + "ChannelMediaRelayStateChanged": ChannelMediaRelayStateChanged, + "ChannelMediaRelayEvent": ChannelMediaRelayEvent, + "FirstRemoteVideoFrame": FirstRemoteVideoFrame, + "FirstRemoteAudioFrame": FirstRemoteAudioFrame, + "FirstRemoteAudioDecoded": FirstRemoteAudioDecoded, + "UserMuteAudio": UserMuteAudio, + "StreamPublished": StreamPublished, + "StreamUnpublished": StreamUnpublished, + "RemoteAudioTransportStats": RemoteAudioTransportStats, + "RemoteVideoTransportStats": RemoteVideoTransportStats, + "UserEnableVideo": UserEnableVideo, + "UserEnableLocalVideo": UserEnableLocalVideo, + "FirstRemoteVideoDecoded": FirstRemoteVideoDecoded, + "MicrophoneEnabled": MicrophoneEnabled, + "ConnectionInterrupted": ConnectionInterrupted, + "ConnectionBanned": ConnectionBanned, + "AudioQuality": AudioQuality, + "CameraReady": CameraReady, + "VideoStopped": VideoStopped, + "MetadataReceived": MetadataReceived, + ] + } +} + +class RtcEngineEventHandler: NSObject { + static let PREFIX = "io.agora.rtc." + + var emitter: (_ methodName: String, _ data: Dictionary?) -> Void + + init(emitter: @escaping (_ methodName: String, _ data: Dictionary?) -> Void) { + self.emitter = emitter + } + + private func callback(_ methodName: String, _ data: Any?...) { + emitter(methodName, ["data": data]) + } +} + +extension RtcEngineEventHandler: AgoraRtcEngineDelegate { + public func rtcEngine(_ engine: AgoraRtcEngineKit, didOccurWarning warningCode: AgoraWarningCode) { + callback(RtcEngineEvents.Warning, warningCode.rawValue) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, didOccurError errorCode: AgoraErrorCode) { + callback(RtcEngineEvents.Error, errorCode.rawValue) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, didApiCallExecute error: Int, api: String, result: String) { + callback(RtcEngineEvents.ApiCallExecuted, error, api, result) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, didJoinChannel channel: String, withUid uid: UInt, elapsed: Int) { + callback(RtcEngineEvents.JoinChannelSuccess, channel, uid, elapsed) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, didRejoinChannel channel: String, withUid uid: UInt, elapsed: Int) { + callback(RtcEngineEvents.RejoinChannelSuccess, uid, elapsed) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, didLeaveChannelWith stats: AgoraChannelStats) { + callback(RtcEngineEvents.LeaveChannel, stats.toMap()) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, didRegisteredLocalUser userAccount: String, withUid uid: UInt) { + callback(RtcEngineEvents.LocalUserRegistered, uid, userAccount) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, didUpdatedUserInfo userInfo: AgoraUserInfo, withUid uid: UInt) { + callback(RtcEngineEvents.UserInfoUpdated, uid, userInfo.toMap()) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, didClientRoleChanged oldRole: AgoraClientRole, newRole: AgoraClientRole) { + callback(RtcEngineEvents.ClientRoleChanged, oldRole.rawValue, newRole.rawValue) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, didJoinedOfUid uid: UInt, elapsed: Int) { + callback(RtcEngineEvents.UserJoined, uid, elapsed) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, didOfflineOfUid uid: UInt, reason: AgoraUserOfflineReason) { + callback(RtcEngineEvents.UserOffline, uid, reason.rawValue) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, connectionChangedTo state: AgoraConnectionStateType, reason: AgoraConnectionChangedReason) { + callback(RtcEngineEvents.ConnectionStateChanged, state.rawValue, reason.rawValue) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, networkTypeChangedTo type: AgoraNetworkType) { + callback(RtcEngineEvents.NetworkTypeChanged, type.rawValue) + } + + public func rtcEngineConnectionDidLost(_ engine: AgoraRtcEngineKit) { + callback(RtcEngineEvents.ConnectionLost) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, tokenPrivilegeWillExpire token: String) { + callback(RtcEngineEvents.TokenPrivilegeWillExpire, token) + } + + public func rtcEngineRequestToken(_ engine: AgoraRtcEngineKit) { + callback(RtcEngineEvents.RequestToken) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, reportAudioVolumeIndicationOfSpeakers speakers: [AgoraRtcAudioVolumeInfo], totalVolume: Int) { + callback(RtcEngineEvents.AudioVolumeIndication, speakers.toMapList(), totalVolume) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, activeSpeaker speakerUid: UInt) { + callback(RtcEngineEvents.ActiveSpeaker, speakerUid) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, firstLocalAudioFrame elapsed: Int) { + callback(RtcEngineEvents.FirstLocalAudioFrame, elapsed) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, firstLocalVideoFrameWith size: CGSize, elapsed: Int) { + callback(RtcEngineEvents.FirstLocalVideoFrame, size.width, size.height, elapsed) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, didVideoMuted muted: Bool, byUid uid: UInt) { + callback(RtcEngineEvents.UserMuteVideo, uid, muted) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, videoSizeChangedOfUid uid: UInt, size: CGSize, rotation: Int) { + callback(RtcEngineEvents.VideoSizeChanged, uid, size.width, size.height, rotation) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, remoteVideoStateChangedOfUid uid: UInt, state: AgoraVideoRemoteState, reason: AgoraVideoRemoteStateReason, elapsed: Int) { + callback(RtcEngineEvents.RemoteVideoStateChanged, uid, state.rawValue, reason.rawValue, elapsed) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, localVideoStateChange state: AgoraLocalVideoStreamState, error: AgoraLocalVideoStreamError) { + callback(RtcEngineEvents.LocalVideoStateChanged, state.rawValue, error.rawValue) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, remoteAudioStateChangedOfUid uid: UInt, state: AgoraAudioRemoteState, reason: AgoraAudioRemoteStateReason, elapsed: Int) { + callback(RtcEngineEvents.RemoteAudioStateChanged, uid, state.rawValue, reason.rawValue, elapsed) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, localAudioStateChange state: AgoraAudioLocalState, error: AgoraAudioLocalError) { + callback(RtcEngineEvents.LocalAudioStateChanged, state.rawValue, error.rawValue) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, didLocalPublishFallbackToAudioOnly isFallbackOrRecover: Bool) { + callback(RtcEngineEvents.LocalPublishFallbackToAudioOnly, isFallbackOrRecover) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, didRemoteSubscribeFallbackToAudioOnly isFallbackOrRecover: Bool, byUid uid: UInt) { + callback(RtcEngineEvents.RemoteSubscribeFallbackToAudioOnly, uid, isFallbackOrRecover) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, didAudioRouteChanged routing: AgoraAudioOutputRouting) { + callback(RtcEngineEvents.AudioRouteChanged, routing.rawValue) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, cameraFocusDidChangedTo rect: CGRect) { + callback(RtcEngineEvents.CameraFocusAreaChanged, rect.toMap()) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, cameraExposureDidChangedTo rect: CGRect) { + callback(RtcEngineEvents.CameraExposureAreaChanged, rect.toMap()) + } + + func rtcEngine(_ engine: AgoraRtcEngineKit, facePositionDidChangeWidth width: Int32, previewHeight height: Int32, faces: [AgoraFacePositionInfo]?) { + callback(RtcEngineEvents.FacePositionChanged, width, height, faces?.toMapList()) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, reportRtcStats stats: AgoraChannelStats) { + callback(RtcEngineEvents.RtcStats, stats.toMap()) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, lastmileQuality quality: AgoraNetworkQuality) { + callback(RtcEngineEvents.LastmileQuality, quality.rawValue) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, networkQuality uid: UInt, txQuality: AgoraNetworkQuality, rxQuality: AgoraNetworkQuality) { + callback(RtcEngineEvents.NetworkQuality, uid, txQuality.rawValue, rxQuality.rawValue) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, lastmileProbeTest result: AgoraLastmileProbeResult) { + callback(RtcEngineEvents.LastmileProbeResult, result.toMap()) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, localVideoStats stats: AgoraRtcLocalVideoStats) { + callback(RtcEngineEvents.LocalVideoStats, stats.toMap()) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, localAudioStats stats: AgoraRtcLocalAudioStats) { + callback(RtcEngineEvents.LocalAudioStats, stats.toMap()) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, remoteVideoStats stats: AgoraRtcRemoteVideoStats) { + callback(RtcEngineEvents.RemoteVideoStats, stats.toMap()) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, remoteAudioStats stats: AgoraRtcRemoteAudioStats) { + callback(RtcEngineEvents.RemoteAudioStats, stats.toMap()) + } + + public func rtcEngineLocalAudioMixingDidFinish(_ engine: AgoraRtcEngineKit) { + callback(RtcEngineEvents.AudioMixingFinished) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, localAudioMixingStateDidChanged state: AgoraAudioMixingStateCode, errorCode: AgoraAudioMixingErrorCode) { + callback(RtcEngineEvents.AudioMixingStateChanged, state.rawValue, errorCode.rawValue) + } + + public func rtcEngineRemoteAudioMixingDidStart(_ engine: AgoraRtcEngineKit) { + // TODO Not in Android + } + + public func rtcEngineRemoteAudioMixingDidFinish(_ engine: AgoraRtcEngineKit) { + // TODO Not in Android + } + + public func rtcEngineDidAudioEffectFinish(_ engine: AgoraRtcEngineKit, soundId: Int) { + callback(RtcEngineEvents.AudioEffectFinished, soundId) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, rtmpStreamingChangedToState url: String, state: AgoraRtmpStreamingState, errorCode: AgoraRtmpStreamingErrorCode) { + callback(RtcEngineEvents.RtmpStreamingStateChanged, url, state.rawValue, errorCode.rawValue) + } + + public func rtcEngineTranscodingUpdated(_ engine: AgoraRtcEngineKit) { + callback(RtcEngineEvents.TranscodingUpdated) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, streamInjectedStatusOfUrl url: String, uid: UInt, status: AgoraInjectStreamStatus) { + callback(RtcEngineEvents.StreamInjectedStatus, url, uid, status.rawValue) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, receiveStreamMessageFromUid uid: UInt, streamId: Int, data: Data) { + callback(RtcEngineEvents.StreamMessage, uid, streamId, String(data: data, encoding: .utf8)) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, didOccurStreamMessageErrorFromUid uid: UInt, streamId: Int, error: Int, missed: Int, cached: Int) { + callback(RtcEngineEvents.StreamMessageError, uid, streamId, error, missed, cached) + } + + public func rtcEngineMediaEngineDidLoaded(_ engine: AgoraRtcEngineKit) { + callback(RtcEngineEvents.MediaEngineLoadSuccess) + } + + public func rtcEngineMediaEngineDidStartCall(_ engine: AgoraRtcEngineKit) { + callback(RtcEngineEvents.MediaEngineStartCallSuccess) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, channelMediaRelayStateDidChange state: AgoraChannelMediaRelayState, error: AgoraChannelMediaRelayError) { + callback(RtcEngineEvents.ChannelMediaRelayStateChanged, state.rawValue, error.rawValue) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, didReceive event: AgoraChannelMediaRelayEvent) { + callback(RtcEngineEvents.ChannelMediaRelayEvent, event.rawValue) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, firstRemoteVideoFrameOfUid uid: UInt, size: CGSize, elapsed: Int) { + callback(RtcEngineEvents.FirstRemoteVideoFrame, uid, size.width, size.height, elapsed) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, firstRemoteAudioFrameOfUid uid: UInt, elapsed: Int) { + callback(RtcEngineEvents.FirstRemoteAudioFrame, uid, elapsed) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, firstRemoteAudioFrameDecodedOfUid uid: UInt, elapsed: Int) { + callback(RtcEngineEvents.FirstRemoteAudioDecoded, uid, elapsed) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, didAudioMuted muted: Bool, byUid uid: UInt) { + callback(RtcEngineEvents.UserMuteAudio, uid, muted) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, streamPublishedWithUrl url: String, errorCode: AgoraErrorCode) { + callback(RtcEngineEvents.StreamPublished, url, errorCode.rawValue) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, streamUnpublishedWithUrl url: String) { + callback(RtcEngineEvents.StreamUnpublished, url) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, audioTransportStatsOfUid uid: UInt, delay: UInt, lost: UInt, rxKBitRate: UInt) { + callback(RtcEngineEvents.RemoteAudioTransportStats, uid, delay, lost, rxKBitRate) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, videoTransportStatsOfUid uid: UInt, delay: UInt, lost: UInt, rxKBitRate: UInt) { + callback(RtcEngineEvents.RemoteVideoTransportStats, uid, delay, lost, rxKBitRate) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, didVideoEnabled enabled: Bool, byUid uid: UInt) { + callback(RtcEngineEvents.UserEnableVideo, uid, enabled) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, didLocalVideoEnabled enabled: Bool, byUid uid: UInt) { + callback(RtcEngineEvents.UserEnableLocalVideo, uid, enabled) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, firstRemoteVideoDecodedOfUid uid: UInt, size: CGSize, elapsed: Int) { + callback(RtcEngineEvents.FirstRemoteVideoDecoded, uid, size.width, size.height, elapsed) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, didMicrophoneEnabled enabled: Bool) { + callback(RtcEngineEvents.MicrophoneEnabled, enabled) + } + + public func rtcEngineConnectionDidInterrupted(_ engine: AgoraRtcEngineKit) { + callback(RtcEngineEvents.ConnectionInterrupted) + } + + public func rtcEngineConnectionDidBanned(_ engine: AgoraRtcEngineKit) { + callback(RtcEngineEvents.ConnectionBanned) + } + + public func rtcEngine(_ engine: AgoraRtcEngineKit, audioQualityOfUid uid: UInt, quality: AgoraNetworkQuality, delay: UInt, lost: UInt) { + callback(RtcEngineEvents.AudioQuality, uid, quality.rawValue, delay, lost) + } + + public func rtcEngineCameraDidReady(_ engine: AgoraRtcEngineKit) { + callback(RtcEngineEvents.CameraReady) + } + + public func rtcEngineVideoDidStop(_ engine: AgoraRtcEngineKit) { + callback(RtcEngineEvents.VideoStopped) + } +} diff --git a/ios/RCTAgora/Base/RtcSurfaceView.swift b/ios/RCTAgora/Base/RtcSurfaceView.swift new file mode 100644 index 000000000..ab25b069c --- /dev/null +++ b/ios/RCTAgora/Base/RtcSurfaceView.swift @@ -0,0 +1,61 @@ +// +// RtcSurfaceView.swift +// RCTAgora +// +// Created by LXH on 2020/4/15. +// Copyright © 2020 Syan. All rights reserved. +// + +import Foundation +import UIKit +import AgoraRtcKit + +class RtcSurfaceView: UIView { + private lazy var canvas: AgoraRtcVideoCanvas = { + var canvas = AgoraRtcVideoCanvas() + canvas.view = self + return canvas + }() + private weak var channel: AgoraRtcChannel? + + func setRenderMode(_ engine: AgoraRtcEngineKit, _ renderMode: Int) { + canvas.renderMode = AgoraVideoRenderMode(rawValue: UInt(renderMode))! + setupRenderMode(engine) + } + + func setChannel(_ engine: AgoraRtcEngineKit, _ channel: AgoraRtcChannel?) { + self.channel = channel + canvas.channelId = channel?.getId() + if canvas.uid == 0 { + engine.setupLocalVideo(canvas) + } else { + engine.setupRemoteVideo(canvas) + } + } + + func setMirrorMode(_ engine: AgoraRtcEngineKit, _ mirrorMode: Int) { + canvas.mirrorMode = AgoraVideoMirrorMode(rawValue: UInt(mirrorMode))! + setupRenderMode(engine) + } + + func setUid(_ engine: AgoraRtcEngineKit, _ uid: Int) { + canvas.uid = UInt(uid) + if canvas.uid == 0 { + engine.setupLocalVideo(canvas) + } else { + engine.setupRemoteVideo(canvas) + } + } + + private func setupRenderMode(_ engine: AgoraRtcEngineKit) { + if canvas.uid == 0 { + engine.setLocalRenderMode(canvas.renderMode, mirrorMode: canvas.mirrorMode) + } else { + if let `channel` = channel { + channel.setRemoteRenderMode(canvas.uid, renderMode: canvas.renderMode, mirrorMode: canvas.mirrorMode) + } else { + engine.setRemoteRenderMode(canvas.uid, renderMode: canvas.renderMode, mirrorMode: canvas.mirrorMode) + } + } + } +} diff --git a/ios/RCTAgora/RCTAgora.h b/ios/RCTAgora/RCTAgora.h deleted file mode 100644 index bad2b71b5..000000000 --- a/ios/RCTAgora/RCTAgora.h +++ /dev/null @@ -1,20 +0,0 @@ -// -// RCTAgora.h -// RCTAgora -// -// Created by 邓博 on 2017/6/13. -// Copyright © 2017年 Syan. All rights reserved. -// - -#import -#import -#import -#import -#import - -@interface RCTAgora : RCTEventEmitter -- (void) sendEvent:(NSString *_Nullable)msg params:(NSDictionary *_Nullable)params; -- (NSInteger) metadataMaxSize; -- (NSData *_Nullable)readyToSendMetadataAtTimestamp:(NSTimeInterval)timestamp; -- (void)receiveMetadata:(NSData *_Nonnull)data fromUser:(NSInteger)uid atTimestamp:(NSTimeInterval)timestamp; -@end diff --git a/ios/RCTAgora/RCTAgora.m b/ios/RCTAgora/RCTAgora.m deleted file mode 100644 index 101a307ef..000000000 --- a/ios/RCTAgora/RCTAgora.m +++ /dev/null @@ -1,2302 +0,0 @@ -// -// RCTAgora.m -// RCTAgora -// -// Created by 邓博 on 2017/6/13. -// Copyright © 2017年 Syan. All rights reserved. -// - -#import "RCTAgora.h" -#import -#import -#import -#import -#import -#import "AgoraConst.h" - -#define MAX_DATA_LENGTH 1024 - -@interface RCTAgora () -@property (strong, nonatomic) AgoraRtcEngineKit *rtcEngine; -@property (strong, nonatomic) NSString *appId; -@property (strong, nonatomic) NSData *metadata; -@end - -@implementation RCTAgora { - RCTResponseSenderBlock _block; - BOOL hasListeners; -} - -+(BOOL)requiresMainQueueSetup { - return YES; -} - - -- (NSInteger) metadataMaxSize { - return MAX_DATA_LENGTH; -} - -- (NSData *_Nullable)readyToSendMetadataAtTimestamp:(NSTimeInterval)timestamp -{ - if (nil == _metadata) { - return nil; - } - NSData *toSend = [_metadata copy]; - if ([toSend length] > MAX_DATA_LENGTH) { - return nil; - } - _metadata = nil; - return toSend; -} - -- (void)receiveMetadata:(NSData *_Nonnull)data fromUser:(NSInteger)uid atTimestamp:(NSTimeInterval)timestamp { - NSString *dataStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; - [self sendEvent:AGMediaMetaDataReceived params:@{ - @"uid": @(uid), - @"data": dataStr, - @"ts": @(timestamp) - }]; -} - - -RCT_EXPORT_MODULE(); - -- (UIColor *) UIColorFromRGB:(NSUInteger)rgbValue { - return [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]; -} - -- (AgoraImage *) makeAgoraImage:(NSDictionary *)options { - AgoraImage *img = [AgoraImage new]; - img.url = [NSURL URLWithString:options[@"url"]]; - - img.rect = CGRectMake((CGFloat)[options[@"x"] floatValue], - (CGFloat)[options[@"y"] floatValue], - (CGFloat)[options[@"width"] floatValue], - (CGFloat)[options[@"height"] floatValue]); - return img; -} - -- (NSDictionary *)constantsToExport { - return @{ - @"FPS1": @(AgoraVideoFrameRateFps1), - @"FPS7": @(AgoraVideoFrameRateFps7), - @"FPS10": @(AgoraVideoFrameRateFps10), - @"FPS15": @(AgoraVideoFrameRateFps15), - @"FPS24": @(AgoraVideoFrameRateFps24), - @"FPS30": @(AgoraVideoFrameRateFps30), - @"FPS60": @(AgoraVideoFrameRateFps60), - @"Adaptative": @(AgoraVideoOutputOrientationModeAdaptative), - @"FixedLandscape": @(AgoraVideoOutputOrientationModeFixedLandscape), - @"FixedPortrait": @(AgoraVideoOutputOrientationModeFixedPortrait), - @"Host": @(AgoraClientRoleBroadcaster), - @"Audience": @(AgoraClientRoleAudience), - @"UserOfflineReasonQuit": @(AgoraUserOfflineReasonQuit), - @"UserOfflineReasonDropped": @(AgoraUserOfflineReasonDropped), - @"UserOfflineReasonBecomeAudience": @(AgoraUserOfflineReasonBecomeAudience), - @"CodecTypeBaseLine": @(AgoraVideoCodecProfileTypeBaseLine), - @"CodecTypeMain": @(AgoraVideoCodecProfileTypeMain), - @"CodecTypeHigh": @(AgoraVideoCodecProfileTypeHigh), - @"AudioSampleRateType32000": @(AgoraAudioSampleRateType32000), - @"AudioSampleRateType44100": @(AgoraAudioSampleRateType44100), - @"AudioSampleRateType48000": @(AgoraAudioSampleRateType48000), - @"QualityLow": @(AgoraAudioRecordingQualityLow), - @"QualityMedium": @(AgoraAudioRecordingQualityMedium), - @"QualityHigh": @(AgoraAudioRecordingQualityHigh), - @"Disconnected": @(AgoraConnectionStateDisconnected), - @"Connecting": @(AgoraConnectionStateConnecting), - @"Connected": @(AgoraConnectionStateConnected), - @"Reconnecting": @(AgoraConnectionStateReconnecting), - @"ConnectionFailed": @(AgoraConnectionStateFailed), - @"ConnectionChangedConnecting": @(AgoraConnectionChangedConnecting), - @"ConnectionChangedJoinSuccess": @(AgoraConnectionChangedJoinSuccess), - @"ConnectionChangedInterrupted": @(AgoraConnectionChangedInterrupted), - @"ConnectionChangedBannedByServer": @(AgoraConnectionChangedBannedByServer), - @"ConnectionChangedJoinFailed": @(AgoraConnectionChangedJoinFailed), - @"ConnectionChangedLeaveChannel": @(AgoraConnectionChangedLeaveChannel), - @"AudioOutputRoutingDefault": @(AgoraAudioOutputRoutingDefault), - @"AudioOutputRoutingHeadset": @(AgoraAudioOutputRoutingHeadset), - @"AudioOutputRoutingEarpiece": @(AgoraAudioOutputRoutingEarpiece), - @"AudioOutputRoutingHeadsetNoMic": @(AgoraAudioOutputRoutingHeadsetNoMic), - @"AudioOutputRoutingSpeakerphone": @(AgoraAudioOutputRoutingSpeakerphone), - @"AudioOutputRoutingLoudspeaker": @(AgoraAudioOutputRoutingLoudspeaker), - @"AudioOutputRoutingHeadsetBluetooth": @(AgoraAudioOutputRoutingHeadsetBluetooth), - @"NetworkQualityUnknown": @(AgoraNetworkQualityUnknown), - @"NetworkQualityExcellent": @(AgoraNetworkQualityExcellent), - @"NetworkQualityGood": @(AgoraNetworkQualityGood), - @"NetworkQualityPoor": @(AgoraNetworkQualityPoor), - @"NetworkQualityBad": @(AgoraNetworkQualityBad), - @"NetworkQualityVBad": @(AgoraNetworkQualityVBad), - @"NetworkQualityDown": @(AgoraNetworkQualityDown), - @"ErrorCodeNoError": @(AgoraErrorCodeNoError), - @"ErrorCodeFailed": @(AgoraErrorCodeFailed), - @"ErrorCodeInvalidArgument": @(AgoraErrorCodeInvalidArgument), - @"ErrorCodeTimedOut": @(AgoraErrorCodeTimedOut), - @"ErrorCodeAlreadyInUse": @(AgoraErrorCodeAlreadyInUse), - @"ErrorCodeAbort": @(AgoraErrorCodeAbort), - @"ErrorCodeResourceLimited": @(AgoraErrorCodeResourceLimited), - @"AudioProfileDefault": @(AgoraAudioProfileDefault), - @"AudioProfileSpeechStandard": @(AgoraAudioProfileSpeechStandard), - @"AudioProfileMusicStandard": @(AgoraAudioProfileMusicStandard), - @"AudioProfileMusicStandardStereo": @(AgoraAudioProfileMusicStandardStereo), - @"AudioProfileMusicHighQuality": @(AgoraAudioProfileMusicHighQuality), - @"AudioProfileMusicHighQualityStereo": @(AgoraAudioProfileMusicHighQualityStereo), - @"AudioScenarioDefault": @(AgoraAudioScenarioDefault), - @"AudioScenarioChatRoomEntertainment": @(AgoraAudioScenarioChatRoomEntertainment), - @"AudioScenarioEducation": @(AgoraAudioScenarioEducation), - @"AudioScenarioGameStreaming": @(AgoraAudioScenarioGameStreaming), - @"AudioScenarioShowRoom": @(AgoraAudioScenarioShowRoom), - @"AudioScenarioChatRoomGaming": @(AgoraAudioScenarioChatRoomGaming), - @"AudioEqualizationBand31": @(AgoraAudioEqualizationBand31), - @"AudioEqualizationBand62": @(AgoraAudioEqualizationBand62), - @"AudioEqualizationBand125": @(AgoraAudioEqualizationBand125), - @"AudioEqualizationBand250": @(AgoraAudioEqualizationBand250), - @"AudioEqualizationBand500": @(AgoraAudioEqualizationBand500), - @"AudioEqualizationBand1K": @(AgoraAudioEqualizationBand1K), - @"AudioEqualizationBand2K": @(AgoraAudioEqualizationBand2K), - @"AudioEqualizationBand4K": @(AgoraAudioEqualizationBand4K), - @"AudioEqualizationBand8K": @(AgoraAudioEqualizationBand8K), - @"AudioEqualizationBand16K": @(AgoraAudioEqualizationBand16K), - @"AudioRawFrameOperationModeReadOnly": @(AgoraAudioRawFrameOperationModeReadOnly), - @"AudioRawFrameOperationModeWriteOnly": @(AgoraAudioRawFrameOperationModeWriteOnly), - @"AudioRawFrameOperationModeReadWrite": @(AgoraAudioRawFrameOperationModeReadWrite), - @"VideoStreamTypeHigh": @(AgoraVideoStreamTypeHigh), - @"VideoStreamTypeLow": @(AgoraVideoStreamTypeLow), - @"VideoMirrorModeAuto": @(AgoraVideoMirrorModeAuto), - @"VideoMirrorModeEnabled": @(AgoraVideoMirrorModeEnabled), - @"VideoMirrorModeDisabled": @(AgoraVideoMirrorModeDisabled), - @"ChannelProfileCommunication": @(AgoraChannelProfileCommunication), - @"ChannelProfileLiveBroadcasting": @(AgoraChannelProfileLiveBroadcasting), - @"ChannelProfileGame": @(AgoraChannelProfileGame), - @"AudioMode": @(AgoraAudioMode), - @"VideoMode": @(AgoraVideoMode), - }; -} - -// init -RCT_EXPORT_METHOD(init:(NSDictionary *)options) { - [self startObserving]; - [AgoraConst share].appid = options[@"appid"]; - - self.rtcEngine = [AgoraRtcEngineKit sharedEngineWithAppId:options[@"appid"] delegate:self]; - self.appId = options[@"appid"]; - - [AgoraConst share].rtcEngine = self.rtcEngine; - - [self.rtcEngine setAppType:AgoraRtc_APP_TYPE_REACTNATIVE]; - //channel mode - [self.rtcEngine setChannelProfile:[options[@"channelProfile"] integerValue]]; - //enable dual stream - if ([options objectForKey:@"dualStream"]) { - [self.rtcEngine enableDualStreamMode:[options[@"dualStream"] boolValue]]; - } - dispatch_sync(dispatch_get_main_queue(), ^{ - [self.rtcEngine enableVideo]; - [self.rtcEngine enableAudio]; - }); - if ([options objectForKey:@"mode"]) { - switch([options[@"mode"] integerValue]) { - case AgoraAudioMode: { - [self.rtcEngine enableLocalAudio:true]; - [self.rtcEngine enableLocalVideo:false]; - break; - } - case AgoraVideoMode: { - [self.rtcEngine enableLocalVideo:true]; - [self.rtcEngine enableLocalAudio:false]; - break; - } - } - } else { - [self.rtcEngine enableLocalVideo:true]; - [self.rtcEngine enableLocalAudio:true]; - } - - if ([options objectForKey:@"beauty"]) { - AgoraBeautyOptions *beautyOption = [[AgoraBeautyOptions alloc] init]; - beautyOption.lighteningContrastLevel = [options[@"beauty"][@"lighteningContrastLevel"] integerValue]; - beautyOption.lighteningLevel = [options[@"beauty"][@"lighteningLevel"] floatValue]; - beautyOption.smoothnessLevel = [options[@"beauty"][@"smoothnessLevel"] floatValue]; - beautyOption.rednessLevel = [options[@"beauty"][@"rednessLevel"] floatValue]; - [self.rtcEngine setBeautyEffectOptions:true options:beautyOption]; - } - if ([options objectForKey:@"voice"]) { - NSInteger voiceValue = [options[@"voice"][@"value"] integerValue]; - NSString *voiceType = options[@"voice"][@"type"]; - if ([voiceType isEqualToString: @"changer"]) { - [self.rtcEngine setLocalVoiceChanger:(AgoraAudioVoiceChanger)voiceValue]; - } - if ([voiceType isEqualToString: @"reverbPreset"]) { - [self.rtcEngine setLocalVoiceReverbPreset:(AgoraAudioReverbPreset)voiceValue]; - } - } - if (options[@"secret"] != nil) { - [self.rtcEngine setEncryptionSecret:options[@"secret"]]; - if (options[@"secretMode"] != nil) { - [self.rtcEngine setEncryptionMode:options[@"secretMode"]]; - } - } - - AgoraVideoEncoderConfiguration *video_encoder_config = [[AgoraVideoEncoderConfiguration new] initWithWidth:[options[@"videoEncoderConfig"][@"width"] integerValue] height:[options[@"videoEncoderConfig"][@"height"] integerValue] frameRate:[options[@"videoEncoderConfig"][@"frameRate"] integerValue] bitrate:[options[@"videoEncoderConfig"][@"bitrate"] integerValue] orientationMode: (AgoraVideoOutputOrientationMode)[options[@"videoEncoderConfig"][@"orientationMode"] integerValue]]; - [self.rtcEngine setVideoEncoderConfiguration:video_encoder_config]; - [self.rtcEngine setClientRole:(AgoraClientRole)[options[@"clientRole"] integerValue]]; - [self.rtcEngine setAudioProfile:(AgoraAudioProfile)[options[@"audioProfile"] integerValue] - scenario:(AgoraAudioScenario)[options[@"audioScenario"] integerValue]]; - - //Enable Agora Native SDK be Interoperable with Agora Web SDK - [self.rtcEngine enableWebSdkInteroperability:YES]; -} - -// renew token -RCT_EXPORT_METHOD(renewToken - :(NSString *)token - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine renewToken:token]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// enable websdk interoperability -RCT_EXPORT_METHOD(enableWebSdkInteroperability: (BOOL)enabled - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine enableWebSdkInteroperability:enabled]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// get agora connection state -RCT_EXPORT_METHOD(getConnectionState - :(RCTPromiseResolveBlock) resolve - reject:(RCTPromiseRejectBlock) reject) { - resolve(@{@"state": @([self.rtcEngine getConnectionState])}); -} - -// set client role -RCT_EXPORT_METHOD(setClientRole:(NSInteger)role - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine setClientRole:(AgoraClientRole)role]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// join channel -RCT_EXPORT_METHOD(joinChannel:(NSDictionary *)options - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - [AgoraConst share].localUid = (NSUInteger)[options[@"uid"] integerValue]; - NSInteger res = [self.rtcEngine joinChannelByToken:options[@"token"] channelId:options[@"channelName"] info:options[@"info"] uid:[AgoraConst share].localUid joinSuccess:nil]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// switch channel -RCT_EXPORT_METHOD(switchChannel:(NSDictionary *)options - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine switchChannelByToken:options[@"token"] channelId:options[@"channelName"] joinSuccess:nil]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// startChannelMediaRelay -RCT_EXPORT_METHOD(startChannelMediaRelay:(NSDictionary *)options - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - AgoraChannelMediaRelayConfiguration *config = [[AgoraChannelMediaRelayConfiguration alloc] init]; - AgoraChannelMediaRelayInfo *src = [config sourceInfo]; - NSDictionary *srcOption = options[@"src"]; - if (srcOption != nil) { - src.channelName = srcOption[@"channelName"]; - src.uid = [srcOption[@"uid"] integerValue]; - src.token = srcOption[@"token"]; - } - NSArray *channels = options[@"channels"]; - for (NSDictionary *channel in channels) { - AgoraChannelMediaRelayInfo *dst = [[AgoraChannelMediaRelayInfo alloc] init]; - dst.channelName = channel[@"channelName"]; - dst.uid = [channel[@"uid"] integerValue]; - dst.token = channel[@"token"]; - [config setDestinationInfo:dst forChannelName:dst.channelName]; - } - NSInteger res = [self.rtcEngine startChannelMediaRelay:config]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// updateChannelMediaRelay -RCT_EXPORT_METHOD(updateChannelMediaRelay:(NSDictionary *)options - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - AgoraChannelMediaRelayConfiguration *config = [[AgoraChannelMediaRelayConfiguration alloc] init]; - AgoraChannelMediaRelayInfo *src = [config sourceInfo]; - NSDictionary *srcOption = options[@"src"]; - if (srcOption != nil) { - src.channelName = srcOption[@"channelName"]; - src.uid = [srcOption[@"uid"] integerValue]; - src.token = srcOption[@"token"]; - } - NSArray *channels = options[@"channels"]; - for (NSDictionary *channel in channels) { - AgoraChannelMediaRelayInfo *dst = [[AgoraChannelMediaRelayInfo alloc] init]; - dst.channelName = channel[@"channelName"]; - dst.uid = [channel[@"uid"] integerValue]; - dst.token = channel[@"token"]; - [config setDestinationInfo:dst forChannelName:dst.channelName]; - } - NSInteger res = [self.rtcEngine updateChannelMediaRelay:config]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// removeChannelMediaRelay -RCT_EXPORT_METHOD(removeChannelMediaRelay:(NSDictionary *)options - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - AgoraChannelMediaRelayConfiguration *config = [[AgoraChannelMediaRelayConfiguration alloc] init]; - AgoraChannelMediaRelayInfo *src = [config sourceInfo]; - NSDictionary *srcOption = options[@"src"]; - if (srcOption != nil) { - src.channelName = srcOption[@"channelName"]; - src.uid = [srcOption[@"uid"] integerValue]; - src.token = srcOption[@"token"]; - } - NSArray *channels = options[@"channels"]; - for (NSDictionary *channel in channels) { - if (channel[@"channelName"] != nil) { - [config removeDestinationInfoForChannelName:channel[@"channelName"]]; - } - } - NSInteger res = [self.rtcEngine updateChannelMediaRelay:config]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// stopChannelMediaRelay -RCT_EXPORT_METHOD(stopChannelMediaRelay:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine stopChannelMediaRelay]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// register user account -RCT_EXPORT_METHOD(registerLocalUserAccount:(NSDictionary *)options - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine registerLocalUserAccount:options[@"userAccount"] appId:self.appId]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// join channel with user account -RCT_EXPORT_METHOD(joinChannelWithUserAccount:(NSDictionary *)options - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSString *token = [options objectForKey:@"token"] != nil ? options[@"token"] : nil; - NSInteger res = [self.rtcEngine joinChannelByUserAccount:options[@"userAccount"] token:token channelId:options[@"channelName"] joinSuccess:nil]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// get user info by uid -RCT_EXPORT_METHOD(getUserInfoByUid:(NSUInteger)uid - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - AgoraErrorCode code = 0; - AgoraUserInfo *info = [self.rtcEngine getUserInfoByUid:uid withError:&code]; - if ((int)code == 0) { - resolve(@{ - @"uid": @(info.uid), - @"userAccount": info.userAccount - }); - } else { - reject(@(-1).stringValue, @((int)code).stringValue, nil); - } -} - -// get user info by user account -RCT_EXPORT_METHOD(getUserInfoByUserAccount:(NSString *)userAccount - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - AgoraErrorCode code = 0; - AgoraUserInfo *info = [self.rtcEngine getUserInfoByUserAccount:userAccount withError:&code]; - if ((int)code == 0) { - resolve(@{ - @"uid": @(info.uid), - @"userAccount": info.userAccount - }); - } else { - reject(@(-1).stringValue, @((int)code).stringValue, nil); - } -} - -// leave channel -RCT_EXPORT_METHOD(leaveChannel - :(RCTPromiseResolveBlock) resolve - reject:(RCTPromiseRejectBlock) reject) { - NSInteger res = [self.rtcEngine leaveChannel:nil]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// destroy -RCT_EXPORT_METHOD(destroy) { - [self stopObserving]; - [AgoraRtcEngineKit destroy]; -} - -// set local video render mode -RCT_EXPORT_METHOD(setLocalRenderMode:(NSInteger) mode - :(RCTPromiseResolveBlock) resolve - reject:(RCTPromiseRejectBlock) reject) { - NSInteger res = [self.rtcEngine setLocalRenderMode:mode]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// set remote video render mode -RCT_EXPORT_METHOD(setRemoteRenderMode:(NSUInteger) uid - mode:(NSInteger) mode - resolve:(RCTPromiseResolveBlock) resolve - reject:(RCTPromiseRejectBlock) reject) { - NSInteger res = [self.rtcEngine setRemoteRenderMode:uid mode:mode]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// start video preview -RCT_EXPORT_METHOD(startPreview - :(RCTPromiseResolveBlock) resolve - reject:(RCTPromiseRejectBlock) reject) { - NSInteger res = [self.rtcEngine startPreview]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// stop video preview -RCT_EXPORT_METHOD(stopPreview - :(RCTPromiseResolveBlock) resolve - reject:(RCTPromiseRejectBlock) reject) { - NSInteger res = [self.rtcEngine stopPreview]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -/* enable speaker phone - * @params enableSpeaker: BOOL - YES: Audio output to speaker - No: Audio output to the handset - */ -RCT_EXPORT_METHOD(setEnableSpeakerphone:(BOOL)enableSpeaker - :(RCTPromiseResolveBlock) resolve - reject:(RCTPromiseRejectBlock) reject) { - NSInteger res = [self.rtcEngine setEnableSpeakerphone: enableSpeaker]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -/* set default audio speaker - * @params defaultToSpeaker: BOOL - YES: Audio output to speaker - No: Audio output to the handset - */ -RCT_EXPORT_METHOD(setDefaultAudioRouteToSpeakerphone:(BOOL)defaultToSpeaker - resolve:(RCTPromiseResolveBlock) resolve - reject:(RCTPromiseRejectBlock) reject) { - NSInteger res = [self.rtcEngine setDefaultAudioRouteToSpeakerphone:defaultToSpeaker]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -RCT_EXPORT_METHOD(setDefaultMuteAllRemoteAudioStreams:(BOOL)defaultToSpeaker - resolve:(RCTPromiseResolveBlock) resolve - reject:(RCTPromiseRejectBlock) reject) { - NSInteger res = [self.rtcEngine setDefaultMuteAllRemoteAudioStreams:defaultToSpeaker]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// enable video -RCT_EXPORT_METHOD(enableVideo:(RCTPromiseResolveBlock) resolve - reject:(RCTPromiseRejectBlock) reject) { - NSInteger res = [self.rtcEngine enableVideo]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// disable Video -RCT_EXPORT_METHOD(disableVideo:(RCTPromiseResolveBlock) resolve - reject:(RCTPromiseRejectBlock) reject) { - NSInteger res = [self.rtcEngine disableVideo]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// enable local video -RCT_EXPORT_METHOD(enableLocalVideo:(BOOL)enabled - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine enableLocalVideo:enabled]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// mute local video stream -RCT_EXPORT_METHOD(muteLocalVideoStream:(BOOL)muted - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine muteLocalVideoStream:muted]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// mute all remote video streams -RCT_EXPORT_METHOD(muteAllRemoteVideoStreams:(BOOL)muted - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine muteAllRemoteVideoStreams:muted]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// mute video stream by uid -RCT_EXPORT_METHOD(muteRemoteVideoStream:(NSUInteger)uid mute:(BOOL)mute - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine muteRemoteVideoStream:uid mute:mute]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -RCT_EXPORT_METHOD(setDefaultMuteAllRemoteVideoStreams:(BOOL)mute - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine setDefaultMuteAllRemoteVideoStreams:mute]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// enable audio -RCT_EXPORT_METHOD(enableAudio:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine enableAudio]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// disable audio -RCT_EXPORT_METHOD(disableAudio:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine disableAudio]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// enable local audio -RCT_EXPORT_METHOD(enableLocalAudio:(BOOL)enabled - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine enableLocalAudio:enabled]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// mute local audio stream -RCT_EXPORT_METHOD(muteLocalAudioStream:(BOOL)mute - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine muteLocalAudioStream:mute]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// mute all remote audio stream -RCT_EXPORT_METHOD(muteAllRemoteAudioStreams:(BOOL)mute - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine muteAllRemoteAudioStreams:mute]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// mute one remote audio stream by uid -RCT_EXPORT_METHOD(muteRemoteAudioStream:(NSUInteger)uid muted:(BOOL)mute - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine muteRemoteAudioStream:uid mute:mute]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// adjust recorcding signal volume -RCT_EXPORT_METHOD(adjustRecordingSignalVolume: (NSInteger) volume - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine adjustRecordingSignalVolume:volume]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// adjust playback signal volume -RCT_EXPORT_METHOD(adjustPlaybackSignalVolume: (NSInteger) volume - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine adjustPlaybackSignalVolume:volume]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// enable audio volume indication -RCT_EXPORT_METHOD(enableAudioVolumeIndication: (NSInteger) interval smooth:(NSInteger)smooth - report_vad:(BOOL)report_vad - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine enableAudioVolumeIndication:interval smooth:smooth report_vad:report_vad]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// is speaker phone enabled -RCT_EXPORT_METHOD(isSpeakerphoneEnabled:(RCTResponseSenderBlock)callback) { - callback(@[@{@"status": @([self.rtcEngine isSpeakerphoneEnabled])}]); -} - -// enable in ear monitoring -RCT_EXPORT_METHOD(enableInEarMonitoring:(BOOL)enabled - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine enableInEarMonitoring:enabled]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// set in ear monitoring -RCT_EXPORT_METHOD(setInEarMonitoringVolume:(NSInteger) volume - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine setInEarMonitoringVolume:volume]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// set local voice pitch -RCT_EXPORT_METHOD(setLocalVoicePitch:(double) pitch - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine setLocalVoicePitch:pitch]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// set local video equalization of band frequency -RCT_EXPORT_METHOD(setLocalVoiceEqualization:(NSInteger)band - gain:(NSInteger)gain - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine setLocalVoiceEqualizationOfBandFrequency:(AgoraAudioEqualizationBandFrequency)band withGain:gain]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// set local voice reverb of type -RCT_EXPORT_METHOD(setLocalVoiceReverb:(NSInteger)reverb value:(NSInteger)value - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine setLocalVoiceReverbOfType:(AgoraAudioReverbType)reverb withValue:value]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// start audio mixing -RCT_EXPORT_METHOD(startAudioMixing:(NSDictionary *) options - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine startAudioMixing:options[@"filepath"] - loopback:[options[@"loopback"] boolValue] - replace:[options[@"replace"] boolValue] - cycle:[options[@"cycle"] integerValue]]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// stop audio mixing -RCT_EXPORT_METHOD(stopAudioMixing:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine stopAudioMixing]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// pause audio mixing -RCT_EXPORT_METHOD(pauseAudioMixing:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine pauseAudioMixing]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// resume audio mixing -RCT_EXPORT_METHOD(resumeAudioMixing:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine resumeAudioMixing]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// adjust audio mixing volume -RCT_EXPORT_METHOD(adjustAudioMixingVolume:(NSInteger) volume - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine adjustAudioMixingVolume:volume]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// adjust audio mixing playout volume -RCT_EXPORT_METHOD(adjustAudioMixingPlayoutVolume:(NSInteger) volume - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine adjustAudioMixingPlayoutVolume:volume]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// adjust audio mixing publish volume -RCT_EXPORT_METHOD(adjustAudioMixingPublishVolume:(NSInteger) volume - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine adjustAudioMixingPublishVolume:volume]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// get audio mixing duration -RCT_EXPORT_METHOD(getAudioMixingDuration - :(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine getAudioMixingDuration]; - if (res >= 0) { - resolve(@(res)); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// get the volume of local audio mixing -RCT_EXPORT_METHOD(getAudioMixingPlayoutVolume - :(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine getAudioMixingPlayoutVolume]; - if (res >= 0) { - resolve(@(res)); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// get the volume of remote audio mixing -RCT_EXPORT_METHOD(getAudioMixingPublishVolume - :(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [_rtcEngine getAudioMixingPublishVolume]; - if (res >= 0) { - resolve(@(res)); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - - -// get audio mixing current position -RCT_EXPORT_METHOD(getAudioMixingCurrentPosition - :(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine getAudioMixingDuration]; - if (res >= 0) { - resolve(@(res)); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// set audio mixing position -RCT_EXPORT_METHOD(setAudioMixingPosition - :(NSInteger) pos - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine setAudioMixingPosition:pos]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// get effects volume -RCT_EXPORT_METHOD(getEffectsVolume - :(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - double res = [self.rtcEngine getEffectsVolume]; - if (res >= 0) { - resolve(@(res)); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// set effects volume -RCT_EXPORT_METHOD(setEffectsVolume - :(double) volume - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine setEffectsVolume:volume]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// set volume of effect -RCT_EXPORT_METHOD(setVolumeOfEffect - :(int) soundId - volume:(double)volume - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine setVolumeOfEffect:soundId withVolume:volume]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// play effect -RCT_EXPORT_METHOD(playEffect - :(NSDictionary *)options - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine playEffect:(int)[options[@"soundid"] integerValue] - filePath:options[@"filepath"] - loopCount:(int)[options[@"loopcount"] integerValue] - pitch:[options[@"pitch"] doubleValue] - pan:[options[@"pan"] doubleValue] - gain:[options[@"gain"] doubleValue] - publish:[options[@"publish"] boolValue]]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// stop effect by soundId -RCT_EXPORT_METHOD(stopEffect - :(NSInteger) soundId - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine stopEffect:(int)soundId]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// stopAllEffects -RCT_EXPORT_METHOD(stopAllEffects - :(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine stopAllEffects]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// preloadEffect -RCT_EXPORT_METHOD(preloadEffect - :(NSInteger) soundId - filePath:(NSString *)filePath - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine preloadEffect:(int)soundId filePath:filePath]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// unload effect -RCT_EXPORT_METHOD(unloadEffect - :(NSInteger) soundId - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine unloadEffect:(int)soundId]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// pause effect by id -RCT_EXPORT_METHOD(pauseEffect - :(NSInteger) soundId - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine pauseEffect:(int)soundId]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// pause all effects -RCT_EXPORT_METHOD(pauseAllEffects - :(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine pauseAllEffects]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// resume effect by id -RCT_EXPORT_METHOD(resumeEffect:(NSInteger) soundId - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine resumeEffect:(int)soundId]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// resume all effect -RCT_EXPORT_METHOD(resumeAllEffects - :(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine resumeAllEffects]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// start audio recording quality -RCT_EXPORT_METHOD(startAudioRecording:(NSDictionary *)options - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - AgoraAudioRecordingQuality qualityType = (AgoraAudioRecordingQuality)[options[@"quality"] integerValue]; - NSInteger res = [self.rtcEngine startAudioRecording:options[@"filepath"] quality:qualityType]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// stop audio recording -RCT_EXPORT_METHOD(stopAudioRecording - :(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine stopAudioRecording]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// set audio session operation restriction -RCT_EXPORT_METHOD(setAudioSessionOperationRestriction - :(NSInteger) restriction) { - AgoraAudioSessionOperationRestriction restrictionType = (AgoraAudioSessionOperationRestriction)restriction; - [self.rtcEngine setAudioSessionOperationRestriction:restrictionType]; -} - -// gateway test stop echo -RCT_EXPORT_METHOD(stopEchoTest - :(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine stopEchoTest]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// enable last mile test -RCT_EXPORT_METHOD(enableLastmileTest - :(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine enableLastmileTest]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// disable last mile test -RCT_EXPORT_METHOD(disableLastmileTest - :(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine disableLastmileTest]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// set recording audioframe parameters with samplerate -RCT_EXPORT_METHOD(setRecordingAudioFrameParameters:(NSDictionary *) options - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine setRecordingAudioFrameParametersWithSampleRate:[options[@"sampleRate"] integerValue] - channel:[options[@"channel"] integerValue] - mode:(AgoraAudioRawFrameOperationMode)[options[@"mode"] integerValue] - samplesPerCall:[options[@"samplesPerCall"] integerValue] - ]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// set playback audioframe parameters with samplerate -RCT_EXPORT_METHOD(setPlaybackAudioFrameParameters:(NSDictionary *) options - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine setPlaybackAudioFrameParametersWithSampleRate:[options[@"sampleRate"] integerValue] - channel:[options[@"channel"] integerValue] - mode:(AgoraAudioRawFrameOperationMode)[options[@"mode"] integerValue] - samplesPerCall:[options[@"samplesPerCall"] integerValue] - ]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// set mixed audio frame parameters with sample rate -RCT_EXPORT_METHOD(setMixedAudioFrameParametersWithSampleRate - :(NSDictionary *)options - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine setMixedAudioFrameParametersWithSampleRate:[options[@"sampleRate"] integerValue] samplesPerCall:[options[@"samplesPerCall"] integerValue]]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// add video watermark -RCT_EXPORT_METHOD(addVideoWatermark:(NSDictionary *)options - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSString *urlStr = options[@"url"]; - NSDictionary *watermarkOptions = options[@"options"]; - WatermarkOptions *watermarkOpts = [WatermarkOptions new]; - watermarkOpts.visibleInPreview = [watermarkOptions[@"visibleInPreview"] boolValue]; - NSDictionary *optionPortrait = watermarkOptions[@"positionInPortraitMode"]; - watermarkOpts.positionInPortraitMode = CGRectMake((CGFloat)[optionPortrait[@"x"] floatValue], - (CGFloat)[optionPortrait[@"y"] floatValue], - (CGFloat)[optionPortrait[@"width"] floatValue], - (CGFloat)[optionPortrait[@"height"] floatValue]); - NSDictionary *optionLandscape = watermarkOptions[@"positionInLandscapeMode"]; - watermarkOpts.positionInLandscapeMode = CGRectMake((CGFloat)[optionLandscape[@"x"] floatValue], - (CGFloat)[optionLandscape[@"y"] floatValue], - (CGFloat)[optionLandscape[@"width"] floatValue], - (CGFloat)[optionLandscape[@"height"] floatValue]); - NSURL *url = [NSURL URLWithString:urlStr]; - NSInteger res = [self.rtcEngine addVideoWatermark:url options:watermarkOpts]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// clear video watermark -RCT_EXPORT_METHOD(clearVideoWatermarks - :(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine clearVideoWatermarks]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// set local publish fallback option -RCT_EXPORT_METHOD(setLocalPublishFallbackOption:(NSInteger)option - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine setLocalPublishFallbackOption:option]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// set remote subscribe fallback option -RCT_EXPORT_METHOD(setRemoteSubscribeFallbackOption:(NSInteger)option - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine setRemoteSubscribeFallbackOption:option]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - - -// enable dual stream mode -RCT_EXPORT_METHOD(enableDualStreamMode - :(BOOL) enabled - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine enableDualStreamMode:enabled]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// set remote video stream -RCT_EXPORT_METHOD(setRemoteVideoStreamType - :(NSDictionary *) options - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine setRemoteVideoStream:[options[@"uid"] integerValue] - type:(AgoraVideoStreamType)[options[@"streamType"] integerValue]]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// set remote default video stream -RCT_EXPORT_METHOD(setRemoteDefaultVideoStreamType - :(NSDictionary *) options - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine setRemoteDefaultVideoStreamType:(AgoraVideoStreamType)[options[@"streamType"] integerValue]]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// add injection stream url -RCT_EXPORT_METHOD(addInjectStreamUrl - :(NSDictionary *)options - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - AgoraLiveInjectStreamConfig *config = [AgoraLiveInjectStreamConfig new]; - config.size = CGSizeMake([options[@"config"][@"size"][@"width"] floatValue], [options[@"config"][@"size"][@"height"] floatValue]); - config.videoGop = [options[@"config"][@"videoGop"] integerValue]; - config.videoFramerate = [options[@"config"][@"videoFramerate"] integerValue]; - config.videoBitrate = [options[@"config"][@"videoBitrate"] integerValue]; - config.audioSampleRate = (AgoraAudioSampleRateType)[options[@"config"][@"audioSampleRate"] integerValue]; - config.audioBitrate = [options[@"config"][@"audioBitrate"] integerValue]; - config.audioChannels = [options[@"config"][@"audioChannels"] integerValue]; - - NSInteger res = [self.rtcEngine addInjectStreamUrl:options[@"url"] - config:config]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// remove injection stream url -RCT_EXPORT_METHOD(removeInjectStreamUrl - :(NSString *)url - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - - NSInteger res = [self.rtcEngine removeInjectStreamUrl:url]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// set local video mirror mode -RCT_EXPORT_METHOD(setLocalVideoMirrorMode - :(NSInteger) mode - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine setLocalVideoMirrorMode:(AgoraVideoMirrorMode) mode]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// switchCamera -RCT_EXPORT_METHOD(switchCamera - :(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine switchCamera]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// getCameraInfo -RCT_EXPORT_METHOD(getCameraInfo - :(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - resolve(@{ - @"support": @{ - @"zoom": @([self.rtcEngine isCameraZoomSupported]), - @"torch": @([self.rtcEngine isCameraTorchSupported]), - @"focusPositionInPreview": @([self.rtcEngine isCameraFocusPositionInPreviewSupported]), - @"exposurePosition": @([self.rtcEngine isCameraExposurePositionSupported]), - @"autoFocusFaceMode": @([self.rtcEngine isCameraAutoFocusFaceModeSupported]) - } - }); -} - -// setCameraZoomFactor -RCT_EXPORT_METHOD(setCameraZoomFactor - :(float)zoomFactor - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - BOOL res = [self.rtcEngine setCameraZoomFactor:(CGFloat)zoomFactor]; - if (res) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// setCameraFocusPositionInPreview -RCT_EXPORT_METHOD(setCameraFocusPositionInPreview - :(NSDictionary *)options - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - BOOL res = [self.rtcEngine setCameraFocusPositionInPreview:CGPointMake((CGFloat)[options[@"x"] floatValue], (CGFloat)[options[@"y"] floatValue])]; - if (res) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// setCameraExposurePosition -RCT_EXPORT_METHOD(setCameraExposurePosition - :(NSDictionary *)options - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - BOOL res = [self.rtcEngine setCameraExposurePosition:CGPointMake((CGFloat)[options[@"x"] floatValue], (CGFloat)[options[@"y"] floatValue])]; - if (res == YES) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// enable camera torch -RCT_EXPORT_METHOD(setCameraTorchOn:(BOOL)isOn - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - BOOL res = [self.rtcEngine setCameraTorchOn:isOn]; - if (res == YES) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// enable auto focus face mode -RCT_EXPORT_METHOD(setCameraAutoFocusFaceModeEnabled:(BOOL)enable - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - BOOL res = [self.rtcEngine setCameraAutoFocusFaceModeEnabled:enable]; - if (res == YES) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// getCallId -RCT_EXPORT_METHOD(getCallId - :(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - resolve(@{ - @"id": [self.rtcEngine getCallId] - }); -} - -// setLogFile and setLogFilter -RCT_EXPORT_METHOD(setLog - :(NSString *)filePath - level:(NSUInteger)level - size:(NSUInteger)size - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine setLogFileSize:size]; - if (res < 0) return reject(@(-1).stringValue, @(res).stringValue, nil); - res = [self.rtcEngine setLogFilter:level]; - if (res < 0) return reject(@(-1).stringValue, @(res).stringValue, nil); - res = [self.rtcEngine setLogFile:filePath]; - if (res < 0) return reject(@(-1).stringValue, @(res).stringValue, nil); - resolve(nil); -} - -// get sdk version -RCT_EXPORT_METHOD(getSdkVersion - :(RCTPromiseResolveBlock) resolve - reject:(RCTPromiseRejectBlock) reject) { - resolve(@[[AgoraRtcEngineKit getSdkVersion]]); -} - -// add publish stream url -RCT_EXPORT_METHOD(addPublishStreamUrl:(NSDictionary *)options - resolve:(RCTPromiseResolveBlock) resolve - reject:(RCTPromiseRejectBlock) reject) { - NSInteger res = [self.rtcEngine addPublishStreamUrl:options[@"url"] transcodingEnabled:[options[@"enable"] boolValue]]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// remove publish stream url -RCT_EXPORT_METHOD(removePublishStreamUrl:(NSDictionary *)options - resolve:(RCTPromiseResolveBlock) resolve - reject:(RCTPromiseRejectBlock) reject) { - NSInteger res = [self.rtcEngine removePublishStreamUrl:options[@"url"]]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -// set living transcoding -RCT_EXPORT_METHOD(setLiveTranscoding:(NSDictionary *)options - resolve:(RCTPromiseResolveBlock) resolve - reject:(RCTPromiseRejectBlock) reject) { - AgoraLiveTranscoding *transcoding = AgoraLiveTranscoding.defaultTranscoding; - if ([options objectForKey:@"size"]) { - transcoding.size = CGSizeMake([options[@"size"][@"width"] doubleValue], [options[@"size"][@"height"] doubleValue]); - } - if ([options objectForKey:@"videoBitrate"]) { - transcoding.videoBitrate = [options[@"videoBitrate"] integerValue]; - } - if ([options objectForKey:@"videoFramerate"]) { - transcoding.videoFramerate = [options[@"videoFramerate"] integerValue]; - } - if ([options objectForKey:@"videoGop"]) { - transcoding.videoGop = [options[@"videoGop"] integerValue]; - } - if ([options objectForKey:@"videoCodecProfile"]) { - transcoding.videoCodecProfile = (AgoraVideoCodecProfileType)[options[@"videoCodecProfile"] integerValue]; - } - if ([options objectForKey:@"audioCodecProfile"]) { - transcoding.audioCodecProfile = (AgoraAudioCodecProfileType)[options[@"audioCodecProfile"] integerValue]; - } - if ([options objectForKey:@"audioSampleRate"]) { - transcoding.audioSampleRate = (AgoraAudioSampleRateType)[options[@"audioSampleRate"] integerValue]; - } - if ([options objectForKey:@"watermark"]) { - transcoding.watermark = [self makeAgoraImage:@{ - @"url": options[@"watermark"][@"url"], - @"x": options[@"watermark"][@"x"], - @"y": options[@"watermark"][@"y"], - @"width": options[@"watermark"][@"width"], - @"height": options[@"watermark"][@"height"] - }]; - } - if ([options objectForKey:@"backgroundImage"]) { - transcoding.backgroundImage = [self makeAgoraImage:@{ - @"url": options[@"backgroundImage"][@"url"], - @"x": options[@"backgroundImage"][@"x"], - @"y": options[@"backgroundImage"][@"y"], - @"width": options[@"backgroundImage"][@"width"], - @"height": options[@"backgroundImage"][@"height"] - }]; - } - - if ([options objectForKey:@"backgroundColor"]) { - transcoding.backgroundColor = [self UIColorFromRGB:(NSUInteger)[options[@"backgroundColor"] integerValue]]; - } - - if ([options objectForKey:@"audioBitrate"]) { - transcoding.audioBitrate = [options[@"audioBitrate"] integerValue]; - } - - if ([options objectForKey:@"audioChannels"]) { - transcoding.audioChannels = [options[@"audioChannels"] integerValue]; - } - - if ([options objectForKey:@"transcodingUsers"]) { - NSMutableArray *transcodingUsers = [NSMutableArray new]; - for (NSDictionary *optionUser in options[@"transcodingUsers"]) { - AgoraLiveTranscodingUser *liveUser = [AgoraLiveTranscodingUser new]; - liveUser.uid = (NSUInteger)[optionUser[@"uid"] integerValue]; - liveUser.rect = CGRectMake((CGFloat)[optionUser[@"x"] floatValue], - (CGFloat)[optionUser[@"y"] floatValue], - (CGFloat)[optionUser[@"width"] floatValue], - (CGFloat)[optionUser[@"height"] floatValue]); - liveUser.zOrder = [optionUser[@"zOrder"] integerValue]; - liveUser.alpha = [optionUser[@"alpha"] doubleValue]; - liveUser.audioChannel = [optionUser[@"audioChannel"] integerValue]; - [transcodingUsers addObject:liveUser]; - } - transcoding.transcodingUsers = transcodingUsers; - } - if ([options objectForKey:@"transcodingExtraInfo"]) { - transcoding.transcodingExtraInfo = options[@"transcodingExtraInfo"]; - } - - NSInteger res = [self.rtcEngine setLiveTranscoding:transcoding]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -RCT_EXPORT_METHOD(setBeautyEffectOptions:(BOOL) enabled - options:(NSDictionary *)options - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - AgoraBeautyOptions *beautyOption = [[AgoraBeautyOptions alloc] init]; - beautyOption.lighteningContrastLevel = [options[@"lighteningContrastLevel"] integerValue]; - beautyOption.lighteningLevel = [options[@"lighteningLevel"] floatValue]; - beautyOption.smoothnessLevel = [options[@"smoothnessLevel"] floatValue]; - beautyOption.rednessLevel = [options[@"rednessLevel"] floatValue]; - NSInteger res = [self.rtcEngine setBeautyEffectOptions:enabled options:beautyOption]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -RCT_EXPORT_METHOD(setLocalVoiceChanger:(NSInteger) voiceChanger - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine setLocalVoiceChanger:(AgoraAudioVoiceChanger)voiceChanger]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -RCT_EXPORT_METHOD(setLocalVoiceReverbPreset:(NSInteger) reverbPreset - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine setLocalVoiceReverbPreset:(AgoraAudioReverbPreset)reverbPreset]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -RCT_EXPORT_METHOD(enableSoundPositionIndication:(BOOL) enabled - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine enableSoundPositionIndication:enabled]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -RCT_EXPORT_METHOD(setRemoteVoicePosition:(NSUInteger) uid - pan:(float)pan - gain:(float)gain - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine setRemoteVoicePosition:uid pan:pan gain: gain]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -RCT_EXPORT_METHOD(startLastmileProbeTest:(NSDictionary*)config - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - AgoraLastmileProbeConfig* probeConfig = [[AgoraLastmileProbeConfig alloc] init]; - probeConfig.probeUplink = [config[@"probeUplink"] boolValue]; - probeConfig.probeDownlink = [config[@"probeDownlink"] boolValue]; - probeConfig.expectedUplinkBitrate = [config[@"expectedUplinkBitrate"] integerValue]; - probeConfig.expectedDownlinkBitrate = [config[@"expectedDownlinkBitrate"] integerValue]; - - NSInteger res = [self.rtcEngine startLastmileProbeTest:probeConfig]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - - -RCT_EXPORT_METHOD(setRemoteUserPriority:(NSUInteger)uid - userPriority:(NSInteger)userPriority - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - - NSInteger res = [self.rtcEngine setRemoteUserPriority:uid type:(AgoraUserPriority)userPriority]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -RCT_EXPORT_METHOD(startEchoTestWithInterval:(NSInteger)interval - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - - NSInteger res = [self.rtcEngine startEchoTestWithInterval:interval successBlock:^(NSString * _Nonnull channel, NSUInteger uid, NSInteger elapsed) { - [self sendEvent:AGIntervalTest params:@{ - @"channel": channel, - @"uid": @(uid), - @"elapsed": @(elapsed), - }]; - }]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -RCT_EXPORT_METHOD(setCameraCapturerConfiguration:(NSDictionary *)config - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - - AgoraCameraCapturerConfiguration* configuration = [[AgoraCameraCapturerConfiguration alloc] init]; - configuration.preference = [config[@"preference"] integerValue]; - configuration.cameraDirection = [config[@"cameraDirection"] integerValue]; - - NSInteger res = [self.rtcEngine setCameraCapturerConfiguration:configuration]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -RCT_EXPORT_METHOD(sendMediaData:(NSString *)dataStr - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - BOOL res = [self respondsToSelector:@selector(readyToSendMetadataAtTimestamp:)]; - if (res == YES) { - self.metadata = [dataStr dataUsingEncoding:NSUTF8StringEncoding]; - resolve(nil); - } else { - reject(@(-1).stringValue, @(res).stringValue, nil); - } -} - -RCT_EXPORT_METHOD(registerMediaMetadataObserver - :(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - if (YES == [_rtcEngine setMediaMetadataDataSource:self withType:AgoraMetadataTypeVideo] && - YES == [_rtcEngine setMediaMetadataDelegate:self withType:AgoraMetadataTypeVideo] - ) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(-1).stringValue, nil); - } -} - -RCT_EXPORT_METHOD(setParameters:(NSString *)paramStr - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSInteger res = [self.rtcEngine setParameters:paramStr]; - if (res == 0) { - resolve(nil); - } else { - reject(@(-1).stringValue, @(-1).stringValue, nil); - } -} - -RCT_EXPORT_METHOD(getParameter:(NSString *)paramStr - args:(NSString *)args - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSString *res = [self.rtcEngine getParameter:paramStr args:args]; - resolve(res); -} - -RCT_EXPORT_METHOD(getParameters:(NSString *)paramStr - resolve:(RCTPromiseResolveBlock)resolve - reject:(RCTPromiseRejectBlock)reject) { - NSString *res = [self.rtcEngine getParameters:paramStr]; - resolve(res); -} - -- (NSArray *)supportedEvents { - return [AgoraConst supportEvents]; -} - -- (void) sendEvent:(NSString *)msg params:(NSDictionary *)params { - if (hasListeners) { - NSString *evtName = [NSString stringWithFormat:@"%@%@", AG_PREFIX, msg]; - [self sendEventWithName:evtName body:params]; - } -} - -- (void) startObserving { - hasListeners = YES; -} - -- (void) stopObserving { - hasListeners = NO; -} - -#pragma mark - -// EVENT CALLBACKS -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine didOccurWarning:(AgoraWarningCode)warningCode { - [self sendEvent:AGWarning params:@{@"errorCode": @(warningCode)}]; -} - -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine didOccurError:(AgoraErrorCode)errorCode { - [self sendEvent:AGError params:@{@"errorCode": @(errorCode)}]; -} - -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine didApiCallExecute:(NSInteger)error api:(NSString *_Nonnull)api result:(NSString *_Nonnull)result { - if (error != 0) { - [self sendEvent:AGError params:@{ - @"api": api, - @"result": result, - @"errorCode": @(error) - }]; - } else { - [self sendEvent:AGApiCallExecute params:@{ - @"api": api, - @"result": result, - @"errorCode": @(error) - }]; - } -} - -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine didJoinChannel:(NSString *_Nonnull)channel withUid:(NSUInteger)uid elapsed:(NSInteger)elapsed { - [self sendEvent:AGJoinChannelSuccess params:@{ - @"channel": channel, - @"uid": @(uid), - @"elapsed": @(elapsed) - }]; -} - -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine didRejoinChannel:(NSString *_Nonnull)channel withUid:(NSUInteger)uid elapsed:(NSInteger)elapsed { - [self sendEvent:AGRejoinChannelSuccess params:@{ - @"channel": channel, - @"uid": @(uid), - @"elapsed": @(elapsed) - }]; -} - -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine didLeaveChannelWithStats:(AgoraChannelStats *_Nonnull)stats { - [self sendEvent:AGLeaveChannel params:@{ - @"stats": @{ - @"duration": @(stats.duration), - @"txBytes": @(stats.txBytes), - @"rxBytes": @(stats.rxBytes), - @"txAudioBytes": @(stats.txAudioBytes), - @"txVideoBytes": @(stats.txVideoBytes), - @"rxAudioBytes": @(stats.rxAudioBytes), - @"rxVideoBytes": @(stats.rxVideoBytes), - @"txPacketLossRate": @(stats.txPacketLossRate), - @"rxPacketLossRate": @(stats.rxPacketLossRate), - @"txAudioKBitrate": @(stats.txAudioKBitrate), - @"rxAudioKBitrate": @(stats.rxVideoKBitrate), - @"txVideoKBitrate": @(stats.txVideoKBitrate), - @"rxVideoKBitrate": @(stats.rxVideoKBitrate), - @"lastmileDelay": @(stats.lastmileDelay), - @"userCount": @(stats.userCount), - @"cpuAppUsage": @(stats.cpuAppUsage), - @"cpuTotalUsage": @(stats.cpuTotalUsage) - } - }]; -} - -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine didClientRoleChanged:(AgoraClientRole)oldRole newRole:(AgoraClientRole)newRole { - [self sendEvent:AGClientRoleChanged params:@{ - @"oldRole": @(oldRole), - @"newRole": @(newRole) - }]; -} - -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine didJoinedOfUid:(NSUInteger)uid elapsed:(NSInteger)elapsed { - [self sendEvent:AGUserJoined params:@{ - @"uid": @(uid), - @"elapsed": @(elapsed) - }]; -} - -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine didRegisteredLocalUser:(NSString *_Nonnull)userAccount withUid:(NSUInteger)uid { - [self sendEvent:AGLocalUserRegistered params:@{ - @"uid": @(uid), - @"userAccount": userAccount - }]; -} - -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine didUpdatedUserInfo:(AgoraUserInfo *_Nonnull)userInfo withUid:(NSUInteger)uid { - [self sendEvent:AGUserInfoUpdated params:@{ - @"uid": @(uid), - @"peer": @{ - @"uid": @(userInfo.uid), - @"userAccount": userInfo.userAccount - }}]; -} - - -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine didOfflineOfUid:(NSUInteger)uid reason:(AgoraUserOfflineReason)reason { - [self sendEvent:AGUserOffline params:@{ - @"uid": @(uid), - @"reason": @(reason) - }]; -} - -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine networkTypeChangedToType:(AgoraNetworkType)type { - [self sendEvent:AGNetworkTypeChanged params:@{ - @"type": @(type) - }]; -} - -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine connectionChangedToState:(AgoraConnectionStateType)state reason:(AgoraConnectionChangedReason)reason { - [self sendEvent:AGConnectionStateChanged params:@{ - @"state": @(state), - @"reason": @(reason) - }]; -} - -- (void)rtcEngineConnectionDidLost:(AgoraRtcEngineKit *_Nonnull)engine { - [self sendEvent:AGConnectionLost params:nil]; -} - -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine tokenPrivilegeWillExpire:(NSString *_Nonnull)token { - [self sendEvent:AGTokenPrivilegeWillExpire params:@{ - @"token": token - }]; -} - -- (void)rtcEngineRequestToken:(AgoraRtcEngineKit *_Nonnull)engine { - [self sendEvent:AGRequestToken params:nil]; -} - -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine localAudioStateChange:(AgoraAudioLocalState)state error:(AgoraAudioLocalError)error { - [self sendEvent:AGLocalAudioStateChanged params:@{ - @"state": @(state), - @"errorCode": @(error) - }]; -} - -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine remoteAudioStateChangedOfUid:(NSUInteger)uid state:(AgoraAudioRemoteState)state reason:(AgoraAudioRemoteStateReason)reason elapsed:(NSInteger)elapsed { - [self sendEvent:AGRemoteAudioStateChanged params:@{ - @"uid": @(uid), - @"state": @(state), - @"reason": @(reason), - @"elapsed": @(elapsed) - }]; -} - -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine localAudioStats:(AgoraRtcLocalAudioStats *_Nonnull)stats { - [self sendEvent:AGLocalAudioStats params:@{ - @"numChannels": @(stats.numChannels), - @"sentSampleRate": @(stats.sentSampleRate), - @"sentBitrate": @(stats.sentBitrate), - }]; -} - -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine reportAudioVolumeIndicationOfSpeakers:(NSArray *_Nonnull)speakers totalVolume:(NSInteger)totalVolume { - NSMutableArray *result = [NSMutableArray new]; - for (AgoraRtcAudioVolumeInfo *speaker in speakers) { - [result addObject:@{ - @"uid": @(speaker.uid), - @"volume": @(speaker.volume), - @"vad": @(speaker.vad), - }]; - } - [self sendEvent:AGAudioVolumeIndication params:@{ - @"speakers": result, - @"totalVolume": @(totalVolume) - }]; -} - -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine activeSpeaker:(NSUInteger)speakerUid { - [self sendEvent:AGActiveSpeaker params:@{ - @"uid": @(speakerUid) - }]; -} - -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine firstLocalAudioFrame:(NSInteger)elapsed { - [self sendEvent:AGFirstLocalAudioFrame params:@{ - @"elapsed": @(elapsed) - }]; -} - -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine firstRemoteAudioFrameOfUid:(NSUInteger)uid elapsed:(NSInteger)elapsed { - [self sendEvent:AGFirstRemoteAudioFrame params:@{ - @"uid": @(uid), - @"elapsed": @(elapsed) - }]; -} - -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine firstRemoteAudioFrameDecodedOfUid:(NSUInteger)uid elapsed:(NSInteger)elapsed { - [self sendEvent:AGFirstRemoteAudioDecoded params:@{ - @"uid": @(uid), - @"elapsed": @(elapsed) - }]; -} - -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine firstLocalVideoFrameWithSize:(CGSize)size elapsed:(NSInteger)elapsed { - [self sendEvent:AGFirstLocalVideoFrame params:@{ - @"width": @(size.width), - @"height": @(size.height), - @"elapsed": @(elapsed) - }]; -} - -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine firstRemoteVideoFrameOfUid:(NSUInteger)uid size:(CGSize)size elapsed:(NSInteger)elapsed { - [self sendEvent:AGFirstRemoteVideoFrame params:@{ - @"uid": @(uid), - @"width": @(size.width), - @"height": @(size.height), - @"elapsed": @(elapsed)}]; -} - -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine didAudioMuted:(BOOL)muted byUid:(NSUInteger)uid { - [self sendEvent:AGUserMuteAudio params:@{ - @"muted": @(muted), - @"uid": @(uid) - }]; -} - -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine videoSizeChangedOfUid:(NSUInteger)uid size:(CGSize)size rotation:(NSInteger)rotation { - [self sendEvent:AGVideoSizeChanged params:@{ - @"uid": @(uid), - @"width": @(size.width), - @"height": @(size.height), - @"rotation": @(rotation) - }]; -} - -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine remoteVideoStateChangedOfUid:(NSUInteger)uid state:(AgoraVideoRemoteState)state reason:(AgoraVideoRemoteStateReason)reason elapsed:(NSInteger)elapsed { - [self sendEvent:AGRemoteVideoStateChanged params:@{ - @"uid": @(uid), - @"state": @(state), - @"reason": @(reason), - @"elapsed": @(elapsed) - }]; -} - -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine didLocalPublishFallbackToAudioOnly:(BOOL)isFallbackOrRecover { - [self sendEvent:AGLocalPublishFallbackToAudioOnly params:@{ - @"isFallbackOrRecover": @(isFallbackOrRecover) - }]; -} - -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine didRemoteSubscribeFallbackToAudioOnly:(BOOL)isFallbackOrRecover byUid:(NSUInteger)uid { - [self sendEvent:AGRemoteSubscribeFallbackToAudioOnly params:@{ - @"isFallbackOrRecover": @(isFallbackOrRecover), - @"uid": @(uid) - }]; -} - -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine didAudioRouteChanged:(AgoraAudioOutputRouting)routing { - [self sendEvent:AGAudioRouteChanged params:@{ - @"routing": @(routing) - }]; -} - -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine cameraFocusDidChangedToRect:(CGRect)rect { - [self sendEvent:AGCameraFocusAreaChanged params:@{ - @"rect": @(rect) - }]; -} - -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine cameraExposureDidChangedToRect:(CGRect)rect { - [self sendEvent:AGCameraExposureAreaChanged params:@{ - @"rect": @(rect) - }]; -} - -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine remoteAudioStats:(AgoraRtcRemoteAudioStats *_Nonnull)stats { - [self sendEvent:AGRemoteAudioStats params:@{ - @"stats": @{ - @"uid": @(stats.uid), - @"quality": @(stats.quality), - @"networkTransportDelay": @(stats.networkTransportDelay), - @"jitterBufferDelay": @(stats.jitterBufferDelay), - @"audioLossRate": @(stats.audioLossRate), - @"totalFrozenTime": @(stats.totalFrozenTime), - @"frozenRate": @(stats.frozenRate), - @"numChannels": @(stats.numChannels), - @"receivedSampleRate": @(stats.receivedSampleRate), - @"receivedBitrate": @(stats.receivedBitrate), - } - }]; -} - -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine reportRtcStats:(AgoraChannelStats *_Nonnull)stats { - [self sendEvent:AGRtcStats params:@{ - @"stats": @{ - @"duration": @(stats.duration), - @"txBytes": @(stats.txBytes), - @"rxBytes": @(stats.rxBytes), - @"txAudioBytes": @(stats.txAudioBytes), - @"txVideoBytes": @(stats.txVideoBytes), - @"rxAudioBytes": @(stats.rxAudioBytes), - @"rxVideoBytes": @(stats.rxVideoBytes), - @"txPacketLossRate": @(stats.txPacketLossRate), - @"rxPacketLossRate": @(stats.rxPacketLossRate), - @"txAudioKBitrate": @(stats.txAudioKBitrate), - @"rxAudioKBitrate": @(stats.rxAudioKBitrate), - @"txVideoKBitrate": @(stats.txVideoKBitrate), - @"rxVideoKBitrate": @(stats.rxVideoKBitrate), - @"lastmileDelay": @(stats.lastmileDelay), - @"userCount": @(stats.userCount), - @"cpuAppUsage": @(stats.cpuAppUsage), - @"cpuTotalUsage": @(stats.cpuTotalUsage) - } - }]; -} - -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine lastmileQuality:(AgoraNetworkQuality)quality { - [self sendEvent:AGLastmileQuality params:@{ - @"quality": @(quality) - }]; -} - -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine networkQuality:(NSUInteger)uid txQuality:(AgoraNetworkQuality)txQuality rxQuality:(AgoraNetworkQuality)rxQuality { - [self sendEvent:AGNetworkQuality params:@{ - @"uid": @(uid), - @"txQuality": @(txQuality), - @"rxQuality": @(rxQuality) - }]; -} - -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine localVideoStats:(AgoraRtcLocalVideoStats *_Nonnull)stats { - [self sendEvent:AGLocalVideoStats params:@{ - @"stats": @{ - @"sentBitrate": @(stats.sentBitrate), - @"sentFrameRate": @(stats.sentFrameRate) - }, - @"encoderOutputFrameRate": @(stats.encoderOutputFrameRate), - @"rendererOutputFrameRate": - @(stats.rendererOutputFrameRate) - }]; -} - -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine remoteVideoStats:(AgoraRtcRemoteVideoStats *_Nonnull)stats { - [self sendEvent:AGRemoteVideoStats params:@{ - @"stats": @{ - @"uid": @(stats.uid), - @"width": @(stats.width), - @"height": @(stats.height), - @"receivedBitrate": @(stats.receivedBitrate), - @"rendererOutputFrameRate": @(stats.rendererOutputFrameRate), - @"rxStreamType": @(stats.rxStreamType), - @"decoderOutputFrameRate": @(stats.decoderOutputFrameRate), - @"totalFrozenTime": @(stats.totalFrozenTime), - @"frozenRate": @(stats.frozenRate) - } - }]; -} - -- (void)rtcEngineRemoteAudioMixingDidStart:(AgoraRtcEngineKit *_Nonnull)engine { - [self sendEvent:AGRemoteAudioMixingStart params:nil]; -} - -- (void)rtcEngineRemoteAudioMixingDidFinish:(AgoraRtcEngineKit *_Nonnull)engine { - [self sendEvent:AGRemoteAudioMixingFinish params:nil]; -} - -- (void)rtcEngineDidAudioEffectFinish:(AgoraRtcEngineKit *_Nonnull)engine soundId:(NSInteger)soundId { - [self sendEvent:AGAudioEffectFinish params:@{ - @"soundid": @(soundId) - }]; -} - -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine streamPublishedWithUrl:(NSString *_Nonnull)url errorCode:(AgoraErrorCode)errorCode { - [self sendEvent:AGStreamPublished params:@{ - @"url": url, - @"errorCode": @(errorCode) - }]; -} - -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine rtmpStreamingChangedToState:(NSString *_Nonnull)url state:(AgoraRtmpStreamingState)state errorCode:(AgoraRtmpStreamingErrorCode)errorCode { - [self sendEvent:AGRtmpStreamingStateChanged params:@{ - @"url": url, - @"state": @(state), - @"errorCode": @(errorCode) - }]; -} - -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine streamUnpublishedWithUrl:(NSString *_Nonnull)url { - [self sendEvent:AGStreamUnpublish params:@{ - @"url": url, - }]; -} - -- (void)rtcEngineTranscodingUpdated:(AgoraRtcEngineKit *_Nonnull)engine { - [self sendEvent:AGTranscodingUpdate params:nil]; -} - -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine localVideoStateChange:(AgoraLocalVideoStreamState)state error:(AgoraLocalVideoStreamError)error { - [self sendEvent:AGLocalVideoChanged params:@{ - @"state": @(state), - @"errorCode": @(error) - }]; -} - -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine streamInjectedStatusOfUrl:(NSString *_Nonnull)url uid:(NSUInteger)uid status:(AgoraInjectStreamStatus)status { - [self sendEvent:AGStreamInjectedStatus params:@{ - @"uid": @(uid), - @"url": url, - @"status": @(status) - }]; -} - -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine channelMediaRelayStateDidChange:(AgoraChannelMediaRelayState)state error:(AgoraChannelMediaRelayError)error { - [self sendEvent:AGMediaRelayStateChanged params:@{ - @"state": @(state), - @"errorCode": @(error), - }]; -} - -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine didReceiveChannelMediaRelayEvent:(AgoraChannelMediaRelayEvent)event { - [self sendEvent:AGReceivedChannelMediaRelay params:@{ - @"event": @(event), - }]; -} - -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine receiveStreamMessageFromUid:(NSUInteger)uid streamId:(NSInteger)streamId data:(NSData *_Nonnull)data { - NSString *_data = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; - [self sendEvent:AGReceiveStreamMessage params:@{ - @"uid": @(uid), - @"streamId": @(streamId), - @"data": _data}]; -} - -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine didOccurStreamMessageErrorFromUid:(NSUInteger)uid streamId:(NSInteger)streamId error:(NSInteger)error missed:(NSInteger)missed cached:(NSInteger)cached { - [self sendEvent:AGOccurStreamMessageError params:@{ - @"uid": @(uid), - @"streamId": @(streamId), - @"errorCode": @(error), - @"missed": @(missed), - @"cached": @(cached) - }]; -} - -- (void)rtcEngineMediaEngineDidLoaded:(AgoraRtcEngineKit *_Nonnull)engine { - [self sendEvent:AGMediaEngineLoaded params:nil]; -} - -- (void)rtcEngineMediaEngineDidStartCall:(AgoraRtcEngineKit *_Nonnull)engine { - [self sendEvent:AGMediaEngineStartCall params:nil]; -} - -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine localAudioMixingStateDidChanged:(AgoraAudioMixingStateCode)state errorCode:(AgoraAudioMixingErrorCode)errorCode { - [self sendEvent:AGAudioMixingStateChanged params:@{ - @"state": @(state), - @"errorCode": @(errorCode) - }]; -} - -- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine lastmileProbeTestResult:(AgoraLastmileProbeResult *_Nonnull)result { - [self sendEvent:AGLastmileProbeTestResult params:@{ - @"result": @{ - @"state": @(result.state), - @"rtt": @(result.rtt), - @"uplinkReport": @{ - @"packetLossRate": @(result.uplinkReport.packetLossRate), - @"jitter": @(result.uplinkReport.jitter), - @"availableBandwidth": @(result.uplinkReport.availableBandwidth), - }, - @"downlinkReport": @{ - @"packetLossRate": @(result.downlinkReport.packetLossRate), - @"jitter": @(result.downlinkReport.jitter), - @"availableBandwidth": @(result.downlinkReport.availableBandwidth), - } - } - }]; -} - -@end diff --git a/ios/RCTAgora/RCTAgoraVideoView.h b/ios/RCTAgora/RCTAgoraVideoView.h deleted file mode 100644 index d5141d4e6..000000000 --- a/ios/RCTAgora/RCTAgoraVideoView.h +++ /dev/null @@ -1,19 +0,0 @@ -// -// RCTAgoraVideoView.h -// RCTAgora -// -// Created by 邓博 on 2017/6/30. -// Copyright © 2017年 Syan. All rights reserved. -// - -#import -#import "AgoraConst.h" - -@interface RCTAgoraVideoView : UIView - -@property (strong, nonatomic) AgoraRtcEngineKit *rtcEngine; -@property (nonatomic) BOOL showLocalVideo; -@property (nonatomic) NSUInteger remoteUid; -@property (nonatomic) NSInteger renderMode; - -@end diff --git a/ios/RCTAgora/RCTAgoraVideoView.m b/ios/RCTAgora/RCTAgoraVideoView.m deleted file mode 100644 index 864237d09..000000000 --- a/ios/RCTAgora/RCTAgoraVideoView.m +++ /dev/null @@ -1,61 +0,0 @@ -// -// RCTAgoraVideoView.m -// RCTAgora -// -// Created by 邓博 on 2017/6/30. -// Copyright © 2017年 Syan. All rights reserved. -// - -#import "RCTAgoraVideoView.h" -#import - -@implementation RCTAgoraVideoView - -- (instancetype)init{ - - if (self == [super init]) { - _rtcEngine = [AgoraConst share].rtcEngine; - _renderMode = AgoraVideoRenderModeHidden; - } - - return self; -} - -- (void)setRenderMode:(NSInteger)renderMode { - _renderMode = renderMode; -} - -- (void)setShowLocalVideo:(BOOL)showLocalVideo { - _showLocalVideo = showLocalVideo; - if (_showLocalVideo) { - AgoraRtcVideoCanvas *canvas = [[AgoraRtcVideoCanvas alloc] init]; - canvas.uid = [AgoraConst share].localUid; - canvas.view = self; - canvas.renderMode = _renderMode; - [_rtcEngine setupLocalVideo:canvas]; - } -} - --(void)setRemoteUid:(NSUInteger)remoteUid { - _remoteUid = remoteUid; - if (_remoteUid != 0) { - AgoraRtcVideoCanvas *canvas = [[AgoraRtcVideoCanvas alloc] init]; - canvas.uid = _remoteUid; - canvas.view = self; - canvas.renderMode = _renderMode; - [_rtcEngine setupRemoteVideo:canvas]; - } -} - --(void) didMoveToWindow { - [super didMoveToWindow]; - if (self.window != nil) { - if (_remoteUid > 0) { - [_rtcEngine setRemoteRenderMode:_remoteUid mode:_renderMode]; - } else { - [_rtcEngine setLocalRenderMode:_renderMode]; - } - } -} - -@end diff --git a/ios/RCTAgora/RCTAgoraViewManager.h b/ios/RCTAgora/RCTAgoraViewManager.h deleted file mode 100644 index 733b7ea79..000000000 --- a/ios/RCTAgora/RCTAgoraViewManager.h +++ /dev/null @@ -1,13 +0,0 @@ -// -// AgoraViewManager.h -// RCTAgora -// -// Created by 邓博 on 2017/6/30. -// Copyright © 2017年 Syan. All rights reserved. -// - -#import - -@interface RCTAgoraViewManager : RCTViewManager - -@end diff --git a/ios/RCTAgora/RCTAgoraViewManager.m b/ios/RCTAgora/RCTAgoraViewManager.m deleted file mode 100644 index 96501c7ee..000000000 --- a/ios/RCTAgora/RCTAgoraViewManager.m +++ /dev/null @@ -1,33 +0,0 @@ -// -// AgoraViewManager.m -// RCTAgora -// -// Created by 邓博 on 2017/6/30. -// Copyright © 2017年 Syan. All rights reserved. -// - -#import "RCTAgoraViewManager.h" -#import "RCTAgoraVideoView.h" - -@implementation RCTAgoraViewManager - -RCT_EXPORT_MODULE(RCTAgoraVideoView) - -RCT_CUSTOM_VIEW_PROPERTY(mode, NSInteger, RCTAgoraVideoView) { - view.renderMode = [RCTConvert NSInteger:json]; -} - -RCT_CUSTOM_VIEW_PROPERTY(showLocalVideo, BOOL, RCTAgoraVideoView) { - view.showLocalVideo = [RCTConvert BOOL:json]; -} - -RCT_CUSTOM_VIEW_PROPERTY(remoteUid, NSInteger, RCTAgoraVideoView) { - view.remoteUid = [RCTConvert NSInteger:json]; -} - -- (UIView *)view { - return [RCTAgoraVideoView new]; -} - - -@end diff --git a/ios/RCTAgora/React/PromiseCallback.swift b/ios/RCTAgora/React/PromiseCallback.swift new file mode 100644 index 000000000..a6c1dfa58 --- /dev/null +++ b/ios/RCTAgora/React/PromiseCallback.swift @@ -0,0 +1,29 @@ +// +// PromiseCallback.swift +// RCTAgora +// +// Created by LXH on 2020/4/13. +// Copyright (c) 2020 Syan. All rights reserved. +// + +import Foundation +import AgoraRtcKit + +@objc(PromiseCallback) +class PromiseCallback: NSObject, Callback { + private var resolve: RCTPromiseResolveBlock? + private var reject: RCTPromiseRejectBlock? + + init(_ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + self.resolve = resolve + self.reject = reject + } + + func success(_ data: Any?) { + resolve?(data) + } + + func failure(_ code: String, _ message: String) { + reject?(code, message, nil) + } +} diff --git a/ios/RCTAgora/React/RCTAgora-bridging-header.h b/ios/RCTAgora/React/RCTAgora-bridging-header.h new file mode 100644 index 000000000..b530229cc --- /dev/null +++ b/ios/RCTAgora/React/RCTAgora-bridging-header.h @@ -0,0 +1,7 @@ +// +// Use this file to import your target's public headers that you would like to expose to Swift. +// +#import +#import +#import +#import "AgoraRtcEngineKit.h" diff --git a/ios/RCTAgora/React/RCTAgoraRtcChannelModule.swift b/ios/RCTAgora/React/RCTAgoraRtcChannelModule.swift new file mode 100644 index 000000000..2059314f5 --- /dev/null +++ b/ios/RCTAgora/React/RCTAgoraRtcChannelModule.swift @@ -0,0 +1,390 @@ +// +// RCTAgoraRtcChannelModule.swift +// RCTAgora +// +// Created by LXH on 2020/4/15. +// Copyright (c) 2020 Syan. All rights reserved. +// + +import Foundation +import AgoraRtcKit + +@objc(RCTAgoraRtcChannelModule) +class RCTAgoraRtcChannelModule: RCTEventEmitter, RtcChannelInterface { + static let REACT_CLASS = "RCTAgoraRtcChannelModule" + + typealias Map = NSDictionary + typealias Callback = PromiseCallback + + private var hasListeners = false + + private lazy var manager: RtcChannelManager = { + RtcChannelManager() + }() + + override class func moduleName() -> String! { + RCTAgoraRtcChannelModule.REACT_CLASS + } + + override func constantsToExport() -> [AnyHashable: Any]! { + ["prefix": RtcChannelEventHandler.PREFIX] + } + + deinit { + manager.release() + } + + override class func requiresMainQueueSetup() -> Bool { + true + } + + override var methodQueue: DispatchQueue! { + DispatchQueue.main + } + + override func supportedEvents() -> [String]! { + var events = [String]() + RtcChannelEvents.toMap().forEach { key, value in + events.append("\(RtcChannelEventHandler.PREFIX)\(value)") + } + return events + } + + override func startObserving() { + hasListeners = true + } + + override func stopObserving() { + hasListeners = false + } + + private func emit(_ methodName: String, _ data: Dictionary?) { + if hasListeners { + sendEvent(withName: "\(RtcChannelEventHandler.PREFIX)\(methodName)", body: data) + } + } + + private func engine() -> AgoraRtcEngineKit? { + (bridge.module(for: RCTAgoraRtcEngineModule.classForCoder()) as? RCTAgoraRtcEngineModule)?.engine + } + + func channel(_ channelId: String) -> AgoraRtcChannel? { + manager[channelId] + } + + func create(_ channelId: String, _ callback: PromiseCallback?) { + callback?.resolve(engine()) { (engine: AgoraRtcEngineKit) in + manager.create(engine, channelId) { [weak self] (methodName, data) in + self?.emit(methodName, data) + } + } + } + + func destroy(_ channelId: String, _ callback: PromiseCallback?) { + callback?.code(manager.destroy(channelId)) + } + + func setClientRole(_ channelId: String, _ role: Int, _ callback: PromiseCallback?) { + callback?.code(channel(channelId)?.setClientRole(AgoraClientRole(rawValue: role)!)) + } + + func joinChannel(_ channelId: String, _ token: String?, _ optionalInfo: String?, _ optionalUid: Int, _ options: NSDictionary, _ callback: PromiseCallback?) { + callback?.code(channel(channelId)?.join(byToken: token, info: optionalInfo, uid: UInt(optionalUid), options: mapToChannelMediaOptions(options as! Dictionary))) + } + + func joinChannelWithUserAccount(_ channelId: String, _ token: String?, _ userAccount: String, _ options: NSDictionary, _ callback: PromiseCallback?) { + callback?.code(channel(channelId)?.join(byUserAccount: userAccount, token: token, options: mapToChannelMediaOptions(options as! Dictionary))) + } + + func leaveChannel(_ channelId: String, _ callback: PromiseCallback?) { + callback?.code(channel(channelId)?.leave()) + } + + func renewToken(_ channelId: String, _ token: String, _ callback: PromiseCallback?) { + callback?.code(channel(channelId)?.renewToken(token)) + } + + func getConnectionState(_ channelId: String, _ callback: PromiseCallback?) { + callback?.resolve(channel(channelId)) { (channel: AgoraRtcChannel) in + channel.getConnectionState() + } + } + + func publish(_ channelId: String, _ callback: PromiseCallback?) { + callback?.code(channel(channelId)?.publish()) + } + + func unpublish(_ channelId: String, _ callback: PromiseCallback?) { + callback?.code(channel(channelId)?.unpublish()) + } + + func getCallId(_ channelId: String, _ callback: PromiseCallback?) { + callback?.resolve(channel(channelId)) { (channel: AgoraRtcChannel) in + channel.getCallId() + } + } + + func adjustUserPlaybackSignalVolume(_ channelId: String, _ uid: Int, _ volume: Int, _ callback: PromiseCallback?) { + callback?.code(channel(channelId)?.adjustUserPlaybackSignalVolume(UInt(uid), volume: Int32(volume))) + } + + func muteRemoteAudioStream(_ channelId: String, _ uid: Int, _ muted: Bool, _ callback: PromiseCallback?) { + callback?.code(channel(channelId)?.muteRemoteAudioStream(UInt(uid), mute: muted)) + } + + func muteAllRemoteAudioStreams(_ channelId: String, _ muted: Bool, _ callback: PromiseCallback?) { + callback?.code(channel(channelId)?.muteAllRemoteAudioStreams(muted)) + } + + func setDefaultMuteAllRemoteAudioStreams(_ channelId: String, _ muted: Bool, _ callback: PromiseCallback?) { + callback?.code(channel(channelId)?.setDefaultMuteAllRemoteAudioStreams(muted)) + } + + func muteRemoteVideoStream(_ channelId: String, _ uid: Int, _ muted: Bool, _ callback: PromiseCallback?) { + callback?.code(channel(channelId)?.muteRemoteVideoStream(UInt(uid), mute: muted)) + } + + func muteAllRemoteVideoStreams(_ channelId: String, _ muted: Bool, _ callback: PromiseCallback?) { + callback?.code(channel(channelId)?.muteAllRemoteVideoStreams(muted)) + } + + func setDefaultMuteAllRemoteVideoStreams(_ channelId: String, _ muted: Bool, _ callback: PromiseCallback?) { + callback?.code(channel(channelId)?.setDefaultMuteAllRemoteVideoStreams(muted)) + } + + func setRemoteVoicePosition(_ channelId: String, _ uid: Int, _ pan: Double, _ gain: Double, _ callback: PromiseCallback?) { + callback?.code(channel(channelId)?.setRemoteVoicePosition(UInt(uid), pan: pan, gain: gain)) + } + + func setLiveTranscoding(_ channelId: String, _ transcoding: NSDictionary, _ callback: PromiseCallback?) { + callback?.code(channel(channelId)?.setLiveTranscoding(mapToLiveTranscoding(transcoding as! Dictionary))) + } + + func addPublishStreamUrl(_ channelId: String, _ url: String, _ transcodingEnabled: Bool, _ callback: PromiseCallback?) { + callback?.code(channel(channelId)?.addPublishStreamUrl(url, transcodingEnabled: transcodingEnabled)) + } + + func removePublishStreamUrl(_ channelId: String, _ url: String, _ callback: PromiseCallback?) { + callback?.code(channel(channelId)?.removePublishStreamUrl(url)) + } + + func startChannelMediaRelay(_ channelId: String, _ channelMediaRelayConfiguration: NSDictionary, _ callback: PromiseCallback?) { + callback?.code(channel(channelId)?.startMediaRelay(mapToChannelMediaRelayConfiguration(channelMediaRelayConfiguration as! Dictionary))) + } + + func updateChannelMediaRelay(_ channelId: String, _ channelMediaRelayConfiguration: NSDictionary, _ callback: PromiseCallback?) { + callback?.code(channel(channelId)?.updateMediaRelay(mapToChannelMediaRelayConfiguration(channelMediaRelayConfiguration as! Dictionary))) + } + + func stopChannelMediaRelay(_ channelId: String, _ callback: PromiseCallback?) { + callback?.code(channel(channelId)?.stopMediaRelay()) + } + + func setRemoteVideoStreamType(_ channelId: String, _ uid: Int, _ streamType: Int, _ callback: PromiseCallback?) { + callback?.code(channel(channelId)?.setRemoteVideoStream(UInt(uid), type: AgoraVideoStreamType(rawValue: streamType)!)) + } + + func setRemoteDefaultVideoStreamType(_ channelId: String, _ streamType: Int, _ callback: PromiseCallback?) { + callback?.code(channel(channelId)?.setRemoteDefaultVideoStreamType(AgoraVideoStreamType(rawValue: streamType)!)) + } + + func setRemoteUserPriority(_ channelId: String, _ uid: Int, _ userPriority: Int, _ callback: PromiseCallback?) { + callback?.code(channel(channelId)?.setRemoteUserPriority(UInt(uid), type: AgoraUserPriority(rawValue: userPriority)!)) + } + + func registerMediaMetadataObserver(_ channelId: String, _ callback: PromiseCallback?) { + callback?.code(manager.registerMediaMetadataObserver(channelId) { [weak self] (methodName, data) in + self?.emit(methodName, data) + }) + } + + func unregisterMediaMetadataObserver(_ channelId: String, _ callback: PromiseCallback?) { + callback?.code(manager.unregisterMediaMetadataObserver(channelId)) + } + + func setMaxMetadataSize(_ channelId: String, _ size: Int, _ callback: PromiseCallback?) { + callback?.code(manager.setMaxMetadataSize(channelId, size)) + } + + func sendMetadata(_ channelId: String, _ metadata: String, _ callback: PromiseCallback?) { + callback?.code(manager.addMetadata(channelId, metadata)) + } + + func setEncryptionSecret(_ channelId: String, _ secret: String, _ callback: PromiseCallback?) { + callback?.code(channel(channelId)?.setEncryptionSecret(secret)) + } + + func setEncryptionMode(_ channelId: String, _ encryptionMode: String, _ callback: PromiseCallback?) { + callback?.code(channel(channelId)?.setEncryptionMode(encryptionMode)) + } + + func addInjectStreamUrl(_ channelId: String, _ url: String, _ config: NSDictionary, _ callback: PromiseCallback?) { + callback?.code(channel(channelId)?.addInjectStreamUrl(url, config: mapToLiveInjectStreamConfig(config as! Dictionary))) + } + + func removeInjectStreamUrl(_ channelId: String, _ url: String, _ callback: PromiseCallback?) { + callback?.code(channel(channelId)?.removeInjectStreamUrl(url)) + } + + func createDataStream(_ channelId: String, _ reliable: Bool, _ ordered: Bool, _ callback: PromiseCallback?) { + callback?.code(manager.createDataStream(channelId, reliable, ordered)) { it in it } + } + + func sendStreamMessage(_ channelId: String, _ streamId: Int, _ message: String, _ callback: PromiseCallback?) { + callback?.code(manager.sendStreamMessage(channelId, streamId, message)) + } +} + +extension RCTAgoraRtcChannelModule { + @objc func create(_ channelId: String, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + create(channelId, PromiseCallback(resolve, reject)) + } + + @objc func destroy(_ channelId: String, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + destroy(channelId, PromiseCallback(resolve, reject)) + } + + @objc func setClientRole(_ channelId: String, _ role: Int, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setClientRole(channelId, role, PromiseCallback(resolve, reject)) + } + + @objc func joinChannel(_ channelId: String, _ token: String?, _ optionalInfo: String?, _ optionalUid: Int, _ options: NSDictionary, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + joinChannel(channelId, token, optionalInfo, optionalUid, options, PromiseCallback(resolve, reject)) + } + + @objc func joinChannelWithUserAccount(_ channelId: String, _ token: String?, _ userAccount: String, _ options: NSDictionary, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + joinChannelWithUserAccount(channelId, token, userAccount, options, PromiseCallback(resolve, reject)) + } + + @objc func leaveChannel(_ channelId: String, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + leaveChannel(channelId, PromiseCallback(resolve, reject)) + } + + @objc func renewToken(_ channelId: String, _ token: String, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + renewToken(channelId, token, PromiseCallback(resolve, reject)) + } + + @objc func getConnectionState(_ channelId: String, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + getConnectionState(channelId, PromiseCallback(resolve, reject)) + } + + @objc func publish(_ channelId: String, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + publish(channelId, PromiseCallback(resolve, reject)) + } + + @objc func unpublish(_ channelId: String, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + unpublish(channelId, PromiseCallback(resolve, reject)) + } + + @objc func getCallId(_ channelId: String, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + getCallId(channelId, PromiseCallback(resolve, reject)) + } + + @objc func adjustUserPlaybackSignalVolume(_ channelId: String, _ uid: Int, _ volume: Int, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + adjustUserPlaybackSignalVolume(channelId, uid, volume, PromiseCallback(resolve, reject)) + } + + @objc func muteRemoteAudioStream(_ channelId: String, _ uid: Int, _ muted: Bool, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + muteRemoteAudioStream(channelId, uid, muted, PromiseCallback(resolve, reject)) + } + + @objc func muteAllRemoteAudioStreams(_ channelId: String, _ muted: Bool, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setDefaultMuteAllRemoteAudioStreams(channelId, muted, PromiseCallback(resolve, reject)) + } + + @objc func setDefaultMuteAllRemoteAudioStreams(_ channelId: String, _ muted: Bool, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setDefaultMuteAllRemoteAudioStreams(channelId, muted, PromiseCallback(resolve, reject)) + } + + @objc func muteRemoteVideoStream(_ channelId: String, _ uid: Int, _ muted: Bool, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + muteRemoteVideoStream(channelId, uid, muted, PromiseCallback(resolve, reject)) + } + + @objc func muteAllRemoteVideoStreams(_ channelId: String, _ muted: Bool, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setDefaultMuteAllRemoteVideoStreams(channelId, muted, PromiseCallback(resolve, reject)) + } + + @objc func setDefaultMuteAllRemoteVideoStreams(_ channelId: String, _ muted: Bool, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setDefaultMuteAllRemoteVideoStreams(channelId, muted, PromiseCallback(resolve, reject)) + } + + @objc func setRemoteVoicePosition(_ channelId: String, _ uid: Int, _ pan: Double, _ gain: Double, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setRemoteVoicePosition(channelId, uid, pan, gain, PromiseCallback(resolve, reject)) + } + + @objc func setLiveTranscoding(_ channelId: String, _ transcoding: NSDictionary, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setLiveTranscoding(channelId, transcoding, PromiseCallback(resolve, reject)) + } + + @objc func addPublishStreamUrl(_ channelId: String, _ url: String, _ transcodingEnabled: Bool, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + addPublishStreamUrl(channelId, url, transcodingEnabled, PromiseCallback(resolve, reject)) + } + + @objc func removePublishStreamUrl(_ channelId: String, _ url: String, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + removePublishStreamUrl(channelId, url, PromiseCallback(resolve, reject)) + } + + @objc func startChannelMediaRelay(_ channelId: String, _ channelMediaRelayConfiguration: NSDictionary, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + startChannelMediaRelay(channelId, channelMediaRelayConfiguration, PromiseCallback(resolve, reject)) + } + + @objc func updateChannelMediaRelay(_ channelId: String, _ channelMediaRelayConfiguration: NSDictionary, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + updateChannelMediaRelay(channelId, channelMediaRelayConfiguration, PromiseCallback(resolve, reject)) + } + + @objc func stopChannelMediaRelay(_ channelId: String, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + stopChannelMediaRelay(channelId, PromiseCallback(resolve, reject)) + } + + @objc func setRemoteVideoStreamType(_ channelId: String, _ uid: Int, _ streamType: Int, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setRemoteVideoStreamType(channelId, uid, streamType, PromiseCallback(resolve, reject)) + } + + @objc func setRemoteDefaultVideoStreamType(_ channelId: String, _ streamType: Int, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setRemoteDefaultVideoStreamType(channelId, streamType, PromiseCallback(resolve, reject)) + } + + @objc func setRemoteUserPriority(_ channelId: String, _ uid: Int, _ userPriority: Int, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setRemoteUserPriority(channelId, uid, userPriority, PromiseCallback(resolve, reject)) + } + + @objc func registerMediaMetadataObserver(_ channelId: String, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + registerMediaMetadataObserver(channelId, PromiseCallback(resolve, reject)) + } + + @objc func unregisterMediaMetadataObserver(_ channelId: String, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + unregisterMediaMetadataObserver(channelId, PromiseCallback(resolve, reject)) + } + + @objc func setMaxMetadataSize(_ channelId: String, _ size: Int, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setMaxMetadataSize(channelId, size, PromiseCallback(resolve, reject)) + } + + @objc func sendMetadata(_ channelId: String, _ metadata: String, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + sendMetadata(channelId, metadata, PromiseCallback(resolve, reject)) + } + + @objc func setEncryptionSecret(_ channelId: String, _ secret: String, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setEncryptionSecret(channelId, secret, PromiseCallback(resolve, reject)) + } + + @objc func setEncryptionMode(_ channelId: String, _ encryptionMode: String, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setEncryptionMode(channelId, encryptionMode, PromiseCallback(resolve, reject)) + } + + @objc func addInjectStreamUrl(_ channelId: String, _ url: String, _ config: NSDictionary, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + addInjectStreamUrl(channelId, url, config, PromiseCallback(resolve, reject)) + } + + @objc func removeInjectStreamUrl(_ channelId: String, _ url: String, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + removeInjectStreamUrl(channelId, url, PromiseCallback(resolve, reject)) + } + + @objc func createDataStream(_ channelId: String, _ reliable: Bool, _ ordered: Bool, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + createDataStream(channelId, reliable, ordered, PromiseCallback(resolve, reject)) + } + + @objc func sendStreamMessage(_ channelId: String, _ streamId: Int, _ message: String, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + sendStreamMessage(channelId, streamId, message, PromiseCallback(resolve, reject)) + } +} diff --git a/ios/RCTAgora/React/RCTAgoraRtcChannelModuleBridge.m b/ios/RCTAgora/React/RCTAgoraRtcChannelModuleBridge.m new file mode 100644 index 000000000..e1f5e14e7 --- /dev/null +++ b/ios/RCTAgora/React/RCTAgoraRtcChannelModuleBridge.m @@ -0,0 +1,128 @@ +// +// RCTAgoraRtcChannelModuleBridge.m +// RCTAgora +// +// Created by LXH on 2020/4/15. +// Copyright (c) 2020 Syan. All rights reserved. +// + +#import +#import + +@interface RCT_EXTERN_MODULE(RCTAgoraRtcChannelModule, NSObject) + +RCT_EXTERN_METHOD(create: + (NSString *) channelId :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(destroy: + (NSString *) channelId :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setClientRole: + (NSString *) channelId :(NSInteger) role :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(joinChannel: + (NSString *) channelId :(NSString *) token :(NSString *) optionalInfo :(NSInteger) optionalUid :(NSDictionary *) options :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(joinChannelWithUserAccount: + (NSString *) channelId :(NSString *) token :(NSString *) userAccount :(NSDictionary *) options :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(leaveChannel: + (NSString *) channelId :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(renewToken: + (NSString *) channelId :(NSString *) token :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(getConnectionState: + (NSString *) channelId :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(publish: + (NSString *) channelId :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(unpublish: + (NSString *) channelId :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(getCallId: + (NSString *) channelId :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(adjustUserPlaybackSignalVolume: + (NSString *) channelId :(NSInteger) uid :(NSInteger) volume :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(muteRemoteAudioStream: + (NSString *) channelId :(NSInteger) uid :(BOOL) muted :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(muteAllRemoteAudioStreams: + (NSString *) channelId :(BOOL) muted :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setDefaultMuteAllRemoteAudioStreams: + (NSString *) channelId :(BOOL) muted :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(muteRemoteVideoStream: + (NSString *) channelId :(NSInteger) uid :(BOOL) muted :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(muteAllRemoteVideoStreams: + (NSString *) channelId :(BOOL) muted :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setDefaultMuteAllRemoteVideoStreams: + (NSString *) channelId :(BOOL) muted :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setRemoteVoicePosition: + (NSString *) channelId :(NSInteger) uid :(double) pan :(double) gain :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setLiveTranscoding: + (NSString *) channelId :(NSDictionary *) transcoding :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(addPublishStreamUrl: + (NSString *) channelId :(NSString *) url :(BOOL) transcodingEnabled :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(removePublishStreamUrl: + (NSString *) channelId :(NSString *) url :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(startChannelMediaRelay: + (NSString *) channelId :(NSDictionary *) channelMediaRelayConfiguration :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(updateChannelMediaRelay: + (NSString *) channelId :(NSDictionary *) channelMediaRelayConfiguration :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(stopChannelMediaRelay: + (NSString *) channelId :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setRemoteVideoStreamType: + (NSString *) channelId :(NSInteger) uid :(NSInteger) streamType :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setRemoteDefaultVideoStreamType: + (NSString *) channelId :(NSInteger) streamType :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setRemoteUserPriority: + (NSString *) channelId :(NSInteger) uid :(NSInteger) userPriority :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(registerMediaMetadataObserver: + (NSString *) channelId :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(unregisterMediaMetadataObserver: + (NSString *) channelId :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setMaxMetadataSize: + (NSString *) channelId :(NSInteger) size :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(sendMetadata: + (NSString *) channelId :(NSString *) metadata :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setEncryptionSecret: + (NSString *) channelId :(NSString *) secret :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setEncryptionMode: + (NSString *) channelId :(NSString *) encryptionMode :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(addInjectStreamUrl: + (NSString *) channelId :(NSString *) url :(NSDictionary *) config :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(removeInjectStreamUrl: + (NSString *) channelId :(NSString *) url :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(createDataStream: + (NSString *) channelId :(BOOL) reliable :(BOOL) ordered :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(sendStreamMessage: + (NSString *) channelId :(NSInteger) streamId :(NSString *) message :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +@end diff --git a/ios/RCTAgora/React/RCTAgoraRtcEngineModule.swift b/ios/RCTAgora/React/RCTAgoraRtcEngineModule.swift new file mode 100644 index 000000000..0e6e8d8fb --- /dev/null +++ b/ios/RCTAgora/React/RCTAgoraRtcEngineModule.swift @@ -0,0 +1,1119 @@ +// +// RCTRtcEngineModule.swift +// RCTAgora +// +// Created by LXH on 2020/4/14. +// Copyright © 2020 Syan. All rights reserved. +// + +import Foundation +import AgoraRtcKit + +@objc(RCTAgoraRtcEngineModule) +class RCTAgoraRtcEngineModule: RCTEventEmitter, RtcEngineInterface { + static let REACT_CLASS = "RCTAgoraRtcEngineModule" + + typealias Map = NSDictionary + typealias Callback = PromiseCallback + + private var hasListeners = false + + private lazy var manager: RtcEngineManager = { + RtcEngineManager() + }() + + override class func moduleName() -> String! { + RCTAgoraRtcEngineModule.REACT_CLASS + } + + override func constantsToExport() -> [AnyHashable: Any]! { + ["prefix": RtcEngineEventHandler.PREFIX] + } + + deinit { + manager.release() + } + + override class func requiresMainQueueSetup() -> Bool { + true + } + + override var methodQueue: DispatchQueue! { + DispatchQueue.main + } + + override func supportedEvents() -> [String]! { + var events = [String]() + RtcEngineEvents.toMap().forEach { key, value in + events.append("\(RtcEngineEventHandler.PREFIX)\(value)") + } + return events + } + + override func startObserving() { + hasListeners = true + } + + override func stopObserving() { + hasListeners = false + } + + private func emit(_ methodName: String, _ data: Dictionary?) { + if hasListeners { + sendEvent(withName: "\(RtcEngineEventHandler.PREFIX)\(methodName)", body: data) + } + } + + var engine: AgoraRtcEngineKit? { + return manager.engine + } + + func create(_ appId: String, _ areaCode: Int, _ callback: PromiseCallback?) { + manager.create(appId, Int32(areaCode), .APP_TYPE_REACTNATIVE) { [weak self] (methodName, data) in + self?.emit(methodName, data) + } + callback?.resolve(engine) { e in nil } + } + + func destroy(_ callback: PromiseCallback?) { + callback?.resolve(engine) { e in manager.destroy() } + } + + func setChannelProfile(_ profile: Int, _ callback: PromiseCallback?) { + callback?.code(engine?.setChannelProfile(AgoraChannelProfile(rawValue: profile)!)) + } + + func setClientRole(_ role: Int, _ callback: PromiseCallback?) { + callback?.code(engine?.setClientRole(AgoraClientRole(rawValue: role)!)) + } + + func joinChannel(_ token: String?, _ channelName: String, _ optionalInfo: String?, _ optionalUid: Int, _ callback: PromiseCallback?) { + callback?.code(engine?.joinChannel(byToken: token, channelId: channelName, info: optionalInfo, uid: UInt(optionalUid))) + } + + func switchChannel(_ token: String?, _ channelName: String, _ callback: PromiseCallback?) { + callback?.code(engine?.switchChannel(byToken: token, channelId: channelName)) + } + + func leaveChannel(_ callback: PromiseCallback?) { + callback?.code(engine?.leaveChannel()) + } + + func renewToken(_ token: String, _ callback: PromiseCallback?) { + callback?.code(engine?.renewToken(token)) + } + + func enableWebSdkInteroperability(_ enabled: Bool, _ callback: PromiseCallback?) { + callback?.code(engine?.enableWebSdkInteroperability(enabled)) + } + + func getConnectionState(_ callback: PromiseCallback?) { + callback?.resolve(engine) { (engine: AgoraRtcEngineKit) in + engine.getConnectionState() + } + } + + func getCallId(_ callback: PromiseCallback?) { + callback?.resolve(engine) { (engine: AgoraRtcEngineKit) in + engine.getCallId() + } + } + + func rate(_ callId: String, _ rating: Int, _ description: String?, _ callback: PromiseCallback?) { + callback?.code(engine?.rate(callId, rating: rating, description: description)) + } + + func complain(_ callId: String, _ description: String, _ callback: PromiseCallback?) { + callback?.code(engine?.complain(callId, description: description)) + } + + func setLogFile(_ filePath: String, _ callback: PromiseCallback?) { + callback?.code(engine?.setLogFile(filePath)) + } + + func setLogFilter(_ filter: Int, _ callback: PromiseCallback?) { + callback?.code(engine?.setLogFilter(UInt(filter))) + } + + func setLogFileSize(_ fileSizeInKBytes: Int, _ callback: PromiseCallback?) { + callback?.code(engine?.setLogFileSize(UInt(fileSizeInKBytes))) + } + + func setParameters(_ parameters: String, _ callback: PromiseCallback?) { + callback?.code(engine?.setParameters(parameters)) + } + + func registerLocalUserAccount(_ appId: String, _ userAccount: String, _ callback: PromiseCallback?) { + callback?.code(engine?.registerLocalUserAccount(userAccount, appId: appId)) + } + + func joinChannelWithUserAccount(_ token: String?, _ channelName: String, _ userAccount: String, _ callback: PromiseCallback?) { + callback?.code(engine?.joinChannel(byUserAccount: userAccount, token: token, channelId: channelName, joinSuccess: nil)) + } + + func getUserInfoByUserAccount(_ userAccount: String, _ callback: PromiseCallback?) { + callback?.resolve(engine) { (engine: AgoraRtcEngineKit) in + manager.getUserInfoByUserAccount(userAccount) + } + } + + func getUserInfoByUid(_ uid: Int, _ callback: PromiseCallback?) { + callback?.resolve(engine) { (engine: AgoraRtcEngineKit) in + manager.getUserInfoByUid(uid) + } + } + + func enableAudio(_ callback: PromiseCallback?) { + callback?.code(engine?.enableAudio()) + } + + func disableAudio(_ callback: PromiseCallback?) { + callback?.code(engine?.disableAudio()) + } + + func setAudioProfile(_ profile: Int, _ scenario: Int, _ callback: PromiseCallback?) { + callback?.code(engine?.setAudioProfile(AgoraAudioProfile(rawValue: profile)!, scenario: AgoraAudioScenario(rawValue: scenario)!)) + } + + func adjustRecordingSignalVolume(_ volume: Int, _ callback: PromiseCallback?) { + callback?.code(engine?.adjustRecordingSignalVolume(volume)) + } + + func adjustUserPlaybackSignalVolume(_ uid: Int, _ volume: Int, _ callback: PromiseCallback?) { + callback?.code(engine?.adjustUserPlaybackSignalVolume(UInt(uid), volume: Int32(volume))) + } + + func adjustPlaybackSignalVolume(_ volume: Int, _ callback: PromiseCallback?) { + callback?.code(engine?.adjustPlaybackSignalVolume(volume)) + } + + func enableLocalAudio(_ enabled: Bool, _ callback: PromiseCallback?) { + callback?.code(engine?.enableLocalAudio(enabled)) + } + + func muteLocalAudioStream(_ muted: Bool, _ callback: PromiseCallback?) { + callback?.code(engine?.muteLocalAudioStream(muted)) + } + + func muteRemoteAudioStream(_ uid: Int, _ muted: Bool, _ callback: PromiseCallback?) { + callback?.code(engine?.muteRemoteAudioStream(UInt(uid), mute: muted)) + } + + func muteAllRemoteAudioStreams(_ muted: Bool, _ callback: PromiseCallback?) { + callback?.code(engine?.muteAllRemoteAudioStreams(muted)) + } + + func setDefaultMuteAllRemoteAudioStreams(_ muted: Bool, _ callback: PromiseCallback?) { + callback?.code(engine?.setDefaultMuteAllRemoteAudioStreams(muted)) + } + + func enableAudioVolumeIndication(_ interval: Int, _ smooth: Int, _ report_vad: Bool, _ callback: PromiseCallback?) { + callback?.code(engine?.enableAudioVolumeIndication(interval, smooth: smooth, report_vad: report_vad)) + } + + func enableVideo(_ callback: PromiseCallback?) { + callback?.code(engine?.enableVideo()) + } + + func disableVideo(_ callback: PromiseCallback?) { + callback?.code(engine?.disableVideo()) + } + + func setVideoEncoderConfiguration(_ config: NSDictionary, _ callback: PromiseCallback?) { + callback?.code(engine?.setVideoEncoderConfiguration(mapToVideoEncoderConfiguration(config as! Dictionary))) + } + + func enableLocalVideo(_ enabled: Bool, _ callback: PromiseCallback?) { + callback?.code(engine?.enableLocalVideo(enabled)) + } + + func muteLocalVideoStream(_ muted: Bool, _ callback: PromiseCallback?) { + callback?.code(engine?.muteLocalVideoStream(muted)) + } + + func muteRemoteVideoStream(_ uid: Int, _ muted: Bool, _ callback: PromiseCallback?) { + callback?.code(engine?.muteRemoteVideoStream(UInt(uid), mute: muted)) + } + + func muteAllRemoteVideoStreams(_ muted: Bool, _ callback: PromiseCallback?) { + callback?.code(engine?.muteAllRemoteVideoStreams(muted)) + } + + func setDefaultMuteAllRemoteVideoStreams(_ muted: Bool, _ callback: PromiseCallback?) { + callback?.code(engine?.setDefaultMuteAllRemoteVideoStreams(muted)) + } + + func setBeautyEffectOptions(_ enabled: Bool, _ options: NSDictionary, _ callback: PromiseCallback?) { + callback?.code(engine?.setBeautyEffectOptions(enabled, options: mapToBeautyOptions(options as! Dictionary))) + } + + func startAudioMixing(_ filePath: String, _ loopback: Bool, _ replace: Bool, _ cycle: Int, _ callback: PromiseCallback?) { + callback?.code(engine?.startAudioMixing(filePath, loopback: loopback, replace: replace, cycle: cycle)) + } + + func stopAudioMixing(_ callback: PromiseCallback?) { + callback?.code(engine?.stopAudioMixing()) + } + + func pauseAudioMixing(_ callback: PromiseCallback?) { + callback?.code(engine?.pauseAudioMixing()) + } + + func resumeAudioMixing(_ callback: PromiseCallback?) { + callback?.code(engine?.resumeAudioMixing()) + } + + func adjustAudioMixingVolume(_ volume: Int, _ callback: PromiseCallback?) { + callback?.code(engine?.adjustAudioMixingVolume(volume)) + } + + func adjustAudioMixingPlayoutVolume(_ volume: Int, _ callback: PromiseCallback?) { + callback?.code(engine?.adjustAudioMixingPlayoutVolume(volume)) + } + + func adjustAudioMixingPublishVolume(_ volume: Int, _ callback: PromiseCallback?) { + callback?.code(engine?.adjustAudioMixingPublishVolume(volume)) + } + + func getAudioMixingPlayoutVolume(_ callback: PromiseCallback?) { + callback?.code(engine?.getAudioMixingPlayoutVolume()){ it in it} + } + + func getAudioMixingPublishVolume(_ callback: PromiseCallback?) { + callback?.code(engine?.getAudioMixingPublishVolume()) { it in it} + } + + func getAudioMixingDuration(_ callback: PromiseCallback?) { + callback?.code(engine?.getAudioMixingDuration()) { it in it } + } + + func getAudioMixingCurrentPosition(_ callback: PromiseCallback?) { + callback?.code(engine?.getAudioMixingCurrentPosition()) { it in it } + } + + func setAudioMixingPosition(_ pos: Int, _ callback: PromiseCallback?) { + callback?.code(engine?.setAudioMixingPosition(pos)) + } + + func setAudioMixingPitch(_ pitch: Int, _ callback: PromiseCallback?) { + callback?.code(engine?.setAudioMixingPitch(pitch)) + } + + func getEffectsVolume(_ callback: PromiseCallback?) { + callback?.resolve(engine) { (engine: AgoraRtcEngineKit) in + engine.getEffectsVolume() + } + } + + func setEffectsVolume(_ volume: Double, _ callback: PromiseCallback?) { + callback?.code(engine?.setEffectsVolume(volume)) + } + + func setVolumeOfEffect(_ soundId: Int, _ volume: Double, _ callback: PromiseCallback?) { + callback?.code(engine?.setVolumeOfEffect(Int32(soundId), withVolume: volume)) + } + + func playEffect(_ soundId: Int, _ filePath: String, _ loopCount: Int, _ pitch: Double, _ pan: Double, _ gain: Double, _ publish: Bool, _ callback: PromiseCallback?) { + callback?.code(engine?.playEffect(Int32(soundId), filePath: filePath, loopCount: Int32(loopCount), pitch: pitch, pan: pan, gain: gain, publish: publish)) + } + + func stopEffect(_ soundId: Int, _ callback: PromiseCallback?) { + callback?.code(engine?.stopEffect(Int32(soundId))) + } + + func stopAllEffects(_ callback: PromiseCallback?) { + callback?.code(engine?.stopAllEffects()) + } + + func preloadEffect(_ soundId: Int, _ filePath: String, _ callback: PromiseCallback?) { + callback?.code(engine?.preloadEffect(Int32(soundId), filePath: filePath)) + } + + func unloadEffect(_ soundId: Int, _ callback: PromiseCallback?) { + callback?.code(engine?.unloadEffect(Int32(soundId))) + } + + func pauseEffect(_ soundId: Int, _ callback: PromiseCallback?) { + callback?.code(engine?.pauseEffect(Int32(soundId))) + } + + func pauseAllEffects(_ callback: PromiseCallback?) { + callback?.code(engine?.pauseAllEffects()) + } + + func resumeEffect(_ soundId: Int, _ callback: PromiseCallback?) { + callback?.code(engine?.resumeEffect(Int32(soundId))) + } + + func resumeAllEffects(_ callback: PromiseCallback?) { + callback?.code(engine?.resumeAllEffects()) + } + + func setLocalVoiceChanger(_ voiceChanger: Int, _ callback: PromiseCallback?) { + callback?.code(engine?.setLocalVoiceChanger(AgoraAudioVoiceChanger(rawValue: voiceChanger)!)) + } + + func setLocalVoiceReverbPreset(_ preset: Int, _ callback: PromiseCallback?) { + callback?.code(engine?.setLocalVoiceReverbPreset(AgoraAudioReverbPreset(rawValue: preset)!)) + } + + func setLocalVoicePitch(_ pitch: Double, _ callback: PromiseCallback?) { + callback?.code(engine?.setLocalVoicePitch(pitch)) + } + + func setLocalVoiceEqualization(_ bandFrequency: Int, _ bandGain: Int, _ callback: PromiseCallback?) { + callback?.code(engine?.setLocalVoiceEqualizationOf(AgoraAudioEqualizationBandFrequency(rawValue: bandFrequency)!, withGain: bandGain)) + } + + func setLocalVoiceReverb(_ reverbKey: Int, _ value: Int, _ callback: PromiseCallback?) { + callback?.code(engine?.setLocalVoiceReverbOf(AgoraAudioReverbType(rawValue: reverbKey)!, withValue: value)) + } + + func enableSoundPositionIndication(_ enabled: Bool, _ callback: PromiseCallback?) { + callback?.code(engine?.enableSoundPositionIndication(enabled)) + } + + func setRemoteVoicePosition(_ uid: Int, _ pan: Double, _ gain: Double, _ callback: PromiseCallback?) { + callback?.code(engine?.setRemoteVoicePosition(UInt(uid), pan: pan, gain: gain)) + } + + func setLiveTranscoding(_ transcoding: NSDictionary, _ callback: PromiseCallback?) { + callback?.code(engine?.setLiveTranscoding(mapToLiveTranscoding(transcoding as! Dictionary))) + } + + func addPublishStreamUrl(_ url: String, _ transcodingEnabled: Bool, _ callback: PromiseCallback?) { + callback?.code(engine?.addPublishStreamUrl(url, transcodingEnabled: transcodingEnabled)) + } + + func removePublishStreamUrl(_ url: String, _ callback: PromiseCallback?) { + callback?.code(engine?.removePublishStreamUrl(url)) + } + + func startChannelMediaRelay(_ channelMediaRelayConfiguration: NSDictionary, _ callback: PromiseCallback?) { + callback?.code(engine?.startChannelMediaRelay(mapToChannelMediaRelayConfiguration(channelMediaRelayConfiguration as! Dictionary))) + } + + func updateChannelMediaRelay(_ channelMediaRelayConfiguration: NSDictionary, _ callback: PromiseCallback?) { + callback?.code(engine?.updateChannelMediaRelay(mapToChannelMediaRelayConfiguration(channelMediaRelayConfiguration as! Dictionary))) + } + + func stopChannelMediaRelay(_ callback: PromiseCallback?) { + callback?.code(engine?.stopChannelMediaRelay()) + } + + func setDefaultAudioRoutetoSpeakerphone(_ defaultToSpeaker: Bool, _ callback: PromiseCallback?) { + callback?.code(engine?.setDefaultAudioRouteToSpeakerphone(defaultToSpeaker)) + } + + func setEnableSpeakerphone(_ enabled: Bool, _ callback: PromiseCallback?) { + callback?.code(engine?.setEnableSpeakerphone(enabled)) + } + + func isSpeakerphoneEnabled(_ callback: PromiseCallback?) { + callback?.resolve(engine) { (engine: AgoraRtcEngineKit) in + engine.isSpeakerphoneEnabled() + } + } + + func enableInEarMonitoring(_ enabled: Bool, _ callback: PromiseCallback?) { + callback?.code(engine?.enable(inEarMonitoring: enabled)) + } + + func setInEarMonitoringVolume(_ volume: Int, _ callback: PromiseCallback?) { + callback?.code(engine?.setInEarMonitoringVolume(volume)) + } + + func enableDualStreamMode(_ enabled: Bool, _ callback: PromiseCallback?) { + callback?.code(engine?.enableDualStreamMode(enabled)) + } + + func setRemoteVideoStreamType(_ uid: Int, _ streamType: Int, _ callback: PromiseCallback?) { + callback?.code(engine?.setRemoteVideoStream(UInt(uid), type: AgoraVideoStreamType(rawValue: streamType)!)) + } + + func setRemoteDefaultVideoStreamType(_ streamType: Int, _ callback: PromiseCallback?) { + callback?.code(engine?.setRemoteDefaultVideoStreamType(AgoraVideoStreamType(rawValue: streamType)!)) + } + + func setLocalPublishFallbackOption(_ option: Int, _ callback: PromiseCallback?) { + callback?.code(engine?.setLocalPublishFallbackOption(AgoraStreamFallbackOptions(rawValue: option)!)) + } + + func setRemoteSubscribeFallbackOption(_ option: Int, _ callback: PromiseCallback?) { + callback?.code(engine?.setRemoteSubscribeFallbackOption(AgoraStreamFallbackOptions(rawValue: option)!)) + } + + func setRemoteUserPriority(_ uid: Int, _ userPriority: Int, _ callback: PromiseCallback?) { + callback?.code(engine?.setRemoteUserPriority(UInt(uid), type: AgoraUserPriority(rawValue: userPriority)!)) + } + + func startEchoTest(_ intervalInSeconds: Int, _ callback: PromiseCallback?) { + callback?.code(engine?.startEchoTest(withInterval: intervalInSeconds)) + } + + func stopEchoTest(_ callback: PromiseCallback?) { + callback?.code(engine?.stopEchoTest()) + } + + func enableLastmileTest(_ callback: PromiseCallback?) { + callback?.code(engine?.enableLastmileTest()) + } + + func disableLastmileTest(_ callback: PromiseCallback?) { + callback?.code(engine?.disableLastmileTest()) + } + + func startLastmileProbeTest(_ config: NSDictionary, _ callback: PromiseCallback?) { + callback?.code(engine?.startLastmileProbeTest(mapToLastmileProbeConfig(config as! Dictionary))) + } + + func stopLastmileProbeTest(_ callback: PromiseCallback?) { + callback?.code(engine?.stopLastmileProbeTest()) + } + + func registerMediaMetadataObserver(_ callback: PromiseCallback?) { + callback?.code(manager.registerMediaMetadataObserver() { [weak self] (methodName, data) in + self?.emit(methodName, data) + }) + } + + func unregisterMediaMetadataObserver(_ callback: PromiseCallback?) { + callback?.code(manager.unregisterMediaMetadataObserver()) + } + + func setMaxMetadataSize(_ size: Int, _ callback: PromiseCallback?) { + callback?.code(manager.setMaxMetadataSize(size)) + } + + func sendMetadata(_ metadata: String, _ callback: PromiseCallback?) { + callback?.code(manager.addMetadata(metadata)) + } + + func addVideoWatermark(_ watermarkUrl: String, _ options: NSDictionary, _ callback: PromiseCallback?) { + callback?.code(engine?.addVideoWatermark(URL(string: watermarkUrl)!, options: mapToWatermarkOptions(options as! Dictionary))) + } + + func clearVideoWatermarks(_ callback: PromiseCallback?) { + callback?.code(engine?.clearVideoWatermarks()) + } + + func setEncryptionSecret(_ secret: String, _ callback: PromiseCallback?) { + callback?.code(engine?.setEncryptionSecret(secret)) + } + + func setEncryptionMode(_ encryptionMode: String, _ callback: PromiseCallback?) { + callback?.code(engine?.setEncryptionMode(encryptionMode)) + } + + func startAudioRecording(_ filePath: String, _ sampleRate: Int, _ quality: Int, _ callback: PromiseCallback?) { + callback?.code(engine?.startAudioRecording(filePath, sampleRate: sampleRate, quality: AgoraAudioRecordingQuality(rawValue: quality)!)) + } + + func stopAudioRecording(_ callback: PromiseCallback?) { + callback?.code(engine?.stopAudioRecording()) + } + + func addInjectStreamUrl(_ url: String, _ config: NSDictionary, _ callback: PromiseCallback?) { + callback?.code(engine?.addInjectStreamUrl(url, config: mapToLiveInjectStreamConfig(config as! Dictionary))) + } + + func removeInjectStreamUrl(_ url: String, _ callback: PromiseCallback?) { + callback?.code(engine?.removeInjectStreamUrl(url)) + } + + func switchCamera(_ callback: PromiseCallback?) { + callback?.code(engine?.switchCamera()) + } + + func isCameraZoomSupported(_ callback: PromiseCallback?) { + callback?.resolve(engine) { (engine: AgoraRtcEngineKit) in + engine.isCameraZoomSupported() + } + } + + func isCameraTorchSupported(_ callback: PromiseCallback?) { + callback?.resolve(engine) { (engine: AgoraRtcEngineKit) in + engine.isCameraTorchSupported() + } + } + + func isCameraFocusSupported(_ callback: PromiseCallback?) { + // TODO Not in iOS + callback?.resolve(engine) { (engine: AgoraRtcEngineKit) in nil } + } + + func isCameraExposurePositionSupported(_ callback: PromiseCallback?) { + callback?.resolve(engine) { (engine: AgoraRtcEngineKit) in + engine.isCameraExposurePositionSupported() + } + } + + func isCameraAutoFocusFaceModeSupported(_ callback: PromiseCallback?) { + callback?.resolve(engine) { (engine: AgoraRtcEngineKit) in + engine.isCameraAutoFocusFaceModeSupported() + } + } + + func setCameraZoomFactor(_ factor: Float, _ callback: PromiseCallback?) { + callback?.resolve(engine) { (engine: AgoraRtcEngineKit) in + engine.setCameraZoomFactor(CGFloat(factor)) + return nil + } + } + + func getCameraMaxZoomFactor(_ callback: PromiseCallback?) { + // TODO Not in iOS + callback?.resolve(engine) { (engine: AgoraRtcEngineKit) in nil } + } + + func setCameraFocusPositionInPreview(_ positionX: Float, _ positionY: Float, _ callback: PromiseCallback?) { + callback?.resolve(engine) { (engine: AgoraRtcEngineKit) in + engine.setCameraFocusPositionInPreview(CGPoint(x: CGFloat(positionX), y: CGFloat(positionY))) + return nil + } + } + + func setCameraExposurePosition(_ positionXinView: Float, _ positionYinView: Float, _ callback: PromiseCallback?) { + callback?.resolve(engine) { (engine: AgoraRtcEngineKit) in + engine.setCameraExposurePosition(CGPoint(x: CGFloat(positionXinView), y: CGFloat(positionYinView))) + return nil + } + } + + func enableFaceDetection(_ enable: Bool, _ callback: PromiseCallback?) { + callback?.resolve(engine) { (engine: AgoraRtcEngineKit) in + engine.enableFaceDetection(enable) + return nil + } + } + + func setCameraTorchOn(_ isOn: Bool, _ callback: PromiseCallback?) { + callback?.resolve(engine) { (engine: AgoraRtcEngineKit) in + engine.setCameraTorchOn(isOn) + return nil + } + } + + func setCameraAutoFocusFaceModeEnabled(_ enabled: Bool, _ callback: PromiseCallback?) { + callback?.resolve(engine) { (engine: AgoraRtcEngineKit) in + engine.setCameraAutoFocusFaceModeEnabled(enabled) + return nil + } + } + + func setCameraCapturerConfiguration(_ config: NSDictionary, _ callback: PromiseCallback?) { + callback?.code(engine?.setCameraCapturerConfiguration(mapToCameraCapturerConfiguration(config as! Dictionary))) + } + + func createDataStream(_ reliable: Bool, _ ordered: Bool, _ callback: PromiseCallback?) { + callback?.code(manager.createDataStream(reliable, ordered)) { it in it } + } + + func sendStreamMessage(_ streamId: Int, _ message: String, _ callback: PromiseCallback?) { + callback?.code(manager.sendStreamMessage(streamId, message)) + } +} + +extension RCTAgoraRtcEngineModule { + @objc func create(_ appId: String, _ areaCode: Int, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + create(appId, areaCode, PromiseCallback(resolve, reject)) + } + + @objc func destroy(_ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + destroy(PromiseCallback(resolve, reject)) + } + + @objc func setChannelProfile(_ profile: Int, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setChannelProfile(profile, PromiseCallback(resolve, reject)) + } + + @objc func setClientRole(_ role: Int, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setClientRole(role, PromiseCallback(resolve, reject)) + } + + @objc func joinChannel(_ token: String?, _ channelName: String, _ optionalInfo: String?, _ optionalUid: Int, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + joinChannel(token, channelName, optionalInfo, optionalUid, PromiseCallback(resolve, reject)) + } + + @objc func switchChannel(_ token: String?, _ channelName: String, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + switchChannel(token, channelName, PromiseCallback(resolve, reject)) + } + + @objc func leaveChannel(_ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + leaveChannel(PromiseCallback(resolve, reject)) + } + + @objc func renewToken(_ token: String, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + renewToken(token, PromiseCallback(resolve, reject)) + } + + @objc func enableWebSdkInteroperability(_ enabled: Bool, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + enableWebSdkInteroperability(enabled, PromiseCallback(resolve, reject)) + } + + @objc func getConnectionState(_ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + getConnectionState(PromiseCallback(resolve, reject)) + } + + @objc func getCallId(_ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + getCallId(PromiseCallback(resolve, reject)) + } + + @objc func rate(_ callId: String, _ rating: Int, _ description: String?, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + rate(callId, rating, description, PromiseCallback(resolve, reject)) + } + + @objc func complain(_ callId: String, _ description: String, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + complain(callId, description, PromiseCallback(resolve, reject)) + } + + @objc func setLogFile(_ filePath: String, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setLogFile(filePath, PromiseCallback(resolve, reject)) + } + + @objc func setLogFilter(_ filter: Int, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setLogFilter(filter, PromiseCallback(resolve, reject)) + } + + @objc func setLogFileSize(_ fileSizeInKBytes: Int, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setLogFileSize(fileSizeInKBytes, PromiseCallback(resolve, reject)) + } + + @objc func setParameters(_ parameters: String, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setParameters(parameters, PromiseCallback(resolve, reject)) + } + + @objc func registerLocalUserAccount(_ appId: String, _ userAccount: String, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + registerLocalUserAccount(appId, userAccount, PromiseCallback(resolve, reject)) + } + + @objc func joinChannelWithUserAccount(_ token: String?, _ channelName: String, _ userAccount: String, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + joinChannelWithUserAccount(token, channelName, userAccount, PromiseCallback(resolve, reject)) + } + + @objc func getUserInfoByUserAccount(_ userAccount: String, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + getUserInfoByUserAccount(userAccount, PromiseCallback(resolve, reject)) + } + + @objc func getUserInfoByUid(_ uid: Int, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + getUserInfoByUid(uid, PromiseCallback(resolve, reject)) + } + + @objc func enableAudio(_ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + enableAudio(PromiseCallback(resolve, reject)) + } + + @objc func disableAudio(_ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + disableAudio(PromiseCallback(resolve, reject)) + } + + @objc func setAudioProfile(_ profile: Int, _ scenario: Int, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setAudioProfile(profile, scenario, PromiseCallback(resolve, reject)) + } + + @objc func adjustRecordingSignalVolume(_ volume: Int, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + adjustRecordingSignalVolume(volume, PromiseCallback(resolve, reject)) + } + + @objc func adjustUserPlaybackSignalVolume(_ uid: Int, _ volume: Int, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + adjustUserPlaybackSignalVolume(uid, volume, PromiseCallback(resolve, reject)) + } + + @objc func adjustPlaybackSignalVolume(_ volume: Int, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + adjustPlaybackSignalVolume(volume, PromiseCallback(resolve, reject)) + } + + @objc func enableLocalAudio(_ enabled: Bool, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + enableLocalAudio(enabled, PromiseCallback(resolve, reject)) + } + + @objc func muteLocalAudioStream(_ muted: Bool, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + muteLocalAudioStream(muted, PromiseCallback(resolve, reject)) + } + + @objc func muteRemoteAudioStream(_ uid: Int, _ muted: Bool, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + muteRemoteAudioStream(uid, muted, PromiseCallback(resolve, reject)) + } + + @objc func muteAllRemoteAudioStreams(_ muted: Bool, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + muteAllRemoteAudioStreams(muted, PromiseCallback(resolve, reject)) + } + + @objc func setDefaultMuteAllRemoteAudioStreams(_ muted: Bool, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setDefaultMuteAllRemoteAudioStreams(muted, PromiseCallback(resolve, reject)) + } + + @objc func enableAudioVolumeIndication(_ interval: Int, _ smooth: Int, _ report_vad: Bool, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + enableAudioVolumeIndication(interval, smooth, report_vad, PromiseCallback(resolve, reject)) + } + + @objc func enableVideo(_ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + enableVideo(PromiseCallback(resolve, reject)) + } + + @objc func disableVideo(_ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + disableVideo(PromiseCallback(resolve, reject)) + } + + @objc func setVideoEncoderConfiguration(_ config: NSDictionary, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setVideoEncoderConfiguration(config, PromiseCallback(resolve, reject)) + } + + @objc func enableLocalVideo(_ enabled: Bool, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + enableLocalVideo(enabled, PromiseCallback(resolve, reject)) + } + + @objc func muteLocalVideoStream(_ muted: Bool, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + muteLocalVideoStream(muted, PromiseCallback(resolve, reject)) + } + + @objc func muteRemoteVideoStream(_ uid: Int, _ muted: Bool, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + muteRemoteVideoStream(uid, muted, PromiseCallback(resolve, reject)) + } + + @objc func muteAllRemoteVideoStreams(_ muted: Bool, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + muteAllRemoteVideoStreams(muted, PromiseCallback(resolve, reject)) + } + + @objc func setDefaultMuteAllRemoteVideoStreams(_ muted: Bool, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setDefaultMuteAllRemoteVideoStreams(muted, PromiseCallback(resolve, reject)) + } + + @objc func setBeautyEffectOptions(_ enabled: Bool, _ options: NSDictionary, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setBeautyEffectOptions(enabled, options, PromiseCallback(resolve, reject)) + } + + @objc func startAudioMixing(_ filePath: String, _ loopback: Bool, _ replace: Bool, _ cycle: Int, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + startAudioMixing(filePath, loopback, replace, cycle, PromiseCallback(resolve, reject)) + } + + @objc func stopAudioMixing(_ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + stopAudioMixing(PromiseCallback(resolve, reject)) + } + + @objc func pauseAudioMixing(_ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + pauseAudioMixing(PromiseCallback(resolve, reject)) + } + + @objc func resumeAudioMixing(_ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + resumeAudioMixing(PromiseCallback(resolve, reject)) + } + + @objc func adjustAudioMixingVolume(_ volume: Int, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + adjustAudioMixingVolume(volume, PromiseCallback(resolve, reject)) + } + + @objc func adjustAudioMixingPlayoutVolume(_ volume: Int, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + adjustAudioMixingPlayoutVolume(volume, PromiseCallback(resolve, reject)) + } + + @objc func adjustAudioMixingPublishVolume(_ volume: Int, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + adjustAudioMixingPublishVolume(volume, PromiseCallback(resolve, reject)) + } + + @objc func getAudioMixingPlayoutVolume(_ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + getAudioMixingPlayoutVolume(PromiseCallback(resolve, reject)) + } + + @objc func getAudioMixingPublishVolume(_ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + getAudioMixingPublishVolume(PromiseCallback(resolve, reject)) + } + + @objc func getAudioMixingDuration(_ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + getAudioMixingDuration(PromiseCallback(resolve, reject)) + } + + @objc func getAudioMixingCurrentPosition(_ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + getAudioMixingCurrentPosition(PromiseCallback(resolve, reject)) + } + + @objc func setAudioMixingPosition(_ pos: Int, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setAudioMixingPosition(pos, PromiseCallback(resolve, reject)) + } + + @objc func setAudioMixingPitch(_ pitch: Int, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setAudioMixingPitch(pitch, PromiseCallback(resolve, reject)) + } + + @objc func getEffectsVolume(_ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + getEffectsVolume(PromiseCallback(resolve, reject)) + } + + @objc func setEffectsVolume(_ volume: Double, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setEffectsVolume(volume, PromiseCallback(resolve, reject)) + } + + @objc func setVolumeOfEffect(_ soundId: Int, _ volume: Double, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setVolumeOfEffect(soundId, volume, PromiseCallback(resolve, reject)) + } + + @objc func playEffect(_ soundId: Int, _ filePath: String, _ loopCount: Int, _ pitch: Double, _ pan: Double, _ gain: Double, _ publish: Bool, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + playEffect(soundId, filePath, loopCount, pitch, pan, gain, publish, PromiseCallback(resolve, reject)) + } + + @objc func stopEffect(_ soundId: Int, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + stopEffect(soundId, PromiseCallback(resolve, reject)) + } + + @objc func stopAllEffects(_ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + stopAllEffects(PromiseCallback(resolve, reject)) + } + + @objc func preloadEffect(_ soundId: Int, _ filePath: String, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + preloadEffect(soundId, filePath, PromiseCallback(resolve, reject)) + } + + @objc func unloadEffect(_ soundId: Int, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + unloadEffect(soundId, PromiseCallback(resolve, reject)) + } + + @objc func pauseEffect(_ soundId: Int, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + pauseEffect(soundId, PromiseCallback(resolve, reject)) + } + + @objc func pauseAllEffects(_ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + pauseAllEffects(PromiseCallback(resolve, reject)) + } + + @objc func resumeEffect(_ soundId: Int, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + resumeEffect(soundId, PromiseCallback(resolve, reject)) + } + + @objc func resumeAllEffects(_ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + resumeAllEffects(PromiseCallback(resolve, reject)) + } + + @objc func setLocalVoiceChanger(_ voiceChanger: Int, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setLocalVoiceChanger(voiceChanger, PromiseCallback(resolve, reject)) + } + + @objc func setLocalVoiceReverbPreset(_ preset: Int, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setLocalVoiceReverbPreset(preset, PromiseCallback(resolve, reject)) + } + + @objc func setLocalVoicePitch(_ pitch: Double, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setLocalVoicePitch(pitch, PromiseCallback(resolve, reject)) + } + + @objc func setLocalVoiceEqualization(_ bandFrequency: Int, _ bandGain: Int, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setLocalVoiceEqualization(bandFrequency, bandGain, PromiseCallback(resolve, reject)) + } + + @objc func setLocalVoiceReverb(_ reverbKey: Int, _ value: Int, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setLocalVoiceReverb(reverbKey, value, PromiseCallback(resolve, reject)) + } + + @objc func enableSoundPositionIndication(_ enabled: Bool, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + enableSoundPositionIndication(enabled, PromiseCallback(resolve, reject)) + } + + @objc func setRemoteVoicePosition(_ uid: Int, _ pan: Double, _ gain: Double, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setRemoteVoicePosition(uid, pan, gain, PromiseCallback(resolve, reject)) + } + + @objc func setLiveTranscoding(_ transcoding: NSDictionary, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setLiveTranscoding(transcoding, PromiseCallback(resolve, reject)) + } + + @objc func addPublishStreamUrl(_ url: String, _ transcodingEnabled: Bool, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + addPublishStreamUrl(url, transcodingEnabled, PromiseCallback(resolve, reject)) + } + + @objc func removePublishStreamUrl(_ url: String, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + removePublishStreamUrl(url, PromiseCallback(resolve, reject)) + } + + @objc func startChannelMediaRelay(_ channelMediaRelayConfiguration: NSDictionary, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + startChannelMediaRelay(channelMediaRelayConfiguration, PromiseCallback(resolve, reject)) + } + + @objc func updateChannelMediaRelay(_ channelMediaRelayConfiguration: NSDictionary, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + updateChannelMediaRelay(channelMediaRelayConfiguration, PromiseCallback(resolve, reject)) + } + + @objc func stopChannelMediaRelay(_ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + stopChannelMediaRelay(PromiseCallback(resolve, reject)) + } + + @objc func setDefaultAudioRoutetoSpeakerphone(_ defaultToSpeaker: Bool, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setDefaultAudioRoutetoSpeakerphone(defaultToSpeaker, PromiseCallback(resolve, reject)) + } + + @objc func setEnableSpeakerphone(_ enabled: Bool, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setEnableSpeakerphone(enabled, PromiseCallback(resolve, reject)) + } + + @objc func isSpeakerphoneEnabled(_ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + isSpeakerphoneEnabled(PromiseCallback(resolve, reject)) + } + + @objc func enableInEarMonitoring(_ enabled: Bool, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + enableInEarMonitoring(enabled, PromiseCallback(resolve, reject)) + } + + @objc func setInEarMonitoringVolume(_ volume: Int, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setInEarMonitoringVolume(volume, PromiseCallback(resolve, reject)) + } + + @objc func enableDualStreamMode(_ enabled: Bool, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + enableDualStreamMode(enabled, PromiseCallback(resolve, reject)) + } + + @objc func setRemoteVideoStreamType(_ uid: Int, _ streamType: Int, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setRemoteVideoStreamType(uid, streamType, PromiseCallback(resolve, reject)) + } + + @objc func setRemoteDefaultVideoStreamType(_ streamType: Int, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setRemoteDefaultVideoStreamType(streamType, PromiseCallback(resolve, reject)) + } + + @objc func setLocalPublishFallbackOption(_ option: Int, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setLocalPublishFallbackOption(option, PromiseCallback(resolve, reject)) + } + + @objc func setRemoteSubscribeFallbackOption(_ option: Int, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setRemoteSubscribeFallbackOption(option, PromiseCallback(resolve, reject)) + } + + @objc func setRemoteUserPriority(_ uid: Int, _ userPriority: Int, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setRemoteUserPriority(uid, userPriority, PromiseCallback(resolve, reject)) + } + + @objc func startEchoTest(_ intervalInSeconds: Int, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + startEchoTest(intervalInSeconds, PromiseCallback(resolve, reject)) + } + + @objc func stopEchoTest(_ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + stopEchoTest(PromiseCallback(resolve, reject)) + } + + @objc func enableLastmileTest(_ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + enableLastmileTest(PromiseCallback(resolve, reject)) + } + + @objc func disableLastmileTest(_ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + disableLastmileTest(PromiseCallback(resolve, reject)) + } + + @objc func startLastmileProbeTest(_ config: NSDictionary, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + startLastmileProbeTest(config, PromiseCallback(resolve, reject)) + } + + @objc func stopLastmileProbeTest(_ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + stopLastmileProbeTest(PromiseCallback(resolve, reject)) + } + + @objc func registerMediaMetadataObserver(_ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + registerMediaMetadataObserver(PromiseCallback(resolve, reject)) + } + + @objc func unregisterMediaMetadataObserver(_ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + unregisterMediaMetadataObserver(PromiseCallback(resolve, reject)) + } + + @objc func setMaxMetadataSize(_ size: Int, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setMaxMetadataSize(size, PromiseCallback(resolve, reject)) + } + + @objc func sendMetadata(_ metadata: String, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + sendMetadata(metadata, PromiseCallback(resolve, reject)) + } + + @objc func addVideoWatermark(_ watermarkUrl: String, _ options: NSDictionary, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + addVideoWatermark(watermarkUrl, options, PromiseCallback(resolve, reject)) + } + + @objc func clearVideoWatermarks(_ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + clearVideoWatermarks(PromiseCallback(resolve, reject)) + } + + @objc func setEncryptionSecret(_ secret: String, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setEncryptionSecret(secret, PromiseCallback(resolve, reject)) + } + + @objc func setEncryptionMode(_ encryptionMode: String, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setEncryptionMode(encryptionMode, PromiseCallback(resolve, reject)) + } + + @objc func startAudioRecording(_ filePath: String, _ sampleRate: Int, _ quality: Int, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + startAudioRecording(filePath, sampleRate, quality, PromiseCallback(resolve, reject)) + } + + @objc func stopAudioRecording(_ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + stopAudioRecording(PromiseCallback(resolve, reject)) + } + + @objc func addInjectStreamUrl(_ url: String, _ config: NSDictionary, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + addInjectStreamUrl(url, config, PromiseCallback(resolve, reject)) + } + + @objc func removeInjectStreamUrl(_ url: String, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + removeInjectStreamUrl(url, PromiseCallback(resolve, reject)) + } + + @objc func switchCamera(_ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + switchCamera(PromiseCallback(resolve, reject)) + } + + @objc func isCameraZoomSupported(_ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + isCameraZoomSupported(PromiseCallback(resolve, reject)) + } + + @objc func isCameraTorchSupported(_ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + isCameraTorchSupported(PromiseCallback(resolve, reject)) + } + + @objc func isCameraFocusSupported(_ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + // TODO Not in iOS + isCameraFocusSupported(PromiseCallback(resolve, reject)) + } + + @objc func isCameraExposurePositionSupported(_ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + isCameraExposurePositionSupported(PromiseCallback(resolve, reject)) + } + + @objc func isCameraAutoFocusFaceModeSupported(_ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + isCameraAutoFocusFaceModeSupported(PromiseCallback(resolve, reject)) + } + + @objc func setCameraZoomFactor(_ factor: Float, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setCameraZoomFactor(factor, PromiseCallback(resolve, reject)) + } + + @objc func getCameraMaxZoomFactor(_ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + // TODO Not in iOS + getCameraMaxZoomFactor(PromiseCallback(resolve, reject)) + } + + @objc func setCameraFocusPositionInPreview(_ positionX: Float, _ positionY: Float, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setCameraFocusPositionInPreview(positionX, positionY, PromiseCallback(resolve, reject)) + } + + @objc func setCameraExposurePosition(_ positionXinView: Float, _ positionYinView: Float, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setCameraExposurePosition(positionXinView, positionYinView, PromiseCallback(resolve, reject)) + } + + @objc func enableFaceDetection(_ enable: Bool, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + enableFaceDetection(enable, PromiseCallback(resolve, reject)) + } + + @objc func setCameraTorchOn(_ isOn: Bool, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setCameraTorchOn(isOn, PromiseCallback(resolve, reject)) + } + + @objc func setCameraAutoFocusFaceModeEnabled(_ enabled: Bool, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setCameraAutoFocusFaceModeEnabled(enabled, PromiseCallback(resolve, reject)) + } + + @objc func setCameraCapturerConfiguration(_ config: NSDictionary, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + setCameraCapturerConfiguration(config, PromiseCallback(resolve, reject)) + } + + @objc func createDataStream(_ reliable: Bool, _ ordered: Bool, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + createDataStream(reliable, ordered, PromiseCallback(resolve, reject)) + } + + @objc func sendStreamMessage(_ streamId: Int, _ message: String, _ resolve: RCTPromiseResolveBlock?, _ reject: RCTPromiseRejectBlock?) { + sendStreamMessage(streamId, message, PromiseCallback(resolve, reject)) + } +} diff --git a/ios/RCTAgora/React/RCTAgoraRtcEngineModuleBridge.m b/ios/RCTAgora/React/RCTAgoraRtcEngineModuleBridge.m new file mode 100644 index 000000000..87f38a087 --- /dev/null +++ b/ios/RCTAgora/React/RCTAgoraRtcEngineModuleBridge.m @@ -0,0 +1,389 @@ +// +// RCTAgoraRtcEngineModuleBridge.m +// RCTAgora +// +// Created by LXH on 2020/4/14. +// Copyright © 2020 Syan. All rights reserved. +// + +#import +#import + +@interface RCT_EXTERN_MODULE(RCTAgoraRtcEngineModule, NSObject) + +RCT_EXTERN_METHOD(create: + (NSString *) appId :(NSInteger) areaCode :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(destroy: + (RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setChannelProfile: + (NSInteger) profile :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setClientRole: + (NSInteger) role :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(joinChannel: + (NSString *) token :(NSString *) channelName :(NSString *) optionalInfo :(NSInteger) optionalUid :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(switchChannel: + (NSString *) token :(NSString *) channelName :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(leaveChannel: + (RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(renewToken: + (NSString *) token :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(enableWebSdkInteroperability: + (BOOL) enabled :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(getConnectionState: + (RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(getCallId: + (RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(rate: + (NSString *) callId :(NSInteger) rating :(NSString *) description :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(complain: + (NSString *) callId :(NSString *) description :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setLogFile: + (NSString *) filePath :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setLogFilter: + (NSInteger) filter :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setLogFileSize: + (NSInteger) fileSizeInKBytes :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setParameters: + (NSString *) parameters :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(registerLocalUserAccount: + (NSString *) appId :(NSString *) userAccount :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(joinChannelWithUserAccount: + (NSString *) token :(NSString *) channelName :(NSString *) userAccount :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(getUserInfoByUserAccount: + (NSString *) userAccount :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(getUserInfoByUid: + (NSInteger) uid :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(enableAudio: + (RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(disableAudio: + (RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setAudioProfile: + (NSInteger) profile :(NSInteger) scenario :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(adjustRecordingSignalVolume: + (NSInteger) volume :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(adjustUserPlaybackSignalVolume: + (NSInteger) uid :(NSInteger) volume :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(adjustPlaybackSignalVolume: + (NSInteger) volume :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(enableLocalAudio: + (BOOL) enabled :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(muteLocalAudioStream: + (BOOL) muted :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(muteRemoteAudioStream: + (NSInteger) uid :(BOOL) muted :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(muteAllRemoteAudioStreams: + (BOOL) muted :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setDefaultMuteAllRemoteAudioStreams: + (BOOL) muted :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(enableAudioVolumeIndication: + (NSInteger) interval :(NSInteger) smooth :(BOOL) report_vad :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(enableVideo: + (RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(disableVideo: + (RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setVideoEncoderConfiguration: + (NSDictionary *) config :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(enableLocalVideo: + (BOOL) enabled :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(muteLocalVideoStream: + (BOOL) muted :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(muteRemoteVideoStream: + (NSInteger) uid :(BOOL) muted :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(muteAllRemoteVideoStreams: + (BOOL) muted :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setDefaultMuteAllRemoteVideoStreams: + (BOOL) muted :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setBeautyEffectOptions: + (BOOL) enabled :(NSDictionary *) options :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(startAudioMixing: + (NSString *) filePath :(BOOL) loopback :(BOOL) replace :(NSInteger) cycle :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(stopAudioMixing: + (RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(pauseAudioMixing: + (RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(resumeAudioMixing: + (RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(adjustAudioMixingVolume: + (NSInteger) volume :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(adjustAudioMixingPlayoutVolume: + (NSInteger) volume :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(adjustAudioMixingPublishVolume: + (NSInteger) volume :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(getAudioMixingPlayoutVolume: + (RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(getAudioMixingPublishVolume: + (RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(getAudioMixingDuration: + (RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(getAudioMixingCurrentPosition: + (RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setAudioMixingPosition: + (NSInteger) pos :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setAudioMixingPitch: + (NSInteger) pitch :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(getEffectsVolume: + (RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setEffectsVolume: + (double) volume :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setVolumeOfEffect: + (NSInteger) soundId :(double) volume :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(playEffect: + (NSInteger) soundId :(NSString *) filePath :(NSInteger) loopCount :(double) pitch :(double) pan :(double) gain :(BOOL) publish :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(stopEffect: + (NSInteger) soundId :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(stopAllEffects: + (RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(preloadEffect: + (NSInteger) soundId :(NSString *) filePath :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(unloadEffect: + (NSInteger) soundId :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(pauseEffect: + (NSInteger) soundId :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(pauseAllEffects: + (RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(resumeEffect: + (NSInteger) soundId :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(resumeAllEffects: + (RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setLocalVoiceChanger: + (NSInteger) voiceChanger :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setLocalVoiceReverbPreset: + (NSInteger) preset :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setLocalVoicePitch: + (double) pitch :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setLocalVoiceEqualization: + (NSInteger) bandFrequency :(NSInteger) bandGain :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setLocalVoiceReverb: + (NSInteger) reverbKey :(NSInteger) value :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(enableSoundPositionIndication: + (BOOL) enabled :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setRemoteVoicePosition: + (NSInteger) uid :(double) pan :(double) gain :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setLiveTranscoding: + (NSDictionary *) transcoding :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(addPublishStreamUrl: + (NSString *) url :(BOOL) transcodingEnabled :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(removePublishStreamUrl: + (NSString *) url :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(startChannelMediaRelay: + (NSDictionary *) channelMediaRelayConfiguration :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(updateChannelMediaRelay: + (NSDictionary *) channelMediaRelayConfiguration :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(stopChannelMediaRelay: + (RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setDefaultAudioRoutetoSpeakerphone: + (BOOL) defaultToSpeaker :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setEnableSpeakerphone: + (BOOL) enabled :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(isSpeakerphoneEnabled: + (RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(enableInEarMonitoring: + (BOOL) enabled :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setInEarMonitoringVolume: + (NSInteger) volume :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(enableDualStreamMode: + (BOOL) enabled :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setRemoteVideoStreamType: + (NSInteger) uid :(NSInteger) streamType :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setRemoteDefaultVideoStreamType: + (NSInteger) streamType :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setLocalPublishFallbackOption: + (NSInteger) option :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setRemoteSubscribeFallbackOption: + (NSInteger) option :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setRemoteUserPriority: + (NSInteger) uid :(NSInteger) userPriority :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(startEchoTest: + (NSInteger) intervalInSeconds :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(stopEchoTest: + (RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(enableLastmileTest: + (RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(disableLastmileTest: + (RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(startLastmileProbeTest: + (NSDictionary *) config :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(stopLastmileProbeTest: + (RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(registerMediaMetadataObserver: + (RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(unregisterMediaMetadataObserver: + (RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setMaxMetadataSize: + (NSInteger) size :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(sendMetadata: + (NSString *) metadata :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(addVideoWatermark: + (NSString *) watermarkUrl :(NSDictionary *) options :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(clearVideoWatermarks: + (RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setEncryptionSecret: + (NSString *) secret :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setEncryptionMode: + (NSString *) encryptionMode :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(startAudioRecording: + (NSString *) filePath :(NSInteger) sampleRate :(NSInteger) quality :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(stopAudioRecording: + (RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(addInjectStreamUrl: + (NSString *) url :(NSDictionary *) config :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(removeInjectStreamUrl: + (NSString *) url :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(switchCamera: + (RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(isCameraZoomSupported: + (RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(isCameraTorchSupported: + (RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(isCameraFocusSupported: + (RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(isCameraExposurePositionSupported: + (RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(isCameraAutoFocusFaceModeSupported: + (RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setCameraZoomFactor: + (float) factor :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(getCameraMaxZoomFactor: + (RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setCameraFocusPositionInPreview: + (float) positionX :(float) positionY :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setCameraExposurePosition: + (float) positionXinView :(float) positionYinView :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(enableFaceDetection: + (BOOL) enable :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setCameraTorchOn: + (BOOL) isOn :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setCameraAutoFocusFaceModeEnabled: + (BOOL) enabled :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(setCameraCapturerConfiguration: + (NSDictionary *) config :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(createDataStream: + (BOOL) reliable :(BOOL) ordered :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +RCT_EXTERN_METHOD(sendStreamMessage: + (NSInteger) streamId :(NSString *) message :(RCTPromiseResolveBlock) resolve :(RCTPromiseRejectBlock) reject) + +@end diff --git a/ios/RCTAgora/React/RCTAgoraRtcSurfaceViewManager.swift b/ios/RCTAgora/React/RCTAgoraRtcSurfaceViewManager.swift new file mode 100644 index 000000000..0e5e57d44 --- /dev/null +++ b/ios/RCTAgora/React/RCTAgoraRtcSurfaceViewManager.swift @@ -0,0 +1,74 @@ +// +// RCTAgoraRtcSurfaceViewManager.swift +// RCTAgora +// +// Created by LXH on 2020/4/15. +// Copyright (c) 2020 Syan. All rights reserved. +// + +import Foundation +import AgoraRtcKit + +@objc(RCTAgoraRtcSurfaceViewManager) +class RCTAgoraRtcSurfaceViewManager: RCTViewManager { + override func view() -> UIView! { + let view = RtcView() + view.setEngine(engine) + view.setChannel(channel(_:)) + return view + } + + override class func requiresMainQueueSetup() -> Bool { + true + } + + override var methodQueue: DispatchQueue! { + DispatchQueue.main + } + + private func engine() -> AgoraRtcEngineKit? { + (bridge.module(for: RCTAgoraRtcEngineModule.classForCoder()) as? RCTAgoraRtcEngineModule)?.engine + } + + private func channel(_ channelId: String) -> AgoraRtcChannel? { + (bridge.module(for: RCTAgoraRtcChannelModule.classForCoder()) as? RCTAgoraRtcChannelModule)?.channel(channelId) + } +} + +@objc(RtcView) +class RtcView: RtcSurfaceView { + private var getEngine: (() -> AgoraRtcEngineKit?)? + private var getChannel: ((_ channelId: String) -> AgoraRtcChannel?)? + + func setEngine(_ getEngine: @escaping () -> AgoraRtcEngineKit?) { + self.getEngine = getEngine + } + + func setChannel(_ getChannel: @escaping (_ channelId: String) -> AgoraRtcChannel?) { + self.getChannel = getChannel + } + + @objc func setRenderMode(_ renderMode: Int) { + if let engine = getEngine?() { + setRenderMode(engine, renderMode) + } + } + + @objc func setChannelId(_ channelId: String) { + if let engine = getEngine?(), let channel = getChannel?(channelId) { + setChannel(engine, channel) + } + } + + @objc func setMirrorMode(_ mirrorMode: Int) { + if let engine = getEngine?() { + setMirrorMode(engine, mirrorMode) + } + } + + @objc func setUid(_ uid: Int) { + if let engine = getEngine?() { + setUid(engine, uid) + } + } +} diff --git a/ios/RCTAgora/React/RCTAgoraRtcSurfaceViewManagerBridge.m b/ios/RCTAgora/React/RCTAgoraRtcSurfaceViewManagerBridge.m new file mode 100644 index 000000000..4a792342d --- /dev/null +++ b/ios/RCTAgora/React/RCTAgoraRtcSurfaceViewManagerBridge.m @@ -0,0 +1,21 @@ +// +// RCTAgoraRtcSurfaceViewManagerBridge.m +// RCTAgora +// +// Created by LXH on 2020/4/15. +// Copyright (c) 2020 Syan. All rights reserved. +// + +#import + +@interface RCT_EXTERN_MODULE(RCTAgoraRtcSurfaceViewManager, NSObject) + +RCT_EXPORT_VIEW_PROPERTY(renderMode, NSInteger) + +RCT_EXPORT_VIEW_PROPERTY(channelId, NSString) + +RCT_EXPORT_VIEW_PROPERTY(mirrorMode, NSInteger) + +RCT_EXPORT_VIEW_PROPERTY(uid, NSInteger) + +@end diff --git a/lib/AgoraView.native.d.ts b/lib/AgoraView.native.d.ts deleted file mode 100644 index 312b7fa2a..000000000 --- a/lib/AgoraView.native.d.ts +++ /dev/null @@ -1,30 +0,0 @@ -import React from 'react'; -import { AgoraViewProps } from "./types"; -/** - * AgoraView is the render layer for rendering video stream - * - * This class is used to rendering native sdk stream - * @props {@link AgoraViewProps} - * - * @descrption AgoraViewProps has four properties. - * @property mode: {@link AgoraViewMode}, this property will setup video render mode. You could see more [details](https://docs.agora.io/en/Interactive%20Broadcast/API%20Reference/java/classio_1_1agora_1_1rtc_1_1_rtc_engine.html#ac08882c4d0ec47b329900df169493673) - * @property showLocalVideo: boolean, this property will render local video, NOTICE: IF YOU SET showLocalVideo YOU CANNOT SET remoteUid - * @property remoteUid: number, this property will render video with remote uid, NOTICE: IF YOU SET remoteUid YOU CANNOT SET showLocalVideo - * @property zOrderMediaOverlay: boolean, this property will working for android side and it likes zIndex behaviour on web side. - * - * @noInheritDoc - */ -export default class AgoraView extends React.Component { - /** - * render - * - * It would render view for VideoStream - */ - render(): JSX.Element; - /** - * getHTMLProps - * - * get agora view props - */ - private getHTMLProps; -} diff --git a/lib/AgoraView.native.js b/lib/AgoraView.native.js deleted file mode 100644 index 38df5b80a..000000000 --- a/lib/AgoraView.native.js +++ /dev/null @@ -1,55 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const tslib_1 = require("tslib"); -const react_1 = tslib_1.__importDefault(require("react")); -const react_native_1 = require("react-native"); -/** - * Import RCTAgoraView from native binding. - * - * This @object is used to bridge native layer between react layer. - */ -const RCTAgoraView = react_native_1.requireNativeComponent("RCTAgoraVideoView"); -/** - * AgoraView is the render layer for rendering video stream - * - * This class is used to rendering native sdk stream - * @props {@link AgoraViewProps} - * - * @descrption AgoraViewProps has four properties. - * @property mode: {@link AgoraViewMode}, this property will setup video render mode. You could see more [details](https://docs.agora.io/en/Interactive%20Broadcast/API%20Reference/java/classio_1_1agora_1_1rtc_1_1_rtc_engine.html#ac08882c4d0ec47b329900df169493673) - * @property showLocalVideo: boolean, this property will render local video, NOTICE: IF YOU SET showLocalVideo YOU CANNOT SET remoteUid - * @property remoteUid: number, this property will render video with remote uid, NOTICE: IF YOU SET remoteUid YOU CANNOT SET showLocalVideo - * @property zOrderMediaOverlay: boolean, this property will working for android side and it likes zIndex behaviour on web side. - * - * @noInheritDoc - */ -class AgoraView extends react_1.default.Component { - /** - * render - * - * It would render view for VideoStream - */ - render() { - return (react_1.default.createElement(RCTAgoraView, Object.assign({}, this.getHTMLProps()))); - } - /** - * getHTMLProps - * - * get agora view props - */ - getHTMLProps() { - let htmlProps = {}; - for (let key in this.props) { - htmlProps[key] = this.props[key]; - } - // convert uint32 to int32 for android - if (react_native_1.Platform.OS === 'android') { - const int32 = new Int32Array(1); - int32[0] = htmlProps.remoteUid; - htmlProps.remoteUid = int32[0]; - } - return htmlProps; - } -} -exports.default = AgoraView; -//# sourceMappingURL=AgoraView.native.js.map \ No newline at end of file diff --git a/lib/AgoraView.native.js.map b/lib/AgoraView.native.js.map deleted file mode 100644 index 533db7e11..000000000 --- a/lib/AgoraView.native.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"AgoraView.native.js","sourceRoot":"","sources":["../src/AgoraView.native.tsx"],"names":[],"mappings":";;;AAAA,0DAA0B;AAC1B,+CAGqB;AAMrB;;;;GAIG;AAEH,MAAM,YAAY,GAAG,qCAAsB,CAAC,mBAAmB,CAAC,CAAC;AAEjE;;;;;;;;;;;;;GAaG;AACH,MAAqB,SAAU,SAAQ,eAAK,CAAC,SAAiC;IAC1E;;;;OAIG;IACI,MAAM;QACT,OAAO,CACH,8BAAC,YAAY,oBAAM,IAAI,CAAC,YAAY,EAAE,EAAK,CAC9C,CAAA;IACL,CAAC;IAED;;;;OAIG;IACK,YAAY;QAChB,IAAI,SAAS,GAAG,EAAoB,CAAC;QACrC,KAAK,IAAI,GAAG,IAAI,IAAI,CAAC,KAAK,EAAE;YACxB,SAAS,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;SACpC;QAED,sCAAsC;QACtC,IAAI,uBAAQ,CAAC,EAAE,KAAK,SAAS,EAAE;YAC3B,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC,CAAC,CAAC,CAAC;YAChC,KAAK,CAAC,CAAC,CAAC,GAAG,SAAS,CAAC,SAAS,CAAC;YAC/B,SAAS,CAAC,SAAS,GAAG,KAAK,CAAC,CAAC,CAAC,CAAA;SACjC;QACD,OAAO,SAAS,CAAC;IACrB,CAAC;CACJ;AA/BD,4BA+BC"} \ No newline at end of file diff --git a/lib/RtcEngine.native.d.ts b/lib/RtcEngine.native.d.ts deleted file mode 100644 index 8fe5239bd..000000000 --- a/lib/RtcEngine.native.d.ts +++ /dev/null @@ -1,1212 +0,0 @@ -import { AgoraUserInfo, AudioFrameOption, AudioMixingOption, AudioRecordingOption, BeautyOption, Callback, CameraCapturerConfiguration, ChannelMediaConfiguration, DefaultVideoStreamOption, ImageOption, InjectStreamOption, LastmileProbeConfig, LiveTranscodingOption, MixedAudioFrameOption, Option, PlayEffectOption, PositionOption, PublishStreamOption, RemoveInjectStreamOption, RemovePublishStreamOption, VideoStreamOption } from "./types"; -/** - * RtcEngine is the javascript object for control agora native sdk through react native bridge. - * - * You can use the RtcEngine methods to create {@link init} - * - * Other methods of the RtcEngine object serve for agora native sdk and set up error logging. - */ -declare class RtcEngine { - /** - * @ignore eventTypes - */ - private static readonly _eventTypes; - /** - * @ignore AG_PREFIX - */ - private static readonly AG_PREFIX; - /** - * Creates a RtcEngine Object internal. - * - * This method creates and start event observer. You should call this method once. - * @example `RtcEngine.init(option)` - * @param options Defines the property of the client, see {@link Option} for details. - * @returns any - */ - static init(options: Option): void; - /** - * join specified channel - * - * This method joins and begin rendering the video stream. when join succeeds. - * Otherwise, it will invoke error by the event - * @param channelName - * @param uid - * @param token - * @param info - * @returns Promise - */ - static joinChannel(channelName: string, uid?: number, token?: string, info?: string): Promise; - /** - * switch to specified channel - * - * This method will switch channel smoothly than you invoke leaveChannel & joinChannel. - * Otherwise, it will invoke error by the event - * It will occurs two events: - * Occurs leaveChannel when achieve leaving stage - * Occurs joinChannelSuccess when achieve joining stage - * @param channelName {@link string} - * @param token {@link string} - * @returns Promise - */ - static switchChannel(channelName: string, token?: string): Promise; - /** - * Starts to relay media streams across channels. - * - * This method will start relay media stream across specified channels. (maximum support 4 channels) - * It will occurs event: - * Occurs mediaRelayStateChanged - * Occurs receivedChannelMediaRelay when peer channel received this message - * @param config {@link ChannelMediaConfiguration} - * @returns Promise - */ - static startChannelMediaRelay(config: ChannelMediaConfiguration): Promise; - /** - * Remove to relay media streams across channels. - * - * This method will remove & update relay media stream across specified channels. (maximum support relay 4 channels) - * It will occurs event: - * Occurs mediaRelayStateChanged - * @param config {@link ChannelMediaConfiguration} - * @returns Promise - */ - static removeChannelMediaRelay(config: ChannelMediaConfiguration): Promise; - /** - * Updates to relay media streams across channels. - * - * This method will update relay media stream across specified channels. (maximum support 4 channels) - * It will occurs event: - * Occurs mediaRelayStateChanged - * @param config {@link ChannelMediaConfiguration} - * @returns Promise - */ - static updateChannelMediaRelay(config: ChannelMediaConfiguration): Promise; - /** - * Stop to relay media streams across channels. - * - * This method will stop relay media stream across specified channels. - * It will occurs event: - * Occurs mediaRelayStateChanged - * @param config {@link ChannelMediaConfiguration} - * @returns Promise - */ - static stopChannelMediaRelay(): Promise; - /** - * Registers a user account. - * - * Once registered, the user account can be used to identify the local user when the user joins the channel. After the user successfully registers a user account, the SDK triggers the `on("localUserRegistered", callback)` on the local client, reporting the user ID and user account of the local user. - * To join a channel with a user account, you can choose either of the following: - * Call the {@link registerLocalUserAccount} method to create a user account, and then the {@link joinChannelWithUserAccount} method to join the channel. - * Call the {@link joinChannelWithUserAccount} method to join the channel. - * - * @note To ensure smooth communication, use the same parameter type to identify the user. For example, if a user joins the channel with a user ID, then ensure all the other users use the user ID too. The same applies to the user account. If a user joins the channel with the Agora Web SDK, ensure that the uid of the user is set to the same parameter type. - * - * @param userAccount - * @returns Promise - */ - static registerLocalUserAccount(userAccount: string): Promise; - /** - * Joins the channel with a user account. - * - * After the user successfully joins the channel, the SDK triggers the following callbacks: - * - * The local client: `on("localUserRegistered", callback)` and `on("joinChannelSuccess", callback)`. - * The remote client: `on("userJoined", callback)` and `on("userInfoUpdated", callback)`, if the user joining the channel is in the Communication profile, or is a BROADCASTER in the Live Broadcast profile. - * - * @note To ensure smooth communication, use the same parameter type to identify the user. For example, if a user joins the channel with a user ID, then ensure all the other users use the user ID too. The same applies to the user account. If a user joins the channel with the Agora Web SDK, ensure that the uid of the user is set to the same parameter type. - * - * @param channelName - * @param userAccount - * @param token - * @returns Promise - */ - static joinChannelWithUserAccount(channelName: string, userAccount: string, token: string): Promise; - /** - * Gets the user information by passing in the user account. - * - * After receiving the "userInfoUpdated" callback, you can call this method to get the user ID of the remote user from the {@link AgoraUserInfo} object by passing in the userAccount. - * @param uid - * @returns Promise<{@link AgoraUserInfo}> - */ - static getUserInfoByUid(uid: number): Promise; - /** - * Gets the user information by passing in the user account. - * - * After receiving the "userInfoUpdated" callback, you can call this method to get the user ID of the remote user from the {@link AgoraUserInfo} object by passing in the userAccount. - * @param userAccount - * @returns Promise<{@link AgoraUserInfo}> - */ - static getUserInfoByUserAccount(userAccount: string): Promise; - /** - * add event listener - * - * This method subscribes specified eventType and run listener. You should call this method at first. - * - * @event listener - * - * --- - * name | description | usage | - * error | occurs when emit error | on("error", evt) | - * warning | occurs when emit warning | on("warning", evt) | - * messageReceived | occurs when message received | on("messageReceived", evt) | - * localInvitationReceivedByPeer | occurs when local inviation received by peer | on("localInvitationReceivedByPeer", evt) | - * localInvitationAccepted | occurs when local invitation accepted | on("localInvitationAccepted", evt) | - * localInvitationRefused | occurs when local invitation refused | on("localInvitationRefused", evt) | - * localInvitationCanceled | occurs when local invitation canceled | on("localInvitationCanceled", evt) | - * localInvitationFailure | occurs when local invitation failure | on("localInvitationFailure", evt) | - * remoteInvitationFailure | occurs when remote invitation failure | on("remoteInvitationFailure", evt) | - * remoteInvitationReceived | occurs when remote invitation received | on("remoteInvitationReceived", evt) | - * remoteInvitationAccepted | occurs when remote invitation accepted | on("remoteInvitationAccepted", evt) | - * remoteInvitationRefused | occurs when remote invitation refused | on("remoteInvitationRefused", evt) | - * remoteInvitationCanceled | occurs when remote invitation canceled | on("remoteInvitationCanceled", evt) | - * channelMessageReceived | occurs when received channel message | on("channelMessageReceived", evt) | - * channelMemberJoined | occurs when some one joined in the subscribed channel | on("channelMemberJoined", evt) | - * channelMemberLeft | occurs when sone one left from u subscribed channel | on("channelMemberLeft", evt) | - * tokenExpired | occurs when token has expired | on("tokenExpired", evt) | - * apiCallExecute | occurs when apiCallExecute emit, this event is api call monitor | on("apiCallExecute", evt) | - * joinChannelSuccess | occurs when joinChannel success | on("joinChannelSuccess", evt) | - * rejoinChannelSuccess | occurs when rejoinChannel success | on("rejoinChannelSuccess", evt) | - * leaveChannel | occurs when leaveChannel success | on("leaveChannel", evt) | - * clientRoleChanged | occurs when setClientRole changed | on("clientRoleChanged", evt) | - * userJoined | occurs when remote user joined | on("userJoined", evt) | - * userOffline | this event occurs when remote user offline in rtc mode, this events only occurs host user offline in live mode | on("userOffline", evt) | - * connectionStateChanged | occurs when sdk connection changed state | on("connectionStateChanged", evt) | - * connectionLost | occurs when sdk connection lost | on("connectionLost", evt) | - * tokenPrivilegeWillExpire | occurs when token will expire | on("tokenPrivilegeWillExpire", evt) | - * requestToken | occurs when token expired | on("requestToken") | - * localAudioStateChanged | occurs when local audio device state changed | on("localAudioStateChanged", (state, errorCode) => {}) | - * audioVolumeIndication | occurs when audio volume indication changed | on("audioVolumeIndication", evt) | - * activeSpeaker | occurs when detect active speaker | on("activeSpeaker", evt) | - * firstLocalAudioFrame | occurs when sent first audio frame on local | on("firstLocalAudioFrame", evt) | - * firstRemoteAudioFrame | occurs when received first audio frame from remote side | on("firstRemoteAudioFrame", evt) | - * firstRemoteAudioDecoded | occurs when first remote audio decoded | on("firstRemoteAudioDecoded", evt) | - * firstLocalVideoFrame | occurs when sent first video frame on local | on("firstLocalVideoFrame", evt) | - * firstRemoteVideoFrame | occurs when received first video frame from remote side | on("firstRemoteVideoFrame", evt) | - * userMuteAudio | occurs when user mute audio | on("userMuteAudio", evt) | - * videoSizeChanged | occurs when change local or remote side video size or rotation | on("videoSizeChanged", evt) | - * remoteVideoStateChanged | occurs when remote video state has any changed | on("remoteVideoStateChanged", evt) | - * remoteAudioStateChanged | occurs when remote audio state has any changed | on("remoteAudioStateChanged", evt) | - * localAudioStats | occurs when engine start to report local audio stats | on("localAudioStats", evt) | - * localPublishFallbackToAudioOnly | occurs when published stream from local side fallback to audio stream | on("localPublishFallbackToAudioOnly", evt) | - * remoteSubscribeFallbackToAudioOnly | occurs when subscribed side's stream fallback to audio stream | on("remoteSubscribeFallbackToAudioOnly", evt) | - * audioRouteChanged | occurs when local audio route changed | on("audioRouteChanged", evt) | - * cameraFocusAreaChanged | occurs when a camera focus area changed | on("cameraFocusAreaChanged", evt) | - * cameraExposureAreaChanged | occurs when a camera exposure area changed | on("cameraExposureAreaChanged", evt) | - * rtcStats | occurs when reports the statistics of the current call session once every two seconds. | on("rtcStats", evt) | - * lastmileQuality | occurs when reports the last mile network quality of the local user once every two seconds before the user joins a channel.| on("lastmileQuality", evt) | - * networkQuality | occurs when reports the last mile network quality of each user in the channel once every two seconds.| on("networkQuality", evt) | - * localVideoStats | occurs when reports local video statistics | on("localVideoStats", evt) | - * remoteVideoStats | occurs when reports remote video statistics| on("remoteVideoStats", evt) | - * remoteAudioStats | occurs when reports remote audio statistics| on("remoteAudioStats", evt) | - * audioEffectFinish | occurs when the local audio effect playback finishes. | on("audioEffectFinish", evt) | - * streamPublished | occurs when addPublishStreamUrl success| on("streamPublished", evt) | - * streamUnpublish | occurs when removePublishStreamUrl success| on("streamUnpublish", evt) | - * transcodingUpdate | occurs when the cdn live streaming settings are updated | on("transcodingUpdate", evt) | - * streamInjectedStatus | occurs when report the status of online injecting stream to a live broadcast | on("streamInjectedStatus", evt) | - * mediaEngineLoaded | occurs when the media engine loaded | on("mediaEngineLoaded", evt) | - * mediaEngineStartCall | occurs when the media engine call starts | on("mediaEngineStartCall", evt) | - * startEchoTestWithInterval | occurs when startEchoTestWithInterval success | on("startEchoTestWithInterval", evt) | - * audioMixingStateChanged | occurs when reports the local audio mixing state changed | on("audioMixingStateChanged", evt) | - * lastmileProbeTestResult | occurs when reports the last-mile network probe result.| on("lastmileProbeTestResult", evt) | - * rtmpStreamingStateChanged | occurs when reports the rtmp injecting stream state changed | on("rtmpStreamingStateChanged", evt) | - * localVideoChanged | occurs when the local video changed | on("localVideoChanged", evt) | - * networkTypeChanged | occurs when the device network type changed | on("networkTypeChanged", evt) | - * mediaMetaDataReceived | occurs when you received media meta data from the remote side through sendMediaData | on("mediaMetaDataReceived", evt) | - * localUserRegistered | occurs when you register user account success | on("localUserRegistered", evt) | - * userInfoUpdated | occurs when you peer side using user account join channel | on("userInfoUpdated", evt) | - * receivedChannelMediaRelay | occurs when you received channel media relay | on('receivedChannelMediaRelay", evt)| - * mediaRelayStateChanged | occurs when you received remote media relay state changed | on('mediaRelayStateChanged", evt)| - * --- - * - * @param eventType - * @param listener - * @return any - */ - static on(eventType: string, listener: (...args: any[]) => any): any; - /** - * @deprecated removeAllListeners - */ - static removeAllListeners(): void; - /** - * @deprecated off - * @param mode - */ - static off(evt: any): void; - /** - * renew token - * - * This method renews a new token. - * @param token - */ - static renewToken(token: string): any; - /** - * enable websdk interoperability - * - * This method used to enable websdk interoperability, so that it can connect with agora websdk apps. - * - * @param enabled - * @return Promise<{success, value}> - */ - static enableWebSdkInteroperability(enabled: boolean): Promise; - /** - * get agora native sdk connection state - * - * This method gets agora native sdk connection state - * @return Promise<{state: (connection state)}> - */ - static getConnectionState(): Promise; - /** - * change the client role - * - * This method changes the client of role. - * @param role (audience: 0, host: 1) - */ - static setClientRole(role: number): Promise; - /** - * leave channel - * - * This method leaves the joined channel, then your video view will not render ever. - * You should call it, when you dont need render video stream. - * - * @return Promise - */ - static leaveChannel(): Promise; - /** - * destroy - * - * This method stops event subscribe and destroy the RtcEngine instance's. - * You should call it, when you want to destroy the engine. - * - * @return void - */ - static destroy(): any; - /** - * set local video render mode - * - * This method calls native sdk render mode for local video. - * @param mode - * @return Promise - */ - static setLocalRenderMode(mode: number): Promise; - /** - * set the specified remote video render mode - * - * This method calls native sdk render mode for the specified remote video. - * - * @param uid - * @param mode - * @return Promise - */ - static setRemoteRenderMode(uid: number, mode: number): Promise; - /** - * start video preview - * - * This method start video preview for video. - * @return Promise - */ - static startPreview(): Promise; - /** - * stop video preview - * - * This method stops video preview for video. - * @return Promise - */ - static stopPreview(): Promise; - /** - * set enable speaker phone - * - * This method set the speaker phone enable or disable by pass boolean parameter. - * @param enabled - * @return Promise - */ - static setEnableSpeakerphone(enabled: boolean): Promise; - /** - * set default audio speaker - * - * This method set the default audio speaker enable or disable by pass boolean parameter. - * @param enabled - * @return Promise - */ - static setDefaultAudioRouteToSpeakerphone(enabled: boolean): Promise; - /** - * set default mute all remote audio streams - * - * This method set default mute all remote audio streams enable or not by pass boolean parameter. - * @param enabled - * @return Promise - */ - static setDefaultMuteAllRemoteAudioStreams(enabled: boolean): Promise; - /** - * enable video - * - * This method enables video. - * @return Promise - */ - static enableVideo(): Promise; - /** - * disable video - * - * This method disables video. - * @return Promise - */ - static disableVideo(): Promise; - /** - * enable local video - * - * This method enables the local video by the boolean parameter. - * @param enabled - * @return Promise - */ - static enableLocalVideo(enabled: boolean): Promise; - /** - * mute local video stream - * - * This method mutes video stream by the boolean parameter. - * @param muted - * @return Promise - */ - static muteLocalVideoStream(muted: boolean): Promise; - /** - * mute all remote video streams - * - * This method mutes all remote streams by the boolean parameter. - * @param muted - * @return Promise - */ - static muteAllRemoteVideoStreams(muted: boolean): Promise; - /** - * @ignore Uint32ToInt32 - */ - private static Uint32ToInt32; - /** - * @ignore Int32ToUint32 - */ - private static Int32ToUint32; - /** - * mute specified remote video stream. - * - * This method mutes remote video stream by the number of uid and boolean parameter. - * @param uid - * @param muted - * @return Promise - */ - static muteRemoteVideoStream(uid: number, muted: boolean): Promise; - /** - * set default mute all remote video stream - * - * This method mutes all remote video stream default by the boolean parameter. - * @param muted - * @return Promise - */ - static setDefaultMuteAllRemoteVideoStreams(muted: boolean): Promise; - /** - * enable audio - * - * This method enables audio - * @return Promise - */ - static enableAudio(): Promise; - /** - * disable audio - * - * This method disables audio - * @return Promise - */ - static disableAudio(): Promise; - /** - * enable local audio - * - * This method enables local audio by the boolean parameter. - * @param enabled - * @return Promise - */ - static enableLocalAudio(enabled: boolean): Promise; - /** - * mute local audio stream - * - * This method mutes the local audio stream by muted. - * @param muted - * @return Promise - */ - static disableLocalAudio(muted: boolean): Promise; - /** - * mute all remote audio streams - * - * This method mutes all remote audio streams by muted - * @param muted boolean - * @return Promise - */ - static muteAllRemoteAudioStreams(muted: boolean): Promise; - /** - * mute specified remote audio stream by muted - * - * This method mutes specified remote audio stream by number uid and boolean muted. - * @param uid - * @param muted - * @return Promise - */ - static muteRemoteAudioStream(uid: number, muted: boolean): Promise; - /** - * adjust recording signal volume - * - * This method adjusts recording your signal by volume. - * @param volume - * @return Promise - */ - static adjustRecordingSignalVolume(volume: number): Promise; - /** - * adjust playback signal volume - * - * This method adjusts playback signal by volume. - * @param volume - * @return Promise - */ - static adjustPlaybackSignalVolume(volume: number): Promise; - /** - * enable audio volume indication - * - * This method enables audio volume by interval and smooth - * @param interval - * @param smooth - * @param vad - * @return Promise - */ - static enableAudioVolumeIndication(interval: number, smooth: number, vad: boolean): Promise; - /** - * check for mobile phone speaker enabled - * - * This method checks the phone speaker is enabled - * @param callback - * @return any - */ - static isSpeakerphoneEnabled(callback: Callback): any; - /** - * enable in-ear monitor - * - * This method enables in-ear monitoring by boolean parameter enabled - * - * @param enabled - * @return Promise - */ - static enableInEarMonitoring(enabled: boolean): Promise; - /** - * set in-ear monitoring volume - * - * This method sets the in-ear-monitoring volume by number parameter volume - * - * @param volume - * @return Promise - */ - static setInEarMonitoringVolume(volume: number): Promise; - /** - * set local voice pitch - * - * This method sets the local voice pitch by float parameter pitch - * - * @param pitch - * @return Promise - */ - static setLocalVoicePitch(pitch: number): Promise; - /** - * set local voice equalization - * - * This method set local video equalization of band frequency by enum band number and number of gain - * - * @param band - * @param gain - * @return Promise - */ - static setLocalVoiceEqualization(band: number, gain: number): void; - /** - * set local voice reverb - * - * This method sets local voice by reverb and value - * @param reverb - * @param value - */ - static setLocalVoiceReverb(reverb: number, value: number): void; - /** - * start audio mixing - * - * This method will start audio mixing by option config - * - * @param options {@link AudioMixingOption} - */ - static startAudioMixing(options: AudioMixingOption): void; - /** - * stop audio mixing - * - * This methods stops for audio mixing. - */ - static stopAudioMixing(): void; - /** - * pause audio mixing - * - * This method pauses for audio mixing. - */ - static pauseAudioMixing(): void; - /** - * resume audio mixing - * - * This method resumes for audio mixing. - */ - static resumeAudioMixing(): void; - /** - * adjust audio mixing volume - * - * This method adjusts audio mixing volume by the volume number parameter - * @param volume - */ - static adjustAudioMixingVolume(volume: number): void; - /** - * adjust audio mixing playout volume - * - * This method adjusts audio mixing playout by the volume parameter - * @param volume - */ - static adjustAudioMixingPlayoutVolume(volume: number): void; - /** - * adjust audio mixing publish volume - * - * This method adjusts audio mixing publish by the volume paraemter - * @param volume - */ - static adjustAudioMixingPublishVolume(volume: number): void; - /** - * get audio mixing duration - * - * This method gets the audio mixing duration - * @return Promise<{success, value}> - */ - static getAudioMixingDuration(): Promise; - /** - * get audio mixing current position - * - * This method gets audio mixing current position value. - * @return Promise<{success, value}> - */ - static getAudioMixingCurrentPosition(): Promise; - /** - * set audio mixing position - * - * This method sets audio mixing position by the parameter pos - * @param pos - */ - static setAudioMixingPosition(pos: number): Promise; - /** - * get effects of volume - * - * This methods get audio mixing effects volume value. - * @return Promise<{success, value}> - */ - static getEffectsVolume(): Promise; - /** - * set effects volume - * - * This methods set audio mixing effects volume by float parameter. - * @param volume - * @return Promise<{success, value}> - */ - static setEffectsVolume(volume: number): Promise; - /** - * set volume for playing effects. - * - * This methods set for playing audio mixing effects - * @return Promise<{success, value}> - */ - static setVolumeOfEffect(volume: number): Promise; - /** - * play specified effect for audio mixing - * - * This methos plays the specified effect of audio mixing file by option config. - * @param options {@link PlayEffectOption} - * @return Promise<{success, value}> - */ - static playEffect(options: PlayEffectOption): Promise; - /** - * stop play effect for audio mixing - * - * This methods stops the specified effect for audio mixing file by soundId. - * @param sounid - * @return Promise<{success, value}> - */ - static stopEffect(soundId: number): Promise; - /** - * stop play all for effect audio mixing. - * - * This methods stops all effect audio mixing. - * @return Promise<{success, value}> - */ - static stopAllEffects(): Promise; - /** - * preload effect for audio mixing file. - * - * This methods preloads the specified audio mixing file to memory by the soundId - * @param soundId - * @param filePath - * @return Promise<{success, value}> - */ - static preloadEffect(soundId: number, filePath: string): Promise; - /** - * unload effect - * - * This methods unload the already loaded audio mixing file from memory by the soundId. - * @param soundId - * @return Promise<{success, value}> - */ - static unloadEffect(soundId: number): Promise; - /** - * pause the specified effect for audio mixing by soundId - * - * This method pauses the specified effect for audio mixing by soundId. - * @param soundId - * @return Promise<{success, value}> - */ - static pauseEffect(soundId: number): Promise; - /** - * pause all effects for audio mixing - * - * This method pause all effects for audio mixing. - * @param soundId - * @return Promise<{success, value}> - */ - static pauseAllEffects(): Promise; - /** - * resume audio mixing effect by the specified soundId - * - * This method resumes audio mixing effect by the specified soundId - * @param soundId - * @return Promise<{success, value}> - */ - static resumeEffect(soundId: number): Promise; - /** - * resume all audio mixing effects. - * - * This method resumes all audio mixing effects. - * @return Promise<{success, value}> - */ - static resumeAllEffects(): Promise; - /** - * start audio recording by quality - * - * This method start audio recording by quality config - * @param options {@link AudioRecordingOption} - * @return Promise<{success, value}> - */ - static startAudioRecording(options: AudioRecordingOption): Promise; - /** - * stop audio recording - * - * This method stops audio recording. - * @return Promise<{success, value}> - */ - static stopAudioRecording(): Promise; - /** - * set audio session operation restriction - * - * The SDK and the app can both configure the audio session by default. The app may occasionally use other apps or third-party components to manipulate the audio session and restrict the SDK from doing so. This method allows the app to restrict the SDK’s manipulation of the audio session. - * You can call this method at any time to return the control of the audio sessions to the SDK. - * This method restricts the SDK’s manipulation of the audio session. Any operation to the audio session relies solely on the app, other apps, or third-party components. - * @notice iOS support only - */ - static setAudioSessionOperationRestriction(): void; - /** - * @deprecated startEchoTest - * startEchoTest - */ - /** - * @deprecated isCameraAutoFocusFaceModeSupported - * @deprecated isCameraExposurePositionSupported - * @deprecated isCameraFocusSupported - * @deprecated isCameraTorchSupported - * @deprecated isCameraZoomSupported - * instead use {@method getCameraInfo} - */ - /** - * stop echo test - * - * This method stop launched an audio call test. - * @return Promise<{success, value}> - */ - static stopEchoTest(): Promise; - /** - * enable lastmile test - * - * This method enables the network connection qualit test. - * - * @return Promise<{success, value}> - */ - static enableLastmileTest(): Promise; - /** - * disable lastmile test - * - * This method disable the network connection qualit test. - * - * @return Promise<{success, value}> - */ - static disableLastmileTest(): Promise; - /** - * set recording audio frame parameters - * - * This method Sets the audio recording format for the audioFrame callback. - * - * @param options {@link RecordingAudioFrameOption} - * @return Promise<{success, value}> - */ - static setRecordingAudioFrameParameters(options: AudioFrameOption): Promise; - /** - * set playback audio frame parameters - * - * This method Sets the audio frame format for the playbackFrame callback. - * - * @param options {@link AudioFrameOption} - * @return Promise<{success, value}> - */ - static setPlaybackAudioFrameParameters(options: AudioFrameOption): Promise; - /** - * set mixed audio frame parameters - * - * This method Sets the audio frame format for the mixedAudioFrame callback. - * - * @param options {@link MixedAudioFrameOption} - * @return Promise<{success, value}> - */ - static setMixedAudioFrameParameters(options: MixedAudioFrameOption): Promise; - /** - * add video watermark - * - * This method adds video watermark to the local video. - * - * @param options {@link ImageOption} - * @return Promise<{success, value}> - */ - static addVideoWatermark(url: string, options: ImageOption): Promise; - /** - * clear video watermarks - * - * This method removes the watermark image from the video stream added by addVideoWatermark. - * - * @return Promise<{success, value}> - */ - static clearVideoWatermarks(): Promise; - /** - * set local publish fallback - * - * This method sets the fallback option for the locally published video stream based on the network conditions. - * - * @param option {0, 1, 2} [more details](https://docs.agora.io/en/Video/API%20Reference/java/classio_1_1agora_1_1rtc_1_1_constants.html#a3e453c93766e783a7e5eca05b1776238) - * @return Promise<{success, value}> - */ - static setLocalPublishFallbackOption(option: number): Promise; - /** - * set remote publish fallback - * - * This method sets the fallback option for the remotely subscribed video stream based on the network conditions. - * - * @param option {0, 1, 2} [more details](https://docs.agora.io/en/Video/API%20Reference/java/classio_1_1agora_1_1rtc_1_1_constants.html#a3e453c93766e783a7e5eca05b1776238) - * @return Promise<{success, value}> - */ - static setRemoteSubscribeFallbackOption(option: number): Promise; - /** - * enable dual stream mode - * - * This method enables the dual stream by parameter mode. - * - * @param enabled - * @return Promise<{success, value}> - */ - static enableDualStreamMode(enabled: boolean): Promise; - /** - * set remote video stream type - * - * This method sets the remote video stream type by uid and streamType. - * - * @param options {@link VideoStreamOption} - * @return Promise<{success, value}> - */ - static setRemoteVideoStreamType(options: VideoStreamOption): Promise; - /** - * set remote default video stream type - * - * This method sets the default video stream type. - * - * @param options {@link DefaultVideoStreamOption} - * @return Promise<{success, value}> - */ - static setRemoteDefaultVideoStreamType(options: DefaultVideoStreamOption): Promise; - /** - * add inject stream url - * - * This method injects an online media stream to a live broadcast. - * - * @param options {@link InjectStreamOption} - * @return Promise<{success, value}> - */ - static addInjectStreamUrl(options: InjectStreamOption): Promise; - /** - * remove inject stream url - * - * This method removes stream by addInjectsStreamUrl. - * - * @param options {@link RemoveInjectStreamOption} - * @return Promise<{success, value}> - */ - static removeInjectStreamUrl(options: RemoveInjectStreamOption): Promise; - /** - * @deprecated sendMessage - * sendMessage - */ - static sendMessage(): Promise; - /** - * @deprecated createDataStream - * createDataStream - */ - /** - * @deprecated setupLocalVideo - * setupLocalVideo - */ - /** - * @deprecated setupRemoteVideo - * setupRemoteVideo - */ - /** - * @deprecated setVideoQualityParameters - * setVideoQualityParameters - */ - /** - * set local video mirror mode - * - * This method sets local video mirror mode - * - * @param mode - * @return Promise<{success, value}> - */ - static setLocalVideoMirrorMode(mode: number): Promise; - /** - * switch camera - * - * This method switches camera between front and rear. - * - * @return Promise<{success, value}> - */ - static switchCamera(): Promise; - /** - * set camera zoom ratio - * - * This method sets the camera zoom ratio. - * - * @param zoomFactor - * @return Promise<{success, value}> - */ - static setCameraZoomFactor(zoomFactor: number): Promise; - /** - * get camera max zoom ratio - * - * This method gets the camera maximum zoom ratio. - * - * @notice Android Only - * @return Promise<{success, value}> - */ - static getCameraMaxZoomFactor(): Promise; - /** - * set camera focus position in preview - * - * This method sets the mannual focus position. - * - * @param options {@link PositionOption} - * @return Promise<{success, value}> - */ - static setCameraFocusPositionInPreview(options: PositionOption): Promise; - /** - * set camera exposure position - * - * This method sets the mannual exposure position. - * - * @param options {@link PositionOption} - * @return Promise<{success, value}> - */ - static setCameraExposurePosition(options: PositionOption): Promise; - /** - * set camera torch on - * - * This method enables the camera flash function. - * - * @param enabled - * @return Promise<{success, value}> - */ - static setCameraTorchOn(enabled: boolean): Promise; - /** - * set enable auto focus face mode - * - * This method enables auto-focus face mode function. - * - * @param enabled boolean - * @return Promise<{success, value}> - */ - static setCameraAutoFocusFaceModeEnabled(enabled: boolean): Promise; - /** - * get call id - * - * This method is used to get call id. - * - * @return Promise<{success, value}> - */ - static getCallId(): Promise; - /** - * set log file and log filter - * - * This method sets the log file generated path and specified the log level. - * - * @param filePath string - * @param level enum - * @param maxfileSize integer (KB) - * @return Promise<{success, value}> - */ - static setLog(filePath: string, level: number, maxfileSize: number): Promise; - /** - * add publish stream url - * - * This method add publish stream by option. - * - * @param options {@link PublishStreamOption} - * @return Promise<{success, value}> - */ - static addPublishStreamUrl(options: PublishStreamOption): Promise; - /** - * remove publish stream url - * - * This method remove publish stream by options. - * - * @param options {@link RemovePublishStreamOption} - * @return Promise<{success, value}> - */ - static removePublishStreamUrl(options: RemovePublishStreamOption): Promise; - /** - * set live transcoding - * - * This method sets the video layout and audio settings for CDN live. - * - * @param options {@link LiveTranscoding} - * @return Promise<{success, value}> - */ - static setLiveTranscoding(options: LiveTranscodingOption): Promise; - /** - * get sdk version - * - * This method gets the sdk version details and passed it into callback function - * - * @param callback to handle resolve from getSdkVersion - * @param errorHandler to handle reject error from getSdkVersion - * @return any - */ - static getSdkVersion(callback: Callback, errorHandler?: Callback): any; - /** - * mute local audio stream - * - * This method sends/stops sending the local audio. - * - * @param enabled - * @return Promise - */ - static muteLocalAudioStream(enabled: boolean): Promise; - /** - * video pre-process/post-process - * - * This method enables/disables image enhancement and sets the options. - * - * @param enabled boolean - * @param options {@link BeautyOptions} - * @return Promise - */ - static setBeautyEffectOptions(enabled: boolean, options: BeautyOption): Promise; - /** - * set local voice change - * - * This method changes local speaker voice with voiceChanger - * - * @param voiceChanger integer - * @voiceChanger value ranges [ - * 0: "The original voice", - * 1: "An old man’s voice", - * 2: "A little boy’s voice.", - * 3: "A little girl’s voice.", - * 4: "TBD", - * 5: "Ethereal vocal effects.", - * 6: "Hulk’s voice." - * ] - * @return Promise - */ - static setLocalVoiceChanger(voiceChanger: number): Promise; - /** - * set the preset local voice reverberation effect. - * - * This method sets the preset local voice reverberation effect. - * - * @param preset integer - * @return Promise - */ - static setLocalVoiceReverbPreset(preset: number): Promise; - /** - * control stereo panning for remote users - * - * This method enables/disables stereo panning for remote users. - * - * @param enabled boolean - * @return Promise - */ - static enableSoundPositionIndication(enabled: boolean): Promise; - /** - * set the sound position of a remote user - * - * This method sets the sound position of a remote user by uid - * - * @param uid number | The ID of the remote user - * @param pan float | The sound position of the remote user. The value ranges from -1.0 to 1.0 - * @pan - * 0.0: the remote sound comes from the front. - * -1.0: the remote sound comes from the left. - * 1.0: the remote sound comes from the right. - * @param gain float | Gain of the remote user. The value ranges from 0.0 to 100.0. The default value is 100.0 (the original gain of the remote user). The smaller the value, the less the gain. - * @return Promise - */ - static setRemoteVoicePosition(uid: number, pan: number, gain: number): Promise; - /** - * start the lastmile probe test - * - * This method start the last-mile network probe test before joining a channel to get the uplink and downlink last-mile network statistics, including the bandwidth, packet loss, jitter, and round-trip time (RTT). - * - * @param config LastmileProbeConfig {@link LastmileProbeConfig} - * - * event onLastmileQuality: the SDK triggers this callback within two seconds depending on the network conditions. This callback rates the network conditions with a score and is more closely linked to the user experience. - * event onLastmileProbeResult: the SDK triggers this callback within 30 seconds depending on the network conditions. This callback returns the real-time statistics of the network conditions and is more objective. - * @return Promise - */ - static startLastmileProbeTest(config: LastmileProbeConfig): Promise; - /** - * stop the lastmile probe test - * - * This method stop the lastmile probe test. - * - * @return Promise - */ - static stopLastmileProbeTest(): Promise; - /** - * sets the priority of a remote user's media stream. - * - * note: Use this method with the setRemoteSubscribeFallbackOption method. If the fallback function is enabled for a subscribed stream, the SDK ensures the high-priority user gets the best possible stream quality. - * - * This method sets the priority of a remote user's media stream. - * @param uid number - * @param userPriority number | The value range is [50 is "user's priority is high", 100 is "the default user's priority is normal"] - * - * @return Promise - */ - static setRemoteUserPriority(uid: number, userPriority: number): Promise; - /** - * start an audio call test. - * - * note: - * Call this method before joining a channel. - * After calling this method, call the stopEchoTest method to end the test. Otherwise, the app cannot run the next echo test, or call the joinChannel method. - * In the Live-broadcast profile, only a host can call this method. - * This method will start an audio call test with interval parameter. - * In the audio call test, you record your voice. If the recording plays back within the set time interval, the audio devices and the network connection are working properly. - * - * @param interval number - * - * @return Promise - */ - static startEchoTestWithInterval(interval: number): Promise; - /** - * set the camera capture preference. - * - * note: - * For a video call or live broadcast, generally the SDK controls the camera output parameters. When the default camera capture settings do not meet special requirements or cause performance problems, we recommend using this method to set the camera capture preference: - * If the resolution or frame rate of the captured raw video data are higher than those set by setVideoEncoderConfiguration, processing video frames requires extra CPU and RAM usage and degrades performance. We recommend setting config as CAPTURER_OUTPUT_PREFERENCE_PERFORMANCE(1) to avoid such problems. - * If you do not need local video preview or are willing to sacrifice preview quality, we recommend setting config as CAPTURER_OUTPUT_PREFERENCE_PERFORMANCE(1) to optimize CPU and RAM usage. - * If you want better quality for the local video preview, we recommend setting config as CAPTURER_OUTPUT_PREFERENCE_PREVIEW(2). - * - * This method will set the camera capture preference. - * - * @param config {@link CameraCapturerConfiguration} - * - * @return Promise - */ - static setCameraCapturerConfiguration(config: CameraCapturerConfiguration): Promise; - /** - * Gets the audio mixing volume for local playback. - * - * note: - * This method helps troubleshoot audio volume related issues. - * - * @return Promise - */ - static getAudioMixingPlayoutVolume(): Promise; - /** - * Gets the audio mixing volume for publishing. - * - * note: - * This method helps troubleshoot audio volume related issues. - * - * @return Promise - */ - static getAudioMixingPublishVolume(): Promise; - /** - * sendMediaData for media observer. - * - * note: - * This method needs you invoke registerMediaMetadataObserver success first and you could send media data through interval media observer feature. - * The data have limit length is 1024 bytes, if you pass data length bigger than limit it will failed. - * @param data String: 1024 bytes limit - * @return Promise - */ - static sendMediaData(data: String): Promise; - /** - * Registers the metadata observer. - * - * note: - * This method only work in live mode - * This method enables you to add synchronized metadata in the video stream for more diversified live broadcast interactions, such as sending shopping links, digital coupons, and online quizzes. - * This method trigger 'mediaMetaDataReceived' event, here is example: - * ```javascript - * RtcEngine.on("mediaMetaDataReceived", (data) => { - * console.log("mediaMetaDataReceived", data); - * }) - * ``` - * @return Promise - */ - static registerMediaMetadataObserver(): Promise; - /** - * Get local device camera support info - * - * note: - * This method returns your current device camera support info. - * ```javascript - * RtcEngine.getCameraInfo().then(info => { - * console.log("your currrent camera", info); - * }) - * ``` - * @return Promise<{cameraSupportInfo}> - */ - static getCameraInfo(): Promise; - /** - * Set Private Parameters - * @param paramsStr - * @return Promise - */ - static setParameters(paramsStr: string): Promise; - /** - * Get Private Parameter - * @param paramsStr - * @param args - * @return Promise - */ - static getParameter(paramsStr: string, args: string): Promise; - /** - * Get Private Parameters - * @param paramsStr - * @param args - * @return Promise - */ - static getParameters(paramsStr: string): Promise; -} -export default RtcEngine; diff --git a/lib/RtcEngine.native.js b/lib/RtcEngine.native.js deleted file mode 100644 index b7aa9efea..000000000 --- a/lib/RtcEngine.native.js +++ /dev/null @@ -1,1572 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const tslib_1 = require("tslib"); -const react_native_1 = require("react-native"); -const { Agora } = react_native_1.NativeModules; -const AgoraEventEmitter = new react_native_1.NativeEventEmitter(Agora); -/** - * RtcEngine is the javascript object for control agora native sdk through react native bridge. - * - * You can use the RtcEngine methods to create {@link init} - * - * Other methods of the RtcEngine object serve for agora native sdk and set up error logging. - */ -let RtcEngine = /** @class */ (() => { - class RtcEngine { - /** - * Creates a RtcEngine Object internal. - * - * This method creates and start event observer. You should call this method once. - * @example `RtcEngine.init(option)` - * @param options Defines the property of the client, see {@link Option} for details. - * @returns any - */ - static init(options) { - Agora.init(options); - } - /** - * join specified channel - * - * This method joins and begin rendering the video stream. when join succeeds. - * Otherwise, it will invoke error by the event - * @param channelName - * @param uid - * @param token - * @param info - * @returns Promise - */ - static joinChannel(channelName, uid, token, info) { - return Agora.joinChannel({ channelName, uid, token, info }); - } - /** - * switch to specified channel - * - * This method will switch channel smoothly than you invoke leaveChannel & joinChannel. - * Otherwise, it will invoke error by the event - * It will occurs two events: - * Occurs leaveChannel when achieve leaving stage - * Occurs joinChannelSuccess when achieve joining stage - * @param channelName {@link string} - * @param token {@link string} - * @returns Promise - */ - static switchChannel(channelName, token) { - return Agora.switchChannel({ channelName, token }); - } - /** - * Starts to relay media streams across channels. - * - * This method will start relay media stream across specified channels. (maximum support 4 channels) - * It will occurs event: - * Occurs mediaRelayStateChanged - * Occurs receivedChannelMediaRelay when peer channel received this message - * @param config {@link ChannelMediaConfiguration} - * @returns Promise - */ - static startChannelMediaRelay(config) { - return Agora.startChannelMediaRelay(config); - } - /** - * Remove to relay media streams across channels. - * - * This method will remove & update relay media stream across specified channels. (maximum support relay 4 channels) - * It will occurs event: - * Occurs mediaRelayStateChanged - * @param config {@link ChannelMediaConfiguration} - * @returns Promise - */ - static removeChannelMediaRelay(config) { - return Agora.removeChannelMediaRelay(config); - } - /** - * Updates to relay media streams across channels. - * - * This method will update relay media stream across specified channels. (maximum support 4 channels) - * It will occurs event: - * Occurs mediaRelayStateChanged - * @param config {@link ChannelMediaConfiguration} - * @returns Promise - */ - static updateChannelMediaRelay(config) { - return Agora.updateChannelMediaRelay(config); - } - /** - * Stop to relay media streams across channels. - * - * This method will stop relay media stream across specified channels. - * It will occurs event: - * Occurs mediaRelayStateChanged - * @param config {@link ChannelMediaConfiguration} - * @returns Promise - */ - static stopChannelMediaRelay() { - return Agora.stopChannelMediaRelay(); - } - /** - * Registers a user account. - * - * Once registered, the user account can be used to identify the local user when the user joins the channel. After the user successfully registers a user account, the SDK triggers the `on("localUserRegistered", callback)` on the local client, reporting the user ID and user account of the local user. - * To join a channel with a user account, you can choose either of the following: - * Call the {@link registerLocalUserAccount} method to create a user account, and then the {@link joinChannelWithUserAccount} method to join the channel. - * Call the {@link joinChannelWithUserAccount} method to join the channel. - * - * @note To ensure smooth communication, use the same parameter type to identify the user. For example, if a user joins the channel with a user ID, then ensure all the other users use the user ID too. The same applies to the user account. If a user joins the channel with the Agora Web SDK, ensure that the uid of the user is set to the same parameter type. - * - * @param userAccount - * @returns Promise - */ - static registerLocalUserAccount(userAccount) { - return Agora.registerLocalUserAccount({ userAccount }); - } - /** - * Joins the channel with a user account. - * - * After the user successfully joins the channel, the SDK triggers the following callbacks: - * - * The local client: `on("localUserRegistered", callback)` and `on("joinChannelSuccess", callback)`. - * The remote client: `on("userJoined", callback)` and `on("userInfoUpdated", callback)`, if the user joining the channel is in the Communication profile, or is a BROADCASTER in the Live Broadcast profile. - * - * @note To ensure smooth communication, use the same parameter type to identify the user. For example, if a user joins the channel with a user ID, then ensure all the other users use the user ID too. The same applies to the user account. If a user joins the channel with the Agora Web SDK, ensure that the uid of the user is set to the same parameter type. - * - * @param channelName - * @param userAccount - * @param token - * @returns Promise - */ - static joinChannelWithUserAccount(channelName, userAccount, token) { - return Agora.joinChannelWithUserAccount({ channelName, userAccount, token }); - } - /** - * Gets the user information by passing in the user account. - * - * After receiving the "userInfoUpdated" callback, you can call this method to get the user ID of the remote user from the {@link AgoraUserInfo} object by passing in the userAccount. - * @param uid - * @returns Promise<{@link AgoraUserInfo}> - */ - static getUserInfoByUid(uid) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - if (react_native_1.Platform.OS === 'android') { - const _uid = this.Uint32ToInt32(uid); - let result = yield Agora.getUserInfoByUid(_uid); - result.uid = this.Int32ToUint32(result.uid); - return result; - } - return Agora.getUserInfoByUid(uid); - }); - } - /** - * Gets the user information by passing in the user account. - * - * After receiving the "userInfoUpdated" callback, you can call this method to get the user ID of the remote user from the {@link AgoraUserInfo} object by passing in the userAccount. - * @param userAccount - * @returns Promise<{@link AgoraUserInfo}> - */ - static getUserInfoByUserAccount(userAccount) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - if (react_native_1.Platform.OS === 'android') { - let result = yield Agora.getUserInfoByUserAccount(userAccount); - result.uid = this.Int32ToUint32(result.uid); - return result; - } - return Agora.getUserInfoByUserAccount(userAccount); - }); - } - /** - * add event listener - * - * This method subscribes specified eventType and run listener. You should call this method at first. - * - * @event listener - * - * --- - * name | description | usage | - * error | occurs when emit error | on("error", evt) | - * warning | occurs when emit warning | on("warning", evt) | - * messageReceived | occurs when message received | on("messageReceived", evt) | - * localInvitationReceivedByPeer | occurs when local inviation received by peer | on("localInvitationReceivedByPeer", evt) | - * localInvitationAccepted | occurs when local invitation accepted | on("localInvitationAccepted", evt) | - * localInvitationRefused | occurs when local invitation refused | on("localInvitationRefused", evt) | - * localInvitationCanceled | occurs when local invitation canceled | on("localInvitationCanceled", evt) | - * localInvitationFailure | occurs when local invitation failure | on("localInvitationFailure", evt) | - * remoteInvitationFailure | occurs when remote invitation failure | on("remoteInvitationFailure", evt) | - * remoteInvitationReceived | occurs when remote invitation received | on("remoteInvitationReceived", evt) | - * remoteInvitationAccepted | occurs when remote invitation accepted | on("remoteInvitationAccepted", evt) | - * remoteInvitationRefused | occurs when remote invitation refused | on("remoteInvitationRefused", evt) | - * remoteInvitationCanceled | occurs when remote invitation canceled | on("remoteInvitationCanceled", evt) | - * channelMessageReceived | occurs when received channel message | on("channelMessageReceived", evt) | - * channelMemberJoined | occurs when some one joined in the subscribed channel | on("channelMemberJoined", evt) | - * channelMemberLeft | occurs when sone one left from u subscribed channel | on("channelMemberLeft", evt) | - * tokenExpired | occurs when token has expired | on("tokenExpired", evt) | - * apiCallExecute | occurs when apiCallExecute emit, this event is api call monitor | on("apiCallExecute", evt) | - * joinChannelSuccess | occurs when joinChannel success | on("joinChannelSuccess", evt) | - * rejoinChannelSuccess | occurs when rejoinChannel success | on("rejoinChannelSuccess", evt) | - * leaveChannel | occurs when leaveChannel success | on("leaveChannel", evt) | - * clientRoleChanged | occurs when setClientRole changed | on("clientRoleChanged", evt) | - * userJoined | occurs when remote user joined | on("userJoined", evt) | - * userOffline | this event occurs when remote user offline in rtc mode, this events only occurs host user offline in live mode | on("userOffline", evt) | - * connectionStateChanged | occurs when sdk connection changed state | on("connectionStateChanged", evt) | - * connectionLost | occurs when sdk connection lost | on("connectionLost", evt) | - * tokenPrivilegeWillExpire | occurs when token will expire | on("tokenPrivilegeWillExpire", evt) | - * requestToken | occurs when token expired | on("requestToken") | - * localAudioStateChanged | occurs when local audio device state changed | on("localAudioStateChanged", (state, errorCode) => {}) | - * audioVolumeIndication | occurs when audio volume indication changed | on("audioVolumeIndication", evt) | - * activeSpeaker | occurs when detect active speaker | on("activeSpeaker", evt) | - * firstLocalAudioFrame | occurs when sent first audio frame on local | on("firstLocalAudioFrame", evt) | - * firstRemoteAudioFrame | occurs when received first audio frame from remote side | on("firstRemoteAudioFrame", evt) | - * firstRemoteAudioDecoded | occurs when first remote audio decoded | on("firstRemoteAudioDecoded", evt) | - * firstLocalVideoFrame | occurs when sent first video frame on local | on("firstLocalVideoFrame", evt) | - * firstRemoteVideoFrame | occurs when received first video frame from remote side | on("firstRemoteVideoFrame", evt) | - * userMuteAudio | occurs when user mute audio | on("userMuteAudio", evt) | - * videoSizeChanged | occurs when change local or remote side video size or rotation | on("videoSizeChanged", evt) | - * remoteVideoStateChanged | occurs when remote video state has any changed | on("remoteVideoStateChanged", evt) | - * remoteAudioStateChanged | occurs when remote audio state has any changed | on("remoteAudioStateChanged", evt) | - * localAudioStats | occurs when engine start to report local audio stats | on("localAudioStats", evt) | - * localPublishFallbackToAudioOnly | occurs when published stream from local side fallback to audio stream | on("localPublishFallbackToAudioOnly", evt) | - * remoteSubscribeFallbackToAudioOnly | occurs when subscribed side's stream fallback to audio stream | on("remoteSubscribeFallbackToAudioOnly", evt) | - * audioRouteChanged | occurs when local audio route changed | on("audioRouteChanged", evt) | - * cameraFocusAreaChanged | occurs when a camera focus area changed | on("cameraFocusAreaChanged", evt) | - * cameraExposureAreaChanged | occurs when a camera exposure area changed | on("cameraExposureAreaChanged", evt) | - * rtcStats | occurs when reports the statistics of the current call session once every two seconds. | on("rtcStats", evt) | - * lastmileQuality | occurs when reports the last mile network quality of the local user once every two seconds before the user joins a channel.| on("lastmileQuality", evt) | - * networkQuality | occurs when reports the last mile network quality of each user in the channel once every two seconds.| on("networkQuality", evt) | - * localVideoStats | occurs when reports local video statistics | on("localVideoStats", evt) | - * remoteVideoStats | occurs when reports remote video statistics| on("remoteVideoStats", evt) | - * remoteAudioStats | occurs when reports remote audio statistics| on("remoteAudioStats", evt) | - * audioEffectFinish | occurs when the local audio effect playback finishes. | on("audioEffectFinish", evt) | - * streamPublished | occurs when addPublishStreamUrl success| on("streamPublished", evt) | - * streamUnpublish | occurs when removePublishStreamUrl success| on("streamUnpublish", evt) | - * transcodingUpdate | occurs when the cdn live streaming settings are updated | on("transcodingUpdate", evt) | - * streamInjectedStatus | occurs when report the status of online injecting stream to a live broadcast | on("streamInjectedStatus", evt) | - * mediaEngineLoaded | occurs when the media engine loaded | on("mediaEngineLoaded", evt) | - * mediaEngineStartCall | occurs when the media engine call starts | on("mediaEngineStartCall", evt) | - * startEchoTestWithInterval | occurs when startEchoTestWithInterval success | on("startEchoTestWithInterval", evt) | - * audioMixingStateChanged | occurs when reports the local audio mixing state changed | on("audioMixingStateChanged", evt) | - * lastmileProbeTestResult | occurs when reports the last-mile network probe result.| on("lastmileProbeTestResult", evt) | - * rtmpStreamingStateChanged | occurs when reports the rtmp injecting stream state changed | on("rtmpStreamingStateChanged", evt) | - * localVideoChanged | occurs when the local video changed | on("localVideoChanged", evt) | - * networkTypeChanged | occurs when the device network type changed | on("networkTypeChanged", evt) | - * mediaMetaDataReceived | occurs when you received media meta data from the remote side through sendMediaData | on("mediaMetaDataReceived", evt) | - * localUserRegistered | occurs when you register user account success | on("localUserRegistered", evt) | - * userInfoUpdated | occurs when you peer side using user account join channel | on("userInfoUpdated", evt) | - * receivedChannelMediaRelay | occurs when you received channel media relay | on('receivedChannelMediaRelay", evt)| - * mediaRelayStateChanged | occurs when you received remote media relay state changed | on('mediaRelayStateChanged", evt)| - * --- - * - * @param eventType - * @param listener - * @return any - */ - static on(eventType, listener) { - this._eventTypes.add(`${RtcEngine.AG_PREFIX}${eventType}`); - // convert int32 to uint32 - if ([ - 'joinChannelSuccess', - 'rejoinChannelSuccess', - 'userJoined', - 'userOffline', - 'occurStreamMessageError', - 'receiveStreamMessage', - 'activeSpeaker', - 'firstRemoteAudioFrame', - 'firstRemoteVideoFrame', - 'userMuteAudio', - 'videoSizeChanged', - 'remoteVideoStateChanged', - 'remoteAudioStateChanged', - 'remoteSubscribeFallbackToAudioOnly', - 'networkQuality', - 'streamInjectedStatus', - 'localUserRegistered' - ].indexOf(eventType) != -1) { - AgoraEventEmitter.addListener(`${RtcEngine.AG_PREFIX}${eventType}`, (args) => { - args.uid = this.Int32ToUint32(args.uid); - // convert int32 streamId to uint32 - if (args.streamId) { - args.streamId = this.Int32ToUint32(args.streamId); - } - listener(args); - }); - return; - } - if (['userInfoUpdated'].indexOf(eventType) != -1) { - AgoraEventEmitter.addListener(`${RtcEngine.AG_PREFIX}${eventType}`, (args) => { - args.uid = this.Int32ToUint32(args.uid); - args.peer.uid = this.Int32ToUint32(args.peer.uid); - listener(args); - }); - return; - } - if (['audioVolumeIndication'].indexOf(eventType) != -1) { - AgoraEventEmitter.addListener(`${RtcEngine.AG_PREFIX}${eventType}`, (args) => { - args.speakers.map((speaker) => { - const uid = this.Int32ToUint32(speaker.uid); - return Object.assign(Object.assign({}, speaker), { uid }); - }); - listener(args); - }); - return; - } - if ([ - 'remoteAudioStats', - 'remoteVideoStats', - ].indexOf(eventType) != -1) { - AgoraEventEmitter.addListener(`${RtcEngine.AG_PREFIX}${eventType}`, (args) => { - args.stats.uid = this.Int32ToUint32(args.stats.uid); - listener(args); - }); - return; - } - AgoraEventEmitter.addListener(`${RtcEngine.AG_PREFIX}${eventType}`, listener); - } - /** - * @deprecated removeAllListeners - */ - static removeAllListeners() { - console.warn("removeAllListeners method already deprecated"); - } - /** - * @deprecated off - * @param mode - */ - static off(evt) { - console.warn("off method already deprecated"); - } - /** - * renew token - * - * This method renews a new token. - * @param token - */ - static renewToken(token) { - return Agora.renewToken(token); - } - /** - * enable websdk interoperability - * - * This method used to enable websdk interoperability, so that it can connect with agora websdk apps. - * - * @param enabled - * @return Promise<{success, value}> - */ - static enableWebSdkInteroperability(enabled) { - return Agora.enableWebSdkInteroperability(enabled); - } - /** - * get agora native sdk connection state - * - * This method gets agora native sdk connection state - * @return Promise<{state: (connection state)}> - */ - static getConnectionState() { - return Agora.getConnectionState(); - } - /** - * change the client role - * - * This method changes the client of role. - * @param role (audience: 0, host: 1) - */ - static setClientRole(role) { - return Agora.setClientRole(role); - } - /** - * leave channel - * - * This method leaves the joined channel, then your video view will not render ever. - * You should call it, when you dont need render video stream. - * - * @return Promise - */ - static leaveChannel() { - return Agora.leaveChannel(); - } - /** - * destroy - * - * This method stops event subscribe and destroy the RtcEngine instance's. - * You should call it, when you want to destroy the engine. - * - * @return void - */ - static destroy() { - if (this._eventTypes.size) { - for (let eventType of this._eventTypes) { - AgoraEventEmitter.removeAllListeners(eventType); - } - this._eventTypes.clear(); - } - return Agora.destroy(); - } - /** - * set local video render mode - * - * This method calls native sdk render mode for local video. - * @param mode - * @return Promise - */ - static setLocalRenderMode(mode) { - return Agora.setLocalRenderMode(mode); - } - /** - * set the specified remote video render mode - * - * This method calls native sdk render mode for the specified remote video. - * - * @param uid - * @param mode - * @return Promise - */ - static setRemoteRenderMode(uid, mode) { - let uint32 = react_native_1.Platform.OS === 'android' ? this.Uint32ToInt32(uid) : uid; - return Agora.setRemoteRenderMode(uint32, mode); - } - /** - * start video preview - * - * This method start video preview for video. - * @return Promise - */ - static startPreview() { - return Agora.startPreview(); - } - /** - * stop video preview - * - * This method stops video preview for video. - * @return Promise - */ - static stopPreview() { - return Agora.stopPreview(); - } - /** - * set enable speaker phone - * - * This method set the speaker phone enable or disable by pass boolean parameter. - * @param enabled - * @return Promise - */ - static setEnableSpeakerphone(enabled) { - return Agora.setEnableSpeakerphone(enabled); - } - /** - * set default audio speaker - * - * This method set the default audio speaker enable or disable by pass boolean parameter. - * @param enabled - * @return Promise - */ - static setDefaultAudioRouteToSpeakerphone(enabled) { - return Agora.setDefaultAudioRouteToSpeakerphone(enabled); - } - /** - * set default mute all remote audio streams - * - * This method set default mute all remote audio streams enable or not by pass boolean parameter. - * @param enabled - * @return Promise - */ - static setDefaultMuteAllRemoteAudioStreams(enabled) { - return Agora.setDefaultMuteAllRemoteAudioStreams(enabled); - } - /** - * enable video - * - * This method enables video. - * @return Promise - */ - static enableVideo() { - return Agora.enableVideo(); - } - /** - * disable video - * - * This method disables video. - * @return Promise - */ - static disableVideo() { - return Agora.disableVideo(); - } - /** - * enable local video - * - * This method enables the local video by the boolean parameter. - * @param enabled - * @return Promise - */ - static enableLocalVideo(enabled) { - return Agora.enableLocalVideo(enabled); - } - /** - * mute local video stream - * - * This method mutes video stream by the boolean parameter. - * @param muted - * @return Promise - */ - static muteLocalVideoStream(muted) { - return Agora.muteLocalVideoStream(muted); - } - /** - * mute all remote video streams - * - * This method mutes all remote streams by the boolean parameter. - * @param muted - * @return Promise - */ - static muteAllRemoteVideoStreams(muted) { - return Agora.muteAllRemoteVideoStreams(muted); - } - /** - * @ignore Uint32ToInt32 - */ - static Uint32ToInt32(num) { - const int32 = new Int32Array(1); - int32[0] = num; - return int32[0]; - } - /** - * @ignore Int32ToUint32 - */ - static Int32ToUint32(num) { - const uint32 = new Uint32Array(1); - uint32[0] = num; - return uint32[0]; - } - /** - * mute specified remote video stream. - * - * This method mutes remote video stream by the number of uid and boolean parameter. - * @param uid - * @param muted - * @return Promise - */ - static muteRemoteVideoStream(uid, muted) { - let uint32 = react_native_1.Platform.OS === 'android' ? this.Uint32ToInt32(uid) : uid; - return Agora.muteRemoteVideoStream(uint32, muted); - } - /** - * set default mute all remote video stream - * - * This method mutes all remote video stream default by the boolean parameter. - * @param muted - * @return Promise - */ - static setDefaultMuteAllRemoteVideoStreams(muted) { - return Agora.setDefaultMuteAllRemoteVideoStreams(muted); - } - /** - * enable audio - * - * This method enables audio - * @return Promise - */ - static enableAudio() { - return Agora.enableAudio(); - } - /** - * disable audio - * - * This method disables audio - * @return Promise - */ - static disableAudio() { - return Agora.disableAudio(); - } - /** - * enable local audio - * - * This method enables local audio by the boolean parameter. - * @param enabled - * @return Promise - */ - static enableLocalAudio(enabled) { - return Agora.enableLocalAudio(enabled); - } - /** - * mute local audio stream - * - * This method mutes the local audio stream by muted. - * @param muted - * @return Promise - */ - static disableLocalAudio(muted) { - return Agora.disableLocalAudio(muted); - } - /** - * mute all remote audio streams - * - * This method mutes all remote audio streams by muted - * @param muted boolean - * @return Promise - */ - static muteAllRemoteAudioStreams(muted) { - return Agora.muteAllRemoteAudioStreams(muted); - } - /** - * mute specified remote audio stream by muted - * - * This method mutes specified remote audio stream by number uid and boolean muted. - * @param uid - * @param muted - * @return Promise - */ - static muteRemoteAudioStream(uid, muted) { - let uint32 = react_native_1.Platform.OS === 'android' ? this.Uint32ToInt32(uid) : uid; - return Agora.muteRemoteAudioStream(uint32, muted); - } - /** - * adjust recording signal volume - * - * This method adjusts recording your signal by volume. - * @param volume - * @return Promise - */ - static adjustRecordingSignalVolume(volume) { - return Agora.adjustRecordingSignalVolume(volume); - } - /** - * adjust playback signal volume - * - * This method adjusts playback signal by volume. - * @param volume - * @return Promise - */ - static adjustPlaybackSignalVolume(volume) { - return Agora.adjustPlaybackSignalVolume(volume); - } - /** - * enable audio volume indication - * - * This method enables audio volume by interval and smooth - * @param interval - * @param smooth - * @param vad - * @return Promise - */ - static enableAudioVolumeIndication(interval, smooth, vad) { - return Agora.enableAudioVolumeIndication(interval, smooth, vad); - } - /** - * check for mobile phone speaker enabled - * - * This method checks the phone speaker is enabled - * @param callback - * @return any - */ - static isSpeakerphoneEnabled(callback) { - return Agora.isSpeakerphoneEnabled(callback); - } - /** - * enable in-ear monitor - * - * This method enables in-ear monitoring by boolean parameter enabled - * - * @param enabled - * @return Promise - */ - static enableInEarMonitoring(enabled) { - return Agora.enableInEarMonitoring(enabled); - } - /** - * set in-ear monitoring volume - * - * This method sets the in-ear-monitoring volume by number parameter volume - * - * @param volume - * @return Promise - */ - static setInEarMonitoringVolume(volume) { - return Agora.setInEarMonitoringVolume(volume); - } - /** - * set local voice pitch - * - * This method sets the local voice pitch by float parameter pitch - * - * @param pitch - * @return Promise - */ - static setLocalVoicePitch(pitch) { - return Agora.setLocalVoicePitch(pitch); - } - /** - * set local voice equalization - * - * This method set local video equalization of band frequency by enum band number and number of gain - * - * @param band - * @param gain - * @return Promise - */ - static setLocalVoiceEqualization(band, gain) { - Agora.setLocalVoiceEqualization(band, gain); - } - /** - * set local voice reverb - * - * This method sets local voice by reverb and value - * @param reverb - * @param value - */ - static setLocalVoiceReverb(reverb, value) { - Agora.setLocalVoiceReverb(reverb, value); - } - /** - * start audio mixing - * - * This method will start audio mixing by option config - * - * @param options {@link AudioMixingOption} - */ - static startAudioMixing(options) { - Agora.startAudioMixing(options); - } - /** - * stop audio mixing - * - * This methods stops for audio mixing. - */ - static stopAudioMixing() { - Agora.stopAudioMixing(); - } - /** - * pause audio mixing - * - * This method pauses for audio mixing. - */ - static pauseAudioMixing() { - Agora.pauseAudioMixing(); - } - /** - * resume audio mixing - * - * This method resumes for audio mixing. - */ - static resumeAudioMixing() { - Agora.resumeAudioMixing(); - } - /** - * adjust audio mixing volume - * - * This method adjusts audio mixing volume by the volume number parameter - * @param volume - */ - static adjustAudioMixingVolume(volume) { - Agora.adjustAudioMixingVolume(volume); - } - /** - * adjust audio mixing playout volume - * - * This method adjusts audio mixing playout by the volume parameter - * @param volume - */ - static adjustAudioMixingPlayoutVolume(volume) { - Agora.adjustAudioMixingPlayoutVolume(volume); - } - /** - * adjust audio mixing publish volume - * - * This method adjusts audio mixing publish by the volume paraemter - * @param volume - */ - static adjustAudioMixingPublishVolume(volume) { - Agora.adjustAudioMixingPublishVolume(volume); - } - /** - * get audio mixing duration - * - * This method gets the audio mixing duration - * @return Promise<{success, value}> - */ - static getAudioMixingDuration() { - return Agora.getAudioMixingDuration(); - } - /** - * get audio mixing current position - * - * This method gets audio mixing current position value. - * @return Promise<{success, value}> - */ - static getAudioMixingCurrentPosition() { - return Agora.getAudioMixingCurrentPosition(); - } - /** - * set audio mixing position - * - * This method sets audio mixing position by the parameter pos - * @param pos - */ - static setAudioMixingPosition(pos) { - return Agora.setAudioMixingPosition(pos); - } - /** - * get effects of volume - * - * This methods get audio mixing effects volume value. - * @return Promise<{success, value}> - */ - static getEffectsVolume() { - return Agora.getEffectsVolume(); - } - /** - * set effects volume - * - * This methods set audio mixing effects volume by float parameter. - * @param volume - * @return Promise<{success, value}> - */ - static setEffectsVolume(volume) { - return Agora.setEffectsVolume(volume); - } - /** - * set volume for playing effects. - * - * This methods set for playing audio mixing effects - * @return Promise<{success, value}> - */ - static setVolumeOfEffect(volume) { - return Agora.setVolumeOfEffect(volume); - } - /** - * play specified effect for audio mixing - * - * This methos plays the specified effect of audio mixing file by option config. - * @param options {@link PlayEffectOption} - * @return Promise<{success, value}> - */ - static playEffect(options) { - return Agora.playEffect(options); - } - /** - * stop play effect for audio mixing - * - * This methods stops the specified effect for audio mixing file by soundId. - * @param sounid - * @return Promise<{success, value}> - */ - static stopEffect(soundId) { - return Agora.stopEffect(soundId); - } - /** - * stop play all for effect audio mixing. - * - * This methods stops all effect audio mixing. - * @return Promise<{success, value}> - */ - static stopAllEffects() { - return Agora.stopAllEffects(); - } - /** - * preload effect for audio mixing file. - * - * This methods preloads the specified audio mixing file to memory by the soundId - * @param soundId - * @param filePath - * @return Promise<{success, value}> - */ - static preloadEffect(soundId, filePath) { - return Agora.preloadEffect(soundId, filePath); - } - /** - * unload effect - * - * This methods unload the already loaded audio mixing file from memory by the soundId. - * @param soundId - * @return Promise<{success, value}> - */ - static unloadEffect(soundId) { - return Agora.unloadEffect(soundId); - } - /** - * pause the specified effect for audio mixing by soundId - * - * This method pauses the specified effect for audio mixing by soundId. - * @param soundId - * @return Promise<{success, value}> - */ - static pauseEffect(soundId) { - return Agora.pauseEffect(soundId); - } - /** - * pause all effects for audio mixing - * - * This method pause all effects for audio mixing. - * @param soundId - * @return Promise<{success, value}> - */ - static pauseAllEffects() { - return Agora.pauseAllEffects(); - } - /** - * resume audio mixing effect by the specified soundId - * - * This method resumes audio mixing effect by the specified soundId - * @param soundId - * @return Promise<{success, value}> - */ - static resumeEffect(soundId) { - return Agora.resumeEffect(soundId); - } - /** - * resume all audio mixing effects. - * - * This method resumes all audio mixing effects. - * @return Promise<{success, value}> - */ - static resumeAllEffects() { - return Agora.resumeAllEffects(); - } - /** - * start audio recording by quality - * - * This method start audio recording by quality config - * @param options {@link AudioRecordingOption} - * @return Promise<{success, value}> - */ - static startAudioRecording(options) { - return Agora.startAudioRecording(options); - } - /** - * stop audio recording - * - * This method stops audio recording. - * @return Promise<{success, value}> - */ - static stopAudioRecording() { - return Agora.stopAudioRecording(); - } - /** - * set audio session operation restriction - * - * The SDK and the app can both configure the audio session by default. The app may occasionally use other apps or third-party components to manipulate the audio session and restrict the SDK from doing so. This method allows the app to restrict the SDK’s manipulation of the audio session. - * You can call this method at any time to return the control of the audio sessions to the SDK. - * This method restricts the SDK’s manipulation of the audio session. Any operation to the audio session relies solely on the app, other apps, or third-party components. - * @notice iOS support only - */ - static setAudioSessionOperationRestriction() { - if (react_native_1.Platform.OS != 'ios') - throw Error(`setAudioSessionOperationRestriction is not support on your platform. Please check the details in react-native-agora docs`); - Agora.setAudioSessionOperationRestriction(); - } - /** - * @deprecated startEchoTest - * startEchoTest - */ - /** - * @deprecated isCameraAutoFocusFaceModeSupported - * @deprecated isCameraExposurePositionSupported - * @deprecated isCameraFocusSupported - * @deprecated isCameraTorchSupported - * @deprecated isCameraZoomSupported - * instead use {@method getCameraInfo} - */ - /** - * stop echo test - * - * This method stop launched an audio call test. - * @return Promise<{success, value}> - */ - static stopEchoTest() { - return Agora.stopEchoTest(); - } - /** - * enable lastmile test - * - * This method enables the network connection qualit test. - * - * @return Promise<{success, value}> - */ - static enableLastmileTest() { - return Agora.enableLastmileTest(); - } - /** - * disable lastmile test - * - * This method disable the network connection qualit test. - * - * @return Promise<{success, value}> - */ - static disableLastmileTest() { - return Agora.disableLastmileTest(); - } - /** - * set recording audio frame parameters - * - * This method Sets the audio recording format for the audioFrame callback. - * - * @param options {@link RecordingAudioFrameOption} - * @return Promise<{success, value}> - */ - static setRecordingAudioFrameParameters(options) { - return Agora.setRecordingAudioFrameParameters(options); - } - /** - * set playback audio frame parameters - * - * This method Sets the audio frame format for the playbackFrame callback. - * - * @param options {@link AudioFrameOption} - * @return Promise<{success, value}> - */ - static setPlaybackAudioFrameParameters(options) { - return Agora.setPlaybackAudioFrameParameters(options); - } - /** - * set mixed audio frame parameters - * - * This method Sets the audio frame format for the mixedAudioFrame callback. - * - * @param options {@link MixedAudioFrameOption} - * @return Promise<{success, value}> - */ - static setMixedAudioFrameParameters(options) { - return Agora.setMixedAudioFrameParameters(options); - } - /** - * add video watermark - * - * This method adds video watermark to the local video. - * - * @param options {@link ImageOption} - * @return Promise<{success, value}> - */ - static addVideoWatermark(url, options) { - return Agora.addVideoWatermark({ url, options }); - } - /** - * clear video watermarks - * - * This method removes the watermark image from the video stream added by addVideoWatermark. - * - * @return Promise<{success, value}> - */ - static clearVideoWatermarks() { - return Agora.clearVideoWatermarks(); - } - /** - * set local publish fallback - * - * This method sets the fallback option for the locally published video stream based on the network conditions. - * - * @param option {0, 1, 2} [more details](https://docs.agora.io/en/Video/API%20Reference/java/classio_1_1agora_1_1rtc_1_1_constants.html#a3e453c93766e783a7e5eca05b1776238) - * @return Promise<{success, value}> - */ - static setLocalPublishFallbackOption(option) { - return Agora.setLocalPublishFallbackOption(option); - } - /** - * set remote publish fallback - * - * This method sets the fallback option for the remotely subscribed video stream based on the network conditions. - * - * @param option {0, 1, 2} [more details](https://docs.agora.io/en/Video/API%20Reference/java/classio_1_1agora_1_1rtc_1_1_constants.html#a3e453c93766e783a7e5eca05b1776238) - * @return Promise<{success, value}> - */ - static setRemoteSubscribeFallbackOption(option) { - return Agora.setRemoteSubscribeFallbackOption(option); - } - /** - * enable dual stream mode - * - * This method enables the dual stream by parameter mode. - * - * @param enabled - * @return Promise<{success, value}> - */ - static enableDualStreamMode(enabled) { - return Agora.enableDualStreamMode(enabled); - } - /** - * set remote video stream type - * - * This method sets the remote video stream type by uid and streamType. - * - * @param options {@link VideoStreamOption} - * @return Promise<{success, value}> - */ - static setRemoteVideoStreamType(options) { - return Agora.setRemoteVideoStreamType(options); - } - /** - * set remote default video stream type - * - * This method sets the default video stream type. - * - * @param options {@link DefaultVideoStreamOption} - * @return Promise<{success, value}> - */ - static setRemoteDefaultVideoStreamType(options) { - return Agora.setRemoteDefaultVideoStreamType(options); - } - /** - * add inject stream url - * - * This method injects an online media stream to a live broadcast. - * - * @param options {@link InjectStreamOption} - * @return Promise<{success, value}> - */ - static addInjectStreamUrl(options) { - return Agora.addInjectStreamUrl(options); - } - /** - * remove inject stream url - * - * This method removes stream by addInjectsStreamUrl. - * - * @param options {@link RemoveInjectStreamOption} - * @return Promise<{success, value}> - */ - static removeInjectStreamUrl(options) { - return Agora.removeInjectStreamUrl(options); - } - /** - * @deprecated sendMessage - * sendMessage - */ - static sendMessage() { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - return console.warn("sendMessage already deprecated"); - }); - } - /** - * @deprecated createDataStream - * createDataStream - */ - /** - * @deprecated setupLocalVideo - * setupLocalVideo - */ - /** - * @deprecated setupRemoteVideo - * setupRemoteVideo - */ - /** - * @deprecated setVideoQualityParameters - * setVideoQualityParameters - */ - /** - * set local video mirror mode - * - * This method sets local video mirror mode - * - * @param mode - * @return Promise<{success, value}> - */ - static setLocalVideoMirrorMode(mode) { - return Agora.setLocalVideoMirrorMode(mode); - } - /** - * switch camera - * - * This method switches camera between front and rear. - * - * @return Promise<{success, value}> - */ - static switchCamera() { - return Agora.switchCamera(); - } - /** - * set camera zoom ratio - * - * This method sets the camera zoom ratio. - * - * @param zoomFactor - * @return Promise<{success, value}> - */ - static setCameraZoomFactor(zoomFactor) { - return Agora.setCameraZoomFactor(zoomFactor); - } - /** - * get camera max zoom ratio - * - * This method gets the camera maximum zoom ratio. - * - * @notice Android Only - * @return Promise<{success, value}> - */ - static getCameraMaxZoomFactor() { - return Agora.getCameraMaxZoomFactor(); - } - /** - * set camera focus position in preview - * - * This method sets the mannual focus position. - * - * @param options {@link PositionOption} - * @return Promise<{success, value}> - */ - static setCameraFocusPositionInPreview(options) { - return Agora.setCameraFocusPositionInPreview(options); - } - /** - * set camera exposure position - * - * This method sets the mannual exposure position. - * - * @param options {@link PositionOption} - * @return Promise<{success, value}> - */ - static setCameraExposurePosition(options) { - return Agora.setCameraExposurePosition(options); - } - /** - * set camera torch on - * - * This method enables the camera flash function. - * - * @param enabled - * @return Promise<{success, value}> - */ - static setCameraTorchOn(enabled) { - return Agora.setCameraTorchOn(enabled); - } - /** - * set enable auto focus face mode - * - * This method enables auto-focus face mode function. - * - * @param enabled boolean - * @return Promise<{success, value}> - */ - static setCameraAutoFocusFaceModeEnabled(enabled) { - return Agora.setCameraAutoFocusFaceModeEnabled(enabled); - } - /** - * get call id - * - * This method is used to get call id. - * - * @return Promise<{success, value}> - */ - static getCallId() { - return Agora.getCallId(); - } - /** - * set log file and log filter - * - * This method sets the log file generated path and specified the log level. - * - * @param filePath string - * @param level enum - * @param maxfileSize integer (KB) - * @return Promise<{success, value}> - */ - static setLog(filePath, level, maxfileSize) { - return Agora.setLog(filePath, level, maxfileSize); - } - /** - * add publish stream url - * - * This method add publish stream by option. - * - * @param options {@link PublishStreamOption} - * @return Promise<{success, value}> - */ - static addPublishStreamUrl(options) { - return Agora.addPublishStreamUrl(options); - } - /** - * remove publish stream url - * - * This method remove publish stream by options. - * - * @param options {@link RemovePublishStreamOption} - * @return Promise<{success, value}> - */ - static removePublishStreamUrl(options) { - return Agora.removePublishStreamUrl(options); - } - /** - * set live transcoding - * - * This method sets the video layout and audio settings for CDN live. - * - * @param options {@link LiveTranscoding} - * @return Promise<{success, value}> - */ - static setLiveTranscoding(options) { - return Agora.setLiveTranscoding(options); - } - /** - * get sdk version - * - * This method gets the sdk version details and passed it into callback function - * - * @param callback to handle resolve from getSdkVersion - * @param errorHandler to handle reject error from getSdkVersion - * @return any - */ - static getSdkVersion(callback, errorHandler) { - return Agora.getSdkVersion().then(callback).catch(errorHandler); - } - /** - * mute local audio stream - * - * This method sends/stops sending the local audio. - * - * @param enabled - * @return Promise - */ - static muteLocalAudioStream(enabled) { - return Agora.muteLocalAudioStream(enabled); - } - /** - * video pre-process/post-process - * - * This method enables/disables image enhancement and sets the options. - * - * @param enabled boolean - * @param options {@link BeautyOptions} - * @return Promise - */ - static setBeautyEffectOptions(enabled, options) { - return Agora.setBeautyEffectOptions(enabled, options); - } - /** - * set local voice change - * - * This method changes local speaker voice with voiceChanger - * - * @param voiceChanger integer - * @voiceChanger value ranges [ - * 0: "The original voice", - * 1: "An old man’s voice", - * 2: "A little boy’s voice.", - * 3: "A little girl’s voice.", - * 4: "TBD", - * 5: "Ethereal vocal effects.", - * 6: "Hulk’s voice." - * ] - * @return Promise - */ - static setLocalVoiceChanger(voiceChanger) { - return Agora.setLocalVoiceChanger(voiceChanger); - } - /** - * set the preset local voice reverberation effect. - * - * This method sets the preset local voice reverberation effect. - * - * @param preset integer - * @return Promise - */ - static setLocalVoiceReverbPreset(preset) { - return Agora.setLocalVoiceReverbPreset(preset); - } - /** - * control stereo panning for remote users - * - * This method enables/disables stereo panning for remote users. - * - * @param enabled boolean - * @return Promise - */ - static enableSoundPositionIndication(enabled) { - return Agora.enableSoundPositionIndication(enabled); - } - /** - * set the sound position of a remote user - * - * This method sets the sound position of a remote user by uid - * - * @param uid number | The ID of the remote user - * @param pan float | The sound position of the remote user. The value ranges from -1.0 to 1.0 - * @pan - * 0.0: the remote sound comes from the front. - * -1.0: the remote sound comes from the left. - * 1.0: the remote sound comes from the right. - * @param gain float | Gain of the remote user. The value ranges from 0.0 to 100.0. The default value is 100.0 (the original gain of the remote user). The smaller the value, the less the gain. - * @return Promise - */ - static setRemoteVoicePosition(uid, pan, gain) { - let uint32 = react_native_1.Platform.OS === 'android' ? this.Uint32ToInt32(uid) : uid; - return Agora.setRemoteVoicePosition(uint32, pan, gain); - } - /** - * start the lastmile probe test - * - * This method start the last-mile network probe test before joining a channel to get the uplink and downlink last-mile network statistics, including the bandwidth, packet loss, jitter, and round-trip time (RTT). - * - * @param config LastmileProbeConfig {@link LastmileProbeConfig} - * - * event onLastmileQuality: the SDK triggers this callback within two seconds depending on the network conditions. This callback rates the network conditions with a score and is more closely linked to the user experience. - * event onLastmileProbeResult: the SDK triggers this callback within 30 seconds depending on the network conditions. This callback returns the real-time statistics of the network conditions and is more objective. - * @return Promise - */ - static startLastmileProbeTest(config) { - return Agora.startLastmileProbeTest(config); - } - /** - * stop the lastmile probe test - * - * This method stop the lastmile probe test. - * - * @return Promise - */ - static stopLastmileProbeTest() { - return Agora.stopLastmileProbeTest(); - } - /** - * sets the priority of a remote user's media stream. - * - * note: Use this method with the setRemoteSubscribeFallbackOption method. If the fallback function is enabled for a subscribed stream, the SDK ensures the high-priority user gets the best possible stream quality. - * - * This method sets the priority of a remote user's media stream. - * @param uid number - * @param userPriority number | The value range is [50 is "user's priority is high", 100 is "the default user's priority is normal"] - * - * @return Promise - */ - static setRemoteUserPriority(uid, userPriority) { - let uint32 = react_native_1.Platform.OS === 'android' ? this.Uint32ToInt32(uid) : uid; - return Agora.setRemoteUserPriority(uint32, userPriority); - } - /** - * start an audio call test. - * - * note: - * Call this method before joining a channel. - * After calling this method, call the stopEchoTest method to end the test. Otherwise, the app cannot run the next echo test, or call the joinChannel method. - * In the Live-broadcast profile, only a host can call this method. - * This method will start an audio call test with interval parameter. - * In the audio call test, you record your voice. If the recording plays back within the set time interval, the audio devices and the network connection are working properly. - * - * @param interval number - * - * @return Promise - */ - static startEchoTestWithInterval(interval) { - return Agora.startEchoTestWithInterval(interval); - } - /** - * set the camera capture preference. - * - * note: - * For a video call or live broadcast, generally the SDK controls the camera output parameters. When the default camera capture settings do not meet special requirements or cause performance problems, we recommend using this method to set the camera capture preference: - * If the resolution or frame rate of the captured raw video data are higher than those set by setVideoEncoderConfiguration, processing video frames requires extra CPU and RAM usage and degrades performance. We recommend setting config as CAPTURER_OUTPUT_PREFERENCE_PERFORMANCE(1) to avoid such problems. - * If you do not need local video preview or are willing to sacrifice preview quality, we recommend setting config as CAPTURER_OUTPUT_PREFERENCE_PERFORMANCE(1) to optimize CPU and RAM usage. - * If you want better quality for the local video preview, we recommend setting config as CAPTURER_OUTPUT_PREFERENCE_PREVIEW(2). - * - * This method will set the camera capture preference. - * - * @param config {@link CameraCapturerConfiguration} - * - * @return Promise - */ - static setCameraCapturerConfiguration(config) { - return Agora.setCameraCapturerConfiguration(config); - } - /** - * Gets the audio mixing volume for local playback. - * - * note: - * This method helps troubleshoot audio volume related issues. - * - * @return Promise - */ - static getAudioMixingPlayoutVolume() { - return Agora.getAudioMixingPlayoutVolume(); - } - /** - * Gets the audio mixing volume for publishing. - * - * note: - * This method helps troubleshoot audio volume related issues. - * - * @return Promise - */ - static getAudioMixingPublishVolume() { - return Agora.getAudioMixingPublishVolume(); - } - /** - * sendMediaData for media observer. - * - * note: - * This method needs you invoke registerMediaMetadataObserver success first and you could send media data through interval media observer feature. - * The data have limit length is 1024 bytes, if you pass data length bigger than limit it will failed. - * @param data String: 1024 bytes limit - * @return Promise - */ - static sendMediaData(data) { - return Agora.sendMediaData(data); - } - /** - * Registers the metadata observer. - * - * note: - * This method only work in live mode - * This method enables you to add synchronized metadata in the video stream for more diversified live broadcast interactions, such as sending shopping links, digital coupons, and online quizzes. - * This method trigger 'mediaMetaDataReceived' event, here is example: - * ```javascript - * RtcEngine.on("mediaMetaDataReceived", (data) => { - * console.log("mediaMetaDataReceived", data); - * }) - * ``` - * @return Promise - */ - static registerMediaMetadataObserver() { - return Agora.registerMediaMetadataObserver(); - } - /** - * Get local device camera support info - * - * note: - * This method returns your current device camera support info. - * ```javascript - * RtcEngine.getCameraInfo().then(info => { - * console.log("your currrent camera", info); - * }) - * ``` - * @return Promise<{cameraSupportInfo}> - */ - static getCameraInfo() { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - return Agora.getCameraInfo(); - }); - } - /** - * Set Private Parameters - * @param paramsStr - * @return Promise - */ - static setParameters(paramsStr) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - return Agora.setParameters(paramsStr); - }); - } - /** - * Get Private Parameter - * @param paramsStr - * @param args - * @return Promise - */ - static getParameter(paramsStr, args) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - return Agora.getParameter(paramsStr, args); - }); - } - /** - * Get Private Parameters - * @param paramsStr - * @param args - * @return Promise - */ - static getParameters(paramsStr) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - return Agora.getParameters(paramsStr); - }); - } - } - /** - * @ignore eventTypes - */ - RtcEngine._eventTypes = new Set(); - /** - * @ignore AG_PREFIX - */ - RtcEngine.AG_PREFIX = 'ag_rtc'; - return RtcEngine; -})(); -exports.default = RtcEngine; -//# sourceMappingURL=RtcEngine.native.js.map \ No newline at end of file diff --git a/lib/RtcEngine.native.js.map b/lib/RtcEngine.native.js.map deleted file mode 100644 index 83095049b..000000000 --- a/lib/RtcEngine.native.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"RtcEngine.native.js","sourceRoot":"","sources":["../src/RtcEngine.native.ts"],"names":[],"mappings":";;;AAAA,+CAAyE;AA2BzE,MAAM,EAAC,KAAK,EAAC,GAAG,4BAAa,CAAC;AAC9B,MAAM,iBAAiB,GAAG,IAAI,iCAAkB,CAAC,KAAK,CAAC,CAAC;AAExD;;;;;;GAMG;AACH;IAAA,MAAM,SAAS;QAYX;;;;;;;WAOG;QACI,MAAM,CAAC,IAAI,CAAC,OAAe;YAC9B,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACxB,CAAC;QAED;;;;;;;;;;WAUG;QACI,MAAM,CAAC,WAAW,CAAC,WAAmB,EAAE,GAAY,EAAE,KAAc,EAAE,IAAa;YACtF,OAAO,KAAK,CAAC,WAAW,CAAC,EAAC,WAAW,EAAE,GAAG,EAAE,KAAK,EAAE,IAAI,EAAC,CAAC,CAAC;QAC9D,CAAC;QAED;;;;;;;;;;;WAWG;QACI,MAAM,CAAC,aAAa,CAAC,WAAmB,EAAE,KAAc;YAC3D,OAAO,KAAK,CAAC,aAAa,CAAC,EAAC,WAAW,EAAE,KAAK,EAAC,CAAC,CAAC;QACrD,CAAC;QAED;;;;;;;;;WASG;QACI,MAAM,CAAC,sBAAsB,CAAC,MAAiC;YAClE,OAAO,KAAK,CAAC,sBAAsB,CAAC,MAAM,CAAC,CAAC;QAChD,CAAC;QAED;;;;;;;;WAQG;QACI,MAAM,CAAC,uBAAuB,CAAC,MAAiC;YACnE,OAAO,KAAK,CAAC,uBAAuB,CAAC,MAAM,CAAC,CAAC;QACjD,CAAC;QAED;;;;;;;;WAQG;QACI,MAAM,CAAC,uBAAuB,CAAC,MAAiC;YACnE,OAAO,KAAK,CAAC,uBAAuB,CAAC,MAAM,CAAC,CAAC;QACjD,CAAC;QAED;;;;;;;;WAQG;QACI,MAAM,CAAC,qBAAqB;YAC/B,OAAO,KAAK,CAAC,qBAAqB,EAAE,CAAC;QACzC,CAAC;QAED;;;;;;;;;;;;WAYG;QACI,MAAM,CAAC,wBAAwB,CAAC,WAAmB;YACtD,OAAO,KAAK,CAAC,wBAAwB,CAAC,EAAC,WAAW,EAAC,CAAC,CAAC;QACzD,CAAC;QAED;;;;;;;;;;;;;;WAcG;QACI,MAAM,CAAC,0BAA0B,CAAC,WAAmB,EAAE,WAAmB,EAAE,KAAa;YAC5F,OAAO,KAAK,CAAC,0BAA0B,CAAC,EAAC,WAAW,EAAE,WAAW,EAAE,KAAK,EAAC,CAAC,CAAC;QAC/E,CAAC;QAED;;;;;;WAMG;QACI,MAAM,CAAO,gBAAgB,CAAC,GAAW;;gBAC5C,IAAI,uBAAQ,CAAC,EAAE,KAAK,SAAS,EAAE;oBAC3B,MAAM,IAAI,GAAG,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC;oBACrC,IAAI,MAAM,GAAG,MAAM,KAAK,CAAC,gBAAgB,CAAC,IAAI,CAAC,CAAC;oBAChD,MAAM,CAAC,GAAG,GAAG,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;oBAC5C,OAAO,MAAM,CAAC;iBACjB;gBACD,OAAO,KAAK,CAAC,gBAAgB,CAAC,GAAG,CAAC,CAAC;YACvC,CAAC;SAAA;QAED;;;;;;WAMG;QACI,MAAM,CAAO,wBAAwB,CAAC,WAAmB;;gBAC5D,IAAI,uBAAQ,CAAC,EAAE,KAAK,SAAS,EAAE;oBAC3B,IAAI,MAAM,GAAG,MAAM,KAAK,CAAC,wBAAwB,CAAC,WAAW,CAAC,CAAC;oBAC/D,MAAM,CAAC,GAAG,GAAG,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;oBAC5C,OAAO,MAAM,CAAC;iBACjB;gBACD,OAAO,KAAK,CAAC,wBAAwB,CAAC,WAAW,CAAC,CAAC;YACvD,CAAC;SAAA;QAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;WAoFG;QACI,MAAM,CAAC,EAAE,CAAC,SAAiB,EAAE,QAAiC;YACjE,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,GAAG,SAAS,CAAC,SAAS,GAAG,SAAS,EAAE,CAAC,CAAC;YAC3D,0BAA0B;YAC1B,IAAI;gBACA,oBAAoB;gBACpB,sBAAsB;gBACtB,YAAY;gBACZ,aAAa;gBACb,yBAAyB;gBACzB,sBAAsB;gBACtB,eAAe;gBACf,uBAAuB;gBACvB,uBAAuB;gBACvB,eAAe;gBACf,kBAAkB;gBAClB,yBAAyB;gBACzB,yBAAyB;gBACzB,oCAAoC;gBACpC,gBAAgB;gBAChB,sBAAsB;gBACtB,qBAAqB;aACxB,CAAC,OAAO,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,EAAE;gBACxB,iBAAiB,CAAC,WAAW,CAAC,GAAG,SAAS,CAAC,SAAS,GAAG,SAAS,EAAE,EAAE,CAAC,IAAI,EAAE,EAAE;oBACzE,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;oBACxC,mCAAmC;oBACnC,IAAI,IAAI,CAAC,QAAQ,EAAE;wBACf,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;qBACrD;oBACD,QAAQ,CAAC,IAAI,CAAC,CAAC;gBACnB,CAAC,CAAC,CAAC;gBACH,OAAO;aACV;YAED,IAAI,CAAC,iBAAiB,CAAC,CAAC,OAAO,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,EAAE;gBAC9C,iBAAiB,CAAC,WAAW,CAAC,GAAG,SAAS,CAAC,SAAS,GAAG,SAAS,EAAE,EAAE,CAAC,IAAI,EAAE,EAAE;oBACzE,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;oBACxC,IAAI,CAAC,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;oBAClD,QAAQ,CAAC,IAAI,CAAC,CAAC;gBACnB,CAAC,CAAC,CAAC;gBACH,OAAO;aACV;YAED,IAAI,CAAC,uBAAuB,CAAC,CAAC,OAAO,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,EAAE;gBACpD,iBAAiB,CAAC,WAAW,CAAC,GAAG,SAAS,CAAC,SAAS,GAAG,SAAS,EAAE,EAAE,CAAC,IAAI,EAAE,EAAE;oBACzE,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,OAAY,EAAE,EAAE;wBAC/B,MAAM,GAAG,GAAG,IAAI,CAAC,aAAa,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;wBAC5C,uCACO,OAAO,KACV,GAAG,IACN;oBACL,CAAC,CAAC,CAAA;oBACF,QAAQ,CAAC,IAAI,CAAC,CAAC;gBACnB,CAAC,CAAC,CAAC;gBACH,OAAO;aACV;YAED,IAAI;gBACA,kBAAkB;gBAClB,kBAAkB;aACrB,CAAC,OAAO,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,EAAE;gBACxB,iBAAiB,CAAC,WAAW,CAAC,GAAG,SAAS,CAAC,SAAS,GAAG,SAAS,EAAE,EAAE,CAAC,IAAI,EAAE,EAAE;oBACzE,IAAI,CAAC,KAAK,CAAC,GAAG,GAAG,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;oBACpD,QAAQ,CAAC,IAAI,CAAC,CAAC;gBACnB,CAAC,CAAC,CAAC;gBACH,OAAO;aACV;YACD,iBAAiB,CAAC,WAAW,CAAC,GAAG,SAAS,CAAC,SAAS,GAAG,SAAS,EAAE,EAAE,QAAQ,CAAC,CAAC;QAClF,CAAC;QAED;;WAEG;QACH,MAAM,CAAC,kBAAkB;YACrB,OAAO,CAAC,IAAI,CAAC,8CAA8C,CAAC,CAAC;QACjE,CAAC;QAED;;;WAGG;QACH,MAAM,CAAC,GAAG,CAAC,GAAQ;YACf,OAAO,CAAC,IAAI,CAAC,+BAA+B,CAAC,CAAC;QAClD,CAAC;QAED;;;;;WAKG;QACI,MAAM,CAAC,UAAU,CAAC,KAAa;YAClC,OAAO,KAAK,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;QACnC,CAAC;QAED;;;;;;;WAOG;QACI,MAAM,CAAC,4BAA4B,CAAC,OAAgB;YACvD,OAAO,KAAK,CAAC,4BAA4B,CAAC,OAAO,CAAC,CAAC;QACvD,CAAC;QAED;;;;;WAKG;QACI,MAAM,CAAC,kBAAkB;YAC5B,OAAO,KAAK,CAAC,kBAAkB,EAAE,CAAC;QACtC,CAAC;QAED;;;;;WAKG;QACI,MAAM,CAAC,aAAa,CAAC,IAAY;YACpC,OAAO,KAAK,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;QACrC,CAAC;QAED;;;;;;;WAOG;QACI,MAAM,CAAC,YAAY;YACtB,OAAO,KAAK,CAAC,YAAY,EAAE,CAAC;QAChC,CAAC;QAED;;;;;;;WAOG;QACI,MAAM,CAAC,OAAO;YACjB,IAAI,IAAI,CAAC,WAAW,CAAC,IAAI,EAAE;gBACvB,KAAK,IAAI,SAAS,IAAI,IAAI,CAAC,WAAW,EAAE;oBACpC,iBAAiB,CAAC,kBAAkB,CAAC,SAAS,CAAC,CAAC;iBACnD;gBACD,IAAI,CAAC,WAAW,CAAC,KAAK,EAAE,CAAC;aAC5B;YACD,OAAO,KAAK,CAAC,OAAO,EAAE,CAAC;QAC3B,CAAC;QAED;;;;;;WAMG;QACI,MAAM,CAAC,kBAAkB,CAAC,IAAY;YACzC,OAAO,KAAK,CAAC,kBAAkB,CAAC,IAAI,CAAC,CAAC;QAC1C,CAAC;QAED;;;;;;;;WAQG;QACI,MAAM,CAAC,mBAAmB,CAAC,GAAW,EAAE,IAAY;YACvD,IAAI,MAAM,GAAG,uBAAQ,CAAC,EAAE,KAAK,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC;YACvE,OAAO,KAAK,CAAC,mBAAmB,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;QACnD,CAAC;QAED;;;;;WAKG;QACI,MAAM,CAAC,YAAY;YACtB,OAAO,KAAK,CAAC,YAAY,EAAE,CAAC;QAChC,CAAC;QAGD;;;;;WAKG;QACI,MAAM,CAAC,WAAW;YACrB,OAAO,KAAK,CAAC,WAAW,EAAE,CAAC;QAC/B,CAAC;QAED;;;;;;WAMG;QACI,MAAM,CAAC,qBAAqB,CAAC,OAAgB;YAChD,OAAO,KAAK,CAAC,qBAAqB,CAAC,OAAO,CAAC,CAAC;QAChD,CAAC;QAED;;;;;;WAMG;QACI,MAAM,CAAC,kCAAkC,CAAC,OAAgB;YAC7D,OAAO,KAAK,CAAC,kCAAkC,CAAC,OAAO,CAAC,CAAC;QAC7D,CAAC;QAED;;;;;;WAMG;QACI,MAAM,CAAC,mCAAmC,CAAC,OAAgB;YAC9D,OAAO,KAAK,CAAC,mCAAmC,CAAC,OAAO,CAAC,CAAC;QAC9D,CAAC;QAED;;;;;WAKG;QACI,MAAM,CAAC,WAAW;YACrB,OAAO,KAAK,CAAC,WAAW,EAAE,CAAC;QAC/B,CAAC;QAED;;;;;WAKG;QACI,MAAM,CAAC,YAAY;YACtB,OAAO,KAAK,CAAC,YAAY,EAAE,CAAC;QAChC,CAAC;QAED;;;;;;WAMG;QACI,MAAM,CAAC,gBAAgB,CAAC,OAAgB;YAC3C,OAAO,KAAK,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC;QAC3C,CAAC;QAED;;;;;;WAMG;QACI,MAAM,CAAC,oBAAoB,CAAC,KAAc;YAC7C,OAAO,KAAK,CAAC,oBAAoB,CAAC,KAAK,CAAC,CAAC;QAC7C,CAAC;QAED;;;;;;WAMG;QACI,MAAM,CAAC,yBAAyB,CAAC,KAAc;YAClD,OAAO,KAAK,CAAC,yBAAyB,CAAC,KAAK,CAAC,CAAC;QAClD,CAAC;QAED;;WAEG;QACK,MAAM,CAAC,aAAa,CAAC,GAAW;YACpC,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC,CAAC,CAAC,CAAC;YAChC,KAAK,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC;YACf,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC;QACpB,CAAC;QAED;;WAEG;QACK,MAAM,CAAC,aAAa,CAAC,GAAW;YACpC,MAAM,MAAM,GAAG,IAAI,WAAW,CAAC,CAAC,CAAC,CAAC;YAClC,MAAM,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC;YAChB,OAAO,MAAM,CAAC,CAAC,CAAC,CAAC;QACrB,CAAC;QAED;;;;;;;WAOG;QACI,MAAM,CAAC,qBAAqB,CAAC,GAAW,EAAE,KAAc;YAC3D,IAAI,MAAM,GAAG,uBAAQ,CAAC,EAAE,KAAK,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC;YACvE,OAAO,KAAK,CAAC,qBAAqB,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;QACtD,CAAC;QAED;;;;;;WAMG;QACI,MAAM,CAAC,mCAAmC,CAAC,KAAc;YAC5D,OAAO,KAAK,CAAC,mCAAmC,CAAC,KAAK,CAAC,CAAC;QAC5D,CAAC;QAED;;;;;WAKG;QACI,MAAM,CAAC,WAAW;YACrB,OAAO,KAAK,CAAC,WAAW,EAAE,CAAC;QAC/B,CAAC;QAED;;;;;WAKG;QACI,MAAM,CAAC,YAAY;YACtB,OAAO,KAAK,CAAC,YAAY,EAAE,CAAC;QAChC,CAAC;QAED;;;;;;WAMG;QACI,MAAM,CAAC,gBAAgB,CAAC,OAAgB;YAC3C,OAAO,KAAK,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC;QAC3C,CAAC;QAED;;;;;;WAMG;QACI,MAAM,CAAC,iBAAiB,CAAC,KAAc;YAC1C,OAAO,KAAK,CAAC,iBAAiB,CAAC,KAAK,CAAC,CAAC;QAC1C,CAAC;QAED;;;;;;WAMG;QACI,MAAM,CAAC,yBAAyB,CAAC,KAAc;YAClD,OAAO,KAAK,CAAC,yBAAyB,CAAC,KAAK,CAAC,CAAC;QAClD,CAAC;QAED;;;;;;;WAOG;QACI,MAAM,CAAC,qBAAqB,CAAC,GAAW,EAAE,KAAc;YAC3D,IAAI,MAAM,GAAG,uBAAQ,CAAC,EAAE,KAAK,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC;YACvE,OAAO,KAAK,CAAC,qBAAqB,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;QACtD,CAAC;QAED;;;;;;WAMG;QACI,MAAM,CAAC,2BAA2B,CAAC,MAAc;YACpD,OAAO,KAAK,CAAC,2BAA2B,CAAC,MAAM,CAAC,CAAC;QACrD,CAAC;QAED;;;;;;WAMG;QACI,MAAM,CAAC,0BAA0B,CAAC,MAAc;YACnD,OAAO,KAAK,CAAC,0BAA0B,CAAC,MAAM,CAAC,CAAC;QACpD,CAAC;QAED;;;;;;;;WAQG;QACI,MAAM,CAAC,2BAA2B,CAAC,QAAgB,EAAE,MAAc,EAAE,GAAY;YACpF,OAAO,KAAK,CAAC,2BAA2B,CAAC,QAAQ,EAAE,MAAM,EAAE,GAAG,CAAC,CAAC;QACpE,CAAC;QAED;;;;;;WAMG;QACI,MAAM,CAAC,qBAAqB,CAAC,QAAuB;YACvD,OAAO,KAAK,CAAC,qBAAqB,CAAC,QAAQ,CAAC,CAAC;QACjD,CAAC;QAED;;;;;;;WAOG;QACI,MAAM,CAAC,qBAAqB,CAAC,OAAgB;YAChD,OAAO,KAAK,CAAC,qBAAqB,CAAC,OAAO,CAAC,CAAC;QAChD,CAAC;QAED;;;;;;;WAOG;QACI,MAAM,CAAC,wBAAwB,CAAC,MAAc;YACjD,OAAO,KAAK,CAAC,wBAAwB,CAAC,MAAM,CAAC,CAAC;QAClD,CAAC;QAED;;;;;;;WAOG;QACI,MAAM,CAAC,kBAAkB,CAAC,KAAa;YAC1C,OAAO,KAAK,CAAC,kBAAkB,CAAC,KAAK,CAAC,CAAC;QAC3C,CAAC;QAED;;;;;;;;WAQG;QACI,MAAM,CAAC,yBAAyB,CAAC,IAAY,EAAE,IAAY;YAC9D,KAAK,CAAC,yBAAyB,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;QAChD,CAAC;QAED;;;;;;WAMG;QACI,MAAM,CAAC,mBAAmB,CAAC,MAAc,EAAE,KAAa;YAC3D,KAAK,CAAC,mBAAmB,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;QAC7C,CAAC;QAED;;;;;;WAMG;QACI,MAAM,CAAC,gBAAgB,CAAC,OAA0B;YACrD,KAAK,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC;QACpC,CAAC;QAED;;;;WAIG;QACI,MAAM,CAAC,eAAe;YACzB,KAAK,CAAC,eAAe,EAAE,CAAC;QAC5B,CAAC;QAED;;;;WAIG;QACI,MAAM,CAAC,gBAAgB;YAC1B,KAAK,CAAC,gBAAgB,EAAE,CAAC;QAC7B,CAAC;QAED;;;;WAIG;QACI,MAAM,CAAC,iBAAiB;YAC3B,KAAK,CAAC,iBAAiB,EAAE,CAAC;QAC9B,CAAC;QAED;;;;;WAKG;QACI,MAAM,CAAC,uBAAuB,CAAC,MAAc;YAChD,KAAK,CAAC,uBAAuB,CAAC,MAAM,CAAC,CAAC;QAC1C,CAAC;QAED;;;;;WAKG;QACI,MAAM,CAAC,8BAA8B,CAAC,MAAc;YACvD,KAAK,CAAC,8BAA8B,CAAC,MAAM,CAAC,CAAC;QACjD,CAAC;QAED;;;;;WAKG;QACI,MAAM,CAAC,8BAA8B,CAAC,MAAc;YACvD,KAAK,CAAC,8BAA8B,CAAC,MAAM,CAAC,CAAC;QACjD,CAAC;QAED;;;;;WAKG;QACI,MAAM,CAAC,sBAAsB;YAChC,OAAO,KAAK,CAAC,sBAAsB,EAAE,CAAC;QAC1C,CAAC;QAED;;;;;WAKG;QACI,MAAM,CAAC,6BAA6B;YACvC,OAAO,KAAK,CAAC,6BAA6B,EAAE,CAAC;QACjD,CAAC;QAED;;;;;WAKG;QACI,MAAM,CAAC,sBAAsB,CAAC,GAAW;YAC5C,OAAO,KAAK,CAAC,sBAAsB,CAAC,GAAG,CAAC,CAAC;QAC7C,CAAC;QAED;;;;;WAKG;QACI,MAAM,CAAC,gBAAgB;YAC1B,OAAO,KAAK,CAAC,gBAAgB,EAAE,CAAC;QACpC,CAAC;QAED;;;;;;WAMG;QACI,MAAM,CAAC,gBAAgB,CAAC,MAAc;YACzC,OAAO,KAAK,CAAC,gBAAgB,CAAC,MAAM,CAAC,CAAC;QAC1C,CAAC;QAED;;;;;WAKG;QACI,MAAM,CAAC,iBAAiB,CAAC,MAAc;YAC1C,OAAO,KAAK,CAAC,iBAAiB,CAAC,MAAM,CAAC,CAAC;QAC3C,CAAC;QAED;;;;;;WAMG;QACI,MAAM,CAAC,UAAU,CAAC,OAAyB;YAC9C,OAAO,KAAK,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;QACrC,CAAC;QAED;;;;;;WAMG;QACI,MAAM,CAAC,UAAU,CAAC,OAAe;YACpC,OAAO,KAAK,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;QACrC,CAAC;QAED;;;;;WAKG;QACI,MAAM,CAAC,cAAc;YACxB,OAAO,KAAK,CAAC,cAAc,EAAE,CAAC;QAClC,CAAC;QAED;;;;;;;WAOG;QACI,MAAM,CAAC,aAAa,CAAC,OAAe,EAAE,QAAgB;YACzD,OAAO,KAAK,CAAC,aAAa,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;QAClD,CAAC;QAED;;;;;;WAMG;QACI,MAAM,CAAC,YAAY,CAAC,OAAe;YACtC,OAAO,KAAK,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;QACvC,CAAC;QAED;;;;;;WAMG;QACI,MAAM,CAAC,WAAW,CAAC,OAAe;YACrC,OAAO,KAAK,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;QACtC,CAAC;QAED;;;;;;WAMG;QACI,MAAM,CAAC,eAAe;YACzB,OAAO,KAAK,CAAC,eAAe,EAAE,CAAC;QACnC,CAAC;QAED;;;;;;WAMG;QACI,MAAM,CAAC,YAAY,CAAC,OAAe;YACtC,OAAO,KAAK,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;QACvC,CAAC;QAED;;;;;WAKG;QACI,MAAM,CAAC,gBAAgB;YAC1B,OAAO,KAAK,CAAC,gBAAgB,EAAE,CAAC;QACpC,CAAC;QAED;;;;;;WAMG;QACI,MAAM,CAAC,mBAAmB,CAAC,OAA6B;YAC3D,OAAO,KAAK,CAAC,mBAAmB,CAAC,OAAO,CAAC,CAAC;QAC9C,CAAC;QAED;;;;;WAKG;QACI,MAAM,CAAC,kBAAkB;YAC5B,OAAO,KAAK,CAAC,kBAAkB,EAAE,CAAC;QACtC,CAAC;QAED;;;;;;;WAOG;QACI,MAAM,CAAC,mCAAmC;YAC7C,IAAI,uBAAQ,CAAC,EAAE,IAAI,KAAK;gBAAE,MAAM,KAAK,CAAC,0HAA0H,CAAC,CAAC;YAClK,KAAK,CAAC,mCAAmC,EAAE,CAAC;QAChD,CAAC;QAED;;;WAGG;QAEH;;;;;;;WAOG;QAEH;;;;;WAKG;QACI,MAAM,CAAC,YAAY;YACtB,OAAO,KAAK,CAAC,YAAY,EAAE,CAAC;QAChC,CAAC;QAED;;;;;;WAMG;QACI,MAAM,CAAC,kBAAkB;YAC5B,OAAO,KAAK,CAAC,kBAAkB,EAAE,CAAC;QACtC,CAAC;QAED;;;;;;WAMG;QACI,MAAM,CAAC,mBAAmB;YAC7B,OAAO,KAAK,CAAC,mBAAmB,EAAE,CAAC;QACvC,CAAC;QAED;;;;;;;WAOG;QACI,MAAM,CAAC,gCAAgC,CAAC,OAAyB;YACpE,OAAO,KAAK,CAAC,gCAAgC,CAAC,OAAO,CAAC,CAAC;QAC3D,CAAC;QAED;;;;;;;WAOG;QACI,MAAM,CAAC,+BAA+B,CAAC,OAAyB;YACnE,OAAO,KAAK,CAAC,+BAA+B,CAAC,OAAO,CAAC,CAAC;QAC1D,CAAC;QAED;;;;;;;WAOG;QACI,MAAM,CAAC,4BAA4B,CAAC,OAA8B;YACrE,OAAO,KAAK,CAAC,4BAA4B,CAAC,OAAO,CAAC,CAAC;QACvD,CAAC;QAED;;;;;;;WAOG;QACI,MAAM,CAAC,iBAAiB,CAAC,GAAW,EAAE,OAAoB;YAC7D,OAAO,KAAK,CAAC,iBAAiB,CAAC,EAAC,GAAG,EAAE,OAAO,EAAC,CAAC,CAAC;QACnD,CAAC;QAED;;;;;;WAMG;QACI,MAAM,CAAC,oBAAoB;YAC9B,OAAO,KAAK,CAAC,oBAAoB,EAAE,CAAC;QACxC,CAAC;QAED;;;;;;;WAOG;QACI,MAAM,CAAC,6BAA6B,CAAC,MAAc;YACtD,OAAO,KAAK,CAAC,6BAA6B,CAAC,MAAM,CAAC,CAAC;QACvD,CAAC;QAED;;;;;;;WAOG;QACI,MAAM,CAAC,gCAAgC,CAAC,MAAc;YACzD,OAAO,KAAK,CAAC,gCAAgC,CAAC,MAAM,CAAC,CAAC;QAC1D,CAAC;QAED;;;;;;;WAOG;QACI,MAAM,CAAC,oBAAoB,CAAC,OAAgB;YAC/C,OAAO,KAAK,CAAC,oBAAoB,CAAC,OAAO,CAAC,CAAC;QAC/C,CAAC;QAED;;;;;;;WAOG;QACI,MAAM,CAAC,wBAAwB,CAAC,OAA0B;YAC7D,OAAO,KAAK,CAAC,wBAAwB,CAAC,OAAO,CAAC,CAAC;QACnD,CAAC;QAED;;;;;;;WAOG;QACI,MAAM,CAAC,+BAA+B,CAAC,OAAiC;YAC3E,OAAO,KAAK,CAAC,+BAA+B,CAAC,OAAO,CAAC,CAAC;QAC1D,CAAC;QAED;;;;;;;WAOG;QACI,MAAM,CAAC,kBAAkB,CAAC,OAA2B;YACxD,OAAO,KAAK,CAAC,kBAAkB,CAAC,OAAO,CAAC,CAAC;QAC7C,CAAC;QAED;;;;;;;WAOG;QACI,MAAM,CAAC,qBAAqB,CAAC,OAAiC;YACjE,OAAO,KAAK,CAAC,qBAAqB,CAAC,OAAO,CAAC,CAAC;QAChD,CAAC;QAED;;;WAGG;QACH,MAAM,CAAO,WAAW;;gBACpB,OAAO,OAAO,CAAC,IAAI,CAAC,gCAAgC,CAAC,CAAC;YAC1D,CAAC;SAAA;QAED;;;WAGG;QAEH;;;WAGG;QAEH;;;WAGG;QAGH;;;WAGG;QAEH;;;;;;;WAOG;QACI,MAAM,CAAC,uBAAuB,CAAC,IAAY;YAC9C,OAAO,KAAK,CAAC,uBAAuB,CAAC,IAAI,CAAC,CAAC;QAC/C,CAAC;QAED;;;;;;WAMG;QACI,MAAM,CAAC,YAAY;YACtB,OAAO,KAAK,CAAC,YAAY,EAAE,CAAC;QAChC,CAAC;QAED;;;;;;;WAOG;QACI,MAAM,CAAC,mBAAmB,CAAC,UAAkB;YAChD,OAAO,KAAK,CAAC,mBAAmB,CAAC,UAAU,CAAC,CAAC;QACjD,CAAC;QAED;;;;;;;WAOG;QACI,MAAM,CAAC,sBAAsB;YAChC,OAAO,KAAK,CAAC,sBAAsB,EAAE,CAAC;QAC1C,CAAC;QAED;;;;;;;WAOG;QACI,MAAM,CAAC,+BAA+B,CAAC,OAAuB;YACjE,OAAO,KAAK,CAAC,+BAA+B,CAAC,OAAO,CAAC,CAAC;QAC1D,CAAC;QAED;;;;;;;WAOG;QACI,MAAM,CAAC,yBAAyB,CAAC,OAAuB;YAC3D,OAAO,KAAK,CAAC,yBAAyB,CAAC,OAAO,CAAC,CAAC;QACpD,CAAC;QAED;;;;;;;WAOG;QACI,MAAM,CAAC,gBAAgB,CAAC,OAAgB;YAC3C,OAAO,KAAK,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC;QAC3C,CAAC;QAED;;;;;;;WAOG;QACI,MAAM,CAAC,iCAAiC,CAAC,OAAgB;YAC5D,OAAO,KAAK,CAAC,iCAAiC,CAAC,OAAO,CAAC,CAAC;QAC5D,CAAC;QAED;;;;;;WAMG;QACI,MAAM,CAAC,SAAS;YACnB,OAAO,KAAK,CAAC,SAAS,EAAE,CAAC;QAC7B,CAAC;QAED;;;;;;;;;WASG;QACI,MAAM,CAAC,MAAM,CAAC,QAAgB,EAAE,KAAa,EAAE,WAAmB;YACrE,OAAO,KAAK,CAAC,MAAM,CAAC,QAAQ,EAAE,KAAK,EAAE,WAAW,CAAC,CAAA;QACrD,CAAC;QAED;;;;;;;WAOG;QACI,MAAM,CAAC,mBAAmB,CAAC,OAA4B;YAC1D,OAAO,KAAK,CAAC,mBAAmB,CAAC,OAAO,CAAC,CAAC;QAC9C,CAAC;QAED;;;;;;;WAOG;QACI,MAAM,CAAC,sBAAsB,CAAC,OAAkC;YACnE,OAAO,KAAK,CAAC,sBAAsB,CAAC,OAAO,CAAC,CAAC;QACjD,CAAC;QAED;;;;;;;WAOG;QACI,MAAM,CAAC,kBAAkB,CAAC,OAA8B;YAC3D,OAAO,KAAK,CAAC,kBAAkB,CAAC,OAAO,CAAC,CAAC;QAC7C,CAAC;QAED;;;;;;;;WAQG;QACI,MAAM,CAAC,aAAa,CAAC,QAAuB,EAAE,YAA4B;YAC7E,OAAO,KAAK,CAAC,aAAa,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;QACpE,CAAC;QAED;;;;;;;WAOG;QAEI,MAAM,CAAC,oBAAoB,CAAC,OAAgB;YAC/C,OAAO,KAAK,CAAC,oBAAoB,CAAC,OAAO,CAAC,CAAC;QAC/C,CAAC;QAED;;;;;;;;WAQG;QACH,MAAM,CAAC,sBAAsB,CAAC,OAAgB,EAAE,OAAqB;YACjE,OAAO,KAAK,CAAC,sBAAsB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QAC1D,CAAC;QAED;;;;;;;;;;;;;;;;WAgBG;QACH,MAAM,CAAC,oBAAoB,CAAC,YAAoB;YAC5C,OAAO,KAAK,CAAC,oBAAoB,CAAC,YAAY,CAAC,CAAC;QACpD,CAAC;QAED;;;;;;;WAOG;QACH,MAAM,CAAC,yBAAyB,CAAC,MAAc;YAC3C,OAAO,KAAK,CAAC,yBAAyB,CAAC,MAAM,CAAC,CAAC;QACnD,CAAC;QAED;;;;;;;WAOG;QACH,MAAM,CAAC,6BAA6B,CAAC,OAAgB;YACjD,OAAO,KAAK,CAAC,6BAA6B,CAAC,OAAO,CAAC,CAAC;QACxD,CAAC;QAED;;;;;;;;;;;;;WAaG;QACH,MAAM,CAAC,sBAAsB,CAAC,GAAW,EAAE,GAAW,EAAE,IAAY;YAChE,IAAI,MAAM,GAAG,uBAAQ,CAAC,EAAE,KAAK,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC;YACvE,OAAO,KAAK,CAAC,sBAAsB,CAAC,MAAM,EAAE,GAAG,EAAE,IAAI,CAAC,CAAA;QAC1D,CAAC;QAED;;;;;;;;;;WAUG;QACH,MAAM,CAAC,sBAAsB,CAAC,MAA2B;YACrD,OAAO,KAAK,CAAC,sBAAsB,CAAC,MAAM,CAAC,CAAC;QAChD,CAAC;QAED;;;;;;WAMG;QACH,MAAM,CAAC,qBAAqB;YACxB,OAAO,KAAK,CAAC,qBAAqB,EAAE,CAAC;QACzC,CAAC;QAED;;;;;;;;;;WAUG;QACH,MAAM,CAAC,qBAAqB,CAAC,GAAW,EAAE,YAAoB;YAC1D,IAAI,MAAM,GAAG,uBAAQ,CAAC,EAAE,KAAK,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC;YACvE,OAAO,KAAK,CAAC,qBAAqB,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;QAC7D,CAAC;QAED;;;;;;;;;;;;;WAaG;QACH,MAAM,CAAC,yBAAyB,CAAC,QAAgB;YAC7C,OAAO,KAAK,CAAC,yBAAyB,CAAC,QAAQ,CAAC,CAAA;QACpD,CAAC;QAED;;;;;;;;;;;;;;WAcG;QACH,MAAM,CAAC,8BAA8B,CAAC,MAAmC;YACrE,OAAO,KAAK,CAAC,8BAA8B,CAAC,MAAM,CAAC,CAAC;QACxD,CAAC;QAED;;;;;;;WAOG;QACH,MAAM,CAAC,2BAA2B;YAC9B,OAAO,KAAK,CAAC,2BAA2B,EAAE,CAAC;QAC/C,CAAC;QAED;;;;;;;WAOG;QACH,MAAM,CAAC,2BAA2B;YAC9B,OAAO,KAAK,CAAC,2BAA2B,EAAE,CAAC;QAC/C,CAAC;QAED;;;;;;;;WAQG;QACH,MAAM,CAAC,aAAa,CAAC,IAAY;YAC7B,OAAO,KAAK,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;QACrC,CAAC;QAED;;;;;;;;;;;;;WAaG;QACH,MAAM,CAAC,6BAA6B;YAChC,OAAO,KAAK,CAAC,6BAA6B,EAAE,CAAC;QACjD,CAAC;QAED;;;;;;;;;;;WAWG;QACH,MAAM,CAAO,aAAa;;gBACtB,OAAO,KAAK,CAAC,aAAa,EAAE,CAAC;YACjC,CAAC;SAAA;QAED;;;;WAIG;QACH,MAAM,CAAO,aAAa,CAAC,SAAiB;;gBACxC,OAAO,KAAK,CAAC,aAAa,CAAC,SAAS,CAAC,CAAC;YAC1C,CAAC;SAAA;QAED;;;;;WAKG;QACH,MAAM,CAAO,YAAY,CAAC,SAAiB,EAAE,IAAY;;gBACrD,OAAO,KAAK,CAAC,YAAY,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;YAC/C,CAAC;SAAA;QAED;;;;;WAKG;QACH,MAAM,CAAO,aAAa,CAAC,SAAiB;;gBACxC,OAAO,KAAK,CAAC,aAAa,CAAC,SAAS,CAAC,CAAC;YAC1C,CAAC;SAAA;;IA7oDD;;OAEG;IACqB,qBAAW,GAAgB,IAAI,GAAG,EAAU,CAAC;IAErE;;OAEG;IACqB,mBAAS,GAAW,QAAQ,CAAC;IAsoDzD,gBAAC;KAAA;AAED,kBAAe,SAAS,CAAC"} \ No newline at end of file diff --git a/lib/index.d.ts b/lib/index.d.ts deleted file mode 100644 index 63b91c3ba..000000000 --- a/lib/index.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -export { default as AgoraView } from './AgoraView.native'; -export { default as RtcEngine } from './RtcEngine.native'; -export * from "./types"; diff --git a/lib/index.js b/lib/index.js deleted file mode 100644 index 020ebd85a..000000000 --- a/lib/index.js +++ /dev/null @@ -1,9 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const tslib_1 = require("tslib"); -var AgoraView_native_1 = require("./AgoraView.native"); -Object.defineProperty(exports, "AgoraView", { enumerable: true, get: function () { return AgoraView_native_1.default; } }); -var RtcEngine_native_1 = require("./RtcEngine.native"); -Object.defineProperty(exports, "RtcEngine", { enumerable: true, get: function () { return RtcEngine_native_1.default; } }); -tslib_1.__exportStar(require("./types"), exports); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/lib/index.js.map b/lib/index.js.map deleted file mode 100644 index f0f0ca6e3..000000000 --- a/lib/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,uDAAwD;AAAhD,6GAAA,OAAO,OAAa;AAC5B,uDAAwD;AAAhD,6GAAA,OAAO,OAAa;AAC5B,kDAAwB"} \ No newline at end of file diff --git a/lib/types.d.ts b/lib/types.d.ts deleted file mode 100644 index 82a32cdce..000000000 --- a/lib/types.d.ts +++ /dev/null @@ -1,335 +0,0 @@ -import { ViewProps } from 'react-native'; -/** - * ChannelMediaInfo - * @property channelName: string - * @property token: string - * @property uid: number - */ -export interface ChannelMediaInfo { - channelName: string; - token?: string; - uid?: number; -} -/** - * ChannelMediaConfiguration - * @property src: { - * @member channelName, - * @member token, - * @member uid, - * } - * @property channels: {@link Array} - */ -export interface ChannelMediaConfiguration { - src?: { - channelName: string; - token?: string; - uid?: number; - }; - channels: Array; -} -/** - * AgoraViewMode - * @mode hidden Uniformly scale the video until it fills the visible boundaries (cropped). One dimension of the video may have clipped contents. - * @mode FIT Uniformly scale the video until one of its dimension fits the boundary (zoomed to fit). Areas that are not filled due to the disparity in the aspect ratio are filled with black. - */ -export declare enum AgoraViewMode { - HIDDEN = 1, - FIT = 2 -} -/** - * AgoraUserInfo - * @property uid: number - * @property userAccount: string - */ -export interface AgoraUserInfo { - uid: number; - userAccount: string; -} -/** - * VideoEncoderConfig details - * @property width: number | The encoder video's width - * @property height: number | The encoder video's height - * @property bitrate: number | The encoder video's bitrate - * @property frameRate: number | The frameRate of encoder video - * @property orientationMode: number | The video orientation mode of the video - * @orientationMode value range is [0 is "mode adapative", 1 is "mode fixed landscape", 2 is "mode fixed portrait"] - */ -export interface VideoEncoderConfig { - width: number; - height: number; - bitrate: number; - frameRate: number; - orientationMode: number; -} -/** - * Option is used to {@link init} - * @member {@link appid} Sets the appid - * @member {@link channelProfile} Number channelProfile Sets the channel mode. 0 is communication mode, 1 is broadcasting mode - * @member {@link VideoEncoderConfig} sets video encoding config - * @member {@link dualStream} is optional parameter only for enable for detail see [more](https://docs.agora.io/en/Video/API%20Reference/oc/Classes/AgoraRtcEngineKit.html#//api/name/enableDualStreamMode) - * @member {@link mode} is optional sets only enable video / audio, 0 is audio mode, 1 is video mode - * @member {@link clientRole} is only work in live mode, 1 is host, 2 is audience - * @member {@link audioProfile} Sets audio profile to agora rtc sdk See more [details](https://docs.agora.io/en/Video/API%20Reference/oc/Constants/AgoraAudioProfile.html) - * @member {@link audioScenario} Sets audio scenario to agora rtc sdk more [details](https://docs.agora.io/en/Video/API%20Reference/oc/Constants/AgoraAudioScenario.html) - * @member {@link beauty} {@link BeautyOption} - * @member {@link voice} {@link VoiceDecorator} - */ -export interface Option { - appid: String; - channelProfile: number; - videoEncoderConfig: VideoEncoderConfig; - dualStream?: boolean; - mode?: number; - clientRole: number; - audioProfile: number; - audioScenario: number; - beauty?: BeautyOption; - voice?: VoiceDecorator; -} -/** - * VoiceDecorator is decorate local audio voice - * - * @description - * type 'reverbPreset' range values: [0 is "off", 1 is "popular", 2 is "rnb", 3 is "rock", 4 is "hiphop", 5 is "vocal concert", 6 is "KTV", 7 is "studio"] - * type 'changer' range values: [0 is "off", 1 is "old man", 2 is "baby boy", 3 is "baby girl", 4 is "zhubajie", 5 is "ethereal", 6 is "hulk"] - * @member type: string | the range values ['changer' | 'reverbPreset'] This property is the identifier for audio voice decorator - * @member value: number | the value for voice parameter option. - */ -export interface VoiceDecorator { - type: string; - value: number; -} -export interface PublisherConfig { - width: number; - height: number; - framerate: number; - bitrate: number; - defaultLayout: number; - lifeCycle: number; - pubishUrl: string; - rawStreamUrl: string; - extraInfo: String; - owner: boolean; -} -export interface BackgroundImage { - url: string; - x: number; - y: number; - width: number; - height: number; -} -export interface Size { - width: number; - height: number; -} -export interface TranscodingUser { - uid: number; - x: number; - y: number; - width: number; - height: number; - alpha: number; - zOrder: number; - audioChannel: number; -} -export interface Color { - red: number; - green: number; - blue: number; - alpha: number; -} -export declare enum VideoCodecProfile { - BASELINE = 66, - MAIN = 77, - HIGH = 100 -} -export declare enum AudioCodecProfile { - LC_AAC = 0, - HE_AAC = 1 -} -export declare enum AudioSampleRate { - TYPE_32000 = 32000, - TYPE_44100 = 44100, - TYPE_48000 = 48000 -} -/** - * AgoraChannelStereo - * @note Agora’s self-defined audio channel type. We recommend choosing ONE or TWO. Special players are required if you choose TRHEE, FOUR or FIVE: - */ -export declare enum AudioChannelStereo { - ONE = 1, - TWO = 2, - TRHEE = 3, - FOUR = 4, - FIVE = 5 -} -/** - * @member {@link size} {@link Size} - * @member {@link videoBitrate} integer number - * @member {@link videoFramerate} integer number - * @member {@link lowLatency} boolean - * @member {@link videoGop} number - * @member {@link videoCodecProfile} {@link VideoCodecProfile} - * @member {@link audioCodecProfile} {@link AudioCodecProfile} - * @member {@link audioSampleRate} {@link AudioSampleRate} - * @member {@link watermark} {@link BackgroundImage} - * @member {@link backgroundImage} {@link BackgroundImage} - * @member {@link backgroundColor} Standard RGB hex number: e.g. 0xffffff - * @member {@link audioBitrate} number - * @member {@link audioChannels} {@link AudioChannelStereo} - * @member {@link transcodingUsers} Array,{@link TranscodingUser}>, - * @member {@link transcodingExtraInfo} string - */ -export interface LiveTranscodingOption { - size: Size; - videoBitrate: number; - videoFramerate: number; - lowLatency: boolean; - videoGop: number; - videoCodecProfile: VideoCodecProfile; - audioCodecProfile: AudioCodecProfile; - audioSampleRate: AudioSampleRate; - watermark: BackgroundImage; - backgroundImage: BackgroundImage; - backgroundColor: number; - audioBitrate: number; - audioChannels: AudioChannelStereo; - transcodingUsers: Array; - transcodingExtraInfo: string; -} -export interface VideoOption { - uid: number; - renderMode: number; - reactTag: number; -} -export interface AudioRecordingOption { - filepath: String; - sampleRate: number; - quality: number; -} -export declare type Callback = (err: any, data: any) => T; -export declare type Nullable = T | null | undefined; -export declare type String = Nullable; -export declare type Number = Nullable | 0; -export interface AgoraViewProps extends ViewProps { - mode: number; - showLocalVideo: boolean; - remoteUid: number; - zOrderMediaOverlay: boolean; - [key: string]: any; -} -export interface DataStreamOption { - streamId: number; - ordered: boolean; - reliable: boolean; -} -export interface AudioMixingOption { - filepath: String; - loopback: boolean; - replace: boolean; - cycle: number; -} -export interface PlayEffectOption { - soundId: number; - filepath: String; - loopcount: number; - pitch: number; - pan: number; - gain: number; - publish: boolean; -} -export interface AudioFrameOption { - sampleRate: number; - channel: number; - mode: number; - samplesPerCall: number; -} -export interface MixedAudioFrameOption { - sampleRate: number; - samplesPerCall: number; -} -export interface ImageOption { - visibleInPreview: boolean; - positionInPortraitMode: { - x: number; - y: number; - width: number; - height: number; - }; - positionInLandscapeMode: { - x: number; - y: number; - width: number; - height: number; - }; -} -export interface VideoStreamOption { - uid: number; - streamType: number; -} -export interface DefaultVideoStreamOption { - streamType: number; -} -export interface InjectStreamOption { - url: String; - config: { - size: { - width: number; - height: number; - }; - videoGop: number; - videoBitrate: number; - videoFramerate: number; - audioBitrate: number; - audioSampleRate: number; - audioChannels: number; - }; -} -export interface RemoveInjectStreamOption { - url: String; -} -export interface PublishStreamOption { - url: String; - enable: boolean; -} -export interface RemovePublishStreamOption { - url: String; -} -export interface PositionOption { - x: number; - y: number; -} -/** - * BeautyOption is setBeautyEffectOptions's option parameter - * @property lighteningContrastLevel: integer | lightening contrast level and the value ranges is low: 0, normal: 1, high: 2 - * @property lighteningLevel: float | brightness level and the value ranges between 0.0 (original) and 1.0. - * @property smoothnessLevel: float | The sharpness level. The value ranges between 0.0 (original) and 1.0. This parameter is usually used to remove blemishes. - * @property rednessLevel: float | The redness level. The value ranges between 0.0 (original) and 1.0. This parameter adjusts the red saturation level. - */ -export interface BeautyOption { - lighteningContrastLevel: number; - lighteningLevel: number; - smoothnessLevel: number; - rednessLevel: number; -} -/** - * LastmileProbeConfig is startLastmileProbeTest's config parameter - * @property probeUplink: boolean | sets whether or not to test the uplink networks. some users, for example, the audience in a Live-broadcast channel, do not need such a test. true: enables the probe test. false: disables the probe test. - * @property probeDownlink: boolean | sets whether or not to probe the downlink network. true: enables the probe test. false: disables the probe test. - * @property expectedUplinkBitrate: integer | The expected maximum sending bitrate (Kbps) of the local user. The value ranges between 100 and 5000. We recommend setting this parameter according to the bitrate value set by setVideoEncoderConfiguration. - * @property expectedDownlinkBitrate: integer | The expected maximum receiving bitrate (Kbps) of the local user. The value ranges between 100 and 5000. - */ -export interface LastmileProbeConfig { - probeUplink: boolean; - probeDownlink: boolean; - expectedUplinkBitrate: number; - expectedDownlinkBitrate: number; -} -/** - * CameraCapturerConfiguration is setCameraCapturerConfiguration's config parameter - * @property preference: number | The Camera capture preference and the value range is [0 is "(default) self-adapts the camera output parameters to the system performance and network conditions to balance CPU consumption and video preview quality.", 1 is "prioritizes the system performance. The SDK chooses the dimension and frame rate of the local camera capture closest to those set by setVideoEncoderConfiguration.", 2 is "prioritizes the local preview quality. The SDK chooses higher camera output parameters to improve the local video preview quality. This option requires extra CPU and RAM usage for video pre-processing."] - */ -export interface CameraCapturerConfiguration { - preference: number; - cameraDirection: number; -} diff --git a/lib/types.js b/lib/types.js deleted file mode 100644 index 07d52eac6..000000000 --- a/lib/types.js +++ /dev/null @@ -1,44 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.AudioChannelStereo = exports.AudioSampleRate = exports.AudioCodecProfile = exports.VideoCodecProfile = exports.AgoraViewMode = void 0; -/** - * AgoraViewMode - * @mode hidden Uniformly scale the video until it fills the visible boundaries (cropped). One dimension of the video may have clipped contents. - * @mode FIT Uniformly scale the video until one of its dimension fits the boundary (zoomed to fit). Areas that are not filled due to the disparity in the aspect ratio are filled with black. - */ -var AgoraViewMode; -(function (AgoraViewMode) { - AgoraViewMode[AgoraViewMode["HIDDEN"] = 1] = "HIDDEN"; - AgoraViewMode[AgoraViewMode["FIT"] = 2] = "FIT"; -})(AgoraViewMode = exports.AgoraViewMode || (exports.AgoraViewMode = {})); -; -var VideoCodecProfile; -(function (VideoCodecProfile) { - VideoCodecProfile[VideoCodecProfile["BASELINE"] = 66] = "BASELINE"; - VideoCodecProfile[VideoCodecProfile["MAIN"] = 77] = "MAIN"; - VideoCodecProfile[VideoCodecProfile["HIGH"] = 100] = "HIGH"; -})(VideoCodecProfile = exports.VideoCodecProfile || (exports.VideoCodecProfile = {})); -var AudioCodecProfile; -(function (AudioCodecProfile) { - AudioCodecProfile[AudioCodecProfile["LC_AAC"] = 0] = "LC_AAC"; - AudioCodecProfile[AudioCodecProfile["HE_AAC"] = 1] = "HE_AAC"; -})(AudioCodecProfile = exports.AudioCodecProfile || (exports.AudioCodecProfile = {})); -var AudioSampleRate; -(function (AudioSampleRate) { - AudioSampleRate[AudioSampleRate["TYPE_32000"] = 32000] = "TYPE_32000"; - AudioSampleRate[AudioSampleRate["TYPE_44100"] = 44100] = "TYPE_44100"; - AudioSampleRate[AudioSampleRate["TYPE_48000"] = 48000] = "TYPE_48000"; -})(AudioSampleRate = exports.AudioSampleRate || (exports.AudioSampleRate = {})); -/** - * AgoraChannelStereo - * @note Agora’s self-defined audio channel type. We recommend choosing ONE or TWO. Special players are required if you choose TRHEE, FOUR or FIVE: - */ -var AudioChannelStereo; -(function (AudioChannelStereo) { - AudioChannelStereo[AudioChannelStereo["ONE"] = 1] = "ONE"; - AudioChannelStereo[AudioChannelStereo["TWO"] = 2] = "TWO"; - AudioChannelStereo[AudioChannelStereo["TRHEE"] = 3] = "TRHEE"; - AudioChannelStereo[AudioChannelStereo["FOUR"] = 4] = "FOUR"; - AudioChannelStereo[AudioChannelStereo["FIVE"] = 5] = "FIVE"; -})(AudioChannelStereo = exports.AudioChannelStereo || (exports.AudioChannelStereo = {})); -//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/lib/types.js.map b/lib/types.js.map deleted file mode 100644 index 50dcb8327..000000000 --- a/lib/types.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":";;;AA+BA;;;;GAIG;AACH,IAAY,aAGX;AAHD,WAAY,aAAa;IACvB,qDAAU,CAAA;IACV,+CAAO,CAAA;AACT,CAAC,EAHW,aAAa,GAAb,qBAAa,KAAb,qBAAa,QAGxB;AAUA,CAAC;AAuGF,IAAY,iBAIX;AAJD,WAAY,iBAAiB;IAC3B,kEAAa,CAAA;IACb,0DAAS,CAAA;IACT,2DAAU,CAAA;AACZ,CAAC,EAJW,iBAAiB,GAAjB,yBAAiB,KAAjB,yBAAiB,QAI5B;AAED,IAAY,iBAGX;AAHD,WAAY,iBAAiB;IAC3B,6DAAU,CAAA;IACV,6DAAU,CAAA;AACZ,CAAC,EAHW,iBAAiB,GAAjB,yBAAiB,KAAjB,yBAAiB,QAG5B;AAED,IAAY,eAIX;AAJD,WAAY,eAAe;IACzB,qEAAkB,CAAA;IAClB,qEAAkB,CAAA;IAClB,qEAAkB,CAAA;AACpB,CAAC,EAJW,eAAe,GAAf,uBAAe,KAAf,uBAAe,QAI1B;AAED;;;GAGG;AACH,IAAY,kBAMX;AAND,WAAY,kBAAkB;IAC5B,yDAAO,CAAA;IACP,yDAAO,CAAA;IACP,6DAAS,CAAA;IACT,2DAAQ,CAAA;IACR,2DAAQ,CAAA;AACV,CAAC,EANW,kBAAkB,GAAlB,0BAAkB,KAAlB,0BAAkB,QAM7B"} \ No newline at end of file diff --git a/package.json b/package.json index d3176f136..eb6e575cc 100644 --- a/package.json +++ b/package.json @@ -1,16 +1,16 @@ { "name": "react-native-agora", - "version": "2.9.1-alpha.7", + "version": "3.0.1-rc.1", "description": "React Native around the Agora RTC SDKs for Android and iOS agora", "summary": "agora native sdk for react-native", "main": "lib/index.js", "types": "lib/index.d.ts", "scripts": { - "pu": "npm publish", - "test": "echo \"Error: no test specified\" && exit 1", - "lint": "tslint", - "build": "tsc", - "doc": "typedoc --out docs/api ./src" + "build": "rm -rf lib && tsc", + "doc": "typedoc --out docs/api ./src", + "test": "jest", + "lint": "eslint . --ext .js,.jsx,.ts,.tsx", + "prepublish": "npm run build" }, "repository": { "type": "git", @@ -26,7 +26,7 @@ "video", "react-native-video" ], - "author": "syanbo", + "author": "luxuhui", "authors": [ "https://github.com/syanbo/react-native-agora/graphs/contributors" ], @@ -36,42 +36,34 @@ }, "homepage": "https://github.com/syanbo/react-native-agora#readme", "peerDependencies": { - "react": "16.3.1", - "react-native": ">=0.55.0" + "react": ">=16.8.3", + "react-native": ">=0.59.9" }, "devDependencies": { - "@types/jest": "^23.3.13", - "@types/react": "^16.3.0", - "@types/react-native": "^0.55.0", - "@types/react-test-renderer": "^16.0.3", - "react": "16.3.1", - "react-native": "0.55.0", - "react-native-typescript-transformer": "^1.2.11", - "ts-jest": "^23.10.5", - "tslint": "^5.12.1", - "typedoc": "0.15.0", - "typedoc-plugin-no-inherit": "^1.1.9", - "typescript": "^3.2.4" + "@babel/core": "^7.6.2", + "@babel/runtime": "^7.6.2", + "@react-native-community/eslint-config": "^0.0.5", + "@types/jest": "^24.0.24", + "@types/react-native": "^0.60.25", + "@types/react-test-renderer": "16.9.1", + "@typescript-eslint/eslint-plugin": "^2.12.0", + "@typescript-eslint/parser": "^2.12.0", + "babel-jest": "^24.9.0", + "eslint": "^6.5.1", + "jest": "^24.9.0", + "metro-react-native-babel-preset": "^0.56.0", + "react-test-renderer": "16.9.0", + "typescript": "^3.7.3" }, "jest": { "preset": "react-native", "moduleFileExtensions": [ "ts", "tsx", - "js" - ], - "transform": { - "^.+\\.(js)$": "/node_modules/babel-jest", - "\\.(ts|tsx)$": "/node_modules/ts-jest/preprocessor.js" - }, - "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$", - "testPathIgnorePatterns": [ - "\\.snap$", - "/node_modules/" - ], - "cacheDirectory": ".jest/cache" - }, - "dependencies": { - "tslib": "^1.9.3" + "js", + "jsx", + "json", + "node" + ] } } diff --git a/react-native-agora.podspec b/react-native-agora.podspec index 28d45ab24..0f0c25e32 100644 --- a/react-native-agora.podspec +++ b/react-native-agora.podspec @@ -9,11 +9,13 @@ Pod::Spec.new do |s| s.homepage = package['homepage'] s.license = package['license'] s.authors = package["authors"] - s.platform = :ios, "8.0" + s.platform = :ios, "9.0" + s.static_framework = true + s.swift_version = "5.0" s.source = { :git => package["repository"]["url"] } - s.source_files = 'ios/RCTAgora/*.{h,m}' + s.source_files = 'ios/RCTAgora/**/*.{h,m,swift}' s.dependency 'React' - s.dependency "AgoraRtcEngine_iOS", "2.9.1" + s.dependency "AgoraRtcEngine_iOS_Crypto", "3.0.1.1" end diff --git a/samples/README.md b/samples/README.md index c9dea3b70..48a05bbb6 100644 --- a/samples/README.md +++ b/samples/README.md @@ -2,4 +2,4 @@ | name | description | | :-------------: | :-------------: | -| [agora-rn-quickstart](https://github.com/agoraio-community/agora-rn-quickstart) | react-native-agora demo for beginner | +| [Agora-RN-QuickStart](https://github.com/AgoraIO-Community/Agora-RN-Quickstart/tree/sdk-v3) | react-native-agora demo for beginner | diff --git a/src/AgoraView.native.tsx b/src/AgoraView.native.tsx deleted file mode 100644 index cd044b2e0..000000000 --- a/src/AgoraView.native.tsx +++ /dev/null @@ -1,65 +0,0 @@ -import React from 'react'; -import { - requireNativeComponent, - Platform -} from 'react-native' - -import { - AgoraViewProps, -} from "./types"; - -/** - * Import RCTAgoraView from native binding. - * - * This @object is used to bridge native layer between react layer. - */ - -const RCTAgoraView = requireNativeComponent("RCTAgoraVideoView"); - -/** - * AgoraView is the render layer for rendering video stream - * - * This class is used to rendering native sdk stream - * @props {@link AgoraViewProps} - * - * @descrption AgoraViewProps has four properties. - * @property mode: {@link AgoraViewMode}, this property will setup video render mode. You could see more [details](https://docs.agora.io/en/Interactive%20Broadcast/API%20Reference/java/classio_1_1agora_1_1rtc_1_1_rtc_engine.html#ac08882c4d0ec47b329900df169493673) - * @property showLocalVideo: boolean, this property will render local video, NOTICE: IF YOU SET showLocalVideo YOU CANNOT SET remoteUid - * @property remoteUid: number, this property will render video with remote uid, NOTICE: IF YOU SET remoteUid YOU CANNOT SET showLocalVideo - * @property zOrderMediaOverlay: boolean, this property will working for android side and it likes zIndex behaviour on web side. - * - * @noInheritDoc - */ -export default class AgoraView extends React.Component { - /** - * render - * - * It would render view for VideoStream - */ - public render(): JSX.Element { - return ( - - ) - } - - /** - * getHTMLProps - * - * get agora view props - */ - private getHTMLProps(): AgoraViewProps { - let htmlProps = {} as AgoraViewProps; - for (let key in this.props) { - htmlProps[key] = this.props[key]; - } - - // convert uint32 to int32 for android - if (Platform.OS === 'android') { - const int32 = new Int32Array(1); - int32[0] = htmlProps.remoteUid; - htmlProps.remoteUid = int32[0] - } - return htmlProps; - } -} - diff --git a/src/RtcChannel.native.ts b/src/RtcChannel.native.ts new file mode 100644 index 000000000..a9c1e8d14 --- /dev/null +++ b/src/RtcChannel.native.ts @@ -0,0 +1,716 @@ +import {NativeEventEmitter, NativeModules} from "react-native"; +import { + ChannelMediaOptions, + ChannelMediaRelayConfiguration, + ClientRole, + ConnectionStateType, + EncryptionMode, + LiveInjectStreamConfig, + LiveTranscoding, + String, + UserPriority, + VideoStreamType +} from "./Types"; +import {Listener, RtcChannelEvents, Subscription} from "./RtcEvents"; + +const {AgoraRtcChannelModule} = NativeModules; +const Prefix = AgoraRtcChannelModule.prefix +const RtcChannelEvent = new NativeEventEmitter(AgoraRtcChannelModule); + +const channels = new Map(); + +/** + * The RtcChannel class. + */ +export default class RtcChannel implements RtcAudioInterface, RtcVideoInterface, RtcVoicePositionInterface, + RtcPublishStreamInterface, RtcMediaRelayInterface, RtcDualStreamInterface, RtcFallbackInterface, + RtcMediaMetadataInterface, RtcEncryptionInterface, RtcInjectStreamInterface, RtcStreamMessageInterface { + + private readonly _channelId: string; + private _listeners = new Map>(); + + private constructor(channelId: string) { + this._channelId = channelId; + } + + /** + * Creates and gets an RtcChannel instance. + * @see RtcChannel + * To join more than one channel, call this method multiple times to create as many RtcChannel instances as needed, and call the joinChannel method of each created RtcChannel object. + * @see RtcChannel.joinChannel + * After joining multiple channels, you can simultaneously subscribe to streams of all the channels, but publish a stream in only one channel at one time. + * @param channelId The unique channel name for the AgoraRTC session in the string format. The string length must be less than 64 bytes. This parameter does not have a default value. You must set it. Do not set it as the empty string "". Otherwise, the SDK returns Refused(-5). Supported character scopes are: + * @see ErrorCode.Refused + * - All lowercase English letters: a to z. + * - All uppercase English letters: A to Z. + * - All numeric characters: 0 to 9. + * - The space character. + * - Punctuation characters and other symbols, including: "!", "#", "$", "%", "&", "(", ")", "+", "-", ":", ";", "<", "=", ".", ">", "?", "@", "[", "]", "^", "_", " {", "}", "|", "~", ",". + */ + static async create(channelId: string): Promise { + if (channels.get(channelId)) return channels.get(channelId) as RtcChannel; + await AgoraRtcChannelModule.create(channelId); + channels.set(channelId, new RtcChannel(channelId)); + return channels.get(channelId) as RtcChannel + } + + /** + * Destroys all RtcChannel instance. + * @see RtcChannel + */ + static destroyAll() { + channels.forEach(async (value, key) => { + await value.destroy() + }); + channels.clear() + } + + /** + * Destroys the RtcChannel instance. + * @see RtcChannel + */ + destroy(): Promise { + this.removeAllListeners(); + channels.delete(this._channelId); + return AgoraRtcChannelModule.destroy(this._channelId) + } + + /** + * Adds the channel event handler. + * After setting the channel event handler, you can listen for channel events and receive the statistics of the corresponding RtcChannel instance. + * @param event The event type. + * @param listener The event handler. + */ + addListener(event: EventType, listener: RtcChannelEvents[EventType]): Subscription { + const callback = (res: any) => { + const {channelId, data} = res; + if (channelId === this._channelId) { + // @ts-ignore + listener(...data) + } + }; + let map = this._listeners.get(event); + if (map === undefined) { + map = new Map(); + this._listeners.set(event, map) + } + RtcChannelEvent.addListener(Prefix + event, callback); + map.set(listener, callback); + return { + remove: () => { + this.removeListener(event, listener) + } + } + } + + /** + * Removes the channel event handler. + * For callback events that you only want to listen for once, call this method to remove it after you have received them. + * @param event The event type. + * @param listener The event handler. + */ + removeListener(event: EventType, listener: RtcChannelEvents[EventType]) { + const map = this._listeners.get(event); + if (map === undefined) return; + RtcChannelEvent.removeListener(Prefix + event, map.get(listener) as Listener); + map.delete(listener) + } + + /** + * Removes all of the engine event handlers. + * @param event The event type. + */ + removeAllListeners(event?: EventType) { + if (event === undefined) { + this._listeners.forEach((value, key) => { + RtcChannelEvent.removeAllListeners(Prefix + key); + }); + this._listeners.clear(); + return + } + RtcChannelEvent.removeAllListeners(Prefix + event); + this._listeners.delete(event as string) + } + + /** + * Sets the role of a user. + * This method sets the role of a user, such as a host or an audience. In a Live-Broadcast channel, only a broadcaster can call the publish method in the RtcChannel class. + * @see RtcChannel.publish + * A successful call of this method triggers the following callbacks: + * - The local client: onClientRoleChanged. + * @see RtcChannelEvents.ClientRoleChanged + * - The remote client: onUserJoined or onUserOffline(BecomeAudience). + * @see RtcChannelEvents.UserJoined + * @see RtcChannelEvents.UserOffline + * @see UserOfflineReason.BecomeAudience + * @param role The role of the user. + * @see ClientRole + */ + setClientRole(role: ClientRole): Promise { + return AgoraRtcChannelModule.setClientRole(this._channelId, role) + } + + /** + * Joins the channel with a user ID. + * Note + * - If you are already in a channel, you cannot rejoin it with the same uid. + * - We recommend using different UIDs for different channels. + * - If you want to join the same channel from different devices, ensure that the UIDs in all devices are different. + * - Ensure that the app ID you use to generate the token is the same with the app ID used when creating the RtcEngine instance. + * @see RtcEngine + * @param token The token generated at your server. + * - In situations not requiring high security: You can use the temporary token generated at Console. For details, see Get a temporary token. + * - In situations requiring high security: Set it as the token generated at your server. For details, see Generate a token. + * @param optionalInfo Additional information about the channel. This parameter can be set as null. Other users in the channel do not receive this information. + * @param optionalUid The user ID. A 32-bit unsigned integer with a value ranging from 1 to (232-1). This parameter must be unique. If uid is not assigned (or set as 0), the SDK assigns a uid and reports it in the onJoinChannelSuccess callback. The app must maintain this user ID. + * @param options The channel media options. + * @see ChannelMediaOptions + */ + joinChannel(token: String, optionalInfo: String, optionalUid: number, options: ChannelMediaOptions): Promise { + return AgoraRtcChannelModule.joinChannel(this._channelId, token, optionalInfo, optionalUid, options) + } + + /** + * Joins a channel with the user account. + * Note + * - If you are already in a channel, you cannot rejoin it with the same uid. + * - We recommend using different user accounts for different channels. + * - If you want to join the same channel from different devices, ensure that the user accounts in all devices are different. + * - Ensure that the app ID you use to generate the token is the same with the app ID used when creating the RtcEngine instance. + * @see RtcEngine + * @param token The token generated at your server. + * - In situations not requiring high security: You can use the temporary token generated at Console. For details, see Get a temporary token. + * - In situations requiring high security: Set it as the token generated at your server. For details, see Generate a token. + * @param userAccount The user account. The maximum length of this parameter is 255 bytes. Ensure that you set this parameter and do not set it as null. + * - All lowercase English letters: a to z. + * - All uppercase English letters: A to Z. + * - All numeric characters: 0 to 9. + * - The space character. + * - Punctuation characters and other symbols, including: "!", "#", "$", "%", "&", "(", ")", "+", "-", ":", ";", "<", "=", ".", ">", "?", "@", "[", "]", "^", "_", " {", "}", "|", "~", ",". + * @param options The channel media options. + * @see ChannelMediaOptions + */ + joinChannelWithUserAccount(token: String, userAccount: string, options: ChannelMediaOptions): Promise { + return AgoraRtcChannelModule.joinChannelWithUserAccount(this._channelId, token, userAccount, options) + } + + /** + * Leaves the current channel. + * A successful leaveChannel method call triggers the following callbacks: + * - The local client: onLeaveChannel. + * @see RtcChannelEvents.LeaveChannel + * - The remote client: onUserOffline, if the user leaving the channel is in a Communication channel, or is a broadcaster in a Live-Broadcast channel. + * @see RtcChannelEvents.UserOffline + */ + leaveChannel(): Promise { + return AgoraRtcChannelModule.leaveChannel(this._channelId) + } + + /** + * Renews the token when the current token expires. + * In the following situations, the SDK decides that the current token has expired: + * - The SDK triggers the onTokenPrivilegeWillExpire callback, or + * @see RtcChannelEvents.TokenPrivilegeWillExpire + * - The onConnectionStateChanged callback reports the TokenExpired(9) error. + * @see RtcChannelEvents.ConnectionStateChanged + * @see ConnectionChangedReason.TokenExpired + * You should get a new token from your server and call this method to renew it. Failure to do so results in the SDK disconnecting from the Agora server. + * @param token The new token. + */ + renewToken(token: string): Promise { + return AgoraRtcChannelModule.renewToken(this._channelId, token) + } + + /** + * Gets the connection state of the SDK. + */ + getConnectionState(): Promise { + return AgoraRtcChannelModule.getConnectionState(this._channelId) + } + + /** + * Publishes the local stream to the channel. + * You must keep the following restrictions in mind when calling this method. Otherwise, the SDK returns the Refused(-5): + * @see ErrorCode.Refused + * - This method publishes one stream only to the channel corresponding to the current RtcChannel instance. + * - In a Live-Broadcast channel, only a broadcaster can call this method. To switch the client role, call setClientRole of the current RtcChannel instance. + * @see RtcChannel.setClientRole + * - You can publish a stream to only one channel at a time. For details, see the advanced guide Join Multiple Channels. + */ + publish(): Promise { + return AgoraRtcChannelModule.publish(this._channelId) + } + + /** + * Stops publishing a stream to the channel. + * If you call this method in a channel where you are not publishing streams, the SDK returns Refused(-5). + * @see ErrorCode.Refused + */ + unpublish(): Promise { + return AgoraRtcChannelModule.unpublish(this._channelId) + } + + /** + * Gets the current call ID. + */ + getCallId(): Promise { + return AgoraRtcChannelModule.getCallId(this._channelId) + } + + adjustUserPlaybackSignalVolume(uid: number, volume: number): Promise { + return AgoraRtcChannelModule.adjustUserPlaybackSignalVolume(this._channelId, uid, volume) + } + + muteRemoteAudioStream(uid: number, muted: boolean): Promise { + return AgoraRtcChannelModule.muteRemoteAudioStream(this._channelId, uid, muted) + } + + muteAllRemoteAudioStreams(muted: boolean): Promise { + return AgoraRtcChannelModule.muteAllRemoteAudioStreams(this._channelId, muted) + } + + setDefaultMuteAllRemoteAudioStreams(muted: boolean): Promise { + return AgoraRtcChannelModule.setDefaultMuteAllRemoteAudioStreams(this._channelId, muted) + } + + muteAllRemoteVideoStreams(muted: boolean): Promise { + return AgoraRtcChannelModule.muteAllRemoteVideoStreams(this._channelId, muted) + } + + muteRemoteVideoStream(uid: number, muted: boolean): Promise { + return AgoraRtcChannelModule.muteRemoteVideoStream(this._channelId, uid, muted) + } + + setDefaultMuteAllRemoteVideoStreams(muted: boolean): Promise { + return AgoraRtcChannelModule.setDefaultMuteAllRemoteVideoStreams(this._channelId, muted) + } + + setRemoteVoicePosition(uid: number, pan: number, gain: number): Promise { + return AgoraRtcChannelModule.setRemoteVoicePosition(this._channelId, uid, pan, gain); + } + + addPublishStreamUrl(url: string, transcodingEnabled: boolean): Promise { + return AgoraRtcChannelModule.addPublishStreamUrl(this._channelId, url, transcodingEnabled); + } + + removePublishStreamUrl(url: string): Promise { + return AgoraRtcChannelModule.removePublishStreamUrl(this._channelId, url); + } + + setLiveTranscoding(transcoding: LiveTranscoding): Promise { + return AgoraRtcChannelModule.setLiveTranscoding(this._channelId, transcoding); + } + + startChannelMediaRelay(channelMediaRelayConfiguration: ChannelMediaRelayConfiguration): Promise { + return AgoraRtcChannelModule.startChannelMediaRelay(this._channelId, channelMediaRelayConfiguration); + } + + stopChannelMediaRelay(): Promise { + return AgoraRtcChannelModule.stopChannelMediaRelay(this._channelId); + } + + updateChannelMediaRelay(channelMediaRelayConfiguration: ChannelMediaRelayConfiguration): Promise { + return AgoraRtcChannelModule.updateChannelMediaRelay(this._channelId, channelMediaRelayConfiguration); + } + + setRemoteDefaultVideoStreamType(streamType: VideoStreamType): Promise { + return AgoraRtcChannelModule.setRemoteDefaultVideoStreamType(this._channelId, streamType); + } + + setRemoteVideoStreamType(uid: number, streamType: VideoStreamType): Promise { + return AgoraRtcChannelModule.setRemoteVideoStreamType(this._channelId, uid, streamType); + } + + setRemoteUserPriority(uid: number, userPriority: UserPriority): Promise { + return AgoraRtcChannelModule.setRemoteUserPriority(this._channelId, uid, userPriority); + } + + registerMediaMetadataObserver(): Promise { + return AgoraRtcChannelModule.registerMediaMetadataObserver(this._channelId); + } + + sendMetadata(metadata: string): Promise { + return AgoraRtcChannelModule.sendMetadata(this._channelId, metadata); + } + + setMaxMetadataSize(size: number): Promise { + return AgoraRtcChannelModule.setMaxMetadataSize(this._channelId, size); + } + + unregisterMediaMetadataObserver(): Promise { + return AgoraRtcChannelModule.unregisterMediaMetadataObserver(this._channelId); + } + + setEncryptionMode(encryptionMode: EncryptionMode): Promise { + return AgoraRtcChannelModule.setEncryptionMode(this._channelId, encryptionMode); + } + + setEncryptionSecret(secret: string): Promise { + return AgoraRtcChannelModule.setEncryptionSecret(this._channelId, secret); + } + + addInjectStreamUrl(url: string, config: LiveInjectStreamConfig): Promise { + return AgoraRtcChannelModule.addInjectStreamUrl(this._channelId, url, config); + } + + removeInjectStreamUrl(url: string): Promise { + return AgoraRtcChannelModule.removeInjectStreamUrl(this._channelId, url); + } + + createDataStream(reliable: boolean, ordered: boolean): Promise { + return AgoraRtcChannelModule.createDataStream(this._channelId, reliable, ordered); + } + + sendStreamMessage(streamId: number, message: string): Promise { + return AgoraRtcChannelModule.sendStreamMessage(this._channelId, streamId, message); + } +} + +interface RtcAudioInterface { + /** + * Adjusts the playback volume of a specified remote user. + * You can call this method as many times as necessary to adjust the playback volume of different remote users, or to repeatedly adjust the playback volume of the same remote user. + * Note + * - Call this method after joining a channel. + * - The playback volume here refers to the mixed volume of a specified remote user. + * - This method can only adjust the playback volume of one specified remote user at a time. To adjust the playback volume of different remote users, call the method as many times, once for each remote user. + * @param uid ID of the remote user. + * @param volume The playback volume of the specified remote user. The value ranges from 0 to 100: + * - 0: Mute. + * - 100: The original volume. + */ + adjustUserPlaybackSignalVolume(uid: number, volume: number): Promise; + + /** + * Stops/Resumes receiving the audio stream of the specified user. + * @param uid ID of the remote user whose audio stream you want to mute. + * @param muted Determines whether to receive/stop receiving the audio stream of the specified user: + * - true: Stop receiving the audio stream of the user. + * - false: (Default) Receive the audio stream of the user. + */ + muteRemoteAudioStream(uid: number, muted: boolean): Promise; + + /** + * Stops/Resumes receiving all remote audio streams. + * @param muted Determines whether to receive/stop receiving all remote audio streams: + * - true: Stop receiving all remote audio streams. + * - false: (Default) Receive all remote audio streams. + */ + muteAllRemoteAudioStreams(muted: boolean): Promise; + + /** + * Sets whether to receive all remote audio streams by default. + * @param muted Determines whether to receive/stop receiving all remote audio streams by default: + * - true: Stop receiving all remote audio streams by default. + * - false: (Default) Receive all remote audio streams by default. + */ + setDefaultMuteAllRemoteAudioStreams(muted: boolean): Promise; +} + +interface RtcVideoInterface { + /** + * Stops/Resumes receiving the video stream of the specified user. + * @param uid ID of the remote user whose video stream you want to mute. + * @param muted Determines whether to receive/stop receiving the video stream of the specified user: + * - true: Stop receiving the video stream of the user. + * - false: (Default) Receive the video stream of the user. + */ + muteRemoteVideoStream(uid: number, muted: boolean): Promise; + + /** + * Stops/Resumes receiving all remote video streams. + * @param muted Determines whether to receive/stop receiving all remote video streams: + * - true: Stop receiving all remote video streams. + * - false: (Default) Receive all remote video streams. + */ + muteAllRemoteVideoStreams(muted: boolean): Promise; + + /** + * Sets whether to receive all remote video streams by default. + * @param muted Determines whether to receive/stop receiving all remote video streams by default: + * - true: Stop receiving all remote video streams by default. + * - false: (Default) Receive all remote video streams by default. + */ + setDefaultMuteAllRemoteVideoStreams(muted: boolean): Promise; +} + +interface RtcVoicePositionInterface { + /** + * Sets the sound position of a remote user. + * When the local user calls this method to set the sound position of a remote user, the sound difference between the left and right channels allows the local user to track the real-time position of the remote user, creating a real sense of space. This method applies to massively multiplayer online games, such as Battle Royale games. + * Note + * - For this method to work, enable stereo panning for remote users by calling the enableSoundPositionIndication method before joining a channel. + * @see RtcEngine.enableSoundPositionIndication + * - This method requires hardware support. For the best sound positioning, we recommend using a stereo headset. + * @param uid The ID of the remote user. + * @param pan The sound position of the remote user. The value ranges from -1.0 to 1.0: + * - 0.0: The remote sound comes from the front. + * - -1.0: The remote sound comes from the left. + * - 1.0: The remote sound comes from the right. + * @param gain Gain of the remote user. The value ranges from 0.0 to 100.0. The default value is 100.0 (the original gain of the remote user). The smaller the value, the less the gain. + */ + setRemoteVoicePosition(uid: number, pan: number, gain: number): Promise; +} + +interface RtcPublishStreamInterface { + /** + * Sets the video layout and audio settings for CDN live. + * The SDK triggers the onTranscodingUpdated callback when you call this method to update the LiveTranscodingclass. If you call this method to set the LiveTranscoding class for the first time, the SDK does not trigger the onTranscodingUpdated callback. + * @see RtcChannelEvents.TranscodingUpdated + * Note + * - Ensure that you enable the RTMP Converter service before using this function. See Prerequisites. + * - Ensure that the user joins a channel before calling this method. + * - This method can only be called by a broadcaster in a Live-Broadcast channel. + * - Ensure that you call this method before calling the addPublishStreamUrl method. + * @see RtcChannel.addPublishStreamUrl + * @param transcoding Sets the CDN live audio/video transcoding settings. + * @see LiveTranscoding + */ + setLiveTranscoding(transcoding: LiveTranscoding): Promise; + + /** + * Publishes the local stream to the CDN. + * This method call triggers the onRtmpStreamingStateChanged callback on the local client to report the state of adding a local stream to the CDN. + * @see RtcChannelEvents.RtmpStreamingStateChanged + * Note + * - Ensure that you enable the RTMP Converter service before using this function. See Prerequisites. + * - Ensure that the user joins a channel before calling this method. + * - This method can only be called by a broadcaster in a Live-Broadcast channel. + * - This method adds only one stream HTTP/HTTPS URL address each time it is called. + * @param url The CDN streaming URL in the RTMP format. The maximum length of this parameter is 1024 bytes. The URL address must not contain special characters, such as Chinese language characters. + * @param transcodingEnabled Sets whether transcoding is enabled/disabled. If you set this parameter as true, ensure that you call the setLiveTranscoding method before this method. + * @see RtcChannel.setLiveTranscoding + * - true: Enable transcoding. To transcode the audio or video streams when publishing them to CDN live, often used for combining the audio and video streams of multiple broadcasters in CDN live. + * - false: Disable transcoding. + */ + addPublishStreamUrl(url: string, transcodingEnabled: boolean): Promise; + + /** + * Removes an RTMP stream from the CDN. + * This method removes the RTMP URL address (added by addPublishStreamUrl) from a CDN live stream. The SDK reports the result of this method call in the onRtmpStreamingStateChanged callback. + * @see RtcChannel.addPublishStreamUrl + * @see RtcChannelEvents.RtmpStreamingStateChanged + * Note + * - Ensure that you enable the RTMP Converter service before using this function. See Prerequisites. + * - This method can only be called by a broadcaster in a Live-Broadcast channel. + * - This method removes only one stream HTTP/HTTPS URL address each time it is called. + * @param url The RTMP URL address to be removed. The maximum length of this parameter is 1024 bytes. The URL address must not contain special characters, such as Chinese language characters. + */ + removePublishStreamUrl(url: string): Promise; +} + +interface RtcMediaRelayInterface { + /** + * Starts to relay media streams across channels. + * After a successful method call, the SDK triggers the onChannelMediaRelayStateChanged and onChannelMediaRelayEvent callbacks, and these callbacks report the state and events of the media stream relay. + * @see RtcChannelEvents.ChannelMediaRelayStateChanged + * @see RtcChannelEvents.ChannelMediaRelayEvent + * - If the onChannelMediaRelayStateChanged callback reports Running(2) and None(0), and the onChannelMediaRelayEvent callback reports SentToDestinationChannel(4), the SDK starts relaying media streams between the original and the destination channel. + * @see ChannelMediaRelayState.Running + * @see ChannelMediaRelayError.None + * @see ChannelMediaRelayEvent.SentToDestinationChannel + * - If the onChannelMediaRelayStateChanged callback returns Failure(3), an exception occurs during the media stream relay. + * @see ChannelMediaRelayState.Failure + * Note + * - Call this method after joining the channel. + * - This method can only be called by a broadcaster in a Live-Broadcast channel. + * - After a successful method call, if you want to call this method again, ensure that you call the stopChannelMediaRelay method to quit the current relay. + * @see RtcChannel.stopChannelMediaRelay + * @param channelMediaRelayConfiguration The configuration of the media stream relay. + * @see ChannelMediaRelayConfiguration + */ + startChannelMediaRelay(channelMediaRelayConfiguration: ChannelMediaRelayConfiguration): Promise; + + /** + * Updates the channels for media relay. + * After the channel media relay starts, if you want to relay the media stream to more channels, or leave the current relay channel, you can call the updateChannelMediaRelay method. + * After a successful method call, the SDK triggers the onChannelMediaRelayEvent callback with the UpdateDestinationChannel(7) state code. + * @see RtcChannelEvents.ChannelMediaRelayEvent + * @see ChannelMediaRelayEvent.UpdateDestinationChannel + * Note + * - Call this method after the startChannelMediaRelay method to update the destination channel. + * @see RtcChannel.startChannelMediaRelay + * - This method supports adding at most four destination channels in the relay. + * @param channelMediaRelayConfiguration The media stream relay configuration. + * @see ChannelMediaRelayConfiguration + */ + updateChannelMediaRelay(channelMediaRelayConfiguration: ChannelMediaRelayConfiguration): Promise; + + /** + * Stops the media stream relay. + * Once the relay stops, the broadcaster quits all the destination channels. + * After a successful method call, the SDK triggers the onChannelMediaRelayStateChanged callback. If the callback reports Idle(0) and None(0), the broadcaster successfully stops the relay. + * @see RtcChannelEvents.ChannelMediaRelayStateChanged + * @see ChannelMediaRelayState.Idle + * @see ChannelMediaRelayError.None + * Note + * - If the method call fails, the SDK triggers the onChannelMediaRelayStateChanged callback with the ServerNoResponse(2) or ServerConnectionLost(8) state code. You can leave the channel using leaveChannel, and the media stream relay automatically stops. + * @see RtcChannelEvents.ChannelMediaRelayStateChanged + * @see ChannelMediaRelayError.ServerNoResponse + * @see ChannelMediaRelayError.ServerConnectionLost + * @see RtcChannel.leaveChannel + */ + stopChannelMediaRelay(): Promise; +} + +interface RtcDualStreamInterface { + /** + * Sets the video stream type of the remote video stream when the remote user sends dual streams. + * This method allows the app to adjust the corresponding video-stream type based on the size of the video window to reduce the bandwidth and resources. + * - If the remote user enables the dual-stream mode by calling the enableDualStreamMode method, the SDK receives the high-video stream by default. You can use this method to switch to the low-video stream. + * @see RtcEngine.enableDualStreamMode + * - If dual-stream mode is not enabled, the SDK receives the high-stream video by default. + * By default, the aspect ratio of the low-video stream is the same as the high-video stream. Once the resolution of the high-video stream is set, the system automatically sets the resolution, frame rate, and bitrate of the low-video stream. + * @param uid ID of the remote user sending the video stream. + * @param streamType Sets the video-stream type. + * @see VideoStreamType + */ + setRemoteVideoStreamType(uid: number, streamType: VideoStreamType): Promise; + + /** + * Sets the default video-stream type of the remote video stream when the remote user sends dual streams. + * @param streamType Sets the default video-stream type. + * @see VideoStreamType + */ + setRemoteDefaultVideoStreamType(streamType: VideoStreamType): Promise; +} + +interface RtcFallbackInterface { + /** + * Sets the priority of a remote user's media stream. + * Use this method with the setRemoteSubscribeFallbackOption method. If a remote video stream experiences the fallback, the SDK ensures the high-priority user gets the best possible stream quality. + * @see RtcEngine.setRemoteSubscribeFallbackOption + * Note + * - The Agora SDK supports setting userPriority as high for one user only. + * @param uid The ID of the remote user. + * @param userPriority The priority of the remote user. + * @see UserPriority + */ + setRemoteUserPriority(uid: number, userPriority: UserPriority): Promise; +} + +interface RtcMediaMetadataInterface { + /** + * Registers the metadata observer. + * A successful call of this method triggers the getMaxMetadataSize callback. + * @see RtcChannel.setMaxMetadataSize + * This method enables you to add synchronized metadata in the video stream for more diversified live broadcast interactions, such as sending shopping links, digital coupons, and online quizzes. + * Note + * - Call this method before the joinChannel method. + * @see RtcChannel.joinChannel + * - This method applies to the Live-Broadcast profile only. + * @see ChannelProfile.LiveBroadcasting + */ + registerMediaMetadataObserver(): Promise; + + /** + * TODO + */ + unregisterMediaMetadataObserver(): Promise; + + /** + * TODO + * @param size + */ + setMaxMetadataSize(size: number): Promise; + + /** + * TODO + * @param metadata + */ + sendMetadata(metadata: string): Promise; +} + +interface RtcEncryptionInterface { + /** + * Enables built-in encryption with an encryption password before joining a channel. + * All users in a channel must set the same encryption password. The encryption password is automatically cleared once a user leaves the channel. If the encryption password is not specified or set to empty, the encryption functionality is disabled. + * Note + * - For optimal transmission, ensure that the encrypted data size does not exceed the original data size + 16 bytes. 16 bytes is the maximum padding size for AES encryption. + * - Do not use this method for CDN live streaming. + * @param secret The encryption password. + */ + setEncryptionSecret(secret: string): Promise; + + /** + * Sets the built-in encryption mode. + * The Agora SDK supports built-in encryption, which is set to aes-128-xts mode by default. Call this method to set the encryption mode to use other encryption modes. All users in the same channel must use the same encryption mode and password. + * Refer to the information related to the AES encryption algorithm on the differences between the encryption modes. + * Note + * - Do not use this method for CDN streaming. + * - Before calling this method, ensure that you have called setEncryptionSecret to enable encryption. + * @see RtcEngine.setEncryptionSecret + * @param encryptionMode Sets the encryption mode. + * @see EncryptionMode + */ + setEncryptionMode(encryptionMode: EncryptionMode): Promise; +} + +interface RtcInjectStreamInterface { + /** + * Injects an online media stream to a Live-Broadcast channel. + * If this method call succeeds, the server pulls the voice or video stream and injects it into a live channel. This applies to scenarios where all audience members in the channel can watch a live show and interact with each other. + * Note + * - Ensure that you enable the RTMP Converter service before using this function. See Prerequisites. + * - This method can only be called by a broadcaster in a Live-Broadcast channel. + * Calling this method triggers the following callbacks: + * - The local client: + * -- onStreamInjectedStatus, with the state of injecting the media stream. + * @see RtcChannelEvents.StreamInjectedStatus + * -- onUserJoined(uid: 666), if the method call succeeds and the online media stream is injected into the channel. + * @see RtcChannelEvents.UserJoined + * - The remote client: + * -- onUserJoined(uid: 666), if the method call succeeds and the online media stream is injected into the channel. + * @see RtcChannelEvents.UserJoined + * @param url The URL address to be added to the ongoing live broadcast. Valid protocols are RTMP, HLS, and FLV. + * - Supported FLV audio codec type: AAC. + * - Supported FLV video codec type: H264(AVC). + * @param config The LiveInjectStreamConfig object, which contains the configuration information for the added voice or video stream. + * @see LiveInjectStreamConfig + */ + addInjectStreamUrl(url: string, config: LiveInjectStreamConfig): Promise; + + /** + * Removes the injected online media stream from a Live-Broadcast channel. + * This method removes the URL address added by addInjectStreamUrl. + * @see RtcChannel.addInjectStreamUrl + * If you successfully remove the URL address from the Live-Broadcast, the SDK triggers the onUserJoined callback, with the stream uid of 666. + * @see RtcChannelEvents.UserJoined + * @param url The URL address to be removed. + */ + removeInjectStreamUrl(url: string): Promise; +} + +interface RtcStreamMessageInterface { + /** + * Creates a data stream. + * Each user can create up to five data streams during the life cycle of the RtcChannel instance. + * @see RtcChannel + * Note + * - Set both the reliable and ordered parameters to true or false. Do not set one as true and the other as false. + * @param reliable Sets whether or not the recipients are guaranteed to receive the data stream from the sender within five seconds. + * - true: The recipients receive the data from the sender within five seconds. If the recipient does not receive the data within five seconds, the SDK triggers the onStreamMessageError callback and returns an error code. + * @see RtcChannelEvents.StreamMessageError + * - false: There is no guarantee that the recipients receive the data stream within five seconds and no error message is reported for any delay or missing data stream. + * @param ordered Determines whether or not the recipients receive the data stream in the sent order. + * - true: The recipients receive the data in the sent order. + * - false: The recipients do not receive the data in the sent order. + */ + createDataStream(reliable: boolean, ordered: boolean): Promise; + + /** + * Sends the data stream message. + * The SDK has the following restrictions on this method: + * - Up to 30 packets can be sent per second in a channel with each packet having a maximum size of 1 KB. + * - Each client can send up to 6 KB of data per second. + * - Each user can have up to five data channels simultaneously. + * A successful sendStreamMessage method call triggers the onStreamMessage callback on the remote client, from which the remote user gets the stream message. + * @see RtcChannelEvents.StreamMessage + * A failed sendStreamMessage method call triggers the onStreamMessageError callback on the remote client. + * @see RtcChannelEvents.StreamMessageError + * @param streamId ID of the sent data stream returned by the createDataStream method. + * @see RtcChannel.createDataStream + * @param message The message data. + */ + sendStreamMessage(streamId: number, message: string): Promise; +} diff --git a/src/RtcEngine.native.ts b/src/RtcEngine.native.ts index 28367bc11..6a06a7b6c 100644 --- a/src/RtcEngine.native.ts +++ b/src/RtcEngine.native.ts @@ -1,1720 +1,2105 @@ -import {NativeEventEmitter, NativeModules, Platform} from 'react-native'; - +import {NativeEventEmitter, NativeModules} from "react-native"; import { - AgoraUserInfo, - AudioFrameOption, - AudioMixingOption, - AudioRecordingOption, - BeautyOption, - Callback, + AudioEqualizationBandFrequency, + AudioProfile, + AudioRecordingQuality, + AudioReverbPreset, + AudioReverbType, + AudioSampleRateType, + AudioScenario, + AudioVoiceChanger, + BeautyOptions, CameraCapturerConfiguration, - ChannelMediaConfiguration, - DefaultVideoStreamOption, - ImageOption, - InjectStreamOption, + ChannelMediaRelayConfiguration, + ChannelProfile, + ClientRole, + ConnectionStateType, + EncryptionMode, + IPAreaCode, LastmileProbeConfig, - LiveTranscodingOption, - MixedAudioFrameOption, - Option, - PlayEffectOption, - PositionOption, - PublishStreamOption, - RemoveInjectStreamOption, - RemovePublishStreamOption, - VideoStreamOption -} from "./types"; - - -const {Agora} = NativeModules; -const AgoraEventEmitter = new NativeEventEmitter(Agora); + LiveInjectStreamConfig, + LiveTranscoding, + LogFilter, + Rate, + StreamFallbackOptions, + String, + UserInfo, + UserPriority, + VideoEncoderConfiguration, + VideoStreamType, + WatermarkOptions +} from "./Types"; +import {Listener, RtcEngineEvents, Subscription} from "./RtcEvents"; +import RtcChannel from "./RtcChannel.native"; + +const {AgoraRtcEngineModule} = NativeModules; +const Prefix = AgoraRtcEngineModule.prefix +const RtcEngineEvent = new NativeEventEmitter(AgoraRtcEngineModule); + +let engine: RtcEngine | undefined; /** - * RtcEngine is the javascript object for control agora native sdk through react native bridge. - * - * You can use the RtcEngine methods to create {@link init} - * - * Other methods of the RtcEngine object serve for agora native sdk and set up error logging. + * RtcEngine is the main class of the Agora SDK. */ -class RtcEngine { +export default class RtcEngine implements RtcUserInfoInterface, RtcAudioInterface, RtcVideoInterface, RtcAudioMixingInterface, + RtcAudioEffectInterface, RtcVoiceChangerInterface, RtcVoicePositionInterface, RtcPublishStreamInterface, + RtcMediaRelayInterface, RtcAudioRouteInterface, RtcEarMonitoringInterface, RtcDualStreamInterface, + RtcFallbackInterface, RtcTestInterface, RtcMediaMetadataInterface, RtcWatermarkInterface, RtcEncryptionInterface, + RtcAudioRecorderInterface, RtcInjectStreamInterface, RtcCameraInterface, RtcStreamMessageInterface { + + private _listeners = new Map>(); + + static instance(): RtcEngine { + if (engine) { + return engine as RtcEngine; + } else { + throw new Error('please create RtcEngine first') + } + } + + /** + * Creates an RtcEngine instance. + * @see RtcEngine + * Unless otherwise specified, all the methods provided by the RtcEngine class are executed asynchronously. Agora recommends calling these methods in the same thread. + * Note + * - You must create an RtcEngine instance before calling any other method. + * - You can create an RtcEngine instance either by calling this method or by calling create2. The difference between create2 and this method is that create2 enables you to specify the connection area. + * @see RtcEngine#createWithAreaCode + * - The Agora RTC Native SDK supports creating only one RtcEngine instance for an app for now. + * @param appId The App ID issued to you by Agora. See How to get the App ID. Only users in apps with the same App ID can join the same channel and communicate with each other. Use an App ID to create only one RtcEngine instance. To change your App ID, call destroy to destroy the current RtcEngine instance, and after destroy returns 0, call create to create an RtcEngine instance with the new App ID. + */ + static async create(appId: string): Promise { + return RtcEngine.createWithAreaCode(appId, IPAreaCode.AREA_GLOBAL) + } + + /** + * Creates an RtcEngine instance. + * @see RtcEngine + * Unless otherwise specified, all the methods provided by the RtcEngine class are executed asynchronously. Agora recommends calling these methods in the same thread. + * Note + * - You must create an RtcEngine instance before calling any other method. + * - You can create an RtcEngine instance either by calling this method or by calling create1. The difference between create1 and this method is that this method enables you to specify the connection area. + * @see RtcEngine#create + * - The Agora RTC Native SDK supports creating only one RtcEngine instance for an app for now. + * @param appId The App ID issued to you by Agora. See How to get the App ID. Only users in apps with the same App ID can join the same channel and communicate with each other. Use an App ID to create only one RtcEngine instance. To change your App ID, call destroy to destroy the current RtcEngine instance and after destroy returns 0, call create to create an RtcEngine instance with the new App ID. + * @param areaCode The area of connection. This advanced feature applies to scenarios that have regional restrictions. + * You can use the bitwise OR operator (|) to specify multiple areas. For details, see IPAreaCode. + * @see IPAreaCode + * After specifying the area of connection: + * - When the app that integrates the Agora SDK is used within the specified area, it connects to the Agora servers within the specified area under normal circumstances. + * - When the app that integrates the Agora SDK is used out of the specified area, it connects to the Agora servers either in the specified area or in the area where the app is located. + */ + static async createWithAreaCode(appId: string, areaCode: IPAreaCode): Promise { + if (engine) return engine; + await AgoraRtcEngineModule.create(appId, areaCode); + engine = new RtcEngine(); + return engine + } + + /** + * Destroys the RtcEngine instance and releases all resources used by the Agora SDK. + * @see RtcEngine + * This method is useful for apps that occasionally make voice or video calls, to free up resources for other operations when not making calls. + * Note + * - Call this method in the subthread. + * - Once the app calls destroy to destroy the created RtcEngine instance, you cannot use any method or callback in the SDK. + */ + destroy(): Promise { + RtcChannel.destroyAll(); + this.removeAllListeners(); + engine = undefined; + return AgoraRtcEngineModule.destroy() + } + + /** + * Adds the engine event handler. + * After setting the engine event handler, you can listen for engine events and receive the statistics of the corresponding RtcEngine instance. + * @param event The event type. + * @param listener The event handler. + */ + addListener(event: EventType, listener: RtcEngineEvents[EventType]): Subscription { + const callback = (res: any) => { + const {channelId, data} = res; + if (channelId === undefined) { + // @ts-ignore + listener(...data) + } + }; + let map = this._listeners.get(event); + if (map === undefined) { + map = new Map(); + this._listeners.set(event, map) + } + RtcEngineEvent.addListener(Prefix + event, callback); + map.set(listener, callback); + return { + remove: () => { + this.removeListener(event, listener) + } + } + } /** - * @ignore eventTypes + * Removes the engine event handler. + * For callback events that you only want to listen for once, call this method to remove it after you have received them. + * @param event The event type. + * @param listener The event handler. */ - private static readonly _eventTypes: Set = new Set(); + removeListener(event: EventType, listener: RtcEngineEvents[EventType]) { + const map = this._listeners.get(event); + if (map === undefined) return; + RtcEngineEvent.removeListener(Prefix + event, map.get(listener) as Listener); + map.delete(listener) + } /** - * @ignore AG_PREFIX + * Removes all of the engine event handlers. + * @param event The event type. + */ + removeAllListeners(event?: EventType) { + if (event === undefined) { + this._listeners.forEach((value, key) => { + RtcEngineEvent.removeAllListeners(Prefix + key); + }); + this._listeners.clear(); + return + } + RtcEngineEvent.removeAllListeners(Prefix + event); + this._listeners.delete(event as string) + } + + /** + * Sets the channel profile of the Agora RtcEngine. + * The Agora RtcEngine differentiates channel profiles and applies different optimization algorithms accordingly. For example, it prioritizes smoothness and low latency for a video call, and prioritizes video quality for a video broadcast. + * @param profile The channel profile of the Agora RtcEngine. + * @see ChannelProfile + */ + setChannelProfile(profile: ChannelProfile): Promise { + return AgoraRtcEngineModule.setChannelProfile(profile) + } + + /** + * Sets the role of a user (Live Broadcast only). + * This method sets the role of a user, such as a host or an audience (default), before joining a channel. + * This method can be used to switch the user role after a user joins a channel. In the Live Broadcast profile, when a user switches user roles after joining a channel, a successful setClientRole method call triggers the following callbacks: + * - The local client: onClientRoleChanged. + * @see RtcEngineEvents.ClientRoleChanged + * - The remote client: onUserJoined or onUserOffline(BecomeAudience). + * @see RtcEngineEvents.UserJoined + * @see RtcEngineEvents.UserOffline + * @see UserOfflineReason.BecomeAudience + * @param role Sets the role of a user. + * @see ClientRole + */ + setClientRole(role: ClientRole): Promise { + return AgoraRtcEngineModule.setClientRole(role) + } + + /** + * Allows a user to join a channel. + * Users in the same channel can talk to each other, and multiple users in the same channel can start a group chat. Users with different App IDs cannot call each other. + * You must call the leaveChannel method to exit the current call before joining another channel. + * @see RtcEngine.leaveChannel + * A successful joinChannel method call triggers the following callbacks: + * - The local client: onJoinChannelSuccess. + * @see RtcEngineEvents.JoinChannelSuccess + * - The remote client: onUserJoined, if the user joining the channel is in the Communication profile, or is a BROADCASTER in the Live Broadcast profile. + * @see RtcEngineEvents.UserJoined + * @see ChannelProfile.Communication + * @see ClientRole.Broadcaster + * @see ChannelProfile.LiveBroadcasting + * When the connection between the client and Agora's server is interrupted due to poor network conditions, the SDK tries reconnecting to the server. When the local client successfully rejoins the channel, the SDK triggers the onRejoinChannelSuccess callback on the local client. + * @see RtcEngineEvents.RejoinChannelSuccess + * The uid is represented as a 32-bit unsigned integer in the SDK. Since unsigned integers are not supported by Java, the uid is handled as a 32-bit signed integer and larger numbers are interpreted as negative numbers in Java. If necessary, the uid can be converted to a 64-bit integer through “uid&0xffffffffL”. + * Note + * - A channel does not accept duplicate uids, such as two users with the same uid. If you set uid as 0, the system automatically assigns a uid. + * Warning + * - Ensure that the App ID used for creating the token is the same App ID used in the create method for creating an RtcEngine object. Otherwise, CDN live streaming may fail. + * @param token The token for authentication: + * - In situations not requiring high security: You can use the temporary token generated at Console. For details, see Get a temporary token. + * - In situations requiring high security: Set it as the token generated at your server. For details, see Generate a token. + * @param channelName The unique channel name for the AgoraRTC session in the string format. The string length must be less than 64 bytes. Supported character scopes are: + * - All lowercase English letters: a to z. + * - All uppercase English letters: A to Z. + * - All numeric characters: 0 to 9. + * - The space character. + * - Punctuation characters and other symbols, including: "!", "#", "$", "%", "&", "(", ")", "+", "-", ":", ";", "<", "=", ".", ">", "?", "@", "[", "]", "^", "_", " {", "}", "|", "~", ",". + * @param optionalInfo Additional information about the channel. This parameter can be set as null or contain channel related information. Other users in the channel do not receive this message. + * @param optionalUid (Optional) User ID. A 32-bit unsigned integer with a value ranging from 1 to (2^32-1). optionalUid must be unique. If optionalUid is not assigned (or set to 0), the SDK assigns and returns uid in the onJoinChannelSuccess callback. Your app must record and maintain the returned uid since the SDK does not do so. + * @see RtcEngineEvents.JoinChannelSuccess + */ + joinChannel(token: String, channelName: string, optionalInfo: String, optionalUid: number): Promise { + return AgoraRtcEngineModule.joinChannel(token, channelName, optionalInfo, optionalUid) + } + + /** + * Switches to a different channel. + * This method allows the audience of a Live-broadcast channel to switch to a different channel. + * After the user successfully switches to another channel, the onLeaveChannel and onJoinChannelSuccess callbacks are triggered to indicate that the user has left the original channel and joined a new one. + * @see RtcEngineEvents.LeaveChannel + * @see RtcEngineEvents.JoinChannelSuccess + * Note + * - This method applies to the audience role in a Live-broadcast channel only. + * @see ClientRole.Audience + * @see ChannelProfile.LiveBroadcasting + * @param token The token for authentication: + * - In situations not requiring high security: You can use the temporary token generated at Console. For details, see Get a temporary token. + * - In situations requiring high security: Set it as the token generated at your server. For details, see Generate a token. + * @param channelName Unique channel name for the AgoraRTC session in the string format. The string length must be less than 64 bytes. Supported character scopes are: + * - All lowercase English letters: a to z. + * - All uppercase English letters: A to Z. + * - All numeric characters: 0 to 9. + * - The space character. + * - Punctuation characters and other symbols, including: "!", "#", "$", "%", "&", "(", ")", "+", "-", ":", ";", "<", "=", ".", ">", "?", "@", "[", "]", "^", "_", " {", "}", "|", "~", ",". */ - private static readonly AG_PREFIX: string = 'ag_rtc'; + switchChannel(token: String, channelName: string): Promise { + return AgoraRtcEngineModule.switchChannel(token, channelName) + } /** - * Creates a RtcEngine Object internal. - * - * This method creates and start event observer. You should call this method once. - * @example `RtcEngine.init(option)` - * @param options Defines the property of the client, see {@link Option} for details. - * @returns any + * Allows a user to leave a channel. + * After joining a channel, the user must call the leaveChannel method to end the call before joining another channel. This method returns 0 if the user leaves the channel and releases all resources related to the call. This method call is asynchronous, and the user has not exited the channel when the method call returns. Once the user leaves the channel, the SDK triggers the onLeaveChannel callback. + * A successful leaveChannel method call triggers the following callbacks: + * - The local client: onLeaveChannel. + * @see RtcEngineEvents.LeaveChannel + * - The remote client: onUserOffline, if the user leaving the channel is in the Communication channel, or is a BROADCASTER in the Live Broadcast profile. + * @see RtcEngineEvents.UserOffline + * @see ChannelProfile.Communication + * @see ClientRole.Broadcaster + * @see ChannelProfile.LiveBroadcasting + * Note + * - If you call the destroy method immediately after calling the leaveChannel method, the leaveChannel process interrupts, and the SDK does not trigger the onLeaveChannel callback. + * @see RtcEngine.destroy + * - If you call the leaveChannel method during CDN live streaming, the SDK triggers the removeInjectStreamUrl method. + * @see RtcEngine.removeInjectStreamUrl */ - public static init(options: Option): void { - Agora.init(options); + leaveChannel(): Promise { + return AgoraRtcEngineModule.leaveChannel() } /** - * join specified channel - * - * This method joins and begin rendering the video stream. when join succeeds. - * Otherwise, it will invoke error by the event - * @param channelName - * @param uid - * @param token - * @param info - * @returns Promise + * Renews the token when the current token expires. + * The token expires after a period of time once the token schema is enabled when: + * - The SDK triggers the onTokenPrivilegeWillExpire callback, or + * @see RtcEngineEvents.TokenPrivilegeWillExpire + * - The onConnectionStateChanged callback reports the TokenExpired(9) error. + * @see RtcEngineEvents.ConnectionStateChanged + * @see ConnectionChangedReason.TokenExpired + * The app should retrieve a new token from the server and call this method to renew it. Failure to do so results in the SDK disconnecting from the server. + * @param token The new token. */ - public static joinChannel(channelName: string, uid?: number, token?: string, info?: string): Promise { - return Agora.joinChannel({channelName, uid, token, info}); + renewToken(token: string): Promise { + return AgoraRtcEngineModule.renewToken(token) } /** - * switch to specified channel - * - * This method will switch channel smoothly than you invoke leaveChannel & joinChannel. - * Otherwise, it will invoke error by the event - * It will occurs two events: - * Occurs leaveChannel when achieve leaving stage - * Occurs joinChannelSuccess when achieve joining stage - * @param channelName {@link string} - * @param token {@link string} - * @returns Promise + * Enables interoperability with the Agora Web SDK (Live Broadcast only). + * @deprecated As of v3.0.0, the Native SDK automatically enables interoperability with the Web SDK, so you no longer need to call this method. + * If the channel has Web SDK users, ensure that you call this method, or the video of the Native user will be a black screen for the Web user. + * Use this method when the channel profile is Live Broadcast. Interoperability with the Agora Web SDK is enabled by default when the channel profile is Communication. + * @param enabled Sets whether to enable/disable interoperability with the Agora Web SDK: + * - true: Enable. + * - false: (Default) Disable. */ - public static switchChannel(channelName: string, token?: string): Promise { - return Agora.switchChannel({channelName, token}); + enableWebSdkInteroperability(enabled: boolean): Promise { + return AgoraRtcEngineModule.enableWebSdkInteroperability(enabled) } /** - * Starts to relay media streams across channels. - * - * This method will start relay media stream across specified channels. (maximum support 4 channels) - * It will occurs event: - * Occurs mediaRelayStateChanged - * Occurs receivedChannelMediaRelay when peer channel received this message - * @param config {@link ChannelMediaConfiguration} - * @returns Promise + * Gets the connection state of the SDK. */ - public static startChannelMediaRelay(config: ChannelMediaConfiguration): Promise { - return Agora.startChannelMediaRelay(config); + getConnectionState(): Promise { + return AgoraRtcEngineModule.getConnectionState() } /** - * Remove to relay media streams across channels. - * - * This method will remove & update relay media stream across specified channels. (maximum support relay 4 channels) - * It will occurs event: - * Occurs mediaRelayStateChanged - * @param config {@link ChannelMediaConfiguration} - * @returns Promise + * Gets the current call ID. + * When a user joins a channel on a client, a call ID is generated to identify the call from the client. Feedback methods, such as the rate and complain method, must be called after the call ends to submit feedback to the SDK. + * @see RtcEngine.rate + * @see RtcEngine.complain + * The rate and complain methods require the callId parameter retrieved from the getCallId method during a call. callId is passed as an argument into the rate and complain methods after the call ends. */ - public static removeChannelMediaRelay(config: ChannelMediaConfiguration): Promise { - return Agora.removeChannelMediaRelay(config); + getCallId(): Promise { + return AgoraRtcEngineModule.getCallId() } /** - * Updates to relay media streams across channels. - * - * This method will update relay media stream across specified channels. (maximum support 4 channels) - * It will occurs event: - * Occurs mediaRelayStateChanged - * @param config {@link ChannelMediaConfiguration} - * @returns Promise + * Allows the user to rate a call after the call ends. + * @param callId ID of the call retrieved from the getCallId method. + * @see RtcEngine.getCallId + * @param rating Rating of the call. The value is between 1 (lowest score) and 5 (highest score). If you set a value out of this range, the InvalidArgument(-2) error occurs. + * @see ErrorCode.InvalidArgument + * @param description (Optional) The description of the rating. The string length must be less than 800 bytes. */ - public static updateChannelMediaRelay(config: ChannelMediaConfiguration): Promise { - return Agora.updateChannelMediaRelay(config); + rate(callId: string, rating: Rate, description?: string): Promise { + return AgoraRtcEngineModule.rate(callId, rating, description) } /** - * Stop to relay media streams across channels. - * - * This method will stop relay media stream across specified channels. - * It will occurs event: - * Occurs mediaRelayStateChanged - * @param config {@link ChannelMediaConfiguration} - * @returns Promise + * Allows a user to complain about the call quality after a call ends. + * @param callId ID of the call retrieved from the getCallId method. + * @see RtcEngine.getCallId + * @param description (Optional) The description of the complaint. The string length must be less than 800 bytes. */ - public static stopChannelMediaRelay(): Promise { - return Agora.stopChannelMediaRelay(); + complain(callId: string, description: string): Promise { + return AgoraRtcEngineModule.complain(callId, description) } /** - * Registers a user account. - * - * Once registered, the user account can be used to identify the local user when the user joins the channel. After the user successfully registers a user account, the SDK triggers the `on("localUserRegistered", callback)` on the local client, reporting the user ID and user account of the local user. - * To join a channel with a user account, you can choose either of the following: - * Call the {@link registerLocalUserAccount} method to create a user account, and then the {@link joinChannelWithUserAccount} method to join the channel. - * Call the {@link joinChannelWithUserAccount} method to join the channel. - * - * @note To ensure smooth communication, use the same parameter type to identify the user. For example, if a user joins the channel with a user ID, then ensure all the other users use the user ID too. The same applies to the user account. If a user joins the channel with the Agora Web SDK, ensure that the uid of the user is set to the same parameter type. - * - * @param userAccount - * @returns Promise + * Specifies an SDK output log file. + * The log file records all log data for the SDK’s operation. Ensure that the directory for the log file exists and is writable. + * Note + * - Ensure that you call this method immediately after calling the create method, otherwise the output log may not be complete. + * @see RtcEngine.create + * @param filePath File path of the log file. The string of the log file is in UTF-8. The default file path is /storage/emulated/0/Android/data/="">/files/agorasdk.log. */ - public static registerLocalUserAccount(userAccount: string): Promise { - return Agora.registerLocalUserAccount({userAccount}); + setLogFile(filePath: string): Promise { + return AgoraRtcEngineModule.setLogFile(filePath) } /** - * Joins the channel with a user account. - * - * After the user successfully joins the channel, the SDK triggers the following callbacks: - * - * The local client: `on("localUserRegistered", callback)` and `on("joinChannelSuccess", callback)`. - * The remote client: `on("userJoined", callback)` and `on("userInfoUpdated", callback)`, if the user joining the channel is in the Communication profile, or is a BROADCASTER in the Live Broadcast profile. - * - * @note To ensure smooth communication, use the same parameter type to identify the user. For example, if a user joins the channel with a user ID, then ensure all the other users use the user ID too. The same applies to the user account. If a user joins the channel with the Agora Web SDK, ensure that the uid of the user is set to the same parameter type. - * - * @param channelName - * @param userAccount - * @param token - * @returns Promise + * Sets the output log level of the SDK. + * You can use one or a combination of the filters. The log level follows the sequence of OFF, CRITICAL, ERROR, WARNING, INFO, and DEBUG. Choose a level to see the logs preceding that level. For example, if you set the log level to WARNING, you see the logs within levels CRITICAL, ERROR, and WARNING. + * @param filter Sets the log filter level. + * @see LogFilter */ - public static joinChannelWithUserAccount(channelName: string, userAccount: string, token: string): Promise { - return Agora.joinChannelWithUserAccount({channelName, userAccount, token}); + setLogFilter(filter: LogFilter): Promise { + return AgoraRtcEngineModule.setLogFilter(filter) } /** - * Gets the user information by passing in the user account. - * - * After receiving the "userInfoUpdated" callback, you can call this method to get the user ID of the remote user from the {@link AgoraUserInfo} object by passing in the userAccount. - * @param uid - * @returns Promise<{@link AgoraUserInfo}> - */ - public static async getUserInfoByUid(uid: number): Promise { - if (Platform.OS === 'android') { - const _uid = this.Uint32ToInt32(uid); - let result = await Agora.getUserInfoByUid(_uid); - result.uid = this.Int32ToUint32(result.uid); - return result; - } - return Agora.getUserInfoByUid(uid); + * Sets the log file size (KB). + * The Agora SDK has two log files, each with a default size of 512 KB. If you set fileSizeInKBytes as 1024 KB, the SDK outputs log files with a total maximum size of 2 MB. If the total size of the log files exceed the set value, the new output log files overwrite the old output log files. + * @param fileSizeInKBytes The SDK log file size (KB). + */ + setLogFileSize(fileSizeInKBytes: number): Promise { + return AgoraRtcEngineModule.setLogFileSize(fileSizeInKBytes) } /** - * Gets the user information by passing in the user account. - * - * After receiving the "userInfoUpdated" callback, you can call this method to get the user ID of the remote user from the {@link AgoraUserInfo} object by passing in the userAccount. - * @param userAccount - * @returns Promise<{@link AgoraUserInfo}> - */ - public static async getUserInfoByUserAccount(userAccount: string): Promise { - if (Platform.OS === 'android') { - let result = await Agora.getUserInfoByUserAccount(userAccount); - result.uid = this.Int32ToUint32(result.uid); - return result; - } - return Agora.getUserInfoByUserAccount(userAccount); - } - - /** - * add event listener - * - * This method subscribes specified eventType and run listener. You should call this method at first. - * - * @event listener - * - * --- - * name | description | usage | - * error | occurs when emit error | on("error", evt) | - * warning | occurs when emit warning | on("warning", evt) | - * messageReceived | occurs when message received | on("messageReceived", evt) | - * localInvitationReceivedByPeer | occurs when local inviation received by peer | on("localInvitationReceivedByPeer", evt) | - * localInvitationAccepted | occurs when local invitation accepted | on("localInvitationAccepted", evt) | - * localInvitationRefused | occurs when local invitation refused | on("localInvitationRefused", evt) | - * localInvitationCanceled | occurs when local invitation canceled | on("localInvitationCanceled", evt) | - * localInvitationFailure | occurs when local invitation failure | on("localInvitationFailure", evt) | - * remoteInvitationFailure | occurs when remote invitation failure | on("remoteInvitationFailure", evt) | - * remoteInvitationReceived | occurs when remote invitation received | on("remoteInvitationReceived", evt) | - * remoteInvitationAccepted | occurs when remote invitation accepted | on("remoteInvitationAccepted", evt) | - * remoteInvitationRefused | occurs when remote invitation refused | on("remoteInvitationRefused", evt) | - * remoteInvitationCanceled | occurs when remote invitation canceled | on("remoteInvitationCanceled", evt) | - * channelMessageReceived | occurs when received channel message | on("channelMessageReceived", evt) | - * channelMemberJoined | occurs when some one joined in the subscribed channel | on("channelMemberJoined", evt) | - * channelMemberLeft | occurs when sone one left from u subscribed channel | on("channelMemberLeft", evt) | - * tokenExpired | occurs when token has expired | on("tokenExpired", evt) | - * apiCallExecute | occurs when apiCallExecute emit, this event is api call monitor | on("apiCallExecute", evt) | - * joinChannelSuccess | occurs when joinChannel success | on("joinChannelSuccess", evt) | - * rejoinChannelSuccess | occurs when rejoinChannel success | on("rejoinChannelSuccess", evt) | - * leaveChannel | occurs when leaveChannel success | on("leaveChannel", evt) | - * clientRoleChanged | occurs when setClientRole changed | on("clientRoleChanged", evt) | - * userJoined | occurs when remote user joined | on("userJoined", evt) | - * userOffline | this event occurs when remote user offline in rtc mode, this events only occurs host user offline in live mode | on("userOffline", evt) | - * connectionStateChanged | occurs when sdk connection changed state | on("connectionStateChanged", evt) | - * connectionLost | occurs when sdk connection lost | on("connectionLost", evt) | - * tokenPrivilegeWillExpire | occurs when token will expire | on("tokenPrivilegeWillExpire", evt) | - * requestToken | occurs when token expired | on("requestToken") | - * localAudioStateChanged | occurs when local audio device state changed | on("localAudioStateChanged", (state, errorCode) => {}) | - * audioVolumeIndication | occurs when audio volume indication changed | on("audioVolumeIndication", evt) | - * activeSpeaker | occurs when detect active speaker | on("activeSpeaker", evt) | - * firstLocalAudioFrame | occurs when sent first audio frame on local | on("firstLocalAudioFrame", evt) | - * firstRemoteAudioFrame | occurs when received first audio frame from remote side | on("firstRemoteAudioFrame", evt) | - * firstRemoteAudioDecoded | occurs when first remote audio decoded | on("firstRemoteAudioDecoded", evt) | - * firstLocalVideoFrame | occurs when sent first video frame on local | on("firstLocalVideoFrame", evt) | - * firstRemoteVideoFrame | occurs when received first video frame from remote side | on("firstRemoteVideoFrame", evt) | - * userMuteAudio | occurs when user mute audio | on("userMuteAudio", evt) | - * videoSizeChanged | occurs when change local or remote side video size or rotation | on("videoSizeChanged", evt) | - * remoteVideoStateChanged | occurs when remote video state has any changed | on("remoteVideoStateChanged", evt) | - * remoteAudioStateChanged | occurs when remote audio state has any changed | on("remoteAudioStateChanged", evt) | - * localAudioStats | occurs when engine start to report local audio stats | on("localAudioStats", evt) | - * localPublishFallbackToAudioOnly | occurs when published stream from local side fallback to audio stream | on("localPublishFallbackToAudioOnly", evt) | - * remoteSubscribeFallbackToAudioOnly | occurs when subscribed side's stream fallback to audio stream | on("remoteSubscribeFallbackToAudioOnly", evt) | - * audioRouteChanged | occurs when local audio route changed | on("audioRouteChanged", evt) | - * cameraFocusAreaChanged | occurs when a camera focus area changed | on("cameraFocusAreaChanged", evt) | - * cameraExposureAreaChanged | occurs when a camera exposure area changed | on("cameraExposureAreaChanged", evt) | - * rtcStats | occurs when reports the statistics of the current call session once every two seconds. | on("rtcStats", evt) | - * lastmileQuality | occurs when reports the last mile network quality of the local user once every two seconds before the user joins a channel.| on("lastmileQuality", evt) | - * networkQuality | occurs when reports the last mile network quality of each user in the channel once every two seconds.| on("networkQuality", evt) | - * localVideoStats | occurs when reports local video statistics | on("localVideoStats", evt) | - * remoteVideoStats | occurs when reports remote video statistics| on("remoteVideoStats", evt) | - * remoteAudioStats | occurs when reports remote audio statistics| on("remoteAudioStats", evt) | - * audioEffectFinish | occurs when the local audio effect playback finishes. | on("audioEffectFinish", evt) | - * streamPublished | occurs when addPublishStreamUrl success| on("streamPublished", evt) | - * streamUnpublish | occurs when removePublishStreamUrl success| on("streamUnpublish", evt) | - * transcodingUpdate | occurs when the cdn live streaming settings are updated | on("transcodingUpdate", evt) | - * streamInjectedStatus | occurs when report the status of online injecting stream to a live broadcast | on("streamInjectedStatus", evt) | - * mediaEngineLoaded | occurs when the media engine loaded | on("mediaEngineLoaded", evt) | - * mediaEngineStartCall | occurs when the media engine call starts | on("mediaEngineStartCall", evt) | - * startEchoTestWithInterval | occurs when startEchoTestWithInterval success | on("startEchoTestWithInterval", evt) | - * audioMixingStateChanged | occurs when reports the local audio mixing state changed | on("audioMixingStateChanged", evt) | - * lastmileProbeTestResult | occurs when reports the last-mile network probe result.| on("lastmileProbeTestResult", evt) | - * rtmpStreamingStateChanged | occurs when reports the rtmp injecting stream state changed | on("rtmpStreamingStateChanged", evt) | - * localVideoChanged | occurs when the local video changed | on("localVideoChanged", evt) | - * networkTypeChanged | occurs when the device network type changed | on("networkTypeChanged", evt) | - * mediaMetaDataReceived | occurs when you received media meta data from the remote side through sendMediaData | on("mediaMetaDataReceived", evt) | - * localUserRegistered | occurs when you register user account success | on("localUserRegistered", evt) | - * userInfoUpdated | occurs when you peer side using user account join channel | on("userInfoUpdated", evt) | - * receivedChannelMediaRelay | occurs when you received channel media relay | on('receivedChannelMediaRelay", evt)| - * mediaRelayStateChanged | occurs when you received remote media relay state changed | on('mediaRelayStateChanged", evt)| - * --- - * - * @param eventType - * @param listener - * @return any - */ - public static on(eventType: string, listener: (...args: any[]) => any): any { - this._eventTypes.add(`${RtcEngine.AG_PREFIX}${eventType}`); - // convert int32 to uint32 - if ([ - 'joinChannelSuccess', - 'rejoinChannelSuccess', - 'userJoined', - 'userOffline', - 'occurStreamMessageError', - 'receiveStreamMessage', - 'activeSpeaker', - 'firstRemoteAudioFrame', - 'firstRemoteVideoFrame', - 'userMuteAudio', - 'videoSizeChanged', - 'remoteVideoStateChanged', - 'remoteAudioStateChanged', - 'remoteSubscribeFallbackToAudioOnly', - 'networkQuality', - 'streamInjectedStatus', - 'localUserRegistered' - ].indexOf(eventType) != -1) { - AgoraEventEmitter.addListener(`${RtcEngine.AG_PREFIX}${eventType}`, (args) => { - args.uid = this.Int32ToUint32(args.uid); - // convert int32 streamId to uint32 - if (args.streamId) { - args.streamId = this.Int32ToUint32(args.streamId); - } - listener(args); - }); - return; - } + * Provides technical preview functionalities or special customizations by configuring the SDK with JSON options. + * The JSON options are not public by default. Agora is working on making commonly used JSON options public in a standard way. + * @param parameters Sets the parameter as a JSON string in the specified format. + */ + setParameters(parameters: string): Promise { + return AgoraRtcEngineModule.setParameters(parameters) + } - if (['userInfoUpdated'].indexOf(eventType) != -1) { - AgoraEventEmitter.addListener(`${RtcEngine.AG_PREFIX}${eventType}`, (args) => { - args.uid = this.Int32ToUint32(args.uid); - args.peer.uid = this.Int32ToUint32(args.peer.uid); - listener(args); - }); - return; - } + getUserInfoByUid(uid: number): Promise { + return AgoraRtcEngineModule.getUserInfoByUid(uid) + } - if (['audioVolumeIndication'].indexOf(eventType) != -1) { - AgoraEventEmitter.addListener(`${RtcEngine.AG_PREFIX}${eventType}`, (args) => { - args.speakers.map((speaker: any) => { - const uid = this.Int32ToUint32(speaker.uid); - return { - ...speaker, - uid - } - }) - listener(args); - }); - return; - } + getUserInfoByUserAccount(userAccount: string): Promise { + return AgoraRtcEngineModule.getUserInfoByUserAccount(userAccount) + } - if ([ - 'remoteAudioStats', - 'remoteVideoStats', - ].indexOf(eventType) != -1) { - AgoraEventEmitter.addListener(`${RtcEngine.AG_PREFIX}${eventType}`, (args) => { - args.stats.uid = this.Int32ToUint32(args.stats.uid); - listener(args); - }); - return; - } - AgoraEventEmitter.addListener(`${RtcEngine.AG_PREFIX}${eventType}`, listener); + joinChannelWithUserAccount(token: String, channelName: string, userAccount: string): Promise { + return AgoraRtcEngineModule.joinChannelWithUserAccount(token, channelName, userAccount); } - /** - * @deprecated removeAllListeners - */ - static removeAllListeners() { - console.warn("removeAllListeners method already deprecated"); + registerLocalUserAccount(appId: string, userAccount: string): Promise { + return AgoraRtcEngineModule.registerLocalUserAccount(appId, userAccount); } - /** - * @deprecated off - * @param mode - */ - static off(evt: any) { - console.warn("off method already deprecated"); + adjustPlaybackSignalVolume(volume: number): Promise { + return AgoraRtcEngineModule.adjustPlaybackSignalVolume(volume); } - /** - * renew token - * - * This method renews a new token. - * @param token - */ - public static renewToken(token: string) { - return Agora.renewToken(token); + adjustRecordingSignalVolume(volume: number): Promise { + return AgoraRtcEngineModule.adjustRecordingSignalVolume(volume); } - /** - * enable websdk interoperability - * - * This method used to enable websdk interoperability, so that it can connect with agora websdk apps. - * - * @param enabled - * @return Promise<{success, value}> - */ - public static enableWebSdkInteroperability(enabled: boolean): Promise { - return Agora.enableWebSdkInteroperability(enabled); + adjustUserPlaybackSignalVolume(uid: number, volume: number): Promise { + return AgoraRtcEngineModule.adjustUserPlaybackSignalVolume(uid, volume); } - /** - * get agora native sdk connection state - * - * This method gets agora native sdk connection state - * @return Promise<{state: (connection state)}> - */ - public static getConnectionState(): Promise { - return Agora.getConnectionState(); + disableAudio(): Promise { + return AgoraRtcEngineModule.disableAudio(); } - /** - * change the client role - * - * This method changes the client of role. - * @param role (audience: 0, host: 1) - */ - public static setClientRole(role: number): Promise { - return Agora.setClientRole(role); + enableAudio(): Promise { + return AgoraRtcEngineModule.enableAudio(); } - /** - * leave channel - * - * This method leaves the joined channel, then your video view will not render ever. - * You should call it, when you dont need render video stream. - * - * @return Promise - */ - public static leaveChannel(): Promise { - return Agora.leaveChannel(); + enableAudioVolumeIndication(interval: number, smooth: number, report_vad: boolean): Promise { + return AgoraRtcEngineModule.enableAudioVolumeIndication(interval, smooth, report_vad); } - /** - * destroy - * - * This method stops event subscribe and destroy the RtcEngine instance's. - * You should call it, when you want to destroy the engine. - * - * @return void - */ - public static destroy() { - if (this._eventTypes.size) { - for (let eventType of this._eventTypes) { - AgoraEventEmitter.removeAllListeners(eventType); - } - this._eventTypes.clear(); - } - return Agora.destroy(); + enableLocalAudio(enabled: boolean): Promise { + return AgoraRtcEngineModule.enableLocalAudio(enabled); } - /** - * set local video render mode - * - * This method calls native sdk render mode for local video. - * @param mode - * @return Promise - */ - public static setLocalRenderMode(mode: number): Promise { - return Agora.setLocalRenderMode(mode); + muteAllRemoteAudioStreams(muted: boolean): Promise { + return AgoraRtcEngineModule.muteAllRemoteAudioStreams(muted); } - /** - * set the specified remote video render mode - * - * This method calls native sdk render mode for the specified remote video. - * - * @param uid - * @param mode - * @return Promise - */ - public static setRemoteRenderMode(uid: number, mode: number): Promise { - let uint32 = Platform.OS === 'android' ? this.Uint32ToInt32(uid) : uid; - return Agora.setRemoteRenderMode(uint32, mode); + muteLocalAudioStream(muted: boolean): Promise { + return AgoraRtcEngineModule.muteLocalAudioStream(muted); } - /** - * start video preview - * - * This method start video preview for video. - * @return Promise - */ - public static startPreview(): Promise { - return Agora.startPreview(); + muteRemoteAudioStream(uid: number, muted: boolean): Promise { + return AgoraRtcEngineModule.muteRemoteAudioStream(uid, muted); } + setAudioProfile(profile: AudioProfile, scenario: AudioScenario): Promise { + return AgoraRtcEngineModule.setAudioProfile(profile, scenario); + } - /** - * stop video preview - * - * This method stops video preview for video. - * @return Promise - */ - public static stopPreview(): Promise { - return Agora.stopPreview(); + setDefaultMuteAllRemoteAudioStreams(muted: boolean): Promise { + return AgoraRtcEngineModule.setDefaultMuteAllRemoteAudioStreams(muted); } - /** - * set enable speaker phone - * - * This method set the speaker phone enable or disable by pass boolean parameter. - * @param enabled - * @return Promise - */ - public static setEnableSpeakerphone(enabled: boolean): Promise { - return Agora.setEnableSpeakerphone(enabled); + disableVideo(): Promise { + return AgoraRtcEngineModule.disableVideo(); } - /** - * set default audio speaker - * - * This method set the default audio speaker enable or disable by pass boolean parameter. - * @param enabled - * @return Promise - */ - public static setDefaultAudioRouteToSpeakerphone(enabled: boolean): Promise { - return Agora.setDefaultAudioRouteToSpeakerphone(enabled); + enableLocalVideo(enabled: boolean): Promise { + return AgoraRtcEngineModule.enableLocalVideo(enabled); } - /** - * set default mute all remote audio streams - * - * This method set default mute all remote audio streams enable or not by pass boolean parameter. - * @param enabled - * @return Promise - */ - public static setDefaultMuteAllRemoteAudioStreams(enabled: boolean): Promise { - return Agora.setDefaultMuteAllRemoteAudioStreams(enabled); + enableVideo(): Promise { + return AgoraRtcEngineModule.enableVideo(); } - /** - * enable video - * - * This method enables video. - * @return Promise - */ - public static enableVideo(): Promise { - return Agora.enableVideo(); + muteAllRemoteVideoStreams(muted: boolean): Promise { + return AgoraRtcEngineModule.muteAllRemoteVideoStreams(muted); } - /** - * disable video - * - * This method disables video. - * @return Promise - */ - public static disableVideo(): Promise { - return Agora.disableVideo(); + muteLocalVideoStream(muted: boolean): Promise { + return AgoraRtcEngineModule.muteLocalVideoStream(muted); } - /** - * enable local video - * - * This method enables the local video by the boolean parameter. - * @param enabled - * @return Promise - */ - public static enableLocalVideo(enabled: boolean): Promise { - return Agora.enableLocalVideo(enabled); + muteRemoteVideoStream(uid: number, muted: boolean): Promise { + return AgoraRtcEngineModule.muteRemoteVideoStream(uid, muted); } - /** - * mute local video stream - * - * This method mutes video stream by the boolean parameter. - * @param muted - * @return Promise - */ - public static muteLocalVideoStream(muted: boolean): Promise { - return Agora.muteLocalVideoStream(muted); + setBeautyEffectOptions(enabled: boolean, options: BeautyOptions): Promise { + return AgoraRtcEngineModule.setBeautyEffectOptions(enabled, options); } - /** - * mute all remote video streams - * - * This method mutes all remote streams by the boolean parameter. - * @param muted - * @return Promise - */ - public static muteAllRemoteVideoStreams(muted: boolean): Promise { - return Agora.muteAllRemoteVideoStreams(muted); + setDefaultMuteAllRemoteVideoStreams(muted: boolean): Promise { + return AgoraRtcEngineModule.setDefaultMuteAllRemoteVideoStreams(muted); } - /** - * @ignore Uint32ToInt32 - */ - private static Uint32ToInt32(num: number) { - const int32 = new Int32Array(1); - int32[0] = num; - return int32[0]; + setVideoEncoderConfiguration(config: VideoEncoderConfiguration): Promise { + return AgoraRtcEngineModule.setVideoEncoderConfiguration(config); } - /** - * @ignore Int32ToUint32 - */ - private static Int32ToUint32(num: number) { - const uint32 = new Uint32Array(1); - uint32[0] = num; - return uint32[0]; + adjustAudioMixingPlayoutVolume(volume: number): Promise { + return AgoraRtcEngineModule.adjustAudioMixingPlayoutVolume(volume); } - /** - * mute specified remote video stream. - * - * This method mutes remote video stream by the number of uid and boolean parameter. - * @param uid - * @param muted - * @return Promise - */ - public static muteRemoteVideoStream(uid: number, muted: boolean): Promise { - let uint32 = Platform.OS === 'android' ? this.Uint32ToInt32(uid) : uid; - return Agora.muteRemoteVideoStream(uint32, muted); + adjustAudioMixingPublishVolume(volume: number): Promise { + return AgoraRtcEngineModule.adjustAudioMixingPublishVolume(volume); } - /** - * set default mute all remote video stream - * - * This method mutes all remote video stream default by the boolean parameter. - * @param muted - * @return Promise - */ - public static setDefaultMuteAllRemoteVideoStreams(muted: boolean): Promise { - return Agora.setDefaultMuteAllRemoteVideoStreams(muted); + adjustAudioMixingVolume(volume: number): Promise { + return AgoraRtcEngineModule.adjustAudioMixingVolume(volume); } - /** - * enable audio - * - * This method enables audio - * @return Promise - */ - public static enableAudio(): Promise { - return Agora.enableAudio(); + getAudioMixingCurrentPosition(): Promise { + return AgoraRtcEngineModule.getAudioMixingCurrentPosition(); } - /** - * disable audio - * - * This method disables audio - * @return Promise - */ - public static disableAudio(): Promise { - return Agora.disableAudio(); + getAudioMixingDuration(): Promise { + return AgoraRtcEngineModule.getAudioMixingDuration(); } - /** - * enable local audio - * - * This method enables local audio by the boolean parameter. - * @param enabled - * @return Promise - */ - public static enableLocalAudio(enabled: boolean): Promise { - return Agora.enableLocalAudio(enabled); + getAudioMixingPlayoutVolume(): Promise { + return AgoraRtcEngineModule.getAudioMixingPlayoutVolume(); } - /** - * mute local audio stream - * - * This method mutes the local audio stream by muted. - * @param muted - * @return Promise - */ - public static disableLocalAudio(muted: boolean): Promise { - return Agora.disableLocalAudio(muted); + getAudioMixingPublishVolume(): Promise { + return AgoraRtcEngineModule.getAudioMixingPublishVolume(); } - /** - * mute all remote audio streams - * - * This method mutes all remote audio streams by muted - * @param muted boolean - * @return Promise - */ - public static muteAllRemoteAudioStreams(muted: boolean): Promise { - return Agora.muteAllRemoteAudioStreams(muted); + pauseAudioMixing(): Promise { + return AgoraRtcEngineModule.pauseAudioMixing(); } - /** - * mute specified remote audio stream by muted - * - * This method mutes specified remote audio stream by number uid and boolean muted. - * @param uid - * @param muted - * @return Promise - */ - public static muteRemoteAudioStream(uid: number, muted: boolean): Promise { - let uint32 = Platform.OS === 'android' ? this.Uint32ToInt32(uid) : uid; - return Agora.muteRemoteAudioStream(uint32, muted); + resumeAudioMixing(): Promise { + return AgoraRtcEngineModule.resumeAudioMixing(); } - /** - * adjust recording signal volume - * - * This method adjusts recording your signal by volume. - * @param volume - * @return Promise - */ - public static adjustRecordingSignalVolume(volume: number): Promise { - return Agora.adjustRecordingSignalVolume(volume); + setAudioMixingPitch(pitch: number): Promise { + return AgoraRtcEngineModule.setAudioMixingPitch(pitch); } - /** - * adjust playback signal volume - * - * This method adjusts playback signal by volume. - * @param volume - * @return Promise - */ - public static adjustPlaybackSignalVolume(volume: number): Promise { - return Agora.adjustPlaybackSignalVolume(volume); + setAudioMixingPosition(pos: number): Promise { + return AgoraRtcEngineModule.setAudioMixingPosition(pos); } - /** - * enable audio volume indication - * - * This method enables audio volume by interval and smooth - * @param interval - * @param smooth - * @param vad - * @return Promise - */ - public static enableAudioVolumeIndication(interval: number, smooth: number, vad: boolean): Promise { - return Agora.enableAudioVolumeIndication(interval, smooth, vad); + startAudioMixing(filePath: string, loopback: boolean, replace: boolean, cycle: number): Promise { + return AgoraRtcEngineModule.startAudioMixing(filePath, loopback, replace, cycle); } - /** - * check for mobile phone speaker enabled - * - * This method checks the phone speaker is enabled - * @param callback - * @return any - */ - public static isSpeakerphoneEnabled(callback: Callback): any { - return Agora.isSpeakerphoneEnabled(callback); + stopAudioMixing(): Promise { + return AgoraRtcEngineModule.stopAudioMixing(); } - /** - * enable in-ear monitor - * - * This method enables in-ear monitoring by boolean parameter enabled - * - * @param enabled - * @return Promise - */ - public static enableInEarMonitoring(enabled: boolean): Promise { - return Agora.enableInEarMonitoring(enabled); + getEffectsVolume(): Promise { + return AgoraRtcEngineModule.getEffectsVolume(); } - /** - * set in-ear monitoring volume - * - * This method sets the in-ear-monitoring volume by number parameter volume - * - * @param volume - * @return Promise - */ - public static setInEarMonitoringVolume(volume: number): Promise { - return Agora.setInEarMonitoringVolume(volume); + pauseAllEffects(): Promise { + return AgoraRtcEngineModule.pauseAllEffects(); } - /** - * set local voice pitch - * - * This method sets the local voice pitch by float parameter pitch - * - * @param pitch - * @return Promise - */ - public static setLocalVoicePitch(pitch: number): Promise { - return Agora.setLocalVoicePitch(pitch); + pauseEffect(soundId: number): Promise { + return AgoraRtcEngineModule.pauseEffect(soundId); } - /** - * set local voice equalization - * - * This method set local video equalization of band frequency by enum band number and number of gain - * - * @param band - * @param gain - * @return Promise - */ - public static setLocalVoiceEqualization(band: number, gain: number) { - Agora.setLocalVoiceEqualization(band, gain); + playEffect(soundId: number, filePath: String, loopCount: number, pitch: number, pan: number, gain: number, publish: Boolean): Promise { + return AgoraRtcEngineModule.playEffect(soundId, filePath, loopCount, pitch, pan, gain, publish); } - /** - * set local voice reverb - * - * This method sets local voice by reverb and value - * @param reverb - * @param value - */ - public static setLocalVoiceReverb(reverb: number, value: number) { - Agora.setLocalVoiceReverb(reverb, value); + preloadEffect(soundId: number, filePath: String): Promise { + return AgoraRtcEngineModule.preloadEffect(soundId, filePath); } - /** - * start audio mixing - * - * This method will start audio mixing by option config - * - * @param options {@link AudioMixingOption} - */ - public static startAudioMixing(options: AudioMixingOption) { - Agora.startAudioMixing(options); + resumeAllEffects(): Promise { + return AgoraRtcEngineModule.resumeAllEffects(); } - /** - * stop audio mixing - * - * This methods stops for audio mixing. - */ - public static stopAudioMixing() { - Agora.stopAudioMixing(); + resumeEffect(soundId: number): Promise { + return AgoraRtcEngineModule.resumeEffect(soundId); } - /** - * pause audio mixing - * - * This method pauses for audio mixing. - */ - public static pauseAudioMixing() { - Agora.pauseAudioMixing(); + setEffectsVolume(volume: number): Promise { + return AgoraRtcEngineModule.setEffectsVolume(volume); } - /** - * resume audio mixing - * - * This method resumes for audio mixing. - */ - public static resumeAudioMixing() { - Agora.resumeAudioMixing(); + setVolumeOfEffect(soundId: number, volume: number): Promise { + return AgoraRtcEngineModule.setVolumeOfEffect(soundId, volume); } - /** - * adjust audio mixing volume - * - * This method adjusts audio mixing volume by the volume number parameter - * @param volume - */ - public static adjustAudioMixingVolume(volume: number) { - Agora.adjustAudioMixingVolume(volume); + stopAllEffects(): Promise { + return AgoraRtcEngineModule.stopAllEffects(); } - /** - * adjust audio mixing playout volume - * - * This method adjusts audio mixing playout by the volume parameter - * @param volume - */ - public static adjustAudioMixingPlayoutVolume(volume: number) { - Agora.adjustAudioMixingPlayoutVolume(volume); + stopEffect(soundId: number): Promise { + return AgoraRtcEngineModule.stopEffect(soundId); } - /** - * adjust audio mixing publish volume - * - * This method adjusts audio mixing publish by the volume paraemter - * @param volume - */ - public static adjustAudioMixingPublishVolume(volume: number) { - Agora.adjustAudioMixingPublishVolume(volume); + unloadEffect(soundId: number): Promise { + return AgoraRtcEngineModule.unloadEffect(soundId); } - /** - * get audio mixing duration - * - * This method gets the audio mixing duration - * @return Promise<{success, value}> - */ - public static getAudioMixingDuration(): Promise { - return Agora.getAudioMixingDuration(); + setLocalVoiceChanger(voiceChanger: AudioVoiceChanger): Promise { + return AgoraRtcEngineModule.setLocalVoiceChanger(voiceChanger); } - /** - * get audio mixing current position - * - * This method gets audio mixing current position value. - * @return Promise<{success, value}> - */ - public static getAudioMixingCurrentPosition(): Promise { - return Agora.getAudioMixingCurrentPosition(); + setLocalVoiceEqualization(bandFrequency: AudioEqualizationBandFrequency, bandGain: number): Promise { + return AgoraRtcEngineModule.setLocalVoiceEqualization(bandFrequency, bandGain); } - /** - * set audio mixing position - * - * This method sets audio mixing position by the parameter pos - * @param pos - */ - public static setAudioMixingPosition(pos: number): Promise { - return Agora.setAudioMixingPosition(pos); + setLocalVoicePitch(pitch: number): Promise { + return AgoraRtcEngineModule.setLocalVoicePitch(pitch); } - /** - * get effects of volume - * - * This methods get audio mixing effects volume value. - * @return Promise<{success, value}> - */ - public static getEffectsVolume(): Promise { - return Agora.getEffectsVolume(); + setLocalVoiceReverb(reverbKey: AudioReverbType, value: number): Promise { + return AgoraRtcEngineModule.setLocalVoiceReverb(reverbKey, value); } - /** - * set effects volume - * - * This methods set audio mixing effects volume by float parameter. - * @param volume - * @return Promise<{success, value}> - */ - public static setEffectsVolume(volume: number): Promise { - return Agora.setEffectsVolume(volume); + setLocalVoiceReverbPreset(preset: AudioReverbPreset): Promise { + return AgoraRtcEngineModule.setLocalVoiceReverbPreset(preset); } - /** - * set volume for playing effects. - * - * This methods set for playing audio mixing effects - * @return Promise<{success, value}> - */ - public static setVolumeOfEffect(volume: number): Promise { - return Agora.setVolumeOfEffect(volume); + enableSoundPositionIndication(enabled: boolean): Promise { + return AgoraRtcEngineModule.enableSoundPositionIndication(enabled); } - /** - * play specified effect for audio mixing - * - * This methos plays the specified effect of audio mixing file by option config. - * @param options {@link PlayEffectOption} - * @return Promise<{success, value}> - */ - public static playEffect(options: PlayEffectOption): Promise { - return Agora.playEffect(options); + setRemoteVoicePosition(uid: number, pan: number, gain: number): Promise { + return AgoraRtcEngineModule.setRemoteVoicePosition(uid, pan, gain); + } + + addPublishStreamUrl(url: string, transcodingEnabled: boolean): Promise { + return AgoraRtcEngineModule.addPublishStreamUrl(url, transcodingEnabled); } + removePublishStreamUrl(url: string): Promise { + return AgoraRtcEngineModule.removePublishStreamUrl(url); + } + + setLiveTranscoding(transcoding: LiveTranscoding): Promise { + return AgoraRtcEngineModule.setLiveTranscoding(transcoding); + } + + startChannelMediaRelay(channelMediaRelayConfiguration: ChannelMediaRelayConfiguration): Promise { + return AgoraRtcEngineModule.startChannelMediaRelay(channelMediaRelayConfiguration); + } + + stopChannelMediaRelay(): Promise { + return AgoraRtcEngineModule.stopChannelMediaRelay(); + } + + updateChannelMediaRelay(channelMediaRelayConfiguration: ChannelMediaRelayConfiguration): Promise { + return AgoraRtcEngineModule.updateChannelMediaRelay(channelMediaRelayConfiguration); + } + + isSpeakerphoneEnabled(): Promise { + return AgoraRtcEngineModule.isSpeakerphoneEnabled(); + } + + setDefaultAudioRoutetoSpeakerphone(defaultToSpeaker: boolean): Promise { + return AgoraRtcEngineModule.setDefaultAudioRoutetoSpeakerphone(defaultToSpeaker); + } + + setEnableSpeakerphone(enabled: boolean): Promise { + return AgoraRtcEngineModule.setEnableSpeakerphone(enabled); + } + + enableInEarMonitoring(enabled: boolean): Promise { + return AgoraRtcEngineModule.enableInEarMonitoring(enabled); + } + + setInEarMonitoringVolume(volume: number): Promise { + return AgoraRtcEngineModule.setInEarMonitoringVolume(volume); + } + + enableDualStreamMode(enabled: boolean): Promise { + return AgoraRtcEngineModule.enableDualStreamMode(enabled); + } + + setRemoteDefaultVideoStreamType(streamType: VideoStreamType): Promise { + return AgoraRtcEngineModule.setRemoteDefaultVideoStreamType(streamType); + } + + setRemoteVideoStreamType(uid: number, streamType: VideoStreamType): Promise { + return AgoraRtcEngineModule.setRemoteVideoStreamType(uid, streamType); + } + + setLocalPublishFallbackOption(option: StreamFallbackOptions): Promise { + return AgoraRtcEngineModule.setLocalPublishFallbackOption(option); + } + + setRemoteSubscribeFallbackOption(option: StreamFallbackOptions): Promise { + return AgoraRtcEngineModule.setRemoteSubscribeFallbackOption(option); + } + + setRemoteUserPriority(uid: number, userPriority: UserPriority): Promise { + return AgoraRtcEngineModule.setRemoteUserPriority(uid, userPriority); + } + + disableLastmileTest(): Promise { + return AgoraRtcEngineModule.disableLastmileTest(); + } + + enableLastmileTest(): Promise { + return AgoraRtcEngineModule.enableLastmileTest(); + } + + startEchoTest(intervalInSeconds: number): Promise { + return AgoraRtcEngineModule.startEchoTest(intervalInSeconds); + } + + startLastmileProbeTest(config: LastmileProbeConfig): Promise { + return AgoraRtcEngineModule.startLastmileProbeTest(config); + } + + stopEchoTest(): Promise { + return AgoraRtcEngineModule.stopEchoTest(); + } + + stopLastmileProbeTest(): Promise { + return AgoraRtcEngineModule.stopLastmileProbeTest(); + } + + registerMediaMetadataObserver(): Promise { + return AgoraRtcEngineModule.registerMediaMetadataObserver(); + } + + sendMetadata(metadata: string): Promise { + return AgoraRtcEngineModule.sendMetadata(metadata); + } + + setMaxMetadataSize(size: number): Promise { + return AgoraRtcEngineModule.setMaxMetadataSize(size); + } + + unregisterMediaMetadataObserver(): Promise { + return AgoraRtcEngineModule.unregisterMediaMetadataObserver(); + } + + addVideoWatermark(watermarkUrl: string, options: WatermarkOptions): Promise { + return AgoraRtcEngineModule.addVideoWatermark(watermarkUrl, options); + } + + clearVideoWatermarks(): Promise { + return AgoraRtcEngineModule.clearVideoWatermarks(); + } + + setEncryptionMode(encryptionMode: EncryptionMode): Promise { + return AgoraRtcEngineModule.setEncryptionMode(encryptionMode); + } + + setEncryptionSecret(secret: string): Promise { + return AgoraRtcEngineModule.setEncryptionSecret(secret); + } + + startAudioRecording(filePath: string, sampleRate: AudioSampleRateType, quality: AudioRecordingQuality): Promise { + return AgoraRtcEngineModule.startAudioRecording(filePath, sampleRate, quality); + } + + stopAudioRecording(): Promise { + return AgoraRtcEngineModule.stopAudioRecording(); + } + + addInjectStreamUrl(url: string, config: LiveInjectStreamConfig): Promise { + return AgoraRtcEngineModule.addInjectStreamUrl(url, config); + } + + removeInjectStreamUrl(url: string): Promise { + return AgoraRtcEngineModule.removeInjectStreamUrl(url); + } + + enableFaceDetection(enable: boolean): Promise { + return AgoraRtcEngineModule.enableFaceDetection(enable) + } + + getCameraMaxZoomFactor(): Promise { + return AgoraRtcEngineModule.getCameraMaxZoomFactor(); + } + + isCameraAutoFocusFaceModeSupported(): Promise { + return AgoraRtcEngineModule.isCameraAutoFocusFaceModeSupported(); + } + + isCameraExposurePositionSupported(): Promise { + return AgoraRtcEngineModule.isCameraExposurePositionSupported(); + } + + isCameraFocusSupported(): Promise { + return AgoraRtcEngineModule.isCameraFocusSupported(); + } + + isCameraTorchSupported(): Promise { + return AgoraRtcEngineModule.isCameraTorchSupported(); + } + + isCameraZoomSupported(): Promise { + return AgoraRtcEngineModule.isCameraZoomSupported(); + } + + setCameraAutoFocusFaceModeEnabled(enabled: boolean): Promise { + return AgoraRtcEngineModule.setCameraAutoFocusFaceModeEnabled(enabled); + } + + setCameraCapturerConfiguration(config: CameraCapturerConfiguration): Promise { + return AgoraRtcEngineModule.setCameraCapturerConfiguration(config); + } + + setCameraExposurePosition(positionXinView: number, positionYinView: number): Promise { + return AgoraRtcEngineModule.setCameraExposurePosition(positionXinView, positionYinView); + } + + setCameraFocusPositionInPreview(positionX: number, positionY: number): Promise { + return AgoraRtcEngineModule.setCameraFocusPositionInPreview(positionX, positionY); + } + + setCameraTorchOn(isOn: boolean): Promise { + return AgoraRtcEngineModule.setCameraTorchOn(isOn); + } + + setCameraZoomFactor(factor: number): Promise { + return AgoraRtcEngineModule.setCameraZoomFactor(factor); + } + + switchCamera(): Promise { + return AgoraRtcEngineModule.switchCamera(); + } + + createDataStream(reliable: boolean, ordered: boolean): Promise { + return AgoraRtcEngineModule.createDataStream(reliable, ordered); + } + + sendStreamMessage(streamId: number, message: string): Promise { + return AgoraRtcEngineModule.sendStreamMessage(streamId, message); + } +} + +interface RtcUserInfoInterface { /** - * stop play effect for audio mixing - * - * This methods stops the specified effect for audio mixing file by soundId. - * @param sounid - * @return Promise<{success, value}> + * Registers a user account. + * Once registered, the user account can be used to identify the local user when the user joins the channel. After the user successfully registers a user account, the SDK triggers the onLocalUserRegistered callback on the local client, reporting the user ID and user account of the local user. + * @see RtcEngineEvents.LocalUserRegistered + * To join a channel with a user account, you can choose either of the following: + * - Call the registerLocalUserAccount method to create a user account, and then the joinChannelWithUserAccount method to join the channel. + * @see RtcEngine.registerLocalUserAccount + * - Call the joinChannelWithUserAccount method to join the channel. + * @see RtcEngine.joinChannelWithUserAccount + * The difference between the two is that for the former, the time elapsed between calling the joinChannelWithUserAccount method and joining the channel is shorter than the latter. + * Note + * - Ensure that you set the userAccount parameter. Otherwise, this method does not take effect. + * - Ensure that the value of the userAccount parameter is unique in the channel. + * - To ensure smooth communication, use the same parameter type to identify the user. For example, if a user joins the channel with a user ID, then ensure all the other users use the user ID too. The same applies to the user account. If a user joins the channel with the Agora Web SDK, ensure that the uid of the user is set to the same parameter type. + * @param appId The App ID of your project. + * @param userAccount The user account. The maximum length of this parameter is 255 bytes. Ensure that you set this parameter and do not set it as null. Supported character scopes are: + * - All lowercase English letters: a to z. + * - All uppercase English letters: A to Z. + * - All numeric characters: 0 to 9. + * - The space character. + * - Punctuation characters and other symbols, including: "!", "#", "$", "%", "&", "(", ")", "+", "-", ":", ";", "<", "=", ".", ">", "?", "@", "[", "]", "^", "_", " {", "}", "|", "~", ",". + */ + registerLocalUserAccount(appId: string, userAccount: string): Promise; + + /** + * Joins the channel with a user account. + * After the user successfully joins the channel, the SDK triggers the following callbacks: + * - The local client: onLocalUserRegistered and onJoinChannelSuccess. + * @see RtcEngineEvents.LocalUserRegistered + * @see RtcEngineEvents.JoinChannelSuccess + * - The remote client: onUserJoined and onUserInfoUpdated, if the user joining the channel is in the Communication profile, or is a BROADCASTER in the Live Broadcast profile. + * @see RtcEngineEvents.UserJoined + * @see RtcEngineEvents.UserInfoUpdated + * Note + * - To ensure smooth communication, use the same parameter type to identify the user. For example, if a user joins the channel with a user ID, then ensure all the other users use the user ID too. The same applies to the user account. If a user joins the channel with the Agora Web SDK, ensure that the uid of the user is set to the same parameter type. + * @param token The token generated at your server: + * - In situations not requiring high security: You can use the temporary token generated at Console. For details, see Get a temporary token. + * - In situations requiring high security: Set it as the token generated at your server. For details, see Generate a token. + * @param channelName The channel name. The maximum length of this parameter is 64 bytes. Supported character scopes are: + * - All lowercase English letters: a to z. + * - All uppercase English letters: A to Z. + * - All numeric characters: 0 to 9. + * - The space character. + * - Punctuation characters and other symbols, including: "!", "#", "$", "%", "&", "(", ")", "+", "-", ":", ";", "<", "=", ".", ">", "?", "@", "[", "]", "^", "_", " {", "}", "|", "~", ",". + * @param userAccount The user account. The maximum length of this parameter is 255 bytes. Ensure that you set this parameter and do not set it as null. + * - All lowercase English letters: a to z. + * - All uppercase English letters: A to Z. + * - All numeric characters: 0 to 9. + * - The space character. + * - Punctuation characters and other symbols, including: "!", "#", "$", "%", "&", "(", ")", "+", "-", ":", ";", "<", "=", ".", ">", "?", "@", "[", "]", "^", "_", " {", "}", "|", "~", ",". + */ + joinChannelWithUserAccount(token: String, channelName: string, userAccount: string): Promise; + + /** + * Gets the user information by passing in the user account. + * After a remote user joins the channel, the SDK gets the user ID and user account of the remote user, caches them in a mapping table object (UserInfo), and triggers the onUserInfoUpdated callback on the local client. + * @see UserInfo + * @see RtcEngineEvents.UserInfoUpdated + * After receiving the onUserInfoUpdated callback, you can call this method to get the user ID of the remote user from the userInfo object by passing in the user account. + * @param userAccount The user account of the user. Ensure that you set this parameter. */ - public static stopEffect(soundId: number): Promise { - return Agora.stopEffect(soundId); - } + getUserInfoByUserAccount(userAccount: string): Promise; /** - * stop play all for effect audio mixing. - * - * This methods stops all effect audio mixing. - * @return Promise<{success, value}> + * Gets the user information by passing in the user ID. + * After a remote user joins the channel, the SDK gets the user ID and user account of the remote user, caches them in a mapping table object (UserInfo), and triggers the onUserInfoUpdated callback on the local client. + * @see UserInfo + * @see RtcEngineEvents.UserInfoUpdated + * After receiving the onUserInfoUpdated callback, you can call this method to get the user ID of the remote user from the userInfo object by passing in the user account. + * @param uid The user ID of the user. Ensure that you set this parameter. */ - public static stopAllEffects(): Promise { - return Agora.stopAllEffects(); - } + getUserInfoByUid(uid: number): Promise; +} +interface RtcAudioInterface { + /** + * Enables the audio module. + * The audio module is enabled by default. + * Note + * - This method affects the internal engine and can be called after calling the leaveChannel method. You can call this method either before or after joining a channel. + * @see RtcEngine.leaveChannel + * - This method resets the internal engine and takes some time to take effect. We recommend using the following API methods to control the audio engine modules separately: + * -- enableLocalAudio: Whether to enable the microphone to create the local audio stream. + * @see RtcEngine.enableLocalAudio + * -- muteLocalAudioStream: Whether to publish the local audio stream. + * @see RtcEngine.muteLocalAudioStream + * -- muteRemoteAudioStream: Whether to subscribe to and play the remote audio stream. + * @see RtcEngine.muteRemoteAudioStream + * -- muteAllRemoteAudioStreams: Whether to subscribe to and play all remote audio streams. + * @see RtcEngine.muteAllRemoteAudioStreams + */ + enableAudio(): Promise; + + /** + * Disables the audio module. + * Note + * - This method affects the internal engine and can be called after calling the leaveChannel method. You can call this method either before or after joining a channel. + * @see RtcEngine.leaveChannel + * - This method resets the engine and takes some time to take effect. We recommend using the following API methods to control the audio engine modules separately: + * -- enableLocalAudio: Whether to enable the microphone to create the local audio stream. + * @see RtcEngine.enableLocalAudio + * -- muteLocalAudioStream: Whether to publish the local audio stream. + * @see RtcEngine.muteLocalAudioStream + * -- muteRemoteAudioStream: Whether to subscribe to and play the remote audio stream. + * @see RtcEngine.muteRemoteAudioStream + * -- muteAllRemoteAudioStreams: Whether to subscribe to and play all remote audio streams. + * @see RtcEngine.muteAllRemoteAudioStreams + */ + disableAudio(): Promise; + + /** + * Sets the audio parameters and application scenarios. + * Note + * - You must call this method before calling the joinChannel method. + * @see RtcEngine.joinChannel + * - In the Communication and Live Broadcast profiles, the bitrates may be different from your settings due to network self-adaptation. + * - In scenarios requiring high-quality audio, we recommend setting profile as ShowRoom(4) and scenario as GameStreaming(3). For example, for music education scenarios. + * @see AudioScenario.ShowRoom + * @see AudioScenario.GameStreaming + * @param profile Sets the sample rate, bitrate, encoding mode, and the number of channels. + * @see AudioProfile + * @param scenario Sets the audio application scenarios. Under different audio scenarios, the device uses different volume tracks, i.e. either the in-call volume or the media volume. + * @see AudioScenario + */ + setAudioProfile(profile: AudioProfile, scenario: AudioScenario): Promise; + + /** + * Adjusts the recording volume. + * Note + * - To avoid echoes and improve call quality, Agora recommends setting the value of volume between 0 and 100. If you need to set the value higher than 100, contact support@agora.io first. + * @param volume Recording volume. The value ranges between 0 and 400: + * - 0: Mute. + * - 100: Original volume. + * - 400: (Maximum) Four times the original volume with signal-clipping protection. + */ + adjustRecordingSignalVolume(volume: number): Promise; + + /** + * Adjusts the playback volume of a specified remote user. + * You can call this method as many times as necessary to adjust the playback volume of different remote users, or to repeatedly adjust the playback volume of the same remote user. + * Note + * - Call this method after joining a channel. + * - The playback volume here refers to the mixed volume of a specified remote user. + * - This method can only adjust the playback volume of one specified remote user at a time. To adjust the playback volume of different remote users, call the method as many times, once for each remote user. + * @param uid ID of the remote user. + * @param volume The playback volume of the specified remote user. The value ranges from 0 to 100: + * - 0: Mute. + * - 100: The original volume. + */ + adjustUserPlaybackSignalVolume(uid: number, volume: number): Promise; + + /** + * Adjusts the playback volume of all remote users. + * Note + * - This method adjusts the playback volume which is mixed volume of all remote users. + * - To mute the local audio playback, call both adjustPlaybackSignalVolume and adjustAudioMixingVolume, and set volume as 0. + * @see RtcEngine.adjustPlaybackSignalVolume + * @see RtcEngine.adjustAudioMixingVolume + * - To avoid echoes and improve call quality, Agora recommends setting the value of volume between 0 and 100. If you need to set the value higher than 100, contact support@agora.io first. + * @param volume The playback volume of all remote users. The value ranges from 0 to 400: + * - 0: Mute. + * - 100: The original volume. + * - 400: (Maximum) Four times the original volume with signal clipping protection. + */ + adjustPlaybackSignalVolume(volume: number): Promise; + + /** + * Enables/Disables the local audio capture. + * The audio function is enabled by default. This method disables/re-enables the local audio function, that is, to stop or restart local audio capture and processing. + * This method does not affect receiving or playing the remote audio streams, and enableLocalAudio(false) is applicable to scenarios where the user wants to receive remote audio streams without sending any audio stream to other users in the channel. + * The SDK triggers the onMicrophoneEnabled callback once the local audio function is disabled or re-enabled. + * @see RtcEngineEvents.MicrophoneEnabled + * Note + * - This method is different from the muteLocalAudioStream method: + * -- enableLocalAudio: Disables/Re-enables the local audio capture and processing. If you disable or re-enable local audio recording using the enableLocalAudio method, the local user may hear a pause in the remote audio playback. + * @see RtcEngine.enableLocalAudio + * -- muteLocalAudioStream: Stops/Continues sending the local audio streams. + * @see RtcEngine.muteLocalAudioStream + * @param enabled Sets whether to disable/re-enable the local audio function: + * - true: (Default) Re-enable the local audio function, that is, to start local audio capture and processing. + * - false: Disable the local audio function, that is, to stop local audio capture and processing. + */ + enableLocalAudio(enabled: boolean): Promise; + + /** + * Stops/Resumes sending the local audio stream. + * A successful muteLocalAudioStream method call triggers the onUserMuteAudio callback on the remote client. + * @see RtcEngineEvents.UserMuteAudio + * Note + * - When muted is set as true, this method does not disable the microphone and thus does not affect any ongoing recording. + * - If you call setChannelProfile after this method, the SDK resets whether or not to mute the local audio according to the channel profile and user role. Therefore, we recommend calling this method after the setChannelProfile method. + * @see RtcEngine.setChannelProfile + * @param muted Sets whether to send/stop sending the local audio stream: + * - true: Stop sending the local audio stream. + * - false: (Default) Send the local audio stream. + */ + muteLocalAudioStream(muted: boolean): Promise; + + /** + * Stops/Resumes receiving a specified audio stream. + * Note + * - If you called the muteAllRemoteAudioStreams method and set muted as true to stop receiving all remote video streams, ensure that the muteAllRemoteAudioStreams method is called and set muted as false before calling this method. The muteAllRemoteAudioStreams method sets all remote audio streams, while the muteRemoteAudioStream method sets a specified remote user's audio stream. + * @see RtcEngine.muteAllRemoteAudioStreams + * @param uid ID of the specified remote user. + * @param muted Sets whether to receive/stop receiving the specified remote user's audio stream: + * - true: Stop receiving the specified remote user’s audio stream. + * - false: (Default) Receive the specified remote user’s audio stream. + */ + muteRemoteAudioStream(uid: number, muted: boolean): Promise; + + /** + * Stops/Resumes receiving all remote audio streams. + * @param muted Sets whether to receive/stop receiving all remote audio streams: + * - true: Stop receiving all remote audio streams. + * - false: (Default) Receive all remote audio streams. + */ + muteAllRemoteAudioStreams(muted: boolean): Promise; + + /** + * Sets whether to receive all remote audio streams by default. + * You can call this method either before or after joining a channel. If you call setDefaultMuteAllRemoteAudioStreams(true) after joining a channel, you will not receive the audio streams of any subsequent user. + * Note + * - If you want to resume receiving audio streams, call muteRemoteAudioStream(false), and specify the ID of the remote user that you want to subscribe to. To resume audio streams of multiple users, call muteRemoteAudioStream as many times. Calling setDefaultMuteAllRemoteAudioStreams(false) resumes receiving audio streams of the subsequent users only. + * @see RtcEngine.muteRemoteAudioStream + * @param muted Sets whether or not to receive/stop receiving the remote audio streams by default: + * - true: Stop receiving any audio stream by default. + * - false: (Default) Receive all remote audio streams by default. + */ + setDefaultMuteAllRemoteAudioStreams(muted: boolean): Promise; + + /** + * Enables the onAudioVolumeIndication callback at a set time interval to report on which users are speaking and the speakers' volume. + * @see RtcEngineEvents.AudioVolumeIndication + * Once this method is enabled, the SDK returns the volume indication in the onAudioVolumeIndication callback at the set time interval, regardless of whether any user is speaking in the channel. + * @param interval Sets the time interval between two consecutive volume indications: + * - ≤ 0: Disables the volume indication. + * - > 0: Time interval (ms) between two consecutive volume indications. We recommend setting interval ≥ 200 ms. + * @param smooth The smoothing factor sets the sensitivity of the audio volume indicator. The value ranges between 0 and 10. The greater the value, the more sensitive the indicator. The recommended value is 3. + * @param report_vad + * - true: Enable the voice activity detection of the local user. Once it is enabled, the vad parameter of the onAudioVolumeIndication callback reports the voice activity status of the local user. + * - false: (Default) Disable the voice activity detection of the local user. Once it is enabled, the vad parameter of the onAudioVolumeIndication callback does not report the voice activity status of the local user, except for scenarios where the engine automatically detects the voice activity of the local user. + */ + enableAudioVolumeIndication(interval: number, smooth: number, report_vad: boolean): Promise; +} + +interface RtcVideoInterface { + /** + * Enables the video module. + * You can call this method either before joining a channel or during a call. If you call this method before joining a channel, the service starts in the video mode. If you call this method during an audio call, the audio mode switches to the video mode. + * A successful enableVideo method call triggers the onUserEnableVideo(true) callback on the remote client. + * @see RtcEngineEvents.UserEnableVideo + * To disable the video, call the disableVideo method. + * @see RtcEngine.disableVideo + * Note + * - This method affects the internal engine and can be called after calling the leaveChannel method. You can call this method either before or after joining a channel. + * @see RtcEngine.leaveChannel + * - This method resets the internal engine and takes some time to take effect. We recommend using the following API methods to control the video engine modules separately: + * -- enableLocalVideo: Whether to enable the camera to create the local video stream. + * @see RtcEngine.enableLocalVideo + * -- muteLocalVideoStream: Whether to publish the local video stream. + * @see RtcEngine.muteLocalVideoStream + * -- muteRemoteVideoStream: Whether to subscribe to and play the remote video stream. + * @see RtcEngine.muteRemoteVideoStream + * -- muteAllRemoteVideoStreams: Whether to subscribe to and play all remote video streams. + * @see RtcEngine.muteAllRemoteVideoStreams + */ + enableVideo(): Promise; + + /** + * Disables the video module. + * You can call this method before joining a channel or during a call. If you call this method before joining a channel, the service starts in audio mode. If you call this method during a video call, the video mode switches to the audio mode. + * - A successful disableVideo method call triggers the onUserEnableVideo(false) callback on the remote client. + * @see RtcEngineEvents.UserEnableVideo + * - To enable the video mode, call the enableVideo method. + * @see RtcEngine.enableVideo + * Note + * - This method affects the internal engine and can be called after calling the leaveChannel method. You can call this method either before or after joining a channel. + * @see RtcEngine.leaveChannel + * - This method resets the internal engine and takes some time to take effect. We recommend using the following API methods to control the video engine modules separately: + * -- enableLocalVideo: Whether to enable the camera to create the local video stream. + * @see RtcEngine.enableLocalVideo + * -- muteLocalVideoStream: Whether to publish the local video stream. + * @see RtcEngine.muteLocalVideoStream + * -- muteRemoteVideoStream: Whether to subscribe to and play the remote video stream. + * @see RtcEngine.muteRemoteVideoStream + * -- muteAllRemoteVideoStreams: Whether to subscribe to and play all remote video streams. + * @see RtcEngine.muteAllRemoteVideoStreams + */ + disableVideo(): Promise; + + /** + * Sets the video encoder configuration. + * Each video encoder configuration corresponds to a set of video parameters, including the resolution, frame rate, bitrate, and video orientation. The parameters specified in this method are the maximum values under ideal network conditions. If the video engine cannot render the video using the specified parameters due to poor network conditions, the parameters further down the list are considered until a successful configuration is found. + * If you do not set the video encoder configuration after joining the channel, you can call this method before calling the enableVideo method to reduce the render time of the first video frame. + * @see RtcEngine.enableVideo + * @param config The local video encoder configuration. + * @see VideoEncoderConfiguration + */ + setVideoEncoderConfiguration(config: VideoEncoderConfiguration): Promise; + + /** + * Disables/Re-enables the local video capture. + * This method disables or re-enables the local video capturer, and does not affect receiving the remote video stream. + * After you call the enableVideo method, the local video capturer is enabled by default. You can call enableLocalVideo(false) to disable the local video capturer. If you want to re-enable it, call enableLocalVideo(true). + * @see RtcEngine.enableVideo + * After the local video capturer is successfully disabled or re-enabled, the SDK triggers the onUserEnableLocalVideo callback on the remote client. + * @see RtcEngineEvents.UserEnableLocalVideo + * Note + * - This method affects the internal engine and can be called after calling the leaveChannel method. + * @param enabled Sets whether to disable/re-enable the local video, including the capturer, renderer, and sender: + * - true: (Default) Re-enable the local video. + * - false: Disable the local video. Once the local video is disabled, the remote users can no longer receive the video stream of this user, while this user can still receive the video streams of other remote users. When you set enabled as false, this method does not require a local camera. + */ + enableLocalVideo(enabled: boolean): Promise; + + /** + * Stops/Resumes sending the local video stream. + * A successful muteLocalVideoStream method call triggers the onUserMuteVideo callback on the remote client. + * @see RtcEngineEvents.UserMuteVideo + * Note + * - When you set muted as true, this method does not disable the camera and thus does not affect the retrieval of the local video streams. This method responds faster than calling the enableLocalVideo method and set muted as false, which controls sending the local video stream. + * @see RtcEngine.enableLocalVideo + * - If you call setChannelProfile after this method, the SDK resets whether or not to mute the local video according to the channel profile and user role. Therefore, we recommend calling this method after the setChannelProfile method. + * @see RtcEngine.setChannelProfile + * @param muted Sets whether to send/stop sending the local video stream: + * - true: Stop sending the local video stream. + * - false: (Default) Send the local video stream. + */ + muteLocalVideoStream(muted: boolean): Promise; + + /** + * Stops/Resumes receiving a specified remote user's video stream. + * Note + * - If you call the muteAllRemoteVideoStreams method and set set muted as true to stop receiving all remote video streams, ensure that the muteAllRemoteVideoStreams method is called and set muted as false before calling this method. The muteAllRemoteVideoStreams method sets all remote streams, while this method sets a specified remote user's stream. + * @see RtcEngine.muteAllRemoteVideoStreams + * @param uid User ID of the specified remote user. + * @param muted Sets whether to receive/stop receiving a specified remote user's video stream: + * - true: Stop receiving a specified remote user’s video stream. + * - false: (Default) Receive a specified remote user’s video stream. + */ + muteRemoteVideoStream(uid: number, muted: boolean): Promise; + + /** + * Stops/Resumes receiving all remote video streams. + * @param muted Sets whether to receive/stop receiving all remote video streams: + * - true: Stop receiving all remote video streams. + * - false: (Default) Receive all remote video streams. + */ + muteAllRemoteVideoStreams(muted: boolean): Promise; + + /** + * Sets whether to receive all remote video streams by default. + * You can call this method either before or after joining a channel. If you call setDefaultMuteAllRemoteVideoStreams(true) after joining a channel, you will not receive the video stream of any subsequent user. + * Note + * - If you want to resume receiving video streams, call muteRemoteVideoStream(false), and specify the ID of the remote user that you want to subscribe to. To resume receiving video streams of multiple users, call muteRemoteVideoStream as many times. Calling setDefaultMuteAllRemoteVideoStreams(false) resumes receiving video streams of the subsequent users only. + * @see RtcEngine.muteRemoteVideoStream + * @param muted Sets whether to receive/stop receiving all remote video streams by default: + * - true: Stop receiving any remote video stream by default. + * - false: (Default) Receive all remote video streams by default. + */ + setDefaultMuteAllRemoteVideoStreams(muted: boolean): Promise; + + /** + * Enables/Disables image enhancement and sets the options. + * Note + * - Call this method after calling enableVideo. + * - This method applies to Android 4.4 or later. + * @param enabled Sets whether or not to enable image enhancement: + * - enables image enhancement. + * - disables image enhancement. + * @param options The image enhancement options. + * @see BeautyOptions + */ + setBeautyEffectOptions(enabled: boolean, options: BeautyOptions): Promise; +} + +interface RtcAudioMixingInterface { /** - * preload effect for audio mixing file. - * - * This methods preloads the specified audio mixing file to memory by the soundId - * @param soundId - * @param filePath - * @return Promise<{success, value}> + * Starts playing and mixing the music file. + * This method mixes the specified local or online audio file with the audio stream from the microphone, or replaces the microphone’s audio stream with the specified local or remote audio file. You can choose whether the other user can hear the local audio playback and specify the number of playback loops. When the audio mixing file playback finishes after calling this method, the SDK triggers the onAudioMixingFinished callback. + * @see RtcEngineEvents.AudioMixingFinished + * A successful startAudioMixing method call triggers the onAudioMixingStateChanged(Playing) callback on the local client. + * @see RtcEngineEvents.AudioMixingStateChanged + * @see AudioMixingStateCode.Playing + * When the audio mixing file playback finishes, the SDK triggers the onAudioMixingStateChanged(Stopped) callback on the local client. + * @see RtcEngineEvents.AudioMixingStateChanged + * @see AudioMixingStateCode.Stopped + * Note + * - To use this method, ensure that the Android device is v4.2 or later, and the API version is v16 or later. + * - Call this method when you are in the channel, otherwise it may cause issues. + * - If you want to play an online music file, ensure that the time interval between calling this method is more than 100 ms, or the TooFrequentCall = 702 error occurs. + * @see AudioMixingErrorCode.TooFrequentCall + * - If you want to play an online music file, Agora does not recommend using the redirected URL address. Some Android devices may fail to open a redirected URL address. + * - If the local audio mixing file does not exist, or if the SDK does not support the file format or cannot access the music file URL, the SDK returns CanNotOpen = 701. + * @see AudioMixingErrorCode.CanNotOpen + * - If you call this method on an emulator, only the MP3 file format is supported. + * @param filePath Specifies the absolute path (including the suffixes of the filename) of the local or online audio file to be mixed. For example, /sdcard/emulated/0/audio.mp4. Supported audio formats: mp3, mp4, m4a, aac, 3gp, mkv, and wav. + * - If the path begins with /assets/, the audio file is in the /assets/ directory. + * - Otherwise, the audio file is in the absolute path. + * @param loopback Sets which user can hear the audio mixing: + * - true: Only the local user can hear the audio mixing. + * - false: Both users can hear the audio mixing. + * @param replace Sets the audio mixing content: + * - true: Only publish the specified audio file; the audio stream from the microphone is not published. + * - false: The local audio file is mixed with the audio stream from the microphone. + * @param cycle Sets the number of playback loops: + * - Positive integer: Number of playback loops + * - -1: Infinite playback loops */ - public static preloadEffect(soundId: number, filePath: string): Promise { - return Agora.preloadEffect(soundId, filePath); - } + startAudioMixing(filePath: string, loopback: boolean, replace: boolean, cycle: number): Promise; /** - * unload effect - * - * This methods unload the already loaded audio mixing file from memory by the soundId. - * @param soundId - * @return Promise<{success, value}> + * Stops playing or mixing the music file. + * Call this method when you are in a channel. */ - public static unloadEffect(soundId: number): Promise { - return Agora.unloadEffect(soundId); - } + stopAudioMixing(): Promise; /** - * pause the specified effect for audio mixing by soundId - * - * This method pauses the specified effect for audio mixing by soundId. - * @param soundId - * @return Promise<{success, value}> + * Pauses playing and mixing the music file. + * Call this method when you are in a channel. */ - public static pauseEffect(soundId: number): Promise { - return Agora.pauseEffect(soundId); - } + pauseAudioMixing(): Promise; /** - * pause all effects for audio mixing - * - * This method pause all effects for audio mixing. - * @param soundId - * @return Promise<{success, value}> + * Resumes playing and mixing the music file. + * Call this method when you are in a channel. */ - public static pauseAllEffects(): Promise { - return Agora.pauseAllEffects(); - } + resumeAudioMixing(): Promise; /** - * resume audio mixing effect by the specified soundId - * - * This method resumes audio mixing effect by the specified soundId - * @param soundId - * @return Promise<{success, value}> + * Adjusts the volume of audio mixing. + * Call this method when you are in a channel. + * Note + * - Calling this method does not affect the volume of the audio effect file playback invoked by the playEffect method. + * @see RtcEngine.playEffect + * @param volume Audio mixing volume. The value ranges between 0 and 100 (default). */ - public static resumeEffect(soundId: number): Promise { - return Agora.resumeEffect(soundId); - } + adjustAudioMixingVolume(volume: number): Promise; /** - * resume all audio mixing effects. - * - * This method resumes all audio mixing effects. - * @return Promise<{success, value}> + * Adjusts the volume of audio mixing for local playback. + * Call this method when you are in a channel. + * @param volume Audio mixing volume for local playback. The value ranges between 0 and 100 (default). */ - public static resumeAllEffects(): Promise { - return Agora.resumeAllEffects(); - } + adjustAudioMixingPlayoutVolume(volume: number): Promise; /** - * start audio recording by quality - * - * This method start audio recording by quality config - * @param options {@link AudioRecordingOption} - * @return Promise<{success, value}> + * Adjusts the volume of audio mixing for publishing (sending to other users). + * Call this method when you are in a channel. + * @param volume Audio mixing volume for publishing. The value ranges between 0 and 100 (default). */ - public static startAudioRecording(options: AudioRecordingOption): Promise { - return Agora.startAudioRecording(options); - } + adjustAudioMixingPublishVolume(volume: number): Promise; /** - * stop audio recording - * - * This method stops audio recording. - * @return Promise<{success, value}> + * Gets the audio mixing volume for local playback. + * This method helps troubleshoot audio volume related issues. */ - public static stopAudioRecording(): Promise { - return Agora.stopAudioRecording(); - } + getAudioMixingPlayoutVolume(): Promise; /** - * set audio session operation restriction - * - * The SDK and the app can both configure the audio session by default. The app may occasionally use other apps or third-party components to manipulate the audio session and restrict the SDK from doing so. This method allows the app to restrict the SDK’s manipulation of the audio session. - * You can call this method at any time to return the control of the audio sessions to the SDK. - * This method restricts the SDK’s manipulation of the audio session. Any operation to the audio session relies solely on the app, other apps, or third-party components. - * @notice iOS support only + * Gets the audio mixing volume for publishing. + * This method helps troubleshoot audio volume related issues. */ - public static setAudioSessionOperationRestriction() { - if (Platform.OS != 'ios') throw Error(`setAudioSessionOperationRestriction is not support on your platform. Please check the details in react-native-agora docs`); - Agora.setAudioSessionOperationRestriction(); - } + getAudioMixingPublishVolume(): Promise; /** - * @deprecated startEchoTest - * startEchoTest + * Gets the duration (ms) of the music file. + * Call this method when you are in a channel. */ + getAudioMixingDuration(): Promise; /** - * @deprecated isCameraAutoFocusFaceModeSupported - * @deprecated isCameraExposurePositionSupported - * @deprecated isCameraFocusSupported - * @deprecated isCameraTorchSupported - * @deprecated isCameraZoomSupported - * instead use {@method getCameraInfo} + * Gets the playback position (ms) of the music file. + * Call this method when you are in a channel. */ + getAudioMixingCurrentPosition(): Promise; /** - * stop echo test - * - * This method stop launched an audio call test. - * @return Promise<{success, value}> + * Sets the playback position (ms) of the music file to a different starting position (the default plays from the beginning). + * @param pos The playback starting position (ms) of the audio mixing file. */ - public static stopEchoTest(): Promise { - return Agora.stopEchoTest(); - } + setAudioMixingPosition(pos: number): Promise; /** - * enable lastmile test - * - * This method enables the network connection qualit test. - * - * @return Promise<{success, value}> + * Sets the pitch of the local music file. + * When a local music file is mixed with a local human voice, call this method to set the pitch of the local music file only. + * Note + * - Call this method after calling startAudioMixing. + * @see RtcEngine#startAudioMixing + * @param pitch Sets the pitch of the local music file by chromatic scale. The default value is 0, which means keep the original pitch. The value ranges from -12 to 12, and the pitch value between consecutive values is a chromatic value. The greater the absolute value of this parameter, the higher or lower the pitch of the local music file. */ - public static enableLastmileTest(): Promise { - return Agora.enableLastmileTest(); - } + setAudioMixingPitch(pitch: number): Promise; +} +interface RtcAudioEffectInterface { /** - * disable lastmile test - * - * This method disable the network connection qualit test. - * - * @return Promise<{success, value}> + * Gets the volume of the audio effects. + * The value ranges between 0.0 and 100.0. */ - public static disableLastmileTest(): Promise { - return Agora.disableLastmileTest(); - } + getEffectsVolume(): Promise; /** - * set recording audio frame parameters - * - * This method Sets the audio recording format for the audioFrame callback. - * - * @param options {@link RecordingAudioFrameOption} - * @return Promise<{success, value}> + * Sets the volume of the audio effects. + * @param volume Volume of the audio effects. The value ranges between 0.0 and 100.0 (default). */ - public static setRecordingAudioFrameParameters(options: AudioFrameOption): Promise { - return Agora.setRecordingAudioFrameParameters(options); - } + setEffectsVolume(volume: number): Promise; /** - * set playback audio frame parameters - * - * This method Sets the audio frame format for the playbackFrame callback. - * - * @param options {@link AudioFrameOption} - * @return Promise<{success, value}> + * Sets the volume of a specified audio effect. + * @param soundId ID of the audio effect. Each audio effect has a unique ID. + * @param volume Volume of the audio effect. The value ranges between 0.0 and 100.0 (default). */ - public static setPlaybackAudioFrameParameters(options: AudioFrameOption): Promise { - return Agora.setPlaybackAudioFrameParameters(options); - } + setVolumeOfEffect(soundId: number, volume: number): Promise; /** - * set mixed audio frame parameters - * - * This method Sets the audio frame format for the mixedAudioFrame callback. - * - * @param options {@link MixedAudioFrameOption} - * @return Promise<{success, value}> + * Plays a specified local or online audio effect file. + * With this method, you can set the loop count, pitch, pan, and gain of the audio effect file and whether the remote user can hear the audio effect. + * To play multiple audio effect files simultaneously, call this method multiple times with different soundIds and filePaths. We recommend playing no more than three audio effect files at the same time. + * When the audio effect file playback is finished, the SDK triggers the onAudioEffectFinished callback. + * @see RtcEngineEvents.AudioEffectFinished + * @param soundId ID of the specified audio effect. Each audio effect has a unique ID. If you preloaded the audio effect into the memory through the preloadEffect method, ensure that the soundID value is set to the same value as in the preloadEffect method. + * @see RtcEngine.preloadEffect + * @param filePath The absolute file path (including the suffixes of the filename) of the audio effect file or the URL of the online audio effect file. For example, /sdcard/emulated/0/audio.mp4. Supported audio formats: mp3, mp4, m4a, aac. 3gp, mkv, and wav. + * @param loopCount Sets the number of times the audio effect loops: + * - 0: Plays the audio effect once. + * - 1: Plays the audio effect twice. + * - -1: Plays the audio effect in a loop indefinitely, until you call the stopEffect or stopAllEffects method. + * @see RtcEngine.stopEffect + * @see RtcEngine.stopAllEffects + * @param pitch Sets the pitch of the audio effect. The value ranges between 0.5 and 2. The default value is 1 (no change to the pitch). The lower the value, the lower the pitch. + * @param pan Sets the spatial position of the audio effect. The value ranges between -1.0 and 1.0. + * - 0.0: The audio effect shows ahead. + * - 1.0: The audio effect shows on the right. + * - -1.0: The audio effect shows on the left. + * @param gain Sets the volume of the audio effect. The value ranges between 0.0 and 100,0. The default value is 100.0. The lower the value, the lower the volume of the audio effect. + * @param publish Set whether or not to publish the specified audio effect to the remote stream: + * - true: The locally played audio effect is published to the Agora Cloud and the remote users can hear it. + * - false: The locally played audio effect is not published to the Agora Cloud and the remote users cannot hear it. */ - public static setMixedAudioFrameParameters(options: MixedAudioFrameOption): Promise { - return Agora.setMixedAudioFrameParameters(options); - } + playEffect(soundId: number, filePath: String, loopCount: number, pitch: number, pan: number, gain: number, publish: Boolean): Promise; /** - * add video watermark - * - * This method adds video watermark to the local video. - * - * @param options {@link ImageOption} - * @return Promise<{success, value}> + * Stops playing a specified audio effect. + * Note + * - If you preloaded the audio effect into the memory through the preloadEffect method, ensure that the soundID value is set to the same value as in the preloadEffect method. + * @see RtcEngine.preloadEffect + * @param soundId ID of the specified audio effect. Each audio effect has a unique ID. */ - public static addVideoWatermark(url: string, options: ImageOption): Promise { - return Agora.addVideoWatermark({url, options}); - } + stopEffect(soundId: number): Promise; /** - * clear video watermarks - * - * This method removes the watermark image from the video stream added by addVideoWatermark. - * - * @return Promise<{success, value}> + * Stops playing all audio effects. */ - public static clearVideoWatermarks(): Promise { - return Agora.clearVideoWatermarks(); - } + stopAllEffects(): Promise; /** - * set local publish fallback - * - * This method sets the fallback option for the locally published video stream based on the network conditions. - * - * @param option {0, 1, 2} [more details](https://docs.agora.io/en/Video/API%20Reference/java/classio_1_1agora_1_1rtc_1_1_constants.html#a3e453c93766e783a7e5eca05b1776238) - * @return Promise<{success, value}> + * Preloads a specified audio effect file into the memory. + * Supported audio formats: mp3, aac, m4a, 3gp, wav. + * Note + * - This method does not support online audio effect files. + * Note + * - To ensure smooth communication, limit the size of the audio effect file. We recommend using this method to preload the audio effect before calling the joinChannel method. + * @see RtcEngine.joinChannel + * @param soundId ID of the audio effect. Each audio effect has a unique ID. + * @param filePath Absolute path of the audio effect file. */ - public static setLocalPublishFallbackOption(option: number): Promise { - return Agora.setLocalPublishFallbackOption(option); - } + preloadEffect(soundId: number, filePath: String): Promise; /** - * set remote publish fallback - * - * This method sets the fallback option for the remotely subscribed video stream based on the network conditions. - * - * @param option {0, 1, 2} [more details](https://docs.agora.io/en/Video/API%20Reference/java/classio_1_1agora_1_1rtc_1_1_constants.html#a3e453c93766e783a7e5eca05b1776238) - * @return Promise<{success, value}> + * Releases a specified preloaded audio effect from the memory. + * @param soundId ID of the audio effect. Each audio effect has a unique ID. */ - public static setRemoteSubscribeFallbackOption(option: number): Promise { - return Agora.setRemoteSubscribeFallbackOption(option); - } + unloadEffect(soundId: number): Promise; /** - * enable dual stream mode - * - * This method enables the dual stream by parameter mode. - * - * @param enabled - * @return Promise<{success, value}> + * Pauses a specified audio effect. + * @param soundId ID of the audio effect. Each audio effect has a unique ID. */ - public static enableDualStreamMode(enabled: boolean): Promise { - return Agora.enableDualStreamMode(enabled); - } + pauseEffect(soundId: number): Promise; /** - * set remote video stream type - * - * This method sets the remote video stream type by uid and streamType. - * - * @param options {@link VideoStreamOption} - * @return Promise<{success, value}> + * Pauses all audio effects. */ - public static setRemoteVideoStreamType(options: VideoStreamOption): Promise { - return Agora.setRemoteVideoStreamType(options); - } + pauseAllEffects(): Promise; /** - * set remote default video stream type - * - * This method sets the default video stream type. - * - * @param options {@link DefaultVideoStreamOption} - * @return Promise<{success, value}> + * Resumes playing a specified audio effect. + * @param soundId ID of the audio effect. Each audio effect has a unique ID. */ - public static setRemoteDefaultVideoStreamType(options: DefaultVideoStreamOption): Promise { - return Agora.setRemoteDefaultVideoStreamType(options); - } + resumeEffect(soundId: number): Promise; /** - * add inject stream url - * - * This method injects an online media stream to a live broadcast. - * - * @param options {@link InjectStreamOption} - * @return Promise<{success, value}> + * Resumes playing all audio effects. */ - public static addInjectStreamUrl(options: InjectStreamOption): Promise { - return Agora.addInjectStreamUrl(options); - } + resumeAllEffects(): Promise; +} +interface RtcVoiceChangerInterface { /** - * remove inject stream url - * - * This method removes stream by addInjectsStreamUrl. - * - * @param options {@link RemoveInjectStreamOption} - * @return Promise<{success, value}> + * Sets the local voice changer option. + * Note + * - Do not use this method together with setLocalVoiceReverbPreset, or the method called earlier does not take effect. + * @see RtcEngine.setLocalVoiceReverbPreset + * @param voiceChanger The local voice changer option. + * @see AudioVoiceChanger */ - public static removeInjectStreamUrl(options: RemoveInjectStreamOption): Promise { - return Agora.removeInjectStreamUrl(options); - } + setLocalVoiceChanger(voiceChanger: AudioVoiceChanger): Promise; /** - * @deprecated sendMessage - * sendMessage + * Sets the preset local voice reverberation effect + * Note + * - Do not use this method together with setLocalVoiceReverb. + * @see RtcEngine.setLocalVoiceReverb + * - Do not use this method together with setLocalVoiceChanger, or the method called eariler does not take effect. + * @see RtcEngine.setLocalVoiceChanger + * @param preset The local voice reverberation preset + * @see AudioReverbPreset */ - static async sendMessage(): Promise { - return console.warn("sendMessage already deprecated"); - } + setLocalVoiceReverbPreset(preset: AudioReverbPreset): Promise; /** - * @deprecated createDataStream - * createDataStream + * Changes the voice pitch of the local speaker. + * @param pitch Sets the voice pitch. The value ranges between 0.5 and 2.0. The lower the value, the lower the voice pitch. The default value is 1.0 (no change to the local voice pitch). */ + setLocalVoicePitch(pitch: number): Promise; /** - * @deprecated setupLocalVideo - * setupLocalVideo + * Sets the local voice equalization effect. + * @param bandFrequency Sets the band frequency. The value ranges between 0 and 9; representing the respective 10-band center frequencies of the voice effects, including 31, 62, 125, 500, 1k, 2k, 4k, 8k, and 16k Hz. + * @see AudioEqualizationBandFrequency + * @param bandGain Sets the gain of each band (dB). The value ranges between -15 and 15. The default value is 0. */ + setLocalVoiceEqualization(bandFrequency: AudioEqualizationBandFrequency, bandGain: number): Promise; /** - * @deprecated setupRemoteVideo - * setupRemoteVideo + * Sets the local voice reverberation. + * Note + * - Adds the setLocalVoiceReverbPreset method, a more user-friendly method for setting the local voice reverberation. You can use this method to set the local reverberation effect, such as Popular, R&B, Rock, Hip-hop, and more. + * @see RtcEngine.setLocalVoiceReverbPreset + * @param reverbKey Sets the reverberation key. This method contains five reverberation keys. For details, see the description of each @ value. + * @see AudioReverbType + * @param value Sets the local voice reverberation value. */ + setLocalVoiceReverb(reverbKey: AudioReverbType, value: number): Promise; +} + +interface RtcVoicePositionInterface { + /** + * Enables/Disables stereo panning for remote users. + * Ensure that you call this method before joinChannel to enable stereo panning for remote users so that the local user can track the position of a remote user by calling setRemoteVoicePosition. + * @see RtcEngine.joinChannel + * @see RtcEngine.setRemoteVoicePosition + * @param enabled Sets whether or not to enable stereo panning for remote users: + * - true: enables stereo panning. + * - false: disables stereo panning. + */ + enableSoundPositionIndication(enabled: boolean): Promise; + + /** + * Sets the sound position of a remote user. + * When the local user calls this method to set the sound position of a remote user, the sound difference between the left and right channels allows the local user to track the real-time position of the remote user, creating a real sense of space. This method applies to massively multiplayer online games, such as Battle Royale games. + * Note + * - For this method to work, enable stereo panning for remote users by calling the enableSoundPositionIndication method before joining a channel. + * @see RtcEngine.enableSoundPositionIndication + * - This method requires hardware support. For the best sound positioning, we recommend using a stereo headset. + * @param uid The ID of the remote user. + * @param pan The sound position of the remote user. The value ranges from -1.0 to 1.0: + * - 0.0: The remote sound comes from the front. + * - -1.0: The remote sound comes from the left. + * - 1.0: The remote sound comes from the right. + * @param gain Gain of the remote user. The value ranges from 0.0 to 100.0. The default value is 100.0 (the original gain of the remote user). The smaller the value, the less the gain. + */ + setRemoteVoicePosition(uid: number, pan: number, gain: number): Promise; +} +interface RtcPublishStreamInterface { + /** + * Sets the video layout and audio settings for CDN live. + * The SDK triggers the onTranscodingUpdated callback when you call this method to update the LiveTranscodingclass. If you call this method to set the LiveTranscoding class for the first time, the SDK does not trigger the onTranscodingUpdated callback. + * @see RtcEngineEvents.TranscodingUpdated + * Note + * - Before calling the methods listed in this section: + * -- This method applies to Live Broadcast only. + * -- Ensure that you enable the RTMP Converter service before using this function. See Prerequisites. + * -- Ensure that you call the setClientRole method and set the user role as the host. + * @see RtcEngine.setClientRole + * -- Ensure that you call the setLiveTranscoding method before calling the addPublishStreamUrl method. + * @see RtcEngine.addPublishStreamUrl + * @param transcoding Sets the CDN live audio/video transcoding settings. + * @see LiveTranscoding + */ + setLiveTranscoding(transcoding: LiveTranscoding): Promise; + + /** + * Publishes the local stream to the CDN. + * The addPublishStreamUrl method call triggers the onRtmpStreamingStateChanged callback on the local client to report the state of adding a local stream to the CDN. + * @see RtcEngineEvents.RtmpStreamingStateChanged + * Note + * - Ensure that you enable the RTMP Converter service before using this function. See Prerequisites. + * - This method applies to Live Broadcast only. + * - Ensure that the user joins a channel before calling this method. + * - This method adds only one stream HTTP/HTTPS URL address each time it is called. + * @param url The CDN streaming URL in the RTMP format. The maximum length of this parameter is 1024 bytes. The URL address must not contain special characters, such as Chinese language characters. + * @param transcodingEnabled Sets whether transcoding is enabled/disabled. If you set this parameter as true, ensure that you call the setLiveTranscoding method before this method. + * @see RtcEngine.setLiveTranscoding + * - true: Enable transcoding. To transcode the audio or video streams when publishing them to CDN live, often used for combining the audio and video streams of multiple hosts in CDN live. + * - false: Disable transcoding. + */ + addPublishStreamUrl(url: string, transcodingEnabled: boolean): Promise; + + /** + * Removes an RTMP stream from the CDN. + * This method removes the RTMP URL address (added by addPublishStreamUrl) from a CDN live stream. The SDK reports the result of this method call in the onRtmpStreamingStateChanged callback. + * @see RtcEngine.addPublishStreamUrl + * @see RtcEngineEvents.RtmpStreamingStateChanged + * Note + * - Ensure that you enable the RTMP Converter service before using this function. See Prerequisites. + * - Ensure that the user joins a channel before calling this method. + * - This method applies to Live Broadcast only. + * - This method removes only one stream RTMP URL address each time it is called. + * @param url The RTMP URL address to be removed. The maximum length of this parameter is 1024 bytes. The URL address must not contain special characters, such as Chinese language characters. + */ + removePublishStreamUrl(url: string): Promise; +} +interface RtcMediaRelayInterface { /** - * @deprecated setVideoQualityParameters - * setVideoQualityParameters - */ + * Starts to relay media streams across channels. + * After a successful method call, the SDK triggers the onChannelMediaRelayStateChanged and onChannelMediaRelayEvent callbacks, and these callbacks return the state and events of the media stream relay. + * @see RtcEngineEvents.ChannelMediaRelayStateChanged + * @see RtcEngineEvents.ChannelMediaRelayEvent + * - If the onChannelMediaRelayStateChanged callback returns Running(2) and None(0), and the onChannelMediaRelayEvent callback returns SentToDestinationChannel(4), the SDK starts relaying media streams between the original and the destination channel. + * @see ChannelMediaRelayState.Running + * @see ChannelMediaRelayError.None + * @see ChannelMediaRelayEvent.SentToDestinationChannel + * - If the onChannelMediaRelayStateChanged callback returns Failure(3), an exception occurs during the media stream relay. + * @see ChannelMediaRelayState.Failure + * Note + * - Contact sales-us@agora.io before implementing this function. + * - We do not support string user accounts in this API. + * - Call this method after the joinChannel method. + * @see RtcEngine.joinChannel + * - This method takes effect only when you are a broadcaster in a Live-broadcast channel. + * - After a successful method call, if you want to call this method again, ensure that you call the stopChannelMediaRelay method to quit the current relay. + * @see RtcEngine.stopChannelMediaRelay + * @param channelMediaRelayConfiguration The configuration of the media stream relay. + * @see ChannelMediaRelayConfiguration + */ + startChannelMediaRelay(channelMediaRelayConfiguration: ChannelMediaRelayConfiguration): Promise; + + /** + * Updates the channels for media relay. + * After the channel media relay starts, if you want to relay the media stream to more channels, or leave the current relay channel, you can call the updateChannelMediaRelay method. + * After a successful method call, the SDK triggers the onChannelMediaRelayEvent callback with the UpdateDestinationChannel(7) state code. + * @see RtcEngineEvents.ChannelMediaRelayEvent + * @see ChannelMediaRelayEvent.UpdateDestinationChannel + * Note + * - Call this method after the startChannelMediaRelay method to update the destination channel. + * @see RtcEngine.startChannelMediaRelay + * - This method supports adding at most four destination channels in the relay. If there are already four destination channels in the relay. + * @param channelMediaRelayConfiguration The media stream relay configuration + * @see ChannelMediaRelayConfiguration + */ + updateChannelMediaRelay(channelMediaRelayConfiguration: ChannelMediaRelayConfiguration): Promise; + + /** + * Stops the media stream relay. + * Once the relay stops, the broadcaster quits all the destination channels. + * After a successful method call, the SDK triggers the onChannelMediaRelayStateChanged callback. If the callback returns Idle(0) and None(0), the broadcaster successfully stops the relay. + * @see RtcEngineEvents.ChannelMediaRelayStateChanged + * @see ChannelMediaRelayState.Idle + * @see ChannelMediaRelayError.None + * Note + * - If the method call fails, the SDK triggers the onChannelMediaRelayStateChanged callback with the ServerNoResponse(2) or ServerConnectionLost(8) state code. You can leave the channel by calling the leaveChannel method, and the media stream relay automatically stops. + * @see RtcEngineEvents.ChannelMediaRelayStateChanged + * @see ChannelMediaRelayError.ServerNoResponse + * @see ChannelMediaRelayError.ServerConnectionLost + * @see RtcEngine.leaveChannel + */ + stopChannelMediaRelay(): Promise; +} + +interface RtcAudioRouteInterface { + /** + * Sets the default audio playback route. + * This method sets whether the received audio is routed to the earpiece or speakerphone by default before joining a channel. If a user does not call this method, the audio is routed to the earpiece by default. If you need to change the default audio route after joining a channel, call the setEnableSpeakerphone method. + * @see RtcEngine.setEnableSpeakerphone + * The default audio route for each scenario: + * - In the Communication profile: + * @see ChannelProfile.Communication + * -- For a voice call, the default audio route is the earpiece. + * -- For a video call, the default audio route is the speaker. If the user disables the video using disableVideo, or muteLocalVideoStream and muteAllRemoteVideoStreams, the default audio route automatically switches back to the earpiece. + * @see RtcEngine.disableVideo + * @see RtcEngine.muteLocalVideoStream + * @see RtcEngine.muteAllRemoteVideoStreams + * - In the Live Broadcast profile: The default audio route is the speaker. + * @see ChannelProfile.LiveBroadcasting + * Note + * - This method applies to the Communication profile only. + * - Call this method before the user joins a channel. + * @param defaultToSpeaker Sets the default audio route: + * - true: Route the audio to the speaker. If the playback device connects to the earpiece or Bluetooth, the audio cannot be routed to the earpiece. + * - false: (Default) Route the audio to the earpiece. If a headset is plugged in, the audio is routed to the headset. + */ + setDefaultAudioRoutetoSpeakerphone(defaultToSpeaker: boolean): Promise; + + /** + * Enables/Disables the audio playback route to the speakerphone. + * This method sets whether the audio is routed to the speakerphone or earpiece. After calling this method, the SDK returns the onAudioRouteChanged callback to indicate the changes. + * @see RtcEngineEvents.AudioRouteChanged + * Note + * - Ensure that you have successfully called the joinChannel method before calling this method. + * @see RtcEngine.joinChannel + * - This method is invalid for audience users in the Live Broadcast profile. + * @see ChannelProfile.LiveBroadcasting + * @param enabled Sets whether to route the audio to the speakerphone or earpiece: + * - true: Route the audio to the speakerphone. + * - false: Route the audio to the earpiece. If the headset is plugged in, the audio is routed to the headset. + */ + setEnableSpeakerphone(enabled: boolean): Promise; + + /** + * Checks whether the speakerphone is enabled. + */ + isSpeakerphoneEnabled(): Promise; +} +interface RtcEarMonitoringInterface { /** - * set local video mirror mode - * - * This method sets local video mirror mode - * - * @param mode - * @return Promise<{success, value}> + * Enables in-ear monitoring. + * @param enabled Sets whether to enable/disable in-ear monitoring: + * - true: Enable. + * - false: (Default) Disable. */ - public static setLocalVideoMirrorMode(mode: number): Promise { - return Agora.setLocalVideoMirrorMode(mode); - } + enableInEarMonitoring(enabled: boolean): Promise; /** - * switch camera - * - * This method switches camera between front and rear. - * - * @return Promise<{success, value}> + * Sets the volume of the in-ear monitor. + * @param volume Sets the volume of the in-ear monitor. The value ranges between 0 and 100 (default). */ - public static switchCamera(): Promise { - return Agora.switchCamera(); - } + setInEarMonitoringVolume(volume: number): Promise; +} +interface RtcDualStreamInterface { /** - * set camera zoom ratio - * - * This method sets the camera zoom ratio. - * - * @param zoomFactor - * @return Promise<{success, value}> + * Enables/Disables the dual video stream mode. + * If dual-stream mode is enabled, the receiver can choose to receive the high stream (high-resolution high-bitrate video stream) or low stream (low-resolution low-bitrate video stream) video. + * @param enabled Sets the stream mode: + * - true: Dual-stream mode. + * - false: (Default) Single-stream mode. */ - public static setCameraZoomFactor(zoomFactor: number): Promise { - return Agora.setCameraZoomFactor(zoomFactor); - } + enableDualStreamMode(enabled: boolean): Promise; /** - * get camera max zoom ratio - * - * This method gets the camera maximum zoom ratio. - * - * @notice Android Only - * @return Promise<{success, value}> + * Sets the stream type of the remote video. + * Under limited network conditions, if the publisher has not disabled the dual-stream mode using enableDualStreamMode(false), the receiver can choose to receive either the high-video stream (the high resolution, and high bitrate video stream) or the low-video stream (the low resolution, and low bitrate video stream). + * @see RtcEngine.enableDualStreamMode + * By default, users receive the high-video stream. Call this method if you want to switch to the low-video stream. This method allows the app to adjust the corresponding video stream type based on the size of the video window to reduce the bandwidth and resources. + * The aspect ratio of the low-video stream is the same as the high-video stream. Once the resolution of the high-video stream is set, the system automatically sets the resolution, frame rate, and bitrate of the low-video stream. + * The SDK reports the result of calling this method in the onApiCallExecuted callback. + * @see RtcEngineEvents.ApiCallExecuted + * @param uid ID of the remote user sending the video stream. + * @param streamType Sets the video-stream type. + * @see VideoStreamType */ - public static getCameraMaxZoomFactor(): Promise { - return Agora.getCameraMaxZoomFactor(); - } + setRemoteVideoStreamType(uid: number, streamType: VideoStreamType): Promise; /** - * set camera focus position in preview - * - * This method sets the mannual focus position. - * - * @param options {@link PositionOption} - * @return Promise<{success, value}> + * Sets the default video-stream type of the remotely subscribed video stream when the remote user sends dual streams. + * @param streamType Sets the default video-stream type. + * @see VideoStreamType */ - public static setCameraFocusPositionInPreview(options: PositionOption): Promise { - return Agora.setCameraFocusPositionInPreview(options); - } + setRemoteDefaultVideoStreamType(streamType: VideoStreamType): Promise; +} +interface RtcFallbackInterface { /** - * set camera exposure position - * - * This method sets the mannual exposure position. - * - * @param options {@link PositionOption} - * @return Promise<{success, value}> + * Sets the fallback option for the locally published video stream based on the network conditions. + * If option is set as AudioOnly(2), the SDK will: + * @see StreamFallbackOptions.AudioOnly + * - Disable the upstream video but enable audio only when the network conditions deteriorate and cannot support both video and audio. + * - Re-enable the video when the network conditions improve. + * When the locally published video stream falls back to audio only or when the audio-only stream switches back to the video, the SDK triggers the onLocalPublishFallbackToAudioOnly. + * @see RtcEngineEvents.LocalPublishFallbackToAudioOnly + * Note + * - Agora does not recommend using this method for CDN live streaming, because the remote CDN live user will have a noticeable lag when the locally published video stream falls back to audio only. + * @param option Sets the fallback option for the locally published video stream. + * @see StreamFallbackOptions */ - public static setCameraExposurePosition(options: PositionOption): Promise { - return Agora.setCameraExposurePosition(options); - } + setLocalPublishFallbackOption(option: StreamFallbackOptions): Promise; /** - * set camera torch on - * - * This method enables the camera flash function. - * - * @param enabled - * @return Promise<{success, value}> + * Sets the fallback option for the remotely subscribed video stream based on the network conditions. + * If option is set as AudioOnly(2), the SDK automatically switches the video from a high-stream to a low-stream, or disables the video when the downlink network condition cannot support both audio and video to guarantee the quality of the audio. The SDK monitors the network quality and restores the video stream when the network conditions improve. When the remotely subscribed video stream falls back to audio only, or the audio-only stream switches back to the video, the SDK triggers the onRemoteSubscribeFallbackToAudioOnly callback. + * @see StreamFallbackOptions.AudioOnly + * @see RtcEngineEvents.RemoteSubscribeFallbackToAudioOnly + * @param option Sets the fallback option for the remotely subscribed video stream. + * @see StreamFallbackOptions */ - public static setCameraTorchOn(enabled: boolean): Promise { - return Agora.setCameraTorchOn(enabled); - } + setRemoteSubscribeFallbackOption(option: StreamFallbackOptions): Promise; /** - * set enable auto focus face mode - * - * This method enables auto-focus face mode function. - * - * @param enabled boolean - * @return Promise<{success, value}> + * Sets the priority of a remote user's media stream. + * Use this method with the setRemoteSubscribeFallbackOption method. If the fallback function is enabled for a subscribed stream, the SDK ensures the high-priority user gets the best possible stream quality. + * @see RtcEngine.setRemoteSubscribeFallbackOption + * Note + * - The Agora SDK supports setting userPriority as high for one user only. + * @param uid The ID of the remote user. + * @param userPriority The priority of the remote user. + * @see UserPriority */ - public static setCameraAutoFocusFaceModeEnabled(enabled: boolean): Promise { - return Agora.setCameraAutoFocusFaceModeEnabled(enabled); - } + setRemoteUserPriority(uid: number, userPriority: UserPriority): Promise; +} +interface RtcTestInterface { /** - * get call id - * - * This method is used to get call id. - * - * @return Promise<{success, value}> + * Starts an audio call test. + * In the audio call test, you record your voice. If the recording plays back within the set time interval, the audio devices and the network connection are working properly. + * Note + * - Call this method before joining a channel. + * - After calling this method, call the stopEchoTest method to end the test. Otherwise, the app cannot run the next echo test, or call the joinChannel method. + * @see RtcEngine.stopEchoTest + * @see RtcEngine.joinChannel + * - In the Live Broadcast profile, only a host can call this method. + * @param intervalInSeconds The time interval (s) between when you speak and when the recording plays back. */ - public static getCallId(): Promise { - return Agora.getCallId(); - } + startEchoTest(intervalInSeconds: number): Promise; /** - * set log file and log filter - * - * This method sets the log file generated path and specified the log level. - * - * @param filePath string - * @param level enum - * @param maxfileSize integer (KB) - * @return Promise<{success, value}> + * Stops the audio call test. */ - public static setLog(filePath: string, level: number, maxfileSize: number): Promise { - return Agora.setLog(filePath, level, maxfileSize) - } + stopEchoTest(): Promise; /** - * add publish stream url - * - * This method add publish stream by option. - * - * @param options {@link PublishStreamOption} - * @return Promise<{success, value}> + * Enables the network connection quality test. + * This method tests the quality of the users' network connections and is disabled by default. + * Before users join a channel or before an audience switches to a host, call this method to check the uplink network quality. This method consumes additional network traffic, which may affect the communication quality. Call the disableLastmileTest method to disable this test after receiving the onLastmileQuality callback, and before the user joins a channel or switches the user role. + * @see RtcEngine.disableLastmileTest + * @see RtcEngineEvents.LastmileQuality + * Note + * - Do not use this method with the startLastmileProbeTest method. + * @see RtcEngine.startLastmileProbeTest + * - Do not call any other methods before receiving the onLastmileQuality callback. Otherwise, the callback may be interrupted by other methods and may not execute. + * @see RtcEngineEvents.LastmileQuality + * - In the Live Broadcast profile, a host should not call this method after joining a channel. + * - If you call this method to test the last-mile quality, the SDK consumes the bandwidth of a video stream, whose bitrate corresponds to the bitrate you set in the setVideoEncoderConfiguration method. After you join the channel, whether you have called the disableLastmileTest method or not, the SDK automatically stops consuming the bandwidth. + * @see RtcEngine.setVideoEncoderConfiguration + * @see RtcEngine.disableLastmileTest */ - public static addPublishStreamUrl(options: PublishStreamOption): Promise { - return Agora.addPublishStreamUrl(options); - } + enableLastmileTest(): Promise; /** - * remove publish stream url - * - * This method remove publish stream by options. - * - * @param options {@link RemovePublishStreamOption} - * @return Promise<{success, value}> + * Disables the network connection quality test. */ - public static removePublishStreamUrl(options: RemovePublishStreamOption): Promise { - return Agora.removePublishStreamUrl(options); - } + disableLastmileTest(): Promise; /** - * set live transcoding - * - * This method sets the video layout and audio settings for CDN live. - * - * @param options {@link LiveTranscoding} - * @return Promise<{success, value}> + * Starts the last-mile network probe test before joining a channel to get the uplink and downlink last-mile network statistics, including the bandwidth, packet loss, jitter, and round-trip time (RTT). + * Once this method is enabled, the SDK returns the following callbacks: + * - onLastmileQuality: the SDK triggers this callback within two seconds depending on the network conditions. This callback rates the network conditions with a score and is more closely linked to the user experience. + * @see RtcEngineEvents.LastmileQuality + * - onLastmileProbeResult: the SDK triggers this callback within 30 seconds depending on the network conditions. This callback returns the real-time statistics of the network conditions and is more objective. + * @see RtcEngineEvents.LastmileProbeResult + * Call this method to check the uplink network quality before users join a channel or before an audience switches to a host. + * Note + * - This method consumes extra network traffic and may affect communication quality. We do not recommend calling this method together with enableLastmileTest. + * @see RtcEngine.enableLastmileTest + * - Do not call other methods before receiving the onLastmileQuality and onLastmileProbeResult callbacks. Otherwise, the callbacks may be interrupted by other methods. + * - In the Live Broadcast profile, a host should not call this method after joining a channel. + * @see ChannelProfile.LiveBroadcasting + * @param config The configurations of the last-mile network probe test. + * @see LastmileProbeConfig */ - public static setLiveTranscoding(options: LiveTranscodingOption): Promise { - return Agora.setLiveTranscoding(options); - } + startLastmileProbeTest(config: LastmileProbeConfig): Promise; /** - * get sdk version - * - * This method gets the sdk version details and passed it into callback function - * - * @param callback to handle resolve from getSdkVersion - * @param errorHandler to handle reject error from getSdkVersion - * @return any + * Stops the last-mile network probe test. */ - public static getSdkVersion(callback: Callback, errorHandler?: Callback): any { - return Agora.getSdkVersion().then(callback).catch(errorHandler); - } + stopLastmileProbeTest(): Promise; +} +interface RtcMediaMetadataInterface { /** - * mute local audio stream - * - * This method sends/stops sending the local audio. - * - * @param enabled - * @return Promise + * Registers the metadata observer. + * This method enables you to add synchronized metadata in the video stream for more diversified live broadcast interactions, such as sending shopping links, digital coupons, and online quizzes. + * Note + * - Call this method before the joinChannel method. + * @see RtcEngine.joinChannel */ + registerMediaMetadataObserver(): Promise; - public static muteLocalAudioStream(enabled: boolean): Promise { - return Agora.muteLocalAudioStream(enabled); - } + /** + * TODO + */ + unregisterMediaMetadataObserver(): Promise; /** - * video pre-process/post-process - * - * This method enables/disables image enhancement and sets the options. - * - * @param enabled boolean - * @param options {@link BeautyOptions} - * @return Promise + * TODO + * @param size */ - static setBeautyEffectOptions(enabled: boolean, options: BeautyOption): Promise { - return Agora.setBeautyEffectOptions(enabled, options); - } + setMaxMetadataSize(size: number): Promise; /** - * set local voice change - * - * This method changes local speaker voice with voiceChanger - * - * @param voiceChanger integer - * @voiceChanger value ranges [ - * 0: "The original voice", - * 1: "An old man’s voice", - * 2: "A little boy’s voice.", - * 3: "A little girl’s voice.", - * 4: "TBD", - * 5: "Ethereal vocal effects.", - * 6: "Hulk’s voice." - * ] - * @return Promise + * TODO + * @param metadata */ - static setLocalVoiceChanger(voiceChanger: number): Promise { - return Agora.setLocalVoiceChanger(voiceChanger); - } + sendMetadata(metadata: string): Promise; +} + +interface RtcWatermarkInterface { + /** + * Adds a watermark image to the local video. + * This method adds a PNG watermark image to the local video stream in a live broadcast. Once the watermark image is added, all the audience in the channel (CDN audience included), and the recording device can see and capture it. + * Agora supports adding only one watermark image onto the local video, and the newly watermark image replaces the previous one. + * The watermark position depends on the settings in the setVideoEncoderConfiguration method: + * @see RtcEngine.setVideoEncoderConfiguration + * - If the orientation mode of the encoding video is FixedLandscape, or the landscape mode in Adaptative, the watermark uses the landscape orientation. + * @see VideoOutputOrientationMode.FixedLandscape + * @see VideoOutputOrientationMode.Adaptative + * - If the orientation mode of the encoding video is FixedPortrait, or the portrait mode in Adaptative, the watermark uses the portrait orientation. + * @see VideoOutputOrientationMode.FixedPortrait + * @see VideoOutputOrientationMode.Adaptative + * - When setting the watermark position, the region must be less than the dimensions set in the setVideoEncoderConfiguration method. Otherwise, the watermark image will be cropped. + * Note + * - Ensure that you have called the enableVideo method to enable the video module before calling this method. + * @see RtcEngine.enableVideo + * - If you only want to add a watermark image to the local video for the audience in the CDN live broadcast channel to see and capture, you can call this method or the setLiveTranscoding method. + * @see RtcEngine.setLiveTranscoding + * - This method supports adding a watermark image in the PNG file format only. Supported pixel formats of the PNG image are RGBA, RGB, Palette, Gray, and Alpha_gray. + * - If the dimensions the PNG image differ from your settings in this method, the image will be cropped or zoomed to conform to your settings. + * - If you have enabled the local video preview by calling the startPreview method, you can use the visibleInPreview member in the WatermarkOptions class to set whether or not the watermark is visible in preview. + * - If you have enabled the mirror mode for the local video, the watermark on the local video is also mirrored. To avoid mirroring the watermark, Agora recommends that you do not use the mirror and watermark functions for the local video at the same time. You can implement the watermark function in your application layer. + * @param watermarkUrl The local file path of the watermark image to be added. This method supports adding a watermark image from either the local file path or the assets file path. If you use the assets file path, you need to start with /assets/ when filling in this parameter. + * @param options The options of the watermark image to be added. + * @see WatermarkOptions + */ + addVideoWatermark(watermarkUrl: string, options: WatermarkOptions): Promise; + + /** + * Removes the watermark image from the video stream added by addVideoWatermark. + * @see RtcEngine.addVideoWatermark + */ + clearVideoWatermarks(): Promise; +} +interface RtcEncryptionInterface { /** - * set the preset local voice reverberation effect. - * - * This method sets the preset local voice reverberation effect. - * - * @param preset integer - * @return Promise + * Enables built-in encryption with an encryption password before joining a channel. + * All users in a channel must set the same encryption password. The encryption password is automatically cleared once a user leaves the channel. If the encryption password is not specified or set to empty, the encryption functionality is disabled. + * Note + * - For optimal transmission, ensure that the encrypted data size does not exceed the original data size + 16 bytes. 16 bytes is the maximum padding size for AES encryption. + * - Do not use this method for CDN live streaming. + * @param secret The encryption password. */ - static setLocalVoiceReverbPreset(preset: number): Promise { - return Agora.setLocalVoiceReverbPreset(preset); - } + setEncryptionSecret(secret: string): Promise; /** - * control stereo panning for remote users - * - * This method enables/disables stereo panning for remote users. - * - * @param enabled boolean - * @return Promise + * Sets the built-in encryption mode. + * The Agora SDK supports built-in encryption, which is set to aes-128-xts mode by default. Call this method to set the encryption mode to use other encryption modes. All users in the same channel must use the same encryption mode and password. + * Refer to the information related to the AES encryption algorithm on the differences between the encryption modes. + * Note + * - Call the setEncryptionSecret method before calling this method. + * @see RtcEngine.setEncryptionSecret + * @param encryptionMode Sets the encryption mode. + * @see EncryptionMode */ - static enableSoundPositionIndication(enabled: boolean): Promise { - return Agora.enableSoundPositionIndication(enabled); - } + setEncryptionMode(encryptionMode: EncryptionMode): Promise; +} + +interface RtcAudioRecorderInterface { + /** + * Starts an audio recording on the client. + * The SDK allows recording during a call. After successfully calling this method, you can record the audio of all the users in the channel and get an audio recording file. + * Supported formats of the recording file are as follows: + * - .wav: Large file size with high fidelity. + * - .aac: Small file size with low fidelity. + * Note + * - Ensure that the directory to save the recording file exists and is writable. + * - This method is usually called after calling the joinChannel method. The recording automatically stops when you call the leaveChannel method. + * @see RtcEngine.joinChannel + * @see RtcEngine.leaveChannel + * - For better recording effects, set quality as AUDIO_RECORDING_QUALITY_MEDIUM or AUDIO_RECORDING_QUALITY_HIGH when sampleRate is 44.1 kHz or 48 kHz. + * @see AudioRecordingQuality.Medium + * @see AudioRecordingQuality.High + * @param filePath Absolute file path (including the suffixes of the filename) of the recording file. The string of the file name is in UTF-8. For example, /sdcard/emulated/0/audio/aac. + * @param sampleRate Sample rate (Hz) of the recording file. Supported values are as follows. + * @see AudioSampleRateType + * @param quality The audio recording quality. + * @see AudioRecordingQuality + */ + startAudioRecording(filePath: string, sampleRate: AudioSampleRateType, quality: AudioRecordingQuality): Promise; + + /** + * Stops the audio recording on the client. + * Note + * - You can call this method before calling the leaveChannel method; else, the recording automatically stops when you call the leaveChannel method. + * @see RtcEngine.leaveChannel + */ + stopAudioRecording(): Promise; +} + +interface RtcInjectStreamInterface { + /** + * Injects an online media stream to a live broadcast. + * If this method call is successful, the server pulls the voice or video stream and injects it into a live channel. This is applicable to scenarios where all audience members in the channel can watch a live show and interact with each other. + * Note + * - This method applies to the Live-Broadcast profile only. + * - Ensure that you enable the RTMP Converter service before using this function. See Prerequisites. + * - You can inject only one media stream into the channel at the same time. + * The addInjectStreamUrl method call triggers the following callbacks: + * - The local client: + * -- onStreamInjectedStatus, with the state of the injecting the online stream. + * @see RtcEngineEvents.StreamInjectedStatus + * -- onUserJoined(uid: 666), if the method call is successful and the online media stream is injected into the channel. + * @see RtcEngineEvents.UserJoined + * - The remote client: + * -- onUserJoined(uid: 666), if the method call is successful and the online media stream is injected into the channel. + * @see RtcEngineEvents.UserJoined + * @param url The URL address to be added to the ongoing live broadcast. Valid protocols are RTMP, HLS, and HTTP-FLV. + * - Supported audio codec type: AAC. + * - Supported video codec type: H264(AVC). + * @param config The LiveInjectStreamConfig object which contains the configuration information for the added voice or video stream. + * @see LiveInjectStreamConfig + */ + addInjectStreamUrl(url: string, config: LiveInjectStreamConfig): Promise; + + /** + * Removes the injected online media stream from a live broadcast. + * This method removes the URL address (added by addInjectStreamUrl) from a live broadcast. + * @see RtcEngine.addInjectStreamUrl + * If this method call is successful, the SDK triggers the onUserOffline callback and returns a stream uid of 666. + * @see RtcEngineEvents.UserOffline + * @param url HTTP/HTTPS URL address of the added stream to be removed. + */ + removeInjectStreamUrl(url: string): Promise; +} +interface RtcCameraInterface { /** - * set the sound position of a remote user - * - * This method sets the sound position of a remote user by uid - * - * @param uid number | The ID of the remote user - * @param pan float | The sound position of the remote user. The value ranges from -1.0 to 1.0 - * @pan - * 0.0: the remote sound comes from the front. - * -1.0: the remote sound comes from the left. - * 1.0: the remote sound comes from the right. - * @param gain float | Gain of the remote user. The value ranges from 0.0 to 100.0. The default value is 100.0 (the original gain of the remote user). The smaller the value, the less the gain. - * @return Promise + * Switches between front and rear cameras. */ - static setRemoteVoicePosition(uid: number, pan: number, gain: number): Promise { - let uint32 = Platform.OS === 'android' ? this.Uint32ToInt32(uid) : uid; - return Agora.setRemoteVoicePosition(uint32, pan, gain) - } + switchCamera(): Promise; /** - * start the lastmile probe test - * - * This method start the last-mile network probe test before joining a channel to get the uplink and downlink last-mile network statistics, including the bandwidth, packet loss, jitter, and round-trip time (RTT). - * - * @param config LastmileProbeConfig {@link LastmileProbeConfig} - * - * event onLastmileQuality: the SDK triggers this callback within two seconds depending on the network conditions. This callback rates the network conditions with a score and is more closely linked to the user experience. - * event onLastmileProbeResult: the SDK triggers this callback within 30 seconds depending on the network conditions. This callback returns the real-time statistics of the network conditions and is more objective. - * @return Promise + * Checks whether the camera zoom function is supported. */ - static startLastmileProbeTest(config: LastmileProbeConfig): Promise { - return Agora.startLastmileProbeTest(config); - } + isCameraZoomSupported(): Promise; /** - * stop the lastmile probe test - * - * This method stop the lastmile probe test. - * - * @return Promise + * Checks whether the camera flash function is supported. */ - static stopLastmileProbeTest(): Promise { - return Agora.stopLastmileProbeTest(); - } + isCameraTorchSupported(): Promise; /** - * sets the priority of a remote user's media stream. - * - * note: Use this method with the setRemoteSubscribeFallbackOption method. If the fallback function is enabled for a subscribed stream, the SDK ensures the high-priority user gets the best possible stream quality. - * - * This method sets the priority of a remote user's media stream. - * @param uid number - * @param userPriority number | The value range is [50 is "user's priority is high", 100 is "the default user's priority is normal"] - * - * @return Promise + * Checks whether the camera manual focus function is supported. */ - static setRemoteUserPriority(uid: number, userPriority: number): Promise { - let uint32 = Platform.OS === 'android' ? this.Uint32ToInt32(uid) : uid; - return Agora.setRemoteUserPriority(uint32, userPriority); - } + isCameraFocusSupported(): Promise; /** - * start an audio call test. - * - * note: - * Call this method before joining a channel. - * After calling this method, call the stopEchoTest method to end the test. Otherwise, the app cannot run the next echo test, or call the joinChannel method. - * In the Live-broadcast profile, only a host can call this method. - * This method will start an audio call test with interval parameter. - * In the audio call test, you record your voice. If the recording plays back within the set time interval, the audio devices and the network connection are working properly. - * - * @param interval number - * - * @return Promise + * Checks whether the camera exposure function is supported. */ - static startEchoTestWithInterval(interval: number): Promise { - return Agora.startEchoTestWithInterval(interval) - } + isCameraExposurePositionSupported(): Promise; /** - * set the camera capture preference. - * - * note: - * For a video call or live broadcast, generally the SDK controls the camera output parameters. When the default camera capture settings do not meet special requirements or cause performance problems, we recommend using this method to set the camera capture preference: - * If the resolution or frame rate of the captured raw video data are higher than those set by setVideoEncoderConfiguration, processing video frames requires extra CPU and RAM usage and degrades performance. We recommend setting config as CAPTURER_OUTPUT_PREFERENCE_PERFORMANCE(1) to avoid such problems. - * If you do not need local video preview or are willing to sacrifice preview quality, we recommend setting config as CAPTURER_OUTPUT_PREFERENCE_PERFORMANCE(1) to optimize CPU and RAM usage. - * If you want better quality for the local video preview, we recommend setting config as CAPTURER_OUTPUT_PREFERENCE_PREVIEW(2). - * - * This method will set the camera capture preference. - * - * @param config {@link CameraCapturerConfiguration} - * - * @return Promise + * Checks whether the camera auto-face focus function is supported. */ - static setCameraCapturerConfiguration(config: CameraCapturerConfiguration): Promise { - return Agora.setCameraCapturerConfiguration(config); - } + isCameraAutoFocusFaceModeSupported(): Promise; /** - * Gets the audio mixing volume for local playback. - * - * note: - * This method helps troubleshoot audio volume related issues. - * - * @return Promise + * Sets the camera zoom ratio. + * @param factor Sets the camera zoom factor. The value ranges between 1.0 and the maximum zoom supported by the device. */ - static getAudioMixingPlayoutVolume(): Promise { - return Agora.getAudioMixingPlayoutVolume(); - } + setCameraZoomFactor(factor: number): Promise; /** - * Gets the audio mixing volume for publishing. - * - * note: - * This method helps troubleshoot audio volume related issues. - * - * @return Promise + * Gets the maximum zoom ratio supported by the camera. */ - static getAudioMixingPublishVolume(): Promise { - return Agora.getAudioMixingPublishVolume(); - } + getCameraMaxZoomFactor(): Promise; /** - * sendMediaData for media observer. - * - * note: - * This method needs you invoke registerMediaMetadataObserver success first and you could send media data through interval media observer feature. - * The data have limit length is 1024 bytes, if you pass data length bigger than limit it will failed. - * @param data String: 1024 bytes limit - * @return Promise + * Sets the camera manual focus position. + * A successful setCameraFocusPositionInPreview method call triggers the onCameraFocusAreaChanged callback on the local client. + * @see RtcEngineEvents.CameraFocusAreaChanged + * @param positionX The horizontal coordinate of the touch point in the view. + * @param positionY The vertical coordinate of the touch point in the view. */ - static sendMediaData(data: String): Promise { - return Agora.sendMediaData(data); - } + setCameraFocusPositionInPreview(positionX: number, positionY: number): Promise; /** - * Registers the metadata observer. - * - * note: - * This method only work in live mode - * This method enables you to add synchronized metadata in the video stream for more diversified live broadcast interactions, such as sending shopping links, digital coupons, and online quizzes. - * This method trigger 'mediaMetaDataReceived' event, here is example: - * ```javascript - * RtcEngine.on("mediaMetaDataReceived", (data) => { - * console.log("mediaMetaDataReceived", data); - * }) - * ``` - * @return Promise + * Sets the camera exposure position. + * A successful setCameraExposurePosition method call triggers the onCameraExposureAreaChanged callback on the local client. + * @see RtcEngineEvents.CameraExposureAreaChanged + * @param positionXinView The horizontal coordinate of the touch point in the view. + * @param positionYinView The vertical coordinate of the touch point in the view. */ - static registerMediaMetadataObserver(): Promise { - return Agora.registerMediaMetadataObserver(); - } + setCameraExposurePosition(positionXinView: number, positionYinView: number): Promise; /** - * Get local device camera support info - * - * note: - * This method returns your current device camera support info. - * ```javascript - * RtcEngine.getCameraInfo().then(info => { - * console.log("your currrent camera", info); - * }) - * ``` - * @return Promise<{cameraSupportInfo}> + * Enables/Disables face detection for the local user. + * Once face detection is enabled, the SDK triggers the onFacePositionChanged callback to report the face information of the local user, which includes the following aspects: + * @see RtcEngineEvents.FacePositionChanged + * - The width and height of the local video. + * - The position of the human face in the local video. + * - The distance between the human face and the device screen. + * @param enable Determines whether to enable the face detection function for the local user: + * - true: Enable face detection. + * - false: (Default) Disable face detection. */ - static async getCameraInfo(): Promise { - return Agora.getCameraInfo(); - } + enableFaceDetection(enable: boolean): Promise; /** - * Set Private Parameters - * @param paramsStr - * @return Promise + * Enables the camera flash function. + * @param isOn Sets whether to enable/disable the camera flash function: + * - true: Enable the camera flash function. + * - false: Disable the camera flash function. */ - static async setParameters(paramsStr: string): Promise { - return Agora.setParameters(paramsStr); - } + setCameraTorchOn(isOn: boolean): Promise; /** - * Get Private Parameter - * @param paramsStr - * @param args - * @return Promise + * Enables the camera auto-face focus function. + * @param enabled Sets whether to enable/disable the camera auto-face focus function: + * - true: Enable the camera auto-face focus function. + * - false: (Default) Disable the camera auto-face focus function. */ - static async getParameter(paramsStr: string, args: string): Promise { - return Agora.getParameter(paramsStr, args); - } + setCameraAutoFocusFaceModeEnabled(enabled: boolean): Promise; /** - * Get Private Parameters - * @param paramsStr - * @param args - * @return Promise + * Sets the camera capturer configuration. + * For a video call or live broadcast, generally the SDK controls the camera output parameters. When the default camera capture settings do not meet special requirements or cause performance problems, we recommend using this method to set the camera capturer configuration: + * - If the resolution or frame rate of the captured raw video data are higher than those set by setVideoEncoderConfiguration, processing video frames requires extra CPU and RAM usage and degrades performance. We recommend setting config as Performance(1) to avoid such problems. + * @see RtcEngine.setVideoEncoderConfiguration + * @see CameraCaptureOutputPreference.Performance + * - If you do not need local video preview or are willing to sacrifice preview quality, we recommend setting config as Performance(1) to optimize CPU and RAM usage. + * @see CameraCaptureOutputPreference.Performance + * - If you want better quality for the local video preview, we recommend setting config as Preview(2). + * @see CameraCaptureOutputPreference.Preview + * Note + * - Call this method before enabling the local camera. That said, you can call this method before calling joinChannel, enableVideo, or enableLocalVideo, depending on which method you use to turn on your local camera. + * @see RtcEngine.joinChannel + * @see RtcEngine.enableVideo + * @see RtcEngine.enableLocalVideo + * @param config The camera capturer configuration. + * @see CameraCapturerConfiguration */ - static async getParameters(paramsStr: string): Promise { - return Agora.getParameters(paramsStr); - } + setCameraCapturerConfiguration(config: CameraCapturerConfiguration): Promise; } -export default RtcEngine; +interface RtcStreamMessageInterface { + /** + * Creates a data stream. + * Each user can create up to five data streams during the lifecycle of the RtcEngine. + * @see RtcEngine + * Note + * - Set both the reliable and ordered parameters to true or false. Do not set one as true and the other as false. + * @param reliable Sets whether or not the recipients are guaranteed to receive the data stream from the sender within five seconds: + * - true: The recipients receive the data from the sender within five seconds. If the recipient does not receive the data within five seconds, the SDK triggers the onStreamMessageError callback and returns an error code. + * @see RtcEngineEvents.StreamMessageError + * - false: There is no guarantee that the recipients receive the data stream within five seconds and no error message is reported for any delay or missing data stream. + * @param ordered Sets whether or not the recipients receive the data stream in the sent order: + * - true: The recipients receive the data in the sent order. + * - false: The recipients do not receive the data in the sent order. + */ + createDataStream(reliable: boolean, ordered: boolean): Promise; + + /** + * Sends data stream messages. + * The SDK has the following restrictions on this method: + * - Up to 30 packets can be sent per second in a channel with each packet having a maximum size of 1 kB. + * - Each client can send up to 6 kB of data per second. + * - Each user can have up to five data channels simultaneously. + * A successful sendStreamMessage method call triggers the onStreamMessage callback on the remote client, from which the remote user gets the stream message. + * @see RtcEngineEvents.StreamMessage + * A failed sendStreamMessage method call triggers the onStreamMessageError callback on the remote client. + * @see RtcEngineEvents.StreamMessageError + * Note + * - Ensure that you have created the data stream using createDataStream before calling this method. + * @see RtcEngine.createDataStream + * - This method applies only to the Communication profile or to hosts in the Live Broadcast profile. + * @param streamId ID of the sent data stream returned by the createDataStream method. + * @see RtcEngine.createDataStream + * @param message Sent data. + */ + sendStreamMessage(streamId: number, message: string): Promise; +} diff --git a/src/RtcEvents.ts b/src/RtcEvents.ts new file mode 100644 index 000000000..116f6af59 --- /dev/null +++ b/src/RtcEvents.ts @@ -0,0 +1,935 @@ +import { + AudioLocalError, + AudioLocalState, + AudioMixingErrorCode, + AudioMixingStateCode, + AudioOutputRouting, + AudioRemoteState, + AudioRemoteStateReason, + AudioVolumeInfo, + ChannelMediaRelayError, + ChannelMediaRelayEvent, + ChannelMediaRelayState, + ClientRole, + ConnectionChangedReason, + ConnectionStateType, + ErrorCode, + FacePositionInfo, + InjectStreamStatus, + LastmileProbeResult, + LocalAudioStats, + LocalVideoStats, + LocalVideoStreamError, + LocalVideoStreamState, + NetworkQuality, + NetworkType, + Rect, + RemoteAudioStats, + RemoteVideoStats, + RtcStats, + RtmpStreamingErrorCode, + RtmpStreamingState, + UserInfo, + UserOfflineReason, + VideoRemoteState, + VideoRemoteStateReason, + WarningCode +} from "./Types" + +export type Listener = (...args: any[]) => any + +export interface Subscription { + remove(): void +} + +type EmptyCallback = () => void +type WarningCallback = (warn: WarningCode) => void +type ErrorCallback = (err: ErrorCode) => void +type ApiCallCallback = (error: ErrorCode, api: string, result: string) => void +type UidWithElapsedAndChannelCallback = (channel: string, uid: number, elapsed: number) => void +type RtcStatsCallback = (stats: RtcStats) => void +type UserAccountCallback = (uid: number, userAccount: string) => void +type UserInfoCallback = (uid: number, userInfo: UserInfo) => void +type ClientRoleCallback = (oldRole: ClientRole, newRole: ClientRole) => void +type UidWithElapsedCallback = (uid: number, elapsed: number) => void +type UserOfflineCallback = (uid: number, reason: UserOfflineReason) => void +type ConnectionStateCallback = (state: ConnectionStateType, reason: ConnectionChangedReason) => void +type NetworkTypeCallback = (type: NetworkType) => void +type TokenCallback = (token: string) => void +type AudioVolumeCallback = (speakers: AudioVolumeInfo[], totalVolume: number) => void +type UidCallback = (uid: number) => void +type ElapsedCallback = (elapsed: number) => void +type VideoFrameCallback = (width: number, height: number, elapsed: number) => void +type UidWithMutedCallback = (uid: number, muted: boolean) => void +type VideoSizeCallback = (uid: number, width: number, height: number, rotation: number) => void +type RemoteVideoStateCallback = (uid: number, state: VideoRemoteState, reason: VideoRemoteStateReason, elapsed: number) => void +type LocalVideoStateCallback = (localVideoState: LocalVideoStreamState, error: LocalVideoStreamError) => void +type RemoteAudioStateCallback = (uid: number, state: AudioRemoteState, reason: AudioRemoteStateReason, elapsed: number) => void +type LocalAudioStateCallback = (state: AudioLocalState, error: AudioLocalError) => void +type FallbackCallback = (isFallbackOrRecover: boolean) => void +type FallbackWithUidCallback = (uid: number, isFallbackOrRecover: boolean) => void +type AudioRouteCallback = (routing: AudioOutputRouting) => void +type RectCallback = (rect: Rect) => void +type NetworkQualityCallback = (quality: NetworkQuality) => void +type NetworkQualityWithUidCallback = (uid: number, txQuality: NetworkQuality, rxQuality: NetworkQuality) => void +type LastmileProbeCallback = (result: LastmileProbeResult) => void +type LocalVideoStatsCallback = (stats: LocalVideoStats) => void +type LocalAudioStatsCallback = (stats: LocalAudioStats) => void +type RemoteVideoStatsCallback = (stats: RemoteVideoStats) => void +type RemoteAudioStatsCallback = (stats: RemoteAudioStats) => void +type AudioMixingStateCallback = (state: AudioMixingStateCode, errorCode: AudioMixingErrorCode) => void +type SoundIdCallback = (soundId: number) => void +type RtmpStreamingStateCallback = (url: string, state: RtmpStreamingState, errCode: RtmpStreamingErrorCode) => void +type StreamInjectedStatusCallback = (url: string, uid: number, status: InjectStreamStatus) => void +type StreamMessageCallback = (uid: number, streamId: number, data: string) => void +type StreamMessageErrorCallback = (uid: number, streamId: number, error: ErrorCode, missed: number, cached: number) => void +type MediaRelayStateCallback = (state: ChannelMediaRelayState, code: ChannelMediaRelayError) => void +type MediaRelayEventCallback = (code: ChannelMediaRelayEvent) => void +type VideoFrameWithUidCallback = (uid: number, width: number, height: number, elapsed: number) => void +type UrlWithErrorCallback = (url: string, error: ErrorCode) => void +type UrlCallback = (url: string) => void +type TransportStatsCallback = (uid: number, delay: number, lost: number, rxKBitRate: number) => void +type UidWithEnabledCallback = (uid: number, enabled: boolean) => void +type EnabledCallback = (enabled: boolean) => void +type AudioQualityCallback = (uid: number, quality: number, delay: number, lost: number) => void +type MetadataCallback = (buffer: string, uid: number, timeStampMs: number) => void +type FacePositionCallback = (imageWidth: number, imageHeight: number, faces: FacePositionInfo[]) => void + +/** + * The SDK uses the RtcEngineEvents interface class to send callbacks to the application, and the application inherits the methods of this interface class to retrieve these callbacks. + * All methods in this interface class have their (empty) default implementations, and the application can inherit only some of the required events instead of all of them. + * In the callbacks, the application should avoid time-consuming tasks or call blocking APIs (such as SendMessage), otherwise, the SDK may not work properly. + */ +export interface RtcEngineEvents { + /** + * Reports a warning during SDK runtime. + * In most cases, the app can ignore the warning reported by the SDK because the SDK can usually fix the issue and resume running. + * For instance, the SDK may report a LookupChannelTimeout warning upon disconnection with the server and tries to reconnect. For detailed warning codes, see Warning Codes. + * @see WarningCode.LookupChannelTimeout + * @see WarningCode + */ + Warning: WarningCallback + + /** + * Reports an error during SDK runtime. + * In most cases, the SDK cannot fix the issue and resume running. The SDK requires the app to take action or informs the user about the issue. + * For example, the SDK reports an StartCall error when failing to initialize a call. The app informs the user that the call initialization failed and invokes the leaveChannel method to leave the channel. For detailed error codes, see Error Codes. + * @see ErrorCode.StartCall + * @see RtcEngine.leaveChannel + * @see ErrorCode + */ + Error: ErrorCallback + + /** + * Occurs when an API method is executed. + */ + ApiCallExecuted: ApiCallCallback + + /** + * Occurs when the local user joins a specified channel. + * The channel name assignment is based on channelName specified in the joinChannel method. + * If the uid is not specified when joinChannel is called, the server automatically assigns a uid. + * @see RtcEngine.joinChannel + */ + JoinChannelSuccess: UidWithElapsedAndChannelCallback + + /** + * Occurs when a user rejoins the channel after being disconnected due to network problems. + * When a user loses connection with the server because of network problems, the SDK automatically tries to reconnect and triggers this callback upon reconnection. + */ + RejoinChannelSuccess: UidWithElapsedAndChannelCallback + + /** + * Occurs when a user leaves the channel. + * When the app calls the leaveChannel method, the SDK uses this callback to notify the app when the user leaves the channel. + * With this callback, the application retrieves the channel information, such as the call duration and statistics. + * @see RtcEngine.leaveChannel + */ + LeaveChannel: RtcStatsCallback + + /** + * Occurs when the local user registers a user account. + * This callback is triggered when the local user successfully registers a user account by calling the registerLocalUserAccount method, or joins a channel by calling the joinChannelWithUserAccount method. This callback reports the user ID and user account of the local user. + * @see RtcEngine.joinChannelWithUserAccount + */ + LocalUserRegistered: UserAccountCallback + + /** + * Occurs when the SDK gets the user ID and user account of the remote user. + * After a remote user joins the channel, the SDK gets the UID and user account of the remote user, caches them in a mapping table object (UserInfo), and triggers this callback on the local client. + * @see UserInfo + */ + UserInfoUpdated: UserInfoCallback + + /** + * Occurs when the user role switches in a live broadcast. For example, from a host to an audience or vice versa. + * The SDK triggers this callback when the local user switches the user role by calling the setClientRole method after joining the channel. + * @see RtcEngine.setClientRole + */ + ClientRoleChanged: ClientRoleCallback + + /** + * Occurs when a remote user (Communication)/host (Live Broadcast) joins the channel. + * - Communication profile: This callback notifies the app when another user joins the channel. If other users are already in the channel, the SDK also reports to the app on the existing users. + * - Live Broadcast profile: This callback notifies the app when the host joins the channel. If other hosts are already in the channel, the SDK also reports to the app on the existing hosts. We recommend having at most 17 hosts in a channel + * The SDK triggers this callback under one of the following circumstances: + * - A remote user/host joins the channel by calling the joinChannel method. + * @see RtcEngine.joinChannel + * - A remote user switches the user role to the host by calling the setClientRole method after joining the channel. + * @see RtcEngine.setClientRole + * - A remote user/host rejoins the channel after a network interruption. + * - The host injects an online media stream into the channel by calling the addInjectStreamUrl method. + * @see RtcEngine.addInjectStreamUrl + * Note + * - In the Live Broadcast profile: + * -- The host receives the onUserJoined callback when another host joins the channel. + * -- The audience in the channel receives the onUserJoined callback when a new host joins the channel. + * -- When a web application joins the channel, the onUserJoined callback is triggered as long as the web application publishes streams. + */ + UserJoined: UidWithElapsedCallback + + /** + * Occurs when a remote user (Communication)/host (Live Broadcast) leaves the channel. + * There are two reasons for users to become offline: + * - Leave the channel: When the user/host leaves the channel, the user/host sends a goodbye message. When this message is received, the SDK determines that the user/host leaves the channel. + * - Drop offline: When no data packet of the user or host is received for a certain period of time (20 seconds for the communication profile, and more for the live broadcast profile), the SDK assumes that the user/host drops offline. A poor network connection may lead to false detections, so we recommend using the Agora RTM SDK for reliable offline detection. + */ + UserOffline: UserOfflineCallback + + /** + * Occurs when the network connection state changes. + * The Agora SDK returns this callback to report on the current network connection state when it changes, and the reason to such change. + */ + ConnectionStateChanged: ConnectionStateCallback + + /** + * Occurs when the network type changes. + * The SDK returns the current network type in this callback. When the network connection is interrupted, this callback indicates whether the interruption is caused by a network type change or poor network conditions. + */ + NetworkTypeChanged: NetworkTypeCallback + + /** + * Occurs when the SDK cannot reconnect to Agora's edge server 10 seconds after its connection to the server is interrupted. + * The SDK triggers this callback when it cannot connect to the server 10 seconds after calling joinChannel(), regardless of whether it is in the channel or not. + * @see RtcEngine.joinChannel + * If the SDK fails to rejoin the channel 20 minutes after being disconnected from Agora's edge server, the SDK stops rejoining the channel. + */ + ConnectionLost: EmptyCallback + + /** + * Occurs when the token expires in 30 seconds. + * The user becomes offline if the token used when joining the channel expires. This callback is triggered 30 seconds before the token expires to remind the app to get a new token. Upon receiving this callback, you need to generate a new token on the server and call renewToken to pass the new token to the SDK. + * @see RtcEngine.renewToken + */ + TokenPrivilegeWillExpire: TokenCallback + + /** + * Occurs when the token has expired. + * After a token is specified when joining the channel, the token expires after a certain period of time, and a new token is required to reconnect to the server. This callback notifies the app to generate a new token and call joinChannel to rejoin the channel with the new token. + * @see RtcEngine.joinChannel + */ + RequestToken: EmptyCallback + + /** + * Reports which users are speaking and the speakers' volume, and whether the local user is speaking. + * This callback reports the IDs and volumes of the loudest speakers (at most 3) at the moment in the channel, and whether the local user is speaking. + * By default, this callback is disabled. You can enable it by calling the enableAudioVolumeIndication method. Once enabled, this callback is triggered at the set interval, regardless of whether a user speaks or not. + * @see RtcEngine.enableAudioVolumeIndication + * The SDK triggers two independent onAudioVolumeIndication callbacks at one time, which separately report the volume information of the local user and all the remote speakers. For more information, see the detailed parameter descriptions. + * Note + * - To enable the voice activity detection of the local user, ensure that you set report_vad(true) in the enableAudioVolumeIndication method. + * @see RtcEngine.enableAudioVolumeIndication + * - Calling the muteLocalAudioStream method affects the SDK's behavior. + * @see RtcEngine.muteLocalAudioStream + * -- If the local user calls the muteLocalAudioStream method, the SDK stops triggering the local user's callback. + * @see RtcEngine.muteLocalAudioStream + * -- 20 seconds after a remote speaker calls the muteLocalAudioStream method, the remote speakers' callback does not include information of this remote user; 20 seconds after all remote users call the the muteLocalAudioStream method, the SDK stops triggering the remote speakers' callback. + * @see RtcEngine.muteLocalAudioStream + */ + AudioVolumeIndication: AudioVolumeCallback + + /** + * Reports which user is the loudest speaker. + * This callback reports the speaker with the highest accumulative volume during a certain period. If the user enables the audio volume indication by calling enableAudioVolumeIndication, this callback returns the uid of the active speaker whose voice is detected by the audio volume detection module of the SDK. + * @see RtcEngine.enableAudioVolumeIndication + * Note + * - To receive this callback, you need to call enableAudioVolumeIndication. + * @see RtcEngine.enableAudioVolumeIndication + * - This callback returns the user ID of the user with the highest voice volume during a period of time, instead of at the moment. + */ + ActiveSpeaker: UidCallback + + /** + * Occurs when the first local audio frame is sent. + */ + FirstLocalAudioFrame: ElapsedCallback + + /** + * Occurs when the first local video frame is rendered. + * This callback is triggered after the first local video frame is rendered on the local video window. + */ + FirstLocalVideoFrame: VideoFrameCallback + + /** + * Occurs when a remote user stops/resumes sending the video stream. + * @deprecated This callback is deprecated. Use the onRemoteVideoStateChanged callback with the following parameters for the same function: + * @see RemoteVideoStateChanged + * - Stopped(0) and RemoteMuted(5). + * @see VideoRemoteState.Stopped + * @see VideoRemoteStateReason.RemoteMuted + * - Decoding(2) and RemoteUnmuted(6). + * @see VideoRemoteState.Decoding + * @see VideoRemoteStateReason.RemoteUnmuted + * The SDK triggers this callback when the remote user stops or resumes sending the video stream by calling the muteLocalVideoStream method. + * @see RtcEngine.muteLocalVideoStream + * Note + * - This callback is invalid when the number of users or broadcasters in the channel exceeds 20. + */ + UserMuteVideo: UidWithMutedCallback + + /** + * Occurs when the video size or rotation information of a remote user changes. + */ + VideoSizeChanged: VideoSizeCallback + + /** + * Occurs when the remote video state changes. + */ + RemoteVideoStateChanged: RemoteVideoStateCallback + + /** + * Occurs when the local video state changes. + * The SDK returns the current video state in this callback. When the state is Failed(3), see the error parameter for details. + * @see LocalVideoStreamState.Failed + * @see LocalVideoStreamError + * Note + * - This callback reports the current state of the local video, which keeps changing throughout the RtcEngine life cycle. We recommend maintaining the states reported in this callback, and check the local video state before starting the local camera. If the SDK reports CaptureFailure(4), the local camera is occupied by either the system or a third-party app. To access the camera, call enableLocalVideo (false) first, and then enableLocalVideo (video). + * @see LocalVideoStreamError.CaptureFailure + * @see RtcEngine.enableLocalVideo + */ + LocalVideoStateChanged: LocalVideoStateCallback + + /** + * Occurs when the remote audio state changes. + * This callback indicates the state change of the remote audio stream. + */ + RemoteAudioStateChanged: RemoteAudioStateCallback + + /** + * Occurs when the local audio stream state changes. + * This callback indicates the state change of the local audio stream, including the state of the audio recording and encoding, and allows you to troubleshoot issues when exceptions occur. + * Note + * - When the state is Failed(3), see the error parameter for details. + * @see AudioLocalState.Failed + * @see AudioLocalError + */ + LocalAudioStateChanged: LocalAudioStateCallback + + /** + * Occurs when the published media stream falls back to an audio-only stream due to poor network conditions or switches back to video stream after the network conditions improve. + * If you call setLocalPublishFallbackOption and set option as AudioOnly(2), this callback is triggered when the locally published stream falls back to audio-only mode due to poor uplink conditions, or when the audio stream switches back to the video after the uplink network condition improves. + * @see RtcEngine.setLocalPublishFallbackOption + * @see StreamFallbackOptions.AudioOnly + */ + LocalPublishFallbackToAudioOnly: FallbackCallback + + /** + * Occurs when the remote media stream falls back to audio-only stream due to poor network conditions or switches back to video stream after the network conditions improve. + * If you call setRemoteSubscribeFallbackOption and set option as AudioOnly(2), this callback is triggered when the remotely subscribed media stream falls back to audio-only mode due to poor uplink conditions, or when the remotely subscribed media stream switches back to the video after the uplink network condition improves. + * @see RtcEngine.setRemoteSubscribeFallbackOption + * @see StreamFallbackOptions.AudioOnly + */ + RemoteSubscribeFallbackToAudioOnly: FallbackWithUidCallback + + /** + * Occurs when the local audio playback route changes. + * This callback returns that the audio route switched to an earpiece, speakerphone, headset, or Bluetooth device. + * The definition of the routing is listed as follows: + * @see AudioOutputRouting + */ + AudioRouteChanged: AudioRouteCallback + + /** + * Occurs when the camera focus area is changed. + * The SDK triggers this callback when the local user changes the camera focus position by calling the setCameraFocusPositionInPreview method. + * @see RtcEngine.setCameraFocusPositionInPreview + */ + CameraFocusAreaChanged: RectCallback + + /** + * The camera exposure area has changed. + * The SDK triggers this callback when the local user changes the camera exposure position by calling the setCameraExposurePosition method. + * @see RtcEngine.setCameraExposurePosition + */ + CameraExposureAreaChanged: RectCallback + + /** + * Reports the face detection result of the local user. + * Once you enable face detection by calling enableFaceDetection, you can get the following information on the local user in real-time: + * @see RtcEngine#enableFaceDetection + * - The width and height of the local video. + * - The position of the human face in the local video. + * - The distance between the human face and the device screen. This value is based on the fitting calculation of the local video size and the position of the human face. + * Note + * - If the SDK does not detect a face, it reduces the frequency of this callback to reduce power consumption on the local device. + * - The SDK stops triggering this callback when a human face is in close proximity to the screen. + * - On Android, the distance value reported in this callback may be slightly different from the actual distance. Therefore, Agora does not recommend using it for accurate calculation. + */ + FacePositionChanged: FacePositionCallback + + /** + * Reports the statistics of the RtcEngine once every two seconds. + * @see RtcEngine + */ + RtcStats: RtcStatsCallback + + /** + * Reports the last mile network quality of the local user once every two seconds before the user joins the channel. Last mile refers to the connection between the local device and Agora's edge server. After the application calls the enableLastmileTest method, this callback reports once every two seconds the uplink and downlink last mile network conditions of the local user before the user joins the channel. + * @see RtcEngine.enableLastmileTest + */ + LastmileQuality: NetworkQualityCallback + + /** + * Reports the last mile network quality of each user in the channel once every two seconds. + * Last mile refers to the connection between the local device and Agora's edge server. This callback reports once every two seconds the last mile network conditions of each user in the channel. If a channel includes multiple users, then this callback will be triggered as many times. + */ + NetworkQuality: NetworkQualityWithUidCallback + + /** + * Reports the last-mile network probe result. + * The SDK triggers this callback within 30 seconds after the app calls the startLastmileProbeTest method. + * @see RtcEngine.startLastmileProbeTest + */ + LastmileProbeResult: LastmileProbeCallback + + /** + * Reports the statistics of the local video streams. + * The SDK triggers this callback once every two seconds for each user/host. If there are multiple users/hosts in the channel, the SDK triggers this callback as many times. + */ + LocalVideoStats: LocalVideoStatsCallback + + /** + * Reports the statistics of the local audio stream. + */ + LocalAudioStats: LocalAudioStatsCallback + + /** + * Reports the statistics of the video stream from each remote user/host. The SDK triggers this callback once every two seconds for each remote user/host. If a channel includes multiple remote users, the SDK triggers this callback as many times. + */ + RemoteVideoStats: RemoteVideoStatsCallback + + /** + * Reports the statistics of the audio stream from each remote user/host. + * The SDK triggers this callback once every two seconds for each remote user/host. If a channel includes multiple remote users, the SDK triggers this callback as many times. + * Schemes such as FEC (Forward Error Correction) or retransmission counter the frame loss rate. Hence, users may find the overall audio quality acceptable even when the packet loss rate is high. + */ + RemoteAudioStats: RemoteAudioStatsCallback + + /** + * Occurs when the audio mixing file playback finishes. + * @deprecated This callback is deprecated. Use onAudioMixingStateChanged instead. + * @see AudioMixingStateChanged + * You can start an audio mixing file playback by calling the startAudioMixing method. This callback is triggered when the audio mixing file playback finishes. + * @see RtcEngine.startAudioMixing + * If the startAudioMixing method call fails, an AudioMixingOpenError warning returns in the onWarning callback. + * @see RtcEngine.startAudioMixing + * @see WarningCode.AudioMixingOpenError + * @see Warning + */ + AudioMixingFinished: EmptyCallback + + /** + * Occurs when the state of the local user's audio mixing file changes. + * When you call the startAudioMixing method and the state of audio mixing file changes, the Agora SDK triggers this callback. + * @see RtcEngine.startAudioMixing + * - When the audio mixing file plays, pauses playing, or stops playing, this callback returns 710, 711, or 713 in state, and 0 in errorCode. + * - When exceptions occur during playback, this callback returns 714 in state and an error in errorCode. + * - If the local audio mixing file does not exist, or if the SDK does not support the file format or cannot access the music file URL, the SDK returns AudioMixingOpenError = 701. + * @see WarningCode.AudioMixingOpenError + */ + AudioMixingStateChanged: AudioMixingStateCallback + + /** + * Occurs when the audio effect file playback finishes. + * You can start a local audio effect playback by calling the playEffect method. This callback is triggered when the local audio effect file playback finishes. + * @see RtcEngine.playEffect + */ + AudioEffectFinished: SoundIdCallback + + /** + * Occurs when the state of the RTMP streaming changes. + * The SDK triggers this callback to report the result of the local user calling the addPublishStreamUrl or removePublishStreamUrl method. This callback returns the URL and its current streaming state. When the streaming state is Failure(4), see the errCode parameter for details. + * @see RtcEngine.addPublishStreamUrl + * @see RtcEngine.removePublishStreamUrl + * @see RtmpStreamingState.Failure + * This callback indicates the state of the RTMP streaming. When exceptions occur, you can troubleshoot issues by referring to the detailed error descriptions in the errCode parameter. + */ + RtmpStreamingStateChanged: RtmpStreamingStateCallback + + /** + * Occurs when the publisher's transcoding settings are updated. + * When the LiveTranscoding class in the setLiveTranscoding method updates, the SDK triggers this callback to report the update information. + * @see RtcEngine.setLiveTranscoding + * Note + * - If you call the setLiveTranscoding method to set the LiveTranscoding class for the first time, the SDK does not trigger this callback. + */ + TranscodingUpdated: EmptyCallback + + /** + * Reports the status of injecting the online media stream. + */ + StreamInjectedStatus: StreamInjectedStatusCallback + + /** + * Occurs when the local user receives a remote data stream. + * The SDK triggers this callback when the local user receives the stream message that the remote user sends by calling the sendStreamMessage method. + * @see RtcEngine.sendStreamMessage + */ + StreamMessage: StreamMessageCallback + + /** + * Occurs when the local user fails to receive a remote data stream. + * The SDK triggers this callback when the local user fails to receive the stream message that the remote user sends by calling the sendStreamMessage method. + * @see RtcEngine.sendStreamMessage + */ + StreamMessageError: StreamMessageErrorCallback + + /** + * Occurs when the media engine is loaded. + */ + MediaEngineLoadSuccess: EmptyCallback + + /** + * Occurs when the media engine starts. + */ + MediaEngineStartCallSuccess: EmptyCallback + + /** + * Occurs when the state of the media stream relay changes. + * The SDK reports the state of the current media relay and possible error messages in this callback. + */ + ChannelMediaRelayStateChanged: MediaRelayStateCallback + + /** + * Reports events during the media stream relay. + */ + ChannelMediaRelayEvent: MediaRelayEventCallback + + /** + * Occurs when the first remote video frame is rendered. + * @deprecated Use Starting(1) or Decoding(2) in the onRemoteVideoStateChanged callback instead. + * @see VideoRemoteState.Starting + * @see VideoRemoteState.Decoding + * @see RemoteVideoStateChanged + * This callback is triggered after the first frame of the remote video is rendered on the video window. The application can retrieve the data of the time elapsed from the user joining the channel until the first video frame is displayed. + */ + FirstRemoteVideoFrame: VideoFrameWithUidCallback + + /** + * Occurs when the first remote audio frame is received. + * @deprecated Use Starting(1) in onRemoteAudioStateChanged instead. + * @see AudioRemoteState.Starting + * @see RemoteAudioStateChanged + */ + FirstRemoteAudioFrame: UidWithElapsedCallback + + /** + * Occurs when the engine receives the first audio frame from a specified remote user. + * @deprecated Use Decoding(2) in onRemoteAudioStateChanged instead. + * @see VideoRemoteState.Decoding + * @see RemoteAudioStateChanged + * This callback is triggered in either of the following scenarios: + * - The remote user joins the channel and sends the audio stream. + * - The remote user stops sending the audio stream and re-sends it after 15 seconds. Possible reasons include: + * -- The remote user leaves channel. + * -- The remote user drops offline. + * -- The remote user calls the muteLocalAudioStream method. + * @see RtcEngine.muteLocalAudioStream + * -- The remote user calls the disableAudio method. + * @see RtcEngine.disableAudio + */ + FirstRemoteAudioDecoded: UidWithElapsedCallback + + /** + * Occurs when a remote user stops/resumes sending the audio stream. + * @deprecated Use the onRemoteAudioStateChanged callback with the following parameters instead: + * @see RemoteAudioStateChanged + * - Stopped(0) and RemoteMuted(5). + * @see VideoRemoteState.Stopped + * @see VideoRemoteStateReason.RemoteMuted + * - Decoding(2) and RemoteUnmuted(6). + * @see VideoRemoteState.Decoding + * @see VideoRemoteStateReason.RemoteUnmuted + * The SDK triggers this callback when the remote user stops or resumes sending the audio stream by calling the muteLocalAudioStream method. + * @see RtcEngine.muteLocalAudioStream + * Note + * - This callback is invalid when the number of users or broadcasters in the channel exceeds 20. + */ + UserMuteAudio: UidWithMutedCallback + + /** + * Reports the result of calling the addPublishStreamUrl method. + * @see RtcEngine.addPublishStreamUrl + * @deprecated Use onRtmpStreamingStateChanged instead. + * @see RtmpStreamingStateChanged + * This callback indicates whether you have successfully added an RTMP stream to the CDN. + */ + StreamPublished: UrlWithErrorCallback + + /** + * Reports the result of calling the removePublishStreamUrl method. + * @see RtcEngine.removePublishStreamUrl + * @deprecated Use onRtmpStreamingStateChanged instead. + * @see RtmpStreamingStateChanged + * This callback indicates whether you have successfully removed an RTMP stream from the CDN. + */ + StreamUnpublished: UrlCallback + + /** + * Reports the transport-layer statistics of each remote audio stream. + * @deprecated This callback is deprecated. Use onRemoteAudioStats instead. + * @see RemoteAudioStats + * This callback reports the transport-layer statistics, such as the packet loss rate and time delay, once every two seconds after the local user receives an audio packet from a remote user. + */ + RemoteAudioTransportStats: TransportStatsCallback + + /** + * Reports the transport-layer statistics of each remote video stream. + * @deprecated This callback is deprecated. Use onRemoteVideoStats instead. + * @see RemoteVideoStats + * This callback reports the transport-layer statistics, such as the packet loss rate and time delay, once every two seconds after the local user receives the video packet from a remote user. + */ + RemoteVideoTransportStats: TransportStatsCallback + + /** + * Occurs when a remote user enables/disables the video module. + * @deprecated This callback is deprecated and replaced by the onRemoteVideoStateChanged callback with the following parameters: + * @see RemoteVideoStateChanged + * - Stopped(0) and RemoteMuted(5). + * @see VideoRemoteState.Stopped + * @see VideoRemoteStateReason.RemoteMuted + * - Decoding(2) and RemoteUnmuted(6). + * @see VideoRemoteState.Decoding + * @see VideoRemoteStateReason.RemoteUnmuted + * Once the video module is disabled, the remote user can only use a voice call. The remote user cannot send or receive any video from other users. + * The SDK triggers this callback when the remote user enables or disables the video module by calling the enableVideo or disableVideo method. + * @see RtcEngine.enableVideo + * @see RtcEngine.disableVideo + * Note + * - This callback is invalid when the number of users or broadcasters in the channel exceeds 20. + */ + UserEnableVideo: UidWithEnabledCallback + + /** + * Occurs when a remote user enables/disables the local video capture function. + * @deprecated This callback is deprecated and replaced by the onRemoteVideoStateChanged callback with the following parameters: + * @see RemoteVideoStateChanged + * - Stopped(0) and RemoteMuted(5). + * @see VideoRemoteState.Stopped + * @see VideoRemoteStateReason.RemoteMuted + * - Decoding(2) and RemoteUnmuted(6). + * @see VideoRemoteState.Decoding + * @see VideoRemoteStateReason.RemoteUnmuted + * The SDK triggers this callback when the remote user resumes or stops capturing the video stream by calling the enableLocalVideo method. + * @see RtcEngine.enableLocalVideo + * This callback is only applicable to the scenario when the remote user only wants to watch the remote video without sending any video stream to the other user. + */ + UserEnableLocalVideo: UidWithEnabledCallback + + /** + * Occurs when the first remote video frame is received and decoded. + * @deprecated This callback is deprecated. Use Starting(1) or Decoding(2) in the onRemoteVideoStateChanged callback instead. + * @see VideoRemoteState.Starting + * @see VideoRemoteState.Decoding + * @see RemoteVideoStateChanged + * This callback is triggered in either of the following scenarios: + * - The remote user joins the channel and sends the video stream. + * - The remote user stops sending the video stream and re-sends it after 15 seconds. Possible reasons include: + * -- The remote user leaves channel. + * -- The remote user drops offline. + * -- The remote user calls the muteLocalVideoStream method. + * @see RtcEngine.muteLocalVideoStream + * -- The remote user calls the disableVideo method. + * @see RtcEngine.disableVideo + */ + FirstRemoteVideoDecoded: VideoFrameWithUidCallback + + /** + * Occurs when the microphone is enabled/disabled. + * @deprecated This callback is deprecated. Use Stopped(0) or Recording(1) in the onLocalAudioStateChanged callback instead. + * @see AudioLocalState.Stopped + * @see AudioLocalState.Recording + * @see LocalAudioStateChanged + * The SDK triggers this callback when the local user resumes or stops capturing the local audio stream by calling the enableLocalAudio method. + * @see RtcEngine.enableLocalAudio + */ + MicrophoneEnabled: EnabledCallback + + /** + * Occurs when the connection between the SDK and the server is interrupted. + * @deprecated Use onConnectionStateChanged instead. + * @see ConnectionStateChanged + * The SDK triggers this callback when it loses connection to the server for more than four seconds after the connection is established. After triggering this callback, the SDK tries to reconnect to the server. You can use this callback to implement pop-up reminders. This callback is different from onConnectionLost: + * @see ConnectionLost + * - The SDK triggers the onConnectionInterrupted callback when the SDK loses connection with the server for more than four seconds after it joins the channel. + * @see ConnectionInterrupted + * - The SDK triggers the onConnectionLost callback when it loses connection with the server for more than 10 seconds, regardless of whether it joins the channel or not. + * @see ConnectionLost + * If the SDK fails to rejoin the channel 20 minutes after being disconnected from Agora's edge server, the SDK stops rejoining the channel. + */ + ConnectionInterrupted: EmptyCallback + + /** + * Occurs when your connection is banned by the Agora Server. + * @deprecated Use onConnectionStateChanged instead. + * @see ConnectionStateChanged + */ + ConnectionBanned: EmptyCallback + + /** + * Reports the statistics of the audio stream from each remote user/host. + * @deprecated Use onRemoteAudioStats instead. + * @see RemoteAudioStats + * The SDK triggers this callback once every two seconds to report the audio quality of each remote user/host sending an audio stream. If a channel has multiple remote users/hosts sending audio streams, the SDK trggers this callback as many times. + */ + AudioQuality: AudioQualityCallback + + /** + * Occurs when the camera is turned on and ready to capture video. + * @deprecated Use Capturing(1) in the onLocalVideoStateChanged callback instead. If the camera fails to turn on, fix the error reported in the onError callback. + * @see LocalVideoStreamState.Capturing + * @see LocalVideoStateChanged + * @see Error + */ + CameraReady: EmptyCallback + + /** + * Occurs when the video stops playing. + * @deprecated Use Stopped(0) in the onLocalVideoStateChanged callback instead. The application can use this callback to change the configuration of the view (for example, displaying other pictures in the view) after the video stops playing. + * @see LocalVideoStreamState.Stopped + * @see LocalVideoStateChanged + */ + VideoStopped: EmptyCallback + + /** + * Occurs when the local user receives the metadata. + */ + MetadataReceived: MetadataCallback +} + +/** + * The RtcChannelEvents interface. + */ +export interface RtcChannelEvents { + /** + * Reports the warning code of the RtcChannel instance. + * @see RtcChannel + */ + Warning: WarningCallback + + /** + * Reports the error code of the RtcChannel instance. + * @see RtcChannel + */ + Error: ErrorCallback + + /** + * Occurs when the local user joins a specified channel. + * If the uid is not specified when calling joinChannel, the server automatically assigns a uid. + * @see RtcChannel.joinChannel + */ + JoinChannelSuccess: UidWithElapsedCallback + + /** + * Occurs when a user rejoins the channel after being disconnected due to network problems. + * When a user loses connection with the server because of network problems, the SDK automatically tries to reconnect and triggers this callback upon reconnection. + */ + RejoinChannelSuccess: UidWithElapsedCallback + + /** + * Occurs when a user leaves the channel. + * When a user leaves the channel by using the leaveChannel method, the SDK uses this callback to notify the app when the user leaves the channel. + * @see RtcChannel.leaveChannel + * With this callback, the app retrieves the channel information, such as the call duration and statistics. + */ + LeaveChannel: RtcStatsCallback + + /** + * Occurs when the user role switches in a Live-Broadcast channel. For example, from broadcaster to audience or vice versa. + * The SDK triggers this callback when the local user switches the user role by calling the setClientRole method after joining the channel. + * @see RtcChannel.setClientRole + */ + ClientRoleChanged: ClientRoleCallback + + /** + * Occurs when a remote user (Communication) or a broadcaster (Live-Broadcast) joins the channel. + * - Communication profile: This callback notifies the app when another user joins the channel. If other users are already in the channel, the SDK also reports to the app on the existing users. + * - Live-Broadcast profile: This callback notifies the app when the host joins the channel. If other hosts are already in the channel, the SDK also reports to the app on the existing hosts. We recommend having at most 17 hosts in a channel. + * Note + * - In the Live-Broadcast profile: + * -- The host receives this callback when another host joins the channel. + * -- The audience in the channel receives this callback when a new host joins the channel. + * -- When a web app joins the channel, this callback is triggered as long as the web app publishes streams. + */ + UserJoined: UidWithElapsedCallback + + /** + * Occurs when a remote user (Communication) or a broadcaster (Live Broadcast) leaves the channel. + * There are two reasons for users to become offline: + * - Leave the channel: When the user/broadcaster leaves the channel, the user/broadcaster sends a goodbye message. When this message is received, the SDK determines that the user/host leaves the channel. + * - Go offline: When no data packet of the user or broadcaster is received for a certain period of time (around 20 seconds), the SDK assumes that the user/broadcaster drops offline. A poor network connection may lead to false detections, so we recommend using the Agora RTM SDK for reliable offline detection. + */ + UserOffline: UserOfflineCallback + + /** + * Occurs when the network connection state changes. + * The Agora SDK triggers this callback to report on the current network connection state when it changes, and the reason to such change. + */ + ConnectionStateChanged: ConnectionStateCallback + + /** + * Occurs when the SDK cannot reconnect to Agora's edge server 10 seconds after its connection to the server is interrupted. + * The SDK also triggers this callback when it cannot connect to the server 10 seconds after calling joinChannel, regardless of whether it is in the channel or not. + * @see RtcChannel.joinChannel + * If the SDK fails to rejoin the channel 20 minutes after being disconnected from Agora's edge server, the SDK stops rejoining the channel. + */ + ConnectionLost: EmptyCallback + + /** + * Occurs when the token expires in 30 seconds. + * The user becomes offline if the token used when joining the channel expires. This callback is triggered 30 seconds before the token expires, to remind the app to get a new token. Upon receiving this callback, you need to generate a new token on the server and call renewToken to pass the new token to the SDK. + * @see RtcChannel.renewToken + */ + TokenPrivilegeWillExpire: TokenCallback + + /** + * Occurs when the token has expired. + * After a token is specified when joining the channel, the token expires after a certain period of time, and a new token is required to reconnect to the server. This callback notifies the app to generate a new token and call renewToken to renew the token. + * @see RtcChannel.renewToken + */ + RequestToken: EmptyCallback + + /** + * Reports which user is the loudest speaker. + * This callback reports the speaker with the highest accumulative volume during a certain period. If the user enables the audio volume indication by calling enableAudioVolumeIndication, this callback returns the uid of the active speaker whose voice is detected by the audio volume detection module of the SDK. + * @see RtcChannel.enableAudioVolumeIndication + * Note + * - To receive this callback, you need to call enableAudioVolumeIndication. + * @see RtcEngine.enableAudioVolumeIndication + * - This callback reports the ID of the user with the highest voice volume during a period of time, instead of at the moment. + */ + ActiveSpeaker: UidCallback + + /** + * Occurs when the video size or rotation information of a remote user changes. + */ + VideoSizeChanged: VideoSizeCallback + + /** + * Occurs when the remote video state changes. + */ + RemoteVideoStateChanged: RemoteVideoStateCallback + + /** + * Occurs when the remote audio state changes. + * This callback indicates the state change of the remote audio stream. + */ + RemoteAudioStateChanged: RemoteAudioStateCallback + + /** + * Occurs when the published media stream falls back to an audio-only stream due to poor network conditions or switches back to video stream after the network conditions improve. + * If you call setLocalPublishFallbackOption and set option as AudioOnly(2), this callback is triggered when the locally published stream falls back to audio-only mode due to poor uplink conditions, or when the audio stream switches back to the video after the uplink network condition improves. + * @see RtcEngine.setLocalPublishFallbackOption + * @see StreamFallbackOptions.AudioOnly + */ + LocalPublishFallbackToAudioOnly: FallbackCallback + + /** + * Occurs when the remote media stream falls back to audio-only stream due to poor network conditions or switches back to video stream after the network conditions improve. + * If you call setRemoteSubscribeFallbackOption and set option as AudioOnly(2), this callback is triggered when the remote media stream falls back to audio-only mode due to poor uplink conditions, or when the remote media stream switches back to the video after the uplink network condition improves. + * @see RtcEngine.setRemoteSubscribeFallbackOption + * @see StreamFallbackOptions.AudioOnly + * Note + * - Once the remote media stream is switched to the low stream due to poor network conditions, you can monitor the stream switch between a high and low stream in the onRemoteVideoStats callback. + * @see onRemoteVideoStats + */ + RemoteSubscribeFallbackToAudioOnly: FallbackWithUidCallback + + /** + * Reports the statistics of the RtcEngine once every two seconds. + * @see RtcEngine + */ + RtcStats: RtcStatsCallback + + /** + * Reports the last mile network quality of each user in the channel once every two seconds. + * Last mile refers to the connection between the local device and Agora's edge server. This callback reports once every two seconds the last mile network conditions of each user in the channel. If a channel includes multiple users, then this callback will be triggered as many times. + */ + NetworkQuality: NetworkQualityWithUidCallback + + /** + * Reports the statistics of the video stream from each remote user/broadcaster. The SDK triggers this callback once every two seconds for each remote user/broadcaster. If a channel includes multiple remote users, the SDK triggers this callback as many times. + */ + RemoteVideoStats: RemoteVideoStatsCallback + + /** + * Reports the statistics of the audio stream from each remote user/broadcaster. + * The SDK triggers this callback once every two seconds for each remote user/broadcaster. If a channel includes multiple remote users, the SDK triggers this callback as many times. + * Schemes such as FEC (Forward Error Correction) or retransmission counter the frame loss rate. Hence, users may find the overall audio quality acceptable even when the packet loss rate is high. + */ + RemoteAudioStats: RemoteAudioStatsCallback + + /** + * Occurs when the state of the RTMP streaming changes. + * The SDK triggers this callback to report the result of the local user calling the addPublishStreamUrl or removePublishStreamUrl method. This callback returns the URL and its current streaming state. When the streaming state is Failure(4), see the errCode parameter for details. + * @see RtcChannel.addPublishStreamUrl + * @see RtcChannel.removePublishStreamUrl + * @see RtmpStreamingState.Failure + * This callback indicates the state of the RTMP streaming. When exceptions occur, you can troubleshoot issues by referring to the detailed error descriptions in the errCode parameter. + */ + RtmpStreamingStateChanged: RtmpStreamingStateCallback + + /** + * Occurs when the publisher's transcoding settings are updated. + * When the LiveTranscoding class in the setLiveTranscoding method updates, the SDK triggers this callback to report the update information. + * @see RtcChannel.setLiveTranscoding + * Note + * - If you call the setLiveTranscoding method to set the LiveTranscoding class for the first time, the SDK does not trigger this callback. + */ + TranscodingUpdated: EmptyCallback + + /** + * Reports the status of injecting the online media stream. + */ + StreamInjectedStatus: StreamInjectedStatusCallback + + /** + * Occurs when the local user receives a remote data stream. + * The SDK triggers this callback when the local user receives the stream message that the remote user sends by calling the sendStreamMessage method. + * @see RtcChannel.sendStreamMessage + */ + StreamMessage: StreamMessageCallback + + /** + * Occurs when the local user fails to receive a remote data stream. + * The SDK triggers this callback when the local user fails to receive the stream message that the remote user sends by calling the sendStreamMessage method. + * @see RtcChannel.sendStreamMessage + */ + StreamMessageError: StreamMessageErrorCallback + + /** + * Occurs when the state of the media stream relay changes. + * The SDK reports the state of the current media relay and possible error messages in this callback. + */ + ChannelMediaRelayStateChanged: MediaRelayStateCallback + + /** + * Reports events during the media stream relay. + */ + ChannelMediaRelayEvent: MediaRelayEventCallback + + /** + * Occurs when the local user receives the metadata. + */ + MetadataReceived: MetadataCallback +} diff --git a/src/RtcRenderView.native.tsx b/src/RtcRenderView.native.tsx new file mode 100644 index 000000000..944121e8d --- /dev/null +++ b/src/RtcRenderView.native.tsx @@ -0,0 +1,146 @@ +import React, {Component} from "react"; +import {Platform, requireNativeComponent, ViewProps} from "react-native"; + +import {VideoMirrorMode, VideoRenderMode} from "./Types"; + +/** + * Properties of the uid. + * @property uid: int | User ID. + */ +interface RtcUidProps { + uid: number; +} + +/** + * Properties of the SurfaceView. + * @property zOrderMediaOverlay: boolean | Control whether the surface view's surface is placed on top of another regular surface view in the window (but still behind the window itself). + * @property zOrderOnTop: boolean | Control whether the surface view's surface is placed on top of its window. + * @property renderMode: number | The rendering mode of the video view. + * @see VideoRenderMode + * @property channelId: string | The unique channel name for the AgoraRTC session in the string format. The string length must be less than 64 bytes. Supported character scopes are: + * - All lowercase English letters: a to z. + * - All uppercase English letters: A to Z. + * - All numeric characters: 0 to 9. + * - The space character. + * - Punctuation characters and other symbols, including: "!", "#", "$", "%", "&", "(", ")", "+", "-", ":", ";", "<", "=", ".", ">", "?", "@", "[", "]", "^", "_", " {", "}", "|", "~", ",". + * Note + * - The default value is the empty string "". Use the default value if the user joins the channel using the joinChannel method in the RtcEngine class. + * @see RtcEngine.joinChannel + * - If the user joins the channel using the joinChannel method in the RtcChannel class, set this parameter as the channelId of the RtcChannel object. + * @see RtcChannel.joinChannel + * @property mirrorMode: number | The video mirror mode. + * @see VideoMirrorMode + */ +interface RtcSurfaceViewProps extends ViewProps { + zOrderMediaOverlay?: boolean; + zOrderOnTop?: boolean; + renderMode?: VideoRenderMode; + channelId?: string; + mirrorMode?: VideoMirrorMode; +} + +/** + * Properties of the TextureView. + * @property channelId: string | The unique channel name for the AgoraRTC session in the string format. The string length must be less than 64 bytes. Supported character scopes are: + * - All lowercase English letters: a to z. + * - All uppercase English letters: A to Z. + * - All numeric characters: 0 to 9. + * - The space character. + * - Punctuation characters and other symbols, including: "!", "#", "$", "%", "&", "(", ")", "+", "-", ":", ";", "<", "=", ".", ">", "?", "@", "[", "]", "^", "_", " {", "}", "|", "~", ",". + * Note + * - The default value is the empty string "". Use the default value if the user joins the channel using the joinChannel method in the RtcEngine class. + * @see RtcEngine.joinChannel + * - If the user joins the channel using the joinChannel method in the RtcChannel class, set this parameter as the channelId of the RtcChannel object. + * @see RtcChannel.joinChannel + * @property mirror: boolean | The video mirror. + */ +interface RtcTextureViewProps extends ViewProps { + channelId?: string; + mirror?: boolean; +} + +const RCTRtcSurfaceView = requireNativeComponent('RCTAgoraRtcSurfaceView'); + +class RtcSurfaceView extends Component { + render() { + return ( + + ) + } +} + +const RCTRtcTextureView = requireNativeComponent('RCTAgoraRtcTextureView'); + +class RtcTextureView extends Component { + render() { + return ( + + ) + } +} + +/** + * View for preview local video. + */ +export namespace RtcLocalView { + /** + * Use SurfaceView in Android. + * Use UIView in iOS. + */ + export class SurfaceView extends Component { + render() { + return ( + + ); + } + } + + /** + * Use TextureView in Android. + * Not support for iOS. + */ + export class TextureView extends Component { + render() { + if (Platform.OS === 'ios') + throw new Error('TextureView not support for iOS') + return ( + + ); + } + } +} + +/** + * View for render remote video. + */ +export namespace RtcRemoteView { + /** + * Use SurfaceView in Android. + * Use UIView in iOS. + */ + export class SurfaceView extends Component { + render() { + return ( + + ); + } + } + + /** + * Use TextureView in Android. + * Not support for iOS. + */ + export class TextureView extends Component { + render() { + if (Platform.OS === 'ios') + throw new Error('TextureView not support for iOS') + return ( + + ); + } + } +} diff --git a/src/Types.ts b/src/Types.ts new file mode 100644 index 000000000..d017ecaad --- /dev/null +++ b/src/Types.ts @@ -0,0 +1,2955 @@ +/** + * IP areas + * @enum {number} + */ +export enum IPAreaCode { + /** + * Mainland China + */ + AREA_CN = 1 << 0, + /** + * North America + */ + AREA_NA = 1 << 1, + /** + * AREA_EUR + */ + AREA_EUR = 1 << 2, + /** + * Asia, excluding Mainland China + */ + AREA_AS = 1 << 3, + /** + * (Default) Global + */ + AREA_GLOBAL = -1, +} + +/** + * Audio codec profile. + * @enum {number} + */ +export enum AudioCodecProfileType { + /** + * (Default) LC-AAC, the low-complexity audio codec profile. + */ + LCAAC = 0, + /** + * HE-AAC, the high-efficiency audio codec profile. + */ + HEAAC = 1, +} + +/** + * Audio equalization band frequency. + * @enum {number} + */ +export enum AudioEqualizationBandFrequency { + /** + * 31 Hz. + */ + Band31 = 0, + /** + * 62 Hz. + */ + Band62 = 1, + /** + * 125 Hz. + */ + Band125 = 2, + /** + * 250 Hz. + */ + Band250 = 3, + /** + * 500 Hz. + */ + Band500 = 4, + /** + * 1 kHz. + */ + Band1K = 5, + /** + * 2 kHz. + */ + Band2K = 6, + /** + * 4 kHz. + */ + Band4K = 7, + /** + * 8 kHz. + */ + Band8K = 8, + /** + * 16 kHz. + */ + Band16K = 9, +} + +/** + * The error information of the local audio. + * @enum {number} + */ +export enum AudioLocalError { + /** + * The local audio is normal. + */ + Ok = 0, + /** + * No specified reason for the local audio failure. + */ + Failure = 1, + /** + * No permission to use the local audio device. + */ + DeviceNoPermission = 2, + /** + * The microphone is in use. + */ + DeviceBusy = 3, + /** + * The local audio recording fails. Check whether the recording device is working properly. + */ + RecordFailure = 4, + /** + * The local audio encoding fails. + */ + EncodeFailure = 5, +} + +/** + * The state of the local audio. + * @enum {number} + */ +export enum AudioLocalState { + /** + * The local audio is in the initial state. + */ + Stopped = 0, + /** + * The recording device starts successfully. + */ + Recording = 1, + /** + * The first audio frame encodes successfully. + */ + Encoding = 2, + /** + * The local audio fails to start. + */ + Failed = 3, +} + +/** + * The error code of the audio mixing file. + * @enum {number} + */ +export enum AudioMixingErrorCode { + /** + * The SDK cannot open the audio mixing file. + */ + CanNotOpen = 701, + /** + * The SDK opens the audio mixing file too frequently. + */ + TooFrequentCall = 702, + /** + * The opening of the audio mixing file is interrupted. + */ + InterruptedEOF = 703, + /** + * No error. + */ + OK = 0, +} + +/** + * The state of the audio mixing file. + * @enum {number} + */ +export enum AudioMixingStateCode { + /** + * The audio mixing file is playing. + */ + Playing = 710, + /** + * The audio mixing file pauses playing. + */ + Paused = 711, + /** + * The audio mixing file stops playing. + */ + Stopped = 713, + /** + * An exception occurs when playing the audio mixing file. + */ + Failed = 714, +} + +/** + * Audio output routing. + * @enum {number} + */ +export enum AudioOutputRouting { + /** + * Default. + */ + Default = -1, + /** + * Headset. + */ + Headset = 0, + /** + * Earpiece. + */ + Earpiece = 1, + /** + * Headset with no microphone. + */ + HeadsetNoMic = 2, + /** + * Speakerphone. + */ + Speakerphone = 3, + /** + * Loudspeaker. + */ + Loudspeaker = 4, + /** + * Bluetooth headset. + */ + HeadsetBluetooth = 5, +} + +/** + * Audio profile. + * @enum {number} + */ +export enum AudioProfile { + /** + * Default audio profile. + * - In the Communication profile: A sample rate of 32 KHz, audio encoding, mono, and a bitrate of up to 18 Kbps. + * - In the Live-broadcast profile: A sample rate of 48 KHz, music encoding, mono, and a bitrate of up to 52 Kbps. + */ + Default = 0, + /** + * A sample rate of 32 KHz, audio encoding, mono, and a bitrate of up to 18 Kbps. + */ + SpeechStandard = 1, + /** + * A sample rate of 48 KHz, music encoding, mono, and a bitrate of up to 48 Kbps. + */ + MusicStandard = 2, + /** + * A sample rate of 48 KHz, music encoding, stereo, and a bitrate of up to 56 Kbps. + */ + MusicStandardStereo = 3, + /** + * A sample rate of 48 KHz, music encoding, mono, and a bitrate of up to 128 Kbps. + */ + MusicHighQuality = 4, + /** + * A sample rate of 48 KHz, music encoding, stereo, and a bitrate of up to 192 Kbps. + */ + MusicHighQualityStereo = 5, +} + +/** + * Use mode of the onRecordAudioFrame callback. + * @enum {number} + * TODO setPlaybackAudioFrameParameters + */ +export enum AudioRawFrameOperationMode { + /** + * Users only read the AudioFrame data without modifying anything. For example, when users acquire data with the Agora SDK then push the RTMP streams. + */ + ReadOnly = 0, + /** + * Users replace the AudioFrame data with their own data and pass them to the SDK for encoding. For example, when users acquire data. + */ + WriteOnly = 1, + /** + * Users read the data from AudioFrame, modify it, and then play it. For example, when users have their own sound-effect processing module and perform some voice pre-processing such as a voice change. + */ + ReadWrite = 2, +} + +/** + * Audio recording quality. + */ +export enum AudioRecordingQuality { + /** + * The sample rate is 32 KHz, and the file size is around 1.2 MB after 10 minutes of recording. + */ + Low = 0, + /** + * The sample rate is 32 KHz, and the file size is around 2 MB after 10 minutes of recording. + */ + Medium = 1, + /** + * The sample rate is 32 KHz, and the file size is around 3.75 MB after 10 minutes of recording. + */ + High = 2, +} + +/** + * The state of the remote audio. + * @enum {number} + */ +export enum AudioRemoteState { + /** + * The remote audio is in the default state, probably due to: + * @see AudioRemoteStateReason.LocalMuted + * @see AudioRemoteStateReason.RemoteMuted + * @see AudioRemoteStateReason.RemoteOffline + */ + Stopped = 0, + /** + * The first remote audio packet is received. + */ + Starting = 1, + /** + * The remote audio stream is decoded and plays normally, probably due to: + * @see AudioRemoteStateReason.NetworkRecovery + * @see AudioRemoteStateReason.LocalUnmuted + * @see AudioRemoteStateReason.RemoteUnmuted + */ + Decoding = 2, + /** + * The remote audio is frozen, probably due to: + * @see AudioRemoteStateReason.NetworkCongestion + */ + Frozen = 3, + /** + * The remote audio fails to start, probably due to: + * @see AudioRemoteStateReason.Internal + */ + Failed = 4, +} + +/** + * The reason of the remote audio state change. + * @enum {number} + */ +export enum AudioRemoteStateReason { + /** + * Internal reasons. + */ + Internal = 0, + /** + * Network congestion. + */ + NetworkCongestion = 1, + /** + * Network recovery. + */ + NetworkRecovery = 2, + /** + * The local user stops receiving the remote audio stream or disables the audio module. + */ + LocalMuted = 3, + /** + * The local user resumes receiving the remote audio stream or enables the audio module. + */ + LocalUnmuted = 4, + /** + * The remote user stops sending the audio stream or disables the audio module. + */ + RemoteMuted = 5, + /** + * The remote user resumes sending the audio stream or enables the audio module. + */ + RemoteUnmuted = 6, + /** + * The remote user leaves the channel. + */ + RemoteOffline = 7, +} + +/** + * The preset local voice reverberation option. + * @enum {number} + */ +export enum AudioReverbPreset { + /** + * The original voice (no local voice reverberation). + */ + Off = 0x00000000, + /** + * Pop music + */ + Popular = 0x00000001, + /** + * R&B + */ + RnB = 0x00000002, + /** + * Rock music + */ + Rock = 0x00000003, + /** + * Hip-hop music + */ + HipHop = 0x00000004, + /** + * Pop concert + */ + VocalConcert = 0x00000005, + /** + * Karaoke + */ + KTV = 0x00000006, + /** + * Recording studio + */ + Studio = 0x00000007, + /** + * The reverberation style typical of a KTV venue (enhanced). + */ + FX_KTV = 0x00100001, + /** + * The reverberation style typical of a concert hall (enhanced). + */ + FX_VOCAL_CONCERT = 0x00100002, + /** + * The reverberation style typical of an uncle’s voice. + */ + FX_UNCLE = 0x00100003, + /** + * The reverberation style typical of a sister’s voice. + */ + FX_SISTER = 0x00100004, + /** + * The reverberation style typical of a recording studio (enhanced). + */ + FX_STUDIO = 0x00100005, + /** + * The reverberation style typical of popular music (enhanced). + */ + FX_POPULAR = 0x00100006, + /** + * The reverberation style typical of R&B music (enhanced). + */ + FX_RNB = 0x00100007, + /** + * The reverberation style typical of the vintage phonograph. + */ + FX_PHONOGRAPH = 0x00100008, + /** + * The reverberation of the virtual stereo. The virtual stereo is an effect that renders the monophonic audio as the stereo audio, so that all users in the channel can hear the stereo voice effect. To achieve better virtual stereo reverberation, Agora recommends setting the profile parameter in setAudioProfile as MusicHighQualityStereo(5). + * @see RtcEngine#setAudioProfile + * @see AudioProfile.MusicHighQualityStereo + */ + VIRTUAL_STEREO = 0x00200001, +} + +/** + * Audio reverberation type. + * @enum {number} + */ +export enum AudioReverbType { + /** + * The level of the dry signal (dB). The value ranges between -20 and 10. + */ + DryLevel = 0, + /** + * The level of the early reflection signal (wet signal) in dB. The value ranges between -20 and 10. + */ + WetLevel = 1, + /** + * The room size of the reverberation. A larger room size means a stronger reverberation. The value ranges between 0 and 100. + */ + RoomSize = 2, + /** + * The length of the initial delay of the wet signal (ms). The value ranges between 0 and 200. + */ + WetDelay = 3, + /** + * The reverberation strength. The value ranges between 0 and 100. + */ + Strength = 4, +} + +/** + * Audio sample rate. + * @enum {number} + */ +export enum AudioSampleRateType { + /** + * 32 kHz. + */ + Type32000 = 32000, + /** + * 44.1 kHz. + */ + Type44100 = 44100, + /** + * 48 kHz. + */ + Type48000 = 48000, +} + +/** + * Audio scenario. + * @enum {number} + */ +export enum AudioScenario { + /** + * Default. + */ + Default = 0, + /** + * Entertainment scenario, supporting voice during gameplay. + */ + ChatRoomEntertainment = 1, + /** + * Education scenario, prioritizing fluency and stability. + */ + Education = 2, + /** + * Live gaming scenario, enabling the gaming audio effects in the speaker mode in a live broadcast scenario. Choose this scenario for high-fidelity music playback. + */ + GameStreaming = 3, + /** + * Showroom scenario, optimizing the audio quality with external professional equipment. + */ + ShowRoom = 4, + /** + * Gaming scenario. + */ + ChatRoomGaming = 5, +} + +/** + * Audio session restriction. + * @enum {number} + * TODO iOS setAudioSessionOperationRestriction + */ +export enum AudioSessionOperationRestriction { + /** + * No restriction, the SDK has full control of the audio session operations. + */ + None = 0, + /** + * The SDK does not change the audio session category. + */ + SetCategory = 1, + /** + * The SDK does not change any setting of the audio session (category, mode, categoryOptions). + */ + ConfigureSession = 1 << 1, + /** + * The SDK keeps the audio session active when leaving a channel. + */ + DeactivateSession = 1 << 2, + /** + * The SDK does not configure the audio session anymore. + */ + All = 1 << 7, +} + +/** + * The preset audio voice configuration used to change the voice effect. + * @enum {number} + */ +export enum AudioVoiceChanger { + /** + * The original voice (no local voice change). + */ + Off = 0x00000000, + /** + * An old man’s voice. + */ + OldMan = 0x00000001, + /** + * A little boy’s voice. + */ + BabyBoy = 0x00000002, + /** + * A little girl’s voice. + */ + BabyGirl = 0x00000003, + /** + * TBD + */ + ZhuBaJie = 0x00000004, + /** + * Ethereal vocal effects. + */ + Ethereal = 0x00000005, + /** + * Hulk’s voice. + */ + Hulk = 0x00000006, + /** + * A more vigorous voice. + */ + BEAUTY_VIGOROUS = 0x00100001, + /** + * A deeper voice. + */ + BEAUTY_DEEP = 0x00100002, + /** + * A mellower voice. + */ + BEAUTY_MELLOW = 0x00100003, + /** + * Falsetto. + */ + BEAUTY_FALSETTO = 0x00100004, + /** + * A fuller voice. + */ + BEAUTY_FULL = 0x00100005, + /** + * A clearer voice. + */ + BEAUTY_CLEAR = 0x00100006, + /** + * A more resounding voice. + */ + BEAUTY_RESOUNDING = 0x00100007, + /** + * A more ringing voice. + */ + BEAUTY_RINGING = 0x00100008, + /** + * A more spatially resonant voice. + */ + BEAUTY_SPACIAL = 0x00100009, + /** + * (For male only) A more magnetic voice. Do not use it when the speaker is a female; otherwise, voice distortion occurs. + */ + GENERAL_BEAUTY_VOICE_MALE_MAGNETIC = 0x00200001, + /** + * (For female only) A fresher voice. Do not use it when the speaker is a male; otherwise, voice distortion occurs. + */ + GENERAL_BEAUTY_VOICE_FEMALE_FRESH = 0x00200002, + /** + * (For female only) A more vital voice. Do not use it when the speaker is a male; otherwise, voice distortion occurs. + */ + GENERAL_BEAUTY_VOICE_FEMALE_VITALITY = 0x00200003, +} + +/** + * The camera capturer configuration. + * @enum {number} + */ +export enum CameraCaptureOutputPreference { + /** + * (default) Self-adapts the camera output parameters to the system performance and network conditions to balance CPU consumption and video preview quality. + */ + Auto = 0, + /** + * Prioritizes the system performance. The SDK chooses the dimension and frame rate of the local camera capture closest to those set by setVideoEncoderConfiguration. + * @see RtcEngine.setVideoEncoderConfiguration + */ + Performance = 1, + /** + * Prioritizes the local preview quality. The SDK chooses higher camera output parameters to improve the local video preview quality. This option requires extra CPU and RAM usage for video pre-processing. + */ + Preview = 2, + /** + * Internal use only + */ + Unkown = 3, +} + +/** + * The camera direction. + * @enum {number} + */ +export enum CameraDirection { + /** + * The rear camera. + */ + Rear = 0, + /** + * The front camera. + */ + Front = 1, +} + +/** + * The error code in AgoraChannelMediaRelayError. + * @enum {number} + */ +export enum ChannelMediaRelayError { + /** + * The state is normal. + */ + None = 0, + /** + * An error occurs in the server response. + */ + ServerErrorResponse = 1, + /** + * No server response. You can call the leaveChannel method to leave the channel. + * @see RtcEngine.leaveChannel + */ + ServerNoResponse = 2, + /** + * The SDK fails to access the service, probably due to limited resources of the server. + */ + NoResourceAvailable = 3, + /** + * Fails to send the relay request. + */ + FailedJoinSourceChannel = 4, + /** + * Fails to accept the relay request. + */ + FailedJoinDestinationChannel = 5, + /** + * The server fails to receive the media stream. + */ + FailedPacketReceivedFromSource = 6, + /** + * The server fails to send the media stream. + */ + FailedPacketSentToDestination = 7, + /** + * The SDK disconnects from the server due to poor network connections. You can call the leaveChannel method to leave the channel. + * @see RtcEngine.leaveChannel + */ + ServerConnectionLost = 8, + /** + * An internal error occurs in the server. + */ + InternalError = 9, + /** + * The token of the source channel has expired. + */ + SourceTokenExpired = 10, + /** + * The token of the destination channel has expired. + */ + DestinationTokenExpired = 11, +} + +/** + * The event code in AgoraChannelMediaRelayEvent. + * @enum {number} + */ +export enum ChannelMediaRelayEvent { + /** + * The user disconnects from the server due to poor network connections. + */ + Disconnect = 0, + /** + * The network reconnects. + */ + Connected = 1, + /** + * The user joins the source channel. + */ + JoinedSourceChannel = 2, + /** + * The user joins the destination channel. + */ + JoinedDestinationChannel = 3, + /** + * The SDK starts relaying the media stream to the destination channel. + */ + SentToDestinationChannel = 4, + /** + * The server receives the video stream from the source channel. + */ + ReceivedVideoPacketFromSource = 5, + /** + * The server receives the audio stream from the source channel. + */ + ReceivedAudioPacketFromSource = 6, + /** + * The destination channel is updated. + */ + UpdateDestinationChannel = 7, + /** + * The destination channel update fails due to internal reasons. + */ + UpdateDestinationChannelRefused = 8, + /** + * The destination channel does not change, which means that the destination channel fails to be updated. + */ + UpdateDestinationChannelNotChange = 9, + /** + * The destination channel name is NULL. + */ + UpdateDestinationChannelIsNil = 10, + /** + * The video profile is sent to the server. + */ + VideoProfileUpdate = 11, +} + +/** + * The state code in AgoraChannelMediaRelayState. + * @enum {number} + */ +export enum ChannelMediaRelayState { + /** + * The SDK is initializing. + */ + Idle = 0, + /** + * The SDK tries to relay the media stream to the destination channel. + */ + Connecting = 1, + /** + * The SDK successfully relays the media stream to the destination channel. + */ + Running = 2, + /** + * A failure occurs. See the details in error. + */ + Failure = 3, +} + +/** + * Channel profile. + * @enum {number} + */ +export enum ChannelProfile { + /** + * (Default) The Communication profile. + * Use this profile in one-on-one calls or group calls, where all users can talk freely. + */ + Communication = 0, + /** + * The Live-Broadcast profile. + * Users in a live-broadcast channel have a role as either broadcaster or audience. A broadcaster can both send and receive streams; an audience can only receive streams. + */ + LiveBroadcasting = 1, + /** + * The Gaming profile. + * This profile uses a codec with a lower bitrate and consumes less power. Applies to the gaming scenario, where all game players can talk freely. + */ + Game = 2, +} + +/** + * Client role in a live broadcast. + * @enum {number} + */ +export enum ClientRole { + /** + * A broadcaster can both send and receive streams. + */ + Broadcaster = 1, + /** + * The default role. An audience can only receive streams. + */ + Audience = 2, +} + +/** + * Reasons for the connection state change. + * @enum {number} + */ +export enum ConnectionChangedReason { + /** + * The SDK is connecting to Agora’s edge server. + */ + Connecting = 0, + /** + * The SDK has joined the channel successfully. + */ + JoinSuccess = 1, + /** + * The connection between the SDK and Agora’s edge server is interrupted. + */ + Interrupted = 2, + /** + * The connection between the SDK and Agora’s edge server is banned by Agora’s edge server. + */ + BannedByServer = 3, + /** + * The SDK fails to join the channel for more than 20 minutes and stops reconnecting to the channel. + */ + JoinFailed = 4, + /** + * The SDK has left the channel. + */ + LeaveChannel = 5, + /** + * The specified App ID is invalid. Try to rejoin the channel with a valid App ID. + */ + InvalidAppId = 6, + /** + * The specified channel name is invalid. Try to rejoin the channel with a valid channel name. + */ + InvalidChannelName = 7, + /** + * The generated token is invalid probably due to the following reasons: + * - The App Certificate for the project is enabled in Console, but you do not use Token when joining the channel. If you enable the App Certificate, you must use a token to join the channel. + * - The uid that you specify in the joinChannel method is different from the uid that you pass for generating the token. + * @see RtcEngine.joinChannel + */ + InvalidToken = 8, + /** + * The token has expired. Generate a new token from your server. + */ + TokenExpired = 9, + /** + * The user is banned by the server. + */ + RejectedByServer = 10, + /** + * The SDK tries to reconnect after setting a proxy server. + */ + SettingProxyServer = 11, + /** + * The token renews. + */ + RenewToken = 12, + /** + * The client IP address has changed, probably due to a change of the network type, IP address, or network port. + */ + ClientIpAddressChanged = 13, + /** + * Timeout for the keep-alive of the connection between the SDK and Agora’s edge server. The connection state changes to: + * @see ConnectionStateType.Reconnecting + */ + KeepAliveTimeout = 14, +} + +/** + * Connection states. + * @enum {number} + */ +export enum ConnectionStateType { + /** + * The SDK is disconnected from Agora's edge server. + * - This is the initial state before joinChannel. + * @see RtcEngine.joinChannel + * - The SDK also enters this state when the app calls leaveChannel. + * @see RtcEngine.leaveChannel + */ + Disconnected = 1, + /** + * The SDK is connecting to Agora's edge server. + * - When the app calls joinChannel, the SDK starts to establish a connection to the specified channel, triggers the onConnectionStateChanged callback, and switches to the Connecting state. + * @see RtcEngine.joinChannel + * @see RtcEngineEvents.onConnectionStateChanged + * @see ConnectionStateType.Connecting + * - When the SDK successfully joins the channel, the SDK triggers the onConnectionStateChanged callback and switches to the Connected state. + * @see RtcEngineEvents.onConnectionStateChanged + * @see ConnectionStateType.Connected + * - After the SDK joins the channel and when it finishes initializing the media engine, the SDK triggers the onJoinChannelSuccess callback. + * @see RtcEngineEvents.onJoinChannelSuccess + */ + Connecting = 2, + /** + * The SDK is connected to Agora's edge server and joins a channel. You can now publish or subscribe to a media stream in the channel. + * If the connection to the channel is lost because, for example, the network is down or switched, the SDK automatically tries to reconnect and triggers: + * - The onConnectionStateChanged callback, and switches to the Reconnecting state. + * @see RtcEngineEvents.onConnectionStateChanged + * @see ConnectionStateType.Reconnecting + */ + Connected = 3, + /** + * The SDK keeps rejoining the channel after being disconnected from a joined channel because of network issues. + * - If the SDK cannot rejoin the channel within 10 seconds after being disconnected from Agora’s edge server, the SDK triggers the onConnectionLost callback, stays in the Reconnecting state, and keeps rejoining the channel. + * @see RtcEngineEvents.onConnectionLost + * - If the SDK fails to rejoin the channel 20 minutes after being disconnected from Agora’s edge server, the SDK triggers the onConnectionStateChanged callback, switches to the Failed state, and stops rejoining the channel. + * @see RtcEngineEvents.onConnectionStateChanged + * @see ConnectionStateType.Failed + */ + Reconnecting = 4, + /** + * The SDK fails to connect to Agora's edge server or join the channel. + * You must call leaveChannel to leave this state, and call joinChannel again to rejoin the channel. + * @see RtcEngine.leaveChannel + * @see RtcEngine.joinChannel + * If the SDK is banned from joining the channel by Agora’s edge server (through the RESTful API), the SDK triggers the onConnectionStateChanged callbacks. + * @see RtcEngineEvents.onConnectionStateChanged + */ + Failed = 5, +} + +/** + * The video encoding degradation preference under limited bandwidth. + * @enum {number} + */ +export enum DegradationPreference { + /** + * (Default) Degrades the frame rate to guarantee the video quality. + */ + MaintainQuality = 0, + /** + * Degrades the video quality to guarantee the frame rate. + */ + MaintainFramerate = 1, + /** + * Reserved for future use. + */ + Balanced = 2, +} + +/** + * Encryption mode + * @enum {string} + */ +export enum EncryptionMode { + /** + * (Default) 128-bit AES encryption, XTS mode. + */ + AES128XTS = 'aes-128-xts', + /** + * 256-bit AES encryption, XTS mode. + */ + AES256XTS = 'aes-256-xts', + /** + * 128-bit AES encryption, ECB mode. + */ + AES128ECB = 'aes-128-ecb', +} + +/** + * Error codes occur when the SDK encounters an error that cannot be recovered automatically without any app intervention. + * @enum {number} + */ +export enum ErrorCode { + /** + * No error occurs. + */ + NoError = 0, + /** + * A general error occurs (no specified reason). + */ + Failed = 1, + /** + * An invalid parameter is used. For example, the specific channel name includes illegal characters. + */ + InvalidArgument = 2, + /** + * The SDK module is not ready. + * Possible solutions: + * - Check the audio device. + * - Check the completeness of the app. + * - Re-initialize the SDK. + */ + NotReady = 3, + /** + * The current state of the SDK does not support this function. + */ + NotSupported = 4, + /** + * The request is rejected. This is for internal SDK use only, and is not returned to the app through any method or callback. + */ + Refused = 5, + /** + * The buffer size is not big enough to store the returned data. + */ + BufferTooSmall = 6, + /** + * The SDK is not initialized before calling this method. + */ + NotInitialized = 7, + /** + * No permission exists. Check if the user has granted access to the audio or video device. + */ + NoPermission = 9, + /** + * An API method timeout occurs. Some API methods require the SDK to return the execution result, and this error occurs if the request takes too long (over 10 seconds) for the SDK to process. + */ + TimedOut = 10, + /** + * The request is canceled. This is for internal SDK use only, and is not returned to the app through any method or callback. + */ + Canceled = 11, + /** + * The method is called too often. This is for internal SDK use only, and is not returned to the app through any method or callback. + */ + TooOften = 12, + /** + * The SDK fails to bind to the network socket. This is for internal SDK use only, and is not returned to the app through any method or callback. + */ + BindSocket = 13, + /** + * The network is unavailable. This is for internal SDK use only, and is not returned to the app through any method or callback. + */ + NetDown = 14, + /** + * No network buffers are available. This is for internal SDK use only, and is not returned to the app through any method or callback. + */ + NoBufs = 15, + /** + * The request to join the channel is rejected. + * Possible reasons are: + * - The user is already in the channel, and still calls the API method to join the channel, for example, joinChannel + * @see RtcEngine.joinChannel + * - The user tries joining the channel during the echo test. Please join the channel after the echo test ends. + */ + JoinChannelRejected = 17, + /** + * The request to leave the channel is rejected. + * Possible reasons are: + * - The user left the channel and still calls the API method to leave the channel, for example, leaveChannel. + * @see RtcEngine.leaveChannel + * - The user has not joined the channel and calls the API method to leave the channel. + */ + LeaveChannelRejected = 18, + /** + * The resources are occupied and cannot be used. + */ + AlreadyInUse = 19, + /** + * The SDK gave up the request due to too many requests. + */ + Abort = 20, + /** + * In Windows, specific firewall settings cause the SDK to fail to initialize and crash. + */ + InitNetEngine = 21, + /** + * The app uses too much of the system resources and the SDK fails to allocate the resources. + */ + ResourceLimited = 22, + /** + * The specified App ID is invalid. Please try to rejoin the channel with a valid App ID. + */ + InvalidAppId = 101, + /** + * The specified channel name is invalid. Please try to rejoin the channel with a valid channel name. + */ + InvalidChannelId = 102, + /** + * The token expired. DEPRECATED as of v2.4.1. Use TokenExpired(9) in the reason parameter of onConnectionStateChanged. + * @see ConnectionChangedReason.TokenExpired + * @see RtcEngineEvents.onConnectionStateChanged + * Possible reasons are: + * - Authorized Timestamp expired: The timestamp is represented by the number of seconds elapsed since 1/1/1970. The user can use the token to access the Agora service within five minutes after the token is generated. If the user does not access the Agora service after five minutes, this token is no longer valid. + * - Call Expiration Timestamp expired: The timestamp is the exact time when a user can no longer use the Agora service (for example, when a user is forced to leave an ongoing call). When a value is set for the Call Expiration Timestamp, it does not mean that the token will expire, but that the user will be banned from the channel. + * @deprecated + */ + TokenExpired = 109, + /** + * The token is invalid. DEPRECATED as of v2.4.1. Use InvalidToken(8) in the reason parameter of onConnectionStateChanged. + * @see ConnectionChangedReason.InvalidToken + * @see RtcEngineEvents.onConnectionStateChanged + * Possible reasons are: + * - The App Certificate for the project is enabled in Console, but the user is using the App ID. Once the App Certificate is enabled, the user must use a token. + * - The uid is mandatory, and users must set the same uid as the one set in the joinChannel method. + * @see RtcEngine.joinChannel + * @deprecated + */ + InvalidToken = 110, + /** + * The Internet connection is interrupted. This applies to the Agora Web SDK only. + */ + ConnectionInterrupted = 111, + /** + * The Internet connection is lost. This applies to the Agora Web SDK only. + */ + ConnectionLost = 112, + /** + * The user is not in the channel when calling the sendStreamMessage or getUserInfoByUserAccount method. + * @see RtcEngine.sendStreamMessage + * @see RtcEngine.getUserInfoByUserAccount + */ + NotInChannel = 113, + /** + * The size of the sent data is over 1024 bytes when the user calls the sendStreamMessage method. + * @see RtcEngine.sendStreamMessage + */ + SizeTooLarge = 114, + /** + * The bitrate of the sent data exceeds the limit of 6 Kbps when the user calls the sendStreamMessage method. + * @see RtcEngine.sendStreamMessage + */ + BitrateLimit = 115, + /** + * Too many data streams (over five streams) are created when the user calls the createDataStream method. + * @see RtcEngine.createDataStream + */ + TooManyDataStreams = 116, + /** + * Decryption fails. The user may have used a different encryption password to join the channel. Check your settings or try rejoining the channel. + */ + DecryptionFailed = 120, + /** + * The client is banned by the server. + */ + ClientIsBannedByServer = 123, + /** + * Incorrect watermark file parameter. + */ + WatermarkParam = 124, + /** + * Incorrect watermark file path. + */ + WatermarkPath = 125, + /** + * Incorrect watermark file format. + */ + WatermarkPng = 126, + /** + * Incorrect watermark file information. + */ + WatermarkInfo = 127, + /** + * Incorrect watermark file data format. + */ + WatermarkAGRB = 128, + /** + * An error occurs in reading the watermark file. + */ + WatermarkRead = 129, + /** + * The encrypted stream is not allowed to publish. + */ + EncryptedStreamNotAllowedPublish = 130, + /** + * The user account is invalid. + */ + InvalidUserAccount = 134, + /** + * CDN related errors. Remove the original URL address and add a new one by calling the removePublishStreamUrl and addPublishStreamUrl methods. + * @see RtcEngine.removePublishStreamUrl + * @see RtcEngine.addPublishStreamUrl + */ + PublishStreamCDNError = 151, + /** + * The host publishes more than 10 URLs. Delete the unnecessary URLs before adding new ones. + */ + PublishStreamNumReachLimit = 152, + /** + * The host manipulates other hosts' URLs. Check your app logic. + */ + PublishStreamNotAuthorized = 153, + /** + * An error occurs in Agora’s streaming server. Call the addPublishStreamUrl method to publish the stream again. + * @see RtcEngine.addPublishStreamUrl + */ + PublishStreamInternalServerError = 154, + /** + * The server fails to find the stream. + */ + PublishStreamNotFound = 155, + /** + * The format of the RTMP stream URL is not supported. Check whether the URL format is correct. + */ + PublishStreamFormatNotSuppported = 156, + /** + * Fails to load the media engine. + */ + LoadMediaEngine = 1001, + /** + * Fails to start the call after enabling the media engine. + */ + StartCall = 1002, + /** + * Fails to start the camera. DEPRECATED as of v2.4.1. Use CaptureFailure(4) in the error parameter of onLocalVideoStateChanged. + * @see LocalVideoStreamError.CaptureFailure + * @see RtcEngineEvents.onLocalVideoStateChanged + * @deprecated + */ + StartCamera = 1003, + /** + * Fails to start the video rendering module. + */ + StartVideoRender = 1004, + /** + * Audio Device Module: A general error occurs in the Audio Device Module (the reason is not classified specifically). Check if the audio device is used by another app, or try rejoining the channel. + */ + AdmGeneralError = 1005, + /** + * Audio Device Module: An error occurs in using the Java resources. + */ + AdmJavaResource = 1006, + /** + * Audio Device Module: An error occurs in setting the sampling frequency. + */ + AdmSampleRate = 1007, + /** + * Audio Device Module: An error occurs in initializing the playback device. + */ + AdmInitPlayout = 1008, + /** + * Audio Device Module: An error occurs in starting the playback device. + */ + AdmStartPlayout = 1009, + /** + * Audio Device Module: An error occurs in stopping the playback device. + */ + AdmStopPlayout = 1010, + /** + * Audio Device Module: An error occurs in initializing the recording device. + */ + AdmInitRecording = 1011, + /** + * Audio Device Module: An error occurs in starting the recording device. + */ + AdmStartRecording = 1012, + /** + * Audio Device Module: An error occurs in stopping the recording device. + */ + AdmStopRecording = 1013, + /** + * Audio Device Module: A playback error occurs. Check your playback device, or try rejoining the channel. + */ + AdmRuntimePlayoutError = 1015, + /** + * Audio Device Module: A recording error occurs. + */ + AdmRuntimeRecordingError = 1017, + /** + * Audio Device Module: Fails to record. + */ + AdmRecordAudioFailed = 1018, + /** + * Audio Device Module: Abnormal audio playback frequency. + */ + AdmPlayAbnormalFrequency = 1020, + /** + * Audio Device Module: Abnormal audio recording frequency. + */ + AdmRecordAbnormalFrequency = 1021, + /** + * Audio Device Module: An error occurs in initializing the loopback device. + */ + AdmInitLoopback = 1022, + /** + * Audio Device Module: An error occurs in starting the loopback device. + */ + AdmStartLoopback = 1023, + /** + * Audio Device Module: An error occurs in no recording Permission. + */ + AdmNoPermission = 1027, + /** + * Audio Routing: Fails to route the audio to the connected Bluetooth device. The default route is used. + */ + AudioBtScoFailed = 1030, + /** + * Audio Device Module: No recording device exists. + */ + AdmNoRecordingDevice = 1359, + /** + * No playback device exists. + */ + AdmNoPlayoutDevice = 1360, + /** + * Video Device Module: The camera is unauthorized. + */ + VdmCameraNotAuthorized = 1501, + /** + * Video Device Module: An unknown error occurs. + */ + VcmUnknownError = 1600, + /** + * Video Device Module: An error occurs in initializing the video encoder. + */ + VcmEncoderInitError = 1601, + /** + * Video Device Module: An error occurs in video encoding. + */ + VcmEncoderEncodeError = 1602, + /** + * Video Device Module: An error occurs in setting the video encoder. + * @deprecated + */ + VcmEncoderSetError = 1603, +} + +/** + * State of importing an external video stream in a live broadcast. + * @enum {number} + */ +export enum InjectStreamStatus { + /** + * The external video stream imported successfully. + */ + StartSuccess = 0, + /** + * The external video stream already exists. + */ + StartAlreadyExists = 1, + /** + * The external video stream import is unauthorized. + */ + StartUnauthorized = 2, + /** + * Import external video stream timeout. + */ + StartTimedout = 3, + /** + * The external video stream failed to import. + */ + StartFailed = 4, + /** + * The external video stream imports successfully. + */ + StopSuccess = 5, + /** + * No external video stream is found. + */ + StopNotFound = 6, + /** + * The external video stream is stopped from being unauthorized. + */ + StopUnauthorized = 7, + /** + * Importing the external video stream timeout. + */ + StopTimedout = 8, + /** + * Importing the external video stream failed. + */ + StopFailed = 9, + /** + * The external video stream import is interrupted. + */ + Broken = 10, +} + +/** + * The state of the probe test result. + * @enum {number} + */ +export enum LastmileProbeResultState { + /** + * the last-mile network probe test is complete. + */ + Complete = 1, + /** + * the last-mile network probe test is incomplete and the bandwidth estimation is not available, probably due to limited test resources. + */ + IncompleteNoBwe = 2, + /** + * the last-mile network probe test is not carried out, probably due to poor network conditions. + */ + Unavailable = 3, +} + +/** + * The lightening contrast level. + * @enum {number} + */ +export enum LighteningContrastLevel { + /** + * Low contrast level. + */ + Low = 0, + /** + * (Default) Normal contrast level. + */ + Normal = 1, + /** + * High contrast level. + */ + High = 2, +} + +/** + * The detailed error information of the local video. + * @enum {number} + */ +export enum LocalVideoStreamError { + /** + * The local video is normal. + */ + OK = 0, + /** + * No specified reason for the local video failure. + */ + Failure = 1, + /** + * No permission to use the local video device. + */ + DeviceNoPermission = 2, + /** + * The local video capturer is in use. + */ + DeviceBusy = 3, + /** + * The local video capture fails. Check whether the capturer is working properly. + */ + CaptureFailure = 4, + /** + * The local video encoding fails. + */ + EncodeFailure = 5, +} + +/** + * The state of the local video stream. + * @enum {number} + */ +export enum LocalVideoStreamState { + /** + * The local video is in the initial state. + */ + Stopped = 0, + /** + * The local video capturer starts successfully. + */ + Capturing = 1, + /** + * The first local video frame encodes successfully. + */ + Encoding = 2, + /** + * The local video fails to start. + */ + Failed = 3, +} + +/** + * Output log filter level. + * @enum {number} + */ +export enum LogFilter { + /** + * Do not output any log information. + */ + Off = 0, + /** + * Output all log information. Set your log filter as debug if you want to get the most complete log file. + */ + Debug = 0x080f, + /** + * Output CRITICAL, ERROR, WARNING, and INFO level log information. We recommend setting your log filter as this level. + */ + Info = 0x000f, + /** + * Outputs CRITICAL, ERROR, and WARNING level log information. + */ + Warning = 0x000e, + /** + * Outputs CRITICAL and ERROR level log information. + */ + Error = 0x000c, + /** + * Outputs CRITICAL level log information. + */ + Critical = 0x0008, +} + +/** + * Media device type. + * @enum {number} + * TODO MacOS AgoraMediaDeviceType + */ +export enum MediaDeviceType { + /** + * Unknown device. + */ + AudioUnknown = -1, + /** + * Audio playback device. + */ + AudioPlayout = 0, + /** + * Audio recording device. + */ + AudioRecording = 1, + /** + * Video render device. + */ + VideoRender = 2, + /** + * Video capture device. + */ + VideoCapture = 3, +} + +/** + * Media type. + * @enum {number} + * TODO LiveEngine + */ +export enum MediaType { + /** + * No audio and video. + */ + None = 0, + /** + * Audio only. + */ + AudioOnly = 1, + /** + * Video only. + */ + VideoOnly = 2, + /** + * Audio and video. + */ + AudioAndVideo = 3, +} + +/** + * The metadata type. + * @enum {number} + * TODO registerMediaMetadataObserver + */ +export enum MetadataType { + /** + * the metadata type is unknown. + */ + Unknown = -1, + /** + * the metadata type is video. + */ + Video = 0, +} + +/** + * Network quality. + * @enum {number} + */ +export enum NetworkQuality { + /** + * The network quality is unknown. + */ + Unknown = 0, + /** + * The network quality is excellent. + */ + Excellent = 1, + /** + * The network quality is quite good, but the bitrate may be slightly lower than excellent. + */ + Good = 2, + /** + * Users can feel the communication slightly impaired. + */ + Poor = 3, + /** + * Users can communicate only not very smoothly. + */ + Bad = 4, + /** + * The network quality is so bad that users can hardly communicate. + */ + VBad = 5, + /** + * The network is disconnected and users cannot communicate at all. + */ + Down = 6, + /** + * Users cannot detect the network quality. (Not in use.) + */ + Unsupported = 7, + /** + * Detecting the network quality. + */ + Detecting = 8, +} + +/** + * Network type. + * @enum {number} + */ +export enum NetworkType { + /** + * The network type is unknown. + */ + Unknown = -1, + /** + * The SDK disconnects from the network. + */ + Disconnected = 0, + /** + * The network type is LAN. + */ + LAN = 1, + /** + * The network type is Wi-Fi (including hotspots). + */ + WIFI = 2, + /** + * The network type is mobile 2G. + */ + Mobile2G = 3, + /** + * The network type is mobile 3G. + */ + Mobile3G = 4, + /** + * The network type is mobile 4G. + */ + Mobile4G = 5, +} + +/** + * Default camera position + * @enum {number} + * TODO AgoraRtcDefaultCamera + */ +export enum RtcDefaultCameraPosition { + /** + * Front camera + */ + Front = 0, + /** + * Rear camera + */ + Back = 1, +} + +/** + * Lifecycle of the CDN live video stream. + * @enum {number} + * TODO AgoraPublisherConfiguration + */ +export enum RtmpStreamLifeCycle { + /** + * Bound to the channel lifecycle. If all hosts leave the channel, the CDN live streaming stops after 30 seconds. + */ + BindToChannel = 1, + /** + * Bound to the owner of the RTMP stream. If the owner leaves the channel, the CDN live streaming stops immediately. + */ + BindToOwnner = 2, +} + +/** + * The detailed error information for streaming. + * @enum {number} + */ +export enum RtmpStreamingErrorCode { + /** + * The RTMP streaming publishes successfully. + */ + OK = 0, + /** + * Invalid argument used. If, for example, you do not call the setLiveTranscoding method to configure the LiveTranscoding parameters before calling the addPublishStreamUrl method, the SDK returns this error. Check whether you set the parameters in the setLiveTranscoding method properly. + * @see RtcEngine.setLiveTranscoding + * @see RtcEngine.addPublishStreamUrl + */ + InvalidParameters = 1, + /** + * The RTMP streaming is encrypted and cannot be published. + */ + EncryptedStreamNotAllowed = 2, + /** + * Timeout for the RTMP streaming. Call the addPublishStreamUrl method to publish the streaming again. + * @see RtcEngine.addPublishStreamUrl + */ + ConnectionTimeout = 3, + /** + * An error occurs in Agora’s streaming server. Call the addPublishStreamUrl method to publish the streaming again. + * @see RtcEngine.addPublishStreamUrl + */ + InternalServerError = 4, + /** + * An error occurs in the RTMP server. + */ + RtmpServerError = 5, + /** + * The RTMP streaming publishes too frequently. + */ + TooOften = 6, + /** + * The host publishes more than 10 URLs. Delete the unnecessary URLs before adding new ones. + */ + ReachLimit = 7, + /** + * The host manipulates other hosts' URLs. Check your app logic. + */ + NotAuthorized = 8, + /** + * Agora’s server fails to find the RTMP streaming. + */ + StreamNotFound = 9, + /** + * The format of the RTMP streaming URL is not supported. Check whether the URL format is correct. + */ + FormatNotSupported = 10, +} + +/** + * The RTMP streaming state. + * @enum {number} + */ +export enum RtmpStreamingState { + /** + * The RTMP streaming has not started or has ended. This state is also triggered after you remove an RTMP address from the CDN by calling removePublishStreamUrl. + * @see RtcEngine.removePublishStreamUrl + */ + Idle = 0, + /** + * The SDK is connecting to Agora’s streaming server and the RTMP server. This state is triggered after you call the addPublishStreamUrl method. + * @see RtcEngine.addPublishStreamUrl + */ + Connecting = 1, + /** + * The RTMP streaming is being published. The SDK successfully publishes the RTMP streaming and returns this state. + */ + Running = 2, + /** + * The RTMP streaming is recovering. When exceptions occur to the CDN, or the streaming is interrupted, the SDK attempts to resume RTMP streaming and returns this state. + * - If the SDK successfully resumes the streaming, Running(2) returns. + * @see RtmpStreamingState.Running + * - If the streaming does not resume within 60 seconds or server errors occur, Failure(4) returns. You can also reconnect to the server by calling the removePublishStreamUrl and addPublishStreamUrl methods. + * @see RtmpStreamingState.Failure + * @see RtcEngine.removePublishStreamUrl + * @see RtcEngine.addPublishStreamUrl + */ + Recovering = 3, + /** + * The RTMP streaming fails. See the errorCode parameter for the detailed error information. You can also call the addPublishStreamUrl method to publish the RTMP streaming again. + * @see RtcEngine.addPublishStreamUrl + */ + Failure = 4, +} + +/** + * Stream fallback option. + * @enum {number} + */ +export enum StreamFallbackOptions { + /** + * No fallback behavior for the local/remote video stream when the uplink/downlink network condition is unreliable. The quality of the stream is not guaranteed. + */ + Disabled = 0, + /** + * Under unreliable downlink network conditions, the remote video stream falls back to the low-stream (low resolution and low bitrate) video. You can only set this option in the setRemoteSubscribeFallbackOption method. Nothing happens when you set this in the setLocalPublishFallbackOption method. + * @see RtcEngine.setRemoteSubscribeFallbackOption + * @see RtcEngine.setLocalPublishFallbackOption + */ + VideoStreamLow = 1, + /** + * Under unreliable uplink network conditions, the published video stream falls back to audio only. Under unreliable downlink network conditions, the remote video stream first falls back to the low-stream (low resolution and low bitrate) video; and then to an audio-only stream if the network condition deteriorates. + */ + AudioOnly = 2, +} + +/** + * Reason for the user being offline. + * @enum {number} + */ +export enum UserOfflineReason { + /** + * The user left the current channel. + */ + Quit = 0, + /** + * The SDK timed out and the user dropped offline because no data packet is received within a certain period of time. If a user quits the call and the message is not passed to the SDK (due to an unreliable channel), the SDK assumes the user dropped offline. + */ + Dropped = 1, + /** + * (Live broadcast only.) The client role switched from the host to the audience. + */ + BecomeAudience = 2, +} + +/** + * The priority of the remote user. + * @enum {number} + */ +export enum UserPriority { + /** + * The user’s priority is high. + */ + High = 50, + /** + * (Default) The user’s priority is normal. + */ + Normal = 100, +} + +/** + * Video buffer type + * @enum {number} + * TODO iOS AgoraVideoSourceProtocol AgoraVideoSinkProtocol + */ +export enum VideoBufferType { + /** + * Use a pixel buffer to transmit the video data. + */ + PixelBuffer = 1, + /** + * Use raw data to transmit the video data. + */ + RawData = 2, +} + +/** + * Self-defined video codec profile. + * @enum {number} + */ +export enum VideoCodecProfileType { + /** + * Baseline video codec profile. Generally used in video calls on mobile phones. + */ + BaseLine = 66, + /** + * Main video codec profile. Generally used in mainstream electronics, such as MP4 players, portable video players, PSP, and iPads. + */ + Main = 77, + /** + * (Default) High video codec profile. Generally used in high-resolution broadcasts or television. + */ + High = 100, +} + +/** + * The content hint for screen sharing. + * @enum {number} + * TODO MacOS setScreenCaptureContentHint + */ +export enum VideoContentHint { + /** + * (Default) No content hint. + */ + None = 0, + /** + * Motion-intensive content. Choose this option if you prefer smoothness or when you are sharing a video clip, movie, or video game. + */ + Motion = 1, + /** + * Motionless content. Choose this option if you prefer sharpness or when you are sharing a picture, PowerPoint slide, or text. + */ + Details = 2, +} + +/** + * Video frame rate + * @enum {number} + */ +export enum VideoFrameRate { + Min = -1, + /** + * 1 fps. + */ + Fps1 = 1, + /** + * 7 fps. + */ + Fps7 = 7, + /** + * 10 fps. + */ + Fps10 = 10, + /** + * 15 fps. + */ + Fps15 = 15, + /** + * 24 fps. + */ + Fps24 = 24, + /** + * 30 fps. + */ + Fps30 = 30, + /** + * 60 fps (macOS only). + */ + Fps60 = 60, +} + +/** + * Sets the video bitrate (Kbps). Refer to the table below and set your bitrate. If you set a bitrate beyond the proper range, the SDK automatically adjusts it to a value within the range. You can also choose from the following options: + * @enum {number} + */ +export enum BitRate { + /** + * (recommended) the standard bitrate mode. In this mode, the bitrates differ between the Live-broadcast and Communication profiles: + * - Communication profile: the video bitrate is the same as the base bitrate. + * - Live-broadcast profile: the video bitrate is twice the base bitrate. + */ + Standard = 0, + /** + * the compatible bitrate mode. In this mode, the bitrate stays the same regardless of the profile. In the Live-broadcast profile, if you choose this mode, the video frame rate may be lower than the set value. + */ + Compatible = -1, +} + +/** + * Video mirror mode. + * @enum {number} + */ +export enum VideoMirrorMode { + /** + * (Default) The SDK determines the mirror mode. + */ + Auto = 0, + /** + * Enables mirror mode. + */ + Enabled = 1, + /** + * Disables mirror mode. + */ + Disabled = 2, +} + +/** + * Video output orientation mode. + * @enum {number} + */ +export enum VideoOutputOrientationMode { + /** + * Adaptive mode (Default). + * The video encoder adapts to the orientation mode of the video input device. When you use a custom video source, the output video from the encoder inherits the orientation of the original video. + * - If the width of the captured video from the SDK is greater than the height, the encoder sends the video in landscape mode. The encoder also sends the rotational information of the video, and the receiver uses the rotational information to rotate the received video. + * - If the original video is in portrait mode, the output video from the encoder is also in portrait mode. The encoder also sends the rotational information of the video to the receiver. + */ + Adaptative = 0, + /** + * Landscape mode. + * The video encoder always sends the video in landscape mode. The video encoder rotates the original video before sending it and the rotational information is 0. This mode applies to scenarios involving CDN live streaming. + */ + FixedLandscape = 1, + /** + * Portrait mode. + * The video encoder always sends the video in portrait mode. The video encoder rotates the original video before sending it and the rotational information is 0. This mode applies to scenarios involving CDN live streaming. + */ + FixedPortrait = 2, +} + +/** + * Video pixel format. + * @enum {number} + * TODO iOS AgoraVideoSinkProtocol + */ +export enum VideoPixelFormat { + /** + * I420 + */ + I420 = 1, + /** + * BGRA + */ + BGRA = 2, + /** + * NV12 + */ + NV12 = 8, +} + +/** + * Quality change of the local video in terms of target frame rate and target bit rate since last count. + * @enum {number} + */ +export enum VideoQualityAdaptIndication { + /** + * The quality of the local video stays the same. + */ + AdaptNone = 0, + /** + * The quality improves because the network bandwidth increases. + */ + AdaptUpBandwidth = 1, + /** + * The quality worsens because the network bandwidth decreases. + */ + AdaptDownBandwidth = 2, +} + +/** + * The state of the remote video. + * @enum {number} + */ +export enum VideoRemoteState { + /** + * The remote video is in the default state, probably due to: + * @see VideoRemoteStateReason.LocalMuted + * @see VideoRemoteStateReason.RemoteMuted + * @see VideoRemoteStateReason.RemoteOffline + */ + Stopped = 0, + /** + * The first remote video packet is received. + */ + Starting = 1, + /** + * The remote video stream is decoded and plays normally, probably due to: + * @see VideoRemoteStateReason.NetworkRecovery + * @see VideoRemoteStateReason.LocalUnmuted + * @see VideoRemoteStateReason.RemoteUnmuted + * @see VideoRemoteStateReason.AudioFallbackRecovery + */ + Decoding = 2, + /** + * The remote video is frozen, probably due to: + * @see VideoRemoteStateReason.NetworkCongestion + * @see VideoRemoteStateReason.AudioFallback + */ + Frozen = 3, + /** + * The remote video fails to start, probably due to: + * @see VideoRemoteStateReason.Internal + */ + Failed = 4, +} + +/** + * The reason of the remote video state change. + * @enum {number} + */ +export enum VideoRemoteStateReason { + /** + * Internal reasons. + */ + Internal = 0, + /** + * Network congestion. + */ + NetworkCongestion = 1, + /** + * Network recovery. + */ + NetworkRecovery = 2, + /** + * The local user stops receiving the remote video stream or disables the video module. + */ + LocalMuted = 3, + /** + * The local user stops receiving the remote video stream or disables the video module. + */ + LocalUnmuted = 4, + /** + * The remote user stops sending the video stream or disables the video module. + */ + RemoteMuted = 5, + /** + * The remote user resumes sending the video stream or enables the video module. + */ + RemoteUnmuted = 6, + /** + * The remote user leaves the channel. + */ + RemoteOffline = 7, + /** + * The remote media stream falls back to the audio-only stream due to poor network conditions. + */ + AudioFallback = 8, + /** + * The remote media stream switches back to the video stream after the network conditions improve. + */ + AudioFallbackRecovery = 9, +} + +/** + * Video display mode. + * @enum {number} + */ +export enum VideoRenderMode { + /** + * Uniformly scale the video until it fills the visible boundaries (cropped). One dimension of the video may have clipped contents. + */ + Hidden = 1, + /** + * Uniformly scale the video until one of its dimension fits the boundary (zoomed to fit). Areas that are not filled due to the disparity in the aspect ratio are filled with black. + */ + Fit = 2, + /** + * This mode is deprecated. + * @deprecated + */ + Adaptive = 3, + /** + * The fill mode. In this mode, the SDK stretches or zooms the video to fill the display window. + */ + FILL = 4, +} + +/** + * Video rotation. + * @enum {number} + * TODO iOS AgoraVideoSourceProtocol AgoraVideoSinkProtocol + */ +export enum VideoRotation { + /** + * No rotation + */ + RotationNone = 0, + /** + * 90 degrees + */ + Rotation90 = 1, + /** + * 180 degrees + */ + Rotation180 = 2, + /** + * 270 degrees + */ + Rotation270 = 3, +} + +/** + * Video stream type. + * @enum {number} + */ +export enum VideoStreamType { + /** + * High-bitrate, high-resolution video stream. + */ + High = 0, + /** + * Low-bitrate, low-resolution video stream. + */ + Low = 1, +} + +/** + * Warning codes occur when the SDK encounters an error that may be recovered automatically. These are only notifications, and can generally be ignored. For example, when the SDK loses connection to the server, the SDK reports the OpenChannelTimeout(106) warning and tries to reconnect automatically. + * @see WarningCode.OpenChannelTimeout + * @enum {number} + */ +export enum WarningCode { + /** + * The specified view is invalid. Specify a view when using the video call function. + */ + InvalidView = 8, + /** + * Failed to initialize the video function, possibly caused by a lack of resources. The users cannot see the video while the voice communication is not affected. + */ + InitVideo = 16, + /** + * The request is pending, usually due to some module not being ready, and the SDK postpones processing the request. + */ + Pending = 20, + /** + * No channel resources are available. Maybe because the server cannot allocate any channel resource. + */ + NoAvailableChannel = 103, + /** + * A timeout occurs when looking up the channel. When joining a channel, the SDK looks up the specified channel. The warning usually occurs when the network condition is too poor for the SDK to connect to the server. + */ + LookupChannelTimeout = 104, + /** + * The server rejects the request to look up the channel. The server cannot process this request or the request is illegal. DEPRECATED as of v2.4.1. Use RejectedByServer(10) in the reason parameter of onConnectionStateChanged. + * @see ConnectionChangedReason.RejectedByServer + * @see RtcEngineEvents.onConnectionStateChanged + * @deprecated + */ + LookupChannelRejected = 105, + /** + * The server rejects the request to look up the channel. The server cannot process this request or the request is illegal. + */ + OpenChannelTimeout = 106, + /** + * The server rejects the request to open the channel. The server cannot process this request or the request is illegal. + */ + OpenChannelRejected = 107, + /** + * A timeout occurs when switching to the live video. + */ + SwitchLiveVideoTimeout = 111, + /** + * A timeout occurs when setting the client role in the live broadcast profile. + */ + SetClientRoleTimeout = 118, + /** + * The client role is unauthorized. + */ + SetClientRoleNotAuthorized = 119, + /** + * The ticket to open the channel is invalid. + */ + OpenChannelInvalidTicket = 121, + /** + * Try connecting to another server. + */ + OpenChannelTryNextVos = 122, + /** + * An error occurs in opening the audio mixing file. + */ + AudioMixingOpenError = 701, + /** + * Audio Device Module: a warning occurs in the playback device. + */ + AdmRuntimePlayoutWarning = 1014, + /** + * Audio Device Module: a warning occurs in the recording device. + */ + AdmRuntimeRecordingWarning = 1016, + /** + * Audio Device Module: no valid audio data is collected. + */ + AdmRecordAudioSilence = 1019, + /** + * Audio Device Module: a playback device fails. + */ + AdmPlaybackMalfunction = 1020, + /** + * Audio Device Module: a recording device fails. + */ + AdmRecordMalfunction = 1021, + /** + * Audio Device Module: call is interrupted by system events such as phone call or siri etc. + */ + AdmInterruption = 1025, + /** + * Audio Device Module: the recorded audio is too low. + */ + AdmRecordAudioLowlevel = 1031, + /** + * Audio Device Module: the playback audio is too low. + */ + AdmPlayoutAudioLowlevel = 1032, + /** + * Audio Device Module: The recording device is busy. + */ + AdmRecordIsOccupied = 1033, + /** + * Audio Device Module: howling is detected. + */ + ApmHowling = 1051, + /** + * Audio Device Module: the device is in the glitch state. + */ + AdmGlitchState = 1052, + /** + * Audio Device Module: the underlying audio settings have changed. + */ + AdmImproperSettings = 1053, +} + +/** + * The audio channel of the sound. + * @enum {number} + */ +export enum AudioChannel { + /** + * (Default) Supports dual channels. Depends on the upstream of the broadcaster. + */ + Channel0 = 0, + /** + * The audio stream of the broadcaster uses the FL audio channel. If the upstream of the broadcaster uses multiple audio channels, these channels will be mixed into mono first. + */ + Channel1 = 1, + /** + * The audio stream of the broadcaster uses the FC audio channel. If the upstream of the broadcaster uses multiple audio channels, these channels will be mixed into mono first. + */ + Channel2 = 2, + /** + * The audio stream of the broadcaster uses the FR audio channel. If the upstream of the broadcaster uses multiple audio channels, these channels will be mixed into mono first. + */ + Channel3 = 3, + /** + * The audio stream of the broadcaster uses the BL audio channel. If the upstream of the broadcaster uses multiple audio channels, these channels will be mixed into mono first. + */ + Channel4 = 4, + /** + * The audio stream of the broadcaster uses the BR audio channel. If the upstream of the broadcaster uses multiple audio channels, these channels will be mixed into mono first. + */ + Channel5 = 5, +} + +/** + * Video codec types. + * @enum {number} + */ +export enum VideoCodecType { + /** + * Standard VP8. + */ + VP8 = 1, + /** + * Standard H264. + */ + H264 = 2, + /** + * Enhanced VP8. + */ + EVP = 3, + /** + * Enhanced H264. + */ + E264 = 4, +} + +export type String = string | undefined | null +export type Rate = 1 | 2 | 3 | 4 | 5 + +/** + * The user information, including the user ID and user account. + * @property uid: int | The user ID of a user. + * @property userAccount: string | The user account of a user. + */ +export interface UserInfo { + uid: number + userAccount: string +} + +/** + * The video resolution. + * @property width: int | The video resolution on the horizontal axis. + * @property height: int | The video resolution on the vertical axis. + */ +export class VideoDimensions { + width: number + height: number + + constructor(width: number, height: number) { + this.width = width; + this.height = height; + } +} + +/** + * Definition of VideoEncoderConfiguration. + * @property dimensions: object | The video frame dimensions (px), which is used to specify the video quality and measured by the total number of pixels along a frame's width and height. The default value is 640 × 360. + * @property frameRate: int | The video frame rate (fps). The default value is 15. Users can either set the frame rate manually or choose from the following options. We do not recommend setting this to a value greater than 30. + * @property minFrameRate: int | The minimum video encoder frame rate (fps). The default value is Min(-1) (the SDK uses the lowest encoder frame rate). + * @property bitrate: int | Bitrate of the video (Kbps). Refer to the table below and set your bitrate. If you set a bitrate beyond the proper range, the SDK automatically adjusts it to a value within the range. + * @property minBitrate: int | The minimum encoding bitrate (Kbps). The Agora SDK automatically adjusts the encoding bitrate to adapt to the network conditions. Using a value greater than the default value forces the video encoder to output high-quality images but may cause more packet loss and hence sacrifice the smoothness of the video transmission. That said, unless you have special requirements for image quality, Agora does not recommend changing this value. + * @property orientationMode: int | The orientation mode. + * @property degradationPrefer: int | The video encoding degradation preference under limited bandwidth. + * @property mirrorMode: int | Sets the mirror mode of the published local video stream. + */ +export class VideoEncoderConfiguration { + dimensions?: VideoDimensions + frameRate?: VideoFrameRate + minFrameRate?: VideoFrameRate + bitrate?: BitRate | number + minBitrate?: number + orientationMode?: VideoOutputOrientationMode + degradationPrefer?: DegradationPreference + mirrorMode?: VideoMirrorMode + + constructor({dimensions, frameRate, minFrameRate, bitrate, minBitrate, orientationMode, degradationPrefer, mirrorMode}: { dimensions?: VideoDimensions, frameRate?: VideoFrameRate, minFrameRate?: VideoFrameRate, bitrate?: BitRate | number, minBitrate?: number, orientationMode?: VideoOutputOrientationMode, degradationPrefer?: DegradationPreference, mirrorMode?: VideoMirrorMode }) { + this.dimensions = dimensions; + this.frameRate = frameRate; + this.minFrameRate = minFrameRate; + this.bitrate = bitrate; + this.minBitrate = minBitrate; + this.orientationMode = orientationMode; + this.degradationPrefer = degradationPrefer; + this.mirrorMode = mirrorMode; + } +} + +/** + * Sets the image enhancement options. + * @property lighteningContrastLevel: int | The lightening contrast level. + * @property lighteningLevel: float | The brightness level. The value ranges between 0.0 (original) and 1.0. The default value is 0.7. + * @property smoothnessLevel: float | The sharpness level. The value ranges between 0.0 (original) and 1.0. The default value is 0.5. This parameter is usually used to remove blemishes. + * @property rednessLevel: float | The redness level. The value ranges between 0.0 (original) and 1.0. The default value is 0.1. This parameter adjusts the red saturation level. + */ +export class BeautyOptions { + lighteningContrastLevel?: LighteningContrastLevel + lighteningLevel?: number + smoothnessLevel?: number + rednessLevel?: number + + constructor({lighteningContrastLevel, lighteningLevel, smoothnessLevel, rednessLevel}: { lighteningContrastLevel?: LighteningContrastLevel, lighteningLevel?: number, smoothnessLevel?: number, rednessLevel?: number }) { + this.lighteningContrastLevel = lighteningContrastLevel; + this.lighteningLevel = lighteningLevel; + this.smoothnessLevel = smoothnessLevel; + this.rednessLevel = rednessLevel; + } +} + +/** + * Agora image properties. A class for setting the properties of the watermark and background images. + * @property url: string | HTTP/HTTPS URL address of the image on the broadcasting video. The maximum length of this parameter is 1024 bytes. + * @property x: int | Position of the image on the upper left of the broadcasting video on the horizontal axis. + * @property y: int | Position of the image on the upper left of the broadcasting video on the vertical axis. + * @property width: int | Width of the image on the broadcasting video. + * @property height: int | Height of the image on the broadcasting video. + */ +export class AgoraImage { + url: string + x: number + y: number + width: number + height: number + + constructor(url: string, x: number, y: number, width: number, height: number) { + this.url = url; + this.x = x; + this.y = y; + this.width = width; + this.height = height; + } +} + +/** + * The transcodingUser class, which defines the audio and video properties in the CDN live. Agora supports a maximum of 17 transcoding users in a CDN live streaming channel. + * @property uid: int | ID of the user in the CDN live streaming. + * @property x: int | Horizontal position of the video frame of the user from the top left corner of the CDN live streaming. + * @property y: int | Vertical position of the video frame of the user from the top left corner of the CDN live streaming. + * @property width: int | Width of the video frame of the user on the CDN live streaming. The default value is 360. + * @property height: int | Height of the video frame of the user on the CDN live streaming. The default value is 640. + * @property zOrder: int | Layer position of video frame of the user on the CDN live streaming. The value ranges between 0 and 100. From v2.3.0, Agora SDK supports setting zOrder as 0. The smallest value is 0 (default value), which means that the video frame is at the bottom layer. The biggest value is 100, which means that the video frame is at the top layer. + * @property alpha: float | The transparency of the video frame of the user in the CDN live stream that ranges between 0.0 and 1.0. 0.0 means that the video frame is completely transparent and 1.0 means opaque. The default value is 1.0. + * @property audioChannel: int | The audio channel ranging between 0 and 5. The default value is 0. + */ +export class TranscodingUser { + uid: number + x: number + y: number + width?: number + height?: number + zOrder?: number + alpha?: number + audioChannel?: AudioChannel + + constructor(uid: number, x: number, y: number, {width, height, zOrder, alpha, audioChannel}: { width?: number, height?: number, zOrder?: number, alpha?: number, audioChannel?: AudioChannel }) { + this.uid = uid; + this.x = x; + this.y = y; + this.width = width; + this.height = height; + this.zOrder = zOrder; + this.alpha = alpha; + this.audioChannel = audioChannel; + } +} + +/** + * Color. + * @property red: int | Red. + * @property green: int | Green. + * @property blue: int | Blue. + */ +export class Color { + red: number + green: number + blue: number + + constructor(red: number, green: number, blue: number) { + this.red = red; + this.green = green; + this.blue = blue; + } +} + +/** + * A class for managing user-specific CDN live audio/video transcoding settings. + * @property width: int | Width (pixel) of the video. The default value is 360. If you push video streams to the CDN, set the value of width × height to at least 64 × 64, or the SDK adjusts it to 64 x 64. If you push audio streams to the CDN, set the value of width × height to 0 × 0. + * @property height: int | Height (pixel) of the video. The default value is 640. If you push video streams to the CDN, set the value of width × height to at least 64 × 64, or the SDK adjusts it to 64 x 64. If you push audio streams to the CDN, set the value of width × height to 0 × 0. + * @property videoBitrate: int | Bitrate (Kbps) of the CDN live output video stream. The default value is 400. Set this parameter according to the Video Bitrate Table. If you set a bitrate beyond the proper range, the SDK automatically adapts it to a value within the range. + * @property videoFramerate: int | Frame rate (fps) of the CDN live output video stream. The value range is [0, 30]. The default value is 15. Agora adjusts all values over 30 to 30. + * @property lowLatency: boolean | true: Low latency with unassured quality. false: (Default) High latency with assured quality. + * @property videoGop: int | Gop of the video frames in the CDN live stream. The default value is 30 fps. + * @property watermark: object | The watermark image added to the CDN live publishing stream. Ensure that the format of the image is PNG. Once a watermark image is added, the audience of the CDN live publishing stream can see it. + * @property backgroundImage: object | The background image added to the CDN live publishing stream. Once a background image is added, the audience of the CDN live publishing stream can see it. + * @property audioSampleRate: int | Self-defined audio-sample rate: AudioSampleRateType. + * @property audioBitrate: int | Bitrate (Kbps) of the CDN live audio output stream. The default value is 48 and the highest value is 128. + * @property audioChannels: int | Agora’s self-defined audio channel type. We recommend choosing 1 or 2. Special players are required if you choose 3, 4 or 5. + * @property audioCodecProfile: int | Audio codec profile type: AudioCodecProfileType. Set it as LC-AAC or HE-AAC. The default value is LC-AAC. + * @property videoCodecProfile: int | Video codec profile type: VideoCodecProfileType. Set it as BASELINE, MAIN, or HIGH (default). If you set this parameter to other values, Agora adjusts it to the default value HIGH. + * @property backgroundColor: int | Sets the background color. + * @property userConfigExtraInfo: string | Reserved property. Extra user-defined information to send the Supplemental Enhancement Information (SEI) for the H.264/H.265 video stream to the CDN live client. Maximum length: 4096 Bytes. + * @property transcodingUsers: array | An TranscodingUser object managing the user layout configuration in the CDN live stream. Agora supports a maximum of 17 transcoding users in a CDN live stream channel. + */ +export class LiveTranscoding { + width?: number + height?: number + videoBitrate?: number + videoFramerate?: VideoFrameRate + /** @deprecated */ + lowLatency?: boolean + videoGop?: number + watermark?: AgoraImage + backgroundImage?: AgoraImage + audioSampleRate?: AudioSampleRateType + audioBitrate?: number + audioChannels?: AudioChannel + audioCodecProfile?: AudioCodecProfileType + videoCodecProfile?: VideoCodecProfileType + backgroundColor?: Color + userConfigExtraInfo?: string + transcodingUsers: TranscodingUser[] + + constructor(transcodingUsers: TranscodingUser[], {width, height, videoBitrate, videoFramerate, lowLatency, videoGop, watermark, backgroundImage, audioSampleRate, audioBitrate, audioChannels, audioCodecProfile, videoCodecProfile, backgroundColor, userConfigExtraInfo}: { width?: number, height?: number, videoBitrate?: number, videoFramerate?: VideoFrameRate, lowLatency?: boolean, videoGop?: number, watermark?: AgoraImage, backgroundImage?: AgoraImage, audioSampleRate?: AudioSampleRateType, audioBitrate?: number, audioChannels?: AudioChannel, audioCodecProfile?: AudioCodecProfileType, videoCodecProfile?: VideoCodecProfileType, backgroundColor?: Color, userConfigExtraInfo?: string, }) { + this.width = width; + this.height = height; + this.videoBitrate = videoBitrate; + this.videoFramerate = videoFramerate; + this.lowLatency = lowLatency; + this.videoGop = videoGop; + this.watermark = watermark; + this.backgroundImage = backgroundImage; + this.audioSampleRate = audioSampleRate; + this.audioBitrate = audioBitrate; + this.audioChannels = audioChannels; + this.audioCodecProfile = audioCodecProfile; + this.videoCodecProfile = videoCodecProfile; + this.backgroundColor = backgroundColor; + this.userConfigExtraInfo = userConfigExtraInfo; + this.transcodingUsers = transcodingUsers; + } +} + +/** + * The ChannelMediaInfo class. + * @property channelName: string | The channel name. + * @property token: string | The token that enables the user to join the channel. + * @property uid: int | The user ID. + */ +export class ChannelMediaInfo { + channelName?: string + token?: string + uid: number + + constructor(uid: number, {channelName, token}: { channelName?: string, token?: string }) { + this.channelName = channelName; + this.token = token; + this.uid = uid; + } +} + +/** + * The ChannelMediaRelayConfiguration class. + * @property srcInfo: object | Sets the information of the source channel. + * @property destInfos: array | Sets the information of the destination channel. + */ +export class ChannelMediaRelayConfiguration { + srcInfo: ChannelMediaInfo + destInfos: ChannelMediaInfo[] + + constructor(srcInfo: ChannelMediaInfo, destInfos: ChannelMediaInfo[]) { + this.srcInfo = srcInfo; + this.destInfos = destInfos; + } +} + +/** + * Lastmile probe configuration. + * @property probeUplink: boolean | Whether to probe uplink of lastmile. i.e., audience don't need probe uplink bandwidth. + * @property probeDownlink: boolean | Whether to probe downlink of lastmile. + * @property expectedUplinkBitrate: int | The expected maximum sending bitrate in bps in range of [100000, 5000000]. It is recommended to set this value according to the required bitrate of selected video profile. + * @property expectedDownlinkBitrate: int | The expected maximum receive bitrate in bps in range of [100000, 5000000]. + */ +export class LastmileProbeConfig { + probeUplink: boolean + probeDownlink: boolean + expectedUplinkBitrate: number + expectedDownlinkBitrate: number + + constructor(probeUplink: boolean, probeDownlink: boolean, expectedUplinkBitrate: number, expectedDownlinkBitrate: number) { + this.probeUplink = probeUplink; + this.probeDownlink = probeDownlink; + this.expectedUplinkBitrate = expectedUplinkBitrate; + this.expectedDownlinkBitrate = expectedDownlinkBitrate; + } +} + +/** + * The position and size of the watermark image. + * @property x: int | The horizontal offset from the top-left corner. + * @property y: int | The vertical offset from the top-left corner. + * @property width: int | The width (pixels) of the watermark image. + * @property height: int | The height (pixels) of the watermark image. + */ +export class Rectangle { + x: number + y: number + width: number + height: number + + constructor(x: number, y: number, width: number, height: number) { + this.x = x; + this.y = y; + this.width = width; + this.height = height; + } +} + +/** + * Agora watermark options. A class for setting the properties of watermark. + * @property visibleInPreview: boolean | Sets whether or not the watermark image is visible in the local video preview: true: (Default) The watermark image is visible in preview. false: The watermark image is not visible in preview. + * @property positionInLandscapeMode: object | The watermark position in the landscape mode. + * @property positionInPortraitMode: object | The watermark position in the portrait mode. + */ +export class WatermarkOptions { + visibleInPreview?: boolean + positionInLandscapeMode: Rectangle + positionInPortraitMode: Rectangle + + constructor(positionInLandscapeMode: Rectangle, positionInPortraitMode: Rectangle, visibleInPreview?: boolean) { + this.visibleInPreview = visibleInPreview; + this.positionInLandscapeMode = positionInLandscapeMode; + this.positionInPortraitMode = positionInPortraitMode; + } +} + +/** + * Configuration of the imported live broadcast voice or video stream. + * @property width: int | Width of the added stream to the broadcast. The default value is 0, which is the same width as the original stream. + * @property height: int | Height of the added stream to the broadcast. The default value is 0, which is the same height as the original stream. + * @property videoGop: int | Video GOP of the added stream to the broadcast. The default value is 30 frames. + * @property videoFramerate: int | Video frame rate of the added stream to the broadcast. The default value is 15 fps. + * @property videoBitrate: int | Video bitrate of the added stream to the broadcast. The default value is 400 Kbps. + * @property audioSampleRate: int | Audio sample rate of the added stream to the broadcast: AudioSampleRateType. The default value is 44100 Hz. + * @property audioBitrate: int | Audio bitrate of the added stream to the broadcast. The default value is 48. + * @property audioChannels: int | Audio channels to add into the broadcast. The value ranges between 1 and 2. The default value is 1. + */ +export class LiveInjectStreamConfig { + width?: number + height?: number + videoGop?: number + videoFramerate?: VideoFrameRate + videoBitrate?: number + audioSampleRate?: AudioSampleRateType + audioBitrate?: number + audioChannels?: AudioChannel + + constructor({width, height, videoGop, videoFramerate, videoBitrate, audioSampleRate, audioBitrate, audioChannels}: { width?: number, height?: number, videoGop?: number, videoFramerate?: VideoFrameRate, videoBitrate?: number, audioSampleRate?: AudioSampleRateType, audioBitrate?: number, audioChannels?: AudioChannel }) { + this.width = width; + this.height = height; + this.videoGop = videoGop; + this.videoFramerate = videoFramerate; + this.videoBitrate = videoBitrate; + this.audioSampleRate = audioSampleRate; + this.audioBitrate = audioBitrate; + this.audioChannels = audioChannels; + } +} + +/** + * The definition of CameraCapturerConfiguration. + * @property preference: int | The camera capturer configuration. + * @property cameraDirection: int | The camera direction. + */ +export class CameraCapturerConfiguration { + preference: CameraCaptureOutputPreference + cameraDirection: CameraDirection + + constructor(preference: CameraCaptureOutputPreference, cameraDirection: CameraDirection) { + this.preference = preference; + this.cameraDirection = cameraDirection; + } +} + +/** + * The channel media options. + * @property autoSubscribeAudio: boolean | Determines whether to subscribe to audio streams when the user joins the channel. + * @property autoSubscribeVideo: boolean | Determines whether to subscribe to video streams when the user joins the channel. + */ +export class ChannelMediaOptions { + autoSubscribeAudio: boolean + autoSubscribeVideo: boolean + + constructor(autoSubscribeAudio: boolean, autoSubscribeVideo: boolean) { + this.autoSubscribeAudio = autoSubscribeAudio; + this.autoSubscribeVideo = autoSubscribeVideo; + } +} + +/** + * Statistics of RTCEngine. + * @property totalDuration: int | Call duration in seconds, represented by an aggregate value. + * @property txBytes: int | Total number of bytes transmitted, represented by an aggregate value. + * @property rxBytes: int | Total number of bytes received, represented by an aggregate value. + * @property txAudioBytes: int | Total number of audio bytes sent (bytes), represented by an aggregate value. + * @property txVideoBytes: int | Total number of video bytes sent (bytes), represented by an aggregate value. + * @property rxAudioBytes: int | Total number of audio bytes received (bytes), represented by an aggregate value. + * @property rxVideoBytes: int | Total number of video bytes received (bytes), represented by an aggregate value. + * @property txKBitRate: int | Transmission bitrate in Kbps, represented by an instantaneous value. + * @property rxKBitRate: int | Receive bitrate (Kbps), represented by an instantaneous value. + * @property txAudioKBitRate: int | The transmission bitrate of the audio packet (Kbps), represented by an instantaneous value. + * @property rxAudioKBitRate: int | Audio receive bitrate (Kbps), represented by an instantaneous value. + * @property txVideoKBitRate: int | Video transmission bitrate (Kbps), represented by an instantaneous value. + * @property rxVideoKBitRate: int | Video receive bitrate (Kbps), represented by an instantaneous value. + * @property users: int | The number of users in the channel. + * @property lastmileDelay: int | Client-server latency. + * @property txPacketLossRate: int | The packet loss rate (%) from the local client to Agora's edge server, before network countermeasures. + * @property rxPacketLossRate: int | The packet loss rate (%) from Agora's edge server to the local client, before network countermeasures. + * @property cpuTotalUsage: float | System CPU usage (%). + * @property cpuAppUsage: float | Application CPU usage (%). + * @property gatewayRtt: int | The round-trip time delay from the client to the local router. + * @property memoryAppUsageRatio: float | The memory usage ratio of the app (%). + * @property memoryTotalUsageRatio: float | The memory usage ratio of the system (%). + * @property memoryAppUsageInKbytes: int | The memory usage of the app (KB). + */ +export interface RtcStats { + totalDuration: number + txBytes: number + rxBytes: number + txAudioBytes: number + txVideoBytes: number + rxAudioBytes: number + rxVideoBytes: number + txKBitRate: number + rxKBitRate: number + txAudioKBitRate: number + rxAudioKBitRate: number + txVideoKBitRate: number + rxVideoKBitRate: number + users: number + lastmileDelay: number + txPacketLossRate: number + rxPacketLossRate: number + cpuTotalUsage: number + cpuAppUsage: number + gatewayRtt: number + memoryAppUsageRatio: number + memoryTotalUsageRatio: number + memoryAppUsageInKbytes: number +} + +/** + * Properties of the audio volume information. An array containing the user ID and volume information for each speaker. + * @property uid: int | The user ID of the speaker. The uid of the local user is 0. + * @property volume: int | The sum of the voice volume and audio-mixing volume of the speaker. The value ranges between 0 (lowest volume) and 255 (highest volume). + * @property vad: int | Voice activity status of the local user. + * @property channelId: string | The channel ID, which indicates which channel the speaker is in. + */ +export interface AudioVolumeInfo { + uid: number + volume: number + vad: number + channelId: string +} + +/** + * Rect. + * @property left: int | Left. + * @property top: int | Top. + * @property right: int | Right. + * @property bottom: int | Bottom. + */ +export interface Rect { + left: number + top: number + right: number + bottom: number +} + +/** + * The one-way last-mile probe result. + * @property packetLossRate: int | The packet loss rate (%). + * @property jitter: int | The network jitter (ms). + * @property availableBandwidth: int | The estimated available bandwidth (bps). + */ +export interface LastmileProbeOneWayResult { + packetLossRate: number + jitter: number + availableBandwidth: number +} + +/** + * Statistics of the lastmile probe. + * @property state: int | The state of the probe test. + * @property rtt: int | The round-trip delay time (ms). + * @property uplinkReport: object | The uplink last-mile network report. + * @property downlinkReport: object | The downlink last-mile network report. + */ +export interface LastmileProbeResult { + state: LastmileProbeResultState + rtt: number + uplinkReport: LastmileProbeOneWayResult + downlinkReport: LastmileProbeOneWayResult +} + +/** + * Statistics of the local audio stream. + * @property numChannels: int | The number of channels. + * @property sentSampleRate: int | The sample rate (Hz). + * @property sentBitrate: int | The average sending bitrate (Kbps). + */ +export interface LocalAudioStats { + numChannels: number + sentSampleRate: number + sentBitrate: number +} + +/** + * Statistics of the local video. + * @property sentBitrate: int | Bitrate (Kbps) sent in the reported interval, which does not include the bitrate of the re-transmission video after the packet loss. + * @property sentFrameRate: int | Frame rate (fps) sent in the reported interval, which does not include the frame rate of the re-transmission video after the packet loss. + * @property encoderOutputFrameRate: int | The encoder output frame rate (fps) of the local video. + * @property rendererOutputFrameRate: int | The renderer output frame rate (fps) of the local video. + * @property targetBitrate: int | The target bitrate (Kbps) of the current encoder. This value is estimated by the SDK based on the current network conditions. + * @property targetFrameRate: int | The target frame rate (fps) of the current encoder. + * @property qualityAdaptIndication: int | Quality change of the local video in terms of target frame rate and target bit rate since last count. + * @property encodedBitrate: int | The encoding bitrate (Kbps), which does not include the bitrate of the re-transmission video after packet loss. + * @property encodedFrameWidth: int | The width of the encoding frame (px). + * @property encodedFrameHeight: int | The height of the encoding frame (px). + * @property encodedFrameCount: int | The value of the sent frame rate, represented by an aggregate value. + * @property codecType: int | The codec type of the local video. + */ +export interface LocalVideoStats { + sentBitrate: number + sentFrameRate: number + encoderOutputFrameRate: number + rendererOutputFrameRate: number + targetBitrate: number + targetFrameRate: number + qualityAdaptIndication: VideoQualityAdaptIndication + encodedBitrate: number + encodedFrameWidth: number + encodedFrameHeight: number + encodedFrameCount: number + codecType: VideoCodecType +} + +/** + * Statistics of the remote audio. + * @property uid: int | User ID of the user sending the audio streams. + * @property quality: int | Audio quality received by the user. + * @property networkTransportDelay: int | Network delay (ms) from the sender to the receiver. + * @property jitterBufferDelay: int | Network delay (ms) from the receiver to the jitter buffer. + * @property audioLossRate: int | Packet loss rate in the reported interval. + * @property numChannels: int | The number of channels. + * @property receivedSampleRate: int | The sample rate (Hz) of the received audio stream in the reported interval. + * @property receivedBitrate: int | The average bitrate (Kbps) of the received audio stream in the reported interval. + * @property totalFrozenTime: int | The total freeze time (ms) of the remote audio stream after the remote user joins the channel. In the reported interval, audio freeze occurs when the audio frame loss rate reaches 4%. totalFrozenTime = The audio freeze time × 2 × 1000 (ms). + * @property frozenRate: int | The total audio freeze time as a percentage (%) of the total time when the audio is available. + * @property totalActiveTime: int | The total time (ms) when the remote user in the Communication profile or the remote broadcaster in the Live-broadcast profile neither stops sending the audio stream nor disables the audio module after joining the channel. + */ +export interface RemoteAudioStats { + uid: number + quality: NetworkQuality + networkTransportDelay: number + jitterBufferDelay: number + audioLossRate: number + numChannels: number + receivedSampleRate: number + receivedBitrate: number + totalFrozenTime: number + frozenRate: number + totalActiveTime: number +} + +/** + * Statistics of the remote video. + * @property uid: int | User ID of the user sending the video streams. + * @property delay: int | Time delay (ms). In scenarios where audio and video is synchronized, you can use the value of networkTransportDelay and jitterBufferDelay in RemoteAudioStats to know the delay statistics of the remote video. + * @property width: int | Width (pixels) of the remote video. + * @property height: int | Height (pixels) of the remote video. + * @property receivedBitrate: int | Bitrate (Kbps) received in the reported interval. + * @property decoderOutputFrameRate: int | The decoder output frame rate (fps) of the remote video. + * @property rendererOutputFrameRate: int | The renderer output frame rate (fps) of the remote video. + * @property packetLossRate: int | Packet loss rate (%) of the remote video stream after network countermeasures. + * @property rxStreamType: int | Video stream type (high-stream or low-stream). + * @property totalFrozenTime: int | The total freeze time (ms) of the remote video stream after the remote user joins the channel. + * @property frozenRate: int | The total video freeze time as a percentage (%) of the total time when the video is available. + * @property totalActiveTime: int | The total time (ms) when the remote user in the Communication profile or the remote broadcaster in the Live-broadcast profile neither stops sending the video stream nor disables the video module after joining the channel. + */ +export interface RemoteVideoStats { + uid: number + /** + * @deprecated + */ + delay: number + width: number + height: number + receivedBitrate: number + decoderOutputFrameRate: number + rendererOutputFrameRate: number + packetLossRate: number + rxStreamType: VideoStreamType + totalFrozenTime: number + frozenRate: number + totalActiveTime: number +} + +/** + * The information of the detected human face. + * @property x: int | The x coordinate (px) of the human face in the local video. Taking the top left corner of the captured video as the origin, the x coordinate represents the relative lateral displacement of the top left corner of the human face to the origin. + * @property y: int | The y coordinate (px) of the human face in the local video. Taking the top left corner of the captured video as the origin, the y coordinate represents the relative longitudinal displacement of the top left corner of the human face to the origin. + * @property width: int | The width (px) of the human face in the captured video. + * @property height: int | The height (px) of the human face in the captured video. + * @property distance: int | The distance (cm) between the human face and the screen. + */ +export interface FacePositionInfo { + x: number + y: number + width: number + height: number + distance: number +} diff --git a/src/index.ts b/src/index.ts index b9985b28a..5c0c95ba4 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,3 +1,12 @@ -export {default as AgoraView} from './AgoraView.native'; -export {default as RtcEngine} from './RtcEngine.native'; -export * from "./types"; \ No newline at end of file +import RtcEngine from './RtcEngine.native' +import RtcChannel from './RtcChannel.native' +import {RtcLocalView, RtcRemoteView} from './RtcRenderView.native' +import * as Types from './Types' + +export default RtcEngine +export { + RtcChannel, + RtcLocalView, + RtcRemoteView, + Types +} diff --git a/src/types.ts b/src/types.ts deleted file mode 100644 index b4443a5b5..000000000 --- a/src/types.ts +++ /dev/null @@ -1,374 +0,0 @@ -import { ViewProps } from 'react-native'; - -/** - * ChannelMediaInfo - * @property channelName: string - * @property token: string - * @property uid: number - */ -export interface ChannelMediaInfo { - channelName: string - token?: string - uid?: number -} -/** - * ChannelMediaConfiguration - * @property src: { - * @member channelName, - * @member token, - * @member uid, - * } - * @property channels: {@link Array} - */ -export interface ChannelMediaConfiguration { - src?: { - channelName: string - token?: string - uid?: number - } - channels: Array -} - -/** - * AgoraViewMode - * @mode hidden Uniformly scale the video until it fills the visible boundaries (cropped). One dimension of the video may have clipped contents. - * @mode FIT Uniformly scale the video until one of its dimension fits the boundary (zoomed to fit). Areas that are not filled due to the disparity in the aspect ratio are filled with black. - */ -export enum AgoraViewMode { - HIDDEN = 1, - FIT = 2 -} - -/** - * AgoraUserInfo - * @property uid: number - * @property userAccount: string - */ -export interface AgoraUserInfo { - uid: number - userAccount: string -}; - -/** - * VideoEncoderConfig details - * @property width: number | The encoder video's width - * @property height: number | The encoder video's height - * @property bitrate: number | The encoder video's bitrate - * @property frameRate: number | The frameRate of encoder video - * @property orientationMode: number | The video orientation mode of the video - * @orientationMode value range is [0 is "mode adapative", 1 is "mode fixed landscape", 2 is "mode fixed portrait"] - */ -export interface VideoEncoderConfig { - width: number, - height: number, - bitrate: number, - frameRate: number, - orientationMode: number, -} - -/** - * Option is used to {@link init} - * @member {@link appid} Sets the appid - * @member {@link channelProfile} Number channelProfile Sets the channel mode. 0 is communication mode, 1 is broadcasting mode - * @member {@link VideoEncoderConfig} sets video encoding config - * @member {@link dualStream} is optional parameter only for enable for detail see [more](https://docs.agora.io/en/Video/API%20Reference/oc/Classes/AgoraRtcEngineKit.html#//api/name/enableDualStreamMode) - * @member {@link mode} is optional sets only enable video / audio, 0 is audio mode, 1 is video mode - * @member {@link clientRole} is only work in live mode, 1 is host, 2 is audience - * @member {@link audioProfile} Sets audio profile to agora rtc sdk See more [details](https://docs.agora.io/en/Video/API%20Reference/oc/Constants/AgoraAudioProfile.html) - * @member {@link audioScenario} Sets audio scenario to agora rtc sdk more [details](https://docs.agora.io/en/Video/API%20Reference/oc/Constants/AgoraAudioScenario.html) - * @member {@link beauty} {@link BeautyOption} - * @member {@link voice} {@link VoiceDecorator} - */ -export interface Option { - appid: String, - channelProfile: number, - videoEncoderConfig: VideoEncoderConfig, - dualStream?: boolean, - mode?: number, - clientRole: number, - audioProfile: number, - audioScenario: number, - beauty?: BeautyOption, - voice?: VoiceDecorator, -} - -/** - * VoiceDecorator is decorate local audio voice - * - * @description - * type 'reverbPreset' range values: [0 is "off", 1 is "popular", 2 is "rnb", 3 is "rock", 4 is "hiphop", 5 is "vocal concert", 6 is "KTV", 7 is "studio"] - * type 'changer' range values: [0 is "off", 1 is "old man", 2 is "baby boy", 3 is "baby girl", 4 is "zhubajie", 5 is "ethereal", 6 is "hulk"] - * @member type: string | the range values ['changer' | 'reverbPreset'] This property is the identifier for audio voice decorator - * @member value: number | the value for voice parameter option. - */ -export interface VoiceDecorator { - type: string, - value: number -} - -export interface PublisherConfig { - width: number, - height: number, - framerate: number, - bitrate: number, - defaultLayout: number, - lifeCycle: number, - pubishUrl: string, - rawStreamUrl: string, - extraInfo: String, - owner: boolean -} - -export interface BackgroundImage { - url: string, - x: number, - y: number, - width: number, - height: number -} - -export interface Size { - width: number, - height: number -} - -export interface TranscodingUser { - uid: number, - x: number, - y: number, - width: number, - height: number, - alpha: number, - zOrder: number, - audioChannel: number -} - -export interface Color { - red: number, - green: number, - blue: number, - alpha: number -} - -export enum VideoCodecProfile { - BASELINE = 66, - MAIN = 77, - HIGH = 100 -} - -export enum AudioCodecProfile { - LC_AAC = 0, - HE_AAC = 1 -} - -export enum AudioSampleRate { - TYPE_32000 = 32000, - TYPE_44100 = 44100, - TYPE_48000 = 48000, -} - -/** - * AgoraChannelStereo - * @note Agora’s self-defined audio channel type. We recommend choosing ONE or TWO. Special players are required if you choose TRHEE, FOUR or FIVE: - */ -export enum AudioChannelStereo { - ONE = 1, - TWO = 2, - TRHEE = 3, - FOUR = 4, - FIVE = 5 -} - -/** - * @member {@link size} {@link Size} - * @member {@link videoBitrate} integer number - * @member {@link videoFramerate} integer number - * @member {@link lowLatency} boolean - * @member {@link videoGop} number - * @member {@link videoCodecProfile} {@link VideoCodecProfile} - * @member {@link audioCodecProfile} {@link AudioCodecProfile} - * @member {@link audioSampleRate} {@link AudioSampleRate} - * @member {@link watermark} {@link BackgroundImage} - * @member {@link backgroundImage} {@link BackgroundImage} - * @member {@link backgroundColor} Standard RGB hex number: e.g. 0xffffff - * @member {@link audioBitrate} number - * @member {@link audioChannels} {@link AudioChannelStereo} - * @member {@link transcodingUsers} Array,{@link TranscodingUser}>, - * @member {@link transcodingExtraInfo} string - */ -export interface LiveTranscodingOption { - size: Size, - videoBitrate: number, - videoFramerate: number, - lowLatency: boolean, // @deprecate lowLatency - videoGop: number, - videoCodecProfile: VideoCodecProfile, - audioCodecProfile: AudioCodecProfile, - audioSampleRate: AudioSampleRate, - watermark: BackgroundImage, - backgroundImage: BackgroundImage, - backgroundColor: number, - audioBitrate: number, - audioChannels: AudioChannelStereo, - transcodingUsers: Array, - transcodingExtraInfo: string, -} - -export interface VideoOption { - uid: number, - renderMode: number, - reactTag: number -} - -export interface AudioRecordingOption { - filepath: String, - sampleRate: number, - quality: number -} - -export type Callback = (err: any, data: any) => T; - -export type Nullable = T | null | undefined; - -export type String = Nullable; -export type Number = Nullable | 0; - -export interface AgoraViewProps extends ViewProps { - mode: number, - showLocalVideo: boolean, - remoteUid: number, - zOrderMediaOverlay: boolean, - [key:string]: any; -} - -export interface DataStreamOption { - streamId: number, - ordered: boolean, - reliable: boolean -} - -export interface AudioMixingOption { - filepath: String, - loopback: boolean, - replace: boolean, - cycle: number -} - -export interface PlayEffectOption { - soundId: number, - filepath: String, - loopcount: number, - pitch: number, - pan: number, - gain: number, - publish: boolean -} - -export interface AudioFrameOption { - sampleRate: number, - channel: number, - mode: number, - samplesPerCall: number -} - -export interface MixedAudioFrameOption { - sampleRate: number, - samplesPerCall: number -} - -export interface ImageOption { - visibleInPreview: boolean - positionInPortraitMode: { - x: number, - y: number, - width: number, - height: number, - } - positionInLandscapeMode: { - x: number, - y: number, - width: number, - height: number, - } -} - -export interface VideoStreamOption { - uid: number, - streamType: number -} - -export interface DefaultVideoStreamOption { - streamType: number -} - -export interface InjectStreamOption { - url: String, - config: { - size: { - width: number, - height: number, - }, - videoGop: number, - videoBitrate: number, - videoFramerate: number, - audioBitrate: number, - audioSampleRate: number, - audioChannels: number - } -} - -export interface RemoveInjectStreamOption { - url: String -} - -export interface PublishStreamOption { - url: String, - enable: boolean -} - -export interface RemovePublishStreamOption { - url: String -} - -export interface PositionOption { - x: number, - y: number -} - -/** - * BeautyOption is setBeautyEffectOptions's option parameter - * @property lighteningContrastLevel: integer | lightening contrast level and the value ranges is low: 0, normal: 1, high: 2 - * @property lighteningLevel: float | brightness level and the value ranges between 0.0 (original) and 1.0. - * @property smoothnessLevel: float | The sharpness level. The value ranges between 0.0 (original) and 1.0. This parameter is usually used to remove blemishes. - * @property rednessLevel: float | The redness level. The value ranges between 0.0 (original) and 1.0. This parameter adjusts the red saturation level. - */ -export interface BeautyOption { - lighteningContrastLevel: number, - lighteningLevel: number, - smoothnessLevel: number, - rednessLevel: number, -} - -/** - * LastmileProbeConfig is startLastmileProbeTest's config parameter - * @property probeUplink: boolean | sets whether or not to test the uplink networks. some users, for example, the audience in a Live-broadcast channel, do not need such a test. true: enables the probe test. false: disables the probe test. - * @property probeDownlink: boolean | sets whether or not to probe the downlink network. true: enables the probe test. false: disables the probe test. - * @property expectedUplinkBitrate: integer | The expected maximum sending bitrate (Kbps) of the local user. The value ranges between 100 and 5000. We recommend setting this parameter according to the bitrate value set by setVideoEncoderConfiguration. - * @property expectedDownlinkBitrate: integer | The expected maximum receiving bitrate (Kbps) of the local user. The value ranges between 100 and 5000. - */ -export interface LastmileProbeConfig { - probeUplink: boolean, - probeDownlink: boolean, - expectedUplinkBitrate: number, - expectedDownlinkBitrate: number -} - - -/** - * CameraCapturerConfiguration is setCameraCapturerConfiguration's config parameter - * @property preference: number | The Camera capture preference and the value range is [0 is "(default) self-adapts the camera output parameters to the system performance and network conditions to balance CPU consumption and video preview quality.", 1 is "prioritizes the system performance. The SDK chooses the dimension and frame rate of the local camera capture closest to those set by setVideoEncoderConfiguration.", 2 is "prioritizes the local preview quality. The SDK chooses higher camera output parameters to improve the local video preview quality. This option requires extra CPU and RAM usage for video pre-processing."] - */ -export interface CameraCapturerConfiguration { - preference: number - cameraDirection: number -} diff --git a/tsconfig.json b/tsconfig.json index 1a8367d6e..55c84cd99 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,26 +1,65 @@ -{ + + { "compilerOptions": { - "declaration": true, - "declarationDir": "./lib", - "types": [ - "react", - "react-native" - ], - "target": "es2015", - "jsx": "react", - "moduleResolution": "node", - "sourceMap": true, - "importHelpers": true, - "outDir": "./lib", - "module": "commonjs", - "strict": true, - "declaration": true, - "allowSyntheticDefaultImports": true, - "esModuleInterop": true, - "lib": ["es2015"] + /* Basic Options */ + "target": "esnext", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */ + "module": "esnext", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */ + "lib": ["es6"], /* Specify library files to be included in the compilation. */ + "allowJs": true, /* Allow javascript files to be compiled. */ + // "checkJs": true, /* Report errors in .js files. */ + "jsx": "react", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ + "declaration": true, /* Generates corresponding '.d.ts' file. */ + "sourceMap": true, /* Generates corresponding '.map' file. */ + // "outFile": "./", /* Concatenate and emit output to single file. */ + "outDir": "./lib", /* Redirect output structure to the directory. */ + // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ + // "removeComments": true, /* Do not emit comments to output. */ + // "noEmit": true, /* Do not emit outputs. */ + "incremental": true, /* Enable incremental compilation */ + "importHelpers": true, /* Import emit helpers from 'tslib'. */ + // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ + "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ + + /* Strict Type-Checking Options */ + "strict": true, /* Enable all strict type-checking options. */ + // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ + // "strictNullChecks": true, /* Enable strict null checks. */ + // "strictFunctionTypes": true, /* Enable strict checking of function types. */ + // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ + // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ + // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ + + /* Additional Checks */ + // "noUnusedLocals": true, /* Report errors on unused locals. */ + // "noUnusedParameters": true, /* Report errors on unused parameters. */ + // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ + // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ + + /* Module Resolution Options */ + "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ + "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ + // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ + // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ + // "typeRoots": [], /* List of folders to include type definitions from. */ + // "types": [], /* Type declaration files to be included in compilation. */ + "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ + "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ + // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ + + /* Source Map Options */ + // "sourceRoot": "./", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ + // "mapRoot": "./", /* Specify the location where debugger should locate map files instead of generated locations. */ + // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ + // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ + + /* Experimental Options */ + // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ + // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ }, - "compileOnSave": true, + "exclude": [ + "node_modules", "babel.config.js", "metro.config.js", "jest.config.js" + ], "include": [ - "src" + "./src" ] }