This commit is contained in:
li 2024-06-04 07:16:08 +00:00 committed by GitHub
commit 3c7f6ac2ef
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
78 changed files with 3394 additions and 950 deletions

6
.gitmodules vendored
View File

@ -7,6 +7,12 @@
[submodule "3rdpart/jsoncpp"]
path = 3rdpart/jsoncpp
url = https://gitee.com/mirrors/jsoncpp.git
[submodule "3rdpart/openssl"]
path = 3rdpart/openssl
url = https://gitee.com/varlet_mirror/openssl-1.1.1k.git
[submodule "www/webassist"]
path = www/webassist
url = https://gitee.com/victor1002/zlm_webassist
[submodule "3rdpart/libsrtp"]
path = 3rdpart/libsrtp
url = https://github.com/cisco/libsrtp.git

View File

@ -7,6 +7,9 @@
[submodule "3rdpart/jsoncpp"]
path = 3rdpart/jsoncpp
url = https://github.com/open-source-parsers/jsoncpp.git
[submodule "3rdpart/openssl"]
path = 3rdpart/openssl
url = https://gitee.com/varlet_mirror/openssl-1.1.1k.git
[submodule "www/webassist"]
path = www/webassist
url = https://github.com/1002victor/zlm_webassist

View File

@ -197,6 +197,7 @@ else()
_CRT_SECURE_NO_WARNINGS _WINSOCK_DEPRECATED_NO_WARNINGS)
endif()
#
add_library(zltoolkit STATIC ${ToolKit_SRC_LIST})
add_library(ZLMediaKit::ToolKit ALIAS zltoolkit)

1
3rdpart/libsrtp Submodule

@ -0,0 +1 @@
Subproject commit 9a139f5c8ba7629b3c0ac9cc7bbf74e4bf10313a

1
3rdpart/openssl Submodule

@ -0,0 +1 @@
Subproject commit 91157f7e572916a7e5b910bae2e0f71b13a7c35e

View File

