Update to 4896 (M100) (#72)

This commit is contained in:
Peter Thatcher 2022-04-15 17:13:23 -06:00 committed by GitHub
parent 9fa95682c0
commit 4a2e0e5d45
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2110 changed files with 77529 additions and 40474 deletions

4
.gn
View file

@ -63,4 +63,8 @@ default_args = {
enable_libaom = false enable_libaom = false
gtest_enable_absl_printers = true gtest_enable_absl_printers = true
# RingRTC change to support SDK >= 19.
# Differently from Chromium, WebRTC still support SDK 19.
default_min_sdk_version = 19
} }

1
.mailmap Normal file
View file

@ -0,0 +1 @@
Tommi <tommi@webrtc.org> Tomas Gunnarsson <tommi@webrtc.org>

4
.style.yapf Normal file
View file

@ -0,0 +1,4 @@
[style]
based_on_style = pep8
indent_width = 2
column_limit = 80

82
.vpython3 Normal file
View file

@ -0,0 +1,82 @@
# This is a vpython "spec" file.
#
# It describes patterns for python wheel dependencies of the python scripts in
# the chromium repo, particularly for dependencies that have compiled components
# (since pure-python dependencies can be easily vendored into third_party).
#
# When vpython is invoked, it finds this file and builds a python VirtualEnv,
# containing all of the dependencies described in this file, fetching them from
# CIPD (the "Chrome Infrastructure Package Deployer" service). Unlike `pip`,
# this never requires the end-user machine to have a working python extension
# compilation environment. All of these packages are built using:
# https://chromium.googlesource.com/infra/infra/+/main/infra/tools/dockerbuild/
#
# All python scripts in the repo share this same spec, to avoid dependency
# fragmentation.
#
# If you have depot_tools installed in your $PATH, you can invoke python scripts
# in this repo by running them as you normally would run them, except
# substituting `vpython` instead of `python` on the command line, e.g.:
# vpython path/to/script.py some --arguments
#
# Read more about `vpython` and how to modify this file here:
# https://chromium.googlesource.com/infra/infra/+/main/doc/users/vpython.md
python_version: "3.8"
# Used by:
# third_party/catapult
wheel: <
name: "infra/python/wheels/psutil/${vpython_platform}"
version: "version:5.8.0.chromium.2"
>
# Used by tools_webrtc/perf/webrtc_dashboard_upload.py.
wheel: <
name: "infra/python/wheels/httplib2-py3"
version: "version:0.19.1"
>
wheel: <
name: "infra/python/wheels/pyparsing-py2_py3"
version: "version:2.4.7"
>
# Used by:
# build/toolchain/win
wheel: <
name: "infra/python/wheels/pywin32/${vpython_platform}"
version: "version:300"
match_tag: <
platform: "win32"
>
match_tag: <
platform: "win_amd64"
>
>
wheel: <
name: "infra/python/wheels/six-py2_py3"
version: "version:1.15.0"
>
wheel: <
name: "infra/python/wheels/pbr-py2_py3"
version: "version:3.0.0"
>
wheel: <
name: "infra/python/wheels/funcsigs-py2_py3"
version: "version:1.0.2"
>
wheel: <
name: "infra/python/wheels/mock-py2_py3"
version: "version:2.0.0"
>
wheel: <
name: "infra/python/wheels/protobuf-py2_py3"
version: "version:3.13.0"
>
wheel: <
name: "infra/python/wheels/requests-py2_py3"
version: "version:2.13.0"
>

10
AUTHORS
View file

@ -58,6 +58,7 @@ Jesús Leganés-Combarro <piranna@gmail.com>
Jiawei Ou <jiawei.ou@gmail.com> Jiawei Ou <jiawei.ou@gmail.com>
Jie Mao <maojie0924@gmail.com> Jie Mao <maojie0924@gmail.com>
Jiwon Kim <jwkim0000@gmail.com> Jiwon Kim <jwkim0000@gmail.com>
Johnny Wong <hellojinqiang@gmail.com>
Jose Antonio Olivera Ortega <josea.olivera@gmail.com> Jose Antonio Olivera Ortega <josea.olivera@gmail.com>
Keiichi Enomoto <enm10k@gmail.com> Keiichi Enomoto <enm10k@gmail.com>
Kiran Thind <kiran.thind@gmail.com> Kiran Thind <kiran.thind@gmail.com>
@ -69,6 +70,7 @@ Mallikarjuna Rao V <vm.arjun@samsung.com>
Manish Jethani <manish.jethani@gmail.com> Manish Jethani <manish.jethani@gmail.com>
Martin Storsjo <martin@martin.st> Martin Storsjo <martin@martin.st>
Matthias Liebig <matthias.gcode@gmail.com> Matthias Liebig <matthias.gcode@gmail.com>
Maksim Sisov <msisov@igalia.com>
Maxim Pavlov <pavllovmax@gmail.com> Maxim Pavlov <pavllovmax@gmail.com>
Maxim Potapov <vopatop.skam@gmail.com> Maxim Potapov <vopatop.skam@gmail.com>
Michael Iedema <michael@kapsulate.com> Michael Iedema <michael@kapsulate.com>
@ -77,6 +79,8 @@ Miguel Paris <mparisdiaz@gmail.com>
Mike Gilbert <floppymaster@gmail.com> Mike Gilbert <floppymaster@gmail.com>
Min Wang <mingewang@gmail.com> Min Wang <mingewang@gmail.com>
Mo Zanaty <mzanaty@cisco.com> Mo Zanaty <mzanaty@cisco.com>
Niek van der Maas <mail@niekvandermaas.nl>
Olivier Crête <olivier.crete@ocrete.ca>
Pali Rohar Pali Rohar
Paul Kapustin <pkapustin@gmail.com> Paul Kapustin <pkapustin@gmail.com>
Peng Yu <yupeng323@gmail.com> Peng Yu <yupeng323@gmail.com>
@ -88,16 +92,19 @@ Raman Budny <budnyjj@gmail.com>
Ramprakash Jelari <ennajelari@gmail.com> Ramprakash Jelari <ennajelari@gmail.com>
Riku Voipio <riku.voipio@linaro.org> Riku Voipio <riku.voipio@linaro.org>
Robert Bares <robert@bares.me> Robert Bares <robert@bares.me>
Robert Mader <robert.mader@posteo.de>
Robert Nagy <robert.nagy@gmail.com> Robert Nagy <robert.nagy@gmail.com>
Ryan Yoakum <ryoakum@skobalt.com> Ryan Yoakum <ryoakum@skobalt.com>
Sarah Thompson <sarah@telergy.com> Sarah Thompson <sarah@telergy.com>
Satender Saroha <ssaroha@yahoo.com> Satender Saroha <ssaroha@yahoo.com>
Saul Kravitz <Saul.Kravitz@celera.com> Saul Kravitz <Saul.Kravitz@celera.com>
Sergio Garcia Murillo <sergio.garcia.murillo@gmail.com> Sergio Garcia Murillo <sergio.garcia.murillo@gmail.com>
Shuhai Peng <shuhai.peng@intel.com>
Silviu Caragea <silviu.cpp@gmail.com> Silviu Caragea <silviu.cpp@gmail.com>
Stefan Gula <steweg@gmail.com> Stefan Gula <steweg@gmail.com>
Stephan Hartmann <stha09@googlemail.com> Stephan Hartmann <stha09@googlemail.com>
Steve Reid <sreid@sea-to-sky.net> Steve Reid <sreid@sea-to-sky.net>
Takaaki Suzuki <takaakisuzuki.14@gmail.com>
Tarun Chawla <trnkumarchawla@gmail.com> Tarun Chawla <trnkumarchawla@gmail.com>
Todd Wong <todd.wong.ndq@gmail.com> Todd Wong <todd.wong.ndq@gmail.com>
Tomas Popela <tomas.popela@gmail.com> Tomas Popela <tomas.popela@gmail.com>
@ -108,6 +115,7 @@ Victor Costan <costan@gmail.com>
Vladimir Beloborodov <VladimirTechMan@gmail.com> Vladimir Beloborodov <VladimirTechMan@gmail.com>
Xiaohong Xu <freemine@yeah.net> Xiaohong Xu <freemine@yeah.net>
Xiaolei Yu <dreifachstein@gmail.com> Xiaolei Yu <dreifachstein@gmail.com>
Yaowen Guo <albertguo88@gmail.com>
Yura Yaroshevich <yura.yaroshevich@gmail.com> Yura Yaroshevich <yura.yaroshevich@gmail.com>
Yuriy Pavlyshak <yuriy@appear.in> Yuriy Pavlyshak <yuriy@appear.in>
Yusuke Suzuki <utatane.tea@gmail.com> Yusuke Suzuki <utatane.tea@gmail.com>
@ -115,6 +123,7 @@ Yusuke Suzuki <utatane.tea@gmail.com>
# BEGIN organizations section. # BEGIN organizations section.
8x8 Inc. <*@8x8.com> 8x8 Inc. <*@8x8.com>
8x8 Inc. <*@jitsi.org>
8x8 Inc. <*@sip-communicator.org> 8x8 Inc. <*@sip-communicator.org>
Agora IO <*@agora.io> Agora IO <*@agora.io>
ARM Holdings <*@arm.com> ARM Holdings <*@arm.com>
@ -130,6 +139,7 @@ Microsoft Corporation <*@microsoft.com>
MIPS Technologies <*@mips.com> MIPS Technologies <*@mips.com>
Mozilla Foundation <*@mozilla.com> Mozilla Foundation <*@mozilla.com>
Netgem S.A. <*@netgem.com> Netgem S.A. <*@netgem.com>
Nutanix Inc. <*@nutanix.com>
NVIDIA Corporation <*@nvidia.com> NVIDIA Corporation <*@nvidia.com>
Opera Software ASA <*@opera.com> Opera Software ASA <*@opera.com>
Optical Tone Ltd <*@opticaltone.com> Optical Tone Ltd <*@opticaltone.com>

View file

@ -12,6 +12,15 @@
# you add a new build file, there must be some path of dependencies from this # you add a new build file, there must be some path of dependencies from this
# file to your new one or GN won't know about it. # file to your new one or GN won't know about it.
# Use of visibility = clauses:
# The default visibility for all rtc_ targets is equivalent to "//*", or
# "all targets in webrtc can depend on this, nothing outside can".
#
# When overriding, the choices are:
# - visibility = [ "*" ] - public. Stuff outside webrtc can use this.
# - visibility = [ ":*" ] - directory private.
# As a general guideline, only targets in api/ should have public visibility.
import("//build/config/linux/pkg_config.gni") import("//build/config/linux/pkg_config.gni")
import("//build/config/sanitizers/sanitizers.gni") import("//build/config/sanitizers/sanitizers.gni")
import("//third_party/google_benchmark/buildconfig.gni") import("//third_party/google_benchmark/buildconfig.gni")
@ -39,7 +48,6 @@ if (!build_with_chromium) {
if (rtc_include_tests) { if (rtc_include_tests) {
deps += [ deps += [
":rtc_unittests", ":rtc_unittests",
":slow_tests",
":video_engine_tests", ":video_engine_tests",
":voip_unittests", ":voip_unittests",
":webrtc_nonparallel_tests", ":webrtc_nonparallel_tests",
@ -73,6 +81,13 @@ if (!build_with_chromium) {
# see bugs.webrtc.org/11027#c5. # see bugs.webrtc.org/11027#c5.
deps += [ ":webrtc_lib_link_test" ] deps += [ ":webrtc_lib_link_test" ]
} }
if (is_ios) {
deps += [
"examples:apprtcmobile_tests",
"sdk:sdk_framework_unittests",
"sdk:sdk_unittests",
]
}
if (is_android) { if (is_android) {
deps += [ deps += [
"examples:android_examples_junit_tests", "examples:android_examples_junit_tests",
@ -84,7 +99,7 @@ if (!build_with_chromium) {
} }
if (rtc_enable_protobuf) { if (rtc_enable_protobuf) {
deps += [ deps += [
"audio:low_bandwidth_audio_test", "audio:low_bandwidth_audio_perf_test",
"logging:rtc_event_log_rtp_dump", "logging:rtc_event_log_rtp_dump",
"tools_webrtc/perf:webrtc_dashboard_upload", "tools_webrtc/perf:webrtc_dashboard_upload",
] ]
@ -118,15 +133,15 @@ config("common_inherited_config") {
cflags = [] cflags = []
ldflags = [] ldflags = []
if (rtc_enable_symbol_export || is_component_build) { if (rtc_dlog_always_on) {
defines = [ "WEBRTC_ENABLE_SYMBOL_EXPORT" ] defines += [ "DLOG_ALWAYS_ON" ]
}
if (rtc_enable_objc_symbol_export) {
defines = [ "WEBRTC_ENABLE_OBJC_SYMBOL_EXPORT" ]
} }
if (build_with_mozilla) { if (rtc_enable_symbol_export || is_component_build) {
defines += [ "WEBRTC_MOZILLA_BUILD" ] defines += [ "WEBRTC_ENABLE_SYMBOL_EXPORT" ]
}
if (rtc_enable_objc_symbol_export) {
defines += [ "WEBRTC_ENABLE_OBJC_SYMBOL_EXPORT" ]
} }
if (!rtc_builtin_ssl_root_certificates) { if (!rtc_builtin_ssl_root_certificates) {
@ -222,14 +237,6 @@ config("common_inherited_config") {
} }
} }
# TODO(bugs.webrtc.org/9693): Remove the possibility to suppress this warning
# as soon as WebRTC compiles without it.
config("no_exit_time_destructors") {
if (is_clang) {
cflags = [ "-Wno-exit-time-destructors" ]
}
}
# TODO(bugs.webrtc.org/9693): Remove the possibility to suppress this warning # TODO(bugs.webrtc.org/9693): Remove the possibility to suppress this warning
# as soon as WebRTC compiles without it. # as soon as WebRTC compiles without it.
config("no_global_constructors") { config("no_global_constructors") {
@ -269,6 +276,10 @@ config("common_config") {
defines += [ "RTC_ENABLE_VP9" ] defines += [ "RTC_ENABLE_VP9" ]
} }
if (rtc_include_dav1d_in_internal_decoder_factory) {
defines += [ "RTC_DAV1D_IN_INTERNAL_DECODER_FACTORY" ]
}
if (rtc_enable_sctp) { if (rtc_enable_sctp) {
defines += [ "WEBRTC_HAVE_SCTP" ] defines += [ "WEBRTC_HAVE_SCTP" ]
} }
@ -305,7 +316,10 @@ config("common_config") {
defines += [ "WEBRTC_EXCLUDE_AUDIO_PROCESSING_MODULE" ] defines += [ "WEBRTC_EXCLUDE_AUDIO_PROCESSING_MODULE" ]
} }
cflags = [] # TODO(webrtc:13219): Fix -Wshadow instances and enable.
if (is_clang) {
cflags += [ "-Wno-shadow" ]
}
if (build_with_chromium) { if (build_with_chromium) {
defines += [ defines += [
@ -346,21 +360,10 @@ config("common_config") {
"-Wundef", "-Wundef",
] ]
# use_xcode_clang only refers to the iOS toolchain, host binaries use if (!is_nacl) {
# chromium's clang always. # Flags NaCl (Clang 3.7) do not recognize.
if (!is_nacl &&
(!use_xcode_clang || current_toolchain == host_toolchain)) {
# Flags NaCl (Clang 3.7) and Xcode 7.3 (Clang clang-703.0.31) do not
# recognize.
cflags += [ "-Wunused-lambda-capture" ] cflags += [ "-Wunused-lambda-capture" ]
} }
if (use_xcode_clang) {
# This may be removed if the clang version in xcode > 12.4 includes the
# fix https://reviews.llvm.org/D73007.
# https://bugs.llvm.org/show_bug.cgi?id=44556
cflags += [ "-Wno-range-loop-analysis" ]
}
} }
if (is_win && !is_clang) { if (is_win && !is_clang) {
@ -575,7 +578,9 @@ if (rtc_include_tests && !build_with_chromium) {
"rtc_base/experiments:experiments_unittests", "rtc_base/experiments:experiments_unittests",
"rtc_base/system:file_wrapper_unittests", "rtc_base/system:file_wrapper_unittests",
"rtc_base/task_utils:pending_task_safety_flag_unittests", "rtc_base/task_utils:pending_task_safety_flag_unittests",
"rtc_base/task_utils:repeating_task_unittests",
"rtc_base/task_utils:to_queued_task_unittests", "rtc_base/task_utils:to_queued_task_unittests",
"rtc_base/units:units_unittests",
"sdk:sdk_tests", "sdk:sdk_tests",
"test:rtp_test_utils", "test:rtp_test_utils",
"test:test_main", "test:test_main",
@ -613,17 +618,6 @@ if (rtc_include_tests && !build_with_chromium) {
} }
} }
# This runs tests that must run in real time and therefore can take some
# time to execute. They are in a separate executable to avoid making the
# regular unittest suite too slow to run frequently.
rtc_test("slow_tests") {
testonly = true
deps = [
"rtc_base/task_utils:repeating_task_unittests",
"test:test_main",
]
}
# TODO(pbos): Rename test suite, this is no longer "just" for video targets. # TODO(pbos): Rename test suite, this is no longer "just" for video targets.
video_engine_tests_resources = [ video_engine_tests_resources = [
"resources/foreman_cif_short.yuv", "resources/foreman_cif_short.yuv",
@ -650,6 +644,7 @@ if (rtc_include_tests && !build_with_chromium) {
"test:test_common", "test:test_common",
"test:test_main", "test:test_main",
"test:video_test_common", "test:video_test_common",
"video:video_legacy_tests",
"video:video_tests", "video:video_tests",
"video/adaptation:video_adaptation_tests", "video/adaptation:video_adaptation_tests",
] ]
@ -746,6 +741,9 @@ group("poison_audio_codecs") {
group("poison_default_task_queue") { group("poison_default_task_queue") {
} }
group("poison_default_echo_detector") {
}
group("poison_rtc_json") { group("poison_rtc_json") {
} }

776
DEPS

File diff suppressed because it is too large Load diff

View file

@ -7,4 +7,3 @@
danilchap@webrtc.org danilchap@webrtc.org
mbonadei@webrtc.org mbonadei@webrtc.org
phoglund@webrtc.org

4
OWNERS
View file

@ -10,9 +10,13 @@ per-file .../BUILD.gn=mbonadei@webrtc.org
per-file *.gni=mbonadei@webrtc.org per-file *.gni=mbonadei@webrtc.org
per-file .../*.gni=mbonadei@webrtc.org per-file .../*.gni=mbonadei@webrtc.org
per-file .vpython=mbonadei@webrtc.org per-file .vpython=mbonadei@webrtc.org
per-file .vpython3=mbonadei@webrtc.org
per-file AUTHORS=* per-file AUTHORS=*
per-file DEPS=* per-file DEPS=*
per-file pylintrc=mbonadei@webrtc.org per-file pylintrc=mbonadei@webrtc.org
per-file WATCHLISTS=* per-file WATCHLISTS=*
per-file native-api.md=mbonadei@webrtc.org per-file native-api.md=mbonadei@webrtc.org
per-file ....lua=titovartem@webrtc.org per-file ....lua=titovartem@webrtc.org
per-file .style.yapf=jleconte@webrtc.org
per-file *.py=jansson@webrtc.org
per-file *.py=jleconte@webrtc.org

View file

@ -1,3 +1,5 @@
#!/usr/bin/env vpython3
# Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. # Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
# #
# Use of this source code is governed by a BSD-style license # Use of this source code is governed by a BSD-style license
@ -13,6 +15,9 @@ import sys
from collections import defaultdict from collections import defaultdict
from contextlib import contextmanager from contextlib import contextmanager
# Runs PRESUBMIT.py in py3 mode by git cl presubmit.
USE_PYTHON3 = True
# Files and directories that are *skipped* by cpplint in the presubmit script. # Files and directories that are *skipped* by cpplint in the presubmit script.
CPPLINT_EXCEPTIONS = [ CPPLINT_EXCEPTIONS = [
'api/video_codecs/video_decoder.h', 'api/video_codecs/video_decoder.h',
@ -31,6 +36,9 @@ CPPLINT_EXCEPTIONS = [
'modules/video_capture', 'modules/video_capture',
'p2p/base/pseudo_tcp.cc', 'p2p/base/pseudo_tcp.cc',
'p2p/base/pseudo_tcp.h', 'p2p/base/pseudo_tcp.h',
'PRESUBMIT.py',
'presubmit_test_mocks.py',
'presubmit_test.py',
'rtc_base', 'rtc_base',
'sdk/android/src/jni', 'sdk/android/src/jni',
'sdk/objc', 'sdk/objc',
@ -137,8 +145,8 @@ def VerifyNativeApiHeadersListIsValid(input_api, output_api):
"""Ensures the list of native API header directories is up to date.""" """Ensures the list of native API header directories is up to date."""
non_existing_paths = [] non_existing_paths = []
native_api_full_paths = [ native_api_full_paths = [
input_api.os_path.join(input_api.PresubmitLocalPath(), input_api.os_path.join(input_api.PresubmitLocalPath(), *path.split('/'))
*path.split('/')) for path in API_DIRS for path in API_DIRS
] ]
for path in native_api_full_paths: for path in native_api_full_paths:
if not os.path.isdir(path): if not os.path.isdir(path):
@ -200,8 +208,8 @@ def CheckNoIOStreamInHeaders(input_api, output_api, source_file_filter):
files = [] files = []
pattern = input_api.re.compile(r'^#include\s*<iostream>', pattern = input_api.re.compile(r'^#include\s*<iostream>',
input_api.re.MULTILINE) input_api.re.MULTILINE)
file_filter = lambda x: (input_api.FilterSourceFile(x) and file_filter = lambda x: (input_api.FilterSourceFile(x) and source_file_filter(
source_file_filter(x)) x))
for f in input_api.AffectedSourceFiles(file_filter): for f in input_api.AffectedSourceFiles(file_filter):
if not f.LocalPath().endswith('.h'): if not f.LocalPath().endswith('.h'):
continue continue
@ -209,13 +217,12 @@ def CheckNoIOStreamInHeaders(input_api, output_api, source_file_filter):
if pattern.search(contents): if pattern.search(contents):
files.append(f) files.append(f)
if len(files): if len(files) > 0:
return [ return [
output_api.PresubmitError( output_api.PresubmitError(
'Do not #include <iostream> in header files, since it inserts ' 'Do not #include <iostream> in header files, since it inserts '
'static initialization into every file including the header. ' 'static initialization into every file including the header. '
'Instead, #include <ostream>. See http://crbug.com/94794', 'Instead, #include <ostream>. See http://crbug.com/94794', files)
files)
] ]
return [] return []
@ -224,8 +231,8 @@ def CheckNoPragmaOnce(input_api, output_api, source_file_filter):
"""Make sure that banned functions are not used.""" """Make sure that banned functions are not used."""
files = [] files = []
pattern = input_api.re.compile(r'^#pragma\s+once', input_api.re.MULTILINE) pattern = input_api.re.compile(r'^#pragma\s+once', input_api.re.MULTILINE)
file_filter = lambda x: (input_api.FilterSourceFile(x) and file_filter = lambda x: (input_api.FilterSourceFile(x) and source_file_filter(
source_file_filter(x)) x))
for f in input_api.AffectedSourceFiles(file_filter): for f in input_api.AffectedSourceFiles(file_filter):
if not f.LocalPath().endswith('.h'): if not f.LocalPath().endswith('.h'):
continue continue
@ -238,11 +245,11 @@ def CheckNoPragmaOnce(input_api, output_api, source_file_filter):
output_api.PresubmitError( output_api.PresubmitError(
'Do not use #pragma once in header files.\n' 'Do not use #pragma once in header files.\n'
'See http://www.chromium.org/developers/coding-style' 'See http://www.chromium.org/developers/coding-style'
'#TOC-File-headers', '#TOC-File-headers', files)
files)
] ]
return [] return []
def CheckNoFRIEND_TEST(# pylint: disable=invalid-name def CheckNoFRIEND_TEST(# pylint: disable=invalid-name
input_api, input_api,
output_api, output_api,
@ -308,8 +315,7 @@ def CheckApprovedFilesLintClean(input_api, output_api,
files = [] files = []
for f in input_api.AffectedSourceFiles(source_file_filter): for f in input_api.AffectedSourceFiles(source_file_filter):
# Note that moved/renamed files also count as added. # Note that moved/renamed files also count as added.
if f.Action() == 'A' or not IsLintDisabled(disabled_paths, if f.Action() == 'A' or not IsLintDisabled(disabled_paths, f.LocalPath()):
f.LocalPath()):
files.append(f.AbsoluteLocalPath()) files.append(f.AbsoluteLocalPath())
for file_name in files: for file_name in files:
@ -337,8 +343,7 @@ def CheckNoSourcesAbove(input_api, gn_files, output_api):
for source_block_match in source_pattern.finditer(contents): for source_block_match in source_pattern.finditer(contents):
# Find all source list entries starting with ../ in the source block # Find all source list entries starting with ../ in the source block
# (exclude overrides entries). # (exclude overrides entries).
for file_list_match in file_pattern.finditer( for file_list_match in file_pattern.finditer(source_block_match.group(1)):
source_block_match.group(1)):
source_file = file_list_match.group(1) source_file = file_list_match.group(1)
if 'overrides/' not in source_file: if 'overrides/' not in source_file:
violating_source_entries.append(source_file) violating_source_entries.append(source_file)
@ -370,6 +375,7 @@ def CheckAbseilDependencies(input_api, gn_files, output_api):
'should be moved to the "absl_deps" parameter.') 'should be moved to the "absl_deps" parameter.')
errors = [] errors = []
# pylint: disable=too-many-nested-blocks
for gn_file in gn_files: for gn_file in gn_files:
gn_file_content = input_api.ReadFile(gn_file) gn_file_content = input_api.ReadFile(gn_file)
for target_match in TARGET_RE.finditer(gn_file_content): for target_match in TARGET_RE.finditer(gn_file_content):
@ -382,8 +388,7 @@ def CheckAbseilDependencies(input_api, gn_files, output_api):
for dep in deps: for dep in deps:
if re.search(absl_re, dep): if re.search(absl_re, dep):
errors.append( errors.append(
output_api.PresubmitError( output_api.PresubmitError(error_msg %
error_msg %
(target_name, gn_file.LocalPath()))) (target_name, gn_file.LocalPath())))
break # no need to warn more than once per target break # no need to warn more than once per target
return errors return errors
@ -398,7 +403,7 @@ def CheckNoMixingSources(input_api, gn_files, output_api):
def _MoreThanOneSourceUsed(*sources_lists): def _MoreThanOneSourceUsed(*sources_lists):
sources_used = 0 sources_used = 0
for source_list in sources_lists: for source_list in sources_lists:
if len(source_list): if len(source_list) > 0:
sources_used += 1 sources_used += 1
return sources_used > 1 return sources_used > 1
@ -432,8 +437,7 @@ def CheckNoMixingSources(input_api, gn_files, output_api):
c_files = [] c_files = []
cc_files = [] cc_files = []
objc_files = [] objc_files = []
for file_match in FILE_PATH_RE.finditer( for file_match in FILE_PATH_RE.finditer(sources_match.group(1)):
sources_match.group(1)):
file_path = file_match.group('file_path') file_path = file_match.group('file_path')
extension = file_match.group('extension') extension = file_match.group('extension')
if extension == '.c': if extension == '.c':
@ -444,12 +448,9 @@ def CheckNoMixingSources(input_api, gn_files, output_api):
objc_files.append(file_path + extension) objc_files.append(file_path + extension)
list_of_sources.append((c_files, cc_files, objc_files)) list_of_sources.append((c_files, cc_files, objc_files))
for c_files_list, cc_files_list, objc_files_list in list_of_sources: for c_files_list, cc_files_list, objc_files_list in list_of_sources:
if _MoreThanOneSourceUsed(c_files_list, cc_files_list, if _MoreThanOneSourceUsed(c_files_list, cc_files_list, objc_files_list):
objc_files_list): all_sources = sorted(c_files_list + cc_files_list + objc_files_list)
all_sources = sorted(c_files_list + cc_files_list + errors[gn_file.LocalPath()].append((target_name, all_sources))
objc_files_list)
errors[gn_file.LocalPath()].append(
(target_name, all_sources))
if errors: if errors:
return [ return [
output_api.PresubmitError( output_api.PresubmitError(
@ -459,7 +460,7 @@ def CheckNoMixingSources(input_api, gn_files, output_api):
'Mixed sources: \n' 'Mixed sources: \n'
'%s\n' '%s\n'
'Violating GN files:\n%s\n' % 'Violating GN files:\n%s\n' %
(json.dumps(errors, indent=2), '\n'.join(errors.keys()))) (json.dumps(errors, indent=2), '\n'.join(list(errors.keys()))))
] ]
return [] return []
@ -467,18 +468,16 @@ def CheckNoMixingSources(input_api, gn_files, output_api):
def CheckNoPackageBoundaryViolations(input_api, gn_files, output_api): def CheckNoPackageBoundaryViolations(input_api, gn_files, output_api):
cwd = input_api.PresubmitLocalPath() cwd = input_api.PresubmitLocalPath()
with _AddToPath( with _AddToPath(
input_api.os_path.join(cwd, 'tools_webrtc', input_api.os_path.join(cwd, 'tools_webrtc', 'presubmit_checks_lib')):
'presubmit_checks_lib')):
from check_package_boundaries import CheckPackageBoundaries from check_package_boundaries import CheckPackageBoundaries
build_files = [ build_files = [os.path.join(cwd, gn_file.LocalPath()) for gn_file in gn_files]
os.path.join(cwd, gn_file.LocalPath()) for gn_file in gn_files
]
errors = CheckPackageBoundaries(cwd, build_files)[:5] errors = CheckPackageBoundaries(cwd, build_files)[:5]
if errors: if errors:
return [ return [
output_api.PresubmitError( output_api.PresubmitError(
'There are package boundary violations in the following GN ' 'There are package boundary violations in the following GN '
'files:', long_text='\n\n'.join(str(err) for err in errors)) 'files:',
long_text='\n\n'.join(str(err) for err in errors))
] ]
return [] return []
@ -492,7 +491,7 @@ def CheckNoWarningSuppressionFlagsAreAdded(gn_files,
input_api, input_api,
output_api, output_api,
error_formatter=_ReportFileAndLine): error_formatter=_ReportFileAndLine):
"""Ensure warning suppression flags are not added wihtout a reason.""" """Ensure warning suppression flags are not added without a reason."""
msg = ('Usage of //build/config/clang:extra_warnings is discouraged ' msg = ('Usage of //build/config/clang:extra_warnings is discouraged '
'in WebRTC.\n' 'in WebRTC.\n'
'If you are not adding this code (e.g. you are just moving ' 'If you are not adding this code (e.g. you are just moving '
@ -502,8 +501,8 @@ def CheckNoWarningSuppressionFlagsAreAdded(gn_files,
'\n' '\n'
'Affected files:\n') 'Affected files:\n')
errors = [] # 2-element tuples with (file, line number) errors = [] # 2-element tuples with (file, line number)
clang_warn_re = input_api.re.compile( clang_warn_re = input_api.re.compile(r'//build/config/clang:extra_warnings')
r'//build/config/clang:extra_warnings') # pylint: disable-next=fixme
no_presubmit_re = input_api.re.compile( no_presubmit_re = input_api.re.compile(
r'# no-presubmit-check TODO\(bugs\.webrtc\.org/\d+\)') r'# no-presubmit-check TODO\(bugs\.webrtc\.org/\d+\)')
for f in gn_files: for f in gn_files:
@ -541,8 +540,7 @@ def CheckNoStreamUsageIsAdded(input_api,
source_file_filter, source_file_filter,
error_formatter=_ReportFileAndLine): error_formatter=_ReportFileAndLine):
"""Make sure that no more dependencies on stringstream are added.""" """Make sure that no more dependencies on stringstream are added."""
error_msg = ( error_msg = ('Usage of <sstream>, <istream> and <ostream> in WebRTC is '
'Usage of <sstream>, <istream> and <ostream> in WebRTC is '
'deprecated.\n' 'deprecated.\n'
'This includes the following types:\n' 'This includes the following types:\n'
'std::istringstream, std::ostringstream, std::wistringstream, ' 'std::istringstream, std::ostringstream, std::wistringstream, '
@ -562,19 +560,18 @@ def CheckNoStreamUsageIsAdded(input_api,
'Affected files:\n') 'Affected files:\n')
errors = [] # 2-element tuples with (file, line number) errors = [] # 2-element tuples with (file, line number)
include_re = input_api.re.compile(r'#include <(i|o|s)stream>') include_re = input_api.re.compile(r'#include <(i|o|s)stream>')
usage_re = input_api.re.compile( usage_re = input_api.re.compile(r'std::(w|i|o|io|wi|wo|wio)(string)*stream')
r'std::(w|i|o|io|wi|wo|wio)(string)*stream')
no_presubmit_re = input_api.re.compile( no_presubmit_re = input_api.re.compile(
r'// no-presubmit-check TODO\(webrtc:8982\)') r'// no-presubmit-check TODO\(webrtc:8982\)')
file_filter = lambda x: (input_api.FilterSourceFile(x) and file_filter = lambda x: (input_api.FilterSourceFile(x) and source_file_filter(
source_file_filter(x)) x))
def _IsException(file_path): def _IsException(file_path):
is_test = any( is_test = any(
file_path.endswith(x) for x in file_path.endswith(x)
['_test.cc', '_tests.cc', '_unittest.cc', '_unittests.cc']) for x in ['_test.cc', '_tests.cc', '_unittest.cc', '_unittests.cc'])
return (file_path.startswith('examples') return (file_path.startswith('examples') or file_path.startswith('test')
or file_path.startswith('test') or is_test) or is_test)
for f in input_api.AffectedSourceFiles(file_filter): for f in input_api.AffectedSourceFiles(file_filter):
# Usage of stringstream is allowed under examples/ and in tests. # Usage of stringstream is allowed under examples/ and in tests.
@ -608,21 +605,20 @@ def CheckPublicDepsIsNotUsed(gn_files, input_api, output_api):
if not surpressed: if not surpressed:
result.append( result.append(
output_api.PresubmitError( output_api.PresubmitError(
error_msg % error_msg % (affected_file.LocalPath(), line_number)))
(affected_file.LocalPath(), line_number)))
return result return result
def CheckCheckIncludesIsNotUsed(gn_files, input_api, output_api): def CheckCheckIncludesIsNotUsed(gn_files, input_api, output_api):
result = [] result = []
error_msg = ( error_msg = ('check_includes overrides are not allowed since it can cause '
'check_includes overrides are not allowed since it can cause '
'incorrect dependencies to form. It effectively means that your ' 'incorrect dependencies to form. It effectively means that your '
'module can include any .h file without depending on its ' 'module can include any .h file without depending on its '
'corresponding target. There are some exceptional cases when ' 'corresponding target. There are some exceptional cases when '
'this is allowed: if so, get approval from a .gn owner in the ' 'this is allowed: if so, get approval from a .gn owner in the '
'root OWNERS file.\n' 'root OWNERS file.\n'
'Used in: %s (line %d).') 'Used in: %s (line %d).')
# pylint: disable-next=fixme
no_presubmit_re = input_api.re.compile( no_presubmit_re = input_api.re.compile(
r'# no-presubmit-check TODO\(bugs\.webrtc\.org/\d+\)') r'# no-presubmit-check TODO\(bugs\.webrtc\.org/\d+\)')
for affected_file in gn_files: for affected_file in gn_files:
@ -630,8 +626,8 @@ def CheckCheckIncludesIsNotUsed(gn_files, input_api, output_api):
if ('check_includes' in affected_line if ('check_includes' in affected_line
and not no_presubmit_re.search(affected_line)): and not no_presubmit_re.search(affected_line)):
result.append( result.append(
output_api.PresubmitError( output_api.PresubmitError(error_msg %
error_msg % (affected_file.LocalPath(), line_number))) (affected_file.LocalPath(), line_number)))
return result return result
@ -652,13 +648,10 @@ def CheckGnChanges(input_api, output_api):
result.extend(CheckAbseilDependencies(input_api, gn_files, output_api)) result.extend(CheckAbseilDependencies(input_api, gn_files, output_api))
result.extend( result.extend(
CheckNoPackageBoundaryViolations(input_api, gn_files, output_api)) CheckNoPackageBoundaryViolations(input_api, gn_files, output_api))
result.extend(CheckPublicDepsIsNotUsed(gn_files, input_api, result.extend(CheckPublicDepsIsNotUsed(gn_files, input_api, output_api))
output_api)) result.extend(CheckCheckIncludesIsNotUsed(gn_files, input_api, output_api))
result.extend( result.extend(
CheckCheckIncludesIsNotUsed(gn_files, input_api, output_api)) CheckNoWarningSuppressionFlagsAreAdded(gn_files, input_api, output_api))
result.extend(
CheckNoWarningSuppressionFlagsAreAdded(gn_files, input_api,
output_api))
return result return result
@ -668,8 +661,8 @@ def CheckGnGen(input_api, output_api):
errors. errors.
""" """
with _AddToPath( with _AddToPath(
input_api.os_path.join(input_api.PresubmitLocalPath(), input_api.os_path.join(input_api.PresubmitLocalPath(), 'tools_webrtc',
'tools_webrtc', 'presubmit_checks_lib')): 'presubmit_checks_lib')):
from build_helpers import RunGnCheck from build_helpers import RunGnCheck
errors = RunGnCheck(FindSrcDirPath(input_api.PresubmitLocalPath()))[:5] errors = RunGnCheck(FindSrcDirPath(input_api.PresubmitLocalPath()))[:5]
if errors: if errors:
@ -694,8 +687,7 @@ def CheckUnwantedDependencies(input_api, output_api, source_file_filter):
# roundabout construct to import checkdeps because this file is # roundabout construct to import checkdeps because this file is
# eval-ed and thus doesn't have __file__. # eval-ed and thus doesn't have __file__.
src_path = FindSrcDirPath(input_api.PresubmitLocalPath()) src_path = FindSrcDirPath(input_api.PresubmitLocalPath())
checkdeps_path = input_api.os_path.join(src_path, 'buildtools', checkdeps_path = input_api.os_path.join(src_path, 'buildtools', 'checkdeps')
'checkdeps')
if not os.path.exists(checkdeps_path): if not os.path.exists(checkdeps_path):
return [ return [
output_api.PresubmitError( output_api.PresubmitError(
@ -752,8 +744,7 @@ def CheckCommitMessageBugEntry(input_api, output_api):
"""Check that bug entries are well-formed in commit message.""" """Check that bug entries are well-formed in commit message."""
bogus_bug_msg = ( bogus_bug_msg = (
'Bogus Bug entry: %s. Please specify the issue tracker prefix and the ' 'Bogus Bug entry: %s. Please specify the issue tracker prefix and the '
'issue number, separated by a colon, e.g. webrtc:123 or chromium:12345.' 'issue number, separated by a colon, e.g. webrtc:123 or chromium:12345.')
)
results = [] results = []
for bug in input_api.change.BugsFromDescription(): for bug in input_api.change.BugsFromDescription():
bug = bug.strip() bug = bug.strip()
@ -766,8 +757,7 @@ def CheckCommitMessageBugEntry(input_api, output_api):
prefix_guess = 'chromium' prefix_guess = 'chromium'
else: else:
prefix_guess = 'webrtc' prefix_guess = 'webrtc'
results.append( results.append('Bug entry requires issue tracker prefix, e.g. %s:%s' %
'Bug entry requires issue tracker prefix, e.g. %s:%s' %
(prefix_guess, bug)) (prefix_guess, bug))
except ValueError: except ValueError:
results.append(bogus_bug_msg % bug) results.append(bogus_bug_msg % bug)
@ -788,15 +778,13 @@ def CheckChangeHasBugField(input_api, output_api):
""" """
if input_api.change.BugsFromDescription(): if input_api.change.BugsFromDescription():
return [] return []
else:
return [ return [
output_api.PresubmitError( output_api.PresubmitError(
'The "Bug: [bug number]" footer is mandatory. Please create a ' 'The "Bug: [bug number]" footer is mandatory. Please create a '
'bug and reference it using either of:\n' 'bug and reference it using either of:\n'
' * https://bugs.webrtc.org - reference it using Bug: ' ' * https://bugs.webrtc.org - reference it using Bug: '
'webrtc:XXXX\n' 'webrtc:XXXX\n'
' * https://crbug.com - reference it using Bug: chromium:XXXXXX' ' * https://crbug.com - reference it using Bug: chromium:XXXXXX')
)
] ]
@ -804,8 +792,7 @@ def CheckJSONParseErrors(input_api, output_api, source_file_filter):
"""Check that JSON files do not contain syntax errors.""" """Check that JSON files do not contain syntax errors."""
def FilterFile(affected_file): def FilterFile(affected_file):
return (input_api.os_path.splitext( return (input_api.os_path.splitext(affected_file.LocalPath())[1] == '.json'
affected_file.LocalPath())[1] == '.json'
and source_file_filter(affected_file)) and source_file_filter(affected_file))
def GetJSONParseError(input_api, filename): def GetJSONParseError(input_api, filename):
@ -823,8 +810,7 @@ def CheckJSONParseErrors(input_api, output_api, source_file_filter):
affected_file.AbsoluteLocalPath()) affected_file.AbsoluteLocalPath())
if parse_error: if parse_error:
results.append( results.append(
output_api.PresubmitError( output_api.PresubmitError('%s could not be parsed: %s' %
'%s could not be parsed: %s' %
(affected_file.LocalPath(), parse_error))) (affected_file.LocalPath(), parse_error)))
return results return results
@ -833,23 +819,32 @@ def RunPythonTests(input_api, output_api):
def Join(*args): def Join(*args):
return input_api.os_path.join(input_api.PresubmitLocalPath(), *args) return input_api.os_path.join(input_api.PresubmitLocalPath(), *args)
excluded_files = [
# These tests should be run manually after webrtc_dashboard_upload target
# has been built.
'catapult_uploader_test.py',
'process_perf_results_test.py',
]
test_directories = [ test_directories = [
input_api.PresubmitLocalPath(), input_api.PresubmitLocalPath(),
Join('rtc_tools', 'py_event_log_analyzer'), Join('rtc_tools', 'py_event_log_analyzer'),
Join('audio', 'test', 'unittests'), Join('audio', 'test', 'unittests'),
] + [ ] + [
root for root, _, files in os.walk(Join('tools_webrtc')) if any( root for root, _, files in os.walk(Join('tools_webrtc')) if any(
f.endswith('_test.py') for f in files) f.endswith('_test.py') and f not in excluded_files for f in files)
] ]
tests = [] tests = []
for directory in test_directories: for directory in test_directories:
tests.extend( tests.extend(
input_api.canned_checks.GetUnitTestsInDirectory( input_api.canned_checks.GetUnitTestsInDirectory(
input_api, input_api,
output_api, output_api,
directory, directory,
files_to_check=[r'.+_test\.py$'])) files_to_check=[r'.+_test\.py$'],
run_on_python2=False))
return input_api.RunTests(tests, parallel=True) return input_api.RunTests(tests, parallel=True)
@ -859,8 +854,8 @@ def CheckUsageOfGoogleProtobufNamespace(input_api, output_api,
files = [] files = []
pattern = input_api.re.compile(r'google::protobuf') pattern = input_api.re.compile(r'google::protobuf')
proto_utils_path = os.path.join('rtc_base', 'protobuf_utils.h') proto_utils_path = os.path.join('rtc_base', 'protobuf_utils.h')
file_filter = lambda x: (input_api.FilterSourceFile(x) and file_filter = lambda x: (input_api.FilterSourceFile(x) and source_file_filter(
source_file_filter(x)) x))
for f in input_api.AffectedSourceFiles(file_filter): for f in input_api.AffectedSourceFiles(file_filter):
if f.LocalPath() in [proto_utils_path, 'PRESUBMIT.py']: if f.LocalPath() in [proto_utils_path, 'PRESUBMIT.py']:
continue continue
@ -872,8 +867,8 @@ def CheckUsageOfGoogleProtobufNamespace(input_api, output_api,
return [ return [
output_api.PresubmitError( output_api.PresubmitError(
'Please avoid to use namespace `google::protobuf` directly.\n' 'Please avoid to use namespace `google::protobuf` directly.\n'
'Add a using directive in `%s` and include that header instead.' 'Add a using directive in `%s` and include that header instead.' %
% proto_utils_path, files) proto_utils_path, files)
] ]
return [] return []
@ -882,7 +877,7 @@ def _LicenseHeader(input_api):
"""Returns the license header regexp.""" """Returns the license header regexp."""
# Accept any year number from 2003 to the current year # Accept any year number from 2003 to the current year
current_year = int(input_api.time.strftime('%Y')) current_year = int(input_api.time.strftime('%Y'))
allowed_years = (str(s) for s in reversed(xrange(2003, current_year + 1))) allowed_years = (str(s) for s in reversed(range(2003, current_year + 1)))
years_re = '(' + '|'.join(allowed_years) + ')' years_re = '(' + '|'.join(allowed_years) + ')'
license_header = ( license_header = (
r'.*? Copyright( \(c\))? %(year)s The WebRTC [Pp]roject [Aa]uthors\. ' r'.*? Copyright( \(c\))? %(year)s The WebRTC [Pp]roject [Aa]uthors\. '
@ -921,8 +916,11 @@ def CommonChecks(input_api, output_api):
# all python files. This is a temporary solution. # all python files. This is a temporary solution.
python_file_filter = lambda f: (f.LocalPath().endswith('.py') and python_file_filter = lambda f: (f.LocalPath().endswith('.py') and
source_file_filter(f)) source_file_filter(f))
python_changed_files = [f.LocalPath() for f in input_api.AffectedFiles( python_changed_files = [
include_deletes=False, file_filter=python_file_filter)] f.LocalPath()
for f in input_api.AffectedFiles(include_deletes=False,
file_filter=python_file_filter)
]
results.extend( results.extend(
input_api.canned_checks.RunPylint( input_api.canned_checks.RunPylint(
@ -939,13 +937,14 @@ def CommonChecks(input_api, output_api):
r'^testing[\\\/].*\.py$', r'^testing[\\\/].*\.py$',
r'^third_party[\\\/].*\.py$', r'^third_party[\\\/].*\.py$',
r'^tools[\\\/].*\.py$', r'^tools[\\\/].*\.py$',
# TODO(phoglund): should arguably be checked. # TODO(bugs.webrtc.org/13605): should arguably be checked.
r'^tools_webrtc[\\\/]mb[\\\/].*\.py$', r'^tools_webrtc[\\\/]mb[\\\/].*\.py$',
r'^xcodebuild.*[\\\/].*\.py$', r'^xcodebuild.*[\\\/].*\.py$',
), ),
pylintrc='pylintrc')) pylintrc='pylintrc',
version='2.7'))
# TODO(nisse): talk/ is no more, so make below checks simpler? # TODO(bugs.webrtc.org/13606): talk/ is no more, so make below checks simpler?
# WebRTC can't use the presubmit_canned_checks.PanProjectChecks function # WebRTC can't use the presubmit_canned_checks.PanProjectChecks function
# since we need to have different license checks # since we need to have different license checks
# in talk/ and webrtc/directories. # in talk/ and webrtc/directories.
@ -1032,8 +1031,7 @@ def CommonChecks(input_api, output_api):
CheckNewlineAtTheEndOfProtoFiles( CheckNewlineAtTheEndOfProtoFiles(
input_api, output_api, source_file_filter=non_third_party_sources)) input_api, output_api, source_file_filter=non_third_party_sources))
results.extend( results.extend(
CheckNoStreamUsageIsAdded(input_api, output_api, CheckNoStreamUsageIsAdded(input_api, output_api, non_third_party_sources))
non_third_party_sources))
results.extend( results.extend(
CheckNoTestCaseUsageIsAdded(input_api, output_api, CheckNoTestCaseUsageIsAdded(input_api, output_api,
non_third_party_sources)) non_third_party_sources))
@ -1044,8 +1042,7 @@ def CommonChecks(input_api, output_api):
results.extend( results.extend(
CheckAssertUsage(input_api, output_api, non_third_party_sources)) CheckAssertUsage(input_api, output_api, non_third_party_sources))
results.extend( results.extend(
CheckBannedAbslMakeUnique(input_api, output_api, CheckBannedAbslMakeUnique(input_api, output_api, non_third_party_sources))
non_third_party_sources))
results.extend( results.extend(
CheckObjcApiSymbols(input_api, output_api, non_third_party_sources)) CheckObjcApiSymbols(input_api, output_api, non_third_party_sources))
return results return results
@ -1075,8 +1072,7 @@ def CheckApiDepsFileIsUpToDate(input_api, output_api):
path_tokens = [t for t in f.LocalPath().split(os.sep) if t] path_tokens = [t for t in f.LocalPath().split(os.sep) if t]
if len(path_tokens) > 1: if len(path_tokens) > 1:
if (path_tokens[0] not in dirs_to_skip and os.path.isdir( if (path_tokens[0] not in dirs_to_skip and os.path.isdir(
os.path.join(input_api.PresubmitLocalPath(), os.path.join(input_api.PresubmitLocalPath(), path_tokens[0]))):
path_tokens[0]))):
dirs_to_check.add(path_tokens[0]) dirs_to_check.add(path_tokens[0])
missing_include_rules = set() missing_include_rules = set()
@ -1119,7 +1115,7 @@ def CheckBannedAbslMakeUnique(input_api, output_api, source_file_filter):
files.append(f) files.append(f)
break break
if len(files): if files:
return [ return [
output_api.PresubmitError( output_api.PresubmitError(
'Please use std::make_unique instead of absl::make_unique.\n' 'Please use std::make_unique instead of absl::make_unique.\n'
@ -1135,8 +1131,8 @@ def CheckObjcApiSymbols(input_api, output_api, source_file_filter):
source_file_filter(f)) source_file_filter(f))
files = [] files = []
file_filter = lambda x: (input_api.FilterSourceFile(x) and file_filter = lambda x: (input_api.FilterSourceFile(x) and source_file_filter(
source_file_filter(x)) x))
for f in input_api.AffectedSourceFiles(file_filter): for f in input_api.AffectedSourceFiles(file_filter):
if not f.LocalPath().endswith('.h') or not 'sdk/objc' in f.LocalPath(): if not f.LocalPath().endswith('.h') or not 'sdk/objc' in f.LocalPath():
continue continue
@ -1148,11 +1144,11 @@ def CheckObjcApiSymbols(input_api, output_api, source_file_filter):
if 'RTC_OBJC_TYPE' not in export_block: if 'RTC_OBJC_TYPE' not in export_block:
files.append(f.LocalPath()) files.append(f.LocalPath())
if len(files): if len(files) > 0:
return [ return [
output_api.PresubmitError( output_api.PresubmitError(
'RTC_OBJC_EXPORT types must be wrapped into an RTC_OBJC_TYPE() ' 'RTC_OBJC_EXPORT types must be wrapped into an RTC_OBJC_TYPE() ' +
+ 'macro.\n\n' + 'For example:\n' + 'macro.\n\n' + 'For example:\n' +
'RTC_OBJC_EXPORT @protocol RTC_OBJC_TYPE(RtcFoo)\n\n' + 'RTC_OBJC_EXPORT @protocol RTC_OBJC_TYPE(RtcFoo)\n\n' +
'RTC_OBJC_EXPORT @interface RTC_OBJC_TYPE(RtcFoo)\n\n' + 'RTC_OBJC_EXPORT @interface RTC_OBJC_TYPE(RtcFoo)\n\n' +
'Please fix the following files:', files) 'Please fix the following files:', files)
@ -1173,7 +1169,7 @@ def CheckAssertUsage(input_api, output_api, source_file_filter):
files.append(f.LocalPath()) files.append(f.LocalPath())
break break
if len(files): if len(files) > 0:
return [ return [
output_api.PresubmitError( output_api.PresubmitError(
'Usage of assert() has been detected in the following files, ' 'Usage of assert() has been detected in the following files, '
@ -1199,7 +1195,7 @@ def CheckAbslMemoryInclude(input_api, output_api, source_file_filter):
files.append(f) files.append(f)
break break
if len(files): if len(files) > 0:
return [ return [
output_api.PresubmitError( output_api.PresubmitError(
'Please include "absl/memory/memory.h" header for ' 'Please include "absl/memory/memory.h" header for '
@ -1213,8 +1209,8 @@ def CheckChangeOnUpload(input_api, output_api):
results = [] results = []
results.extend(CommonChecks(input_api, output_api)) results.extend(CommonChecks(input_api, output_api))
results.extend(CheckGnGen(input_api, output_api)) results.extend(CheckGnGen(input_api, output_api))
results.extend( results.extend(input_api.canned_checks.CheckGNFormatted(
input_api.canned_checks.CheckGNFormatted(input_api, output_api)) input_api, output_api))
return results return results
@ -1226,8 +1222,7 @@ def CheckChangeOnCommit(input_api, output_api):
results.extend( results.extend(
input_api.canned_checks.CheckChangeWasUploaded(input_api, output_api)) input_api.canned_checks.CheckChangeWasUploaded(input_api, output_api))
results.extend( results.extend(
input_api.canned_checks.CheckChangeHasDescription( input_api.canned_checks.CheckChangeHasDescription(input_api, output_api))
input_api, output_api))
results.extend(CheckChangeHasBugField(input_api, output_api)) results.extend(CheckChangeHasBugField(input_api, output_api))
results.extend(CheckCommitMessageBugEntry(input_api, output_api)) results.extend(CheckCommitMessageBugEntry(input_api, output_api))
results.extend( results.extend(
@ -1244,12 +1239,11 @@ def CheckOrphanHeaders(input_api, output_api, source_file_filter):
# eval-ed and thus doesn't have __file__. # eval-ed and thus doesn't have __file__.
error_msg = """{} should be listed in {}.""" error_msg = """{} should be listed in {}."""
results = [] results = []
exempt_paths = [ exempt_paths = [re.escape(os.path.join('tools_webrtc', 'ios', 'SDK'))]
os.path.join('tools_webrtc', 'ios', 'SDK'),
]
with _AddToPath( with _AddToPath(
input_api.os_path.join(input_api.PresubmitLocalPath(), input_api.os_path.join(input_api.PresubmitLocalPath(), 'tools_webrtc',
'tools_webrtc', 'presubmit_checks_lib')): 'presubmit_checks_lib')):
from check_orphan_headers import GetBuildGnPathFromFilePath from check_orphan_headers import GetBuildGnPathFromFilePath
from check_orphan_headers import IsHeaderInBuildGn from check_orphan_headers import IsHeaderInBuildGn
@ -1259,14 +1253,13 @@ def CheckOrphanHeaders(input_api, output_api, source_file_filter):
if f.LocalPath().endswith('.h'): if f.LocalPath().endswith('.h'):
file_path = os.path.abspath(f.LocalPath()) file_path = os.path.abspath(f.LocalPath())
root_dir = os.getcwd() root_dir = os.getcwd()
gn_file_path = GetBuildGnPathFromFilePath(file_path, gn_file_path = GetBuildGnPathFromFilePath(file_path, os.path.exists,
os.path.exists, root_dir) root_dir)
in_build_gn = IsHeaderInBuildGn(file_path, gn_file_path) in_build_gn = IsHeaderInBuildGn(file_path, gn_file_path)
if not in_build_gn: if not in_build_gn:
results.append( results.append(
output_api.PresubmitError( output_api.PresubmitError(
error_msg.format(f.LocalPath(), error_msg.format(f.LocalPath(), os.path.relpath(gn_file_path))))
os.path.relpath(gn_file_path))))
return results return results
@ -1282,8 +1275,7 @@ def CheckNewlineAtTheEndOfProtoFiles(input_api, output_api,
with open(file_path) as f: with open(file_path) as f:
lines = f.readlines() lines = f.readlines()
if len(lines) > 0 and not lines[-1].endswith('\n'): if len(lines) > 0 and not lines[-1].endswith('\n'):
results.append( results.append(output_api.PresubmitError(error_msg.format(file_path)))
output_api.PresubmitError(error_msg.format(file_path)))
return results return results
@ -1297,7 +1289,7 @@ def _ExtractAddRulesFromParsedDeps(parsed_deps):
rule[1:] for rule in parsed_deps.get('include_rules', []) rule[1:] for rule in parsed_deps.get('include_rules', [])
if rule.startswith('+') or rule.startswith('!') if rule.startswith('+') or rule.startswith('!')
]) ])
for _, rules in parsed_deps.get('specific_include_rules', {}).iteritems(): for _, rules in parsed_deps.get('specific_include_rules', {}).items():
add_rules.update([ add_rules.update([
rule[1:] for rule in rules rule[1:] for rule in rules
if rule.startswith('+') or rule.startswith('!') if rule.startswith('+') or rule.startswith('!')
@ -1309,7 +1301,7 @@ def _ParseDeps(contents):
"""Simple helper for parsing DEPS files.""" """Simple helper for parsing DEPS files."""
# Stubs for handling special syntax in the root DEPS file. # Stubs for handling special syntax in the root DEPS file.
class VarImpl(object): class VarImpl:
def __init__(self, local_scope): def __init__(self, local_scope):
self._local_scope = local_scope self._local_scope = local_scope
@ -1317,14 +1309,15 @@ def _ParseDeps(contents):
"""Implements the Var syntax.""" """Implements the Var syntax."""
try: try:
return self._local_scope['vars'][var_name] return self._local_scope['vars'][var_name]
except KeyError: except KeyError as var_not_defined:
raise Exception('Var is not defined: %s' % var_name) raise Exception('Var is not defined: %s' %
var_name) from var_not_defined
local_scope = {} local_scope = {}
global_scope = { global_scope = {
'Var': VarImpl(local_scope).Lookup, 'Var': VarImpl(local_scope).Lookup,
} }
exec contents in global_scope, local_scope exec(contents, global_scope, local_scope)
return local_scope return local_scope
@ -1371,8 +1364,7 @@ def CheckAddedDepsHaveTargetApprovals(input_api, output_api):
filename = input_api.os_path.basename(f.LocalPath()) filename = input_api.os_path.basename(f.LocalPath())
if filename == 'DEPS': if filename == 'DEPS':
virtual_depended_on_files.update( virtual_depended_on_files.update(
_CalculateAddedDeps(input_api.os_path, _CalculateAddedDeps(input_api.os_path, '\n'.join(f.OldContents()),
'\n'.join(f.OldContents()),
'\n'.join(f.NewContents()))) '\n'.join(f.NewContents())))
if not virtual_depended_on_files: if not virtual_depended_on_files:
@ -1383,15 +1375,13 @@ def CheckAddedDepsHaveTargetApprovals(input_api, output_api):
return [ return [
output_api.PresubmitNotifyResult( output_api.PresubmitNotifyResult(
'--tbr was specified, skipping OWNERS check for DEPS ' '--tbr was specified, skipping OWNERS check for DEPS '
'additions' 'additions')
)
] ]
if input_api.dry_run: if input_api.dry_run:
return [ return [
output_api.PresubmitNotifyResult( output_api.PresubmitNotifyResult(
'This is a dry run, skipping OWNERS check for DEPS ' 'This is a dry run, skipping OWNERS check for DEPS '
'additions' 'additions')
)
] ]
if not input_api.change.issue: if not input_api.change.issue:
return [ return [
@ -1405,9 +1395,7 @@ def CheckAddedDepsHaveTargetApprovals(input_api, output_api):
owner_email, reviewers = ( owner_email, reviewers = (
input_api.canned_checks.GetCodereviewOwnerAndReviewers( input_api.canned_checks.GetCodereviewOwnerAndReviewers(
input_api, input_api, None, approval_needed=input_api.is_committing))
None,
approval_needed=input_api.is_committing))
owner_email = owner_email or input_api.change.author_email owner_email = owner_email or input_api.change.author_email
@ -1415,7 +1403,8 @@ def CheckAddedDepsHaveTargetApprovals(input_api, output_api):
virtual_depended_on_files, reviewers.union([owner_email]), []) virtual_depended_on_files, reviewers.union([owner_email]), [])
missing_files = [ missing_files = [
f for f in virtual_depended_on_files f for f in virtual_depended_on_files
if approval_status[f] != input_api.owners_client.APPROVED] if approval_status[f] != input_api.owners_client.APPROVED
]
# We strip the /DEPS part that was added by # We strip the /DEPS part that was added by
# _FilesToCheckForIncomingDeps to fake a path to a file in a # _FilesToCheckForIncomingDeps to fake a path to a file in a
@ -1424,7 +1413,6 @@ def CheckAddedDepsHaveTargetApprovals(input_api, output_api):
start_deps = path.rfind('/DEPS') start_deps = path.rfind('/DEPS')
if start_deps != -1: if start_deps != -1:
return path[:start_deps] return path[:start_deps]
else:
return path return path
unapproved_dependencies = [ unapproved_dependencies = [
@ -1433,8 +1421,7 @@ def CheckAddedDepsHaveTargetApprovals(input_api, output_api):
if unapproved_dependencies: if unapproved_dependencies:
output_list = [ output_list = [
output( output('You need LGTM from owners of depends-on paths in DEPS that '
'You need LGTM from owners of depends-on paths in DEPS that '
' were modified in this CL:\n %s' % ' were modified in this CL:\n %s' %
'\n '.join(sorted(unapproved_dependencies))) '\n '.join(sorted(unapproved_dependencies)))
] ]

View file

@ -98,6 +98,12 @@ rtc_library("rtp_packet_info") {
absl_deps = [ "//third_party/abseil-cpp/absl/types:optional" ] absl_deps = [ "//third_party/abseil-cpp/absl/types:optional" ]
} }
rtc_source_set("video_track_source_constraints") {
visibility = [ "*" ]
sources = [ "video_track_source_constraints.h" ]
absl_deps = [ "//third_party/abseil-cpp/absl/types:optional" ]
}
rtc_library("media_stream_interface") { rtc_library("media_stream_interface") {
visibility = [ "*" ] visibility = [ "*" ]
sources = [ sources = [
@ -110,9 +116,12 @@ rtc_library("media_stream_interface") {
":audio_options_api", ":audio_options_api",
":rtp_parameters", ":rtp_parameters",
":scoped_refptr", ":scoped_refptr",
":sequence_checker",
":video_track_source_constraints",
"../modules/audio_processing:audio_processing_statistics", "../modules/audio_processing:audio_processing_statistics",
"../rtc_base:checks", "../rtc_base:checks",
"../rtc_base:refcount", "../rtc_base:refcount",
"../rtc_base/system:no_unique_address",
"../rtc_base/system:rtc_export", "../rtc_base/system:rtc_export",
"video:recordable_encoded_frame", "video:recordable_encoded_frame",
"video:video_frame", "video:video_frame",
@ -185,6 +194,7 @@ rtc_library("libjingle_peerconnection_api") {
"crypto:frame_decryptor_interface", "crypto:frame_decryptor_interface",
"crypto:frame_encryptor_interface", "crypto:frame_encryptor_interface",
"crypto:options", "crypto:options",
"metronome",
"neteq:neteq_api", "neteq:neteq_api",
"rtc_event_log", "rtc_event_log",
"task_queue", "task_queue",
@ -257,6 +267,7 @@ rtc_source_set("packet_socket_factory") {
] ]
deps = [ deps = [
":async_dns_resolver", ":async_dns_resolver",
":wrapping_async_dns_resolver",
"../rtc_base:async_resolver_interface", "../rtc_base:async_resolver_interface",
"../rtc_base:rtc_base", "../rtc_base:rtc_base",
"../rtc_base:socket_address", "../rtc_base:socket_address",
@ -273,6 +284,28 @@ rtc_source_set("async_dns_resolver") {
] ]
} }
rtc_source_set("wrapping_async_dns_resolver") {
visibility = [
":*",
"../p2p:rtc_p2p",
]
sources = [
"wrapping_async_dns_resolver.cc",
"wrapping_async_dns_resolver.h",
]
deps = [
":async_dns_resolver",
":sequence_checker",
"../rtc_base:async_resolver_interface",
"../rtc_base:checks",
"../rtc_base:macromagic",
"../rtc_base:socket_address",
"../rtc_base:threading",
"../rtc_base/third_party/sigslot",
]
absl_deps = [ "//third_party/abseil-cpp/absl/memory" ]
}
rtc_source_set("scoped_refptr") { rtc_source_set("scoped_refptr") {
visibility = [ "*" ] visibility = [ "*" ]
sources = [ "scoped_refptr.h" ] sources = [ "scoped_refptr.h" ]
@ -382,6 +415,16 @@ rtc_source_set("stats_observer_interface") {
absl_deps = [ "//third_party/abseil-cpp/absl/strings" ] absl_deps = [ "//third_party/abseil-cpp/absl/strings" ]
} }
rtc_source_set("peer_network_dependencies") {
visibility = [ "*" ]
sources = [ "test/peer_network_dependencies.h" ]
deps = [
":packet_socket_factory",
"../rtc_base",
"../rtc_base:threading",
]
}
rtc_source_set("peer_connection_quality_test_fixture_api") { rtc_source_set("peer_connection_quality_test_fixture_api") {
visibility = [ "*" ] visibility = [ "*" ]
testonly = true testonly = true
@ -397,14 +440,17 @@ rtc_source_set("peer_connection_quality_test_fixture_api") {
":media_stream_interface", ":media_stream_interface",
":network_state_predictor_api", ":network_state_predictor_api",
":packet_socket_factory", ":packet_socket_factory",
":peer_network_dependencies",
":rtp_parameters", ":rtp_parameters",
":simulated_network_api", ":simulated_network_api",
":stats_observer_interface", ":stats_observer_interface",
":track_id_stream_info_map", ":track_id_stream_info_map",
":video_quality_analyzer_api", ":video_quality_analyzer_api",
"../media:rtc_media_base", "../media:rtc_media_base",
"../modules/audio_processing:api",
"../rtc_base:rtc_base", "../rtc_base:rtc_base",
"../rtc_base:threading", "../rtc_base:threading",
"audio:audio_mixer_api",
"rtc_event_log", "rtc_event_log",
"task_queue", "task_queue",
"transport:network_control", "transport:network_control",
@ -625,6 +671,8 @@ rtc_source_set("network_emulation_manager_api") {
] ]
deps = [ deps = [
":array_view", ":array_view",
":packet_socket_factory",
":peer_network_dependencies",
":simulated_network_api", ":simulated_network_api",
":time_controller", ":time_controller",
"../call:simulated_network", "../call:simulated_network",
@ -1177,3 +1225,10 @@ if (rtc_include_tests) {
] ]
} }
} }
rtc_source_set("webrtc_key_value_config") {
visibility = [ "*" ]
sources = [ "webrtc_key_value_config.h" ]
deps = [ "../rtc_base/system:rtc_export" ]
absl_deps = [ "//third_party/abseil-cpp/absl/strings" ]
}

View file

@ -112,14 +112,6 @@ specific_include_rules = {
"+rtc_base/ref_count.h", "+rtc_base/ref_count.h",
], ],
"jsep_ice_candidate\.h": [
"+rtc_base/constructor_magic.h",
],
"jsep_session_description\.h": [
"+rtc_base/constructor_magic.h",
],
"media_stream_interface\.h": [ "media_stream_interface\.h": [
"+modules/audio_processing/include/audio_processing_statistics.h", "+modules/audio_processing/include/audio_processing_statistics.h",
"+rtc_base/ref_count.h", "+rtc_base/ref_count.h",
@ -156,7 +148,6 @@ specific_include_rules = {
], ],
"ref_counted_base\.h": [ "ref_counted_base\.h": [
"+rtc_base/constructor_magic.h",
"+rtc_base/ref_count.h", "+rtc_base/ref_count.h",
"+rtc_base/ref_counter.h", "+rtc_base/ref_counter.h",
], ],
@ -168,6 +159,9 @@ specific_include_rules = {
# For private member and constructor. # For private member and constructor.
"+rtc_base/system/file_wrapper.h", "+rtc_base/system/file_wrapper.h",
], ],
"rtp_packet_infos\.h": [
"+rtc_base/ref_counted_object.h",
],
"rtp_receiver_interface\.h": [ "rtp_receiver_interface\.h": [
"+rtc_base/ref_count.h", "+rtc_base/ref_count.h",
], ],
@ -192,7 +186,6 @@ specific_include_rules = {
], ],
"stats_types\.h": [ "stats_types\.h": [
"+rtc_base/constructor_magic.h",
"+rtc_base/ref_count.h", "+rtc_base/ref_count.h",
"+rtc_base/thread_checker.h", "+rtc_base/thread_checker.h",
], ],
@ -201,17 +194,12 @@ specific_include_rules = {
"+rtc_base/ref_count.h", "+rtc_base/ref_count.h",
], ],
"audio_frame\.h": [
"+rtc_base/constructor_magic.h",
],
"audio_mixer\.h": [ "audio_mixer\.h": [
"+rtc_base/ref_count.h", "+rtc_base/ref_count.h",
], ],
"audio_decoder\.h": [ "audio_decoder\.h": [
"+rtc_base/buffer.h", "+rtc_base/buffer.h",
"+rtc_base/constructor_magic.h",
], ],
"audio_decoder_factory\.h": [ "audio_decoder_factory\.h": [
@ -267,6 +255,13 @@ specific_include_rules = {
"+rtc_base/ref_counted_object.h", "+rtc_base/ref_counted_object.h",
], ],
"fake_metronome\.h": [
"+rtc_base/synchronization/mutex.h",
"+rtc_base/task_queue.h",
"+rtc_base/task_utils/repeating_task.h",
"+rtc_base/thread_annotations.h",
],
"mock.*\.h": [ "mock.*\.h": [
"+test/gmock.h", "+test/gmock.h",
], ],
@ -279,6 +274,10 @@ specific_include_rules = {
"+rtc_base/ref_counted_object.h", "+rtc_base/ref_counted_object.h",
], ],
"notifier\.h": [
"+rtc_base/system/no_unique_address.h",
],
"simulated_network\.h": [ "simulated_network\.h": [
"+rtc_base/random.h", "+rtc_base/random.h",
"+rtc_base/thread_annotations.h", "+rtc_base/thread_annotations.h",
@ -305,6 +304,18 @@ specific_include_rules = {
"+rtc_base/thread_annotations.h", "+rtc_base/thread_annotations.h",
], ],
"wrapping_async_dns_resolver\.h": [
"+rtc_base/async_resolver.h",
"+rtc_base/async_resolver_interface.h",
"+rtc_base/socket_address.h",
"+rtc_base/third_party/sigslot/sigslot.h",
"+rtc_base/thread_annotations.h",
],
"video_encoder_factory_template.*\.h": [
"+modules/video_coding",
],
# .cc files in api/ should not be restricted in what they can #include, # .cc files in api/ should not be restricted in what they can #include,
# so we re-add all the top-level directories here. (That's because .h # so we re-add all the top-level directories here. (That's because .h
# files leak their #includes to whoever's #including them, but .cc files # files leak their #includes to whoever's #including them, but .cc files

View file

@ -51,6 +51,11 @@ class AsyncDnsResolverResult {
virtual int GetError() const = 0; virtual int GetError() const = 0;
}; };
// The API for a single name query.
// The constructor, destructor and all functions must be called from
// the same sequence, and the callback will also be called on that sequence.
// The class guarantees that the callback will not be called if the
// resolver's destructor has been called.
class RTC_EXPORT AsyncDnsResolverInterface { class RTC_EXPORT AsyncDnsResolverInterface {
public: public:
virtual ~AsyncDnsResolverInterface() = default; virtual ~AsyncDnsResolverInterface() = default;
@ -70,7 +75,7 @@ class AsyncDnsResolverFactoryInterface {
// Creates an AsyncDnsResolver and starts resolving the name. The callback // Creates an AsyncDnsResolver and starts resolving the name. The callback
// will be called when resolution is finished. // will be called when resolution is finished.
// The callback will be called on the thread that the caller runs on. // The callback will be called on the sequence that the caller runs on.
virtual std::unique_ptr<webrtc::AsyncDnsResolverInterface> CreateAndResolve( virtual std::unique_ptr<webrtc::AsyncDnsResolverInterface> CreateAndResolve(
const rtc::SocketAddress& addr, const rtc::SocketAddress& addr,
std::function<void()> callback) = 0; std::function<void()> callback) = 0;

View file

@ -95,6 +95,7 @@ rtc_source_set("echo_control") {
rtc_source_set("echo_detector_creator") { rtc_source_set("echo_detector_creator") {
visibility = [ "*" ] visibility = [ "*" ]
allow_poison = [ "default_echo_detector" ]
sources = [ sources = [
"echo_detector_creator.cc", "echo_detector_creator.cc",
"echo_detector_creator.h", "echo_detector_creator.h",
@ -102,7 +103,7 @@ rtc_source_set("echo_detector_creator") {
deps = [ deps = [
"../../api:scoped_refptr", "../../api:scoped_refptr",
"../../modules/audio_processing:api", "../../modules/audio_processing:api",
"../../modules/audio_processing:audio_processing", "../../modules/audio_processing:residual_echo_detector",
"../../rtc_base:refcount", "../../rtc_base:refcount",
] ]
} }

View file

@ -11,8 +11,6 @@
#include "api/audio/audio_frame.h" #include "api/audio/audio_frame.h"
#include <string.h> #include <string.h>
#include <algorithm>
#include <utility>
#include "rtc_base/checks.h" #include "rtc_base/checks.h"
#include "rtc_base/time_utils.h" #include "rtc_base/time_utils.h"
@ -24,28 +22,6 @@ AudioFrame::AudioFrame() {
static_assert(sizeof(data_) == kMaxDataSizeBytes, "kMaxDataSizeBytes"); static_assert(sizeof(data_) == kMaxDataSizeBytes, "kMaxDataSizeBytes");
} }
void swap(AudioFrame& a, AudioFrame& b) {
using std::swap;
swap(a.timestamp_, b.timestamp_);
swap(a.elapsed_time_ms_, b.elapsed_time_ms_);
swap(a.ntp_time_ms_, b.ntp_time_ms_);
swap(a.samples_per_channel_, b.samples_per_channel_);
swap(a.sample_rate_hz_, b.sample_rate_hz_);
swap(a.num_channels_, b.num_channels_);
swap(a.channel_layout_, b.channel_layout_);
swap(a.speech_type_, b.speech_type_);
swap(a.vad_activity_, b.vad_activity_);
swap(a.profile_timestamp_ms_, b.profile_timestamp_ms_);
swap(a.packet_infos_, b.packet_infos_);
const size_t length_a = a.samples_per_channel_ * a.num_channels_;
const size_t length_b = b.samples_per_channel_ * b.num_channels_;
RTC_DCHECK_LE(length_a, AudioFrame::kMaxDataSizeSamples);
RTC_DCHECK_LE(length_b, AudioFrame::kMaxDataSizeSamples);
std::swap_ranges(a.data_, a.data_ + std::max(length_a, length_b), b.data_);
swap(a.muted_, b.muted_);
swap(a.absolute_capture_timestamp_ms_, b.absolute_capture_timestamp_ms_);
}
void AudioFrame::Reset() { void AudioFrame::Reset() {
ResetWithoutMuting(); ResetWithoutMuting();
muted_ = true; muted_ = true;

View file

@ -14,11 +14,8 @@
#include <stddef.h> #include <stddef.h>
#include <stdint.h> #include <stdint.h>
#include <utility>
#include "api/audio/channel_layout.h" #include "api/audio/channel_layout.h"
#include "api/rtp_packet_infos.h" #include "api/rtp_packet_infos.h"
#include "rtc_base/constructor_magic.h"
namespace webrtc { namespace webrtc {
@ -60,7 +57,8 @@ class AudioFrame {
AudioFrame(); AudioFrame();
friend void swap(AudioFrame& a, AudioFrame& b); AudioFrame(const AudioFrame&) = delete;
AudioFrame& operator=(const AudioFrame&) = delete;
// Resets all members to their default state. // Resets all members to their default state.
void Reset(); void Reset();
@ -168,8 +166,6 @@ class AudioFrame {
// capture timestamp of a received frame is found in `packet_infos_`. // capture timestamp of a received frame is found in `packet_infos_`.
// This timestamp MUST be based on the same clock as rtc::TimeMillis(). // This timestamp MUST be based on the same clock as rtc::TimeMillis().
absl::optional<int64_t> absolute_capture_timestamp_ms_; absl::optional<int64_t> absolute_capture_timestamp_ms_;
RTC_DISALLOW_COPY_AND_ASSIGN(AudioFrame);
}; };
} // namespace webrtc } // namespace webrtc

View file

@ -275,7 +275,7 @@ const char* ChannelLayoutToString(ChannelLayout layout) {
case CHANNEL_LAYOUT_BITSTREAM: case CHANNEL_LAYOUT_BITSTREAM:
return "BITSTREAM"; return "BITSTREAM";
} }
RTC_NOTREACHED() << "Invalid channel layout provided: " << layout; RTC_DCHECK_NOTREACHED() << "Invalid channel layout provided: " << layout;
return ""; return "";
} }

View file

@ -112,7 +112,7 @@ struct RTC_EXPORT EchoCanceller3Config {
bool echo_can_saturate = true; bool echo_can_saturate = true;
bool bounded_erl = false; bool bounded_erl = false;
bool erle_onset_compensation_in_dominant_nearend = false; bool erle_onset_compensation_in_dominant_nearend = false;
bool use_conservative_tail_frequency_response = false; bool use_conservative_tail_frequency_response = true;
} ep_strength; } ep_strength;
struct EchoAudibility { struct EchoAudibility {
@ -209,6 +209,7 @@ struct RTC_EXPORT EchoCanceller3Config {
int hold_duration = 50; int hold_duration = 50;
int trigger_threshold = 12; int trigger_threshold = 12;
bool use_during_initial_phase = true; bool use_during_initial_phase = true;
bool use_unbounded_echo_spectrum = true;
} dominant_nearend_detection; } dominant_nearend_detection;
struct SubbandNearendDetection { struct SubbandNearendDetection {

View file

@ -374,6 +374,9 @@ void Aec3ConfigFromJsonString(absl::string_view json_string,
ReadParam( ReadParam(
subsection, "use_during_initial_phase", subsection, "use_during_initial_phase",
&cfg.suppressor.dominant_nearend_detection.use_during_initial_phase); &cfg.suppressor.dominant_nearend_detection.use_during_initial_phase);
ReadParam(subsection, "use_unbounded_echo_spectrum",
&cfg.suppressor.dominant_nearend_detection
.use_unbounded_echo_spectrum);
} }
if (rtc::GetValueFromJsonObject(section, "subband_nearend_detection", if (rtc::GetValueFromJsonObject(section, "subband_nearend_detection",
@ -684,20 +687,20 @@ std::string Aec3ConfigToJsonString(const EchoCanceller3Config& config) {
<< config.suppressor.last_lf_smoothing_band << ","; << config.suppressor.last_lf_smoothing_band << ",";
ost << "\"last_lf_band\": " << config.suppressor.last_lf_band << ","; ost << "\"last_lf_band\": " << config.suppressor.last_lf_band << ",";
ost << "\"first_hf_band\": " << config.suppressor.first_hf_band << ","; ost << "\"first_hf_band\": " << config.suppressor.first_hf_band << ",";
{
const auto& dnd = config.suppressor.dominant_nearend_detection;
ost << "\"dominant_nearend_detection\": {"; ost << "\"dominant_nearend_detection\": {";
ost << "\"enr_threshold\": " ost << "\"enr_threshold\": " << dnd.enr_threshold << ",";
<< config.suppressor.dominant_nearend_detection.enr_threshold << ","; ost << "\"enr_exit_threshold\": " << dnd.enr_exit_threshold << ",";
ost << "\"enr_exit_threshold\": " ost << "\"snr_threshold\": " << dnd.snr_threshold << ",";
<< config.suppressor.dominant_nearend_detection.enr_exit_threshold << ","; ost << "\"hold_duration\": " << dnd.hold_duration << ",";
ost << "\"snr_threshold\": " ost << "\"trigger_threshold\": " << dnd.trigger_threshold << ",";
<< config.suppressor.dominant_nearend_detection.snr_threshold << ","; ost << "\"use_during_initial_phase\": " << dnd.use_during_initial_phase
ost << "\"hold_duration\": " << ",";
<< config.suppressor.dominant_nearend_detection.hold_duration << ","; ost << "\"use_unbounded_echo_spectrum\": "
ost << "\"trigger_threshold\": " << dnd.use_unbounded_echo_spectrum;
<< config.suppressor.dominant_nearend_detection.trigger_threshold << ",";
ost << "\"use_during_initial_phase\": "
<< config.suppressor.dominant_nearend_detection.use_during_initial_phase;
ost << "},"; ost << "},";
}
ost << "\"subband_nearend_detection\": {"; ost << "\"subband_nearend_detection\": {";
ost << "\"nearend_average_blocks\": " ost << "\"nearend_average_blocks\": "
<< config.suppressor.subband_nearend_detection.nearend_average_blocks << config.suppressor.subband_nearend_detection.nearend_average_blocks

View file

@ -133,54 +133,4 @@ TEST(AudioFrameTest, CopyFrom) {
EXPECT_EQ(0, memcmp(frame2.data(), frame1.data(), sizeof(samples))); EXPECT_EQ(0, memcmp(frame2.data(), frame1.data(), sizeof(samples)));
} }
TEST(AudioFrameTest, SwapFrames) {
AudioFrame frame1, frame2;
int16_t samples1[kNumChannelsMono * kSamplesPerChannel];
for (size_t i = 0; i < kNumChannelsMono * kSamplesPerChannel; ++i) {
samples1[i] = i;
}
frame1.UpdateFrame(kTimestamp, samples1, kSamplesPerChannel, kSampleRateHz,
AudioFrame::kPLC, AudioFrame::kVadActive,
kNumChannelsMono);
frame1.set_absolute_capture_timestamp_ms(12345678);
const auto frame1_channel_layout = frame1.channel_layout();
int16_t samples2[(kNumChannelsMono + 1) * (kSamplesPerChannel + 1)];
for (size_t i = 0; i < (kNumChannelsMono + 1) * (kSamplesPerChannel + 1);
++i) {
samples2[i] = 1000 + i;
}
frame2.UpdateFrame(kTimestamp + 1, samples2, kSamplesPerChannel + 1,
kSampleRateHz + 1, AudioFrame::kNormalSpeech,
AudioFrame::kVadPassive, kNumChannelsMono + 1);
const auto frame2_channel_layout = frame2.channel_layout();
swap(frame1, frame2);
EXPECT_EQ(kTimestamp + 1, frame1.timestamp_);
ASSERT_EQ(kSamplesPerChannel + 1, frame1.samples_per_channel_);
EXPECT_EQ(kSampleRateHz + 1, frame1.sample_rate_hz_);
EXPECT_EQ(AudioFrame::kNormalSpeech, frame1.speech_type_);
EXPECT_EQ(AudioFrame::kVadPassive, frame1.vad_activity_);
ASSERT_EQ(kNumChannelsMono + 1, frame1.num_channels_);
for (size_t i = 0; i < (kNumChannelsMono + 1) * (kSamplesPerChannel + 1);
++i) {
EXPECT_EQ(samples2[i], frame1.data()[i]);
}
EXPECT_FALSE(frame1.absolute_capture_timestamp_ms());
EXPECT_EQ(frame2_channel_layout, frame1.channel_layout());
EXPECT_EQ(kTimestamp, frame2.timestamp_);
ASSERT_EQ(kSamplesPerChannel, frame2.samples_per_channel_);
EXPECT_EQ(kSampleRateHz, frame2.sample_rate_hz_);
EXPECT_EQ(AudioFrame::kPLC, frame2.speech_type_);
EXPECT_EQ(AudioFrame::kVadActive, frame2.vad_activity_);
ASSERT_EQ(kNumChannelsMono, frame2.num_channels_);
for (size_t i = 0; i < kNumChannelsMono * kSamplesPerChannel; ++i) {
EXPECT_EQ(samples1[i], frame2.data()[i]);
}
EXPECT_EQ(12345678, frame2.absolute_capture_timestamp_ms());
EXPECT_EQ(frame1_channel_layout, frame2.channel_layout());
}
} // namespace webrtc } // namespace webrtc

View file

@ -32,6 +32,7 @@ rtc_library("audio_codecs_api") {
"..:array_view", "..:array_view",
"..:bitrate_allocation", "..:bitrate_allocation",
"..:scoped_refptr", "..:scoped_refptr",
"../../api:webrtc_key_value_config",
"../../rtc_base:checks", "../../rtc_base:checks",
"../../rtc_base:rtc_base_approved", "../../rtc_base:rtc_base_approved",
"../../rtc_base:sanitizer", "../../rtc_base:sanitizer",

View file

@ -21,6 +21,7 @@ rtc_library("audio_encoder_L16") {
] ]
deps = [ deps = [
"..:audio_codecs_api", "..:audio_codecs_api",
"../../../api:webrtc_key_value_config",
"../../../modules/audio_coding:pcm16b", "../../../modules/audio_coding:pcm16b",
"../../../rtc_base:rtc_base_approved", "../../../rtc_base:rtc_base_approved",
"../../../rtc_base:safe_minmax", "../../../rtc_base:safe_minmax",
@ -41,6 +42,7 @@ rtc_library("audio_decoder_L16") {
] ]
deps = [ deps = [
"..:audio_codecs_api", "..:audio_codecs_api",
"../../../api:webrtc_key_value_config",
"../../../modules/audio_coding:pcm16b", "../../../modules/audio_coding:pcm16b",
"../../../rtc_base:rtc_base_approved", "../../../rtc_base:rtc_base_approved",
"../../../rtc_base/system:rtc_export", "../../../rtc_base/system:rtc_export",

View file

@ -24,9 +24,10 @@ absl::optional<AudioDecoderL16::Config> AudioDecoderL16::SdpToConfig(
Config config; Config config;
config.sample_rate_hz = format.clockrate_hz; config.sample_rate_hz = format.clockrate_hz;
config.num_channels = rtc::checked_cast<int>(format.num_channels); config.num_channels = rtc::checked_cast<int>(format.num_channels);
return absl::EqualsIgnoreCase(format.name, "L16") && config.IsOk() if (absl::EqualsIgnoreCase(format.name, "L16") && config.IsOk()) {
? absl::optional<Config>(config) return config;
: absl::nullopt; }
return absl::nullopt;
} }
void AudioDecoderL16::AppendSupportedDecoders( void AudioDecoderL16::AppendSupportedDecoders(
@ -37,10 +38,13 @@ void AudioDecoderL16::AppendSupportedDecoders(
std::unique_ptr<AudioDecoder> AudioDecoderL16::MakeAudioDecoder( std::unique_ptr<AudioDecoder> AudioDecoderL16::MakeAudioDecoder(
const Config& config, const Config& config,
absl::optional<AudioCodecPairId> /*codec_pair_id*/) { absl::optional<AudioCodecPairId> /*codec_pair_id*/,
return config.IsOk() ? std::make_unique<AudioDecoderPcm16B>( const WebRtcKeyValueConfig* field_trials) {
config.sample_rate_hz, config.num_channels) if (!config.IsOk()) {
: nullptr; return nullptr;
}
return std::make_unique<AudioDecoderPcm16B>(config.sample_rate_hz,
config.num_channels);
} }
} // namespace webrtc } // namespace webrtc

View file

@ -18,6 +18,7 @@
#include "api/audio_codecs/audio_codec_pair_id.h" #include "api/audio_codecs/audio_codec_pair_id.h"
#include "api/audio_codecs/audio_decoder.h" #include "api/audio_codecs/audio_decoder.h"
#include "api/audio_codecs/audio_format.h" #include "api/audio_codecs/audio_format.h"
#include "api/webrtc_key_value_config.h"
#include "rtc_base/system/rtc_export.h" #include "rtc_base/system/rtc_export.h"
namespace webrtc { namespace webrtc {
@ -29,7 +30,8 @@ struct RTC_EXPORT AudioDecoderL16 {
bool IsOk() const { bool IsOk() const {
return (sample_rate_hz == 8000 || sample_rate_hz == 16000 || return (sample_rate_hz == 8000 || sample_rate_hz == 16000 ||
sample_rate_hz == 32000 || sample_rate_hz == 48000) && sample_rate_hz == 32000 || sample_rate_hz == 48000) &&
num_channels >= 1; (num_channels >= 1 &&
num_channels <= AudioDecoder::kMaxNumberOfChannels);
} }
int sample_rate_hz = 8000; int sample_rate_hz = 8000;
int num_channels = 1; int num_channels = 1;
@ -38,7 +40,8 @@ struct RTC_EXPORT AudioDecoderL16 {
static void AppendSupportedDecoders(std::vector<AudioCodecSpec>* specs); static void AppendSupportedDecoders(std::vector<AudioCodecSpec>* specs);
static std::unique_ptr<AudioDecoder> MakeAudioDecoder( static std::unique_ptr<AudioDecoder> MakeAudioDecoder(
const Config& config, const Config& config,
absl::optional<AudioCodecPairId> codec_pair_id = absl::nullopt); absl::optional<AudioCodecPairId> codec_pair_id = absl::nullopt,
const WebRtcKeyValueConfig* field_trials = nullptr);
}; };
} // namespace webrtc } // namespace webrtc

View file

@ -24,6 +24,7 @@ namespace webrtc {
absl::optional<AudioEncoderL16::Config> AudioEncoderL16::SdpToConfig( absl::optional<AudioEncoderL16::Config> AudioEncoderL16::SdpToConfig(
const SdpAudioFormat& format) { const SdpAudioFormat& format) {
if (!rtc::IsValueInRangeForNumericType<int>(format.num_channels)) { if (!rtc::IsValueInRangeForNumericType<int>(format.num_channels)) {
RTC_DCHECK_NOTREACHED();
return absl::nullopt; return absl::nullopt;
} }
Config config; Config config;
@ -36,9 +37,10 @@ absl::optional<AudioEncoderL16::Config> AudioEncoderL16::SdpToConfig(
config.frame_size_ms = rtc::SafeClamp(10 * (*ptime / 10), 10, 60); config.frame_size_ms = rtc::SafeClamp(10 * (*ptime / 10), 10, 60);
} }
} }
return absl::EqualsIgnoreCase(format.name, "L16") && config.IsOk() if (absl::EqualsIgnoreCase(format.name, "L16") && config.IsOk()) {
? absl::optional<Config>(config) return config;
: absl::nullopt; }
return absl::nullopt;
} }
void AudioEncoderL16::AppendSupportedEncoders( void AudioEncoderL16::AppendSupportedEncoders(
@ -58,13 +60,17 @@ AudioCodecInfo AudioEncoderL16::QueryAudioEncoder(
std::unique_ptr<AudioEncoder> AudioEncoderL16::MakeAudioEncoder( std::unique_ptr<AudioEncoder> AudioEncoderL16::MakeAudioEncoder(
const AudioEncoderL16::Config& config, const AudioEncoderL16::Config& config,
int payload_type, int payload_type,
absl::optional<AudioCodecPairId> /*codec_pair_id*/) { absl::optional<AudioCodecPairId> /*codec_pair_id*/,
RTC_DCHECK(config.IsOk()); const WebRtcKeyValueConfig* field_trials) {
AudioEncoderPcm16B::Config c; AudioEncoderPcm16B::Config c;
c.sample_rate_hz = config.sample_rate_hz; c.sample_rate_hz = config.sample_rate_hz;
c.num_channels = config.num_channels; c.num_channels = config.num_channels;
c.frame_size_ms = config.frame_size_ms; c.frame_size_ms = config.frame_size_ms;
c.payload_type = payload_type; c.payload_type = payload_type;
if (!config.IsOk()) {
RTC_DCHECK_NOTREACHED();
return nullptr;
}
return std::make_unique<AudioEncoderPcm16B>(c); return std::make_unique<AudioEncoderPcm16B>(c);
} }

View file

@ -18,6 +18,7 @@
#include "api/audio_codecs/audio_codec_pair_id.h" #include "api/audio_codecs/audio_codec_pair_id.h"
#include "api/audio_codecs/audio_encoder.h" #include "api/audio_codecs/audio_encoder.h"
#include "api/audio_codecs/audio_format.h" #include "api/audio_codecs/audio_format.h"
#include "api/webrtc_key_value_config.h"
#include "rtc_base/system/rtc_export.h" #include "rtc_base/system/rtc_export.h"
namespace webrtc { namespace webrtc {
@ -29,7 +30,9 @@ struct RTC_EXPORT AudioEncoderL16 {
bool IsOk() const { bool IsOk() const {
return (sample_rate_hz == 8000 || sample_rate_hz == 16000 || return (sample_rate_hz == 8000 || sample_rate_hz == 16000 ||
sample_rate_hz == 32000 || sample_rate_hz == 48000) && sample_rate_hz == 32000 || sample_rate_hz == 48000) &&
num_channels >= 1 && frame_size_ms > 0 && frame_size_ms <= 120 && num_channels >= 1 &&
num_channels <= AudioEncoder::kMaxNumberOfChannels &&
frame_size_ms > 0 && frame_size_ms <= 120 &&
frame_size_ms % 10 == 0; frame_size_ms % 10 == 0;
} }
int sample_rate_hz = 8000; int sample_rate_hz = 8000;
@ -42,7 +45,8 @@ struct RTC_EXPORT AudioEncoderL16 {
static std::unique_ptr<AudioEncoder> MakeAudioEncoder( static std::unique_ptr<AudioEncoder> MakeAudioEncoder(
const Config& config, const Config& config,
int payload_type, int payload_type,
absl::optional<AudioCodecPairId> codec_pair_id = absl::nullopt); absl::optional<AudioCodecPairId> codec_pair_id = absl::nullopt,
const WebRtcKeyValueConfig* field_trials = nullptr);
}; };
} // namespace webrtc } // namespace webrtc

View file

@ -161,9 +161,10 @@ AudioDecoder::SpeechType AudioDecoder::ConvertSpeechType(int16_t type) {
case 2: case 2:
return kComfortNoise; return kComfortNoise;
default: default:
RTC_NOTREACHED(); RTC_DCHECK_NOTREACHED();
return kSpeech; return kSpeech;
} }
} }
constexpr int AudioDecoder::kMaxNumberOfChannels;
} // namespace webrtc } // namespace webrtc

View file

@ -20,7 +20,6 @@
#include "absl/types/optional.h" #include "absl/types/optional.h"
#include "api/array_view.h" #include "api/array_view.h"
#include "rtc_base/buffer.h" #include "rtc_base/buffer.h"
#include "rtc_base/constructor_magic.h"
namespace webrtc { namespace webrtc {
@ -37,6 +36,9 @@ class AudioDecoder {
AudioDecoder() = default; AudioDecoder() = default;
virtual ~AudioDecoder() = default; virtual ~AudioDecoder() = default;
AudioDecoder(const AudioDecoder&) = delete;
AudioDecoder& operator=(const AudioDecoder&) = delete;
class EncodedAudioFrame { class EncodedAudioFrame {
public: public:
struct DecodeResult { struct DecodeResult {
@ -170,6 +172,9 @@ class AudioDecoder {
// during the lifetime of the decoder. // during the lifetime of the decoder.
virtual size_t Channels() const = 0; virtual size_t Channels() const = 0;
// The maximum number of audio channels supported by WebRTC decoders.
static constexpr int kMaxNumberOfChannels = 24;
protected: protected:
static SpeechType ConvertSpeechType(int16_t type); static SpeechType ConvertSpeechType(int16_t type);
@ -184,9 +189,6 @@ class AudioDecoder {
int sample_rate_hz, int sample_rate_hz,
int16_t* decoded, int16_t* decoded,
SpeechType* speech_type); SpeechType* speech_type);
private:
RTC_DISALLOW_COPY_AND_ASSIGN(AudioDecoder);
}; };
} // namespace webrtc } // namespace webrtc

View file

@ -16,6 +16,7 @@
#include "api/audio_codecs/audio_decoder_factory.h" #include "api/audio_codecs/audio_decoder_factory.h"
#include "api/scoped_refptr.h" #include "api/scoped_refptr.h"
#include "api/webrtc_key_value_config.h"
#include "rtc_base/ref_counted_object.h" #include "rtc_base/ref_counted_object.h"
namespace webrtc { namespace webrtc {
@ -32,7 +33,8 @@ struct Helper<> {
static bool IsSupportedDecoder(const SdpAudioFormat& format) { return false; } static bool IsSupportedDecoder(const SdpAudioFormat& format) { return false; }
static std::unique_ptr<AudioDecoder> MakeAudioDecoder( static std::unique_ptr<AudioDecoder> MakeAudioDecoder(
const SdpAudioFormat& format, const SdpAudioFormat& format,
absl::optional<AudioCodecPairId> codec_pair_id) { absl::optional<AudioCodecPairId> codec_pair_id,
const WebRtcKeyValueConfig* field_trials) {
return nullptr; return nullptr;
} }
}; };
@ -55,16 +57,22 @@ struct Helper<T, Ts...> {
} }
static std::unique_ptr<AudioDecoder> MakeAudioDecoder( static std::unique_ptr<AudioDecoder> MakeAudioDecoder(
const SdpAudioFormat& format, const SdpAudioFormat& format,
absl::optional<AudioCodecPairId> codec_pair_id) { absl::optional<AudioCodecPairId> codec_pair_id,
const WebRtcKeyValueConfig* field_trials) {
auto opt_config = T::SdpToConfig(format); auto opt_config = T::SdpToConfig(format);
return opt_config ? T::MakeAudioDecoder(*opt_config, codec_pair_id) return opt_config ? T::MakeAudioDecoder(*opt_config, codec_pair_id)
: Helper<Ts...>::MakeAudioDecoder(format, codec_pair_id); : Helper<Ts...>::MakeAudioDecoder(format, codec_pair_id,
field_trials);
} }
}; };
template <typename... Ts> template <typename... Ts>
class AudioDecoderFactoryT : public AudioDecoderFactory { class AudioDecoderFactoryT : public AudioDecoderFactory {
public: public:
explicit AudioDecoderFactoryT(const WebRtcKeyValueConfig* field_trials) {
field_trials_ = field_trials;
}
std::vector<AudioCodecSpec> GetSupportedDecoders() override { std::vector<AudioCodecSpec> GetSupportedDecoders() override {
std::vector<AudioCodecSpec> specs; std::vector<AudioCodecSpec> specs;
Helper<Ts...>::AppendSupportedDecoders(&specs); Helper<Ts...>::AppendSupportedDecoders(&specs);
@ -78,8 +86,11 @@ class AudioDecoderFactoryT : public AudioDecoderFactory {
std::unique_ptr<AudioDecoder> MakeAudioDecoder( std::unique_ptr<AudioDecoder> MakeAudioDecoder(
const SdpAudioFormat& format, const SdpAudioFormat& format,
absl::optional<AudioCodecPairId> codec_pair_id) override { absl::optional<AudioCodecPairId> codec_pair_id) override {
return Helper<Ts...>::MakeAudioDecoder(format, codec_pair_id); return Helper<Ts...>::MakeAudioDecoder(format, codec_pair_id,
field_trials_);
} }
const WebRtcKeyValueConfig* field_trials_;
}; };
} // namespace audio_decoder_factory_template_impl } // namespace audio_decoder_factory_template_impl
@ -115,7 +126,8 @@ class AudioDecoderFactoryT : public AudioDecoderFactory {
// TODO(kwiberg): Point at CreateBuiltinAudioDecoderFactory() for an example of // TODO(kwiberg): Point at CreateBuiltinAudioDecoderFactory() for an example of
// how it is used. // how it is used.
template <typename... Ts> template <typename... Ts>
rtc::scoped_refptr<AudioDecoderFactory> CreateAudioDecoderFactory() { rtc::scoped_refptr<AudioDecoderFactory> CreateAudioDecoderFactory(
const WebRtcKeyValueConfig* field_trials = nullptr) {
// There's no technical reason we couldn't allow zero template parameters, // There's no technical reason we couldn't allow zero template parameters,
// but such a factory couldn't create any decoders, and callers can do this // but such a factory couldn't create any decoders, and callers can do this
// by mistake by simply forgetting the <> altogether. So we forbid it in // by mistake by simply forgetting the <> altogether. So we forbid it in
@ -124,7 +136,8 @@ rtc::scoped_refptr<AudioDecoderFactory> CreateAudioDecoderFactory() {
"Caller must give at least one template parameter"); "Caller must give at least one template parameter");
return rtc::make_ref_counted< return rtc::make_ref_counted<
audio_decoder_factory_template_impl::AudioDecoderFactoryT<Ts...>>(); audio_decoder_factory_template_impl::AudioDecoderFactoryT<Ts...>>(
field_trials);
} }
} // namespace webrtc } // namespace webrtc

View file

@ -83,7 +83,7 @@ void AudioEncoder::OnReceivedUplinkPacketLossFraction(
void AudioEncoder::OnReceivedUplinkRecoverablePacketLossFraction( void AudioEncoder::OnReceivedUplinkRecoverablePacketLossFraction(
float uplink_recoverable_packet_loss_fraction) { float uplink_recoverable_packet_loss_fraction) {
RTC_NOTREACHED(); RTC_DCHECK_NOTREACHED();
} }
void AudioEncoder::OnReceivedTargetAudioBitrate(int target_audio_bitrate_bps) { void AudioEncoder::OnReceivedTargetAudioBitrate(int target_audio_bitrate_bps) {
@ -110,4 +110,5 @@ ANAStats AudioEncoder::GetANAStats() const {
return ANAStats(); return ANAStats();
} }
constexpr int AudioEncoder::kMaxNumberOfChannels;
} // namespace webrtc } // namespace webrtc

View file

@ -276,6 +276,9 @@ class AudioEncoder {
virtual absl::optional<std::pair<TimeDelta, TimeDelta>> GetFrameLengthRange() virtual absl::optional<std::pair<TimeDelta, TimeDelta>> GetFrameLengthRange()
const = 0; const = 0;
// The maximum number of audio channels supported by WebRTC encoders.
static constexpr int kMaxNumberOfChannels = 24;
// RingRTC Change to configure OPUS // RingRTC Change to configure OPUS
virtual bool Configure(const Config& config) { virtual bool Configure(const Config& config) {
RTC_LOG(LS_WARNING) << "Default AudioEncoder::Configure(...) does nothing!"; RTC_LOG(LS_WARNING) << "Default AudioEncoder::Configure(...) does nothing!";

View file

@ -16,6 +16,7 @@
#include "api/audio_codecs/audio_encoder_factory.h" #include "api/audio_codecs/audio_encoder_factory.h"
#include "api/scoped_refptr.h" #include "api/scoped_refptr.h"
#include "api/webrtc_key_value_config.h"
#include "rtc_base/ref_counted_object.h" #include "rtc_base/ref_counted_object.h"
namespace webrtc { namespace webrtc {
@ -36,7 +37,8 @@ struct Helper<> {
static std::unique_ptr<AudioEncoder> MakeAudioEncoder( static std::unique_ptr<AudioEncoder> MakeAudioEncoder(
int payload_type, int payload_type,
const SdpAudioFormat& format, const SdpAudioFormat& format,
absl::optional<AudioCodecPairId> codec_pair_id) { absl::optional<AudioCodecPairId> codec_pair_id,
const WebRtcKeyValueConfig* field_trials) {
return nullptr; return nullptr;
} }
}; };
@ -63,13 +65,14 @@ struct Helper<T, Ts...> {
static std::unique_ptr<AudioEncoder> MakeAudioEncoder( static std::unique_ptr<AudioEncoder> MakeAudioEncoder(
int payload_type, int payload_type,
const SdpAudioFormat& format, const SdpAudioFormat& format,
absl::optional<AudioCodecPairId> codec_pair_id) { absl::optional<AudioCodecPairId> codec_pair_id,
const WebRtcKeyValueConfig* field_trials) {
auto opt_config = T::SdpToConfig(format); auto opt_config = T::SdpToConfig(format);
if (opt_config) { if (opt_config) {
return T::MakeAudioEncoder(*opt_config, payload_type, codec_pair_id); return T::MakeAudioEncoder(*opt_config, payload_type, codec_pair_id);
} else { } else {
return Helper<Ts...>::MakeAudioEncoder(payload_type, format, return Helper<Ts...>::MakeAudioEncoder(payload_type, format,
codec_pair_id); codec_pair_id, field_trials);
} }
} }
}; };
@ -77,6 +80,10 @@ struct Helper<T, Ts...> {
template <typename... Ts> template <typename... Ts>
class AudioEncoderFactoryT : public AudioEncoderFactory { class AudioEncoderFactoryT : public AudioEncoderFactory {
public: public:
explicit AudioEncoderFactoryT(const WebRtcKeyValueConfig* field_trials) {
field_trials_ = field_trials;
}
std::vector<AudioCodecSpec> GetSupportedEncoders() override { std::vector<AudioCodecSpec> GetSupportedEncoders() override {
std::vector<AudioCodecSpec> specs; std::vector<AudioCodecSpec> specs;
Helper<Ts...>::AppendSupportedEncoders(&specs); Helper<Ts...>::AppendSupportedEncoders(&specs);
@ -92,8 +99,11 @@ class AudioEncoderFactoryT : public AudioEncoderFactory {
int payload_type, int payload_type,
const SdpAudioFormat& format, const SdpAudioFormat& format,
absl::optional<AudioCodecPairId> codec_pair_id) override { absl::optional<AudioCodecPairId> codec_pair_id) override {
return Helper<Ts...>::MakeAudioEncoder(payload_type, format, codec_pair_id); return Helper<Ts...>::MakeAudioEncoder(payload_type, format, codec_pair_id,
field_trials_);
} }
const WebRtcKeyValueConfig* field_trials_;
}; };
} // namespace audio_encoder_factory_template_impl } // namespace audio_encoder_factory_template_impl
@ -134,7 +144,8 @@ class AudioEncoderFactoryT : public AudioEncoderFactory {
// TODO(kwiberg): Point at CreateBuiltinAudioEncoderFactory() for an example of // TODO(kwiberg): Point at CreateBuiltinAudioEncoderFactory() for an example of
// how it is used. // how it is used.
template <typename... Ts> template <typename... Ts>
rtc::scoped_refptr<AudioEncoderFactory> CreateAudioEncoderFactory() { rtc::scoped_refptr<AudioEncoderFactory> CreateAudioEncoderFactory(
const WebRtcKeyValueConfig* field_trials = nullptr) {
// There's no technical reason we couldn't allow zero template parameters, // There's no technical reason we couldn't allow zero template parameters,
// but such a factory couldn't create any encoders, and callers can do this // but such a factory couldn't create any encoders, and callers can do this
// by mistake by simply forgetting the <> altogether. So we forbid it in // by mistake by simply forgetting the <> altogether. So we forbid it in
@ -143,7 +154,8 @@ rtc::scoped_refptr<AudioEncoderFactory> CreateAudioEncoderFactory() {
"Caller must give at least one template parameter"); "Caller must give at least one template parameter");
return rtc::make_ref_counted< return rtc::make_ref_counted<
audio_encoder_factory_template_impl::AudioEncoderFactoryT<Ts...>>(); audio_encoder_factory_template_impl::AudioEncoderFactoryT<Ts...>>(
field_trials);
} }
} // namespace webrtc } // namespace webrtc

View file

@ -47,8 +47,10 @@ struct NotAdvertised {
static std::unique_ptr<AudioEncoder> MakeAudioEncoder( static std::unique_ptr<AudioEncoder> MakeAudioEncoder(
const Config& config, const Config& config,
int payload_type, int payload_type,
absl::optional<AudioCodecPairId> codec_pair_id = absl::nullopt) { absl::optional<AudioCodecPairId> codec_pair_id = absl::nullopt,
return T::MakeAudioEncoder(config, payload_type, codec_pair_id); const WebRtcKeyValueConfig* field_trials = nullptr) {
return T::MakeAudioEncoder(config, payload_type, codec_pair_id,
field_trials);
} }
}; };

View file

@ -21,6 +21,7 @@ rtc_library("audio_encoder_g711") {
] ]
deps = [ deps = [
"..:audio_codecs_api", "..:audio_codecs_api",
"../../../api:webrtc_key_value_config",
"../../../modules/audio_coding:g711", "../../../modules/audio_coding:g711",
"../../../rtc_base:rtc_base_approved", "../../../rtc_base:rtc_base_approved",
"../../../rtc_base:safe_minmax", "../../../rtc_base:safe_minmax",
@ -41,6 +42,7 @@ rtc_library("audio_decoder_g711") {
] ]
deps = [ deps = [
"..:audio_codecs_api", "..:audio_codecs_api",
"../../../api:webrtc_key_value_config",
"../../../modules/audio_coding:g711", "../../../modules/audio_coding:g711",
"../../../rtc_base:rtc_base_approved", "../../../rtc_base:rtc_base_approved",
"../../../rtc_base/system:rtc_export", "../../../rtc_base/system:rtc_export",

View file

@ -28,7 +28,10 @@ absl::optional<AudioDecoderG711::Config> AudioDecoderG711::SdpToConfig(
Config config; Config config;
config.type = is_pcmu ? Config::Type::kPcmU : Config::Type::kPcmA; config.type = is_pcmu ? Config::Type::kPcmU : Config::Type::kPcmA;
config.num_channels = rtc::dchecked_cast<int>(format.num_channels); config.num_channels = rtc::dchecked_cast<int>(format.num_channels);
RTC_DCHECK(config.IsOk()); if (!config.IsOk()) {
RTC_DCHECK_NOTREACHED();
return absl::nullopt;
}
return config; return config;
} else { } else {
return absl::nullopt; return absl::nullopt;
@ -45,14 +48,19 @@ void AudioDecoderG711::AppendSupportedDecoders(
std::unique_ptr<AudioDecoder> AudioDecoderG711::MakeAudioDecoder( std::unique_ptr<AudioDecoder> AudioDecoderG711::MakeAudioDecoder(
const Config& config, const Config& config,
absl::optional<AudioCodecPairId> /*codec_pair_id*/) { absl::optional<AudioCodecPairId> /*codec_pair_id*/,
RTC_DCHECK(config.IsOk()); const WebRtcKeyValueConfig* field_trials) {
if (!config.IsOk()) {
RTC_DCHECK_NOTREACHED();
return nullptr;
}
switch (config.type) { switch (config.type) {
case Config::Type::kPcmU: case Config::Type::kPcmU:
return std::make_unique<AudioDecoderPcmU>(config.num_channels); return std::make_unique<AudioDecoderPcmU>(config.num_channels);
case Config::Type::kPcmA: case Config::Type::kPcmA:
return std::make_unique<AudioDecoderPcmA>(config.num_channels); return std::make_unique<AudioDecoderPcmA>(config.num_channels);
default: default:
RTC_DCHECK_NOTREACHED();
return nullptr; return nullptr;
} }
} }

View file

@ -18,6 +18,7 @@
#include "api/audio_codecs/audio_codec_pair_id.h" #include "api/audio_codecs/audio_codec_pair_id.h"
#include "api/audio_codecs/audio_decoder.h" #include "api/audio_codecs/audio_decoder.h"
#include "api/audio_codecs/audio_format.h" #include "api/audio_codecs/audio_format.h"
#include "api/webrtc_key_value_config.h"
#include "rtc_base/system/rtc_export.h" #include "rtc_base/system/rtc_export.h"
namespace webrtc { namespace webrtc {
@ -28,7 +29,9 @@ struct RTC_EXPORT AudioDecoderG711 {
struct Config { struct Config {
enum class Type { kPcmU, kPcmA }; enum class Type { kPcmU, kPcmA };
bool IsOk() const { bool IsOk() const {
return (type == Type::kPcmU || type == Type::kPcmA) && num_channels >= 1; return (type == Type::kPcmU || type == Type::kPcmA) &&
num_channels >= 1 &&
num_channels <= AudioDecoder::kMaxNumberOfChannels;
} }
Type type; Type type;
int num_channels; int num_channels;
@ -37,7 +40,8 @@ struct RTC_EXPORT AudioDecoderG711 {
static void AppendSupportedDecoders(std::vector<AudioCodecSpec>* specs); static void AppendSupportedDecoders(std::vector<AudioCodecSpec>* specs);
static std::unique_ptr<AudioDecoder> MakeAudioDecoder( static std::unique_ptr<AudioDecoder> MakeAudioDecoder(
const Config& config, const Config& config,
absl::optional<AudioCodecPairId> codec_pair_id = absl::nullopt); absl::optional<AudioCodecPairId> codec_pair_id = absl::nullopt,
const WebRtcKeyValueConfig* field_trials = nullptr);
}; };
} // namespace webrtc } // namespace webrtc

View file

@ -38,7 +38,10 @@ absl::optional<AudioEncoderG711::Config> AudioEncoderG711::SdpToConfig(
config.frame_size_ms = rtc::SafeClamp(10 * (*ptime / 10), 10, 60); config.frame_size_ms = rtc::SafeClamp(10 * (*ptime / 10), 10, 60);
} }
} }
RTC_DCHECK(config.IsOk()); if (!config.IsOk()) {
RTC_DCHECK_NOTREACHED();
return absl::nullopt;
}
return config; return config;
} else { } else {
return absl::nullopt; return absl::nullopt;
@ -62,8 +65,12 @@ AudioCodecInfo AudioEncoderG711::QueryAudioEncoder(const Config& config) {
std::unique_ptr<AudioEncoder> AudioEncoderG711::MakeAudioEncoder( std::unique_ptr<AudioEncoder> AudioEncoderG711::MakeAudioEncoder(
const Config& config, const Config& config,
int payload_type, int payload_type,
absl::optional<AudioCodecPairId> /*codec_pair_id*/) { absl::optional<AudioCodecPairId> /*codec_pair_id*/,
RTC_DCHECK(config.IsOk()); const WebRtcKeyValueConfig* field_trials) {
if (!config.IsOk()) {
RTC_DCHECK_NOTREACHED();
return nullptr;
}
switch (config.type) { switch (config.type) {
case Config::Type::kPcmU: { case Config::Type::kPcmU: {
AudioEncoderPcmU::Config impl_config; AudioEncoderPcmU::Config impl_config;
@ -80,6 +87,7 @@ std::unique_ptr<AudioEncoder> AudioEncoderG711::MakeAudioEncoder(
return std::make_unique<AudioEncoderPcmA>(impl_config); return std::make_unique<AudioEncoderPcmA>(impl_config);
} }
default: { default: {
RTC_DCHECK_NOTREACHED();
return nullptr; return nullptr;
} }
} }

View file

@ -18,6 +18,7 @@
#include "api/audio_codecs/audio_codec_pair_id.h" #include "api/audio_codecs/audio_codec_pair_id.h"
#include "api/audio_codecs/audio_encoder.h" #include "api/audio_codecs/audio_encoder.h"
#include "api/audio_codecs/audio_format.h" #include "api/audio_codecs/audio_format.h"
#include "api/webrtc_key_value_config.h"
#include "rtc_base/system/rtc_export.h" #include "rtc_base/system/rtc_export.h"
namespace webrtc { namespace webrtc {
@ -29,7 +30,9 @@ struct RTC_EXPORT AudioEncoderG711 {
enum class Type { kPcmU, kPcmA }; enum class Type { kPcmU, kPcmA };
bool IsOk() const { bool IsOk() const {
return (type == Type::kPcmU || type == Type::kPcmA) && return (type == Type::kPcmU || type == Type::kPcmA) &&
frame_size_ms > 0 && frame_size_ms % 10 == 0 && num_channels >= 1; frame_size_ms > 0 && frame_size_ms % 10 == 0 &&
num_channels >= 1 &&
num_channels <= AudioEncoder::kMaxNumberOfChannels;
} }
Type type = Type::kPcmU; Type type = Type::kPcmU;
int num_channels = 1; int num_channels = 1;
@ -42,7 +45,8 @@ struct RTC_EXPORT AudioEncoderG711 {
static std::unique_ptr<AudioEncoder> MakeAudioEncoder( static std::unique_ptr<AudioEncoder> MakeAudioEncoder(
const Config& config, const Config& config,
int payload_type, int payload_type,
absl::optional<AudioCodecPairId> codec_pair_id = absl::nullopt); absl::optional<AudioCodecPairId> codec_pair_id = absl::nullopt,
const WebRtcKeyValueConfig* field_trials = nullptr);
}; };
} // namespace webrtc } // namespace webrtc

View file

@ -27,6 +27,7 @@ rtc_library("audio_encoder_g722") {
deps = [ deps = [
":audio_encoder_g722_config", ":audio_encoder_g722_config",
"..:audio_codecs_api", "..:audio_codecs_api",
"../../../api:webrtc_key_value_config",
"../../../modules/audio_coding:g722", "../../../modules/audio_coding:g722",
"../../../rtc_base:rtc_base_approved", "../../../rtc_base:rtc_base_approved",
"../../../rtc_base:safe_minmax", "../../../rtc_base:safe_minmax",
@ -47,6 +48,7 @@ rtc_library("audio_decoder_g722") {
] ]
deps = [ deps = [
"..:audio_codecs_api", "..:audio_codecs_api",
"../../../api:webrtc_key_value_config",
"../../../modules/audio_coding:g722", "../../../modules/audio_coding:g722",
"../../../rtc_base:rtc_base_approved", "../../../rtc_base:rtc_base_approved",
"../../../rtc_base/system:rtc_export", "../../../rtc_base/system:rtc_export",

View file

@ -21,12 +21,12 @@ namespace webrtc {
absl::optional<AudioDecoderG722::Config> AudioDecoderG722::SdpToConfig( absl::optional<AudioDecoderG722::Config> AudioDecoderG722::SdpToConfig(
const SdpAudioFormat& format) { const SdpAudioFormat& format) {
return absl::EqualsIgnoreCase(format.name, "G722") && if (absl::EqualsIgnoreCase(format.name, "G722") &&
format.clockrate_hz == 8000 && format.clockrate_hz == 8000 &&
(format.num_channels == 1 || format.num_channels == 2) (format.num_channels == 1 || format.num_channels == 2)) {
? absl::optional<Config>( return Config{rtc::dchecked_cast<int>(format.num_channels)};
Config{rtc::dchecked_cast<int>(format.num_channels)}) }
: absl::nullopt; return absl::nullopt;
} }
void AudioDecoderG722::AppendSupportedDecoders( void AudioDecoderG722::AppendSupportedDecoders(
@ -37,13 +37,19 @@ void AudioDecoderG722::AppendSupportedDecoders(
std::unique_ptr<AudioDecoder> AudioDecoderG722::MakeAudioDecoder( std::unique_ptr<AudioDecoder> AudioDecoderG722::MakeAudioDecoder(
Config config, Config config,
absl::optional<AudioCodecPairId> /*codec_pair_id*/) { absl::optional<AudioCodecPairId> /*codec_pair_id*/,
const WebRtcKeyValueConfig* field_trials) {
if (!config.IsOk()) {
RTC_DCHECK_NOTREACHED();
return nullptr;
}
switch (config.num_channels) { switch (config.num_channels) {
case 1: case 1:
return std::make_unique<AudioDecoderG722Impl>(); return std::make_unique<AudioDecoderG722Impl>();
case 2: case 2:
return std::make_unique<AudioDecoderG722StereoImpl>(); return std::make_unique<AudioDecoderG722StereoImpl>();
default: default:
RTC_DCHECK_NOTREACHED();
return nullptr; return nullptr;
} }
} }

View file

@ -18,6 +18,7 @@
#include "api/audio_codecs/audio_codec_pair_id.h" #include "api/audio_codecs/audio_codec_pair_id.h"
#include "api/audio_codecs/audio_decoder.h" #include "api/audio_codecs/audio_decoder.h"
#include "api/audio_codecs/audio_format.h" #include "api/audio_codecs/audio_format.h"
#include "api/webrtc_key_value_config.h"
#include "rtc_base/system/rtc_export.h" #include "rtc_base/system/rtc_export.h"
namespace webrtc { namespace webrtc {
@ -33,7 +34,8 @@ struct RTC_EXPORT AudioDecoderG722 {
static void AppendSupportedDecoders(std::vector<AudioCodecSpec>* specs); static void AppendSupportedDecoders(std::vector<AudioCodecSpec>* specs);
static std::unique_ptr<AudioDecoder> MakeAudioDecoder( static std::unique_ptr<AudioDecoder> MakeAudioDecoder(
Config config, Config config,
absl::optional<AudioCodecPairId> codec_pair_id = absl::nullopt); absl::optional<AudioCodecPairId> codec_pair_id = absl::nullopt,
const WebRtcKeyValueConfig* field_trials = nullptr);
}; };
} // namespace webrtc } // namespace webrtc

View file

@ -38,8 +38,11 @@ absl::optional<AudioEncoderG722Config> AudioEncoderG722::SdpToConfig(
config.frame_size_ms = rtc::SafeClamp<int>(whole_packets * 10, 10, 60); config.frame_size_ms = rtc::SafeClamp<int>(whole_packets * 10, 10, 60);
} }
} }
return config.IsOk() ? absl::optional<AudioEncoderG722Config>(config) if (!config.IsOk()) {
: absl::nullopt; RTC_DCHECK_NOTREACHED();
return absl::nullopt;
}
return config;
} }
void AudioEncoderG722::AppendSupportedEncoders( void AudioEncoderG722::AppendSupportedEncoders(
@ -60,8 +63,12 @@ AudioCodecInfo AudioEncoderG722::QueryAudioEncoder(
std::unique_ptr<AudioEncoder> AudioEncoderG722::MakeAudioEncoder( std::unique_ptr<AudioEncoder> AudioEncoderG722::MakeAudioEncoder(
const AudioEncoderG722Config& config, const AudioEncoderG722Config& config,
int payload_type, int payload_type,
absl::optional<AudioCodecPairId> /*codec_pair_id*/) { absl::optional<AudioCodecPairId> /*codec_pair_id*/,
RTC_DCHECK(config.IsOk()); const WebRtcKeyValueConfig* field_trials) {
if (!config.IsOk()) {
RTC_DCHECK_NOTREACHED();
return nullptr;
}
return std::make_unique<AudioEncoderG722Impl>(config, payload_type); return std::make_unique<AudioEncoderG722Impl>(config, payload_type);
} }

View file

@ -19,6 +19,7 @@
#include "api/audio_codecs/audio_encoder.h" #include "api/audio_codecs/audio_encoder.h"
#include "api/audio_codecs/audio_format.h" #include "api/audio_codecs/audio_format.h"
#include "api/audio_codecs/g722/audio_encoder_g722_config.h" #include "api/audio_codecs/g722/audio_encoder_g722_config.h"
#include "api/webrtc_key_value_config.h"
#include "rtc_base/system/rtc_export.h" #include "rtc_base/system/rtc_export.h"
namespace webrtc { namespace webrtc {
@ -34,7 +35,8 @@ struct RTC_EXPORT AudioEncoderG722 {
static std::unique_ptr<AudioEncoder> MakeAudioEncoder( static std::unique_ptr<AudioEncoder> MakeAudioEncoder(
const AudioEncoderG722Config& config, const AudioEncoderG722Config& config,
int payload_type, int payload_type,
absl::optional<AudioCodecPairId> codec_pair_id = absl::nullopt); absl::optional<AudioCodecPairId> codec_pair_id = absl::nullopt,
const WebRtcKeyValueConfig* field_trials = nullptr);
}; };
} // namespace webrtc } // namespace webrtc

View file

@ -15,7 +15,8 @@ namespace webrtc {
struct AudioEncoderG722Config { struct AudioEncoderG722Config {
bool IsOk() const { bool IsOk() const {
return frame_size_ms > 0 && frame_size_ms % 10 == 0 && num_channels >= 1; return frame_size_ms > 0 && frame_size_ms % 10 == 0 && num_channels >= 1 &&
num_channels <= AudioEncoder::kMaxNumberOfChannels;
} }
int frame_size_ms = 20; int frame_size_ms = 20;
int num_channels = 1; int num_channels = 1;

View file

@ -27,6 +27,7 @@ rtc_library("audio_encoder_ilbc") {
deps = [ deps = [
":audio_encoder_ilbc_config", ":audio_encoder_ilbc_config",
"..:audio_codecs_api", "..:audio_codecs_api",
"../../../api:webrtc_key_value_config",
"../../../modules/audio_coding:ilbc", "../../../modules/audio_coding:ilbc",
"../../../rtc_base:rtc_base_approved", "../../../rtc_base:rtc_base_approved",
"../../../rtc_base:safe_minmax", "../../../rtc_base:safe_minmax",
@ -46,6 +47,7 @@ rtc_library("audio_decoder_ilbc") {
] ]
deps = [ deps = [
"..:audio_codecs_api", "..:audio_codecs_api",
"../../../api:webrtc_key_value_config",
"../../../modules/audio_coding:ilbc", "../../../modules/audio_coding:ilbc",
"../../../rtc_base:rtc_base_approved", "../../../rtc_base:rtc_base_approved",
] ]

View file

@ -20,10 +20,11 @@ namespace webrtc {
absl::optional<AudioDecoderIlbc::Config> AudioDecoderIlbc::SdpToConfig( absl::optional<AudioDecoderIlbc::Config> AudioDecoderIlbc::SdpToConfig(
const SdpAudioFormat& format) { const SdpAudioFormat& format) {
return absl::EqualsIgnoreCase(format.name, "ILBC") && if (absl::EqualsIgnoreCase(format.name, "ILBC") &&
format.clockrate_hz == 8000 && format.num_channels == 1 format.clockrate_hz == 8000 && format.num_channels == 1) {
? absl::optional<Config>(Config()) return Config();
: absl::nullopt; }
return absl::nullopt;
} }
void AudioDecoderIlbc::AppendSupportedDecoders( void AudioDecoderIlbc::AppendSupportedDecoders(
@ -34,7 +35,8 @@ void AudioDecoderIlbc::AppendSupportedDecoders(
std::unique_ptr<AudioDecoder> AudioDecoderIlbc::MakeAudioDecoder( std::unique_ptr<AudioDecoder> AudioDecoderIlbc::MakeAudioDecoder(
Config config, Config config,
absl::optional<AudioCodecPairId> /*codec_pair_id*/) { absl::optional<AudioCodecPairId> /*codec_pair_id*/,
const WebRtcKeyValueConfig* field_trials) {
return std::make_unique<AudioDecoderIlbcImpl>(); return std::make_unique<AudioDecoderIlbcImpl>();
} }

View file

@ -18,6 +18,7 @@
#include "api/audio_codecs/audio_codec_pair_id.h" #include "api/audio_codecs/audio_codec_pair_id.h"
#include "api/audio_codecs/audio_decoder.h" #include "api/audio_codecs/audio_decoder.h"
#include "api/audio_codecs/audio_format.h" #include "api/audio_codecs/audio_format.h"
#include "api/webrtc_key_value_config.h"
namespace webrtc { namespace webrtc {
@ -29,7 +30,8 @@ struct AudioDecoderIlbc {
static void AppendSupportedDecoders(std::vector<AudioCodecSpec>* specs); static void AppendSupportedDecoders(std::vector<AudioCodecSpec>* specs);
static std::unique_ptr<AudioDecoder> MakeAudioDecoder( static std::unique_ptr<AudioDecoder> MakeAudioDecoder(
Config config, Config config,
absl::optional<AudioCodecPairId> codec_pair_id = absl::nullopt); absl::optional<AudioCodecPairId> codec_pair_id = absl::nullopt,
const WebRtcKeyValueConfig* field_trials = nullptr);
}; };
} // namespace webrtc } // namespace webrtc

View file

@ -53,8 +53,11 @@ absl::optional<AudioEncoderIlbcConfig> AudioEncoderIlbc::SdpToConfig(
config.frame_size_ms = rtc::SafeClamp<int>(whole_packets * 10, 20, 60); config.frame_size_ms = rtc::SafeClamp<int>(whole_packets * 10, 20, 60);
} }
} }
return config.IsOk() ? absl::optional<AudioEncoderIlbcConfig>(config) if (!config.IsOk()) {
: absl::nullopt; RTC_DCHECK_NOTREACHED();
return absl::nullopt;
}
return config;
} }
void AudioEncoderIlbc::AppendSupportedEncoders( void AudioEncoderIlbc::AppendSupportedEncoders(
@ -74,8 +77,12 @@ AudioCodecInfo AudioEncoderIlbc::QueryAudioEncoder(
std::unique_ptr<AudioEncoder> AudioEncoderIlbc::MakeAudioEncoder( std::unique_ptr<AudioEncoder> AudioEncoderIlbc::MakeAudioEncoder(
const AudioEncoderIlbcConfig& config, const AudioEncoderIlbcConfig& config,
int payload_type, int payload_type,
absl::optional<AudioCodecPairId> /*codec_pair_id*/) { absl::optional<AudioCodecPairId> /*codec_pair_id*/,
RTC_DCHECK(config.IsOk()); const WebRtcKeyValueConfig* field_trials) {
if (!config.IsOk()) {
RTC_DCHECK_NOTREACHED();
return nullptr;
}
return std::make_unique<AudioEncoderIlbcImpl>(config, payload_type); return std::make_unique<AudioEncoderIlbcImpl>(config, payload_type);
} }

View file

@ -19,6 +19,7 @@
#include "api/audio_codecs/audio_encoder.h" #include "api/audio_codecs/audio_encoder.h"
#include "api/audio_codecs/audio_format.h" #include "api/audio_codecs/audio_format.h"
#include "api/audio_codecs/ilbc/audio_encoder_ilbc_config.h" #include "api/audio_codecs/ilbc/audio_encoder_ilbc_config.h"
#include "api/webrtc_key_value_config.h"
namespace webrtc { namespace webrtc {
@ -33,7 +34,8 @@ struct AudioEncoderIlbc {
static std::unique_ptr<AudioEncoder> MakeAudioEncoder( static std::unique_ptr<AudioEncoder> MakeAudioEncoder(
const AudioEncoderIlbcConfig& config, const AudioEncoderIlbcConfig& config,
int payload_type, int payload_type,
absl::optional<AudioCodecPairId> codec_pair_id = absl::nullopt); absl::optional<AudioCodecPairId> codec_pair_id = absl::nullopt,
const WebRtcKeyValueConfig* field_trials = nullptr);
}; };
} // namespace webrtc } // namespace webrtc

View file

@ -65,6 +65,7 @@ rtc_library("audio_encoder_isac_fix") {
] ]
deps = [ deps = [
"..:audio_codecs_api", "..:audio_codecs_api",
"../../../api:webrtc_key_value_config",
"../../../modules/audio_coding:isac_fix", "../../../modules/audio_coding:isac_fix",
"../../../rtc_base:rtc_base_approved", "../../../rtc_base:rtc_base_approved",
"../../../rtc_base/system:rtc_export", "../../../rtc_base/system:rtc_export",
@ -84,6 +85,7 @@ rtc_library("audio_decoder_isac_fix") {
] ]
deps = [ deps = [
"..:audio_codecs_api", "..:audio_codecs_api",
"../../../api:webrtc_key_value_config",
"../../../modules/audio_coding:isac_fix", "../../../modules/audio_coding:isac_fix",
"../../../rtc_base:rtc_base_approved", "../../../rtc_base:rtc_base_approved",
"../../../rtc_base/system:rtc_export", "../../../rtc_base/system:rtc_export",
@ -103,6 +105,7 @@ rtc_library("audio_encoder_isac_float") {
] ]
deps = [ deps = [
"..:audio_codecs_api", "..:audio_codecs_api",
"../../../api:webrtc_key_value_config",
"../../../modules/audio_coding:isac", "../../../modules/audio_coding:isac",
"../../../rtc_base:rtc_base_approved", "../../../rtc_base:rtc_base_approved",
"../../../rtc_base/system:rtc_export", "../../../rtc_base/system:rtc_export",
@ -122,6 +125,7 @@ rtc_library("audio_decoder_isac_float") {
] ]
deps = [ deps = [
"..:audio_codecs_api", "..:audio_codecs_api",
"../../../api:webrtc_key_value_config",
"../../../modules/audio_coding:isac", "../../../modules/audio_coding:isac",
"../../../rtc_base:rtc_base_approved", "../../../rtc_base:rtc_base_approved",
"../../../rtc_base/system:rtc_export", "../../../rtc_base/system:rtc_export",

View file

@ -19,10 +19,11 @@ namespace webrtc {
absl::optional<AudioDecoderIsacFix::Config> AudioDecoderIsacFix::SdpToConfig( absl::optional<AudioDecoderIsacFix::Config> AudioDecoderIsacFix::SdpToConfig(
const SdpAudioFormat& format) { const SdpAudioFormat& format) {
return absl::EqualsIgnoreCase(format.name, "ISAC") && if (absl::EqualsIgnoreCase(format.name, "ISAC") &&
format.clockrate_hz == 16000 && format.num_channels == 1 format.clockrate_hz == 16000 && format.num_channels == 1) {
? absl::optional<Config>(Config()) return Config();
: absl::nullopt; }
return absl::nullopt;
} }
void AudioDecoderIsacFix::AppendSupportedDecoders( void AudioDecoderIsacFix::AppendSupportedDecoders(
@ -33,7 +34,8 @@ void AudioDecoderIsacFix::AppendSupportedDecoders(
std::unique_ptr<AudioDecoder> AudioDecoderIsacFix::MakeAudioDecoder( std::unique_ptr<AudioDecoder> AudioDecoderIsacFix::MakeAudioDecoder(
Config config, Config config,
absl::optional<AudioCodecPairId> /*codec_pair_id*/) { absl::optional<AudioCodecPairId> /*codec_pair_id*/,
const WebRtcKeyValueConfig* field_trials) {
AudioDecoderIsacFixImpl::Config c; AudioDecoderIsacFixImpl::Config c;
c.sample_rate_hz = 16000; c.sample_rate_hz = 16000;
return std::make_unique<AudioDecoderIsacFixImpl>(c); return std::make_unique<AudioDecoderIsacFixImpl>(c);

View file

@ -18,6 +18,7 @@
#include "api/audio_codecs/audio_codec_pair_id.h" #include "api/audio_codecs/audio_codec_pair_id.h"
#include "api/audio_codecs/audio_decoder.h" #include "api/audio_codecs/audio_decoder.h"
#include "api/audio_codecs/audio_format.h" #include "api/audio_codecs/audio_format.h"
#include "api/webrtc_key_value_config.h"
#include "rtc_base/system/rtc_export.h" #include "rtc_base/system/rtc_export.h"
namespace webrtc { namespace webrtc {
@ -30,7 +31,8 @@ struct RTC_EXPORT AudioDecoderIsacFix {
static void AppendSupportedDecoders(std::vector<AudioCodecSpec>* specs); static void AppendSupportedDecoders(std::vector<AudioCodecSpec>* specs);
static std::unique_ptr<AudioDecoder> MakeAudioDecoder( static std::unique_ptr<AudioDecoder> MakeAudioDecoder(
Config config, Config config,
absl::optional<AudioCodecPairId> codec_pair_id = absl::nullopt); absl::optional<AudioCodecPairId> codec_pair_id = absl::nullopt,
const WebRtcKeyValueConfig* field_trials = nullptr);
}; };
} // namespace webrtc } // namespace webrtc

View file

@ -24,6 +24,10 @@ AudioDecoderIsacFloat::SdpToConfig(const SdpAudioFormat& format) {
format.num_channels == 1) { format.num_channels == 1) {
Config config; Config config;
config.sample_rate_hz = format.clockrate_hz; config.sample_rate_hz = format.clockrate_hz;
if (!config.IsOk()) {
RTC_DCHECK_NOTREACHED();
return absl::nullopt;
}
return config; return config;
} else { } else {
return absl::nullopt; return absl::nullopt;
@ -39,10 +43,14 @@ void AudioDecoderIsacFloat::AppendSupportedDecoders(
std::unique_ptr<AudioDecoder> AudioDecoderIsacFloat::MakeAudioDecoder( std::unique_ptr<AudioDecoder> AudioDecoderIsacFloat::MakeAudioDecoder(
Config config, Config config,
absl::optional<AudioCodecPairId> /*codec_pair_id*/) { absl::optional<AudioCodecPairId> /*codec_pair_id*/,
RTC_DCHECK(config.IsOk()); const WebRtcKeyValueConfig* field_trials) {
AudioDecoderIsacFloatImpl::Config c; AudioDecoderIsacFloatImpl::Config c;
c.sample_rate_hz = config.sample_rate_hz; c.sample_rate_hz = config.sample_rate_hz;
if (!config.IsOk()) {
RTC_DCHECK_NOTREACHED();
return nullptr;
}
return std::make_unique<AudioDecoderIsacFloatImpl>(c); return std::make_unique<AudioDecoderIsacFloatImpl>(c);
} }

View file

@ -18,6 +18,7 @@
#include "api/audio_codecs/audio_codec_pair_id.h" #include "api/audio_codecs/audio_codec_pair_id.h"
#include "api/audio_codecs/audio_decoder.h" #include "api/audio_codecs/audio_decoder.h"
#include "api/audio_codecs/audio_format.h" #include "api/audio_codecs/audio_format.h"
#include "api/webrtc_key_value_config.h"
#include "rtc_base/system/rtc_export.h" #include "rtc_base/system/rtc_export.h"
namespace webrtc { namespace webrtc {
@ -35,7 +36,8 @@ struct RTC_EXPORT AudioDecoderIsacFloat {
static void AppendSupportedDecoders(std::vector<AudioCodecSpec>* specs); static void AppendSupportedDecoders(std::vector<AudioCodecSpec>* specs);
static std::unique_ptr<AudioDecoder> MakeAudioDecoder( static std::unique_ptr<AudioDecoder> MakeAudioDecoder(
Config config, Config config,
absl::optional<AudioCodecPairId> codec_pair_id = absl::nullopt); absl::optional<AudioCodecPairId> codec_pair_id = absl::nullopt,
const WebRtcKeyValueConfig* field_trials = nullptr);
}; };
} // namespace webrtc } // namespace webrtc

View file

@ -30,6 +30,10 @@ absl::optional<AudioEncoderIsacFix::Config> AudioEncoderIsacFix::SdpToConfig(
config.frame_size_ms = 60; config.frame_size_ms = 60;
} }
} }
if (!config.IsOk()) {
RTC_DCHECK_NOTREACHED();
return absl::nullopt;
}
return config; return config;
} else { } else {
return absl::nullopt; return absl::nullopt;
@ -53,12 +57,16 @@ AudioCodecInfo AudioEncoderIsacFix::QueryAudioEncoder(
std::unique_ptr<AudioEncoder> AudioEncoderIsacFix::MakeAudioEncoder( std::unique_ptr<AudioEncoder> AudioEncoderIsacFix::MakeAudioEncoder(
AudioEncoderIsacFix::Config config, AudioEncoderIsacFix::Config config,
int payload_type, int payload_type,
absl::optional<AudioCodecPairId> /*codec_pair_id*/) { absl::optional<AudioCodecPairId> /*codec_pair_id*/,
RTC_DCHECK(config.IsOk()); const WebRtcKeyValueConfig* field_trials) {
AudioEncoderIsacFixImpl::Config c; AudioEncoderIsacFixImpl::Config c;
c.frame_size_ms = config.frame_size_ms; c.frame_size_ms = config.frame_size_ms;
c.bit_rate = config.bit_rate; c.bit_rate = config.bit_rate;
c.payload_type = payload_type; c.payload_type = payload_type;
if (!config.IsOk()) {
RTC_DCHECK_NOTREACHED();
return nullptr;
}
return std::make_unique<AudioEncoderIsacFixImpl>(c); return std::make_unique<AudioEncoderIsacFixImpl>(c);
} }

View file

@ -18,6 +18,7 @@
#include "api/audio_codecs/audio_codec_pair_id.h" #include "api/audio_codecs/audio_codec_pair_id.h"
#include "api/audio_codecs/audio_encoder.h" #include "api/audio_codecs/audio_encoder.h"
#include "api/audio_codecs/audio_format.h" #include "api/audio_codecs/audio_format.h"
#include "api/webrtc_key_value_config.h"
#include "rtc_base/system/rtc_export.h" #include "rtc_base/system/rtc_export.h"
namespace webrtc { namespace webrtc {
@ -44,7 +45,8 @@ struct RTC_EXPORT AudioEncoderIsacFix {
static std::unique_ptr<AudioEncoder> MakeAudioEncoder( static std::unique_ptr<AudioEncoder> MakeAudioEncoder(
Config config, Config config,
int payload_type, int payload_type,
absl::optional<AudioCodecPairId> codec_pair_id = absl::nullopt); absl::optional<AudioCodecPairId> codec_pair_id = absl::nullopt,
const WebRtcKeyValueConfig* field_trials = nullptr);
}; };
} // namespace webrtc } // namespace webrtc

View file

@ -37,6 +37,10 @@ AudioEncoderIsacFloat::SdpToConfig(const SdpAudioFormat& format) {
} }
} }
} }
if (!config.IsOk()) {
RTC_DCHECK_NOTREACHED();
return absl::nullopt;
}
return config; return config;
} else { } else {
return absl::nullopt; return absl::nullopt;
@ -65,13 +69,17 @@ AudioCodecInfo AudioEncoderIsacFloat::QueryAudioEncoder(
std::unique_ptr<AudioEncoder> AudioEncoderIsacFloat::MakeAudioEncoder( std::unique_ptr<AudioEncoder> AudioEncoderIsacFloat::MakeAudioEncoder(
const AudioEncoderIsacFloat::Config& config, const AudioEncoderIsacFloat::Config& config,
int payload_type, int payload_type,
absl::optional<AudioCodecPairId> /*codec_pair_id*/) { absl::optional<AudioCodecPairId> /*codec_pair_id*/,
RTC_DCHECK(config.IsOk()); const WebRtcKeyValueConfig* field_trials) {
AudioEncoderIsacFloatImpl::Config c; AudioEncoderIsacFloatImpl::Config c;
c.payload_type = payload_type; c.payload_type = payload_type;
c.sample_rate_hz = config.sample_rate_hz; c.sample_rate_hz = config.sample_rate_hz;
c.frame_size_ms = config.frame_size_ms; c.frame_size_ms = config.frame_size_ms;
c.bit_rate = config.bit_rate; c.bit_rate = config.bit_rate;
if (!config.IsOk()) {
RTC_DCHECK_NOTREACHED();
return nullptr;
}
return std::make_unique<AudioEncoderIsacFloatImpl>(c); return std::make_unique<AudioEncoderIsacFloatImpl>(c);
} }

View file

@ -18,6 +18,7 @@
#include "api/audio_codecs/audio_codec_pair_id.h" #include "api/audio_codecs/audio_codec_pair_id.h"
#include "api/audio_codecs/audio_encoder.h" #include "api/audio_codecs/audio_encoder.h"
#include "api/audio_codecs/audio_format.h" #include "api/audio_codecs/audio_format.h"
#include "api/webrtc_key_value_config.h"
#include "rtc_base/system/rtc_export.h" #include "rtc_base/system/rtc_export.h"
namespace webrtc { namespace webrtc {
@ -58,7 +59,8 @@ struct RTC_EXPORT AudioEncoderIsacFloat {
static std::unique_ptr<AudioEncoder> MakeAudioEncoder( static std::unique_ptr<AudioEncoder> MakeAudioEncoder(
const Config& config, const Config& config,
int payload_type, int payload_type,
absl::optional<AudioCodecPairId> codec_pair_id = absl::nullopt); absl::optional<AudioCodecPairId> codec_pair_id = absl::nullopt,
const WebRtcKeyValueConfig* field_trials = nullptr);
}; };
} // namespace webrtc } // namespace webrtc

View file

@ -46,6 +46,7 @@ rtc_library("audio_encoder_opus") {
deps = [ deps = [
":audio_encoder_opus_config", ":audio_encoder_opus_config",
"..:audio_codecs_api", "..:audio_codecs_api",
"../../../api:webrtc_key_value_config",
"../../../modules/audio_coding:webrtc_opus", "../../../modules/audio_coding:webrtc_opus",
"../../../rtc_base:rtc_base_approved", "../../../rtc_base:rtc_base_approved",
"../../../rtc_base/system:rtc_export", "../../../rtc_base/system:rtc_export",
@ -65,6 +66,7 @@ rtc_library("audio_decoder_opus") {
] ]
deps = [ deps = [
"..:audio_codecs_api", "..:audio_codecs_api",
"../../../api:webrtc_key_value_config",
"../../../modules/audio_coding:webrtc_opus", "../../../modules/audio_coding:webrtc_opus",
"../../../rtc_base:rtc_base_approved", "../../../rtc_base:rtc_base_approved",
"../../../rtc_base/system:rtc_export", "../../../rtc_base/system:rtc_export",
@ -82,6 +84,7 @@ rtc_library("audio_encoder_multiopus") {
sources = [ "audio_encoder_multi_channel_opus.cc" ] sources = [ "audio_encoder_multi_channel_opus.cc" ]
deps = [ deps = [
"..:audio_codecs_api", "..:audio_codecs_api",
"../../../api:webrtc_key_value_config",
"../../../modules/audio_coding:webrtc_multiopus", "../../../modules/audio_coding:webrtc_multiopus",
"../../../rtc_base:rtc_base_approved", "../../../rtc_base:rtc_base_approved",
"../../../rtc_base/system:rtc_export", "../../../rtc_base/system:rtc_export",
@ -100,6 +103,7 @@ rtc_library("audio_decoder_multiopus") {
deps = [ deps = [
":audio_decoder_opus_config", ":audio_decoder_opus_config",
"..:audio_codecs_api", "..:audio_codecs_api",
"../../../api:webrtc_key_value_config",
"../../../modules/audio_coding:webrtc_multiopus", "../../../modules/audio_coding:webrtc_multiopus",
"../../../rtc_base:rtc_base_approved", "../../../rtc_base:rtc_base_approved",
"../../../rtc_base/system:rtc_export", "../../../rtc_base/system:rtc_export",

View file

@ -64,7 +64,8 @@ void AudioDecoderMultiChannelOpus::AppendSupportedDecoders(
std::unique_ptr<AudioDecoder> AudioDecoderMultiChannelOpus::MakeAudioDecoder( std::unique_ptr<AudioDecoder> AudioDecoderMultiChannelOpus::MakeAudioDecoder(
AudioDecoderMultiChannelOpusConfig config, AudioDecoderMultiChannelOpusConfig config,
absl::optional<AudioCodecPairId> /*codec_pair_id*/) { absl::optional<AudioCodecPairId> /*codec_pair_id*/,
const WebRtcKeyValueConfig* field_trials) {
return AudioDecoderMultiChannelOpusImpl::MakeAudioDecoder(config); return AudioDecoderMultiChannelOpusImpl::MakeAudioDecoder(config);
} }
} // namespace webrtc } // namespace webrtc

View file

@ -19,6 +19,7 @@
#include "api/audio_codecs/audio_decoder.h" #include "api/audio_codecs/audio_decoder.h"
#include "api/audio_codecs/audio_format.h" #include "api/audio_codecs/audio_format.h"
#include "api/audio_codecs/opus/audio_decoder_multi_channel_opus_config.h" #include "api/audio_codecs/opus/audio_decoder_multi_channel_opus_config.h"
#include "api/webrtc_key_value_config.h"
#include "rtc_base/system/rtc_export.h" #include "rtc_base/system/rtc_export.h"
namespace webrtc { namespace webrtc {
@ -32,7 +33,8 @@ struct RTC_EXPORT AudioDecoderMultiChannelOpus {
static void AppendSupportedDecoders(std::vector<AudioCodecSpec>* specs); static void AppendSupportedDecoders(std::vector<AudioCodecSpec>* specs);
static std::unique_ptr<AudioDecoder> MakeAudioDecoder( static std::unique_ptr<AudioDecoder> MakeAudioDecoder(
AudioDecoderMultiChannelOpusConfig config, AudioDecoderMultiChannelOpusConfig config,
absl::optional<AudioCodecPairId> codec_pair_id = absl::nullopt); absl::optional<AudioCodecPairId> codec_pair_id = absl::nullopt,
const WebRtcKeyValueConfig* field_trials = nullptr);
}; };
} // namespace webrtc } // namespace webrtc

View file

@ -30,7 +30,8 @@ struct AudioDecoderMultiChannelOpusConfig {
std::vector<unsigned char> channel_mapping; std::vector<unsigned char> channel_mapping;
bool IsOk() const { bool IsOk() const {
if (num_channels < 0 || num_streams < 0 || coupled_streams < 0) { if (num_channels < 1 || num_channels > AudioDecoder::kMaxNumberOfChannels ||
num_streams < 0 || coupled_streams < 0) {
return false; return false;
} }
if (num_streams < coupled_streams) { if (num_streams < coupled_streams) {

View file

@ -51,7 +51,10 @@ absl::optional<AudioDecoderOpus::Config> AudioDecoderOpus::SdpToConfig(
num_channels) { num_channels) {
Config config; Config config;
config.num_channels = *num_channels; config.num_channels = *num_channels;
RTC_DCHECK(config.IsOk()); if (!config.IsOk()) {
RTC_DCHECK_NOTREACHED();
return absl::nullopt;
}
return config; return config;
} else { } else {
return absl::nullopt; return absl::nullopt;
@ -70,8 +73,12 @@ void AudioDecoderOpus::AppendSupportedDecoders(
std::unique_ptr<AudioDecoder> AudioDecoderOpus::MakeAudioDecoder( std::unique_ptr<AudioDecoder> AudioDecoderOpus::MakeAudioDecoder(
Config config, Config config,
absl::optional<AudioCodecPairId> /*codec_pair_id*/) { absl::optional<AudioCodecPairId> /*codec_pair_id*/,
RTC_DCHECK(config.IsOk()); const WebRtcKeyValueConfig* field_trials) {
if (!config.IsOk()) {
RTC_DCHECK_NOTREACHED();
return nullptr;
}
return std::make_unique<AudioDecoderOpusImpl>(config.num_channels, return std::make_unique<AudioDecoderOpusImpl>(config.num_channels,
config.sample_rate_hz); config.sample_rate_hz);
} }

View file

@ -18,6 +18,7 @@
#include "api/audio_codecs/audio_codec_pair_id.h" #include "api/audio_codecs/audio_codec_pair_id.h"
#include "api/audio_codecs/audio_decoder.h" #include "api/audio_codecs/audio_decoder.h"
#include "api/audio_codecs/audio_format.h" #include "api/audio_codecs/audio_format.h"
#include "api/webrtc_key_value_config.h"
#include "rtc_base/system/rtc_export.h" #include "rtc_base/system/rtc_export.h"
namespace webrtc { namespace webrtc {
@ -34,7 +35,8 @@ struct RTC_EXPORT AudioDecoderOpus {
static void AppendSupportedDecoders(std::vector<AudioCodecSpec>* specs); static void AppendSupportedDecoders(std::vector<AudioCodecSpec>* specs);
static std::unique_ptr<AudioDecoder> MakeAudioDecoder( static std::unique_ptr<AudioDecoder> MakeAudioDecoder(
Config config, Config config,
absl::optional<AudioCodecPairId> codec_pair_id = absl::nullopt); absl::optional<AudioCodecPairId> codec_pair_id = absl::nullopt,
const WebRtcKeyValueConfig* field_trials = nullptr);
}; };
} // namespace webrtc } // namespace webrtc

View file

@ -66,7 +66,8 @@ AudioCodecInfo AudioEncoderMultiChannelOpus::QueryAudioEncoder(
std::unique_ptr<AudioEncoder> AudioEncoderMultiChannelOpus::MakeAudioEncoder( std::unique_ptr<AudioEncoder> AudioEncoderMultiChannelOpus::MakeAudioEncoder(
const AudioEncoderMultiChannelOpusConfig& config, const AudioEncoderMultiChannelOpusConfig& config,
int payload_type, int payload_type,
absl::optional<AudioCodecPairId> /*codec_pair_id*/) { absl::optional<AudioCodecPairId> /*codec_pair_id*/,
const WebRtcKeyValueConfig* field_trials) {
return AudioEncoderMultiChannelOpusImpl::MakeAudioEncoder(config, return AudioEncoderMultiChannelOpusImpl::MakeAudioEncoder(config,
payload_type); payload_type);
} }

View file

@ -19,6 +19,7 @@
#include "api/audio_codecs/audio_encoder.h" #include "api/audio_codecs/audio_encoder.h"
#include "api/audio_codecs/audio_format.h" #include "api/audio_codecs/audio_format.h"
#include "api/audio_codecs/opus/audio_encoder_multi_channel_opus_config.h" #include "api/audio_codecs/opus/audio_encoder_multi_channel_opus_config.h"
#include "api/webrtc_key_value_config.h"
#include "rtc_base/system/rtc_export.h" #include "rtc_base/system/rtc_export.h"
namespace webrtc { namespace webrtc {
@ -33,7 +34,8 @@ struct RTC_EXPORT AudioEncoderMultiChannelOpus {
static std::unique_ptr<AudioEncoder> MakeAudioEncoder( static std::unique_ptr<AudioEncoder> MakeAudioEncoder(
const Config& config, const Config& config,
int payload_type, int payload_type,
absl::optional<AudioCodecPairId> codec_pair_id = absl::nullopt); absl::optional<AudioCodecPairId> codec_pair_id = absl::nullopt,
const WebRtcKeyValueConfig* field_trials = nullptr);
}; };
} // namespace webrtc } // namespace webrtc

View file

@ -32,7 +32,12 @@ AudioCodecInfo AudioEncoderOpus::QueryAudioEncoder(
std::unique_ptr<AudioEncoder> AudioEncoderOpus::MakeAudioEncoder( std::unique_ptr<AudioEncoder> AudioEncoderOpus::MakeAudioEncoder(
const AudioEncoderOpusConfig& config, const AudioEncoderOpusConfig& config,
int payload_type, int payload_type,
absl::optional<AudioCodecPairId> /*codec_pair_id*/) { absl::optional<AudioCodecPairId> /*codec_pair_id*/,
const WebRtcKeyValueConfig* field_trials) {
if (!config.IsOk()) {
RTC_DCHECK_NOTREACHED();
return nullptr;
}
return AudioEncoderOpusImpl::MakeAudioEncoder(config, payload_type); return AudioEncoderOpusImpl::MakeAudioEncoder(config, payload_type);
} }

View file

@ -19,6 +19,7 @@
#include "api/audio_codecs/audio_encoder.h" #include "api/audio_codecs/audio_encoder.h"
#include "api/audio_codecs/audio_format.h" #include "api/audio_codecs/audio_format.h"
#include "api/audio_codecs/opus/audio_encoder_opus_config.h" #include "api/audio_codecs/opus/audio_encoder_opus_config.h"
#include "api/webrtc_key_value_config.h"
#include "rtc_base/system/rtc_export.h" #include "rtc_base/system/rtc_export.h"
namespace webrtc { namespace webrtc {
@ -34,7 +35,8 @@ struct RTC_EXPORT AudioEncoderOpus {
static std::unique_ptr<AudioEncoder> MakeAudioEncoder( static std::unique_ptr<AudioEncoder> MakeAudioEncoder(
const AudioEncoderOpusConfig& config, const AudioEncoderOpusConfig& config,
int payload_type, int payload_type,
absl::optional<AudioCodecPairId> codec_pair_id = absl::nullopt); absl::optional<AudioCodecPairId> codec_pair_id = absl::nullopt,
const WebRtcKeyValueConfig* field_trials = nullptr);
}; };
} // namespace webrtc } // namespace webrtc

View file

@ -37,8 +37,10 @@ struct NotAdvertised {
static std::unique_ptr<AudioEncoder> MakeAudioEncoder( static std::unique_ptr<AudioEncoder> MakeAudioEncoder(
const Config& config, const Config& config,
int payload_type, int payload_type,
absl::optional<AudioCodecPairId> codec_pair_id = absl::nullopt) { absl::optional<AudioCodecPairId> codec_pair_id = absl::nullopt,
return T::MakeAudioEncoder(config, payload_type, codec_pair_id); const WebRtcKeyValueConfig* field_trials = nullptr) {
return T::MakeAudioEncoder(config, payload_type, codec_pair_id,
field_trials);
} }
}; };

View file

@ -23,6 +23,7 @@ if (rtc_include_tests) {
"..:audio_codecs_api", "..:audio_codecs_api",
"../../../rtc_base:rtc_base_approved", "../../../rtc_base:rtc_base_approved",
"../../../test:audio_codec_mocks", "../../../test:audio_codec_mocks",
"../../../test:scoped_key_value_config",
"../../../test:test_support", "../../../test:test_support",
"../L16:audio_decoder_L16", "../L16:audio_decoder_L16",
"../L16:audio_encoder_L16", "../L16:audio_encoder_L16",

View file

@ -22,6 +22,7 @@
#include "test/gmock.h" #include "test/gmock.h"
#include "test/gtest.h" #include "test/gtest.h"
#include "test/mock_audio_decoder.h" #include "test/mock_audio_decoder.h"
#include "test/scoped_key_value_config.h"
namespace webrtc { namespace webrtc {
@ -77,9 +78,11 @@ struct AudioDecoderFakeApi {
} // namespace } // namespace
TEST(AudioDecoderFactoryTemplateTest, NoDecoderTypes) { TEST(AudioDecoderFactoryTemplateTest, NoDecoderTypes) {
test::ScopedKeyValueConfig field_trials;
rtc::scoped_refptr<AudioDecoderFactory> factory( rtc::scoped_refptr<AudioDecoderFactory> factory(
rtc::make_ref_counted< rtc::make_ref_counted<
audio_decoder_factory_template_impl::AudioDecoderFactoryT<>>()); audio_decoder_factory_template_impl::AudioDecoderFactoryT<>>(
&field_trials));
EXPECT_THAT(factory->GetSupportedDecoders(), ::testing::IsEmpty()); EXPECT_THAT(factory->GetSupportedDecoders(), ::testing::IsEmpty());
EXPECT_FALSE(factory->IsSupportedDecoder({"foo", 8000, 1})); EXPECT_FALSE(factory->IsSupportedDecoder({"foo", 8000, 1}));
EXPECT_EQ(nullptr, EXPECT_EQ(nullptr,

View file

@ -22,6 +22,7 @@
#include "test/gmock.h" #include "test/gmock.h"
#include "test/gtest.h" #include "test/gtest.h"
#include "test/mock_audio_encoder.h" #include "test/mock_audio_encoder.h"
#include "test/scoped_key_value_config.h"
namespace webrtc { namespace webrtc {
@ -77,9 +78,11 @@ struct AudioEncoderFakeApi {
} // namespace } // namespace
TEST(AudioEncoderFactoryTemplateTest, NoEncoderTypes) { TEST(AudioEncoderFactoryTemplateTest, NoEncoderTypes) {
test::ScopedKeyValueConfig field_trials;
rtc::scoped_refptr<AudioEncoderFactory> factory( rtc::scoped_refptr<AudioEncoderFactory> factory(
rtc::make_ref_counted< rtc::make_ref_counted<
audio_encoder_factory_template_impl::AudioEncoderFactoryT<>>()); audio_encoder_factory_template_impl::AudioEncoderFactoryT<>>(
&field_trials));
EXPECT_THAT(factory->GetSupportedEncoders(), ::testing::IsEmpty()); EXPECT_THAT(factory->GetSupportedEncoders(), ::testing::IsEmpty());
EXPECT_EQ(absl::nullopt, factory->QueryAudioEncoder({"foo", 8000, 1})); EXPECT_EQ(absl::nullopt, factory->QueryAudioEncoder({"foo", 8000, 1}));
EXPECT_EQ(nullptr, EXPECT_EQ(nullptr,

View file

@ -55,16 +55,11 @@ void AudioOptions::SetAll(const AudioOptions& change) {
SetFrom(&audio_jitter_buffer_enable_rtx_handling, SetFrom(&audio_jitter_buffer_enable_rtx_handling,
change.audio_jitter_buffer_enable_rtx_handling); change.audio_jitter_buffer_enable_rtx_handling);
SetFrom(&typing_detection, change.typing_detection); SetFrom(&typing_detection, change.typing_detection);
SetFrom(&experimental_agc, change.experimental_agc);
SetFrom(&experimental_ns, change.experimental_ns);
SetFrom(&residual_echo_detector, change.residual_echo_detector); SetFrom(&residual_echo_detector, change.residual_echo_detector);
SetFrom(&tx_agc_target_dbov, change.tx_agc_target_dbov);
SetFrom(&tx_agc_digital_compression_gain,
change.tx_agc_digital_compression_gain);
SetFrom(&tx_agc_limiter, change.tx_agc_limiter);
SetFrom(&combined_audio_video_bwe, change.combined_audio_video_bwe); SetFrom(&combined_audio_video_bwe, change.combined_audio_video_bwe);
SetFrom(&audio_network_adaptor, change.audio_network_adaptor); SetFrom(&audio_network_adaptor, change.audio_network_adaptor);
SetFrom(&audio_network_adaptor_config, change.audio_network_adaptor_config); SetFrom(&audio_network_adaptor_config, change.audio_network_adaptor_config);
SetFrom(&init_recording_on_send, change.init_recording_on_send);
} }
bool AudioOptions::operator==(const AudioOptions& o) const { bool AudioOptions::operator==(const AudioOptions& o) const {
@ -84,15 +79,11 @@ bool AudioOptions::operator==(const AudioOptions& o) const {
audio_jitter_buffer_enable_rtx_handling == audio_jitter_buffer_enable_rtx_handling ==
o.audio_jitter_buffer_enable_rtx_handling && o.audio_jitter_buffer_enable_rtx_handling &&
typing_detection == o.typing_detection && typing_detection == o.typing_detection &&
experimental_agc == o.experimental_agc &&
experimental_ns == o.experimental_ns &&
residual_echo_detector == o.residual_echo_detector && residual_echo_detector == o.residual_echo_detector &&
tx_agc_target_dbov == o.tx_agc_target_dbov &&
tx_agc_digital_compression_gain == o.tx_agc_digital_compression_gain &&
tx_agc_limiter == o.tx_agc_limiter &&
combined_audio_video_bwe == o.combined_audio_video_bwe && combined_audio_video_bwe == o.combined_audio_video_bwe &&
audio_network_adaptor == o.audio_network_adaptor && audio_network_adaptor == o.audio_network_adaptor &&
audio_network_adaptor_config == o.audio_network_adaptor_config; audio_network_adaptor_config == o.audio_network_adaptor_config &&
init_recording_on_send == o.init_recording_on_send;
} }
std::string AudioOptions::ToString() const { std::string AudioOptions::ToString() const {
@ -117,15 +108,10 @@ std::string AudioOptions::ToString() const {
ToStringIfSet(&result, "audio_jitter_buffer_enable_rtx_handling", ToStringIfSet(&result, "audio_jitter_buffer_enable_rtx_handling",
audio_jitter_buffer_enable_rtx_handling); audio_jitter_buffer_enable_rtx_handling);
ToStringIfSet(&result, "typing", typing_detection); ToStringIfSet(&result, "typing", typing_detection);
ToStringIfSet(&result, "experimental_agc", experimental_agc);
ToStringIfSet(&result, "experimental_ns", experimental_ns);
ToStringIfSet(&result, "residual_echo_detector", residual_echo_detector); ToStringIfSet(&result, "residual_echo_detector", residual_echo_detector);
ToStringIfSet(&result, "tx_agc_target_dbov", tx_agc_target_dbov);
ToStringIfSet(&result, "tx_agc_digital_compression_gain",
tx_agc_digital_compression_gain);
ToStringIfSet(&result, "tx_agc_limiter", tx_agc_limiter);
ToStringIfSet(&result, "combined_audio_video_bwe", combined_audio_video_bwe); ToStringIfSet(&result, "combined_audio_video_bwe", combined_audio_video_bwe);
ToStringIfSet(&result, "audio_network_adaptor", audio_network_adaptor); ToStringIfSet(&result, "audio_network_adaptor", audio_network_adaptor);
ToStringIfSet(&result, "init_recording_on_send", init_recording_on_send);
result << "}"; result << "}";
return result.str(); return result.str();
} }

View file

@ -60,15 +60,14 @@ struct RTC_EXPORT AudioOptions {
absl::optional<int> audio_jitter_buffer_min_delay_ms; absl::optional<int> audio_jitter_buffer_min_delay_ms;
// Audio receiver jitter buffer (NetEq) should handle retransmitted packets. // Audio receiver jitter buffer (NetEq) should handle retransmitted packets.
absl::optional<bool> audio_jitter_buffer_enable_rtx_handling; absl::optional<bool> audio_jitter_buffer_enable_rtx_handling;
// Deprecated.
// TODO(bugs.webrtc.org/11226): Remove.
// Audio processing to detect typing. // Audio processing to detect typing.
absl::optional<bool> typing_detection; absl::optional<bool> typing_detection;
absl::optional<bool> experimental_agc; // TODO(bugs.webrtc.org/11539): Deprecated, replaced by
absl::optional<bool> experimental_ns; // webrtc::CreateEchoDetector() and injection when creating the audio
// Note that tx_agc_* only applies to non-experimental AGC. // processing module.
absl::optional<bool> residual_echo_detector; absl::optional<bool> residual_echo_detector;
absl::optional<uint16_t> tx_agc_target_dbov;
absl::optional<uint16_t> tx_agc_digital_compression_gain;
absl::optional<bool> tx_agc_limiter;
// Enable combined audio+bandwidth BWE. // Enable combined audio+bandwidth BWE.
// TODO(pthatcher): This flag is set from the // TODO(pthatcher): This flag is set from the
// "googCombinedAudioVideoBwe", but not used anywhere. So delete it, // "googCombinedAudioVideoBwe", but not used anywhere. So delete it,
@ -80,6 +79,10 @@ struct RTC_EXPORT AudioOptions {
absl::optional<bool> audio_network_adaptor; absl::optional<bool> audio_network_adaptor;
// Config string for audio network adaptor. // Config string for audio network adaptor.
absl::optional<std::string> audio_network_adaptor_config; absl::optional<std::string> audio_network_adaptor_config;
// Pre-initialize the ADM for recording when starting to send. Default to
// true.
// TODO(webrtc:13566): Remove this option. See issue for details.
absl::optional<bool> init_recording_on_send;
}; };
} // namespace cricket } // namespace cricket

View file

@ -27,14 +27,14 @@ Candidate::Candidate()
network_cost_(0) {} network_cost_(0) {}
Candidate::Candidate(int component, Candidate::Candidate(int component,
const std::string& protocol, absl::string_view protocol,
const rtc::SocketAddress& address, const rtc::SocketAddress& address,
uint32_t priority, uint32_t priority,
const std::string& username, absl::string_view username,
const std::string& password, absl::string_view password,
const std::string& type, absl::string_view type,
uint32_t generation, uint32_t generation,
const std::string& foundation, absl::string_view foundation,
uint16_t network_id, uint16_t network_id,
uint16_t network_cost) uint16_t network_cost)
: id_(rtc::CreateRandomString(8)), : id_(rtc::CreateRandomString(8)),
@ -101,7 +101,9 @@ uint32_t Candidate::GetPriority(uint32_t type_preference,
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// NIC Type - Type of the network adapter e.g. 3G/Wifi/Wired. // NIC Type - Type of the network adapter e.g. 3G/Wifi/Wired.
// Addr Pref - Address preference value as per RFC 3484. // Addr Pref - Address preference value as per RFC 3484.
// local preference = (NIC Type << 8 | Addr_Pref) - relay preference. // local preference = (NIC Type << 8 | Addr_Pref) + relay preference.
// The relay preference is based on the number of TURN servers, the
// first TURN server gets the highest preference.
int addr_pref = IPAddressPrecedence(address_.ipaddr()); int addr_pref = IPAddressPrecedence(address_.ipaddr());
int local_preference = int local_preference =
@ -153,4 +155,11 @@ Candidate Candidate::ToSanitizedCopy(bool use_hostname_address,
return copy; return copy;
} }
void Candidate::Assign(std::string& s, absl::string_view view) {
// Assigning via a temporary object, like s = std::string(view), results in
// binary size bloat. To avoid that, extract pointer and size from the
// string view, and use std::string::assign method.
s.assign(view.data(), view.size());
}
} // namespace cricket } // namespace cricket

View file

@ -17,6 +17,7 @@
#include <algorithm> #include <algorithm>
#include <string> #include <string>
#include "absl/strings/string_view.h"
#include "rtc_base/checks.h" #include "rtc_base/checks.h"
#include "rtc_base/network_constants.h" #include "rtc_base/network_constants.h"
#include "rtc_base/socket_address.h" #include "rtc_base/socket_address.h"
@ -33,32 +34,32 @@ class RTC_EXPORT Candidate {
// TODO(pthatcher): Match the ordering and param list as per RFC 5245 // TODO(pthatcher): Match the ordering and param list as per RFC 5245
// candidate-attribute syntax. http://tools.ietf.org/html/rfc5245#section-15.1 // candidate-attribute syntax. http://tools.ietf.org/html/rfc5245#section-15.1
Candidate(int component, Candidate(int component,
const std::string& protocol, absl::string_view protocol,
const rtc::SocketAddress& address, const rtc::SocketAddress& address,
uint32_t priority, uint32_t priority,
const std::string& username, absl::string_view username,
const std::string& password, absl::string_view password,
const std::string& type, absl::string_view type,
uint32_t generation, uint32_t generation,
const std::string& foundation, absl::string_view foundation,
uint16_t network_id = 0, uint16_t network_id = 0,
uint16_t network_cost = 0); uint16_t network_cost = 0);
Candidate(const Candidate&); Candidate(const Candidate&);
~Candidate(); ~Candidate();
const std::string& id() const { return id_; } const std::string& id() const { return id_; }
void set_id(const std::string& id) { id_ = id; } void set_id(absl::string_view id) { Assign(id_, id); }
int component() const { return component_; } int component() const { return component_; }
void set_component(int component) { component_ = component; } void set_component(int component) { component_ = component; }
const std::string& protocol() const { return protocol_; } const std::string& protocol() const { return protocol_; }
void set_protocol(const std::string& protocol) { protocol_ = protocol; } void set_protocol(absl::string_view protocol) { Assign(protocol_, protocol); }
// The protocol used to talk to relay. // The protocol used to talk to relay.
const std::string& relay_protocol() const { return relay_protocol_; } const std::string& relay_protocol() const { return relay_protocol_; }
void set_relay_protocol(const std::string& protocol) { void set_relay_protocol(absl::string_view protocol) {
relay_protocol_ = protocol; Assign(relay_protocol_, protocol);
} }
const rtc::SocketAddress& address() const { return address_; } const rtc::SocketAddress& address() const { return address_; }
@ -90,17 +91,17 @@ class RTC_EXPORT Candidate {
// TODO(honghaiz): Change to usernameFragment or ufrag. // TODO(honghaiz): Change to usernameFragment or ufrag.
const std::string& username() const { return username_; } const std::string& username() const { return username_; }
void set_username(const std::string& username) { username_ = username; } void set_username(absl::string_view username) { Assign(username_, username); }
const std::string& password() const { return password_; } const std::string& password() const { return password_; }
void set_password(const std::string& password) { password_ = password; } void set_password(absl::string_view password) { Assign(password_, password); }
const std::string& type() const { return type_; } const std::string& type() const { return type_; }
void set_type(const std::string& type) { type_ = type; } void set_type(absl::string_view type) { Assign(type_, type); }
const std::string& network_name() const { return network_name_; } const std::string& network_name() const { return network_name_; }
void set_network_name(const std::string& network_name) { void set_network_name(absl::string_view network_name) {
network_name_ = network_name; Assign(network_name_, network_name);
} }
rtc::AdapterType network_type() const { return network_type_; } rtc::AdapterType network_type() const { return network_type_; }
@ -108,6 +109,13 @@ class RTC_EXPORT Candidate {
network_type_ = network_type; network_type_ = network_type;
} }
rtc::AdapterType underlying_type_for_vpn() const {
return underlying_type_for_vpn_;
}
void set_underlying_type_for_vpn(rtc::AdapterType network_type) {
underlying_type_for_vpn_ = network_type;
}
// Candidates in a new generation replace those in the old generation. // Candidates in a new generation replace those in the old generation.
uint32_t generation() const { return generation_; } uint32_t generation() const { return generation_; }
void set_generation(uint32_t generation) { generation_ = generation; } void set_generation(uint32_t generation) { generation_ = generation; }
@ -126,8 +134,8 @@ class RTC_EXPORT Candidate {
void set_network_id(uint16_t network_id) { network_id_ = network_id; } void set_network_id(uint16_t network_id) { network_id_ = network_id; }
const std::string& foundation() const { return foundation_; } const std::string& foundation() const { return foundation_; }
void set_foundation(const std::string& foundation) { void set_foundation(absl::string_view foundation) {
foundation_ = foundation; Assign(foundation_, foundation);
} }
const rtc::SocketAddress& related_address() const { return related_address_; } const rtc::SocketAddress& related_address() const { return related_address_; }
@ -135,18 +143,18 @@ class RTC_EXPORT Candidate {
related_address_ = related_address; related_address_ = related_address;
} }
const std::string& tcptype() const { return tcptype_; } const std::string& tcptype() const { return tcptype_; }
void set_tcptype(const std::string& tcptype) { tcptype_ = tcptype; } void set_tcptype(absl::string_view tcptype) { Assign(tcptype_, tcptype); }
// The name of the transport channel of this candidate. // The name of the transport channel of this candidate.
// TODO(phoglund): remove. // TODO(phoglund): remove.
const std::string& transport_name() const { return transport_name_; } const std::string& transport_name() const { return transport_name_; }
void set_transport_name(const std::string& transport_name) { void set_transport_name(absl::string_view transport_name) {
transport_name_ = transport_name; Assign(transport_name_, transport_name);
} }
// The URL of the ICE server which this candidate is gathered from. // The URL of the ICE server which this candidate is gathered from.
const std::string& url() const { return url_; } const std::string& url() const { return url_; }
void set_url(const std::string& url) { url_ = url; } void set_url(absl::string_view url) { Assign(url_, url); }
// Determines whether this candidate is equivalent to the given one. // Determines whether this candidate is equivalent to the given one.
bool IsEquivalent(const Candidate& c) const; bool IsEquivalent(const Candidate& c) const;
@ -177,6 +185,10 @@ class RTC_EXPORT Candidate {
bool filter_related_address) const; bool filter_related_address) const;
private: private:
// TODO(bugs.webrtc.org/13220): With C++17, we get a std::string assignment
// operator accepting any object implicitly convertible to std::string_view,
// and then we don't need this workaround.
static void Assign(std::string& s, absl::string_view view);
std::string ToStringInternal(bool sensitive) const; std::string ToStringInternal(bool sensitive) const;
std::string id_; std::string id_;
@ -190,6 +202,7 @@ class RTC_EXPORT Candidate {
std::string type_; std::string type_;
std::string network_name_; std::string network_name_;
rtc::AdapterType network_type_; rtc::AdapterType network_type_;
rtc::AdapterType underlying_type_for_vpn_;
uint32_t generation_; uint32_t generation_;
std::string foundation_; std::string foundation_;
rtc::SocketAddress related_address_; rtc::SocketAddress related_address_;

View file

@ -49,6 +49,10 @@ rtc::scoped_refptr<PeerConnectionFactoryInterface> CreatePeerConnectionFactory(
dependencies.task_queue_factory.get()); dependencies.task_queue_factory.get());
dependencies.trials = std::make_unique<webrtc::FieldTrialBasedConfig>(); dependencies.trials = std::make_unique<webrtc::FieldTrialBasedConfig>();
if (network_thread) {
// TODO(bugs.webrtc.org/13145): Add an rtc::SocketFactory* argument.
dependencies.socket_factory = network_thread->socketserver();
}
cricket::MediaEngineDependencies media_dependencies; cricket::MediaEngineDependencies media_dependencies;
media_dependencies.task_queue_factory = dependencies.task_queue_factory.get(); media_dependencies.task_queue_factory = dependencies.task_queue_factory.get();
media_dependencies.adm = std::move(default_adm); media_dependencies.adm = std::move(default_adm);

View file

@ -40,4 +40,8 @@ bool DataChannelInterface::negotiated() const {
return false; return false;
} }
uint64_t DataChannelInterface::MaxSendQueueSize() {
return 16 * 1024 * 1024; // 16 MiB
}
} // namespace webrtc } // namespace webrtc

View file

@ -174,6 +174,7 @@ class RTC_EXPORT DataChannelInterface : public rtc::RefCountInterface {
// Returns the number of bytes of application data (UTF-8 text and binary // Returns the number of bytes of application data (UTF-8 text and binary
// data) that have been queued using Send but have not yet been processed at // data) that have been queued using Send but have not yet been processed at
// the SCTP level. See comment above Send below. // the SCTP level. See comment above Send below.
// Values are less or equal to MaxSendQueueSize().
virtual uint64_t buffered_amount() const = 0; virtual uint64_t buffered_amount() const = 0;
// Begins the graceful data channel closing procedure. See: // Begins the graceful data channel closing procedure. See:
@ -182,14 +183,16 @@ class RTC_EXPORT DataChannelInterface : public rtc::RefCountInterface {
// Sends `data` to the remote peer. If the data can't be sent at the SCTP // Sends `data` to the remote peer. If the data can't be sent at the SCTP
// level (due to congestion control), it's buffered at the data channel level, // level (due to congestion control), it's buffered at the data channel level,
// up to a maximum of 16MB. If Send is called while this buffer is full, the // up to a maximum of MaxSendQueueSize().
// data channel will be closed abruptly. // Returns false if the data channel is not in open state or if the send
// // buffer is full.
// So, it's important to use buffered_amount() and OnBufferedAmountChange to // TODO(webrtc:13289): Return an RTCError with information about the failure.
// ensure the data channel is used efficiently but without filling this
// buffer.
virtual bool Send(const DataBuffer& buffer) = 0; virtual bool Send(const DataBuffer& buffer) = 0;
// Amount of bytes that can be queued for sending on the data channel.
// Those are bytes that have not yet been processed at the SCTP level.
static uint64_t MaxSendQueueSize();
protected: protected:
~DataChannelInterface() override = default; ~DataChannelInterface() override = default;
}; };

View file

@ -20,11 +20,27 @@ DtlsTransportInformation::DtlsTransportInformation(DtlsTransportState state)
DtlsTransportInformation::DtlsTransportInformation( DtlsTransportInformation::DtlsTransportInformation(
DtlsTransportState state, DtlsTransportState state,
absl::optional<DtlsTransportTlsRole> role,
absl::optional<int> tls_version, absl::optional<int> tls_version,
absl::optional<int> ssl_cipher_suite, absl::optional<int> ssl_cipher_suite,
absl::optional<int> srtp_cipher_suite, absl::optional<int> srtp_cipher_suite,
std::unique_ptr<rtc::SSLCertChain> remote_ssl_certificates) std::unique_ptr<rtc::SSLCertChain> remote_ssl_certificates)
: state_(state), : state_(state),
role_(role),
tls_version_(tls_version),
ssl_cipher_suite_(ssl_cipher_suite),
srtp_cipher_suite_(srtp_cipher_suite),
remote_ssl_certificates_(std::move(remote_ssl_certificates)) {}
// Deprecated version
DtlsTransportInformation::DtlsTransportInformation(
DtlsTransportState state,
absl::optional<int> tls_version,
absl::optional<int> ssl_cipher_suite,
absl::optional<int> srtp_cipher_suite,
std::unique_ptr<rtc::SSLCertChain> remote_ssl_certificates)
: state_(state),
role_(absl::nullopt),
tls_version_(tls_version), tls_version_(tls_version),
ssl_cipher_suite_(ssl_cipher_suite), ssl_cipher_suite_(ssl_cipher_suite),
srtp_cipher_suite_(srtp_cipher_suite), srtp_cipher_suite_(srtp_cipher_suite),
@ -33,6 +49,7 @@ DtlsTransportInformation::DtlsTransportInformation(
DtlsTransportInformation::DtlsTransportInformation( DtlsTransportInformation::DtlsTransportInformation(
const DtlsTransportInformation& c) const DtlsTransportInformation& c)
: state_(c.state()), : state_(c.state()),
role_(c.role_),
tls_version_(c.tls_version_), tls_version_(c.tls_version_),
ssl_cipher_suite_(c.ssl_cipher_suite_), ssl_cipher_suite_(c.ssl_cipher_suite_),
srtp_cipher_suite_(c.srtp_cipher_suite_), srtp_cipher_suite_(c.srtp_cipher_suite_),
@ -43,6 +60,7 @@ DtlsTransportInformation::DtlsTransportInformation(
DtlsTransportInformation& DtlsTransportInformation::operator=( DtlsTransportInformation& DtlsTransportInformation::operator=(
const DtlsTransportInformation& c) { const DtlsTransportInformation& c) {
state_ = c.state(); state_ = c.state();
role_ = c.role_;
tls_version_ = c.tls_version_; tls_version_ = c.tls_version_;
ssl_cipher_suite_ = c.ssl_cipher_suite_; ssl_cipher_suite_ = c.ssl_cipher_suite_;
srtp_cipher_suite_ = c.srtp_cipher_suite_; srtp_cipher_suite_ = c.srtp_cipher_suite_;

View file

@ -36,6 +36,11 @@ enum class DtlsTransportState {
kNumValues kNumValues
}; };
enum class DtlsTransportTlsRole {
kServer, // Other end sends CLIENT_HELLO
kClient // This end sends CLIENT_HELLO
};
// This object gives snapshot information about the changeable state of a // This object gives snapshot information about the changeable state of a
// DTLSTransport. // DTLSTransport.
class RTC_EXPORT DtlsTransportInformation { class RTC_EXPORT DtlsTransportInformation {
@ -44,10 +49,19 @@ class RTC_EXPORT DtlsTransportInformation {
explicit DtlsTransportInformation(DtlsTransportState state); explicit DtlsTransportInformation(DtlsTransportState state);
DtlsTransportInformation( DtlsTransportInformation(
DtlsTransportState state, DtlsTransportState state,
absl::optional<DtlsTransportTlsRole> role,
absl::optional<int> tls_version, absl::optional<int> tls_version,
absl::optional<int> ssl_cipher_suite, absl::optional<int> ssl_cipher_suite,
absl::optional<int> srtp_cipher_suite, absl::optional<int> srtp_cipher_suite,
std::unique_ptr<rtc::SSLCertChain> remote_ssl_certificates); std::unique_ptr<rtc::SSLCertChain> remote_ssl_certificates);
ABSL_DEPRECATED("Use version with role parameter")
DtlsTransportInformation(
DtlsTransportState state,
absl::optional<int> tls_version,
absl::optional<int> ssl_cipher_suite,
absl::optional<int> srtp_cipher_suite,
std::unique_ptr<rtc::SSLCertChain> remote_ssl_certificates);
// Copy and assign // Copy and assign
DtlsTransportInformation(const DtlsTransportInformation& c); DtlsTransportInformation(const DtlsTransportInformation& c);
DtlsTransportInformation& operator=(const DtlsTransportInformation& c); DtlsTransportInformation& operator=(const DtlsTransportInformation& c);
@ -57,6 +71,7 @@ class RTC_EXPORT DtlsTransportInformation {
default; default;
DtlsTransportState state() const { return state_; } DtlsTransportState state() const { return state_; }
absl::optional<DtlsTransportTlsRole> role() const { return role_; }
absl::optional<int> tls_version() const { return tls_version_; } absl::optional<int> tls_version() const { return tls_version_; }
absl::optional<int> ssl_cipher_suite() const { return ssl_cipher_suite_; } absl::optional<int> ssl_cipher_suite() const { return ssl_cipher_suite_; }
absl::optional<int> srtp_cipher_suite() const { return srtp_cipher_suite_; } absl::optional<int> srtp_cipher_suite() const { return srtp_cipher_suite_; }
@ -67,6 +82,7 @@ class RTC_EXPORT DtlsTransportInformation {
private: private:
DtlsTransportState state_; DtlsTransportState state_;
absl::optional<DtlsTransportTlsRole> role_;
absl::optional<int> tls_version_; absl::optional<int> tls_version_;
absl::optional<int> ssl_cipher_suite_; absl::optional<int> ssl_cipher_suite_;
absl::optional<int> srtp_cipher_suite_; absl::optional<int> srtp_cipher_suite_;

View file

@ -58,18 +58,9 @@ rtc::scoped_refptr<IceTransportInterface> CreateIceTransport(
rtc::scoped_refptr<IceTransportInterface> CreateIceTransport( rtc::scoped_refptr<IceTransportInterface> CreateIceTransport(
IceTransportInit init) { IceTransportInit init) {
if (init.async_resolver_factory()) {
// Backwards compatibility mode
return rtc::make_ref_counted<IceTransportWithTransportChannel>(
std::make_unique<cricket::P2PTransportChannel>(
"", cricket::ICE_CANDIDATE_COMPONENT_RTP, init.port_allocator(),
init.async_resolver_factory(), init.event_log()));
} else {
return rtc::make_ref_counted<IceTransportWithTransportChannel>( return rtc::make_ref_counted<IceTransportWithTransportChannel>(
cricket::P2PTransportChannel::Create( cricket::P2PTransportChannel::Create(
"", cricket::ICE_CANDIDATE_COMPONENT_RTP, init.port_allocator(), "", cricket::ICE_CANDIDATE_COMPONENT_RTP, std::move(init)));
init.async_dns_resolver_factory(), init.event_log()));
}
} }
} // namespace webrtc } // namespace webrtc

View file

@ -23,9 +23,11 @@
namespace cricket { namespace cricket {
class IceTransportInternal; class IceTransportInternal;
class PortAllocator; class PortAllocator;
class IceControllerFactoryInterface;
} // namespace cricket } // namespace cricket
namespace webrtc { namespace webrtc {
class WebRtcKeyValueConfig;
// An ICE transport, as represented to the outside world. // An ICE transport, as represented to the outside world.
// This object is refcounted, and is therefore alive until the // This object is refcounted, and is therefore alive until the
@ -74,12 +76,27 @@ struct IceTransportInit final {
RtcEventLog* event_log() { return event_log_; } RtcEventLog* event_log() { return event_log_; }
void set_event_log(RtcEventLog* event_log) { event_log_ = event_log; } void set_event_log(RtcEventLog* event_log) { event_log_ = event_log; }
void set_ice_controller_factory(
cricket::IceControllerFactoryInterface* ice_controller_factory) {
ice_controller_factory_ = ice_controller_factory;
}
cricket::IceControllerFactoryInterface* ice_controller_factory() {
return ice_controller_factory_;
}
const WebRtcKeyValueConfig* field_trials() { return field_trials_; }
void set_field_trials(const WebRtcKeyValueConfig* field_trials) {
field_trials_ = field_trials;
}
private: private:
cricket::PortAllocator* port_allocator_ = nullptr; cricket::PortAllocator* port_allocator_ = nullptr;
AsyncDnsResolverFactoryInterface* async_dns_resolver_factory_ = nullptr; AsyncDnsResolverFactoryInterface* async_dns_resolver_factory_ = nullptr;
// For backwards compatibility. Only one resolver factory can be set. // For backwards compatibility. Only one resolver factory can be set.
AsyncResolverFactory* async_resolver_factory_ = nullptr; AsyncResolverFactory* async_resolver_factory_ = nullptr;
RtcEventLog* event_log_ = nullptr; RtcEventLog* event_log_ = nullptr;
cricket::IceControllerFactoryInterface* ice_controller_factory_ = nullptr;
const WebRtcKeyValueConfig* field_trials_ = nullptr;
// TODO(https://crbug.com/webrtc/12657): Redesign to have const members. // TODO(https://crbug.com/webrtc/12657): Redesign to have const members.
}; };

View file

@ -22,7 +22,6 @@
#include "api/candidate.h" #include "api/candidate.h"
#include "api/jsep.h" #include "api/jsep.h"
#include "rtc_base/constructor_magic.h"
#include "rtc_base/system/rtc_export.h" #include "rtc_base/system/rtc_export.h"
namespace webrtc { namespace webrtc {
@ -64,6 +63,10 @@ class JsepCandidateCollection : public IceCandidateCollection {
// Move constructor is defined so that a vector of JsepCandidateCollections // Move constructor is defined so that a vector of JsepCandidateCollections
// can be resized. // can be resized.
JsepCandidateCollection(JsepCandidateCollection&& o); JsepCandidateCollection(JsepCandidateCollection&& o);
JsepCandidateCollection(const JsepCandidateCollection&) = delete;
JsepCandidateCollection& operator=(const JsepCandidateCollection&) = delete;
// Returns a copy of the candidate collection. // Returns a copy of the candidate collection.
JsepCandidateCollection Clone() const; JsepCandidateCollection Clone() const;
size_t count() const override; size_t count() const override;
@ -80,8 +83,6 @@ class JsepCandidateCollection : public IceCandidateCollection {
private: private:
std::vector<std::unique_ptr<JsepIceCandidate>> candidates_; std::vector<std::unique_ptr<JsepIceCandidate>> candidates_;
RTC_DISALLOW_COPY_AND_ASSIGN(JsepCandidateCollection);
}; };
} // namespace webrtc } // namespace webrtc

View file

@ -22,7 +22,6 @@
#include "api/candidate.h" #include "api/candidate.h"
#include "api/jsep.h" #include "api/jsep.h"
#include "api/jsep_ice_candidate.h" #include "api/jsep_ice_candidate.h"
#include "rtc_base/constructor_magic.h"
namespace cricket { namespace cricket {
class SessionDescription; class SessionDescription;
@ -43,6 +42,9 @@ class JsepSessionDescription : public SessionDescriptionInterface {
absl::string_view session_version); absl::string_view session_version);
virtual ~JsepSessionDescription(); virtual ~JsepSessionDescription();
JsepSessionDescription(const JsepSessionDescription&) = delete;
JsepSessionDescription& operator=(const JsepSessionDescription&) = delete;
// Takes ownership of `description`. // Takes ownership of `description`.
bool Initialize(std::unique_ptr<cricket::SessionDescription> description, bool Initialize(std::unique_ptr<cricket::SessionDescription> description,
const std::string& session_id, const std::string& session_id,
@ -82,8 +84,6 @@ class JsepSessionDescription : public SessionDescriptionInterface {
bool GetMediasectionIndex(const IceCandidateInterface* candidate, bool GetMediasectionIndex(const IceCandidateInterface* candidate,
size_t* index); size_t* index);
int GetMediasectionIndex(const cricket::Candidate& candidate); int GetMediasectionIndex(const cricket::Candidate& candidate);
RTC_DISALLOW_COPY_AND_ASSIGN(JsepSessionDescription);
}; };
} // namespace webrtc } // namespace webrtc

View file

@ -28,6 +28,7 @@
#include "api/video/video_frame.h" #include "api/video/video_frame.h"
#include "api/video/video_sink_interface.h" #include "api/video/video_sink_interface.h"
#include "api/video/video_source_interface.h" #include "api/video/video_source_interface.h"
#include "api/video_track_source_constraints.h"
#include "modules/audio_processing/include/audio_processing_statistics.h" #include "modules/audio_processing/include/audio_processing_statistics.h"
#include "rtc_base/ref_count.h" #include "rtc_base/ref_count.h"
#include "rtc_base/system/rtc_export.h" #include "rtc_base/system/rtc_export.h"
@ -146,8 +147,6 @@ class VideoTrackSourceInterface : public MediaSourceInterface,
// Add an encoded video sink to the source and additionally cause // Add an encoded video sink to the source and additionally cause
// a key frame to be generated from the source. The sink will be // a key frame to be generated from the source. The sink will be
// invoked from a decoder queue. // invoked from a decoder queue.
// TODO(bugs.webrtc.org/11114): make pure virtual once downstream project
// adapts.
virtual void AddEncodedSink( virtual void AddEncodedSink(
rtc::VideoSinkInterface<RecordableEncodedFrame>* sink) = 0; rtc::VideoSinkInterface<RecordableEncodedFrame>* sink) = 0;
@ -155,6 +154,13 @@ class VideoTrackSourceInterface : public MediaSourceInterface,
virtual void RemoveEncodedSink( virtual void RemoveEncodedSink(
rtc::VideoSinkInterface<RecordableEncodedFrame>* sink) = 0; rtc::VideoSinkInterface<RecordableEncodedFrame>* sink) = 0;
// Notify about constraints set on the source. The information eventually gets
// routed to attached sinks via VideoSinkInterface<>::OnConstraintsChanged.
// The call is expected to happen on the network thread.
// TODO(crbug/1255737): make pure virtual once downstream project adapts.
virtual void ProcessConstraints(
const webrtc::VideoTrackSourceConstraints& constraints) {}
protected: protected:
~VideoTrackSourceInterface() override = default; ~VideoTrackSourceInterface() override = default;
}; };
@ -197,7 +203,7 @@ class AudioTrackSinkInterface {
int sample_rate, int sample_rate,
size_t number_of_channels, size_t number_of_channels,
size_t number_of_frames) { size_t number_of_frames) {
RTC_NOTREACHED() << "This method must be overridden, or not used."; RTC_DCHECK_NOTREACHED() << "This method must be overridden, or not used.";
} }
// In this method, `absolute_capture_timestamp_ms`, when available, is // In this method, `absolute_capture_timestamp_ms`, when available, is
@ -327,6 +333,8 @@ class MediaStreamInterface : public rtc::RefCountInterface,
virtual rtc::scoped_refptr<VideoTrackInterface> FindVideoTrack( virtual rtc::scoped_refptr<VideoTrackInterface> FindVideoTrack(
const std::string& track_id) = 0; const std::string& track_id) = 0;
// Takes ownership of added tracks.
// TODO(hta): Should take scoped_refptr rather than raw pointer.
virtual bool AddTrack(AudioTrackInterface* track) = 0; virtual bool AddTrack(AudioTrackInterface* track) = 0;
virtual bool AddTrack(VideoTrackInterface* track) = 0; virtual bool AddTrack(VideoTrackInterface* track) = 0;
virtual bool RemoveTrack(AudioTrackInterface* track) = 0; virtual bool RemoveTrack(AudioTrackInterface* track) = 0;

View file

@ -28,7 +28,7 @@ std::string MediaTypeToString(MediaType type) {
return kMediaTypeData; return kMediaTypeData;
case MEDIA_TYPE_UNSUPPORTED: case MEDIA_TYPE_UNSUPPORTED:
// Unsupported media stores the m=<mediatype> differently. // Unsupported media stores the m=<mediatype> differently.
RTC_NOTREACHED(); RTC_DCHECK_NOTREACHED();
return ""; return "";
} }
RTC_CHECK_NOTREACHED(); RTC_CHECK_NOTREACHED();

View file

@ -1,15 +1,19 @@
#!/bin/sh # Copyright (c) 2022 The WebRTC project authors. All Rights Reserved.
#
# Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
# #
# Use of this source code is governed by a BSD-style license # Use of this source code is governed by a BSD-style license
# that can be found in the LICENSE file in the root of the source # that can be found in the LICENSE file in the root of the source
# tree. An additional intellectual property rights grant can be found # tree. An additional intellectual property rights grant can be found
# in the file PATENTS. All contributing project authors may # in the file PATENTS. All contributing project authors may
# be found in the AUTHORS file in the root of the source tree. # be found in the AUTHORS file in the root of the source tree.
#
# This script is used to launch a simple http server for files in the same import("../../webrtc.gni")
# location as the script itself.
cd "`dirname \"$0\"`" rtc_source_set("metronome") {
echo "Starting http server in port 8080." visibility = [ "*" ]
exec python -m SimpleHTTPServer 8080 sources = [ "metronome.h" ]
deps = [
"../../rtc_base/system:rtc_export",
"../task_queue",
"../units:time_delta",
]
}

65
api/metronome/metronome.h Normal file
View file

@ -0,0 +1,65 @@
/*
* Copyright (c) 2022 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef API_METRONOME_METRONOME_H_
#define API_METRONOME_METRONOME_H_
#include "api/task_queue/task_queue_base.h"
#include "api/units/time_delta.h"
#include "rtc_base/system/rtc_export.h"
namespace webrtc {
// The Metronome posts OnTick() on task queues provided by its listeners' task
// queue periodically. The metronome can be used as an alternative to using
// PostDelayedTask on a thread or task queue for coalescing work and reducing
// the number of idle-wakeups.
//
// Listeners can be added and removed from any sequence, but it is illegal to
// remove a listener from an OnTick invocation.
//
// The metronome concept is still under experimentation, and may not be availble
// in all platforms or applications. See https://crbug.com/1253787 for more
// details.
//
// Metronome implementations must be thread-safe.
class RTC_EXPORT Metronome {
public:
class RTC_EXPORT TickListener {
public:
virtual ~TickListener() = default;
// OnTick is run on the task queue provided by OnTickTaskQueue each time the
// metronome ticks.
virtual void OnTick() = 0;
// The task queue that OnTick will run on. Must not be null.
virtual TaskQueueBase* OnTickTaskQueue() = 0;
};
virtual ~Metronome() = default;
// Adds a tick listener to the metronome. Once this method has returned
// OnTick will be invoked on each metronome tick. A listener may
// only be added to the metronome once.
virtual void AddListener(TickListener* listener) = 0;
// Removes the tick listener from the metronome. Once this method has returned
// OnTick will never be called again. This method must not be called from
// within OnTick.
virtual void RemoveListener(TickListener* listener) = 0;
// Returns the current tick period of the metronome.
virtual TimeDelta TickPeriod() const = 0;
};
} // namespace webrtc
#endif // API_METRONOME_METRONOME_H_

View file

@ -0,0 +1,30 @@
# Copyright (c) 2022 The WebRTC project authors. All Rights Reserved.
#
# Use of this source code is governed by a BSD-style license
# that can be found in the LICENSE file in the root of the source
# tree. An additional intellectual property rights grant can be found
# in the file PATENTS. All contributing project authors may
# be found in the AUTHORS file in the root of the source tree.
import("../../../webrtc.gni")
rtc_library("fake_metronome") {
testonly = true
sources = [
"fake_metronome.cc",
"fake_metronome.h",
]
deps = [
"..:metronome",
"../..:priority",
"../..:sequence_checker",
"../../../rtc_base:macromagic",
"../../../rtc_base:rtc_event",
"../../../rtc_base:rtc_task_queue",
"../../../rtc_base/synchronization:mutex",
"../../../rtc_base/task_utils:repeating_task",
"../../../rtc_base/task_utils:to_queued_task",
"../../task_queue",
"../../units:time_delta",
]
}

View file

@ -0,0 +1,93 @@
/*
* Copyright (c) 2022 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "api/metronome/test/fake_metronome.h"
#include "api/priority.h"
#include "api/sequence_checker.h"
#include "api/task_queue/task_queue_factory.h"
#include "api/units/time_delta.h"
#include "rtc_base/event.h"
#include "rtc_base/task_utils/repeating_task.h"
#include "rtc_base/task_utils/to_queued_task.h"
namespace webrtc::test {
ForcedTickMetronome::ForcedTickMetronome(TimeDelta tick_period)
: tick_period_(tick_period) {}
void ForcedTickMetronome::AddListener(TickListener* listener) {
listeners_.insert(listener);
}
void ForcedTickMetronome::RemoveListener(TickListener* listener) {
listeners_.erase(listener);
}
TimeDelta ForcedTickMetronome::TickPeriod() const {
return tick_period_;
}
size_t ForcedTickMetronome::NumListeners() {
return listeners_.size();
}
void ForcedTickMetronome::Tick() {
for (auto* listener : listeners_) {
listener->OnTickTaskQueue()->PostTask(
ToQueuedTask([listener] { listener->OnTick(); }));
}
}
FakeMetronome::FakeMetronome(TaskQueueFactory* factory, TimeDelta tick_period)
: tick_period_(tick_period),
queue_(factory->CreateTaskQueue("MetronomeQueue",
TaskQueueFactory::Priority::HIGH)) {}
FakeMetronome::~FakeMetronome() {
RTC_DCHECK(listeners_.empty());
}
void FakeMetronome::AddListener(TickListener* listener) {
MutexLock lock(&mutex_);
listeners_.insert(listener);
if (!started_) {
tick_task_ = RepeatingTaskHandle::Start(queue_.Get(), [this] {
MutexLock lock(&mutex_);
// Stop if empty.
if (listeners_.empty())
return TimeDelta::PlusInfinity();
for (auto* listener : listeners_) {
listener->OnTickTaskQueue()->PostTask(
ToQueuedTask([listener] { listener->OnTick(); }));
}
return tick_period_;
});
started_ = true;
}
}
void FakeMetronome::RemoveListener(TickListener* listener) {
MutexLock lock(&mutex_);
listeners_.erase(listener);
}
void FakeMetronome::Stop() {
MutexLock lock(&mutex_);
RTC_DCHECK(listeners_.empty());
if (started_)
queue_.PostTask([this] { tick_task_.Stop(); });
}
TimeDelta FakeMetronome::TickPeriod() const {
return tick_period_;
}
} // namespace webrtc::test

View file

@ -0,0 +1,77 @@
/*
* Copyright (c) 2022 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef API_METRONOME_TEST_FAKE_METRONOME_H_
#define API_METRONOME_TEST_FAKE_METRONOME_H_
#include <memory>
#include <set>
#include "api/metronome/metronome.h"
#include "api/task_queue/task_queue_base.h"
#include "api/task_queue/task_queue_factory.h"
#include "api/units/time_delta.h"
#include "rtc_base/synchronization/mutex.h"
#include "rtc_base/task_queue.h"
#include "rtc_base/task_utils/repeating_task.h"
#include "rtc_base/thread_annotations.h"
namespace webrtc::test {
// ForcedTickMetronome is a Metronome that ticks when `Tick()` is invoked.
// The constructor argument `tick_period` returned in `TickPeriod()`.
class ForcedTickMetronome : public Metronome {
public:
explicit ForcedTickMetronome(TimeDelta tick_period);
// Forces all TickListeners to run `OnTick`.
void Tick();
size_t NumListeners();
// Metronome implementation.
void AddListener(TickListener* listener) override;
void RemoveListener(TickListener* listener) override;
TimeDelta TickPeriod() const override;
private:
const TimeDelta tick_period_;
std::set<TickListener*> listeners_;
};
// FakeMetronome is a metronome that ticks based on a repeating task at the
// `tick_period` provided in the constructor. It is designed for use with
// simulated task queues for unit tests.
//
// `Stop()` must be called before destruction, as it cancels the metronome tick
// on the proper task queue.
class FakeMetronome : public Metronome {
public:
FakeMetronome(TaskQueueFactory* factory, TimeDelta tick_period);
~FakeMetronome() override;
// Metronome implementation.
void AddListener(TickListener* listener) override;
void RemoveListener(TickListener* listener) override;
TimeDelta TickPeriod() const override;
void Stop();
private:
const TimeDelta tick_period_;
RepeatingTaskHandle tick_task_;
bool started_ RTC_GUARDED_BY(mutex_) = false;
std::set<TickListener*> listeners_ RTC_GUARDED_BY(mutex_);
Mutex mutex_;
rtc::TaskQueue queue_;
};
} // namespace webrtc::test
#endif // API_METRONOME_TEST_FAKE_METRONOME_H_

View file

@ -30,8 +30,7 @@ std::string NetEq::Config::ToString() const {
<< ", min_delay_ms=" << min_delay_ms << ", enable_fast_accelerate=" << ", min_delay_ms=" << min_delay_ms << ", enable_fast_accelerate="
<< (enable_fast_accelerate ? "true" : "false") << (enable_fast_accelerate ? "true" : "false")
<< ", enable_muted_state=" << (enable_muted_state ? "true" : "false") << ", enable_muted_state=" << (enable_muted_state ? "true" : "false")
<< ", enable_rtx_handling=" << (enable_rtx_handling ? "true" : "false") << ", enable_rtx_handling=" << (enable_rtx_handling ? "true" : "false");
<< ", extra_output_delay_ms=" << extra_output_delay_ms;
return ss.str(); return ss.str();
} }

View file

@ -136,10 +136,6 @@ class NetEq {
bool enable_rtx_handling = false; bool enable_rtx_handling = false;
absl::optional<AudioCodecPairId> codec_pair_id; absl::optional<AudioCodecPairId> codec_pair_id;
bool for_test_no_time_stretching = false; // Use only for testing. bool for_test_no_time_stretching = false; // Use only for testing.
// Adds extra delay to the output of NetEq, without affecting jitter or
// loss behavior. This is mainly for testing. Value must be a non-negative
// multiple of 10 ms.
int extra_output_delay_ms = 0;
}; };
enum ReturnCodes { kOK = 0, kFail = -1 }; enum ReturnCodes { kOK = 0, kFail = -1 };
@ -183,14 +179,6 @@ class NetEq {
SdpAudioFormat sdp_format; SdpAudioFormat sdp_format;
}; };
// Creates a new NetEq object, with parameters set in `config`. The `config`
// object will only have to be valid for the duration of the call to this
// method.
static NetEq* Create(
const NetEq::Config& config,
Clock* clock,
const rtc::scoped_refptr<AudioDecoderFactory>& decoder_factory);
virtual ~NetEq() {} virtual ~NetEq() {}
// Inserts a new packet into NetEq. // Inserts a new packet into NetEq.

View file

@ -14,7 +14,9 @@
#include <list> #include <list>
#include "api/media_stream_interface.h" #include "api/media_stream_interface.h"
#include "api/sequence_checker.h"
#include "rtc_base/checks.h" #include "rtc_base/checks.h"
#include "rtc_base/system/no_unique_address.h"
namespace webrtc { namespace webrtc {
@ -23,14 +25,16 @@ namespace webrtc {
template <class T> template <class T>
class Notifier : public T { class Notifier : public T {
public: public:
Notifier() {} Notifier() { sequence_checker_.Detach(); }
virtual void RegisterObserver(ObserverInterface* observer) { virtual void RegisterObserver(ObserverInterface* observer) {
RTC_DCHECK_RUN_ON(&sequence_checker_);
RTC_DCHECK(observer != nullptr); RTC_DCHECK(observer != nullptr);
observers_.push_back(observer); observers_.push_back(observer);
} }
virtual void UnregisterObserver(ObserverInterface* observer) { virtual void UnregisterObserver(ObserverInterface* observer) {
RTC_DCHECK_RUN_ON(&sequence_checker_);
for (std::list<ObserverInterface*>::iterator it = observers_.begin(); for (std::list<ObserverInterface*>::iterator it = observers_.begin();
it != observers_.end(); it++) { it != observers_.end(); it++) {
if (*it == observer) { if (*it == observer) {
@ -41,6 +45,7 @@ class Notifier : public T {
} }
void FireOnChanged() { void FireOnChanged() {
RTC_DCHECK_RUN_ON(&sequence_checker_);
// Copy the list of observers to avoid a crash if the observer object // Copy the list of observers to avoid a crash if the observer object
// unregisters as a result of the OnChanged() call. If the same list is used // unregisters as a result of the OnChanged() call. If the same list is used
// UnregisterObserver will affect the list make the iterator invalid. // UnregisterObserver will affect the list make the iterator invalid.
@ -52,7 +57,10 @@ class Notifier : public T {
} }
protected: protected:
std::list<ObserverInterface*> observers_; std::list<ObserverInterface*> observers_ RTC_GUARDED_BY(sequence_checker_);
private:
RTC_NO_UNIQUE_ADDRESS SequenceChecker sequence_checker_;
}; };
} // namespace webrtc } // namespace webrtc

View file

@ -11,9 +11,12 @@
#ifndef API_PACKET_SOCKET_FACTORY_H_ #ifndef API_PACKET_SOCKET_FACTORY_H_
#define API_PACKET_SOCKET_FACTORY_H_ #define API_PACKET_SOCKET_FACTORY_H_
#include <memory>
#include <string> #include <string>
#include <vector> #include <vector>
#include "api/async_dns_resolver.h"
#include "api/wrapping_async_dns_resolver.h"
#include "rtc_base/async_packet_socket.h" #include "rtc_base/async_packet_socket.h"
#include "rtc_base/proxy_info.h" #include "rtc_base/proxy_info.h"
#include "rtc_base/system/rtc_export.h" #include "rtc_base/system/rtc_export.h"
@ -56,7 +59,7 @@ class RTC_EXPORT PacketSocketFactory {
virtual AsyncPacketSocket* CreateUdpSocket(const SocketAddress& address, virtual AsyncPacketSocket* CreateUdpSocket(const SocketAddress& address,
uint16_t min_port, uint16_t min_port,
uint16_t max_port) = 0; uint16_t max_port) = 0;
virtual AsyncPacketSocket* CreateServerTcpSocket( virtual AsyncListenSocket* CreateServerTcpSocket(
const SocketAddress& local_address, const SocketAddress& local_address,
uint16_t min_port, uint16_t min_port,
uint16_t max_port, uint16_t max_port,
@ -69,7 +72,23 @@ class RTC_EXPORT PacketSocketFactory {
const std::string& user_agent, const std::string& user_agent,
const PacketSocketTcpOptions& tcp_options) = 0; const PacketSocketTcpOptions& tcp_options) = 0;
virtual AsyncResolverInterface* CreateAsyncResolver() = 0; // The AsyncResolverInterface is deprecated; users are encouraged
// to switch to the AsyncDnsResolverInterface.
// TODO(bugs.webrtc.org/12598): Remove once all downstream users
// are converted.
virtual AsyncResolverInterface* CreateAsyncResolver() {
// Default implementation, so that downstream users can remove this
// immediately after changing to CreateAsyncDnsResolver
RTC_DCHECK_NOTREACHED();
return nullptr;
}
virtual std::unique_ptr<webrtc::AsyncDnsResolverInterface>
CreateAsyncDnsResolver() {
// Default implementation, to aid in transition to AsyncDnsResolverInterface
return std::make_unique<webrtc::WrappingAsyncDnsResolver>(
CreateAsyncResolver());
}
private: private:
PacketSocketFactory(const PacketSocketFactory&) = delete; PacketSocketFactory(const PacketSocketFactory&) = delete;

View file

@ -41,12 +41,6 @@ PeerConnectionInterface::RTCConfiguration::RTCConfiguration(
PeerConnectionInterface::RTCConfiguration::~RTCConfiguration() = default; PeerConnectionInterface::RTCConfiguration::~RTCConfiguration() = default;
RTCError PeerConnectionInterface::RemoveTrackNew(
rtc::scoped_refptr<RtpSenderInterface> sender) {
return RTCError(RemoveTrack(sender) ? RTCErrorType::NONE
: RTCErrorType::INTERNAL_ERROR);
}
RTCError PeerConnectionInterface::SetConfiguration( RTCError PeerConnectionInterface::SetConfiguration(
const PeerConnectionInterface::RTCConfiguration& config) { const PeerConnectionInterface::RTCConfiguration& config) {
return RTCError(); return RTCError();

View file

@ -76,6 +76,7 @@
#include <vector> #include <vector>
#include "absl/base/attributes.h" #include "absl/base/attributes.h"
#include "absl/strings/string_view.h"
#include "absl/types/optional.h" #include "absl/types/optional.h"
#include "api/adaptation/resource.h" #include "api/adaptation/resource.h"
#include "api/async_dns_resolver.h" #include "api/async_dns_resolver.h"
@ -95,6 +96,7 @@
#include "api/jsep.h" #include "api/jsep.h"
#include "api/media_stream_interface.h" #include "api/media_stream_interface.h"
#include "api/media_types.h" #include "api/media_types.h"
#include "api/metronome/metronome.h"
#include "api/neteq/neteq_factory.h" #include "api/neteq/neteq_factory.h"
#include "api/network_state_predictor.h" #include "api/network_state_predictor.h"
#include "api/packet_socket_factory.h" #include "api/packet_socket_factory.h"
@ -171,7 +173,12 @@ class StatsObserver : public rtc::RefCountInterface {
~StatsObserver() override = default; ~StatsObserver() override = default;
}; };
enum class SdpSemantics { kPlanB, kUnifiedPlan }; enum class SdpSemantics {
// TODO(https://crbug.com/webrtc/13528): Remove support for kPlanB.
kPlanB_DEPRECATED,
kPlanB [[deprecated]] = kPlanB_DEPRECATED,
kUnifiedPlan,
};
class RTC_EXPORT PeerConnectionInterface : public rtc::RefCountInterface { class RTC_EXPORT PeerConnectionInterface : public rtc::RefCountInterface {
public: public:
@ -184,6 +191,7 @@ class RTC_EXPORT PeerConnectionInterface : public rtc::RefCountInterface {
kHaveRemotePrAnswer, kHaveRemotePrAnswer,
kClosed, kClosed,
}; };
static constexpr absl::string_view AsString(SignalingState);
// See https://w3c.github.io/webrtc-pc/#dom-rtcicegatheringstate // See https://w3c.github.io/webrtc-pc/#dom-rtcicegatheringstate
enum IceGatheringState { enum IceGatheringState {
@ -191,6 +199,7 @@ class RTC_EXPORT PeerConnectionInterface : public rtc::RefCountInterface {
kIceGatheringGathering, kIceGatheringGathering,
kIceGatheringComplete kIceGatheringComplete
}; };
static constexpr absl::string_view AsString(IceGatheringState state);
// See https://w3c.github.io/webrtc-pc/#dom-rtcpeerconnectionstate // See https://w3c.github.io/webrtc-pc/#dom-rtcpeerconnectionstate
enum class PeerConnectionState { enum class PeerConnectionState {
@ -201,6 +210,7 @@ class RTC_EXPORT PeerConnectionInterface : public rtc::RefCountInterface {
kFailed, kFailed,
kClosed, kClosed,
}; };
static constexpr absl::string_view AsString(PeerConnectionState state);
// See https://w3c.github.io/webrtc-pc/#dom-rtciceconnectionstate // See https://w3c.github.io/webrtc-pc/#dom-rtciceconnectionstate
enum IceConnectionState { enum IceConnectionState {
@ -213,6 +223,7 @@ class RTC_EXPORT PeerConnectionInterface : public rtc::RefCountInterface {
kIceConnectionClosed, kIceConnectionClosed,
kIceConnectionMax, kIceConnectionMax,
}; };
static constexpr absl::string_view AsString(IceConnectionState state);
// TLS certificate policy. // TLS certificate policy.
enum TlsCertPolicy { enum TlsCertPolicy {
@ -294,6 +305,13 @@ class RTC_EXPORT PeerConnectionInterface : public rtc::RefCountInterface {
enum ContinualGatheringPolicy { GATHER_ONCE, GATHER_CONTINUALLY }; enum ContinualGatheringPolicy { GATHER_ONCE, GATHER_CONTINUALLY };
struct PortAllocatorConfig {
// For min_port and max_port, 0 means not specified.
int min_port = 0;
int max_port = 0;
uint32_t flags = 0; // Same as kDefaultPortAllocatorFlags.
};
enum class RTCConfigurationType { enum class RTCConfigurationType {
// A configuration that is safer to use, despite not having the best // A configuration that is safer to use, despite not having the best
// performance. Currently this is the default configuration. // performance. Currently this is the default configuration.
@ -371,6 +389,18 @@ class RTC_EXPORT PeerConnectionInterface : public rtc::RefCountInterface {
video_rtcp_report_interval_ms; video_rtcp_report_interval_ms;
} }
// Settings for the port allcoator. Applied only if the port allocator is
// created by PeerConnectionFactory, not if it is injected with
// PeerConnectionDependencies
int min_port() const { return port_allocator_config.min_port; }
void set_min_port(int port) { port_allocator_config.min_port = port; }
int max_port() const { return port_allocator_config.max_port; }
void set_max_port(int port) { port_allocator_config.max_port = port; }
uint32_t port_allocator_flags() { return port_allocator_config.flags; }
void set_port_allocator_flags(uint32_t flags) {
port_allocator_config.flags = flags;
}
static const int kUndefined = -1; static const int kUndefined = -1;
// Default maximum number of packets in the audio jitter buffer. // Default maximum number of packets in the audio jitter buffer.
static const int kAudioJitterBufferMaxPackets = 200; static const int kAudioJitterBufferMaxPackets = 200;
@ -598,28 +628,27 @@ class RTC_EXPORT PeerConnectionInterface : public rtc::RefCountInterface {
// cost. // cost.
absl::optional<rtc::AdapterType> network_preference; absl::optional<rtc::AdapterType> network_preference;
// Configure the SDP semantics used by this PeerConnection. Note that the // Configure the SDP semantics used by this PeerConnection. By default, this
// WebRTC 1.0 specification requires kUnifiedPlan semantics. The // is Unified Plan which is compliant to the WebRTC 1.0 specification. It is
// RtpTransceiver API is only available with kUnifiedPlan semantics. // possible to overrwite this to the deprecated Plan B SDP format, but note
// that kPlanB will be deleted at some future date, see
// https://crbug.com/webrtc/13528.
// //
// kPlanB will cause PeerConnection to create offers and answers with at // kUnifiedPlan will cause the PeerConnection to create offers and answers
// with multiple m= sections where each m= section maps to one RtpSender and
// one RtpReceiver (an RtpTransceiver), either both audio or both video.
// This will also cause the PeerConnection to ignore all but the first
// a=ssrc lines that form a Plan B streams (if the PeerConnection is given
// Plan B SDP to process).
//
// kPlanB will cause the PeerConnection to create offers and answers with at
// most one audio and one video m= section with multiple RtpSenders and // most one audio and one video m= section with multiple RtpSenders and
// RtpReceivers specified as multiple a=ssrc lines within the section. This // RtpReceivers specified as multiple a=ssrc lines within the section. This
// will also cause PeerConnection to ignore all but the first m= section of // will also cause PeerConnection to ignore all but the first m= section of
// the same media type. // the same media type (if the PeerConnection is given Unified Plan SDP to
// // process).
// kUnifiedPlan will cause PeerConnection to create offers and answers with // RingRTC Change to use "Plan B"
// multiple m= sections where each m= section maps to one RtpSender and one SdpSemantics sdp_semantics = SdpSemantics::kPlanB_DEPRECATED;
// RtpReceiver (an RtpTransceiver), either both audio or both video. This
// will also cause PeerConnection to ignore all but the first a=ssrc lines
// that form a Plan B stream.
//
// For users who wish to send multiple audio/video streams and need to stay
// interoperable with legacy WebRTC implementations or use legacy APIs,
// specify kPlanB.
//
// For all other users, specify kUnifiedPlan.
SdpSemantics sdp_semantics = SdpSemantics::kPlanB;
// TODO(bugs.webrtc.org/9891) - Move to crypto_options or remove. // TODO(bugs.webrtc.org/9891) - Move to crypto_options or remove.
// Actively reset the SRTP parameters whenever the DTLS transports // Actively reset the SRTP parameters whenever the DTLS transports
@ -669,6 +698,8 @@ class RTC_EXPORT PeerConnectionInterface : public rtc::RefCountInterface {
// VPN (in case webrtc fails to auto detect them). // VPN (in case webrtc fails to auto detect them).
std::vector<rtc::NetworkMask> vpn_list; std::vector<rtc::NetworkMask> vpn_list;
PortAllocatorConfig port_allocator_config;
// //
// Don't forget to update operator== if adding something. // Don't forget to update operator== if adding something.
// //
@ -780,23 +811,25 @@ class RTC_EXPORT PeerConnectionInterface : public rtc::RefCountInterface {
rtc::scoped_refptr<MediaStreamTrackInterface> track, rtc::scoped_refptr<MediaStreamTrackInterface> track,
const std::vector<std::string>& stream_ids) = 0; const std::vector<std::string>& stream_ids) = 0;
// Remove an RtpSender from this PeerConnection. // Removes the connection between a MediaStreamTrack and the PeerConnection.
// Returns true on success. // Stops sending on the RtpSender and marks the
// TODO(steveanton): Replace with signature that returns RTCError.
virtual bool RemoveTrack(RtpSenderInterface* sender) = 0;
// Plan B semantics: Removes the RtpSender from this PeerConnection.
// Unified Plan semantics: Stop sending on the RtpSender and mark the
// corresponding RtpTransceiver direction as no longer sending. // corresponding RtpTransceiver direction as no longer sending.
// https://w3c.github.io/webrtc-pc/#dom-rtcpeerconnection-removetrack
// //
// Errors: // Errors:
// - INVALID_PARAMETER: `sender` is null or (Plan B only) the sender is not // - INVALID_PARAMETER: `sender` is null or (Plan B only) the sender is not
// associated with this PeerConnection. // associated with this PeerConnection.
// - INVALID_STATE: PeerConnection is closed. // - INVALID_STATE: PeerConnection is closed.
//
// Plan B semantics: Removes the RtpSender from this PeerConnection.
//
// TODO(bugs.webrtc.org/9534): Rename to RemoveTrack once the other signature // TODO(bugs.webrtc.org/9534): Rename to RemoveTrack once the other signature
// is removed. // is removed; remove default implementation once upstream is updated.
virtual RTCError RemoveTrackNew( virtual RTCError RemoveTrackOrError(
rtc::scoped_refptr<RtpSenderInterface> sender); rtc::scoped_refptr<RtpSenderInterface> sender) {
RTC_CHECK_NOTREACHED();
return RTCError();
}
// AddTransceiver creates a new RtpTransceiver and adds it to the set of // AddTransceiver creates a new RtpTransceiver and adds it to the set of
// transceivers. Adding a transceiver will cause future calls to CreateOffer // transceivers. Adding a transceiver will cause future calls to CreateOffer
@ -1311,14 +1344,6 @@ class PeerConnectionObserver : public RtpPacketSinkInterface {
// A new ICE candidate has been gathered. // A new ICE candidate has been gathered.
virtual void OnIceCandidate(const IceCandidateInterface* candidate) = 0; virtual void OnIceCandidate(const IceCandidateInterface* candidate) = 0;
// Gathering of an ICE candidate failed.
// See https://w3c.github.io/webrtc-pc/#event-icecandidateerror
// `host_candidate` is a stringified socket address.
virtual void OnIceCandidateError(const std::string& host_candidate,
const std::string& url,
int error_code,
const std::string& error_text) {}
// Gathering of an ICE candidate failed. // Gathering of an ICE candidate failed.
// See https://w3c.github.io/webrtc-pc/#event-icecandidateerror // See https://w3c.github.io/webrtc-pc/#event-icecandidateerror
virtual void OnIceCandidateError(const std::string& address, virtual void OnIceCandidateError(const std::string& address,
@ -1443,6 +1468,7 @@ struct RTC_EXPORT PeerConnectionFactoryDependencies final {
rtc::Thread* network_thread = nullptr; rtc::Thread* network_thread = nullptr;
rtc::Thread* worker_thread = nullptr; rtc::Thread* worker_thread = nullptr;
rtc::Thread* signaling_thread = nullptr; rtc::Thread* signaling_thread = nullptr;
rtc::SocketFactory* socket_factory = nullptr;
std::unique_ptr<TaskQueueFactory> task_queue_factory; std::unique_ptr<TaskQueueFactory> task_queue_factory;
std::unique_ptr<cricket::MediaEngineInterface> media_engine; std::unique_ptr<cricket::MediaEngineInterface> media_engine;
std::unique_ptr<CallFactoryInterface> call_factory; std::unique_ptr<CallFactoryInterface> call_factory;
@ -1460,6 +1486,7 @@ struct RTC_EXPORT PeerConnectionFactoryDependencies final {
std::unique_ptr<WebRtcKeyValueConfig> trials; std::unique_ptr<WebRtcKeyValueConfig> trials;
std::unique_ptr<RtpTransportControllerSendFactoryInterface> std::unique_ptr<RtpTransportControllerSendFactoryInterface>
transport_controller_send_factory; transport_controller_send_factory;
std::unique_ptr<Metronome> metronome;
}; };
// PeerConnectionFactoryInterface is the factory interface used for creating // PeerConnectionFactoryInterface is the factory interface used for creating
@ -1616,6 +1643,93 @@ RTC_EXPORT rtc::scoped_refptr<PeerConnectionFactoryInterface>
CreateModularPeerConnectionFactory( CreateModularPeerConnectionFactory(
PeerConnectionFactoryDependencies dependencies); PeerConnectionFactoryDependencies dependencies);
// https://w3c.github.io/webrtc-pc/#dom-rtcsignalingstate
inline constexpr absl::string_view PeerConnectionInterface::AsString(
SignalingState state) {
switch (state) {
case SignalingState::kStable:
return "stable";
case SignalingState::kHaveLocalOffer:
return "have-local-offer";
case SignalingState::kHaveLocalPrAnswer:
return "have-local-pranswer";
case SignalingState::kHaveRemoteOffer:
return "have-remote-offer";
case SignalingState::kHaveRemotePrAnswer:
return "have-remote-pranswer";
case SignalingState::kClosed:
return "closed";
}
// This cannot happen.
// Not using "RTC_CHECK_NOTREACHED()" because AsString() is constexpr.
return "";
}
// https://w3c.github.io/webrtc-pc/#dom-rtcicegatheringstate
inline constexpr absl::string_view PeerConnectionInterface::AsString(
IceGatheringState state) {
switch (state) {
case IceGatheringState::kIceGatheringNew:
return "new";
case IceGatheringState::kIceGatheringGathering:
return "gathering";
case IceGatheringState::kIceGatheringComplete:
return "complete";
}
// This cannot happen.
// Not using "RTC_CHECK_NOTREACHED()" because AsString() is constexpr.
return "";
}
// https://w3c.github.io/webrtc-pc/#dom-rtciceconnectionstate
inline constexpr absl::string_view PeerConnectionInterface::AsString(
PeerConnectionState state) {
switch (state) {
case PeerConnectionState::kNew:
return "new";
case PeerConnectionState::kConnecting:
return "connecting";
case PeerConnectionState::kConnected:
return "connected";
case PeerConnectionState::kDisconnected:
return "disconnected";
case PeerConnectionState::kFailed:
return "failed";
case PeerConnectionState::kClosed:
return "closed";
}
// This cannot happen.
// Not using "RTC_CHECK_NOTREACHED()" because AsString() is constexpr.
return "";
}
inline constexpr absl::string_view PeerConnectionInterface::AsString(
IceConnectionState state) {
switch (state) {
case kIceConnectionNew:
return "new";
case kIceConnectionChecking:
return "checking";
case kIceConnectionConnected:
return "connected";
case kIceConnectionCompleted:
return "completed";
case kIceConnectionFailed:
return "failed";
case kIceConnectionDisconnected:
return "disconnected";
case kIceConnectionClosed:
return "closed";
case kIceConnectionMax:
// This cannot happen.
// Not using "RTC_CHECK_NOTREACHED()" because AsString() is constexpr.
return "";
}
// This cannot happen.
// Not using "RTC_CHECK_NOTREACHED()" because AsString() is constexpr.
return "";
}
} // namespace webrtc } // namespace webrtc
#endif // API_PEER_CONNECTION_INTERFACE_H_ #endif // API_PEER_CONNECTION_INTERFACE_H_

View file

@ -12,7 +12,6 @@
#include <type_traits> #include <type_traits>
#include "rtc_base/constructor_magic.h"
#include "rtc_base/ref_counter.h" #include "rtc_base/ref_counter.h"
namespace rtc { namespace rtc {
@ -21,6 +20,9 @@ class RefCountedBase {
public: public:
RefCountedBase() = default; RefCountedBase() = default;
RefCountedBase(const RefCountedBase&) = delete;
RefCountedBase& operator=(const RefCountedBase&) = delete;
void AddRef() const { ref_count_.IncRef(); } void AddRef() const { ref_count_.IncRef(); }
RefCountReleaseStatus Release() const { RefCountReleaseStatus Release() const {
const auto status = ref_count_.DecRef(); const auto status = ref_count_.DecRef();
@ -39,8 +41,6 @@ class RefCountedBase {
private: private:
mutable webrtc::webrtc_impl::RefCounter ref_count_{0}; mutable webrtc::webrtc_impl::RefCounter ref_count_{0};
RTC_DISALLOW_COPY_AND_ASSIGN(RefCountedBase);
}; };
// Template based version of `RefCountedBase` for simple implementations that do // Template based version of `RefCountedBase` for simple implementations that do
@ -61,6 +61,9 @@ class RefCountedNonVirtual {
public: public:
RefCountedNonVirtual() = default; RefCountedNonVirtual() = default;
RefCountedNonVirtual(const RefCountedNonVirtual&) = delete;
RefCountedNonVirtual& operator=(const RefCountedNonVirtual&) = delete;
void AddRef() const { ref_count_.IncRef(); } void AddRef() const { ref_count_.IncRef(); }
RefCountReleaseStatus Release() const { RefCountReleaseStatus Release() const {
// If you run into this assert, T has virtual methods. There are two // If you run into this assert, T has virtual methods. There are two
@ -88,8 +91,6 @@ class RefCountedNonVirtual {
private: private:
mutable webrtc::webrtc_impl::RefCounter ref_count_{0}; mutable webrtc::webrtc_impl::RefCounter ref_count_{0};
RTC_DISALLOW_COPY_AND_ASSIGN(RefCountedNonVirtual);
}; };
} // namespace rtc } // namespace rtc

View file

@ -181,8 +181,8 @@ inline std::ostream& operator<<( // no-presubmit-check TODO(webrtc:8982)
#define LOG_AND_RETURN_ERROR_EX(type, message, severity) \ #define LOG_AND_RETURN_ERROR_EX(type, message, severity) \
{ \ { \
RTC_DCHECK(type != RTCErrorType::NONE); \ RTC_DCHECK(type != RTCErrorType::NONE); \
RTC_LOG(severity) << message << " (" << ToString(type) << ")"; \ RTC_LOG(severity) << message << " (" << ::webrtc::ToString(type) << ")"; \
return webrtc::RTCError(type, message); \ return ::webrtc::RTCError(type, message); \
} }
#define LOG_AND_RETURN_ERROR(type, message) \ #define LOG_AND_RETURN_ERROR(type, message) \
@ -244,7 +244,7 @@ class RTCErrorOr {
// //
// REQUIRES: !error.ok(). This requirement is DCHECKed. // REQUIRES: !error.ok(). This requirement is DCHECKed.
RTCErrorOr(RTCError&& error) : error_(std::move(error)) { // NOLINT RTCErrorOr(RTCError&& error) : error_(std::move(error)) { // NOLINT
RTC_DCHECK(!error.ok()); RTC_DCHECK(!error_.ok());
} }
// Constructs a new RTCErrorOr with the given value. After calling this // Constructs a new RTCErrorOr with the given value. After calling this

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