@ -1,7 +1,7 @@
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
compileSdkVersion 30
//ndkVersion "25.1.xxx"
defaultConfig {
applicationId "com.zlmediakit.demo"
@ -33,6 +33,21 @@ android {
path "src/main/cpp/CMakeLists.txt"
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
// kotlinOptions {
// jvmTarget = "17"
// }
// buildFeatures {
// viewBinding = true
// buildConfig = true
// }
}
dependencies {

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -9,15 +9,42 @@ set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/libs_export/${AND
set(EXECUTABLE_OUTPUT_PATH ${CMAKE_CURRENT_SOURCE_DIR}/libs_export/${ANDROID_ABI}/binary)
set(OPENSSL_ROOT_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../../libs/${ANDROID_ABI}")
#openssl-fPICgithub action ci
#set(OPENSSL_INCLUDE_DIR "${OPENSSL_ROOT_DIR}/include")
#set(OPENSSL_CRYPTO_LIBRARY "${OPENSSL_ROOT_DIR}/libcrypto.a")
#set(OPENSSL_SSL_LIBRARY "${OPENSSL_ROOT_DIR}/libssl.a")
###################################################################
# openssl 1.1.1k
#if (ANDROID)
# message(WARNING "Enable Android openssl compile")
# execute_process(
# COMMAND bash -c "./../../3rdpart/openssl/Configure android-aarch64 -D__ANDROID_API__=16"
# OUTPUT_VARIABLE output
# RESULT_VARIABLE result
# )
# if (result)
# message(FATAL_ERROR "Failed to execute bash command: ${result}")
# endif ()
# message(WARNING "Enable Android openssl compile===================")
# message("Output: ${output}")
#ENDIF ()
#
set(JNI_Root ${CMAKE_CURRENT_SOURCE_DIR})
set(ZLMediaKit_Root ${CMAKE_CURRENT_SOURCE_DIR}/../../../../../)
#openssl-fPICgithub action ci
set(OPENSSL_INCLUDE_DIR "${ZLMediaKit_Root}3rdpart/openssl/include")
set(OPENSSL_CRYPTO_LIBRARY "${ZLMediaKit_Root}Android/app/libs/${ANDROID_ABI}/libcrypto.a")
set(OPENSSL_SSL_LIBRARY "${ZLMediaKit_Root}Android/app/libs/${ANDROID_ABI}/libssl.a")
set(SRTP_INCLUDE_DIRS "include")
set(SRTP_LIBRARIES "${ZLMediaKit_Root}Android/app/libs/${ANDROID_ABI}/libsrtp2.a")
include_directories(${OPENSSL_INCLUDE_DIR})
include_directories(${SRTP_INCLUDE_DIRS})
#cmake
add_subdirectory(${ZLMediaKit_Root} ${EXECUTABLE_OUTPUT_PATH})
@ -34,7 +61,7 @@ include_directories(${ZLMediaKit_Root}/3rdpart/ZLToolKit/src)
#
file(GLOB JNI_src_list ${JNI_Root}/*.cpp ${JNI_Root}/*.h)
add_library(zlmediakit_jni SHARED ${JNI_src_list})
message(WARNING ${MK_LINK_LIBRARIES})
#
target_link_libraries(zlmediakit_jni -Wl,--start-group log z ${MK_LINK_LIBRARIES} -Wl,--end-group)

View File

@ -0,0 +1,173 @@
/*
* auth.h
*
* common interface to authentication functions
*
* David A. McGrew
* Cisco Systems, Inc.
*/
/*
*
* Copyright (c) 2001-2017, Cisco Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* Neither the name of the Cisco Systems, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef SRTP_AUTH_H
#define SRTP_AUTH_H
#include "srtp.h"
#include "crypto_types.h" /* for values of auth_type_id_t */
#ifdef __cplusplus
extern "C" {
#endif
typedef const struct srtp_auth_type_t *srtp_auth_type_pointer;
typedef struct srtp_auth_t *srtp_auth_pointer_t;
typedef srtp_err_status_t (*srtp_auth_alloc_func)(srtp_auth_pointer_t *ap,
int key_len,
int out_len);
typedef srtp_err_status_t (*srtp_auth_init_func)(void *state,
const uint8_t *key,
int key_len);
typedef srtp_err_status_t (*srtp_auth_dealloc_func)(srtp_auth_pointer_t ap);
typedef srtp_err_status_t (*srtp_auth_compute_func)(void *state,
const uint8_t *buffer,
int octets_to_auth,
int tag_len,
uint8_t *tag);
typedef srtp_err_status_t (*srtp_auth_update_func)(void *state,
const uint8_t *buffer,
int octets_to_auth);
typedef srtp_err_status_t (*srtp_auth_start_func)(void *state);
/* some syntactic sugar on these function types */
#define srtp_auth_type_alloc(at, a, klen, outlen) \
((at)->alloc((a), (klen), (outlen)))
#define srtp_auth_init(a, key) \
(((a)->type)->init((a)->state, (key), ((a)->key_len)))
#define srtp_auth_compute(a, buf, len, res) \
(((a)->type)->compute((a)->state, (buf), (len), (a)->out_len, (res)))
#define srtp_auth_update(a, buf, len) \
(((a)->type)->update((a)->state, (buf), (len)))
#define srtp_auth_start(a) (((a)->type)->start((a)->state))
#define srtp_auth_dealloc(c) (((c)->type)->dealloc(c))
/* functions to get information about a particular auth_t */
int srtp_auth_get_key_length(const struct srtp_auth_t *a);
int srtp_auth_get_tag_length(const struct srtp_auth_t *a);
int srtp_auth_get_prefix_length(const struct srtp_auth_t *a);
/*
* srtp_auth_test_case_t is a (list of) key/message/tag values that are
* known to be correct for a particular cipher. this data can be used
* to test an implementation in an on-the-fly self test of the
* correctness of the implementation. (see the srtp_auth_type_self_test()
* function below)
*/
typedef struct srtp_auth_test_case_t {
int key_length_octets; /* octets in key */
const uint8_t *key; /* key */
int data_length_octets; /* octets in data */
const uint8_t *data; /* data */
int tag_length_octets; /* octets in tag */
const uint8_t *tag; /* tag */
const struct srtp_auth_test_case_t
*next_test_case; /* pointer to next testcase */
} srtp_auth_test_case_t;
/* srtp_auth_type_t */
typedef struct srtp_auth_type_t {
srtp_auth_alloc_func alloc;
srtp_auth_dealloc_func dealloc;
srtp_auth_init_func init;
srtp_auth_compute_func compute;
srtp_auth_update_func update;
srtp_auth_start_func start;
const char *description;
const srtp_auth_test_case_t *test_data;
srtp_auth_type_id_t id;
} srtp_auth_type_t;
typedef struct srtp_auth_t {
const srtp_auth_type_t *type;
void *state;
int out_len; /* length of output tag in octets */
int key_len; /* length of key in octets */
int prefix_len; /* length of keystream prefix */
} srtp_auth_t;
/*
* srtp_auth_type_self_test() tests an auth_type against test cases
* provided in an array of values of key/message/tag that is known to
* be good
*/
srtp_err_status_t srtp_auth_type_self_test(const srtp_auth_type_t *at);
/*
* srtp_auth_type_test() tests an auth_type against external test cases
* provided in an array of values of key/message/tag that is known to
* be good
*/
srtp_err_status_t srtp_auth_type_test(const srtp_auth_type_t *at,
const srtp_auth_test_case_t *test_data);
/*
* srtp_replace_auth_type(ct, id)
*
* replaces srtp's kernel's auth type implementation for the auth_type id
* with a new one passed in externally. The new auth type must pass all the
* existing auth_type's self tests as well as its own.
*/
srtp_err_status_t srtp_replace_auth_type(const srtp_auth_type_t *ct,
srtp_auth_type_id_t id);
#ifdef __cplusplus
}
#endif
#endif /* SRTP_AUTH_H */

View File

@ -0,0 +1,248 @@
/*
* cipher.h
*
* common interface to ciphers
*
* David A. McGrew
* Cisco Systems, Inc.
*/
/*
*
* Copyright (c) 2001-2017 Cisco Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* Neither the name of the Cisco Systems, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef SRTP_CIPHER_H
#define SRTP_CIPHER_H
#include "srtp.h"
#include "crypto_types.h" /* for values of cipher_type_id_t */
#ifdef __cplusplus
extern "C" {
#endif
/*
* srtp_cipher_direction_t defines a particular cipher operation.
*
* A srtp_cipher_direction_t is an enum that describes a particular cipher
* operation, i.e. encryption or decryption. For some ciphers, this
* distinction does not matter, but for others, it is essential.
*/
typedef enum {
srtp_direction_encrypt, /**< encryption (convert plaintext to ciphertext) */
srtp_direction_decrypt, /**< decryption (convert ciphertext to plaintext) */
srtp_direction_any /**< encryption or decryption */
} srtp_cipher_direction_t;
/*
* the srtp_cipher_pointer_t definition is needed
* as srtp_cipher_t is not yet defined
*/
typedef struct srtp_cipher_t *srtp_cipher_pointer_t;
/*
* a srtp_cipher_alloc_func_t allocates (but does not initialize) a
* srtp_cipher_t
*/
typedef srtp_err_status_t (*srtp_cipher_alloc_func_t)(srtp_cipher_pointer_t *cp,
int key_len,
int tag_len);
/*
* a srtp_cipher_init_func_t [re-]initializes a cipher_t with a given key
*/
typedef srtp_err_status_t (*srtp_cipher_init_func_t)(void *state,
const uint8_t *key);
/* a srtp_cipher_dealloc_func_t de-allocates a cipher_t */
typedef srtp_err_status_t (*srtp_cipher_dealloc_func_t)(
srtp_cipher_pointer_t cp);
/*
* a srtp_cipher_set_aad_func_t processes the AAD data for AEAD ciphers
*/
typedef srtp_err_status_t (*srtp_cipher_set_aad_func_t)(void *state,
const uint8_t *aad,
uint32_t aad_len);
/* a srtp_cipher_encrypt_func_t encrypts data in-place */
typedef srtp_err_status_t (*srtp_cipher_encrypt_func_t)(
void *state,
uint8_t *buffer,
unsigned int *octets_to_encrypt);
/* a srtp_cipher_decrypt_func_t decrypts data in-place */
typedef srtp_err_status_t (*srtp_cipher_decrypt_func_t)(
void *state,
uint8_t *buffer,
unsigned int *octets_to_decrypt);
/*
* a srtp_cipher_set_iv_func_t function sets the current initialization vector
*/
typedef srtp_err_status_t (*srtp_cipher_set_iv_func_t)(
void *state,
uint8_t *iv,
srtp_cipher_direction_t direction);
/*
* a cipher_get_tag_func_t function is used to get the authentication
* tag that was calculated by an AEAD cipher.
*/
typedef srtp_err_status_t (*srtp_cipher_get_tag_func_t)(void *state,
uint8_t *tag,
uint32_t *len);
/*
* srtp_cipher_test_case_t is a (list of) key, salt, plaintext, ciphertext,
* and aad values that are known to be correct for a
* particular cipher. this data can be used to test an implementation
* in an on-the-fly self test of the correctness of the implementation.
* (see the srtp_cipher_type_self_test() function below)
*/
typedef struct srtp_cipher_test_case_t {
int key_length_octets; /* octets in key */
const uint8_t *key; /* key */
uint8_t *idx; /* packet index */
unsigned int plaintext_length_octets; /* octets in plaintext */
const uint8_t *plaintext; /* plaintext */
unsigned int ciphertext_length_octets; /* octets in plaintext */
const uint8_t *ciphertext; /* ciphertext */
int aad_length_octets; /* octets in AAD */
const uint8_t *aad; /* AAD */
int tag_length_octets; /* Length of AEAD tag */
const struct srtp_cipher_test_case_t
*next_test_case; /* pointer to next testcase */
} srtp_cipher_test_case_t;
/* srtp_cipher_type_t defines the 'metadata' for a particular cipher type */
typedef struct srtp_cipher_type_t {
srtp_cipher_alloc_func_t alloc;
srtp_cipher_dealloc_func_t dealloc;
srtp_cipher_init_func_t init;
srtp_cipher_set_aad_func_t set_aad;
srtp_cipher_encrypt_func_t encrypt;
srtp_cipher_encrypt_func_t decrypt;
srtp_cipher_set_iv_func_t set_iv;
srtp_cipher_get_tag_func_t get_tag;
const char *description;
const srtp_cipher_test_case_t *test_data;
srtp_cipher_type_id_t id;
} srtp_cipher_type_t;
/*
* srtp_cipher_t defines an instantiation of a particular cipher, with fixed
* key length, key and salt values
*/
typedef struct srtp_cipher_t {
const srtp_cipher_type_t *type;
void *state;
int key_len;
int algorithm;
} srtp_cipher_t;
/* some bookkeeping functions */
int srtp_cipher_get_key_length(const srtp_cipher_t *c);
/*
* srtp_cipher_type_self_test() tests a cipher against test cases provided in
* an array of values of key/srtp_xtd_seq_num_t/plaintext/ciphertext
* that is known to be good
*/
srtp_err_status_t srtp_cipher_type_self_test(const srtp_cipher_type_t *ct);
/*
* srtp_cipher_type_test() tests a cipher against external test cases provided
* in
* an array of values of key/srtp_xtd_seq_num_t/plaintext/ciphertext
* that is known to be good
*/
srtp_err_status_t srtp_cipher_type_test(
const srtp_cipher_type_t *ct,
const srtp_cipher_test_case_t *test_data);
/*
* srtp_cipher_bits_per_second(c, l, t) computes (an estimate of) the
* number of bits that a cipher implementation can encrypt in a second
*
* c is a cipher (which MUST be allocated and initialized already), l
* is the length in octets of the test data to be encrypted, and t is
* the number of trials
*
* if an error is encountered, then the value 0 is returned
*/
uint64_t srtp_cipher_bits_per_second(srtp_cipher_t *c,
int octets_in_buffer,
int num_trials);
srtp_err_status_t srtp_cipher_type_alloc(const srtp_cipher_type_t *ct,
srtp_cipher_t **c,
int key_len,
int tlen);
srtp_err_status_t srtp_cipher_dealloc(srtp_cipher_t *c);
srtp_err_status_t srtp_cipher_init(srtp_cipher_t *c, const uint8_t *key);
srtp_err_status_t srtp_cipher_set_iv(srtp_cipher_t *c,
uint8_t *iv,
int direction);
srtp_err_status_t srtp_cipher_output(srtp_cipher_t *c,
uint8_t *buffer,
uint32_t *num_octets_to_output);
srtp_err_status_t srtp_cipher_encrypt(srtp_cipher_t *c,
uint8_t *buffer,
uint32_t *num_octets_to_output);
srtp_err_status_t srtp_cipher_decrypt(srtp_cipher_t *c,
uint8_t *buffer,
uint32_t *num_octets_to_output);
srtp_err_status_t srtp_cipher_get_tag(srtp_cipher_t *c,
uint8_t *buffer,
uint32_t *tag_len);
srtp_err_status_t srtp_cipher_set_aad(srtp_cipher_t *c,
const uint8_t *aad,
uint32_t aad_len);
/*
* srtp_replace_cipher_type(ct, id)
*
* replaces srtp's existing cipher implementation for the cipher_type id
* with a new one passed in externally. The new cipher must pass all the
* existing cipher_type's self tests as well as its own.
*/
srtp_err_status_t srtp_replace_cipher_type(const srtp_cipher_type_t *ct,
srtp_cipher_type_id_t id);
#ifdef __cplusplus
}
#endif
#endif /* SRTP_CIPHER_H */

View File

@ -0,0 +1,116 @@
/*
* crypto_types.h
*
* constants for cipher types and auth func types
*
* David A. McGrew
* Cisco Systems, Inc.
*/
/*
*
* Copyright(c) 2001-2017 Cisco Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* Neither the name of the Cisco Systems, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef SRTP_CRYPTO_TYPES_H
#define SRTP_CRYPTO_TYPES_H
/*
* The null cipher performs no encryption.
*
* The SRTP_NULL_CIPHER leaves its inputs unaltered, during both the
* encryption and decryption operations. This cipher can be chosen
* to indicate that no encryption is to be performed.
*/
#define SRTP_NULL_CIPHER 0
/*
* AES-128 Integer Counter Mode (AES ICM)
*
* AES-128 ICM is the variant of counter mode that is used by
* Secure RTP. This cipher uses a 16-octet key concatenated with a
* 14-octet offset (or salt) value.
*/
#define SRTP_AES_ICM_128 1
/*
* AES-192 Integer Counter Mode (AES ICM)
*
* AES-128 ICM is the variant of counter mode that is used by
* Secure RTP. This cipher uses a 24-octet key concatenated with a
* 14-octet offset (or salt) value.
*/
#define SRTP_AES_ICM_192 4
/*
* AES-256 Integer Counter Mode (AES ICM)
*
* AES-128 ICM is the variant of counter mode that is used by
* Secure RTP. This cipher uses a 32-octet key concatenated with a
* 14-octet offset (or salt) value.
*/
#define SRTP_AES_ICM_256 5
/*
* AES-128_GCM Galois Counter Mode (AES GCM)
*
* AES-128 GCM is the variant of galois counter mode that is used by
* Secure RTP. This cipher uses a 16-octet key.
*/
#define SRTP_AES_GCM_128 6
/*
* AES-256_GCM Galois Counter Mode (AES GCM)
*
* AES-256 GCM is the variant of galois counter mode that is used by
* Secure RTP. This cipher uses a 32-octet key.
*/
#define SRTP_AES_GCM_256 7
/*
* The null authentication function performs no authentication.
*
* The NULL_AUTH function does nothing, and can be selected to indicate
* that authentication should not be performed.
*/
#define SRTP_NULL_AUTH 0
/*
* HMAC-SHA1
*
* SRTP_HMAC_SHA1 implements the Hash-based MAC using the NIST Secure
* Hash Algorithm version 1 (SHA1).
*/
#define SRTP_HMAC_SHA1 3
#endif /* SRTP_CRYPTO_TYPES_H */

File diff suppressed because it is too large Load Diff

View File

@ -34,7 +34,7 @@ public class MainActivity extends AppCompatActivity {
}
}
String sd_dir = Environment.getExternalStoragePublicDirectory("").toString();
String sd_dir = Environment.getExternalStoragePublicDirectory("zlmediakit").toString();
if(permissionSuccess){
Toast.makeText(this,"你可以修改配置文件再启动:" + sd_dir + "/zlmediakit.ini" ,Toast.LENGTH_LONG).show();
Toast.makeText(this,"SSL证书请放置在" + sd_dir + "/zlmediakit.pem" ,Toast.LENGTH_LONG).show();

View File

@ -7,7 +7,7 @@ buildscript {
}
dependencies {
classpath 'com.android.tools.build:gradle:4.0.1'
classpath 'com.android.tools.build:gradle:7.2.2'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files

Binary file not shown.

View File

@ -1,6 +1,6 @@
#Sun Jun 19 15:19:24 CST 2022
#Fri Dec 22 09:27:45 CST 2023
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.1.1-all.zip

286
Android/gradlew vendored
View File

@ -1,78 +1,129 @@
#!/usr/bin/env sh
#!/bin/sh
#
# Copyright ? 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
##
## Gradle start up script for UN*X
##
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions ?$var?, ?${var}?, ?${var:-default}?, ?${var+SET}?,
# ?${var#prefix}?, ?${var%suffix}?, and ?$( cmd )?;
# * compound commands having a testable exit status, especially ?case?;
# * various built-in commands including ?command?, ?set?, and ?ulimit?.
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# 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
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
APP_BASE_NAME=${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=""
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
MAX_FD=maximum
warn () {
echo "$*"
}
} >&2
die () {
echo
echo "$*"
echo
exit 1
}
} >&2
# 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
;;
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | 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"
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD="$JAVA_HOME/bin/java"
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
@ -81,7 +132,7 @@ Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
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
@ -89,84 +140,95 @@ 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" ;;
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
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, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# 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"
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
# 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")"
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

43
Android/gradlew.bat vendored
View File

@ -1,3 +1,19 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@ -13,15 +29,18 @@ if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@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=
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@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
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
@ -35,7 +54,7 @@ goto fail
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
@ -45,28 +64,14 @@ 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%
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell

View File

@ -191,6 +191,7 @@ bash build_docker_images.sh
- [jessibuca](https://github.com/langhuihui/jessibuca) 基于wasm支持H265的播放器
- [wsPlayer](https://github.com/v354412101/wsPlayer) 基于MSE的websocket-fmp4播放器
- [BXC_gb28181Player](https://github.com/any12345com/BXC_gb28181Player) C++开发的支持国标GB28181协议的视频流播放器
- [RTCPlayer](https://github.com/leo94666/RTCPlayer) 一个基于Android客户端的的RTC播放器
- WEB管理网站
- [zlm_webassist](https://github.com/1002victor/zlm_webassist) 本项目配套的前后端分离web管理项目
@ -366,6 +367,7 @@ bash build_docker_images.sh
[jamesZHANG500](https://github.com/jamesZHANG500)
[weidelong](https://github.com/wdl1697454803)
[小强先生](https://github.com/linshangqiang)
[李之阳](https://github.com/leo94666)
同时感谢JetBrains对开源项目的支持本项目使用CLion开发与调试

View File

@ -319,6 +319,7 @@ int start_main(int argc,char *argv[]) {
#endif//defined(ENABLE_RTPPROXY)
#if defined(ENABLE_WEBRTC)
InfoL << "已启动webrtc";
auto rtcSrv_tcp = std::make_shared<TcpServer>();
//webrtc udp服务器
auto rtcSrv_udp = std::make_shared<UdpServer>();

View File

@ -13,4 +13,3 @@
.externalNativeBuild
.cxx
local.properties
/.idea/

View File

@ -0,0 +1,3 @@
# Default ignored files
/shelf/
/workspace.xml

View File

@ -0,0 +1 @@
RTCPlayer

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<bytecodeTargetLevel target="17" />
</component>
</project>

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="deploymentTargetDropDown">
<value>
<entry key="app">
<State />
</entry>
</value>
</component>
</project>

View File

@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleMigrationSettings" migrationVersion="1" />
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="gradleJvm" value="#GRADLE_LOCAL_JAVA_HOME" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
<option value="$PROJECT_DIR$/app" />
</set>
</option>
<option name="resolveExternalAnnotations" value="false" />
</GradleProjectSettings>
</option>
</component>
</project>

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="KotlinJpsPluginSettings">
<option name="version" value="1.9.22" />
</component>
</project>

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectMigrations">
<option name="MigrateToGradleLocalJavaHome">
<set>
<option value="$PROJECT_DIR$" />
</set>
</option>
</component>
</project>

View File

@ -0,0 +1,9 @@
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="jbr-17" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/build/classes" />
</component>
<component name="ProjectType">
<option name="id" value="Android" />
</component>
</project>

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/../.." vcs="Git" />
</component>
</project>

View File

@ -0,0 +1,106 @@
# RTCPlayer 播放器
一个基于Android客户端的的RTC播放器
## 项目特点
- :white_check_mark:低延迟(200~500ms)
- :white_check_mark:支持[ZLMediakit](https://github.com/ZLMediaKit/ZLMediaKit)流媒体
- :black_square_button:支持[SRS](https://github.com/ossrs/srs)
- :black_square_button:支持[Janus](https://github.com/meetecho/janus-gateway)
如果您需要支持SRS或者Janus请寻找下方联系我
<p align="center">
<img src="doc/home.jpg" width="240"/>&nbsp;&nbsp;&nbsp;
<img src="doc/player.jpg" width="240"/>&nbsp;&nbsp;&nbsp;
<img src="doc/pusher.jpg" width="240"/>
</p>
## 延迟情况
- **网页端推流Android端播放**
<p align="center">
<img src="doc/delay_play1.jpg" width="240"/>&nbsp;&nbsp;&nbsp;
<img src="doc/delay_play2.jpg" width="240"/>&nbsp;&nbsp;&nbsp;
<img src="doc/delay_play3.jpg" width="240"/>
</p>
三次延迟分别为490ms、526ms、560ms
- **Android端推屏幕流网页端播放**
<p align="center">
<img src="doc/delay_push1.jpg" width="240"/>&nbsp;&nbsp;&nbsp;
<img src="doc/delay_push2.jpg" width="240"/>&nbsp;&nbsp;&nbsp;
<img src="doc/delay_push3.jpg" width="240"/>
</p>
三次延迟分别为440ms、430ms、387ms
## 接口说明
### Player
- bind(surface: RTCSurfaceView)
绑定视图
- play(app: String, streamId: String)
播放
- setVolume(volume:Float)
设置音量,范围: 0.0~1.0f
- stop()
停止播放
- pause()
暂停播放
- resume()
恢复播放
- capture(listener: (bitmap: Bitmap) -> Unit)
截图
- record(duration: Long, result: (path: String) -> Unit)
录制
- setOnErrorListener(listener: (code: Int, msg: String) -> Unit)
设置播放器错误监听回调
- setOnStatusListener(listener: (status: Status) -> Unit)
设置播放器状态回调
### Pusher
- bind(surface: RTCSurfaceView, localPreview: Boolean)
绑定视图
- push(app: String, streamId: String, mode: PushMode = PushMode.CAMERA, inputFile: String = "")
推流支持Camera、Screen、File
- stop()
停止推流
- setOnErrorListener(listener: (code: Int, msg: String) -> Unit)
设置播放器错误监听回调
## 联系作者
如果您需要深度二次开发,深度优化延迟,并支持其他流媒体服务,可以找我哦!
[李之阳](https://github.com/leo94666)
## 特别感谢
感谢[ZLMediakit](https://github.com/ZLMediaKit/ZLMediaKit)开源项目
同时感谢JetBrains对开源项目的支持本项目使用Android Studio开发与调试
[![Android Studio](https://th.bing.com/th?id=ODLS.d2ea10a5-5792-4f82-bd13-1595fd9d969c&w=32&h=32&qlt=90&pcl=fffffa&o=6&pid=1.2)](https://developer.android.com/studio?hl=zh-cn)

Binary file not shown.

View File

@ -1,2 +1 @@
/build
.cxx
/build

View File

@ -1,54 +0,0 @@
plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
id 'kotlin-android-extensions'
id 'kotlin-kapt'
}
apply plugin: 'kotlin-android'
android {
compileSdk 32
defaultConfig {
applicationId "com.zlmediakit.webrtc"
minSdk 21
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
}
dependencies {
implementation 'androidx.core:core-ktx:1.7.0'
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.6.1'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
implementation 'com.google.code.gson:gson:2.8.9'
implementation("com.squareup.okhttp3:okhttp:4.10.0")
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'org.webrtc:google-webrtc:1.0.32006'
}

View File

@ -0,0 +1,58 @@
plugins {
id("com.android.application")
id("org.jetbrains.kotlin.android")
}
android {
namespace = "com.top.player"
compileSdk = 34
defaultConfig {
applicationId = "com.top.player"
minSdk = 24
targetSdk = 34
versionCode = 1
versionName = "1.0"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = "1.8"
}
viewBinding {
enable = true
}
}
dependencies {
implementation("androidx.appcompat:appcompat:1.5.1")
implementation("com.google.android.material:material:1.6.1")
implementation("androidx.constraintlayout:constraintlayout:2.1.4")
testImplementation("junit:junit:4.13.2")
androidTestImplementation("androidx.test.ext:junit:1.1.3")
androidTestImplementation("androidx.test.espresso:espresso-core:3.4.0")
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.8.22")
implementation("com.guolindev.permissionx:permissionx:1.7.1")
//implementation(project(":RTCPlayer"))
implementation("com.rtc.core:RTCPlayer:1.0.0.beta")
}

View File

@ -0,0 +1,26 @@
package com.top.player;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.top.player", appContext.getPackageName());
}
}

View File

@ -1,24 +0,0 @@
package com.zlmediakit.webrtc
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.zlmediakit.webrtc", appContext.packageName)
}
}

View File

@ -1,24 +1,27 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.zlmediakit.webrtc">
xmlns:tools="http://schemas.android.com/tools">
<uses-feature android:name="android.hardware.camera"/>
<uses-feature android:name="android.hardware.camera.autofocus"/>
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
android:required="true" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CAPTURE_VIDEO_OUTPUT" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PROJECTION" />
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CAPTURE_VIDEO_OUTPUT"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
@ -27,11 +30,12 @@
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.AndroidWebRTC"
android:theme="@style/Theme.RTCPlayer"
tools:targetApi="31"
android:usesCleartextTraffic="true"
tools:targetApi="31">
android:hardwareAccelerated="true"
tools:overrideLibrary="com.rtc.core"
android:name=".App">
<activity
android:name=".MainActivity"
android:exported="true">
@ -41,6 +45,13 @@
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".PlayerDemoActivity"
android:screenOrientation="portrait" />
<activity
android:name=".PusherDemoActivity"
android:screenOrientation="portrait" />
</application>
</manifest>

View File

@ -0,0 +1,11 @@
package com.top.player
import android.app.Application
class App: Application() {
override fun onCreate() {
super.onCreate()
}
}

View File

@ -0,0 +1,25 @@
package com.top.player
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun toPlayActivity(view: View) {
startActivity(Intent(this, PlayerDemoActivity::class.java))
}
fun toPushActivity(view: View) {
startActivity(Intent(this, PusherDemoActivity::class.java))
}
}

View File

@ -0,0 +1,112 @@
package com.top.player
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.rtc.core.ZLMRTCPlayer
import com.rtc.core.play.Status
import com.rtc.core.play.ZLMRTCPlayerImpl
import com.top.player.databinding.ActivityPlayerBinding
class PlayerDemoActivity : AppCompatActivity() {
private val player: ZLMRTCPlayer by lazy {
ZLMRTCPlayerImpl(this)
}
private val binding by lazy {
ActivityPlayerBinding.inflate(layoutInflater)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
//ffmpeg -re -stream_loop -1 -i "D:\li\hot\data\data\baseline.mp4" -vcodec h264 -acodec aac -f rtsp -rtsp_transport tcp -bf 0 rtsp://zlmediakit.com/live/li
//ffmpeg -re -stream_loop -1 -i "D:\li\hot\data\data\test.mp4" -vcodec h264 -acodec aac -f flv -bf 0 rtmp://zlmediakit.com/live/li
setTitle("Player Demo")
player.bind(binding.surfaceViewRender)
player.setOnErrorListener { code, msg ->
Toast.makeText(this, "code:$code,msg:${msg}", Toast.LENGTH_SHORT).show()
}
player.setOnStatusListener {
when (it) {
Status.PREPARING -> {
binding.tvStatus.text = "准备播放"
}
Status.PLAYING -> {
binding.tvStatus.text = "播放中.."
}
Status.PAUSE -> {
binding.tvStatus.text = "暂停中.."
}
Status.RESUME -> {
binding.tvStatus.text = "播放中.."
}
Status.STOP -> {
binding.tvStatus.text = ""
}
Status.ERROR -> {
binding.tvStatus.text = "播放异常"
}
else -> {}
}
}
}
override fun onDestroy() {
super.onDestroy()
player.stop()
}
fun onPlayClick(view: View) {
player.play(binding.tvApp.text.toString(), binding.tvStreamId.text.toString())
}
fun onPauseClick(view: View) {
player.pause()
//Toast.makeText(this, "ok", Toast.LENGTH_SHORT).show()
}
fun onStopClick(view: View) {
player.stop()
}
fun onResumeClick(view: View) {
player.resume()
}
fun onCapture(view: View) {
player.capture {
Toast.makeText(this, "capture ok", Toast.LENGTH_SHORT).show()
}
}
fun onRecord(view: View) {
player.record(10 * 1000) {
Toast.makeText(this, "" + it, Toast.LENGTH_SHORT).show()
}
}
fun onVolume(view: View) {
player.setVolume(0.0f)
}
}

View File

@ -0,0 +1,97 @@
package com.top.player
import android.Manifest
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.permissionx.guolindev.PermissionX
import com.rtc.core.RTCSurfaceView
import com.rtc.core.ZLMRTCPusher
import com.rtc.core.push.PushMode
import com.rtc.core.push.ZLMRTCPusherImpl
import com.top.player.databinding.ActivityPlayerBinding
import com.top.player.databinding.ActivityPusherBinding
class PusherDemoActivity : AppCompatActivity() {
private val pusher: ZLMRTCPusher by lazy {
ZLMRTCPusherImpl(this)
}
private val binding by lazy {
ActivityPusherBinding.inflate(layoutInflater)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_pusher)
val rtcSurfaceView = findViewById<RTCSurfaceView>(R.id.surface_view_render)
pusher.bind(rtcSurfaceView, true)
setTitle("Pusher Demo")
pusher.setOnErrorListener { code, msg ->
Toast.makeText(this, "code:${code},msg:${msg}", Toast.LENGTH_SHORT).show()
}
}
fun onPushCamera(view: View) {
PermissionX.init(this)
.permissions(Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO)
.request { allGranted, grantedList, deniedList ->
if (allGranted) {
pusher.push(binding.tvApp.text.toString(), binding.tvStreamId.text.toString())
}
}
}
fun onPushScreen(view: View) {
PermissionX.init(this)
.permissions(Manifest.permission.RECORD_AUDIO)
.request { allGranted, grantedList, deniedList ->
if (allGranted) {
pusher.push(
binding.tvApp.text.toString(),
binding.tvStreamId.text.toString(),
PushMode.SCREEN
)
}
}
}
fun onPushFile(view: View) {
PermissionX.init(this)
.permissions(Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE)
.request { allGranted, grantedList, deniedList ->
if (allGranted) {
pusher.push(
binding.tvApp.text.toString(),
binding.tvStreamId.text.toString(),
PushMode.FILE,
""
)
}
}
}
override fun onDestroy() {
super.onDestroy()
pusher.stop()
}
fun onStopPush(view: View) {
pusher.stop()
}
}

View File

@ -1,79 +0,0 @@
package com.zlmediakit.webrtc
import android.annotation.SuppressLint
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.activity_main.view.*
class MainActivity : AppCompatActivity() {
private var isSpeaker = true
@SuppressLint("SetTextI18n")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
lifecycle.addObserver(web_rtc_sv)
//http://124.223.98.45/index/api/webrtc?app=live&stream=test&type=play
url.setText("http://124.223.98.45/index/api/webrtc?app=live&stream=test&type=play")
//http://192.168.1.17/index/api/webrtc?app=live&stream=test&type=play
btn_play.setOnClickListener {
web_rtc_sv?.setVideoPath(url.text.toString())
web_rtc_sv.start()
}
web_rtc_sv.setOnErrorListener { errorCode, errorMsg ->
runOnUiThread {
Toast.makeText(this, "errorCode:$errorCode,errorMsg:$errorMsg", Toast.LENGTH_SHORT)
.show()
}
}
btn_pause.setOnClickListener {
web_rtc_sv?.pause()
}
btn_resume.setOnClickListener {
web_rtc_sv?.resume()
}
btn_screenshot.setOnClickListener {
web_rtc_sv?.screenshot {
runOnUiThread {
iv_screen.setImageDrawable(BitmapDrawable(it))
}
}
}
btn_mute.setOnClickListener {
web_rtc_sv.mute(true)
}
selectAudio()
btn_speaker.setOnClickListener {
selectAudio()
}
}
fun selectAudio(){
if (isSpeaker){
btn_speaker.setText("扬声器")
web_rtc_sv.setSpeakerphoneOn(isSpeaker)
}else{
btn_speaker.setText("话筒")
web_rtc_sv.setSpeakerphoneOn(isSpeaker)
}
isSpeaker=!isSpeaker
}
}

View File

@ -1,439 +0,0 @@
package com.zlmediakit.webrtc
import android.content.Context
import android.graphics.Bitmap
import android.media.AudioManager
import android.util.AttributeSet
import android.util.Log
import android.view.LayoutInflater
import android.widget.RelativeLayout
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import com.google.gson.Gson
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import org.webrtc.*
import org.webrtc.RendererCommon.ScalingType
import org.webrtc.audio.AudioDeviceModule
import org.webrtc.audio.JavaAudioDeviceModule
import java.io.IOException
import java.util.*
public class WebRTCSurfaceView(context: Context, attrs: AttributeSet?) :
RelativeLayout(context, attrs), DefaultLifecycleObserver, RendererCommon.RendererEvents {
private data class sdp(var sdp: String, var username: String, var password: String)
private data class SdpResponse(var code: Int, var id: String, var sdp: String, var type: String)
private enum class ErrorCode(val errorCode: Int) {
SUCCESS(0x00),
GET_REMOTE_SDP_ERROR(0x01);
}
companion object {
private val TAG = "WebRTCSurfaceView"
}
private var mContext: Context = context
private val eglBase: EglBase = EglBase.create()
private var mEGLBaseContext: EglBase.Context = eglBase.eglBaseContext
private lateinit var videoUrl: String;
private var mPeerConnectionFactory: PeerConnectionFactory? = null
private var mLocalMediaStream: MediaStream? = null
private var mLocalAudioTrack: AudioTrack? = null
private var mAudioSource: AudioSource? = null
private var mLocalSessionDescription: SessionDescription? = null
private var mRemoteSessionDescription: SessionDescription? = null
private var mLocalPeer: Peer? = null
private var mSurfaceViewRenderer: SurfaceViewRenderer
private lateinit var OnErrorListener: (errorCode: Int, errorMsg: String) -> Unit?
fun setOnErrorListener(listener: (errorCode: Int, errorMsg: String) -> Unit) {
this.OnErrorListener = listener
}
private lateinit var OnPreparedListener: () -> Unit?
fun setOnPreparedListener(listener: () -> Unit) {
this.OnPreparedListener = listener
}
private val audioManager: AudioManager
init {
val view = LayoutInflater.from(mContext).inflate(R.layout.layout_videoview, this)
mPeerConnectionFactory = createConnectionFactory()
mSurfaceViewRenderer = view.findViewById(R.id.surface_view_renderer)
mSurfaceViewRenderer.init(mEGLBaseContext, this)
mSurfaceViewRenderer.setScalingType(ScalingType.SCALE_ASPECT_FILL)
mSurfaceViewRenderer.setEnableHardwareScaler(true)
//创建媒体流
mLocalMediaStream = mPeerConnectionFactory?.createLocalMediaStream("ARDAMS")
//采集音频
mAudioSource = mPeerConnectionFactory?.createAudioSource(createAudioConstraints())
mLocalAudioTrack = mPeerConnectionFactory?.createAudioTrack("ARDAMSa0", mAudioSource)
//添加Tracks
mLocalMediaStream?.addTrack(mLocalAudioTrack)
audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
audioManager.isSpeakerphoneOn = false
}
private fun set(width: Int, height: Int) {
layoutParams.width = width
layoutParams.height = height
}
private fun createConnectionFactory(): PeerConnectionFactory? {
val options = PeerConnectionFactory.InitializationOptions.builder(mContext)
.setEnableInternalTracer(false)
.createInitializationOptions()
PeerConnectionFactory.initialize(options)
val videoEncoderFactory = DefaultVideoEncoderFactory(
mEGLBaseContext,
true,
true
)
val videoDecoderFactory = DefaultVideoDecoderFactory(mEGLBaseContext)
val audioDevice = createJavaAudioDevice()
val peerConnectionFactory = PeerConnectionFactory.builder()
.setAudioDeviceModule(audioDevice)
.setVideoEncoderFactory(videoEncoderFactory)
.setVideoDecoderFactory(videoDecoderFactory)
.createPeerConnectionFactory()
audioDevice.release()
return peerConnectionFactory
}
private fun createAudioConstraints(): MediaConstraints {
val audioConstraints = MediaConstraints()
audioConstraints.mandatory.add(
MediaConstraints.KeyValuePair(
"googEchoCancellation",
"true"
)
)
audioConstraints.mandatory.add(
MediaConstraints.KeyValuePair(
"googAutoGainControl",
"false"
)
)
audioConstraints.mandatory.add(
MediaConstraints.KeyValuePair(
"googHighpassFilter",
"true"
)
)
audioConstraints.mandatory.add(
MediaConstraints.KeyValuePair(
"googNoiseSuppression",
"true"
)
)
return audioConstraints
}
private fun offerOrAnswerConstraint(): MediaConstraints {
val mediaConstraints = MediaConstraints()
val keyValuePairs = java.util.ArrayList<MediaConstraints.KeyValuePair>()
keyValuePairs.add(MediaConstraints.KeyValuePair("OfferToReceiveAudio", "true"))
keyValuePairs.add(MediaConstraints.KeyValuePair("OfferToReceiveVideo", "true"))
mediaConstraints.mandatory.addAll(keyValuePairs)
return mediaConstraints
}
private fun createJavaAudioDevice(): AudioDeviceModule {
val audioTrackErrorCallback: JavaAudioDeviceModule.AudioTrackErrorCallback = object :
JavaAudioDeviceModule.AudioTrackErrorCallback {
override fun onWebRtcAudioTrackInitError(errorMessage: String) {
Log.i(TAG, "onWebRtcAudioTrackInitError ============> $errorMessage")
}
override fun onWebRtcAudioTrackStartError(
errorCode: JavaAudioDeviceModule.AudioTrackStartErrorCode, errorMessage: String
) {
Log.i(TAG, "onWebRtcAudioTrackStartError ============> $errorCode:$errorMessage")
}
override fun onWebRtcAudioTrackError(errorMessage: String) {
Log.i(TAG, "onWebRtcAudioTrackError ============> $errorMessage")
}
}
// Set audio track state callbacks.
val audioTrackStateCallback: JavaAudioDeviceModule.AudioTrackStateCallback = object :
JavaAudioDeviceModule.AudioTrackStateCallback {
override fun onWebRtcAudioTrackStart() {
Log.i(TAG, "onWebRtcAudioTrackStart ============>")
}
override fun onWebRtcAudioTrackStop() {
Log.i(TAG, "onWebRtcAudioTrackStop ============>")
}
}
return JavaAudioDeviceModule.builder(mContext)
.setUseHardwareAcousticEchoCanceler(true)
.setUseHardwareNoiseSuppressor(true)
.setAudioTrackErrorCallback(audioTrackErrorCallback)
.setAudioTrackStateCallback(audioTrackStateCallback)
.setUseStereoOutput(true) //立体声
.createAudioDeviceModule()
}
fun setVideoPath(url: String) {
videoUrl = url
}
fun start() {
mLocalPeer = Peer {
val okHttpClient = OkHttpClient.Builder().build()
val body = RequestBody.create("text/plain; charset=utf-8".toMediaType(), it!!)
val request: Request = Request.Builder()
.url(videoUrl)
.post(body)
.build()
val call: Call = okHttpClient.newCall(request)
call.enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
Log.i(TAG, "onFailure")
OnErrorListener?.invoke(
ErrorCode.GET_REMOTE_SDP_ERROR.errorCode,
e.message.toString()
)
}
override fun onResponse(call: Call, response: Response) {
val body = response.body?.string()
val sdpResponse = Gson().fromJson(body, SdpResponse::class.java)
try {
mRemoteSessionDescription = SessionDescription(
SessionDescription.Type.fromCanonicalForm("answer"),
sdpResponse.sdp
)
Log.i(
TAG,
"RemoteSdpObserver onCreateSuccess:[SessionDescription[type=${mRemoteSessionDescription?.type?.name},description=${mRemoteSessionDescription?.description}]]"
)
mLocalPeer?.setRemoteDescription(mRemoteSessionDescription!!)
} catch (e: Exception) {
Log.i(TAG, e.toString())
OnErrorListener.invoke(
ErrorCode.GET_REMOTE_SDP_ERROR.errorCode,
e.localizedMessage
)
}
}
})
}
}
fun pause() {
mSurfaceViewRenderer.pauseVideo()
//mSurfaceViewRenderer.disableFpsReduction()
}
fun resume() {
mSurfaceViewRenderer.setFpsReduction(15f)
}
fun screenshot(listener: (bitmap: Bitmap) -> Unit) {
mSurfaceViewRenderer.addFrameListener({
listener.invoke(it)
}, 1f)
}
fun setSpeakerphoneOn(on: Boolean) {
audioManager.isSpeakerphoneOn = on
}
fun mute(on:Boolean) {
audioManager.isMicrophoneMute=on
}
override fun onDestroy(owner: LifecycleOwner) {
super.onDestroy(owner)
mSurfaceViewRenderer.release()
mLocalPeer?.mPeerConnection?.dispose()
mAudioSource?.dispose()
mPeerConnectionFactory?.dispose()
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
}
inner class Peer(var sdp: (String?) -> Unit = {}) : PeerConnection.Observer, SdpObserver {
var mPeerConnection: PeerConnection? = null
init {
mPeerConnection = createPeerConnection()
mPeerConnection?.createOffer(this, offerOrAnswerConstraint())
}
//初始化 RTCPeerConnection 连接管道
private fun createPeerConnection(): PeerConnection? {
if (mPeerConnectionFactory == null) {
mPeerConnectionFactory = createConnectionFactory()
}
// 管道连接抽象类实现方法
val ICEServers = LinkedList<PeerConnection.IceServer>()
val rtcConfig = PeerConnection.RTCConfiguration(ICEServers)
//修改模式 PlanB无法使用仅接收音视频的配置
//rtcConfig.sdpSemantics = PeerConnection.SdpSemantics.PLAN_B
return mPeerConnectionFactory?.createPeerConnection(rtcConfig, this)
}
fun setRemoteDescription(sdp: SessionDescription) {
mPeerConnection?.setRemoteDescription(this, sdp)
}
override fun onCreateSuccess(sessionDescription: SessionDescription?) {
mPeerConnection?.setLocalDescription(this, sessionDescription)
mPeerConnection?.addStream(mLocalMediaStream)
sdp.invoke(sessionDescription?.description)
}
override fun onSetSuccess() {
}
override fun onCreateFailure(p0: String?) {
}
override fun onSetFailure(p0: String?) {
}
override fun onSignalingChange(signalingState: PeerConnection.SignalingState?) {
Log.i(TAG, "onSignalingChange ============> " + signalingState.toString())
}
override fun onIceConnectionChange(iceConnectionState: PeerConnection.IceConnectionState?) {
Log.i(TAG, "onIceConnectionChange ============> " + iceConnectionState.toString())
}
override fun onIceConnectionReceivingChange(p0: Boolean) {
Log.i(TAG, "onIceConnectionReceivingChange ============> $p0")
}
override fun onIceGatheringChange(iceGatheringState: PeerConnection.IceGatheringState?) {
Log.i(TAG, "onIceGatheringChange ============> ${iceGatheringState.toString()}")
}
override fun onIceCandidate(iceCandidate: IceCandidate?) {
Log.i(TAG, "onIceCandidate ============> ${iceCandidate.toString()}")
}
override fun onIceCandidatesRemoved(p0: Array<out IceCandidate>?) {
Log.i(TAG, "onIceCandidatesRemoved ============> ${p0.toString()}")
}
override fun onAddStream(mediaStream: MediaStream?) {
Log.i(TAG, "onAddStream ============> ${mediaStream?.toString()}")
if (mediaStream?.videoTracks?.isEmpty() != true) {
val remoteVideoTrack = mediaStream?.videoTracks?.get(0)
remoteVideoTrack?.setEnabled(true)
remoteVideoTrack?.addSink(mSurfaceViewRenderer)
}
if (mediaStream?.audioTracks?.isEmpty() != true) {
val remoteAudioTrack = mediaStream?.audioTracks?.get(0)
remoteAudioTrack?.setEnabled(true)
remoteAudioTrack?.setVolume(1.0)
}
}
override fun onRemoveStream(mediaStream: MediaStream?) {
Log.i(TAG, "onRemoveStream ============> ${mediaStream.toString()}")
}
override fun onDataChannel(dataChannel: DataChannel?) {
Log.i(TAG, "onDataChannel ============> ${dataChannel.toString()}")
}
override fun onRenegotiationNeeded() {
Log.i(TAG, "onRenegotiationNeeded ============>")
}
override fun onAddTrack(rtpReceiver: RtpReceiver?, p1: Array<out MediaStream>?) {
Log.i(TAG, "onAddTrack ============>" + rtpReceiver?.track())
Log.i(TAG, "onAddTrack ============>" + p1?.size)
}
}
override fun onFirstFrameRendered() {
Log.i(TAG, "onFirstFrameRendered ============>")
}
override fun onFrameResolutionChanged(frameWidth: Int, frameHeight: Int, rotation: Int) {
Log.i(TAG, "onFrameResolutionChanged ============> $frameWidth:$frameHeight:$rotation")
//set(frameWidth,frameHeight)
}
}

View File

@ -1,93 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
<androidx.appcompat.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
android:orientation="vertical">
<com.zlmediakit.webrtc.WebRTCSurfaceView
android:id="@+id/web_rtc_sv"
android:layout_width="match_parent"
android:layout_height="200dp"
app:layout_constraintTop_toTopOf="parent" />
<androidx.appcompat.widget.AppCompatEditText
android:id="@+id/url"
<androidx.appcompat.widget.AppCompatButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@+id/web_rtc_sv"
android:text=""/>
<LinearLayout
android:id="@+id/ll"
android:onClick="toPlayActivity"
android:text="播放" />
<androidx.appcompat.widget.AppCompatButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="30dp"
app:layout_constraintTop_toBottomOf="@+id/url">
<androidx.appcompat.widget.AppCompatButton
android:id="@+id/btn_play"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="播放" />
<androidx.appcompat.widget.AppCompatButton
android:id="@+id/btn_pause"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="暂停" />
<androidx.appcompat.widget.AppCompatButton
android:id="@+id/btn_resume"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="恢复" />
<androidx.appcompat.widget.AppCompatButton
android:id="@+id/btn_speaker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="扬声器" />
<androidx.appcompat.widget.AppCompatButton
android:id="@+id/btn_mute"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="静音" />
</LinearLayout>
<LinearLayout
android:id="@+id/ll2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="10dp"
app:layout_constraintTop_toBottomOf="@+id/ll">
android:onClick="toPushActivity"
android:text="推流" />
<androidx.appcompat.widget.AppCompatButton
android:id="@+id/btn_screenshot"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="截图" />
<androidx.appcompat.widget.AppCompatButton
android:id="@+id/btn_screen_record"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="录制" />
</LinearLayout>
<androidx.appcompat.widget.AppCompatImageView
android:id="@+id/iv_screen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.appcompat.widget.LinearLayoutCompat>

View File

@ -0,0 +1,140 @@
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.rtc.core.RTCSurfaceView
android:id="@+id/surface_view_render"
android:layout_width="match_parent"
android:layout_height="240dp" />
<androidx.appcompat.widget.AppCompatTextView
android:id="@+id/tv_status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textSize="12sp"
android:textColor="@android:color/holo_red_light"
android:layout_alignParentRight="true"
android:layout_margin="6dp"
android:background="@color/black"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/surface_view_render"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.appcompat.widget.AppCompatTextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:gravity="end"
android:text="app: " />
<androidx.appcompat.widget.AppCompatEditText
android:id="@+id/tv_app"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="4"
android:text="live"
android:gravity="center"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/surface_view_render">
<androidx.appcompat.widget.AppCompatTextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:gravity="end"
android:text="streamId:" />
<androidx.appcompat.widget.AppCompatEditText
android:id="@+id/tv_stream_id"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="4"
android:text="test"
android:gravity="center"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.appcompat.widget.AppCompatButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="play"
android:onClick="onPlayClick"
android:textAllCaps="false" />
<androidx.appcompat.widget.AppCompatButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="pause"
android:onClick="onPauseClick"
android:textAllCaps="false" />
<androidx.appcompat.widget.AppCompatButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="resume"
android:onClick="onResumeClick"
android:textAllCaps="false" />
<androidx.appcompat.widget.AppCompatButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="stop"
android:onClick="onStopClick"
android:textAllCaps="false" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.appcompat.widget.AppCompatButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="volume"
android:onClick="onVolume"
android:textAllCaps="false" />
<androidx.appcompat.widget.AppCompatButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="capture"
android:onClick="onCapture"
android:textAllCaps="false" />
<androidx.appcompat.widget.AppCompatButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="record"
android:onClick="onRecord"
android:textAllCaps="false" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>

View File

@ -0,0 +1,95 @@
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<com.rtc.core.RTCSurfaceView
android:id="@+id/surface_view_render"
android:layout_width="match_parent"
android:layout_height="240dp" />
<androidx.appcompat.widget.LinearLayoutCompat
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_below="@id/surface_view_render"
app:layout_constraintTop_toBottomOf="@id/surface_view_render">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.appcompat.widget.AppCompatTextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:gravity="end"
android:text="app: " />
<androidx.appcompat.widget.AppCompatEditText
android:id="@+id/tv_app"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="4"
android:text="live"
android:gravity="center"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/surface_view_render">
<androidx.appcompat.widget.AppCompatTextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:gravity="end"
android:text="streamId:" />
<androidx.appcompat.widget.AppCompatEditText
android:id="@+id/tv_stream_id"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="4"
android:text="test"
android:gravity="center"/>
</LinearLayout>
<androidx.appcompat.widget.AppCompatButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Push Camera"
android:textAllCaps="false"
android:onClick="onPushCamera"/>
<androidx.appcompat.widget.AppCompatButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Push Screen"
android:textAllCaps="false"
android:onClick="onPushScreen"/>
<androidx.appcompat.widget.AppCompatButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Push File"
android:textAllCaps="false"
android:onClick="onPushFile"/>
<androidx.appcompat.widget.AppCompatButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Stop Push"
android:textAllCaps="false"
android:onClick="onStopPush"/>
</androidx.appcompat.widget.LinearLayoutCompat>
</RelativeLayout>

View File

@ -1,13 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<org.webrtc.SurfaceViewRenderer
android:id="@+id/surface_view_renderer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>

View File

@ -2,4 +2,5 @@
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
<monochrome android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>

View File

@ -2,4 +2,5 @@
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
<monochrome android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>

View File

@ -1,16 +1,7 @@
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.AndroidWebRTC" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
<!-- Primary brand color. -->
<item name="colorPrimary">@color/purple_200</item>
<item name="colorPrimaryVariant">@color/purple_700</item>
<item name="colorOnPrimary">@color/black</item>
<!-- Secondary brand color. -->
<item name="colorSecondary">@color/teal_200</item>
<item name="colorSecondaryVariant">@color/teal_200</item>
<item name="colorOnSecondary">@color/black</item>
<!-- Status bar color. -->
<item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
<!-- Customize your theme here. -->
<style name="Base.Theme.RTCPlayer" parent="Theme.Material3.DayNight.NoActionBar">
<!-- Customize your dark theme here. -->
<!-- <item name="colorPrimary">@color/my_dark_primary</item> -->
</style>
</resources>

View File

@ -1,10 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="purple_200">#FFBB86FC</color>
<color name="purple_500">#FF6200EE</color>
<color name="purple_700">#FF3700B3</color>
<color name="teal_200">#FF03DAC5</color>
<color name="teal_700">#FF018786</color>
<color name="black">#FF000000</color>
<color name="white">#FFFFFFFF</color>
</resources>

View File

@ -1,3 +1,3 @@
<resources>
<string name="app_name">AndroidWebRTC</string>
<string name="app_name">RTCPlayer</string>
</resources>

View File

@ -1,16 +1,9 @@
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.AndroidWebRTC" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
<!-- Primary brand color. -->
<item name="colorPrimary">@color/purple_500</item>
<item name="colorPrimaryVariant">@color/purple_700</item>
<item name="colorOnPrimary">@color/white</item>
<!-- Secondary brand color. -->
<item name="colorSecondary">@color/teal_200</item>
<item name="colorSecondaryVariant">@color/teal_700</item>
<item name="colorOnSecondary">@color/black</item>
<!-- Status bar color. -->
<item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
<!-- Customize your theme here. -->
<style name="Base.Theme.RTCPlayer" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
<!-- Customize your light theme here. -->
<!-- <item name="colorPrimary">@color/my_light_primary</item> -->
</style>
<style name="Theme.RTCPlayer" parent="Base.Theme.RTCPlayer" />
</resources>

View File

@ -0,0 +1,17 @@
package com.top.player;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
}

View File

@ -1,17 +0,0 @@
package com.zlmediakit.webrtc
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}

View File

@ -1,19 +0,0 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = '1.7.10'
repositories {
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
plugins {
id 'com.android.application' version '7.2.1' apply false
id 'com.android.library' version '7.2.1' apply false
id 'org.jetbrains.kotlin.android' version '1.7.10' apply false
}
task clean(type: Delete) {
delete rootProject.buildDir
}

View File

@ -0,0 +1,6 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
id("com.android.application") version "8.2.2" apply false
id("com.android.library") version "8.2.2" apply false
id("org.jetbrains.kotlin.android") version "1.9.22" apply false
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.7 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 140 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 154 KiB

View File

@ -12,11 +12,9 @@ org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app"s APK
# Android operating system, and which are packaged with your app's APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
# Kotlin code style for this project: "official" or "obsolete":
kotlin.code.style=official
# Enables namespacing of each library's R class so that its R class includes only the
# resources declared in the library itself and none from the library's dependencies,
# thereby reducing the size of the R class for that library

View File

@ -1,6 +1,6 @@
#Mon Sep 19 22:08:36 CST 2022
#Fri May 31 15:05:44 CST 2024
distributionBase=GRADLE_USER_HOME
distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-bin.zip
distributionPath=wrapper/dists
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.2-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

Binary file not shown.

Before

Width:  |  Height:  |  Size: 635 KiB

View File

@ -1,24 +0,0 @@
pluginManagement {
repositories {
gradlePluginPortal()
google()
mavenCentral()
jcenter() // Warning: this repository is going to shut down soon
maven { url 'https://jitpack.io' }
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
jcenter() // Warning: this repository is going to shut down soon
maven { url 'https://jitpack.io' }
}
}
rootProject.name = "android"
include ':app'

View File

@ -0,0 +1,25 @@
pluginManagement {
repositories {
mavenCentral()
gradlePluginPortal()
google()
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
mavenCentral()
google()
maven {
credentials {
username = ("6256cd6c7e8dbc28d896a661")
password = ("KRuEgA3WYUVy")
}
url = uri("https://packages.aliyun.com/maven/repository/2302596-release-mpvXBR/")
}
}
}
rootProject.name = "RTCPlayer"
include(":app")
//include(":RTCPlayer")