diff --git a/.gn b/.gn index d29e7e3ced..fbd2c38721 100644 --- a/.gn +++ b/.gn @@ -81,8 +81,7 @@ default_args = { # let's temporarily disable it. enable_jni_multiplexing = false - # TODO(b/42223878): use_fuzztest_wrapper adds a dependency to //base so - # let's temporarly disable it. + # use_fuzztest_wrapper adds a dependency to //base so we have to disable it. use_fuzztest_wrapper = false # Enable Rust in WebRTC diff --git a/DEPS b/DEPS index 2ae7d6b92a..2117a1507e 100644 --- a/DEPS +++ b/DEPS @@ -10,7 +10,7 @@ vars = { # chromium waterfalls. More info at: crbug.com/570091. 'checkout_configuration': 'default', 'checkout_instrumented_libraries': 'checkout_linux and checkout_configuration == "default"', - 'chromium_revision': '8a36d47cdc4cb85d99099ba00f864008f8a38dbe', + 'chromium_revision': '24cc1d0706d34abea623ee00e855b7f22fbc309f', # Fetch the prebuilt binaries for llvm-cov and llvm-profdata. Needed to # process the raw profiles produced by instrumented targets (built with @@ -23,20 +23,17 @@ vars = { # Fetch clang-tidy into the same bin/ directory as our clang binary. 'checkout_clang_tidy': False, - # Fetch libraries required to compile and run fuzzer tests. - 'checkout_fuzzer': False, - 'chromium_git': 'https://chromium.googlesource.com', # Keep the Chromium default of generating location tags. 'generate_location_tags': True, # ResultDB version - 'resultdb_version': 'git_revision:ebc74d10fa0d64057daa6f128e89f3672eeeec95', + 'result_adapter_revision': 'git_revision:5fb3ca203842fd691cab615453f8e5a14302a1d8', # By default, download the fuchsia sdk from the public sdk directory. 'fuchsia_sdk_cipd_prefix': 'fuchsia/sdk/core/', - 'fuchsia_version': 'version:28.20250522.3.1', + 'fuchsia_version': 'version:28.20250609.4.1', # By default, download the fuchsia images from the fuchsia GCS bucket. 'fuchsia_images_bucket': 'fuchsia', 'checkout_fuchsia': False, @@ -51,9 +48,9 @@ vars = { # RBE instance to use for running remote builds 'rbe_instance': 'projects/rbe-webrtc-developer/instances/default_instance', # reclient CIPD package version - 'reclient_version': 're_client_version:0.178.0.5ee9d3e8-gomaip', + 'reclient_version': 're_client_version:0.179.0.28341fc7-gomaip', # siso CIPD package version. - 'siso_version': 'git_revision:df8adf712c5b5605b438fdfcd44235107811e5ef', + 'siso_version': 'git_revision:7e7d85fc69f9084d2168385fb504b31e830dbfff', # ninja CIPD package. 'ninja_package': 'infra/3pp/tools/ninja/', @@ -71,32 +68,29 @@ vars = { } deps = { - # TODO(kjellander): Move this to be Android-only. - 'src/base': - 'https://chromium.googlesource.com/chromium/src/base@4ba67f727a84a10e32a417dc7e194f4fc6a23390', 'src/build': - 'https://chromium.googlesource.com/chromium/src/build@7adbc7e3263f3ab427ba7c5ac7839a69082ff7fb', + 'https://chromium.googlesource.com/chromium/src/build@6311c38ef211e0d9d11ae6b0316fd38246df5e84', 'src/buildtools': - 'https://chromium.googlesource.com/chromium/src/buildtools@1fc7350e65e9d7848c083b83aaf67611e74a5654', + 'https://chromium.googlesource.com/chromium/src/buildtools@b2eba427b82f292067b546b1075363b44b27b9c4', # Gradle 6.6.1. Used for testing Android Studio project generation for WebRTC. 'src/examples/androidtests/third_party/gradle': { 'url': 'https://chromium.googlesource.com/external/github.com/gradle/gradle.git@f2d1fb54a951d8b11d25748e4711bec8d128d7e3', 'condition': 'checkout_android', }, 'src/ios': { - 'url': 'https://chromium.googlesource.com/chromium/src/ios@28bb2043d52518c3358080a865271d72b7478e06', + 'url': 'https://chromium.googlesource.com/chromium/src/ios@0818da033e3fa948de459e52ce16cab743dbb4b5', 'condition': 'checkout_ios', }, 'src/testing': - 'https://chromium.googlesource.com/chromium/src/testing@44b0a8d794b28dbd74614e5f5e7da2b407030647', + 'https://chromium.googlesource.com/chromium/src/testing@766840625d37bc9e41a74c61ffa632691576bdf5', 'src/third_party': - 'https://chromium.googlesource.com/chromium/src/third_party@8a150db896356cd9b47f8c1a6d916347393f90f2', + 'https://chromium.googlesource.com/chromium/src/third_party@fbcbb2a67783f602bea3483091e3aad5b3ae1ebd', 'src/buildtools/linux64': { 'packages': [ { 'package': 'gn/gn/linux-${{arch}}', - 'version': 'git_revision:ebc8f16ca7b0d36a3e532ee90896f9eb48e5423b', + 'version': 'git_revision:81dab9f25cb2381400c237fdea7030d5068f9a73', } ], 'dep_type': 'cipd', @@ -106,7 +100,7 @@ deps = { 'packages': [ { 'package': 'gn/gn/mac-${{arch}}', - 'version': 'git_revision:ebc8f16ca7b0d36a3e532ee90896f9eb48e5423b', + 'version': 'git_revision:81dab9f25cb2381400c237fdea7030d5068f9a73', } ], 'dep_type': 'cipd', @@ -116,7 +110,7 @@ deps = { 'packages': [ { 'package': 'gn/gn/windows-amd64', - 'version': 'git_revision:ebc8f16ca7b0d36a3e532ee90896f9eb48e5423b', + 'version': 'git_revision:81dab9f25cb2381400c237fdea7030d5068f9a73', } ], 'dep_type': 'cipd', @@ -323,15 +317,15 @@ deps = { 'src/third_party/clang-format/script': 'https://chromium.googlesource.com/external/github.com/llvm/llvm-project/clang/tools/clang-format.git@37f6e68a107df43b7d7e044fd36a13cbae3413f2', 'src/third_party/compiler-rt/src': - 'https://chromium.googlesource.com/external/github.com/llvm/llvm-project/compiler-rt.git@57196dd146582915c955f6d388e31aea93220c51', + 'https://chromium.googlesource.com/external/github.com/llvm/llvm-project/compiler-rt.git@249b29a0e0b0f4b9dac1b099a44e3536903d6896', 'src/third_party/libc++/src': - 'https://chromium.googlesource.com/external/github.com/llvm/llvm-project/libcxx.git@a01c02c9d4acbdae3b7e8a2f3ee58579a9c29f96', + 'https://chromium.googlesource.com/external/github.com/llvm/llvm-project/libcxx.git@2c359c239b138a20a03f798e47889448ef131c22', 'src/third_party/libc++abi/src': - 'https://chromium.googlesource.com/external/github.com/llvm/llvm-project/libcxxabi.git@9810fb23f6ba666f017c2b67c67de2bcac2b44bd', + 'https://chromium.googlesource.com/external/github.com/llvm/llvm-project/libcxxabi.git@e44c3c4560f1742744ef3f9fb4217a5f26ebca1b', 'src/third_party/llvm-libc/src': - 'https://chromium.googlesource.com/external/github.com/llvm/llvm-project/libc.git@9c3ae3120fe83b998d0498dcc9ad3a56c29fad0c', + 'https://chromium.googlesource.com/external/github.com/llvm/llvm-project/libc.git@3d71fc6b43d55209a3c351031421b794f726b405', 'src/third_party/libunwind/src': - 'https://chromium.googlesource.com/external/github.com/llvm/llvm-project/libunwind.git@8575f4ae4fcf8892938bd9766cf1a5c90a0ed04e', + 'https://chromium.googlesource.com/external/github.com/llvm/llvm-project/libunwind.git@5bbf35ae6801f579c523893176789774c0726e22', 'src/third_party/test_fonts/test_fonts': { 'dep_type': 'gcs', @@ -384,7 +378,7 @@ deps = { 'packages': [ { 'package': 'infra/tools/result_adapter/${{platform}}', - 'version': Var('resultdb_version'), + 'version': Var('result_adapter_revision'), }, ], 'dep_type': 'cipd', @@ -427,7 +421,7 @@ deps = { 'packages': [ { 'package': 'chromium/third_party/android_build_tools/error_prone', - 'version': '2jzgic7at7ZxQds7qXCsmkfC4bO7d3qnWU5Q7SFUiJwC', + 'version': 'RiplT9oTSE0lQHviAF6FMk5P9863t0-WHcl2te12hi0C', }, ], 'condition': 'checkout_android', @@ -449,19 +443,7 @@ deps = { 'packages': [ { 'package': 'chromium/third_party/android_build_tools/lint', - 'version': 'Rh_qNy2kyeA9GGIdsjnPMvQa1WpHOEoUBZqV9opGGgIC', - }, - ], - 'condition': 'checkout_android and non_git_source', - 'dep_type': 'cipd', - }, - - # TODO(webrtc:42223878): This is only needed for //base. - 'src/third_party/android_build_tools/nullaway/cipd': { - 'packages': [ - { - 'package': 'chromium/third_party/android_build_tools/nullaway', - 'version': 'mFkUqdlIqmMQ3rAaTHFmOBYjNFgFUQOmMlPG6PGgmHYC', + 'version': '3bWjs4NjBtTIXoWH03nPx8c--ehZzlDkL8PUE_GaPKUC', }, ], 'condition': 'checkout_android and non_git_source', @@ -480,11 +462,11 @@ deps = { }, 'src/third_party/boringssl/src': - 'https://boringssl.googlesource.com/boringssl.git@9295969e1dad2c31d0d99481734c1c68dcbc6403', + 'https://boringssl.googlesource.com/boringssl.git@860c27038fcd9c2c27242e9874c18408dec1f84c', 'src/third_party/breakpad/breakpad': - 'https://chromium.googlesource.com/breakpad/breakpad.git@2625edb085169e92cf036c236ac79ab594a7b1cc', + 'https://chromium.googlesource.com/breakpad/breakpad.git@9d1f417714a6883f8d4e345c07802eb79edd2e90', 'src/third_party/catapult': - 'https://chromium.googlesource.com/catapult.git@5477c6dfde1132b685c73edc16e1bc71449a691d', + 'https://chromium.googlesource.com/catapult.git@5b85fe2b7c3e03e36f8206dacd7d1d58268b3a94', 'src/third_party/ced/src': { 'url': 'https://chromium.googlesource.com/external/github.com/google/compact_enc_det.git@ba412eaaacd3186085babcd901679a48863c7dd5', }, @@ -497,21 +479,21 @@ deps = { 'src/third_party/crc32c/src': 'https://chromium.googlesource.com/external/github.com/google/crc32c.git@d3d60ac6e0f16780bcfcc825385e1d338801a558', 'src/third_party/depot_tools': - 'https://chromium.googlesource.com/chromium/tools/depot_tools.git@a8900cc0f023d6a662eb66b317e8ddceeb113490', + 'https://chromium.googlesource.com/chromium/tools/depot_tools.git@377f55f382fe2b3b4734a94ac3e1b60339695ef8', 'src/third_party/ffmpeg': 'https://chromium.googlesource.com/chromium/third_party/ffmpeg.git@dcdd0fa51b65a0b1688ff6b8f0cc81908f09ded2', 'src/third_party/flatbuffers/src': 'https://chromium.googlesource.com/external/github.com/google/flatbuffers.git@8db59321d9f02cdffa30126654059c7d02f70c32', 'src/third_party/grpc/src': { - 'url': 'https://chromium.googlesource.com/external/github.com/grpc/grpc.git@cadf3c8329377e93b1f5e2d6a43d91f7a4becc28', + 'url': 'https://chromium.googlesource.com/external/github.com/grpc/grpc.git@ec70317566ae70bd8804b65360a21b75233bff99', }, # Used for embedded builds. CrOS & Linux use the system version. 'src/third_party/fontconfig/src': { - 'url': 'https://chromium.googlesource.com/external/fontconfig.git@8cf0ce700a8abe0d97ace4bf7efc7f9534b729ba', + 'url': 'https://chromium.googlesource.com/external/fontconfig.git@f71f39e7da6bccfb5a803a4adcdfe88d382a6eab', 'condition': 'checkout_linux', }, 'src/third_party/freetype/src': - 'https://chromium.googlesource.com/chromium/src/third_party/freetype2.git@e07e56c7f106b600262ab653d696b7b57f320127', + 'https://chromium.googlesource.com/chromium/src/third_party/freetype2.git@738905b34bd1f5a8ff51bd2bc8e38a2d8be9bfd6', 'src/third_party/harfbuzz-ng/src': 'https://chromium.googlesource.com/external/github.com/harfbuzz/harfbuzz.git@9f83bbbe64654b45ba5bb06927ff36c2e7588495', 'src/third_party/google_benchmark/src': { @@ -525,7 +507,7 @@ deps = { 'condition': 'checkout_android', }, 'src/third_party/googletest/src': - 'https://chromium.googlesource.com/external/github.com/google/googletest.git@09ffd0015395354774c059a17d9f5bee36177ff9', + 'https://chromium.googlesource.com/external/github.com/google/googletest.git@35b75a2cba6ef72b7ce2b6b94b05c54ca07df866', 'src/third_party/icu': { 'url': 'https://chromium.googlesource.com/chromium/deps/icu.git@b929596baebf0ab4ac7ec07f38365db4c50a559d', }, @@ -563,7 +545,7 @@ deps = { 'packages': [ { 'package': 'chromium/third_party/kotlin_stdlib', - 'version': 'GUpKElqF0PYGB-SP4D5w6p_MuMYQSBrRkGqFGjPhsIYC', + 'version': 'E405j4iATVcDLLGq9LbG61CRuyD0rs08XuMkg_GCJAwC', }, ], 'condition': 'checkout_android', @@ -574,7 +556,7 @@ deps = { 'packages': [ { 'package': 'chromium/third_party/kotlinc', - 'version': 'XmaM7JA4hB75AuMdzCegF-XYzXtoHKOA1anrWqAJL3QC', + 'version': 'mGeAAvYPiWnWdB1IzKIoMQGoAMYI3GYfT7zWdPTypJEC', }, ], 'condition': 'checkout_android', @@ -583,25 +565,25 @@ deps = { 'src/third_party/libFuzzer/src': 'https://chromium.googlesource.com/external/github.com/llvm/llvm-project/compiler-rt/lib/fuzzer.git@e31b99917861f891308269c36a32363b120126bb', 'src/third_party/fuzztest/src': - 'https://chromium.googlesource.com/external/github.com/google/fuzztest.git@f03aafb7516050ea73f617bf969f03eac641aefc', + 'https://chromium.googlesource.com/external/github.com/google/fuzztest.git@6c64b55603eab828e5acb92d40cf92c663194fb2', 'src/third_party/libjpeg_turbo': 'https://chromium.googlesource.com/chromium/deps/libjpeg_turbo.git@e14cbfaa85529d47f9f55b0f104a579c1061f9ad', 'src/third_party/libsrtp': 'https://chromium.googlesource.com/chromium/deps/libsrtp.git@a52756acb1c5e133089c798736dd171567df11f5', 'src/third_party/dav1d/libdav1d': - 'https://chromium.googlesource.com/external/github.com/videolan/dav1d.git@8d956180934f16244bdb58b39175824775125e55', + 'https://chromium.googlesource.com/external/github.com/videolan/dav1d.git@63bf075aada99afa112f84c61ddc9cead8ce04d3', 'src/third_party/libaom/source/libaom': - 'https://aomedia.googlesource.com/aom.git@2cca4aba034f99842c2e6cdc173f83801d289764', + 'https://aomedia.googlesource.com/aom.git@6c4010bde34318fd6c1f0d10196f27ac9908eeb8', 'src/third_party/libunwindstack': { 'url': 'https://chromium.googlesource.com/chromium/src/third_party/libunwindstack.git@0d758dd57f42564acecdd7a1e7ac5c8521c1b01a', 'condition': 'checkout_android', }, 'src/third_party/perfetto': - Var('chromium_git') + '/external/github.com/google/perfetto.git' + '@' + 'dd35b295cd359ba094404218414955f961a0d6ae', + Var('chromium_git') + '/external/github.com/google/perfetto.git' + '@' + '8824a8a3db2061f80f1ae662300c7d7f2c5fcad7', 'src/third_party/protobuf-javascript/src': Var('chromium_git') + '/external/github.com/protocolbuffers/protobuf-javascript' + '@' + '28bf5df73ef2f345a936d9cc95d64ba8ed426a53', 'src/third_party/libvpx/source/libvpx': - 'https://chromium.googlesource.com/webm/libvpx.git@b84ca9b63730e7d4563573a56a66317eb0087ebf', + 'https://chromium.googlesource.com/webm/libvpx.git@686bf6f1cde888898498f89ba9aefa66b683566a', 'src/third_party/libyuv': 'https://chromium.googlesource.com/libyuv/libyuv.git@61bdaee13a701d2b52c6dc943ccc5c888077a591', 'src/third_party/lss': { @@ -619,7 +601,7 @@ deps = { # Used by boringssl. 'src/third_party/nasm': { - 'url': 'https://chromium.googlesource.com/chromium/deps/nasm.git@9f916e90e6fc34ec302573f6ce147e43e33d68ca' + 'url': 'https://chromium.googlesource.com/chromium/deps/nasm.git@e2c93c34982b286b27ce8b56dd7159e0b90869a2' }, 'src/third_party/openh264/src': @@ -632,7 +614,7 @@ deps = { 'packages': [ { 'package': 'chromium/third_party/r8', - 'version': 'QhYGRVpYYKZmt3f_Zb2HoJ9LIBEnWaeeLXRNei47Z30C', + 'version': 'vyND5ed7BNCedbc49JaNOodeA7NrhM08caDYzWEh4PoC', }, ], 'condition': 'checkout_android', @@ -645,7 +627,7 @@ deps = { 'packages': [ { 'package': 'chromium/third_party/r8', - 'version': 'QhYGRVpYYKZmt3f_Zb2HoJ9LIBEnWaeeLXRNei47Z30C', + 'version': 'F0pTWc6uG70kZPngypnQxCgD3CgY5D8O-pDqj_qeoQMC', }, ], 'condition': 'checkout_android', @@ -656,7 +638,7 @@ deps = { 'condition': 'checkout_android', }, 'src/tools': - 'https://chromium.googlesource.com/chromium/src/tools@901b847deda65d44f1bba16a9f47e2ea68a805be', + 'https://chromium.googlesource.com/chromium/src/tools@0f1d03e3d2e946991644070d6a702c6d7b4a9898', 'src/third_party/espresso': { 'packages': [ @@ -695,7 +677,7 @@ deps = { 'packages': [ { 'package': 'chromium/third_party/androidx', - 'version': 'SRLnRQtsEaeNt_-cy_acdUbX63elq51jmwvif531vHgC', + 'version': 'PNhEgzpn3fLIoqcPAPoa_8pYF-b7mk1e1bmeV8r3ti0C', }, ], 'condition': 'checkout_android and non_git_source', @@ -706,7 +688,7 @@ deps = { 'packages': [ { 'package': 'chromium/third_party/android_build_tools/manifest_merger', - 'version': 'i1CvLtWlkB9QDx0DL_52AZNLpuQc2d6MbpRsCbzgEtEC', + 'version': 'AFWUMAcwcd0L1DG2-ib4ghtQYFsCvZjWuQkhuTJl4ToC', }, ], 'condition': 'checkout_android', @@ -777,7 +759,7 @@ deps = { 'packages': [ { 'package': 'chromium/third_party/turbine', - 'version': 'VGtOG2ivl1SJR7Lai5FQddIu15mWCYDnp47QtozMQeoC', + 'version': 'npJIrAZr4-2wb6qWV0r2oeWQd-Q1wiMGAAi8Up15SkQC', }, ], 'condition': 'checkout_android', @@ -793,15 +775,15 @@ deps = { 'packages': [ { 'package': 'infra/tools/luci/cas/${{platform}}', - 'version': 'git_revision:14c1dfd95e07b23eeaff304bd29a2eb80b06fe0b', + 'version': 'git_revision:0250323d999386415553b5e2297eafe827ca41f3', }, { 'package': 'infra/tools/luci/isolate/${{platform}}', - 'version': 'git_revision:14c1dfd95e07b23eeaff304bd29a2eb80b06fe0b', + 'version': 'git_revision:0250323d999386415553b5e2297eafe827ca41f3', }, { 'package': 'infra/tools/luci/swarming/${{platform}}', - 'version': 'git_revision:14c1dfd95e07b23eeaff304bd29a2eb80b06fe0b', + 'version': 'git_revision:0250323d999386415553b5e2297eafe827ca41f3', } ], 'dep_type': 'cipd', @@ -827,7 +809,7 @@ deps = { 'packages': [ { 'package': 'chromium/third_party/android_deps/autorolled', - 'version': 'p_9xkMekw1ax7bzdkzI9gjCXkONcxJb-xhJDLgyxxlUC', + 'version': 'DUJmkzdVnkEDGATSbsAPZ0prXoXODlDZn8HA9NOMD9UC', }, ], 'condition': 'checkout_android and non_git_source', diff --git a/PRESUBMIT.py b/PRESUBMIT.py index 96fa8abd9d..debc65fb24 100755 --- a/PRESUBMIT.py +++ b/PRESUBMIT.py @@ -991,6 +991,8 @@ def CommonChecks(input_api, output_api): bot_allowlist=[ 'chromium-webrtc-autoroll@webrtc-ci.iam.gserviceaccount.com', 'webrtc-version-updater@webrtc-ci.iam.gserviceaccount.com', + ('chrome-cherry-picker' + '@chops-service-accounts.iam.gserviceaccount.com'), ])) results.extend( input_api.canned_checks.CheckChangeTodoHasOwner( diff --git a/api/BUILD.gn b/api/BUILD.gn index d7d103de5b..706c48dcc6 100644 --- a/api/BUILD.gn +++ b/api/BUILD.gn @@ -216,6 +216,7 @@ rtc_source_set("ice_transport_interface") { sources = [ "ice_transport_interface.h" ] deps = [ ":async_dns_resolver", + ":local_network_access_permission", ":packet_socket_factory", ":ref_count", ":rtc_error", @@ -323,6 +324,7 @@ rtc_library("libjingle_peerconnection_api") { ":frame_transformer_interface", ":ice_transport_interface", ":libjingle_logging_api", + ":local_network_access_permission", ":make_ref_counted", ":media_stream_interface", ":network_state_predictor_api", @@ -384,9 +386,11 @@ rtc_library("libjingle_peerconnection_api") { "video_codecs:video_codecs_api", "//third_party/abseil-cpp/absl/algorithm:container", "//third_party/abseil-cpp/absl/base:core_headers", + "//third_party/abseil-cpp/absl/base:nullability", "//third_party/abseil-cpp/absl/functional:any_invocable", "//third_party/abseil-cpp/absl/memory", "//third_party/abseil-cpp/absl/strings", + "//third_party/abseil-cpp/absl/strings:str_format", "//third_party/abseil-cpp/absl/strings:string_view", # Basically, don't add stuff here. You might break sensitive downstream @@ -471,6 +475,17 @@ rtc_source_set("async_dns_resolver") { ] } +rtc_source_set("local_network_access_permission") { + visibility = [ "*" ] + sources = [ "local_network_access_permission.h" ] + deps = [ + "../rtc_base:checks", + "../rtc_base:socket_address", + "../rtc_base/system:rtc_export", + "//third_party/abseil-cpp/absl/functional:any_invocable", + ] +} + rtc_source_set("ref_count") { visibility = [ "*" ] sources = [ "ref_count.h" ] @@ -704,20 +719,6 @@ if (rtc_include_tests) { ] } - rtc_library("test_dependency_factory") { - visibility = [ "*" ] - testonly = true - sources = [ - "test/test_dependency_factory.cc", - "test/test_dependency_factory.h", - ] - deps = [ - ":video_quality_test_fixture_api", - "../rtc_base:checks", - "../rtc_base:platform_thread_types", - ] - } - rtc_library("create_video_quality_test_fixture_api") { visibility = [ "*" ] testonly = true @@ -726,9 +727,6 @@ if (rtc_include_tests) { "test/create_video_quality_test_fixture.h", ] deps = [ - ":fec_controller_api", - ":network_state_predictor_api", - ":scoped_refptr", ":video_quality_test_fixture_api", "../video:video_quality_test", ] @@ -1108,6 +1106,7 @@ if (rtc_include_tests) { testonly = true sources = [ "test/videocodec_test_fixture.h" ] deps = [ + ":field_trials", ":videocodec_test_stats_api", "../modules/video_coding:codec_globals_headers", "../modules/video_coding:video_codec_interface", @@ -1394,6 +1393,18 @@ if (rtc_include_tests) { ] } + rtc_source_set("mock_local_network_access_permission") { + visibility = [ "*" ] + testonly = true + sources = [ "test/mock_local_network_access_permission.h" ] + deps = [ + ":local_network_access_permission", + "../rtc_base:socket_address", + "../test:test_support", + "//third_party/abseil-cpp/absl/functional:any_invocable", + ] + } + rtc_source_set("mock_rtp") { visibility = [ "*" ] testonly = true @@ -1574,40 +1585,28 @@ if (rtc_include_tests) { deps = [ ":array_view", ":candidate", - ":create_time_controller", ":field_trials", - ":field_trials_view", ":function_view", ":libjingle_peerconnection_api", - ":peer_connection_quality_test_fixture_api", ":rtc_error", ":rtc_event_log_output_file", ":rtp_headers", - ":rtp_headers", ":rtp_packet_info", ":rtp_parameters", ":scoped_refptr", ":sequence_checker", - ":time_controller", "../p2p:p2p_constants", "../rtc_base:buffer", "../rtc_base:checks", - "../rtc_base:gunit_helpers", "../rtc_base:logging", "../rtc_base:macromagic", "../rtc_base:platform_thread", "../rtc_base:rtc_event", "../rtc_base:socket_address", - "../rtc_base:ssl", "../rtc_base:task_queue_for_test", "../rtc_base/containers:flat_set", "../rtc_base/synchronization:sequence_checker_internal", - "../rtc_base/task_utils:repeating_task", - "../system_wrappers", - "../system_wrappers:field_trial", - "../test:field_trial", "../test:fileutils", - "../test:rtc_expect_death", "../test:test_support", "audio_codecs/opus:unittests", "environment:environment_unittests", @@ -1621,7 +1620,6 @@ if (rtc_include_tests) { "video:rtp_video_frame_assembler_unittests", "video:video_frame", "video:video_frame_metadata_unittest", - "//testing/gtest", "//third_party/abseil-cpp/absl/functional:any_invocable", "//third_party/abseil-cpp/absl/strings", "//third_party/abseil-cpp/absl/strings:string_view", @@ -1696,12 +1694,6 @@ rtc_source_set("field_trials_view") { ] } -rtc_source_set("webrtc_key_value_config") { - visibility = [ "*" ] - sources = [ "webrtc_key_value_config.h" ] - deps = [ ":field_trials_view" ] -} - rtc_library("field_trials") { visibility = [ "*" ] sources = [ diff --git a/api/DEPS b/api/DEPS index 7f168075d9..be22215db1 100644 --- a/api/DEPS +++ b/api/DEPS @@ -77,7 +77,7 @@ specific_include_rules = { "audio_device_defines\.h": [ "+rtc_base/strings/string_builder.h", ], - + "audio_format\.h": [ "+rtc_base/strings/string_builder.h", ], @@ -107,6 +107,15 @@ specific_include_rules = { "+modules/include/module_fec_types.h", ], + "jsep\.h": [ + "+absl/strings/has_absl_stringify.h", + "+absl/strings/str_format.h", + ], + + "local_network_access_permission\.h": [ + "+rtc_base/socket_address.h", + ], + "packet_socket_factory\.h": [ "+rtc_base/async_packet_socket.h", "+rtc_base/socket_address.h", @@ -198,10 +207,6 @@ specific_include_rules = { "+rtc_base/thread_annotations.h", ], - "test_dependency_factory\.h": [ - "+rtc_base/thread_checker.h", - ], - "time_controller\.h": [ "+rtc_base/thread.h", ], diff --git a/api/array_view.h b/api/array_view.h index 577d6cb46c..8b68b9d22d 100644 --- a/api/array_view.h +++ b/api/array_view.h @@ -22,7 +22,7 @@ namespace webrtc { -// tl;dr: webrtc::ArrayView is the same thing as gsl::span from the Guideline +// tl;dr: ArrayView is the same thing as gsl::span from the Guideline // Support Library. // // Many functions read from or write to arrays. The obvious way to do this is @@ -37,7 +37,7 @@ namespace webrtc { // } // // This is flexible, since it doesn't matter how the array is stored (C array, -// std::vector, webrtc::Buffer, ...), but it's error-prone because the caller +// std::vector, Buffer, ...), but it's error-prone because the caller // has to correctly specify the array length: // // Contains17(arr, std::size(arr)); // C array @@ -48,11 +48,11 @@ namespace webrtc { // It's also kind of messy to have two separate arguments for what is // conceptually a single thing. // -// Enter webrtc::ArrayView. It contains a T pointer (to an array it doesn't +// Enter ArrayView. It contains a T pointer (to an array it doesn't // own) and a count, and supports the basic things you'd expect, such as // indexing and iteration. It allows us to write our function like this: // -// bool Contains17(webrtc::ArrayView arr) { +// bool Contains17(ArrayView arr) { // for (auto e : arr) { // if (e == 17) // return true; @@ -65,7 +65,7 @@ namespace webrtc { // // Contains17(arr); // C array // Contains17(arr); // std::vector -// Contains17(webrtc::ArrayView(arr, size)); // pointer + size +// Contains17(ArrayView(arr, size)); // pointer + size // Contains17(nullptr); // nullptr -> empty ArrayView // ... // @@ -239,8 +239,8 @@ class ArrayView final : public array_view_internal::ArrayViewBase { // ArrayView to ArrayView or ArrayView, // std::vector to ArrayView or ArrayView, // const std::vector to ArrayView, - // webrtc::Buffer to ArrayView or ArrayView, and - // const webrtc::Buffer to ArrayView. + // Buffer to ArrayView or ArrayView, and + // const Buffer to ArrayView. template < typename U, typename std::enable_if CreateAndResolve( + virtual std::unique_ptr CreateAndResolve( const SocketAddress& addr, absl::AnyInvocable callback) = 0; // Creates an AsyncDnsResolver and starts resolving the name to an address // matching the specified family. The callback will be called when resolution // is finished. The callback will be called on the sequence that the caller // runs on. - virtual std::unique_ptr CreateAndResolve( + virtual std::unique_ptr CreateAndResolve( const SocketAddress& addr, int family, absl::AnyInvocable callback) = 0; @@ -94,7 +94,7 @@ class AsyncDnsResolverFactoryInterface { // For backwards compatibility, will be deprecated and removed. // One has to do a separate Start() call on the // resolver to start name resolution. - virtual std::unique_ptr Create() = 0; + virtual std::unique_ptr Create() = 0; }; } // namespace webrtc diff --git a/api/audio/audio_device.h b/api/audio/audio_device.h index 5db7d7ecdd..fe3ef15a9a 100644 --- a/api/audio/audio_device.h +++ b/api/audio/audio_device.h @@ -21,7 +21,7 @@ namespace webrtc { class AudioDeviceModuleForTest; -class AudioDeviceModule : public webrtc::RefCountInterface { +class AudioDeviceModule : public RefCountInterface { public: enum AudioLayer { kPlatformDefaultAudio = 0, diff --git a/api/audio/audio_frame.cc b/api/audio/audio_frame.cc index 4fc224bb52..c6a89361cd 100644 --- a/api/audio/audio_frame.cc +++ b/api/audio/audio_frame.cc @@ -148,7 +148,7 @@ InterleavedView AudioFrame::data_view() const { // If you get a nullptr from `data_view()`, it's likely because the // samples_per_channel_ and/or num_channels_ members haven't been properly // set. Since `data_view()` returns an InterleavedView<> (which internally - // uses webrtc::ArrayView<>), we inherit the behavior in InterleavedView when + // uses ArrayView<>), we inherit the behavior in InterleavedView when // the view size is 0 that ArrayView<>::data() returns nullptr. So, even when // an AudioFrame is muted and we want to return `zeroed_data()`, if // samples_per_channel_ or num_channels_ is 0, the view will point to diff --git a/api/audio/audio_frame.h b/api/audio/audio_frame.h index f6f7abe22b..58f2781bae 100644 --- a/api/audio/audio_frame.h +++ b/api/audio/audio_frame.h @@ -225,7 +225,7 @@ class AudioFrame { // Absolute capture timestamp when this audio frame was originally captured. // This is only valid for audio frames captured on this machine. The absolute // capture timestamp of a received frame is found in `packet_infos_`. - // This timestamp MUST be based on the same clock as webrtc::TimeMillis(). + // This timestamp MUST be based on the same clock as TimeMillis(). std::optional absolute_capture_timestamp_ms_; }; diff --git a/api/audio/audio_processing.h b/api/audio/audio_processing.h index b7882133ff..d9d2407d39 100644 --- a/api/audio/audio_processing.h +++ b/api/audio/audio_processing.h @@ -11,18 +11,11 @@ #ifndef API_AUDIO_AUDIO_PROCESSING_H_ #define API_AUDIO_AUDIO_PROCESSING_H_ -// MSVC++ requires this to be set before any other includes to get M_PI. -#ifndef _USE_MATH_DEFINES -#define _USE_MATH_DEFINES -#endif - -#include -#include // size_t -#include // FILE -#include - #include +#include #include +#include +#include #include #include #include @@ -622,7 +615,7 @@ class RTC_EXPORT AudioProcessing : public RefCountInterface { // with this chunk of audio. virtual void set_stream_key_pressed(bool key_pressed) = 0; - // Creates and attaches an webrtc::AecDump for recording debugging + // Creates and attaches an AecDump for recording debugging // information. // The `worker_queue` may not be null and must outlive the created // AecDump instance. |max_log_size_bytes == -1| means the log size @@ -641,7 +634,7 @@ class RTC_EXPORT AudioProcessing : public RefCountInterface { worker_queue) = 0; // TODO(webrtc:5298) Deprecated variant. - // Attaches provided webrtc::AecDump for recording debugging + // Attaches provided AecDump for recording debugging // information. Log file and maximum file size logic is supposed to // be handled by implementing instance of AecDump. Calling this // method when another AecDump is attached resets the active AecDump diff --git a/api/audio/audio_view.h b/api/audio/audio_view.h index 9c4396fd8e..7b7e1bd7af 100644 --- a/api/audio/audio_view.h +++ b/api/audio/audio_view.h @@ -33,7 +33,7 @@ namespace webrtc { // buffer. Channels can be enumerated and accessing the individual channel // data is done via MonoView<>. // -// The views are comparable to and built on webrtc::ArrayView<> but add +// The views are comparable to and built on ArrayView<> but add // audio specific properties for the dimensions of the buffer and the above // specialized [de]interleaved support. // diff --git a/api/audio/echo_detector_creator.h b/api/audio/echo_detector_creator.h index 8f260ae0da..a901d5c13e 100644 --- a/api/audio/echo_detector_creator.h +++ b/api/audio/echo_detector_creator.h @@ -17,7 +17,7 @@ namespace webrtc { // Returns an instance of the WebRTC implementation of a residual echo detector. -// It can be provided to the webrtc::BuiltinAudioProcessingBuilder to obtain the +// It can be provided to the BuiltinAudioProcessingBuilder to obtain the // usual residual echo metrics. scoped_refptr CreateEchoDetector(); diff --git a/api/audio/test/BUILD.gn b/api/audio/test/BUILD.gn index 73762fc54a..b1060faae3 100644 --- a/api/audio/test/BUILD.gn +++ b/api/audio/test/BUILD.gn @@ -26,7 +26,6 @@ if (rtc_include_tests) { "../..:array_view", "../../../modules/audio_processing:aec3_config_json", "../../../rtc_base:checks", - "../../../rtc_base:macromagic", "../../../test:test_support", ] } diff --git a/api/audio/test/audio_view_unittest.cc b/api/audio/test/audio_view_unittest.cc index 55e9d87f63..e28c73ca11 100644 --- a/api/audio/test/audio_view_unittest.cc +++ b/api/audio/test/audio_view_unittest.cc @@ -16,7 +16,6 @@ #include #include "api/array_view.h" -#include "rtc_base/arraysize.h" #include "test/gtest.h" namespace webrtc { @@ -210,7 +209,7 @@ TEST(AudioViewTest, DeinterleavedViewPointerArray) { // Test that the same thing works with T* const *. float* channel_array[] = {&v1[0], &v2[0], &v3[0], &v4[0]}; di = DeinterleavedView(channel_array, v1.size(), - arraysize(channel_array)); + std::size(channel_array)); EXPECT_EQ(NumChannels(di), channels.size()); EXPECT_EQ(SamplesPerChannel(di), v1.size()); EXPECT_EQ(di[0].data(), v1.data()); diff --git a/api/audio_codecs/audio_format.h b/api/audio_codecs/audio_format.h index a5d4a92065..f7daf76aea 100644 --- a/api/audio_codecs/audio_format.h +++ b/api/audio_codecs/audio_format.h @@ -26,7 +26,7 @@ namespace webrtc { // SDP specification for a single audio codec. struct RTC_EXPORT SdpAudioFormat { - using Parameters [[deprecated("Use webrtc::CodecParameterMap")]] = + using Parameters [[deprecated("Use CodecParameterMap")]] = std::map; SdpAudioFormat(const SdpAudioFormat&); diff --git a/api/audio_codecs/opus/BUILD.gn b/api/audio_codecs/opus/BUILD.gn index c24e3d779b..ad59ce700e 100644 --- a/api/audio_codecs/opus/BUILD.gn +++ b/api/audio_codecs/opus/BUILD.gn @@ -110,9 +110,10 @@ rtc_library("unittests") { deps = [ ":audio_decoder_opus", "..:audio_codecs_api", - "../../../api/environment", - "../../../api/environment:environment_factory", - "../../../test:explicit_key_value_config", + "../..:field_trials", + "../../../test:create_test_field_trials", "../../../test:test_support", + "../../environment", + "../../environment:environment_factory", ] } diff --git a/api/audio_codecs/opus/audio_decoder_opus_unittest.cc b/api/audio_codecs/opus/audio_decoder_opus_unittest.cc index fdcb28c4b5..f8fe4fafa7 100644 --- a/api/audio_codecs/opus/audio_decoder_opus_unittest.cc +++ b/api/audio_codecs/opus/audio_decoder_opus_unittest.cc @@ -17,14 +17,14 @@ #include "api/audio_codecs/audio_format.h" #include "api/environment/environment.h" #include "api/environment/environment_factory.h" -#include "test/explicit_key_value_config.h" +#include "api/field_trials.h" +#include "test/create_test_field_trials.h" #include "test/gmock.h" #include "test/gtest.h" namespace webrtc { namespace { -using test::ExplicitKeyValueConfig; using ::testing::Field; using ::testing::Optional; using Config = AudioDecoderOpus::Config; @@ -89,8 +89,8 @@ TEST(AudioDecoderOpusTest, MakeAudioDecoderCannotForceDefaultNumChannels) { TEST(AudioDecoderOpusTest, MakeAudioDecoderForcesStereo) { const Environment env = - CreateEnvironment(std::make_unique( - "WebRTC-Audio-OpusDecodeStereoByDefault/Enabled/")); + CreateEnvironment(std::make_unique(CreateTestFieldTrials( + "WebRTC-Audio-OpusDecodeStereoByDefault/Enabled/"))); auto decoder = AudioDecoderOpus::MakeAudioDecoder( env, /*config=*/{.num_channels = std::nullopt}); @@ -100,8 +100,8 @@ TEST(AudioDecoderOpusTest, MakeAudioDecoderForcesStereo) { TEST(AudioDecoderOpusTest, MakeAudioDecoderCannotForceStereo) { const Environment env = - CreateEnvironment(std::make_unique( - "WebRTC-Audio-OpusDecodeStereoByDefault/Enabled/")); + CreateEnvironment(std::make_unique(CreateTestFieldTrials( + "WebRTC-Audio-OpusDecodeStereoByDefault/Enabled/"))); auto decoder = AudioDecoderOpus::MakeAudioDecoder(env, /*config=*/{.num_channels = 1}); diff --git a/api/call/bitrate_allocation.h b/api/call/bitrate_allocation.h index 4b4e5e7ae1..7373d6cc28 100644 --- a/api/call/bitrate_allocation.h +++ b/api/call/bitrate_allocation.h @@ -23,11 +23,6 @@ struct BitrateAllocationUpdate { // data. (Note that this may include packet overhead depending on // configuration.) DataRate target_bitrate = DataRate::Zero(); - // The allocated part of the estimated link capacity. This is more stable than - // the target as it is based on the underlying link capacity estimate. This - // should be used to change encoder configuration when the cost of change is - // high. - DataRate stable_target_bitrate = DataRate::Zero(); // Predicted packet loss ratio. double packet_loss_ratio = 0; // Predicted round trip time. diff --git a/api/candidate.h b/api/candidate.h index b02d0ac3a3..69e66ef526 100644 --- a/api/candidate.h +++ b/api/candidate.h @@ -105,7 +105,7 @@ class RTC_EXPORT Candidate { absl::string_view type_name() const; // Setting the type requires a constant string (e.g. - // webrtc::LOCAL_PORT_TYPE). The type should really be an enum rather than a + // LOCAL_PORT_TYPE). The type should really be an enum rather than a // string, but until we make that change the lifetime attribute helps us lock // things down. See also the `Port` class. void set_type(IceCandidateType type) { type_ = type; } @@ -159,10 +159,10 @@ class RTC_EXPORT Candidate { // `network_cost` measures the cost/penalty of using this candidate. A network // cost of 0 indicates this candidate can be used freely. A value of - // webrtc::kNetworkCostMax indicates it should be used only as the last + // kNetworkCostMax indicates it should be used only as the last // resort. void set_network_cost(uint16_t network_cost) { - RTC_DCHECK_LE(network_cost, webrtc::kNetworkCostMax); + RTC_DCHECK_LE(network_cost, kNetworkCostMax); network_cost_ = network_cost; } uint16_t network_cost() const { return network_cost_; } diff --git a/api/create_peerconnection_factory.cc b/api/create_peerconnection_factory.cc index aec4f12549..12434eef58 100644 --- a/api/create_peerconnection_factory.cc +++ b/api/create_peerconnection_factory.cc @@ -52,7 +52,7 @@ scoped_refptr CreatePeerConnectionFactory( dependencies.env = CreateEnvironment(std::move(field_trials)); if (network_thread) { - // TODO(bugs.webrtc.org/13145): Add an webrtc::SocketFactory* argument. + // TODO(bugs.webrtc.org/13145): Add an SocketFactory* argument. dependencies.socket_factory = network_thread->socketserver(); } dependencies.adm = std::move(default_adm); diff --git a/api/crypto/crypto_options.h b/api/crypto/crypto_options.h index 8adfe4eb36..5504f6f900 100644 --- a/api/crypto/crypto_options.h +++ b/api/crypto/crypto_options.h @@ -72,7 +72,7 @@ struct RTC_EXPORT CryptoOptions { // Cipher groups used by DTLS when establishing an ephemeral key during // handshake. - class EphemeralKeyExchangeCipherGroups { + class RTC_EXPORT EphemeralKeyExchangeCipherGroups { public: // Which cipher groups are supported by this binary, // - ssl.h: SSL_GROUP_{} diff --git a/api/crypto/frame_decryptor_interface.h b/api/crypto/frame_decryptor_interface.h index 7ed165fc84..659f16654c 100644 --- a/api/crypto/frame_decryptor_interface.h +++ b/api/crypto/frame_decryptor_interface.h @@ -60,7 +60,7 @@ class FrameDecryptorInterface : public RefCountInterface { // kRecoverable should be returned if the failure was due to something other // than a decryption failure. kFailedToDecrypt should be returned in all other // cases. - virtual Result Decrypt(webrtc::MediaType media_type, + virtual Result Decrypt(MediaType media_type, const std::vector& csrcs, ArrayView additional_data, ArrayView encrypted_frame, @@ -69,7 +69,7 @@ class FrameDecryptorInterface : public RefCountInterface { // Returns the total required length in bytes for the output of the // decryption. This can be larger than the actual number of bytes you need but // must never be smaller as it informs the size of the frame buffer. - virtual size_t GetMaxPlaintextByteSize(webrtc::MediaType media_type, + virtual size_t GetMaxPlaintextByteSize(MediaType media_type, size_t encrypted_frame_size) = 0; }; diff --git a/api/crypto/frame_encryptor_interface.h b/api/crypto/frame_encryptor_interface.h index 9a2b1709d8..6a1797249d 100644 --- a/api/crypto/frame_encryptor_interface.h +++ b/api/crypto/frame_encryptor_interface.h @@ -38,7 +38,7 @@ class FrameEncryptorInterface : public RefCountInterface { // must set bytes_written to the number of bytes you wrote in the // encrypted_frame. 0 must be returned if successful all other numbers can be // selected by the implementer to represent error codes. - virtual int Encrypt(webrtc::MediaType media_type, + virtual int Encrypt(MediaType media_type, uint32_t ssrc, ArrayView additional_data, ArrayView frame, @@ -48,7 +48,7 @@ class FrameEncryptorInterface : public RefCountInterface { // Returns the total required length in bytes for the output of the // encryption. This can be larger than the actual number of bytes you need but // must never be smaller as it informs the size of the encrypted_frame buffer. - virtual size_t GetMaxCiphertextByteSize(webrtc::MediaType media_type, + virtual size_t GetMaxCiphertextByteSize(MediaType media_type, size_t frame_size) = 0; }; diff --git a/api/dtls_transport_interface.h b/api/dtls_transport_interface.h index c444313a5d..79099f43a2 100644 --- a/api/dtls_transport_interface.h +++ b/api/dtls_transport_interface.h @@ -110,7 +110,7 @@ class DtlsTransportObserverInterface { // accessed on that thread, except for functions explicitly marked otherwise. // References can be held by other threads, and destruction can therefore // be initiated by other threads. -class DtlsTransportInterface : public webrtc::RefCountInterface { +class DtlsTransportInterface : public RefCountInterface { public: // Returns a pointer to the ICE transport that is owned by the DTLS transport. virtual scoped_refptr ice_transport() = 0; diff --git a/api/dtmf_sender_interface.h b/api/dtmf_sender_interface.h index 16ce665e53..3b184832c0 100644 --- a/api/dtmf_sender_interface.h +++ b/api/dtmf_sender_interface.h @@ -41,7 +41,7 @@ class DtmfSenderObserverInterface { // The interface of native implementation of the RTCDTMFSender defined by the // WebRTC W3C Editor's Draft. // See: https://www.w3.org/TR/webrtc/#peer-to-peer-dtmf -class DtmfSenderInterface : public webrtc::RefCountInterface { +class DtmfSenderInterface : public RefCountInterface { public: // Provides the spec compliant default 2 second delay for the ',' character. static const int kDtmfDefaultCommaDelayMs = 2000; diff --git a/api/environment/environment_factory.cc b/api/environment/environment_factory.cc index 692ecc09c2..8ee52c3d8d 100644 --- a/api/environment/environment_factory.cc +++ b/api/environment/environment_factory.cc @@ -31,7 +31,7 @@ namespace { template void Store(absl_nonnull std::unique_ptr value, - scoped_refptr& leaf) { + scoped_refptr& leaf) { class StorageNode : public RefCountedBase { public: StorageNode(scoped_refptr parent, diff --git a/api/field_trials_unittest.cc b/api/field_trials_unittest.cc index d3521b49ca..e27ab4e628 100644 --- a/api/field_trials_unittest.cc +++ b/api/field_trials_unittest.cc @@ -12,16 +12,12 @@ #include "absl/strings/str_cat.h" #include "rtc_base/containers/flat_set.h" -#include "system_wrappers/include/field_trial.h" -#include "test/field_trial.h" #include "test/gmock.h" #include "test/gtest.h" namespace webrtc { namespace { -using field_trial::FieldTrialsAllowedInScopeForTesting; -using test::ScopedFieldTrials; using ::testing::AllOf; using ::testing::HasSubstr; using ::testing::IsNull; @@ -29,7 +25,6 @@ using ::testing::Not; using ::testing::NotNull; TEST(FieldTrialsTest, EmptyStringHasNoEffect) { - FieldTrialsAllowedInScopeForTesting k({"MyCoolTrial"}); FieldTrials f(""); f.RegisterKeysForTesting({"MyCoolTrial"}); @@ -49,25 +44,6 @@ TEST(FieldTrialsTest, EnabledDisabledMustBeFirstInValue) { EXPECT_FALSE(f.IsEnabled("AnotherTrial")); } -TEST(FieldTrialsTest, FieldTrialsDoesNotReadGlobalString) { - FieldTrialsAllowedInScopeForTesting k({"MyCoolTrial", "MyUncoolTrial"}); - ScopedFieldTrials g("MyCoolTrial/Enabled/MyUncoolTrial/Disabled/"); - FieldTrials f(""); - f.RegisterKeysForTesting({"MyCoolTrial", "MyUncoolTrial"}); - - EXPECT_FALSE(f.IsEnabled("MyCoolTrial")); - EXPECT_FALSE(f.IsDisabled("MyUncoolTrial")); -} - -TEST(FieldTrialsTest, FieldTrialsInstanceDoesNotModifyGlobalString) { - FieldTrialsAllowedInScopeForTesting k({"SomeString"}); - FieldTrials f("SomeString/Enabled/"); - f.RegisterKeysForTesting({"SomeString"}); - - EXPECT_TRUE(f.IsEnabled("SomeString")); - EXPECT_FALSE(field_trial::IsEnabled("SomeString")); -} - TEST(FieldTrialsTest, FieldTrialsSupportSimultaneousInstances) { FieldTrials f1("SomeString/Enabled/"); FieldTrials f2("SomeOtherString/Enabled/"); @@ -81,20 +57,6 @@ TEST(FieldTrialsTest, FieldTrialsSupportSimultaneousInstances) { EXPECT_TRUE(f2.IsEnabled("SomeOtherString")); } -TEST(FieldTrialsTest, GlobalAndNonGlobalFieldTrialsAreDisjoint) { - FieldTrialsAllowedInScopeForTesting k({"SomeString", "SomeOtherString"}); - ScopedFieldTrials g("SomeString/Enabled/"); - FieldTrials f("SomeOtherString/Enabled/"); - - f.RegisterKeysForTesting({"SomeString", "SomeOtherString"}); - - EXPECT_TRUE(field_trial::IsEnabled("SomeString")); - EXPECT_FALSE(field_trial::IsEnabled("SomeOtherString")); - - EXPECT_FALSE(f.IsEnabled("SomeString")); - EXPECT_TRUE(f.IsEnabled("SomeOtherString")); -} - TEST(FieldTrialsTest, CreateAcceptsValidInputs) { EXPECT_THAT(FieldTrials::Create(""), NotNull()); EXPECT_THAT(FieldTrials::Create("Audio/Enabled/"), NotNull()); diff --git a/api/ice_transport_factory.cc b/api/ice_transport_factory.cc index 3cd2deb1a7..8ac27fab88 100644 --- a/api/ice_transport_factory.cc +++ b/api/ice_transport_factory.cc @@ -62,7 +62,7 @@ scoped_refptr CreateIceTransport( scoped_refptr CreateIceTransport(IceTransportInit init) { return make_ref_counted( - P2PTransportChannel::Create("", ICE_CANDIDATE_COMPONENT_RTP, + P2PTransportChannel::Create("standalone", ICE_CANDIDATE_COMPONENT_RTP, std::move(init))); } diff --git a/api/ice_transport_factory.h b/api/ice_transport_factory.h index cdd9db1a2f..56ac4b3c38 100644 --- a/api/ice_transport_factory.h +++ b/api/ice_transport_factory.h @@ -19,7 +19,7 @@ namespace webrtc { // Static factory for an IceTransport object that can be created -// without using a webrtc::PeerConnection. +// without using a PeerConnection. // The returned object must be accessed and destroyed on the thread that // created it. // The PortAllocator must outlive the created IceTransportInterface object. @@ -29,7 +29,7 @@ RTC_EXPORT scoped_refptr CreateIceTransport( PortAllocator* port_allocator); // Static factory for an IceTransport object that can be created -// without using a webrtc::PeerConnection. +// without using a PeerConnection. // The returned object must be accessed and destroyed on the thread that // created it. // `init.port_allocator()` is required and must outlive the created diff --git a/api/ice_transport_interface.h b/api/ice_transport_interface.h index d859ed6aa8..9f1889419c 100644 --- a/api/ice_transport_interface.h +++ b/api/ice_transport_interface.h @@ -14,6 +14,7 @@ #include #include "api/async_dns_resolver.h" +#include "api/local_network_access_permission.h" #include "api/ref_count.h" #include "api/rtc_event_log/rtc_event_log.h" #include "api/scoped_refptr.h" @@ -35,7 +36,7 @@ class IceTransportInterface : public RefCountInterface { // The returned object can only be safely used on the signalling thread. // TODO(crbug.com/907849): Add API calls for the functions that have to // be exposed to clients, and stop allowing access to the - // webrtc::IceTransportInternal API. + // IceTransportInternal API. virtual IceTransportInternal* internal() = 0; }; @@ -60,6 +61,15 @@ struct IceTransportInit final { async_dns_resolver_factory_ = async_dns_resolver_factory; } + LocalNetworkAccessPermissionFactoryInterface* lna_permission_factory() { + return lna_permission_factory_; + } + + void set_lna_permission_factory( + LocalNetworkAccessPermissionFactoryInterface* lna_permission_factory) { + lna_permission_factory_ = lna_permission_factory; + } + RtcEventLog* event_log() { return event_log_; } void set_event_log(RtcEventLog* event_log) { event_log_ = event_log; } @@ -98,6 +108,8 @@ struct IceTransportInit final { private: PortAllocator* port_allocator_ = nullptr; AsyncDnsResolverFactoryInterface* async_dns_resolver_factory_ = nullptr; + LocalNetworkAccessPermissionFactoryInterface* lna_permission_factory_ = + nullptr; RtcEventLog* event_log_ = nullptr; IceControllerFactoryInterface* ice_controller_factory_ = nullptr; ActiveIceControllerFactoryInterface* active_ice_controller_factory_ = nullptr; diff --git a/api/jsep.cc b/api/jsep.cc index 65e22442f8..cf7c97bade 100644 --- a/api/jsep.cc +++ b/api/jsep.cc @@ -19,10 +19,6 @@ namespace webrtc { -std::string IceCandidateInterface::server_url() const { - return ""; -} - size_t SessionDescriptionInterface::RemoveCandidates( const std::vector& /* candidates */) { return 0; diff --git a/api/jsep.h b/api/jsep.h index c5674e90cd..5808e990a6 100644 --- a/api/jsep.h +++ b/api/jsep.h @@ -25,8 +25,12 @@ #include #include #include +#include #include +#include "absl/base/nullability.h" +#include "absl/strings/str_format.h" +#include "absl/strings/string_view.h" #include "api/candidate.h" #include "api/ref_count.h" #include "api/rtc_error.h" @@ -45,55 +49,137 @@ struct SdpParseError { }; // Class representation of an ICE candidate. -// -// An instance of this interface is supposed to be owned by one class at -// a time and is therefore not expected to be thread safe. -// -// An instance can be created by CreateIceCandidate. -class RTC_EXPORT IceCandidateInterface { +class RTC_EXPORT IceCandidate final { public: - virtual ~IceCandidateInterface() {} + IceCandidate(absl::string_view sdp_mid, + int sdp_mline_index, + const Candidate& candidate); + ~IceCandidate() = default; + + IceCandidate(const IceCandidate&) = delete; + IceCandidate& operator=(const IceCandidate&) = delete; + + // Parses an sdp candidate string (only the first line) to construct an + // IceCandidate instance. If an error occurs, details about the error can + // optionally be returned via the `error` paramter, and the function returns + // nullptr. + static std::unique_ptr Create( + absl::string_view mid, + int sdp_mline_index, + absl::string_view sdp, + SdpParseError* absl_nullable error = nullptr); + // If present, this is the value of the "a=mid" attribute of the candidate's // m= section in SDP, which identifies the m= section. - virtual std::string sdp_mid() const = 0; + // TODO: webrtc:406795492 - string_view. + std::string sdp_mid() const { return sdp_mid_; } + // This indicates the index (starting at zero) of m= section this candidate // is associated with. Needed when an endpoint doesn't support MIDs. - virtual int sdp_mline_index() const = 0; + int sdp_mline_index() const { return sdp_mline_index_; } + // Only for use internally. - virtual const Candidate& candidate() const = 0; + const Candidate& candidate() const { return candidate_; } + // The URL of the ICE server which this candidate was gathered from. - // TODO(zhihuang): Remove the default implementation once the subclasses - // implement this method. - virtual std::string server_url() const; + // TODO: webrtc:406795492 - string_view. + std::string server_url() const { return candidate_.url(); } + // Creates a SDP-ized form of this candidate. - virtual bool ToString(std::string* out) const = 0; + std::string ToString() const; + + // TODO: webrtc:406795492 - Deprecate and remove this method. + // [[deprecated("Use ToString()")]] + bool ToString(std::string* out) const { + if (!out) + return false; + *out = ToString(); + return !out->empty(); + } + + template + friend void AbslStringify(Sink& sink, const IceCandidate& c) { + absl::Format(&sink, "IceCandidate: {'%s', %i, '%s'}", c.sdp_mid_.c_str(), + c.sdp_mline_index_, c.ToString().c_str()); + } + + private: + const std::string sdp_mid_; + const int sdp_mline_index_; + const Candidate candidate_; }; -// Creates a IceCandidateInterface based on SDP string. +// TODO: webrtc:406795492 - Deprecate and eventually remove these types when no +// longer referenced. They're provided here for backwards compatiblity. +using JsepIceCandidate = IceCandidate; +using IceCandidateInterface = IceCandidate; + +// Creates an IceCandidate based on SDP string. // Returns null if the sdp string can't be parsed. // `error` may be null. -RTC_EXPORT IceCandidateInterface* CreateIceCandidate(const std::string& sdp_mid, - int sdp_mline_index, - const std::string& sdp, - SdpParseError* error); +RTC_EXPORT IceCandidate* CreateIceCandidate(const std::string& sdp_mid, + int sdp_mline_index, + const std::string& sdp, + SdpParseError* error); -// Creates an IceCandidateInterface based on a parsed candidate structure. -RTC_EXPORT std::unique_ptr CreateIceCandidate( +// Creates an IceCandidate based on a parsed candidate structure. +RTC_EXPORT std::unique_ptr CreateIceCandidate( const std::string& sdp_mid, int sdp_mline_index, const Candidate& candidate); // This class represents a collection of candidates for a specific m= section. // Used in SessionDescriptionInterface. -class IceCandidateCollection { +class IceCandidateCollection final { public: - virtual ~IceCandidateCollection() {} - virtual size_t count() const = 0; + IceCandidateCollection() = default; + explicit IceCandidateCollection( + std::vector>&& candidates) + : candidates_(std::move(candidates)) {} + ~IceCandidateCollection() = default; + + // Move constructor is defined so that a vector of IceCandidateCollections + // can be resized. + IceCandidateCollection(IceCandidateCollection&& o) = default; + + IceCandidateCollection(const IceCandidateCollection&) = delete; + IceCandidateCollection& operator=(const IceCandidateCollection&) = delete; + + size_t count() const { return candidates_.size(); } + bool empty() const { return candidates_.empty(); } + const IceCandidate* at(size_t index) const; + + // Adds and takes ownership of the IceCandidate. + void add(std::unique_ptr candidate); + [[deprecated("Use unique_ptr version")]] + void add(IceCandidate* candidate); + + // Removes the candidate that has a matching address and protocol. + // + // Returns the number of candidates that were removed. + size_t remove(const Candidate& candidate); + + // Removes the candidate that has a matching address and protocol. + // + // Returns the number of candidates that were removed. + size_t remove(const IceCandidate* candidate); + + const std::vector>& candidates() const { + return candidates_; + } + // Returns true if an equivalent `candidate` exist in the collection. - virtual bool HasCandidate(const IceCandidateInterface* candidate) const = 0; - virtual const IceCandidateInterface* at(size_t index) const = 0; + bool HasCandidate(const IceCandidate* candidate) const; + + IceCandidateCollection Clone() const; + + private: + std::vector> candidates_; }; +// TODO: webrtc:406795492 - Deprecate. +using JsepCandidateCollection = IceCandidateCollection; + // Enum that describes the type of the SessionDescriptionInterface. // Corresponds to RTCSdpType in the WebRTC specification. // https://w3c.github.io/webrtc-pc/#dom-rtcsdptype @@ -167,11 +253,21 @@ class RTC_EXPORT SessionDescriptionInterface { // Returns false if the session description does not have a media section // that corresponds to `candidate.sdp_mid()` or // `candidate.sdp_mline_index()`. - virtual bool AddCandidate(const IceCandidateInterface* candidate) = 0; + virtual bool AddCandidate(const IceCandidate* candidate) = 0; + + // Removes the first matching candidate (at most 1) from the description + // that meets the `Candidate::MatchesForRemoval()` requirement and matches + // either the `IceCandidate::sdp_mid()` property or + // `IceCandidate::sdp_mline_index()`. + // + // Returns false if no matching candidate was found (and removed). + virtual bool RemoveCandidate(const IceCandidate* candidate) = 0; // Removes the candidates from the description, if found. // // Returns the number of candidates removed. + // TODO: webrtc:42233526 - Deprecate and eventually remove this method in + // favor of the IceCandidate version. virtual size_t RemoveCandidates(const std::vector& candidates); // Returns the number of m= sections in the session description. @@ -231,8 +327,7 @@ std::unique_ptr CreateSessionDescription( std::unique_ptr description); // CreateOffer and CreateAnswer callback interface. -class RTC_EXPORT CreateSessionDescriptionObserver - : public webrtc::RefCountInterface { +class RTC_EXPORT CreateSessionDescriptionObserver : public RefCountInterface { public: // This callback transfers the ownership of the `desc`. // TODO(deadbeef): Make this take an std::unique_ptr<> to avoid confusion @@ -251,8 +346,7 @@ class RTC_EXPORT CreateSessionDescriptionObserver }; // SetLocalDescription and SetRemoteDescription callback interface. -class RTC_EXPORT SetSessionDescriptionObserver - : public webrtc::RefCountInterface { +class RTC_EXPORT SetSessionDescriptionObserver : public RefCountInterface { public: virtual void OnSuccess() = 0; // See description in CreateSessionDescriptionObserver for OnFailure. diff --git a/api/jsep_ice_candidate.cc b/api/jsep_ice_candidate.cc index 9642dbe86b..0e7db64c8c 100644 --- a/api/jsep_ice_candidate.cc +++ b/api/jsep_ice_candidate.cc @@ -11,63 +11,71 @@ #include "api/jsep_ice_candidate.h" #include +#include +#include #include #include #include #include "absl/algorithm/container.h" #include "absl/memory/memory.h" +#include "absl/strings/string_view.h" #include "api/candidate.h" #include "api/jsep.h" +#include "rtc_base/checks.h" namespace webrtc { - -std::string JsepIceCandidate::sdp_mid() const { - return sdp_mid_; -} - -int JsepIceCandidate::sdp_mline_index() const { - return sdp_mline_index_; -} - -const Candidate& JsepIceCandidate::candidate() const { - return candidate_; -} - -std::string JsepIceCandidate::server_url() const { - return candidate_.url(); +namespace { +// The sdpMLineIndex property is an unsigned short, a zero based index of the +// m-line associated with the candidate. This function ensures we consistently +// set the property to -1 for out-of-bounds values, to make candidate +// comparisons more robust. +int EnsureValidMLineIndex(int sdp_mline_index) { + if (sdp_mline_index < 0 || + sdp_mline_index > std::numeric_limits::max()) + return -1; + return sdp_mline_index; } +} // namespace -JsepCandidateCollection::JsepCandidateCollection() = default; +IceCandidate::IceCandidate(absl::string_view sdp_mid, + int sdp_mline_index, + const Candidate& candidate) + : sdp_mid_(sdp_mid), + sdp_mline_index_(EnsureValidMLineIndex(sdp_mline_index)), + candidate_(candidate) {} -JsepCandidateCollection::JsepCandidateCollection(JsepCandidateCollection&& o) - : candidates_(std::move(o.candidates_)) {} - -size_t JsepCandidateCollection::count() const { - return candidates_.size(); +void IceCandidateCollection::add(std::unique_ptr candidate) { + candidates_.push_back(std::move(candidate)); } -void JsepCandidateCollection::add(JsepIceCandidate* candidate) { +void IceCandidateCollection::add(IceCandidate* candidate) { candidates_.push_back(absl::WrapUnique(candidate)); } -const IceCandidateInterface* JsepCandidateCollection::at(size_t index) const { +const IceCandidate* IceCandidateCollection::at(size_t index) const { return candidates_[index].get(); } -bool JsepCandidateCollection::HasCandidate( - const IceCandidateInterface* candidate) const { +bool IceCandidateCollection::HasCandidate(const IceCandidate* candidate) const { + const auto sdp_mid = candidate->sdp_mid(); // avoid string copy per entry. return absl::c_any_of( - candidates_, [&](const std::unique_ptr& entry) { - return entry->sdp_mid() == candidate->sdp_mid() && - entry->sdp_mline_index() == candidate->sdp_mline_index() && - entry->candidate().IsEquivalent(candidate->candidate()); + candidates_, [&](const std::unique_ptr& entry) { + if (!entry->candidate().IsEquivalent(candidate->candidate())) { + return false; + } + if (!sdp_mid.empty()) { + // In this case, we ignore the `sdp_mline_index()` property. + return sdp_mid == entry->sdp_mid(); + } + RTC_DCHECK_NE(candidate->sdp_mline_index(), -1); + return candidate->sdp_mline_index() == entry->sdp_mline_index(); }); } size_t JsepCandidateCollection::remove(const Candidate& candidate) { - auto iter = absl::c_find_if( - candidates_, [&](const std::unique_ptr& c) { + auto iter = + absl::c_find_if(candidates_, [&](const std::unique_ptr& c) { return candidate.MatchesForRemoval(c->candidate()); }); if (iter != candidates_.end()) { @@ -77,4 +85,17 @@ size_t JsepCandidateCollection::remove(const Candidate& candidate) { return 0; } +size_t JsepCandidateCollection::remove(const IceCandidate* candidate) { + RTC_DCHECK(candidate); + auto iter = + absl::c_find_if(candidates_, [&](const std::unique_ptr& c) { + return c->candidate().MatchesForRemoval(candidate->candidate()); + }); + if (iter != candidates_.end()) { + candidates_.erase(iter); + return 1u; + } + return 0u; +} + } // namespace webrtc diff --git a/api/jsep_ice_candidate.h b/api/jsep_ice_candidate.h index 63880818ec..f0a41bef91 100644 --- a/api/jsep_ice_candidate.h +++ b/api/jsep_ice_candidate.h @@ -8,81 +8,10 @@ * be found in the AUTHORS file in the root of the source tree. */ -// TODO(deadbeef): Move this out of api/; it's an implementation detail and -// shouldn't be used externally. - #ifndef API_JSEP_ICE_CANDIDATE_H_ #define API_JSEP_ICE_CANDIDATE_H_ -#include - -#include -#include -#include - -#include "api/candidate.h" +// TODO: webrtc:406795492 - Delete file once no longer #included. #include "api/jsep.h" -#include "rtc_base/system/rtc_export.h" - -namespace webrtc { - -// Implementation of IceCandidateInterface. -class RTC_EXPORT JsepIceCandidate : public IceCandidateInterface { - public: - JsepIceCandidate(const std::string& sdp_mid, int sdp_mline_index); - JsepIceCandidate(const std::string& sdp_mid, - int sdp_mline_index, - const Candidate& candidate); - JsepIceCandidate(const JsepIceCandidate&) = delete; - JsepIceCandidate& operator=(const JsepIceCandidate&) = delete; - ~JsepIceCandidate() override; - // `err` may be null. - bool Initialize(const std::string& sdp, SdpParseError* err); - void SetCandidate(const Candidate& candidate) { candidate_ = candidate; } - - std::string sdp_mid() const override; - int sdp_mline_index() const override; - const Candidate& candidate() const override; - - std::string server_url() const override; - - bool ToString(std::string* out) const override; - - private: - std::string sdp_mid_; - int sdp_mline_index_; - Candidate candidate_; -}; - -// Implementation of IceCandidateCollection which stores JsepIceCandidates. -class JsepCandidateCollection : public IceCandidateCollection { - public: - JsepCandidateCollection(); - // Move constructor is defined so that a vector of JsepCandidateCollections - // can be resized. - JsepCandidateCollection(JsepCandidateCollection&& o); - - JsepCandidateCollection(const JsepCandidateCollection&) = delete; - JsepCandidateCollection& operator=(const JsepCandidateCollection&) = delete; - - // Returns a copy of the candidate collection. - JsepCandidateCollection Clone() const; - size_t count() const override; - bool HasCandidate(const IceCandidateInterface* candidate) const override; - // Adds and takes ownership of the JsepIceCandidate. - // TODO(deadbeef): Make this use an std::unique_ptr<>, so ownership logic is - // more clear. - virtual void add(JsepIceCandidate* candidate); - const IceCandidateInterface* at(size_t index) const override; - // Removes the candidate that has a matching address and protocol. - // - // Returns the number of candidates that were removed. - size_t remove(const Candidate& candidate); - - private: - std::vector> candidates_; -}; - -} // namespace webrtc #endif // API_JSEP_ICE_CANDIDATE_H_ diff --git a/api/jsep_session_description.h b/api/jsep_session_description.h index 2b25bb1cf9..d2683a01db 100644 --- a/api/jsep_session_description.h +++ b/api/jsep_session_description.h @@ -22,7 +22,6 @@ #include "absl/strings/string_view.h" #include "api/candidate.h" #include "api/jsep.h" -#include "api/jsep_ice_candidate.h" namespace webrtc { @@ -59,7 +58,10 @@ class JsepSessionDescription : public SessionDescriptionInterface { virtual SdpType GetType() const { return type_; } virtual std::string type() const { return SdpTypeToString(type_); } // Allows changing the type. Used for testing. - virtual bool AddCandidate(const IceCandidateInterface* candidate); + virtual bool AddCandidate(const IceCandidate* candidate); + virtual bool RemoveCandidate(const IceCandidate* candidate); + // TODO: https://issues.webrtc.org/42233526 - Remove this method in favor of + // the IceCandidate version. virtual size_t RemoveCandidates(const std::vector& candidates); virtual size_t number_of_mediasections() const; virtual const IceCandidateCollection* candidates( @@ -73,8 +75,7 @@ class JsepSessionDescription : public SessionDescriptionInterface { SdpType type_; std::vector candidate_collection_; - bool GetMediasectionIndex(const IceCandidateInterface* candidate, - size_t* index); + bool GetMediasectionIndex(const IceCandidate* candidate, size_t* index); int GetMediasectionIndex(const Candidate& candidate); }; diff --git a/api/legacy_stats_types.h b/api/legacy_stats_types.h index 8d94541ed8..51b9318c2d 100644 --- a/api/legacy_stats_types.h +++ b/api/legacy_stats_types.h @@ -244,7 +244,7 @@ class RTC_EXPORT StatsReport { kStatsValueNameLocalCandidateRelayProtocol, }; - class RTC_EXPORT IdBase : public webrtc::RefCountInterface { + class RTC_EXPORT IdBase : public RefCountInterface { public: ~IdBase() override; StatsType type() const; @@ -356,7 +356,7 @@ class RTC_EXPORT StatsReport { #endif private: - webrtc::SequenceChecker thread_checker_{webrtc::SequenceChecker::kDetached}; + SequenceChecker thread_checker_{SequenceChecker::kDetached}; mutable int ref_count_ RTC_GUARDED_BY(thread_checker_) = 0; const Type type_; @@ -474,7 +474,7 @@ class StatsCollection { private: Container list_; - webrtc::SequenceChecker thread_checker_{SequenceChecker::kDetached}; + SequenceChecker thread_checker_{SequenceChecker::kDetached}; }; } // namespace webrtc diff --git a/api/local_network_access_permission.h b/api/local_network_access_permission.h new file mode 100644 index 0000000000..0dad57f9dc --- /dev/null +++ b/api/local_network_access_permission.h @@ -0,0 +1,86 @@ +/* + * Copyright 2025 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_LOCAL_NETWORK_ACCESS_PERMISSION_H_ +#define API_LOCAL_NETWORK_ACCESS_PERMISSION_H_ + +#include + +#include "absl/functional/any_invocable.h" +#include "rtc_base/socket_address.h" + +namespace webrtc { + +// This interface defines methods to request a Local Network Access permission +// asynchronously. The LocalNetworkAccessPermissionInterface class encapsulates +// a single permission request. +// +// Usage: +// // An implementation of the factory should be passed in by the embedder. +// std::unique_ptr factory = +// embedder_factory; +// +// Stores pending permission requests. +// std::vector> +// permission_list; +// +// std::unique_ptr permission = +// factory->Create(); +// permission->RequestPermission( +// target_address, +// [&, r = permission.get()](LocalNetworkAccessPermissionStatus status) { +// permission_list.erase(std::remove_if( +// permission_list.begin(), permission_list.end(), +// [&](const auto& refptr) { return refptr.get() == r; })); +// +// if (status == LocalNetworkAccessPermissionStatus::kGranted) { +// // Permission was granted. +// } else { +// // Permission was denied. +// } +// }); +// permission_list.push_back(std::move(permission)); + +enum class LocalNetworkAccessPermissionStatus { + kGranted, + kDenied, +}; + +// The API for a single permission 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 +// permission's destructor has been called. +class LocalNetworkAccessPermissionInterface { + public: + virtual ~LocalNetworkAccessPermissionInterface() = default; + + // The callback will be called when the permission is granted or denied. The + // callback will be called on the sequence that the caller runs on. + virtual void RequestPermission( + const SocketAddress& addr, + absl::AnyInvocable + callback) = 0; +}; + +// An abstract factory for creating LocalNetworkPermissionInterfaces. This +// allows client applications to provide WebRTC with their own mechanism for +// checking and requesting Local Network Access permission. +class LocalNetworkAccessPermissionFactoryInterface { + public: + virtual ~LocalNetworkAccessPermissionFactoryInterface() = default; + + // Creates a LocalNetworkAccessPermission. + virtual std::unique_ptr Create() = 0; +}; + +} // namespace webrtc + +#endif // API_LOCAL_NETWORK_ACCESS_PERMISSION_H_ diff --git a/api/make_ref_counted.h b/api/make_ref_counted.h index b7781e9bed..48a05359a4 100644 --- a/api/make_ref_counted.h +++ b/api/make_ref_counted.h @@ -56,7 +56,7 @@ class HasAddRefAndRelease { // auto p = scoped_refptr(new RefCountedObject("bar", 123)); // // If the class does not inherit from RefCountInterface, but does have -// AddRef/Release methods (so a T* is convertible to webrtc::scoped_refptr), +// AddRef/Release methods (so a T* is convertible to scoped_refptr), // this is equivalent to just // // auto p = scoped_refptr(new Foo("bar", 123)); diff --git a/api/media_stream_interface.h b/api/media_stream_interface.h index c3b60f7034..07fc72dc12 100644 --- a/api/media_stream_interface.h +++ b/api/media_stream_interface.h @@ -56,7 +56,7 @@ class NotifierInterface { // Base class for sources. A MediaStreamTrack has an underlying source that // provides media. A source can be shared by multiple tracks. -class RTC_EXPORT MediaSourceInterface : public webrtc::RefCountInterface, +class RTC_EXPORT MediaSourceInterface : public RefCountInterface, public NotifierInterface { public: enum SourceState { kInitializing, kLive, kEnded, kMuted }; @@ -71,7 +71,7 @@ class RTC_EXPORT MediaSourceInterface : public webrtc::RefCountInterface, // C++ version of MediaStreamTrack. // See: https://www.w3.org/TR/mediacapture-streams/#mediastreamtrack -class RTC_EXPORT MediaStreamTrackInterface : public webrtc::RefCountInterface, +class RTC_EXPORT MediaStreamTrackInterface : public RefCountInterface, public NotifierInterface { public: enum TrackState { @@ -106,7 +106,7 @@ class RTC_EXPORT MediaStreamTrackInterface : public webrtc::RefCountInterface, // VideoTrackSourceInterface is a reference counted source used for // VideoTracks. The same source can be used by multiple VideoTracks. // VideoTrackSourceInterface is designed to be invoked on the signaling thread -// except for webrtc::VideoSourceInterface methods that will be +// except for VideoSourceInterface methods that will be // invoked on the worker thread via a VideoTrack. A custom implementation of a // source can inherit AdaptedVideoTrackSource instead of directly implementing // this interface. @@ -161,14 +161,14 @@ class VideoTrackSourceInterface : public MediaSourceInterface, // 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 */) {} + const VideoTrackSourceConstraints& /* constraints */) {} protected: ~VideoTrackSourceInterface() override = default; }; // VideoTrackInterface is designed to be invoked on the signaling thread except -// for webrtc::VideoSourceInterface methods that must be invoked +// for VideoSourceInterface methods that must be invoked // on the worker thread. // PeerConnectionFactory::CreateVideoTrack can be used for creating a VideoTrack // that ensures thread safety and that all methods are called on the right @@ -210,7 +210,7 @@ class AudioTrackSinkInterface { // In this method, `absolute_capture_timestamp_ms`, when available, is // supposed to deliver the timestamp when this audio frame was originally // captured. This timestamp MUST be based on the same clock as - // webrtc::TimeMillis(). + // TimeMillis(). virtual void OnData( const void* audio_data, int bits_per_sample, @@ -269,7 +269,7 @@ class RTC_EXPORT AudioSourceInterface : public MediaSourceInterface { // Interface of the audio processor used by the audio track to collect // statistics. -class AudioProcessorInterface : public webrtc::RefCountInterface { +class AudioProcessorInterface : public RefCountInterface { public: struct AudioProcessorStatistics { bool typing_noise_detected = false; @@ -323,7 +323,7 @@ typedef std::vector > VideoTrackVector; // must be pushed down. // // Thus, this interface acts as simply a container for tracks. -class MediaStreamInterface : public webrtc::RefCountInterface, +class MediaStreamInterface : public RefCountInterface, public NotifierInterface { public: virtual std::string id() const = 0; diff --git a/api/media_types.h b/api/media_types.h index c2d4149161..e58abfdb3b 100644 --- a/api/media_types.h +++ b/api/media_types.h @@ -24,7 +24,7 @@ enum class MediaType { DATA, UNSUPPORTED, ANY, - // Backwards compatibility values for webrtc::MediaType users + // Backwards compatibility values for MediaType users // TODO: https://issues.webrtc.org/42222911 - remove MEDIA_TYPE_AUDIO [[deprecated("Use AUDIO")]] = AUDIO, MEDIA_TYPE_VIDEO [[deprecated("Use VIDEO")]] = VIDEO, diff --git a/api/peer_connection_interface.cc b/api/peer_connection_interface.cc index 1af738a9d9..a6eaba6f50 100644 --- a/api/peer_connection_interface.cc +++ b/api/peer_connection_interface.cc @@ -53,13 +53,8 @@ PeerConnectionDependencies::~PeerConnectionDependencies() = default; PeerConnectionFactoryDependencies::PeerConnectionFactoryDependencies() = default; -// Allow move constructor to move deprecated members. Pragma can be removed -// when there are no deprecated depedencies at the moment. -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdeprecated-declarations" PeerConnectionFactoryDependencies::PeerConnectionFactoryDependencies( PeerConnectionFactoryDependencies&&) = default; -#pragma clang diagnostic pop PeerConnectionFactoryDependencies::~PeerConnectionFactoryDependencies() = default; diff --git a/api/peer_connection_interface.h b/api/peer_connection_interface.h index 1cd3379cba..25ac226bad 100644 --- a/api/peer_connection_interface.h +++ b/api/peer_connection_interface.h @@ -98,6 +98,7 @@ #include "api/ice_transport_interface.h" #include "api/jsep.h" #include "api/legacy_stats_types.h" +#include "api/local_network_access_permission.h" #include "api/media_stream_interface.h" #include "api/media_types.h" #include "api/metronome/metronome.h" @@ -116,7 +117,6 @@ #include "api/set_local_description_observer_interface.h" #include "api/set_remote_description_observer_interface.h" #include "api/stats/rtc_stats_collector_callback.h" -#include "api/task_queue/task_queue_factory.h" #include "api/transport/bandwidth_estimation_settings.h" #include "api/transport/bitrate_settings.h" #include "api/transport/enums.h" @@ -155,7 +155,7 @@ class MediaFactory; // IWYU pragma: end_keep // MediaStream container interface. -class StreamCollectionInterface : public webrtc::RefCountInterface { +class StreamCollectionInterface : public RefCountInterface { public: // TODO(ronghuawu): Update the function names to c++ style, e.g. find -> Find. virtual size_t count() = 0; @@ -169,7 +169,7 @@ class StreamCollectionInterface : public webrtc::RefCountInterface { ~StreamCollectionInterface() override = default; }; -class StatsObserver : public webrtc::RefCountInterface { +class StatsObserver : public RefCountInterface { public: virtual void OnComplete(const StatsReports& reports) = 0; @@ -184,7 +184,7 @@ enum class SdpSemantics { kUnifiedPlan, }; -class RTC_EXPORT PeerConnectionInterface : public webrtc::RefCountInterface { +class RTC_EXPORT PeerConnectionInterface : public RefCountInterface { public: // See https://w3c.github.io/webrtc-pc/#dom-rtcsignalingstate enum SignalingState { @@ -613,7 +613,7 @@ class RTC_EXPORT PeerConnectionInterface : public webrtc::RefCountInterface { // With this class one can modify outgoing TURN messages. // The object passed in must remain valid until PeerConnection::Close() is // called. - webrtc::TurnCustomizer* turn_customizer = nullptr; + TurnCustomizer* turn_customizer = nullptr; // Preferred network interface. // A candidate pair on a preferred network has a higher precedence in ICE @@ -864,13 +864,13 @@ class RTC_EXPORT PeerConnectionInterface : public webrtc::RefCountInterface { const RtpTransceiverInit& init) = 0; // Adds a transceiver with the given kind. Can either be - // webrtc::MediaType::AUDIO or webrtc::MediaType::VIDEO. Errors: - // - INVALID_PARAMETER: `media_type` is not webrtc::MediaType::AUDIO or - // webrtc::MediaType::VIDEO. + // MediaType::AUDIO or MediaType::VIDEO. Errors: + // - INVALID_PARAMETER: `media_type` is not MediaType::AUDIO or + // MediaType::VIDEO. virtual RTCErrorOr> AddTransceiver( - webrtc::MediaType media_type) = 0; + MediaType media_type) = 0; virtual RTCErrorOr> AddTransceiver( - webrtc::MediaType media_type, + MediaType media_type, const RtpTransceiverInit& init) = 0; // Creates a sender without a track. Can be used for "early media"/"warmup" @@ -941,7 +941,7 @@ class RTC_EXPORT PeerConnectionInterface : public webrtc::RefCountInterface { // version of getStats() in JavaScript. Implementation status is described in // api/stats/rtcstats_objects.h. For more details on stats, see spec: // https://w3c.github.io/webrtc-pc/#dom-rtcpeerconnection-getstats - // TODO(hbos): Takes shared ownership, use webrtc::scoped_refptr<> instead. + // TODO(hbos): Takes shared ownership, use scoped_refptr<> instead. // This requires stop overriding the current version in third party or making // third party calls explicit to avoid ambiguity during switch. Make the // future version abstract as soon as third party projects implement it. @@ -1117,19 +1117,18 @@ class RTC_EXPORT PeerConnectionInterface : public webrtc::RefCountInterface { // TODO(hbos): The spec mandates chaining this operation onto the operations // chain; deprecate and remove this version in favor of the callback-based // signature. - virtual bool AddIceCandidate(const IceCandidateInterface* candidate) = 0; + virtual bool AddIceCandidate(const IceCandidate* candidate) = 0; // TODO(hbos): Remove default implementation once implemented by downstream // projects. - virtual void AddIceCandidate( - std::unique_ptr /* candidate */, - std::function /* callback */) {} + virtual void AddIceCandidate(std::unique_ptr /* candidate */, + std::function /* callback */) {} // Removes a group of remote candidates from the ICE agent. Needed mainly for // continual gathering, to avoid an ever-growing list of candidates as // networks come and go. Note that the candidates' transport_name must be set // to the MID of the m= section that generated the candidate. - // TODO(bugs.webrtc.org/8395): Use IceCandidateInterface instead of - // webrtc::Candidate, which would avoid the transport_name oddity. + // TODO(bugs.webrtc.org/8395): Use IceCandidate instead of + // Candidate, which would avoid the transport_name oddity. virtual bool RemoveIceCandidates( const std::vector& candidates) = 0; @@ -1302,7 +1301,7 @@ class PeerConnectionObserver { PeerConnectionInterface::IceGatheringState new_state) = 0; // A new ICE candidate has been gathered. - virtual void OnIceCandidate(const IceCandidateInterface* candidate) = 0; + virtual void OnIceCandidate(const IceCandidate* candidate) = 0; // Gathering of an ICE candidate failed. // See https://w3c.github.io/webrtc-pc/#event-icecandidateerror @@ -1391,17 +1390,19 @@ struct RTC_EXPORT PeerConnectionDependencies final { // PacketSocketFactory when creating the PeerConnectionFactory. std::unique_ptr allocator; // Factory for creating resolvers that look up hostnames in DNS - std::unique_ptr - async_dns_resolver_factory; - std::unique_ptr ice_transport_factory; + std::unique_ptr async_dns_resolver_factory; + std::unique_ptr ice_transport_factory; std::unique_ptr cert_generator; std::unique_ptr tls_cert_verifier; - std::unique_ptr - video_bitrate_allocator_factory; + std::unique_ptr video_bitrate_allocator_factory; // Optional network controller factory to use. // Overrides that set in PeerConnectionFactoryDependencies. std::unique_ptr network_controller_factory; + // Optional permission factory to request Local Network Access permission. + std::unique_ptr + lna_permission_factory; + // Optional field trials to use. // Overrides those from PeerConnectionFactoryDependencies. std::unique_ptr trials; @@ -1433,15 +1434,11 @@ struct RTC_EXPORT PeerConnectionFactoryDependencies final { SocketFactory* socket_factory = nullptr; // Provides common widely used dependencies for webrtc subcomponents. - // `task_queue_factory` and `field_trials` members below override values in - // `env` when set. std::optional env; // The `packet_socket_factory` will only be used if CreatePeerConnection is // called without a `port_allocator`. std::unique_ptr packet_socket_factory; - [[deprecated("Pass custom task queue factory through the 'env'")]] - std::unique_ptr task_queue_factory; std::unique_ptr event_log_factory; std::unique_ptr fec_controller_factory; std::unique_ptr @@ -1456,8 +1453,6 @@ struct RTC_EXPORT PeerConnectionFactoryDependencies final { std::unique_ptr network_monitor_factory; std::unique_ptr neteq_factory; std::unique_ptr sctp_factory; - [[deprecated("Pass custom field trials through the 'env'")]] - std::unique_ptr trials; std::unique_ptr transport_controller_send_factory; // Metronome used for decoding, must be called on the worker thread. @@ -1498,8 +1493,7 @@ struct RTC_EXPORT PeerConnectionFactoryDependencies final { // of networking classes, it should use the alternate // CreatePeerConnectionFactory method which accepts threads as input, and use // the CreatePeerConnection version that takes a PortAllocator as an argument. -class RTC_EXPORT PeerConnectionFactoryInterface - : public webrtc::RefCountInterface { +class RTC_EXPORT PeerConnectionFactoryInterface : public RefCountInterface { public: class Options { public: @@ -1542,16 +1536,14 @@ class RTC_EXPORT PeerConnectionFactoryInterface PeerConnectionDependencies dependencies) = 0; // Returns the capabilities of an RTP sender of type `kind`. - // If for some reason you pass in webrtc::MediaType::DATA, returns an empty + // If for some reason you pass in MediaType::DATA, returns an empty // structure. - virtual RtpCapabilities GetRtpSenderCapabilities( - webrtc::MediaType kind) const = 0; + virtual RtpCapabilities GetRtpSenderCapabilities(MediaType kind) const = 0; // Returns the capabilities of an RTP receiver of type `kind`. - // If for some reason you pass in webrtc::MediaType::DATA, returns an empty + // If for some reason you pass in MediaType::DATA, returns an empty // structure. - virtual RtpCapabilities GetRtpReceiverCapabilities( - webrtc::MediaType kind) const = 0; + virtual RtpCapabilities GetRtpReceiverCapabilities(MediaType kind) const = 0; virtual scoped_refptr CreateLocalMediaStream( const std::string& stream_id) = 0; @@ -1617,7 +1609,7 @@ class RTC_EXPORT PeerConnectionFactoryInterface // If `network_thread` or `worker_thread` are null, the PeerConnectionFactory // will create the necessary thread internally. If `signaling_thread` is null, // the PeerConnectionFactory will use the thread on which this method is called -// as the signaling thread, wrapping it in an webrtc::Thread object if needed. +// as the signaling thread, wrapping it in an Thread object if needed. RTC_EXPORT scoped_refptr CreateModularPeerConnectionFactory( PeerConnectionFactoryDependencies dependencies); diff --git a/api/priority.h b/api/priority.h index bb2f88187b..e74e7d32fc 100644 --- a/api/priority.h +++ b/api/priority.h @@ -27,7 +27,7 @@ enum class Priority { }; class RTC_EXPORT PriorityValue - : public webrtc::StrongAlias { + : public StrongAlias { public: explicit PriorityValue(Priority priority); explicit PriorityValue(uint16_t priority) : StrongAlias(priority) {} diff --git a/api/ref_count.h b/api/ref_count.h index b3fb7630c8..0b9d56cc38 100644 --- a/api/ref_count.h +++ b/api/ref_count.h @@ -22,7 +22,7 @@ namespace webrtc { // you're borrowing someone else's reference. (A newly created object is a // special case: the reference count is zero on construction, and the code that // creates the object should immediately call AddRef(), bringing the reference -// count from zero to one, e.g., by constructing an webrtc::scoped_refptr). +// count from zero to one, e.g., by constructing an scoped_refptr). // // AddRef() creates a new reference to the object. // @@ -41,8 +41,8 @@ namespace webrtc { // result of another thread calling Release(). // // Calling AddRef() and Release() manually is discouraged. It's recommended to -// use webrtc::scoped_refptr to manage all pointers to reference counted -// objects. Note that webrtc::scoped_refptr depends on compile-time duck-typing; +// use scoped_refptr to manage all pointers to reference counted +// objects. Note that scoped_refptr depends on compile-time duck-typing; // formally implementing the below RefCountInterface is not required. enum class RefCountReleaseStatus { kDroppedLastRef, kOtherRefsRemained }; diff --git a/api/ref_counted_base.h b/api/ref_counted_base.h index 8862ebdcad..a411257069 100644 --- a/api/ref_counted_base.h +++ b/api/ref_counted_base.h @@ -41,7 +41,7 @@ class RefCountedBase { virtual ~RefCountedBase() = default; private: - mutable webrtc::webrtc_impl::RefCounter ref_count_{0}; + mutable webrtc_impl::RefCounter ref_count_{0}; }; // Template based version of `RefCountedBase` for simple implementations that do @@ -49,11 +49,11 @@ class RefCountedBase { // vtable. // // To use: -// struct MyInt : public webrtc::RefCountedNonVirtual { +// struct MyInt : public RefCountedNonVirtual { // int foo_ = 0; // }; // -// webrtc::scoped_refptr my_int(new MyInt()); +// scoped_refptr my_int(new MyInt()); // // sizeof(MyInt) on a 32 bit system would then be 8, int + refcount and no // vtable generated. @@ -73,7 +73,7 @@ class RefCountedNonVirtual { // so the virtual attribute(s) can be removed. // 2) The virtual methods are a part of the design of the class. In this // case you can consider using `RefCountedBase` instead or alternatively - // use `webrtc::RefCountedObject`. + // use `RefCountedObject`. static_assert(!std::is_polymorphic::value, "T has virtual methods. RefCountedBase is a better fit."); const auto status = ref_count_.DecRef(); @@ -91,7 +91,7 @@ class RefCountedNonVirtual { ~RefCountedNonVirtual() = default; private: - mutable webrtc::webrtc_impl::RefCounter ref_count_{0}; + mutable webrtc_impl::RefCounter ref_count_{0}; }; } // namespace webrtc diff --git a/api/rtp_packet_info.h b/api/rtp_packet_info.h index 8e8236d8f0..4059108c83 100644 --- a/api/rtp_packet_info.h +++ b/api/rtp_packet_info.h @@ -87,7 +87,7 @@ class RTC_EXPORT RtpPacketInfo { std::vector csrcs_; uint32_t rtp_timestamp_; - // Local `webrtc::Clock`-based timestamp of when the packet was received. + // Local `Clock`-based timestamp of when the packet was received. Timestamp receive_time_; // Fields from the Audio Level header extension: diff --git a/api/rtp_parameters.cc b/api/rtp_parameters.cc index c6560d4bb0..06c581157a 100644 --- a/api/rtp_parameters.cc +++ b/api/rtp_parameters.cc @@ -202,7 +202,7 @@ bool RtpExtension::IsEncryptionSupported(absl::string_view uri) { // srtpfilter. External auth is used by Chromium and replaces the // extension header value of "kAbsSendTimeUri", so it must not be // encrypted (which can't be done by Chromium). - uri != webrtc::RtpExtension::kAbsSendTimeUri && + uri != RtpExtension::kAbsSendTimeUri && #endif uri != RtpExtension::kEncryptHeaderExtensionsUri; } diff --git a/api/rtp_parameters.h b/api/rtp_parameters.h index 57d77f2fe4..f30db96c6c 100644 --- a/api/rtp_parameters.h +++ b/api/rtp_parameters.h @@ -137,7 +137,7 @@ struct RTC_EXPORT RtpCodec { std::string name; // The media type of this codec. Equivalent to MIME top-level type. - webrtc::MediaType kind = webrtc::MediaType::AUDIO; + MediaType kind = MediaType::AUDIO; // If unset, the implementation default is used. std::optional clock_rate; @@ -195,7 +195,7 @@ struct RTC_EXPORT RtpCodecCapability : public RtpCodec { template friend void AbslStringify(Sink& sink, const RtpCodecCapability& cap) { - if (cap.kind == webrtc::MediaType::AUDIO) { + if (cap.kind == MediaType::AUDIO) { absl::Format(&sink, "[audio/%s/%d/%d]", cap.name, cap.clock_rate.value_or(0), cap.num_channels.value_or(1)); } else { @@ -214,7 +214,7 @@ struct RTC_EXPORT RtpCodecCapability : public RtpCodec { // // Note that ORTC includes a "kind" field, but we omit this because it's // redundant; if you call -// "RtpReceiver::GetCapabilities(webrtc::MediaType::AUDIO)", you know you're +// "RtpReceiver::GetCapabilities(MediaType::AUDIO)", you know you're // getting audio capabilities. struct RTC_EXPORT RtpHeaderExtensionCapability { // URI of this extension, as defined in RFC8285. @@ -251,6 +251,17 @@ struct RTC_EXPORT RtpHeaderExtensionCapability { bool operator!=(const RtpHeaderExtensionCapability& o) const { return !(*this == o); } + template + friend void AbslStringify(Sink& sink, + const RtpHeaderExtensionCapability& cap) { + absl::Format(&sink, "%s", cap.uri); + if (cap.direction != RtpTransceiverDirection::kSendRecv) { + absl::Format(&sink, "/%v", cap.direction); + } + if (cap.preferred_encrypt) { + sink.Append(" (encrypt)"); + } + } }; // RTP header extension, see RFC8285. @@ -383,7 +394,7 @@ struct RTC_EXPORT RtpExtension { static constexpr char kRepairedRidUri[] = "urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"; - // Header extension to propagate webrtc::VideoFrame id field + // Header extension to propagate VideoFrame id field static constexpr char kVideoFrameTrackingIdUri[] = "http://www.webrtc.org/experiments/rtp-hdrext/video-frame-tracking-id"; @@ -466,6 +477,14 @@ struct RTC_EXPORT RtpEncodingParameters { // unset SSRC acts as a "wildcard" SSRC. std::optional ssrc; + // The list of CSRCs to be included in the RTP header. Defaults to an empty + // list. At most 15 CSRCs can be specified, and they must be the same for all + // encodings in an RtpParameters struct. + // + // If this field is set, the list is replaced with the specified values. + // Otherwise, it is left unchanged. Specify an empty vector to clear the list. + std::optional> csrcs; + // The relative bitrate priority of this encoding. Currently this is // implemented for the entire rtp sender by using the value of the first // encoding parameter. @@ -550,7 +569,8 @@ struct RTC_EXPORT RtpEncodingParameters { std::optional codec; bool operator==(const RtpEncodingParameters& o) const { - return ssrc == o.ssrc && bitrate_priority == o.bitrate_priority && + return ssrc == o.ssrc && csrcs == o.csrcs && + bitrate_priority == o.bitrate_priority && network_priority == o.network_priority && max_bitrate_bps == o.max_bitrate_bps && min_bitrate_bps == o.min_bitrate_bps && @@ -581,6 +601,10 @@ struct RTC_EXPORT RtpCodecParameters : public RtpCodec { return RtpCodec::operator==(o) && payload_type == o.payload_type; } bool operator!=(const RtpCodecParameters& o) const { return !(*this == o); } + template + friend void AbslStringify(Sink& sink, const RtpCodecParameters& p) { + absl::Format(&sink, "[%d: %s]", p.payload_type, p.mime_type()); + } }; // RtpCapabilities is used to represent the static capabilities of an endpoint. diff --git a/api/rtp_receiver_interface.h b/api/rtp_receiver_interface.h index 29df678e18..bf87f463c3 100644 --- a/api/rtp_receiver_interface.h +++ b/api/rtp_receiver_interface.h @@ -40,13 +40,13 @@ class RtpReceiverObserverInterface { // In the future, it's likely that an RtpReceiver will only call // OnFirstPacketReceived when a packet is received specifically for its // SSRC/mid. - virtual void OnFirstPacketReceived(webrtc::MediaType media_type) = 0; + virtual void OnFirstPacketReceived(MediaType media_type) = 0; protected: virtual ~RtpReceiverObserverInterface() {} }; -class RTC_EXPORT RtpReceiverInterface : public webrtc::RefCountInterface, +class RTC_EXPORT RtpReceiverInterface : public RefCountInterface, public FrameTransformerHost { public: virtual scoped_refptr track() const = 0; @@ -68,7 +68,7 @@ class RTC_EXPORT RtpReceiverInterface : public webrtc::RefCountInterface, virtual std::vector> streams() const; // Audio or video receiver? - virtual webrtc::MediaType media_type() const = 0; + virtual MediaType media_type() const = 0; // Not to be confused with "mid", this is a field we can temporarily use // to uniquely identify a receiver until we implement Unified Plan SDP. diff --git a/api/rtp_sender_interface.h b/api/rtp_sender_interface.h index 478e15d570..2a7907dc4e 100644 --- a/api/rtp_sender_interface.h +++ b/api/rtp_sender_interface.h @@ -40,7 +40,7 @@ class RtpSenderObserverInterface { public: // The observer is called when the first media packet is sent for the observed // sender. It is called immediately if the first packet was already sent. - virtual void OnFirstPacketSent(webrtc::MediaType media_type) = 0; + virtual void OnFirstPacketSent(MediaType media_type) = 0; protected: virtual ~RtpSenderObserverInterface() {} @@ -48,7 +48,7 @@ class RtpSenderObserverInterface { using SetParametersCallback = absl::AnyInvocable; -class RTC_EXPORT RtpSenderInterface : public webrtc::RefCountInterface, +class RTC_EXPORT RtpSenderInterface : public RefCountInterface, public FrameTransformerHost { public: // Returns true if successful in setting the track. @@ -68,7 +68,7 @@ class RTC_EXPORT RtpSenderInterface : public webrtc::RefCountInterface, virtual uint32_t ssrc() const = 0; // Audio or video sender? - virtual webrtc::MediaType media_type() const = 0; + virtual MediaType media_type() const = 0; // Not to be confused with "mid", this is a field we can temporarily use // to uniquely identify a receiver until we implement Unified Plan SDP. diff --git a/api/rtp_transceiver_direction.h b/api/rtp_transceiver_direction.h index 3c7d4cb0ad..dceff67bdb 100644 --- a/api/rtp_transceiver_direction.h +++ b/api/rtp_transceiver_direction.h @@ -22,6 +22,27 @@ enum class RtpTransceiverDirection { kStopped, }; +template +void AbslStringify(Sink& sink, RtpTransceiverDirection direction) { + switch (direction) { + case RtpTransceiverDirection::kSendRecv: + sink.Append("sendrecv"); + break; + case RtpTransceiverDirection::kSendOnly: + sink.Append("send"); + break; + case RtpTransceiverDirection::kRecvOnly: + sink.Append("recv"); + break; + case RtpTransceiverDirection::kInactive: + sink.Append("inactive"); + break; + case RtpTransceiverDirection::kStopped: + sink.Append("stopped"); + break; + } +} + } // namespace webrtc #endif // API_RTP_TRANSCEIVER_DIRECTION_H_ diff --git a/api/rtp_transceiver_interface.h b/api/rtp_transceiver_interface.h index e35c5b729f..0d9671f010 100644 --- a/api/rtp_transceiver_interface.h +++ b/api/rtp_transceiver_interface.h @@ -59,11 +59,11 @@ struct RTC_EXPORT RtpTransceiverInit final { // // WebRTC specification for RTCRtpTransceiver, the JavaScript analog: // https://w3c.github.io/webrtc-pc/#dom-rtcrtptransceiver -class RTC_EXPORT RtpTransceiverInterface : public webrtc::RefCountInterface { +class RTC_EXPORT RtpTransceiverInterface : public RefCountInterface { public: // Media type of the transceiver. Any sender(s)/receiver(s) will have this // type as well. - virtual webrtc::MediaType media_type() const = 0; + virtual MediaType media_type() const = 0; // The mid attribute is the mid negotiated and present in the local and // remote descriptions. Before negotiation is complete, the mid value may be @@ -165,7 +165,7 @@ class RTC_EXPORT RtpTransceiverInterface : public webrtc::RefCountInterface { // The SetHeaderExtensionsToNegotiate method modifies the next SDP negotiation // so that it negotiates use of header extensions which are not kStopped. // https://w3c.github.io/webrtc-extensions/#rtcrtptransceiver-interface - virtual webrtc::RTCError SetHeaderExtensionsToNegotiate( + virtual RTCError SetHeaderExtensionsToNegotiate( ArrayView header_extensions) = 0; protected: diff --git a/api/sctp_transport_interface.h b/api/sctp_transport_interface.h index a9fd115937..ba68ca0924 100644 --- a/api/sctp_transport_interface.h +++ b/api/sctp_transport_interface.h @@ -75,7 +75,7 @@ class SctpTransportObserverInterface { // accessed on that thread, except for functions explicitly marked otherwise. // References can be held by other threads, and destruction can therefore // be initiated by other threads. -class SctpTransportInterface : public webrtc::RefCountInterface { +class SctpTransportInterface : public RefCountInterface { public: // This function can be called from other threads. virtual scoped_refptr dtls_transport() const = 0; diff --git a/api/set_local_description_observer_interface.h b/api/set_local_description_observer_interface.h index 40f85b944e..3ba19f9fef 100644 --- a/api/set_local_description_observer_interface.h +++ b/api/set_local_description_observer_interface.h @@ -19,7 +19,7 @@ namespace webrtc { // OnSetLocalDescriptionComplete() invokes as soon as // PeerConnectionInterface::SetLocalDescription() operation completes, allowing // the observer to examine the effects of the operation without delay. -class SetLocalDescriptionObserverInterface : public webrtc::RefCountInterface { +class SetLocalDescriptionObserverInterface : public RefCountInterface { public: // On success, `error.ok()` is true. virtual void OnSetLocalDescriptionComplete(RTCError error) = 0; diff --git a/api/set_remote_description_observer_interface.h b/api/set_remote_description_observer_interface.h index c1625410df..4e77be0428 100644 --- a/api/set_remote_description_observer_interface.h +++ b/api/set_remote_description_observer_interface.h @@ -20,7 +20,7 @@ namespace webrtc { // callback is invoked such that the state of the peer connection can be // examined to accurately reflect the effects of the SetRemoteDescription // operation. -class SetRemoteDescriptionObserverInterface : public webrtc::RefCountInterface { +class SetRemoteDescriptionObserverInterface : public RefCountInterface { public: // On success, `error.ok()` is true. virtual void OnSetRemoteDescriptionComplete(RTCError error) = 0; diff --git a/api/task_queue/pending_task_safety_flag.h b/api/task_queue/pending_task_safety_flag.h index 71e871064b..e514b41d85 100644 --- a/api/task_queue/pending_task_safety_flag.h +++ b/api/task_queue/pending_task_safety_flag.h @@ -40,7 +40,7 @@ namespace webrtc { // // class ExampleClass { // .... -// webrtc::scoped_refptr flag = safety_flag_; +// scoped_refptr flag = safety_flag_; // my_task_queue_->PostTask( // [flag = std::move(flag), this] { // // Now running on the main thread. diff --git a/api/task_queue/task_queue_test.cc b/api/task_queue/task_queue_test.cc index a7c62262e3..b0054de320 100644 --- a/api/task_queue/task_queue_test.cc +++ b/api/task_queue/task_queue_test.cc @@ -54,7 +54,7 @@ TEST_P(TaskQueueTest, PostAndCheckCurrent) { auto queue = CreateTaskQueue(factory, "PostAndCheckCurrent"); // We're not running a task, so `queue` shouldn't be current. - // Note that because webrtc::Thread also supports the TQ interface and + // Note that because Thread also supports the TQ interface and // TestMainImpl::Init wraps the main test thread (bugs.webrtc.org/9714), that // means that TaskQueueBase::Current() will still return a valid value. EXPECT_FALSE(queue->IsCurrent()); diff --git a/api/task_queue/task_queue_test.h b/api/task_queue/task_queue_test.h index 214f95008f..6237f7f567 100644 --- a/api/task_queue/task_queue_test.h +++ b/api/task_queue/task_queue_test.h @@ -27,7 +27,7 @@ namespace webrtc { // using ::testing::Values; // using ::webrtc::TaskQueueTest; // -// std::unique_ptr CreateMyFactory(); +// std::unique_ptr CreateMyFactory(); // // INSTANTIATE_TEST_SUITE_P(My, TaskQueueTest, Values(CreateMyFactory)); // diff --git a/api/test/DEPS b/api/test/DEPS index b54b321b59..b3504bd021 100644 --- a/api/test/DEPS +++ b/api/test/DEPS @@ -44,6 +44,9 @@ specific_include_rules = { "mock_async_dns_resolver\.h": [ "+rtc_base/socket_address.h", ], + "mock_local_network_access_permission\.h": [ + "+rtc_base/socket_address.h", + ], "mock_packet_socket_factory\.h": [ "+rtc_base/async_packet_socket.h", "+rtc_base/socket_address.h", diff --git a/api/test/compile_all_headers.cc b/api/test/compile_all_headers.cc index ca586b39b1..2254a85de1 100644 --- a/api/test/compile_all_headers.cc +++ b/api/test/compile_all_headers.cc @@ -23,7 +23,6 @@ // "api/test/neteq_simulator.h" // "api/test/simulated_network.h" // "api/test/simulcast_test_fixture.h" -// "api/test/test_dependency_factory.h" // "api/test/videocodec_test_fixture.h" // "api/test/videocodec_test_stats.h" diff --git a/api/test/create_video_quality_test_fixture.cc b/api/test/create_video_quality_test_fixture.cc index 1cfe228423..f393c11d10 100644 --- a/api/test/create_video_quality_test_fixture.cc +++ b/api/test/create_video_quality_test_fixture.cc @@ -13,30 +13,23 @@ #include #include -#include "api/fec_controller.h" #include "api/test/video_quality_test_fixture.h" #include "video/video_quality_test.h" namespace webrtc { -std::unique_ptr -CreateVideoQualityTestFixture() { - // By default, we don't override the FEC module, so pass an empty factory. - return std::make_unique(nullptr); -} - std::unique_ptr CreateVideoQualityTestFixture( - std::unique_ptr fec_controller_factory) { - auto components = - std::make_unique(); - components->fec_controller_factory = std::move(fec_controller_factory); + VideoQualityTestFixtureInterface::InjectionComponents components) { return std::make_unique(std::move(components)); } std::unique_ptr CreateVideoQualityTestFixture( std::unique_ptr components) { - return std::make_unique(std::move(components)); + if (components == nullptr) { + return CreateVideoQualityTestFixture(); + } + return CreateVideoQualityTestFixture(std::move(*components)); } } // namespace webrtc diff --git a/api/test/create_video_quality_test_fixture.h b/api/test/create_video_quality_test_fixture.h index ed618fefc8..ea6b3a5929 100644 --- a/api/test/create_video_quality_test_fixture.h +++ b/api/test/create_video_quality_test_fixture.h @@ -12,17 +12,14 @@ #include -#include "api/fec_controller.h" #include "api/test/video_quality_test_fixture.h" namespace webrtc { -std::unique_ptr -CreateVideoQualityTestFixture(); - std::unique_ptr CreateVideoQualityTestFixture( - std::unique_ptr fec_controller_factory); + VideoQualityTestFixtureInterface::InjectionComponents components = {}); +[[deprecated]] std::unique_ptr CreateVideoQualityTestFixture( std::unique_ptr components); diff --git a/api/test/fake_frame_decryptor.h b/api/test/fake_frame_decryptor.h index f204a91aeb..b3a79970d2 100644 --- a/api/test/fake_frame_decryptor.h +++ b/api/test/fake_frame_decryptor.h @@ -34,13 +34,13 @@ class FakeFrameDecryptor : public FrameDecryptorInterface { uint8_t expected_postfix_byte = 255); // Fake decryption that just xors the payload with the 1 byte key and checks // the postfix byte. This will always fail if fail_decryption_ is set to true. - Result Decrypt(webrtc::MediaType media_type, + Result Decrypt(MediaType media_type, const std::vector& csrcs, ArrayView additional_data, ArrayView encrypted_frame, ArrayView frame) override; // Always returns 1 less than the size of the encrypted frame. - size_t GetMaxPlaintextByteSize(webrtc::MediaType media_type, + size_t GetMaxPlaintextByteSize(MediaType media_type, size_t encrypted_frame_size) override; // Sets the fake key to use for encryption. void SetFakeKey(uint8_t fake_key); diff --git a/api/test/fake_frame_encryptor.h b/api/test/fake_frame_encryptor.h index 4cb615b00d..eae0e41b3d 100644 --- a/api/test/fake_frame_encryptor.h +++ b/api/test/fake_frame_encryptor.h @@ -32,14 +32,14 @@ class FakeFrameEncryptor : public RefCountedObject { uint8_t postfix_byte = 255); // Simply xors each payload with the provided fake key and adds the postfix // bit to the end. This will always fail if fail_encryption_ is set to true. - int Encrypt(webrtc::MediaType media_type, + int Encrypt(MediaType media_type, uint32_t ssrc, ArrayView additional_data, ArrayView frame, ArrayView encrypted_frame, size_t* bytes_written) override; // Always returns 1 more than the size of the frame. - size_t GetMaxCiphertextByteSize(webrtc::MediaType media_type, + size_t GetMaxCiphertextByteSize(MediaType media_type, size_t frame_size) override; // Sets the fake key to use during encryption. void SetFakeKey(uint8_t fake_key); diff --git a/api/test/mock_async_dns_resolver.h b/api/test/mock_async_dns_resolver.h index 5848972d07..3ae0557265 100644 --- a/api/test/mock_async_dns_resolver.h +++ b/api/test/mock_async_dns_resolver.h @@ -24,7 +24,7 @@ class MockAsyncDnsResolverResult : public AsyncDnsResolverResult { public: MOCK_METHOD(bool, GetResolvedAddress, - (int, webrtc::SocketAddress*), + (int, SocketAddress*), (const, override)); MOCK_METHOD(int, GetError, (), (const, override)); }; @@ -33,28 +33,26 @@ class MockAsyncDnsResolver : public AsyncDnsResolverInterface { public: MOCK_METHOD(void, Start, - (const webrtc::SocketAddress&, absl::AnyInvocable), + (const SocketAddress&, absl::AnyInvocable), (override)); MOCK_METHOD(void, Start, - (const webrtc::SocketAddress&, - int family, - absl::AnyInvocable), + (const SocketAddress&, int family, absl::AnyInvocable), (override)); MOCK_METHOD(AsyncDnsResolverResult&, result, (), (const, override)); }; class MockAsyncDnsResolverFactory : public AsyncDnsResolverFactoryInterface { public: - MOCK_METHOD(std::unique_ptr, + MOCK_METHOD(std::unique_ptr, CreateAndResolve, - (const webrtc::SocketAddress&, absl::AnyInvocable), + (const SocketAddress&, absl::AnyInvocable), (override)); - MOCK_METHOD(std::unique_ptr, + MOCK_METHOD(std::unique_ptr, CreateAndResolve, - (const webrtc::SocketAddress&, int, absl::AnyInvocable), + (const SocketAddress&, int, absl::AnyInvocable), (override)); - MOCK_METHOD(std::unique_ptr, + MOCK_METHOD(std::unique_ptr, Create, (), (override)); diff --git a/api/test/mock_audio_sink.h b/api/test/mock_audio_sink.h index dcb01cc678..c2463ca9e5 100644 --- a/api/test/mock_audio_sink.h +++ b/api/test/mock_audio_sink.h @@ -20,7 +20,7 @@ namespace webrtc { -class MockAudioSink : public webrtc::AudioTrackSinkInterface { +class MockAudioSink : public AudioTrackSinkInterface { public: MOCK_METHOD(void, OnData, diff --git a/api/test/mock_data_channel.h b/api/test/mock_data_channel.h index 9a8ff8cf51..494f9ecbb7 100644 --- a/api/test/mock_data_channel.h +++ b/api/test/mock_data_channel.h @@ -25,8 +25,7 @@ namespace webrtc { -class MockDataChannelInterface - : public RefCountedObject { +class MockDataChannelInterface : public RefCountedObject { public: static scoped_refptr Create() { return scoped_refptr( diff --git a/api/test/mock_dtmf_sender.h b/api/test/mock_dtmf_sender.h index 3164975568..7351ecd88c 100644 --- a/api/test/mock_dtmf_sender.h +++ b/api/test/mock_dtmf_sender.h @@ -53,8 +53,7 @@ class MockDtmfSender : public DtmfSenderInterface { MockDtmfSender() = default; }; -static_assert(!std::is_abstract_v>, - ""); +static_assert(!std::is_abstract_v>, ""); } // namespace webrtc diff --git a/api/test/mock_frame_decryptor.h b/api/test/mock_frame_decryptor.h index 79062ba3ea..191a7dd83a 100644 --- a/api/test/mock_frame_decryptor.h +++ b/api/test/mock_frame_decryptor.h @@ -26,16 +26,16 @@ class MockFrameDecryptor : public FrameDecryptorInterface { public: MOCK_METHOD(Result, Decrypt, - (webrtc::MediaType, + (MediaType, const std::vector&, - webrtc::ArrayView, - webrtc::ArrayView, - webrtc::ArrayView), + ArrayView, + ArrayView, + ArrayView), (override)); MOCK_METHOD(size_t, GetMaxPlaintextByteSize, - (webrtc::MediaType, size_t encrypted_frame_size), + (MediaType, size_t encrypted_frame_size), (override)); }; diff --git a/api/test/mock_frame_encryptor.h b/api/test/mock_frame_encryptor.h index 31f0a2c518..a449a29aee 100644 --- a/api/test/mock_frame_encryptor.h +++ b/api/test/mock_frame_encryptor.h @@ -25,17 +25,17 @@ class MockFrameEncryptor : public FrameEncryptorInterface { public: MOCK_METHOD(int, Encrypt, - (webrtc::MediaType, + (MediaType, uint32_t, - webrtc::ArrayView, - webrtc::ArrayView, - webrtc::ArrayView, + ArrayView, + ArrayView, + ArrayView, size_t*), (override)); MOCK_METHOD(size_t, GetMaxCiphertextByteSize, - (webrtc::MediaType media_type, size_t frame_size), + (MediaType media_type, size_t frame_size), (override)); }; diff --git a/api/test/mock_frame_transformer.h b/api/test/mock_frame_transformer.h index 8dd311c854..06845132f7 100644 --- a/api/test/mock_frame_transformer.h +++ b/api/test/mock_frame_transformer.h @@ -28,11 +28,11 @@ class MockFrameTransformer : public FrameTransformerInterface { (override)); MOCK_METHOD(void, RegisterTransformedFrameCallback, - (webrtc::scoped_refptr), + (scoped_refptr), (override)); MOCK_METHOD(void, RegisterTransformedFrameSinkCallback, - (webrtc::scoped_refptr, uint32_t), + (scoped_refptr, uint32_t), (override)); MOCK_METHOD(void, UnregisterTransformedFrameCallback, (), (override)); MOCK_METHOD(void, diff --git a/api/test/mock_local_network_access_permission.h b/api/test/mock_local_network_access_permission.h new file mode 100644 index 0000000000..47fac75898 --- /dev/null +++ b/api/test/mock_local_network_access_permission.h @@ -0,0 +1,45 @@ +/* + * Copyright 2025 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_TEST_MOCK_LOCAL_NETWORK_ACCESS_PERMISSION_H_ +#define API_TEST_MOCK_LOCAL_NETWORK_ACCESS_PERMISSION_H_ + +#include + +#include "absl/functional/any_invocable.h" +#include "api/local_network_access_permission.h" +#include "rtc_base/socket_address.h" +#include "test/gmock.h" + +namespace webrtc { + +class MockLocalNetworkAccessPermission + : public LocalNetworkAccessPermissionInterface { + public: + MOCK_METHOD( + void, + RequestPermission, + (const SocketAddress& addr, + absl::AnyInvocable callback), + (override)); +}; + +class MockLocalNetworkAccessPermissionFactory + : public LocalNetworkAccessPermissionFactoryInterface { + public: + MOCK_METHOD(std::unique_ptr, + Create, + (), + (override)); +}; + +} // namespace webrtc + +#endif // API_TEST_MOCK_LOCAL_NETWORK_ACCESS_PERMISSION_H_ diff --git a/api/test/mock_media_stream_interface.h b/api/test/mock_media_stream_interface.h index 0910f1daac..d0f452218c 100644 --- a/api/test/mock_media_stream_interface.h +++ b/api/test/mock_media_stream_interface.h @@ -102,19 +102,19 @@ class MockMediaStream : public MediaStreamInterface { (override)); MOCK_METHOD(bool, AddTrack, - (webrtc::scoped_refptr track), + (scoped_refptr track), (override)); MOCK_METHOD(bool, AddTrack, - (webrtc::scoped_refptr track), + (scoped_refptr track), (override)); MOCK_METHOD(bool, RemoveTrack, - (webrtc::scoped_refptr track), + (scoped_refptr track), (override)); MOCK_METHOD(bool, RemoveTrack, - (webrtc::scoped_refptr track), + (scoped_refptr track), (override)); MOCK_METHOD(void, RegisterObserver, @@ -126,8 +126,7 @@ class MockMediaStream : public MediaStreamInterface { (override)); }; -static_assert(!std::is_abstract_v>, - ""); +static_assert(!std::is_abstract_v>, ""); } // namespace webrtc diff --git a/api/test/mock_peer_connection_factory_interface.h b/api/test/mock_peer_connection_factory_interface.h index a297e58435..4e75a10266 100644 --- a/api/test/mock_peer_connection_factory_interface.h +++ b/api/test/mock_peer_connection_factory_interface.h @@ -29,7 +29,7 @@ namespace webrtc { class MockPeerConnectionFactoryInterface - : public RefCountedObject { + : public RefCountedObject { public: static scoped_refptr Create() { return scoped_refptr( @@ -44,11 +44,11 @@ class MockPeerConnectionFactoryInterface (override)); MOCK_METHOD(RtpCapabilities, GetRtpSenderCapabilities, - (webrtc::MediaType), + (MediaType), (const, override)); MOCK_METHOD(RtpCapabilities, GetRtpReceiverCapabilities, - (webrtc::MediaType), + (MediaType), (const, override)); MOCK_METHOD(scoped_refptr, CreateLocalMediaStream, @@ -56,7 +56,7 @@ class MockPeerConnectionFactoryInterface (override)); MOCK_METHOD(scoped_refptr, CreateAudioSource, - (const webrtc::AudioOptions&), + (const AudioOptions&), (override)); MOCK_METHOD(scoped_refptr, CreateVideoTrack, @@ -64,8 +64,7 @@ class MockPeerConnectionFactoryInterface (override)); MOCK_METHOD(scoped_refptr, CreateVideoTrack, - (webrtc::scoped_refptr, - absl::string_view), + (scoped_refptr, absl::string_view), (override)); MOCK_METHOD(scoped_refptr, CreateAudioTrack, diff --git a/api/test/mock_peerconnectioninterface.h b/api/test/mock_peerconnectioninterface.h index 1a75fa356c..575f4bc910 100644 --- a/api/test/mock_peerconnectioninterface.h +++ b/api/test/mock_peerconnectioninterface.h @@ -47,7 +47,7 @@ namespace webrtc { -class MockPeerConnectionInterface : public webrtc::PeerConnectionInterface { +class MockPeerConnectionInterface : public PeerConnectionInterface { public: static scoped_refptr Create() { return make_ref_counted(); @@ -66,35 +66,35 @@ class MockPeerConnectionInterface : public webrtc::PeerConnectionInterface { MOCK_METHOD(void, RemoveStream, (MediaStreamInterface*), (override)); MOCK_METHOD(RTCErrorOr>, AddTrack, - (webrtc::scoped_refptr, + (scoped_refptr, const std::vector&), (override)); MOCK_METHOD(RTCErrorOr>, AddTrack, - (webrtc::scoped_refptr, + (scoped_refptr, const std::vector&, const std::vector&), (override)); MOCK_METHOD(RTCError, RemoveTrackOrError, - (webrtc::scoped_refptr), + (scoped_refptr), (override)); MOCK_METHOD(RTCErrorOr>, AddTransceiver, - (webrtc::scoped_refptr), + (scoped_refptr), (override)); MOCK_METHOD(RTCErrorOr>, AddTransceiver, - (webrtc::scoped_refptr, + (scoped_refptr, const RtpTransceiverInit&), (override)); MOCK_METHOD(RTCErrorOr>, AddTransceiver, - (webrtc::MediaType), + (MediaType), (override)); MOCK_METHOD(RTCErrorOr>, AddTransceiver, - (webrtc::MediaType, const RtpTransceiverInit&), + (MediaType, const RtpTransceiverInit&), (override)); MOCK_METHOD(scoped_refptr, CreateSender, @@ -119,13 +119,13 @@ class MockPeerConnectionInterface : public webrtc::PeerConnectionInterface { MOCK_METHOD(void, GetStats, (RTCStatsCollectorCallback*), (override)); MOCK_METHOD(void, GetStats, - (webrtc::scoped_refptr, - webrtc::scoped_refptr), + (scoped_refptr, + scoped_refptr), (override)); MOCK_METHOD(void, GetStats, - (webrtc::scoped_refptr, - webrtc::scoped_refptr), + (scoped_refptr, + scoped_refptr), (override)); MOCK_METHOD(void, ClearStatsCache, (), (override)); MOCK_METHOD(scoped_refptr, @@ -180,7 +180,7 @@ class MockPeerConnectionInterface : public webrtc::PeerConnectionInterface { MOCK_METHOD(void, SetRemoteDescription, (std::unique_ptr, - webrtc::scoped_refptr), + scoped_refptr), (override)); MOCK_METHOD(bool, ShouldFireNegotiationNeededEvent, @@ -194,13 +194,10 @@ class MockPeerConnectionInterface : public webrtc::PeerConnectionInterface { SetConfiguration, (const PeerConnectionInterface::RTCConfiguration&), (override)); - MOCK_METHOD(bool, - AddIceCandidate, - (const IceCandidateInterface*), - (override)); + MOCK_METHOD(bool, AddIceCandidate, (const IceCandidate*), (override)); MOCK_METHOD(bool, RemoveIceCandidates, - (const std::vector&), + (const std::vector&), (override)); MOCK_METHOD(RTCError, SetBitrate, (const BitrateSettings&), (override)); MOCK_METHOD(void, @@ -223,7 +220,7 @@ class MockPeerConnectionInterface : public webrtc::PeerConnectionInterface { MOCK_METHOD(IceGatheringState, ice_gathering_state, (), (override)); MOCK_METHOD(void, AddAdaptationResource, - (webrtc::scoped_refptr), + (scoped_refptr), (override)); MOCK_METHOD(std::optional, can_trickle_ice_candidates, (), (override)); MOCK_METHOD(bool, @@ -248,7 +245,7 @@ class MockPeerConnectionInterface : public webrtc::PeerConnectionInterface { }; static_assert( - !std::is_abstract_v>, + !std::is_abstract_v>, ""); } // namespace webrtc diff --git a/api/test/mock_rtp_transceiver.h b/api/test/mock_rtp_transceiver.h index 6992c54bf3..1a55efa1e1 100644 --- a/api/test/mock_rtp_transceiver.h +++ b/api/test/mock_rtp_transceiver.h @@ -37,7 +37,7 @@ class MockRtpTransceiver : public RtpTransceiverInterface { return make_ref_counted(); } - MOCK_METHOD(webrtc::MediaType, media_type, (), (const, override)); + MOCK_METHOD(MediaType, media_type, (), (const, override)); MOCK_METHOD(std::optional, mid, (), (const, override)); MOCK_METHOD(scoped_refptr, sender, (), (const, override)); MOCK_METHOD(scoped_refptr, @@ -68,7 +68,7 @@ class MockRtpTransceiver : public RtpTransceiverInterface { MOCK_METHOD(void, Stop, (), (override)); MOCK_METHOD(RTCError, SetCodecPreferences, - (webrtc::ArrayView codecs), + (ArrayView codecs), (override)); MOCK_METHOD(std::vector, codec_preferences, @@ -82,11 +82,10 @@ class MockRtpTransceiver : public RtpTransceiverInterface { GetNegotiatedHeaderExtensions, (), (const, override)); - MOCK_METHOD( - webrtc::RTCError, - SetHeaderExtensionsToNegotiate, - (webrtc::ArrayView header_extensions), - (override)); + MOCK_METHOD(RTCError, + SetHeaderExtensionsToNegotiate, + (ArrayView header_extensions), + (override)); }; } // namespace webrtc diff --git a/api/test/mock_rtpreceiver.h b/api/test/mock_rtpreceiver.h index b0c34a20a0..ba375f891d 100644 --- a/api/test/mock_rtpreceiver.h +++ b/api/test/mock_rtpreceiver.h @@ -37,12 +37,12 @@ class MockRtpReceiver : public RefCountedObject { streams, (), (const, override)); - MOCK_METHOD(webrtc::MediaType, media_type, (), (const, override)); + MOCK_METHOD(MediaType, media_type, (), (const, override)); MOCK_METHOD(std::string, id, (), (const, override)); MOCK_METHOD(RtpParameters, GetParameters, (), (const, override)); MOCK_METHOD(bool, SetParameters, - (const webrtc::RtpParameters& parameters), + (const RtpParameters& parameters), (override)); MOCK_METHOD(void, SetObserver, (RtpReceiverObserverInterface*), (override)); MOCK_METHOD(void, @@ -52,9 +52,9 @@ class MockRtpReceiver : public RefCountedObject { MOCK_METHOD(std::vector, GetSources, (), (const, override)); MOCK_METHOD(void, SetFrameDecryptor, - (webrtc::scoped_refptr), + (scoped_refptr), (override)); - MOCK_METHOD(scoped_refptr, + MOCK_METHOD(scoped_refptr, GetFrameDecryptor, (), (const, override)); diff --git a/api/test/mock_rtpsender.h b/api/test/mock_rtpsender.h index da1078f356..59da4653ae 100644 --- a/api/test/mock_rtpsender.h +++ b/api/test/mock_rtpsender.h @@ -50,7 +50,7 @@ class MockRtpSender : public RtpSenderInterface { (), (const, override)); MOCK_METHOD(uint32_t, ssrc, (), (const, override)); - MOCK_METHOD(webrtc::MediaType, media_type, (), (const, override)); + MOCK_METHOD(MediaType, media_type, (), (const, override)); MOCK_METHOD(std::string, id, (), (const, override)); MOCK_METHOD(std::vector, stream_ids, (), (const, override)); MOCK_METHOD(void, SetStreams, (const std::vector&), (override)); @@ -70,7 +70,7 @@ class MockRtpSender : public RtpSenderInterface { (const, override)); MOCK_METHOD(void, SetFrameEncryptor, - (webrtc::scoped_refptr), + (scoped_refptr), (override)); MOCK_METHOD(scoped_refptr, GetFrameEncryptor, @@ -78,7 +78,7 @@ class MockRtpSender : public RtpSenderInterface { (const, override)); MOCK_METHOD(void, SetFrameTransformer, - (webrtc::scoped_refptr), + (scoped_refptr), (override)); MOCK_METHOD(void, SetEncoderSelector, @@ -87,7 +87,7 @@ class MockRtpSender : public RtpSenderInterface { MOCK_METHOD(void, SetObserver, (RtpSenderObserverInterface*), (override)); }; -static_assert(!std::is_abstract_v>, ""); +static_assert(!std::is_abstract_v>, ""); } // namespace webrtc #endif // API_TEST_MOCK_RTPSENDER_H_ diff --git a/api/test/mock_session_description_interface.h b/api/test/mock_session_description_interface.h index 549eded2f9..655055af8a 100644 --- a/api/test/mock_session_description_interface.h +++ b/api/test/mock_session_description_interface.h @@ -35,10 +35,11 @@ class MockSessionDescriptionInterface : public SessionDescriptionInterface { MOCK_METHOD(std::string, session_version, (), (const, override)); MOCK_METHOD(SdpType, GetType, (), (const, override)); MOCK_METHOD(std::string, type, (), (const, override)); - MOCK_METHOD(bool, AddCandidate, (const IceCandidateInterface*), (override)); + MOCK_METHOD(bool, AddCandidate, (const IceCandidate*), (override)); + MOCK_METHOD(bool, RemoveCandidate, (const IceCandidate*), (override)); MOCK_METHOD(size_t, RemoveCandidates, - (const std::vector&), + (const std::vector&), (override)); MOCK_METHOD(size_t, number_of_mediasections, (), (const, override)); MOCK_METHOD(const IceCandidateCollection*, diff --git a/api/test/mock_transformable_audio_frame.h b/api/test/mock_transformable_audio_frame.h index c92624a0ad..9de3c3fa29 100644 --- a/api/test/mock_transformable_audio_frame.h +++ b/api/test/mock_transformable_audio_frame.h @@ -28,7 +28,7 @@ class MockTransformableAudioFrame : public TransformableAudioFrameInterface { MockTransformableAudioFrame() : TransformableAudioFrameInterface(Passkey()) {} MOCK_METHOD(ArrayView, GetData, (), (const, override)); - MOCK_METHOD(void, SetData, (webrtc::ArrayView), (override)); + MOCK_METHOD(void, SetData, (ArrayView), (override)); MOCK_METHOD(void, SetRTPTimestamp, (uint32_t), (override)); MOCK_METHOD(uint8_t, GetPayloadType, (), (const, override)); MOCK_METHOD(bool, CanSetPayloadType, (), (const, override)); diff --git a/api/test/mock_transformable_frame.h b/api/test/mock_transformable_frame.h index e79834068d..252622abc4 100644 --- a/api/test/mock_transformable_frame.h +++ b/api/test/mock_transformable_frame.h @@ -30,14 +30,14 @@ class MockTransformableFrame : public TransformableFrameInterface { MockTransformableFrame() : TransformableFrameInterface(Passkey()) {} MOCK_METHOD(ArrayView, GetData, (), (const, override)); - MOCK_METHOD(void, SetData, (webrtc::ArrayView), (override)); + MOCK_METHOD(void, SetData, (ArrayView), (override)); MOCK_METHOD(uint8_t, GetPayloadType, (), (const, override)); MOCK_METHOD(bool, CanSetPayloadType, (), (const, override)); MOCK_METHOD(void, SetPayloadType, (uint8_t), (override)); MOCK_METHOD(uint32_t, GetSsrc, (), (const, override)); MOCK_METHOD(uint32_t, GetTimestamp, (), (const, override)); MOCK_METHOD(void, SetRTPTimestamp, (uint32_t), (override)); - MOCK_METHOD(std::optional, + MOCK_METHOD(std::optional, GetPresentationTimestamp, (), (const, override)); diff --git a/api/test/mock_transformable_video_frame.h b/api/test/mock_transformable_video_frame.h index 61207c2ee9..2f6fd63178 100644 --- a/api/test/mock_transformable_video_frame.h +++ b/api/test/mock_transformable_video_frame.h @@ -25,23 +25,16 @@ namespace webrtc { -class MockTransformableVideoFrame - : public webrtc::TransformableVideoFrameInterface { +class MockTransformableVideoFrame : public TransformableVideoFrameInterface { public: MockTransformableVideoFrame() : TransformableVideoFrameInterface(Passkey()) {} MOCK_METHOD(ArrayView, GetData, (), (const, override)); - MOCK_METHOD(void, - SetData, - (webrtc::ArrayView data), - (override)); + MOCK_METHOD(void, SetData, (ArrayView data), (override)); MOCK_METHOD(uint32_t, GetTimestamp, (), (const, override)); MOCK_METHOD(void, SetRTPTimestamp, (uint32_t), (override)); MOCK_METHOD(uint32_t, GetSsrc, (), (const, override)); MOCK_METHOD(bool, IsKeyFrame, (), (const, override)); - MOCK_METHOD(void, - SetMetadata, - (const webrtc::VideoFrameMetadata&), - (override)); + MOCK_METHOD(void, SetMetadata, (const VideoFrameMetadata&), (override)); MOCK_METHOD(uint8_t, GetPayloadType, (), (const, override)); MOCK_METHOD(bool, CanSetPayloadType, (), (const, override)); MOCK_METHOD(void, SetPayloadType, (uint8_t), (override)); diff --git a/api/test/mock_video_bitrate_allocator.h b/api/test/mock_video_bitrate_allocator.h index de06d93e3f..d933cf7727 100644 --- a/api/test/mock_video_bitrate_allocator.h +++ b/api/test/mock_video_bitrate_allocator.h @@ -17,7 +17,7 @@ namespace webrtc { -class MockVideoBitrateAllocator : public webrtc::VideoBitrateAllocator { +class MockVideoBitrateAllocator : public VideoBitrateAllocator { MOCK_METHOD(VideoBitrateAllocation, Allocate, (VideoBitrateAllocationParameters parameters), diff --git a/api/test/mock_video_encoder_factory.h b/api/test/mock_video_encoder_factory.h index beeba29d8a..e1a8210c10 100644 --- a/api/test/mock_video_encoder_factory.h +++ b/api/test/mock_video_encoder_factory.h @@ -22,7 +22,7 @@ namespace webrtc { -class MockVideoEncoderFactory : public webrtc::VideoEncoderFactory { +class MockVideoEncoderFactory : public VideoEncoderFactory { public: ~MockVideoEncoderFactory() override { Die(); } diff --git a/api/test/mock_video_track.h b/api/test/mock_video_track.h index 3bf083dd6c..87fea70d7e 100644 --- a/api/test/mock_video_track.h +++ b/api/test/mock_video_track.h @@ -23,7 +23,7 @@ namespace webrtc { -class MockVideoTrack : public RefCountedObject { +class MockVideoTrack : public RefCountedObject { public: static scoped_refptr Create() { return scoped_refptr(new MockVideoTrack()); @@ -49,14 +49,14 @@ class MockVideoTrack : public RefCountedObject { // VideoSourceInterface MOCK_METHOD(void, AddOrUpdateSink, - (webrtc::VideoSinkInterface * sink, - const webrtc::VideoSinkWants& wants), + (VideoSinkInterface * sink, + const VideoSinkWants& wants), (override)); // RemoveSink must guarantee that at the time the method returns, // there is no current and no future calls to VideoSinkInterface::OnFrame. MOCK_METHOD(void, RemoveSink, - (webrtc::VideoSinkInterface * sink), + (VideoSinkInterface * sink), (override)); // VideoTrackInterface diff --git a/api/test/network_emulation/schedulable_network_node_builder.h b/api/test/network_emulation/schedulable_network_node_builder.h index 9ac6547a32..ee15215e40 100644 --- a/api/test/network_emulation/schedulable_network_node_builder.h +++ b/api/test/network_emulation/schedulable_network_node_builder.h @@ -23,25 +23,24 @@ namespace webrtc { class SchedulableNetworkNodeBuilder { public: SchedulableNetworkNodeBuilder( - webrtc::NetworkEmulationManager& net, + NetworkEmulationManager& net, network_behaviour::NetworkConfigSchedule schedule); // set_start_condition allows a test to control when the schedule start. // `start_condition` is invoked every time a packet is enqueued on the network // until the first time `start_condition` returns true. Until then, the first // NetworkConfigScheduleItem is used. There is no guarantee on which // thread/task queue that will be used. - void set_start_condition( - absl::AnyInvocable start_condition); + void set_start_condition(absl::AnyInvocable start_condition); // If no random seed is provided, one will be created. // The random seed is required for loss rate and to delay standard deviation. - webrtc::EmulatedNetworkNode* Build( + EmulatedNetworkNode* Build( std::optional random_seed = std::nullopt); private: - webrtc::NetworkEmulationManager& net_; + NetworkEmulationManager& net_; network_behaviour::NetworkConfigSchedule schedule_; - absl::AnyInvocable start_condition_; + absl::AnyInvocable start_condition_; }; } // namespace webrtc diff --git a/api/test/pclf/BUILD.gn b/api/test/pclf/BUILD.gn index 3082bdd7d3..7c9a0de483 100644 --- a/api/test/pclf/BUILD.gn +++ b/api/test/pclf/BUILD.gn @@ -32,7 +32,7 @@ rtc_library("media_configuration") { ] } -rtc_library("media_quality_test_params") { +rtc_source_set("media_quality_test_params") { visibility = [ "*" ] testonly = true sources = [ "media_quality_test_params.h" ] @@ -41,7 +41,7 @@ rtc_library("media_quality_test_params") { ":media_configuration", "../..:async_dns_resolver", "../..:fec_controller_api", - "../..:field_trials_view", + "../..:field_trials", "../..:ice_transport_interface", "../..:libjingle_peerconnection_api", "../..:scoped_refptr", @@ -77,7 +77,7 @@ rtc_library("peer_configurer") { "../..:async_dns_resolver", "../..:create_peer_connection_quality_test_frame_generator", "../..:fec_controller_api", - "../..:field_trials_view", + "../..:field_trials", "../..:frame_generator_api", "../..:ice_transport_interface", "../..:libjingle_peerconnection_api", @@ -87,6 +87,7 @@ rtc_library("peer_configurer") { "../../../rtc_base:checks", "../../../rtc_base:rtc_certificate_generator", "../../../rtc_base:ssl", + "../../../test:create_test_field_trials", "../../audio:audio_mixer_api", "../../audio:audio_processing", "../../audio_codecs:audio_codecs_api", diff --git a/api/test/pclf/media_quality_test_params.h b/api/test/pclf/media_quality_test_params.h index 7305aa3fad..eb5d9e6109 100644 --- a/api/test/pclf/media_quality_test_params.h +++ b/api/test/pclf/media_quality_test_params.h @@ -24,7 +24,7 @@ #include "api/audio_codecs/audio_decoder_factory.h" #include "api/audio_codecs/audio_encoder_factory.h" #include "api/fec_controller.h" -#include "api/field_trials_view.h" +#include "api/field_trials.h" #include "api/ice_transport_interface.h" #include "api/neteq/neteq_factory.h" #include "api/peer_connection_interface.h" @@ -69,7 +69,7 @@ struct PeerConnectionFactoryComponents { scoped_refptr audio_encoder_factory; scoped_refptr audio_decoder_factory; - std::unique_ptr trials; + std::unique_ptr field_trials; std::unique_ptr audio_processing; scoped_refptr audio_mixer; @@ -177,9 +177,6 @@ struct RunParams { // it will be shut downed. TimeDelta run_duration; - // If set to true peers will be able to use Flex FEC, otherwise they won't - // be able to negotiate it even if it's enabled on per peer level. - bool enable_flex_fec_support = false; // If true will set conference mode in SDP media section for all video // tracks for all peers. bool use_conference_mode = false; diff --git a/api/test/pclf/peer_configurer.cc b/api/test/pclf/peer_configurer.cc index 9077be94bf..668f29af73 100644 --- a/api/test/pclf/peer_configurer.cc +++ b/api/test/pclf/peer_configurer.cc @@ -24,7 +24,7 @@ #include "api/audio_codecs/audio_decoder_factory.h" #include "api/audio_codecs/audio_encoder_factory.h" #include "api/fec_controller.h" -#include "api/field_trials_view.h" +#include "api/field_trials.h" #include "api/ice_transport_interface.h" #include "api/neteq/neteq_factory.h" #include "api/peer_connection_interface.h" @@ -43,6 +43,7 @@ #include "rtc_base/checks.h" #include "rtc_base/rtc_certificate_generator.h" #include "rtc_base/ssl_certificate.h" +#include "test/create_test_field_trials.h" namespace webrtc { namespace webrtc_pc_e2e { @@ -53,7 +54,10 @@ PeerConfigurer::PeerConfigurer(PeerNetworkDependencies& network) network.ReleaseNetworkManager(), network.socket_factory())), params_(std::make_unique()), - configurable_params_(std::make_unique()) {} + configurable_params_(std::make_unique()) { + components_->pcf_dependencies->field_trials = + std::make_unique(CreateTestFieldTrials()); +} PeerConfigurer* PeerConfigurer::SetName(absl::string_view name) { params_->name = std::string(name); @@ -169,6 +173,10 @@ PeerConfigurer* PeerConfigurer::SetUseUlpFEC(bool value) { } PeerConfigurer* PeerConfigurer::SetUseFlexFEC(bool value) { params_->use_flex_fec = value; + absl::string_view group = value ? "Enabled" : "Disabled"; + FieldTrials& field_trials = GetFieldTrials(); + field_trials.Set("WebRTC-FlexFEC-03-Advertised", group); + field_trials.Set("WebRTC-FlexFEC-03", group); return this; } PeerConfigurer* PeerConfigurer::SetVideoEncoderBitrateMultiplier( @@ -232,12 +240,6 @@ PeerConfigurer* PeerConfigurer::SetIceTransportFactory( return this; } -PeerConfigurer* PeerConfigurer::SetFieldTrials( - std::unique_ptr field_trials) { - components_->pcf_dependencies->trials = std::move(field_trials); - return this; -} - PeerConfigurer* PeerConfigurer::SetPortAllocatorExtraFlags( uint32_t extra_flags) { params_->port_allocator_flags = diff --git a/api/test/pclf/peer_configurer.h b/api/test/pclf/peer_configurer.h index 9fab752fe7..821962dd17 100644 --- a/api/test/pclf/peer_configurer.h +++ b/api/test/pclf/peer_configurer.h @@ -23,7 +23,7 @@ #include "api/audio_codecs/audio_decoder_factory.h" #include "api/audio_codecs/audio_encoder_factory.h" #include "api/fec_controller.h" -#include "api/field_trials_view.h" +#include "api/field_trials.h" #include "api/ice_transport_interface.h" #include "api/neteq/neteq_factory.h" #include "api/peer_connection_interface.h" @@ -176,8 +176,12 @@ class PeerConfigurer { // Set bitrate parameters on PeerConnection. This constraints will be // applied to all summed RTP streams for this peer. PeerConfigurer* SetBitrateSettings(BitrateSettings bitrate_settings); - // Set field trials used for this PeerConnection. - PeerConfigurer* SetFieldTrials(std::unique_ptr field_trials); + + // Appends field trials for this PeerConnection. + PeerConfigurer* AddFieldTrials(const FieldTrials& field_trials) { + GetFieldTrials().Merge(field_trials); + return this; + } // Returns InjectableComponents and transfer ownership to the caller. // Can be called once. @@ -207,6 +211,10 @@ class PeerConfigurer { std::vector* video_sources() { return &video_sources_; } private: + FieldTrials& GetFieldTrials() { + return *components_->pcf_dependencies->field_trials; + } + std::unique_ptr components_; std::unique_ptr params_; std::unique_ptr configurable_params_; diff --git a/api/test/simulated_network.h b/api/test/simulated_network.h index 6f31c60c97..174fc0bb2b 100644 --- a/api/test/simulated_network.h +++ b/api/test/simulated_network.h @@ -28,23 +28,21 @@ struct PacketInFlightInfo { PacketInFlightInfo(size_t size, int64_t send_time_us, uint64_t packet_id, - webrtc::EcnMarking ecn) + EcnMarking ecn) : size(size), send_time_us(send_time_us), packet_id(packet_id), ecn(ecn) {} PacketInFlightInfo(size_t size, int64_t send_time_us, uint64_t packet_id) - : PacketInFlightInfo(size, - send_time_us, - packet_id, - webrtc::EcnMarking::kNotEct) {} + : PacketInFlightInfo(size, send_time_us, packet_id, EcnMarking::kNotEct) { + } size_t size; int64_t send_time_us; // Unique identifier for the packet in relation to other packets in flight. uint64_t packet_id; - webrtc::EcnMarking ecn; + EcnMarking ecn; }; struct PacketDeliveryInfo { @@ -61,7 +59,7 @@ struct PacketDeliveryInfo { int64_t receive_time_us; uint64_t packet_id; - webrtc::EcnMarking ecn; + EcnMarking ecn; }; // BuiltInNetworkBehaviorConfig is a built-in network behavior configuration diff --git a/api/test/test_dependency_factory.cc b/api/test/test_dependency_factory.cc deleted file mode 100644 index 4ed18d4a71..0000000000 --- a/api/test/test_dependency_factory.cc +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) 2018 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/test/test_dependency_factory.h" - -#include -#include - -#include "api/test/video_quality_test_fixture.h" -#include "rtc_base/checks.h" -#include "rtc_base/platform_thread_types.h" - -namespace webrtc { - -namespace { -// This checks everything in this file gets called on the same thread. It's -// static because it needs to look at the static methods too. -bool IsValidTestDependencyFactoryThread() { - const PlatformThreadRef main_thread = CurrentThreadRef(); - return IsThreadRefEqual(main_thread, CurrentThreadRef()); -} -} // namespace - -std::unique_ptr TestDependencyFactory::instance_ = - nullptr; - -const TestDependencyFactory& TestDependencyFactory::GetInstance() { - RTC_DCHECK(IsValidTestDependencyFactoryThread()); - if (instance_ == nullptr) { - instance_ = std::make_unique(); - } - return *instance_; -} - -void TestDependencyFactory::SetInstance( - std::unique_ptr instance) { - RTC_DCHECK(IsValidTestDependencyFactoryThread()); - RTC_CHECK(instance_ == nullptr); - instance_ = std::move(instance); -} - -std::unique_ptr -TestDependencyFactory::CreateComponents() const { - RTC_DCHECK(IsValidTestDependencyFactoryThread()); - return nullptr; -} - -} // namespace webrtc diff --git a/api/test/test_dependency_factory.h b/api/test/test_dependency_factory.h deleted file mode 100644 index 29f00b8070..0000000000 --- a/api/test/test_dependency_factory.h +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2018 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_TEST_TEST_DEPENDENCY_FACTORY_H_ -#define API_TEST_TEST_DEPENDENCY_FACTORY_H_ - -#include - -#include "api/test/video_quality_test_fixture.h" - -namespace webrtc { - -// Override this class if to inject custom components into WebRTC tests. -// Not all WebRTC tests get their components from here, so you need to make -// sure the tests you want actually use this class. -// -// This class is not thread safe and you need to make call calls from the same -// (test main) thread. -class TestDependencyFactory { - public: - virtual ~TestDependencyFactory() = default; - - // The singleton MUST be stateless since tests execute in any order. It must - // be set before tests start executing. - static const TestDependencyFactory& GetInstance(); - static void SetInstance(std::unique_ptr instance); - - // Returns the component a test should use. Returning nullptr means that the - // test is free to use whatever defaults it wants. The injection components - // themselves can be mutable, but we need to make new ones for every test that - // executes so state doesn't spread between tests. - virtual std::unique_ptr - CreateComponents() const; - - private: - static std::unique_ptr instance_; -}; - -} // namespace webrtc - -#endif // API_TEST_TEST_DEPENDENCY_FACTORY_H_ diff --git a/api/test/time_controller.h b/api/test/time_controller.h index 8d9cb7c28a..86669d53df 100644 --- a/api/test/time_controller.h +++ b/api/test/time_controller.h @@ -39,14 +39,14 @@ class TimeController { // is destroyed. std::unique_ptr CreateTaskQueueFactory(); - // Creates an webrtc::Thread instance. If `socket_server` is nullptr, a + // Creates an Thread instance. If `socket_server` is nullptr, a // default noop socket server is created. Returned thread is not null and // started. virtual std::unique_ptr CreateThread( const std::string& name, std::unique_ptr socket_server = nullptr) = 0; - // Creates an webrtc::Thread instance that ensure that it's set as the current + // Creates an Thread instance that ensure that it's set as the current // thread. virtual Thread* GetMainThread() = 0; // Allow task queues and process threads created by this instance to execute diff --git a/api/test/video_quality_test_fixture.h b/api/test/video_quality_test_fixture.h index 763dd7ddf8..c0454a60bf 100644 --- a/api/test/video_quality_test_fixture.h +++ b/api/test/video_quality_test_fixture.h @@ -117,15 +117,13 @@ class VideoQualityTestFixtureInterface { // Contains objects, that will be injected on different layers of test // framework to override the behavior of system parts. struct InjectionComponents { - InjectionComponents(); - ~InjectionComponents(); - // Simulations of sender and receiver networks. They must either both be // null (in which case `config` from Params is used), or both be non-null // (in which case `config` from Params must be nullopt). std::unique_ptr sender_network; std::unique_ptr receiver_network; + std::string field_trials; std::unique_ptr fec_controller_factory; std::unique_ptr video_encoder_factory; std::unique_ptr video_decoder_factory; @@ -140,7 +138,7 @@ class VideoQualityTestFixtureInterface { virtual void RunWithAnalyzer(const Params& params) = 0; virtual void RunWithRenderers(const Params& params) = 0; - virtual const std::map& payload_type_map() = 0; + virtual const std::map& payload_type_map() = 0; }; } // namespace webrtc diff --git a/api/test/videocodec_test_fixture.h b/api/test/videocodec_test_fixture.h index 0e35ec354f..89e8f0ec47 100644 --- a/api/test/videocodec_test_fixture.h +++ b/api/test/videocodec_test_fixture.h @@ -16,6 +16,7 @@ #include #include +#include "api/field_trials.h" #include "api/test/videocodec_test_stats.h" #include "api/video/encoded_image.h" #include "api/video/video_codec_type.h" @@ -91,6 +92,8 @@ class VideoCodecTestFixture { // Name of this config, to be used for accounting by the test runner. std::string test_name; + FieldTrials field_trials; + // Plain name of YUV file to process without file extension. std::string filename; // Dimensions of test clip. Falls back to (codec_settings.width/height) if diff --git a/api/transport/goog_cc_factory.cc b/api/transport/goog_cc_factory.cc index 11dd3686df..7d2c079709 100644 --- a/api/transport/goog_cc_factory.cc +++ b/api/transport/goog_cc_factory.cc @@ -27,7 +27,6 @@ GoogCcNetworkControllerFactory::GoogCcNetworkControllerFactory( std::unique_ptr GoogCcNetworkControllerFactory::Create(NetworkControllerConfig config) { GoogCcConfig goog_cc_config; - goog_cc_config.feedback_only = factory_config_.feedback_only; if (factory_config_.network_state_estimator_factory) { goog_cc_config.network_state_estimator = factory_config_.network_state_estimator_factory->Create( diff --git a/api/transport/goog_cc_factory.h b/api/transport/goog_cc_factory.h index 56947306bc..fd3f6e30a1 100644 --- a/api/transport/goog_cc_factory.h +++ b/api/transport/goog_cc_factory.h @@ -24,7 +24,6 @@ struct GoogCcFactoryConfig { std::unique_ptr network_state_estimator_factory; NetworkStatePredictorFactoryInterface* network_state_predictor_factory = nullptr; - bool feedback_only = false; }; class RTC_EXPORT GoogCcNetworkControllerFactory diff --git a/api/transport/rtp/BUILD.gn b/api/transport/rtp/BUILD.gn index 9982346e12..9facb7afa8 100644 --- a/api/transport/rtp/BUILD.gn +++ b/api/transport/rtp/BUILD.gn @@ -16,6 +16,7 @@ rtc_source_set("rtp_source") { "../../../api/units:time_delta", "../../../api/units:timestamp", "../../../rtc_base:checks", + "//third_party/abseil-cpp/absl/strings:str_format", ] } diff --git a/api/transport/rtp/DEPS b/api/transport/rtp/DEPS new file mode 100644 index 0000000000..97daa2bb67 --- /dev/null +++ b/api/transport/rtp/DEPS @@ -0,0 +1,5 @@ +specific_include_rules = { + "rtp_source\.h": [ + "+absl/strings/str_format.h", + ], +} diff --git a/api/transport/rtp/rtp_source.h b/api/transport/rtp/rtp_source.h index 4732044be2..3f73fdc271 100644 --- a/api/transport/rtp/rtp_source.h +++ b/api/transport/rtp/rtp_source.h @@ -15,6 +15,7 @@ #include +#include "absl/strings/str_format.h" #include "api/rtp_headers.h" #include "api/units/time_delta.h" #include "api/units/timestamp.h" @@ -84,6 +85,13 @@ class RtpSource { return extensions_.local_capture_clock_offset; } + template + friend void AbslStringify(Sink& sink, const RtpSource& source) { + absl::Format(&sink, "{ source_type: %s, source_id: %u }", + source.source_type() == RtpSourceType::CSRC ? "CSRC" : "SSRC", + source.source_id()); + } + bool operator==(const RtpSource& o) const { return timestamp_ == o.timestamp() && source_id_ == o.source_id() && source_type_ == o.source_type() && diff --git a/api/transport/sctp_transport_factory_interface.h b/api/transport/sctp_transport_factory_interface.h index d624994184..9d41596110 100644 --- a/api/transport/sctp_transport_factory_interface.h +++ b/api/transport/sctp_transport_factory_interface.h @@ -24,7 +24,7 @@ class SctpTransportInternal; // Factory class which can be used to allow fake SctpTransports to be injected // for testing. An application is not intended to implement this interface nor -// 'webrtc::SctpTransportInternal' because SctpTransportInternal is not +// 'SctpTransportInternal' because SctpTransportInternal is not // guaranteed to remain stable in future WebRTC versions. class SctpTransportFactoryInterface { public: diff --git a/api/video/encoded_frame.h b/api/video/encoded_frame.h index 18c426bb1f..49480f108b 100644 --- a/api/video/encoded_frame.h +++ b/api/video/encoded_frame.h @@ -41,7 +41,7 @@ class EncodedFrame : public EncodedImage { virtual int64_t ReceivedTime() const { return -1; } // Returns a Timestamp from `ReceivedTime`, or nullopt if there is no receive // time. - std::optional ReceivedTimestamp() const; + std::optional ReceivedTimestamp() const; // When this frame should be rendered. // TODO(bugs.webrtc.org/13756): Use Timestamp instead of int. @@ -50,7 +50,7 @@ class EncodedFrame : public EncodedImage { int64_t RenderTimeMs() const { return _renderTimeMs; } // Returns a Timestamp from `RenderTime`, or nullopt if there is no // render time. - std::optional RenderTimestamp() const; + std::optional RenderTimestamp() const; // This information is currently needed by the timing calculation class. // TODO(philipel): Remove this function when a new timing class has diff --git a/api/video/encoded_image.h b/api/video/encoded_image.h index ea48495054..34df30f395 100644 --- a/api/video/encoded_image.h +++ b/api/video/encoded_image.h @@ -220,11 +220,9 @@ class RTC_EXPORT EncodedImage { is_steady_state_refresh_frame_ = refresh_frame; } - webrtc::VideoFrameType FrameType() const { return _frameType; } + VideoFrameType FrameType() const { return _frameType; } - void SetFrameType(webrtc::VideoFrameType frame_type) { - _frameType = frame_type; - } + void SetFrameType(VideoFrameType frame_type) { _frameType = frame_type; } VideoContentType contentType() const { return content_type_; } VideoRotation rotation() const { return rotation_; } @@ -279,7 +277,7 @@ class RTC_EXPORT EncodedImage { std::map spatial_layer_frame_size_bytes_; std::optional color_space_; // This field is meant for media quality testing purpose only. When enabled it - // carries the webrtc::VideoFrame id field from the sender to the receiver. + // carries the VideoFrame id field from the sender to the receiver. std::optional video_frame_tracking_id_; // Information about packets used to assemble this video frame. This is needed // by `SourceTracker` when the frame is delivered to the RTCRtpReceiver's diff --git a/api/video/nv12_buffer.cc b/api/video/nv12_buffer.cc index 946b54fd39..270dbde00c 100644 --- a/api/video/nv12_buffer.cc +++ b/api/video/nv12_buffer.cc @@ -29,7 +29,7 @@ namespace webrtc { namespace { -static const int kBufferAlignment = 64; +const int kBufferAlignment = 64; int NV12DataSize(int width, int height, int stride_y, int stride_uv) { CheckValidDimensions(width, height, stride_y, stride_uv, stride_uv); diff --git a/api/video/recordable_encoded_frame.h b/api/video/recordable_encoded_frame.h index aa55e9480a..ff771a0024 100644 --- a/api/video/recordable_encoded_frame.h +++ b/api/video/recordable_encoded_frame.h @@ -42,11 +42,11 @@ class RecordableEncodedFrame { // Optionally returns the colorspace of the encoded frame. This can differ // from the eventually decoded frame's colorspace. - virtual std::optional color_space() const = 0; + virtual std::optional color_space() const = 0; // Optionally returns the rotation of the encoded frame. This is limited to // {0,90,180,270} degrees. - virtual std::optional video_rotation() const = 0; + virtual std::optional video_rotation() const = 0; // Returns the codec of the encoded frame virtual VideoCodecType codec() const = 0; diff --git a/api/video/test/mock_recordable_encoded_frame.h b/api/video/test/mock_recordable_encoded_frame.h index d99c0ddece..f8ee6c3a12 100644 --- a/api/video/test/mock_recordable_encoded_frame.h +++ b/api/video/test/mock_recordable_encoded_frame.h @@ -29,11 +29,8 @@ class MockRecordableEncodedFrame : public RecordableEncodedFrame { encoded_buffer, (), (const, override)); - MOCK_METHOD(std::optional, - color_space, - (), - (const, override)); - MOCK_METHOD(std::optional, + MOCK_METHOD(std::optional, color_space, (), (const, override)); + MOCK_METHOD(std::optional, video_rotation, (), (const, override)); diff --git a/api/video/video_bitrate_allocator.cc b/api/video/video_bitrate_allocator.cc index 128a34ac36..566ee51be9 100644 --- a/api/video/video_bitrate_allocator.cc +++ b/api/video/video_bitrate_allocator.cc @@ -21,23 +21,12 @@ VideoBitrateAllocationParameters::VideoBitrateAllocationParameters( uint32_t total_bitrate_bps, uint32_t framerate) : total_bitrate(DataRate::BitsPerSec(total_bitrate_bps)), - stable_bitrate(DataRate::BitsPerSec(total_bitrate_bps)), framerate(static_cast(framerate)) {} VideoBitrateAllocationParameters::VideoBitrateAllocationParameters( DataRate total_bitrate, double framerate) - : total_bitrate(total_bitrate), - stable_bitrate(total_bitrate), - framerate(framerate) {} - -VideoBitrateAllocationParameters::VideoBitrateAllocationParameters( - DataRate total_bitrate, - DataRate stable_bitrate, - double framerate) - : total_bitrate(total_bitrate), - stable_bitrate(stable_bitrate), - framerate(framerate) {} + : total_bitrate(total_bitrate), framerate(framerate) {} VideoBitrateAllocationParameters::~VideoBitrateAllocationParameters() = default; @@ -45,7 +34,6 @@ VideoBitrateAllocation VideoBitrateAllocator::GetAllocation( uint32_t total_bitrate_bps, uint32_t framerate) { return Allocate({DataRate::BitsPerSec(total_bitrate_bps), - DataRate::BitsPerSec(total_bitrate_bps), static_cast(framerate)}); } diff --git a/api/video/video_bitrate_allocator.h b/api/video/video_bitrate_allocator.h index 61d74ae490..c877316ff6 100644 --- a/api/video/video_bitrate_allocator.h +++ b/api/video/video_bitrate_allocator.h @@ -22,13 +22,9 @@ struct VideoBitrateAllocationParameters { VideoBitrateAllocationParameters(uint32_t total_bitrate_bps, uint32_t framerate); VideoBitrateAllocationParameters(DataRate total_bitrate, double framerate); - VideoBitrateAllocationParameters(DataRate total_bitrate, - DataRate stable_bitrate, - double framerate); ~VideoBitrateAllocationParameters(); DataRate total_bitrate; - DataRate stable_bitrate; double framerate; }; diff --git a/api/video/video_content_type.cc b/api/video/video_content_type.cc index 75beb5c935..8b96080936 100644 --- a/api/video/video_content_type.cc +++ b/api/video/video_content_type.cc @@ -18,9 +18,8 @@ namespace webrtc { namespace videocontenttypehelpers { namespace { -static constexpr uint8_t kScreenshareBitsSize = 1; -static constexpr uint8_t kScreenshareBitsMask = - (1u << kScreenshareBitsSize) - 1; +constexpr uint8_t kScreenshareBitsSize = 1; +constexpr uint8_t kScreenshareBitsMask = (1u << kScreenshareBitsSize) - 1; } // namespace bool IsScreenshare(const VideoContentType& content_type) { diff --git a/api/video/video_frame.h b/api/video/video_frame.h index f7616d3a02..e39d06f1ef 100644 --- a/api/video/video_frame.h +++ b/api/video/video_frame.h @@ -127,7 +127,7 @@ class RTC_EXPORT VideoFrame { private: uint16_t id_ = kNotSetId; - scoped_refptr video_frame_buffer_; + scoped_refptr video_frame_buffer_; int64_t timestamp_us_ = 0; std::optional presentation_timestamp_; std::optional reference_time_; @@ -142,7 +142,7 @@ class RTC_EXPORT VideoFrame { // To be deprecated. Migrate all use to Builder. VideoFrame(const scoped_refptr& buffer, - webrtc::VideoRotation rotation, + VideoRotation rotation, int64_t timestamp_us); VideoFrame(const scoped_refptr& buffer, uint32_t timestamp_rtp, @@ -173,7 +173,7 @@ class RTC_EXPORT VideoFrame { uint16_t id() const { return id_; } void set_id(uint16_t id) { id_ = id; } - // System monotonic clock, same timebase as webrtc::TimeMicros(). + // System monotonic clock, same timebase as TimeMicros(). int64_t timestamp_us() const { return timestamp_us_; } void set_timestamp_us(int64_t timestamp_us) { timestamp_us_ = timestamp_us; } @@ -241,7 +241,7 @@ class RTC_EXPORT VideoFrame { // Return the underlying buffer. Never nullptr for a properly // initialized VideoFrame. - scoped_refptr video_frame_buffer() const; + scoped_refptr video_frame_buffer() const; void set_video_frame_buffer(const scoped_refptr& buffer); @@ -299,7 +299,7 @@ class RTC_EXPORT VideoFrame { uint16_t id_; // An opaque reference counted handle that stores the pixel data. - scoped_refptr video_frame_buffer_; + scoped_refptr video_frame_buffer_; uint32_t timestamp_rtp_; int64_t ntp_time_ms_; int64_t timestamp_us_; diff --git a/api/video/video_frame_buffer.h b/api/video/video_frame_buffer.h index e5df90075f..1fbaa53a55 100644 --- a/api/video/video_frame_buffer.h +++ b/api/video/video_frame_buffer.h @@ -44,8 +44,8 @@ class NV12BufferInterface; // correct subclass in custom video sinks. The purpose of this is to improve // performance by providing an optimized path without intermediate conversions. // Frame metadata such as rotation and timestamp are stored in -// webrtc::VideoFrame, and not here. -class RTC_EXPORT VideoFrameBuffer : public webrtc::RefCountInterface { +// VideoFrame, and not here. +class RTC_EXPORT VideoFrameBuffer : public RefCountInterface { public: // New frame buffer types will be added conservatively when there is an // opportunity to optimize the path between some pair of video source and diff --git a/api/video/video_source_interface.h b/api/video/video_source_interface.h index b6f418218c..e6f94c67e5 100644 --- a/api/video/video_source_interface.h +++ b/api/video/video_source_interface.h @@ -67,19 +67,19 @@ struct RTC_EXPORT VideoSinkWants { // resolutions per frame. // // The sink is always configured to consume a subset of the - // webrtc::VideoFrame's resolution. In the case of encoding, we usually encode - // at webrtc::VideoFrame's resolution but this may not always be the case due + // VideoFrame's resolution. In the case of encoding, we usually encode + // at VideoFrame's resolution but this may not always be the case due // to scaleResolutionDownBy or turning off simulcast or SVC layers. // // For example, we may capture at 720p and due to adaptation (e.g. applying - // `max_pixel_count` constraints) create webrtc::VideoFrames of size 480p, but + // `max_pixel_count` constraints) create VideoFrames of size 480p, but // if we do scaleResolutionDownBy:2 then the only resolution we end up - // encoding is 240p. In this case we still need to provide webrtc::VideoFrames + // encoding is 240p. In this case we still need to provide VideoFrames // of size 480p but we can optimize internal buffers for 240p, avoiding // downsampling to 480p if possible. // // Note that the `resolutions` can change while frames are in flight and - // should only be used as a hint when constructing the webrtc::VideoFrame. + // should only be used as a hint when constructing the VideoFrame. std::vector resolutions; // This is the resolution requested by the user using RtpEncodingParameters, diff --git a/api/video_codecs/h264_profile_level_id.cc b/api/video_codecs/h264_profile_level_id.cc index 4dafda078f..e410fc22f2 100644 --- a/api/video_codecs/h264_profile_level_id.cc +++ b/api/video_codecs/h264_profile_level_id.cc @@ -80,7 +80,7 @@ struct LevelConstraint { }; // This is from ITU-T H.264 (02/2016) Table A-1 – Level limits. -static constexpr LevelConstraint kLevelConstraints[] = { +constexpr LevelConstraint kLevelConstraints[] = { {1485, 99, H264Level::kLevel1}, {1485, 99, H264Level::kLevel1_b}, {3000, 396, H264Level::kLevel1_1}, diff --git a/api/video_codecs/h265_profile_tier_level.cc b/api/video_codecs/h265_profile_tier_level.cc index 306effa96a..4ec1c8070f 100644 --- a/api/video_codecs/h265_profile_tier_level.cc +++ b/api/video_codecs/h265_profile_tier_level.cc @@ -28,7 +28,7 @@ const char kH265FmtpLevel[] = "level-id"; // Used to align frame width and height for luma picture size calculation. // Use the maximum value allowed by spec to get upper bound of luma picture // size for given resolution. -static constexpr int kMinCbSizeYMax = 64; +constexpr int kMinCbSizeYMax = 64; struct LevelConstraint { const int max_luma_picture_size; @@ -45,7 +45,7 @@ struct LevelConstraint { // max_luma_picture_size is 36864, so pic_width_in_luma_samples <= sqrt(36864 * // 8) = 543.06. The largest integer that is multiple of 8 and less than 543.06 // is 536. -static constexpr LevelConstraint kLevelConstraints[] = { +constexpr LevelConstraint kLevelConstraints[] = { {36864, 552960, 536, H265Level::kLevel1}, {122880, 3686400, 984, H265Level::kLevel2}, {245760, 7372800, 1400, H265Level::kLevel2_1}, diff --git a/api/video_codecs/libaom_av1_encoder_factory_test.cc b/api/video_codecs/libaom_av1_encoder_factory_test.cc index 62d74424e5..a3b3680711 100644 --- a/api/video_codecs/libaom_av1_encoder_factory_test.cc +++ b/api/video_codecs/libaom_av1_encoder_factory_test.cc @@ -86,7 +86,7 @@ class Av1Decoder : public DecodedImageCallback { } } - ~Av1Decoder() { + ~Av1Decoder() override { if (raw_out_file_) { fclose(raw_out_file_); } @@ -261,7 +261,7 @@ double Psnr(const scoped_refptr& ref_buffer, return I420PSNR(*ref_buffer, *decoded_frame.video_frame_buffer()->ToI420()); } -static constexpr VideoEncoderFactoryInterface::StaticEncoderSettings +constexpr VideoEncoderFactoryInterface::StaticEncoderSettings kCbrEncoderSettings{ .max_encode_dimensions = {.width = 1920, .height = 1080}, .encoding_format = {.sub_sampling = EncodingFormat::SubSampling::k420, @@ -273,7 +273,7 @@ static constexpr VideoEncoderFactoryInterface::StaticEncoderSettings .max_number_of_threads = 1, }; -static constexpr VideoEncoderFactoryInterface::StaticEncoderSettings +constexpr VideoEncoderFactoryInterface::StaticEncoderSettings kCqpEncoderSettings{ .max_encode_dimensions = {.width = 1920, .height = 1080}, .encoding_format = {.sub_sampling = EncodingFormat::SubSampling::k420, @@ -282,8 +282,8 @@ static constexpr VideoEncoderFactoryInterface::StaticEncoderSettings .max_number_of_threads = 1, }; -static constexpr Cbr kCbr{.duration = TimeDelta::Millis(100), - .target_bitrate = DataRate::KilobitsPerSec(1000)}; +constexpr Cbr kCbr{.duration = TimeDelta::Millis(100), + .target_bitrate = DataRate::KilobitsPerSec(1000)}; TEST(LibaomAv1EncoderFactory, CodecName) { EXPECT_THAT(LibaomAv1EncoderFactory().CodecName(), Eq("AV1")); diff --git a/api/video_codecs/sdp_video_format.h b/api/video_codecs/sdp_video_format.h index 80054cffee..494d1df856 100644 --- a/api/video_codecs/sdp_video_format.h +++ b/api/video_codecs/sdp_video_format.h @@ -26,7 +26,7 @@ namespace webrtc { // SDP specification for a single video codec. // NOTE: This class is still under development and may change without notice. struct RTC_EXPORT SdpVideoFormat { - using Parameters [[deprecated("Use webrtc::CodecParameterMap")]] = + using Parameters [[deprecated("Use CodecParameterMap")]] = std::map; explicit SdpVideoFormat(const std::string& name); @@ -55,7 +55,7 @@ struct RTC_EXPORT SdpVideoFormat { // specific parameters. Please note that two SdpVideoFormats can represent the // same codec even though not all parameters are the same. bool IsSameCodec(const SdpVideoFormat& other) const; - bool IsCodecInList(ArrayView formats) const; + bool IsCodecInList(ArrayView formats) const; std::string ToString() const; diff --git a/api/video_codecs/simple_encoder_wrapper.h b/api/video_codecs/simple_encoder_wrapper.h index 466d45b656..c29b6a4f18 100644 --- a/api/video_codecs/simple_encoder_wrapper.h +++ b/api/video_codecs/simple_encoder_wrapper.h @@ -59,7 +59,7 @@ class SimpleEncoderWrapper { void SetEncodeFps(int fps); - void Encode(scoped_refptr frame_buffer, + void Encode(scoped_refptr frame_buffer, bool force_keyframe, EncodeResultCallback callback); diff --git a/api/video_codecs/video_encoder_interface.h b/api/video_codecs/video_encoder_interface.h index b0b18eeb80..2e99d50770 100644 --- a/api/video_codecs/video_encoder_interface.h +++ b/api/video_codecs/video_encoder_interface.h @@ -75,7 +75,7 @@ class VideoEncoderInterface { std::unique_ptr frame_output; }; - virtual void Encode(scoped_refptr frame_buffer, + virtual void Encode(scoped_refptr frame_buffer, const TemporalUnitSettings& settings, std::vector frame_settings) = 0; }; diff --git a/api/voip/test/mock_voip_engine.h b/api/voip/test/mock_voip_engine.h index 6f9e2813fc..97006a5928 100644 --- a/api/voip/test/mock_voip_engine.h +++ b/api/voip/test/mock_voip_engine.h @@ -69,13 +69,11 @@ class MockVoipNetwork : public VoipNetwork { public: MOCK_METHOD(VoipResult, ReceivedRTPPacket, - (ChannelId channel_id, - webrtc::ArrayView rtp_packet), + (ChannelId channel_id, ArrayView rtp_packet), (override)); MOCK_METHOD(VoipResult, ReceivedRTCPPacket, - (ChannelId channel_id, - webrtc::ArrayView rtcp_packet), + (ChannelId channel_id, ArrayView rtcp_packet), (override)); }; diff --git a/api/voip/voip_base.h b/api/voip/voip_base.h index f7f4432a6c..72cd4b752b 100644 --- a/api/voip/voip_base.h +++ b/api/voip/voip_base.h @@ -58,7 +58,7 @@ class VoipBase { // Creates a channel. // Each channel handle maps into one audio media session where each has // its own separate module for send/receive rtp packet with one peer. - // Caller must set `transport`, webrtc::Transport callback pointer to + // Caller must set `transport`, Transport callback pointer to // receive rtp/rtcp packets from corresponding media session in VoIP engine. // VoipEngine framework expects applications to handle network I/O directly // and injection for incoming RTP from remote endpoint is handled via diff --git a/api/webrtc_key_value_config.h b/api/webrtc_key_value_config.h deleted file mode 100644 index 0648a7f593..0000000000 --- a/api/webrtc_key_value_config.h +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Copyright 2019 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_WEBRTC_KEY_VALUE_CONFIG_H_ -#define API_WEBRTC_KEY_VALUE_CONFIG_H_ - -// TODO(bugs.webrtc.org/10335): Remove once all migrated to -// api/field_trials_view.h -#include "api/field_trials_view.h" // IWYU pragma: keep - -#endif // API_WEBRTC_KEY_VALUE_CONFIG_H_ diff --git a/audio/BUILD.gn b/audio/BUILD.gn index 0492dd24e5..aa82f7a149 100644 --- a/audio/BUILD.gn +++ b/audio/BUILD.gn @@ -45,9 +45,11 @@ rtc_library("audio") { "../api:frame_transformer_interface", "../api:function_view", "../api:make_ref_counted", + "../api:rtc_error", "../api:rtp_headers", "../api:rtp_packet_info", "../api:rtp_parameters", + "../api:rtp_sender_interface", "../api:scoped_refptr", "../api:sequence_checker", "../api:transport_api", @@ -82,6 +84,7 @@ rtc_library("audio") { "../logging:rtc_stream_config", "../media:media_channel", "../media:media_channel_impl", + "../media:media_constants", "../modules/async_audio_processing", "../modules/audio_coding", "../modules/audio_coding:audio_coding_module_typedefs", @@ -120,6 +123,7 @@ rtc_library("audio") { "utility:audio_frame_operations", "//third_party/abseil-cpp/absl/functional:any_invocable", "//third_party/abseil-cpp/absl/memory", + "//third_party/abseil-cpp/absl/strings", "//third_party/abseil-cpp/absl/strings:string_view", ] } @@ -169,10 +173,10 @@ if (rtc_include_tests) { "../api:array_view", "../api:bitrate_allocation", "../api:call_api", + "../api:field_trials", "../api:frame_transformer_factory", "../api:frame_transformer_interface", "../api:function_view", - "../api:libjingle_peerconnection_api", "../api:make_ref_counted", "../api:mock_audio_mixer", "../api:mock_frame_decryptor", @@ -190,15 +194,12 @@ if (rtc_include_tests) { "../api/audio:audio_processing_statistics", "../api/audio_codecs:audio_codecs_api", "../api/audio_codecs:builtin_audio_encoder_factory", - "../api/audio_codecs/opus:audio_decoder_opus", - "../api/audio_codecs/opus:audio_encoder_opus", "../api/crypto:frame_decryptor_interface", "../api/crypto:frame_encryptor_interface", "../api/crypto:options", "../api/environment", "../api/environment:environment_factory", "../api/task_queue", - "../api/task_queue:default_task_queue_factory", "../api/task_queue/test:mock_task_queue_base", "../api/transport:bitrate_settings", "../api/transport:network_control", @@ -217,39 +218,31 @@ if (rtc_include_tests) { "../call:rtp_sender", "../common_audio", "../modules/audio_coding:audio_coding_module_typedefs", - "../modules/audio_device:audio_device_impl", # For TestAudioDeviceModule "../modules/audio_device:mock_audio_device", "../modules/audio_mixer:audio_mixer_impl", "../modules/audio_mixer:audio_mixer_test_utils", "../modules/audio_processing:mocks", "../modules/pacing", + "../modules/rtp_rtcp", "../modules/rtp_rtcp:mock_rtp_rtcp", - "../modules/rtp_rtcp:rtp_rtcp", "../modules/rtp_rtcp:rtp_rtcp_format", - "../rtc_base:checks", - "../rtc_base:gunit_helpers", - "../rtc_base:macromagic", - "../rtc_base:refcount", - "../rtc_base:rtc_base_tests_utils", "../rtc_base:safe_compare", "../rtc_base:task_queue_for_test", "../rtc_base:threading", "../rtc_base:timeutils", "../system_wrappers", "../test:audio_codec_mocks", + "../test:create_test_field_trials", "../test:field_trial", "../test:mock_transport", "../test:rtp_test_utils", "../test:run_loop", - "../test:scoped_key_value_config", "../test:test_common", "../test:test_support", "../test:video_test_constants", "../test:wait_until", - "../test/time_controller:time_controller", + "../test/time_controller", "utility:utility_tests", - "//testing/gmock", - "//testing/gtest", "//third_party/abseil-cpp/absl/memory", "//third_party/abseil-cpp/absl/strings:string_view", ] diff --git a/audio/audio_send_stream.cc b/audio/audio_send_stream.cc index 94991f76e4..692527d000 100644 --- a/audio/audio_send_stream.cc +++ b/audio/audio_send_stream.cc @@ -10,34 +10,54 @@ #include "audio/audio_send_stream.h" +#include +#include #include +#include #include #include #include +#include "absl/strings/str_cat.h" +#include "absl/strings/string_view.h" +#include "api/audio/audio_frame.h" #include "api/audio/audio_processing.h" #include "api/audio_codecs/audio_encoder.h" #include "api/audio_codecs/audio_encoder_factory.h" #include "api/audio_codecs/audio_format.h" -#include "api/call/transport.h" -#include "api/crypto/frame_encryptor_interface.h" +#include "api/call/bitrate_allocation.h" +#include "api/environment/environment.h" +#include "api/field_trials_view.h" #include "api/function_view.h" +#include "api/rtc_error.h" #include "api/rtc_event_log/rtc_event_log.h" -#include "api/task_queue/task_queue_base.h" +#include "api/rtp_parameters.h" +#include "api/rtp_sender_interface.h" +#include "api/scoped_refptr.h" +#include "api/sequence_checker.h" +#include "api/units/data_rate.h" +#include "api/units/data_size.h" +#include "api/units/time_delta.h" #include "audio/audio_state.h" #include "audio/channel_send.h" -#include "audio/conversion.h" -#include "call/rtp_config.h" +#include "call/audio_state.h" +#include "call/bitrate_allocator.h" #include "call/rtp_transport_controller_send_interface.h" #include "common_audio/vad/include/vad.h" #include "logging/rtc_event_log/events/rtc_event_audio_send_stream_config.h" #include "logging/rtc_event_log/rtc_stream_config.h" #include "media/base/media_channel.h" +#include "media/base/media_constants.h" #include "modules/audio_coding/codecs/cng/audio_encoder_cng.h" #include "modules/audio_coding/codecs/red/audio_encoder_copy_red.h" +#include "modules/rtp_rtcp/include/report_block_data.h" +#include "modules/rtp_rtcp/include/rtp_rtcp_defines.h" #include "modules/rtp_rtcp/source/rtp_header_extensions.h" #include "rtc_base/checks.h" +#include "rtc_base/experiments/struct_parameters_parser.h" #include "rtc_base/logging.h" +#include "rtc_base/race_checker.h" +#include "rtc_base/synchronization/mutex.h" #include "rtc_base/trace_event.h" namespace webrtc { @@ -244,6 +264,10 @@ void AudioSendStream::ConfigureStream( rtp_rtcp_module_->SetExtmapAllowMixed(new_config.rtp.extmap_allow_mixed); } + if (first_time || new_config.rtp.csrcs != old_config.rtp.csrcs) { + channel_send_->SetCsrcs(new_config.rtp.csrcs); + } + const ExtensionIds old_ids = FindExtensionIds(old_config.rtp.extensions); const ExtensionIds new_ids = FindExtensionIds(new_config.rtp.extensions); @@ -482,7 +506,6 @@ uint32_t AudioSendStream::OnBitrateUpdated(BitrateAllocationUpdate update) { GetMinMaxBitrateConstraints(); if (constraints) { update.target_bitrate.Clamp(constraints->min, constraints->max); - update.stable_target_bitrate.Clamp(constraints->min, constraints->max); } channel_send_->OnBitrateAllocation(update); // The amount of audio protection is not exposed by the encoder, hence diff --git a/audio/audio_send_stream_unittest.cc b/audio/audio_send_stream_unittest.cc index 336323e1e5..0cc99124e8 100644 --- a/audio/audio_send_stream_unittest.cc +++ b/audio/audio_send_stream_unittest.cc @@ -10,6 +10,7 @@ #include "audio/audio_send_stream.h" +#include #include #include #include @@ -25,6 +26,7 @@ #include "api/call/bitrate_allocation.h" #include "api/crypto/frame_encryptor_interface.h" #include "api/environment/environment_factory.h" +#include "api/field_trials.h" #include "api/function_view.h" #include "api/make_ref_counted.h" #include "api/rtp_parameters.h" @@ -50,11 +52,11 @@ #include "modules/rtp_rtcp/mocks/mock_network_link_rtcp_observer.h" #include "modules/rtp_rtcp/mocks/mock_rtp_rtcp.h" #include "modules/rtp_rtcp/source/rtp_header_extensions.h" +#include "test/create_test_field_trials.h" #include "test/gmock.h" #include "test/gtest.h" #include "test/mock_audio_encoder.h" #include "test/mock_audio_encoder_factory.h" -#include "test/scoped_key_value_config.h" #include "test/time_controller/real_time_controller.h" namespace webrtc { @@ -63,6 +65,7 @@ namespace { using ::testing::_; using ::testing::AnyNumber; +using ::testing::ElementsAreArray; using ::testing::Eq; using ::testing::Field; using ::testing::InSequence; @@ -73,10 +76,11 @@ using ::testing::Return; using ::testing::StrEq; using ::testing::WithArg; -static const float kTolerance = 0.0001f; +const float kTolerance = 0.0001f; const uint32_t kSsrc = 1234; const char* kCName = "foo_name"; +const std::array kCsrcs = {5678, 9012}; const int kAudioLevelId = 2; const int kTransportSequenceNumberId = 4; const int32_t kEchoDelayMedian = 254; @@ -160,18 +164,18 @@ scoped_refptr SetupEncoderFactoryMock() { return factory; } -struct ConfigHelper { +class ConfigHelper { + public: ConfigHelper(bool audio_bwe_enabled, bool expect_set_encoder_call, bool use_null_audio_processing) - : stream_config_(/*send_transport=*/nullptr), + : field_trials_(CreateTestFieldTrials()), + stream_config_(/*send_transport=*/nullptr), audio_processing_( use_null_audio_processing ? nullptr : make_ref_counted>()), audio_encoder_(nullptr) { - using ::testing::Invoke; - AudioState::Config config; config.audio_mixer = AudioMixerImpl::Create(); config.audio_processing = audio_processing_; @@ -187,6 +191,7 @@ struct ConfigHelper { stream_config_.send_codec_spec = AudioSendStream::Config::SendCodecSpec(kIsacPayloadType, kIsacFormat); stream_config_.rtp.ssrc = kSsrc; + stream_config_.rtp.csrcs.assign(kCsrcs.begin(), kCsrcs.end()); stream_config_.rtp.c_name = kCName; stream_config_.rtp.extensions.push_back( RtpExtension(RtpExtension::kAudioLevelUri, kAudioLevelId)); @@ -200,7 +205,7 @@ struct ConfigHelper { std::unique_ptr CreateAudioSendStream() { return std::make_unique( - CreateEnvironment(&field_trials, time_controller_.GetClock(), + CreateEnvironment(&field_trials_, time_controller_.GetClock(), time_controller_.GetTaskQueueFactory()), stream_config_, audio_state_, &rtp_transport_, &bitrate_allocator_, std::nullopt, @@ -234,6 +239,7 @@ struct ConfigHelper { EXPECT_CALL(*channel_send_, SetEncoderToPacketizerFrameTransformer(_)) .Times(1); EXPECT_CALL(rtp_rtcp_, SetExtmapAllowMixed(false)).Times(1); + EXPECT_CALL(*channel_send_, SetCsrcs(ElementsAreArray(kCsrcs))).Times(1); EXPECT_CALL(*channel_send_, SetSendAudioLevelIndicationStatus(true, kAudioLevelId)) .Times(1); @@ -326,9 +332,10 @@ struct ConfigHelper { } } - test::ScopedKeyValueConfig field_trials; + FieldTrials& field_trials() { return field_trials_; } private: + FieldTrials field_trials_; RealTimeController time_controller_; scoped_refptr audio_state_; AudioSendStream::Config stream_config_; @@ -365,6 +372,7 @@ std::unique_ptr CreateAudioFrame1kHzSineWave(int16_t audio_level, TEST(AudioSendStreamTest, ConfigToString) { AudioSendStream::Config config(/*send_transport=*/nullptr); config.rtp.ssrc = kSsrc; + config.rtp.csrcs.assign(kCsrcs.begin(), kCsrcs.end()); config.rtp.c_name = kCName; config.min_bitrate_bps = 12000; config.max_bitrate_bps = 34000; @@ -380,9 +388,9 @@ TEST(AudioSendStreamTest, ConfigToString) { RtpExtension(RtpExtension::kAudioLevelUri, kAudioLevelId)); config.rtcp_report_interval_ms = 2500; EXPECT_EQ( - "{rtp: {ssrc: 1234, extmap-allow-mixed: true, extensions: [{uri: " - "urn:ietf:params:rtp-hdrext:ssrc-audio-level, id: 2}], " - "c_name: foo_name}, rtcp_report_interval_ms: 2500, " + "{rtp: {ssrc: 1234, csrcs: [5678, 9012], extmap-allow-mixed: true, " + "extensions: [{uri: urn:ietf:params:rtp-hdrext:ssrc-audio-level, " + "id: 2}], c_name: foo_name}, rtcp_report_interval_ms: 2500, " "send_transport: null, " "min_bitrate_bps: 12000, max_bitrate_bps: 34000, has " "audio_network_adaptor_config: false, has_dscp: true, " @@ -421,6 +429,19 @@ TEST(AudioSendStreamTest, SetMuted) { } } +TEST(AudioSendStreamTest, SetCsrcs) { + for (bool use_null_audio_processing : {false, true}) { + ConfigHelper helper(false, true, use_null_audio_processing); + auto send_stream = helper.CreateAudioSendStream(); + + std::vector updated_csrcs = {4, 5, 6}; + helper.config().rtp.csrcs = updated_csrcs; + EXPECT_CALL(*helper.channel_send(), + SetCsrcs(ElementsAreArray(updated_csrcs))); + send_stream->Reconfigure(helper.config(), nullptr); + } +} + TEST(AudioSendStreamTest, AudioBweCorrectObjectsOnChannelProxy) { for (bool use_null_audio_processing : {false, true}) { ConfigHelper helper(true, true, use_null_audio_processing); @@ -654,8 +675,8 @@ TEST(AudioSendStreamTest, SSBweTargetInRangeRespected) { TEST(AudioSendStreamTest, SSBweFieldTrialMinRespected) { for (bool use_null_audio_processing : {false, true}) { ConfigHelper helper(true, true, use_null_audio_processing); - ScopedKeyValueConfig field_trials( - helper.field_trials, "WebRTC-Audio-Allocation/min:6kbps,max:64kbps/"); + helper.field_trials().Set("WebRTC-Audio-Allocation", + "min:6kbps,max:64kbps"); auto send_stream = helper.CreateAudioSendStream(); EXPECT_CALL( *helper.channel_send(), @@ -670,8 +691,8 @@ TEST(AudioSendStreamTest, SSBweFieldTrialMinRespected) { TEST(AudioSendStreamTest, SSBweFieldTrialMaxRespected) { for (bool use_null_audio_processing : {false, true}) { ConfigHelper helper(true, true, use_null_audio_processing); - ScopedKeyValueConfig field_trials( - helper.field_trials, "WebRTC-Audio-Allocation/min:6kbps,max:64kbps/"); + helper.field_trials().Set("WebRTC-Audio-Allocation", + "min:6kbps,max:64kbps"); auto send_stream = helper.CreateAudioSendStream(); EXPECT_CALL( *helper.channel_send(), @@ -686,8 +707,7 @@ TEST(AudioSendStreamTest, SSBweFieldTrialMaxRespected) { TEST(AudioSendStreamTest, SSBweWithOverhead) { for (bool use_null_audio_processing : {false, true}) { ConfigHelper helper(true, true, use_null_audio_processing); - ScopedKeyValueConfig field_trials(helper.field_trials, - "WebRTC-Audio-LegacyOverhead/Disabled/"); + helper.field_trials().Set("WebRTC-Audio-LegacyOverhead", "Disabled"); EXPECT_CALL(*helper.rtp_rtcp(), ExpectedPerPacketOverhead) .WillRepeatedly(Return(kOverheadPerPacket.bytes())); EXPECT_CALL(*helper.channel_send(), RegisterPacketOverhead); @@ -707,10 +727,9 @@ TEST(AudioSendStreamTest, SSBweWithOverhead) { TEST(AudioSendStreamTest, SSBweWithOverheadMinRespected) { for (bool use_null_audio_processing : {false, true}) { ConfigHelper helper(true, true, use_null_audio_processing); - ScopedKeyValueConfig field_trials( - helper.field_trials, - "WebRTC-Audio-LegacyOverhead/Disabled/" - "WebRTC-Audio-Allocation/min:6kbps,max:64kbps/"); + helper.field_trials().Set("WebRTC-Audio-LegacyOverhead", "Disabled"); + helper.field_trials().Set("WebRTC-Audio-Allocation", + "min:6kbps,max:64kbps"); EXPECT_CALL(*helper.rtp_rtcp(), ExpectedPerPacketOverhead) .WillRepeatedly(Return(kOverheadPerPacket.bytes())); EXPECT_CALL(*helper.channel_send(), RegisterPacketOverhead); @@ -728,10 +747,9 @@ TEST(AudioSendStreamTest, SSBweWithOverheadMinRespected) { TEST(AudioSendStreamTest, SSBweWithOverheadMaxRespected) { for (bool use_null_audio_processing : {false, true}) { ConfigHelper helper(true, true, use_null_audio_processing); - ScopedKeyValueConfig field_trials( - helper.field_trials, - "WebRTC-Audio-LegacyOverhead/Disabled/" - "WebRTC-Audio-Allocation/min:6kbps,max:64kbps/"); + helper.field_trials().Set("WebRTC-Audio-LegacyOverhead", "Disabled"); + helper.field_trials().Set("WebRTC-Audio-Allocation", + "min:6kbps,max:64kbps"); EXPECT_CALL(*helper.rtp_rtcp(), ExpectedPerPacketOverhead) .WillRepeatedly(Return(kOverheadPerPacket.bytes())); EXPECT_CALL(*helper.channel_send(), RegisterPacketOverhead); @@ -940,8 +958,7 @@ TEST(AudioSendStreamTest, ReconfigureWithFrameEncryptor) { TEST(AudioSendStreamTest, DefaultsHonorsPriorityBitrate) { ConfigHelper helper(true, true, true); - ScopedKeyValueConfig field_trials(helper.field_trials, - "WebRTC-Audio-Allocation/prio_rate:20/"); + helper.field_trials().Set("WebRTC-Audio-Allocation", "prio_rate:20"); auto send_stream = helper.CreateAudioSendStream(); EXPECT_CALL(*helper.bitrate_allocator(), AddObserver(send_stream.get(), _)) .WillOnce(Invoke( @@ -970,9 +987,8 @@ TEST(AudioSendStreamTest, DefaultsToContributeUnusedBitrate) { TEST(AudioSendStreamTest, OverridesPriorityBitrate) { ConfigHelper helper(true, true, true); - ScopedKeyValueConfig field_trials(helper.field_trials, - "WebRTC-Audio-Allocation/prio_rate:20/" - "WebRTC-Audio-PriorityBitrate/Disabled/"); + helper.field_trials().Set("WebRTC-Audio-Allocation", "prio_rate:20"); + helper.field_trials().Set("WebRTC-Audio-PriorityBitrate", "Disabled"); auto send_stream = helper.CreateAudioSendStream(); EXPECT_CALL(*helper.bitrate_allocator(), AddObserver(send_stream.get(), _)) .WillOnce(Invoke( diff --git a/audio/audio_state_unittest.cc b/audio/audio_state_unittest.cc index c886a13b86..959eb38b62 100644 --- a/audio/audio_state_unittest.cc +++ b/audio/audio_state_unittest.cc @@ -132,13 +132,9 @@ struct ConfigHelper { class FakeAudioSource : public AudioMixer::Source { public: - // TODO(aleloi): Valid overrides commented out, because the gmock - // methods don't use any override declarations, and we want to avoid - // warnings from -Winconsistent-missing-override. See - // http://crbug.com/428099. - int Ssrc() const /*override*/ { return 0; } + int Ssrc() const override { return 0; } - int PreferredSampleRate() const /*override*/ { return kSampleRate; } + int PreferredSampleRate() const override { return kSampleRate; } MOCK_METHOD(AudioFrameInfo, GetAudioFrameWithInfo, diff --git a/audio/channel_receive.cc b/audio/channel_receive.cc index 832f86aaab..724fb32ff3 100644 --- a/audio/channel_receive.cc +++ b/audio/channel_receive.cc @@ -407,7 +407,6 @@ AudioMixer::Source::AudioFrameInfo ChannelReceive::GetAudioFrameWithInfo( TRACE_EVENT_BEGIN1("webrtc", "ChannelReceive::GetAudioFrameWithInfo", "sample_rate_hz", sample_rate_hz); RTC_DCHECK_RUNS_SERIALIZED(&audio_thread_race_checker_); - audio_frame->sample_rate_hz_ = sample_rate_hz; env_.event_log().Log(std::make_unique(remote_ssrc_)); diff --git a/audio/channel_receive_frame_transformer_delegate.cc b/audio/channel_receive_frame_transformer_delegate.cc index 7995548043..f409c1a9df 100644 --- a/audio/channel_receive_frame_transformer_delegate.cc +++ b/audio/channel_receive_frame_transformer_delegate.cc @@ -112,7 +112,7 @@ class TransformableIncomingAudioFrame std::optional CaptureTime() const override { if (header_.extension.absolute_capture_time) { - return Timestamp::Millis(UQ32x32ToInt64Ms( + return Timestamp::Micros(UQ32x32ToInt64Us( header_.extension.absolute_capture_time->absolute_capture_timestamp)); } return std::nullopt; @@ -122,8 +122,8 @@ class TransformableIncomingAudioFrame if (header_.extension.absolute_capture_time && header_.extension.absolute_capture_time ->estimated_capture_clock_offset) { - return TimeDelta::Millis( - Q32x32ToInt64Ms(*header_.extension.absolute_capture_time + return TimeDelta::Micros( + Q32x32ToInt64Us(*header_.extension.absolute_capture_time ->estimated_capture_clock_offset)); } return std::nullopt; diff --git a/audio/channel_send.cc b/audio/channel_send.cc index 2077d97718..06ebdd2346 100644 --- a/audio/channel_send.cc +++ b/audio/channel_send.cc @@ -163,6 +163,9 @@ class ChannelSend : public ChannelSendInterface, // Muting, Volume and Level. void SetInputMute(bool enable) override; + // CSRCs. + void SetCsrcs(ArrayView csrcs) override; + // Stats. ANAStats GetANAStatistics() const override; @@ -320,6 +323,8 @@ class ChannelSend : public ChannelSendInterface, mutable Mutex bitrate_accountant_mutex_; AudioBitrateAccountant bitrate_accountant_ RTC_GUARDED_BY(bitrate_accountant_mutex_); + + std::vector csrcs_ RTC_GUARDED_BY(encoder_queue_checker_); }; const int kTelephoneEventAttenuationdB = 10; @@ -393,12 +398,11 @@ int32_t ChannelSend::SendData(AudioFrameType frameType, frame_transformer_delegate_->Transform( frameType, payloadType, rtp_timestamp + rtp_rtcp_->StartTimestamp(), payloadData, payloadSize, absolute_capture_timestamp_ms, - rtp_rtcp_->SSRC(), mime_type.str(), audio_level_dbov); + rtp_rtcp_->SSRC(), mime_type.str(), audio_level_dbov, csrcs_); return 0; } return SendRtpAudio(frameType, payloadType, rtp_timestamp, payload, - absolute_capture_timestamp_ms, /*csrcs=*/{}, - audio_level_dbov); + absolute_capture_timestamp_ms, csrcs_, audio_level_dbov); } int32_t ChannelSend::SendRtpAudio(AudioFrameType frameType, @@ -694,6 +698,17 @@ bool ChannelSend::InputMute() const { return input_mute_; } +void ChannelSend::SetCsrcs(ArrayView csrcs) { + RTC_DCHECK_RUN_ON(&worker_thread_checker_); + std::vector csrcs_copy( + csrcs.begin(), + csrcs.begin() + std::min(csrcs.size(), kRtpCsrcSize)); + encoder_queue_->PostTask([this, csrcs = std::move(csrcs_copy)]() mutable { + RTC_DCHECK_RUN_ON(&encoder_queue_checker_); + csrcs_ = csrcs; + }); +} + bool ChannelSend::SendTelephoneEventOutband(int event, int duration_ms) { RTC_DCHECK_RUN_ON(&worker_thread_checker_); RTC_DCHECK_LE(0, event); diff --git a/audio/channel_send.h b/audio/channel_send.h index 8991fc0f44..0ed544afed 100644 --- a/audio/channel_send.h +++ b/audio/channel_send.h @@ -18,6 +18,7 @@ #include #include "absl/strings/string_view.h" +#include "api/array_view.h" #include "api/audio/audio_frame.h" #include "api/audio_codecs/audio_encoder.h" #include "api/audio_codecs/audio_format.h" @@ -90,6 +91,10 @@ class ChannelSendInterface { virtual void OnBitrateAllocation(BitrateAllocationUpdate update) = 0; virtual int GetTargetBitrate() const = 0; virtual void SetInputMute(bool muted) = 0; + // Sets the list of CSRCs to be included in the RTP header. If more than + // kRtpCsrcSize CSRCs are provided, only the first kRtpCsrcSize elements are + // kept. + virtual void SetCsrcs(ArrayView csrcs) = 0; virtual void ProcessAndEncodeAudio( std::unique_ptr audio_frame) = 0; diff --git a/audio/channel_send_frame_transformer_delegate.cc b/audio/channel_send_frame_transformer_delegate.cc index f1a8b4e37d..d82b0f5137 100644 --- a/audio/channel_send_frame_transformer_delegate.cc +++ b/audio/channel_send_frame_transformer_delegate.cc @@ -10,11 +10,25 @@ #include "audio/channel_send_frame_transformer_delegate.h" +#include +#include +#include +#include +#include #include #include +#include "api/array_view.h" +#include "api/frame_transformer_interface.h" +#include "api/scoped_refptr.h" +#include "api/sequence_checker.h" +#include "api/task_queue/task_queue_base.h" #include "api/units/time_delta.h" #include "api/units/timestamp.h" +#include "modules/audio_coding/include/audio_coding_module_typedefs.h" +#include "rtc_base/buffer.h" +#include "rtc_base/checks.h" +#include "rtc_base/synchronization/mutex.h" namespace webrtc { namespace { @@ -183,14 +197,15 @@ void ChannelSendFrameTransformerDelegate::Transform( size_t payload_size, int64_t absolute_capture_timestamp_ms, uint32_t ssrc, - const std::string& codec_mimetype, - std::optional audio_level_dbov) { + const std::string& codec_mime_type, + std::optional audio_level_dbov, + const std::vector& csrcs) { { MutexLock lock(&send_lock_); if (short_circuit_) { send_frame_callback_(frame_type, payload_type, rtp_timestamp, ArrayView(payload_data, payload_size), - absolute_capture_timestamp_ms, /*csrcs=*/{}, + absolute_capture_timestamp_ms, csrcs, audio_level_dbov); return; } @@ -198,8 +213,7 @@ void ChannelSendFrameTransformerDelegate::Transform( frame_transformer_->Transform( std::make_unique( frame_type, payload_type, rtp_timestamp, payload_data, payload_size, - absolute_capture_timestamp_ms, ssrc, - /*csrcs=*/std::vector(), codec_mimetype, + absolute_capture_timestamp_ms, ssrc, csrcs, codec_mime_type, /*sequence_number=*/std::nullopt, audio_level_dbov)); } diff --git a/audio/channel_send_frame_transformer_delegate.h b/audio/channel_send_frame_transformer_delegate.h index eae9cac407..f1a6d206e6 100644 --- a/audio/channel_send_frame_transformer_delegate.h +++ b/audio/channel_send_frame_transformer_delegate.h @@ -11,15 +11,21 @@ #ifndef AUDIO_CHANNEL_SEND_FRAME_TRANSFORMER_DELEGATE_H_ #define AUDIO_CHANNEL_SEND_FRAME_TRANSFORMER_DELEGATE_H_ +#include +#include +#include #include +#include #include +#include +#include "api/array_view.h" #include "api/frame_transformer_interface.h" -#include "api/sequence_checker.h" +#include "api/scoped_refptr.h" #include "api/task_queue/task_queue_base.h" #include "modules/audio_coding/include/audio_coding_module_typedefs.h" -#include "rtc_base/buffer.h" #include "rtc_base/synchronization/mutex.h" +#include "rtc_base/thread_annotations.h" namespace webrtc { @@ -62,7 +68,8 @@ class ChannelSendFrameTransformerDelegate : public TransformedFrameCallback { int64_t absolute_capture_timestamp_ms, uint32_t ssrc, const std::string& codec_mime_type, - std::optional audio_level_dbov); + std::optional audio_level_dbov, + const std::vector& csrcs = {}); // Implements TransformedFrameCallback. Can be called on any thread. void OnTransformedFrame( diff --git a/audio/channel_send_frame_transformer_delegate_unittest.cc b/audio/channel_send_frame_transformer_delegate_unittest.cc index 2eac45ca4f..f0d498bb49 100644 --- a/audio/channel_send_frame_transformer_delegate_unittest.cc +++ b/audio/channel_send_frame_transformer_delegate_unittest.cc @@ -23,6 +23,7 @@ #include "api/scoped_refptr.h" #include "api/test/mock_frame_transformer.h" #include "api/test/mock_transformable_audio_frame.h" +#include "api/units/timestamp.h" #include "modules/audio_coding/include/audio_coding_module_typedefs.h" #include "rtc_base/task_queue_for_test.h" #include "test/gmock.h" @@ -200,6 +201,59 @@ TEST(ChannelSendFrameTransformerDelegateTest, channel_queue.WaitForPreviouslyPostedTasks(); } +// Test that CSRCs are propagated correctly from the Transform call to the frame +// transformer. +TEST(ChannelSendFrameTransformerDelegateTest, + TransformForwardsCsrcsViaFrameTransformer) { + TaskQueueForTest channel_queue("channel_queue"); + scoped_refptr mock_frame_transformer = + make_ref_counted>(); + MockChannelSend mock_channel; + scoped_refptr delegate = + make_ref_counted( + mock_channel.callback(), mock_frame_transformer, channel_queue.Get()); + scoped_refptr callback; + EXPECT_CALL(*mock_frame_transformer, RegisterTransformedFrameCallback) + .WillOnce(SaveArg<0>(&callback)); + delegate->Init(); + ASSERT_TRUE(callback); + + std::vector csrcs = {123, 234, 345, 456}; + EXPECT_CALL(mock_channel, + SendFrame(_, _, _, _, _, ElementsAreArray(csrcs), _)); + ON_CALL(*mock_frame_transformer, Transform) + .WillByDefault( + [&callback](std::unique_ptr frame) { + callback->OnTransformedFrame(std::move(frame)); + }); + delegate->Transform( + AudioFrameType::kEmptyFrame, 0, 0, mock_data, sizeof(mock_data), 0, + /*ssrc=*/0, /*mimeType=*/"audio/opus", /*audio_level_dbov=*/31, csrcs); + channel_queue.WaitForPreviouslyPostedTasks(); +} + +// Test that CSRCs are propagated correctly from the Transform call to the send +// frame callback when short circuiting is enabled. +TEST(ChannelSendFrameTransformerDelegateTest, + TransformForwardsCsrcsViaShortCircuiting) { + TaskQueueForTest channel_queue("channel_queue"); + scoped_refptr mock_frame_transformer = + make_ref_counted>(); + MockChannelSend mock_channel; + scoped_refptr delegate = + make_ref_counted( + mock_channel.callback(), mock_frame_transformer, channel_queue.Get()); + + std::vector csrcs = {123, 234, 345, 456}; + delegate->StartShortCircuiting(); + EXPECT_CALL(mock_channel, + SendFrame(_, _, _, _, _, ElementsAreArray(csrcs), _)); + delegate->Transform( + AudioFrameType::kEmptyFrame, 0, 0, mock_data, sizeof(mock_data), 0, + /*ssrc=*/0, /*mimeType=*/"audio/opus", /*audio_level_dbov=*/31, csrcs); + channel_queue.WaitForPreviouslyPostedTasks(); +} + // Test that if the delegate receives a transformed frame after it has been // reset, it does not run the SendFrameCallback, as the channel is destroyed // after resetting the delegate. diff --git a/audio/channel_send_unittest.cc b/audio/channel_send_unittest.cc index 7636ee32c6..793af1bf9d 100644 --- a/audio/channel_send_unittest.cc +++ b/audio/channel_send_unittest.cc @@ -28,6 +28,7 @@ #include "api/crypto/crypto_options.h" #include "api/environment/environment.h" #include "api/environment/environment_factory.h" +#include "api/field_trials.h" #include "api/frame_transformer_interface.h" #include "api/make_ref_counted.h" #include "api/rtp_headers.h" @@ -43,10 +44,10 @@ #include "call/rtp_transport_controller_send.h" #include "modules/rtp_rtcp/include/rtp_rtcp_defines.h" #include "modules/rtp_rtcp/source/rtp_packet_received.h" +#include "test/create_test_field_trials.h" #include "test/gmock.h" #include "test/gtest.h" #include "test/mock_transport.h" -#include "test/scoped_key_value_config.h" #include "test/time_controller/simulated_time_controller.h" #include "test/wait_until.h" @@ -79,6 +80,7 @@ class ChannelSendTest : public ::testing::Test { protected: ChannelSendTest() : time_controller_(Timestamp::Seconds(1)), + field_trials_(CreateTestFieldTrials()), env_(CreateEnvironment(&field_trials_, time_controller_.GetClock(), time_controller_.CreateTaskQueueFactory())), @@ -123,7 +125,7 @@ class ChannelSendTest : public ::testing::Test { void ProcessNextFrame() { ProcessNextFrame(CreateAudioFrame()); } GlobalSimulatedTimeController time_controller_; - test::ScopedKeyValueConfig field_trials_; + FieldTrials field_trials_; Environment env_; NiceMock transport_; CryptoOptions crypto_options_; @@ -409,6 +411,117 @@ TEST_F(ChannelSendTest, EnqueuePacketsGracefullyHandlesNonInitializedPacer) { ProcessNextFrame(); } +TEST_F(ChannelSendTest, ConfiguredCsrcsAreIncludedInRtpPackets) { + channel_->StartSend(); + std::vector expected_csrcs = {1, 2, 3}; + channel_->SetCsrcs(expected_csrcs); + + std::vector csrcs; + auto send_rtp = [&](ArrayView data, + const PacketOptions& /* options */) { + RtpPacketReceived packet; + packet.Parse(data); + csrcs = packet.Csrcs(); + return true; + }; + + EXPECT_CALL(transport_, SendRtp).WillRepeatedly(Invoke(send_rtp)); + ProcessNextFrame(); + ProcessNextFrame(); + + EXPECT_EQ(csrcs, expected_csrcs); +} + +// Creates a frame with the given CSRCs where other values are copied from the +// template. +std::unique_ptr CreateMockFrameWithCsrcs( + const TransformableAudioFrameInterface* frame_template, + const std::vector& csrcs) { + std::unique_ptr mock_frame = + std::make_unique(); + EXPECT_CALL(*mock_frame, GetContributingSources) + .WillRepeatedly(Return(csrcs)); + + std::vector frame_data = std::vector( + frame_template->GetData().begin(), frame_template->GetData().end()); + ON_CALL(*mock_frame, GetData).WillByDefault(Return(frame_data)); + + ON_CALL(*mock_frame, GetTimestamp) + .WillByDefault(Return(frame_template->GetTimestamp())); + ON_CALL(*mock_frame, GetPayloadType) + .WillByDefault(Return(frame_template->GetPayloadType())); + ON_CALL(*mock_frame, GetSsrc) + .WillByDefault(Return(frame_template->GetSsrc())); + ON_CALL(*mock_frame, GetMimeType) + .WillByDefault(Return(frame_template->GetMimeType())); + ON_CALL(*mock_frame, SequenceNumber) + .WillByDefault(Return(frame_template->SequenceNumber())); + ON_CALL(*mock_frame, GetDirection) + .WillByDefault(Return(frame_template->GetDirection())); + ON_CALL(*mock_frame, AbsoluteCaptureTimestamp) + .WillByDefault(Return(frame_template->AbsoluteCaptureTimestamp())); + ON_CALL(*mock_frame, Type).WillByDefault(Return(frame_template->Type())); + ON_CALL(*mock_frame, AudioLevel) + .WillByDefault(Return(frame_template->AudioLevel())); + ON_CALL(*mock_frame, ReceiveTime) + .WillByDefault(Return(frame_template->ReceiveTime())); + ON_CALL(*mock_frame, CaptureTime) + .WillByDefault(Return(frame_template->CaptureTime())); + ON_CALL(*mock_frame, SenderCaptureTimeOffset) + .WillByDefault(Return(frame_template->SenderCaptureTimeOffset())); + return mock_frame; +} + +TEST_F(ChannelSendTest, FrameTransformerTakesPrecedenceOverSetCsrcs) { + scoped_refptr mock_frame_transformer = + make_ref_counted(); + scoped_refptr callback; + EXPECT_CALL(*mock_frame_transformer, RegisterTransformedFrameCallback) + .WillOnce(SaveArg<0>(&callback)); + EXPECT_CALL(*mock_frame_transformer, UnregisterTransformedFrameCallback); + channel_->SetEncoderToPacketizerFrameTransformer(mock_frame_transformer); + + // Configure the mock frame transformer to return a frame with different CSRCs + // than it is provided. + std::vector csrcs_provided_to_frame_transformer; + std::vector csrcs_output_by_frame_transformer = {1, 2, 3}; + EXPECT_CALL(*mock_frame_transformer, Transform) + .WillRepeatedly( + Invoke([&](std::unique_ptr frame) { + auto audio_frame = + static_cast(frame.get()); + csrcs_provided_to_frame_transformer.assign( + audio_frame->GetContributingSources().begin(), + audio_frame->GetContributingSources().end()); + callback->OnTransformedFrame(CreateMockFrameWithCsrcs( + audio_frame, csrcs_output_by_frame_transformer)); + })); + + std::vector set_csrcs = {4, 5, 6}; + channel_->SetCsrcs(set_csrcs); + channel_->StartSend(); + + std::vector sent_csrcs; + auto send_rtp = [&](ArrayView data, + const PacketOptions& /* options */) { + RtpPacketReceived packet; + packet.Parse(data); + sent_csrcs = packet.Csrcs(); + return true; + }; + + EXPECT_CALL(transport_, SendRtp).WillRepeatedly(Invoke(send_rtp)); + ProcessNextFrame(); + ProcessNextFrame(); + + EXPECT_EQ(csrcs_provided_to_frame_transformer, set_csrcs) + << "The CSRCs configured in ChannelSend should be passed to the frame " + "transformer."; + EXPECT_EQ(sent_csrcs, csrcs_output_by_frame_transformer) + << "CSRCs provided by the frame transformer should propagate to the RTP " + "packet."; +} + } // namespace } // namespace voe } // namespace webrtc diff --git a/audio/mock_voe_channel_proxy.h b/audio/mock_voe_channel_proxy.h index 0038f3aa24..cd2927d153 100644 --- a/audio/mock_voe_channel_proxy.h +++ b/audio/mock_voe_channel_proxy.h @@ -20,6 +20,7 @@ #include #include "absl/strings/string_view.h" +#include "api/array_view.h" #include "api/audio/audio_frame.h" #include "api/audio/audio_mixer.h" #include "api/audio_codecs/audio_encoder.h" @@ -200,6 +201,7 @@ class MockChannelSend : public voe::ChannelSendInterface { RegisterPacketOverhead, (int packet_byte_overhead), (override)); + MOCK_METHOD(void, SetCsrcs, (ArrayView csrcs), (override)); }; } // namespace test } // namespace webrtc diff --git a/audio/remix_resample_unittest.cc b/audio/remix_resample_unittest.cc index 31dcfac1fe..6bfa855c73 100644 --- a/audio/remix_resample_unittest.cc +++ b/audio/remix_resample_unittest.cc @@ -11,10 +11,12 @@ #include "audio/remix_resample.h" #include +#include +#include +#include +#include "api/audio/audio_frame.h" #include "common_audio/resampler/include/push_resampler.h" -#include "rtc_base/arraysize.h" -#include "rtc_base/checks.h" #include "test/gtest.h" namespace webrtc { diff --git a/audio/utility/BUILD.gn b/audio/utility/BUILD.gn index 2ced9aa70d..4d763fdd1c 100644 --- a/audio/utility/BUILD.gn +++ b/audio/utility/BUILD.gn @@ -46,7 +46,6 @@ if (rtc_include_tests) { "../../api/audio:audio_frame_api", "../../rtc_base:checks", "../../rtc_base:logging", - "../../rtc_base:macromagic", "../../rtc_base:stringutils", "../../test:test_support", "//testing/gtest", diff --git a/audio/utility/channel_mixer_unittest.cc b/audio/utility/channel_mixer_unittest.cc index 7aa3810936..62ffca6ec1 100644 --- a/audio/utility/channel_mixer_unittest.cc +++ b/audio/utility/channel_mixer_unittest.cc @@ -10,12 +10,11 @@ #include "audio/utility/channel_mixer.h" -#include +#include +#include #include "api/audio/audio_frame.h" #include "api/audio/channel_layout.h" -#include "audio/utility/channel_mixing_matrix.h" -#include "rtc_base/arraysize.h" #include "rtc_base/strings/string_builder.h" #include "test/gtest.h" @@ -36,7 +35,7 @@ class ChannelMixerTest : public ::testing::Test { EXPECT_TRUE(frame_.muted()); } - virtual ~ChannelMixerTest() {} + ~ChannelMixerTest() override {} AudioFrame frame_; }; diff --git a/audio/utility/channel_mixing_matrix_unittest.cc b/audio/utility/channel_mixing_matrix_unittest.cc index d7a7f3f038..b6a2a7d656 100644 --- a/audio/utility/channel_mixing_matrix_unittest.cc +++ b/audio/utility/channel_mixing_matrix_unittest.cc @@ -12,9 +12,10 @@ #include +#include + +#include "api/audio/channel_layout.h" #include "audio/utility/channel_mixer.h" -#include "rtc_base/arraysize.h" -#include "rtc_base/logging.h" #include "rtc_base/strings/string_builder.h" #include "test/gtest.h" @@ -358,9 +359,7 @@ TEST(ChannelMixingMatrixTest, DiscreteToDiscrete) { {5, 2}, }; - for (size_t n = 0; n < arraysize(test_case); n++) { - int input_channels = test_case[n].input_channels; - int output_channels = test_case[n].output_channels; + for (auto [input_channels, output_channels] : test_case) { ChannelMixingMatrix matrix_builder(CHANNEL_LAYOUT_DISCRETE, input_channels, CHANNEL_LAYOUT_DISCRETE, output_channels); diff --git a/audio/voip/BUILD.gn b/audio/voip/BUILD.gn index 3754bbd266..fab9291f6b 100644 --- a/audio/voip/BUILD.gn +++ b/audio/voip/BUILD.gn @@ -66,10 +66,13 @@ rtc_library("audio_ingress") { "../../api/environment", "../../api/neteq:default_neteq_factory", "../../api/neteq:neteq_api", + "../../api/units:time_delta", "../../api/voip:voip_api", "../../modules/audio_coding", + "../../modules/audio_coding:audio_coding_module_typedefs", "../../modules/rtp_rtcp", "../../modules/rtp_rtcp:rtp_rtcp_format", + "../../rtc_base:checks", "../../rtc_base:criticalsection", "../../rtc_base:logging", "../../rtc_base:rtc_numerics", diff --git a/audio/voip/audio_ingress.cc b/audio/voip/audio_ingress.cc index 3fcfa5547b..7f8b86792a 100644 --- a/audio/voip/audio_ingress.cc +++ b/audio/voip/audio_ingress.cc @@ -10,22 +10,38 @@ #include "audio/voip/audio_ingress.h" -#include +#include #include +#include +#include #include #include +#include "api/array_view.h" +#include "api/audio/audio_mixer.h" +#include "api/audio_codecs/audio_decoder_factory.h" #include "api/audio_codecs/audio_format.h" +#include "api/environment/environment.h" #include "api/neteq/default_neteq_factory.h" +#include "api/neteq/neteq.h" +#include "api/scoped_refptr.h" +#include "api/units/time_delta.h" +#include "api/voip/voip_statistics.h" #include "audio/utility/audio_frame_operations.h" #include "modules/audio_coding/include/audio_coding_module.h" +#include "modules/audio_coding/include/audio_coding_module_typedefs.h" +#include "modules/rtp_rtcp/include/receive_statistics.h" +#include "modules/rtp_rtcp/include/report_block_data.h" +#include "modules/rtp_rtcp/include/rtp_rtcp_defines.h" #include "modules/rtp_rtcp/source/byte_io.h" #include "modules/rtp_rtcp/source/rtcp_packet/common_header.h" #include "modules/rtp_rtcp/source/rtcp_packet/receiver_report.h" #include "modules/rtp_rtcp/source/rtcp_packet/sender_report.h" +#include "modules/rtp_rtcp/source/rtp_packet_received.h" +#include "modules/rtp_rtcp/source/rtp_rtcp_interface.h" +#include "rtc_base/checks.h" #include "rtc_base/logging.h" -#include "rtc_base/numerics/safe_minmax.h" -#include "rtc_base/time_utils.h" +#include "rtc_base/synchronization/mutex.h" namespace webrtc { @@ -59,8 +75,6 @@ AudioIngress::~AudioIngress() = default; AudioMixer::Source::AudioFrameInfo AudioIngress::GetAudioFrameWithInfo( int sampling_rate, AudioFrame* audio_frame) { - audio_frame->sample_rate_hz_ = sampling_rate; - // Get 10ms raw PCM data from the ACM. bool muted = false; { diff --git a/audio/voip/voip_core.cc b/audio/voip/voip_core.cc index 11586d0f64..a557c3567a 100644 --- a/audio/voip/voip_core.cc +++ b/audio/voip/voip_core.cc @@ -33,7 +33,7 @@ constexpr uint16_t kAudioDeviceId = 0; // Maximum value range limit on ChannelId. This can be increased without any // side effect and only set at this moderate value for better readability for // logging. -static constexpr int kMaxChannelId = 100000; +constexpr int kMaxChannelId = 100000; } // namespace diff --git a/build_overrides/build.gni b/build_overrides/build.gni index 10cedb7525..4cb3f53760 100644 --- a/build_overrides/build.gni +++ b/build_overrides/build.gni @@ -49,15 +49,6 @@ if (host_os == "mac" || host_os == "linux") { } declare_args() { - # WebRTC doesn't depend on //base from production code but only for testing - # purposes. In any case, it doesn't depend on //third_party/perfetto which - # is used for base tracing, so this feature is disabled. - enable_base_tracing = false - - # TODO(b/336718643): Remove use_perfetto_client_library_flag. - use_perfetto_client_library = false - use_perfetto_trace_processor = false - # Limits the defined //third_party/android_deps targets to only "buildCompile" # and "buildCompileNoDeps" targets. This is useful for third-party # repositories which do not use JUnit tests. For instance, diff --git a/call/BUILD.gn b/call/BUILD.gn index cf4ad08d15..7334d82cf1 100644 --- a/call/BUILD.gn +++ b/call/BUILD.gn @@ -79,6 +79,7 @@ rtc_library("call_interfaces") { "../rtc_base/network:sent_packet", "../video/config:encoder_config", "//third_party/abseil-cpp/absl/functional:any_invocable", + "//third_party/abseil-cpp/absl/strings", "//third_party/abseil-cpp/absl/strings:string_view", ] } @@ -401,6 +402,7 @@ rtc_library("video_send_stream_api") { ] deps = [ ":rtp_interfaces", + "../api:array_view", "../api:frame_transformer_interface", "../api:rtp_parameters", "../api:rtp_sender_interface", @@ -515,6 +517,7 @@ if (rtc_include_tests) { "../api:array_view", "../api:bitrate_allocation", "../api:create_frame_generator", + "../api:field_trials", "../api:frame_transformer_interface", "../api:make_ref_counted", "../api:mock_audio_mixer", @@ -531,7 +534,6 @@ if (rtc_include_tests) { "../api/test/network_emulation", "../api/test/video:function_video_factory", "../api/transport:bitrate_settings", - "../api/transport:field_trial_based_config", "../api/transport:network_control", "../api/transport/rtp:dependency_descriptor", "../api/units:data_rate", @@ -572,13 +574,12 @@ if (rtc_include_tests) { "../rtc_base:timeutils", "../rtc_base/synchronization:mutex", "../test:audio_codec_mocks", + "../test:create_test_field_trials", "../test:encoder_settings", - "../test:explicit_key_value_config", "../test:fake_video_codecs", "../test:frame_generator_capturer", "../test:mock_transport", "../test:run_loop", - "../test:scoped_key_value_config", "../test:test_common", "../test:test_support", "../test:video_test_constants", diff --git a/call/adaptation/BUILD.gn b/call/adaptation/BUILD.gn index c6e5d8f5bf..7425e5b5a3 100644 --- a/call/adaptation/BUILD.gn +++ b/call/adaptation/BUILD.gn @@ -89,10 +89,11 @@ if (rtc_include_tests) { "../../rtc_base:stringutils", "../../rtc_base:task_queue_for_test", "../../rtc_base:threading", - "../../test:scoped_key_value_config", + "../../test:create_test_field_trials", "../../test:test_support", "../../test:wait_until", "../../video/config:encoder_config", + "//third_party/abseil-cpp/absl/strings", ] } diff --git a/call/adaptation/resource_adaptation_processor_unittest.cc b/call/adaptation/resource_adaptation_processor_unittest.cc index fe60171c2a..d698d03047 100644 --- a/call/adaptation/resource_adaptation_processor_unittest.cc +++ b/call/adaptation/resource_adaptation_processor_unittest.cc @@ -29,9 +29,9 @@ #include "rtc_base/task_queue_for_test.h" #include "rtc_base/thread.h" #include "rtc_base/thread_annotations.h" +#include "test/create_test_field_trials.h" #include "test/gmock.h" #include "test/gtest.h" -#include "test/scoped_key_value_config.h" #include "test/wait_until.h" namespace webrtc { @@ -103,7 +103,7 @@ class ResourceAdaptationProcessorTest : public ::testing::Test { video_stream_adapter_( std::make_unique(&input_state_provider_, &frame_rate_provider_, - field_trials_)), + CreateTestFieldTrials())), processor_(std::make_unique( video_stream_adapter_.get())) { video_stream_adapter_->AddRestrictionsListener(&restrictions_listener_); @@ -147,7 +147,6 @@ class ResourceAdaptationProcessorTest : public ::testing::Test { protected: AutoThread main_thread_; - test::ScopedKeyValueConfig field_trials_; FakeFrameRateProvider frame_rate_provider_; VideoStreamInputStateProvider input_state_provider_; scoped_refptr resource_; diff --git a/call/adaptation/video_stream_adapter_unittest.cc b/call/adaptation/video_stream_adapter_unittest.cc index 4e57883d89..16d070b3ad 100644 --- a/call/adaptation/video_stream_adapter_unittest.cc +++ b/call/adaptation/video_stream_adapter_unittest.cc @@ -14,6 +14,7 @@ #include #include +#include "absl/strings/str_cat.h" #include "api/adaptation/resource.h" #include "api/rtp_parameters.h" #include "api/scoped_refptr.h" @@ -26,10 +27,9 @@ #include "call/adaptation/video_source_restrictions.h" #include "call/adaptation/video_stream_input_state.h" #include "rtc_base/checks.h" -#include "rtc_base/string_encode.h" +#include "test/create_test_field_trials.h" #include "test/gmock.h" #include "test/gtest.h" -#include "test/scoped_key_value_config.h" namespace webrtc { @@ -148,14 +148,12 @@ class MockAdaptationConstraint : public AdaptationConstraint { class VideoStreamAdapterTest : public ::testing::Test { public: VideoStreamAdapterTest() - : field_trials_(BalancedFieldTrialConfig()), - resource_(FakeResource::Create("FakeResource")), + : resource_(FakeResource::Create("FakeResource")), adapter_(&input_state_provider_, &encoder_stats_observer_, - field_trials_) {} + CreateTestFieldTrials(BalancedFieldTrialConfig())) {} protected: - test::ScopedKeyValueConfig field_trials_; FakeVideoStreamInputStateProvider input_state_provider_; scoped_refptr resource_; testing::StrictMock encoder_stats_observer_; @@ -918,11 +916,10 @@ TEST_F(VideoStreamAdapterTest, AdaptationConstraintDisallowsAdaptationsUp) { TEST(VideoStreamAdapterDeathTest, SetDegradationPreferenceInvalidatesAdaptations) { - test::ScopedKeyValueConfig field_trials; FakeVideoStreamInputStateProvider input_state_provider; testing::StrictMock encoder_stats_observer_; VideoStreamAdapter adapter(&input_state_provider, &encoder_stats_observer_, - field_trials); + CreateTestFieldTrials()); adapter.SetDegradationPreference(DegradationPreference::MAINTAIN_FRAMERATE); input_state_provider.SetInputState(1280 * 720, 30, kDefaultMinPixelsPerFrame); Adaptation adaptation = adapter.GetAdaptationDown(); @@ -931,11 +928,10 @@ TEST(VideoStreamAdapterDeathTest, } TEST(VideoStreamAdapterDeathTest, AdaptDownInvalidatesAdaptations) { - test::ScopedKeyValueConfig field_trials; FakeVideoStreamInputStateProvider input_state_provider; testing::StrictMock encoder_stats_observer_; VideoStreamAdapter adapter(&input_state_provider, &encoder_stats_observer_, - field_trials); + CreateTestFieldTrials()); adapter.SetDegradationPreference(DegradationPreference::MAINTAIN_RESOLUTION); input_state_provider.SetInputState(1280 * 720, 30, kDefaultMinPixelsPerFrame); Adaptation adaptation = adapter.GetAdaptationDown(); diff --git a/call/audio_send_stream.cc b/call/audio_send_stream.cc index 612d27a60c..e2f3862f54 100644 --- a/call/audio_send_stream.cc +++ b/call/audio_send_stream.cc @@ -14,9 +14,9 @@ #include +#include "absl/strings/str_cat.h" #include "api/audio_codecs/audio_format.h" #include "api/call/transport.h" -#include "rtc_base/string_encode.h" #include "rtc_base/strings/string_builder.h" namespace webrtc { @@ -59,6 +59,14 @@ std::string AudioSendStream::Config::Rtp::ToString() const { if (!mid.empty()) { ss << ", mid: " << mid; } + ss << ", csrcs: ["; + for (size_t i = 0; i < csrcs.size(); ++i) { + ss << csrcs[i]; + if (i != csrcs.size() - 1) { + ss << ", "; + } + } + ss << ']'; ss << ", extmap-allow-mixed: " << (extmap_allow_mixed ? "true" : "false"); ss << ", extensions: ["; for (size_t i = 0; i < extensions.size(); ++i) { diff --git a/call/audio_send_stream.h b/call/audio_send_stream.h index d1b3e64ba3..2cc5397e31 100644 --- a/call/audio_send_stream.h +++ b/call/audio_send_stream.h @@ -99,6 +99,9 @@ class AudioSendStream : public AudioSender { // included in the list of extensions. std::string mid; + // The list of CSRCs to be included in the RTP header. + std::vector csrcs; + // Corresponds to the SDP attribute extmap-allow-mixed. bool extmap_allow_mixed = false; diff --git a/call/bitrate_allocator.cc b/call/bitrate_allocator.cc index 0a63398878..434fd81776 100644 --- a/call/bitrate_allocator.cc +++ b/call/bitrate_allocator.cc @@ -462,7 +462,6 @@ BitrateAllocator::BitrateAllocator(LimitObserver* limit_observer, DataRate upper_elastic_rate_limit) : limit_observer_(limit_observer), last_target_bps_(0), - last_stable_target_bps_(0), last_non_zero_bitrate_bps_(kDefaultBitrateBps), last_fraction_loss_(0), last_rtt_(0), @@ -486,7 +485,6 @@ void BitrateAllocator::UpdateStartRate(uint32_t start_rate_bps) { void BitrateAllocator::OnNetworkEstimateChanged(TargetTransferRate msg) { RTC_DCHECK_RUN_ON(&sequenced_checker_); last_target_bps_ = msg.target_rate.bps(); - last_stable_target_bps_ = msg.stable_target_rate.bps(); last_non_zero_bitrate_bps_ = last_target_bps_ > 0 ? last_target_bps_ : last_non_zero_bitrate_bps_; @@ -505,17 +503,11 @@ void BitrateAllocator::OnNetworkEstimateChanged(TargetTransferRate msg) { auto allocation = AllocateBitrates(allocatable_tracks_, last_target_bps_, upper_elastic_rate_limit_); - auto stable_bitrate_allocation = AllocateBitrates( - allocatable_tracks_, last_stable_target_bps_, DataRate::Zero()); for (auto& track : allocatable_tracks_) { uint32_t allocated_bitrate = allocation[track.observer]; - uint32_t allocated_stable_target_rate = - stable_bitrate_allocation[track.observer]; BitrateAllocationUpdate update; update.target_bitrate = DataRate::BitsPerSec(allocated_bitrate); - update.stable_target_bitrate = - DataRate::BitsPerSec(allocated_stable_target_rate); update.packet_loss_ratio = last_fraction_loss_ / 256.0; update.round_trip_time = TimeDelta::Millis(last_rtt_); update.bwe_period = TimeDelta::Millis(last_bwe_period_ms_); @@ -574,16 +566,10 @@ void BitrateAllocator::AddObserver(BitrateAllocatorObserver* observer, auto allocation = AllocateBitrates(allocatable_tracks_, last_target_bps_, upper_elastic_rate_limit_); - auto stable_bitrate_allocation = AllocateBitrates( - allocatable_tracks_, last_stable_target_bps_, DataRate::Zero()); for (auto& track : allocatable_tracks_) { uint32_t allocated_bitrate = allocation[track.observer]; - uint32_t allocated_stable_bitrate = - stable_bitrate_allocation[track.observer]; BitrateAllocationUpdate update; update.target_bitrate = DataRate::BitsPerSec(allocated_bitrate); - update.stable_target_bitrate = - DataRate::BitsPerSec(allocated_stable_bitrate); update.packet_loss_ratio = last_fraction_loss_ / 256.0; update.round_trip_time = TimeDelta::Millis(last_rtt_); update.bwe_period = TimeDelta::Millis(last_bwe_period_ms_); @@ -600,7 +586,6 @@ void BitrateAllocator::AddObserver(BitrateAllocatorObserver* observer, BitrateAllocationUpdate update; update.target_bitrate = DataRate::Zero(); - update.stable_target_bitrate = DataRate::Zero(); update.packet_loss_ratio = last_fraction_loss_ / 256.0; update.round_trip_time = TimeDelta::Millis(last_rtt_); update.bwe_period = TimeDelta::Millis(last_bwe_period_ms_); @@ -655,16 +640,11 @@ bool BitrateAllocator::RecomputeAllocationIfNeeded() { // Calculate a new allocation and update all observers. auto allocation = AllocateBitrates(allocatable_tracks_, last_target_bps_, upper_elastic_rate_limit_); - auto stable_bitrate_allocation = AllocateBitrates( - allocatable_tracks_, last_stable_target_bps_, DataRate::Zero()); for (auto& track : allocatable_tracks_) { DataRate allocated_bitrate = DataRate::BitsPerSec(allocation[track.observer]); - DataRate allocated_stable_bitrate = - DataRate::BitsPerSec(stable_bitrate_allocation[track.observer]); BitrateAllocationUpdate update; update.target_bitrate = allocated_bitrate; - update.stable_target_bitrate = allocated_stable_bitrate; update.packet_loss_ratio = last_fraction_loss_ / 256.0; update.round_trip_time = TimeDelta::Millis(last_rtt_); update.bwe_period = TimeDelta::Millis(last_bwe_period_ms_); diff --git a/call/bitrate_allocator.h b/call/bitrate_allocator.h index 270a34e1f7..ef6bd2474a 100644 --- a/call/bitrate_allocator.h +++ b/call/bitrate_allocator.h @@ -174,7 +174,6 @@ class BitrateAllocator : public BitrateAllocatorInterface { std::vector allocatable_tracks_ RTC_GUARDED_BY(&sequenced_checker_); uint32_t last_target_bps_ RTC_GUARDED_BY(&sequenced_checker_); - uint32_t last_stable_target_bps_ RTC_GUARDED_BY(&sequenced_checker_); uint32_t last_non_zero_bitrate_bps_ RTC_GUARDED_BY(&sequenced_checker_); uint8_t last_fraction_loss_ RTC_GUARDED_BY(&sequenced_checker_); int64_t last_rtt_ RTC_GUARDED_BY(&sequenced_checker_); diff --git a/call/bitrate_allocator_unittest.cc b/call/bitrate_allocator_unittest.cc index 63f270f3e2..13f00abeb7 100644 --- a/call/bitrate_allocator_unittest.cc +++ b/call/bitrate_allocator_unittest.cc @@ -18,12 +18,13 @@ #include "absl/strings/string_view.h" #include "api/call/bitrate_allocation.h" +#include "api/field_trials.h" #include "api/transport/network_types.h" #include "api/units/data_rate.h" #include "api/units/time_delta.h" #include "api/units/timestamp.h" #include "rtc_base/numerics/safe_conversions.h" -#include "test/explicit_key_value_config.h" +#include "test/create_test_field_trials.h" #include "test/gmock.h" #include "test/gtest.h" @@ -110,7 +111,6 @@ TargetTransferRate CreateTargetRateMessage(uint32_t target_bitrate_bps, // messages in the test. msg.at_time = Timestamp::Seconds(10000); msg.target_rate = DataRate::BitsPerSec(target_bitrate_bps); - msg.stable_target_rate = msg.target_rate; msg.network_estimate.bandwidth = msg.target_rate; msg.network_estimate.loss_rate_ratio = fraction_loss / 255.0; msg.network_estimate.round_trip_time = TimeDelta::Millis(rtt_ms); @@ -126,7 +126,7 @@ class BitrateAllocatorTest : public ::testing::Test { allocator_->OnNetworkEstimateChanged( CreateTargetRateMessage(300000u, 0, 0, kDefaultProbingIntervalMs)); } - ~BitrateAllocatorTest() {} + ~BitrateAllocatorTest() override {} void AddObserver( BitrateAllocatorObserver* observer, uint32_t min_bitrate_bps, @@ -326,7 +326,7 @@ class BitrateAllocatorTestNoEnforceMin : public ::testing::Test { allocator_->OnNetworkEstimateChanged( CreateTargetRateMessage(300000u, 0, 0, kDefaultProbingIntervalMs)); } - ~BitrateAllocatorTestNoEnforceMin() {} + ~BitrateAllocatorTestNoEnforceMin() override {} void AddObserver(BitrateAllocatorObserver* observer, uint32_t min_bitrate_bps, uint32_t max_bitrate_bps, @@ -1060,7 +1060,7 @@ TEST_F(BitrateAllocatorTest, PriorityRateThreeObserversTwoAllocatedToMax) { } TEST_F(BitrateAllocatorTest, ElasticRateAllocationCanBorrowUnsedRate) { - test::ExplicitKeyValueConfig field_trials( + FieldTrials field_trials = CreateTestFieldTrials( "WebRTC-ElasticBitrateAllocation/upper_limit:200bps/"); ReconfigureAllocator( GetElasticRateAllocationFieldTrialParameter(field_trials)); @@ -1085,9 +1085,8 @@ TEST_F(BitrateAllocatorTest, ElasticRateAllocationCanBorrowUnsedRate) { } TEST_F(BitrateAllocatorTest, ElasticRateAllocationDefaultsInactive) { - test::ExplicitKeyValueConfig field_trials(""); ReconfigureAllocator( - GetElasticRateAllocationFieldTrialParameter(field_trials)); + GetElasticRateAllocationFieldTrialParameter(CreateTestFieldTrials())); TestBitrateObserver observer_consume; TestContributingBitrateObserver observer_contribute; AddObserver(&observer_consume, 10, 100, 0, false, 1.0, @@ -1107,7 +1106,7 @@ TEST_F(BitrateAllocatorTest, ElasticRateAllocationDefaultsInactive) { } TEST_F(BitrateAllocatorTest, ElasticRateAllocationDontExceedMaxBitrate) { - test::ExplicitKeyValueConfig field_trials( + FieldTrials field_trials = CreateTestFieldTrials( "WebRTC-ElasticBitrateAllocation/upper_limit:200bps/"); ReconfigureAllocator( GetElasticRateAllocationFieldTrialParameter(field_trials)); @@ -1134,9 +1133,9 @@ TEST_F(BitrateAllocatorTest, ElasticRateAllocationDontExceedMaxBitrate) { TEST_F(BitrateAllocatorTest, ElasticRateAllocationStayWithinUpperLimit) { uint32_t upper_limit = 70; - test::ExplicitKeyValueConfig field_trials( - "WebRTC-ElasticBitrateAllocation/upper_limit:" + - std::to_string(upper_limit) + "bps/"); + FieldTrials field_trials = + CreateTestFieldTrials("WebRTC-ElasticBitrateAllocation/upper_limit:" + + std::to_string(upper_limit) + "bps/"); ReconfigureAllocator( GetElasticRateAllocationFieldTrialParameter(field_trials)); TestBitrateObserver observer_consume; @@ -1161,9 +1160,9 @@ TEST_F(BitrateAllocatorTest, ElasticRateAllocationStayWithinUpperLimit) { TEST_F(BitrateAllocatorTest, ElasticRateAllocationDontReduceAllocation) { uint32_t upper_limit = 70; - test::ExplicitKeyValueConfig field_trials( - "WebRTC-ElasticBitrateAllocation/upper_limit:" + - std::to_string(upper_limit) + "bps/"); + FieldTrials field_trials = + CreateTestFieldTrials("WebRTC-ElasticBitrateAllocation/upper_limit:" + + std::to_string(upper_limit) + "bps/"); ReconfigureAllocator( GetElasticRateAllocationFieldTrialParameter(field_trials)); TestBitrateObserver observer_consume; diff --git a/call/bitrate_estimator_tests.cc b/call/bitrate_estimator_tests.cc index 28d401d309..58cbaea044 100644 --- a/call/bitrate_estimator_tests.cc +++ b/call/bitrate_estimator_tests.cc @@ -118,9 +118,9 @@ class BitrateEstimatorTest : public test::CallTest { public: BitrateEstimatorTest() : receive_config_(nullptr) {} - virtual ~BitrateEstimatorTest() { EXPECT_TRUE(streams_.empty()); } + ~BitrateEstimatorTest() override { EXPECT_TRUE(streams_.empty()); } - virtual void SetUp() { + void SetUp() override { SendTask(task_queue(), [this]() { RegisterRtpExtension( RtpExtension(RtpExtension::kTimestampOffsetUri, kTOFExtensionId)); @@ -157,7 +157,7 @@ class BitrateEstimatorTest : public test::CallTest { }); } - virtual void TearDown() { + void TearDown() override { SendTask(task_queue(), [this]() { for (auto* stream : streams_) { stream->StopSending(); diff --git a/call/fake_network_pipe_unittest.cc b/call/fake_network_pipe_unittest.cc index 05a348cb36..dc8c0ca02b 100644 --- a/call/fake_network_pipe_unittest.cc +++ b/call/fake_network_pipe_unittest.cc @@ -45,7 +45,7 @@ class MockReceiver : public PacketReceiver { RtpPacketReceived packet, OnUndemuxablePacketHandler undemuxable_packet_handler), (override)); - virtual ~MockReceiver() = default; + ~MockReceiver() override = default; }; class ReorderTestReceiver : public MockReceiver { diff --git a/call/flexfec_receive_stream_unittest.cc b/call/flexfec_receive_stream_unittest.cc index e49d02d31b..0621014bbb 100644 --- a/call/flexfec_receive_stream_unittest.cc +++ b/call/flexfec_receive_stream_unittest.cc @@ -89,7 +89,9 @@ class FlexfecReceiveStreamTest : public ::testing::Test { receive_stream_->RegisterWithTransport(&rtp_stream_receiver_controller_); } - ~FlexfecReceiveStreamTest() { receive_stream_->UnregisterFromTransport(); } + ~FlexfecReceiveStreamTest() override { + receive_stream_->UnregisterFromTransport(); + } AutoThread main_thread_; MockTransport rtcp_send_transport_; diff --git a/call/payload_type_picker.cc b/call/payload_type_picker.cc index 3ce57cc502..9b4e7f1163 100644 --- a/call/payload_type_picker.cc +++ b/call/payload_type_picker.cc @@ -33,11 +33,11 @@ namespace { // Due to interoperability issues with old Chrome/WebRTC versions that // ignore the [35, 63] range prefer the lower range for new codecs. -static const int kFirstDynamicPayloadTypeLowerRange = 35; -static const int kLastDynamicPayloadTypeLowerRange = 63; +const int kFirstDynamicPayloadTypeLowerRange = 35; +const int kLastDynamicPayloadTypeLowerRange = 63; -static const int kFirstDynamicPayloadTypeUpperRange = 96; -static const int kLastDynamicPayloadTypeUpperRange = 127; +const int kFirstDynamicPayloadTypeUpperRange = 96; +const int kLastDynamicPayloadTypeUpperRange = 127; // Note: The only fields we need from a Codec are the type (audio/video), // the subtype (vp8/h264/....), the clock rate, the channel count, and the diff --git a/call/rampup_tests.cc b/call/rampup_tests.cc index 3a18e8c6d8..243a374795 100644 --- a/call/rampup_tests.cc +++ b/call/rampup_tests.cc @@ -66,12 +66,12 @@ using test::ImprovementDirection; using test::Unit; constexpr TimeDelta kPollInterval = TimeDelta::Millis(20); -static const int kExpectedHighVideoBitrateBps = 80000; -static const int kExpectedHighAudioBitrateBps = 30000; -static const int kLowBandwidthLimitBps = 20000; +const int kExpectedHighVideoBitrateBps = 80000; +const int kExpectedHighAudioBitrateBps = 30000; +const int kLowBandwidthLimitBps = 20000; // Set target detected bitrate to slightly larger than the target bitrate to // avoid flakiness. -static const int kLowBitrateMarginBps = 2000; +const int kLowBitrateMarginBps = 2000; std::vector GenerateSsrcs(size_t num_streams, uint32_t ssrc_offset) { std::vector ssrcs; diff --git a/call/receive_time_calculator_unittest.cc b/call/receive_time_calculator_unittest.cc index 61275f884e..f7a382c228 100644 --- a/call/receive_time_calculator_unittest.cc +++ b/call/receive_time_calculator_unittest.cc @@ -18,10 +18,11 @@ #include #include +#include "api/field_trials.h" #include "rtc_base/random.h" #include "rtc_base/time_utils.h" +#include "test/create_test_field_trials.h" #include "test/gtest.h" -#include "test/scoped_key_value_config.h" namespace webrtc { namespace test { @@ -58,7 +59,7 @@ class EmulatedClock { class EmulatedMonotoneousClock : public EmulatedClock { public: explicit EmulatedMonotoneousClock(int seed) : EmulatedClock(seed) {} - ~EmulatedMonotoneousClock() = default; + ~EmulatedMonotoneousClock() override = default; int64_t Query(int64_t time_us) { int64_t skip_us = UpdateClock(time_us); @@ -111,7 +112,7 @@ class EmulatedNonMonotoneousClock : public EmulatedClock { : EmulatedClock(seed, drift) { Pregenerate(duration_us); } - ~EmulatedNonMonotoneousClock() = default; + ~EmulatedNonMonotoneousClock() override = default; void Pregenerate(int64_t duration_us) { int64_t time_since_reset_us = kMinTimeBetweenResetsUs; @@ -169,7 +170,7 @@ class EmulatedNonMonotoneousClock : public EmulatedClock { }; TEST(ClockRepair, NoClockDrift) { - test::ScopedKeyValueConfig field_trials; + FieldTrials field_trials = CreateTestFieldTrials(); const int kSeeds = 10; const int kFirstSeed = 1; const int64_t kRuntimeUs = 10 * kNumMicrosecsPerSec; diff --git a/call/rtp_demuxer_unittest.cc b/call/rtp_demuxer_unittest.cc index 5cbc1bc641..83e5422b73 100644 --- a/call/rtp_demuxer_unittest.cc +++ b/call/rtp_demuxer_unittest.cc @@ -36,7 +36,7 @@ using ::testing::NiceMock; class RtpDemuxerTest : public ::testing::Test { protected: - ~RtpDemuxerTest() { + ~RtpDemuxerTest() override { for (auto* sink : sinks_to_tear_down_) { demuxer_.RemoveSink(sink); } diff --git a/call/rtp_payload_params_unittest.cc b/call/rtp_payload_params_unittest.cc index 1f3214454b..e38235f95a 100644 --- a/call/rtp_payload_params_unittest.cc +++ b/call/rtp_payload_params_unittest.cc @@ -18,7 +18,7 @@ #include #include "absl/container/inlined_vector.h" -#include "api/transport/field_trial_based_config.h" +#include "api/field_trials.h" #include "api/transport/rtp/dependency_descriptor.h" #include "api/video/color_space.h" #include "api/video/encoded_image.h" @@ -35,9 +35,9 @@ #include "modules/video_coding/codecs/vp8/include/vp8_globals.h" #include "modules/video_coding/codecs/vp9/include/vp9_globals.h" #include "modules/video_coding/include/video_codec_interface.h" +#include "test/create_test_field_trials.h" #include "test/gmock.h" #include "test/gtest.h" -#include "test/scoped_key_value_config.h" namespace webrtc { namespace { @@ -69,7 +69,7 @@ TEST(RtpPayloadParamsTest, InfoMappedToRtpVideoHeader_Vp8) { state2.tl0_pic_idx = kTl0PicIdx; std::map states = {{kSsrc2, state2}}; - RtpPayloadParams params(kSsrc2, &state2, FieldTrialBasedConfig()); + RtpPayloadParams params(kSsrc2, &state2, CreateTestFieldTrials()); EncodedImage encoded_image; encoded_image.rotation_ = kVideoRotation_90; encoded_image.content_type_ = VideoContentType::SCREENSHARE; @@ -109,7 +109,7 @@ TEST(RtpPayloadParamsTest, InfoMappedToRtpVideoHeader_Vp9) { RtpPayloadState state; state.picture_id = kPictureId; state.tl0_pic_idx = kTl0PicIdx; - RtpPayloadParams params(kSsrc1, &state, FieldTrialBasedConfig()); + RtpPayloadParams params(kSsrc1, &state, CreateTestFieldTrials()); EncodedImage encoded_image; encoded_image.rotation_ = kVideoRotation_90; @@ -172,7 +172,7 @@ TEST(RtpPayloadParamsTest, PictureIdIsSetForVp8) { CodecSpecificInfo codec_info; codec_info.codecType = kVideoCodecVP8; - RtpPayloadParams params(kSsrc1, &state, FieldTrialBasedConfig()); + RtpPayloadParams params(kSsrc1, &state, CreateTestFieldTrials()); RTPVideoHeader header = params.GetRtpVideoHeader(encoded_image, &codec_info, kDontCare); EXPECT_EQ(kVideoCodecVP8, header.codec); @@ -195,7 +195,7 @@ TEST(RtpPayloadParamsTest, PictureIdWraps) { codec_info.codecType = kVideoCodecVP8; codec_info.codecSpecific.VP8.temporalIdx = kNoTemporalIdx; - RtpPayloadParams params(kSsrc1, &state, FieldTrialBasedConfig()); + RtpPayloadParams params(kSsrc1, &state, CreateTestFieldTrials()); RTPVideoHeader header = params.GetRtpVideoHeader(encoded_image, &codec_info, kDontCare); EXPECT_EQ(kVideoCodecVP8, header.codec); @@ -211,7 +211,7 @@ TEST(RtpPayloadParamsTest, CreatesGenericDescriptorForVp8) { constexpr auto kNotPresent = DecodeTargetIndication::kNotPresent; RtpPayloadState state; - RtpPayloadParams params(kSsrc1, &state, FieldTrialBasedConfig()); + RtpPayloadParams params(kSsrc1, &state, CreateTestFieldTrials()); EncodedImage key_frame_image; key_frame_image._frameType = VideoFrameType::kVideoFrameKey; @@ -299,7 +299,7 @@ TEST(RtpPayloadParamsTest, Tl0PicIdxUpdatedForVp8) { codec_info.codecType = kVideoCodecVP8; codec_info.codecSpecific.VP8.temporalIdx = 1; - RtpPayloadParams params(kSsrc1, &state, FieldTrialBasedConfig()); + RtpPayloadParams params(kSsrc1, &state, CreateTestFieldTrials()); RTPVideoHeader header = params.GetRtpVideoHeader(encoded_image, &codec_info, kDontCare); @@ -335,7 +335,7 @@ TEST(RtpPayloadParamsTest, Tl0PicIdxUpdatedForVp9) { codec_info.codecSpecific.VP9.temporal_idx = 1; codec_info.codecSpecific.VP9.first_frame_in_picture = true; - RtpPayloadParams params(kSsrc1, &state, FieldTrialBasedConfig()); + RtpPayloadParams params(kSsrc1, &state, CreateTestFieldTrials()); RTPVideoHeader header = params.GetRtpVideoHeader(encoded_image, &codec_info, kDontCare); @@ -377,7 +377,7 @@ TEST(RtpPayloadParamsTest, GenerateFrameIdWhenExternalFrameIdsAreNotProvided) { CodecSpecificInfo codec_info; codec_info.codecType = kVideoCodecGeneric; - RtpPayloadParams params(kSsrc1, &state, FieldTrialBasedConfig()); + RtpPayloadParams params(kSsrc1, &state, CreateTestFieldTrials()); RTPVideoHeader header = params.GetRtpVideoHeader(encoded_image, &codec_info, std::nullopt); @@ -393,7 +393,8 @@ TEST(RtpPayloadParamsTest, GenerateFrameIdWhenExternalFrameIdsAreNotProvided) { } TEST(RtpPayloadParamsTest, PictureIdForOldGenericFormat) { - test::ScopedKeyValueConfig field_trials("WebRTC-GenericPictureId/Enabled/"); + FieldTrials field_trials = + CreateTestFieldTrials("WebRTC-GenericPictureId/Enabled/"); RtpPayloadState state{}; EncodedImage encoded_image; @@ -426,7 +427,7 @@ TEST(RtpPayloadParamsTest, GenericDescriptorForGenericCodec) { CodecSpecificInfo codec_info; codec_info.codecType = kVideoCodecGeneric; - RtpPayloadParams params(kSsrc1, &state, FieldTrialBasedConfig()); + RtpPayloadParams params(kSsrc1, &state, CreateTestFieldTrials()); RTPVideoHeader header = params.GetRtpVideoHeader(encoded_image, &codec_info, 0); @@ -458,7 +459,7 @@ TEST(RtpPayloadParamsTest, SetsGenericFromGenericFrameInfo) { EncodedImage encoded_image; CodecSpecificInfo codec_info; - RtpPayloadParams params(kSsrc1, &state, FieldTrialBasedConfig()); + RtpPayloadParams params(kSsrc1, &state, CreateTestFieldTrials()); encoded_image._frameType = VideoFrameType::kVideoFrameKey; codec_info.generic_frame_info = @@ -502,7 +503,7 @@ class RtpPayloadParamsVp8ToGenericTest : public ::testing::Test { enum LayerSync { kNoSync, kSync }; RtpPayloadParamsVp8ToGenericTest() - : state_(), params_(123, &state_, trials_config_) {} + : state_(), params_(123, &state_, CreateTestFieldTrials()) {} void ConvertAndCheck(int temporal_index, int64_t shared_frame_id, @@ -538,7 +539,6 @@ class RtpPayloadParamsVp8ToGenericTest : public ::testing::Test { } protected: - FieldTrialBasedConfig trials_config_; RtpPayloadState state_; RtpPayloadParams params_; }; @@ -593,7 +593,7 @@ TEST_F(RtpPayloadParamsVp8ToGenericTest, FrameIdGaps) { TEST(RtpPayloadParamsVp9ToGenericTest, NoScalability) { RtpPayloadState state; - RtpPayloadParams params(/*ssrc=*/123, &state, FieldTrialBasedConfig()); + RtpPayloadParams params(/*ssrc=*/123, &state, CreateTestFieldTrials()); EncodedImage encoded_image; CodecSpecificInfo codec_info; @@ -645,7 +645,7 @@ TEST(RtpPayloadParamsVp9ToGenericTest, NoScalability) { TEST(RtpPayloadParamsVp9ToGenericTest, NoScalabilityNonFlexibleMode) { RtpPayloadState state; - RtpPayloadParams params(/*ssrc=*/123, &state, FieldTrialBasedConfig()); + RtpPayloadParams params(/*ssrc=*/123, &state, CreateTestFieldTrials()); EncodedImage encoded_image; CodecSpecificInfo codec_info; @@ -698,7 +698,7 @@ TEST(RtpPayloadParamsVp9ToGenericTest, TemporalScalabilityWith2Layers) { // / / / ... // 0---2---4--- RtpPayloadState state; - RtpPayloadParams params(/*ssrc=*/123, &state, FieldTrialBasedConfig()); + RtpPayloadParams params(/*ssrc=*/123, &state, CreateTestFieldTrials()); EncodedImage image; CodecSpecificInfo info; @@ -809,7 +809,7 @@ TEST(RtpPayloadParamsVp9ToGenericTest, TemporalScalabilityWith3Layers) { // Test with 3 temporal layers structure that is not used by webrtc, but used // by chromium: https://imgur.com/pURAGvp RtpPayloadState state; - RtpPayloadParams params(/*ssrc=*/123, &state, FieldTrialBasedConfig()); + RtpPayloadParams params(/*ssrc=*/123, &state, CreateTestFieldTrials()); EncodedImage image; CodecSpecificInfo info; @@ -963,7 +963,7 @@ TEST(RtpPayloadParamsVp9ToGenericTest, SpatialScalabilityKSvc) { // | ... // 0---2-- RtpPayloadState state; - RtpPayloadParams params(/*ssrc=*/123, &state, FieldTrialBasedConfig()); + RtpPayloadParams params(/*ssrc=*/123, &state, CreateTestFieldTrials()); EncodedImage image; CodecSpecificInfo info; @@ -1072,7 +1072,7 @@ TEST(RtpPayloadParamsVp9ToGenericTest, // | ... // S0 1---3-- RtpPayloadState state; - RtpPayloadParams params(/*ssrc=*/123, &state, FieldTrialBasedConfig()); + RtpPayloadParams params(/*ssrc=*/123, &state, CreateTestFieldTrials()); EncodedImage image; CodecSpecificInfo info; @@ -1174,7 +1174,7 @@ TEST(RtpPayloadParamsVp9ToGenericTest, ChangeFirstActiveLayer) { // // S0 0---2 6 RtpPayloadState state; - RtpPayloadParams params(/*ssrc=*/123, &state, FieldTrialBasedConfig()); + RtpPayloadParams params(/*ssrc=*/123, &state, CreateTestFieldTrials()); EncodedImage image; CodecSpecificInfo info; @@ -1336,7 +1336,7 @@ class RtpPayloadParamsH264ToGenericTest : public ::testing::Test { enum LayerSync { kNoSync, kSync }; RtpPayloadParamsH264ToGenericTest() - : state_(), params_(123, &state_, trials_config_) {} + : state_(), params_(123, &state_, CreateTestFieldTrials()) {} void ConvertAndCheck(int temporal_index, int64_t shared_frame_id, @@ -1381,7 +1381,6 @@ class RtpPayloadParamsH264ToGenericTest : public ::testing::Test { } protected: - FieldTrialBasedConfig trials_config_; RtpPayloadState state_; RtpPayloadParams params_; }; diff --git a/call/rtp_transport_controller_send.cc b/call/rtp_transport_controller_send.cc index dcf12b2159..f85d944db8 100644 --- a/call/rtp_transport_controller_send.cc +++ b/call/rtp_transport_controller_send.cc @@ -61,8 +61,8 @@ namespace webrtc { namespace { -static const int64_t kRetransmitWindowSizeMs = 500; -static const size_t kMaxOverheadBytes = 500; +const int64_t kRetransmitWindowSizeMs = 500; +const size_t kMaxOverheadBytes = 500; constexpr TimeDelta kPacerQueueUpdateInterval = TimeDelta::Millis(25); diff --git a/call/rtp_video_sender.cc b/call/rtp_video_sender.cc index 4943443db1..06ce7b36ec 100644 --- a/call/rtp_video_sender.cc +++ b/call/rtp_video_sender.cc @@ -89,9 +89,9 @@ RtpStreamSender::~RtpStreamSender() = default; } // namespace webrtc_internal_rtp_video_sender namespace { -static const int kMinSendSidePacketHistorySize = 600; +const int kMinSendSidePacketHistorySize = 600; // We don't do MTU discovery, so assume that we have the standard ethernet MTU. -static const size_t kPathMTU = 1500; +const size_t kPathMTU = 1500; using webrtc_internal_rtp_video_sender::RtpStreamSender; @@ -625,7 +625,7 @@ EncodedImageCallback::Result RtpVideoSender::OnEncodedImage( encoded_image, params_[simulcast_index].GetRtpVideoHeader( encoded_image, codec_specific_info, frame_id), - expected_retransmission_time); + expected_retransmission_time, csrcs_); if (frame_count_observer_) { FrameCounts& counts = frame_counts_[simulcast_index]; if (encoded_image._frameType == VideoFrameType::kVideoFrameKey) { @@ -1031,6 +1031,12 @@ void RtpVideoSender::SetEncodingData(size_t width, rtp_config_.max_packet_size); } +void RtpVideoSender::SetCsrcs(ArrayView csrcs) { + MutexLock lock(&mutex_); + csrcs_.assign(csrcs.begin(), + csrcs.begin() + std::min(csrcs.size(), kRtpCsrcSize)); +} + DataRate RtpVideoSender::CalculateOverheadRate(DataRate data_rate, DataSize packet_size, DataSize overhead_per_packet, diff --git a/call/rtp_video_sender.h b/call/rtp_video_sender.h index 6fce841da7..86a5338f91 100644 --- a/call/rtp_video_sender.h +++ b/call/rtp_video_sender.h @@ -152,6 +152,12 @@ class RtpVideoSender : public RtpVideoSenderInterface, void SetEncodingData(size_t width, size_t height, size_t num_temporal_layers) RTC_LOCKS_EXCLUDED(mutex_) override; + // Sets the list of CSRCs to be included in every packet. If more than + // kRtpCsrcSize CSRCs are provided, only the first kRtpCsrcSize elements are + // kept. + void SetCsrcs(ArrayView csrcs) + RTC_LOCKS_EXCLUDED(mutex_) override; + std::vector GetSentRtpPacketInfos( uint32_t ssrc, ArrayView sequence_numbers) const @@ -201,6 +207,9 @@ class RtpVideoSender : public RtpVideoSenderInterface, const RtpConfig rtp_config_; RtpTransportControllerSendInterface* const transport_; + // The list of CSRCs to be included when sending an encoded image. + std::vector csrcs_ RTC_GUARDED_BY(mutex_); + // When using the generic descriptor we want all simulcast streams to share // one frame id space (so that the SFU can switch stream without having to // rewrite the frame id), therefore `shared_frame_id` has to live in a place diff --git a/call/rtp_video_sender_interface.h b/call/rtp_video_sender_interface.h index 069a2a8b36..70c0800f3a 100644 --- a/call/rtp_video_sender_interface.h +++ b/call/rtp_video_sender_interface.h @@ -55,6 +55,7 @@ class RtpVideoSenderInterface : public EncodedImageCallback, virtual void SetEncodingData(size_t width, size_t height, size_t num_temporal_layers) = 0; + virtual void SetCsrcs(ArrayView csrcs) = 0; virtual std::vector GetSentRtpPacketInfos( uint32_t ssrc, ArrayView sequence_numbers) const = 0; diff --git a/call/rtp_video_sender_unittest.cc b/call/rtp_video_sender_unittest.cc index cee6e8d9f0..c7c83ebc59 100644 --- a/call/rtp_video_sender_unittest.cc +++ b/call/rtp_video_sender_unittest.cc @@ -17,12 +17,14 @@ #include #include +#include "absl/strings/string_view.h" #include "api/array_view.h" #include "api/call/bitrate_allocation.h" #include "api/call/transport.h" #include "api/crypto/crypto_options.h" #include "api/environment/environment.h" #include "api/environment/environment_factory.h" +#include "api/field_trials.h" #include "api/frame_transformer_interface.h" #include "api/make_ref_counted.h" #include "api/rtp_parameters.h" @@ -61,13 +63,12 @@ #include "rtc_base/buffer.h" #include "rtc_base/checks.h" #include "rtc_base/rate_limiter.h" -#include "test/explicit_key_value_config.h" +#include "test/create_test_field_trials.h" #include "test/gmock.h" #include "test/gtest.h" #include "test/mock_transport.h" #include "test/scenario/scenario.h" #include "test/scenario/scenario_config.h" -#include "test/scoped_key_value_config.h" #include "test/time_controller/simulated_time_controller.h" #include "video/config/video_encoder_config.h" #include "video/send_statistics_proxy.h" @@ -175,10 +176,10 @@ class RtpVideoSenderTestFixture { FrameCountObserver* frame_count_observer, scoped_refptr frame_transformer, const std::vector& payload_types, - const FieldTrialsView* field_trials = nullptr) - : time_controller_(Timestamp::Millis(1000000)), + absl::string_view field_trials = "") + : field_trials_(CreateTestFieldTrials(field_trials)), + time_controller_(Timestamp::Millis(1000000)), env_(CreateEnvironment(&field_trials_, - field_trials, time_controller_.GetClock(), time_controller_.CreateTaskQueueFactory())), config_(CreateVideoSendStreamConfig(&transport_, @@ -214,7 +215,7 @@ class RtpVideoSenderTestFixture { const std::map& suspended_payload_states, FrameCountObserver* frame_count_observer, scoped_refptr frame_transformer, - const FieldTrialsView* field_trials = nullptr) + absl::string_view field_trials = "") : RtpVideoSenderTestFixture(ssrcs, rtx_ssrcs, payload_type, @@ -230,7 +231,7 @@ class RtpVideoSenderTestFixture { int payload_type, const std::map& suspended_payload_states, FrameCountObserver* frame_count_observer, - const FieldTrialsView* field_trials = nullptr) + absl::string_view field_trials = "") : RtpVideoSenderTestFixture(ssrcs, rtx_ssrcs, payload_type, @@ -245,7 +246,7 @@ class RtpVideoSenderTestFixture { const std::vector& rtx_ssrcs, int payload_type, const std::map& suspended_payload_states, - const FieldTrialsView* field_trials = nullptr) + absl::string_view field_trials = "") : RtpVideoSenderTestFixture(ssrcs, rtx_ssrcs, payload_type, @@ -264,7 +265,7 @@ class RtpVideoSenderTestFixture { void SetSending(bool sending) { router_->SetSending(sending); } private: - test::ScopedKeyValueConfig field_trials_; + FieldTrials field_trials_; NiceMock transport_; NiceMock encoder_feedback_; GlobalSimulatedTimeController time_controller_; @@ -810,12 +811,11 @@ TEST(RtpVideoSenderTest, SupportsDependencyDescriptor) { } TEST(RtpVideoSenderTest, SimulcastIndependentFrameIds) { - test::ExplicitKeyValueConfig field_trials( - "WebRTC-GenericDescriptorAuth/Disabled/"); + absl::string_view field_trials = "WebRTC-GenericDescriptorAuth/Disabled/"; const std::map kPayloadStates = { {kSsrc1, {.frame_id = 100}}, {kSsrc2, {.frame_id = 200}}}; RtpVideoSenderTestFixture test({kSsrc1, kSsrc2}, {}, kPayloadType, - kPayloadStates, &field_trials); + kPayloadStates, field_trials); test.SetSending(true); RtpHeaderExtensionMap extensions; @@ -869,13 +869,12 @@ TEST(RtpVideoSenderTest, SimulcastIndependentFrameIds) { TEST(RtpVideoSenderTest, SimulcastNoIndependentFrameIdsIfGenericDescriptorAuthIsEnabled) { - test::ExplicitKeyValueConfig field_trials( - "WebRTC-GenericDescriptorAuth/Enabled/"); + absl::string_view field_trials = "WebRTC-GenericDescriptorAuth/Enabled/"; const std::map kPayloadStates = { {kSsrc1, {.shared_frame_id = 1000, .frame_id = 100}}, {kSsrc2, {.shared_frame_id = 1000, .frame_id = 200}}}; RtpVideoSenderTestFixture test({kSsrc1, kSsrc2}, {}, kPayloadType, - kPayloadStates, &field_trials); + kPayloadStates, field_trials); test.SetSending(true); RtpHeaderExtensionMap extensions; @@ -1213,9 +1212,9 @@ TEST(RtpVideoSenderTest, } TEST(RtpVideoSenderTest, GenerateDependecyDescriptorForGenericCodecs) { - test::ScopedKeyValueConfig field_trials( - "WebRTC-GenericCodecDependencyDescriptor/Enabled/"); - RtpVideoSenderTestFixture test({kSsrc1}, {}, kPayloadType, {}, &field_trials); + absl::string_view field_trials = + "WebRTC-GenericCodecDependencyDescriptor/Enabled/"; + RtpVideoSenderTestFixture test({kSsrc1}, {}, kPayloadType, {}, field_trials); test.SetSending(true); RtpHeaderExtensionMap extensions; @@ -1337,15 +1336,15 @@ TEST(RtpVideoSenderTest, SimulcastSenderRegistersFrameTransformers) { } TEST(RtpVideoSenderTest, OverheadIsSubtractedFromTargetBitrate) { - test::ScopedKeyValueConfig field_trials( - "WebRTC-Video-UseFrameRateForOverhead/Enabled/"); + absl::string_view field_trials = + "WebRTC-Video-UseFrameRateForOverhead/Enabled/"; // TODO(jakobi): RTP header size should not be hard coded. constexpr uint32_t kRtpHeaderSizeBytes = 20; constexpr uint32_t kTransportPacketOverheadBytes = 40; constexpr uint32_t kOverheadPerPacketBytes = kRtpHeaderSizeBytes + kTransportPacketOverheadBytes; - RtpVideoSenderTestFixture test({kSsrc1}, {}, kPayloadType, {}, &field_trials); + RtpVideoSenderTestFixture test({kSsrc1}, {}, kPayloadType, {}, field_trials); test.router()->OnTransportOverheadChanged(kTransportPacketOverheadBytes); test.SetSending(true); diff --git a/call/version.cc b/call/version.cc index f10e6c2f1a..97caf539b4 100644 --- a/call/version.cc +++ b/call/version.cc @@ -13,7 +13,7 @@ namespace webrtc { // The timestamp is always in UTC. -const char* const kSourceTimestamp = "WebRTC source stamp 2025-05-26T04:07:21"; +const char* const kSourceTimestamp = "WebRTC source stamp 2025-06-18T04:04:29"; void LoadWebRTCVersionInRegister() { // Using volatile to instruct the compiler to not optimize `p` away even diff --git a/call/video_receive_stream.cc b/call/video_receive_stream.cc index 3bfb35297f..c16cd59b4d 100644 --- a/call/video_receive_stream.cc +++ b/call/video_receive_stream.cc @@ -36,8 +36,7 @@ bool VideoReceiveStreamInterface::Decoder::operator==( } std::string VideoReceiveStreamInterface::Decoder::ToString() const { - char buf[1024]; - SimpleStringBuilder ss(buf); + StringBuilder ss; ss << "{payload_type: " << payload_type; ss << ", payload_name: " << video_format.name; ss << ", codec_params: {"; @@ -48,8 +47,8 @@ std::string VideoReceiveStreamInterface::Decoder::ToString() const { } ss << it->first << ": " << it->second; } - ss << '}'; - ss << '}'; + ss << "}"; + ss << "}"; return ss.str(); } @@ -59,8 +58,7 @@ VideoReceiveStreamInterface::Stats::~Stats() = default; std::string VideoReceiveStreamInterface::Stats::ToString( int64_t time_ms) const { - char buf[2048]; - SimpleStringBuilder ss(buf); + StringBuilder ss; ss << "VideoReceiveStreamInterface stats: " << time_ms << ", {ssrc: " << ssrc << ", "; ss << "total_bps: " << total_bitrate_bps << ", "; @@ -102,7 +100,7 @@ std::string VideoReceiveStreamInterface::Stats::ToString( ss << "nackCount: " << rtcp_packet_type_counts.nack_packets << ", "; ss << "firCount: " << rtcp_packet_type_counts.fir_packets << ", "; ss << "pliCount: " << rtcp_packet_type_counts.pli_packets; - ss << '}'; + ss << "}"; return ss.str(); } @@ -119,21 +117,20 @@ VideoReceiveStreamInterface::Config::operator=(Config&&) = default; VideoReceiveStreamInterface::Config::Config::~Config() = default; std::string VideoReceiveStreamInterface::Config::ToString() const { - char buf[4 * 1024]; - SimpleStringBuilder ss(buf); + StringBuilder ss; ss << "{decoders: ["; for (size_t i = 0; i < decoders.size(); ++i) { ss << decoders[i].ToString(); if (i != decoders.size() - 1) ss << ", "; } - ss << ']'; + ss << "]"; ss << ", rtp: " << rtp.ToString(); ss << ", renderer: " << (renderer ? "(renderer)" : "nullptr"); ss << ", render_delay_ms: " << render_delay_ms; if (!sync_group.empty()) ss << ", sync_group: " << sync_group; - ss << '}'; + ss << "}"; return ss.str(); } @@ -143,8 +140,7 @@ VideoReceiveStreamInterface::Config::Rtp::Rtp(const Rtp&) = default; VideoReceiveStreamInterface::Config::Rtp::~Rtp() = default; std::string VideoReceiveStreamInterface::Config::Rtp::ToString() const { - char buf[2 * 1024]; - SimpleStringBuilder ss(buf); + StringBuilder ss; ss << "{remote_ssrc: " << remote_ssrc; ss << ", local_ssrc: " << local_ssrc; ss << ", rtcp_mode: " @@ -153,9 +149,9 @@ std::string VideoReceiveStreamInterface::Config::Rtp::ToString() const { ss << ", rtcp_xr: "; ss << "{receiver_reference_time_report: " << (rtcp_xr.receiver_reference_time_report ? "on" : "off"); - ss << '}'; - ss << ", lntf: {enabled: " << (lntf.enabled ? "true" : "false") << '}'; - ss << ", nack: {rtp_history_ms: " << nack.rtp_history_ms << '}'; + ss << "}"; + ss << ", lntf: {enabled: " << (lntf.enabled ? "true" : "false") << "}"; + ss << ", nack: {rtp_history_ms: " << nack.rtp_history_ms << "}"; ss << ", ulpfec_payload_type: " << ulpfec_payload_type; ss << ", red_type: " << red_payload_type; ss << ", rtx_ssrc: " << rtx_ssrc; @@ -163,13 +159,13 @@ std::string VideoReceiveStreamInterface::Config::Rtp::ToString() const { for (auto& kv : rtx_associated_payload_types) { ss << kv.first << " (pt) -> " << kv.second << " (apt), "; } - ss << '}'; + ss << "}"; ss << ", raw_payload_types: {"; for (const auto& pt : raw_payload_types) { ss << pt << ", "; } - ss << '}'; - ss << '}'; + ss << "}"; + ss << "}"; return ss.str(); } diff --git a/call/video_send_stream.cc b/call/video_send_stream.cc index 79a911c828..e68f73bbe8 100644 --- a/call/video_send_stream.cc +++ b/call/video_send_stream.cc @@ -42,8 +42,7 @@ VideoSendStream::StreamStats::StreamStats() = default; VideoSendStream::StreamStats::~StreamStats() = default; std::string VideoSendStream::StreamStats::ToString() const { - char buf[1024]; - SimpleStringBuilder ss(buf); + StringBuilder ss; ss << "type: " << StreamTypeToString(type); if (referenced_media_ssrc.has_value()) ss << " (for: " << referenced_media_ssrc.value() << ")"; @@ -71,8 +70,7 @@ VideoSendStream::Stats::Stats() = default; VideoSendStream::Stats::~Stats() = default; std::string VideoSendStream::Stats::ToString(int64_t time_ms) const { - char buf[2048]; - SimpleStringBuilder ss(buf); + StringBuilder ss; ss << "VideoSendStream stats: " << time_ms << ", {"; ss << "input_fps: " << StringFormat("%.1f", input_frame_rate) << ", "; ss << "encode_fps: " << encode_frame_rate << ", "; @@ -90,13 +88,13 @@ std::string VideoSendStream::Stats::ToString(int64_t time_ms) const { << ", "; ss << "#cpu_adaptations: " << number_of_cpu_adapt_changes << ", "; ss << "#quality_adaptations: " << number_of_quality_adapt_changes; - ss << '}'; + ss << "}"; for (const auto& substream : substreams) { if (substream.second.type == VideoSendStream::StreamStats::StreamType::kMedia) { ss << " {ssrc: " << substream.first << ", "; ss << substream.second.ToString(); - ss << '}'; + ss << "}"; } } return ss.str(); @@ -113,8 +111,7 @@ VideoSendStream::Config& VideoSendStream::Config::operator=(Config&&) = default; VideoSendStream::Config::Config::~Config() = default; std::string VideoSendStream::Config::ToString() const { - char buf[2 * 1024]; - SimpleStringBuilder ss(buf); + StringBuilder ss; ss << "{encoder_settings: { experiment_cpu_load_estimator: " << (encoder_settings.experiment_cpu_load_estimator ? "on" : "off") << "}}"; ss << ", rtp: " << rtp.ToString(); @@ -124,7 +121,7 @@ std::string VideoSendStream::Config::ToString() const { ss << ", target_delay_ms: " << target_delay_ms; ss << ", suspend_below_min_bitrate: " << (suspend_below_min_bitrate ? "on" : "off"); - ss << '}'; + ss << "}"; return ss.str(); } diff --git a/call/video_send_stream.h b/call/video_send_stream.h index 906d79598b..bfcc15cc88 100644 --- a/call/video_send_stream.h +++ b/call/video_send_stream.h @@ -19,6 +19,7 @@ #include #include "api/adaptation/resource.h" +#include "api/array_view.h" #include "api/call/transport.h" #include "api/crypto/crypto_options.h" #include "api/frame_transformer_interface.h" @@ -259,6 +260,9 @@ class VideoSendStream { // TODO: webrtc:40644448 - Make this pure virtual. virtual void SetStats(const Stats& stats) { RTC_CHECK_NOTREACHED(); } + // Sets the list of CSRCs to be included in every packet. + virtual void SetCsrcs(ArrayView csrcs) = 0; + virtual void GenerateKeyFrame(const std::vector& rids) = 0; protected: diff --git a/common_audio/BUILD.gn b/common_audio/BUILD.gn index d40cf4e2b5..c5459b21bb 100644 --- a/common_audio/BUILD.gn +++ b/common_audio/BUILD.gn @@ -48,6 +48,7 @@ rtc_library("common_audio") { "../api:array_view", "../api/audio:audio_frame_api", "../rtc_base:checks", + "../rtc_base:cpu_info", "../rtc_base:gtest_prod", "../rtc_base:logging", "../rtc_base:safe_conversions", @@ -56,7 +57,6 @@ rtc_library("common_audio") { "../rtc_base/memory:aligned_malloc", "../rtc_base/system:arch", "../rtc_base/system:file_wrapper", - "../system_wrappers", "third_party/ooura:fft_size_256", ] @@ -184,7 +184,6 @@ rtc_library("common_audio_c") { "../rtc_base:compile_assert_c", "../rtc_base:sanitizer", "../rtc_base/system:arch", - "../system_wrappers", "third_party/ooura:fft_size_256", "third_party/spl_sqrt_floor", ] @@ -197,19 +196,16 @@ rtc_library("common_audio_cc") { "signal_processing/dot_product_with_scale.h", ] - deps = [ - "../rtc_base:safe_conversions", - "../system_wrappers", - ] + deps = [ "../rtc_base:safe_conversions" ] } rtc_source_set("sinc_resampler") { sources = [ "resampler/sinc_resampler.h" ] deps = [ + "../rtc_base:cpu_info", "../rtc_base:gtest_prod", "../rtc_base/memory:aligned_malloc", "../rtc_base/system:arch", - "../system_wrappers", ] } @@ -229,8 +225,8 @@ rtc_library("fir_filter_factory") { deps = [ ":fir_filter", "../rtc_base:checks", + "../rtc_base:cpu_info", "../rtc_base/system:arch", - "../system_wrappers", ] if (current_cpu == "x86" || current_cpu == "x64") { deps += [ ":common_audio_sse2" ] @@ -376,14 +372,14 @@ if (rtc_include_tests && !build_with_chromium) { ":fir_filter", ":fir_filter_factory", ":sinc_resampler", + "../api/audio:audio_frame_api", "../rtc_base:checks", + "../rtc_base:cpu_info", "../rtc_base:logging", - "../rtc_base:macromagic", "../rtc_base:rtc_base_tests_utils", "../rtc_base:stringutils", "../rtc_base:timeutils", "../rtc_base/system:arch", - "../system_wrappers", "../test:fileutils", "../test:rtc_expect_death", "../test:test_main", diff --git a/common_audio/audio_converter_unittest.cc b/common_audio/audio_converter_unittest.cc index 7fbd06d1b4..3118951afd 100644 --- a/common_audio/audio_converter_unittest.cc +++ b/common_audio/audio_converter_unittest.cc @@ -12,12 +12,13 @@ #include #include +#include +#include #include #include #include "common_audio/channel_buffer.h" #include "common_audio/resampler/push_sinc_resampler.h" -#include "rtc_base/arraysize.h" #include "test/gtest.h" namespace webrtc { diff --git a/common_audio/audio_util_unittest.cc b/common_audio/audio_util_unittest.cc index 497ff7329f..fda6bd19ba 100644 --- a/common_audio/audio_util_unittest.cc +++ b/common_audio/audio_util_unittest.cc @@ -10,7 +10,11 @@ #include "common_audio/include/audio_util.h" -#include "rtc_base/arraysize.h" +#include +#include +#include + +#include "api/audio/audio_view.h" #include "test/gmock.h" #include "test/gtest.h" @@ -35,8 +39,8 @@ TEST(AudioUtilTest, S16ToFloat) { static constexpr int16_t kInput[] = {0, 1, -1, 16384, -16384, 32767, -32768}; static constexpr float kReference[] = { 0.f, 1.f / 32767.f, -1.f / 32768.f, 16384.f / 32767.f, -0.5f, 1.f, -1.f}; - static constexpr size_t kSize = arraysize(kInput); - static_assert(arraysize(kReference) == kSize, ""); + static constexpr size_t kSize = std::size(kInput); + static_assert(std::size(kReference) == kSize); float output[kSize]; S16ToFloat(kInput, kSize, output); ExpectArraysEq(kReference, output, kSize); @@ -46,8 +50,8 @@ TEST(AudioUtilTest, FloatS16ToS16) { static constexpr float kInput[] = {0.f, 0.4f, 0.5f, -0.4f, -0.5f, 32768.f, -32769.f}; static constexpr int16_t kReference[] = {0, 0, 1, 0, -1, 32767, -32768}; - static constexpr size_t kSize = arraysize(kInput); - static_assert(arraysize(kReference) == kSize, ""); + static constexpr size_t kSize = std::size(kInput); + static_assert(std::size(kReference) == kSize); int16_t output[kSize]; FloatS16ToS16(kInput, kSize, output); ExpectArraysEq(kReference, output, kSize); @@ -65,8 +69,8 @@ TEST(AudioUtilTest, FloatToFloatS16) { -1.f}; static constexpr float kReference[] = { 0.f, 0.4f, 0.6f, -0.4f, -0.6f, 32768.f, -32768.f, 32768.f, -32768.f}; - static constexpr size_t kSize = arraysize(kInput); - static_assert(arraysize(kReference) == kSize, ""); + static constexpr size_t kSize = std::size(kInput); + static_assert(std::size(kReference) == kSize); float output[kSize]; FloatToFloatS16(kInput, kSize, output); ExpectArraysEq(kReference, output, kSize); @@ -84,8 +88,8 @@ TEST(AudioUtilTest, FloatS16ToFloat) { -1.f, 1.f, -1.f}; - static constexpr size_t kSize = arraysize(kInput); - static_assert(arraysize(kReference) == kSize, ""); + static constexpr size_t kSize = std::size(kInput); + static_assert(std::size(kReference) == kSize); float output[kSize]; FloatS16ToFloat(kInput, kSize, output); ExpectArraysEq(kReference, output, kSize); @@ -97,8 +101,8 @@ TEST(AudioUtilTest, DbfsToFloatS16) { static constexpr float kReference[] = { 1.036215186f, 10.36215115f, 1036.215088f, 3276.800049f, 10362.15137f, 18426.80078f, 29204.51172f, 32768.f, 36766.30078f}; - static constexpr size_t kSize = arraysize(kInput); - static_assert(arraysize(kReference) == kSize, ""); + static constexpr size_t kSize = std::size(kInput); + static_assert(std::size(kReference) == kSize); float output[kSize]; for (size_t i = 0; i < kSize; ++i) { output[i] = DbfsToFloatS16(kInput[i]); @@ -113,8 +117,8 @@ TEST(AudioUtilTest, FloatS16ToDbfs) { static constexpr float kReference[] = { -90.f, -70.f, -30.f, -20.f, -10.f, -5.f, -1.f, 0.f, 0.9999923706f}; - static constexpr size_t kSize = arraysize(kInput); - static_assert(arraysize(kReference) == kSize, ""); + static constexpr size_t kSize = std::size(kInput); + static_assert(std::size(kReference) == kSize); float output[kSize]; for (size_t i = 0; i < kSize; ++i) { diff --git a/common_audio/fir_filter_factory.cc b/common_audio/fir_filter_factory.cc index 2ecef6501f..fdf758ee79 100644 --- a/common_audio/fir_filter_factory.cc +++ b/common_audio/fir_filter_factory.cc @@ -12,6 +12,7 @@ #include "common_audio/fir_filter_c.h" #include "rtc_base/checks.h" +#include "rtc_base/cpu_info.h" #include "rtc_base/system/arch.h" #if defined(WEBRTC_HAS_NEON) @@ -19,7 +20,6 @@ #elif defined(WEBRTC_ARCH_X86_FAMILY) #include "common_audio/fir_filter_avx2.h" #include "common_audio/fir_filter_sse.h" -#include "system_wrappers/include/cpu_features_wrapper.h" // kSSE2, WebRtc_G... #endif namespace webrtc { @@ -36,10 +36,10 @@ FIRFilter* CreateFirFilter(const float* coefficients, // If we know the minimum architecture at compile time, avoid CPU detection. #if defined(WEBRTC_ARCH_X86_FAMILY) // x86 CPU detection required. - if (GetCPUInfo(kAVX2)) { + if (cpu_info::Supports(cpu_info::ISA::kAVX2)) { filter = new FIRFilterAVX2(coefficients, coefficients_length, max_input_length); - } else if (GetCPUInfo(kSSE2)) { + } else if (cpu_info::Supports(cpu_info::ISA::kSSE2)) { filter = new FIRFilterSSE2(coefficients, coefficients_length, max_input_length); } else { diff --git a/common_audio/fir_filter_unittest.cc b/common_audio/fir_filter_unittest.cc index 9b973882e2..9b2783b9f1 100644 --- a/common_audio/fir_filter_unittest.cc +++ b/common_audio/fir_filter_unittest.cc @@ -21,13 +21,13 @@ namespace webrtc { namespace { -static constexpr size_t kCoefficientsSize = 5; -static const std::array kCoefficients = { - 0.2f, 0.3f, 0.5f, 0.7f, 0.11f}; +constexpr size_t kCoefficientsSize = 5; +const std::array kCoefficients = {0.2f, 0.3f, 0.5f, + 0.7f, 0.11f}; -static constexpr size_t kInputSize = 10; -static const std::array kInput = {1.f, 2.f, 3.f, 4.f, 5.f, - 6.f, 7.f, 8.f, 9.f, 10.f}; +constexpr size_t kInputSize = 10; +const std::array kInput = {1.f, 2.f, 3.f, 4.f, 5.f, + 6.f, 7.f, 8.f, 9.f, 10.f}; } // namespace diff --git a/common_audio/real_fourier_unittest.cc b/common_audio/real_fourier_unittest.cc index eac4fce42e..3f3a2eb5e9 100644 --- a/common_audio/real_fourier_unittest.cc +++ b/common_audio/real_fourier_unittest.cc @@ -60,7 +60,7 @@ class RealFourierTest : public ::testing::Test { real_buffer_(RealFourier::AllocRealBuffer(4)), cplx_buffer_(RealFourier::AllocCplxBuffer(3)) {} - ~RealFourierTest() {} + ~RealFourierTest() override {} T rf_; const RealFourier::fft_real_scoper real_buffer_; diff --git a/common_audio/resampler/sinc_resampler.cc b/common_audio/resampler/sinc_resampler.cc index 66a99b6190..fc64ba6f1d 100644 --- a/common_audio/resampler/sinc_resampler.cc +++ b/common_audio/resampler/sinc_resampler.cc @@ -82,20 +82,18 @@ // Note: we're glossing over how the sub-sample handling works with // `virtual_source_idx_`, etc. -// MSVC++ requires this to be set before any other includes to get M_PI. -#define _USE_MATH_DEFINES - #include "common_audio/resampler/sinc_resampler.h" -#include -#include -#include - +#include +#include +#include #include +#include #include "rtc_base/checks.h" +#include "rtc_base/cpu_info.h" +#include "rtc_base/memory/aligned_malloc.h" #include "rtc_base/system/arch.h" -#include "system_wrappers/include/cpu_features_wrapper.h" // kSSE2, WebRtc_G... namespace webrtc { @@ -127,9 +125,10 @@ void SincResampler::InitializeCPUSpecificFeatures() { convolve_proc_ = Convolve_NEON; #elif defined(WEBRTC_ARCH_X86_FAMILY) // Using AVX2 instead of SSE2 when AVX2/FMA3 supported. - if (GetCPUInfo(kAVX2) && GetCPUInfo(kFMA3)) + if (cpu_info::Supports(cpu_info::ISA::kAVX2) && + cpu_info::Supports(cpu_info::ISA::kFMA3)) convolve_proc_ = Convolve_AVX2; - else if (GetCPUInfo(kSSE2)) + else if (cpu_info::Supports(cpu_info::ISA::kSSE2)) convolve_proc_ = Convolve_SSE; else convolve_proc_ = Convolve_C; @@ -209,14 +208,16 @@ void SincResampler::InitializeKernel() { for (size_t i = 0; i < kKernelSize; ++i) { const size_t idx = i + offset_idx * kKernelSize; const float pre_sinc = static_cast( - M_PI * (static_cast(i) - static_cast(kKernelSize / 2) - - subsample_offset)); + std::numbers::pi * + (static_cast(i) - static_cast(kKernelSize / 2) - + subsample_offset)); kernel_pre_sinc_storage_[idx] = pre_sinc; // Compute Blackman window, matching the offset of the sinc(). const float x = (i - subsample_offset) / kKernelSize; - const float window = static_cast(kA0 - kA1 * cos(2.0 * M_PI * x) + - kA2 * cos(4.0 * M_PI * x)); + const float window = + static_cast(kA0 - kA1 * cos(2.0 * std::numbers::pi * x) + + kA2 * cos(4.0 * std::numbers::pi * x)); kernel_window_storage_[idx] = window; // Compute the sinc with offset, then window the sinc() function and store diff --git a/common_audio/resampler/sinc_resampler_unittest.cc b/common_audio/resampler/sinc_resampler_unittest.cc index 483d3d0374..8fbe0d87c2 100644 --- a/common_audio/resampler/sinc_resampler_unittest.cc +++ b/common_audio/resampler/sinc_resampler_unittest.cc @@ -11,21 +11,22 @@ // Modified from the Chromium original: // src/media/base/sinc_resampler_unittest.cc -// MSVC++ requires this to be set before any other includes to get M_PI. -#define _USE_MATH_DEFINES - #include "common_audio/resampler/sinc_resampler.h" -#include - #include +#include +#include +#include +#include +#include #include +#include #include #include "common_audio/resampler/sinusoidal_linear_chirp_source.h" +#include "rtc_base/cpu_info.h" #include "rtc_base/system/arch.h" #include "rtc_base/time_utils.h" -#include "system_wrappers/include/cpu_features_wrapper.h" #include "test/gmock.h" #include "test/gtest.h" @@ -119,9 +120,9 @@ TEST(SincResamplerTest, DISABLED_SetRatioBench) { // will be tested by the parameterized SincResampler tests below. TEST(SincResamplerTest, Convolve) { #if defined(WEBRTC_ARCH_X86_FAMILY) - ASSERT_TRUE(GetCPUInfo(kSSE2)); + ASSERT_TRUE(cpu_info::Supports(cpu_info::ISA::kSSE2)); #elif defined(WEBRTC_ARCH_ARM_V7) - ASSERT_TRUE(GetCPUFeaturesARM() & kCPUFeatureNEON); + ASSERT_TRUE(cpu_info::Supports(cpu_info::ISA::kNeon)); #endif // Initialize a dummy resampler. @@ -179,9 +180,9 @@ TEST(SincResamplerTest, ConvolveBenchmark) { printf("Convolve_C took %.2fms.\n", total_time_c_us / 1000); #if defined(WEBRTC_ARCH_X86_FAMILY) - ASSERT_TRUE(GetCPUInfo(kSSE2)); + ASSERT_TRUE(cpu_info::Supports(cpu_info::ISA::kSSE2)); #elif defined(WEBRTC_ARCH_ARM_V7) - ASSERT_TRUE(GetCPUFeaturesARM() & kCPUFeatureNEON); + ASSERT_TRUE(cpu_info::Supports(cpu_info::ISA::kNeon)); #endif // Benchmark with unaligned input pointer. @@ -227,7 +228,7 @@ class SincResamplerTest rms_error_(std::get<2>(GetParam())), low_freq_error_(std::get<3>(GetParam())) {} - virtual ~SincResamplerTest() {} + ~SincResamplerTest() override {} protected: int input_rate_; @@ -261,7 +262,7 @@ TEST_P(SincResamplerTest, Resample) { std::unique_ptr kernel(new float[SincResampler::kKernelStorageSize]); memcpy(kernel.get(), resampler.get_kernel_for_testing(), SincResampler::kKernelStorageSize); - resampler.SetRatio(M_PI); + resampler.SetRatio(std::numbers::pi_v); ASSERT_NE(0, memcmp(kernel.get(), resampler.get_kernel_for_testing(), SincResampler::kKernelStorageSize)); resampler.SetRatio(io_ratio); diff --git a/common_audio/resampler/sinusoidal_linear_chirp_source.cc b/common_audio/resampler/sinusoidal_linear_chirp_source.cc index 2afdd1be47..7c680094a8 100644 --- a/common_audio/resampler/sinusoidal_linear_chirp_source.cc +++ b/common_audio/resampler/sinusoidal_linear_chirp_source.cc @@ -8,12 +8,11 @@ * be found in the AUTHORS file in the root of the source tree. */ -// MSVC++ requires this to be set before any other includes to get M_PI. -#define _USE_MATH_DEFINES - #include "common_audio/resampler/sinusoidal_linear_chirp_source.h" -#include +#include +#include +#include namespace webrtc { @@ -43,7 +42,8 @@ void SinusoidalLinearChirpSource::Run(size_t frames, float* destination) { } else { // Sinusoidal linear chirp. double t = (current_index_ - delay_samples_) / sample_rate_; - destination[i] = sin(2 * M_PI * (kMinFrequency * t + (k_ / 2) * t * t)); + destination[i] = + sin(2 * std::numbers::pi * (kMinFrequency * t + (k_ / 2) * t * t)); } } } diff --git a/common_audio/third_party/ooura/BUILD.gn b/common_audio/third_party/ooura/BUILD.gn index 0cdf98e591..a12adb2c0b 100644 --- a/common_audio/third_party/ooura/BUILD.gn +++ b/common_audio/third_party/ooura/BUILD.gn @@ -15,8 +15,8 @@ rtc_library("fft_size_128") { "fft_size_128/ooura_fft_tables_common.h", ] deps = [ + "../../../rtc_base:cpu_info", "../../../rtc_base/system:arch", - "../../../system_wrappers", ] cflags = [] diff --git a/common_audio/third_party/ooura/fft_size_128/ooura_fft.cc b/common_audio/third_party/ooura/fft_size_128/ooura_fft.cc index b7a529d1b1..98a8f02ed1 100644 --- a/common_audio/third_party/ooura/fft_size_128/ooura_fft.cc +++ b/common_audio/third_party/ooura/fft_size_128/ooura_fft.cc @@ -24,15 +24,15 @@ #include "common_audio/third_party/ooura/fft_size_128/ooura_fft.h" #include "common_audio/third_party/ooura/fft_size_128/ooura_fft_tables_common.h" +#include "rtc_base/cpu_info.h" #include "rtc_base/system/arch.h" -#include "system_wrappers/include/cpu_features_wrapper.h" namespace webrtc { namespace { #if !(defined(MIPS_FPU_LE) || defined(WEBRTC_HAS_NEON)) -static void cft1st_128_C(float* a) { +void cft1st_128_C(float* a) { const int n = 128; int j, k1, k2; float wk1r, wk1i, wk2r, wk2i, wk3r, wk3i; @@ -139,7 +139,7 @@ static void cft1st_128_C(float* a) { } } -static void cftmdl_128_C(float* a) { +void cftmdl_128_C(float* a) { const int l = 8; const int n = 128; const int m = 32; @@ -266,7 +266,7 @@ static void cftmdl_128_C(float* a) { } } -static void rftfsub_128_C(float* a) { +void rftfsub_128_C(float* a) { const float* c = rdft_w + 32; int j1, j2, k1, k2; float wkr, wki, xr, xi, yr, yi; @@ -287,7 +287,7 @@ static void rftfsub_128_C(float* a) { } } -static void rftbsub_128_C(float* a) { +void rftbsub_128_C(float* a) { const float* c = rdft_w + 32; int j1, j2, k1, k2; float wkr, wki, xr, xi, yr, yi; @@ -323,7 +323,7 @@ OouraFft::OouraFft([[maybe_unused]] bool sse2_available) { OouraFft::OouraFft() { #if defined(WEBRTC_ARCH_X86_FAMILY) - use_sse2_ = (GetCPUInfo(kSSE2) != 0); + use_sse2_ = cpu_info::Supports(cpu_info::ISA::kSSE2); #else use_sse2_ = false; #endif diff --git a/common_audio/wav_file_unittest.cc b/common_audio/wav_file_unittest.cc index fbfa4aa73d..f4a04b7a0a 100644 --- a/common_audio/wav_file_unittest.cc +++ b/common_audio/wav_file_unittest.cc @@ -8,15 +8,19 @@ * be found in the AUTHORS file in the root of the source tree. */ -// MSVC++ requires this to be set before any other includes to get M_PI. -#define _USE_MATH_DEFINES - #include "common_audio/wav_file.h" #include +#include +#include +#include +#include #include +#include +#include #include "common_audio/wav_header.h" +#include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "test/gtest.h" #include "test/testsupport/file_utils.h" @@ -135,12 +139,13 @@ TEST(WavWriterTest, LargeFile) { const double t = static_cast(i) / (kNumChannels * kSampleRate); const double x = std::numeric_limits::max() * - std::sin(t * kToneHz * 2 * M_PI); - samples[i] = std::pow(std::sin(t * 2 * 2 * M_PI), 10) * x; - samples[i + 1] = std::pow(std::cos(t * 2 * 2 * M_PI), 10) * x; + std::sin(t * kToneHz * 2 * std::numbers::pi); + samples[i] = std::pow(std::sin(t * 2 * 2 * std::numbers::pi), 10) * x; + samples[i + 1] = + std::pow(std::cos(t * 2 * 2 * std::numbers::pi), 10) * x; // See https://issues.webrtc.org/issues/379973428 - RTC_CHECK(isfinite(samples[i])); - RTC_CHECK(isfinite(samples[i + 1])); + RTC_CHECK(std::isfinite(samples[i])); + RTC_CHECK(std::isfinite(samples[i + 1])); } { WavWriter w(outfile, kSampleRate, kNumChannels, wav_format); @@ -177,7 +182,7 @@ TEST(WavWriterTest, LargeFile) { EXPECT_EQ(kNumSamples, r.ReadSamples(kNumSamples, read_samples)); for (size_t i = 0; i < kNumSamples; ++i) { EXPECT_NEAR(samples[i], read_samples[i], 1); - if (!isfinite(samples[i])) { + if (!std::isfinite(samples[i])) { // See https://issues.webrtc.org/issues/379973428 RTC_LOG(LS_ERROR) << "samples[" << i << "] is not finite. " @@ -192,7 +197,7 @@ TEST(WavWriterTest, LargeFile) { EXPECT_EQ(kNumSamples, r.ReadSamples(kNumSamples, read_samples)); for (size_t i = 0; i < kNumSamples; ++i) { EXPECT_NEAR(samples[i], static_cast(read_samples[i]), 1); - if (!isfinite(samples[i])) { + if (!std::isfinite(samples[i])) { // See https://issues.webrtc.org/issues/379973428 RTC_LOG(LS_ERROR) << "samples[" << i << "] is not finite. " diff --git a/common_audio/window_generator.cc b/common_audio/window_generator.cc index 7c33d255f0..5a6de1aec1 100644 --- a/common_audio/window_generator.cc +++ b/common_audio/window_generator.cc @@ -8,12 +8,11 @@ * be found in the AUTHORS file in the root of the source tree. */ -#define _USE_MATH_DEFINES - #include "common_audio/window_generator.h" #include #include +#include #include #include "rtc_base/checks.h" diff --git a/common_video/frame_rate_estimator_unittest.cc b/common_video/frame_rate_estimator_unittest.cc index f4d37cd97e..063cb010d6 100644 --- a/common_video/frame_rate_estimator_unittest.cc +++ b/common_video/frame_rate_estimator_unittest.cc @@ -18,7 +18,7 @@ namespace webrtc { namespace { constexpr TimeDelta kDefaultWindow = TimeDelta::Millis(1000); -} +} // namespace class FrameRateEstimatorTest : public ::testing::Test { public: diff --git a/common_video/h264/sps_vui_rewriter_unittest.cc b/common_video/h264/sps_vui_rewriter_unittest.cc index b9c6c86bf5..854196ab6b 100644 --- a/common_video/h264/sps_vui_rewriter_unittest.cc +++ b/common_video/h264/sps_vui_rewriter_unittest.cc @@ -35,15 +35,15 @@ enum SpsMode { kRewriteRequired_VuiSuboptimal, }; -static const size_t kSpsBufferMaxSize = 256; -static const size_t kWidth = 640; -static const size_t kHeight = 480; +const size_t kSpsBufferMaxSize = 256; +const size_t kWidth = 640; +const size_t kHeight = 480; -static const uint8_t kStartSequence[] = {0x00, 0x00, 0x00, 0x01}; -static const uint8_t kAud[] = {H264::NaluType::kAud, 0x09, 0x10}; -static const uint8_t kSpsNaluType[] = {H264::NaluType::kSps}; -static const uint8_t kIdr1[] = {H264::NaluType::kIdr, 0xFF, 0x00, 0x00, 0x04}; -static const uint8_t kIdr2[] = {H264::NaluType::kIdr, 0xFF, 0x00, 0x11}; +const uint8_t kStartSequence[] = {0x00, 0x00, 0x00, 0x01}; +const uint8_t kAud[] = {H264::NaluType::kAud, 0x09, 0x10}; +const uint8_t kSpsNaluType[] = {H264::NaluType::kSps}; +const uint8_t kIdr1[] = {H264::NaluType::kIdr, 0xFF, 0x00, 0x00, 0x04}; +const uint8_t kIdr2[] = {H264::NaluType::kIdr, 0xFF, 0x00, 0x11}; struct VuiHeader { uint32_t vui_parameters_present_flag; @@ -58,7 +58,7 @@ struct VuiHeader { uint8_t matrix_coefficients; }; -static const VuiHeader kVuiNotPresent = { +const VuiHeader kVuiNotPresent = { /* vui_parameters_present_flag= */ 0, /* bitstream_restriction_flag= */ 0, /* max_num_reorder_frames= */ 0, @@ -70,7 +70,7 @@ static const VuiHeader kVuiNotPresent = { /* transfer_characteristics= */ 0, /* matrix_coefficients= */ 0}; -static const VuiHeader kVuiNoBitstreamRestriction = { +const VuiHeader kVuiNoBitstreamRestriction = { /* vui_parameters_present_flag= */ 1, /* bitstream_restriction_flag= */ 0, /* max_num_reorder_frames= */ 0, @@ -82,7 +82,7 @@ static const VuiHeader kVuiNoBitstreamRestriction = { /* transfer_characteristics= */ 0, /* matrix_coefficients= */ 0}; -static const VuiHeader kVuiNoFrameBuffering = { +const VuiHeader kVuiNoFrameBuffering = { /* vui_parameters_present_flag= */ 1, /* bitstream_restriction_flag= */ 1, /* max_num_reorder_frames= */ 0, @@ -94,7 +94,7 @@ static const VuiHeader kVuiNoFrameBuffering = { /* transfer_characteristics= */ 0, /* matrix_coefficients= */ 0}; -static const VuiHeader kVuiFrameBuffering = { +const VuiHeader kVuiFrameBuffering = { /* vui_parameters_present_flag= */ 1, /* bitstream_restriction_flag= */ 1, /* max_num_reorder_frames= */ 3, @@ -106,7 +106,7 @@ static const VuiHeader kVuiFrameBuffering = { /* transfer_characteristics= */ 0, /* matrix_coefficients= */ 0}; -static const VuiHeader kVuiNoVideoSignalType = { +const VuiHeader kVuiNoVideoSignalType = { /* vui_parameters_present_flag= */ 1, /* bitstream_restriction_flag= */ 1, /* max_num_reorder_frames= */ 0, @@ -118,7 +118,7 @@ static const VuiHeader kVuiNoVideoSignalType = { /* transfer_characteristics= */ 0, /* matrix_coefficients= */ 0}; -static const VuiHeader kVuiLimitedRangeNoColourDescription = { +const VuiHeader kVuiLimitedRangeNoColourDescription = { /* vui_parameters_present_flag= */ 1, /* bitstream_restriction_flag= */ 1, /* max_num_reorder_frames= */ 0, @@ -130,7 +130,7 @@ static const VuiHeader kVuiLimitedRangeNoColourDescription = { /* transfer_characteristics= */ 0, /* matrix_coefficients= */ 0}; -static const VuiHeader kVuiFullRangeNoColourDescription = { +const VuiHeader kVuiFullRangeNoColourDescription = { /* vui_parameters_present_flag= */ 1, /* bitstream_restriction_flag= */ 1, /* max_num_reorder_frames= */ 0, @@ -142,7 +142,7 @@ static const VuiHeader kVuiFullRangeNoColourDescription = { /* transfer_characteristics= */ 0, /* matrix_coefficients= */ 0}; -static const VuiHeader kVuiLimitedRangeBt709Color = { +const VuiHeader kVuiLimitedRangeBt709Color = { /* vui_parameters_present_flag= */ 1, /* bitstream_restriction_flag= */ 1, /* max_num_reorder_frames= */ 0, @@ -154,41 +154,35 @@ static const VuiHeader kVuiLimitedRangeBt709Color = { /* transfer_characteristics= */ 1, /* matrix_coefficients= */ 1}; -static const ColorSpace kColorSpaceH264Default( - ColorSpace::PrimaryID::kUnspecified, - ColorSpace::TransferID::kUnspecified, - ColorSpace::MatrixID::kUnspecified, - ColorSpace::RangeID::kLimited); - -static const ColorSpace kColorSpacePrimariesBt709( - ColorSpace::PrimaryID::kBT709, - ColorSpace::TransferID::kUnspecified, - ColorSpace::MatrixID::kUnspecified, - ColorSpace::RangeID::kLimited); - -static const ColorSpace kColorSpaceTransferBt709( - ColorSpace::PrimaryID::kUnspecified, - ColorSpace::TransferID::kBT709, - ColorSpace::MatrixID::kUnspecified, - ColorSpace::RangeID::kLimited); - -static const ColorSpace kColorSpaceMatrixBt709( - ColorSpace::PrimaryID::kUnspecified, - ColorSpace::TransferID::kUnspecified, - ColorSpace::MatrixID::kBT709, - ColorSpace::RangeID::kLimited); - -static const ColorSpace kColorSpaceFullRange( - ColorSpace::PrimaryID::kBT709, - ColorSpace::TransferID::kUnspecified, - ColorSpace::MatrixID::kUnspecified, - ColorSpace::RangeID::kFull); - -static const ColorSpace kColorSpaceBt709LimitedRange( - ColorSpace::PrimaryID::kBT709, - ColorSpace::TransferID::kBT709, - ColorSpace::MatrixID::kBT709, - ColorSpace::RangeID::kLimited); +const ColorSpace kColorSpaceH264Default(ColorSpace::PrimaryID::kUnspecified, + ColorSpace::TransferID::kUnspecified, + ColorSpace::MatrixID::kUnspecified, + ColorSpace::RangeID::kLimited); + +const ColorSpace kColorSpacePrimariesBt709(ColorSpace::PrimaryID::kBT709, + ColorSpace::TransferID::kUnspecified, + ColorSpace::MatrixID::kUnspecified, + ColorSpace::RangeID::kLimited); + +const ColorSpace kColorSpaceTransferBt709(ColorSpace::PrimaryID::kUnspecified, + ColorSpace::TransferID::kBT709, + ColorSpace::MatrixID::kUnspecified, + ColorSpace::RangeID::kLimited); + +const ColorSpace kColorSpaceMatrixBt709(ColorSpace::PrimaryID::kUnspecified, + ColorSpace::TransferID::kUnspecified, + ColorSpace::MatrixID::kBT709, + ColorSpace::RangeID::kLimited); + +const ColorSpace kColorSpaceFullRange(ColorSpace::PrimaryID::kBT709, + ColorSpace::TransferID::kUnspecified, + ColorSpace::MatrixID::kUnspecified, + ColorSpace::RangeID::kFull); + +const ColorSpace kColorSpaceBt709LimitedRange(ColorSpace::PrimaryID::kBT709, + ColorSpace::TransferID::kBT709, + ColorSpace::MatrixID::kBT709, + ColorSpace::RangeID::kLimited); } // namespace // Generates a fake SPS with basically everything empty and with characteristics diff --git a/docs/native-code/development/contributing.md b/docs/native-code/development/contributing.md index 918948166e..8960229d6d 100644 --- a/docs/native-code/development/contributing.md +++ b/docs/native-code/development/contributing.md @@ -81,6 +81,33 @@ for gclient to find the `.gitcookies` file. [example CL link]: https://webrtc-review.googlesource.com/c/src/+/53121 +### Stacked Diffs +Stacked diffs are an advanced feature to "stack" multiple gerrit changes on top +of each other. They show up as separate changes in gerrit codereview but the relationship +is retained. To create a stacked diff: + +* Assuming you are on the main branch: + * `git checkout -b my-first-work-branch` +* Make changes, build locally, run tests locally + * `git commit -am "Changed x, and it is working"` + * `git cl upload` +* Checkout the second branch from the current branch: + * `git checkout -b my-second-work-branch` +* Set the `upstream` branch to the first branch: + * `git cl upstream my-first-work-branch` +* Make changes, build locally, run tests locally + * `git commit -am "Changed y, and it is working too"` + * `git cl upload` +* You can now run tests or ask for review of my-second-work-branch independently + of my-first-work-branch. +* You can go back to the first branch, update, rebase and reupload + the second branch afterwards: + * `git rebase-update --no-fetch my-second-work-branch` + * `git cl upload` + +See https://newsletter.pragmaticengineer.com/p/stacked-diffs for an in-depth +explanation of stacked diffs. + ### Trybots If you're working a lot in WebRTC, you can apply for *try rights*. This means you diff --git a/docs/native-code/development/fuzzers/README.md b/docs/native-code/development/fuzzers/README.md index ce7941243f..2b54ded84e 100644 --- a/docs/native-code/development/fuzzers/README.md +++ b/docs/native-code/development/fuzzers/README.md @@ -18,7 +18,7 @@ custom variable in your .gclient file then run gclient runhooks. ## Compiling locally To build the fuzzers residing in the [test/fuzzers][fuzzers] directory, use ``` -$ gn gen out/fuzzers --args='enable_rust=true enable_rust_cxx=true optimize_for_fuzzing=true use_fuzztest_wrapper=true use_libfuzzer=true' +$ gn gen out/fuzzers --args='optimize_for_fuzzing=true use_libfuzzer=true' ``` Depending on the fuzzer additional arguments like `is_asan`, `is_msan` or `is_ubsan_security` might be required. @@ -27,6 +27,9 @@ See the [GN][gn-doc] documentation for all available options. There are also more platform specific tips on the [Android][webrtc-android-development] and [iOS][webrtc-ios-development] instructions. +Note that `use_fuzztest_wrapper` is set to false by default because it adds a +dependency to Chromium //base. + ## Add new fuzzers Create a new `.cc` file in the [test/fuzzers][fuzzers] directory, use existing files as a guide. diff --git a/examples/androidnativeapi/jni/android_call_client.cc b/examples/androidnativeapi/jni/android_call_client.cc index 33ccc2e5b1..0735266511 100644 --- a/examples/androidnativeapi/jni/android_call_client.cc +++ b/examples/androidnativeapi/jni/android_call_client.cc @@ -56,7 +56,7 @@ class AndroidCallClient::PCObserver : public webrtc::PeerConnectionObserver { webrtc::PeerConnectionInterface::IceConnectionState new_state) override; void OnIceGatheringChange( webrtc::PeerConnectionInterface::IceGatheringState new_state) override; - void OnIceCandidate(const webrtc::IceCandidateInterface* candidate) override; + void OnIceCandidate(const webrtc::IceCandidate* candidate) override; private: AndroidCallClient* const client_; @@ -250,7 +250,7 @@ void AndroidCallClient::PCObserver::OnIceGatheringChange( } void AndroidCallClient::PCObserver::OnIceCandidate( - const webrtc::IceCandidateInterface* candidate) { + const webrtc::IceCandidate* candidate) { RTC_LOG(LS_INFO) << "OnIceCandidate: " << candidate->server_url(); webrtc::MutexLock lock(&client_->pc_mutex_); RTC_DCHECK(client_->pc_ != nullptr); diff --git a/examples/objcnativeapi/objc/objc_call_client.h b/examples/objcnativeapi/objc/objc_call_client.h index 658500d1ac..fe8680d84d 100644 --- a/examples/objcnativeapi/objc/objc_call_client.h +++ b/examples/objcnativeapi/objc/objc_call_client.h @@ -49,8 +49,7 @@ class ObjCCallClient { webrtc::PeerConnectionInterface::IceConnectionState new_state) override; void OnIceGatheringChange( webrtc::PeerConnectionInterface::IceGatheringState new_state) override; - void OnIceCandidate( - const webrtc::IceCandidateInterface* candidate) override; + void OnIceCandidate(const webrtc::IceCandidate* candidate) override; private: ObjCCallClient* const client_; diff --git a/examples/objcnativeapi/objc/objc_call_client.mm b/examples/objcnativeapi/objc/objc_call_client.mm index a0c9e4bfdb..ea476ce417 100644 --- a/examples/objcnativeapi/objc/objc_call_client.mm +++ b/examples/objcnativeapi/objc/objc_call_client.mm @@ -203,7 +203,7 @@ explicit CreateOfferObserver( } void ObjCCallClient::PCObserver::OnIceCandidate( - const webrtc::IceCandidateInterface* candidate) { + const webrtc::IceCandidate* candidate) { RTC_LOG(LS_INFO) << "OnIceCandidate: " << candidate->server_url(); webrtc::MutexLock lock(&client_->pc_mutex_); RTC_DCHECK(client_->pc_ != nullptr); diff --git a/examples/peerconnection/client/conductor.cc b/examples/peerconnection/client/conductor.cc index 2039ea66ee..43c4cdd2f9 100644 --- a/examples/peerconnection/client/conductor.cc +++ b/examples/peerconnection/client/conductor.cc @@ -83,8 +83,8 @@ class DummySetSessionDescriptionObserver static webrtc::scoped_refptr Create() { return webrtc::make_ref_counted(); } - virtual void OnSuccess() { RTC_LOG(LS_INFO) << __FUNCTION__; } - virtual void OnFailure(webrtc::RTCError error) { + void OnSuccess() override { RTC_LOG(LS_INFO) << __FUNCTION__; } + void OnFailure(webrtc::RTCError error) override { RTC_LOG(LS_INFO) << __FUNCTION__ << " " << ToString(error.type()) << ": " << error.message(); } @@ -290,7 +290,7 @@ void Conductor::OnRemoveTrack( main_wnd_->QueueUIThreadCallback(TRACK_REMOVED, receiver->track().release()); } -void Conductor::OnIceCandidate(const webrtc::IceCandidateInterface* candidate) { +void Conductor::OnIceCandidate(const webrtc::IceCandidate* candidate) { RTC_LOG(LS_INFO) << __FUNCTION__ << " " << candidate->sdp_mline_index(); // For loopback test. To save some connecting delay. if (loopback_) { @@ -303,12 +303,7 @@ void Conductor::OnIceCandidate(const webrtc::IceCandidateInterface* candidate) { Json::Value jmessage; jmessage[kCandidateSdpMidName] = candidate->sdp_mid(); jmessage[kCandidateSdpMlineIndexName] = candidate->sdp_mline_index(); - std::string sdp; - if (!candidate->ToString(&sdp)) { - RTC_LOG(LS_ERROR) << "Failed to serialize candidate"; - return; - } - jmessage[kCandidateSdpName] = sdp; + jmessage[kCandidateSdpName] = candidate->ToString(); Json::StreamWriterBuilder factory; SendMessage(Json::writeString(factory, jmessage)); @@ -442,7 +437,7 @@ void Conductor::OnMessageFromPeer(int peer_id, const std::string& message) { return; } webrtc::SdpParseError error; - std::unique_ptr candidate( + std::unique_ptr candidate( webrtc::CreateIceCandidate(sdp_mid, sdp_mlineindex, sdp, &error)); if (!candidate.get()) { RTC_LOG(LS_WARNING) << "Can't parse received candidate message. " diff --git a/examples/peerconnection/client/conductor.h b/examples/peerconnection/client/conductor.h index 68b70bb2f6..d9f6d5fa3e 100644 --- a/examples/peerconnection/client/conductor.h +++ b/examples/peerconnection/client/conductor.h @@ -82,7 +82,7 @@ class Conductor : public webrtc::PeerConnectionObserver, webrtc::PeerConnectionInterface::IceConnectionState new_state) override {} void OnIceGatheringChange( webrtc::PeerConnectionInterface::IceGatheringState new_state) override {} - void OnIceCandidate(const webrtc::IceCandidateInterface* candidate) override; + void OnIceCandidate(const webrtc::IceCandidate* candidate) override; void OnIceConnectionReceivingChange(bool receiving) override {} // diff --git a/examples/peerconnection/client/linux/main.cc b/examples/peerconnection/client/linux/main.cc index a0a80e83ac..68ac5998cb 100644 --- a/examples/peerconnection/client/linux/main.cc +++ b/examples/peerconnection/client/linux/main.cc @@ -35,7 +35,7 @@ class CustomSocketServer : public webrtc::PhysicalSocketServer { public: explicit CustomSocketServer(GtkMainWnd* wnd) : wnd_(wnd), conductor_(nullptr), client_(nullptr) {} - virtual ~CustomSocketServer() {} + ~CustomSocketServer() override {} void SetMessageQueue(webrtc::Thread* queue) override { message_queue_ = queue; diff --git a/examples/turnserver/turnserver_main.cc b/examples/turnserver/turnserver_main.cc index 9248ea2e73..6419509d59 100644 --- a/examples/turnserver/turnserver_main.cc +++ b/examples/turnserver/turnserver_main.cc @@ -33,9 +33,9 @@ class TurnFileAuth : public webrtc::TurnAuthInterface { explicit TurnFileAuth(std::map name_to_key) : name_to_key_(std::move(name_to_key)) {} - virtual bool GetKey(absl::string_view username, - absl::string_view realm, - std::string* key) { + bool GetKey(absl::string_view username, + absl::string_view realm, + std::string* key) override { // File is stored as lines of =. // Generate HA1 via "echo -n "::" | md5sum" auto it = name_to_key_.find(std::string(username)); diff --git a/experiments/field_trials.py b/experiments/field_trials.py index a8ecc034ef..9fe38176fb 100755 --- a/experiments/field_trials.py +++ b/experiments/field_trials.py @@ -95,9 +95,6 @@ def bug_url(self) -> str: FieldTrial('WebRTC-EnableDtlsPqc', 404763475, date(2026,6,1)), - FieldTrial('WebRTC-FrameCadenceAdapter-UseVideoFrameTimestamp', - 42226256, - date(2024, 10, 1)), FieldTrial('WebRTC-IPv6NetworkResolutionFixes', 42224598, date(2024, 4, 1)), @@ -182,6 +179,9 @@ def bug_url(self) -> str: FieldTrial('WebRTC-PayloadTypesInTransport', 360058654, date(2025, 9, 11)), + FieldTrial('WebRTC-TimestampExtrapolatorConfig', + 424739326, + date(2026, 6, 30)), FieldTrial('WebRTC-UseAbsCapTimeForG2gMetric', 401512883, date(2025, 9, 10)), @@ -203,9 +203,6 @@ def bug_url(self) -> str: FieldTrial('WebRTC-VideoEncoderSettings', 40252667, date(2024, 4, 1)), - FieldTrial('WebRTC-ZeroHertzQueueOverload', - 42225879, - date(2024, 7, 1)), FieldTrial('WebRTC-Video-H26xPacketBuffer', 41480904, date(2024, 6, 1)), @@ -523,9 +520,6 @@ def bug_url(self) -> str: FieldTrial('WebRTC-Audio-Red-For-Opus', 42221750, date(2024, 4, 1)), - FieldTrial('WebRTC-Audio-StableTargetAdaptation', - 42221061, - INDEFINITE), FieldTrial('WebRTC-Audio-iOS-Holding', 42233253, date(2024, 4, 1)), @@ -562,9 +556,6 @@ def bug_url(self) -> str: FieldTrial('WebRTC-Bwe-LossBasedBweV2', 42222865, date(2024, 4, 1)), - FieldTrial('WebRTC-Bwe-LossBasedControl', - NO_BUG, - date(2024, 4, 1)), FieldTrial('WebRTC-Bwe-MaxRttLimit', 42234928, INDEFINITE), @@ -790,9 +781,6 @@ def bug_url(self) -> str: FieldTrial('WebRTC-SpsPpsIdrIsH264Keyframe', 42233557, INDEFINITE), - FieldTrial('WebRTC-StableTargetRate', - 42220156, - date(2024, 4, 1)), FieldTrial('WebRTC-StrictPacingAndProbing', 42233198, date(2024, 4, 1)), @@ -911,7 +899,7 @@ def bug_url(self) -> str: ]) # yapf: disable POLICY_EXEMPT_FIELD_TRIALS_DIGEST: str = \ - '8e2640561e5ff33824da8ecf4f37b34eeaad92f3' + '625f8d689ab8bcfe4118347c6f8c852e3ac372c7' REGISTERED_FIELD_TRIALS: FrozenSet[FieldTrial] = ACTIVE_FIELD_TRIALS.union( POLICY_EXEMPT_FIELD_TRIALS) diff --git a/logging/BUILD.gn b/logging/BUILD.gn index a56f9266e4..65fe4b69f5 100644 --- a/logging/BUILD.gn +++ b/logging/BUILD.gn @@ -621,7 +621,6 @@ if (rtc_enable_protobuf) { "../rtc_base:buffer", "../rtc_base:checks", "../rtc_base:logging", - "../rtc_base:macromagic", "../rtc_base:random", "../rtc_base:rtc_base_tests_utils", "../rtc_base:safe_conversions", diff --git a/logging/rtc_event_log/encoder/delta_encoding_unittest.cc b/logging/rtc_event_log/encoder/delta_encoding_unittest.cc index 6f46ff9c3c..df9cb2f95c 100644 --- a/logging/rtc_event_log/encoder/delta_encoding_unittest.cc +++ b/logging/rtc_event_log/encoder/delta_encoding_unittest.cc @@ -21,9 +21,9 @@ #include #include -#include "rtc_base/arraysize.h" #include "rtc_base/checks.h" #include "rtc_base/random.h" +#include "test/gmock.h" #include "test/gtest.h" namespace webrtc { @@ -33,6 +33,9 @@ void UnsetFixedLengthEncoderDeltaSignednessForTesting(); namespace { +using ::testing::Each; +using ::testing::Eq; + enum class DeltaSignedness { kNoOverride, kForceUnsigned, kForceSigned }; void MaybeSetSignedness(DeltaSignedness signedness) { @@ -488,26 +491,24 @@ class DeltaEncodingCompressionQualityTest // If no wrap-around occurs in the stream, the width of the values does not // matter to compression performance; only the deltas matter. -TEST_P(DeltaEncodingCompressionQualityTest, - BaseDoesNotAffectEfficiencyIfNoWrapAround) { +TEST_P(DeltaEncodingCompressionQualityTest, BaseDoesNotAffectEfficiency) { // 1. Bases which will not produce a wrap-around. // 2. The last base - 0xffffffffffffffff - does cause a wrap-around, but // that still works, because the width is 64 anyway, and does not // need to be conveyed explicitly in the encoding header. const uint64_t bases[] = {0, 0x55, 0xffffffff, std::numeric_limits::max()}; - const size_t kIntendedWrapAroundBaseIndex = arraysize(bases); std::vector deltas(num_of_values_); // Allows us to make sure that the deltas do not produce a wrap-around. - uint64_t last_element[arraysize(bases)]; + uint64_t last_element[std::size(bases)]; memcpy(last_element, bases, sizeof(bases)); // Avoid empty `deltas` due to first element causing wrap-around. deltas[0] = 1; - for (size_t i = 0; i < arraysize(last_element); ++i) { - last_element[i] += 1; + for (uint64_t& element : last_element) { + ++element; } Random prng(Seed()); @@ -516,11 +517,7 @@ TEST_P(DeltaEncodingCompressionQualityTest, const uint64_t delta = RandomWithMaxBitWidth(&prng, delta_max_bit_width_); bool wrap_around = false; - for (size_t j = 0; j < arraysize(last_element); ++j) { - if (j == kIntendedWrapAroundBaseIndex) { - continue; - } - + for (size_t j = 0; j < std::size(last_element); ++j) { last_element[j] += delta; if (last_element[j] < bases[j]) { wrap_around = true; @@ -536,9 +533,9 @@ TEST_P(DeltaEncodingCompressionQualityTest, deltas[i] = delta; } - std::string encodings[arraysize(bases)]; + std::string encodings[std::size(bases)]; - for (size_t i = 0; i < arraysize(bases); ++i) { + for (size_t i = 0; i < std::size(bases); ++i) { const auto values = CreateSequenceByDeltas(bases[i], deltas, num_of_values_); // Produce the encoding and write it to encodings[i]. @@ -552,9 +549,7 @@ TEST_P(DeltaEncodingCompressionQualityTest, // Test focus - all of the encodings should be the same, as they are based // on the same delta sequence, and do not contain a wrap-around. - for (size_t i = 1; i < arraysize(encodings); ++i) { - EXPECT_EQ(encodings[i], encodings[0]); - } + EXPECT_THAT(encodings, Each(Eq(encodings[0]))); } INSTANTIATE_TEST_SUITE_P( diff --git a/logging/rtc_event_log/rtc_event_log_impl_unittest.cc b/logging/rtc_event_log/rtc_event_log_impl_unittest.cc index f2bde7534e..f1bc96f5e2 100644 --- a/logging/rtc_event_log/rtc_event_log_impl_unittest.cc +++ b/logging/rtc_event_log/rtc_event_log_impl_unittest.cc @@ -66,7 +66,7 @@ class FakeOutput : public RtcEventLogOutput { public: explicit FakeOutput(std::string& written_data) : written_data_(written_data) {} - bool IsActive() const { return is_active_; } + bool IsActive() const override { return is_active_; } bool Write(absl::string_view data) override { RTC_DCHECK(is_active_); if (fails_write_) { diff --git a/media/BUILD.gn b/media/BUILD.gn index 47782316a6..203a55ba9d 100644 --- a/media/BUILD.gn +++ b/media/BUILD.gn @@ -245,6 +245,7 @@ rtc_library("media_engine") { "../api:audio_options_api", "../api:field_trials_view", "../api:rtc_error", + "../api:rtp_headers", "../api:rtp_parameters", "../api:rtp_transceiver_direction", "../api:scoped_refptr", @@ -806,9 +807,11 @@ if (rtc_include_tests) { ":rtp_utils", ":stream_params", ":video_common", + "../api:array_view", "../api:audio_options_api", "../api:call_api", "../api:fec_controller_api", + "../api:field_trials_view", "../api:frame_transformer_interface", "../api:make_ref_counted", "../api:rtc_error", @@ -875,8 +878,7 @@ if (rtc_include_tests) { "../rtc_base/synchronization:mutex", "../rtc_base/system:file_wrapper", "../rtc_base/third_party/sigslot", - "../test:explicit_key_value_config", - "../test:scoped_key_value_config", + "../test:create_test_field_trials", "../test:test_support", "../video/config:encoder_config", "../video/config:streams_config", @@ -953,6 +955,7 @@ if (rtc_include_tests) { "../api:call_api", "../api:create_simulcast_test_fixture_api", "../api:fec_controller_api", + "../api:field_trials", "../api:make_ref_counted", "../api:mock_encoder_selector", "../api:mock_video_bitrate_allocator", @@ -981,7 +984,6 @@ if (rtc_include_tests) { "../api/test/video:function_video_factory", "../api/transport:bitrate_settings", "../api/transport:datagram_transport_interface", - "../api/transport:field_trial_based_config", "../api/transport/rtp:rtp_source", "../api/units:data_rate", "../api/units:time_delta", @@ -1040,10 +1042,9 @@ if (rtc_include_tests) { "../rtc_base/system:file_wrapper", "../system_wrappers", "../test:audio_codec_mocks", + "../test:create_test_field_trials", "../test:fake_video_codecs", - "../test:field_trial", "../test:rtp_test_utils", - "../test:scoped_key_value_config", "../test:test_main", "../test:test_support", "../test:video_test_common", diff --git a/media/base/adapted_video_track_source.h b/media/base/adapted_video_track_source.h index 74b3de4761..a6ef9e5fcf 100644 --- a/media/base/adapted_video_track_source.h +++ b/media/base/adapted_video_track_source.h @@ -74,7 +74,7 @@ class RTC_EXPORT AdaptedVideoTrackSource VideoAdapter* video_adapter() { return &video_adapter_; } private: - // Implements webrtc::VideoSourceInterface. + // Implements VideoSourceInterface. void AddOrUpdateSink(VideoSinkInterface* sink, const VideoSinkWants& wants) override; void RemoveSink(VideoSinkInterface* sink) override; diff --git a/media/base/audio_source.h b/media/base/audio_source.h index ee05352f2d..f7a7f50060 100644 --- a/media/base/audio_source.h +++ b/media/base/audio_source.h @@ -19,7 +19,7 @@ namespace webrtc { // Abstract interface for providing the audio data. // TODO(deadbeef): Rename this to AudioSourceInterface, and rename -// webrtc::AudioSourceInterface to AudioTrackSourceInterface. +// AudioSourceInterface to AudioTrackSourceInterface. class AudioSource { public: class Sink { diff --git a/media/base/codec.cc b/media/base/codec.cc index f97f082fd9..aa75ebe090 100644 --- a/media/base/codec.cc +++ b/media/base/codec.cc @@ -121,12 +121,12 @@ Codec::Codec(Type type) type == Type::kVideo ? kDefaultVideoClockRateHz : kDefaultAudioClockRateHz) {} -Codec::Codec(const webrtc::SdpAudioFormat& c) +Codec::Codec(const SdpAudioFormat& c) : Codec(Type::kAudio, kIdNotSet, c.name, c.clockrate_hz, c.num_channels) { params = c.parameters; } -Codec::Codec(const webrtc::SdpVideoFormat& c) +Codec::Codec(const SdpVideoFormat& c) : Codec(Type::kVideo, kIdNotSet, c.name, kVideoCodecClockrate) { params = c.parameters; scalability_modes = c.scalability_modes; @@ -148,11 +148,11 @@ bool Codec::operator==(const Codec& c) const { } bool Codec::Matches(const Codec& codec) const { - return webrtc::MatchesWithCodecRules(*this, codec); + return MatchesWithCodecRules(*this, codec); } -bool Codec::MatchesRtpCodec(const webrtc::RtpCodec& codec_capability) const { - webrtc::RtpCodecParameters codec_parameters = ToCodecParameters(); +bool Codec::MatchesRtpCodec(const RtpCodec& codec_capability) const { + RtpCodecParameters codec_parameters = ToCodecParameters(); return codec_parameters.name == codec_capability.name && codec_parameters.kind == codec_capability.kind && @@ -163,7 +163,7 @@ bool Codec::MatchesRtpCodec(const webrtc::RtpCodec& codec_capability) const { } bool Codec::GetParam(const std::string& key, std::string* out) const { - webrtc::CodecParameterMap::const_iterator iter = params.find(key); + CodecParameterMap::const_iterator iter = params.find(key); if (iter == params.end()) return false; *out = iter->second; @@ -171,10 +171,10 @@ bool Codec::GetParam(const std::string& key, std::string* out) const { } bool Codec::GetParam(const std::string& key, int* out) const { - webrtc::CodecParameterMap::const_iterator iter = params.find(key); + CodecParameterMap::const_iterator iter = params.find(key); if (iter == params.end()) return false; - return webrtc::FromString(iter->second, out); + return FromString(iter->second, out); } void Codec::SetParam(const std::string& key, const std::string& value) { @@ -202,7 +202,7 @@ void Codec::IntersectFeedbackParams(const Codec& other) { } webrtc::RtpCodecParameters Codec::ToCodecParameters() const { - webrtc::RtpCodecParameters codec_params; + RtpCodecParameters codec_params; codec_params.payload_type = id; codec_params.name = name; codec_params.clock_rate = clockrate; @@ -211,11 +211,11 @@ webrtc::RtpCodecParameters Codec::ToCodecParameters() const { switch (type) { case Type::kAudio: { codec_params.num_channels = static_cast(channels); - codec_params.kind = webrtc::MediaType::AUDIO; + codec_params.kind = MediaType::AUDIO; break; } case Type::kVideo: { - codec_params.kind = webrtc::MediaType::VIDEO; + codec_params.kind = MediaType::VIDEO; break; } } @@ -334,7 +334,7 @@ bool HasRrtr(const Codec& codec) { const Codec* FindMatchingVideoCodec(const std::vector& supported_codecs, const Codec& codec) { - webrtc::SdpVideoFormat sdp_video_format{codec.name, codec.params}; + SdpVideoFormat sdp_video_format{codec.name, codec.params}; for (const Codec& supported_codec : supported_codecs) { if (sdp_video_format.IsSameCodec( {supported_codec.name, supported_codec.params})) { @@ -348,7 +348,7 @@ std::vector FindAllMatchingCodecs( const std::vector& supported_codecs, const Codec& codec) { std::vector result; - webrtc::SdpVideoFormat sdp(codec.name, codec.params); + SdpVideoFormat sdp(codec.name, codec.params); for (const Codec& supported_codec : supported_codecs) { if (sdp.IsSameCodec({supported_codec.name, supported_codec.params})) { result.push_back(&supported_codec); @@ -360,24 +360,23 @@ std::vector FindAllMatchingCodecs( // If a decoder supports any H264 profile, it is implicitly assumed to also // support constrained base line even though it's not explicitly listed. void AddH264ConstrainedBaselineProfileToSupportedFormats( - std::vector* supported_formats) { - std::vector cbr_supported_formats; + std::vector* supported_formats) { + std::vector cbr_supported_formats; // For any H264 supported profile, add the corresponding constrained baseline // profile. for (auto it = supported_formats->cbegin(); it != supported_formats->cend(); ++it) { if (it->name == kH264CodecName) { - const std::optional profile_level_id = - webrtc::ParseSdpForH264ProfileLevelId(it->parameters); - if (profile_level_id && - profile_level_id->profile != - webrtc::H264Profile::kProfileConstrainedBaseline) { - webrtc::SdpVideoFormat cbp_format = *it; - webrtc::H264ProfileLevelId cbp_profile = *profile_level_id; - cbp_profile.profile = webrtc::H264Profile::kProfileConstrainedBaseline; + const std::optional profile_level_id = + ParseSdpForH264ProfileLevelId(it->parameters); + if (profile_level_id && profile_level_id->profile != + H264Profile::kProfileConstrainedBaseline) { + SdpVideoFormat cbp_format = *it; + H264ProfileLevelId cbp_profile = *profile_level_id; + cbp_profile.profile = H264Profile::kProfileConstrainedBaseline; cbp_format.parameters[kH264FmtpProfileLevelId] = - *webrtc::H264ProfileLevelIdToString(cbp_profile); + *H264ProfileLevelIdToString(cbp_profile); cbr_supported_formats.push_back(cbp_format); } } @@ -387,7 +386,7 @@ void AddH264ConstrainedBaselineProfileToSupportedFormats( // ...if it's not already in the list. std::copy_if(cbr_supported_formats.begin(), cbr_supported_formats.end(), std::back_inserter(*supported_formats), - [supported_formats](const webrtc::SdpVideoFormat& format) { + [supported_formats](const SdpVideoFormat& format) { return !format.IsCodecInList(*supported_formats); }); @@ -404,7 +403,7 @@ Codec CreateAudioCodec(int id, return Codec(Codec::Type::kAudio, id, name, clockrate, channels); } -Codec CreateAudioCodec(const webrtc::SdpAudioFormat& c) { +Codec CreateAudioCodec(const SdpAudioFormat& c) { return Codec(c); } @@ -424,11 +423,11 @@ Codec CreateVideoCodec(int id, const std::string& name) { return c; } -Codec CreateVideoCodec(const webrtc::SdpVideoFormat& c) { +Codec CreateVideoCodec(const SdpVideoFormat& c) { return Codec(c); } -Codec CreateVideoCodec(int id, const webrtc::SdpVideoFormat& sdp) { +Codec CreateVideoCodec(int id, const SdpVideoFormat& sdp) { Codec c = CreateVideoCodec(sdp); c.id = id; return c; diff --git a/media/base/codec.h b/media/base/codec.h index 9566f37e73..694589dd14 100644 --- a/media/base/codec.h +++ b/media/base/codec.h @@ -99,8 +99,7 @@ struct RTC_EXPORT Codec { // Video only std::optional packetization; - absl::InlinedVector - scalability_modes; + absl::InlinedVector scalability_modes; // H.265 only std::optional tx_mode; @@ -108,7 +107,7 @@ struct RTC_EXPORT Codec { // Non key-value parameters such as the telephone-event "0‐15" are // represented using an empty string as key, i.e. {"": "0-15"}. // The equivalent of fmtp in SDP. - webrtc::CodecParameterMap params; + CodecParameterMap params; // The equivalent of rtcp-fb in SDP. FeedbackParams feedback_params; @@ -138,7 +137,7 @@ struct RTC_EXPORT Codec { // - parameters is compared element-wise, not as a string comparison. // This method should only be used to compare input on our end to something we // generated, done e.g. by setCodecPreferences or setParameters. - bool MatchesRtpCodec(const webrtc::RtpCodec& capability) const; + bool MatchesRtpCodec(const RtpCodec& capability) const; // Find the parameter for `key` and write the value to `out`. bool GetParam(const std::string& key, std::string* out) const; @@ -158,7 +157,7 @@ struct RTC_EXPORT Codec { // and `other` are kept. void IntersectFeedbackParams(const Codec& other); - virtual webrtc::RtpCodecParameters ToCodecParameters() const; + virtual RtpCodecParameters ToCodecParameters() const; // The codec represent an actual media codec, and not a resiliency codec. bool IsMediaCodec() const; @@ -213,18 +212,18 @@ struct RTC_EXPORT Codec { int clockrate, size_t channels); - explicit Codec(const webrtc::SdpAudioFormat& c); - explicit Codec(const webrtc::SdpVideoFormat& c); + explicit Codec(const SdpAudioFormat& c); + explicit Codec(const SdpVideoFormat& c); friend Codec CreateAudioCodec(int id, const std::string& name, int clockrate, size_t channels); - friend Codec CreateAudioCodec(const webrtc::SdpAudioFormat& c); + friend Codec CreateAudioCodec(const SdpAudioFormat& c); friend Codec CreateAudioRtxCodec(int rtx_payload_type, int associated_payload_type); friend Codec CreateVideoCodec(int id, const std::string& name); - friend Codec CreateVideoCodec(const webrtc::SdpVideoFormat& c); + friend Codec CreateVideoCodec(const SdpVideoFormat& c); friend Codec CreateVideoRtxCodec(int rtx_payload_type, int associated_payload_type); }; @@ -235,12 +234,12 @@ Codec CreateAudioCodec(int id, const std::string& name, int clockrate, size_t channels); -Codec CreateAudioCodec(const webrtc::SdpAudioFormat& c); +Codec CreateAudioCodec(const SdpAudioFormat& c); Codec CreateAudioRtxCodec(int rtx_payload_type, int associated_payload_type); Codec CreateVideoCodec(const std::string& name); Codec CreateVideoCodec(int id, const std::string& name); -Codec CreateVideoCodec(const webrtc::SdpVideoFormat& c); -Codec CreateVideoCodec(int id, const webrtc::SdpVideoFormat& sdp); +Codec CreateVideoCodec(const SdpVideoFormat& c); +Codec CreateVideoCodec(int id, const SdpVideoFormat& sdp); Codec CreateVideoRtxCodec(int rtx_payload_type, int associated_payload_type); // Get the codec setting associated with `payload_type`. If there @@ -263,7 +262,7 @@ std::vector FindAllMatchingCodecs( const Codec& codec); RTC_EXPORT void AddH264ConstrainedBaselineProfileToSupportedFormats( - std::vector* supported_formats); + std::vector* supported_formats); } // namespace webrtc // Re-export symbols from the webrtc namespace for backwards compatibility. diff --git a/media/base/codec_comparators.cc b/media/base/codec_comparators.cc index 02ed96ac7c..e71c52db26 100644 --- a/media/base/codec_comparators.cc +++ b/media/base/codec_comparators.cc @@ -186,7 +186,7 @@ bool MatchesWithReferenceAttributesAndComparator( split(red_parameters_1->second, '/'); std::vector redundant_payloads_2 = split(red_parameters_2->second, '/'); - // note: webrtc::split returns at least 1 string even on empty strings. + // note: split returns at least 1 string even on empty strings. size_t smallest_size = std::min(redundant_payloads_1.size(), redundant_payloads_2.size()); // If the smaller list is equivalent to the longer list, we consider them diff --git a/media/base/fake_frame_source.h b/media/base/fake_frame_source.h index f87473c4b1..7f3ad561aa 100644 --- a/media/base/fake_frame_source.h +++ b/media/base/fake_frame_source.h @@ -43,7 +43,7 @@ class FakeFrameSource { const int height_; const int interval_us_; - VideoRotation rotation_ = webrtc::kVideoRotation_0; + VideoRotation rotation_ = kVideoRotation_0; int64_t next_timestamp_us_; }; diff --git a/media/base/fake_media_engine.h b/media/base/fake_media_engine.h index 132205817c..8c05e4a797 100644 --- a/media/base/fake_media_engine.h +++ b/media/base/fake_media_engine.h @@ -70,7 +70,7 @@ #include "rtc_base/network/sent_packet.h" #include "rtc_base/network_route.h" #include "rtc_base/system/file_wrapper.h" -#include "test/explicit_key_value_config.h" +#include "test/create_test_field_trials.h" namespace webrtc { @@ -162,7 +162,7 @@ class RtpReceiveChannelHelper : public Base, public MediaChannelUtil { return RtpParameters(); } - const std::vector& recv_streams() const { + const std::vector& recv_streams() const { return receive_streams_; } bool HasRecvStream(uint32_t ssrc) const { @@ -189,12 +189,12 @@ class RtpReceiveChannelHelper : public Base, public MediaChannelUtil { } void SetFrameDecryptor(uint32_t /* ssrc */, - scoped_refptr + scoped_refptr /* frame_decryptor */) override {} void SetDepacketizerToDecoderFrameTransformer( uint32_t /* ssrc */, - scoped_refptr /* frame_transformer */) + scoped_refptr /* frame_transformer */) override {} void SetInterface(MediaChannelNetworkInterface* iface) override { @@ -331,7 +331,10 @@ class RtpSendChannelHelper : public Base, public MediaChannelUtil { RtpParameters GetRtpSendParameters(uint32_t ssrc) const override { auto parameters_iterator = rtp_send_parameters_.find(ssrc); if (parameters_iterator != rtp_send_parameters_.end()) { - return parameters_iterator->second; + // Take header extensions from channel global, not iterated. + auto parameters = parameters_iterator->second; + parameters.header_extensions = send_extensions_; + return parameters; } return RtpParameters(); } @@ -341,15 +344,14 @@ class RtpSendChannelHelper : public Base, public MediaChannelUtil { auto parameters_iterator = rtp_send_parameters_.find(ssrc); if (parameters_iterator != rtp_send_parameters_.end()) { auto result = CheckRtpParametersInvalidModificationAndValues( - parameters_iterator->second, parameters, - test::ExplicitKeyValueConfig("")); + parameters_iterator->second, parameters, CreateTestFieldTrials()); if (!result.ok()) { - return webrtc::InvokeSetParametersCallback(callback, result); + return InvokeSetParametersCallback(callback, result); } parameters_iterator->second = parameters; - return webrtc::InvokeSetParametersCallback(callback, RTCError::OK()); + return InvokeSetParametersCallback(callback, RTCError::OK()); } // Replicate the behavior of the real media channel: return false // when setting parameters for unknown SSRCs. @@ -366,7 +368,7 @@ class RtpSendChannelHelper : public Base, public MediaChannelUtil { } return ret; } - const std::vector& send_streams() const { + const std::vector& send_streams() const { return send_streams_; } bool HasSendStream(uint32_t ssrc) const { @@ -403,11 +405,11 @@ class RtpSendChannelHelper : public Base, public MediaChannelUtil { // Stuff that deals with encryptors, transformers and the like void SetFrameEncryptor(uint32_t /* ssrc */, - scoped_refptr + scoped_refptr /* frame_encryptor */) override {} void SetEncoderToPacketizerFrameTransformer( uint32_t /* ssrc */, - scoped_refptr /* frame_transformer */) + scoped_refptr /* frame_transformer */) override {} void SetInterface(MediaChannelNetworkInterface* iface) override { diff --git a/media/base/fake_network_interface.h b/media/base/fake_network_interface.h index 1ef126ffa7..e3b60a1cf7 100644 --- a/media/base/fake_network_interface.h +++ b/media/base/fake_network_interface.h @@ -125,12 +125,12 @@ class FakeNetworkInterface : public MediaChannelNetworkInterface { virtual bool SendPacket(CopyOnWriteBuffer* packet, const AsyncSocketPacketOptions& options) RTC_LOCKS_EXCLUDED(mutex_) { - if (!webrtc::IsRtpPacket(*packet)) { + if (!IsRtpPacket(*packet)) { return false; } MutexLock lock(&mutex_); - sent_ssrcs_[webrtc::ParseRtpSsrc(*packet)]++; + sent_ssrcs_[ParseRtpSsrc(*packet)]++; options_ = options; rtp_packets_.push_back(*packet); @@ -188,7 +188,7 @@ class FakeNetworkInterface : public MediaChannelNetworkInterface { private: void SetRtpSsrc(uint32_t ssrc, CopyOnWriteBuffer& buffer) { RTC_CHECK_GE(buffer.size(), 12); - webrtc::SetBE32(buffer.MutableData() + 8, ssrc); + SetBE32(buffer.MutableData() + 8, ssrc); } void GetNumRtpBytesAndPackets(uint32_t ssrc, int* bytes, int* packets) { @@ -199,7 +199,7 @@ class FakeNetworkInterface : public MediaChannelNetworkInterface { *packets = 0; } for (size_t i = 0; i < rtp_packets_.size(); ++i) { - if (ssrc == webrtc::ParseRtpSsrc(rtp_packets_[i])) { + if (ssrc == ParseRtpSsrc(rtp_packets_[i])) { if (bytes) { *bytes += static_cast(rtp_packets_[i].size()); } diff --git a/media/base/fake_video_renderer.h b/media/base/fake_video_renderer.h index ad894883f5..4b0e08eaa7 100644 --- a/media/base/fake_video_renderer.h +++ b/media/base/fake_video_renderer.h @@ -59,7 +59,7 @@ class FakeVideoRenderer : public VideoSinkInterface { private: int width_ = 0; int height_ = 0; - VideoRotation rotation_ = webrtc::kVideoRotation_0; + VideoRotation rotation_ = kVideoRotation_0; int64_t timestamp_us_ = 0; int num_rendered_frames_ = 0; bool black_frame_ = false; diff --git a/media/base/media_channel.h b/media/base/media_channel.h index b1f026372a..1a74631f17 100644 --- a/media/base/media_channel.h +++ b/media/base/media_channel.h @@ -150,7 +150,7 @@ struct VideoOptions { // things, e.g., screencast of a text document and screencast of a // youtube video have different needs. std::optional is_screencast; - webrtc::VideoTrackInterface::ContentHint content_hint; + VideoTrackInterface::ContentHint content_hint; private: template @@ -168,9 +168,7 @@ class MediaChannelNetworkInterface { const AsyncSocketPacketOptions& options) = 0; virtual bool SendRtcp(CopyOnWriteBuffer* packet, const AsyncSocketPacketOptions& options) = 0; - virtual int SetOption(SocketType type, - webrtc::Socket::Option opt, - int option) = 0; + virtual int SetOption(SocketType type, Socket::Option opt, int option) = 0; virtual ~MediaChannelNetworkInterface() {} }; @@ -181,14 +179,14 @@ class MediaSendChannelInterface { virtual VideoMediaSendChannelInterface* AsVideoSendChannel() = 0; virtual VoiceMediaSendChannelInterface* AsVoiceSendChannel() = 0; - virtual webrtc::MediaType media_type() const = 0; + virtual MediaType media_type() const = 0; // Gets the currently set codecs/payload types to be used for outgoing media. - virtual std::optional GetSendCodec() const = 0; + virtual std::optional GetSendCodec() const = 0; // Creates a new outgoing media stream with SSRCs and CNAME as described // by sp. - virtual bool AddSendStream(const webrtc::StreamParams& sp) = 0; + virtual bool AddSendStream(const StreamParams& sp) = 0; // Removes an outgoing media stream. // SSRC must be the first SSRC of the media stream if the stream uses // multiple SSRCs. In the case of an ssrc of 0, the possibly cached @@ -200,9 +198,8 @@ class MediaSendChannelInterface { // Called when the socket's ability to send has changed. virtual void OnReadyToSend(bool ready) = 0; // Called when the network route used for sending packets changed. - virtual void OnNetworkRouteChanged( - absl::string_view transport_name, - const webrtc::NetworkRoute& network_route) = 0; + virtual void OnNetworkRouteChanged(absl::string_view transport_name, + const NetworkRoute& network_route) = 0; // Sets the abstract interface class for sending RTP/RTCP data. virtual void SetInterface(MediaChannelNetworkInterface* iface) = 0; @@ -222,24 +219,23 @@ class MediaSendChannelInterface { // to. virtual void SetFrameEncryptor( uint32_t ssrc, - scoped_refptr frame_encryptor) = 0; + scoped_refptr frame_encryptor) = 0; - virtual webrtc::RTCError SetRtpSendParameters( + virtual RTCError SetRtpSendParameters( uint32_t ssrc, - const webrtc::RtpParameters& parameters, - webrtc::SetParametersCallback callback = nullptr) = 0; + const RtpParameters& parameters, + SetParametersCallback callback = nullptr) = 0; virtual void SetEncoderToPacketizerFrameTransformer( uint32_t ssrc, - scoped_refptr frame_transformer) = 0; + scoped_refptr frame_transformer) = 0; // note: The encoder_selector object must remain valid for the lifetime of the // MediaChannel, unless replaced. virtual void SetEncoderSelector( uint32_t /* ssrc */, - webrtc::VideoEncoderFactory:: - EncoderSelectorInterface* /* encoder_selector */) {} - virtual webrtc::RtpParameters GetRtpSendParameters(uint32_t ssrc) const = 0; + VideoEncoderFactory::EncoderSelectorInterface* /* encoder_selector */) {} + virtual RtpParameters GetRtpSendParameters(uint32_t ssrc) const = 0; virtual bool SendCodecHasNack() const = 0; // Called whenever the list of sending SSRCs changes. virtual void SetSsrcListChangedCallback( @@ -256,11 +252,11 @@ class MediaReceiveChannelInterface { virtual VideoMediaReceiveChannelInterface* AsVideoReceiveChannel() = 0; virtual VoiceMediaReceiveChannelInterface* AsVoiceReceiveChannel() = 0; - virtual webrtc::MediaType media_type() const = 0; + virtual MediaType media_type() const = 0; // Creates a new incoming media stream with SSRCs, CNAME as described // by sp. In the case of a sp without SSRCs, the unsignaled sp is cached // to be used later for unsignaled streams received. - virtual bool AddRecvStream(const webrtc::StreamParams& sp) = 0; + virtual bool AddRecvStream(const StreamParams& sp) = 0; // Removes an incoming media stream. // ssrc must be the first SSRC of the media stream if the stream uses // multiple SSRCs. @@ -271,7 +267,7 @@ class MediaReceiveChannelInterface { // Sets the abstract interface class for sending RTP/RTCP data. virtual void SetInterface(MediaChannelNetworkInterface* iface) = 0; // Called on the network when an RTP packet is received. - virtual void OnPacketReceived(const webrtc::RtpPacketReceived& packet) = 0; + virtual void OnPacketReceived(const RtpPacketReceived& packet) = 0; // Gets the current unsignaled receive stream's SSRC, if there is one. virtual std::optional GetUnsignaledSsrc() const = 0; // Sets the local SSRC for listening to incoming RTCP reports. @@ -295,11 +291,11 @@ class MediaReceiveChannelInterface { // attached to. virtual void SetFrameDecryptor( uint32_t ssrc, - scoped_refptr frame_decryptor) = 0; + scoped_refptr frame_decryptor) = 0; virtual void SetDepacketizerToDecoderFrameTransformer( uint32_t ssrc, - scoped_refptr frame_transformer) = 0; + scoped_refptr frame_transformer) = 0; // Set base minimum delay of the receive stream with specified ssrc. // Base minimum delay sets lower bound on minimum delay value which @@ -375,7 +371,7 @@ struct MediaSenderInfo { // https://w3c.github.io/webrtc-stats/#dom-rtcoutboundrtpstreamstats-nackcount uint32_t nacks_received = 0; // https://w3c.github.io/webrtc-stats/#dom-rtcoutboundrtpstreamstats-targetbitrate - std::optional target_bitrate; + std::optional target_bitrate; int packets_lost = 0; float fraction_lost = 0.0f; int64_t rtt_ms = 0; @@ -387,10 +383,10 @@ struct MediaSenderInfo { // to statistics. Used to implement RTCRemoteInboundRtpStreamStats. Within // this list, the `ReportBlockData::source_ssrc()`, which is the SSRC of the // corresponding outbound RTP stream, is unique. - std::vector report_block_datas; + std::vector report_block_datas; std::optional active; // https://w3c.github.io/webrtc-stats/#dom-rtcoutboundrtpstreamstats-totalpacketsenddelay - webrtc::TimeDelta total_packet_send_delay = webrtc::TimeDelta::Zero(); + TimeDelta total_packet_send_delay = TimeDelta::Zero(); }; struct MediaReceiverInfo { @@ -453,7 +449,7 @@ struct MediaReceiverInfo { // The timestamp at which the last packet was received, i.e. the time of the // local clock when it was received - not the RTP timestamp of that packet. // https://w3c.github.io/webrtc-stats/#dom-rtcinboundrtpstreamstats-lastpacketreceivedtimestamp - std::optional last_packet_received; + std::optional last_packet_received; // https://w3c.github.io/webrtc-stats/#dom-rtcinboundrtpstreamstats-estimatedplayouttimestamp std::optional estimated_playout_ntp_timestamp_ms; std::string codec_name; @@ -471,18 +467,18 @@ struct MediaReceiverInfo { // Remote outbound stats derived by the received RTCP sender reports. // https://w3c.github.io/webrtc-stats/#remoteoutboundrtpstats-dict* - std::optional last_sender_report_timestamp; + std::optional last_sender_report_timestamp; // TODO: bugs.webrtc.org/370535296 - Remove the utc timestamp when linked // issue is fixed. - std::optional last_sender_report_utc_timestamp; - std::optional last_sender_report_remote_utc_timestamp; + std::optional last_sender_report_utc_timestamp; + std::optional last_sender_report_remote_utc_timestamp; uint64_t sender_reports_packets_sent = 0; uint64_t sender_reports_bytes_sent = 0; uint64_t sender_reports_reports_count = 0; // These require a DLRR block, see // https://w3c.github.io/webrtc-stats/#dom-rtcremoteoutboundrtpstreamstats-roundtriptime - std::optional round_trip_time; - webrtc::TimeDelta total_round_trip_time = webrtc::TimeDelta::Zero(); + std::optional round_trip_time; + TimeDelta total_round_trip_time = TimeDelta::Zero(); int round_trip_time_measurements = 0; }; @@ -496,8 +492,8 @@ struct VoiceSenderInfo : public MediaSenderInfo { // https://w3c.github.io/webrtc-stats/#dom-rtcmediastreamtrackstats-totalaudioenergy double total_input_energy = 0.0; double total_input_duration = 0.0; - webrtc::ANAStats ana_statistics; - webrtc::AudioProcessingStats apm_statistics; + ANAStats ana_statistics; + AudioProcessingStats apm_statistics; }; struct VoiceReceiverInfo : public MediaReceiverInfo { @@ -565,7 +561,7 @@ struct VideoSenderInfo : public MediaSenderInfo { VideoSenderInfo(); ~VideoSenderInfo(); std::optional encoding_index; - std::vector ssrc_groups; + std::vector ssrc_groups; std::optional encoder_implementation_name; int firs_received = 0; int plis_received = 0; @@ -579,11 +575,10 @@ struct VideoSenderInfo : public MediaSenderInfo { int adapt_reason = 0; int adapt_changes = 0; // https://w3c.github.io/webrtc-stats/#dom-rtcoutboundrtpstreamstats-qualitylimitationreason - webrtc::QualityLimitationReason quality_limitation_reason = - webrtc::QualityLimitationReason::kNone; + QualityLimitationReason quality_limitation_reason = + QualityLimitationReason::kNone; // https://w3c.github.io/webrtc-stats/#dom-rtcoutboundrtpstreamstats-qualitylimitationdurations - std::map - quality_limitation_durations_ms; + std::map quality_limitation_durations_ms; // https://w3c.github.io/webrtc-stats/#dom-rtcoutboundrtpstreamstats-qualitylimitationresolutionchanges uint32_t quality_limitation_resolution_changes = 0; int avg_encode_ms = 0; @@ -596,20 +591,20 @@ struct VideoSenderInfo : public MediaSenderInfo { uint64_t total_encoded_bytes_target = 0; bool has_entered_low_resolution = false; std::optional qp_sum; - webrtc::VideoContentType content_type = webrtc::VideoContentType::UNSPECIFIED; + VideoContentType content_type = VideoContentType::UNSPECIFIED; uint32_t frames_sent = 0; // https://w3c.github.io/webrtc-stats/#dom-rtcvideosenderstats-hugeframessent uint32_t huge_frames_sent = 0; uint32_t aggregated_huge_frames_sent = 0; std::optional rid; std::optional power_efficient_encoder; - std::optional scalability_mode; + std::optional scalability_mode; }; struct VideoReceiverInfo : public MediaReceiverInfo { VideoReceiverInfo(); ~VideoReceiverInfo(); - std::vector ssrc_groups; + std::vector ssrc_groups; std::optional decoder_implementation_name; std::optional power_efficient_decoder; int packets_concealed = 0; @@ -642,10 +637,10 @@ struct VideoReceiverInfo : public MediaReceiverInfo { // usually not the same as `frames_decoded` or `frames_rendered`. uint32_t corruption_score_count = 0; // https://w3c.github.io/webrtc-stats/#dom-rtcinboundrtpstreamstats-totaldecodetime - webrtc::TimeDelta total_decode_time = webrtc::TimeDelta::Zero(); + TimeDelta total_decode_time = TimeDelta::Zero(); // https://w3c.github.io/webrtc-stats/#dom-rtcinboundrtpstreamstats-totalprocessingdelay - webrtc::TimeDelta total_processing_delay = webrtc::TimeDelta::Zero(); - webrtc::TimeDelta total_assembly_time = webrtc::TimeDelta::Zero(); + TimeDelta total_processing_delay = TimeDelta::Zero(); + TimeDelta total_assembly_time = TimeDelta::Zero(); uint32_t frames_assembled_from_multiple_packets = 0; double total_inter_frame_delay = 0; double total_squared_inter_frame_delay = 0; @@ -656,7 +651,7 @@ struct VideoReceiverInfo : public MediaReceiverInfo { uint32_t total_pauses_duration_ms = 0; uint32_t jitter_ms = 0; - webrtc::VideoContentType content_type = webrtc::VideoContentType::UNSPECIFIED; + VideoContentType content_type = VideoContentType::UNSPECIFIED; // All stats below are gathered per-VideoReceiver, but some will be correlated // across MediaStreamTracks. NOTE(hta): when sinking stats into per-SSRC @@ -686,7 +681,7 @@ struct VideoReceiverInfo : public MediaReceiverInfo { // Timing frame info: all important timestamps for a full lifetime of a // single 'timing frame'. - std::optional timing_frame_info; + std::optional timing_frame_info; }; struct BandwidthEstimationInfo { @@ -700,7 +695,7 @@ struct BandwidthEstimationInfo { }; // Maps from payload type to `RtpCodecParameters`. -typedef std::map RtpCodecParametersMap; +typedef std::map RtpCodecParametersMap; // Stats returned from VoiceMediaSendChannel.GetStats() struct VoiceMediaSendInfo { @@ -823,8 +818,8 @@ struct MediaChannelParameters { // It is also used as a key to map the channel to its transport. std::string mid; - std::vector codecs; - std::vector extensions; + std::vector codecs; + std::vector extensions; // For a send stream this is true if we've negotiated a send direction, // for a receive stream this is true if we've negotiated a receive direction. bool is_stream_active = true; @@ -874,7 +869,7 @@ struct SenderParameters : MediaChannelParameters { struct AudioSenderParameter : SenderParameters { AudioSenderParameter(); ~AudioSenderParameter() override; - webrtc::AudioOptions options; + AudioOptions options; protected: std::map ToStringMap() const override; @@ -890,8 +885,8 @@ class VoiceMediaSendChannelInterface : public MediaSendChannelInterface { // Configure stream for sending. virtual bool SetAudioSend(uint32_t ssrc, bool enable, - const webrtc::AudioOptions* options, - webrtc::AudioSource* source) = 0; + const AudioOptions* options, + AudioSource* source) = 0; // Returns if the telephone-event has been negotiated. virtual bool CanInsertDtmf() = 0; // Send a DTMF `event`. The DTMF out-of-band signal will be used. @@ -908,26 +903,24 @@ class VoiceMediaReceiveChannelInterface : public MediaReceiveChannelInterface { public: virtual bool SetReceiverParameters(const AudioReceiverParameters& params) = 0; // Get the receive parameters for the incoming stream identified by `ssrc`. - virtual webrtc::RtpParameters GetRtpReceiverParameters( - uint32_t ssrc) const = 0; - virtual std::vector GetSources(uint32_t ssrc) const = 0; + virtual RtpParameters GetRtpReceiverParameters(uint32_t ssrc) const = 0; + virtual std::vector GetSources(uint32_t ssrc) const = 0; // Retrieve the receive parameters for the default receive // stream, which is used when SSRCs are not signaled. - virtual webrtc::RtpParameters GetDefaultRtpReceiveParameters() const = 0; + virtual RtpParameters GetDefaultRtpReceiveParameters() const = 0; // Starts or stops playout of received audio. virtual void SetPlayout(bool playout) = 0; // Set speaker output volume of the specified ssrc. virtual bool SetOutputVolume(uint32_t ssrc, double volume) = 0; // Set speaker output volume for future unsignaled streams. virtual bool SetDefaultOutputVolume(double volume) = 0; - virtual void SetRawAudioSink( - uint32_t ssrc, - std::unique_ptr sink) = 0; + virtual void SetRawAudioSink(uint32_t ssrc, + std::unique_ptr sink) = 0; virtual void SetDefaultRawAudioSink( - std::unique_ptr sink) = 0; + std::unique_ptr sink) = 0; virtual bool GetStats(VoiceMediaReceiveInfo* stats, bool reset_legacy) = 0; - virtual webrtc::RtcpMode RtcpMode() const = 0; - virtual void SetRtcpMode(webrtc::RtcpMode mode) = 0; + virtual enum RtcpMode RtcpMode() const = 0; + virtual void SetRtcpMode(enum RtcpMode mode) = 0; virtual void SetReceiveNackEnabled(bool enabled) = 0; virtual void SetReceiveNonSenderRttEnabled(bool enabled) = 0; }; @@ -956,17 +949,16 @@ class VideoMediaSendChannelInterface : public MediaSendChannelInterface { virtual bool SetSend(bool send) = 0; // Configure stream for sending and register a source. // The `ssrc` must correspond to a registered send stream. - virtual bool SetVideoSend( - uint32_t ssrc, - const VideoOptions* options, - webrtc::VideoSourceInterface* source) = 0; + virtual bool SetVideoSend(uint32_t ssrc, + const VideoOptions* options, + VideoSourceInterface* source) = 0; // Cause generation of a keyframe for `ssrc` on a sending channel. virtual void GenerateSendKeyFrame(uint32_t ssrc, const std::vector& rids) = 0; virtual bool GetStats(VideoMediaSendInfo* stats) = 0; // This fills the "bitrate parts" (rtx, video bitrate) of the // BandwidthEstimationInfo, since that part that isn't possible to get - // through webrtc::Call::GetStats, as they are statistics of the send + // through Call::GetStats, as they are statistics of the send // streams. // TODO(holmer): We should change this so that either BWE graphs doesn't // need access to bitrates of the streams, or change the (RTC)StatsCollector @@ -974,7 +966,7 @@ class VideoMediaSendChannelInterface : public MediaSendChannelInterface { // GetStats(), and merges with BandwidthEstimationInfo by itself. virtual void FillBitrateInfo(BandwidthEstimationInfo* bwe_info) = 0; // Information queries to support SetReceiverFeedbackParameters - virtual webrtc::RtcpMode SendCodecRtcpMode() const = 0; + virtual RtcpMode SendCodecRtcpMode() const = 0; virtual bool SendCodecHasLntf() const = 0; virtual std::optional SendCodecRtxTime() const = 0; }; @@ -983,38 +975,33 @@ class VideoMediaReceiveChannelInterface : public MediaReceiveChannelInterface { public: virtual bool SetReceiverParameters(const VideoReceiverParameters& params) = 0; // Get the receive parameters for the incoming stream identified by `ssrc`. - virtual webrtc::RtpParameters GetRtpReceiverParameters( - uint32_t ssrc) const = 0; + virtual RtpParameters GetRtpReceiverParameters(uint32_t ssrc) const = 0; // Starts or stops decoding of remote video. virtual void SetReceive(bool receive) = 0; // Retrieve the receive parameters for the default receive // stream, which is used when SSRCs are not signaled. - virtual webrtc::RtpParameters GetDefaultRtpReceiveParameters() const = 0; + virtual RtpParameters GetDefaultRtpReceiveParameters() const = 0; // Sets the sink object to be used for the specified stream. - virtual bool SetSink( - uint32_t ssrc, - webrtc::VideoSinkInterface* sink) = 0; + virtual bool SetSink(uint32_t ssrc, VideoSinkInterface* sink) = 0; // The sink is used for the 'default' stream. - virtual void SetDefaultSink( - webrtc::VideoSinkInterface* sink) = 0; + virtual void SetDefaultSink(VideoSinkInterface* sink) = 0; // Request generation of a keyframe for `ssrc` on a receiving channel via // RTCP feedback. virtual void RequestRecvKeyFrame(uint32_t ssrc) = 0; - virtual std::vector GetSources(uint32_t ssrc) const = 0; + virtual std::vector GetSources(uint32_t ssrc) const = 0; // Set recordable encoded frame callback for `ssrc` virtual void SetRecordableEncodedFrameCallback( uint32_t ssrc, - std::function callback) = 0; + std::function callback) = 0; // Clear recordable encoded frame callback for `ssrc` virtual void ClearRecordableEncodedFrameCallback(uint32_t ssrc) = 0; virtual bool GetStats(VideoMediaReceiveInfo* stats) = 0; virtual void SetReceiverFeedbackParameters(bool lntf_enabled, bool nack_enabled, - webrtc::RtcpMode rtcp_mode, + RtcpMode rtcp_mode, std::optional rtx_time) = 0; - virtual bool AddDefaultRecvStreamForTesting( - const webrtc::StreamParams& sp) = 0; + virtual bool AddDefaultRecvStreamForTesting(const StreamParams& sp) = 0; }; } // namespace webrtc diff --git a/media/base/media_channel_impl.cc b/media/base/media_channel_impl.cc index b88007703c..6d4d4a2363 100644 --- a/media/base/media_channel_impl.cc +++ b/media/base/media_channel_impl.cc @@ -73,7 +73,7 @@ bool MediaChannelUtil::SendRtcp(CopyOnWriteBuffer* packet, } int MediaChannelUtil::SetOption(MediaChannelNetworkInterface::SocketType type, - webrtc::Socket::Option opt, + Socket::Option opt, int option) { return transport_.SetOption(type, opt, option); } @@ -98,7 +98,7 @@ bool MediaChannelUtil::DscpEnabled() const { return transport_.DscpEnabled(); } -void MediaChannelUtil::SetPreferredDscp(webrtc::DiffServCodePoint new_dscp) { +void MediaChannelUtil::SetPreferredDscp(DiffServCodePoint new_dscp) { transport_.SetPreferredDscp(new_dscp); } @@ -159,9 +159,9 @@ std::map VideoSenderParameters::ToStringMap() const { // --------------------- MediaChannelUtil::TransportForMediaChannels ----- MediaChannelUtil::TransportForMediaChannels::TransportForMediaChannels( - webrtc::TaskQueueBase* network_thread, + TaskQueueBase* network_thread, bool enable_dscp) - : network_safety_(webrtc::PendingTaskSafetyFlag::CreateDetachedInactive()), + : network_safety_(PendingTaskSafetyFlag::CreateDetachedInactive()), network_thread_(network_thread), enable_dscp_(enable_dscp) {} @@ -192,8 +192,7 @@ MediaChannelUtil::TransportForMediaChannels::TranslatePacketOptions( bool MediaChannelUtil::TransportForMediaChannels::SendRtcp( ArrayView packet, const PacketOptions& options) { - auto send = [this, - packet = CopyOnWriteBuffer(packet, webrtc::kMaxRtpPacketLen), + auto send = [this, packet = CopyOnWriteBuffer(packet, kMaxRtpPacketLen), options]() mutable { DoSendPacket(&packet, true, TranslatePacketOptions(options)); }; @@ -208,9 +207,8 @@ bool MediaChannelUtil::TransportForMediaChannels::SendRtcp( bool MediaChannelUtil::TransportForMediaChannels::SendRtp( ArrayView packet, - const webrtc::PacketOptions& options) { - auto send = [this, - packet = CopyOnWriteBuffer(packet, webrtc::kMaxRtpPacketLen), + const PacketOptions& options) { + auto send = [this, packet = CopyOnWriteBuffer(packet, kMaxRtpPacketLen), options]() mutable { DoSendPacket(&packet, false, TranslatePacketOptions(options)); }; @@ -236,13 +234,12 @@ void MediaChannelUtil::TransportForMediaChannels::SetInterface( } void MediaChannelUtil::TransportForMediaChannels::UpdateDscp() { - webrtc::DiffServCodePoint value = - enable_dscp_ ? preferred_dscp_ : webrtc::DSCP_DEFAULT; + DiffServCodePoint value = enable_dscp_ ? preferred_dscp_ : DSCP_DEFAULT; int ret = SetOptionLocked(MediaChannelNetworkInterface::ST_RTP, - webrtc::Socket::OPT_DSCP, value); + Socket::OPT_DSCP, value); if (ret == 0) - SetOptionLocked(MediaChannelNetworkInterface::ST_RTCP, - webrtc::Socket::OPT_DSCP, value); + SetOptionLocked(MediaChannelNetworkInterface::ST_RTCP, Socket::OPT_DSCP, + value); } bool MediaChannelUtil::TransportForMediaChannels::DoSendPacket( @@ -259,7 +256,7 @@ bool MediaChannelUtil::TransportForMediaChannels::DoSendPacket( int MediaChannelUtil::TransportForMediaChannels::SetOption( MediaChannelNetworkInterface::SocketType type, - webrtc::Socket::Option opt, + Socket::Option opt, int option) { RTC_DCHECK_RUN_ON(network_thread_); return SetOptionLocked(type, opt, option); @@ -267,7 +264,7 @@ int MediaChannelUtil::TransportForMediaChannels::SetOption( int MediaChannelUtil::TransportForMediaChannels::SetOptionLocked( MediaChannelNetworkInterface::SocketType type, - webrtc::Socket::Option opt, + Socket::Option opt, int option) { if (!network_interface_) return -1; @@ -275,7 +272,7 @@ int MediaChannelUtil::TransportForMediaChannels::SetOptionLocked( } void MediaChannelUtil::TransportForMediaChannels::SetPreferredDscp( - webrtc::DiffServCodePoint new_dscp) { + DiffServCodePoint new_dscp) { if (!network_thread_->IsCurrent()) { // This is currently the common path as the derived channel classes // get called on the worker thread. There are still some tests though diff --git a/media/base/media_channel_impl.h b/media/base/media_channel_impl.h index 8c222b23b7..d68ba18e2a 100644 --- a/media/base/media_channel_impl.h +++ b/media/base/media_channel_impl.h @@ -80,7 +80,7 @@ class MediaChannelUtil { void SetPreferredDscp(DiffServCodePoint new_dscp); private: - // Implementation of the webrtc::Transport interface required + // Implementation of the Transport interface required // by Call(). class TransportForMediaChannels : public Transport { public: @@ -88,13 +88,13 @@ class MediaChannelUtil { virtual ~TransportForMediaChannels(); - // Implementation of webrtc::Transport + // Implementation of Transport bool SendRtp(ArrayView packet, const PacketOptions& options) override; bool SendRtcp(ArrayView packet, const PacketOptions& options) override; - // Not implementation of webrtc::Transport + // Not implementation of Transport void SetInterface(MediaChannelNetworkInterface* iface); int SetOption(MediaChannelNetworkInterface::SocketType type, @@ -139,7 +139,7 @@ class MediaChannelUtil { MediaChannelNetworkInterface* network_interface_ RTC_GUARDED_BY(network_thread_) = nullptr; DiffServCodePoint preferred_dscp_ RTC_GUARDED_BY(network_thread_) = - webrtc::DSCP_DEFAULT; + DSCP_DEFAULT; }; bool extmap_allow_mixed_ = false; diff --git a/media/base/media_config.h b/media/base/media_config.h index 8d0a597d20..bb727b8e74 100644 --- a/media/base/media_config.h +++ b/media/base/media_config.h @@ -25,9 +25,9 @@ struct MediaConfig { // If true, RTCStats timestamps are sourced from the monotonically increasing // environment Clock, where the epoch is unspecified (i.e. up to the Clock // implementation). If false, RTCStats timestamps are either sourced from - // system clock via webrtc::TimeUTCMicros() which is relative to 1970 but not + // system clock via TimeUTCMicros() which is relative to 1970 but not // necessarily monotonically increasing, or from a monotonic clock that is - // set to webrtc::TimeUTCMicros() at first call, and then procceeds to + // set to TimeUTCMicros() at first call, and then procceeds to // increase monotonically. // TODO: bugs.webrtc.org/370535296 - Change default value to true and delete // this flag once downstream projects have migrated. diff --git a/media/base/media_engine.cc b/media/base/media_engine.cc index e9d9c6c72a..b81a8f4dd4 100644 --- a/media/base/media_engine.cc +++ b/media/base/media_engine.cc @@ -23,6 +23,7 @@ #include "api/array_view.h" #include "api/field_trials_view.h" #include "api/rtc_error.h" +#include "api/rtp_headers.h" #include "api/rtp_parameters.h" #include "api/rtp_transceiver_direction.h" #include "api/video/video_codec_constants.h" @@ -217,11 +218,25 @@ RTCError CheckRtpParametersValues(const RtpParameters& rtp_parameters, "different encodings."); } } + + if (rtp_parameters.encodings[i].csrcs.has_value() && + rtp_parameters.encodings[i].csrcs.value().size() > kRtpCsrcSize) { + LOG_AND_RETURN_ERROR( + RTCErrorType::INVALID_RANGE, + "Attempted to set more than the maximum allowed number of CSRCs.") + } + + if (i > 0 && rtp_parameters.encodings[i - 1].csrcs != + rtp_parameters.encodings[i].csrcs) { + LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION, + "Attempted to set different CSRCs for different " + "encodings."); + } } if (has_scale_resolution_down_to && absl::c_any_of(rtp_parameters.encodings, - [](const webrtc::RtpEncodingParameters& encoding) { + [](const RtpEncodingParameters& encoding) { return encoding.active && !encoding.scale_resolution_down_to.has_value(); })) { @@ -264,16 +279,16 @@ RTCError CheckRtpParametersInvalidModificationAndValues( "Attempted to set RtpParameters with modified header extensions"); } if (!absl::c_equal(old_rtp_parameters.encodings, rtp_parameters.encodings, - [](const webrtc::RtpEncodingParameters& encoding1, - const webrtc::RtpEncodingParameters& encoding2) { + [](const RtpEncodingParameters& encoding1, + const RtpEncodingParameters& encoding2) { return encoding1.rid == encoding2.rid; })) { LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION, "Attempted to change RID values in the encodings."); } if (!absl::c_equal(old_rtp_parameters.encodings, rtp_parameters.encodings, - [](const webrtc::RtpEncodingParameters& encoding1, - const webrtc::RtpEncodingParameters& encoding2) { + [](const RtpEncodingParameters& encoding1, + const RtpEncodingParameters& encoding2) { return encoding1.ssrc == encoding2.ssrc; })) { LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION, diff --git a/media/base/rtp_utils.cc b/media/base/rtp_utils.cc index 7b4fe196dd..76feba308e 100644 --- a/media/base/rtp_utils.cc +++ b/media/base/rtp_utils.cc @@ -39,8 +39,8 @@ namespace { // Fake auth tag written by the sender when external authentication is enabled. // HMAC in packet will be compared against this value before updating packet // with actual HMAC value. -static const uint8_t kFakeAuthTag[10] = {0xba, 0xdd, 0xba, 0xdd, 0xba, - 0xdd, 0xba, 0xdd, 0xba, 0xdd}; +const uint8_t kFakeAuthTag[10] = {0xba, 0xdd, 0xba, 0xdd, 0xba, + 0xdd, 0xba, 0xdd, 0xba, 0xdd}; void UpdateAbsSendTimeExtensionValue(uint8_t* extension_data, size_t length, diff --git a/media/base/test_utils.h b/media/base/test_utils.h index 403b4922b0..76e4ea55a3 100644 --- a/media/base/test_utils.h +++ b/media/base/test_utils.h @@ -33,6 +33,7 @@ template inline std::vector MakeVector(const T a[], size_t s) { return std::vector(a, a + s); } +// Note that MAKE_VECTOR can be used outside of the webrtc namespace. #define MAKE_VECTOR(a) webrtc::MakeVector(a, std::size(a)) // Create Simulcast StreamParams with given `ssrcs` and `cname`. diff --git a/media/base/video_adapter.cc b/media/base/video_adapter.cc index 2b5dcf6513..a33fe6fc64 100644 --- a/media/base/video_adapter.cc +++ b/media/base/video_adapter.cc @@ -374,8 +374,8 @@ void VideoAdapter::OnSinkWants(const VideoSinkWants& sink_wants) { max_framerate_request_ = sink_wants.max_framerate_fps; resolution_alignment_ = std::lcm(source_resolution_alignment_, sink_wants.resolution_alignment); - // Convert from std::optional to - // std::optional. Both are {int,int}. + // Convert from std::optional to + // std::optional. Both are {int,int}. scale_resolution_down_to_ = std::nullopt; if (sink_wants.requested_resolution.has_value()) { scale_resolution_down_to_ = { diff --git a/media/base/video_adapter_unittest.cc b/media/base/video_adapter_unittest.cc index 8b4a158095..bed63f5407 100644 --- a/media/base/video_adapter_unittest.cc +++ b/media/base/video_adapter_unittest.cc @@ -18,13 +18,14 @@ #include #include +#include "api/field_trials.h" #include "api/video/resolution.h" #include "api/video/video_frame.h" #include "api/video/video_source_interface.h" #include "media/base/fake_frame_source.h" #include "media/base/video_common.h" #include "rtc_base/time_utils.h" -#include "test/field_trial.h" +#include "test/create_test_field_trials.h" #include "test/gmock.h" #include "test/gtest.h" @@ -34,7 +35,6 @@ constexpr int kWidth = 1280; constexpr int kHeight = 720; constexpr int kDefaultFps = 30; -using test::ScopedFieldTrials; using ::testing::_; using ::testing::Eq; using ::testing::Pair; @@ -79,7 +79,7 @@ class VideoAdapterTest : public ::testing::Test, VideoAdapterTest() : VideoAdapterTest("", 1) {} explicit VideoAdapterTest(const std::string& field_trials, int source_resolution_alignment) - : override_field_trials_(field_trials), + : field_trials_(CreateTestFieldTrials(field_trials)), frame_source_(std::make_unique( kWidth, kHeight, @@ -176,7 +176,7 @@ class VideoAdapterTest : public ::testing::Test, return std::make_pair(out, cropped); } - ScopedFieldTrials override_field_trials_; + FieldTrials field_trials_; const std::unique_ptr frame_source_; VideoAdapter adapter_; int64_t timestamp_ns_ = 0; diff --git a/media/base/video_broadcaster.h b/media/base/video_broadcaster.h index 9d6f7a7ecc..c8fc17db5b 100644 --- a/media/base/video_broadcaster.h +++ b/media/base/video_broadcaster.h @@ -26,8 +26,8 @@ namespace webrtc { // VideoBroadcaster broadcast video frames to sinks and combines VideoSinkWants -// from its sinks. It does that by implementing webrtc::VideoSourceInterface and -// webrtc::VideoSinkInterface. The class is threadsafe; methods may be called on +// from its sinks. It does that by implementing VideoSourceInterface and +// VideoSinkInterface. The class is threadsafe; methods may be called on // any thread. This is needed because VideoStreamEncoder calls AddOrUpdateSink // both on the worker thread and on the encoder task queue. class VideoBroadcaster : public VideoSourceBase, diff --git a/media/base/video_common.h b/media/base/video_common.h index 38219a8d60..25c782f644 100644 --- a/media/base/video_common.h +++ b/media/base/video_common.h @@ -142,7 +142,7 @@ struct VideoFormatPod { struct RTC_EXPORT VideoFormat : VideoFormatPod { static const int64_t kMinimumInterval = - webrtc::kNumNanosecsPerSec / 10000; // 10k fps. + kNumNanosecsPerSec / 10000; // 10k fps. VideoFormat() { Construct(0, 0, 0, 0); } @@ -162,21 +162,21 @@ struct RTC_EXPORT VideoFormat : VideoFormatPod { } static int64_t FpsToInterval(int fps) { - return fps ? webrtc::kNumNanosecsPerSec / fps : kMinimumInterval; + return fps ? kNumNanosecsPerSec / fps : kMinimumInterval; } static int IntervalToFps(int64_t interval) { if (!interval) { return 0; } - return static_cast(webrtc::kNumNanosecsPerSec / interval); + return static_cast(kNumNanosecsPerSec / interval); } static float IntervalToFpsFloat(int64_t interval) { if (!interval) { return 0.f; } - return static_cast(webrtc::kNumNanosecsPerSec) / + return static_cast(kNumNanosecsPerSec) / static_cast(interval); } diff --git a/media/engine/fake_video_codec_factory.cc b/media/engine/fake_video_codec_factory.cc index d7b9b2e24f..1c62353544 100644 --- a/media/engine/fake_video_codec_factory.cc +++ b/media/engine/fake_video_codec_factory.cc @@ -24,7 +24,7 @@ namespace { -static const char kFakeCodecFactoryCodecName[] = "FakeCodec"; +const char kFakeCodecFactoryCodecName[] = "FakeCodec"; } // anonymous namespace diff --git a/media/engine/fake_webrtc_call.cc b/media/engine/fake_webrtc_call.cc index 523ce610c4..64a7dc61f6 100644 --- a/media/engine/fake_webrtc_call.cc +++ b/media/engine/fake_webrtc_call.cc @@ -20,6 +20,7 @@ #include "absl/algorithm/container.h" #include "absl/strings/string_view.h" #include "api/adaptation/resource.h" +#include "api/array_view.h" #include "api/audio_codecs/audio_format.h" #include "api/call/audio_sink.h" #include "api/crypto/frame_decryptor_interface.h" @@ -46,7 +47,6 @@ #include "call/video_send_stream.h" #include "media/base/media_channel.h" #include "modules/rtp_rtcp/source/rtp_packet_received.h" -#include "modules/rtp_rtcp/source/rtp_util.h" #include "rtc_base/buffer.h" #include "rtc_base/checks.h" #include "rtc_base/copy_on_write_buffer.h" @@ -294,6 +294,8 @@ VideoSendStream::Stats FakeVideoSendStream::GetStats() { return stats_; } +void FakeVideoSendStream::SetCsrcs(ArrayView csrcs) {} + void FakeVideoSendStream::ReconfigureVideoEncoder(VideoEncoderConfig config) { ReconfigureVideoEncoder(std::move(config), nullptr); } diff --git a/media/engine/fake_webrtc_call.h b/media/engine/fake_webrtc_call.h index aec1fc1626..4324a90d1e 100644 --- a/media/engine/fake_webrtc_call.h +++ b/media/engine/fake_webrtc_call.h @@ -31,11 +31,13 @@ #include "absl/strings/string_view.h" #include "api/adaptation/resource.h" +#include "api/array_view.h" #include "api/audio/audio_frame.h" #include "api/audio/audio_mixer.h" #include "api/audio_codecs/audio_format.h" #include "api/crypto/frame_decryptor_interface.h" #include "api/environment/environment.h" +#include "api/field_trials_view.h" #include "api/frame_transformer_interface.h" #include "api/media_types.h" #include "api/rtp_headers.h" @@ -90,7 +92,7 @@ class FakeAudioSendStream final : public AudioSendStream { bool muted() const { return muted_; } private: - // webrtc::AudioSendStream implementation. + // AudioSendStream implementation. void Reconfigure(const AudioSendStream::Config& config, SetParametersCallback callback) override; void Start() override { sending_ = true; } @@ -205,6 +207,7 @@ class FakeVideoSendStream final : public VideoSendStream, int GetLastHeight() const; int64_t GetLastTimestamp() const; void SetStats(const VideoSendStream::Stats& stats); + void SetCsrcs(ArrayView csrcs) override; int num_encoder_reconfigurations() const { return num_encoder_reconfigurations_; } @@ -222,10 +225,10 @@ class FakeVideoSendStream final : public VideoSendStream, } private: - // webrtc::VideoSinkInterface implementation. + // VideoSinkInterface implementation. void OnFrame(const VideoFrame& frame) override; - // webrtc::VideoSendStream implementation. + // VideoSendStream implementation. void Start() override; void Stop() override; bool started() override { return IsSending(); } diff --git a/media/engine/fake_webrtc_video_engine.cc b/media/engine/fake_webrtc_video_engine.cc index b016da355d..93d7e99561 100644 --- a/media/engine/fake_webrtc_video_engine.cc +++ b/media/engine/fake_webrtc_video_engine.cc @@ -42,8 +42,7 @@ namespace webrtc { namespace { - -static constexpr TimeDelta kEventTimeout = TimeDelta::Seconds(10); +constexpr TimeDelta kEventTimeout = TimeDelta::Seconds(10); bool IsScalabilityModeSupported(const std::vector& formats, std::optional scalability_mode) { diff --git a/media/engine/fake_webrtc_video_engine.h b/media/engine/fake_webrtc_video_engine.h index fcc75b55c0..1889214432 100644 --- a/media/engine/fake_webrtc_video_engine.h +++ b/media/engine/fake_webrtc_video_engine.h @@ -40,7 +40,7 @@ namespace webrtc { class FakeWebRtcVideoDecoderFactory; class FakeWebRtcVideoEncoderFactory; -// Fake class for mocking out webrtc::VideoDecoder +// Fake class for mocking out VideoDecoder class FakeWebRtcVideoDecoder : public VideoDecoder { public: explicit FakeWebRtcVideoDecoder(FakeWebRtcVideoDecoderFactory* factory); @@ -58,7 +58,7 @@ class FakeWebRtcVideoDecoder : public VideoDecoder { FakeWebRtcVideoDecoderFactory* factory_; }; -// Fake class for mocking out webrtc::VideoDecoderFactory. +// Fake class for mocking out VideoDecoderFactory. class FakeWebRtcVideoDecoderFactory : public VideoDecoderFactory { public: FakeWebRtcVideoDecoderFactory(); @@ -79,7 +79,7 @@ class FakeWebRtcVideoDecoderFactory : public VideoDecoderFactory { int num_created_decoders_; }; -// Fake class for mocking out webrtc::VideoEnoder +// Fake class for mocking out VideoEnoder class FakeWebRtcVideoEncoder : public VideoEncoder { public: explicit FakeWebRtcVideoEncoder(FakeWebRtcVideoEncoderFactory* factory); @@ -109,7 +109,7 @@ class FakeWebRtcVideoEncoder : public VideoEncoder { FakeWebRtcVideoEncoderFactory* factory_; }; -// Fake class for mocking out webrtc::VideoEncoderFactory. +// Fake class for mocking out VideoEncoderFactory. class FakeWebRtcVideoEncoderFactory : public VideoEncoderFactory { public: FakeWebRtcVideoEncoderFactory(); diff --git a/media/engine/internal_decoder_factory_unittest.cc b/media/engine/internal_decoder_factory_unittest.cc index d5a30c1acc..16c105d86e 100644 --- a/media/engine/internal_decoder_factory_unittest.cc +++ b/media/engine/internal_decoder_factory_unittest.cc @@ -112,7 +112,7 @@ TEST(InternalDecoderFactoryTest, H265IsNotEnabled) { TEST(InternalDecoderFactoryTest, Av1) { InternalDecoderFactory factory; EXPECT_THAT(factory.GetSupportedFormats(), - Contains(Field(&SdpVideoFormat::name, webrtc::kAv1CodecName))); + Contains(Field(&SdpVideoFormat::name, kAv1CodecName))); } #endif diff --git a/media/engine/internal_encoder_factory.cc b/media/engine/internal_encoder_factory.cc index 9c02ac13bf..43992b3a93 100644 --- a/media/engine/internal_encoder_factory.cc +++ b/media/engine/internal_encoder_factory.cc @@ -32,15 +32,14 @@ namespace webrtc { namespace { -using Factory = - VideoEncoderFactoryTemplate; + LibvpxVp9EncoderTemplateAdapter>; } // namespace std::vector InternalEncoderFactory::GetSupportedFormats() diff --git a/media/engine/internal_encoder_factory_unittest.cc b/media/engine/internal_encoder_factory_unittest.cc index 9a079d6bc2..28e189e81e 100644 --- a/media/engine/internal_encoder_factory_unittest.cc +++ b/media/engine/internal_encoder_factory_unittest.cc @@ -113,7 +113,7 @@ TEST(InternalEncoderFactoryTest, QueryCodecSupportWithScalabilityMode) { TEST(InternalEncoderFactoryTest, Av1) { InternalEncoderFactory factory; EXPECT_THAT(factory.GetSupportedFormats(), - Contains(Field(&SdpVideoFormat::name, webrtc::kAv1CodecName))); + Contains(Field(&SdpVideoFormat::name, kAv1CodecName))); EXPECT_TRUE( factory.Create(CreateEnvironment(), SdpVideoFormat::AV1Profile0())); } diff --git a/media/engine/simulcast_encoder_adapter.h b/media/engine/simulcast_encoder_adapter.h index 7673683127..4bc9f4f694 100644 --- a/media/engine/simulcast_encoder_adapter.h +++ b/media/engine/simulcast_encoder_adapter.h @@ -41,7 +41,7 @@ namespace webrtc { // SimulcastEncoderAdapter implements simulcast support by creating multiple -// webrtc::VideoEncoder instances with the given VideoEncoderFactory. +// VideoEncoder instances with the given VideoEncoderFactory. // The object is created and destroyed on the worker thread, but all public // interfaces should be called from the encoder task queue. class RTC_EXPORT SimulcastEncoderAdapter : public VideoEncoder { @@ -158,11 +158,11 @@ class RTC_EXPORT SimulcastEncoderAdapter : public VideoEncoder { std::unique_ptr FetchOrCreateEncoderContext( bool is_lowest_quality_stream) const; - webrtc::VideoCodec MakeStreamCodec(const webrtc::VideoCodec& codec, - int stream_idx, - uint32_t start_bitrate_kbps, - bool is_lowest_quality_stream, - bool is_highest_quality_stream); + VideoCodec MakeStreamCodec(const VideoCodec& codec, + int stream_idx, + uint32_t start_bitrate_kbps, + bool is_lowest_quality_stream, + bool is_highest_quality_stream); EncodedImageCallback::Result OnEncodedImage( size_t stream_idx, diff --git a/media/engine/simulcast_encoder_adapter_unittest.cc b/media/engine/simulcast_encoder_adapter_unittest.cc index 86475311ff..4de878f36c 100644 --- a/media/engine/simulcast_encoder_adapter_unittest.cc +++ b/media/engine/simulcast_encoder_adapter_unittest.cc @@ -23,6 +23,7 @@ #include "api/environment/environment.h" #include "api/environment/environment_factory.h" #include "api/fec_controller_override.h" +#include "api/field_trials.h" #include "api/make_ref_counted.h" #include "api/rtp_parameters.h" #include "api/scoped_refptr.h" @@ -55,9 +56,9 @@ #include "modules/video_coding/utility/simulcast_rate_allocator.h" #include "modules/video_coding/utility/simulcast_test_fixture_impl.h" #include "rtc_base/checks.h" +#include "test/create_test_field_trials.h" #include "test/gmock.h" #include "test/gtest.h" -#include "test/scoped_key_value_config.h" using ::testing::_; using ::testing::Return; @@ -268,7 +269,7 @@ class MockVideoEncoder : public VideoEncoder { MOCK_METHOD(int32_t, Release, (), (override)); - void SetRates(const RateControlParameters& parameters) { + void SetRates(const RateControlParameters& parameters) override { last_set_rates_ = parameters; } @@ -289,7 +290,7 @@ class MockVideoEncoder : public VideoEncoder { return info; } - virtual ~MockVideoEncoder() { factory_->DestroyVideoEncoder(this); } + ~MockVideoEncoder() override { factory_->DestroyVideoEncoder(this); } const VideoCodec& codec() const { return codec_; } @@ -477,7 +478,7 @@ class TestSimulcastEncoderAdapterFake : public ::testing::Test, public: TestSimulcastEncoderAdapterFake() : use_fallback_factory_(false) {} - virtual ~TestSimulcastEncoderAdapterFake() { + ~TestSimulcastEncoderAdapterFake() override { if (adapter_) { adapter_->Release(); } @@ -640,7 +641,7 @@ class TestSimulcastEncoderAdapterFake : public ::testing::Test, } protected: - test::ScopedKeyValueConfig field_trials_; + FieldTrials field_trials_ = CreateTestFieldTrials(); const Environment env_ = CreateEnvironment(&field_trials_); std::unique_ptr helper_; std::unique_ptr adapter_; @@ -1561,13 +1562,11 @@ TEST_F(TestSimulcastEncoderAdapterFake, TEST_F( TestSimulcastEncoderAdapterFake, EncoderInfoFromFieldTrialDoesNotOverrideExistingBitrateLimitsInSinglecast) { - test::ScopedKeyValueConfig field_trials( - field_trials_, - "WebRTC-SimulcastEncoderAdapter-GetEncoderInfoOverride/" - "frame_size_pixels:123|456|789," - "min_start_bitrate_bps:11000|22000|33000," - "min_bitrate_bps:44000|55000|66000," - "max_bitrate_bps:77000|88000|99000/"); + field_trials_.Set("WebRTC-SimulcastEncoderAdapter-GetEncoderInfoOverride", + "frame_size_pixels:123|456|789," + "min_start_bitrate_bps:11000|22000|33000," + "min_bitrate_bps:44000|55000|66000," + "max_bitrate_bps:77000|88000|99000"); SetUp(); std::vector bitrate_limits; @@ -1591,11 +1590,9 @@ TEST_F( } TEST_F(TestSimulcastEncoderAdapterFake, EncoderInfoFromFieldTrial) { - test::ScopedKeyValueConfig field_trials( - field_trials_, - "WebRTC-SimulcastEncoderAdapter-GetEncoderInfoOverride/" - "requested_resolution_alignment:8," - "apply_alignment_to_all_simulcast_layers/"); + field_trials_.Set("WebRTC-SimulcastEncoderAdapter-GetEncoderInfoOverride", + "requested_resolution_alignment:8," + "apply_alignment_to_all_simulcast_layers"); SetUp(); SimulcastTestFixtureImpl::DefaultSettings( &codec_, static_cast(kTestTemporalLayerProfile), @@ -1612,14 +1609,12 @@ TEST_F(TestSimulcastEncoderAdapterFake, EncoderInfoFromFieldTrial) { TEST_F(TestSimulcastEncoderAdapterFake, EncoderInfoFromFieldTrialForSingleStream) { - test::ScopedKeyValueConfig field_trials( - field_trials_, - "WebRTC-SimulcastEncoderAdapter-GetEncoderInfoOverride/" - "requested_resolution_alignment:9," - "frame_size_pixels:123|456|789," - "min_start_bitrate_bps:11000|22000|33000," - "min_bitrate_bps:44000|55000|66000," - "max_bitrate_bps:77000|88000|99000/"); + field_trials_.Set("WebRTC-SimulcastEncoderAdapter-GetEncoderInfoOverride", + "requested_resolution_alignment:9," + "frame_size_pixels:123|456|789," + "min_start_bitrate_bps:11000|22000|33000," + "min_bitrate_bps:44000|55000|66000," + "max_bitrate_bps:77000|88000|99000"); SetUp(); SimulcastTestFixtureImpl::DefaultSettings( &codec_, static_cast(kTestTemporalLayerProfile), @@ -2035,8 +2030,7 @@ TEST_F(TestSimulcastEncoderAdapterFake, // Normally SEA reuses encoders. But, when TL-based SW fallback is enabled, // the encoder which served the lowest stream should be recreated before it // can be used to process an upper layer and vice-versa. - test::ScopedKeyValueConfig field_trials( - field_trials_, "WebRTC-Video-PreferTemporalSupportOnBaseLayer/Enabled/"); + field_trials_.Set("WebRTC-Video-PreferTemporalSupportOnBaseLayer", "Enabled"); use_fallback_factory_ = true; ReSetUp(); @@ -2126,11 +2120,9 @@ TEST_F(TestSimulcastEncoderAdapterFake, PopulatesScalabilityModeOfSubcodecs) { TEST_F(TestSimulcastEncoderAdapterFake, EncodeDropsFrameIfResolutionIsNotAlignedByDefault) { - test::ScopedKeyValueConfig field_trials( - field_trials_, - "WebRTC-SimulcastEncoderAdapter-GetEncoderInfoOverride/" - "requested_resolution_alignment:8," - "apply_alignment_to_all_simulcast_layers/"); + field_trials_.Set("WebRTC-SimulcastEncoderAdapter-GetEncoderInfoOverride", + "requested_resolution_alignment:8," + "apply_alignment_to_all_simulcast_layers"); SetUp(); SimulcastTestFixtureImpl::DefaultSettings( &codec_, static_cast(kTestTemporalLayerProfile), @@ -2152,12 +2144,11 @@ TEST_F(TestSimulcastEncoderAdapterFake, TEST_F(TestSimulcastEncoderAdapterFake, EncodeReturnsErrorIfResolutionIsNotAlignedAndDroppingIsDisabled) { - test::ScopedKeyValueConfig field_trials( - field_trials_, - "WebRTC-SimulcastEncoderAdapter-DropUnalignedResolution/Disabled/" - "WebRTC-SimulcastEncoderAdapter-GetEncoderInfoOverride/" - "requested_resolution_alignment:8," - "apply_alignment_to_all_simulcast_layers/"); + field_trials_.Set("WebRTC-SimulcastEncoderAdapter-DropUnalignedResolution", + "Disabled"); + field_trials_.Set("WebRTC-SimulcastEncoderAdapter-GetEncoderInfoOverride", + "requested_resolution_alignment:8," + "apply_alignment_to_all_simulcast_layers"); SetUp(); SimulcastTestFixtureImpl::DefaultSettings( &codec_, static_cast(kTestTemporalLayerProfile), diff --git a/media/engine/webrtc_media_engine.cc b/media/engine/webrtc_media_engine.cc index 7565d9a540..f375952eec 100644 --- a/media/engine/webrtc_media_engine.cc +++ b/media/engine/webrtc_media_engine.cc @@ -129,19 +129,18 @@ std::vector FilterRtpExtensions( // Sort by name, ascending (prioritise encryption), so that we don't reset // extensions if they were specified in a different order (also allows us // to use std::unique below). - absl::c_sort(result, [](const webrtc::RtpExtension& rhs, - const webrtc::RtpExtension& lhs) { + absl::c_sort(result, [](const RtpExtension& rhs, const RtpExtension& lhs) { return rhs.encrypt == lhs.encrypt ? rhs.uri < lhs.uri : rhs.encrypt > lhs.encrypt; }); // Remove unnecessary extensions (used on send side). if (filter_redundant_extensions) { - auto it = std::unique( - result.begin(), result.end(), - [](const webrtc::RtpExtension& rhs, const webrtc::RtpExtension& lhs) { - return rhs.uri == lhs.uri && rhs.encrypt == lhs.encrypt; - }); + auto it = + std::unique(result.begin(), result.end(), + [](const RtpExtension& rhs, const RtpExtension& lhs) { + return rhs.uri == lhs.uri && rhs.encrypt == lhs.encrypt; + }); result.erase(it, result.end()); // Keep just the highest priority extension of any in the following lists. diff --git a/media/engine/webrtc_media_engine_unittest.cc b/media/engine/webrtc_media_engine_unittest.cc index ec41af8c29..69f5f1b015 100644 --- a/media/engine/webrtc_media_engine_unittest.cc +++ b/media/engine/webrtc_media_engine_unittest.cc @@ -15,15 +15,14 @@ #include #include "absl/strings/string_view.h" +#include "api/field_trials.h" #include "api/rtp_parameters.h" +#include "test/create_test_field_trials.h" #include "test/gtest.h" -#include "test/scoped_key_value_config.h" namespace webrtc { namespace { -using test::ScopedKeyValueConfig; - std::vector MakeUniqueExtensions() { std::vector result; char name[] = "a"; @@ -130,7 +129,7 @@ TEST(WebRtcMediaEngineTest, ValidateRtpExtensionsChangeIdForUrl) { TEST(WebRtcMediaEngineTest, FilterRtpExtensionsEmptyList) { std::vector extensions; - ScopedKeyValueConfig trials; + FieldTrials trials = CreateTestFieldTrials(); std::vector filtered = FilterRtpExtensions(extensions, SupportedExtensions1, true, trials); EXPECT_EQ(0u, filtered.size()); @@ -138,7 +137,7 @@ TEST(WebRtcMediaEngineTest, FilterRtpExtensionsEmptyList) { TEST(WebRtcMediaEngineTest, FilterRtpExtensionsIncludeOnlySupported) { std::vector extensions = MakeUniqueExtensions(); - ScopedKeyValueConfig trials; + FieldTrials trials = CreateTestFieldTrials(); std::vector filtered = FilterRtpExtensions(extensions, SupportedExtensions1, false, trials); EXPECT_EQ(2u, filtered.size()); @@ -148,7 +147,7 @@ TEST(WebRtcMediaEngineTest, FilterRtpExtensionsIncludeOnlySupported) { TEST(WebRtcMediaEngineTest, FilterRtpExtensionsSortedByName1) { std::vector extensions = MakeUniqueExtensions(); - ScopedKeyValueConfig trials; + FieldTrials trials = CreateTestFieldTrials(); std::vector filtered = FilterRtpExtensions(extensions, SupportedExtensions2, false, trials); EXPECT_EQ(12u, filtered.size()); @@ -157,7 +156,7 @@ TEST(WebRtcMediaEngineTest, FilterRtpExtensionsSortedByName1) { TEST(WebRtcMediaEngineTest, FilterRtpExtensionsSortedByName2) { std::vector extensions = MakeUniqueExtensions(); - ScopedKeyValueConfig trials; + FieldTrials trials = CreateTestFieldTrials(); std::vector filtered = FilterRtpExtensions(extensions, SupportedExtensions2, true, trials); EXPECT_EQ(12u, filtered.size()); @@ -166,7 +165,7 @@ TEST(WebRtcMediaEngineTest, FilterRtpExtensionsSortedByName2) { TEST(WebRtcMediaEngineTest, FilterRtpExtensionsDontRemoveRedundant) { std::vector extensions = MakeRedundantExtensions(); - ScopedKeyValueConfig trials; + FieldTrials trials = CreateTestFieldTrials(); std::vector filtered = FilterRtpExtensions(extensions, SupportedExtensions2, false, trials); EXPECT_EQ(12u, filtered.size()); @@ -176,7 +175,7 @@ TEST(WebRtcMediaEngineTest, FilterRtpExtensionsDontRemoveRedundant) { TEST(WebRtcMediaEngineTest, FilterRtpExtensionsRemoveRedundant) { std::vector extensions = MakeRedundantExtensions(); - ScopedKeyValueConfig trials; + FieldTrials trials = CreateTestFieldTrials(); std::vector filtered = FilterRtpExtensions(extensions, SupportedExtensions2, true, trials); EXPECT_EQ(6u, filtered.size()); @@ -190,7 +189,7 @@ TEST(WebRtcMediaEngineTest, FilterRtpExtensionsRemoveRedundantEncrypted1) { extensions.push_back(RtpExtension("b", 2, true)); extensions.push_back(RtpExtension("c", 3)); extensions.push_back(RtpExtension("b", 4)); - ScopedKeyValueConfig trials; + FieldTrials trials = CreateTestFieldTrials(); std::vector filtered = FilterRtpExtensions(extensions, SupportedExtensions2, true, trials); EXPECT_EQ(3u, filtered.size()); @@ -207,7 +206,7 @@ TEST(WebRtcMediaEngineTest, FilterRtpExtensionsRemoveRedundantEncrypted2) { extensions.push_back(RtpExtension("b", 2)); extensions.push_back(RtpExtension("c", 3)); extensions.push_back(RtpExtension("b", 4)); - ScopedKeyValueConfig trials; + FieldTrials trials = CreateTestFieldTrials(); std::vector filtered = FilterRtpExtensions(extensions, SupportedExtensions2, true, trials); EXPECT_EQ(3u, filtered.size()); @@ -219,7 +218,8 @@ TEST(WebRtcMediaEngineTest, FilterRtpExtensionsRemoveRedundantEncrypted2) { } TEST(WebRtcMediaEngineTest, FilterRtpExtensionsRemoveRedundantBwe1) { - ScopedKeyValueConfig trials("WebRTC-FilterAbsSendTimeExtension/Enabled/"); + FieldTrials trials = + CreateTestFieldTrials("WebRTC-FilterAbsSendTimeExtension/Enabled/"); std::vector extensions; extensions.push_back( RtpExtension(RtpExtension::kTransportSequenceNumberUri, 3)); @@ -244,7 +244,7 @@ TEST(WebRtcMediaEngineTest, extensions.push_back( RtpExtension(RtpExtension::kTransportSequenceNumberUri, 1)); extensions.push_back(RtpExtension(RtpExtension::kTimestampOffsetUri, 14)); - ScopedKeyValueConfig trials; + FieldTrials trials = CreateTestFieldTrials(); std::vector filtered = FilterRtpExtensions(extensions, SupportedExtensions2, true, trials); EXPECT_EQ(2u, filtered.size()); @@ -253,7 +253,8 @@ TEST(WebRtcMediaEngineTest, } TEST(WebRtcMediaEngineTest, FilterRtpExtensionsRemoveRedundantBweEncrypted1) { - ScopedKeyValueConfig trials("WebRTC-FilterAbsSendTimeExtension/Enabled/"); + FieldTrials trials = + CreateTestFieldTrials("WebRTC-FilterAbsSendTimeExtension/Enabled/"); std::vector extensions; extensions.push_back( RtpExtension(RtpExtension::kTransportSequenceNumberUri, 3)); @@ -288,7 +289,7 @@ TEST(WebRtcMediaEngineTest, extensions.push_back( RtpExtension(RtpExtension::kTransportSequenceNumberUri, 2, true)); extensions.push_back(RtpExtension(RtpExtension::kTimestampOffsetUri, 14)); - ScopedKeyValueConfig trials; + FieldTrials trials = CreateTestFieldTrials(); std::vector filtered = FilterRtpExtensions(extensions, SupportedExtensions2, true, trials); EXPECT_EQ(3u, filtered.size()); @@ -303,7 +304,7 @@ TEST(WebRtcMediaEngineTest, FilterRtpExtensionsRemoveRedundantBwe2) { extensions.push_back(RtpExtension(RtpExtension::kTimestampOffsetUri, 1)); extensions.push_back(RtpExtension(RtpExtension::kAbsSendTimeUri, 14)); extensions.push_back(RtpExtension(RtpExtension::kTimestampOffsetUri, 7)); - ScopedKeyValueConfig trials; + FieldTrials trials = CreateTestFieldTrials(); std::vector filtered = FilterRtpExtensions(extensions, SupportedExtensions2, true, trials); EXPECT_EQ(1u, filtered.size()); @@ -314,7 +315,7 @@ TEST(WebRtcMediaEngineTest, FilterRtpExtensionsRemoveRedundantBwe3) { std::vector extensions; extensions.push_back(RtpExtension(RtpExtension::kTimestampOffsetUri, 2)); extensions.push_back(RtpExtension(RtpExtension::kTimestampOffsetUri, 14)); - ScopedKeyValueConfig trials; + FieldTrials trials = CreateTestFieldTrials(); std::vector filtered = FilterRtpExtensions(extensions, SupportedExtensions2, true, trials); EXPECT_EQ(1u, filtered.size()); diff --git a/media/engine/webrtc_video_engine.cc b/media/engine/webrtc_video_engine.cc index 3a3d197cc6..9b71d020df 100644 --- a/media/engine/webrtc_video_engine.cc +++ b/media/engine/webrtc_video_engine.cc @@ -161,7 +161,7 @@ void AddDefaultFeedbackParams(Codec* codec, const FieldTrialsView& trials) { // Also, is_decoder_factory is used to decide whether FlexFEC video format // should be advertised as supported. template -std::vector GetDefaultSupportedFormats( +std::vector GetDefaultSupportedFormats( const T* factory, bool is_decoder_factory, const FieldTrialsView& trials) { @@ -228,7 +228,7 @@ RTCErrorOr AddRtx(const Codec& primary_codec, // TODO(kron): Perhaps it is better to move the implicit knowledge to the place // where codecs are negotiated. template -std::vector GetPayloadTypesAndDefaultCodecs( +std::vector GetPayloadTypesAndDefaultCodecs( const T* factory, bool is_decoder_factory, bool include_rtx, @@ -277,7 +277,7 @@ std::vector GetPayloadTypesAndDefaultCodecs( return output_codecs; } -static std::string CodecVectorToString(const std::vector& codecs) { +std::string CodecVectorToString(const std::vector& codecs) { StringBuilder out; out << "{"; for (size_t i = 0; i < codecs.size(); ++i) { @@ -290,7 +290,7 @@ static std::string CodecVectorToString(const std::vector& codecs) { return out.Release(); } -static bool ValidateCodecFormats(const std::vector& codecs) { +bool ValidateCodecFormats(const std::vector& codecs) { bool has_video = false; for (size_t i = 0; i < codecs.size(); ++i) { if (!codecs[i].ValidateCodecFormat()) { @@ -308,7 +308,7 @@ static bool ValidateCodecFormats(const std::vector& codecs) { return true; } -static bool ValidateStreamParams(const StreamParams& sp) { +bool ValidateStreamParams(const StreamParams& sp) { if (sp.ssrcs.empty()) { RTC_LOG(LS_ERROR) << "No SSRCs in stream parameters: " << sp.ToString(); return false; @@ -514,11 +514,9 @@ void FallbackToDefaultScalabilityModeIfNotSupported( const Codec& codec, const VideoSendStream::Config& config, std::vector& encodings) { - if (!absl::c_any_of(encodings, - [](const webrtc::RtpEncodingParameters& encoding) { - return encoding.scalability_mode && - !encoding.scalability_mode->empty(); - })) { + if (!absl::c_any_of(encodings, [](const RtpEncodingParameters& encoding) { + return encoding.scalability_mode && !encoding.scalability_mode->empty(); + })) { // Fallback is only enabled if the scalability mode is configured for any of // the encodings for now. return; @@ -2155,6 +2153,9 @@ RTCError WebRtcVideoSendChannel::WebRtcVideoSendStream::SetRtpParameters( new_send_state = true; } } + bool new_csrcs = + (new_parameters.encodings[0].csrcs.has_value() && + new_parameters.encodings[0].csrcs != rtp_parameters_.encodings[0].csrcs); rtp_parameters_ = new_parameters; // Codecs are currently handled at the WebRtcVideoSendChannel level. @@ -2169,6 +2170,9 @@ RTCError WebRtcVideoSendChannel::WebRtcVideoSendStream::SetRtpParameters( stream_->SetSource(source_, GetDegradationPreference()); } } + if (stream_ && new_csrcs) { + stream_->SetCsrcs(rtp_parameters_.encodings[0].csrcs.value()); + } // Check if a key frame was requested via setParameters. std::vector key_frames_requested_by_rid; for (const auto& encoding : rtp_parameters_.encodings) { @@ -2366,7 +2370,7 @@ void WebRtcVideoSendChannel::WebRtcVideoSendStream::ReconfigureEncoder( SetParametersCallback callback) { RTC_DCHECK_RUN_ON(&thread_checker_); if (!stream_) { - // The webrtc::VideoSendStream `stream_` has not yet been created but other + // The VideoSendStream `stream_` has not yet been created but other // parameters has changed. InvokeSetParametersCallback(callback, RTCError::OK()); return; @@ -2671,6 +2675,10 @@ void WebRtcVideoSendChannel::WebRtcVideoSendStream::RecreateWebRtcStream() { stream_ = call_->CreateVideoSendStream(std::move(config), parameters_.encoder_config.Copy()); } + if (!rtp_parameters_.encodings.empty() && + rtp_parameters_.encodings[0].csrcs.has_value()) { + stream_->SetCsrcs(rtp_parameters_.encodings[0].csrcs.value()); + } parameters_.encoder_config.encoder_specific_settings = nullptr; diff --git a/media/engine/webrtc_video_engine.h b/media/engine/webrtc_video_engine.h index e8cfa264bc..b46c391ec6 100644 --- a/media/engine/webrtc_video_engine.h +++ b/media/engine/webrtc_video_engine.h @@ -245,7 +245,7 @@ class WebRtcVideoSendChannel : public MediaChannelUtil, ADAPTREASON_BANDWIDTH = 2, }; - // Implements webrtc::EncoderSwitchRequestCallback. + // Implements EncoderSwitchRequestCallback. void RequestEncoderFallback() override; void RequestEncoderSwitch(const SdpVideoFormat& format, bool allow_default_fallback) override; @@ -268,14 +268,14 @@ class WebRtcVideoSendChannel : public MediaChannelUtil, if (!send_codec()) { return false; } - return webrtc::HasLntf(send_codec()->codec); + return HasLntf(send_codec()->codec); } bool SendCodecHasNack() const override { RTC_DCHECK_RUN_ON(&thread_checker_); if (!send_codec()) { return false; } - return webrtc::HasNack(send_codec()->codec); + return HasNack(send_codec()->codec); } std::optional SendCodecRtxTime() const override { RTC_DCHECK_RUN_ON(&thread_checker_); @@ -355,7 +355,7 @@ class WebRtcVideoSendChannel : public MediaChannelUtil, private: // Parameters needed to reconstruct the underlying stream. - // webrtc::VideoSendStream doesn't support setting a lot of options on the + // VideoSendStream doesn't support setting a lot of options on the // fly, so when those need to be changed we tear down and reconstruct with // similar parameters depending on which options changed etc. struct VideoSendStreamParameters { @@ -849,7 +849,7 @@ class WebRtcVideoReceiveChannel : public MediaChannelUtil, }; // Keeping the old name "WebRtcVideoChannel" around because some external -// customers are using webrtc::WebRtcVideoChannel::AdaptReason +// customers are using WebRtcVideoChannel::AdaptReason // TODO(bugs.webrtc.org/15216): Move this enum to an interface class and // delete this workaround. class WebRtcVideoChannel : public WebRtcVideoSendChannel { diff --git a/media/engine/webrtc_video_engine_unittest.cc b/media/engine/webrtc_video_engine_unittest.cc index 596c555f15..5f22336d45 100644 --- a/media/engine/webrtc_video_engine_unittest.cc +++ b/media/engine/webrtc_video_engine_unittest.cc @@ -32,6 +32,7 @@ #include "api/crypto/crypto_options.h" #include "api/environment/environment.h" #include "api/environment/environment_factory.h" +#include "api/field_trials.h" #include "api/make_ref_counted.h" #include "api/media_types.h" #include "api/priority.h" @@ -46,7 +47,6 @@ #include "api/test/mock_video_encoder_factory.h" #include "api/test/video/function_video_decoder_factory.h" #include "api/transport/bitrate_settings.h" -#include "api/transport/field_trial_based_config.h" #include "api/transport/rtp/rtp_source.h" #include "api/units/time_delta.h" #include "api/units/timestamp.h" @@ -115,12 +115,12 @@ #include "rtc_base/numerics/safe_conversions.h" #include "rtc_base/socket.h" #include "rtc_base/time_utils.h" +#include "test/create_test_field_trials.h" #include "test/fake_decoder.h" #include "test/frame_forwarder.h" #include "test/gmock.h" #include "test/gtest.h" #include "test/rtcp_packet_parser.h" -#include "test/scoped_key_value_config.h" #include "test/time_controller/simulated_time_controller.h" #include "video/config/encoder_stream_factory.h" #include "video/config/simulcast.h" @@ -146,33 +146,32 @@ using ::testing::SizeIs; using ::testing::StrNe; using ::testing::Values; using ::testing::WithArg; +using ::webrtc::CreateTestFieldTrials; +using ::webrtc::FieldTrials; using ::webrtc::test::FrameForwarder; using ::webrtc::test::FunctionVideoDecoderFactory; using ::webrtc::test::RtcpPacketParser; -using ::webrtc::test::ScopedKeyValueConfig; +const uint8_t kRedRtxPayloadType = 125; -static const uint8_t kRedRtxPayloadType = 125; +const uint32_t kSsrc = 1234u; +const uint32_t kSsrcs4[] = {1, 2, 3, 4}; +const int kVideoWidth = 640; +const int kVideoHeight = 360; +const int kFramerate = 30; +constexpr TimeDelta kFrameDuration = TimeDelta::Millis(1000 / kFramerate); -static const uint32_t kSsrc = 1234u; -static const uint32_t kSsrcs4[] = {1, 2, 3, 4}; -static const int kVideoWidth = 640; -static const int kVideoHeight = 360; -static const int kFramerate = 30; -static constexpr TimeDelta kFrameDuration = - TimeDelta::Millis(1000 / kFramerate); - -static const uint32_t kSsrcs1[] = {1}; -static const uint32_t kSsrcs3[] = {1, 2, 3}; -static const uint32_t kRtxSsrcs1[] = {4}; -static const uint32_t kFlexfecSsrc = 5; -static const uint32_t kIncomingUnsignalledSsrc = 0xC0FFEE; -static const int64_t kUnsignalledReceiveStreamCooldownMs = 500; +const uint32_t kSsrcs1[] = {1}; +const uint32_t kSsrcs3[] = {1, 2, 3}; +const uint32_t kRtxSsrcs1[] = {4}; +const uint32_t kFlexfecSsrc = 5; +const uint32_t kIncomingUnsignalledSsrc = 0xC0FFEE; +const int64_t kUnsignalledReceiveStreamCooldownMs = 500; constexpr uint32_t kRtpHeaderSize = 12; constexpr size_t kNumSimulcastStreams = 3; -static const char kUnsupportedExtensionName[] = +const char kUnsupportedExtensionName[] = "urn:ietf:params:rtp-hdrext:unsupported"; Codec RemoveFeedbackParams(Codec&& codec) { @@ -383,7 +382,7 @@ class WebRtcVideoEngineTest : public ::testing::Test { public: WebRtcVideoEngineTest() : WebRtcVideoEngineTest("") {} explicit WebRtcVideoEngineTest(const std::string& field_trials) - : field_trials_(field_trials), + : field_trials_(CreateTestFieldTrials(field_trials)), time_controller_(Timestamp::Millis(4711)), env_(CreateEnvironment(&field_trials_, time_controller_.CreateTaskQueueFactory(), @@ -424,7 +423,7 @@ class WebRtcVideoEngineTest : public ::testing::Test { void ExpectRtpCapabilitySupport(const char* uri, bool supported) const; - ScopedKeyValueConfig field_trials_; + FieldTrials field_trials_; GlobalSimulatedTimeController time_controller_; Environment env_; // Used in WebRtcVideoEngineVoiceTest, but defined here so it's properly @@ -1000,8 +999,7 @@ void WebRtcVideoEngineTest::ExpectRtpCapabilitySupport(const char* uri, } TEST_F(WebRtcVideoEngineTest, ReceiveBufferSizeViaFieldTrial) { - ScopedKeyValueConfig override_field_trials( - field_trials_, "WebRTC-ReceiveBufferSize/size_bytes:10000/"); + field_trials_.Set("WebRTC-ReceiveBufferSize", "size_bytes:10000"); std::unique_ptr receive_channel = engine_.CreateReceiveChannel(call_.get(), GetMediaConfig(), VideoOptions(), CryptoOptions()); @@ -1014,8 +1012,7 @@ TEST_F(WebRtcVideoEngineTest, ReceiveBufferSizeViaFieldTrial) { TEST_F(WebRtcVideoEngineTest, TooLowReceiveBufferSizeViaFieldTrial) { // 10000001 is too high, it will revert to the default // kVideoRtpRecvBufferSize. - ScopedKeyValueConfig override_field_trials( - field_trials_, "WebRTC-ReceiveBufferSize/size_bytes:10000001/"); + field_trials_.Set("WebRTC-ReceiveBufferSize", "size_bytes:10000001"); std::unique_ptr receive_channel = engine_.CreateReceiveChannel(call_.get(), GetMediaConfig(), VideoOptions(), CryptoOptions()); @@ -1027,8 +1024,7 @@ TEST_F(WebRtcVideoEngineTest, TooLowReceiveBufferSizeViaFieldTrial) { TEST_F(WebRtcVideoEngineTest, TooHighReceiveBufferSizeViaFieldTrial) { // 9999 is too low, it will revert to the default kVideoRtpRecvBufferSize. - ScopedKeyValueConfig override_field_trials( - field_trials_, "WebRTC-ReceiveBufferSize/size_bytes:9999/"); + field_trials_.Set("WebRTC-ReceiveBufferSize", "size_bytes:9999"); std::unique_ptr receive_channel = engine_.CreateReceiveChannel(call_.get(), GetMediaConfig(), VideoOptions(), CryptoOptions()); @@ -1266,8 +1262,7 @@ TEST_F(WebRtcVideoEngineTest, Flexfec03SendCodecEnablesWithFieldTrial) { EXPECT_THAT(engine_.LegacySendCodecs(), Not(Contains(flexfec))); - ScopedKeyValueConfig override_field_trials( - field_trials_, "WebRTC-FlexFEC-03-Advertised/Enabled/"); + field_trials_.Set("WebRTC-FlexFEC-03-Advertised", "Enabled"); EXPECT_THAT(engine_.LegacySendCodecs(), Contains(flexfec)); } @@ -1278,12 +1273,11 @@ TEST_F(WebRtcVideoEngineTest, Flexfec03LowerPayloadTypeRange) { auto flexfec = Field("name", &Codec::name, "flexfec-03"); // FlexFEC is active with field trial. - ScopedKeyValueConfig override_field_trials( - field_trials_, "WebRTC-FlexFEC-03-Advertised/Enabled/"); + field_trials_.Set("WebRTC-FlexFEC-03-Advertised", "Enabled"); auto send_codecs = engine_.LegacySendCodecs(); auto it = std::find_if( send_codecs.begin(), send_codecs.end(), - [](const webrtc::Codec& codec) { return codec.name == "flexfec-03"; }); + [](const Codec& codec) { return codec.name == "flexfec-03"; }); ASSERT_NE(it, send_codecs.end()); EXPECT_LE(35, it->id); EXPECT_GE(65, it->id); @@ -1394,7 +1388,7 @@ TEST_F(WebRtcVideoEngineTest, GetSourcesWithNonExistingSsrc) { TEST(WebRtcVideoEngineNewVideoCodecFactoryTest, NullFactories) { std::unique_ptr encoder_factory; std::unique_ptr decoder_factory; - FieldTrialBasedConfig trials; + FieldTrials trials = CreateTestFieldTrials(); WebRtcVideoEngine engine(std::move(encoder_factory), std::move(decoder_factory), trials); EXPECT_EQ(0u, engine.LegacySendCodecs().size()); @@ -1405,7 +1399,7 @@ TEST(WebRtcVideoEngineNewVideoCodecFactoryTest, EmptyFactories) { // `engine` take ownership of the factories. MockVideoEncoderFactory* encoder_factory = new MockVideoEncoderFactory(); MockVideoDecoderFactory* decoder_factory = new MockVideoDecoderFactory(); - FieldTrialBasedConfig trials; + FieldTrials trials = CreateTestFieldTrials(); WebRtcVideoEngine engine( (std::unique_ptr(encoder_factory)), (std::unique_ptr(decoder_factory)), trials); @@ -1431,7 +1425,7 @@ TEST(WebRtcVideoEngineNewVideoCodecFactoryTest, Vp8) { EXPECT_CALL(*rate_allocator_factory, Create(_, Field(&VideoCodec::codecType, kVideoCodecVP8))) .WillOnce([] { return std::make_unique(); }); - FieldTrialBasedConfig trials; + FieldTrials trials = CreateTestFieldTrials(); WebRtcVideoEngine engine( (std::unique_ptr(encoder_factory)), (std::unique_ptr(decoder_factory)), trials); @@ -1595,8 +1589,6 @@ TEST_F(WebRtcVideoEngineTest, SetVideoRtxEnabled) { std::vector send_codecs; std::vector recv_codecs; - ScopedKeyValueConfig field_trials; - // Don't want RTX send_codecs = engine_.LegacySendCodecs(false); EXPECT_FALSE(HasAnyRtxCodec(send_codecs)); @@ -1613,7 +1605,8 @@ TEST_F(WebRtcVideoEngineTest, SetVideoRtxEnabled) { class WebRtcVideoChannelEncodedFrameCallbackTest : public ::testing::Test { protected: WebRtcVideoChannelEncodedFrameCallbackTest() - : env_(CreateEnvironment(&field_trials_, + : field_trials_(CreateTestFieldTrials()), + env_(CreateEnvironment(&field_trials_, time_controller_.CreateTaskQueueFactory(), time_controller_.GetClock())), call_(Call::Create(CallConfig(env_))), @@ -1663,7 +1656,7 @@ class WebRtcVideoChannelEncodedFrameCallbackTest : public ::testing::Test { static const std::vector kSdpVideoFormats; GlobalSimulatedTimeController time_controller_{Timestamp::Seconds(1000)}; - ScopedKeyValueConfig field_trials_; + FieldTrials field_trials_; Environment env_; std::unique_ptr call_; std::unique_ptr @@ -1783,7 +1776,8 @@ TEST_F(WebRtcVideoChannelEncodedFrameCallbackTest, DoesNotDecodeWhenDisabled) { class WebRtcVideoChannelBaseTest : public ::testing::Test { protected: WebRtcVideoChannelBaseTest() - : env_(CreateEnvironment(&field_trials_, + : field_trials_(CreateTestFieldTrials()), + env_(CreateEnvironment(&field_trials_, time_controller_.CreateTaskQueueFactory(), time_controller_.GetClock())), video_bitrate_allocator_factory_( @@ -2001,8 +1995,7 @@ class WebRtcVideoChannelBaseTest : public ::testing::Test { GlobalSimulatedTimeController time_controller_{Timestamp::Seconds(1000)}; - ScopedKeyValueConfig field_trials_; - std::unique_ptr override_field_trials_; + FieldTrials field_trials_; Environment env_; std::unique_ptr call_; std::unique_ptr @@ -2556,8 +2549,8 @@ TEST_F(WebRtcVideoChannelBaseTest, TwoStreamsSendAndReceive) { TEST_F(WebRtcVideoChannelBaseTest, RequestEncoderFallbackNextCodecFollowNegotiatedOrder) { - webrtc::test::ScopedKeyValueConfig field_trials( - field_trials_, "WebRTC-SwitchEncoderFollowCodecPreferenceOrder/Enabled/"); + field_trials_.Set("WebRTC-SwitchEncoderFollowCodecPreferenceOrder", + "Enabled"); VideoSenderParameters parameters; parameters.codecs.push_back(GetEngineCodec("VP9")); parameters.codecs.push_back(GetEngineCodec("AV1")); @@ -2755,7 +2748,7 @@ class WebRtcVideoChannelTest : public WebRtcVideoEngineTest { return static_cast(send_channel_.get()); } - // Casts a shim channel to a webrtc::Transport. Used once. + // Casts a shim channel to a Transport. Used once. Transport* ChannelImplAsTransport(VideoMediaSendChannelInterface* channel) { return static_cast(channel)->transport(); } @@ -3178,8 +3171,7 @@ TEST_F(WebRtcVideoChannelTest, RecvAbsoluteSendTimeHeaderExtensions) { } TEST_F(WebRtcVideoChannelTest, FiltersExtensionsPicksTransportSeqNum) { - ScopedKeyValueConfig override_field_trials( - field_trials_, "WebRTC-FilterAbsSendTimeExtension/Enabled/"); + field_trials_.Set("WebRTC-FilterAbsSendTimeExtension", "Enabled"); // Enable three redundant extensions. std::vector extensions; extensions.push_back(RtpExtension::kAbsSendTimeUri); @@ -3412,15 +3404,13 @@ TEST_F(WebRtcVideoChannelTest, LossNotificationIsDisabledByDefault) { } TEST_F(WebRtcVideoChannelTest, LossNotificationIsEnabledByFieldTrial) { - ScopedKeyValueConfig override_field_trials( - field_trials_, "WebRTC-RtcpLossNotification/Enabled/"); + field_trials_.Set("WebRTC-RtcpLossNotification", "Enabled"); ResetTest(); TestLossNotificationState(true); } TEST_F(WebRtcVideoChannelTest, LossNotificationCanBeEnabledAndDisabled) { - ScopedKeyValueConfig override_field_trials( - field_trials_, "WebRTC-RtcpLossNotification/Enabled/"); + field_trials_.Set("WebRTC-RtcpLossNotification", "Enabled"); ResetTest(); AssignDefaultCodec(); @@ -3863,7 +3853,7 @@ class Vp9SettingsTest : public WebRtcVideoChannelTest { : WebRtcVideoChannelTest(field_trials) { encoder_factory_->AddSupportedVideoCodecType("VP9"); } - virtual ~Vp9SettingsTest() {} + ~Vp9SettingsTest() override {} protected: void TearDown() override { @@ -4227,9 +4217,8 @@ TEST_F(WebRtcVideoChannelTest, VerifyMinBitrate) { } TEST_F(WebRtcVideoChannelTest, VerifyMinBitrateWithForcedFallbackFieldTrial) { - ScopedKeyValueConfig override_field_trials( - field_trials_, - "WebRTC-VP8-Forced-Fallback-Encoder-v2/Enabled-1,2,34567/"); + field_trials_.Set("WebRTC-VP8-Forced-Fallback-Encoder-v2", + "Enabled-1,2,34567"); std::vector streams = AddSendStream()->GetVideoStreams(); ASSERT_EQ(1u, streams.size()); EXPECT_EQ(34567, streams[0].min_bitrate_bps); @@ -4237,8 +4226,7 @@ TEST_F(WebRtcVideoChannelTest, VerifyMinBitrateWithForcedFallbackFieldTrial) { TEST_F(WebRtcVideoChannelTest, BalancedDegradationPreferenceNotSupportedWithoutFieldtrial) { - ScopedKeyValueConfig override_field_trials( - field_trials_, "WebRTC-Video-BalancedDegradation/Disabled/"); + field_trials_.Set("WebRTC-Video-BalancedDegradation", "Disabled"); const bool kResolutionScalingEnabled = true; const bool kFpsScalingEnabled = false; TestDegradationPreference(kResolutionScalingEnabled, kFpsScalingEnabled); @@ -4246,8 +4234,7 @@ TEST_F(WebRtcVideoChannelTest, TEST_F(WebRtcVideoChannelTest, BalancedDegradationPreferenceSupportedBehindFieldtrial) { - ScopedKeyValueConfig override_field_trials( - field_trials_, "WebRTC-Video-BalancedDegradation/Enabled/"); + field_trials_.Set("WebRTC-Video-BalancedDegradation", "Enabled"); const bool kResolutionScalingEnabled = true; const bool kFpsScalingEnabled = true; TestDegradationPreference(kResolutionScalingEnabled, kFpsScalingEnabled); @@ -7635,7 +7622,7 @@ TEST_F(WebRtcVideoChannelTest, ReceiveDifferentUnsignaledSsrc) { parameters.codecs.push_back(GetEngineCodec("VP9")); #if defined(WEBRTC_USE_H264) - webrtc::Codec H264codec = webrtc::CreateVideoCodec(126, "H264"); + Codec H264codec = CreateVideoCodec(126, "H264"); parameters.codecs.push_back(H264codec); #endif @@ -7694,12 +7681,12 @@ TEST_F(WebRtcVideoChannelTest, ReceiveDifferentUnsignaledSsrc) { recv_stream = fake_call_->GetVideoReceiveStreams()[0]; EXPECT_EQ(rtp_packet.Ssrc(), recv_stream->GetConfig().rtp.remote_ssrc); // Verify that the receive stream sinks to a renderer. - webrtc::VideoFrame video_frame3 = - webrtc::VideoFrame::Builder() + VideoFrame video_frame3 = + VideoFrame::Builder() .set_video_frame_buffer(CreateBlackFrameBuffer(4, 4)) .set_rtp_timestamp(300) .set_timestamp_us(0) - .set_rotation(webrtc::kVideoRotation_0) + .set_rotation(kVideoRotation_0) .build(); recv_stream->InjectFrame(video_frame3); EXPECT_EQ(3, renderer.num_rendered_frames()); @@ -8083,7 +8070,7 @@ class WebRtcVideoChannelScaleResolutionDownByTest TEST_P(WebRtcVideoChannelScaleResolutionDownByTest, ScaleResolutionDownBy) { ScaleResolutionDownByTestParameters test_params = std::get<0>(GetParam()); std::string codec_name = std::get<1>(GetParam()); - ScopedKeyValueConfig field_trial(field_trials_, test_params.field_trials); + field_trials_.Merge(FieldTrials(test_params.field_trials)); // Set up WebRtcVideoChannel for 3-layer simulcast. encoder_factory_->AddSupportedVideoCodecType(codec_name); VideoSenderParameters parameters; @@ -9108,8 +9095,7 @@ TEST_F(WebRtcVideoChannelTest, } TEST_F(WebRtcVideoChannelTest, SetMixedCodecSimulcastStreamConfig) { - ScopedKeyValueConfig field_trials(field_trials_, - "WebRTC-MixedCodecSimulcast/Enabled/"); + field_trials_.Set("WebRTC-MixedCodecSimulcast", "Enabled"); StreamParams sp = CreateSimStreamParams("cname", {123, 456, 789}); @@ -9158,8 +9144,7 @@ TEST_F(WebRtcVideoChannelTest, SetMixedCodecSimulcastStreamConfig) { #if RTC_DCHECK_IS_ON && GTEST_HAS_DEATH_TEST && !defined(WEBRTC_ANDROID) TEST_F(WebRtcVideoChannelTest, SetMixedCodecSimulcastWithDifferentConfigSettingsSizes) { - test::ScopedKeyValueConfig field_trials( - field_trials_, "WebRTC-MixedCodecSimulcast/Enabled/"); + field_trials_.Set("WebRTC-MixedCodecSimulcast", "Enabled"); AddSendStream(); VideoSenderParameters parameters; @@ -9699,7 +9684,8 @@ TEST_F(WebRtcVideoChannelTest, GenerateKeyFrameSimulcast) { class WebRtcVideoChannelSimulcastTest : public ::testing::Test { public: WebRtcVideoChannelSimulcastTest() - : fake_call_(CreateEnvironment(&field_trials_)), + : field_trials_(CreateTestFieldTrials()), + fake_call_(CreateEnvironment(&field_trials_)), encoder_factory_(new FakeWebRtcVideoEncoderFactory), decoder_factory_(new FakeWebRtcVideoDecoderFactory), mock_rate_allocator_factory_( @@ -9863,7 +9849,7 @@ class WebRtcVideoChannelSimulcastTest : public ::testing::Test { return streams[streams.size() - 1]; } - ScopedKeyValueConfig field_trials_; + FieldTrials field_trials_; FakeCall fake_call_; FakeWebRtcVideoEncoderFactory* encoder_factory_; FakeWebRtcVideoDecoderFactory* decoder_factory_; diff --git a/media/engine/webrtc_voice_engine.cc b/media/engine/webrtc_voice_engine.cc index 2d397c6008..3690ffb255 100644 --- a/media/engine/webrtc_voice_engine.cc +++ b/media/engine/webrtc_voice_engine.cc @@ -175,7 +175,7 @@ bool IsCodec(const Codec& codec, const char* ref_name) { std::optional FindCodec(const std::vector& codecs, const Codec& codec) { - for (const webrtc::Codec& c : codecs) { + for (const Codec& c : codecs) { if (c.Matches(codec)) { return c; } @@ -189,7 +189,7 @@ bool VerifyUniquePayloadTypes(const std::vector& codecs) { } std::vector payload_types; absl::c_transform(codecs, std::back_inserter(payload_types), - [](const webrtc::Codec& codec) { return codec.id; }); + [](const Codec& codec) { return codec.id; }); absl::c_sort(payload_types); return absl::c_adjacent_find(payload_types) == payload_types.end(); } @@ -343,7 +343,7 @@ bool CheckRedParameters( return false; } std::vector redundant_payloads = - webrtc::split(red_parameters->second, '/'); + split(red_parameters->second, '/'); // 32 is chosen as a maximum upper bound for consistency with the // red payload splitter. if (redundant_payloads.size() < 2 || redundant_payloads.size() > 32) { @@ -378,7 +378,7 @@ std::vector LegacyCollectCodecs(const std::vector& specs, {48000, false}}; for (const auto& spec : specs) { - Codec codec = webrtc::CreateAudioCodec(spec.format); + Codec codec = CreateAudioCodec(spec.format); if (allocate_pt) { auto pt_or_error = pt_mapper.SuggestMapping(codec, nullptr); // We need to do some extra stuff before adding the main codecs to out. @@ -415,14 +415,14 @@ std::vector LegacyCollectCodecs(const std::vector& specs, if (allocate_pt) { std::string red_fmtp = absl::StrCat(codec.id) + "/" + absl::StrCat(codec.id); - Codec red_codec = webrtc::CreateAudioCodec( + Codec red_codec = CreateAudioCodec( {kRedCodecName, codec.clockrate, codec.channels, {{"", red_fmtp}}}); red_codec.id = pt_mapper.SuggestMapping(red_codec, nullptr).value(); out.push_back(red_codec); } else { // We don't know the PT to put into the RED fmtp parameter yet. // Leave it out. - Codec red_codec = webrtc::CreateAudioCodec({kRedCodecName, 48000, 2}); + Codec red_codec = CreateAudioCodec({kRedCodecName, 48000, 2}); out.push_back(red_codec); } } @@ -431,7 +431,7 @@ std::vector LegacyCollectCodecs(const std::vector& specs, // Add CN codecs after "proper" audio codecs. for (const auto& cn : generate_cn) { if (cn.second) { - Codec cn_codec = webrtc::CreateAudioCodec({kCnCodecName, cn.first, 1}); + Codec cn_codec = CreateAudioCodec({kCnCodecName, cn.first, 1}); if (allocate_pt) { cn_codec.id = pt_mapper.SuggestMapping(cn_codec, nullptr).value(); } @@ -442,8 +442,7 @@ std::vector LegacyCollectCodecs(const std::vector& specs, // Add telephone-event codecs last. for (const auto& dtmf : generate_dtmf) { if (dtmf.second) { - Codec dtmf_codec = - webrtc::CreateAudioCodec({kDtmfCodecName, dtmf.first, 1}); + Codec dtmf_codec = CreateAudioCodec({kDtmfCodecName, dtmf.first, 1}); if (allocate_pt) { dtmf_codec.id = pt_mapper.SuggestMapping(dtmf_codec, nullptr).value(); } @@ -509,7 +508,7 @@ void WebRtcVoiceEngine::Init() { send_codecs_ = LegacyCollectCodecs(encoder_factory_->GetSupportedEncoders(), !payload_types_in_transport_trial_enabled_); - for (const webrtc::Codec& codec : send_codecs_) { + for (const Codec& codec : send_codecs_) { RTC_LOG(LS_VERBOSE) << ToString(codec); } @@ -517,7 +516,7 @@ void WebRtcVoiceEngine::Init() { recv_codecs_ = LegacyCollectCodecs(decoder_factory_->GetSupportedDecoders(), !payload_types_in_transport_trial_enabled_); - for (const webrtc::Codec& codec : recv_codecs_) { + for (const Codec& codec : recv_codecs_) { RTC_LOG(LS_VERBOSE) << ToString(codec); } @@ -529,7 +528,7 @@ void WebRtcVoiceEngine::Init() { } #endif // WEBRTC_INCLUDE_INTERNAL_AUDIO_DEVICE RTC_CHECK(adm()); - webrtc::adm_helpers::Init(adm()); + adm_helpers::Init(adm()); // Set up AudioState. { @@ -771,13 +770,12 @@ WebRtcVoiceEngine::GetRtpHeaderExtensions() const { // id is *not* incremented for non-default extensions, UsedIds needs to // resolve conflicts. int id = 1; - for (const auto& uri : {webrtc::RtpExtension::kAudioLevelUri, - webrtc::RtpExtension::kAbsSendTimeUri, - webrtc::RtpExtension::kTransportSequenceNumberUri, - webrtc::RtpExtension::kMidUri}) { + for (const auto& uri : + {RtpExtension::kAudioLevelUri, RtpExtension::kAbsSendTimeUri, + RtpExtension::kTransportSequenceNumberUri, RtpExtension::kMidUri}) { result.emplace_back(uri, id++, RtpTransceiverDirection::kSendRecv); } - for (const auto& uri : {webrtc::RtpExtension::kAbsoluteCaptureTimeUri}) { + for (const auto& uri : {RtpExtension::kAbsoluteCaptureTimeUri}) { result.emplace_back(uri, id, RtpTransceiverDirection::kStopped); } return result; @@ -1083,7 +1081,7 @@ class WebRtcVoiceSendChannel::WebRtcAudioSendStream : public AudioSource::Sink { RTCError error = CheckRtpParametersInvalidModificationAndValues( rtp_parameters_, parameters, call_->trials()); if (!error.ok()) { - return webrtc::InvokeSetParametersCallback(callback, error); + return InvokeSetParametersCallback(callback, error); } std::optional send_rate; @@ -1092,7 +1090,7 @@ class WebRtcVoiceSendChannel::WebRtcAudioSendStream : public AudioSource::Sink { parameters.encodings[0].max_bitrate_bps, *audio_codec_spec_); if (!send_rate) { - return webrtc::InvokeSetParametersCallback( + return InvokeSetParametersCallback( callback, RTCError(RTCErrorType::INTERNAL_ERROR)); } } @@ -1102,16 +1100,23 @@ class WebRtcVoiceSendChannel::WebRtcAudioSendStream : public AudioSource::Sink { double old_priority = rtp_parameters_.encodings[0].bitrate_priority; Priority old_dscp = rtp_parameters_.encodings[0].network_priority; bool old_adaptive_ptime = rtp_parameters_.encodings[0].adaptive_ptime; + std::optional> old_csrcs = + rtp_parameters_.encodings[0].csrcs; + rtp_parameters_ = parameters; config_.bitrate_priority = rtp_parameters_.encodings[0].bitrate_priority; config_.has_dscp = (rtp_parameters_.encodings[0].network_priority != Priority::kLow); + if (rtp_parameters_.encodings[0].csrcs.has_value()) { + config_.rtp.csrcs = rtp_parameters_.encodings[0].csrcs.value(); + } bool reconfigure_send_stream = (rtp_parameters_.encodings[0].max_bitrate_bps != old_rtp_max_bitrate) || (rtp_parameters_.encodings[0].bitrate_priority != old_priority) || (rtp_parameters_.encodings[0].network_priority != old_dscp) || - (rtp_parameters_.encodings[0].adaptive_ptime != old_adaptive_ptime); + (rtp_parameters_.encodings[0].adaptive_ptime != old_adaptive_ptime) || + (rtp_parameters_.encodings[0].csrcs != old_csrcs); if (rtp_parameters_.encodings[0].max_bitrate_bps != old_rtp_max_bitrate) { // Update the bitrate range. if (send_rate) { @@ -1125,7 +1130,7 @@ class WebRtcVoiceSendChannel::WebRtcAudioSendStream : public AudioSource::Sink { UpdateAllowedBitrateRange(); ReconfigureAudioSendStream(std::move(callback)); } else { - webrtc::InvokeSetParametersCallback(callback, RTCError::OK()); + InvokeSetParametersCallback(callback, RTCError::OK()); } rtp_parameters_.rtcp.cname = config_.rtp.c_name; @@ -1386,7 +1391,7 @@ bool WebRtcVoiceSendChannel::SetSenderParameters( std::optional WebRtcVoiceSendChannel::GetSendCodec() const { if (send_codec_spec_) { - return webrtc::CreateAudioCodec(send_codec_spec_->format); + return CreateAudioCodec(send_codec_spec_->format); } return std::nullopt; } @@ -1402,7 +1407,7 @@ bool WebRtcVoiceSendChannel::SetSendCodecs( dtmf_payload_freq_ = -1; // Validate supplied codecs list. - for (const webrtc::Codec& codec : codecs) { + for (const Codec& codec : codecs) { // TODO(solenberg): Validate more aspects of input - that payload types // don't overlap, remove redundant/unsupported codecs etc - // the same way it is done for RtpHeaderExtensions. @@ -1417,7 +1422,7 @@ bool WebRtcVoiceSendChannel::SetSendCodecs( // case we don't have a DTMF codec with a rate matching the send codec's, or // if this function returns early. std::vector dtmf_codecs; - for (const webrtc::Codec& codec : codecs) { + for (const Codec& codec : codecs) { if (IsCodec(codec, kDtmfCodecName)) { dtmf_codecs.push_back(codec); if (!dtmf_payload_type_ || codec.clockrate < dtmf_payload_freq_) { @@ -1432,7 +1437,7 @@ bool WebRtcVoiceSendChannel::SetSendCodecs( BitrateConstraints bitrate_config; std::optional voice_codec_info; size_t send_codec_position = 0; - for (const webrtc::Codec& voice_codec : codecs) { + for (const Codec& voice_codec : codecs) { if (!(IsCodec(voice_codec, kCnCodecName) || IsCodec(voice_codec, kDtmfCodecName) || IsCodec(voice_codec, kRedCodecName)) && @@ -1452,8 +1457,8 @@ bool WebRtcVoiceSendChannel::SetSendCodecs( if (voice_codec.bitrate > 0) { send_codec_spec->target_bitrate_bps = voice_codec.bitrate; } - send_codec_spec->nack_enabled = webrtc::HasNack(voice_codec); - send_codec_spec->enable_non_sender_rtt = webrtc::HasRrtr(voice_codec); + send_codec_spec->nack_enabled = HasNack(voice_codec); + send_codec_spec->enable_non_sender_rtt = HasRrtr(voice_codec); bitrate_config = GetBitrateConfigForCodec(voice_codec); break; } @@ -1469,7 +1474,7 @@ bool WebRtcVoiceSendChannel::SetSendCodecs( if (voice_codec_info->allow_comfort_noise) { // Loop through the codecs list again to find the CN codec. // TODO(solenberg): Break out into a separate function? - for (const webrtc::Codec& cn_codec : codecs) { + for (const Codec& cn_codec : codecs) { if (IsCodec(cn_codec, kCnCodecName) && cn_codec.clockrate == send_codec_spec->format.clockrate_hz && cn_codec.channels == voice_codec_info->num_channels) { @@ -1487,7 +1492,7 @@ bool WebRtcVoiceSendChannel::SetSendCodecs( } // Find the telephone-event PT exactly matching the preferred send codec. - for (const webrtc::Codec& dtmf_codec : dtmf_codecs) { + for (const Codec& dtmf_codec : dtmf_codecs) { if (dtmf_codec.clockrate == send_codec_spec->format.clockrate_hz) { dtmf_payload_type_ = dtmf_codec.id; dtmf_payload_freq_ = dtmf_codec.clockrate; @@ -1773,8 +1778,8 @@ bool WebRtcVoiceSendChannel::SetMaxSendBitrate(int bps) { void WebRtcVoiceSendChannel::OnReadyToSend(bool ready) { RTC_DCHECK_RUN_ON(&network_thread_checker_); RTC_LOG(LS_VERBOSE) << "OnReadyToSend: " << (ready ? "Ready." : "Not ready."); - call_->SignalChannelNetworkState( - MediaType::AUDIO, ready ? webrtc::kNetworkUp : webrtc::kNetworkDown); + call_->SignalChannelNetworkState(MediaType::AUDIO, + ready ? kNetworkUp : kNetworkDown); } bool WebRtcVoiceSendChannel::GetStats(VoiceMediaSendInfo* info) { @@ -1831,11 +1836,9 @@ bool WebRtcVoiceSendChannel::GetStats(VoiceMediaSendInfo* info) { void WebRtcVoiceSendChannel::FillSendCodecStats( VoiceMediaSendInfo* voice_media_info) { for (const auto& sender : voice_media_info->senders) { - auto codec = - absl::c_find_if(send_codecs_, [&sender](const webrtc::Codec& c) { - return sender.codec_payload_type && - *sender.codec_payload_type == c.id; - }); + auto codec = absl::c_find_if(send_codecs_, [&sender](const Codec& c) { + return sender.codec_payload_type && *sender.codec_payload_type == c.id; + }); if (codec != send_codecs_.end()) { voice_media_info->send_codecs.insert( std::make_pair(codec->id, codec->ToCodecParameters())); @@ -1871,7 +1874,7 @@ RtpParameters WebRtcVoiceSendChannel::GetRtpSendParameters( RtpParameters rtp_params = it->second->rtp_parameters(); // Need to add the common list of codecs to the send stream-specific // RTP parameters. - for (const webrtc::Codec& codec : send_codecs_) { + for (const Codec& codec : send_codecs_) { rtp_params.codecs.push_back(codec.ToCodecParameters()); } return rtp_params; @@ -1887,8 +1890,8 @@ RTCError WebRtcVoiceSendChannel::SetRtpSendParameters( RTC_LOG(LS_WARNING) << "Attempting to set RTP send parameters for stream " "with ssrc " << ssrc << " which doesn't exist."; - return webrtc::InvokeSetParametersCallback( - callback, RTCError(RTCErrorType::INTERNAL_ERROR)); + return InvokeSetParametersCallback(callback, + RTCError(RTCErrorType::INTERNAL_ERROR)); } // TODO(deadbeef): Handle setting parameters with a list of codecs in a @@ -1897,26 +1900,26 @@ RTCError WebRtcVoiceSendChannel::SetRtpSendParameters( if (current_parameters.codecs != parameters.codecs) { RTC_DLOG(LS_ERROR) << "Using SetParameters to change the set of codecs " "is not currently supported."; - return webrtc::InvokeSetParametersCallback( - callback, RTCError(RTCErrorType::INTERNAL_ERROR)); + return InvokeSetParametersCallback(callback, + RTCError(RTCErrorType::INTERNAL_ERROR)); } if (!parameters.encodings.empty()) { // Note that these values come from: // https://tools.ietf.org/html/draft-ietf-tsvwg-rtcweb-qos-16#section-5 - DiffServCodePoint new_dscp = webrtc::DSCP_DEFAULT; + DiffServCodePoint new_dscp = DSCP_DEFAULT; switch (parameters.encodings[0].network_priority) { case Priority::kVeryLow: - new_dscp = webrtc::DSCP_CS1; + new_dscp = DSCP_CS1; break; case Priority::kLow: - new_dscp = webrtc::DSCP_DEFAULT; + new_dscp = DSCP_DEFAULT; break; case Priority::kMedium: - new_dscp = webrtc::DSCP_EF; + new_dscp = DSCP_EF; break; case Priority::kHigh: - new_dscp = webrtc::DSCP_EF; + new_dscp = DSCP_EF; break; } SetPreferredDscp(new_dscp); @@ -1936,7 +1939,7 @@ RTCError WebRtcVoiceSendChannel::SetRtpSendParameters( }); if (matched_codec == send_codecs_.end()) { - return webrtc::InvokeSetParametersCallback( + return InvokeSetParametersCallback( callback, RTCError(RTCErrorType::INVALID_MODIFICATION, "Attempted to use an unsupported codec for layer 0")); @@ -2154,7 +2157,7 @@ RtpParameters WebRtcVoiceReceiveChannel::GetRtpReceiverParameters( rtp_params.encodings.back().ssrc = it->second->stream().remote_ssrc(); rtp_params.header_extensions = recv_rtp_extensions_; - for (const webrtc::Codec& codec : recv_codecs_) { + for (const Codec& codec : recv_codecs_) { rtp_params.codecs.push_back(codec.ToCodecParameters()); } rtp_params.rtcp.reduced_size = recv_rtcp_mode_ == RtcpMode::kReducedSize; @@ -2173,7 +2176,7 @@ RtpParameters WebRtcVoiceReceiveChannel::GetDefaultRtpReceiveParameters() } rtp_params.encodings.emplace_back(); - for (const webrtc::Codec& codec : recv_codecs_) { + for (const Codec& codec : recv_codecs_) { rtp_params.codecs.push_back(codec.ToCodecParameters()); } return rtp_params; @@ -2218,7 +2221,7 @@ bool WebRtcVoiceReceiveChannel::SetRecvCodecs( // Create a payload type -> SdpAudioFormat map with all the decoders. Fail // unless the factory claims to support all decoders. std::map decoder_map; - for (const webrtc::Codec& codec : codecs) { + for (const Codec& codec : codecs) { // Log a warning if a codec's payload type is changing. This used to be // treated as an error. It's abnormal, but not really illegal. std::optional old_codec = FindCodec(recv_codecs_, codec); @@ -2445,17 +2448,17 @@ void WebRtcVoiceReceiveChannel::OnDemuxerCriteriaUpdateComplete() {} bool WebRtcVoiceReceiveChannel::SetOutputVolume(uint32_t ssrc, double volume) { RTC_DCHECK_RUN_ON(worker_thread_); - RTC_LOG(LS_INFO) << webrtc::StringFormat( - "WRVMC::%s({ssrc=%u}, {volume=%.2f})", __func__, ssrc, volume); + RTC_LOG(LS_INFO) << StringFormat("WRVMC::%s({ssrc=%u}, {volume=%.2f})", + __func__, ssrc, volume); const auto it = recv_streams_.find(ssrc); if (it == recv_streams_.end()) { - RTC_LOG(LS_WARNING) << webrtc::StringFormat( + RTC_LOG(LS_WARNING) << StringFormat( "WRVMC::%s => (WARNING: no receive stream for SSRC %u)", __func__, ssrc); return false; } it->second->SetOutputVolume(volume); - RTC_LOG(LS_INFO) << webrtc::StringFormat( + RTC_LOG(LS_INFO) << StringFormat( "WRVMC::%s => (stream with SSRC %u now uses volume %.2f)", __func__, ssrc, volume); return true; @@ -2551,7 +2554,7 @@ void WebRtcVoiceReceiveChannel::OnPacketReceived( // applied directly in RtpTransport::DemuxPacket; packet.IdentifyExtensions(recv_rtp_extension_map_); if (!packet.arrival_time().IsFinite()) { - packet.set_arrival_time(Timestamp::Micros(webrtc::TimeMicros())); + packet.set_arrival_time(Timestamp::Micros(TimeMicros())); } call_->Receiver()->DeliverRtpPacket( @@ -2725,7 +2728,7 @@ void WebRtcVoiceReceiveChannel::FillReceiveCodecStats( VoiceMediaReceiveInfo* voice_media_info) { for (const auto& receiver : voice_media_info->receivers) { auto codec = - absl::c_find_if(recv_codecs_, [&receiver](const webrtc::Codec& c) { + absl::c_find_if(recv_codecs_, [&receiver](const Codec& c) { return receiver.codec_payload_type && *receiver.codec_payload_type == c.id; }); diff --git a/media/engine/webrtc_voice_engine_unittest.cc b/media/engine/webrtc_voice_engine_unittest.cc index 3bdd0f7250..6dfe2bbea3 100644 --- a/media/engine/webrtc_voice_engine_unittest.cc +++ b/media/engine/webrtc_voice_engine_unittest.cc @@ -34,6 +34,7 @@ #include "api/crypto/crypto_options.h" #include "api/environment/environment.h" #include "api/environment/environment_factory.h" +#include "api/field_trials.h" #include "api/make_ref_counted.h" #include "api/media_types.h" #include "api/priority.h" @@ -72,11 +73,11 @@ #include "rtc_base/dscp.h" #include "rtc_base/numerics/safe_conversions.h" #include "rtc_base/thread.h" +#include "test/create_test_field_trials.h" #include "test/gmock.h" #include "test/gtest.h" #include "test/mock_audio_decoder_factory.h" #include "test/mock_audio_encoder_factory.h" -#include "test/scoped_key_value_config.h" namespace { using ::testing::_; @@ -95,7 +96,9 @@ using ::webrtc::BuiltinAudioProcessingBuilder; using ::webrtc::Call; using ::webrtc::CallConfig; using ::webrtc::CreateEnvironment; +using ::webrtc::CreateTestFieldTrials; using ::webrtc::Environment; +using ::webrtc::FieldTrials; using ::webrtc::scoped_refptr; constexpr uint32_t kMaxUnsignaledRecvStreams = 4; @@ -251,6 +254,7 @@ class WebRtcVoiceEngineTestFake : public ::testing::TestWithParam { public: WebRtcVoiceEngineTestFake() : use_null_apm_(GetParam()), + field_trials_(CreateTestFieldTrials()), env_(CreateEnvironment(&field_trials_)), adm_(webrtc::test::MockAudioDeviceModule::CreateStrict()), apm_(use_null_apm_ @@ -911,7 +915,7 @@ class WebRtcVoiceEngineTestFake : public ::testing::TestWithParam { protected: webrtc::AutoThread main_thread_; const bool use_null_apm_; - webrtc::test::ScopedKeyValueConfig field_trials_; + FieldTrials field_trials_; const Environment env_; webrtc::scoped_refptr adm_; webrtc::scoped_refptr> apm_; @@ -1326,8 +1330,7 @@ TEST_P(WebRtcVoiceEngineTestFake, } TEST_P(WebRtcVoiceEngineTestFake, AdaptivePtimeFieldTrial) { - webrtc::test::ScopedKeyValueConfig override_field_trials( - field_trials_, "WebRTC-Audio-AdaptivePtime/enabled:true/"); + field_trials_.Set("WebRTC-Audio-AdaptivePtime", "enabled:true"); EXPECT_TRUE(SetupSendStream()); EXPECT_TRUE(GetAudioNetworkAdaptorConfig(kSsrcX)); } @@ -4124,8 +4127,8 @@ TEST(WebRtcVoiceEngineTest, CollectRecvCodecs) { } TEST(WebRtcVoiceEngineTest, CollectRecvCodecsWithLatePtAssignment) { - webrtc::test::ScopedKeyValueConfig field_trials( - "WebRTC-PayloadTypesInTransport/Enabled/"); + FieldTrials field_trials = + CreateTestFieldTrials("WebRTC-PayloadTypesInTransport/Enabled/"); Environment env = CreateEnvironment(&field_trials); for (bool use_null_apm : {false, true}) { diff --git a/media/sctp/dcsctp_transport.h b/media/sctp/dcsctp_transport.h index 582e273d48..476dec80e5 100644 --- a/media/sctp/dcsctp_transport.h +++ b/media/sctp/dcsctp_transport.h @@ -59,7 +59,7 @@ class DcSctpTransport : public SctpTransportInternal, std::unique_ptr socket_factory); ~DcSctpTransport() override; - // webrtc::SctpTransportInternal + // SctpTransportInternal void SetOnConnectedCallback(std::function callback) override; void SetDataChannelSink(DataChannelSink* sink) override; void SetDtlsTransport(DtlsTransportInternal* transport) override; @@ -108,7 +108,7 @@ class DcSctpTransport : public SctpTransportInternal, void OnTransportReadPacket(PacketTransportInternal* transport, const ReceivedIpPacket& packet); void OnDtlsTransportState(DtlsTransportInternal* transport, - webrtc::DtlsTransportState); + DtlsTransportState); void MaybeConnectSocket(); Thread* network_thread_; @@ -137,7 +137,7 @@ class DcSctpTransport : public SctpTransportInternal, bool outgoing_reset_done = false; // Priority of the stream according to RFC 8831, section 6.4 dcsctp::StreamPriority priority = - dcsctp::StreamPriority(PriorityValue(webrtc::Priority::kLow).value()); + dcsctp::StreamPriority(PriorityValue(Priority::kLow).value()); }; // Map of all currently open or closing data channels diff --git a/modules/audio_coding/BUILD.gn b/modules/audio_coding/BUILD.gn index 3a8d0db866..c3f061f69f 100644 --- a/modules/audio_coding/BUILD.gn +++ b/modules/audio_coding/BUILD.gn @@ -293,7 +293,6 @@ rtc_library("webrtc_opus") { "../../rtc_base:buffer", "../../rtc_base:checks", "../../rtc_base:logging", - "../../rtc_base:macromagic", "../../rtc_base:protobuf_utils", "../../rtc_base:rtc_numerics", "../../rtc_base:safe_conversions", @@ -331,7 +330,6 @@ rtc_library("webrtc_multiopus") { "../../rtc_base:buffer", "../../rtc_base:checks", "../../rtc_base:logging", - "../../rtc_base:macromagic", "../../rtc_base:safe_conversions", "../../rtc_base:safe_minmax", "../../rtc_base:stringutils", @@ -868,9 +866,8 @@ if (rtc_include_tests) { ":audio_encoder_cng", ":pcm16b_c", ":red", - ":webrtc_opus_wrapper", - "..:module_api", "../../api:array_view", + "../../api:field_trials", "../../api:rtp_headers", "../../api:scoped_refptr", "../../api/audio:audio_frame_api", @@ -893,13 +890,12 @@ if (rtc_include_tests) { "../../common_audio", "../../rtc_base:checks", "../../rtc_base:ip_address", - "../../rtc_base:logging", "../../rtc_base:macromagic", "../../rtc_base:stringutils", "../../rtc_base:timeutils", "../../rtc_base/synchronization:mutex", + "../../test:create_test_field_trials", "../../test:fileutils", - "../../test:scoped_key_value_config", "../../test:test_support", "//third_party/abseil-cpp/absl/strings", "//third_party/abseil-cpp/absl/strings:string_view", @@ -926,7 +922,6 @@ if (rtc_include_tests) { "../../api/test/metrics:global_metrics_logger_and_exporter", "../../api/test/metrics:metric", "../../rtc_base:buffer", - "../../rtc_base:macromagic", "../../rtc_base:timeutils", "../../system_wrappers", "../../test:fileutils", @@ -1014,24 +1009,19 @@ if (rtc_include_tests) { defines = neteq_defines deps = [ - ":neteq", ":neteq_input_audio_tools", - ":neteq_tools", "../../api:array_view", "../../api/audio_codecs:audio_codecs_api", "../../api/audio_codecs/g722:audio_encoder_g722_config", "../../api/audio_codecs/opus:audio_encoder_opus", "../../api/audio_codecs/opus:audio_encoder_opus_config", "../../api/environment:environment_factory", - "../../common_audio", "../../rtc_base:buffer", "../../rtc_base:checks", - "../../rtc_base/system:arch", - "../../test:explicit_key_value_config", + "../../test:create_test_field_trials", "../../test:fileutils", "../../test:test_main", "../../test:test_support", - "//testing/gtest", ] + audio_coding_deps data = audio_decoder_unittests_resources @@ -1089,15 +1079,12 @@ if (rtc_include_tests) { defines = [] deps = [ ":neteq_test_factory", - ":neteq_test_tools", ":neteq_tools_minimal", "../../rtc_base:checks", "../../rtc_base:stringutils", - "../../system_wrappers:field_trial", - "../../test:field_trial", "//third_party/abseil-cpp/absl/flags:flag", "//third_party/abseil-cpp/absl/flags:parse", - "//third_party/abseil-cpp/absl/strings", + "//third_party/abseil-cpp/absl/strings:string_view", ] sources = [ "neteq/tools/neteq_rtpplay.cc" ] } @@ -1122,7 +1109,6 @@ if (rtc_include_tests) { testonly = true defines = [] deps = [ - "../../rtc_base:macromagic", "../../test:fileutils", "//third_party/opus", ] @@ -1401,7 +1387,6 @@ if (rtc_include_tests) { deps = [ ":webrtc_opus", "../../common_audio", - "../../rtc_base:macromagic", "../../test:fileutils", "../../test:test_main", "../../test:test_support", @@ -1496,23 +1481,24 @@ if (rtc_include_tests) { ":audio_coding_opus_common", ":audio_encoder_cng", ":audio_network_adaptor", + ":audio_network_adaptor_config", ":g711", ":legacy_encoded_audio_frame", ":mocks", ":neteq", ":neteq_input_audio_tools", - ":neteq_test_support", ":neteq_test_tools", - ":neteq_tools", ":neteq_tools_minimal", ":pcm16b", + ":pcm16b_c", ":red", ":webrtc_cng", ":webrtc_opus", - "..:module_api", + ":webrtc_opus_wrapper", "..:module_api_public", "../../api:array_view", "../../api:bitrate_allocation", + "../../api:field_trials", "../../api:field_trials_view", "../../api:make_ref_counted", "../../api:rtp_headers", @@ -1541,11 +1527,9 @@ if (rtc_include_tests) { "../../api/units:time_delta", "../../api/units:timestamp", "../../common_audio", - "../../common_audio:common_audio_c", "../../common_audio:mock_common_audio", "../../logging:mocks", "../../logging:rtc_event_audio", - "../../modules/rtp_rtcp:rtp_rtcp_format", "../../rtc_base:buffer", "../../rtc_base:checks", "../../rtc_base:copy_on_write_buffer", @@ -1554,30 +1538,23 @@ if (rtc_include_tests) { "../../rtc_base:macromagic", "../../rtc_base:platform_thread", "../../rtc_base:random", - "../../rtc_base:refcount", "../../rtc_base:rtc_base_tests_utils", "../../rtc_base:rtc_event", "../../rtc_base:safe_conversions", - "../../rtc_base:sanitizer", "../../rtc_base:stringutils", "../../rtc_base:threading", - "../../rtc_base:timeutils", "../../rtc_base/synchronization:mutex", "../../rtc_base/system:arch", "../../system_wrappers", "../../test:audio_codec_mocks", "../../test:audio_test_common", - "../../test:explicit_key_value_config", + "../../test:create_test_field_trials", "../../test:fileutils", "../../test:rtc_expect_death", - "../../test:rtp_test_utils", - "../../test:scoped_key_value_config", - "../../test:test_common", "../../test:test_support", + "../rtp_rtcp:rtp_rtcp_format", "codecs/opus/test", "codecs/opus/test:test_unittest", - "//testing/gmock", - "//testing/gtest", "//third_party/abseil-cpp/absl/flags:flag", "//third_party/abseil-cpp/absl/memory", "//third_party/abseil-cpp/absl/strings:string_view", diff --git a/modules/audio_coding/acm2/audio_coding_module_unittest.cc b/modules/audio_coding/acm2/audio_coding_module_unittest.cc index ba8ca870d1..7982ffc1b3 100644 --- a/modules/audio_coding/acm2/audio_coding_module_unittest.cc +++ b/modules/audio_coding/acm2/audio_coding_module_unittest.cc @@ -179,11 +179,11 @@ class AudioCodingModuleTestOldApi : public ::testing::Test { : env_(CreateEnvironment()), rtp_utility_(new RtpData(kFrameSizeSamples, kPayloadType)) {} - ~AudioCodingModuleTestOldApi() {} + ~AudioCodingModuleTestOldApi() override {} - void TearDown() {} + void TearDown() override {} - void SetUp() { + void SetUp() override { acm_ = AudioCodingModule::Create(); neteq_ = DefaultNetEqFactory().Create(env_, NetEq::Config(), CreateBuiltinAudioDecoderFactory()); @@ -383,7 +383,7 @@ class AudioCodingModuleMtTestOldApi : public AudioCodingModuleTestOldApi { env_ = override_clock.Create(); } - void SetUp() { + void SetUp() override { AudioCodingModuleTestOldApi::SetUp(); RegisterCodec(); // Must be called before the threads start below. StartThreads(); @@ -417,7 +417,7 @@ class AudioCodingModuleMtTestOldApi : public AudioCodingModuleTestOldApi { "pull_audio", attributes); } - void TearDown() { + void TearDown() override { AudioCodingModuleTestOldApi::TearDown(); quit_.store(true); pull_audio_thread_.Finalize(); @@ -540,7 +540,7 @@ class AcmAbsoluteCaptureTimestamp : public ::testing::Test { static constexpr int kFrameSize = kSampleRateHz / 100; static constexpr int kNumChannels = 2; - void SetUp() { + void SetUp() override { scoped_refptr codec_factory = CreateBuiltinAudioEncoderFactory(); acm_ = AudioCodingModule::Create(); diff --git a/modules/audio_coding/codecs/cng/audio_encoder_cng_unittest.cc b/modules/audio_coding/codecs/cng/audio_encoder_cng_unittest.cc index 606a6b807c..4f5e3af616 100644 --- a/modules/audio_coding/codecs/cng/audio_encoder_cng_unittest.cc +++ b/modules/audio_coding/codecs/cng/audio_encoder_cng_unittest.cc @@ -41,9 +41,9 @@ using ::testing::SetArgPointee; namespace webrtc { namespace { -static const size_t kMaxNumSamples = 48 * 10 * 2; // 10 ms @ 48 kHz stereo. -static const size_t kMockReturnEncodedBytes = 17; -static const int kCngPayloadType = 18; +const size_t kMaxNumSamples = 48 * 10 * 2; // 10 ms @ 48 kHz stereo. +const size_t kMockReturnEncodedBytes = 17; +const int kCngPayloadType = 18; } // namespace class AudioEncoderCngTest : public ::testing::Test { diff --git a/modules/audio_coding/codecs/cng/cng_unittest.cc b/modules/audio_coding/codecs/cng/cng_unittest.cc index 01b7fbfb1c..309e2b6880 100644 --- a/modules/audio_coding/codecs/cng/cng_unittest.cc +++ b/modules/audio_coding/codecs/cng/cng_unittest.cc @@ -38,7 +38,7 @@ enum { kNoSid, kForceSid }; class CngTest : public ::testing::Test { protected: - virtual void SetUp(); + void SetUp() override; void TestCngEncode(int sample_rate_hz, int quality); diff --git a/modules/audio_coding/codecs/legacy_encoded_audio_frame_unittest.cc b/modules/audio_coding/codecs/legacy_encoded_audio_frame_unittest.cc index 5e03dce2bd..a1712b74cd 100644 --- a/modules/audio_coding/codecs/legacy_encoded_audio_frame_unittest.cc +++ b/modules/audio_coding/codecs/legacy_encoded_audio_frame_unittest.cc @@ -39,7 +39,7 @@ enum class NetEqDecoder { class SplitBySamplesTest : public ::testing::TestWithParam { protected: - virtual void SetUp() { + void SetUp() override { decoder_type_ = GetParam(); switch (decoder_type_) { case NetEqDecoder::kDecoderPCMu: diff --git a/modules/audio_coding/codecs/opus/audio_decoder_opus_unittest.cc b/modules/audio_coding/codecs/opus/audio_decoder_opus_unittest.cc index 56b846f8cf..8c6635f0fd 100644 --- a/modules/audio_coding/codecs/opus/audio_decoder_opus_unittest.cc +++ b/modules/audio_coding/codecs/opus/audio_decoder_opus_unittest.cc @@ -26,13 +26,14 @@ #include "api/audio_codecs/opus/audio_encoder_opus_config.h" #include "api/environment/environment.h" #include "api/environment/environment_factory.h" +#include "api/field_trials.h" #include "modules/audio_coding/codecs/opus/audio_encoder_opus.h" #include "modules/audio_coding/test/PCMFile.h" #include "rtc_base/buffer.h" #include "rtc_base/checks.h" #include "rtc_base/numerics/safe_conversions.h" #include "rtc_base/random.h" -#include "test/explicit_key_value_config.h" +#include "test/create_test_field_trials.h" #include "test/gmock.h" #include "test/gtest.h" #include "test/testsupport/file_utils.h" @@ -40,8 +41,7 @@ namespace webrtc { namespace { -using test::ExplicitKeyValueConfig; -using testing::SizeIs; +using ::testing::SizeIs; using DecodeResult = AudioDecoder::EncodedAudioFrame::DecodeResult; using ParseResult = AudioDecoder::ParseResult; @@ -328,10 +328,9 @@ TEST(AudioDecoderOpusTest, } TEST(AudioDecoderOpusTest, MonoEncoderStereoDecoderOutputsTrivialStereoPlc) { - const ExplicitKeyValueConfig trials("WebRTC-Audio-OpusGeneratePlc/Enabled/"); - EnvironmentFactory env_factory; - env_factory.Set(&trials); - const Environment env = env_factory.Create(); + const FieldTrials trials = + CreateTestFieldTrials("WebRTC-Audio-OpusGeneratePlc/Enabled/"); + const Environment env = CreateEnvironment(&trials); // Create a mono encoder. const AudioEncoderOpusConfig encoder_config = GetEncoderConfig(/*num_channels=*/1, /*dtx_enabled=*/false); @@ -407,10 +406,9 @@ TEST(AudioDecoderOpusTest, TEST(AudioDecoderOpusTest, StereoEncoderStereoDecoderOutputsNonTrivialStereoPlc) { - const ExplicitKeyValueConfig trials("WebRTC-Audio-OpusGeneratePlc/Enabled/"); - EnvironmentFactory env_factory; - env_factory.Set(&trials); - const Environment env = env_factory.Create(); + const FieldTrials trials = + CreateTestFieldTrials("WebRTC-Audio-OpusGeneratePlc/Enabled/"); + const Environment env = CreateEnvironment(&trials); // Create a stereo encoder. const AudioEncoderOpusConfig encoder_config = GetEncoderConfig(/*num_channels=*/2, /*dtx_enabled=*/false); diff --git a/modules/audio_coding/codecs/opus/audio_encoder_opus.cc b/modules/audio_coding/codecs/opus/audio_encoder_opus.cc index 8f95fed01c..85995137ef 100644 --- a/modules/audio_coding/codecs/opus/audio_encoder_opus.cc +++ b/modules/audio_coding/codecs/opus/audio_encoder_opus.cc @@ -11,6 +11,7 @@ #include "modules/audio_coding/codecs/opus/audio_encoder_opus.h" #include +#include #include #include #include @@ -37,7 +38,6 @@ #include "modules/audio_coding/audio_network_adaptor/include/audio_network_adaptor.h" #include "modules/audio_coding/codecs/opus/audio_coder_opus_common.h" #include "modules/audio_coding/codecs/opus/opus_interface.h" -#include "rtc_base/arraysize.h" #include "rtc_base/buffer.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" @@ -72,11 +72,11 @@ constexpr int kDefaultMaxPlaybackRate = 48000; // These two lists must be sorted from low to high #if WEBRTC_OPUS_SUPPORT_120MS_PTIME -constexpr int kANASupportedFrameLengths[] = {20, 40, 60, 120}; -constexpr int kOpusSupportedFrameLengths[] = {10, 20, 40, 60, 120}; +constexpr std::array kANASupportedFrameLengths = {20, 40, 60, 120}; +constexpr std::array kOpusSupportedFrameLengths = {10, 20, 40, 60, 120}; #else -constexpr int kANASupportedFrameLengths[] = {20, 40, 60}; -constexpr int kOpusSupportedFrameLengths[] = {10, 20, 40, 60}; +constexpr std::array kANASupportedFrameLengths = {20, 40, 60}; +constexpr std::array kOpusSupportedFrameLengths = {10, 20, 40, 60}; #endif // PacketLossFractionSmoother uses an exponential filter with a time constant @@ -264,9 +264,8 @@ std::optional AudioEncoderOpusImpl::SdpToConfig( ? AudioEncoderOpusConfig::ApplicationMode::kVoip : AudioEncoderOpusConfig::ApplicationMode::kAudio; - constexpr int kMinANAFrameLength = kANASupportedFrameLengths[0]; - constexpr int kMaxANAFrameLength = - kANASupportedFrameLengths[arraysize(kANASupportedFrameLengths) - 1]; + constexpr int kMinANAFrameLength = kANASupportedFrameLengths.front(); + constexpr int kMaxANAFrameLength = kANASupportedFrameLengths.back(); // For now, minptime and maxptime are only used with ANA. If ptime is outside // of this range, it will get adjusted once ANA takes hold. Ideally, we'd know @@ -383,8 +382,6 @@ AudioEncoderOpusImpl::AudioEncoderOpusImpl( const AudioNetworkAdaptorCreator& audio_network_adaptor_creator, std::unique_ptr bitrate_smoother) : payload_type_(payload_type), - use_stable_target_for_adaptation_(!env.field_trials().IsDisabled( - "WebRTC-Audio-StableTargetAdaptation")), adjust_bandwidth_( env.field_trials().IsEnabled("WebRTC-AdjustOpusBandwidth")), bitrate_changed_(true), @@ -509,31 +506,25 @@ void AudioEncoderOpusImpl::OnReceivedTargetAudioBitrate( SetTargetBitrate(target_audio_bitrate_bps); } -void AudioEncoderOpusImpl::OnReceivedUplinkBandwidth( +void AudioEncoderOpusImpl::OnReceivedUplinkBandwidthImpl( int target_audio_bitrate_bps, - std::optional bwe_period_ms, - std::optional stable_target_bitrate_bps) { + std::optional bwe_period_ms) { if (audio_network_adaptor_) { audio_network_adaptor_->SetTargetAudioBitrate(target_audio_bitrate_bps); - if (use_stable_target_for_adaptation_) { - if (stable_target_bitrate_bps) - audio_network_adaptor_->SetUplinkBandwidth(*stable_target_bitrate_bps); - } else { - // We give smoothed bitrate allocation to audio network adaptor as - // the uplink bandwidth. - // The BWE spikes should not affect the bitrate smoother more than 25%. - // To simplify the calculations we use a step response as input signal. - // The step response of an exponential filter is - // u(t) = 1 - e^(-t / time_constant). - // In order to limit the affect of a BWE spike within 25% of its value - // before - // the next BWE update, we would choose a time constant that fulfills - // 1 - e^(-bwe_period_ms / time_constant) < 0.25 - // Then 4 * bwe_period_ms is a good choice. - if (bwe_period_ms) - bitrate_smoother_->SetTimeConstantMs(*bwe_period_ms * 4); - bitrate_smoother_->AddSample(target_audio_bitrate_bps); - } + // We give smoothed bitrate allocation to audio network adaptor as + // the uplink bandwidth. + // The BWE spikes should not affect the bitrate smoother more than 25%. + // To simplify the calculations we use a step response as input signal. + // The step response of an exponential filter is + // u(t) = 1 - e^(-t / time_constant). + // In order to limit the affect of a BWE spike within 25% of its value + // before + // the next BWE update, we would choose a time constant that fulfills + // 1 - e^(-bwe_period_ms / time_constant) < 0.25 + // Then 4 * bwe_period_ms is a good choice. + if (bwe_period_ms) + bitrate_smoother_->SetTimeConstantMs(*bwe_period_ms * 4); + bitrate_smoother_->AddSample(target_audio_bitrate_bps); ApplyAudioNetworkAdaptor(); } else { @@ -554,14 +545,13 @@ void AudioEncoderOpusImpl::OnReceivedUplinkBandwidth( void AudioEncoderOpusImpl::OnReceivedUplinkBandwidth( int target_audio_bitrate_bps, std::optional bwe_period_ms) { - OnReceivedUplinkBandwidth(target_audio_bitrate_bps, bwe_period_ms, - std::nullopt); + OnReceivedUplinkBandwidthImpl(target_audio_bitrate_bps, bwe_period_ms); } void AudioEncoderOpusImpl::OnReceivedUplinkAllocation( BitrateAllocationUpdate update) { - OnReceivedUplinkBandwidth(update.target_bitrate.bps(), update.bwe_period.ms(), - update.stable_target_bitrate.bps()); + OnReceivedUplinkBandwidthImpl(update.target_bitrate.bps(), + update.bwe_period.ms()); } void AudioEncoderOpusImpl::OnReceivedRtt(int rtt_ms) { @@ -795,7 +785,7 @@ AudioEncoderOpusImpl::DefaultAudioNetworkAdaptorCreator( } void AudioEncoderOpusImpl::MaybeUpdateUplinkBandwidth() { - if (audio_network_adaptor_ && !use_stable_target_for_adaptation_) { + if (audio_network_adaptor_) { int64_t now_ms = TimeMillis(); if (!bitrate_smoother_last_update_time_ || now_ms - *bitrate_smoother_last_update_time_ >= diff --git a/modules/audio_coding/codecs/opus/audio_encoder_opus.h b/modules/audio_coding/codecs/opus/audio_encoder_opus.h index d46d2b5770..52b852b8d1 100644 --- a/modules/audio_coding/codecs/opus/audio_encoder_opus.h +++ b/modules/audio_coding/codecs/opus/audio_encoder_opus.h @@ -147,11 +147,8 @@ class AudioEncoderOpusImpl final : public AudioEncoder { void SetFrameLength(int frame_length_ms); void SetNumChannelsToEncode(size_t num_channels_to_encode); void SetProjectedPacketLossRate(float fraction); - - void OnReceivedUplinkBandwidth( - int target_audio_bitrate_bps, - std::optional bwe_period_ms, - std::optional link_capacity_allocation); + void OnReceivedUplinkBandwidthImpl(int target_audio_bitrate_bps, + std::optional bwe_period_ms); // TODO(minyue): remove "override" when we can deprecate // `AudioEncoder::SetTargetBitrate`. @@ -166,7 +163,6 @@ class AudioEncoderOpusImpl final : public AudioEncoder { AudioEncoderOpusConfig config_; const int payload_type_; - const bool use_stable_target_for_adaptation_; const bool adjust_bandwidth_; bool bitrate_changed_; // A multiplier for bitrates at 5 kbps and higher. The target bitrate diff --git a/modules/audio_coding/codecs/opus/audio_encoder_opus_unittest.cc b/modules/audio_coding/codecs/opus/audio_encoder_opus_unittest.cc index 1d777112c4..ee06128480 100644 --- a/modules/audio_coding/codecs/opus/audio_encoder_opus_unittest.cc +++ b/modules/audio_coding/codecs/opus/audio_encoder_opus_unittest.cc @@ -25,6 +25,7 @@ #include "api/audio_codecs/opus/audio_encoder_opus_config.h" #include "api/call/bitrate_allocation.h" #include "api/environment/environment_factory.h" +#include "api/field_trials.h" #include "api/field_trials_view.h" #include "api/rtp_parameters.h" #include "api/units/data_rate.h" @@ -39,14 +40,13 @@ #include "rtc_base/buffer.h" #include "rtc_base/checks.h" #include "rtc_base/fake_clock.h" -#include "test/explicit_key_value_config.h" +#include "test/create_test_field_trials.h" #include "test/gmock.h" #include "test/gtest.h" #include "test/testsupport/file_utils.h" namespace webrtc { namespace { -using test::ExplicitKeyValueConfig; using ::testing::NiceMock; using ::testing::Return; @@ -282,8 +282,7 @@ TEST_P(AudioEncoderOpusTest, TEST_P(AudioEncoderOpusTest, InvokeAudioNetworkAdaptorOnReceivedUplinkBandwidth) { - ExplicitKeyValueConfig field_trials( - "WebRTC-Audio-StableTargetAdaptation/Disabled/"); + FieldTrials field_trials = CreateTestFieldTrials(""); auto states = CreateCodec(sample_rate_hz_, 2, &field_trials); states->encoder->EnableAudioNetworkAdaptor("", nullptr); @@ -316,12 +315,10 @@ TEST_P(AudioEncoderOpusTest, BitrateAllocationUpdate update; update.target_bitrate = DataRate::BitsPerSec(30000); - update.stable_target_bitrate = DataRate::BitsPerSec(20000); update.bwe_period = TimeDelta::Millis(200); EXPECT_CALL(*states->mock_audio_network_adaptor, SetTargetAudioBitrate(update.target_bitrate.bps())); - EXPECT_CALL(*states->mock_audio_network_adaptor, - SetUplinkBandwidth(update.stable_target_bitrate.bps())); + states->encoder->OnReceivedUplinkAllocation(update); CheckEncoderRuntimeConfig(states->encoder.get(), config); @@ -503,8 +500,7 @@ TEST_P(AudioEncoderOpusTest, EmptyConfigDoesNotAffectEncoderSettings) { } TEST_P(AudioEncoderOpusTest, UpdateUplinkBandwidthInAudioNetworkAdaptor) { - ExplicitKeyValueConfig field_trials( - "WebRTC-Audio-StableTargetAdaptation/Disabled/"); + FieldTrials field_trials = CreateTestFieldTrials(""); auto states = CreateCodec(sample_rate_hz_, 2, &field_trials); states->encoder->EnableAudioNetworkAdaptor("", nullptr); const size_t opus_rate_khz = CheckedDivExact(sample_rate_hz_, 1000); diff --git a/modules/audio_coding/codecs/opus/opus_bandwidth_unittest.cc b/modules/audio_coding/codecs/opus/opus_bandwidth_unittest.cc index 12783a656d..decd1ec8a9 100644 --- a/modules/audio_coding/codecs/opus/opus_bandwidth_unittest.cc +++ b/modules/audio_coding/codecs/opus/opus_bandwidth_unittest.cc @@ -24,12 +24,13 @@ #include "api/audio_codecs/opus/audio_encoder_opus_config.h" #include "api/environment/environment.h" #include "api/environment/environment_factory.h" +#include "api/field_trials.h" #include "common_audio/include/audio_util.h" #include "common_audio/window_generator.h" #include "modules/audio_coding/codecs/opus/test/lapped_transform.h" #include "modules/audio_coding/neteq/tools/audio_loop.h" #include "rtc_base/buffer.h" -#include "test/explicit_key_value_config.h" +#include "test/create_test_field_trials.h" #include "test/gtest.h" #include "test/testsupport/file_utils.h" @@ -118,9 +119,8 @@ float EncodedPowerRatio(AudioEncoder* encoder, // TODO(ivoc): Remove this test, WebRTC-AdjustOpusBandwidth is obsolete. TEST(BandwidthAdaptationTest, BandwidthAdaptationTest) { - const Environment env = - CreateEnvironment(std::make_unique( - "WebRTC-AdjustOpusBandwidth/Enabled/")); + const Environment env = CreateEnvironment(std::make_unique( + CreateTestFieldTrials("WebRTC-AdjustOpusBandwidth/Enabled/"))); constexpr float kMaxNarrowbandRatio = 0.0035f; constexpr float kMinWidebandRatio = 0.01f; diff --git a/modules/audio_coding/codecs/opus/test/blocker_unittest.cc b/modules/audio_coding/codecs/opus/test/blocker_unittest.cc index b5a349451c..47c53fbcd0 100644 --- a/modules/audio_coding/codecs/opus/test/blocker_unittest.cc +++ b/modules/audio_coding/codecs/opus/test/blocker_unittest.cc @@ -12,10 +12,10 @@ #include #include +#include #include #include "common_audio/channel_buffer.h" -#include "rtc_base/arraysize.h" #include "test/gtest.h" namespace { @@ -271,7 +271,7 @@ TEST_F(BlockerTest, InitialDelaysAreMinimum) { CopyBlockerCallback callback; - for (size_t i = 0; i < arraysize(kChunkSize); ++i) { + for (size_t i = 0; i < std::size(kChunkSize); ++i) { std::unique_ptr window(new float[kBlockSize[i]]); for (size_t j = 0; j < kBlockSize[i]; ++j) { window[j] = 1.f; diff --git a/modules/audio_coding/codecs/red/audio_encoder_copy_red_unittest.cc b/modules/audio_coding/codecs/red/audio_encoder_copy_red_unittest.cc index cc791dde44..0349926d72 100644 --- a/modules/audio_coding/codecs/red/audio_encoder_copy_red_unittest.cc +++ b/modules/audio_coding/codecs/red/audio_encoder_copy_red_unittest.cc @@ -20,13 +20,14 @@ #include "api/array_view.h" #include "api/audio_codecs/audio_encoder.h" +#include "api/field_trials.h" #include "api/units/time_delta.h" #include "rtc_base/buffer.h" #include "rtc_base/numerics/safe_conversions.h" +#include "test/create_test_field_trials.h" #include "test/gmock.h" #include "test/gtest.h" #include "test/mock_audio_encoder.h" -#include "test/scoped_key_value_config.h" #include "test/testsupport/rtc_expect_death.h" using ::testing::_; @@ -42,15 +43,16 @@ using ::testing::SetArgPointee; namespace webrtc { namespace { -static const size_t kMaxNumSamples = 48 * 10 * 2; // 10 ms @ 48 kHz stereo. -static const size_t kRedLastHeaderLength = +const size_t kMaxNumSamples = 48 * 10 * 2; // 10 ms @ 48 kHz stereo. +const size_t kRedLastHeaderLength = 1; // 1 byte RED header for the last element. } // namespace class AudioEncoderCopyRedTest : public ::testing::Test { protected: AudioEncoderCopyRedTest() - : mock_encoder_(new MockAudioEncoder), + : field_trials_(CreateTestFieldTrials()), + mock_encoder_(new MockAudioEncoder), timestamp_(4711), sample_rate_hz_(16000), num_audio_samples_10ms(sample_rate_hz_ / 100), @@ -76,7 +78,7 @@ class AudioEncoderCopyRedTest : public ::testing::Test { timestamp_ += checked_cast(num_audio_samples_10ms); } - test::ScopedKeyValueConfig field_trials_; + FieldTrials field_trials_; MockAudioEncoder* mock_encoder_; std::unique_ptr red_; uint32_t timestamp_; @@ -207,13 +209,12 @@ TEST_F(AudioEncoderCopyRedTest, CheckPayloadSizes1) { // Checks that the correct payload sizes are populated into the redundancy // information for a redundancy level of 0. TEST_F(AudioEncoderCopyRedTest, CheckPayloadSizes0) { - test::ScopedKeyValueConfig field_trials( - field_trials_, "WebRTC-Audio-Red-For-Opus/Enabled-0/"); + field_trials_.Set("WebRTC-Audio-Red-For-Opus", "Enabled-0"); // Recreate the RED encoder to take the new field trial setting into account. AudioEncoderCopyRed::Config config; config.payload_type = red_payload_type_; config.speech_encoder = std::move(red_->ReclaimContainedEncoders()[0]); - red_.reset(new AudioEncoderCopyRed(std::move(config), field_trials)); + red_.reset(new AudioEncoderCopyRed(std::move(config), field_trials_)); // Let the mock encoder return payload sizes 1, 2, 3, ..., 10 for the sequence // of calls. @@ -233,13 +234,12 @@ TEST_F(AudioEncoderCopyRedTest, CheckPayloadSizes0) { // Checks that the correct payload sizes are populated into the redundancy // information for a redundancy level of 2. TEST_F(AudioEncoderCopyRedTest, CheckPayloadSizes2) { - test::ScopedKeyValueConfig field_trials( - field_trials_, "WebRTC-Audio-Red-For-Opus/Enabled-2/"); + field_trials_.Set("WebRTC-Audio-Red-For-Opus", "Enabled-2"); // Recreate the RED encoder to take the new field trial setting into account. AudioEncoderCopyRed::Config config; config.payload_type = red_payload_type_; config.speech_encoder = std::move(red_->ReclaimContainedEncoders()[0]); - red_.reset(new AudioEncoderCopyRed(std::move(config), field_trials)); + red_.reset(new AudioEncoderCopyRed(std::move(config), field_trials_)); // Let the mock encoder return payload sizes 1, 2, 3, ..., 10 for the sequence // of calls. @@ -275,8 +275,7 @@ TEST_F(AudioEncoderCopyRedTest, CheckPayloadSizes2) { // Checks that the correct payload sizes are populated into the redundancy // information for a redundancy level of 3. TEST_F(AudioEncoderCopyRedTest, CheckPayloadSizes3) { - test::ScopedKeyValueConfig field_trials( - field_trials_, "WebRTC-Audio-Red-For-Opus/Enabled-3/"); + field_trials_.Set("WebRTC-Audio-Red-For-Opus", "Enabled-3"); // Recreate the RED encoder to take the new field trial setting into account. AudioEncoderCopyRed::Config config; config.payload_type = red_payload_type_; @@ -489,13 +488,12 @@ TEST_F(AudioEncoderCopyRedTest, CheckRFC2198Header) { // Variant with a redundancy of 0. TEST_F(AudioEncoderCopyRedTest, CheckRFC2198Header0) { - test::ScopedKeyValueConfig field_trials( - field_trials_, "WebRTC-Audio-Red-For-Opus/Enabled-0/"); + field_trials_.Set("WebRTC-Audio-Red-For-Opus", "Enabled-0"); // Recreate the RED encoder to take the new field trial setting into account. AudioEncoderCopyRed::Config config; config.payload_type = red_payload_type_; config.speech_encoder = std::move(red_->ReclaimContainedEncoders()[0]); - red_.reset(new AudioEncoderCopyRed(std::move(config), field_trials)); + red_.reset(new AudioEncoderCopyRed(std::move(config), field_trials_)); const int primary_payload_type = red_payload_type_ + 1; AudioEncoder::EncodedInfo info; @@ -517,13 +515,12 @@ TEST_F(AudioEncoderCopyRedTest, CheckRFC2198Header0) { } // Variant with a redundancy of 2. TEST_F(AudioEncoderCopyRedTest, CheckRFC2198Header2) { - test::ScopedKeyValueConfig field_trials( - field_trials_, "WebRTC-Audio-Red-For-Opus/Enabled-2/"); + field_trials_.Set("WebRTC-Audio-Red-For-Opus", "Enabled-2"); // Recreate the RED encoder to take the new field trial setting into account. AudioEncoderCopyRed::Config config; config.payload_type = red_payload_type_; config.speech_encoder = std::move(red_->ReclaimContainedEncoders()[0]); - red_.reset(new AudioEncoderCopyRed(std::move(config), field_trials)); + red_.reset(new AudioEncoderCopyRed(std::move(config), field_trials_)); const int primary_payload_type = red_payload_type_ + 1; AudioEncoder::EncodedInfo info; @@ -649,12 +646,11 @@ TEST_F(AudioEncoderCopyRedDeathTest, WrongFrameSize) { } TEST_F(AudioEncoderCopyRedDeathTest, NullSpeechEncoder) { - test::ScopedKeyValueConfig field_trials; AudioEncoderCopyRed* red = nullptr; AudioEncoderCopyRed::Config config; config.speech_encoder = nullptr; RTC_EXPECT_DEATH( - red = new AudioEncoderCopyRed(std::move(config), field_trials), + red = new AudioEncoderCopyRed(std::move(config), field_trials_), "Speech encoder not provided."); // The delete operation is needed to avoid leak reports from memcheck. delete red; diff --git a/modules/audio_coding/neteq/audio_decoder_unittest.cc b/modules/audio_coding/neteq/audio_decoder_unittest.cc index d8b891298e..a22b0f15d6 100644 --- a/modules/audio_coding/neteq/audio_decoder_unittest.cc +++ b/modules/audio_coding/neteq/audio_decoder_unittest.cc @@ -37,7 +37,7 @@ #include "modules/audio_coding/neteq/tools/resample_input_audio_file.h" #include "rtc_base/buffer.h" #include "rtc_base/checks.h" -#include "test/explicit_key_value_config.h" +#include "test/create_test_field_trials.h" #include "test/gtest.h" #include "test/testsupport/file_utils.h" @@ -45,8 +45,6 @@ namespace webrtc { namespace { -using test::ExplicitKeyValueConfig; - constexpr int kOverheadBytesPerPacket = 50; // The absolute difference between the input and output (the first channel) is @@ -361,7 +359,7 @@ class AudioDecoderOpusTest frame_size_ = CheckedDivExact(opus_sample_rate_hz_, 100); data_length_ = 10 * frame_size_; decoder_ = new AudioDecoderOpusImpl( - ExplicitKeyValueConfig(""), opus_num_channels_, opus_sample_rate_hz_); + CreateTestFieldTrials(), opus_num_channels_, opus_sample_rate_hz_); AudioEncoderOpusConfig config; config.frame_size_ms = 10; config.sample_rate_hz = opus_sample_rate_hz_; diff --git a/modules/audio_coding/neteq/audio_multi_vector.cc b/modules/audio_coding/neteq/audio_multi_vector.cc index baad7720eb..6ba4bc37f6 100644 --- a/modules/audio_coding/neteq/audio_multi_vector.cc +++ b/modules/audio_coding/neteq/audio_multi_vector.cc @@ -13,6 +13,7 @@ #include #include #include +#include #include #include "api/array_view.h" @@ -21,23 +22,26 @@ #include "rtc_base/checks.h" namespace webrtc { - -AudioMultiVector::AudioMultiVector(size_t N) : channels_(N) { - RTC_DCHECK_GT(N, 0); - RTC_DCHECK_LE(N, kMaxNumberOfAudioChannels); - for (auto& c : channels_) { - c.reset(new AudioVector()); +namespace { +std::vector> InitializeChannelVector( + size_t num_channels, + size_t channel_size = 0u) { + RTC_DCHECK_GT(num_channels, 0u); + RTC_CHECK_LE(num_channels, kMaxNumberOfAudioChannels); + std::vector> channels(num_channels); + for (auto& c : channels) { + c = channel_size ? std::make_unique(channel_size) + : std::make_unique(); } + return channels; } +} // namespace + +AudioMultiVector::AudioMultiVector(size_t N) + : channels_(InitializeChannelVector(N)) {} AudioMultiVector::AudioMultiVector(size_t N, size_t initial_size) - : channels_(N) { - RTC_DCHECK_GT(N, 0); - RTC_DCHECK_LE(N, kMaxNumberOfAudioChannels); - for (auto& c : channels_) { - c.reset(new AudioVector(initial_size)); - } -} + : channels_(InitializeChannelVector(N, initial_size)) {} AudioMultiVector::~AudioMultiVector() = default; @@ -148,6 +152,27 @@ size_t AudioMultiVector::ReadInterleavedFromIndex(size_t start_index, return index; } +bool AudioMultiVector::ReadInterleavedFromIndex( + const size_t start_index, + InterleavedView dst) const { + RTC_DCHECK_EQ(dst.num_channels(), Channels()); + if (start_index + dst.samples_per_channel() > Size()) { + return false; + } + if (Channels() == 1) { + // Special case to avoid the nested for loop below. + return channels_[0]->CopyTo(start_index, dst.AsMono()); + } + size_t index = 0; + for (size_t i = 0; i < dst.samples_per_channel(); ++i) { + for (const auto& ch : channels_) { + dst[index] = (*ch)[i + start_index]; + ++index; + } + } + return true; +} + size_t AudioMultiVector::ReadInterleavedFromEnd(size_t length, int16_t* destination) const { length = std::min(length, Size()); // Cannot read more than Size() elements. diff --git a/modules/audio_coding/neteq/audio_multi_vector.h b/modules/audio_coding/neteq/audio_multi_vector.h index b98e870f82..486c13ab54 100644 --- a/modules/audio_coding/neteq/audio_multi_vector.h +++ b/modules/audio_coding/neteq/audio_multi_vector.h @@ -18,6 +18,7 @@ #include #include "api/array_view.h" +#include "api/audio/audio_view.h" #include "modules/audio_coding/neteq/audio_vector.h" namespace webrtc { @@ -86,6 +87,19 @@ class AudioMultiVector { size_t length, int16_t* destination) const; + // Reads `dst.samples_per_channel()` from each channel into `dst`, a total of + // `dst.size()` samples, starting from the position provided by `start_index`. + // + // If not enough samples are available to read, then *none* will be read and + // the function returns false. If enough samples could be read, the return + // value will be true. + // + // This behavior is currently different from the pointer based + // `ReadInterleaved*` methods, but intentionally so in order to simplify the + // logic at the caller site. + bool ReadInterleavedFromIndex(const size_t start_index, + InterleavedView dst) const; + // Like ReadInterleaved() above, but reads from the end instead of from // the beginning. size_t ReadInterleavedFromEnd(size_t length, int16_t* destination) const; @@ -129,7 +143,7 @@ class AudioMultiVector { AudioVector& operator[](size_t index); protected: - std::vector> channels_; + const std::vector> channels_; }; } // namespace webrtc diff --git a/modules/audio_coding/neteq/audio_multi_vector_unittest.cc b/modules/audio_coding/neteq/audio_multi_vector_unittest.cc index 61938476ee..a7bc4ea323 100644 --- a/modules/audio_coding/neteq/audio_multi_vector_unittest.cc +++ b/modules/audio_coding/neteq/audio_multi_vector_unittest.cc @@ -14,8 +14,10 @@ #include #include +#include #include +#include "api/audio/audio_view.h" #include "modules/audio_coding/neteq/audio_vector.h" #include "rtc_base/numerics/safe_conversions.h" #include "test/gtest.h" @@ -36,9 +38,9 @@ class AudioMultiVectorTest : public ::testing::TestWithParam { : num_channels_(GetParam()), // Get the test parameter. array_interleaved_(num_channels_ * array_length()) {} - ~AudioMultiVectorTest() = default; + ~AudioMultiVectorTest() override = default; - virtual void SetUp() { + void SetUp() override { // Populate test arrays. for (size_t i = 0; i < array_length(); ++i) { array_[i] = static_cast(i); @@ -187,21 +189,37 @@ TEST_P(AudioMultiVectorTest, Zeros) { TEST_P(AudioMultiVectorTest, ReadInterleaved) { AudioMultiVector vec(num_channels_); vec.PushBackInterleaved(array_interleaved_); - int16_t* output = new int16_t[array_interleaved_.size()]; + std::unique_ptr output(new int16_t[array_interleaved_.size()]); // Read 5 samples. size_t read_samples = 5; EXPECT_EQ(num_channels_ * read_samples, - vec.ReadInterleaved(read_samples, output)); - EXPECT_EQ(0, memcmp(array_interleaved_.data(), output, + vec.ReadInterleaved(read_samples, output.get())); + EXPECT_EQ(0, memcmp(array_interleaved_.data(), output.get(), read_samples * sizeof(int16_t))); // Read too many samples. Expect to get all samples from the vector. EXPECT_EQ(array_interleaved_.size(), - vec.ReadInterleaved(array_length() + 1, output)); - EXPECT_EQ(0, memcmp(array_interleaved_.data(), output, + vec.ReadInterleaved(array_length() + 1, output.get())); + EXPECT_EQ(0, memcmp(array_interleaved_.data(), output.get(), read_samples * sizeof(int16_t))); +} - delete[] output; +TEST_P(AudioMultiVectorTest, ReadInterleavedView) { + AudioMultiVector vec(num_channels_); + vec.PushBackInterleaved(array_interleaved_); + + // Read 5 samples. + size_t samples_per_channel = 5; + ASSERT_GT(array_length(), samples_per_channel); + std::unique_ptr buffer(new int16_t[array_interleaved_.size()]); + InterleavedView view(buffer.get(), samples_per_channel, + num_channels_); + EXPECT_TRUE(vec.ReadInterleavedFromIndex(0u, view)); + EXPECT_EQ(0, memcmp(array_interleaved_.data(), &view[0], + view.size() * sizeof(int16_t))); + // Trying to read too much should result in failure. + // Attempt to read 5 samples when only 4 can be read. + EXPECT_FALSE(vec.ReadInterleavedFromIndex(vec.Size() - 4u, view)); } // Test the PopFront method. diff --git a/modules/audio_coding/neteq/audio_vector.cc b/modules/audio_coding/neteq/audio_vector.cc index afbd6d4e41..096c8c483f 100644 --- a/modules/audio_coding/neteq/audio_vector.cc +++ b/modules/audio_coding/neteq/audio_vector.cc @@ -16,6 +16,7 @@ #include #include +#include "api/audio/audio_view.h" #include "rtc_base/checks.h" namespace webrtc { @@ -62,6 +63,24 @@ void AudioVector::CopyTo(size_t length, } } +bool AudioVector::CopyTo(size_t position, MonoView dst) const { + if ((Size() - position) < dst.size()) { + return false; + } + const size_t copy_index = (begin_index_ + position) % capacity_; + const size_t first_chunk_length = + std::min(dst.size(), capacity_ - copy_index); + auto first_chunk = dst.subview(0, first_chunk_length); + CopySamples(first_chunk, + MonoView(&array_[copy_index], first_chunk_length)); + const size_t remaining_length = dst.size() - first_chunk_length; + if (remaining_length > 0) { + auto second_chunk = dst.subview(first_chunk_length, remaining_length); + CopySamples(second_chunk, MonoView(&array_[0], remaining_length)); + } + return true; +} + void AudioVector::PushFront(const AudioVector& prepend_this) { const size_t length = prepend_this.Size(); if (length == 0) diff --git a/modules/audio_coding/neteq/audio_vector.h b/modules/audio_coding/neteq/audio_vector.h index 6b37aedf5f..b8e7d496b3 100644 --- a/modules/audio_coding/neteq/audio_vector.h +++ b/modules/audio_coding/neteq/audio_vector.h @@ -16,6 +16,7 @@ #include #include +#include "api/audio/audio_view.h" #include "rtc_base/checks.h" namespace webrtc { @@ -44,6 +45,11 @@ class AudioVector final { // Copies `length` values from `position` in this vector to `copy_to`. void CopyTo(size_t length, size_t position, int16_t* copy_to) const; + // Copies `dst.size()` samples from a given position of the vector. + // If not enough samples are available, the function will return + // false and not do any copying. + bool CopyTo(size_t position, MonoView dst) const; + // Prepends the contents of AudioVector `prepend_this` to this object. The // length of this object is increased with the length of `prepend_this`. void PushFront(const AudioVector& prepend_this); diff --git a/modules/audio_coding/neteq/audio_vector_unittest.cc b/modules/audio_coding/neteq/audio_vector_unittest.cc index 97c1b7e10e..f048594109 100644 --- a/modules/audio_coding/neteq/audio_vector_unittest.cc +++ b/modules/audio_coding/neteq/audio_vector_unittest.cc @@ -12,8 +12,10 @@ #include +#include #include +#include "api/audio/audio_view.h" #include "rtc_base/numerics/safe_conversions.h" #include "test/gtest.h" @@ -21,14 +23,16 @@ namespace webrtc { class AudioVectorTest : public ::testing::Test { protected: - virtual void SetUp() { + void SetUp() override { // Populate test array. for (size_t i = 0; i < array_length(); ++i) { array_[i] = checked_cast(i); } } - size_t array_length() const { return sizeof(array_) / sizeof(array_[0]); } + constexpr size_t array_length() const { + return sizeof(array_) / sizeof(array_[0]); + } int16_t array_[10]; }; @@ -79,6 +83,34 @@ TEST_F(AudioVectorTest, PushBackAndCopy) { EXPECT_TRUE(vec_copy.Empty()); } +TEST_F(AudioVectorTest, CopyTo) { + AudioVector vec; + vec.PushBack(array_, array_length()); + ASSERT_EQ(vec.Size(), 10u); + + std::array buffer; + MonoView view(&buffer[0], buffer.size()); + // Try to read 10 samples from position 1, which should fail. + EXPECT_FALSE(vec.CopyTo(1, view)); + // Reading 10 samples from position 0, should succeed. + EXPECT_TRUE(vec.CopyTo(0, view)); + EXPECT_EQ(view[5], 5); // sanity check. + + // Free up space at the front of the buffer. This changes + // the internal start position without reallocating memory. + vec.PopFront(2); + + std::array new_values = {20, 21}; + vec.PushBack(&new_values[0], new_values.size()); + + // Now the CopyTo() operation will need to wrap around + // the end of the internal buffer to fill the view. + EXPECT_TRUE(vec.CopyTo(0, view)); + EXPECT_EQ(view[0], 2); + EXPECT_EQ(view[8], 20); + EXPECT_EQ(view[9], 21); +} + // Test the PushBack method with another AudioVector as input argument. TEST_F(AudioVectorTest, PushBackVector) { static const size_t kLength = 10; diff --git a/modules/audio_coding/neteq/decision_logic_unittest.cc b/modules/audio_coding/neteq/decision_logic_unittest.cc index 363b45c83b..3c4924741e 100644 --- a/modules/audio_coding/neteq/decision_logic_unittest.cc +++ b/modules/audio_coding/neteq/decision_logic_unittest.cc @@ -23,7 +23,7 @@ #include "modules/audio_coding/neteq/mock/mock_buffer_level_filter.h" #include "modules/audio_coding/neteq/mock/mock_delay_manager.h" #include "modules/audio_coding/neteq/mock/mock_packet_arrival_history.h" -#include "test/explicit_key_value_config.h" +#include "test/create_test_field_trials.h" #include "test/gmock.h" #include "test/gtest.h" @@ -31,7 +31,8 @@ namespace webrtc { namespace { -using test::ExplicitKeyValueConfig; +using ::testing::_; +using ::testing::Return; constexpr int kSampleRate = 8000; constexpr int kSamplesPerMs = kSampleRate / 1000; @@ -56,9 +57,6 @@ NetEqController::NetEqStatus CreateNetEqStatus(NetEq::Mode last_mode, return status; } -using ::testing::_; -using ::testing::Return; - } // namespace class DecisionLogicTest : public ::testing::Test { @@ -70,7 +68,7 @@ class DecisionLogicTest : public ::testing::Test { config.max_packets_in_buffer = 200; config.base_min_delay_ms = 0; auto delay_manager = std::make_unique( - DelayManager::Config(ExplicitKeyValueConfig("")), config.tick_timer); + DelayManager::Config(CreateTestFieldTrials()), config.tick_timer); mock_delay_manager_ = delay_manager.get(); auto buffer_level_filter = std::make_unique(); mock_buffer_level_filter_ = buffer_level_filter.get(); diff --git a/modules/audio_coding/neteq/delay_manager_unittest.cc b/modules/audio_coding/neteq/delay_manager_unittest.cc index 169e2ab950..79fc982ae7 100644 --- a/modules/audio_coding/neteq/delay_manager_unittest.cc +++ b/modules/audio_coding/neteq/delay_manager_unittest.cc @@ -13,18 +13,15 @@ #include "modules/audio_coding/neteq/delay_manager.h" #include "api/neteq/tick_timer.h" -#include "test/explicit_key_value_config.h" +#include "test/create_test_field_trials.h" #include "test/gtest.h" namespace webrtc { namespace { -using test::ExplicitKeyValueConfig; - TEST(DelayManagerTest, UpdateNormal) { TickTimer tick_timer; - DelayManager dm(DelayManager::Config(ExplicitKeyValueConfig("")), - &tick_timer); + DelayManager dm(DelayManager::Config(CreateTestFieldTrials()), &tick_timer); for (int i = 0; i < 50; ++i) { dm.Update(0, false); tick_timer.Increment(2); diff --git a/modules/audio_coding/neteq/dtmf_tone_generator.cc b/modules/audio_coding/neteq/dtmf_tone_generator.cc index 01f6ead3d9..b22385df2a 100644 --- a/modules/audio_coding/neteq/dtmf_tone_generator.cc +++ b/modules/audio_coding/neteq/dtmf_tone_generator.cc @@ -32,10 +32,10 @@ #include #include +#include #include "modules/audio_coding/neteq/audio_multi_vector.h" #include "modules/audio_coding/neteq/audio_vector.h" -#include "rtc_base/arraysize.h" #include "rtc_base/checks.h" namespace webrtc { @@ -137,26 +137,26 @@ int DtmfToneGenerator::Init(int fs, int event, int attenuation) { // Look up oscillator coefficient for low and high frequencies. RTC_DCHECK_LE(0, fs_index); - RTC_DCHECK_GT(arraysize(kCoeff1), fs_index); - RTC_DCHECK_GT(arraysize(kCoeff2), fs_index); + RTC_DCHECK_GT(std::size(kCoeff1), fs_index); + RTC_DCHECK_GT(std::size(kCoeff2), fs_index); RTC_DCHECK_LE(0, event); - RTC_DCHECK_GT(arraysize(kCoeff1[fs_index]), event); - RTC_DCHECK_GT(arraysize(kCoeff2[fs_index]), event); + RTC_DCHECK_GT(std::ssize(kCoeff1[fs_index]), event); + RTC_DCHECK_GT(std::ssize(kCoeff2[fs_index]), event); coeff1_ = kCoeff1[fs_index][event]; coeff2_ = kCoeff2[fs_index][event]; // Look up amplitude multiplier. RTC_DCHECK_LE(0, attenuation); - RTC_DCHECK_GT(arraysize(kAmplitude), attenuation); + RTC_DCHECK_GT(std::ssize(kAmplitude), attenuation); amplitude_ = kAmplitude[attenuation]; // Initialize sample history. RTC_DCHECK_LE(0, fs_index); - RTC_DCHECK_GT(arraysize(kInitValue1), fs_index); - RTC_DCHECK_GT(arraysize(kInitValue2), fs_index); + RTC_DCHECK_GT(std::size(kInitValue1), fs_index); + RTC_DCHECK_GT(std::size(kInitValue2), fs_index); RTC_DCHECK_LE(0, event); - RTC_DCHECK_GT(arraysize(kInitValue1[fs_index]), event); - RTC_DCHECK_GT(arraysize(kInitValue2[fs_index]), event); + RTC_DCHECK_GT(std::ssize(kInitValue1[fs_index]), event); + RTC_DCHECK_GT(std::ssize(kInitValue2[fs_index]), event); sample_history1_[0] = kInitValue1[fs_index][event]; sample_history1_[1] = 0; sample_history2_[0] = kInitValue2[fs_index][event]; diff --git a/modules/audio_coding/neteq/nack_tracker_unittest.cc b/modules/audio_coding/neteq/nack_tracker_unittest.cc index 716544a75e..f3629805b0 100644 --- a/modules/audio_coding/neteq/nack_tracker_unittest.cc +++ b/modules/audio_coding/neteq/nack_tracker_unittest.cc @@ -17,14 +17,13 @@ #include #include -#include "test/explicit_key_value_config.h" +#include "api/field_trials.h" +#include "test/create_test_field_trials.h" #include "test/gtest.h" namespace webrtc { namespace { -using test::ExplicitKeyValueConfig; - const int kSampleRateHz = 16000; const int kPacketSizeMs = 30; const uint32_t kTimestampIncrement = 480; // 30 ms. @@ -57,7 +56,7 @@ bool IsNackListCorrect(const std::vector& nack_list, } // namespace TEST(NackTrackerTest, EmptyListWhenNoPacketLoss) { - ExplicitKeyValueConfig field_trials(""); + FieldTrials field_trials = CreateTestFieldTrials(); NackTracker nack(field_trials); nack.UpdateSampleRate(kSampleRateHz); @@ -76,7 +75,7 @@ TEST(NackTrackerTest, EmptyListWhenNoPacketLoss) { } TEST(NackTrackerTest, LatePacketsMovedToNackThenNackListDoesNotChange) { - ExplicitKeyValueConfig field_trials(""); + FieldTrials field_trials = CreateTestFieldTrials(); const uint16_t kSequenceNumberLostPackets[] = {2, 3, 4, 5, 6, 7, 8, 9}; static const int kNumAllLostPackets = sizeof(kSequenceNumberLostPackets) / sizeof(kSequenceNumberLostPackets[0]); @@ -124,7 +123,7 @@ TEST(NackTrackerTest, LatePacketsMovedToNackThenNackListDoesNotChange) { } TEST(NackTrackerTest, ArrivedPacketsAreRemovedFromNackList) { - ExplicitKeyValueConfig field_trials(""); + FieldTrials field_trials = CreateTestFieldTrials(); const uint16_t kSequenceNumberLostPackets[] = {2, 3, 4, 5, 6, 7, 8, 9}; static const int kNumAllLostPackets = sizeof(kSequenceNumberLostPackets) / sizeof(kSequenceNumberLostPackets[0]); @@ -186,7 +185,7 @@ TEST(NackTrackerTest, ArrivedPacketsAreRemovedFromNackList) { // Assess if estimation of timestamps and time-to-play is correct. Introduce all // combinations that timestamps and sequence numbers might have wrap around. TEST(NackTrackerTest, EstimateTimestampAndTimeToPlay) { - ExplicitKeyValueConfig field_trials(""); + FieldTrials field_trials = CreateTestFieldTrials(); const uint16_t kLostPackets[] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; static const int kNumAllLostPackets = @@ -250,7 +249,7 @@ TEST(NackTrackerTest, EstimateTimestampAndTimeToPlay) { TEST(NackTrackerTest, MissingPacketsPriorToLastDecodedRtpShouldNotBeInNackList) { - ExplicitKeyValueConfig field_trials(""); + FieldTrials field_trials = CreateTestFieldTrials(); for (int m = 0; m < 2; ++m) { uint16_t seq_num_offset = (m == 0) ? 0 : 65531; // Wrap around if `m` is 1. NackTracker nack(field_trials); @@ -304,7 +303,7 @@ TEST(NackTrackerTest, } TEST(NackTrackerTest, Reset) { - ExplicitKeyValueConfig field_trials(""); + FieldTrials field_trials = CreateTestFieldTrials(); NackTracker nack(field_trials); nack.UpdateSampleRate(kSampleRateHz); @@ -329,7 +328,7 @@ TEST(NackTrackerTest, Reset) { } TEST(NackTrackerTest, ListSizeAppliedFromBeginning) { - ExplicitKeyValueConfig field_trials(""); + FieldTrials field_trials = CreateTestFieldTrials(); const size_t kNackListSize = 10; for (int m = 0; m < 2; ++m) { uint16_t seq_num_offset = (m == 0) ? 0 : 65525; // Wrap around if `m` is 1. @@ -354,7 +353,7 @@ TEST(NackTrackerTest, ListSizeAppliedFromBeginning) { } TEST(NackTrackerTest, ChangeOfListSizeAppliedAndOldElementsRemoved) { - ExplicitKeyValueConfig field_trials(""); + FieldTrials field_trials = CreateTestFieldTrials(); const size_t kNackListSize = 10; for (int m = 0; m < 2; ++m) { uint16_t seq_num_offset = (m == 0) ? 0 : 65525; // Wrap around if `m` is 1. @@ -410,7 +409,7 @@ TEST(NackTrackerTest, ChangeOfListSizeAppliedAndOldElementsRemoved) { } TEST(NackTrackerTest, RoudTripTimeIsApplied) { - ExplicitKeyValueConfig field_trials(""); + FieldTrials field_trials = CreateTestFieldTrials(); const int kNackListSize = 200; NackTracker nack(field_trials); nack.UpdateSampleRate(kSampleRateHz); @@ -442,7 +441,7 @@ TEST(NackTrackerTest, RoudTripTimeIsApplied) { // Set never_nack_multiple_times to true with a field trial and verify that // packets are not nacked multiple times. TEST(NackTrackerTest, DoNotNackMultipleTimes) { - ExplicitKeyValueConfig field_trials( + FieldTrials field_trials = CreateTestFieldTrials( "WebRTC-Audio-NetEqNackTrackerConfig/" "packet_loss_forget_factor:0.996,ms_per_loss_percent:20," "never_nack_multiple_times:true/"); @@ -473,7 +472,7 @@ TEST(NackTrackerTest, DoNotNackMultipleTimes) { // Test if estimated packet loss rate is correct. TEST(NackTrackerTest, PacketLossRateCorrect) { - ExplicitKeyValueConfig field_trials(""); + FieldTrials field_trials = CreateTestFieldTrials(); const int kNackListSize = 200; NackTracker nack(field_trials); nack.UpdateSampleRate(kSampleRateHz); @@ -500,7 +499,7 @@ TEST(NackTrackerTest, PacketLossRateCorrect) { } TEST(NackTrackerTest, DoNotNackAfterDtx) { - ExplicitKeyValueConfig field_trials(""); + FieldTrials field_trials = CreateTestFieldTrials(); const int kNackListSize = 200; NackTracker nack(field_trials); nack.UpdateSampleRate(kSampleRateHz); @@ -516,7 +515,7 @@ TEST(NackTrackerTest, DoNotNackAfterDtx) { } TEST(NackTrackerTest, DoNotNackIfLossRateIsTooHigh) { - ExplicitKeyValueConfig field_trials( + FieldTrials field_trials = CreateTestFieldTrials( "WebRTC-Audio-NetEqNackTrackerConfig/max_loss_rate:0.4/"); const int kNackListSize = 200; NackTracker nack(field_trials); @@ -541,7 +540,7 @@ TEST(NackTrackerTest, DoNotNackIfLossRateIsTooHigh) { } TEST(NackTrackerTest, OnlyNackIfRttIsValid) { - ExplicitKeyValueConfig field_trials( + FieldTrials field_trials = CreateTestFieldTrials( "WebRTC-Audio-NetEqNackTrackerConfig/require_valid_rtt:true/"); const int kNackListSize = 200; NackTracker nack(field_trials); diff --git a/modules/audio_coding/neteq/neteq_decoder_plc_unittest.cc b/modules/audio_coding/neteq/neteq_decoder_plc_unittest.cc index 6417cf45e7..edd57a079a 100644 --- a/modules/audio_coding/neteq/neteq_decoder_plc_unittest.cc +++ b/modules/audio_coding/neteq/neteq_decoder_plc_unittest.cc @@ -176,7 +176,7 @@ class AudioChecksumWithOutput : public AudioChecksum { public: explicit AudioChecksumWithOutput(std::string* output_str) : output_str_(*output_str) {} - ~AudioChecksumWithOutput() { output_str_ = Finish(); } + ~AudioChecksumWithOutput() override { output_str_ = Finish(); } private: std::string& output_str_; diff --git a/modules/audio_coding/neteq/neteq_impl.cc b/modules/audio_coding/neteq/neteq_impl.cc index 4141b76868..e1de77c906 100644 --- a/modules/audio_coding/neteq/neteq_impl.cc +++ b/modules/audio_coding/neteq/neteq_impl.cc @@ -750,6 +750,11 @@ int NetEqImpl::GetAudioInternal(AudioFrame* audio_frame, last_decoded_packet_infos_.clear(); tick_timer_->Increment(); + // Sanity check - should already be taken care of when setting + // output_size_samples_. + RTC_DCHECK_LE(output_size_samples_ * sync_buffer_->Channels(), + AudioFrame::kMaxDataSizeSamples); + // Check for muted state. if (enable_muted_state_ && expand_->Muted() && packet_buffer_->Empty()) { RTC_DCHECK_EQ(last_mode_, Mode::kExpand); @@ -757,14 +762,6 @@ int NetEqImpl::GetAudioInternal(AudioFrame* audio_frame, RTC_DCHECK(audio_frame->muted()); // Reset() should mute the frame. playout_timestamp_ += static_cast(output_size_samples_); audio_frame->sample_rate_hz_ = fs_hz_; - // Make sure the total number of samples fits in the AudioFrame. - if (output_size_samples_ * sync_buffer_->Channels() > - AudioFrame::kMaxDataSizeSamples) { - // TODO(tommi): Remove this check. This should no longer happen - // after stricter checks were added to SetSampleRateAndChannels(). - RTC_DCHECK_NOTREACHED(); - return kSampleUnderrun; - } audio_frame->samples_per_channel_ = output_size_samples_; audio_frame->timestamp_ = first_packet_ @@ -886,23 +883,12 @@ int NetEqImpl::GetAudioInternal(AudioFrame* audio_frame, sync_buffer_->PushBack(*algorithm_buffer_); // Extract data from `sync_buffer_` to `output`. - size_t num_output_samples_per_channel = output_size_samples_; - size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels(); - if (num_output_samples > AudioFrame::kMaxDataSizeSamples) { - // TODO(tommi): Remove this check. This should no longer happen - // after stricter checks were added to SetSampleRateAndChannels(). - RTC_DCHECK_NOTREACHED(); - RTC_LOG(LS_WARNING) << "Output array is too short. " - << AudioFrame::kMaxDataSizeSamples << " < " - << output_size_samples_ << " * " - << sync_buffer_->Channels(); - num_output_samples = AudioFrame::kMaxDataSizeSamples; - num_output_samples_per_channel = - AudioFrame::kMaxDataSizeSamples / sync_buffer_->Channels(); - } - sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel, - audio_frame); - audio_frame->sample_rate_hz_ = fs_hz_; + audio_frame->ResetWithoutMuting(); + audio_frame->SetSampleRateAndChannelSize(fs_hz_); + InterleavedView view = + audio_frame->mutable_data(output_size_samples_, sync_buffer_->Channels()); + bool got_audio = sync_buffer_->GetNextAudioInterleaved(view); + // TODO(bugs.webrtc.org/10757): // We don't have the ability to properly track individual packets once their // audio samples have entered `sync_buffer_`. So for now, treat it as if @@ -920,7 +906,8 @@ int NetEqImpl::GetAudioInternal(AudioFrame* audio_frame, sync_buffer_->set_next_index(sync_buffer_->next_index() - missing_lookahead_samples); } - if (audio_frame->samples_per_channel_ != output_size_samples_) { + + if (!got_audio) { RTC_LOG(LS_ERROR) << "audio_frame->samples_per_channel_ (" << audio_frame->samples_per_channel_ << ") != output_size_samples_ (" << output_size_samples_ diff --git a/modules/audio_coding/neteq/neteq_impl.h b/modules/audio_coding/neteq/neteq_impl.h index 2a5b4acdc0..150a18584b 100644 --- a/modules/audio_coding/neteq/neteq_impl.h +++ b/modules/audio_coding/neteq/neteq_impl.h @@ -64,7 +64,7 @@ struct DtmfEvent; struct ExpandFactory; struct PreemptiveExpandFactory; -class NetEqImpl : public webrtc::NetEq { +class NetEqImpl : public NetEq { public: enum class OutputType { kNormalSpeech, diff --git a/modules/audio_coding/neteq/neteq_impl_unittest.cc b/modules/audio_coding/neteq/neteq_impl_unittest.cc index bc9e84ae24..a336e4cb2a 100644 --- a/modules/audio_coding/neteq/neteq_impl_unittest.cc +++ b/modules/audio_coding/neteq/neteq_impl_unittest.cc @@ -173,7 +173,7 @@ class NetEqImplTest : public ::testing::Test { use_mock_payload_splitter_ = false; } - virtual ~NetEqImplTest() { + ~NetEqImplTest() override { if (use_mock_decoder_database_) { EXPECT_CALL(*mock_decoder_database_, Die()).Times(1); } @@ -1790,7 +1790,7 @@ class Decoder120ms : public AudioDecoder { class NetEqImplTest120ms : public NetEqImplTest { protected: NetEqImplTest120ms() : NetEqImplTest() {} - virtual ~NetEqImplTest120ms() {} + ~NetEqImplTest120ms() override {} void CreateInstanceNoMocks() { UseNoMocks(); diff --git a/modules/audio_coding/neteq/neteq_stereo_unittest.cc b/modules/audio_coding/neteq/neteq_stereo_unittest.cc index 6cab630474..bdb0cfea23 100644 --- a/modules/audio_coding/neteq/neteq_stereo_unittest.cc +++ b/modules/audio_coding/neteq/neteq_stereo_unittest.cc @@ -91,14 +91,14 @@ class NetEqStereoTest : public ::testing::TestWithParam { new uint8_t[frame_size_samples_ * 2 * num_channels_]; } - ~NetEqStereoTest() { + ~NetEqStereoTest() override { delete[] input_; delete[] encoded_; delete[] input_multi_channel_; delete[] encoded_multi_channel_; } - virtual void SetUp() { + void SetUp() override { const std::string file_name = test::ResourcePath("audio_coding/testfile32kHz", "pcm"); input_file_.reset(new test::InputAudioFile(file_name)); @@ -110,7 +110,7 @@ class NetEqStereoTest : public ::testing::TestWithParam { SdpAudioFormat("l16", sample_rate_hz_, num_channels_))); } - virtual void TearDown() {} + void TearDown() override {} int GetNewPackets() { if (!input_file_->Read(frame_size_samples_, input_)) { @@ -266,7 +266,7 @@ class NetEqStereoTestPositiveDrift : public NetEqStereoTest { // TODO(hlundin): Mock the decision making instead to control the modes. last_arrival_time_ = -100; } - virtual int GetArrivalTime(int send_time) { + int GetArrivalTime(int send_time) override { int arrival_time = last_arrival_time_ + drift_factor * (send_time - last_send_time_); last_send_time_ = send_time; @@ -299,7 +299,7 @@ class NetEqStereoTestDelays : public NetEqStereoTest { static const int kDelay = 1000; NetEqStereoTestDelays() : NetEqStereoTest(), frame_index_(0) {} - virtual int GetArrivalTime(int send_time) { + int GetArrivalTime(int send_time) override { // Deliver immediately, unless we have a back-log. int arrival_time = std::min(last_arrival_time_, send_time); if (++frame_index_ % kDelayInterval == 0) { @@ -323,10 +323,10 @@ class NetEqStereoTestLosses : public NetEqStereoTest { static const int kLossInterval = 10; NetEqStereoTestLosses() : NetEqStereoTest(), frame_index_(0) {} - virtual bool Lost() { return (++frame_index_) % kLossInterval == 0; } + bool Lost() override { return (++frame_index_) % kLossInterval == 0; } // TODO(hlundin): NetEq is not giving bitexact results for these cases. - virtual void VerifyOutput(size_t num_samples) { + void VerifyOutput(size_t num_samples) override { for (size_t i = 0; i < num_samples; ++i) { const int16_t* output_data = output_.data(); const int16_t* output_multi_channel_data = output_multi_channel_.data(); @@ -354,7 +354,7 @@ class NetEqStereoTestSingleActiveChannelPlc : public NetEqStereoTestLosses { protected: NetEqStereoTestSingleActiveChannelPlc() : NetEqStereoTestLosses() {} - virtual void MakeMultiChannelInput() override { + void MakeMultiChannelInput() override { // Create a multi-channel input by copying the mono channel from file to the // first channel, and setting the others to zero. memset(input_multi_channel_, 0, @@ -364,7 +364,7 @@ class NetEqStereoTestSingleActiveChannelPlc : public NetEqStereoTestLosses { } } - virtual void VerifyOutput(size_t num_samples) override { + void VerifyOutput(size_t num_samples) override { // Simply verify that all samples in channels other than the first are zero. const int16_t* output_multi_channel_data = output_multi_channel_.data(); for (size_t i = 0; i < num_samples; ++i) { diff --git a/modules/audio_coding/neteq/sync_buffer.cc b/modules/audio_coding/neteq/sync_buffer.cc index 26fa54f2a6..21a3bd77f6 100644 --- a/modules/audio_coding/neteq/sync_buffer.cc +++ b/modules/audio_coding/neteq/sync_buffer.cc @@ -14,7 +14,7 @@ #include #include -#include "api/audio/audio_frame.h" +#include "api/audio/audio_view.h" #include "modules/audio_coding/neteq/audio_multi_vector.h" #include "rtc_base/buffer.h" #include "rtc_base/checks.h" @@ -86,17 +86,13 @@ void SyncBuffer::ReplaceAtIndex(const AudioMultiVector& insert_this, ReplaceAtIndex(insert_this, insert_this.Size(), position); } -void SyncBuffer::GetNextAudioInterleaved(size_t requested_len, - AudioFrame* output) { - RTC_DCHECK(output); - const size_t samples_to_read = std::min(FutureLength(), requested_len); - output->ResetWithoutMuting(); - const size_t tot_samples_read = ReadInterleavedFromIndex( - next_index_, samples_to_read, output->mutable_data()); - const size_t samples_read_per_channel = tot_samples_read / Channels(); - next_index_ += samples_read_per_channel; - output->num_channels_ = Channels(); - output->samples_per_channel_ = samples_read_per_channel; +bool SyncBuffer::GetNextAudioInterleaved(InterleavedView audio) { + RTC_DCHECK_EQ(audio.num_channels(), Channels()); + bool read = ReadInterleavedFromIndex(next_index_, audio); + if (read) { + next_index_ += audio.samples_per_channel(); + } + return read; } void SyncBuffer::IncreaseEndTimestamp(uint32_t increment) { diff --git a/modules/audio_coding/neteq/sync_buffer.h b/modules/audio_coding/neteq/sync_buffer.h index 7374fdd685..855cbbf86b 100644 --- a/modules/audio_coding/neteq/sync_buffer.h +++ b/modules/audio_coding/neteq/sync_buffer.h @@ -16,7 +16,7 @@ #include -#include "api/audio/audio_frame.h" +#include "api/audio/audio_view.h" #include "modules/audio_coding/neteq/audio_multi_vector.h" #include "modules/audio_coding/neteq/audio_vector.h" #include "rtc_base/buffer.h" @@ -76,11 +76,17 @@ class SyncBuffer final : public AudioMultiVector { // the same constraints as above, that the SyncBuffer is not extended). void ReplaceAtIndex(const AudioMultiVector& insert_this, size_t position); - // Reads `requested_len` samples from each channel and writes them interleaved - // into `output`. The `next_index_` is updated to point to the sample to read - // next time. The AudioFrame `output` is first reset, and the `data_`, - // `num_channels_`, and `samples_per_channel_` fields are updated. - void GetNextAudioInterleaved(size_t requested_len, AudioFrame* output); + // If enough data is available, reads `audio.samples_per_channel()` samples + // from each channel into `audio` and return true. + // If not enough data is available, the function returns false and no data + // will have been read. + // + // When successful, the internal `next_index_` position is updated to point + // to the samples to read next time around. + // + // Note: `audio` must be configured to have the same number of channels as + // `Channels()` and expected to meet the size limitations of AudioFrame. + bool GetNextAudioInterleaved(InterleavedView audio); // Adds `increment` to `end_timestamp_`. void IncreaseEndTimestamp(uint32_t increment); diff --git a/modules/audio_coding/neteq/sync_buffer_unittest.cc b/modules/audio_coding/neteq/sync_buffer_unittest.cc index d2137e3f7b..c0808a51c9 100644 --- a/modules/audio_coding/neteq/sync_buffer_unittest.cc +++ b/modules/audio_coding/neteq/sync_buffer_unittest.cc @@ -146,22 +146,21 @@ TEST(SyncBuffer, GetNextAudioInterleaved) { // Read to interleaved output. Read in two batches, where each read operation // should automatically update the `net_index_` in the SyncBuffer. - // Note that `samples_read` is the number of samples read from each channel. - // That is, the number of samples written to `output` is - // `samples_read` * `kChannels`. + // `samples` is the number of samples read from each channel. + // That is, the number of samples written to `output` is `samples` * + // `kChannels`. + const size_t samples = kNewLen / 2; AudioFrame output1; - sync_buffer.GetNextAudioInterleaved(kNewLen / 2, &output1); - EXPECT_EQ(kChannels, output1.num_channels_); - EXPECT_EQ(kNewLen / 2, output1.samples_per_channel_); + EXPECT_TRUE(sync_buffer.GetNextAudioInterleaved( + output1.mutable_data(samples, kChannels))); AudioFrame output2; - sync_buffer.GetNextAudioInterleaved(kNewLen / 2, &output2); - EXPECT_EQ(kChannels, output2.num_channels_); - EXPECT_EQ(kNewLen / 2, output2.samples_per_channel_); + EXPECT_TRUE(sync_buffer.GetNextAudioInterleaved( + output2.mutable_data(samples, kChannels))); // Verify the data. const int16_t* output_ptr = output1.data(); - for (size_t i = 0; i < kNewLen / 2; ++i) { + for (size_t i = 0; i < samples; ++i) { for (size_t channel = 0; channel < kChannels; ++channel) { EXPECT_EQ(new_data[channel][i], *output_ptr); ++output_ptr; diff --git a/modules/audio_coding/neteq/test/neteq_decoding_test.cc b/modules/audio_coding/neteq/test/neteq_decoding_test.cc index eb0b196499..e44a387b10 100644 --- a/modules/audio_coding/neteq/test/neteq_decoding_test.cc +++ b/modules/audio_coding/neteq/test/neteq_decoding_test.cc @@ -37,7 +37,7 @@ #ifdef WEBRTC_ANDROID_PLATFORM_BUILD #include "external/webrtc/webrtc/modules/audio_coding/neteq/neteq_unittest.pb.h" #else -#include "modules/audio_coding/neteq/neteq_unittest.pb.h" // IWYU pragma: keep +#include "modules/audio_coding/neteq/neteq_unittest.pb.h" #endif #endif diff --git a/modules/audio_coding/neteq/test/neteq_opus_quality_test.cc b/modules/audio_coding/neteq/test/neteq_opus_quality_test.cc index 276adc106e..a469ea0249 100644 --- a/modules/audio_coding/neteq/test/neteq_opus_quality_test.cc +++ b/modules/audio_coding/neteq/test/neteq_opus_quality_test.cc @@ -49,8 +49,8 @@ namespace webrtc { namespace test { namespace { -static const int kOpusBlockDurationMs = 20; -static const int kOpusSamplingKhz = 48; +const int kOpusBlockDurationMs = 20; +const int kOpusSamplingKhz = 48; } // namespace class NetEqOpusQualityTest : public NetEqQualityTest { diff --git a/modules/audio_coding/neteq/test/neteq_pcm16b_quality_test.cc b/modules/audio_coding/neteq/test/neteq_pcm16b_quality_test.cc index 6cf73f6bda..9f1fffaa9f 100644 --- a/modules/audio_coding/neteq/test/neteq_pcm16b_quality_test.cc +++ b/modules/audio_coding/neteq/test/neteq_pcm16b_quality_test.cc @@ -31,8 +31,8 @@ using ::testing::InitGoogleTest; namespace webrtc { namespace test { namespace { -static const int kInputSampleRateKhz = 48; -static const int kOutputSampleRateKhz = 48; +const int kInputSampleRateKhz = 48; +const int kOutputSampleRateKhz = 48; } // namespace class NetEqPcm16bQualityTest : public NetEqQualityTest { diff --git a/modules/audio_coding/neteq/test/neteq_pcmu_quality_test.cc b/modules/audio_coding/neteq/test/neteq_pcmu_quality_test.cc index 2de5170c26..c365d839cb 100644 --- a/modules/audio_coding/neteq/test/neteq_pcmu_quality_test.cc +++ b/modules/audio_coding/neteq/test/neteq_pcmu_quality_test.cc @@ -31,8 +31,8 @@ using ::testing::InitGoogleTest; namespace webrtc { namespace test { namespace { -static const int kInputSampleRateKhz = 8; -static const int kOutputSampleRateKhz = 8; +const int kInputSampleRateKhz = 8; +const int kOutputSampleRateKhz = 8; } // namespace class NetEqPcmuQualityTest : public NetEqQualityTest { diff --git a/modules/audio_coding/neteq/time_stretch_unittest.cc b/modules/audio_coding/neteq/time_stretch_unittest.cc index 029ab887e9..539312ab17 100644 --- a/modules/audio_coding/neteq/time_stretch_unittest.cc +++ b/modules/audio_coding/neteq/time_stretch_unittest.cc @@ -29,7 +29,7 @@ namespace webrtc { namespace { const size_t kNumChannels = 1; -} +} // namespace TEST(TimeStretch, CreateAndDestroy) { const int kSampleRate = 8000; diff --git a/modules/audio_coding/neteq/tools/neteq_rtpplay.cc b/modules/audio_coding/neteq/tools/neteq_rtpplay.cc index a05e1b360e..da2df22d64 100644 --- a/modules/audio_coding/neteq/tools/neteq_rtpplay.cc +++ b/modules/audio_coding/neteq/tools/neteq_rtpplay.cc @@ -27,7 +27,6 @@ #include "modules/audio_coding/neteq/tools/neteq_test_factory.h" #include "rtc_base/checks.h" #include "rtc_base/strings/string_builder.h" -#include "system_wrappers/include/field_trial.h" using TestConfig = webrtc::test::NetEqTestFactory::Config; @@ -191,7 +190,7 @@ bool ParseSsrc(absl::string_view str, uint32_t* ssrc) { return true; } -static bool ValidateExtensionId(int value) { +bool ValidateExtensionId(int value) { if (value > 0 && value <= 255) // Value is ok. return true; printf("Extension ID must be between 1 and 255, not %d\n", @@ -352,13 +351,8 @@ int main(int argc, char* argv[]) { RTC_CHECK(ValidateExtensionId(absl::GetFlag(FLAGS_video_content_type))); RTC_CHECK(ValidateExtensionId(absl::GetFlag(FLAGS_video_timing))); - // Make force_fieldtrials persistent string during entire program live as - // absl::GetFlag creates temporary string and c_str() will point to - // deallocated string. - const std::string force_fieldtrials = absl::GetFlag(FLAGS_force_fieldtrials); - webrtc::field_trial::InitFieldTrialsFromString(force_fieldtrials.c_str()); - webrtc::test::NetEqTestFactory::Config config; + config.field_trial_string = absl::GetFlag(FLAGS_force_fieldtrials); config.pcmu = absl::GetFlag(FLAGS_pcmu); config.pcma = absl::GetFlag(FLAGS_pcma); config.isac = absl::GetFlag(FLAGS_isac); diff --git a/modules/audio_coding/neteq/tools/neteq_test.cc b/modules/audio_coding/neteq/tools/neteq_test.cc index 2baea86b46..cfeccfd995 100644 --- a/modules/audio_coding/neteq/tools/neteq_test.cc +++ b/modules/audio_coding/neteq/tools/neteq_test.cc @@ -17,7 +17,6 @@ #include #include #include -#include #include #include "absl/strings/string_view.h" @@ -93,9 +92,8 @@ NetEqTest::NetEqTest(const NetEq::Config& config, absl::string_view field_trials) : input_(std::move(input)), clock_(Timestamp::Millis(input_->NextEventTime().value_or(0))), - env_(CreateEnvironment( - &clock_, - FieldTrials::CreateNoGlobal(std::string(field_trials)))), + env_(CreateEnvironment(&clock_, + std::make_unique(field_trials))), neteq_( neteq_factory ? neteq_factory->Create(env_, config, std::move(decoder_factory)) diff --git a/modules/audio_coding/test/TestAllCodecs.cc b/modules/audio_coding/test/TestAllCodecs.cc index cbf04a43d0..0914f0acfe 100644 --- a/modules/audio_coding/test/TestAllCodecs.cc +++ b/modules/audio_coding/test/TestAllCodecs.cc @@ -50,7 +50,7 @@ namespace { const size_t kVariableSize = std::numeric_limits::max(); -} +} // namespace namespace webrtc { diff --git a/modules/audio_coding/test/TestRedFec.cc b/modules/audio_coding/test/TestRedFec.cc index 965eb69506..f8dce3790b 100644 --- a/modules/audio_coding/test/TestRedFec.cc +++ b/modules/audio_coding/test/TestRedFec.cc @@ -33,6 +33,7 @@ #include "api/audio_codecs/opus/audio_decoder_opus.h" #include "api/audio_codecs/opus/audio_encoder_opus.h" #include "api/environment/environment_factory.h" +#include "api/field_trials.h" #include "api/neteq/default_neteq_factory.h" #include "api/neteq/neteq.h" #include "common_audio/vad/include/vad.h" @@ -41,13 +42,15 @@ #include "modules/audio_coding/include/audio_coding_module.h" #include "modules/audio_coding/test/Channel.h" #include "rtc_base/strings/string_builder.h" +#include "test/create_test_field_trials.h" #include "test/gtest.h" #include "test/testsupport/file_utils.h" namespace webrtc { TestRedFec::TestRedFec() - : env_(CreateEnvironment(&field_trials_)), + : env_(CreateEnvironment( + std::make_unique(CreateTestFieldTrials()))), encoder_factory_(CreateAudioEncoderFactory(std::move(config), - field_trials_); + env_.field_trials()); receive_codecs.emplace( std::make_pair(red_payload_type, SdpAudioFormat("red", codec_format.clockrate_hz, 1))); diff --git a/modules/audio_coding/test/TestRedFec.h b/modules/audio_coding/test/TestRedFec.h index 112de845aa..30360073af 100644 --- a/modules/audio_coding/test/TestRedFec.h +++ b/modules/audio_coding/test/TestRedFec.h @@ -26,7 +26,6 @@ #include "modules/audio_coding/include/audio_coding_module.h" #include "modules/audio_coding/test/Channel.h" #include "modules/audio_coding/test/PCMFile.h" -#include "test/scoped_key_value_config.h" namespace webrtc { @@ -45,7 +44,6 @@ class TestRedFec final { void Run(); void OpenOutFile(int16_t testNumber); - test::ScopedKeyValueConfig field_trials_; const Environment env_; const scoped_refptr encoder_factory_; const scoped_refptr decoder_factory_; diff --git a/modules/audio_coding/test/target_delay_unittest.cc b/modules/audio_coding/test/target_delay_unittest.cc index 0b26e888c9..b437e834bb 100644 --- a/modules/audio_coding/test/target_delay_unittest.cc +++ b/modules/audio_coding/test/target_delay_unittest.cc @@ -38,9 +38,9 @@ class TargetDelayTest : public ::testing::Test { NetEq::Config(), CreateBuiltinAudioDecoderFactory())) {} - ~TargetDelayTest() {} + ~TargetDelayTest() override {} - void SetUp() { + void SetUp() override { constexpr int pltype = 108; std::map receive_codecs = { {pltype, {"L16", kSampleRateHz, 1}}}; diff --git a/modules/audio_device/BUILD.gn b/modules/audio_device/BUILD.gn index 9bf81c315f..b879e4f571 100644 --- a/modules/audio_device/BUILD.gn +++ b/modules/audio_device/BUILD.gn @@ -114,7 +114,6 @@ rtc_library("windows_core_audio_utility") { "../../api/units:time_delta", "../../rtc_base:checks", "../../rtc_base:logging", - "../../rtc_base:macromagic", "../../rtc_base:platform_thread_types", "../../rtc_base:stringutils", "../../rtc_base/win:windows_version", @@ -157,7 +156,6 @@ rtc_library("audio_device_module_from_input_and_output") { "../../api/task_queue", "../../rtc_base:checks", "../../rtc_base:logging", - "../../rtc_base:macromagic", "../../rtc_base:platform_thread", "../../rtc_base:safe_conversions", "../../rtc_base:stringutils", diff --git a/modules/audio_device/audio_device_unittest.cc b/modules/audio_device/audio_device_unittest.cc index c7b1cb3c62..11f8d64122 100644 --- a/modules/audio_device/audio_device_unittest.cc +++ b/modules/audio_device/audio_device_unittest.cc @@ -85,21 +85,21 @@ namespace { // Number of callbacks (input or output) the tests waits for before we set // an event indicating that the test was OK. -static constexpr size_t kNumCallbacks = 10; +constexpr size_t kNumCallbacks = 10; // Max amount of time we wait for an event to be set while counting callbacks. -static constexpr TimeDelta kTestTimeOut = TimeDelta::Seconds(10); +constexpr TimeDelta kTestTimeOut = TimeDelta::Seconds(10); // Average number of audio callbacks per second assuming 10ms packet size. -static constexpr size_t kNumCallbacksPerSecond = 100; +constexpr size_t kNumCallbacksPerSecond = 100; // Run the full-duplex test during this time (unit is in seconds). -static constexpr TimeDelta kFullDuplexTime = TimeDelta::Seconds(5); +constexpr TimeDelta kFullDuplexTime = TimeDelta::Seconds(5); // Length of round-trip latency measurements. Number of deteced impulses // shall be kImpulseFrequencyInHz * kMeasureLatencyTime - 1 since the // last transmitted pulse is not used. -static constexpr TimeDelta kMeasureLatencyTime = TimeDelta::Seconds(10); +constexpr TimeDelta kMeasureLatencyTime = TimeDelta::Seconds(10); // Sets the number of impulses per second in the latency test. -static constexpr size_t kImpulseFrequencyInHz = 1; +constexpr size_t kImpulseFrequencyInHz = 1; // Utilized in round-trip latency measurements to avoid capturing noise samples. -static constexpr int kImpulseThreshold = 1000; +constexpr int kImpulseThreshold = 1000; enum class TransportType { kInvalid, @@ -269,7 +269,7 @@ class LatencyAudioStream : public AudioStream { PRINTD("(%zu, %zu)", max, index_of_max); int64_t now_time = TimeMillis(); int extra_delay = IndexToMilliseconds(index_of_max, source.size()); - PRINTD("[%d]", webrtc::checked_cast(now_time - pulse_time_)); + PRINTD("[%d]", checked_cast(now_time - pulse_time_)); PRINTD("[%d]", extra_delay); // Total latency is the difference between transmit time and detection // tome plus the extra delay within the buffer in which we detected the @@ -339,7 +339,7 @@ class LatencyAudioStream : public AudioStream { class MockAudioTransport : public test::MockAudioTransport { public: explicit MockAudioTransport(TransportType type) : type_(type) {} - ~MockAudioTransport() {} + ~MockAudioTransport() override {} // Set default actions of the mock object. We are delegating to fake // implementation where the number of callbacks is counted and an event @@ -572,7 +572,7 @@ class MAYBE_AudioDeviceTest // An alternative would be for the mock to outlive audio_device. void PreTearDown() { EXPECT_EQ(0, audio_device_->Terminate()); } - virtual ~MAYBE_AudioDeviceTest() { + ~MAYBE_AudioDeviceTest() override { if (audio_device_) { EXPECT_EQ(0, audio_device_->Terminate()); } diff --git a/modules/audio_device/include/audio_device_factory.h b/modules/audio_device/include/audio_device_factory.h index 535b89fc72..398b6b08ff 100644 --- a/modules/audio_device/include/audio_device_factory.h +++ b/modules/audio_device/include/audio_device_factory.h @@ -27,7 +27,7 @@ namespace webrtc { // Example (assuming webrtc namespace): // // public: -// webrtc::scoped_refptr CreateAudioDevice() { +// scoped_refptr CreateAudioDevice() { // task_queue_factory_ = CreateDefaultTaskQueueFactory(); // // Tell COM that this thread shall live in the MTA. // com_initializer_ = std::make_unique( diff --git a/modules/audio_device/include/fake_audio_device.h b/modules/audio_device/include/fake_audio_device.h index b348483fb1..0eaa609f95 100644 --- a/modules/audio_device/include/fake_audio_device.h +++ b/modules/audio_device/include/fake_audio_device.h @@ -23,8 +23,8 @@ class FakeAudioDeviceModule // references using scoped_refptr. Current code doesn't always use refcounting // for this class. void AddRef() const override {} - webrtc::RefCountReleaseStatus Release() const override { - return webrtc::RefCountReleaseStatus::kDroppedLastRef; + RefCountReleaseStatus Release() const override { + return RefCountReleaseStatus::kDroppedLastRef; } }; diff --git a/modules/audio_device/linux/audio_device_alsa_linux.cc b/modules/audio_device/linux/audio_device_alsa_linux.cc index 5667df1aa0..e9afc683bf 100644 --- a/modules/audio_device/linux/audio_device_alsa_linux.cc +++ b/modules/audio_device/linux/audio_device_alsa_linux.cc @@ -1019,14 +1019,13 @@ int32_t AudioDeviceLinuxALSA::StartRecording() { return -1; } // RECORDING - _ptrThreadRec = webrtc::PlatformThread::SpawnJoinable( + _ptrThreadRec = PlatformThread::SpawnJoinable( [this] { while (RecThreadProcess()) { } }, "webrtc_audio_module_capture_thread", - webrtc::ThreadAttributes().SetPriority( - webrtc::ThreadPriority::kRealtime)); + ThreadAttributes().SetPriority(ThreadPriority::kRealtime)); errVal = LATE(snd_pcm_prepare)(_handleRecord); if (errVal < 0) { @@ -1137,14 +1136,13 @@ int32_t AudioDeviceLinuxALSA::StartPlayout() { } // PLAYOUT - _ptrThreadPlay = webrtc::PlatformThread::SpawnJoinable( + _ptrThreadPlay = PlatformThread::SpawnJoinable( [this] { while (PlayThreadProcess()) { } }, "webrtc_audio_module_play_thread", - webrtc::ThreadAttributes().SetPriority( - webrtc::ThreadPriority::kRealtime)); + ThreadAttributes().SetPriority(ThreadPriority::kRealtime)); int errVal = LATE(snd_pcm_prepare)(_handlePlayout); if (errVal < 0) { diff --git a/modules/audio_device/linux/audio_device_alsa_linux.h b/modules/audio_device/linux/audio_device_alsa_linux.h index dc7f544201..f40ee5a623 100644 --- a/modules/audio_device/linux/audio_device_alsa_linux.h +++ b/modules/audio_device/linux/audio_device_alsa_linux.h @@ -155,8 +155,8 @@ class AudioDeviceLinuxALSA : public AudioDeviceGeneric { Mutex mutex_; - webrtc::PlatformThread _ptrThreadRec; - webrtc::PlatformThread _ptrThreadPlay; + PlatformThread _ptrThreadRec; + PlatformThread _ptrThreadPlay; AudioMixerManagerLinuxALSA _mixerManager; diff --git a/modules/audio_device/linux/audio_device_pulse_linux.cc b/modules/audio_device/linux/audio_device_pulse_linux.cc index 7acfc5d9b9..dfdafa6517 100644 --- a/modules/audio_device/linux/audio_device_pulse_linux.cc +++ b/modules/audio_device/linux/audio_device_pulse_linux.cc @@ -160,8 +160,8 @@ AudioDeviceGeneric::InitStatus AudioDeviceLinuxPulse::Init() { // RECORDING const auto attributes = - webrtc::ThreadAttributes().SetPriority(webrtc::ThreadPriority::kRealtime); - _ptrThreadRec = webrtc::PlatformThread::SpawnJoinable( + ThreadAttributes().SetPriority(ThreadPriority::kRealtime); + _ptrThreadRec = PlatformThread::SpawnJoinable( [this] { while (RecThreadProcess()) { } @@ -169,7 +169,7 @@ AudioDeviceGeneric::InitStatus AudioDeviceLinuxPulse::Init() { "webrtc_audio_module_rec_thread", attributes); // PLAYOUT - _ptrThreadPlay = webrtc::PlatformThread::SpawnJoinable( + _ptrThreadPlay = PlatformThread::SpawnJoinable( [this] { while (PlayThreadProcess()) { } diff --git a/modules/audio_device/linux/audio_device_pulse_linux.h b/modules/audio_device/linux/audio_device_pulse_linux.h index 2ea6ebf90d..2ee327bda8 100644 --- a/modules/audio_device/linux/audio_device_pulse_linux.h +++ b/modules/audio_device/linux/audio_device_pulse_linux.h @@ -263,13 +263,13 @@ class AudioDeviceLinuxPulse : public AudioDeviceGeneric { AudioDeviceBuffer* _ptrAudioBuffer; mutable Mutex mutex_; - webrtc::Event _timeEventRec; - webrtc::Event _timeEventPlay; - webrtc::Event _recStartEvent; - webrtc::Event _playStartEvent; + Event _timeEventRec; + Event _timeEventPlay; + Event _recStartEvent; + Event _playStartEvent; - webrtc::PlatformThread _ptrThreadPlay; - webrtc::PlatformThread _ptrThreadRec; + PlatformThread _ptrThreadPlay; + PlatformThread _ptrThreadRec; AudioMixerManagerLinuxPulse _mixerManager; diff --git a/modules/audio_device/mac/audio_device_mac.cc b/modules/audio_device/mac/audio_device_mac.cc index 0d21a986f0..d077a8b185 100644 --- a/modules/audio_device/mac/audio_device_mac.cc +++ b/modules/audio_device/mac/audio_device_mac.cc @@ -19,42 +19,41 @@ #include "modules/audio_device/audio_device_config.h" #include "modules/third_party/portaudio/pa_ringbuffer.h" -#include "rtc_base/arraysize.h" #include "rtc_base/checks.h" #include "rtc_base/platform_thread.h" #include "rtc_base/system/arch.h" namespace webrtc { -#define WEBRTC_CA_RETURN_ON_ERR(expr) \ - do { \ - err = expr; \ - if (err != noErr) { \ - logCAMsg(webrtc::LS_ERROR, "Error in " #expr, (const char*)&err); \ - return -1; \ - } \ - } while (0) - -#define WEBRTC_CA_LOG_ERR(expr) \ - do { \ - err = expr; \ - if (err != noErr) { \ - logCAMsg(webrtc::LS_ERROR, "Error in " #expr, (const char*)&err); \ - } \ +#define WEBRTC_CA_RETURN_ON_ERR(expr) \ + do { \ + err = expr; \ + if (err != noErr) { \ + logCAMsg(::webrtc::LS_ERROR, "Error in " #expr, (const char*)&err); \ + return -1; \ + } \ } while (0) -#define WEBRTC_CA_LOG_WARN(expr) \ +#define WEBRTC_CA_LOG_ERR(expr) \ do { \ err = expr; \ if (err != noErr) { \ - logCAMsg(webrtc::LS_WARNING, "Error in " #expr, (const char*)&err); \ + logCAMsg(::webrtc::LS_ERROR, "Error in " #expr, (const char*)&err); \ } \ } while (0) +#define WEBRTC_CA_LOG_WARN(expr) \ + do { \ + err = expr; \ + if (err != noErr) { \ + logCAMsg(::webrtc::LS_WARNING, "Error in " #expr, (const char*)&err); \ + } \ + } while (0) + enum { MaxNumberDevices = 64 }; // CoreAudio errors are best interpreted as four character strings. -void AudioDeviceMac::logCAMsg(const webrtc::LoggingSeverity sev, +void AudioDeviceMac::logCAMsg(const LoggingSeverity sev, const char* msg, const char* err) { RTC_DCHECK(msg != NULL); @@ -62,14 +61,14 @@ void AudioDeviceMac::logCAMsg(const webrtc::LoggingSeverity sev, #ifdef WEBRTC_ARCH_BIG_ENDIAN switch (sev) { - case webrtc::LS_ERROR: + case LS_ERROR: RTC_LOG(LS_ERROR) << msg << ": " << err[0] << err[1] << err[2] << err[3]; break; - case webrtc::LS_WARNING: + case LS_WARNING: RTC_LOG(LS_WARNING) << msg << ": " << err[0] << err[1] << err[2] << err[3]; break; - case webrtc::LS_VERBOSE: + case LS_VERBOSE: RTC_LOG(LS_VERBOSE) << msg << ": " << err[0] << err[1] << err[2] << err[3]; break; @@ -79,14 +78,14 @@ void AudioDeviceMac::logCAMsg(const webrtc::LoggingSeverity sev, #else // We need to flip the characters in this case. switch (sev) { - case webrtc::LS_ERROR: + case LS_ERROR: RTC_LOG(LS_ERROR) << msg << ": " << err[3] << err[2] << err[1] << err[0]; break; - case webrtc::LS_WARNING: + case LS_WARNING: RTC_LOG(LS_WARNING) << msg << ": " << err[3] << err[2] << err[1] << err[0]; break; - case webrtc::LS_VERBOSE: + case LS_VERBOSE: RTC_LOG(LS_VERBOSE) << msg << ": " << err[3] << err[2] << err[1] << err[0]; break; @@ -279,7 +278,7 @@ AudioDeviceGeneric::InitStatus AudioDeviceMac::Init() { // main thread to issue notifications. AudioObjectPropertyAddress propertyAddress = { kAudioHardwarePropertyRunLoop, kAudioObjectPropertyScopeGlobal, - kAudioObjectPropertyElementMaster}; + kAudioObjectPropertyElementMain}; CFRunLoopRef runLoop = NULL; UInt32 size = sizeof(CFRunLoopRef); int aoerr = AudioObjectSetPropertyData( @@ -340,14 +339,13 @@ int32_t AudioDeviceMac::Terminate() { AudioObjectPropertyAddress propertyAddress = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, - kAudioObjectPropertyElementMaster}; + kAudioObjectPropertyElementMain}; WEBRTC_CA_LOG_WARN(AudioObjectRemovePropertyListener( kAudioObjectSystemObject, &propertyAddress, &objectListenerProc, this)); err = AudioHardwareUnload(); if (err != noErr) { - logCAMsg(webrtc::LS_ERROR, "Error in AudioHardwareUnload()", - (const char*)&err); + logCAMsg(LS_ERROR, "Error in AudioHardwareUnload()", (const char*)&err); retVal = -1; } @@ -837,7 +835,7 @@ int32_t AudioDeviceMac::PlayoutDeviceName(uint16_t index, } return GetDeviceName(kAudioDevicePropertyScopeOutput, index, - webrtc::ArrayView(name, kAdmMaxDeviceNameSize)); + ArrayView(name, kAdmMaxDeviceNameSize)); } int32_t AudioDeviceMac::RecordingDeviceName(uint16_t index, @@ -856,7 +854,7 @@ int32_t AudioDeviceMac::RecordingDeviceName(uint16_t index, } return GetDeviceName(kAudioDevicePropertyScopeInput, index, - webrtc::ArrayView(name, kAdmMaxDeviceNameSize)); + ArrayView(name, kAdmMaxDeviceNameSize)); } int16_t AudioDeviceMac::RecordingDevices() { @@ -1017,7 +1015,7 @@ int32_t AudioDeviceMac::InitPlayout() { _outputDeviceID, &propertyAddress, 0, NULL, &size, &_outStreamFormat)); if (_outStreamFormat.mFormatID != kAudioFormatLinearPCM) { - logCAMsg(webrtc::LS_ERROR, "Unacceptable output stream format -> mFormatID", + logCAMsg(LS_ERROR, "Unacceptable output stream format -> mFormatID", (const char*)&_outStreamFormat.mFormatID); return -1; } @@ -1047,8 +1045,7 @@ int32_t AudioDeviceMac::InitPlayout() { << ", mBitsPerChannel = " << _outStreamFormat.mBitsPerChannel; RTC_LOG(LS_VERBOSE) << "mFormatFlags = " << _outStreamFormat.mFormatFlags; - logCAMsg(webrtc::LS_VERBOSE, "mFormatID", - (const char*)&_outStreamFormat.mFormatID); + logCAMsg(LS_VERBOSE, "mFormatID", (const char*)&_outStreamFormat.mFormatID); // Our preferred format to work with. if (_outStreamFormat.mChannelsPerFrame < 2) { @@ -1127,7 +1124,7 @@ int32_t AudioDeviceMac::InitRecording() { _inputDeviceID, &propertyAddress, 0, NULL, &size, &_inStreamFormat)); if (_inStreamFormat.mFormatID != kAudioFormatLinearPCM) { - logCAMsg(webrtc::LS_ERROR, "Unacceptable input stream format -> mFormatID", + logCAMsg(LS_ERROR, "Unacceptable input stream format -> mFormatID", (const char*)&_inStreamFormat.mFormatID); return -1; } @@ -1160,8 +1157,7 @@ int32_t AudioDeviceMac::InitRecording() { << ", mBitsPerChannel = " << _inStreamFormat.mBitsPerChannel; RTC_LOG(LS_VERBOSE) << "mFormatFlags = " << _inStreamFormat.mFormatFlags; - logCAMsg(webrtc::LS_VERBOSE, "mFormatID", - (const char*)&_inStreamFormat.mFormatID); + logCAMsg(LS_VERBOSE, "mFormatID", (const char*)&_inStreamFormat.mFormatID); // Our preferred format to work with if (_inStreamFormat.mChannelsPerFrame >= 2 && (_recChannels == 2)) { @@ -1293,14 +1289,13 @@ int32_t AudioDeviceMac::StartRecording() { } RTC_DCHECK(capture_worker_thread_.empty()); - capture_worker_thread_ = webrtc::PlatformThread::SpawnJoinable( + capture_worker_thread_ = PlatformThread::SpawnJoinable( [this] { while (CaptureWorkerThread()) { } }, "CaptureWorkerThread", - webrtc::ThreadAttributes().SetPriority( - webrtc::ThreadPriority::kRealtime)); + ThreadAttributes().SetPriority(ThreadPriority::kRealtime)); OSStatus err = noErr; if (_twoDevices) { @@ -1431,14 +1426,13 @@ int32_t AudioDeviceMac::StartPlayout() { } RTC_DCHECK(render_worker_thread_.empty()); - render_worker_thread_ = webrtc::PlatformThread::SpawnJoinable( + render_worker_thread_ = PlatformThread::SpawnJoinable( [this] { while (RenderWorkerThread()) { } }, "RenderWorkerThread", - webrtc::ThreadAttributes().SetPriority( - webrtc::ThreadPriority::kRealtime)); + ThreadAttributes().SetPriority(ThreadPriority::kRealtime)); if (_twoDevices || !_recording) { OSStatus err = noErr; @@ -1552,7 +1546,7 @@ int32_t AudioDeviceMac::GetNumberDevices(const AudioObjectPropertyScope scope, AudioObjectPropertyAddress propertyAddress = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, - kAudioObjectPropertyElementMaster}; + kAudioObjectPropertyElementMain}; UInt32 size = 0; WEBRTC_CA_RETURN_ON_ERR(AudioObjectGetPropertyDataSize( kAudioObjectSystemObject, &propertyAddress, 0, NULL, &size)); @@ -1576,7 +1570,7 @@ int32_t AudioDeviceMac::GetNumberDevices(const AudioObjectPropertyScope scope, AudioObjectPropertyAddress propertyAddressDefault = { hardwareProperty, kAudioObjectPropertyScopeGlobal, - kAudioObjectPropertyElementMaster}; + kAudioObjectPropertyElementMain}; AudioDeviceID usedID; UInt32 uintSize = sizeof(UInt32); @@ -1651,7 +1645,7 @@ int32_t AudioDeviceMac::GetNumberDevices(const AudioObjectPropertyScope scope, int32_t AudioDeviceMac::GetDeviceName(const AudioObjectPropertyScope scope, const uint16_t index, - webrtc::ArrayView name) { + ArrayView name) { OSStatus err = noErr; AudioDeviceID deviceIds[MaxNumberDevices]; @@ -1678,7 +1672,7 @@ int32_t AudioDeviceMac::GetDeviceName(const AudioObjectPropertyScope scope, } AudioObjectPropertyAddress propertyAddress = { hardwareProperty, kAudioObjectPropertyScopeGlobal, - kAudioObjectPropertyElementMaster}; + kAudioObjectPropertyElementMain}; UInt32 size = sizeof(UInt32); WEBRTC_CA_RETURN_ON_ERR(AudioObjectGetPropertyData( kAudioObjectSystemObject, &propertyAddress, 0, NULL, &size, &usedID)); @@ -1699,7 +1693,7 @@ int32_t AudioDeviceMac::GetDeviceName(const AudioObjectPropertyScope scope, WEBRTC_CA_RETURN_ON_ERR(AudioObjectGetPropertyData( usedID, &propertyAddress, 0, NULL, &len, devName.data())); - webrtc::SimpleStringBuilder ss(name); + SimpleStringBuilder ss(name); ss.AppendFormat("default (%s)", devName.data()); } else { if (index < numberDevices) { @@ -1735,7 +1729,7 @@ int32_t AudioDeviceMac::InitDevice(const uint16_t userDeviceIndex, AudioObjectPropertyAddress propertyAddress = { defaultDeviceSelector, kAudioObjectPropertyScopeGlobal, - kAudioObjectPropertyElementMaster}; + kAudioObjectPropertyElementMain}; // Get the actual device IDs int numberDevices = @@ -1945,7 +1939,7 @@ int32_t AudioDeviceMac::HandleDeviceChange() { _captureDeviceIsAlive = 0; _mixerManager.CloseMicrophone(); } else if (err != noErr) { - logCAMsg(webrtc::LS_ERROR, "Error in AudioDeviceGetProperty()", + logCAMsg(LS_ERROR, "Error in AudioDeviceGetProperty()", (const char*)&err); return -1; } @@ -1964,7 +1958,7 @@ int32_t AudioDeviceMac::HandleDeviceChange() { _renderDeviceIsAlive = 0; _mixerManager.CloseSpeaker(); } else if (err != noErr) { - logCAMsg(webrtc::LS_ERROR, "Error in AudioDeviceGetProperty()", + logCAMsg(LS_ERROR, "Error in AudioDeviceGetProperty()", (const char*)&err); return -1; } @@ -1991,7 +1985,7 @@ int32_t AudioDeviceMac::HandleStreamFormatChange( objectId, &propertyAddress, 0, NULL, &size, &streamFormat)); if (streamFormat.mFormatID != kAudioFormatLinearPCM) { - logCAMsg(webrtc::LS_ERROR, "Unacceptable input stream format -> mFormatID", + logCAMsg(LS_ERROR, "Unacceptable input stream format -> mFormatID", (const char*)&streamFormat.mFormatID); return -1; } @@ -2018,8 +2012,7 @@ int32_t AudioDeviceMac::HandleStreamFormatChange( RTC_LOG(LS_VERBOSE) << "mBytesPerFrame = " << streamFormat.mBytesPerFrame << ", mBitsPerChannel = " << streamFormat.mBitsPerChannel; RTC_LOG(LS_VERBOSE) << "mFormatFlags = " << streamFormat.mFormatFlags; - logCAMsg(webrtc::LS_VERBOSE, "mFormatID", - (const char*)&streamFormat.mFormatID); + logCAMsg(LS_VERBOSE, "mFormatID", (const char*)&streamFormat.mFormatID); if (propertyAddress.mScope == kAudioDevicePropertyScopeInput) { const int io_block_size_samples = streamFormat.mChannelsPerFrame * @@ -2221,7 +2214,7 @@ OSStatus AudioDeviceMac::implDeviceIOProc(const AudioBufferList* inputData, RTC_LOG(LS_ERROR) << "Error in AudioConverterFillComplexBuffer()"; return 1; } else { - logCAMsg(webrtc::LS_ERROR, "Error in AudioConverterFillComplexBuffer()", + logCAMsg(LS_ERROR, "Error in AudioConverterFillComplexBuffer()", (const char*)&err); return 1; } @@ -2449,7 +2442,7 @@ bool AudioDeviceMac::CaptureWorkerThread() { // This is our own error. return false; } else { - logCAMsg(webrtc::LS_ERROR, "Error in AudioConverterFillComplexBuffer()", + logCAMsg(LS_ERROR, "Error in AudioConverterFillComplexBuffer()", (const char*)&err); return false; } @@ -2491,7 +2484,7 @@ bool AudioDeviceMac::CaptureWorkerThread() { bool AudioDeviceMac::KeyPressed() { bool key_down = false; // Loop through all Mac virtual key constant values. - for (unsigned int key_index = 0; key_index < arraysize(prev_key_state_); + for (unsigned int key_index = 0; key_index < std::size(prev_key_state_); ++key_index) { bool keyState = CGEventSourceKeyState(kCGEventSourceStateHIDSystemState, key_index); diff --git a/modules/audio_device/mac/audio_device_mac.h b/modules/audio_device/mac/audio_device_mac.h index 6c07d62f01..c80de22b46 100644 --- a/modules/audio_device/mac/audio_device_mac.h +++ b/modules/audio_device/mac/audio_device_mac.h @@ -170,9 +170,7 @@ class AudioDeviceMac : public AudioDeviceGeneric { static void AtomicSet32(int32_t* theValue, int32_t newValue); static int32_t AtomicGet32(int32_t* theValue); - static void logCAMsg(webrtc::LoggingSeverity sev, - const char* msg, - const char* err); + static void logCAMsg(LoggingSeverity sev, const char* msg, const char* err); int32_t GetNumberDevices(AudioObjectPropertyScope scope, AudioDeviceID scopedDeviceIds[], @@ -180,7 +178,7 @@ class AudioDeviceMac : public AudioDeviceGeneric { int32_t GetDeviceName(AudioObjectPropertyScope scope, uint16_t index, - webrtc::ArrayView name); + ArrayView name); int32_t InitDevice(uint16_t userDeviceIndex, AudioDeviceID& deviceId, @@ -267,14 +265,14 @@ class AudioDeviceMac : public AudioDeviceGeneric { Mutex mutex_; - webrtc::Event _stopEventRec; - webrtc::Event _stopEvent; + Event _stopEventRec; + Event _stopEvent; // Only valid/running between calls to StartRecording and StopRecording. - webrtc::PlatformThread capture_worker_thread_; + PlatformThread capture_worker_thread_; // Only valid/running between calls to StartPlayout and StopPlayout. - webrtc::PlatformThread render_worker_thread_; + PlatformThread render_worker_thread_; AudioMixerManagerMac _mixerManager; diff --git a/modules/audio_device/mac/audio_mixer_manager_mac.cc b/modules/audio_device/mac/audio_mixer_manager_mac.cc index 6644c5acc4..229a0ceb0b 100644 --- a/modules/audio_device/mac/audio_mixer_manager_mac.cc +++ b/modules/audio_device/mac/audio_mixer_manager_mac.cc @@ -16,31 +16,31 @@ namespace webrtc { -#define WEBRTC_CA_RETURN_ON_ERR(expr) \ - do { \ - err = expr; \ - if (err != noErr) { \ - logCAMsg(webrtc::LS_ERROR, "Error in " #expr, (const char*)&err); \ - return -1; \ - } \ - } while (0) - -#define WEBRTC_CA_LOG_ERR(expr) \ - do { \ - err = expr; \ - if (err != noErr) { \ - logCAMsg(webrtc::LS_ERROR, "Error in " #expr, (const char*)&err); \ - } \ +#define WEBRTC_CA_RETURN_ON_ERR(expr) \ + do { \ + err = expr; \ + if (err != noErr) { \ + logCAMsg(::webrtc::LS_ERROR, "Error in " #expr, (const char*)&err); \ + return -1; \ + } \ } while (0) -#define WEBRTC_CA_LOG_WARN(expr) \ +#define WEBRTC_CA_LOG_ERR(expr) \ do { \ err = expr; \ if (err != noErr) { \ - logCAMsg(webrtc::LS_WARNING, "Error in " #expr, (const char*)&err); \ + logCAMsg(::webrtc::LS_ERROR, "Error in " #expr, (const char*)&err); \ } \ } while (0) +#define WEBRTC_CA_LOG_WARN(expr) \ + do { \ + err = expr; \ + if (err != noErr) { \ + logCAMsg(::webrtc::LS_WARNING, "Error in " #expr, (const char*)&err); \ + } \ + } while (0) + AudioMixerManagerMac::AudioMixerManagerMac() : _inputDeviceID(kAudioObjectUnknown), _outputDeviceID(kAudioObjectUnknown), @@ -885,19 +885,19 @@ int32_t AudioMixerManagerMac::MinMicrophoneVolume(uint32_t& minVolume) const { // ============================================================================ // CoreAudio errors are best interpreted as four character strings. -void AudioMixerManagerMac::logCAMsg(const webrtc::LoggingSeverity sev, +void AudioMixerManagerMac::logCAMsg(const LoggingSeverity sev, const char* msg, const char* err) { RTC_DCHECK(msg != NULL); RTC_DCHECK(err != NULL); - RTC_DCHECK(sev == webrtc::LS_ERROR || sev == webrtc::LS_WARNING); + RTC_DCHECK(sev == LS_ERROR || sev == LS_WARNING); #ifdef WEBRTC_ARCH_BIG_ENDIAN switch (sev) { - case webrtc::LS_ERROR: + case LS_ERROR: RTC_LOG(LS_ERROR) << msg << ": " << err[0] << err[1] << err[2] << err[3]; break; - case webrtc::LS_WARNING: + case LS_WARNING: RTC_LOG(LS_WARNING) << msg << ": " << err[0] << err[1] << err[2] << err[3]; break; @@ -907,10 +907,10 @@ void AudioMixerManagerMac::logCAMsg(const webrtc::LoggingSeverity sev, #else // We need to flip the characters in this case. switch (sev) { - case webrtc::LS_ERROR: + case LS_ERROR: RTC_LOG(LS_ERROR) << msg << ": " << err[3] << err[2] << err[1] << err[0]; break; - case webrtc::LS_WARNING: + case LS_WARNING: RTC_LOG(LS_WARNING) << msg << ": " << err[3] << err[2] << err[1] << err[0]; break; diff --git a/modules/audio_device/mac/audio_mixer_manager_mac.h b/modules/audio_device/mac/audio_mixer_manager_mac.h index 78ce8319e9..89287bcb6f 100644 --- a/modules/audio_device/mac/audio_mixer_manager_mac.h +++ b/modules/audio_device/mac/audio_mixer_manager_mac.h @@ -54,9 +54,7 @@ class AudioMixerManagerMac { private: int32_t CloseSpeakerLocked() RTC_EXCLUSIVE_LOCKS_REQUIRED(mutex_); int32_t CloseMicrophoneLocked() RTC_EXCLUSIVE_LOCKS_REQUIRED(mutex_); - static void logCAMsg(webrtc::LoggingSeverity sev, - const char* msg, - const char* err); + static void logCAMsg(LoggingSeverity sev, const char* msg, const char* err); private: Mutex mutex_; diff --git a/modules/audio_device/test_audio_device_impl.cc b/modules/audio_device/test_audio_device_impl.cc index 32944d0539..a04dcfcb81 100644 --- a/modules/audio_device/test_audio_device_impl.cc +++ b/modules/audio_device/test_audio_device_impl.cc @@ -26,7 +26,7 @@ namespace { constexpr int kFrameLengthUs = 10000; -} +} // namespace TestAudioDevice::TestAudioDevice( TaskQueueFactory* task_queue_factory, diff --git a/modules/audio_device/win/audio_device_core_win.cc b/modules/audio_device/win/audio_device_core_win.cc index de17a0f647..f4321d115b 100644 --- a/modules/audio_device/win/audio_device_core_win.cc +++ b/modules/audio_device/win/audio_device_core_win.cc @@ -1849,9 +1849,8 @@ int32_t AudioDeviceWindowsCore::InitPlayout() { if (SUCCEEDED(hr)) { RTC_LOG(LS_VERBOSE) << "Audio Engine's current rendering mix format:"; // format type - RTC_LOG(LS_VERBOSE) << "wFormatTag : 0x" - << webrtc::ToHex(pWfxOut->wFormatTag) << " (" - << pWfxOut->wFormatTag << ")"; + RTC_LOG(LS_VERBOSE) << "wFormatTag : 0x" << ToHex(pWfxOut->wFormatTag) + << " (" << pWfxOut->wFormatTag << ")"; // number of channels (i.e. mono, stereo...) RTC_LOG(LS_VERBOSE) << "nChannels : " << pWfxOut->nChannels; // sample rate @@ -1924,9 +1923,8 @@ int32_t AudioDeviceWindowsCore::InitPlayout() { _playChannels = Wfx.nChannels; RTC_LOG(LS_VERBOSE) << "VoE selected this rendering format:"; - RTC_LOG(LS_VERBOSE) << "wFormatTag : 0x" - << webrtc::ToHex(Wfx.wFormatTag) << " (" - << Wfx.wFormatTag << ")"; + RTC_LOG(LS_VERBOSE) << "wFormatTag : 0x" << ToHex(Wfx.wFormatTag) + << " (" << Wfx.wFormatTag << ")"; RTC_LOG(LS_VERBOSE) << "nChannels : " << Wfx.nChannels; RTC_LOG(LS_VERBOSE) << "nSamplesPerSec : " << Wfx.nSamplesPerSec; RTC_LOG(LS_VERBOSE) << "nAvgBytesPerSec : " << Wfx.nAvgBytesPerSec; @@ -2094,8 +2092,8 @@ int32_t AudioDeviceWindowsCore::InitRecordingDMO() { << "AudioDeviceBuffer must be attached before streaming can start"; } - _mediaBuffer = webrtc::make_ref_counted(_recBlockSize * - _recAudioFrameSize); + _mediaBuffer = + make_ref_counted(_recBlockSize * _recAudioFrameSize); // Optional, but if called, must be after media types are set. hr = _dmo->AllocateStreamingResources(); @@ -2166,9 +2164,8 @@ int32_t AudioDeviceWindowsCore::InitRecording() { if (SUCCEEDED(hr)) { RTC_LOG(LS_VERBOSE) << "Audio Engine's current capturing mix format:"; // format type - RTC_LOG(LS_VERBOSE) << "wFormatTag : 0x" - << webrtc::ToHex(pWfxIn->wFormatTag) << " (" - << pWfxIn->wFormatTag << ")"; + RTC_LOG(LS_VERBOSE) << "wFormatTag : 0x" << ToHex(pWfxIn->wFormatTag) + << " (" << pWfxIn->wFormatTag << ")"; // number of channels (i.e. mono, stereo...) RTC_LOG(LS_VERBOSE) << "nChannels : " << pWfxIn->nChannels; // sample rate @@ -2240,7 +2237,7 @@ int32_t AudioDeviceWindowsCore::InitRecording() { RTC_LOG(LS_VERBOSE) << "VoE selected this capturing format:"; RTC_LOG(LS_VERBOSE) << "wFormatTag : 0x" - << webrtc::ToHex(Wfx.Format.wFormatTag) << " (" + << ToHex(Wfx.Format.wFormatTag) << " (" << Wfx.Format.wFormatTag << ")"; RTC_LOG(LS_VERBOSE) << "nChannels : " << Wfx.Format.nChannels; RTC_LOG(LS_VERBOSE) << "nSamplesPerSec : " << Wfx.Format.nSamplesPerSec; @@ -2661,7 +2658,7 @@ DWORD AudioDeviceWindowsCore::DoRenderThread() { return 1; } - webrtc::SetCurrentThreadName("webrtc_core_audio_render_thread"); + SetCurrentThreadName("webrtc_core_audio_render_thread"); // Use Multimedia Class Scheduler Service (MMCSS) to boost the thread // priority. @@ -2923,7 +2920,7 @@ DWORD AudioDeviceWindowsCore::DoRenderThread() { DWORD AudioDeviceWindowsCore::InitCaptureThreadPriority() { _hMmTask = NULL; - webrtc::SetCurrentThreadName("webrtc_core_audio_capture_thread"); + SetCurrentThreadName("webrtc_core_audio_capture_thread"); // Use Multimedia Class Scheduler Service (MMCSS) to boost the thread // priority. @@ -3300,7 +3297,7 @@ DWORD AudioDeviceWindowsCore::DoCaptureThread() { // client. RTC_LOG(LS_ERROR) << "IAudioCaptureClient::GetBuffer returned" " AUDCLNT_E_BUFFER_ERROR, hr = 0x" - << webrtc::ToHex(hr); + << ToHex(hr); goto Exit; } @@ -3384,7 +3381,7 @@ int AudioDeviceWindowsCore::SetDMOProperties() { HRESULT hr = S_OK; RTC_DCHECK(_dmo); - webrtc::scoped_refptr ps; + scoped_refptr ps; { IPropertyStore* ptrPS = NULL; hr = _dmo->QueryInterface(IID_IPropertyStore, @@ -3763,7 +3760,7 @@ int32_t AudioDeviceWindowsCore::_GetDefaultDeviceIndex(EDataFlow dir, *index = -1; for (UINT i = 0; i < count; i++) { memset(szDeviceID, 0, sizeof(szDeviceID)); - webrtc::scoped_refptr device; + scoped_refptr device; { IMMDevice* ptrDevice = NULL; hr = collection->Item(i, &ptrDevice); @@ -3816,7 +3813,7 @@ int32_t AudioDeviceWindowsCore::_GetDeviceName(IMMDevice* pDevice, hr = pDevice->OpenPropertyStore(STGM_READ, &pProps); if (FAILED(hr)) { RTC_LOG(LS_ERROR) << "IMMDevice::OpenPropertyStore failed, hr = 0x" - << webrtc::ToHex(hr); + << ToHex(hr); } } @@ -3828,7 +3825,7 @@ int32_t AudioDeviceWindowsCore::_GetDeviceName(IMMDevice* pDevice, hr = pProps->GetValue(PKEY_Device_FriendlyName, &varName); if (FAILED(hr)) { RTC_LOG(LS_ERROR) << "IPropertyStore::GetValue failed, hr = 0x" - << webrtc::ToHex(hr); + << ToHex(hr); } } @@ -3836,7 +3833,7 @@ int32_t AudioDeviceWindowsCore::_GetDeviceName(IMMDevice* pDevice, hr = E_FAIL; RTC_LOG(LS_ERROR) << "IPropertyStore::GetValue returned no value," " hr = 0x" - << webrtc::ToHex(hr); + << ToHex(hr); } if ((SUCCEEDED(hr)) && (VT_LPWSTR != varName.vt)) { @@ -3844,7 +3841,7 @@ int32_t AudioDeviceWindowsCore::_GetDeviceName(IMMDevice* pDevice, hr = E_UNEXPECTED; RTC_LOG(LS_ERROR) << "IPropertyStore::GetValue returned unexpected" " type, hr = 0x" - << webrtc::ToHex(hr); + << ToHex(hr); } if (SUCCEEDED(hr) && (varName.pwszVal != NULL)) { @@ -4035,17 +4032,13 @@ int32_t AudioDeviceWindowsCore::_EnumerateEndpointDevicesAll( hr = pEndpoint->GetState(&dwState); CONTINUE_ON_ERROR(hr); if (dwState & DEVICE_STATE_ACTIVE) - RTC_LOG(LS_VERBOSE) << "state (0x" << webrtc::ToHex(dwState) - << ") : *ACTIVE*"; + RTC_LOG(LS_VERBOSE) << "state (0x" << ToHex(dwState) << ") : *ACTIVE*"; if (dwState & DEVICE_STATE_DISABLED) - RTC_LOG(LS_VERBOSE) << "state (0x" << webrtc::ToHex(dwState) - << ") : DISABLED"; + RTC_LOG(LS_VERBOSE) << "state (0x" << ToHex(dwState) << ") : DISABLED"; if (dwState & DEVICE_STATE_NOTPRESENT) - RTC_LOG(LS_VERBOSE) << "state (0x" << webrtc::ToHex(dwState) - << ") : NOTPRESENT"; + RTC_LOG(LS_VERBOSE) << "state (0x" << ToHex(dwState) << ") : NOTPRESENT"; if (dwState & DEVICE_STATE_UNPLUGGED) - RTC_LOG(LS_VERBOSE) << "state (0x" << webrtc::ToHex(dwState) - << ") : UNPLUGGED"; + RTC_LOG(LS_VERBOSE) << "state (0x" << ToHex(dwState) << ") : UNPLUGGED"; // Check the hardware volume capabilities. DWORD dwHwSupportMask = 0; @@ -4056,15 +4049,15 @@ int32_t AudioDeviceWindowsCore::_EnumerateEndpointDevicesAll( CONTINUE_ON_ERROR(hr); if (dwHwSupportMask & ENDPOINT_HARDWARE_SUPPORT_VOLUME) // The audio endpoint device supports a hardware volume control - RTC_LOG(LS_VERBOSE) << "hwmask (0x" << webrtc::ToHex(dwHwSupportMask) + RTC_LOG(LS_VERBOSE) << "hwmask (0x" << ToHex(dwHwSupportMask) << ") : HARDWARE_SUPPORT_VOLUME"; if (dwHwSupportMask & ENDPOINT_HARDWARE_SUPPORT_MUTE) // The audio endpoint device supports a hardware mute control - RTC_LOG(LS_VERBOSE) << "hwmask (0x" << webrtc::ToHex(dwHwSupportMask) + RTC_LOG(LS_VERBOSE) << "hwmask (0x" << ToHex(dwHwSupportMask) << ") : HARDWARE_SUPPORT_MUTE"; if (dwHwSupportMask & ENDPOINT_HARDWARE_SUPPORT_METER) // The audio endpoint device supports a hardware peak meter - RTC_LOG(LS_VERBOSE) << "hwmask (0x" << webrtc::ToHex(dwHwSupportMask) + RTC_LOG(LS_VERBOSE) << "hwmask (0x" << ToHex(dwHwSupportMask) << ") : HARDWARE_SUPPORT_METER"; // Check the channel count (#channels in the audio stream that enters or diff --git a/modules/audio_device/win/audio_device_core_win.h b/modules/audio_device/win/audio_device_core_win.h index d09bed9939..c00bee500f 100644 --- a/modules/audio_device/win/audio_device_core_win.h +++ b/modules/audio_device/win/audio_device_core_win.h @@ -238,8 +238,8 @@ class AudioDeviceWindowsCore : public AudioDeviceGeneric { ISimpleAudioVolume* _ptrRenderSimpleVolume; // DirectX Media Object (DMO) for the built-in AEC. - webrtc::scoped_refptr _dmo; - webrtc::scoped_refptr _mediaBuffer; + scoped_refptr _dmo; + scoped_refptr _mediaBuffer; bool _builtInAecEnabled; HANDLE _hRenderSamplesReadyEvent; diff --git a/modules/audio_device/win/core_audio_base_win.cc b/modules/audio_device/win/core_audio_base_win.cc index 4d73ea59d4..98cb29fdb6 100644 --- a/modules/audio_device/win/core_audio_base_win.cc +++ b/modules/audio_device/win/core_audio_base_win.cc @@ -10,12 +10,12 @@ #include "modules/audio_device/win/core_audio_base_win.h" +#include #include #include #include "absl/strings/string_view.h" #include "modules/audio_device/audio_device_buffer.h" -#include "rtc_base/arraysize.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "rtc_base/numerics/safe_conversions.h" @@ -905,7 +905,7 @@ void CoreAudioBase::ThreadRun() { // is signaled. An error event can also break the main thread loop. while (streaming && !error) { // Wait for a close-down event, stream-switch event or a new render event. - DWORD wait_result = WaitForMultipleObjects(arraysize(wait_array), + DWORD wait_result = WaitForMultipleObjects(std::size(wait_array), wait_array, false, INFINITE); switch (wait_result) { case WAIT_OBJECT_0 + 0: diff --git a/modules/audio_device/win/core_audio_utility_win.cc b/modules/audio_device/win/core_audio_utility_win.cc index b574c287db..dbfefa0428 100644 --- a/modules/audio_device/win/core_audio_utility_win.cc +++ b/modules/audio_device/win/core_audio_utility_win.cc @@ -15,11 +15,11 @@ #include #include +#include #include #include #include "absl/strings/string_view.h" -#include "rtc_base/arraysize.h" #include "rtc_base/logging.h" #include "rtc_base/platform_thread_types.h" #include "rtc_base/string_utils.h" @@ -205,7 +205,7 @@ bool LoadAudiosesDll() { static const wchar_t* const kAudiosesDLL = L"%WINDIR%\\system32\\audioses.dll"; wchar_t path[MAX_PATH] = {0}; - ExpandEnvironmentStringsW(kAudiosesDLL, path, arraysize(path)); + ExpandEnvironmentStringsW(kAudiosesDLL, path, std::size(path)); RTC_DLOG(LS_INFO) << webrtc::ToUtf8(path); return (LoadLibraryExW(path, nullptr, LOAD_WITH_ALTERED_SEARCH_PATH) != nullptr); @@ -214,7 +214,7 @@ bool LoadAudiosesDll() { bool LoadAvrtDll() { static const wchar_t* const kAvrtDLL = L"%WINDIR%\\system32\\Avrt.dll"; wchar_t path[MAX_PATH] = {0}; - ExpandEnvironmentStringsW(kAvrtDLL, path, arraysize(path)); + ExpandEnvironmentStringsW(kAvrtDLL, path, std::size(path)); RTC_DLOG(LS_INFO) << webrtc::ToUtf8(path); return (LoadLibraryExW(path, nullptr, LOAD_WITH_ALTERED_SEARCH_PATH) != nullptr); @@ -548,22 +548,21 @@ bool GetDeviceNamesInternal(EDataFlow data_flow, // id if only one active device exists). The first element (index 0) is the // default device and the second element (index 1) is the default // communication device. - ERole role[] = {eCommunications, eConsole}; ComPtr default_device; AudioDeviceName default_device_name; - for (size_t i = 0; i < arraysize(role); ++i) { + for (ERole role : {eCommunications, eConsole}) { default_device = CreateDeviceInternal(AudioDeviceName::kDefaultDeviceId, - data_flow, role[i]); + data_flow, role); if (!default_device.Get()) { // Add empty strings to device name if the device could not be created. RTC_DLOG(LS_WARNING) << "Failed to add device with role: " - << RoleToString(role[i]); + << RoleToString(role); default_device_name.device_name = std::string(); default_device_name.unique_id = std::string(); } else { // Populate the device name with friendly name and unique id. std::string device_name; - device_name += (role[i] == eConsole ? "Default - " : "Communication - "); + device_name += (role == eConsole ? "Default - " : "Communication - "); device_name += GetDeviceFriendlyNameInternal(default_device.Get()); std::string unique_id = GetDeviceIdInternal(default_device.Get()); default_device_name.device_name = std::move(device_name); diff --git a/modules/audio_device/win/core_audio_utility_win_unittest.cc b/modules/audio_device/win/core_audio_utility_win_unittest.cc index c035cc4d56..e6514e519d 100644 --- a/modules/audio_device/win/core_audio_utility_win_unittest.cc +++ b/modules/audio_device/win/core_audio_utility_win_unittest.cc @@ -10,7 +10,6 @@ #include "modules/audio_device/win/core_audio_utility_win.h" -#include "rtc_base/arraysize.h" #include "rtc_base/logging.h" #include "rtc_base/win/scoped_com_initializer.h" #include "rtc_base/win/windows_version.h" @@ -204,12 +203,11 @@ TEST_F(CoreAudioUtilityWinTest, CreateDefaultDevice) { // Create default devices for all flow/role combinations above. ComPtr audio_device; - for (size_t i = 0; i < arraysize(data); ++i) { + for (auto [flow, role] : data) { audio_device = core_audio_utility::CreateDevice( - AudioDeviceName::kDefaultDeviceId, data[i].flow, data[i].role); + AudioDeviceName::kDefaultDeviceId, flow, role); EXPECT_TRUE(audio_device.Get()); - EXPECT_EQ(data[i].flow, - core_audio_utility::GetDataFlow(audio_device.Get())); + EXPECT_EQ(flow, core_audio_utility::GetDataFlow(audio_device.Get())); } // Only eRender and eCapture are allowed as flow parameter. @@ -256,9 +254,9 @@ TEST_F(CoreAudioUtilityWinTest, GetDefaultDeviceName) { // Get name and ID of default devices for all flow/role combinations above. ComPtr audio_device; AudioDeviceName device_name; - for (size_t i = 0; i < arraysize(data); ++i) { + for (auto [flow, role] : data) { audio_device = core_audio_utility::CreateDevice( - AudioDeviceName::kDefaultDeviceId, data[i].flow, data[i].role); + AudioDeviceName::kDefaultDeviceId, flow, role); device_name = core_audio_utility::GetDeviceName(audio_device.Get()); EXPECT_TRUE(device_name.IsValid()); } @@ -317,14 +315,12 @@ TEST_F(CoreAudioUtilityWinTest, CreateSessionManager2) { ABORT_TEST_IF_NOT(DevicesAvailable() && webrtc::rtc_win::GetVersion() >= webrtc::rtc_win::VERSION_WIN7); - EDataFlow data_flow[] = {eRender, eCapture}; - // Obtain reference to an IAudioSessionManager2 interface for a default audio // endpoint device specified by two different data flows and the `eConsole` // role. - for (size_t i = 0; i < arraysize(data_flow); ++i) { + for (EDataFlow data_flow : {eRender, eCapture}) { ComPtr device(core_audio_utility::CreateDevice( - AudioDeviceName::kDefaultDeviceId, data_flow[i], eConsole)); + AudioDeviceName::kDefaultDeviceId, data_flow, eConsole)); EXPECT_TRUE(device.Get()); ComPtr session_manager = core_audio_utility::CreateSessionManager2(device.Get()); @@ -336,14 +332,12 @@ TEST_F(CoreAudioUtilityWinTest, CreateSessionEnumerator) { ABORT_TEST_IF_NOT(DevicesAvailable() && webrtc::rtc_win::GetVersion() >= webrtc::rtc_win::VERSION_WIN7); - EDataFlow data_flow[] = {eRender, eCapture}; - // Obtain reference to an IAudioSessionEnumerator interface for a default // audio endpoint device specified by two different data flows and the // `eConsole` role. - for (size_t i = 0; i < arraysize(data_flow); ++i) { + for (EDataFlow data_flow : {eRender, eCapture}) { ComPtr device(core_audio_utility::CreateDevice( - AudioDeviceName::kDefaultDeviceId, data_flow[i], eConsole)); + AudioDeviceName::kDefaultDeviceId, data_flow, eConsole)); EXPECT_TRUE(device.Get()); ComPtr session_enumerator = core_audio_utility::CreateSessionEnumerator(device.Get()); @@ -362,16 +356,14 @@ TEST_F(CoreAudioUtilityWinTest, NumberOfActiveSessions) { ABORT_TEST_IF_NOT(DevicesAvailable() && webrtc::rtc_win::GetVersion() >= webrtc::rtc_win::VERSION_WIN7); - EDataFlow data_flow[] = {eRender, eCapture}; - // Count number of active audio session for a default audio endpoint device // specified by two different data flows and the `eConsole` role. // Ensure that the number of active audio sessions is less than or equal to // the total number of audio sessions on that same device. - for (size_t i = 0; i < arraysize(data_flow); ++i) { + for (EDataFlow data_flow : {eRender, eCapture}) { // Create an audio endpoint device. ComPtr device(core_audio_utility::CreateDevice( - AudioDeviceName::kDefaultDeviceId, data_flow[i], eConsole)); + AudioDeviceName::kDefaultDeviceId, data_flow, eConsole)); EXPECT_TRUE(device.Get()); // Ask for total number of audio sessions on the created device. @@ -392,13 +384,11 @@ TEST_F(CoreAudioUtilityWinTest, NumberOfActiveSessions) { TEST_F(CoreAudioUtilityWinTest, CreateClient) { ABORT_TEST_IF_NOT(DevicesAvailable()); - EDataFlow data_flow[] = {eRender, eCapture}; - // Obtain reference to an IAudioClient interface for a default audio endpoint // device specified by two different data flows and the `eConsole` role. - for (size_t i = 0; i < arraysize(data_flow); ++i) { + for (EDataFlow data_flow : {eRender, eCapture}) { ComPtr client = core_audio_utility::CreateClient( - AudioDeviceName::kDefaultDeviceId, data_flow[i], eConsole); + AudioDeviceName::kDefaultDeviceId, data_flow, eConsole); EXPECT_TRUE(client.Get()); } } @@ -407,13 +397,11 @@ TEST_F(CoreAudioUtilityWinTest, CreateClient2) { ABORT_TEST_IF_NOT(DevicesAvailable() && core_audio_utility::GetAudioClientVersion() >= 2); - EDataFlow data_flow[] = {eRender, eCapture}; - // Obtain reference to an IAudioClient2 interface for a default audio endpoint // device specified by two different data flows and the `eConsole` role. - for (size_t i = 0; i < arraysize(data_flow); ++i) { + for (EDataFlow data_flow : {eRender, eCapture}) { ComPtr client2 = core_audio_utility::CreateClient2( - AudioDeviceName::kDefaultDeviceId, data_flow[i], eConsole); + AudioDeviceName::kDefaultDeviceId, data_flow, eConsole); EXPECT_TRUE(client2.Get()); } } @@ -422,13 +410,11 @@ TEST_F(CoreAudioUtilityWinTest, CreateClient3) { ABORT_TEST_IF_NOT(DevicesAvailable() && core_audio_utility::GetAudioClientVersion() >= 3); - EDataFlow data_flow[] = {eRender, eCapture}; - // Obtain reference to an IAudioClient3 interface for a default audio endpoint // device specified by two different data flows and the `eConsole` role. - for (size_t i = 0; i < arraysize(data_flow); ++i) { + for (EDataFlow data_flow : {eRender, eCapture}) { ComPtr client3 = core_audio_utility::CreateClient3( - AudioDeviceName::kDefaultDeviceId, data_flow[i], eConsole); + AudioDeviceName::kDefaultDeviceId, data_flow, eConsole); EXPECT_TRUE(client3.Get()); } } @@ -541,16 +527,14 @@ TEST_F(CoreAudioUtilityWinTest, IsFormatSupported) { TEST_F(CoreAudioUtilityWinTest, GetDevicePeriod) { ABORT_TEST_IF_NOT(DevicesAvailable()); - EDataFlow data_flow[] = {eRender, eCapture}; - // Verify that the device periods are valid for the default render and // capture devices. ComPtr client; - for (size_t i = 0; i < arraysize(data_flow); ++i) { + for (EDataFlow data_flow : {eRender, eCapture}) { REFERENCE_TIME shared_time_period = 0; REFERENCE_TIME exclusive_time_period = 0; client = core_audio_utility::CreateClient(AudioDeviceName::kDefaultDeviceId, - data_flow[i], eConsole); + data_flow, eConsole); EXPECT_TRUE(client.Get()); EXPECT_TRUE(SUCCEEDED(core_audio_utility::GetDevicePeriod( client.Get(), AUDCLNT_SHAREMODE_SHARED, &shared_time_period))); @@ -577,9 +561,9 @@ TEST_F(CoreAudioUtilityWinTest, GetPreferredAudioParameters) { // combinations above. ComPtr client; webrtc::AudioParameters params; - for (size_t i = 0; i < arraysize(data); ++i) { + for (auto [flow, role] : data) { client = core_audio_utility::CreateClient(AudioDeviceName::kDefaultDeviceId, - data[i].flow, data[i].role); + flow, role); EXPECT_TRUE(client.Get()); EXPECT_TRUE(SUCCEEDED(core_audio_utility::GetPreferredAudioParameters( client.Get(), ¶ms))); @@ -661,23 +645,21 @@ TEST_F(CoreAudioUtilityWinTest, SharedModeInitialize) { TEST_F(CoreAudioUtilityWinTest, CreateRenderAndCaptureClients) { ABORT_TEST_IF_NOT(DevicesAvailable()); - EDataFlow data_flow[] = {eRender, eCapture}; - WAVEFORMATPCMEX format; uint32_t endpoint_buffer_size = 0; - for (size_t i = 0; i < arraysize(data_flow); ++i) { + for (EDataFlow data_flow : {eRender, eCapture}) { ComPtr client; ComPtr render_client; ComPtr capture_client; // Create a default client for the given data-flow direction. client = core_audio_utility::CreateClient(AudioDeviceName::kDefaultDeviceId, - data_flow[i], eConsole); + data_flow, eConsole); EXPECT_TRUE(client.Get()); EXPECT_TRUE(SUCCEEDED( core_audio_utility::GetSharedModeMixFormat(client.Get(), &format))); - if (data_flow[i] == eRender) { + if (data_flow == eRender) { // It is not possible to create a render client using an unitialized // client interface. render_client = core_audio_utility::CreateRenderClient(client.Get()); @@ -689,7 +671,7 @@ TEST_F(CoreAudioUtilityWinTest, CreateRenderAndCaptureClients) { render_client = core_audio_utility::CreateRenderClient(client.Get()); EXPECT_TRUE(render_client.Get()); EXPECT_GT(endpoint_buffer_size, 0u); - } else if (data_flow[i] == eCapture) { + } else if (data_flow == eCapture) { // It is not possible to create a capture client using an unitialized // client interface. capture_client = core_audio_utility::CreateCaptureClient(client.Get()); @@ -708,18 +690,16 @@ TEST_F(CoreAudioUtilityWinTest, CreateRenderAndCaptureClients) { TEST_F(CoreAudioUtilityWinTest, CreateAudioClock) { ABORT_TEST_IF_NOT(DevicesAvailable()); - EDataFlow data_flow[] = {eRender, eCapture}; - WAVEFORMATPCMEX format; uint32_t endpoint_buffer_size = 0; - for (size_t i = 0; i < arraysize(data_flow); ++i) { + for (EDataFlow data_flow : {eRender, eCapture}) { ComPtr client; ComPtr audio_clock; // Create a default client for the given data-flow direction. client = core_audio_utility::CreateClient(AudioDeviceName::kDefaultDeviceId, - data_flow[i], eConsole); + data_flow, eConsole); EXPECT_TRUE(client.Get()); EXPECT_TRUE(SUCCEEDED( core_audio_utility::GetSharedModeMixFormat(client.Get(), &format))); @@ -746,18 +726,16 @@ TEST_F(CoreAudioUtilityWinTest, CreateAudioClock) { TEST_F(CoreAudioUtilityWinTest, CreateAudioSessionControl) { ABORT_TEST_IF_NOT(DevicesAvailable()); - EDataFlow data_flow[] = {eRender, eCapture}; - WAVEFORMATPCMEX format; uint32_t endpoint_buffer_size = 0; - for (size_t i = 0; i < arraysize(data_flow); ++i) { + for (EDataFlow data_flow : {eRender, eCapture}) { ComPtr client; ComPtr audio_session_control; // Create a default client for the given data-flow direction. client = core_audio_utility::CreateClient(AudioDeviceName::kDefaultDeviceId, - data_flow[i], eConsole); + data_flow, eConsole); EXPECT_TRUE(client.Get()); EXPECT_TRUE(SUCCEEDED( core_audio_utility::GetSharedModeMixFormat(client.Get(), &format))); @@ -791,18 +769,16 @@ TEST_F(CoreAudioUtilityWinTest, CreateAudioSessionControl) { TEST_F(CoreAudioUtilityWinTest, CreateSimpleAudioVolume) { ABORT_TEST_IF_NOT(DevicesAvailable()); - EDataFlow data_flow[] = {eRender, eCapture}; - WAVEFORMATPCMEX format; uint32_t endpoint_buffer_size = 0; - for (size_t i = 0; i < arraysize(data_flow); ++i) { + for (EDataFlow data_flow : {eRender, eCapture}) { ComPtr client; ComPtr simple_audio_volume; // Create a default client for the given data-flow direction. client = core_audio_utility::CreateClient(AudioDeviceName::kDefaultDeviceId, - data_flow[i], eConsole); + data_flow, eConsole); EXPECT_TRUE(client.Get()); EXPECT_TRUE(SUCCEEDED( core_audio_utility::GetSharedModeMixFormat(client.Get(), &format))); diff --git a/modules/audio_mixer/BUILD.gn b/modules/audio_mixer/BUILD.gn index 37c82ff731..d2fa8dbaec 100644 --- a/modules/audio_mixer/BUILD.gn +++ b/modules/audio_mixer/BUILD.gn @@ -32,6 +32,7 @@ rtc_library("audio_mixer_impl") { "default_output_rate_calculator.h", # For creating a mixer with limiter # disabled. "frame_combiner.h", + "output_rate_calculator.h", ] configs += [ "../audio_processing:apm_debug_dump" ] @@ -39,6 +40,7 @@ rtc_library("audio_mixer_impl") { deps = [ ":audio_frame_manipulator", "../../api:array_view", + "../../api:make_ref_counted", "../../api:rtp_packet_info", "../../api:scoped_refptr", "../../api/audio:audio_frame_api", @@ -116,6 +118,7 @@ if (rtc_include_tests) { ":audio_mixer_test_utils", "../../api:array_view", "../../api:rtp_packet_info", + "../../api:scoped_refptr", "../../api/audio:audio_frame_api", "../../api/audio:audio_mixer_api", "../../api/units:timestamp", @@ -135,11 +138,15 @@ if (rtc_include_tests) { deps = [ ":audio_mixer_impl", + "../../api:scoped_refptr", + "../../api/audio:audio_frame_api", "../../api/audio:audio_mixer_api", "../../common_audio", + "../../rtc_base:checks", "../../rtc_base:stringutils", "//third_party/abseil-cpp/absl/flags:flag", "//third_party/abseil-cpp/absl/flags:parse", + "//third_party/abseil-cpp/absl/strings:string_view", ] } } diff --git a/modules/audio_mixer/audio_frame_manipulator.cc b/modules/audio_mixer/audio_frame_manipulator.cc index 94f03b2037..5a6e067111 100644 --- a/modules/audio_mixer/audio_frame_manipulator.cc +++ b/modules/audio_mixer/audio_frame_manipulator.cc @@ -10,6 +10,11 @@ #include "modules/audio_mixer/audio_frame_manipulator.h" +#include +#include + +#include "api/audio/audio_frame.h" +#include "api/audio/channel_layout.h" #include "audio/utility/audio_frame_operations.h" #include "audio/utility/channel_mixer.h" #include "rtc_base/checks.h" diff --git a/modules/audio_mixer/audio_frame_manipulator_unittest.cc b/modules/audio_mixer/audio_frame_manipulator_unittest.cc index cfb3f2c230..0f340f72a1 100644 --- a/modules/audio_mixer/audio_frame_manipulator_unittest.cc +++ b/modules/audio_mixer/audio_frame_manipulator_unittest.cc @@ -11,7 +11,10 @@ #include "modules/audio_mixer/audio_frame_manipulator.h" #include +#include +#include +#include "api/audio/audio_frame.h" #include "test/gtest.h" namespace webrtc { diff --git a/modules/audio_mixer/audio_mixer_impl.cc b/modules/audio_mixer/audio_mixer_impl.cc index 7a877a4024..edf68284e4 100644 --- a/modules/audio_mixer/audio_mixer_impl.cc +++ b/modules/audio_mixer/audio_mixer_impl.cc @@ -10,17 +10,21 @@ #include "modules/audio_mixer/audio_mixer_impl.h" -#include - #include -#include -#include +#include +#include #include +#include -#include "modules/audio_mixer/audio_frame_manipulator.h" +#include "api/array_view.h" +#include "api/audio/audio_frame.h" +#include "api/make_ref_counted.h" +#include "api/scoped_refptr.h" #include "modules/audio_mixer/default_output_rate_calculator.h" +#include "modules/audio_mixer/output_rate_calculator.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" +#include "rtc_base/synchronization/mutex.h" #include "rtc_base/trace_event.h" #include "system_wrappers/include/metrics.h" diff --git a/modules/audio_mixer/audio_mixer_impl.h b/modules/audio_mixer/audio_mixer_impl.h index fa90929385..104f1304b7 100644 --- a/modules/audio_mixer/audio_mixer_impl.h +++ b/modules/audio_mixer/audio_mixer_impl.h @@ -22,7 +22,6 @@ #include "api/scoped_refptr.h" #include "modules/audio_mixer/frame_combiner.h" #include "modules/audio_mixer/output_rate_calculator.h" -#include "rtc_base/race_checker.h" #include "rtc_base/synchronization/mutex.h" #include "rtc_base/thread_annotations.h" diff --git a/modules/audio_mixer/audio_mixer_impl_unittest.cc b/modules/audio_mixer/audio_mixer_impl_unittest.cc index 19b304f03a..82d2419cbe 100644 --- a/modules/audio_mixer/audio_mixer_impl_unittest.cc +++ b/modules/audio_mixer/audio_mixer_impl_unittest.cc @@ -10,21 +10,23 @@ #include "modules/audio_mixer/audio_mixer_impl.h" -#include - +#include #include -#include +#include #include #include #include -#include #include +#include "api/array_view.h" +#include "api/audio/audio_frame.h" #include "api/audio/audio_mixer.h" #include "api/rtp_packet_info.h" #include "api/rtp_packet_infos.h" +#include "api/scoped_refptr.h" #include "api/units/timestamp.h" #include "modules/audio_mixer/default_output_rate_calculator.h" +#include "modules/audio_mixer/output_rate_calculator.h" #include "rtc_base/checks.h" #include "rtc_base/strings/string_builder.h" #include "rtc_base/task_queue_for_test.h" diff --git a/modules/audio_mixer/audio_mixer_test.cc b/modules/audio_mixer/audio_mixer_test.cc index b93547e3c3..fb7de856c5 100644 --- a/modules/audio_mixer/audio_mixer_test.cc +++ b/modules/audio_mixer/audio_mixer_test.cc @@ -10,15 +10,23 @@ #include "api/audio/audio_mixer.h" +#include #include #include +#include +#include #include #include "absl/flags/flag.h" #include "absl/flags/parse.h" +#include "absl/strings/string_view.h" +#include "api/audio/audio_frame.h" +#include "api/scoped_refptr.h" #include "common_audio/wav_file.h" #include "modules/audio_mixer/audio_mixer_impl.h" #include "modules/audio_mixer/default_output_rate_calculator.h" +#include "modules/audio_mixer/output_rate_calculator.h" +#include "rtc_base/checks.h" #include "rtc_base/strings/string_builder.h" ABSL_FLAG(int, diff --git a/modules/audio_mixer/default_output_rate_calculator.cc b/modules/audio_mixer/default_output_rate_calculator.cc index 576e83836d..6885875cae 100644 --- a/modules/audio_mixer/default_output_rate_calculator.cc +++ b/modules/audio_mixer/default_output_rate_calculator.cc @@ -13,6 +13,7 @@ #include #include +#include "api/array_view.h" #include "api/audio/audio_processing.h" #include "rtc_base/checks.h" diff --git a/modules/audio_mixer/default_output_rate_calculator.h b/modules/audio_mixer/default_output_rate_calculator.h index 88e4435e42..acae77fe0a 100644 --- a/modules/audio_mixer/default_output_rate_calculator.h +++ b/modules/audio_mixer/default_output_rate_calculator.h @@ -11,8 +11,6 @@ #ifndef MODULES_AUDIO_MIXER_DEFAULT_OUTPUT_RATE_CALCULATOR_H_ #define MODULES_AUDIO_MIXER_DEFAULT_OUTPUT_RATE_CALCULATOR_H_ -#include - #include "api/array_view.h" #include "modules/audio_mixer/output_rate_calculator.h" diff --git a/modules/audio_mixer/frame_combiner.h b/modules/audio_mixer/frame_combiner.h index fd7d40ec13..74c4547cc8 100644 --- a/modules/audio_mixer/frame_combiner.h +++ b/modules/audio_mixer/frame_combiner.h @@ -11,8 +11,9 @@ #ifndef MODULES_AUDIO_MIXER_FRAME_COMBINER_H_ #define MODULES_AUDIO_MIXER_FRAME_COMBINER_H_ +#include +#include #include -#include #include "api/array_view.h" #include "api/audio/audio_frame.h" diff --git a/modules/audio_mixer/gain_change_calculator.cc b/modules/audio_mixer/gain_change_calculator.cc index 729ab4b7d4..ff14baaa52 100644 --- a/modules/audio_mixer/gain_change_calculator.cc +++ b/modules/audio_mixer/gain_change_calculator.cc @@ -10,11 +10,12 @@ #include "modules/audio_mixer/gain_change_calculator.h" -#include - +#include +#include #include #include +#include "api/array_view.h" #include "rtc_base/checks.h" namespace webrtc { diff --git a/modules/audio_mixer/output_rate_calculator.h b/modules/audio_mixer/output_rate_calculator.h index 04ab82c12f..755da3285f 100644 --- a/modules/audio_mixer/output_rate_calculator.h +++ b/modules/audio_mixer/output_rate_calculator.h @@ -11,8 +11,6 @@ #ifndef MODULES_AUDIO_MIXER_OUTPUT_RATE_CALCULATOR_H_ #define MODULES_AUDIO_MIXER_OUTPUT_RATE_CALCULATOR_H_ -#include - #include "api/array_view.h" namespace webrtc { diff --git a/modules/audio_mixer/sine_wave_generator.cc b/modules/audio_mixer/sine_wave_generator.cc index be3dd0cfa6..6bb2b975d3 100644 --- a/modules/audio_mixer/sine_wave_generator.cc +++ b/modules/audio_mixer/sine_wave_generator.cc @@ -10,11 +10,13 @@ #include "modules/audio_mixer/sine_wave_generator.h" -#include -#include - +#include +#include +#include #include +#include "api/audio/audio_frame.h" +#include "rtc_base/checks.h" #include "rtc_base/numerics/safe_conversions.h" namespace webrtc { diff --git a/modules/audio_processing/BUILD.gn b/modules/audio_processing/BUILD.gn index 2d92bc5178..20ee6256cc 100644 --- a/modules/audio_processing/BUILD.gn +++ b/modules/audio_processing/BUILD.gn @@ -35,6 +35,8 @@ rtc_library("audio_frame_proxies") { ":audio_frame_view", "../../api/audio:audio_frame_api", "../../api/audio:audio_processing", + "../../api/audio:audio_processing_statistics", + "../../rtc_base:checks", ] } @@ -310,9 +312,11 @@ if (rtc_include_tests) { ":aec_dump_interface", ":audio_buffer", ":audio_processing", + "../../api:array_view", "../../api:scoped_refptr", "../../api/audio:audio_processing", "../../api/audio:audio_processing_statistics", + "../../api/audio:echo_control", "../../api/environment", "../../api/task_queue", "../../test:test_support", @@ -363,6 +367,7 @@ if (rtc_include_tests) { ":post_filter", "../../api:array_view", "../../api:make_ref_counted", + "../../api:ref_count", "../../api:scoped_refptr", "../../api/audio:aec3_config", "../../api/audio:aec3_factory", @@ -373,9 +378,11 @@ if (rtc_include_tests) { "../../api/audio:echo_detector_creator", "../../api/environment", "../../api/environment:environment_factory", + "../../api/units:time_delta", "../../common_audio", "../../common_audio:common_audio_c", "../../rtc_base:checks", + "../../rtc_base:cpu_info", "../../rtc_base:denormal_disabler", "../../rtc_base:gtest_prod", "../../rtc_base:macromagic", @@ -393,7 +400,6 @@ if (rtc_include_tests) { "../../rtc_base/synchronization:mutex", "../../rtc_base/system:arch", "../../rtc_base/system:file_wrapper", - "../../system_wrappers", "../../test:field_trial", "../../test:fileutils", "../../test:rtc_expect_death", @@ -401,16 +407,20 @@ if (rtc_include_tests) { "../audio_coding:neteq_input_audio_tools", "aec_dump:mock_aec_dump_unittests", "agc:agc_unittests", + "agc:gain_control_interface", "agc2:adaptive_digital_gain_controller_unittest", "agc2:biquad_filter_unittests", + "agc2:cpu_features", "agc2:fixed_digital_unittests", "agc2:gain_applier_unittest", + "agc2:input_volume_controller", "agc2:input_volume_controller_unittests", "agc2:input_volume_stats_reporter_unittests", "agc2:noise_estimator_unittests", "agc2:saturation_protector_unittest", "agc2:speech_level_estimator_unittest", "agc2:test_utils", + "agc2:vad_wrapper", "agc2:vad_wrapper_unittests", "agc2/rnn_vad:unittests", "capture_levels_adjuster", @@ -484,11 +494,15 @@ if (rtc_include_tests) { ":audio_processing", ":audioproc_test_utils", "../../api:array_view", + "../../api:scoped_refptr", + "../../api/audio:audio_processing", "../../api/audio:builtin_audio_processing_builder", "../../api/environment:environment_factory", "../../api/numerics", "../../api/test/metrics:global_metrics_logger_and_exporter", "../../api/test/metrics:metric", + "../../api/units:time_delta", + "../../rtc_base:checks", "../../rtc_base:platform_thread", "../../rtc_base:protobuf_utils", "../../rtc_base:random", diff --git a/modules/audio_processing/aec3/BUILD.gn b/modules/audio_processing/aec3/BUILD.gn index a0bda5f494..e643570330 100644 --- a/modules/audio_processing/aec3/BUILD.gn +++ b/modules/audio_processing/aec3/BUILD.gn @@ -147,6 +147,8 @@ rtc_library("aec3") { "../../../api/environment", "../../../common_audio:common_audio_c", "../../../rtc_base:checks", + "../../../rtc_base:cpu_info", + "../../../rtc_base:gtest_prod", "../../../rtc_base:logging", "../../../rtc_base:macromagic", "../../../rtc_base:race_checker", @@ -154,7 +156,6 @@ rtc_library("aec3") { "../../../rtc_base:swap_queue", "../../../rtc_base/experiments:field_trial_parser", "../../../rtc_base/system:arch", - "../../../system_wrappers", "../../../system_wrappers:metrics", "../utility:cascaded_biquad_filter", "//third_party/abseil-cpp/absl/strings:string_view", @@ -246,6 +247,7 @@ rtc_source_set("fft_data") { deps = [ ":aec3_common", "../../../api:array_view", + "../../../rtc_base:checks", "../../../rtc_base/system:arch", ] } @@ -273,8 +275,10 @@ if (current_cpu == "x86" || current_cpu == "x64") { deps = [ ":adaptive_fir_filter", ":adaptive_fir_filter_erl", + ":aec3_common", ":fft_data", ":matched_filter", + ":render_buffer", ":vector_math", "../../../api:array_view", "../../../rtc_base:checks", @@ -314,15 +318,15 @@ if (rtc_include_tests) { "..:high_pass_filter", "../../../api:array_view", "../../../api/audio:aec3_config", + "../../../api/audio:echo_control", "../../../api/environment", "../../../api/environment:environment_factory", "../../../rtc_base:checks", - "../../../rtc_base:macromagic", + "../../../rtc_base:cpu_info", "../../../rtc_base:random", "../../../rtc_base:safe_minmax", "../../../rtc_base:stringutils", "../../../rtc_base/system:arch", - "../../../system_wrappers", "../../../system_wrappers:metrics", "../../../test:explicit_key_value_config", "../../../test:field_trial", diff --git a/modules/audio_processing/aec3/adaptive_fir_filter.cc b/modules/audio_processing/aec3/adaptive_fir_filter.cc index e6e1de47b4..6a2e3ba712 100644 --- a/modules/audio_processing/aec3/adaptive_fir_filter.cc +++ b/modules/audio_processing/aec3/adaptive_fir_filter.cc @@ -10,29 +10,27 @@ #include "modules/audio_processing/aec3/adaptive_fir_filter.h" +#include #include +#include #include #include -// Defines WEBRTC_ARCH_X86_FAMILY, used below. #include "api/array_view.h" #include "modules/audio_processing/aec3/aec3_common.h" +#include "modules/audio_processing/aec3/fft_data.h" #include "modules/audio_processing/aec3/render_buffer.h" #include "modules/audio_processing/logging/apm_data_dumper.h" -#include "rtc_base/system/arch.h" +#include "rtc_base/checks.h" +// Defines WEBRTC_ARCH_X86_FAMILY, used below. +#include "rtc_base/system/arch.h" #if defined(WEBRTC_HAS_NEON) #include #endif #if defined(WEBRTC_ARCH_X86_FAMILY) #include #endif -#include - -#include - -#include "modules/audio_processing/aec3/fft_data.h" -#include "rtc_base/checks.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/adaptive_fir_filter_avx2.cc b/modules/audio_processing/aec3/adaptive_fir_filter_avx2.cc index 9f720a5abf..f7ba1fda86 100644 --- a/modules/audio_processing/aec3/adaptive_fir_filter_avx2.cc +++ b/modules/audio_processing/aec3/adaptive_fir_filter_avx2.cc @@ -10,7 +10,16 @@ #include +#include +#include +#include +#include + +#include "api/array_view.h" #include "modules/audio_processing/aec3/adaptive_fir_filter.h" +#include "modules/audio_processing/aec3/aec3_common.h" +#include "modules/audio_processing/aec3/fft_data.h" +#include "modules/audio_processing/aec3/render_buffer.h" #include "rtc_base/checks.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/adaptive_fir_filter_erl.cc b/modules/audio_processing/aec3/adaptive_fir_filter_erl.cc index 9bf7bc7de1..11f83af7fe 100644 --- a/modules/audio_processing/aec3/adaptive_fir_filter_erl.cc +++ b/modules/audio_processing/aec3/adaptive_fir_filter_erl.cc @@ -11,8 +11,17 @@ #include "modules/audio_processing/aec3/adaptive_fir_filter_erl.h" #include +#include +#include #include +#include +#include "api/array_view.h" +#include "modules/audio_processing/aec3/aec3_common.h" +#include "rtc_base/checks.h" + +// Defines WEBRTC_ARCH_X86_FAMILY, used below. +#include "rtc_base/system/arch.h" #if defined(WEBRTC_HAS_NEON) #include #endif diff --git a/modules/audio_processing/aec3/adaptive_fir_filter_erl_avx2.cc b/modules/audio_processing/aec3/adaptive_fir_filter_erl_avx2.cc index dbcaa9acb7..6abbcaec5a 100644 --- a/modules/audio_processing/aec3/adaptive_fir_filter_erl_avx2.cc +++ b/modules/audio_processing/aec3/adaptive_fir_filter_erl_avx2.cc @@ -10,7 +10,14 @@ #include +#include +#include +#include +#include + +#include "api/array_view.h" #include "modules/audio_processing/aec3/adaptive_fir_filter_erl.h" +#include "modules/audio_processing/aec3/aec3_common.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/adaptive_fir_filter_erl_unittest.cc b/modules/audio_processing/aec3/adaptive_fir_filter_erl_unittest.cc index d2af70a9f2..d95aad1a24 100644 --- a/modules/audio_processing/aec3/adaptive_fir_filter_erl_unittest.cc +++ b/modules/audio_processing/aec3/adaptive_fir_filter_erl_unittest.cc @@ -11,16 +11,19 @@ #include "modules/audio_processing/aec3/adaptive_fir_filter_erl.h" #include +#include #include +#include "modules/audio_processing/aec3/aec3_common.h" +#include "rtc_base/cpu_info.h" +#include "test/gtest.h" + +// Defines WEBRTC_ARCH_X86_FAMILY, used below. #include "rtc_base/system/arch.h" #if defined(WEBRTC_ARCH_X86_FAMILY) #include #endif -#include "system_wrappers/include/cpu_features_wrapper.h" -#include "test/gtest.h" - namespace webrtc { namespace aec3 { @@ -53,7 +56,7 @@ TEST(AdaptiveFirFilter, UpdateErlNeonOptimization) { // Verifies that the optimized method for echo return loss computation is // bitexact to the reference counterpart. TEST(AdaptiveFirFilter, UpdateErlSse2Optimization) { - bool use_sse2 = (GetCPUInfo(kSSE2) != 0); + bool use_sse2 = cpu_info::Supports(cpu_info::ISA::kSSE2); if (use_sse2) { const size_t kNumPartitions = 12; std::vector> H2(kNumPartitions); @@ -78,7 +81,7 @@ TEST(AdaptiveFirFilter, UpdateErlSse2Optimization) { // Verifies that the optimized method for echo return loss computation is // bitexact to the reference counterpart. TEST(AdaptiveFirFilter, UpdateErlAvx2Optimization) { - bool use_avx2 = (GetCPUInfo(kAVX2) != 0); + bool use_avx2 = cpu_info::Supports(cpu_info::ISA::kAVX2); if (use_avx2) { const size_t kNumPartitions = 12; std::vector> H2(kNumPartitions); diff --git a/modules/audio_processing/aec3/adaptive_fir_filter_unittest.cc b/modules/audio_processing/aec3/adaptive_fir_filter_unittest.cc index d229abea32..a645aa688a 100644 --- a/modules/audio_processing/aec3/adaptive_fir_filter_unittest.cc +++ b/modules/audio_processing/aec3/adaptive_fir_filter_unittest.cc @@ -10,9 +10,6 @@ #include "modules/audio_processing/aec3/adaptive_fir_filter.h" -// Defines WEBRTC_ARCH_X86_FAMILY, used below. -#include - #include #include #include @@ -25,34 +22,35 @@ #include "api/array_view.h" #include "api/audio/echo_canceller3_config.h" -#include "modules/audio_processing/aec3/aec3_common.h" -#include "modules/audio_processing/aec3/block.h" -#include "modules/audio_processing/aec3/delay_estimate.h" -#include "modules/audio_processing/aec3/echo_path_variability.h" -#include "modules/audio_processing/aec3/fft_data.h" -#include "modules/audio_processing/aec3/subtractor_output.h" -#include "rtc_base/checks.h" -#include "rtc_base/system/arch.h" -#if defined(WEBRTC_ARCH_X86_FAMILY) -#include -#endif - #include "api/environment/environment_factory.h" #include "modules/audio_processing/aec3/adaptive_fir_filter_erl.h" +#include "modules/audio_processing/aec3/aec3_common.h" #include "modules/audio_processing/aec3/aec3_fft.h" #include "modules/audio_processing/aec3/aec_state.h" +#include "modules/audio_processing/aec3/block.h" #include "modules/audio_processing/aec3/coarse_filter_update_gain.h" +#include "modules/audio_processing/aec3/delay_estimate.h" +#include "modules/audio_processing/aec3/echo_path_variability.h" +#include "modules/audio_processing/aec3/fft_data.h" #include "modules/audio_processing/aec3/render_delay_buffer.h" #include "modules/audio_processing/aec3/render_signal_analyzer.h" +#include "modules/audio_processing/aec3/subtractor_output.h" #include "modules/audio_processing/logging/apm_data_dumper.h" #include "modules/audio_processing/test/echo_canceller_test_tools.h" #include "modules/audio_processing/utility/cascaded_biquad_filter.h" +#include "rtc_base/checks.h" +#include "rtc_base/cpu_info.h" #include "rtc_base/numerics/safe_minmax.h" #include "rtc_base/random.h" #include "rtc_base/strings/string_builder.h" -#include "system_wrappers/include/cpu_features_wrapper.h" #include "test/gtest.h" +// Defines WEBRTC_ARCH_X86_FAMILY, used below. +#include "rtc_base/system/arch.h" +#if defined(WEBRTC_ARCH_X86_FAMILY) +#include +#endif + namespace webrtc { namespace aec3 { namespace { @@ -191,7 +189,7 @@ TEST_P(AdaptiveFirFilterOneTwoFourEightRenderChannels, constexpr int kSampleRateHz = 48000; constexpr size_t kNumBands = NumBandsForRate(kSampleRateHz); - bool use_sse2 = (GetCPUInfo(kSSE2) != 0); + bool use_sse2 = cpu_info::Supports(cpu_info::ISA::kSSE2); if (use_sse2) { for (size_t num_partitions : {2, 5, 12, 30, 50}) { std::unique_ptr render_delay_buffer( @@ -263,7 +261,7 @@ TEST_P(AdaptiveFirFilterOneTwoFourEightRenderChannels, constexpr int kSampleRateHz = 48000; constexpr size_t kNumBands = NumBandsForRate(kSampleRateHz); - bool use_avx2 = (GetCPUInfo(kAVX2) != 0); + bool use_avx2 = cpu_info::Supports(cpu_info::ISA::kAVX2); if (use_avx2) { for (size_t num_partitions : {2, 5, 12, 30, 50}) { std::unique_ptr render_delay_buffer( @@ -332,7 +330,7 @@ TEST_P(AdaptiveFirFilterOneTwoFourEightRenderChannels, TEST_P(AdaptiveFirFilterOneTwoFourEightRenderChannels, ComputeFrequencyResponseSse2Optimization) { const size_t num_render_channels = GetParam(); - bool use_sse2 = (GetCPUInfo(kSSE2) != 0); + bool use_sse2 = cpu_info::Supports(cpu_info::ISA::kSSE2); if (use_sse2) { for (size_t num_partitions : {2, 5, 12, 30, 50}) { std::vector> H( @@ -367,7 +365,7 @@ TEST_P(AdaptiveFirFilterOneTwoFourEightRenderChannels, TEST_P(AdaptiveFirFilterOneTwoFourEightRenderChannels, ComputeFrequencyResponseAvx2Optimization) { const size_t num_render_channels = GetParam(); - bool use_avx2 = (GetCPUInfo(kAVX2) != 0); + bool use_avx2 = cpu_info::Supports(cpu_info::ISA::kAVX2); if (use_avx2) { for (size_t num_partitions : {2, 5, 12, 30, 50}) { std::vector> H( diff --git a/modules/audio_processing/aec3/aec3_common.cc b/modules/audio_processing/aec3/aec3_common.cc index 3ba10d5baf..4fb1f547c2 100644 --- a/modules/audio_processing/aec3/aec3_common.cc +++ b/modules/audio_processing/aec3/aec3_common.cc @@ -13,16 +13,16 @@ #include #include "rtc_base/checks.h" +#include "rtc_base/cpu_info.h" #include "rtc_base/system/arch.h" -#include "system_wrappers/include/cpu_features_wrapper.h" namespace webrtc { Aec3Optimization DetectOptimization() { #if defined(WEBRTC_ARCH_X86_FAMILY) - if (GetCPUInfo(kAVX2) != 0) { + if (cpu_info::Supports(cpu_info::ISA::kAVX2)) { return Aec3Optimization::kAvx2; - } else if (GetCPUInfo(kSSE2) != 0) { + } else if (cpu_info::Supports(cpu_info::ISA::kSSE2)) { return Aec3Optimization::kSse2; } #endif diff --git a/modules/audio_processing/aec3/aec3_fft.cc b/modules/audio_processing/aec3/aec3_fft.cc index 1c4cf33c3b..7652e306a0 100644 --- a/modules/audio_processing/aec3/aec3_fft.cc +++ b/modules/audio_processing/aec3/aec3_fft.cc @@ -11,11 +11,15 @@ #include "modules/audio_processing/aec3/aec3_fft.h" #include +#include #include #include +#include "api/array_view.h" +#include "modules/audio_processing/aec3/aec3_common.h" +#include "modules/audio_processing/aec3/fft_data.h" #include "rtc_base/checks.h" -#include "system_wrappers/include/cpu_features_wrapper.h" +#include "rtc_base/cpu_info.h" namespace webrtc { @@ -73,7 +77,7 @@ const float kSqrtHanning128[kFftLength] = { bool IsSse2Available() { #if defined(WEBRTC_ARCH_X86_FAMILY) - return GetCPUInfo(kSSE2) != 0; + return cpu_info::Supports(cpu_info::ISA::kSSE2); #else return false; #endif diff --git a/modules/audio_processing/aec3/aec3_fft_unittest.cc b/modules/audio_processing/aec3/aec3_fft_unittest.cc index e60ef5b713..4372cc440c 100644 --- a/modules/audio_processing/aec3/aec3_fft_unittest.cc +++ b/modules/audio_processing/aec3/aec3_fft_unittest.cc @@ -11,7 +11,12 @@ #include "modules/audio_processing/aec3/aec3_fft.h" #include +#include +#include +#include "modules/audio_processing/aec3/aec3_common.h" +#include "modules/audio_processing/aec3/fft_data.h" +#include "rtc_base/checks.h" #include "test/gmock.h" #include "test/gtest.h" diff --git a/modules/audio_processing/aec3/aec_state.cc b/modules/audio_processing/aec3/aec_state.cc index cc8642dc32..8856c4e6f0 100644 --- a/modules/audio_processing/aec3/aec_state.cc +++ b/modules/audio_processing/aec3/aec_state.cc @@ -13,14 +13,26 @@ #include #include +#include +#include +#include #include #include #include #include "api/array_view.h" +#include "api/audio/echo_canceller3_config.h" #include "api/environment/environment.h" #include "api/field_trials_view.h" #include "modules/audio_processing/aec3/aec3_common.h" +#include "modules/audio_processing/aec3/block.h" +#include "modules/audio_processing/aec3/delay_estimate.h" +#include "modules/audio_processing/aec3/echo_path_variability.h" +#include "modules/audio_processing/aec3/render_buffer.h" +#include "modules/audio_processing/aec3/reverb_model.h" +#include "modules/audio_processing/aec3/spectrum_buffer.h" +#include "modules/audio_processing/aec3/subtractor_output.h" +#include "modules/audio_processing/aec3/transparent_mode.h" #include "modules/audio_processing/logging/apm_data_dumper.h" #include "rtc_base/checks.h" diff --git a/modules/audio_processing/aec3/aec_state.h b/modules/audio_processing/aec3/aec_state.h index bd7050c3fd..407d3e9598 100644 --- a/modules/audio_processing/aec3/aec_state.h +++ b/modules/audio_processing/aec3/aec_state.h @@ -23,6 +23,7 @@ #include "api/audio/echo_canceller3_config.h" #include "api/environment/environment.h" #include "modules/audio_processing/aec3/aec3_common.h" +#include "modules/audio_processing/aec3/block.h" #include "modules/audio_processing/aec3/delay_estimate.h" #include "modules/audio_processing/aec3/echo_audibility.h" #include "modules/audio_processing/aec3/echo_path_variability.h" @@ -30,6 +31,7 @@ #include "modules/audio_processing/aec3/erle_estimator.h" #include "modules/audio_processing/aec3/filter_analyzer.h" #include "modules/audio_processing/aec3/render_buffer.h" +#include "modules/audio_processing/aec3/reverb_model.h" #include "modules/audio_processing/aec3/reverb_model_estimator.h" #include "modules/audio_processing/aec3/subtractor_output.h" #include "modules/audio_processing/aec3/subtractor_output_analyzer.h" diff --git a/modules/audio_processing/aec3/aec_state_unittest.cc b/modules/audio_processing/aec3/aec_state_unittest.cc index f96828c6d9..54a3c97aa5 100644 --- a/modules/audio_processing/aec3/aec_state_unittest.cc +++ b/modules/audio_processing/aec3/aec_state_unittest.cc @@ -10,12 +10,24 @@ #include "modules/audio_processing/aec3/aec_state.h" -#include "api/environment/environment.h" +#include +#include +#include +#include +#include +#include +#include + +#include "api/audio/echo_canceller3_config.h" #include "api/environment/environment_factory.h" +#include "modules/audio_processing/aec3/aec3_common.h" #include "modules/audio_processing/aec3/aec3_fft.h" +#include "modules/audio_processing/aec3/block.h" +#include "modules/audio_processing/aec3/delay_estimate.h" +#include "modules/audio_processing/aec3/echo_path_variability.h" #include "modules/audio_processing/aec3/render_delay_buffer.h" +#include "modules/audio_processing/aec3/subtractor_output.h" #include "modules/audio_processing/logging/apm_data_dumper.h" -#include "rtc_base/strings/string_builder.h" #include "test/gtest.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/alignment_mixer.cc b/modules/audio_processing/aec3/alignment_mixer.cc index 728e0f7bb8..0370aebcaf 100644 --- a/modules/audio_processing/aec3/alignment_mixer.cc +++ b/modules/audio_processing/aec3/alignment_mixer.cc @@ -10,7 +10,13 @@ #include "modules/audio_processing/aec3/alignment_mixer.h" #include +#include +#include +#include "api/array_view.h" +#include "api/audio/echo_canceller3_config.h" +#include "modules/audio_processing/aec3/aec3_common.h" +#include "modules/audio_processing/aec3/block.h" #include "rtc_base/checks.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/alignment_mixer.h b/modules/audio_processing/aec3/alignment_mixer.h index 238f9a0ecf..29bf14b675 100644 --- a/modules/audio_processing/aec3/alignment_mixer.h +++ b/modules/audio_processing/aec3/alignment_mixer.h @@ -11,6 +11,8 @@ #ifndef MODULES_AUDIO_PROCESSING_AEC3_ALIGNMENT_MIXER_H_ #define MODULES_AUDIO_PROCESSING_AEC3_ALIGNMENT_MIXER_H_ +#include +#include #include #include "api/array_view.h" diff --git a/modules/audio_processing/aec3/alignment_mixer_unittest.cc b/modules/audio_processing/aec3/alignment_mixer_unittest.cc index ef2abee9ff..d621e390c1 100644 --- a/modules/audio_processing/aec3/alignment_mixer_unittest.cc +++ b/modules/audio_processing/aec3/alignment_mixer_unittest.cc @@ -10,10 +10,15 @@ #include "modules/audio_processing/aec3/alignment_mixer.h" +#include +#include +#include #include #include "api/array_view.h" #include "modules/audio_processing/aec3/aec3_common.h" +#include "modules/audio_processing/aec3/block.h" +#include "rtc_base/checks.h" #include "rtc_base/strings/string_builder.h" #include "test/gmock.h" #include "test/gtest.h" diff --git a/modules/audio_processing/aec3/api_call_jitter_metrics.cc b/modules/audio_processing/aec3/api_call_jitter_metrics.cc index 45f56a5dce..4e25ffe160 100644 --- a/modules/audio_processing/aec3/api_call_jitter_metrics.cc +++ b/modules/audio_processing/aec3/api_call_jitter_metrics.cc @@ -13,7 +13,6 @@ #include #include -#include "modules/audio_processing/aec3/aec3_common.h" #include "system_wrappers/include/metrics.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/api_call_jitter_metrics_unittest.cc b/modules/audio_processing/aec3/api_call_jitter_metrics_unittest.cc index b902487152..a9e4d9149d 100644 --- a/modules/audio_processing/aec3/api_call_jitter_metrics_unittest.cc +++ b/modules/audio_processing/aec3/api_call_jitter_metrics_unittest.cc @@ -10,6 +10,8 @@ #include "modules/audio_processing/aec3/api_call_jitter_metrics.h" +#include + #include "modules/audio_processing/aec3/aec3_common.h" #include "test/gtest.h" diff --git a/modules/audio_processing/aec3/block.h b/modules/audio_processing/aec3/block.h index 3f0f4f6be6..75f032d0f2 100644 --- a/modules/audio_processing/aec3/block.h +++ b/modules/audio_processing/aec3/block.h @@ -11,7 +11,8 @@ #ifndef MODULES_AUDIO_PROCESSING_AEC3_BLOCK_H_ #define MODULES_AUDIO_PROCESSING_AEC3_BLOCK_H_ -#include +#include +#include #include #include "api/array_view.h" diff --git a/modules/audio_processing/aec3/block_buffer.cc b/modules/audio_processing/aec3/block_buffer.cc index 289c3f0d10..1409a46df1 100644 --- a/modules/audio_processing/aec3/block_buffer.cc +++ b/modules/audio_processing/aec3/block_buffer.cc @@ -10,7 +10,9 @@ #include "modules/audio_processing/aec3/block_buffer.h" -#include +#include + +#include "modules/audio_processing/aec3/block.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/block_delay_buffer.cc b/modules/audio_processing/aec3/block_delay_buffer.cc index c599b3924d..3d67aae6cb 100644 --- a/modules/audio_processing/aec3/block_delay_buffer.cc +++ b/modules/audio_processing/aec3/block_delay_buffer.cc @@ -9,7 +9,11 @@ */ #include "modules/audio_processing/aec3/block_delay_buffer.h" +#include +#include + #include "api/array_view.h" +#include "modules/audio_processing/audio_buffer.h" #include "rtc_base/checks.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/block_delay_buffer_unittest.cc b/modules/audio_processing/aec3/block_delay_buffer_unittest.cc index f12508485d..68a6db9103 100644 --- a/modules/audio_processing/aec3/block_delay_buffer_unittest.cc +++ b/modules/audio_processing/aec3/block_delay_buffer_unittest.cc @@ -10,7 +10,9 @@ #include "modules/audio_processing/aec3/block_delay_buffer.h" +#include #include +#include #include "modules/audio_processing/aec3/aec3_common.h" #include "modules/audio_processing/audio_buffer.h" diff --git a/modules/audio_processing/aec3/block_framer.cc b/modules/audio_processing/aec3/block_framer.cc index 6ce39c1a9e..58d1effba7 100644 --- a/modules/audio_processing/aec3/block_framer.cc +++ b/modules/audio_processing/aec3/block_framer.cc @@ -11,8 +11,12 @@ #include "modules/audio_processing/aec3/block_framer.h" #include +#include +#include +#include "api/array_view.h" #include "modules/audio_processing/aec3/aec3_common.h" +#include "modules/audio_processing/aec3/block.h" #include "rtc_base/checks.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/block_framer.h b/modules/audio_processing/aec3/block_framer.h index e45a83841e..c7ddc4987e 100644 --- a/modules/audio_processing/aec3/block_framer.h +++ b/modules/audio_processing/aec3/block_framer.h @@ -11,10 +11,10 @@ #ifndef MODULES_AUDIO_PROCESSING_AEC3_BLOCK_FRAMER_H_ #define MODULES_AUDIO_PROCESSING_AEC3_BLOCK_FRAMER_H_ +#include #include #include "api/array_view.h" -#include "modules/audio_processing/aec3/aec3_common.h" #include "modules/audio_processing/aec3/block.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/block_framer_unittest.cc b/modules/audio_processing/aec3/block_framer_unittest.cc index d45b96e980..b898f32db6 100644 --- a/modules/audio_processing/aec3/block_framer_unittest.cc +++ b/modules/audio_processing/aec3/block_framer_unittest.cc @@ -10,10 +10,14 @@ #include "modules/audio_processing/aec3/block_framer.h" +#include #include #include +#include "api/array_view.h" #include "modules/audio_processing/aec3/aec3_common.h" +#include "modules/audio_processing/aec3/block.h" +#include "rtc_base/checks.h" #include "rtc_base/strings/string_builder.h" #include "test/gtest.h" diff --git a/modules/audio_processing/aec3/block_processor.cc b/modules/audio_processing/aec3/block_processor.cc index c7f198e7a6..e92b8ed7b4 100644 --- a/modules/audio_processing/aec3/block_processor.cc +++ b/modules/audio_processing/aec3/block_processor.cc @@ -15,11 +15,12 @@ #include #include #include -#include #include "api/audio/echo_canceller3_config.h" #include "api/audio/echo_control.h" +#include "api/environment/environment.h" #include "modules/audio_processing/aec3/aec3_common.h" +#include "modules/audio_processing/aec3/block.h" #include "modules/audio_processing/aec3/block_processor_metrics.h" #include "modules/audio_processing/aec3/delay_estimate.h" #include "modules/audio_processing/aec3/echo_path_variability.h" diff --git a/modules/audio_processing/aec3/block_processor.h b/modules/audio_processing/aec3/block_processor.h index 06669ab977..254f287281 100644 --- a/modules/audio_processing/aec3/block_processor.h +++ b/modules/audio_processing/aec3/block_processor.h @@ -14,7 +14,6 @@ #include #include -#include #include "api/audio/echo_canceller3_config.h" #include "api/audio/echo_control.h" diff --git a/modules/audio_processing/aec3/block_processor_metrics.cc b/modules/audio_processing/aec3/block_processor_metrics.cc index deac1fcd22..c8bdda7389 100644 --- a/modules/audio_processing/aec3/block_processor_metrics.cc +++ b/modules/audio_processing/aec3/block_processor_metrics.cc @@ -11,7 +11,6 @@ #include "modules/audio_processing/aec3/block_processor_metrics.h" #include "modules/audio_processing/aec3/aec3_common.h" -#include "rtc_base/checks.h" #include "system_wrappers/include/metrics.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/block_processor_unittest.cc b/modules/audio_processing/aec3/block_processor_unittest.cc index eece30c9a7..9603751b76 100644 --- a/modules/audio_processing/aec3/block_processor_unittest.cc +++ b/modules/audio_processing/aec3/block_processor_unittest.cc @@ -10,16 +10,25 @@ #include "modules/audio_processing/aec3/block_processor.h" +#include #include +#include #include -#include +#include +#include "api/array_view.h" +#include "api/audio/echo_canceller3_config.h" #include "api/environment/environment.h" #include "api/environment/environment_factory.h" #include "modules/audio_processing/aec3/aec3_common.h" +#include "modules/audio_processing/aec3/block.h" +#include "modules/audio_processing/aec3/delay_estimate.h" +#include "modules/audio_processing/aec3/echo_path_variability.h" #include "modules/audio_processing/aec3/mock/mock_echo_remover.h" #include "modules/audio_processing/aec3/mock/mock_render_delay_buffer.h" #include "modules/audio_processing/aec3/mock/mock_render_delay_controller.h" +#include "modules/audio_processing/aec3/render_buffer.h" +#include "modules/audio_processing/aec3/render_delay_buffer.h" #include "modules/audio_processing/test/echo_canceller_test_tools.h" #include "rtc_base/checks.h" #include "rtc_base/random.h" diff --git a/modules/audio_processing/aec3/coarse_filter_update_gain.cc b/modules/audio_processing/aec3/coarse_filter_update_gain.cc index f4fb74d20d..d0771991ac 100644 --- a/modules/audio_processing/aec3/coarse_filter_update_gain.cc +++ b/modules/audio_processing/aec3/coarse_filter_update_gain.cc @@ -10,9 +10,13 @@ #include "modules/audio_processing/aec3/coarse_filter_update_gain.h" -#include -#include +#include +#include +#include "api/audio/echo_canceller3_config.h" +#include "modules/audio_processing/aec3/aec3_common.h" +#include "modules/audio_processing/aec3/fft_data.h" +#include "modules/audio_processing/aec3/render_signal_analyzer.h" #include "rtc_base/checks.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/coarse_filter_update_gain_unittest.cc b/modules/audio_processing/aec3/coarse_filter_update_gain_unittest.cc index 0f532b6e44..403caab575 100644 --- a/modules/audio_processing/aec3/coarse_filter_update_gain_unittest.cc +++ b/modules/audio_processing/aec3/coarse_filter_update_gain_unittest.cc @@ -11,16 +11,25 @@ #include "modules/audio_processing/aec3/coarse_filter_update_gain.h" #include +#include +#include #include #include #include #include +#include "api/audio/echo_canceller3_config.h" #include "modules/audio_processing/aec3/adaptive_fir_filter.h" #include "modules/audio_processing/aec3/aec3_common.h" +#include "modules/audio_processing/aec3/aec3_fft.h" #include "modules/audio_processing/aec3/aec_state.h" +#include "modules/audio_processing/aec3/block.h" +#include "modules/audio_processing/aec3/fft_buffer.h" +#include "modules/audio_processing/aec3/fft_data.h" #include "modules/audio_processing/aec3/render_delay_buffer.h" +#include "modules/audio_processing/aec3/render_signal_analyzer.h" #include "modules/audio_processing/test/echo_canceller_test_tools.h" +#include "rtc_base/checks.h" #include "rtc_base/numerics/safe_minmax.h" #include "rtc_base/random.h" #include "rtc_base/strings/string_builder.h" diff --git a/modules/audio_processing/aec3/comfort_noise_generator.cc b/modules/audio_processing/aec3/comfort_noise_generator.cc index 17a3b70d36..ce500a57d5 100644 --- a/modules/audio_processing/aec3/comfort_noise_generator.cc +++ b/modules/audio_processing/aec3/comfort_noise_generator.cc @@ -10,23 +10,27 @@ #include "modules/audio_processing/aec3/comfort_noise_generator.h" -// Defines WEBRTC_ARCH_X86_FAMILY, used below. -#include "rtc_base/system/arch.h" - -#if defined(WEBRTC_ARCH_X86_FAMILY) -#include -#endif #include #include #include +#include #include -#include +#include #include #include +#include -#include "common_audio/signal_processing/include/signal_processing_library.h" +#include "api/array_view.h" +#include "api/audio/echo_canceller3_config.h" +#include "modules/audio_processing/aec3/aec3_common.h" +#include "modules/audio_processing/aec3/fft_data.h" #include "modules/audio_processing/aec3/vector_math.h" -#include "rtc_base/checks.h" + +// Defines WEBRTC_ARCH_X86_FAMILY, used below. +#include "rtc_base/system/arch.h" +#if defined(WEBRTC_ARCH_X86_FAMILY) +#include +#endif namespace webrtc { diff --git a/modules/audio_processing/aec3/comfort_noise_generator.h b/modules/audio_processing/aec3/comfort_noise_generator.h index b5212fb68f..3672185f99 100644 --- a/modules/audio_processing/aec3/comfort_noise_generator.h +++ b/modules/audio_processing/aec3/comfort_noise_generator.h @@ -14,10 +14,13 @@ #include #include +#include #include +#include +#include "api/array_view.h" +#include "api/audio/echo_canceller3_config.h" #include "modules/audio_processing/aec3/aec3_common.h" -#include "modules/audio_processing/aec3/aec_state.h" #include "modules/audio_processing/aec3/fft_data.h" #include "rtc_base/system/arch.h" diff --git a/modules/audio_processing/aec3/comfort_noise_generator_unittest.cc b/modules/audio_processing/aec3/comfort_noise_generator_unittest.cc index b74e2afdff..17ce0477d7 100644 --- a/modules/audio_processing/aec3/comfort_noise_generator_unittest.cc +++ b/modules/audio_processing/aec3/comfort_noise_generator_unittest.cc @@ -10,15 +10,16 @@ #include "modules/audio_processing/aec3/comfort_noise_generator.h" -#include +#include +#include #include +#include #include "api/audio/echo_canceller3_config.h" #include "api/environment/environment_factory.h" +#include "modules/audio_processing/aec3/aec3_common.h" #include "modules/audio_processing/aec3/aec_state.h" -#include "rtc_base/random.h" -#include "rtc_base/system/arch.h" -#include "system_wrappers/include/cpu_features_wrapper.h" +#include "modules/audio_processing/aec3/fft_data.h" #include "test/gtest.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/config_selector.cc b/modules/audio_processing/aec3/config_selector.cc index e6bd8297ba..4e82dec7ee 100644 --- a/modules/audio_processing/aec3/config_selector.cc +++ b/modules/audio_processing/aec3/config_selector.cc @@ -11,6 +11,9 @@ #include "modules/audio_processing/aec3/config_selector.h" +#include + +#include "api/audio/echo_canceller3_config.h" #include "rtc_base/checks.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/config_selector_unittest.cc b/modules/audio_processing/aec3/config_selector_unittest.cc index 91a60d87ca..c459991ba1 100644 --- a/modules/audio_processing/aec3/config_selector_unittest.cc +++ b/modules/audio_processing/aec3/config_selector_unittest.cc @@ -10,6 +10,7 @@ #include "modules/audio_processing/aec3/config_selector.h" +#include #include #include diff --git a/modules/audio_processing/aec3/decimator.h b/modules/audio_processing/aec3/decimator.h index 69a022cee9..805616948f 100644 --- a/modules/audio_processing/aec3/decimator.h +++ b/modules/audio_processing/aec3/decimator.h @@ -11,11 +11,9 @@ #ifndef MODULES_AUDIO_PROCESSING_AEC3_DECIMATOR_H_ #define MODULES_AUDIO_PROCESSING_AEC3_DECIMATOR_H_ -#include -#include +#include #include "api/array_view.h" -#include "modules/audio_processing/aec3/aec3_common.h" #include "modules/audio_processing/utility/cascaded_biquad_filter.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/dominant_nearend_detector.cc b/modules/audio_processing/aec3/dominant_nearend_detector.cc index 815e1901f8..c37fa9a4ba 100644 --- a/modules/audio_processing/aec3/dominant_nearend_detector.cc +++ b/modules/audio_processing/aec3/dominant_nearend_detector.cc @@ -10,8 +10,16 @@ #include "modules/audio_processing/aec3/dominant_nearend_detector.h" +#include +#include +#include #include +#include "api/array_view.h" +#include "api/audio/echo_canceller3_config.h" +#include "modules/audio_processing/aec3/aec3_common.h" +#include "rtc_base/checks.h" + namespace webrtc { DominantNearendDetector::DominantNearendDetector( const EchoCanceller3Config::Suppressor::DominantNearendDetection& config, diff --git a/modules/audio_processing/aec3/dominant_nearend_detector.h b/modules/audio_processing/aec3/dominant_nearend_detector.h index 625f3d0af3..afd1516042 100644 --- a/modules/audio_processing/aec3/dominant_nearend_detector.h +++ b/modules/audio_processing/aec3/dominant_nearend_detector.h @@ -11,10 +11,13 @@ #ifndef MODULES_AUDIO_PROCESSING_AEC3_DOMINANT_NEAREND_DETECTOR_H_ #define MODULES_AUDIO_PROCESSING_AEC3_DOMINANT_NEAREND_DETECTOR_H_ +#include +#include #include #include "api/array_view.h" #include "api/audio/echo_canceller3_config.h" +#include "modules/audio_processing/aec3/aec3_common.h" #include "modules/audio_processing/aec3/nearend_detector.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/downsampled_render_buffer.cc b/modules/audio_processing/aec3/downsampled_render_buffer.cc index c105911aa8..9fcd70fe84 100644 --- a/modules/audio_processing/aec3/downsampled_render_buffer.cc +++ b/modules/audio_processing/aec3/downsampled_render_buffer.cc @@ -11,6 +11,7 @@ #include "modules/audio_processing/aec3/downsampled_render_buffer.h" #include +#include namespace webrtc { diff --git a/modules/audio_processing/aec3/echo_audibility.cc b/modules/audio_processing/aec3/echo_audibility.cc index b0c26ba39c..6853f51126 100644 --- a/modules/audio_processing/aec3/echo_audibility.cc +++ b/modules/audio_processing/aec3/echo_audibility.cc @@ -12,11 +12,14 @@ #include #include +#include #include #include #include "api/array_view.h" +#include "modules/audio_processing/aec3/aec3_common.h" #include "modules/audio_processing/aec3/block_buffer.h" +#include "modules/audio_processing/aec3/render_buffer.h" #include "modules/audio_processing/aec3/spectrum_buffer.h" #include "modules/audio_processing/aec3/stationarity_estimator.h" diff --git a/modules/audio_processing/aec3/echo_canceller3.h b/modules/audio_processing/aec3/echo_canceller3.h index a10cb13785..c9f528cec1 100644 --- a/modules/audio_processing/aec3/echo_canceller3.h +++ b/modules/audio_processing/aec3/echo_canceller3.h @@ -24,6 +24,7 @@ #include "api/environment/environment.h" #include "api/field_trials_view.h" #include "modules/audio_processing/aec3/api_call_jitter_metrics.h" +#include "modules/audio_processing/aec3/block.h" #include "modules/audio_processing/aec3/block_delay_buffer.h" #include "modules/audio_processing/aec3/block_framer.h" #include "modules/audio_processing/aec3/block_processor.h" @@ -32,7 +33,7 @@ #include "modules/audio_processing/aec3/multi_channel_content_detector.h" #include "modules/audio_processing/audio_buffer.h" #include "modules/audio_processing/logging/apm_data_dumper.h" -#include "rtc_base/checks.h" +#include "rtc_base/gtest_prod_util.h" #include "rtc_base/race_checker.h" #include "rtc_base/swap_queue.h" #include "rtc_base/thread_annotations.h" diff --git a/modules/audio_processing/aec3/echo_canceller3_unittest.cc b/modules/audio_processing/aec3/echo_canceller3_unittest.cc index f0fa73de42..01e1d9f6cc 100644 --- a/modules/audio_processing/aec3/echo_canceller3_unittest.cc +++ b/modules/audio_processing/aec3/echo_canceller3_unittest.cc @@ -10,21 +10,28 @@ #include "modules/audio_processing/aec3/echo_canceller3.h" +#include +#include #include #include +#include #include #include #include +#include "api/array_view.h" +#include "api/audio/echo_canceller3_config.h" +#include "api/audio/echo_control.h" #include "api/environment/environment.h" #include "api/environment/environment_factory.h" #include "modules/audio_processing/aec3/aec3_common.h" +#include "modules/audio_processing/aec3/block.h" #include "modules/audio_processing/aec3/block_processor.h" -#include "modules/audio_processing/aec3/frame_blocker.h" #include "modules/audio_processing/aec3/mock/mock_block_processor.h" #include "modules/audio_processing/audio_buffer.h" #include "modules/audio_processing/high_pass_filter.h" -#include "modules/audio_processing/utility/cascaded_biquad_filter.h" +#include "modules/audio_processing/logging/apm_data_dumper.h" +#include "rtc_base/checks.h" #include "rtc_base/strings/string_builder.h" #include "test/explicit_key_value_config.h" #include "test/gmock.h" @@ -133,7 +140,7 @@ class CaptureTransportVerificationProcessor : public BlockProcessor { void SetAudioBufferDelay(int /* delay_ms */) override {} - void SetCaptureOutputUsage(bool /* capture_output_used */) {} + void SetCaptureOutputUsage(bool /* capture_output_used */) override {} }; // Class for testing that the render data is properly received by the block @@ -169,7 +176,7 @@ class RenderTransportVerificationProcessor : public BlockProcessor { void SetAudioBufferDelay(int /* delay_ms */) override {} - void SetCaptureOutputUsage(bool /* capture_output_used */) {} + void SetCaptureOutputUsage(bool /* capture_output_used */) override {} private: std::deque received_render_blocks_; diff --git a/modules/audio_processing/aec3/echo_path_delay_estimator.cc b/modules/audio_processing/aec3/echo_path_delay_estimator.cc index 32eb5d8f6a..30b66896b3 100644 --- a/modules/audio_processing/aec3/echo_path_delay_estimator.cc +++ b/modules/audio_processing/aec3/echo_path_delay_estimator.cc @@ -10,9 +10,14 @@ #include "modules/audio_processing/aec3/echo_path_delay_estimator.h" #include +#include +#include +#include "api/array_view.h" #include "api/audio/echo_canceller3_config.h" #include "modules/audio_processing/aec3/aec3_common.h" +#include "modules/audio_processing/aec3/block.h" +#include "modules/audio_processing/aec3/delay_estimate.h" #include "modules/audio_processing/aec3/downsampled_render_buffer.h" #include "modules/audio_processing/logging/apm_data_dumper.h" #include "rtc_base/checks.h" diff --git a/modules/audio_processing/aec3/echo_path_delay_estimator.h b/modules/audio_processing/aec3/echo_path_delay_estimator.h index bd5c3b0697..657e0a75c4 100644 --- a/modules/audio_processing/aec3/echo_path_delay_estimator.h +++ b/modules/audio_processing/aec3/echo_path_delay_estimator.h @@ -11,11 +11,9 @@ #ifndef MODULES_AUDIO_PROCESSING_AEC3_ECHO_PATH_DELAY_ESTIMATOR_H_ #define MODULES_AUDIO_PROCESSING_AEC3_ECHO_PATH_DELAY_ESTIMATOR_H_ -#include - +#include #include -#include "api/array_view.h" #include "modules/audio_processing/aec3/alignment_mixer.h" #include "modules/audio_processing/aec3/block.h" #include "modules/audio_processing/aec3/clockdrift_detector.h" diff --git a/modules/audio_processing/aec3/echo_remover.cc b/modules/audio_processing/aec3/echo_remover.cc index c19da94dbc..7863cab627 100644 --- a/modules/audio_processing/aec3/echo_remover.cc +++ b/modules/audio_processing/aec3/echo_remover.cc @@ -9,21 +9,25 @@ */ #include "modules/audio_processing/aec3/echo_remover.h" -#include -#include - #include #include #include #include +#include #include +#include +#include #include "api/array_view.h" +#include "api/audio/echo_canceller3_config.h" +#include "api/audio/echo_control.h" #include "api/environment/environment.h" #include "modules/audio_processing/aec3/aec3_common.h" #include "modules/audio_processing/aec3/aec3_fft.h" #include "modules/audio_processing/aec3/aec_state.h" +#include "modules/audio_processing/aec3/block.h" #include "modules/audio_processing/aec3/comfort_noise_generator.h" +#include "modules/audio_processing/aec3/delay_estimate.h" #include "modules/audio_processing/aec3/echo_path_variability.h" #include "modules/audio_processing/aec3/echo_remover_metrics.h" #include "modules/audio_processing/aec3/fft_data.h" diff --git a/modules/audio_processing/aec3/echo_remover.h b/modules/audio_processing/aec3/echo_remover.h index 18a7bc3cfa..ff6fcce320 100644 --- a/modules/audio_processing/aec3/echo_remover.h +++ b/modules/audio_processing/aec3/echo_remover.h @@ -11,9 +11,9 @@ #ifndef MODULES_AUDIO_PROCESSING_AEC3_ECHO_REMOVER_H_ #define MODULES_AUDIO_PROCESSING_AEC3_ECHO_REMOVER_H_ +#include #include #include -#include #include "api/audio/echo_canceller3_config.h" #include "api/audio/echo_control.h" diff --git a/modules/audio_processing/aec3/echo_remover_metrics.cc b/modules/audio_processing/aec3/echo_remover_metrics.cc index aa13da9abd..fce3964da5 100644 --- a/modules/audio_processing/aec3/echo_remover_metrics.cc +++ b/modules/audio_processing/aec3/echo_remover_metrics.cc @@ -10,13 +10,14 @@ #include "modules/audio_processing/aec3/echo_remover_metrics.h" -#include -#include - #include +#include #include +#include #include +#include "modules/audio_processing/aec3/aec3_common.h" +#include "modules/audio_processing/aec3/aec_state.h" #include "rtc_base/checks.h" #include "rtc_base/numerics/safe_minmax.h" #include "system_wrappers/include/metrics.h" diff --git a/modules/audio_processing/aec3/echo_remover_metrics_unittest.cc b/modules/audio_processing/aec3/echo_remover_metrics_unittest.cc index b7a0d58f12..85b04b77e0 100644 --- a/modules/audio_processing/aec3/echo_remover_metrics_unittest.cc +++ b/modules/audio_processing/aec3/echo_remover_metrics_unittest.cc @@ -10,13 +10,17 @@ #include "modules/audio_processing/aec3/echo_remover_metrics.h" -#include - +#include +#include #include +#include "api/audio/echo_canceller3_config.h" #include "api/environment/environment_factory.h" +#include "modules/audio_processing/aec3/aec3_common.h" #include "modules/audio_processing/aec3/aec3_fft.h" #include "modules/audio_processing/aec3/aec_state.h" +#include "modules/audio_processing/aec3/fft_data.h" +#include "rtc_base/checks.h" #include "test/gtest.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/echo_remover_unittest.cc b/modules/audio_processing/aec3/echo_remover_unittest.cc index fb2eb78d2b..80c3ebc677 100644 --- a/modules/audio_processing/aec3/echo_remover_unittest.cc +++ b/modules/audio_processing/aec3/echo_remover_unittest.cc @@ -11,17 +11,24 @@ #include "modules/audio_processing/aec3/echo_remover.h" #include +#include #include #include +#include #include +#include +#include +#include "api/audio/echo_canceller3_config.h" #include "api/environment/environment.h" #include "api/environment/environment_factory.h" #include "modules/audio_processing/aec3/aec3_common.h" -#include "modules/audio_processing/aec3/render_buffer.h" +#include "modules/audio_processing/aec3/block.h" +#include "modules/audio_processing/aec3/delay_estimate.h" +#include "modules/audio_processing/aec3/echo_path_variability.h" #include "modules/audio_processing/aec3/render_delay_buffer.h" -#include "modules/audio_processing/logging/apm_data_dumper.h" #include "modules/audio_processing/test/echo_canceller_test_tools.h" +#include "rtc_base/checks.h" #include "rtc_base/random.h" #include "rtc_base/strings/string_builder.h" #include "test/gtest.h" diff --git a/modules/audio_processing/aec3/erl_estimator.cc b/modules/audio_processing/aec3/erl_estimator.cc index d3eeafc419..2bf6ee9e72 100644 --- a/modules/audio_processing/aec3/erl_estimator.cc +++ b/modules/audio_processing/aec3/erl_estimator.cc @@ -11,8 +11,14 @@ #include "modules/audio_processing/aec3/erl_estimator.h" #include +#include +#include +#include #include +#include +#include "api/array_view.h" +#include "modules/audio_processing/aec3/aec3_common.h" #include "rtc_base/checks.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/erl_estimator_unittest.cc b/modules/audio_processing/aec3/erl_estimator_unittest.cc index 4bb07c3ccc..c2efe03482 100644 --- a/modules/audio_processing/aec3/erl_estimator_unittest.cc +++ b/modules/audio_processing/aec3/erl_estimator_unittest.cc @@ -10,6 +10,14 @@ #include "modules/audio_processing/aec3/erl_estimator.h" +#include +#include +#include +#include +#include +#include + +#include "modules/audio_processing/aec3/aec3_common.h" #include "rtc_base/strings/string_builder.h" #include "test/gtest.h" diff --git a/modules/audio_processing/aec3/erle_estimator.cc b/modules/audio_processing/aec3/erle_estimator.cc index f1edfe601a..15de377594 100644 --- a/modules/audio_processing/aec3/erle_estimator.cc +++ b/modules/audio_processing/aec3/erle_estimator.cc @@ -10,7 +10,18 @@ #include "modules/audio_processing/aec3/erle_estimator.h" +#include +#include +#include +#include + +#include "api/array_view.h" +#include "api/audio/echo_canceller3_config.h" +#include "api/environment/environment.h" #include "modules/audio_processing/aec3/aec3_common.h" +#include "modules/audio_processing/aec3/render_buffer.h" +#include "modules/audio_processing/aec3/signal_dependent_erle_estimator.h" +#include "modules/audio_processing/logging/apm_data_dumper.h" #include "rtc_base/checks.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/erle_estimator.h b/modules/audio_processing/aec3/erle_estimator.h index cb014b0e68..fe6e71a355 100644 --- a/modules/audio_processing/aec3/erle_estimator.h +++ b/modules/audio_processing/aec3/erle_estimator.h @@ -20,6 +20,7 @@ #include "api/array_view.h" #include "api/audio/echo_canceller3_config.h" +#include "api/environment/environment.h" #include "modules/audio_processing/aec3/aec3_common.h" #include "modules/audio_processing/aec3/fullband_erle_estimator.h" #include "modules/audio_processing/aec3/render_buffer.h" diff --git a/modules/audio_processing/aec3/erle_estimator_unittest.cc b/modules/audio_processing/aec3/erle_estimator_unittest.cc index 9f06ffa4ec..ce75cfcafe 100644 --- a/modules/audio_processing/aec3/erle_estimator_unittest.cc +++ b/modules/audio_processing/aec3/erle_estimator_unittest.cc @@ -10,14 +10,23 @@ #include "modules/audio_processing/aec3/erle_estimator.h" +#include +#include #include +#include +#include +#include +#include #include "api/array_view.h" +#include "api/audio/echo_canceller3_config.h" #include "api/environment/environment_factory.h" +#include "modules/audio_processing/aec3/aec3_common.h" +#include "modules/audio_processing/aec3/block.h" +#include "modules/audio_processing/aec3/render_buffer.h" #include "modules/audio_processing/aec3/render_delay_buffer.h" #include "modules/audio_processing/aec3/spectrum_buffer.h" -#include "rtc_base/random.h" -#include "rtc_base/strings/string_builder.h" +#include "rtc_base/checks.h" #include "test/gtest.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/fft_buffer.cc b/modules/audio_processing/aec3/fft_buffer.cc index 1ce2d31d8f..fda753b134 100644 --- a/modules/audio_processing/aec3/fft_buffer.cc +++ b/modules/audio_processing/aec3/fft_buffer.cc @@ -10,6 +10,11 @@ #include "modules/audio_processing/aec3/fft_buffer.h" +#include +#include + +#include "modules/audio_processing/aec3/fft_data.h" + namespace webrtc { FftBuffer::FftBuffer(size_t size, size_t num_channels) diff --git a/modules/audio_processing/aec3/fft_data.h b/modules/audio_processing/aec3/fft_data.h index d8ac43e918..b227496388 100644 --- a/modules/audio_processing/aec3/fft_data.h +++ b/modules/audio_processing/aec3/fft_data.h @@ -11,17 +11,19 @@ #ifndef MODULES_AUDIO_PROCESSING_AEC3_FFT_DATA_H_ #define MODULES_AUDIO_PROCESSING_AEC3_FFT_DATA_H_ -// Defines WEBRTC_ARCH_X86_FAMILY, used below. -#include "rtc_base/system/arch.h" - -#if defined(WEBRTC_ARCH_X86_FAMILY) -#include -#endif #include #include +#include #include "api/array_view.h" #include "modules/audio_processing/aec3/aec3_common.h" +#include "rtc_base/checks.h" + +// Defines WEBRTC_ARCH_X86_FAMILY, used below. +#include "rtc_base/system/arch.h" +#if defined(WEBRTC_ARCH_X86_FAMILY) +#include +#endif namespace webrtc { diff --git a/modules/audio_processing/aec3/fft_data_avx2.cc b/modules/audio_processing/aec3/fft_data_avx2.cc index c604b56a96..eaa93c0db1 100644 --- a/modules/audio_processing/aec3/fft_data_avx2.cc +++ b/modules/audio_processing/aec3/fft_data_avx2.cc @@ -10,8 +10,12 @@ #include +#include + #include "api/array_view.h" +#include "modules/audio_processing/aec3/aec3_common.h" #include "modules/audio_processing/aec3/fft_data.h" +#include "rtc_base/checks.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/fft_data_unittest.cc b/modules/audio_processing/aec3/fft_data_unittest.cc index d76fabdbd6..a089c7b7bc 100644 --- a/modules/audio_processing/aec3/fft_data_unittest.cc +++ b/modules/audio_processing/aec3/fft_data_unittest.cc @@ -10,8 +10,13 @@ #include "modules/audio_processing/aec3/fft_data.h" +#include +#include + +#include "modules/audio_processing/aec3/aec3_common.h" +#include "rtc_base/checks.h" +#include "rtc_base/cpu_info.h" #include "rtc_base/system/arch.h" -#include "system_wrappers/include/cpu_features_wrapper.h" #include "test/gtest.h" namespace webrtc { @@ -20,7 +25,7 @@ namespace webrtc { // Verifies that the optimized methods are bitexact to their reference // counterparts. TEST(FftData, TestSse2Optimizations) { - if (GetCPUInfo(kSSE2) != 0) { + if (cpu_info::Supports(cpu_info::ISA::kSSE2)) { FftData x; for (size_t k = 0; k < x.re.size(); ++k) { @@ -43,7 +48,7 @@ TEST(FftData, TestSse2Optimizations) { // Verifies that the optimized methods are bitexact to their reference // counterparts. TEST(FftData, TestAvx2Optimizations) { - if (GetCPUInfo(kAVX2) != 0) { + if (cpu_info::Supports(cpu_info::ISA::kAVX2)) { FftData x; for (size_t k = 0; k < x.re.size(); ++k) { diff --git a/modules/audio_processing/aec3/filter_analyzer.cc b/modules/audio_processing/aec3/filter_analyzer.cc index b5bcad74c4..8147a216ce 100644 --- a/modules/audio_processing/aec3/filter_analyzer.cc +++ b/modules/audio_processing/aec3/filter_analyzer.cc @@ -14,9 +14,15 @@ #include #include +#include +#include #include +#include +#include "api/array_view.h" +#include "api/audio/echo_canceller3_config.h" #include "modules/audio_processing/aec3/aec3_common.h" +#include "modules/audio_processing/aec3/block.h" #include "modules/audio_processing/aec3/render_buffer.h" #include "modules/audio_processing/logging/apm_data_dumper.h" #include "rtc_base/checks.h" diff --git a/modules/audio_processing/aec3/filter_analyzer.h b/modules/audio_processing/aec3/filter_analyzer.h index 9e87fbb975..83c48650c5 100644 --- a/modules/audio_processing/aec3/filter_analyzer.h +++ b/modules/audio_processing/aec3/filter_analyzer.h @@ -13,14 +13,12 @@ #include -#include #include #include #include #include "api/array_view.h" #include "api/audio/echo_canceller3_config.h" -#include "modules/audio_processing/aec3/aec3_common.h" #include "modules/audio_processing/aec3/block.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/filter_analyzer_unittest.cc b/modules/audio_processing/aec3/filter_analyzer_unittest.cc index f1e2e4c188..b3d261c65e 100644 --- a/modules/audio_processing/aec3/filter_analyzer_unittest.cc +++ b/modules/audio_processing/aec3/filter_analyzer_unittest.cc @@ -10,9 +10,10 @@ #include "modules/audio_processing/aec3/filter_analyzer.h" -#include +#include +#include -#include "test/gmock.h" +#include "api/audio/echo_canceller3_config.h" #include "test/gtest.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/frame_blocker.cc b/modules/audio_processing/aec3/frame_blocker.cc index 154dc12642..97246e14ca 100644 --- a/modules/audio_processing/aec3/frame_blocker.cc +++ b/modules/audio_processing/aec3/frame_blocker.cc @@ -10,7 +10,13 @@ #include "modules/audio_processing/aec3/frame_blocker.h" +#include +#include +#include + +#include "api/array_view.h" #include "modules/audio_processing/aec3/aec3_common.h" +#include "modules/audio_processing/aec3/block.h" #include "rtc_base/checks.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/frame_blocker.h b/modules/audio_processing/aec3/frame_blocker.h index 4cac7566f7..f9dd88b76a 100644 --- a/modules/audio_processing/aec3/frame_blocker.h +++ b/modules/audio_processing/aec3/frame_blocker.h @@ -16,7 +16,6 @@ #include #include "api/array_view.h" -#include "modules/audio_processing/aec3/aec3_common.h" #include "modules/audio_processing/aec3/block.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/frame_blocker_unittest.cc b/modules/audio_processing/aec3/frame_blocker_unittest.cc index ee6296978f..d32cd80b29 100644 --- a/modules/audio_processing/aec3/frame_blocker_unittest.cc +++ b/modules/audio_processing/aec3/frame_blocker_unittest.cc @@ -10,11 +10,15 @@ #include "modules/audio_processing/aec3/frame_blocker.h" +#include #include #include +#include "api/array_view.h" #include "modules/audio_processing/aec3/aec3_common.h" +#include "modules/audio_processing/aec3/block.h" #include "modules/audio_processing/aec3/block_framer.h" +#include "rtc_base/checks.h" #include "rtc_base/strings/string_builder.h" #include "test/gtest.h" diff --git a/modules/audio_processing/aec3/fullband_erle_estimator.cc b/modules/audio_processing/aec3/fullband_erle_estimator.cc index 498c21b568..07acfa98a3 100644 --- a/modules/audio_processing/aec3/fullband_erle_estimator.cc +++ b/modules/audio_processing/aec3/fullband_erle_estimator.cc @@ -11,15 +11,18 @@ #include "modules/audio_processing/aec3/fullband_erle_estimator.h" #include +#include +#include #include #include #include +#include #include "api/array_view.h" +#include "api/audio/echo_canceller3_config.h" #include "modules/audio_processing/aec3/aec3_common.h" #include "modules/audio_processing/logging/apm_data_dumper.h" #include "rtc_base/checks.h" -#include "rtc_base/numerics/safe_minmax.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/fullband_erle_estimator.h b/modules/audio_processing/aec3/fullband_erle_estimator.h index d012d3477b..bb710c96d0 100644 --- a/modules/audio_processing/aec3/fullband_erle_estimator.h +++ b/modules/audio_processing/aec3/fullband_erle_estimator.h @@ -11,6 +11,9 @@ #ifndef MODULES_AUDIO_PROCESSING_AEC3_FULLBAND_ERLE_ESTIMATOR_H_ #define MODULES_AUDIO_PROCESSING_AEC3_FULLBAND_ERLE_ESTIMATOR_H_ +#include +#include +#include #include #include #include diff --git a/modules/audio_processing/aec3/matched_filter.h b/modules/audio_processing/aec3/matched_filter.h index 63992bd108..2a910b7eb2 100644 --- a/modules/audio_processing/aec3/matched_filter.h +++ b/modules/audio_processing/aec3/matched_filter.h @@ -18,7 +18,6 @@ #include "api/array_view.h" #include "modules/audio_processing/aec3/aec3_common.h" -#include "rtc_base/gtest_prod_util.h" #include "rtc_base/system/arch.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/matched_filter_lag_aggregator.cc b/modules/audio_processing/aec3/matched_filter_lag_aggregator.cc index fd6dc5bd3a..4909182157 100644 --- a/modules/audio_processing/aec3/matched_filter_lag_aggregator.cc +++ b/modules/audio_processing/aec3/matched_filter_lag_aggregator.cc @@ -10,8 +10,16 @@ #include "modules/audio_processing/aec3/matched_filter_lag_aggregator.h" #include +#include #include - +#include +#include + +#include "api/array_view.h" +#include "api/audio/echo_canceller3_config.h" +#include "modules/audio_processing/aec3/aec3_common.h" +#include "modules/audio_processing/aec3/delay_estimate.h" +#include "modules/audio_processing/aec3/matched_filter.h" #include "modules/audio_processing/logging/apm_data_dumper.h" #include "rtc_base/checks.h" #include "rtc_base/numerics/safe_minmax.h" diff --git a/modules/audio_processing/aec3/matched_filter_lag_aggregator.h b/modules/audio_processing/aec3/matched_filter_lag_aggregator.h index d1b4161d71..26cafbca15 100644 --- a/modules/audio_processing/aec3/matched_filter_lag_aggregator.h +++ b/modules/audio_processing/aec3/matched_filter_lag_aggregator.h @@ -11,9 +11,13 @@ #ifndef MODULES_AUDIO_PROCESSING_AEC3_MATCHED_FILTER_LAG_AGGREGATOR_H_ #define MODULES_AUDIO_PROCESSING_AEC3_MATCHED_FILTER_LAG_AGGREGATOR_H_ +#include +#include +#include #include #include +#include "api/array_view.h" #include "api/audio/echo_canceller3_config.h" #include "modules/audio_processing/aec3/delay_estimate.h" #include "modules/audio_processing/aec3/matched_filter.h" diff --git a/modules/audio_processing/aec3/matched_filter_lag_aggregator_unittest.cc b/modules/audio_processing/aec3/matched_filter_lag_aggregator_unittest.cc index 25c62fe753..12b525eacc 100644 --- a/modules/audio_processing/aec3/matched_filter_lag_aggregator_unittest.cc +++ b/modules/audio_processing/aec3/matched_filter_lag_aggregator_unittest.cc @@ -10,14 +10,16 @@ #include "modules/audio_processing/aec3/matched_filter_lag_aggregator.h" -#include -#include +#include +#include +#include #include -#include "api/array_view.h" #include "api/audio/echo_canceller3_config.h" -#include "modules/audio_processing/aec3/aec3_common.h" +#include "modules/audio_processing/aec3/delay_estimate.h" +#include "modules/audio_processing/aec3/matched_filter.h" #include "modules/audio_processing/logging/apm_data_dumper.h" +#include "rtc_base/checks.h" #include "test/gtest.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/matched_filter_unittest.cc b/modules/audio_processing/aec3/matched_filter_unittest.cc index 691bca4b48..dc75bcccce 100644 --- a/modules/audio_processing/aec3/matched_filter_unittest.cc +++ b/modules/audio_processing/aec3/matched_filter_unittest.cc @@ -10,36 +10,36 @@ #include "modules/audio_processing/aec3/matched_filter.h" +#include #include #include #include #include #include +#include #include -// Defines WEBRTC_ARCH_X86_FAMILY, used below. #include "api/array_view.h" #include "api/audio/echo_canceller3_config.h" -#include "modules/audio_processing/aec3/block.h" -#include "rtc_base/checks.h" -#include "rtc_base/system/arch.h" - -#if defined(WEBRTC_ARCH_X86_FAMILY) -#include -#endif -#include -#include - #include "modules/audio_processing/aec3/aec3_common.h" +#include "modules/audio_processing/aec3/block.h" #include "modules/audio_processing/aec3/decimator.h" #include "modules/audio_processing/aec3/render_delay_buffer.h" #include "modules/audio_processing/logging/apm_data_dumper.h" #include "modules/audio_processing/test/echo_canceller_test_tools.h" +#include "rtc_base/checks.h" +#include "rtc_base/cpu_info.h" #include "rtc_base/random.h" #include "rtc_base/strings/string_builder.h" -#include "system_wrappers/include/cpu_features_wrapper.h" +#include "rtc_base/system/arch.h" #include "test/gtest.h" +// Defines WEBRTC_ARCH_X86_FAMILY, used below. +#include "rtc_base/system/arch.h" +#if defined(WEBRTC_ARCH_X86_FAMILY) +#include +#endif + namespace webrtc { namespace aec3 { namespace { @@ -126,7 +126,7 @@ TEST_P(MatchedFilterTest, TestNeonOptimizations) { // counterparts. TEST_P(MatchedFilterTest, TestSse2Optimizations) { const bool kComputeAccumulatederror = GetParam(); - bool use_sse2 = (GetCPUInfo(kSSE2) != 0); + bool use_sse2 = cpu_info::Supports(cpu_info::ISA::kSSE2); if (use_sse2) { Random random_generator(42U); constexpr float kSmoothing = 0.7f; @@ -181,7 +181,7 @@ TEST_P(MatchedFilterTest, TestSse2Optimizations) { } TEST_P(MatchedFilterTest, TestAvx2Optimizations) { - bool use_avx2 = (GetCPUInfo(kAVX2) != 0); + bool use_avx2 = cpu_info::Supports(cpu_info::ISA::kAVX2); const bool kComputeAccumulatederror = GetParam(); if (use_avx2) { Random random_generator(42U); diff --git a/modules/audio_processing/aec3/mock/mock_block_processor.h b/modules/audio_processing/aec3/mock/mock_block_processor.h index c9ae38c4aa..b305a93b44 100644 --- a/modules/audio_processing/aec3/mock/mock_block_processor.h +++ b/modules/audio_processing/aec3/mock/mock_block_processor.h @@ -11,8 +11,8 @@ #ifndef MODULES_AUDIO_PROCESSING_AEC3_MOCK_MOCK_BLOCK_PROCESSOR_H_ #define MODULES_AUDIO_PROCESSING_AEC3_MOCK_MOCK_BLOCK_PROCESSOR_H_ -#include - +#include "api/audio/echo_control.h" +#include "modules/audio_processing/aec3/block.h" #include "modules/audio_processing/aec3/block_processor.h" #include "test/gmock.h" diff --git a/modules/audio_processing/aec3/mock/mock_echo_remover.h b/modules/audio_processing/aec3/mock/mock_echo_remover.h index 0be4a650d4..e1474dd555 100644 --- a/modules/audio_processing/aec3/mock/mock_echo_remover.h +++ b/modules/audio_processing/aec3/mock/mock_echo_remover.h @@ -12,8 +12,10 @@ #define MODULES_AUDIO_PROCESSING_AEC3_MOCK_MOCK_ECHO_REMOVER_H_ #include -#include +#include "api/audio/echo_control.h" +#include "modules/audio_processing/aec3/block.h" +#include "modules/audio_processing/aec3/delay_estimate.h" #include "modules/audio_processing/aec3/echo_path_variability.h" #include "modules/audio_processing/aec3/echo_remover.h" #include "modules/audio_processing/aec3/render_buffer.h" diff --git a/modules/audio_processing/aec3/mock/mock_render_delay_buffer.cc b/modules/audio_processing/aec3/mock/mock_render_delay_buffer.cc index d4ad09b4bc..6eedf1c40e 100644 --- a/modules/audio_processing/aec3/mock/mock_render_delay_buffer.cc +++ b/modules/audio_processing/aec3/mock/mock_render_delay_buffer.cc @@ -10,6 +10,11 @@ #include "modules/audio_processing/aec3/mock/mock_render_delay_buffer.h" +#include + +#include "modules/audio_processing/aec3/aec3_common.h" +#include "test/gmock.h" + namespace webrtc { namespace test { diff --git a/modules/audio_processing/aec3/mock/mock_render_delay_buffer.h b/modules/audio_processing/aec3/mock/mock_render_delay_buffer.h index c17fd62caa..80ba97a4a4 100644 --- a/modules/audio_processing/aec3/mock/mock_render_delay_buffer.h +++ b/modules/audio_processing/aec3/mock/mock_render_delay_buffer.h @@ -11,12 +11,15 @@ #ifndef MODULES_AUDIO_PROCESSING_AEC3_MOCK_MOCK_RENDER_DELAY_BUFFER_H_ #define MODULES_AUDIO_PROCESSING_AEC3_MOCK_MOCK_RENDER_DELAY_BUFFER_H_ -#include +#include -#include "modules/audio_processing/aec3/aec3_common.h" +#include "modules/audio_processing/aec3/block.h" +#include "modules/audio_processing/aec3/block_buffer.h" #include "modules/audio_processing/aec3/downsampled_render_buffer.h" +#include "modules/audio_processing/aec3/fft_buffer.h" #include "modules/audio_processing/aec3/render_buffer.h" #include "modules/audio_processing/aec3/render_delay_buffer.h" +#include "modules/audio_processing/aec3/spectrum_buffer.h" #include "test/gmock.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/mock/mock_render_delay_controller.h b/modules/audio_processing/aec3/mock/mock_render_delay_controller.h index 3395044cf9..c459090cb5 100644 --- a/modules/audio_processing/aec3/mock/mock_render_delay_controller.h +++ b/modules/audio_processing/aec3/mock/mock_render_delay_controller.h @@ -11,9 +11,11 @@ #ifndef MODULES_AUDIO_PROCESSING_AEC3_MOCK_MOCK_RENDER_DELAY_CONTROLLER_H_ #define MODULES_AUDIO_PROCESSING_AEC3_MOCK_MOCK_RENDER_DELAY_CONTROLLER_H_ +#include #include -#include "api/array_view.h" +#include "modules/audio_processing/aec3/block.h" +#include "modules/audio_processing/aec3/delay_estimate.h" #include "modules/audio_processing/aec3/downsampled_render_buffer.h" #include "modules/audio_processing/aec3/render_delay_controller.h" #include "test/gmock.h" diff --git a/modules/audio_processing/aec3/moving_average.cc b/modules/audio_processing/aec3/moving_average.cc index f89789ec77..e1e5589ff3 100644 --- a/modules/audio_processing/aec3/moving_average.cc +++ b/modules/audio_processing/aec3/moving_average.cc @@ -12,8 +12,10 @@ #include "modules/audio_processing/aec3/moving_average.h" #include +#include #include +#include "api/array_view.h" #include "rtc_base/checks.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/moving_average_unittest.cc b/modules/audio_processing/aec3/moving_average_unittest.cc index 84ba9cbc5b..ca985176cd 100644 --- a/modules/audio_processing/aec3/moving_average_unittest.cc +++ b/modules/audio_processing/aec3/moving_average_unittest.cc @@ -10,6 +10,9 @@ #include "modules/audio_processing/aec3/moving_average.h" +#include +#include + #include "test/gtest.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/multi_channel_content_detector.cc b/modules/audio_processing/aec3/multi_channel_content_detector.cc index 2b07585c1b..d1eb19ea65 100644 --- a/modules/audio_processing/aec3/multi_channel_content_detector.cc +++ b/modules/audio_processing/aec3/multi_channel_content_detector.cc @@ -11,6 +11,10 @@ #include "modules/audio_processing/aec3/multi_channel_content_detector.h" #include +#include +#include +#include +#include #include "rtc_base/checks.h" #include "system_wrappers/include/metrics.h" diff --git a/modules/audio_processing/aec3/multi_channel_content_detector_unittest.cc b/modules/audio_processing/aec3/multi_channel_content_detector_unittest.cc index 3b6e942d88..5b9b13e457 100644 --- a/modules/audio_processing/aec3/multi_channel_content_detector_unittest.cc +++ b/modules/audio_processing/aec3/multi_channel_content_detector_unittest.cc @@ -10,6 +10,10 @@ #include "modules/audio_processing/aec3/multi_channel_content_detector.h" +#include +#include +#include + #include "system_wrappers/include/metrics.h" #include "test/gtest.h" diff --git a/modules/audio_processing/aec3/nearend_detector.h b/modules/audio_processing/aec3/nearend_detector.h index 72e798a115..a1f30a977c 100644 --- a/modules/audio_processing/aec3/nearend_detector.h +++ b/modules/audio_processing/aec3/nearend_detector.h @@ -11,10 +11,9 @@ #ifndef MODULES_AUDIO_PROCESSING_AEC3_NEAREND_DETECTOR_H_ #define MODULES_AUDIO_PROCESSING_AEC3_NEAREND_DETECTOR_H_ -#include +#include #include "api/array_view.h" -#include "api/audio/echo_canceller3_config.h" #include "modules/audio_processing/aec3/aec3_common.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/refined_filter_update_gain.cc b/modules/audio_processing/aec3/refined_filter_update_gain.cc index 7d32bae49b..80a55c21b3 100644 --- a/modules/audio_processing/aec3/refined_filter_update_gain.cc +++ b/modules/audio_processing/aec3/refined_filter_update_gain.cc @@ -11,9 +11,12 @@ #include "modules/audio_processing/aec3/refined_filter_update_gain.h" #include -#include +#include +#include +#include -#include "modules/audio_processing/aec3/adaptive_fir_filter.h" +#include "api/array_view.h" +#include "api/audio/echo_canceller3_config.h" #include "modules/audio_processing/aec3/aec3_common.h" #include "modules/audio_processing/aec3/echo_path_variability.h" #include "modules/audio_processing/aec3/fft_data.h" diff --git a/modules/audio_processing/aec3/render_buffer.cc b/modules/audio_processing/aec3/render_buffer.cc index aa511e2b6b..32d4314e39 100644 --- a/modules/audio_processing/aec3/render_buffer.cc +++ b/modules/audio_processing/aec3/render_buffer.cc @@ -11,9 +11,13 @@ #include "modules/audio_processing/aec3/render_buffer.h" #include -#include +#include +#include #include "modules/audio_processing/aec3/aec3_common.h" +#include "modules/audio_processing/aec3/block_buffer.h" +#include "modules/audio_processing/aec3/fft_buffer.h" +#include "modules/audio_processing/aec3/spectrum_buffer.h" #include "rtc_base/checks.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/render_buffer.h b/modules/audio_processing/aec3/render_buffer.h index e70d48211f..8f76bd04af 100644 --- a/modules/audio_processing/aec3/render_buffer.h +++ b/modules/audio_processing/aec3/render_buffer.h @@ -18,6 +18,7 @@ #include "api/array_view.h" #include "modules/audio_processing/aec3/aec3_common.h" +#include "modules/audio_processing/aec3/block.h" #include "modules/audio_processing/aec3/block_buffer.h" #include "modules/audio_processing/aec3/fft_buffer.h" #include "modules/audio_processing/aec3/fft_data.h" diff --git a/modules/audio_processing/aec3/render_buffer_unittest.cc b/modules/audio_processing/aec3/render_buffer_unittest.cc index 5d9d646e76..ab217236b7 100644 --- a/modules/audio_processing/aec3/render_buffer_unittest.cc +++ b/modules/audio_processing/aec3/render_buffer_unittest.cc @@ -10,10 +10,10 @@ #include "modules/audio_processing/aec3/render_buffer.h" -#include -#include -#include - +#include "modules/audio_processing/aec3/block_buffer.h" +#include "modules/audio_processing/aec3/fft_buffer.h" +#include "modules/audio_processing/aec3/spectrum_buffer.h" +#include "rtc_base/checks.h" #include "test/gtest.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/render_delay_buffer.cc b/modules/audio_processing/aec3/render_delay_buffer.cc index 37a7801c3e..0f72be4b62 100644 --- a/modules/audio_processing/aec3/render_delay_buffer.cc +++ b/modules/audio_processing/aec3/render_delay_buffer.cc @@ -13,8 +13,10 @@ #include #include +#include #include #include +#include #include #include #include @@ -25,11 +27,11 @@ #include "modules/audio_processing/aec3/aec3_common.h" #include "modules/audio_processing/aec3/aec3_fft.h" #include "modules/audio_processing/aec3/alignment_mixer.h" +#include "modules/audio_processing/aec3/block.h" #include "modules/audio_processing/aec3/block_buffer.h" #include "modules/audio_processing/aec3/decimator.h" #include "modules/audio_processing/aec3/downsampled_render_buffer.h" #include "modules/audio_processing/aec3/fft_buffer.h" -#include "modules/audio_processing/aec3/fft_data.h" #include "modules/audio_processing/aec3/render_buffer.h" #include "modules/audio_processing/aec3/spectrum_buffer.h" #include "modules/audio_processing/logging/apm_data_dumper.h" diff --git a/modules/audio_processing/aec3/render_delay_buffer.h b/modules/audio_processing/aec3/render_delay_buffer.h index 6dc1aefb85..e0488d6d66 100644 --- a/modules/audio_processing/aec3/render_delay_buffer.h +++ b/modules/audio_processing/aec3/render_delay_buffer.h @@ -13,7 +13,6 @@ #include -#include #include "api/audio/echo_canceller3_config.h" #include "modules/audio_processing/aec3/block.h" diff --git a/modules/audio_processing/aec3/render_delay_buffer_unittest.cc b/modules/audio_processing/aec3/render_delay_buffer_unittest.cc index e46a69abf0..8deb77c8f1 100644 --- a/modules/audio_processing/aec3/render_delay_buffer_unittest.cc +++ b/modules/audio_processing/aec3/render_delay_buffer_unittest.cc @@ -10,14 +10,14 @@ #include "modules/audio_processing/aec3/render_delay_buffer.h" +#include #include #include -#include -#include "api/array_view.h" +#include "api/audio/echo_canceller3_config.h" #include "modules/audio_processing/aec3/aec3_common.h" -#include "modules/audio_processing/logging/apm_data_dumper.h" -#include "rtc_base/random.h" +#include "modules/audio_processing/aec3/block.h" +#include "rtc_base/checks.h" #include "rtc_base/strings/string_builder.h" #include "test/gtest.h" diff --git a/modules/audio_processing/aec3/render_delay_controller.cc b/modules/audio_processing/aec3/render_delay_controller.cc index b02e516a04..a4046f26c1 100644 --- a/modules/audio_processing/aec3/render_delay_controller.cc +++ b/modules/audio_processing/aec3/render_delay_controller.cc @@ -9,16 +9,15 @@ */ #include "modules/audio_processing/aec3/render_delay_controller.h" -#include - -#include #include +#include #include #include -#include "api/array_view.h" #include "api/audio/echo_canceller3_config.h" #include "modules/audio_processing/aec3/aec3_common.h" +#include "modules/audio_processing/aec3/block.h" +#include "modules/audio_processing/aec3/clockdrift_detector.h" #include "modules/audio_processing/aec3/delay_estimate.h" #include "modules/audio_processing/aec3/downsampled_render_buffer.h" #include "modules/audio_processing/aec3/echo_path_delay_estimator.h" diff --git a/modules/audio_processing/aec3/render_delay_controller.h b/modules/audio_processing/aec3/render_delay_controller.h index b74c1619b4..0d6ff7f2bc 100644 --- a/modules/audio_processing/aec3/render_delay_controller.h +++ b/modules/audio_processing/aec3/render_delay_controller.h @@ -11,15 +11,13 @@ #ifndef MODULES_AUDIO_PROCESSING_AEC3_RENDER_DELAY_CONTROLLER_H_ #define MODULES_AUDIO_PROCESSING_AEC3_RENDER_DELAY_CONTROLLER_H_ +#include #include -#include "api/array_view.h" #include "api/audio/echo_canceller3_config.h" #include "modules/audio_processing/aec3/block.h" #include "modules/audio_processing/aec3/delay_estimate.h" #include "modules/audio_processing/aec3/downsampled_render_buffer.h" -#include "modules/audio_processing/aec3/render_delay_buffer.h" -#include "modules/audio_processing/logging/apm_data_dumper.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/render_delay_controller_metrics.cc b/modules/audio_processing/aec3/render_delay_controller_metrics.cc index 8d3f41533a..014b36029e 100644 --- a/modules/audio_processing/aec3/render_delay_controller_metrics.cc +++ b/modules/audio_processing/aec3/render_delay_controller_metrics.cc @@ -11,9 +11,11 @@ #include "modules/audio_processing/aec3/render_delay_controller_metrics.h" #include +#include +#include #include "modules/audio_processing/aec3/aec3_common.h" -#include "rtc_base/checks.h" +#include "modules/audio_processing/aec3/clockdrift_detector.h" #include "system_wrappers/include/metrics.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/render_delay_controller_metrics_unittest.cc b/modules/audio_processing/aec3/render_delay_controller_metrics_unittest.cc index 22739e7107..58b74b40b2 100644 --- a/modules/audio_processing/aec3/render_delay_controller_metrics_unittest.cc +++ b/modules/audio_processing/aec3/render_delay_controller_metrics_unittest.cc @@ -13,6 +13,7 @@ #include #include "modules/audio_processing/aec3/aec3_common.h" +#include "modules/audio_processing/aec3/clockdrift_detector.h" #include "system_wrappers/include/metrics.h" #include "test/gtest.h" diff --git a/modules/audio_processing/aec3/render_signal_analyzer.cc b/modules/audio_processing/aec3/render_signal_analyzer.cc index 7970caf622..ae013e7189 100644 --- a/modules/audio_processing/aec3/render_signal_analyzer.cc +++ b/modules/audio_processing/aec3/render_signal_analyzer.cc @@ -10,13 +10,18 @@ #include "modules/audio_processing/aec3/render_signal_analyzer.h" -#include - #include +#include +#include +#include +#include #include -#include #include "api/array_view.h" +#include "api/audio/echo_canceller3_config.h" +#include "modules/audio_processing/aec3/aec3_common.h" +#include "modules/audio_processing/aec3/block.h" +#include "modules/audio_processing/aec3/render_buffer.h" #include "rtc_base/checks.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/render_signal_analyzer_unittest.cc b/modules/audio_processing/aec3/render_signal_analyzer_unittest.cc index 9ef60406a3..9cb8ebe005 100644 --- a/modules/audio_processing/aec3/render_signal_analyzer_unittest.cc +++ b/modules/audio_processing/aec3/render_signal_analyzer_unittest.cc @@ -10,19 +10,23 @@ #include "modules/audio_processing/aec3/render_signal_analyzer.h" -#include - +#include #include #include +#include +#include #include -#include +#include +#include #include "api/array_view.h" +#include "api/audio/echo_canceller3_config.h" #include "modules/audio_processing/aec3/aec3_common.h" #include "modules/audio_processing/aec3/aec3_fft.h" -#include "modules/audio_processing/aec3/fft_data.h" +#include "modules/audio_processing/aec3/block.h" #include "modules/audio_processing/aec3/render_delay_buffer.h" #include "modules/audio_processing/test/echo_canceller_test_tools.h" +#include "rtc_base/checks.h" #include "rtc_base/random.h" #include "rtc_base/strings/string_builder.h" #include "test/gtest.h" diff --git a/modules/audio_processing/aec3/residual_echo_estimator.cc b/modules/audio_processing/aec3/residual_echo_estimator.cc index 384abfff49..8e8849634b 100644 --- a/modules/audio_processing/aec3/residual_echo_estimator.cc +++ b/modules/audio_processing/aec3/residual_echo_estimator.cc @@ -10,15 +10,20 @@ #include "modules/audio_processing/aec3/residual_echo_estimator.h" -#include - #include +#include +#include #include #include "api/array_view.h" +#include "api/audio/echo_canceller3_config.h" #include "api/environment/environment.h" #include "api/field_trials_view.h" +#include "modules/audio_processing/aec3/aec3_common.h" +#include "modules/audio_processing/aec3/aec_state.h" +#include "modules/audio_processing/aec3/render_buffer.h" #include "modules/audio_processing/aec3/reverb_model.h" +#include "modules/audio_processing/aec3/spectrum_buffer.h" #include "rtc_base/checks.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/residual_echo_estimator.h b/modules/audio_processing/aec3/residual_echo_estimator.h index 549d3defc9..79c1d63b44 100644 --- a/modules/audio_processing/aec3/residual_echo_estimator.h +++ b/modules/audio_processing/aec3/residual_echo_estimator.h @@ -12,17 +12,15 @@ #define MODULES_AUDIO_PROCESSING_AEC3_RESIDUAL_ECHO_ESTIMATOR_H_ #include -#include -#include +#include +#include "api/array_view.h" #include "api/audio/echo_canceller3_config.h" #include "api/environment/environment.h" #include "modules/audio_processing/aec3/aec3_common.h" #include "modules/audio_processing/aec3/aec_state.h" #include "modules/audio_processing/aec3/render_buffer.h" #include "modules/audio_processing/aec3/reverb_model.h" -#include "modules/audio_processing/aec3/spectrum_buffer.h" -#include "rtc_base/checks.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/residual_echo_estimator_unittest.cc b/modules/audio_processing/aec3/residual_echo_estimator_unittest.cc index d083f8b439..1211f65d4e 100644 --- a/modules/audio_processing/aec3/residual_echo_estimator_unittest.cc +++ b/modules/audio_processing/aec3/residual_echo_estimator_unittest.cc @@ -10,17 +10,26 @@ #include "modules/audio_processing/aec3/residual_echo_estimator.h" +#include +#include +#include #include +#include +#include +#include +#include "api/array_view.h" #include "api/audio/echo_canceller3_config.h" #include "api/environment/environment.h" #include "api/environment/environment_factory.h" -#include "modules/audio_processing/aec3/aec3_fft.h" +#include "modules/audio_processing/aec3/aec3_common.h" #include "modules/audio_processing/aec3/aec_state.h" +#include "modules/audio_processing/aec3/block.h" +#include "modules/audio_processing/aec3/delay_estimate.h" #include "modules/audio_processing/aec3/render_delay_buffer.h" +#include "modules/audio_processing/aec3/subtractor_output.h" #include "modules/audio_processing/test/echo_canceller_test_tools.h" #include "rtc_base/random.h" -#include "rtc_base/strings/string_builder.h" #include "test/gtest.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/reverb_decay_estimator.cc b/modules/audio_processing/aec3/reverb_decay_estimator.cc index f973f86ec4..bd7c4251ed 100644 --- a/modules/audio_processing/aec3/reverb_decay_estimator.cc +++ b/modules/audio_processing/aec3/reverb_decay_estimator.cc @@ -10,14 +10,16 @@ #include "modules/audio_processing/aec3/reverb_decay_estimator.h" -#include - #include +#include #include +#include #include +#include #include "api/array_view.h" #include "api/audio/echo_canceller3_config.h" +#include "modules/audio_processing/aec3/aec3_common.h" #include "modules/audio_processing/logging/apm_data_dumper.h" #include "rtc_base/checks.h" diff --git a/modules/audio_processing/aec3/reverb_decay_estimator.h b/modules/audio_processing/aec3/reverb_decay_estimator.h index 4fcc8897d3..721cd2bbec 100644 --- a/modules/audio_processing/aec3/reverb_decay_estimator.h +++ b/modules/audio_processing/aec3/reverb_decay_estimator.h @@ -11,12 +11,10 @@ #ifndef MODULES_AUDIO_PROCESSING_AEC3_REVERB_DECAY_ESTIMATOR_H_ #define MODULES_AUDIO_PROCESSING_AEC3_REVERB_DECAY_ESTIMATOR_H_ -#include #include #include #include "api/array_view.h" -#include "modules/audio_processing/aec3/aec3_common.h" // kMaxAdaptiveFilter... namespace webrtc { diff --git a/modules/audio_processing/aec3/reverb_frequency_response.cc b/modules/audio_processing/aec3/reverb_frequency_response.cc index 508b0b825c..3006af81e2 100644 --- a/modules/audio_processing/aec3/reverb_frequency_response.cc +++ b/modules/audio_processing/aec3/reverb_frequency_response.cc @@ -15,6 +15,8 @@ #include #include #include +#include +#include #include "api/array_view.h" #include "modules/audio_processing/aec3/aec3_common.h" diff --git a/modules/audio_processing/aec3/reverb_model.cc b/modules/audio_processing/aec3/reverb_model.cc index 3581696163..7bd719c76d 100644 --- a/modules/audio_processing/aec3/reverb_model.cc +++ b/modules/audio_processing/aec3/reverb_model.cc @@ -10,10 +10,7 @@ #include "modules/audio_processing/aec3/reverb_model.h" -#include - -#include -#include +#include #include "api/array_view.h" diff --git a/modules/audio_processing/aec3/reverb_model_estimator.cc b/modules/audio_processing/aec3/reverb_model_estimator.cc index 398b906e32..6465299909 100644 --- a/modules/audio_processing/aec3/reverb_model_estimator.cc +++ b/modules/audio_processing/aec3/reverb_model_estimator.cc @@ -10,6 +10,19 @@ #include "modules/audio_processing/aec3/reverb_model_estimator.h" +#include +#include +#include +#include +#include + +#include "api/array_view.h" +#include "api/audio/echo_canceller3_config.h" +#include "modules/audio_processing/aec3/aec3_common.h" +#include "modules/audio_processing/aec3/reverb_decay_estimator.h" +#include "modules/audio_processing/aec3/reverb_frequency_response.h" +#include "rtc_base/checks.h" + namespace webrtc { ReverbModelEstimator::ReverbModelEstimator(const EchoCanceller3Config& config, diff --git a/modules/audio_processing/aec3/reverb_model_estimator.h b/modules/audio_processing/aec3/reverb_model_estimator.h index 8994a4a55e..08bbc86447 100644 --- a/modules/audio_processing/aec3/reverb_model_estimator.h +++ b/modules/audio_processing/aec3/reverb_model_estimator.h @@ -12,6 +12,7 @@ #define MODULES_AUDIO_PROCESSING_AEC3_REVERB_MODEL_ESTIMATOR_H_ #include +#include #include #include #include diff --git a/modules/audio_processing/aec3/reverb_model_estimator_unittest.cc b/modules/audio_processing/aec3/reverb_model_estimator_unittest.cc index 2e99a08360..e3cde9e4e1 100644 --- a/modules/audio_processing/aec3/reverb_model_estimator_unittest.cc +++ b/modules/audio_processing/aec3/reverb_model_estimator_unittest.cc @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include diff --git a/modules/audio_processing/aec3/signal_dependent_erle_estimator.cc b/modules/audio_processing/aec3/signal_dependent_erle_estimator.cc index b2bdb27cb7..d0a854c57b 100644 --- a/modules/audio_processing/aec3/signal_dependent_erle_estimator.cc +++ b/modules/audio_processing/aec3/signal_dependent_erle_estimator.cc @@ -11,10 +11,20 @@ #include "modules/audio_processing/aec3/signal_dependent_erle_estimator.h" #include +#include +#include #include +#include #include +#include +#include "api/array_view.h" +#include "api/audio/echo_canceller3_config.h" +#include "modules/audio_processing/aec3/aec3_common.h" +#include "modules/audio_processing/aec3/render_buffer.h" #include "modules/audio_processing/aec3/spectrum_buffer.h" +#include "modules/audio_processing/logging/apm_data_dumper.h" +#include "rtc_base/checks.h" #include "rtc_base/numerics/safe_minmax.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/signal_dependent_erle_estimator.h b/modules/audio_processing/aec3/signal_dependent_erle_estimator.h index d46fd19e10..4c58bd4f4f 100644 --- a/modules/audio_processing/aec3/signal_dependent_erle_estimator.h +++ b/modules/audio_processing/aec3/signal_dependent_erle_estimator.h @@ -11,6 +11,8 @@ #ifndef MODULES_AUDIO_PROCESSING_AEC3_SIGNAL_DEPENDENT_ERLE_ESTIMATOR_H_ #define MODULES_AUDIO_PROCESSING_AEC3_SIGNAL_DEPENDENT_ERLE_ESTIMATOR_H_ +#include +#include #include #include diff --git a/modules/audio_processing/aec3/signal_dependent_erle_estimator_unittest.cc b/modules/audio_processing/aec3/signal_dependent_erle_estimator_unittest.cc index 2653c9e474..c834b39e94 100644 --- a/modules/audio_processing/aec3/signal_dependent_erle_estimator_unittest.cc +++ b/modules/audio_processing/aec3/signal_dependent_erle_estimator_unittest.cc @@ -11,13 +11,20 @@ #include "modules/audio_processing/aec3/signal_dependent_erle_estimator.h" #include -#include -#include +#include +#include +#include +#include +#include +#include "api/array_view.h" #include "api/audio/echo_canceller3_config.h" +#include "modules/audio_processing/aec3/aec3_common.h" +#include "modules/audio_processing/aec3/block.h" #include "modules/audio_processing/aec3/render_buffer.h" #include "modules/audio_processing/aec3/render_delay_buffer.h" -#include "rtc_base/strings/string_builder.h" +#include "modules/audio_processing/aec3/spectrum_buffer.h" +#include "rtc_base/checks.h" #include "test/gtest.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/spectrum_buffer.cc b/modules/audio_processing/aec3/spectrum_buffer.cc index fe32ece09c..4caec83c3b 100644 --- a/modules/audio_processing/aec3/spectrum_buffer.cc +++ b/modules/audio_processing/aec3/spectrum_buffer.cc @@ -11,6 +11,11 @@ #include "modules/audio_processing/aec3/spectrum_buffer.h" #include +#include +#include +#include + +#include "modules/audio_processing/aec3/aec3_common.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/stationarity_estimator.cc b/modules/audio_processing/aec3/stationarity_estimator.cc index b6da56a3fd..cba546bdd1 100644 --- a/modules/audio_processing/aec3/stationarity_estimator.cc +++ b/modules/audio_processing/aec3/stationarity_estimator.cc @@ -12,11 +12,14 @@ #include #include +#include +#include #include "api/array_view.h" #include "modules/audio_processing/aec3/aec3_common.h" #include "modules/audio_processing/aec3/spectrum_buffer.h" #include "modules/audio_processing/logging/apm_data_dumper.h" +#include "rtc_base/checks.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/stationarity_estimator.h b/modules/audio_processing/aec3/stationarity_estimator.h index 6edc195b66..0c10a099b0 100644 --- a/modules/audio_processing/aec3/stationarity_estimator.h +++ b/modules/audio_processing/aec3/stationarity_estimator.h @@ -11,15 +11,13 @@ #ifndef MODULES_AUDIO_PROCESSING_AEC3_STATIONARITY_ESTIMATOR_H_ #define MODULES_AUDIO_PROCESSING_AEC3_STATIONARITY_ESTIMATOR_H_ -#include - #include #include +#include #include #include "api/array_view.h" #include "modules/audio_processing/aec3/aec3_common.h" // kFftLengthBy2Plus1... -#include "modules/audio_processing/aec3/reverb_model.h" #include "rtc_base/checks.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/subband_erle_estimator.cc b/modules/audio_processing/aec3/subband_erle_estimator.cc index 6208d26388..8db40a2579 100644 --- a/modules/audio_processing/aec3/subband_erle_estimator.cc +++ b/modules/audio_processing/aec3/subband_erle_estimator.cc @@ -11,10 +11,18 @@ #include "modules/audio_processing/aec3/subband_erle_estimator.h" #include +#include +#include #include +#include +#include +#include "api/array_view.h" +#include "api/audio/echo_canceller3_config.h" #include "api/environment/environment.h" #include "api/field_trials_view.h" +#include "modules/audio_processing/aec3/aec3_common.h" +#include "modules/audio_processing/logging/apm_data_dumper.h" #include "rtc_base/checks.h" #include "rtc_base/numerics/safe_minmax.h" diff --git a/modules/audio_processing/aec3/subband_nearend_detector.cc b/modules/audio_processing/aec3/subband_nearend_detector.cc index 73c7c3c0e0..37b356367b 100644 --- a/modules/audio_processing/aec3/subband_nearend_detector.cc +++ b/modules/audio_processing/aec3/subband_nearend_detector.cc @@ -10,8 +10,15 @@ #include "modules/audio_processing/aec3/subband_nearend_detector.h" +#include +#include #include +#include "api/array_view.h" +#include "api/audio/echo_canceller3_config.h" +#include "modules/audio_processing/aec3/aec3_common.h" +#include "modules/audio_processing/aec3/moving_average.h" + namespace webrtc { SubbandNearendDetector::SubbandNearendDetector( const EchoCanceller3Config::Suppressor::SubbandNearendDetection& config, diff --git a/modules/audio_processing/aec3/subband_nearend_detector.h b/modules/audio_processing/aec3/subband_nearend_detector.h index 846b8345cf..ab733b9acb 100644 --- a/modules/audio_processing/aec3/subband_nearend_detector.h +++ b/modules/audio_processing/aec3/subband_nearend_detector.h @@ -11,10 +11,13 @@ #ifndef MODULES_AUDIO_PROCESSING_AEC3_SUBBAND_NEAREND_DETECTOR_H_ #define MODULES_AUDIO_PROCESSING_AEC3_SUBBAND_NEAREND_DETECTOR_H_ +#include +#include #include #include "api/array_view.h" #include "api/audio/echo_canceller3_config.h" +#include "modules/audio_processing/aec3/aec3_common.h" #include "modules/audio_processing/aec3/moving_average.h" #include "modules/audio_processing/aec3/nearend_detector.h" diff --git a/modules/audio_processing/aec3/subtractor.cc b/modules/audio_processing/aec3/subtractor.cc index 4d81a6cc18..bfce13f42d 100644 --- a/modules/audio_processing/aec3/subtractor.cc +++ b/modules/audio_processing/aec3/subtractor.cc @@ -11,13 +11,28 @@ #include "modules/audio_processing/aec3/subtractor.h" #include -#include +#include +#include +#include +#include #include "api/array_view.h" +#include "api/audio/echo_canceller3_config.h" #include "api/environment/environment.h" #include "api/field_trials_view.h" +#include "modules/audio_processing/aec3/adaptive_fir_filter.h" #include "modules/audio_processing/aec3/adaptive_fir_filter_erl.h" +#include "modules/audio_processing/aec3/aec3_common.h" +#include "modules/audio_processing/aec3/aec3_fft.h" +#include "modules/audio_processing/aec3/aec_state.h" +#include "modules/audio_processing/aec3/block.h" +#include "modules/audio_processing/aec3/coarse_filter_update_gain.h" +#include "modules/audio_processing/aec3/echo_path_variability.h" #include "modules/audio_processing/aec3/fft_data.h" +#include "modules/audio_processing/aec3/refined_filter_update_gain.h" +#include "modules/audio_processing/aec3/render_buffer.h" +#include "modules/audio_processing/aec3/render_signal_analyzer.h" +#include "modules/audio_processing/aec3/subtractor_output.h" #include "modules/audio_processing/logging/apm_data_dumper.h" #include "rtc_base/checks.h" #include "rtc_base/numerics/safe_minmax.h" diff --git a/modules/audio_processing/aec3/subtractor.h b/modules/audio_processing/aec3/subtractor.h index 0b8d04719a..148bdf2c1f 100644 --- a/modules/audio_processing/aec3/subtractor.h +++ b/modules/audio_processing/aec3/subtractor.h @@ -11,10 +11,10 @@ #ifndef MODULES_AUDIO_PROCESSING_AEC3_SUBTRACTOR_H_ #define MODULES_AUDIO_PROCESSING_AEC3_SUBTRACTOR_H_ -#include -#include - #include +#include +#include +#include #include #include "api/array_view.h" diff --git a/modules/audio_processing/aec3/subtractor_output.cc b/modules/audio_processing/aec3/subtractor_output.cc index 0aef6b9ad5..7a5bd17ef9 100644 --- a/modules/audio_processing/aec3/subtractor_output.cc +++ b/modules/audio_processing/aec3/subtractor_output.cc @@ -10,8 +10,11 @@ #include "modules/audio_processing/aec3/subtractor_output.h" +#include #include +#include "api/array_view.h" + namespace webrtc { SubtractorOutput::SubtractorOutput() = default; diff --git a/modules/audio_processing/aec3/subtractor_output_analyzer.cc b/modules/audio_processing/aec3/subtractor_output_analyzer.cc index b2b5ce0b60..f0cb67278f 100644 --- a/modules/audio_processing/aec3/subtractor_output_analyzer.cc +++ b/modules/audio_processing/aec3/subtractor_output_analyzer.cc @@ -11,8 +11,12 @@ #include "modules/audio_processing/aec3/subtractor_output_analyzer.h" #include +#include +#include "api/array_view.h" #include "modules/audio_processing/aec3/aec3_common.h" +#include "modules/audio_processing/aec3/subtractor_output.h" +#include "rtc_base/checks.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/subtractor_output_analyzer.h b/modules/audio_processing/aec3/subtractor_output_analyzer.h index c9ccafacc3..760ffe63b0 100644 --- a/modules/audio_processing/aec3/subtractor_output_analyzer.h +++ b/modules/audio_processing/aec3/subtractor_output_analyzer.h @@ -11,8 +11,10 @@ #ifndef MODULES_AUDIO_PROCESSING_AEC3_SUBTRACTOR_OUTPUT_ANALYZER_H_ #define MODULES_AUDIO_PROCESSING_AEC3_SUBTRACTOR_OUTPUT_ANALYZER_H_ +#include #include +#include "api/array_view.h" #include "modules/audio_processing/aec3/subtractor_output.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/suppression_filter.cc b/modules/audio_processing/aec3/suppression_filter.cc index ec081ab6d1..fa44591b13 100644 --- a/modules/audio_processing/aec3/suppression_filter.cc +++ b/modules/audio_processing/aec3/suppression_filter.cc @@ -11,11 +11,16 @@ #include "modules/audio_processing/aec3/suppression_filter.h" #include +#include #include #include -#include #include +#include +#include "api/array_view.h" +#include "modules/audio_processing/aec3/aec3_common.h" +#include "modules/audio_processing/aec3/block.h" +#include "modules/audio_processing/aec3/fft_data.h" #include "modules/audio_processing/aec3/vector_math.h" #include "rtc_base/checks.h" #include "rtc_base/numerics/safe_minmax.h" diff --git a/modules/audio_processing/aec3/suppression_filter.h b/modules/audio_processing/aec3/suppression_filter.h index e8082845f1..4a6de28eba 100644 --- a/modules/audio_processing/aec3/suppression_filter.h +++ b/modules/audio_processing/aec3/suppression_filter.h @@ -12,8 +12,10 @@ #define MODULES_AUDIO_PROCESSING_AEC3_SUPPRESSION_FILTER_H_ #include +#include #include +#include "api/array_view.h" #include "modules/audio_processing/aec3/aec3_common.h" #include "modules/audio_processing/aec3/aec3_fft.h" #include "modules/audio_processing/aec3/block.h" diff --git a/modules/audio_processing/aec3/suppression_filter_unittest.cc b/modules/audio_processing/aec3/suppression_filter_unittest.cc index 8ecc7ecfea..370c32db5a 100644 --- a/modules/audio_processing/aec3/suppression_filter_unittest.cc +++ b/modules/audio_processing/aec3/suppression_filter_unittest.cc @@ -10,13 +10,19 @@ #include "modules/audio_processing/aec3/suppression_filter.h" -#include - #include +#include #include +#include #include #include +#include +#include "modules/audio_processing/aec3/aec3_common.h" +#include "modules/audio_processing/aec3/aec3_fft.h" +#include "modules/audio_processing/aec3/block.h" +#include "modules/audio_processing/aec3/fft_data.h" +#include "rtc_base/checks.h" #include "test/gtest.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/suppression_gain.cc b/modules/audio_processing/aec3/suppression_gain.cc index 6ae9bfc1a1..eb5dcda7f8 100644 --- a/modules/audio_processing/aec3/suppression_gain.cc +++ b/modules/audio_processing/aec3/suppression_gain.cc @@ -10,14 +10,23 @@ #include "modules/audio_processing/aec3/suppression_gain.h" -#include -#include - #include +#include +#include +#include +#include +#include #include +#include +#include "api/array_view.h" +#include "api/audio/echo_canceller3_config.h" +#include "modules/audio_processing/aec3/aec3_common.h" +#include "modules/audio_processing/aec3/aec_state.h" +#include "modules/audio_processing/aec3/block.h" #include "modules/audio_processing/aec3/dominant_nearend_detector.h" #include "modules/audio_processing/aec3/moving_average.h" +#include "modules/audio_processing/aec3/render_signal_analyzer.h" #include "modules/audio_processing/aec3/subband_nearend_detector.h" #include "modules/audio_processing/aec3/vector_math.h" #include "modules/audio_processing/logging/apm_data_dumper.h" diff --git a/modules/audio_processing/aec3/suppression_gain.h b/modules/audio_processing/aec3/suppression_gain.h index 65d7985fb5..b0a56d04ad 100644 --- a/modules/audio_processing/aec3/suppression_gain.h +++ b/modules/audio_processing/aec3/suppression_gain.h @@ -13,6 +13,7 @@ #include #include +#include #include #include #include @@ -21,7 +22,7 @@ #include "api/audio/echo_canceller3_config.h" #include "modules/audio_processing/aec3/aec3_common.h" #include "modules/audio_processing/aec3/aec_state.h" -#include "modules/audio_processing/aec3/fft_data.h" +#include "modules/audio_processing/aec3/block.h" #include "modules/audio_processing/aec3/moving_average.h" #include "modules/audio_processing/aec3/nearend_detector.h" #include "modules/audio_processing/aec3/render_signal_analyzer.h" diff --git a/modules/audio_processing/aec3/suppression_gain_unittest.cc b/modules/audio_processing/aec3/suppression_gain_unittest.cc index b079186e92..2da9589261 100644 --- a/modules/audio_processing/aec3/suppression_gain_unittest.cc +++ b/modules/audio_processing/aec3/suppression_gain_unittest.cc @@ -10,15 +10,27 @@ #include "modules/audio_processing/aec3/suppression_gain.h" +#include +#include +#include +#include +#include +#include + +#include "api/audio/echo_canceller3_config.h" #include "api/environment/environment.h" #include "api/environment/environment_factory.h" +#include "modules/audio_processing/aec3/aec3_common.h" #include "modules/audio_processing/aec3/aec_state.h" +#include "modules/audio_processing/aec3/block.h" +#include "modules/audio_processing/aec3/delay_estimate.h" +#include "modules/audio_processing/aec3/fft_data.h" #include "modules/audio_processing/aec3/render_delay_buffer.h" +#include "modules/audio_processing/aec3/render_signal_analyzer.h" #include "modules/audio_processing/aec3/subtractor.h" #include "modules/audio_processing/aec3/subtractor_output.h" #include "modules/audio_processing/logging/apm_data_dumper.h" #include "rtc_base/checks.h" -#include "system_wrappers/include/cpu_features_wrapper.h" #include "test/gtest.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/transparent_mode.cc b/modules/audio_processing/aec3/transparent_mode.cc index 1349d0d342..196cb7eb3d 100644 --- a/modules/audio_processing/aec3/transparent_mode.cc +++ b/modules/audio_processing/aec3/transparent_mode.cc @@ -10,8 +10,13 @@ #include "modules/audio_processing/aec3/transparent_mode.h" +#include +#include + +#include "api/audio/echo_canceller3_config.h" #include "api/environment/environment.h" #include "api/field_trials_view.h" +#include "modules/audio_processing/aec3/aec3_common.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" diff --git a/modules/audio_processing/aec3/transparent_mode.h b/modules/audio_processing/aec3/transparent_mode.h index 7b6148f998..1caa16a03e 100644 --- a/modules/audio_processing/aec3/transparent_mode.h +++ b/modules/audio_processing/aec3/transparent_mode.h @@ -15,7 +15,6 @@ #include "api/audio/echo_canceller3_config.h" #include "api/environment/environment.h" -#include "modules/audio_processing/aec3/aec3_common.h" namespace webrtc { diff --git a/modules/audio_processing/aec3/vector_math.h b/modules/audio_processing/aec3/vector_math.h index e6ccf6e803..9fd7792d3f 100644 --- a/modules/audio_processing/aec3/vector_math.h +++ b/modules/audio_processing/aec3/vector_math.h @@ -11,24 +11,22 @@ #ifndef MODULES_AUDIO_PROCESSING_AEC3_VECTOR_MATH_H_ #define MODULES_AUDIO_PROCESSING_AEC3_VECTOR_MATH_H_ +#include +#include +#include + +#include "api/array_view.h" +#include "modules/audio_processing/aec3/aec3_common.h" +#include "rtc_base/checks.h" + // Defines WEBRTC_ARCH_X86_FAMILY, used below. #include "rtc_base/system/arch.h" - #if defined(WEBRTC_HAS_NEON) #include #endif #if defined(WEBRTC_ARCH_X86_FAMILY) #include #endif -#include - -#include -#include -#include - -#include "api/array_view.h" -#include "modules/audio_processing/aec3/aec3_common.h" -#include "rtc_base/checks.h" namespace webrtc { namespace aec3 { diff --git a/modules/audio_processing/aec3/vector_math_unittest.cc b/modules/audio_processing/aec3/vector_math_unittest.cc index a9c37e33cf..a47263b305 100644 --- a/modules/audio_processing/aec3/vector_math_unittest.cc +++ b/modules/audio_processing/aec3/vector_math_unittest.cc @@ -10,10 +10,14 @@ #include "modules/audio_processing/aec3/vector_math.h" -#include +#include +#include +#include +#include +#include "modules/audio_processing/aec3/aec3_common.h" +#include "rtc_base/cpu_info.h" #include "rtc_base/system/arch.h" -#include "system_wrappers/include/cpu_features_wrapper.h" #include "test/gtest.h" namespace webrtc { @@ -80,7 +84,7 @@ TEST(VectorMath, Accumulate) { #if defined(WEBRTC_ARCH_X86_FAMILY) TEST(VectorMath, Sse2Sqrt) { - if (GetCPUInfo(kSSE2) != 0) { + if (cpu_info::Supports(cpu_info::ISA::kSSE2)) { std::array x; std::array z; std::array z_sse2; @@ -102,7 +106,7 @@ TEST(VectorMath, Sse2Sqrt) { } TEST(VectorMath, Avx2Sqrt) { - if (GetCPUInfo(kAVX2) != 0) { + if (cpu_info::Supports(cpu_info::ISA::kAVX2)) { std::array x; std::array z; std::array z_avx2; @@ -124,7 +128,7 @@ TEST(VectorMath, Avx2Sqrt) { } TEST(VectorMath, Sse2Multiply) { - if (GetCPUInfo(kSSE2) != 0) { + if (cpu_info::Supports(cpu_info::ISA::kSSE2)) { std::array x; std::array y; std::array z; @@ -145,7 +149,7 @@ TEST(VectorMath, Sse2Multiply) { } TEST(VectorMath, Avx2Multiply) { - if (GetCPUInfo(kAVX2) != 0) { + if (cpu_info::Supports(cpu_info::ISA::kAVX2)) { std::array x; std::array y; std::array z; @@ -166,7 +170,7 @@ TEST(VectorMath, Avx2Multiply) { } TEST(VectorMath, Sse2Accumulate) { - if (GetCPUInfo(kSSE2) != 0) { + if (cpu_info::Supports(cpu_info::ISA::kSSE2)) { std::array x; std::array z; std::array z_sse2; @@ -186,7 +190,7 @@ TEST(VectorMath, Sse2Accumulate) { } TEST(VectorMath, Avx2Accumulate) { - if (GetCPUInfo(kAVX2) != 0) { + if (cpu_info::Supports(cpu_info::ISA::kAVX2)) { std::array x; std::array z; std::array z_avx2; diff --git a/modules/audio_processing/aec_dump/BUILD.gn b/modules/audio_processing/aec_dump/BUILD.gn index b747aaab8f..227d6dec6b 100644 --- a/modules/audio_processing/aec_dump/BUILD.gn +++ b/modules/audio_processing/aec_dump/BUILD.gn @@ -32,11 +32,11 @@ if (rtc_include_tests) { deps = [ "..:aec_dump_interface", + "..:audio_frame_view", "..:audioproc_test_utils", "../", "../../../api/audio:audio_frame_api", "../../../api/audio:audio_processing", - "../../../modules/audio_processing:audio_frame_view", "../../../test:test_support", ] } @@ -73,10 +73,10 @@ if (rtc_enable_protobuf) { deps = [ ":aec_dump", "..:aec_dump_interface", + "..:audio_frame_view", "../../../api/audio:audio_frame_api", "../../../api/audio:audio_processing", "../../../api/task_queue", - "../../../modules/audio_processing:audio_frame_view", "../../../rtc_base:checks", "../../../rtc_base:logging", "../../../rtc_base:macromagic", @@ -99,8 +99,10 @@ if (rtc_enable_protobuf) { deps = [ ":aec_dump", ":aec_dump_impl", + "..:aec_dump_interface", "..:audioproc_debug_proto", "../", + "../../../api/audio:audio_processing", "../../../rtc_base:task_queue_for_test", "../../../test:fileutils", "../../../test:test_support", @@ -119,6 +121,7 @@ rtc_library("null_aec_dump_factory") { ":aec_dump", "..:aec_dump_interface", "../../../api/task_queue", + "../../../rtc_base/system:file_wrapper", "//third_party/abseil-cpp/absl/base:nullability", "//third_party/abseil-cpp/absl/strings:string_view", ] diff --git a/modules/audio_processing/aec_dump/aec_dump_factory.h b/modules/audio_processing/aec_dump/aec_dump_factory.h index 9a68691f56..a32e7c05b5 100644 --- a/modules/audio_processing/aec_dump/aec_dump_factory.h +++ b/modules/audio_processing/aec_dump/aec_dump_factory.h @@ -11,6 +11,8 @@ #ifndef MODULES_AUDIO_PROCESSING_AEC_DUMP_AEC_DUMP_FACTORY_H_ #define MODULES_AUDIO_PROCESSING_AEC_DUMP_AEC_DUMP_FACTORY_H_ +#include +#include #include #include "absl/base/nullability.h" diff --git a/modules/audio_processing/aec_dump/aec_dump_impl.cc b/modules/audio_processing/aec_dump/aec_dump_impl.cc index 92f3bd3eb3..9d9608245f 100644 --- a/modules/audio_processing/aec_dump/aec_dump_impl.cc +++ b/modules/audio_processing/aec_dump/aec_dump_impl.cc @@ -23,7 +23,6 @@ #include "api/audio/audio_view.h" #include "api/task_queue/task_queue_base.h" #include "modules/audio_processing/aec_dump/aec_dump_factory.h" -#include "modules/audio_processing/debug.pb.h" #include "modules/audio_processing/include/aec_dump.h" #include "modules/audio_processing/include/audio_frame_view.h" #include "rtc_base/checks.h" @@ -31,6 +30,9 @@ #include "rtc_base/race_checker.h" #include "rtc_base/system/file_wrapper.h" +// Generated at build-time by the protobuf compiler. +#include "modules/audio_processing/debug.pb.h" + namespace webrtc { namespace { diff --git a/modules/audio_processing/aec_dump/aec_dump_unittest.cc b/modules/audio_processing/aec_dump/aec_dump_unittest.cc index 935402b31d..0f501de806 100644 --- a/modules/audio_processing/aec_dump/aec_dump_unittest.cc +++ b/modules/audio_processing/aec_dump/aec_dump_unittest.cc @@ -8,9 +8,18 @@ * be found in the AUTHORS file in the root of the source tree. */ +#include "modules/audio_processing/include/aec_dump.h" + +#include + #include -#include +#include +#include +#include +#include +#include +#include "api/audio/audio_processing.h" #include "modules/audio_processing/aec_dump/aec_dump_factory.h" #include "rtc_base/task_queue_for_test.h" #include "test/gtest.h" diff --git a/modules/audio_processing/aec_dump/null_aec_dump_factory.cc b/modules/audio_processing/aec_dump/null_aec_dump_factory.cc index 9ab5d140e2..04fb024a7a 100644 --- a/modules/audio_processing/aec_dump/null_aec_dump_factory.cc +++ b/modules/audio_processing/aec_dump/null_aec_dump_factory.cc @@ -8,11 +8,16 @@ * be found in the AUTHORS file in the root of the source tree. */ +#include +#include +#include + #include "absl/base/nullability.h" #include "absl/strings/string_view.h" #include "api/task_queue/task_queue_base.h" #include "modules/audio_processing/aec_dump/aec_dump_factory.h" #include "modules/audio_processing/include/aec_dump.h" +#include "rtc_base/system/file_wrapper.h" namespace webrtc { diff --git a/modules/audio_processing/aecm/BUILD.gn b/modules/audio_processing/aecm/BUILD.gn index 80f2901049..a945d0c58d 100644 --- a/modules/audio_processing/aecm/BUILD.gn +++ b/modules/audio_processing/aecm/BUILD.gn @@ -21,7 +21,6 @@ rtc_library("aecm_core") { "../../../rtc_base:checks", "../../../rtc_base:safe_conversions", "../../../rtc_base:sanitizer", - "../../../system_wrappers", "../utility:legacy_delay_estimator", ] cflags = [] diff --git a/modules/audio_processing/aecm/aecm_core.cc b/modules/audio_processing/aecm/aecm_core.cc index 8b1e12794c..d61da76947 100644 --- a/modules/audio_processing/aecm/aecm_core.cc +++ b/modules/audio_processing/aecm/aecm_core.cc @@ -10,20 +10,24 @@ #include "modules/audio_processing/aecm/aecm_core.h" -#include -#include -#include +#include +#include +#include +#include -extern "C" { -#include "common_audio/ring_buffer.h" -#include "common_audio/signal_processing/include/real_fft.h" -} #include "common_audio/signal_processing/include/signal_processing_library.h" +#include "common_audio/signal_processing/include/spl_inl.h" +#include "modules/audio_processing/aecm/aecm_defines.h" #include "modules/audio_processing/aecm/echo_control_mobile.h" #include "modules/audio_processing/utility/delay_estimator_wrapper.h" #include "rtc_base/checks.h" #include "rtc_base/numerics/safe_conversions.h" +extern "C" { +#include "common_audio/ring_buffer.h" +#include "common_audio/signal_processing/include/real_fft.h" +} + namespace webrtc { namespace { @@ -34,7 +38,7 @@ FILE* testfile; #endif // Initialization table for echo channel in 8 kHz -static const int16_t kChannelStored8kHz[PART_LEN1] = { +const int16_t kChannelStored8kHz[PART_LEN1] = { 2040, 1815, 1590, 1498, 1405, 1395, 1385, 1418, 1451, 1506, 1562, 1644, 1726, 1804, 1882, 1918, 1953, 1982, 2010, 2025, 2040, 2034, 2027, 2021, 2014, 1997, 1980, 1925, 1869, 1800, 1732, 1683, 1635, @@ -43,7 +47,7 @@ static const int16_t kChannelStored8kHz[PART_LEN1] = { 1470, 1499, 1524, 1549, 1565, 1582, 1601, 1621, 1649, 1676}; // Initialization table for echo channel in 16 kHz -static const int16_t kChannelStored16kHz[PART_LEN1] = { +const int16_t kChannelStored16kHz[PART_LEN1] = { 2040, 1590, 1405, 1385, 1451, 1562, 1726, 1882, 1953, 2010, 2040, 2027, 2014, 1980, 1869, 1732, 1635, 1572, 1517, 1444, 1367, 1294, 1245, 1233, 1260, 1303, 1373, 1441, 1499, 1549, 1582, 1621, 1676, diff --git a/modules/audio_processing/aecm/aecm_core.h b/modules/audio_processing/aecm/aecm_core.h index 3de49315c4..a76660b9ba 100644 --- a/modules/audio_processing/aecm/aecm_core.h +++ b/modules/audio_processing/aecm/aecm_core.h @@ -13,12 +13,13 @@ #ifndef MODULES_AUDIO_PROCESSING_AECM_AECM_CORE_H_ #define MODULES_AUDIO_PROCESSING_AECM_AECM_CORE_H_ +#include + +#include "modules/audio_processing/aecm/aecm_defines.h" + extern "C" { #include "common_audio/ring_buffer.h" -#include "common_audio/signal_processing/include/signal_processing_library.h" } -#include "modules/audio_processing/aecm/aecm_defines.h" - struct RealFFT; namespace webrtc { diff --git a/modules/audio_processing/aecm/aecm_core_c.cc b/modules/audio_processing/aecm/aecm_core_c.cc index 1a975d2adc..439481c77b 100644 --- a/modules/audio_processing/aecm/aecm_core_c.cc +++ b/modules/audio_processing/aecm/aecm_core_c.cc @@ -11,28 +11,29 @@ #include #include -#include "modules/audio_processing/aecm/aecm_core.h" +#include +#include -extern "C" { -#include "common_audio/ring_buffer.h" -#include "common_audio/signal_processing/include/real_fft.h" -} +#include "common_audio/signal_processing/include/signal_processing_library.h" +#include "common_audio/signal_processing/include/spl_inl.h" +#include "modules/audio_processing/aecm/aecm_core.h" +#include "modules/audio_processing/aecm/aecm_defines.h" #include "modules/audio_processing/aecm/echo_control_mobile.h" #include "modules/audio_processing/utility/delay_estimator_wrapper.h" -extern "C" { -#include "system_wrappers/include/cpu_features_wrapper.h" -} - #include "rtc_base/checks.h" #include "rtc_base/numerics/safe_conversions.h" #include "rtc_base/sanitizer.h" +extern "C" { +#include "common_audio/signal_processing/include/real_fft.h" +} + namespace webrtc { namespace { // Square root of Hanning window in Q14. -static const ALIGN8_BEG int16_t WebRtcAecm_kSqrtHanning[] ALIGN8_END = { +const ALIGN8_BEG int16_t WebRtcAecm_kSqrtHanning[] ALIGN8_END = { 0, 399, 798, 1196, 1594, 1990, 2386, 2780, 3172, 3562, 3951, 4337, 4720, 5101, 5478, 5853, 6224, 6591, 6954, 7313, 7668, 8019, 8364, 8705, 9040, 9370, 9695, 10013, 10326, 10633, 10933, 11227, 11514, @@ -55,13 +56,13 @@ static const uint16_t kAlpha3 = 26951; static const uint16_t kBeta3 = 18927; #endif -static const int16_t kNoiseEstQDomain = 15; -static const int16_t kNoiseEstIncCount = 5; +const int16_t kNoiseEstQDomain = 15; +const int16_t kNoiseEstIncCount = 5; -static void ComfortNoise(AecmCore* aecm, - const uint16_t* dfa, - ComplexInt16* out, - const int16_t* lambda) { +void ComfortNoise(AecmCore* aecm, + const uint16_t* dfa, + ComplexInt16* out, + const int16_t* lambda) { int16_t i; int16_t tmp16; int32_t tmp32; @@ -171,11 +172,11 @@ static void ComfortNoise(AecmCore* aecm, } } -static void WindowAndFFT(AecmCore* aecm, - int16_t* fft, - const int16_t* time_signal, - ComplexInt16* freq_signal, - int time_signal_scaling) { +void WindowAndFFT(AecmCore* aecm, + int16_t* fft, + const int16_t* time_signal, + ComplexInt16* freq_signal, + int time_signal_scaling) { int i = 0; // FFT of signal @@ -198,11 +199,11 @@ static void WindowAndFFT(AecmCore* aecm, } } -static void InverseFFTAndWindow(AecmCore* aecm, - int16_t* fft, - ComplexInt16* efw, - int16_t* output, - const int16_t* nearendClean) { +void InverseFFTAndWindow(AecmCore* aecm, + int16_t* fft, + ComplexInt16* efw, + int16_t* output, + const int16_t* nearendClean) { int i, j, outCFFT; int32_t tmp32no1; // Reuse `efw` for the inverse FFT output after transferring @@ -262,11 +263,11 @@ static void InverseFFTAndWindow(AecmCore* aecm, // the frequency domain array // return value The Q-domain of current frequency values // -static int TimeToFrequencyDomain(AecmCore* aecm, - const int16_t* time_signal, - ComplexInt16* freq_signal, - uint16_t* freq_signal_abs, - uint32_t* freq_signal_sum_abs) { +int TimeToFrequencyDomain(AecmCore* aecm, + const int16_t* time_signal, + ComplexInt16* freq_signal, + uint16_t* freq_signal_abs, + uint32_t* freq_signal_sum_abs) { int i = 0; int time_signal_scaling = 0; diff --git a/modules/audio_processing/aecm/aecm_core_mips.cc b/modules/audio_processing/aecm/aecm_core_mips.cc index 819737d861..2d008b0b01 100644 --- a/modules/audio_processing/aecm/aecm_core_mips.cc +++ b/modules/audio_processing/aecm/aecm_core_mips.cc @@ -1078,8 +1078,7 @@ int WebRtcAecm_ProcessBlock(AecmCore* aecm, // Far end signal through channel estimate in Q8 // How much can we shift right to preserve resolution tmp32no1 = echoEst32[i] - aecm->echoFilt[i]; - aecm->echoFilt[i] += - webrtc::dchecked_cast((int64_t{tmp32no1} * 50) >> 8); + aecm->echoFilt[i] += dchecked_cast((int64_t{tmp32no1} * 50) >> 8); zeros32 = WebRtcSpl_NormW32(aecm->echoFilt[i]) + 1; zeros16 = WebRtcSpl_NormW16(supGain) + 1; diff --git a/modules/audio_processing/aecm/aecm_core_neon.cc b/modules/audio_processing/aecm/aecm_core_neon.cc index 584110d3af..e6507d32e1 100644 --- a/modules/audio_processing/aecm/aecm_core_neon.cc +++ b/modules/audio_processing/aecm/aecm_core_neon.cc @@ -14,6 +14,10 @@ #include "modules/audio_processing/aecm/aecm_core.h" #include "rtc_base/checks.h" +extern "C" { +#include "common_audio/signal_processing/include/signal_processing_library.h" +} + namespace webrtc { namespace { diff --git a/modules/audio_processing/aecm/echo_control_mobile.cc b/modules/audio_processing/aecm/echo_control_mobile.cc index 1f58984441..d09556de1f 100644 --- a/modules/audio_processing/aecm/echo_control_mobile.cc +++ b/modules/audio_processing/aecm/echo_control_mobile.cc @@ -10,18 +10,20 @@ #include "modules/audio_processing/aecm/echo_control_mobile.h" +#include +#include +#include #ifdef AEC_DEBUG -#include +#include #endif -#include -#include + +#include "modules/audio_processing/aecm/aecm_core.h" extern "C" { #include "common_audio/ring_buffer.h" #include "common_audio/signal_processing/include/signal_processing_library.h" #include "modules/audio_processing/aecm/aecm_defines.h" } -#include "modules/audio_processing/aecm/aecm_core.h" namespace webrtc { @@ -33,12 +35,12 @@ namespace { // The factor of 2 handles wb, and the + 1 is as a safety margin #define MAX_RESAMP_LEN (5 * FRAME_LEN) -static const size_t kBufSizeSamp = +const size_t kBufSizeSamp = BUF_SIZE_FRAMES * FRAME_LEN; // buffer size (samples) -static const int kSampMsNb = 8; // samples per ms in nb +const int kSampMsNb = 8; // samples per ms in nb // Target suppression levels for nlp modes // log{0.001, 0.00001, 0.00000001} -static const int kInitCheck = 42; +const int kInitCheck = 42; typedef struct { int sampFreq; diff --git a/modules/audio_processing/agc/BUILD.gn b/modules/audio_processing/agc/BUILD.gn index 61a450922f..f0824fea75 100644 --- a/modules/audio_processing/agc/BUILD.gn +++ b/modules/audio_processing/agc/BUILD.gn @@ -77,6 +77,7 @@ rtc_library("legacy_agc") { deps = [ "../../../common_audio", "../../../common_audio:common_audio_c", + "../../../common_audio:common_audio_cc", "../../../common_audio/third_party/ooura:fft_size_256", "../../../rtc_base:checks", "../../../system_wrappers", @@ -105,9 +106,11 @@ if (rtc_include_tests) { ":agc", ":gain_control_interface", ":level_estimation", + "..:audio_buffer", "..:mocks", "../../../api:array_view", "../../../api:field_trials", + "../../../api/audio:audio_processing", "../../../api/environment", "../../../api/environment:environment_factory", "../../../rtc_base:checks", diff --git a/modules/audio_processing/agc/agc.cc b/modules/audio_processing/agc/agc.cc index f172b03a5a..29e84b4380 100644 --- a/modules/audio_processing/agc/agc.cc +++ b/modules/audio_processing/agc/agc.cc @@ -11,9 +11,11 @@ #include "modules/audio_processing/agc/agc.h" #include +#include #include #include +#include "api/array_view.h" #include "modules/audio_processing/agc/loudness_histogram.h" #include "modules/audio_processing/agc/utility.h" #include "rtc_base/checks.h" diff --git a/modules/audio_processing/agc/agc.h b/modules/audio_processing/agc/agc.h index 65afbf07bc..dfc769bce6 100644 --- a/modules/audio_processing/agc/agc.h +++ b/modules/audio_processing/agc/agc.h @@ -11,6 +11,7 @@ #ifndef MODULES_AUDIO_PROCESSING_AGC_AGC_H_ #define MODULES_AUDIO_PROCESSING_AGC_AGC_H_ +#include #include #include "api/array_view.h" diff --git a/modules/audio_processing/agc/agc_manager_direct.cc b/modules/audio_processing/agc/agc_manager_direct.cc index 5fc12c0439..2477d42ab0 100644 --- a/modules/audio_processing/agc/agc_manager_direct.cc +++ b/modules/audio_processing/agc/agc_manager_direct.cc @@ -11,16 +11,28 @@ #include "modules/audio_processing/agc/agc_manager_direct.h" #include +#include +#include #include +#include +#include +#include +#include +#include #include "api/array_view.h" +#include "api/audio/audio_processing.h" #include "api/environment/environment.h" #include "api/field_trials_view.h" #include "common_audio/include/audio_util.h" +#include "modules/audio_processing/agc/agc.h" #include "modules/audio_processing/agc/gain_control.h" +#include "modules/audio_processing/agc2/clipping_predictor.h" #include "modules/audio_processing/agc2/gain_map_internal.h" #include "modules/audio_processing/agc2/input_volume_stats_reporter.h" +#include "modules/audio_processing/audio_buffer.h" #include "modules/audio_processing/include/audio_frame_view.h" +#include "modules/audio_processing/logging/apm_data_dumper.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "rtc_base/numerics/safe_minmax.h" diff --git a/modules/audio_processing/agc/agc_manager_direct.h b/modules/audio_processing/agc/agc_manager_direct.h index c3100e5f15..9df71250b3 100644 --- a/modules/audio_processing/agc/agc_manager_direct.h +++ b/modules/audio_processing/agc/agc_manager_direct.h @@ -12,8 +12,10 @@ #define MODULES_AUDIO_PROCESSING_AGC_AGC_MANAGER_DIRECT_H_ #include +#include #include #include +#include #include "api/array_view.h" #include "api/audio/audio_processing.h" diff --git a/modules/audio_processing/agc/agc_manager_direct_unittest.cc b/modules/audio_processing/agc/agc_manager_direct_unittest.cc index 51708df740..49c8c78990 100644 --- a/modules/audio_processing/agc/agc_manager_direct_unittest.cc +++ b/modules/audio_processing/agc/agc_manager_direct_unittest.cc @@ -10,17 +10,28 @@ #include "modules/audio_processing/agc/agc_manager_direct.h" +#include +#include +#include +#include #include +#include #include +#include +#include +#include #include #include +#include "api/audio/audio_processing.h" #include "api/environment/environment.h" #include "api/environment/environment_factory.h" #include "api/field_trials.h" +#include "modules/audio_processing/agc/agc.h" #include "modules/audio_processing/agc/gain_control.h" #include "modules/audio_processing/agc/mock_agc.h" -#include "modules/audio_processing/include/mock_audio_processing.h" +#include "modules/audio_processing/audio_buffer.h" +#include "rtc_base/checks.h" #include "rtc_base/numerics/safe_minmax.h" #include "rtc_base/strings/string_builder.h" #include "test/gmock.h" @@ -60,7 +71,7 @@ constexpr AnalogAgcConfig kDefaultAnalogConfig{}; class MockGainControl : public GainControl { public: - virtual ~MockGainControl() {} + ~MockGainControl() override {} MOCK_METHOD(int, set_stream_analog_level, (int level), (override)); MOCK_METHOD(int, stream_analog_level, (), (const, override)); MOCK_METHOD(int, set_mode, (Mode mode), (override)); diff --git a/modules/audio_processing/agc/legacy/analog_agc.cc b/modules/audio_processing/agc/legacy/analog_agc.cc index d946060e85..be46148e4a 100644 --- a/modules/audio_processing/agc/legacy/analog_agc.cc +++ b/modules/audio_processing/agc/legacy/analog_agc.cc @@ -19,8 +19,15 @@ #include "modules/audio_processing/agc/legacy/analog_agc.h" -#include - +#include +#include +#include + +#include "common_audio/signal_processing/dot_product_with_scale.h" +#include "common_audio/signal_processing/include/signal_processing_library.h" +#include "common_audio/signal_processing/include/spl_inl.h" +#include "modules/audio_processing/agc/legacy/digital_agc.h" +#include "modules/audio_processing/agc/legacy/gain_control.h" #include "rtc_base/checks.h" namespace webrtc { @@ -34,23 +41,22 @@ namespace { #define AGC_BAD_PARAMETER_ERROR 18004 /* The slope of in Q13*/ -static const int16_t kSlope1[8] = {21793, 12517, 7189, 4129, - 2372, 1362, 472, 78}; +const int16_t kSlope1[8] = {21793, 12517, 7189, 4129, 2372, 1362, 472, 78}; /* The offset in Q14 */ -static const int16_t kOffset1[8] = {25395, 23911, 22206, 20737, - 19612, 18805, 17951, 17367}; +const int16_t kOffset1[8] = {25395, 23911, 22206, 20737, + 19612, 18805, 17951, 17367}; /* The slope of in Q13*/ -static const int16_t kSlope2[8] = {2063, 1731, 1452, 1218, 1021, 857, 597, 337}; +const int16_t kSlope2[8] = {2063, 1731, 1452, 1218, 1021, 857, 597, 337}; /* The offset in Q14 */ -static const int16_t kOffset2[8] = {18432, 18379, 18290, 18177, - 18052, 17920, 17670, 17286}; +const int16_t kOffset2[8] = {18432, 18379, 18290, 18177, + 18052, 17920, 17670, 17286}; -static const int16_t kMuteGuardTimeMs = 8000; -static const int16_t kInitCheck = 42; -static const size_t kNumSubframes = 10; +const int16_t kMuteGuardTimeMs = 8000; +const int16_t kInitCheck = 42; +const size_t kNumSubframes = 10; /* Default settings if config is not used */ #define AGC_DEFAULT_TARGET_LEVEL 3 @@ -85,13 +91,13 @@ static const size_t kNumSubframes = 10; * fprintf(1, '\t%i, %i, %i, %i,\n', round(10.^(linspace(0,10,32)/20) * 2^12)); */ /* Q12 */ -static const uint16_t kGainTableAnalog[GAIN_TBL_LEN] = { +const uint16_t kGainTableAnalog[GAIN_TBL_LEN] = { 4096, 4251, 4412, 4579, 4752, 4932, 5118, 5312, 5513, 5722, 5938, 6163, 6396, 6638, 6889, 7150, 7420, 7701, 7992, 8295, 8609, 8934, 9273, 9623, 9987, 10365, 10758, 11165, 11587, 12025, 12480, 12953}; /* Gain/Suppression tables for virtual Mic (in Q10) */ -static const uint16_t kGainTableVirtualMic[128] = { +const uint16_t kGainTableVirtualMic[128] = { 1052, 1081, 1110, 1141, 1172, 1204, 1237, 1271, 1305, 1341, 1378, 1416, 1454, 1494, 1535, 1577, 1620, 1664, 1710, 1757, 1805, 1854, 1905, 1957, 2010, 2065, 2122, 2180, 2239, 2301, 2364, 2428, 2495, @@ -104,7 +110,7 @@ static const uint16_t kGainTableVirtualMic[128] = { 15212, 15628, 16055, 16494, 16945, 17409, 17885, 18374, 18877, 19393, 19923, 20468, 21028, 21603, 22194, 22801, 23425, 24065, 24724, 25400, 26095, 26808, 27541, 28295, 29069, 29864, 30681, 31520, 32382}; -static const uint16_t kSuppressionTableVirtualMic[128] = { +const uint16_t kSuppressionTableVirtualMic[128] = { 1024, 1006, 988, 970, 952, 935, 918, 902, 886, 870, 854, 839, 824, 809, 794, 780, 766, 752, 739, 726, 713, 700, 687, 675, 663, 651, 639, 628, 616, 605, 594, 584, 573, 563, 553, 543, 533, 524, 514, 505, 496, 487, 478, 470, 461, @@ -120,7 +126,7 @@ static const uint16_t kSuppressionTableVirtualMic[128] = { * targetLevelTable = fprintf('%d,\t%d,\t%d,\t%d,\n', * round((32767*10.^(-(0:63)'/20)).^2*16/2^7) */ -static const int32_t kTargetLevelTable[64] = { +const int32_t kTargetLevelTable[64] = { 134209536, 106606424, 84680493, 67264106, 53429779, 42440782, 33711911, 26778323, 21270778, 16895980, 13420954, 10660642, 8468049, 6726411, 5342978, 4244078, 3371191, 2677832, 2127078, 1689598, 1342095, diff --git a/modules/audio_processing/agc/legacy/analog_agc.h b/modules/audio_processing/agc/legacy/analog_agc.h index 7a231c8a64..fe163cb1c5 100644 --- a/modules/audio_processing/agc/legacy/analog_agc.h +++ b/modules/audio_processing/agc/legacy/analog_agc.h @@ -11,6 +11,8 @@ #ifndef MODULES_AUDIO_PROCESSING_AGC_LEGACY_ANALOG_AGC_H_ #define MODULES_AUDIO_PROCESSING_AGC_LEGACY_ANALOG_AGC_H_ +#include + #include "modules/audio_processing/agc/legacy/digital_agc.h" #include "modules/audio_processing/agc/legacy/gain_control.h" diff --git a/modules/audio_processing/agc/legacy/digital_agc.cc b/modules/audio_processing/agc/legacy/digital_agc.cc index 5bf7aaff57..6df01d07d0 100644 --- a/modules/audio_processing/agc/legacy/digital_agc.cc +++ b/modules/audio_processing/agc/legacy/digital_agc.cc @@ -10,8 +10,11 @@ #include "modules/audio_processing/agc/legacy/digital_agc.h" -#include +#include +#include +#include "common_audio/signal_processing/include/signal_processing_library.h" +#include "common_audio/signal_processing/include/spl_inl.h" #include "modules/audio_processing/agc/legacy/gain_control.h" #include "rtc_base/checks.h" @@ -39,7 +42,7 @@ namespace { // Generator table for y=log2(1+e^x) in Q8. enum { kGenFuncTableSize = 128 }; -static const uint16_t kGenFuncTable[kGenFuncTableSize] = { +const uint16_t kGenFuncTable[kGenFuncTableSize] = { 256, 485, 786, 1126, 1484, 1849, 2217, 2586, 2955, 3324, 3693, 4063, 4432, 4801, 5171, 5540, 5909, 6279, 6648, 7017, 7387, 7756, 8125, 8495, 8864, 9233, 9603, 9972, 10341, 10711, 11080, 11449, 11819, @@ -53,7 +56,7 @@ static const uint16_t kGenFuncTable[kGenFuncTableSize] = { 40626, 40996, 41365, 41734, 42104, 42473, 42842, 43212, 43581, 43950, 44320, 44689, 45058, 45428, 45797, 46166, 46536, 46905}; -static const int16_t kAvgDecayTime = 250; // frames; < 3000 +const int16_t kAvgDecayTime = 250; // frames; < 3000 // the 32 most significant bits of A(19) * B(26) >> 13 #define AGC_MUL32(A, B) (((B) >> 13) * (A) + (((0x00001FFF & (B)) * (A)) >> 13)) diff --git a/modules/audio_processing/agc/legacy/digital_agc.h b/modules/audio_processing/agc/legacy/digital_agc.h index 223c74b9bd..43d53c5dca 100644 --- a/modules/audio_processing/agc/legacy/digital_agc.h +++ b/modules/audio_processing/agc/legacy/digital_agc.h @@ -11,7 +11,8 @@ #ifndef MODULES_AUDIO_PROCESSING_AGC_LEGACY_DIGITAL_AGC_H_ #define MODULES_AUDIO_PROCESSING_AGC_LEGACY_DIGITAL_AGC_H_ -#include "common_audio/signal_processing/include/signal_processing_library.h" +#include +#include namespace webrtc { diff --git a/modules/audio_processing/agc/loudness_histogram.cc b/modules/audio_processing/agc/loudness_histogram.cc index 492d00b390..bfa213be90 100644 --- a/modules/audio_processing/agc/loudness_histogram.cc +++ b/modules/audio_processing/agc/loudness_histogram.cc @@ -10,9 +10,9 @@ #include "modules/audio_processing/agc/loudness_histogram.h" -#include - #include +#include +#include #include "rtc_base/checks.h" diff --git a/modules/audio_processing/agc/mock_agc.h b/modules/audio_processing/agc/mock_agc.h index bc31148153..548358b641 100644 --- a/modules/audio_processing/agc/mock_agc.h +++ b/modules/audio_processing/agc/mock_agc.h @@ -11,6 +11,8 @@ #ifndef MODULES_AUDIO_PROCESSING_AGC_MOCK_AGC_H_ #define MODULES_AUDIO_PROCESSING_AGC_MOCK_AGC_H_ +#include + #include "api/array_view.h" #include "modules/audio_processing/agc/agc.h" #include "test/gmock.h" @@ -20,10 +22,7 @@ namespace webrtc { class MockAgc : public Agc { public: virtual ~MockAgc() {} - MOCK_METHOD(void, - Process, - (webrtc::ArrayView audio), - (override)); + MOCK_METHOD(void, Process, (ArrayView audio), (override)); MOCK_METHOD(bool, GetRmsErrorDb, (int* error), (override)); MOCK_METHOD(void, Reset, (), (override)); MOCK_METHOD(int, set_target_level_dbfs, (int level), (override)); diff --git a/modules/audio_processing/agc2/BUILD.gn b/modules/audio_processing/agc2/BUILD.gn index e9d1743f4e..36d7f983f1 100644 --- a/modules/audio_processing/agc2/BUILD.gn +++ b/modules/audio_processing/agc2/BUILD.gn @@ -91,7 +91,7 @@ rtc_library("biquad_filter") { ] deps = [ "../../../api:array_view", - "../../../rtc_base:macromagic", + "../../../rtc_base:checks", ] } @@ -173,6 +173,7 @@ rtc_library("gain_applier") { ":common", "..:audio_frame_view", "../../../api/audio:audio_frame_api", + "../../../rtc_base:checks", "../../../rtc_base:safe_minmax", ] } @@ -197,6 +198,7 @@ rtc_library("input_volume_controller") { visibility = [ "..:audio_processing", + "..:audio_processing_unittests", "..:gain_controller2", "./*", ] @@ -249,6 +251,7 @@ rtc_library("vad_wrapper") { ] visibility = [ + "..:audio_processing_unittests", "..:gain_controller2", "./*", ] @@ -277,14 +280,15 @@ rtc_library("cpu_features") { ] visibility = [ + "..:audio_processing_unittests", "..:gain_controller2", "./*", ] deps = [ + "../../../rtc_base:cpu_info", "../../../rtc_base:stringutils", "../../../rtc_base/system:arch", - "../../../system_wrappers", ] } @@ -298,6 +302,7 @@ rtc_library("speech_level_estimator_unittest") { ":speech_level_estimator", "..:apm_logging", "../../../api/audio:audio_processing", + "../../../rtc_base:checks", "../../../rtc_base:gunit_helpers", "../../../test:test_support", ] @@ -358,7 +363,9 @@ rtc_library("biquad_filter_unittests") { sources = [ "biquad_filter_unittest.cc" ] deps = [ ":biquad_filter", + "../../../api:array_view", "../../../rtc_base:gunit_helpers", + "../../../test:test_support", ] } @@ -389,6 +396,7 @@ rtc_library("fixed_digital_unittests") { "../../../rtc_base:checks", "../../../rtc_base:gunit_helpers", "../../../system_wrappers:metrics", + "../../../test:test_support", ] } @@ -408,6 +416,7 @@ rtc_library("input_volume_controller_unittests") { ":gain_map", ":input_volume_controller", "..:audio_buffer", + "..:audio_frame_view", "../../../api:array_view", "../../../api/audio:audio_processing", "../../../rtc_base:checks", @@ -436,6 +445,7 @@ rtc_library("noise_estimator_unittests") { "../../../api/audio:audio_frame_api", "../../../rtc_base:checks", "../../../rtc_base:gunit_helpers", + "../../../test:test_support", ] } @@ -445,6 +455,7 @@ rtc_library("vad_wrapper_unittests") { deps = [ ":common", ":vad_wrapper", + "../../../api:array_view", "../../../api/audio:audio_frame_api", "../../../rtc_base:checks", "../../../rtc_base:gunit_helpers", @@ -479,6 +490,7 @@ rtc_library("input_volume_stats_reporter") { "input_volume_stats_reporter.h", ] deps = [ + "../../../rtc_base:checks", "../../../rtc_base:gtest_prod", "../../../rtc_base:logging", "../../../rtc_base:safe_minmax", diff --git a/modules/audio_processing/agc2/adaptive_digital_gain_controller.cc b/modules/audio_processing/agc2/adaptive_digital_gain_controller.cc index 8bbbedced5..adfc4fc3cc 100644 --- a/modules/audio_processing/agc2/adaptive_digital_gain_controller.cc +++ b/modules/audio_processing/agc2/adaptive_digital_gain_controller.cc @@ -12,6 +12,8 @@ #include +#include "api/audio/audio_processing.h" +#include "api/audio/audio_view.h" #include "common_audio/include/audio_util.h" #include "modules/audio_processing/agc2/agc2_common.h" #include "modules/audio_processing/logging/apm_data_dumper.h" diff --git a/modules/audio_processing/agc2/adaptive_digital_gain_controller.h b/modules/audio_processing/agc2/adaptive_digital_gain_controller.h index d464dc6b2c..cc618da935 100644 --- a/modules/audio_processing/agc2/adaptive_digital_gain_controller.h +++ b/modules/audio_processing/agc2/adaptive_digital_gain_controller.h @@ -11,7 +11,6 @@ #ifndef MODULES_AUDIO_PROCESSING_AGC2_ADAPTIVE_DIGITAL_GAIN_CONTROLLER_H_ #define MODULES_AUDIO_PROCESSING_AGC2_ADAPTIVE_DIGITAL_GAIN_CONTROLLER_H_ -#include #include "api/audio/audio_processing.h" #include "api/audio/audio_view.h" diff --git a/modules/audio_processing/agc2/adaptive_digital_gain_controller_unittest.cc b/modules/audio_processing/agc2/adaptive_digital_gain_controller_unittest.cc index 1647a5b6f9..248fc75bba 100644 --- a/modules/audio_processing/agc2/adaptive_digital_gain_controller_unittest.cc +++ b/modules/audio_processing/agc2/adaptive_digital_gain_controller_unittest.cc @@ -19,7 +19,7 @@ #include "modules/audio_processing/agc2/agc2_common.h" #include "modules/audio_processing/agc2/vector_float_frame.h" #include "modules/audio_processing/logging/apm_data_dumper.h" -#include "rtc_base/gunit.h" +#include "test/gtest.h" namespace webrtc { namespace { diff --git a/modules/audio_processing/agc2/agc2_testing_common.cc b/modules/audio_processing/agc2/agc2_testing_common.cc index b9d0492fca..4f54e4c2e8 100644 --- a/modules/audio_processing/agc2/agc2_testing_common.cc +++ b/modules/audio_processing/agc2/agc2_testing_common.cc @@ -10,9 +10,9 @@ #include "modules/audio_processing/agc2/agc2_testing_common.h" -#include - +#include #include +#include #include "rtc_base/checks.h" diff --git a/modules/audio_processing/agc2/agc2_testing_common.h b/modules/audio_processing/agc2/agc2_testing_common.h index afed97e83b..2701e24b2a 100644 --- a/modules/audio_processing/agc2/agc2_testing_common.h +++ b/modules/audio_processing/agc2/agc2_testing_common.h @@ -11,6 +11,7 @@ #ifndef MODULES_AUDIO_PROCESSING_AGC2_AGC2_TESTING_COMMON_H_ #define MODULES_AUDIO_PROCESSING_AGC2_AGC2_TESTING_COMMON_H_ +#include #include #include diff --git a/modules/audio_processing/agc2/agc2_testing_common_unittest.cc b/modules/audio_processing/agc2/agc2_testing_common_unittest.cc index 79c3cc95d9..cb524b8805 100644 --- a/modules/audio_processing/agc2/agc2_testing_common_unittest.cc +++ b/modules/audio_processing/agc2/agc2_testing_common_unittest.cc @@ -10,7 +10,9 @@ #include "modules/audio_processing/agc2/agc2_testing_common.h" -#include "rtc_base/gunit.h" +#include + +#include "test/gtest.h" namespace webrtc { diff --git a/modules/audio_processing/agc2/biquad_filter.cc b/modules/audio_processing/agc2/biquad_filter.cc index e2e112904c..9ff831a04e 100644 --- a/modules/audio_processing/agc2/biquad_filter.cc +++ b/modules/audio_processing/agc2/biquad_filter.cc @@ -10,7 +10,10 @@ #include "modules/audio_processing/agc2/biquad_filter.h" -#include "rtc_base/arraysize.h" +#include + +#include "api/array_view.h" +#include "rtc_base/checks.h" namespace webrtc { diff --git a/modules/audio_processing/agc2/biquad_filter_unittest.cc b/modules/audio_processing/agc2/biquad_filter_unittest.cc index 8ef85744d0..db29bfef82 100644 --- a/modules/audio_processing/agc2/biquad_filter_unittest.cc +++ b/modules/audio_processing/agc2/biquad_filter_unittest.cc @@ -13,10 +13,12 @@ #include #include #include +#include // TODO(bugs.webrtc.org/8948): Add when the issue is fixed. // #include "test/fpe_observer.h" -#include "rtc_base/gunit.h" +#include "api/array_view.h" +#include "test/gtest.h" namespace webrtc { namespace { @@ -56,7 +58,7 @@ constexpr FloatArraySequence kBiQuadOutputSeq = { {{24.84286614f, -62.18094158f, 57.91488056f, -106.65685933f, 13.38760103f, -36.60367134f, -94.44880104f, -3.59920354f}}}}; -// Fails for every pair from two equally sized webrtc::ArrayView views +// Fails for every pair from two equally sized ArrayView views // such that their relative error is above a given threshold. If the expected // value of a pair is 0, `tolerance` is used to check the absolute error. void ExpectNearRelative(ArrayView expected, diff --git a/modules/audio_processing/agc2/clipping_predictor.cc b/modules/audio_processing/agc2/clipping_predictor.cc index 77f928d2bd..a14ed7eb78 100644 --- a/modules/audio_processing/agc2/clipping_predictor.cc +++ b/modules/audio_processing/agc2/clipping_predictor.cc @@ -11,11 +11,16 @@ #include "modules/audio_processing/agc2/clipping_predictor.h" #include +#include #include +#include +#include +#include "api/audio/audio_processing.h" #include "common_audio/include/audio_util.h" #include "modules/audio_processing/agc2/clipping_predictor_level_buffer.h" #include "modules/audio_processing/agc2/gain_map_internal.h" +#include "modules/audio_processing/include/audio_frame_view.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "rtc_base/numerics/safe_minmax.h" @@ -97,9 +102,9 @@ class ClippingEventPredictor : public ClippingPredictor { ClippingEventPredictor(const ClippingEventPredictor&) = delete; ClippingEventPredictor& operator=(const ClippingEventPredictor&) = delete; - ~ClippingEventPredictor() {} + ~ClippingEventPredictor() override {} - void Reset() { + void Reset() override { const int num_channels = ch_buffers_.size(); for (int i = 0; i < num_channels; ++i) { ch_buffers_[i]->Reset(); @@ -108,7 +113,7 @@ class ClippingEventPredictor : public ClippingPredictor { // Analyzes a frame of audio and stores the framewise metrics in // `ch_buffers_`. - void Analyze(const AudioFrameView& frame) { + void Analyze(const AudioFrameView& frame) override { const int num_channels = frame.num_channels(); RTC_DCHECK_EQ(num_channels, ch_buffers_.size()); const int samples_per_channel = frame.samples_per_channel(); @@ -131,11 +136,12 @@ class ClippingEventPredictor : public ClippingPredictor { // if at least `GetMinFramesProcessed()` frames have been processed since the // last reset and a clipping event is predicted. `level`, `min_mic_level`, and // `max_mic_level` are limited to [0, 255] and `default_step` to [1, 255]. - std::optional EstimateClippedLevelStep(int channel, - int level, - int default_step, - int min_mic_level, - int max_mic_level) const { + std::optional EstimateClippedLevelStep( + int channel, + int level, + int default_step, + int min_mic_level, + int max_mic_level) const override { RTC_CHECK_GE(channel, 0); RTC_CHECK_LT(channel, ch_buffers_.size()); RTC_DCHECK_GE(level, 0); @@ -236,9 +242,9 @@ class ClippingPeakPredictor : public ClippingPredictor { ClippingPeakPredictor(const ClippingPeakPredictor&) = delete; ClippingPeakPredictor& operator=(const ClippingPeakPredictor&) = delete; - ~ClippingPeakPredictor() {} + ~ClippingPeakPredictor() override {} - void Reset() { + void Reset() override { const int num_channels = ch_buffers_.size(); for (int i = 0; i < num_channels; ++i) { ch_buffers_[i]->Reset(); @@ -247,7 +253,7 @@ class ClippingPeakPredictor : public ClippingPredictor { // Analyzes a frame of audio and stores the framewise metrics in // `ch_buffers_`. - void Analyze(const AudioFrameView& frame) { + void Analyze(const AudioFrameView& frame) override { const int num_channels = frame.num_channels(); RTC_DCHECK_EQ(num_channels, ch_buffers_.size()); const int samples_per_channel = frame.samples_per_channel(); @@ -271,11 +277,12 @@ class ClippingPeakPredictor : public ClippingPredictor { // least `GetMinFramesProcessed()` frames have been processed since the last // reset and a clipping event is predicted. `level`, `min_mic_level`, and // `max_mic_level` are limited to [0, 255] and `default_step` to [1, 255]. - std::optional EstimateClippedLevelStep(int channel, - int level, - int default_step, - int min_mic_level, - int max_mic_level) const { + std::optional EstimateClippedLevelStep( + int channel, + int level, + int default_step, + int min_mic_level, + int max_mic_level) const override { RTC_DCHECK_GE(channel, 0); RTC_DCHECK_LT(channel, ch_buffers_.size()); RTC_DCHECK_GE(level, 0); diff --git a/modules/audio_processing/agc2/clipping_predictor.h b/modules/audio_processing/agc2/clipping_predictor.h index 3fd1086631..259f790ff5 100644 --- a/modules/audio_processing/agc2/clipping_predictor.h +++ b/modules/audio_processing/agc2/clipping_predictor.h @@ -13,7 +13,6 @@ #include #include -#include #include "api/audio/audio_processing.h" #include "modules/audio_processing/include/audio_frame_view.h" diff --git a/modules/audio_processing/agc2/clipping_predictor_level_buffer.cc b/modules/audio_processing/agc2/clipping_predictor_level_buffer.cc index acc114c476..4cc2f05ce6 100644 --- a/modules/audio_processing/agc2/clipping_predictor_level_buffer.cc +++ b/modules/audio_processing/agc2/clipping_predictor_level_buffer.cc @@ -12,6 +12,7 @@ #include #include +#include #include "rtc_base/checks.h" #include "rtc_base/logging.h" diff --git a/modules/audio_processing/agc2/clipping_predictor_level_buffer.h b/modules/audio_processing/agc2/clipping_predictor_level_buffer.h index 21e9b461a7..6979641af6 100644 --- a/modules/audio_processing/agc2/clipping_predictor_level_buffer.h +++ b/modules/audio_processing/agc2/clipping_predictor_level_buffer.h @@ -11,7 +11,6 @@ #ifndef MODULES_AUDIO_PROCESSING_AGC2_CLIPPING_PREDICTOR_LEVEL_BUFFER_H_ #define MODULES_AUDIO_PROCESSING_AGC2_CLIPPING_PREDICTOR_LEVEL_BUFFER_H_ -#include #include #include diff --git a/modules/audio_processing/agc2/clipping_predictor_level_buffer_unittest.cc b/modules/audio_processing/agc2/clipping_predictor_level_buffer_unittest.cc index 4f20ddb0b7..2ffa3f2ccc 100644 --- a/modules/audio_processing/agc2/clipping_predictor_level_buffer_unittest.cc +++ b/modules/audio_processing/agc2/clipping_predictor_level_buffer_unittest.cc @@ -11,6 +11,7 @@ #include "modules/audio_processing/agc2/clipping_predictor_level_buffer.h" #include +#include #include "test/gmock.h" #include "test/gtest.h" diff --git a/modules/audio_processing/agc2/clipping_predictor_unittest.cc b/modules/audio_processing/agc2/clipping_predictor_unittest.cc index dbb6c23eb7..b25c660d5b 100644 --- a/modules/audio_processing/agc2/clipping_predictor_unittest.cc +++ b/modules/audio_processing/agc2/clipping_predictor_unittest.cc @@ -12,8 +12,12 @@ #include #include +#include #include +#include +#include "api/audio/audio_processing.h" +#include "modules/audio_processing/include/audio_frame_view.h" #include "rtc_base/checks.h" #include "test/gmock.h" #include "test/gtest.h" diff --git a/modules/audio_processing/agc2/compute_interpolated_gain_curve.cc b/modules/audio_processing/agc2/compute_interpolated_gain_curve.cc index 221b499e32..db71f97534 100644 --- a/modules/audio_processing/agc2/compute_interpolated_gain_curve.cc +++ b/modules/audio_processing/agc2/compute_interpolated_gain_curve.cc @@ -11,7 +11,7 @@ #include "modules/audio_processing/agc2/compute_interpolated_gain_curve.h" #include -#include +#include #include #include #include diff --git a/modules/audio_processing/agc2/cpu_features.cc b/modules/audio_processing/agc2/cpu_features.cc index aa5a57834f..af505175be 100644 --- a/modules/audio_processing/agc2/cpu_features.cc +++ b/modules/audio_processing/agc2/cpu_features.cc @@ -10,9 +10,11 @@ #include "modules/audio_processing/agc2/cpu_features.h" +#include + +#include "rtc_base/cpu_info.h" #include "rtc_base/strings/string_builder.h" #include "rtc_base/system/arch.h" -#include "system_wrappers/include/cpu_features_wrapper.h" namespace webrtc { @@ -41,8 +43,8 @@ std::string AvailableCpuFeatures::ToString() const { // Detects available CPU features. AvailableCpuFeatures GetAvailableCpuFeatures() { #if defined(WEBRTC_ARCH_X86_FAMILY) - return {/*sse2=*/GetCPUInfo(kSSE2) != 0, - /*avx2=*/GetCPUInfo(kAVX2) != 0, + return {/*sse2=*/cpu_info::Supports(cpu_info::ISA::kSSE2), + /*avx2=*/cpu_info::Supports(cpu_info::ISA::kAVX2), /*neon=*/false}; #elif defined(WEBRTC_HAS_NEON) return {/*sse2=*/false, diff --git a/modules/audio_processing/agc2/fixed_digital_level_estimator.cc b/modules/audio_processing/agc2/fixed_digital_level_estimator.cc index 20e8491c0e..a84bb2c0b0 100644 --- a/modules/audio_processing/agc2/fixed_digital_level_estimator.cc +++ b/modules/audio_processing/agc2/fixed_digital_level_estimator.cc @@ -11,10 +11,14 @@ #include "modules/audio_processing/agc2/fixed_digital_level_estimator.h" #include +#include #include +#include #include "api/array_view.h" #include "api/audio/audio_frame.h" +#include "api/audio/audio_view.h" +#include "modules/audio_processing/agc2/agc2_common.h" #include "modules/audio_processing/logging/apm_data_dumper.h" #include "rtc_base/checks.h" diff --git a/modules/audio_processing/agc2/fixed_digital_level_estimator.h b/modules/audio_processing/agc2/fixed_digital_level_estimator.h index 1669acdc71..3e5f11bd70 100644 --- a/modules/audio_processing/agc2/fixed_digital_level_estimator.h +++ b/modules/audio_processing/agc2/fixed_digital_level_estimator.h @@ -12,10 +12,10 @@ #define MODULES_AUDIO_PROCESSING_AGC2_FIXED_DIGITAL_LEVEL_ESTIMATOR_H_ #include -#include +#include +#include "api/audio/audio_view.h" #include "modules/audio_processing/agc2/agc2_common.h" -#include "modules/audio_processing/include/audio_frame_view.h" namespace webrtc { diff --git a/modules/audio_processing/agc2/fixed_digital_level_estimator_unittest.cc b/modules/audio_processing/agc2/fixed_digital_level_estimator_unittest.cc index c76db85a5c..7b609c7cec 100644 --- a/modules/audio_processing/agc2/fixed_digital_level_estimator_unittest.cc +++ b/modules/audio_processing/agc2/fixed_digital_level_estimator_unittest.cc @@ -10,6 +10,7 @@ #include "modules/audio_processing/agc2/fixed_digital_level_estimator.h" +#include #include #include "api/audio/audio_frame.h" @@ -18,7 +19,8 @@ #include "modules/audio_processing/agc2/agc2_testing_common.h" #include "modules/audio_processing/agc2/vector_float_frame.h" #include "modules/audio_processing/logging/apm_data_dumper.h" -#include "rtc_base/gunit.h" +#include "rtc_base/checks.h" +#include "test/gtest.h" namespace webrtc { namespace { diff --git a/modules/audio_processing/agc2/gain_applier.cc b/modules/audio_processing/agc2/gain_applier.cc index 927bb554c4..5c7d3d3827 100644 --- a/modules/audio_processing/agc2/gain_applier.cc +++ b/modules/audio_processing/agc2/gain_applier.cc @@ -10,8 +10,11 @@ #include "modules/audio_processing/agc2/gain_applier.h" +#include + #include "api/audio/audio_view.h" #include "modules/audio_processing/agc2/agc2_common.h" +#include "rtc_base/checks.h" #include "rtc_base/numerics/safe_minmax.h" namespace webrtc { diff --git a/modules/audio_processing/agc2/gain_applier_unittest.cc b/modules/audio_processing/agc2/gain_applier_unittest.cc index 7548faa61b..4c8860d582 100644 --- a/modules/audio_processing/agc2/gain_applier_unittest.cc +++ b/modules/audio_processing/agc2/gain_applier_unittest.cc @@ -13,11 +13,13 @@ #include #include +#include +#include #include #include "api/audio/audio_view.h" #include "modules/audio_processing/agc2/vector_float_frame.h" -#include "rtc_base/gunit.h" +#include "test/gtest.h" namespace webrtc { TEST(AutomaticGainController2GainApplier, InitialGainIsRespected) { diff --git a/modules/audio_processing/agc2/input_volume_controller.h b/modules/audio_processing/agc2/input_volume_controller.h index 60e76d8e04..011febfb94 100644 --- a/modules/audio_processing/agc2/input_volume_controller.h +++ b/modules/audio_processing/agc2/input_volume_controller.h @@ -15,7 +15,6 @@ #include #include -#include "api/array_view.h" #include "api/audio/audio_processing.h" #include "modules/audio_processing/agc2/clipping_predictor.h" #include "modules/audio_processing/audio_buffer.h" diff --git a/modules/audio_processing/agc2/input_volume_stats_reporter.cc b/modules/audio_processing/agc2/input_volume_stats_reporter.cc index a0f33a7311..ed580a81cc 100644 --- a/modules/audio_processing/agc2/input_volume_stats_reporter.cc +++ b/modules/audio_processing/agc2/input_volume_stats_reporter.cc @@ -13,8 +13,8 @@ #include #include "absl/strings/string_view.h" +#include "rtc_base/checks.h" #include "rtc_base/logging.h" -#include "rtc_base/numerics/safe_minmax.h" #include "rtc_base/strings/string_builder.h" #include "system_wrappers/include/metrics.h" diff --git a/modules/audio_processing/agc2/input_volume_stats_reporter_unittest.cc b/modules/audio_processing/agc2/input_volume_stats_reporter_unittest.cc index 5db063d53d..8cbbd72e99 100644 --- a/modules/audio_processing/agc2/input_volume_stats_reporter_unittest.cc +++ b/modules/audio_processing/agc2/input_volume_stats_reporter_unittest.cc @@ -10,10 +10,13 @@ #include "modules/audio_processing/agc2/input_volume_stats_reporter.h" +#include + #include "absl/strings/string_view.h" #include "rtc_base/strings/string_builder.h" #include "system_wrappers/include/metrics.h" #include "test/gmock.h" +#include "test/gtest.h" namespace webrtc { namespace { diff --git a/modules/audio_processing/agc2/interpolated_gain_curve.cc b/modules/audio_processing/agc2/interpolated_gain_curve.cc index d7651dddd7..0aa9ffcb54 100644 --- a/modules/audio_processing/agc2/interpolated_gain_curve.cc +++ b/modules/audio_processing/agc2/interpolated_gain_curve.cc @@ -11,6 +11,8 @@ #include "modules/audio_processing/agc2/interpolated_gain_curve.h" #include +#include +#include #include #include "absl/strings/string_view.h" @@ -18,6 +20,7 @@ #include "modules/audio_processing/logging/apm_data_dumper.h" #include "rtc_base/checks.h" #include "rtc_base/strings/string_builder.h" +#include "system_wrappers/include/metrics.h" namespace webrtc { diff --git a/modules/audio_processing/agc2/interpolated_gain_curve.h b/modules/audio_processing/agc2/interpolated_gain_curve.h index 8dd3e48f21..71371e34da 100644 --- a/modules/audio_processing/agc2/interpolated_gain_curve.h +++ b/modules/audio_processing/agc2/interpolated_gain_curve.h @@ -12,6 +12,8 @@ #define MODULES_AUDIO_PROCESSING_AGC2_INTERPOLATED_GAIN_CURVE_H_ #include +#include +#include #include "absl/strings/string_view.h" #include "modules/audio_processing/agc2/agc2_common.h" diff --git a/modules/audio_processing/agc2/interpolated_gain_curve_unittest.cc b/modules/audio_processing/agc2/interpolated_gain_curve_unittest.cc index 7861ae997d..aad6921255 100644 --- a/modules/audio_processing/agc2/interpolated_gain_curve_unittest.cc +++ b/modules/audio_processing/agc2/interpolated_gain_curve_unittest.cc @@ -11,17 +11,19 @@ #include "modules/audio_processing/agc2/interpolated_gain_curve.h" #include +#include +#include +#include #include #include -#include "api/array_view.h" #include "common_audio/include/audio_util.h" #include "modules/audio_processing/agc2/agc2_common.h" +#include "modules/audio_processing/agc2/agc2_testing_common.h" #include "modules/audio_processing/agc2/compute_interpolated_gain_curve.h" #include "modules/audio_processing/agc2/limiter_db_gain_curve.h" #include "modules/audio_processing/logging/apm_data_dumper.h" -#include "rtc_base/checks.h" -#include "rtc_base/gunit.h" +#include "test/gtest.h" namespace webrtc { namespace { diff --git a/modules/audio_processing/agc2/limiter_db_gain_curve.cc b/modules/audio_processing/agc2/limiter_db_gain_curve.cc index d47c0b2e17..acf6856337 100644 --- a/modules/audio_processing/agc2/limiter_db_gain_curve.cc +++ b/modules/audio_processing/agc2/limiter_db_gain_curve.cc @@ -10,6 +10,7 @@ #include "modules/audio_processing/agc2/limiter_db_gain_curve.h" +#include #include #include "common_audio/include/audio_util.h" diff --git a/modules/audio_processing/agc2/limiter_db_gain_curve_unittest.cc b/modules/audio_processing/agc2/limiter_db_gain_curve_unittest.cc index 049c8d568e..efdba5094c 100644 --- a/modules/audio_processing/agc2/limiter_db_gain_curve_unittest.cc +++ b/modules/audio_processing/agc2/limiter_db_gain_curve_unittest.cc @@ -10,7 +10,7 @@ #include "modules/audio_processing/agc2/limiter_db_gain_curve.h" -#include "rtc_base/gunit.h" +#include "test/gtest.h" namespace webrtc { diff --git a/modules/audio_processing/agc2/limiter_unittest.cc b/modules/audio_processing/agc2/limiter_unittest.cc index 6c72e729ee..c3383b7313 100644 --- a/modules/audio_processing/agc2/limiter_unittest.cc +++ b/modules/audio_processing/agc2/limiter_unittest.cc @@ -11,13 +11,15 @@ #include "modules/audio_processing/agc2/limiter.h" #include +#include +#include +#include "api/audio/audio_view.h" #include "common_audio/include/audio_util.h" #include "modules/audio_processing/agc2/agc2_common.h" #include "modules/audio_processing/agc2/agc2_testing_common.h" -#include "modules/audio_processing/agc2/vector_float_frame.h" #include "modules/audio_processing/logging/apm_data_dumper.h" -#include "rtc_base/gunit.h" +#include "test/gtest.h" namespace webrtc { diff --git a/modules/audio_processing/agc2/noise_level_estimator.cc b/modules/audio_processing/agc2/noise_level_estimator.cc index c43738aad3..76e7bfb0f5 100644 --- a/modules/audio_processing/agc2/noise_level_estimator.cc +++ b/modules/audio_processing/agc2/noise_level_estimator.cc @@ -14,6 +14,7 @@ #include #include +#include #include #include "api/audio/audio_view.h" @@ -80,7 +81,7 @@ class NoiseFloorEstimator : public NoiseLevelEstimator { } NoiseFloorEstimator(const NoiseFloorEstimator&) = delete; NoiseFloorEstimator& operator=(const NoiseFloorEstimator&) = delete; - ~NoiseFloorEstimator() = default; + ~NoiseFloorEstimator() override = default; float Analyze(DeinterleavedView frame) override { // Detect sample rate changes. diff --git a/modules/audio_processing/agc2/noise_level_estimator_unittest.cc b/modules/audio_processing/agc2/noise_level_estimator_unittest.cc index 1825f5c29c..87e1db3240 100644 --- a/modules/audio_processing/agc2/noise_level_estimator_unittest.cc +++ b/modules/audio_processing/agc2/noise_level_estimator_unittest.cc @@ -10,17 +10,15 @@ #include "modules/audio_processing/agc2/noise_level_estimator.h" -#include #include -#include -#include #include "api/audio/audio_view.h" #include "api/function_view.h" #include "modules/audio_processing/agc2/agc2_testing_common.h" #include "modules/audio_processing/agc2/vector_float_frame.h" #include "modules/audio_processing/logging/apm_data_dumper.h" -#include "rtc_base/gunit.h" +#include "rtc_base/checks.h" +#include "test/gtest.h" namespace webrtc { namespace { diff --git a/modules/audio_processing/agc2/rnn_vad/BUILD.gn b/modules/audio_processing/agc2/rnn_vad/BUILD.gn index ddec89972d..075e2a8110 100644 --- a/modules/audio_processing/agc2/rnn_vad/BUILD.gn +++ b/modules/audio_processing/agc2/rnn_vad/BUILD.gn @@ -321,6 +321,7 @@ if (rtc_include_tests) { "..:cpu_features", "../../../../api:array_view", "../../../../common_audio", + "../../../../rtc_base:checks", "../../../../rtc_base:logging", "../../../../rtc_base:safe_compare", "../../../../test:test_support", diff --git a/modules/audio_processing/agc2/rnn_vad/auto_correlation.cc b/modules/audio_processing/agc2/rnn_vad/auto_correlation.cc index f079b0107c..b5f9f758a3 100644 --- a/modules/audio_processing/agc2/rnn_vad/auto_correlation.cc +++ b/modules/audio_processing/agc2/rnn_vad/auto_correlation.cc @@ -12,6 +12,9 @@ #include +#include "api/array_view.h" +#include "modules/audio_processing/agc2/rnn_vad/common.h" +#include "modules/audio_processing/utility/pffft_wrapper.h" #include "rtc_base/checks.h" namespace webrtc { diff --git a/modules/audio_processing/agc2/rnn_vad/auto_correlation_unittest.cc b/modules/audio_processing/agc2/rnn_vad/auto_correlation_unittest.cc index 76001ed7b7..afcbaa5858 100644 --- a/modules/audio_processing/agc2/rnn_vad/auto_correlation_unittest.cc +++ b/modules/audio_processing/agc2/rnn_vad/auto_correlation_unittest.cc @@ -10,6 +10,9 @@ #include "modules/audio_processing/agc2/rnn_vad/auto_correlation.h" +#include +#include + #include "modules/audio_processing/agc2/rnn_vad/common.h" #include "modules/audio_processing/agc2/rnn_vad/pitch_search_internal.h" #include "modules/audio_processing/agc2/rnn_vad/test_utils.h" diff --git a/modules/audio_processing/agc2/rnn_vad/features_extraction.cc b/modules/audio_processing/agc2/rnn_vad/features_extraction.cc index b090281493..f602bb43a9 100644 --- a/modules/audio_processing/agc2/rnn_vad/features_extraction.cc +++ b/modules/audio_processing/agc2/rnn_vad/features_extraction.cc @@ -12,6 +12,10 @@ #include +#include "api/array_view.h" +#include "modules/audio_processing/agc2/biquad_filter.h" +#include "modules/audio_processing/agc2/cpu_features.h" +#include "modules/audio_processing/agc2/rnn_vad/common.h" #include "modules/audio_processing/agc2/rnn_vad/lp_residual.h" #include "rtc_base/checks.h" diff --git a/modules/audio_processing/agc2/rnn_vad/features_extraction.h b/modules/audio_processing/agc2/rnn_vad/features_extraction.h index 3fe14a4990..2928a7fa00 100644 --- a/modules/audio_processing/agc2/rnn_vad/features_extraction.h +++ b/modules/audio_processing/agc2/rnn_vad/features_extraction.h @@ -15,6 +15,7 @@ #include "api/array_view.h" #include "modules/audio_processing/agc2/biquad_filter.h" +#include "modules/audio_processing/agc2/cpu_features.h" #include "modules/audio_processing/agc2/rnn_vad/common.h" #include "modules/audio_processing/agc2/rnn_vad/pitch_search.h" #include "modules/audio_processing/agc2/rnn_vad/sequence_buffer.h" diff --git a/modules/audio_processing/agc2/rnn_vad/features_extraction_unittest.cc b/modules/audio_processing/agc2/rnn_vad/features_extraction_unittest.cc index f6a1392f62..9f5b4d37ff 100644 --- a/modules/audio_processing/agc2/rnn_vad/features_extraction_unittest.cc +++ b/modules/audio_processing/agc2/rnn_vad/features_extraction_unittest.cc @@ -13,7 +13,9 @@ #include #include +#include "api/array_view.h" #include "modules/audio_processing/agc2/cpu_features.h" +#include "modules/audio_processing/agc2/rnn_vad/common.h" #include "rtc_base/numerics/safe_compare.h" #include "rtc_base/numerics/safe_conversions.h" // TODO(bugs.webrtc.org/8948): Add when the issue is fixed. diff --git a/modules/audio_processing/agc2/rnn_vad/lp_residual.cc b/modules/audio_processing/agc2/rnn_vad/lp_residual.cc index f942099b01..6568f93e4d 100644 --- a/modules/audio_processing/agc2/rnn_vad/lp_residual.cc +++ b/modules/audio_processing/agc2/rnn_vad/lp_residual.cc @@ -15,6 +15,7 @@ #include #include +#include "api/array_view.h" #include "rtc_base/checks.h" #include "rtc_base/numerics/safe_compare.h" diff --git a/modules/audio_processing/agc2/rnn_vad/pitch_search.cc b/modules/audio_processing/agc2/rnn_vad/pitch_search.cc index 3d4bb3f848..d6fe28be58 100644 --- a/modules/audio_processing/agc2/rnn_vad/pitch_search.cc +++ b/modules/audio_processing/agc2/rnn_vad/pitch_search.cc @@ -10,9 +10,12 @@ #include "modules/audio_processing/agc2/rnn_vad/pitch_search.h" -#include #include +#include "api/array_view.h" +#include "modules/audio_processing/agc2/cpu_features.h" +#include "modules/audio_processing/agc2/rnn_vad/common.h" +#include "modules/audio_processing/agc2/rnn_vad/pitch_search_internal.h" #include "rtc_base/checks.h" namespace webrtc { diff --git a/modules/audio_processing/agc2/rnn_vad/pitch_search.h b/modules/audio_processing/agc2/rnn_vad/pitch_search.h index 28f755e316..2804424893 100644 --- a/modules/audio_processing/agc2/rnn_vad/pitch_search.h +++ b/modules/audio_processing/agc2/rnn_vad/pitch_search.h @@ -11,7 +11,6 @@ #ifndef MODULES_AUDIO_PROCESSING_AGC2_RNN_VAD_PITCH_SEARCH_H_ #define MODULES_AUDIO_PROCESSING_AGC2_RNN_VAD_PITCH_SEARCH_H_ -#include #include #include "api/array_view.h" diff --git a/modules/audio_processing/agc2/rnn_vad/pitch_search_internal.cc b/modules/audio_processing/agc2/rnn_vad/pitch_search_internal.cc index ebb03bd854..70ab6e95a8 100644 --- a/modules/audio_processing/agc2/rnn_vad/pitch_search_internal.cc +++ b/modules/audio_processing/agc2/rnn_vad/pitch_search_internal.cc @@ -10,19 +10,17 @@ #include "modules/audio_processing/agc2/rnn_vad/pitch_search_internal.h" -#include - #include +#include #include #include -#include +#include +#include "api/array_view.h" +#include "modules/audio_processing/agc2/cpu_features.h" #include "modules/audio_processing/agc2/rnn_vad/common.h" #include "modules/audio_processing/agc2/rnn_vad/vector_math.h" #include "rtc_base/checks.h" -#include "rtc_base/numerics/safe_compare.h" -#include "rtc_base/numerics/safe_conversions.h" -#include "rtc_base/system/arch.h" namespace webrtc { namespace rnn_vad { diff --git a/modules/audio_processing/agc2/rnn_vad/pitch_search_internal.h b/modules/audio_processing/agc2/rnn_vad/pitch_search_internal.h index 2366c5aa07..5609d5a058 100644 --- a/modules/audio_processing/agc2/rnn_vad/pitch_search_internal.h +++ b/modules/audio_processing/agc2/rnn_vad/pitch_search_internal.h @@ -11,10 +11,7 @@ #ifndef MODULES_AUDIO_PROCESSING_AGC2_RNN_VAD_PITCH_SEARCH_INTERNAL_H_ #define MODULES_AUDIO_PROCESSING_AGC2_RNN_VAD_PITCH_SEARCH_INTERNAL_H_ -#include - -#include -#include +#include #include "api/array_view.h" #include "modules/audio_processing/agc2/cpu_features.h" diff --git a/modules/audio_processing/agc2/rnn_vad/pitch_search_internal_unittest.cc b/modules/audio_processing/agc2/rnn_vad/pitch_search_internal_unittest.cc index fa879c1e49..d767c3b974 100644 --- a/modules/audio_processing/agc2/rnn_vad/pitch_search_internal_unittest.cc +++ b/modules/audio_processing/agc2/rnn_vad/pitch_search_internal_unittest.cc @@ -12,8 +12,11 @@ #include #include -#include +#include +#include "api/array_view.h" +#include "modules/audio_processing/agc2/cpu_features.h" +#include "modules/audio_processing/agc2/rnn_vad/common.h" #include "modules/audio_processing/agc2/rnn_vad/test_utils.h" #include "rtc_base/strings/string_builder.h" // TODO(bugs.webrtc.org/8948): Add when the issue is fixed. diff --git a/modules/audio_processing/agc2/rnn_vad/pitch_search_unittest.cc b/modules/audio_processing/agc2/rnn_vad/pitch_search_unittest.cc index 79b44b995c..4cddd566f7 100644 --- a/modules/audio_processing/agc2/rnn_vad/pitch_search_unittest.cc +++ b/modules/audio_processing/agc2/rnn_vad/pitch_search_unittest.cc @@ -14,7 +14,7 @@ #include #include "modules/audio_processing/agc2/cpu_features.h" -#include "modules/audio_processing/agc2/rnn_vad/pitch_search_internal.h" +#include "modules/audio_processing/agc2/rnn_vad/common.h" #include "modules/audio_processing/agc2/rnn_vad/test_utils.h" // TODO(bugs.webrtc.org/8948): Add when the issue is fixed. // #include "test/fpe_observer.h" diff --git a/modules/audio_processing/agc2/rnn_vad/ring_buffer.h b/modules/audio_processing/agc2/rnn_vad/ring_buffer.h index a37df4e1cf..0f12b39805 100644 --- a/modules/audio_processing/agc2/rnn_vad/ring_buffer.h +++ b/modules/audio_processing/agc2/rnn_vad/ring_buffer.h @@ -16,6 +16,7 @@ #include #include "api/array_view.h" +#include "rtc_base/checks.h" namespace webrtc { namespace rnn_vad { diff --git a/modules/audio_processing/agc2/rnn_vad/ring_buffer_unittest.cc b/modules/audio_processing/agc2/rnn_vad/ring_buffer_unittest.cc index e5dded51dc..7300121bdb 100644 --- a/modules/audio_processing/agc2/rnn_vad/ring_buffer_unittest.cc +++ b/modules/audio_processing/agc2/rnn_vad/ring_buffer_unittest.cc @@ -10,6 +10,11 @@ #include "modules/audio_processing/agc2/rnn_vad/ring_buffer.h" +#include +#include +#include + +#include "api/array_view.h" #include "test/gtest.h" namespace webrtc { diff --git a/modules/audio_processing/agc2/rnn_vad/rnn.cc b/modules/audio_processing/agc2/rnn_vad/rnn.cc index 394aea9ad1..3b88554880 100644 --- a/modules/audio_processing/agc2/rnn_vad/rnn.cc +++ b/modules/audio_processing/agc2/rnn_vad/rnn.cc @@ -10,6 +10,11 @@ #include "modules/audio_processing/agc2/rnn_vad/rnn.h" +#include "api/array_view.h" +#include "modules/audio_processing/agc2/cpu_features.h" +#include "modules/audio_processing/agc2/rnn_vad/common.h" +#include "modules/audio_processing/agc2/rnn_vad/rnn_fc.h" +#include "modules/audio_processing/agc2/rnn_vad/rnn_gru.h" #include "rtc_base/checks.h" #include "third_party/rnnoise/src/rnn_vad_weights.h" diff --git a/modules/audio_processing/agc2/rnn_vad/rnn.h b/modules/audio_processing/agc2/rnn_vad/rnn.h index 2f9063a1a8..7b47d23e2d 100644 --- a/modules/audio_processing/agc2/rnn_vad/rnn.h +++ b/modules/audio_processing/agc2/rnn_vad/rnn.h @@ -12,10 +12,7 @@ #define MODULES_AUDIO_PROCESSING_AGC2_RNN_VAD_RNN_H_ #include -#include -#include -#include #include "api/array_view.h" #include "modules/audio_processing/agc2/cpu_features.h" diff --git a/modules/audio_processing/agc2/rnn_vad/rnn_fc.cc b/modules/audio_processing/agc2/rnn_vad/rnn_fc.cc index b5a35b2a3d..3850a256fd 100644 --- a/modules/audio_processing/agc2/rnn_vad/rnn_fc.cc +++ b/modules/audio_processing/agc2/rnn_vad/rnn_fc.cc @@ -11,8 +11,13 @@ #include "modules/audio_processing/agc2/rnn_vad/rnn_fc.h" #include -#include +#include +#include +#include "absl/strings/string_view.h" +#include "api/array_view.h" +#include "api/function_view.h" +#include "modules/audio_processing/agc2/cpu_features.h" #include "rtc_base/checks.h" #include "rtc_base/numerics/safe_conversions.h" #include "third_party/rnnoise/src/rnn_activations.h" diff --git a/modules/audio_processing/agc2/rnn_vad/rnn_fc.h b/modules/audio_processing/agc2/rnn_vad/rnn_fc.h index b802ea78e6..8f3e9b43bb 100644 --- a/modules/audio_processing/agc2/rnn_vad/rnn_fc.h +++ b/modules/audio_processing/agc2/rnn_vad/rnn_fc.h @@ -12,6 +12,7 @@ #define MODULES_AUDIO_PROCESSING_AGC2_RNN_VAD_RNN_FC_H_ #include +#include #include #include "absl/strings/string_view.h" diff --git a/modules/audio_processing/agc2/rnn_vad/rnn_fc_unittest.cc b/modules/audio_processing/agc2/rnn_vad/rnn_fc_unittest.cc index 672090bad3..8f86b27881 100644 --- a/modules/audio_processing/agc2/rnn_vad/rnn_fc_unittest.cc +++ b/modules/audio_processing/agc2/rnn_vad/rnn_fc_unittest.cc @@ -18,7 +18,6 @@ #include "modules/audio_processing/agc2/rnn_vad/test_utils.h" #include "modules/audio_processing/test/performance_timer.h" #include "rtc_base/logging.h" -#include "rtc_base/system/arch.h" #include "test/gtest.h" #include "third_party/rnnoise/src/rnn_vad_weights.h" diff --git a/modules/audio_processing/agc2/rnn_vad/rnn_gru.cc b/modules/audio_processing/agc2/rnn_vad/rnn_gru.cc index e463045a9f..d679b614a8 100644 --- a/modules/audio_processing/agc2/rnn_vad/rnn_gru.cc +++ b/modules/audio_processing/agc2/rnn_vad/rnn_gru.cc @@ -10,6 +10,16 @@ #include "modules/audio_processing/agc2/rnn_vad/rnn_gru.h" +#include +#include +#include +#include +#include + +#include "absl/strings/string_view.h" +#include "api/array_view.h" +#include "modules/audio_processing/agc2/cpu_features.h" +#include "modules/audio_processing/agc2/rnn_vad/vector_math.h" #include "rtc_base/checks.h" #include "rtc_base/numerics/safe_conversions.h" #include "third_party/rnnoise/src/rnn_activations.h" diff --git a/modules/audio_processing/agc2/rnn_vad/rnn_gru.h b/modules/audio_processing/agc2/rnn_vad/rnn_gru.h index ae3063b357..5712ee4fa9 100644 --- a/modules/audio_processing/agc2/rnn_vad/rnn_gru.h +++ b/modules/audio_processing/agc2/rnn_vad/rnn_gru.h @@ -12,6 +12,7 @@ #define MODULES_AUDIO_PROCESSING_AGC2_RNN_VAD_RNN_GRU_H_ #include +#include #include #include "absl/strings/string_view.h" diff --git a/modules/audio_processing/agc2/rnn_vad/rnn_gru_unittest.cc b/modules/audio_processing/agc2/rnn_vad/rnn_gru_unittest.cc index 5afd4383d2..d49a116354 100644 --- a/modules/audio_processing/agc2/rnn_vad/rnn_gru_unittest.cc +++ b/modules/audio_processing/agc2/rnn_vad/rnn_gru_unittest.cc @@ -11,14 +11,18 @@ #include "modules/audio_processing/agc2/rnn_vad/rnn_gru.h" #include +#include +#include #include #include #include "api/array_view.h" +#include "modules/audio_processing/agc2/cpu_features.h" #include "modules/audio_processing/agc2/rnn_vad/test_utils.h" #include "modules/audio_processing/test/performance_timer.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" +#include "rtc_base/numerics/safe_conversions.h" #include "test/gtest.h" #include "third_party/rnnoise/src/rnn_vad_weights.h" diff --git a/modules/audio_processing/agc2/rnn_vad/rnn_unittest.cc b/modules/audio_processing/agc2/rnn_vad/rnn_unittest.cc index 4c5409a14e..a944e2b933 100644 --- a/modules/audio_processing/agc2/rnn_vad/rnn_unittest.cc +++ b/modules/audio_processing/agc2/rnn_vad/rnn_unittest.cc @@ -10,6 +10,8 @@ #include "modules/audio_processing/agc2/rnn_vad/rnn.h" +#include + #include "api/array_view.h" #include "modules/audio_processing/agc2/cpu_features.h" #include "modules/audio_processing/agc2/rnn_vad/common.h" diff --git a/modules/audio_processing/agc2/rnn_vad/rnn_vad_tool.cc b/modules/audio_processing/agc2/rnn_vad/rnn_vad_tool.cc index 6686391a4e..b865749ac6 100644 --- a/modules/audio_processing/agc2/rnn_vad/rnn_vad_tool.cc +++ b/modules/audio_processing/agc2/rnn_vad/rnn_vad_tool.cc @@ -9,6 +9,8 @@ */ #include +#include +#include #include #include @@ -20,6 +22,7 @@ #include "modules/audio_processing/agc2/rnn_vad/common.h" #include "modules/audio_processing/agc2/rnn_vad/features_extraction.h" #include "modules/audio_processing/agc2/rnn_vad/rnn.h" +#include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "rtc_base/numerics/safe_compare.h" diff --git a/modules/audio_processing/agc2/rnn_vad/rnn_vad_unittest.cc b/modules/audio_processing/agc2/rnn_vad/rnn_vad_unittest.cc index b9991eab91..5015957f69 100644 --- a/modules/audio_processing/agc2/rnn_vad/rnn_vad_unittest.cc +++ b/modules/audio_processing/agc2/rnn_vad/rnn_vad_unittest.cc @@ -9,21 +9,19 @@ */ #include +#include #include -#include #include #include "common_audio/resampler/push_sinc_resampler.h" #include "modules/audio_processing/agc2/cpu_features.h" +#include "modules/audio_processing/agc2/rnn_vad/common.h" #include "modules/audio_processing/agc2/rnn_vad/features_extraction.h" #include "modules/audio_processing/agc2/rnn_vad/rnn.h" #include "modules/audio_processing/agc2/rnn_vad/test_utils.h" #include "modules/audio_processing/test/performance_timer.h" -#include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "test/gtest.h" -#include "third_party/rnnoise/src/rnn_activations.h" -#include "third_party/rnnoise/src/rnn_vad_weights.h" namespace webrtc { namespace rnn_vad { diff --git a/modules/audio_processing/agc2/rnn_vad/sequence_buffer_unittest.cc b/modules/audio_processing/agc2/rnn_vad/sequence_buffer_unittest.cc index af005833c1..c43f99dc08 100644 --- a/modules/audio_processing/agc2/rnn_vad/sequence_buffer_unittest.cc +++ b/modules/audio_processing/agc2/rnn_vad/sequence_buffer_unittest.cc @@ -12,6 +12,7 @@ #include #include +#include #include "test/gtest.h" diff --git a/modules/audio_processing/agc2/rnn_vad/spectral_features.cc b/modules/audio_processing/agc2/rnn_vad/spectral_features.cc index 3ad4cae4b9..1712c7d933 100644 --- a/modules/audio_processing/agc2/rnn_vad/spectral_features.cc +++ b/modules/audio_processing/agc2/rnn_vad/spectral_features.cc @@ -11,10 +11,17 @@ #include "modules/audio_processing/agc2/rnn_vad/spectral_features.h" #include +#include #include #include #include +#include "api/array_view.h" +#include "modules/audio_processing/agc2/rnn_vad/common.h" +#include "modules/audio_processing/agc2/rnn_vad/ring_buffer.h" +#include "modules/audio_processing/agc2/rnn_vad/spectral_features_internal.h" +#include "modules/audio_processing/agc2/rnn_vad/symmetric_matrix_buffer.h" +#include "modules/audio_processing/utility/pffft_wrapper.h" #include "rtc_base/checks.h" #include "rtc_base/numerics/safe_compare.h" diff --git a/modules/audio_processing/agc2/rnn_vad/spectral_features.h b/modules/audio_processing/agc2/rnn_vad/spectral_features.h index 714999c46b..6994e451d2 100644 --- a/modules/audio_processing/agc2/rnn_vad/spectral_features.h +++ b/modules/audio_processing/agc2/rnn_vad/spectral_features.h @@ -14,7 +14,6 @@ #include #include #include -#include #include "api/array_view.h" #include "modules/audio_processing/agc2/rnn_vad/common.h" diff --git a/modules/audio_processing/agc2/rnn_vad/spectral_features_internal.cc b/modules/audio_processing/agc2/rnn_vad/spectral_features_internal.cc index c9aa26a707..7cbdcecb91 100644 --- a/modules/audio_processing/agc2/rnn_vad/spectral_features_internal.cc +++ b/modules/audio_processing/agc2/rnn_vad/spectral_features_internal.cc @@ -11,9 +11,12 @@ #include "modules/audio_processing/agc2/rnn_vad/spectral_features_internal.h" #include +#include #include #include +#include "api/array_view.h" +#include "modules/audio_processing/agc2/rnn_vad/common.h" #include "rtc_base/checks.h" #include "rtc_base/numerics/safe_compare.h" diff --git a/modules/audio_processing/agc2/rnn_vad/spectral_features_internal_unittest.cc b/modules/audio_processing/agc2/rnn_vad/spectral_features_internal_unittest.cc index 9c8226ac34..668a4eef2d 100644 --- a/modules/audio_processing/agc2/rnn_vad/spectral_features_internal_unittest.cc +++ b/modules/audio_processing/agc2/rnn_vad/spectral_features_internal_unittest.cc @@ -12,11 +12,11 @@ #include #include -#include #include #include #include "api/array_view.h" +#include "modules/audio_processing/agc2/rnn_vad/common.h" #include "modules/audio_processing/agc2/rnn_vad/test_utils.h" #include "modules/audio_processing/utility/pffft_wrapper.h" #include "rtc_base/numerics/safe_compare.h" diff --git a/modules/audio_processing/agc2/rnn_vad/spectral_features_unittest.cc b/modules/audio_processing/agc2/rnn_vad/spectral_features_unittest.cc index df3f35a55c..3f416bf642 100644 --- a/modules/audio_processing/agc2/rnn_vad/spectral_features_unittest.cc +++ b/modules/audio_processing/agc2/rnn_vad/spectral_features_unittest.cc @@ -11,9 +11,11 @@ #include "modules/audio_processing/agc2/rnn_vad/spectral_features.h" #include +#include +#include "api/array_view.h" +#include "modules/audio_processing/agc2/rnn_vad/common.h" #include "modules/audio_processing/agc2/rnn_vad/test_utils.h" -#include "rtc_base/checks.h" #include "rtc_base/numerics/safe_compare.h" // TODO(bugs.webrtc.org/8948): Add when the issue is fixed. // #include "test/fpe_observer.h" diff --git a/modules/audio_processing/agc2/rnn_vad/symmetric_matrix_buffer.h b/modules/audio_processing/agc2/rnn_vad/symmetric_matrix_buffer.h index a84fa32b52..bd1ace8f5e 100644 --- a/modules/audio_processing/agc2/rnn_vad/symmetric_matrix_buffer.h +++ b/modules/audio_processing/agc2/rnn_vad/symmetric_matrix_buffer.h @@ -14,6 +14,7 @@ #include #include #include +#include #include #include "api/array_view.h" diff --git a/modules/audio_processing/agc2/rnn_vad/symmetric_matrix_buffer_unittest.cc b/modules/audio_processing/agc2/rnn_vad/symmetric_matrix_buffer_unittest.cc index 1509ca5ac1..b041acba58 100644 --- a/modules/audio_processing/agc2/rnn_vad/symmetric_matrix_buffer_unittest.cc +++ b/modules/audio_processing/agc2/rnn_vad/symmetric_matrix_buffer_unittest.cc @@ -10,6 +10,10 @@ #include "modules/audio_processing/agc2/rnn_vad/symmetric_matrix_buffer.h" +#include +#include +#include + #include "modules/audio_processing/agc2/rnn_vad/ring_buffer.h" #include "test/gtest.h" diff --git a/modules/audio_processing/agc2/rnn_vad/test_utils.cc b/modules/audio_processing/agc2/rnn_vad/test_utils.cc index aa78b70ecb..4fb11cec95 100644 --- a/modules/audio_processing/agc2/rnn_vad/test_utils.cc +++ b/modules/audio_processing/agc2/rnn_vad/test_utils.cc @@ -11,13 +11,18 @@ #include "modules/audio_processing/agc2/rnn_vad/test_utils.h" #include +#include #include +#include #include #include #include +#include #include #include "absl/strings/string_view.h" +#include "api/array_view.h" +#include "modules/audio_processing/agc2/rnn_vad/common.h" #include "rtc_base/checks.h" #include "rtc_base/numerics/safe_compare.h" #include "test/gtest.h" @@ -41,7 +46,7 @@ class FloatFileReader : public FileReader { } FloatFileReader(const FloatFileReader&) = delete; FloatFileReader& operator=(const FloatFileReader&) = delete; - ~FloatFileReader() = default; + ~FloatFileReader() override = default; int size() const override { return size_; } bool ReadChunk(ArrayView dst) override { diff --git a/modules/audio_processing/agc2/rnn_vad/test_utils.h b/modules/audio_processing/agc2/rnn_vad/test_utils.h index 60417826e3..4345b04dd1 100644 --- a/modules/audio_processing/agc2/rnn_vad/test_utils.h +++ b/modules/audio_processing/agc2/rnn_vad/test_utils.h @@ -13,14 +13,14 @@ #include #include +#include +#include #include #include #include "absl/strings/string_view.h" #include "api/array_view.h" #include "modules/audio_processing/agc2/rnn_vad/common.h" -#include "rtc_base/checks.h" -#include "rtc_base/numerics/safe_compare.h" namespace webrtc { namespace rnn_vad { diff --git a/modules/audio_processing/agc2/saturation_protector.cc b/modules/audio_processing/agc2/saturation_protector.cc index fa35045662..e5f2cdb5c0 100644 --- a/modules/audio_processing/agc2/saturation_protector.cc +++ b/modules/audio_processing/agc2/saturation_protector.cc @@ -10,12 +10,13 @@ #include "modules/audio_processing/agc2/saturation_protector.h" +#include #include #include "modules/audio_processing/agc2/agc2_common.h" #include "modules/audio_processing/agc2/saturation_protector_buffer.h" #include "modules/audio_processing/logging/apm_data_dumper.h" -#include "rtc_base/checks.h" +#include "rtc_base/numerics/safe_compare.h" #include "rtc_base/numerics/safe_minmax.h" namespace webrtc { @@ -104,7 +105,7 @@ class SaturationProtectorImpl : public SaturationProtector { } SaturationProtectorImpl(const SaturationProtectorImpl&) = delete; SaturationProtectorImpl& operator=(const SaturationProtectorImpl&) = delete; - ~SaturationProtectorImpl() = default; + ~SaturationProtectorImpl() override = default; float HeadroomDb() override { return headroom_db_; } diff --git a/modules/audio_processing/agc2/saturation_protector_buffer.cc b/modules/audio_processing/agc2/saturation_protector_buffer.cc index be0c121fab..7224bb313c 100644 --- a/modules/audio_processing/agc2/saturation_protector_buffer.cc +++ b/modules/audio_processing/agc2/saturation_protector_buffer.cc @@ -10,6 +10,8 @@ #include "modules/audio_processing/agc2/saturation_protector_buffer.h" +#include + #include "rtc_base/checks.h" #include "rtc_base/numerics/safe_compare.h" diff --git a/modules/audio_processing/agc2/saturation_protector_unittest.cc b/modules/audio_processing/agc2/saturation_protector_unittest.cc index 3b104be8cd..65f274ed19 100644 --- a/modules/audio_processing/agc2/saturation_protector_unittest.cc +++ b/modules/audio_processing/agc2/saturation_protector_unittest.cc @@ -10,9 +10,12 @@ #include "modules/audio_processing/agc2/saturation_protector.h" +#include +#include + #include "modules/audio_processing/agc2/agc2_common.h" #include "modules/audio_processing/logging/apm_data_dumper.h" -#include "rtc_base/gunit.h" +#include "test/gtest.h" namespace webrtc { namespace { diff --git a/modules/audio_processing/agc2/speech_level_estimator.cc b/modules/audio_processing/agc2/speech_level_estimator.cc index f9354d1607..6601693a42 100644 --- a/modules/audio_processing/agc2/speech_level_estimator.cc +++ b/modules/audio_processing/agc2/speech_level_estimator.cc @@ -10,10 +10,10 @@ #include "modules/audio_processing/agc2/speech_level_estimator.h" +#include "api/audio/audio_processing.h" #include "modules/audio_processing/agc2/agc2_common.h" #include "modules/audio_processing/logging/apm_data_dumper.h" #include "rtc_base/checks.h" -#include "rtc_base/logging.h" #include "rtc_base/numerics/safe_minmax.h" namespace webrtc { diff --git a/modules/audio_processing/agc2/speech_level_estimator.h b/modules/audio_processing/agc2/speech_level_estimator.h index adbf84c6c5..5f002596ac 100644 --- a/modules/audio_processing/agc2/speech_level_estimator.h +++ b/modules/audio_processing/agc2/speech_level_estimator.h @@ -11,12 +11,10 @@ #ifndef MODULES_AUDIO_PROCESSING_AGC2_SPEECH_LEVEL_ESTIMATOR_H_ #define MODULES_AUDIO_PROCESSING_AGC2_SPEECH_LEVEL_ESTIMATOR_H_ -#include - +#include #include #include "api/audio/audio_processing.h" -#include "modules/audio_processing/agc2/agc2_common.h" namespace webrtc { class ApmDataDumper; diff --git a/modules/audio_processing/agc2/speech_level_estimator_unittest.cc b/modules/audio_processing/agc2/speech_level_estimator_unittest.cc index 939b1146de..4637610c5f 100644 --- a/modules/audio_processing/agc2/speech_level_estimator_unittest.cc +++ b/modules/audio_processing/agc2/speech_level_estimator_unittest.cc @@ -15,7 +15,8 @@ #include "api/audio/audio_processing.h" #include "modules/audio_processing/agc2/agc2_common.h" #include "modules/audio_processing/logging/apm_data_dumper.h" -#include "rtc_base/gunit.h" +#include "rtc_base/checks.h" +#include "test/gtest.h" namespace webrtc { namespace { diff --git a/modules/audio_processing/agc2/speech_probability_buffer.cc b/modules/audio_processing/agc2/speech_probability_buffer.cc index 7746f6c000..5685964eb3 100644 --- a/modules/audio_processing/agc2/speech_probability_buffer.cc +++ b/modules/audio_processing/agc2/speech_probability_buffer.cc @@ -10,8 +10,6 @@ #include "modules/audio_processing/agc2/speech_probability_buffer.h" -#include - #include "rtc_base/checks.h" namespace webrtc { diff --git a/modules/audio_processing/agc2/speech_probability_buffer_unittest.cc b/modules/audio_processing/agc2/speech_probability_buffer_unittest.cc index 89cc209d9d..5ae7beec64 100644 --- a/modules/audio_processing/agc2/speech_probability_buffer_unittest.cc +++ b/modules/audio_processing/agc2/speech_probability_buffer_unittest.cc @@ -10,8 +10,6 @@ #include "modules/audio_processing/agc2/speech_probability_buffer.h" -#include - #include "test/gtest.h" namespace webrtc { diff --git a/modules/audio_processing/agc2/vad_wrapper.cc b/modules/audio_processing/agc2/vad_wrapper.cc index 238c51e422..0d77e7fb25 100644 --- a/modules/audio_processing/agc2/vad_wrapper.cc +++ b/modules/audio_processing/agc2/vad_wrapper.cc @@ -11,10 +11,13 @@ #include "modules/audio_processing/agc2/vad_wrapper.h" #include +#include #include +#include "api/audio/audio_view.h" #include "common_audio/resampler/include/push_resampler.h" #include "modules/audio_processing/agc2/agc2_common.h" +#include "modules/audio_processing/agc2/cpu_features.h" #include "modules/audio_processing/agc2/rnn_vad/common.h" #include "modules/audio_processing/agc2/rnn_vad/features_extraction.h" #include "modules/audio_processing/agc2/rnn_vad/rnn.h" @@ -31,7 +34,7 @@ class MonoVadImpl : public VoiceActivityDetectorWrapper::MonoVad { : features_extractor_(cpu_features), rnn_vad_(cpu_features) {} MonoVadImpl(const MonoVadImpl&) = delete; MonoVadImpl& operator=(const MonoVadImpl&) = delete; - ~MonoVadImpl() = default; + ~MonoVadImpl() override = default; int SampleRateHz() const override { return rnn_vad::kSampleRate24kHz; } void Reset() override { rnn_vad_.Reset(); } diff --git a/modules/audio_processing/agc2/vad_wrapper_unittest.cc b/modules/audio_processing/agc2/vad_wrapper_unittest.cc index 4cac82d2db..7d51591456 100644 --- a/modules/audio_processing/agc2/vad_wrapper_unittest.cc +++ b/modules/audio_processing/agc2/vad_wrapper_unittest.cc @@ -16,12 +16,13 @@ #include #include +#include "api/array_view.h" #include "api/audio/audio_view.h" #include "modules/audio_processing/agc2/agc2_common.h" #include "rtc_base/checks.h" -#include "rtc_base/gunit.h" #include "rtc_base/numerics/safe_compare.h" #include "test/gmock.h" +#include "test/gtest.h" namespace webrtc { namespace { diff --git a/modules/audio_processing/agc2/vector_float_frame.cc b/modules/audio_processing/agc2/vector_float_frame.cc index 85dd7feb21..133ba8a5d9 100644 --- a/modules/audio_processing/agc2/vector_float_frame.cc +++ b/modules/audio_processing/agc2/vector_float_frame.cc @@ -10,6 +10,8 @@ #include "modules/audio_processing/agc2/vector_float_frame.h" +#include "modules/audio_processing/include/audio_frame_view.h" + namespace webrtc { VectorFloatFrame::VectorFloatFrame(int num_channels, diff --git a/modules/audio_processing/audio_buffer.cc b/modules/audio_processing/audio_buffer.cc index a1b55fe10a..0c9bbc9fea 100644 --- a/modules/audio_processing/audio_buffer.cc +++ b/modules/audio_processing/audio_buffer.cc @@ -10,11 +10,15 @@ #include "modules/audio_processing/audio_buffer.h" -#include - +#include +#include #include +#include +#include +#include "api/audio/audio_processing.h" #include "common_audio/channel_buffer.h" +#include "common_audio/include/audio_util.h" #include "common_audio/resampler/push_sinc_resampler.h" #include "modules/audio_processing/splitting_filter.h" #include "rtc_base/checks.h" diff --git a/modules/audio_processing/audio_buffer.h b/modules/audio_processing/audio_buffer.h index a876aa8741..6f11a7039c 100644 --- a/modules/audio_processing/audio_buffer.h +++ b/modules/audio_processing/audio_buffer.h @@ -36,7 +36,7 @@ class AudioBuffer { public: static const int kSplitBandSize = 160; // TODO(tommi): Remove this (`AudioBuffer::kMaxSampleRate`) constant. - static const int kMaxSampleRate = webrtc::kMaxSampleRateHz; + static const int kMaxSampleRate = kMaxSampleRateHz; AudioBuffer(size_t input_rate, size_t input_num_channels, size_t buffer_rate, diff --git a/modules/audio_processing/audio_buffer_unittest.cc b/modules/audio_processing/audio_buffer_unittest.cc index ef3479e4f5..19711c66a4 100644 --- a/modules/audio_processing/audio_buffer_unittest.cc +++ b/modules/audio_processing/audio_buffer_unittest.cc @@ -11,8 +11,10 @@ #include "modules/audio_processing/audio_buffer.h" #include +#include #include "api/audio/audio_view.h" +#include "rtc_base/checks.h" #include "test/gtest.h" #include "test/testsupport/rtc_expect_death.h" diff --git a/modules/audio_processing/audio_frame_view_unittest.cc b/modules/audio_processing/audio_frame_view_unittest.cc index 30f1d8e0c3..e8aee63c26 100644 --- a/modules/audio_processing/audio_frame_view_unittest.cc +++ b/modules/audio_processing/audio_frame_view_unittest.cc @@ -11,10 +11,12 @@ #include "modules/audio_processing/include/audio_frame_view.h" #include +#include +#include "api/audio/audio_processing.h" +#include "api/audio/audio_view.h" #include "common_audio/channel_buffer.h" #include "modules/audio_processing/audio_buffer.h" -#include "rtc_base/arraysize.h" #include "test/gtest.h" namespace webrtc { diff --git a/modules/audio_processing/audio_processing_impl.cc b/modules/audio_processing/audio_processing_impl.cc index 9a6f785657..b4b6bbab4b 100644 --- a/modules/audio_processing/audio_processing_impl.cc +++ b/modules/audio_processing/audio_processing_impl.cc @@ -132,13 +132,13 @@ bool MinimizeProcessingForUnusedOutput(const FieldTrialsView& field_trials) { // Maximum lengths that frame of samples being passed from the render side to // the capture side can have (does not apply to AEC3). -static const size_t kMaxAllowedValuesOfSamplesPerBand = 160; -static const size_t kMaxAllowedValuesOfSamplesPerFrame = 480; +const size_t kMaxAllowedValuesOfSamplesPerBand = 160; +const size_t kMaxAllowedValuesOfSamplesPerFrame = 480; // Maximum number of frames to buffer in the render queue. // TODO(peah): Decrease this once we properly handle hugely unbalanced // reverse and forward call numbers. -static const size_t kMaxNumFramesToBuffer = 100; +const size_t kMaxNumFramesToBuffer = 100; void PackRenderAudioBufferForEchoDetector(const AudioBuffer& audio, std::vector& packed_buffer) { diff --git a/modules/audio_processing/audio_processing_impl.h b/modules/audio_processing/audio_processing_impl.h index ffaca0151e..91951d7a70 100644 --- a/modules/audio_processing/audio_processing_impl.h +++ b/modules/audio_processing/audio_processing_impl.h @@ -11,11 +11,10 @@ #ifndef MODULES_AUDIO_PROCESSING_AUDIO_PROCESSING_IMPL_H_ #define MODULES_AUDIO_PROCESSING_AUDIO_PROCESSING_IMPL_H_ -#include - #include #include #include +#include #include #include #include diff --git a/modules/audio_processing/audio_processing_impl_locking_unittest.cc b/modules/audio_processing/audio_processing_impl_locking_unittest.cc index d9d75dccd6..cf1cae4864 100644 --- a/modules/audio_processing/audio_processing_impl_locking_unittest.cc +++ b/modules/audio_processing/audio_processing_impl_locking_unittest.cc @@ -9,19 +9,22 @@ */ #include -#include +#include +#include #include #include "api/array_view.h" +#include "api/audio/audio_processing.h" #include "api/audio/builtin_audio_processing_builder.h" #include "api/environment/environment_factory.h" -#include "modules/audio_processing/audio_processing_impl.h" -#include "modules/audio_processing/test/test_utils.h" +#include "api/scoped_refptr.h" +#include "api/units/time_delta.h" #include "rtc_base/event.h" #include "rtc_base/platform_thread.h" #include "rtc_base/random.h" #include "rtc_base/synchronization/mutex.h" #include "rtc_base/thread.h" +#include "rtc_base/thread_annotations.h" #include "test/gtest.h" namespace webrtc { diff --git a/modules/audio_processing/audio_processing_impl_unittest.cc b/modules/audio_processing/audio_processing_impl_unittest.cc index e761f7609b..a75d485dee 100644 --- a/modules/audio_processing/audio_processing_impl_unittest.cc +++ b/modules/audio_processing/audio_processing_impl_unittest.cc @@ -12,23 +12,27 @@ #include #include +#include +#include #include -#include +#include #include +#include +#include +#include "api/array_view.h" #include "api/audio/audio_processing.h" #include "api/audio/builtin_audio_processing_builder.h" +#include "api/audio/echo_control.h" #include "api/environment/environment.h" #include "api/environment/environment_factory.h" #include "api/make_ref_counted.h" +#include "api/ref_count.h" #include "api/scoped_refptr.h" #include "modules/audio_processing/test/echo_canceller_test_tools.h" #include "modules/audio_processing/test/echo_control_mock.h" #include "modules/audio_processing/test/test_utils.h" -#include "rtc_base/checks.h" #include "rtc_base/random.h" -#include "rtc_base/strings/string_builder.h" -#include "test/field_trial.h" #include "test/gmock.h" #include "test/gtest.h" @@ -117,7 +121,7 @@ class TestEchoDetector : public EchoDetector { class TestRenderPreProcessor : public CustomProcessing { public: TestRenderPreProcessor() = default; - ~TestRenderPreProcessor() = default; + ~TestRenderPreProcessor() override = default; void Initialize(int /* sample_rate_hz */, int /* num_channels */) override {} void Process(AudioBuffer* audio) override { for (size_t k = 0; k < audio->num_channels(); ++k) { diff --git a/modules/audio_processing/audio_processing_performance_unittest.cc b/modules/audio_processing/audio_processing_performance_unittest.cc index 820d403eee..cf0b7949ef 100644 --- a/modules/audio_processing/audio_processing_performance_unittest.cc +++ b/modules/audio_processing/audio_processing_performance_unittest.cc @@ -7,24 +7,26 @@ * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ -#include -#include #include +#include +#include +#include #include +#include #include #include "absl/strings/string_view.h" -#include "api/array_view.h" +#include "api/audio/audio_processing.h" #include "api/audio/builtin_audio_processing_builder.h" #include "api/environment/environment_factory.h" #include "api/numerics/samples_stats_counter.h" +#include "api/scoped_refptr.h" #include "api/test/metrics/global_metrics_logger_and_exporter.h" #include "api/test/metrics/metric.h" -#include "modules/audio_processing/audio_processing_impl.h" -#include "modules/audio_processing/test/test_utils.h" +#include "api/units/time_delta.h" +#include "rtc_base/checks.h" #include "rtc_base/event.h" -#include "rtc_base/numerics/safe_conversions.h" #include "rtc_base/platform_thread.h" #include "rtc_base/random.h" #include "system_wrappers/include/clock.h" diff --git a/modules/audio_processing/audio_processing_unittest.cc b/modules/audio_processing/audio_processing_unittest.cc index 1f4a9eda1a..6882031850 100644 --- a/modules/audio_processing/audio_processing_unittest.cc +++ b/modules/audio_processing/audio_processing_unittest.cc @@ -9,13 +9,13 @@ */ #include "api/audio/audio_processing.h" -#include #include #include #include #include #include +#include #include #include #include @@ -49,8 +49,8 @@ #include "modules/audio_processing/include/mock_audio_processing.h" #include "modules/audio_processing/test/protobuf_utils.h" #include "modules/audio_processing/test/test_utils.h" -#include "rtc_base/arraysize.h" #include "rtc_base/checks.h" +#include "rtc_base/cpu_info.h" #include "rtc_base/fake_clock.h" #include "rtc_base/numerics/safe_conversions.h" #include "rtc_base/numerics/safe_minmax.h" @@ -59,7 +59,6 @@ #include "rtc_base/swap_queue.h" #include "rtc_base/system/file_wrapper.h" #include "rtc_base/task_queue_for_test.h" -#include "system_wrappers/include/cpu_features_wrapper.h" #include "test/gmock.h" #include "test/gtest.h" #include "test/testsupport/file_utils.h" @@ -295,7 +294,7 @@ std::string GetReferenceFilename() { #if defined(WEBRTC_AUDIOPROC_FIXED_PROFILE) return test::ResourcePath("audio_processing/output_data_fixed", "pb"); #elif defined(WEBRTC_AUDIOPROC_FLOAT_PROFILE) - if (GetCPUInfo(kAVX2) != 0) { + if (cpu_info::Supports(cpu_info::ISA::kAVX2)) { return test::ResourcePath("audio_processing/output_data_float_avx2", "pb"); } return test::ResourcePath("audio_processing/output_data_float", "pb"); @@ -371,8 +370,8 @@ bool ExpectMessageEq(ArrayView actual, class ApmTest : public ::testing::Test { protected: ApmTest(); - virtual void SetUp(); - virtual void TearDown(); + void SetUp() override; + void TearDown() override; static void SetUpTestSuite() {} @@ -1329,9 +1328,8 @@ TEST_F(ApmTest, NoProcessingWhenAllComponentsDisabledFloat) { TEST_F(ApmTest, IdenticalInputChannelsResultInIdenticalOutputChannels) { EnableAllComponents(); - for (size_t i = 0; i < arraysize(kProcessSampleRates); i++) { - Init(kProcessSampleRates[i], kProcessSampleRates[i], kProcessSampleRates[i], - 2, 2, 2, false); + for (int sample_rate_hz : kProcessSampleRates) { + Init(sample_rate_hz, sample_rate_hz, sample_rate_hz, 2, 2, 2, false); int analog_level = 127; ASSERT_EQ(0, feof(far_file_)); ASSERT_EQ(0, feof(near_file_)); @@ -1691,13 +1689,13 @@ TEST_F(ApmTest, Process) { } else { const int kChannels[] = {1, 2}; // Write the desired tests to the protobuf reference file. - for (size_t i = 0; i < arraysize(kChannels); i++) { - for (size_t j = 0; j < arraysize(kChannels); j++) { + for (int num_reverse_channels : kChannels) { + for (int num_channels : kChannels) { for (int sample_rate_hz : AudioProcessing::kNativeSampleRatesHz) { audioproc::Test* test = ref_data.add_test(); - test->set_num_reverse_channels(kChannels[i]); - test->set_num_input_channels(kChannels[j]); - test->set_num_output_channels(kChannels[j]); + test->set_num_reverse_channels(num_reverse_channels); + test->set_num_input_channels(num_channels); + test->set_num_output_channels(num_channels); test->set_sample_rate(sample_rate_hz); test->set_use_aec_extended_filter(false); } @@ -1922,25 +1920,24 @@ class AudioProcessingTest expected_snr_(std::get<4>(GetParam())), expected_reverse_snr_(std::get<5>(GetParam())) {} - virtual ~AudioProcessingTest() {} + ~AudioProcessingTest() override {} static void SetUpTestSuite() { // Create all needed output reference files. const size_t kNumChannels[] = {1, 2}; - for (size_t i = 0; i < arraysize(kProcessSampleRates); ++i) { - for (size_t j = 0; j < arraysize(kNumChannels); ++j) { - for (size_t k = 0; k < arraysize(kNumChannels); ++k) { + for (int sample_rate_hz : kProcessSampleRates) { + for (int num_channels : kNumChannels) { + for (int num_reverse_channels : kNumChannels) { // The reference files always have matching input and output channels. - ProcessFormat(kProcessSampleRates[i], kProcessSampleRates[i], - kProcessSampleRates[i], kProcessSampleRates[i], - kNumChannels[j], kNumChannels[j], kNumChannels[k], - kNumChannels[k], "ref"); + ProcessFormat(sample_rate_hz, sample_rate_hz, sample_rate_hz, + sample_rate_hz, num_channels, num_channels, + num_reverse_channels, num_reverse_channels, "ref"); } } } } - void TearDown() { + void TearDown() override { // Remove "out" files after each test. ClearTempOutFiles(); } @@ -2083,10 +2080,11 @@ TEST_P(AudioProcessingTest, Formats) { {2, 1, 2, 1}, {2, 2, 1, 1}, {2, 2, 2, 2}, }; - for (size_t i = 0; i < arraysize(cf); ++i) { + for (auto [num_input, num_output, num_reverse_input, num_reverse_output] : + cf) { ProcessFormat(input_rate_, output_rate_, reverse_input_rate_, - reverse_output_rate_, cf[i].num_input, cf[i].num_output, - cf[i].num_reverse_input, cf[i].num_reverse_output, "out"); + reverse_output_rate_, num_input, num_output, + num_reverse_input, num_reverse_output, "out"); // Verify output for both directions. std::vector stream_directions; @@ -2095,8 +2093,7 @@ TEST_P(AudioProcessingTest, Formats) { for (StreamDirection file_direction : stream_directions) { const int in_rate = file_direction ? reverse_input_rate_ : input_rate_; const int out_rate = file_direction ? reverse_output_rate_ : output_rate_; - const int out_num = - file_direction ? cf[i].num_reverse_output : cf[i].num_output; + const int out_num = file_direction ? num_reverse_output : num_output; const double expected_snr = file_direction ? expected_reverse_snr_ : expected_snr_; @@ -2112,17 +2109,15 @@ TEST_P(AudioProcessingTest, Formats) { FILE* out_file = fopen( OutputFilePath("out", input_rate_, output_rate_, reverse_input_rate_, - reverse_output_rate_, cf[i].num_input, - cf[i].num_output, cf[i].num_reverse_input, - cf[i].num_reverse_output, file_direction) + reverse_output_rate_, num_input, num_output, + num_reverse_input, num_reverse_output, file_direction) .c_str(), "rb"); // The reference files always have matching input and output channels. FILE* ref_file = fopen(OutputFilePath("ref", ref_rate, ref_rate, ref_rate, ref_rate, - cf[i].num_output, cf[i].num_output, - cf[i].num_reverse_output, - cf[i].num_reverse_output, file_direction) + num_output, num_output, num_reverse_output, + num_reverse_output, file_direction) .c_str(), "rb"); ASSERT_TRUE(out_file != nullptr); @@ -2192,9 +2187,9 @@ TEST_P(AudioProcessingTest, Formats) { std::cout << "(" << input_rate_ << ", " << output_rate_ << ", " << reverse_input_rate_ << ", " << reverse_output_rate_ << ", " - << cf[i].num_input << ", " << cf[i].num_output << ", " - << cf[i].num_reverse_input << ", " << cf[i].num_reverse_output - << ", " << file_direction << "): "; + << num_input << ", " << num_output << ", " << num_reverse_input + << ", " << num_reverse_output << ", " << file_direction + << "): "; if (sq_error > 0) { double snr = 10 * log10(variance / sq_error); EXPECT_GE(snr, expected_snr); diff --git a/modules/audio_processing/capture_levels_adjuster/BUILD.gn b/modules/audio_processing/capture_levels_adjuster/BUILD.gn index e7ff8482f6..20b2e395a8 100644 --- a/modules/audio_processing/capture_levels_adjuster/BUILD.gn +++ b/modules/audio_processing/capture_levels_adjuster/BUILD.gn @@ -37,6 +37,7 @@ rtc_library("capture_levels_adjuster_unittests") { ] deps = [ ":capture_levels_adjuster", + "..:audio_buffer", "..:audioproc_test_utils", "../../../rtc_base:gunit_helpers", "../../../rtc_base:stringutils", diff --git a/modules/audio_processing/capture_levels_adjuster/audio_samples_scaler.cc b/modules/audio_processing/capture_levels_adjuster/audio_samples_scaler.cc index e9d765320e..a2430ab4f1 100644 --- a/modules/audio_processing/capture_levels_adjuster/audio_samples_scaler.cc +++ b/modules/audio_processing/capture_levels_adjuster/audio_samples_scaler.cc @@ -10,6 +10,7 @@ #include "modules/audio_processing/capture_levels_adjuster/audio_samples_scaler.h" #include +#include #include "api/array_view.h" #include "modules/audio_processing/audio_buffer.h" diff --git a/modules/audio_processing/capture_levels_adjuster/audio_samples_scaler_unittest.cc b/modules/audio_processing/capture_levels_adjuster/audio_samples_scaler_unittest.cc index 6e5fc2cbe3..98f8deee00 100644 --- a/modules/audio_processing/capture_levels_adjuster/audio_samples_scaler_unittest.cc +++ b/modules/audio_processing/capture_levels_adjuster/audio_samples_scaler_unittest.cc @@ -9,10 +9,11 @@ */ #include "modules/audio_processing/capture_levels_adjuster/audio_samples_scaler.h" +#include #include +#include "modules/audio_processing/audio_buffer.h" #include "modules/audio_processing/test/audio_buffer_tools.h" -#include "rtc_base/strings/string_builder.h" #include "test/gtest.h" namespace webrtc { diff --git a/modules/audio_processing/capture_levels_adjuster/capture_levels_adjuster_unittest.cc b/modules/audio_processing/capture_levels_adjuster/capture_levels_adjuster_unittest.cc index 1183441a14..1cb04090e3 100644 --- a/modules/audio_processing/capture_levels_adjuster/capture_levels_adjuster_unittest.cc +++ b/modules/audio_processing/capture_levels_adjuster/capture_levels_adjuster_unittest.cc @@ -10,10 +10,11 @@ #include "modules/audio_processing/capture_levels_adjuster/capture_levels_adjuster.h" #include +#include #include +#include "modules/audio_processing/audio_buffer.h" #include "modules/audio_processing/test/audio_buffer_tools.h" -#include "rtc_base/strings/string_builder.h" #include "test/gtest.h" namespace webrtc { diff --git a/modules/audio_processing/echo_control_mobile_bit_exact_unittest.cc b/modules/audio_processing/echo_control_mobile_bit_exact_unittest.cc index 636ba6026e..4491054ad9 100644 --- a/modules/audio_processing/echo_control_mobile_bit_exact_unittest.cc +++ b/modules/audio_processing/echo_control_mobile_bit_exact_unittest.cc @@ -7,13 +7,18 @@ * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ +#include +#include #include #include "api/array_view.h" +#include "api/audio/audio_processing.h" +#include "modules/audio_coding/neteq/tools/input_audio_file.h" #include "modules/audio_processing/audio_buffer.h" #include "modules/audio_processing/echo_control_mobile_impl.h" #include "modules/audio_processing/test/audio_buffer_tools.h" #include "modules/audio_processing/test/bitexactness_tools.h" +#include "rtc_base/checks.h" #include "test/gtest.h" namespace webrtc { diff --git a/modules/audio_processing/echo_control_mobile_impl.cc b/modules/audio_processing/echo_control_mobile_impl.cc index e1e0d3fcfc..edfb57b742 100644 --- a/modules/audio_processing/echo_control_mobile_impl.cc +++ b/modules/audio_processing/echo_control_mobile_impl.cc @@ -10,11 +10,14 @@ #include "modules/audio_processing/echo_control_mobile_impl.h" -#include - +#include #include +#include +#include +#include "api/array_view.h" #include "api/audio/audio_processing.h" +#include "common_audio/include/audio_util.h" #include "modules/audio_processing/aecm/echo_control_mobile.h" #include "modules/audio_processing/audio_buffer.h" #include "rtc_base/checks.h" diff --git a/modules/audio_processing/echo_control_mobile_impl.h b/modules/audio_processing/echo_control_mobile_impl.h index 0d605fe42b..696ac6ee2f 100644 --- a/modules/audio_processing/echo_control_mobile_impl.h +++ b/modules/audio_processing/echo_control_mobile_impl.h @@ -11,9 +11,9 @@ #ifndef MODULES_AUDIO_PROCESSING_ECHO_CONTROL_MOBILE_IMPL_H_ #define MODULES_AUDIO_PROCESSING_ECHO_CONTROL_MOBILE_IMPL_H_ -#include -#include - +#include +#include +#include #include #include diff --git a/modules/audio_processing/echo_control_mobile_unittest.cc b/modules/audio_processing/echo_control_mobile_unittest.cc index dc11a812d3..d0063be556 100644 --- a/modules/audio_processing/echo_control_mobile_unittest.cc +++ b/modules/audio_processing/echo_control_mobile_unittest.cc @@ -9,7 +9,6 @@ */ #include -#include #include "api/audio/audio_processing.h" #include "modules/audio_processing/echo_control_mobile_impl.h" diff --git a/modules/audio_processing/echo_detector/circular_buffer.cc b/modules/audio_processing/echo_detector/circular_buffer.cc index c24f920c8e..30aadfb36d 100644 --- a/modules/audio_processing/echo_detector/circular_buffer.cc +++ b/modules/audio_processing/echo_detector/circular_buffer.cc @@ -11,6 +11,8 @@ #include "modules/audio_processing/echo_detector/circular_buffer.h" #include +#include +#include #include "rtc_base/checks.h" diff --git a/modules/audio_processing/echo_detector/circular_buffer_unittest.cc b/modules/audio_processing/echo_detector/circular_buffer_unittest.cc index 95bea5e2e2..13c6ec98f7 100644 --- a/modules/audio_processing/echo_detector/circular_buffer_unittest.cc +++ b/modules/audio_processing/echo_detector/circular_buffer_unittest.cc @@ -10,6 +10,8 @@ #include "modules/audio_processing/echo_detector/circular_buffer.h" +#include + #include "test/gtest.h" namespace webrtc { diff --git a/modules/audio_processing/echo_detector/mean_variance_estimator_unittest.cc b/modules/audio_processing/echo_detector/mean_variance_estimator_unittest.cc index 8327d23e8a..aec277befc 100644 --- a/modules/audio_processing/echo_detector/mean_variance_estimator_unittest.cc +++ b/modules/audio_processing/echo_detector/mean_variance_estimator_unittest.cc @@ -11,6 +11,8 @@ #include "modules/audio_processing/echo_detector/mean_variance_estimator.h" +#include + #include "test/gtest.h" namespace webrtc { diff --git a/modules/audio_processing/echo_detector/moving_max.cc b/modules/audio_processing/echo_detector/moving_max.cc index 3054e98bd3..a638e07cf3 100644 --- a/modules/audio_processing/echo_detector/moving_max.cc +++ b/modules/audio_processing/echo_detector/moving_max.cc @@ -10,6 +10,8 @@ #include "modules/audio_processing/echo_detector/moving_max.h" +#include + #include "rtc_base/checks.h" namespace webrtc { diff --git a/modules/audio_processing/echo_detector/normalized_covariance_estimator_unittest.cc b/modules/audio_processing/echo_detector/normalized_covariance_estimator_unittest.cc index 89fb9383f6..ef88bf2e7a 100644 --- a/modules/audio_processing/echo_detector/normalized_covariance_estimator_unittest.cc +++ b/modules/audio_processing/echo_detector/normalized_covariance_estimator_unittest.cc @@ -11,6 +11,8 @@ #include "modules/audio_processing/echo_detector/normalized_covariance_estimator.h" +#include + #include "test/gtest.h" namespace webrtc { diff --git a/modules/audio_processing/gain_control_impl.cc b/modules/audio_processing/gain_control_impl.cc index f20548e019..5bccb2ec0b 100644 --- a/modules/audio_processing/gain_control_impl.cc +++ b/modules/audio_processing/gain_control_impl.cc @@ -10,10 +10,17 @@ #include "modules/audio_processing/gain_control_impl.h" +#include +#include +#include #include #include +#include +#include "api/array_view.h" #include "api/audio/audio_processing.h" +#include "common_audio/include/audio_util.h" +#include "modules/audio_processing/agc/gain_control.h" #include "modules/audio_processing/agc/legacy/gain_control.h" #include "modules/audio_processing/audio_buffer.h" #include "modules/audio_processing/logging/apm_data_dumper.h" diff --git a/modules/audio_processing/gain_control_unittest.cc b/modules/audio_processing/gain_control_unittest.cc index d3549ab0f0..050d2204aa 100644 --- a/modules/audio_processing/gain_control_unittest.cc +++ b/modules/audio_processing/gain_control_unittest.cc @@ -7,13 +7,20 @@ * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ +#include "modules/audio_processing/agc/gain_control.h" + +#include +#include #include #include "api/array_view.h" +#include "api/audio/audio_processing.h" +#include "modules/audio_coding/neteq/tools/input_audio_file.h" #include "modules/audio_processing/audio_buffer.h" #include "modules/audio_processing/gain_control_impl.h" #include "modules/audio_processing/test/audio_buffer_tools.h" #include "modules/audio_processing/test/bitexactness_tools.h" +#include "rtc_base/checks.h" #include "test/gtest.h" namespace webrtc { diff --git a/modules/audio_processing/gain_controller2.h b/modules/audio_processing/gain_controller2.h index 5594e80b0d..3fbbc07475 100644 --- a/modules/audio_processing/gain_controller2.h +++ b/modules/audio_processing/gain_controller2.h @@ -13,7 +13,7 @@ #include #include -#include +#include #include "api/audio/audio_processing.h" #include "api/environment/environment.h" diff --git a/modules/audio_processing/gain_controller2_unittest.cc b/modules/audio_processing/gain_controller2_unittest.cc index 1d415a5de4..8897f1dff3 100644 --- a/modules/audio_processing/gain_controller2_unittest.cc +++ b/modules/audio_processing/gain_controller2_unittest.cc @@ -12,13 +12,20 @@ #include #include +#include #include -#include +#include #include +#include +#include "api/audio/audio_processing.h" #include "api/environment/environment.h" #include "api/environment/environment_factory.h" +#include "modules/audio_coding/neteq/tools/input_audio_file.h" #include "modules/audio_processing/agc2/agc2_testing_common.h" +#include "modules/audio_processing/agc2/cpu_features.h" +#include "modules/audio_processing/agc2/input_volume_controller.h" +#include "modules/audio_processing/agc2/vad_wrapper.h" #include "modules/audio_processing/audio_buffer.h" #include "modules/audio_processing/test/audio_buffer_tools.h" #include "modules/audio_processing/test/bitexactness_tools.h" diff --git a/modules/audio_processing/high_pass_filter.h b/modules/audio_processing/high_pass_filter.h index 7e7c370cd1..babe5d3d7f 100644 --- a/modules/audio_processing/high_pass_filter.h +++ b/modules/audio_processing/high_pass_filter.h @@ -11,10 +11,10 @@ #ifndef MODULES_AUDIO_PROCESSING_HIGH_PASS_FILTER_H_ #define MODULES_AUDIO_PROCESSING_HIGH_PASS_FILTER_H_ +#include #include #include -#include "api/array_view.h" #include "modules/audio_processing/utility/cascaded_biquad_filter.h" namespace webrtc { diff --git a/modules/audio_processing/high_pass_filter_unittest.cc b/modules/audio_processing/high_pass_filter_unittest.cc index 4fa7e7534e..b05f053906 100644 --- a/modules/audio_processing/high_pass_filter_unittest.cc +++ b/modules/audio_processing/high_pass_filter_unittest.cc @@ -9,9 +9,12 @@ */ #include "modules/audio_processing/high_pass_filter.h" +#include +#include #include #include "api/array_view.h" +#include "api/audio/audio_processing.h" #include "modules/audio_processing/audio_buffer.h" #include "modules/audio_processing/test/audio_buffer_tools.h" #include "modules/audio_processing/test/bitexactness_tools.h" diff --git a/modules/audio_processing/include/audio_frame_proxies.cc b/modules/audio_processing/include/audio_frame_proxies.cc index e37645ef20..97d81e6b85 100644 --- a/modules/audio_processing/include/audio_frame_proxies.cc +++ b/modules/audio_processing/include/audio_frame_proxies.cc @@ -12,6 +12,8 @@ #include "api/audio/audio_frame.h" #include "api/audio/audio_processing.h" +#include "api/audio/audio_processing_statistics.h" +#include "rtc_base/checks.h" namespace webrtc { diff --git a/modules/audio_processing/include/mock_audio_processing.h b/modules/audio_processing/include/mock_audio_processing.h index 805aa411e8..03b29d810e 100644 --- a/modules/audio_processing/include/mock_audio_processing.h +++ b/modules/audio_processing/include/mock_audio_processing.h @@ -11,12 +11,19 @@ #ifndef MODULES_AUDIO_PROCESSING_INCLUDE_MOCK_AUDIO_PROCESSING_H_ #define MODULES_AUDIO_PROCESSING_INCLUDE_MOCK_AUDIO_PROCESSING_H_ +#include +#include +#include +#include #include +#include #include "absl/base/nullability.h" #include "absl/strings/string_view.h" +#include "api/array_view.h" #include "api/audio/audio_processing.h" #include "api/audio/audio_processing_statistics.h" +#include "api/audio/echo_control.h" #include "api/environment/environment.h" #include "api/scoped_refptr.h" #include "api/task_queue/task_queue_base.h" diff --git a/modules/audio_processing/logging/apm_data_dumper.cc b/modules/audio_processing/logging/apm_data_dumper.cc index ec2cc7f958..b26d90fbc8 100644 --- a/modules/audio_processing/logging/apm_data_dumper.cc +++ b/modules/audio_processing/logging/apm_data_dumper.cc @@ -10,8 +10,6 @@ #include "modules/audio_processing/logging/apm_data_dumper.h" -#include "absl/strings/string_view.h" -#include "rtc_base/strings/string_builder.h" // Check to verify that the define is properly set. #if !defined(WEBRTC_APM_DEBUG_DUMP) || \ @@ -36,7 +34,7 @@ std::string FormFileName(absl::string_view output_dir, int reinit_index, absl::string_view suffix) { char buf[1024]; - webrtc::SimpleStringBuilder ss(buf); + SimpleStringBuilder ss(buf); if (!output_dir.empty()) { ss << output_dir; if (output_dir.back() != kPathDelimiter) { diff --git a/modules/audio_processing/logging/apm_data_dumper.h b/modules/audio_processing/logging/apm_data_dumper.h index a8178bf151..24e5ad913a 100644 --- a/modules/audio_processing/logging/apm_data_dumper.h +++ b/modules/audio_processing/logging/apm_data_dumper.h @@ -11,17 +11,14 @@ #ifndef MODULES_AUDIO_PROCESSING_LOGGING_APM_DATA_DUMPER_H_ #define MODULES_AUDIO_PROCESSING_LOGGING_APM_DATA_DUMPER_H_ -#include -#include - +#include +#include #if WEBRTC_APM_DEBUG_DUMP == 1 #include #include #include #endif -#include - #include "absl/strings/string_view.h" #include "api/array_view.h" #if WEBRTC_APM_DEBUG_DUMP == 1 @@ -93,7 +90,7 @@ class ApmDataDumper { [[maybe_unused]] absl::string_view output_dir) { #if WEBRTC_APM_DEBUG_DUMP == 1 RTC_CHECK_LT(output_dir.size(), kOutputDirMaxLength); - webrtc::strcpyn(output_dir_, kOutputDirMaxLength, output_dir); + strcpyn(output_dir_, kOutputDirMaxLength, output_dir); #endif } diff --git a/modules/audio_processing/ns/fast_math.cc b/modules/audio_processing/ns/fast_math.cc index 7b8fe1f55b..7d52252201 100644 --- a/modules/audio_processing/ns/fast_math.cc +++ b/modules/audio_processing/ns/fast_math.cc @@ -10,11 +10,12 @@ #include "modules/audio_processing/ns/fast_math.h" -#include -#include - +#include +#include +#include #include +#include "api/array_view.h" #include "rtc_base/checks.h" namespace webrtc { diff --git a/modules/audio_processing/ns/histograms.cc b/modules/audio_processing/ns/histograms.cc index 1d4f4590d2..1161ce8b79 100644 --- a/modules/audio_processing/ns/histograms.cc +++ b/modules/audio_processing/ns/histograms.cc @@ -10,6 +10,9 @@ #include "modules/audio_processing/ns/histograms.h" +#include "modules/audio_processing/ns/ns_common.h" +#include "modules/audio_processing/ns/signal_model.h" + namespace webrtc { Histograms::Histograms() { diff --git a/modules/audio_processing/ns/histograms.h b/modules/audio_processing/ns/histograms.h index 54efbe097b..3f4445486b 100644 --- a/modules/audio_processing/ns/histograms.h +++ b/modules/audio_processing/ns/histograms.h @@ -14,7 +14,6 @@ #include #include "api/array_view.h" -#include "modules/audio_processing/ns/ns_common.h" #include "modules/audio_processing/ns/signal_model.h" namespace webrtc { diff --git a/modules/audio_processing/ns/noise_estimator.h b/modules/audio_processing/ns/noise_estimator.h index 124ab930f3..2ae89d5ed3 100644 --- a/modules/audio_processing/ns/noise_estimator.h +++ b/modules/audio_processing/ns/noise_estimator.h @@ -12,6 +12,7 @@ #define MODULES_AUDIO_PROCESSING_NS_NOISE_ESTIMATOR_H_ #include +#include #include "api/array_view.h" #include "modules/audio_processing/ns/ns_common.h" diff --git a/modules/audio_processing/ns/noise_suppressor.cc b/modules/audio_processing/ns/noise_suppressor.cc index 070d046ccd..c86ddfd3eb 100644 --- a/modules/audio_processing/ns/noise_suppressor.cc +++ b/modules/audio_processing/ns/noise_suppressor.cc @@ -15,8 +15,15 @@ #include #include +#include +#include +#include "api/array_view.h" +#include "modules/audio_processing/audio_buffer.h" #include "modules/audio_processing/ns/fast_math.h" +#include "modules/audio_processing/ns/ns_common.h" +#include "modules/audio_processing/ns/ns_config.h" +#include "modules/audio_processing/ns/suppression_params.h" #include "rtc_base/checks.h" namespace webrtc { diff --git a/modules/audio_processing/ns/noise_suppressor.h b/modules/audio_processing/ns/noise_suppressor.h index 8ca0735fce..59312ef0fb 100644 --- a/modules/audio_processing/ns/noise_suppressor.h +++ b/modules/audio_processing/ns/noise_suppressor.h @@ -11,6 +11,9 @@ #ifndef MODULES_AUDIO_PROCESSING_NS_NOISE_SUPPRESSOR_H_ #define MODULES_AUDIO_PROCESSING_NS_NOISE_SUPPRESSOR_H_ +#include +#include +#include #include #include @@ -21,6 +24,7 @@ #include "modules/audio_processing/ns/ns_config.h" #include "modules/audio_processing/ns/ns_fft.h" #include "modules/audio_processing/ns/speech_probability_estimator.h" +#include "modules/audio_processing/ns/suppression_params.h" #include "modules/audio_processing/ns/wiener_filter.h" namespace webrtc { diff --git a/modules/audio_processing/ns/noise_suppressor_unittest.cc b/modules/audio_processing/ns/noise_suppressor_unittest.cc index f1da06eabc..1cb45637d8 100644 --- a/modules/audio_processing/ns/noise_suppressor_unittest.cc +++ b/modules/audio_processing/ns/noise_suppressor_unittest.cc @@ -10,14 +10,12 @@ #include "modules/audio_processing/ns/noise_suppressor.h" -#include -#include +#include #include -#include -#include +#include "modules/audio_processing/audio_buffer.h" +#include "modules/audio_processing/ns/ns_config.h" #include "rtc_base/strings/string_builder.h" -#include "test/gmock.h" #include "test/gtest.h" namespace webrtc { @@ -74,7 +72,7 @@ TEST(NoiseSuppressor, IdenticalChannelEffects) { SCOPED_TRACE(ProduceDebugText(rate, num_channels, level)); const size_t num_bands = rate / 16000; - // const int frame_length = webrtc::CheckedDivExact(rate, 100); + // const int frame_length = CheckedDivExact(rate, 100); AudioBuffer audio(rate, num_channels, rate, num_channels, rate, num_channels); NsConfig cfg; diff --git a/modules/audio_processing/ns/ns_fft.cc b/modules/audio_processing/ns/ns_fft.cc index bdbda8e17d..07e63739aa 100644 --- a/modules/audio_processing/ns/ns_fft.cc +++ b/modules/audio_processing/ns/ns_fft.cc @@ -10,7 +10,12 @@ #include "modules/audio_processing/ns/ns_fft.h" +#include +#include + +#include "api/array_view.h" #include "common_audio/third_party/ooura/fft_size_256/fft4g.h" +#include "modules/audio_processing/ns/ns_common.h" namespace webrtc { diff --git a/modules/audio_processing/ns/ns_fft.h b/modules/audio_processing/ns/ns_fft.h index 8cba188f80..78872512da 100644 --- a/modules/audio_processing/ns/ns_fft.h +++ b/modules/audio_processing/ns/ns_fft.h @@ -11,6 +11,7 @@ #ifndef MODULES_AUDIO_PROCESSING_NS_NS_FFT_H_ #define MODULES_AUDIO_PROCESSING_NS_NS_FFT_H_ +#include #include #include "api/array_view.h" diff --git a/modules/audio_processing/ns/prior_signal_model_estimator.cc b/modules/audio_processing/ns/prior_signal_model_estimator.cc index 3a03dc9f8a..f401764554 100644 --- a/modules/audio_processing/ns/prior_signal_model_estimator.cc +++ b/modules/audio_processing/ns/prior_signal_model_estimator.cc @@ -10,11 +10,12 @@ #include "modules/audio_processing/ns/prior_signal_model_estimator.h" -#include - #include +#include -#include "modules/audio_processing/ns/fast_math.h" +#include "api/array_view.h" +#include "modules/audio_processing/ns/histograms.h" +#include "modules/audio_processing/ns/ns_common.h" #include "rtc_base/checks.h" namespace webrtc { diff --git a/modules/audio_processing/ns/quantile_noise_estimator.cc b/modules/audio_processing/ns/quantile_noise_estimator.cc index b7847551d9..fec852b531 100644 --- a/modules/audio_processing/ns/quantile_noise_estimator.cc +++ b/modules/audio_processing/ns/quantile_noise_estimator.cc @@ -11,8 +11,13 @@ #include "modules/audio_processing/ns/quantile_noise_estimator.h" #include +#include +#include +#include +#include "api/array_view.h" #include "modules/audio_processing/ns/fast_math.h" +#include "modules/audio_processing/ns/ns_common.h" namespace webrtc { diff --git a/modules/audio_processing/ns/signal_model.cc b/modules/audio_processing/ns/signal_model.cc index 364bfd00d8..38b2637efe 100644 --- a/modules/audio_processing/ns/signal_model.cc +++ b/modules/audio_processing/ns/signal_model.cc @@ -10,6 +10,8 @@ #include "modules/audio_processing/ns/signal_model.h" +#include "modules/audio_processing/ns/ns_common.h" + namespace webrtc { SignalModel::SignalModel() { diff --git a/modules/audio_processing/ns/signal_model_estimator.cc b/modules/audio_processing/ns/signal_model_estimator.cc index 55c36ef43a..84f175f71f 100644 --- a/modules/audio_processing/ns/signal_model_estimator.cc +++ b/modules/audio_processing/ns/signal_model_estimator.cc @@ -10,7 +10,13 @@ #include "modules/audio_processing/ns/signal_model_estimator.h" +#include +#include + +#include "api/array_view.h" #include "modules/audio_processing/ns/fast_math.h" +#include "modules/audio_processing/ns/ns_common.h" +#include "rtc_base/checks.h" namespace webrtc { diff --git a/modules/audio_processing/ns/signal_model_estimator.h b/modules/audio_processing/ns/signal_model_estimator.h index 834af1ede9..540e478661 100644 --- a/modules/audio_processing/ns/signal_model_estimator.h +++ b/modules/audio_processing/ns/signal_model_estimator.h @@ -11,7 +11,7 @@ #ifndef MODULES_AUDIO_PROCESSING_NS_SIGNAL_MODEL_ESTIMATOR_H_ #define MODULES_AUDIO_PROCESSING_NS_SIGNAL_MODEL_ESTIMATOR_H_ -#include +#include #include "api/array_view.h" #include "modules/audio_processing/ns/histograms.h" diff --git a/modules/audio_processing/ns/speech_probability_estimator.cc b/modules/audio_processing/ns/speech_probability_estimator.cc index ddd20bddad..0f7369382f 100644 --- a/modules/audio_processing/ns/speech_probability_estimator.cc +++ b/modules/audio_processing/ns/speech_probability_estimator.cc @@ -10,12 +10,17 @@ #include "modules/audio_processing/ns/speech_probability_estimator.h" -#include - #include +#include +#include +#include +#include +#include "api/array_view.h" #include "modules/audio_processing/ns/fast_math.h" -#include "rtc_base/checks.h" +#include "modules/audio_processing/ns/ns_common.h" +#include "modules/audio_processing/ns/prior_signal_model.h" +#include "modules/audio_processing/ns/signal_model.h" namespace webrtc { diff --git a/modules/audio_processing/ns/speech_probability_estimator.h b/modules/audio_processing/ns/speech_probability_estimator.h index 64ed60247c..8651e8a883 100644 --- a/modules/audio_processing/ns/speech_probability_estimator.h +++ b/modules/audio_processing/ns/speech_probability_estimator.h @@ -12,6 +12,7 @@ #define MODULES_AUDIO_PROCESSING_NS_SPEECH_PROBABILITY_ESTIMATOR_H_ #include +#include #include "api/array_view.h" #include "modules/audio_processing/ns/ns_common.h" diff --git a/modules/audio_processing/ns/suppression_params.cc b/modules/audio_processing/ns/suppression_params.cc index 7bf18346f9..fd467df56d 100644 --- a/modules/audio_processing/ns/suppression_params.cc +++ b/modules/audio_processing/ns/suppression_params.cc @@ -10,6 +10,7 @@ #include "modules/audio_processing/ns/suppression_params.h" +#include "modules/audio_processing/ns/ns_config.h" #include "rtc_base/checks.h" namespace webrtc { diff --git a/modules/audio_processing/ns/wiener_filter.cc b/modules/audio_processing/ns/wiener_filter.cc index 83e40dcb07..ff8ec4d638 100644 --- a/modules/audio_processing/ns/wiener_filter.cc +++ b/modules/audio_processing/ns/wiener_filter.cc @@ -10,14 +10,16 @@ #include "modules/audio_processing/ns/wiener_filter.h" -#include -#include -#include - #include +#include +#include +#include +#include +#include "api/array_view.h" #include "modules/audio_processing/ns/fast_math.h" -#include "rtc_base/checks.h" +#include "modules/audio_processing/ns/ns_common.h" +#include "modules/audio_processing/ns/suppression_params.h" namespace webrtc { diff --git a/modules/audio_processing/ns/wiener_filter.h b/modules/audio_processing/ns/wiener_filter.h index cd45541eca..d34cd56e15 100644 --- a/modules/audio_processing/ns/wiener_filter.h +++ b/modules/audio_processing/ns/wiener_filter.h @@ -12,6 +12,7 @@ #define MODULES_AUDIO_PROCESSING_NS_WIENER_FILTER_H_ #include +#include #include "api/array_view.h" #include "modules/audio_processing/ns/ns_common.h" diff --git a/modules/audio_processing/post_filter_unittest.cc b/modules/audio_processing/post_filter_unittest.cc index 096d734a93..ecb7536373 100644 --- a/modules/audio_processing/post_filter_unittest.cc +++ b/modules/audio_processing/post_filter_unittest.cc @@ -14,6 +14,7 @@ #include #include #include +#include #include #include "api/array_view.h" @@ -91,7 +92,8 @@ TEST(PostFilterTest, Tone19p8kHzSignalAttenuation48k) { constexpr int num_frames = sample_rate_hz * 10 / 1000; // 10ms; constexpr double tone_frequency = 19800; // Hz - const double phase_increment = tone_frequency * 2.0 * M_PI / sample_rate_hz; + const double phase_increment = + tone_frequency * 2.0 * std::numbers::pi / sample_rate_hz; double phase = 0.0; std::vector audio_input(num_frames); @@ -132,7 +134,8 @@ TEST(PostFilterTest, Tone17kHzSignalNoAttenuation48k) { constexpr int num_frames = sample_rate_hz * 10 / 1000; // 10ms; constexpr double tone_frequency = 16800; // Hz - const double phase_increment = tone_frequency * 2.0 * M_PI / sample_rate_hz; + const double phase_increment = + tone_frequency * 2.0 * std::numbers::pi / sample_rate_hz; double phase = 0.0; std::vector audio_input(num_frames); diff --git a/modules/audio_processing/render_queue_item_verifier.h b/modules/audio_processing/render_queue_item_verifier.h index b8aff4a107..772d411434 100644 --- a/modules/audio_processing/render_queue_item_verifier.h +++ b/modules/audio_processing/render_queue_item_verifier.h @@ -11,6 +11,7 @@ #ifndef MODULES_AUDIO_PROCESSING_RENDER_QUEUE_ITEM_VERIFIER_H_ #define MODULES_AUDIO_PROCESSING_RENDER_QUEUE_ITEM_VERIFIER_H_ +#include #include namespace webrtc { diff --git a/modules/audio_processing/residual_echo_detector.h b/modules/audio_processing/residual_echo_detector.h index 495cc557b1..292b6ce658 100644 --- a/modules/audio_processing/residual_echo_detector.h +++ b/modules/audio_processing/residual_echo_detector.h @@ -12,6 +12,8 @@ #define MODULES_AUDIO_PROCESSING_RESIDUAL_ECHO_DETECTOR_H_ #include +#include +#include #include #include "api/array_view.h" diff --git a/modules/audio_processing/rms_level.cc b/modules/audio_processing/rms_level.cc index ffb8e91414..ef61accd0a 100644 --- a/modules/audio_processing/rms_level.cc +++ b/modules/audio_processing/rms_level.cc @@ -12,15 +12,19 @@ #include #include +#include +#include #include +#include +#include "api/array_view.h" #include "rtc_base/checks.h" namespace webrtc { namespace { -static constexpr float kMaxSquaredLevel = 32768 * 32768; +constexpr float kMaxSquaredLevel = 32768 * 32768; // kMinLevel is the level corresponding to kMinLevelDb, that is 10^(-127/10). -static constexpr float kMinLevel = 1.995262314968883e-13f; +constexpr float kMinLevel = 1.995262314968883e-13f; // Calculates the normalized RMS value from a mean square value. The input // should be the sum of squared samples divided by the number of samples. The diff --git a/modules/audio_processing/rms_level_unittest.cc b/modules/audio_processing/rms_level_unittest.cc index f9f1f9cbeb..9c95652705 100644 --- a/modules/audio_processing/rms_level_unittest.cc +++ b/modules/audio_processing/rms_level_unittest.cc @@ -7,12 +7,13 @@ * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ -// MSVC++ requires this to be set before any other includes to get M_PI. -#define _USE_MATH_DEFINES #include "modules/audio_processing/rms_level.h" #include +#include +#include #include +#include #include #include "api/array_view.h" @@ -49,7 +50,8 @@ std::vector CreateInt16Sinusoid(int frequency_hz, std::vector x(num_samples); for (size_t n = 0; n < num_samples; ++n) { x[n] = saturated_cast( - amplitude * std::sin(2 * M_PI * n * frequency_hz / kSampleRateHz)); + amplitude * + std::sin(2 * std::numbers::pi * n * frequency_hz / kSampleRateHz)); } return x; } diff --git a/modules/audio_processing/splitting_filter.cc b/modules/audio_processing/splitting_filter.cc index f607552301..c20d139f2c 100644 --- a/modules/audio_processing/splitting_filter.cc +++ b/modules/audio_processing/splitting_filter.cc @@ -11,10 +11,14 @@ #include "modules/audio_processing/splitting_filter.h" #include +#include +#include #include "api/array_view.h" #include "common_audio/channel_buffer.h" +#include "common_audio/include/audio_util.h" #include "common_audio/signal_processing/include/signal_processing_library.h" +#include "modules/audio_processing/three_band_filter_bank.h" #include "rtc_base/checks.h" namespace webrtc { diff --git a/modules/audio_processing/splitting_filter.h b/modules/audio_processing/splitting_filter.h index e578dd07c1..a4c081a368 100644 --- a/modules/audio_processing/splitting_filter.h +++ b/modules/audio_processing/splitting_filter.h @@ -12,7 +12,6 @@ #define MODULES_AUDIO_PROCESSING_SPLITTING_FILTER_H_ #include -#include #include #include "common_audio/channel_buffer.h" diff --git a/modules/audio_processing/splitting_filter_unittest.cc b/modules/audio_processing/splitting_filter_unittest.cc index 30fe4caf9c..9c6a793422 100644 --- a/modules/audio_processing/splitting_filter_unittest.cc +++ b/modules/audio_processing/splitting_filter_unittest.cc @@ -8,12 +8,12 @@ * be found in the AUTHORS file in the root of the source tree. */ -// MSVC++ requires this to be set before any other includes to get M_PI. -#define _USE_MATH_DEFINES - #include "modules/audio_processing/splitting_filter.h" #include +#include +#include +#include #include "common_audio/channel_buffer.h" #include "test/gtest.h" @@ -55,7 +55,7 @@ TEST(SplittingFilterTest, SplitsIntoThreeBandsAndReconstructs) { float amplitude = is_present[j] ? kAmplitude : 0.f; for (size_t k = 0; k < kSamplesPer48kHzChannel; ++k) { in_data.channels()[0][k] += - amplitude * sin(2.f * M_PI * kFrequenciesHz[j] * + amplitude * sin(2.f * std::numbers::pi * kFrequenciesHz[j] * (i * kSamplesPer48kHzChannel + k) / kSampleRateHz); } } diff --git a/modules/audio_processing/test/api_call_statistics.cc b/modules/audio_processing/test/api_call_statistics.cc index f3fcb12c7f..27b0db051f 100644 --- a/modules/audio_processing/test/api_call_statistics.cc +++ b/modules/audio_processing/test/api_call_statistics.cc @@ -11,6 +11,7 @@ #include "modules/audio_processing/test/api_call_statistics.h" #include +#include #include #include #include diff --git a/modules/audio_processing/test/api_call_statistics.h b/modules/audio_processing/test/api_call_statistics.h index 8fced104f9..bc1727005c 100644 --- a/modules/audio_processing/test/api_call_statistics.h +++ b/modules/audio_processing/test/api_call_statistics.h @@ -11,6 +11,7 @@ #ifndef MODULES_AUDIO_PROCESSING_TEST_API_CALL_STATISTICS_H_ #define MODULES_AUDIO_PROCESSING_TEST_API_CALL_STATISTICS_H_ +#include #include #include "absl/strings/string_view.h" diff --git a/modules/audio_processing/test/audio_buffer_tools.cc b/modules/audio_processing/test/audio_buffer_tools.cc index 10e6ad4585..8c9f58ed83 100644 --- a/modules/audio_processing/test/audio_buffer_tools.cc +++ b/modules/audio_processing/test/audio_buffer_tools.cc @@ -10,7 +10,13 @@ #include "modules/audio_processing/test/audio_buffer_tools.h" -#include +#include +#include + +#include "api/array_view.h" +#include "api/audio/audio_processing.h" +#include "modules/audio_processing/audio_buffer.h" +#include "rtc_base/checks.h" namespace webrtc { namespace test { diff --git a/modules/audio_processing/test/bitexactness_tools.cc b/modules/audio_processing/test/bitexactness_tools.cc index 25d8da9fa9..64538b3fea 100644 --- a/modules/audio_processing/test/bitexactness_tools.cc +++ b/modules/audio_processing/test/bitexactness_tools.cc @@ -10,13 +10,18 @@ #include "modules/audio_processing/test/bitexactness_tools.h" -#include - #include +#include +#include +#include +#include // no-presubmit-check TODO(webrtc:8982) #include #include #include "api/array_view.h" +#include "modules/audio_coding/neteq/tools/input_audio_file.h" +#include "rtc_base/checks.h" +#include "test/gtest.h" #include "test/testsupport/file_utils.h" namespace webrtc { diff --git a/modules/audio_processing/test/bitexactness_tools.h b/modules/audio_processing/test/bitexactness_tools.h index 30b491609f..f87658e3c6 100644 --- a/modules/audio_processing/test/bitexactness_tools.h +++ b/modules/audio_processing/test/bitexactness_tools.h @@ -12,6 +12,7 @@ #ifndef MODULES_AUDIO_PROCESSING_TEST_BITEXACTNESS_TOOLS_H_ #define MODULES_AUDIO_PROCESSING_TEST_BITEXACTNESS_TOOLS_H_ +#include #include #include "api/array_view.h" diff --git a/modules/audio_processing/test/conversational_speech/BUILD.gn b/modules/audio_processing/test/conversational_speech/BUILD.gn index b7a317db57..28f27daae4 100644 --- a/modules/audio_processing/test/conversational_speech/BUILD.gn +++ b/modules/audio_processing/test/conversational_speech/BUILD.gn @@ -19,6 +19,7 @@ if (!build_with_chromium) { sources = [ "generator.cc" ] deps = [ ":lib", + "../../../../rtc_base:checks", "../../../../test:fileutils", "../../../../test:test_support", "//third_party/abseil-cpp/absl/flags:flag", diff --git a/modules/audio_processing/test/conversational_speech/config.cc b/modules/audio_processing/test/conversational_speech/config.cc index 76d3de8108..46dc1efe69 100644 --- a/modules/audio_processing/test/conversational_speech/config.cc +++ b/modules/audio_processing/test/conversational_speech/config.cc @@ -10,6 +10,8 @@ #include "modules/audio_processing/test/conversational_speech/config.h" +#include + namespace webrtc { namespace test { namespace conversational_speech { diff --git a/modules/audio_processing/test/conversational_speech/generator.cc b/modules/audio_processing/test/conversational_speech/generator.cc index 4f776fa216..c4a0857fc4 100644 --- a/modules/audio_processing/test/conversational_speech/generator.cc +++ b/modules/audio_processing/test/conversational_speech/generator.cc @@ -8,8 +8,11 @@ * be found in the AUTHORS file in the root of the source tree. */ +#include #include #include +#include +#include #include #include "absl/flags/flag.h" @@ -19,6 +22,7 @@ #include "modules/audio_processing/test/conversational_speech/simulator.h" #include "modules/audio_processing/test/conversational_speech/timing.h" #include "modules/audio_processing/test/conversational_speech/wavreader_factory.h" +#include "rtc_base/checks.h" #include "test/testsupport/file_utils.h" ABSL_FLAG(std::string, i, "", "Directory containing the speech turn wav files"); diff --git a/modules/audio_processing/test/conversational_speech/generator_unittest.cc b/modules/audio_processing/test/conversational_speech/generator_unittest.cc index 71acb15448..390ce675e6 100644 --- a/modules/audio_processing/test/conversational_speech/generator_unittest.cc +++ b/modules/audio_processing/test/conversational_speech/generator_unittest.cc @@ -33,17 +33,13 @@ // cases in which there are wrong offsets leading to self cross-talk (which is // rejected). -// MSVC++ requires this to be set before any other includes to get M_PI. -#define _USE_MATH_DEFINES - -#include -#include - #include #include #include +#include #include #include +#include #include #include #include @@ -108,7 +104,8 @@ std::unique_ptr CreateMockWavReaderFactory() { void CreateSineWavFile(absl::string_view filepath, const MockWavReaderFactory::Params& params, float frequency_hz = 440.0f) { - const double phase_step = 2 * M_PI * frequency_hz / params.sample_rate; + const double phase_step = + 2 * std::numbers::pi * frequency_hz / params.sample_rate; double phase = 0.0; std::vector samples(params.num_samples); for (size_t i = 0; i < params.num_samples; ++i) { diff --git a/modules/audio_processing/test/conversational_speech/mock_wavreader.cc b/modules/audio_processing/test/conversational_speech/mock_wavreader.cc index 1263e938c4..7f037fe8e2 100644 --- a/modules/audio_processing/test/conversational_speech/mock_wavreader.cc +++ b/modules/audio_processing/test/conversational_speech/mock_wavreader.cc @@ -10,6 +10,10 @@ #include "modules/audio_processing/test/conversational_speech/mock_wavreader.h" +#include + +#include "test/gmock.h" + namespace webrtc { namespace test { namespace conversational_speech { diff --git a/modules/audio_processing/test/conversational_speech/mock_wavreader.h b/modules/audio_processing/test/conversational_speech/mock_wavreader.h index 298728c262..213fa57ca6 100644 --- a/modules/audio_processing/test/conversational_speech/mock_wavreader.h +++ b/modules/audio_processing/test/conversational_speech/mock_wavreader.h @@ -12,7 +12,7 @@ #define MODULES_AUDIO_PROCESSING_TEST_CONVERSATIONAL_SPEECH_MOCK_WAVREADER_H_ #include -#include +#include #include "api/array_view.h" #include "modules/audio_processing/test/conversational_speech/wavreader_interface.h" diff --git a/modules/audio_processing/test/conversational_speech/mock_wavreader_factory.cc b/modules/audio_processing/test/conversational_speech/mock_wavreader_factory.cc index a377cce7e3..2e087ff4f8 100644 --- a/modules/audio_processing/test/conversational_speech/mock_wavreader_factory.cc +++ b/modules/audio_processing/test/conversational_speech/mock_wavreader_factory.cc @@ -10,8 +10,14 @@ #include "modules/audio_processing/test/conversational_speech/mock_wavreader_factory.h" +#include +#include +#include +#include + #include "absl/strings/string_view.h" #include "modules/audio_processing/test/conversational_speech/mock_wavreader.h" +#include "modules/audio_processing/test/conversational_speech/wavreader_interface.h" #include "rtc_base/logging.h" #include "test/gmock.h" diff --git a/modules/audio_processing/test/conversational_speech/mock_wavreader_factory.h b/modules/audio_processing/test/conversational_speech/mock_wavreader_factory.h index bcc7f3069b..8dbb1446f8 100644 --- a/modules/audio_processing/test/conversational_speech/mock_wavreader_factory.h +++ b/modules/audio_processing/test/conversational_speech/mock_wavreader_factory.h @@ -11,6 +11,7 @@ #ifndef MODULES_AUDIO_PROCESSING_TEST_CONVERSATIONAL_SPEECH_MOCK_WAVREADER_FACTORY_H_ #define MODULES_AUDIO_PROCESSING_TEST_CONVERSATIONAL_SPEECH_MOCK_WAVREADER_FACTORY_H_ +#include #include #include #include diff --git a/modules/audio_processing/test/conversational_speech/multiend_call.cc b/modules/audio_processing/test/conversational_speech/multiend_call.cc index db92c5d701..242814a5c6 100644 --- a/modules/audio_processing/test/conversational_speech/multiend_call.cc +++ b/modules/audio_processing/test/conversational_speech/multiend_call.cc @@ -11,9 +11,21 @@ #include "modules/audio_processing/test/conversational_speech/multiend_call.h" #include +#include #include +#include +#include +#include +#include +#include +#include #include "absl/strings/string_view.h" +#include "api/array_view.h" +#include "modules/audio_processing/test/conversational_speech/timing.h" +#include "modules/audio_processing/test/conversational_speech/wavreader_abstract_factory.h" +#include "modules/audio_processing/test/conversational_speech/wavreader_interface.h" +#include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "test/testsupport/file_utils.h" diff --git a/modules/audio_processing/test/conversational_speech/multiend_call.h b/modules/audio_processing/test/conversational_speech/multiend_call.h index ffdbf16911..4ea53c9ff5 100644 --- a/modules/audio_processing/test/conversational_speech/multiend_call.h +++ b/modules/audio_processing/test/conversational_speech/multiend_call.h @@ -17,7 +17,6 @@ #include #include #include -#include #include #include "absl/strings/string_view.h" diff --git a/modules/audio_processing/test/conversational_speech/simulator.cc b/modules/audio_processing/test/conversational_speech/simulator.cc index 1294c551eb..f95b508cc3 100644 --- a/modules/audio_processing/test/conversational_speech/simulator.cc +++ b/modules/audio_processing/test/conversational_speech/simulator.cc @@ -10,11 +10,14 @@ #include "modules/audio_processing/test/conversational_speech/simulator.h" -#include - #include +#include +#include +#include #include #include +#include +#include #include #include @@ -22,7 +25,9 @@ #include "api/array_view.h" #include "common_audio/include/audio_util.h" #include "common_audio/wav_file.h" +#include "modules/audio_processing/test/conversational_speech/multiend_call.h" #include "modules/audio_processing/test/conversational_speech/wavreader_interface.h" +#include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "rtc_base/numerics/safe_conversions.h" #include "test/testsupport/file_utils.h" diff --git a/modules/audio_processing/test/conversational_speech/simulator.h b/modules/audio_processing/test/conversational_speech/simulator.h index 2f311e16b3..f6fe2f9e81 100644 --- a/modules/audio_processing/test/conversational_speech/simulator.h +++ b/modules/audio_processing/test/conversational_speech/simulator.h @@ -14,7 +14,6 @@ #include #include #include -#include #include "absl/strings/string_view.h" #include "modules/audio_processing/test/conversational_speech/multiend_call.h" diff --git a/modules/audio_processing/test/conversational_speech/timing.cc b/modules/audio_processing/test/conversational_speech/timing.cc index 1fc62db9f6..6f21113a09 100644 --- a/modules/audio_processing/test/conversational_speech/timing.cc +++ b/modules/audio_processing/test/conversational_speech/timing.cc @@ -13,9 +13,13 @@ #include #include #include +#include #include "absl/strings/string_view.h" +#include "api/array_view.h" +#include "rtc_base/checks.h" #include "rtc_base/string_encode.h" +#include "rtc_base/string_to_number.h" namespace webrtc { namespace test { diff --git a/modules/audio_processing/test/conversational_speech/wavreader_factory.cc b/modules/audio_processing/test/conversational_speech/wavreader_factory.cc index b277c6dc7c..0a24f4f2e0 100644 --- a/modules/audio_processing/test/conversational_speech/wavreader_factory.cc +++ b/modules/audio_processing/test/conversational_speech/wavreader_factory.cc @@ -11,11 +11,13 @@ #include "modules/audio_processing/test/conversational_speech/wavreader_factory.h" #include +#include +#include #include "absl/strings/string_view.h" #include "api/array_view.h" #include "common_audio/wav_file.h" -#include "rtc_base/checks.h" +#include "modules/audio_processing/test/conversational_speech/wavreader_interface.h" namespace webrtc { namespace test { diff --git a/modules/audio_processing/test/conversational_speech/wavreader_interface.h b/modules/audio_processing/test/conversational_speech/wavreader_interface.h index e013726680..c589c579d4 100644 --- a/modules/audio_processing/test/conversational_speech/wavreader_interface.h +++ b/modules/audio_processing/test/conversational_speech/wavreader_interface.h @@ -11,7 +11,8 @@ #ifndef MODULES_AUDIO_PROCESSING_TEST_CONVERSATIONAL_SPEECH_WAVREADER_INTERFACE_H_ #define MODULES_AUDIO_PROCESSING_TEST_CONVERSATIONAL_SPEECH_WAVREADER_INTERFACE_H_ -#include +#include +#include #include "api/array_view.h" diff --git a/modules/audio_processing/test/debug_dump_replayer.cc b/modules/audio_processing/test/debug_dump_replayer.cc index bd3631d2c3..cebc7feb43 100644 --- a/modules/audio_processing/test/debug_dump_replayer.cc +++ b/modules/audio_processing/test/debug_dump_replayer.cc @@ -10,11 +10,18 @@ #include "modules/audio_processing/test/debug_dump_replayer.h" +#include +#include +#include +#include +#include #include #include "absl/strings/string_view.h" +#include "api/audio/audio_processing.h" #include "api/audio/builtin_audio_processing_builder.h" #include "api/environment/environment_factory.h" +#include "common_audio/channel_buffer.h" #include "modules/audio_processing/test/protobuf_utils.h" #include "modules/audio_processing/test/runtime_setting_util.h" #include "rtc_base/checks.h" diff --git a/modules/audio_processing/test/debug_dump_replayer.h b/modules/audio_processing/test/debug_dump_replayer.h index 6101fc32fd..12c723952f 100644 --- a/modules/audio_processing/test/debug_dump_replayer.h +++ b/modules/audio_processing/test/debug_dump_replayer.h @@ -11,10 +11,13 @@ #ifndef MODULES_AUDIO_PROCESSING_TEST_DEBUG_DUMP_REPLAYER_H_ #define MODULES_AUDIO_PROCESSING_TEST_DEBUG_DUMP_REPLAYER_H_ +#include #include +#include #include "absl/strings/string_view.h" #include "api/audio/audio_processing.h" +#include "api/scoped_refptr.h" #include "common_audio/channel_buffer.h" // Generated at build-time by the protobuf compiler. diff --git a/modules/audio_processing/test/debug_dump_test.cc b/modules/audio_processing/test/debug_dump_test.cc index b6cb8a9716..8f6051c941 100644 --- a/modules/audio_processing/test/debug_dump_test.cc +++ b/modules/audio_processing/test/debug_dump_test.cc @@ -8,20 +8,29 @@ * be found in the AUTHORS file in the root of the source tree. */ -#include // size_t +#include +#include +#include +#include +#include #include +#include #include #include #include "absl/strings/string_view.h" +#include "api/audio/audio_processing.h" #include "api/audio/builtin_audio_processing_builder.h" -#include "api/audio/echo_canceller3_factory.h" #include "api/environment/environment_factory.h" +#include "api/scoped_refptr.h" +#include "common_audio/channel_buffer.h" +#include "common_audio/include/audio_util.h" #include "modules/audio_coding/neteq/tools/resample_input_audio_file.h" #include "modules/audio_processing/aec_dump/aec_dump_factory.h" #include "modules/audio_processing/test/debug_dump_replayer.h" -#include "modules/audio_processing/test/test_utils.h" +#include "modules/audio_processing/test/protobuf_utils.h" +#include "rtc_base/checks.h" #include "rtc_base/task_queue_for_test.h" #include "test/gtest.h" #include "test/testsupport/file_utils.h" diff --git a/modules/audio_processing/test/echo_canceller3_config_json.cc b/modules/audio_processing/test/echo_canceller3_config_json.cc index 4b89be6ee7..da449a27d9 100644 --- a/modules/audio_processing/test/echo_canceller3_config_json.cc +++ b/modules/audio_processing/test/echo_canceller3_config_json.cc @@ -9,12 +9,13 @@ */ #include "modules/audio_processing/test/echo_canceller3_config_json.h" -#include - +#include #include #include #include +#include "absl/strings/string_view.h" +#include "api/audio/echo_canceller3_config.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "rtc_base/strings/json.h" diff --git a/modules/audio_processing/test/echo_canceller3_config_json_unittest.cc b/modules/audio_processing/test/echo_canceller3_config_json_unittest.cc index ce95d8179f..e94cb962f1 100644 --- a/modules/audio_processing/test/echo_canceller3_config_json_unittest.cc +++ b/modules/audio_processing/test/echo_canceller3_config_json_unittest.cc @@ -10,6 +10,8 @@ #include "modules/audio_processing/test/echo_canceller3_config_json.h" +#include + #include "api/audio/echo_canceller3_config.h" #include "test/gtest.h" diff --git a/modules/audio_processing/test/echo_canceller_test_tools.cc b/modules/audio_processing/test/echo_canceller_test_tools.cc index f627d6783c..0d0e4077d6 100644 --- a/modules/audio_processing/test/echo_canceller_test_tools.cc +++ b/modules/audio_processing/test/echo_canceller_test_tools.cc @@ -10,7 +10,12 @@ #include "modules/audio_processing/test/echo_canceller_test_tools.h" +#include +#include + +#include "api/array_view.h" #include "rtc_base/checks.h" +#include "rtc_base/random.h" namespace webrtc { diff --git a/modules/audio_processing/test/echo_canceller_test_tools.h b/modules/audio_processing/test/echo_canceller_test_tools.h index eb5c326d46..f8a805a726 100644 --- a/modules/audio_processing/test/echo_canceller_test_tools.h +++ b/modules/audio_processing/test/echo_canceller_test_tools.h @@ -11,7 +11,7 @@ #ifndef MODULES_AUDIO_PROCESSING_TEST_ECHO_CANCELLER_TEST_TOOLS_H_ #define MODULES_AUDIO_PROCESSING_TEST_ECHO_CANCELLER_TEST_TOOLS_H_ -#include +#include #include #include "api/array_view.h" diff --git a/modules/audio_processing/test/echo_canceller_test_tools_unittest.cc b/modules/audio_processing/test/echo_canceller_test_tools_unittest.cc index cc86a192ac..b22bd452a0 100644 --- a/modules/audio_processing/test/echo_canceller_test_tools_unittest.cc +++ b/modules/audio_processing/test/echo_canceller_test_tools_unittest.cc @@ -10,6 +10,8 @@ #include "modules/audio_processing/test/echo_canceller_test_tools.h" +#include +#include #include #include "api/array_view.h" diff --git a/modules/audio_processing/test/fake_recording_device.cc b/modules/audio_processing/test/fake_recording_device.cc index dec9a93d45..6706fe56ac 100644 --- a/modules/audio_processing/test/fake_recording_device.cc +++ b/modules/audio_processing/test/fake_recording_device.cc @@ -10,11 +10,16 @@ #include "modules/audio_processing/test/fake_recording_device.h" -#include +#include +#include #include #include +#include "api/array_view.h" +#include "common_audio/channel_buffer.h" +#include "common_audio/include/audio_util.h" #include "modules/audio_processing/agc2/gain_map_internal.h" +#include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "rtc_base/numerics/safe_conversions.h" #include "rtc_base/numerics/safe_minmax.h" diff --git a/modules/audio_processing/test/fake_recording_device.h b/modules/audio_processing/test/fake_recording_device.h index 439ab84151..0fcb4d18ee 100644 --- a/modules/audio_processing/test/fake_recording_device.h +++ b/modules/audio_processing/test/fake_recording_device.h @@ -11,13 +11,11 @@ #ifndef MODULES_AUDIO_PROCESSING_TEST_FAKE_RECORDING_DEVICE_H_ #define MODULES_AUDIO_PROCESSING_TEST_FAKE_RECORDING_DEVICE_H_ -#include +#include #include -#include #include "api/array_view.h" #include "common_audio/channel_buffer.h" -#include "rtc_base/checks.h" namespace webrtc { namespace test { diff --git a/modules/audio_processing/test/fake_recording_device_unittest.cc b/modules/audio_processing/test/fake_recording_device_unittest.cc index 9da2903a01..a93dbbfa54 100644 --- a/modules/audio_processing/test/fake_recording_device_unittest.cc +++ b/modules/audio_processing/test/fake_recording_device_unittest.cc @@ -11,11 +11,13 @@ #include "modules/audio_processing/test/fake_recording_device.h" #include +#include #include #include #include -#include "api/array_view.h" +#include "common_audio/channel_buffer.h" +#include "rtc_base/checks.h" #include "rtc_base/strings/string_builder.h" #include "test/gtest.h" diff --git a/modules/audio_processing/test/performance_timer.cc b/modules/audio_processing/test/performance_timer.cc index cc12e00d6c..42e915bba2 100644 --- a/modules/audio_processing/test/performance_timer.cc +++ b/modules/audio_processing/test/performance_timer.cc @@ -12,9 +12,12 @@ #include +#include +#include #include #include "rtc_base/checks.h" +#include "system_wrappers/include/clock.h" namespace webrtc { namespace test { diff --git a/modules/audio_processing/test/performance_timer.h b/modules/audio_processing/test/performance_timer.h index b97a67d01b..1c2318491d 100644 --- a/modules/audio_processing/test/performance_timer.h +++ b/modules/audio_processing/test/performance_timer.h @@ -11,6 +11,8 @@ #ifndef MODULES_AUDIO_PROCESSING_TEST_PERFORMANCE_TIMER_H_ #define MODULES_AUDIO_PROCESSING_TEST_PERFORMANCE_TIMER_H_ +#include +#include #include #include diff --git a/modules/audio_processing/test/protobuf_utils.cc b/modules/audio_processing/test/protobuf_utils.cc index 75574961b0..a9195f299f 100644 --- a/modules/audio_processing/test/protobuf_utils.cc +++ b/modules/audio_processing/test/protobuf_utils.cc @@ -10,8 +10,13 @@ #include "modules/audio_processing/test/protobuf_utils.h" +#include +#include +#include #include +#include // no-presubmit-check TODO(webrtc:8982) +#include "rtc_base/protobuf_utils.h" #include "rtc_base/system/arch.h" namespace { diff --git a/modules/audio_processing/test/protobuf_utils.h b/modules/audio_processing/test/protobuf_utils.h index eb93383f5a..2685a4c75a 100644 --- a/modules/audio_processing/test/protobuf_utils.h +++ b/modules/audio_processing/test/protobuf_utils.h @@ -11,13 +11,16 @@ #ifndef MODULES_AUDIO_PROCESSING_TEST_PROTOBUF_UTILS_H_ #define MODULES_AUDIO_PROCESSING_TEST_PROTOBUF_UTILS_H_ +#include +#include +#include #include #include // no-presubmit-check TODO(webrtc:8982) #include "rtc_base/protobuf_utils.h" // Generated at build-time by the protobuf compiler. -#include "modules/audio_processing/debug.pb.h" +#include "modules/audio_processing/debug.pb.h" // IWYU pragma: export namespace webrtc { diff --git a/modules/audio_processing/test/runtime_setting_util.cc b/modules/audio_processing/test/runtime_setting_util.cc index 2240768d74..aec776ab56 100644 --- a/modules/audio_processing/test/runtime_setting_util.cc +++ b/modules/audio_processing/test/runtime_setting_util.cc @@ -10,6 +10,8 @@ #include "modules/audio_processing/test/runtime_setting_util.h" +#include "api/audio/audio_processing.h" +#include "modules/audio_processing/test/protobuf_utils.h" #include "rtc_base/checks.h" namespace webrtc { diff --git a/modules/audio_processing/test/runtime_setting_util.h b/modules/audio_processing/test/runtime_setting_util.h index 85ed5ecdab..54f826ae7b 100644 --- a/modules/audio_processing/test/runtime_setting_util.h +++ b/modules/audio_processing/test/runtime_setting_util.h @@ -17,7 +17,7 @@ namespace webrtc { void ReplayRuntimeSetting(AudioProcessing* apm, - const webrtc::audioproc::RuntimeSetting& setting); + const audioproc::RuntimeSetting& setting); } #endif // MODULES_AUDIO_PROCESSING_TEST_RUNTIME_SETTING_UTIL_H_ diff --git a/modules/audio_processing/test/simulator_buffers.cc b/modules/audio_processing/test/simulator_buffers.cc index a47604ee0d..aed1071077 100644 --- a/modules/audio_processing/test/simulator_buffers.cc +++ b/modules/audio_processing/test/simulator_buffers.cc @@ -10,8 +10,15 @@ #include "modules/audio_processing/test/simulator_buffers.h" +#include +#include +#include + +#include "api/audio/audio_processing.h" +#include "modules/audio_processing/audio_buffer.h" #include "modules/audio_processing/test/audio_buffer_tools.h" #include "rtc_base/checks.h" +#include "rtc_base/random.h" namespace webrtc { namespace test { diff --git a/modules/audio_processing/test/simulator_buffers.h b/modules/audio_processing/test/simulator_buffers.h index 4e1b086f7b..ebd89758f1 100644 --- a/modules/audio_processing/test/simulator_buffers.h +++ b/modules/audio_processing/test/simulator_buffers.h @@ -11,6 +11,7 @@ #ifndef MODULES_AUDIO_PROCESSING_TEST_SIMULATOR_BUFFERS_H_ #define MODULES_AUDIO_PROCESSING_TEST_SIMULATOR_BUFFERS_H_ +#include #include #include diff --git a/modules/audio_processing/test/test_utils.cc b/modules/audio_processing/test/test_utils.cc index fcbd5e495e..d4b221d668 100644 --- a/modules/audio_processing/test/test_utils.cc +++ b/modules/audio_processing/test/test_utils.cc @@ -11,12 +11,22 @@ #include "modules/audio_processing/test/test_utils.h" #include +#include +#include +#include +#include +#include +#include #include #include +#include #include "absl/strings/string_view.h" +#include "api/audio/audio_view.h" +#include "common_audio/channel_buffer.h" +#include "common_audio/include/audio_util.h" +#include "common_audio/wav_file.h" #include "rtc_base/checks.h" -#include "rtc_base/system/arch.h" namespace webrtc { diff --git a/modules/audio_processing/test/test_utils.h b/modules/audio_processing/test/test_utils.h index 90cfb5ccc4..e979c85978 100644 --- a/modules/audio_processing/test/test_utils.h +++ b/modules/audio_processing/test/test_utils.h @@ -11,12 +11,12 @@ #ifndef MODULES_AUDIO_PROCESSING_TEST_TEST_UTILS_H_ #define MODULES_AUDIO_PROCESSING_TEST_TEST_UTILS_H_ -#include - -#include -#include +#include +#include +#include +#include +#include #include -#include #include #include "absl/strings/string_view.h" diff --git a/modules/audio_processing/three_band_filter_bank.cc b/modules/audio_processing/three_band_filter_bank.cc index 45b44a7762..a04852a4c7 100644 --- a/modules/audio_processing/three_band_filter_bank.cc +++ b/modules/audio_processing/three_band_filter_bank.cc @@ -32,9 +32,11 @@ #include "modules/audio_processing/three_band_filter_bank.h" +#include #include #include +#include "api/array_view.h" #include "rtc_base/checks.h" namespace webrtc { diff --git a/modules/audio_processing/three_band_filter_bank.h b/modules/audio_processing/three_band_filter_bank.h index 5c7dc1c834..84feb39d07 100644 --- a/modules/audio_processing/three_band_filter_bank.h +++ b/modules/audio_processing/three_band_filter_bank.h @@ -13,8 +13,6 @@ #include #include -#include -#include #include "api/array_view.h" diff --git a/modules/audio_processing/utility/BUILD.gn b/modules/audio_processing/utility/BUILD.gn index 8dfb870cc9..63ee6d066e 100644 --- a/modules/audio_processing/utility/BUILD.gn +++ b/modules/audio_processing/utility/BUILD.gn @@ -50,6 +50,7 @@ if (rtc_include_tests) { sources = [ "cascaded_biquad_filter_unittest.cc" ] deps = [ ":cascaded_biquad_filter", + "../../../rtc_base:checks", "../../../test:test_support", "//api:array_view", "//rtc_base:checks", @@ -73,6 +74,7 @@ if (rtc_include_tests) { sources = [ "pffft_wrapper_unittest.cc" ] deps = [ ":pffft_wrapper", + "../../../api:array_view", "../../../test:test_support", "//testing/gtest", "//third_party/pffft", diff --git a/modules/audio_processing/utility/delay_estimator.cc b/modules/audio_processing/utility/delay_estimator.cc index 6f97b28a77..20609fbbfa 100644 --- a/modules/audio_processing/utility/delay_estimator.cc +++ b/modules/audio_processing/utility/delay_estimator.cc @@ -14,6 +14,7 @@ #include #include +#include #include "rtc_base/checks.h" @@ -23,24 +24,24 @@ namespace { // Number of right shifts for scaling is linearly depending on number of bits in // the far-end binary spectrum. -static const int kShiftsAtZero = 13; // Right shifts at zero binary spectrum. -static const int kShiftsLinearSlope = 3; +const int kShiftsAtZero = 13; // Right shifts at zero binary spectrum. +const int kShiftsLinearSlope = 3; -static const int32_t kProbabilityOffset = 1024; // 2 in Q9. -static const int32_t kProbabilityLowerLimit = 8704; // 17 in Q9. -static const int32_t kProbabilityMinSpread = 2816; // 5.5 in Q9. +const int32_t kProbabilityOffset = 1024; // 2 in Q9. +const int32_t kProbabilityLowerLimit = 8704; // 17 in Q9. +const int32_t kProbabilityMinSpread = 2816; // 5.5 in Q9. // Robust validation settings -static const float kHistogramMax = 3000.f; -static const float kLastHistogramMax = 250.f; -static const float kMinHistogramThreshold = 1.5f; -static const int kMinRequiredHits = 10; -static const int kMaxHitsWhenPossiblyNonCausal = 10; -static const int kMaxHitsWhenPossiblyCausal = 1000; -static const float kQ14Scaling = 1.f / (1 << 14); // Scaling by 2^14 to get Q0. -static const float kFractionSlope = 0.05f; -static const float kMinFractionWhenPossiblyCausal = 0.5f; -static const float kMinFractionWhenPossiblyNonCausal = 0.25f; +const float kHistogramMax = 3000.f; +const float kLastHistogramMax = 250.f; +const float kMinHistogramThreshold = 1.5f; +const int kMinRequiredHits = 10; +const int kMaxHitsWhenPossiblyNonCausal = 10; +const int kMaxHitsWhenPossiblyCausal = 1000; +const float kQ14Scaling = 1.f / (1 << 14); // Scaling by 2^14 to get Q0. +const float kFractionSlope = 0.05f; +const float kMinFractionWhenPossiblyCausal = 0.5f; +const float kMinFractionWhenPossiblyNonCausal = 0.25f; } // namespace diff --git a/modules/audio_processing/utility/delay_estimator_internal.h b/modules/audio_processing/utility/delay_estimator_internal.h index 891e20027d..1ef6cd478a 100644 --- a/modules/audio_processing/utility/delay_estimator_internal.h +++ b/modules/audio_processing/utility/delay_estimator_internal.h @@ -13,6 +13,8 @@ #ifndef MODULES_AUDIO_PROCESSING_UTILITY_DELAY_ESTIMATOR_INTERNAL_H_ #define MODULES_AUDIO_PROCESSING_UTILITY_DELAY_ESTIMATOR_INTERNAL_H_ +#include + #include "modules/audio_processing/utility/delay_estimator.h" namespace webrtc { diff --git a/modules/audio_processing/utility/delay_estimator_unittest.cc b/modules/audio_processing/utility/delay_estimator_unittest.cc index b026088a90..ba77688fed 100644 --- a/modules/audio_processing/utility/delay_estimator_unittest.cc +++ b/modules/audio_processing/utility/delay_estimator_unittest.cc @@ -10,6 +10,10 @@ #include "modules/audio_processing/utility/delay_estimator.h" +#include +#include +#include + #include "modules/audio_processing/utility/delay_estimator_internal.h" #include "modules/audio_processing/utility/delay_estimator_wrapper.h" #include "test/gtest.h" diff --git a/modules/audio_processing/utility/delay_estimator_wrapper.cc b/modules/audio_processing/utility/delay_estimator_wrapper.cc index 216066afe0..05e4b74393 100644 --- a/modules/audio_processing/utility/delay_estimator_wrapper.cc +++ b/modules/audio_processing/utility/delay_estimator_wrapper.cc @@ -13,6 +13,8 @@ #include #include +#include + #include "modules/audio_processing/utility/delay_estimator.h" #include "modules/audio_processing/utility/delay_estimator_internal.h" #include "rtc_base/checks.h" diff --git a/modules/audio_processing/utility/pffft_wrapper.cc b/modules/audio_processing/utility/pffft_wrapper.cc index 3f65941c76..59b590005d 100644 --- a/modules/audio_processing/utility/pffft_wrapper.cc +++ b/modules/audio_processing/utility/pffft_wrapper.cc @@ -10,6 +10,10 @@ #include "modules/audio_processing/utility/pffft_wrapper.h" +#include +#include + +#include "api/array_view.h" #include "rtc_base/checks.h" #include "third_party/pffft/src/pffft.h" diff --git a/modules/audio_processing/utility/pffft_wrapper.h b/modules/audio_processing/utility/pffft_wrapper.h index b555b4b1e1..590310e5dc 100644 --- a/modules/audio_processing/utility/pffft_wrapper.h +++ b/modules/audio_processing/utility/pffft_wrapper.h @@ -11,6 +11,7 @@ #ifndef MODULES_AUDIO_PROCESSING_UTILITY_PFFFT_WRAPPER_H_ #define MODULES_AUDIO_PROCESSING_UTILITY_PFFFT_WRAPPER_H_ +#include #include #include "api/array_view.h" @@ -67,7 +68,7 @@ class Pffft { // Creates a buffer of the right size. std::unique_ptr CreateBuffer() const; - // TODO(https://crbug.com/webrtc/9577): Overload with webrtc::ArrayView args. + // TODO(https://crbug.com/webrtc/9577): Overload with ArrayView args. // Computes the forward fast Fourier transform. void ForwardTransform(const FloatBuffer& in, FloatBuffer* out, bool ordered); // Computes the backward fast Fourier transform. diff --git a/modules/audio_processing/utility/pffft_wrapper_unittest.cc b/modules/audio_processing/utility/pffft_wrapper_unittest.cc index 71cda9333e..f1ce5209d2 100644 --- a/modules/audio_processing/utility/pffft_wrapper_unittest.cc +++ b/modules/audio_processing/utility/pffft_wrapper_unittest.cc @@ -14,6 +14,7 @@ #include #include +#include "api/array_view.h" #include "test/gtest.h" #include "third_party/pffft/src/pffft.h" @@ -23,9 +24,9 @@ namespace { constexpr size_t kMaxValidSizeCheck = 1024; -static constexpr int kFftSizes[] = { - 16, 32, 64, 96, 128, 160, 192, 256, 288, 384, 5 * 96, 512, - 576, 5 * 128, 800, 864, 1024, 2048, 2592, 4000, 4096, 12000, 36864}; +constexpr int kFftSizes[] = {16, 32, 64, 96, 128, 160, 192, 256, + 288, 384, 5 * 96, 512, 576, 5 * 128, 800, 864, + 1024, 2048, 2592, 4000, 4096, 12000, 36864}; void CreatePffftWrapper(size_t fft_size, Pffft::FftType fft_type) { Pffft pffft_wrapper(fft_size, fft_type); diff --git a/modules/audio_processing/vad/pitch_based_vad.cc b/modules/audio_processing/vad/pitch_based_vad.cc index 68e60dc66a..8bbbd242f1 100644 --- a/modules/audio_processing/vad/pitch_based_vad.cc +++ b/modules/audio_processing/vad/pitch_based_vad.cc @@ -10,9 +10,10 @@ #include "modules/audio_processing/vad/pitch_based_vad.h" -#include +#include #include "modules/audio_processing/vad/common.h" +#include "modules/audio_processing/vad/gmm.h" #include "modules/audio_processing/vad/noise_gmm_tables.h" #include "modules/audio_processing/vad/vad_circular_buffer.h" #include "modules/audio_processing/vad/voice_gmm_tables.h" diff --git a/modules/audio_processing/vad/pitch_based_vad_unittest.cc b/modules/audio_processing/vad/pitch_based_vad_unittest.cc index 3b7b956fa1..f2aa6d3780 100644 --- a/modules/audio_processing/vad/pitch_based_vad_unittest.cc +++ b/modules/audio_processing/vad/pitch_based_vad_unittest.cc @@ -10,11 +10,11 @@ #include "modules/audio_processing/vad/pitch_based_vad.h" -#include -#include - +#include +#include #include +#include "modules/audio_processing/vad/common.h" #include "test/gtest.h" #include "test/testsupport/file_utils.h" diff --git a/modules/audio_processing/vad/pole_zero_filter.cc b/modules/audio_processing/vad/pole_zero_filter.cc index 97688a44cb..c9282a63bd 100644 --- a/modules/audio_processing/vad/pole_zero_filter.cc +++ b/modules/audio_processing/vad/pole_zero_filter.cc @@ -10,9 +10,9 @@ #include "modules/audio_processing/vad/pole_zero_filter.h" -#include - #include +#include +#include namespace webrtc { diff --git a/modules/audio_processing/vad/pole_zero_filter_unittest.cc b/modules/audio_processing/vad/pole_zero_filter_unittest.cc index 8088b40125..909e7709b3 100644 --- a/modules/audio_processing/vad/pole_zero_filter_unittest.cc +++ b/modules/audio_processing/vad/pole_zero_filter_unittest.cc @@ -10,14 +10,11 @@ #include "modules/audio_processing/vad/pole_zero_filter.h" -#include -#include - +#include #include #include "modules/audio_processing/vad/vad_audio_proc_internal.h" #include "test/gtest.h" -#include "test/testsupport/file_utils.h" namespace webrtc { diff --git a/modules/audio_processing/vad/standalone_vad.cc b/modules/audio_processing/vad/standalone_vad.cc index 1397668eb4..107349d300 100644 --- a/modules/audio_processing/vad/standalone_vad.cc +++ b/modules/audio_processing/vad/standalone_vad.cc @@ -10,9 +10,11 @@ #include "modules/audio_processing/vad/standalone_vad.h" -#include +#include +#include #include "common_audio/vad/include/webrtc_vad.h" +#include "modules/audio_processing/vad/common.h" #include "rtc_base/checks.h" namespace webrtc { diff --git a/modules/audio_processing/vad/standalone_vad_unittest.cc b/modules/audio_processing/vad/standalone_vad_unittest.cc index 139f49a235..1618fdc89f 100644 --- a/modules/audio_processing/vad/standalone_vad_unittest.cc +++ b/modules/audio_processing/vad/standalone_vad_unittest.cc @@ -10,10 +10,12 @@ #include "modules/audio_processing/vad/standalone_vad.h" -#include - +#include +#include +#include #include +#include "modules/audio_processing/vad/common.h" #include "test/gtest.h" #include "test/testsupport/file_utils.h" diff --git a/modules/audio_processing/vad/vad_audio_proc.cc b/modules/audio_processing/vad/vad_audio_proc.cc index aaf8214d7c..bd7c07ff27 100644 --- a/modules/audio_processing/vad/vad_audio_proc.cc +++ b/modules/audio_processing/vad/vad_audio_proc.cc @@ -10,11 +10,13 @@ #include "modules/audio_processing/vad/vad_audio_proc.h" -#include -#include -#include +#include +#include +#include +#include #include "common_audio/third_party/ooura/fft_size_256/fft4g.h" +#include "modules/audio_processing/vad/common.h" #include "modules/audio_processing/vad/pitch_internal.h" #include "modules/audio_processing/vad/pole_zero_filter.h" #include "modules/audio_processing/vad/vad_audio_proc_internal.h" diff --git a/modules/audio_processing/vad/vad_audio_proc_unittest.cc b/modules/audio_processing/vad/vad_audio_proc_unittest.cc index 9fe3dc6c03..c7d3a8b515 100644 --- a/modules/audio_processing/vad/vad_audio_proc_unittest.cc +++ b/modules/audio_processing/vad/vad_audio_proc_unittest.cc @@ -14,9 +14,8 @@ #include "modules/audio_processing/vad/vad_audio_proc.h" -#include -#include - +#include +#include #include #include "modules/audio_processing/vad/common.h" diff --git a/modules/audio_processing/vad/voice_activity_detector.cc b/modules/audio_processing/vad/voice_activity_detector.cc index 02023d6a72..1b22831cd2 100644 --- a/modules/audio_processing/vad/voice_activity_detector.cc +++ b/modules/audio_processing/vad/voice_activity_detector.cc @@ -11,7 +11,11 @@ #include "modules/audio_processing/vad/voice_activity_detector.h" #include +#include +#include +#include "modules/audio_processing/vad/common.h" +#include "modules/audio_processing/vad/standalone_vad.h" #include "rtc_base/checks.h" namespace webrtc { diff --git a/modules/audio_processing/vad/voice_activity_detector.h b/modules/audio_processing/vad/voice_activity_detector.h index 401acca699..5754e89523 100644 --- a/modules/audio_processing/vad/voice_activity_detector.h +++ b/modules/audio_processing/vad/voice_activity_detector.h @@ -33,7 +33,7 @@ class VoiceActivityDetector { ~VoiceActivityDetector(); // Processes each audio chunk and estimates the voice probability. - // TODO(bugs.webrtc.org/7494): Switch to webrtc::ArrayView and remove + // TODO(bugs.webrtc.org/7494): Switch to ArrayView and remove // `sample_rate_hz`. void ProcessChunk(const int16_t* audio, size_t length, int sample_rate_hz); diff --git a/modules/audio_processing/vad/voice_activity_detector_unittest.cc b/modules/audio_processing/vad/voice_activity_detector_unittest.cc index 80f21c8db0..5922c8bf70 100644 --- a/modules/audio_processing/vad/voice_activity_detector_unittest.cc +++ b/modules/audio_processing/vad/voice_activity_detector_unittest.cc @@ -11,8 +11,13 @@ #include "modules/audio_processing/vad/voice_activity_detector.h" #include +#include +#include +#include +#include #include +#include "modules/audio_processing/vad/common.h" #include "test/gtest.h" #include "test/testsupport/file_utils.h" diff --git a/modules/congestion_controller/BUILD.gn b/modules/congestion_controller/BUILD.gn index 64dbdcd845..b82bbf72df 100644 --- a/modules/congestion_controller/BUILD.gn +++ b/modules/congestion_controller/BUILD.gn @@ -52,6 +52,7 @@ if (rtc_include_tests && !build_with_chromium) { ] deps = [ ":congestion_controller", + "../../api:field_trials", "../../api:rtp_parameters", "../../api/environment:environment_factory", "../../api/test/network_emulation", @@ -62,7 +63,7 @@ if (rtc_include_tests && !build_with_chromium) { "../../api/units:timestamp", "../../rtc_base:buffer", "../../system_wrappers", - "../../test:explicit_key_value_config", + "../../test:create_test_field_trials", "../../test:test_support", "../../test/scenario", "../pacing", diff --git a/modules/congestion_controller/goog_cc/BUILD.gn b/modules/congestion_controller/goog_cc/BUILD.gn index f970a33b94..e1cd1c4813 100644 --- a/modules/congestion_controller/goog_cc/BUILD.gn +++ b/modules/congestion_controller/goog_cc/BUILD.gn @@ -118,13 +118,8 @@ rtc_library("estimators") { "../../../logging:rtc_event_bwe", "../../../rtc_base:checks", "../../../rtc_base:logging", - "../../../rtc_base:macromagic", - "../../../rtc_base:rtc_numerics", - "../../../rtc_base:safe_conversions", "../../../rtc_base:safe_minmax", "../../../rtc_base/experiments:field_trial_parser", - "../../remote_bitrate_estimator", - "//third_party/abseil-cpp/absl/strings", ] } @@ -148,31 +143,12 @@ rtc_library("loss_based_bwe_v2") { ] } -rtc_library("loss_based_bwe_v1") { - sources = [ - "loss_based_bandwidth_estimation.cc", - "loss_based_bandwidth_estimation.h", - ] - deps = [ - "../../../api:field_trials_view", - "../../../api/transport:network_control", - "../../../api/units:data_rate", - "../../../api/units:time_delta", - "../../../api/units:timestamp", - "../../../rtc_base:checks", - "../../../rtc_base/experiments:field_trial_parser", - "//third_party/abseil-cpp/absl/strings", - "//third_party/abseil-cpp/absl/strings:string_view", - ] -} - rtc_library("send_side_bwe") { sources = [ "send_side_bandwidth_estimation.cc", "send_side_bandwidth_estimation.h", ] deps = [ - ":loss_based_bwe_v1", ":loss_based_bwe_v2", "../../../api:field_trials_view", "../../../api/rtc_event_log", @@ -303,6 +279,7 @@ if (rtc_include_tests) { ":probe_controller", ":pushback_controller", ":send_side_bwe", + "../../../api:field_trials", "../../../api:field_trials_view", "../../../api:network_state_predictor_api", "../../../api/environment", @@ -328,8 +305,7 @@ if (rtc_include_tests) { "../../../rtc_base:stringutils", "../../../rtc_base/experiments:alr_experiment", "../../../system_wrappers", - "../../../test:explicit_key_value_config", - "../../../test:field_trial", + "../../../test:create_test_field_trials", "../../../test:test_support", "../../../test/network:emulated_network", "../../../test/scenario", diff --git a/modules/congestion_controller/goog_cc/acknowledged_bitrate_estimator_unittest.cc b/modules/congestion_controller/goog_cc/acknowledged_bitrate_estimator_unittest.cc index cc6e4a07e5..098ae958b1 100644 --- a/modules/congestion_controller/goog_cc/acknowledged_bitrate_estimator_unittest.cc +++ b/modules/congestion_controller/goog_cc/acknowledged_bitrate_estimator_unittest.cc @@ -17,12 +17,13 @@ #include #include -#include "api/transport/field_trial_based_config.h" +#include "api/field_trials.h" #include "api/transport/network_types.h" #include "api/units/data_rate.h" #include "api/units/data_size.h" #include "api/units/timestamp.h" #include "modules/congestion_controller/goog_cc/bitrate_estimator.h" +#include "test/create_test_field_trials.h" #include "test/gmock.h" #include "test/gtest.h" @@ -50,7 +51,7 @@ class MockBitrateEstimator : public BitrateEstimator { }; struct AcknowledgedBitrateEstimatorTestStates { - FieldTrialBasedConfig field_trial_config; + FieldTrials field_trial_config = CreateTestFieldTrials(); std::unique_ptr acknowledged_bitrate_estimator; MockBitrateEstimator* mock_bitrate_estimator; }; @@ -139,4 +140,4 @@ TEST(TestAcknowledgedBitrateEstimator, ReturnBitrate) { EXPECT_EQ(return_value, states.acknowledged_bitrate_estimator->bitrate()); } -} // namespace webrtc*/ +} // namespace webrtc diff --git a/modules/congestion_controller/goog_cc/alr_detector_unittest.cc b/modules/congestion_controller/goog_cc/alr_detector_unittest.cc index 725bd342d6..2fdba71dff 100644 --- a/modules/congestion_controller/goog_cc/alr_detector_unittest.cc +++ b/modules/congestion_controller/goog_cc/alr_detector_unittest.cc @@ -13,10 +13,10 @@ #include #include -#include "api/transport/field_trial_based_config.h" +#include "api/field_trials.h" #include "rtc_base/checks.h" #include "rtc_base/experiments/alr_experiment.h" -#include "test/field_trial.h" +#include "test/create_test_field_trials.h" #include "test/gtest.h" namespace { @@ -74,7 +74,7 @@ class SimulateOutgoingTrafficIn { } // namespace TEST(AlrDetectorTest, AlrDetection) { - FieldTrialBasedConfig field_trials; + FieldTrials field_trials = CreateTestFieldTrials(); int64_t timestamp_ms = 1000; AlrDetector alr_detector(&field_trials); alr_detector.SetEstimatedBitrate(kEstimatedBitrateBps); @@ -102,7 +102,7 @@ TEST(AlrDetectorTest, AlrDetection) { } TEST(AlrDetectorTest, ShortSpike) { - FieldTrialBasedConfig field_trials; + FieldTrials field_trials = CreateTestFieldTrials(); int64_t timestamp_ms = 1000; AlrDetector alr_detector(&field_trials); alr_detector.SetEstimatedBitrate(kEstimatedBitrateBps); @@ -129,7 +129,7 @@ TEST(AlrDetectorTest, ShortSpike) { } TEST(AlrDetectorTest, BandwidthEstimateChanges) { - FieldTrialBasedConfig field_trials; + FieldTrials field_trials = CreateTestFieldTrials(); int64_t timestamp_ms = 1000; AlrDetector alr_detector(&field_trials); alr_detector.SetEstimatedBitrate(kEstimatedBitrateBps); @@ -156,20 +156,20 @@ TEST(AlrDetectorTest, BandwidthEstimateChanges) { } TEST(AlrDetectorTest, ParseControlFieldTrial) { - test::ScopedFieldTrials scoped_field_trial( - "WebRTC-ProbingScreenshareBwe/Control/"); + FieldTrials field_trials = + CreateTestFieldTrials("WebRTC-ProbingScreenshareBwe/Control/"); std::optional parsed_params = AlrExperimentSettings::CreateFromFieldTrial( - FieldTrialBasedConfig(), "WebRTC-ProbingScreenshareBwe"); + field_trials, "WebRTC-ProbingScreenshareBwe"); EXPECT_FALSE(static_cast(parsed_params)); } TEST(AlrDetectorTest, ParseActiveFieldTrial) { - test::ScopedFieldTrials scoped_field_trial( + FieldTrials field_trials = CreateTestFieldTrials( "WebRTC-ProbingScreenshareBwe/1.1,2875,85,20,-20,1/"); std::optional parsed_params = AlrExperimentSettings::CreateFromFieldTrial( - FieldTrialBasedConfig(), "WebRTC-ProbingScreenshareBwe"); + field_trials, "WebRTC-ProbingScreenshareBwe"); ASSERT_TRUE(static_cast(parsed_params)); EXPECT_EQ(1.1f, parsed_params->pacing_factor); EXPECT_EQ(2875, parsed_params->max_paced_queue_time); @@ -180,10 +180,9 @@ TEST(AlrDetectorTest, ParseActiveFieldTrial) { } TEST(AlrDetectorTest, ParseAlrSpecificFieldTrial) { - test::ScopedFieldTrials scoped_field_trial( + FieldTrials field_trials = CreateTestFieldTrials( "WebRTC-AlrDetectorParameters/" "bw_usage:90%,start:0%,stop:-10%/"); - FieldTrialBasedConfig field_trials; AlrDetector alr_detector(&field_trials); int64_t timestamp_ms = 1000; alr_detector.SetEstimatedBitrate(kEstimatedBitrateBps); diff --git a/modules/congestion_controller/goog_cc/congestion_window_pushback_controller_unittest.cc b/modules/congestion_controller/goog_cc/congestion_window_pushback_controller_unittest.cc index 6f85c4c8d4..76db80e35b 100644 --- a/modules/congestion_controller/goog_cc/congestion_window_pushback_controller_unittest.cc +++ b/modules/congestion_controller/goog_cc/congestion_window_pushback_controller_unittest.cc @@ -13,15 +13,14 @@ #include #include "api/units/data_size.h" -#include "test/explicit_key_value_config.h" +#include "test/create_test_field_trials.h" #include "test/gtest.h" namespace webrtc { namespace test { TEST(CongestionWindowPushbackControllerTest, FullCongestionWindow) { - CongestionWindowPushbackController cwnd_controller( - ExplicitKeyValueConfig("")); + CongestionWindowPushbackController cwnd_controller(CreateTestFieldTrials()); cwnd_controller.UpdateOutstandingData(100000); cwnd_controller.SetDataWindow(DataSize::Bytes(50000)); @@ -36,8 +35,7 @@ TEST(CongestionWindowPushbackControllerTest, FullCongestionWindow) { } TEST(CongestionWindowPushbackControllerTest, NormalCongestionWindow) { - CongestionWindowPushbackController cwnd_controller( - ExplicitKeyValueConfig("")); + CongestionWindowPushbackController cwnd_controller(CreateTestFieldTrials()); cwnd_controller.UpdateOutstandingData(199999); cwnd_controller.SetDataWindow(DataSize::Bytes(200000)); @@ -48,8 +46,7 @@ TEST(CongestionWindowPushbackControllerTest, NormalCongestionWindow) { } TEST(CongestionWindowPushbackControllerTest, LowBitrate) { - CongestionWindowPushbackController cwnd_controller( - ExplicitKeyValueConfig("")); + CongestionWindowPushbackController cwnd_controller(CreateTestFieldTrials()); cwnd_controller.UpdateOutstandingData(100000); cwnd_controller.SetDataWindow(DataSize::Bytes(50000)); @@ -64,8 +61,7 @@ TEST(CongestionWindowPushbackControllerTest, LowBitrate) { } TEST(CongestionWindowPushbackControllerTest, NoPushbackOnDataWindowUnset) { - CongestionWindowPushbackController cwnd_controller( - ExplicitKeyValueConfig("")); + CongestionWindowPushbackController cwnd_controller(CreateTestFieldTrials()); cwnd_controller.UpdateOutstandingData(1e8); // Large number @@ -76,7 +72,7 @@ TEST(CongestionWindowPushbackControllerTest, NoPushbackOnDataWindowUnset) { TEST(CongestionWindowPushbackControllerTest, PushbackOnInititialDataWindow) { CongestionWindowPushbackController cwnd_controller( - ExplicitKeyValueConfig("WebRTC-CongestionWindow/InitWin:100000/")); + CreateTestFieldTrials("WebRTC-CongestionWindow/InitWin:100000/")); cwnd_controller.UpdateOutstandingData(1e8); // Large number @@ -87,7 +83,7 @@ TEST(CongestionWindowPushbackControllerTest, PushbackOnInititialDataWindow) { TEST(CongestionWindowPushbackControllerTest, PushbackDropFrame) { CongestionWindowPushbackController cwnd_controller( - ExplicitKeyValueConfig("WebRTC-CongestionWindow/DropFrame:true/")); + CreateTestFieldTrials("WebRTC-CongestionWindow/DropFrame:true/")); cwnd_controller.UpdateOutstandingData(1e8); // Large number cwnd_controller.SetDataWindow(DataSize::Bytes(50000)); diff --git a/modules/congestion_controller/goog_cc/delay_based_bwe.cc b/modules/congestion_controller/goog_cc/delay_based_bwe.cc index 9769792de3..079ce22568 100644 --- a/modules/congestion_controller/goog_cc/delay_based_bwe.cc +++ b/modules/congestion_controller/goog_cc/delay_based_bwe.cc @@ -80,9 +80,9 @@ DelayBasedBwe::DelayBasedBwe(const FieldTrialsView* key_value_config, last_video_packet_recv_time_(Timestamp::MinusInfinity()), network_state_predictor_(network_state_predictor), video_delay_detector_( - new TrendlineEstimator(key_value_config_, network_state_predictor_)), + new TrendlineEstimator(*key_value_config_, network_state_predictor_)), audio_delay_detector_( - new TrendlineEstimator(key_value_config_, network_state_predictor_)), + new TrendlineEstimator(*key_value_config_, network_state_predictor_)), active_delay_detector_(video_delay_detector_.get()), last_seen_packet_(Timestamp::MinusInfinity()), uma_recorded_(false), @@ -155,9 +155,9 @@ void DelayBasedBwe::IncomingPacketFeedback(const PacketResult& packet_feedback, std::make_unique(kSendTimeGroupLength); video_delay_detector_.reset( - new TrendlineEstimator(key_value_config_, network_state_predictor_)); + new TrendlineEstimator(*key_value_config_, network_state_predictor_)); audio_delay_detector_.reset( - new TrendlineEstimator(key_value_config_, network_state_predictor_)); + new TrendlineEstimator(*key_value_config_, network_state_predictor_)); active_delay_detector_ = video_delay_detector_.get(); } last_seen_packet_ = at_time; diff --git a/modules/congestion_controller/goog_cc/delay_based_bwe_unittest_helper.cc b/modules/congestion_controller/goog_cc/delay_based_bwe_unittest_helper.cc index 9e22ae8682..c6e44a0513 100644 --- a/modules/congestion_controller/goog_cc/delay_based_bwe_unittest_helper.cc +++ b/modules/congestion_controller/goog_cc/delay_based_bwe_unittest_helper.cc @@ -25,7 +25,7 @@ #include "modules/congestion_controller/goog_cc/delay_based_bwe.h" #include "modules/congestion_controller/goog_cc/probe_bitrate_estimator.h" #include "rtc_base/checks.h" -#include "test/field_trial.h" +#include "test/create_test_field_trials.h" #include "test/gtest.h" namespace webrtc { @@ -159,14 +159,13 @@ int64_t StreamGenerator::GenerateFrame(int64_t time_now_us, } // namespace test DelayBasedBweTest::DelayBasedBweTest() - : field_trial(std::make_unique( + : field_trials_(CreateTestFieldTrials( "WebRTC-Bwe-RobustThroughputEstimatorSettings/enabled:true/")), clock_(100000000), acknowledged_bitrate_estimator_( - AcknowledgedBitrateEstimatorInterface::Create(&field_trial_config_)), + AcknowledgedBitrateEstimatorInterface::Create(&field_trials_)), probe_bitrate_estimator_(new ProbeBitrateEstimator(nullptr)), - bitrate_estimator_( - new DelayBasedBwe(&field_trial_config_, nullptr, nullptr)), + bitrate_estimator_(new DelayBasedBwe(&field_trials_, nullptr, nullptr)), stream_generator_(new test::StreamGenerator(1e6, // Capacity. clock_.TimeInMicroseconds())), arrival_time_offset_ms_(0), diff --git a/modules/congestion_controller/goog_cc/delay_based_bwe_unittest_helper.h b/modules/congestion_controller/goog_cc/delay_based_bwe_unittest_helper.h index b885ef2d23..78850c3e74 100644 --- a/modules/congestion_controller/goog_cc/delay_based_bwe_unittest_helper.h +++ b/modules/congestion_controller/goog_cc/delay_based_bwe_unittest_helper.h @@ -17,14 +17,13 @@ #include #include -#include "api/transport/field_trial_based_config.h" +#include "api/field_trials.h" #include "api/transport/network_types.h" #include "api/units/timestamp.h" #include "modules/congestion_controller/goog_cc/acknowledged_bitrate_estimator_interface.h" #include "modules/congestion_controller/goog_cc/delay_based_bwe.h" #include "modules/congestion_controller/goog_cc/probe_bitrate_estimator.h" #include "system_wrappers/include/clock.h" -#include "test/field_trial.h" #include "test/gtest.h" namespace webrtc { @@ -170,10 +169,7 @@ class DelayBasedBweTest : public ::testing::Test { int64_t receiver_clock_offset_change_ms); static const uint32_t kDefaultSsrc; - FieldTrialBasedConfig field_trial_config_; - - std::unique_ptr - field_trial; // Must be initialized first. + FieldTrials field_trials_; SimulatedClock clock_; // Time at the receiver. test::TestBitrateObserver bitrate_observer_; std::unique_ptr diff --git a/modules/congestion_controller/goog_cc/goog_cc_network_control.cc b/modules/congestion_controller/goog_cc/goog_cc_network_control.cc index f318e85612..e3ee7f3299 100644 --- a/modules/congestion_controller/goog_cc/goog_cc_network_control.cc +++ b/modules/congestion_controller/goog_cc/goog_cc_network_control.cc @@ -15,7 +15,6 @@ #include #include #include -#include #include #include #include @@ -48,8 +47,6 @@ namespace webrtc { namespace { -// From RTCPSender video report interval. -constexpr TimeDelta kLossUpdateInterval = TimeDelta::Millis(1000); // Pacing-rate relative to our target send rate. // Multiplicative factor that is applied to the target bitrate to calculate @@ -93,7 +90,6 @@ BandwidthLimitedCause GetBandwidthLimitedCause(LossBasedState loss_based_state, GoogCcNetworkController::GoogCcNetworkController(NetworkControllerConfig config, GoogCcConfig goog_cc_config) : env_(config.env), - packet_feedback_only_(goog_cc_config.feedback_only), safe_reset_on_route_change_("Enabled"), safe_reset_acknowledged_rate_("ack"), use_min_allocatable_as_lower_bound_( @@ -250,10 +246,6 @@ NetworkControlUpdate GoogCcNetworkController::OnProcessInterval( NetworkControlUpdate GoogCcNetworkController::OnRemoteBitrateReport( RemoteBitrateReport msg) { - if (packet_feedback_only_) { - RTC_LOG(LS_ERROR) << "Received REMB for packet feedback only GoogCC"; - return NetworkControlUpdate(); - } bandwidth_estimation_->UpdateReceiverEstimate(msg.receive_time, msg.bandwidth); return NetworkControlUpdate(); @@ -261,8 +253,9 @@ NetworkControlUpdate GoogCcNetworkController::OnRemoteBitrateReport( NetworkControlUpdate GoogCcNetworkController::OnRoundTripTimeUpdate( RoundTripTimeUpdate msg) { - if (packet_feedback_only_ || msg.smoothed) + if (msg.smoothed) { return NetworkControlUpdate(); + } RTC_DCHECK(!msg.round_trip_time.IsZero()); if (delay_based_bwe_) delay_based_bwe_->OnRttUpdate(msg.round_trip_time); @@ -388,8 +381,6 @@ std::vector GoogCcNetworkController::ResetConstraints( NetworkControlUpdate GoogCcNetworkController::OnTransportLossReport( TransportLossReport msg) { - if (packet_feedback_only_) - return NetworkControlUpdate(); int64_t total_packets_delta = msg.packets_received_delta + msg.packets_lost_delta; bandwidth_estimation_->UpdatePacketsLost( @@ -455,46 +446,9 @@ NetworkControlUpdate GoogCcNetworkController::OnTransportPacketsFeedback( bandwidth_estimation_->UpdatePropagationRtt(report.feedback_time, min_propagation_rtt); } - if (packet_feedback_only_) { - if (!feedback_max_rtts_.empty()) { - int64_t sum_rtt_ms = - std::accumulate(feedback_max_rtts_.begin(), feedback_max_rtts_.end(), - static_cast(0)); - int64_t mean_rtt_ms = sum_rtt_ms / feedback_max_rtts_.size(); - if (delay_based_bwe_) - delay_based_bwe_->OnRttUpdate(TimeDelta::Millis(mean_rtt_ms)); - } - - TimeDelta feedback_min_rtt = TimeDelta::PlusInfinity(); - for (const auto& packet_feedback : feedbacks) { - TimeDelta pending_time = max_recv_time - packet_feedback.receive_time; - TimeDelta rtt = report.feedback_time - - packet_feedback.sent_packet.send_time - pending_time; - // Value used for predicting NACK round trip time in FEC controller. - feedback_min_rtt = std::min(rtt, feedback_min_rtt); - } - if (feedback_min_rtt.IsFinite()) { - bandwidth_estimation_->UpdateRtt(feedback_min_rtt, report.feedback_time); - } - expected_packets_since_last_loss_update_ += - report.PacketsWithFeedback().size(); - for (const auto& packet_feedback : report.PacketsWithFeedback()) { - if (!packet_feedback.IsReceived()) - lost_packets_since_last_loss_update_ += 1; - } - if (report.feedback_time > next_loss_update_) { - next_loss_update_ = report.feedback_time + kLossUpdateInterval; - bandwidth_estimation_->UpdatePacketsLost( - lost_packets_since_last_loss_update_, - expected_packets_since_last_loss_update_, report.feedback_time); - expected_packets_since_last_loss_update_ = 0; - lost_packets_since_last_loss_update_ = 0; - } - } std::optional alr_start_time = alr_detector_->GetApplicationLimitedRegionStartTime(); - if (previously_in_alr_ && !alr_start_time.has_value()) { int64_t now_ms = report.feedback_time.ms(); acknowledged_bitrate_estimator_->SetAlrEndedTime(report.feedback_time); diff --git a/modules/congestion_controller/goog_cc/goog_cc_network_control.h b/modules/congestion_controller/goog_cc/goog_cc_network_control.h index 46d1cabe53..ade7b91f7a 100644 --- a/modules/congestion_controller/goog_cc/goog_cc_network_control.h +++ b/modules/congestion_controller/goog_cc/goog_cc_network_control.h @@ -41,7 +41,6 @@ namespace webrtc { struct GoogCcConfig { std::unique_ptr network_state_estimator = nullptr; std::unique_ptr network_state_predictor = nullptr; - bool feedback_only = false; }; class GoogCcNetworkController : public NetworkControllerInterface { @@ -86,7 +85,6 @@ class GoogCcNetworkController : public NetworkControllerInterface { void SetNetworkStateEstimate(std::optional estimate); const Environment env_; - const bool packet_feedback_only_; FieldTrialFlag safe_reset_on_route_change_; FieldTrialFlag safe_reset_acknowledged_rate_; const bool use_min_allocatable_as_lower_bound_; @@ -119,10 +117,6 @@ class GoogCcNetworkController : public NetworkControllerInterface { std::optional estimate_; - Timestamp next_loss_update_ = Timestamp::MinusInfinity(); - int lost_packets_since_last_loss_update_ = 0; - int expected_packets_since_last_loss_update_ = 0; - std::deque feedback_max_rtts_; DataRate last_loss_based_target_rate_; diff --git a/modules/congestion_controller/goog_cc/goog_cc_network_control_unittest.cc b/modules/congestion_controller/goog_cc/goog_cc_network_control_unittest.cc index abe9a9b53d..dbbdd4d1fd 100644 --- a/modules/congestion_controller/goog_cc/goog_cc_network_control_unittest.cc +++ b/modules/congestion_controller/goog_cc/goog_cc_network_control_unittest.cc @@ -21,6 +21,7 @@ #include "absl/strings/string_view.h" #include "api/environment/environment.h" #include "api/environment/environment_factory.h" +#include "api/field_trials.h" #include "api/test/network_emulation/create_cross_traffic.h" #include "api/test/network_emulation/cross_traffic.h" #include "api/transport/goog_cc_factory.h" @@ -31,8 +32,7 @@ #include "api/units/time_delta.h" #include "api/units/timestamp.h" #include "call/video_receive_stream.h" -#include "logging/rtc_event_log/mock/mock_rtc_event_log.h" -#include "test/field_trial.h" +#include "test/create_test_field_trials.h" #include "test/gmock.h" #include "test/gtest.h" #include "test/network/network_emulation.h" @@ -71,11 +71,6 @@ int CountBandwidthDips(std::queue bandwidth_history, } return dips; } -GoogCcNetworkControllerFactory CreateFeedbackOnlyFactory() { - GoogCcFactoryConfig config; - config.feedback_only = true; - return GoogCcNetworkControllerFactory(std::move(config)); -} const uint32_t kInitialBitrateKbps = 60; const DataRate kInitialBitrate = DataRate::KilobitsPerSec(kInitialBitrateKbps); @@ -158,32 +153,14 @@ std::optional PacketTransmissionAndFeedbackBlock( return target_bitrate; } -// Create transport packets feedback with a built-up delay. -TransportPacketsFeedback CreateTransportPacketsFeedback( - TimeDelta per_packet_network_delay, - TimeDelta one_way_delay, - Timestamp send_time) { - TimeDelta delay_buildup = one_way_delay; - constexpr int kFeedbackSize = 3; - constexpr size_t kPayloadSize = 1000; - TransportPacketsFeedback feedback; - for (int i = 0; i < kFeedbackSize; ++i) { - PacketResult packet = CreatePacketResult( - /*arrival_time=*/send_time + delay_buildup, send_time, kPayloadSize, - PacedPacketInfo()); - delay_buildup += per_packet_network_delay; - feedback.feedback_time = packet.receive_time + one_way_delay; - feedback.packet_feedbacks.push_back(packet); - } - return feedback; -} - // Scenarios: -void UpdatesTargetRateBasedOnLinkCapacity(absl::string_view test_name = "") { - auto factory = CreateFeedbackOnlyFactory(); +void UpdatesTargetRateBasedOnLinkCapacity(absl::string_view test_name = "", + absl::string_view field_trials = "") { + GoogCcNetworkControllerFactory factory; Scenario s("googcc_unit/target_capacity" + std::string(test_name), false); CallClientConfig config; + config.field_trials.Merge(FieldTrials(field_trials)); config.transport.cc_factory = &factory; config.transport.rates.min_rate = DataRate::KilobitsPerSec(10); config.transport.rates.max_rate = DataRate::KilobitsPerSec(1500); @@ -262,7 +239,8 @@ DataRate RunRembDipScenario(absl::string_view test_name) { class NetworkControllerTestFixture { public: - NetworkControllerTestFixture() : factory_() {} + explicit NetworkControllerTestFixture(absl::string_view field_trials = "") + : field_trials_(CreateTestFieldTrials(field_trials)) {} explicit NetworkControllerTestFixture(GoogCcFactoryConfig googcc_config) : factory_(std::move(googcc_config)) {} @@ -289,8 +267,8 @@ class NetworkControllerTestFixture { return config; } - NiceMock event_log_; - const Environment env_ = CreateEnvironment(&event_log_); + FieldTrials field_trials_ = CreateTestFieldTrials(); + const Environment env_ = CreateEnvironment(&field_trials_); GoogCcNetworkControllerFactory factory_; }; @@ -439,9 +417,9 @@ TEST(GoogCcNetworkControllerTest, UpdatesDelayBasedEstimate) { } TEST(GoogCcNetworkControllerTest, LimitPacingFactorToUpperLinkCapacity) { - ScopedFieldTrials trial( + NetworkControllerTestFixture fixture( + /*field_trials=*/ "WebRTC-Bwe-LimitPacingFactorByUpperLinkCapacityEstimate/Enabled/"); - NetworkControllerTestFixture fixture; std::unique_ptr controller = fixture.CreateController(); Timestamp current_time = Timestamp::Millis(123); @@ -471,9 +449,7 @@ TEST(GoogCcNetworkControllerTest, LimitPacingFactorToUpperLinkCapacity) { // Test congestion window pushback on network delay happens. TEST(GoogCcScenario, CongestionWindowPushbackOnNetworkDelay) { - auto factory = CreateFeedbackOnlyFactory(); - ScopedFieldTrials trial( - "WebRTC-CongestionWindow/QueueSize:800,MinBitrate:30000/"); + GoogCcNetworkControllerFactory factory; Scenario s("googcc_unit/cwnd_on_delay", false); auto send_net = s.CreateMutableSimulationNode([=](NetworkSimulationConfig* c) { @@ -483,6 +459,8 @@ TEST(GoogCcScenario, CongestionWindowPushbackOnNetworkDelay) { auto ret_net = s.CreateSimulationNode( [](NetworkSimulationConfig* c) { c->delay = TimeDelta::Millis(100); }); CallClientConfig config; + config.field_trials.Set("WebRTC-CongestionWindow", + "QueueSize:800,MinBitrate:30000"); config.transport.cc_factory = &factory; // Start high so bandwidth drop has max effect. config.transport.rates.start_rate = DataRate::KilobitsPerSec(300); @@ -505,9 +483,7 @@ TEST(GoogCcScenario, CongestionWindowPushbackOnNetworkDelay) { // Test congestion window pushback on network delay happens. TEST(GoogCcScenario, CongestionWindowPushbackDropFrameOnNetworkDelay) { - auto factory = CreateFeedbackOnlyFactory(); - ScopedFieldTrials trial( - "WebRTC-CongestionWindow/QueueSize:800,MinBitrate:30000,DropFrame:true/"); + GoogCcNetworkControllerFactory factory; Scenario s("googcc_unit/cwnd_on_delay", false); auto send_net = s.CreateMutableSimulationNode([=](NetworkSimulationConfig* c) { @@ -517,6 +493,8 @@ TEST(GoogCcScenario, CongestionWindowPushbackDropFrameOnNetworkDelay) { auto ret_net = s.CreateSimulationNode( [](NetworkSimulationConfig* c) { c->delay = TimeDelta::Millis(100); }); CallClientConfig config; + config.field_trials.Set("WebRTC-CongestionWindow", + "QueueSize:800,MinBitrate:30000,DropFrame:true"); config.transport.cc_factory = &factory; // Start high so bandwidth drop has max effect. config.transport.rates.start_rate = DataRate::KilobitsPerSec(300); @@ -537,9 +515,6 @@ TEST(GoogCcScenario, CongestionWindowPushbackDropFrameOnNetworkDelay) { } TEST(GoogCcScenario, PaddingRateLimitedByCongestionWindowInTrial) { - ScopedFieldTrials trial( - "WebRTC-CongestionWindow/QueueSize:200,MinBitrate:30000/"); - Scenario s("googcc_unit/padding_limited", false); auto send_net = s.CreateMutableSimulationNode([=](NetworkSimulationConfig* c) { @@ -549,6 +524,8 @@ TEST(GoogCcScenario, PaddingRateLimitedByCongestionWindowInTrial) { auto ret_net = s.CreateSimulationNode( [](NetworkSimulationConfig* c) { c->delay = TimeDelta::Millis(100); }); CallClientConfig config; + config.field_trials.Set("WebRTC-CongestionWindow", + "QueueSize:200,MinBitrate:30000"); // Start high so bandwidth drop has max effect. config.transport.rates.start_rate = DataRate::KilobitsPerSec(1000); config.transport.rates.max_rate = DataRate::KilobitsPerSec(2000); @@ -577,8 +554,6 @@ TEST(GoogCcScenario, LimitsToFloorIfRttIsHighInTrial) { // allows the RTT to recover faster than the regular control mechanism would // achieve. const DataRate kBandwidthFloor = DataRate::KilobitsPerSec(50); - ScopedFieldTrials trial("WebRTC-Bwe-MaxRttLimit/limit:2s,floor:" + - std::to_string(kBandwidthFloor.kbps()) + "kbps/"); // In the test case, we limit the capacity and add a cross traffic packet // burst that blocks media from being sent. This causes the RTT to quickly // increase above the threshold in the trial. @@ -592,6 +567,9 @@ TEST(GoogCcScenario, LimitsToFloorIfRttIsHighInTrial) { auto ret_net = s.CreateSimulationNode( [](NetworkSimulationConfig* c) { c->delay = TimeDelta::Millis(100); }); CallClientConfig config; + config.field_trials.Set( + "WebRTC-Bwe-MaxRttLimit", + "limit:2s,floor:" + std::to_string(kBandwidthFloor.kbps()) + "kbps"); config.transport.rates.start_rate = kLinkCapacity; auto* client = CreateVideoSendingClient(&s, config, {send_net}, {ret_net}); @@ -613,7 +591,7 @@ TEST(GoogCcScenario, UpdatesTargetRateBasedOnLinkCapacity) { } TEST(GoogCcScenario, StableEstimateDoesNotVaryInSteadyState) { - auto factory = CreateFeedbackOnlyFactory(); + GoogCcNetworkControllerFactory factory; Scenario s("googcc_unit/stable_target", false); CallClientConfig config; config.transport.cc_factory = &factory; @@ -649,14 +627,7 @@ TEST(GoogCcScenario, StableEstimateDoesNotVaryInSteadyState) { EXPECT_GE(min_stable_target / max_stable_target, min_target / max_target); } -TEST(GoogCcScenario, LossBasedControlUpdatesTargetRateBasedOnLinkCapacity) { - ScopedFieldTrials trial("WebRTC-Bwe-LossBasedControl/Enabled/"); - // TODO(srte): Should the behavior be unaffected at low loss rates? - UpdatesTargetRateBasedOnLinkCapacity("_loss_based"); -} - TEST(GoogCcScenario, LossBasedControlDoesModestBackoffToHighLoss) { - ScopedFieldTrials trial("WebRTC-Bwe-LossBasedControl/Enabled/"); Scenario s("googcc_unit/high_loss_channel", false); CallClientConfig config; config.transport.rates.min_rate = DataRate::KilobitsPerSec(10); @@ -673,7 +644,6 @@ TEST(GoogCcScenario, LossBasedControlDoesModestBackoffToHighLoss) { auto* client = CreateVideoSendingClient(&s, config, {send_net}, {ret_net}); s.RunFor(TimeDelta::Seconds(120)); - // Without LossBasedControl trial, bandwidth drops to ~10 kbps. EXPECT_GT(client->target_rate().kbps(), 100); } @@ -726,13 +696,13 @@ TEST(GoogCcScenario, MaintainsLowRateInSafeResetTrial) { const DataRate kLinkCapacity = DataRate::KilobitsPerSec(200); const DataRate kStartRate = DataRate::KilobitsPerSec(300); - ScopedFieldTrials trial("WebRTC-Bwe-SafeResetOnRouteChange/Enabled/"); Scenario s("googcc_unit/safe_reset_low"); auto* send_net = s.CreateSimulationNode([&](NetworkSimulationConfig* c) { c->bandwidth = kLinkCapacity; c->delay = TimeDelta::Millis(10); }); auto* client = s.CreateClient("send", [&](CallClientConfig* c) { + c->field_trials.Set("WebRTC-Bwe-SafeResetOnRouteChange", "Enabled"); c->transport.rates.start_rate = kStartRate; }); auto* route = s.CreateRoutes( @@ -750,7 +720,6 @@ TEST(GoogCcScenario, MaintainsLowRateInSafeResetTrial) { } TEST(GoogCcScenario, DoNotResetBweUnlessNetworkAdapterChangeOnRoutChange) { - ScopedFieldTrials trial("WebRTC-Bwe-ResetOnAdapterIdChange/Enabled/"); Scenario s("googcc_unit/do_not_reset_bwe_unless_adapter_change"); const DataRate kLinkCapacity = DataRate::KilobitsPerSec(1000); @@ -761,6 +730,7 @@ TEST(GoogCcScenario, DoNotResetBweUnlessNetworkAdapterChangeOnRoutChange) { c->delay = TimeDelta::Millis(50); }); auto* client = s.CreateClient("send", [&](CallClientConfig* c) { + c->field_trials.Set("WebRTC-Bwe-ResetOnAdapterIdChange", "Enabled"); c->transport.rates.start_rate = kStartRate; }); client->UpdateNetworkAdapterId(0); @@ -791,13 +761,13 @@ TEST(GoogCcScenario, CutsHighRateInSafeResetTrial) { const DataRate kLinkCapacity = DataRate::KilobitsPerSec(1000); const DataRate kStartRate = DataRate::KilobitsPerSec(300); - ScopedFieldTrials trial("WebRTC-Bwe-SafeResetOnRouteChange/Enabled/"); Scenario s("googcc_unit/safe_reset_high_cut"); auto send_net = s.CreateSimulationNode([&](NetworkSimulationConfig* c) { c->bandwidth = kLinkCapacity; c->delay = TimeDelta::Millis(50); }); auto* client = s.CreateClient("send", [&](CallClientConfig* c) { + c->field_trials.Set("WebRTC-Bwe-SafeResetOnRouteChange", "Enabled"); c->transport.rates.start_rate = kStartRate; }); auto* route = s.CreateRoutes( @@ -816,7 +786,6 @@ TEST(GoogCcScenario, CutsHighRateInSafeResetTrial) { } TEST(GoogCcScenario, DetectsHighRateInSafeResetTrial) { - ScopedFieldTrials trial("WebRTC-Bwe-SafeResetOnRouteChange/Enabled,ack/"); const DataRate kInitialLinkCapacity = DataRate::KilobitsPerSec(200); const DataRate kNewLinkCapacity = DataRate::KilobitsPerSec(800); const DataRate kStartRate = DataRate::KilobitsPerSec(300); @@ -831,6 +800,7 @@ TEST(GoogCcScenario, DetectsHighRateInSafeResetTrial) { c->delay = TimeDelta::Millis(50); }); auto* client = s.CreateClient("send", [&](CallClientConfig* c) { + c->field_trials.Set("WebRTC-Bwe-SafeResetOnRouteChange", "Enabled,ack"); c->transport.rates.start_rate = kStartRate; }); auto* route = s.CreateRoutes( @@ -855,12 +825,6 @@ TEST(GoogCcScenario, DetectsHighRateInSafeResetTrial) { } TEST(GoogCcScenario, TargetRateReducedOnPacingBufferBuildupInTrial) { - // Configure strict pacing to ensure build-up. - ScopedFieldTrials trial( - "WebRTC-CongestionWindow/QueueSize:100,MinBitrate:30000/" - "WebRTC-Video-Pacing/factor:1.0/" - "WebRTC-AddPacingToCongestionWindowPushback/Enabled/"); - const DataRate kLinkCapacity = DataRate::KilobitsPerSec(1000); const DataRate kStartRate = DataRate::KilobitsPerSec(1000); @@ -870,6 +834,11 @@ TEST(GoogCcScenario, TargetRateReducedOnPacingBufferBuildupInTrial) { c->delay = TimeDelta::Millis(50); }); auto* client = s.CreateClient("send", [&](CallClientConfig* c) { + c->field_trials.Set("WebRTC-CongestionWindow", + "QueueSize:100,MinBitrate:30000"); + c->field_trials.Set("WebRTC-Video-Pacing", "factor:1.0"); + c->field_trials.Set("WebRTC-AddPacingToCongestionWindowPushback", + "Enabled"); c->transport.rates.start_rate = kStartRate; }); auto* route = s.CreateRoutes( @@ -884,7 +853,6 @@ TEST(GoogCcScenario, TargetRateReducedOnPacingBufferBuildupInTrial) { } TEST(GoogCcScenario, NoBandwidthTogglingInLossControlTrial) { - ScopedFieldTrials trial("WebRTC-Bwe-LossBasedControl/Enabled/"); Scenario s("googcc_unit/no_toggling"); auto* send_net = s.CreateSimulationNode([&](NetworkSimulationConfig* c) { c->bandwidth = DataRate::KilobitsPerSec(2000); @@ -893,6 +861,7 @@ TEST(GoogCcScenario, NoBandwidthTogglingInLossControlTrial) { }); auto* client = s.CreateClient("send", [&](CallClientConfig* c) { + c->field_trials.Set("WebRTC-Bwe-LossBasedControl", "Enabled"); c->transport.rates.start_rate = DataRate::KilobitsPerSec(300); }); auto* route = s.CreateRoutes( @@ -918,7 +887,6 @@ TEST(GoogCcScenario, NoBandwidthTogglingInLossControlTrial) { } TEST(GoogCcScenario, NoRttBackoffCollapseWhenVideoStops) { - ScopedFieldTrials trial("WebRTC-Bwe-MaxRttLimit/limit:2s/"); Scenario s("googcc_unit/rttbackoff_video_stop"); auto* send_net = s.CreateSimulationNode([&](NetworkSimulationConfig* c) { c->bandwidth = DataRate::KilobitsPerSec(2000); @@ -926,6 +894,7 @@ TEST(GoogCcScenario, NoRttBackoffCollapseWhenVideoStops) { }); auto* client = s.CreateClient("send", [&](CallClientConfig* c) { + c->field_trials.Set("WebRTC-Bwe-MaxRttLimit", "limit:2s"); c->transport.rates.start_rate = DataRate::KilobitsPerSec(1000); }); auto* route = s.CreateRoutes( @@ -1026,45 +995,5 @@ TEST(GoogCcScenario, FallbackToLossBasedBweWithoutPacketFeedback) { EXPECT_LE(client->target_rate().kbps(), 300); } -class GoogCcRttTest : public ::testing::TestWithParam { - protected: - GoogCcFactoryConfig Config(bool feedback_only) { - GoogCcFactoryConfig config; - config.feedback_only = feedback_only; - return config; - } -}; - -TEST_P(GoogCcRttTest, CalculatesRttFromTransporFeedback) { - GoogCcFactoryConfig config(Config(/*feedback_only=*/GetParam())); - if (!GetParam()) { - // TODO(diepbp): understand the usage difference between - // UpdatePropagationRtt and UpdateRtt - GTEST_SKIP() << "This test should run only if " - "feedback_only is enabled"; - } - NetworkControllerTestFixture fixture(std::move(config)); - std::unique_ptr controller = - fixture.CreateController(); - Timestamp current_time = Timestamp::Millis(123); - TimeDelta one_way_delay = TimeDelta::Millis(10); - std::optional rtt = std::nullopt; - - TransportPacketsFeedback feedback = CreateTransportPacketsFeedback( - /*per_packet_network_delay=*/TimeDelta::Millis(50), one_way_delay, - /*send_time=*/current_time); - NetworkControlUpdate update = - controller->OnTransportPacketsFeedback(feedback); - current_time += TimeDelta::Millis(50); - update = controller->OnProcessInterval({.at_time = current_time}); - if (update.target_rate) { - rtt = update.target_rate->network_estimate.round_trip_time; - } - ASSERT_TRUE(rtt.has_value()); - EXPECT_EQ(rtt->ms(), 2 * one_way_delay.ms()); -} - -INSTANTIATE_TEST_SUITE_P(GoogCcRttTests, GoogCcRttTest, ::testing::Bool()); - } // namespace test } // namespace webrtc diff --git a/modules/congestion_controller/goog_cc/loss_based_bandwidth_estimation.cc b/modules/congestion_controller/goog_cc/loss_based_bandwidth_estimation.cc deleted file mode 100644 index 08bd4b3fc4..0000000000 --- a/modules/congestion_controller/goog_cc/loss_based_bandwidth_estimation.cc +++ /dev/null @@ -1,266 +0,0 @@ -/* - * Copyright (c) 2018 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 "modules/congestion_controller/goog_cc/loss_based_bandwidth_estimation.h" - -#include -#include -#include - -#include "absl/strings/match.h" -#include "absl/strings/string_view.h" -#include "api/field_trials_view.h" -#include "api/transport/network_types.h" -#include "api/units/data_rate.h" -#include "api/units/time_delta.h" -#include "api/units/timestamp.h" -#include "rtc_base/checks.h" -#include "rtc_base/experiments/field_trial_parser.h" - -namespace webrtc { -namespace { -const char kBweLossBasedControl[] = "WebRTC-Bwe-LossBasedControl"; - -// Expecting RTCP feedback to be sent with roughly 1s intervals, a 5s gap -// indicates a channel outage. -constexpr TimeDelta kMaxRtcpFeedbackInterval = TimeDelta::Millis(5000); - -// Increase slower when RTT is high. -double GetIncreaseFactor(const LossBasedControlConfig& config, TimeDelta rtt) { - // Clamp the RTT - if (rtt < config.increase_low_rtt) { - rtt = config.increase_low_rtt; - } else if (rtt > config.increase_high_rtt) { - rtt = config.increase_high_rtt; - } - auto rtt_range = config.increase_high_rtt.Get() - config.increase_low_rtt; - if (rtt_range <= TimeDelta::Zero()) { - RTC_DCHECK_NOTREACHED(); // Only on misconfiguration. - return config.min_increase_factor; - } - auto rtt_offset = rtt - config.increase_low_rtt; - auto relative_offset = std::max(0.0, std::min(rtt_offset / rtt_range, 1.0)); - auto factor_range = config.max_increase_factor - config.min_increase_factor; - return config.min_increase_factor + (1 - relative_offset) * factor_range; -} - -double LossFromBitrate(DataRate bitrate, - DataRate loss_bandwidth_balance, - double exponent) { - if (loss_bandwidth_balance >= bitrate) - return 1.0; - return pow(loss_bandwidth_balance / bitrate, exponent); -} - -DataRate BitrateFromLoss(double loss, - DataRate loss_bandwidth_balance, - double exponent) { - if (exponent <= 0) { - RTC_DCHECK_NOTREACHED(); - return DataRate::Infinity(); - } - if (loss < 1e-5) - return DataRate::Infinity(); - return loss_bandwidth_balance * pow(loss, -1.0 / exponent); -} - -double ExponentialUpdate(TimeDelta window, TimeDelta interval) { - // Use the convention that exponential window length (which is really - // infinite) is the time it takes to dampen to 1/e. - if (window <= TimeDelta::Zero()) { - RTC_DCHECK_NOTREACHED(); - return 1.0f; - } - return 1.0f - exp(interval / window * -1.0); -} - -bool IsEnabled(const FieldTrialsView& key_value_config, - absl::string_view name) { - return absl::StartsWith(key_value_config.Lookup(name), "Enabled"); -} - -} // namespace - -LossBasedControlConfig::LossBasedControlConfig( - const FieldTrialsView* key_value_config) - : enabled(IsEnabled(*key_value_config, kBweLossBasedControl)), - min_increase_factor("min_incr", 1.02), - max_increase_factor("max_incr", 1.08), - increase_low_rtt("incr_low_rtt", TimeDelta::Millis(200)), - increase_high_rtt("incr_high_rtt", TimeDelta::Millis(800)), - decrease_factor("decr", 0.99), - loss_window("loss_win", TimeDelta::Millis(800)), - loss_max_window("loss_max_win", TimeDelta::Millis(800)), - acknowledged_rate_max_window("ackrate_max_win", TimeDelta::Millis(800)), - increase_offset("incr_offset", DataRate::BitsPerSec(1000)), - loss_bandwidth_balance_increase("balance_incr", - DataRate::KilobitsPerSec(0.5)), - loss_bandwidth_balance_decrease("balance_decr", - DataRate::KilobitsPerSec(4)), - loss_bandwidth_balance_reset("balance_reset", - DataRate::KilobitsPerSec(0.1)), - loss_bandwidth_balance_exponent("exponent", 0.5), - allow_resets("resets", false), - decrease_interval("decr_intvl", TimeDelta::Millis(300)), - loss_report_timeout("timeout", TimeDelta::Millis(6000)) { - ParseFieldTrial( - {&min_increase_factor, &max_increase_factor, &increase_low_rtt, - &increase_high_rtt, &decrease_factor, &loss_window, &loss_max_window, - &acknowledged_rate_max_window, &increase_offset, - &loss_bandwidth_balance_increase, &loss_bandwidth_balance_decrease, - &loss_bandwidth_balance_reset, &loss_bandwidth_balance_exponent, - &allow_resets, &decrease_interval, &loss_report_timeout}, - key_value_config->Lookup(kBweLossBasedControl)); -} -LossBasedControlConfig::LossBasedControlConfig(const LossBasedControlConfig&) = - default; -LossBasedControlConfig::~LossBasedControlConfig() = default; - -LossBasedBandwidthEstimation::LossBasedBandwidthEstimation( - const FieldTrialsView* key_value_config) - : config_(key_value_config), - average_loss_(0), - average_loss_max_(0), - loss_based_bitrate_(DataRate::Zero()), - acknowledged_bitrate_max_(DataRate::Zero()), - acknowledged_bitrate_last_update_(Timestamp::MinusInfinity()), - time_last_decrease_(Timestamp::MinusInfinity()), - has_decreased_since_last_loss_report_(false), - last_loss_packet_report_(Timestamp::MinusInfinity()), - last_loss_ratio_(0) {} - -void LossBasedBandwidthEstimation::UpdateLossStatistics( - const std::vector& packet_results, - Timestamp at_time) { - if (packet_results.empty()) { - RTC_DCHECK_NOTREACHED(); - return; - } - int loss_count = 0; - for (const auto& pkt : packet_results) { - loss_count += !pkt.IsReceived() ? 1 : 0; - } - last_loss_ratio_ = static_cast(loss_count) / packet_results.size(); - const TimeDelta time_passed = last_loss_packet_report_.IsFinite() - ? at_time - last_loss_packet_report_ - : TimeDelta::Seconds(1); - last_loss_packet_report_ = at_time; - has_decreased_since_last_loss_report_ = false; - - average_loss_ += ExponentialUpdate(config_.loss_window, time_passed) * - (last_loss_ratio_ - average_loss_); - if (average_loss_ > average_loss_max_) { - average_loss_max_ = average_loss_; - } else { - average_loss_max_ += - ExponentialUpdate(config_.loss_max_window, time_passed) * - (average_loss_ - average_loss_max_); - } -} - -void LossBasedBandwidthEstimation::UpdateAcknowledgedBitrate( - DataRate acknowledged_bitrate, - Timestamp at_time) { - const TimeDelta time_passed = - acknowledged_bitrate_last_update_.IsFinite() - ? at_time - acknowledged_bitrate_last_update_ - : TimeDelta::Seconds(1); - acknowledged_bitrate_last_update_ = at_time; - if (acknowledged_bitrate > acknowledged_bitrate_max_) { - acknowledged_bitrate_max_ = acknowledged_bitrate; - } else { - acknowledged_bitrate_max_ -= - ExponentialUpdate(config_.acknowledged_rate_max_window, time_passed) * - (acknowledged_bitrate_max_ - acknowledged_bitrate); - } -} - -DataRate LossBasedBandwidthEstimation::Update(Timestamp at_time, - DataRate min_bitrate, - DataRate wanted_bitrate, - TimeDelta last_round_trip_time) { - if (loss_based_bitrate_.IsZero()) { - loss_based_bitrate_ = wanted_bitrate; - } - - // Only increase if loss has been low for some time. - const double loss_estimate_for_increase = average_loss_max_; - // Avoid multiple decreases from averaging over one loss spike. - const double loss_estimate_for_decrease = - std::min(average_loss_, last_loss_ratio_); - const bool allow_decrease = - !has_decreased_since_last_loss_report_ && - (at_time - time_last_decrease_ >= - last_round_trip_time + config_.decrease_interval); - // If packet lost reports are too old, dont increase bitrate. - const bool loss_report_valid = - at_time - last_loss_packet_report_ < 1.2 * kMaxRtcpFeedbackInterval; - - if (loss_report_valid && config_.allow_resets && - loss_estimate_for_increase < loss_reset_threshold()) { - loss_based_bitrate_ = wanted_bitrate; - } else if (loss_report_valid && - loss_estimate_for_increase < loss_increase_threshold()) { - // Increase bitrate by RTT-adaptive ratio. - DataRate new_increased_bitrate = - min_bitrate * GetIncreaseFactor(config_, last_round_trip_time) + - config_.increase_offset; - // The bitrate that would make the loss "just high enough". - const DataRate new_increased_bitrate_cap = BitrateFromLoss( - loss_estimate_for_increase, config_.loss_bandwidth_balance_increase, - config_.loss_bandwidth_balance_exponent); - new_increased_bitrate = - std::min(new_increased_bitrate, new_increased_bitrate_cap); - loss_based_bitrate_ = std::max(new_increased_bitrate, loss_based_bitrate_); - } else if (loss_estimate_for_decrease > loss_decrease_threshold() && - allow_decrease) { - // The bitrate that would make the loss "just acceptable". - const DataRate new_decreased_bitrate_floor = BitrateFromLoss( - loss_estimate_for_decrease, config_.loss_bandwidth_balance_decrease, - config_.loss_bandwidth_balance_exponent); - DataRate new_decreased_bitrate = - std::max(decreased_bitrate(), new_decreased_bitrate_floor); - if (new_decreased_bitrate < loss_based_bitrate_) { - time_last_decrease_ = at_time; - has_decreased_since_last_loss_report_ = true; - loss_based_bitrate_ = new_decreased_bitrate; - } - } - return loss_based_bitrate_; -} - -void LossBasedBandwidthEstimation::Initialize(DataRate bitrate) { - loss_based_bitrate_ = bitrate; - average_loss_ = 0; - average_loss_max_ = 0; -} - -double LossBasedBandwidthEstimation::loss_reset_threshold() const { - return LossFromBitrate(loss_based_bitrate_, - config_.loss_bandwidth_balance_reset, - config_.loss_bandwidth_balance_exponent); -} - -double LossBasedBandwidthEstimation::loss_increase_threshold() const { - return LossFromBitrate(loss_based_bitrate_, - config_.loss_bandwidth_balance_increase, - config_.loss_bandwidth_balance_exponent); -} - -double LossBasedBandwidthEstimation::loss_decrease_threshold() const { - return LossFromBitrate(loss_based_bitrate_, - config_.loss_bandwidth_balance_decrease, - config_.loss_bandwidth_balance_exponent); -} - -DataRate LossBasedBandwidthEstimation::decreased_bitrate() const { - return config_.decrease_factor * acknowledged_bitrate_max_; -} -} // namespace webrtc diff --git a/modules/congestion_controller/goog_cc/loss_based_bandwidth_estimation.h b/modules/congestion_controller/goog_cc/loss_based_bandwidth_estimation.h deleted file mode 100644 index 9f69caba89..0000000000 --- a/modules/congestion_controller/goog_cc/loss_based_bandwidth_estimation.h +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (c) 2018 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 MODULES_CONGESTION_CONTROLLER_GOOG_CC_LOSS_BASED_BANDWIDTH_ESTIMATION_H_ -#define MODULES_CONGESTION_CONTROLLER_GOOG_CC_LOSS_BASED_BANDWIDTH_ESTIMATION_H_ - -#include - -#include "api/field_trials_view.h" -#include "api/transport/network_types.h" -#include "api/units/data_rate.h" -#include "api/units/time_delta.h" -#include "api/units/timestamp.h" -#include "rtc_base/experiments/field_trial_parser.h" - -namespace webrtc { - -struct LossBasedControlConfig { - explicit LossBasedControlConfig(const FieldTrialsView* key_value_config); - LossBasedControlConfig(const LossBasedControlConfig&); - LossBasedControlConfig& operator=(const LossBasedControlConfig&) = default; - ~LossBasedControlConfig(); - bool enabled; - FieldTrialParameter min_increase_factor; - FieldTrialParameter max_increase_factor; - FieldTrialParameter increase_low_rtt; - FieldTrialParameter increase_high_rtt; - FieldTrialParameter decrease_factor; - FieldTrialParameter loss_window; - FieldTrialParameter loss_max_window; - FieldTrialParameter acknowledged_rate_max_window; - FieldTrialParameter increase_offset; - FieldTrialParameter loss_bandwidth_balance_increase; - FieldTrialParameter loss_bandwidth_balance_decrease; - FieldTrialParameter loss_bandwidth_balance_reset; - FieldTrialParameter loss_bandwidth_balance_exponent; - FieldTrialParameter allow_resets; - FieldTrialParameter decrease_interval; - FieldTrialParameter loss_report_timeout; -}; - -// Estimates an upper BWE limit based on loss. -// It requires knowledge about lost packets and acknowledged bitrate. -// Ie, this class require transport feedback. -class LossBasedBandwidthEstimation { - public: - explicit LossBasedBandwidthEstimation( - const FieldTrialsView* key_value_config); - // Returns the new estimate. - DataRate Update(Timestamp at_time, - DataRate min_bitrate, - DataRate wanted_bitrate, - TimeDelta last_round_trip_time); - void UpdateAcknowledgedBitrate(DataRate acknowledged_bitrate, - Timestamp at_time); - void Initialize(DataRate bitrate); - bool Enabled() const { return config_.enabled; } - // Returns true if LossBasedBandwidthEstimation is enabled and have - // received loss statistics. Ie, this class require transport feedback. - bool InUse() const { - return Enabled() && last_loss_packet_report_.IsFinite(); - } - void UpdateLossStatistics(const std::vector& packet_results, - Timestamp at_time); - DataRate GetEstimate() const { return loss_based_bitrate_; } - - private: - friend class GoogCcStatePrinter; - void Reset(DataRate bitrate); - double loss_increase_threshold() const; - double loss_decrease_threshold() const; - double loss_reset_threshold() const; - - DataRate decreased_bitrate() const; - - const LossBasedControlConfig config_; - double average_loss_; - double average_loss_max_; - DataRate loss_based_bitrate_; - DataRate acknowledged_bitrate_max_; - Timestamp acknowledged_bitrate_last_update_; - Timestamp time_last_decrease_; - bool has_decreased_since_last_loss_report_; - Timestamp last_loss_packet_report_; - double last_loss_ratio_; -}; - -} // namespace webrtc - -#endif // MODULES_CONGESTION_CONTROLLER_GOOG_CC_LOSS_BASED_BANDWIDTH_ESTIMATION_H_ diff --git a/modules/congestion_controller/goog_cc/loss_based_bwe_v2.cc b/modules/congestion_controller/goog_cc/loss_based_bwe_v2.cc index bd0a81b80c..75744b5cb2 100644 --- a/modules/congestion_controller/goog_cc/loss_based_bwe_v2.cc +++ b/modules/congestion_controller/goog_cc/loss_based_bwe_v2.cc @@ -350,7 +350,8 @@ void LossBasedBweV2::UpdateBandwidthEstimate( config_->hold_duration_factor > 0) { RTC_LOG(LS_INFO) << this << " " << "Switch to HOLD. Bounded BWE: " << bounded_bandwidth_estimate.kbps() - << ", duration: " << last_hold_info_.duration.ms(); + << ", duration: " << last_hold_info_.duration.ms() + << ", avg loss rate: " << average_reported_loss_ratio_; last_hold_info_ = { .timestamp = last_send_time_most_recent_observation_ + last_hold_info_.duration, diff --git a/modules/congestion_controller/goog_cc/loss_based_bwe_v2_test.cc b/modules/congestion_controller/goog_cc/loss_based_bwe_v2_test.cc index e308ff8730..a9c8506d33 100644 --- a/modules/congestion_controller/goog_cc/loss_based_bwe_v2_test.cc +++ b/modules/congestion_controller/goog_cc/loss_based_bwe_v2_test.cc @@ -14,21 +14,20 @@ #include #include +#include "api/field_trials.h" #include "api/transport/network_types.h" #include "api/units/data_rate.h" #include "api/units/data_size.h" #include "api/units/time_delta.h" #include "api/units/timestamp.h" #include "rtc_base/strings/string_builder.h" -#include "test/explicit_key_value_config.h" +#include "test/create_test_field_trials.h" #include "test/gtest.h" namespace webrtc { namespace { -using test::ExplicitKeyValueConfig; - constexpr TimeDelta kObservationDurationLowerBound = TimeDelta::Millis(250); constexpr TimeDelta kDelayedIncreaseWindow = TimeDelta::Millis(300); constexpr double kMaxIncreaseFactor = 1.5; @@ -36,7 +35,7 @@ constexpr int kPacketSize = 15'000; class LossBasedBweV2Test : public ::testing::TestWithParam { protected: - std::string Config(bool enabled, bool valid) { + FieldTrials Config(bool enabled, bool valid) { char buffer[1024]; SimpleStringBuilder config_string(buffer); @@ -74,10 +73,10 @@ class LossBasedBweV2Test : public ::testing::TestWithParam { config_string << "/"; - return config_string.str(); + return CreateTestFieldTrials(config_string.str()); } - std::string ShortObservationConfig(std::string custom_config) { + FieldTrials ShortObservationConfig(std::string custom_config) { char buffer[1024]; SimpleStringBuilder config_string(buffer); @@ -86,7 +85,7 @@ class LossBasedBweV2Test : public ::testing::TestWithParam { config_string << custom_config; config_string << "/"; - return config_string.str(); + return CreateTestFieldTrials(config_string.str()); } std::vector CreatePacketResultsWithReceivedPackets( @@ -173,37 +172,35 @@ class LossBasedBweV2Test : public ::testing::TestWithParam { }; TEST_F(LossBasedBweV2Test, EnabledWhenGivenValidConfigurationValues) { - ExplicitKeyValueConfig key_value_config( - Config(/*enabled=*/true, /*valid=*/true)); + FieldTrials key_value_config = Config(/*enabled=*/true, /*valid=*/true); LossBasedBweV2 loss_based_bandwidth_estimator(&key_value_config); EXPECT_TRUE(loss_based_bandwidth_estimator.IsEnabled()); } TEST_F(LossBasedBweV2Test, DisabledWhenGivenDisabledConfiguration) { - ExplicitKeyValueConfig key_value_config( - Config(/*enabled=*/false, /*valid=*/true)); + FieldTrials key_value_config = Config(/*enabled=*/false, /*valid=*/true); LossBasedBweV2 loss_based_bandwidth_estimator(&key_value_config); EXPECT_FALSE(loss_based_bandwidth_estimator.IsEnabled()); } TEST_F(LossBasedBweV2Test, DisabledWhenGivenNonValidConfigurationValues) { - ExplicitKeyValueConfig key_value_config( - Config(/*enabled=*/true, /*valid=*/false)); + FieldTrials key_value_config = Config(/*enabled=*/true, /*valid=*/false); LossBasedBweV2 loss_based_bandwidth_estimator(&key_value_config); EXPECT_FALSE(loss_based_bandwidth_estimator.IsEnabled()); } TEST_F(LossBasedBweV2Test, DisabledWhenGivenNonPositiveCandidateFactor) { - ExplicitKeyValueConfig key_value_config_negative_candidate_factor( - "WebRTC-Bwe-LossBasedBweV2/CandidateFactors:-1.3|1.1/"); + FieldTrials key_value_config_negative_candidate_factor = + CreateTestFieldTrials( + "WebRTC-Bwe-LossBasedBweV2/CandidateFactors:-1.3|1.1/"); LossBasedBweV2 loss_based_bandwidth_estimator_1( &key_value_config_negative_candidate_factor); EXPECT_FALSE(loss_based_bandwidth_estimator_1.IsEnabled()); - ExplicitKeyValueConfig key_value_config_zero_candidate_factor( + FieldTrials key_value_config_zero_candidate_factor = CreateTestFieldTrials( "WebRTC-Bwe-LossBasedBweV2/CandidateFactors:0.0|1.1/"); LossBasedBweV2 loss_based_bandwidth_estimator_2( &key_value_config_zero_candidate_factor); @@ -212,7 +209,7 @@ TEST_F(LossBasedBweV2Test, DisabledWhenGivenNonPositiveCandidateFactor) { TEST_F(LossBasedBweV2Test, DisabledWhenGivenConfigurationThatDoesNotAllowGeneratingCandidates) { - ExplicitKeyValueConfig key_value_config( + FieldTrials key_value_config = CreateTestFieldTrials( "WebRTC-Bwe-LossBasedBweV2/" "CandidateFactors:1.0,AckedRateCandidate:false," "DelayBasedCandidate:false/"); @@ -221,8 +218,7 @@ TEST_F(LossBasedBweV2Test, } TEST_F(LossBasedBweV2Test, ReturnsDelayBasedEstimateWhenDisabled) { - ExplicitKeyValueConfig key_value_config( - Config(/*enabled=*/false, /*valid=*/true)); + FieldTrials key_value_config = Config(/*enabled=*/false, /*valid=*/true); LossBasedBweV2 loss_based_bandwidth_estimator(&key_value_config); loss_based_bandwidth_estimator.UpdateBandwidthEstimate( /*packet_results=*/{}, @@ -236,13 +232,11 @@ TEST_F(LossBasedBweV2Test, ReturnsDelayBasedEstimateWhenDisabled) { TEST_F(LossBasedBweV2Test, ReturnsDelayBasedEstimateWhenWhenGivenNonValidConfigurationValues) { - ExplicitKeyValueConfig key_value_config( - Config(/*enabled=*/true, /*valid=*/false)); + FieldTrials key_value_config = Config(/*enabled=*/true, /*valid=*/false); LossBasedBweV2 loss_based_bandwidth_estimator(&key_value_config); loss_based_bandwidth_estimator.UpdateBandwidthEstimate( /*packet_results=*/{}, /*delay_based_estimate=*/DataRate::KilobitsPerSec(100), - /*in_alr=*/false); EXPECT_EQ( loss_based_bandwidth_estimator.GetLossBasedResult().bandwidth_estimate, @@ -255,15 +249,13 @@ TEST_F(LossBasedBweV2Test, CreatePacketResultsWithReceivedPackets( /*first_packet_timestamp=*/Timestamp::Zero()); - ExplicitKeyValueConfig key_value_config( - Config(/*enabled=*/true, /*valid=*/true)); + FieldTrials key_value_config = Config(/*enabled=*/true, /*valid=*/true); LossBasedBweV2 loss_based_bandwidth_estimator(&key_value_config); loss_based_bandwidth_estimator.SetBandwidthEstimate( DataRate::KilobitsPerSec(600)); loss_based_bandwidth_estimator.UpdateBandwidthEstimate( enough_feedback, /*delay_based_estimate=*/DataRate::PlusInfinity(), - /*in_alr=*/false); EXPECT_TRUE(loss_based_bandwidth_estimator.IsReady()); @@ -275,8 +267,7 @@ TEST_F(LossBasedBweV2Test, NoBandwidthEstimateGivenNoInitialization) { std::vector enough_feedback = CreatePacketResultsWithReceivedPackets( /*first_packet_timestamp=*/Timestamp::Zero()); - ExplicitKeyValueConfig key_value_config( - Config(/*enabled=*/true, /*valid=*/true)); + FieldTrials key_value_config = Config(/*enabled=*/true, /*valid=*/true); LossBasedBweV2 loss_based_bandwidth_estimator(&key_value_config); loss_based_bandwidth_estimator.UpdateBandwidthEstimate( @@ -303,8 +294,7 @@ TEST_F(LossBasedBweV2Test, NoBandwidthEstimateGivenNotEnoughFeedback) { not_enough_feedback[1].receive_time = Timestamp::Zero() + kObservationDurationLowerBound; - ExplicitKeyValueConfig key_value_config( - Config(/*enabled=*/true, /*valid=*/true)); + FieldTrials key_value_config = Config(/*enabled=*/true, /*valid=*/true); LossBasedBweV2 loss_based_bandwidth_estimator(&key_value_config); loss_based_bandwidth_estimator.SetBandwidthEstimate( @@ -334,8 +324,7 @@ TEST_F(LossBasedBweV2Test, /*first_packet_timestamp=*/Timestamp::Zero() + 2 * kObservationDurationLowerBound); - ExplicitKeyValueConfig key_value_config( - Config(/*enabled=*/true, /*valid=*/true)); + FieldTrials key_value_config = Config(/*enabled=*/true, /*valid=*/true); LossBasedBweV2 loss_based_bandwidth_estimator(&key_value_config); loss_based_bandwidth_estimator.SetBandwidthEstimate( @@ -376,8 +365,7 @@ TEST_F(LossBasedBweV2Test, /*first_packet_timestamp=*/Timestamp::Zero() + 2 * kObservationDurationLowerBound); - ExplicitKeyValueConfig key_value_config( - Config(/*enabled=*/true, /*valid=*/true)); + FieldTrials key_value_config = Config(/*enabled=*/true, /*valid=*/true); LossBasedBweV2 loss_based_bandwidth_estimator_1(&key_value_config); LossBasedBweV2 loss_based_bandwidth_estimator_2(&key_value_config); @@ -425,8 +413,7 @@ TEST_F(LossBasedBweV2Test, CreatePacketResultsWith100pLossRate( /*first_packet_timestamp=*/Timestamp::Zero()); - ExplicitKeyValueConfig key_value_config( - Config(/*enabled=*/true, /*valid=*/true)); + FieldTrials key_value_config = Config(/*enabled=*/true, /*valid=*/true); LossBasedBweV2 loss_based_bandwidth_estimator(&key_value_config); loss_based_bandwidth_estimator.SetBandwidthEstimate( @@ -454,8 +441,7 @@ TEST_F(LossBasedBweV2Test, CreatePacketResultsWithReceivedPackets( /*first_packet_timestamp=*/Timestamp::Zero() + 2 * kObservationDurationLowerBound); - ExplicitKeyValueConfig key_value_config( - Config(/*enabled=*/true, /*valid=*/true)); + FieldTrials key_value_config = Config(/*enabled=*/true, /*valid=*/true); LossBasedBweV2 loss_based_bandwidth_estimator(&key_value_config); loss_based_bandwidth_estimator.SetBandwidthEstimate( @@ -493,8 +479,7 @@ TEST_F(LossBasedBweV2Test, UseAckedBitrateForEmegencyBackOff) { /*first_packet_timestamp=*/Timestamp::Zero() + 2 * kObservationDurationLowerBound); - ExplicitKeyValueConfig key_value_config( - Config(/*enabled=*/true, /*valid=*/true)); + FieldTrials key_value_config = Config(/*enabled=*/true, /*valid=*/true); LossBasedBweV2 loss_based_bandwidth_estimator(&key_value_config); loss_based_bandwidth_estimator.SetBandwidthEstimate( @@ -522,8 +507,7 @@ TEST_F(LossBasedBweV2Test, NoBweChangeIfObservationDurationUnchanged) { std::vector enough_feedback_1 = CreatePacketResultsWithReceivedPackets( /*first_packet_timestamp=*/Timestamp::Zero()); - ExplicitKeyValueConfig key_value_config( - Config(/*enabled=*/true, /*valid=*/true)); + FieldTrials key_value_config = Config(/*enabled=*/true, /*valid=*/true); LossBasedBweV2 loss_based_bandwidth_estimator(&key_value_config); loss_based_bandwidth_estimator.SetBandwidthEstimate( DataRate::KilobitsPerSec(600)); @@ -559,8 +543,7 @@ TEST_F(LossBasedBweV2Test, CreatePacketResultsWithReceivedPackets( /*first_packet_timestamp=*/Timestamp::Zero() + kObservationDurationLowerBound - TimeDelta::Millis(1)); - ExplicitKeyValueConfig key_value_config( - Config(/*enabled=*/true, /*valid=*/true)); + FieldTrials key_value_config = Config(/*enabled=*/true, /*valid=*/true); LossBasedBweV2 loss_based_bandwidth_estimator(&key_value_config); loss_based_bandwidth_estimator.SetBandwidthEstimate( DataRate::KilobitsPerSec(600)); @@ -592,8 +575,7 @@ TEST_F(LossBasedBweV2Test, CreatePacketResultsWithReceivedPackets( /*first_packet_timestamp=*/Timestamp::Zero() + kObservationDurationLowerBound - TimeDelta::Millis(1)); - ExplicitKeyValueConfig key_value_config( - Config(/*enabled=*/true, /*valid=*/true)); + FieldTrials key_value_config = Config(/*enabled=*/true, /*valid=*/true); LossBasedBweV2 loss_based_bandwidth_estimator(&key_value_config); loss_based_bandwidth_estimator.SetBandwidthEstimate( DataRate::KilobitsPerSec(600)); @@ -621,8 +603,7 @@ TEST_F(LossBasedBweV2Test, CreatePacketResultsWithReceivedPackets( /*first_packet_timestamp=*/Timestamp::Zero() + 2 * kObservationDurationLowerBound); - ExplicitKeyValueConfig key_value_config( - Config(/*enabled=*/true, /*valid=*/true)); + FieldTrials key_value_config = Config(/*enabled=*/true, /*valid=*/true); LossBasedBweV2 loss_based_bandwidth_estimator(&key_value_config); DataRate delay_based_estimate = DataRate::KilobitsPerSec(5000); loss_based_bandwidth_estimator.SetBandwidthEstimate( @@ -643,7 +624,7 @@ TEST_F(LossBasedBweV2Test, } TEST_F(LossBasedBweV2Test, IncreaseByHoldFactorAfterLossBasedBweBacksOff) { - ExplicitKeyValueConfig key_value_config(ShortObservationConfig("")); + FieldTrials key_value_config = ShortObservationConfig(""); LossBasedBweV2 loss_based_bandwidth_estimator(&key_value_config); DataRate delay_based_estimate = DataRate::KilobitsPerSec(5000); @@ -684,11 +665,11 @@ TEST_F(LossBasedBweV2Test, IncreaseByHoldFactorAfterLossBasedBweBacksOff) { TEST_F(LossBasedBweV2Test, LossBasedStateIsDelayBasedEstimateAfterNetworkRecovering) { - ExplicitKeyValueConfig key_value_config(ShortObservationConfig( + FieldTrials key_value_config = ShortObservationConfig( "CandidateFactors:100|1|0.5," "InstantUpperBoundBwBalance:10000kbps," "MaxIncreaseFactor:100," - "NotIncreaseIfInherentLossLessThanAverageLoss:false")); + "NotIncreaseIfInherentLossLessThanAverageLoss:false"); LossBasedBweV2 loss_based_bandwidth_estimator(&key_value_config); DataRate delay_based_estimate = DataRate::KilobitsPerSec(600); DataRate acked_rate = DataRate::KilobitsPerSec(300); @@ -735,10 +716,10 @@ TEST_F(LossBasedBweV2Test, TEST_F(LossBasedBweV2Test, LossBasedStateIsNotDelayBasedEstimateIfDelayBasedEstimateInfinite) { - ExplicitKeyValueConfig key_value_config( - ShortObservationConfig("CandidateFactors:100|1|0.5," - "InstantUpperBoundBwBalance:10000kbps," - "MaxIncreaseFactor:100")); + FieldTrials key_value_config = ShortObservationConfig( + "CandidateFactors:100|1|0.5," + "InstantUpperBoundBwBalance:10000kbps," + "MaxIncreaseFactor:100"); LossBasedBweV2 loss_based_bandwidth_estimator(&key_value_config); loss_based_bandwidth_estimator.SetBandwidthEstimate( DataRate::KilobitsPerSec(600)); @@ -773,11 +754,11 @@ TEST_F(LossBasedBweV2Test, // a factor of acked bitrate. TEST_F(LossBasedBweV2Test, IncreaseByFactorOfAckedBitrateAfterLossBasedBweBacksOff) { - ExplicitKeyValueConfig key_value_config(ShortObservationConfig( + FieldTrials key_value_config = ShortObservationConfig( "LossThresholdOfHighBandwidthPreference:0.99," "BwRampupUpperBoundFactor:1.2," // Set InstantUpperBoundBwBalance high to disable InstantUpperBound cap. - "InstantUpperBoundBwBalance:10000kbps,")); + "InstantUpperBoundBwBalance:10000kbps,"); std::vector enough_feedback_1 = CreatePacketResultsWith100pLossRate( /*first_packet_timestamp=*/Timestamp::Zero()); @@ -832,11 +813,11 @@ TEST_F(LossBasedBweV2Test, // Ensure that the state can switch to kIncrease even when the bandwidth is // bounded by acked bitrate. TEST_F(LossBasedBweV2Test, EnsureIncreaseEvenIfAckedBitrateBound) { - ExplicitKeyValueConfig key_value_config(ShortObservationConfig( + FieldTrials key_value_config = ShortObservationConfig( "LossThresholdOfHighBandwidthPreference:0.99," "BwRampupUpperBoundFactor:1.2," // Set InstantUpperBoundBwBalance high to disable InstantUpperBound cap. - "InstantUpperBoundBwBalance:10000kbps,")); + "InstantUpperBoundBwBalance:10000kbps,"); std::vector enough_feedback_1 = CreatePacketResultsWith100pLossRate( /*first_packet_timestamp=*/Timestamp::Zero()); @@ -891,8 +872,7 @@ TEST_F(LossBasedBweV2Test, CreatePacketResultsWithReceivedPackets( /*first_packet_timestamp=*/Timestamp::Zero() + kDelayedIncreaseWindow - TimeDelta::Millis(1)); - ExplicitKeyValueConfig key_value_config( - Config(/*enabled=*/true, /*valid=*/true)); + FieldTrials key_value_config = Config(/*enabled=*/true, /*valid=*/true); LossBasedBweV2 loss_based_bandwidth_estimator(&key_value_config); DataRate delay_based_estimate = DataRate::KilobitsPerSec(5000); @@ -939,8 +919,7 @@ TEST_F(LossBasedBweV2Test, KeepIncreasingEstimateAfterDelayedIncreaseWindow) { CreatePacketResultsWithReceivedPackets( /*first_packet_timestamp=*/Timestamp::Zero() + kDelayedIncreaseWindow + TimeDelta::Millis(1)); - ExplicitKeyValueConfig key_value_config( - Config(/*enabled=*/true, /*valid=*/true)); + FieldTrials key_value_config = Config(/*enabled=*/true, /*valid=*/true); LossBasedBweV2 loss_based_bandwidth_estimator(&key_value_config); DataRate delay_based_estimate = DataRate::KilobitsPerSec(5000); @@ -974,9 +953,9 @@ TEST_F(LossBasedBweV2Test, KeepIncreasingEstimateAfterDelayedIncreaseWindow) { } TEST_F(LossBasedBweV2Test, NotIncreaseIfInherentLossLessThanAverageLoss) { - ExplicitKeyValueConfig key_value_config(ShortObservationConfig( + FieldTrials key_value_config = ShortObservationConfig( "CandidateFactors:1.2," - "NotIncreaseIfInherentLossLessThanAverageLoss:true")); + "NotIncreaseIfInherentLossLessThanAverageLoss:true"); LossBasedBweV2 loss_based_bandwidth_estimator(&key_value_config); loss_based_bandwidth_estimator.SetBandwidthEstimate( @@ -1007,9 +986,9 @@ TEST_F(LossBasedBweV2Test, NotIncreaseIfInherentLossLessThanAverageLoss) { TEST_F(LossBasedBweV2Test, SelectHighBandwidthCandidateIfLossRateIsLessThanThreshold) { - ExplicitKeyValueConfig key_value_config(ShortObservationConfig( + FieldTrials key_value_config = ShortObservationConfig( "LossThresholdOfHighBandwidthPreference:0.20," - "NotIncreaseIfInherentLossLessThanAverageLoss:false")); + "NotIncreaseIfInherentLossLessThanAverageLoss:false"); LossBasedBweV2 loss_based_bandwidth_estimator(&key_value_config); DataRate delay_based_estimate = DataRate::KilobitsPerSec(5000); @@ -1042,8 +1021,8 @@ TEST_F(LossBasedBweV2Test, TEST_F(LossBasedBweV2Test, SelectLowBandwidthCandidateIfLossRateIsIsHigherThanThreshold) { - ExplicitKeyValueConfig key_value_config( - ShortObservationConfig("LossThresholdOfHighBandwidthPreference:0.05")); + FieldTrials key_value_config = + ShortObservationConfig("LossThresholdOfHighBandwidthPreference:0.05"); LossBasedBweV2 loss_based_bandwidth_estimator(&key_value_config); DataRate delay_based_estimate = DataRate::KilobitsPerSec(5000); @@ -1075,8 +1054,7 @@ TEST_F(LossBasedBweV2Test, } TEST_F(LossBasedBweV2Test, EstimateIsNotHigherThanMaxBitrate) { - ExplicitKeyValueConfig key_value_config( - Config(/*enabled=*/true, /*valid=*/true)); + FieldTrials key_value_config = Config(/*enabled=*/true, /*valid=*/true); LossBasedBweV2 loss_based_bandwidth_estimator(&key_value_config); loss_based_bandwidth_estimator.SetMinMaxBitrate( /*min_bitrate=*/DataRate::KilobitsPerSec(10), @@ -1097,8 +1075,8 @@ TEST_F(LossBasedBweV2Test, EstimateIsNotHigherThanMaxBitrate) { } TEST_F(LossBasedBweV2Test, NotBackOffToAckedRateInAlr) { - ExplicitKeyValueConfig key_value_config( - ShortObservationConfig("InstantUpperBoundBwBalance:100kbps")); + FieldTrials key_value_config = + ShortObservationConfig("InstantUpperBoundBwBalance:100kbps"); LossBasedBweV2 loss_based_bandwidth_estimator(&key_value_config); loss_based_bandwidth_estimator.SetMinMaxBitrate( /*min_bitrate=*/DataRate::KilobitsPerSec(10), @@ -1127,8 +1105,8 @@ TEST_F(LossBasedBweV2Test, NotBackOffToAckedRateInAlr) { } TEST_F(LossBasedBweV2Test, BackOffToAckedRateIfNotInAlr) { - ExplicitKeyValueConfig key_value_config( - ShortObservationConfig("InstantUpperBoundBwBalance:100kbps")); + FieldTrials key_value_config = + ShortObservationConfig("InstantUpperBoundBwBalance:100kbps"); LossBasedBweV2 loss_based_bandwidth_estimator(&key_value_config); loss_based_bandwidth_estimator.SetMinMaxBitrate( /*min_bitrate=*/DataRate::KilobitsPerSec(10), @@ -1154,8 +1132,7 @@ TEST_F(LossBasedBweV2Test, BackOffToAckedRateIfNotInAlr) { } TEST_F(LossBasedBweV2Test, NotReadyToUseInStartPhase) { - ExplicitKeyValueConfig key_value_config( - ShortObservationConfig("UseInStartPhase:true")); + FieldTrials key_value_config = ShortObservationConfig("UseInStartPhase:true"); LossBasedBweV2 loss_based_bandwidth_estimator(&key_value_config); // Make sure that the estimator is not ready to use in start phase because of // lacking TWCC feedback. @@ -1163,8 +1140,7 @@ TEST_F(LossBasedBweV2Test, NotReadyToUseInStartPhase) { } TEST_F(LossBasedBweV2Test, ReadyToUseInStartPhase) { - ExplicitKeyValueConfig key_value_config( - ShortObservationConfig("UseInStartPhase:true")); + FieldTrials key_value_config = ShortObservationConfig("UseInStartPhase:true"); LossBasedBweV2 loss_based_bandwidth_estimator(&key_value_config); std::vector enough_feedback = CreatePacketResultsWithReceivedPackets( @@ -1177,8 +1153,8 @@ TEST_F(LossBasedBweV2Test, ReadyToUseInStartPhase) { } TEST_F(LossBasedBweV2Test, BoundEstimateByAckedRate) { - ExplicitKeyValueConfig key_value_config( - ShortObservationConfig("LowerBoundByAckedRateFactor:1.0")); + FieldTrials key_value_config = + ShortObservationConfig("LowerBoundByAckedRateFactor:1.0"); LossBasedBweV2 loss_based_bandwidth_estimator(&key_value_config); loss_based_bandwidth_estimator.SetMinMaxBitrate( /*min_bitrate=*/DataRate::KilobitsPerSec(10), @@ -1202,8 +1178,8 @@ TEST_F(LossBasedBweV2Test, BoundEstimateByAckedRate) { } TEST_F(LossBasedBweV2Test, NotBoundEstimateByAckedRate) { - ExplicitKeyValueConfig key_value_config( - ShortObservationConfig("LowerBoundByAckedRateFactor:0.0")); + FieldTrials key_value_config = + ShortObservationConfig("LowerBoundByAckedRateFactor:0.0"); LossBasedBweV2 loss_based_bandwidth_estimator(&key_value_config); loss_based_bandwidth_estimator.SetMinMaxBitrate( /*min_bitrate=*/DataRate::KilobitsPerSec(10), @@ -1227,8 +1203,8 @@ TEST_F(LossBasedBweV2Test, NotBoundEstimateByAckedRate) { } TEST_F(LossBasedBweV2Test, HasDecreaseStateBecauseOfUpperBound) { - ExplicitKeyValueConfig key_value_config(ShortObservationConfig( - "CandidateFactors:1.0,InstantUpperBoundBwBalance:10kbps")); + FieldTrials key_value_config = ShortObservationConfig( + "CandidateFactors:1.0,InstantUpperBoundBwBalance:10kbps"); LossBasedBweV2 loss_based_bandwidth_estimator(&key_value_config); loss_based_bandwidth_estimator.SetMinMaxBitrate( /*min_bitrate=*/DataRate::KilobitsPerSec(10), @@ -1256,8 +1232,8 @@ TEST_F(LossBasedBweV2Test, HasDecreaseStateBecauseOfUpperBound) { } TEST_F(LossBasedBweV2Test, HasIncreaseStateBecauseOfLowerBound) { - ExplicitKeyValueConfig key_value_config(ShortObservationConfig( - "CandidateFactors:1.0,LowerBoundByAckedRateFactor:10.0")); + FieldTrials key_value_config = ShortObservationConfig( + "CandidateFactors:1.0,LowerBoundByAckedRateFactor:10.0"); LossBasedBweV2 loss_based_bandwidth_estimator(&key_value_config); loss_based_bandwidth_estimator.SetMinMaxBitrate( /*min_bitrate=*/DataRate::KilobitsPerSec(10), @@ -1302,8 +1278,8 @@ TEST_F(LossBasedBweV2Test, HasIncreaseStateBecauseOfLowerBound) { TEST_F(LossBasedBweV2Test, EstimateIncreaseSlowlyFromInstantUpperBoundInAlrIfFieldTrial) { - ExplicitKeyValueConfig key_value_config( - ShortObservationConfig("UpperBoundCandidateInAlr:true")); + FieldTrials key_value_config = + ShortObservationConfig("UpperBoundCandidateInAlr:true"); LossBasedBweV2 loss_based_bandwidth_estimator(&key_value_config); loss_based_bandwidth_estimator.SetBandwidthEstimate( DataRate::KilobitsPerSec(1000)); @@ -1333,7 +1309,7 @@ TEST_F(LossBasedBweV2Test, } TEST_F(LossBasedBweV2Test, HasDelayBasedStateIfLossBasedBweIsMax) { - ExplicitKeyValueConfig key_value_config(ShortObservationConfig("")); + FieldTrials key_value_config = ShortObservationConfig(""); LossBasedBweV2 loss_based_bandwidth_estimator(&key_value_config); loss_based_bandwidth_estimator.SetMinMaxBitrate( /*min_bitrate=*/DataRate::KilobitsPerSec(10), @@ -1379,8 +1355,8 @@ TEST_F(LossBasedBweV2Test, HasDelayBasedStateIfLossBasedBweIsMax) { } TEST_F(LossBasedBweV2Test, IncreaseUsingPaddingStateIfFieldTrial) { - ExplicitKeyValueConfig key_value_config( - ShortObservationConfig("PaddingDuration:1000ms")); + FieldTrials key_value_config = + ShortObservationConfig("PaddingDuration:1000ms"); LossBasedBweV2 loss_based_bandwidth_estimator(&key_value_config); loss_based_bandwidth_estimator.SetBandwidthEstimate( DataRate::KilobitsPerSec(2500)); @@ -1407,8 +1383,8 @@ TEST_F(LossBasedBweV2Test, IncreaseUsingPaddingStateIfFieldTrial) { } TEST_F(LossBasedBweV2Test, BestCandidateResetsToUpperBoundInFieldTrial) { - ExplicitKeyValueConfig key_value_config( - ShortObservationConfig("PaddingDuration:1000ms,BoundBestCandidate:true")); + FieldTrials key_value_config = + ShortObservationConfig("PaddingDuration:1000ms,BoundBestCandidate:true"); LossBasedBweV2 loss_based_bandwidth_estimator(&key_value_config); loss_based_bandwidth_estimator.SetBandwidthEstimate( DataRate::KilobitsPerSec(2500)); @@ -1443,10 +1419,10 @@ TEST_F(LossBasedBweV2Test, BestCandidateResetsToUpperBoundInFieldTrial) { } TEST_F(LossBasedBweV2Test, DecreaseToAckedCandidateIfPaddingInAlr) { - ExplicitKeyValueConfig key_value_config(ShortObservationConfig( + FieldTrials key_value_config = ShortObservationConfig( "PaddingDuration:1000ms," // Set InstantUpperBoundBwBalance high to disable InstantUpperBound cap. - "InstantUpperBoundBwBalance:10000kbps")); + "InstantUpperBoundBwBalance:10000kbps"); LossBasedBweV2 loss_based_bandwidth_estimator(&key_value_config); loss_based_bandwidth_estimator.SetBandwidthEstimate( DataRate::KilobitsPerSec(1000)); @@ -1493,8 +1469,8 @@ TEST_F(LossBasedBweV2Test, DecreaseToAckedCandidateIfPaddingInAlr) { } TEST_F(LossBasedBweV2Test, DecreaseAfterPadding) { - ExplicitKeyValueConfig key_value_config(ShortObservationConfig( - "PaddingDuration:1000ms,BwRampupUpperBoundFactor:2.0")); + FieldTrials key_value_config = ShortObservationConfig( + "PaddingDuration:1000ms,BwRampupUpperBoundFactor:2.0"); LossBasedBweV2 loss_based_bandwidth_estimator(&key_value_config); loss_based_bandwidth_estimator.SetBandwidthEstimate( DataRate::KilobitsPerSec(2500)); @@ -1549,8 +1525,8 @@ TEST_F(LossBasedBweV2Test, DecreaseAfterPadding) { TEST_F(LossBasedBweV2Test, HoldRateNotLowerThanAckedRate) { - ExplicitKeyValueConfig key_value_config(ShortObservationConfig( - "HoldDurationFactor:10,LowerBoundByAckedRateFactor:1.0")); + FieldTrials key_value_config = ShortObservationConfig( + "HoldDurationFactor:10,LowerBoundByAckedRateFactor:1.0"); LossBasedBweV2 loss_based_bandwidth_estimator(&key_value_config); loss_based_bandwidth_estimator.SetBandwidthEstimate( DataRate::KilobitsPerSec(2500)); @@ -1579,8 +1555,8 @@ TEST_F(LossBasedBweV2Test, HoldRateNotLowerThanAckedRate) { } TEST_F(LossBasedBweV2Test, EstimateNotLowerThanAckedRate) { - ExplicitKeyValueConfig key_value_config( - ShortObservationConfig("LowerBoundByAckedRateFactor:1.0")); + FieldTrials key_value_config = + ShortObservationConfig("LowerBoundByAckedRateFactor:1.0"); LossBasedBweV2 loss_based_bandwidth_estimator(&key_value_config); loss_based_bandwidth_estimator.SetBandwidthEstimate( DataRate::KilobitsPerSec(2500)); @@ -1625,7 +1601,7 @@ TEST_F(LossBasedBweV2Test, EstimateNotLowerThanAckedRate) { } TEST_F(LossBasedBweV2Test, EndHoldDurationIfDelayBasedEstimateWorks) { - ExplicitKeyValueConfig key_value_config(ShortObservationConfig("")); + FieldTrials key_value_config = ShortObservationConfig(""); LossBasedBweV2 loss_based_bandwidth_estimator(&key_value_config); loss_based_bandwidth_estimator.SetBandwidthEstimate( DataRate::KilobitsPerSec(2500)); @@ -1659,8 +1635,7 @@ TEST_F(LossBasedBweV2Test, EndHoldDurationIfDelayBasedEstimateWorks) { } TEST_F(LossBasedBweV2Test, UseByteLossRate) { - ExplicitKeyValueConfig key_value_config( - ShortObservationConfig("UseByteLossRate:true")); + FieldTrials key_value_config = ShortObservationConfig("UseByteLossRate:true"); LossBasedBweV2 loss_based_bandwidth_estimator(&key_value_config); loss_based_bandwidth_estimator.SetBandwidthEstimate( DataRate::KilobitsPerSec(500)); @@ -1680,7 +1655,7 @@ TEST_F(LossBasedBweV2Test, UseByteLossRate) { } TEST_F(LossBasedBweV2Test, UseByteLossRateIgnoreLossSpike) { - ExplicitKeyValueConfig key_value_config( + FieldTrials key_value_config = CreateTestFieldTrials( "WebRTC-Bwe-LossBasedBweV2/" "UseByteLossRate:true,ObservationWindowSize:5/"); LossBasedBweV2 loss_based_bandwidth_estimator(&key_value_config); @@ -1729,7 +1704,7 @@ TEST_F(LossBasedBweV2Test, UseByteLossRateIgnoreLossSpike) { } TEST_F(LossBasedBweV2Test, UseByteLossRateDoesNotIgnoreLossSpikeOnSendBurst) { - ExplicitKeyValueConfig key_value_config( + FieldTrials key_value_config = CreateTestFieldTrials( "WebRTC-Bwe-LossBasedBweV2/" "UseByteLossRate:true,ObservationWindowSize:5/"); LossBasedBweV2 loss_based_bandwidth_estimator(&key_value_config); @@ -1764,7 +1739,7 @@ TEST_F(LossBasedBweV2Test, UseByteLossRateDoesNotIgnoreLossSpikeOnSendBurst) { TEST_F(LossBasedBweV2Test, EstimateDoesNotBackOffDueToPacketReorderingBetweenFeedback) { - ExplicitKeyValueConfig key_value_config(ShortObservationConfig("")); + FieldTrials key_value_config = ShortObservationConfig(""); LossBasedBweV2 loss_based_bandwidth_estimator(&key_value_config); const DataRate kStartBitrate = DataRate::KilobitsPerSec(2500); loss_based_bandwidth_estimator.SetBandwidthEstimate(kStartBitrate); diff --git a/modules/congestion_controller/goog_cc/probe_controller.h b/modules/congestion_controller/goog_cc/probe_controller.h index 9c9c39ecad..08938f8b5d 100644 --- a/modules/congestion_controller/goog_cc/probe_controller.h +++ b/modules/congestion_controller/goog_cc/probe_controller.h @@ -152,7 +152,7 @@ class ProbeController { ABSL_MUST_USE_RESULT std::vector RequestProbe( Timestamp at_time); - void SetNetworkStateEstimate(webrtc::NetworkStateEstimate estimate); + void SetNetworkStateEstimate(NetworkStateEstimate estimate); // Resets the ProbeController to a state equivalent to as if it was just // created EXCEPT for configuration settings like @@ -195,7 +195,7 @@ class ProbeController { DataRate min_bitrate_to_probe_further_ = DataRate::PlusInfinity(); Timestamp time_last_probing_initiated_ = Timestamp::MinusInfinity(); DataRate estimated_bitrate_ = DataRate::Zero(); - std::optional network_estimate_; + std::optional network_estimate_; DataRate start_bitrate_ = DataRate::Zero(); DataRate max_bitrate_ = DataRate::PlusInfinity(); Timestamp last_bwe_drop_probing_time_ = Timestamp::Zero(); diff --git a/modules/congestion_controller/goog_cc/probe_controller_unittest.cc b/modules/congestion_controller/goog_cc/probe_controller_unittest.cc index 39712ad4f6..7b6267dd7f 100644 --- a/modules/congestion_controller/goog_cc/probe_controller_unittest.cc +++ b/modules/congestion_controller/goog_cc/probe_controller_unittest.cc @@ -14,13 +14,14 @@ #include #include "absl/strings/string_view.h" +#include "api/field_trials.h" #include "api/transport/network_types.h" #include "api/units/data_rate.h" #include "api/units/time_delta.h" #include "api/units/timestamp.h" #include "logging/rtc_event_log/mock/mock_rtc_event_log.h" #include "system_wrappers/include/clock.h" -#include "test/explicit_key_value_config.h" +#include "test/create_test_field_trials.h" #include "test/gmock.h" #include "test/gtest.h" @@ -49,7 +50,8 @@ constexpr TimeDelta kBitrateDropTimeout = TimeDelta::Seconds(5); class ProbeControllerFixture { public: explicit ProbeControllerFixture(absl::string_view field_trials = "") - : field_trial_config_(field_trials), clock_(100000000L) {} + : field_trial_config_(CreateTestFieldTrials(field_trials)), + clock_(100000000L) {} std::unique_ptr CreateController() { return std::make_unique(&field_trial_config_, @@ -59,7 +61,7 @@ class ProbeControllerFixture { Timestamp CurrentTime() { return clock_.CurrentTime(); } void AdvanceTime(TimeDelta delta) { clock_.AdvanceTime(delta); } - ExplicitKeyValueConfig field_trial_config_; + FieldTrials field_trial_config_; SimulatedClock clock_; NiceMock mock_rtc_event_log; }; diff --git a/modules/congestion_controller/goog_cc/robust_throughput_estimator_unittest.cc b/modules/congestion_controller/goog_cc/robust_throughput_estimator_unittest.cc index ef58263678..6d5a7420c0 100644 --- a/modules/congestion_controller/goog_cc/robust_throughput_estimator_unittest.cc +++ b/modules/congestion_controller/goog_cc/robust_throughput_estimator_unittest.cc @@ -17,20 +17,21 @@ #include #include "absl/strings/string_view.h" +#include "api/field_trials.h" #include "api/transport/network_types.h" #include "api/units/data_rate.h" #include "api/units/data_size.h" #include "api/units/time_delta.h" #include "api/units/timestamp.h" #include "modules/congestion_controller/goog_cc/acknowledged_bitrate_estimator_interface.h" -#include "test/explicit_key_value_config.h" +#include "test/create_test_field_trials.h" #include "test/gtest.h" namespace webrtc { RobustThroughputEstimatorSettings CreateRobustThroughputEstimatorSettings( absl::string_view field_trial_string) { - test::ExplicitKeyValueConfig trials(field_trial_string); + FieldTrials trials = CreateTestFieldTrials(field_trial_string); RobustThroughputEstimatorSettings settings(&trials); return settings; } diff --git a/modules/congestion_controller/goog_cc/send_side_bandwidth_estimation.cc b/modules/congestion_controller/goog_cc/send_side_bandwidth_estimation.cc index c42e0152a7..d599958272 100644 --- a/modules/congestion_controller/goog_cc/send_side_bandwidth_estimation.cc +++ b/modules/congestion_controller/goog_cc/send_side_bandwidth_estimation.cc @@ -152,7 +152,7 @@ DataRate LinkCapacityTracker::estimate() const { return DataRate::BitsPerSec(capacity_estimate_bps_); } -RttBasedBackoff::RttBasedBackoff(const FieldTrialsView* key_value_config) +RttBasedBackoff::RttBasedBackoff(const FieldTrialsView& key_value_config) : disabled_("Disabled"), configured_limit_("limit", TimeDelta::Seconds(3)), drop_fraction_("fraction", 0.8), @@ -166,7 +166,7 @@ RttBasedBackoff::RttBasedBackoff(const FieldTrialsView* key_value_config) last_packet_sent_(Timestamp::MinusInfinity()) { ParseFieldTrial({&disabled_, &configured_limit_, &drop_fraction_, &drop_interval_, &bandwidth_floor_}, - key_value_config->Lookup("WebRTC-Bwe-MaxRttLimit")); + key_value_config.Lookup("WebRTC-Bwe-MaxRttLimit")); if (!disabled_) { rtt_limit_ = configured_limit_.Get(); } @@ -195,7 +195,7 @@ SendSideBandwidthEstimation::SendSideBandwidthEstimation( const FieldTrialsView* key_value_config, RtcEventLog* event_log) : key_value_config_(key_value_config), - rtt_backoff_(key_value_config), + rtt_backoff_(*key_value_config), lost_packets_since_last_loss_update_(0), expected_packets_since_last_loss_update_(0), current_target_(DataRate::Zero()), @@ -223,7 +223,6 @@ SendSideBandwidthEstimation::SendSideBandwidthEstimation( low_loss_threshold_(kDefaultLowLossThreshold), high_loss_threshold_(kDefaultHighLossThreshold), bitrate_threshold_(kDefaultBitrateThreshold), - loss_based_bandwidth_estimator_v1_(key_value_config), loss_based_bandwidth_estimator_v2_(new LossBasedBweV2(key_value_config)), loss_based_state_(LossBasedState::kDelayBasedEstimate), disable_receiver_limit_caps_only_("Disabled") { @@ -361,10 +360,6 @@ void SendSideBandwidthEstimation::SetAcknowledgedRate( if (!acknowledged_rate.has_value()) { return; } - if (LossBasedBandwidthEstimatorV1Enabled()) { - loss_based_bandwidth_estimator_v1_.UpdateAcknowledgedBitrate( - *acknowledged_rate, at_time); - } if (LossBasedBandwidthEstimatorV2Enabled()) { loss_based_bandwidth_estimator_v2_->SetAcknowledgedBitrate( *acknowledged_rate); @@ -376,10 +371,6 @@ void SendSideBandwidthEstimation::UpdateLossBasedEstimator( BandwidthUsage /* delay_detector_state */, std::optional /* probe_bitrate */, bool in_alr) { - if (LossBasedBandwidthEstimatorV1Enabled()) { - loss_based_bandwidth_estimator_v1_.UpdateLossStatistics( - report.packet_feedbacks, report.feedback_time); - } if (LossBasedBandwidthEstimatorV2Enabled()) { loss_based_bandwidth_estimator_v2_->UpdateBandwidthEstimate( report.packet_feedbacks, delay_based_limit_, in_alr); @@ -493,20 +484,12 @@ void SendSideBandwidthEstimation::UpdateEstimate(Timestamp at_time) { // receiver limit here. if (receiver_limit_.IsFinite()) new_bitrate = std::max(receiver_limit_, new_bitrate); - if (delay_based_limit_.IsFinite()) + if (delay_based_limit_.IsFinite()) { new_bitrate = std::max(delay_based_limit_, new_bitrate); - if (LossBasedBandwidthEstimatorV1Enabled()) { - loss_based_bandwidth_estimator_v1_.Initialize(new_bitrate); } - if (new_bitrate != current_target_) { min_bitrate_history_.clear(); - if (LossBasedBandwidthEstimatorV1Enabled()) { - min_bitrate_history_.push_back(std::make_pair(at_time, new_bitrate)); - } else { - min_bitrate_history_.push_back( - std::make_pair(at_time, current_target_)); - } + min_bitrate_history_.push_back(std::make_pair(at_time, current_target_)); UpdateTargetBitrate(new_bitrate, at_time); return; } @@ -519,14 +502,6 @@ void SendSideBandwidthEstimation::UpdateEstimate(Timestamp at_time) { return; } - if (LossBasedBandwidthEstimatorV1ReadyForUse()) { - DataRate new_bitrate = loss_based_bandwidth_estimator_v1_.Update( - at_time, min_bitrate_history_.front().second, delay_based_limit_, - last_round_trip_time_); - UpdateTargetBitrate(new_bitrate, at_time); - return; - } - if (LossBasedBandwidthEstimatorV2ReadyForUse()) { LossBasedBweV2::Result result = loss_based_bandwidth_estimator_v2_->GetLossBasedResult(); @@ -673,17 +648,6 @@ void SendSideBandwidthEstimation::ApplyTargetLimits(Timestamp at_time) { UpdateTargetBitrate(current_target_, at_time); } -bool SendSideBandwidthEstimation::LossBasedBandwidthEstimatorV1Enabled() const { - return loss_based_bandwidth_estimator_v1_.Enabled() && - !LossBasedBandwidthEstimatorV2Enabled(); -} - -bool SendSideBandwidthEstimation::LossBasedBandwidthEstimatorV1ReadyForUse() - const { - return LossBasedBandwidthEstimatorV1Enabled() && - loss_based_bandwidth_estimator_v1_.InUse(); -} - bool SendSideBandwidthEstimation::LossBasedBandwidthEstimatorV2Enabled() const { return loss_based_bandwidth_estimator_v2_->IsEnabled(); } diff --git a/modules/congestion_controller/goog_cc/send_side_bandwidth_estimation.h b/modules/congestion_controller/goog_cc/send_side_bandwidth_estimation.h index 72123a7308..6c701e0fd0 100644 --- a/modules/congestion_controller/goog_cc/send_side_bandwidth_estimation.h +++ b/modules/congestion_controller/goog_cc/send_side_bandwidth_estimation.h @@ -27,7 +27,6 @@ #include "api/units/data_rate.h" #include "api/units/time_delta.h" #include "api/units/timestamp.h" -#include "modules/congestion_controller/goog_cc/loss_based_bandwidth_estimation.h" #include "modules/congestion_controller/goog_cc/loss_based_bwe_v2.h" #include "rtc_base/experiments/field_trial_parser.h" @@ -57,7 +56,7 @@ class LinkCapacityTracker { class RttBasedBackoff { public: - explicit RttBasedBackoff(const FieldTrialsView* key_value_config); + explicit RttBasedBackoff(const FieldTrialsView& key_value_config); ~RttBasedBackoff(); void UpdatePropagationRtt(Timestamp at_time, TimeDelta propagation_rtt); bool IsRttAboveLimit() const; @@ -161,10 +160,7 @@ class SendSideBandwidthEstimation { // should be cleaned up. void ApplyTargetLimits(Timestamp at_time); - bool LossBasedBandwidthEstimatorV1Enabled() const; bool LossBasedBandwidthEstimatorV2Enabled() const; - - bool LossBasedBandwidthEstimatorV1ReadyForUse() const; bool LossBasedBandwidthEstimatorV2ReadyForUse() const; const FieldTrialsView* key_value_config_; @@ -208,7 +204,6 @@ class SendSideBandwidthEstimation { float low_loss_threshold_; float high_loss_threshold_; DataRate bitrate_threshold_; - LossBasedBandwidthEstimation loss_based_bandwidth_estimator_v1_; std::unique_ptr loss_based_bandwidth_estimator_v2_; LossBasedState loss_based_state_; FieldTrialFlag disable_receiver_limit_caps_only_; diff --git a/modules/congestion_controller/goog_cc/send_side_bandwidth_estimation_unittest.cc b/modules/congestion_controller/goog_cc/send_side_bandwidth_estimation_unittest.cc index 866700b09a..5efd337710 100644 --- a/modules/congestion_controller/goog_cc/send_side_bandwidth_estimation_unittest.cc +++ b/modules/congestion_controller/goog_cc/send_side_bandwidth_estimation_unittest.cc @@ -12,13 +12,14 @@ #include +#include "api/field_trials.h" #include "api/rtc_event_log/rtc_event.h" #include "api/units/data_rate.h" #include "api/units/time_delta.h" #include "api/units/timestamp.h" #include "logging/rtc_event_log/events/rtc_event_bwe_update_loss_based.h" #include "logging/rtc_event_log/mock/mock_rtc_event_log.h" -#include "test/explicit_key_value_config.h" +#include "test/create_test_field_trials.h" #include "test/gmock.h" #include "test/gtest.h" @@ -42,7 +43,7 @@ MATCHER(LossBasedBweUpdateWithBitrateAndLossFraction, "") { void TestProbing(bool use_delay_based) { ::testing::NiceMock event_log; - test::ExplicitKeyValueConfig key_value_config(""); + FieldTrials key_value_config = CreateTestFieldTrials(); SendSideBandwidthEstimation bwe(&key_value_config, &event_log); int64_t now_ms = 0; bwe.SetMinMaxBitrate(DataRate::BitsPerSec(100000), @@ -95,7 +96,7 @@ TEST(SendSideBweTest, DoesntReapplyBitrateDecreaseWithoutFollowingRemb) { EXPECT_CALL(event_log, LogProxy(LossBasedBweUpdateWithBitrateAndLossFraction())) .Times(1); - test::ExplicitKeyValueConfig key_value_config(""); + FieldTrials key_value_config = CreateTestFieldTrials(); SendSideBandwidthEstimation bwe(&key_value_config, &event_log); static const int kMinBitrateBps = 100000; static const int kInitialBitrateBps = 1000000; @@ -146,7 +147,7 @@ TEST(SendSideBweTest, DoesntReapplyBitrateDecreaseWithoutFollowingRemb) { TEST(SendSideBweTest, SettingSendBitrateOverridesDelayBasedEstimate) { ::testing::NiceMock event_log; - test::ExplicitKeyValueConfig key_value_config(""); + FieldTrials key_value_config = CreateTestFieldTrials(); SendSideBandwidthEstimation bwe(&key_value_config, &event_log); static const int kMinBitrateBps = 10000; static const int kMaxBitrateBps = 10000000; @@ -173,21 +174,20 @@ TEST(SendSideBweTest, SettingSendBitrateOverridesDelayBasedEstimate) { } TEST(RttBasedBackoff, DefaultEnabled) { - test::ExplicitKeyValueConfig key_value_config(""); - RttBasedBackoff rtt_backoff(&key_value_config); + RttBasedBackoff rtt_backoff(CreateTestFieldTrials()); EXPECT_TRUE(rtt_backoff.rtt_limit_.IsFinite()); } TEST(RttBasedBackoff, CanBeDisabled) { - test::ExplicitKeyValueConfig key_value_config( - "WebRTC-Bwe-MaxRttLimit/Disabled/"); - RttBasedBackoff rtt_backoff(&key_value_config); + FieldTrials key_value_config = + CreateTestFieldTrials("WebRTC-Bwe-MaxRttLimit/Disabled/"); + RttBasedBackoff rtt_backoff(key_value_config); EXPECT_TRUE(rtt_backoff.rtt_limit_.IsPlusInfinity()); } TEST(SendSideBweTest, FractionLossIsNotOverflowed) { MockRtcEventLog event_log; - test::ExplicitKeyValueConfig key_value_config(""); + FieldTrials key_value_config = CreateTestFieldTrials(); SendSideBandwidthEstimation bwe(&key_value_config, &event_log); static const int kMinBitrateBps = 100000; static const int kInitialBitrateBps = 1000000; @@ -210,7 +210,7 @@ TEST(SendSideBweTest, FractionLossIsNotOverflowed) { TEST(SendSideBweTest, RttIsAboveLimitIfRttGreaterThanLimit) { ::testing::NiceMock event_log; - test::ExplicitKeyValueConfig key_value_config(""); + FieldTrials key_value_config = CreateTestFieldTrials(); SendSideBandwidthEstimation bwe(&key_value_config, &event_log); static const int kMinBitrateBps = 10000; static const int kMaxBitrateBps = 10000000; @@ -227,7 +227,7 @@ TEST(SendSideBweTest, RttIsAboveLimitIfRttGreaterThanLimit) { TEST(SendSideBweTest, RttIsBelowLimitIfRttLessThanLimit) { ::testing::NiceMock event_log; - test::ExplicitKeyValueConfig key_value_config(""); + FieldTrials key_value_config = CreateTestFieldTrials(); SendSideBandwidthEstimation bwe(&key_value_config, &event_log); static const int kMinBitrateBps = 10000; static const int kMaxBitrateBps = 10000000; diff --git a/modules/congestion_controller/goog_cc/test/goog_cc_printer.cc b/modules/congestion_controller/goog_cc/test/goog_cc_printer.cc index cef4bf4158..6e5bbb3b28 100644 --- a/modules/congestion_controller/goog_cc/test/goog_cc_printer.cc +++ b/modules/congestion_controller/goog_cc/test/goog_cc_printer.cc @@ -99,10 +99,6 @@ std::deque GoogCcStatePrinter::CreateLoggers() { auto acknowledged_rate = [this] { return controller_->acknowledged_bitrate_estimator_->bitrate(); }; - auto loss_cont = [&] { - return &controller_->bandwidth_estimation_ - ->loss_based_bandwidth_estimator_v1_; - }; std::deque loggers({ Log("time", [this] { return target_.at_time; }), Log("rtt", [this] { return target_.network_estimate.round_trip_time; }), @@ -127,17 +123,6 @@ std::deque GoogCcStatePrinter::CreateLoggers() { Log("est_pre_buffer", [this] { return est_.pre_link_buffer_delay; }), Log("est_post_buffer", [this] { return est_.post_link_buffer_delay; }), Log("est_propagation", [this] { return est_.propagation_delay; }), - Log("loss_ratio", [=] { return loss_cont()->last_loss_ratio_; }), - Log("loss_average", [=] { return loss_cont()->average_loss_; }), - Log("loss_average_max", [=] { return loss_cont()->average_loss_max_; }), - Log("loss_thres_inc", - [=] { return loss_cont()->loss_increase_threshold(); }), - Log("loss_thres_dec", - [=] { return loss_cont()->loss_decrease_threshold(); }), - Log("loss_dec_rate", [=] { return loss_cont()->decreased_bitrate(); }), - Log("loss_based_rate", [=] { return loss_cont()->loss_based_bitrate_; }), - Log("loss_ack_rate", - [=] { return loss_cont()->acknowledged_bitrate_max_; }), Log("data_window", [this] { return controller_->current_data_window_; }), Log("pushback_target", [this] { return controller_->last_pushback_target_rate_; }), diff --git a/modules/congestion_controller/goog_cc/trendline_estimator.cc b/modules/congestion_controller/goog_cc/trendline_estimator.cc index 2f8835a3cd..35ec1393c6 100644 --- a/modules/congestion_controller/goog_cc/trendline_estimator.cc +++ b/modules/congestion_controller/goog_cc/trendline_estimator.cc @@ -22,7 +22,6 @@ #include #include -#include "absl/strings/match.h" #include "api/field_trials_view.h" #include "api/network_state_predictor.h" #include "api/transport/bandwidth_usage.h" @@ -41,9 +40,9 @@ constexpr double kDefaultTrendlineThresholdGain = 4.0; const char kBweWindowSizeInPacketsExperiment[] = "WebRTC-BweWindowSizeInPackets"; -size_t ReadTrendlineFilterWindowSize(const FieldTrialsView* key_value_config) { +size_t ReadTrendlineFilterWindowSize(const FieldTrialsView& key_value_config) { std::string experiment_string = - key_value_config->Lookup(kBweWindowSizeInPacketsExperiment); + key_value_config.Lookup(kBweWindowSizeInPacketsExperiment); size_t window_size; int parsed_values = sscanf(experiment_string.c_str(), "Enabled-%zu", &window_size); @@ -121,13 +120,11 @@ constexpr int kDeltaCounterMax = 1000; constexpr char TrendlineEstimatorSettings::kKey[]; TrendlineEstimatorSettings::TrendlineEstimatorSettings( - const FieldTrialsView* key_value_config) { - if (absl::StartsWith( - key_value_config->Lookup(kBweWindowSizeInPacketsExperiment), - "Enabled")) { + const FieldTrialsView& key_value_config) { + if (key_value_config.IsEnabled(kBweWindowSizeInPacketsExperiment)) { window_size = ReadTrendlineFilterWindowSize(key_value_config); } - Parser()->Parse(key_value_config->Lookup(TrendlineEstimatorSettings::kKey)); + Parser()->Parse(key_value_config.Lookup(TrendlineEstimatorSettings::kKey)); if (window_size < 10 || 200 < window_size) { RTC_LOG(LS_WARNING) << "Window size must be between 10 and 200 packets"; window_size = kDefaultTrendlineWindowSize; @@ -166,7 +163,7 @@ std::unique_ptr TrendlineEstimatorSettings::Parser() { } TrendlineEstimator::TrendlineEstimator( - const FieldTrialsView* key_value_config, + const FieldTrialsView& key_value_config, NetworkStatePredictor* network_state_predictor) : settings_(key_value_config), smoothing_coef_(kDefaultTrendlineSmoothingCoeff), diff --git a/modules/congestion_controller/goog_cc/trendline_estimator.h b/modules/congestion_controller/goog_cc/trendline_estimator.h index 70336ea09f..5fc55acaca 100644 --- a/modules/congestion_controller/goog_cc/trendline_estimator.h +++ b/modules/congestion_controller/goog_cc/trendline_estimator.h @@ -29,7 +29,7 @@ struct TrendlineEstimatorSettings { static constexpr unsigned kDefaultTrendlineWindowSize = 20; TrendlineEstimatorSettings() = delete; - explicit TrendlineEstimatorSettings(const FieldTrialsView* key_value_config); + explicit TrendlineEstimatorSettings(const FieldTrialsView& key_value_config); // Sort the packets in the window. Should be redundant, // but then almost no cost. @@ -50,7 +50,7 @@ struct TrendlineEstimatorSettings { class TrendlineEstimator : public DelayIncreaseDetectorInterface { public: - TrendlineEstimator(const FieldTrialsView* key_value_config, + TrendlineEstimator(const FieldTrialsView& key_value_config, NetworkStatePredictor* network_state_predictor); ~TrendlineEstimator() override; diff --git a/modules/congestion_controller/goog_cc/trendline_estimator_unittest.cc b/modules/congestion_controller/goog_cc/trendline_estimator_unittest.cc index 2c52d7dd4b..3e4368ca26 100644 --- a/modules/congestion_controller/goog_cc/trendline_estimator_unittest.cc +++ b/modules/congestion_controller/goog_cc/trendline_estimator_unittest.cc @@ -16,8 +16,8 @@ #include #include "api/transport/bandwidth_usage.h" -#include "api/transport/field_trial_based_config.h" #include "rtc_base/checks.h" +#include "test/create_test_field_trials.h" #include "test/gtest.h" namespace webrtc { @@ -45,8 +45,7 @@ class TrendlineEstimatorTest : public testing::Test { : send_times(kPacketCount), recv_times(kPacketCount), packet_sizes(kPacketCount), - config(), - estimator(&config, nullptr), + estimator(CreateTestFieldTrials(), nullptr), count(1) { std::fill(packet_sizes.begin(), packet_sizes.end(), kPacketSizeBytes); } @@ -76,7 +75,6 @@ class TrendlineEstimatorTest : public testing::Test { std::vector send_times; std::vector recv_times; std::vector packet_sizes; - const FieldTrialBasedConfig config; TrendlineEstimator estimator; size_t count; }; diff --git a/modules/congestion_controller/receive_side_congestion_controller.cc b/modules/congestion_controller/receive_side_congestion_controller.cc index d6aec6639b..111c84a4b0 100644 --- a/modules/congestion_controller/receive_side_congestion_controller.cc +++ b/modules/congestion_controller/receive_side_congestion_controller.cc @@ -35,7 +35,7 @@ namespace webrtc { namespace { -static const uint32_t kTimeOffsetSwitchThreshold = 30; +const uint32_t kTimeOffsetSwitchThreshold = 30; } // namespace void ReceiveSideCongestionController::OnRttUpdate(int64_t avg_rtt_ms, diff --git a/modules/congestion_controller/receive_side_congestion_controller_unittest.cc b/modules/congestion_controller/receive_side_congestion_controller_unittest.cc index 0fb59147a6..405d3b7e67 100644 --- a/modules/congestion_controller/receive_side_congestion_controller_unittest.cc +++ b/modules/congestion_controller/receive_side_congestion_controller_unittest.cc @@ -15,6 +15,7 @@ #include #include "api/environment/environment_factory.h" +#include "api/field_trials.h" #include "api/media_types.h" #include "api/test/network_emulation/create_cross_traffic.h" #include "api/test/network_emulation/cross_traffic.h" @@ -30,7 +31,7 @@ #include "modules/rtp_rtcp/source/rtp_packet_received.h" #include "rtc_base/buffer.h" #include "system_wrappers/include/clock.h" -#include "test/explicit_key_value_config.h" +#include "test/create_test_field_trials.h" #include "test/gmock.h" #include "test/gtest.h" #include "test/scenario/scenario.h" @@ -104,7 +105,7 @@ void CheckRfc8888Feedback( } TEST(ReceiveSideCongestionControllerTest, SendsRfc8888FeedbackIfForced) { - test::ExplicitKeyValueConfig field_trials( + FieldTrials field_trials = CreateTestFieldTrials( "WebRTC-RFC8888CongestionControlFeedback/force_send:true/"); MockFunction>)> rtcp_sender; diff --git a/modules/congestion_controller/rtp/BUILD.gn b/modules/congestion_controller/rtp/BUILD.gn index f9e230ebb9..3f66157a8d 100644 --- a/modules/congestion_controller/rtp/BUILD.gn +++ b/modules/congestion_controller/rtp/BUILD.gn @@ -85,7 +85,6 @@ if (rtc_include_tests) { "../../../rtc_base:safe_conversions", "../../../rtc_base/network:sent_packet", "../../../system_wrappers", - "../../../test:field_trial", "../../../test:test_support", "../../pacing", "../../remote_bitrate_estimator", diff --git a/modules/congestion_controller/rtp/transport_feedback_demuxer_unittest.cc b/modules/congestion_controller/rtp/transport_feedback_demuxer_unittest.cc index f37f43817d..19850b3653 100644 --- a/modules/congestion_controller/rtp/transport_feedback_demuxer_unittest.cc +++ b/modules/congestion_controller/rtp/transport_feedback_demuxer_unittest.cc @@ -26,7 +26,7 @@ using ::testing::ElementsAre; using ::testing::Field; using PacketInfo = StreamFeedbackObserver::StreamPacketInfo; -static constexpr uint32_t kSsrc = 8492; +constexpr uint32_t kSsrc = 8492; class MockStreamFeedbackObserver : public StreamFeedbackObserver { public: diff --git a/modules/desktop_capture/BUILD.gn b/modules/desktop_capture/BUILD.gn index a49c24fe46..1ba95f7e81 100644 --- a/modules/desktop_capture/BUILD.gn +++ b/modules/desktop_capture/BUILD.gn @@ -38,6 +38,7 @@ rtc_library("primitives") { "../../api:scoped_refptr", "../../rtc_base:checks", "../../rtc_base:refcount", + "../../rtc_base:stringutils", "../../rtc_base/system:rtc_export", "//third_party/libyuv", ] @@ -103,6 +104,7 @@ if (rtc_include_tests) { ":desktop_capture", ":desktop_capture_mock", ":primitives", + "../../api:scoped_refptr", "../../rtc_base:checks", "../../rtc_base:logging", "../../rtc_base:random", @@ -154,14 +156,13 @@ if (rtc_include_tests) { ":desktop_capture", ":desktop_capture_mock", ":primitives", + "../../api:array_view", "../../rtc_base:checks", "../../rtc_base:logging", - "../../rtc_base:macromagic", "../../rtc_base:random", "../../rtc_base:task_queue_for_test", "../../rtc_base:threading", "../../rtc_base:timeutils", - "../../system_wrappers", "../../test:test_support", ] @@ -291,6 +292,7 @@ rtc_library("desktop_capture") { "delegated_source_list_controller.h", "desktop_and_cursor_composer.cc", "desktop_and_cursor_composer.h", + "desktop_capture_metadata.h", "desktop_capture_metrics_helper.cc", "desktop_capture_metrics_helper.h", "desktop_capture_options.cc", @@ -328,9 +330,6 @@ rtc_library("desktop_capture") { "window_finder.cc", "window_finder.h", ] - if (is_linux && !is_castos && rtc_use_pipewire) { - sources += [ "desktop_capture_metadata.h" ] - } if (is_mac) { sources += [ "mac/desktop_configuration.h", @@ -433,6 +432,7 @@ rtc_library("desktop_capture") { "../../api:scoped_refptr", "../../api:sequence_checker", "../../rtc_base:checks", + "../../rtc_base:cpu_info", "../../rtc_base:event_tracer", "../../rtc_base:logging", "../../rtc_base:macromagic", @@ -443,7 +443,6 @@ rtc_library("desktop_capture") { "../../rtc_base/system:arch", "../../rtc_base/system:no_unique_address", "../../rtc_base/system:rtc_export", - "../../system_wrappers", "../../system_wrappers:metrics", ] @@ -615,6 +614,7 @@ if (is_mac) { visibility = [ ":desktop_capture" ] sources = [ "delegated_source_list_controller.h", + "desktop_capture_metadata.h", "desktop_capture_options.h", "desktop_capturer.h", "full_screen_application_handler.h", diff --git a/modules/desktop_capture/blank_detector_desktop_capturer_wrapper.cc b/modules/desktop_capture/blank_detector_desktop_capturer_wrapper.cc index 8e56ffc3fd..7d74adf6f2 100644 --- a/modules/desktop_capture/blank_detector_desktop_capturer_wrapper.cc +++ b/modules/desktop_capture/blank_detector_desktop_capturer_wrapper.cc @@ -12,10 +12,16 @@ #include +#include #include +#include "modules/desktop_capture/desktop_capture_types.h" +#include "modules/desktop_capture/desktop_capturer.h" +#include "modules/desktop_capture/desktop_frame.h" #include "modules/desktop_capture/desktop_geometry.h" #include "modules/desktop_capture/desktop_region.h" +#include "modules/desktop_capture/rgba_color.h" +#include "modules/desktop_capture/shared_memory.h" #include "rtc_base/checks.h" #include "system_wrappers/include/metrics.h" diff --git a/modules/desktop_capture/blank_detector_desktop_capturer_wrapper.h b/modules/desktop_capture/blank_detector_desktop_capturer_wrapper.h index d10f9cf725..47eaa6891f 100644 --- a/modules/desktop_capture/blank_detector_desktop_capturer_wrapper.h +++ b/modules/desktop_capture/blank_detector_desktop_capturer_wrapper.h @@ -16,6 +16,7 @@ #include "modules/desktop_capture/desktop_capture_types.h" #include "modules/desktop_capture/desktop_capturer.h" #include "modules/desktop_capture/desktop_frame.h" +#include "modules/desktop_capture/desktop_geometry.h" #include "modules/desktop_capture/rgba_color.h" #include "modules/desktop_capture/shared_memory.h" diff --git a/modules/desktop_capture/blank_detector_desktop_capturer_wrapper_unittest.cc b/modules/desktop_capture/blank_detector_desktop_capturer_wrapper_unittest.cc index 25a81edd89..e2e5b9d7eb 100644 --- a/modules/desktop_capture/blank_detector_desktop_capturer_wrapper_unittest.cc +++ b/modules/desktop_capture/blank_detector_desktop_capturer_wrapper_unittest.cc @@ -19,6 +19,7 @@ #include "modules/desktop_capture/desktop_geometry.h" #include "modules/desktop_capture/desktop_region.h" #include "modules/desktop_capture/fake_desktop_capturer.h" +#include "modules/desktop_capture/rgba_color.h" #include "test/gtest.h" namespace webrtc { diff --git a/modules/desktop_capture/cropped_desktop_frame.cc b/modules/desktop_capture/cropped_desktop_frame.cc index 54488b7d62..9315ecde8f 100644 --- a/modules/desktop_capture/cropped_desktop_frame.cc +++ b/modules/desktop_capture/cropped_desktop_frame.cc @@ -13,6 +13,8 @@ #include #include +#include "modules/desktop_capture/desktop_frame.h" +#include "modules/desktop_capture/desktop_geometry.h" #include "modules/desktop_capture/desktop_region.h" #include "rtc_base/checks.h" diff --git a/modules/desktop_capture/cropped_desktop_frame_unittest.cc b/modules/desktop_capture/cropped_desktop_frame_unittest.cc index 9becf69636..78fa6d8b1d 100644 --- a/modules/desktop_capture/cropped_desktop_frame_unittest.cc +++ b/modules/desktop_capture/cropped_desktop_frame_unittest.cc @@ -10,10 +10,13 @@ #include "modules/desktop_capture/cropped_desktop_frame.h" +#include #include #include +#include #include "modules/desktop_capture/desktop_frame.h" +#include "modules/desktop_capture/desktop_geometry.h" #include "modules/desktop_capture/shared_desktop_frame.h" #include "test/gtest.h" diff --git a/modules/desktop_capture/cropping_window_capturer.cc b/modules/desktop_capture/cropping_window_capturer.cc index d1cc1c8313..b0aa492804 100644 --- a/modules/desktop_capture/cropping_window_capturer.cc +++ b/modules/desktop_capture/cropping_window_capturer.cc @@ -12,9 +12,16 @@ #include +#include #include #include "modules/desktop_capture/cropped_desktop_frame.h" +#include "modules/desktop_capture/desktop_capture_options.h" +#include "modules/desktop_capture/desktop_capture_types.h" +#include "modules/desktop_capture/desktop_capturer.h" +#include "modules/desktop_capture/desktop_frame.h" +#include "modules/desktop_capture/desktop_geometry.h" +#include "modules/desktop_capture/shared_memory.h" #include "rtc_base/logging.h" namespace webrtc { diff --git a/modules/desktop_capture/cropping_window_capturer_win.cc b/modules/desktop_capture/cropping_window_capturer_win.cc index 8376f1110a..8337714161 100644 --- a/modules/desktop_capture/cropping_window_capturer_win.cc +++ b/modules/desktop_capture/cropping_window_capturer_win.cc @@ -8,11 +8,22 @@ * be found in the AUTHORS file in the root of the source tree. */ +#include +#include +#include + +#include "api/scoped_refptr.h" #include "modules/desktop_capture/cropping_window_capturer.h" +#include "modules/desktop_capture/desktop_capture_options.h" +#include "modules/desktop_capture/desktop_capture_types.h" +#include "modules/desktop_capture/desktop_capturer.h" #include "modules/desktop_capture/desktop_capturer_differ_wrapper.h" +#include "modules/desktop_capture/desktop_geometry.h" +#include "modules/desktop_capture/full_screen_window_detector.h" #include "modules/desktop_capture/win/screen_capture_utils.h" #include "modules/desktop_capture/win/selected_window_context.h" #include "modules/desktop_capture/win/window_capture_utils.h" +#include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "rtc_base/trace_event.h" #include "rtc_base/win/windows_version.h" @@ -152,7 +163,7 @@ class CroppingWindowCapturerWin : public CroppingWindowCapturer { bool enumerate_current_process_windows_; - webrtc::scoped_refptr full_screen_window_detector_; + scoped_refptr full_screen_window_detector_; // Used to make sure that we only log the usage of fullscreen detection once. mutable bool fullscreen_usage_logged_ = false; @@ -176,7 +187,7 @@ void CroppingWindowCapturerWin::CaptureFrame() { ? GetWindowListFlags::kNone : GetWindowListFlags::kIgnoreCurrentProcessWindows; - if (!webrtc::GetWindowList(window_list_flags, &result)) + if (!GetWindowList(window_list_flags, &result)) return false; // Filter out windows not visible on current desktop @@ -199,7 +210,7 @@ void CroppingWindowCapturerWin::CaptureFrame() { } bool CroppingWindowCapturerWin::ShouldUseScreenCapturer() { - if (webrtc::rtc_win::GetVersion() < webrtc::rtc_win::Version::VERSION_WIN8 && + if (rtc_win::GetVersion() < rtc_win::Version::VERSION_WIN8 && window_capture_helper_.IsAeroEnabled()) { return false; } diff --git a/modules/desktop_capture/desktop_and_cursor_composer.cc b/modules/desktop_capture/desktop_and_cursor_composer.cc index 91aea58628..838b1c2fd2 100644 --- a/modules/desktop_capture/desktop_and_cursor_composer.cc +++ b/modules/desktop_capture/desktop_and_cursor_composer.cc @@ -10,16 +10,19 @@ #include "modules/desktop_capture/desktop_and_cursor_composer.h" -#include -#include - +#include +#include #include #include +#include "modules/desktop_capture/desktop_capture_metadata.h" +#include "modules/desktop_capture/desktop_capture_types.h" #include "modules/desktop_capture/desktop_capturer.h" #include "modules/desktop_capture/desktop_frame.h" +#include "modules/desktop_capture/desktop_geometry.h" #include "modules/desktop_capture/mouse_cursor.h" #include "modules/desktop_capture/mouse_cursor_monitor.h" +#include "modules/desktop_capture/shared_memory.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" diff --git a/modules/desktop_capture/desktop_and_cursor_composer.h b/modules/desktop_capture/desktop_and_cursor_composer.h index 28ea25c8c9..1429959fb6 100644 --- a/modules/desktop_capture/desktop_and_cursor_composer.h +++ b/modules/desktop_capture/desktop_and_cursor_composer.h @@ -11,10 +11,10 @@ #ifndef MODULES_DESKTOP_CAPTURE_DESKTOP_AND_CURSOR_COMPOSER_H_ #define MODULES_DESKTOP_CAPTURE_DESKTOP_AND_CURSOR_COMPOSER_H_ +#include #include -#if defined(WEBRTC_USE_GIO) + #include "modules/desktop_capture/desktop_capture_metadata.h" -#endif // defined(WEBRTC_USE_GIO) #include "modules/desktop_capture/desktop_capture_options.h" #include "modules/desktop_capture/desktop_capture_types.h" #include "modules/desktop_capture/desktop_capturer.h" diff --git a/modules/desktop_capture/desktop_and_cursor_composer_unittest.cc b/modules/desktop_capture/desktop_and_cursor_composer_unittest.cc index 45673722fe..913258f129 100644 --- a/modules/desktop_capture/desktop_and_cursor_composer_unittest.cc +++ b/modules/desktop_capture/desktop_and_cursor_composer_unittest.cc @@ -10,18 +10,20 @@ #include "modules/desktop_capture/desktop_and_cursor_composer.h" -#include -#include - +#include +#include +#include #include +#include #include -#include #include "modules/desktop_capture/desktop_capturer.h" #include "modules/desktop_capture/desktop_frame.h" +#include "modules/desktop_capture/desktop_geometry.h" +#include "modules/desktop_capture/desktop_region.h" #include "modules/desktop_capture/mouse_cursor.h" +#include "modules/desktop_capture/mouse_cursor_monitor.h" #include "modules/desktop_capture/shared_desktop_frame.h" -#include "rtc_base/arraysize.h" #include "test/gmock.h" #include "test/gtest.h" @@ -247,7 +249,7 @@ TEST_F(DesktopAndCursorComposerTest, CursorShouldBeIgnoredIfNoFrameCaptured) { {0, 0, 0, 0, false}, }; - for (size_t i = 0; i < arraysize(tests); i++) { + for (size_t i = 0; i < std::size(tests); i++) { SCOPED_TRACE(i); DesktopVector hotspot(tests[i].hotspot_x, tests[i].hotspot_y); @@ -285,8 +287,7 @@ TEST_F(DesktopAndCursorComposerTest, CursorShouldBeIgnoredIfFrameMayContainIt) { {150, 250, true}, {150, 250, false}, }; - - for (size_t i = 0; i < arraysize(tests); i++) { + for (size_t i = 0; i < std::size(tests); i++) { SCOPED_TRACE(i); std::unique_ptr frame(CreateTestFrame()); @@ -326,21 +327,17 @@ TEST_F(DesktopAndCursorComposerTest, frame->set_top_left(DesktopVector(kFrameXCoord, kFrameYCoord)); // The frame covers (100, 200) - (200, 300). - struct { - int x; - int y; - } tests[] = { + DesktopVector tests[] = { {0, 0}, {50, 50}, {50, 150}, {100, 150}, {50, 200}, {99, 200}, {100, 199}, {200, 300}, {200, 299}, {199, 300}, {-1, -1}, {-10000, -10000}, {10000, 10000}, }; - for (size_t i = 0; i < arraysize(tests); i++) { - SCOPED_TRACE(i); + for (const DesktopVector& abs_pos : tests) { + SCOPED_TRACE(abs_pos); fake_screen_->SetNextFrame(frame->Share()); // The CursorState is ignored when using absolute cursor position. - fake_cursor_->SetState(MouseCursorMonitor::OUTSIDE, - DesktopVector(tests[i].x, tests[i].y)); + fake_cursor_->SetState(MouseCursorMonitor::OUTSIDE, abs_pos); blender_.CaptureFrame(); VerifyFrame(*frame_, MouseCursorMonitor::OUTSIDE, DesktopVector(0, 0)); } @@ -352,20 +349,16 @@ TEST_F(DesktopAndCursorComposerTest, IsOccludedShouldBeConsidered) { frame->set_top_left(DesktopVector(kFrameXCoord, kFrameYCoord)); // The frame covers (100, 200) - (200, 300). - struct { - int x; - int y; - } tests[] = { + DesktopVector tests[] = { {100, 200}, {101, 200}, {100, 201}, {101, 201}, {150, 250}, {199, 299}, }; fake_screen_->set_is_occluded(true); - for (size_t i = 0; i < arraysize(tests); i++) { - SCOPED_TRACE(i); + for (const DesktopVector& abs_pos : tests) { + SCOPED_TRACE(abs_pos); fake_screen_->SetNextFrame(frame->Share()); // The CursorState is ignored when using absolute cursor position. - fake_cursor_->SetState(MouseCursorMonitor::OUTSIDE, - DesktopVector(tests[i].x, tests[i].y)); + fake_cursor_->SetState(MouseCursorMonitor::OUTSIDE, abs_pos); blender_.CaptureFrame(); VerifyFrame(*frame_, MouseCursorMonitor::OUTSIDE, DesktopVector()); } @@ -377,16 +370,12 @@ TEST_F(DesktopAndCursorComposerTest, CursorIncluded) { frame->set_top_left(DesktopVector(kFrameXCoord, kFrameYCoord)); // The frame covers (100, 200) - (200, 300). - struct { - int x; - int y; - } tests[] = { + DesktopVector tests[] = { {100, 200}, {101, 200}, {100, 201}, {101, 201}, {150, 250}, {199, 299}, }; - for (size_t i = 0; i < arraysize(tests); i++) { - SCOPED_TRACE(i); + for (const DesktopVector& abs_pos : tests) { + SCOPED_TRACE(abs_pos); - const DesktopVector abs_pos(tests[i].x, tests[i].y); const DesktopVector rel_pos(abs_pos.subtract(frame->top_left())); fake_screen_->SetNextFrame(frame->Share()); diff --git a/modules/desktop_capture/desktop_capture_metrics_helper.cc b/modules/desktop_capture/desktop_capture_metrics_helper.cc index 9f20b56c35..4cacd257e0 100644 --- a/modules/desktop_capture/desktop_capture_metrics_helper.cc +++ b/modules/desktop_capture/desktop_capture_metrics_helper.cc @@ -10,6 +10,8 @@ #include "modules/desktop_capture/desktop_capture_metrics_helper.h" +#include + #include "modules/desktop_capture/desktop_capture_types.h" #include "system_wrappers/include/metrics.h" diff --git a/modules/desktop_capture/desktop_capture_options.cc b/modules/desktop_capture/desktop_capture_options.cc index 8d28d2bacc..97070d02de 100644 --- a/modules/desktop_capture/desktop_capture_options.cc +++ b/modules/desktop_capture/desktop_capture_options.cc @@ -10,7 +10,8 @@ #include "modules/desktop_capture/desktop_capture_options.h" -#include "api/make_ref_counted.h" +#include "api/make_ref_counted.h" // IWYU pragma: keep +#include "modules/desktop_capture/linux/x11/shared_x_display.h" #if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS) #include "modules/desktop_capture/mac/full_screen_mac_application_handler.h" @@ -46,13 +47,13 @@ DesktopCaptureOptions DesktopCaptureOptions::CreateDefault() { #endif #if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS) result.set_configuration_monitor( - webrtc::make_ref_counted()); + make_ref_counted()); result.set_full_screen_window_detector( - webrtc::make_ref_counted( + make_ref_counted( CreateFullScreenMacApplicationHandler)); #elif defined(WEBRTC_WIN) result.set_full_screen_window_detector( - webrtc::make_ref_counted( + make_ref_counted( CreateFullScreenWinApplicationHandler)); #endif return result; diff --git a/modules/desktop_capture/desktop_capture_options.h b/modules/desktop_capture/desktop_capture_options.h index dca0c6386f..c62476f405 100644 --- a/modules/desktop_capture/desktop_capture_options.h +++ b/modules/desktop_capture/desktop_capture_options.h @@ -10,6 +10,8 @@ #ifndef MODULES_DESKTOP_CAPTURE_DESKTOP_CAPTURE_OPTIONS_H_ #define MODULES_DESKTOP_CAPTURE_DESKTOP_CAPTURE_OPTIONS_H_ +#include + #include "api/scoped_refptr.h" #include "rtc_base/system/rtc_export.h" @@ -57,14 +59,13 @@ class RTC_EXPORT DesktopCaptureOptions { // TODO(zijiehe): Remove both DesktopConfigurationMonitor and // FullScreenChromeWindowDetector out of DesktopCaptureOptions. It's not // reasonable for external consumers to set these two parameters. - const webrtc::scoped_refptr& - configuration_monitor() const { + const scoped_refptr& configuration_monitor() + const { return configuration_monitor_; } // If nullptr is set, ScreenCapturer won't work and WindowCapturer may return // inaccurate result from IsOccluded() function. - void set_configuration_monitor( - webrtc::scoped_refptr m) { + void set_configuration_monitor(scoped_refptr m) { configuration_monitor_ = m; } @@ -219,12 +220,10 @@ class RTC_EXPORT DesktopCaptureOptions { bool allow_pipewire() const { return allow_pipewire_; } void set_allow_pipewire(bool allow) { allow_pipewire_ = allow; } - const webrtc::scoped_refptr& screencast_stream() - const { + const scoped_refptr& screencast_stream() const { return screencast_stream_; } - void set_screencast_stream( - webrtc::scoped_refptr stream) { + void set_screencast_stream(scoped_refptr stream) { screencast_stream_ = stream; } @@ -250,10 +249,10 @@ class RTC_EXPORT DesktopCaptureOptions { // An instance of shared PipeWire ScreenCast stream we share between // BaseCapturerPipeWire and MouseCursorMonitorPipeWire as cursor information // is sent together with screen content. - webrtc::scoped_refptr screencast_stream_; + scoped_refptr screencast_stream_; #endif #if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS) - webrtc::scoped_refptr configuration_monitor_; + scoped_refptr configuration_monitor_; bool allow_iosurface_ = false; bool allow_sck_capturer_ = false; bool allow_sck_system_picker_ = false; diff --git a/modules/desktop_capture/desktop_capturer.cc b/modules/desktop_capture/desktop_capturer.cc index 94605f409c..ae9aba26ee 100644 --- a/modules/desktop_capture/desktop_capturer.cc +++ b/modules/desktop_capture/desktop_capturer.cc @@ -10,17 +10,23 @@ #include "modules/desktop_capture/desktop_capturer.h" -#include -#include - +#include #include +#include #include -#include "modules/desktop_capture/cropping_window_capturer.h" +#include "modules/desktop_capture/delegated_source_list_controller.h" #include "modules/desktop_capture/desktop_capture_options.h" +#include "modules/desktop_capture/desktop_capture_types.h" #include "modules/desktop_capture/desktop_capturer_differ_wrapper.h" +#include "modules/desktop_capture/desktop_geometry.h" +#include "modules/desktop_capture/shared_memory.h" #include "system_wrappers/include/metrics.h" +#if defined(WEBRTC_WIN) +#include "modules/desktop_capture/cropping_window_capturer.h" +#endif // defined(WEBRTC_WIN) + #if defined(RTC_ENABLE_WIN_WGC) #include "modules/desktop_capture/win/wgc_capturer_win.h" #include "rtc_base/win/windows_version.h" @@ -28,11 +34,11 @@ #if defined(WEBRTC_USE_PIPEWIRE) #include "modules/desktop_capture/linux/wayland/base_capturer_pipewire.h" -#endif +#endif // defined(WEBRTC_USE_PIPEWIRE) #if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS) #include "modules/desktop_capture/mac/screen_capturer_sck.h" -#endif +#endif // defined(WEBRTC_MAC) && !defined(WEBRTC_IOS) namespace webrtc { diff --git a/modules/desktop_capture/desktop_capturer.h b/modules/desktop_capture/desktop_capturer.h index bb0742a410..50d3e9206e 100644 --- a/modules/desktop_capture/desktop_capturer.h +++ b/modules/desktop_capture/desktop_capturer.h @@ -11,9 +11,8 @@ #ifndef MODULES_DESKTOP_CAPTURE_DESKTOP_CAPTURER_H_ #define MODULES_DESKTOP_CAPTURE_DESKTOP_CAPTURER_H_ -#include -#include - +#include +#include #include #include #include @@ -22,11 +21,10 @@ // TODO(alcooper): Update include usage in downstream consumers and then change // this to a forward declaration. #include "modules/desktop_capture/delegated_source_list_controller.h" -#if defined(WEBRTC_USE_GIO) #include "modules/desktop_capture/desktop_capture_metadata.h" -#endif // defined(WEBRTC_USE_GIO) #include "modules/desktop_capture/desktop_capture_types.h" #include "modules/desktop_capture/desktop_frame.h" +#include "modules/desktop_capture/desktop_geometry.h" #include "modules/desktop_capture/shared_memory.h" #include "rtc_base/system/rtc_export.h" diff --git a/modules/desktop_capture/desktop_capturer_differ_wrapper.cc b/modules/desktop_capture/desktop_capturer_differ_wrapper.cc index 6656fdda2f..613628e9cd 100644 --- a/modules/desktop_capture/desktop_capturer_differ_wrapper.cc +++ b/modules/desktop_capture/desktop_capturer_differ_wrapper.cc @@ -10,14 +10,20 @@ #include "modules/desktop_capture/desktop_capturer_differ_wrapper.h" -#include -#include - +#include +#include +#include #include +#include "modules/desktop_capture/desktop_capture_metadata.h" +#include "modules/desktop_capture/desktop_capture_types.h" +#include "modules/desktop_capture/desktop_capturer.h" +#include "modules/desktop_capture/desktop_frame.h" #include "modules/desktop_capture/desktop_geometry.h" #include "modules/desktop_capture/desktop_region.h" #include "modules/desktop_capture/differ_block.h" +#include "modules/desktop_capture/shared_desktop_frame.h" +#include "modules/desktop_capture/shared_memory.h" #include "rtc_base/checks.h" #include "rtc_base/time_utils.h" diff --git a/modules/desktop_capture/desktop_capturer_differ_wrapper.h b/modules/desktop_capture/desktop_capturer_differ_wrapper.h index 6ebb5d7bc3..9b68a4808f 100644 --- a/modules/desktop_capture/desktop_capturer_differ_wrapper.h +++ b/modules/desktop_capture/desktop_capturer_differ_wrapper.h @@ -12,9 +12,8 @@ #define MODULES_DESKTOP_CAPTURE_DESKTOP_CAPTURER_DIFFER_WRAPPER_H_ #include -#if defined(WEBRTC_USE_GIO) + #include "modules/desktop_capture/desktop_capture_metadata.h" -#endif // defined(WEBRTC_USE_GIO) #include "modules/desktop_capture/desktop_capture_types.h" #include "modules/desktop_capture/desktop_capturer.h" #include "modules/desktop_capture/desktop_frame.h" diff --git a/modules/desktop_capture/desktop_capturer_differ_wrapper_unittest.cc b/modules/desktop_capture/desktop_capturer_differ_wrapper_unittest.cc index dba6c3041f..297128736f 100644 --- a/modules/desktop_capture/desktop_capturer_differ_wrapper_unittest.cc +++ b/modules/desktop_capture/desktop_capturer_differ_wrapper_unittest.cc @@ -10,11 +10,15 @@ #include "modules/desktop_capture/desktop_capturer_differ_wrapper.h" +#include #include #include #include #include +#include "modules/desktop_capture/desktop_capturer.h" +#include "modules/desktop_capture/desktop_frame.h" +#include "modules/desktop_capture/desktop_frame_generator.h" #include "modules/desktop_capture/desktop_geometry.h" #include "modules/desktop_capture/desktop_region.h" #include "modules/desktop_capture/differ_block.h" @@ -22,7 +26,7 @@ #include "modules/desktop_capture/mock_desktop_capturer_callback.h" #include "rtc_base/random.h" #include "rtc_base/time_utils.h" -#include "system_wrappers/include/cpu_features_wrapper.h" +#include "test/gmock.h" #include "test/gtest.h" namespace webrtc { diff --git a/modules/desktop_capture/desktop_capturer_wrapper.cc b/modules/desktop_capture/desktop_capturer_wrapper.cc index 4bbdd6c94f..d2d0a2f8b0 100644 --- a/modules/desktop_capture/desktop_capturer_wrapper.cc +++ b/modules/desktop_capture/desktop_capturer_wrapper.cc @@ -10,8 +10,13 @@ #include "modules/desktop_capture/desktop_capturer_wrapper.h" +#include #include +#include "modules/desktop_capture/desktop_capture_types.h" +#include "modules/desktop_capture/desktop_capturer.h" +#include "modules/desktop_capture/desktop_geometry.h" +#include "modules/desktop_capture/shared_memory.h" #include "rtc_base/checks.h" namespace webrtc { diff --git a/modules/desktop_capture/desktop_frame.cc b/modules/desktop_capture/desktop_frame.cc index 00316e3fdd..8368f3c988 100644 --- a/modules/desktop_capture/desktop_frame.cc +++ b/modules/desktop_capture/desktop_frame.cc @@ -10,14 +10,16 @@ #include "modules/desktop_capture/desktop_frame.h" -#include - +#include #include +#include +#include #include #include #include "modules/desktop_capture/desktop_capture_types.h" #include "modules/desktop_capture/desktop_geometry.h" +#include "modules/desktop_capture/shared_memory.h" #include "rtc_base/checks.h" #include "third_party/libyuv/include/libyuv/planar_functions.h" diff --git a/modules/desktop_capture/desktop_frame_generator.cc b/modules/desktop_capture/desktop_frame_generator.cc index 7ec96c5126..8b54ab1781 100644 --- a/modules/desktop_capture/desktop_frame_generator.cc +++ b/modules/desktop_capture/desktop_frame_generator.cc @@ -10,12 +10,15 @@ #include "modules/desktop_capture/desktop_frame_generator.h" -#include -#include - +#include +#include #include +#include "modules/desktop_capture/desktop_frame.h" +#include "modules/desktop_capture/desktop_geometry.h" +#include "modules/desktop_capture/desktop_region.h" #include "modules/desktop_capture/rgba_color.h" +#include "modules/desktop_capture/shared_memory.h" #include "rtc_base/checks.h" #include "rtc_base/random.h" #include "rtc_base/time_utils.h" diff --git a/modules/desktop_capture/desktop_frame_rotation.cc b/modules/desktop_capture/desktop_frame_rotation.cc index f2745cf70b..59a9cca02f 100644 --- a/modules/desktop_capture/desktop_frame_rotation.cc +++ b/modules/desktop_capture/desktop_frame_rotation.cc @@ -10,7 +10,10 @@ #include "modules/desktop_capture/desktop_frame_rotation.h" +#include "modules/desktop_capture/desktop_frame.h" +#include "modules/desktop_capture/desktop_geometry.h" #include "rtc_base/checks.h" +#include "third_party/libyuv/include/libyuv/rotate.h" #include "third_party/libyuv/include/libyuv/rotate_argb.h" namespace webrtc { diff --git a/modules/desktop_capture/desktop_frame_rotation_unittest.cc b/modules/desktop_capture/desktop_frame_rotation_unittest.cc index 782ca63e61..4038fcbacc 100644 --- a/modules/desktop_capture/desktop_frame_rotation_unittest.cc +++ b/modules/desktop_capture/desktop_frame_rotation_unittest.cc @@ -10,9 +10,10 @@ #include "modules/desktop_capture/desktop_frame_rotation.h" -#include +#include #include "modules/desktop_capture/desktop_frame.h" +#include "modules/desktop_capture/desktop_geometry.h" #include "modules/desktop_capture/desktop_region.h" #include "modules/desktop_capture/test_utils.h" #include "test/gtest.h" diff --git a/modules/desktop_capture/desktop_frame_unittest.cc b/modules/desktop_capture/desktop_frame_unittest.cc index 77945f6be9..5ca766d4f5 100644 --- a/modules/desktop_capture/desktop_frame_unittest.cc +++ b/modules/desktop_capture/desktop_frame_unittest.cc @@ -10,11 +10,13 @@ #include "modules/desktop_capture/desktop_frame.h" +#include +#include #include +#include -#include "modules/desktop_capture/desktop_region.h" -#include "modules/desktop_capture/test_utils.h" -#include "rtc_base/arraysize.h" +#include "api/array_view.h" +#include "modules/desktop_capture/desktop_geometry.h" #include "test/gtest.h" namespace webrtc { @@ -75,10 +77,8 @@ void RunTest(const TestData& test) { } } -void RunTests(const TestData* tests, int num_tests) { - for (int i = 0; i < num_tests; i++) { - const TestData& test = tests[i]; - +void RunTests(ArrayView tests) { + for (const TestData& test : tests) { SCOPED_TRACE(test.description); RunTest(test); @@ -134,7 +134,7 @@ TEST(DesktopFrameTest, CopyIntersectingPixelsMatchingRects) { }; // clang-format on - RunTests(tests, arraysize(tests)); + RunTests(tests); } TEST(DesktopFrameTest, CopyIntersectingPixelsMatchingRectsScaled) { @@ -168,7 +168,7 @@ TEST(DesktopFrameTest, CopyIntersectingPixelsMatchingRectsScaled) { }; // clang-format on - RunTests(tests, arraysize(tests)); + RunTests(tests); } TEST(DesktopFrameTest, CopyIntersectingPixelsFullyContainedRects) { @@ -194,7 +194,7 @@ TEST(DesktopFrameTest, CopyIntersectingPixelsFullyContainedRects) { }; // clang-format on - RunTests(tests, arraysize(tests)); + RunTests(tests); } TEST(DesktopFrameTest, CopyIntersectingPixelsFullyContainedRectsScaled) { @@ -244,7 +244,7 @@ TEST(DesktopFrameTest, CopyIntersectingPixelsFullyContainedRectsScaled) { }; // clang-format on - RunTests(tests, arraysize(tests)); + RunTests(tests); } TEST(DesktopFrameTest, CopyIntersectingPixelsPartiallyContainedRects) { @@ -276,7 +276,7 @@ TEST(DesktopFrameTest, CopyIntersectingPixelsPartiallyContainedRects) { }; // clang-format on - RunTests(tests, arraysize(tests)); + RunTests(tests); } TEST(DesktopFrameTest, CopyIntersectingPixelsPartiallyContainedRectsScaled) { @@ -308,7 +308,7 @@ TEST(DesktopFrameTest, CopyIntersectingPixelsPartiallyContainedRectsScaled) { }; // clang-format on - RunTests(tests, arraysize(tests)); + RunTests(tests); } TEST(DesktopFrameTest, CopyIntersectingPixelsUncontainedRects) { @@ -341,7 +341,7 @@ TEST(DesktopFrameTest, CopyIntersectingPixelsUncontainedRects) { }; // clang-format on - RunTests(tests, arraysize(tests)); + RunTests(tests); } TEST(DesktopFrameTest, CopyIntersectingPixelsUncontainedRectsScaled) { @@ -374,7 +374,7 @@ TEST(DesktopFrameTest, CopyIntersectingPixelsUncontainedRectsScaled) { }; // clang-format on - RunTests(tests, arraysize(tests)); + RunTests(tests); } } // namespace webrtc diff --git a/modules/desktop_capture/desktop_frame_win.cc b/modules/desktop_capture/desktop_frame_win.cc index 262ebbdec0..7a0c172cee 100644 --- a/modules/desktop_capture/desktop_frame_win.cc +++ b/modules/desktop_capture/desktop_frame_win.cc @@ -10,8 +10,13 @@ #include "modules/desktop_capture/desktop_frame_win.h" +#include +#include #include +#include "modules/desktop_capture/desktop_frame.h" +#include "modules/desktop_capture/desktop_geometry.h" +#include "modules/desktop_capture/shared_memory.h" #include "rtc_base/logging.h" namespace webrtc { diff --git a/modules/desktop_capture/desktop_frame_win.h b/modules/desktop_capture/desktop_frame_win.h index f8faad6777..e3973df888 100644 --- a/modules/desktop_capture/desktop_frame_win.h +++ b/modules/desktop_capture/desktop_frame_win.h @@ -13,9 +13,12 @@ #include +#include #include #include "modules/desktop_capture/desktop_frame.h" +#include "modules/desktop_capture/desktop_geometry.h" +#include "modules/desktop_capture/shared_memory.h" namespace webrtc { diff --git a/modules/desktop_capture/desktop_geometry.cc b/modules/desktop_capture/desktop_geometry.cc index e0a5d7af83..2a2873fe6e 100644 --- a/modules/desktop_capture/desktop_geometry.cc +++ b/modules/desktop_capture/desktop_geometry.cc @@ -12,6 +12,7 @@ #include #include +#include namespace webrtc { diff --git a/modules/desktop_capture/desktop_geometry.h b/modules/desktop_capture/desktop_geometry.h index 691455df57..8a79ea9fea 100644 --- a/modules/desktop_capture/desktop_geometry.h +++ b/modules/desktop_capture/desktop_geometry.h @@ -13,6 +13,7 @@ #include +#include "rtc_base/strings/string_builder.h" #include "rtc_base/system/rtc_export.h" namespace webrtc { @@ -45,6 +46,12 @@ class DesktopVector { DesktopVector operator-() const { return DesktopVector(-x_, -y_); } + template + friend void AbslStringify(Sink& sink, const DesktopVector& self) { + StringBuilder sb; + sink.Append((sb << "x: " << self.x() << ", y: " << self.y()).str()); + } + private: int32_t x_; int32_t y_; diff --git a/modules/desktop_capture/desktop_region.cc b/modules/desktop_capture/desktop_region.cc index 2c87c11eb3..a025e17cbf 100644 --- a/modules/desktop_capture/desktop_region.cc +++ b/modules/desktop_capture/desktop_region.cc @@ -11,8 +11,10 @@ #include "modules/desktop_capture/desktop_region.h" #include +#include #include +#include "modules/desktop_capture/desktop_geometry.h" #include "rtc_base/checks.h" namespace webrtc { diff --git a/modules/desktop_capture/desktop_region_unittest.cc b/modules/desktop_capture/desktop_region_unittest.cc index 0cd45e9c6b..20d873df5e 100644 --- a/modules/desktop_capture/desktop_region_unittest.cc +++ b/modules/desktop_capture/desktop_region_unittest.cc @@ -10,11 +10,10 @@ #include "modules/desktop_capture/desktop_region.h" -#include - #include -#include +#include +#include "modules/desktop_capture/desktop_geometry.h" #include "test/gtest.h" namespace webrtc { diff --git a/modules/desktop_capture/differ_block.cc b/modules/desktop_capture/differ_block.cc index c51d33e41e..06f04e521d 100644 --- a/modules/desktop_capture/differ_block.cc +++ b/modules/desktop_capture/differ_block.cc @@ -10,13 +10,13 @@ #include "modules/desktop_capture/differ_block.h" -#include +#include +#include -#include "rtc_base/system/arch.h" -#include "system_wrappers/include/cpu_features_wrapper.h" +#include "rtc_base/cpu_info.h" -// This needs to be after rtc_base/system/arch.h which defines -// architecture macros. +// Defines WEBRTC_ARCH_X86_FAMILY, used below. +#include "rtc_base/system/arch.h" #if defined(WEBRTC_ARCH_X86_FAMILY) #include "modules/desktop_capture/differ_vector_sse2.h" #endif @@ -36,7 +36,7 @@ bool VectorDifference(const uint8_t* image1, const uint8_t* image2) { if (!diff_proc) { #if defined(WEBRTC_ARCH_X86_FAMILY) - bool have_sse2 = GetCPUInfo(kSSE2) != 0; + bool have_sse2 = cpu_info::Supports(cpu_info::ISA::kSSE2); // For x86 processors, check if SSE2 is supported. if (have_sse2 && kBlockSize == 32) { diff_proc = &VectorDifference_SSE2_W32; diff --git a/modules/desktop_capture/differ_block_unittest.cc b/modules/desktop_capture/differ_block_unittest.cc index aa454c872d..819e6617a5 100644 --- a/modules/desktop_capture/differ_block_unittest.cc +++ b/modules/desktop_capture/differ_block_unittest.cc @@ -10,7 +10,8 @@ #include "modules/desktop_capture/differ_block.h" -#include +#include +#include #include "test/gtest.h" diff --git a/modules/desktop_capture/differ_vector_sse2.cc b/modules/desktop_capture/differ_vector_sse2.cc index 1c8b602d71..a3fd3d2df0 100644 --- a/modules/desktop_capture/differ_vector_sse2.cc +++ b/modules/desktop_capture/differ_vector_sse2.cc @@ -10,6 +10,8 @@ #include "modules/desktop_capture/differ_vector_sse2.h" +#include + #if defined(_MSC_VER) #include #else diff --git a/modules/desktop_capture/fake_desktop_capturer.cc b/modules/desktop_capture/fake_desktop_capturer.cc index f9d9dbd2c4..a80d9aa1ff 100644 --- a/modules/desktop_capture/fake_desktop_capturer.cc +++ b/modules/desktop_capture/fake_desktop_capturer.cc @@ -10,10 +10,14 @@ #include "modules/desktop_capture/fake_desktop_capturer.h" +#include #include #include "modules/desktop_capture/desktop_capture_types.h" +#include "modules/desktop_capture/desktop_capturer.h" #include "modules/desktop_capture/desktop_frame.h" +#include "modules/desktop_capture/desktop_frame_generator.h" +#include "modules/desktop_capture/shared_memory.h" namespace webrtc { diff --git a/modules/desktop_capture/fallback_desktop_capturer_wrapper.cc b/modules/desktop_capture/fallback_desktop_capturer_wrapper.cc index 61fdb416f2..3f1ff2206b 100644 --- a/modules/desktop_capture/fallback_desktop_capturer_wrapper.cc +++ b/modules/desktop_capture/fallback_desktop_capturer_wrapper.cc @@ -10,11 +10,16 @@ #include "modules/desktop_capture/fallback_desktop_capturer_wrapper.h" -#include - +#include +#include #include #include "api/sequence_checker.h" +#include "modules/desktop_capture/desktop_capture_types.h" +#include "modules/desktop_capture/desktop_capturer.h" +#include "modules/desktop_capture/desktop_frame.h" +#include "modules/desktop_capture/desktop_geometry.h" +#include "modules/desktop_capture/shared_memory.h" #include "rtc_base/checks.h" #include "system_wrappers/include/metrics.h" diff --git a/modules/desktop_capture/fallback_desktop_capturer_wrapper_unittest.cc b/modules/desktop_capture/fallback_desktop_capturer_wrapper_unittest.cc index de66386434..570d8c86a9 100644 --- a/modules/desktop_capture/fallback_desktop_capturer_wrapper_unittest.cc +++ b/modules/desktop_capture/fallback_desktop_capturer_wrapper_unittest.cc @@ -10,8 +10,7 @@ #include "modules/desktop_capture/fallback_desktop_capturer_wrapper.h" -#include - +#include #include #include #include @@ -19,6 +18,7 @@ #include "modules/desktop_capture/desktop_capturer.h" #include "modules/desktop_capture/desktop_frame_generator.h" #include "modules/desktop_capture/fake_desktop_capturer.h" +#include "modules/desktop_capture/shared_memory.h" #include "test/gtest.h" namespace webrtc { diff --git a/modules/desktop_capture/full_screen_application_handler.cc b/modules/desktop_capture/full_screen_application_handler.cc index 68ee8321b4..53570a4cb6 100644 --- a/modules/desktop_capture/full_screen_application_handler.cc +++ b/modules/desktop_capture/full_screen_application_handler.cc @@ -10,7 +10,9 @@ #include "modules/desktop_capture/full_screen_application_handler.h" -#include "rtc_base/logging.h" +#include + +#include "modules/desktop_capture/desktop_capturer.h" namespace webrtc { diff --git a/modules/desktop_capture/full_screen_application_handler.h b/modules/desktop_capture/full_screen_application_handler.h index f816dd416c..da9aa9e164 100644 --- a/modules/desktop_capture/full_screen_application_handler.h +++ b/modules/desktop_capture/full_screen_application_handler.h @@ -11,7 +11,7 @@ #ifndef MODULES_DESKTOP_CAPTURE_FULL_SCREEN_APPLICATION_HANDLER_H_ #define MODULES_DESKTOP_CAPTURE_FULL_SCREEN_APPLICATION_HANDLER_H_ -#include +#include #include "modules/desktop_capture/desktop_capturer.h" diff --git a/modules/desktop_capture/full_screen_window_detector.cc b/modules/desktop_capture/full_screen_window_detector.cc index b4eafc1771..2bbd1f8f51 100644 --- a/modules/desktop_capture/full_screen_window_detector.cc +++ b/modules/desktop_capture/full_screen_window_detector.cc @@ -10,6 +10,10 @@ #include "modules/desktop_capture/full_screen_window_detector.h" +#include + +#include "api/function_view.h" +#include "modules/desktop_capture/desktop_capturer.h" #include "modules/desktop_capture/full_screen_application_handler.h" #include "rtc_base/time_utils.h" diff --git a/modules/desktop_capture/full_screen_window_detector.h b/modules/desktop_capture/full_screen_window_detector.h index ad50c2ce47..2c882790e9 100644 --- a/modules/desktop_capture/full_screen_window_detector.h +++ b/modules/desktop_capture/full_screen_window_detector.h @@ -11,6 +11,8 @@ #ifndef MODULES_DESKTOP_CAPTURE_FULL_SCREEN_WINDOW_DETECTOR_H_ #define MODULES_DESKTOP_CAPTURE_FULL_SCREEN_WINDOW_DETECTOR_H_ +#include +#include #include #include "api/function_view.h" diff --git a/modules/desktop_capture/linux/wayland/base_capturer_pipewire.cc b/modules/desktop_capture/linux/wayland/base_capturer_pipewire.cc index 76340ced41..b2864eeee5 100644 --- a/modules/desktop_capture/linux/wayland/base_capturer_pipewire.cc +++ b/modules/desktop_capture/linux/wayland/base_capturer_pipewire.cc @@ -10,11 +10,22 @@ #include "modules/desktop_capture/linux/wayland/base_capturer_pipewire.h" +#include + +#include +#include +#include + +#include "modules/desktop_capture/delegated_source_list_controller.h" #include "modules/desktop_capture/desktop_capture_options.h" +#include "modules/desktop_capture/desktop_capture_types.h" #include "modules/desktop_capture/desktop_capturer.h" #include "modules/desktop_capture/linux/wayland/restore_token_manager.h" +#include "modules/desktop_capture/linux/wayland/screen_capture_portal_interface.h" +#include "modules/desktop_capture/linux/wayland/screencast_portal.h" #include "modules/portal/pipewire_utils.h" -#include "modules/portal/xdg_desktop_portal_utils.h" +#include "modules/portal/portal_request_response.h" +#include "modules/portal/xdg_session_details.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "rtc_base/time_utils.h" @@ -159,7 +170,7 @@ void BaseCapturerPipeWire::CaptureFrame() { return; } - int64_t capture_start_time_nanos = webrtc::TimeNanos(); + int64_t capture_start_time_nanos = TimeNanos(); std::unique_ptr frame = options_.screencast_stream()->CaptureFrame(); @@ -172,8 +183,8 @@ void BaseCapturerPipeWire::CaptureFrame() { // the frame, see ScreenCapturerX11::CaptureFrame. frame->set_capturer_id(DesktopCapturerId::kWaylandCapturerLinux); - frame->set_capture_time_ms((webrtc::TimeNanos() - capture_start_time_nanos) / - webrtc::kNumNanosecsPerMillisec); + frame->set_capture_time_ms((TimeNanos() - capture_start_time_nanos) / + kNumNanosecsPerMillisec); callback_->OnCaptureResult(Result::SUCCESS, std::move(frame)); } diff --git a/modules/desktop_capture/linux/wayland/base_capturer_pipewire.h b/modules/desktop_capture/linux/wayland/base_capturer_pipewire.h index 083d373c17..7f2eaf12ae 100644 --- a/modules/desktop_capture/linux/wayland/base_capturer_pipewire.h +++ b/modules/desktop_capture/linux/wayland/base_capturer_pipewire.h @@ -11,15 +11,18 @@ #ifndef MODULES_DESKTOP_CAPTURE_LINUX_WAYLAND_BASE_CAPTURER_PIPEWIRE_H_ #define MODULES_DESKTOP_CAPTURE_LINUX_WAYLAND_BASE_CAPTURER_PIPEWIRE_H_ +#include +#include + #include "modules/desktop_capture/delegated_source_list_controller.h" #include "modules/desktop_capture/desktop_capture_options.h" +#include "modules/desktop_capture/desktop_capture_types.h" #include "modules/desktop_capture/desktop_capturer.h" #include "modules/desktop_capture/linux/wayland/screen_capture_portal_interface.h" #include "modules/desktop_capture/linux/wayland/screencast_portal.h" -#include "modules/desktop_capture/linux/wayland/shared_screencast_stream.h" #include "modules/portal/portal_request_response.h" -#include "modules/portal/xdg_desktop_portal_utils.h" #include "modules/portal/xdg_session_details.h" +#include "rtc_base/system/rtc_export.h" namespace webrtc { diff --git a/modules/desktop_capture/linux/wayland/egl_dmabuf.cc b/modules/desktop_capture/linux/wayland/egl_dmabuf.cc index c67f126fad..b580717bf4 100644 --- a/modules/desktop_capture/linux/wayland/egl_dmabuf.cc +++ b/modules/desktop_capture/linux/wayland/egl_dmabuf.cc @@ -10,19 +10,30 @@ #include "modules/desktop_capture/linux/wayland/egl_dmabuf.h" +#include #include +#include +#include +#include #include #include #include +#include #include -#include #include #include #include +#include +#include +#include +#include #include +#include +#include -#include "absl/memory/memory.h" +#include "absl/strings/string_view.h" +#include "modules/desktop_capture/desktop_geometry.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "rtc_base/sanitizer.h" @@ -498,7 +509,7 @@ bool EglDmaBuf::GetClientExtensions(EGLDisplay dpy, EGLint name) { } std::vector client_extensions = - webrtc::split(client_extensions_cstring, ' '); + split(client_extensions_cstring, ' '); for (const auto& extension : client_extensions) { egl_.extensions.push_back(std::string(extension)); } diff --git a/modules/desktop_capture/linux/wayland/egl_dmabuf.h b/modules/desktop_capture/linux/wayland/egl_dmabuf.h index 08df16bc63..a5d38685b9 100644 --- a/modules/desktop_capture/linux/wayland/egl_dmabuf.h +++ b/modules/desktop_capture/linux/wayland/egl_dmabuf.h @@ -12,10 +12,11 @@ #define MODULES_DESKTOP_CAPTURE_LINUX_WAYLAND_EGL_DMABUF_H_ #include +#include #include #include -#include +#include #include #include #include diff --git a/modules/desktop_capture/linux/wayland/mouse_cursor_monitor_pipewire.cc b/modules/desktop_capture/linux/wayland/mouse_cursor_monitor_pipewire.cc index 21f550bea2..03cc9079bf 100644 --- a/modules/desktop_capture/linux/wayland/mouse_cursor_monitor_pipewire.cc +++ b/modules/desktop_capture/linux/wayland/mouse_cursor_monitor_pipewire.cc @@ -10,12 +10,16 @@ #include "modules/desktop_capture/linux/wayland/mouse_cursor_monitor_pipewire.h" -#include +#include +#include +#include "api/sequence_checker.h" #include "modules/desktop_capture/desktop_capture_options.h" #include "modules/desktop_capture/desktop_capturer.h" +#include "modules/desktop_capture/desktop_geometry.h" +#include "modules/desktop_capture/mouse_cursor.h" +#include "modules/desktop_capture/mouse_cursor_monitor.h" #include "rtc_base/checks.h" -#include "rtc_base/logging.h" namespace webrtc { diff --git a/modules/desktop_capture/linux/wayland/mouse_cursor_monitor_pipewire.h b/modules/desktop_capture/linux/wayland/mouse_cursor_monitor_pipewire.h index da670bece9..9ddb8e3174 100644 --- a/modules/desktop_capture/linux/wayland/mouse_cursor_monitor_pipewire.h +++ b/modules/desktop_capture/linux/wayland/mouse_cursor_monitor_pipewire.h @@ -11,16 +11,11 @@ #ifndef MODULES_DESKTOP_CAPTURE_LINUX_WAYLAND_MOUSE_CURSOR_MONITOR_PIPEWIRE_H_ #define MODULES_DESKTOP_CAPTURE_LINUX_WAYLAND_MOUSE_CURSOR_MONITOR_PIPEWIRE_H_ -#include - -#include "api/scoped_refptr.h" #include "api/sequence_checker.h" #include "modules/desktop_capture/desktop_capture_options.h" -#include "modules/desktop_capture/desktop_capture_types.h" -#include "modules/desktop_capture/linux/wayland/shared_screencast_stream.h" -#include "modules/desktop_capture/mouse_cursor.h" #include "modules/desktop_capture/mouse_cursor_monitor.h" #include "rtc_base/system/no_unique_address.h" +#include "rtc_base/thread_annotations.h" namespace webrtc { diff --git a/modules/desktop_capture/linux/wayland/restore_token_manager.cc b/modules/desktop_capture/linux/wayland/restore_token_manager.cc index a17d9a49bb..ff843c2047 100644 --- a/modules/desktop_capture/linux/wayland/restore_token_manager.cc +++ b/modules/desktop_capture/linux/wayland/restore_token_manager.cc @@ -10,11 +10,15 @@ #include "modules/desktop_capture/linux/wayland/restore_token_manager.h" +#include + +#include "modules/desktop_capture/desktop_capturer.h" + namespace webrtc { // static RestoreTokenManager& RestoreTokenManager::GetInstance() { - static webrtc::RestoreTokenManager* manager = new RestoreTokenManager(); + static RestoreTokenManager* manager = new RestoreTokenManager(); return *manager; } diff --git a/modules/desktop_capture/linux/wayland/restore_token_manager.h b/modules/desktop_capture/linux/wayland/restore_token_manager.h index ad4f74790f..06d3071565 100644 --- a/modules/desktop_capture/linux/wayland/restore_token_manager.h +++ b/modules/desktop_capture/linux/wayland/restore_token_manager.h @@ -11,7 +11,6 @@ #ifndef MODULES_DESKTOP_CAPTURE_LINUX_WAYLAND_RESTORE_TOKEN_MANAGER_H_ #define MODULES_DESKTOP_CAPTURE_LINUX_WAYLAND_RESTORE_TOKEN_MANAGER_H_ -#include #include #include diff --git a/modules/desktop_capture/linux/wayland/screen_capture_portal_interface.cc b/modules/desktop_capture/linux/wayland/screen_capture_portal_interface.cc index 1c7cc379df..3ea47e4d3f 100644 --- a/modules/desktop_capture/linux/wayland/screen_capture_portal_interface.cc +++ b/modules/desktop_capture/linux/wayland/screen_capture_portal_interface.cc @@ -9,8 +9,14 @@ */ #include "modules/desktop_capture/linux/wayland/screen_capture_portal_interface.h" +#include +#include + +#include #include +#include "modules/portal/portal_request_response.h" +#include "modules/portal/scoped_glib.h" #include "modules/portal/xdg_desktop_portal_utils.h" #include "rtc_base/logging.h" diff --git a/modules/desktop_capture/linux/wayland/screen_capture_portal_interface.h b/modules/desktop_capture/linux/wayland/screen_capture_portal_interface.h index 7953c6470c..06401f0de2 100644 --- a/modules/desktop_capture/linux/wayland/screen_capture_portal_interface.h +++ b/modules/desktop_capture/linux/wayland/screen_capture_portal_interface.h @@ -12,13 +12,13 @@ #define MODULES_DESKTOP_CAPTURE_LINUX_WAYLAND_SCREEN_CAPTURE_PORTAL_INTERFACE_H_ #include +#include #include #include "modules/portal/portal_request_response.h" -#include "modules/portal/scoped_glib.h" -#include "modules/portal/xdg_desktop_portal_utils.h" #include "modules/portal/xdg_session_details.h" +#include "rtc_base/system/rtc_export.h" namespace webrtc { namespace xdg_portal { diff --git a/modules/desktop_capture/linux/wayland/screencast_portal.cc b/modules/desktop_capture/linux/wayland/screencast_portal.cc index 61ed84ebb5..d3c8c077fa 100644 --- a/modules/desktop_capture/linux/wayland/screencast_portal.cc +++ b/modules/desktop_capture/linux/wayland/screencast_portal.cc @@ -10,11 +10,23 @@ #include "modules/desktop_capture/linux/wayland/screencast_portal.h" +#include #include #include +#include +#include +#include +#include +#include +#include + +#include "modules/desktop_capture/desktop_capture_types.h" +#include "modules/portal/pipewire_utils.h" +#include "modules/portal/portal_request_response.h" #include "modules/portal/scoped_glib.h" #include "modules/portal/xdg_desktop_portal_utils.h" +#include "modules/portal/xdg_session_details.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" @@ -88,23 +100,19 @@ void ScreenCastPortal::Stop() { } } -void ScreenCastPortal::UnsubscribeSignalHandlers() { - if (start_request_signal_id_) { - g_dbus_connection_signal_unsubscribe(connection_, start_request_signal_id_); - start_request_signal_id_ = 0; - } - - if (sources_request_signal_id_) { - g_dbus_connection_signal_unsubscribe(connection_, - sources_request_signal_id_); - sources_request_signal_id_ = 0; +// static +void UnsubscribeSignalHandler(GDBusConnection* connection, guint* signal_id) { + if (signal_id && *signal_id) { + g_dbus_connection_signal_unsubscribe(connection, *signal_id); + *signal_id = 0; } +} - if (session_request_signal_id_) { - g_dbus_connection_signal_unsubscribe(connection_, - session_request_signal_id_); - session_request_signal_id_ = 0; - } +void ScreenCastPortal::UnsubscribeSignalHandlers() { + UnsubscribeSignalHandler(connection_, &session_request_signal_id_); + UnsubscribeSignalHandler(connection_, &sources_request_signal_id_); + UnsubscribeSignalHandler(connection_, &start_request_signal_id_); + UnsubscribeSignalHandler(connection_, &session_closed_signal_id_); } void ScreenCastPortal::SetSessionDetails( @@ -200,12 +208,11 @@ void ScreenCastPortal::OnSessionClosedSignal(GDBusConnection* connection, RTC_LOG(LS_INFO) << "Received closed signal from session."; - that->notifier_->OnScreenCastSessionClosed(); + // Clear the session handle to avoid calling Session::Close from the destructor + // since it's already closed + that->session_handle_ = ""; - // Unsubscribe from the signal and free the session handle to avoid calling - // Session::Close from the destructor since it's already closed - g_dbus_connection_signal_unsubscribe(that->connection_, - that->session_closed_signal_id_); + that->notifier_->OnScreenCastSessionClosed(); } void ScreenCastPortal::SourcesRequest() { @@ -293,11 +300,8 @@ void ScreenCastPortal::OnSourcesRequested(GDBusProxy* proxy, g_variant_get_child(variant.get(), 0, "o", handle.receive()); if (!handle) { RTC_LOG(LS_ERROR) << "Failed to initialize the screen cast session."; - if (that->sources_request_signal_id_) { - g_dbus_connection_signal_unsubscribe(that->connection_, - that->sources_request_signal_id_); - that->sources_request_signal_id_ = 0; - } + UnsubscribeSignalHandler(that->connection_, + &that->sources_request_signal_id_); that->OnPortalDone(RequestResponse::kError); return; } diff --git a/modules/desktop_capture/linux/wayland/screencast_portal.h b/modules/desktop_capture/linux/wayland/screencast_portal.h index 2bf7800921..de36b62265 100644 --- a/modules/desktop_capture/linux/wayland/screencast_portal.h +++ b/modules/desktop_capture/linux/wayland/screencast_portal.h @@ -12,15 +12,18 @@ #define MODULES_DESKTOP_CAPTURE_LINUX_WAYLAND_SCREENCAST_PORTAL_H_ #include +#include +#include +#include #include #include "modules/desktop_capture/desktop_capture_types.h" #include "modules/desktop_capture/linux/wayland/screen_capture_portal_interface.h" #include "modules/portal/pipewire_utils.h" #include "modules/portal/portal_request_response.h" -#include "modules/portal/xdg_desktop_portal_utils.h" #include "modules/portal/xdg_session_details.h" +#include "rtc_base/system/rtc_export.h" namespace webrtc { diff --git a/modules/desktop_capture/linux/wayland/screencast_stream_utils.cc b/modules/desktop_capture/linux/wayland/screencast_stream_utils.cc index e5eb267dcf..c0023edda0 100644 --- a/modules/desktop_capture/linux/wayland/screencast_stream_utils.cc +++ b/modules/desktop_capture/linux/wayland/screencast_stream_utils.cc @@ -14,8 +14,13 @@ #include #include -#include +#include +#include +#include +#include +#include "absl/strings/string_view.h" +#include "rtc_base/string_encode.h" #include "rtc_base/string_to_number.h" #if !PW_CHECK_VERSION(0, 3, 29) @@ -28,15 +33,15 @@ namespace webrtc { PipeWireVersion PipeWireVersion::Parse(const absl::string_view& version) { - std::vector parsed_version = webrtc::split(version, '.'); + std::vector parsed_version = split(version, '.'); if (parsed_version.size() != 3) { return {}; } - std::optional major = webrtc::StringToNumber(parsed_version.at(0)); - std::optional minor = webrtc::StringToNumber(parsed_version.at(1)); - std::optional micro = webrtc::StringToNumber(parsed_version.at(2)); + std::optional major = StringToNumber(parsed_version.at(0)); + std::optional minor = StringToNumber(parsed_version.at(1)); + std::optional micro = StringToNumber(parsed_version.at(2)); // Return invalid version if we failed to parse it if (!major || !minor || !micro) { diff --git a/modules/desktop_capture/linux/wayland/screencast_stream_utils.h b/modules/desktop_capture/linux/wayland/screencast_stream_utils.h index 2f44300f73..ee684f4384 100644 --- a/modules/desktop_capture/linux/wayland/screencast_stream_utils.h +++ b/modules/desktop_capture/linux/wayland/screencast_stream_utils.h @@ -13,10 +13,9 @@ #include -#include #include -#include "rtc_base/string_encode.h" +#include "absl/strings/string_view.h" struct spa_pod; struct spa_pod_builder; diff --git a/modules/desktop_capture/linux/wayland/shared_screencast_stream.cc b/modules/desktop_capture/linux/wayland/shared_screencast_stream.cc index a022de6c6a..b3e6553a05 100644 --- a/modules/desktop_capture/linux/wayland/shared_screencast_stream.cc +++ b/modules/desktop_capture/linux/wayland/shared_screencast_stream.cc @@ -14,17 +14,35 @@ #include #include #include - +#include +#include + +#include +#include +#include +#include +#include +#include +#include #include -#include "absl/memory/memory.h" +#include "api/scoped_refptr.h" +#include "modules/desktop_capture/desktop_capture_types.h" +#include "modules/desktop_capture/desktop_capturer.h" +#include "modules/desktop_capture/desktop_frame.h" +#include "modules/desktop_capture/desktop_geometry.h" +#include "modules/desktop_capture/desktop_region.h" #include "modules/desktop_capture/linux/wayland/egl_dmabuf.h" #include "modules/desktop_capture/linux/wayland/screencast_stream_utils.h" +#include "modules/desktop_capture/mouse_cursor.h" +#include "modules/desktop_capture/screen_capture_frame_queue.h" +#include "modules/desktop_capture/shared_desktop_frame.h" #include "modules/portal/pipewire_utils.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "rtc_base/sanitizer.h" #include "rtc_base/synchronization/mutex.h" +#include "rtc_base/thread_annotations.h" #include "rtc_base/time_utils.h" namespace webrtc { @@ -80,10 +98,10 @@ class SharedScreenCastStreamPrivate { DesktopSize stream_size_ = {}; DesktopSize frame_size_; - webrtc::Mutex queue_lock_; + Mutex queue_lock_; ScreenCaptureFrameQueue queue_ RTC_GUARDED_BY(&queue_lock_); - webrtc::Mutex latest_frame_lock_ RTC_ACQUIRED_AFTER(queue_lock_); + Mutex latest_frame_lock_ RTC_ACQUIRED_AFTER(queue_lock_); SharedDesktopFrame* latest_available_frame_ RTC_GUARDED_BY(&latest_frame_lock_) = nullptr; std::unique_ptr mouse_cursor_; @@ -584,11 +602,11 @@ void SharedScreenCastStreamPrivate::StopAndCleanupStream() { pw_stream_ = nullptr; { - webrtc::MutexLock lock(&queue_lock_); + MutexLock lock(&queue_lock_); queue_.Reset(); } { - webrtc::MutexLock latest_frame_lock(&latest_frame_lock_); + MutexLock latest_frame_lock(&latest_frame_lock_); latest_available_frame_ = nullptr; } } @@ -609,7 +627,7 @@ void SharedScreenCastStreamPrivate::StopAndCleanupStream() { std::unique_ptr SharedScreenCastStreamPrivate::CaptureFrame() { - webrtc::MutexLock latest_frame_lock(&latest_frame_lock_); + MutexLock latest_frame_lock(&latest_frame_lock_); if (!pw_stream_ || !latest_available_frame_) { return std::unique_ptr{}; @@ -671,7 +689,7 @@ void SharedScreenCastStreamPrivate::UpdateFrameUpdatedRegions( RTC_NO_SANITIZE("cfi-icall") void SharedScreenCastStreamPrivate::ProcessBuffer(pw_buffer* buffer) { - int64_t capture_start_time_nanos = webrtc::TimeNanos(); + int64_t capture_start_time_nanos = TimeNanos(); if (callback_) { callback_->OnFrameCaptureStart(); } @@ -810,7 +828,7 @@ void SharedScreenCastStreamPrivate::ProcessBuffer(pw_buffer* buffer) { : 0; DesktopVector offset = DesktopVector(x_offset, y_offset); - webrtc::MutexLock lock(&queue_lock_); + MutexLock lock(&queue_lock_); queue_.MoveToNextFrame(); if (queue_.current_frame() && queue_.current_frame()->IsShared()) { @@ -840,7 +858,7 @@ void SharedScreenCastStreamPrivate::ProcessBuffer(pw_buffer* buffer) { if (observer_) { observer_->OnFailedToProcessBuffer(); } - webrtc::MutexLock latest_frame_lock(&latest_frame_lock_); + MutexLock latest_frame_lock(&latest_frame_lock_); latest_available_frame_ = nullptr; return; } @@ -862,7 +880,7 @@ void SharedScreenCastStreamPrivate::ProcessBuffer(pw_buffer* buffer) { std::unique_ptr frame; { - webrtc::MutexLock latest_frame_lock(&latest_frame_lock_); + MutexLock latest_frame_lock(&latest_frame_lock_); UpdateFrameUpdatedRegions(spa_buffer, *queue_.current_frame()); queue_.current_frame()->set_may_contain_cursor(is_cursor_embedded_); @@ -875,9 +893,8 @@ void SharedScreenCastStreamPrivate::ProcessBuffer(pw_buffer* buffer) { frame = latest_available_frame_->Share(); frame->set_capturer_id(DesktopCapturerId::kWaylandCapturerLinux); - frame->set_capture_time_ms( - (webrtc::TimeNanos() - capture_start_time_nanos) / - webrtc::kNumNanosecsPerMillisec); + frame->set_capture_time_ms((TimeNanos() - capture_start_time_nanos) / + kNumNanosecsPerMillisec); if (use_damage_region_) { frame->mutable_updated_region()->Swap(&damage_region_); damage_region_.Clear(); @@ -989,8 +1006,7 @@ SharedScreenCastStream::~SharedScreenCastStream() {} webrtc::scoped_refptr SharedScreenCastStream::CreateDefault() { // Explicit new, to access non-public constructor. - return webrtc::scoped_refptr( - new SharedScreenCastStream()); + return scoped_refptr(new SharedScreenCastStream()); } bool SharedScreenCastStream::StartScreenCastStream(uint32_t stream_node_id) { diff --git a/modules/desktop_capture/linux/wayland/shared_screencast_stream.h b/modules/desktop_capture/linux/wayland/shared_screencast_stream.h index 0043f7af77..6b827115c4 100644 --- a/modules/desktop_capture/linux/wayland/shared_screencast_stream.h +++ b/modules/desktop_capture/linux/wayland/shared_screencast_stream.h @@ -11,14 +11,15 @@ #ifndef MODULES_DESKTOP_CAPTURE_LINUX_WAYLAND_SHARED_SCREENCAST_STREAM_H_ #define MODULES_DESKTOP_CAPTURE_LINUX_WAYLAND_SHARED_SCREENCAST_STREAM_H_ +#include #include #include #include "api/ref_counted_base.h" #include "api/scoped_refptr.h" #include "modules/desktop_capture/desktop_capturer.h" +#include "modules/desktop_capture/desktop_geometry.h" #include "modules/desktop_capture/mouse_cursor.h" -#include "modules/desktop_capture/screen_capture_frame_queue.h" #include "modules/desktop_capture/shared_desktop_frame.h" #include "rtc_base/system/rtc_export.h" @@ -27,7 +28,7 @@ namespace webrtc { class SharedScreenCastStreamPrivate; class RTC_EXPORT SharedScreenCastStream - : public webrtc::RefCountedNonVirtual { + : public RefCountedNonVirtual { public: class Observer { public: @@ -46,7 +47,7 @@ class RTC_EXPORT SharedScreenCastStream virtual ~Observer() = default; }; - static webrtc::scoped_refptr CreateDefault(); + static scoped_refptr CreateDefault(); bool StartScreenCastStream(uint32_t stream_node_id); bool StartScreenCastStream(uint32_t stream_node_id, diff --git a/modules/desktop_capture/linux/wayland/shared_screencast_stream_unittest.cc b/modules/desktop_capture/linux/wayland/shared_screencast_stream_unittest.cc index 4ae7b78d6e..9bedc8e4bc 100644 --- a/modules/desktop_capture/linux/wayland/shared_screencast_stream_unittest.cc +++ b/modules/desktop_capture/linux/wayland/shared_screencast_stream_unittest.cc @@ -10,14 +10,16 @@ #include "modules/desktop_capture/linux/wayland/shared_screencast_stream.h" +#include + +#include #include -#include +#include "api/scoped_refptr.h" #include "api/units/time_delta.h" -#include "modules/desktop_capture/desktop_capturer.h" -#include "modules/desktop_capture/desktop_frame.h" #include "modules/desktop_capture/linux/wayland/test/test_screencast_stream_provider.h" #include "modules/desktop_capture/rgba_color.h" +#include "modules/desktop_capture/shared_desktop_frame.h" #include "rtc_base/event.h" #include "test/gmock.h" #include "test/gtest.h" @@ -41,7 +43,7 @@ class PipeWireStreamTest : public ::testing::Test, public SharedScreenCastStream::Observer { public: PipeWireStreamTest() = default; - ~PipeWireStreamTest() = default; + ~PipeWireStreamTest() override = default; // FakeScreenCastPortal::Observer MOCK_METHOD(void, OnBufferAdded, (), (override)); @@ -77,15 +79,15 @@ class PipeWireStreamTest : public ::testing::Test, bool streaming_ = false; std::unique_ptr test_screencast_stream_provider_; - webrtc::scoped_refptr shared_screencast_stream_; + scoped_refptr shared_screencast_stream_; }; TEST_F(PipeWireStreamTest, TestPipeWire) { // Set expectations for PipeWire to successfully connect both streams - webrtc::Event waitConnectEvent; - webrtc::Event waitStartStreamingEvent; - webrtc::Event waitStreamParamChangedEvent1; - webrtc::Event waitStreamParamChangedEvent2; + Event waitConnectEvent; + Event waitStartStreamingEvent; + Event waitStreamParamChangedEvent1; + Event waitStreamParamChangedEvent2; EXPECT_CALL(*this, OnStreamReady(_)) .WillOnce(Invoke(this, &PipeWireStreamTest::StartScreenCastStream)); @@ -105,7 +107,7 @@ TEST_F(PipeWireStreamTest, TestPipeWire) { // Wait until we start streaming waitStartStreamingEvent.Wait(kShortWait); - webrtc::Event frameRetrievedEvent; + Event frameRetrievedEvent; EXPECT_CALL(*this, OnFrameRecorded).Times(6); EXPECT_CALL(*this, OnDesktopFrameChanged) .Times(3) @@ -147,7 +149,7 @@ TEST_F(PipeWireStreamTest, TestPipeWire) { EXPECT_NE(frame->data(), frame2->data()); // This should result into overwriting a frame in use - webrtc::Event frameRecordedEvent; + Event frameRecordedEvent; RgbaColor blue_color(255, 0, 0); EXPECT_CALL(*this, OnFailedToProcessBuffer).WillOnce([&frameRecordedEvent] { frameRecordedEvent.Set(); @@ -161,7 +163,7 @@ TEST_F(PipeWireStreamTest, TestPipeWire) { EXPECT_EQ(RgbaColor(frame->data()), blue_color); // Check we don't process faulty buffers - webrtc::Event corruptedMetadataFrameEvent; + Event corruptedMetadataFrameEvent; EXPECT_CALL(*this, OnBufferCorruptedMetadata) .WillOnce([&corruptedMetadataFrameEvent] { corruptedMetadataFrameEvent.Set(); @@ -171,7 +173,7 @@ TEST_F(PipeWireStreamTest, TestPipeWire) { blue_color, TestScreenCastStreamProvider::CorruptedMetadata); corruptedMetadataFrameEvent.Wait(kShortWait); - webrtc::Event corruptedDataFrameEvent; + Event corruptedDataFrameEvent; EXPECT_CALL(*this, OnBufferCorruptedData) .WillOnce([&corruptedDataFrameEvent] { corruptedDataFrameEvent.Set(); }); @@ -179,7 +181,7 @@ TEST_F(PipeWireStreamTest, TestPipeWire) { blue_color, TestScreenCastStreamProvider::CorruptedData); corruptedDataFrameEvent.Wait(kShortWait); - webrtc::Event emptyFrameEvent; + Event emptyFrameEvent; EXPECT_CALL(*this, OnEmptyBuffer).WillOnce([&emptyFrameEvent] { emptyFrameEvent.Set(); }); diff --git a/modules/desktop_capture/linux/wayland/test/test_screencast_stream_provider.cc b/modules/desktop_capture/linux/wayland/test/test_screencast_stream_provider.cc index 10551047a9..8b7fb41def 100644 --- a/modules/desktop_capture/linux/wayland/test/test_screencast_stream_provider.cc +++ b/modules/desktop_capture/linux/wayland/test/test_screencast_stream_provider.cc @@ -12,15 +12,18 @@ #include "modules/desktop_capture/linux/wayland/test/test_screencast_stream_provider.h" #include +#include +#include #include -#include #include -#include -#include +#include #include +#include "modules/desktop_capture/linux/wayland/screencast_stream_utils.h" +#include "modules/desktop_capture/rgba_color.h" #include "modules/portal/pipewire_utils.h" +#include "rtc_base/checks.h" #include "rtc_base/logging.h" namespace webrtc { diff --git a/modules/desktop_capture/linux/wayland/test/test_screencast_stream_provider.h b/modules/desktop_capture/linux/wayland/test/test_screencast_stream_provider.h index f63a2e647c..63244d2b9c 100644 --- a/modules/desktop_capture/linux/wayland/test/test_screencast_stream_provider.h +++ b/modules/desktop_capture/linux/wayland/test/test_screencast_stream_provider.h @@ -14,9 +14,10 @@ #include #include +#include + #include "modules/desktop_capture/linux/wayland/screencast_stream_utils.h" #include "modules/desktop_capture/rgba_color.h" -#include "rtc_base/random.h" namespace webrtc { diff --git a/modules/desktop_capture/linux/x11/mouse_cursor_monitor_x11.cc b/modules/desktop_capture/linux/x11/mouse_cursor_monitor_x11.cc index 064b98fa15..59047dc03f 100644 --- a/modules/desktop_capture/linux/x11/mouse_cursor_monitor_x11.cc +++ b/modules/desktop_capture/linux/x11/mouse_cursor_monitor_x11.cc @@ -10,13 +10,14 @@ #include "modules/desktop_capture/linux/x11/mouse_cursor_monitor_x11.h" +#include #include #include #include -#include -#include #include +#include +#include #include #include "modules/desktop_capture/desktop_capture_options.h" diff --git a/modules/desktop_capture/linux/x11/screen_capturer_x11.cc b/modules/desktop_capture/linux/x11/screen_capturer_x11.cc index 0384a0373b..4f32a27426 100644 --- a/modules/desktop_capture/linux/x11/screen_capturer_x11.cc +++ b/modules/desktop_capture/linux/x11/screen_capturer_x11.cc @@ -10,21 +10,26 @@ #include "modules/desktop_capture/linux/x11/screen_capturer_x11.h" +#include #include #include #include +#include #include +#include #include -#include -#include +#include +#include #include #include #include "modules/desktop_capture/desktop_capture_options.h" +#include "modules/desktop_capture/desktop_capture_types.h" #include "modules/desktop_capture/desktop_capturer.h" #include "modules/desktop_capture/desktop_frame.h" #include "modules/desktop_capture/desktop_geometry.h" +#include "modules/desktop_capture/desktop_region.h" #include "modules/desktop_capture/linux/x11/x_server_pixel_buffer.h" #include "modules/desktop_capture/screen_capture_frame_queue.h" #include "modules/desktop_capture/screen_capturer_helper.h" diff --git a/modules/desktop_capture/linux/x11/screen_capturer_x11.h b/modules/desktop_capture/linux/x11/screen_capturer_x11.h index d2a437aaa2..4379094734 100644 --- a/modules/desktop_capture/linux/x11/screen_capturer_x11.h +++ b/modules/desktop_capture/linux/x11/screen_capturer_x11.h @@ -22,6 +22,7 @@ #include "modules/desktop_capture/desktop_capture_options.h" #include "modules/desktop_capture/desktop_capturer.h" #include "modules/desktop_capture/desktop_frame.h" +#include "modules/desktop_capture/desktop_geometry.h" #include "modules/desktop_capture/desktop_region.h" #include "modules/desktop_capture/linux/x11/shared_x_display.h" #include "modules/desktop_capture/linux/x11/x_atom_cache.h" diff --git a/modules/desktop_capture/linux/x11/shared_x_display.cc b/modules/desktop_capture/linux/x11/shared_x_display.cc index 60101b9aa4..a5781a5fb3 100644 --- a/modules/desktop_capture/linux/x11/shared_x_display.cc +++ b/modules/desktop_capture/linux/x11/shared_x_display.cc @@ -14,10 +14,15 @@ #include #include +#include +#include +#include #include "absl/strings/string_view.h" +#include "api/scoped_refptr.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" +#include "rtc_base/synchronization/mutex.h" namespace webrtc { diff --git a/modules/desktop_capture/linux/x11/window_capturer_x11.cc b/modules/desktop_capture/linux/x11/window_capturer_x11.cc index b55f7e8fa9..95f453064e 100644 --- a/modules/desktop_capture/linux/x11/window_capturer_x11.cc +++ b/modules/desktop_capture/linux/x11/window_capturer_x11.cc @@ -10,18 +10,23 @@ #include "modules/desktop_capture/linux/x11/window_capturer_x11.h" +#include +#include #include #include #include -#include +#include #include #include #include #include "api/scoped_refptr.h" +#include "modules/desktop_capture/desktop_capture_options.h" #include "modules/desktop_capture/desktop_capture_types.h" +#include "modules/desktop_capture/desktop_capturer.h" #include "modules/desktop_capture/desktop_frame.h" +#include "modules/desktop_capture/desktop_geometry.h" #include "modules/desktop_capture/desktop_region.h" #include "modules/desktop_capture/linux/x11/shared_x_display.h" #include "modules/desktop_capture/linux/x11/window_finder_x11.h" diff --git a/modules/desktop_capture/linux/x11/window_finder_x11.cc b/modules/desktop_capture/linux/x11/window_finder_x11.cc index dec17ab51f..93fa60761b 100644 --- a/modules/desktop_capture/linux/x11/window_finder_x11.cc +++ b/modules/desktop_capture/linux/x11/window_finder_x11.cc @@ -14,7 +14,10 @@ #include +#include "modules/desktop_capture/desktop_capture_types.h" +#include "modules/desktop_capture/desktop_geometry.h" #include "modules/desktop_capture/linux/x11/window_list_utils.h" +#include "modules/desktop_capture/window_finder.h" #include "rtc_base/checks.h" namespace webrtc { diff --git a/modules/desktop_capture/linux/x11/window_finder_x11.h b/modules/desktop_capture/linux/x11/window_finder_x11.h index 91de876417..590b1fa9fb 100644 --- a/modules/desktop_capture/linux/x11/window_finder_x11.h +++ b/modules/desktop_capture/linux/x11/window_finder_x11.h @@ -11,6 +11,8 @@ #ifndef MODULES_DESKTOP_CAPTURE_LINUX_X11_WINDOW_FINDER_X11_H_ #define MODULES_DESKTOP_CAPTURE_LINUX_X11_WINDOW_FINDER_X11_H_ +#include "modules/desktop_capture/desktop_capture_types.h" +#include "modules/desktop_capture/desktop_geometry.h" #include "modules/desktop_capture/window_finder.h" namespace webrtc { diff --git a/modules/desktop_capture/linux/x11/window_list_utils.cc b/modules/desktop_capture/linux/x11/window_list_utils.cc index 41de4f84b4..e80df6a974 100644 --- a/modules/desktop_capture/linux/x11/window_list_utils.cc +++ b/modules/desktop_capture/linux/x11/window_list_utils.cc @@ -10,12 +10,17 @@ #include "modules/desktop_capture/linux/x11/window_list_utils.h" +#include #include #include -#include #include +#include +#include +#include "api/function_view.h" +#include "modules/desktop_capture/desktop_geometry.h" +#include "modules/desktop_capture/linux/x11/x_atom_cache.h" #include "modules/desktop_capture/linux/x11/x_error_trap.h" #include "modules/desktop_capture/linux/x11/x_window_property.h" #include "rtc_base/checks.h" diff --git a/modules/desktop_capture/linux/x11/x_atom_cache.cc b/modules/desktop_capture/linux/x11/x_atom_cache.cc index 157ba8b8fd..ac8815edc2 100644 --- a/modules/desktop_capture/linux/x11/x_atom_cache.cc +++ b/modules/desktop_capture/linux/x11/x_atom_cache.cc @@ -10,6 +10,9 @@ #include "modules/desktop_capture/linux/x11/x_atom_cache.h" +#include +#include + #include "rtc_base/checks.h" namespace webrtc { diff --git a/modules/desktop_capture/linux/x11/x_error_trap.cc b/modules/desktop_capture/linux/x11/x_error_trap.cc index 24c2065111..ebfdde4afb 100644 --- a/modules/desktop_capture/linux/x11/x_error_trap.cc +++ b/modules/desktop_capture/linux/x11/x_error_trap.cc @@ -10,18 +10,20 @@ #include "modules/desktop_capture/linux/x11/x_error_trap.h" -#include +#include #include +#include #include "rtc_base/checks.h" +#include "rtc_base/synchronization/mutex.h" namespace webrtc { namespace { -static int g_last_xserver_error_code = 0; -static std::atomic g_display_for_error_handler = nullptr; +int g_last_xserver_error_code = 0; +std::atomic g_display_for_error_handler = nullptr; Mutex* AcquireMutex() { static Mutex* mutex = new Mutex(); diff --git a/modules/desktop_capture/linux/x11/x_server_pixel_buffer.cc b/modules/desktop_capture/linux/x11/x_server_pixel_buffer.cc index d62a014ae8..f3b7dea04f 100644 --- a/modules/desktop_capture/linux/x11/x_server_pixel_buffer.cc +++ b/modules/desktop_capture/linux/x11/x_server_pixel_buffer.cc @@ -10,13 +10,18 @@ #include "modules/desktop_capture/linux/x11/x_server_pixel_buffer.h" +#include +#include #include -#include -#include +#include #include #include +#include +#include + #include "modules/desktop_capture/desktop_frame.h" +#include "modules/desktop_capture/desktop_geometry.h" #include "modules/desktop_capture/linux/x11/window_list_utils.h" #include "modules/desktop_capture/linux/x11/x_error_trap.h" #include "modules/desktop_capture/linux/x11/x_window_property.h" diff --git a/modules/desktop_capture/linux/x11/x_server_pixel_buffer.h b/modules/desktop_capture/linux/x11/x_server_pixel_buffer.h index 1ccf8af971..40ccc6acd0 100644 --- a/modules/desktop_capture/linux/x11/x_server_pixel_buffer.h +++ b/modules/desktop_capture/linux/x11/x_server_pixel_buffer.h @@ -13,10 +13,11 @@ #ifndef MODULES_DESKTOP_CAPTURE_LINUX_X11_X_SERVER_PIXEL_BUFFER_H_ #define MODULES_DESKTOP_CAPTURE_LINUX_X11_X_SERVER_PIXEL_BUFFER_H_ -#include +#include +#include #include -#include +#include #include #include "modules/desktop_capture/desktop_geometry.h" diff --git a/modules/desktop_capture/linux/x11/x_window_property.cc b/modules/desktop_capture/linux/x11/x_window_property.cc index 5e16dac404..2965836fad 100644 --- a/modules/desktop_capture/linux/x11/x_window_property.cc +++ b/modules/desktop_capture/linux/x11/x_window_property.cc @@ -10,6 +10,9 @@ #include "modules/desktop_capture/linux/x11/x_window_property.h" +#include +#include + namespace webrtc { XWindowPropertyBase::XWindowPropertyBase(Display* display, diff --git a/modules/desktop_capture/linux/x11/x_window_property.h b/modules/desktop_capture/linux/x11/x_window_property.h index 28dfb97311..80b4accb12 100644 --- a/modules/desktop_capture/linux/x11/x_window_property.h +++ b/modules/desktop_capture/linux/x11/x_window_property.h @@ -14,6 +14,8 @@ #include #include +#include + namespace webrtc { class XWindowPropertyBase { diff --git a/modules/desktop_capture/mac/desktop_configuration_monitor.h b/modules/desktop_capture/mac/desktop_configuration_monitor.h index b4650e31cc..1ef480470b 100644 --- a/modules/desktop_capture/mac/desktop_configuration_monitor.h +++ b/modules/desktop_capture/mac/desktop_configuration_monitor.h @@ -25,7 +25,7 @@ namespace webrtc { // The class provides functions to synchronize capturing and display // reconfiguring across threads, and the up-to-date MacDesktopConfiguration. class DesktopConfigurationMonitor final - : public webrtc::RefCountedNonVirtual { + : public RefCountedNonVirtual { public: DesktopConfigurationMonitor(); ~DesktopConfigurationMonitor(); diff --git a/modules/desktop_capture/mac/desktop_frame_cgimage.h b/modules/desktop_capture/mac/desktop_frame_cgimage.h index 16db9e80a7..4523f66683 100644 --- a/modules/desktop_capture/mac/desktop_frame_cgimage.h +++ b/modules/desktop_capture/mac/desktop_frame_cgimage.h @@ -34,7 +34,7 @@ class RTC_EXPORT DesktopFrameCGImage final : public DesktopFrame { CGWindowID window_id); static std::unique_ptr CreateFromCGImage( - webrtc::ScopedCFTypeRef cg_image); + ScopedCFTypeRef cg_image); ~DesktopFrameCGImage() override; @@ -46,11 +46,11 @@ class RTC_EXPORT DesktopFrameCGImage final : public DesktopFrame { DesktopFrameCGImage(DesktopSize size, int stride, uint8_t* data, - webrtc::ScopedCFTypeRef cg_image, - webrtc::ScopedCFTypeRef cg_data); + ScopedCFTypeRef cg_image, + ScopedCFTypeRef cg_data); - const webrtc::ScopedCFTypeRef cg_image_; - const webrtc::ScopedCFTypeRef cg_data_; + const ScopedCFTypeRef cg_image_; + const ScopedCFTypeRef cg_data_; }; } // namespace webrtc diff --git a/modules/desktop_capture/mac/desktop_frame_iosurface.h b/modules/desktop_capture/mac/desktop_frame_iosurface.h index 3dc2abad3e..8dfebea335 100644 --- a/modules/desktop_capture/mac/desktop_frame_iosurface.h +++ b/modules/desktop_capture/mac/desktop_frame_iosurface.h @@ -27,7 +27,7 @@ class DesktopFrameIOSurface final : public DesktopFrame { // failed to lock. `rect` specifies the portion of the surface that the // DesktopFrame should be cropped to. static std::unique_ptr Wrap( - webrtc::ScopedCFTypeRef io_surface, CGRect rect = {}); + ScopedCFTypeRef io_surface, CGRect rect = {}); ~DesktopFrameIOSurface() override; @@ -40,13 +40,13 @@ class DesktopFrameIOSurface final : public DesktopFrame { // buffer. // `width` and `height` make up the dimensions of `io_surface` in pixels. // `stride` is the number of bytes of a single row of pixels in `data`. - DesktopFrameIOSurface(webrtc::ScopedCFTypeRef io_surface, + DesktopFrameIOSurface(ScopedCFTypeRef io_surface, uint8_t* data, int32_t width, int32_t height, int32_t stride); - const webrtc::ScopedCFTypeRef io_surface_; + const ScopedCFTypeRef io_surface_; }; } // namespace webrtc diff --git a/modules/desktop_capture/mac/desktop_frame_utils.cc b/modules/desktop_capture/mac/desktop_frame_utils.cc index a2f04c724a..c78270826c 100644 --- a/modules/desktop_capture/mac/desktop_frame_utils.cc +++ b/modules/desktop_capture/mac/desktop_frame_utils.cc @@ -15,7 +15,7 @@ namespace webrtc { std::unique_ptr CreateDesktopFrameFromCGImage( - webrtc::ScopedCFTypeRef cg_image) { + ScopedCFTypeRef cg_image) { return DesktopFrameCGImage::CreateFromCGImage(cg_image); } diff --git a/modules/desktop_capture/mac/desktop_frame_utils.h b/modules/desktop_capture/mac/desktop_frame_utils.h index a7be7c5b8e..3429e71fef 100644 --- a/modules/desktop_capture/mac/desktop_frame_utils.h +++ b/modules/desktop_capture/mac/desktop_frame_utils.h @@ -20,7 +20,7 @@ namespace webrtc { std::unique_ptr RTC_EXPORT -CreateDesktopFrameFromCGImage(webrtc::ScopedCFTypeRef cg_image); +CreateDesktopFrameFromCGImage(ScopedCFTypeRef cg_image); } // namespace webrtc diff --git a/modules/desktop_capture/mac/full_screen_mac_application_handler.cc b/modules/desktop_capture/mac/full_screen_mac_application_handler.cc index 48767ba6ab..a43797f8a6 100644 --- a/modules/desktop_capture/mac/full_screen_mac_application_handler.cc +++ b/modules/desktop_capture/mac/full_screen_mac_application_handler.cc @@ -67,8 +67,7 @@ class FullScreenMacApplicationHandler : public FullScreenApplicationHandler { ignore_original_window_(ignore_original_window) {} protected: - using CachePredicate = - webrtc::FunctionView; + using CachePredicate = FunctionView; void InvalidateCacheIfNeeded(const DesktopCapturer::SourceList& source_list, int64_t timestamp, diff --git a/modules/desktop_capture/mac/full_screen_mac_application_handler.h b/modules/desktop_capture/mac/full_screen_mac_application_handler.h index 060cdb5a61..d9ff943ef4 100644 --- a/modules/desktop_capture/mac/full_screen_mac_application_handler.h +++ b/modules/desktop_capture/mac/full_screen_mac_application_handler.h @@ -13,6 +13,7 @@ #include +#include "modules/desktop_capture/desktop_capturer.h" #include "modules/desktop_capture/full_screen_application_handler.h" namespace webrtc { diff --git a/modules/desktop_capture/mac/window_list_utils.cc b/modules/desktop_capture/mac/window_list_utils.cc index 3aeb8dd02b..9eba2ac904 100644 --- a/modules/desktop_capture/mac/window_list_utils.cc +++ b/modules/desktop_capture/mac/window_list_utils.cc @@ -54,7 +54,7 @@ bool ToUtf8(const CFStringRef str16, std::string* str8) { // not represent a window. `on_window` will not be called if false is returned // from this function. bool GetWindowRef(CGWindowID id, - webrtc::FunctionView on_window) { + FunctionView on_window) { RTC_DCHECK(on_window); // TODO(zijiehe): `id` is a 32-bit integer, casting it to an array seems not @@ -85,7 +85,7 @@ bool GetWindowRef(CGWindowID id, } // namespace -bool GetWindowList(webrtc::FunctionView on_window, +bool GetWindowList(FunctionView on_window, bool ignore_minimized, bool only_zero_layer) { RTC_DCHECK(on_window); diff --git a/modules/desktop_capture/mac/window_list_utils.h b/modules/desktop_capture/mac/window_list_utils.h index 98666ec521..bc499f5076 100644 --- a/modules/desktop_capture/mac/window_list_utils.h +++ b/modules/desktop_capture/mac/window_list_utils.h @@ -30,10 +30,9 @@ namespace webrtc { // failed. Menus, dock (if `only_zero_layer`), minimized windows (if // `ignore_minimized` is true) and any windows which do not have a valid window // id or title will be ignored. -bool RTC_EXPORT -GetWindowList(webrtc::FunctionView on_window, - bool ignore_minimized, - bool only_zero_layer); +bool RTC_EXPORT GetWindowList(FunctionView on_window, + bool ignore_minimized, + bool only_zero_layer); // Another helper function to get the on-screen windows. bool RTC_EXPORT GetWindowList(DesktopCapturer::SourceList* windows, diff --git a/modules/desktop_capture/mock_desktop_capturer_callback.cc b/modules/desktop_capture/mock_desktop_capturer_callback.cc index de77d99e18..f581733c73 100644 --- a/modules/desktop_capture/mock_desktop_capturer_callback.cc +++ b/modules/desktop_capture/mock_desktop_capturer_callback.cc @@ -9,6 +9,11 @@ #include "modules/desktop_capture/mock_desktop_capturer_callback.h" +#include + +#include "modules/desktop_capture/desktop_capturer.h" +#include "modules/desktop_capture/desktop_frame.h" + namespace webrtc { MockDesktopCapturerCallback::MockDesktopCapturerCallback() = default; diff --git a/modules/desktop_capture/mouse_cursor.cc b/modules/desktop_capture/mouse_cursor.cc index e826552b0f..16b86254ef 100644 --- a/modules/desktop_capture/mouse_cursor.cc +++ b/modules/desktop_capture/mouse_cursor.cc @@ -11,6 +11,7 @@ #include "modules/desktop_capture/mouse_cursor.h" #include "modules/desktop_capture/desktop_frame.h" +#include "modules/desktop_capture/desktop_geometry.h" #include "rtc_base/checks.h" namespace webrtc { diff --git a/modules/desktop_capture/mouse_cursor_monitor_linux.cc b/modules/desktop_capture/mouse_cursor_monitor_linux.cc index b44500d4e8..c6e8da6c32 100644 --- a/modules/desktop_capture/mouse_cursor_monitor_linux.cc +++ b/modules/desktop_capture/mouse_cursor_monitor_linux.cc @@ -11,6 +11,7 @@ #include #include "modules/desktop_capture/desktop_capture_types.h" +#include "modules/desktop_capture/desktop_capturer.h" #include "modules/desktop_capture/mouse_cursor_monitor.h" #if defined(WEBRTC_USE_X11) diff --git a/modules/desktop_capture/mouse_cursor_monitor_win.cc b/modules/desktop_capture/mouse_cursor_monitor_win.cc index 85b8c5cfab..df48772a06 100644 --- a/modules/desktop_capture/mouse_cursor_monitor_win.cc +++ b/modules/desktop_capture/mouse_cursor_monitor_win.cc @@ -8,8 +8,7 @@ * be found in the AUTHORS file in the root of the source tree. */ -#include - +#include #include #include "modules/desktop_capture/desktop_capture_types.h" @@ -18,7 +17,6 @@ #include "modules/desktop_capture/mouse_cursor.h" #include "modules/desktop_capture/mouse_cursor_monitor.h" #include "modules/desktop_capture/win/cursor.h" -#include "modules/desktop_capture/win/screen_capture_utils.h" #include "modules/desktop_capture/win/window_capture_utils.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" diff --git a/modules/desktop_capture/resolution_tracker.cc b/modules/desktop_capture/resolution_tracker.cc index 9639d627fa..71b05df194 100644 --- a/modules/desktop_capture/resolution_tracker.cc +++ b/modules/desktop_capture/resolution_tracker.cc @@ -10,6 +10,8 @@ #include "modules/desktop_capture/resolution_tracker.h" +#include "modules/desktop_capture/desktop_geometry.h" + namespace webrtc { bool ResolutionTracker::SetResolution(DesktopSize size) { diff --git a/modules/desktop_capture/rgba_color.cc b/modules/desktop_capture/rgba_color.cc index 362928a474..3845746bb0 100644 --- a/modules/desktop_capture/rgba_color.cc +++ b/modules/desktop_capture/rgba_color.cc @@ -10,6 +10,8 @@ #include "modules/desktop_capture/rgba_color.h" +#include + #include "rtc_base/system/arch.h" namespace webrtc { diff --git a/modules/desktop_capture/screen_capturer_fuchsia.cc b/modules/desktop_capture/screen_capturer_fuchsia.cc index 5fb9e39058..5cbe8d2c52 100644 --- a/modules/desktop_capture/screen_capturer_fuchsia.cc +++ b/modules/desktop_capture/screen_capturer_fuchsia.cc @@ -93,7 +93,7 @@ void ScreenCapturerFuchsia::CaptureFrame() { return; } - int64_t capture_start_time_nanos = webrtc::TimeNanos(); + int64_t capture_start_time_nanos = TimeNanos(); zx::event event; zx::event dup; @@ -148,8 +148,8 @@ void ScreenCapturerFuchsia::CaptureFrame() { << release_result.err(); } - int capture_time_ms = (webrtc::TimeNanos() - capture_start_time_nanos) / - webrtc::kNumNanosecsPerMillisec; + int capture_time_ms = + (TimeNanos() - capture_start_time_nanos) / kNumNanosecsPerMillisec; frame->set_capture_time_ms(capture_time_ms); callback_->OnCaptureResult(Result::SUCCESS, std::move(frame)); } diff --git a/modules/desktop_capture/screen_capturer_helper.cc b/modules/desktop_capture/screen_capturer_helper.cc index 04e72b3e9f..ebf9ec7e6a 100644 --- a/modules/desktop_capture/screen_capturer_helper.cc +++ b/modules/desktop_capture/screen_capturer_helper.cc @@ -10,6 +10,11 @@ #include "modules/desktop_capture/screen_capturer_helper.h" +#include "modules/desktop_capture/desktop_geometry.h" +#include "modules/desktop_capture/desktop_region.h" +#include "rtc_base/checks.h" +#include "rtc_base/synchronization/mutex.h" + namespace webrtc { void ScreenCapturerHelper::ClearInvalidRegion() { diff --git a/modules/desktop_capture/screen_capturer_helper.h b/modules/desktop_capture/screen_capturer_helper.h index cd7fa689c0..a91ff8e777 100644 --- a/modules/desktop_capture/screen_capturer_helper.h +++ b/modules/desktop_capture/screen_capturer_helper.h @@ -11,8 +11,6 @@ #ifndef MODULES_DESKTOP_CAPTURE_SCREEN_CAPTURER_HELPER_H_ #define MODULES_DESKTOP_CAPTURE_SCREEN_CAPTURER_HELPER_H_ -#include - #include "modules/desktop_capture/desktop_geometry.h" #include "modules/desktop_capture/desktop_region.h" #include "rtc_base/synchronization/mutex.h" diff --git a/modules/desktop_capture/screen_capturer_helper_unittest.cc b/modules/desktop_capture/screen_capturer_helper_unittest.cc index 165bbe42de..2befa897d6 100644 --- a/modules/desktop_capture/screen_capturer_helper_unittest.cc +++ b/modules/desktop_capture/screen_capturer_helper_unittest.cc @@ -10,6 +10,8 @@ #include "modules/desktop_capture/screen_capturer_helper.h" +#include "modules/desktop_capture/desktop_geometry.h" +#include "modules/desktop_capture/desktop_region.h" #include "test/gtest.h" namespace webrtc { diff --git a/modules/desktop_capture/screen_capturer_linux.cc b/modules/desktop_capture/screen_capturer_linux.cc index 44993837e8..94726750c5 100644 --- a/modules/desktop_capture/screen_capturer_linux.cc +++ b/modules/desktop_capture/screen_capturer_linux.cc @@ -11,6 +11,7 @@ #include #include "modules/desktop_capture/desktop_capture_options.h" +#include "modules/desktop_capture/desktop_capture_types.h" #include "modules/desktop_capture/desktop_capturer.h" #if defined(WEBRTC_USE_PIPEWIRE) diff --git a/modules/desktop_capture/screen_capturer_null.cc b/modules/desktop_capture/screen_capturer_null.cc index 6b1ccb322e..aa6d4991a0 100644 --- a/modules/desktop_capture/screen_capturer_null.cc +++ b/modules/desktop_capture/screen_capturer_null.cc @@ -8,6 +8,8 @@ * be found in the AUTHORS file in the root of the source tree. */ +#include + #include "modules/desktop_capture/desktop_capturer.h" namespace webrtc { diff --git a/modules/desktop_capture/screen_capturer_unittest.cc b/modules/desktop_capture/screen_capturer_unittest.cc index 0176314551..ccbce1c8db 100644 --- a/modules/desktop_capture/screen_capturer_unittest.cc +++ b/modules/desktop_capture/screen_capturer_unittest.cc @@ -8,14 +8,17 @@ * be found in the AUTHORS file in the root of the source tree. */ +#include #include #include "modules/desktop_capture/desktop_capture_options.h" #include "modules/desktop_capture/desktop_capturer.h" #include "modules/desktop_capture/desktop_frame.h" +#include "modules/desktop_capture/desktop_geometry.h" #include "modules/desktop_capture/desktop_region.h" #include "modules/desktop_capture/mock_desktop_capturer_callback.h" -#include "rtc_base/logging.h" +#include "modules/desktop_capture/shared_memory.h" +#include "rtc_base/logging.h" // IWYU pragma: keep #include "test/gmock.h" #include "test/gtest.h" diff --git a/modules/desktop_capture/screen_capturer_win.cc b/modules/desktop_capture/screen_capturer_win.cc index e91764360f..a5f2052979 100644 --- a/modules/desktop_capture/screen_capturer_win.cc +++ b/modules/desktop_capture/screen_capturer_win.cc @@ -16,6 +16,7 @@ #include "modules/desktop_capture/desktop_capturer.h" #include "modules/desktop_capture/fallback_desktop_capturer_wrapper.h" #include "modules/desktop_capture/rgba_color.h" +#include "modules/desktop_capture/win/dxgi_duplicator_controller.h" #include "modules/desktop_capture/win/screen_capturer_win_directx.h" #include "modules/desktop_capture/win/screen_capturer_win_gdi.h" diff --git a/modules/desktop_capture/screen_drawer.cc b/modules/desktop_capture/screen_drawer.cc index 6460f19f65..d66b0eea41 100644 --- a/modules/desktop_capture/screen_drawer.cc +++ b/modules/desktop_capture/screen_drawer.cc @@ -10,6 +10,8 @@ #include "modules/desktop_capture/screen_drawer.h" +#include + namespace webrtc { namespace { diff --git a/modules/desktop_capture/screen_drawer.h b/modules/desktop_capture/screen_drawer.h index ad7c0ad8d1..6f5d3cdbd3 100644 --- a/modules/desktop_capture/screen_drawer.h +++ b/modules/desktop_capture/screen_drawer.h @@ -11,6 +11,8 @@ #ifndef MODULES_DESKTOP_CAPTURE_SCREEN_DRAWER_H_ #define MODULES_DESKTOP_CAPTURE_SCREEN_DRAWER_H_ +#include + #include "modules/desktop_capture/desktop_capture_types.h" #include "modules/desktop_capture/desktop_geometry.h" #include "modules/desktop_capture/rgba_color.h" diff --git a/modules/desktop_capture/screen_drawer_lock_posix.cc b/modules/desktop_capture/screen_drawer_lock_posix.cc index 28cb501fe7..2f17e858e1 100644 --- a/modules/desktop_capture/screen_drawer_lock_posix.cc +++ b/modules/desktop_capture/screen_drawer_lock_posix.cc @@ -11,8 +11,11 @@ #include "modules/desktop_capture/screen_drawer_lock_posix.h" #include +#include #include +#include + #include "absl/strings/string_view.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" @@ -22,7 +25,7 @@ namespace webrtc { namespace { // A uuid as the name of semaphore. -static constexpr char kSemaphoreName[] = "GSDL54fe5552804711e6a7253f429a"; +constexpr char kSemaphoreName[] = "GSDL54fe5552804711e6a7253f429a"; } // namespace diff --git a/modules/desktop_capture/screen_drawer_unittest.cc b/modules/desktop_capture/screen_drawer_unittest.cc index b832b1752c..fac7932bfb 100644 --- a/modules/desktop_capture/screen_drawer_unittest.cc +++ b/modules/desktop_capture/screen_drawer_unittest.cc @@ -10,13 +10,13 @@ #include "modules/desktop_capture/screen_drawer.h" -#include - #include +#include #include #include "api/function_view.h" -#include "rtc_base/checks.h" +#include "modules/desktop_capture/desktop_geometry.h" +#include "modules/desktop_capture/rgba_color.h" #include "rtc_base/logging.h" #include "rtc_base/platform_thread.h" #include "rtc_base/random.h" diff --git a/modules/desktop_capture/screen_drawer_win.cc b/modules/desktop_capture/screen_drawer_win.cc index 76c6081a4d..16b3ae9f66 100644 --- a/modules/desktop_capture/screen_drawer_win.cc +++ b/modules/desktop_capture/screen_drawer_win.cc @@ -10,8 +10,12 @@ #include +#include #include +#include "modules/desktop_capture/desktop_capture_types.h" +#include "modules/desktop_capture/desktop_geometry.h" +#include "modules/desktop_capture/rgba_color.h" #include "modules/desktop_capture/screen_drawer.h" #include "rtc_base/thread.h" diff --git a/modules/desktop_capture/shared_desktop_frame.cc b/modules/desktop_capture/shared_desktop_frame.cc index 538e27b6dd..3dbf1daa87 100644 --- a/modules/desktop_capture/shared_desktop_frame.cc +++ b/modules/desktop_capture/shared_desktop_frame.cc @@ -11,9 +11,11 @@ #include "modules/desktop_capture/shared_desktop_frame.h" #include -#include #include +#include "api/scoped_refptr.h" +#include "modules/desktop_capture/desktop_frame.h" + namespace webrtc { SharedDesktopFrame::~SharedDesktopFrame() {} diff --git a/modules/desktop_capture/shared_memory.cc b/modules/desktop_capture/shared_memory.cc index b4ff78b2a0..ffcac38943 100644 --- a/modules/desktop_capture/shared_memory.cc +++ b/modules/desktop_capture/shared_memory.cc @@ -10,6 +10,8 @@ #include "modules/desktop_capture/shared_memory.h" +#include + namespace webrtc { #if defined(WEBRTC_WIN) diff --git a/modules/desktop_capture/test_utils.cc b/modules/desktop_capture/test_utils.cc index 9483bf41ea..bcfc38317e 100644 --- a/modules/desktop_capture/test_utils.cc +++ b/modules/desktop_capture/test_utils.cc @@ -10,9 +10,10 @@ #include "modules/desktop_capture/test_utils.h" -#include -#include +#include +#include +#include "modules/desktop_capture/desktop_frame.h" #include "modules/desktop_capture/desktop_geometry.h" #include "rtc_base/checks.h" diff --git a/modules/desktop_capture/test_utils_unittest.cc b/modules/desktop_capture/test_utils_unittest.cc index c1326f01cc..4554d12f7d 100644 --- a/modules/desktop_capture/test_utils_unittest.cc +++ b/modules/desktop_capture/test_utils_unittest.cc @@ -10,11 +10,11 @@ #include "modules/desktop_capture/test_utils.h" -#include +#include +#include "modules/desktop_capture/desktop_frame.h" #include "modules/desktop_capture/desktop_geometry.h" #include "modules/desktop_capture/rgba_color.h" -#include "rtc_base/checks.h" #include "test/gtest.h" namespace webrtc { diff --git a/modules/desktop_capture/win/cursor.cc b/modules/desktop_capture/win/cursor.cc index 82fe43ee0c..be8ccae0ff 100644 --- a/modules/desktop_capture/win/cursor.cc +++ b/modules/desktop_capture/win/cursor.cc @@ -10,7 +10,9 @@ #include "modules/desktop_capture/win/cursor.h" -#include +#include +#include +#include #include #include "modules/desktop_capture/desktop_frame.h" diff --git a/modules/desktop_capture/win/d3d_device.cc b/modules/desktop_capture/win/d3d_device.cc index 3d46117501..c19c87aee1 100644 --- a/modules/desktop_capture/win/d3d_device.cc +++ b/modules/desktop_capture/win/d3d_device.cc @@ -11,6 +11,7 @@ #include "modules/desktop_capture/win/d3d_device.h" #include +#include #include "modules/desktop_capture/win/desktop_capture_utils.h" #include "rtc_base/logging.h" diff --git a/modules/desktop_capture/win/desktop.cc b/modules/desktop_capture/win/desktop.cc index b062ee0cc1..9dfb924415 100644 --- a/modules/desktop_capture/win/desktop.cc +++ b/modules/desktop_capture/win/desktop.cc @@ -10,6 +10,8 @@ #include "modules/desktop_capture/win/desktop.h" +#include +#include #include #include "rtc_base/logging.h" diff --git a/modules/desktop_capture/win/desktop_capture_utils.cc b/modules/desktop_capture/win/desktop_capture_utils.cc index 4acd31c5cb..18c8fa3f53 100644 --- a/modules/desktop_capture/win/desktop_capture_utils.cc +++ b/modules/desktop_capture/win/desktop_capture_utils.cc @@ -10,6 +10,8 @@ #include "modules/desktop_capture/win/desktop_capture_utils.h" +#include + #include "rtc_base/strings/string_builder.h" namespace webrtc { diff --git a/modules/desktop_capture/win/display_configuration_monitor.cc b/modules/desktop_capture/win/display_configuration_monitor.cc index 6bc92695d9..ae9db42dbc 100644 --- a/modules/desktop_capture/win/display_configuration_monitor.cc +++ b/modules/desktop_capture/win/display_configuration_monitor.cc @@ -12,6 +12,11 @@ #include +#include + +#include "modules/desktop_capture/desktop_capture_types.h" +#include "modules/desktop_capture/desktop_capturer.h" +#include "modules/desktop_capture/desktop_geometry.h" #include "modules/desktop_capture/win/screen_capture_utils.h" #include "rtc_base/logging.h" diff --git a/modules/desktop_capture/win/dxgi_adapter_duplicator.cc b/modules/desktop_capture/win/dxgi_adapter_duplicator.cc index d3d7ea03a3..8f624c6696 100644 --- a/modules/desktop_capture/win/dxgi_adapter_duplicator.cc +++ b/modules/desktop_capture/win/dxgi_adapter_duplicator.cc @@ -12,10 +12,20 @@ #include #include +#include #include - +#include +#include +#include +#include +#include + +#include "modules/desktop_capture/desktop_geometry.h" +#include "modules/desktop_capture/shared_desktop_frame.h" +#include "modules/desktop_capture/win/d3d_device.h" #include "modules/desktop_capture/win/desktop_capture_utils.h" +#include "modules/desktop_capture/win/dxgi_output_duplicator.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" diff --git a/modules/desktop_capture/win/dxgi_adapter_duplicator.h b/modules/desktop_capture/win/dxgi_adapter_duplicator.h index 4779a3bfb9..096e853560 100644 --- a/modules/desktop_capture/win/dxgi_adapter_duplicator.h +++ b/modules/desktop_capture/win/dxgi_adapter_duplicator.h @@ -11,8 +11,9 @@ #ifndef MODULES_DESKTOP_CAPTURE_WIN_DXGI_ADAPTER_DUPLICATOR_H_ #define MODULES_DESKTOP_CAPTURE_WIN_DXGI_ADAPTER_DUPLICATOR_H_ -#include - +#include +#include +#include #include #include "modules/desktop_capture/desktop_geometry.h" diff --git a/modules/desktop_capture/win/dxgi_duplicator_controller.cc b/modules/desktop_capture/win/dxgi_duplicator_controller.cc index 24d8ad18f0..a140029d78 100644 --- a/modules/desktop_capture/win/dxgi_duplicator_controller.cc +++ b/modules/desktop_capture/win/dxgi_duplicator_controller.cc @@ -13,13 +13,24 @@ #include #include +#include +#include +#include +#include #include - -#include "modules/desktop_capture/desktop_capture_types.h" +#include +#include + +#include "api/scoped_refptr.h" +#include "modules/desktop_capture/desktop_frame.h" +#include "modules/desktop_capture/desktop_geometry.h" +#include "modules/desktop_capture/shared_desktop_frame.h" +#include "modules/desktop_capture/win/d3d_device.h" +#include "modules/desktop_capture/win/dxgi_adapter_duplicator.h" #include "modules/desktop_capture/win/dxgi_frame.h" -#include "modules/desktop_capture/win/screen_capture_utils.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" +#include "rtc_base/synchronization/mutex.h" #include "rtc_base/thread.h" #include "rtc_base/time_utils.h" @@ -72,7 +83,7 @@ DxgiDuplicatorController::Instance() { // The static instance won't be deleted to ensure it can be used by other // threads even during program exiting. static DxgiDuplicatorController* instance = new DxgiDuplicatorController(); - return webrtc::scoped_refptr(instance); + return scoped_refptr(instance); } // static @@ -504,7 +515,7 @@ bool DxgiDuplicatorController::EnsureFrameCaptured(Context* context, shared_frame = fallback_frame.get(); } - const int64_t start_ms = webrtc::TimeMillis(); + const int64_t start_ms = TimeMillis(); while (GetNumFramesCaptured(monitor_id) < frames_to_skip) { if (monitor_id < 0) { if (!DoDuplicateAll(context, shared_frame)) { @@ -521,7 +532,7 @@ bool DxgiDuplicatorController::EnsureFrameCaptured(Context* context, break; } - if (webrtc::TimeMillis() - start_ms > timeout_ms) { + if (TimeMillis() - start_ms > timeout_ms) { RTC_LOG(LS_ERROR) << "Failed to capture " << frames_to_skip << " frames " "within " diff --git a/modules/desktop_capture/win/dxgi_duplicator_controller.h b/modules/desktop_capture/win/dxgi_duplicator_controller.h index a63bafbf6e..c1b82547de 100644 --- a/modules/desktop_capture/win/dxgi_duplicator_controller.h +++ b/modules/desktop_capture/win/dxgi_duplicator_controller.h @@ -14,19 +14,21 @@ #include #include +#include +#include #include #include #include "api/scoped_refptr.h" #include "modules/desktop_capture/desktop_geometry.h" #include "modules/desktop_capture/shared_desktop_frame.h" -#include "modules/desktop_capture/win/d3d_device.h" #include "modules/desktop_capture/win/display_configuration_monitor.h" #include "modules/desktop_capture/win/dxgi_adapter_duplicator.h" #include "modules/desktop_capture/win/dxgi_context.h" #include "modules/desktop_capture/win/dxgi_frame.h" #include "rtc_base/synchronization/mutex.h" #include "rtc_base/system/rtc_export.h" +#include "rtc_base/thread_annotations.h" namespace webrtc { @@ -82,7 +84,7 @@ class RTC_EXPORT DxgiDuplicatorController { static std::string ResultName(Result result); // Returns the singleton instance of DxgiDuplicatorController. - static webrtc::scoped_refptr Instance(); + static scoped_refptr Instance(); // See ScreenCapturerWinDirectx::IsCurrentSessionSupported(). static bool IsCurrentSessionSupported(); @@ -132,7 +134,7 @@ class RTC_EXPORT DxgiDuplicatorController { // scoped_refptr accesses private AddRef() and // Release() functions. - friend class webrtc::scoped_refptr; + friend class scoped_refptr; // A private constructor to ensure consumers to use // DxgiDuplicatorController::Instance(). diff --git a/modules/desktop_capture/win/dxgi_frame.cc b/modules/desktop_capture/win/dxgi_frame.cc index 55495aec26..a35e93d39d 100644 --- a/modules/desktop_capture/win/dxgi_frame.cc +++ b/modules/desktop_capture/win/dxgi_frame.cc @@ -10,12 +10,15 @@ #include "modules/desktop_capture/win/dxgi_frame.h" -#include - +#include +#include #include +#include "modules/desktop_capture/desktop_capturer.h" #include "modules/desktop_capture/desktop_frame.h" -#include "modules/desktop_capture/win/dxgi_duplicator_controller.h" +#include "modules/desktop_capture/desktop_geometry.h" +#include "modules/desktop_capture/shared_desktop_frame.h" +#include "modules/desktop_capture/shared_memory.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" diff --git a/modules/desktop_capture/win/dxgi_frame.h b/modules/desktop_capture/win/dxgi_frame.h index 6a9ce868a7..5c571a886a 100644 --- a/modules/desktop_capture/win/dxgi_frame.h +++ b/modules/desktop_capture/win/dxgi_frame.h @@ -12,7 +12,6 @@ #define MODULES_DESKTOP_CAPTURE_WIN_DXGI_FRAME_H_ #include -#include #include "modules/desktop_capture/desktop_capture_types.h" #include "modules/desktop_capture/desktop_capturer.h" diff --git a/modules/desktop_capture/win/dxgi_output_duplicator.cc b/modules/desktop_capture/win/dxgi_output_duplicator.cc index 706265a7ed..f07a55af46 100644 --- a/modules/desktop_capture/win/dxgi_output_duplicator.cc +++ b/modules/desktop_capture/win/dxgi_output_duplicator.cc @@ -12,12 +12,20 @@ #include #include -#include #include #include #include - +#include +#include +#include + +#include "modules/desktop_capture/desktop_frame.h" +#include "modules/desktop_capture/desktop_frame_rotation.h" +#include "modules/desktop_capture/desktop_geometry.h" +#include "modules/desktop_capture/desktop_region.h" +#include "modules/desktop_capture/shared_desktop_frame.h" +#include "modules/desktop_capture/win/d3d_device.h" #include "modules/desktop_capture/win/desktop_capture_utils.h" #include "modules/desktop_capture/win/dxgi_texture_mapping.h" #include "modules/desktop_capture/win/dxgi_texture_staging.h" @@ -67,7 +75,7 @@ DxgiOutputDuplicator::DxgiOutputDuplicator(const D3dDevice& device, const DXGI_OUTPUT_DESC& desc) : device_(device), output_(output), - device_name_(webrtc::ToUtf8(desc.DeviceName)), + device_name_(ToUtf8(desc.DeviceName)), desktop_rect_(RECTToDesktopRect(desc.DesktopCoordinates)), monitor_(desc.Monitor) { RTC_DCHECK(output_); diff --git a/modules/desktop_capture/win/dxgi_output_duplicator.h b/modules/desktop_capture/win/dxgi_output_duplicator.h index e2a87751d6..c12e70e003 100644 --- a/modules/desktop_capture/win/dxgi_output_duplicator.h +++ b/modules/desktop_capture/win/dxgi_output_duplicator.h @@ -17,7 +17,9 @@ #include #include +#include #include +#include #include #include @@ -28,7 +30,6 @@ #include "modules/desktop_capture/win/d3d_device.h" #include "modules/desktop_capture/win/dxgi_context.h" #include "modules/desktop_capture/win/dxgi_texture.h" -#include "rtc_base/thread_annotations.h" namespace webrtc { diff --git a/modules/desktop_capture/win/dxgi_texture.cc b/modules/desktop_capture/win/dxgi_texture.cc index b8f5b81f90..1a6eb2e2d4 100644 --- a/modules/desktop_capture/win/dxgi_texture.cc +++ b/modules/desktop_capture/win/dxgi_texture.cc @@ -12,9 +12,12 @@ #include #include +#include +#include +#include #include -#include "modules/desktop_capture/desktop_region.h" +#include "modules/desktop_capture/desktop_frame.h" #include "modules/desktop_capture/win/desktop_capture_utils.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" diff --git a/modules/desktop_capture/win/dxgi_texture.h b/modules/desktop_capture/win/dxgi_texture.h index a663b95a04..b68f022329 100644 --- a/modules/desktop_capture/win/dxgi_texture.h +++ b/modules/desktop_capture/win/dxgi_texture.h @@ -12,8 +12,10 @@ #define MODULES_DESKTOP_CAPTURE_WIN_DXGI_TEXTURE_H_ #include +#include #include +#include #include #include "modules/desktop_capture/desktop_frame.h" diff --git a/modules/desktop_capture/win/dxgi_texture_mapping.cc b/modules/desktop_capture/win/dxgi_texture_mapping.cc index 7ecf1adc61..277153815f 100644 --- a/modules/desktop_capture/win/dxgi_texture_mapping.cc +++ b/modules/desktop_capture/win/dxgi_texture_mapping.cc @@ -11,8 +11,10 @@ #include "modules/desktop_capture/win/dxgi_texture_mapping.h" #include +#include #include #include +#include #include "modules/desktop_capture/win/desktop_capture_utils.h" #include "rtc_base/checks.h" diff --git a/modules/desktop_capture/win/dxgi_texture_mapping.h b/modules/desktop_capture/win/dxgi_texture_mapping.h index 71f00b99ab..afcbcc3303 100644 --- a/modules/desktop_capture/win/dxgi_texture_mapping.h +++ b/modules/desktop_capture/win/dxgi_texture_mapping.h @@ -14,8 +14,6 @@ #include #include -#include "modules/desktop_capture/desktop_geometry.h" -#include "modules/desktop_capture/desktop_region.h" #include "modules/desktop_capture/win/dxgi_texture.h" namespace webrtc { diff --git a/modules/desktop_capture/win/dxgi_texture_staging.cc b/modules/desktop_capture/win/dxgi_texture_staging.cc index 17e8518a7d..e9e57f7b16 100644 --- a/modules/desktop_capture/win/dxgi_texture_staging.cc +++ b/modules/desktop_capture/win/dxgi_texture_staging.cc @@ -11,10 +11,16 @@ #include "modules/desktop_capture/win/dxgi_texture_staging.h" #include +#include #include #include #include +#include +#include +#include + +#include "modules/desktop_capture/win/d3d_device.h" #include "modules/desktop_capture/win/desktop_capture_utils.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" diff --git a/modules/desktop_capture/win/dxgi_texture_staging.h b/modules/desktop_capture/win/dxgi_texture_staging.h index e8c2af6662..58a3d0fb3f 100644 --- a/modules/desktop_capture/win/dxgi_texture_staging.h +++ b/modules/desktop_capture/win/dxgi_texture_staging.h @@ -12,11 +12,11 @@ #define MODULES_DESKTOP_CAPTURE_WIN_DXGI_TEXTURE_STAGING_H_ #include +#include #include #include #include "modules/desktop_capture/desktop_geometry.h" -#include "modules/desktop_capture/desktop_region.h" #include "modules/desktop_capture/win/d3d_device.h" #include "modules/desktop_capture/win/dxgi_texture.h" diff --git a/modules/desktop_capture/win/full_screen_win_application_handler.cc b/modules/desktop_capture/win/full_screen_win_application_handler.cc index fa15b3e7e0..8f01d6a26b 100644 --- a/modules/desktop_capture/win/full_screen_win_application_handler.cc +++ b/modules/desktop_capture/win/full_screen_win_application_handler.cc @@ -11,16 +11,20 @@ #include "modules/desktop_capture/win/full_screen_win_application_handler.h" #include +#include +#include +#include #include +#include #include #include #include #include "absl/strings/ascii.h" #include "absl/strings/match.h" -#include "modules/desktop_capture/win/screen_capture_utils.h" -#include "modules/desktop_capture/win/window_capture_utils.h" -#include "rtc_base/arraysize.h" +#include "absl/strings/string_view.h" +#include "modules/desktop_capture/desktop_capturer.h" +#include "modules/desktop_capture/full_screen_application_handler.h" #include "rtc_base/logging.h" // For RTC_LOG_GLE #include "rtc_base/string_utils.h" @@ -59,7 +63,7 @@ std::string WindowText(HWND window) { if (copied == 0) { return std::string(); } - return webrtc::ToUtf8(buffer.data(), copied); + return ToUtf8(buffer.data(), copied); } DWORD WindowProcessId(HWND window) { diff --git a/modules/desktop_capture/win/full_screen_win_application_handler.h b/modules/desktop_capture/win/full_screen_win_application_handler.h index 706e96eaef..7aebff50fa 100644 --- a/modules/desktop_capture/win/full_screen_win_application_handler.h +++ b/modules/desktop_capture/win/full_screen_win_application_handler.h @@ -11,10 +11,14 @@ #ifndef MODULES_DESKTOP_CAPTURE_WIN_FULL_SCREEN_WIN_APPLICATION_HANDLER_H_ #define MODULES_DESKTOP_CAPTURE_WIN_FULL_SCREEN_WIN_APPLICATION_HANDLER_H_ +#include + +#include #include +#include +#include "modules/desktop_capture/desktop_capturer.h" #include "modules/desktop_capture/full_screen_application_handler.h" -#include "modules/desktop_capture/win/window_capture_utils.h" namespace webrtc { diff --git a/modules/desktop_capture/win/scoped_gdi_object.h b/modules/desktop_capture/win/scoped_gdi_object.h index 2b01941e20..93ca6e4899 100644 --- a/modules/desktop_capture/win/scoped_gdi_object.h +++ b/modules/desktop_capture/win/scoped_gdi_object.h @@ -13,6 +13,8 @@ #include +#include + namespace webrtc { namespace win { diff --git a/modules/desktop_capture/win/scoped_thread_desktop.cc b/modules/desktop_capture/win/scoped_thread_desktop.cc index 22e8e7bc8f..1cf6f1ba7d 100644 --- a/modules/desktop_capture/win/scoped_thread_desktop.cc +++ b/modules/desktop_capture/win/scoped_thread_desktop.cc @@ -10,6 +10,11 @@ #include "modules/desktop_capture/win/scoped_thread_desktop.h" +#include + +#include +#include + #include "modules/desktop_capture/win/desktop.h" namespace webrtc { diff --git a/modules/desktop_capture/win/scoped_thread_desktop.h b/modules/desktop_capture/win/scoped_thread_desktop.h index 98f151a46c..983af5d0cc 100644 --- a/modules/desktop_capture/win/scoped_thread_desktop.h +++ b/modules/desktop_capture/win/scoped_thread_desktop.h @@ -11,8 +11,6 @@ #ifndef MODULES_DESKTOP_CAPTURE_WIN_SCOPED_THREAD_DESKTOP_H_ #define MODULES_DESKTOP_CAPTURE_WIN_SCOPED_THREAD_DESKTOP_H_ -#include - #include #include "rtc_base/system/rtc_export.h" diff --git a/modules/desktop_capture/win/screen_capture_utils.cc b/modules/desktop_capture/win/screen_capture_utils.cc index 8ac8bfcd0c..28509654c4 100644 --- a/modules/desktop_capture/win/screen_capture_utils.cc +++ b/modules/desktop_capture/win/screen_capture_utils.cc @@ -13,9 +13,12 @@ #include #include +#include +#include #include #include +#include "modules/desktop_capture/desktop_capture_types.h" #include "modules/desktop_capture/desktop_capturer.h" #include "modules/desktop_capture/desktop_geometry.h" #include "rtc_base/checks.h" @@ -54,7 +57,7 @@ bool GetScreenList(DesktopCapturer::SourceList* screens, screens->push_back({device_index, std::string()}); if (device_names) { - device_names->push_back(webrtc::ToUtf8(device.DeviceName)); + device_names->push_back(ToUtf8(device.DeviceName)); } } return true; diff --git a/modules/desktop_capture/win/screen_capture_utils.h b/modules/desktop_capture/win/screen_capture_utils.h index 68407f5fda..7e95dde9d4 100644 --- a/modules/desktop_capture/win/screen_capture_utils.h +++ b/modules/desktop_capture/win/screen_capture_utils.h @@ -11,6 +11,14 @@ #ifndef MODULES_DESKTOP_CAPTURE_WIN_SCREEN_CAPTURE_UTILS_H_ #define MODULES_DESKTOP_CAPTURE_WIN_SCREEN_CAPTURE_UTILS_H_ +#include +#include +#include + +#include "modules/desktop_capture/desktop_capturer.h" +#include "modules/desktop_capture/desktop_geometry.h" +#include "rtc_base/system/rtc_export.h" + #if defined(WEBRTC_WIN) // Forward declare HMONITOR in a windows.h compatible way so that we can avoid // including windows.h. @@ -21,12 +29,6 @@ WEBRTC_DECLARE_HANDLE(HMONITOR); #undef WEBRTC_DECLARE_HANDLE #endif -#include -#include - -#include "modules/desktop_capture/desktop_capturer.h" -#include "rtc_base/system/rtc_export.h" - namespace webrtc { // Returns true if the system has at least one active display. diff --git a/modules/desktop_capture/win/screen_capturer_win_directx.cc b/modules/desktop_capture/win/screen_capturer_win_directx.cc index 9bf22d8ac6..e2e67497b0 100644 --- a/modules/desktop_capture/win/screen_capturer_win_directx.cc +++ b/modules/desktop_capture/win/screen_capturer_win_directx.cc @@ -10,15 +10,25 @@ #include "modules/desktop_capture/win/screen_capturer_win_directx.h" +#include + #include +#include +#include #include #include #include #include #include "modules/desktop_capture/desktop_capture_metrics_helper.h" +#include "modules/desktop_capture/desktop_capture_options.h" #include "modules/desktop_capture/desktop_capture_types.h" +#include "modules/desktop_capture/desktop_capturer.h" #include "modules/desktop_capture/desktop_frame.h" +#include "modules/desktop_capture/screen_capture_frame_queue.h" +#include "modules/desktop_capture/shared_memory.h" +#include "modules/desktop_capture/win/dxgi_duplicator_controller.h" +#include "modules/desktop_capture/win/dxgi_frame.h" #include "modules/desktop_capture/win/screen_capture_utils.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" @@ -129,7 +139,7 @@ void ScreenCapturerWinDirectx::CaptureFrame() { RTC_DCHECK(callback_); TRACE_EVENT0("webrtc", "ScreenCapturerWinDirectx::CaptureFrame"); - int64_t capture_start_time_nanos = webrtc::TimeNanos(); + int64_t capture_start_time_nanos = TimeNanos(); // Note that the [] operator will create the ScreenCaptureFrameQueue if it // doesn't exist, so this is safe. @@ -190,8 +200,8 @@ void ScreenCapturerWinDirectx::CaptureFrame() { std::unique_ptr frame = frames.current_frame()->frame()->Share(); - int capture_time_ms = (webrtc::TimeNanos() - capture_start_time_nanos) / - webrtc::kNumNanosecsPerMillisec; + int capture_time_ms = + (TimeNanos() - capture_start_time_nanos) / kNumNanosecsPerMillisec; RTC_HISTOGRAM_COUNTS_1000( "WebRTC.DesktopCapture.Win.DirectXCapturerFrameTime", capture_time_ms); diff --git a/modules/desktop_capture/win/screen_capturer_win_directx.h b/modules/desktop_capture/win/screen_capturer_win_directx.h index ea1deb9293..9bc095309e 100644 --- a/modules/desktop_capture/win/screen_capturer_win_directx.h +++ b/modules/desktop_capture/win/screen_capturer_win_directx.h @@ -11,17 +11,17 @@ #ifndef MODULES_DESKTOP_CAPTURE_WIN_SCREEN_CAPTURER_WIN_DIRECTX_H_ #define MODULES_DESKTOP_CAPTURE_WIN_SCREEN_CAPTURER_WIN_DIRECTX_H_ -#include - #include +#include #include #include #include "api/scoped_refptr.h" #include "modules/desktop_capture/desktop_capture_options.h" +#include "modules/desktop_capture/desktop_capture_types.h" #include "modules/desktop_capture/desktop_capturer.h" -#include "modules/desktop_capture/desktop_region.h" #include "modules/desktop_capture/screen_capture_frame_queue.h" +#include "modules/desktop_capture/shared_memory.h" #include "modules/desktop_capture/win/dxgi_duplicator_controller.h" #include "modules/desktop_capture/win/dxgi_frame.h" #include "rtc_base/system/rtc_export.h" @@ -88,7 +88,7 @@ class RTC_EXPORT ScreenCapturerWinDirectx : public DesktopCapturer { bool SelectSource(SourceId id) override; private: - const webrtc::scoped_refptr controller_; + const scoped_refptr controller_; DesktopCaptureOptions options_; // The underlying DxgiDuplicators may retain a reference to the frames that diff --git a/modules/desktop_capture/win/screen_capturer_win_directx_unittest.cc b/modules/desktop_capture/win/screen_capturer_win_directx_unittest.cc index c9f46f782c..5bbe35cfd1 100644 --- a/modules/desktop_capture/win/screen_capturer_win_directx_unittest.cc +++ b/modules/desktop_capture/win/screen_capturer_win_directx_unittest.cc @@ -10,6 +10,7 @@ #include "modules/desktop_capture/win/screen_capturer_win_directx.h" +#include #include #include diff --git a/modules/desktop_capture/win/screen_capturer_win_gdi.cc b/modules/desktop_capture/win/screen_capturer_win_gdi.cc index 9e65b7fa41..7f25e37313 100644 --- a/modules/desktop_capture/win/screen_capturer_win_gdi.cc +++ b/modules/desktop_capture/win/screen_capturer_win_gdi.cc @@ -10,6 +10,11 @@ #include "modules/desktop_capture/win/screen_capturer_win_gdi.h" +#include +#include +#include +#include +#include #include #include "modules/desktop_capture/desktop_capture_metrics_helper.h" @@ -17,9 +22,10 @@ #include "modules/desktop_capture/desktop_capture_types.h" #include "modules/desktop_capture/desktop_frame.h" #include "modules/desktop_capture/desktop_frame_win.h" +#include "modules/desktop_capture/desktop_geometry.h" #include "modules/desktop_capture/desktop_region.h" -#include "modules/desktop_capture/mouse_cursor.h" -#include "modules/desktop_capture/win/cursor.h" +#include "modules/desktop_capture/shared_desktop_frame.h" +#include "modules/desktop_capture/shared_memory.h" #include "modules/desktop_capture/win/desktop.h" #include "modules/desktop_capture/win/screen_capture_utils.h" #include "rtc_base/checks.h" @@ -75,7 +81,7 @@ void ScreenCapturerWinGdi::SetSharedMemoryFactory( void ScreenCapturerWinGdi::CaptureFrame() { TRACE_EVENT0("webrtc", "ScreenCapturerWinGdi::CaptureFrame"); - int64_t capture_start_time_nanos = webrtc::TimeNanos(); + int64_t capture_start_time_nanos = TimeNanos(); queue_.MoveToNextFrame(); if (queue_.current_frame() && queue_.current_frame()->IsShared()) { @@ -98,8 +104,8 @@ void ScreenCapturerWinGdi::CaptureFrame() { frame->mutable_updated_region()->SetRect( DesktopRect::MakeSize(frame->size())); - int capture_time_ms = (webrtc::TimeNanos() - capture_start_time_nanos) / - webrtc::kNumNanosecsPerMillisec; + int capture_time_ms = + (TimeNanos() - capture_start_time_nanos) / kNumNanosecsPerMillisec; RTC_HISTOGRAM_COUNTS_1000( "WebRTC.DesktopCapture.Win.ScreenGdiCapturerFrameTime", capture_time_ms); frame->set_capture_time_ms(capture_time_ms); @@ -108,7 +114,7 @@ void ScreenCapturerWinGdi::CaptureFrame() { } bool ScreenCapturerWinGdi::GetSourceList(SourceList* sources) { - return webrtc::GetScreenList(sources); + return GetScreenList(sources); } bool ScreenCapturerWinGdi::SelectSource(SourceId id) { diff --git a/modules/desktop_capture/win/screen_capturer_win_gdi.h b/modules/desktop_capture/win/screen_capturer_win_gdi.h index 6e103aea4d..ecbeb41bab 100644 --- a/modules/desktop_capture/win/screen_capturer_win_gdi.h +++ b/modules/desktop_capture/win/screen_capturer_win_gdi.h @@ -13,11 +13,16 @@ #include +#include #include +#include +#include +#include "modules/desktop_capture/desktop_capture_types.h" #include "modules/desktop_capture/desktop_capturer.h" #include "modules/desktop_capture/screen_capture_frame_queue.h" #include "modules/desktop_capture/shared_desktop_frame.h" +#include "modules/desktop_capture/shared_memory.h" #include "modules/desktop_capture/win/display_configuration_monitor.h" #include "modules/desktop_capture/win/scoped_thread_desktop.h" diff --git a/modules/desktop_capture/win/screen_capturer_win_magnifier.cc b/modules/desktop_capture/win/screen_capturer_win_magnifier.cc index bb445129fc..95ac9968ca 100644 --- a/modules/desktop_capture/win/screen_capturer_win_magnifier.cc +++ b/modules/desktop_capture/win/screen_capturer_win_magnifier.cc @@ -10,16 +10,20 @@ #include "modules/desktop_capture/win/screen_capturer_win_magnifier.h" +#include +#include +#include +#include +#include #include #include "modules/desktop_capture/desktop_capture_metrics_helper.h" -#include "modules/desktop_capture/desktop_capture_options.h" #include "modules/desktop_capture/desktop_capture_types.h" #include "modules/desktop_capture/desktop_frame.h" -#include "modules/desktop_capture/desktop_frame_win.h" +#include "modules/desktop_capture/desktop_geometry.h" #include "modules/desktop_capture/desktop_region.h" -#include "modules/desktop_capture/mouse_cursor.h" -#include "modules/desktop_capture/win/cursor.h" +#include "modules/desktop_capture/shared_desktop_frame.h" +#include "modules/desktop_capture/shared_memory.h" #include "modules/desktop_capture/win/desktop.h" #include "modules/desktop_capture/win/screen_capture_utils.h" #include "rtc_base/checks.h" @@ -87,7 +91,7 @@ void ScreenCapturerWinMagnifier::CaptureFrame() { return; } - int64_t capture_start_time_nanos = webrtc::TimeNanos(); + int64_t capture_start_time_nanos = TimeNanos(); // Switch to the desktop receiving user input if different from the current // one. @@ -121,8 +125,8 @@ void ScreenCapturerWinMagnifier::CaptureFrame() { frame->mutable_updated_region()->SetRect( DesktopRect::MakeSize(frame->size())); - int capture_time_ms = (webrtc::TimeNanos() - capture_start_time_nanos) / - webrtc::kNumNanosecsPerMillisec; + int capture_time_ms = + (TimeNanos() - capture_start_time_nanos) / kNumNanosecsPerMillisec; RTC_HISTOGRAM_COUNTS_1000( "WebRTC.DesktopCapture.Win.MagnifierCapturerFrameTime", capture_time_ms); frame->set_capture_time_ms(capture_time_ms); @@ -131,7 +135,7 @@ void ScreenCapturerWinMagnifier::CaptureFrame() { } bool ScreenCapturerWinMagnifier::GetSourceList(SourceList* sources) { - return webrtc::GetScreenList(sources); + return GetScreenList(sources); } bool ScreenCapturerWinMagnifier::SelectSource(SourceId id) { diff --git a/modules/desktop_capture/win/screen_capturer_win_magnifier.h b/modules/desktop_capture/win/screen_capturer_win_magnifier.h index 80cf6d410b..80937054da 100644 --- a/modules/desktop_capture/win/screen_capturer_win_magnifier.h +++ b/modules/desktop_capture/win/screen_capturer_win_magnifier.h @@ -11,16 +11,22 @@ #ifndef MODULES_DESKTOP_CAPTURE_WIN_SCREEN_CAPTURER_WIN_MAGNIFIER_H_ #define MODULES_DESKTOP_CAPTURE_WIN_SCREEN_CAPTURER_WIN_MAGNIFIER_H_ +#include #include #include #include +#include #include +#include +#include +#include "modules/desktop_capture/desktop_capture_types.h" #include "modules/desktop_capture/desktop_capturer.h" +#include "modules/desktop_capture/desktop_geometry.h" #include "modules/desktop_capture/screen_capture_frame_queue.h" -#include "modules/desktop_capture/screen_capturer_helper.h" #include "modules/desktop_capture/shared_desktop_frame.h" +#include "modules/desktop_capture/shared_memory.h" #include "modules/desktop_capture/win/scoped_thread_desktop.h" namespace webrtc { diff --git a/modules/desktop_capture/win/selected_window_context.cc b/modules/desktop_capture/win/selected_window_context.cc index 398ea1e53a..868192e789 100644 --- a/modules/desktop_capture/win/selected_window_context.cc +++ b/modules/desktop_capture/win/selected_window_context.cc @@ -10,6 +10,9 @@ #include "modules/desktop_capture/win/selected_window_context.h" +#include "modules/desktop_capture/desktop_geometry.h" +#include "modules/desktop_capture/win/window_capture_utils.h" + namespace webrtc { SelectedWindowContext::SelectedWindowContext( diff --git a/modules/desktop_capture/win/test_support/test_window.cc b/modules/desktop_capture/win/test_support/test_window.cc index 2b7d132630..b699bf4ed0 100644 --- a/modules/desktop_capture/win/test_support/test_window.cc +++ b/modules/desktop_capture/win/test_support/test_window.cc @@ -10,6 +10,8 @@ #include "modules/desktop_capture/win/test_support/test_window.h" +#include + namespace webrtc { namespace { diff --git a/modules/desktop_capture/win/test_support/test_window.h b/modules/desktop_capture/win/test_support/test_window.h index a30d4532c4..460acd35f2 100644 --- a/modules/desktop_capture/win/test_support/test_window.h +++ b/modules/desktop_capture/win/test_support/test_window.h @@ -10,9 +10,6 @@ #ifndef MODULES_DESKTOP_CAPTURE_WIN_TEST_SUPPORT_TEST_WINDOW_H_ #define MODULES_DESKTOP_CAPTURE_WIN_TEST_SUPPORT_TEST_WINDOW_H_ -#ifndef WIN32_LEAN_AND_MEAN -#define WIN32_LEAN_AND_MEAN -#endif #include namespace webrtc { diff --git a/modules/desktop_capture/win/wgc_capture_session.cc b/modules/desktop_capture/win/wgc_capture_session.cc index da9054e0eb..039a49cf29 100644 --- a/modules/desktop_capture/win/wgc_capture_session.cc +++ b/modules/desktop_capture/win/wgc_capture_session.cc @@ -16,16 +16,20 @@ #include #include +#include +#include #include #include -#include +#include "api/sequence_checker.h" +#include "modules/desktop_capture/desktop_capture_options.h" +#include "modules/desktop_capture/desktop_frame.h" +#include "modules/desktop_capture/desktop_geometry.h" +#include "modules/desktop_capture/shared_desktop_frame.h" #include "modules/desktop_capture/win/screen_capture_utils.h" -#include "modules/desktop_capture/win/wgc_desktop_frame.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "rtc_base/thread.h" -#include "rtc_base/time_utils.h" #include "rtc_base/win/create_direct3d_device.h" #include "rtc_base/win/get_activation_factory.h" #include "rtc_base/win/windows_version.h" @@ -98,8 +102,7 @@ bool SizeHasChanged(ABI::Windows::Graphics::SizeInt32 size_new, } bool DoesWgcSkipStaticFrames() { - return (webrtc::rtc_win::GetVersion() >= - webrtc::rtc_win::Version::VERSION_WIN11_24H2); + return (rtc_win::GetVersion() >= rtc_win::Version::VERSION_WIN11_24H2); } } // namespace diff --git a/modules/desktop_capture/win/wgc_capture_session.h b/modules/desktop_capture/win/wgc_capture_session.h index ca88b061a1..b62c352917 100644 --- a/modules/desktop_capture/win/wgc_capture_session.h +++ b/modules/desktop_capture/win/wgc_capture_session.h @@ -17,14 +17,16 @@ #include #include +#include #include +#include #include "api/sequence_checker.h" #include "modules/desktop_capture/desktop_capture_options.h" +#include "modules/desktop_capture/desktop_frame.h" +#include "modules/desktop_capture/desktop_region.h" #include "modules/desktop_capture/screen_capture_frame_queue.h" #include "modules/desktop_capture/shared_desktop_frame.h" -#include "modules/desktop_capture/win/wgc_capture_source.h" -#include "rtc_base/event.h" namespace webrtc { diff --git a/modules/desktop_capture/win/wgc_capture_source.cc b/modules/desktop_capture/win/wgc_capture_source.cc index 1688878cde..86444cb3a6 100644 --- a/modules/desktop_capture/win/wgc_capture_source.cc +++ b/modules/desktop_capture/win/wgc_capture_source.cc @@ -14,8 +14,11 @@ #include #include +#include #include +#include "modules/desktop_capture/desktop_capturer.h" +#include "modules/desktop_capture/desktop_geometry.h" #include "modules/desktop_capture/win/screen_capture_utils.h" #include "modules/desktop_capture/win/window_capture_utils.h" #include "rtc_base/win/get_activation_factory.h" diff --git a/modules/desktop_capture/win/wgc_capturer_win.cc b/modules/desktop_capture/win/wgc_capturer_win.cc index f6e84658fc..609a3e226a 100644 --- a/modules/desktop_capture/win/wgc_capturer_win.cc +++ b/modules/desktop_capture/win/wgc_capturer_win.cc @@ -14,11 +14,22 @@ #include #include +#include +#include +#include +#include +#include #include #include "modules/desktop_capture/desktop_capture_metrics_helper.h" +#include "modules/desktop_capture/desktop_capture_options.h" #include "modules/desktop_capture/desktop_capture_types.h" -#include "modules/desktop_capture/win/wgc_desktop_frame.h" +#include "modules/desktop_capture/desktop_capturer.h" +#include "modules/desktop_capture/desktop_frame.h" +#include "modules/desktop_capture/win/screen_capture_utils.h" +#include "modules/desktop_capture/win/wgc_capture_session.h" +#include "modules/desktop_capture/win/wgc_capture_source.h" +#include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "rtc_base/time_utils.h" #include "rtc_base/win/get_activation_factory.h" @@ -76,16 +87,16 @@ void LogDirtyRegionSupport() { } HSTRING dirty_region_mode; - hr = webrtc::CreateHstring(kDirtyRegionMode, wcslen(kDirtyRegionMode), - &dirty_region_mode); + hr = CreateHstring(kDirtyRegionMode, wcslen(kDirtyRegionMode), + &dirty_region_mode); if (FAILED(hr)) { - webrtc::DeleteHstring(dirty_region_mode); + DeleteHstring(dirty_region_mode); return; } HSTRING wgc_session_type; - hr = webrtc::CreateHstring(kWgcSessionType, wcslen(kWgcSessionType), - &wgc_session_type); + hr = CreateHstring(kWgcSessionType, wcslen(kWgcSessionType), + &wgc_session_type); if (SUCCEEDED(hr)) { boolean is_dirty_region_mode_supported = api_info_statics->IsPropertyPresent(wgc_session_type, dirty_region_mode, @@ -93,8 +104,8 @@ void LogDirtyRegionSupport() { RTC_HISTOGRAM_BOOLEAN("WebRTC.DesktopCapture.Win.WgcDirtyRegionSupport", !!is_dirty_region_mode_supported); } - webrtc::DeleteHstring(dirty_region_mode); - webrtc::DeleteHstring(wgc_session_type); + DeleteHstring(dirty_region_mode); + DeleteHstring(wgc_session_type); } } // namespace @@ -110,7 +121,7 @@ bool IsWgcSupported(CaptureType capture_type) { // There is a bug in the DWM (Desktop Window Manager) that prevents it from // providing image data if there are no displays attached. This was fixed in // Windows 11. - if (webrtc::rtc_win::GetVersion() < webrtc::rtc_win::Version::VERSION_WIN11) + if (rtc_win::GetVersion() < rtc_win::Version::VERSION_WIN11) return false; } @@ -119,8 +130,7 @@ bool IsWgcSupported(CaptureType capture_type) { // we can't assert that we won't be asked to capture the entire virtual // screen, we report unsupported so we can fallback to another capturer. if (capture_type == CaptureType::kScreen && - webrtc::rtc_win::GetVersion() < - webrtc::rtc_win::Version::VERSION_WIN10_20H1) { + rtc_win::GetVersion() < rtc_win::Version::VERSION_WIN10_20H1) { return false; } @@ -139,26 +149,26 @@ bool IsWgcSupported(CaptureType capture_type) { return false; HSTRING api_contract; - hr = webrtc::CreateHstring(kApiContract, wcslen(kApiContract), &api_contract); + hr = CreateHstring(kApiContract, wcslen(kApiContract), &api_contract); if (FAILED(hr)) return false; boolean is_api_present; hr = api_info_statics->IsApiContractPresentByMajor( api_contract, kRequiredApiContractVersion, &is_api_present); - webrtc::DeleteHstring(api_contract); + DeleteHstring(api_contract); if (FAILED(hr) || !is_api_present) return false; HSTRING wgc_session_type; - hr = webrtc::CreateHstring(kWgcSessionType, wcslen(kWgcSessionType), - &wgc_session_type); + hr = CreateHstring(kWgcSessionType, wcslen(kWgcSessionType), + &wgc_session_type); if (FAILED(hr)) return false; boolean is_type_present; hr = api_info_statics->IsTypePresent(wgc_session_type, &is_type_present); - webrtc::DeleteHstring(wgc_session_type); + DeleteHstring(wgc_session_type); if (FAILED(hr) || !is_type_present) return false; @@ -323,7 +333,7 @@ void WgcCapturerWin::CaptureFrame() { } } - int64_t capture_start_time_nanos = webrtc::TimeNanos(); + int64_t capture_start_time_nanos = TimeNanos(); WgcCaptureSession* capture_session = nullptr; std::map::iterator session_iter = @@ -381,8 +391,8 @@ void WgcCapturerWin::CaptureFrame() { return; } - int capture_time_ms = (webrtc::TimeNanos() - capture_start_time_nanos) / - webrtc::kNumNanosecsPerMillisec; + int capture_time_ms = + (TimeNanos() - capture_start_time_nanos) / kNumNanosecsPerMillisec; RTC_HISTOGRAM_COUNTS_1000("WebRTC.DesktopCapture.Win.WgcCapturerFrameTime", capture_time_ms); frame->set_capture_time_ms(capture_time_ms); diff --git a/modules/desktop_capture/win/wgc_capturer_win.h b/modules/desktop_capture/win/wgc_capturer_win.h index 30253d9db6..60309d7b23 100644 --- a/modules/desktop_capture/win/wgc_capturer_win.h +++ b/modules/desktop_capture/win/wgc_capturer_win.h @@ -15,10 +15,12 @@ #include #include +#include #include #include #include "modules/desktop_capture/desktop_capture_options.h" +#include "modules/desktop_capture/desktop_capture_types.h" #include "modules/desktop_capture/desktop_capturer.h" #include "modules/desktop_capture/win/screen_capture_utils.h" #include "modules/desktop_capture/win/wgc_capture_session.h" @@ -72,7 +74,7 @@ class ScreenEnumerator final : public SourceEnumerator { ~ScreenEnumerator() override = default; bool FindAllSources(DesktopCapturer::SourceList* sources) override { - return webrtc::GetScreenList(sources); + return GetScreenList(sources); } }; diff --git a/modules/desktop_capture/win/wgc_capturer_win_unittest.cc b/modules/desktop_capture/win/wgc_capturer_win_unittest.cc index 6190579753..baeca2d924 100644 --- a/modules/desktop_capture/win/wgc_capturer_win_unittest.cc +++ b/modules/desktop_capture/win/wgc_capturer_win_unittest.cc @@ -10,17 +10,20 @@ #include "modules/desktop_capture/win/wgc_capturer_win.h" -#include +#include +#include +#include +#include #include #include #include "modules/desktop_capture/desktop_capture_options.h" #include "modules/desktop_capture/desktop_capture_types.h" #include "modules/desktop_capture/desktop_capturer.h" +#include "modules/desktop_capture/win/screen_capture_utils.h" #include "modules/desktop_capture/win/test_support/test_window.h" #include "modules/desktop_capture/win/wgc_capture_session.h" #include "modules/desktop_capture/win/window_capture_utils.h" -#include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "rtc_base/task_queue_for_test.h" #include "rtc_base/thread.h" @@ -125,7 +128,7 @@ class WgcCapturerWinTest : public ::testing::TestWithParam, // having GraphicsCaptureItem events (i.e. the Closed event) fire, and it more // closely resembles how capture works in the wild. void CreateWindowOnSeparateThread(int window_width, int window_height) { - window_thread_ = webrtc::Thread::Create(); + window_thread_ = Thread::Create(); window_thread_->SetName(kWindowThreadName, nullptr); window_thread_->Start(); SendTask(window_thread_.get(), [this, window_width, window_height]() { @@ -266,7 +269,7 @@ class WgcCapturerWinTest : public ::testing::TestWithParam, protected: std::unique_ptr com_initializer_; DWORD window_thread_id_; - std::unique_ptr window_thread_; + std::unique_ptr window_thread_; WindowInfo window_info_; intptr_t source_id_; bool window_open_ = false; @@ -330,11 +333,10 @@ TEST_P(WgcCapturerWinTest, CaptureTime) { capturer_->Start(this); int64_t start_time; - start_time = webrtc::TimeNanos(); + start_time = TimeNanos(); capturer_->CaptureFrame(); - int capture_time_ms = - (webrtc::TimeNanos() - start_time) / webrtc::kNumNanosecsPerMillisec; + int capture_time_ms = (TimeNanos() - start_time) / kNumNanosecsPerMillisec; EXPECT_EQ(result_, DesktopCapturer::Result::SUCCESS); EXPECT_TRUE(frame_); @@ -365,7 +367,7 @@ TEST(WgcCapturerNoMonitorTest, NoMonitors) { // A bug in the DWM (Desktop Window Manager) prevents it from providing image // data if there are no displays attached. This was fixed in Windows 11. - if (webrtc::rtc_win::GetVersion() < webrtc::rtc_win::Version::VERSION_WIN11) + if (rtc_win::GetVersion() < rtc_win::Version::VERSION_WIN11) EXPECT_FALSE(IsWgcSupported(CaptureType::kWindow)); else EXPECT_TRUE(IsWgcSupported(CaptureType::kWindow)); diff --git a/modules/desktop_capture/win/wgc_desktop_frame.cc b/modules/desktop_capture/win/wgc_desktop_frame.cc index dd9009120b..d10ee1891c 100644 --- a/modules/desktop_capture/win/wgc_desktop_frame.cc +++ b/modules/desktop_capture/win/wgc_desktop_frame.cc @@ -10,7 +10,12 @@ #include "modules/desktop_capture/win/wgc_desktop_frame.h" +#include #include +#include + +#include "modules/desktop_capture/desktop_frame.h" +#include "modules/desktop_capture/desktop_geometry.h" namespace webrtc { diff --git a/modules/desktop_capture/win/wgc_desktop_frame.h b/modules/desktop_capture/win/wgc_desktop_frame.h index 0a671cf2f8..3a478cfad5 100644 --- a/modules/desktop_capture/win/wgc_desktop_frame.h +++ b/modules/desktop_capture/win/wgc_desktop_frame.h @@ -11,10 +11,7 @@ #ifndef MODULES_DESKTOP_CAPTURE_WIN_WGC_DESKTOP_FRAME_H_ #define MODULES_DESKTOP_CAPTURE_WIN_WGC_DESKTOP_FRAME_H_ -#include -#include - -#include +#include #include #include "modules/desktop_capture/desktop_frame.h" diff --git a/modules/desktop_capture/win/window_capture_utils.cc b/modules/desktop_capture/win/window_capture_utils.cc index 263b2c3780..fcfa927699 100644 --- a/modules/desktop_capture/win/window_capture_utils.cc +++ b/modules/desktop_capture/win/window_capture_utils.cc @@ -12,11 +12,17 @@ // Just for the DWMWINDOWATTRIBUTE enums (DWMWA_CLOAKED). #include +#include #include +#include +#include +#include +#include "modules/desktop_capture/desktop_capture_types.h" +#include "modules/desktop_capture/desktop_capturer.h" +#include "modules/desktop_capture/desktop_geometry.h" #include "modules/desktop_capture/win/scoped_gdi_object.h" -#include "rtc_base/arraysize.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "rtc_base/string_utils.h" @@ -104,7 +110,7 @@ BOOL CALLBACK GetWindowListHandler(HWND hwnd, LPARAM param) { WCHAR window_title[kTitleLength] = L""; if (GetWindowTextLength(hwnd) != 0 && GetWindowTextW(hwnd, window_title, kTitleLength) > 0) { - window.title = webrtc::ToUtf8(window_title); + window.title = ToUtf8(window_title); } } @@ -179,8 +185,7 @@ bool GetCroppedWindowRect(HWND window, // As of Windows8, transparent resize borders are added by the OS at // left/bottom/right sides of a resizeable window. If the cropped window // doesn't remove these borders, the background will be exposed a bit. - if (webrtc::rtc_win::GetVersion() >= webrtc::rtc_win::Version::VERSION_WIN8 || - is_maximized) { + if (rtc_win::GetVersion() >= rtc_win::Version::VERSION_WIN8 || is_maximized) { // Only apply this cropping to windows with a resize border (otherwise, // it'd clip the edges of captured pop-up windows without this border). RECT rect; @@ -319,8 +324,7 @@ WindowCaptureHelperWin::WindowCaptureHelperWin() { GetProcAddress(dwmapi_library_, "DwmGetWindowAttribute")); } - if (webrtc::rtc_win::GetVersion() >= - webrtc::rtc_win::Version::VERSION_WIN10) { + if (rtc_win::GetVersion() >= rtc_win::Version::VERSION_WIN10) { if (FAILED(::CoCreateInstance(__uuidof(VirtualDesktopManager), nullptr, CLSCTX_ALL, IID_PPV_ARGS(&virtual_desktop_manager_)))) { @@ -472,7 +476,7 @@ bool WindowCaptureHelperWin::EnumerateCapturableWindows( flags |= GetWindowListFlags::kIgnoreCurrentProcessWindows; } - if (!webrtc::GetWindowList(flags, results, ex_style_filters)) { + if (!GetWindowList(flags, results, ex_style_filters)) { return false; } diff --git a/modules/desktop_capture/win/window_capture_utils.h b/modules/desktop_capture/win/window_capture_utils.h index caea07958d..a69bc79874 100644 --- a/modules/desktop_capture/win/window_capture_utils.h +++ b/modules/desktop_capture/win/window_capture_utils.h @@ -11,7 +11,7 @@ #ifndef MODULES_DESKTOP_CAPTURE_WIN_WINDOW_CAPTURE_UTILS_H_ #define MODULES_DESKTOP_CAPTURE_WIN_WINDOW_CAPTURE_UTILS_H_ -#include +#include #include #include diff --git a/modules/desktop_capture/win/window_capture_utils_unittest.cc b/modules/desktop_capture/win/window_capture_utils_unittest.cc index 76cb537a87..ec70c80ed2 100644 --- a/modules/desktop_capture/win/window_capture_utils_unittest.cc +++ b/modules/desktop_capture/win/window_capture_utils_unittest.cc @@ -28,10 +28,10 @@ namespace { const char kWindowThreadName[] = "window_capture_utils_test_thread"; const WCHAR kWindowTitle[] = L"Window Capture Utils Test"; -std::unique_ptr SetUpUnresponsiveWindow(std::mutex& mtx, - WindowInfo& info) { - std::unique_ptr window_thread; - window_thread = webrtc::Thread::Create(); +std::unique_ptr SetUpUnresponsiveWindow(std::mutex& mtx, + WindowInfo& info) { + std::unique_ptr window_thread; + window_thread = Thread::Create(); window_thread->SetName(kWindowThreadName, nullptr); window_thread->Start(); @@ -66,8 +66,7 @@ TEST(WindowCaptureUtilsTest, GetWindowList) { TEST(WindowCaptureUtilsTest, IncludeUnresponsiveWindows) { std::mutex mtx; WindowInfo info; - std::unique_ptr window_thread = - SetUpUnresponsiveWindow(mtx, info); + std::unique_ptr window_thread = SetUpUnresponsiveWindow(mtx, info); EXPECT_FALSE(IsWindowResponding(info.hwnd)); @@ -89,8 +88,7 @@ TEST(WindowCaptureUtilsTest, IncludeUnresponsiveWindows) { TEST(WindowCaptureUtilsTest, IgnoreUnresponsiveWindows) { std::mutex mtx; WindowInfo info; - std::unique_ptr window_thread = - SetUpUnresponsiveWindow(mtx, info); + std::unique_ptr window_thread = SetUpUnresponsiveWindow(mtx, info); EXPECT_FALSE(IsWindowResponding(info.hwnd)); diff --git a/modules/desktop_capture/win/window_capturer_win_gdi.cc b/modules/desktop_capture/win/window_capturer_win_gdi.cc index 610e058a9f..8e9be705d2 100644 --- a/modules/desktop_capture/win/window_capturer_win_gdi.cc +++ b/modules/desktop_capture/win/window_capturer_win_gdi.cc @@ -10,7 +10,11 @@ #include "modules/desktop_capture/win/window_capturer_win_gdi.h" +#include #include +#include +#include +#include #include #include #include @@ -20,13 +24,14 @@ #include "modules/desktop_capture/desktop_capture_metrics_helper.h" #include "modules/desktop_capture/desktop_capture_types.h" #include "modules/desktop_capture/desktop_capturer.h" +#include "modules/desktop_capture/desktop_frame.h" #include "modules/desktop_capture/desktop_frame_win.h" +#include "modules/desktop_capture/desktop_geometry.h" #include "modules/desktop_capture/win/screen_capture_utils.h" #include "modules/desktop_capture/win/selected_window_context.h" -#include "rtc_base/arraysize.h" +#include "modules/desktop_capture/win/window_capture_utils.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" -#include "rtc_base/string_utils.h" #include "rtc_base/time_utils.h" #include "rtc_base/trace_event.h" #include "rtc_base/win/windows_version.h" @@ -79,7 +84,7 @@ BOOL CALLBACK OwnedWindowCollector(HWND hwnd, LPARAM param) { // e.g. some tooltips have the transparent style set). if (GetWindowLong(hwnd, GWL_EXSTYLE) & WS_EX_TRANSPARENT) { const WCHAR kSysShadow[] = L"SysShadow"; - const size_t kClassLength = arraysize(kSysShadow); + const size_t kClassLength = std::size(kSysShadow); WCHAR class_name[kClassLength]; const int class_name_length = GetClassNameW(hwnd, class_name, kClassLength); @@ -157,7 +162,7 @@ void WindowCapturerWinGdi::Start(Callback* callback) { void WindowCapturerWinGdi::CaptureFrame() { RTC_DCHECK(callback_); - int64_t capture_start_time_nanos = webrtc::TimeNanos(); + int64_t capture_start_time_nanos = TimeNanos(); CaptureResults results = CaptureFrame(/*capture_owned_windows*/ true); if (!results.frame) { @@ -168,8 +173,8 @@ void WindowCapturerWinGdi::CaptureFrame() { return; } - int capture_time_ms = (webrtc::TimeNanos() - capture_start_time_nanos) / - webrtc::kNumNanosecsPerMillisec; + int capture_time_ms = + (TimeNanos() - capture_start_time_nanos) / kNumNanosecsPerMillisec; RTC_HISTOGRAM_COUNTS_1000( "WebRTC.DesktopCapture.Win.WindowGdiCapturerFrameTime", capture_time_ms); results.frame->set_capture_time_ms(capture_time_ms); @@ -298,7 +303,7 @@ WindowCapturerWinGdi::CaptureResults WindowCapturerWinGdi::CaptureFrame( // on Windows 8.1 and later, PrintWindow is only used when the window is // occluded. When the window is not occluded, it is much faster to capture // the screen and to crop it to the window position and size. - if (webrtc::rtc_win::GetVersion() >= webrtc::rtc_win::Version::VERSION_WIN8) { + if (rtc_win::GetVersion() >= rtc_win::Version::VERSION_WIN8) { // Special flag that makes PrintWindow to work on Windows 8.1 and later. // Indeed certain apps (e.g. those using DirectComposition rendering) can't // be captured using BitBlt or PrintWindow without this flag. Note that on diff --git a/modules/desktop_capture/win/window_capturer_win_gdi.h b/modules/desktop_capture/win/window_capturer_win_gdi.h index bf94dfe192..b8e56e5736 100644 --- a/modules/desktop_capture/win/window_capturer_win_gdi.h +++ b/modules/desktop_capture/win/window_capturer_win_gdi.h @@ -17,6 +17,7 @@ #include "modules/desktop_capture/desktop_capture_options.h" #include "modules/desktop_capture/desktop_capturer.h" +#include "modules/desktop_capture/desktop_geometry.h" #include "modules/desktop_capture/win/window_capture_utils.h" #include "modules/desktop_capture/window_finder_win.h" diff --git a/modules/desktop_capture/window_capturer_linux.cc b/modules/desktop_capture/window_capturer_linux.cc index 4205bf9bc0..f621a63e72 100644 --- a/modules/desktop_capture/window_capturer_linux.cc +++ b/modules/desktop_capture/window_capturer_linux.cc @@ -11,6 +11,7 @@ #include #include "modules/desktop_capture/desktop_capture_options.h" +#include "modules/desktop_capture/desktop_capture_types.h" #include "modules/desktop_capture/desktop_capturer.h" #if defined(WEBRTC_USE_PIPEWIRE) diff --git a/modules/desktop_capture/window_capturer_null.cc b/modules/desktop_capture/window_capturer_null.cc index 6da2a76691..2061dc5248 100644 --- a/modules/desktop_capture/window_capturer_null.cc +++ b/modules/desktop_capture/window_capturer_null.cc @@ -8,8 +8,9 @@ * be found in the AUTHORS file in the root of the source tree. */ +#include + #include "modules/desktop_capture/desktop_capturer.h" -#include "modules/desktop_capture/desktop_frame.h" #include "rtc_base/checks.h" namespace webrtc { diff --git a/modules/desktop_capture/window_capturer_unittest.cc b/modules/desktop_capture/window_capturer_unittest.cc index 3483d4d2c8..4930f3d102 100644 --- a/modules/desktop_capture/window_capturer_unittest.cc +++ b/modules/desktop_capture/window_capturer_unittest.cc @@ -16,7 +16,6 @@ #include "modules/desktop_capture/desktop_capturer.h" #include "modules/desktop_capture/desktop_frame.h" #include "modules/desktop_capture/desktop_geometry.h" -#include "rtc_base/checks.h" #include "test/gtest.h" namespace webrtc { diff --git a/modules/desktop_capture/window_capturer_win.cc b/modules/desktop_capture/window_capturer_win.cc index c525dcc5fe..115bc7d9b0 100644 --- a/modules/desktop_capture/window_capturer_win.cc +++ b/modules/desktop_capture/window_capturer_win.cc @@ -8,8 +8,12 @@ * be found in the AUTHORS file in the root of the source tree. */ +#include +#include + #include "modules/desktop_capture/desktop_capture_options.h" #include "modules/desktop_capture/desktop_capturer.h" +#include "modules/desktop_capture/rgba_color.h" #include "modules/desktop_capture/win/window_capturer_win_gdi.h" #if defined(RTC_ENABLE_WIN_WGC) diff --git a/modules/desktop_capture/window_finder.h b/modules/desktop_capture/window_finder.h index 1b79f932b7..1fdc2eb8fc 100644 --- a/modules/desktop_capture/window_finder.h +++ b/modules/desktop_capture/window_finder.h @@ -13,7 +13,6 @@ #include -#include "api/scoped_refptr.h" #include "modules/desktop_capture/desktop_capture_types.h" #include "modules/desktop_capture/desktop_geometry.h" @@ -50,7 +49,7 @@ class WindowFinder { XAtomCache* cache = nullptr; #endif #if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS) - webrtc::scoped_refptr configuration_monitor; + scoped_refptr configuration_monitor; #endif }; diff --git a/modules/desktop_capture/window_finder_mac.h b/modules/desktop_capture/window_finder_mac.h index 171f098396..8030e24821 100644 --- a/modules/desktop_capture/window_finder_mac.h +++ b/modules/desktop_capture/window_finder_mac.h @@ -12,6 +12,8 @@ #define MODULES_DESKTOP_CAPTURE_WINDOW_FINDER_MAC_H_ #include "api/scoped_refptr.h" +#include "modules/desktop_capture/desktop_capture_types.h" +#include "modules/desktop_capture/desktop_geometry.h" #include "modules/desktop_capture/window_finder.h" namespace webrtc { @@ -22,15 +24,14 @@ class DesktopConfigurationMonitor; class WindowFinderMac final : public WindowFinder { public: explicit WindowFinderMac( - webrtc::scoped_refptr configuration_monitor); + scoped_refptr configuration_monitor); ~WindowFinderMac() override; // WindowFinder implementation. WindowId GetWindowUnderPoint(DesktopVector point) override; private: - const webrtc::scoped_refptr - configuration_monitor_; + const scoped_refptr configuration_monitor_; }; } // namespace webrtc diff --git a/modules/desktop_capture/window_finder_unittest.cc b/modules/desktop_capture/window_finder_unittest.cc index e30d715494..ebceac4a92 100644 --- a/modules/desktop_capture/window_finder_unittest.cc +++ b/modules/desktop_capture/window_finder_unittest.cc @@ -15,6 +15,7 @@ #include #include "api/scoped_refptr.h" +#include "modules/desktop_capture/desktop_capture_types.h" #include "modules/desktop_capture/desktop_geometry.h" #include "modules/desktop_capture/screen_drawer.h" #include "rtc_base/logging.h" diff --git a/modules/desktop_capture/window_finder_win.cc b/modules/desktop_capture/window_finder_win.cc index a8c3d39e19..03e7ec9812 100644 --- a/modules/desktop_capture/window_finder_win.cc +++ b/modules/desktop_capture/window_finder_win.cc @@ -14,6 +14,10 @@ #include +#include "modules/desktop_capture/desktop_capture_types.h" +#include "modules/desktop_capture/desktop_geometry.h" +#include "modules/desktop_capture/window_finder.h" + namespace webrtc { WindowFinderWin::WindowFinderWin() = default; diff --git a/modules/desktop_capture/window_finder_win.h b/modules/desktop_capture/window_finder_win.h index a04e7e1aae..a25754c10d 100644 --- a/modules/desktop_capture/window_finder_win.h +++ b/modules/desktop_capture/window_finder_win.h @@ -11,6 +11,8 @@ #ifndef MODULES_DESKTOP_CAPTURE_WINDOW_FINDER_WIN_H_ #define MODULES_DESKTOP_CAPTURE_WINDOW_FINDER_WIN_H_ +#include "modules/desktop_capture/desktop_capture_types.h" +#include "modules/desktop_capture/desktop_geometry.h" #include "modules/desktop_capture/window_finder.h" namespace webrtc { diff --git a/modules/pacing/BUILD.gn b/modules/pacing/BUILD.gn index 9faa33a254..74787dd3cc 100644 --- a/modules/pacing/BUILD.gn +++ b/modules/pacing/BUILD.gn @@ -29,43 +29,33 @@ rtc_library("pacing") { ] deps = [ - ":interval_budget", "../../api:array_view", "../../api:field_trials_view", - "../../api:field_trials_view", - "../../api:function_view", "../../api:rtp_headers", "../../api:rtp_packet_sender", "../../api:sequence_checker", - "../../api/rtc_event_log", + "../../api/task_queue", "../../api/task_queue:pending_task_safety_flag", - "../../api/task_queue:task_queue", "../../api/transport:network_control", "../../api/units:data_rate", "../../api/units:data_size", "../../api/units:time_delta", "../../api/units:timestamp", - "../../logging:rtc_event_bwe", - "../../logging:rtc_event_pacing", "../../rtc_base:checks", "../../rtc_base:event_tracer", "../../rtc_base:logging", "../../rtc_base:macromagic", "../../rtc_base:rtc_numerics", "../../rtc_base:safe_conversions", - "../../rtc_base:timeutils", "../../rtc_base/experiments:field_trial_parser", - "../../rtc_base/synchronization:mutex", "../../rtc_base/system:unused", "../../system_wrappers", - "../../system_wrappers:metrics", "../rtp_rtcp", "../rtp_rtcp:rtp_rtcp_format", - "../utility:utility", "//third_party/abseil-cpp/absl/cleanup", "//third_party/abseil-cpp/absl/container:inlined_vector", "//third_party/abseil-cpp/absl/functional:any_invocable", - "//third_party/abseil-cpp/absl/strings", + "//third_party/abseil-cpp/absl/strings:string_view", ] } @@ -97,10 +87,10 @@ if (rtc_include_tests) { ":interval_budget", ":pacing", "../../api:array_view", + "../../api:field_trials", "../../api:rtp_headers", "../../api:sequence_checker", - "../../api/task_queue:task_queue", - "../../api/transport:field_trial_based_config", + "../../api/task_queue", "../../api/transport:network_control", "../../api/units:data_rate", "../../api/units:data_size", @@ -108,13 +98,10 @@ if (rtc_include_tests) { "../../api/units:timestamp", "../../rtc_base:checks", "../../rtc_base:rtc_base_tests_utils", - "../../rtc_base/experiments:alr_experiment", "../../system_wrappers", - "../../test:explicit_key_value_config", - "../../test:scoped_key_value_config", + "../../test:create_test_field_trials", "../../test:test_support", - "../../test/time_controller:time_controller", - "../rtp_rtcp", + "../../test/time_controller", "../rtp_rtcp:mock_rtp_rtcp", "../rtp_rtcp:rtp_rtcp_format", ] diff --git a/modules/pacing/bitrate_prober_unittest.cc b/modules/pacing/bitrate_prober_unittest.cc index 826e895aa4..a727d2d8c0 100644 --- a/modules/pacing/bitrate_prober_unittest.cc +++ b/modules/pacing/bitrate_prober_unittest.cc @@ -12,19 +12,19 @@ #include -#include "api/transport/field_trial_based_config.h" +#include "api/field_trials.h" #include "api/transport/network_types.h" #include "api/units/data_rate.h" #include "api/units/data_size.h" #include "api/units/time_delta.h" #include "api/units/timestamp.h" -#include "test/explicit_key_value_config.h" +#include "test/create_test_field_trials.h" #include "test/gtest.h" namespace webrtc { TEST(BitrateProberTest, VerifyStatesAndTimeBetweenProbes) { - const FieldTrialBasedConfig config; + const FieldTrials config = CreateTestFieldTrials(); BitrateProber prober(config); EXPECT_FALSE(prober.is_probing()); @@ -94,7 +94,7 @@ TEST(BitrateProberTest, VerifyStatesAndTimeBetweenProbes) { } TEST(BitrateProberTest, DoesntProbeWithoutRecentPackets) { - const FieldTrialBasedConfig config; + const FieldTrials config = CreateTestFieldTrials(); BitrateProber prober(config); const DataSize kProbeSize = DataSize::Bytes(1000); @@ -117,7 +117,7 @@ TEST(BitrateProberTest, DoesntProbeWithoutRecentPackets) { TEST(BitrateProberTest, DiscardsDelayedProbes) { const TimeDelta kMaxProbeDelay = TimeDelta::Millis(3); - const test::ExplicitKeyValueConfig trials( + const FieldTrials trials = CreateTestFieldTrials( "WebRTC-Bwe-ProbingBehavior/" "abort_delayed_probes:1," "max_probe_delay:3ms/"); @@ -153,7 +153,7 @@ TEST(BitrateProberTest, DiscardsDelayedProbes) { } TEST(BitrateProberTest, LimitsNumberOfPendingProbeClusters) { - const FieldTrialBasedConfig config; + const FieldTrials config = CreateTestFieldTrials(); BitrateProber prober(config); const DataSize kProbeSize = DataSize::Bytes(1000); Timestamp now = Timestamp::Zero(); @@ -190,7 +190,7 @@ TEST(BitrateProberTest, LimitsNumberOfPendingProbeClusters) { } TEST(BitrateProberTest, DoesntInitializeProbingForSmallPackets) { - const FieldTrialBasedConfig config; + const FieldTrials config = CreateTestFieldTrials(); BitrateProber prober(config); prober.SetEnabled(true); ASSERT_FALSE(prober.is_probing()); @@ -207,7 +207,7 @@ TEST(BitrateProberTest, DoesntInitializeProbingForSmallPackets) { } TEST(BitrateProberTest, DoesInitializeProbingForSmallPacketsIfConfigured) { - const test::ExplicitKeyValueConfig config( + const FieldTrials config = CreateTestFieldTrials( "WebRTC-Bwe-ProbingBehavior/" "min_packet_size:0bytes/"); BitrateProber prober(config); @@ -226,7 +226,7 @@ TEST(BitrateProberTest, DoesInitializeProbingForSmallPacketsIfConfigured) { } TEST(BitrateProberTest, VerifyProbeSizeOnHighBitrate) { - const FieldTrialBasedConfig config; + const FieldTrials config = CreateTestFieldTrials(); BitrateProber prober(config); const DataRate kHighBitrate = DataRate::KilobitsPerSec(10000); // 10 Mbps @@ -243,7 +243,7 @@ TEST(BitrateProberTest, VerifyProbeSizeOnHighBitrate) { } TEST(BitrateProberTest, ProbeSizeCanBeSetInProbeClusterConfig) { - const FieldTrialBasedConfig config; + const FieldTrials config = CreateTestFieldTrials(); BitrateProber prober(config); prober.SetEnabled(true); @@ -267,7 +267,7 @@ TEST(BitrateProberTest, ProbeSizeCanBeSetInProbeClusterConfig) { } TEST(BitrateProberTest, MinumumNumberOfProbingPackets) { - const FieldTrialBasedConfig config; + const FieldTrials config = CreateTestFieldTrials(); BitrateProber prober(config); // Even when probing at a low bitrate we expect a minimum number // of packets to be sent. @@ -292,7 +292,7 @@ TEST(BitrateProberTest, MinumumNumberOfProbingPackets) { } TEST(BitrateProberTest, ScaleBytesUsedForProbing) { - const FieldTrialBasedConfig config; + const FieldTrials config = CreateTestFieldTrials(); BitrateProber prober(config); const DataRate kBitrate = DataRate::KilobitsPerSec(10000); // 10 Mbps. const DataSize kPacketSize = DataSize::Bytes(1000); @@ -317,7 +317,7 @@ TEST(BitrateProberTest, ScaleBytesUsedForProbing) { } TEST(BitrateProberTest, HighBitrateProbing) { - const FieldTrialBasedConfig config; + const FieldTrials config = CreateTestFieldTrials(); BitrateProber prober(config); const DataRate kBitrate = DataRate::KilobitsPerSec(1000000); // 1 Gbps. const DataSize kPacketSize = DataSize::Bytes(1000); @@ -342,7 +342,7 @@ TEST(BitrateProberTest, HighBitrateProbing) { } TEST(BitrateProberTest, ProbeClusterTimeout) { - const FieldTrialBasedConfig config; + const FieldTrials config = CreateTestFieldTrials(); BitrateProber prober(config); const DataRate kBitrate = DataRate::KilobitsPerSec(300); const DataSize kSmallPacketSize = DataSize::Bytes(20); @@ -388,8 +388,8 @@ TEST(BitrateProberTest, ProbeClusterTimeout) { } TEST(BitrateProberTest, CanProbeImmediatelyIfConfigured) { - const test::ExplicitKeyValueConfig trials( - "WebRTC-Bwe-ProbingBehavior/min_packet_size:0/"); + const FieldTrials trials = + CreateTestFieldTrials("WebRTC-Bwe-ProbingBehavior/min_packet_size:0/"); BitrateProber prober(trials); prober.CreateProbeCluster({.at_time = Timestamp::Zero(), @@ -402,8 +402,8 @@ TEST(BitrateProberTest, CanProbeImmediatelyIfConfigured) { } TEST(BitrateProberTest, CanProbeImmediatelyAgainAfterProbeIfConfigured) { - const test::ExplicitKeyValueConfig trials( - "WebRTC-Bwe-ProbingBehavior/min_packet_size:0/"); + const FieldTrials trials = + CreateTestFieldTrials("WebRTC-Bwe-ProbingBehavior/min_packet_size:0/"); BitrateProber prober(trials); ProbeClusterConfig cluster_config = { diff --git a/modules/pacing/interval_budget.cc b/modules/pacing/interval_budget.cc index b7f29acdb6..ec8b92be31 100644 --- a/modules/pacing/interval_budget.cc +++ b/modules/pacing/interval_budget.cc @@ -19,7 +19,7 @@ namespace webrtc { namespace { constexpr int64_t kWindowMs = 500; -} +} // namespace IntervalBudget::IntervalBudget(int initial_target_rate_kbps) : IntervalBudget(initial_target_rate_kbps, false) {} diff --git a/modules/pacing/pacing_controller.cc b/modules/pacing/pacing_controller.cc index d328c8692e..3764259805 100644 --- a/modules/pacing/pacing_controller.cc +++ b/modules/pacing/pacing_controller.cc @@ -20,7 +20,6 @@ #include #include "absl/cleanup/cleanup.h" -#include "absl/strings/match.h" #include "absl/strings/string_view.h" #include "api/array_view.h" #include "api/field_trials_view.h" @@ -43,15 +42,6 @@ constexpr TimeDelta kCongestedPacketInterval = TimeDelta::Millis(500); // The maximum debt level, in terms of time, capped when sending packets. constexpr TimeDelta kMaxDebtInTime = TimeDelta::Millis(500); constexpr TimeDelta kMaxElapsedTime = TimeDelta::Seconds(2); - -bool IsDisabled(const FieldTrialsView& field_trials, absl::string_view key) { - return absl::StartsWith(field_trials.Lookup(key), "Disabled"); -} - -bool IsEnabled(const FieldTrialsView& field_trials, absl::string_view key) { - return absl::StartsWith(field_trials.Lookup(key), "Enabled"); -} - } // namespace const TimeDelta PacingController::kPausedProcessInterval = @@ -69,20 +59,18 @@ PacingController::PacingController(Clock* clock, Configuration configuration) : clock_(clock), packet_sender_(packet_sender), - field_trials_(field_trials), - drain_large_queues_( - configuration.drain_large_queues && - !IsDisabled(field_trials_, "WebRTC-Pacer-DrainQueue")), + drain_large_queues_(configuration.drain_large_queues && + !field_trials.IsDisabled("WebRTC-Pacer-DrainQueue")), send_padding_if_silent_( - IsEnabled(field_trials_, "WebRTC-Pacer-PadInSilence")), - pace_audio_(IsEnabled(field_trials_, "WebRTC-Pacer-BlockAudio")), + field_trials.IsEnabled("WebRTC-Pacer-PadInSilence")), + pace_audio_(field_trials.IsEnabled("WebRTC-Pacer-BlockAudio")), ignore_transport_overhead_( - IsEnabled(field_trials_, "WebRTC-Pacer-IgnoreTransportOverhead")), + field_trials.IsEnabled("WebRTC-Pacer-IgnoreTransportOverhead")), fast_retransmissions_( - IsEnabled(field_trials_, "WebRTC-Pacer-FastRetransmissions")), + field_trials.IsEnabled("WebRTC-Pacer-FastRetransmissions")), keyframe_flushing_( configuration.keyframe_flushing || - IsEnabled(field_trials_, "WebRTC-Pacer-KeyframeFlushing")), + field_trials.IsEnabled("WebRTC-Pacer-KeyframeFlushing")), transport_overhead_per_packet_(DataSize::Zero()), send_burst_interval_(configuration.send_burst_interval), last_timestamp_(clock_->CurrentTime()), @@ -92,7 +80,7 @@ PacingController::PacingController(Clock* clock, pacing_rate_(DataRate::Zero()), adjusted_media_rate_(DataRate::Zero()), padding_rate_(DataRate::Zero()), - prober_(field_trials_), + prober_(field_trials), probing_send_failure_(false), last_process_time_(clock->CurrentTime()), last_send_time_(last_process_time_), diff --git a/modules/pacing/pacing_controller.h b/modules/pacing/pacing_controller.h index a745f4480f..6a4b92cd30 100644 --- a/modules/pacing/pacing_controller.h +++ b/modules/pacing/pacing_controller.h @@ -238,7 +238,6 @@ class PacingController { Clock* const clock_; PacketSender* const packet_sender_; - const FieldTrialsView& field_trials_; const bool drain_large_queues_; const bool send_padding_if_silent_; diff --git a/modules/pacing/pacing_controller_unittest.cc b/modules/pacing/pacing_controller_unittest.cc index 27fdbd1aba..8a272f06b9 100644 --- a/modules/pacing/pacing_controller_unittest.cc +++ b/modules/pacing/pacing_controller_unittest.cc @@ -21,6 +21,7 @@ #include #include "api/array_view.h" +#include "api/field_trials.h" #include "api/transport/network_types.h" #include "api/units/data_rate.h" #include "api/units/data_size.h" @@ -30,7 +31,7 @@ #include "modules/rtp_rtcp/include/rtp_rtcp_defines.h" #include "modules/rtp_rtcp/source/rtp_packet_to_send.h" #include "system_wrappers/include/clock.h" -#include "test/explicit_key_value_config.h" +#include "test/create_test_field_trials.h" #include "test/gmock.h" #include "test/gtest.h" @@ -43,8 +44,6 @@ using ::testing::Property; using ::testing::Return; using ::testing::WithoutArgs; -using ::webrtc::test::ExplicitKeyValueConfig; - namespace webrtc { namespace { constexpr DataRate kFirstClusterRate = DataRate::KilobitsPerSec(900); @@ -288,7 +287,7 @@ class PacingControllerProbing : public PacingController::PacketSender { class PacingControllerTest : public ::testing::Test { protected: - PacingControllerTest() : clock_(123456), trials_("") {} + PacingControllerTest() : clock_(123456), trials_(CreateTestFieldTrials()) {} void SendAndExpectPacket(PacingController* pacer, RtpPacketMediaType type, @@ -345,11 +344,11 @@ class PacingControllerTest : public ::testing::Test { /*packet_size*/ 1000); ::testing::NiceMock callback_; - ExplicitKeyValueConfig trials_; + FieldTrials trials_; }; TEST_F(PacingControllerTest, DefaultNoPaddingInSilence) { - const test::ExplicitKeyValueConfig trials(""); + const FieldTrials trials = CreateTestFieldTrials(); PacingController pacer(&clock_, &callback_, trials); pacer.SetPacingRates(kTargetRate, DataRate::Zero()); // Video packet to reset last send time and provide padding data. @@ -364,8 +363,8 @@ TEST_F(PacingControllerTest, DefaultNoPaddingInSilence) { } TEST_F(PacingControllerTest, PaddingInSilenceWithTrial) { - const test::ExplicitKeyValueConfig trials( - "WebRTC-Pacer-PadInSilence/Enabled/"); + const FieldTrials trials = + CreateTestFieldTrials("WebRTC-Pacer-PadInSilence/Enabled/"); PacingController pacer(&clock_, &callback_, trials); pacer.SetPacingRates(kTargetRate, DataRate::Zero()); // Video packet to reset last send time and provide padding data. @@ -380,7 +379,8 @@ TEST_F(PacingControllerTest, PaddingInSilenceWithTrial) { } TEST_F(PacingControllerTest, CongestionWindowAffectsAudioInTrial) { - const test::ExplicitKeyValueConfig trials("WebRTC-Pacer-BlockAudio/Enabled/"); + const FieldTrials trials = + CreateTestFieldTrials("WebRTC-Pacer-BlockAudio/Enabled/"); EXPECT_CALL(callback_, SendPadding).Times(0); PacingController pacer(&clock_, &callback_, trials); pacer.SetPacingRates(DataRate::KilobitsPerSec(10000), DataRate::Zero()); @@ -409,7 +409,7 @@ TEST_F(PacingControllerTest, CongestionWindowAffectsAudioInTrial) { TEST_F(PacingControllerTest, DefaultCongestionWindowDoesNotAffectAudio) { EXPECT_CALL(callback_, SendPadding).Times(0); - const test::ExplicitKeyValueConfig trials(""); + const FieldTrials trials = CreateTestFieldTrials(); PacingController pacer(&clock_, &callback_, trials); pacer.SetPacingRates(DataRate::BitsPerSec(10000000), DataRate::Zero()); // Video packet fills congestion window. @@ -426,7 +426,8 @@ TEST_F(PacingControllerTest, DefaultCongestionWindowDoesNotAffectAudio) { } TEST_F(PacingControllerTest, BudgetAffectsAudioInTrial) { - ExplicitKeyValueConfig trials("WebRTC-Pacer-BlockAudio/Enabled/"); + FieldTrials trials = + CreateTestFieldTrials("WebRTC-Pacer-BlockAudio/Enabled/"); PacingController pacer(&clock_, &callback_, trials); const size_t kPacketSize = 1000; const int kProcessIntervalsPerSecond = 1000 / 5; @@ -460,7 +461,7 @@ TEST_F(PacingControllerTest, BudgetAffectsAudioInTrial) { TEST_F(PacingControllerTest, DefaultBudgetDoesNotAffectAudio) { const size_t kPacketSize = 1000; EXPECT_CALL(callback_, SendPadding).Times(0); - const test::ExplicitKeyValueConfig trials(""); + const FieldTrials trials = CreateTestFieldTrials(); PacingController pacer(&clock_, &callback_, trials); const int kProcessIntervalsPerSecond = 1000 / 5; pacer.SetPacingRates( @@ -1242,8 +1243,8 @@ TEST_F(PacingControllerTest, SkipsProbesWhenProcessIntervalTooLarge) { PacingControllerProbing packet_sender; - const test::ExplicitKeyValueConfig trials( - "WebRTC-Bwe-ProbingBehavior/max_probe_delay:2ms/"); + const FieldTrials trials = + CreateTestFieldTrials("WebRTC-Bwe-ProbingBehavior/max_probe_delay:2ms/"); auto pacer = std::make_unique(&clock_, &packet_sender, trials); pacer->SetPacingRates( @@ -2311,8 +2312,8 @@ TEST_F(PacingControllerTest, BudgetDoesNotAffectRetransmissionInsTrial) { const DataSize kPacketSize = DataSize::Bytes(1000); EXPECT_CALL(callback_, SendPadding).Times(0); - const test::ExplicitKeyValueConfig trials( - "WebRTC-Pacer-FastRetransmissions/Enabled/"); + const FieldTrials trials = + CreateTestFieldTrials("WebRTC-Pacer-FastRetransmissions/Enabled/"); PacingController pacer(&clock_, &callback_, trials); pacer.SetPacingRates(kTargetRate, /*padding_rate=*/DataRate::Zero()); @@ -2392,8 +2393,8 @@ TEST_F(PacingControllerTest, FlushesPacketsOnKeyFrames) { const uint32_t kSsrc = 12345; const uint32_t kRtxSsrc = 12346; - const test::ExplicitKeyValueConfig trials( - "WebRTC-Pacer-KeyframeFlushing/Enabled/"); + const FieldTrials trials = + CreateTestFieldTrials("WebRTC-Pacer-KeyframeFlushing/Enabled/"); auto pacer = std::make_unique(&clock_, &callback_, trials); EXPECT_CALL(callback_, GetRtxSsrcForMedia(kSsrc)) .WillRepeatedly(Return(kRtxSsrc)); diff --git a/modules/pacing/task_queue_paced_sender_unittest.cc b/modules/pacing/task_queue_paced_sender_unittest.cc index 16590ad09b..5cc4fe92b9 100644 --- a/modules/pacing/task_queue_paced_sender_unittest.cc +++ b/modules/pacing/task_queue_paced_sender_unittest.cc @@ -17,6 +17,7 @@ #include #include +#include "api/field_trials.h" #include "api/sequence_checker.h" #include "api/task_queue/task_queue_base.h" #include "api/task_queue/task_queue_factory.h" @@ -28,9 +29,9 @@ #include "modules/pacing/pacing_controller.h" #include "modules/pacing/packet_router.h" #include "modules/rtp_rtcp/include/rtp_rtcp_defines.h" +#include "test/create_test_field_trials.h" #include "test/gmock.h" #include "test/gtest.h" -#include "test/scoped_key_value_config.h" #include "test/time_controller/simulated_time_controller.h" using ::testing::_; @@ -123,7 +124,7 @@ std::vector> GeneratePackets( TEST(TaskQueuePacedSenderTest, PacesPackets) { GlobalSimulatedTimeController time_controller(Timestamp::Millis(1234)); MockPacketRouter packet_router; - ScopedKeyValueConfig trials; + FieldTrials trials = CreateTestFieldTrials(); TaskQueuePacedSender pacer(time_controller.GetClock(), &packet_router, trials, PacingController::kMinSleepTime, TaskQueuePacedSender::kNoPacketHoldback); @@ -165,9 +166,8 @@ TEST(TaskQueuePacedSenderTest, PacesPackets) { TEST(TaskQueuePacedSenderTest, PacesPacketsWithBurst) { GlobalSimulatedTimeController time_controller(Timestamp::Millis(1234)); MockPacketRouter packet_router; - ScopedKeyValueConfig trials; + FieldTrials trials = CreateTestFieldTrials(); TaskQueuePacedSender pacer(time_controller.GetClock(), &packet_router, trials, - PacingController::kMinSleepTime, TaskQueuePacedSender::kNoPacketHoldback); pacer.SetSendBurstInterval( @@ -212,9 +212,8 @@ TEST(TaskQueuePacedSenderTest, PacesPacketsWithBurst) { TEST(TaskQueuePacedSenderTest, ReschedulesProcessOnRateChange) { GlobalSimulatedTimeController time_controller(Timestamp::Millis(1234)); MockPacketRouter packet_router; - ScopedKeyValueConfig trials; + FieldTrials trials = CreateTestFieldTrials(); TaskQueuePacedSender pacer(time_controller.GetClock(), &packet_router, trials, - PacingController::kMinSleepTime, TaskQueuePacedSender::kNoPacketHoldback); @@ -266,9 +265,8 @@ TEST(TaskQueuePacedSenderTest, ReschedulesProcessOnRateChange) { TEST(TaskQueuePacedSenderTest, SendsAudioImmediately) { GlobalSimulatedTimeController time_controller(Timestamp::Millis(1234)); NiceMock packet_router; - ScopedKeyValueConfig trials; + FieldTrials trials = CreateTestFieldTrials(); TaskQueuePacedSender pacer(time_controller.GetClock(), &packet_router, trials, - PacingController::kMinSleepTime, TaskQueuePacedSender::kNoPacketHoldback); @@ -294,9 +292,8 @@ TEST(TaskQueuePacedSenderTest, SleepsDuringCoalscingWindow) { const TimeDelta kCoalescingWindow = TimeDelta::Millis(5); GlobalSimulatedTimeController time_controller(Timestamp::Millis(1234)); NiceMock packet_router; - ScopedKeyValueConfig trials; + FieldTrials trials = CreateTestFieldTrials(); TaskQueuePacedSender pacer(time_controller.GetClock(), &packet_router, trials, - kCoalescingWindow, TaskQueuePacedSender::kNoPacketHoldback); pacer.SetSendBurstInterval(TimeDelta::Zero()); @@ -332,9 +329,8 @@ TEST(TaskQueuePacedSenderTest, ProbingOverridesCoalescingWindow) { const TimeDelta kCoalescingWindow = TimeDelta::Millis(5); GlobalSimulatedTimeController time_controller(Timestamp::Millis(1234)); MockPacketRouter packet_router; - ScopedKeyValueConfig trials; + FieldTrials trials = CreateTestFieldTrials(); TaskQueuePacedSender pacer(time_controller.GetClock(), &packet_router, trials, - kCoalescingWindow, TaskQueuePacedSender::kNoPacketHoldback); @@ -366,12 +362,11 @@ TEST(TaskQueuePacedSenderTest, ProbingOverridesCoalescingWindow) { } TEST(TaskQueuePacedSenderTest, SchedulesProbeAtSentTime) { - ScopedKeyValueConfig trials( - "WebRTC-Bwe-ProbingBehavior/min_probe_delta:1ms/"); + FieldTrials trials = + CreateTestFieldTrials("WebRTC-Bwe-ProbingBehavior/min_probe_delta:1ms/"); GlobalSimulatedTimeController time_controller(Timestamp::Millis(1234)); NiceMock packet_router; TaskQueuePacedSender pacer(time_controller.GetClock(), &packet_router, trials, - PacingController::kMinSleepTime, TaskQueuePacedSender::kNoPacketHoldback); pacer.SetSendBurstInterval(TimeDelta::Zero()); @@ -440,11 +435,10 @@ TEST(TaskQueuePacedSenderTest, SchedulesProbeAtSentTime) { TEST(TaskQueuePacedSenderTest, NoMinSleepTimeWhenProbing) { // Set min_probe_delta to be less than kMinSleepTime (1ms). const TimeDelta kMinProbeDelta = TimeDelta::Micros(200); - ScopedKeyValueConfig trials; + FieldTrials trials = CreateTestFieldTrials(); GlobalSimulatedTimeController time_controller(Timestamp::Millis(1234)); MockPacketRouter packet_router; TaskQueuePacedSender pacer(time_controller.GetClock(), &packet_router, trials, - PacingController::kMinSleepTime, TaskQueuePacedSender::kNoPacketHoldback); @@ -505,9 +499,8 @@ TEST(TaskQueuePacedSenderTest, PacketBasedCoalescing) { GlobalSimulatedTimeController time_controller(Timestamp::Millis(1234)); NiceMock packet_router; - ScopedKeyValueConfig trials; + FieldTrials trials = CreateTestFieldTrials(); TaskQueuePacedSender pacer(time_controller.GetClock(), &packet_router, trials, - kFixedCoalescingWindow, kPacketBasedHoldback); pacer.SetSendBurstInterval(TimeDelta::Zero()); @@ -556,9 +549,8 @@ TEST(TaskQueuePacedSenderTest, FixedHoldBackHasPriorityOverPackets) { GlobalSimulatedTimeController time_controller(Timestamp::Millis(1234)); MockPacketRouter packet_router; - ScopedKeyValueConfig trials; + FieldTrials trials = CreateTestFieldTrials(); TaskQueuePacedSender pacer(time_controller.GetClock(), &packet_router, trials, - kFixedCoalescingWindow, kPacketBasedHoldback); pacer.SetSendBurstInterval(TimeDelta::Zero()); @@ -600,13 +592,12 @@ TEST(TaskQueuePacedSenderTest, FixedHoldBackHasPriorityOverPackets) { TEST(TaskQueuePacedSenderTest, ProbingStopDuringSendLoop) { // Set a low `min_probe_delta` to let probing finish during send loop. - ScopedKeyValueConfig trials( + FieldTrials trials = CreateTestFieldTrials( "WebRTC-Bwe-ProbingBehavior/min_probe_delta:100us/"); GlobalSimulatedTimeController time_controller(Timestamp::Millis(1234)); MockPacketRouter packet_router; TaskQueuePacedSender pacer(time_controller.GetClock(), &packet_router, trials, - PacingController::kMinSleepTime, TaskQueuePacedSender::kNoPacketHoldback); @@ -651,10 +642,9 @@ TEST(TaskQueuePacedSenderTest, ProbingStopDuringSendLoop) { TEST(TaskQueuePacedSenderTest, PostedPacketsNotSendFromRemovePacketsForSsrc) { static constexpr Timestamp kStartTime = Timestamp::Millis(1234); GlobalSimulatedTimeController time_controller(kStartTime); - ScopedKeyValueConfig trials; + FieldTrials trials = CreateTestFieldTrials(); MockPacketRouter packet_router; TaskQueuePacedSender pacer(time_controller.GetClock(), &packet_router, trials, - PacingController::kMinSleepTime, TaskQueuePacedSender::kNoPacketHoldback); @@ -694,9 +684,8 @@ TEST(TaskQueuePacedSenderTest, Stats) { static constexpr Timestamp kStartTime = Timestamp::Millis(1234); GlobalSimulatedTimeController time_controller(kStartTime); NiceMock packet_router; - ScopedKeyValueConfig trials; + FieldTrials trials = CreateTestFieldTrials(); TaskQueuePacedSender pacer(time_controller.GetClock(), &packet_router, trials, - PacingController::kMinSleepTime, TaskQueuePacedSender::kNoPacketHoldback); diff --git a/modules/remote_bitrate_estimator/inter_arrival_unittest.cc b/modules/remote_bitrate_estimator/inter_arrival_unittest.cc index 80cb74cc65..50d3b0fe09 100644 --- a/modules/remote_bitrate_estimator/inter_arrival_unittest.cc +++ b/modules/remote_bitrate_estimator/inter_arrival_unittest.cc @@ -34,7 +34,7 @@ const double kAstToMs = 1000.0 / static_cast(1 << kInterArrivalShift); class InterArrivalTest : public ::testing::Test { protected: - virtual void SetUp() { + void SetUp() override { inter_arrival_.reset(new InterArrival(kTimestampGroupLengthUs / 1000, 1.0)); inter_arrival_rtp_.reset(new InterArrival( MakeRtpTimestamp(kTimestampGroupLengthUs), kRtpTimestampToMs)); diff --git a/modules/rtp_rtcp/BUILD.gn b/modules/rtp_rtcp/BUILD.gn index 2a680f5567..5b7d5f4eee 100644 --- a/modules/rtp_rtcp/BUILD.gn +++ b/modules/rtp_rtcp/BUILD.gn @@ -136,7 +136,6 @@ rtc_library("rtp_rtcp_format") { "../../rtc_base:divide_round", "../../rtc_base:event_tracer", "../../rtc_base:logging", - "../../rtc_base:macromagic", "../../rtc_base:safe_compare", "../../rtc_base:safe_conversions", "../../rtc_base:stringutils", @@ -742,7 +741,6 @@ if (rtc_include_tests) { "../../rtc_base:checks", "../../rtc_base:copy_on_write_buffer", "../../rtc_base:logging", - "../../rtc_base:macromagic", "../../rtc_base:random", "../../rtc_base:rate_limiter", "../../rtc_base:rtc_base_tests_utils", diff --git a/modules/rtp_rtcp/include/rtp_rtcp_defines.h b/modules/rtp_rtcp/include/rtp_rtcp_defines.h index aae48bc268..a888e4f3d8 100644 --- a/modules/rtp_rtcp/include/rtp_rtcp_defines.h +++ b/modules/rtp_rtcp/include/rtp_rtcp_defines.h @@ -40,7 +40,7 @@ class RtpPacket; class RtpPacketToSend; namespace rtcp { class TransportFeedback; -} +} // namespace rtcp const int kVideoPayloadTypeFrequency = 90000; @@ -302,7 +302,7 @@ struct RtpPacketCounter { size_t packets; // Number of packets. // The total delay of all `packets`. For RtpPacketToSend packets, this is // `time_in_send_queue()`. For receive packets, this is zero. - webrtc::TimeDelta total_packet_delay = webrtc::TimeDelta::Zero(); + TimeDelta total_packet_delay = TimeDelta::Zero(); }; // Data usage statistics for a (rtp) stream. @@ -391,7 +391,7 @@ struct RtpReceiveStats { // Interarrival jitter in samples. uint32_t jitter = 0; // Interarrival jitter in time. - webrtc::TimeDelta interarrival_jitter = webrtc::TimeDelta::Zero(); + TimeDelta interarrival_jitter = TimeDelta::Zero(); // Time of the last packet received in unix epoch, // i.e. Timestamp::Zero() represents 1st Jan 1970 00:00 diff --git a/modules/rtp_rtcp/source/dtmf_queue.cc b/modules/rtp_rtcp/source/dtmf_queue.cc index 4c315bd8c2..9b9b98a9dc 100644 --- a/modules/rtp_rtcp/source/dtmf_queue.cc +++ b/modules/rtp_rtcp/source/dtmf_queue.cc @@ -17,7 +17,7 @@ namespace { constexpr size_t kDtmfOutbandMax = 20; -} +} // namespace namespace webrtc { DtmfQueue::DtmfQueue() {} diff --git a/modules/rtp_rtcp/source/fec_private_tables_bursty_unittest.cc b/modules/rtp_rtcp/source/fec_private_tables_bursty_unittest.cc index 69fbde03ae..d85b450bdc 100644 --- a/modules/rtp_rtcp/source/fec_private_tables_bursty_unittest.cc +++ b/modules/rtp_rtcp/source/fec_private_tables_bursty_unittest.cc @@ -23,7 +23,7 @@ namespace webrtc { namespace { constexpr uint8_t kMaskRandom15_6[] = {0x82, 0x08, 0x41, 0x04, 0x20, 0x82, 0x10, 0x40, 0x08, 0x20, 0x04, 0x10}; -} +} // namespace namespace fec_private_tables { diff --git a/modules/rtp_rtcp/source/frame_object.cc b/modules/rtp_rtcp/source/frame_object.cc index d1ae7b98d5..6efb262af0 100644 --- a/modules/rtp_rtcp/source/frame_object.cc +++ b/modules/rtp_rtcp/source/frame_object.cc @@ -44,7 +44,7 @@ RtpFrameObject::RtpFrameObject( VideoRotation rotation, VideoContentType content_type, const RTPVideoHeader& video_header, - const std::optional& color_space, + const std::optional& color_space, const std::optional< std::variant>& frame_instrumentation_data, diff --git a/modules/rtp_rtcp/source/frame_object.h b/modules/rtp_rtcp/source/frame_object.h index 44bbf6eec5..ef0112ffe2 100644 --- a/modules/rtp_rtcp/source/frame_object.h +++ b/modules/rtp_rtcp/source/frame_object.h @@ -48,7 +48,7 @@ class RtpFrameObject : public EncodedFrame { VideoRotation rotation, VideoContentType content_type, const RTPVideoHeader& video_header, - const std::optional& color_space, + const std::optional& color_space, const std::optional>& frame_instrumentation_data, diff --git a/modules/rtp_rtcp/source/rtcp_packet/remote_estimate.cc b/modules/rtp_rtcp/source/rtcp_packet/remote_estimate.cc index 30c02cf319..8210628b87 100644 --- a/modules/rtp_rtcp/source/rtcp_packet/remote_estimate.cc +++ b/modules/rtp_rtcp/source/rtcp_packet/remote_estimate.cc @@ -28,9 +28,9 @@ namespace webrtc { namespace rtcp { namespace { -static constexpr int kFieldValueSize = 3; -static constexpr int kFieldSize = 1 + kFieldValueSize; -static constexpr DataRate kDataRateResolution = DataRate::KilobitsPerSec(1); +constexpr int kFieldValueSize = 3; +constexpr int kFieldSize = 1 + kFieldValueSize; +constexpr DataRate kDataRateResolution = DataRate::KilobitsPerSec(1); constexpr int64_t kMaxEncoded = (1 << (kFieldValueSize * 8)) - 1; class DataRateSerializer { diff --git a/modules/rtp_rtcp/source/rtcp_receiver_unittest.cc b/modules/rtp_rtcp/source/rtcp_receiver_unittest.cc index 31d218eea2..d9a777d6de 100644 --- a/modules/rtp_rtcp/source/rtcp_receiver_unittest.cc +++ b/modules/rtp_rtcp/source/rtcp_receiver_unittest.cc @@ -55,7 +55,6 @@ #include "modules/rtp_rtcp/source/rtcp_packet/tmmbr.h" #include "modules/rtp_rtcp/source/rtcp_packet/transport_feedback.h" #include "modules/rtp_rtcp/source/rtp_rtcp_interface.h" -#include "rtc_base/arraysize.h" #include "rtc_base/buffer.h" #include "rtc_base/random.h" #include "system_wrappers/include/clock.h" @@ -1952,7 +1951,7 @@ TEST(RtcpReceiverTest, Nack) { const uint16_t kNackList1[] = {1, 2, 3, 5}; const uint16_t kNackList23[] = {5, 7, 30, 40, 41, 58, 59, 61, 63}; const size_t kNackListLength2 = 4; - const size_t kNackListLength3 = arraysize(kNackList23) - kNackListLength2; + const size_t kNackListLength3 = std::size(kNackList23) - kNackListLength2; std::set nack_set; nack_set.insert(std::begin(kNackList1), std::end(kNackList1)); nack_set.insert(std::begin(kNackList23), std::end(kNackList23)); @@ -1960,7 +1959,7 @@ TEST(RtcpReceiverTest, Nack) { auto nack1 = std::make_unique(); nack1->SetSenderSsrc(kSenderSsrc); nack1->SetMediaSsrc(kReceiverMainSsrc); - nack1->SetPacketIds(kNackList1, arraysize(kNackList1)); + nack1->SetPacketIds(kNackList1, std::size(kNackList1)); EXPECT_CALL(mocks.rtp_rtcp_impl, OnReceivedNack(ElementsAreArray(kNackList1))); @@ -1968,9 +1967,9 @@ TEST(RtcpReceiverTest, Nack) { RtcpPacketTypesCounterUpdated( kReceiverMainSsrc, AllOf(Field(&RtcpPacketTypeCounter::nack_requests, - arraysize(kNackList1)), + std::size(kNackList1)), Field(&RtcpPacketTypeCounter::unique_nack_requests, - arraysize(kNackList1))))); + std::size(kNackList1))))); receiver.IncomingPacket(nack1->Build()); auto nack2 = std::make_unique(); @@ -1993,7 +1992,7 @@ TEST(RtcpReceiverTest, Nack) { RtcpPacketTypesCounterUpdated( kReceiverMainSsrc, AllOf(Field(&RtcpPacketTypeCounter::nack_requests, - arraysize(kNackList1) + arraysize(kNackList23)), + std::size(kNackList1) + std::size(kNackList23)), Field(&RtcpPacketTypeCounter::unique_nack_requests, nack_set.size())))); receiver.IncomingPacket(two_nacks.Build()); diff --git a/modules/rtp_rtcp/source/rtcp_sender.cc b/modules/rtp_rtcp/source/rtcp_sender.cc index e1cbe26e24..e06698e0db 100644 --- a/modules/rtp_rtcp/source/rtcp_sender.cc +++ b/modules/rtp_rtcp/source/rtcp_sender.cc @@ -119,17 +119,12 @@ RTCPSender::FeedbackState::~FeedbackState() = default; class RTCPSender::RtcpContext { public: RtcpContext(const FeedbackState& feedback_state, - int32_t nack_size, - const uint16_t* nack_list, + ArrayView nacks, Timestamp now) - : feedback_state_(feedback_state), - nack_size_(nack_size), - nack_list_(nack_list), - now_(now) {} + : feedback_state_(feedback_state), nacks_(nacks), now_(now) {} const FeedbackState& feedback_state_; - const int32_t nack_size_; - const uint16_t* nack_list_; + const ArrayView nacks_; const Timestamp now_; }; @@ -262,8 +257,7 @@ int32_t RTCPSender::SendLossNotification(const FeedbackState& feedback_state, sender.emplace(callback, max_packet_size_); auto result = ComputeCompoundRTCPPacket( - feedback_state, RTCPPacketType::kRtcpLossNotification, 0, nullptr, - *sender); + feedback_state, RTCPPacketType::kRtcpLossNotification, {}, *sender); if (result) { return *result; } @@ -538,11 +532,11 @@ void RTCPSender::BuildNACK(const RtcpContext& ctx, PacketSender& sender) { rtcp::Nack nack; nack.SetSenderSsrc(ssrc_); nack.SetMediaSsrc(remote_ssrc_); - nack.SetPacketIds(ctx.nack_list_, ctx.nack_size_); + nack.SetPacketIds(ctx.nacks_.data(), ctx.nacks_.size()); // Report stats. - for (int idx = 0; idx < ctx.nack_size_; ++idx) { - nack_stats_.ReportRequest(ctx.nack_list_[idx]); + for (uint16_t sequence_number : ctx.nacks_) { + nack_stats_.ReportRequest(sequence_number); } packet_type_counter_.nack_requests = nack_stats_.requests(); packet_type_counter_.unique_nack_requests = nack_stats_.unique_requests(); @@ -593,8 +587,7 @@ void RTCPSender::BuildExtendedReports(const RtcpContext& ctx, int32_t RTCPSender::SendRTCP(const FeedbackState& feedback_state, RTCPPacketType packet_type, - int32_t nack_size, - const uint16_t* nack_list) { + ArrayView nacks) { int32_t error_code = -1; auto callback = [&](ArrayView packet) { if (transport_->SendRtcp(packet, /*packet_options=*/{})) { @@ -607,8 +600,8 @@ int32_t RTCPSender::SendRTCP(const FeedbackState& feedback_state, { MutexLock lock(&mutex_rtcp_sender_); sender.emplace(callback, max_packet_size_); - auto result = ComputeCompoundRTCPPacket(feedback_state, packet_type, - nack_size, nack_list, *sender); + auto result = + ComputeCompoundRTCPPacket(feedback_state, packet_type, nacks, *sender); if (result) { return *result; } @@ -621,8 +614,7 @@ int32_t RTCPSender::SendRTCP(const FeedbackState& feedback_state, std::optional RTCPSender::ComputeCompoundRTCPPacket( const FeedbackState& feedback_state, RTCPPacketType packet_type, - int32_t nack_size, - const uint16_t* nack_list, + ArrayView nacks, PacketSender& sender) { if (method_ == RtcpMode::kOff) { RTC_LOG(LS_WARNING) << "Can't send RTCP if it is disabled."; @@ -649,8 +641,7 @@ std::optional RTCPSender::ComputeCompoundRTCPPacket( } // We need to send our NTP even if we haven't received any reports. - RtcpContext context(feedback_state, nack_size, nack_list, - env_.clock().CurrentTime()); + RtcpContext context(feedback_state, nacks, env_.clock().CurrentTime()); PrepareReport(feedback_state); diff --git a/modules/rtp_rtcp/source/rtcp_sender.h b/modules/rtp_rtcp/source/rtcp_sender.h index 307228134d..fb9f18b65c 100644 --- a/modules/rtp_rtcp/source/rtcp_sender.h +++ b/modules/rtp_rtcp/source/rtcp_sender.h @@ -22,6 +22,7 @@ #include #include "absl/strings/string_view.h" +#include "api/array_view.h" #include "api/call/transport.h" #include "api/environment/environment.h" #include "api/rtp_headers.h" @@ -147,8 +148,7 @@ class RTCPSender final { int32_t SendRTCP(const FeedbackState& feedback_state, RTCPPacketType packetType, - int32_t nackSize = 0, - const uint16_t* nackList = 0) + ArrayView nacks = {}) RTC_LOCKS_EXCLUDED(mutex_rtcp_sender_); int32_t SendLossNotification(const FeedbackState& feedback_state, @@ -189,8 +189,7 @@ class RTCPSender final { std::optional ComputeCompoundRTCPPacket( const FeedbackState& feedback_state, RTCPPacketType packet_type, - int32_t nack_size, - const uint16_t* nack_list, + ArrayView nacks, PacketSender& sender) RTC_EXCLUSIVE_LOCKS_REQUIRED(mutex_rtcp_sender_); TimeDelta ComputeTimeUntilNextReport(DataRate send_bitrate) diff --git a/modules/rtp_rtcp/source/rtcp_sender_unittest.cc b/modules/rtp_rtcp/source/rtcp_sender_unittest.cc index e93b38e625..4184f22e1b 100644 --- a/modules/rtp_rtcp/source/rtcp_sender_unittest.cc +++ b/modules/rtp_rtcp/source/rtcp_sender_unittest.cc @@ -17,7 +17,6 @@ #include #include -#include "absl/base/macros.h" #include "api/array_view.h" #include "api/call/transport.h" #include "api/environment/environment.h" @@ -383,8 +382,7 @@ TEST_F(RtcpSenderTest, SendNack) { auto rtcp_sender = CreateRtcpSender(GetDefaultConfig()); rtcp_sender->SetRTCPStatus(RtcpMode::kReducedSize); const uint16_t kList[] = {0, 1, 16}; - EXPECT_EQ(0, rtcp_sender->SendRTCP(feedback_state(), kRtcpNack, - ABSL_ARRAYSIZE(kList), kList)); + EXPECT_EQ(0, rtcp_sender->SendRTCP(feedback_state(), kRtcpNack, kList)); EXPECT_EQ(1, parser()->nack()->num_packets()); EXPECT_EQ(kSenderSsrc, parser()->nack()->sender_ssrc()); EXPECT_EQ(kRemoteSsrc, parser()->nack()->media_ssrc()); @@ -425,9 +423,7 @@ TEST_F(RtcpSenderTest, SendLossNotificationBufferingAllowed) { // Sending another messages triggers sending the LNTF messages as well. const uint16_t kList[] = {0, 1, 16}; - EXPECT_EQ(rtcp_sender->SendRTCP(feedback_state(), kRtcpNack, - ABSL_ARRAYSIZE(kList), kList), - 0); + EXPECT_EQ(rtcp_sender->SendRTCP(feedback_state(), kRtcpNack, kList), 0); // Exactly one packet was produced, and it contained both the buffered LNTF // as well as the message that had triggered the packet. diff --git a/modules/rtp_rtcp/source/rtp_header_extension_map.cc b/modules/rtp_rtcp/source/rtp_header_extension_map.cc index ef28dbae20..2ceb5a178b 100644 --- a/modules/rtp_rtcp/source/rtp_header_extension_map.cc +++ b/modules/rtp_rtcp/source/rtp_header_extension_map.cc @@ -21,7 +21,6 @@ #include "modules/rtp_rtcp/source/rtp_generic_frame_descriptor_extension.h" #include "modules/rtp_rtcp/source/rtp_header_extensions.h" #include "modules/rtp_rtcp/source/rtp_video_layers_allocation_extension.h" -#include "rtc_base/arraysize.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" @@ -64,7 +63,7 @@ constexpr ExtensionInfo kExtensions[] = { // Because of kRtpExtensionNone, NumberOfExtension is 1 bigger than the actual // number of known extensions. -static_assert(arraysize(kExtensions) == +static_assert(std::ssize(kExtensions) == static_cast(kRtpExtensionNumberOfExtensions) - 1, "kExtensions expect to list all known extensions"); diff --git a/modules/rtp_rtcp/source/rtp_packet_received.cc b/modules/rtp_rtcp/source/rtp_packet_received.cc index b8fd1e5b6d..f56c31a9fe 100644 --- a/modules/rtp_rtcp/source/rtp_packet_received.cc +++ b/modules/rtp_rtcp/source/rtp_packet_received.cc @@ -26,7 +26,7 @@ namespace webrtc { RtpPacketReceived::RtpPacketReceived() = default; RtpPacketReceived::RtpPacketReceived( const ExtensionManager* extensions, - webrtc::Timestamp arrival_time /*= webrtc::Timestamp::MinusInfinity()*/) + class Timestamp arrival_time /*= Timestamp::MinusInfinity()*/) : RtpPacket(extensions), arrival_time_(arrival_time) {} RtpPacketReceived::RtpPacketReceived(const RtpPacketReceived& packet) = default; RtpPacketReceived::RtpPacketReceived(RtpPacketReceived&& packet) = default; diff --git a/modules/rtp_rtcp/source/rtp_packet_received.h b/modules/rtp_rtcp/source/rtp_packet_received.h index 21a6955044..f4e2a98dbe 100644 --- a/modules/rtp_rtcp/source/rtp_packet_received.h +++ b/modules/rtp_rtcp/source/rtp_packet_received.h @@ -30,7 +30,7 @@ class RtpPacketReceived : public RtpPacket { RtpPacketReceived(); explicit RtpPacketReceived( const ExtensionManager* extensions, - webrtc::Timestamp arrival_time = webrtc::Timestamp::MinusInfinity()); + webrtc::Timestamp arrival_time = Timestamp::MinusInfinity()); RtpPacketReceived(const RtpPacketReceived& packet); RtpPacketReceived(RtpPacketReceived&& packet); diff --git a/modules/rtp_rtcp/source/rtp_packet_to_send.h b/modules/rtp_rtcp/source/rtp_packet_to_send.h index 4e60c1203f..ccbb6faa47 100644 --- a/modules/rtp_rtcp/source/rtp_packet_to_send.h +++ b/modules/rtp_rtcp/source/rtp_packet_to_send.h @@ -45,8 +45,8 @@ class RtpPacketToSend : public RtpPacket { ~RtpPacketToSend(); // Time in local time base as close as it can to frame capture time. - webrtc::Timestamp capture_time() const { return capture_time_; } - void set_capture_time(webrtc::Timestamp time) { capture_time_ = time; } + class Timestamp capture_time() const { return capture_time_; } + void set_capture_time(class Timestamp time) { capture_time_ = time; } void set_packet_type(RtpPacketMediaType type); @@ -87,25 +87,25 @@ class RtpPacketToSend : public RtpPacket { additional_data_ = std::move(data); } - void set_packetization_finish_time(webrtc::Timestamp time) { + void set_packetization_finish_time(class Timestamp time) { SetExtension( VideoSendTiming::GetDeltaCappedMs(time - capture_time_), VideoTimingExtension::kPacketizationFinishDeltaOffset); } - void set_pacer_exit_time(webrtc::Timestamp time) { + void set_pacer_exit_time(class Timestamp time) { SetExtension( VideoSendTiming::GetDeltaCappedMs(time - capture_time_), VideoTimingExtension::kPacerExitDeltaOffset); } - void set_network_time(webrtc::Timestamp time) { + void set_network_time(class Timestamp time) { SetExtension( VideoSendTiming::GetDeltaCappedMs(time - capture_time_), VideoTimingExtension::kNetworkTimestampDeltaOffset); } - void set_network2_time(webrtc::Timestamp time) { + void set_network2_time(class Timestamp time) { SetExtension( VideoSendTiming::GetDeltaCappedMs(time - capture_time_), VideoTimingExtension::kNetwork2TimestampDeltaOffset); @@ -153,7 +153,7 @@ class RtpPacketToSend : public RtpPacket { void set_send_as_ect1() { send_as_ect1_ = true; } private: - webrtc::Timestamp capture_time_ = webrtc::Timestamp::Zero(); + class Timestamp capture_time_ = Timestamp::Zero(); std::optional packet_type_; std::optional original_packet_type_; std::optional original_ssrc_; diff --git a/modules/rtp_rtcp/source/rtp_rtcp_impl.cc b/modules/rtp_rtcp/source/rtp_rtcp_impl.cc index 5bd844f3d4..bc9ccfcebe 100644 --- a/modules/rtp_rtcp/source/rtp_rtcp_impl.cc +++ b/modules/rtp_rtcp/source/rtp_rtcp_impl.cc @@ -99,7 +99,7 @@ ModuleRtpRtcpImpl::ModuleRtpRtcpImpl(const Environment& env, // Set default packet size limit. // TODO(nisse): Kind-of duplicates - // webrtc::VideoSendStream::Config::Rtp::kDefaultMaxPacketSize. + // VideoSendStream::Config::Rtp::kDefaultMaxPacketSize. const size_t kTcpOverIpv4HeaderSize = 40; SetMaxRtpPacketSize(IP_PACKET_SIZE - kTcpOverIpv4HeaderSize); } @@ -593,14 +593,14 @@ int32_t ModuleRtpRtcpImpl::SendNACK(const uint16_t* nack_list, } nack_last_seq_number_sent_ = nack_list[start_id + nack_length - 1]; - return rtcp_sender_.SendRTCP(GetFeedbackState(), kRtcpNack, nack_length, - &nack_list[start_id]); + return rtcp_sender_.SendRTCP( + GetFeedbackState(), kRtcpNack, + MakeArrayView(&nack_list[start_id], nack_length)); } void ModuleRtpRtcpImpl::SendNack( const std::vector& sequence_numbers) { - rtcp_sender_.SendRTCP(GetFeedbackState(), kRtcpNack, sequence_numbers.size(), - sequence_numbers.data()); + rtcp_sender_.SendRTCP(GetFeedbackState(), kRtcpNack, sequence_numbers); } bool ModuleRtpRtcpImpl::TimeToSendFullNackList(int64_t now) const { diff --git a/modules/rtp_rtcp/source/rtp_rtcp_impl2.cc b/modules/rtp_rtcp/source/rtp_rtcp_impl2.cc index f71ca3c1df..f9952a04b0 100644 --- a/modules/rtp_rtcp/source/rtp_rtcp_impl2.cc +++ b/modules/rtp_rtcp/source/rtp_rtcp_impl2.cc @@ -118,7 +118,7 @@ ModuleRtpRtcpImpl2::ModuleRtpRtcpImpl2(const Environment& env, // Set default packet size limit. // TODO(nisse): Kind-of duplicates - // webrtc::VideoSendStream::Config::Rtp::kDefaultMaxPacketSize. + // VideoSendStream::Config::Rtp::kDefaultMaxPacketSize. const size_t kTcpOverIpv4HeaderSize = 40; SetMaxRtpPacketSize(IP_PACKET_SIZE - kTcpOverIpv4HeaderSize); rtt_update_task_ = RepeatingTaskHandle::DelayedStart( @@ -609,14 +609,14 @@ int32_t ModuleRtpRtcpImpl2::SendNACK(const uint16_t* nack_list, } nack_last_seq_number_sent_ = nack_list[start_id + nack_length - 1]; - return rtcp_sender_.SendRTCP(GetFeedbackState(), kRtcpNack, nack_length, - &nack_list[start_id]); + return rtcp_sender_.SendRTCP( + GetFeedbackState(), kRtcpNack, + MakeArrayView(&nack_list[start_id], nack_length)); } void ModuleRtpRtcpImpl2::SendNack( const std::vector& sequence_numbers) { - rtcp_sender_.SendRTCP(GetFeedbackState(), kRtcpNack, sequence_numbers.size(), - sequence_numbers.data()); + rtcp_sender_.SendRTCP(GetFeedbackState(), kRtcpNack, sequence_numbers); } bool ModuleRtpRtcpImpl2::TimeToSendFullNackList(int64_t now) const { diff --git a/modules/rtp_rtcp/source/rtp_rtcp_impl2_unittest.cc b/modules/rtp_rtcp/source/rtp_rtcp_impl2_unittest.cc index 8fa658019a..664b795ae6 100644 --- a/modules/rtp_rtcp/source/rtp_rtcp_impl2_unittest.cc +++ b/modules/rtp_rtcp/source/rtp_rtcp_impl2_unittest.cc @@ -121,7 +121,7 @@ class SendTransport : public Transport, time_controller_->Register(this); } - ~SendTransport() { time_controller_->Unregister(this); } + ~SendTransport() override { time_controller_->Unregister(this); } void SetRtpRtcpModule(ModuleRtpRtcpImpl2* receiver) { receiver_ = receiver; } void SimulateNetworkDelay(TimeDelta delay) { delay_ = delay; } diff --git a/modules/rtp_rtcp/source/rtp_sender.cc b/modules/rtp_rtcp/source/rtp_sender.cc index 888e601e7f..45d5dbf686 100644 --- a/modules/rtp_rtcp/source/rtp_sender.cc +++ b/modules/rtp_rtcp/source/rtp_sender.cc @@ -38,7 +38,6 @@ #include "modules/rtp_rtcp/source/rtp_packet_history.h" #include "modules/rtp_rtcp/source/rtp_packet_to_send.h" #include "modules/rtp_rtcp/source/rtp_rtcp_interface.h" -#include "rtc_base/arraysize.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "rtc_base/numerics/safe_minmax.h" @@ -200,16 +199,15 @@ RTPSender::~RTPSender() { } ArrayView RTPSender::FecExtensionSizes() { - return MakeArrayView(kFecOrPaddingExtensionSizes, - arraysize(kFecOrPaddingExtensionSizes)); + return kFecOrPaddingExtensionSizes; } ArrayView RTPSender::VideoExtensionSizes() { - return MakeArrayView(kVideoExtensionSizes, arraysize(kVideoExtensionSizes)); + return kVideoExtensionSizes; } ArrayView RTPSender::AudioExtensionSizes() { - return MakeArrayView(kAudioExtensionSizes, arraysize(kAudioExtensionSizes)); + return kAudioExtensionSizes; } void RTPSender::SetExtmapAllowMixed(bool extmap_allow_mixed) { diff --git a/modules/rtp_rtcp/source/rtp_sender_unittest.cc b/modules/rtp_rtcp/source/rtp_sender_unittest.cc index eb9306bcab..2607c58391 100644 --- a/modules/rtp_rtcp/source/rtp_sender_unittest.cc +++ b/modules/rtp_rtcp/source/rtp_sender_unittest.cc @@ -92,7 +92,7 @@ using ::testing::SizeIs; class MockRtpPacketPacer : public RtpPacketSender { public: MockRtpPacketPacer() {} - virtual ~MockRtpPacketPacer() {} + ~MockRtpPacketPacer() override {} MOCK_METHOD(void, EnqueuePackets, diff --git a/modules/rtp_rtcp/source/rtp_sender_video.cc b/modules/rtp_rtcp/source/rtp_sender_video.cc index 96662d1743..8503b0db75 100644 --- a/modules/rtp_rtcp/source/rtp_sender_video.cc +++ b/modules/rtp_rtcp/source/rtp_sender_video.cc @@ -804,17 +804,18 @@ bool RTPSenderVideo::SendEncodedImage(int payload_type, uint32_t rtp_timestamp, const EncodedImage& encoded_image, RTPVideoHeader video_header, - TimeDelta expected_retransmission_time) { + TimeDelta expected_retransmission_time, + const std::vector& csrcs) { if (frame_transformer_delegate_) { // The frame will be sent async once transformed. return frame_transformer_delegate_->TransformFrame( payload_type, codec_type, rtp_timestamp, encoded_image, video_header, - expected_retransmission_time); + expected_retransmission_time, csrcs); } return SendVideo(payload_type, codec_type, rtp_timestamp, encoded_image.CaptureTime(), encoded_image, encoded_image.size(), video_header, - expected_retransmission_time, /*csrcs=*/{}); + expected_retransmission_time, csrcs); } DataRate RTPSenderVideo::PostEncodeOverhead() const { diff --git a/modules/rtp_rtcp/source/rtp_sender_video.h b/modules/rtp_rtcp/source/rtp_sender_video.h index 86943db0e8..8e300214af 100644 --- a/modules/rtp_rtcp/source/rtp_sender_video.h +++ b/modules/rtp_rtcp/source/rtp_sender_video.h @@ -116,7 +116,8 @@ class RTPSenderVideo : public RTPVideoFrameSenderInterface { uint32_t rtp_timestamp, const EncodedImage& encoded_image, RTPVideoHeader video_header, - TimeDelta expected_retransmission_time); + TimeDelta expected_retransmission_time, + const std::vector& csrcs = {}); // Configures video structures produced by encoder to send using the // dependency descriptor rtp header extension. Next call to SendVideo should diff --git a/modules/rtp_rtcp/source/rtp_sender_video_frame_transformer_delegate.cc b/modules/rtp_rtcp/source/rtp_sender_video_frame_transformer_delegate.cc index 2d08bd6e8f..7f9a80ed4e 100644 --- a/modules/rtp_rtcp/source/rtp_sender_video_frame_transformer_delegate.cc +++ b/modules/rtp_rtcp/source/rtp_sender_video_frame_transformer_delegate.cc @@ -180,22 +180,21 @@ bool RTPSenderVideoFrameTransformerDelegate::TransformFrame( uint32_t rtp_timestamp, const EncodedImage& encoded_image, RTPVideoHeader video_header, - TimeDelta expected_retransmission_time) { + TimeDelta expected_retransmission_time, + const std::vector& csrcs) { { MutexLock lock(&sender_lock_); if (short_circuit_) { sender_->SendVideo(payload_type, codec_type, rtp_timestamp, encoded_image.CaptureTime(), *encoded_image.GetEncodedData(), encoded_image.size(), - video_header, expected_retransmission_time, - /*csrcs=*/{}); + video_header, expected_retransmission_time, csrcs); return true; } } frame_transformer_->Transform(std::make_unique( encoded_image, video_header, payload_type, codec_type, rtp_timestamp, - expected_retransmission_time, ssrc_, - /*csrcs=*/std::vector())); + expected_retransmission_time, ssrc_, csrcs)); return true; } diff --git a/modules/rtp_rtcp/source/rtp_sender_video_frame_transformer_delegate.h b/modules/rtp_rtcp/source/rtp_sender_video_frame_transformer_delegate.h index 4302fb7e5f..2e84e1f074 100644 --- a/modules/rtp_rtcp/source/rtp_sender_video_frame_transformer_delegate.h +++ b/modules/rtp_rtcp/source/rtp_sender_video_frame_transformer_delegate.h @@ -77,7 +77,8 @@ class RTPSenderVideoFrameTransformerDelegate : public TransformedFrameCallback { uint32_t rtp_timestamp, const EncodedImage& encoded_image, RTPVideoHeader video_header, - TimeDelta expected_retransmission_time); + TimeDelta expected_retransmission_time, + const std::vector& csrcs = {}); // Implements TransformedFrameCallback. Can be called on any thread. Posts // the transformed frame to be sent on the `encoder_queue_`. diff --git a/modules/rtp_rtcp/source/rtp_sender_video_frame_transformer_delegate_unittest.cc b/modules/rtp_rtcp/source/rtp_sender_video_frame_transformer_delegate_unittest.cc index af3083bcc5..48c6d09304 100644 --- a/modules/rtp_rtcp/source/rtp_sender_video_frame_transformer_delegate_unittest.cc +++ b/modules/rtp_rtcp/source/rtp_sender_video_frame_transformer_delegate_unittest.cc @@ -42,6 +42,7 @@ namespace webrtc { namespace { using ::testing::_; +using ::testing::ElementsAreArray; using ::testing::NiceMock; using ::testing::Return; using ::testing::SaveArg; @@ -136,13 +137,22 @@ TEST_F(RtpSenderVideoFrameTransformerDelegateTest, auto delegate = make_ref_counted( &test_sender_, frame_transformer_, /*ssrc=*/1111, time_controller_.CreateTaskQueueFactory().get()); + VideoFrameMetadata metadata; + EXPECT_CALL(*frame_transformer_, Transform) + .WillOnce([&](std::unique_ptr frame) { + metadata = static_cast(frame.get()) + ->Metadata(); + }); + std::vector csrcs = {1, 2, 3}; EncodedImage encoded_image; - EXPECT_CALL(*frame_transformer_, Transform); delegate->TransformFrame( /*payload_type=*/1, VideoCodecType::kVideoCodecVP8, /*rtp_timestamp=*/2, encoded_image, RTPVideoHeader(), - /*expected_retransmission_time=*/TimeDelta::Millis(10)); + /*expected_retransmission_time=*/TimeDelta::Millis(10), csrcs); + + EXPECT_EQ(metadata.GetSsrc(), 1111U); + EXPECT_THAT(metadata.GetCsrcs(), ElementsAreArray(csrcs)); } TEST_F(RtpSenderVideoFrameTransformerDelegateTest, @@ -319,17 +329,19 @@ TEST_F(RtpSenderVideoFrameTransformerDelegateTest, delegate->StartShortCircuiting(); + std::vector csrcs = {1, 2, 3}; // Will not call the actual transformer. EXPECT_CALL(*frame_transformer_, Transform).Times(0); // Will pass the frame straight to the reciever. - EXPECT_CALL(test_sender_, SendVideo); + EXPECT_CALL(test_sender_, + SendVideo(_, _, _, _, _, _, _, _, ElementsAreArray(csrcs))); EncodedImage encoded_image; encoded_image.SetEncodedData(EncodedImageBuffer::Create(1)); delegate->TransformFrame( /*payload_type=*/1, VideoCodecType::kVideoCodecVP8, /*rtp_timestamp=*/2, encoded_image, RTPVideoHeader(), - /*expected_retransmission_time=*/TimeDelta::Millis(10)); + /*expected_retransmission_time=*/TimeDelta::Millis(10), csrcs); } } // namespace diff --git a/modules/rtp_rtcp/source/rtp_sender_video_unittest.cc b/modules/rtp_rtcp/source/rtp_sender_video_unittest.cc index 79432a97fa..c279ee5649 100644 --- a/modules/rtp_rtcp/source/rtp_sender_video_unittest.cc +++ b/modules/rtp_rtcp/source/rtp_sender_video_unittest.cc @@ -10,6 +10,7 @@ #include "modules/rtp_rtcp/source/rtp_sender_video.h" +#include #include #include #include @@ -65,7 +66,6 @@ #include "modules/video_coding/codecs/h264/include/h264_globals.h" #include "modules/video_coding/codecs/vp8/include/vp8_globals.h" #include "modules/video_coding/codecs/vp9/include/vp9_globals.h" -#include "rtc_base/arraysize.h" #include "rtc_base/checks.h" #include "rtc_base/rate_limiter.h" #include "rtc_base/thread.h" @@ -513,10 +513,10 @@ TEST_F(RtpSenderVideoTest, ConditionalRetransmit) { // Fill averaging window to prevent rounding errors. constexpr int kNumRepetitions = RTPSenderVideo::kTLRateWindowSize / kFrameInterval; - constexpr int kPattern[] = {0, 2, 1, 2}; + constexpr std::array kPattern = {0, 2, 1, 2}; auto& vp8_header = header.video_type_header.emplace(); - for (size_t i = 0; i < arraysize(kPattern) * kNumRepetitions; ++i) { - vp8_header.temporalIdx = kPattern[i % arraysize(kPattern)]; + for (size_t i = 0; i < kPattern.size() * kNumRepetitions; ++i) { + vp8_header.temporalIdx = kPattern[i % kPattern.size()]; rtp_sender_video_->AllowRetransmission(header, kSettings, kRtt); fake_clock_.AdvanceTime(kFrameInterval); } @@ -564,10 +564,10 @@ TEST_F(RtpSenderVideoTest, ConditionalRetransmitLimit) { // Fill averaging window to prevent rounding errors. constexpr int kNumRepetitions = RTPSenderVideo::kTLRateWindowSize / kFrameInterval; - constexpr int kPattern[] = {0, 2, 2, 2}; + constexpr std::array kPattern = {0, 2, 2, 2}; auto& vp8_header = header.video_type_header.emplace(); - for (size_t i = 0; i < arraysize(kPattern) * kNumRepetitions; ++i) { - vp8_header.temporalIdx = kPattern[i % arraysize(kPattern)]; + for (size_t i = 0; i < kPattern.size() * kNumRepetitions; ++i) { + vp8_header.temporalIdx = kPattern[i % kPattern.size()]; rtp_sender_video_->AllowRetransmission(header, kSettings, kRtt); fake_clock_.AdvanceTime(kFrameInterval); @@ -1617,6 +1617,55 @@ TEST_F(RtpSenderVideoWithFrameTransformerTest, kDefaultExpectedRetransmissionTime); } +TEST_F(RtpSenderVideoTest, SendEncodedImageIncludesProvidedCsrcs) { + std::vector expected_csrcs = {1, 2, 3}; + std::unique_ptr encoded_image = CreateDefaultEncodedImage(); + RTPVideoHeader video_header; + video_header.frame_type = VideoFrameType::kVideoFrameKey; + + ASSERT_TRUE(rtp_sender_video_->SendEncodedImage( + 0, kType, kTimestamp, *encoded_image, video_header, + kDefaultExpectedRetransmissionTime, expected_csrcs)); + + ASSERT_GT(transport_.packets_sent(), 0); + std::vector csrcs = transport_.last_sent_packet().Csrcs(); + EXPECT_EQ(csrcs, expected_csrcs); +} + +TEST_F(RtpSenderVideoWithFrameTransformerTest, + SendEncodedImageIncludesProvidedCsrcs) { + auto mock_frame_transformer = + make_ref_counted>(); + scoped_refptr callback; + EXPECT_CALL(*mock_frame_transformer, RegisterTransformedFrameSinkCallback) + .WillOnce(SaveArg<0>(&callback)); + std::unique_ptr rtp_sender_video = + CreateSenderWithFrameTransformer(mock_frame_transformer); + ASSERT_TRUE(callback); + ON_CALL(*mock_frame_transformer, Transform) + .WillByDefault( + [&callback](std::unique_ptr frame) { + callback->OnTransformedFrame(std::move(frame)); + }); + + auto encoded_image = CreateDefaultEncodedImage(); + std::vector expected_csrcs = {1, 2, 3}; + RTPVideoHeader video_header; + video_header.frame_type = VideoFrameType::kVideoFrameKey; + auto encoder_queue = time_controller_.GetTaskQueueFactory()->CreateTaskQueue( + "encoder_queue", TaskQueueFactory::Priority::NORMAL); + encoder_queue->PostTask([&] { + rtp_sender_video->SendEncodedImage( + kPayloadType, kType, kTimestamp, *encoded_image, video_header, + kDefaultExpectedRetransmissionTime, expected_csrcs); + }); + time_controller_.AdvanceTime(TimeDelta::Zero()); + + ASSERT_GT(transport_.packets_sent(), 0); + std::vector csrcs = transport_.last_sent_packet().Csrcs(); + EXPECT_EQ(csrcs, expected_csrcs); +} + #if RTC_DCHECK_IS_ON && GTEST_HAS_DEATH_TEST && !defined(WEBRTC_ANDROID) TEST_F(RtpSenderVideoWithFrameTransformerTest, ValidPayloadTypes) { auto mock_frame_transformer = diff --git a/modules/rtp_rtcp/source/rtp_video_header.h b/modules/rtp_rtcp/source/rtp_video_header.h index 1e6579d447..163ebfd241 100644 --- a/modules/rtp_rtcp/source/rtp_video_header.h +++ b/modules/rtp_rtcp/source/rtp_video_header.h @@ -87,7 +87,7 @@ struct RTPVideoHeader { VideoSendTiming video_timing; std::optional color_space; // This field is meant for media quality testing purpose only. When enabled it - // carries the webrtc::VideoFrame id field from the sender to the receiver. + // carries the VideoFrame id field from the sender to the receiver. std::optional video_frame_tracking_id; RTPVideoTypeHeader video_type_header; diff --git a/modules/rtp_rtcp/test/testFec/test_fec.cc b/modules/rtp_rtcp/test/testFec/test_fec.cc index 2898a47940..4a7ceab3a1 100644 --- a/modules/rtp_rtcp/test/testFec/test_fec.cc +++ b/modules/rtp_rtcp/test/testFec/test_fec.cc @@ -39,7 +39,7 @@ namespace webrtc { namespace fec_private_tables { extern const uint8_t** kPacketMaskBurstyTbl[12]; -} +} // namespace fec_private_tables namespace test { using fec_private_tables::kPacketMaskBurstyTbl; diff --git a/modules/utility/BUILD.gn b/modules/utility/BUILD.gn index b30cb0c6d4..167bce9157 100644 --- a/modules/utility/BUILD.gn +++ b/modules/utility/BUILD.gn @@ -23,6 +23,7 @@ rtc_library("utility") { "../../rtc_base:checks", "../../rtc_base:logging", "../../rtc_base:platform_thread", + "../../rtc_base:platform_thread_types", "../../rtc_base/system:arch", ] } diff --git a/modules/utility/include/helpers_android.h b/modules/utility/include/helpers_android.h index 5e8deb9536..c61742edd5 100644 --- a/modules/utility/include/helpers_android.h +++ b/modules/utility/include/helpers_android.h @@ -13,10 +13,6 @@ #include -#include - -#include "rtc_base/system/arch.h" - // Abort the process if `jni` has a Java exception pending. // TODO(henrika): merge with CHECK_JNI_EXCEPTION() in jni_helpers.h. #define CHECK_EXCEPTION(jni) \ diff --git a/modules/utility/include/jvm_android.h b/modules/utility/include/jvm_android.h index bafb8f2c15..5838aa288c 100644 --- a/modules/utility/include/jvm_android.h +++ b/modules/utility/include/jvm_android.h @@ -123,7 +123,7 @@ class JNIEnvironment { // JNIEnv* jni = ::base::android::AttachCurrentThread(); // JavaVM* jvm = NULL; // jni->GetJavaVM(&jvm); -// webrtc::JVM::Initialize(jvm); +// JVM::Initialize(jvm); // // // Header (.h) file of example class called User. // std::unique_ptr env; diff --git a/modules/utility/source/helpers_android.cc b/modules/utility/source/helpers_android.cc index 74e6ed914e..93492b6796 100644 --- a/modules/utility/source/helpers_android.cc +++ b/modules/utility/source/helpers_android.cc @@ -11,12 +11,13 @@ #include "modules/utility/include/helpers_android.h" #include -#include +#include #include -#include + +#include #include "rtc_base/checks.h" -#include "rtc_base/platform_thread.h" +#include "rtc_base/platform_thread_types.h" #define TAG "HelpersAndroid" #define ALOGD(...) __android_log_print(ANDROID_LOG_DEBUG, TAG, __VA_ARGS__) diff --git a/modules/utility/source/jvm_android.cc b/modules/utility/source/jvm_android.cc index 017920ea22..590fa0e66a 100644 --- a/modules/utility/source/jvm_android.cc +++ b/modules/utility/source/jvm_android.cc @@ -10,13 +10,16 @@ #include "modules/utility/include/jvm_android.h" -#include +#include +#include +#include #include +#include +#include "modules/utility/include/helpers_android.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" -#include "rtc_base/platform_thread.h" namespace webrtc { diff --git a/modules/video_capture/BUILD.gn b/modules/video_capture/BUILD.gn index c3e0e5af71..058b86bce4 100644 --- a/modules/video_capture/BUILD.gn +++ b/modules/video_capture/BUILD.gn @@ -59,16 +59,19 @@ if (!build_with_chromium || is_linux || is_chromeos) { "../../api:make_ref_counted", "../../api:scoped_refptr", "../../api:sequence_checker", + "../../common_video", "../../media:video_common", "../../rtc_base:checks", "../../rtc_base:logging", "../../rtc_base:macromagic", "../../rtc_base:platform_thread", + "../../rtc_base:platform_thread_types", "../../rtc_base:refcount", "../../rtc_base:stringutils", "../../rtc_base/synchronization:mutex", "../../rtc_base/system:rtc_export", "../../system_wrappers", + "//third_party/abseil-cpp/absl/strings", ] sources = [ "video_capture_options.cc", diff --git a/modules/video_capture/linux/camera_portal.cc b/modules/video_capture/linux/camera_portal.cc index 106ca1682c..093ad82419 100644 --- a/modules/video_capture/linux/camera_portal.cc +++ b/modules/video_capture/linux/camera_portal.cc @@ -55,7 +55,7 @@ class CameraPortalPrivate { GAsyncResult* result, gpointer user_data); - webrtc::Mutex notifier_lock_; + Mutex notifier_lock_; CameraPortal::PortalNotifier* notifier_ RTC_GUARDED_BY(¬ifier_lock_) = nullptr; @@ -70,7 +70,7 @@ CameraPortalPrivate::CameraPortalPrivate(CameraPortal::PortalNotifier* notifier) CameraPortalPrivate::~CameraPortalPrivate() { { - webrtc::MutexLock lock(¬ifier_lock_); + MutexLock lock(¬ifier_lock_); notifier_ = nullptr; } @@ -237,7 +237,7 @@ void CameraPortalPrivate::OnOpenResponse(GDBusProxy* proxy, } void CameraPortalPrivate::OnPortalDone(RequestResponse result, int fd) { - webrtc::MutexLock lock(¬ifier_lock_); + MutexLock lock(¬ifier_lock_); if (notifier_) { notifier_->OnCameraRequestResult(result, fd); notifier_ = nullptr; diff --git a/modules/video_capture/raw_video_sink_interface.h b/modules/video_capture/raw_video_sink_interface.h index a22ca9811d..eb824c7933 100644 --- a/modules/video_capture/raw_video_sink_interface.h +++ b/modules/video_capture/raw_video_sink_interface.h @@ -28,7 +28,7 @@ class RawVideoSinkInterface { virtual int32_t OnRawFrame(uint8_t* videoFrame, size_t videoFrameLength, - const webrtc::VideoCaptureCapability& frameInfo, + const VideoCaptureCapability& frameInfo, VideoRotation rotation, int64_t captureTime) = 0; }; diff --git a/modules/video_capture/video_capture_options.cc b/modules/video_capture/video_capture_options.cc index dd102df9db..0d401cc610 100644 --- a/modules/video_capture/video_capture_options.cc +++ b/modules/video_capture/video_capture_options.cc @@ -34,8 +34,7 @@ VideoCaptureOptions& VideoCaptureOptions::operator=( void VideoCaptureOptions::Init(Callback* callback) { #if defined(WEBRTC_USE_PIPEWIRE) if (allow_pipewire_) { - pipewire_session_ = - webrtc::make_ref_counted(); + pipewire_session_ = make_ref_counted(); pipewire_session_->Init(callback, pipewire_fd_); return; } diff --git a/modules/video_capture/video_capture_options.h b/modules/video_capture/video_capture_options.h index d1d4ebe4b9..14fa4be252 100644 --- a/modules/video_capture/video_capture_options.h +++ b/modules/video_capture/video_capture_options.h @@ -22,7 +22,7 @@ namespace webrtc { #if defined(WEBRTC_USE_PIPEWIRE) namespace videocapturemodule { class PipeWireSession; -} +} // namespace videocapturemodule #endif // An object that stores initialization parameters for video capturers @@ -64,7 +64,7 @@ class RTC_EXPORT VideoCaptureOptions { bool allow_pipewire() const { return allow_pipewire_; } void set_allow_pipewire(bool allow) { allow_pipewire_ = allow; } void set_pipewire_fd(int fd) { pipewire_fd_ = fd; } - webrtc::scoped_refptr pipewire_session(); + scoped_refptr pipewire_session(); #endif private: @@ -74,7 +74,7 @@ class RTC_EXPORT VideoCaptureOptions { #if defined(WEBRTC_USE_PIPEWIRE) bool allow_pipewire_ = false; int pipewire_fd_ = kInvalidPipeWireFd; - webrtc::scoped_refptr pipewire_session_; + scoped_refptr pipewire_session_; #endif }; diff --git a/modules/video_capture/windows/sink_filter_ds.cc b/modules/video_capture/windows/sink_filter_ds.cc index 33e7a269bb..027a9afb46 100644 --- a/modules/video_capture/windows/sink_filter_ds.cc +++ b/modules/video_capture/windows/sink_filter_ds.cc @@ -14,12 +14,24 @@ #include #include +#include +#include +#include +#include +#include #include - -#include "rtc_base/arraysize.h" +#include + +#include "absl/strings/str_cat.h" +#include "api/scoped_refptr.h" +#include "api/sequence_checker.h" +#include "common_video/libyuv/include/webrtc_libyuv.h" +#include "modules/video_capture/video_capture_defines.h" +#include "modules/video_capture/video_capture_impl.h" +#include "modules/video_capture/windows/help_functions_ds.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" -#include "rtc_base/platform_thread.h" +#include "rtc_base/platform_thread_types.h" #include "rtc_base/string_utils.h" DEFINE_GUID(CLSID_SINKFILTER, @@ -907,7 +919,7 @@ CaptureSinkFilter::JoinFilterGraph(IFilterGraph* graph, LPCWSTR name) { info_.achName[0] = L'\0'; if (name) - lstrcpynW(info_.achName, name, arraysize(info_.achName)); + lstrcpynW(info_.achName, name, std::size(info_.achName)); return S_OK; } diff --git a/modules/video_coding/BUILD.gn b/modules/video_coding/BUILD.gn index 52c391dc3f..606c1161bc 100644 --- a/modules/video_coding/BUILD.gn +++ b/modules/video_coding/BUILD.gn @@ -106,7 +106,6 @@ rtc_library("packet_buffer") { "../../rtc_base:checks", "../../rtc_base:copy_on_write_buffer", "../../rtc_base:logging", - "../../rtc_base:macromagic", "../../rtc_base:mod_ops", "../../rtc_base:rtc_numerics", "../rtp_rtcp:rtp_rtcp_format", @@ -459,7 +458,6 @@ rtc_library("video_coding_utility") { "../../rtc_base/experiments:quality_scaler_settings", "../../rtc_base/experiments:quality_scaling_experiment", "../../rtc_base/experiments:rate_control_settings", - "../../rtc_base/experiments:stable_target_rate_experiment", "../../rtc_base/synchronization:mutex", "../../rtc_base/system:arch", "../../rtc_base/system:file_wrapper", @@ -649,7 +647,6 @@ rtc_library("webrtc_vp8_temporal_layers") { "../../common_video/generic_frame_descriptor", "../../rtc_base:checks", "../../rtc_base:logging", - "../../rtc_base:macromagic", "../../rtc_base:rate_statistics", "../../rtc_base:rtc_numerics", "../../rtc_base:timeutils", @@ -679,7 +676,6 @@ rtc_library("webrtc_vp9_helpers") { "../../media:video_common", "../../rtc_base:checks", "../../rtc_base:logging", - "../../rtc_base/experiments:stable_target_rate_experiment", "svc:scalability_mode_util", "svc:scalability_structures", "svc:scalable_video_controller", @@ -862,6 +858,7 @@ if (rtc_include_tests) { ":webrtc_vp9_helpers", "..:module_api", "../../api:create_frame_generator", + "../../api:field_trials", "../../api:frame_generator_api", "../../api:scoped_refptr", "../../api:sequence_checker", @@ -894,6 +891,7 @@ if (rtc_include_tests) { "../../rtc_base:timeutils", "../../rtc_base/synchronization:mutex", "../../rtc_base/system:no_unique_address", + "../../test:create_test_field_trials", "../../test:test_support", "../../test:video_frame_writer", "../../test:video_test_common", @@ -950,6 +948,7 @@ if (rtc_include_tests) { ":videocodec_test_stats_impl", ":webrtc_vp9_helpers", "../../api:array_view", + "../../api:field_trials_view", "../../api:make_ref_counted", "../../api:rtp_parameters", "../../api:videocodec_test_fixture_api", @@ -959,7 +958,6 @@ if (rtc_include_tests) { "../../api/test/metrics:global_metrics_logger_and_exporter", "../../api/test/metrics:metric", "../../api/test/video:function_video_factory", - "../../api/transport:field_trial_based_config", "../../api/video:encoded_image", "../../api/video:resolution", "../../api/video:video_bitrate_allocation", @@ -989,6 +987,7 @@ if (rtc_include_tests) { "../../rtc_base:threading", "../../rtc_base:timeutils", "../../rtc_base/system:file_wrapper", + "../../test:create_test_field_trials", "../../test:fileutils", "../../test:test_support", "../../test:video_frame_writer", @@ -1030,6 +1029,7 @@ if (rtc_include_tests) { deps = [ ":video_codec_interface", + "../../api:field_trials", "../../api/environment", "../../api/environment:environment_factory", "../../api/test/metrics:global_metrics_logger_and_exporter", @@ -1044,8 +1044,7 @@ if (rtc_include_tests) { "../../rtc_base:checks", "../../rtc_base:logging", "../../rtc_base:stringutils", - "../../test:explicit_key_value_config", - "../../test:field_trial", + "../../test:create_test_field_trials", "../../test:fileutils", "../../test:test_flags", "../../test:test_main", @@ -1103,6 +1102,7 @@ if (rtc_include_tests) { "../../api:array_view", "../../api:create_frame_generator", "../../api:create_videocodec_test_fixture_api", + "../../api:field_trials", "../../api:frame_generator_api", "../../api:mock_video_codec_factory", "../../api:mock_video_decoder", @@ -1137,10 +1137,8 @@ if (rtc_include_tests) { "../../rtc_base:refcount", "../../rtc_base:stringutils", "../../rtc_base:timeutils", - "../../test:explicit_key_value_config", - "../../test:field_trial", + "../../test:create_test_field_trials", "../../test:fileutils", - "../../test:scoped_key_value_config", "../../test:test_support", "../../test:video_test_common", "../rtp_rtcp:rtp_rtcp_format", @@ -1254,6 +1252,7 @@ if (rtc_include_tests) { "../../api:array_view", "../../api:create_simulcast_test_fixture_api", "../../api:fec_controller_api", + "../../api:field_trials", "../../api:field_trials_view", "../../api:make_ref_counted", "../../api:mock_fec_controller_override", @@ -1319,13 +1318,11 @@ if (rtc_include_tests) { "../../rtc_base/system:unused", "../../system_wrappers", "../../system_wrappers:metrics", - "../../test:explicit_key_value_config", + "../../test:create_test_field_trials", "../../test:fake_encoded_frame", "../../test:fake_video_codecs", - "../../test:field_trial", "../../test:fileutils", "../../test:run_loop", - "../../test:scoped_key_value_config", "../../test:test_support", "../../test:video_test_common", "../../test:video_test_support", diff --git a/modules/video_coding/DEPS b/modules/video_coding/DEPS index 49c640bd54..8794491681 100644 --- a/modules/video_coding/DEPS +++ b/modules/video_coding/DEPS @@ -1,5 +1,4 @@ include_rules = [ - "+vpx", "+call", "+common_video", "+sdk", @@ -8,6 +7,7 @@ include_rules = [ "+third_party/libyuv", "+rtc_base/system/rtc_export.h", "+video/config", + "+third_party/libvpx", ] specific_include_rules = { diff --git a/modules/video_coding/codecs/av1/BUILD.gn b/modules/video_coding/codecs/av1/BUILD.gn index 6b97218c84..eb48e4939e 100644 --- a/modules/video_coding/codecs/av1/BUILD.gn +++ b/modules/video_coding/codecs/av1/BUILD.gn @@ -99,6 +99,7 @@ if (rtc_include_tests) { ":dav1d_decoder", "../..:video_codec_interface", "../../../../api:array_view", + "../../../../api:field_trials", "../../../../api/environment", "../../../../api/environment:environment_factory", "../../../../api/transport/rtp:dependency_descriptor", @@ -112,6 +113,7 @@ if (rtc_include_tests) { "../../../../api/video_codecs:scalability_mode", "../../../../api/video_codecs:video_codecs_api", "../../../../rtc_base:checks", + "../../../../test:create_test_field_trials", "../../../../test:explicit_key_value_config", "../../../../test:test_support", ] diff --git a/modules/video_coding/codecs/av1/dav1d_decoder_unittest.cc b/modules/video_coding/codecs/av1/dav1d_decoder_unittest.cc index f2ad3a57a6..cfd1116c8e 100644 --- a/modules/video_coding/codecs/av1/dav1d_decoder_unittest.cc +++ b/modules/video_coding/codecs/av1/dav1d_decoder_unittest.cc @@ -18,11 +18,12 @@ #include "api/array_view.h" #include "api/environment/environment.h" #include "api/environment/environment_factory.h" +#include "api/field_trials.h" #include "api/video/encoded_image.h" #include "api/video/video_frame.h" #include "api/video_codecs/video_decoder.h" #include "modules/video_coding/include/video_error_codes.h" -#include "test/explicit_key_value_config.h" +#include "test/create_test_field_trials.h" #include "test/gmock.h" #include "test/gtest.h" @@ -97,8 +98,8 @@ TEST(Dav1dDecoderTest, KeepsDecodedResolutionByDefault) { TEST(Dav1dDecoderTest, CropsToRenderResolutionWhenCropIsEnabled) { TestAv1Decoder decoder( - CreateEnvironment(std::make_unique( - "WebRTC-Dav1dDecoder-CropToRenderResolution/Enabled/"))); + CreateEnvironment(std::make_unique(CreateTestFieldTrials( + "WebRTC-Dav1dDecoder-CropToRenderResolution/Enabled/")))); decoder.Decode( CreateEncodedImage(kAv1FrameWith36x20EncodededAnd32x16RenderResolution)); EXPECT_EQ(decoder.decoded_frame().width(), 32); @@ -107,8 +108,8 @@ TEST(Dav1dDecoderTest, CropsToRenderResolutionWhenCropIsEnabled) { TEST(Dav1dDecoderTest, DoesNotCropToRenderResolutionWhenCropIsDisabled) { TestAv1Decoder decoder( - CreateEnvironment(std::make_unique( - "WebRTC-Dav1dDecoder-CropToRenderResolution/Disabled/"))); + CreateEnvironment(std::make_unique(CreateTestFieldTrials( + "WebRTC-Dav1dDecoder-CropToRenderResolution/Disabled/")))); decoder.Decode( CreateEncodedImage(kAv1FrameWith36x20EncodededAnd32x16RenderResolution)); EXPECT_EQ(decoder.decoded_frame().width(), 36); diff --git a/modules/video_coding/codecs/av1/libaom_av1_encoder.cc b/modules/video_coding/codecs/av1/libaom_av1_encoder.cc index 339a508256..1ebfe0da06 100644 --- a/modules/video_coding/codecs/av1/libaom_av1_encoder.cc +++ b/modules/video_coding/codecs/av1/libaom_av1_encoder.cc @@ -19,7 +19,6 @@ #include #include "absl/algorithm/container.h" -#include "absl/base/macros.h" #include "absl/base/nullability.h" #include "absl/container/inlined_vector.h" #include "api/environment/environment.h" @@ -87,7 +86,7 @@ aom_superblock_size_t GetSuperblockSize(int width, int height, int threads) { class LibaomAv1Encoder final : public VideoEncoder { public: LibaomAv1Encoder(const Environment& env, LibaomAv1EncoderSettings settings); - ~LibaomAv1Encoder(); + ~LibaomAv1Encoder() override; int InitEncode(const VideoCodec* codec_settings, const Settings& settings) override; @@ -524,7 +523,7 @@ void LibaomAv1Encoder::SetSvcRefFrameConfig( static constexpr int kAv1NumBuffers = 8; aom_svc_ref_frame_config_t ref_frame_config = {}; - RTC_CHECK_LE(layer_frame.Buffers().size(), ABSL_ARRAYSIZE(kPreferedSlotName)); + RTC_CHECK_LE(layer_frame.Buffers().size(), std::size(kPreferedSlotName)); for (size_t i = 0; i < layer_frame.Buffers().size(); ++i) { const CodecBufferUsage& buffer = layer_frame.Buffers()[i]; int slot_name = kPreferedSlotName[i]; diff --git a/modules/video_coding/codecs/av1/libaom_av1_encoder_unittest.cc b/modules/video_coding/codecs/av1/libaom_av1_encoder_unittest.cc index 0bbf6a2814..bcd1695439 100644 --- a/modules/video_coding/codecs/av1/libaom_av1_encoder_unittest.cc +++ b/modules/video_coding/codecs/av1/libaom_av1_encoder_unittest.cc @@ -22,6 +22,7 @@ #include "api/environment/environment.h" #include "api/environment/environment_factory.h" +#include "api/field_trials.h" #include "api/test/create_frame_generator.h" #include "api/test/frame_generator_interface.h" #include "api/units/data_size.h" @@ -41,16 +42,15 @@ #include "modules/video_coding/codecs/test/encoded_video_frame_producer.h" #include "modules/video_coding/include/video_error_codes.h" #include "rtc_base/checks.h" +#include "test/create_test_field_trials.h" #include "test/gmock.h" #include "test/gtest.h" -#include "test/scoped_key_value_config.h" #include "test/testsupport/file_utils.h" #include "test/testsupport/frame_reader.h" namespace webrtc { namespace { -using test::ScopedKeyValueConfig; using ::testing::ElementsAre; using ::testing::Eq; using ::testing::Field; @@ -315,12 +315,12 @@ TEST(LibaomAv1EncoderTest, EncoderInfoWithoutResolutionBitrateLimits) { } TEST(LibaomAv1EncoderTest, EncoderInfoWithBitrateLimitsFromFieldTrial) { - auto field_trials = std::make_unique( - "WebRTC-Av1-GetEncoderInfoOverride/" - "frame_size_pixels:123|456|789," - "min_start_bitrate_bps:11000|22000|33000," - "min_bitrate_bps:44000|55000|66000," - "max_bitrate_bps:77000|88000|99000/"); + auto field_trials = std::make_unique( + CreateTestFieldTrials("WebRTC-Av1-GetEncoderInfoOverride/" + "frame_size_pixels:123|456|789," + "min_start_bitrate_bps:11000|22000|33000," + "min_bitrate_bps:44000|55000|66000," + "max_bitrate_bps:77000|88000|99000/")); const Environment env = CreateEnvironment(std::move(field_trials)); std::unique_ptr encoder = CreateLibaomAv1Encoder(env); diff --git a/modules/video_coding/codecs/h264/h264_decoder_impl.cc b/modules/video_coding/codecs/h264/h264_decoder_impl.cc index f3737a1edd..b6c8417094 100644 --- a/modules/video_coding/codecs/h264/h264_decoder_impl.cc +++ b/modules/video_coding/codecs/h264/h264_decoder_impl.cc @@ -119,13 +119,13 @@ int H264DecoderImpl::AVGetBuffer2(AVCodecContext* context, // http://crbug.com/390941. Our pool is set up to zero-initialize new buffers. // TODO(https://crbug.com/390941): Delete that feature from the video pool, // instead add an explicit call to InitializeData here. - webrtc::scoped_refptr frame_buffer; - webrtc::scoped_refptr i444_buffer; - webrtc::scoped_refptr i420_buffer; - webrtc::scoped_refptr i422_buffer; - webrtc::scoped_refptr i010_buffer; - webrtc::scoped_refptr i210_buffer; - webrtc::scoped_refptr i410_buffer; + scoped_refptr frame_buffer; + scoped_refptr i444_buffer; + scoped_refptr i420_buffer; + scoped_refptr i422_buffer; + scoped_refptr i010_buffer; + scoped_refptr i210_buffer; + scoped_refptr i410_buffer; int bytes_per_pixel = 1; switch (context->pix_fmt) { case AV_PIX_FMT_YUV420P: @@ -405,44 +405,44 @@ int32_t H264DecoderImpl::Decode(const EncodedImage& input_image, VideoFrame* input_frame = static_cast(av_buffer_get_opaque(av_frame_->buf[0])); RTC_DCHECK(input_frame); - webrtc::scoped_refptr frame_buffer = + scoped_refptr frame_buffer = input_frame->video_frame_buffer(); // Instantiate Planar YUV buffer according to video frame buffer type - const webrtc::PlanarYuvBuffer* planar_yuv_buffer = nullptr; - const webrtc::PlanarYuv8Buffer* planar_yuv8_buffer = nullptr; - const webrtc::PlanarYuv16BBuffer* planar_yuv16_buffer = nullptr; + const PlanarYuvBuffer* planar_yuv_buffer = nullptr; + const PlanarYuv8Buffer* planar_yuv8_buffer = nullptr; + const PlanarYuv16BBuffer* planar_yuv16_buffer = nullptr; VideoFrameBuffer::Type video_frame_buffer_type = frame_buffer->type(); switch (video_frame_buffer_type) { case VideoFrameBuffer::Type::kI420: planar_yuv_buffer = frame_buffer->GetI420(); planar_yuv8_buffer = - reinterpret_cast(planar_yuv_buffer); + reinterpret_cast(planar_yuv_buffer); break; case VideoFrameBuffer::Type::kI444: planar_yuv_buffer = frame_buffer->GetI444(); planar_yuv8_buffer = - reinterpret_cast(planar_yuv_buffer); + reinterpret_cast(planar_yuv_buffer); break; case VideoFrameBuffer::Type::kI422: planar_yuv_buffer = frame_buffer->GetI422(); planar_yuv8_buffer = - reinterpret_cast(planar_yuv_buffer); + reinterpret_cast(planar_yuv_buffer); break; case VideoFrameBuffer::Type::kI010: planar_yuv_buffer = frame_buffer->GetI010(); - planar_yuv16_buffer = reinterpret_cast( - planar_yuv_buffer); + planar_yuv16_buffer = + reinterpret_cast(planar_yuv_buffer); break; case VideoFrameBuffer::Type::kI210: planar_yuv_buffer = frame_buffer->GetI210(); - planar_yuv16_buffer = reinterpret_cast( - planar_yuv_buffer); + planar_yuv16_buffer = + reinterpret_cast(planar_yuv_buffer); break; case VideoFrameBuffer::Type::kI410: planar_yuv_buffer = frame_buffer->GetI410(); - planar_yuv16_buffer = reinterpret_cast( - planar_yuv_buffer); + planar_yuv16_buffer = + reinterpret_cast(planar_yuv_buffer); break; default: // If this code is changed to allow other video frame buffer type, @@ -530,7 +530,7 @@ int32_t H264DecoderImpl::Decode(const EncodedImage& input_image, return WEBRTC_VIDEO_CODEC_ERROR; } - webrtc::scoped_refptr cropped_buffer; + scoped_refptr cropped_buffer; switch (video_frame_buffer_type) { case VideoFrameBuffer::Type::kI420: cropped_buffer = WrapI420Buffer( diff --git a/modules/video_coding/codecs/h264/h264_decoder_impl.h b/modules/video_coding/codecs/h264/h264_decoder_impl.h index e9da6a7a0d..09530e7b0f 100644 --- a/modules/video_coding/codecs/h264/h264_decoder_impl.h +++ b/modules/video_coding/codecs/h264/h264_decoder_impl.h @@ -98,7 +98,7 @@ class H264DecoderImpl : public H264Decoder { bool has_reported_init_; bool has_reported_error_; - webrtc::H264BitstreamParser h264_bitstream_parser_; + H264BitstreamParser h264_bitstream_parser_; }; } // namespace webrtc diff --git a/modules/video_coding/codecs/h264/h264_encoder_impl.cc b/modules/video_coding/codecs/h264/h264_encoder_impl.cc index 7792d53e32..387a88b8cf 100644 --- a/modules/video_coding/codecs/h264/h264_encoder_impl.cc +++ b/modules/video_coding/codecs/h264/h264_encoder_impl.cc @@ -48,8 +48,8 @@ namespace { const bool kOpenH264EncoderDetailedLogging = false; // QP scaling thresholds. -static const int kLowH264QpThreshold = 24; -static const int kHighH264QpThreshold = 37; +const int kLowH264QpThreshold = 24; +const int kHighH264QpThreshold = 37; // Used by histograms. Values of entries should not be changed. enum H264EncoderImplEvent { @@ -420,7 +420,7 @@ int32_t H264EncoderImpl::Encode( return WEBRTC_VIDEO_CODEC_UNINITIALIZED; } - webrtc::scoped_refptr frame_buffer = + scoped_refptr frame_buffer = input_frame.video_frame_buffer()->ToI420(); if (!frame_buffer) { RTC_LOG(LS_ERROR) << "Failed to convert " diff --git a/modules/video_coding/codecs/h264/h264_encoder_impl.h b/modules/video_coding/codecs/h264/h264_encoder_impl.h index 2d4a95311d..d8f1156a8f 100644 --- a/modules/video_coding/codecs/h264/h264_encoder_impl.h +++ b/modules/video_coding/codecs/h264/h264_encoder_impl.h @@ -92,14 +92,14 @@ class H264EncoderImpl : public VideoEncoder { private: SEncParamExt CreateEncoderParams(size_t i) const; - webrtc::H264BitstreamParser h264_bitstream_parser_; + H264BitstreamParser h264_bitstream_parser_; // Reports statistics with histograms. void ReportInit(); void ReportError(); std::vector encoders_; std::vector pictures_; - std::vector> downscaled_buffers_; + std::vector> downscaled_buffers_; std::vector configurations_; std::vector encoded_images_; std::vector> svc_controllers_; diff --git a/modules/video_coding/codecs/test/video_codec_test.cc b/modules/video_coding/codecs/test/video_codec_test.cc index a19bd5995b..5f13099ae8 100644 --- a/modules/video_coding/codecs/test/video_codec_test.cc +++ b/modules/video_coding/codecs/test/video_codec_test.cc @@ -23,6 +23,7 @@ #include "absl/flags/flag.h" #include "api/environment/environment.h" #include "api/environment/environment_factory.h" +#include "api/field_trials.h" #include "api/test/metrics/global_metrics_logger_and_exporter.h" #include "api/units/data_rate.h" #include "api/units/frequency.h" @@ -40,8 +41,7 @@ #include "modules/video_coding/svc/scalability_mode_util.h" #include "rtc_base/logging.h" #include "rtc_base/strings/string_builder.h" -#include "test/explicit_key_value_config.h" -#include "test/field_trial.h" +#include "test/create_test_field_trials.h" #include "test/gtest.h" #include "test/test_flags.h" #include "test/testsupport/file_utils.h" @@ -83,7 +83,6 @@ ABSL_FLAG(int, std::numeric_limits::max(), "Keyframe interval in frames."); ABSL_FLAG(int, num_frames, 300, "Number of frames to encode and/or decode."); -ABSL_FLAG(std::string, field_trials, "", "Field trials to apply."); ABSL_FLAG(std::string, test_name, "", "Test name."); ABSL_FLAG(bool, dump_decoder_input, false, "Dump decoder input."); ABSL_FLAG(bool, dump_decoder_output, false, "Dump decoder output."); @@ -114,7 +113,7 @@ VideoInfo kFourPeople_1280x720_30 = { .resolution = {.width = 1280, .height = 720}, .framerate = Frequency::Hertz(30)}; -static constexpr Frequency k90kHz = Frequency::Hertz(90000); +constexpr Frequency k90kHz = Frequency::Hertz(90000); VideoSourceSettings ToSourceSettings(VideoInfo video_info) { return VideoSourceSettings{.file_path = ResourcePath(video_info.name, "yuv"), @@ -576,10 +575,8 @@ INSTANTIATE_TEST_SUITE_P(All, FramerateAdaptationTest::TestParamsToString); TEST(VideoCodecTest, DISABLED_EncodeDecode) { - ScopedFieldTrials field_trials(absl::GetFlag(FLAGS_field_trials)); const Environment env = - CreateEnvironment(std::make_unique( - absl::GetFlag(FLAGS_field_trials))); + CreateEnvironment(std::make_unique(CreateTestFieldTrials())); VideoSourceSettings source_settings{ .file_path = absl::GetFlag(FLAGS_input_path), diff --git a/modules/video_coding/codecs/test/video_codec_unittest.cc b/modules/video_coding/codecs/test/video_codec_unittest.cc index 966da6b879..6357311f0c 100644 --- a/modules/video_coding/codecs/test/video_codec_unittest.cc +++ b/modules/video_coding/codecs/test/video_codec_unittest.cc @@ -47,7 +47,7 @@ static const int kMaxFramerate = 30; // Arbitrary value. namespace webrtc { namespace { const VideoEncoder::Capabilities kCapabilities(false); -} +} // namespace EncodedImageCallback::Result VideoCodecUnitTest::FakeEncodeCompleteCallback::OnEncodedImage( diff --git a/modules/video_coding/codecs/test/video_codec_unittest.h b/modules/video_coding/codecs/test/video_codec_unittest.h index 90b01bfa2a..d03d34fa84 100644 --- a/modules/video_coding/codecs/test/video_codec_unittest.h +++ b/modules/video_coding/codecs/test/video_codec_unittest.h @@ -19,6 +19,7 @@ #include "api/environment/environment.h" #include "api/environment/environment_factory.h" +#include "api/field_trials.h" #include "api/test/frame_generator_interface.h" #include "api/video/encoded_image.h" #include "api/video/video_frame.h" @@ -30,6 +31,7 @@ #include "rtc_base/event.h" #include "rtc_base/synchronization/mutex.h" #include "rtc_base/thread_annotations.h" +#include "test/create_test_field_trials.h" #include "test/gtest.h" namespace webrtc { @@ -37,14 +39,15 @@ namespace webrtc { class VideoCodecUnitTest : public ::testing::Test { public: VideoCodecUnitTest() - : env_(CreateEnvironment()), + : field_trials_(CreateTestFieldTrials()), + env_(CreateEnvironment(&field_trials_)), encode_complete_callback_(this), decode_complete_callback_(this), wait_for_encoded_frames_threshold_(1), last_input_frame_timestamp_(0) {} protected: - class FakeEncodeCompleteCallback : public webrtc::EncodedImageCallback { + class FakeEncodeCompleteCallback : public EncodedImageCallback { public: explicit FakeEncodeCompleteCallback(VideoCodecUnitTest* test) : test_(test) {} @@ -56,7 +59,7 @@ class VideoCodecUnitTest : public ::testing::Test { VideoCodecUnitTest* const test_; }; - class FakeDecodeCompleteCallback : public webrtc::DecodedImageCallback { + class FakeDecodeCompleteCallback : public DecodedImageCallback { public: explicit FakeDecodeCompleteCallback(VideoCodecUnitTest* test) : test_(test) {} @@ -105,6 +108,7 @@ class VideoCodecUnitTest : public ::testing::Test { size_t GetNumEncodedFrames(); + FieldTrials field_trials_; const Environment env_; VideoCodec codec_settings_; diff --git a/modules/video_coding/codecs/test/video_encoder_decoder_instantiation_tests.cc b/modules/video_coding/codecs/test/video_encoder_decoder_instantiation_tests.cc index b0af26f494..6d248e4652 100644 --- a/modules/video_coding/codecs/test/video_encoder_decoder_instantiation_tests.cc +++ b/modules/video_coding/codecs/test/video_encoder_decoder_instantiation_tests.cc @@ -84,7 +84,7 @@ class VideoEncoderDecoderInstantiationTest #endif } - ~VideoEncoderDecoderInstantiationTest() { + ~VideoEncoderDecoderInstantiationTest() override { for (auto& encoder : encoders_) { encoder->Release(); } diff --git a/modules/video_coding/codecs/test/videocodec_test_fixture_impl.cc b/modules/video_coding/codecs/test/videocodec_test_fixture_impl.cc index 5732dccc6d..39e7af4583 100644 --- a/modules/video_coding/codecs/test/videocodec_test_fixture_impl.cc +++ b/modules/video_coding/codecs/test/videocodec_test_fixture_impl.cc @@ -27,13 +27,13 @@ #include "absl/strings/string_view.h" #include "api/array_view.h" #include "api/environment/environment_factory.h" +#include "api/field_trials_view.h" #include "api/make_ref_counted.h" #include "api/rtp_parameters.h" #include "api/test/metrics/global_metrics_logger_and_exporter.h" #include "api/test/metrics/metric.h" #include "api/test/videocodec_test_fixture.h" #include "api/test/videocodec_test_stats.h" -#include "api/transport/field_trial_based_config.h" #include "api/video/encoded_image.h" #include "api/video/resolution.h" #include "api/video/video_codec_constants.h" @@ -74,6 +74,7 @@ #include "rtc_base/task_queue_for_test.h" #include "rtc_base/thread.h" #include "rtc_base/time_utils.h" +#include "test/create_test_field_trials.h" #include "test/gtest.h" #include "test/testsupport/file_utils.h" #include "test/testsupport/frame_reader.h" @@ -92,8 +93,8 @@ const int kBaseKeyFrameInterval = 3000; const int kDefaultMaxFramerateFps = 30; const int kMaxQp = 56; -void ConfigureSimulcast(VideoCodec* codec_settings) { - FieldTrialBasedConfig trials; +void ConfigureSimulcast(const FieldTrialsView& trials, + VideoCodec* codec_settings) { VideoEncoderConfig encoder_config; encoder_config.codec_type = codec_settings->codecType; encoder_config.number_of_streams = codec_settings->numberOfSimulcastStreams; @@ -215,7 +216,8 @@ SdpVideoFormat CreateSdpVideoFormat( } // namespace -VideoCodecTestFixtureImpl::Config::Config() = default; +VideoCodecTestFixtureImpl::Config::Config() + : field_trials(CreateTestFieldTrials()) {} void VideoCodecTestFixtureImpl::Config::SetCodecSettings( std::string codec_name_to_set, @@ -288,7 +290,7 @@ void VideoCodecTestFixtureImpl::Config::SetCodecSettings( } if (codec_settings.numberOfSimulcastStreams > 1) { - ConfigureSimulcast(&codec_settings); + ConfigureSimulcast(field_trials, &codec_settings); } else if (codec_settings.codecType == kVideoCodecVP9 && codec_settings.VP9()->numberOfSpatialLayers > 1) { ConfigureSvc(&codec_settings); @@ -469,8 +471,8 @@ VideoCodecTestFixtureImpl::VideoCodecTestFixtureImpl(Config config) LibvpxVp9DecoderTemplateAdapter, OpenH264DecoderTemplateAdapter, Dav1dDecoderTemplateAdapter>>()), - env_(CreateEnvironment()), - config_(config) {} + config_(std::move(config)), + env_(CreateEnvironment(&config_.field_trials)) {} VideoCodecTestFixtureImpl::VideoCodecTestFixtureImpl( Config config, @@ -478,8 +480,8 @@ VideoCodecTestFixtureImpl::VideoCodecTestFixtureImpl( std::unique_ptr encoder_factory) : encoder_factory_(std::move(encoder_factory)), decoder_factory_(std::move(decoder_factory)), - env_(CreateEnvironment()), - config_(config) {} + config_(std::move(config)), + env_(CreateEnvironment(&config_.field_trials)) {} VideoCodecTestFixtureImpl::~VideoCodecTestFixtureImpl() = default; diff --git a/modules/video_coding/codecs/test/videocodec_test_fixture_impl.h b/modules/video_coding/codecs/test/videocodec_test_fixture_impl.h index b36b80adc5..a9a16069e7 100644 --- a/modules/video_coding/codecs/test/videocodec_test_fixture_impl.h +++ b/modules/video_coding/codecs/test/videocodec_test_fixture_impl.h @@ -95,8 +95,8 @@ class VideoCodecTestFixtureImpl : public VideoCodecTestFixture { VideoProcessor::VideoDecoderList decoders_; // Helper objects. - const Environment env_; Config config_; + const Environment env_; VideoCodecTestStatsImpl stats_; std::unique_ptr source_frame_reader_; VideoProcessor::IvfFileWriterMap encoded_frame_writers_; diff --git a/modules/video_coding/codecs/test/videocodec_test_stats_impl.cc b/modules/video_coding/codecs/test/videocodec_test_stats_impl.cc index fb2ccfebb5..61fd5817bc 100644 --- a/modules/video_coding/codecs/test/videocodec_test_stats_impl.cc +++ b/modules/video_coding/codecs/test/videocodec_test_stats_impl.cc @@ -34,7 +34,7 @@ using VideoStatistics = VideoCodecTestStats::VideoStatistics; namespace { const int kMaxBitrateMismatchPercent = 20; -} +} // namespace VideoCodecTestStatsImpl::VideoCodecTestStatsImpl() = default; VideoCodecTestStatsImpl::~VideoCodecTestStatsImpl() = default; diff --git a/modules/video_coding/codecs/test/videoprocessor_unittest.cc b/modules/video_coding/codecs/test/videoprocessor_unittest.cc index 66f36d6854..0e44884260 100644 --- a/modules/video_coding/codecs/test/videoprocessor_unittest.cc +++ b/modules/video_coding/codecs/test/videoprocessor_unittest.cc @@ -64,7 +64,7 @@ class VideoProcessorTest : public ::testing::Test { }); } - ~VideoProcessorTest() { + ~VideoProcessorTest() override { q_.SendTask([this] { video_processor_.reset(); }); } diff --git a/modules/video_coding/codecs/vp8/default_temporal_layers.cc b/modules/video_coding/codecs/vp8/default_temporal_layers.cc index cd55e0ff37..0ad4bb8f62 100644 --- a/modules/video_coding/codecs/vp8/default_temporal_layers.cc +++ b/modules/video_coding/codecs/vp8/default_temporal_layers.cc @@ -31,7 +31,6 @@ #include "modules/video_coding/codecs/interface/common_constants.h" #include "modules/video_coding/codecs/vp8/include/temporal_layers_checker.h" #include "modules/video_coding/include/video_codec_interface.h" -#include "rtc_base/arraysize.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" @@ -58,9 +57,9 @@ constexpr BufferFlags kUpdate = BufferFlags::kUpdate; constexpr BufferFlags kReferenceAndUpdate = BufferFlags::kReferenceAndUpdate; constexpr FreezeEntropy kFreezeEntropy = FreezeEntropy::kFreezeEntropy; -static constexpr uint8_t kUninitializedPatternIndex = +constexpr uint8_t kUninitializedPatternIndex = std::numeric_limits::max(); -static constexpr std::array kAllBuffers = { +constexpr std::array kAllBuffers = { {Vp8BufferReference::kLast, Vp8BufferReference::kGolden, Vp8BufferReference::kAltref}}; @@ -546,7 +545,7 @@ void DefaultTemporalLayers::OnEncodeDone(size_t stream_index, if (!is_keyframe && frame_config.References(static_cast(i))) { RTC_DCHECK_LT(vp8_info.referencedBuffersCount, - arraysize(CodecSpecificInfoVP8::referencedBuffers)); + std::size(vp8_info.referencedBuffers)); references = true; vp8_info.referencedBuffers[vp8_info.referencedBuffersCount++] = i; } @@ -554,7 +553,7 @@ void DefaultTemporalLayers::OnEncodeDone(size_t stream_index, if (is_keyframe || frame_config.Updates(static_cast(i))) { RTC_DCHECK_LT(vp8_info.updatedBuffersCount, - arraysize(CodecSpecificInfoVP8::updatedBuffers)); + std::size(vp8_info.updatedBuffers)); updates = true; vp8_info.updatedBuffers[vp8_info.updatedBuffersCount++] = i; } diff --git a/modules/video_coding/codecs/vp8/default_temporal_layers_unittest.cc b/modules/video_coding/codecs/vp8/default_temporal_layers_unittest.cc index 503c6a19ff..b50db65f96 100644 --- a/modules/video_coding/codecs/vp8/default_temporal_layers_unittest.cc +++ b/modules/video_coding/codecs/vp8/default_temporal_layers_unittest.cc @@ -30,7 +30,7 @@ #include "modules/video_coding/utility/simulcast_rate_allocator.h" #include "test/gmock.h" #include "test/gtest.h" -#include "vpx/vp8cx.h" +#include "third_party/libvpx/source/libvpx/vpx/vp8cx.h" // TODO(bugs.webrtc.org/10582): Test the behavior of UpdateConfiguration(). @@ -388,7 +388,7 @@ class TemporalLayersReferenceTest : public TemporalLayersTest, : timestamp_(1), last_sync_timestamp_(timestamp_), tl0_reference_(nullptr) {} - virtual ~TemporalLayersReferenceTest() {} + ~TemporalLayersReferenceTest() override {} protected: static const int kMaxPatternLength = 32; diff --git a/modules/video_coding/codecs/vp8/libvpx_vp8_decoder.cc b/modules/video_coding/codecs/vp8/libvpx_vp8_decoder.cc index 741c4628d2..c05a91df34 100644 --- a/modules/video_coding/codecs/vp8/libvpx_vp8_decoder.cc +++ b/modules/video_coding/codecs/vp8/libvpx_vp8_decoder.cc @@ -35,11 +35,11 @@ #include "rtc_base/numerics/exp_filter.h" #include "rtc_base/time_utils.h" #include "system_wrappers/include/metrics.h" +#include "third_party/libvpx/source/libvpx/vpx/vp8.h" +#include "third_party/libvpx/source/libvpx/vpx/vp8dx.h" +#include "third_party/libvpx/source/libvpx/vpx/vpx_decoder.h" +#include "third_party/libvpx/source/libvpx/vpx/vpx_image.h" #include "third_party/libyuv/include/libyuv/convert.h" -#include "vpx/vp8.h" -#include "vpx/vp8dx.h" -#include "vpx/vpx_decoder.h" -#include "vpx/vpx_image.h" namespace webrtc { namespace { diff --git a/modules/video_coding/codecs/vp8/libvpx_vp8_decoder.h b/modules/video_coding/codecs/vp8/libvpx_vp8_decoder.h index 58c209de99..e9056eb93a 100644 --- a/modules/video_coding/codecs/vp8/libvpx_vp8_decoder.h +++ b/modules/video_coding/codecs/vp8/libvpx_vp8_decoder.h @@ -20,8 +20,8 @@ #include "api/video/encoded_image.h" #include "api/video_codecs/video_decoder.h" #include "common_video/include/video_frame_buffer_pool.h" -#include "vpx/vpx_decoder.h" -#include "vpx/vpx_image.h" +#include "third_party/libvpx/source/libvpx/vpx/vpx_decoder.h" +#include "third_party/libvpx/source/libvpx/vpx/vpx_image.h" namespace webrtc { @@ -61,7 +61,7 @@ class LibvpxVp8Decoder : public VideoDecoder { int ReturnFrame(const vpx_image_t* img, uint32_t timeStamp, int qp, - const webrtc::ColorSpace* explicit_color_space); + const ColorSpace* explicit_color_space); const bool use_postproc_; VideoFrameBufferPool buffer_pool_; diff --git a/modules/video_coding/codecs/vp8/libvpx_vp8_encoder.cc b/modules/video_coding/codecs/vp8/libvpx_vp8_encoder.cc index 4557a4fab1..9e533cf33e 100644 --- a/modules/video_coding/codecs/vp8/libvpx_vp8_encoder.cc +++ b/modules/video_coding/codecs/vp8/libvpx_vp8_encoder.cc @@ -60,10 +60,10 @@ #include "rtc_base/logging.h" #include "rtc_base/numerics/safe_conversions.h" #include "rtc_base/trace_event.h" -#include "vpx/vp8cx.h" -#include "vpx/vpx_codec.h" -#include "vpx/vpx_encoder.h" -#include "vpx/vpx_image.h" +#include "third_party/libvpx/source/libvpx/vpx/vp8cx.h" +#include "third_party/libvpx/source/libvpx/vpx/vpx_codec.h" +#include "third_party/libvpx/source/libvpx/vpx/vpx_encoder.h" +#include "third_party/libvpx/source/libvpx/vpx/vpx_image.h" #if (defined(WEBRTC_ARCH_ARM) || defined(WEBRTC_ARCH_ARM64)) && \ (defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)) @@ -79,8 +79,8 @@ constexpr char kVP8IosMaxNumberOfThreadFieldTrialParameter[] = "max_thread"; #endif namespace variable_framerate_screenshare { -static constexpr double kMinFps = 5.0; -static constexpr int kUndershootPct = 30; +constexpr double kMinFps = 5.0; +constexpr int kUndershootPct = 30; } // namespace variable_framerate_screenshare constexpr char kVp8ForcePartitionResilience[] = diff --git a/modules/video_coding/codecs/vp8/libvpx_vp8_encoder.h b/modules/video_coding/codecs/vp8/libvpx_vp8_encoder.h index 02f36e8d15..9b5088732a 100644 --- a/modules/video_coding/codecs/vp8/libvpx_vp8_encoder.h +++ b/modules/video_coding/codecs/vp8/libvpx_vp8_encoder.h @@ -37,8 +37,8 @@ #include "modules/video_coding/utility/framerate_controller_deprecated.h" #include "rtc_base/experiments/encoder_info_settings.h" #include "rtc_base/experiments/rate_control_settings.h" -#include "vpx/vpx_encoder.h" -#include "vpx/vpx_image.h" +#include "third_party/libvpx/source/libvpx/vpx/vpx_encoder.h" +#include "third_party/libvpx/source/libvpx/vpx/vpx_image.h" namespace webrtc { diff --git a/modules/video_coding/codecs/vp8/screenshare_layers.cc b/modules/video_coding/codecs/vp8/screenshare_layers.cc index f89c7364ad..885d44bdf0 100644 --- a/modules/video_coding/codecs/vp8/screenshare_layers.cc +++ b/modules/video_coding/codecs/vp8/screenshare_layers.cc @@ -26,7 +26,6 @@ #include "modules/video_coding/codecs/interface/common_constants.h" #include "modules/video_coding/codecs/vp8/include/temporal_layers_checker.h" #include "modules/video_coding/include/video_codec_interface.h" -#include "rtc_base/arraysize.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "rtc_base/time_utils.h" @@ -376,7 +375,7 @@ void ScreenshareLayers::OnEncodeDone(size_t stream_index, if (!is_keyframe && dependency_info->frame_config.References( static_cast(i))) { RTC_DCHECK_LT(vp8_info.referencedBuffersCount, - arraysize(CodecSpecificInfoVP8::referencedBuffers)); + std::size(vp8_info.referencedBuffers)); references = true; vp8_info.referencedBuffers[vp8_info.referencedBuffersCount++] = i; } @@ -384,7 +383,7 @@ void ScreenshareLayers::OnEncodeDone(size_t stream_index, if (is_keyframe || dependency_info->frame_config.Updates( static_cast(i))) { RTC_DCHECK_LT(vp8_info.updatedBuffersCount, - arraysize(CodecSpecificInfoVP8::updatedBuffers)); + std::size(vp8_info.updatedBuffers)); updates = true; vp8_info.updatedBuffers[vp8_info.updatedBuffersCount++] = i; } diff --git a/modules/video_coding/codecs/vp8/screenshare_layers_unittest.cc b/modules/video_coding/codecs/vp8/screenshare_layers_unittest.cc index 8158b0dcad..cfafc7249e 100644 --- a/modules/video_coding/codecs/vp8/screenshare_layers_unittest.cc +++ b/modules/video_coding/codecs/vp8/screenshare_layers_unittest.cc @@ -30,7 +30,7 @@ #include "system_wrappers/include/metrics.h" #include "test/gmock.h" #include "test/gtest.h" -#include "vpx/vp8cx.h" +#include "third_party/libvpx/source/libvpx/vpx/vp8cx.h" using ::testing::_; using ::testing::ElementsAre; @@ -68,7 +68,7 @@ class ScreenshareLayerTest : public ::testing::Test { frame_size_(-1), timestamp_(90), config_updated_(false) {} - virtual ~ScreenshareLayerTest() {} + ~ScreenshareLayerTest() override {} void SetUp() override { layers_.reset(new ScreenshareLayers(2)); diff --git a/modules/video_coding/codecs/vp8/test/vp8_impl_unittest.cc b/modules/video_coding/codecs/vp8/test/vp8_impl_unittest.cc index 2f537f0a91..f129cbc6f8 100644 --- a/modules/video_coding/codecs/vp8/test/vp8_impl_unittest.cc +++ b/modules/video_coding/codecs/vp8/test/vp8_impl_unittest.cc @@ -22,6 +22,7 @@ #include "absl/container/inlined_vector.h" #include "absl/memory/memory.h" #include "api/environment/environment_factory.h" +#include "api/field_trials.h" #include "api/scoped_refptr.h" #include "api/test/create_frame_generator.h" #include "api/test/frame_generator_interface.h" @@ -48,15 +49,14 @@ #include "modules/video_coding/include/video_error_codes.h" #include "modules/video_coding/utility/vp8_header_parser.h" #include "rtc_base/time_utils.h" -#include "test/field_trial.h" +#include "test/create_test_field_trials.h" #include "test/gmock.h" #include "test/gtest.h" #include "test/mappable_native_buffer.h" -#include "test/scoped_key_value_config.h" #include "test/video_codec_settings.h" -#include "vpx/vpx_codec.h" -#include "vpx/vpx_encoder.h" -#include "vpx/vpx_image.h" +#include "third_party/libvpx/source/libvpx/vpx/vpx_codec.h" +#include "third_party/libvpx/source/libvpx/vpx/vpx_encoder.h" +#include "third_party/libvpx/source/libvpx/vpx/vpx_image.h" namespace webrtc { @@ -174,13 +174,14 @@ TEST_F(TestVp8Impl, DefaultErrorResilienceEnabledForTemporalLayers) { TEST_F(TestVp8Impl, PartitionErrorResilienceEnabledForTemporalLayersWithFieldTrial) { - test::ScopedFieldTrials field_trials( - "WebRTC-VP8-ForcePartitionResilience/Enabled/"); + FieldTrials field_trials = + CreateTestFieldTrials("WebRTC-VP8-ForcePartitionResilience/Enabled/"); codec_settings_.simulcastStream[0].numberOfTemporalLayers = 2; codec_settings_.VP8()->numberOfTemporalLayers = 2; auto* const vpx = new NiceMock(); - LibvpxVp8Encoder encoder(CreateEnvironment(), {}, absl::WrapUnique(vpx)); + LibvpxVp8Encoder encoder(CreateEnvironment(&field_trials), {}, + absl::WrapUnique(vpx)); EXPECT_CALL(*vpx, codec_enc_init(_, _, Field(&vpx_codec_enc_cfg_t::g_error_resilient, @@ -686,7 +687,7 @@ TEST(LibvpxVp8EncoderTest, GetEncoderInfoReturnsStaticInformation) { } TEST(LibvpxVp8EncoderTest, RequestedResolutionAlignmentFromFieldTrial) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials = CreateTestFieldTrials( "WebRTC-VP8-GetEncoderInfoOverride/" "requested_resolution_alignment:10/"); @@ -701,7 +702,7 @@ TEST(LibvpxVp8EncoderTest, RequestedResolutionAlignmentFromFieldTrial) { } TEST(LibvpxVp8EncoderTest, ResolutionBitrateLimitsFromFieldTrial) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials = CreateTestFieldTrials( "WebRTC-VP8-GetEncoderInfoOverride/" "frame_size_pixels:123|456|789," "min_start_bitrate_bps:11000|22000|33000," @@ -874,11 +875,9 @@ class TestVp8ImplWithMaxFrameDropTrial : public TestVp8Impl, public WithParamInterface> { public: - TestVp8ImplWithMaxFrameDropTrial() - : TestVp8Impl(), trials_(std::get<0>(GetParam())) {} - - protected: - test::ScopedFieldTrials trials_; + TestVp8ImplWithMaxFrameDropTrial() { + field_trials_.Merge(FieldTrials(std::get<0>(GetParam()))); + } }; TEST_P(TestVp8ImplWithMaxFrameDropTrial, EnforcesMaxFrameDropInterval) { @@ -940,8 +939,9 @@ TEST_P(TestVp8ImplWithMaxFrameDropTrial, EnforcesMaxFrameDropInterval) { void ClearCallbackDeltas() { callback_deltas_.clear(); } protected: - Result OnEncodedImage(const EncodedImage& encoded_image, - const CodecSpecificInfo* /* codec_specific_info */) { + Result OnEncodedImage( + const EncodedImage& encoded_image, + const CodecSpecificInfo* /* codec_specific_info */) override { Timestamp timestamp = Timestamp::Millis(encoded_image.RtpTimestamp() / 90); if (last_callback_.IsFinite()) { diff --git a/modules/video_coding/codecs/vp9/libvpx_vp9_decoder.cc b/modules/video_coding/codecs/vp9/libvpx_vp9_decoder.cc index e6d9f96a8f..2dce0d1033 100644 --- a/modules/video_coding/codecs/vp9/libvpx_vp9_decoder.cc +++ b/modules/video_coding/codecs/vp9/libvpx_vp9_decoder.cc @@ -33,10 +33,10 @@ #include "modules/video_coding/utility/vp9_uncompressed_header_parser.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" -#include "vpx/vp8dx.h" -#include "vpx/vpx_decoder.h" -#include "vpx/vpx_encoder.h" -#include "vpx/vpx_image.h" +#include "third_party/libvpx/source/libvpx/vpx/vp8dx.h" +#include "third_party/libvpx/source/libvpx/vpx/vpx_decoder.h" +#include "third_party/libvpx/source/libvpx/vpx/vpx_encoder.h" +#include "third_party/libvpx/source/libvpx/vpx/vpx_image.h" namespace webrtc { namespace { diff --git a/modules/video_coding/codecs/vp9/libvpx_vp9_decoder.h b/modules/video_coding/codecs/vp9/libvpx_vp9_decoder.h index 773b94cd3f..8067fe068c 100644 --- a/modules/video_coding/codecs/vp9/libvpx_vp9_decoder.h +++ b/modules/video_coding/codecs/vp9/libvpx_vp9_decoder.h @@ -21,8 +21,8 @@ #include "api/video_codecs/video_decoder.h" #include "modules/video_coding/codecs/vp9/include/vp9.h" #include "modules/video_coding/codecs/vp9/vp9_frame_buffer_pool.h" -#include "vpx/vpx_codec.h" -#include "vpx/vpx_image.h" +#include "third_party/libvpx/source/libvpx/vpx/vpx_codec.h" +#include "third_party/libvpx/source/libvpx/vpx/vpx_image.h" namespace webrtc { @@ -47,7 +47,7 @@ class LibvpxVp9Decoder : public VP9Decoder { int ReturnFrame(const vpx_image_t* img, uint32_t timestamp, int qp, - const webrtc::ColorSpace* explicit_color_space); + const ColorSpace* explicit_color_space); // Memory pool used to share buffers between libvpx and webrtc. Vp9FrameBufferPool libvpx_buffer_pool_; diff --git a/modules/video_coding/codecs/vp9/libvpx_vp9_encoder.cc b/modules/video_coding/codecs/vp9/libvpx_vp9_encoder.cc index ce540775f4..d941cd6f00 100644 --- a/modules/video_coding/codecs/vp9/libvpx_vp9_encoder.cc +++ b/modules/video_coding/codecs/vp9/libvpx_vp9_encoder.cc @@ -70,9 +70,9 @@ #include "rtc_base/numerics/safe_conversions.h" #include "rtc_base/strings/string_builder.h" #include "rtc_base/trace_event.h" -#include "vpx/vp8cx.h" -#include "vpx/vpx_encoder.h" -#include "vpx/vpx_image.h" +#include "third_party/libvpx/source/libvpx/vpx/vp8cx.h" +#include "third_party/libvpx/source/libvpx/vpx/vpx_encoder.h" +#include "third_party/libvpx/source/libvpx/vpx/vpx_image.h" #if (defined(WEBRTC_ARCH_ARM) || defined(WEBRTC_ARCH_ARM64)) && \ (defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)) diff --git a/modules/video_coding/codecs/vp9/libvpx_vp9_encoder.h b/modules/video_coding/codecs/vp9/libvpx_vp9_encoder.h index aa54caa6b2..d5ce6105a3 100644 --- a/modules/video_coding/codecs/vp9/libvpx_vp9_encoder.h +++ b/modules/video_coding/codecs/vp9/libvpx_vp9_encoder.h @@ -43,10 +43,10 @@ #include "modules/video_coding/utility/framerate_controller_deprecated.h" #include "rtc_base/containers/flat_map.h" #include "rtc_base/experiments/encoder_info_settings.h" -#include "vpx/vp8cx.h" -#include "vpx/vpx_codec.h" -#include "vpx/vpx_encoder.h" -#include "vpx/vpx_image.h" +#include "third_party/libvpx/source/libvpx/vpx/vp8cx.h" +#include "third_party/libvpx/source/libvpx/vpx/vpx_codec.h" +#include "third_party/libvpx/source/libvpx/vpx/vpx_encoder.h" +#include "third_party/libvpx/source/libvpx/vpx/vpx_image.h" namespace webrtc { diff --git a/modules/video_coding/codecs/vp9/test/vp9_impl_unittest.cc b/modules/video_coding/codecs/vp9/test/vp9_impl_unittest.cc index e23fe8b561..fc392cfd00 100644 --- a/modules/video_coding/codecs/vp9/test/vp9_impl_unittest.cc +++ b/modules/video_coding/codecs/vp9/test/vp9_impl_unittest.cc @@ -22,6 +22,7 @@ #include "absl/memory/memory.h" #include "api/array_view.h" #include "api/environment/environment_factory.h" +#include "api/field_trials.h" #include "api/scoped_refptr.h" #include "api/test/create_frame_generator.h" #include "api/test/frame_generator_interface.h" @@ -57,16 +58,15 @@ #include "modules/video_coding/include/video_error_codes.h" #include "modules/video_coding/svc/scalability_mode_util.h" #include "modules/video_coding/utility/vp9_uncompressed_header_parser.h" -#include "test/explicit_key_value_config.h" -#include "test/field_trial.h" +#include "test/create_test_field_trials.h" #include "test/gmock.h" #include "test/gtest.h" #include "test/mappable_native_buffer.h" #include "test/video_codec_settings.h" -#include "vpx/vp8cx.h" -#include "vpx/vpx_codec.h" -#include "vpx/vpx_encoder.h" -#include "vpx/vpx_image.h" +#include "third_party/libvpx/source/libvpx/vpx/vp8cx.h" +#include "third_party/libvpx/source/libvpx/vpx/vpx_codec.h" +#include "third_party/libvpx/source/libvpx/vpx/vpx_encoder.h" +#include "third_party/libvpx/source/libvpx/vpx/vpx_image.h" namespace webrtc { namespace { @@ -1887,12 +1887,11 @@ TEST_F(TestVp9Impl, EncoderInfoWithoutResolutionBitrateLimits) { } TEST_F(TestVp9Impl, EncoderInfoWithBitrateLimitsFromFieldTrial) { - test::ScopedFieldTrials field_trials( - "WebRTC-VP9-GetEncoderInfoOverride/" - "frame_size_pixels:123|456|789," - "min_start_bitrate_bps:11000|22000|33000," - "min_bitrate_bps:44000|55000|66000," - "max_bitrate_bps:77000|88000|99000/"); + field_trials_.Set("WebRTC-VP9-GetEncoderInfoOverride", + "frame_size_pixels:123|456|789," + "min_start_bitrate_bps:11000|22000|33000," + "min_bitrate_bps:44000|55000|66000," + "max_bitrate_bps:77000|88000|99000"); SetUp(); EXPECT_THAT( @@ -2227,8 +2226,7 @@ TEST_F(TestVp9ImplProfile2, EncodeDecode) { TEST_F(TestVp9Impl, EncodeWithDynamicRate) { // Configured dynamic rate field trial and re-create the encoder. - test::ScopedFieldTrials field_trials( - "WebRTC-VideoRateControl/vp9_dynamic_rate:true/"); + field_trials_.Set("WebRTC-VideoRateControl", "vp9_dynamic_rate:true"); SetUp(); // Set 300kbps target with 100% headroom. @@ -2459,7 +2457,7 @@ TEST_F(TestVp9Impl, ScalesInputToActiveResolution) { TEST(Vp9SpeedSettingsTrialsTest, NoSvcUsesGlobalSpeedFromTl0InLayerConfig) { // TL0 speed 8 at >= 480x270, 5 if below that. - test::ExplicitKeyValueConfig trials( + FieldTrials trials = CreateTestFieldTrials( "WebRTC-VP9-PerformanceFlags/" "use_per_layer_speed," "min_pixel_count:0|129600," @@ -2504,7 +2502,7 @@ TEST(Vp9SpeedSettingsTrialsTest, NoSvcUsesGlobalSpeedFromTl0InLayerConfig) { TEST(Vp9SpeedSettingsTrialsTest, NoPerLayerFlagUsesGlobalSpeedFromTopLayerInConfig) { // TL0 speed 8 at >= 480x270, 5 if below that. - test::ExplicitKeyValueConfig trials( + FieldTrials trials = CreateTestFieldTrials( "WebRTC-VP9-PerformanceFlags/" "min_pixel_count:0|129600," "base_layer_speed:4|8," @@ -2561,7 +2559,7 @@ TEST(Vp9SpeedSettingsTrialsTest, DefaultPerLayerFlagsWithSvc) { // SL1/2: TL0 = speed 7, TL1/TL2 = speed 8. // Deblocking-mode per spatial layer: // SL0: mode 1, SL1/2: mode 0. - test::ExplicitKeyValueConfig trials( + FieldTrials trials = CreateTestFieldTrials( "WebRTC-VP9-PerformanceFlags/" "use_per_layer_speed," "min_pixel_count:0|129600," @@ -2721,10 +2719,9 @@ class TestVp9ImplSvcFrameDropConfig TEST_P(TestVp9ImplSvcFrameDropConfig, SvcFrameDropConfig) { SvcFrameDropConfigTestParameters test_params = GetParam(); auto* const vpx = new NiceMock(); - LibvpxVp9Encoder encoder( - CreateEnvironment(std::make_unique( - test_params.field_trial)), - {}, absl::WrapUnique(vpx)); + LibvpxVp9Encoder encoder(CreateEnvironment(std::make_unique( + CreateTestFieldTrials(test_params.field_trial))), + {}, absl::WrapUnique(vpx)); vpx_image_t img; ON_CALL(*vpx, img_wrap).WillByDefault(GetWrapImageFunction(&img)); diff --git a/modules/video_coding/codecs/vp9/vp9.cc b/modules/video_coding/codecs/vp9/vp9.cc index cc773f24a0..5888ed8120 100644 --- a/modules/video_coding/codecs/vp9/vp9.cc +++ b/modules/video_coding/codecs/vp9/vp9.cc @@ -23,9 +23,9 @@ #include "modules/video_coding/codecs/vp9/libvpx_vp9_decoder.h" #include "modules/video_coding/codecs/vp9/libvpx_vp9_encoder.h" #include "modules/video_coding/svc/create_scalability_structure.h" -#include "vpx/vp8cx.h" -#include "vpx/vp8dx.h" -#include "vpx/vpx_codec.h" +#include "third_party/libvpx/source/libvpx/vpx/vp8cx.h" +#include "third_party/libvpx/source/libvpx/vpx/vp8dx.h" +#include "third_party/libvpx/source/libvpx/vpx/vpx_codec.h" namespace webrtc { diff --git a/modules/video_coding/codecs/vp9/vp9_frame_buffer_pool.cc b/modules/video_coding/codecs/vp9/vp9_frame_buffer_pool.cc index d8d91bc1d6..bcb85315a3 100644 --- a/modules/video_coding/codecs/vp9/vp9_frame_buffer_pool.cc +++ b/modules/video_coding/codecs/vp9/vp9_frame_buffer_pool.cc @@ -20,9 +20,9 @@ #include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "rtc_base/synchronization/mutex.h" -#include "vpx/vpx_codec.h" -#include "vpx/vpx_decoder.h" -#include "vpx/vpx_frame_buffer.h" +#include "third_party/libvpx/source/libvpx/vpx/vpx_codec.h" +#include "third_party/libvpx/source/libvpx/vpx/vpx_decoder.h" +#include "third_party/libvpx/source/libvpx/vpx/vpx_frame_buffer.h" namespace webrtc { diff --git a/modules/video_coding/deprecated/BUILD.gn b/modules/video_coding/deprecated/BUILD.gn index 9b68262c0a..d7227b86cf 100644 --- a/modules/video_coding/deprecated/BUILD.gn +++ b/modules/video_coding/deprecated/BUILD.gn @@ -191,6 +191,7 @@ rtc_library("deprecated_unittests") { ":deprecated_receiver", ":deprecated_session_info", ":deprecated_stream_generator", + "../../../api:field_trials", "../../../api:rtp_headers", "../../../api/units:time_delta", "../../../api/video:video_frame", @@ -202,6 +203,7 @@ rtc_library("deprecated_unittests") { "../../../modules/video_coding/timing:timing_module", "../../../rtc_base:checks", "../../../system_wrappers", + "../../../test:create_test_field_trials", "../../../test:scoped_key_value_config", "../../../test:test_support", "//third_party/abseil-cpp/absl/memory", diff --git a/modules/video_coding/deprecated/frame_buffer.h b/modules/video_coding/deprecated/frame_buffer.h index 9aae5dbf9d..18c36529b3 100644 --- a/modules/video_coding/deprecated/frame_buffer.h +++ b/modules/video_coding/deprecated/frame_buffer.h @@ -72,7 +72,7 @@ class VCMFrameBuffer : public VCMEncodedFrame { int64_t LatestPacketTimeMs() const; - webrtc::VideoFrameType FrameType() const; + VideoFrameType FrameType() const; private: void SetState(VCMFrameBufferStateEnum state); // Set state of frame diff --git a/modules/video_coding/deprecated/jitter_buffer_unittest.cc b/modules/video_coding/deprecated/jitter_buffer_unittest.cc index 5c7c265811..cf1dd54960 100644 --- a/modules/video_coding/deprecated/jitter_buffer_unittest.cc +++ b/modules/video_coding/deprecated/jitter_buffer_unittest.cc @@ -17,6 +17,7 @@ #include #include "absl/memory/memory.h" +#include "api/field_trials.h" #include "api/rtp_headers.h" #include "api/video/video_codec_type.h" #include "api/video/video_frame_type.h" @@ -30,8 +31,8 @@ #include "modules/video_coding/deprecated/stream_generator.h" #include "modules/video_coding/encoded_frame.h" #include "system_wrappers/include/clock.h" +#include "test/create_test_field_trials.h" #include "test/gtest.h" -#include "test/scoped_key_value_config.h" namespace webrtc { @@ -122,7 +123,7 @@ class TestBasicJitterBuffer : public ::testing::Test { uint32_t timestamp_; int size_; uint8_t data_[1500]; - test::ScopedKeyValueConfig field_trials_; + FieldTrials field_trials_ = CreateTestFieldTrials(); std::unique_ptr packet_; std::unique_ptr clock_; std::unique_ptr jitter_buffer_; @@ -132,7 +133,7 @@ class TestRunningJitterBuffer : public ::testing::Test { protected: enum { kDataBufferSize = 10 }; - virtual void SetUp() { + void SetUp() override { clock_.reset(new SimulatedClock(0)); max_nack_list_size_ = 150; oldest_packet_to_nack_ = 250; @@ -145,7 +146,7 @@ class TestRunningJitterBuffer : public ::testing::Test { memset(data_buffer_, 0, kDataBufferSize); } - virtual void TearDown() { + void TearDown() override { jitter_buffer_->Stop(); delete stream_generator_; delete jitter_buffer_; @@ -217,7 +218,7 @@ class TestRunningJitterBuffer : public ::testing::Test { return ret; } - test::ScopedKeyValueConfig field_trials_; + FieldTrials field_trials_ = CreateTestFieldTrials(); VCMJitterBuffer* jitter_buffer_; StreamGenerator* stream_generator_; std::unique_ptr clock_; @@ -229,9 +230,9 @@ class TestRunningJitterBuffer : public ::testing::Test { class TestJitterBufferNack : public TestRunningJitterBuffer { protected: TestJitterBufferNack() {} - virtual void SetUp() { TestRunningJitterBuffer::SetUp(); } + void SetUp() override { TestRunningJitterBuffer::SetUp(); } - virtual void TearDown() { TestRunningJitterBuffer::TearDown(); } + void TearDown() override { TestRunningJitterBuffer::TearDown(); } }; TEST_F(TestBasicJitterBuffer, StopRunning) { diff --git a/modules/video_coding/deprecated/receiver_unittest.cc b/modules/video_coding/deprecated/receiver_unittest.cc index 0d41a111d7..1221b4e02a 100644 --- a/modules/video_coding/deprecated/receiver_unittest.cc +++ b/modules/video_coding/deprecated/receiver_unittest.cc @@ -16,6 +16,7 @@ #include #include +#include "api/field_trials.h" #include "api/units/time_delta.h" #include "api/video/video_frame_type.h" #include "modules/video_coding/deprecated/event_wrapper.h" @@ -26,15 +27,16 @@ #include "modules/video_coding/timing/timing.h" #include "rtc_base/checks.h" #include "system_wrappers/include/clock.h" +#include "test/create_test_field_trials.h" #include "test/gtest.h" -#include "test/scoped_key_value_config.h" namespace webrtc { class TestVCMReceiver : public ::testing::Test { protected: TestVCMReceiver() - : clock_(0), + : field_trials_(CreateTestFieldTrials()), + clock_(0), timing_(&clock_, field_trials_), receiver_(&timing_, &clock_, field_trials_), stream_generator_(0, clock_.TimeInMilliseconds()) {} @@ -82,7 +84,7 @@ class TestVCMReceiver : public ::testing::Test { return true; } - test::ScopedKeyValueConfig field_trials_; + FieldTrials field_trials_; SimulatedClock clock_; VCMTiming timing_; VCMReceiver receiver_; @@ -247,7 +249,7 @@ class SimulatedClockWithFrames : public SimulatedClock { : SimulatedClock(0), stream_generator_(stream_generator), receiver_(receiver) {} - virtual ~SimulatedClockWithFrames() {} + ~SimulatedClockWithFrames() override {} // If `stop_on_frame` is true and next frame arrives between now and // now+`milliseconds`, the clock will be advanced to the arrival time of next @@ -368,7 +370,8 @@ class FrameInjectEvent : public EventWrapper { class VCMReceiverTimingTest : public ::testing::Test { protected: VCMReceiverTimingTest() - : clock_(&stream_generator_, &receiver_), + : field_trials_(CreateTestFieldTrials()), + clock_(&stream_generator_, &receiver_), stream_generator_(0, clock_.TimeInMilliseconds()), timing_(&clock_, field_trials_), receiver_( @@ -378,9 +381,9 @@ class VCMReceiverTimingTest : public ::testing::Test { std::unique_ptr(new FrameInjectEvent(&clock_, true)), field_trials_) {} - virtual void SetUp() {} + void SetUp() override {} - test::ScopedKeyValueConfig field_trials_; + FieldTrials field_trials_; SimulatedClockWithFrames clock_; StreamGenerator stream_generator_; VCMTiming timing_; diff --git a/modules/video_coding/deprecated/session_info.h b/modules/video_coding/deprecated/session_info.h index 735d649c6d..1533f96b27 100644 --- a/modules/video_coding/deprecated/session_info.h +++ b/modules/video_coding/deprecated/session_info.h @@ -53,7 +53,7 @@ class VCMSessionInfo { int NumPackets() const; bool HaveFirstPacket() const; bool HaveLastPacket() const; - webrtc::VideoFrameType FrameType() const { return frame_type_; } + VideoFrameType FrameType() const { return frame_type_; } int LowSequenceNumber() const; // Returns highest sequence number, media or empty. @@ -102,7 +102,7 @@ class VCMSessionInfo { void UpdateCompleteSession(); bool complete_; - webrtc::VideoFrameType frame_type_; + VideoFrameType frame_type_; // Packets in this frame. PacketList packets_; int empty_seq_num_low_; diff --git a/modules/video_coding/deprecated/session_info_unittest.cc b/modules/video_coding/deprecated/session_info_unittest.cc index 598a2ef1d5..e648b77c2c 100644 --- a/modules/video_coding/deprecated/session_info_unittest.cc +++ b/modules/video_coding/deprecated/session_info_unittest.cc @@ -23,7 +23,7 @@ namespace webrtc { class TestSessionInfo : public ::testing::Test { protected: - virtual void SetUp() { + void SetUp() override { memset(packet_buffer_, 0, sizeof(packet_buffer_)); memset(frame_buffer_, 0, sizeof(frame_buffer_)); session_.Reset(); @@ -66,7 +66,7 @@ class TestSessionInfo : public ::testing::Test { class TestNalUnits : public TestSessionInfo { protected: - virtual void SetUp() { + void SetUp() override { TestSessionInfo::SetUp(); packet_.video_header.codec = kVideoCodecVP8; } @@ -86,7 +86,7 @@ class TestNackList : public TestSessionInfo { protected: static const size_t kMaxSeqNumListLength = 30; - virtual void SetUp() { + void SetUp() override { TestSessionInfo::SetUp(); seq_num_list_length_ = 0; memset(seq_num_list_, 0, sizeof(seq_num_list_)); diff --git a/modules/video_coding/encoded_frame.h b/modules/video_coding/encoded_frame.h index b9c528f722..e33a38d692 100644 --- a/modules/video_coding/encoded_frame.h +++ b/modules/video_coding/encoded_frame.h @@ -37,8 +37,8 @@ class RTC_EXPORT VCMEncodedFrame : public EncodedImage { /** * Get the encoded image */ - const webrtc::EncodedImage& EncodedImage() const { - return static_cast(*this); + const EncodedImage& EncodedImage() const { + return static_cast(*this); } using EncodedImage::ColorSpace; @@ -90,7 +90,7 @@ class RTC_EXPORT VCMEncodedFrame : public EncodedImage { uint8_t _payloadType; bool _missingFrame; CodecSpecificInfo _codecSpecificInfo; - webrtc::VideoCodecType _codec; + VideoCodecType _codec; }; } // namespace webrtc diff --git a/modules/video_coding/fec_controller_unittest.cc b/modules/video_coding/fec_controller_unittest.cc index 30d3d90a62..4a162e2472 100644 --- a/modules/video_coding/fec_controller_unittest.cc +++ b/modules/video_coding/fec_controller_unittest.cc @@ -42,7 +42,7 @@ class ProtectionBitrateCalculatorTest : public ::testing::Test { *sent_fec_rate_bps = fec_rate_bps_; return 0; } - void SetRetransmissionMode(int /* retransmission_mode */) {} + void SetRetransmissionMode(int /* retransmission_mode */) override {} uint32_t fec_rate_bps_ = 0; uint32_t nack_rate_bps_ = 0; diff --git a/modules/video_coding/frame_helpers.cc b/modules/video_coding/frame_helpers.cc index 1ce54c08fd..c4a502e810 100644 --- a/modules/video_coding/frame_helpers.cc +++ b/modules/video_coding/frame_helpers.cc @@ -28,7 +28,7 @@ namespace webrtc { namespace { constexpr TimeDelta kMaxVideoDelay = TimeDelta::Millis(10000); -} +} // namespace bool FrameHasBadRenderTiming(Timestamp render_time, Timestamp now) { // Zero render time means render immediately. diff --git a/modules/video_coding/generic_decoder.cc b/modules/video_coding/generic_decoder.cc index b6d14adf6b..ab23106f94 100644 --- a/modules/video_coding/generic_decoder.cc +++ b/modules/video_coding/generic_decoder.cc @@ -51,7 +51,7 @@ namespace { constexpr size_t kDecoderFrameMemoryLength = 10; -} +} // namespace VCMDecodedFrameCallback::VCMDecodedFrameCallback( VCMTiming* timing, diff --git a/modules/video_coding/generic_decoder_unittest.cc b/modules/video_coding/generic_decoder_unittest.cc index 29f8bdd59a..e75c040b04 100644 --- a/modules/video_coding/generic_decoder_unittest.cc +++ b/modules/video_coding/generic_decoder_unittest.cc @@ -16,6 +16,7 @@ #include #include "api/array_view.h" +#include "api/field_trials.h" #include "api/rtp_packet_infos.h" #include "api/scoped_refptr.h" #include "api/units/time_delta.h" @@ -34,10 +35,10 @@ #include "modules/video_coding/include/video_coding_defines.h" #include "modules/video_coding/timing/timing.h" #include "system_wrappers/include/clock.h" +#include "test/create_test_field_trials.h" #include "test/fake_decoder.h" #include "test/gmock.h" #include "test/gtest.h" -#include "test/scoped_key_value_config.h" #include "test/time_controller/simulated_time_controller.h" using ::testing::Return; @@ -72,7 +73,7 @@ class ReceiveCallback : public VCMReceiveCallback { ArrayView GetAllFrames() const { return frames_; } - void OnDroppedFrames(uint32_t frames_dropped) { + void OnDroppedFrames(uint32_t frames_dropped) override { frames_dropped_ += frames_dropped; } @@ -93,6 +94,7 @@ class GenericDecoderTest : public ::testing::Test { GenericDecoderTest() : time_controller_(Timestamp::Zero()), clock_(time_controller_.GetClock()), + field_trials_(CreateTestFieldTrials()), timing_(time_controller_.GetClock(), field_trials_), decoder_(time_controller_.GetTaskQueueFactory()), vcm_callback_(&timing_, @@ -113,7 +115,7 @@ class GenericDecoderTest : public ::testing::Test { GlobalSimulatedTimeController time_controller_; Clock* const clock_; - test::ScopedKeyValueConfig field_trials_; + FieldTrials field_trials_; VCMTiming timing_; test::FakeDecoder decoder_; VCMDecodedFrameCallback vcm_callback_; diff --git a/modules/video_coding/h26x_packet_buffer_unittest.cc b/modules/video_coding/h26x_packet_buffer_unittest.cc index c07de1f0a1..467184ebef 100644 --- a/modules/video_coding/h26x_packet_buffer_unittest.cc +++ b/modules/video_coding/h26x_packet_buffer_unittest.cc @@ -51,9 +51,9 @@ using H264::NaluType::kStapA; constexpr int kBufferSize = 2048; // Example sprop string from https://tools.ietf.org/html/rfc3984. const char kExampleSpropString[] = "Z0IACpZTBYmI,aMljiA=="; -static const std::vector kExampleSpropRawSps{ - 0x67, 0x42, 0x00, 0x0A, 0x96, 0x53, 0x05, 0x89, 0x88}; -static const std::vector kExampleSpropRawPps{0x68, 0xC9, 0x63, 0x88}; +const std::vector kExampleSpropRawSps{0x67, 0x42, 0x00, 0x0A, 0x96, + 0x53, 0x05, 0x89, 0x88}; +const std::vector kExampleSpropRawPps{0x68, 0xC9, 0x63, 0x88}; std::vector StartCode() { return {0, 0, 0, 1}; diff --git a/modules/video_coding/nack_requester_unittest.cc b/modules/video_coding/nack_requester_unittest.cc index 5432f3cb4b..411ddb22a0 100644 --- a/modules/video_coding/nack_requester_unittest.cc +++ b/modules/video_coding/nack_requester_unittest.cc @@ -22,9 +22,9 @@ #include "rtc_base/checks.h" #include "rtc_base/thread.h" #include "system_wrappers/include/clock.h" +#include "test/create_test_field_trials.h" #include "test/gtest.h" #include "test/run_loop.h" -#include "test/scoped_key_value_config.h" namespace webrtc { // TODO(bugs.webrtc.org/11594): Use the use the GlobalSimulatedTimeController @@ -86,10 +86,9 @@ class TestNackRequester : public ::testing::Test, RTC_DCHECK(!nack_module_.get()); nack_periodic_processor_ = std::make_unique(interval); - test::ScopedKeyValueConfig empty_field_trials_; nack_module_ = std::make_unique( TaskQueueBase::Current(), nack_periodic_processor_.get(), clock_.get(), - this, this, empty_field_trials_); + this, this, CreateTestFieldTrials()); nack_module_->UpdateRtt(kDefaultRttMs); return *nack_module_.get(); } @@ -271,14 +270,13 @@ class TestNackRequesterWithFieldTrial : public ::testing::Test, public KeyFrameRequestSender { protected: TestNackRequesterWithFieldTrial() - : nack_delay_field_trial_("WebRTC-SendNackDelayMs/10/"), - clock_(new SimulatedClock(0)), + : clock_(new SimulatedClock(0)), nack_module_(TaskQueueBase::Current(), &nack_periodic_processor_, clock_.get(), this, this, - nack_delay_field_trial_), + CreateTestFieldTrials("WebRTC-SendNackDelayMs/10/")), keyframes_requested_(0) {} void SendNack(const std::vector& sequence_numbers, @@ -289,7 +287,6 @@ class TestNackRequesterWithFieldTrial : public ::testing::Test, void RequestKeyFrame() override { ++keyframes_requested_; } - test::ScopedKeyValueConfig nack_delay_field_trial_; AutoThread main_thread_; std::unique_ptr clock_; NackPeriodicProcessor nack_periodic_processor_; diff --git a/modules/video_coding/svc/BUILD.gn b/modules/video_coding/svc/BUILD.gn index 81c747d536..6cb19bfe8f 100644 --- a/modules/video_coding/svc/BUILD.gn +++ b/modules/video_coding/svc/BUILD.gn @@ -83,7 +83,6 @@ rtc_library("svc_rate_allocator") { "../../../api/video_codecs:scalability_mode", "../../../api/video_codecs:video_codecs_api", "../../../rtc_base:checks", - "../../../rtc_base/experiments:stable_target_rate_experiment", "//third_party/abseil-cpp/absl/container:inlined_vector", ] } @@ -147,6 +146,7 @@ if (rtc_include_tests) { deps = [ ":svc_rate_allocator", "..:webrtc_vp9_helpers", + "../../../api:field_trials", "../../../api/units:data_rate", "../../../api/video:video_bitrate_allocation", "../../../api/video:video_bitrate_allocator", @@ -155,6 +155,7 @@ if (rtc_include_tests) { "../../../api/video_codecs:scalability_mode", "../../../api/video_codecs:video_codecs_api", "../../../rtc_base:checks", + "../../../test:create_test_field_trials", "../../../test:explicit_key_value_config", "../../../test:test_support", "../codecs/av1:av1_svc_config", diff --git a/modules/video_coding/svc/svc_rate_allocator.cc b/modules/video_coding/svc/svc_rate_allocator.cc index fbf5dcd9ea..df05a206fb 100644 --- a/modules/video_coding/svc/svc_rate_allocator.cc +++ b/modules/video_coding/svc/svc_rate_allocator.cc @@ -97,9 +97,9 @@ std::vector AdjustAndVerify( return adjusted_spatial_layer_rates; } -static std::vector SplitBitrate(size_t num_layers, - DataRate total_bitrate, - float rate_scaling_factor) { +std::vector SplitBitrate(size_t num_layers, + DataRate total_bitrate, + float rate_scaling_factor) { std::vector bitrates; double denominator = 0.0; @@ -249,7 +249,6 @@ SvcRateAllocator::SvcRateAllocator(const VideoCodec& codec, const FieldTrialsView& field_trials) : codec_(codec), num_layers_(GetNumLayers(codec)), - experiment_settings_(field_trials), cumulative_layer_start_bitrates_(GetLayerStartBitrates(codec)), last_active_layer_count_(0) { RTC_DCHECK_GT(num_layers_.spatial, 0); @@ -295,29 +294,7 @@ VideoBitrateAllocation SvcRateAllocator::Allocate( } // Figure out how many spatial layers should be active. - if (experiment_settings_.IsEnabled() && - parameters.stable_bitrate > DataRate::Zero()) { - double hysteresis_factor; - if (codec_.mode == VideoCodecMode::kScreensharing) { - hysteresis_factor = experiment_settings_.GetScreenshareHysteresisFactor(); - } else { - hysteresis_factor = experiment_settings_.GetVideoHysteresisFactor(); - } - - DataRate stable_rate = std::min(total_bitrate, parameters.stable_bitrate); - // First check if bitrate has grown large enough to enable new layers. - size_t num_enabled_with_hysteresis = - FindNumEnabledLayers(stable_rate / hysteresis_factor); - if (num_enabled_with_hysteresis >= last_active_layer_count_) { - num_spatial_layers = num_enabled_with_hysteresis; - } else { - // We could not enable new layers, check if any should be disabled. - num_spatial_layers = - std::min(last_active_layer_count_, FindNumEnabledLayers(stable_rate)); - } - } else { - num_spatial_layers = FindNumEnabledLayers(total_bitrate); - } + num_spatial_layers = FindNumEnabledLayers(total_bitrate); last_active_layer_count_ = num_spatial_layers; std::vector spatial_layer_bitrates; diff --git a/modules/video_coding/svc/svc_rate_allocator.h b/modules/video_coding/svc/svc_rate_allocator.h index a8d05b6ec0..56960b8c44 100644 --- a/modules/video_coding/svc/svc_rate_allocator.h +++ b/modules/video_coding/svc/svc_rate_allocator.h @@ -22,7 +22,6 @@ #include "api/video/video_bitrate_allocator.h" #include "api/video/video_codec_constants.h" #include "api/video_codecs/video_codec.h" -#include "rtc_base/experiments/stable_target_rate_experiment.h" namespace webrtc { @@ -62,7 +61,6 @@ class SvcRateAllocator : public VideoBitrateAllocator { const VideoCodec codec_; const NumLayers num_layers_; - const StableTargetRateExperiment experiment_settings_; const absl::InlinedVector cumulative_layer_start_bitrates_; size_t last_active_layer_count_; diff --git a/modules/video_coding/svc/svc_rate_allocator_unittest.cc b/modules/video_coding/svc/svc_rate_allocator_unittest.cc index 09a769a0ec..fc64411489 100644 --- a/modules/video_coding/svc/svc_rate_allocator_unittest.cc +++ b/modules/video_coding/svc/svc_rate_allocator_unittest.cc @@ -16,6 +16,7 @@ #include #include "absl/container/inlined_vector.h" +#include "api/field_trials.h" #include "api/units/data_rate.h" #include "api/video/video_bitrate_allocation.h" #include "api/video/video_bitrate_allocator.h" @@ -27,7 +28,7 @@ #include "modules/video_coding/codecs/av1/av1_svc_config.h" #include "modules/video_coding/codecs/vp9/svc_config.h" #include "rtc_base/checks.h" -#include "test/explicit_key_value_config.h" +#include "test/create_test_field_trials.h" #include "test/gtest.h" namespace webrtc { @@ -36,12 +37,12 @@ namespace { using ::testing::Bool; using ::testing::TestWithParam; -static VideoCodec Configure(VideoCodecType codecType, - size_t width, - size_t height, - size_t num_spatial_layers, - size_t num_temporal_layers, - bool is_screen_sharing) { +VideoCodec Configure(VideoCodecType codecType, + size_t width, + size_t height, + size_t num_spatial_layers, + size_t num_temporal_layers, + bool is_screen_sharing) { VideoCodec codec; codec.width = width; codec.height = height; @@ -86,7 +87,7 @@ static VideoCodec Configure(VideoCodecType codecType, TEST(SvcRateAllocatorTest, SingleLayerFor320x180Input) { VideoCodec codec = Configure(kVideoCodecVP9, 320, 180, 3, 3, false); - ExplicitKeyValueConfig field_trials(""); + FieldTrials field_trials = CreateTestFieldTrials(); SvcRateAllocator allocator = SvcRateAllocator(codec, field_trials); VideoBitrateAllocation allocation = @@ -98,7 +99,7 @@ TEST(SvcRateAllocatorTest, SingleLayerFor320x180Input) { TEST(SvcRateAllocatorTest, TwoLayersFor640x360Input) { VideoCodec codec = Configure(kVideoCodecVP9, 640, 360, 3, 3, false); - ExplicitKeyValueConfig field_trials(""); + FieldTrials field_trials = CreateTestFieldTrials(); SvcRateAllocator allocator = SvcRateAllocator(codec, field_trials); VideoBitrateAllocation allocation = @@ -111,7 +112,7 @@ TEST(SvcRateAllocatorTest, TwoLayersFor640x360Input) { TEST(SvcRateAllocatorTest, ThreeLayersFor1280x720Input) { VideoCodec codec = Configure(kVideoCodecVP9, 1280, 720, 3, 3, false); - ExplicitKeyValueConfig field_trials(""); + FieldTrials field_trials = CreateTestFieldTrials(); SvcRateAllocator allocator = SvcRateAllocator(codec, field_trials); VideoBitrateAllocation allocation = @@ -125,7 +126,7 @@ TEST(SvcRateAllocatorTest, ThreeLayersFor1280x720Input) { TEST(SvcRateAllocatorTest, BaseLayerNonZeroBitrateEvenIfTotalIfLessThanMinimum) { VideoCodec codec = Configure(kVideoCodecVP9, 1280, 720, 3, 3, false); - ExplicitKeyValueConfig field_trials(""); + FieldTrials field_trials = CreateTestFieldTrials(); SvcRateAllocator allocator = SvcRateAllocator(codec, field_trials); const SpatialLayer* layers = codec.spatialLayers; @@ -140,7 +141,7 @@ TEST(SvcRateAllocatorTest, TEST(SvcRateAllocatorTest, Disable640x360Layer) { VideoCodec codec = Configure(kVideoCodecVP9, 1280, 720, 3, 3, false); - ExplicitKeyValueConfig field_trials(""); + FieldTrials field_trials = CreateTestFieldTrials(); SvcRateAllocator allocator = SvcRateAllocator(codec, field_trials); const SpatialLayer* layers = codec.spatialLayers; @@ -158,7 +159,7 @@ TEST(SvcRateAllocatorTest, Disable640x360Layer) { TEST(SvcRateAllocatorTest, Disable1280x720Layer) { VideoCodec codec = Configure(kVideoCodecVP9, 1280, 720, 3, 3, false); - ExplicitKeyValueConfig field_trials(""); + FieldTrials field_trials = CreateTestFieldTrials(); SvcRateAllocator allocator = SvcRateAllocator(codec, field_trials); const SpatialLayer* layers = codec.spatialLayers; @@ -177,7 +178,7 @@ TEST(SvcRateAllocatorTest, Disable1280x720Layer) { TEST(SvcRateAllocatorTest, BitrateIsCapped) { VideoCodec codec = Configure(kVideoCodecVP9, 1280, 720, 3, 3, false); - ExplicitKeyValueConfig field_trials(""); + FieldTrials field_trials = CreateTestFieldTrials(); SvcRateAllocator allocator = SvcRateAllocator(codec, field_trials); const SpatialLayer* layers = codec.spatialLayers; @@ -195,7 +196,7 @@ TEST(SvcRateAllocatorTest, BitrateIsCapped) { TEST(SvcRateAllocatorTest, MinBitrateToGetQualityLayer) { VideoCodec codec = Configure(kVideoCodecVP9, 1280, 720, 3, 1, true); - ExplicitKeyValueConfig field_trials(""); + FieldTrials field_trials = CreateTestFieldTrials(); SvcRateAllocator allocator = SvcRateAllocator(codec, field_trials); const SpatialLayer* layers = codec.spatialLayers; @@ -214,7 +215,7 @@ TEST(SvcRateAllocatorTest, MinBitrateToGetQualityLayer) { } TEST(SvcRateAllocatorTest, DeactivateHigherLayers) { - ExplicitKeyValueConfig field_trials(""); + FieldTrials field_trials = CreateTestFieldTrials(); for (int deactivated_idx = 2; deactivated_idx >= 0; --deactivated_idx) { VideoCodec codec = Configure(kVideoCodecVP9, 1280, 720, 3, 1, false); EXPECT_LE(codec.VP9()->numberOfSpatialLayers, 3U); @@ -240,7 +241,7 @@ TEST(SvcRateAllocatorTest, DeactivateHigherLayers) { } TEST(SvcRateAllocatorTest, DeactivateLowerLayers) { - ExplicitKeyValueConfig field_trials(""); + FieldTrials field_trials = CreateTestFieldTrials(); for (int deactivated_idx = 0; deactivated_idx < 3; ++deactivated_idx) { VideoCodec codec = Configure(kVideoCodecVP9, 1280, 720, 3, 1, false); EXPECT_LE(codec.VP9()->numberOfSpatialLayers, 3U); @@ -268,7 +269,7 @@ TEST(SvcRateAllocatorTest, DeactivateLowerLayers) { TEST(SvcRateAllocatorTest, SignalsBwLimited) { VideoCodec codec = Configure(kVideoCodecVP9, 1280, 720, 3, 1, false); - ExplicitKeyValueConfig field_trials(""); + FieldTrials field_trials = CreateTestFieldTrials(); SvcRateAllocator allocator = SvcRateAllocator(codec, field_trials); // Rough estimate calculated by hand. @@ -331,7 +332,7 @@ TEST(SvcRateAllocatorTest, SupportsAv1) { codec.spatialLayers[2].minBitrate = 193; codec.spatialLayers[2].targetBitrate = 305; codec.spatialLayers[2].maxBitrate = 418; - ExplicitKeyValueConfig field_trials(""); + FieldTrials field_trials = CreateTestFieldTrials(); SvcRateAllocator allocator(codec, field_trials); @@ -361,7 +362,7 @@ TEST(SvcRateAllocatorTest, SupportsAv1WithSkippedLayer) { codec.spatialLayers[2].minBitrate = 193; codec.spatialLayers[2].targetBitrate = 305; codec.spatialLayers[2].maxBitrate = 418; - ExplicitKeyValueConfig field_trials(""); + FieldTrials field_trials = CreateTestFieldTrials(); SvcRateAllocator allocator(codec, field_trials); @@ -391,7 +392,7 @@ TEST(SvcRateAllocatorTest, UsesScalabilityModeToGetNumberOfLayers) { codec.spatialLayers[2].minBitrate = 193; codec.spatialLayers[2].targetBitrate = 305; codec.spatialLayers[2].maxBitrate = 418; - ExplicitKeyValueConfig field_trials(""); + FieldTrials field_trials = CreateTestFieldTrials(); SvcRateAllocator allocator(codec, field_trials); VideoBitrateAllocation allocation = @@ -410,7 +411,7 @@ TEST(SvcRateAllocatorTest, UsesScalabilityModeToGetNumberOfLayers) { TEST(SvcRateAllocatorTest, CapsAllocationToMaxBitrate) { VideoCodec codec = Configure(kVideoCodecVP9, 1280, 720, 3, 3, false); codec.maxBitrate = 70; // Cap the overall max bitrate to 70kbps. - ExplicitKeyValueConfig field_trials(""); + FieldTrials field_trials = CreateTestFieldTrials(); SvcRateAllocator allocator = SvcRateAllocator(codec, field_trials); @@ -449,7 +450,7 @@ TEST_P(SvcRateAllocatorTestParametrizedContentType, MaxBitrate) { TEST_P(SvcRateAllocatorTestParametrizedContentType, PaddingBitrate) { VideoCodec codec = Configure(kVideoCodecVP9, 1280, 720, 3, 1, is_screen_sharing_); - ExplicitKeyValueConfig field_trials(""); + FieldTrials field_trials = CreateTestFieldTrials(); SvcRateAllocator allocator = SvcRateAllocator(codec, field_trials); DataRate padding_bitrate = SvcRateAllocator::GetPaddingBitrate(codec); @@ -493,159 +494,10 @@ TEST_P(SvcRateAllocatorTestParametrizedContentType, PaddingBitrate) { EXPECT_EQ(DataRate::Zero(), padding_bitrate); } -TEST_P(SvcRateAllocatorTestParametrizedContentType, StableBitrate) { - ExplicitKeyValueConfig field_trials( - "WebRTC-StableTargetRate/enabled:true,video_hysteresis_factor:1.0," - "screenshare_hysteresis_factor:1.0/"); - - const VideoCodec codec = - Configure(kVideoCodecVP9, 1280, 720, 3, 1, is_screen_sharing_); - const auto start_rates = SvcRateAllocator::GetLayerStartBitrates(codec); - const DataRate min_rate_two_layers = start_rates[1]; - const DataRate min_rate_three_layers = start_rates[2]; - - const DataRate max_rate_one_layer = - DataRate::KilobitsPerSec(codec.spatialLayers[0].maxBitrate); - const DataRate max_rate_two_layers = - is_screen_sharing_ - ? DataRate::KilobitsPerSec(codec.spatialLayers[0].targetBitrate + - codec.spatialLayers[1].maxBitrate) - : DataRate::KilobitsPerSec(codec.spatialLayers[0].maxBitrate + - codec.spatialLayers[1].maxBitrate); - - SvcRateAllocator allocator = SvcRateAllocator(codec, field_trials); - - // Two layers, stable and target equal. - auto allocation = allocator.Allocate(VideoBitrateAllocationParameters( - /*total_bitrate=*/min_rate_two_layers, - /*stable_bitrate=*/min_rate_two_layers, /*fps=*/30.0)); - EXPECT_TRUE(allocation.IsSpatialLayerUsed(1)); - EXPECT_EQ(allocation.get_sum_bps(), min_rate_two_layers.bps()); - - // Two layers, stable bitrate too low for two layers. - allocation = allocator.Allocate(VideoBitrateAllocationParameters( - /*total_bitrate=*/min_rate_two_layers, - /*stable_bitrate=*/min_rate_two_layers - DataRate::BitsPerSec(1), - /*fps=*/30.0)); - EXPECT_FALSE(allocation.IsSpatialLayerUsed(1)); - EXPECT_EQ(DataRate::BitsPerSec(allocation.get_sum_bps()), - std::min(min_rate_two_layers - DataRate::BitsPerSec(1), - max_rate_one_layer)); - - // Three layers, stable and target equal. - allocation = allocator.Allocate(VideoBitrateAllocationParameters( - /*total_bitrate=*/min_rate_three_layers, - /*stable_bitrate=*/min_rate_three_layers, /*fps=*/30.0)); - EXPECT_TRUE(allocation.IsSpatialLayerUsed(2)); - EXPECT_EQ(allocation.get_sum_bps(), min_rate_three_layers.bps()); - - // Three layers, stable bitrate too low for three layers. - allocation = allocator.Allocate(VideoBitrateAllocationParameters( - /*total_bitrate=*/min_rate_three_layers, - /*stable_bitrate=*/min_rate_three_layers - DataRate::BitsPerSec(1), - /*fps=*/30.0)); - EXPECT_FALSE(allocation.IsSpatialLayerUsed(2)); - EXPECT_EQ(DataRate::BitsPerSec(allocation.get_sum_bps()), - std::min(min_rate_three_layers - DataRate::BitsPerSec(1), - max_rate_two_layers)); -} - -TEST_P(SvcRateAllocatorTestParametrizedContentType, - StableBitrateWithHysteresis) { - const VideoCodec codec = - Configure(kVideoCodecVP9, 1280, 720, 3, 1, is_screen_sharing_); - const auto start_rates = SvcRateAllocator::GetLayerStartBitrates(codec); - const DataRate min_rate_single_layer = start_rates[0]; - const DataRate min_rate_two_layers = start_rates[1]; - const DataRate min_rate_three_layers = start_rates[2]; - - ExplicitKeyValueConfig field_trials( - "WebRTC-StableTargetRate/enabled:true,video_hysteresis_factor:1.1," - "screenshare_hysteresis_factor:1.1/"); - SvcRateAllocator allocator = SvcRateAllocator(codec, field_trials); - // Always use max bitrate as target, verify only stable is used for layer - // count selection. - const DataRate max_bitrate = allocator.GetMaxBitrate(codec); - - // Start with a single layer. - auto allocation = allocator.Allocate(VideoBitrateAllocationParameters( - /*total_bitrate=*/max_bitrate, - /*stable_bitrate=*/min_rate_single_layer, /*fps=*/30.0)); - EXPECT_TRUE(allocation.IsSpatialLayerUsed(0)); - EXPECT_FALSE(allocation.IsSpatialLayerUsed(1)); - EXPECT_FALSE(allocation.IsSpatialLayerUsed(2)); - - // Min bitrate not enough to enable second layer due to 10% hysteresis. - allocation = allocator.Allocate(VideoBitrateAllocationParameters( - /*total_bitrate=*/max_bitrate, - /*stable_bitrate=*/min_rate_two_layers, /*fps=*/30.0)); - EXPECT_TRUE(allocation.IsSpatialLayerUsed(0)); - EXPECT_FALSE(allocation.IsSpatialLayerUsed(1)); - EXPECT_FALSE(allocation.IsSpatialLayerUsed(2)); - - // Add hysteresis, second layer should turn on. - allocation = allocator.Allocate(VideoBitrateAllocationParameters( - /*total_bitrate=*/max_bitrate, - /*stable_bitrate=*/min_rate_two_layers * 1.1, /*fps=*/30.0)); - EXPECT_TRUE(allocation.IsSpatialLayerUsed(0)); - EXPECT_TRUE(allocation.IsSpatialLayerUsed(1)); - EXPECT_FALSE(allocation.IsSpatialLayerUsed(2)); - - // Remove hysteresis, second layer should stay on. - allocation = allocator.Allocate(VideoBitrateAllocationParameters( - /*total_bitrate=*/max_bitrate, - /*stable_bitrate=*/min_rate_two_layers, /*fps=*/30.0)); - EXPECT_TRUE(allocation.IsSpatialLayerUsed(0)); - EXPECT_TRUE(allocation.IsSpatialLayerUsed(1)); - EXPECT_FALSE(allocation.IsSpatialLayerUsed(2)); - - // Going below min for two layers, second layer should turn off again. - allocation = allocator.Allocate(VideoBitrateAllocationParameters( - /*total_bitrate=*/max_bitrate, - /*stable_bitrate=*/min_rate_two_layers - DataRate::BitsPerSec(1), - /*fps=*/30.0)); - EXPECT_TRUE(allocation.IsSpatialLayerUsed(0)); - EXPECT_FALSE(allocation.IsSpatialLayerUsed(1)); - EXPECT_FALSE(allocation.IsSpatialLayerUsed(2)); - - // Min bitrate not enough to enable third layer due to 10% hysteresis. - allocation = allocator.Allocate(VideoBitrateAllocationParameters( - /*total_bitrate=*/max_bitrate, - /*stable_bitrate=*/min_rate_three_layers, /*fps=*/30.0)); - EXPECT_TRUE(allocation.IsSpatialLayerUsed(0)); - EXPECT_TRUE(allocation.IsSpatialLayerUsed(1)); - EXPECT_FALSE(allocation.IsSpatialLayerUsed(2)); - - // Add hysteresis, third layer should turn on. - allocation = allocator.Allocate(VideoBitrateAllocationParameters( - /*total_bitrate=*/max_bitrate, - /*stable_bitrate=*/min_rate_three_layers * 1.1, /*fps=*/30.0)); - EXPECT_TRUE(allocation.IsSpatialLayerUsed(0)); - EXPECT_TRUE(allocation.IsSpatialLayerUsed(1)); - EXPECT_TRUE(allocation.IsSpatialLayerUsed(2)); - - // Remove hysteresis, third layer should stay on. - allocation = allocator.Allocate(VideoBitrateAllocationParameters( - /*total_bitrate=*/max_bitrate, - /*stable_bitrate=*/min_rate_three_layers, /*fps=*/30.0)); - EXPECT_TRUE(allocation.IsSpatialLayerUsed(0)); - EXPECT_TRUE(allocation.IsSpatialLayerUsed(1)); - EXPECT_TRUE(allocation.IsSpatialLayerUsed(2)); - - // Going below min for three layers, third layer should turn off again. - allocation = allocator.Allocate(VideoBitrateAllocationParameters( - /*total_bitrate=*/max_bitrate, - /*stable_bitrate=*/min_rate_three_layers - DataRate::BitsPerSec(1), - /*fps=*/30.0)); - EXPECT_TRUE(allocation.IsSpatialLayerUsed(0)); - EXPECT_TRUE(allocation.IsSpatialLayerUsed(1)); - EXPECT_FALSE(allocation.IsSpatialLayerUsed(2)); -} - TEST_P(SvcRateAllocatorTestParametrizedContentType, TwoTemporalLayersAv1) { VideoCodec codec = Configure(kVideoCodecAV1, 1280, 720, 1, 2, is_screen_sharing_); - ExplicitKeyValueConfig field_trials(""); + FieldTrials field_trials = CreateTestFieldTrials(); SvcRateAllocator allocator = SvcRateAllocator(codec, field_trials); VideoBitrateAllocation allocation = allocator.Allocate(VideoBitrateAllocationParameters( @@ -660,7 +512,7 @@ TEST_P(SvcRateAllocatorTestParametrizedContentType, TwoTemporalLayersAv1) { TEST_P(SvcRateAllocatorTestParametrizedContentType, ThreeTemporalLayersAv1) { VideoCodec codec = Configure(kVideoCodecAV1, 1280, 720, 1, 3, is_screen_sharing_); - ExplicitKeyValueConfig field_trials(""); + FieldTrials field_trials = CreateTestFieldTrials(); SvcRateAllocator allocator = SvcRateAllocator(codec, field_trials); VideoBitrateAllocation allocation = allocator.Allocate(VideoBitrateAllocationParameters( diff --git a/modules/video_coding/timing/BUILD.gn b/modules/video_coding/timing/BUILD.gn index a24f570c3e..c242f3d4c4 100644 --- a/modules/video_coding/timing/BUILD.gn +++ b/modules/video_coding/timing/BUILD.gn @@ -89,11 +89,16 @@ rtc_library("timestamp_extrapolator") { "timestamp_extrapolator.h", ] deps = [ + "../../../api:field_trials", + "../../../api:field_trials_view", "../../../api/units:time_delta", "../../../api/units:timestamp", "../../../modules:module_api_public", + "../../../rtc_base:logging", "../../../rtc_base:rtc_numerics", + "../../../rtc_base/experiments:field_trial_parser", "../../../system_wrappers:metrics", + "//third_party/abseil-cpp/absl/strings:string_view", ] } @@ -147,6 +152,7 @@ rtc_library("timing_unittests") { "../../../rtc_base:timeutils", "../../../system_wrappers:metrics", "../../../system_wrappers:system_wrappers", + "../../../test:create_test_field_trials", "../../../test:scoped_key_value_config", "../../../test:test_support", ] diff --git a/modules/video_coding/timing/inter_frame_delay_variation_calculator.cc b/modules/video_coding/timing/inter_frame_delay_variation_calculator.cc index 8a1441905c..e00cc8eaad 100644 --- a/modules/video_coding/timing/inter_frame_delay_variation_calculator.cc +++ b/modules/video_coding/timing/inter_frame_delay_variation_calculator.cc @@ -22,7 +22,7 @@ namespace webrtc { namespace { constexpr Frequency k90kHz = Frequency::KiloHertz(90); -} +} // namespace InterFrameDelayVariationCalculator::InterFrameDelayVariationCalculator() { Reset(); diff --git a/modules/video_coding/timing/jitter_estimator.cc b/modules/video_coding/timing/jitter_estimator.cc index b2e433f8bc..7b394d13f8 100644 --- a/modules/video_coding/timing/jitter_estimator.cc +++ b/modules/video_coding/timing/jitter_estimator.cc @@ -77,7 +77,7 @@ constexpr TimeDelta OPERATING_SYSTEM_JITTER = TimeDelta::Millis(10); constexpr TimeDelta kNackCountTimeout = TimeDelta::Seconds(60); // RTT mult activation. -constexpr size_t kNackLimit = 3; +constexpr int kNackLimit = 3; // Frame rate estimate clamping limit. constexpr Frequency kMaxFramerateEstimate = Frequency::Hertz(200); @@ -108,7 +108,9 @@ JitterEstimator::Config JitterEstimator::Config::ParseAndValidate( config.frame_size_window = 1; } - // General sanity checks. + // General validation checks. + // TODO(brandtr): We should probably unset the fields here rather than setting + // them to zero. if (config.num_stddev_delay_clamp && config.num_stddev_delay_clamp < 0.0) { RTC_LOG(LS_ERROR) << "Skipping invalid num_stddev_delay_clamp=" << *config.num_stddev_delay_clamp; @@ -125,6 +127,16 @@ JitterEstimator::Config JitterEstimator::Config::ParseAndValidate( << *config.num_stddev_size_outlier; config.num_stddev_size_outlier = 0.0; } + if (config.nack_limit && *config.nack_limit < 0) { + RTC_LOG(LS_ERROR) << "Skipping invalid nack_limit=" << *config.nack_limit; + config.nack_limit = std::nullopt; + } + if (config.nack_count_timeout && + *config.nack_count_timeout <= TimeDelta::Zero()) { + RTC_LOG(LS_ERROR) << "Skipping invalid nack_count_timeout=" + << *config.nack_count_timeout; + config.nack_count_timeout = std::nullopt; + } return config; } @@ -428,12 +440,14 @@ TimeDelta JitterEstimator::GetJitterEstimate( TimeDelta jitter = CalculateEstimate() + OPERATING_SYSTEM_JITTER; Timestamp now = clock_->CurrentTime(); - if (now - latest_nack_ > kNackCountTimeout) + if (now - latest_nack_ > + config_.nack_count_timeout.value_or(kNackCountTimeout)) { nack_count_ = 0; + } if (filter_jitter_estimate_ > jitter) jitter = filter_jitter_estimate_; - if (nack_count_ >= kNackLimit) { + if (nack_count_ >= config_.nack_limit.value_or(kNackLimit)) { if (rtt_mult_add_cap.has_value()) { jitter += std::min(rtt_filter_.Rtt() * rtt_multiplier, rtt_mult_add_cap.value()); diff --git a/modules/video_coding/timing/jitter_estimator.h b/modules/video_coding/timing/jitter_estimator.h index 08f16aac89..d4ea6b6132 100644 --- a/modules/video_coding/timing/jitter_estimator.h +++ b/modules/video_coding/timing/jitter_estimator.h @@ -52,7 +52,9 @@ class JitterEstimator { "num_stddev_delay_outlier", &num_stddev_delay_outlier, "num_stddev_size_outlier", &num_stddev_size_outlier, "congestion_rejection_factor", &congestion_rejection_factor, - "estimate_noise_when_congested", &estimate_noise_when_congested); + "estimate_noise_when_congested", &estimate_noise_when_congested, + "nack_limit", &nack_limit, + "nack_count_timeout", &nack_count_timeout); // clang-format on } @@ -103,6 +105,14 @@ class JitterEstimator { // since congested frames typically are not spread around the line with // Gaussian noise. (This is the whole reason for the congestion rejection!) bool estimate_noise_when_congested = true; + + // The number of frames required to be NACKed within `nack_count_timeout` + // in order for RttMult to be enabled. + std::optional nack_limit = std::nullopt; + + // The time period in which `nack_limit` number of frames required to be + // NACKed in order for RttMult to be enabled. + std::optional nack_count_timeout = std::nullopt; }; JitterEstimator(Clock* clock, const FieldTrialsView& field_trials); @@ -205,7 +215,7 @@ class JitterEstimator { Timestamp latest_nack_ = Timestamp::Zero(); // Keeps track of the number of nacks received, but never goes above // kNackLimit. - size_t nack_count_; + int nack_count_; RttFilter rtt_filter_; // Tracks frame rates in microseconds. diff --git a/modules/video_coding/timing/jitter_estimator_unittest.cc b/modules/video_coding/timing/jitter_estimator_unittest.cc index 3b3449ee6d..f12e49eda3 100644 --- a/modules/video_coding/timing/jitter_estimator_unittest.cc +++ b/modules/video_coding/timing/jitter_estimator_unittest.cc @@ -11,7 +11,6 @@ #include -#include #include #include #include @@ -23,6 +22,7 @@ #include "api/units/time_delta.h" #include "rtc_base/numerics/histogram_percentile_counter.h" #include "system_wrappers/include/clock.h" +#include "test/create_test_field_trials.h" #include "test/gtest.h" namespace webrtc { @@ -55,10 +55,10 @@ class JitterEstimatorTest : public ::testing::Test { protected: explicit JitterEstimatorTest(const std::string& field_trials) : fake_clock_(0), - field_trials_(FieldTrials::CreateNoGlobal(field_trials)), - estimator_(&fake_clock_, *field_trials_) {} + field_trials_(CreateTestFieldTrials(field_trials)), + estimator_(&fake_clock_, field_trials_) {} JitterEstimatorTest() : JitterEstimatorTest("") {} - virtual ~JitterEstimatorTest() {} + ~JitterEstimatorTest() override {} void Run(int duration_s, int framerate_fps, ValueGenerator& gen) { TimeDelta tick = 1 / Frequency::Hertz(framerate_fps); @@ -70,7 +70,7 @@ class JitterEstimatorTest : public ::testing::Test { } SimulatedClock fake_clock_; - std::unique_ptr field_trials_; + FieldTrials field_trials_; JitterEstimator estimator_; }; @@ -198,8 +198,10 @@ class FieldTrialsOverriddenJitterEstimatorTest : public JitterEstimatorTest { "num_stddev_delay_outlier:2," "num_stddev_size_outlier:3.1," "congestion_rejection_factor:-1.55," - "estimate_noise_when_congested:false/") {} - ~FieldTrialsOverriddenJitterEstimatorTest() {} + "estimate_noise_when_congested:false," + "nack_limit:2," + "nack_count_timeout:100ms/") {} + ~FieldTrialsOverriddenJitterEstimatorTest() override {} }; TEST_F(FieldTrialsOverriddenJitterEstimatorTest, FieldTrialsParsesCorrectly) { @@ -212,6 +214,8 @@ TEST_F(FieldTrialsOverriddenJitterEstimatorTest, FieldTrialsParsesCorrectly) { EXPECT_EQ(*config.num_stddev_size_outlier, 3.1); EXPECT_EQ(*config.congestion_rejection_factor, -1.55); EXPECT_FALSE(config.estimate_noise_when_congested); + EXPECT_EQ(*config.nack_limit, 2); + EXPECT_EQ(*config.nack_count_timeout, TimeDelta::Millis(100)); } TEST_F(FieldTrialsOverriddenJitterEstimatorTest, @@ -271,6 +275,51 @@ TEST_F(FieldTrialsOverriddenJitterEstimatorTest, EXPECT_EQ(outlier_jitter.ms(), steady_state_jitter.ms()); } +TEST_F(FieldTrialsOverriddenJitterEstimatorTest, + NackedFramesIncreaseEstimateWithinTimeoutWindow) { + ValueGenerator gen(10); + constexpr double kRttMult = 1.0; + constexpr TimeDelta kRttMultAddCap = TimeDelta::Millis(200); + constexpr TimeDelta kRtt = TimeDelta::Millis(100); + constexpr TimeDelta kInterArrivalTime = TimeDelta::Millis(33); + estimator_.UpdateRtt(kRtt); + + // Ten perfect frames stabilize the estimate. + for (int i = 0; i < 10; ++i) { + fake_clock_.AdvanceTime(kInterArrivalTime); + estimator_.UpdateEstimate(gen.Delay(), gen.FrameSize()); + gen.Advance(); + } + EXPECT_EQ(estimator_.GetJitterEstimate(kRttMult, kRttMultAddCap), + TimeDelta::Millis(11)); + + // RTT is added to estimate after two NACKed frames. + fake_clock_.AdvanceTime(kInterArrivalTime); + estimator_.FrameNacked(); + estimator_.UpdateEstimate(gen.Delay() + kRtt, gen.FrameSize()); + gen.Advance(); + EXPECT_EQ(estimator_.GetJitterEstimate(kRttMult, kRttMultAddCap), + TimeDelta::Millis(11)); + fake_clock_.AdvanceTime(kInterArrivalTime); + estimator_.FrameNacked(); + estimator_.UpdateEstimate(gen.Delay(), gen.FrameSize()); + gen.Advance(); + EXPECT_EQ(estimator_.GetJitterEstimate(kRttMult, kRttMultAddCap), + TimeDelta::Millis(111)); + + // RTT is removed from estimate after 101ms of no NACKed frames. + fake_clock_.AdvanceTime(TimeDelta::Millis(100)); + estimator_.UpdateEstimate(gen.Delay() - kRtt, gen.FrameSize()); + gen.Advance(); + EXPECT_EQ(estimator_.GetJitterEstimate(kRttMult, kRttMultAddCap), + TimeDelta::Millis(111)); + fake_clock_.AdvanceTime(TimeDelta::Millis(1)); + estimator_.UpdateEstimate(gen.Delay(), gen.FrameSize()); + gen.Advance(); + EXPECT_EQ(estimator_.GetJitterEstimate(kRttMult, kRttMultAddCap), + TimeDelta::Millis(11)); +} + class MisconfiguredFieldTrialsJitterEstimatorTest : public JitterEstimatorTest { protected: MisconfiguredFieldTrialsJitterEstimatorTest() @@ -280,8 +329,10 @@ class MisconfiguredFieldTrialsJitterEstimatorTest : public JitterEstimatorTest { "frame_size_window:-1," "num_stddev_delay_clamp:-1.9," "num_stddev_delay_outlier:-2," - "num_stddev_size_outlier:-23.1/") {} - ~MisconfiguredFieldTrialsJitterEstimatorTest() {} + "num_stddev_size_outlier:-23.1," + "nack_limit:-1," + "nack_count_timeout:0s/") {} + ~MisconfiguredFieldTrialsJitterEstimatorTest() override {} }; TEST_F(MisconfiguredFieldTrialsJitterEstimatorTest, FieldTrialsAreValidated) { @@ -291,6 +342,8 @@ TEST_F(MisconfiguredFieldTrialsJitterEstimatorTest, FieldTrialsAreValidated) { EXPECT_EQ(*config.num_stddev_delay_clamp, 0.0); EXPECT_EQ(*config.num_stddev_delay_outlier, 0.0); EXPECT_EQ(*config.num_stddev_size_outlier, 0.0); + EXPECT_FALSE(config.nack_limit.has_value()); + EXPECT_FALSE(config.nack_count_timeout.has_value()); } } // namespace diff --git a/modules/video_coding/timing/timestamp_extrapolator.cc b/modules/video_coding/timing/timestamp_extrapolator.cc index 404ea60c05..6f1be747eb 100644 --- a/modules/video_coding/timing/timestamp_extrapolator.cc +++ b/modules/video_coding/timing/timestamp_extrapolator.cc @@ -15,8 +15,10 @@ #include #include +#include "api/field_trials_view.h" #include "api/units/time_delta.h" #include "api/units/timestamp.h" +#include "rtc_base/logging.h" #include "rtc_base/numerics/sequence_number_unwrapper.h" #include "system_wrappers/include/metrics.h" @@ -28,16 +30,47 @@ constexpr int kMinimumSamplesToLogEstimatedClockDrift = 3000; // 100 seconds at 30 fps. constexpr double kLambda = 1; constexpr int kStartUpFilterDelayInPackets = 2; -constexpr double kAlarmThreshold = 60e3; -// in timestamp ticks, i.e. 15 ms -constexpr double kAccDrift = 6600; -constexpr double kAccMaxError = 7000; +constexpr double kP00 = 1.0; constexpr double kP11 = 1e10; } // namespace -TimestampExtrapolator::TimestampExtrapolator(Timestamp start) - : start_(Timestamp::Zero()), +TimestampExtrapolator::Config TimestampExtrapolator::Config::ParseAndValidate( + const FieldTrialsView& field_trials) { + // Parse. + Config config; + config.Parser()->Parse(field_trials.Lookup(kFieldTrialsKey)); + + // Validate. + Config defaults; + if (config.hard_reset_timeout <= TimeDelta::Zero()) { + RTC_LOG(LS_WARNING) << "Skipping invalid hard_reset_timeout=" + << config.hard_reset_timeout; + config.hard_reset_timeout = defaults.hard_reset_timeout; + } + if (config.alarm_threshold <= 0) { + RTC_LOG(LS_WARNING) << "Skipping invalid alarm_threshold=" + << config.alarm_threshold; + config.alarm_threshold = defaults.alarm_threshold; + } + if (config.acc_drift < 0) { + RTC_LOG(LS_WARNING) << "Skipping invalid acc_drift=" << config.acc_drift; + config.acc_drift = defaults.acc_drift; + } + if (config.acc_max_error <= 0) { + RTC_LOG(LS_WARNING) << "Skipping invalid acc_max_error=" + << config.acc_max_error; + config.acc_max_error = defaults.acc_max_error; + } + + return config; +} + +TimestampExtrapolator::TimestampExtrapolator( + Timestamp start, + const FieldTrialsView& field_trials) + : config_(Config::ParseAndValidate(field_trials)), + start_(Timestamp::Zero()), prev_(Timestamp::Zero()), packet_count_(0), detector_accumulator_pos_(0), @@ -61,7 +94,7 @@ void TimestampExtrapolator::Reset(Timestamp start) { prev_unwrapped_timestamp_ = std::nullopt; w_[0] = 90.0; w_[1] = 0; - p_[0][0] = 1; + p_[0][0] = kP00; p_[1][1] = kP11; p_[0][1] = p_[1][0] = 0; unwrapper_ = RtpTimestampUnwrapper(); @@ -71,9 +104,8 @@ void TimestampExtrapolator::Reset(Timestamp start) { } void TimestampExtrapolator::Update(Timestamp now, uint32_t ts90khz) { - if (now - prev_ > TimeDelta::Seconds(10)) { - // Ten seconds without a complete frame. - // Reset the extrapolator + if (now - prev_ > config_.hard_reset_timeout) { + // No complete frame within the timeout. Reset(now); } else { prev_ = now; @@ -98,9 +130,12 @@ void TimestampExtrapolator::Update(Timestamp now, uint32_t ts90khz) { t_ms * w_[0] - w_[1]; if (DelayChangeDetection(residual) && packet_count_ >= kStartUpFilterDelayInPackets) { - // A sudden change of average network delay has been detected. // Force the filter to adjust its offset parameter by changing - // the offset uncertainty. Don't do this during startup. + // the uncertainties. Don't do this during startup. + if (config_.reset_full_cov_on_alarm) { + p_[0][0] = kP00; + p_[0][1] = p_[1][0] = 0; + } p_[1][1] = kP11; } @@ -176,14 +211,15 @@ std::optional TimestampExtrapolator::ExtrapolateLocalTime( bool TimestampExtrapolator::DelayChangeDetection(double error) { // CUSUM detection of sudden delay changes - error = (error > 0) ? std::min(error, kAccMaxError) - : std::max(error, -kAccMaxError); - detector_accumulator_pos_ = - std::max(detector_accumulator_pos_ + error - kAccDrift, double{0}); - detector_accumulator_neg_ = - std::min(detector_accumulator_neg_ + error + kAccDrift, double{0}); - if (detector_accumulator_pos_ > kAlarmThreshold || - detector_accumulator_neg_ < -kAlarmThreshold) { + double acc_max_error = static_cast(config_.acc_max_error); + error = (error > 0) ? std::min(error, acc_max_error) + : std::max(error, -acc_max_error); + detector_accumulator_pos_ = std::max( + detector_accumulator_pos_ + error - config_.acc_drift, double{0}); + detector_accumulator_neg_ = std::min( + detector_accumulator_neg_ + error + config_.acc_drift, double{0}); + if (detector_accumulator_pos_ > config_.alarm_threshold || + detector_accumulator_neg_ < -config_.alarm_threshold) { // Alarm detector_accumulator_pos_ = detector_accumulator_neg_ = 0; return true; diff --git a/modules/video_coding/timing/timestamp_extrapolator.h b/modules/video_coding/timing/timestamp_extrapolator.h index b1cd0b641d..aed2e3f95d 100644 --- a/modules/video_coding/timing/timestamp_extrapolator.h +++ b/modules/video_coding/timing/timestamp_extrapolator.h @@ -13,9 +13,14 @@ #include +#include #include +#include "absl/strings/string_view.h" +#include "api/field_trials_view.h" +#include "api/units/time_delta.h" #include "api/units/timestamp.h" +#include "rtc_base/experiments/struct_parameters_parser.h" #include "rtc_base/numerics/sequence_number_unwrapper.h" namespace webrtc { @@ -23,16 +28,64 @@ namespace webrtc { // Not thread safe. class TimestampExtrapolator { public: - explicit TimestampExtrapolator(Timestamp start); + // Configuration struct for overriding some constants and behaviour, + // configurable through field trials. + struct Config { + inline static constexpr absl::string_view kFieldTrialsKey = + "WebRTC-TimestampExtrapolatorConfig"; + + // Factory function that parses the field trials and returns a `Config` + // with validated values. + static Config ParseAndValidate(const FieldTrialsView& field_trials); + + std::unique_ptr Parser() { + // clang-format off + return StructParametersParser::Create( + "hard_reset_timeout", &hard_reset_timeout, + "alarm_threshold", &alarm_threshold, + "acc_drift", &acc_drift, + "acc_max_error", &acc_max_error, + "reset_full_cov_on_alarm", &reset_full_cov_on_alarm); + // clang-format on + } + + // If a frame has not been received within this timeout, do a full reset. + TimeDelta hard_reset_timeout = TimeDelta::Seconds(10); + + // Alarm on sudden delay change if the (filtered; see below) accumulated + // residuals are larger than this number of RTP ticks. After the + // startup period, an alarm will result in a full or partial reset of the + // uncertainty covariance (see `reset_full_cov_on_alarm` below). + int alarm_threshold = 60000; // 666 ms <=> 20 frames@30fps. + + // Acceptable level of per-frame drift in the detector (in RTP ticks). + int acc_drift = 6600; // 73 ms <=> 2.2 frames@30fps. + + // Max limit on residuals in the detector (in RTP ticks). + // TODO(brandtr): Increase from this unreasonably low value. + int acc_max_error = 7000; // 77 ms <=> 2.3 frames@30fps. + + // If true, reset the entire uncertainty covariance matrix on alarms. + // If false, only reset the offset variance term. + // TODO(brandtr): Flip so that the frequency term won't get hit tpp badly + // when a large delay spike happens. + bool reset_full_cov_on_alarm = false; + }; + + TimestampExtrapolator(Timestamp start, const FieldTrialsView& field_trials); ~TimestampExtrapolator(); void Update(Timestamp now, uint32_t ts90khz); std::optional ExtrapolateLocalTime(uint32_t timestamp90khz) const; void Reset(Timestamp start); + Config GetConfigForTest() const { return config_; } + private: void CheckForWrapArounds(uint32_t ts90khz); bool DelayChangeDetection(double error); + const Config config_; + double w_[2]; double p_[2][2]; Timestamp start_; diff --git a/modules/video_coding/timing/timestamp_extrapolator_unittest.cc b/modules/video_coding/timing/timestamp_extrapolator_unittest.cc index e0367a3026..f03a50e2a0 100644 --- a/modules/video_coding/timing/timestamp_extrapolator_unittest.cc +++ b/modules/video_coding/timing/timestamp_extrapolator_unittest.cc @@ -22,6 +22,7 @@ #include "api/units/timestamp.h" #include "system_wrappers/include/clock.h" #include "system_wrappers/include/metrics.h" +#include "test/create_test_field_trials.h" #include "test/gmock.h" #include "test/gtest.h" @@ -40,7 +41,8 @@ constexpr TimeDelta k25FpsDelay = 1 / k25Fps; TEST(TimestampExtrapolatorTest, ExtrapolationOccursAfter2Packets) { SimulatedClock clock(Timestamp::Millis(1337)); - TimestampExtrapolator ts_extrapolator(clock.CurrentTime()); + TimestampExtrapolator ts_extrapolator(clock.CurrentTime(), + CreateTestFieldTrials()); // No packets so no timestamp. EXPECT_THAT(ts_extrapolator.ExtrapolateLocalTime(90000), Eq(std::nullopt)); @@ -64,7 +66,8 @@ TEST(TimestampExtrapolatorTest, ExtrapolationOccursAfter2Packets) { TEST(TimestampExtrapolatorTest, ResetsAfter10SecondPause) { SimulatedClock clock(Timestamp::Millis(1337)); - TimestampExtrapolator ts_extrapolator(clock.CurrentTime()); + TimestampExtrapolator ts_extrapolator(clock.CurrentTime(), + CreateTestFieldTrials()); uint32_t rtp = 90000; ts_extrapolator.Update(clock.CurrentTime(), rtp); @@ -86,7 +89,8 @@ TEST(TimestampExtrapolatorTest, ResetsAfter10SecondPause) { TEST(TimestampExtrapolatorTest, TimestampExtrapolatesMultipleRtpWrapArounds) { SimulatedClock clock(Timestamp::Millis(1337)); - TimestampExtrapolator ts_extrapolator(clock.CurrentTime()); + TimestampExtrapolator ts_extrapolator(clock.CurrentTime(), + CreateTestFieldTrials()); uint32_t rtp = std::numeric_limits::max(); ts_extrapolator.Update(clock.CurrentTime(), rtp); @@ -125,7 +129,8 @@ TEST(TimestampExtrapolatorTest, TimestampExtrapolatesMultipleRtpWrapArounds) { TEST(TimestampExtrapolatorTest, NegativeRtpTimestampWrapAround) { SimulatedClock clock(Timestamp::Millis(1337)); - TimestampExtrapolator ts_extrapolator(clock.CurrentTime()); + TimestampExtrapolator ts_extrapolator(clock.CurrentTime(), + CreateTestFieldTrials()); uint32_t rtp = 0; ts_extrapolator.Update(clock.CurrentTime(), rtp); EXPECT_THAT(ts_extrapolator.ExtrapolateLocalTime(rtp), @@ -138,7 +143,8 @@ TEST(TimestampExtrapolatorTest, NegativeRtpTimestampWrapAround) { TEST(TimestampExtrapolatorTest, NegativeRtpTimestampWrapAroundSecondScenario) { SimulatedClock clock(Timestamp::Millis(1337)); - TimestampExtrapolator ts_extrapolator(clock.CurrentTime()); + TimestampExtrapolator ts_extrapolator(clock.CurrentTime(), + CreateTestFieldTrials()); uint32_t rtp = 0; ts_extrapolator.Update(clock.CurrentTime(), rtp); EXPECT_THAT(ts_extrapolator.ExtrapolateLocalTime(rtp), @@ -153,7 +159,8 @@ TEST(TimestampExtrapolatorTest, Slow90KHzClock) { // This simulates a slow camera, which produces frames at 24Hz instead of // 25Hz. The extrapolator should be able to resolve this with enough data. SimulatedClock clock(Timestamp::Millis(1337)); - TimestampExtrapolator ts_extrapolator(clock.CurrentTime()); + TimestampExtrapolator ts_extrapolator(clock.CurrentTime(), + CreateTestFieldTrials()); constexpr TimeDelta k24FpsDelay = 1 / Frequency::Hertz(24); uint32_t rtp = 90000; @@ -179,7 +186,8 @@ TEST(TimestampExtrapolatorTest, Fast90KHzClock) { // This simulates a fast camera, which produces frames at 26Hz instead of // 25Hz. The extrapolator should be able to resolve this with enough data. SimulatedClock clock(Timestamp::Millis(1337)); - TimestampExtrapolator ts_extrapolator(clock.CurrentTime()); + TimestampExtrapolator ts_extrapolator(clock.CurrentTime(), + CreateTestFieldTrials()); constexpr TimeDelta k26FpsDelay = 1 / Frequency::Hertz(26); uint32_t rtp = 90000; @@ -205,7 +213,8 @@ TEST(TimestampExtrapolatorTest, TimestampJump) { // This simulates a jump in RTP timestamp, which could occur if a camera was // swapped for example. SimulatedClock clock(Timestamp::Millis(1337)); - TimestampExtrapolator ts_extrapolator(clock.CurrentTime()); + TimestampExtrapolator ts_extrapolator(clock.CurrentTime(), + CreateTestFieldTrials()); uint32_t rtp = 90000; clock.AdvanceTime(k25FpsDelay); @@ -235,7 +244,8 @@ TEST(TimestampExtrapolatorTest, TimestampJump) { TEST(TimestampExtrapolatorTest, GapInReceivedFrames) { SimulatedClock clock( Timestamp::Seconds(std::numeric_limits::max() / 90000 - 31)); - TimestampExtrapolator ts_extrapolator(clock.CurrentTime()); + TimestampExtrapolator ts_extrapolator(clock.CurrentTime(), + CreateTestFieldTrials()); uint32_t rtp = std::numeric_limits::max(); clock.AdvanceTime(k25FpsDelay); @@ -262,7 +272,8 @@ TEST(TimestampExtrapolatorTest, EstimatedClockDriftHistogram) { // Clear all histogram data. metrics::Reset(); SimulatedClock clock(Timestamp::Millis(1337)); - TimestampExtrapolator ts_extrapolator(clock.CurrentTime()); + TimestampExtrapolator ts_extrapolator(clock.CurrentTime(), + CreateTestFieldTrials()); uint32_t rtp = 90000; for (int i = 0; i < kMinimumSamples; ++i) { @@ -283,7 +294,8 @@ TEST(TimestampExtrapolatorTest, EstimatedClockDriftHistogram) { // Clear all histogram data. metrics::Reset(); SimulatedClock clock(Timestamp::Millis(1337)); - TimestampExtrapolator ts_extrapolator(clock.CurrentTime()); + TimestampExtrapolator ts_extrapolator(clock.CurrentTime(), + CreateTestFieldTrials()); uint32_t rtp = 90000; for (int i = 0; i < kMinimumSamples; ++i) { @@ -305,7 +317,8 @@ TEST(TimestampExtrapolatorTest, EstimatedClockDriftHistogram) { // Clear all histogram data. metrics::Reset(); SimulatedClock clock(Timestamp::Millis(1337)); - TimestampExtrapolator ts_extrapolator(clock.CurrentTime()); + TimestampExtrapolator ts_extrapolator(clock.CurrentTime(), + CreateTestFieldTrials()); uint32_t rtp = 90000; for (int i = 0; i < kMinimumSamples; ++i) { @@ -320,4 +333,44 @@ TEST(TimestampExtrapolatorTest, EstimatedClockDriftHistogram) { kPpmTolerance); } +TEST(TimestampExtrapolatorTest, SetsValidConfig) { + SimulatedClock clock(Timestamp::Millis(1337)); + // clang-format off + TimestampExtrapolator ts_extrapolator( + clock.CurrentTime(), CreateTestFieldTrials( + "WebRTC-TimestampExtrapolatorConfig/" + "hard_reset_timeout:1s," + "alarm_threshold:123," + "acc_drift:456," + "acc_max_error:789," + "reset_full_cov_on_alarm:true/")); + // clang-format on + + TimestampExtrapolator::Config config = ts_extrapolator.GetConfigForTest(); + EXPECT_EQ(config.hard_reset_timeout, TimeDelta::Seconds(1)); + EXPECT_EQ(config.alarm_threshold, 123); + EXPECT_EQ(config.acc_drift, 456); + EXPECT_EQ(config.acc_max_error, 789); + EXPECT_TRUE(config.reset_full_cov_on_alarm); +} + +TEST(TimestampExtrapolatorTest, DoesNotSetInvalidConfig) { + SimulatedClock clock(Timestamp::Millis(1337)); + // clang-format off + TimestampExtrapolator ts_extrapolator( + clock.CurrentTime(), CreateTestFieldTrials( + "WebRTC-TimestampExtrapolatorConfig/" + "hard_reset_timeout:-1s," + "alarm_threshold:-123," + "acc_drift:-456," + "acc_max_error:-789/")); + // clang-format on + + TimestampExtrapolator::Config config = ts_extrapolator.GetConfigForTest(); + EXPECT_EQ(config.hard_reset_timeout, TimeDelta::Seconds(10)); + EXPECT_EQ(config.alarm_threshold, 60000); + EXPECT_EQ(config.acc_drift, 6600); + EXPECT_EQ(config.acc_max_error, 7000); +} + } // namespace webrtc diff --git a/modules/video_coding/timing/timing.cc b/modules/video_coding/timing/timing.cc index 302cc7ffa5..853d8cff5e 100644 --- a/modules/video_coding/timing/timing.cc +++ b/modules/video_coding/timing/timing.cc @@ -56,7 +56,8 @@ void CheckDelaysValid(TimeDelta min_delay, TimeDelta max_delay) { VCMTiming::VCMTiming(Clock* clock, const FieldTrialsView& field_trials) : clock_(clock), ts_extrapolator_( - std::make_unique(clock_->CurrentTime())), + std::make_unique(clock_->CurrentTime(), + field_trials)), decode_time_filter_(std::make_unique()), render_delay_(kDefaultRenderDelay), min_playout_delay_(TimeDelta::Zero()), diff --git a/modules/video_coding/timing/timing_unittest.cc b/modules/video_coding/timing/timing_unittest.cc index 61ec9bfb9e..17e1d3d677 100644 --- a/modules/video_coding/timing/timing_unittest.cc +++ b/modules/video_coding/timing/timing_unittest.cc @@ -12,13 +12,14 @@ #include +#include "api/field_trials.h" #include "api/units/frequency.h" #include "api/units/time_delta.h" #include "api/units/timestamp.h" #include "system_wrappers/include/clock.h" +#include "test/create_test_field_trials.h" #include "test/gmock.h" #include "test/gtest.h" -#include "test/scoped_key_value_config.h" namespace webrtc { namespace { @@ -81,7 +82,7 @@ MATCHER(HasConsistentVideoDelayTimings, "") { } // namespace TEST(VCMTimingTest, JitterDelay) { - test::ScopedKeyValueConfig field_trials; + FieldTrials field_trials = CreateTestFieldTrials(); SimulatedClock clock(0); VCMTiming timing(&clock, field_trials); timing.Reset(); @@ -177,7 +178,7 @@ TEST(VCMTimingTest, JitterDelay) { TEST(VCMTimingTest, TimestampWrapAround) { constexpr auto kStartTime = Timestamp::Millis(1337); - test::ScopedKeyValueConfig field_trials; + FieldTrials field_trials = CreateTestFieldTrials(); SimulatedClock clock(kStartTime); VCMTiming timing(&clock, field_trials); @@ -199,7 +200,7 @@ TEST(VCMTimingTest, TimestampWrapAround) { } TEST(VCMTimingTest, UseLowLatencyRenderer) { - test::ScopedKeyValueConfig field_trials; + FieldTrials field_trials = CreateTestFieldTrials(); SimulatedClock clock(0); VCMTiming timing(&clock, field_trials); timing.Reset(); @@ -231,7 +232,7 @@ TEST(VCMTimingTest, MaxWaitingTimeIsZeroForZeroRenderTime) { constexpr TimeDelta kTimeDelta = 1 / Frequency::Hertz(60); constexpr Timestamp kZeroRenderTime = Timestamp::Zero(); SimulatedClock clock(kStartTimeUs); - test::ScopedKeyValueConfig field_trials; + FieldTrials field_trials = CreateTestFieldTrials(); VCMTiming timing(&clock, field_trials); timing.Reset(); timing.set_playout_delay({TimeDelta::Zero(), TimeDelta::Zero()}); @@ -266,8 +267,8 @@ TEST(VCMTimingTest, MaxWaitingTimeZeroDelayPacingExperiment) { // The minimum pacing is enabled by a field trial and active if the RTP // playout delay header extension is set to min==0. constexpr TimeDelta kMinPacing = TimeDelta::Millis(3); - test::ScopedKeyValueConfig field_trials( - "WebRTC-ZeroPlayoutDelay/min_pacing:3ms/"); + FieldTrials field_trials = + CreateTestFieldTrials("WebRTC-ZeroPlayoutDelay/min_pacing:3ms/"); constexpr int64_t kStartTimeUs = 3.15e13; // About one year in us. constexpr TimeDelta kTimeDelta = 1 / Frequency::Hertz(60); constexpr auto kZeroRenderTime = Timestamp::Zero(); @@ -317,8 +318,8 @@ TEST(VCMTimingTest, MaxWaitingTimeZeroDelayPacingExperiment) { TEST(VCMTimingTest, DefaultMaxWaitingTimeUnaffectedByPacingExperiment) { // The minimum pacing is enabled by a field trial but should not have any // effect if render_time_ms is greater than 0; - test::ScopedKeyValueConfig field_trials( - "WebRTC-ZeroPlayoutDelay/min_pacing:3ms/"); + FieldTrials field_trials = + CreateTestFieldTrials("WebRTC-ZeroPlayoutDelay/min_pacing:3ms/"); constexpr int64_t kStartTimeUs = 3.15e13; // About one year in us. const TimeDelta kTimeDelta = TimeDelta::Millis(1000.0 / 60.0); SimulatedClock clock(kStartTimeUs); @@ -350,8 +351,8 @@ TEST(VCMTimingTest, MaxWaitingTimeReturnsZeroIfTooManyFramesQueuedIsTrue) { // The minimum pacing is enabled by a field trial and active if the RTP // playout delay header extension is set to min==0. constexpr TimeDelta kMinPacing = TimeDelta::Millis(3); - test::ScopedKeyValueConfig field_trials( - "WebRTC-ZeroPlayoutDelay/min_pacing:3ms/"); + FieldTrials field_trials = + CreateTestFieldTrials("WebRTC-ZeroPlayoutDelay/min_pacing:3ms/"); constexpr int64_t kStartTimeUs = 3.15e13; // About one year in us. const TimeDelta kTimeDelta = TimeDelta::Millis(1000.0 / 60.0); constexpr auto kZeroRenderTime = Timestamp::Zero(); @@ -386,7 +387,7 @@ TEST(VCMTimingTest, MaxWaitingTimeReturnsZeroIfTooManyFramesQueuedIsTrue) { } TEST(VCMTimingTest, UpdateCurrentDelayCapsWhenOffByMicroseconds) { - test::ScopedKeyValueConfig field_trials; + FieldTrials field_trials = CreateTestFieldTrials(); SimulatedClock clock(0); VCMTiming timing(&clock, field_trials); timing.Reset(); @@ -409,7 +410,7 @@ TEST(VCMTimingTest, UpdateCurrentDelayCapsWhenOffByMicroseconds) { } TEST(VCMTimingTest, GetTimings) { - test::ScopedKeyValueConfig field_trials; + FieldTrials field_trials = CreateTestFieldTrials(); SimulatedClock clock(33); VCMTiming timing(&clock, field_trials); timing.Reset(); @@ -452,7 +453,7 @@ TEST(VCMTimingTest, GetTimings) { TEST(VCMTimingTest, GetTimingsBeforeAndAfterValidRtpTimestamp) { SimulatedClock clock(33); - test::ScopedKeyValueConfig field_trials; + FieldTrials field_trials = CreateTestFieldTrials(); VCMTiming timing(&clock, field_trials); // Setup. diff --git a/modules/video_coding/utility/bandwidth_quality_scaler_unittest.cc b/modules/video_coding/utility/bandwidth_quality_scaler_unittest.cc index e54b597d0b..b563d358df 100644 --- a/modules/video_coding/utility/bandwidth_quality_scaler_unittest.cc +++ b/modules/video_coding/utility/bandwidth_quality_scaler_unittest.cc @@ -102,7 +102,7 @@ class BandwidthQualityScalerTest : public ::testing::Test { }); } - ~BandwidthQualityScalerTest() { + ~BandwidthQualityScalerTest() override { task_queue_.SendTask([this] { bandwidth_quality_scaler_ = nullptr; }); } diff --git a/modules/video_coding/utility/framerate_controller_deprecated.h b/modules/video_coding/utility/framerate_controller_deprecated.h index 6fcda3ddc9..e2d3f119f2 100644 --- a/modules/video_coding/utility/framerate_controller_deprecated.h +++ b/modules/video_coding/utility/framerate_controller_deprecated.h @@ -19,7 +19,7 @@ namespace webrtc { -// Please use webrtc::FramerateController instead. +// Please use FramerateController instead. class FramerateControllerDeprecated { public: explicit FramerateControllerDeprecated(float target_framerate_fps); diff --git a/modules/video_coding/utility/ivf_file_writer_unittest.cc b/modules/video_coding/utility/ivf_file_writer_unittest.cc index 007448fd14..bc6c87722f 100644 --- a/modules/video_coding/utility/ivf_file_writer_unittest.cc +++ b/modules/video_coding/utility/ivf_file_writer_unittest.cc @@ -26,9 +26,9 @@ namespace webrtc { namespace { -static const int kHeaderSize = 32; -static const int kFrameHeaderSize = 12; -static uint8_t dummy_payload[4] = {0, 1, 2, 3}; +const int kHeaderSize = 32; +const int kFrameHeaderSize = 12; +uint8_t dummy_payload[4] = {0, 1, 2, 3}; // As the default parameter when the width and height of encodedImage are 0, // the values are copied from ivf_file_writer.cc constexpr int kDefaultWidth = 1280; diff --git a/modules/video_coding/utility/quality_scaler.cc b/modules/video_coding/utility/quality_scaler.cc index a5fc7041a9..dec77862e9 100644 --- a/modules/video_coding/utility/quality_scaler.cc +++ b/modules/video_coding/utility/quality_scaler.cc @@ -31,10 +31,10 @@ namespace webrtc { namespace { // Threshold constant used until first downscale (to permit fast rampup). -static const int kMeasureMs = 2000; -static const float kSamplePeriodScaleFactor = 2.5; -static const int kFramedropPercentThreshold = 60; -static const size_t kMinFramesNeededToScale = 2 * 30; +const int kMeasureMs = 2000; +const float kSamplePeriodScaleFactor = 2.5; +const int kFramedropPercentThreshold = 60; +const size_t kMinFramesNeededToScale = 2 * 30; } // namespace diff --git a/modules/video_coding/utility/quality_scaler_unittest.cc b/modules/video_coding/utility/quality_scaler_unittest.cc index 6febf0d93d..dca0f4a9af 100644 --- a/modules/video_coding/utility/quality_scaler_unittest.cc +++ b/modules/video_coding/utility/quality_scaler_unittest.cc @@ -13,21 +13,22 @@ #include #include +#include "api/field_trials.h" #include "api/field_trials_view.h" #include "api/units/time_delta.h" #include "api/video_codecs/video_encoder.h" #include "rtc_base/event.h" #include "rtc_base/task_queue_for_test.h" +#include "test/create_test_field_trials.h" #include "test/gtest.h" -#include "test/scoped_key_value_config.h" namespace webrtc { namespace { -static const int kFramerate = 30; -static const int kLowQp = 15; -static const int kHighQp = 40; -static const int kMinFramesNeededToScale = 60; // From quality_scaler.cc. -static constexpr TimeDelta kDefaultTimeout = TimeDelta::Millis(150); +const int kFramerate = 30; +const int kLowQp = 15; +const int kHighQp = 40; +const int kMinFramesNeededToScale = 60; // From quality_scaler.cc. +constexpr TimeDelta kDefaultTimeout = TimeDelta::Millis(150); } // namespace class FakeQpUsageHandler : public QualityScalerQpUsageHandlerInterface { @@ -71,13 +72,13 @@ class QualityScalerTest : public ::testing::Test, }; QualityScalerTest() - : scoped_field_trial_(GetParam()), + : field_trials_(CreateTestFieldTrials(GetParam())), task_queue_("QualityScalerTestQueue"), handler_(std::make_unique()) { task_queue_.SendTask([this] { qs_ = std::unique_ptr(new QualityScalerUnderTest( handler_.get(), VideoEncoder::QpThresholds(kLowQp, kHighQp), - scoped_field_trial_)); + field_trials_)); }); } @@ -107,7 +108,7 @@ class QualityScalerTest : public ::testing::Test, } } - test::ScopedKeyValueConfig scoped_field_trial_; + FieldTrials field_trials_; TaskQueueForTest task_queue_; std::unique_ptr qs_; std::unique_ptr handler_; diff --git a/modules/video_coding/utility/simulcast_rate_allocator.cc b/modules/video_coding/utility/simulcast_rate_allocator.cc index 2811d52a0c..5083d1b888 100644 --- a/modules/video_coding/utility/simulcast_rate_allocator.cc +++ b/modules/video_coding/utility/simulcast_rate_allocator.cc @@ -33,20 +33,22 @@ namespace webrtc { namespace { // Ratio allocation between temporal streams: // Values as required for the VP8 codec (accumulating). -static const float - kLayerRateAllocation[kMaxTemporalStreams][kMaxTemporalStreams] = { - {1.0f, 1.0f, 1.0f, 1.0f}, // 1 layer - {0.6f, 1.0f, 1.0f, 1.0f}, // 2 layers {60%, 40%} - {0.4f, 0.6f, 1.0f, 1.0f}, // 3 layers {40%, 20%, 40%} - {0.25f, 0.4f, 0.6f, 1.0f} // 4 layers {25%, 15%, 20%, 40%} +const float kLayerRateAllocation[kMaxTemporalStreams][kMaxTemporalStreams] = { + {1.0f, 1.0f, 1.0f, 1.0f}, // 1 layer + {0.6f, 1.0f, 1.0f, 1.0f}, // 2 layers {60%, 40%} + {0.4f, 0.6f, 1.0f, 1.0f}, // 3 layers {40%, 20%, 40%} + {0.25f, 0.4f, 0.6f, 1.0f} // 4 layers {25%, 15%, 20%, 40%} }; -static const float kBaseHeavy3TlRateAllocation[kMaxTemporalStreams] = { +const float kBaseHeavy3TlRateAllocation[kMaxTemporalStreams] = { 0.6f, 0.8f, 1.0f, 1.0f // 3 layers {60%, 20%, 20%} }; const uint32_t kLegacyScreenshareTl0BitrateKbps = 200; const uint32_t kLegacyScreenshareTl1BitrateKbps = 1000; + +constexpr double kVideoHysteresisFactor = 1.2; +constexpr double kScreenshareHysteresisFactor = 1.35; } // namespace float SimulcastRateAllocator::GetTemporalRateAllocation( @@ -66,7 +68,6 @@ float SimulcastRateAllocator::GetTemporalRateAllocation( SimulcastRateAllocator::SimulcastRateAllocator(const Environment& env, const VideoCodec& codec) : codec_(codec), - stable_rate_settings_(env.field_trials()), rate_control_settings_(env.field_trials()), legacy_conference_mode_(false) {} @@ -76,10 +77,6 @@ VideoBitrateAllocation SimulcastRateAllocator::Allocate( VideoBitrateAllocationParameters parameters) { VideoBitrateAllocation allocated_bitrates; DataRate stable_rate = parameters.total_bitrate; - if (stable_rate_settings_.IsEnabled() && - parameters.stable_bitrate > DataRate::Zero()) { - stable_rate = std::min(parameters.stable_bitrate, parameters.total_bitrate); - } DistributeAllocationToSimulcastLayers(parameters.total_bitrate, stable_rate, &allocated_bitrates); DistributeAllocationToTemporalLayers(&allocated_bitrates); @@ -167,10 +164,9 @@ void SimulcastRateAllocator::DistributeAllocationToSimulcastLayers( // layers because they require a higher minimum bitrate. DataRate min_bitrate = DataRate::KilobitsPerSec(stream.minBitrate); DataRate target_bitrate = DataRate::KilobitsPerSec(stream.targetBitrate); - double hysteresis_factor = - codec_.mode == VideoCodecMode::kRealtimeVideo - ? stable_rate_settings_.GetVideoHysteresisFactor() - : stable_rate_settings_.GetScreenshareHysteresisFactor(); + double hysteresis_factor = codec_.mode == VideoCodecMode::kRealtimeVideo + ? kVideoHysteresisFactor + : kScreenshareHysteresisFactor; if (!first_allocation && !stream_enabled_[layer_index[active_layer]]) { min_bitrate = std::min(hysteresis_factor * min_bitrate, target_bitrate); } diff --git a/modules/video_coding/utility/simulcast_rate_allocator.h b/modules/video_coding/utility/simulcast_rate_allocator.h index 34da59ef31..0529d0f962 100644 --- a/modules/video_coding/utility/simulcast_rate_allocator.h +++ b/modules/video_coding/utility/simulcast_rate_allocator.h @@ -22,7 +22,6 @@ #include "api/video/video_bitrate_allocator.h" #include "api/video_codecs/video_codec.h" #include "rtc_base/experiments/rate_control_settings.h" -#include "rtc_base/experiments/stable_target_rate_experiment.h" namespace webrtc { @@ -61,7 +60,6 @@ class SimulcastRateAllocator : public VideoBitrateAllocator { int NumTemporalStreams(size_t simulcast_id) const; const VideoCodec codec_; - const StableTargetRateExperiment stable_rate_settings_; const RateControlSettings rate_control_settings_; std::vector stream_enabled_; bool legacy_conference_mode_; diff --git a/modules/video_coding/utility/simulcast_rate_allocator_unittest.cc b/modules/video_coding/utility/simulcast_rate_allocator_unittest.cc index dc15e7d6a2..8909182707 100644 --- a/modules/video_coding/utility/simulcast_rate_allocator_unittest.cc +++ b/modules/video_coding/utility/simulcast_rate_allocator_unittest.cc @@ -18,6 +18,7 @@ #include "api/environment/environment.h" #include "api/environment/environment_factory.h" +#include "api/field_trials.h" #include "api/units/data_rate.h" #include "api/video/video_bitrate_allocation.h" #include "api/video/video_bitrate_allocator.h" @@ -26,13 +27,13 @@ #include "api/video_codecs/vp8_frame_buffer_controller.h" #include "api/video_codecs/vp8_frame_config.h" #include "rtc_base/checks.h" -#include "test/explicit_key_value_config.h" +#include "test/create_test_field_trials.h" #include "test/gmock.h" #include "test/gtest.h" namespace webrtc { namespace { -using test::ExplicitKeyValueConfig; + using ::testing::_; constexpr uint32_t kFramerateFps = 5; @@ -71,7 +72,7 @@ class SimulcastRateAllocatorTest : public ::testing::TestWithParam { codec_.active = true; CreateAllocator(); } - virtual ~SimulcastRateAllocatorTest() {} + ~SimulcastRateAllocatorTest() override {} template void ExpectEqual(uint32_t (&expected)[S], @@ -148,10 +149,9 @@ class SimulcastRateAllocatorTest : public ::testing::TestWithParam { DataRate::KilobitsPerSec(target_bitrate), kDefaultFrameRate)); } - VideoBitrateAllocation GetAllocation(DataRate target_rate, - DataRate stable_rate) { - return allocator_->Allocate(VideoBitrateAllocationParameters( - target_rate, stable_rate, kDefaultFrameRate)); + VideoBitrateAllocation GetAllocation(DataRate target_rate) { + return allocator_->Allocate( + VideoBitrateAllocationParameters(target_rate, kDefaultFrameRate)); } DataRate MinRate(size_t layer_index) const { @@ -305,8 +305,8 @@ TEST_F(SimulcastRateAllocatorTest, Regular3TLTemporalRateAllocation) { } TEST_F(SimulcastRateAllocatorTest, BaseHeavy3TLTemporalRateAllocation) { - ExplicitKeyValueConfig field_trials( - "WebRTC-UseBaseHeavyVP8TL3RateAllocation/Enabled/"); + FieldTrials field_trials = + CreateTestFieldTrials("WebRTC-UseBaseHeavyVP8TL3RateAllocation/Enabled/"); SetupCodec3SL3TL({true, true, true}); CreateAllocator(CreateEnvironment(&field_trials)); @@ -589,71 +589,6 @@ TEST_F(SimulcastRateAllocatorTest, NonConferenceModeScreenshare) { EXPECT_EQ(alloc.GetTemporalLayerAllocation(2).size(), 3u); } -TEST_F(SimulcastRateAllocatorTest, StableRate) { - ExplicitKeyValueConfig field_trials( - "WebRTC-StableTargetRate/" - "enabled:true," - "video_hysteresis_factor:1.1/"); - - SetupCodec3SL3TL({true, true, true}); - CreateAllocator(CreateEnvironment(&field_trials)); - - // Let the volatile rate always be be enough for all streams, in this test we - // are only interested in how the stable rate affects enablement. - const DataRate volatile_rate = - (TargetRate(0) + TargetRate(1) + MinRate(2)) * 1.1; - - { - // On the first call to a new SimulcastRateAllocator instance, hysteresis - // is disabled, but stable rate still caps layers. - uint32_t expected[] = {TargetRate(0).kbps(), - MaxRate(1).kbps()}; - ExpectEqual(expected, - GetAllocation(volatile_rate, TargetRate(0) + MinRate(1))); - } - - { - // Let stable rate go to a bitrate below what is needed for two streams. - uint32_t expected[] = {MaxRate(0).kbps(), 0}; - ExpectEqual(expected, - GetAllocation(volatile_rate, TargetRate(0) + MinRate(1) - - DataRate::BitsPerSec(1))); - } - - { - // Don't enable stream as we need to get up above hysteresis threshold. - uint32_t expected[] = {MaxRate(0).kbps(), 0}; - ExpectEqual(expected, - GetAllocation(volatile_rate, TargetRate(0) + MinRate(1))); - } - - { - // Above threshold with hysteresis, enable second stream. - uint32_t expected[] = {TargetRate(0).kbps(), - MaxRate(1).kbps()}; - ExpectEqual(expected, GetAllocation(volatile_rate, - (TargetRate(0) + MinRate(1)) * 1.1)); - } - - { - // Enough to enable all thee layers. - uint32_t expected[] = { - TargetRate(0).kbps(), TargetRate(1).kbps(), - (volatile_rate - TargetRate(0) - TargetRate(1)).kbps()}; - ExpectEqual(expected, GetAllocation(volatile_rate, volatile_rate)); - } - - { - // Drop hysteresis, all three still on. - uint32_t expected[] = { - TargetRate(0).kbps(), TargetRate(1).kbps(), - (volatile_rate - TargetRate(0) - TargetRate(1)).kbps()}; - ExpectEqual(expected, - GetAllocation(volatile_rate, - TargetRate(0) + TargetRate(1) + MinRate(2))); - } -} - class ScreenshareRateAllocationTest : public SimulcastRateAllocatorTest { public: void SetupConferenceScreenshare(bool use_simulcast, bool active = true) { diff --git a/modules/video_coding/video_codec_initializer_unittest.cc b/modules/video_coding/video_codec_initializer_unittest.cc index f97bf88c58..045c86a6ad 100644 --- a/modules/video_coding/video_codec_initializer_unittest.cc +++ b/modules/video_coding/video_codec_initializer_unittest.cc @@ -40,28 +40,28 @@ namespace webrtc { namespace { -static const int kDefaultWidth = 1280; -static const int kDefaultHeight = 720; -static const int kDefaultFrameRate = 30; -static const uint32_t kDefaultMinBitrateBps = 60000; -static const uint32_t kDefaultTargetBitrateBps = 2000000; -static const uint32_t kDefaultMaxBitrateBps = 2000000; -static const uint32_t kDefaultMinTransmitBitrateBps = 400000; -static const int kDefaultMaxQp = 48; -static const uint32_t kScreenshareTl0BitrateBps = 120000; -static const uint32_t kScreenshareConferenceTl0BitrateBps = 200000; -static const uint32_t kScreenshareCodecTargetBitrateBps = 200000; -static const uint32_t kScreenshareDefaultFramerate = 5; +const int kDefaultWidth = 1280; +const int kDefaultHeight = 720; +const int kDefaultFrameRate = 30; +const uint32_t kDefaultMinBitrateBps = 60000; +const uint32_t kDefaultTargetBitrateBps = 2000000; +const uint32_t kDefaultMaxBitrateBps = 2000000; +const uint32_t kDefaultMinTransmitBitrateBps = 400000; +const int kDefaultMaxQp = 48; +const uint32_t kScreenshareTl0BitrateBps = 120000; +const uint32_t kScreenshareConferenceTl0BitrateBps = 200000; +const uint32_t kScreenshareCodecTargetBitrateBps = 200000; +const uint32_t kScreenshareDefaultFramerate = 5; // Bitrates for the temporal layers of the higher screenshare simulcast stream. -static const uint32_t kHighScreenshareTl0Bps = 800000; -static const uint32_t kHighScreenshareTl1Bps = 1200000; +const uint32_t kHighScreenshareTl0Bps = 800000; +const uint32_t kHighScreenshareTl1Bps = 1200000; } // namespace // TODO(sprang): Extend coverage to handle the rest of the codec initializer. class VideoCodecInitializerTest : public ::testing::Test { public: VideoCodecInitializerTest() {} - virtual ~VideoCodecInitializerTest() {} + ~VideoCodecInitializerTest() override {} protected: void SetUpFor(VideoCodecType type, diff --git a/modules/video_coding/video_receiver2_unittest.cc b/modules/video_coding/video_receiver2_unittest.cc index 8bce1de57c..d665692487 100644 --- a/modules/video_coding/video_receiver2_unittest.cc +++ b/modules/video_coding/video_receiver2_unittest.cc @@ -14,6 +14,7 @@ #include #include +#include "api/field_trials.h" #include "api/test/mock_video_decoder.h" #include "api/units/timestamp.h" #include "api/video/encoded_frame.h" @@ -24,9 +25,9 @@ #include "modules/video_coding/include/video_error_codes.h" #include "modules/video_coding/timing/timing.h" #include "system_wrappers/include/clock.h" +#include "test/create_test_field_trials.h" #include "test/gmock.h" #include "test/gtest.h" -#include "test/scoped_key_value_config.h" namespace webrtc { namespace { @@ -82,7 +83,7 @@ class VideoReceiver2Test : public ::testing::Test { receiver_.RegisterReceiveCodec(payload_type, settings); } - test::ScopedKeyValueConfig field_trials_; + FieldTrials field_trials_ = CreateTestFieldTrials(); SimulatedClock clock_{Timestamp::Millis(1337)}; VCMTiming timing_{&clock_, field_trials_}; NiceMock receive_callback_; diff --git a/modules/video_coding/video_receiver_unittest.cc b/modules/video_coding/video_receiver_unittest.cc index 0e29146aef..0e3036d0aa 100644 --- a/modules/video_coding/video_receiver_unittest.cc +++ b/modules/video_coding/video_receiver_unittest.cc @@ -11,6 +11,7 @@ #include #include +#include "api/field_trials.h" #include "api/rtp_headers.h" #include "api/test/mock_video_decoder.h" #include "api/video/video_codec_type.h" @@ -22,9 +23,9 @@ #include "modules/video_coding/timing/timing.h" #include "modules/video_coding/video_coding_impl.h" #include "system_wrappers/include/clock.h" +#include "test/create_test_field_trials.h" #include "test/gmock.h" #include "test/gtest.h" -#include "test/scoped_key_value_config.h" using ::testing::_; using ::testing::AnyNumber; @@ -45,7 +46,7 @@ class MockPacketRequestCallback : public VCMPacketRequestCallback { class MockVCMReceiveCallback : public VCMReceiveCallback { public: MockVCMReceiveCallback() {} - virtual ~MockVCMReceiveCallback() {} + ~MockVCMReceiveCallback() override {} MOCK_METHOD(int32_t, OnFrameToRender, (const FrameToRender&), (override)); MOCK_METHOD(void, OnIncomingPayloadType, (int), (override)); @@ -61,11 +62,12 @@ class TestVideoReceiver : public ::testing::Test { static const uint16_t kMaxWaitTimeMs = 100; TestVideoReceiver() - : clock_(0), + : field_trials_(CreateTestFieldTrials()), + clock_(0), timing_(&clock_, field_trials_), receiver_(&clock_, &timing_, field_trials_) {} - virtual void SetUp() { + void SetUp() override { // Register decoder. receiver_.RegisterExternalDecoder(&decoder_, kUnusedPayloadType); VideoDecoder::Settings settings; @@ -129,7 +131,7 @@ class TestVideoReceiver : public ::testing::Test { EXPECT_EQ(0, receiver_.Decode(kMaxWaitTimeMs)); } - test::ScopedKeyValueConfig field_trials_; + FieldTrials field_trials_; SimulatedClock clock_; NiceMock decoder_; NiceMock packet_request_callback_; diff --git a/net/dcsctp/fuzzers/dcsctp_fuzzers.cc b/net/dcsctp/fuzzers/dcsctp_fuzzers.cc index 91f258fd2a..35deb0ee17 100644 --- a/net/dcsctp/fuzzers/dcsctp_fuzzers.cc +++ b/net/dcsctp/fuzzers/dcsctp_fuzzers.cc @@ -34,9 +34,9 @@ namespace dcsctp { namespace dcsctp_fuzzers { namespace { -static constexpr int kRandomValue = FuzzerCallbacks::kRandomValue; -static constexpr size_t kMinInputLength = 5; -static constexpr size_t kMaxInputLength = 1024; +constexpr int kRandomValue = FuzzerCallbacks::kRandomValue; +constexpr size_t kMinInputLength = 5; +constexpr size_t kMaxInputLength = 1024; // A starting state for the socket, when fuzzing. enum class StartingState : int { diff --git a/net/dcsctp/packet/BUILD.gn b/net/dcsctp/packet/BUILD.gn index dcdff0856c..f1ab075eb3 100644 --- a/net/dcsctp/packet/BUILD.gn +++ b/net/dcsctp/packet/BUILD.gn @@ -159,8 +159,10 @@ rtc_library("chunk") { "../../../rtc_base:checks", "../../../rtc_base:logging", "../../../rtc_base:stringutils", + "../common:internal_types", "../common:math", "../packet:bounded_io", + "../public:types", "//third_party/abseil-cpp/absl/algorithm:container", "//third_party/abseil-cpp/absl/strings:string_view", ] diff --git a/net/dcsctp/packet/chunk/abort_chunk.cc b/net/dcsctp/packet/chunk/abort_chunk.cc index d7190a7d5e..42840d34a0 100644 --- a/net/dcsctp/packet/chunk/abort_chunk.cc +++ b/net/dcsctp/packet/chunk/abort_chunk.cc @@ -9,17 +9,16 @@ */ #include "net/dcsctp/packet/chunk/abort_chunk.h" -#include - +#include #include +#include #include #include #include "api/array_view.h" #include "net/dcsctp/packet/bounded_byte_reader.h" #include "net/dcsctp/packet/bounded_byte_writer.h" -#include "net/dcsctp/packet/error_cause/error_cause.h" -#include "net/dcsctp/packet/tlv_trait.h" +#include "net/dcsctp/packet/parameter/parameter.h" namespace dcsctp { diff --git a/net/dcsctp/packet/chunk/abort_chunk_test.cc b/net/dcsctp/packet/chunk/abort_chunk_test.cc index c1f3a4d5b9..ac471d846d 100644 --- a/net/dcsctp/packet/chunk/abort_chunk_test.cc +++ b/net/dcsctp/packet/chunk/abort_chunk_test.cc @@ -9,16 +9,13 @@ */ #include "net/dcsctp/packet/chunk/abort_chunk.h" -#include - -#include +#include #include -#include "net/dcsctp/packet/error_cause/error_cause.h" #include "net/dcsctp/packet/error_cause/user_initiated_abort_cause.h" +#include "net/dcsctp/packet/parameter/parameter.h" #include "net/dcsctp/testing/testing_macros.h" -#include "rtc_base/gunit.h" -#include "test/gmock.h" +#include "test/gtest.h" namespace dcsctp { namespace { diff --git a/net/dcsctp/packet/chunk/cookie_ack_chunk.cc b/net/dcsctp/packet/chunk/cookie_ack_chunk.cc index c48462067a..194bbca01b 100644 --- a/net/dcsctp/packet/chunk/cookie_ack_chunk.cc +++ b/net/dcsctp/packet/chunk/cookie_ack_chunk.cc @@ -9,9 +9,9 @@ */ #include "net/dcsctp/packet/chunk/cookie_ack_chunk.h" -#include - +#include #include +#include #include #include "api/array_view.h" diff --git a/net/dcsctp/packet/chunk/cookie_ack_chunk_test.cc b/net/dcsctp/packet/chunk/cookie_ack_chunk_test.cc index 3f560c6fef..05e007756d 100644 --- a/net/dcsctp/packet/chunk/cookie_ack_chunk_test.cc +++ b/net/dcsctp/packet/chunk/cookie_ack_chunk_test.cc @@ -9,14 +9,11 @@ */ #include "net/dcsctp/packet/chunk/cookie_ack_chunk.h" -#include - -#include +#include #include #include "net/dcsctp/testing/testing_macros.h" -#include "rtc_base/gunit.h" -#include "test/gmock.h" +#include "test/gtest.h" namespace dcsctp { namespace { diff --git a/net/dcsctp/packet/chunk/cookie_echo_chunk.cc b/net/dcsctp/packet/chunk/cookie_echo_chunk.cc index daa85622ee..580e15d460 100644 --- a/net/dcsctp/packet/chunk/cookie_echo_chunk.cc +++ b/net/dcsctp/packet/chunk/cookie_echo_chunk.cc @@ -9,16 +9,14 @@ */ #include "net/dcsctp/packet/chunk/cookie_echo_chunk.h" -#include - +#include #include -#include +#include #include #include "api/array_view.h" #include "net/dcsctp/packet/bounded_byte_reader.h" #include "net/dcsctp/packet/bounded_byte_writer.h" -#include "net/dcsctp/packet/tlv_trait.h" namespace dcsctp { diff --git a/net/dcsctp/packet/chunk/cookie_echo_chunk_test.cc b/net/dcsctp/packet/chunk/cookie_echo_chunk_test.cc index d06e0a6439..9f3f24cdf1 100644 --- a/net/dcsctp/packet/chunk/cookie_echo_chunk_test.cc +++ b/net/dcsctp/packet/chunk/cookie_echo_chunk_test.cc @@ -9,15 +9,13 @@ */ #include "net/dcsctp/packet/chunk/cookie_echo_chunk.h" -#include - -#include +#include #include #include "api/array_view.h" #include "net/dcsctp/testing/testing_macros.h" -#include "rtc_base/gunit.h" #include "test/gmock.h" +#include "test/gtest.h" namespace dcsctp { namespace { diff --git a/net/dcsctp/packet/chunk/data_chunk.cc b/net/dcsctp/packet/chunk/data_chunk.cc index 229ba0cc36..2f242bad10 100644 --- a/net/dcsctp/packet/chunk/data_chunk.cc +++ b/net/dcsctp/packet/chunk/data_chunk.cc @@ -9,17 +9,18 @@ */ #include "net/dcsctp/packet/chunk/data_chunk.h" -#include - +#include #include #include -#include #include #include "api/array_view.h" +#include "net/dcsctp/common/internal_types.h" #include "net/dcsctp/packet/bounded_byte_reader.h" #include "net/dcsctp/packet/bounded_byte_writer.h" #include "net/dcsctp/packet/chunk/data_common.h" +#include "net/dcsctp/packet/data.h" +#include "net/dcsctp/public/types.h" #include "rtc_base/strings/string_builder.h" namespace dcsctp { diff --git a/net/dcsctp/packet/chunk/error_chunk.cc b/net/dcsctp/packet/chunk/error_chunk.cc index 67a439ee7b..7d445b320a 100644 --- a/net/dcsctp/packet/chunk/error_chunk.cc +++ b/net/dcsctp/packet/chunk/error_chunk.cc @@ -9,17 +9,16 @@ */ #include "net/dcsctp/packet/chunk/error_chunk.h" -#include - +#include #include +#include #include #include #include "api/array_view.h" #include "net/dcsctp/packet/bounded_byte_reader.h" #include "net/dcsctp/packet/bounded_byte_writer.h" -#include "net/dcsctp/packet/error_cause/error_cause.h" -#include "net/dcsctp/packet/tlv_trait.h" +#include "net/dcsctp/packet/parameter/parameter.h" namespace dcsctp { diff --git a/net/dcsctp/packet/chunk/forward_tsn_chunk.cc b/net/dcsctp/packet/chunk/forward_tsn_chunk.cc index f9cf67e117..59c9ed3a9e 100644 --- a/net/dcsctp/packet/chunk/forward_tsn_chunk.cc +++ b/net/dcsctp/packet/chunk/forward_tsn_chunk.cc @@ -9,19 +9,19 @@ */ #include "net/dcsctp/packet/chunk/forward_tsn_chunk.h" -#include -#include - +#include +#include #include #include #include #include #include "api/array_view.h" +#include "net/dcsctp/common/internal_types.h" #include "net/dcsctp/packet/bounded_byte_reader.h" #include "net/dcsctp/packet/bounded_byte_writer.h" #include "net/dcsctp/packet/chunk/forward_tsn_common.h" -#include "net/dcsctp/packet/tlv_trait.h" +#include "net/dcsctp/public/types.h" #include "rtc_base/strings/string_builder.h" namespace dcsctp { diff --git a/net/dcsctp/packet/chunk/forward_tsn_chunk_test.cc b/net/dcsctp/packet/chunk/forward_tsn_chunk_test.cc index 51f97f2396..982e7ce229 100644 --- a/net/dcsctp/packet/chunk/forward_tsn_chunk_test.cc +++ b/net/dcsctp/packet/chunk/forward_tsn_chunk_test.cc @@ -9,16 +9,16 @@ */ #include "net/dcsctp/packet/chunk/forward_tsn_chunk.h" -#include - -#include +#include #include #include "api/array_view.h" +#include "net/dcsctp/common/internal_types.h" #include "net/dcsctp/packet/chunk/forward_tsn_common.h" +#include "net/dcsctp/public/types.h" #include "net/dcsctp/testing/testing_macros.h" -#include "rtc_base/gunit.h" #include "test/gmock.h" +#include "test/gtest.h" namespace dcsctp { namespace { diff --git a/net/dcsctp/packet/chunk/heartbeat_ack_chunk.cc b/net/dcsctp/packet/chunk/heartbeat_ack_chunk.cc index 68855bc52a..0d86ed34a1 100644 --- a/net/dcsctp/packet/chunk/heartbeat_ack_chunk.cc +++ b/net/dcsctp/packet/chunk/heartbeat_ack_chunk.cc @@ -9,9 +9,9 @@ */ #include "net/dcsctp/packet/chunk/heartbeat_ack_chunk.h" -#include - +#include #include +#include #include #include @@ -19,7 +19,6 @@ #include "net/dcsctp/packet/bounded_byte_reader.h" #include "net/dcsctp/packet/bounded_byte_writer.h" #include "net/dcsctp/packet/parameter/parameter.h" -#include "net/dcsctp/packet/tlv_trait.h" namespace dcsctp { diff --git a/net/dcsctp/packet/chunk/heartbeat_ack_chunk_test.cc b/net/dcsctp/packet/chunk/heartbeat_ack_chunk_test.cc index e4d0dd1489..6e41e7b272 100644 --- a/net/dcsctp/packet/chunk/heartbeat_ack_chunk_test.cc +++ b/net/dcsctp/packet/chunk/heartbeat_ack_chunk_test.cc @@ -9,8 +9,7 @@ */ #include "net/dcsctp/packet/chunk/heartbeat_ack_chunk.h" -#include - +#include #include #include @@ -18,8 +17,8 @@ #include "net/dcsctp/packet/parameter/heartbeat_info_parameter.h" #include "net/dcsctp/packet/parameter/parameter.h" #include "net/dcsctp/testing/testing_macros.h" -#include "rtc_base/gunit.h" #include "test/gmock.h" +#include "test/gtest.h" namespace dcsctp { namespace { diff --git a/net/dcsctp/packet/chunk/heartbeat_request_chunk.cc b/net/dcsctp/packet/chunk/heartbeat_request_chunk.cc index dd8f3e8c8b..6efb7e0d4e 100644 --- a/net/dcsctp/packet/chunk/heartbeat_request_chunk.cc +++ b/net/dcsctp/packet/chunk/heartbeat_request_chunk.cc @@ -9,9 +9,9 @@ */ #include "net/dcsctp/packet/chunk/heartbeat_request_chunk.h" -#include - +#include #include +#include #include #include @@ -19,7 +19,6 @@ #include "net/dcsctp/packet/bounded_byte_reader.h" #include "net/dcsctp/packet/bounded_byte_writer.h" #include "net/dcsctp/packet/parameter/parameter.h" -#include "net/dcsctp/packet/tlv_trait.h" namespace dcsctp { diff --git a/net/dcsctp/packet/chunk/heartbeat_request_chunk_test.cc b/net/dcsctp/packet/chunk/heartbeat_request_chunk_test.cc index 94911fe28b..ab50025550 100644 --- a/net/dcsctp/packet/chunk/heartbeat_request_chunk_test.cc +++ b/net/dcsctp/packet/chunk/heartbeat_request_chunk_test.cc @@ -9,8 +9,7 @@ */ #include "net/dcsctp/packet/chunk/heartbeat_request_chunk.h" -#include - +#include #include #include @@ -18,8 +17,8 @@ #include "net/dcsctp/packet/parameter/heartbeat_info_parameter.h" #include "net/dcsctp/packet/parameter/parameter.h" #include "net/dcsctp/testing/testing_macros.h" -#include "rtc_base/gunit.h" #include "test/gmock.h" +#include "test/gtest.h" namespace dcsctp { namespace { diff --git a/net/dcsctp/packet/chunk/idata_chunk.cc b/net/dcsctp/packet/chunk/idata_chunk.cc index e084dc332f..2d38f97967 100644 --- a/net/dcsctp/packet/chunk/idata_chunk.cc +++ b/net/dcsctp/packet/chunk/idata_chunk.cc @@ -9,17 +9,18 @@ */ #include "net/dcsctp/packet/chunk/idata_chunk.h" -#include - +#include #include #include -#include #include #include "api/array_view.h" +#include "net/dcsctp/common/internal_types.h" #include "net/dcsctp/packet/bounded_byte_reader.h" #include "net/dcsctp/packet/bounded_byte_writer.h" #include "net/dcsctp/packet/chunk/data_common.h" +#include "net/dcsctp/packet/data.h" +#include "net/dcsctp/public/types.h" #include "rtc_base/strings/string_builder.h" namespace dcsctp { diff --git a/net/dcsctp/packet/chunk/iforward_tsn_chunk.cc b/net/dcsctp/packet/chunk/iforward_tsn_chunk.cc index 19f5780951..b454420fd2 100644 --- a/net/dcsctp/packet/chunk/iforward_tsn_chunk.cc +++ b/net/dcsctp/packet/chunk/iforward_tsn_chunk.cc @@ -9,19 +9,20 @@ */ #include "net/dcsctp/packet/chunk/iforward_tsn_chunk.h" -#include -#include - +#include +#include #include #include #include #include #include "api/array_view.h" +#include "net/dcsctp/common/internal_types.h" #include "net/dcsctp/packet/bounded_byte_reader.h" #include "net/dcsctp/packet/bounded_byte_writer.h" #include "net/dcsctp/packet/chunk/forward_tsn_common.h" -#include "net/dcsctp/packet/tlv_trait.h" +#include "net/dcsctp/public/types.h" +#include "rtc_base/checks.h" #include "rtc_base/strings/string_builder.h" namespace dcsctp { diff --git a/net/dcsctp/packet/chunk/iforward_tsn_chunk_test.cc b/net/dcsctp/packet/chunk/iforward_tsn_chunk_test.cc index 6a89433be1..d7f3479242 100644 --- a/net/dcsctp/packet/chunk/iforward_tsn_chunk_test.cc +++ b/net/dcsctp/packet/chunk/iforward_tsn_chunk_test.cc @@ -9,16 +9,16 @@ */ #include "net/dcsctp/packet/chunk/iforward_tsn_chunk.h" -#include - -#include +#include #include #include "api/array_view.h" +#include "net/dcsctp/common/internal_types.h" #include "net/dcsctp/packet/chunk/forward_tsn_common.h" +#include "net/dcsctp/public/types.h" #include "net/dcsctp/testing/testing_macros.h" -#include "rtc_base/gunit.h" #include "test/gmock.h" +#include "test/gtest.h" namespace dcsctp { namespace { diff --git a/net/dcsctp/packet/chunk/init_ack_chunk.cc b/net/dcsctp/packet/chunk/init_ack_chunk.cc index 5b6a03c3b5..027a98f945 100644 --- a/net/dcsctp/packet/chunk/init_ack_chunk.cc +++ b/net/dcsctp/packet/chunk/init_ack_chunk.cc @@ -9,18 +9,17 @@ */ #include "net/dcsctp/packet/chunk/init_ack_chunk.h" -#include - +#include #include #include #include #include #include "api/array_view.h" +#include "net/dcsctp/common/internal_types.h" #include "net/dcsctp/packet/bounded_byte_reader.h" #include "net/dcsctp/packet/bounded_byte_writer.h" #include "net/dcsctp/packet/parameter/parameter.h" -#include "net/dcsctp/packet/tlv_trait.h" #include "rtc_base/strings/string_format.h" namespace dcsctp { diff --git a/net/dcsctp/packet/chunk/init_ack_chunk_test.cc b/net/dcsctp/packet/chunk/init_ack_chunk_test.cc index 184ade747d..2741d6757b 100644 --- a/net/dcsctp/packet/chunk/init_ack_chunk_test.cc +++ b/net/dcsctp/packet/chunk/init_ack_chunk_test.cc @@ -9,19 +9,19 @@ */ #include "net/dcsctp/packet/chunk/init_ack_chunk.h" -#include - +#include #include #include #include "api/array_view.h" +#include "net/dcsctp/common/internal_types.h" #include "net/dcsctp/packet/parameter/forward_tsn_supported_parameter.h" #include "net/dcsctp/packet/parameter/parameter.h" #include "net/dcsctp/packet/parameter/state_cookie_parameter.h" #include "net/dcsctp/packet/parameter/supported_extensions_parameter.h" #include "net/dcsctp/testing/testing_macros.h" -#include "rtc_base/gunit.h" #include "test/gmock.h" +#include "test/gtest.h" namespace dcsctp { namespace { diff --git a/net/dcsctp/packet/chunk/init_chunk.cc b/net/dcsctp/packet/chunk/init_chunk.cc index c9ca4ae711..5f557c775a 100644 --- a/net/dcsctp/packet/chunk/init_chunk.cc +++ b/net/dcsctp/packet/chunk/init_chunk.cc @@ -9,18 +9,17 @@ */ #include "net/dcsctp/packet/chunk/init_chunk.h" -#include - +#include #include #include #include #include #include "api/array_view.h" +#include "net/dcsctp/common/internal_types.h" #include "net/dcsctp/packet/bounded_byte_reader.h" #include "net/dcsctp/packet/bounded_byte_writer.h" #include "net/dcsctp/packet/parameter/parameter.h" -#include "net/dcsctp/packet/tlv_trait.h" #include "rtc_base/strings/string_format.h" namespace dcsctp { diff --git a/net/dcsctp/packet/chunk/init_chunk_test.cc b/net/dcsctp/packet/chunk/init_chunk_test.cc index bd36d6fdf8..70372c7529 100644 --- a/net/dcsctp/packet/chunk/init_chunk_test.cc +++ b/net/dcsctp/packet/chunk/init_chunk_test.cc @@ -9,17 +9,15 @@ */ #include "net/dcsctp/packet/chunk/init_chunk.h" -#include - -#include +#include #include +#include "net/dcsctp/common/internal_types.h" #include "net/dcsctp/packet/parameter/forward_tsn_supported_parameter.h" #include "net/dcsctp/packet/parameter/parameter.h" #include "net/dcsctp/packet/parameter/supported_extensions_parameter.h" #include "net/dcsctp/testing/testing_macros.h" -#include "rtc_base/gunit.h" -#include "test/gmock.h" +#include "test/gtest.h" namespace dcsctp { namespace { diff --git a/net/dcsctp/packet/chunk/reconfig_chunk.cc b/net/dcsctp/packet/chunk/reconfig_chunk.cc index 6cbbd17ef0..b9188c9786 100644 --- a/net/dcsctp/packet/chunk/reconfig_chunk.cc +++ b/net/dcsctp/packet/chunk/reconfig_chunk.cc @@ -9,9 +9,9 @@ */ #include "net/dcsctp/packet/chunk/reconfig_chunk.h" -#include - +#include #include +#include #include #include @@ -19,7 +19,6 @@ #include "net/dcsctp/packet/bounded_byte_reader.h" #include "net/dcsctp/packet/bounded_byte_writer.h" #include "net/dcsctp/packet/parameter/parameter.h" -#include "net/dcsctp/packet/tlv_trait.h" namespace dcsctp { diff --git a/net/dcsctp/packet/chunk/sack_chunk.cc b/net/dcsctp/packet/chunk/sack_chunk.cc index 108c5cab0a..3ee23a8acd 100644 --- a/net/dcsctp/packet/chunk/sack_chunk.cc +++ b/net/dcsctp/packet/chunk/sack_chunk.cc @@ -9,18 +9,18 @@ */ #include "net/dcsctp/packet/chunk/sack_chunk.h" -#include - +#include #include #include +#include #include -#include #include #include "api/array_view.h" +#include "net/dcsctp/common/internal_types.h" #include "net/dcsctp/packet/bounded_byte_reader.h" #include "net/dcsctp/packet/bounded_byte_writer.h" -#include "net/dcsctp/packet/tlv_trait.h" +#include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "rtc_base/strings/str_join.h" #include "rtc_base/strings/string_builder.h" diff --git a/net/dcsctp/packet/chunk/shutdown_ack_chunk.cc b/net/dcsctp/packet/chunk/shutdown_ack_chunk.cc index 31ba417f70..438bfa8ab0 100644 --- a/net/dcsctp/packet/chunk/shutdown_ack_chunk.cc +++ b/net/dcsctp/packet/chunk/shutdown_ack_chunk.cc @@ -9,9 +9,9 @@ */ #include "net/dcsctp/packet/chunk/shutdown_ack_chunk.h" -#include - +#include #include +#include #include #include "api/array_view.h" diff --git a/net/dcsctp/packet/chunk/shutdown_ack_chunk_test.cc b/net/dcsctp/packet/chunk/shutdown_ack_chunk_test.cc index ef04ea9892..a2a05a181b 100644 --- a/net/dcsctp/packet/chunk/shutdown_ack_chunk_test.cc +++ b/net/dcsctp/packet/chunk/shutdown_ack_chunk_test.cc @@ -9,12 +9,10 @@ */ #include "net/dcsctp/packet/chunk/shutdown_ack_chunk.h" -#include - +#include #include -#include "rtc_base/gunit.h" -#include "test/gmock.h" +#include "test/gtest.h" namespace dcsctp { namespace { diff --git a/net/dcsctp/packet/chunk/shutdown_chunk.cc b/net/dcsctp/packet/chunk/shutdown_chunk.cc index 8038458724..9554b621f1 100644 --- a/net/dcsctp/packet/chunk/shutdown_chunk.cc +++ b/net/dcsctp/packet/chunk/shutdown_chunk.cc @@ -9,16 +9,15 @@ */ #include "net/dcsctp/packet/chunk/shutdown_chunk.h" -#include - +#include #include -#include +#include #include #include "api/array_view.h" +#include "net/dcsctp/common/internal_types.h" #include "net/dcsctp/packet/bounded_byte_reader.h" #include "net/dcsctp/packet/bounded_byte_writer.h" -#include "net/dcsctp/packet/tlv_trait.h" namespace dcsctp { diff --git a/net/dcsctp/packet/chunk/shutdown_chunk_test.cc b/net/dcsctp/packet/chunk/shutdown_chunk_test.cc index 16d147ca83..072a1a177d 100644 --- a/net/dcsctp/packet/chunk/shutdown_chunk_test.cc +++ b/net/dcsctp/packet/chunk/shutdown_chunk_test.cc @@ -9,13 +9,12 @@ */ #include "net/dcsctp/packet/chunk/shutdown_chunk.h" -#include - -#include +#include #include +#include "net/dcsctp/common/internal_types.h" #include "net/dcsctp/testing/testing_macros.h" -#include "rtc_base/gunit.h" +#include "test/gtest.h" namespace dcsctp { namespace { diff --git a/net/dcsctp/packet/chunk/shutdown_complete_chunk.cc b/net/dcsctp/packet/chunk/shutdown_complete_chunk.cc index 0733f2164b..5fa1c3710a 100644 --- a/net/dcsctp/packet/chunk/shutdown_complete_chunk.cc +++ b/net/dcsctp/packet/chunk/shutdown_complete_chunk.cc @@ -9,16 +9,14 @@ */ #include "net/dcsctp/packet/chunk/shutdown_complete_chunk.h" -#include - +#include #include -#include +#include #include #include "api/array_view.h" #include "net/dcsctp/packet/bounded_byte_reader.h" #include "net/dcsctp/packet/bounded_byte_writer.h" -#include "net/dcsctp/packet/tlv_trait.h" namespace dcsctp { diff --git a/net/dcsctp/packet/chunk/shutdown_complete_chunk_test.cc b/net/dcsctp/packet/chunk/shutdown_complete_chunk_test.cc index 253900d5cd..cc1d01b442 100644 --- a/net/dcsctp/packet/chunk/shutdown_complete_chunk_test.cc +++ b/net/dcsctp/packet/chunk/shutdown_complete_chunk_test.cc @@ -9,12 +9,10 @@ */ #include "net/dcsctp/packet/chunk/shutdown_complete_chunk.h" -#include - +#include #include -#include "rtc_base/gunit.h" -#include "test/gmock.h" +#include "test/gtest.h" namespace dcsctp { namespace { diff --git a/net/dcsctp/packet/error_cause/cookie_received_while_shutting_down_cause.cc b/net/dcsctp/packet/error_cause/cookie_received_while_shutting_down_cause.cc index 61dc953f11..6530f40396 100644 --- a/net/dcsctp/packet/error_cause/cookie_received_while_shutting_down_cause.cc +++ b/net/dcsctp/packet/error_cause/cookie_received_while_shutting_down_cause.cc @@ -9,9 +9,9 @@ */ #include "net/dcsctp/packet/error_cause/cookie_received_while_shutting_down_cause.h" -#include - +#include #include +#include #include #include "api/array_view.h" diff --git a/net/dcsctp/packet/error_cause/cookie_received_while_shutting_down_cause_test.cc b/net/dcsctp/packet/error_cause/cookie_received_while_shutting_down_cause_test.cc index afb8364c32..475e53d43c 100644 --- a/net/dcsctp/packet/error_cause/cookie_received_while_shutting_down_cause_test.cc +++ b/net/dcsctp/packet/error_cause/cookie_received_while_shutting_down_cause_test.cc @@ -9,13 +9,11 @@ */ #include "net/dcsctp/packet/error_cause/cookie_received_while_shutting_down_cause.h" -#include - -#include +#include #include #include "net/dcsctp/testing/testing_macros.h" -#include "rtc_base/gunit.h" +#include "test/gtest.h" namespace dcsctp { namespace { diff --git a/net/dcsctp/packet/error_cause/error_cause.cc b/net/dcsctp/packet/error_cause/error_cause.cc index 291cc51776..d6a885b964 100644 --- a/net/dcsctp/packet/error_cause/error_cause.cc +++ b/net/dcsctp/packet/error_cause/error_cause.cc @@ -9,17 +9,11 @@ */ #include "net/dcsctp/packet/error_cause/error_cause.h" -#include - -#include -#include +#include #include #include -#include #include -#include "api/array_view.h" -#include "net/dcsctp/common/math.h" #include "net/dcsctp/packet/error_cause/cookie_received_while_shutting_down_cause.h" #include "net/dcsctp/packet/error_cause/invalid_mandatory_parameter_cause.h" #include "net/dcsctp/packet/error_cause/invalid_stream_identifier_cause.h" @@ -33,6 +27,7 @@ #include "net/dcsctp/packet/error_cause/unrecognized_parameter_cause.h" #include "net/dcsctp/packet/error_cause/unresolvable_address_cause.h" #include "net/dcsctp/packet/error_cause/user_initiated_abort_cause.h" +#include "net/dcsctp/packet/parameter/parameter.h" #include "rtc_base/strings/string_builder.h" namespace dcsctp { diff --git a/net/dcsctp/packet/error_cause/invalid_mandatory_parameter_cause.cc b/net/dcsctp/packet/error_cause/invalid_mandatory_parameter_cause.cc index 8ddd4fb495..4e8fdf934b 100644 --- a/net/dcsctp/packet/error_cause/invalid_mandatory_parameter_cause.cc +++ b/net/dcsctp/packet/error_cause/invalid_mandatory_parameter_cause.cc @@ -9,9 +9,9 @@ */ #include "net/dcsctp/packet/error_cause/invalid_mandatory_parameter_cause.h" -#include - +#include #include +#include #include #include "api/array_view.h" diff --git a/net/dcsctp/packet/error_cause/invalid_mandatory_parameter_cause_test.cc b/net/dcsctp/packet/error_cause/invalid_mandatory_parameter_cause_test.cc index 3d532d09b1..b6d461c932 100644 --- a/net/dcsctp/packet/error_cause/invalid_mandatory_parameter_cause_test.cc +++ b/net/dcsctp/packet/error_cause/invalid_mandatory_parameter_cause_test.cc @@ -9,13 +9,11 @@ */ #include "net/dcsctp/packet/error_cause/invalid_mandatory_parameter_cause.h" -#include - -#include +#include #include #include "net/dcsctp/testing/testing_macros.h" -#include "rtc_base/gunit.h" +#include "test/gtest.h" namespace dcsctp { namespace { diff --git a/net/dcsctp/packet/error_cause/invalid_stream_identifier_cause.cc b/net/dcsctp/packet/error_cause/invalid_stream_identifier_cause.cc index 225ed71e38..3e661cae86 100644 --- a/net/dcsctp/packet/error_cause/invalid_stream_identifier_cause.cc +++ b/net/dcsctp/packet/error_cause/invalid_stream_identifier_cause.cc @@ -9,17 +9,15 @@ */ #include "net/dcsctp/packet/error_cause/invalid_stream_identifier_cause.h" -#include - +#include #include #include -#include #include #include "api/array_view.h" #include "net/dcsctp/packet/bounded_byte_reader.h" #include "net/dcsctp/packet/bounded_byte_writer.h" -#include "net/dcsctp/packet/tlv_trait.h" +#include "net/dcsctp/public/types.h" #include "rtc_base/strings/string_builder.h" namespace dcsctp { diff --git a/net/dcsctp/packet/error_cause/invalid_stream_identifier_cause_test.cc b/net/dcsctp/packet/error_cause/invalid_stream_identifier_cause_test.cc index a282ce5ee8..5b2fe803a4 100644 --- a/net/dcsctp/packet/error_cause/invalid_stream_identifier_cause_test.cc +++ b/net/dcsctp/packet/error_cause/invalid_stream_identifier_cause_test.cc @@ -9,13 +9,12 @@ */ #include "net/dcsctp/packet/error_cause/invalid_stream_identifier_cause.h" -#include - -#include +#include #include +#include "net/dcsctp/public/types.h" #include "net/dcsctp/testing/testing_macros.h" -#include "rtc_base/gunit.h" +#include "test/gtest.h" namespace dcsctp { namespace { diff --git a/net/dcsctp/packet/error_cause/missing_mandatory_parameter_cause.cc b/net/dcsctp/packet/error_cause/missing_mandatory_parameter_cause.cc index 378d83d5b2..5a408370f5 100644 --- a/net/dcsctp/packet/error_cause/missing_mandatory_parameter_cause.cc +++ b/net/dcsctp/packet/error_cause/missing_mandatory_parameter_cause.cc @@ -9,18 +9,15 @@ */ #include "net/dcsctp/packet/error_cause/missing_mandatory_parameter_cause.h" -#include - +#include #include #include #include -#include #include #include "api/array_view.h" #include "net/dcsctp/packet/bounded_byte_reader.h" #include "net/dcsctp/packet/bounded_byte_writer.h" -#include "net/dcsctp/packet/tlv_trait.h" #include "rtc_base/logging.h" #include "rtc_base/strings/str_join.h" #include "rtc_base/strings/string_builder.h" diff --git a/net/dcsctp/packet/error_cause/missing_mandatory_parameter_cause_test.cc b/net/dcsctp/packet/error_cause/missing_mandatory_parameter_cause_test.cc index 1c526ff0e2..ade3667484 100644 --- a/net/dcsctp/packet/error_cause/missing_mandatory_parameter_cause_test.cc +++ b/net/dcsctp/packet/error_cause/missing_mandatory_parameter_cause_test.cc @@ -9,15 +9,13 @@ */ #include "net/dcsctp/packet/error_cause/missing_mandatory_parameter_cause.h" -#include - -#include +#include #include #include "api/array_view.h" #include "net/dcsctp/testing/testing_macros.h" -#include "rtc_base/gunit.h" #include "test/gmock.h" +#include "test/gtest.h" namespace dcsctp { namespace { diff --git a/net/dcsctp/packet/error_cause/no_user_data_cause.cc b/net/dcsctp/packet/error_cause/no_user_data_cause.cc index 45cef7e9ec..c73163ecca 100644 --- a/net/dcsctp/packet/error_cause/no_user_data_cause.cc +++ b/net/dcsctp/packet/error_cause/no_user_data_cause.cc @@ -9,17 +9,15 @@ */ #include "net/dcsctp/packet/error_cause/no_user_data_cause.h" -#include - +#include #include #include -#include #include #include "api/array_view.h" +#include "net/dcsctp/common/internal_types.h" #include "net/dcsctp/packet/bounded_byte_reader.h" #include "net/dcsctp/packet/bounded_byte_writer.h" -#include "net/dcsctp/packet/tlv_trait.h" #include "rtc_base/strings/string_builder.h" namespace dcsctp { diff --git a/net/dcsctp/packet/error_cause/no_user_data_cause_test.cc b/net/dcsctp/packet/error_cause/no_user_data_cause_test.cc index 0a535bf4fa..c96d570752 100644 --- a/net/dcsctp/packet/error_cause/no_user_data_cause_test.cc +++ b/net/dcsctp/packet/error_cause/no_user_data_cause_test.cc @@ -9,13 +9,12 @@ */ #include "net/dcsctp/packet/error_cause/no_user_data_cause.h" -#include - -#include +#include #include +#include "net/dcsctp/common/internal_types.h" #include "net/dcsctp/testing/testing_macros.h" -#include "rtc_base/gunit.h" +#include "test/gtest.h" namespace dcsctp { namespace { diff --git a/net/dcsctp/packet/error_cause/out_of_resource_error_cause.cc b/net/dcsctp/packet/error_cause/out_of_resource_error_cause.cc index ffa3c16967..9e2adc7bec 100644 --- a/net/dcsctp/packet/error_cause/out_of_resource_error_cause.cc +++ b/net/dcsctp/packet/error_cause/out_of_resource_error_cause.cc @@ -9,9 +9,9 @@ */ #include "net/dcsctp/packet/error_cause/out_of_resource_error_cause.h" -#include - +#include #include +#include #include #include "api/array_view.h" diff --git a/net/dcsctp/packet/error_cause/out_of_resource_error_cause_test.cc b/net/dcsctp/packet/error_cause/out_of_resource_error_cause_test.cc index 501fc201cd..38eef4acfa 100644 --- a/net/dcsctp/packet/error_cause/out_of_resource_error_cause_test.cc +++ b/net/dcsctp/packet/error_cause/out_of_resource_error_cause_test.cc @@ -9,13 +9,11 @@ */ #include "net/dcsctp/packet/error_cause/out_of_resource_error_cause.h" -#include - -#include +#include #include #include "net/dcsctp/testing/testing_macros.h" -#include "rtc_base/gunit.h" +#include "test/gtest.h" namespace dcsctp { namespace { diff --git a/net/dcsctp/packet/error_cause/protocol_violation_cause.cc b/net/dcsctp/packet/error_cause/protocol_violation_cause.cc index d7bc582050..65bbfefe62 100644 --- a/net/dcsctp/packet/error_cause/protocol_violation_cause.cc +++ b/net/dcsctp/packet/error_cause/protocol_violation_cause.cc @@ -9,17 +9,14 @@ */ #include "net/dcsctp/packet/error_cause/protocol_violation_cause.h" -#include - +#include #include #include -#include #include #include "api/array_view.h" #include "net/dcsctp/packet/bounded_byte_reader.h" #include "net/dcsctp/packet/bounded_byte_writer.h" -#include "net/dcsctp/packet/tlv_trait.h" #include "rtc_base/strings/string_builder.h" namespace dcsctp { diff --git a/net/dcsctp/packet/error_cause/protocol_violation_cause_test.cc b/net/dcsctp/packet/error_cause/protocol_violation_cause_test.cc index 902d867091..de3ef22086 100644 --- a/net/dcsctp/packet/error_cause/protocol_violation_cause_test.cc +++ b/net/dcsctp/packet/error_cause/protocol_violation_cause_test.cc @@ -9,17 +9,13 @@ */ #include "net/dcsctp/packet/error_cause/protocol_violation_cause.h" -#include - -#include #include #include "api/array_view.h" -#include "net/dcsctp/packet/error_cause/error_cause.h" -#include "net/dcsctp/packet/tlv_trait.h" +#include "net/dcsctp/packet/parameter/parameter.h" #include "net/dcsctp/testing/testing_macros.h" -#include "rtc_base/gunit.h" #include "test/gmock.h" +#include "test/gtest.h" namespace dcsctp { namespace { diff --git a/net/dcsctp/packet/error_cause/restart_of_an_association_with_new_address_cause.cc b/net/dcsctp/packet/error_cause/restart_of_an_association_with_new_address_cause.cc index fd3dfa88b7..ab15b6a22f 100644 --- a/net/dcsctp/packet/error_cause/restart_of_an_association_with_new_address_cause.cc +++ b/net/dcsctp/packet/error_cause/restart_of_an_association_with_new_address_cause.cc @@ -9,16 +9,14 @@ */ #include "net/dcsctp/packet/error_cause/restart_of_an_association_with_new_address_cause.h" -#include - +#include #include -#include +#include #include #include "api/array_view.h" #include "net/dcsctp/packet/bounded_byte_reader.h" #include "net/dcsctp/packet/bounded_byte_writer.h" -#include "net/dcsctp/packet/tlv_trait.h" namespace dcsctp { diff --git a/net/dcsctp/packet/error_cause/restart_of_an_association_with_new_address_cause_test.cc b/net/dcsctp/packet/error_cause/restart_of_an_association_with_new_address_cause_test.cc index b8ab8b6803..0c3b3fcb30 100644 --- a/net/dcsctp/packet/error_cause/restart_of_an_association_with_new_address_cause_test.cc +++ b/net/dcsctp/packet/error_cause/restart_of_an_association_with_new_address_cause_test.cc @@ -9,15 +9,13 @@ */ #include "net/dcsctp/packet/error_cause/restart_of_an_association_with_new_address_cause.h" -#include - -#include +#include #include #include "api/array_view.h" #include "net/dcsctp/testing/testing_macros.h" -#include "rtc_base/gunit.h" #include "test/gmock.h" +#include "test/gtest.h" namespace dcsctp { namespace { diff --git a/net/dcsctp/packet/error_cause/stale_cookie_error_cause.cc b/net/dcsctp/packet/error_cause/stale_cookie_error_cause.cc index 122c28f4a9..8cb6f8ee87 100644 --- a/net/dcsctp/packet/error_cause/stale_cookie_error_cause.cc +++ b/net/dcsctp/packet/error_cause/stale_cookie_error_cause.cc @@ -9,17 +9,14 @@ */ #include "net/dcsctp/packet/error_cause/stale_cookie_error_cause.h" -#include - +#include #include #include -#include #include #include "api/array_view.h" #include "net/dcsctp/packet/bounded_byte_reader.h" #include "net/dcsctp/packet/bounded_byte_writer.h" -#include "net/dcsctp/packet/tlv_trait.h" #include "rtc_base/strings/string_builder.h" namespace dcsctp { diff --git a/net/dcsctp/packet/error_cause/stale_cookie_error_cause_test.cc b/net/dcsctp/packet/error_cause/stale_cookie_error_cause_test.cc index c0d1ac1c58..aef130cec4 100644 --- a/net/dcsctp/packet/error_cause/stale_cookie_error_cause_test.cc +++ b/net/dcsctp/packet/error_cause/stale_cookie_error_cause_test.cc @@ -9,13 +9,11 @@ */ #include "net/dcsctp/packet/error_cause/stale_cookie_error_cause.h" -#include - -#include +#include #include #include "net/dcsctp/testing/testing_macros.h" -#include "rtc_base/gunit.h" +#include "test/gtest.h" namespace dcsctp { namespace { diff --git a/net/dcsctp/packet/error_cause/unrecognized_parameter_cause.cc b/net/dcsctp/packet/error_cause/unrecognized_parameter_cause.cc index 708111ed4c..fac0647738 100644 --- a/net/dcsctp/packet/error_cause/unrecognized_parameter_cause.cc +++ b/net/dcsctp/packet/error_cause/unrecognized_parameter_cause.cc @@ -9,16 +9,14 @@ */ #include "net/dcsctp/packet/error_cause/unrecognized_parameter_cause.h" -#include - +#include #include -#include +#include #include #include "api/array_view.h" #include "net/dcsctp/packet/bounded_byte_reader.h" #include "net/dcsctp/packet/bounded_byte_writer.h" -#include "net/dcsctp/packet/tlv_trait.h" namespace dcsctp { diff --git a/net/dcsctp/packet/error_cause/unrecognized_parameter_cause_test.cc b/net/dcsctp/packet/error_cause/unrecognized_parameter_cause_test.cc index 0449599ca6..189205c2a1 100644 --- a/net/dcsctp/packet/error_cause/unrecognized_parameter_cause_test.cc +++ b/net/dcsctp/packet/error_cause/unrecognized_parameter_cause_test.cc @@ -9,15 +9,13 @@ */ #include "net/dcsctp/packet/error_cause/unrecognized_parameter_cause.h" -#include - -#include +#include #include #include "api/array_view.h" #include "net/dcsctp/testing/testing_macros.h" -#include "rtc_base/gunit.h" #include "test/gmock.h" +#include "test/gtest.h" namespace dcsctp { namespace { diff --git a/net/dcsctp/packet/error_cause/unresolvable_address_cause.cc b/net/dcsctp/packet/error_cause/unresolvable_address_cause.cc index b7b9ffbec7..8b3493ec66 100644 --- a/net/dcsctp/packet/error_cause/unresolvable_address_cause.cc +++ b/net/dcsctp/packet/error_cause/unresolvable_address_cause.cc @@ -9,16 +9,14 @@ */ #include "net/dcsctp/packet/error_cause/unresolvable_address_cause.h" -#include - +#include #include -#include +#include #include #include "api/array_view.h" #include "net/dcsctp/packet/bounded_byte_reader.h" #include "net/dcsctp/packet/bounded_byte_writer.h" -#include "net/dcsctp/packet/tlv_trait.h" namespace dcsctp { diff --git a/net/dcsctp/packet/error_cause/unresolvable_address_cause_test.cc b/net/dcsctp/packet/error_cause/unresolvable_address_cause_test.cc index 688730e6b3..4c76683ed3 100644 --- a/net/dcsctp/packet/error_cause/unresolvable_address_cause_test.cc +++ b/net/dcsctp/packet/error_cause/unresolvable_address_cause_test.cc @@ -9,15 +9,13 @@ */ #include "net/dcsctp/packet/error_cause/unresolvable_address_cause.h" -#include - -#include +#include #include #include "api/array_view.h" #include "net/dcsctp/testing/testing_macros.h" -#include "rtc_base/gunit.h" #include "test/gmock.h" +#include "test/gtest.h" namespace dcsctp { namespace { diff --git a/net/dcsctp/packet/error_cause/user_initiated_abort_cause.cc b/net/dcsctp/packet/error_cause/user_initiated_abort_cause.cc index de86983fcb..557a1527a2 100644 --- a/net/dcsctp/packet/error_cause/user_initiated_abort_cause.cc +++ b/net/dcsctp/packet/error_cause/user_initiated_abort_cause.cc @@ -9,17 +9,14 @@ */ #include "net/dcsctp/packet/error_cause/user_initiated_abort_cause.h" -#include - +#include #include #include -#include #include #include "api/array_view.h" #include "net/dcsctp/packet/bounded_byte_reader.h" #include "net/dcsctp/packet/bounded_byte_writer.h" -#include "net/dcsctp/packet/tlv_trait.h" #include "rtc_base/strings/string_builder.h" namespace dcsctp { diff --git a/net/dcsctp/packet/error_cause/user_initiated_abort_cause_test.cc b/net/dcsctp/packet/error_cause/user_initiated_abort_cause_test.cc index 250959e3df..683900778f 100644 --- a/net/dcsctp/packet/error_cause/user_initiated_abort_cause_test.cc +++ b/net/dcsctp/packet/error_cause/user_initiated_abort_cause_test.cc @@ -9,17 +9,13 @@ */ #include "net/dcsctp/packet/error_cause/user_initiated_abort_cause.h" -#include - -#include #include #include "api/array_view.h" -#include "net/dcsctp/packet/error_cause/error_cause.h" -#include "net/dcsctp/packet/tlv_trait.h" +#include "net/dcsctp/packet/parameter/parameter.h" #include "net/dcsctp/testing/testing_macros.h" -#include "rtc_base/gunit.h" #include "test/gmock.h" +#include "test/gtest.h" namespace dcsctp { namespace { diff --git a/net/dcsctp/packet/parameter/add_incoming_streams_request_parameter.cc b/net/dcsctp/packet/parameter/add_incoming_streams_request_parameter.cc index 55b189bf2c..bb982da473 100644 --- a/net/dcsctp/packet/parameter/add_incoming_streams_request_parameter.cc +++ b/net/dcsctp/packet/parameter/add_incoming_streams_request_parameter.cc @@ -9,18 +9,15 @@ */ #include "net/dcsctp/packet/parameter/add_incoming_streams_request_parameter.h" -#include - +#include #include #include -#include #include #include "api/array_view.h" #include "net/dcsctp/common/internal_types.h" #include "net/dcsctp/packet/bounded_byte_reader.h" #include "net/dcsctp/packet/bounded_byte_writer.h" -#include "net/dcsctp/packet/tlv_trait.h" #include "rtc_base/strings/string_builder.h" namespace dcsctp { diff --git a/net/dcsctp/packet/parameter/add_incoming_streams_request_parameter_test.cc b/net/dcsctp/packet/parameter/add_incoming_streams_request_parameter_test.cc index a29257a8f8..134201c079 100644 --- a/net/dcsctp/packet/parameter/add_incoming_streams_request_parameter_test.cc +++ b/net/dcsctp/packet/parameter/add_incoming_streams_request_parameter_test.cc @@ -9,13 +9,12 @@ */ #include "net/dcsctp/packet/parameter/add_incoming_streams_request_parameter.h" -#include - -#include +#include #include +#include "net/dcsctp/common/internal_types.h" #include "net/dcsctp/testing/testing_macros.h" -#include "rtc_base/gunit.h" +#include "test/gtest.h" namespace dcsctp { namespace { diff --git a/net/dcsctp/packet/parameter/add_outgoing_streams_request_parameter.cc b/net/dcsctp/packet/parameter/add_outgoing_streams_request_parameter.cc index 3f9e9c377f..9e4f679479 100644 --- a/net/dcsctp/packet/parameter/add_outgoing_streams_request_parameter.cc +++ b/net/dcsctp/packet/parameter/add_outgoing_streams_request_parameter.cc @@ -9,17 +9,15 @@ */ #include "net/dcsctp/packet/parameter/add_outgoing_streams_request_parameter.h" -#include - +#include #include #include -#include #include #include "api/array_view.h" +#include "net/dcsctp/common/internal_types.h" #include "net/dcsctp/packet/bounded_byte_reader.h" #include "net/dcsctp/packet/bounded_byte_writer.h" -#include "net/dcsctp/packet/tlv_trait.h" #include "rtc_base/strings/string_builder.h" namespace dcsctp { diff --git a/net/dcsctp/packet/parameter/add_outgoing_streams_request_parameter_test.cc b/net/dcsctp/packet/parameter/add_outgoing_streams_request_parameter_test.cc index d0303b1ba8..0e1f18175a 100644 --- a/net/dcsctp/packet/parameter/add_outgoing_streams_request_parameter_test.cc +++ b/net/dcsctp/packet/parameter/add_outgoing_streams_request_parameter_test.cc @@ -9,13 +9,12 @@ */ #include "net/dcsctp/packet/parameter/add_outgoing_streams_request_parameter.h" -#include - -#include +#include #include +#include "net/dcsctp/common/internal_types.h" #include "net/dcsctp/testing/testing_macros.h" -#include "rtc_base/gunit.h" +#include "test/gtest.h" namespace dcsctp { namespace { diff --git a/net/dcsctp/packet/parameter/forward_tsn_supported_parameter.cc b/net/dcsctp/packet/parameter/forward_tsn_supported_parameter.cc index fed399ff0b..6ab7b75e40 100644 --- a/net/dcsctp/packet/parameter/forward_tsn_supported_parameter.cc +++ b/net/dcsctp/packet/parameter/forward_tsn_supported_parameter.cc @@ -9,9 +9,9 @@ */ #include "net/dcsctp/packet/parameter/forward_tsn_supported_parameter.h" -#include - +#include #include +#include #include #include "api/array_view.h" diff --git a/net/dcsctp/packet/parameter/forward_tsn_supported_parameter_test.cc b/net/dcsctp/packet/parameter/forward_tsn_supported_parameter_test.cc index fb4f983fae..b5429eed5d 100644 --- a/net/dcsctp/packet/parameter/forward_tsn_supported_parameter_test.cc +++ b/net/dcsctp/packet/parameter/forward_tsn_supported_parameter_test.cc @@ -9,13 +9,11 @@ */ #include "net/dcsctp/packet/parameter/forward_tsn_supported_parameter.h" -#include - -#include +#include #include #include "net/dcsctp/testing/testing_macros.h" -#include "rtc_base/gunit.h" +#include "test/gtest.h" namespace dcsctp { namespace { diff --git a/net/dcsctp/packet/parameter/heartbeat_info_parameter.cc b/net/dcsctp/packet/parameter/heartbeat_info_parameter.cc index 93d283d545..dc78b77223 100644 --- a/net/dcsctp/packet/parameter/heartbeat_info_parameter.cc +++ b/net/dcsctp/packet/parameter/heartbeat_info_parameter.cc @@ -9,17 +9,14 @@ */ #include "net/dcsctp/packet/parameter/heartbeat_info_parameter.h" -#include - +#include #include #include -#include #include #include "api/array_view.h" #include "net/dcsctp/packet/bounded_byte_reader.h" #include "net/dcsctp/packet/bounded_byte_writer.h" -#include "net/dcsctp/packet/tlv_trait.h" #include "rtc_base/strings/string_builder.h" namespace dcsctp { diff --git a/net/dcsctp/packet/parameter/incoming_ssn_reset_request_parameter.cc b/net/dcsctp/packet/parameter/incoming_ssn_reset_request_parameter.cc index 138c2fd086..e9e70a3ad7 100644 --- a/net/dcsctp/packet/parameter/incoming_ssn_reset_request_parameter.cc +++ b/net/dcsctp/packet/parameter/incoming_ssn_reset_request_parameter.cc @@ -9,8 +9,7 @@ */ #include "net/dcsctp/packet/parameter/incoming_ssn_reset_request_parameter.h" -#include - +#include #include #include #include @@ -18,9 +17,10 @@ #include #include "api/array_view.h" +#include "net/dcsctp/common/internal_types.h" #include "net/dcsctp/packet/bounded_byte_reader.h" #include "net/dcsctp/packet/bounded_byte_writer.h" -#include "net/dcsctp/packet/tlv_trait.h" +#include "net/dcsctp/public/types.h" #include "rtc_base/strings/string_builder.h" namespace dcsctp { diff --git a/net/dcsctp/packet/parameter/outgoing_ssn_reset_request_parameter.cc b/net/dcsctp/packet/parameter/outgoing_ssn_reset_request_parameter.cc index 56ec00ecbd..4338dcf934 100644 --- a/net/dcsctp/packet/parameter/outgoing_ssn_reset_request_parameter.cc +++ b/net/dcsctp/packet/parameter/outgoing_ssn_reset_request_parameter.cc @@ -9,8 +9,7 @@ */ #include "net/dcsctp/packet/parameter/outgoing_ssn_reset_request_parameter.h" -#include - +#include #include #include #include @@ -21,7 +20,6 @@ #include "net/dcsctp/common/internal_types.h" #include "net/dcsctp/packet/bounded_byte_reader.h" #include "net/dcsctp/packet/bounded_byte_writer.h" -#include "net/dcsctp/packet/tlv_trait.h" #include "net/dcsctp/public/types.h" #include "rtc_base/strings/string_builder.h" diff --git a/net/dcsctp/packet/parameter/parameter.cc b/net/dcsctp/packet/parameter/parameter.cc index e6765c197c..fadcbd4a6c 100644 --- a/net/dcsctp/packet/parameter/parameter.cc +++ b/net/dcsctp/packet/parameter/parameter.cc @@ -9,32 +9,15 @@ */ #include "net/dcsctp/packet/parameter/parameter.h" -#include - +#include #include -#include #include -#include -#include #include -#include "absl/memory/memory.h" #include "api/array_view.h" #include "net/dcsctp/common/math.h" #include "net/dcsctp/packet/bounded_byte_reader.h" -#include "net/dcsctp/packet/parameter/add_incoming_streams_request_parameter.h" -#include "net/dcsctp/packet/parameter/add_outgoing_streams_request_parameter.h" -#include "net/dcsctp/packet/parameter/forward_tsn_supported_parameter.h" -#include "net/dcsctp/packet/parameter/heartbeat_info_parameter.h" -#include "net/dcsctp/packet/parameter/incoming_ssn_reset_request_parameter.h" -#include "net/dcsctp/packet/parameter/outgoing_ssn_reset_request_parameter.h" -#include "net/dcsctp/packet/parameter/reconfiguration_response_parameter.h" -#include "net/dcsctp/packet/parameter/ssn_tsn_reset_request_parameter.h" -#include "net/dcsctp/packet/parameter/state_cookie_parameter.h" -#include "net/dcsctp/packet/parameter/supported_extensions_parameter.h" -#include "net/dcsctp/packet/tlv_trait.h" #include "rtc_base/logging.h" -#include "rtc_base/strings/string_builder.h" namespace dcsctp { diff --git a/net/dcsctp/packet/parameter/reconfiguration_response_parameter.cc b/net/dcsctp/packet/parameter/reconfiguration_response_parameter.cc index b8debe8bf9..c8a494d905 100644 --- a/net/dcsctp/packet/parameter/reconfiguration_response_parameter.cc +++ b/net/dcsctp/packet/parameter/reconfiguration_response_parameter.cc @@ -9,9 +9,8 @@ */ #include "net/dcsctp/packet/parameter/reconfiguration_response_parameter.h" -#include -#include - +#include +#include #include #include #include @@ -19,9 +18,9 @@ #include "absl/strings/string_view.h" #include "api/array_view.h" +#include "net/dcsctp/common/internal_types.h" #include "net/dcsctp/packet/bounded_byte_reader.h" #include "net/dcsctp/packet/bounded_byte_writer.h" -#include "net/dcsctp/packet/tlv_trait.h" #include "rtc_base/logging.h" #include "rtc_base/strings/string_builder.h" diff --git a/net/dcsctp/packet/parameter/reconfiguration_response_parameter_test.cc b/net/dcsctp/packet/parameter/reconfiguration_response_parameter_test.cc index b7845452dd..dd54fe69af 100644 --- a/net/dcsctp/packet/parameter/reconfiguration_response_parameter_test.cc +++ b/net/dcsctp/packet/parameter/reconfiguration_response_parameter_test.cc @@ -9,15 +9,13 @@ */ #include "net/dcsctp/packet/parameter/reconfiguration_response_parameter.h" -#include - +#include #include -#include #include +#include "net/dcsctp/common/internal_types.h" #include "net/dcsctp/testing/testing_macros.h" -#include "rtc_base/gunit.h" -#include "test/gmock.h" +#include "test/gtest.h" namespace dcsctp { namespace { diff --git a/net/dcsctp/packet/parameter/ssn_tsn_reset_request_parameter.cc b/net/dcsctp/packet/parameter/ssn_tsn_reset_request_parameter.cc index 93d5f133f4..090bd08dda 100644 --- a/net/dcsctp/packet/parameter/ssn_tsn_reset_request_parameter.cc +++ b/net/dcsctp/packet/parameter/ssn_tsn_reset_request_parameter.cc @@ -9,17 +9,15 @@ */ #include "net/dcsctp/packet/parameter/ssn_tsn_reset_request_parameter.h" -#include - +#include #include #include -#include #include #include "api/array_view.h" +#include "net/dcsctp/common/internal_types.h" #include "net/dcsctp/packet/bounded_byte_reader.h" #include "net/dcsctp/packet/bounded_byte_writer.h" -#include "net/dcsctp/packet/tlv_trait.h" #include "rtc_base/strings/string_builder.h" namespace dcsctp { diff --git a/net/dcsctp/packet/parameter/ssn_tsn_reset_request_parameter_test.cc b/net/dcsctp/packet/parameter/ssn_tsn_reset_request_parameter_test.cc index eeb973cbcb..abbdeec126 100644 --- a/net/dcsctp/packet/parameter/ssn_tsn_reset_request_parameter_test.cc +++ b/net/dcsctp/packet/parameter/ssn_tsn_reset_request_parameter_test.cc @@ -9,14 +9,12 @@ */ #include "net/dcsctp/packet/parameter/ssn_tsn_reset_request_parameter.h" -#include - -#include +#include #include +#include "net/dcsctp/common/internal_types.h" #include "net/dcsctp/testing/testing_macros.h" -#include "rtc_base/gunit.h" -#include "test/gmock.h" +#include "test/gtest.h" namespace dcsctp { namespace { diff --git a/net/dcsctp/packet/parameter/state_cookie_parameter.cc b/net/dcsctp/packet/parameter/state_cookie_parameter.cc index 0c4d068fa0..9fd65587c8 100644 --- a/net/dcsctp/packet/parameter/state_cookie_parameter.cc +++ b/net/dcsctp/packet/parameter/state_cookie_parameter.cc @@ -9,17 +9,14 @@ */ #include "net/dcsctp/packet/parameter/state_cookie_parameter.h" -#include - +#include #include #include -#include #include #include "api/array_view.h" #include "net/dcsctp/packet/bounded_byte_reader.h" #include "net/dcsctp/packet/bounded_byte_writer.h" -#include "net/dcsctp/packet/tlv_trait.h" #include "rtc_base/strings/string_builder.h" namespace dcsctp { diff --git a/net/dcsctp/packet/parameter/state_cookie_parameter_test.cc b/net/dcsctp/packet/parameter/state_cookie_parameter_test.cc index bcca38b586..4093764768 100644 --- a/net/dcsctp/packet/parameter/state_cookie_parameter_test.cc +++ b/net/dcsctp/packet/parameter/state_cookie_parameter_test.cc @@ -9,15 +9,13 @@ */ #include "net/dcsctp/packet/parameter/state_cookie_parameter.h" -#include - -#include +#include #include #include "api/array_view.h" #include "net/dcsctp/testing/testing_macros.h" -#include "rtc_base/gunit.h" #include "test/gmock.h" +#include "test/gtest.h" namespace dcsctp { namespace { diff --git a/net/dcsctp/packet/parameter/zero_checksum_acceptable_chunk_parameter.cc b/net/dcsctp/packet/parameter/zero_checksum_acceptable_chunk_parameter.cc index 4fd46c96ec..d65105f858 100644 --- a/net/dcsctp/packet/parameter/zero_checksum_acceptable_chunk_parameter.cc +++ b/net/dcsctp/packet/parameter/zero_checksum_acceptable_chunk_parameter.cc @@ -9,12 +9,15 @@ */ #include "net/dcsctp/packet/parameter/zero_checksum_acceptable_chunk_parameter.h" -#include - +#include #include +#include #include #include "api/array_view.h" +#include "net/dcsctp/packet/bounded_byte_reader.h" +#include "net/dcsctp/packet/bounded_byte_writer.h" +#include "net/dcsctp/public/types.h" #include "rtc_base/strings/string_builder.h" namespace dcsctp { diff --git a/net/dcsctp/packet/parameter/zero_checksum_acceptable_chunk_parameter_test.cc b/net/dcsctp/packet/parameter/zero_checksum_acceptable_chunk_parameter_test.cc index 861fa4d785..f5c7d3f16d 100644 --- a/net/dcsctp/packet/parameter/zero_checksum_acceptable_chunk_parameter_test.cc +++ b/net/dcsctp/packet/parameter/zero_checksum_acceptable_chunk_parameter_test.cc @@ -9,13 +9,11 @@ */ #include "net/dcsctp/packet/parameter/zero_checksum_acceptable_chunk_parameter.h" -#include - -#include +#include #include +#include "net/dcsctp/public/types.h" #include "net/dcsctp/testing/testing_macros.h" -#include "rtc_base/gunit.h" #include "test/gmock.h" #include "test/gtest.h" diff --git a/net/dcsctp/packet/sctp_packet.cc b/net/dcsctp/packet/sctp_packet.cc index 391d52151a..0440f3627f 100644 --- a/net/dcsctp/packet/sctp_packet.cc +++ b/net/dcsctp/packet/sctp_packet.cc @@ -9,22 +9,22 @@ */ #include "net/dcsctp/packet/sctp_packet.h" -#include - +#include #include #include -#include #include #include -#include "absl/memory/memory.h" #include "api/array_view.h" +#include "net/dcsctp/common/internal_types.h" #include "net/dcsctp/common/math.h" #include "net/dcsctp/packet/bounded_byte_reader.h" #include "net/dcsctp/packet/bounded_byte_writer.h" #include "net/dcsctp/packet/chunk/chunk.h" #include "net/dcsctp/packet/crc32c.h" #include "net/dcsctp/public/dcsctp_options.h" +#include "net/dcsctp/public/types.h" +#include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "rtc_base/strings/string_format.h" diff --git a/net/dcsctp/rx/BUILD.gn b/net/dcsctp/rx/BUILD.gn index 2046a27a80..33d5228d01 100644 --- a/net/dcsctp/rx/BUILD.gn +++ b/net/dcsctp/rx/BUILD.gn @@ -47,9 +47,11 @@ rtc_library("interleaved_reassembly_streams") { "../../../api:array_view", "../../../rtc_base:checks", "../../../rtc_base:logging", + "../common:internal_types", "../common:sequence_numbers", "../packet:chunk", "../packet:data", + "../public:socket", "../public:types", "//third_party/abseil-cpp/absl/algorithm:container", "//third_party/abseil-cpp/absl/strings:string_view", @@ -65,9 +67,11 @@ rtc_library("traditional_reassembly_streams") { "../../../api:array_view", "../../../rtc_base:checks", "../../../rtc_base:logging", + "../common:internal_types", "../common:sequence_numbers", "../packet:chunk", "../packet:data", + "../public:socket", "../public:types", "//third_party/abseil-cpp/absl/algorithm:container", "//third_party/abseil-cpp/absl/strings:string_view", @@ -120,9 +124,11 @@ if (rtc_include_tests) { "../../../rtc_base:gunit_helpers", "../../../test:test_support", "../common:handover_testing", + "../common:internal_types", "../common:sequence_numbers", "../packet:chunk", "../packet:data", + "../public:socket", "../public:types", "../testing:data_generator", "../timer", diff --git a/net/dcsctp/rx/interleaved_reassembly_streams.cc b/net/dcsctp/rx/interleaved_reassembly_streams.cc index c34c042281..0e4dbe21fe 100644 --- a/net/dcsctp/rx/interleaved_reassembly_streams.cc +++ b/net/dcsctp/rx/interleaved_reassembly_streams.cc @@ -9,23 +9,25 @@ */ #include "net/dcsctp/rx/interleaved_reassembly_streams.h" -#include - +#include #include -#include #include #include -#include -#include +#include #include #include #include "absl/algorithm/container.h" +#include "absl/strings/string_view.h" #include "api/array_view.h" +#include "net/dcsctp/common/internal_types.h" #include "net/dcsctp/common/sequence_numbers.h" #include "net/dcsctp/packet/chunk/forward_tsn_common.h" #include "net/dcsctp/packet/data.h" +#include "net/dcsctp/public/dcsctp_handover_state.h" +#include "net/dcsctp/public/dcsctp_message.h" #include "net/dcsctp/public/types.h" +#include "rtc_base/checks.h" #include "rtc_base/logging.h" namespace dcsctp { diff --git a/net/dcsctp/rx/reassembly_queue.cc b/net/dcsctp/rx/reassembly_queue.cc index 3d3c5a4205..5607221ca4 100644 --- a/net/dcsctp/rx/reassembly_queue.cc +++ b/net/dcsctp/rx/reassembly_queue.cc @@ -9,32 +9,29 @@ */ #include "net/dcsctp/rx/reassembly_queue.h" -#include - -#include -#include +#include #include #include -#include -#include #include #include #include "absl/strings/string_view.h" #include "api/array_view.h" +#include "net/dcsctp/common/internal_types.h" #include "net/dcsctp/common/sequence_numbers.h" #include "net/dcsctp/packet/chunk/forward_tsn_common.h" #include "net/dcsctp/packet/data.h" -#include "net/dcsctp/packet/parameter/outgoing_ssn_reset_request_parameter.h" -#include "net/dcsctp/packet/parameter/reconfiguration_response_parameter.h" #include "net/dcsctp/public/dcsctp_handover_state.h" #include "net/dcsctp/public/dcsctp_message.h" #include "net/dcsctp/public/types.h" #include "net/dcsctp/rx/interleaved_reassembly_streams.h" #include "net/dcsctp/rx/reassembly_streams.h" #include "net/dcsctp/rx/traditional_reassembly_streams.h" +#include "rtc_base/checks.h" +#include "rtc_base/containers/flat_set.h" #include "rtc_base/logging.h" #include "rtc_base/strings/str_join.h" +#include "rtc_base/strings/string_builder.h" namespace dcsctp { namespace { diff --git a/net/dcsctp/rx/reassembly_queue_test.cc b/net/dcsctp/rx/reassembly_queue_test.cc index e619f403c8..ff93625765 100644 --- a/net/dcsctp/rx/reassembly_queue_test.cc +++ b/net/dcsctp/rx/reassembly_queue_test.cc @@ -9,25 +9,24 @@ */ #include "net/dcsctp/rx/reassembly_queue.h" -#include - #include #include +#include #include #include #include #include "api/array_view.h" #include "net/dcsctp/common/handover_testing.h" -#include "net/dcsctp/packet/chunk/forward_tsn_chunk.h" +#include "net/dcsctp/common/internal_types.h" #include "net/dcsctp/packet/chunk/forward_tsn_common.h" -#include "net/dcsctp/packet/chunk/iforward_tsn_chunk.h" #include "net/dcsctp/packet/data.h" +#include "net/dcsctp/public/dcsctp_handover_state.h" #include "net/dcsctp/public/dcsctp_message.h" #include "net/dcsctp/public/types.h" #include "net/dcsctp/testing/data_generator.h" -#include "rtc_base/gunit.h" #include "test/gmock.h" +#include "test/gtest.h" namespace dcsctp { namespace { @@ -37,22 +36,21 @@ using ::testing::UnorderedElementsAre; using SkippedStream = AnyForwardTsnChunk::SkippedStream; // The default maximum size of the Reassembly Queue. -static constexpr size_t kBufferSize = 10000; - -static constexpr StreamID kStreamID(1); -static constexpr SSN kSSN(0); -static constexpr MID kMID(0); -static constexpr FSN kFSN(0); -static constexpr PPID kPPID(53); - -static constexpr std::array kShortPayload = {1, 2, 3, 4}; -static constexpr std::array kMessage2Payload = {5, 6, 7, 8}; -static constexpr std::array kSixBytePayload = {1, 2, 3, 4, 5, 6}; -static constexpr std::array kMediumPayload1 = {1, 2, 3, 4, - 5, 6, 7, 8}; -static constexpr std::array kMediumPayload2 = {9, 10, 11, 12, - 13, 14, 15, 16}; -static constexpr std::array kLongPayload = { +constexpr size_t kBufferSize = 10000; + +constexpr StreamID kStreamID(1); +constexpr SSN kSSN(0); +constexpr MID kMID(0); +constexpr FSN kFSN(0); +constexpr PPID kPPID(53); + +constexpr std::array kShortPayload = {1, 2, 3, 4}; +constexpr std::array kMessage2Payload = {5, 6, 7, 8}; +constexpr std::array kSixBytePayload = {1, 2, 3, 4, 5, 6}; +constexpr std::array kMediumPayload1 = {1, 2, 3, 4, 5, 6, 7, 8}; +constexpr std::array kMediumPayload2 = {9, 10, 11, 12, + 13, 14, 15, 16}; +constexpr std::array kLongPayload = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; MATCHER_P3(SctpMessageIs, stream_id, ppid, expected_payload, "") { diff --git a/net/dcsctp/rx/traditional_reassembly_streams.cc b/net/dcsctp/rx/traditional_reassembly_streams.cc index aca565d668..cae1d7dc61 100644 --- a/net/dcsctp/rx/traditional_reassembly_streams.cc +++ b/net/dcsctp/rx/traditional_reassembly_streams.cc @@ -9,23 +9,27 @@ */ #include "net/dcsctp/rx/traditional_reassembly_streams.h" -#include - +#include #include -#include #include #include #include #include +#include #include #include #include "absl/algorithm/container.h" +#include "absl/strings/string_view.h" #include "api/array_view.h" +#include "net/dcsctp/common/internal_types.h" #include "net/dcsctp/common/sequence_numbers.h" #include "net/dcsctp/packet/chunk/forward_tsn_common.h" #include "net/dcsctp/packet/data.h" +#include "net/dcsctp/public/dcsctp_handover_state.h" #include "net/dcsctp/public/dcsctp_message.h" +#include "net/dcsctp/public/types.h" +#include "rtc_base/checks.h" #include "rtc_base/logging.h" namespace dcsctp { diff --git a/net/dcsctp/socket/BUILD.gn b/net/dcsctp/socket/BUILD.gn index f6fbe7f3e3..5c26ea0231 100644 --- a/net/dcsctp/socket/BUILD.gn +++ b/net/dcsctp/socket/BUILD.gn @@ -25,6 +25,7 @@ rtc_library("heartbeat_handler") { ":context", "../../../api:array_view", "../../../api/units:time_delta", + "../../../api/units:timestamp", "../../../rtc_base:checks", "../../../rtc_base:logging", "../packet:bounded_io", diff --git a/net/dcsctp/socket/heartbeat_handler.cc b/net/dcsctp/socket/heartbeat_handler.cc index 5131ee05b2..1b52900d13 100644 --- a/net/dcsctp/socket/heartbeat_handler.cc +++ b/net/dcsctp/socket/heartbeat_handler.cc @@ -9,12 +9,10 @@ */ #include "net/dcsctp/socket/heartbeat_handler.h" -#include - +#include #include #include #include -#include #include #include @@ -22,6 +20,7 @@ #include "absl/strings/string_view.h" #include "api/array_view.h" #include "api/units/time_delta.h" +#include "api/units/timestamp.h" #include "net/dcsctp/packet/bounded_byte_reader.h" #include "net/dcsctp/packet/bounded_byte_writer.h" #include "net/dcsctp/packet/chunk/heartbeat_ack_chunk.h" @@ -33,6 +32,7 @@ #include "net/dcsctp/public/dcsctp_socket.h" #include "net/dcsctp/socket/context.h" #include "net/dcsctp/timer/timer.h" +#include "rtc_base/checks.h" #include "rtc_base/logging.h" namespace dcsctp { diff --git a/p2p/BUILD.gn b/p2p/BUILD.gn index 69d876d957..5dab31046b 100644 --- a/p2p/BUILD.gn +++ b/p2p/BUILD.gn @@ -479,6 +479,7 @@ rtc_library("p2p_transport_channel") { "../api:candidate", "../api:field_trials_view", "../api:ice_transport_interface", + "../api:local_network_access_permission", "../api:rtc_error", "../api:sequence_checker", "../api/task_queue:pending_task_safety_flag", @@ -772,6 +773,7 @@ rtc_library("stun_port") { "../rtc_base/network:received_packet", "../rtc_base/network:sent_packet", "../rtc_base/system:rtc_export", + "../system_wrappers:metrics", "//third_party/abseil-cpp/absl/memory", "//third_party/abseil-cpp/absl/strings:string_view", ] @@ -922,6 +924,7 @@ rtc_library("turn_port") { "../rtc_base/network:received_packet", "../rtc_base/network:sent_packet", "../rtc_base/third_party/sigslot", + "../system_wrappers:metrics", "//third_party/abseil-cpp/absl/algorithm:container", "//third_party/abseil-cpp/absl/memory", "//third_party/abseil-cpp/absl/strings", @@ -1223,7 +1226,9 @@ if (rtc_include_tests) { "../api:field_trials", "../api:field_trials_view", "../api:ice_transport_interface", + "../api:local_network_access_permission", "../api:mock_async_dns_resolver", + "../api:mock_local_network_access_permission", "../api:network_emulation_manager_api", "../api:packet_socket_factory", "../api:rtc_error", diff --git a/p2p/base/async_stun_tcp_socket_unittest.cc b/p2p/base/async_stun_tcp_socket_unittest.cc index bdb8bbb7e7..5e3bd96b4d 100644 --- a/p2p/base/async_stun_tcp_socket_unittest.cc +++ b/p2p/base/async_stun_tcp_socket_unittest.cc @@ -81,7 +81,7 @@ class AsyncStunTCPSocketTest : public ::testing::Test, AsyncStunTCPSocketTest() : vss_(new VirtualSocketServer()), thread_(vss_.get()) {} - virtual void SetUp() { CreateSockets(); } + void SetUp() override { CreateSockets(); } void CreateSockets() { std::unique_ptr server = diff --git a/p2p/base/basic_async_resolver_factory.h b/p2p/base/basic_async_resolver_factory.h index a553f90e66..9a0a4c8d81 100644 --- a/p2p/base/basic_async_resolver_factory.h +++ b/p2p/base/basic_async_resolver_factory.h @@ -25,16 +25,16 @@ class BasicAsyncDnsResolverFactory final public: BasicAsyncDnsResolverFactory() = default; - std::unique_ptr CreateAndResolve( + std::unique_ptr CreateAndResolve( const SocketAddress& addr, absl::AnyInvocable callback) override; - std::unique_ptr CreateAndResolve( + std::unique_ptr CreateAndResolve( const SocketAddress& addr, int family, absl::AnyInvocable callback) override; - std::unique_ptr Create() override; + std::unique_ptr Create() override; }; } // namespace webrtc diff --git a/p2p/base/basic_ice_controller.cc b/p2p/base/basic_ice_controller.cc index cea38d9270..3dce374f64 100644 --- a/p2p/base/basic_ice_controller.cc +++ b/p2p/base/basic_ice_controller.cc @@ -54,9 +54,9 @@ bool IsUdp(const webrtc::Connection* conn) { // TODO(qingsi) Use an enum to replace the following constants for all // comparision results. -static constexpr int a_is_better = 1; -static constexpr int b_is_better = -1; -static constexpr int a_and_b_equal = 0; +constexpr int a_is_better = 1; +constexpr int b_is_better = -1; +constexpr int a_and_b_equal = 0; bool LocalCandidateUsesPreferredNetwork( const webrtc::Connection* conn, @@ -128,7 +128,7 @@ IceControllerInterface::PingResult BasicIceController::SelectConnectionToPing( // active connection has not been pinged enough times, use the weak ping // interval. bool need_more_pings_at_weak_interval = - absl::c_any_of(connections_, [](const webrtc::Connection* conn) { + absl::c_any_of(connections_, [](const Connection* conn) { return conn->active() && conn->num_pings_sent() < MIN_PINGS_AT_WEAK_PING_INTERVAL; }); @@ -180,7 +180,7 @@ const Connection* BasicIceController::FindNextPingableConnection() { }); auto iter = absl::c_min_element( pingable_selectable_connections, - [](const webrtc::Connection* conn1, const webrtc::Connection* conn2) { + [](const Connection* conn1, const Connection* conn2) { return conn1->last_ping_sent() < conn2->last_ping_sent(); }); if (iter != pingable_selectable_connections.end()) { diff --git a/p2p/base/basic_ice_controller.h b/p2p/base/basic_ice_controller.h index 70ebafceb0..e8593dbed0 100644 --- a/p2p/base/basic_ice_controller.h +++ b/p2p/base/basic_ice_controller.h @@ -86,7 +86,7 @@ class BasicIceController : public IceControllerInterface { } int check_receiving_interval() const { - return std::max(webrtc::MIN_CHECK_RECEIVING_INTERVAL, + return std::max(MIN_CHECK_RECEIVING_INTERVAL, config_.receiving_timeout_or_default() / 10); } diff --git a/p2p/base/connection.h b/p2p/base/connection.h index e1b0bb83ae..79cb94a0b6 100644 --- a/p2p/base/connection.h +++ b/p2p/base/connection.h @@ -151,8 +151,7 @@ class RTC_EXPORT Connection : public CandidatePairInterface { // Register as a recipient of received packets. There can only be one. void RegisterReceivedPacketCallback( - absl::AnyInvocable + absl::AnyInvocable received_packet_callback); void DeregisterReceivedPacketCallback(); @@ -160,7 +159,7 @@ class RTC_EXPORT Connection : public CandidatePairInterface { // Called when a packet is received on this connection. void OnReadPacket(const ReceivedIpPacket& packet); - [[deprecated("Pass a webrtc::ReceivedIpPacket")]] void + [[deprecated("Pass a ReceivedIpPacket")]] void OnReadPacket(const char* data, size_t size, int64_t packet_time_us); // Called when the socket is currently able to send. @@ -350,8 +349,8 @@ class RTC_EXPORT Connection : public CandidatePairInterface { void SetStunDictConsumer( std::function( - const webrtc::StunByteStringAttribute*)> goog_delta_consumer, - std::function)> + const StunByteStringAttribute*)> goog_delta_consumer, + std::function)> goog_delta_ack_consumer) { goog_delta_consumer_ = std::move(goog_delta_consumer); goog_delta_ack_consumer_ = std::move(goog_delta_ack_consumer); @@ -513,12 +512,11 @@ class RTC_EXPORT Connection : public CandidatePairInterface { RTC_GUARDED_BY(network_thread_); std::optional( - const webrtc::StunByteStringAttribute*)>> + const StunByteStringAttribute*)>> goog_delta_consumer_; - std::optional< - std::function)>> + std::optional)>> goog_delta_ack_consumer_; - absl::AnyInvocable + absl::AnyInvocable received_packet_callback_; void MaybeAddDtlsPiggybackingAttributes(StunMessage* msg); diff --git a/p2p/base/ice_controller_factory_interface.h b/p2p/base/ice_controller_factory_interface.h index 958d3223da..bcf493da21 100644 --- a/p2p/base/ice_controller_factory_interface.h +++ b/p2p/base/ice_controller_factory_interface.h @@ -26,7 +26,7 @@ namespace webrtc { struct IceControllerFactoryArgs { std::function ice_transport_state_func; std::function ice_role_func; - std::function is_connection_pruned_func; + std::function is_connection_pruned_func; const IceFieldTrials* ice_field_trials; std::string ice_controller_field_trials; }; diff --git a/p2p/base/ice_transport_internal.h b/p2p/base/ice_transport_internal.h index 507660519e..ac6362459e 100644 --- a/p2p/base/ice_transport_internal.h +++ b/p2p/base/ice_transport_internal.h @@ -115,7 +115,7 @@ enum class NominationMode { // is valid RTCError::OK() is returned. RTCError VerifyCandidate(const Candidate& cand); -// Runs through a list of webrtc::Candidate instances and calls VerifyCandidate +// Runs through a list of Candidate instances and calls VerifyCandidate // for each one, stopping on the first error encounted and returning that error // value if so. On success returns RTCError::OK(). RTCError VerifyCandidates(const Candidates& candidates); @@ -343,7 +343,7 @@ class RTC_EXPORT IceTransportInternal : public PacketTransportInternal { void AddGatheringStateCallback( const void* removal_tag, - absl::AnyInvocable callback); + absl::AnyInvocable callback); void RemoveGatheringStateCallback(const void* removal_tag); // Handles sending and receiving of candidates. @@ -351,15 +351,14 @@ class RTC_EXPORT IceTransportInternal : public PacketTransportInternal { SignalCandidateGathered; void SetCandidateErrorCallback( - absl::AnyInvocable - callback) { + absl::AnyInvocable callback) { RTC_DCHECK(!candidate_error_callback_); candidate_error_callback_ = std::move(callback); } void SetCandidatesRemovedCallback( - absl::AnyInvocable + absl::AnyInvocable callback) { RTC_DCHECK(!candidates_removed_callback_); candidates_removed_callback_ = std::move(callback); @@ -374,8 +373,7 @@ class RTC_EXPORT IceTransportInternal : public PacketTransportInternal { sigslot::signal2 SignalRouteChange; void SetCandidatePairChangeCallback( - absl::AnyInvocable - callback) { + absl::AnyInvocable callback) { RTC_DCHECK(!candidate_pair_change_callback_); candidate_pair_change_callback_ = std::move(callback); } @@ -436,14 +434,13 @@ class RTC_EXPORT IceTransportInternal : public PacketTransportInternal { CallbackList gathering_state_callback_list_; - absl::AnyInvocable + absl::AnyInvocable candidate_error_callback_; - absl::AnyInvocable + absl::AnyInvocable candidates_removed_callback_; - absl::AnyInvocable + absl::AnyInvocable candidate_pair_change_callback_; }; diff --git a/p2p/base/p2p_transport_channel.cc b/p2p/base/p2p_transport_channel.cc index ad69f37445..81af5da411 100644 --- a/p2p/base/p2p_transport_channel.cc +++ b/p2p/base/p2p_transport_channel.cc @@ -35,6 +35,7 @@ #include "api/candidate.h" #include "api/field_trials_view.h" #include "api/ice_transport_interface.h" +#include "api/local_network_access_permission.h" #include "api/rtc_error.h" #include "api/sequence_checker.h" #include "api/transport/enums.h" @@ -74,6 +75,7 @@ #include "rtc_base/thread.h" #include "rtc_base/time_utils.h" #include "rtc_base/trace_event.h" +#include "system_wrappers/include/metrics.h" namespace webrtc { namespace { @@ -138,7 +140,8 @@ std::unique_ptr P2PTransportChannel::Create( IceTransportInit init) { return absl::WrapUnique(new P2PTransportChannel( transport_name, component, init.port_allocator(), - init.async_dns_resolver_factory(), nullptr, init.event_log(), + init.async_dns_resolver_factory(), /*owned_dns_resolver_factory=*/nullptr, + init.lna_permission_factory(), init.event_log(), init.ice_controller_factory(), init.active_ice_controller_factory(), init.field_trials())); } @@ -152,6 +155,7 @@ P2PTransportChannel::P2PTransportChannel(absl::string_view transport_name, allocator, /* async_dns_resolver_factory= */ nullptr, /* owned_dns_resolver_factory= */ nullptr, + /* lna_permission_factory= */ nullptr, /* event_log= */ nullptr, /* ice_controller_factory= */ nullptr, /* active_ice_controller_factory= */ nullptr, @@ -165,6 +169,7 @@ P2PTransportChannel::P2PTransportChannel( AsyncDnsResolverFactoryInterface* async_dns_resolver_factory, std::unique_ptr owned_dns_resolver_factory, + LocalNetworkAccessPermissionFactoryInterface* lna_permission_factory, RtcEventLog* event_log, IceControllerFactoryInterface* ice_controller_factory, ActiveIceControllerFactoryInterface* active_ice_controller_factory, @@ -178,6 +183,7 @@ P2PTransportChannel::P2PTransportChannel( ? owned_dns_resolver_factory.get() : async_dns_resolver_factory), owned_dns_resolver_factory_(std::move(owned_dns_resolver_factory)), + lna_permission_factory_(lna_permission_factory), network_thread_(Thread::Current()), incoming_only_(false), error_(0), @@ -196,6 +202,7 @@ P2PTransportChannel::P2PTransportChannel( field_trials_(field_trials) { TRACE_EVENT0("webrtc", "P2PTransportChannel::P2PTransportChannel"); RTC_DCHECK(allocator_ != nullptr); + RTC_DCHECK(!transport_name_.empty()); // Validate IceConfig even for mostly built-in constant default values in case // we change them. RTC_DCHECK(config_.IsValid().ok()); @@ -1235,13 +1242,13 @@ void P2PTransportChannel::AddRemoteCandidate(const Candidate& candidate) { return; } - FinishAddingRemoteCandidate(new_remote_candidate); + CheckLocalNetworkAccessPermission(new_remote_candidate); } P2PTransportChannel::CandidateAndResolver::CandidateAndResolver( const Candidate& candidate, std::unique_ptr&& resolver) - : candidate_(candidate), resolver_(std::move(resolver)) {} + : candidate(candidate), resolver(std::move(resolver)) {} P2PTransportChannel::CandidateAndResolver::~CandidateAndResolver() {} @@ -1250,20 +1257,19 @@ void P2PTransportChannel::OnCandidateResolved( RTC_DCHECK_RUN_ON(network_thread_); auto p = absl::c_find_if(resolvers_, [resolver](const CandidateAndResolver& cr) { - return cr.resolver_.get() == resolver; + return cr.resolver.get() == resolver; }); if (p == resolvers_.end()) { RTC_LOG(LS_ERROR) << "Unexpected AsyncDnsResolver return"; RTC_DCHECK_NOTREACHED(); return; } - Candidate candidate = p->candidate_; + Candidate candidate = p->candidate; AddRemoteCandidateWithResult(candidate, resolver->result()); // Now we can delete the resolver. // TODO(bugs.webrtc.org/12651): Replace the stuff below with // resolvers_.erase(p); - std::unique_ptr to_delete = - std::move(p->resolver_); + std::unique_ptr to_delete = std::move(p->resolver); // Delay the actual deletion of the resolver until the lambda executes. network_thread_->PostTask([to_delete = std::move(to_delete)] {}); resolvers_.erase(p); @@ -1297,12 +1303,79 @@ void P2PTransportChannel::AddRemoteCandidateWithResult( << candidate.address().HostAsSensitiveURIString() << " to " << resolved_address.ipaddr().ToSensitiveString(); candidate.set_address(resolved_address); - FinishAddingRemoteCandidate(candidate); + + CheckLocalNetworkAccessPermission(candidate); +} + +void P2PTransportChannel::CheckLocalNetworkAccessPermission( + const Candidate& candidate) { + RTC_DCHECK_RUN_ON(network_thread_); + if (!lna_permission_factory_) { + RTC_LOG(LS_VERBOSE) << "No LocalNetworkAccessPermissionFactory"; + FinishAddingRemoteCandidate(candidate); + return; + } + + if (!candidate.address().IsPrivateIP() && + !candidate.address().IsLoopbackIP()) { + RTC_LOG(LS_VERBOSE) << "Skipping LNA permission check for public IP " + << candidate.address().ipaddr().ToSensitiveString() + << "."; + FinishAddingRemoteCandidate(candidate); + return; + } + + std::unique_ptr permission_query = + lna_permission_factory_->Create(); + auto permission_query_ptr = permission_query.get(); + permission_queries_.emplace_back(candidate, std::move(permission_query)); + + RTC_LOG(LS_VERBOSE) << "Asynchronously requesting LNA permission." + << candidate.address().HostAsSensitiveURIString(); + permission_query_ptr->RequestPermission( + candidate.address(), + [this, permission_query_ptr](LocalNetworkAccessPermissionStatus status) { + OnLocalNetworkAccessResult(permission_query_ptr, status); + }); +} + +void P2PTransportChannel::OnLocalNetworkAccessResult( + LocalNetworkAccessPermissionInterface* permission_query, + LocalNetworkAccessPermissionStatus status) { + RTC_DCHECK_RUN_ON(network_thread_); + auto p = + absl::c_find_if(permission_queries_, + [permission_query](const CandidateAndPermission& cr) { + return cr.permission_query.get() == permission_query; + }); + + if (p == permission_queries_.end()) { + RTC_LOG(LS_ERROR) << "Unexpected LocalNetworkAccessPermission return"; + RTC_DCHECK_NOTREACHED(); + return; + } + + Candidate candidate = std::move(p->candidate); + permission_queries_.erase(p); + + if (status != LocalNetworkAccessPermissionStatus::kGranted) { + RTC_LOG(LS_INFO) << "LNA Permission denied for " + << candidate.address().HostAsSensitiveURIString() << "."; + return; + } + + FinishAddingRemoteCandidate(std::move(candidate)); } void P2PTransportChannel::FinishAddingRemoteCandidate( const Candidate& new_remote_candidate) { RTC_DCHECK_RUN_ON(network_thread_); + + RTC_HISTOGRAM_ENUMERATION( + "WebRTC.PeerConnection.CandidateAddressType", + static_cast(new_remote_candidate.address().GetIPAddressType()), + static_cast(IPAddressType::kMaxValue)); + // If this candidate matches what was thought to be a peer reflexive // candidate, we need to update the candidate priority/etc. for (Connection* conn : connections_) { @@ -2324,4 +2397,9 @@ void P2PTransportChannel::ResetDtlsStunPiggybackCallbacks() { } } +size_t P2PTransportChannel::PermissionQueriesOutstandingForTesting() const { + RTC_DCHECK_RUN_ON(network_thread_); + return permission_queries_.size(); +} + } // namespace webrtc diff --git a/p2p/base/p2p_transport_channel.h b/p2p/base/p2p_transport_channel.h index a42d2916c5..479c2e50a1 100644 --- a/p2p/base/p2p_transport_channel.h +++ b/p2p/base/p2p_transport_channel.h @@ -35,6 +35,7 @@ #include "api/async_dns_resolver.h" #include "api/candidate.h" #include "api/ice_transport_interface.h" +#include "api/local_network_access_permission.h" #include "api/rtc_error.h" #include "api/sequence_checker.h" #include "api/transport/enums.h" @@ -129,9 +130,6 @@ class RTC_EXPORT P2PTransportChannel : public IceTransportInternal, void SetIceParameters(const IceParameters& ice_params) override; void SetRemoteIceParameters(const IceParameters& ice_params) override; void SetRemoteIceMode(IceMode mode) override; - // TODO(deadbeef): Deprecated. Remove when Chromium's - // IceTransportChannel does not depend on this. - void Connect() {} void MaybeStartGathering() override; IceGatheringState gathering_state() const override; void ResolveHostnameCandidate(const Candidate& candidate); @@ -266,7 +264,27 @@ class RTC_EXPORT P2PTransportChannel : public IceTransportInternal, : &remote_ice_parameters_.back(); } + // Returns the number of outstanding Local Network Access permission queries. + size_t PermissionQueriesOutstandingForTesting() const; + private: + struct CandidateAndResolver final { + CandidateAndResolver(const Candidate& candidate, + std::unique_ptr&& resolver); + ~CandidateAndResolver(); + // Moveable, but not copyable. + CandidateAndResolver(CandidateAndResolver&&) = default; + CandidateAndResolver& operator=(CandidateAndResolver&&) = default; + + Candidate candidate; + std::unique_ptr resolver; + }; + + struct CandidateAndPermission final { + Candidate candidate; + std::unique_ptr permission_query; + }; + P2PTransportChannel( absl::string_view transport_name, int component, @@ -277,6 +295,7 @@ class RTC_EXPORT P2PTransportChannel : public IceTransportInternal, // on release, this pointer is set. std::unique_ptr owned_dns_resolver_factory, + LocalNetworkAccessPermissionFactoryInterface* lna_permission_factory, RtcEventLog* event_log, IceControllerFactoryInterface* ice_controller_factory, ActiveIceControllerFactoryInterface* active_ice_controller_factory, @@ -412,6 +431,19 @@ class RTC_EXPORT P2PTransportChannel : public IceTransportInternal, void ParseFieldTrials(const FieldTrialsView* field_trials); + void FinishAddingRemoteCandidate(const Candidate& new_remote_candidate); + void OnCandidateResolved(AsyncDnsResolverInterface* resolver); + void CheckLocalNetworkAccessPermission(const Candidate& new_remote_candidate); + void OnLocalNetworkAccessResult( + LocalNetworkAccessPermissionInterface* permission_query, + LocalNetworkAccessPermissionStatus status); + void AddRemoteCandidateWithResult(Candidate candidate, + const AsyncDnsResolverResult& result); + + std::unique_ptr GoogDeltaReceived( + const StunByteStringAttribute*); + void GoogDeltaAckReceived(RTCErrorOr); + std::string transport_name_ RTC_GUARDED_BY(network_thread_); int component_ RTC_GUARDED_BY(network_thread_); PortAllocator* allocator_ RTC_GUARDED_BY(network_thread_); @@ -419,6 +451,8 @@ class RTC_EXPORT P2PTransportChannel : public IceTransportInternal, RTC_GUARDED_BY(network_thread_); const std::unique_ptr owned_dns_resolver_factory_; + LocalNetworkAccessPermissionFactoryInterface* const lna_permission_factory_ + RTC_GUARDED_BY(network_thread_); Thread* const network_thread_; bool incoming_only_ RTC_GUARDED_BY(network_thread_); int error_ RTC_GUARDED_BY(network_thread_); @@ -475,26 +509,10 @@ class RTC_EXPORT P2PTransportChannel : public IceTransportInternal, std::unique_ptr ice_controller_ RTC_GUARDED_BY(network_thread_); - struct CandidateAndResolver final { - CandidateAndResolver(const Candidate& candidate, - std::unique_ptr&& resolver); - ~CandidateAndResolver(); - // Moveable, but not copyable. - CandidateAndResolver(CandidateAndResolver&&) = default; - CandidateAndResolver& operator=(CandidateAndResolver&&) = default; - - Candidate candidate_; - std::unique_ptr resolver_; - }; std::vector resolvers_ RTC_GUARDED_BY(network_thread_); - void FinishAddingRemoteCandidate(const Candidate& new_remote_candidate); - void OnCandidateResolved(AsyncDnsResolverInterface* resolver); - void AddRemoteCandidateWithResult(Candidate candidate, - const AsyncDnsResolverResult& result); - - std::unique_ptr GoogDeltaReceived( - const StunByteStringAttribute*); - void GoogDeltaAckReceived(RTCErrorOr); + // Stores pending Local Area Network permission queries. + std::vector permission_queries_ + RTC_GUARDED_BY(network_thread_); // Bytes/packets sent/received on this channel. uint64_t bytes_sent_ = 0; @@ -506,7 +524,7 @@ class RTC_EXPORT P2PTransportChannel : public IceTransportInternal, uint32_t selected_candidate_pair_changes_ = 0; // When was last data received on a existing connection, - // from connection->last_data_received() that uses webrtc::TimeMillis(). + // from connection->last_data_received() that uses TimeMillis(). int64_t last_data_received_ms_ = 0; // Parsed field trials. diff --git a/p2p/base/p2p_transport_channel_unittest.cc b/p2p/base/p2p_transport_channel_unittest.cc index cceb4cc33c..5a207730db 100644 --- a/p2p/base/p2p_transport_channel_unittest.cc +++ b/p2p/base/p2p_transport_channel_unittest.cc @@ -31,10 +31,12 @@ #include "api/environment/environment_factory.h" #include "api/field_trials.h" #include "api/ice_transport_interface.h" +#include "api/local_network_access_permission.h" #include "api/packet_socket_factory.h" #include "api/scoped_refptr.h" #include "api/task_queue/pending_task_safety_flag.h" #include "api/test/mock_async_dns_resolver.h" +#include "api/test/mock_local_network_access_permission.h" #include "api/test/rtc_error_matchers.h" #include "api/transport/enums.h" #include "api/transport/stun.h" @@ -126,48 +128,46 @@ using ::webrtc::SocketAddress; // Default timeout for tests in this file. // Should be large enough for slow buildbots to run the tests reliably. -static const int kDefaultTimeout = 10000; -static const int kMediumTimeout = 3000; -static const int kShortTimeout = 1000; - -static const int kOnlyLocalPorts = webrtc::PORTALLOCATOR_DISABLE_STUN | - webrtc::PORTALLOCATOR_DISABLE_RELAY | - webrtc::PORTALLOCATOR_DISABLE_TCP; -static const int LOW_RTT = 20; +const int kDefaultTimeout = 10000; +const int kMediumTimeout = 3000; +const int kShortTimeout = 1000; + +const int kOnlyLocalPorts = webrtc::PORTALLOCATOR_DISABLE_STUN | + webrtc::PORTALLOCATOR_DISABLE_RELAY | + webrtc::PORTALLOCATOR_DISABLE_TCP; +const int LOW_RTT = 20; // Addresses on the public internet. -static const SocketAddress kPublicAddrs[2] = {SocketAddress("11.11.11.11", 0), - SocketAddress("22.22.22.22", 0)}; +const SocketAddress kPublicAddrs[2] = {SocketAddress("11.11.11.11", 0), + SocketAddress("22.22.22.22", 0)}; // IPv6 Addresses on the public internet. -static const SocketAddress kIPv6PublicAddrs[2] = { +const SocketAddress kIPv6PublicAddrs[2] = { SocketAddress("2400:4030:1:2c00:be30:abcd:efab:cdef", 0), SocketAddress("2600:0:1000:1b03:2e41:38ff:fea6:f2a4", 0)}; // For configuring multihomed clients. -static const SocketAddress kAlternateAddrs[2] = { - SocketAddress("101.101.101.101", 0), SocketAddress("202.202.202.202", 0)}; -static const SocketAddress kIPv6AlternateAddrs[2] = { +const SocketAddress kAlternateAddrs[2] = {SocketAddress("101.101.101.101", 0), + SocketAddress("202.202.202.202", 0)}; +const SocketAddress kIPv6AlternateAddrs[2] = { SocketAddress("2401:4030:1:2c00:be30:abcd:efab:cdef", 0), SocketAddress("2601:0:1000:1b03:2e41:38ff:fea6:f2a4", 0)}; // Internal addresses for NAT boxes. -static const SocketAddress kNatAddrs[2] = {SocketAddress("192.168.1.1", 0), - SocketAddress("192.168.2.1", 0)}; +const SocketAddress kNatAddrs[2] = {SocketAddress("192.168.1.1", 0), + SocketAddress("192.168.2.1", 0)}; // Private addresses inside the NAT private networks. -static const SocketAddress kPrivateAddrs[2] = { - SocketAddress("192.168.1.11", 0), SocketAddress("192.168.2.22", 0)}; +const SocketAddress kPrivateAddrs[2] = {SocketAddress("192.168.1.11", 0), + SocketAddress("192.168.2.22", 0)}; // For cascaded NATs, the internal addresses of the inner NAT boxes. -static const SocketAddress kCascadedNatAddrs[2] = { - SocketAddress("192.168.10.1", 0), SocketAddress("192.168.20.1", 0)}; +const SocketAddress kCascadedNatAddrs[2] = {SocketAddress("192.168.10.1", 0), + SocketAddress("192.168.20.1", 0)}; // For cascaded NATs, private addresses inside the inner private networks. -static const SocketAddress kCascadedPrivateAddrs[2] = { +const SocketAddress kCascadedPrivateAddrs[2] = { SocketAddress("192.168.10.11", 0), SocketAddress("192.168.20.22", 0)}; // The address of the public STUN server. -static const SocketAddress kStunAddr("99.99.99.1", webrtc::STUN_SERVER_PORT); +const SocketAddress kStunAddr("99.99.99.1", webrtc::STUN_SERVER_PORT); // The addresses for the public turn server. -static const SocketAddress kTurnUdpIntAddr("99.99.99.3", - webrtc::STUN_SERVER_PORT); -static const SocketAddress kTurnTcpIntAddr("99.99.99.4", - webrtc::STUN_SERVER_PORT + 1); -static const SocketAddress kTurnUdpExtAddr("99.99.99.5", 0); -static const webrtc::RelayCredentials kRelayCredentials("test", "test"); +const SocketAddress kTurnUdpIntAddr("99.99.99.3", webrtc::STUN_SERVER_PORT); +const SocketAddress kTurnTcpIntAddr("99.99.99.4", webrtc::STUN_SERVER_PORT + 1); +const SocketAddress kTurnUdpExtAddr("99.99.99.5", 0); +const webrtc::RelayCredentials kRelayCredentials("test", "test"); // Based on ICE_UFRAG_LENGTH const char* kIceUfrag[4] = {"UF00", "UF01", "UF02", "UF03"}; @@ -282,6 +282,32 @@ class ResolverFactoryFixture : public webrtc::MockAsyncDnsResolverFactory { absl::AnyInvocable saved_callback_; }; +class PermissionFactoryFixture + : public webrtc::MockLocalNetworkAccessPermissionFactory { + public: + explicit PermissionFactoryFixture( + webrtc::LocalNetworkAccessPermissionStatus result) { + EXPECT_CALL(*this, Create()).WillRepeatedly([result]() { + auto mock_lna_permission = + std::make_unique(); + + EXPECT_CALL(*mock_lna_permission, RequestPermission(_, _)) + .WillRepeatedly( + [result]( + const SocketAddress& /* addr */, + absl::AnyInvocable callback) { + webrtc::Thread::Current()->PostTask( + [callback = std::move(callback), result]() mutable { + callback(result); + }); + }); + + return mock_lna_permission; + }); + } +}; + bool HasLocalAddress(const webrtc::CandidatePairInterface* pair, const SocketAddress& address) { return pair->local_candidate().address().EqualIPs(address); @@ -324,10 +350,10 @@ class P2PTransportChannelTestBase : public ::testing::Test, stun_server_(TestStunServer::Create(ss_.get(), kStunAddr, main_)), turn_server_(&main_, ss_.get(), kTurnUdpIntAddr, kTurnUdpExtAddr), force_relay_(false) { - ep1_.role_ = webrtc::ICEROLE_CONTROLLING; - ep2_.role_ = webrtc::ICEROLE_CONTROLLED; + ep1_.role_ = ICEROLE_CONTROLLING; + ep2_.role_ = ICEROLE_CONTROLLED; - webrtc::metrics::Reset(); + metrics::Reset(); } void CreatePortAllocators(const Environment& env) { @@ -400,7 +426,7 @@ class P2PTransportChannelTestBase : public ::testing::Test, struct Endpoint : public sigslot::has_slots<> { Endpoint() - : role_(webrtc::ICEROLE_UNKNOWN), + : role_(ICEROLE_UNKNOWN), tiebreaker_(0), role_conflict_(false), save_candidates_(false) {} @@ -593,7 +619,7 @@ class P2PTransportChannelTestBase : public ::testing::Test, } void RemoveAddress(int endpoint, const SocketAddress& addr) { GetEndpoint(endpoint)->network_manager_.RemoveInterface(addr); - fw()->AddRule(false, webrtc::FP_ANY, webrtc::FD_ANY, addr); + fw()->AddRule(false, FP_ANY, FD_ANY, addr); } void SetAllocatorFlags(int endpoint, int flags) { GetAllocator(endpoint)->set_flags(flags); @@ -710,19 +736,18 @@ class P2PTransportChannelTestBase : public ::testing::Test, void Test(const Environment& env, const Result& expected) { ScopedFakeClock clock; - int64_t connect_start = webrtc::TimeMillis(); + int64_t connect_start = TimeMillis(); int64_t connect_time; // Create the channels and wait for them to connect. CreateChannels(env); - EXPECT_THAT( - webrtc::WaitUntil( - [&] { return CheckConnected(ep1_ch1(), ep2_ch1()); }, IsTrue(), - {.timeout = - TimeDelta::Millis(expected.connect_wait + kShortTimeout), - .clock = &clock}), - webrtc::IsRtcOk()); - connect_time = webrtc::TimeMillis() - connect_start; + EXPECT_THAT(WaitUntil([&] { return CheckConnected(ep1_ch1(), ep2_ch1()); }, + IsTrue(), + {.timeout = TimeDelta::Millis(expected.connect_wait + + kShortTimeout), + .clock = &clock}), + IsRtcOk()); + connect_time = TimeMillis() - connect_start; if (connect_time < expected.connect_wait) { RTC_LOG(LS_INFO) << "Connect time: " << connect_time << " ms"; } else { @@ -733,25 +758,25 @@ class P2PTransportChannelTestBase : public ::testing::Test, // Allow a few turns of the crank for the selected connections to emerge. // This may take up to 2 seconds. if (ep1_ch1()->selected_connection() && ep2_ch1()->selected_connection()) { - int64_t converge_start = webrtc::TimeMillis(); + int64_t converge_start = TimeMillis(); int64_t converge_time; // Verifying local and remote channel selected connection information. // This is done only for the RFC 5245 as controlled agent will use // USE-CANDIDATE from controlling (ep1) agent. We can easily predict from // EP1 result matrix. EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return CheckCandidate1(expected) && CheckCandidate2(expected); }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); // Also do EXPECT_EQ on each part so that failures are more verbose. ExpectCandidate1(expected); ExpectCandidate2(expected); - converge_time = webrtc::TimeMillis() - converge_start; + converge_time = TimeMillis() - converge_start; int64_t converge_wait = 2000; if (converge_time < converge_wait) { RTC_LOG(LS_INFO) << "Converge time: " << converge_time << " ms"; @@ -773,27 +798,27 @@ class P2PTransportChannelTestBase : public ::testing::Test, int len = static_cast(strlen(data)); // local_channel1 <==> remote_channel1 EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return SendData(ep1_ch1(), data, len); }, Eq(len), {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &*clock}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return CheckDataOnChannel(ep2_ch1(), data, len); }, IsTrue(), {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &*clock}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return SendData(ep2_ch1(), data, len); }, Eq(len), {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &*clock}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return CheckDataOnChannel(ep1_ch1(), data, len); }, IsTrue(), {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &*clock}), - webrtc::IsRtcOk()); + IsRtcOk()); } } @@ -807,10 +832,10 @@ class P2PTransportChannelTestBase : public ::testing::Test, ep1_ch1()->SetRemoteIceParameters(kIceParams[1]); ep2_ch1()->SetRemoteIceParameters(kIceParams[0]); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return CheckConnected(ep1_ch1(), ep2_ch1()); }, IsTrue(), {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); const Candidate* old_local_candidate1 = LocalCandidate(ep1_ch1()); const Candidate* old_local_candidate2 = LocalCandidate(ep2_ch1()); @@ -826,29 +851,29 @@ class P2PTransportChannelTestBase : public ::testing::Test, ep2_ch1()->MaybeStartGathering(); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return LocalCandidate(ep1_ch1())->generation(); }, Ne(old_local_candidate1->generation()), {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return LocalCandidate(ep2_ch1())->generation(); }, Ne(old_local_candidate2->generation()), {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return RemoteCandidate(ep1_ch1())->generation(); }, Ne(old_remote_candidate1->generation()), {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return RemoteCandidate(ep2_ch1())->generation(); }, Ne(old_remote_candidate2->generation()), {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_EQ(1u, RemoteCandidate(ep2_ch1())->generation()); EXPECT_EQ(1u, RemoteCandidate(ep1_ch1())->generation()); } @@ -914,12 +939,12 @@ class P2PTransportChannelTestBase : public ::testing::Test, // Tcp candidate verification has to be done when they are generated. void VerifySavedTcpCandidates(int endpoint, absl::string_view tcptype) { for (auto& data : GetEndpoint(endpoint)->saved_candidates_) { - EXPECT_EQ(data.candidate.protocol(), webrtc::TCP_PROTOCOL_NAME); + EXPECT_EQ(data.candidate.protocol(), TCP_PROTOCOL_NAME); EXPECT_EQ(data.candidate.tcptype(), tcptype); - if (data.candidate.tcptype() == webrtc::TCPTYPE_ACTIVE_STR) { - EXPECT_EQ(data.candidate.address().port(), webrtc::DISCARD_PORT); - } else if (data.candidate.tcptype() == webrtc::TCPTYPE_PASSIVE_STR) { - EXPECT_NE(data.candidate.address().port(), webrtc::DISCARD_PORT); + if (data.candidate.tcptype() == TCPTYPE_ACTIVE_STR) { + EXPECT_EQ(data.candidate.address().port(), DISCARD_PORT); + } else if (data.candidate.tcptype() == TCPTYPE_PASSIVE_STR) { + EXPECT_NE(data.candidate.address().port(), DISCARD_PORT); } else { FAIL() << "Unknown tcptype: " << data.candidate.tcptype(); } @@ -965,10 +990,9 @@ class P2PTransportChannelTestBase : public ::testing::Test, void OnRoleConflict(IceTransportInternal* channel) { GetEndpoint(channel)->OnRoleConflict(true); - IceRole new_role = - GetEndpoint(channel)->ice_role() == webrtc::ICEROLE_CONTROLLING - ? webrtc::ICEROLE_CONTROLLED - : webrtc::ICEROLE_CONTROLLING; + IceRole new_role = GetEndpoint(channel)->ice_role() == ICEROLE_CONTROLLING + ? ICEROLE_CONTROLLED + : ICEROLE_CONTROLLING; channel->SetIceRole(new_role); } @@ -1158,10 +1182,10 @@ class P2PTransportChannelTest : public P2PTransportChannelTestBase { CreatePortAllocators(env); ConfigureEndpoint(0, config1); SetAllocatorFlags(0, allocator_flags1); - SetAllocationStepDelay(0, webrtc::kMinimumStepDelay); + SetAllocationStepDelay(0, kMinimumStepDelay); ConfigureEndpoint(1, config2); SetAllocatorFlags(1, allocator_flags2); - SetAllocationStepDelay(1, webrtc::kMinimumStepDelay); + SetAllocationStepDelay(1, kMinimumStepDelay); set_remote_ice_parameter_source(FROM_SETICEPARAMETERS); } @@ -1187,10 +1211,11 @@ class P2PTransportChannelTest : public P2PTransportChannelTestBase { // Add a two cascaded NATs of the desired types nat() ->AddTranslator(kPublicAddrs[endpoint], kNatAddrs[endpoint], - (config == NAT_DOUBLE_CONE) ? webrtc::NAT_OPEN_CONE - : webrtc::NAT_SYMMETRIC) + (config == Config::NAT_DOUBLE_CONE) + ? NATType::NAT_OPEN_CONE + : NATType::NAT_SYMMETRIC) ->AddTranslator(kPrivateAddrs[endpoint], - kCascadedNatAddrs[endpoint], webrtc::NAT_OPEN_CONE) + kCascadedNatAddrs[endpoint], NAT_OPEN_CONE) ->AddClient(kCascadedPrivateAddrs[endpoint]); break; case BLOCK_UDP: @@ -1198,20 +1223,17 @@ class P2PTransportChannelTest : public P2PTransportChannelTestBase { case BLOCK_ALL_BUT_OUTGOING_HTTP: AddAddress(endpoint, kPublicAddrs[endpoint]); // Block all UDP - fw()->AddRule(false, webrtc::FP_UDP, webrtc::FD_ANY, - kPublicAddrs[endpoint]); + fw()->AddRule(false, FP_UDP, FD_ANY, kPublicAddrs[endpoint]); if (config == BLOCK_UDP_AND_INCOMING_TCP) { // Block TCP inbound to the endpoint - fw()->AddRule(false, webrtc::FP_TCP, SocketAddress(), - kPublicAddrs[endpoint]); + fw()->AddRule(false, FP_TCP, SocketAddress(), kPublicAddrs[endpoint]); } else if (config == BLOCK_ALL_BUT_OUTGOING_HTTP) { // Block all TCP to/from the endpoint except 80/443 out - fw()->AddRule(true, webrtc::FP_TCP, kPublicAddrs[endpoint], + fw()->AddRule(true, FP_TCP, kPublicAddrs[endpoint], SocketAddress(IPAddress(INADDR_ANY), 80)); - fw()->AddRule(true, webrtc::FP_TCP, kPublicAddrs[endpoint], + fw()->AddRule(true, FP_TCP, kPublicAddrs[endpoint], SocketAddress(IPAddress(INADDR_ANY), 443)); - fw()->AddRule(false, webrtc::FP_TCP, webrtc::FD_ANY, - kPublicAddrs[endpoint]); + fw()->AddRule(false, FP_TCP, FD_ANY, kPublicAddrs[endpoint]); } break; default: @@ -1326,8 +1348,8 @@ INSTANTIATE_TEST_SUITE_P( // Standard Ice protocol is used. TEST_F(P2PTransportChannelTest, HandleUfragPwdChange) { const Environment env = CreateEnvironment(); - ConfigureEndpoints(env, OPEN, OPEN, webrtc::kDefaultPortAllocatorFlags, - webrtc::kDefaultPortAllocatorFlags); + ConfigureEndpoints(env, OPEN, OPEN, kDefaultPortAllocatorFlags, + kDefaultPortAllocatorFlags); CreateChannels(env); TestHandleIceUfragPasswordChanged(); DestroyChannels(); @@ -1338,8 +1360,7 @@ TEST_F(P2PTransportChannelTest, HandleUfragPwdChange) { TEST_F(P2PTransportChannelTest, HandleUfragPwdChangeSymmetricNat) { const Environment env = CreateEnvironment(); ConfigureEndpoints(env, NAT_SYMMETRIC, NAT_SYMMETRIC, - webrtc::kDefaultPortAllocatorFlags, - webrtc::kDefaultPortAllocatorFlags); + kDefaultPortAllocatorFlags, kDefaultPortAllocatorFlags); CreateChannels(env); TestHandleIceUfragPasswordChanged(); DestroyChannels(); @@ -1349,18 +1370,18 @@ TEST_F(P2PTransportChannelTest, HandleUfragPwdChangeSymmetricNat) { TEST_F(P2PTransportChannelTest, GetStats) { ScopedFakeClock clock; const Environment env = CreateEnvironment(); - ConfigureEndpoints(env, OPEN, OPEN, webrtc::kDefaultPortAllocatorFlags, - webrtc::kDefaultPortAllocatorFlags); + ConfigureEndpoints(env, OPEN, OPEN, kDefaultPortAllocatorFlags, + kDefaultPortAllocatorFlags); CreateChannels(env); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return ep1_ch1()->receiving() && ep1_ch1()->writable() && ep2_ch1()->receiving() && ep2_ch1()->writable(); }, IsTrue(), {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); // Sends and receives 10 packets. TestSendRecv(&clock); @@ -1405,23 +1426,23 @@ TEST_F(P2PTransportChannelTest, GetStatsSwitchConnection) { ScopedFakeClock clock; const Environment env = CreateEnvironment(); IceConfig continual_gathering_config = - CreateIceConfig(1000, webrtc::GATHER_CONTINUALLY); + CreateIceConfig(1000, GATHER_CONTINUALLY); - ConfigureEndpoints(env, OPEN, OPEN, webrtc::kDefaultPortAllocatorFlags, - webrtc::kDefaultPortAllocatorFlags); + ConfigureEndpoints(env, OPEN, OPEN, kDefaultPortAllocatorFlags, + kDefaultPortAllocatorFlags); AddAddress(0, kAlternateAddrs[1], "rmnet0", ADAPTER_TYPE_CELLULAR); CreateChannels(env, continual_gathering_config, continual_gathering_config); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return ep1_ch1()->receiving() && ep1_ch1()->writable() && ep2_ch1()->receiving() && ep2_ch1()->writable(); }, IsTrue(), {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); // Sends and receives 10 packets. TestSendRecv(&clock); @@ -1453,10 +1474,10 @@ TEST_F(P2PTransportChannelTest, GetStatsSwitchConnection) { const_cast(old_selected_connection)); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return ep1_ch1()->selected_connection(); }, Ne(nullptr), {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); // Sends and receives 10 packets. TestSendRecv(&clock); @@ -1490,27 +1511,27 @@ TEST_F(P2PTransportChannelTest, // ep1 gathers continually but ep2 does not. IceConfig continual_gathering_config = - CreateIceConfig(1000, webrtc::GATHER_CONTINUALLY); + CreateIceConfig(1000, GATHER_CONTINUALLY); IceConfig default_config; CreateChannels(env, continual_gathering_config, default_config); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return CheckConnected(ep1_ch1(), ep2_ch1()); }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); // Adding address in ep1 will trigger continual gathering. AddAddress(0, kAlternateAddrs[0]); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return GetEndpoint(0)->GetIceRegatheringCountForReason( IceRegatheringReason::NETWORK_CHANGE); }, Eq(1), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); ep2_ch1()->SetIceParameters(kIceParams[3]); ep2_ch1()->SetRemoteIceParameters(kIceParams[2]); @@ -1534,19 +1555,19 @@ TEST_F(P2PTransportChannelTest, ConfigureEndpoints(env, OPEN, OPEN, kOnlyLocalPorts, kOnlyLocalPorts); // ep1 gathers continually but ep2 does not. - IceConfig config1 = CreateIceConfig(1000, webrtc::GATHER_CONTINUALLY); + IceConfig config1 = CreateIceConfig(1000, GATHER_CONTINUALLY); config1.regather_on_failed_networks_interval = 2000; IceConfig config2; config2.regather_on_failed_networks_interval = 2000; CreateChannels(env, config1, config2); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return CheckConnected(ep1_ch1(), ep2_ch1()); }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); - fw()->AddRule(false, webrtc::FP_ANY, webrtc::FD_ANY, kPublicAddrs[0]); + fw()->AddRule(false, FP_ANY, FD_ANY, kPublicAddrs[0]); // Timeout value such that all connections are deleted. const int kNetworkFailureTimeout = 35000; SIMULATED_WAIT(false, kNetworkFailureTimeout, clock); @@ -1562,8 +1583,8 @@ TEST_F(P2PTransportChannelTest, // when the signaling is slow. TEST_F(P2PTransportChannelTest, PeerReflexiveCandidateBeforeSignaling) { const Environment env = CreateEnvironment(); - ConfigureEndpoints(env, OPEN, OPEN, webrtc::kDefaultPortAllocatorFlags, - webrtc::kDefaultPortAllocatorFlags); + ConfigureEndpoints(env, OPEN, OPEN, kDefaultPortAllocatorFlags, + kDefaultPortAllocatorFlags); // Emulate no remote parameters coming in. set_remote_ice_parameter_source(FROM_CANDIDATE); CreateChannels(env); @@ -1576,10 +1597,10 @@ TEST_F(P2PTransportChannelTest, PeerReflexiveCandidateBeforeSignaling) { // Wait until the callee becomes writable to make sure that a ping request is // received by the caller before their remote ICE credentials are set. - ASSERT_THAT(webrtc::WaitUntil( - [&] { return ep2_ch1()->selected_connection(); }, Ne(nullptr), - {.timeout = TimeDelta::Millis(kMediumTimeout)}), - webrtc::IsRtcOk()); + ASSERT_THAT( + WaitUntil([&] { return ep2_ch1()->selected_connection(); }, Ne(nullptr), + {.timeout = TimeDelta::Millis(kMediumTimeout)}), + IsRtcOk()); // Add two sets of remote ICE credentials, so that the ones used by the // candidate will be generation 1 instead of 0. ep1_ch1()->SetRemoteIceParameters(kIceParams[3]); @@ -1587,13 +1608,13 @@ TEST_F(P2PTransportChannelTest, PeerReflexiveCandidateBeforeSignaling) { // The caller should have the selected connection connected to the peer // reflexive candidate. const Connection* selected_connection = nullptr; - ASSERT_THAT(webrtc::WaitUntil( + ASSERT_THAT(WaitUntil( [&] { return selected_connection = ep1_ch1()->selected_connection(); }, Ne(nullptr), {.timeout = TimeDelta::Millis(kMediumTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_TRUE(selected_connection->remote_candidate().is_prflx()); EXPECT_EQ(kIceUfrag[1], selected_connection->remote_candidate().username()); EXPECT_EQ(kIcePwd[1], selected_connection->remote_candidate().password()); @@ -1601,7 +1622,7 @@ TEST_F(P2PTransportChannelTest, PeerReflexiveCandidateBeforeSignaling) { ResumeCandidates(1); // Verify ep1's selected connection is updated to use the 'local' candidate. - EXPECT_THAT(webrtc::WaitUntil( + EXPECT_THAT(WaitUntil( [&] { return ep1_ch1() ->selected_connection() @@ -1609,7 +1630,7 @@ TEST_F(P2PTransportChannelTest, PeerReflexiveCandidateBeforeSignaling) { .is_local(); }, IsTrue(), {.timeout = TimeDelta::Millis(kMediumTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_EQ(selected_connection, ep1_ch1()->selected_connection()); DestroyChannels(); } @@ -1631,15 +1652,15 @@ TEST_F(P2PTransportChannelTest, PeerReflexiveRemoteCandidateIsSanitized) { // candidate. PauseCandidates(1); - ASSERT_THAT(webrtc::WaitUntil( - [&] { return ep2_ch1()->selected_connection(); }, Ne(nullptr), - {.timeout = TimeDelta::Millis(kMediumTimeout)}), - webrtc::IsRtcOk()); + ASSERT_THAT( + WaitUntil([&] { return ep2_ch1()->selected_connection(); }, Ne(nullptr), + {.timeout = TimeDelta::Millis(kMediumTimeout)}), + IsRtcOk()); ep1_ch1()->SetRemoteIceParameters(kIceParams[1]); - ASSERT_THAT(webrtc::WaitUntil( - [&] { return ep1_ch1()->selected_connection(); }, Ne(nullptr), - {.timeout = TimeDelta::Millis(kMediumTimeout)}), - webrtc::IsRtcOk()); + ASSERT_THAT( + WaitUntil([&] { return ep1_ch1()->selected_connection(); }, Ne(nullptr), + {.timeout = TimeDelta::Millis(kMediumTimeout)}), + IsRtcOk()); // Check the selected candidate pair. auto pair_ep1 = ep1_ch1()->GetSelectedCandidatePair(); @@ -1660,7 +1681,7 @@ TEST_F(P2PTransportChannelTest, PeerReflexiveRemoteCandidateIsSanitized) { // Let ep1 receive the remote candidate to update its type from prflx to host. ResumeCandidates(1); - ASSERT_THAT(webrtc::WaitUntil( + ASSERT_THAT(WaitUntil( [&] { return ep1_ch1()->selected_connection() != nullptr && ep1_ch1() @@ -1669,7 +1690,7 @@ TEST_F(P2PTransportChannelTest, PeerReflexiveRemoteCandidateIsSanitized) { .is_local(); }, IsTrue(), {.timeout = TimeDelta::Millis(kMediumTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); // We should be able to reveal the address after it is learnt via // AddIceCandidate. @@ -1696,9 +1717,8 @@ TEST_F(P2PTransportChannelTest, PeerReflexiveRemoteCandidateIsSanitized) { // when the signaling is slow and the end points are behind NAT. TEST_F(P2PTransportChannelTest, PeerReflexiveCandidateBeforeSignalingWithNAT) { const Environment env = CreateEnvironment(); - ConfigureEndpoints(env, OPEN, NAT_SYMMETRIC, - webrtc::kDefaultPortAllocatorFlags, - webrtc::kDefaultPortAllocatorFlags); + ConfigureEndpoints(env, OPEN, NAT_SYMMETRIC, kDefaultPortAllocatorFlags, + kDefaultPortAllocatorFlags); // Emulate no remote parameters coming in. set_remote_ice_parameter_source(FROM_CANDIDATE); CreateChannels(env); @@ -1710,10 +1730,10 @@ TEST_F(P2PTransportChannelTest, PeerReflexiveCandidateBeforeSignalingWithNAT) { // Wait until the callee becomes writable to make sure that a ping request is // received by the caller before their remote ICE credentials are set. - ASSERT_THAT(webrtc::WaitUntil( - [&] { return ep2_ch1()->selected_connection(); }, Ne(nullptr), - {.timeout = TimeDelta::Millis(kMediumTimeout)}), - webrtc::IsRtcOk()); + ASSERT_THAT( + WaitUntil([&] { return ep2_ch1()->selected_connection(); }, Ne(nullptr), + {.timeout = TimeDelta::Millis(kMediumTimeout)}), + IsRtcOk()); // Add two sets of remote ICE credentials, so that the ones used by the // candidate will be generation 1 instead of 0. ep1_ch1()->SetRemoteIceParameters(kIceParams[3]); @@ -1722,13 +1742,13 @@ TEST_F(P2PTransportChannelTest, PeerReflexiveCandidateBeforeSignalingWithNAT) { // The caller's selected connection should be connected to the peer reflexive // candidate. const Connection* selected_connection = nullptr; - ASSERT_THAT(webrtc::WaitUntil( + ASSERT_THAT(WaitUntil( [&] { return selected_connection = ep1_ch1()->selected_connection(); }, Ne(nullptr), {.timeout = TimeDelta::Millis(kMediumTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_TRUE(selected_connection->remote_candidate().is_prflx()); EXPECT_EQ(kIceUfrag[1], selected_connection->remote_candidate().username()); EXPECT_EQ(kIcePwd[1], selected_connection->remote_candidate().password()); @@ -1736,7 +1756,7 @@ TEST_F(P2PTransportChannelTest, PeerReflexiveCandidateBeforeSignalingWithNAT) { ResumeCandidates(1); - EXPECT_THAT(webrtc::WaitUntil( + EXPECT_THAT(WaitUntil( [&] { return ep1_ch1() ->selected_connection() @@ -1744,7 +1764,7 @@ TEST_F(P2PTransportChannelTest, PeerReflexiveCandidateBeforeSignalingWithNAT) { .is_prflx(); }, IsTrue(), {.timeout = TimeDelta::Millis(kMediumTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_EQ(selected_connection, ep1_ch1()->selected_connection()); DestroyChannels(); } @@ -1761,22 +1781,22 @@ TEST_F(P2PTransportChannelTest, PeerReflexiveCandidateBeforeSignalingWithNAT) { TEST_F(P2PTransportChannelTest, PeerReflexiveCandidateBeforeSignalingWithIceRestart) { const Environment env = CreateEnvironment(); - ConfigureEndpoints(env, OPEN, OPEN, webrtc::kDefaultPortAllocatorFlags, - webrtc::kDefaultPortAllocatorFlags); + ConfigureEndpoints(env, OPEN, OPEN, kDefaultPortAllocatorFlags, + kDefaultPortAllocatorFlags); // Only gather relay candidates, so that when the prflx candidate arrives // it's prioritized above the current candidate pair. - GetEndpoint(0)->allocator_->SetCandidateFilter(webrtc::CF_RELAY); - GetEndpoint(1)->allocator_->SetCandidateFilter(webrtc::CF_RELAY); + GetEndpoint(0)->allocator_->SetCandidateFilter(CF_RELAY); + GetEndpoint(1)->allocator_->SetCandidateFilter(CF_RELAY); // Setting this allows us to control when SetRemoteIceParameters is called. set_remote_ice_parameter_source(FROM_CANDIDATE); CreateChannels(env); // Wait for the initial connection to be made. ep1_ch1()->SetRemoteIceParameters(kIceParams[1]); ep2_ch1()->SetRemoteIceParameters(kIceParams[0]); - EXPECT_THAT(webrtc::WaitUntil( - [&] { return CheckConnected(ep1_ch1(), ep2_ch1()); }, - IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + EXPECT_THAT( + WaitUntil([&] { return CheckConnected(ep1_ch1(), ep2_ch1()); }, IsTrue(), + {.timeout = TimeDelta::Millis(kDefaultTimeout)}), + IsRtcOk()); // Simulate an ICE restart on ep2, but don't signal the candidate or new // ICE parameters until after a prflx connection has been made. @@ -1788,7 +1808,7 @@ TEST_F(P2PTransportChannelTest, // The caller should have the selected connection connected to the peer // reflexive candidate. - EXPECT_THAT(webrtc::WaitUntil( + EXPECT_THAT(WaitUntil( [&] { return ep1_ch1() ->selected_connection() @@ -1796,7 +1816,7 @@ TEST_F(P2PTransportChannelTest, .is_prflx(); }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); const Connection* prflx_selected_connection = ep1_ch1()->selected_connection(); @@ -1810,7 +1830,7 @@ TEST_F(P2PTransportChannelTest, // their information to update the peer reflexive candidate. ResumeCandidates(1); - EXPECT_THAT(webrtc::WaitUntil( + EXPECT_THAT(WaitUntil( [&] { return ep1_ch1() ->selected_connection() @@ -1818,7 +1838,7 @@ TEST_F(P2PTransportChannelTest, .is_relay(); }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_EQ(prflx_selected_connection, ep1_ch1()->selected_connection()); DestroyChannels(); } @@ -1828,19 +1848,19 @@ TEST_F(P2PTransportChannelTest, RemoteCandidatesWithoutUfragPwd) { ScopedFakeClock clock; const Environment env = CreateEnvironment(); set_remote_ice_parameter_source(FROM_SETICEPARAMETERS); - ConfigureEndpoints(env, OPEN, OPEN, webrtc::kDefaultPortAllocatorFlags, - webrtc::kDefaultPortAllocatorFlags); + ConfigureEndpoints(env, OPEN, OPEN, kDefaultPortAllocatorFlags, + kDefaultPortAllocatorFlags); CreateChannels(env); const Connection* selected_connection = nullptr; // Wait until the callee's connections are created. EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return selected_connection = ep2_ch1()->selected_connection(); }, NotNull(), {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); // Wait to make sure the selected connection is not changed. SIMULATED_WAIT(ep2_ch1()->selected_connection() != selected_connection, kShortTimeout, clock); @@ -1853,9 +1873,8 @@ TEST_F(P2PTransportChannelTest, RemoteCandidatesWithoutUfragPwd) { TEST_F(P2PTransportChannelTest, IncomingOnlyBlocked) { ScopedFakeClock clock; const Environment env = CreateEnvironment(); - ConfigureEndpoints(env, NAT_FULL_CONE, OPEN, - webrtc::kDefaultPortAllocatorFlags, - webrtc::kDefaultPortAllocatorFlags); + ConfigureEndpoints(env, NAT_FULL_CONE, OPEN, kDefaultPortAllocatorFlags, + kDefaultPortAllocatorFlags); SetAllocatorFlags(0, kOnlyLocalPorts); CreateChannels(env); @@ -1877,19 +1896,18 @@ TEST_F(P2PTransportChannelTest, IncomingOnlyBlocked) { TEST_F(P2PTransportChannelTest, IncomingOnlyOpen) { ScopedFakeClock clock; const Environment env = CreateEnvironment(); - ConfigureEndpoints(env, OPEN, NAT_FULL_CONE, - webrtc::kDefaultPortAllocatorFlags, - webrtc::kDefaultPortAllocatorFlags); + ConfigureEndpoints(env, OPEN, NAT_FULL_CONE, kDefaultPortAllocatorFlags, + kDefaultPortAllocatorFlags); SetAllocatorFlags(0, kOnlyLocalPorts); CreateChannels(env); ep1_ch1()->set_incoming_only(true); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return CheckConnected(ep1_ch1(), ep2_ch1()); }, IsTrue(), {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); DestroyChannels(); } @@ -1905,15 +1923,15 @@ TEST_F(P2PTransportChannelTest, CanOnlyMakeOutgoingTcpConnections) { // // TODO(deadbeef): Later, make this flag the default, and do more elegant // things to ensure extra candidates don't waste resources? - ConfigureEndpoints(env, OPEN, OPEN, - webrtc::kDefaultPortAllocatorFlags | - webrtc::PORTALLOCATOR_ENABLE_ANY_ADDRESS_PORTS, - webrtc::kDefaultPortAllocatorFlags); + ConfigureEndpoints( + env, OPEN, OPEN, + kDefaultPortAllocatorFlags | PORTALLOCATOR_ENABLE_ANY_ADDRESS_PORTS, + kDefaultPortAllocatorFlags); // In order to simulate nothing working but outgoing TCP connections, prevent // the endpoint from binding to its interface's address as well as the // "any" addresses. It can then only make a connection by using "Connect()". - fw()->SetUnbindableIps({webrtc::GetAnyIP(AF_INET), webrtc::GetAnyIP(AF_INET6), - kPublicAddrs[0].ipaddr()}); + fw()->SetUnbindableIps( + {GetAnyIP(AF_INET), GetAnyIP(AF_INET6), kPublicAddrs[0].ipaddr()}); CreateChannels(env); // Expect a IceCandidateType::kPrflx candidate on the side that can only make // outgoing connections, endpoint 0. @@ -1928,12 +1946,12 @@ TEST_F(P2PTransportChannelTest, TestTcpConnectionsFromActiveToPassive) { AddAddress(0, kPublicAddrs[0]); AddAddress(1, kPublicAddrs[1]); - SetAllocationStepDelay(0, webrtc::kMinimumStepDelay); - SetAllocationStepDelay(1, webrtc::kMinimumStepDelay); + SetAllocationStepDelay(0, kMinimumStepDelay); + SetAllocationStepDelay(1, kMinimumStepDelay); - int kOnlyLocalTcpPorts = webrtc::PORTALLOCATOR_DISABLE_UDP | - webrtc::PORTALLOCATOR_DISABLE_STUN | - webrtc::PORTALLOCATOR_DISABLE_RELAY; + int kOnlyLocalTcpPorts = PORTALLOCATOR_DISABLE_UDP | + PORTALLOCATOR_DISABLE_STUN | + PORTALLOCATOR_DISABLE_RELAY; // Disable all protocols except TCP. SetAllocatorFlags(0, kOnlyLocalTcpPorts); SetAllocatorFlags(1, kOnlyLocalTcpPorts); @@ -1952,22 +1970,22 @@ TEST_F(P2PTransportChannelTest, TestTcpConnectionsFromActiveToPassive) { CreateChannels(env); // Verify tcp candidates. - VerifySavedTcpCandidates(0, webrtc::TCPTYPE_PASSIVE_STR); - VerifySavedTcpCandidates(1, webrtc::TCPTYPE_ACTIVE_STR); + VerifySavedTcpCandidates(0, TCPTYPE_PASSIVE_STR); + VerifySavedTcpCandidates(1, TCPTYPE_ACTIVE_STR); // Resume candidates. ResumeCandidates(0); ResumeCandidates(1); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return CheckCandidatePairAndConnected( ep1_ch1(), ep2_ch1(), kPublicAddrs[0], kPublicAddrs[1]); }, IsTrue(), {.timeout = TimeDelta::Millis(kShortTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); TestSendRecv(&clock); DestroyChannels(); @@ -1978,18 +1996,18 @@ TEST_F(P2PTransportChannelTest, TestTcpConnectionTcptypeSet) { ScopedFakeClock clock; const Environment env = CreateEnvironment(); ConfigureEndpoints(env, BLOCK_UDP_AND_INCOMING_TCP, OPEN, - webrtc::PORTALLOCATOR_ENABLE_SHARED_SOCKET, - webrtc::PORTALLOCATOR_ENABLE_SHARED_SOCKET); + PORTALLOCATOR_ENABLE_SHARED_SOCKET, + PORTALLOCATOR_ENABLE_SHARED_SOCKET); SetAllowTcpListen(0, false); // active. SetAllowTcpListen(1, true); // actpass. CreateChannels(env); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return CheckConnected(ep1_ch1(), ep2_ch1()); }, IsTrue(), {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); SIMULATED_WAIT(false, kDefaultTimeout, clock); EXPECT_EQ(RemoteCandidate(ep1_ch1())->tcptype(), "passive"); @@ -2008,8 +2026,8 @@ TEST_F(P2PTransportChannelTest, TestIceRoleConflict) { AddAddress(1, kPublicAddrs[1]); // Creating channels with both channels role set to CONTROLLING. - SetIceRole(0, webrtc::ICEROLE_CONTROLLING); - SetIceRole(1, webrtc::ICEROLE_CONTROLLING); + SetIceRole(0, ICEROLE_CONTROLLING); + SetIceRole(1, ICEROLE_CONTROLLING); CreateChannels(env); bool first_endpoint_has_lower_tiebreaker = @@ -2018,20 +2036,19 @@ TEST_F(P2PTransportChannelTest, TestIceRoleConflict) { // Since both the channels initiated with controlling state, the channel with // the lower tiebreaker should receive SignalRoleConflict. EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return GetRoleConflict(first_endpoint_has_lower_tiebreaker ? 0 : 1); }, IsTrue(), {.timeout = TimeDelta::Millis(kShortTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_FALSE(GetRoleConflict(first_endpoint_has_lower_tiebreaker ? 1 : 0)); EXPECT_THAT( - webrtc::WaitUntil( - [&] { return CheckConnected(ep1_ch1(), ep2_ch1()); }, IsTrue(), - {.timeout = TimeDelta::Millis(kShortTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + WaitUntil([&] { return CheckConnected(ep1_ch1(), ep2_ch1()); }, IsTrue(), + {.timeout = TimeDelta::Millis(kShortTimeout), .clock = &clock}), + IsRtcOk()); EXPECT_TRUE(ep1_ch1()->selected_connection() && ep2_ch1()->selected_connection()); @@ -2050,34 +2067,32 @@ TEST_F(P2PTransportChannelTest, TestIceConfigWillPassDownToPort) { // Give the first connection the higher tiebreaker so its role won't // change unless we tell it to. - SetIceRole(0, webrtc::ICEROLE_CONTROLLING); - SetIceRole(1, webrtc::ICEROLE_CONTROLLING); + SetIceRole(0, ICEROLE_CONTROLLING); + SetIceRole(1, ICEROLE_CONTROLLING); CreateChannels(env); EXPECT_THAT( - webrtc::WaitUntil( - [&] { return ep1_ch1()->ports().size(); }, Eq(2u), - {.timeout = TimeDelta::Millis(kShortTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + WaitUntil([&] { return ep1_ch1()->ports().size(); }, Eq(2u), + {.timeout = TimeDelta::Millis(kShortTimeout), .clock = &clock}), + IsRtcOk()); const std::vector ports_before = ep1_ch1()->ports(); for (size_t i = 0; i < ports_before.size(); ++i) { - EXPECT_EQ(webrtc::ICEROLE_CONTROLLING, ports_before[i]->GetIceRole()); + EXPECT_EQ(ICEROLE_CONTROLLING, ports_before[i]->GetIceRole()); } - ep1_ch1()->SetIceRole(webrtc::ICEROLE_CONTROLLED); + ep1_ch1()->SetIceRole(ICEROLE_CONTROLLED); const std::vector ports_after = ep1_ch1()->ports(); for (size_t i = 0; i < ports_after.size(); ++i) { - EXPECT_EQ(webrtc::ICEROLE_CONTROLLED, ports_before[i]->GetIceRole()); + EXPECT_EQ(ICEROLE_CONTROLLED, ports_before[i]->GetIceRole()); } EXPECT_THAT( - webrtc::WaitUntil( - [&] { return CheckConnected(ep1_ch1(), ep2_ch1()); }, IsTrue(), - {.timeout = TimeDelta::Millis(kShortTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + WaitUntil([&] { return CheckConnected(ep1_ch1(), ep2_ch1()); }, IsTrue(), + {.timeout = TimeDelta::Millis(kShortTimeout), .clock = &clock}), + IsRtcOk()); EXPECT_TRUE(ep1_ch1()->selected_connection() && ep2_ch1()->selected_connection()); @@ -2117,26 +2132,26 @@ TEST_F(P2PTransportChannelTest, TestIPv6Connections) { AddAddress(1, kIPv6PublicAddrs[1]); AddAddress(1, kPublicAddrs[1]); - SetAllocationStepDelay(0, webrtc::kMinimumStepDelay); - SetAllocationStepDelay(1, webrtc::kMinimumStepDelay); + SetAllocationStepDelay(0, kMinimumStepDelay); + SetAllocationStepDelay(1, kMinimumStepDelay); // Enable IPv6 - SetAllocatorFlags(0, webrtc::PORTALLOCATOR_ENABLE_IPV6 | - webrtc::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI); - SetAllocatorFlags(1, webrtc::PORTALLOCATOR_ENABLE_IPV6 | - webrtc::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI); + SetAllocatorFlags( + 0, PORTALLOCATOR_ENABLE_IPV6 | PORTALLOCATOR_ENABLE_IPV6_ON_WIFI); + SetAllocatorFlags( + 1, PORTALLOCATOR_ENABLE_IPV6 | PORTALLOCATOR_ENABLE_IPV6_ON_WIFI); CreateChannels(env); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return CheckCandidatePairAndConnected( ep1_ch1(), ep2_ch1(), kIPv6PublicAddrs[0], kIPv6PublicAddrs[1]); }, IsTrue(), {.timeout = TimeDelta::Millis(kShortTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); TestSendRecv(&clock); DestroyChannels(); @@ -2146,23 +2161,22 @@ TEST_F(P2PTransportChannelTest, TestIPv6Connections) { TEST_F(P2PTransportChannelTest, TestForceTurn) { ScopedFakeClock clock; const Environment env = CreateEnvironment(); - ConfigureEndpoints(env, NAT_PORT_RESTRICTED, NAT_SYMMETRIC, - webrtc::kDefaultPortAllocatorFlags | - webrtc::PORTALLOCATOR_ENABLE_SHARED_SOCKET, - webrtc::kDefaultPortAllocatorFlags | - webrtc::PORTALLOCATOR_ENABLE_SHARED_SOCKET); + ConfigureEndpoints( + env, NAT_PORT_RESTRICTED, NAT_SYMMETRIC, + kDefaultPortAllocatorFlags | PORTALLOCATOR_ENABLE_SHARED_SOCKET, + kDefaultPortAllocatorFlags | PORTALLOCATOR_ENABLE_SHARED_SOCKET); set_force_relay(true); - SetAllocationStepDelay(0, webrtc::kMinimumStepDelay); - SetAllocationStepDelay(1, webrtc::kMinimumStepDelay); + SetAllocationStepDelay(0, kMinimumStepDelay); + SetAllocationStepDelay(1, kMinimumStepDelay); CreateChannels(env); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return CheckConnected(ep1_ch1(), ep2_ch1()); }, IsTrue(), {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_TRUE(ep1_ch1()->selected_connection() && ep2_ch1()->selected_connection()); @@ -2181,21 +2195,21 @@ TEST_F(P2PTransportChannelTest, TestForceTurn) { TEST_F(P2PTransportChannelTest, TestContinualGathering) { ScopedFakeClock clock; const Environment env = CreateEnvironment(); - ConfigureEndpoints(env, OPEN, OPEN, webrtc::kDefaultPortAllocatorFlags, - webrtc::kDefaultPortAllocatorFlags); - SetAllocationStepDelay(0, webrtc::kDefaultStepDelay); - SetAllocationStepDelay(1, webrtc::kDefaultStepDelay); + ConfigureEndpoints(env, OPEN, OPEN, kDefaultPortAllocatorFlags, + kDefaultPortAllocatorFlags); + SetAllocationStepDelay(0, kDefaultStepDelay); + SetAllocationStepDelay(1, kDefaultStepDelay); IceConfig continual_gathering_config = - CreateIceConfig(1000, webrtc::GATHER_CONTINUALLY); + CreateIceConfig(1000, GATHER_CONTINUALLY); // By default, ep2 does not gather continually. IceConfig default_config; CreateChannels(env, continual_gathering_config, default_config); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return CheckConnected(ep1_ch1(), ep2_ch1()); }, IsTrue(), {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); SIMULATED_WAIT( IceGatheringState::kIceGatheringComplete == ep1_ch1()->gathering_state(), kShortTimeout, clock); @@ -2213,18 +2227,18 @@ TEST_F(P2PTransportChannelTest, TestContinualGathering) { TEST_F(P2PTransportChannelTest, TestUsingPooledSessionBeforeDoneGathering) { ScopedFakeClock clock; const Environment env = CreateEnvironment(); - ConfigureEndpoints(env, OPEN, OPEN, webrtc::kDefaultPortAllocatorFlags, - webrtc::kDefaultPortAllocatorFlags); + ConfigureEndpoints(env, OPEN, OPEN, kDefaultPortAllocatorFlags, + kDefaultPortAllocatorFlags); // First create a pooled session for each endpoint. auto& allocator_1 = GetEndpoint(0)->allocator_; auto& allocator_2 = GetEndpoint(1)->allocator_; int pool_size = 1; allocator_1->SetConfiguration(allocator_1->stun_servers(), allocator_1->turn_servers(), pool_size, - webrtc::NO_PRUNE); + NO_PRUNE); allocator_2->SetConfiguration(allocator_2->stun_servers(), allocator_2->turn_servers(), pool_size, - webrtc::NO_PRUNE); + NO_PRUNE); const PortAllocatorSession* pooled_session_1 = allocator_1->GetPooledSession(); const PortAllocatorSession* pooled_session_2 = @@ -2239,10 +2253,10 @@ TEST_F(P2PTransportChannelTest, TestUsingPooledSessionBeforeDoneGathering) { // Now let the endpoints connect and try exchanging some data. CreateChannels(env); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return CheckConnected(ep1_ch1(), ep2_ch1()); }, IsTrue(), {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); TestSendRecv(&clock); // Make sure the P2PTransportChannels are actually using ports from the // pooled sessions. @@ -2260,18 +2274,18 @@ TEST_F(P2PTransportChannelTest, TestUsingPooledSessionBeforeDoneGathering) { TEST_F(P2PTransportChannelTest, TestUsingPooledSessionAfterDoneGathering) { ScopedFakeClock clock; const Environment env = CreateEnvironment(); - ConfigureEndpoints(env, OPEN, OPEN, webrtc::kDefaultPortAllocatorFlags, - webrtc::kDefaultPortAllocatorFlags); + ConfigureEndpoints(env, OPEN, OPEN, kDefaultPortAllocatorFlags, + kDefaultPortAllocatorFlags); // First create a pooled session for each endpoint. auto& allocator_1 = GetEndpoint(0)->allocator_; auto& allocator_2 = GetEndpoint(1)->allocator_; int pool_size = 1; allocator_1->SetConfiguration(allocator_1->stun_servers(), allocator_1->turn_servers(), pool_size, - webrtc::NO_PRUNE); + NO_PRUNE); allocator_2->SetConfiguration(allocator_2->stun_servers(), allocator_2->turn_servers(), pool_size, - webrtc::NO_PRUNE); + NO_PRUNE); const PortAllocatorSession* pooled_session_1 = allocator_1->GetPooledSession(); const PortAllocatorSession* pooled_session_2 = @@ -2281,21 +2295,21 @@ TEST_F(P2PTransportChannelTest, TestUsingPooledSessionAfterDoneGathering) { // Wait for the pooled sessions to finish gathering before the // P2PTransportChannels try to use them. EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return pooled_session_1->CandidatesAllocationDone() && pooled_session_2->CandidatesAllocationDone(); }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); // Now let the endpoints connect and try exchanging some data. CreateChannels(env); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return CheckConnected(ep1_ch1(), ep2_ch1()); }, IsTrue(), {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); TestSendRecv(&clock); // Make sure the P2PTransportChannels are actually using ports from the // pooled sessions. @@ -2316,8 +2330,8 @@ TEST_F(P2PTransportChannelTest, TestUsingPooledSessionAfterDoneGathering) { // (which supports TURN servers and TURN candidate gathering) is available. TEST_F(P2PTransportChannelTest, TurnToTurnPresumedWritable) { const Environment env = CreateEnvironment(); - ConfigureEndpoints(env, OPEN, OPEN, webrtc::kDefaultPortAllocatorFlags, - webrtc::kDefaultPortAllocatorFlags); + ConfigureEndpoints(env, OPEN, OPEN, kDefaultPortAllocatorFlags, + kDefaultPortAllocatorFlags); // Only configure one channel so we can control when the remote candidate // is added. GetEndpoint(0)->cd1_.ch_ = CreateChannel( @@ -2326,11 +2340,10 @@ TEST_F(P2PTransportChannelTest, TurnToTurnPresumedWritable) { config.presume_writable_when_fully_relayed = true; ep1_ch1()->SetIceConfig(config); ep1_ch1()->MaybeStartGathering(); - EXPECT_THAT( - webrtc::WaitUntil([&] { return ep1_ch1()->gathering_state(); }, + EXPECT_THAT(WaitUntil([&] { return ep1_ch1()->gathering_state(); }, Eq(IceGatheringState::kIceGatheringComplete), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); // Add two remote candidates; a host candidate (with higher priority) // and TURN candidate. ep1_ch1()->AddRemoteCandidate( @@ -2339,10 +2352,10 @@ TEST_F(P2PTransportChannelTest, TurnToTurnPresumedWritable) { CreateUdpCandidate(IceCandidateType::kRelay, "2.2.2.2", 2, 0)); // Expect that the TURN-TURN candidate pair will be prioritized since it's // "probably writable". - EXPECT_THAT(webrtc::WaitUntil( - [&] { return ep1_ch1()->selected_connection(); }, Ne(nullptr), - {.timeout = TimeDelta::Millis(kShortTimeout)}), - webrtc::IsRtcOk()); + EXPECT_THAT( + WaitUntil([&] { return ep1_ch1()->selected_connection(); }, Ne(nullptr), + {.timeout = TimeDelta::Millis(kShortTimeout)}), + IsRtcOk()); EXPECT_TRUE(LocalCandidate(ep1_ch1())->is_relay()); EXPECT_TRUE(RemoteCandidate(ep1_ch1())->is_relay()); // Also expect that the channel instantly indicates that it's writable since @@ -2369,8 +2382,7 @@ TEST_F(P2PTransportChannelTest, TurnToPrflxPresumedWritable) { virtual_socket_server()->UpdateDelayDistribution(); ConfigureEndpoints(env, NAT_SYMMETRIC, NAT_SYMMETRIC, - webrtc::kDefaultPortAllocatorFlags, - webrtc::kDefaultPortAllocatorFlags); + kDefaultPortAllocatorFlags, kDefaultPortAllocatorFlags); // We want the remote TURN candidate to show up as prflx. To do this we need // to configure the server to accept packets from an address we haven't // explicitly installed permission for. @@ -2391,11 +2403,11 @@ TEST_F(P2PTransportChannelTest, TurnToPrflxPresumedWritable) { // Wait for the TURN<->prflx connection. EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return ep1_ch1()->receiving() && ep1_ch1()->writable(); }, IsTrue(), {.timeout = TimeDelta::Millis(kShortTimeout), .clock = &fake_clock}), - webrtc::IsRtcOk()); + IsRtcOk()); ASSERT_NE(nullptr, ep1_ch1()->selected_connection()); EXPECT_TRUE(LocalCandidate(ep1_ch1())->is_relay()); EXPECT_TRUE(RemoteCandidate(ep1_ch1())->is_prflx()); @@ -2405,11 +2417,11 @@ TEST_F(P2PTransportChannelTest, TurnToPrflxPresumedWritable) { // Now wait for it to actually become writable. EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return ep1_ch1()->selected_connection()->writable(); }, IsTrue(), {.timeout = TimeDelta::Millis(kShortTimeout), .clock = &fake_clock}), - webrtc::IsRtcOk()); + IsRtcOk()); // Explitly destroy channels, before fake clock is destroyed. DestroyChannels(); @@ -2422,8 +2434,7 @@ TEST_F(P2PTransportChannelTest, PresumedWritablePreferredOverUnreliable) { const Environment env = CreateEnvironment(); ConfigureEndpoints(env, NAT_SYMMETRIC, NAT_SYMMETRIC, - webrtc::kDefaultPortAllocatorFlags, - webrtc::kDefaultPortAllocatorFlags); + kDefaultPortAllocatorFlags, kDefaultPortAllocatorFlags); IceConfig config; config.presume_writable_when_fully_relayed = true; GetEndpoint(0)->cd1_.ch_ = CreateChannel( @@ -2436,19 +2447,18 @@ TEST_F(P2PTransportChannelTest, PresumedWritablePreferredOverUnreliable) { ep2_ch1()->MaybeStartGathering(); // Wait for initial connection as usual. EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return CheckConnected(ep1_ch1(), ep2_ch1()); }, IsTrue(), {.timeout = TimeDelta::Millis(kShortTimeout), .clock = &fake_clock}), - webrtc::IsRtcOk()); + IsRtcOk()); const Connection* old_selected_connection = ep1_ch1()->selected_connection(); // Destroy the second channel and wait for the current connection on the // first channel to become "unreliable", making it no longer writable. GetEndpoint(1)->cd1_.ch_.reset(); - EXPECT_THAT( - webrtc::WaitUntil([&] { return !ep1_ch1()->writable(); }, IsTrue(), + EXPECT_THAT(WaitUntil([&] { return !ep1_ch1()->writable(); }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &fake_clock}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_NE(nullptr, ep1_ch1()->selected_connection()); // Add a remote TURN candidate. The first channel should still have a TURN // port available to make a TURN<->TURN pair that's presumed writable. @@ -2467,8 +2477,8 @@ TEST_F(P2PTransportChannelTest, PresumedWritablePreferredOverUnreliable) { // writable" connection. Previously this did not work. TEST_F(P2PTransportChannelTest, SignalReadyToSendWithPresumedWritable) { const Environment env = CreateEnvironment(); - ConfigureEndpoints(env, OPEN, OPEN, webrtc::kDefaultPortAllocatorFlags, - webrtc::kDefaultPortAllocatorFlags); + ConfigureEndpoints(env, OPEN, OPEN, kDefaultPortAllocatorFlags, + kDefaultPortAllocatorFlags); // Only test one endpoint, so we can ensure the connection doesn't receive a // binding response and advance beyond being "presumed" writable. GetEndpoint(0)->cd1_.ch_ = CreateChannel( @@ -2477,18 +2487,17 @@ TEST_F(P2PTransportChannelTest, SignalReadyToSendWithPresumedWritable) { config.presume_writable_when_fully_relayed = true; ep1_ch1()->SetIceConfig(config); ep1_ch1()->MaybeStartGathering(); - EXPECT_THAT( - webrtc::WaitUntil([&] { return ep1_ch1()->gathering_state(); }, + EXPECT_THAT(WaitUntil([&] { return ep1_ch1()->gathering_state(); }, Eq(IceGatheringState::kIceGatheringComplete), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); ep1_ch1()->AddRemoteCandidate( CreateUdpCandidate(IceCandidateType::kRelay, "1.1.1.1", 1, 0)); // Sanity checking the type of the connection. - EXPECT_THAT(webrtc::WaitUntil( - [&] { return ep1_ch1()->selected_connection(); }, Ne(nullptr), - {.timeout = TimeDelta::Millis(kShortTimeout)}), - webrtc::IsRtcOk()); + EXPECT_THAT( + WaitUntil([&] { return ep1_ch1()->selected_connection(); }, Ne(nullptr), + {.timeout = TimeDelta::Millis(kShortTimeout)}), + IsRtcOk()); EXPECT_TRUE(LocalCandidate(ep1_ch1())->is_relay()); EXPECT_TRUE(RemoteCandidate(ep1_ch1())->is_relay()); @@ -2515,18 +2524,16 @@ TEST_F(P2PTransportChannelTest, ScopedFakeClock clock; const Environment env = CreateEnvironment(); // Gather only relay candidates. - ConfigureEndpoints( - env, NAT_SYMMETRIC, NAT_SYMMETRIC, - webrtc::kDefaultPortAllocatorFlags | webrtc::PORTALLOCATOR_DISABLE_UDP | - webrtc::PORTALLOCATOR_DISABLE_STUN | - webrtc::PORTALLOCATOR_DISABLE_TCP, - webrtc::kDefaultPortAllocatorFlags | webrtc::PORTALLOCATOR_DISABLE_UDP | - webrtc::PORTALLOCATOR_DISABLE_STUN | - webrtc::PORTALLOCATOR_DISABLE_TCP); + ConfigureEndpoints(env, NAT_SYMMETRIC, NAT_SYMMETRIC, + kDefaultPortAllocatorFlags | PORTALLOCATOR_DISABLE_UDP | + PORTALLOCATOR_DISABLE_STUN | PORTALLOCATOR_DISABLE_TCP, + kDefaultPortAllocatorFlags | PORTALLOCATOR_DISABLE_UDP | + PORTALLOCATOR_DISABLE_STUN | + PORTALLOCATOR_DISABLE_TCP); // With conflicting ICE roles, endpoint 1 has the higher tie breaker and will // send a binding error response. - SetIceRole(0, webrtc::ICEROLE_CONTROLLING); - SetIceRole(1, webrtc::ICEROLE_CONTROLLING); + SetIceRole(0, ICEROLE_CONTROLLING); + SetIceRole(1, ICEROLE_CONTROLLING); // We want the remote TURN candidate to show up as prflx. To do this we need // to configure the server to accept packets from an address we haven't // explicitly installed permission for. @@ -2542,11 +2549,11 @@ TEST_F(P2PTransportChannelTest, ep2_ch1()->MaybeStartGathering(); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return ep1_ch1()->receiving() && ep1_ch1()->writable(); }, IsTrue(), {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); ASSERT_NE(nullptr, ep1_ch1()->selected_connection()); @@ -2565,7 +2572,7 @@ TEST_F(P2PTransportChannelTest, "WebRTC-PiggybackIceCheckAcknowledgement/Enabled/")); ConfigureEndpoints(env, OPEN, OPEN, kOnlyLocalPorts, kOnlyLocalPorts); IceConfig ep1_config; - IceConfig ep2_config = CreateIceConfig(1000, webrtc::GATHER_CONTINUALLY); + IceConfig ep2_config = CreateIceConfig(1000, GATHER_CONTINUALLY); // Let ep2 be tolerable of the loss of connectivity checks, so that it keeps // sending pings even after ep1 becomes unwritable as we configure the // firewall below. @@ -2578,23 +2585,22 @@ TEST_F(P2PTransportChannelTest, // Wait until both sides become writable for the first time. EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return CheckConnected(ep1_ch1(), ep2_ch1()); }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); // Block the ingress traffic to ep1 so that there is no check response from // ep2. ASSERT_NE(nullptr, LocalCandidate(ep1_ch1())); - fw()->AddRule(false, webrtc::FP_ANY, webrtc::FD_IN, - LocalCandidate(ep1_ch1())->address()); + fw()->AddRule(false, FP_ANY, FD_IN, LocalCandidate(ep1_ch1())->address()); // Wait until ep1 becomes unwritable. At the same time ep2 should be still // fine so that it will keep sending pings. EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return ep1_ch1() != nullptr && !ep1_ch1()->writable(); }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_TRUE(ep2_ch1() != nullptr && ep2_ch1()->writable()); // Now let the pings from ep2 to flow but block any pings from ep1, so that // ep1 can only become writable again after receiving an incoming ping from @@ -2602,14 +2608,13 @@ TEST_F(P2PTransportChannelTest, // though that ep1 should have stopped sending pings after becoming unwritable // in the current design. fw()->ClearRules(); - fw()->AddRule(false, webrtc::FP_ANY, webrtc::FD_OUT, - LocalCandidate(ep1_ch1())->address()); + fw()->AddRule(false, FP_ANY, FD_OUT, LocalCandidate(ep1_ch1())->address()); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return ep1_ch1() != nullptr && ep1_ch1()->writable(); }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); DestroyChannels(); } @@ -2752,43 +2757,43 @@ TEST_F(P2PTransportChannelMultihomedTest, TestFailoverControlledSide) { SetAllocatorFlags(1, kOnlyLocalPorts); // Make the receiving timeout shorter for testing. - IceConfig config = CreateIceConfig(1000, webrtc::GATHER_ONCE); + IceConfig config = CreateIceConfig(1000, GATHER_ONCE); // Create channels and let them go writable, as usual. CreateChannels(env, config, config); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return CheckCandidatePairAndConnected( ep1_ch1(), ep2_ch1(), kPublicAddrs[0], kPublicAddrs[1]); }, IsTrue(), {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); // Blackhole any traffic to or from the public addrs. RTC_LOG(LS_INFO) << "Failing over..."; - fw()->AddRule(false, webrtc::FP_ANY, webrtc::FD_ANY, kPublicAddrs[1]); + fw()->AddRule(false, FP_ANY, FD_ANY, kPublicAddrs[1]); // The selected connections may switch, so keep references to them. const Connection* selected_connection1 = ep1_ch1()->selected_connection(); // We should detect loss of receiving within 1 second or so. EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return !selected_connection1->receiving(); }, IsTrue(), {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); // We should switch over to use the alternate addr on both sides // when we are not receiving. EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return ep1_ch1()->selected_connection()->receiving() && ep2_ch1()->selected_connection()->receiving(); }, IsTrue(), {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_TRUE(LocalCandidate(ep1_ch1())->address().EqualIPs(kPublicAddrs[0])); EXPECT_TRUE( RemoteCandidate(ep1_ch1())->address().EqualIPs(kAlternateAddrs[1])); @@ -2814,35 +2819,35 @@ TEST_F(P2PTransportChannelMultihomedTest, TestFailoverControllingSide) { SetAllocatorFlags(1, kOnlyLocalPorts); // Make the receiving timeout shorter for testing. - IceConfig config = CreateIceConfig(1000, webrtc::GATHER_ONCE); + IceConfig config = CreateIceConfig(1000, GATHER_ONCE); // Create channels and let them go writable, as usual. CreateChannels(env, config, config); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return CheckCandidatePairAndConnected( ep1_ch1(), ep2_ch1(), kPublicAddrs[0], kPublicAddrs[1]); }, IsTrue(), {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); // Blackhole any traffic to or from the public addrs. RTC_LOG(LS_INFO) << "Failing over..."; - fw()->AddRule(false, webrtc::FP_ANY, webrtc::FD_ANY, kPublicAddrs[0]); + fw()->AddRule(false, FP_ANY, FD_ANY, kPublicAddrs[0]); // We should detect loss of receiving within 1 second or so. // We should switch over to use the alternate addr on both sides // when we are not receiving. EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return CheckCandidatePairAndConnected( ep1_ch1(), ep2_ch1(), kAlternateAddrs[0], kPublicAddrs[1]); }, IsTrue(), {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); DestroyChannels(); } @@ -2853,20 +2858,19 @@ TEST_F(P2PTransportChannelMultihomedTest, TestFailoverWithManyConnections) { ScopedFakeClock clock; const Environment env = CreateEnvironment(); CreatePortAllocators(env); - test_turn_server()->AddInternalSocket(kTurnTcpIntAddr, webrtc::PROTO_TCP); + test_turn_server()->AddInternalSocket(kTurnTcpIntAddr, PROTO_TCP); RelayServerConfig turn_server; turn_server.credentials = kRelayCredentials; - turn_server.ports.push_back( - ProtocolAddress(kTurnTcpIntAddr, webrtc::PROTO_TCP)); + turn_server.ports.push_back(ProtocolAddress(kTurnTcpIntAddr, PROTO_TCP)); GetAllocator(0)->AddTurnServerForTesting(turn_server); GetAllocator(1)->AddTurnServerForTesting(turn_server); // Enable IPv6 - SetAllocatorFlags(0, webrtc::PORTALLOCATOR_ENABLE_IPV6 | - webrtc::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI); - SetAllocatorFlags(1, webrtc::PORTALLOCATOR_ENABLE_IPV6 | - webrtc::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI); - SetAllocationStepDelay(0, webrtc::kMinimumStepDelay); - SetAllocationStepDelay(1, webrtc::kMinimumStepDelay); + SetAllocatorFlags( + 0, PORTALLOCATOR_ENABLE_IPV6 | PORTALLOCATOR_ENABLE_IPV6_ON_WIFI); + SetAllocatorFlags( + 1, PORTALLOCATOR_ENABLE_IPV6 | PORTALLOCATOR_ENABLE_IPV6_ON_WIFI); + SetAllocationStepDelay(0, kMinimumStepDelay); + SetAllocationStepDelay(1, kMinimumStepDelay); auto& wifi = kPublicAddrs; auto& cellular = kAlternateAddrs; @@ -2889,36 +2893,36 @@ TEST_F(P2PTransportChannelMultihomedTest, TestFailoverWithManyConnections) { virtual_socket_server()->UpdateDelayDistribution(); // Make the receiving timeout shorter for testing. - IceConfig config = CreateIceConfig(1000, webrtc::GATHER_CONTINUALLY); + IceConfig config = CreateIceConfig(1000, GATHER_CONTINUALLY); // Create channels and let them go writable, as usual. CreateChannels(env, config, config, true /* ice_renomination */); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return CheckCandidatePairAndConnected(ep1_ch1(), ep2_ch1(), wifiIpv6[0], wifiIpv6[1]); }, IsTrue(), {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); // Blackhole any traffic to or from the wifi on endpoint 1. RTC_LOG(LS_INFO) << "Failing over..."; - fw()->AddRule(false, webrtc::FP_ANY, webrtc::FD_ANY, wifi[0]); - fw()->AddRule(false, webrtc::FP_ANY, webrtc::FD_ANY, wifiIpv6[0]); + fw()->AddRule(false, FP_ANY, FD_ANY, wifi[0]); + fw()->AddRule(false, FP_ANY, FD_ANY, wifiIpv6[0]); // The selected connections may switch, so keep references to them. const Connection* selected_connection1 = ep1_ch1()->selected_connection(); const Connection* selected_connection2 = ep2_ch1()->selected_connection(); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return !selected_connection1->receiving() && !selected_connection2->receiving(); }, IsTrue(), {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); // Per-network best connections will be pinged at relatively higher rate when // the selected connection becomes not receiving. @@ -2928,11 +2932,11 @@ TEST_F(P2PTransportChannelMultihomedTest, TestFailoverWithManyConnections) { int64_t last_ping_sent1 = per_network_best_connection1->last_ping_sent(); int num_pings_sent1 = per_network_best_connection1->num_pings_sent(); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return per_network_best_connection1->num_pings_sent(); }, Gt(num_pings_sent1), {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); ASSERT_GT(per_network_best_connection1->num_pings_sent() - num_pings_sent1, 0); int64_t ping_interval1 = @@ -2946,14 +2950,14 @@ TEST_F(P2PTransportChannelMultihomedTest, TestFailoverWithManyConnections) { // It should switch over to use the cellular IPv6 addr on endpoint 1 before // it timed out on writing. EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return CheckCandidatePairAndConnected(ep1_ch1(), ep2_ch1(), cellularIpv6[0], wifiIpv6[1]); }, IsTrue(), {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); DestroyChannels(); } @@ -2977,23 +2981,23 @@ TEST_F(P2PTransportChannelMultihomedTest, TestIceRenomination) { // We want it to set the remote ICE parameters when creating channels. set_remote_ice_parameter_source(FROM_SETICEPARAMETERS); // Make the receiving timeout shorter for testing. - IceConfig config = CreateIceConfig(1000, webrtc::GATHER_ONCE); + IceConfig config = CreateIceConfig(1000, GATHER_ONCE); // Create channels with ICE renomination and let them go writable as usual. CreateChannels(env, config, config, true); ASSERT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return CheckConnected(ep1_ch1(), ep2_ch1()); }, IsTrue(), {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return ep2_ch1()->selected_connection()->remote_nomination() > 0 && ep1_ch1()->selected_connection()->acked_nomination() > 0; }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); const Connection* selected_connection1 = ep1_ch1()->selected_connection(); Connection* selected_connection2 = const_cast(ep2_ch1()->selected_connection()); @@ -3006,23 +3010,22 @@ TEST_F(P2PTransportChannelMultihomedTest, TestIceRenomination) { // Blackhole any traffic to or from the public addrs. RTC_LOG(LS_INFO) << "Failing over..."; - fw()->AddRule(false, webrtc::FP_ANY, webrtc::FD_ANY, kPublicAddrs[0]); + fw()->AddRule(false, FP_ANY, FD_ANY, kPublicAddrs[0]); // The selected connection on the controlling side should switch. - EXPECT_THAT( - webrtc::WaitUntil( - [&] { return ep1_ch1()->selected_connection(); }, - Ne(selected_connection1), - {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + EXPECT_THAT(WaitUntil([&] { return ep1_ch1()->selected_connection(); }, + Ne(selected_connection1), + {.timeout = TimeDelta::Millis(kMediumTimeout), + .clock = &clock}), + IsRtcOk()); // The connection on the controlled side should be nominated again // and have an increased nomination. EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return ep2_ch1()->selected_connection()->remote_nomination(); }, Gt(remote_nomination2), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); DestroyChannels(); } @@ -3050,33 +3053,33 @@ TEST_F(P2PTransportChannelMultihomedTest, CreateChannels(env); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return CheckCandidatePairAndConnected( ep1_ch1(), ep2_ch1(), kPublicAddrs[0], kPublicAddrs[1]); }, IsTrue(), {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); // Make the receiving timeout shorter for testing. - IceConfig config = CreateIceConfig(1000, webrtc::GATHER_ONCE); + IceConfig config = CreateIceConfig(1000, GATHER_ONCE); ep1_ch1()->SetIceConfig(config); ep2_ch1()->SetIceConfig(config); reset_selected_candidate_pair_switches(); // Blackhole any traffic to or from the public addrs. RTC_LOG(LS_INFO) << "Failing over..."; - fw()->AddRule(false, webrtc::FP_ANY, webrtc::FD_ANY, kPublicAddrs[1]); + fw()->AddRule(false, FP_ANY, FD_ANY, kPublicAddrs[1]); // The selected connections may switch, so keep references to them. const Connection* selected_connection1 = ep1_ch1()->selected_connection(); // We should detect loss of receiving within 1 second or so. EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return !selected_connection1->receiving(); }, IsTrue(), {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); // After a short while, the link recovers itself. SIMULATED_WAIT(false, 10, clock); fw()->ClearRules(); @@ -3084,14 +3087,14 @@ TEST_F(P2PTransportChannelMultihomedTest, // We should remain on the public address on both sides and no connection // switches should have happened. EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return ep1_ch1()->selected_connection()->receiving() && ep2_ch1()->selected_connection()->receiving(); }, IsTrue(), {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_TRUE(RemoteCandidate(ep1_ch1())->address().EqualIPs(kPublicAddrs[1])); EXPECT_TRUE(LocalCandidate(ep2_ch1())->address().EqualIPs(kPublicAddrs[1])); EXPECT_EQ(0, reset_selected_candidate_pair_switches()); @@ -3118,32 +3121,32 @@ TEST_F(P2PTransportChannelMultihomedTest, // Create channels and let them go writable, as usual. CreateChannels(env); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return CheckCandidatePairAndConnected( ep1_ch1(), ep2_ch1(), kPublicAddrs[0], kPublicAddrs[1]); }, IsTrue(), {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); // Make the receiving timeout shorter for testing. - IceConfig config = CreateIceConfig(1000, webrtc::GATHER_ONCE); + IceConfig config = CreateIceConfig(1000, GATHER_ONCE); ep1_ch1()->SetIceConfig(config); ep2_ch1()->SetIceConfig(config); reset_selected_candidate_pair_switches(); // Blackhole any traffic to or from the public addrs. RTC_LOG(LS_INFO) << "Failing over..."; - fw()->AddRule(false, webrtc::FP_ANY, webrtc::FD_ANY, kPublicAddrs[0]); + fw()->AddRule(false, FP_ANY, FD_ANY, kPublicAddrs[0]); // The selected connections may switch, so keep references to them. const Connection* selected_connection1 = ep1_ch1()->selected_connection(); // We should detect loss of receiving within 1 second or so. EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return !selected_connection1->receiving(); }, IsTrue(), {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); // The link recovers after a short while. SIMULATED_WAIT(false, 10, clock); fw()->ClearRules(); @@ -3151,14 +3154,14 @@ TEST_F(P2PTransportChannelMultihomedTest, // We should not switch to the alternate addr on both sides because of the // dampening. EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return CheckCandidatePairAndConnected( ep1_ch1(), ep2_ch1(), kPublicAddrs[0], kPublicAddrs[1]); }, IsTrue(), {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_EQ(0, reset_selected_candidate_pair_switches()); DestroyChannels(); } @@ -3184,36 +3187,36 @@ TEST_F(P2PTransportChannelMultihomedTest, TestRemoteFailover) { CreateChannels(env); // Make the receiving timeout shorter for testing. // Set the backup connection ping interval to 25s. - IceConfig config = CreateIceConfig(1000, webrtc::GATHER_ONCE, 25000); + IceConfig config = CreateIceConfig(1000, GATHER_ONCE, 25000); // Ping the best connection more frequently since we don't have traffic. config.stable_writable_connection_ping_interval = 900; ep1_ch1()->SetIceConfig(config); ep2_ch1()->SetIceConfig(config); // Need to wait to make sure the connections on both networks are writable. EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return CheckCandidatePairAndConnected(ep1_ch1(), ep2_ch1(), wifi[0], wifi[1]); }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); Connection* backup_conn = GetConnectionWithLocalAddress(ep1_ch1(), cellular[0]); ASSERT_NE(nullptr, backup_conn); // After a short while, the backup connection will be writable but not // receiving because backup connection is pinged at a slower rate. EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return backup_conn->writable() && !backup_conn->receiving(); }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); reset_selected_candidate_pair_switches(); // Blackhole any traffic to or from the remote WiFi networks. RTC_LOG(LS_INFO) << "Failing over..."; - fw()->AddRule(false, webrtc::FP_ANY, webrtc::FD_ANY, wifi[1]); + fw()->AddRule(false, FP_ANY, FD_ANY, wifi[1]); int num_switches = 0; SIMULATED_WAIT((num_switches = reset_selected_candidate_pair_switches()) > 0, @@ -3242,18 +3245,17 @@ TEST_F(P2PTransportChannelMultihomedTest, TestPreferWifiToWifiConnection) { // Create channels and let them go writable, as usual. CreateChannels(env); - EXPECT_THAT( - webrtc::WaitUntil([&]() { return CheckConnected(ep1_ch1(), ep2_ch1()); }, + EXPECT_THAT(WaitUntil([&]() { return CheckConnected(ep1_ch1(), ep2_ch1()); }, IsTrue()), - webrtc::IsRtcOk()); + IsRtcOk()); // Need to wait to make sure the connections on both networks are writable. - EXPECT_THAT(webrtc::WaitUntil( + EXPECT_THAT(WaitUntil( [&] { return CheckCandidatePairAndConnected(ep1_ch1(), ep2_ch1(), wifi[0], wifi[1]); }, IsTrue()), - webrtc::IsRtcOk()); + IsRtcOk()); DestroyChannels(); } @@ -3277,13 +3279,13 @@ TEST_F(P2PTransportChannelMultihomedTest, TestPreferWifiOverCellularNetwork) { // Create channels and let them go writable, as usual. CreateChannels(env); - EXPECT_THAT(webrtc::WaitUntil( + EXPECT_THAT(WaitUntil( [&]() { return CheckCandidatePairAndConnected(ep1_ch1(), ep2_ch1(), cellular[0], wifi[1]); }, IsTrue()), - webrtc::IsRtcOk()); + IsRtcOk()); DestroyChannels(); } @@ -3305,30 +3307,28 @@ TEST_F(P2PTransportChannelMultihomedTest, TestPingBackupConnectionRate) { // Create channels and let them go writable, as usual. CreateChannels(env); EXPECT_THAT( - webrtc::WaitUntil([&] { return CheckConnected(ep1_ch1(), ep2_ch1()); }, - IsTrue()), - webrtc::IsRtcOk()); + WaitUntil([&] { return CheckConnected(ep1_ch1(), ep2_ch1()); }, IsTrue()), + IsRtcOk()); int backup_ping_interval = 2000; ep2_ch1()->SetIceConfig( - CreateIceConfig(2000, webrtc::GATHER_ONCE, backup_ping_interval)); + CreateIceConfig(2000, GATHER_ONCE, backup_ping_interval)); // After the state becomes COMPLETED, the backup connection will be pinged // once every `backup_ping_interval` milliseconds. - ASSERT_THAT(webrtc::WaitUntil([&] { return ep2_ch1()->GetState(); }, - Eq(IceTransportStateInternal::STATE_COMPLETED)), - webrtc::IsRtcOk()); + ASSERT_THAT(WaitUntil([&] { return ep2_ch1()->GetState(); }, + Eq(IceTransportStateInternal::STATE_COMPLETED)), + IsRtcOk()); auto connections = ep2_ch1()->connections(); ASSERT_EQ(2U, connections.size()); Connection* backup_conn = GetBackupConnection(ep2_ch1()); - EXPECT_THAT( - webrtc::WaitUntil([&] { return backup_conn->writable(); }, IsTrue(), + EXPECT_THAT(WaitUntil([&] { return backup_conn->writable(); }, IsTrue(), {.timeout = TimeDelta::Millis(kMediumTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); int64_t last_ping_response_ms = backup_conn->last_ping_response_received(); - EXPECT_THAT(webrtc::WaitUntil( - [&] { return backup_conn->last_ping_response_received(); }, - Gt(last_ping_response_ms), - {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + EXPECT_THAT( + WaitUntil([&] { return backup_conn->last_ping_response_received(); }, + Gt(last_ping_response_ms), + {.timeout = TimeDelta::Millis(kDefaultTimeout)}), + IsRtcOk()); int time_elapsed = backup_conn->last_ping_response_received() - last_ping_response_ms; RTC_LOG(LS_INFO) << "Time elapsed: " << time_elapsed; @@ -3355,35 +3355,33 @@ TEST_F(P2PTransportChannelMultihomedTest, TestStableWritableRate) { // Create channels and let them go writable, as usual. CreateChannels(env); EXPECT_THAT( - webrtc::WaitUntil([&] { return CheckConnected(ep1_ch1(), ep2_ch1()); }, - IsTrue()), - webrtc::IsRtcOk()); + WaitUntil([&] { return CheckConnected(ep1_ch1(), ep2_ch1()); }, IsTrue()), + IsRtcOk()); // Set a value larger than the default value of 2500 ms int ping_interval_ms = 3456; - IceConfig config = CreateIceConfig(2 * ping_interval_ms, webrtc::GATHER_ONCE); + IceConfig config = CreateIceConfig(2 * ping_interval_ms, GATHER_ONCE); config.stable_writable_connection_ping_interval = ping_interval_ms; ep2_ch1()->SetIceConfig(config); // After the state becomes COMPLETED and is stable and writable, the // connection will be pinged once every `ping_interval_ms` milliseconds. - ASSERT_THAT(webrtc::WaitUntil([&] { return ep2_ch1()->GetState(); }, - Eq(IceTransportStateInternal::STATE_COMPLETED)), - webrtc::IsRtcOk()); + ASSERT_THAT(WaitUntil([&] { return ep2_ch1()->GetState(); }, + Eq(IceTransportStateInternal::STATE_COMPLETED)), + IsRtcOk()); auto connections = ep2_ch1()->connections(); ASSERT_EQ(2U, connections.size()); Connection* conn = GetBestConnection(ep2_ch1()); - EXPECT_THAT(webrtc::WaitUntil([&] { return conn->writable(); }, IsTrue(), - {.timeout = TimeDelta::Millis(kMediumTimeout)}), - webrtc::IsRtcOk()); + EXPECT_THAT(WaitUntil([&] { return conn->writable(); }, IsTrue(), + {.timeout = TimeDelta::Millis(kMediumTimeout)}), + IsRtcOk()); int64_t last_ping_response_ms; // Burn through some pings so the connection is stable. for (int i = 0; i < 5; i++) { last_ping_response_ms = conn->last_ping_response_received(); - EXPECT_THAT( - webrtc::WaitUntil([&] { return conn->last_ping_response_received(); }, + EXPECT_THAT(WaitUntil([&] { return conn->last_ping_response_received(); }, Gt(last_ping_response_ms), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); } EXPECT_TRUE(conn->stable(last_ping_response_ms)) << "Connection not stable"; int time_elapsed = @@ -3405,16 +3403,16 @@ TEST_F(P2PTransportChannelMultihomedTest, TestGetState) { CreateChannels(env); // Both transport channels will reach STATE_COMPLETED quickly. - EXPECT_THAT(webrtc::WaitUntil([&] { return ep1_ch1()->GetState(); }, - Eq(IceTransportStateInternal::STATE_COMPLETED), - {.timeout = TimeDelta::Millis(kShortTimeout), - .clock = &clock}), - webrtc::IsRtcOk()); - EXPECT_THAT(webrtc::WaitUntil([&] { return ep2_ch1()->GetState(); }, - Eq(IceTransportStateInternal::STATE_COMPLETED), - {.timeout = TimeDelta::Millis(kShortTimeout), - .clock = &clock}), - webrtc::IsRtcOk()); + EXPECT_THAT( + WaitUntil([&] { return ep1_ch1()->GetState(); }, + Eq(IceTransportStateInternal::STATE_COMPLETED), + {.timeout = TimeDelta::Millis(kShortTimeout), .clock = &clock}), + IsRtcOk()); + EXPECT_THAT( + WaitUntil([&] { return ep2_ch1()->GetState(); }, + Eq(IceTransportStateInternal::STATE_COMPLETED), + {.timeout = TimeDelta::Millis(kShortTimeout), .clock = &clock}), + IsRtcOk()); DestroyChannels(); } @@ -3429,17 +3427,17 @@ TEST_F(P2PTransportChannelMultihomedTest, TestNetworkBecomesInactive) { AddAddress(0, kPublicAddrs[0]); AddAddress(1, kPublicAddrs[1]); // Create channels and let them go writable, as usual. - IceConfig ep1_config = CreateIceConfig(2000, webrtc::GATHER_CONTINUALLY); - IceConfig ep2_config = CreateIceConfig(2000, webrtc::GATHER_ONCE); + IceConfig ep1_config = CreateIceConfig(2000, GATHER_CONTINUALLY); + IceConfig ep2_config = CreateIceConfig(2000, GATHER_ONCE); CreateChannels(env, ep1_config, ep2_config); SetAllocatorFlags(0, kOnlyLocalPorts); SetAllocatorFlags(1, kOnlyLocalPorts); ASSERT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return CheckConnected(ep1_ch1(), ep2_ch1()); }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); // More than one port has been created. EXPECT_LE(1U, ep1_ch1()->ports().size()); // Endpoint 1 enabled continual gathering; the port will be removed @@ -3447,10 +3445,9 @@ TEST_F(P2PTransportChannelMultihomedTest, TestNetworkBecomesInactive) { RemoveAddress(0, kPublicAddrs[0]); EXPECT_TRUE(ep1_ch1()->ports().empty()); // The remote candidates will be removed eventually. - EXPECT_THAT( - webrtc::WaitUntil([&] { return ep2_ch1()->remote_candidates().empty(); }, + EXPECT_THAT(WaitUntil([&] { return ep2_ch1()->remote_candidates().empty(); }, IsTrue(), {.clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); size_t num_ports = ep2_ch1()->ports().size(); EXPECT_LE(1U, num_ports); @@ -3460,11 +3457,10 @@ TEST_F(P2PTransportChannelMultihomedTest, TestNetworkBecomesInactive) { // other participant will not be removed. RemoveAddress(1, kPublicAddrs[1]); - EXPECT_THAT( - webrtc::WaitUntil( - [&] { return ep2_ch1()->ports().size(); }, Eq(0U), - {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + EXPECT_THAT(WaitUntil([&] { return ep2_ch1()->ports().size(); }, Eq(0U), + {.timeout = TimeDelta::Millis(kDefaultTimeout), + .clock = &clock}), + IsRtcOk()); SIMULATED_WAIT(ep1_ch1()->remote_candidates().empty(), 500, clock); EXPECT_EQ(num_remote_candidates, ep1_ch1()->remote_candidates().size()); @@ -3483,40 +3479,40 @@ TEST_F(P2PTransportChannelMultihomedTest, AddAddress(1, cellular[1], "test_cell1", ADAPTER_TYPE_CELLULAR); // Set continual gathering policy. IceConfig continual_gathering_config = - CreateIceConfig(1000, webrtc::GATHER_CONTINUALLY); + CreateIceConfig(1000, GATHER_CONTINUALLY); CreateChannels(env, continual_gathering_config, continual_gathering_config); SetAllocatorFlags(0, kOnlyLocalPorts); SetAllocatorFlags(1, kOnlyLocalPorts); - EXPECT_THAT(webrtc::WaitUntil( - [&] { return CheckConnected(ep1_ch1(), ep2_ch1()); }, - IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + EXPECT_THAT( + WaitUntil([&] { return CheckConnected(ep1_ch1(), ep2_ch1()); }, IsTrue(), + {.timeout = TimeDelta::Millis(kDefaultTimeout)}), + IsRtcOk()); // Add a new wifi interface on end point 2. We should expect a new connection // to be created and the new one will be the best connection. AddAddress(1, wifi[1], "test_wifi1", ADAPTER_TYPE_WIFI); const Connection* conn; - EXPECT_THAT(webrtc::WaitUntil( + EXPECT_THAT(WaitUntil( [&] { return (conn = ep1_ch1()->selected_connection()) != nullptr && HasRemoteAddress(conn, wifi[1]); }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); - EXPECT_THAT(webrtc::WaitUntil( + IsRtcOk()); + EXPECT_THAT(WaitUntil( [&] { return (conn = ep2_ch1()->selected_connection()) != nullptr && HasLocalAddress(conn, wifi[1]); }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); // Add a new cellular interface on end point 1, we should expect a new // backup connection created using this new interface. AddAddress(0, cellular[0], "test_cellular0", ADAPTER_TYPE_CELLULAR); - EXPECT_THAT(webrtc::WaitUntil( + EXPECT_THAT(WaitUntil( [&] { return ep1_ch1()->GetState() == IceTransportStateInternal::STATE_COMPLETED && @@ -3531,8 +3527,8 @@ TEST_F(P2PTransportChannelMultihomedTest, }); }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); - EXPECT_THAT(webrtc::WaitUntil( + IsRtcOk()); + EXPECT_THAT(WaitUntil( [&] { return ep2_ch1()->GetState() == IceTransportStateInternal::STATE_COMPLETED && @@ -3547,7 +3543,7 @@ TEST_F(P2PTransportChannelMultihomedTest, }); }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); DestroyChannels(); } @@ -3566,18 +3562,18 @@ TEST_F(P2PTransportChannelMultihomedTest, // Set continual gathering policy. IceConfig continual_gathering_config = - CreateIceConfig(1000, webrtc::GATHER_CONTINUALLY); + CreateIceConfig(1000, GATHER_CONTINUALLY); // Create channels and let them go writable, as usual. CreateChannels(env, continual_gathering_config, continual_gathering_config); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return CheckCandidatePairAndConnected( ep1_ch1(), ep2_ch1(), kPublicAddrs[0], kPublicAddrs[1]); }, IsTrue(), {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); // Add the new address first and then remove the other one. RTC_LOG(LS_INFO) << "Draining..."; @@ -3585,28 +3581,28 @@ TEST_F(P2PTransportChannelMultihomedTest, RemoveAddress(1, kPublicAddrs[1]); // We should switch to use the alternate address after an exchange of pings. EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return CheckCandidatePairAndConnected( ep1_ch1(), ep2_ch1(), kPublicAddrs[0], kAlternateAddrs[1]); }, IsTrue(), {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); // Remove one address first and then add another address. RTC_LOG(LS_INFO) << "Draining again..."; RemoveAddress(1, kAlternateAddrs[1]); AddAddress(1, kAlternateAddrs[0]); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return CheckCandidatePairAndConnected( ep1_ch1(), ep2_ch1(), kPublicAddrs[0], kAlternateAddrs[0]); }, IsTrue(), {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); DestroyChannels(); } @@ -3627,31 +3623,31 @@ TEST_F(P2PTransportChannelMultihomedTest, TestRestoreBackupConnection) { SetAllocatorFlags(1, kOnlyLocalPorts); // Create channels and let them go writable, as usual. - IceConfig config = CreateIceConfig(1000, webrtc::GATHER_CONTINUALLY); + IceConfig config = CreateIceConfig(1000, GATHER_CONTINUALLY); config.regather_on_failed_networks_interval = 2000; CreateChannels(env, config, config); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return CheckCandidatePairAndConnected(ep1_ch1(), ep2_ch1(), wifi[0], wifi[1]); }, IsTrue(), {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); // Destroy all backup connections. DestroyAllButBestConnection(ep1_ch1()); // Ensure the backup connection is removed first. EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return GetConnectionWithLocalAddress(ep1_ch1(), cellular[0]); }, Eq(nullptr), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); const Connection* conn; EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return (conn = GetConnectionWithLocalAddress( ep1_ch1(), cellular[0])) != nullptr && @@ -3659,7 +3655,7 @@ TEST_F(P2PTransportChannelMultihomedTest, TestRestoreBackupConnection) { }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); DestroyChannels(); } @@ -3675,14 +3671,14 @@ TEST_F(P2PTransportChannelMultihomedTest, TestVpnDefault) { IceConfig config; CreateChannels(env, config, config, false); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return CheckConnected(ep1_ch1(), ep2_ch1()) && !ep1_ch1()->selected_connection()->network()->IsVpn(); }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); } TEST_F(P2PTransportChannelMultihomedTest, TestVpnPreferVpn) { @@ -3699,28 +3695,28 @@ TEST_F(P2PTransportChannelMultihomedTest, TestVpnPreferVpn) { RTC_LOG(LS_INFO) << "KESO: config.vpn_preference: " << config.vpn_preference; CreateChannels(env, config, config, false); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return CheckConnected(ep1_ch1(), ep2_ch1()) && ep1_ch1()->selected_connection()->network()->IsVpn(); }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); // Block VPN. - fw()->AddRule(false, webrtc::FP_ANY, webrtc::FD_ANY, kAlternateAddrs[0]); + fw()->AddRule(false, FP_ANY, FD_ANY, kAlternateAddrs[0]); // Check that it switches to non-VPN EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return CheckConnected(ep1_ch1(), ep2_ch1()) && !ep1_ch1()->selected_connection()->network()->IsVpn(); }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); } TEST_F(P2PTransportChannelMultihomedTest, TestVpnAvoidVpn) { @@ -3736,28 +3732,28 @@ TEST_F(P2PTransportChannelMultihomedTest, TestVpnAvoidVpn) { config.vpn_preference = VpnPreference::kAvoidVpn; CreateChannels(env, config, config, false); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return CheckConnected(ep1_ch1(), ep2_ch1()) && !ep1_ch1()->selected_connection()->network()->IsVpn(); }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); // Block non-VPN. - fw()->AddRule(false, webrtc::FP_ANY, webrtc::FD_ANY, kPublicAddrs[0]); + fw()->AddRule(false, FP_ANY, FD_ANY, kPublicAddrs[0]); // Check that it switches to VPN EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return CheckConnected(ep1_ch1(), ep2_ch1()) && ep1_ch1()->selected_connection()->network()->IsVpn(); }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); } TEST_F(P2PTransportChannelMultihomedTest, TestVpnNeverVpn) { @@ -3773,25 +3769,25 @@ TEST_F(P2PTransportChannelMultihomedTest, TestVpnNeverVpn) { config.vpn_preference = VpnPreference::kNeverUseVpn; CreateChannels(env, config, config, false); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return CheckConnected(ep1_ch1(), ep2_ch1()) && !ep1_ch1()->selected_connection()->network()->IsVpn(); }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); // Block non-VPN. - fw()->AddRule(false, webrtc::FP_ANY, webrtc::FD_ANY, kPublicAddrs[0]); + fw()->AddRule(false, FP_ANY, FD_ANY, kPublicAddrs[0]); // Check that it does not switches to VPN clock.AdvanceTime(TimeDelta::Millis(kDefaultTimeout)); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return !CheckConnected(ep1_ch1(), ep2_ch1()); }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); } TEST_F(P2PTransportChannelMultihomedTest, TestVpnOnlyVpn) { @@ -3807,25 +3803,25 @@ TEST_F(P2PTransportChannelMultihomedTest, TestVpnOnlyVpn) { config.vpn_preference = VpnPreference::kOnlyUseVpn; CreateChannels(env, config, config, false); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return CheckConnected(ep1_ch1(), ep2_ch1()) && ep1_ch1()->selected_connection()->network()->IsVpn(); }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); // Block VPN. - fw()->AddRule(false, webrtc::FP_ANY, webrtc::FD_ANY, kAlternateAddrs[0]); + fw()->AddRule(false, FP_ANY, FD_ANY, kAlternateAddrs[0]); // Check that it does not switch to non-VPN clock.AdvanceTime(TimeDelta::Millis(kDefaultTimeout)); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return !CheckConnected(ep1_ch1(), ep2_ch1()); }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); } TEST_F(P2PTransportChannelMultihomedTest, StunDictionaryPerformsSync) { @@ -3841,7 +3837,7 @@ TEST_F(P2PTransportChannelMultihomedTest, StunDictionaryPerformsSync) { CreateChannels(env); MockFunction)> + ArrayView)> view_updated_func; ep2_ch1()->AddDictionaryViewUpdatedCallback( "tag", view_updated_func.AsStdFunction()); @@ -3859,10 +3855,10 @@ TEST_F(P2PTransportChannelMultihomedTest, StunDictionaryPerformsSync) { }); EXPECT_CALL(writer_synced_func, Call).Times(1); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return CheckConnected(ep1_ch1(), ep2_ch1()); }, IsTrue(), {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); } // A collection of tests which tests a single P2PTransportChannel by sending @@ -3878,7 +3874,7 @@ class P2PTransportChannelPingTest : public ::testing::Test, protected: void PrepareChannel(P2PTransportChannel* ch) { - ch->SetIceRole(webrtc::ICEROLE_CONTROLLING); + ch->SetIceRole(ICEROLE_CONTROLLING); ch->SetIceParameters(kIceParams[0]); ch->SetRemoteIceParameters(kIceParams[1]); ch->SignalNetworkRouteChanged.connect( @@ -3898,17 +3894,16 @@ class P2PTransportChannelPingTest : public ::testing::Test, int port_num, ThreadProcessingFakeClock* clock = nullptr) { if (clock == nullptr) { - EXPECT_THAT( - webrtc::WaitUntil([&] { return GetConnectionTo(ch, ip, port_num); }, + EXPECT_THAT(WaitUntil([&] { return GetConnectionTo(ch, ip, port_num); }, Ne(nullptr), {.timeout = TimeDelta::Millis(kMediumTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); } else { EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return GetConnectionTo(ch, ip, port_num); }, Ne(nullptr), {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &*clock}), - webrtc::IsRtcOk()); + IsRtcOk()); } return GetConnectionTo(ch, ip, port_num); } @@ -3963,11 +3958,11 @@ class P2PTransportChannelPingTest : public ::testing::Test, channel->AddRemoteCandidate( CreateUdpCandidate(IceCandidateType::kHost, ip_addr, port, priority)); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return GetConnectionTo(channel, ip_addr, port); }, Ne(nullptr), {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &*clock}), - webrtc::IsRtcOk()); + IsRtcOk()); Connection* conn = GetConnectionTo(channel, ip_addr, port); if (conn && writable) { @@ -4014,8 +4009,7 @@ class P2PTransportChannelPingTest : public ::testing::Test, ByteBufferWriter buf; msg.Write(&buf); conn->OnReadPacket(ReceivedIpPacket::CreateFromLegacy( - reinterpret_cast(buf.Data()), buf.Length(), - webrtc::TimeMicros())); + reinterpret_cast(buf.Data()), buf.Length(), TimeMicros())); } void ReceivePingOnConnection(Connection* conn, @@ -4149,13 +4143,13 @@ TEST_F(P2PTransportChannelPingTest, TestAllConnectionsPingedSufficiently) { // is not pruned. conn1->ReceivedPingResponse(LOW_RTT, "id"); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return conn1->num_pings_sent() >= MIN_PINGS_AT_WEAK_PING_INTERVAL && conn2->num_pings_sent() >= MIN_PINGS_AT_WEAK_PING_INTERVAL; }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); } // Verify that the connections are pinged at the right time. @@ -4183,7 +4177,7 @@ TEST_F(P2PTransportChannelPingTest, TestStunPingIntervals) { SIMULATED_WAIT(conn->num_pings_sent() >= MIN_PINGS_AT_WEAK_PING_INTERVAL, kDefaultTimeout, clock); int64_t ping_interval_ms = (clock.TimeNanos() - start) / - webrtc::kNumNanosecsPerMillisec / + kNumNanosecsPerMillisec / (MIN_PINGS_AT_WEAK_PING_INTERVAL - 1); EXPECT_EQ(ping_interval_ms, WEAK_PING_INTERVAL); @@ -4196,8 +4190,7 @@ TEST_F(P2PTransportChannelPingTest, TestStunPingIntervals) { // to converge the RTT. SIMULATED_WAIT(conn->num_pings_sent() == ping_sent_before + 1, kMediumTimeout, clock); - ping_interval_ms = - (clock.TimeNanos() - start) / webrtc::kNumNanosecsPerMillisec; + ping_interval_ms = (clock.TimeNanos() - start) / kNumNanosecsPerMillisec; EXPECT_GE(ping_interval_ms, WEAK_OR_STABILIZING_WRITABLE_CONNECTION_PING_INTERVAL); EXPECT_LE( @@ -4215,8 +4208,7 @@ TEST_F(P2PTransportChannelPingTest, TestStunPingIntervals) { start = clock.TimeNanos(); SIMULATED_WAIT(conn->num_pings_sent() == ping_sent_before + 1, kMediumTimeout, clock); - ping_interval_ms = - (clock.TimeNanos() - start) / webrtc::kNumNanosecsPerMillisec; + ping_interval_ms = (clock.TimeNanos() - start) / kNumNanosecsPerMillisec; EXPECT_GE(ping_interval_ms, STRONG_AND_STABLE_WRITABLE_CONNECTION_PING_INTERVAL); EXPECT_LE( @@ -4227,14 +4219,12 @@ TEST_F(P2PTransportChannelPingTest, TestStunPingIntervals) { conn->ReceivedPingResponse(LOW_RTT, "id"); // Create a in-flight ping. - conn->Ping(clock.TimeNanos() / webrtc::kNumNanosecsPerMillisec); + conn->Ping(clock.TimeNanos() / kNumNanosecsPerMillisec); start = clock.TimeNanos(); // In-flight ping timeout and the connection will be unstable. - SIMULATED_WAIT( - !conn->stable(clock.TimeNanos() / webrtc::kNumNanosecsPerMillisec), - kMediumTimeout, clock); - int64_t duration_ms = - (clock.TimeNanos() - start) / webrtc::kNumNanosecsPerMillisec; + SIMULATED_WAIT(!conn->stable(clock.TimeNanos() / kNumNanosecsPerMillisec), + kMediumTimeout, clock); + int64_t duration_ms = (clock.TimeNanos() - start) / kNumNanosecsPerMillisec; EXPECT_GE(duration_ms, 2 * conn->rtt() - RTT_RANGE); EXPECT_LE(duration_ms, 2 * conn->rtt() + RTT_RANGE); // The connection become unstable due to not receiving ping responses. @@ -4247,8 +4237,7 @@ TEST_F(P2PTransportChannelPingTest, TestStunPingIntervals) { ping_sent_before = conn->num_pings_sent(); SIMULATED_WAIT(conn->num_pings_sent() == ping_sent_before + 1, kMediumTimeout, clock); - ping_interval_ms = - (clock.TimeNanos() - start) / webrtc::kNumNanosecsPerMillisec; + ping_interval_ms = (clock.TimeNanos() - start) / kNumNanosecsPerMillisec; EXPECT_GE(ping_interval_ms, WEAK_OR_STABILIZING_WRITABLE_CONNECTION_PING_INTERVAL); EXPECT_LE( @@ -4264,14 +4253,13 @@ TEST_F(P2PTransportChannelPingTest, PingingStartedAsSoonAsPossible) { FakePortAllocator pa(env, ss()); P2PTransportChannel ch("TestChannel", 1, &pa, &env.field_trials()); - ch.SetIceRole(webrtc::ICEROLE_CONTROLLING); + ch.SetIceRole(ICEROLE_CONTROLLING); ch.SetIceParameters(kIceParams[0]); ch.MaybeStartGathering(); - EXPECT_THAT( - webrtc::WaitUntil([&] { return ch.gathering_state(); }, + EXPECT_THAT(WaitUntil([&] { return ch.gathering_state(); }, Eq(IceGatheringState::kIceGatheringComplete), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); // Simulate a binding request being received, creating a peer reflexive // candidate pair while we still don't have remote ICE parameters. @@ -4283,8 +4271,8 @@ TEST_F(P2PTransportChannelPingTest, PingingStartedAsSoonAsPossible) { prflx_priority)); Port* port = GetPort(&ch); ASSERT_NE(nullptr, port); - port->SignalUnknownAddress(port, SocketAddress("1.1.1.1", 1), - webrtc::PROTO_UDP, &request, kIceUfrag[1], false); + port->SignalUnknownAddress(port, SocketAddress("1.1.1.1", 1), PROTO_UDP, + &request, kIceUfrag[1], false); Connection* conn = GetConnectionTo(&ch, "1.1.1.1", 1); ASSERT_NE(nullptr, conn); @@ -4297,9 +4285,9 @@ TEST_F(P2PTransportChannelPingTest, PingingStartedAsSoonAsPossible) { // the first ping is sent as soon as possible, within one simulated clock // tick. ch.SetRemoteIceParameters(kIceParams[1]); - EXPECT_THAT(webrtc::WaitUntil([&] { return conn->num_pings_sent(); }, Gt(0), - {.clock = &clock}), - webrtc::IsRtcOk()); + EXPECT_THAT(WaitUntil([&] { return conn->num_pings_sent(); }, Gt(0), + {.clock = &clock}), + IsRtcOk()); } TEST_F(P2PTransportChannelPingTest, TestNoTriggeredChecksWhenWritable) { @@ -4363,11 +4351,10 @@ TEST_F(P2PTransportChannelPingTest, TestSignalStateChanged) { // Pruning the connection reduces the set of active connections and changes // the channel state. conn1->Prune(); - EXPECT_THAT( - webrtc::WaitUntil([&] { return channel_state(); }, + EXPECT_THAT(WaitUntil([&] { return channel_state(); }, Eq(IceTransportStateInternal::STATE_FAILED), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); } // Test adding remote candidates with different ufrags. If a remote candidate @@ -4411,10 +4398,10 @@ TEST_F(P2PTransportChannelPingTest, TestAddRemoteCandidateWithVariousUfrags) { ch.AddRemoteCandidate(CreateUdpCandidate(IceCandidateType::kHost, "3.3.3.3", 3, 0, kIceUfrag[2])); Connection* conn3 = nullptr; - ASSERT_THAT(webrtc::WaitUntil( - [&] { return conn3 = GetConnectionTo(&ch, "3.3.3.3", 3); }, - Ne(nullptr), {.timeout = TimeDelta::Millis(kMediumTimeout)}), - webrtc::IsRtcOk()); + ASSERT_THAT( + WaitUntil([&] { return conn3 = GetConnectionTo(&ch, "3.3.3.3", 3); }, + Ne(nullptr), {.timeout = TimeDelta::Millis(kMediumTimeout)}), + IsRtcOk()); const Candidate& new_candidate = conn3->remote_candidate(); EXPECT_EQ(kIcePwd[2], new_candidate.password()); EXPECT_EQ(1U, new_candidate.generation()); @@ -4456,16 +4443,15 @@ TEST_F(P2PTransportChannelPingTest, ConnectionResurrection) { conn2->ReceivedPingResponse(LOW_RTT, "id"); // Wait for conn2 to be selected. - EXPECT_THAT( - webrtc::WaitUntil([&] { return ch.selected_connection(); }, Eq(conn2), + EXPECT_THAT(WaitUntil([&] { return ch.selected_connection(); }, Eq(conn2), {.timeout = TimeDelta::Millis(kMediumTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); // Destroy the connection to test SignalUnknownAddress. ch.RemoveConnectionForTest(conn1); - EXPECT_THAT(webrtc::WaitUntil( - [&] { return GetConnectionTo(&ch, "1.1.1.1", 1); }, - Eq(nullptr), {.timeout = TimeDelta::Millis(kMediumTimeout)}), - webrtc::IsRtcOk()); + EXPECT_THAT( + WaitUntil([&] { return GetConnectionTo(&ch, "1.1.1.1", 1); }, Eq(nullptr), + {.timeout = TimeDelta::Millis(kMediumTimeout)}), + IsRtcOk()); // Create a minimal STUN message with prflx priority. IceMessage request(STUN_BINDING_REQUEST); @@ -4478,15 +4464,15 @@ TEST_F(P2PTransportChannelPingTest, ConnectionResurrection) { Port* port = GetPort(&ch); // conn1 should be resurrected with original priority. - port->SignalUnknownAddress(port, SocketAddress("1.1.1.1", 1), - webrtc::PROTO_UDP, &request, kIceUfrag[1], false); + port->SignalUnknownAddress(port, SocketAddress("1.1.1.1", 1), PROTO_UDP, + &request, kIceUfrag[1], false); conn1 = WaitForConnectionTo(&ch, "1.1.1.1", 1); ASSERT_TRUE(conn1 != nullptr); EXPECT_EQ(conn1->remote_candidate().priority(), remote_priority); // conn3, a real prflx connection, should have prflx priority. - port->SignalUnknownAddress(port, SocketAddress("3.3.3.3", 1), - webrtc::PROTO_UDP, &request, kIceUfrag[1], false); + port->SignalUnknownAddress(port, SocketAddress("3.3.3.3", 1), PROTO_UDP, + &request, kIceUfrag[1], false); Connection* conn3 = WaitForConnectionTo(&ch, "3.3.3.3", 1); ASSERT_TRUE(conn3 != nullptr); EXPECT_EQ(conn3->remote_candidate().priority(), prflx_priority); @@ -4502,7 +4488,7 @@ TEST_F(P2PTransportChannelPingTest, TestReceivingStateChange) { // small. EXPECT_LE(1000, ch.config().receiving_timeout_or_default()); EXPECT_LE(200, ch.check_receiving_interval()); - ch.SetIceConfig(CreateIceConfig(500, webrtc::GATHER_ONCE)); + ch.SetIceConfig(CreateIceConfig(500, GATHER_ONCE)); EXPECT_EQ(500, ch.config().receiving_timeout_or_default()); EXPECT_EQ(50, ch.check_receiving_interval()); ch.MaybeStartGathering(); @@ -4514,16 +4500,16 @@ TEST_F(P2PTransportChannelPingTest, TestReceivingStateChange) { clock.AdvanceTime(TimeDelta::Seconds(1)); conn1->ReceivedPing(); conn1->OnReadPacket( - ReceivedIpPacket::CreateFromLegacy("ABC", 3, webrtc::TimeMicros())); + ReceivedIpPacket::CreateFromLegacy("ABC", 3, TimeMicros())); - EXPECT_THAT(webrtc::WaitUntil([&] { return ch.receiving(); }, IsTrue(), - {.timeout = TimeDelta::Millis(kShortTimeout), - .clock = &clock}), - webrtc::IsRtcOk()); - EXPECT_THAT(webrtc::WaitUntil([&] { return !ch.receiving(); }, IsTrue(), - {.timeout = TimeDelta::Millis(kShortTimeout), - .clock = &clock}), - webrtc::IsRtcOk()); + EXPECT_THAT( + WaitUntil([&] { return ch.receiving(); }, IsTrue(), + {.timeout = TimeDelta::Millis(kShortTimeout), .clock = &clock}), + IsRtcOk()); + EXPECT_THAT( + WaitUntil([&] { return !ch.receiving(); }, IsTrue(), + {.timeout = TimeDelta::Millis(kShortTimeout), .clock = &clock}), + IsRtcOk()); } // The controlled side will select a connection as the "selected connection" @@ -4537,7 +4523,7 @@ TEST_F(P2PTransportChannelPingTest, TestSelectConnectionBeforeNomination) { FakePortAllocator pa(env, ss()); P2PTransportChannel ch("receiving state change", 1, &pa, &env.field_trials()); PrepareChannel(&ch); - ch.SetIceRole(webrtc::ICEROLE_CONTROLLED); + ch.SetIceRole(ICEROLE_CONTROLLED); ch.MaybeStartGathering(); ch.AddRemoteCandidate( CreateUdpCandidate(IceCandidateType::kHost, "1.1.1.1", 1, 1)); @@ -4553,10 +4539,9 @@ TEST_F(P2PTransportChannelPingTest, TestSelectConnectionBeforeNomination) { // A connection needs to be writable before it is selected for transmission. conn1->ReceivedPingResponse(LOW_RTT, "id"); - EXPECT_THAT( - webrtc::WaitUntil([&] { return ch.selected_connection(); }, Eq(conn1), + EXPECT_THAT(WaitUntil([&] { return ch.selected_connection(); }, Eq(conn1), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_TRUE(CandidatePairMatchesNetworkRoute(conn1)); EXPECT_TRUE(ConnectionMatchesChangeEvent( conn1, "remote candidate generation maybe changed")); @@ -4569,10 +4554,9 @@ TEST_F(P2PTransportChannelPingTest, TestSelectConnectionBeforeNomination) { Connection* conn2 = WaitForConnectionTo(&ch, "2.2.2.2", 2); ASSERT_TRUE(conn2 != nullptr); conn2->ReceivedPingResponse(LOW_RTT, "id"); - EXPECT_THAT( - webrtc::WaitUntil([&] { return ch.selected_connection(); }, Eq(conn2), + EXPECT_THAT(WaitUntil([&] { return ch.selected_connection(); }, Eq(conn2), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_TRUE(CandidatePairMatchesNetworkRoute(conn2)); EXPECT_TRUE( ConnectionMatchesChangeEvent(conn2, "candidate pair state changed")); @@ -4618,10 +4602,9 @@ TEST_F(P2PTransportChannelPingTest, TestSelectConnectionBeforeNomination) { reset_channel_ready_to_send(); // The selected connection switches after conn4 becomes writable. conn4->ReceivedPingResponse(LOW_RTT, "id"); - EXPECT_THAT( - webrtc::WaitUntil([&] { return ch.selected_connection(); }, Eq(conn4), + EXPECT_THAT(WaitUntil([&] { return ch.selected_connection(); }, Eq(conn4), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_TRUE(CandidatePairMatchesNetworkRoute(conn4)); EXPECT_TRUE( ConnectionMatchesChangeEvent(conn4, "candidate pair state changed")); @@ -4640,7 +4623,7 @@ TEST_F(P2PTransportChannelPingTest, TestPingOnNomination) { P2PTransportChannel ch("receiving state change", 1, &pa, &env.field_trials()); PrepareChannel(&ch); ch.SetIceConfig(ch.config()); - ch.SetIceRole(webrtc::ICEROLE_CONTROLLED); + ch.SetIceRole(ICEROLE_CONTROLLED); ch.MaybeStartGathering(); ch.AddRemoteCandidate( CreateUdpCandidate(IceCandidateType::kHost, "1.1.1.1", 1, 1)); @@ -4649,10 +4632,9 @@ TEST_F(P2PTransportChannelPingTest, TestPingOnNomination) { // A connection needs to be writable before it is selected for transmission. conn1->ReceivedPingResponse(LOW_RTT, "id"); - EXPECT_THAT( - webrtc::WaitUntil([&] { return ch.selected_connection(); }, Eq(conn1), + EXPECT_THAT(WaitUntil([&] { return ch.selected_connection(); }, Eq(conn1), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_TRUE(CandidatePairMatchesNetworkRoute(conn1)); // When a higher priority candidate comes in, the new connection is chosen @@ -4662,10 +4644,9 @@ TEST_F(P2PTransportChannelPingTest, TestPingOnNomination) { Connection* conn2 = WaitForConnectionTo(&ch, "2.2.2.2", 2); ASSERT_TRUE(conn2 != nullptr); conn2->ReceivedPingResponse(LOW_RTT, "id"); - EXPECT_THAT( - webrtc::WaitUntil([&] { return ch.selected_connection(); }, Eq(conn2), + EXPECT_THAT(WaitUntil([&] { return ch.selected_connection(); }, Eq(conn2), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_TRUE(CandidatePairMatchesNetworkRoute(conn2)); // Now nominate conn1 (low prio), it shall be choosen. @@ -4688,7 +4669,7 @@ TEST_F(P2PTransportChannelPingTest, TestPingOnSwitch) { P2PTransportChannel ch("receiving state change", 1, &pa, &env.field_trials()); PrepareChannel(&ch); ch.SetIceConfig(ch.config()); - ch.SetIceRole(webrtc::ICEROLE_CONTROLLING); + ch.SetIceRole(ICEROLE_CONTROLLING); ch.MaybeStartGathering(); ch.AddRemoteCandidate( CreateUdpCandidate(IceCandidateType::kHost, "1.1.1.1", 1, 1)); @@ -4697,10 +4678,9 @@ TEST_F(P2PTransportChannelPingTest, TestPingOnSwitch) { // A connection needs to be writable before it is selected for transmission. conn1->ReceivedPingResponse(LOW_RTT, "id"); - EXPECT_THAT( - webrtc::WaitUntil([&] { return ch.selected_connection(); }, Eq(conn1), + EXPECT_THAT(WaitUntil([&] { return ch.selected_connection(); }, Eq(conn1), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_TRUE(CandidatePairMatchesNetworkRoute(conn1)); // When a higher priority candidate comes in, the new connection is chosen @@ -4713,10 +4693,9 @@ TEST_F(P2PTransportChannelPingTest, TestPingOnSwitch) { const int before = conn2->num_pings_sent(); conn2->ReceivedPingResponse(LOW_RTT, "id"); - EXPECT_THAT( - webrtc::WaitUntil([&] { return ch.selected_connection(); }, Eq(conn2), + EXPECT_THAT(WaitUntil([&] { return ch.selected_connection(); }, Eq(conn2), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_TRUE(CandidatePairMatchesNetworkRoute(conn2)); // And the additional ping should have been sent directly. @@ -4733,7 +4712,7 @@ TEST_F(P2PTransportChannelPingTest, TestPingOnSelected) { P2PTransportChannel ch("receiving state change", 1, &pa, &env.field_trials()); PrepareChannel(&ch); ch.SetIceConfig(ch.config()); - ch.SetIceRole(webrtc::ICEROLE_CONTROLLING); + ch.SetIceRole(ICEROLE_CONTROLLING); ch.MaybeStartGathering(); ch.AddRemoteCandidate( CreateUdpCandidate(IceCandidateType::kHost, "1.1.1.1", 1, 1)); @@ -4744,10 +4723,9 @@ TEST_F(P2PTransportChannelPingTest, TestPingOnSelected) { // A connection needs to be writable before it is selected for transmission. conn1->ReceivedPingResponse(LOW_RTT, "id"); - EXPECT_THAT( - webrtc::WaitUntil([&] { return ch.selected_connection(); }, Eq(conn1), + EXPECT_THAT(WaitUntil([&] { return ch.selected_connection(); }, Eq(conn1), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_TRUE(CandidatePairMatchesNetworkRoute(conn1)); // And the additional ping should have been sent directly. @@ -4765,7 +4743,7 @@ TEST_F(P2PTransportChannelPingTest, TestSelectConnectionFromUnknownAddress) { FakePortAllocator pa(env, ss()); P2PTransportChannel ch("receiving state change", 1, &pa, &env.field_trials()); PrepareChannel(&ch); - ch.SetIceRole(webrtc::ICEROLE_CONTROLLED); + ch.SetIceRole(ICEROLE_CONTROLLED); ch.MaybeStartGathering(); // A minimal STUN message with prflx priority. IceMessage request(STUN_BINDING_REQUEST); @@ -4775,17 +4753,16 @@ TEST_F(P2PTransportChannelPingTest, TestSelectConnectionFromUnknownAddress) { request.AddAttribute(std::make_unique(STUN_ATTR_PRIORITY, prflx_priority)); TestUDPPort* port = static_cast(GetPort(&ch)); - port->SignalUnknownAddress(port, SocketAddress("1.1.1.1", 1), - webrtc::PROTO_UDP, &request, kIceUfrag[1], false); + port->SignalUnknownAddress(port, SocketAddress("1.1.1.1", 1), PROTO_UDP, + &request, kIceUfrag[1], false); Connection* conn1 = WaitForConnectionTo(&ch, "1.1.1.1", 1); ASSERT_TRUE(conn1 != nullptr); EXPECT_EQ(conn1->stats().sent_ping_responses, 1u); EXPECT_NE(conn1, ch.selected_connection()); conn1->ReceivedPingResponse(LOW_RTT, "id"); - EXPECT_THAT( - webrtc::WaitUntil([&] { return ch.selected_connection(); }, Eq(conn1), + EXPECT_THAT(WaitUntil([&] { return ch.selected_connection(); }, Eq(conn1), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); // Another connection is nominated via use_candidate. ch.AddRemoteCandidate( @@ -4803,8 +4780,8 @@ TEST_F(P2PTransportChannelPingTest, TestSelectConnectionFromUnknownAddress) { // Another request with unknown address, it will not be set as the selected // connection because the selected connection was nominated by the controlling // side. - port->SignalUnknownAddress(port, SocketAddress("3.3.3.3", 3), - webrtc::PROTO_UDP, &request, kIceUfrag[1], false); + port->SignalUnknownAddress(port, SocketAddress("3.3.3.3", 3), PROTO_UDP, + &request, kIceUfrag[1], false); Connection* conn3 = WaitForConnectionTo(&ch, "3.3.3.3", 3); ASSERT_TRUE(conn3 != nullptr); EXPECT_EQ(conn3->stats().sent_ping_responses, 1u); @@ -4815,26 +4792,25 @@ TEST_F(P2PTransportChannelPingTest, TestSelectConnectionFromUnknownAddress) { // selected as the selected connection. request.AddAttribute( std::make_unique(STUN_ATTR_USE_CANDIDATE)); - port->SignalUnknownAddress(port, SocketAddress("4.4.4.4", 4), - webrtc::PROTO_UDP, &request, kIceUfrag[1], false); + port->SignalUnknownAddress(port, SocketAddress("4.4.4.4", 4), PROTO_UDP, + &request, kIceUfrag[1], false); Connection* conn4 = WaitForConnectionTo(&ch, "4.4.4.4", 4); ASSERT_TRUE(conn4 != nullptr); EXPECT_EQ(conn4->stats().sent_ping_responses, 1u); // conn4 is not the selected connection yet because it is not writable. EXPECT_EQ(conn2, ch.selected_connection()); conn4->ReceivedPingResponse(LOW_RTT, "id"); // Become writable. - EXPECT_THAT( - webrtc::WaitUntil([&] { return ch.selected_connection(); }, Eq(conn4), + EXPECT_THAT(WaitUntil([&] { return ch.selected_connection(); }, Eq(conn4), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); // Test that the request from an unknown address contains a ufrag from an old // generation. // port->set_sent_binding_response(false); ch.SetRemoteIceParameters(kIceParams[2]); ch.SetRemoteIceParameters(kIceParams[3]); - port->SignalUnknownAddress(port, SocketAddress("5.5.5.5", 5), - webrtc::PROTO_UDP, &request, kIceUfrag[2], false); + port->SignalUnknownAddress(port, SocketAddress("5.5.5.5", 5), PROTO_UDP, + &request, kIceUfrag[2], false); Connection* conn5 = WaitForConnectionTo(&ch, "5.5.5.5", 5); ASSERT_TRUE(conn5 != nullptr); EXPECT_EQ(conn5->stats().sent_ping_responses, 1u); @@ -4850,17 +4826,16 @@ TEST_F(P2PTransportChannelPingTest, TestSelectConnectionBasedOnMediaReceived) { FakePortAllocator pa(env, ss()); P2PTransportChannel ch("receiving state change", 1, &pa, &env.field_trials()); PrepareChannel(&ch); - ch.SetIceRole(webrtc::ICEROLE_CONTROLLED); + ch.SetIceRole(ICEROLE_CONTROLLED); ch.MaybeStartGathering(); ch.AddRemoteCandidate( CreateUdpCandidate(IceCandidateType::kHost, "1.1.1.1", 1, 10)); Connection* conn1 = WaitForConnectionTo(&ch, "1.1.1.1", 1); ASSERT_TRUE(conn1 != nullptr); conn1->ReceivedPingResponse(LOW_RTT, "id"); - EXPECT_THAT( - webrtc::WaitUntil([&] { return ch.selected_connection(); }, Eq(conn1), + EXPECT_THAT(WaitUntil([&] { return ch.selected_connection(); }, Eq(conn1), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); // If a data packet is received on conn2, the selected connection should // switch to conn2 because the controlled side must mirror the media path @@ -4871,7 +4846,7 @@ TEST_F(P2PTransportChannelPingTest, TestSelectConnectionBasedOnMediaReceived) { ASSERT_TRUE(conn2 != nullptr); conn2->ReceivedPingResponse(LOW_RTT, "id"); // Become writable and receiving. conn2->OnReadPacket( - ReceivedIpPacket::CreateFromLegacy("ABC", 3, webrtc::TimeMicros())); + ReceivedIpPacket::CreateFromLegacy("ABC", 3, TimeMicros())); EXPECT_EQ(conn2, ch.selected_connection()); conn2->ReceivedPingResponse(LOW_RTT, "id"); // Become writable. @@ -4886,27 +4861,25 @@ TEST_F(P2PTransportChannelPingTest, TestSelectConnectionBasedOnMediaReceived) { request.AddAttribute( std::make_unique(STUN_ATTR_USE_CANDIDATE)); Port* port = GetPort(&ch); - port->SignalUnknownAddress(port, SocketAddress("3.3.3.3", 3), - webrtc::PROTO_UDP, &request, kIceUfrag[1], false); + port->SignalUnknownAddress(port, SocketAddress("3.3.3.3", 3), PROTO_UDP, + &request, kIceUfrag[1], false); Connection* conn3 = WaitForConnectionTo(&ch, "3.3.3.3", 3); ASSERT_TRUE(conn3 != nullptr); EXPECT_NE(conn3, ch.selected_connection()); // Not writable yet. conn3->ReceivedPingResponse(LOW_RTT, "id"); // Become writable. - EXPECT_THAT( - webrtc::WaitUntil([&] { return ch.selected_connection(); }, Eq(conn3), + EXPECT_THAT(WaitUntil([&] { return ch.selected_connection(); }, Eq(conn3), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); // Now another data packet will not switch the selected connection because the // selected connection was nominated by the controlling side. conn2->ReceivedPing(); conn2->ReceivedPingResponse(LOW_RTT, "id"); conn2->OnReadPacket( - ReceivedIpPacket::CreateFromLegacy("XYZ", 3, webrtc::TimeMicros())); - EXPECT_THAT( - webrtc::WaitUntil([&] { return ch.selected_connection(); }, Eq(conn3), + ReceivedIpPacket::CreateFromLegacy("XYZ", 3, TimeMicros())); + EXPECT_THAT(WaitUntil([&] { return ch.selected_connection(); }, Eq(conn3), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); } TEST_F(P2PTransportChannelPingTest, @@ -4918,7 +4891,7 @@ TEST_F(P2PTransportChannelPingTest, P2PTransportChannel ch("SwitchSelectedConnection", 1, &pa, &env.field_trials()); PrepareChannel(&ch); - ch.SetIceRole(webrtc::ICEROLE_CONTROLLED); + ch.SetIceRole(ICEROLE_CONTROLLED); ch.MaybeStartGathering(); // The connections have decreasing priority. Connection* conn1 = @@ -4938,13 +4911,13 @@ TEST_F(P2PTransportChannelPingTest, SIMULATED_WAIT(false, 1, clock); conn2->OnReadPacket( - ReceivedIpPacket::CreateFromLegacy("XYZ", 3, webrtc::TimeMicros())); + ReceivedIpPacket::CreateFromLegacy("XYZ", 3, TimeMicros())); EXPECT_EQ(1, reset_selected_candidate_pair_switches()); EXPECT_TRUE(CandidatePairMatchesNetworkRoute(conn2)); // conn1 also receives data; it becomes selected due to priority again. conn1->OnReadPacket( - ReceivedIpPacket::CreateFromLegacy("ABC", 3, webrtc::TimeMicros())); + ReceivedIpPacket::CreateFromLegacy("ABC", 3, TimeMicros())); EXPECT_EQ(1, reset_selected_candidate_pair_switches()); EXPECT_TRUE(CandidatePairMatchesNetworkRoute(conn2)); @@ -4954,7 +4927,7 @@ TEST_F(P2PTransportChannelPingTest, // Need to become writable again because it was pruned. conn2->ReceivedPingResponse(LOW_RTT, "id"); conn2->OnReadPacket( - ReceivedIpPacket::CreateFromLegacy("ABC", 3, webrtc::TimeMicros())); + ReceivedIpPacket::CreateFromLegacy("ABC", 3, TimeMicros())); EXPECT_EQ(1, reset_selected_candidate_pair_switches()); EXPECT_TRUE(CandidatePairMatchesNetworkRoute(conn2)); @@ -4973,7 +4946,7 @@ TEST_F(P2PTransportChannelPingTest, P2PTransportChannel ch("SwitchSelectedConnection", 1, &pa, &env.field_trials()); PrepareChannel(&ch); - ch.SetIceRole(webrtc::ICEROLE_CONTROLLED); + ch.SetIceRole(ICEROLE_CONTROLLED); ch.MaybeStartGathering(); // The connections have decreasing priority. Connection* conn1 = @@ -4988,7 +4961,7 @@ TEST_F(P2PTransportChannelPingTest, SIMULATED_WAIT(false, 1, clock); conn1->OnReadPacket( - ReceivedIpPacket::CreateFromLegacy("XYZ", 3, webrtc::TimeMicros())); + ReceivedIpPacket::CreateFromLegacy("XYZ", 3, TimeMicros())); EXPECT_EQ(1, reset_selected_candidate_pair_switches()); EXPECT_TRUE(CandidatePairMatchesNetworkRoute(conn1)); @@ -5016,7 +4989,7 @@ TEST_F(P2PTransportChannelPingTest, FakePortAllocator pa(env, ss()); P2PTransportChannel ch("test", 1, &pa, &env.field_trials()); PrepareChannel(&ch); - ch.SetIceRole(webrtc::ICEROLE_CONTROLLED); + ch.SetIceRole(ICEROLE_CONTROLLED); ch.MaybeStartGathering(); // The connections have decreasing priority. Connection* conn1 = @@ -5027,11 +5000,10 @@ TEST_F(P2PTransportChannelPingTest, ASSERT_TRUE(conn2 != nullptr); // conn1 is the selected connection because it has a higher priority, - EXPECT_THAT( - webrtc::WaitUntil( - [&] { return ch.selected_connection(); }, Eq(conn1), - {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + EXPECT_THAT(WaitUntil([&] { return ch.selected_connection(); }, Eq(conn1), + {.timeout = TimeDelta::Millis(kDefaultTimeout), + .clock = &clock}), + IsRtcOk()); EXPECT_TRUE(CandidatePairMatchesNetworkRoute(conn1)); reset_selected_candidate_pair_switches(); @@ -5066,7 +5038,7 @@ TEST_F(P2PTransportChannelPingTest, TestEstimatedDisconnectedTime) { FakePortAllocator pa(env, ss()); P2PTransportChannel ch("test", 1, &pa, &env.field_trials()); PrepareChannel(&ch); - ch.SetIceRole(webrtc::ICEROLE_CONTROLLED); + ch.SetIceRole(ICEROLE_CONTROLLED); ch.MaybeStartGathering(); // The connections have decreasing priority. Connection* conn1 = @@ -5079,11 +5051,10 @@ TEST_F(P2PTransportChannelPingTest, TestEstimatedDisconnectedTime) { ASSERT_TRUE(conn2 != nullptr); // conn1 is the selected connection because it has a higher priority, - EXPECT_THAT( - webrtc::WaitUntil( - [&] { return ch.selected_connection(); }, Eq(conn1), - {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + EXPECT_THAT(WaitUntil([&] { return ch.selected_connection(); }, Eq(conn1), + {.timeout = TimeDelta::Millis(kDefaultTimeout), + .clock = &clock}), + IsRtcOk()); EXPECT_TRUE(CandidatePairMatchesNetworkRoute(conn1)); // No estimateded disconnect time at first connect <=> value is 0. EXPECT_EQ(LastEstimatedDisconnectedTimeMs(), 0); @@ -5095,7 +5066,7 @@ TEST_F(P2PTransportChannelPingTest, TestEstimatedDisconnectedTime) { clock.AdvanceTime(TimeDelta::Seconds(1)); // This will not parse as STUN, and is considered data conn1->OnReadPacket( - ReceivedIpPacket::CreateFromLegacy("XYZ", 3, webrtc::TimeMicros())); + ReceivedIpPacket::CreateFromLegacy("XYZ", 3, TimeMicros())); clock.AdvanceTime(TimeDelta::Seconds(2)); // conn2 is nominated; it becomes selected. @@ -5108,7 +5079,7 @@ TEST_F(P2PTransportChannelPingTest, TestEstimatedDisconnectedTime) { { clock.AdvanceTime(TimeDelta::Seconds(1)); conn2->OnReadPacket( - ReceivedIpPacket::CreateFromLegacy("XYZ", 3, webrtc::TimeMicros())); + ReceivedIpPacket::CreateFromLegacy("XYZ", 3, TimeMicros())); clock.AdvanceTime(TimeDelta::Seconds(2)); ReceivePingOnConnection(conn2, kIceUfrag[1], 1, nomination++); @@ -5130,7 +5101,7 @@ TEST_F(P2PTransportChannelPingTest, FakePortAllocator pa(env, ss()); P2PTransportChannel ch("test", 1, &pa, &env.field_trials()); PrepareChannel(&ch); - ch.SetIceRole(webrtc::ICEROLE_CONTROLLED); + ch.SetIceRole(ICEROLE_CONTROLLED); ch.MaybeStartGathering(); Connection* conn = CreateConnectionWithCandidate(&ch, &clock, "1.1.1.1", 1, 10, false); @@ -5150,7 +5121,7 @@ TEST_F(P2PTransportChannelPingTest, P2PTransportChannel ch("SwitchSelectedConnection", 1, &pa, &env.field_trials()); PrepareChannel(&ch); - ch.SetIceRole(webrtc::ICEROLE_CONTROLLED); + ch.SetIceRole(ICEROLE_CONTROLLED); ch.MaybeStartGathering(); // The connections have decreasing priority. Connection* conn1 = @@ -5167,29 +5138,27 @@ TEST_F(P2PTransportChannelPingTest, // conn2 becomes writable; it is selected even though it is not nominated. conn2->ReceivedPingResponse(LOW_RTT, "id"); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return reset_selected_candidate_pair_switches(); }, Eq(1), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); - EXPECT_THAT( - webrtc::WaitUntil( - [&] { return ch.selected_connection(); }, Eq(conn2), - {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); + EXPECT_THAT(WaitUntil([&] { return ch.selected_connection(); }, Eq(conn2), + {.timeout = TimeDelta::Millis(kDefaultTimeout), + .clock = &clock}), + IsRtcOk()); EXPECT_TRUE(CandidatePairMatchesNetworkRoute(conn2)); // If conn1 is also writable, it will become selected. conn1->ReceivedPingResponse(LOW_RTT, "id"); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return reset_selected_candidate_pair_switches(); }, Eq(1), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); - EXPECT_THAT( - webrtc::WaitUntil( - [&] { return ch.selected_connection(); }, Eq(conn1), - {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); + EXPECT_THAT(WaitUntil([&] { return ch.selected_connection(); }, Eq(conn1), + {.timeout = TimeDelta::Millis(kDefaultTimeout), + .clock = &clock}), + IsRtcOk()); EXPECT_TRUE(CandidatePairMatchesNetworkRoute(conn1)); // Make sure sorting won't reselect candidate pair. @@ -5245,7 +5214,7 @@ TEST_F(P2PTransportChannelPingTest, TestDontPruneWhenWeak) { FakePortAllocator pa(env, ss()); P2PTransportChannel ch("test channel", 1, &pa, &env.field_trials()); PrepareChannel(&ch); - ch.SetIceRole(webrtc::ICEROLE_CONTROLLED); + ch.SetIceRole(ICEROLE_CONTROLLED); ch.MaybeStartGathering(); ch.AddRemoteCandidate( CreateUdpCandidate(IceCandidateType::kHost, "1.1.1.1", 1, 1)); @@ -5262,17 +5231,17 @@ TEST_F(P2PTransportChannelPingTest, TestDontPruneWhenWeak) { ASSERT_TRUE(conn2 != nullptr); conn2->ReceivedPingResponse(LOW_RTT, "id"); // Becomes writable and receiving NominateConnection(conn2); - EXPECT_THAT(webrtc::WaitUntil([&] { return conn1->pruned(); }, IsTrue(), - {.timeout = TimeDelta::Millis(kMediumTimeout), - .clock = &clock}), - webrtc::IsRtcOk()); + EXPECT_THAT(WaitUntil([&] { return conn1->pruned(); }, IsTrue(), + {.timeout = TimeDelta::Millis(kMediumTimeout), + .clock = &clock}), + IsRtcOk()); - ch.SetIceConfig(CreateIceConfig(500, webrtc::GATHER_ONCE)); + ch.SetIceConfig(CreateIceConfig(500, GATHER_ONCE)); // Wait until conn2 becomes not receiving. - EXPECT_THAT(webrtc::WaitUntil([&] { return !conn2->receiving(); }, IsTrue(), - {.timeout = TimeDelta::Millis(kMediumTimeout), - .clock = &clock}), - webrtc::IsRtcOk()); + EXPECT_THAT(WaitUntil([&] { return !conn2->receiving(); }, IsTrue(), + {.timeout = TimeDelta::Millis(kMediumTimeout), + .clock = &clock}), + IsRtcOk()); ch.AddRemoteCandidate( CreateUdpCandidate(IceCandidateType::kHost, "3.3.3.3", 3, 1)); @@ -5291,7 +5260,7 @@ TEST_F(P2PTransportChannelPingTest, TestDontPruneHighPriorityConnections) { FakePortAllocator pa(env, ss()); P2PTransportChannel ch("test channel", 1, &pa, &env.field_trials()); PrepareChannel(&ch); - ch.SetIceRole(webrtc::ICEROLE_CONTROLLED); + ch.SetIceRole(ICEROLE_CONTROLLED); ch.MaybeStartGathering(); Connection* conn1 = CreateConnectionWithCandidate(&ch, &clock, "1.1.1.1", 1, 100, true); @@ -5304,7 +5273,7 @@ TEST_F(P2PTransportChannelPingTest, TestDontPruneHighPriorityConnections) { NominateConnection(conn1); SIMULATED_WAIT(false, 1, clock); conn1->OnReadPacket( - ReceivedIpPacket::CreateFromLegacy("XYZ", 3, webrtc::TimeMicros())); + ReceivedIpPacket::CreateFromLegacy("XYZ", 3, TimeMicros())); SIMULATED_WAIT(conn2->pruned(), 100, clock); EXPECT_FALSE(conn2->pruned()); } @@ -5341,19 +5310,19 @@ TEST_F(P2PTransportChannelPingTest, TestGetState) { EXPECT_EQ(IceTransportState::kChecking, ch.GetIceTransportState()); // `conn1` becomes writable and receiving; it then should prune `conn2`. conn1->ReceivedPingResponse(LOW_RTT, "id"); - EXPECT_THAT(webrtc::WaitUntil([&] { return conn2->pruned(); }, IsTrue(), - {.timeout = TimeDelta::Millis(kShortTimeout), - .clock = &clock}), - webrtc::IsRtcOk()); + EXPECT_THAT( + WaitUntil([&] { return conn2->pruned(); }, IsTrue(), + {.timeout = TimeDelta::Millis(kShortTimeout), .clock = &clock}), + IsRtcOk()); EXPECT_EQ(IceTransportStateInternal::STATE_COMPLETED, ch.GetState()); EXPECT_EQ(IceTransportState::kConnected, ch.GetIceTransportState()); conn1->Prune(); // All connections are pruned. // Need to wait until the channel state is updated. - EXPECT_THAT(webrtc::WaitUntil([&] { return ch.GetState(); }, - Eq(IceTransportStateInternal::STATE_FAILED), - {.timeout = TimeDelta::Millis(kShortTimeout), - .clock = &clock}), - webrtc::IsRtcOk()); + EXPECT_THAT( + WaitUntil([&] { return ch.GetState(); }, + Eq(IceTransportStateInternal::STATE_FAILED), + {.timeout = TimeDelta::Millis(kShortTimeout), .clock = &clock}), + IsRtcOk()); EXPECT_EQ(IceTransportState::kFailed, ch.GetIceTransportState()); } @@ -5367,7 +5336,7 @@ TEST_F(P2PTransportChannelPingTest, TestConnectionPrunedAgain) { FakePortAllocator pa(env, ss()); P2PTransportChannel ch("test channel", 1, &pa, &env.field_trials()); PrepareChannel(&ch); - IceConfig config = CreateIceConfig(1000, webrtc::GATHER_ONCE); + IceConfig config = CreateIceConfig(1000, GATHER_ONCE); config.receiving_switching_delay = 800; ch.SetIceConfig(config); ch.MaybeStartGathering(); @@ -5377,11 +5346,10 @@ TEST_F(P2PTransportChannelPingTest, TestConnectionPrunedAgain) { ASSERT_TRUE(conn1 != nullptr); EXPECT_EQ(nullptr, ch.selected_connection()); conn1->ReceivedPingResponse(LOW_RTT, "id"); // Becomes writable and receiving - EXPECT_THAT( - webrtc::WaitUntil( - [&] { return ch.selected_connection(); }, Eq(conn1), - {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + EXPECT_THAT(WaitUntil([&] { return ch.selected_connection(); }, Eq(conn1), + {.timeout = TimeDelta::Millis(kDefaultTimeout), + .clock = &clock}), + IsRtcOk()); // Add a low-priority connection `conn2`, which will be pruned, but it will // not be deleted right away. Once the current selected connection becomes not @@ -5391,45 +5359,43 @@ TEST_F(P2PTransportChannelPingTest, TestConnectionPrunedAgain) { CreateUdpCandidate(IceCandidateType::kHost, "2.2.2.2", 2, 1)); Connection* conn2 = WaitForConnectionTo(&ch, "2.2.2.2", 2, &clock); ASSERT_TRUE(conn2 != nullptr); - EXPECT_THAT(webrtc::WaitUntil([&] { return !conn2->active(); }, IsTrue(), - {.timeout = TimeDelta::Millis(kDefaultTimeout), - .clock = &clock}), - webrtc::IsRtcOk()); + EXPECT_THAT(WaitUntil([&] { return !conn2->active(); }, IsTrue(), + {.timeout = TimeDelta::Millis(kDefaultTimeout), + .clock = &clock}), + IsRtcOk()); // `conn2` should not send a ping yet. EXPECT_EQ(IceCandidatePairState::WAITING, conn2->state()); EXPECT_EQ(IceTransportStateInternal::STATE_COMPLETED, ch.GetState()); // Wait for `conn1` becoming not receiving. - EXPECT_THAT(webrtc::WaitUntil([&] { return !conn1->receiving(); }, IsTrue(), - {.timeout = TimeDelta::Millis(kMediumTimeout), - .clock = &clock}), - webrtc::IsRtcOk()); + EXPECT_THAT(WaitUntil([&] { return !conn1->receiving(); }, IsTrue(), + {.timeout = TimeDelta::Millis(kMediumTimeout), + .clock = &clock}), + IsRtcOk()); // Make sure conn2 is not deleted. conn2 = WaitForConnectionTo(&ch, "2.2.2.2", 2, &clock); ASSERT_TRUE(conn2 != nullptr); - EXPECT_THAT(webrtc::WaitUntil([&] { return conn2->state(); }, - Eq(IceCandidatePairState::IN_PROGRESS), - {.timeout = TimeDelta::Millis(kDefaultTimeout), - .clock = &clock}), - webrtc::IsRtcOk()); + EXPECT_THAT(WaitUntil([&] { return conn2->state(); }, + Eq(IceCandidatePairState::IN_PROGRESS), + {.timeout = TimeDelta::Millis(kDefaultTimeout), + .clock = &clock}), + IsRtcOk()); conn2->ReceivedPingResponse(LOW_RTT, "id"); - EXPECT_THAT( - webrtc::WaitUntil( - [&] { return ch.selected_connection(); }, Eq(conn2), - {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + EXPECT_THAT(WaitUntil([&] { return ch.selected_connection(); }, Eq(conn2), + {.timeout = TimeDelta::Millis(kDefaultTimeout), + .clock = &clock}), + IsRtcOk()); EXPECT_EQ(IceTransportStateInternal::STATE_CONNECTING, ch.GetState()); // When `conn1` comes back again, `conn2` will be pruned again. conn1->ReceivedPingResponse(LOW_RTT, "id"); - EXPECT_THAT( - webrtc::WaitUntil( - [&] { return ch.selected_connection(); }, Eq(conn1), - {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); - EXPECT_THAT(webrtc::WaitUntil([&] { return !conn2->active(); }, IsTrue(), - {.timeout = TimeDelta::Millis(kDefaultTimeout), - .clock = &clock}), - webrtc::IsRtcOk()); + EXPECT_THAT(WaitUntil([&] { return ch.selected_connection(); }, Eq(conn1), + {.timeout = TimeDelta::Millis(kDefaultTimeout), + .clock = &clock}), + IsRtcOk()); + EXPECT_THAT(WaitUntil([&] { return !conn2->active(); }, IsTrue(), + {.timeout = TimeDelta::Millis(kDefaultTimeout), + .clock = &clock}), + IsRtcOk()); EXPECT_EQ(IceTransportStateInternal::STATE_COMPLETED, ch.GetState()); } @@ -5450,10 +5416,9 @@ TEST_F(P2PTransportChannelPingTest, TestDeleteConnectionsIfAllWriteTimedout) { conn1->ReceivedPing(); // Becomes receiving conn1->Prune(); EXPECT_THAT( - webrtc::WaitUntil( - [&] { return ch.connections().empty(); }, IsTrue(), - {.timeout = TimeDelta::Millis(kShortTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + WaitUntil([&] { return ch.connections().empty(); }, IsTrue(), + {.timeout = TimeDelta::Millis(kShortTimeout), .clock = &clock}), + IsRtcOk()); // Have two connections but both become write-time-out later. ch.AddRemoteCandidate( @@ -5470,10 +5435,9 @@ TEST_F(P2PTransportChannelPingTest, TestDeleteConnectionsIfAllWriteTimedout) { conn2->Prune(); conn3->Prune(); EXPECT_THAT( - webrtc::WaitUntil( - [&] { return ch.connections().empty(); }, IsTrue(), - {.timeout = TimeDelta::Millis(kShortTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + WaitUntil([&] { return ch.connections().empty(); }, IsTrue(), + {.timeout = TimeDelta::Millis(kShortTimeout), .clock = &clock}), + IsRtcOk()); } // Tests that after a port allocator session is started, it will be stopped @@ -5485,7 +5449,7 @@ TEST_F(P2PTransportChannelPingTest, TestStopPortAllocatorSessions) { FakePortAllocator pa(env, ss()); P2PTransportChannel ch("test channel", 1, &pa, &env.field_trials()); PrepareChannel(&ch); - ch.SetIceConfig(CreateIceConfig(2000, webrtc::GATHER_ONCE)); + ch.SetIceConfig(CreateIceConfig(2000, GATHER_ONCE)); ch.MaybeStartGathering(); ch.AddRemoteCandidate( CreateUdpCandidate(IceCandidateType::kHost, "1.1.1.1", 1, 100)); @@ -5523,7 +5487,7 @@ TEST_F(P2PTransportChannelPingTest, TestIceRoleUpdatedOnRemovedPort) { &env.field_trials()); // Starts with ICEROLE_CONTROLLING. PrepareChannel(&ch); - IceConfig config = CreateIceConfig(1000, webrtc::GATHER_CONTINUALLY); + IceConfig config = CreateIceConfig(1000, GATHER_CONTINUALLY); ch.SetIceConfig(config); ch.MaybeStartGathering(); ch.AddRemoteCandidate( @@ -5536,8 +5500,8 @@ TEST_F(P2PTransportChannelPingTest, TestIceRoleUpdatedOnRemovedPort) { // change the ICE role and expect it to be updated. std::vector ports(1, conn->PortForTest()); ch.allocator_session()->SignalPortsPruned(ch.allocator_session(), ports); - ch.SetIceRole(webrtc::ICEROLE_CONTROLLED); - EXPECT_EQ(webrtc::ICEROLE_CONTROLLED, conn->PortForTest()->GetIceRole()); + ch.SetIceRole(ICEROLE_CONTROLLED); + EXPECT_EQ(ICEROLE_CONTROLLED, conn->PortForTest()->GetIceRole()); } // Test that the ICE role is updated even on ports with inactive networks. @@ -5562,8 +5526,8 @@ TEST_F(P2PTransportChannelPingTest, TestIceRoleUpdatedOnPortAfterIceRestart) { // role updated. ch.SetIceParameters(kIceParams[1]); ch.MaybeStartGathering(); - ch.SetIceRole(webrtc::ICEROLE_CONTROLLED); - EXPECT_EQ(webrtc::ICEROLE_CONTROLLED, conn->PortForTest()->GetIceRole()); + ch.SetIceRole(ICEROLE_CONTROLLED); + EXPECT_EQ(ICEROLE_CONTROLLED, conn->PortForTest()->GetIceRole()); } // Test that after some amount of time without receiving data, the connection @@ -5577,7 +5541,7 @@ TEST_F(P2PTransportChannelPingTest, TestPortDestroyedAfterTimeoutAndPruned) { P2PTransportChannel ch("test channel", ICE_CANDIDATE_COMPONENT_DEFAULT, &pa, &env.field_trials()); PrepareChannel(&ch); - ch.SetIceRole(webrtc::ICEROLE_CONTROLLED); + ch.SetIceRole(ICEROLE_CONTROLLED); ch.MaybeStartGathering(); ch.AddRemoteCandidate( CreateUdpCandidate(IceCandidateType::kHost, "1.1.1.1", 1, 1)); @@ -5597,12 +5561,12 @@ TEST_F(P2PTransportChannelPingTest, TestPortDestroyedAfterTimeoutAndPruned) { // If the session prunes all ports, the port will be destroyed. ch.allocator_session()->PruneAllPorts(); - EXPECT_THAT(webrtc::WaitUntil([&] { return GetPort(&ch); }, Eq(nullptr), - {.clock = &fake_clock}), - webrtc::IsRtcOk()); - EXPECT_THAT(webrtc::WaitUntil([&] { return GetPrunedPort(&ch); }, Eq(nullptr), - {.clock = &fake_clock}), - webrtc::IsRtcOk()); + EXPECT_THAT(WaitUntil([&] { return GetPort(&ch); }, Eq(nullptr), + {.clock = &fake_clock}), + IsRtcOk()); + EXPECT_THAT(WaitUntil([&] { return GetPrunedPort(&ch); }, Eq(nullptr), + {.clock = &fake_clock}), + IsRtcOk()); } TEST_F(P2PTransportChannelPingTest, TestMaxOutstandingPingsFieldTrial) { @@ -5623,13 +5587,13 @@ TEST_F(P2PTransportChannelPingTest, TestMaxOutstandingPingsFieldTrial) { ASSERT_TRUE(conn1 != nullptr); ASSERT_TRUE(conn2 != nullptr); - EXPECT_THAT(webrtc::WaitUntil( + EXPECT_THAT(WaitUntil( [&] { return conn1->num_pings_sent() == 3 && conn2->num_pings_sent() == 3; }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); // Check that these connections don't send any more pings. EXPECT_EQ(nullptr, ch.FindNextPingableConnection()); @@ -5651,9 +5615,9 @@ class P2PTransportChannelMostLikelyToWorkFirstTest env, &network_manager_, packet_socket_factory(), ServerAddresses(), kTurnUdpIntAddr, SocketAddress()); port_allocator_->set_flags(port_allocator_->flags() | - webrtc::PORTALLOCATOR_DISABLE_STUN | - webrtc::PORTALLOCATOR_DISABLE_TCP); - port_allocator_->set_step_delay(webrtc::kMinimumStepDelay); + PORTALLOCATOR_DISABLE_STUN | + PORTALLOCATOR_DISABLE_TCP); + port_allocator_->set_step_delay(kMinimumStepDelay); return *port_allocator_; } @@ -5682,7 +5646,7 @@ class P2PTransportChannelMostLikelyToWorkFirstTest void VerifyNextPingableConnection( IceCandidateType local_candidate_type, IceCandidateType remote_candidate_type, - absl::string_view relay_protocol_type = webrtc::UDP_PROTOCOL_NAME) { + absl::string_view relay_protocol_type = UDP_PROTOCOL_NAME) { Connection* conn = FindNextPingableConnectionAndPingIt(channel_.get()); ASSERT_TRUE(conn != nullptr); EXPECT_EQ(conn->local_candidate().type(), local_candidate_type); @@ -5709,10 +5673,9 @@ TEST_F(P2PTransportChannelMostLikelyToWorkFirstTest, CreatePortAllocator(env); P2PTransportChannel& ch = StartTransportChannel(env, true, max_strong_interval); - EXPECT_THAT( - webrtc::WaitUntil([&] { return ch.ports().size(); }, Eq(2), + EXPECT_THAT(WaitUntil([&] { return ch.ports().size(); }, Eq(2), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_EQ(ch.ports()[0]->Type(), IceCandidateType::kHost); EXPECT_EQ(ch.ports()[1]->Type(), IceCandidateType::kRelay); @@ -5721,10 +5684,9 @@ TEST_F(P2PTransportChannelMostLikelyToWorkFirstTest, ch.AddRemoteCandidate( CreateUdpCandidate(IceCandidateType::kHost, "2.2.2.2", 2, 2)); - EXPECT_THAT( - webrtc::WaitUntil([&] { return ch.connections().size(); }, Eq(4), + EXPECT_THAT(WaitUntil([&] { return ch.connections().size(); }, Eq(4), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); // Relay/Relay should be the first pingable connection. Connection* conn = FindNextPingableConnectionAndPingIt(&ch); @@ -5778,19 +5740,17 @@ TEST_F(P2PTransportChannelMostLikelyToWorkFirstTest, const Environment env = CreateEnvironment(); CreatePortAllocator(env); P2PTransportChannel& ch = StartTransportChannel(env, true, 500); - EXPECT_THAT( - webrtc::WaitUntil([&] { return ch.ports().size(); }, Eq(2), + EXPECT_THAT(WaitUntil([&] { return ch.ports().size(); }, Eq(2), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_EQ(ch.ports()[0]->Type(), IceCandidateType::kHost); EXPECT_EQ(ch.ports()[1]->Type(), IceCandidateType::kRelay); ch.AddRemoteCandidate( CreateUdpCandidate(IceCandidateType::kHost, "1.1.1.1", 1, 1)); - EXPECT_THAT( - webrtc::WaitUntil([&] { return ch.connections().size(); }, Eq(2), + EXPECT_THAT(WaitUntil([&] { return ch.connections().size(); }, Eq(2), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); // Initially, only have Local/Local and Local/Relay. VerifyNextPingableConnection(IceCandidateType::kHost, @@ -5801,10 +5761,9 @@ TEST_F(P2PTransportChannelMostLikelyToWorkFirstTest, // Remote Relay candidate arrives. ch.AddRemoteCandidate( CreateUdpCandidate(IceCandidateType::kRelay, "2.2.2.2", 2, 2)); - EXPECT_THAT( - webrtc::WaitUntil([&] { return ch.connections().size(); }, Eq(4), + EXPECT_THAT(WaitUntil([&] { return ch.connections().size(); }, Eq(4), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); // Relay/Relay should be the first since it hasn't been pinged before. VerifyNextPingableConnection(IceCandidateType::kRelay, @@ -5827,19 +5786,17 @@ TEST_F(P2PTransportChannelMostLikelyToWorkFirstTest, const Environment env = CreateEnvironment(); CreatePortAllocator(env); P2PTransportChannel& ch = StartTransportChannel(env, true, 500); - EXPECT_THAT( - webrtc::WaitUntil([&] { return ch.ports().size(); }, Eq(2), + EXPECT_THAT(WaitUntil([&] { return ch.ports().size(); }, Eq(2), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_EQ(ch.ports()[0]->Type(), IceCandidateType::kHost); EXPECT_EQ(ch.ports()[1]->Type(), IceCandidateType::kRelay); ch.AddRemoteCandidate( CreateUdpCandidate(IceCandidateType::kRelay, "1.1.1.1", 1, 1)); - EXPECT_THAT( - webrtc::WaitUntil([&] { return ch.connections().size(); }, Eq(2), + EXPECT_THAT(WaitUntil([&] { return ch.connections().size(); }, Eq(2), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); // Initially, only have Relay/Relay and Local/Relay. Ping Relay/Relay first. VerifyNextPingableConnection(IceCandidateType::kRelay, @@ -5852,10 +5809,9 @@ TEST_F(P2PTransportChannelMostLikelyToWorkFirstTest, // Remote Local candidate arrives. ch.AddRemoteCandidate( CreateUdpCandidate(IceCandidateType::kHost, "2.2.2.2", 2, 2)); - EXPECT_THAT( - webrtc::WaitUntil([&] { return ch.connections().size(); }, Eq(4), + EXPECT_THAT(WaitUntil([&] { return ch.connections().size(); }, Eq(4), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); // Local/Local should be the first since it hasn't been pinged before. VerifyNextPingableConnection(IceCandidateType::kHost, @@ -5879,28 +5835,25 @@ TEST_F(P2PTransportChannelMostLikelyToWorkFirstTest, "WebRTC-IceFieldTrials/skip_relay_to_non_relay_connections:true/")); CreatePortAllocator(env); P2PTransportChannel& ch = StartTransportChannel(env, true, 500); - EXPECT_THAT( - webrtc::WaitUntil([&] { return ch.ports().size(); }, Eq(2), + EXPECT_THAT(WaitUntil([&] { return ch.ports().size(); }, Eq(2), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_EQ(ch.ports()[0]->Type(), IceCandidateType::kHost); EXPECT_EQ(ch.ports()[1]->Type(), IceCandidateType::kRelay); // Remote Relay candidate arrives. ch.AddRemoteCandidate( CreateUdpCandidate(IceCandidateType::kRelay, "1.1.1.1", 1, 1)); - EXPECT_THAT( - webrtc::WaitUntil([&] { return ch.connections().size(); }, Eq(1), + EXPECT_THAT(WaitUntil([&] { return ch.connections().size(); }, Eq(1), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); // Remote Local candidate arrives. ch.AddRemoteCandidate( CreateUdpCandidate(IceCandidateType::kHost, "2.2.2.2", 2, 2)); - EXPECT_THAT( - webrtc::WaitUntil([&] { return ch.connections().size(); }, Eq(2), + EXPECT_THAT(WaitUntil([&] { return ch.connections().size(); }, Eq(2), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); } // Test the ping sequence is UDP Relay/Relay followed by TCP Relay/Relay, @@ -5908,17 +5861,16 @@ TEST_F(P2PTransportChannelMostLikelyToWorkFirstTest, TEST_F(P2PTransportChannelMostLikelyToWorkFirstTest, TestTcpTurn) { const Environment env = CreateEnvironment(); // Add a Tcp Turn server. - turn_server()->AddInternalSocket(kTurnTcpIntAddr, webrtc::PROTO_TCP); + turn_server()->AddInternalSocket(kTurnTcpIntAddr, PROTO_TCP); RelayServerConfig config; config.credentials = kRelayCredentials; - config.ports.push_back(ProtocolAddress(kTurnTcpIntAddr, webrtc::PROTO_TCP)); + config.ports.push_back(ProtocolAddress(kTurnTcpIntAddr, PROTO_TCP)); CreatePortAllocator(env).AddTurnServerForTesting(config); P2PTransportChannel& ch = StartTransportChannel(env, true, 500); - EXPECT_THAT( - webrtc::WaitUntil([&] { return ch.ports().size(); }, Eq(3), + EXPECT_THAT(WaitUntil([&] { return ch.ports().size(); }, Eq(3), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_EQ(ch.ports()[0]->Type(), IceCandidateType::kHost); EXPECT_EQ(ch.ports()[1]->Type(), IceCandidateType::kRelay); EXPECT_EQ(ch.ports()[2]->Type(), IceCandidateType::kRelay); @@ -5926,10 +5878,9 @@ TEST_F(P2PTransportChannelMostLikelyToWorkFirstTest, TestTcpTurn) { // Remote Relay candidate arrives. ch.AddRemoteCandidate( CreateUdpCandidate(IceCandidateType::kRelay, "1.1.1.1", 1, 1)); - EXPECT_THAT( - webrtc::WaitUntil([&] { return ch.connections().size(); }, Eq(3), + EXPECT_THAT(WaitUntil([&] { return ch.connections().size(); }, Eq(3), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); // UDP Relay/Relay should be pinged first. VerifyNextPingableConnection(IceCandidateType::kRelay, @@ -5937,8 +5888,7 @@ TEST_F(P2PTransportChannelMostLikelyToWorkFirstTest, TestTcpTurn) { // TCP Relay/Relay is the next. VerifyNextPingableConnection(IceCandidateType::kRelay, - IceCandidateType::kRelay, - webrtc::TCP_PROTOCOL_NAME); + IceCandidateType::kRelay, TCP_PROTOCOL_NAME); // Finally, Local/Relay will be pinged. VerifyNextPingableConnection(IceCandidateType::kHost, @@ -5951,8 +5901,7 @@ TEST_F(P2PTransportChannelMostLikelyToWorkFirstTest, TestTcpTurn) { TEST(P2PTransportChannelResolverTest, HostnameCandidateIsResolved) { const Environment env = CreateEnvironment(); ResolverFactoryFixture resolver_fixture; - std::unique_ptr socket_server = - webrtc::CreateDefaultSocketServer(); + std::unique_ptr socket_server = CreateDefaultSocketServer(); AutoSocketServerThread main_thread(socket_server.get()); FakePortAllocator allocator(env, socket_server.get()); IceTransportInit init; @@ -5965,10 +5914,10 @@ TEST(P2PTransportChannelResolverTest, HostnameCandidateIsResolved) { hostname_candidate.set_address(hostname_address); channel->AddRemoteCandidate(hostname_candidate); - ASSERT_THAT(webrtc::WaitUntil( - [&] { return channel->remote_candidates().size(); }, Eq(1u), - {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + ASSERT_THAT( + WaitUntil([&] { return channel->remote_candidates().size(); }, Eq(1u), + {.timeout = TimeDelta::Millis(kDefaultTimeout)}), + IsRtcOk()); const RemoteCandidate& candidate = channel->remote_candidates()[0]; EXPECT_FALSE(candidate.address().IsUnresolvedIP()); } @@ -5995,10 +5944,10 @@ TEST_F(P2PTransportChannelTest, // number is assgined to ep1's host candidate. PauseCandidates(0); PauseCandidates(1); - ASSERT_THAT(webrtc::WaitUntil( - [&] { return GetEndpoint(0)->saved_candidates_.size(); }, - Eq(1u), {.timeout = TimeDelta::Millis(kMediumTimeout)}), - webrtc::IsRtcOk()); + ASSERT_THAT( + WaitUntil([&] { return GetEndpoint(0)->saved_candidates_.size(); }, + Eq(1u), {.timeout = TimeDelta::Millis(kMediumTimeout)}), + IsRtcOk()); const auto& local_candidate = GetEndpoint(0)->saved_candidates_[0].candidate; // The IP address of ep1's host candidate should be obfuscated. EXPECT_TRUE(local_candidate.address().IsUnresolvedIP()); @@ -6010,20 +5959,20 @@ TEST_F(P2PTransportChannelTest, // pair and start to ping. After receiving the ping, ep2 discovers a prflx // remote candidate and form a candidate pair as well. ResumeCandidates(1); - ASSERT_THAT(webrtc::WaitUntil( - [&] { return ep1_ch1()->selected_connection(); }, Ne(nullptr), - {.timeout = TimeDelta::Millis(kMediumTimeout)}), - webrtc::IsRtcOk()); + ASSERT_THAT( + WaitUntil([&] { return ep1_ch1()->selected_connection(); }, Ne(nullptr), + {.timeout = TimeDelta::Millis(kMediumTimeout)}), + IsRtcOk()); // ep2 should have the selected connection connected to the prflx remote // candidate. const Connection* selected_connection = nullptr; - ASSERT_THAT(webrtc::WaitUntil( + ASSERT_THAT(WaitUntil( [&] { return selected_connection = ep2_ch1()->selected_connection(); }, Ne(nullptr), {.timeout = TimeDelta::Millis(kMediumTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_TRUE(selected_connection->remote_candidate().is_prflx()); EXPECT_EQ(kIceUfrag[0], selected_connection->remote_candidate().username()); EXPECT_EQ(kIcePwd[0], selected_connection->remote_candidate().password()); @@ -6031,7 +5980,7 @@ TEST_F(P2PTransportChannelTest, resolver_fixture.SetAddressToReturn(local_address); ResumeCandidates(0); // Verify ep2's selected connection is updated to use the 'local' candidate. - EXPECT_THAT(webrtc::WaitUntil( + EXPECT_THAT(WaitUntil( [&] { return ep2_ch1() ->selected_connection() @@ -6039,7 +5988,7 @@ TEST_F(P2PTransportChannelTest, .is_local(); }, IsTrue(), {.timeout = TimeDelta::Millis(kMediumTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_EQ(selected_connection, ep2_ch1()->selected_connection()); DestroyChannels(); @@ -6070,10 +6019,10 @@ TEST_F(P2PTransportChannelTest, PauseCandidates(0); PauseCandidates(1); - ASSERT_THAT(webrtc::WaitUntil( - [&] { return GetEndpoint(0)->saved_candidates_.size(); }, - Eq(1u), {.timeout = TimeDelta::Millis(kMediumTimeout)}), - webrtc::IsRtcOk()); + ASSERT_THAT( + WaitUntil([&] { return GetEndpoint(0)->saved_candidates_.size(); }, + Eq(1u), {.timeout = TimeDelta::Millis(kMediumTimeout)}), + IsRtcOk()); const auto& local_candidate = GetEndpoint(0)->saved_candidates_[0].candidate; // The IP address of ep1's host candidate should be obfuscated. ASSERT_TRUE(local_candidate.address().IsUnresolvedIP()); @@ -6086,10 +6035,10 @@ TEST_F(P2PTransportChannelTest, // by ep1. Let ep2 signal its host candidate with an IP address to ep1, so // that ep1 can form a candidate pair, select it and start to ping ep2. ResumeCandidates(1); - ASSERT_THAT(webrtc::WaitUntil( - [&] { return ep1_ch1()->selected_connection(); }, Ne(nullptr), - {.timeout = TimeDelta::Millis(kMediumTimeout)}), - webrtc::IsRtcOk()); + ASSERT_THAT( + WaitUntil([&] { return ep1_ch1()->selected_connection(); }, Ne(nullptr), + {.timeout = TimeDelta::Millis(kMediumTimeout)}), + IsRtcOk()); // Let the mock resolver of ep2 receives the correct resolution. resolver_fixture.SetAddressToReturn(local_address); @@ -6098,17 +6047,17 @@ TEST_F(P2PTransportChannelTest, // // There is a caveat in our implementation associated with this expectation. // See the big comment in P2PTransportChannel::OnUnknownAddress. - ASSERT_THAT(webrtc::WaitUntil( - [&] { return ep2_ch1()->selected_connection(); }, Ne(nullptr), - {.timeout = TimeDelta::Millis(kMediumTimeout)}), - webrtc::IsRtcOk()); + ASSERT_THAT( + WaitUntil([&] { return ep2_ch1()->selected_connection(); }, Ne(nullptr), + {.timeout = TimeDelta::Millis(kMediumTimeout)}), + IsRtcOk()); EXPECT_TRUE(ep2_ch1()->selected_connection()->remote_candidate().is_prflx()); // ep2 should also be able resolve the hostname candidate. The resolved remote // host candidate should be merged with the prflx remote candidate. resolver_fixture.FireDelayedResolution(); - EXPECT_THAT(webrtc::WaitUntil( + EXPECT_THAT(WaitUntil( [&] { return ep2_ch1() ->selected_connection() @@ -6116,7 +6065,7 @@ TEST_F(P2PTransportChannelTest, .is_local(); }, IsTrue(), {.timeout = TimeDelta::Millis(kMediumTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_EQ(1u, ep2_ch1()->remote_candidates().size()); DestroyChannels(); @@ -6142,10 +6091,10 @@ TEST_F(P2PTransportChannelTest, CanConnectWithHostCandidateWithMdnsName) { // number is assgined to ep1's host candidate. PauseCandidates(0); PauseCandidates(1); - ASSERT_THAT(webrtc::WaitUntil( - [&] { return GetEndpoint(0)->saved_candidates_.size(); }, - Eq(1u), {.timeout = TimeDelta::Millis(kMediumTimeout)}), - webrtc::IsRtcOk()); + ASSERT_THAT( + WaitUntil([&] { return GetEndpoint(0)->saved_candidates_.size(); }, + Eq(1u), {.timeout = TimeDelta::Millis(kMediumTimeout)}), + IsRtcOk()); const auto& local_candidate_ep1 = GetEndpoint(0)->saved_candidates_[0].candidate; // The IP address of ep1's host candidate should be obfuscated. @@ -6161,10 +6110,10 @@ TEST_F(P2PTransportChannelTest, CanConnectWithHostCandidateWithMdnsName) { // We should be able to receive a ping from ep2 and establish a connection // with a peer reflexive candidate from ep2. - ASSERT_THAT(webrtc::WaitUntil( - [&] { return ep1_ch1()->selected_connection(); }, Ne(nullptr), - {.timeout = TimeDelta::Millis(kMediumTimeout)}), - webrtc::IsRtcOk()); + ASSERT_THAT( + WaitUntil([&] { return ep1_ch1()->selected_connection(); }, Ne(nullptr), + {.timeout = TimeDelta::Millis(kMediumTimeout)}), + IsRtcOk()); EXPECT_TRUE(ep1_ch1()->selected_connection()->local_candidate().is_local()); EXPECT_TRUE(ep1_ch1()->selected_connection()->remote_candidate().is_prflx()); @@ -6185,10 +6134,9 @@ TEST_F(P2PTransportChannelTest, // ep1 and ep2 will gather host candidates with addresses // kPublicAddrs[0] and kPublicAddrs[1], respectively. ep1 also gathers a srflx // and a relay candidates. - ConfigureEndpoints( - env, OPEN, OPEN, - webrtc::kDefaultPortAllocatorFlags | webrtc::PORTALLOCATOR_DISABLE_TCP, - kOnlyLocalPorts); + ConfigureEndpoints(env, OPEN, OPEN, + kDefaultPortAllocatorFlags | PORTALLOCATOR_DISABLE_TCP, + kOnlyLocalPorts); // ICE parameter will be set up when creating the channels. set_remote_ice_parameter_source(FROM_SETICEPARAMETERS); GetEndpoint(0)->network_manager_.set_mdns_responder( @@ -6200,14 +6148,14 @@ TEST_F(P2PTransportChannelTest, PauseCandidates(0); PauseCandidates(1); // Ep1 has a UDP host, a srflx and a relay candidates. - ASSERT_THAT(webrtc::WaitUntil( - [&] { return GetEndpoint(0)->saved_candidates_.size(); }, - Eq(3u), {.timeout = TimeDelta::Millis(kMediumTimeout)}), - webrtc::IsRtcOk()); - ASSERT_THAT(webrtc::WaitUntil( - [&] { return GetEndpoint(1)->saved_candidates_.size(); }, - Eq(1u), {.timeout = TimeDelta::Millis(kMediumTimeout)}), - webrtc::IsRtcOk()); + ASSERT_THAT( + WaitUntil([&] { return GetEndpoint(0)->saved_candidates_.size(); }, + Eq(3u), {.timeout = TimeDelta::Millis(kMediumTimeout)}), + IsRtcOk()); + ASSERT_THAT( + WaitUntil([&] { return GetEndpoint(1)->saved_candidates_.size(); }, + Eq(1u), {.timeout = TimeDelta::Millis(kMediumTimeout)}), + IsRtcOk()); for (const auto& candidates_data : GetEndpoint(0)->saved_candidates_) { const auto& local_candidate_ep1 = candidates_data.candidate; @@ -6223,20 +6171,18 @@ TEST_F(P2PTransportChannelTest, ResumeCandidates(0); ResumeCandidates(1); - ASSERT_THAT(webrtc::WaitUntil([&] { return ep1_ch1()->gathering_state(); }, - Eq(webrtc::kIceGatheringComplete), - {.timeout = TimeDelta::Millis(kMediumTimeout)}), - webrtc::IsRtcOk()); + ASSERT_THAT(WaitUntil([&] { return ep1_ch1()->gathering_state(); }, + Eq(kIceGatheringComplete), + {.timeout = TimeDelta::Millis(kMediumTimeout)}), + IsRtcOk()); // We should have the following candidate pairs on both endpoints: // ep1_host <-> ep2_host, ep1_srflx <-> ep2_host, ep1_relay <-> ep2_host - ASSERT_THAT( - webrtc::WaitUntil([&] { return ep1_ch1()->connections().size(); }, Eq(3u), + ASSERT_THAT(WaitUntil([&] { return ep1_ch1()->connections().size(); }, Eq(3u), {.timeout = TimeDelta::Millis(kMediumTimeout)}), - webrtc::IsRtcOk()); - ASSERT_THAT( - webrtc::WaitUntil([&] { return ep2_ch1()->connections().size(); }, Eq(3u), + IsRtcOk()); + ASSERT_THAT(WaitUntil([&] { return ep2_ch1()->connections().size(); }, Eq(3u), {.timeout = TimeDelta::Millis(kMediumTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); IceTransportStats ice_transport_stats1; IceTransportStats ice_transport_stats2; @@ -6283,8 +6229,8 @@ TEST_F(P2PTransportChannelTest, ConnectingIncreasesSelectedCandidatePairChanges) { ScopedFakeClock clock; const Environment env = CreateEnvironment(); - ConfigureEndpoints(env, OPEN, OPEN, webrtc::kDefaultPortAllocatorFlags, - webrtc::kDefaultPortAllocatorFlags); + ConfigureEndpoints(env, OPEN, OPEN, kDefaultPortAllocatorFlags, + kDefaultPortAllocatorFlags); CreateChannels(env); IceTransportStats ice_transport_stats; @@ -6293,10 +6239,10 @@ TEST_F(P2PTransportChannelTest, // Let the channels connect. EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return ep1_ch1()->selected_connection(); }, Ne(nullptr), {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); ASSERT_TRUE(ep1_ch1()->GetStats(&ice_transport_stats)); EXPECT_EQ(1u, ice_transport_stats.selected_candidate_pair_changes); @@ -6308,8 +6254,8 @@ TEST_F(P2PTransportChannelTest, DisconnectedIncreasesSelectedCandidatePairChanges) { ScopedFakeClock clock; const Environment env = CreateEnvironment(); - ConfigureEndpoints(env, OPEN, OPEN, webrtc::kDefaultPortAllocatorFlags, - webrtc::kDefaultPortAllocatorFlags); + ConfigureEndpoints(env, OPEN, OPEN, kDefaultPortAllocatorFlags, + kDefaultPortAllocatorFlags); CreateChannels(env); IceTransportStats ice_transport_stats; @@ -6318,10 +6264,10 @@ TEST_F(P2PTransportChannelTest, // Let the channels connect. EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return ep1_ch1()->selected_connection(); }, Ne(nullptr), {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); ASSERT_TRUE(ep1_ch1()->GetStats(&ice_transport_stats)); EXPECT_EQ(1u, ice_transport_stats.selected_candidate_pair_changes); @@ -6331,10 +6277,10 @@ TEST_F(P2PTransportChannelTest, con->Prune(); } EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return ep1_ch1()->selected_connection(); }, Eq(nullptr), {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); ASSERT_TRUE(ep1_ch1()->GetStats(&ice_transport_stats)); EXPECT_EQ(2u, ice_transport_stats.selected_candidate_pair_changes); @@ -6346,8 +6292,8 @@ TEST_F(P2PTransportChannelTest, NewSelectionIncreasesSelectedCandidatePairChanges) { ScopedFakeClock clock; const Environment env = CreateEnvironment(); - ConfigureEndpoints(env, OPEN, OPEN, webrtc::kDefaultPortAllocatorFlags, - webrtc::kDefaultPortAllocatorFlags); + ConfigureEndpoints(env, OPEN, OPEN, kDefaultPortAllocatorFlags, + kDefaultPortAllocatorFlags); CreateChannels(env); IceTransportStats ice_transport_stats; @@ -6356,10 +6302,10 @@ TEST_F(P2PTransportChannelTest, // Let the channels connect. EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return ep1_ch1()->selected_connection(); }, Ne(nullptr), {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); ASSERT_TRUE(ep1_ch1()->GetStats(&ice_transport_stats)); EXPECT_EQ(1u, ice_transport_stats.selected_candidate_pair_changes); @@ -6373,7 +6319,7 @@ TEST_F(P2PTransportChannelTest, } } EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return ep1_ch1()->selected_connection() != nullptr && (ep1_ch1()->GetStats(&ice_transport_stats), @@ -6381,7 +6327,7 @@ TEST_F(P2PTransportChannelTest, }, IsTrue(), {.timeout = TimeDelta::Millis(kMediumTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); ASSERT_TRUE(ep1_ch1()->GetStats(&ice_transport_stats)); EXPECT_GE(ice_transport_stats.selected_candidate_pair_changes, 2u); @@ -6409,10 +6355,10 @@ TEST_F(P2PTransportChannelTest, // number is assigned to ep1's host candidate. PauseCandidates(0); PauseCandidates(1); - ASSERT_THAT(webrtc::WaitUntil( - [&] { return GetEndpoint(0)->saved_candidates_.size(); }, - Eq(1u), {.timeout = TimeDelta::Millis(kMediumTimeout)}), - webrtc::IsRtcOk()); + ASSERT_THAT( + WaitUntil([&] { return GetEndpoint(0)->saved_candidates_.size(); }, + Eq(1u), {.timeout = TimeDelta::Millis(kMediumTimeout)}), + IsRtcOk()); const auto& candidates_data = GetEndpoint(0)->saved_candidates_[0]; const auto& local_candidate_ep1 = candidates_data.candidate; ASSERT_TRUE(local_candidate_ep1.is_local()); @@ -6425,13 +6371,13 @@ TEST_F(P2PTransportChannelTest, ResumeCandidates(0); ResumeCandidates(1); - ASSERT_THAT(webrtc::WaitUntil( + ASSERT_THAT(WaitUntil( [&] { return ep1_ch1()->selected_connection() != nullptr && ep2_ch1()->selected_connection() != nullptr; }, IsTrue(), {.timeout = TimeDelta::Millis(kMediumTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); const auto pair_ep1 = ep1_ch1()->GetSelectedCandidatePair(); ASSERT_TRUE(pair_ep1.has_value()); @@ -6449,24 +6395,23 @@ TEST_F(P2PTransportChannelTest, TEST_F(P2PTransportChannelTest, NoPairOfLocalRelayCandidateWithRemoteMdnsCandidate) { const Environment env = CreateEnvironment(); - const int kOnlyRelayPorts = webrtc::PORTALLOCATOR_DISABLE_UDP | - webrtc::PORTALLOCATOR_DISABLE_STUN | - webrtc::PORTALLOCATOR_DISABLE_TCP; + const int kOnlyRelayPorts = PORTALLOCATOR_DISABLE_UDP | + PORTALLOCATOR_DISABLE_STUN | + PORTALLOCATOR_DISABLE_TCP; // We use one endpoint to test the behavior of adding remote candidates, and // this endpoint only gathers relay candidates. ConfigureEndpoints(env, OPEN, OPEN, kOnlyRelayPorts, - webrtc::kDefaultPortAllocatorFlags); + kDefaultPortAllocatorFlags); GetEndpoint(0)->cd1_.ch_ = CreateChannel( env, 0, ICE_CANDIDATE_COMPONENT_DEFAULT, kIceParams[0], kIceParams[1]); IceConfig config; // Start gathering and we should have only a single relay port. ep1_ch1()->SetIceConfig(config); ep1_ch1()->MaybeStartGathering(); - EXPECT_THAT( - webrtc::WaitUntil([&] { return ep1_ch1()->gathering_state(); }, + EXPECT_THAT(WaitUntil([&] { return ep1_ch1()->gathering_state(); }, Eq(IceGatheringState::kIceGatheringComplete), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_EQ(1u, ep1_ch1()->ports().size()); // Add a plain remote host candidate and three remote mDNS candidates with the // host, srflx and relay types. Note that the candidates differ in their @@ -6526,9 +6471,9 @@ TEST_F(P2PTransportChannelTest, // ep1 and ep2 will only gather host and srflx candidates with base addresses // kPublicAddrs[0] and kPublicAddrs[1], respectively, and we use a shared // socket in gathering. - const auto kOnlyLocalAndStunPorts = - webrtc::PORTALLOCATOR_DISABLE_RELAY | webrtc::PORTALLOCATOR_DISABLE_TCP | - webrtc::PORTALLOCATOR_ENABLE_SHARED_SOCKET; + const auto kOnlyLocalAndStunPorts = PORTALLOCATOR_DISABLE_RELAY | + PORTALLOCATOR_DISABLE_TCP | + PORTALLOCATOR_ENABLE_SHARED_SOCKET; // ep1 is configured with a NAT so that we do gather a srflx candidate. ConfigureEndpoints(env, NAT_FULL_CONE, OPEN, kOnlyLocalAndStunPorts, kOnlyLocalAndStunPorts); @@ -6546,10 +6491,10 @@ TEST_F(P2PTransportChannelTest, CreateChannels(env); // We should be able to form a srflx-host connection to ep2. - ASSERT_THAT(webrtc::WaitUntil( - [&] { return ep1_ch1()->selected_connection(); }, Ne(nullptr), - {.timeout = TimeDelta::Millis(kMediumTimeout)}), - webrtc::IsRtcOk()); + ASSERT_THAT( + WaitUntil([&] { return ep1_ch1()->selected_connection(); }, Ne(nullptr), + {.timeout = TimeDelta::Millis(kMediumTimeout)}), + IsRtcOk()); EXPECT_TRUE(ep1_ch1()->selected_connection()->local_candidate().is_stun()); EXPECT_TRUE(ep1_ch1()->selected_connection()->remote_candidate().is_local()); @@ -6566,37 +6511,36 @@ TEST_F(P2PTransportChannelTest, ScopedFakeClock clock; const Environment env = CreateEnvironment(); - ConfigureEndpoints(env, OPEN, OPEN, - webrtc::kDefaultPortAllocatorFlags | - webrtc::PORTALLOCATOR_ENABLE_SHARED_SOCKET, - webrtc::kDefaultPortAllocatorFlags | - webrtc::PORTALLOCATOR_ENABLE_SHARED_SOCKET); + ConfigureEndpoints( + env, OPEN, OPEN, + kDefaultPortAllocatorFlags | PORTALLOCATOR_ENABLE_SHARED_SOCKET, + kDefaultPortAllocatorFlags | PORTALLOCATOR_ENABLE_SHARED_SOCKET); auto* ep1 = GetEndpoint(0); auto* ep2 = GetEndpoint(1); - ep1->allocator_->SetCandidateFilter(webrtc::CF_RELAY); - ep2->allocator_->SetCandidateFilter(webrtc::CF_RELAY); + ep1->allocator_->SetCandidateFilter(CF_RELAY); + ep2->allocator_->SetCandidateFilter(CF_RELAY); // Enable continual gathering and also resurfacing gathered candidates upon // the candidate filter changed in the ICE configuration. - IceConfig ice_config = CreateIceConfig(1000, webrtc::GATHER_CONTINUALLY); + IceConfig ice_config = CreateIceConfig(1000, GATHER_CONTINUALLY); ice_config.surface_ice_candidates_on_ice_transport_type_changed = true; CreateChannels(env, ice_config, ice_config); ASSERT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return ep1_ch1()->selected_connection(); }, Ne(nullptr), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); ASSERT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return ep2_ch1()->selected_connection(); }, Ne(nullptr), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_TRUE(ep1_ch1()->selected_connection()->local_candidate().is_relay()); EXPECT_TRUE(ep2_ch1()->selected_connection()->local_candidate().is_relay()); // Loosen the candidate filter at ep1. - ep1->allocator_->SetCandidateFilter(webrtc::CF_ALL); + ep1->allocator_->SetCandidateFilter(CF_ALL); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return ep1_ch1()->selected_connection() != nullptr && ep1_ch1() @@ -6606,13 +6550,13 @@ TEST_F(P2PTransportChannelTest, }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_TRUE(ep1_ch1()->selected_connection()->remote_candidate().is_relay()); // Loosen the candidate filter at ep2. - ep2->allocator_->SetCandidateFilter(webrtc::CF_ALL); + ep2->allocator_->SetCandidateFilter(CF_ALL); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return ep2_ch1()->selected_connection() != nullptr && ep2_ch1() @@ -6622,19 +6566,19 @@ TEST_F(P2PTransportChannelTest, }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); // We have migrated to a host-host candidate pair. EXPECT_TRUE(ep2_ch1()->selected_connection()->remote_candidate().is_local()); // Block the traffic over non-relay-to-relay routes and expect a route change. - fw()->AddRule(false, webrtc::FP_ANY, kPublicAddrs[0], kPublicAddrs[1]); - fw()->AddRule(false, webrtc::FP_ANY, kPublicAddrs[1], kPublicAddrs[0]); - fw()->AddRule(false, webrtc::FP_ANY, kPublicAddrs[0], kTurnUdpExtAddr); - fw()->AddRule(false, webrtc::FP_ANY, kPublicAddrs[1], kTurnUdpExtAddr); + fw()->AddRule(false, FP_ANY, kPublicAddrs[0], kPublicAddrs[1]); + fw()->AddRule(false, FP_ANY, kPublicAddrs[1], kPublicAddrs[0]); + fw()->AddRule(false, FP_ANY, kPublicAddrs[0], kTurnUdpExtAddr); + fw()->AddRule(false, FP_ANY, kPublicAddrs[1], kTurnUdpExtAddr); // We should be able to reuse the previously gathered relay candidates. EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return ep1_ch1() ->selected_connection() @@ -6643,7 +6587,7 @@ TEST_F(P2PTransportChannelTest, }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_TRUE(ep1_ch1()->selected_connection()->remote_candidate().is_relay()); DestroyChannels(); } @@ -6662,35 +6606,34 @@ TEST_F(P2PTransportChannelTest, // 1. We don't generate the srflx candidate when we have public IP. // 2. We keep the host candidate in this case in CheckCandidateFilter even // though we intend to filter them. - ConfigureEndpoints(env, NAT_FULL_CONE, NAT_FULL_CONE, - webrtc::kDefaultPortAllocatorFlags | - webrtc::PORTALLOCATOR_ENABLE_SHARED_SOCKET, - webrtc::kDefaultPortAllocatorFlags | - webrtc::PORTALLOCATOR_ENABLE_SHARED_SOCKET); + ConfigureEndpoints( + env, NAT_FULL_CONE, NAT_FULL_CONE, + kDefaultPortAllocatorFlags | PORTALLOCATOR_ENABLE_SHARED_SOCKET, + kDefaultPortAllocatorFlags | PORTALLOCATOR_ENABLE_SHARED_SOCKET); auto* ep1 = GetEndpoint(0); auto* ep2 = GetEndpoint(1); - ep1->allocator_->SetCandidateFilter(webrtc::CF_RELAY); - ep2->allocator_->SetCandidateFilter(webrtc::CF_RELAY); + ep1->allocator_->SetCandidateFilter(CF_RELAY); + ep2->allocator_->SetCandidateFilter(CF_RELAY); // Enable continual gathering and also resurfacing gathered candidates upon // the candidate filter changed in the ICE configuration. - IceConfig ice_config = CreateIceConfig(1000, webrtc::GATHER_CONTINUALLY); + IceConfig ice_config = CreateIceConfig(1000, GATHER_CONTINUALLY); ice_config.surface_ice_candidates_on_ice_transport_type_changed = true; CreateChannels(env, ice_config, ice_config); ASSERT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return ep1_ch1()->selected_connection(); }, Ne(nullptr), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); ASSERT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return ep2_ch1()->selected_connection(); }, Ne(nullptr), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); - const uint32_t kCandidateFilterNoHost = webrtc::CF_ALL & ~webrtc::CF_HOST; + IsRtcOk()); + const uint32_t kCandidateFilterNoHost = CF_ALL & ~CF_HOST; // Loosen the candidate filter at ep1. ep1->allocator_->SetCandidateFilter(kCandidateFilterNoHost); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return ep1_ch1()->selected_connection() != nullptr && ep1_ch1() @@ -6700,13 +6643,13 @@ TEST_F(P2PTransportChannelTest, }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_TRUE(ep1_ch1()->selected_connection()->remote_candidate().is_relay()); // Loosen the candidate filter at ep2. ep2->allocator_->SetCandidateFilter(kCandidateFilterNoHost); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return ep2_ch1()->selected_connection() != nullptr && ep2_ch1() @@ -6716,18 +6659,18 @@ TEST_F(P2PTransportChannelTest, }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); // We have migrated to a srflx-srflx candidate pair. EXPECT_TRUE(ep2_ch1()->selected_connection()->remote_candidate().is_stun()); // Block the traffic over non-relay-to-relay routes and expect a route change. - fw()->AddRule(false, webrtc::FP_ANY, kPrivateAddrs[0], kPublicAddrs[1]); - fw()->AddRule(false, webrtc::FP_ANY, kPrivateAddrs[1], kPublicAddrs[0]); - fw()->AddRule(false, webrtc::FP_ANY, kPrivateAddrs[0], kTurnUdpExtAddr); - fw()->AddRule(false, webrtc::FP_ANY, kPrivateAddrs[1], kTurnUdpExtAddr); + fw()->AddRule(false, FP_ANY, kPrivateAddrs[0], kPublicAddrs[1]); + fw()->AddRule(false, FP_ANY, kPrivateAddrs[1], kPublicAddrs[0]); + fw()->AddRule(false, FP_ANY, kPrivateAddrs[0], kTurnUdpExtAddr); + fw()->AddRule(false, FP_ANY, kPrivateAddrs[1], kTurnUdpExtAddr); // We should be able to reuse the previously gathered relay candidates. EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return ep1_ch1() ->selected_connection() @@ -6736,7 +6679,7 @@ TEST_F(P2PTransportChannelTest, }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_TRUE(ep1_ch1()->selected_connection()->remote_candidate().is_relay()); DestroyChannels(); } @@ -6751,37 +6694,36 @@ TEST_F(P2PTransportChannelTest, ScopedFakeClock clock; const Environment env = CreateEnvironment(); - ConfigureEndpoints(env, OPEN, OPEN, - webrtc::kDefaultPortAllocatorFlags | - webrtc::PORTALLOCATOR_ENABLE_SHARED_SOCKET, - webrtc::kDefaultPortAllocatorFlags | - webrtc::PORTALLOCATOR_ENABLE_SHARED_SOCKET); + ConfigureEndpoints( + env, OPEN, OPEN, + kDefaultPortAllocatorFlags | PORTALLOCATOR_ENABLE_SHARED_SOCKET, + kDefaultPortAllocatorFlags | PORTALLOCATOR_ENABLE_SHARED_SOCKET); auto* ep1 = GetEndpoint(0); auto* ep2 = GetEndpoint(1); - ep1->allocator_->SetCandidateFilter(webrtc::CF_RELAY); - ep2->allocator_->SetCandidateFilter(webrtc::CF_RELAY); + ep1->allocator_->SetCandidateFilter(CF_RELAY); + ep2->allocator_->SetCandidateFilter(CF_RELAY); // Only gather once. - IceConfig ice_config = CreateIceConfig(1000, webrtc::GATHER_ONCE); + IceConfig ice_config = CreateIceConfig(1000, GATHER_ONCE); ice_config.surface_ice_candidates_on_ice_transport_type_changed = true; CreateChannels(env, ice_config, ice_config); ASSERT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return ep1_ch1()->selected_connection(); }, Ne(nullptr), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); ASSERT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return ep2_ch1()->selected_connection(); }, Ne(nullptr), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); // Loosen the candidate filter at ep1. - ep1->allocator_->SetCandidateFilter(webrtc::CF_ALL); + ep1->allocator_->SetCandidateFilter(CF_ALL); // Wait for a period for any potential surfacing of new candidates. SIMULATED_WAIT(false, kDefaultTimeout, clock); EXPECT_TRUE(ep1_ch1()->selected_connection()->local_candidate().is_relay()); // Loosen the candidate filter at ep2. - ep2->allocator_->SetCandidateFilter(webrtc::CF_ALL); + ep2->allocator_->SetCandidateFilter(CF_ALL); EXPECT_TRUE(ep2_ch1()->selected_connection()->local_candidate().is_relay()); DestroyChannels(); } @@ -6794,18 +6736,17 @@ TEST_F(P2PTransportChannelTest, ScopedFakeClock clock; const Environment env = CreateEnvironment(); - ConfigureEndpoints(env, OPEN, OPEN, - webrtc::kDefaultPortAllocatorFlags | - webrtc::PORTALLOCATOR_ENABLE_SHARED_SOCKET, - webrtc::kDefaultPortAllocatorFlags | - webrtc::PORTALLOCATOR_ENABLE_SHARED_SOCKET); + ConfigureEndpoints( + env, OPEN, OPEN, + kDefaultPortAllocatorFlags | PORTALLOCATOR_ENABLE_SHARED_SOCKET, + kDefaultPortAllocatorFlags | PORTALLOCATOR_ENABLE_SHARED_SOCKET); auto* ep1 = GetEndpoint(0); auto* ep2 = GetEndpoint(1); - ep1->allocator_->SetCandidateFilter(webrtc::CF_ALL); - ep2->allocator_->SetCandidateFilter(webrtc::CF_ALL); + ep1->allocator_->SetCandidateFilter(CF_ALL); + ep2->allocator_->SetCandidateFilter(CF_ALL); // Enable continual gathering and also resurfacing gathered candidates upon // the candidate filter changed in the ICE configuration. - IceConfig ice_config = CreateIceConfig(1000, webrtc::GATHER_CONTINUALLY); + IceConfig ice_config = CreateIceConfig(1000, GATHER_CONTINUALLY); ice_config.surface_ice_candidates_on_ice_transport_type_changed = true; // Pause candidates so we can gather all types of candidates. See // P2PTransportChannel::OnConnectionStateChange, where we would stop the @@ -6815,15 +6756,14 @@ TEST_F(P2PTransportChannelTest, CreateChannels(env, ice_config, ice_config); // We have gathered host, srflx and relay candidates. - EXPECT_THAT( - webrtc::WaitUntil( - [&] { return ep1->saved_candidates_.size(); }, Eq(3u), - {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + EXPECT_THAT(WaitUntil([&] { return ep1->saved_candidates_.size(); }, Eq(3u), + {.timeout = TimeDelta::Millis(kDefaultTimeout), + .clock = &clock}), + IsRtcOk()); ResumeCandidates(0); ResumeCandidates(1); ASSERT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return ep1_ch1()->selected_connection() != nullptr && ep1_ch1() @@ -6838,12 +6778,12 @@ TEST_F(P2PTransportChannelTest, }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); ASSERT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return ep2_ch1()->selected_connection(); }, Ne(nullptr), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); // Test that we have a host-host candidate pair selected and the number of // candidates signaled to the remote peer stays the same. auto test_invariants = [this]() { @@ -6856,15 +6796,15 @@ TEST_F(P2PTransportChannelTest, test_invariants(); // Set a more restrictive candidate filter at ep1. - ep1->allocator_->SetCandidateFilter(webrtc::CF_HOST | webrtc::CF_REFLEXIVE); + ep1->allocator_->SetCandidateFilter(CF_HOST | CF_REFLEXIVE); SIMULATED_WAIT(false, kDefaultTimeout, clock); test_invariants(); - ep1->allocator_->SetCandidateFilter(webrtc::CF_HOST); + ep1->allocator_->SetCandidateFilter(CF_HOST); SIMULATED_WAIT(false, kDefaultTimeout, clock); test_invariants(); - ep1->allocator_->SetCandidateFilter(webrtc::CF_NONE); + ep1->allocator_->SetCandidateFilter(CF_NONE); SIMULATED_WAIT(false, kDefaultTimeout, clock); test_invariants(); DestroyChannels(); @@ -6881,18 +6821,17 @@ TEST_F(P2PTransportChannelTest, SurfaceRequiresCoordination) { const Environment env = CreateEnvironment(FieldTrials::CreateNoGlobal( "WebRTC-IceFieldTrials/skip_relay_to_non_relay_connections:true/")); - ConfigureEndpoints(env, OPEN, OPEN, - webrtc::kDefaultPortAllocatorFlags | - webrtc::PORTALLOCATOR_ENABLE_SHARED_SOCKET, - webrtc::kDefaultPortAllocatorFlags | - webrtc::PORTALLOCATOR_ENABLE_SHARED_SOCKET); + ConfigureEndpoints( + env, OPEN, OPEN, + kDefaultPortAllocatorFlags | PORTALLOCATOR_ENABLE_SHARED_SOCKET, + kDefaultPortAllocatorFlags | PORTALLOCATOR_ENABLE_SHARED_SOCKET); auto* ep1 = GetEndpoint(0); auto* ep2 = GetEndpoint(1); - ep1->allocator_->SetCandidateFilter(webrtc::CF_RELAY); - ep2->allocator_->SetCandidateFilter(webrtc::CF_ALL); + ep1->allocator_->SetCandidateFilter(CF_RELAY); + ep2->allocator_->SetCandidateFilter(CF_ALL); // Enable continual gathering and also resurfacing gathered candidates upon // the candidate filter changed in the ICE configuration. - IceConfig ice_config = CreateIceConfig(1000, webrtc::GATHER_CONTINUALLY); + IceConfig ice_config = CreateIceConfig(1000, GATHER_CONTINUALLY); ice_config.surface_ice_candidates_on_ice_transport_type_changed = true; // Pause candidates gathering so we can gather all types of candidates. See // P2PTransportChannel::OnConnectionStateChange, where we would stop the @@ -6903,21 +6842,19 @@ TEST_F(P2PTransportChannelTest, SurfaceRequiresCoordination) { // On the caller we only have relay, // on the callee we have host, srflx and relay. - EXPECT_THAT( - webrtc::WaitUntil( - [&] { return ep1->saved_candidates_.size(); }, Eq(1u), - {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); - EXPECT_THAT( - webrtc::WaitUntil( - [&] { return ep2->saved_candidates_.size(); }, Eq(3u), - {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + EXPECT_THAT(WaitUntil([&] { return ep1->saved_candidates_.size(); }, Eq(1u), + {.timeout = TimeDelta::Millis(kDefaultTimeout), + .clock = &clock}), + IsRtcOk()); + EXPECT_THAT(WaitUntil([&] { return ep2->saved_candidates_.size(); }, Eq(3u), + {.timeout = TimeDelta::Millis(kDefaultTimeout), + .clock = &clock}), + IsRtcOk()); ResumeCandidates(0); ResumeCandidates(1); ASSERT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return ep1_ch1()->selected_connection() != nullptr && ep1_ch1() @@ -6932,19 +6869,19 @@ TEST_F(P2PTransportChannelTest, SurfaceRequiresCoordination) { }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); ASSERT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return ep2_ch1()->selected_connection(); }, Ne(nullptr), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); // Wait until the callee discards it's candidates // since they don't manage to connect. SIMULATED_WAIT(false, 300000, clock); // And then loosen caller candidate filter. - ep1->allocator_->SetCandidateFilter(webrtc::CF_ALL); + ep1->allocator_->SetCandidateFilter(CF_ALL); SIMULATED_WAIT(false, kDefaultTimeout, clock); @@ -6978,10 +6915,10 @@ TEST_F(P2PTransportChannelPingTest, TestInitialSelectDampening0) { conn1->ReceivedPingResponse(LOW_RTT, "id"); // Becomes writable and receiving // It shall not be selected until 0ms has passed....i.e it should be connected // directly. - EXPECT_THAT(webrtc::WaitUntil( - [&] { return ch.selected_connection(); }, Eq(conn1), - {.timeout = TimeDelta::Millis(kMargin), .clock = &clock}), - webrtc::IsRtcOk()); + EXPECT_THAT( + WaitUntil([&] { return ch.selected_connection(); }, Eq(conn1), + {.timeout = TimeDelta::Millis(kMargin), .clock = &clock}), + IsRtcOk()); } TEST_F(P2PTransportChannelPingTest, TestInitialSelectDampening) { @@ -7005,10 +6942,10 @@ TEST_F(P2PTransportChannelPingTest, TestInitialSelectDampening) { conn1->ReceivedPingResponse(LOW_RTT, "id"); // Becomes writable and receiving // It shall not be selected until 100ms has passed. SIMULATED_WAIT(conn1 == ch.selected_connection(), 100 - kMargin, clock); - EXPECT_THAT(webrtc::WaitUntil( - [&] { return ch.selected_connection(); }, Eq(conn1), - {.timeout = TimeDelta::Millis(2 * kMargin), .clock = &clock}), - webrtc::IsRtcOk()); + EXPECT_THAT( + WaitUntil([&] { return ch.selected_connection(); }, Eq(conn1), + {.timeout = TimeDelta::Millis(2 * kMargin), .clock = &clock}), + IsRtcOk()); } TEST_F(P2PTransportChannelPingTest, TestInitialSelectDampeningPingReceived) { @@ -7033,10 +6970,10 @@ TEST_F(P2PTransportChannelPingTest, TestInitialSelectDampeningPingReceived) { conn1->ReceivedPing("id1"); // // It shall not be selected until 100ms has passed. SIMULATED_WAIT(conn1 == ch.selected_connection(), 100 - kMargin, clock); - EXPECT_THAT(webrtc::WaitUntil( - [&] { return ch.selected_connection(); }, Eq(conn1), - {.timeout = TimeDelta::Millis(2 * kMargin), .clock = &clock}), - webrtc::IsRtcOk()); + EXPECT_THAT( + WaitUntil([&] { return ch.selected_connection(); }, Eq(conn1), + {.timeout = TimeDelta::Millis(2 * kMargin), .clock = &clock}), + IsRtcOk()); } TEST_F(P2PTransportChannelPingTest, TestInitialSelectDampeningBoth) { @@ -7064,16 +7001,15 @@ TEST_F(P2PTransportChannelPingTest, TestInitialSelectDampeningBoth) { SIMULATED_WAIT(conn1 == ch.selected_connection(), 50 - kMargin, clock); // Now receiving ping and new timeout should kick in. conn1->ReceivedPing("id1"); // - EXPECT_THAT(webrtc::WaitUntil( - [&] { return ch.selected_connection(); }, Eq(conn1), - {.timeout = TimeDelta::Millis(2 * kMargin), .clock = &clock}), - webrtc::IsRtcOk()); + EXPECT_THAT( + WaitUntil([&] { return ch.selected_connection(); }, Eq(conn1), + {.timeout = TimeDelta::Millis(2 * kMargin), .clock = &clock}), + IsRtcOk()); } TEST(P2PTransportChannelIceControllerTest, InjectIceController) { const Environment env = CreateEnvironment(); - std::unique_ptr socket_server = - webrtc::CreateDefaultSocketServer(); + std::unique_ptr socket_server = CreateDefaultSocketServer(); AutoSocketServerThread main_thread(socket_server.get()); MockIceControllerFactory factory; FakePortAllocator pa(env, socket_server.get()); @@ -7089,8 +7025,7 @@ TEST(P2PTransportChannelIceControllerTest, InjectIceController) { TEST(P2PTransportChannel, InjectActiveIceController) { const Environment env = CreateEnvironment(); - std::unique_ptr socket_server = - webrtc::CreateDefaultSocketServer(); + std::unique_ptr socket_server = CreateDefaultSocketServer(); AutoSocketServerThread main_thread(socket_server.get()); MockActiveIceControllerFactory factory; FakePortAllocator pa(env, socket_server.get()); @@ -7139,7 +7074,7 @@ class ForgetLearnedStateControllerFactory controller_ = controller.get(); return controller; } - virtual ~ForgetLearnedStateControllerFactory() = default; + ~ForgetLearnedStateControllerFactory() override = default; ForgetLearnedStateController* controller_; }; @@ -7169,10 +7104,9 @@ TEST_F(P2PTransportChannelPingTest, TestForgetLearnedState) { // Wait for conn1 to be selected. conn1->ReceivedPingResponse(LOW_RTT, "id"); - EXPECT_THAT( - webrtc::WaitUntil([&] { return ch->selected_connection(); }, Eq(conn1), + EXPECT_THAT(WaitUntil([&] { return ch->selected_connection(); }, Eq(conn1), {.timeout = TimeDelta::Millis(kMediumTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); conn2->ReceivedPingResponse(LOW_RTT, "id"); EXPECT_TRUE(conn2->writable()); @@ -7184,17 +7118,17 @@ TEST_F(P2PTransportChannelPingTest, TestForgetLearnedState) { // We don't have a mock Connection, so verify this by checking that it // is no longer writable. - EXPECT_THAT(webrtc::WaitUntil([&] { return conn2->writable(); }, IsFalse(), - {.timeout = TimeDelta::Millis(kMediumTimeout)}), - webrtc::IsRtcOk()); + EXPECT_THAT(WaitUntil([&] { return conn2->writable(); }, IsFalse(), + {.timeout = TimeDelta::Millis(kMediumTimeout)}), + IsRtcOk()); } TEST_F(P2PTransportChannelTest, DisableDnsLookupsWithTransportPolicyRelay) { const Environment env = CreateEnvironment(); - ConfigureEndpoints(env, OPEN, OPEN, webrtc::kDefaultPortAllocatorFlags, - webrtc::kDefaultPortAllocatorFlags); + ConfigureEndpoints(env, OPEN, OPEN, kDefaultPortAllocatorFlags, + kDefaultPortAllocatorFlags); auto* ep1 = GetEndpoint(0); - ep1->allocator_->SetCandidateFilter(webrtc::CF_RELAY); + ep1->allocator_->SetCandidateFilter(CF_RELAY); std::unique_ptr mock_async_resolver = std::make_unique(); @@ -7218,10 +7152,10 @@ TEST_F(P2PTransportChannelTest, DisableDnsLookupsWithTransportPolicyRelay) { TEST_F(P2PTransportChannelTest, DisableDnsLookupsWithTransportPolicyNone) { const Environment env = CreateEnvironment(); - ConfigureEndpoints(env, OPEN, OPEN, webrtc::kDefaultPortAllocatorFlags, - webrtc::kDefaultPortAllocatorFlags); + ConfigureEndpoints(env, OPEN, OPEN, kDefaultPortAllocatorFlags, + kDefaultPortAllocatorFlags); auto* ep1 = GetEndpoint(0); - ep1->allocator_->SetCandidateFilter(webrtc::CF_NONE); + ep1->allocator_->SetCandidateFilter(CF_NONE); std::unique_ptr mock_async_resolver = std::make_unique(); @@ -7245,10 +7179,10 @@ TEST_F(P2PTransportChannelTest, DisableDnsLookupsWithTransportPolicyNone) { TEST_F(P2PTransportChannelTest, EnableDnsLookupsWithTransportPolicyNoHost) { const Environment env = CreateEnvironment(); - ConfigureEndpoints(env, OPEN, OPEN, webrtc::kDefaultPortAllocatorFlags, - webrtc::kDefaultPortAllocatorFlags); + ConfigureEndpoints(env, OPEN, OPEN, kDefaultPortAllocatorFlags, + kDefaultPortAllocatorFlags); auto* ep1 = GetEndpoint(0); - ep1->allocator_->SetCandidateFilter(webrtc::CF_ALL & ~webrtc::CF_HOST); + ep1->allocator_->SetCandidateFilter(CF_ALL & ~CF_HOST); std::unique_ptr mock_async_resolver = std::make_unique(); @@ -7273,6 +7207,125 @@ TEST_F(P2PTransportChannelTest, EnableDnsLookupsWithTransportPolicyNoHost) { DestroyChannels(); } +static struct LocalAreaNetworkPermissionTestConfig { + template + friend void AbslStringify( + Sink& sink, + const LocalAreaNetworkPermissionTestConfig& config) { + sink.Append(config.address); + sink.Append("_"); + switch (config.lna_permission_status) { + case webrtc::LocalNetworkAccessPermissionStatus::kDenied: + sink.Append("Denied"); + break; + case webrtc::LocalNetworkAccessPermissionStatus::kGranted: + sink.Append("Granted"); + break; + } + } + + webrtc::LocalNetworkAccessPermissionStatus lna_permission_status; + absl::string_view address; + bool candidate_added; +} kAllLocalAreNetworkPermissionTestConfigs[] = { + {LocalNetworkAccessPermissionStatus::kDenied, "127.0.0.1", + /*candidate_added=*/false}, + {LocalNetworkAccessPermissionStatus::kDenied, "10.0.0.3", + /*candidate_added=*/false}, + {LocalNetworkAccessPermissionStatus::kDenied, "1.1.1.1", + /*candidate_added=*/true}, + {LocalNetworkAccessPermissionStatus::kDenied, "::1", + /*candidate_added=*/false}, + {LocalNetworkAccessPermissionStatus::kDenied, "fd00:4860:4860::8844", + /*candidate_added=*/false}, + {LocalNetworkAccessPermissionStatus::kDenied, "2001:4860:4860::8888", + /*candidate_added=*/true}, + {LocalNetworkAccessPermissionStatus::kGranted, "127.0.0.1", + /*candidate_added=*/true}, + {LocalNetworkAccessPermissionStatus::kGranted, "10.0.0.3", + /*candidate_added=*/true}, + {LocalNetworkAccessPermissionStatus::kGranted, "1.1.1.1", + /*candidate_added=*/true}, + {LocalNetworkAccessPermissionStatus::kGranted, "::1", + /*candidate_added=*/true}, + {LocalNetworkAccessPermissionStatus::kGranted, "fd00:4860:4860::8844", + /*candidate_added=*/true}, + {LocalNetworkAccessPermissionStatus::kGranted, "2001:4860:4860::8888", + /*candidate_added=*/true}, +}; + +class LocalAreaNetworkPermissionTest + : public P2PTransportChannelPingTest, + public ::testing::WithParamInterface< + LocalAreaNetworkPermissionTestConfig> {}; + +TEST_P(LocalAreaNetworkPermissionTest, LiteralAddresses) { + const Environment env = CreateEnvironment(); + FakePortAllocator pa(env, ss()); + PermissionFactoryFixture lna_permission_factory( + GetParam().lna_permission_status); + + IceTransportInit init; + init.set_port_allocator(&pa); + init.set_field_trials(&env.field_trials()); + init.set_lna_permission_factory(&lna_permission_factory); + + auto ch = P2PTransportChannel::Create("foo", 1, std::move(init)); + PrepareChannel(ch.get()); + ch->MaybeStartGathering(); + + ch->AddRemoteCandidate( + CreateUdpCandidate(IceCandidateType::kHost, GetParam().address, 5000, 1)); + + ASSERT_THAT( + WaitUntil([&] { return ch->PermissionQueriesOutstandingForTesting(); }, + Eq(0)), + IsRtcOk()); + if (GetParam().candidate_added) { + EXPECT_EQ(1u, ch->remote_candidates().size()); + } else { + EXPECT_EQ(0u, ch->remote_candidates().size()); + } +} + +TEST_P(LocalAreaNetworkPermissionTest, UnresolvedAddresses) { + const Environment env = CreateEnvironment(); + FakePortAllocator pa(env, ss()); + PermissionFactoryFixture lna_permission_factory( + GetParam().lna_permission_status); + + ResolverFactoryFixture resolver_fixture; + resolver_fixture.SetAddressToReturn({GetParam().address, 5000}); + + IceTransportInit init; + init.set_port_allocator(&pa); + init.set_field_trials(&env.field_trials()); + init.set_lna_permission_factory(&lna_permission_factory); + init.set_async_dns_resolver_factory(&resolver_fixture); + + auto ch = P2PTransportChannel::Create("foo", 1, std::move(init)); + PrepareChannel(ch.get()); + ch->MaybeStartGathering(); + + ch->AddRemoteCandidate( + CreateUdpCandidate(IceCandidateType::kHost, "fake.test", 5000, 1)); + + ASSERT_THAT( + WaitUntil([&] { return ch->PermissionQueriesOutstandingForTesting(); }, + Eq(0)), + IsRtcOk()); + if (GetParam().candidate_added) { + EXPECT_EQ(1u, ch->remote_candidates().size()); + } else { + EXPECT_EQ(0u, ch->remote_candidates().size()); + } +} + +INSTANTIATE_TEST_SUITE_P( + All, + LocalAreaNetworkPermissionTest, + ::testing::ValuesIn(kAllLocalAreNetworkPermissionTestConfigs)); + class GatherAfterConnectedTest : public P2PTransportChannelTest, public WithParamInterface {}; @@ -7288,22 +7341,21 @@ TEST_P(GatherAfterConnectedTest, GatherAfterConnected) { const Environment env = CreateEnvironment(FieldTrials::CreateNoGlobal(field_trial)); // Use local + relay - constexpr uint32_t flags = webrtc::kDefaultPortAllocatorFlags | - webrtc::PORTALLOCATOR_ENABLE_SHARED_SOCKET | - webrtc::PORTALLOCATOR_DISABLE_STUN | - webrtc::PORTALLOCATOR_DISABLE_TCP; + constexpr uint32_t flags = + kDefaultPortAllocatorFlags | PORTALLOCATOR_ENABLE_SHARED_SOCKET | + PORTALLOCATOR_DISABLE_STUN | PORTALLOCATOR_DISABLE_TCP; ConfigureEndpoints(env, OPEN, OPEN, flags, flags); auto* ep1 = GetEndpoint(0); auto* ep2 = GetEndpoint(1); - ep1->allocator_->SetCandidateFilter(webrtc::CF_ALL); - ep2->allocator_->SetCandidateFilter(webrtc::CF_ALL); + ep1->allocator_->SetCandidateFilter(CF_ALL); + ep2->allocator_->SetCandidateFilter(CF_ALL); // Use step delay 3s which is long enough for // connection to be established before managing to gather relay candidates. int delay = 3000; SetAllocationStepDelay(0, delay); SetAllocationStepDelay(1, delay); - IceConfig ice_config = CreateIceConfig(1000, webrtc::GATHER_CONTINUALLY); + IceConfig ice_config = CreateIceConfig(1000, GATHER_CONTINUALLY); CreateChannels(env, ice_config, ice_config); PauseCandidates(0); @@ -7311,14 +7363,14 @@ TEST_P(GatherAfterConnectedTest, GatherAfterConnected) { // We have gathered host candidates but not relay. ASSERT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return ep1->saved_candidates_.size() == 1u && ep2->saved_candidates_.size() == 1u; }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); ResumeCandidates(0); ResumeCandidates(1); @@ -7327,24 +7379,24 @@ TEST_P(GatherAfterConnectedTest, GatherAfterConnected) { PauseCandidates(1); ASSERT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return ep1_ch1()->remote_candidates().size() == 1 && ep2_ch1()->remote_candidates().size() == 1; }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); ASSERT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return ep1_ch1()->selected_connection() && ep2_ch1()->selected_connection(); }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); clock.AdvanceTime(TimeDelta::Millis(10 * delay)); @@ -7370,23 +7422,22 @@ TEST_P(GatherAfterConnectedTest, GatherAfterConnectedMultiHomed) { CreateEnvironment(FieldTrials::CreateNoGlobal(field_trial)); // Use local + relay - constexpr uint32_t flags = webrtc::kDefaultPortAllocatorFlags | - webrtc::PORTALLOCATOR_ENABLE_SHARED_SOCKET | - webrtc::PORTALLOCATOR_DISABLE_STUN | - webrtc::PORTALLOCATOR_DISABLE_TCP; + constexpr uint32_t flags = + kDefaultPortAllocatorFlags | PORTALLOCATOR_ENABLE_SHARED_SOCKET | + PORTALLOCATOR_DISABLE_STUN | PORTALLOCATOR_DISABLE_TCP; AddAddress(0, kAlternateAddrs[0]); ConfigureEndpoints(env, OPEN, OPEN, flags, flags); auto* ep1 = GetEndpoint(0); auto* ep2 = GetEndpoint(1); - ep1->allocator_->SetCandidateFilter(webrtc::CF_ALL); - ep2->allocator_->SetCandidateFilter(webrtc::CF_ALL); + ep1->allocator_->SetCandidateFilter(CF_ALL); + ep2->allocator_->SetCandidateFilter(CF_ALL); // Use step delay 3s which is long enough for // connection to be established before managing to gather relay candidates. int delay = 3000; SetAllocationStepDelay(0, delay); SetAllocationStepDelay(1, delay); - IceConfig ice_config = CreateIceConfig(1000, webrtc::GATHER_CONTINUALLY); + IceConfig ice_config = CreateIceConfig(1000, GATHER_CONTINUALLY); CreateChannels(env, ice_config, ice_config); PauseCandidates(0); @@ -7394,14 +7445,14 @@ TEST_P(GatherAfterConnectedTest, GatherAfterConnectedMultiHomed) { // We have gathered host candidates but not relay. ASSERT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return ep1->saved_candidates_.size() == 2u && ep2->saved_candidates_.size() == 1u; }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); ResumeCandidates(0); ResumeCandidates(1); @@ -7410,24 +7461,24 @@ TEST_P(GatherAfterConnectedTest, GatherAfterConnectedMultiHomed) { PauseCandidates(1); ASSERT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return ep1_ch1()->remote_candidates().size() == 1 && ep2_ch1()->remote_candidates().size() == 2; }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); ASSERT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return ep1_ch1()->selected_connection() && ep2_ch1()->selected_connection(); }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); clock.AdvanceTime(TimeDelta::Millis(10 * delay)); @@ -7448,18 +7499,18 @@ TEST_F(P2PTransportChannelTest, TestIceNoOldCandidatesAfterIceRestart) { ScopedFakeClock clock; const Environment env = CreateEnvironment(); AddAddress(0, kAlternateAddrs[0]); - ConfigureEndpoints(env, OPEN, OPEN, webrtc::kDefaultPortAllocatorFlags, - webrtc::kDefaultPortAllocatorFlags); + ConfigureEndpoints(env, OPEN, OPEN, kDefaultPortAllocatorFlags, + kDefaultPortAllocatorFlags); // gathers continually. - IceConfig config = CreateIceConfig(1000, webrtc::GATHER_CONTINUALLY); + IceConfig config = CreateIceConfig(1000, GATHER_CONTINUALLY); CreateChannels(env, config, config); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return CheckConnected(ep1_ch1(), ep2_ch1()); }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); PauseCandidates(0); @@ -7467,10 +7518,10 @@ TEST_F(P2PTransportChannelTest, TestIceNoOldCandidatesAfterIceRestart) { ep1_ch1()->MaybeStartGathering(); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return GetEndpoint(0)->saved_candidates_.size(); }, Gt(0), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); for (const auto& cd : GetEndpoint(0)->saved_candidates_) { EXPECT_EQ(cd.candidate.username(), kIceUfrag[3]); @@ -7511,10 +7562,10 @@ class P2PTransportChannelTestDtlsInStun : public P2PTransportChannelTestBase { [&](auto data, auto ack) { piggyback_data_received(data, ack); })); } EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return CheckConnected(ep1_ch1(), ep2_ch1()); }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock_}), - webrtc::IsRtcOk()); + IsRtcOk()); DestroyChannels(); } diff --git a/p2p/base/packet_transport_internal.h b/p2p/base/packet_transport_internal.h index a326ce7e5c..2418cf4b3c 100644 --- a/p2p/base/packet_transport_internal.h +++ b/p2p/base/packet_transport_internal.h @@ -83,8 +83,8 @@ class RTC_EXPORT PacketTransportInternal : public sigslot::has_slots<> { // Callback is invoked each time a packet is received on this channel. void RegisterReceivedPacketCallback( void* id, - absl::AnyInvocable callback); + absl::AnyInvocable callback); void DeregisterReceivedPacketCallback(void* id); diff --git a/p2p/base/port.h b/p2p/base/port.h index 522fc9329e..b7dbe49a3d 100644 --- a/p2p/base/port.h +++ b/p2p/base/port.h @@ -386,7 +386,7 @@ class RTC_EXPORT Port : public PortInterface, public sigslot::has_slots<> { void OnReadPacket(const ReceivedIpPacket& packet, ProtocolType proto); [[deprecated( - "Use OnReadPacket(const webrtc::ReceivedIpPacket& packet, ProtocolType " + "Use OnReadPacket(const ReceivedIpPacket& packet, ProtocolType " "proto)")]] void OnReadPacket(const char* data, size_t size, diff --git a/p2p/base/port_allocator.h b/p2p/base/port_allocator.h index 3b957720ef..997ddfb852 100644 --- a/p2p/base/port_allocator.h +++ b/p2p/base/port_allocator.h @@ -548,7 +548,7 @@ class RTC_EXPORT PortAllocator : public sigslot::has_slots<> { // Deprecated (by the next method). bool prune_turn_ports() const { CheckRunOnValidThreadIfInitialized(); - return turn_port_prune_policy_ == webrtc::PRUNE_BASED_ON_PRIORITY; + return turn_port_prune_policy_ == PRUNE_BASED_ON_PRIORITY; } PortPrunePolicy turn_port_prune_policy() const { @@ -619,7 +619,7 @@ class RTC_EXPORT PortAllocator : public sigslot::has_slots<> { std::vector turn_servers_; int candidate_pool_size_ = 0; // Last value passed into SetConfiguration. std::vector> pooled_sessions_; - PortPrunePolicy turn_port_prune_policy_ = webrtc::NO_PRUNE; + PortPrunePolicy turn_port_prune_policy_ = NO_PRUNE; // Customizer for TURN messages. // The instance is owned by application and will be shared among diff --git a/p2p/base/port_interface.h b/p2p/base/port_interface.h index 93a3a252ee..3d0b014522 100644 --- a/p2p/base/port_interface.h +++ b/p2p/base/port_interface.h @@ -121,7 +121,7 @@ class PortInterface { // Signaled when this port decides to delete itself because it no longer has // any usefulness. virtual void SubscribePortDestroyed( - std::function callback) = 0; + std::function callback) = 0; // Signaled when Port discovers ice role conflict with the peer. sigslot::signal1 SignalRoleConflict; diff --git a/p2p/base/port_unittest.cc b/p2p/base/port_unittest.cc index 5bf4b43347..68b0aea338 100644 --- a/p2p/base/port_unittest.cc +++ b/p2p/base/port_unittest.cc @@ -105,10 +105,10 @@ constexpr int kMaxExpectedSimulatedRtt = 200; const SocketAddress kLocalAddr1("192.168.1.2", 0); const SocketAddress kLocalAddr2("192.168.1.3", 0); const SocketAddress kLinkLocalIPv6Addr("fe80::aabb:ccff:fedd:eeff", 0); -const SocketAddress kNatAddr1("77.77.77.77", webrtc::NAT_SERVER_UDP_PORT); -const SocketAddress kNatAddr2("88.88.88.88", webrtc::NAT_SERVER_UDP_PORT); -const SocketAddress kStunAddr("99.99.99.1", webrtc::STUN_SERVER_PORT); -const SocketAddress kTurnUdpIntAddr("99.99.99.4", webrtc::STUN_SERVER_PORT); +const SocketAddress kNatAddr1("77.77.77.77", NAT_SERVER_UDP_PORT); +const SocketAddress kNatAddr2("88.88.88.88", NAT_SERVER_UDP_PORT); +const SocketAddress kStunAddr("99.99.99.1", STUN_SERVER_PORT); +const SocketAddress kTurnUdpIntAddr("99.99.99.4", STUN_SERVER_PORT); const SocketAddress kTurnTcpIntAddr("99.99.99.4", 5010); const SocketAddress kTurnUdpExtAddr("99.99.99.5", 0); const RelayCredentials kRelayCredentials("test", "test"); @@ -155,7 +155,7 @@ class TestPort : public Port { public: TestPort(const PortParametersRef& args, uint16_t min_port, uint16_t max_port) : Port(args, IceCandidateType::kHost, min_port, max_port) {} - ~TestPort() {} + ~TestPort() override {} // Expose GetStunMessage so that we can test it. using Port::GetStunMessage; @@ -178,7 +178,7 @@ class TestPort : public Port { return code; } - virtual void PrepareAddress() { + void PrepareAddress() override { // Act as if the socket was bound to the best IP on the network, to the // first port in the allowed range. SocketAddress addr(Network()->GetBestIP(), min_port()); @@ -186,11 +186,11 @@ class TestPort : public Port { ICE_TYPE_PREFERENCE_HOST, 0, "", true); } - virtual bool SupportsProtocol(absl::string_view /* protocol */) const { + bool SupportsProtocol(absl::string_view /* protocol */) const override { return true; } - virtual ProtocolType GetProtocol() const { return webrtc::PROTO_UDP; } + ProtocolType GetProtocol() const override { return PROTO_UDP; } // Exposed for testing candidate building. void AddCandidateAddress(const SocketAddress& addr) { @@ -206,8 +206,8 @@ class TestPort : public Port { type_preference, 0, "", final); } - virtual Connection* CreateConnection(const Candidate& remote_candidate, - CandidateOrigin /* origin */) { + Connection* CreateConnection(const Candidate& remote_candidate, + CandidateOrigin /* origin */) override { Connection* conn = new ProxyConnection(NewWeakPtr(), 0, remote_candidate); AddOrReplaceConnection(conn); // Set use-candidate attribute flag as this will add USE-CANDIDATE attribute @@ -215,11 +215,11 @@ class TestPort : public Port { conn->set_use_candidate_attr(true); return conn; } - virtual int SendTo(const void* data, - size_t size, - const SocketAddress& /* addr */, - const AsyncSocketPacketOptions& /* options */, - bool payload) { + int SendTo(const void* data, + size_t size, + const SocketAddress& /* addr */, + const AsyncSocketPacketOptions& /* options */, + bool payload) override { if (!payload) { auto msg = std::make_unique(); auto buf = std::make_unique>( @@ -233,9 +233,11 @@ class TestPort : public Port { } return static_cast(size); } - virtual int SetOption(Socket::Option /* opt */, int /* value */) { return 0; } - virtual int GetOption(Socket::Option opt, int* value) { return -1; } - virtual int GetError() { return 0; } + int SetOption(Socket::Option /* opt */, int /* value */) override { + return 0; + } + int GetOption(Socket::Option opt, int* value) override { return -1; } + int GetError() override { return 0; } void Reset() { last_stun_buf_.reset(); last_stun_msg_.reset(); @@ -246,7 +248,7 @@ class TestPort : public Port { private: void OnSentPacket(AsyncPacketSocket* socket, - const SentPacketInfo& sent_packet) { + const SentPacketInfo& sent_packet) override { PortInterface::SignalSentPacket(sent_packet); } std::unique_ptr> last_stun_buf_; @@ -269,20 +271,18 @@ static void SendPingAndReceiveResponse(Connection* lconn, TestPort* rport, ScopedFakeClock* clock, int64_t ms) { - lconn->Ping(webrtc::TimeMillis()); - ASSERT_THAT( - webrtc::WaitUntil([&] { return lport->last_stun_msg(); }, IsTrue(), + lconn->Ping(TimeMillis()); + ASSERT_THAT(WaitUntil([&] { return lport->last_stun_msg(); }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); ASSERT_GT(lport->last_stun_buf().size(), 0u); rconn->OnReadPacket( ReceivedIpPacket(lport->last_stun_buf(), SocketAddress(), std::nullopt)); clock->AdvanceTime(TimeDelta::Millis(ms)); - ASSERT_THAT( - webrtc::WaitUntil([&] { return rport->last_stun_msg(); }, IsTrue(), + ASSERT_THAT(WaitUntil([&] { return rport->last_stun_msg(); }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); ASSERT_GT(rport->last_stun_buf().size(), 0u); lconn->OnReadPacket( ReceivedIpPacket(rport->last_stun_buf(), SocketAddress(), std::nullopt)); @@ -298,7 +298,7 @@ class TestChannel : public sigslot::has_slots<> { [this](PortInterface* port) { OnSrcPortDestroyed(port); }); } - ~TestChannel() { Stop(); } + ~TestChannel() override { Stop(); } int complete_count() { return complete_count_; } Connection* conn() { return conn_; } @@ -309,10 +309,9 @@ class TestChannel : public sigslot::has_slots<> { void CreateConnection(const Candidate& remote_candidate) { RTC_DCHECK(!conn_); conn_ = port_->CreateConnection(remote_candidate, Port::ORIGIN_MESSAGE); - IceMode remote_ice_mode = (ice_mode_ == webrtc::ICEMODE_FULL) - ? webrtc::ICEMODE_LITE - : webrtc::ICEMODE_FULL; - conn_->set_use_candidate_attr(remote_ice_mode == webrtc::ICEMODE_FULL); + IceMode remote_ice_mode = + (ice_mode_ == ICEMODE_FULL) ? ICEMODE_LITE : ICEMODE_FULL; + conn_->set_use_candidate_attr(remote_ice_mode == ICEMODE_FULL); conn_->SignalStateChange.connect(this, &TestChannel::OnConnectionStateChange); conn_->SignalDestroyed.connect(this, &TestChannel::OnDestroyed); @@ -412,7 +411,7 @@ class TestChannel : public sigslot::has_slots<> { connection_ready_to_send_ = true; } - IceMode ice_mode_ = webrtc::ICEMODE_FULL; + IceMode ice_mode_ = ICEMODE_FULL; std::unique_ptr port_; int complete_count_ = 0; @@ -436,12 +435,12 @@ class PortTest : public ::testing::Test, public sigslot::has_slots<> { nat_socket_factory2_(&nat_factory2_), stun_server_(TestStunServer::Create(ss_.get(), kStunAddr, main_)), turn_server_(&main_, ss_.get(), kTurnUdpIntAddr, kTurnUdpExtAddr), - username_(webrtc::CreateRandomString(ICE_UFRAG_LENGTH)), - password_(webrtc::CreateRandomString(ICE_PWD_LENGTH)), + username_(CreateRandomString(ICE_UFRAG_LENGTH)), + password_(CreateRandomString(ICE_PWD_LENGTH)), role_conflict_(false), ports_destroyed_(0) {} - ~PortTest() { + ~PortTest() override { // Workaround for tests that trigger async destruction of objects that we // need to give an opportunity here to run, before proceeding with other // teardown. @@ -453,84 +452,82 @@ class PortTest : public ::testing::Test, public sigslot::has_slots<> { void TestLocalToLocal() { auto port1 = CreateUdpPort(kLocalAddr1); - port1->SetIceRole(webrtc::ICEROLE_CONTROLLING); + port1->SetIceRole(ICEROLE_CONTROLLING); auto port2 = CreateUdpPort(kLocalAddr2); - port2->SetIceRole(webrtc::ICEROLE_CONTROLLED); + port2->SetIceRole(ICEROLE_CONTROLLED); TestConnectivity("udp", std::move(port1), "udp", std::move(port2), true, true, true, true); } void TestLocalToStun(NATType ntype) { auto port1 = CreateUdpPort(kLocalAddr1); - port1->SetIceRole(webrtc::ICEROLE_CONTROLLING); + port1->SetIceRole(ICEROLE_CONTROLLING); nat_server2_ = CreateNatServer(kNatAddr2, ntype); auto port2 = CreateStunPort(kLocalAddr2, &nat_socket_factory2_); - port2->SetIceRole(webrtc::ICEROLE_CONTROLLED); + port2->SetIceRole(ICEROLE_CONTROLLED); TestConnectivity("udp", std::move(port1), StunName(ntype), std::move(port2), - ntype == webrtc::NAT_OPEN_CONE, true, - ntype != webrtc::NAT_SYMMETRIC, true); + ntype == NAT_OPEN_CONE, true, ntype != NAT_SYMMETRIC, + true); } void TestLocalToRelay(ProtocolType proto) { auto port1 = CreateUdpPort(kLocalAddr1); - port1->SetIceRole(webrtc::ICEROLE_CONTROLLING); - auto port2 = CreateRelayPort(kLocalAddr2, proto, webrtc::PROTO_UDP); - port2->SetIceRole(webrtc::ICEROLE_CONTROLLED); + port1->SetIceRole(ICEROLE_CONTROLLING); + auto port2 = CreateRelayPort(kLocalAddr2, proto, PROTO_UDP); + port2->SetIceRole(ICEROLE_CONTROLLED); TestConnectivity("udp", std::move(port1), RelayName(proto), std::move(port2), false, true, true, true); } void TestStunToLocal(NATType ntype) { nat_server1_ = CreateNatServer(kNatAddr1, ntype); auto port1 = CreateStunPort(kLocalAddr1, &nat_socket_factory1_); - port1->SetIceRole(webrtc::ICEROLE_CONTROLLING); + port1->SetIceRole(ICEROLE_CONTROLLING); auto port2 = CreateUdpPort(kLocalAddr2); - port2->SetIceRole(webrtc::ICEROLE_CONTROLLED); + port2->SetIceRole(ICEROLE_CONTROLLED); TestConnectivity(StunName(ntype), std::move(port1), "udp", std::move(port2), - true, ntype != webrtc::NAT_SYMMETRIC, true, true); + true, ntype != NAT_SYMMETRIC, true, true); } void TestStunToStun(NATType ntype1, NATType ntype2) { nat_server1_ = CreateNatServer(kNatAddr1, ntype1); auto port1 = CreateStunPort(kLocalAddr1, &nat_socket_factory1_); - port1->SetIceRole(webrtc::ICEROLE_CONTROLLING); + port1->SetIceRole(ICEROLE_CONTROLLING); nat_server2_ = CreateNatServer(kNatAddr2, ntype2); auto port2 = CreateStunPort(kLocalAddr2, &nat_socket_factory2_); - port2->SetIceRole(webrtc::ICEROLE_CONTROLLED); + port2->SetIceRole(ICEROLE_CONTROLLED); TestConnectivity(StunName(ntype1), std::move(port1), StunName(ntype2), - std::move(port2), ntype2 == webrtc::NAT_OPEN_CONE, - ntype1 != webrtc::NAT_SYMMETRIC, - ntype2 != webrtc::NAT_SYMMETRIC, - ntype1 + ntype2 < - (webrtc::NAT_PORT_RESTRICTED + webrtc::NAT_SYMMETRIC)); + std::move(port2), ntype2 == NAT_OPEN_CONE, + ntype1 != NAT_SYMMETRIC, ntype2 != NAT_SYMMETRIC, + ntype1 + ntype2 < (NAT_PORT_RESTRICTED + NAT_SYMMETRIC)); } void TestStunToRelay(NATType ntype, ProtocolType proto) { nat_server1_ = CreateNatServer(kNatAddr1, ntype); auto port1 = CreateStunPort(kLocalAddr1, &nat_socket_factory1_); - port1->SetIceRole(webrtc::ICEROLE_CONTROLLING); - auto port2 = CreateRelayPort(kLocalAddr2, proto, webrtc::PROTO_UDP); - port2->SetIceRole(webrtc::ICEROLE_CONTROLLED); + port1->SetIceRole(ICEROLE_CONTROLLING); + auto port2 = CreateRelayPort(kLocalAddr2, proto, PROTO_UDP); + port2->SetIceRole(ICEROLE_CONTROLLED); TestConnectivity(StunName(ntype), std::move(port1), RelayName(proto), - std::move(port2), false, ntype != webrtc::NAT_SYMMETRIC, - true, true); + std::move(port2), false, ntype != NAT_SYMMETRIC, true, + true); } void TestTcpToTcp() { auto port1 = CreateTcpPort(kLocalAddr1); - port1->SetIceRole(webrtc::ICEROLE_CONTROLLING); + port1->SetIceRole(ICEROLE_CONTROLLING); auto port2 = CreateTcpPort(kLocalAddr2); - port2->SetIceRole(webrtc::ICEROLE_CONTROLLED); + port2->SetIceRole(ICEROLE_CONTROLLED); TestConnectivity("tcp", std::move(port1), "tcp", std::move(port2), true, false, true, true); } void TestTcpToRelay(ProtocolType proto) { auto port1 = CreateTcpPort(kLocalAddr1); - port1->SetIceRole(webrtc::ICEROLE_CONTROLLING); - auto port2 = CreateRelayPort(kLocalAddr2, proto, webrtc::PROTO_TCP); - port2->SetIceRole(webrtc::ICEROLE_CONTROLLED); + port1->SetIceRole(ICEROLE_CONTROLLING); + auto port2 = CreateRelayPort(kLocalAddr2, proto, PROTO_TCP); + port2->SetIceRole(ICEROLE_CONTROLLED); TestConnectivity("tcp", std::move(port1), RelayName(proto), std::move(port2), false, false, true, true); } void TestSslTcpToRelay(ProtocolType proto) { auto port1 = CreateTcpPort(kLocalAddr1); - port1->SetIceRole(webrtc::ICEROLE_CONTROLLING); - auto port2 = CreateRelayPort(kLocalAddr2, proto, webrtc::PROTO_SSLTCP); - port2->SetIceRole(webrtc::ICEROLE_CONTROLLED); + port1->SetIceRole(ICEROLE_CONTROLLING); + auto port2 = CreateRelayPort(kLocalAddr2, proto, PROTO_SSLTCP); + port2->SetIceRole(ICEROLE_CONTROLLED); TestConnectivity("ssltcp", std::move(port1), RelayName(proto), std::move(port2), false, false, true, true); } @@ -544,7 +541,7 @@ class PortTest : public ::testing::Test, public sigslot::has_slots<> { Network* MakeNetworkMultipleAddrs(const SocketAddress& global_addr, const SocketAddress& link_local_addr) { networks_.emplace_back("unittest", "unittest", global_addr.ipaddr(), 32, - webrtc::ADAPTER_TYPE_UNKNOWN); + ADAPTER_TYPE_UNKNOWN); networks_.back().AddIP(link_local_addr.ipaddr()); networks_.back().AddIP(global_addr.ipaddr()); networks_.back().AddIP(link_local_addr.ipaddr()); @@ -623,7 +620,7 @@ class PortTest : public ::testing::Test, public sigslot::has_slots<> { ProtocolType int_proto, ProtocolType ext_proto) { SocketAddress server_addr = - int_proto == webrtc::PROTO_TCP ? kTurnTcpIntAddr : kTurnUdpIntAddr; + int_proto == PROTO_TCP ? kTurnTcpIntAddr : kTurnUdpIntAddr; return CreateTurnPort(addr, socket_factory, int_proto, ext_proto, server_addr); } @@ -656,13 +653,13 @@ class PortTest : public ::testing::Test, public sigslot::has_slots<> { } static const char* StunName(NATType type) { switch (type) { - case webrtc::NAT_OPEN_CONE: + case NAT_OPEN_CONE: return "stun(open cone)"; - case webrtc::NAT_ADDR_RESTRICTED: + case NAT_ADDR_RESTRICTED: return "stun(addr restricted)"; - case webrtc::NAT_PORT_RESTRICTED: + case NAT_PORT_RESTRICTED: return "stun(port restricted)"; - case webrtc::NAT_SYMMETRIC: + case NAT_SYMMETRIC: return "stun(symmetric)"; default: return "stun(?)"; @@ -670,13 +667,13 @@ class PortTest : public ::testing::Test, public sigslot::has_slots<> { } static const char* RelayName(ProtocolType proto) { switch (proto) { - case webrtc::PROTO_UDP: + case PROTO_UDP: return "turn(udp)"; - case webrtc::PROTO_TCP: + case PROTO_TCP: return "turn(tcp)"; - case webrtc::PROTO_SSLTCP: + case PROTO_SSLTCP: return "turn(ssltcp)"; - case webrtc::PROTO_TLS: + case PROTO_TLS: return "turn(tls)"; default: return "turn(?)"; @@ -702,21 +699,19 @@ class PortTest : public ::testing::Test, public sigslot::has_slots<> { // TCP reconnecting mechanism before entering this function. void ConnectStartedChannels(TestChannel* ch1, TestChannel* ch2) { ASSERT_TRUE(ch1->conn()); - EXPECT_THAT( - webrtc::WaitUntil([&] { return ch1->conn()->connected(); }, IsTrue(), + EXPECT_THAT(WaitUntil([&] { return ch1->conn()->connected(); }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); // for TCP connect + IsRtcOk()); // for TCP connect ch1->Ping(); WAIT(!ch2->remote_address().IsNil(), kShortTimeout); // Send a ping from dst to src. ch2->AcceptConnection(GetCandidate(ch1->port())); ch2->Ping(); - EXPECT_THAT( - webrtc::WaitUntil([&] { return ch2->conn()->write_state(); }, + EXPECT_THAT(WaitUntil([&] { return ch2->conn()->write_state(); }, Eq(Connection::STATE_WRITABLE), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); } // This connects and disconnects the provided channels in the same sequence as @@ -745,14 +740,12 @@ class PortTest : public ::testing::Test, public sigslot::has_slots<> { tcp_conn2->socket()->GetLocalAddress())); // Wait for both OnClose are delivered. - EXPECT_THAT( - webrtc::WaitUntil([&] { return !ch1->conn()->connected(); }, IsTrue(), + EXPECT_THAT(WaitUntil([&] { return !ch1->conn()->connected(); }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); - EXPECT_THAT( - webrtc::WaitUntil([&] { return !ch2->conn()->connected(); }, IsTrue(), + IsRtcOk()); + EXPECT_THAT(WaitUntil([&] { return !ch2->conn()->connected(); }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); // Ensure redundant SignalClose events on TcpConnection won't break tcp // reconnection. Chromium will fire SignalClose for all outstanding IPC @@ -763,18 +756,17 @@ class PortTest : public ::testing::Test, public sigslot::has_slots<> { // Speed up destroying ch2's connection such that the test is ready to // accept a new connection from ch1 before ch1's connection destroys itself. ch2->Stop(); - EXPECT_THAT( - webrtc::WaitUntil([&] { return ch2->conn(); }, IsNull(), + EXPECT_THAT(WaitUntil([&] { return ch2->conn(); }, IsNull(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); } void TestTcpReconnect(bool ping_after_disconnected, bool send_after_disconnected) { auto port1 = CreateTcpPort(kLocalAddr1); - port1->SetIceRole(webrtc::ICEROLE_CONTROLLING); + port1->SetIceRole(ICEROLE_CONTROLLING); auto port2 = CreateTcpPort(kLocalAddr2); - port2->SetIceRole(webrtc::ICEROLE_CONTROLLED); + port2->SetIceRole(ICEROLE_CONTROLLED); port1->set_component(ICE_CANDIDATE_COMPONENT_DEFAULT); port2->set_component(ICE_CANDIDATE_COMPONENT_DEFAULT); @@ -787,14 +779,12 @@ class PortTest : public ::testing::Test, public sigslot::has_slots<> { ch1.Start(); ch2.Start(); - ASSERT_THAT( - webrtc::WaitUntil([&] { return ch1.complete_count(); }, Eq(1), + ASSERT_THAT(WaitUntil([&] { return ch1.complete_count(); }, Eq(1), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); - ASSERT_THAT( - webrtc::WaitUntil([&] { return ch2.complete_count(); }, Eq(1), + IsRtcOk()); + ASSERT_THAT(WaitUntil([&] { return ch2.complete_count(); }, Eq(1), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); // Initial connecting the channel, create connection on channel1. ch1.CreateConnection(GetCandidate(ch2.port())); @@ -827,17 +817,16 @@ class PortTest : public ::testing::Test, public sigslot::has_slots<> { } // Wait for channel's outgoing TCPConnection connected. - EXPECT_THAT( - webrtc::WaitUntil([&] { return ch1.conn()->connected(); }, IsTrue(), + EXPECT_THAT(WaitUntil([&] { return ch1.conn()->connected(); }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); // Verify that we could still connect channels. ConnectStartedChannels(&ch1, &ch2); - EXPECT_THAT(webrtc::WaitUntil( - [&] { return ch1.connection_ready_to_send(); }, IsTrue(), - {.timeout = TimeDelta::Millis(kTcpReconnectTimeout)}), - webrtc::IsRtcOk()); + EXPECT_THAT( + WaitUntil([&] { return ch1.connection_ready_to_send(); }, IsTrue(), + {.timeout = TimeDelta::Millis(kTcpReconnectTimeout)}), + IsRtcOk()); // Channel2 is the passive one so a new connection is created during // reconnect. This new connection should never have issued ENOTCONN // hence the connection_ready_to_send() should be false. @@ -846,25 +835,22 @@ class PortTest : public ::testing::Test, public sigslot::has_slots<> { EXPECT_EQ(ch1.conn()->write_state(), Connection::STATE_WRITABLE); // Since the reconnection never happens, the connections should have been // destroyed after the timeout. - EXPECT_THAT( - webrtc::WaitUntil([&] { return !ch1.conn(); }, IsTrue(), + EXPECT_THAT(WaitUntil([&] { return !ch1.conn(); }, IsTrue(), {.timeout = TimeDelta::Millis(kTcpReconnectTimeout + kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_TRUE(!ch2.conn()); } // Tear down and ensure that goes smoothly. ch1.Stop(); ch2.Stop(); - EXPECT_THAT( - webrtc::WaitUntil([&] { return ch1.conn(); }, IsNull(), + EXPECT_THAT(WaitUntil([&] { return ch1.conn(); }, IsNull(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); - EXPECT_THAT( - webrtc::WaitUntil([&] { return ch2.conn(); }, IsNull(), + IsRtcOk()); + EXPECT_THAT(WaitUntil([&] { return ch2.conn(); }, IsNull(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); } std::unique_ptr CreateStunMessage(StunMessageType type) { @@ -904,7 +890,7 @@ class PortTest : public ::testing::Test, public sigslot::has_slots<> { port->SetIceTiebreaker(tiebreaker); return port; } - // Overload to create a test port given an webrtc::Network directly. + // Overload to create a test port given an Network directly. std::unique_ptr CreateTestPort(const Network* network, absl::string_view username, absl::string_view password) { @@ -981,23 +967,22 @@ void PortTest::TestConnectivity(absl::string_view name1, // Acquire addresses. ch1.Start(); ch2.Start(); - ASSERT_THAT(webrtc::WaitUntil([&] { return ch1.complete_count(); }, Eq(1), - {.timeout = TimeDelta::Millis(kDefaultTimeout), - .clock = &clock}), - webrtc::IsRtcOk()); - ASSERT_THAT(webrtc::WaitUntil([&] { return ch2.complete_count(); }, Eq(1), - {.timeout = TimeDelta::Millis(kDefaultTimeout), - .clock = &clock}), - webrtc::IsRtcOk()); + ASSERT_THAT(WaitUntil([&] { return ch1.complete_count(); }, Eq(1), + {.timeout = TimeDelta::Millis(kDefaultTimeout), + .clock = &clock}), + IsRtcOk()); + ASSERT_THAT(WaitUntil([&] { return ch2.complete_count(); }, Eq(1), + {.timeout = TimeDelta::Millis(kDefaultTimeout), + .clock = &clock}), + IsRtcOk()); // Send a ping from src to dst. This may or may not make it. ch1.CreateConnection(GetCandidate(ch2.port())); ASSERT_TRUE(ch1.conn() != nullptr); - EXPECT_THAT( - webrtc::WaitUntil( - [&] { return ch1.conn()->connected(); }, IsTrue(), - {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); // for TCP connect + EXPECT_THAT(WaitUntil([&] { return ch1.conn()->connected(); }, IsTrue(), + {.timeout = TimeDelta::Millis(kDefaultTimeout), + .clock = &clock}), + IsRtcOk()); // for TCP connect ch1.Ping(); SIMULATED_WAIT(!ch2.remote_address().IsNil(), kShortTimeout, clock); @@ -1017,12 +1002,11 @@ void PortTest::TestConnectivity(absl::string_view name1, ch2.AcceptConnection(GetCandidate(ch1.port())); ASSERT_TRUE(ch2.conn() != nullptr); ch2.Ping(); - EXPECT_THAT( - webrtc::WaitUntil( - [&] { return ch2.conn()->write_state(); }, - Eq(Connection::STATE_WRITABLE), - {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + EXPECT_THAT(WaitUntil([&] { return ch2.conn()->write_state(); }, + Eq(Connection::STATE_WRITABLE), + {.timeout = TimeDelta::Millis(kDefaultTimeout), + .clock = &clock}), + IsRtcOk()); } else { // We can't send a ping from src to dst, so flip it around. This will happen // when the destination NAT is addr/port restricted or symmetric. @@ -1045,12 +1029,11 @@ void PortTest::TestConnectivity(absl::string_view name1, // through. So we will have to do another. if (ch1.conn()->write_state() == Connection::STATE_WRITE_INIT) { ch1.Ping(); - EXPECT_THAT( - webrtc::WaitUntil([&] { return ch1.conn()->write_state(); }, + EXPECT_THAT(WaitUntil([&] { return ch1.conn()->write_state(); }, Eq(Connection::STATE_WRITABLE), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); } } else if (!same_addr1 && possible) { // The new ping went to the candidate address, but that address was bad. @@ -1062,10 +1045,10 @@ void PortTest::TestConnectivity(absl::string_view name1, // able to get a ping from it. This gives us the real source address. ch1.Ping(); EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return !ch2.remote_address().IsNil(); }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_FALSE(ch2.conn()->receiving()); EXPECT_TRUE(ch1.remote_address().IsNil()); @@ -1073,12 +1056,11 @@ void PortTest::TestConnectivity(absl::string_view name1, ch2.AcceptConnection(GetCandidate(ch1.port())); ASSERT_TRUE(ch2.conn() != nullptr); ch2.Ping(); - EXPECT_THAT( - webrtc::WaitUntil( - [&] { return ch2.conn()->write_state(); }, - Eq(Connection::STATE_WRITABLE), - {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + EXPECT_THAT(WaitUntil([&] { return ch2.conn()->write_state(); }, + Eq(Connection::STATE_WRITABLE), + {.timeout = TimeDelta::Millis(kDefaultTimeout), + .clock = &clock}), + IsRtcOk()); } else if (!same_addr2 && possible) { // The new ping came in, but from an unexpected address. This will happen // when the destination NAT is symmetric. @@ -1088,12 +1070,11 @@ void PortTest::TestConnectivity(absl::string_view name1, // Update our address and complete the connection. ch1.AcceptConnection(GetCandidate(ch2.port())); ch1.Ping(); - EXPECT_THAT( - webrtc::WaitUntil( - [&] { return ch1.conn()->write_state(); }, - Eq(Connection::STATE_WRITABLE), - {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + EXPECT_THAT(WaitUntil([&] { return ch1.conn()->write_state(); }, + Eq(Connection::STATE_WRITABLE), + {.timeout = TimeDelta::Millis(kDefaultTimeout), + .clock = &clock}), + IsRtcOk()); } else { // (!possible) // There should be s no way for the pings to reach each other. Check it. EXPECT_TRUE(ch1.remote_address().IsNil()); @@ -1123,14 +1104,14 @@ void PortTest::TestConnectivity(absl::string_view name1, // Tear down and ensure that goes smoothly. ch1.Stop(); ch2.Stop(); - EXPECT_THAT(webrtc::WaitUntil([&] { return ch1.conn(); }, IsNull(), - {.timeout = TimeDelta::Millis(kDefaultTimeout), - .clock = &clock}), - webrtc::IsRtcOk()); - EXPECT_THAT(webrtc::WaitUntil([&] { return ch2.conn(); }, IsNull(), - {.timeout = TimeDelta::Millis(kDefaultTimeout), - .clock = &clock}), - webrtc::IsRtcOk()); + EXPECT_THAT(WaitUntil([&] { return ch1.conn(); }, IsNull(), + {.timeout = TimeDelta::Millis(kDefaultTimeout), + .clock = &clock}), + IsRtcOk()); + EXPECT_THAT(WaitUntil([&] { return ch2.conn(); }, IsNull(), + {.timeout = TimeDelta::Millis(kDefaultTimeout), + .clock = &clock}), + IsRtcOk()); } class FakePacketSocketFactory : public PacketSocketFactory { @@ -1191,38 +1172,38 @@ class FakeAsyncPacketSocket : public AsyncPacketSocket { public: // Returns current local address. Address may be set to NULL if the // socket is not bound yet (GetState() returns STATE_BINDING). - virtual SocketAddress GetLocalAddress() const { return local_address_; } + SocketAddress GetLocalAddress() const override { return local_address_; } // Returns remote address. Returns zeroes if this is not a client TCP socket. - virtual SocketAddress GetRemoteAddress() const { return remote_address_; } + SocketAddress GetRemoteAddress() const override { return remote_address_; } // Send a packet. - virtual int Send(const void* pv, - size_t cb, - const AsyncSocketPacketOptions& options) { + int Send(const void* pv, + size_t cb, + const AsyncSocketPacketOptions& options) override { if (error_ == 0) { return static_cast(cb); } else { return -1; } } - virtual int SendTo(const void* pv, - size_t cb, - const SocketAddress& addr, - const AsyncSocketPacketOptions& options) { + int SendTo(const void* pv, + size_t cb, + const SocketAddress& addr, + const AsyncSocketPacketOptions& options) override { if (error_ == 0) { return static_cast(cb); } else { return -1; } } - virtual int Close() { return 0; } + int Close() override { return 0; } - virtual State GetState() const { return state_; } - virtual int GetOption(Socket::Option opt, int* value) { return 0; } - virtual int SetOption(Socket::Option opt, int value) { return 0; } - virtual int GetError() const { return 0; } - virtual void SetError(int error) { error_ = error; } + State GetState() const override { return state_; } + int GetOption(Socket::Option opt, int* value) override { return 0; } + int SetOption(Socket::Option opt, int value) override { return 0; } + int GetError() const override { return 0; } + void SetError(int error) override { error_ = error; } void set_state(State state) { state_ = state; } @@ -1238,14 +1219,14 @@ class FakeAsyncListenSocket : public AsyncListenSocket { public: // Returns current local address. Address may be set to NULL if the // socket is not bound yet (GetState() returns STATE_BINDING). - virtual SocketAddress GetLocalAddress() const { return local_address_; } + SocketAddress GetLocalAddress() const override { return local_address_; } void Bind(const SocketAddress& address) { local_address_ = address; state_ = State::kBound; } virtual int GetOption(Socket::Option opt, int* value) { return 0; } virtual int SetOption(Socket::Option opt, int value) { return 0; } - virtual State GetState() const { return state_; } + State GetState() const override { return state_; } private: SocketAddress local_address_; @@ -1258,127 +1239,127 @@ TEST_F(PortTest, TestLocalToLocal) { } TEST_F(PortTest, TestLocalToConeNat) { - TestLocalToStun(webrtc::NAT_OPEN_CONE); + TestLocalToStun(NAT_OPEN_CONE); } TEST_F(PortTest, TestLocalToARNat) { - TestLocalToStun(webrtc::NAT_ADDR_RESTRICTED); + TestLocalToStun(NAT_ADDR_RESTRICTED); } TEST_F(PortTest, TestLocalToPRNat) { - TestLocalToStun(webrtc::NAT_PORT_RESTRICTED); + TestLocalToStun(NAT_PORT_RESTRICTED); } TEST_F(PortTest, TestLocalToSymNat) { - TestLocalToStun(webrtc::NAT_SYMMETRIC); + TestLocalToStun(NAT_SYMMETRIC); } // Flaky: https://code.google.com/p/webrtc/issues/detail?id=3316. TEST_F(PortTest, DISABLED_TestLocalToTurn) { - TestLocalToRelay(webrtc::PROTO_UDP); + TestLocalToRelay(PROTO_UDP); } // Cone NAT -> XXXX TEST_F(PortTest, TestConeNatToLocal) { - TestStunToLocal(webrtc::NAT_OPEN_CONE); + TestStunToLocal(NAT_OPEN_CONE); } TEST_F(PortTest, TestConeNatToConeNat) { - TestStunToStun(webrtc::NAT_OPEN_CONE, webrtc::NAT_OPEN_CONE); + TestStunToStun(NAT_OPEN_CONE, NAT_OPEN_CONE); } TEST_F(PortTest, TestConeNatToARNat) { - TestStunToStun(webrtc::NAT_OPEN_CONE, webrtc::NAT_ADDR_RESTRICTED); + TestStunToStun(NAT_OPEN_CONE, NAT_ADDR_RESTRICTED); } TEST_F(PortTest, TestConeNatToPRNat) { - TestStunToStun(webrtc::NAT_OPEN_CONE, webrtc::NAT_PORT_RESTRICTED); + TestStunToStun(NAT_OPEN_CONE, NAT_PORT_RESTRICTED); } TEST_F(PortTest, TestConeNatToSymNat) { - TestStunToStun(webrtc::NAT_OPEN_CONE, webrtc::NAT_SYMMETRIC); + TestStunToStun(NAT_OPEN_CONE, NAT_SYMMETRIC); } TEST_F(PortTest, TestConeNatToTurn) { - TestStunToRelay(webrtc::NAT_OPEN_CONE, webrtc::PROTO_UDP); + TestStunToRelay(NAT_OPEN_CONE, PROTO_UDP); } // Address-restricted NAT -> XXXX TEST_F(PortTest, TestARNatToLocal) { - TestStunToLocal(webrtc::NAT_ADDR_RESTRICTED); + TestStunToLocal(NAT_ADDR_RESTRICTED); } TEST_F(PortTest, TestARNatToConeNat) { - TestStunToStun(webrtc::NAT_ADDR_RESTRICTED, webrtc::NAT_OPEN_CONE); + TestStunToStun(NAT_ADDR_RESTRICTED, NAT_OPEN_CONE); } TEST_F(PortTest, TestARNatToARNat) { - TestStunToStun(webrtc::NAT_ADDR_RESTRICTED, webrtc::NAT_ADDR_RESTRICTED); + TestStunToStun(NAT_ADDR_RESTRICTED, NAT_ADDR_RESTRICTED); } TEST_F(PortTest, TestARNatToPRNat) { - TestStunToStun(webrtc::NAT_ADDR_RESTRICTED, webrtc::NAT_PORT_RESTRICTED); + TestStunToStun(NAT_ADDR_RESTRICTED, NAT_PORT_RESTRICTED); } TEST_F(PortTest, TestARNatToSymNat) { - TestStunToStun(webrtc::NAT_ADDR_RESTRICTED, webrtc::NAT_SYMMETRIC); + TestStunToStun(NAT_ADDR_RESTRICTED, NAT_SYMMETRIC); } TEST_F(PortTest, TestARNatToTurn) { - TestStunToRelay(webrtc::NAT_ADDR_RESTRICTED, webrtc::PROTO_UDP); + TestStunToRelay(NAT_ADDR_RESTRICTED, PROTO_UDP); } // Port-restricted NAT -> XXXX TEST_F(PortTest, TestPRNatToLocal) { - TestStunToLocal(webrtc::NAT_PORT_RESTRICTED); + TestStunToLocal(NAT_PORT_RESTRICTED); } TEST_F(PortTest, TestPRNatToConeNat) { - TestStunToStun(webrtc::NAT_PORT_RESTRICTED, webrtc::NAT_OPEN_CONE); + TestStunToStun(NAT_PORT_RESTRICTED, NAT_OPEN_CONE); } TEST_F(PortTest, TestPRNatToARNat) { - TestStunToStun(webrtc::NAT_PORT_RESTRICTED, webrtc::NAT_ADDR_RESTRICTED); + TestStunToStun(NAT_PORT_RESTRICTED, NAT_ADDR_RESTRICTED); } TEST_F(PortTest, TestPRNatToPRNat) { - TestStunToStun(webrtc::NAT_PORT_RESTRICTED, webrtc::NAT_PORT_RESTRICTED); + TestStunToStun(NAT_PORT_RESTRICTED, NAT_PORT_RESTRICTED); } TEST_F(PortTest, TestPRNatToSymNat) { // Will "fail" - TestStunToStun(webrtc::NAT_PORT_RESTRICTED, webrtc::NAT_SYMMETRIC); + TestStunToStun(NAT_PORT_RESTRICTED, NAT_SYMMETRIC); } TEST_F(PortTest, TestPRNatToTurn) { - TestStunToRelay(webrtc::NAT_PORT_RESTRICTED, webrtc::PROTO_UDP); + TestStunToRelay(NAT_PORT_RESTRICTED, PROTO_UDP); } // Symmetric NAT -> XXXX TEST_F(PortTest, TestSymNatToLocal) { - TestStunToLocal(webrtc::NAT_SYMMETRIC); + TestStunToLocal(NAT_SYMMETRIC); } TEST_F(PortTest, TestSymNatToConeNat) { - TestStunToStun(webrtc::NAT_SYMMETRIC, webrtc::NAT_OPEN_CONE); + TestStunToStun(NAT_SYMMETRIC, NAT_OPEN_CONE); } TEST_F(PortTest, TestSymNatToARNat) { - TestStunToStun(webrtc::NAT_SYMMETRIC, webrtc::NAT_ADDR_RESTRICTED); + TestStunToStun(NAT_SYMMETRIC, NAT_ADDR_RESTRICTED); } TEST_F(PortTest, TestSymNatToPRNat) { // Will "fail" - TestStunToStun(webrtc::NAT_SYMMETRIC, webrtc::NAT_PORT_RESTRICTED); + TestStunToStun(NAT_SYMMETRIC, NAT_PORT_RESTRICTED); } TEST_F(PortTest, TestSymNatToSymNat) { // Will "fail" - TestStunToStun(webrtc::NAT_SYMMETRIC, webrtc::NAT_SYMMETRIC); + TestStunToStun(NAT_SYMMETRIC, NAT_SYMMETRIC); } TEST_F(PortTest, TestSymNatToTurn) { - TestStunToRelay(webrtc::NAT_SYMMETRIC, webrtc::PROTO_UDP); + TestStunToRelay(NAT_SYMMETRIC, PROTO_UDP); } // Outbound TCP -> XXXX @@ -1402,7 +1383,7 @@ TEST_F(PortTest, TestTcpReconnectTimeout) { // destroy the connection. TEST_F(PortTest, TestTcpNeverConnect) { auto port1 = CreateTcpPort(kLocalAddr1); - port1->SetIceRole(webrtc::ICEROLE_CONTROLLING); + port1->SetIceRole(ICEROLE_CONTROLLING); port1->set_component(ICE_CANDIDATE_COMPONENT_DEFAULT); // Set up a channel and ensure the port will be deleted. @@ -1410,10 +1391,9 @@ TEST_F(PortTest, TestTcpNeverConnect) { EXPECT_EQ(0, ch1.complete_count()); ch1.Start(); - ASSERT_THAT( - webrtc::WaitUntil([&] { return ch1.complete_count(); }, Eq(1), + ASSERT_THAT(WaitUntil([&] { return ch1.complete_count(); }, Eq(1), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); std::unique_ptr server( vss()->CreateSocket(kLocalAddr2.family(), SOCK_STREAM)); @@ -1425,10 +1405,9 @@ TEST_F(PortTest, TestTcpNeverConnect) { ch1.CreateConnection(c); EXPECT_TRUE(ch1.conn()); - EXPECT_THAT( - webrtc::WaitUntil([&] { return !ch1.conn(); }, IsTrue(), + EXPECT_THAT(WaitUntil([&] { return !ch1.conn(); }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); // for TCP connect + IsRtcOk()); // for TCP connect } /* TODO(?): Enable these once testrelayserver can accept external TCP. @@ -1463,19 +1442,17 @@ TEST_F(PortTest, TestConnectionDead) { // Acquire address. ch1.Start(); ch2.Start(); - ASSERT_THAT( - webrtc::WaitUntil([&] { return ch1.complete_count(); }, Eq(1), + ASSERT_THAT(WaitUntil([&] { return ch1.complete_count(); }, Eq(1), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); - ASSERT_THAT( - webrtc::WaitUntil([&] { return ch2.complete_count(); }, Eq(1), + IsRtcOk()); + ASSERT_THAT(WaitUntil([&] { return ch2.complete_count(); }, Eq(1), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); // Test case that the connection has never received anything. - int64_t before_created = webrtc::TimeMillis(); + int64_t before_created = TimeMillis(); ch1.CreateConnection(GetCandidate(ch2.port())); - int64_t after_created = webrtc::TimeMillis(); + int64_t after_created = TimeMillis(); Connection* conn = ch1.conn(); ASSERT_NE(conn, nullptr); // It is not dead if it is after MIN_CONNECTION_LIFETIME but not pruned. @@ -1489,29 +1466,27 @@ TEST_F(PortTest, TestConnectionDead) { EXPECT_TRUE(ch1.conn() != nullptr); // It will be dead after MIN_CONNECTION_LIFETIME and pruned. conn->UpdateState(after_created + MIN_CONNECTION_LIFETIME + 1); - EXPECT_THAT( - webrtc::WaitUntil([&] { return ch1.conn(); }, Eq(nullptr), + EXPECT_THAT(WaitUntil([&] { return ch1.conn(); }, Eq(nullptr), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); // Test case that the connection has received something. // Create a connection again and receive a ping. ch1.CreateConnection(GetCandidate(ch2.port())); conn = ch1.conn(); ASSERT_NE(conn, nullptr); - int64_t before_last_receiving = webrtc::TimeMillis(); + int64_t before_last_receiving = TimeMillis(); conn->ReceivedPing(); - int64_t after_last_receiving = webrtc::TimeMillis(); + int64_t after_last_receiving = TimeMillis(); // The connection will be dead after DEAD_CONNECTION_RECEIVE_TIMEOUT conn->UpdateState(before_last_receiving + DEAD_CONNECTION_RECEIVE_TIMEOUT - 1); Thread::Current()->ProcessMessages(100); EXPECT_TRUE(ch1.conn() != nullptr); conn->UpdateState(after_last_receiving + DEAD_CONNECTION_RECEIVE_TIMEOUT + 1); - EXPECT_THAT( - webrtc::WaitUntil([&] { return ch1.conn(); }, Eq(nullptr), + EXPECT_THAT(WaitUntil([&] { return ch1.conn(); }, Eq(nullptr), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); } TEST_F(PortTest, TestConnectionDeadWithDeadConnectionTimeout) { @@ -1520,14 +1495,12 @@ TEST_F(PortTest, TestConnectionDeadWithDeadConnectionTimeout) { // Acquire address. ch1.Start(); ch2.Start(); - ASSERT_THAT( - webrtc::WaitUntil([&] { return ch1.complete_count(); }, Eq(1), + ASSERT_THAT(WaitUntil([&] { return ch1.complete_count(); }, Eq(1), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); - ASSERT_THAT( - webrtc::WaitUntil([&] { return ch2.complete_count(); }, Eq(1), + IsRtcOk()); + ASSERT_THAT(WaitUntil([&] { return ch2.complete_count(); }, Eq(1), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); // Note: set field trials manually since they are parsed by // P2PTransportChannel but P2PTransportChannel is not used in this test. @@ -1540,26 +1513,25 @@ TEST_F(PortTest, TestConnectionDeadWithDeadConnectionTimeout) { conn->SetIceFieldTrials(&field_trials); ASSERT_NE(conn, nullptr); - int64_t before_last_receiving = webrtc::TimeMillis(); + int64_t before_last_receiving = TimeMillis(); conn->ReceivedPing(); - int64_t after_last_receiving = webrtc::TimeMillis(); + int64_t after_last_receiving = TimeMillis(); // The connection will be dead after 90s conn->UpdateState(before_last_receiving + 90000 - 1); Thread::Current()->ProcessMessages(100); EXPECT_TRUE(ch1.conn() != nullptr); conn->UpdateState(after_last_receiving + 90000 + 1); - EXPECT_THAT( - webrtc::WaitUntil([&] { return ch1.conn(); }, Eq(nullptr), + EXPECT_THAT(WaitUntil([&] { return ch1.conn(); }, Eq(nullptr), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); } TEST_F(PortTest, TestConnectionDeadOutstandingPing) { auto port1 = CreateUdpPort(kLocalAddr1); - port1->SetIceRole(webrtc::ICEROLE_CONTROLLING); + port1->SetIceRole(ICEROLE_CONTROLLING); port1->SetIceTiebreaker(kTiebreaker1); auto port2 = CreateUdpPort(kLocalAddr2); - port2->SetIceRole(webrtc::ICEROLE_CONTROLLED); + port2->SetIceRole(ICEROLE_CONTROLLED); port2->SetIceTiebreaker(kTiebreaker2); TestChannel ch1(std::move(port1)); @@ -1567,14 +1539,12 @@ TEST_F(PortTest, TestConnectionDeadOutstandingPing) { // Acquire address. ch1.Start(); ch2.Start(); - ASSERT_THAT( - webrtc::WaitUntil([&] { return ch1.complete_count(); }, Eq(1), + ASSERT_THAT(WaitUntil([&] { return ch1.complete_count(); }, Eq(1), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); - ASSERT_THAT( - webrtc::WaitUntil([&] { return ch2.complete_count(); }, Eq(1), + IsRtcOk()); + ASSERT_THAT(WaitUntil([&] { return ch2.complete_count(); }, Eq(1), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); // Note: set field trials manually since they are parsed by // P2PTransportChannel but P2PTransportChannel is not used in this test. @@ -1589,7 +1559,7 @@ TEST_F(PortTest, TestConnectionDeadOutstandingPing) { ASSERT_NE(conn, nullptr); conn->ReceivedPing(); - int64_t send_ping_timestamp = webrtc::TimeMillis(); + int64_t send_ping_timestamp = TimeMillis(); conn->Ping(send_ping_timestamp); // The connection will be dead 30s after the ping was sent. @@ -1597,10 +1567,9 @@ TEST_F(PortTest, TestConnectionDeadOutstandingPing) { Thread::Current()->ProcessMessages(100); EXPECT_TRUE(ch1.conn() != nullptr); conn->UpdateState(send_ping_timestamp + DEAD_CONNECTION_RECEIVE_TIMEOUT + 1); - EXPECT_THAT( - webrtc::WaitUntil([&] { return ch1.conn(); }, Eq(nullptr), + EXPECT_THAT(WaitUntil([&] { return ch1.conn(); }, Eq(nullptr), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); } // This test case verifies standard ICE features in STUN messages. Currently it @@ -1608,10 +1577,10 @@ TEST_F(PortTest, TestConnectionDeadOutstandingPing) { // binding request will have colon (":") between remote and local username. TEST_F(PortTest, TestLocalToLocalStandard) { auto port1 = CreateUdpPort(kLocalAddr1); - port1->SetIceRole(webrtc::ICEROLE_CONTROLLING); + port1->SetIceRole(ICEROLE_CONTROLLING); port1->SetIceTiebreaker(kTiebreaker1); auto port2 = CreateUdpPort(kLocalAddr2); - port2->SetIceRole(webrtc::ICEROLE_CONTROLLED); + port2->SetIceRole(ICEROLE_CONTROLLED); port2->SetIceTiebreaker(kTiebreaker2); // Same parameters as TestLocalToLocal above. TestConnectivity("udp", std::move(port1), "udp", std::move(port2), true, true, @@ -1624,7 +1593,7 @@ TEST_F(PortTest, TestLocalToLocalStandard) { // must be in controlling. TEST_F(PortTest, TestLoopbackCall) { auto lport = CreateTestPort(kLocalAddr1, "lfrag", "lpass"); - lport->SetIceRole(webrtc::ICEROLE_CONTROLLING); + lport->SetIceRole(ICEROLE_CONTROLLING); lport->SetIceTiebreaker(kTiebreaker1); lport->PrepareAddress(); ASSERT_FALSE(lport->Candidates().empty()); @@ -1632,18 +1601,16 @@ TEST_F(PortTest, TestLoopbackCall) { lport->CreateConnection(lport->Candidates()[0], Port::ORIGIN_MESSAGE); conn->Ping(0); - ASSERT_THAT( - webrtc::WaitUntil([&] { return lport->last_stun_msg(); }, NotNull(), + ASSERT_THAT(WaitUntil([&] { return lport->last_stun_msg(); }, NotNull(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); IceMessage* msg = lport->last_stun_msg(); EXPECT_EQ(STUN_BINDING_REQUEST, msg->type()); conn->OnReadPacket( ReceivedIpPacket(lport->last_stun_buf(), SocketAddress(), std::nullopt)); - ASSERT_THAT( - webrtc::WaitUntil([&] { return lport->last_stun_msg(); }, NotNull(), + ASSERT_THAT(WaitUntil([&] { return lport->last_stun_msg(); }, NotNull(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); msg = lport->last_stun_msg(); EXPECT_EQ(STUN_BINDING_RESPONSE, msg->type()); @@ -1656,10 +1623,9 @@ TEST_F(PortTest, TestLoopbackCall) { lport->CreateConnection(lport->Candidates()[1], Port::ORIGIN_MESSAGE); conn1->Ping(0); - ASSERT_THAT( - webrtc::WaitUntil([&] { return lport->last_stun_msg(); }, NotNull(), + ASSERT_THAT(WaitUntil([&] { return lport->last_stun_msg(); }, NotNull(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); msg = lport->last_stun_msg(); EXPECT_EQ(STUN_BINDING_REQUEST, msg->type()); std::unique_ptr modified_req( @@ -1681,10 +1647,9 @@ TEST_F(PortTest, TestLoopbackCall) { conn1->OnReadPacket(ReceivedIpPacket::CreateFromLegacy( reinterpret_cast(buf->Data()), buf->Length(), /*packet_time_us=*/-1)); - ASSERT_THAT( - webrtc::WaitUntil([&] { return lport->last_stun_msg(); }, NotNull(), + ASSERT_THAT(WaitUntil([&] { return lport->last_stun_msg(); }, NotNull(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); msg = lport->last_stun_msg(); EXPECT_EQ(STUN_BINDING_ERROR_RESPONSE, msg->type()); } @@ -1696,10 +1661,10 @@ TEST_F(PortTest, TestLoopbackCall) { // send role conflict signal. TEST_F(PortTest, TestIceRoleConflict) { auto lport = CreateTestPort(kLocalAddr1, "lfrag", "lpass"); - lport->SetIceRole(webrtc::ICEROLE_CONTROLLING); + lport->SetIceRole(ICEROLE_CONTROLLING); lport->SetIceTiebreaker(kTiebreaker1); auto rport = CreateTestPort(kLocalAddr2, "rfrag", "rpass"); - rport->SetIceRole(webrtc::ICEROLE_CONTROLLING); + rport->SetIceRole(ICEROLE_CONTROLLING); rport->SetIceTiebreaker(kTiebreaker2); lport->PrepareAddress(); @@ -1712,20 +1677,18 @@ TEST_F(PortTest, TestIceRoleConflict) { rport->CreateConnection(lport->Candidates()[0], Port::ORIGIN_MESSAGE); rconn->Ping(0); - ASSERT_THAT( - webrtc::WaitUntil([&] { return rport->last_stun_msg(); }, NotNull(), + ASSERT_THAT(WaitUntil([&] { return rport->last_stun_msg(); }, NotNull(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); IceMessage* msg = rport->last_stun_msg(); EXPECT_EQ(STUN_BINDING_REQUEST, msg->type()); // Send rport binding request to lport. lconn->OnReadPacket( ReceivedIpPacket(rport->last_stun_buf(), SocketAddress(), std::nullopt)); - ASSERT_THAT( - webrtc::WaitUntil([&] { return lport->last_stun_msg(); }, NotNull(), + ASSERT_THAT(WaitUntil([&] { return lport->last_stun_msg(); }, NotNull(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_EQ(STUN_BINDING_RESPONSE, lport->last_stun_msg()->type()); EXPECT_TRUE(role_conflict()); } @@ -1733,14 +1696,14 @@ TEST_F(PortTest, TestIceRoleConflict) { TEST_F(PortTest, TestTcpNoDelay) { ScopedFakeClock clock; auto port1 = CreateTcpPort(kLocalAddr1); - port1->SetIceRole(webrtc::ICEROLE_CONTROLLING); + port1->SetIceRole(ICEROLE_CONTROLLING); int option_value = -1; int success = port1->GetOption(Socket::OPT_NODELAY, &option_value); ASSERT_EQ(0, success); // GetOption() should complete successfully w/ 0 EXPECT_EQ(1, option_value); auto port2 = CreateTcpPort(kLocalAddr2); - port2->SetIceRole(webrtc::ICEROLE_CONTROLLED); + port2->SetIceRole(ICEROLE_CONTROLLED); // Set up a connection, and verify that option is set on connected sockets at // both ends. @@ -1749,22 +1712,21 @@ TEST_F(PortTest, TestTcpNoDelay) { // Acquire addresses. ch1.Start(); ch2.Start(); - ASSERT_THAT(webrtc::WaitUntil([&] { return ch1.complete_count(); }, Eq(1), - {.timeout = TimeDelta::Millis(kDefaultTimeout), - .clock = &clock}), - webrtc::IsRtcOk()); - ASSERT_THAT(webrtc::WaitUntil([&] { return ch2.complete_count(); }, Eq(1), - {.timeout = TimeDelta::Millis(kDefaultTimeout), - .clock = &clock}), - webrtc::IsRtcOk()); + ASSERT_THAT(WaitUntil([&] { return ch1.complete_count(); }, Eq(1), + {.timeout = TimeDelta::Millis(kDefaultTimeout), + .clock = &clock}), + IsRtcOk()); + ASSERT_THAT(WaitUntil([&] { return ch2.complete_count(); }, Eq(1), + {.timeout = TimeDelta::Millis(kDefaultTimeout), + .clock = &clock}), + IsRtcOk()); // Connect and send a ping from src to dst. ch1.CreateConnection(GetCandidate(ch2.port())); ASSERT_TRUE(ch1.conn() != nullptr); - EXPECT_THAT( - webrtc::WaitUntil( - [&] { return ch1.conn()->connected(); }, IsTrue(), - {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); // for TCP connect + EXPECT_THAT(WaitUntil([&] { return ch1.conn()->connected(); }, IsTrue(), + {.timeout = TimeDelta::Millis(kDefaultTimeout), + .clock = &clock}), + IsRtcOk()); // for TCP connect ch1.Ping(); SIMULATED_WAIT(!ch2.remote_address().IsNil(), kShortTimeout, clock); @@ -1817,9 +1779,9 @@ TEST_F(PortTest, TestDisableInterfaceOfTcpPort) { lsocket->Bind(kLocalAddr1); rsocket->Bind(kLocalAddr2); - lport->SetIceRole(webrtc::ICEROLE_CONTROLLING); + lport->SetIceRole(ICEROLE_CONTROLLING); lport->SetIceTiebreaker(kTiebreaker1); - rport->SetIceRole(webrtc::ICEROLE_CONTROLLED); + rport->SetIceRole(ICEROLE_CONTROLLED); rport->SetIceTiebreaker(kTiebreaker2); lport->PrepareAddress(); @@ -1997,16 +1959,16 @@ TEST_F(PortTest, TestDefaultDscpValue) { EXPECT_EQ(0, stunport->SetOption(Socket::OPT_DSCP, DSCP_AF41)); EXPECT_EQ(0, stunport->GetOption(Socket::OPT_DSCP, &dscp)); EXPECT_EQ(DSCP_AF41, dscp); - auto turnport1 = CreateTurnPort(kLocalAddr1, nat_socket_factory1(), - webrtc::PROTO_UDP, webrtc::PROTO_UDP); + auto turnport1 = + CreateTurnPort(kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP); // Socket is created in PrepareAddress. turnport1->PrepareAddress(); EXPECT_EQ(0, turnport1->SetOption(Socket::OPT_DSCP, DSCP_CS7)); EXPECT_EQ(0, turnport1->GetOption(Socket::OPT_DSCP, &dscp)); EXPECT_EQ(DSCP_CS7, dscp); // This will verify correct value returned without the socket. - auto turnport2 = CreateTurnPort(kLocalAddr1, nat_socket_factory1(), - webrtc::PROTO_UDP, webrtc::PROTO_UDP); + auto turnport2 = + CreateTurnPort(kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP); EXPECT_EQ(0, turnport2->SetOption(Socket::OPT_DSCP, DSCP_CS6)); EXPECT_EQ(0, turnport2->GetOption(Socket::OPT_DSCP, &dscp)); EXPECT_EQ(DSCP_CS6, dscp); @@ -2016,9 +1978,9 @@ TEST_F(PortTest, TestDefaultDscpValue) { TEST_F(PortTest, TestSendStunMessage) { auto lport = CreateTestPort(kLocalAddr1, "lfrag", "lpass"); auto rport = CreateTestPort(kLocalAddr2, "rfrag", "rpass"); - lport->SetIceRole(webrtc::ICEROLE_CONTROLLING); + lport->SetIceRole(ICEROLE_CONTROLLING); lport->SetIceTiebreaker(kTiebreaker1); - rport->SetIceRole(webrtc::ICEROLE_CONTROLLED); + rport->SetIceRole(ICEROLE_CONTROLLED); rport->SetIceTiebreaker(kTiebreaker2); // Send a fake ping from lport to rport. @@ -2032,10 +1994,9 @@ TEST_F(PortTest, TestSendStunMessage) { lconn->Ping(0); // Check that it's a proper BINDING-REQUEST. - ASSERT_THAT( - webrtc::WaitUntil([&] { return lport->last_stun_msg(); }, NotNull(), + ASSERT_THAT(WaitUntil([&] { return lport->last_stun_msg(); }, NotNull(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); IceMessage* msg = lport->last_stun_msg(); EXPECT_EQ(STUN_BINDING_REQUEST, msg->type()); EXPECT_FALSE(msg->IsLegacy()); @@ -2137,10 +2098,9 @@ TEST_F(PortTest, TestSendStunMessage) { rconn->Ping(0); rconn->Ping(0); rconn->Ping(0); - ASSERT_THAT( - webrtc::WaitUntil([&] { return rport->last_stun_msg(); }, NotNull(), + ASSERT_THAT(WaitUntil([&] { return rport->last_stun_msg(); }, NotNull(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); msg = rport->last_stun_msg(); EXPECT_EQ(STUN_BINDING_REQUEST, msg->type()); const StunUInt64Attribute* ice_controlled_attr = @@ -2185,9 +2145,9 @@ TEST_F(PortTest, TestSendStunMessage) { TEST_F(PortTest, TestNomination) { auto lport = CreateTestPort(kLocalAddr1, "lfrag", "lpass"); auto rport = CreateTestPort(kLocalAddr2, "rfrag", "rpass"); - lport->SetIceRole(webrtc::ICEROLE_CONTROLLING); + lport->SetIceRole(ICEROLE_CONTROLLING); lport->SetIceTiebreaker(kTiebreaker1); - rport->SetIceRole(webrtc::ICEROLE_CONTROLLED); + rport->SetIceRole(ICEROLE_CONTROLLED); rport->SetIceTiebreaker(kTiebreaker2); lport->PrepareAddress(); @@ -2211,10 +2171,9 @@ TEST_F(PortTest, TestNomination) { // Send ping (including the nomination value) from `lconn` to `rconn`. This // should set the remote nomination of `rconn`. lconn->Ping(0); - ASSERT_THAT( - webrtc::WaitUntil([&] { return lport->last_stun_msg(); }, IsTrue(), + ASSERT_THAT(WaitUntil([&] { return lport->last_stun_msg(); }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); ASSERT_GT(lport->last_stun_buf().size(), 0u); rconn->OnReadPacket( ReceivedIpPacket(lport->last_stun_buf(), SocketAddress(), std::nullopt)); @@ -2227,10 +2186,9 @@ TEST_F(PortTest, TestNomination) { // This should result in an acknowledgment sent back from `rconn` to `lconn`, // updating the acknowledged nomination of `lconn`. - ASSERT_THAT( - webrtc::WaitUntil([&] { return rport->last_stun_msg(); }, IsTrue(), + ASSERT_THAT(WaitUntil([&] { return rport->last_stun_msg(); }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); ASSERT_GT(rport->last_stun_buf().size(), 0u); lconn->OnReadPacket( ReceivedIpPacket(rport->last_stun_buf(), SocketAddress(), std::nullopt)); @@ -2247,9 +2205,9 @@ TEST_F(PortTest, TestRoundTripTime) { auto lport = CreateTestPort(kLocalAddr1, "lfrag", "lpass"); auto rport = CreateTestPort(kLocalAddr2, "rfrag", "rpass"); - lport->SetIceRole(webrtc::ICEROLE_CONTROLLING); + lport->SetIceRole(ICEROLE_CONTROLLING); lport->SetIceTiebreaker(kTiebreaker1); - rport->SetIceRole(webrtc::ICEROLE_CONTROLLED); + rport->SetIceRole(ICEROLE_CONTROLLED); rport->SetIceTiebreaker(kTiebreaker2); lport->PrepareAddress(); @@ -2286,9 +2244,9 @@ TEST_F(PortTest, TestRoundTripTime) { TEST_F(PortTest, TestUseCandidateAttribute) { auto lport = CreateTestPort(kLocalAddr1, "lfrag", "lpass"); auto rport = CreateTestPort(kLocalAddr2, "rfrag", "rpass"); - lport->SetIceRole(webrtc::ICEROLE_CONTROLLING); + lport->SetIceRole(ICEROLE_CONTROLLING); lport->SetIceTiebreaker(kTiebreaker1); - rport->SetIceRole(webrtc::ICEROLE_CONTROLLED); + rport->SetIceRole(ICEROLE_CONTROLLED); rport->SetIceTiebreaker(kTiebreaker2); // Send a fake ping from lport to rport. @@ -2298,10 +2256,9 @@ TEST_F(PortTest, TestUseCandidateAttribute) { Connection* lconn = lport->CreateConnection(rport->Candidates()[0], Port::ORIGIN_MESSAGE); lconn->Ping(0); - ASSERT_THAT( - webrtc::WaitUntil([&] { return lport->last_stun_msg(); }, NotNull(), + ASSERT_THAT(WaitUntil([&] { return lport->last_stun_msg(); }, NotNull(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); IceMessage* msg = lport->last_stun_msg(); const StunUInt64Attribute* ice_controlling_attr = msg->GetUInt64(STUN_ATTR_ICE_CONTROLLING); @@ -2318,51 +2275,50 @@ TEST_F(PortTest, TestNetworkCostChange) { Network* test_network = MakeNetwork(kLocalAddr1); auto lport = CreateTestPort(test_network, "lfrag", "lpass"); auto rport = CreateTestPort(test_network, "rfrag", "rpass"); - lport->SetIceRole(webrtc::ICEROLE_CONTROLLING); + lport->SetIceRole(ICEROLE_CONTROLLING); lport->SetIceTiebreaker(kTiebreaker1); - rport->SetIceRole(webrtc::ICEROLE_CONTROLLED); + rport->SetIceRole(ICEROLE_CONTROLLED); rport->SetIceTiebreaker(kTiebreaker2); lport->PrepareAddress(); rport->PrepareAddress(); - // Default local port cost is webrtc::kNetworkCostUnknown. - EXPECT_EQ(webrtc::kNetworkCostUnknown, lport->network_cost()); + // Default local port cost is kNetworkCostUnknown. + EXPECT_EQ(kNetworkCostUnknown, lport->network_cost()); ASSERT_TRUE(!lport->Candidates().empty()); for (const Candidate& candidate : lport->Candidates()) { - EXPECT_EQ(webrtc::kNetworkCostUnknown, candidate.network_cost()); + EXPECT_EQ(kNetworkCostUnknown, candidate.network_cost()); } // Change the network type to wifi. - test_network->set_type(webrtc::ADAPTER_TYPE_WIFI); - EXPECT_EQ(webrtc::kNetworkCostLow, lport->network_cost()); + test_network->set_type(ADAPTER_TYPE_WIFI); + EXPECT_EQ(kNetworkCostLow, lport->network_cost()); for (const Candidate& candidate : lport->Candidates()) { - EXPECT_EQ(webrtc::kNetworkCostLow, candidate.network_cost()); + EXPECT_EQ(kNetworkCostLow, candidate.network_cost()); } // Add a connection and then change the network type. Connection* lconn = lport->CreateConnection(rport->Candidates()[0], Port::ORIGIN_MESSAGE); // Change the network type to cellular. - test_network->set_type(webrtc::ADAPTER_TYPE_CELLULAR); - EXPECT_EQ(webrtc::kNetworkCostHigh, lport->network_cost()); + test_network->set_type(ADAPTER_TYPE_CELLULAR); + EXPECT_EQ(kNetworkCostHigh, lport->network_cost()); for (const Candidate& candidate : lport->Candidates()) { - EXPECT_EQ(webrtc::kNetworkCostHigh, candidate.network_cost()); + EXPECT_EQ(kNetworkCostHigh, candidate.network_cost()); } - test_network->set_type(webrtc::ADAPTER_TYPE_WIFI); + test_network->set_type(ADAPTER_TYPE_WIFI); Connection* rconn = rport->CreateConnection(lport->Candidates()[0], Port::ORIGIN_MESSAGE); - test_network->set_type(webrtc::ADAPTER_TYPE_CELLULAR); + test_network->set_type(ADAPTER_TYPE_CELLULAR); lconn->Ping(0); - // The rconn's remote candidate cost is webrtc::kNetworkCostLow, but the ping - // contains an attribute of network cost of webrtc::kNetworkCostHigh. Once the + // The rconn's remote candidate cost is kNetworkCostLow, but the ping + // contains an attribute of network cost of kNetworkCostHigh. Once the // message is handled in rconn, The rconn's remote candidate will have cost - // webrtc::kNetworkCostHigh; - EXPECT_EQ(webrtc::kNetworkCostLow, rconn->remote_candidate().network_cost()); - ASSERT_THAT( - webrtc::WaitUntil([&] { return lport->last_stun_msg(); }, NotNull(), + // kNetworkCostHigh; + EXPECT_EQ(kNetworkCostLow, rconn->remote_candidate().network_cost()); + ASSERT_THAT(WaitUntil([&] { return lport->last_stun_msg(); }, NotNull(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); IceMessage* msg = lport->last_stun_msg(); EXPECT_EQ(STUN_BINDING_REQUEST, msg->type()); // Pass the binding request to rport. @@ -2370,20 +2326,19 @@ TEST_F(PortTest, TestNetworkCostChange) { ReceivedIpPacket(lport->last_stun_buf(), SocketAddress(), std::nullopt)); // Wait until rport sends the response and then check the remote network cost. - ASSERT_THAT( - webrtc::WaitUntil([&] { return rport->last_stun_msg(); }, NotNull(), + ASSERT_THAT(WaitUntil([&] { return rport->last_stun_msg(); }, NotNull(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); - EXPECT_EQ(webrtc::kNetworkCostHigh, rconn->remote_candidate().network_cost()); + IsRtcOk()); + EXPECT_EQ(kNetworkCostHigh, rconn->remote_candidate().network_cost()); } TEST_F(PortTest, TestNetworkInfoAttribute) { Network* test_network = MakeNetwork(kLocalAddr1); auto lport = CreateTestPort(test_network, "lfrag", "lpass"); auto rport = CreateTestPort(test_network, "rfrag", "rpass"); - lport->SetIceRole(webrtc::ICEROLE_CONTROLLING); + lport->SetIceRole(ICEROLE_CONTROLLING); lport->SetIceTiebreaker(kTiebreaker1); - rport->SetIceRole(webrtc::ICEROLE_CONTROLLED); + rport->SetIceRole(ICEROLE_CONTROLLED); rport->SetIceTiebreaker(kTiebreaker2); uint16_t lnetwork_id = 9; @@ -2394,10 +2349,9 @@ TEST_F(PortTest, TestNetworkInfoAttribute) { Connection* lconn = lport->CreateConnection(rport->Candidates()[0], Port::ORIGIN_MESSAGE); lconn->Ping(0); - ASSERT_THAT( - webrtc::WaitUntil([&] { return lport->last_stun_msg(); }, NotNull(), + ASSERT_THAT(WaitUntil([&] { return lport->last_stun_msg(); }, NotNull(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); IceMessage* msg = lport->last_stun_msg(); const StunUInt32Attribute* network_info_attr = msg->GetUInt32(STUN_ATTR_GOOG_NETWORK_INFO); @@ -2405,26 +2359,25 @@ TEST_F(PortTest, TestNetworkInfoAttribute) { uint32_t network_info = network_info_attr->value(); EXPECT_EQ(lnetwork_id, network_info >> 16); // Default network has unknown type and cost kNetworkCostUnknown. - EXPECT_EQ(webrtc::kNetworkCostUnknown, network_info & 0xFFFF); + EXPECT_EQ(kNetworkCostUnknown, network_info & 0xFFFF); // Set the network type to be cellular so its cost will be kNetworkCostHigh. // Send a fake ping from rport to lport. - test_network->set_type(webrtc::ADAPTER_TYPE_CELLULAR); + test_network->set_type(ADAPTER_TYPE_CELLULAR); uint16_t rnetwork_id = 8; test_network->set_id(rnetwork_id); Connection* rconn = rport->CreateConnection(lport->Candidates()[0], Port::ORIGIN_MESSAGE); rconn->Ping(0); - ASSERT_THAT( - webrtc::WaitUntil([&] { return rport->last_stun_msg(); }, NotNull(), + ASSERT_THAT(WaitUntil([&] { return rport->last_stun_msg(); }, NotNull(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); msg = rport->last_stun_msg(); network_info_attr = msg->GetUInt32(STUN_ATTR_GOOG_NETWORK_INFO); ASSERT_TRUE(network_info_attr != nullptr); network_info = network_info_attr->value(); EXPECT_EQ(rnetwork_id, network_info >> 16); - EXPECT_EQ(webrtc::kNetworkCostHigh, network_info & 0xFFFF); + EXPECT_EQ(kNetworkCostHigh, network_info & 0xFFFF); } // Test handling STUN messages. @@ -2691,9 +2644,9 @@ TEST_F(PortTest, TestHandleStunResponseWithUnknownComprehensionRequiredAttribute) { // Generic setup. auto lport = CreateTestPort(kLocalAddr1, "lfrag", "lpass", - webrtc::ICEROLE_CONTROLLING, kTiebreakerDefault); - auto rport = CreateTestPort(kLocalAddr2, "rfrag", "rpass", - webrtc::ICEROLE_CONTROLLED, kTiebreakerDefault); + ICEROLE_CONTROLLING, kTiebreakerDefault); + auto rport = CreateTestPort(kLocalAddr2, "rfrag", "rpass", ICEROLE_CONTROLLED, + kTiebreakerDefault); lport->PrepareAddress(); rport->PrepareAddress(); ASSERT_FALSE(lport->Candidates().empty()); @@ -2705,18 +2658,16 @@ TEST_F(PortTest, // Send request. lconn->Ping(0); - ASSERT_THAT( - webrtc::WaitUntil([&] { return lport->last_stun_msg(); }, NotNull(), + ASSERT_THAT(WaitUntil([&] { return lport->last_stun_msg(); }, NotNull(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); rconn->OnReadPacket( ReceivedIpPacket(lport->last_stun_buf(), SocketAddress(), std::nullopt)); // Intercept request and add comprehension required attribute. - ASSERT_THAT( - webrtc::WaitUntil([&] { return rport->last_stun_msg(); }, NotNull(), + ASSERT_THAT(WaitUntil([&] { return rport->last_stun_msg(); }, NotNull(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); auto modified_response = rport->last_stun_msg()->Clone(); modified_response->AddAttribute(StunAttribute::CreateUInt32(0x7777)); modified_response->RemoveAttribute(STUN_ATTR_FINGERPRINT); @@ -2736,9 +2687,9 @@ TEST_F(PortTest, TestHandleStunIndicationWithUnknownComprehensionRequiredAttribute) { // Generic set up. auto lport = CreateTestPort(kLocalAddr2, "lfrag", "lpass", - webrtc::ICEROLE_CONTROLLING, kTiebreakerDefault); - auto rport = CreateTestPort(kLocalAddr2, "rfrag", "rpass", - webrtc::ICEROLE_CONTROLLED, kTiebreakerDefault); + ICEROLE_CONTROLLING, kTiebreakerDefault); + auto rport = CreateTestPort(kLocalAddr2, "rfrag", "rpass", ICEROLE_CONTROLLED, + kTiebreakerDefault); lport->PrepareAddress(); rport->PrepareAddress(); ASSERT_FALSE(lport->Candidates().empty()); @@ -2762,7 +2713,7 @@ TEST_F(PortTest, // indications are allowed only to the connection which is in read mode. TEST_F(PortTest, TestHandleStunBindingIndication) { auto lport = CreateTestPort(kLocalAddr2, "lfrag", "lpass", - webrtc::ICEROLE_CONTROLLING, kTiebreaker1); + ICEROLE_CONTROLLING, kTiebreaker1); // Verifying encoding and decoding STUN indication message. std::unique_ptr in_msg, out_msg; @@ -2782,7 +2733,7 @@ TEST_F(PortTest, TestHandleStunBindingIndication) { // Verify connection can handle STUN indication and updates // last_ping_received. auto rport = CreateTestPort(kLocalAddr2, "rfrag", "rpass"); - rport->SetIceRole(webrtc::ICEROLE_CONTROLLED); + rport->SetIceRole(ICEROLE_CONTROLLED); rport->SetIceTiebreaker(kTiebreaker2); lport->PrepareAddress(); @@ -2796,20 +2747,18 @@ TEST_F(PortTest, TestHandleStunBindingIndication) { rport->CreateConnection(lport->Candidates()[0], Port::ORIGIN_MESSAGE); rconn->Ping(0); - ASSERT_THAT( - webrtc::WaitUntil([&] { return rport->last_stun_msg(); }, NotNull(), + ASSERT_THAT(WaitUntil([&] { return rport->last_stun_msg(); }, NotNull(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); IceMessage* msg = rport->last_stun_msg(); EXPECT_EQ(STUN_BINDING_REQUEST, msg->type()); // Send rport binding request to lport. lconn->OnReadPacket( ReceivedIpPacket(rport->last_stun_buf(), SocketAddress(), std::nullopt)); - ASSERT_THAT( - webrtc::WaitUntil([&] { return lport->last_stun_msg(); }, NotNull(), + ASSERT_THAT(WaitUntil([&] { return lport->last_stun_msg(); }, NotNull(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_EQ(STUN_BINDING_RESPONSE, lport->last_stun_msg()->type()); int64_t last_ping_received1 = lconn->last_ping_received(); @@ -2876,20 +2825,15 @@ TEST_F(PortTest, TestComputeCandidatePriorityWithPriorityAdjustment) { port->AddCandidateAddress(SocketAddress("3ffe::1234:5678", 1234)); // These should all be: // (90 << 24) | (([rfc3484 pref value] << 8) + kMaxTurnServers) | (256 - 177) - uint32_t expected_priority_v4 = 1509957199U + (webrtc::kMaxTurnServers << 8); - uint32_t expected_priority_v6 = 1509959759U + (webrtc::kMaxTurnServers << 8); - uint32_t expected_priority_ula = 1509962319U + (webrtc::kMaxTurnServers << 8); + uint32_t expected_priority_v4 = 1509957199U + (kMaxTurnServers << 8); + uint32_t expected_priority_v6 = 1509959759U + (kMaxTurnServers << 8); + uint32_t expected_priority_ula = 1509962319U + (kMaxTurnServers << 8); uint32_t expected_priority_v4mapped = expected_priority_v4; - uint32_t expected_priority_v4compat = - 1509949775U + (webrtc::kMaxTurnServers << 8); - uint32_t expected_priority_6to4 = - 1509954639U + (webrtc::kMaxTurnServers << 8); - uint32_t expected_priority_teredo = - 1509952079U + (webrtc::kMaxTurnServers << 8); - uint32_t expected_priority_sitelocal = - 1509949775U + (webrtc::kMaxTurnServers << 8); - uint32_t expected_priority_6bone = - 1509949775U + (webrtc::kMaxTurnServers << 8); + uint32_t expected_priority_v4compat = 1509949775U + (kMaxTurnServers << 8); + uint32_t expected_priority_6to4 = 1509954639U + (kMaxTurnServers << 8); + uint32_t expected_priority_teredo = 1509952079U + (kMaxTurnServers << 8); + uint32_t expected_priority_sitelocal = 1509949775U + (kMaxTurnServers << 8); + uint32_t expected_priority_6bone = 1509949775U + (kMaxTurnServers << 8); ASSERT_EQ(expected_priority_v4, port->Candidates()[0].priority()); ASSERT_EQ(expected_priority_v6, port->Candidates()[1].priority()); ASSERT_EQ(expected_priority_ula, port->Candidates()[2].priority()); @@ -2919,7 +2863,7 @@ TEST_F(PortTest, TestFoundation) { // This test verifies the foundation of different types of ICE candidates. TEST_F(PortTest, TestCandidateFoundation) { std::unique_ptr nat_server( - CreateNatServer(kNatAddr1, webrtc::NAT_OPEN_CONE)); + CreateNatServer(kNatAddr1, NAT_OPEN_CONE)); auto udpport1 = CreateUdpPort(kLocalAddr1); udpport1->PrepareAddress(); auto udpport2 = CreateUdpPort(kLocalAddr1); @@ -2934,10 +2878,9 @@ TEST_F(PortTest, TestCandidateFoundation) { tcpport2->Candidates()[0].foundation()); auto stunport = CreateStunPort(kLocalAddr1, nat_socket_factory1()); stunport->PrepareAddress(); - ASSERT_THAT( - webrtc::WaitUntil([&] { return stunport->Candidates().size(); }, Eq(1U), + ASSERT_THAT(WaitUntil([&] { return stunport->Candidates().size(); }, Eq(1U), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_NE(tcpport1->Candidates()[0].foundation(), stunport->Candidates()[0].foundation()); EXPECT_NE(tcpport2->Candidates()[0].foundation(), @@ -2947,56 +2890,51 @@ TEST_F(PortTest, TestCandidateFoundation) { EXPECT_NE(udpport2->Candidates()[0].foundation(), stunport->Candidates()[0].foundation()); // Verifying TURN candidate foundation. - auto turnport1 = CreateTurnPort(kLocalAddr1, nat_socket_factory1(), - webrtc::PROTO_UDP, webrtc::PROTO_UDP); + auto turnport1 = + CreateTurnPort(kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP); turnport1->PrepareAddress(); - ASSERT_THAT( - webrtc::WaitUntil([&] { return turnport1->Candidates().size(); }, Eq(1U), + ASSERT_THAT(WaitUntil([&] { return turnport1->Candidates().size(); }, Eq(1U), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_NE(udpport1->Candidates()[0].foundation(), turnport1->Candidates()[0].foundation()); EXPECT_NE(udpport2->Candidates()[0].foundation(), turnport1->Candidates()[0].foundation()); EXPECT_NE(stunport->Candidates()[0].foundation(), turnport1->Candidates()[0].foundation()); - auto turnport2 = CreateTurnPort(kLocalAddr1, nat_socket_factory1(), - webrtc::PROTO_UDP, webrtc::PROTO_UDP); + auto turnport2 = + CreateTurnPort(kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP); turnport2->PrepareAddress(); - ASSERT_THAT( - webrtc::WaitUntil([&] { return turnport2->Candidates().size(); }, Eq(1U), + ASSERT_THAT(WaitUntil([&] { return turnport2->Candidates().size(); }, Eq(1U), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_EQ(turnport1->Candidates()[0].foundation(), turnport2->Candidates()[0].foundation()); // Running a second turn server, to get different base IP address. - SocketAddress kTurnUdpIntAddr2("99.99.98.4", webrtc::STUN_SERVER_PORT); + SocketAddress kTurnUdpIntAddr2("99.99.98.4", STUN_SERVER_PORT); SocketAddress kTurnUdpExtAddr2("99.99.98.5", 0); TestTurnServer turn_server2(Thread::Current(), vss(), kTurnUdpIntAddr2, kTurnUdpExtAddr2); - auto turnport3 = - CreateTurnPort(kLocalAddr1, nat_socket_factory1(), webrtc::PROTO_UDP, - webrtc::PROTO_UDP, kTurnUdpIntAddr2); + auto turnport3 = CreateTurnPort(kLocalAddr1, nat_socket_factory1(), PROTO_UDP, + PROTO_UDP, kTurnUdpIntAddr2); turnport3->PrepareAddress(); - ASSERT_THAT( - webrtc::WaitUntil([&] { return turnport3->Candidates().size(); }, Eq(1U), + ASSERT_THAT(WaitUntil([&] { return turnport3->Candidates().size(); }, Eq(1U), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_NE(turnport3->Candidates()[0].foundation(), turnport2->Candidates()[0].foundation()); // Start a TCP turn server, and check that two turn candidates have // different foundations if their relay protocols are different. TestTurnServer turn_server3(Thread::Current(), vss(), kTurnTcpIntAddr, - kTurnUdpExtAddr, webrtc::PROTO_TCP); - auto turnport4 = CreateTurnPort(kLocalAddr1, nat_socket_factory1(), - webrtc::PROTO_TCP, webrtc::PROTO_UDP); + kTurnUdpExtAddr, PROTO_TCP); + auto turnport4 = + CreateTurnPort(kLocalAddr1, nat_socket_factory1(), PROTO_TCP, PROTO_UDP); turnport4->PrepareAddress(); - ASSERT_THAT( - webrtc::WaitUntil([&] { return turnport4->Candidates().size(); }, Eq(1U), + ASSERT_THAT(WaitUntil([&] { return turnport4->Candidates().size(); }, Eq(1U), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_NE(turnport2->Candidates()[0].foundation(), turnport4->Candidates()[0].foundation()); } @@ -3004,7 +2942,7 @@ TEST_F(PortTest, TestCandidateFoundation) { // This test verifies the related addresses of different types of // ICE candidates. TEST_F(PortTest, TestCandidateRelatedAddress) { - auto nat_server = CreateNatServer(kNatAddr1, webrtc::NAT_OPEN_CONE); + auto nat_server = CreateNatServer(kNatAddr1, NAT_OPEN_CONE); auto udpport = CreateUdpPort(kLocalAddr1); udpport->PrepareAddress(); // For UDPPort, related address will be empty. @@ -3014,10 +2952,9 @@ TEST_F(PortTest, TestCandidateRelatedAddress) { // socket address. auto stunport = CreateStunPort(kLocalAddr1, nat_socket_factory1()); stunport->PrepareAddress(); - ASSERT_THAT( - webrtc::WaitUntil([&] { return stunport->Candidates().size(); }, Eq(1U), + ASSERT_THAT(WaitUntil([&] { return stunport->Candidates().size(); }, Eq(1U), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); // Check STUN candidate address. EXPECT_EQ(stunport->Candidates()[0].address().ipaddr(), kNatAddr1.ipaddr()); // Check STUN candidate related address. @@ -3025,13 +2962,12 @@ TEST_F(PortTest, TestCandidateRelatedAddress) { stunport->GetLocalAddress()); // Verifying the related address for TURN candidate. // For TURN related address must be equal to the mapped address. - auto turnport = CreateTurnPort(kLocalAddr1, nat_socket_factory1(), - webrtc::PROTO_UDP, webrtc::PROTO_UDP); + auto turnport = + CreateTurnPort(kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP); turnport->PrepareAddress(); - ASSERT_THAT( - webrtc::WaitUntil([&] { return turnport->Candidates().size(); }, Eq(1U), + ASSERT_THAT(WaitUntil([&] { return turnport->Candidates().size(); }, Eq(1U), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_EQ(kTurnUdpExtAddr.ipaddr(), turnport->Candidates()[0].address().ipaddr()); EXPECT_EQ(kNatAddr1.ipaddr(), @@ -3066,8 +3002,8 @@ TEST_F(PortTest, TestConnectionPriority) { // RFC 5245 // pair priority = 2^32*MIN(G,D) + 2*MAX(G,D) + (G>D?1:0) - lport->SetIceRole(webrtc::ICEROLE_CONTROLLING); - rport->SetIceRole(webrtc::ICEROLE_CONTROLLED); + lport->SetIceRole(ICEROLE_CONTROLLING); + rport->SetIceRole(ICEROLE_CONTROLLED); Connection* lconn = lport->CreateConnection(rport->Candidates()[0], Port::ORIGIN_MESSAGE); #if defined(WEBRTC_WIN) @@ -3076,8 +3012,8 @@ TEST_F(PortTest, TestConnectionPriority) { EXPECT_EQ(0x2001EE9FC003D0BLLU, lconn->priority()); #endif - lport->SetIceRole(webrtc::ICEROLE_CONTROLLED); - rport->SetIceRole(webrtc::ICEROLE_CONTROLLING); + lport->SetIceRole(ICEROLE_CONTROLLED); + rport->SetIceRole(ICEROLE_CONTROLLING); Connection* rconn = rport->CreateConnection(lport->Candidates()[0], Port::ORIGIN_MESSAGE); #if defined(WEBRTC_WIN) @@ -3103,15 +3039,15 @@ TEST_F(PortTest, TestConnectionPriorityWithPriorityAdjustment) { rport->set_component(23); rport->AddCandidateAddress(SocketAddress("10.1.1.100", 1234)); - EXPECT_EQ(0x7E001E85U + (webrtc::kMaxTurnServers << 8), + EXPECT_EQ(0x7E001E85U + (kMaxTurnServers << 8), lport->Candidates()[0].priority()); - EXPECT_EQ(0x2001EE9U + (webrtc::kMaxTurnServers << 8), + EXPECT_EQ(0x2001EE9U + (kMaxTurnServers << 8), rport->Candidates()[0].priority()); // RFC 5245 // pair priority = 2^32*MIN(G,D) + 2*MAX(G,D) + (G>D?1:0) - lport->SetIceRole(webrtc::ICEROLE_CONTROLLING); - rport->SetIceRole(webrtc::ICEROLE_CONTROLLED); + lport->SetIceRole(ICEROLE_CONTROLLING); + rport->SetIceRole(ICEROLE_CONTROLLED); Connection* lconn = lport->CreateConnection(rport->Candidates()[0], Port::ORIGIN_MESSAGE); #if defined(WEBRTC_WIN) @@ -3120,8 +3056,8 @@ TEST_F(PortTest, TestConnectionPriorityWithPriorityAdjustment) { EXPECT_EQ(0x2003EE9FC007D0BLLU, lconn->priority()); #endif - lport->SetIceRole(webrtc::ICEROLE_CONTROLLED); - rport->SetIceRole(webrtc::ICEROLE_CONTROLLING); + lport->SetIceRole(ICEROLE_CONTROLLED); + rport->SetIceRole(ICEROLE_CONTROLLING); Connection* rconn = rport->CreateConnection(lport->Candidates()[0], Port::ORIGIN_MESSAGE); RTC_LOG(LS_ERROR) << "RCONN " << rconn->priority(); @@ -3141,9 +3077,9 @@ TEST_F(PortTest, TestConnectionPriorityWithPriorityAdjustment) { TEST_F(PortTest, TestWritableState) { ScopedFakeClock clock; auto port1 = CreateUdpPort(kLocalAddr1); - port1->SetIceRole(webrtc::ICEROLE_CONTROLLING); + port1->SetIceRole(ICEROLE_CONTROLLING); auto port2 = CreateUdpPort(kLocalAddr2); - port2->SetIceRole(webrtc::ICEROLE_CONTROLLED); + port2->SetIceRole(ICEROLE_CONTROLLED); // Set up channels. TestChannel ch1(std::move(port1)); @@ -3152,25 +3088,24 @@ TEST_F(PortTest, TestWritableState) { // Acquire addresses. ch1.Start(); ch2.Start(); - ASSERT_THAT(webrtc::WaitUntil([&] { return ch1.complete_count(); }, Eq(1), - {.timeout = TimeDelta::Millis(kDefaultTimeout), - .clock = &clock}), - webrtc::IsRtcOk()); - ASSERT_THAT(webrtc::WaitUntil([&] { return ch2.complete_count(); }, Eq(1), - {.timeout = TimeDelta::Millis(kDefaultTimeout), - .clock = &clock}), - webrtc::IsRtcOk()); + ASSERT_THAT(WaitUntil([&] { return ch1.complete_count(); }, Eq(1), + {.timeout = TimeDelta::Millis(kDefaultTimeout), + .clock = &clock}), + IsRtcOk()); + ASSERT_THAT(WaitUntil([&] { return ch2.complete_count(); }, Eq(1), + {.timeout = TimeDelta::Millis(kDefaultTimeout), + .clock = &clock}), + IsRtcOk()); // Send a ping from src to dst. ch1.CreateConnection(GetCandidate(ch2.port())); ASSERT_TRUE(ch1.conn() != nullptr); EXPECT_EQ(Connection::STATE_WRITE_INIT, ch1.conn()->write_state()); // for TCP connect - EXPECT_THAT( - webrtc::WaitUntil( - [&] { return ch1.conn()->connected(); }, IsTrue(), - {.timeout = TimeDelta::Millis(kDefaultTimeout), .clock = &clock}), - webrtc::IsRtcOk()); + EXPECT_THAT(WaitUntil([&] { return ch1.conn()->connected(); }, IsTrue(), + {.timeout = TimeDelta::Millis(kDefaultTimeout), + .clock = &clock}), + IsRtcOk()); ch1.Ping(); SIMULATED_WAIT(!ch2.remote_address().IsNil(), kShortTimeout, clock); @@ -3183,11 +3118,11 @@ TEST_F(PortTest, TestWritableState) { // Accept the connection to return the binding response, transition to // writable, and allow data to be sent. ch2.AcceptConnection(GetCandidate(ch1.port())); - EXPECT_THAT(webrtc::WaitUntil([&] { return ch1.conn()->write_state(); }, - Eq(Connection::STATE_WRITABLE), - {.timeout = TimeDelta::Millis(kDefaultTimeout), - .clock = &clock}), - webrtc::IsRtcOk()); + EXPECT_THAT(WaitUntil([&] { return ch1.conn()->write_state(); }, + Eq(Connection::STATE_WRITABLE), + {.timeout = TimeDelta::Millis(kDefaultTimeout), + .clock = &clock}), + IsRtcOk()); EXPECT_EQ(data_size, ch1.conn()->Send(data, data_size, options)); // Ask the connection to update state as if enough time has passed to lose @@ -3206,11 +3141,11 @@ TEST_F(PortTest, TestWritableState) { // And now allow the other side to process the pings and send binding // responses. - EXPECT_THAT(webrtc::WaitUntil([&] { return ch1.conn()->write_state(); }, - Eq(Connection::STATE_WRITABLE), - {.timeout = TimeDelta::Millis(kDefaultTimeout), - .clock = &clock}), - webrtc::IsRtcOk()); + EXPECT_THAT(WaitUntil([&] { return ch1.conn()->write_state(); }, + Eq(Connection::STATE_WRITABLE), + {.timeout = TimeDelta::Millis(kDefaultTimeout), + .clock = &clock}), + IsRtcOk()); // Wait long enough for a full timeout (past however long we've already // waited). for (uint32_t i = 1; i <= CONNECTION_WRITE_CONNECT_FAILURES; ++i) { @@ -3234,9 +3169,9 @@ TEST_F(PortTest, TestWritableState) { TEST_F(PortTest, TestWritableStateWithConfiguredThreshold) { ScopedFakeClock clock; auto port1 = CreateUdpPort(kLocalAddr1); - port1->SetIceRole(webrtc::ICEROLE_CONTROLLING); + port1->SetIceRole(ICEROLE_CONTROLLING); auto port2 = CreateUdpPort(kLocalAddr2); - port2->SetIceRole(webrtc::ICEROLE_CONTROLLED); + port2->SetIceRole(ICEROLE_CONTROLLED); // Set up channels. TestChannel ch1(std::move(port1)); @@ -3245,14 +3180,14 @@ TEST_F(PortTest, TestWritableStateWithConfiguredThreshold) { // Acquire addresses. ch1.Start(); ch2.Start(); - ASSERT_THAT(webrtc::WaitUntil([&] { return ch1.complete_count(); }, Eq(1), - {.timeout = TimeDelta::Millis(kDefaultTimeout), - .clock = &clock}), - webrtc::IsRtcOk()); - ASSERT_THAT(webrtc::WaitUntil([&] { return ch2.complete_count(); }, Eq(1), - {.timeout = TimeDelta::Millis(kDefaultTimeout), - .clock = &clock}), - webrtc::IsRtcOk()); + ASSERT_THAT(WaitUntil([&] { return ch1.complete_count(); }, Eq(1), + {.timeout = TimeDelta::Millis(kDefaultTimeout), + .clock = &clock}), + IsRtcOk()); + ASSERT_THAT(WaitUntil([&] { return ch2.complete_count(); }, Eq(1), + {.timeout = TimeDelta::Millis(kDefaultTimeout), + .clock = &clock}), + IsRtcOk()); // Send a ping from src to dst. ch1.CreateConnection(GetCandidate(ch2.port())); @@ -3263,11 +3198,11 @@ TEST_F(PortTest, TestWritableStateWithConfiguredThreshold) { // Accept the connection to return the binding response, transition to // writable, and allow data to be sent. ch2.AcceptConnection(GetCandidate(ch1.port())); - EXPECT_THAT(webrtc::WaitUntil([&] { return ch1.conn()->write_state(); }, - Eq(Connection::STATE_WRITABLE), - {.timeout = TimeDelta::Millis(kDefaultTimeout), - .clock = &clock}), - webrtc::IsRtcOk()); + EXPECT_THAT(WaitUntil([&] { return ch1.conn()->write_state(); }, + Eq(Connection::STATE_WRITABLE), + {.timeout = TimeDelta::Millis(kDefaultTimeout), + .clock = &clock}), + IsRtcOk()); ch1.conn()->set_unwritable_timeout(1000); ch1.conn()->set_unwritable_min_checks(3); @@ -3297,9 +3232,9 @@ TEST_F(PortTest, TestWritableStateWithConfiguredThreshold) { TEST_F(PortTest, TestTimeoutForNeverWritable) { auto port1 = CreateUdpPort(kLocalAddr1); - port1->SetIceRole(webrtc::ICEROLE_CONTROLLING); + port1->SetIceRole(ICEROLE_CONTROLLING); auto port2 = CreateUdpPort(kLocalAddr2); - port2->SetIceRole(webrtc::ICEROLE_CONTROLLED); + port2->SetIceRole(ICEROLE_CONTROLLED); // Set up channels. TestChannel ch1(std::move(port1)); @@ -3326,24 +3261,23 @@ TEST_F(PortTest, TestTimeoutForNeverWritable) { // In this test `ch1` behaves like FULL mode client and we have created // port which responds to the ping message just like LITE client. TEST_F(PortTest, TestIceLiteConnectivity) { - auto ice_full_port = CreateTestPort( - kLocalAddr1, "lfrag", "lpass", webrtc::ICEROLE_CONTROLLING, kTiebreaker1); + auto ice_full_port = CreateTestPort(kLocalAddr1, "lfrag", "lpass", + ICEROLE_CONTROLLING, kTiebreaker1); auto* ice_full_port_ptr = ice_full_port.get(); auto ice_lite_port = CreateTestPort(kLocalAddr2, "rfrag", "rpass", - webrtc::ICEROLE_CONTROLLED, kTiebreaker2); + ICEROLE_CONTROLLED, kTiebreaker2); // Setup TestChannel. This behaves like FULL mode client. TestChannel ch1(std::move(ice_full_port)); - ch1.SetIceMode(webrtc::ICEMODE_FULL); + ch1.SetIceMode(ICEMODE_FULL); // Start gathering candidates. ch1.Start(); ice_lite_port->PrepareAddress(); - ASSERT_THAT( - webrtc::WaitUntil([&] { return ch1.complete_count(); }, Eq(1), + ASSERT_THAT(WaitUntil([&] { return ch1.complete_count(); }, Eq(1), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); ASSERT_FALSE(ice_lite_port->Candidates().empty()); ch1.CreateConnection(GetCandidate(ice_lite_port.get())); @@ -3356,10 +3290,10 @@ TEST_F(PortTest, TestIceLiteConnectivity) { // Verify stun ping is without USE_CANDIDATE_ATTR. Getting message directly // from port. - ASSERT_THAT(webrtc::WaitUntil( - [&] { return ice_full_port_ptr->last_stun_msg(); }, NotNull(), - {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + ASSERT_THAT( + WaitUntil([&] { return ice_full_port_ptr->last_stun_msg(); }, NotNull(), + {.timeout = TimeDelta::Millis(kDefaultTimeout)}), + IsRtcOk()); IceMessage* msg = ice_full_port_ptr->last_stun_msg(); EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) == nullptr); @@ -3377,25 +3311,23 @@ TEST_F(PortTest, TestIceLiteConnectivity) { SocketAddress(), std::nullopt)); // Verifying full mode connection becomes writable from the response. - EXPECT_THAT( - webrtc::WaitUntil([&] { return ch1.conn()->write_state(); }, + EXPECT_THAT(WaitUntil([&] { return ch1.conn()->write_state(); }, Eq(Connection::STATE_WRITABLE), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); - EXPECT_THAT( - webrtc::WaitUntil([&] { return ch1.nominated(); }, IsTrue(), + IsRtcOk()); + EXPECT_THAT(WaitUntil([&] { return ch1.nominated(); }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); // Clear existing stun messsages. Otherwise we will process old stun // message right after we send ping. ice_full_port_ptr->Reset(); // Send ping. This must have USE_CANDIDATE_ATTR. ch1.Ping(); - ASSERT_THAT(webrtc::WaitUntil( - [&] { return ice_full_port_ptr->last_stun_msg(); }, NotNull(), - {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + ASSERT_THAT( + WaitUntil([&] { return ice_full_port_ptr->last_stun_msg(); }, NotNull(), + {.timeout = TimeDelta::Millis(kDefaultTimeout)}), + IsRtcOk()); msg = ice_full_port_ptr->last_stun_msg(); EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) != nullptr); ch1.Stop(); @@ -3453,24 +3385,23 @@ TEST_P(GoogPingTest, TestGoogPingAnnounceEnable) { << " enable:" << trials.enable_goog_ping; auto port1_unique = CreateTestPort(kLocalAddr1, "lfrag", "lpass", - webrtc::ICEROLE_CONTROLLING, kTiebreaker1); + ICEROLE_CONTROLLING, kTiebreaker1); auto* port1 = port1_unique.get(); - auto port2 = CreateTestPort(kLocalAddr2, "rfrag", "rpass", - webrtc::ICEROLE_CONTROLLED, kTiebreaker2); + auto port2 = CreateTestPort(kLocalAddr2, "rfrag", "rpass", ICEROLE_CONTROLLED, + kTiebreaker2); TestChannel ch1(std::move(port1_unique)); // Block usage of STUN_ATTR_USE_CANDIDATE so that // ch1.conn() will sent GOOG_PING_REQUEST directly. // This only makes test a bit shorter... - ch1.SetIceMode(webrtc::ICEMODE_LITE); + ch1.SetIceMode(ICEMODE_LITE); // Start gathering candidates. ch1.Start(); port2->PrepareAddress(); - ASSERT_THAT( - webrtc::WaitUntil([&] { return ch1.complete_count(); }, Eq(1), + ASSERT_THAT(WaitUntil([&] { return ch1.complete_count(); }, Eq(1), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); ASSERT_FALSE(port2->Candidates().empty()); ch1.CreateConnection(GetCandidate(port2.get())); @@ -3481,10 +3412,9 @@ TEST_P(GoogPingTest, TestGoogPingAnnounceEnable) { // Send ping. ch1.Ping(); - ASSERT_THAT( - webrtc::WaitUntil([&] { return port1->last_stun_msg(); }, NotNull(), + ASSERT_THAT(WaitUntil([&] { return port1->last_stun_msg(); }, NotNull(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); const IceMessage* request1 = port1->last_stun_msg(); ASSERT_EQ(trials.enable_goog_ping, @@ -3512,10 +3442,9 @@ TEST_P(GoogPingTest, TestGoogPingAnnounceEnable) { port2->Reset(); ch1.Ping(); - ASSERT_THAT( - webrtc::WaitUntil([&] { return port1->last_stun_msg(); }, NotNull(), + ASSERT_THAT(WaitUntil([&] { return port1->last_stun_msg(); }, NotNull(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); const IceMessage* request2 = port1->last_stun_msg(); // It should be a GOOG_PING if both of these are TRUE @@ -3552,24 +3481,23 @@ TEST_F(PortTest, TestGoogPingUnsupportedVersionInStunBinding) { trials.enable_goog_ping = true; auto port1_unique = CreateTestPort(kLocalAddr1, "lfrag", "lpass", - webrtc::ICEROLE_CONTROLLING, kTiebreaker1); + ICEROLE_CONTROLLING, kTiebreaker1); auto* port1 = port1_unique.get(); - auto port2 = CreateTestPort(kLocalAddr2, "rfrag", "rpass", - webrtc::ICEROLE_CONTROLLED, kTiebreaker2); + auto port2 = CreateTestPort(kLocalAddr2, "rfrag", "rpass", ICEROLE_CONTROLLED, + kTiebreaker2); TestChannel ch1(std::move(port1_unique)); // Block usage of STUN_ATTR_USE_CANDIDATE so that // ch1.conn() will sent GOOG_PING_REQUEST directly. // This only makes test a bit shorter... - ch1.SetIceMode(webrtc::ICEMODE_LITE); + ch1.SetIceMode(ICEMODE_LITE); // Start gathering candidates. ch1.Start(); port2->PrepareAddress(); - ASSERT_THAT( - webrtc::WaitUntil([&] { return ch1.complete_count(); }, Eq(1), + ASSERT_THAT(WaitUntil([&] { return ch1.complete_count(); }, Eq(1), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); ASSERT_FALSE(port2->Candidates().empty()); ch1.CreateConnection(GetCandidate(port2.get())); @@ -3580,10 +3508,9 @@ TEST_F(PortTest, TestGoogPingUnsupportedVersionInStunBinding) { // Send ping. ch1.Ping(); - ASSERT_THAT( - webrtc::WaitUntil([&] { return port1->last_stun_msg(); }, NotNull(), + ASSERT_THAT(WaitUntil([&] { return port1->last_stun_msg(); }, NotNull(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); const IceMessage* request1 = port1->last_stun_msg(); ASSERT_TRUE(GetSupportedGoogPingVersion(request1) && @@ -3627,24 +3554,23 @@ TEST_F(PortTest, TestGoogPingUnsupportedVersionInStunBindingResponse) { trials.enable_goog_ping = true; auto port1_unique = CreateTestPort(kLocalAddr1, "lfrag", "lpass", - webrtc::ICEROLE_CONTROLLING, kTiebreaker1); + ICEROLE_CONTROLLING, kTiebreaker1); auto* port1 = port1_unique.get(); - auto port2 = CreateTestPort(kLocalAddr2, "rfrag", "rpass", - webrtc::ICEROLE_CONTROLLED, kTiebreaker2); + auto port2 = CreateTestPort(kLocalAddr2, "rfrag", "rpass", ICEROLE_CONTROLLED, + kTiebreaker2); TestChannel ch1(std::move(port1_unique)); // Block usage of STUN_ATTR_USE_CANDIDATE so that // ch1.conn() will sent GOOG_PING_REQUEST directly. // This only makes test a bit shorter... - ch1.SetIceMode(webrtc::ICEMODE_LITE); + ch1.SetIceMode(ICEMODE_LITE); // Start gathering candidates. ch1.Start(); port2->PrepareAddress(); - ASSERT_THAT( - webrtc::WaitUntil([&] { return ch1.complete_count(); }, Eq(1), + ASSERT_THAT(WaitUntil([&] { return ch1.complete_count(); }, Eq(1), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); ASSERT_FALSE(port2->Candidates().empty()); ch1.CreateConnection(GetCandidate(port2.get())); @@ -3655,10 +3581,9 @@ TEST_F(PortTest, TestGoogPingUnsupportedVersionInStunBindingResponse) { // Send ping. ch1.Ping(); - ASSERT_THAT( - webrtc::WaitUntil([&] { return port1->last_stun_msg(); }, NotNull(), + ASSERT_THAT(WaitUntil([&] { return port1->last_stun_msg(); }, NotNull(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); const IceMessage* request1 = port1->last_stun_msg(); ASSERT_TRUE(GetSupportedGoogPingVersion(request1) && @@ -3707,10 +3632,9 @@ TEST_F(PortTest, TestGoogPingUnsupportedVersionInStunBindingResponse) { port2->Reset(); ch1.Ping(); - ASSERT_THAT( - webrtc::WaitUntil([&] { return port1->last_stun_msg(); }, NotNull(), + ASSERT_THAT(WaitUntil([&] { return port1->last_stun_msg(); }, NotNull(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); // This should now be a STUN_BINDING...without a kGoogPingVersion const IceMessage* request2 = port1->last_stun_msg(); @@ -3735,24 +3659,23 @@ TEST_F(PortTest, TestChangeInAttributeMakesGoogPingFallsbackToStunBinding) { trials.enable_goog_ping = true; auto port1_unique = CreateTestPort(kLocalAddr1, "lfrag", "lpass", - webrtc::ICEROLE_CONTROLLING, kTiebreaker1); + ICEROLE_CONTROLLING, kTiebreaker1); auto* port1 = port1_unique.get(); - auto port2 = CreateTestPort(kLocalAddr2, "rfrag", "rpass", - webrtc::ICEROLE_CONTROLLED, kTiebreaker2); + auto port2 = CreateTestPort(kLocalAddr2, "rfrag", "rpass", ICEROLE_CONTROLLED, + kTiebreaker2); TestChannel ch1(std::move(port1_unique)); // Block usage of STUN_ATTR_USE_CANDIDATE so that // ch1.conn() will sent GOOG_PING_REQUEST directly. // This only makes test a bit shorter... - ch1.SetIceMode(webrtc::ICEMODE_LITE); + ch1.SetIceMode(ICEMODE_LITE); // Start gathering candidates. ch1.Start(); port2->PrepareAddress(); - ASSERT_THAT( - webrtc::WaitUntil([&] { return ch1.complete_count(); }, Eq(1), + ASSERT_THAT(WaitUntil([&] { return ch1.complete_count(); }, Eq(1), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); ASSERT_FALSE(port2->Candidates().empty()); ch1.CreateConnection(GetCandidate(port2.get())); @@ -3763,10 +3686,9 @@ TEST_F(PortTest, TestChangeInAttributeMakesGoogPingFallsbackToStunBinding) { // Send ping. ch1.Ping(); - ASSERT_THAT( - webrtc::WaitUntil([&] { return port1->last_stun_msg(); }, NotNull(), + ASSERT_THAT(WaitUntil([&] { return port1->last_stun_msg(); }, NotNull(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); const IceMessage* msg = port1->last_stun_msg(); auto* con = port2->CreateConnection(port1->Candidates()[0], Port::ORIGIN_MESSAGE); @@ -3788,10 +3710,9 @@ TEST_F(PortTest, TestChangeInAttributeMakesGoogPingFallsbackToStunBinding) { port2->Reset(); ch1.Ping(); - ASSERT_THAT( - webrtc::WaitUntil([&] { return port1->last_stun_msg(); }, NotNull(), + ASSERT_THAT(WaitUntil([&] { return port1->last_stun_msg(); }, NotNull(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); const IceMessage* msg2 = port1->last_stun_msg(); // It should be a GOOG_PING if both of these are TRUE @@ -3812,10 +3733,9 @@ TEST_F(PortTest, TestChangeInAttributeMakesGoogPingFallsbackToStunBinding) { ch1.conn()->set_use_candidate_attr(!ch1.conn()->use_candidate_attr()); ch1.Ping(); - ASSERT_THAT( - webrtc::WaitUntil([&] { return port1->last_stun_msg(); }, NotNull(), + ASSERT_THAT(WaitUntil([&] { return port1->last_stun_msg(); }, NotNull(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); const IceMessage* msg3 = port1->last_stun_msg(); // It should be a STUN_BINDING_REQUEST @@ -3831,24 +3751,23 @@ TEST_F(PortTest, TestErrorResponseMakesGoogPingFallBackToStunBinding) { trials.enable_goog_ping = true; auto port1_unique = CreateTestPort(kLocalAddr1, "lfrag", "lpass", - webrtc::ICEROLE_CONTROLLING, kTiebreaker1); + ICEROLE_CONTROLLING, kTiebreaker1); auto* port1 = port1_unique.get(); - auto port2 = CreateTestPort(kLocalAddr2, "rfrag", "rpass", - webrtc::ICEROLE_CONTROLLED, kTiebreaker2); + auto port2 = CreateTestPort(kLocalAddr2, "rfrag", "rpass", ICEROLE_CONTROLLED, + kTiebreaker2); TestChannel ch1(std::move(port1_unique)); // Block usage of STUN_ATTR_USE_CANDIDATE so that // ch1.conn() will sent GOOG_PING_REQUEST directly. // This only makes test a bit shorter... - ch1.SetIceMode(webrtc::ICEMODE_LITE); + ch1.SetIceMode(ICEMODE_LITE); // Start gathering candidates. ch1.Start(); port2->PrepareAddress(); - ASSERT_THAT( - webrtc::WaitUntil([&] { return ch1.complete_count(); }, Eq(1), + ASSERT_THAT(WaitUntil([&] { return ch1.complete_count(); }, Eq(1), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); ASSERT_FALSE(port2->Candidates().empty()); ch1.CreateConnection(GetCandidate(port2.get())); @@ -3859,10 +3778,9 @@ TEST_F(PortTest, TestErrorResponseMakesGoogPingFallBackToStunBinding) { // Send ping. ch1.Ping(); - ASSERT_THAT( - webrtc::WaitUntil([&] { return port1->last_stun_msg(); }, NotNull(), + ASSERT_THAT(WaitUntil([&] { return port1->last_stun_msg(); }, NotNull(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); const IceMessage* msg = port1->last_stun_msg(); auto* con = port2->CreateConnection(port1->Candidates()[0], Port::ORIGIN_MESSAGE); @@ -3884,10 +3802,9 @@ TEST_F(PortTest, TestErrorResponseMakesGoogPingFallBackToStunBinding) { port2->Reset(); ch1.Ping(); - ASSERT_THAT( - webrtc::WaitUntil([&] { return port1->last_stun_msg(); }, NotNull(), + ASSERT_THAT(WaitUntil([&] { return port1->last_stun_msg(); }, NotNull(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); const IceMessage* msg2 = port1->last_stun_msg(); // It should be a GOOG_PING. @@ -3915,10 +3832,9 @@ TEST_F(PortTest, TestErrorResponseMakesGoogPingFallBackToStunBinding) { port2->Reset(); ch1.Ping(); - ASSERT_THAT( - webrtc::WaitUntil([&] { return port1->last_stun_msg(); }, NotNull(), + ASSERT_THAT(WaitUntil([&] { return port1->last_stun_msg(); }, NotNull(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); const IceMessage* msg3 = port1->last_stun_msg(); // It should be a STUN_BINDING_REQUEST @@ -3936,13 +3852,13 @@ TEST_F(PortTest, TestPortTimeoutIfNotKeptAlive) { auto port1 = CreateUdpPort(kLocalAddr1); ConnectToSignalDestroyed(port1.get()); port1->set_timeout_delay(timeout_delay); // milliseconds - port1->SetIceRole(webrtc::ICEROLE_CONTROLLING); + port1->SetIceRole(ICEROLE_CONTROLLING); port1->SetIceTiebreaker(kTiebreaker1); auto port2 = CreateUdpPort(kLocalAddr2); ConnectToSignalDestroyed(port2.get()); port2->set_timeout_delay(timeout_delay); // milliseconds - port2->SetIceRole(webrtc::ICEROLE_CONTROLLED); + port2->SetIceRole(ICEROLE_CONTROLLED); port2->SetIceTiebreaker(kTiebreaker2); // Set up channels and ensure both ports will be deleted. @@ -3953,9 +3869,9 @@ TEST_F(PortTest, TestPortTimeoutIfNotKeptAlive) { StartConnectAndStopChannels(&ch1, &ch2); // After the connection is destroyed, the port will be destroyed because // none of them is marked as "keep alive until pruned. - EXPECT_THAT(webrtc::WaitUntil([&] { return ports_destroyed(); }, Eq(2), - {.clock = &clock}), - webrtc::IsRtcOk()); + EXPECT_THAT( + WaitUntil([&] { return ports_destroyed(); }, Eq(2), {.clock = &clock}), + IsRtcOk()); } // Test that if after all connection are destroyed, new connections are created @@ -3967,14 +3883,14 @@ TEST_F(PortTest, TestPortTimeoutAfterNewConnectionCreatedAndDestroyed) { auto port1 = CreateUdpPort(kLocalAddr1); ConnectToSignalDestroyed(port1.get()); port1->set_timeout_delay(timeout_delay); // milliseconds - port1->SetIceRole(webrtc::ICEROLE_CONTROLLING); + port1->SetIceRole(ICEROLE_CONTROLLING); port1->SetIceTiebreaker(kTiebreaker1); auto port2 = CreateUdpPort(kLocalAddr2); ConnectToSignalDestroyed(port2.get()); port2->set_timeout_delay(timeout_delay); // milliseconds - port2->SetIceRole(webrtc::ICEROLE_CONTROLLED); + port2->SetIceRole(ICEROLE_CONTROLLED); port2->SetIceTiebreaker(kTiebreaker2); // Set up channels and ensure both ports will be deleted. @@ -3996,9 +3912,9 @@ TEST_F(PortTest, TestPortTimeoutAfterNewConnectionCreatedAndDestroyed) { EXPECT_EQ(0, ports_destroyed()); // The ports on both sides should be destroyed after timeout. - EXPECT_THAT(webrtc::WaitUntil([&] { return ports_destroyed(); }, Eq(2), - {.clock = &clock}), - webrtc::IsRtcOk()); + EXPECT_THAT( + WaitUntil([&] { return ports_destroyed(); }, Eq(2), {.clock = &clock}), + IsRtcOk()); } // This test case verifies that neither the controlling port nor the controlled @@ -4010,13 +3926,13 @@ TEST_F(PortTest, TestPortNotTimeoutUntilPruned) { auto port1 = CreateUdpPort(kLocalAddr1); ConnectToSignalDestroyed(port1.get()); port1->set_timeout_delay(timeout_delay); // milliseconds - port1->SetIceRole(webrtc::ICEROLE_CONTROLLING); + port1->SetIceRole(ICEROLE_CONTROLLING); port1->SetIceTiebreaker(kTiebreaker1); auto port2 = CreateUdpPort(kLocalAddr2); ConnectToSignalDestroyed(port2.get()); port2->set_timeout_delay(timeout_delay); // milliseconds - port2->SetIceRole(webrtc::ICEROLE_CONTROLLED); + port2->SetIceRole(ICEROLE_CONTROLLED); port2->SetIceTiebreaker(kTiebreaker2); // The connection must not be destroyed before a connection is attempted. EXPECT_EQ(0, ports_destroyed()); @@ -4039,29 +3955,29 @@ TEST_F(PortTest, TestPortNotTimeoutUntilPruned) { ch1.port()->Prune(); ch2.port()->Prune(); // The ports on both sides should be destroyed after timeout. - EXPECT_THAT(webrtc::WaitUntil([&] { return ports_destroyed(); }, Eq(2), - {.clock = &clock}), - webrtc::IsRtcOk()); + EXPECT_THAT( + WaitUntil([&] { return ports_destroyed(); }, Eq(2), {.clock = &clock}), + IsRtcOk()); } TEST_F(PortTest, TestSupportsProtocol) { auto udp_port = CreateUdpPort(kLocalAddr1); - EXPECT_TRUE(udp_port->SupportsProtocol(webrtc::UDP_PROTOCOL_NAME)); - EXPECT_FALSE(udp_port->SupportsProtocol(webrtc::TCP_PROTOCOL_NAME)); + EXPECT_TRUE(udp_port->SupportsProtocol(UDP_PROTOCOL_NAME)); + EXPECT_FALSE(udp_port->SupportsProtocol(TCP_PROTOCOL_NAME)); auto stun_port = CreateStunPort(kLocalAddr1, nat_socket_factory1()); - EXPECT_TRUE(stun_port->SupportsProtocol(webrtc::UDP_PROTOCOL_NAME)); - EXPECT_FALSE(stun_port->SupportsProtocol(webrtc::TCP_PROTOCOL_NAME)); + EXPECT_TRUE(stun_port->SupportsProtocol(UDP_PROTOCOL_NAME)); + EXPECT_FALSE(stun_port->SupportsProtocol(TCP_PROTOCOL_NAME)); auto tcp_port = CreateTcpPort(kLocalAddr1); - EXPECT_TRUE(tcp_port->SupportsProtocol(webrtc::TCP_PROTOCOL_NAME)); - EXPECT_TRUE(tcp_port->SupportsProtocol(webrtc::SSLTCP_PROTOCOL_NAME)); - EXPECT_FALSE(tcp_port->SupportsProtocol(webrtc::UDP_PROTOCOL_NAME)); - - auto turn_port = CreateTurnPort(kLocalAddr1, nat_socket_factory1(), - webrtc::PROTO_UDP, webrtc::PROTO_UDP); - EXPECT_TRUE(turn_port->SupportsProtocol(webrtc::UDP_PROTOCOL_NAME)); - EXPECT_FALSE(turn_port->SupportsProtocol(webrtc::TCP_PROTOCOL_NAME)); + EXPECT_TRUE(tcp_port->SupportsProtocol(TCP_PROTOCOL_NAME)); + EXPECT_TRUE(tcp_port->SupportsProtocol(SSLTCP_PROTOCOL_NAME)); + EXPECT_FALSE(tcp_port->SupportsProtocol(UDP_PROTOCOL_NAME)); + + auto turn_port = + CreateTurnPort(kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP); + EXPECT_TRUE(turn_port->SupportsProtocol(UDP_PROTOCOL_NAME)); + EXPECT_FALSE(turn_port->SupportsProtocol(TCP_PROTOCOL_NAME)); } // Test that SetIceParameters updates the component, ufrag and password @@ -4116,9 +4032,9 @@ class ConnectionTest : public PortTest { ConnectionTest() { lport_ = CreateTestPort(kLocalAddr1, "lfrag", "lpass"); rport_ = CreateTestPort(kLocalAddr2, "rfrag", "rpass"); - lport_->SetIceRole(webrtc::ICEROLE_CONTROLLING); + lport_->SetIceRole(ICEROLE_CONTROLLING); lport_->SetIceTiebreaker(kTiebreaker1); - rport_->SetIceRole(webrtc::ICEROLE_CONTROLLED); + rport_->SetIceRole(ICEROLE_CONTROLLED); rport_->SetIceTiebreaker(kTiebreaker2); lport_->PrepareAddress(); @@ -4130,7 +4046,7 @@ class ConnectionTest : public PortTest { Connection* CreateConnection(IceRole role) { Connection* conn; - if (role == webrtc::ICEROLE_CONTROLLING) { + if (role == ICEROLE_CONTROLLING) { conn = lport_->CreateConnection(rport_->Candidates()[0], Port::ORIGIN_MESSAGE); } else { @@ -4150,20 +4066,18 @@ class ConnectionTest : public PortTest { lconn->PortForTest() == lport_.get() ? lport_.get() : rport_.get(); TestPort* rport = rconn->PortForTest() == rport_.get() ? rport_.get() : lport_.get(); - lconn->Ping(webrtc::TimeMillis()); - ASSERT_THAT( - webrtc::WaitUntil([&] { return lport->last_stun_msg(); }, IsTrue(), + lconn->Ping(TimeMillis()); + ASSERT_THAT(WaitUntil([&] { return lport->last_stun_msg(); }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); ASSERT_GT(lport->last_stun_buf().size(), 0u); rconn->OnReadPacket(ReceivedIpPacket(lport->last_stun_buf(), SocketAddress(), std::nullopt)); clock_.AdvanceTime(TimeDelta::Millis(ms)); - ASSERT_THAT( - webrtc::WaitUntil([&] { return rport->last_stun_msg(); }, IsTrue(), + ASSERT_THAT(WaitUntil([&] { return rport->last_stun_msg(); }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); ASSERT_GT(rport->last_stun_buf().size(), 0u); reply->SetData(rport->last_stun_buf()); } @@ -4184,8 +4098,8 @@ class ConnectionTest : public PortTest { }; TEST_F(ConnectionTest, ConnectionForgetLearnedState) { - Connection* lconn = CreateConnection(webrtc::ICEROLE_CONTROLLING); - Connection* rconn = CreateConnection(webrtc::ICEROLE_CONTROLLED); + Connection* lconn = CreateConnection(ICEROLE_CONTROLLING); + Connection* rconn = CreateConnection(ICEROLE_CONTROLLED); EXPECT_FALSE(lconn->writable()); EXPECT_FALSE(lconn->receiving()); @@ -4219,8 +4133,8 @@ TEST_F(ConnectionTest, ConnectionForgetLearnedState) { } TEST_F(ConnectionTest, ConnectionForgetLearnedStateDiscardsPendingPings) { - Connection* lconn = CreateConnection(webrtc::ICEROLE_CONTROLLING); - Connection* rconn = CreateConnection(webrtc::ICEROLE_CONTROLLED); + Connection* lconn = CreateConnection(ICEROLE_CONTROLLING); + Connection* rconn = CreateConnection(ICEROLE_CONTROLLED); SendPingAndReceiveResponse(lconn, rconn, 10); @@ -4249,8 +4163,8 @@ TEST_F(ConnectionTest, ConnectionForgetLearnedStateDiscardsPendingPings) { } TEST_F(ConnectionTest, ConnectionForgetLearnedStateDoesNotTriggerStateChange) { - Connection* lconn = CreateConnection(webrtc::ICEROLE_CONTROLLING); - Connection* rconn = CreateConnection(webrtc::ICEROLE_CONTROLLED); + Connection* lconn = CreateConnection(ICEROLE_CONTROLLING); + Connection* rconn = CreateConnection(ICEROLE_CONTROLLED); EXPECT_EQ(num_state_changes_, 0); SendPingAndReceiveResponse(lconn, rconn, 10); @@ -4270,8 +4184,8 @@ TEST_F(ConnectionTest, ConnectionForgetLearnedStateDoesNotTriggerStateChange) { // Sending a delta and getting a delta ack in response. TEST_F(ConnectionTest, SendReceiveGoogDelta) { constexpr int64_t ms = 10; - Connection* lconn = CreateConnection(webrtc::ICEROLE_CONTROLLING); - Connection* rconn = CreateConnection(webrtc::ICEROLE_CONTROLLED); + Connection* lconn = CreateConnection(ICEROLE_CONTROLLING); + Connection* rconn = CreateConnection(ICEROLE_CONTROLLED); std::unique_ptr delta = absl::WrapUnique(new StunByteStringAttribute(STUN_ATTR_GOOG_DELTA)); @@ -4285,9 +4199,9 @@ TEST_F(ConnectionTest, SendReceiveGoogDelta) { lconn->SetStunDictConsumer( // DeltaReceived [](const StunByteStringAttribute* delta) - -> std::unique_ptr { return nullptr; }, + -> std::unique_ptr { return nullptr; }, // DeltaAckReceived - [&](webrtc::RTCErrorOr error_or_ack) { + [&](RTCErrorOr error_or_ack) { received_goog_delta_ack = true; EXPECT_TRUE(error_or_ack.ok()); EXPECT_EQ(error_or_ack.value()->value(), 133ull); @@ -4302,24 +4216,21 @@ TEST_F(ConnectionTest, SendReceiveGoogDelta) { return std::move(delta_ack); }, // DeltaAckReceived - [](webrtc::RTCErrorOr error_or__ack) { - }); + [](RTCErrorOr error_or__ack) {}); - lconn->Ping(webrtc::TimeMillis(), std::move(delta)); - ASSERT_THAT( - webrtc::WaitUntil([&] { return lport_->last_stun_msg(); }, IsTrue(), + lconn->Ping(TimeMillis(), std::move(delta)); + ASSERT_THAT(WaitUntil([&] { return lport_->last_stun_msg(); }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); ASSERT_GT(lport_->last_stun_buf().size(), 0u); rconn->OnReadPacket( ReceivedIpPacket(lport_->last_stun_buf(), SocketAddress(), std::nullopt)); EXPECT_TRUE(received_goog_delta); clock_.AdvanceTime(TimeDelta::Millis(ms)); - ASSERT_THAT( - webrtc::WaitUntil([&] { return rport_->last_stun_msg(); }, IsTrue(), + ASSERT_THAT(WaitUntil([&] { return rport_->last_stun_msg(); }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); ASSERT_GT(rport_->last_stun_buf().size(), 0u); lconn->OnReadPacket( ReceivedIpPacket(rport_->last_stun_buf(), SocketAddress(), std::nullopt)); @@ -4331,8 +4242,8 @@ TEST_F(ConnectionTest, SendReceiveGoogDelta) { // a delta ack in reply gives an error callback. TEST_F(ConnectionTest, SendGoogDeltaNoReply) { constexpr int64_t ms = 10; - Connection* lconn = CreateConnection(webrtc::ICEROLE_CONTROLLING); - Connection* rconn = CreateConnection(webrtc::ICEROLE_CONTROLLED); + Connection* lconn = CreateConnection(ICEROLE_CONTROLLING); + Connection* rconn = CreateConnection(ICEROLE_CONTROLLED); std::unique_ptr delta = absl::WrapUnique(new StunByteStringAttribute(STUN_ATTR_GOOG_DELTA)); @@ -4342,27 +4253,25 @@ TEST_F(ConnectionTest, SendGoogDeltaNoReply) { lconn->SetStunDictConsumer( // DeltaReceived [](const StunByteStringAttribute* delta) - -> std::unique_ptr { return nullptr; }, + -> std::unique_ptr { return nullptr; }, // DeltaAckReceived - [&](webrtc::RTCErrorOr error_or_ack) { + [&](RTCErrorOr error_or_ack) { received_goog_delta_ack_error = true; EXPECT_FALSE(error_or_ack.ok()); }); - lconn->Ping(webrtc::TimeMillis(), std::move(delta)); - ASSERT_THAT( - webrtc::WaitUntil([&] { return lport_->last_stun_msg(); }, IsTrue(), + lconn->Ping(TimeMillis(), std::move(delta)); + ASSERT_THAT(WaitUntil([&] { return lport_->last_stun_msg(); }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); ASSERT_GT(lport_->last_stun_buf().size(), 0u); rconn->OnReadPacket( ReceivedIpPacket(lport_->last_stun_buf(), SocketAddress(), std::nullopt)); clock_.AdvanceTime(TimeDelta::Millis(ms)); - ASSERT_THAT( - webrtc::WaitUntil([&] { return rport_->last_stun_msg(); }, IsTrue(), + ASSERT_THAT(WaitUntil([&] { return rport_->last_stun_msg(); }, IsTrue(), {.timeout = TimeDelta::Millis(kDefaultTimeout)}), - webrtc::IsRtcOk()); + IsRtcOk()); ASSERT_GT(rport_->last_stun_buf().size(), 0u); lconn->OnReadPacket( ReceivedIpPacket(rport_->last_stun_buf(), SocketAddress(), std::nullopt)); diff --git a/p2p/base/pseudo_tcp.cc b/p2p/base/pseudo_tcp.cc index 8564afe9a0..a3e336e199 100644 --- a/p2p/base/pseudo_tcp.cc +++ b/p2p/base/pseudo_tcp.cc @@ -203,7 +203,7 @@ void ReportStats() { uint32_t PseudoTcp::Now() { #if 0 // Use this to synchronize timers with logging timestamps (easier debug) - return static_cast(webrtc::TimeSince(StartTime())); + return static_cast(TimeSince(StartTime())); #else return Time32(); #endif @@ -625,10 +625,9 @@ bool PseudoTcp::clock_check(uint32_t now, long& nTimeout) { #if PSEUDO_KEEPALIVE if (m_state == TCP_ESTABLISHED) { nTimeout = std::min( - nTimeout, - webrtc::TimeDiff32( - m_lasttraffic + (m_bOutgoing ? IDLE_PING * 3 / 2 : IDLE_PING), - now)); + nTimeout, TimeDiff32(m_lasttraffic + + (m_bOutgoing ? IDLE_PING * 3 / 2 : IDLE_PING), + now)); } #endif // PSEUDO_KEEPALIVE return true; diff --git a/p2p/base/pseudo_tcp_unittest.cc b/p2p/base/pseudo_tcp_unittest.cc index cdb794a2ba..7d5400f2ed 100644 --- a/p2p/base/pseudo_tcp_unittest.cc +++ b/p2p/base/pseudo_tcp_unittest.cc @@ -72,7 +72,7 @@ class PseudoTcpTestBase : public ::testing::Test, // this test would occasionally get really unlucky loss and time out. webrtc::SetRandomTestMode(true); } - ~PseudoTcpTestBase() { + ~PseudoTcpTestBase() override { // Put it back for the next test. webrtc::SetRandomTestMode(false); } @@ -133,7 +133,7 @@ class PseudoTcpTestBase : public ::testing::Test, UpdateLocalClock(); } - virtual void OnTcpOpen(PseudoTcp* tcp) { + void OnTcpOpen(PseudoTcp* tcp) override { // Consider ourselves connected when the local side gets OnTcpOpen. // OnTcpWriteable isn't fired at open, so we trigger it now. RTC_LOG(LS_VERBOSE) << "Opened"; @@ -146,7 +146,7 @@ class PseudoTcpTestBase : public ::testing::Test, // virtual void OnTcpReadable(PseudoTcp* tcp) // and // virtual void OnTcpWritable(PseudoTcp* tcp) - virtual void OnTcpClosed(PseudoTcp* tcp, uint32_t error) { + void OnTcpClosed(PseudoTcp* tcp, uint32_t error) override { // Consider ourselves closed when the remote side gets OnTcpClosed. // TODO(?): OnTcpClosed is only ever notified in case of error in // the current implementation. Solicited close is not (yet) supported. @@ -156,9 +156,9 @@ class PseudoTcpTestBase : public ::testing::Test, have_disconnected_ = true; } } - virtual WriteResult TcpWritePacket(PseudoTcp* tcp, - const char* buffer, - size_t len) { + WriteResult TcpWritePacket(PseudoTcp* tcp, + const char* buffer, + size_t len) override { // Drop a packet if the test called DropNextPacket. if (drop_next_packet_) { drop_next_packet_ = false; @@ -278,7 +278,7 @@ class PseudoTcpTest : public PseudoTcpTestBase { private: // IPseudoTcpNotify interface - virtual void OnTcpReadable(PseudoTcp* tcp) { + void OnTcpReadable(PseudoTcp* tcp) override { // Stream bytes to the recv stream as they arrive. if (tcp == &remote_) { ReadData(); @@ -293,7 +293,7 @@ class PseudoTcpTest : public PseudoTcpTestBase { OnTcpClosed(&remote_, 0); } } - virtual void OnTcpWriteable(PseudoTcp* tcp) { + void OnTcpWriteable(PseudoTcp* tcp) override { // Write bytes from the send stream when we can. // Shut down when we've sent everything. if (tcp == &local_) { @@ -399,7 +399,7 @@ class PseudoTcpTestPingPong : public PseudoTcpTestBase { private: // IPseudoTcpNotify interface - virtual void OnTcpReadable(PseudoTcp* tcp) { + void OnTcpReadable(PseudoTcp* tcp) override { if (tcp != receiver_) { RTC_LOG_F(LS_ERROR) << "unexpected OnTcpReadable"; return; @@ -426,7 +426,7 @@ class PseudoTcpTestPingPong : public PseudoTcpTestBase { OnTcpWriteable(sender_); } } - virtual void OnTcpWriteable(PseudoTcp* tcp) { + void OnTcpWriteable(PseudoTcp* tcp) override { if (tcp != sender_) return; // Write bytes from the send stream when we can. @@ -545,9 +545,9 @@ class PseudoTcpTestReceiveWindow : public PseudoTcpTestBase { private: // IPseudoTcpNotify interface - virtual void OnTcpReadable(PseudoTcp* /* tcp */) {} + void OnTcpReadable(PseudoTcp* /* tcp */) override {} - virtual void OnTcpWriteable(PseudoTcp* /* tcp */) {} + void OnTcpWriteable(PseudoTcp* /* tcp */) override {} void ReadUntilIOPending() { char block[kBlockSize]; diff --git a/p2p/base/stun_port.cc b/p2p/base/stun_port.cc index f5df2d830c..d87ed42abb 100644 --- a/p2p/base/stun_port.cc +++ b/p2p/base/stun_port.cc @@ -43,6 +43,7 @@ #include "rtc_base/socket_address.h" #include "rtc_base/strings/string_builder.h" #include "rtc_base/time_utils.h" +#include "system_wrappers/include/metrics.h" namespace webrtc { @@ -471,23 +472,30 @@ void UDPPort::OnResolveResult(const SocketAddress& input, int error) { void UDPPort::SendStunBindingRequest(const SocketAddress& stun_addr) { if (stun_addr.IsUnresolvedIP()) { ResolveStunAddress(stun_addr); + return; + } + + if (socket_->GetState() != AsyncPacketSocket::STATE_BOUND) { + return; + } - } else if (socket_->GetState() == AsyncPacketSocket::STATE_BOUND) { // Check if `server_addr_` is compatible with the port's ip. - if (IsCompatibleAddress(stun_addr)) { - request_manager_.Send( - new StunBindingRequest(this, stun_addr, TimeMillis())); - } else { - // Since we can't send stun messages to the server, we should mark this - // port ready. This is not an error but similar to ignoring - // a mismatch of th address family when pairing candidates. - RTC_LOG(LS_WARNING) << ToString() - << ": STUN server address is incompatible."; - OnStunBindingOrResolveRequestFailed( - stun_addr, STUN_ERROR_NOT_AN_ERROR, - "STUN server address is incompatible."); - } + if (!IsCompatibleAddress(stun_addr)) { + // Since we can't send stun messages to the server, we should mark this + // port ready. This is not an error but similar to ignoring + // a mismatch of the address family when pairing candidates. + RTC_LOG(LS_WARNING) << ToString() + << ": STUN server address is incompatible."; + OnStunBindingOrResolveRequestFailed(stun_addr, STUN_ERROR_NOT_AN_ERROR, + "STUN server address is incompatible."); + return; } + + RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.Stun.ServerAddressType", + static_cast(stun_addr.GetIPAddressType()), + static_cast(IPAddressType::kMaxValue)); + + request_manager_.Send(new StunBindingRequest(this, stun_addr, TimeMillis())); } bool UDPPort::MaybeSetDefaultLocalAddress(SocketAddress* addr) const { diff --git a/p2p/base/stun_port.h b/p2p/base/stun_port.h index 612ee0f8b3..c04e9a18c8 100644 --- a/p2p/base/stun_port.h +++ b/p2p/base/stun_port.h @@ -162,7 +162,7 @@ class RTC_EXPORT UDPPort : public Port { private: // A helper class which can be called repeatedly to resolve multiple - // addresses, as opposed to webrtc::AsyncDnsResolverInterface, which can only + // addresses, as opposed to AsyncDnsResolverInterface, which can only // resolve one address per instance. class AddressResolver { public: @@ -212,7 +212,7 @@ class RTC_EXPORT UDPPort : public Port { // Sends STUN requests to the server. void OnSendPacket(const void* data, size_t size, StunRequest* req); - // TODO(mallinaht): Move this up to webrtc::Port when SignalAddressReady is + // TODO(mallinaht): Move this up to Port when SignalAddressReady is // changed to SignalPortReady. void MaybeSetPortCompleteOrError(); @@ -222,7 +222,7 @@ class RTC_EXPORT UDPPort : public Port { // requests indefinitely to keep the NAT binding alive. Otherwise, stop // sending STUN binding requests after HIGH_COST_PORT_KEEPALIVE_LIFETIME. int GetStunKeepaliveLifetime() { - return (network_cost() >= webrtc::kNetworkCostHigh) + return (network_cost() >= kNetworkCostHigh) ? HIGH_COST_PORT_KEEPALIVE_LIFETIME : INFINITE_LIFETIME; } diff --git a/p2p/base/stun_port_unittest.cc b/p2p/base/stun_port_unittest.cc index 809c435b78..e59dd92bee 100644 --- a/p2p/base/stun_port_unittest.cc +++ b/p2p/base/stun_port_unittest.cc @@ -19,6 +19,7 @@ #include #include "absl/functional/any_invocable.h" +#include "absl/strings/string_view.h" #include "api/candidate.h" #include "api/environment/environment_factory.h" #include "api/field_trials_view.h" @@ -54,6 +55,7 @@ #include "rtc_base/third_party/sigslot/sigslot.h" #include "rtc_base/thread.h" #include "rtc_base/virtual_socket_server.h" +#include "system_wrappers/include/metrics.h" #include "test/gmock.h" #include "test/gtest.h" #include "test/scoped_key_value_config.h" @@ -73,39 +75,45 @@ using ::webrtc::IceCandidateType; using ::webrtc::ServerAddresses; using ::webrtc::SocketAddress; -static const SocketAddress kPrivateIP("192.168.1.12", 0); -static const SocketAddress kMsdnAddress("unittest-mdns-host-name.local", 0); -static const SocketAddress kPublicIP("212.116.91.133", 0); -static const SocketAddress kNatAddr(kPublicIP.ipaddr(), - webrtc::NAT_SERVER_UDP_PORT); -static const SocketAddress kStunServerAddr1("34.38.54.120", 5000); -static const SocketAddress kStunServerAddr2("34.38.54.120", 4000); - -static const SocketAddress kPrivateIPv6("2001:4860:4860::8844", 0); -static const SocketAddress kPublicIPv6("2002:4860:4860::8844", 5000); -static const SocketAddress kNatAddrIPv6(kPublicIPv6.ipaddr(), - webrtc::NAT_SERVER_UDP_PORT); -static const SocketAddress kStunServerAddrIPv6Addr("2003:4860:4860::8844", - 5000); - -static const SocketAddress kBadAddr("0.0.0.1", 5000); -static const SocketAddress kIPv6BadAddr("::ffff:0:1", 5000); -static const SocketAddress kValidHostnameAddr("valid-hostname", 5000); -static const SocketAddress kBadHostnameAddr("not-a-real-hostname", 5000); +const SocketAddress kPrivateIP("192.168.1.12", 0); +const SocketAddress kMsdnAddress("unittest-mdns-host-name.local", 0); +const SocketAddress kPublicIP("212.116.91.133", 0); +const SocketAddress kNatAddr(kPublicIP.ipaddr(), webrtc::NAT_SERVER_UDP_PORT); +const SocketAddress kStunServerAddr1("34.38.54.120", 5000); +const SocketAddress kStunServerAddr2("34.38.54.120", 4000); + +const SocketAddress kPrivateIPv6("2001:4860:4860::8844", 0); +const SocketAddress kPublicIPv6("2002:4860:4860::8844", 5000); +const SocketAddress kNatAddrIPv6(kPublicIPv6.ipaddr(), + webrtc::NAT_SERVER_UDP_PORT); +const SocketAddress kStunServerAddrIPv6Addr("2003:4860:4860::8844", 5000); + +const SocketAddress kBadAddr("0.0.0.1", 5000); +const SocketAddress kIPv6BadAddr("::ffff:0:1", 5000); +const SocketAddress kValidHostnameAddr("valid-hostname", 5000); +const SocketAddress kBadHostnameAddr("not-a-real-hostname", 5000); // STUN timeout (with all retries) is webrtc::STUN_TOTAL_TIMEOUT. // Add some margin of error for slow bots. -static const int kTimeoutMs = webrtc::STUN_TOTAL_TIMEOUT; +const int kTimeoutMs = webrtc::STUN_TOTAL_TIMEOUT; // stun prio = 100 (srflx) << 24 | 30 (IPv4) << 8 | 256 - 1 (component) -static const uint32_t kStunCandidatePriority = - (100 << 24) | (30 << 8) | (256 - 1); +const uint32_t kStunCandidatePriority = (100 << 24) | (30 << 8) | (256 - 1); // stun prio = 100 (srflx) << 24 | 40 (IPv6) << 8 | 256 - 1 (component) -static const uint32_t kIPv6StunCandidatePriority = - (100 << 24) | (40 << 8) | (256 - 1); -static const int kInfiniteLifetime = -1; -static const int kHighCostPortKeepaliveLifetimeMs = 2 * 60 * 1000; +const uint32_t kIPv6StunCandidatePriority = (100 << 24) | (40 << 8) | (256 - 1); +const int kInfiniteLifetime = -1; +const int kHighCostPortKeepaliveLifetimeMs = 2 * 60 * 1000; constexpr uint64_t kTiebreakerDefault = 44444; +struct IPAddressTypeTestConfig { + absl::string_view address; + webrtc::IPAddressType address_type; +}; + +// Used by the test framework to print the param value for parameterized tests. +std::string PrintToString(const IPAddressTypeTestConfig& param) { + return std::string(param.address); +} + class FakeMdnsResponder : public webrtc::MdnsResponderInterface { public: void CreateNameForAddress(const webrtc::IPAddress& addr, @@ -717,9 +725,58 @@ TEST_F(StunPortTest, TestStunBindingRequestLongLifetime) { webrtc::IsRtcOk()); } +class StunPortIPAddressTypeMetricsTest + : public StunPortWithMockDnsResolverTest, + public ::testing::WithParamInterface {}; + +TEST_P(StunPortIPAddressTypeMetricsTest, TestIPAddressTypeMetrics) { + SetDnsResolverExpectations( + [](webrtc::MockAsyncDnsResolver* resolver, + webrtc::MockAsyncDnsResolverResult* resolver_result) { + EXPECT_CALL(*resolver, Start(SocketAddress("localhost", 5000), + /*family=*/AF_INET, _)) + .WillOnce([](const webrtc::SocketAddress& /* addr */, + int /* family */, + absl::AnyInvocable callback) { callback(); }); + + EXPECT_CALL(*resolver, result) + .WillRepeatedly(ReturnPointee(resolver_result)); + EXPECT_CALL(*resolver_result, GetError).WillOnce(Return(0)); + EXPECT_CALL(*resolver_result, GetResolvedAddress(AF_INET, _)) + .WillOnce(DoAll(SetArgPointee<1>(SocketAddress("127.0.0.1", 5000)), + Return(true))); + }); + + webrtc::metrics::Reset(); + + CreateStunPort({GetParam().address, 5000}); + PrepareAddress(); + EXPECT_THAT( + webrtc::WaitUntil([&] { return done(); }, IsTrue(), + {.timeout = webrtc::TimeDelta::Millis(kTimeoutMs), + .clock = &fake_clock}), + webrtc::IsRtcOk()); + + auto samples = + webrtc::metrics::Samples("WebRTC.PeerConnection.Stun.ServerAddressType"); + ASSERT_EQ(samples.size(), 1u); + EXPECT_EQ(samples[static_cast(GetParam().address_type)], 1); +} + +const IPAddressTypeTestConfig kAllIPAddressTypeTestConfigs[] = { + {"127.0.0.1", webrtc::IPAddressType::kLoopback}, + {"localhost", webrtc::IPAddressType::kLoopback}, + {"10.0.0.3", webrtc::IPAddressType::kPrivate}, + {"1.1.1.1", webrtc::IPAddressType::kPublic}, +}; + +INSTANTIATE_TEST_SUITE_P(All, + StunPortIPAddressTypeMetricsTest, + ::testing::ValuesIn(kAllIPAddressTypeTestConfigs)); + class MockAsyncPacketSocket : public webrtc::AsyncPacketSocket { public: - ~MockAsyncPacketSocket() = default; + ~MockAsyncPacketSocket() override = default; MOCK_METHOD(SocketAddress, GetLocalAddress, (), (const, override)); MOCK_METHOD(SocketAddress, GetRemoteAddress, (), (const, override)); @@ -944,4 +1001,35 @@ TEST_F(StunIPv6PortTestWithMockDnsResolver, port()->Candidates()[0].priority()); } +class StunIPv6PortIPAddressTypeMetricsTest + : public StunIPv6PortTestWithMockDnsResolver, + public ::testing::WithParamInterface {}; + +TEST_P(StunIPv6PortIPAddressTypeMetricsTest, TestIPAddressTypeMetrics) { + webrtc::metrics::Reset(); + + CreateStunPort({GetParam().address, 5000}); + PrepareAddress(); + EXPECT_THAT( + webrtc::WaitUntil([&] { return done(); }, IsTrue(), + {.timeout = webrtc::TimeDelta::Millis(kTimeoutMs), + .clock = &fake_clock}), + webrtc::IsRtcOk()); + + auto samples = + webrtc::metrics::Samples("WebRTC.PeerConnection.Stun.ServerAddressType"); + ASSERT_EQ(samples.size(), 1u); + EXPECT_EQ(samples[static_cast(GetParam().address_type)], 1); +} + +const IPAddressTypeTestConfig kAllIPv6AddressTypeTestConfigs[] = { + {"::1", webrtc::IPAddressType::kLoopback}, + {"fd00:4860:4860::8844", webrtc::IPAddressType::kPrivate}, + {"2001:4860:4860::8888", webrtc::IPAddressType::kPublic}, +}; + +INSTANTIATE_TEST_SUITE_P(All, + StunIPv6PortIPAddressTypeMetricsTest, + ::testing::ValuesIn(kAllIPv6AddressTypeTestConfigs)); + } // namespace diff --git a/p2p/base/stun_request.h b/p2p/base/stun_request.h index 9c10e40a78..22a252ecc1 100644 --- a/p2p/base/stun_request.h +++ b/p2p/base/stun_request.h @@ -42,8 +42,7 @@ class StunRequestManager { public: StunRequestManager( TaskQueueBase* thread, - std::function - send_packet); + std::function send_packet); ~StunRequestManager(); // Starts sending the given request (perhaps after a delay). @@ -85,8 +84,7 @@ class StunRequestManager { TaskQueueBase* const thread_; RequestMap requests_ RTC_GUARDED_BY(thread_); - const std::function - send_packet_; + const std::function send_packet_; }; // Represents an individual request to be sent. The STUN message can either be diff --git a/p2p/base/stun_request_unittest.cc b/p2p/base/stun_request_unittest.cc index 945d29b82e..ec3bb747fc 100644 --- a/p2p/base/stun_request_unittest.cc +++ b/p2p/base/stun_request_unittest.cc @@ -98,11 +98,11 @@ class StunRequestThunker : public StunRequest { } private: - virtual void OnResponse(StunMessage* res) { test_->OnResponse(res); } - virtual void OnErrorResponse(StunMessage* res) { + void OnResponse(StunMessage* res) override { test_->OnResponse(res); } + void OnErrorResponse(StunMessage* res) override { test_->OnErrorResponse(res); } - virtual void OnTimeout() { test_->OnTimeout(); } + void OnTimeout() override { test_->OnTimeout(); } StunRequestTest* test_; }; diff --git a/p2p/base/tcp_port.h b/p2p/base/tcp_port.h index 3f82c9d79d..6ea517abe6 100644 --- a/p2p/base/tcp_port.h +++ b/p2p/base/tcp_port.h @@ -174,7 +174,7 @@ class TCPConnection : public Connection, public sigslot::has_slots<> { void OnDestroyed(Connection* c); TCPPort* tcp_port() { - RTC_DCHECK_EQ(port()->GetProtocol(), webrtc::PROTO_TCP); + RTC_DCHECK_EQ(port()->GetProtocol(), PROTO_TCP); return static_cast(port()); } diff --git a/p2p/base/tcp_port_unittest.cc b/p2p/base/tcp_port_unittest.cc index a5e7982bbf..d2437f5a8f 100644 --- a/p2p/base/tcp_port_unittest.cc +++ b/p2p/base/tcp_port_unittest.cc @@ -70,7 +70,7 @@ class ConnectionObserver : public sigslot::has_slots<> { conn->SignalDestroyed.connect(this, &ConnectionObserver::OnDestroyed); } - ~ConnectionObserver() { + ~ConnectionObserver() override { if (!connection_destroyed_) { RTC_DCHECK(conn_); conn_->SignalDestroyed.disconnect(this); diff --git a/p2p/base/turn_port.cc b/p2p/base/turn_port.cc index 9395fe5ee9..01580b8bf7 100644 --- a/p2p/base/turn_port.cc +++ b/p2p/base/turn_port.cc @@ -56,6 +56,7 @@ #include "rtc_base/string_encode.h" #include "rtc_base/strings/string_builder.h" #include "rtc_base/third_party/sigslot/sigslot.h" +#include "system_wrappers/include/metrics.h" namespace webrtc { @@ -168,7 +169,7 @@ class TurnEntry : public sigslot::has_slots<> { public: enum BindState { STATE_UNBOUND, STATE_BINDING, STATE_BOUND }; TurnEntry(TurnPort* port, Connection* conn, int channel_id); - ~TurnEntry(); + ~TurnEntry() override; TurnPort* port() { return port_; } @@ -369,39 +370,45 @@ void TurnPort::PrepareAddress() { "Attempt to start allocation to a disallowed port"); return; } + if (server_address_.address.IsUnresolvedIP()) { ResolveTurnAddress(server_address_.address); - } else { - // If protocol family of server address doesn't match with local, return. - if (!IsCompatibleAddress(server_address_.address)) { - RTC_LOG(LS_ERROR) << ToString() - << ": IP address family does not match. Server: " - << server_address_.address.family() - << " local: " << Network()->GetBestIP().family(); - OnAllocateError(STUN_ERROR_NOT_AN_ERROR, - "TURN server address is incompatible."); - return; - } + return; + } - // Insert the current address to prevent redirection pingpong. - attempted_server_addresses_.insert(server_address_.address); + // If protocol family of server address doesn't match with local, return. + if (!IsCompatibleAddress(server_address_.address)) { + RTC_LOG(LS_ERROR) << ToString() + << ": IP address family does not match. Server: " + << server_address_.address.family() + << " local: " << Network()->GetBestIP().family(); + OnAllocateError(STUN_ERROR_NOT_AN_ERROR, + "TURN server address is incompatible."); + return; + } - RTC_LOG(LS_INFO) - << ToString() << ": Trying to connect to TURN server via " - << ProtoToString(server_address_.proto) << " @ " - << server_address_.address.ToSensitiveNameAndAddressString(); - if (!CreateTurnClientSocket()) { - RTC_LOG(LS_ERROR) << ToString() - << ": Failed to create TURN client socket"; - OnAllocateError(STUN_ERROR_SERVER_NOT_REACHABLE, - "Failed to create TURN client socket."); - return; - } - if (server_address_.proto == PROTO_UDP) { - // If its UDP, send AllocateRequest now. - // For TCP and TLS AllcateRequest will be sent by OnSocketConnect. - SendRequest(new TurnAllocateRequest(this), 0); - } + RTC_HISTOGRAM_ENUMERATION( + "WebRTC.PeerConnection.Turn.ServerAddressType", + static_cast(server_address_.address.GetIPAddressType()), + static_cast(IPAddressType::kMaxValue)); + + // Insert the current address to prevent redirection pingpong. + attempted_server_addresses_.insert(server_address_.address); + + RTC_LOG(LS_INFO) << ToString() << ": Trying to connect to TURN server via " + << ProtoToString(server_address_.proto) << " @ " + << server_address_.address.ToSensitiveNameAndAddressString(); + if (!CreateTurnClientSocket()) { + RTC_LOG(LS_ERROR) << ToString() << ": Failed to create TURN client socket"; + OnAllocateError(STUN_ERROR_SERVER_NOT_REACHABLE, + "Failed to create TURN client socket."); + return; + } + + if (server_address_.proto == PROTO_UDP) { + // If its UDP, send AllocateRequest now. + // For TCP and TLS AllcateRequest will be sent by OnSocketConnect. + SendRequest(new TurnAllocateRequest(this), 0); } } diff --git a/p2p/base/turn_port_unittest.cc b/p2p/base/turn_port_unittest.cc index d8f4505665..c5da027d43 100644 --- a/p2p/base/turn_port_unittest.cc +++ b/p2p/base/turn_port_unittest.cc @@ -31,10 +31,11 @@ #include "rtc_base/network.h" #include "rtc_base/network/received_packet.h" #include "rtc_base/third_party/sigslot/sigslot.h" +#include "system_wrappers/include/metrics.h" #include "test/gmock.h" #include "test/wait_until.h" #if defined(WEBRTC_POSIX) -#include +#include // IWYU pragma: keep #include "absl/strings/string_view.h" #endif @@ -84,82 +85,76 @@ using ::webrtc::Environment; using ::webrtc::IceCandidateType; using ::webrtc::SocketAddress; -static const SocketAddress kLocalAddr1("11.11.11.11", 0); -static const SocketAddress kLocalAddr2("22.22.22.22", 0); -static const SocketAddress kLocalIPv6Addr("2401:fa00:4:1000:be30:5bff:fee5:c3", - 0); -static const SocketAddress kLocalIPv6Addr2("2401:fa00:4:2000:be30:5bff:fee5:d4", - 0); -static const SocketAddress kTurnUdpIntAddr("99.99.99.3", - webrtc::TURN_SERVER_PORT); -static const SocketAddress kTurnTcpIntAddr("99.99.99.4", - webrtc::TURN_SERVER_PORT); -static const SocketAddress kTurnUdpExtAddr("99.99.99.5", 0); -static const SocketAddress kTurnAlternateIntAddr("99.99.99.6", - webrtc::TURN_SERVER_PORT); +const SocketAddress kLocalAddr1("11.11.11.11", 0); +const SocketAddress kLocalAddr2("22.22.22.22", 0); +const SocketAddress kLocalIPv6Addr("2401:fa00:4:1000:be30:5bff:fee5:c3", 0); +const SocketAddress kLocalIPv6Addr2("2401:fa00:4:2000:be30:5bff:fee5:d4", 0); +const SocketAddress kTurnUdpIntAddr("99.99.99.3", webrtc::TURN_SERVER_PORT); +const SocketAddress kTurnTcpIntAddr("99.99.99.4", webrtc::TURN_SERVER_PORT); +const SocketAddress kTurnUdpExtAddr("99.99.99.5", 0); +const SocketAddress kTurnAlternateIntAddr("99.99.99.6", + webrtc::TURN_SERVER_PORT); // Port for redirecting to a TCP Web server. Should not work. -static const SocketAddress kTurnDangerousAddr("99.99.99.7", 81); +const SocketAddress kTurnDangerousAddr("99.99.99.7", 81); // Port 53 (the DNS port); should work. -static const SocketAddress kTurnPort53Addr("99.99.99.7", 53); +const SocketAddress kTurnPort53Addr("99.99.99.7", 53); // Port 80 (the HTTP port); should work. -static const SocketAddress kTurnPort80Addr("99.99.99.7", 80); +const SocketAddress kTurnPort80Addr("99.99.99.7", 80); // Port 443 (the HTTPS port); should work. -static const SocketAddress kTurnPort443Addr("99.99.99.7", 443); +const SocketAddress kTurnPort443Addr("99.99.99.7", 443); // The default TURN server port. -static const SocketAddress kTurnIntAddr("99.99.99.7", webrtc::TURN_SERVER_PORT); -static const SocketAddress kTurnIPv6IntAddr( - "2400:4030:2:2c00:be30:abcd:efab:cdef", - webrtc::TURN_SERVER_PORT); -static const SocketAddress kTurnUdpIPv6IntAddr( - "2400:4030:1:2c00:be30:abcd:efab:cdef", - webrtc::TURN_SERVER_PORT); -static const SocketAddress kTurnInvalidAddr("www.google.invalid.", 3478); -static const SocketAddress kTurnValidAddr("www.google.valid.", 3478); - -static const char kCandidateFoundation[] = "foundation"; -static const char kIceUfrag1[] = "TESTICEUFRAG0001"; -static const char kIceUfrag2[] = "TESTICEUFRAG0002"; -static const char kIcePwd1[] = "TESTICEPWD00000000000001"; -static const char kIcePwd2[] = "TESTICEPWD00000000000002"; -static const char kTurnUsername[] = "test"; -static const char kTurnPassword[] = "test"; +const SocketAddress kTurnIntAddr("99.99.99.7", webrtc::TURN_SERVER_PORT); +const SocketAddress kTurnIPv6IntAddr("2400:4030:2:2c00:be30:abcd:efab:cdef", + webrtc::TURN_SERVER_PORT); +const SocketAddress kTurnUdpIPv6IntAddr("2400:4030:1:2c00:be30:abcd:efab:cdef", + webrtc::TURN_SERVER_PORT); +const SocketAddress kTurnInvalidAddr("www.google.invalid.", 3478); +const SocketAddress kTurnValidAddr("www.google.valid.", 3478); + +const char kCandidateFoundation[] = "foundation"; +const char kIceUfrag1[] = "TESTICEUFRAG0001"; +const char kIceUfrag2[] = "TESTICEUFRAG0002"; +const char kIcePwd1[] = "TESTICEPWD00000000000001"; +const char kIcePwd2[] = "TESTICEPWD00000000000002"; +const char kTurnUsername[] = "test"; +const char kTurnPassword[] = "test"; // This test configures the virtual socket server to simulate delay so that we // can verify operations take no more than the expected number of round trips. -static constexpr unsigned int kSimulatedRtt = 50; +constexpr unsigned int kSimulatedRtt = 50; // Connection destruction may happen asynchronously, but it should only // take one simulated clock tick. -static constexpr unsigned int kConnectionDestructionDelay = 1; +constexpr unsigned int kConnectionDestructionDelay = 1; // This used to be 1 second, but that's not always enough for getaddrinfo(). // See: https://bugs.chromium.org/p/webrtc/issues/detail?id=5191 -static constexpr unsigned int kResolverTimeout = 10000; +constexpr unsigned int kResolverTimeout = 10000; constexpr uint64_t kTiebreakerDefault = 44444; -static const webrtc::ProtocolAddress kTurnUdpProtoAddr(kTurnUdpIntAddr, - webrtc::PROTO_UDP); -static const webrtc::ProtocolAddress kTurnTcpProtoAddr(kTurnTcpIntAddr, - webrtc::PROTO_TCP); -static const webrtc::ProtocolAddress kTurnTlsProtoAddr(kTurnTcpIntAddr, - webrtc::PROTO_TLS); -static const webrtc::ProtocolAddress kTurnUdpIPv6ProtoAddr(kTurnUdpIPv6IntAddr, - webrtc::PROTO_UDP); -static const webrtc::ProtocolAddress kTurnDangerousProtoAddr(kTurnDangerousAddr, - webrtc::PROTO_TCP); -static const webrtc::ProtocolAddress kTurnPort53ProtoAddr(kTurnPort53Addr, - webrtc::PROTO_TCP); -static const webrtc::ProtocolAddress kTurnPort80ProtoAddr(kTurnPort80Addr, - webrtc::PROTO_TCP); -static const webrtc::ProtocolAddress kTurnPort443ProtoAddr(kTurnPort443Addr, - webrtc::PROTO_TCP); -static const webrtc::ProtocolAddress kTurnPortInvalidHostnameProtoAddr( +const webrtc::ProtocolAddress kTurnUdpProtoAddr(kTurnUdpIntAddr, + webrtc::PROTO_UDP); +const webrtc::ProtocolAddress kTurnTcpProtoAddr(kTurnTcpIntAddr, + webrtc::PROTO_TCP); +const webrtc::ProtocolAddress kTurnTlsProtoAddr(kTurnTcpIntAddr, + webrtc::PROTO_TLS); +const webrtc::ProtocolAddress kTurnUdpIPv6ProtoAddr(kTurnUdpIPv6IntAddr, + webrtc::PROTO_UDP); +const webrtc::ProtocolAddress kTurnDangerousProtoAddr(kTurnDangerousAddr, + webrtc::PROTO_TCP); +const webrtc::ProtocolAddress kTurnPort53ProtoAddr(kTurnPort53Addr, + webrtc::PROTO_TCP); +const webrtc::ProtocolAddress kTurnPort80ProtoAddr(kTurnPort80Addr, + webrtc::PROTO_TCP); +const webrtc::ProtocolAddress kTurnPort443ProtoAddr(kTurnPort443Addr, + webrtc::PROTO_TCP); +const webrtc::ProtocolAddress kTurnPortInvalidHostnameProtoAddr( kTurnInvalidAddr, webrtc::PROTO_UDP); -static const webrtc::ProtocolAddress kTurnPortValidHostnameProtoAddr( +const webrtc::ProtocolAddress kTurnPortValidHostnameProtoAddr( kTurnValidAddr, webrtc::PROTO_UDP); #if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID) -static int GetFDCount() { +int GetFDCount() { struct dirent* dp; int fd_count = 0; DIR* dir = opendir("/proc/self/fd/"); @@ -196,7 +191,7 @@ class TestConnectionWrapper : public sigslot::has_slots<> { this, &TestConnectionWrapper::OnConnectionDestroyed); } - ~TestConnectionWrapper() { + ~TestConnectionWrapper() override { if (connection_) { connection_->SignalDestroyed.disconnect(this); } @@ -1008,7 +1003,7 @@ class TurnLoggingIdValidator : public StunMessageObserver { public: explicit TurnLoggingIdValidator(const char* expect_val) : expect_val_(expect_val) {} - ~TurnLoggingIdValidator() {} + ~TurnLoggingIdValidator() override {} void ReceivedMessage(const TurnMessage* msg) override { if (msg->type() == STUN_ALLOCATE_REQUEST) { const StunByteStringAttribute* attr = @@ -1187,7 +1182,7 @@ TEST_F(TurnPortTest, TurnTcpAllocationNotDiscardedIfNotBoundToBestIP) { } // Regression test for crbug.com/webrtc/8972, caused by buggy comparison -// between webrtc::IPAddress and webrtc::InterfaceAddress. +// between IPAddress and InterfaceAddress. TEST_F(TurnPortTest, TCPPortNotDiscardedIfBoundToTemporaryIP) { networks_.emplace_back("unittest", "unittest", kLocalIPv6Addr.ipaddr(), 32); networks_.back().AddIP( @@ -1939,7 +1934,7 @@ class MessageObserver : public StunMessageObserver { : message_counter_(message_counter), channel_data_counter_(channel_data_counter), attr_counter_(attr_counter) {} - virtual ~MessageObserver() {} + ~MessageObserver() override {} void ReceivedMessage(const TurnMessage* msg) override { if (message_counter_ != nullptr) { (*message_counter_)++; @@ -2146,10 +2141,10 @@ class TurnPortWithMockDnsResolverTest : public TurnPortTest { TEST_F(TurnPortWithMockDnsResolverTest, TestHostnameResolved) { CreateTurnPort(kTurnUsername, kTurnPassword, kTurnPortValidHostnameProtoAddr); SetDnsResolverExpectations( - [](webrtc::MockAsyncDnsResolver* resolver, - webrtc::MockAsyncDnsResolverResult* resolver_result) { + [](MockAsyncDnsResolver* resolver, + MockAsyncDnsResolverResult* resolver_result) { EXPECT_CALL(*resolver, Start(kTurnValidAddr, /*family=*/AF_INET, _)) - .WillOnce([](const webrtc::SocketAddress& addr, int family, + .WillOnce([](const SocketAddress& addr, int family, absl::AnyInvocable callback) { callback(); }); EXPECT_CALL(*resolver, result) .WillRepeatedly(ReturnPointee(resolver_result)); @@ -2167,10 +2162,10 @@ TEST_F(TurnPortWithMockDnsResolverTest, TestHostnameResolvedIPv6Network) { CreateTurnPort(kLocalIPv6Addr, kTurnUsername, kTurnPassword, kTurnPortValidHostnameProtoAddr); SetDnsResolverExpectations( - [](webrtc::MockAsyncDnsResolver* resolver, - webrtc::MockAsyncDnsResolverResult* resolver_result) { + [](MockAsyncDnsResolver* resolver, + MockAsyncDnsResolverResult* resolver_result) { EXPECT_CALL(*resolver, Start(kTurnValidAddr, /*family=*/AF_INET6, _)) - .WillOnce([](const webrtc::SocketAddress& addr, int family, + .WillOnce([](const SocketAddress& addr, int family, absl::AnyInvocable callback) { callback(); }); EXPECT_CALL(*resolver, result) .WillRepeatedly(ReturnPointee(resolver_result)); @@ -2182,4 +2177,65 @@ TEST_F(TurnPortWithMockDnsResolverTest, TestHostnameResolvedIPv6Network) { TestTurnAllocateSucceeds(kSimulatedRtt * 2); } +static struct IPAddressTypeTestConfig { + absl::string_view address; + IPAddressType address_type; +} kAllIPAddressTypeTestConfigs[] = { + {"127.0.0.1", IPAddressType::kLoopback}, + {"localhost", IPAddressType::kLoopback}, + {"::1", IPAddressType::kLoopback}, + {"10.0.0.3", IPAddressType::kPrivate}, + {"fd00:4860:4860::8844", IPAddressType::kPrivate}, + {"1.1.1.1", IPAddressType::kPublic}, + {"2001:4860:4860::8888", IPAddressType::kPublic}, +}; + +// Used by the test framework to print the param value for parameterized tests. +std::string PrintToString(const IPAddressTypeTestConfig& param) { + return std::string(param.address); +} + +class TurnPortIPAddressTypeMetricsTest + : public TurnPortWithMockDnsResolverTest, + public ::testing::WithParamInterface {}; + +TEST_P(TurnPortIPAddressTypeMetricsTest, TestIPAddressTypeMetrics) { + metrics::Reset(); + + SetDnsResolverExpectations( + [](webrtc::MockAsyncDnsResolver* resolver, + webrtc::MockAsyncDnsResolverResult* resolver_result) { + EXPECT_CALL(*resolver, Start(SocketAddress("localhost", 5000), + /*family=*/AF_INET, _)) + .WillOnce([](const webrtc::SocketAddress& /* addr */, + int /* family */, + absl::AnyInvocable callback) { callback(); }); + EXPECT_CALL(*resolver, result) + .WillRepeatedly(ReturnPointee(resolver_result)); + EXPECT_CALL(*resolver_result, GetError).WillRepeatedly(Return(0)); + EXPECT_CALL(*resolver_result, GetResolvedAddress(AF_INET, _)) + .WillOnce(DoAll(SetArgPointee<1>(SocketAddress("127.0.0.1", 5000)), + Return(true))); + }); + + ProtocolAddress server_address({GetParam().address, 5000}, PROTO_UDP); + SocketAddress local_address = server_address.address.family() == AF_INET6 + ? kLocalIPv6Addr + : kLocalAddr1; + CreateTurnPort(local_address, kTurnUsername, kTurnPassword, server_address); + turn_port_->PrepareAddress(); + + ASSERT_THAT(WaitUntil([&] { return turn_port_->HasRequests(); }, IsTrue()), + IsRtcOk()); + + auto samples = + metrics::Samples("WebRTC.PeerConnection.Turn.ServerAddressType"); + ASSERT_EQ(samples.size(), 1u); + EXPECT_EQ(samples[static_cast(GetParam().address_type)], 1); +} + +INSTANTIATE_TEST_SUITE_P(All, + TurnPortIPAddressTypeMetricsTest, + ::testing::ValuesIn(kAllIPAddressTypeTestConfigs)); + } // namespace webrtc diff --git a/p2p/base/wrapping_active_ice_controller_unittest.cc b/p2p/base/wrapping_active_ice_controller_unittest.cc index ee9cc510f7..113e6b6574 100644 --- a/p2p/base/wrapping_active_ice_controller_unittest.cc +++ b/p2p/base/wrapping_active_ice_controller_unittest.cc @@ -59,17 +59,15 @@ using ::webrtc::TimeDelta; using NiceMockIceController = NiceMock; -static const Connection* kConnection = - reinterpret_cast(0xabcd); -static const Connection* kConnectionTwo = - reinterpret_cast(0xbcde); -static const Connection* kConnectionThree = +const Connection* kConnection = reinterpret_cast(0xabcd); +const Connection* kConnectionTwo = reinterpret_cast(0xbcde); +const Connection* kConnectionThree = reinterpret_cast(0xcdef); -static const std::vector kEmptyConnsList = +const std::vector kEmptyConnsList = std::vector(); -static const TimeDelta kTick = TimeDelta::Millis(1); +const TimeDelta kTick = TimeDelta::Millis(1); TEST(WrappingActiveIceControllerTest, CreateLegacyIceControllerFromFactory) { AutoThread main; diff --git a/p2p/client/basic_port_allocator.cc b/p2p/client/basic_port_allocator.cc index fa12319c6c..cf370d9ad9 100644 --- a/p2p/client/basic_port_allocator.cc +++ b/p2p/client/basic_port_allocator.cc @@ -704,9 +704,7 @@ std::vector BasicPortAllocatorSession::GetNetworks() { // Filter out link-local networks if needed. if (flags() & PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS) { NetworkFilter link_local_filter( - [](const webrtc::Network* network) { - return IPIsLinkLocal(network->prefix()); - }, + [](const Network* network) { return IPIsLinkLocal(network->prefix()); }, "link-local"); FilterNetworks(&networks, link_local_filter); } diff --git a/p2p/client/basic_port_allocator.h b/p2p/client/basic_port_allocator.h index 3af4d1b194..01d118a33b 100644 --- a/p2p/client/basic_port_allocator.h +++ b/p2p/client/basic_port_allocator.h @@ -103,7 +103,7 @@ class RTC_EXPORT BasicPortAllocator : public PortAllocator { NetworkManager* network_manager_; // Always externally-owned pointer to a socket factory. PacketSocketFactory* const socket_factory_; - int network_ignore_mask_ = webrtc::kDefaultNetworkIgnoreMask; + int network_ignore_mask_ = kDefaultNetworkIgnoreMask; AlwaysValidPointer relay_port_factory_; @@ -143,7 +143,7 @@ class RTC_EXPORT BasicPortAllocatorSession : public PortAllocatorSession { // the type of candidates to gather and the candidate filter only controls the // signaling of candidates. As a result, with the candidate filter changed // alone, all newly allowed candidates for signaling should already be - // gathered by the respective webrtc::Port. + // gathered by the respective Port. void SetCandidateFilter(uint32_t filter) override; void StartGettingPorts() override; void StopGettingPorts() override; @@ -151,7 +151,7 @@ class RTC_EXPORT BasicPortAllocatorSession : public PortAllocatorSession { bool IsGettingPorts() override; bool IsCleared() const override; bool IsStopped() const override; - // These will all be webrtc::Ports. + // These will all be Ports. std::vector ReadyPorts() const override; std::vector ReadyCandidates() const override; bool CandidatesAllocationDone() const override; @@ -286,7 +286,7 @@ class RTC_EXPORT BasicPortAllocatorSession : public PortAllocatorSession { std::vector sequences_; std::vector ports_; std::vector candidate_error_events_; - uint32_t candidate_filter_ = webrtc::CF_ALL; + uint32_t candidate_filter_ = CF_ALL; // Policy on how to prune turn ports, taken from the port allocator. PortPrunePolicy turn_port_prune_policy_; SessionState state_ = SessionState::CLEARED; diff --git a/p2p/client/basic_port_allocator_unittest.cc b/p2p/client/basic_port_allocator_unittest.cc index c022efe33f..c8e5464593 100644 --- a/p2p/client/basic_port_allocator_unittest.cc +++ b/p2p/client/basic_port_allocator_unittest.cc @@ -1597,7 +1597,7 @@ TEST_F(BasicPortAllocatorTest, TestGetAllPortsNoUdpAllowed) { EXPECT_TRUE( HasCandidate(candidates_, IceCandidateType::kHost, "tcp", kClientAddr)); // We wait at least for a full STUN timeout, which - // webrtc::STUN_TOTAL_TIMEOUT seconds. + // STUN_TOTAL_TIMEOUT seconds. EXPECT_THAT(WaitUntil([&] { return candidate_allocation_done_; }, IsTrue(), {.timeout = TimeDelta::Millis(STUN_TOTAL_TIMEOUT), .clock = &fake_clock}), @@ -2524,7 +2524,7 @@ TEST_F( .clock = &fake_clock}), IsRtcOk()); EXPECT_TRUE(candidates_.back().is_local()); - // We use a shared socket and webrtc::UDPPort handles the srflx candidate. + // We use a shared socket and UDPPort handles the srflx candidate. EXPECT_EQ(2u, ports_.size()); } diff --git a/p2p/dtls/dtls_ice_integrationtest.cc b/p2p/dtls/dtls_ice_integrationtest.cc index 8a638faab1..536b89ea78 100644 --- a/p2p/dtls/dtls_ice_integrationtest.cc +++ b/p2p/dtls/dtls_ice_integrationtest.cc @@ -63,17 +63,17 @@ using ::testing::IsTrue; class DtlsIceIntegrationTest : public ::testing::TestWithParam>, public sigslot::has_slots<> { public: - void CandidateC2S(webrtc::IceTransportInternal*, const webrtc::Candidate& c) { + void CandidateC2S(IceTransportInternal*, const Candidate& c) { server_thread()->PostTask( [this, c = c]() { server_.ice->AddRemoteCandidate(c); }); } - void CandidateS2C(webrtc::IceTransportInternal*, const webrtc::Candidate& c) { + void CandidateS2C(IceTransportInternal*, const Candidate& c) { client_thread()->PostTask( [this, c = c]() { client_.ice->AddRemoteCandidate(c); }); } @@ -86,17 +86,17 @@ class DtlsIceIntegrationTest : public ::testing::TestWithParam network_manager; - std::unique_ptr packet_socket_factory; - std::unique_ptr allocator; - std::unique_ptr ice; + EmulatedNetworkManagerInterface* emulated_network_manager = nullptr; + std::unique_ptr network_manager; + std::unique_ptr packet_socket_factory; + std::unique_ptr allocator; + std::unique_ptr ice; std::unique_ptr dtls; // SetRemoteFingerprintFromCert does not actually set the fingerprint, // but only store it for setting later. bool store_but_dont_set_remote_fingerprint = false; - std::unique_ptr remote_fingerprint; + std::unique_ptr remote_fingerprint; Environment env; bool dtls_stun_piggyback; @@ -105,14 +105,13 @@ class DtlsIceIntegrationTest : public ::testing::TestWithParam()), - socket_factory_( - std::make_unique(ss_.get())), + : ss_(std::make_unique()), + socket_factory_(std::make_unique(ss_.get())), client_(std::get<0>(GetParam()), - std::get<2>(GetParam()) == webrtc::SSL_PROTOCOL_DTLS_13 && + std::get<2>(GetParam()) == SSL_PROTOCOL_DTLS_13 && std::get<4>(GetParam())), server_(std::get<1>(GetParam()), - std::get<2>(GetParam()) == webrtc::SSL_PROTOCOL_DTLS_13 && + std::get<2>(GetParam()) == SSL_PROTOCOL_DTLS_13 && std::get<5>(GetParam())), client_ice_parameters_("c_ufrag", "c_icepwd_something_something", @@ -122,11 +121,11 @@ class DtlsIceIntegrationTest : public ::testing::TestWithParam client_certificate, - const scoped_refptr server_certificate) { + void SetupEndpoint(Endpoint& ep, + bool client, + const scoped_refptr client_certificate, + const scoped_refptr server_certificate) { thread(ep)->BlockingCall([&]() { if (!network_manager_) { network_manager_ = std::make_unique(Thread::Current()); } if (network_emulation_manager_ == nullptr) { - ep.allocator = std::make_unique( + ep.allocator = std::make_unique( ep.env, network_manager_.get(), socket_factory_.get()); } else { ep.network_manager = ep.emulated_network_manager->ReleaseNetworkManager(); - ep.packet_socket_factory = - std::make_unique( - ep.emulated_network_manager->socket_factory()); - ep.allocator = std::make_unique( + ep.packet_socket_factory = std::make_unique( + ep.emulated_network_manager->socket_factory()); + ep.allocator = std::make_unique( ep.env, ep.network_manager.get(), ep.packet_socket_factory.get()); } ep.allocator->set_flags(ep.allocator->flags() | - webrtc::PORTALLOCATOR_DISABLE_TCP); - ep.ice = std::make_unique( + PORTALLOCATOR_DISABLE_TCP); + ep.ice = std::make_unique( client ? "client_transport" : "server_transport", 0, ep.allocator.get(), &ep.env.field_trials()); CryptoOptions crypto_options; @@ -181,8 +178,8 @@ class DtlsIceIntegrationTest : public ::testing::TestWithParamSetIceConfig(config); @@ -192,13 +189,11 @@ class DtlsIceIntegrationTest : public ::testing::TestWithParamSetRemoteIceParameters(client ? server_ice_parameters_ : client_ice_parameters_); if (client) { - ep.ice->SetIceRole(std::get<3>(GetParam()) - ? webrtc::ICEROLE_CONTROLLED - : webrtc::ICEROLE_CONTROLLING); + ep.ice->SetIceRole(std::get<3>(GetParam()) ? ICEROLE_CONTROLLED + : ICEROLE_CONTROLLING); } else { - ep.ice->SetIceRole(std::get<3>(GetParam()) - ? webrtc::ICEROLE_CONTROLLING - : webrtc::ICEROLE_CONTROLLED); + ep.ice->SetIceRole(std::get<3>(GetParam()) ? ICEROLE_CONTROLLING + : ICEROLE_CONTROLLED); } if (client) { ep.ice->SignalCandidateGathered.connect( @@ -209,7 +204,7 @@ class DtlsIceIntegrationTest : public ::testing::TestWithParamSetDtlsRole(client ? webrtc::SSL_SERVER : webrtc::SSL_CLIENT); + ep.dtls->SetDtlsRole(client ? SSL_SERVER : SSL_CLIENT); SetLocalCertificate(ep, client ? client_certificate : server_certificate); SetRemoteFingerprintFromCert( ep, client ? server_certificate : client_certificate); @@ -217,13 +212,13 @@ class DtlsIceIntegrationTest : public ::testing::TestWithParam(ss_.get()); + thread_ = std::make_unique(ss_.get()); } client_thread()->BlockingCall([&]() { @@ -238,14 +233,14 @@ class DtlsIceIntegrationTest : public ::testing::TestWithParamAddInterface(webrtc::SocketAddress("192.168.1.1", 0)); + network_manager_->AddInterface(SocketAddress("192.168.1.1", 0)); } client_thread()->BlockingCall([&]() { client_.allocator->Initialize(); }); server_thread()->BlockingCall([&]() { server_.allocator->Initialize(); }); } - void TearDown() { + void TearDown() override { client_thread()->BlockingCall([&]() { client_.dtls.reset(); client_.ice.reset(); @@ -259,12 +254,12 @@ class DtlsIceIntegrationTest : public ::testing::TestWithParam filter) { - webrtc::IceTransportStats stats; + IceTransportInternal* ice, + std::function filter) { + IceTransportStats stats; ice->GetStats(&stats); int count = 0; for (const auto& con : stats.connection_infos) { @@ -275,30 +270,30 @@ class DtlsIceIntegrationTest : public ::testing::TestWithParamtime_controller(), }; } } - webrtc::Thread* thread(Endpoint& ep) { + Thread* thread(Endpoint& ep) { if (ep.emulated_network_manager == nullptr) { return thread_.get(); } else { @@ -306,14 +301,13 @@ class DtlsIceIntegrationTest : public ::testing::TestWithParam& cert) { - ep.remote_fingerprint = - webrtc::SSLFingerprint::CreateFromCertificate(*cert); + ep.remote_fingerprint = SSLFingerprint::CreateFromCertificate(*cert); if (ep.store_but_dont_set_remote_fingerprint) { return; } @@ -338,18 +332,18 @@ class DtlsIceIntegrationTest : public ::testing::TestWithParamSetLocalCertificate(certificate); } - webrtc::ScopedFakeClock fake_clock_; - std::unique_ptr ss_; - std::unique_ptr socket_factory_; - std::unique_ptr network_emulation_manager_; - std::unique_ptr thread_; - std::unique_ptr network_manager_; + ScopedFakeClock fake_clock_; + std::unique_ptr ss_; + std::unique_ptr socket_factory_; + std::unique_ptr network_emulation_manager_; + std::unique_ptr thread_; + std::unique_ptr network_manager_; Endpoint client_; Endpoint server_; - webrtc::IceParameters client_ice_parameters_; - webrtc::IceParameters server_ice_parameters_; + IceParameters client_ice_parameters_; + IceParameters server_ice_parameters_; }; TEST_P(DtlsIceIntegrationTest, SmokeTest) { @@ -359,10 +353,10 @@ TEST_P(DtlsIceIntegrationTest, SmokeTest) { // Note: this only reaches the pending piggybacking state. EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return client_.dtls->writable() && server_.dtls->writable(); }, IsTrue(), wait_until_settings()), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_EQ(client_.dtls->IsDtlsPiggybackSupportedByPeer(), client_.dtls_stun_piggyback && server_.dtls_stun_piggyback); EXPECT_EQ(server_.dtls->IsDtlsPiggybackSupportedByPeer(), @@ -390,14 +384,14 @@ TEST_P(DtlsIceIntegrationTest, SmokeTest) { } // Validate that we can add new Connections (that become writable). - network_manager_->AddInterface(webrtc::SocketAddress("192.168.2.1", 0)); - EXPECT_THAT(webrtc::WaitUntil( + network_manager_->AddInterface(SocketAddress("192.168.2.1", 0)); + EXPECT_THAT(WaitUntil( [&] { return CountWritableConnections(client_.ice.get()) > 1 && CountWritableConnections(server_.ice.get()) > 1; }, IsTrue(), wait_until_settings()), - webrtc::IsRtcOk()); + IsRtcOk()); } // Check that DtlsInStun still works even if SetRemoteFingerprint is called @@ -410,17 +404,16 @@ TEST_P(DtlsIceIntegrationTest, ClientLateCertificate) { server_.ice->MaybeStartGathering(); ASSERT_THAT( - webrtc::WaitUntil( - [&] { return CountWritableConnections(client_.ice.get()) > 0; }, - IsTrue(), wait_until_settings()), - webrtc::IsRtcOk()); + WaitUntil([&] { return CountWritableConnections(client_.ice.get()) > 0; }, + IsTrue(), wait_until_settings()), + IsRtcOk()); SetRemoteFingerprint(client_); ASSERT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return client_.dtls->writable() && server_.dtls->writable(); }, IsTrue(), wait_until_settings()), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_EQ(client_.dtls->IsDtlsPiggybackSupportedByPeer(), client_.dtls_stun_piggyback && server_.dtls_stun_piggyback); @@ -451,7 +444,7 @@ TEST_P(DtlsIceIntegrationTest, TestWithPacketLoss) { server_thread()->PostTask([&]() { server_.ice->MaybeStartGathering(); }); - EXPECT_THAT(webrtc::WaitUntil( + EXPECT_THAT(WaitUntil( [&] { return client_thread()->BlockingCall([&]() { return client_.dtls->writable(); @@ -460,7 +453,7 @@ TEST_P(DtlsIceIntegrationTest, TestWithPacketLoss) { }); }, IsTrue(), wait_until_settings()), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_EQ(client_thread()->BlockingCall([&]() { return client_.dtls->IsDtlsPiggybackSupportedByPeer(); @@ -488,10 +481,10 @@ TEST_P(DtlsIceIntegrationTest, AlmostFullSTUN_BINDING) { // Note: this only reaches the pending piggybacking state. EXPECT_THAT( - webrtc::WaitUntil( + WaitUntil( [&] { return client_.dtls->writable() && server_.dtls->writable(); }, IsTrue(), wait_until_settings()), - webrtc::IsRtcOk()); + IsRtcOk()); EXPECT_EQ(client_.dtls->IsDtlsPiggybackSupportedByPeer(), client_.dtls_stun_piggyback && server_.dtls_stun_piggyback); EXPECT_EQ(server_.dtls->IsDtlsPiggybackSupportedByPeer(), @@ -528,8 +521,8 @@ INSTANTIATE_TEST_SUITE_P( DtlsIceIntegrationTest, ::testing::Combine(testing::Bool(), testing::Bool(), - testing::Values(webrtc::SSL_PROTOCOL_DTLS_12, - webrtc::SSL_PROTOCOL_DTLS_13), + testing::Values(SSL_PROTOCOL_DTLS_12, + SSL_PROTOCOL_DTLS_13), testing::Bool(), testing::Bool(), testing::Bool())); diff --git a/p2p/dtls/dtls_stun_piggyback_callbacks.h b/p2p/dtls/dtls_stun_piggyback_callbacks.h index 4c8b226f91..e9c176cc23 100644 --- a/p2p/dtls/dtls_stun_piggyback_callbacks.h +++ b/p2p/dtls/dtls_stun_piggyback_callbacks.h @@ -32,14 +32,13 @@ class DtlsStunPiggybackCallbacks { // - an optional DTLS_IN_STUN_ACK attribute absl::AnyInvocable, std::optional>( - /* request-type */ webrtc::StunMessageType)>&& send_data, + /* request-type */ StunMessageType)>&& send_data, // Function invoked when receiving a STUN_BINDING { REQUEST / RESPONSE } // contains the (nullable) DTLS_IN_STUN and DTLS_IN_STUN_ACK attributes. - absl::AnyInvocable< - void(const webrtc::StunByteStringAttribute* /* DTLS_IN_STUN */, - const webrtc::StunByteStringAttribute* /* DTLS_IN_STUN_ACK */)>&& - recv_data) + absl::AnyInvocable&& recv_data) : send_data_(std::move(send_data)), recv_data_(std::move(recv_data)) { RTC_DCHECK( // either all set @@ -69,11 +68,11 @@ class DtlsStunPiggybackCallbacks { private: absl::AnyInvocable, std::optional>( - /* request-type */ webrtc::StunMessageType)> + /* request-type */ StunMessageType)> send_data_; absl::AnyInvocable + const StunByteStringAttribute* /* DTLS_IN_STUN */, + const StunByteStringAttribute* /* DTLS_IN_STUN_ACK */)> recv_data_; }; diff --git a/p2p/dtls/dtls_stun_piggyback_controller.h b/p2p/dtls/dtls_stun_piggyback_controller.h index 9f9c3e9868..ad9b97a32c 100644 --- a/p2p/dtls/dtls_stun_piggyback_controller.h +++ b/p2p/dtls/dtls_stun_piggyback_controller.h @@ -37,8 +37,7 @@ class DtlsStunPiggybackController { // dtls_data_callback will be called with any DTLS packets received // piggybacked. DtlsStunPiggybackController( - absl::AnyInvocable)> - dtls_data_callback); + absl::AnyInvocable)> dtls_data_callback); ~DtlsStunPiggybackController(); enum class State { diff --git a/p2p/dtls/dtls_transport.cc b/p2p/dtls/dtls_transport.cc index bcbf7ec681..0d2dbc82b0 100644 --- a/p2p/dtls/dtls_transport.cc +++ b/p2p/dtls/dtls_transport.cc @@ -459,9 +459,9 @@ bool DtlsTransportInternalImpl::SetupDtls() { // (such as automatic packetization smoothing). if (dtls_in_stun_) { // - This is only needed when using PQC but we don't know that here. - // - 800 is sufficiently small so that dtls pqc handshake packets - // can get put into STUN attributes. - const int kDtlsMtu = 800; + // - 900 is sufficiently small so that dtls pqc handshake packets + // can get put into STUN attributes and still fit into two packets. + const int kDtlsMtu = 900; dtls_->SetMTU(kDtlsMtu); } @@ -571,13 +571,13 @@ int DtlsTransportInternalImpl::SendPacket( // Can't send anything when we're failed. RTC_LOG(LS_ERROR) << ToString() << ": Couldn't send packet due to " - "webrtc::DtlsTransportState::kFailed."; + "DtlsTransportState::kFailed."; return -1; case DtlsTransportState::kClosed: // Can't send anything when we're closed. RTC_LOG(LS_ERROR) << ToString() << ": Couldn't send packet due to " - "webrtc::DtlsTransportState::kClosed."; + "DtlsTransportState::kClosed."; return -1; default: RTC_DCHECK_NOTREACHED(); @@ -729,13 +729,13 @@ void DtlsTransportInternalImpl::OnWritableState( // Should not happen. Do nothing. RTC_LOG(LS_ERROR) << ToString() << ": OnWritableState() called in state " - "webrtc::DtlsTransportState::kFailed."; + "DtlsTransportState::kFailed."; break; case DtlsTransportState::kClosed: // Should not happen. Do nothing. RTC_LOG(LS_ERROR) << ToString() << ": OnWritableState() called in state " - "webrtc::DtlsTransportState::kClosed."; + "DtlsTransportState::kClosed."; break; case DtlsTransportState::kNumValues: RTC_DCHECK_NOTREACHED(); diff --git a/p2p/dtls/dtls_transport.h b/p2p/dtls/dtls_transport.h index a7fb055adb..edf0635dc6 100644 --- a/p2p/dtls/dtls_transport.h +++ b/p2p/dtls/dtls_transport.h @@ -54,10 +54,10 @@ namespace webrtc { // the bottom and a StreamInterface on the top. class StreamInterfaceChannel : public StreamInterface { public: - explicit StreamInterfaceChannel(webrtc::IceTransportInternal* ice_transport); + explicit StreamInterfaceChannel(IceTransportInternal* ice_transport); void SetDtlsStunPiggybackController( - webrtc::DtlsStunPiggybackController* dtls_stun_piggyback_controller); + DtlsStunPiggybackController* dtls_stun_piggyback_controller); StreamInterfaceChannel(const StreamInterfaceChannel&) = delete; StreamInterfaceChannel& operator=(const StreamInterfaceChannel&) = delete; @@ -78,11 +78,11 @@ class StreamInterfaceChannel : public StreamInterface { bool Flush() override; private: - webrtc::IceTransportInternal* const ice_transport_; // owned by DtlsTransport - webrtc::DtlsStunPiggybackController* dtls_stun_piggyback_controller_ = + IceTransportInternal* const ice_transport_; // owned by DtlsTransport + DtlsStunPiggybackController* dtls_stun_piggyback_controller_ = nullptr; // owned by DtlsTransport StreamState state_ RTC_GUARDED_BY(callback_sequence_); - webrtc::BufferQueue packets_ RTC_GUARDED_BY(callback_sequence_); + BufferQueue packets_ RTC_GUARDED_BY(callback_sequence_); }; // This class provides a DTLS SSLStreamAdapter inside a TransportChannel-style @@ -113,7 +113,7 @@ class StreamInterfaceChannel : public StreamInterface { // // This class is not thread safe; all methods must be called on the same thread // as the constructor. -class DtlsTransportInternalImpl : public webrtc::DtlsTransportInternal { +class DtlsTransportInternalImpl : public DtlsTransportInternal { public: // `ice_transport` is the ICE transport this DTLS transport is wrapping. It // must outlive this DTLS transport. @@ -124,10 +124,10 @@ class DtlsTransportInternalImpl : public webrtc::DtlsTransportInternal { // `event_log` is an optional RtcEventLog for logging state changes. It should // outlive the DtlsTransport. DtlsTransportInternalImpl( - webrtc::IceTransportInternal* ice_transport, - const webrtc::CryptoOptions& crypto_options, - webrtc::RtcEventLog* event_log, - webrtc::SSLProtocolVersion max_version = webrtc::SSL_PROTOCOL_DTLS_12); + IceTransportInternal* ice_transport, + const CryptoOptions& crypto_options, + RtcEventLog* event_log, + SSLProtocolVersion max_version = SSL_PROTOCOL_DTLS_12); ~DtlsTransportInternalImpl() override; @@ -135,7 +135,7 @@ class DtlsTransportInternalImpl : public webrtc::DtlsTransportInternal { DtlsTransportInternalImpl& operator=(const DtlsTransportInternalImpl&) = delete; - webrtc::DtlsTransportState dtls_state() const override; + DtlsTransportState dtls_state() const override; const std::string& transport_name() const override; int component() const override; @@ -151,8 +151,8 @@ class DtlsTransportInternalImpl : public webrtc::DtlsTransportInternal { // being "active" or not (acting as a passthrough if not active), just require // this certificate on construction or "Start". bool SetLocalCertificate( - const scoped_refptr& certificate) override; - scoped_refptr GetLocalCertificate() const override; + const scoped_refptr& certificate) override; + scoped_refptr GetLocalCertificate() const override; // SetRemoteFingerprint must be called after SetLocalCertificate, and any // other methods like SetDtlsRole. It's what triggers the actual DTLS setup. @@ -162,11 +162,10 @@ class DtlsTransportInternalImpl : public webrtc::DtlsTransportInternal { size_t digest_len) override; // SetRemoteParameters must be called after SetLocalCertificate. - webrtc::RTCError SetRemoteParameters( - absl::string_view digest_alg, - const uint8_t* digest, - size_t digest_len, - std::optional role) override; + RTCError SetRemoteParameters(absl::string_view digest_alg, + const uint8_t* digest, + size_t digest_len, + std::optional role) override; // Called to send a packet (via DTLS, if turned on). int SendPacket(const char* data, @@ -174,7 +173,7 @@ class DtlsTransportInternalImpl : public webrtc::DtlsTransportInternal { const AsyncSocketPacketOptions& options, int flags) override; - bool GetOption(webrtc::Socket::Option opt, int* value) override; + bool GetOption(Socket::Option opt, int* value) override; // Find out which TLS version was negotiated bool GetSslVersionBytes(int* version) const override; @@ -190,8 +189,8 @@ class DtlsTransportInternalImpl : public webrtc::DtlsTransportInternal { // If not applicable, it returns zero. uint16_t GetSslPeerSignatureAlgorithm() const override; - bool GetDtlsRole(webrtc::SSLRole* role) const override; - bool SetDtlsRole(webrtc::SSLRole role) override; + bool GetDtlsRole(SSLRole* role) const override; + bool SetDtlsRole(SSLRole role) override; // Find out which DTLS cipher was negotiated bool GetSslCipherSuite(int* cipher) const override; @@ -200,7 +199,7 @@ class DtlsTransportInternalImpl : public webrtc::DtlsTransportInternal { // Once DTLS has been established, this method retrieves the certificate // chain in use by the remote peer, for use in external identity // verification. - std::unique_ptr GetRemoteSSLCertChain() const override; + std::unique_ptr GetRemoteSSLCertChain() const override; // Once DTLS has established (i.e., this ice_transport is writable), this // method extracts the keys negotiated during the DTLS handshake, for use in @@ -208,7 +207,7 @@ class DtlsTransportInternalImpl : public webrtc::DtlsTransportInternal { bool ExportSrtpKeyingMaterial( ZeroOnFreeBuffer& keying_material) override; - webrtc::IceTransportInternal* ice_transport() override; + IceTransportInternal* ice_transport() override; // For informational purposes. Tells if the DTLS handshake has finished. // This may be true even if writable() is false, if the remote fingerprint @@ -220,9 +219,9 @@ class DtlsTransportInternalImpl : public webrtc::DtlsTransportInternal { int GetError() override; - std::optional network_route() const override; + std::optional network_route() const override; - int SetOption(webrtc::Socket::Option opt, int value) override; + int SetOption(Socket::Option opt, int value) override; std::string ToString() const { const absl::string_view RECEIVING_ABBREV[2] = {"_", "R"}; @@ -247,48 +246,47 @@ class DtlsTransportInternalImpl : public webrtc::DtlsTransportInternal { private: void ConnectToIceTransport(); - void OnWritableState(webrtc::PacketTransportInternal* transport); - void OnReadPacket(webrtc::PacketTransportInternal* transport, + void OnWritableState(PacketTransportInternal* transport); + void OnReadPacket(PacketTransportInternal* transport, const ReceivedIpPacket& packet, bool piggybacked); - void OnSentPacket(webrtc::PacketTransportInternal* transport, + void OnSentPacket(PacketTransportInternal* transport, const SentPacketInfo& sent_packet); - void OnReadyToSend(webrtc::PacketTransportInternal* transport); - void OnReceivingState(webrtc::PacketTransportInternal* transport); + void OnReadyToSend(PacketTransportInternal* transport); + void OnReceivingState(PacketTransportInternal* transport); void OnDtlsEvent(int sig, int err); - void OnNetworkRouteChanged(std::optional network_route); + void OnNetworkRouteChanged(std::optional network_route); bool SetupDtls(); void MaybeStartDtls(); bool HandleDtlsPacket(ArrayView payload); - void OnDtlsHandshakeError(webrtc::SSLHandshakeError error); + void OnDtlsHandshakeError(SSLHandshakeError error); void ConfigureHandshakeTimeout(); void set_receiving(bool receiving); void set_writable(bool writable); // Sets the DTLS state, signaling if necessary. - void set_dtls_state(webrtc::DtlsTransportState state); + void set_dtls_state(DtlsTransportState state); void SetPiggybackDtlsDataCallback( - absl::AnyInvocable - callback); + absl::AnyInvocable callback); void PeriodicRetransmitDtlsPacketUntilDtlsConnected(); - RTC_NO_UNIQUE_ADDRESS webrtc::SequenceChecker thread_checker_; + RTC_NO_UNIQUE_ADDRESS SequenceChecker thread_checker_; const int component_; - webrtc::DtlsTransportState dtls_state_ = webrtc::DtlsTransportState::kNew; + DtlsTransportState dtls_state_ = DtlsTransportState::kNew; // Underlying ice_transport, not owned by this class. - webrtc::IceTransportInternal* const ice_transport_; - std::unique_ptr dtls_; // The DTLS stream + IceTransportInternal* const ice_transport_; + std::unique_ptr dtls_; // The DTLS stream StreamInterfaceChannel* downward_; // Wrapper for ice_transport_, owned by dtls_. const std::vector srtp_ciphers_; // SRTP ciphers to use with DTLS. // Cipher groups used for DTLS handshake to establish ephemeral key. const std::vector ephemeral_key_exchange_cipher_groups_; bool dtls_active_ = false; - scoped_refptr local_certificate_; - std::optional dtls_role_; - const webrtc::SSLProtocolVersion ssl_max_version_; + scoped_refptr local_certificate_; + std::optional dtls_role_; + const SSLProtocolVersion ssl_max_version_; Buffer remote_fingerprint_value_; std::string remote_fingerprint_algorithm_; @@ -306,7 +304,7 @@ class DtlsTransportInternalImpl : public webrtc::DtlsTransportInternal { // of the stack. bool ice_has_been_writable_ = false; - webrtc::RtcEventLog* const event_log_; + RtcEventLog* const event_log_; // Initialized in constructor based on WebRTC-IceHandshakeDtls, // (so that we return PIGGYBACK_ACK to client if we get STUN_BINDING_REQUEST @@ -314,10 +312,9 @@ class DtlsTransportInternalImpl : public webrtc::DtlsTransportInternal { bool dtls_in_stun_ = false; // A controller for piggybacking DTLS in STUN. - webrtc::DtlsStunPiggybackController dtls_stun_piggyback_controller_; + DtlsStunPiggybackController dtls_stun_piggyback_controller_; - absl::AnyInvocable + absl::AnyInvocable piggybacked_dtls_callback_; // When ICE get writable during dtls piggybacked handshake @@ -325,7 +322,7 @@ class DtlsTransportInternalImpl : public webrtc::DtlsTransportInternal { // in boringssl (that is work in progress). Therefore // DtlsTransportInternalImpl has a "hack" to periodically retransmit. bool pending_periodic_retransmit_dtls_packet_ = false; - webrtc::ScopedTaskSafetyDetached safety_flag_; + ScopedTaskSafetyDetached safety_flag_; }; } // namespace webrtc diff --git a/p2p/dtls/dtls_transport_internal.h b/p2p/dtls/dtls_transport_internal.h index c5df3c51cf..c54d56727d 100644 --- a/p2p/dtls/dtls_transport_internal.h +++ b/p2p/dtls/dtls_transport_internal.h @@ -115,7 +115,7 @@ class DtlsTransportInternal : public PacketTransportInternal { // Expose the underneath IceTransport. virtual IceTransportInternal* ice_transport() = 0; - // F: void(DtlsTransportInternal*, const webrtc::DtlsTransportState) + // F: void(DtlsTransportInternal*, const DtlsTransportState) template void SubscribeDtlsTransportState(F&& callback) { dtls_transport_state_callback_list_.AddReceiver(std::forward(callback)); @@ -137,7 +137,7 @@ class DtlsTransportInternal : public PacketTransportInternal { } // Emitted whenever the Dtls handshake failed on some transport channel. - // F: void(webrtc::SSLHandshakeError) + // F: void(SSLHandshakeError) template void SubscribeDtlsHandshakeError(F&& callback) { dtls_handshake_error_callback_list_.AddReceiver(std::forward(callback)); diff --git a/p2p/dtls/dtls_transport_unittest.cc b/p2p/dtls/dtls_transport_unittest.cc index 0fc2814016..1e7067d118 100644 --- a/p2p/dtls/dtls_transport_unittest.cc +++ b/p2p/dtls/dtls_transport_unittest.cc @@ -112,7 +112,7 @@ class DtlsTestClient : public sigslot::has_slots<> { dtls_transport_ = nullptr; fake_ice_transport_ = nullptr; - webrtc::CryptoOptions crypto_options; + CryptoOptions crypto_options; if (pqc_) { FieldTrials field_trials("WebRTC-EnableDtlsPqc/Enabled/"); crypto_options.ephemeral_key_exchange_cipher_groups.Update(&field_trials); diff --git a/p2p/dtls/fake_dtls_transport.h b/p2p/dtls/fake_dtls_transport.h index a0f7596439..dc99ed5227 100644 --- a/p2p/dtls/fake_dtls_transport.h +++ b/p2p/dtls/fake_dtls_transport.h @@ -145,7 +145,7 @@ class FakeDtlsTransport : public DtlsTransportInternal { } // If the `dtls_role_` is unset, set it to SSL_CLIENT by default. if (!dtls_role_) { - dtls_role_ = std::move(webrtc::SSL_CLIENT); + dtls_role_ = std::move(SSL_CLIENT); } SetDtlsState(DtlsTransportState::kConnected); ice_transport_->SetDestination( @@ -320,10 +320,10 @@ class FakeDtlsTransport : public DtlsTransportInternal { scoped_refptr local_cert_; FakeSSLCertificate* remote_cert_ = nullptr; bool do_dtls_ = false; - SSLProtocolVersion ssl_max_version_ = webrtc::SSL_PROTOCOL_DTLS_12; + SSLProtocolVersion ssl_max_version_ = SSL_PROTOCOL_DTLS_12; SSLFingerprint dtls_fingerprint_; std::optional dtls_role_; - int crypto_suite_ = webrtc::kSrtpAes128CmSha1_80; + int crypto_suite_ = kSrtpAes128CmSha1_80; std::optional ssl_cipher_suite_; DtlsTransportState dtls_state_ = DtlsTransportState::kNew; diff --git a/p2p/test/fake_ice_transport.h b/p2p/test/fake_ice_transport.h index 29b8a9e7b7..ef4a90c13d 100644 --- a/p2p/test/fake_ice_transport.h +++ b/p2p/test/fake_ice_transport.h @@ -11,6 +11,7 @@ #ifndef P2P_TEST_FAKE_ICE_TRANSPORT_H_ #define P2P_TEST_FAKE_ICE_TRANSPORT_H_ +#include #include #include #include @@ -19,7 +20,6 @@ #include #include -#include "absl/algorithm/container.h" #include "absl/functional/any_invocable.h" #include "absl/strings/string_view.h" #include "api/array_view.h" @@ -168,8 +168,8 @@ class FakeIceTransport : public IceTransportInternal { void SetCandidatesGatheringComplete() { RTC_DCHECK_RUN_ON(network_thread_); - if (gathering_state_ != webrtc::kIceGatheringComplete) { - gathering_state_ = webrtc::kIceGatheringComplete; + if (gathering_state_ != kIceGatheringComplete) { + gathering_state_ = kIceGatheringComplete; SendGatheringStateEvent(); } } @@ -264,8 +264,8 @@ class FakeIceTransport : public IceTransportInternal { void MaybeStartGathering() override { RTC_DCHECK_RUN_ON(network_thread_); - if (gathering_state_ == webrtc::kIceGatheringNew) { - gathering_state_ = webrtc::kIceGatheringGathering; + if (gathering_state_ == kIceGatheringNew) { + gathering_state_ = kIceGatheringGathering; SendGatheringStateEvent(); } } @@ -288,7 +288,9 @@ class FakeIceTransport : public IceTransportInternal { } void RemoveRemoteCandidate(const Candidate& candidate) override { RTC_DCHECK_RUN_ON(network_thread_); - auto it = absl::c_find(remote_candidates_, candidate); + auto it = std::remove_if( + remote_candidates_.begin(), remote_candidates_.end(), + [&](const Candidate& c) { return candidate.MatchesForRemoval(c); }); if (it == remote_candidates_.end()) { RTC_LOG(LS_INFO) << "Trying to remove a candidate which doesn't exist."; return; @@ -351,7 +353,7 @@ class FakeIceTransport : public IceTransportInternal { } } - SentPacketInfo sent_packet(options.packet_id, webrtc::TimeMillis()); + SentPacketInfo sent_packet(options.packet_id, TimeMillis()); SignalSentPacket(this, sent_packet); return static_cast(len); } @@ -396,7 +398,7 @@ class FakeIceTransport : public IceTransportInternal { void set_packet_send_filter( absl::AnyInvocable func) { RTC_DCHECK_RUN_ON(network_thread_); packet_send_filter_func_ = std::move(func); @@ -434,7 +436,7 @@ class FakeIceTransport : public IceTransportInternal { bool SendIcePing() { RTC_DCHECK_RUN_ON(network_thread_); RTC_DLOG(LS_INFO) << name_ << ": SendIcePing()"; - last_sent_ping_timestamp_ = webrtc::TimeMicros(); + last_sent_ping_timestamp_ = TimeMicros(); auto msg = std::make_unique(STUN_BINDING_REQUEST); MaybeAddDtlsPiggybackingAttributes(msg.get()); msg->AddFingerprint(); @@ -562,7 +564,7 @@ class FakeIceTransport : public IceTransportInternal { void ReceivePacketInternal(const CopyOnWriteBuffer& packet) { RTC_DCHECK_RUN_ON(network_thread_); - auto now = webrtc::TimeMicros(); + auto now = TimeMicros(); if (auto msg = GetStunMessage(packet)) { RTC_LOG(LS_INFO) << name_ << ": RECV STUN message: " << ", data[0]: " @@ -632,7 +634,7 @@ class FakeIceTransport : public IceTransportInternal { std::optional legacy_transport_state_ RTC_GUARDED_BY(network_thread_); IceGatheringState gathering_state_ RTC_GUARDED_BY(network_thread_) = - webrtc::kIceGatheringNew; + kIceGatheringNew; bool had_connection_ RTC_GUARDED_BY(network_thread_) = false; bool writable_ RTC_GUARDED_BY(network_thread_) = false; bool receiving_ RTC_GUARDED_BY(network_thread_) = false; diff --git a/p2p/test/fake_port_allocator.h b/p2p/test/fake_port_allocator.h index bce083448b..3853b2198f 100644 --- a/p2p/test/fake_port_allocator.h +++ b/p2p/test/fake_port_allocator.h @@ -122,10 +122,10 @@ class FakePortAllocatorSession : public PortAllocatorSession { void StartGettingPorts() override { if (!port_) { - Network& network = (webrtc::HasIPv6Enabled() && - (flags() & webrtc::PORTALLOCATOR_ENABLE_IPV6)) - ? ipv6_network_ - : ipv4_network_; + Network& network = + (HasIPv6Enabled() && (flags() & PORTALLOCATOR_ENABLE_IPV6)) + ? ipv6_network_ + : ipv4_network_; port_.reset(TestUDPPort::Create({.env = env_, .network_thread = network_thread_, .socket_factory = factory_, @@ -220,7 +220,7 @@ class FakePortAllocatorSession : public PortAllocatorSession { bool is_cleared = false; ServerAddresses stun_servers_; std::vector turn_servers_; - uint32_t candidate_filter_ = webrtc::CF_ALL; + uint32_t candidate_filter_ = CF_ALL; int transport_info_update_count_ = 0; bool running_ = false; }; diff --git a/p2p/test/mock_active_ice_controller.h b/p2p/test/mock_active_ice_controller.h index df18a444a8..98d6cb91f0 100644 --- a/p2p/test/mock_active_ice_controller.h +++ b/p2p/test/mock_active_ice_controller.h @@ -29,41 +29,24 @@ class MockActiveIceController : public ActiveIceControllerInterface { const ActiveIceControllerFactoryArgs& /* args */) {} ~MockActiveIceController() override = default; - MOCK_METHOD(void, SetIceConfig, (const webrtc::IceConfig&), (override)); - MOCK_METHOD(void, OnConnectionAdded, (const webrtc::Connection*), (override)); - MOCK_METHOD(void, - OnConnectionSwitched, - (const webrtc::Connection*), - (override)); - MOCK_METHOD(void, - OnConnectionDestroyed, - (const webrtc::Connection*), - (override)); - MOCK_METHOD(void, - OnConnectionPinged, - (const webrtc::Connection*), - (override)); - MOCK_METHOD(void, - OnConnectionUpdated, - (const webrtc::Connection*), - (override)); + MOCK_METHOD(void, SetIceConfig, (const IceConfig&), (override)); + MOCK_METHOD(void, OnConnectionAdded, (const Connection*), (override)); + MOCK_METHOD(void, OnConnectionSwitched, (const Connection*), (override)); + MOCK_METHOD(void, OnConnectionDestroyed, (const Connection*), (override)); + MOCK_METHOD(void, OnConnectionPinged, (const Connection*), (override)); + MOCK_METHOD(void, OnConnectionUpdated, (const Connection*), (override)); MOCK_METHOD(bool, GetUseCandidateAttribute, - (const webrtc::Connection*, - webrtc::NominationMode, - webrtc::IceMode), + (const Connection*, NominationMode, IceMode), (const, override)); - MOCK_METHOD(void, - OnSortAndSwitchRequest, - (webrtc::IceSwitchReason), - (override)); + MOCK_METHOD(void, OnSortAndSwitchRequest, (IceSwitchReason), (override)); MOCK_METHOD(void, OnImmediateSortAndSwitchRequest, - (webrtc::IceSwitchReason), + (IceSwitchReason), (override)); MOCK_METHOD(bool, OnImmediateSwitchRequest, - (webrtc::IceSwitchReason, const webrtc::Connection*), + (IceSwitchReason, const Connection*), (override)); MOCK_METHOD(const Connection*, FindNextPingableConnection, (), (override)); }; diff --git a/p2p/test/mock_ice_agent.h b/p2p/test/mock_ice_agent.h index 113ddf4105..3ae3f755e0 100644 --- a/p2p/test/mock_ice_agent.h +++ b/p2p/test/mock_ice_agent.h @@ -33,16 +33,16 @@ class MockIceAgent : public IceAgentInterface { MOCK_METHOD(void, UpdateState, (), (override)); MOCK_METHOD(void, ForgetLearnedStateForConnections, - (webrtc::ArrayView), + (ArrayView), (override)); - MOCK_METHOD(void, SendPingRequest, (const webrtc::Connection*), (override)); + MOCK_METHOD(void, SendPingRequest, (const Connection*), (override)); MOCK_METHOD(void, SwitchSelectedConnection, - (const webrtc::Connection*, webrtc::IceSwitchReason), + (const Connection*, IceSwitchReason), (override)); MOCK_METHOD(bool, PruneConnections, - (webrtc::ArrayView), + (ArrayView), (override)); }; diff --git a/p2p/test/mock_ice_controller.h b/p2p/test/mock_ice_controller.h index 5b92dde753..5cc4f316f0 100644 --- a/p2p/test/mock_ice_controller.h +++ b/p2p/test/mock_ice_controller.h @@ -31,16 +31,10 @@ class MockIceController : public IceControllerInterface { explicit MockIceController(const IceControllerFactoryArgs& /* args */) {} ~MockIceController() override = default; - MOCK_METHOD(void, SetIceConfig, (const webrtc::IceConfig&), (override)); - MOCK_METHOD(void, - SetSelectedConnection, - (const webrtc::Connection*), - (override)); - MOCK_METHOD(void, AddConnection, (const webrtc::Connection*), (override)); - MOCK_METHOD(void, - OnConnectionDestroyed, - (const webrtc::Connection*), - (override)); + MOCK_METHOD(void, SetIceConfig, (const IceConfig&), (override)); + MOCK_METHOD(void, SetSelectedConnection, (const Connection*), (override)); + MOCK_METHOD(void, AddConnection, (const Connection*), (override)); + MOCK_METHOD(void, OnConnectionDestroyed, (const Connection*), (override)); MOCK_METHOD(ArrayView, GetConnections, (), @@ -53,22 +47,17 @@ class MockIceController : public IceControllerInterface { (override)); MOCK_METHOD(bool, GetUseCandidateAttr, - (const webrtc::Connection*, - webrtc::NominationMode, - webrtc::IceMode), + (const Connection*, NominationMode, IceMode), (const, override)); MOCK_METHOD(const Connection*, FindNextPingableConnection, (), (override)); - MOCK_METHOD(void, - MarkConnectionPinged, - (const webrtc::Connection*), - (override)); + MOCK_METHOD(void, MarkConnectionPinged, (const Connection*), (override)); MOCK_METHOD(IceControllerInterface::SwitchResult, ShouldSwitchConnection, - (webrtc::IceSwitchReason, const webrtc::Connection*), + (IceSwitchReason, const Connection*), (override)); MOCK_METHOD(IceControllerInterface::SwitchResult, SortAndSwitchConnection, - (webrtc::IceSwitchReason), + (IceSwitchReason), (override)); MOCK_METHOD(std::vector, PruneConnections, (), (override)); }; diff --git a/p2p/test/nat_unittest.cc b/p2p/test/nat_unittest.cc index b9dddc1da5..e98bd176ef 100644 --- a/p2p/test/nat_unittest.cc +++ b/p2p/test/nat_unittest.cc @@ -45,7 +45,7 @@ namespace webrtc { namespace { -bool CheckReceive(webrtc::TestClient* client, +bool CheckReceive(TestClient* client, bool should_receive, const char* buf, size_t size) { @@ -53,44 +53,43 @@ bool CheckReceive(webrtc::TestClient* client, : client->CheckNoPacket(); } -webrtc::TestClient* CreateTestClient(webrtc::SocketFactory* factory, - const webrtc::SocketAddress& local_addr) { - return new webrtc::TestClient( - absl::WrapUnique(webrtc::AsyncUDPSocket::Create(factory, local_addr))); +webrtc::TestClient* CreateTestClient(SocketFactory* factory, + const SocketAddress& local_addr) { + return new TestClient( + absl::WrapUnique(AsyncUDPSocket::Create(factory, local_addr))); } -webrtc::TestClient* CreateTCPTestClient(webrtc::Socket* socket) { - return new webrtc::TestClient( - std::make_unique(socket)); +webrtc::TestClient* CreateTCPTestClient(Socket* socket) { + return new TestClient(std::make_unique(socket)); } // Tests that when sending from internal_addr to external_addrs through the // NAT type specified by nat_type, all external addrs receive the sent packet // and, if exp_same is true, all use the same mapped-address on the NAT. -void TestSend(webrtc::SocketServer* internal, - const webrtc::SocketAddress& internal_addr, - webrtc::SocketServer* external, - const webrtc::SocketAddress external_addrs[4], - webrtc::NATType nat_type, +void TestSend(SocketServer* internal, + const SocketAddress& internal_addr, + SocketServer* external, + const SocketAddress external_addrs[4], + NATType nat_type, bool exp_same) { - webrtc::Thread th_int(internal); - webrtc::Thread th_ext(external); + Thread th_int(internal); + Thread th_ext(external); th_int.Start(); th_ext.Start(); - webrtc::SocketAddress server_addr = internal_addr; + SocketAddress server_addr = internal_addr; server_addr.SetPort(0); // Auto-select a port - webrtc::NATServer* nat = - new webrtc::NATServer(nat_type, th_int, internal, server_addr, - server_addr, th_ext, external, external_addrs[0]); - webrtc::NATSocketFactory* natsf = new webrtc::NATSocketFactory( + NATServer* nat = + new NATServer(nat_type, th_int, internal, server_addr, server_addr, + th_ext, external, external_addrs[0]); + NATSocketFactory* natsf = new NATSocketFactory( internal, nat->internal_udp_address(), nat->internal_tcp_address()); - webrtc::TestClient* in; + TestClient* in; th_int.BlockingCall([&] { in = CreateTestClient(natsf, internal_addr); }); - webrtc::TestClient* out[4]; + TestClient* out[4]; th_ext.BlockingCall([&] { for (int i = 0; i < 4; i++) out[i] = CreateTestClient(external, external_addrs[i]); @@ -100,13 +99,13 @@ void TestSend(webrtc::SocketServer* internal, size_t len = strlen(buf); th_int.BlockingCall([&] { in->SendTo(buf, len, out[0]->address()); }); - webrtc::SocketAddress trans_addr; + SocketAddress trans_addr; th_ext.BlockingCall( [&] { EXPECT_TRUE(out[0]->CheckNextPacket(buf, len, &trans_addr)); }); for (int i = 1; i < 4; i++) { th_int.BlockingCall([&] { in->SendTo(buf, len, out[i]->address()); }); - webrtc::SocketAddress trans_addr2; + SocketAddress trans_addr2; th_ext.BlockingCall([&] { EXPECT_TRUE(out[i]->CheckNextPacket(buf, len, &trans_addr2)); bool are_same = (trans_addr == trans_addr2); @@ -128,30 +127,30 @@ void TestSend(webrtc::SocketServer* internal, // Tests that when sending from external_addrs to internal_addr, the packet // is delivered according to the specified filter_ip and filter_port rules. -void TestRecv(webrtc::SocketServer* internal, - const webrtc::SocketAddress& internal_addr, - webrtc::SocketServer* external, - const webrtc::SocketAddress external_addrs[4], - webrtc::NATType nat_type, +void TestRecv(SocketServer* internal, + const SocketAddress& internal_addr, + SocketServer* external, + const SocketAddress external_addrs[4], + NATType nat_type, bool filter_ip, bool filter_port) { - webrtc::Thread th_int(internal); - webrtc::Thread th_ext(external); + Thread th_int(internal); + Thread th_ext(external); - webrtc::SocketAddress server_addr = internal_addr; + SocketAddress server_addr = internal_addr; server_addr.SetPort(0); // Auto-select a port th_int.Start(); th_ext.Start(); - webrtc::NATServer* nat = - new webrtc::NATServer(nat_type, th_int, internal, server_addr, - server_addr, th_ext, external, external_addrs[0]); - webrtc::NATSocketFactory* natsf = new webrtc::NATSocketFactory( + NATServer* nat = + new NATServer(nat_type, th_int, internal, server_addr, server_addr, + th_ext, external, external_addrs[0]); + NATSocketFactory* natsf = new NATSocketFactory( internal, nat->internal_udp_address(), nat->internal_tcp_address()); - webrtc::TestClient* in = nullptr; + TestClient* in = nullptr; th_int.BlockingCall([&] { in = CreateTestClient(natsf, internal_addr); }); - webrtc::TestClient* out[4]; + TestClient* out[4]; th_ext.BlockingCall([&] { for (int i = 0; i < 4; i++) out[i] = CreateTestClient(external, external_addrs[i]); @@ -161,7 +160,7 @@ void TestRecv(webrtc::SocketServer* internal, size_t len = strlen(buf); th_int.BlockingCall([&] { in->SendTo(buf, len, out[0]->address()); }); - webrtc::SocketAddress trans_addr; + SocketAddress trans_addr; th_ext.BlockingCall( [&] { EXPECT_TRUE(out[0]->CheckNextPacket(buf, len, &trans_addr)); }); @@ -190,74 +189,69 @@ void TestRecv(webrtc::SocketServer* internal, } // Tests that NATServer allocates bindings properly. -void TestBindings(webrtc::SocketServer* internal, - const webrtc::SocketAddress& internal_addr, - webrtc::SocketServer* external, - const webrtc::SocketAddress external_addrs[4]) { +void TestBindings(SocketServer* internal, + const SocketAddress& internal_addr, + SocketServer* external, + const SocketAddress external_addrs[4]) { + TestSend(internal, internal_addr, external, external_addrs, NAT_OPEN_CONE, + true); TestSend(internal, internal_addr, external, external_addrs, - webrtc::NAT_OPEN_CONE, true); + NAT_ADDR_RESTRICTED, true); TestSend(internal, internal_addr, external, external_addrs, - webrtc::NAT_ADDR_RESTRICTED, true); - TestSend(internal, internal_addr, external, external_addrs, - webrtc::NAT_PORT_RESTRICTED, true); - TestSend(internal, internal_addr, external, external_addrs, - webrtc::NAT_SYMMETRIC, false); + NAT_PORT_RESTRICTED, true); + TestSend(internal, internal_addr, external, external_addrs, NAT_SYMMETRIC, + false); } // Tests that NATServer filters packets properly. -void TestFilters(webrtc::SocketServer* internal, - const webrtc::SocketAddress& internal_addr, - webrtc::SocketServer* external, - const webrtc::SocketAddress external_addrs[4]) { - TestRecv(internal, internal_addr, external, external_addrs, - webrtc::NAT_OPEN_CONE, false, false); +void TestFilters(SocketServer* internal, + const SocketAddress& internal_addr, + SocketServer* external, + const SocketAddress external_addrs[4]) { + TestRecv(internal, internal_addr, external, external_addrs, NAT_OPEN_CONE, + false, false); TestRecv(internal, internal_addr, external, external_addrs, - webrtc::NAT_ADDR_RESTRICTED, true, false); + NAT_ADDR_RESTRICTED, true, false); TestRecv(internal, internal_addr, external, external_addrs, - webrtc::NAT_PORT_RESTRICTED, true, true); - TestRecv(internal, internal_addr, external, external_addrs, - webrtc::NAT_SYMMETRIC, true, true); + NAT_PORT_RESTRICTED, true, true); + TestRecv(internal, internal_addr, external, external_addrs, NAT_SYMMETRIC, + true, true); } -bool TestConnectivity(const webrtc::SocketAddress& src, - const webrtc::IPAddress& dst) { +bool TestConnectivity(const SocketAddress& src, const IPAddress& dst) { // The physical NAT tests require connectivity to the selected ip from the // internal address used for the NAT. Things like firewalls can break that, so // check to see if it's worth even trying with this ip. - std::unique_ptr pss( - new webrtc::PhysicalSocketServer()); - std::unique_ptr client( - pss->CreateSocket(src.family(), SOCK_DGRAM)); - std::unique_ptr server( - pss->CreateSocket(src.family(), SOCK_DGRAM)); - if (client->Bind(webrtc::SocketAddress(src.ipaddr(), 0)) != 0 || - server->Bind(webrtc::SocketAddress(dst, 0)) != 0) { + std::unique_ptr pss(new PhysicalSocketServer()); + std::unique_ptr client(pss->CreateSocket(src.family(), SOCK_DGRAM)); + std::unique_ptr server(pss->CreateSocket(src.family(), SOCK_DGRAM)); + if (client->Bind(SocketAddress(src.ipaddr(), 0)) != 0 || + server->Bind(SocketAddress(dst, 0)) != 0) { return false; } const char* buf = "hello other socket"; size_t len = strlen(buf); int sent = client->SendTo(buf, len, server->GetLocalAddress()); - webrtc::Thread::Current()->SleepMs(100); + Thread::Current()->SleepMs(100); Buffer payload; - webrtc::Socket::ReceiveBuffer receive_buffer(payload); + Socket::ReceiveBuffer receive_buffer(payload); int received = server->RecvFrom(receive_buffer); return received == sent && ::memcmp(buf, payload.data(), len) == 0; } -void TestPhysicalInternal(const webrtc::SocketAddress& int_addr) { - webrtc::AutoThread main_thread; - webrtc::PhysicalSocketServer socket_server; - webrtc::BasicNetworkManager network_manager(CreateEnvironment(), - &socket_server); +void TestPhysicalInternal(const SocketAddress& int_addr) { + AutoThread main_thread; + PhysicalSocketServer socket_server; + BasicNetworkManager network_manager(CreateEnvironment(), &socket_server); network_manager.StartUpdating(); // Process pending messages so the network list is updated. - webrtc::Thread::Current()->ProcessMessages(0); + Thread::Current()->ProcessMessages(0); - std::vector networks = network_manager.GetNetworks(); + std::vector networks = network_manager.GetNetworks(); networks.erase(std::remove_if(networks.begin(), networks.end(), - [](const webrtc::Network* network) { - return webrtc::kDefaultNetworkIgnoreMask & + [](const Network* network) { + return kDefaultNetworkIgnoreMask & network->type(); }), networks.end()); @@ -266,12 +260,12 @@ void TestPhysicalInternal(const webrtc::SocketAddress& int_addr) { return; } - webrtc::SocketAddress ext_addr1(int_addr); - webrtc::SocketAddress ext_addr2; + SocketAddress ext_addr1(int_addr); + SocketAddress ext_addr2; // Find an available IP with matching family. The test breaks if int_addr // can't talk to ip, so check for connectivity as well. for (const Network* const network : networks) { - const webrtc::IPAddress& ip = network->GetBestIP(); + const IPAddress& ip = network->GetBestIP(); if (ip.family() == int_addr.family() && TestConnectivity(int_addr, ip)) { ext_addr2.SetIP(ip); break; @@ -285,26 +279,24 @@ void TestPhysicalInternal(const webrtc::SocketAddress& int_addr) { RTC_LOG(LS_INFO) << "selected ip " << ext_addr2.ipaddr().ToString(); - webrtc::SocketAddress ext_addrs[4] = { - webrtc::SocketAddress(ext_addr1), webrtc::SocketAddress(ext_addr2), - webrtc::SocketAddress(ext_addr1), webrtc::SocketAddress(ext_addr2)}; + SocketAddress ext_addrs[4] = { + SocketAddress(ext_addr1), SocketAddress(ext_addr2), + SocketAddress(ext_addr1), SocketAddress(ext_addr2)}; - std::unique_ptr int_pss( - new webrtc::PhysicalSocketServer()); - std::unique_ptr ext_pss( - new webrtc::PhysicalSocketServer()); + std::unique_ptr int_pss(new PhysicalSocketServer()); + std::unique_ptr ext_pss(new PhysicalSocketServer()); TestBindings(int_pss.get(), int_addr, ext_pss.get(), ext_addrs); TestFilters(int_pss.get(), int_addr, ext_pss.get(), ext_addrs); } TEST(NatTest, TestPhysicalIPv4) { - TestPhysicalInternal(webrtc::SocketAddress("127.0.0.1", 0)); + TestPhysicalInternal(SocketAddress("127.0.0.1", 0)); } TEST(NatTest, TestPhysicalIPv6) { - if (webrtc::HasIPv6Enabled()) { - TestPhysicalInternal(webrtc::SocketAddress("::1", 0)); + if (HasIPv6Enabled()) { + TestPhysicalInternal(SocketAddress("::1", 0)); } else { RTC_LOG(LS_WARNING) << "No IPv6, skipping"; } @@ -312,25 +304,23 @@ TEST(NatTest, TestPhysicalIPv6) { namespace { -class TestVirtualSocketServer : public webrtc::VirtualSocketServer { +class TestVirtualSocketServer : public VirtualSocketServer { public: // Expose this publicly - webrtc::IPAddress GetNextIP(int af) { - return webrtc::VirtualSocketServer::GetNextIP(af); - } + IPAddress GetNextIP(int af) { return VirtualSocketServer::GetNextIP(af); } }; } // namespace void TestVirtualInternal(int family) { - webrtc::AutoThread main_thread; + AutoThread main_thread; std::unique_ptr int_vss( new TestVirtualSocketServer()); std::unique_ptr ext_vss( new TestVirtualSocketServer()); - webrtc::SocketAddress int_addr; - webrtc::SocketAddress ext_addrs[4]; + SocketAddress int_addr; + SocketAddress ext_addrs[4]; int_addr.SetIP(int_vss->GetNextIP(family)); ext_addrs[0].SetIP(ext_vss->GetNextIP(int_addr.family())); ext_addrs[1].SetIP(ext_vss->GetNextIP(int_addr.family())); @@ -346,7 +336,7 @@ TEST(NatTest, TestVirtualIPv4) { } TEST(NatTest, TestVirtualIPv6) { - if (webrtc::HasIPv6Enabled()) { + if (HasIPv6Enabled()) { TestVirtualInternal(AF_INET6); } else { RTC_LOG(LS_WARNING) << "No IPv6, skipping"; @@ -361,48 +351,48 @@ class NatTcpTest : public ::testing::Test, public sigslot::has_slots<> { connected_(false), int_vss_(new TestVirtualSocketServer()), ext_vss_(new TestVirtualSocketServer()), - int_thread_(new webrtc::Thread(int_vss_.get())), - ext_thread_(new webrtc::Thread(ext_vss_.get())), - nat_(new webrtc::NATServer(webrtc::NAT_OPEN_CONE, - *int_thread_, - int_vss_.get(), - int_addr_, - int_addr_, - *ext_thread_, - ext_vss_.get(), - ext_addr_)), - natsf_(new webrtc::NATSocketFactory(int_vss_.get(), - nat_->internal_udp_address(), - nat_->internal_tcp_address())) { + int_thread_(new Thread(int_vss_.get())), + ext_thread_(new Thread(ext_vss_.get())), + nat_(new NATServer(NAT_OPEN_CONE, + *int_thread_, + int_vss_.get(), + int_addr_, + int_addr_, + *ext_thread_, + ext_vss_.get(), + ext_addr_)), + natsf_(new NATSocketFactory(int_vss_.get(), + nat_->internal_udp_address(), + nat_->internal_tcp_address())) { int_thread_->Start(); ext_thread_->Start(); } - void OnConnectEvent(webrtc::Socket* socket) { connected_ = true; } + void OnConnectEvent(Socket* socket) { connected_ = true; } - void OnAcceptEvent(webrtc::Socket* socket) { + void OnAcceptEvent(Socket* socket) { accepted_.reset(server_->Accept(nullptr)); } - void OnCloseEvent(webrtc::Socket* socket, int error) {} + void OnCloseEvent(Socket* socket, int error) {} void ConnectEvents() { server_->SignalReadEvent.connect(this, &NatTcpTest::OnAcceptEvent); client_->SignalConnectEvent.connect(this, &NatTcpTest::OnConnectEvent); } - webrtc::SocketAddress int_addr_; - webrtc::SocketAddress ext_addr_; + SocketAddress int_addr_; + SocketAddress ext_addr_; bool connected_; std::unique_ptr int_vss_; std::unique_ptr ext_vss_; - std::unique_ptr int_thread_; - std::unique_ptr ext_thread_; - std::unique_ptr nat_; - std::unique_ptr natsf_; - std::unique_ptr client_; - std::unique_ptr server_; - std::unique_ptr accepted_; + std::unique_ptr int_thread_; + std::unique_ptr ext_thread_; + std::unique_ptr nat_; + std::unique_ptr natsf_; + std::unique_ptr client_; + std::unique_ptr server_; + std::unique_ptr accepted_; }; TEST_F(NatTcpTest, DISABLED_TestConnectOut) { @@ -416,22 +406,19 @@ TEST_F(NatTcpTest, DISABLED_TestConnectOut) { ConnectEvents(); - EXPECT_THAT( - webrtc::WaitUntil([&] { return connected_; }, ::testing::IsTrue()), - webrtc::IsRtcOk()); + EXPECT_THAT(WaitUntil([&] { return connected_; }, ::testing::IsTrue()), + IsRtcOk()); EXPECT_EQ(client_->GetRemoteAddress(), server_->GetLocalAddress()); EXPECT_EQ(accepted_->GetRemoteAddress().ipaddr(), ext_addr_.ipaddr()); - std::unique_ptr in( - CreateTCPTestClient(client_.release())); - std::unique_ptr out( - CreateTCPTestClient(accepted_.release())); + std::unique_ptr in(CreateTCPTestClient(client_.release())); + std::unique_ptr out(CreateTCPTestClient(accepted_.release())); const char* buf = "test_packet"; size_t len = strlen(buf); in->Send(buf, len); - webrtc::SocketAddress trans_addr; + SocketAddress trans_addr; EXPECT_TRUE(out->CheckNextPacket(buf, len, &trans_addr)); out->Send(buf, len); diff --git a/p2p/test/test_stun_server.h b/p2p/test/test_stun_server.h index b65bc85f0f..9cee166f68 100644 --- a/p2p/test/test_stun_server.h +++ b/p2p/test/test_stun_server.h @@ -27,8 +27,7 @@ namespace webrtc { class TestStunServer : StunServer { public: using StunServerPtr = - std::unique_ptr>; + std::unique_ptr>; static StunServerPtr Create(SocketServer* ss, const SocketAddress& addr, Thread& network_thread); diff --git a/p2p/test/test_turn_server.h b/p2p/test/test_turn_server.h index e4165001d8..6f26b3697c 100644 --- a/p2p/test/test_turn_server.h +++ b/p2p/test/test_turn_server.h @@ -64,7 +64,7 @@ class TestTurnServer : public TurnAuthInterface { SocketFactory* socket_factory, const SocketAddress& int_addr, const SocketAddress& udp_ext_addr, - ProtocolType int_protocol = webrtc::PROTO_UDP, + ProtocolType int_protocol = PROTO_UDP, bool ignore_bad_cert = true, absl::string_view common_name = "test turn server") : server_(thread), socket_factory_(socket_factory) { @@ -103,23 +103,23 @@ class TestTurnServer : public TurnAuthInterface { bool ignore_bad_cert = true, absl::string_view common_name = "test turn server") { RTC_DCHECK(thread_checker_.IsCurrent()); - if (proto == webrtc::PROTO_UDP) { + if (proto == PROTO_UDP) { server_.AddInternalSocket( AsyncUDPSocket::Create(socket_factory_, int_addr), proto); - } else if (proto == webrtc::PROTO_TCP || proto == webrtc::PROTO_TLS) { + } else if (proto == PROTO_TCP || proto == PROTO_TLS) { // For TCP we need to create a server socket which can listen for incoming // new connections. Socket* socket = socket_factory_->CreateSocket(AF_INET, SOCK_STREAM); socket->Bind(int_addr); socket->Listen(5); - if (proto == webrtc::PROTO_TLS) { + if (proto == PROTO_TLS) { // For TLS, wrap the TCP socket with an SSL adapter. The adapter must // be configured with a self-signed certificate for testing. // Additionally, the client will not present a valid certificate, so we // must not fail when checking the peer's identity. std::unique_ptr ssl_adapter_factory = SSLAdapterFactory::Create(); - ssl_adapter_factory->SetRole(webrtc::SSL_SERVER); + ssl_adapter_factory->SetRole(SSL_SERVER); ssl_adapter_factory->SetIdentity( SSLIdentity::Create(common_name, KeyParams())); ssl_adapter_factory->SetIgnoreBadCert(ignore_bad_cert); diff --git a/p2p/test/turn_server.h b/p2p/test/turn_server.h index 0a74d52650..59397a6764 100644 --- a/p2p/test/turn_server.h +++ b/p2p/test/turn_server.h @@ -51,7 +51,7 @@ const int TURN_SERVER_PORT = 3478; // Encapsulates the client's connection to the server. class TurnServerConnection { public: - TurnServerConnection() : proto_(webrtc::PROTO_UDP), socket_(NULL) {} + TurnServerConnection() : proto_(PROTO_UDP), socket_(NULL) {} TurnServerConnection(const SocketAddress& src, ProtocolType proto, AsyncPacketSocket* socket); diff --git a/pc/BUILD.gn b/pc/BUILD.gn index 704aa2ad87..9b4f1ce01f 100644 --- a/pc/BUILD.gn +++ b/pc/BUILD.gn @@ -291,6 +291,7 @@ rtc_library("jsep_transport_controller") { "../api:ice_transport_factory", "../api:ice_transport_interface", "../api:libjingle_peerconnection_api", + "../api:local_network_access_permission", "../api:rtc_error", "../api:rtp_parameters", "../api:scoped_refptr", @@ -1215,6 +1216,7 @@ rtc_library("peer_connection") { "../api:ice_transport_interface", "../api:libjingle_logging_api", "../api:libjingle_peerconnection_api", + "../api:local_network_access_permission", "../api:make_ref_counted", "../api:media_stream_interface", "../api:rtc_error", @@ -1425,7 +1427,6 @@ rtc_library("webrtc_sdp") { "../rtc_base:crypto_random", "../rtc_base:ip_address", "../rtc_base:logging", - "../rtc_base:macromagic", "../rtc_base:net_helper", "../rtc_base:net_helpers", "../rtc_base:network_constants", @@ -1434,6 +1435,7 @@ rtc_library("webrtc_sdp") { "../rtc_base:stringutils", "../rtc_base/system:rtc_export", "//third_party/abseil-cpp/absl/algorithm:container", + "//third_party/abseil-cpp/absl/base:nullability", "//third_party/abseil-cpp/absl/strings", "//third_party/abseil-cpp/absl/strings:string_view", ] @@ -1491,7 +1493,6 @@ rtc_library("ice_server_parsing") { "../rtc_base:checks", "../rtc_base:ip_address", "../rtc_base:logging", - "../rtc_base:macromagic", "../rtc_base:socket_address", "../rtc_base:stringutils", "../rtc_base/system:rtc_export", @@ -2132,6 +2133,7 @@ if (rtc_include_tests && !build_with_chromium) { "../api/task_queue", "../api/task_queue:pending_task_safety_flag", "../api/transport:datagram_transport_interface", + "../api/transport:ecn_marking", "../api/transport:enums", "../api/units:time_delta", "../api/video:recordable_encoded_frame", @@ -2173,7 +2175,6 @@ if (rtc_include_tests && !build_with_chromium) { "../rtc_base:checks", "../rtc_base:copy_on_write_buffer", "../rtc_base:logging", - "../rtc_base:macromagic", "../rtc_base:net_helper", "../rtc_base:network_route", "../rtc_base:rtc_base_tests_utils", @@ -2187,14 +2188,12 @@ if (rtc_include_tests && !build_with_chromium) { "../rtc_base:threading", "../rtc_base:unique_id_generator", "../rtc_base/containers:flat_set", - "../rtc_base/network:ecn_marking", "../rtc_base/network:received_packet", "../rtc_base/network:sent_packet", "../rtc_base/third_party/sigslot", "../system_wrappers:metrics", - "../test:explicit_key_value_config", + "../test:create_test_field_trials", "../test:run_loop", - "../test:scoped_key_value_config", "../test:test_main", "../test:test_support", "../test:wait_until", @@ -2272,9 +2271,11 @@ if (rtc_include_tests && !build_with_chromium) { "../rtc_base:threading", "../rtc_base:timeutils", "../system_wrappers", + "../test:create_test_field_trials", "../test:test_support", "../test:wait_until", "//third_party/abseil-cpp/absl/strings", + "//third_party/abseil-cpp/absl/strings:string_view", ] } @@ -2563,7 +2564,6 @@ if (rtc_include_tests && !build_with_chromium) { "../rtc_base:gunit_helpers", "../rtc_base:ip_address", "../rtc_base:logging", - "../rtc_base:macromagic", "../rtc_base:net_helper", "../rtc_base:network", "../rtc_base:network_constants", @@ -2590,14 +2590,17 @@ if (rtc_include_tests && !build_with_chromium) { "../system_wrappers", "../system_wrappers:metrics", "../test:audio_codec_mocks", + "../test:create_test_field_trials", "../test:rtc_expect_death", "../test:run_loop", "../test:test_support", "../test:wait_until", "../test/pc/sctp:fake_sctp_transport", + "scenario_tests:pc_scenario_tests", "//third_party/abseil-cpp/absl/algorithm:container", "//third_party/abseil-cpp/absl/memory", "//third_party/abseil-cpp/absl/strings", + "//third_party/abseil-cpp/absl/strings:str_format", "//third_party/abseil-cpp/absl/strings:string_view", "//third_party/jsoncpp", ] @@ -2730,6 +2733,7 @@ if (rtc_include_tests && !build_with_chromium) { "../rtc_base:threading", "../rtc_base:timeutils", "../system_wrappers:metrics", + "../test:create_test_field_trials", "../test:test_support", "../test:wait_until", "//third_party/abseil-cpp/absl/functional:any_invocable", @@ -2820,6 +2824,7 @@ if (rtc_include_tests && !build_with_chromium) { "../api:create_peerconnection_factory", "../api:data_channel_event_observer_interface", "../api:dtls_transport_interface", + "../api:field_trials", "../api:field_trials_view", "../api:field_trials_view", "../api:frame_transformer_interface", @@ -2908,8 +2913,8 @@ if (rtc_include_tests && !build_with_chromium) { "../rtc_base/task_utils:repeating_task", "../rtc_base/third_party/sigslot", "../system_wrappers", + "../test:create_test_field_trials", "../test:frame_generator_capturer", - "../test:scoped_key_value_config", "../test:test_support", "../test:wait_until", "//testing/gmock", @@ -2940,6 +2945,7 @@ if (rtc_include_tests && !build_with_chromium) { "../api:create_network_emulation_manager", "../api:create_peer_connection_quality_test_frame_generator", "../api:create_peerconnection_quality_test_fixture", + "../api:field_trials", "../api:frame_generator_api", "../api:function_view", "../api:media_stream_interface", @@ -2966,8 +2972,6 @@ if (rtc_include_tests && !build_with_chromium) { "../rtc_base:logging", "../rtc_base/containers:flat_map", "../system_wrappers", - "../system_wrappers:field_trial", - "../test:field_trial", "../test:fileutils", "../test:test_main", "../test:test_support", diff --git a/pc/audio_rtp_receiver_unittest.cc b/pc/audio_rtp_receiver_unittest.cc index b056bdf07e..375b8a4faf 100644 --- a/pc/audio_rtp_receiver_unittest.cc +++ b/pc/audio_rtp_receiver_unittest.cc @@ -49,7 +49,7 @@ class AudioRtpReceiverTest : public ::testing::Test { EXPECT_CALL(receive_channel_, SetBaseMinimumPlayoutDelayMs(kSsrc, _)); } - ~AudioRtpReceiverTest() { + ~AudioRtpReceiverTest() override { EXPECT_CALL(receive_channel_, SetOutputVolume(kSsrc, kVolumeMuted)); receiver_->SetMediaChannel(nullptr); } diff --git a/pc/channel.cc b/pc/channel.cc index 1ab970f245..bccd1e2480 100644 --- a/pc/channel.cc +++ b/pc/channel.cc @@ -99,11 +99,7 @@ void MediaChannelParametersFromMediaDescription( desc->type() == MediaType::VIDEO); params->is_stream_active = is_stream_active; params->codecs = desc->codecs(); - // TODO(bugs.webrtc.org/11513): See if we really need - // rtp_header_extensions_set() and remove it if we don't. - if (desc->rtp_header_extensions_set()) { - params->extensions = extensions; - } + params->extensions = extensions; params->rtcp.reduced_size = desc->rtcp_reduced_size(); params->rtcp.remote_estimate = desc->remote_estimate(); } diff --git a/pc/channel_unittest.cc b/pc/channel_unittest.cc index 0f52078245..e3488a98a9 100644 --- a/pc/channel_unittest.cc +++ b/pc/channel_unittest.cc @@ -23,6 +23,7 @@ #include "api/array_view.h" #include "api/audio_options.h" #include "api/crypto/crypto_options.h" +#include "api/field_trials.h" #include "api/jsep.h" #include "api/rtp_headers.h" #include "api/rtp_parameters.h" @@ -48,7 +49,6 @@ #include "pc/rtp_transport.h" #include "pc/rtp_transport_internal.h" #include "pc/session_description.h" -#include "rtc_base/arraysize.h" #include "rtc_base/async_packet_socket.h" #include "rtc_base/buffer.h" #include "rtc_base/byte_order.h" @@ -61,18 +61,21 @@ #include "rtc_base/third_party/sigslot/sigslot.h" #include "rtc_base/thread.h" #include "rtc_base/unique_id_generator.h" +#include "test/create_test_field_trials.h" #include "test/gmock.h" #include "test/gtest.h" -#include "test/scoped_key_value_config.h" namespace { using ::testing::AllOf; using ::testing::ElementsAre; using ::testing::Field; +using ::webrtc::ArrayView; +using ::webrtc::CreateTestFieldTrials; using ::webrtc::DtlsTransportInternal; using ::webrtc::FakeVoiceMediaReceiveChannel; using ::webrtc::FakeVoiceMediaSendChannel; +using ::webrtc::FieldTrials; using ::webrtc::RidDescription; using ::webrtc::RidDirection; using ::webrtc::RtpTransceiverDirection; @@ -161,7 +164,7 @@ class ChannelTest : public ::testing::Test, public sigslot::has_slots<> { RTC_DCHECK(network_thread_); } - ~ChannelTest() { + ~ChannelTest() override { if (network_thread_) { SendTask(network_thread_, [this]() { network_thread_safety_->SetNotAlive(); @@ -1206,11 +1209,9 @@ class ChannelTest : public ::testing::Test, public sigslot::has_slots<> { EXPECT_TRUE(CheckNoRtp2()); } - void SendBundleToBundle(const int* pl_types, - int len, + void SendBundleToBundle(ArrayView pl_types, bool rtcp_mux, bool secure) { - ASSERT_EQ(2, len); int sequence_number1_1 = 0, sequence_number2_2 = 0; // Only pl_type1 was added to the bundle filter for both `channel1_` // and `channel2_`. @@ -1594,7 +1595,7 @@ class ChannelTest : public ::testing::Test, public sigslot::has_slots<> { webrtc::Buffer rtcp_packet_; webrtc::CandidatePairInterface* last_selected_candidate_pair_; webrtc::UniqueRandomIdGenerator ssrc_generator_; - webrtc::test::ScopedKeyValueConfig field_trials_; + FieldTrials field_trials_ = CreateTestFieldTrials(); }; template <> @@ -1853,19 +1854,19 @@ TEST_F(VoiceChannelSingleThreadTest, TestOnTransportReadyToSend) { } TEST_F(VoiceChannelSingleThreadTest, SendBundleToBundle) { - Base::SendBundleToBundle(kAudioPts, arraysize(kAudioPts), false, false); + Base::SendBundleToBundle(kAudioPts, false, false); } TEST_F(VoiceChannelSingleThreadTest, SendBundleToBundleSecure) { - Base::SendBundleToBundle(kAudioPts, arraysize(kAudioPts), false, true); + Base::SendBundleToBundle(kAudioPts, false, true); } TEST_F(VoiceChannelSingleThreadTest, SendBundleToBundleWithRtcpMux) { - Base::SendBundleToBundle(kAudioPts, arraysize(kAudioPts), true, false); + Base::SendBundleToBundle(kAudioPts, true, false); } TEST_F(VoiceChannelSingleThreadTest, SendBundleToBundleWithRtcpMuxSecure) { - Base::SendBundleToBundle(kAudioPts, arraysize(kAudioPts), true, true); + Base::SendBundleToBundle(kAudioPts, true, true); } TEST_F(VoiceChannelSingleThreadTest, DefaultMaxBitrateIsUnlimited) { @@ -1994,19 +1995,19 @@ TEST_F(VoiceChannelDoubleThreadTest, TestOnTransportReadyToSend) { } TEST_F(VoiceChannelDoubleThreadTest, SendBundleToBundle) { - Base::SendBundleToBundle(kAudioPts, arraysize(kAudioPts), false, false); + Base::SendBundleToBundle(kAudioPts, false, false); } TEST_F(VoiceChannelDoubleThreadTest, SendBundleToBundleSecure) { - Base::SendBundleToBundle(kAudioPts, arraysize(kAudioPts), false, true); + Base::SendBundleToBundle(kAudioPts, false, true); } TEST_F(VoiceChannelDoubleThreadTest, SendBundleToBundleWithRtcpMux) { - Base::SendBundleToBundle(kAudioPts, arraysize(kAudioPts), true, false); + Base::SendBundleToBundle(kAudioPts, true, false); } TEST_F(VoiceChannelDoubleThreadTest, SendBundleToBundleWithRtcpMuxSecure) { - Base::SendBundleToBundle(kAudioPts, arraysize(kAudioPts), true, true); + Base::SendBundleToBundle(kAudioPts, true, true); } TEST_F(VoiceChannelDoubleThreadTest, DefaultMaxBitrateIsUnlimited) { @@ -2125,19 +2126,19 @@ TEST_F(VideoChannelSingleThreadTest, TestReceivePrAnswer) { } TEST_F(VideoChannelSingleThreadTest, SendBundleToBundle) { - Base::SendBundleToBundle(kVideoPts, arraysize(kVideoPts), false, false); + Base::SendBundleToBundle(kVideoPts, false, false); } TEST_F(VideoChannelSingleThreadTest, SendBundleToBundleSecure) { - Base::SendBundleToBundle(kVideoPts, arraysize(kVideoPts), false, true); + Base::SendBundleToBundle(kVideoPts, false, true); } TEST_F(VideoChannelSingleThreadTest, SendBundleToBundleWithRtcpMux) { - Base::SendBundleToBundle(kVideoPts, arraysize(kVideoPts), true, false); + Base::SendBundleToBundle(kVideoPts, true, false); } TEST_F(VideoChannelSingleThreadTest, SendBundleToBundleWithRtcpMuxSecure) { - Base::SendBundleToBundle(kVideoPts, arraysize(kVideoPts), true, true); + Base::SendBundleToBundle(kVideoPts, true, true); } TEST_F(VideoChannelSingleThreadTest, TestOnTransportReadyToSend) { @@ -2570,19 +2571,19 @@ TEST_F(VideoChannelDoubleThreadTest, TestReceivePrAnswer) { } TEST_F(VideoChannelDoubleThreadTest, SendBundleToBundle) { - Base::SendBundleToBundle(kVideoPts, arraysize(kVideoPts), false, false); + Base::SendBundleToBundle(kVideoPts, false, false); } TEST_F(VideoChannelDoubleThreadTest, SendBundleToBundleSecure) { - Base::SendBundleToBundle(kVideoPts, arraysize(kVideoPts), false, true); + Base::SendBundleToBundle(kVideoPts, false, true); } TEST_F(VideoChannelDoubleThreadTest, SendBundleToBundleWithRtcpMux) { - Base::SendBundleToBundle(kVideoPts, arraysize(kVideoPts), true, false); + Base::SendBundleToBundle(kVideoPts, true, false); } TEST_F(VideoChannelDoubleThreadTest, SendBundleToBundleWithRtcpMuxSecure) { - Base::SendBundleToBundle(kVideoPts, arraysize(kVideoPts), true, true); + Base::SendBundleToBundle(kVideoPts, true, true); } TEST_F(VideoChannelDoubleThreadTest, TestOnTransportReadyToSend) { diff --git a/pc/codec_vendor_unittest.cc b/pc/codec_vendor_unittest.cc index 6e2ae36b53..8dd99f25a8 100644 --- a/pc/codec_vendor_unittest.cc +++ b/pc/codec_vendor_unittest.cc @@ -12,7 +12,6 @@ #include -#include #include #include @@ -34,6 +33,7 @@ #include "pc/rtp_parameters_conversion.h" #include "pc/session_description.h" #include "rtc_base/checks.h" +#include "test/create_test_field_trials.h" #include "test/gmock.h" #include "test/gtest.h" @@ -70,8 +70,8 @@ const Codec kAudioCodecsAnswer[] = { }; TEST(CodecVendorTest, TestSetAudioCodecs) { - std::unique_ptr trials = FieldTrials::CreateNoGlobal(""); - CodecVendor codec_vendor(nullptr, false, *trials); + FieldTrials trials = CreateTestFieldTrials(); + CodecVendor codec_vendor(nullptr, false, trials); std::vector send_codecs = MAKE_VECTOR(kAudioCodecs1); std::vector recv_codecs = MAKE_VECTOR(kAudioCodecs2); diff --git a/pc/congestion_control_integrationtest.cc b/pc/congestion_control_integrationtest.cc index d93a31924f..a0bb6a6997 100644 --- a/pc/congestion_control_integrationtest.cc +++ b/pc/congestion_control_integrationtest.cc @@ -12,9 +12,13 @@ // are correctly negotiated in the SDP offer/answer. #include +#include #include "absl/strings/str_cat.h" +#include "api/media_types.h" #include "api/peer_connection_interface.h" +#include "api/rtp_parameters.h" +#include "api/rtp_transceiver_direction.h" #include "api/test/rtc_error_matchers.h" #include "pc/test/integration_test_helpers.h" #include "test/gmock.h" @@ -23,11 +27,14 @@ namespace webrtc { -using testing::Eq; +using ::testing::Contains; +using ::testing::Eq; +using ::testing::Field; using ::testing::Gt; -using testing::HasSubstr; +using ::testing::HasSubstr; using ::testing::IsTrue; -using testing::Not; +using ::testing::Ne; +using ::testing::Not; class PeerConnectionCongestionControlTest : public PeerConnectionIntegrationBaseTest { @@ -126,4 +133,67 @@ TEST_F(PeerConnectionCongestionControlTest, TransportCcGetsUsed) { EXPECT_THAT(pc_internal->FeedbackAccordingToRfc8888CountForTesting(), Eq(0)); } +TEST_F(PeerConnectionCongestionControlTest, + DISABLED_CcfbGetsUsedCalleeToCaller) { + SetFieldTrials("WebRTC-RFC8888CongestionControlFeedback/Enabled/"); + ASSERT_TRUE(CreatePeerConnectionWrappers()); + ConnectFakeSignaling(); + callee()->AddVideoTrack(); + // Add transceivers to caller in order to accomodate reception + caller()->pc()->AddTransceiver(MediaType::VIDEO); + auto parameters = caller()->pc()->GetSenders()[0]->GetParameters(); + caller()->CreateAndSetAndSignalOffer(); + ASSERT_THAT(WaitUntil([&] { return SignalingStateStable(); }, IsTrue()), + IsRtcOk()); + + std::vector negotiated_header_extensions = + caller()->pc()->GetTransceivers()[0]->GetNegotiatedHeaderExtensions(); + EXPECT_THAT( + negotiated_header_extensions, + Not(Contains( + AllOf(Field("uri", &RtpHeaderExtensionCapability::uri, + RtpExtension::kTransportSequenceNumberUri), + Not(Field("direction", &RtpHeaderExtensionCapability::direction, + RtpTransceiverDirection::kStopped)))))) + << " in caller negotiated header extensions"; + + parameters = caller()->pc()->GetSenders()[0]->GetParameters(); + EXPECT_THAT(parameters.header_extensions, + Not(Contains(Field("uri", &RtpExtension::uri, + RtpExtension::kTransportSequenceNumberUri)))) + << " in caller sender parameters"; + parameters = caller()->pc()->GetReceivers()[0]->GetParameters(); + EXPECT_THAT(parameters.header_extensions, + Not(Contains(Field("uri", &RtpExtension::uri, + RtpExtension::kTransportSequenceNumberUri)))) + << " in caller receiver parameters"; + + parameters = callee()->pc()->GetSenders()[0]->GetParameters(); + EXPECT_THAT(parameters.header_extensions, + Not(Contains(Field("uri", &RtpExtension::uri, + RtpExtension::kTransportSequenceNumberUri)))) + << " in callee sender parameters"; + + parameters = callee()->pc()->GetReceivers()[0]->GetParameters(); + EXPECT_THAT(parameters.header_extensions, + Not(Contains(Field("uri", &RtpExtension::uri, + RtpExtension::kTransportSequenceNumberUri)))) + << " in callee receiver parameters"; + + MediaExpectations media_expectations; + media_expectations.CallerExpectsSomeVideo(); + ASSERT_TRUE(ExpectNewFrames(media_expectations)); + auto pc_internal = callee()->pc_internal(); + EXPECT_THAT( + WaitUntil( + [&] { + return pc_internal->FeedbackAccordingToRfc8888CountForTesting() > 2; + }, + IsTrue()), + IsRtcOk()); + // There should be no transport-cc generated. + EXPECT_THAT(pc_internal->FeedbackAccordingToTransportCcCountForTesting(), + Eq(0)); +} + } // namespace webrtc diff --git a/pc/data_channel_integrationtest.cc b/pc/data_channel_integrationtest.cc index e9476573b1..9b0800a41e 100644 --- a/pc/data_channel_integrationtest.cc +++ b/pc/data_channel_integrationtest.cc @@ -950,7 +950,7 @@ TEST_P(DataChannelIntegrationTest, SctpDataChannelToAudioVideoUpgrade) { ASSERT_TRUE(ExpectNewFrames(media_expectations)); } -static void MakeSpecCompliantSctpOffer( +void MakeSpecCompliantSctpOffer( std::unique_ptr& desc) { SctpDataContentDescription* dcd_offer = GetFirstSctpDataContentDescription(desc->description()); @@ -1638,7 +1638,7 @@ class DataChannelIntegrationTestUnifiedPlanFieldTrials } }; -static const char* kTrialsVariants[] = { +const char* kTrialsVariants[] = { "", "WebRTC-ForceDtls13/Enabled/", "WebRTC-IceHandshakeDtls/Enabled/", @@ -1771,8 +1771,7 @@ TEST_P(DataChannelIntegrationTestUnifiedPlanFieldTrials, // Forward turn ice candidate also to callee2. auto candidate = caller()->last_gathered_ice_candidate(); - std::string ice_sdp; - EXPECT_TRUE(candidate->ToString(&ice_sdp)); + std::string ice_sdp = candidate->ToString(); callee2->ReceiveIceMessage(candidate->sdp_mid(), candidate->sdp_mline_index(), ice_sdp); diff --git a/pc/dtls_srtp_transport_integrationtest.cc b/pc/dtls_srtp_transport_integrationtest.cc index 1b4990b978..2d3cafe7d6 100644 --- a/pc/dtls_srtp_transport_integrationtest.cc +++ b/pc/dtls_srtp_transport_integrationtest.cc @@ -17,6 +17,7 @@ #include "absl/strings/str_cat.h" #include "api/crypto/crypto_options.h" #include "api/dtls_transport_interface.h" +#include "api/field_trials.h" #include "api/scoped_refptr.h" #include "api/test/rtc_error_matchers.h" #include "api/units/time_delta.h" @@ -38,9 +39,9 @@ #include "rtc_base/ssl_identity.h" #include "rtc_base/ssl_stream_adapter.h" #include "rtc_base/thread.h" +#include "test/create_test_field_trials.h" #include "test/gmock.h" #include "test/gtest.h" -#include "test/scoped_key_value_config.h" #include "test/wait_until.h" const int kRtpAuthTagLen = 10; @@ -72,7 +73,7 @@ class DtlsSrtpTransportIntegrationTest : public ::testing::Test { srtp_transport_.RegisterRtpDemuxerSink(demuxer_criteria, &srtp_transport_observer_); } - ~DtlsSrtpTransportIntegrationTest() { + ~DtlsSrtpTransportIntegrationTest() override { dtls_srtp_transport_.UnregisterRtpDemuxerSink( &dtls_srtp_transport_observer_); srtp_transport_.UnregisterRtpDemuxerSink(&srtp_transport_observer_); @@ -219,7 +220,7 @@ class DtlsSrtpTransportIntegrationTest : public ::testing::Test { private: webrtc::AutoThread main_thread_; webrtc::ScopedFakeClock fake_clock_; - webrtc::test::ScopedKeyValueConfig field_trials_; + webrtc::FieldTrials field_trials_ = webrtc::CreateTestFieldTrials(); std::unique_ptr client_ice_transport_; std::unique_ptr server_ice_transport_; diff --git a/pc/dtls_srtp_transport_unittest.cc b/pc/dtls_srtp_transport_unittest.cc index 19499ab8d0..a4c27fe017 100644 --- a/pc/dtls_srtp_transport_unittest.cc +++ b/pc/dtls_srtp_transport_unittest.cc @@ -16,6 +16,7 @@ #include #include +#include "api/field_trials.h" #include "call/rtp_demuxer.h" #include "media/base/fake_rtp.h" #include "p2p/base/p2p_constants.h" @@ -34,14 +35,16 @@ #include "rtc_base/ssl_identity.h" #include "rtc_base/third_party/sigslot/sigslot.h" #include "rtc_base/thread.h" +#include "test/create_test_field_trials.h" #include "test/gtest.h" -#include "test/scoped_key_value_config.h" -using webrtc::DtlsSrtpTransport; +using ::webrtc::CreateTestFieldTrials; +using ::webrtc::DtlsSrtpTransport; using ::webrtc::FakeDtlsTransport; using ::webrtc::FakeIceTransport; -using webrtc::RtpTransport; -using webrtc::SrtpTransport; +using ::webrtc::FieldTrials; +using ::webrtc::RtpTransport; +using ::webrtc::SrtpTransport; const int kRtpAuthTagLen = 10; @@ -50,7 +53,7 @@ class DtlsSrtpTransportTest : public ::testing::Test, protected: DtlsSrtpTransportTest() {} - ~DtlsSrtpTransportTest() { + ~DtlsSrtpTransportTest() override { if (dtls_srtp_transport1_) { dtls_srtp_transport1_->UnregisterRtpDemuxerSink(&transport_observer1_); } @@ -270,7 +273,7 @@ class DtlsSrtpTransportTest : public ::testing::Test, webrtc::TransportObserver transport_observer2_; int sequence_number_ = 0; - webrtc::test::ScopedKeyValueConfig field_trials_; + FieldTrials field_trials_ = CreateTestFieldTrials(); }; // Tests that if RTCP muxing is enabled and transports are set after RTP diff --git a/pc/dtmf_sender_unittest.cc b/pc/dtmf_sender_unittest.cc index 6c442e1419..82b149b9db 100644 --- a/pc/dtmf_sender_unittest.cc +++ b/pc/dtmf_sender_unittest.cc @@ -123,7 +123,7 @@ class DtmfSenderTest : public ::testing::Test { dtmf_->RegisterObserver(observer_.get()); } - ~DtmfSenderTest() { + ~DtmfSenderTest() override { if (dtmf_) { dtmf_->UnregisterObserver(); } diff --git a/pc/ice_server_parsing.cc b/pc/ice_server_parsing.cc index c929a2f1cd..ee3b4467d2 100644 --- a/pc/ice_server_parsing.cc +++ b/pc/ice_server_parsing.cc @@ -26,7 +26,6 @@ #include "p2p/base/port.h" #include "p2p/base/port_allocator.h" #include "p2p/base/port_interface.h" -#include "rtc_base/arraysize.h" #include "rtc_base/checks.h" #include "rtc_base/ip_address.h" #include "rtc_base/logging.h" @@ -66,7 +65,7 @@ enum class ServiceType { INVALID, // Unknown. }; static_assert(static_cast(ServiceType::INVALID) == - arraysize(kValidIceServiceTypes), + std::size(kValidIceServiceTypes), "kValidIceServiceTypes must have as many strings as ServiceType " "has values."); @@ -90,7 +89,7 @@ std::tuple GetServiceTypeAndHostnameFromUri( RTC_LOG(LS_WARNING) << "Empty hostname in ICE URI: " << in_str; return {ServiceType::INVALID, ""}; } - for (size_t i = 0; i < arraysize(kValidIceServiceTypes); ++i) { + for (size_t i = 0; i < std::size(kValidIceServiceTypes); ++i) { if (in_str.compare(0, colonpos, kValidIceServiceTypes[i]) == 0) { return {static_cast(i), in_str.substr(colonpos + 1)}; } diff --git a/pc/jsep_ice_candidate.cc b/pc/jsep_ice_candidate.cc index 3245f45584..7809aa508d 100644 --- a/pc/jsep_ice_candidate.cc +++ b/pc/jsep_ice_candidate.cc @@ -14,68 +14,62 @@ #include #include +#include "absl/base/nullability.h" +#include "absl/strings/string_view.h" #include "api/candidate.h" +#include "api/jsep.h" #include "pc/webrtc_sdp.h" -// This file contains JsepIceCandidate-related functions that are not +// This file contains IceCandidate-related functions that are not // included in api/jsep_ice_candidate.cc. Some of these link to SDP // parsing/serializing functions, which some users may not want. // TODO(bugs.webrtc.org/12330): Merge the two .cc files somehow. namespace webrtc { -IceCandidateInterface* CreateIceCandidate(const std::string& sdp_mid, - int sdp_mline_index, - const std::string& sdp, - SdpParseError* error) { - JsepIceCandidate* jsep_ice = new JsepIceCandidate(sdp_mid, sdp_mline_index); - if (!jsep_ice->Initialize(sdp, error)) { - delete jsep_ice; +IceCandidate* CreateIceCandidate(const std::string& sdp_mid, + int sdp_mline_index, + const std::string& sdp, + SdpParseError* error) { + std::unique_ptr candidate = + IceCandidate::Create(sdp_mid, sdp_mline_index, sdp, error); + if (!candidate) { return nullptr; } - return jsep_ice; + return candidate.release(); } -std::unique_ptr CreateIceCandidate( - const std::string& sdp_mid, - int sdp_mline_index, - const Candidate& candidate) { - return std::make_unique(sdp_mid, sdp_mline_index, - candidate); +std::unique_ptr CreateIceCandidate(const std::string& sdp_mid, + int sdp_mline_index, + const Candidate& candidate) { + return std::make_unique(sdp_mid, sdp_mline_index, candidate); } -JsepIceCandidate::JsepIceCandidate(const std::string& sdp_mid, - int sdp_mline_index) - : sdp_mid_(sdp_mid), sdp_mline_index_(sdp_mline_index) {} - -JsepIceCandidate::JsepIceCandidate(const std::string& sdp_mid, - int sdp_mline_index, - const Candidate& candidate) - : sdp_mid_(sdp_mid), - sdp_mline_index_(sdp_mline_index), - candidate_(candidate) {} - -JsepIceCandidate::~JsepIceCandidate() {} +// static +std::unique_ptr IceCandidate::Create(absl::string_view mid, + int sdp_mline_index, + absl::string_view sdp, + SdpParseError* absl_nullable + error /*= nullptr*/) { + Candidate candidate; + if (!SdpDeserializeCandidate(mid, sdp, &candidate, error)) { + return nullptr; + } + return std::make_unique(mid, sdp_mline_index, candidate); +} -JsepCandidateCollection JsepCandidateCollection::Clone() const { - JsepCandidateCollection new_collection; +IceCandidateCollection IceCandidateCollection::Clone() const { + IceCandidateCollection new_collection; for (const auto& candidate : candidates_) { - new_collection.candidates_.push_back(std::make_unique( + new_collection.candidates_.push_back(std::make_unique( candidate->sdp_mid(), candidate->sdp_mline_index(), candidate->candidate())); } return new_collection; } -bool JsepIceCandidate::Initialize(const std::string& sdp, SdpParseError* err) { - return SdpDeserializeCandidate(sdp, this, err); -} - -bool JsepIceCandidate::ToString(std::string* out) const { - if (!out) - return false; - *out = SdpSerializeCandidate(*this); - return !out->empty(); +std::string IceCandidate::ToString() const { + return SdpSerializeCandidate(*this); } } // namespace webrtc diff --git a/pc/jsep_session_description.cc b/pc/jsep_session_description.cc index 48feb1012a..bbeb4c3c07 100644 --- a/pc/jsep_session_description.cc +++ b/pc/jsep_session_description.cc @@ -20,7 +20,6 @@ #include "absl/strings/string_view.h" #include "api/candidate.h" #include "api/jsep.h" -#include "api/jsep_ice_candidate.h" #include "p2p/base/p2p_constants.h" #include "p2p/base/transport_description.h" #include "p2p/base/transport_info.h" @@ -54,7 +53,7 @@ void UpdateConnectionAddress( int current_preference = 0; // Start with lowest preference. int current_family = AF_UNSPEC; for (size_t i = 0; i < candidate_collection.count(); ++i) { - const IceCandidateInterface* jsep_candidate = candidate_collection.at(i); + const IceCandidate* jsep_candidate = candidate_collection.at(i); if (jsep_candidate->candidate().component() != ICE_CANDIDATE_COMPONENT_RTP) { continue; @@ -219,20 +218,17 @@ std::unique_ptr JsepSessionDescription::Clone() return new_description; } -bool JsepSessionDescription::AddCandidate( - const IceCandidateInterface* candidate) { +bool JsepSessionDescription::AddCandidate(const IceCandidate* candidate) { if (!candidate) return false; size_t mediasection_index = 0; if (!GetMediasectionIndex(candidate, &mediasection_index)) { return false; } - if (mediasection_index >= number_of_mediasections()) - return false; - const std::string& content_name = + const std::string& mediasection_mid = description_->contents()[mediasection_index].mid(); const TransportInfo* transport_info = - description_->GetTransportInfoByName(content_name); + description_->GetTransportInfoByName(mediasection_mid); if (!transport_info) { return false; } @@ -245,14 +241,21 @@ bool JsepSessionDescription::AddCandidate( updated_candidate.set_password(transport_info->description.ice_pwd); } - std::unique_ptr updated_candidate_wrapper( - new JsepIceCandidate(candidate->sdp_mid(), - static_cast(mediasection_index), - updated_candidate)); + // Use `mediasection_mid` as the mid for the updated candidate. The + // `candidate->sdp_mid()` property *should* be the same. However, in some + // cases specifying an empty mid but a valid index is a way to add a candidate + // without knowing (or caring about) the mid. This is done in several tests. + RTC_DCHECK(candidate->sdp_mid().empty() || + candidate->sdp_mid() == mediasection_mid) + << "sdp_mid='" << candidate->sdp_mid() << "' mediasection_mid='" + << mediasection_mid << "'"; + auto updated_candidate_wrapper = std::make_unique( + mediasection_mid, static_cast(mediasection_index), + updated_candidate); if (!candidate_collection_[mediasection_index].HasCandidate( updated_candidate_wrapper.get())) { candidate_collection_[mediasection_index].add( - updated_candidate_wrapper.release()); + std::move(updated_candidate_wrapper)); UpdateConnectionAddress( candidate_collection_[mediasection_index], description_->contents()[mediasection_index].media_description()); @@ -261,6 +264,20 @@ bool JsepSessionDescription::AddCandidate( return true; } +bool JsepSessionDescription::RemoveCandidate(const IceCandidate* candidate) { + size_t mediasection_index = 0u; + if (!GetMediasectionIndex(candidate, &mediasection_index)) { + return false; + } + if (!candidate_collection_[mediasection_index].remove(candidate)) { + return false; + } + UpdateConnectionAddress( + candidate_collection_[mediasection_index], + description_->contents()[mediasection_index].media_description()); + return true; +} + size_t JsepSessionDescription::RemoveCandidates( const std::vector& candidates) { size_t num_removed = 0; @@ -299,9 +316,8 @@ bool JsepSessionDescription::ToString(std::string* out) const { return !out->empty(); } -bool JsepSessionDescription::GetMediasectionIndex( - const IceCandidateInterface* candidate, - size_t* index) { +bool JsepSessionDescription::GetMediasectionIndex(const IceCandidate* candidate, + size_t* index) { if (!candidate || !index) { return false; } diff --git a/pc/jsep_session_description_unittest.cc b/pc/jsep_session_description_unittest.cc index 789ece47fb..d561a3b1d3 100644 --- a/pc/jsep_session_description_unittest.cc +++ b/pc/jsep_session_description_unittest.cc @@ -21,7 +21,6 @@ #include "absl/strings/str_cat.h" #include "api/candidate.h" #include "api/jsep.h" -#include "api/jsep_ice_candidate.h" #include "media/base/codec.h" #include "p2p/base/p2p_constants.h" #include "p2p/base/transport_description.h" @@ -31,13 +30,14 @@ #include "rtc_base/crypto_random.h" #include "rtc_base/net_helper.h" #include "rtc_base/socket_address.h" +#include "test/gmock.h" #include "test/gtest.h" +using ::testing::NotNull; using ::testing::Values; +using webrtc::IceCandidate; using webrtc::IceCandidateCollection; -using webrtc::IceCandidateInterface; using webrtc::IceCandidateType; -using webrtc::JsepIceCandidate; using webrtc::JsepSessionDescription; using ::webrtc::MediaProtocolType; using webrtc::SdpType; @@ -85,7 +85,7 @@ CreateCricketSessionDescription() { class JsepSessionDescriptionTest : public ::testing::Test { protected: - virtual void SetUp() { + void SetUp() override { int port = 1234; webrtc::SocketAddress address("127.0.0.1", port++); webrtc::Candidate candidate(webrtc::ICE_CANDIDATE_COMPONENT_RTP, "udp", @@ -145,10 +145,10 @@ TEST_F(JsepSessionDescriptionTest, CloneWithCandidates) { webrtc::SocketAddress("::1", 1234), kCandidatePriority, "", "", IceCandidateType::kHost, kCandidateGeneration, kCandidateFoundation); - JsepIceCandidate jice_v4("audio", 0, candidate_v4); - JsepIceCandidate jice_v6("audio", 0, candidate_v6); - JsepIceCandidate jice_v4_video("video", 0, candidate_v4); - JsepIceCandidate jice_v6_video("video", 0, candidate_v6); + IceCandidate jice_v4("audio", 0, candidate_v4); + IceCandidate jice_v6("audio", 0, candidate_v6); + IceCandidate jice_v4_video("video", 0, candidate_v4); + IceCandidate jice_v6_video("video", 0, candidate_v6); ASSERT_TRUE(jsep_desc_->AddCandidate(&jice_v4)); ASSERT_TRUE(jsep_desc_->AddCandidate(&jice_v6)); ASSERT_TRUE(jsep_desc_->AddCandidate(&jice_v4_video)); @@ -170,32 +170,57 @@ TEST_F(JsepSessionDescriptionTest, CheckSessionDescription) { // Test that we can add a candidate to a session description without MID. TEST_F(JsepSessionDescriptionTest, AddCandidateWithoutMid) { - JsepIceCandidate jsep_candidate("", 0, candidate_); + IceCandidate jsep_candidate("", 0, candidate_); EXPECT_TRUE(jsep_desc_->AddCandidate(&jsep_candidate)); const IceCandidateCollection* ice_candidates = jsep_desc_->candidates(0); ASSERT_TRUE(ice_candidates != nullptr); EXPECT_EQ(1u, ice_candidates->count()); - const IceCandidateInterface* ice_candidate = ice_candidates->at(0); + const IceCandidate* ice_candidate = ice_candidates->at(0); ASSERT_TRUE(ice_candidate != nullptr); candidate_.set_username(kCandidateUfragVoice); candidate_.set_password(kCandidatePwdVoice); EXPECT_TRUE(ice_candidate->candidate().IsEquivalent(candidate_)); EXPECT_EQ(0, ice_candidate->sdp_mline_index()); + EXPECT_EQ("audio", ice_candidate->sdp_mid()); EXPECT_EQ(0u, jsep_desc_->candidates(1)->count()); } // Test that we can add and remove candidates to a session description with -// MID. Removing candidates requires MID (transport_name). +// MID. Removing candidates requires MID. +TEST_F(JsepSessionDescriptionTest, AddAndRemoveIceCandidatesWithMid) { + // mid and m-line index don't match, in this case mid is preferred. + std::string mid = "video"; + IceCandidate jsep_candidate(mid, 0, candidate_); + EXPECT_TRUE(jsep_desc_->AddCandidate(&jsep_candidate)); + EXPECT_EQ(0u, jsep_desc_->candidates(0)->count()); + const IceCandidateCollection* ice_candidates = jsep_desc_->candidates(1); + ASSERT_THAT(ice_candidates, NotNull()); + EXPECT_EQ(1u, ice_candidates->count()); + const IceCandidate* ice_candidate = ice_candidates->at(0); + ASSERT_THAT(ice_candidate, NotNull()); + candidate_.set_username(kCandidateUfragVideo); + candidate_.set_password(kCandidatePwdVideo); + EXPECT_TRUE(ice_candidate->candidate().IsEquivalent(candidate_)); + // The mline index should have been updated according to mid. + EXPECT_EQ(1, ice_candidate->sdp_mline_index()); + + EXPECT_EQ(1u, jsep_desc_->RemoveCandidate(ice_candidate)); + EXPECT_EQ(0u, jsep_desc_->candidates(0)->count()); + EXPECT_EQ(0u, jsep_desc_->candidates(1)->count()); +} + +// TODO(bugs.webrtc.org/8395): Remove this test and leave +// AddAndRemoveIceCandidatesWithMid. TEST_F(JsepSessionDescriptionTest, AddAndRemoveCandidatesWithMid) { // mid and m-line index don't match, in this case mid is preferred. std::string mid = "video"; - JsepIceCandidate jsep_candidate(mid, 0, candidate_); + IceCandidate jsep_candidate(mid, 0, candidate_); EXPECT_TRUE(jsep_desc_->AddCandidate(&jsep_candidate)); EXPECT_EQ(0u, jsep_desc_->candidates(0)->count()); const IceCandidateCollection* ice_candidates = jsep_desc_->candidates(1); ASSERT_TRUE(ice_candidates != nullptr); EXPECT_EQ(1u, ice_candidates->count()); - const IceCandidateInterface* ice_candidate = ice_candidates->at(0); + const IceCandidate* ice_candidate = ice_candidates->at(0); ASSERT_TRUE(ice_candidate != nullptr); candidate_.set_username(kCandidateUfragVideo); candidate_.set_password(kCandidatePwdVideo); @@ -213,12 +238,12 @@ TEST_F(JsepSessionDescriptionTest, AddAndRemoveCandidatesWithMid) { TEST_F(JsepSessionDescriptionTest, AddCandidateAlreadyHasUfrag) { candidate_.set_username(kCandidateUfrag); candidate_.set_password(kCandidatePwd); - JsepIceCandidate jsep_candidate("audio", 0, candidate_); + IceCandidate jsep_candidate("audio", 0, candidate_); EXPECT_TRUE(jsep_desc_->AddCandidate(&jsep_candidate)); const IceCandidateCollection* ice_candidates = jsep_desc_->candidates(0); ASSERT_TRUE(ice_candidates != nullptr); EXPECT_EQ(1u, ice_candidates->count()); - const IceCandidateInterface* ice_candidate = ice_candidates->at(0); + const IceCandidate* ice_candidate = ice_candidates->at(0); ASSERT_TRUE(ice_candidate != nullptr); candidate_.set_username(kCandidateUfrag); candidate_.set_password(kCandidatePwd); @@ -230,17 +255,17 @@ TEST_F(JsepSessionDescriptionTest, AddCandidateAlreadyHasUfrag) { // Test that we can not add a candidate if there is no corresponding media // content in the session description. TEST_F(JsepSessionDescriptionTest, AddBadCandidate) { - JsepIceCandidate bad_candidate1("", 55, candidate_); + IceCandidate bad_candidate1("", 55, candidate_); EXPECT_FALSE(jsep_desc_->AddCandidate(&bad_candidate1)); - JsepIceCandidate bad_candidate2("some weird mid", 0, candidate_); + IceCandidate bad_candidate2("some weird mid", 0, candidate_); EXPECT_FALSE(jsep_desc_->AddCandidate(&bad_candidate2)); } // Tests that repeatedly adding the same candidate, with or without credentials, // does not increase the number of candidates in the description. TEST_F(JsepSessionDescriptionTest, AddCandidateDuplicates) { - JsepIceCandidate jsep_candidate("", 0, candidate_); + IceCandidate jsep_candidate("", 0, candidate_); EXPECT_TRUE(jsep_desc_->AddCandidate(&jsep_candidate)); EXPECT_EQ(1u, jsep_desc_->candidates(0)->count()); @@ -252,7 +277,7 @@ TEST_F(JsepSessionDescriptionTest, AddCandidateDuplicates) { // populated. candidate_.set_username(kCandidateUfragVoice); candidate_.set_password(kCandidatePwdVoice); - JsepIceCandidate jsep_candidate_with_credentials("", 0, candidate_); + IceCandidate jsep_candidate_with_credentials("", 0, candidate_); // This should also be identified as redundant and ignored. EXPECT_TRUE(jsep_desc_->AddCandidate(&jsep_candidate_with_credentials)); @@ -268,7 +293,7 @@ TEST_F(JsepSessionDescriptionTest, AddHostnameCandidate) { c.set_address(webrtc::SocketAddress("example.local", 1234)); c.set_type(IceCandidateType::kHost); const size_t audio_index = 0; - JsepIceCandidate hostname_candidate("audio", audio_index, c); + IceCandidate hostname_candidate("audio", audio_index, c); EXPECT_TRUE(jsep_desc_->AddCandidate(&hostname_candidate)); ASSERT_NE(nullptr, jsep_desc_->description()); @@ -300,8 +325,8 @@ TEST_F(JsepSessionDescriptionTest, SerializeDeserializeWithHostnameCandidate) { c.set_type(IceCandidateType::kHost); const size_t audio_index = 0; const size_t video_index = 1; - JsepIceCandidate hostname_candidate_audio("audio", audio_index, c); - JsepIceCandidate hostname_candidate_video("video", video_index, c); + IceCandidate hostname_candidate_audio("audio", audio_index, c); + IceCandidate hostname_candidate_video("video", video_index, c); EXPECT_TRUE(jsep_desc_->AddCandidate(&hostname_candidate_audio)); EXPECT_TRUE(jsep_desc_->AddCandidate(&hostname_candidate_video)); @@ -328,7 +353,7 @@ TEST_F(JsepSessionDescriptionTest, SerializeDeserializeWithCandidates) { std::string sdp = Serialize(jsep_desc_.get()); // Add a candidate and check that the serialized result is different. - JsepIceCandidate jsep_candidate("audio", 0, candidate_); + IceCandidate jsep_candidate("audio", 0, candidate_); EXPECT_TRUE(jsep_desc_->AddCandidate(&jsep_candidate)); std::string sdp_with_candidate = Serialize(jsep_desc_.get()); EXPECT_NE(sdp, sdp_with_candidate); @@ -355,10 +380,10 @@ TEST_F(JsepSessionDescriptionTest, SerializeSessionDescriptionWithIPv6Only) { webrtc::SocketAddress("::2", 1235), kCandidatePriority, "", "", IceCandidateType::kHost, kCandidateGeneration, kCandidateFoundation); - JsepIceCandidate jice1("audio", 0, candidate1); - JsepIceCandidate jice2("audio", 0, candidate2); - JsepIceCandidate jice3("video", 0, candidate1); - JsepIceCandidate jice4("video", 0, candidate2); + IceCandidate jice1("audio", 0, candidate1); + IceCandidate jice2("audio", 0, candidate2); + IceCandidate jice3("video", 0, candidate1); + IceCandidate jice4("video", 0, candidate2); ASSERT_TRUE(jsep_desc_->AddCandidate(&jice1)); ASSERT_TRUE(jsep_desc_->AddCandidate(&jice2)); ASSERT_TRUE(jsep_desc_->AddCandidate(&jice3)); @@ -385,10 +410,10 @@ TEST_F(JsepSessionDescriptionTest, webrtc::SocketAddress("::1", 1234), kCandidatePriority, "", "", IceCandidateType::kHost, kCandidateGeneration, kCandidateFoundation); - JsepIceCandidate jice_v4("audio", 0, candidate_v4); - JsepIceCandidate jice_v6("audio", 0, candidate_v6); - JsepIceCandidate jice_v4_video("video", 0, candidate_v4); - JsepIceCandidate jice_v6_video("video", 0, candidate_v6); + IceCandidate jice_v4("audio", 0, candidate_v4); + IceCandidate jice_v6("audio", 0, candidate_v6); + IceCandidate jice_v4_video("video", 0, candidate_v4); + IceCandidate jice_v6_video("video", 0, candidate_v6); ASSERT_TRUE(jsep_desc_->AddCandidate(&jice_v4)); ASSERT_TRUE(jsep_desc_->AddCandidate(&jice_v6)); ASSERT_TRUE(jsep_desc_->AddCandidate(&jice_v4_video)); @@ -417,10 +442,10 @@ TEST_F(JsepSessionDescriptionTest, kCandidatePriority, "", "", IceCandidateType::kHost, kCandidateGeneration, kCandidateFoundation); - JsepIceCandidate jice1("audio", 0, candidate1); - JsepIceCandidate jice2("audio", 0, candidate2); - JsepIceCandidate jice3("video", 0, candidate1); - JsepIceCandidate jice4("video", 0, candidate2); + IceCandidate jice1("audio", 0, candidate1); + IceCandidate jice2("audio", 0, candidate2); + IceCandidate jice3("video", 0, candidate1); + IceCandidate jice4("video", 0, candidate2); ASSERT_TRUE(jsep_desc_->AddCandidate(&jice1)); ASSERT_TRUE(jsep_desc_->AddCandidate(&jice2)); ASSERT_TRUE(jsep_desc_->AddCandidate(&jice3)); @@ -447,10 +472,10 @@ TEST_F(JsepSessionDescriptionTest, SerializeSessionDescriptionWithTCPOnly) { webrtc::SocketAddress("::2", 1235), kCandidatePriority, "", "", IceCandidateType::kHost, kCandidateGeneration, kCandidateFoundation); - JsepIceCandidate jice1("audio", 0, candidate1); - JsepIceCandidate jice2("audio", 0, candidate2); - JsepIceCandidate jice3("video", 0, candidate1); - JsepIceCandidate jice4("video", 0, candidate2); + IceCandidate jice1("audio", 0, candidate1); + IceCandidate jice2("audio", 0, candidate2); + IceCandidate jice3("video", 0, candidate1); + IceCandidate jice4("video", 0, candidate2); ASSERT_TRUE(jsep_desc_->AddCandidate(&jice1)); ASSERT_TRUE(jsep_desc_->AddCandidate(&jice2)); ASSERT_TRUE(jsep_desc_->AddCandidate(&jice3)); @@ -483,9 +508,9 @@ TEST_F(JsepSessionDescriptionTest, RemoveCandidateAndSetConnectionAddress) { IceCandidateType::kHost, kCandidateGeneration, kCandidateFoundation); candidate3.set_transport_name("audio"); - JsepIceCandidate jice1("audio", 0, candidate1); - JsepIceCandidate jice2("audio", 0, candidate2); - JsepIceCandidate jice3("audio", 0, candidate3); + IceCandidate jice1("audio", 0, candidate1); + IceCandidate jice2("audio", 0, candidate2); + IceCandidate jice3("audio", 0, candidate3); size_t audio_index = 0; auto media_desc = diff --git a/pc/jsep_transport_controller.cc b/pc/jsep_transport_controller.cc index 7fb6917c91..0d706a20c9 100644 --- a/pc/jsep_transport_controller.cc +++ b/pc/jsep_transport_controller.cc @@ -29,6 +29,7 @@ #include "api/environment/environment.h" #include "api/ice_transport_interface.h" #include "api/jsep.h" +#include "api/local_network_access_permission.h" #include "api/peer_connection_interface.h" #include "api/rtc_error.h" #include "api/rtp_parameters.h" @@ -77,12 +78,14 @@ JsepTransportController::JsepTransportController( Thread* network_thread, PortAllocator* port_allocator, AsyncDnsResolverFactoryInterface* async_dns_resolver_factory, + LocalNetworkAccessPermissionFactoryInterface* lna_permission_factory, PayloadTypePicker& payload_type_picker, Config config) : env_(env), network_thread_(network_thread), port_allocator_(port_allocator), async_dns_resolver_factory_(async_dns_resolver_factory), + lna_permission_factory_(lna_permission_factory), transports_( [this](const std::string& mid, JsepTransport* transport) { return OnTransportChanged(mid, transport); @@ -499,6 +502,7 @@ JsepTransportController::CreateIceTransport(const std::string& transport_name, IceTransportInit init; init.set_port_allocator(port_allocator_); init.set_async_dns_resolver_factory(async_dns_resolver_factory_); + init.set_lna_permission_factory(lna_permission_factory_); init.set_event_log(config_.event_log); init.set_field_trials(&env_.field_trials()); auto transport = config_.ice_transport_factory->CreateIceTransport( diff --git a/pc/jsep_transport_controller.h b/pc/jsep_transport_controller.h index 3f42a0251b..202da8dc1e 100644 --- a/pc/jsep_transport_controller.h +++ b/pc/jsep_transport_controller.h @@ -29,6 +29,7 @@ #include "api/environment/environment.h" #include "api/ice_transport_interface.h" #include "api/jsep.h" +#include "api/local_network_access_permission.h" #include "api/peer_connection_interface.h" #include "api/rtc_error.h" #include "api/rtc_event_log/rtc_event_log.h" @@ -145,6 +146,7 @@ class JsepTransportController : public PayloadTypeSuggester, Thread* network_thread, PortAllocator* port_allocator, AsyncDnsResolverFactoryInterface* async_dns_resolver_factory, + LocalNetworkAccessPermissionFactoryInterface* lna_permission_factory, PayloadTypePicker& payload_type_picker, Config config); virtual ~JsepTransportController(); @@ -480,6 +482,8 @@ class JsepTransportController : public PayloadTypeSuggester, Thread* const network_thread_ = nullptr; PortAllocator* const port_allocator_ = nullptr; AsyncDnsResolverFactoryInterface* const async_dns_resolver_factory_ = nullptr; + LocalNetworkAccessPermissionFactoryInterface* const lna_permission_factory_ = + nullptr; JsepTransportCollection transports_ RTC_GUARDED_BY(network_thread_); // Aggregate states for Transports. diff --git a/pc/jsep_transport_controller_unittest.cc b/pc/jsep_transport_controller_unittest.cc index fa42946900..dc106922a9 100644 --- a/pc/jsep_transport_controller_unittest.cc +++ b/pc/jsep_transport_controller_unittest.cc @@ -23,6 +23,7 @@ #include "api/dtls_transport_interface.h" #include "api/environment/environment.h" #include "api/environment/environment_factory.h" +#include "api/field_trials.h" #include "api/ice_transport_interface.h" #include "api/jsep.h" #include "api/make_ref_counted.h" @@ -64,9 +65,9 @@ #include "rtc_base/task_queue_for_test.h" #include "rtc_base/third_party/sigslot/sigslot.h" #include "rtc_base/thread.h" +#include "test/create_test_field_trials.h" #include "test/gmock.h" #include "test/gtest.h" -#include "test/scoped_key_value_config.h" #include "test/wait_until.h" using webrtc::Candidate; @@ -137,7 +138,8 @@ class JsepTransportControllerTest : public JsepTransportController::Observer, config.on_dtls_handshake_error_ = [](SSLHandshakeError s) {}; transport_controller_ = std::make_unique( env_, network_thread, port_allocator, - nullptr /* async_resolver_factory */, payload_type_picker_, + /*async_resolver_factory=*/nullptr, + /*lna_permission_factory=*/nullptr, payload_type_picker_, std::move(config)); SendTask(network_thread, [&] { ConnectTransportControllerSignals(); }); } @@ -375,7 +377,7 @@ class JsepTransportControllerTest : public JsepTransportController::Observer, return true; } - test::ScopedKeyValueConfig field_trials_; + FieldTrials field_trials_ = CreateTestFieldTrials(); Environment env_; AutoThread main_thread_; // Information received from signals from transport controller. diff --git a/pc/jsep_transport_unittest.cc b/pc/jsep_transport_unittest.cc index 1b46142e29..f4257774f6 100644 --- a/pc/jsep_transport_unittest.cc +++ b/pc/jsep_transport_unittest.cc @@ -22,6 +22,7 @@ #include #include "api/candidate.h" +#include "api/field_trials.h" #include "api/ice_transport_interface.h" #include "api/jsep.h" #include "api/make_ref_counted.h" @@ -54,19 +55,17 @@ #include "rtc_base/ssl_stream_adapter.h" #include "rtc_base/third_party/sigslot/sigslot.h" #include "rtc_base/thread.h" +#include "test/create_test_field_trials.h" #include "test/gtest.h" -#include "test/scoped_key_value_config.h" namespace webrtc { namespace { -using test::ScopedKeyValueConfig; - -static const char kIceUfrag1[] = "U001"; -static const char kIcePwd1[] = "TESTICEPWD00000000000001"; -static const char kIceUfrag2[] = "U002"; -static const char kIcePwd2[] = "TESTIEPWD00000000000002"; -static const char kTransportName[] = "Test Transport"; +const char kIceUfrag1[] = "U001"; +const char kIcePwd1[] = "TESTICEPWD00000000000001"; +const char kIceUfrag2[] = "U002"; +const char kIcePwd2[] = "TESTIEPWD00000000000002"; +const char kTransportName[] = "Test Transport"; struct NegotiateRoleParams { ConnectionRole local_role; @@ -198,7 +197,7 @@ class JsepTransport2Test : public ::testing::Test, public sigslot::has_slots<> { // for testing. SrtpTransport* sdes_transport_ = nullptr; - ScopedKeyValueConfig field_trials_; + FieldTrials field_trials_ = CreateTestFieldTrials(); PayloadTypePicker payload_type_picker_; }; diff --git a/pc/legacy_stats_collector_unittest.cc b/pc/legacy_stats_collector_unittest.cc index f9af394c63..5f6aff4ffa 100644 --- a/pc/legacy_stats_collector_unittest.cc +++ b/pc/legacy_stats_collector_unittest.cc @@ -89,7 +89,7 @@ const uint32_t kSsrcOfTrack = 1234; class FakeAudioProcessor : public AudioProcessorInterface { public: FakeAudioProcessor() {} - ~FakeAudioProcessor() {} + ~FakeAudioProcessor() override {} private: AudioProcessorInterface::AudioProcessorStatistics GetStats( @@ -131,7 +131,7 @@ class FakeAudioTrack : public MediaStreamTrack { class FakeAudioProcessorWithInitValue : public AudioProcessorInterface { public: FakeAudioProcessorWithInitValue() {} - ~FakeAudioProcessorWithInitValue() {} + ~FakeAudioProcessorWithInitValue() override {} private: AudioProcessorInterface::AudioProcessorStatistics GetStats( diff --git a/pc/media_session_unittest.cc b/pc/media_session_unittest.cc index 7c782eb26b..c0df6a61e9 100644 --- a/pc/media_session_unittest.cc +++ b/pc/media_session_unittest.cc @@ -26,6 +26,7 @@ #include "api/array_view.h" #include "api/audio_codecs/audio_format.h" #include "api/candidate.h" +#include "api/field_trials.h" #include "api/field_trials_view.h" #include "api/media_types.h" #include "api/rtp_parameters.h" @@ -59,9 +60,9 @@ #include "rtc_base/string_encode.h" #include "rtc_base/strings/string_builder.h" #include "rtc_base/unique_id_generator.h" +#include "test/create_test_field_trials.h" #include "test/gmock.h" #include "test/gtest.h" -#include "test/scoped_key_value_config.h" namespace webrtc { namespace { @@ -82,7 +83,6 @@ using ::testing::UnorderedElementsAreArray; using ::testing::Values; using ::testing::ValuesIn; using ::webrtc::UniqueRandomIdGenerator; -using ::webrtc::test::ScopedKeyValueConfig; using Candidates = std::vector; @@ -527,10 +527,11 @@ MediaSessionOptions CreateAudioMediaSession() { class MediaSessionDescriptionFactoryTest : public testing::Test { public: MediaSessionDescriptionFactoryTest() - : tdf1_(field_trials), - tdf2_(field_trials), - codec_lookup_helper_1_(field_trials), - codec_lookup_helper_2_(field_trials), + : field_trials_(CreateTestFieldTrials()), + tdf1_(field_trials_), + tdf2_(field_trials_), + codec_lookup_helper_1_(field_trials_), + codec_lookup_helper_2_(field_trials_), f1_(nullptr, false, &ssrc_generator1, &tdf1_, &codec_lookup_helper_1_), f2_(nullptr, false, &ssrc_generator2, &tdf2_, &codec_lookup_helper_2_) { codec_lookup_helper_1_.GetCodecVendor()->set_audio_codecs( @@ -776,7 +777,7 @@ class MediaSessionDescriptionFactoryTest : public testing::Test { } protected: - ScopedKeyValueConfig field_trials; + FieldTrials field_trials_; UniqueRandomIdGenerator ssrc_generator1; UniqueRandomIdGenerator ssrc_generator2; TransportDescriptionFactory tdf1_; @@ -3647,8 +3648,7 @@ TEST_F(MediaSessionDescriptionFactoryTest, SimSsrcsGenerateMultipleRtxSsrcs) { // Test that, when the FlexFEC codec is added, a FlexFEC ssrc is created // together with a FEC-FR grouping. Guarded by WebRTC-FlexFEC-03 trial. TEST_F(MediaSessionDescriptionFactoryTest, GenerateFlexfecSsrc) { - ScopedKeyValueConfig override_field_trials(field_trials, - "WebRTC-FlexFEC-03/Enabled/"); + field_trials_.Set("WebRTC-FlexFEC-03", "Enabled"); MediaSessionOptions opts; AddMediaDescriptionOptions(webrtc::MediaType::VIDEO, "video", RtpTransceiverDirection::kSendRecv, kActive, @@ -3691,8 +3691,7 @@ TEST_F(MediaSessionDescriptionFactoryTest, GenerateFlexfecSsrc) { // TODO(brandtr): Remove this test when we support simulcast, either through // multiple FlexfecSenders, or through multistream protection. TEST_F(MediaSessionDescriptionFactoryTest, SimSsrcsGenerateNoFlexfecSsrcs) { - ScopedKeyValueConfig override_field_trials(field_trials, - "WebRTC-FlexFEC-03/Enabled/"); + field_trials_.Set("WebRTC-FlexFEC-03", "Enabled"); MediaSessionOptions opts; AddMediaDescriptionOptions(webrtc::MediaType::VIDEO, "video", RtpTransceiverDirection::kSendRecv, kActive, @@ -4732,7 +4731,7 @@ class MediaProtocolTest : public testing::TestWithParam { } protected: - ScopedKeyValueConfig field_trials_; + FieldTrials field_trials_ = CreateTestFieldTrials(); TransportDescriptionFactory tdf1_; TransportDescriptionFactory tdf2_; CodecLookupHelperForTesting codec_lookup_helper_1_; @@ -4790,7 +4789,7 @@ bool CodecsMatch(const std::vector& codecs1, } void TestAudioCodecsOffer(RtpTransceiverDirection direction) { - ScopedKeyValueConfig field_trials; + FieldTrials field_trials = CreateTestFieldTrials(); TransportDescriptionFactory tdf(field_trials); tdf.set_certificate(RTCCertificate::Create( std::unique_ptr(new FakeSSLIdentity("id")))); @@ -4896,7 +4895,7 @@ std::vector VectorFromIndices(const T* array, const int (&indices)[IDXS]) { void TestAudioCodecsAnswer(RtpTransceiverDirection offer_direction, RtpTransceiverDirection answer_direction, bool add_legacy_stream) { - ScopedKeyValueConfig field_trials; + FieldTrials field_trials = CreateTestFieldTrials(); TransportDescriptionFactory offer_tdf(field_trials); TransportDescriptionFactory answer_tdf(field_trials); offer_tdf.set_certificate(RTCCertificate::Create( @@ -5084,7 +5083,7 @@ class VideoCodecsOfferH265LevelIdTest : public testing::Test { } protected: - ScopedKeyValueConfig field_trials_; + FieldTrials field_trials_ = CreateTestFieldTrials(); TransportDescriptionFactory tdf_offerer_; TransportDescriptionFactory tdf_answerer_; UniqueRandomIdGenerator ssrc_generator_offerer_; diff --git a/pc/media_stream_unittest.cc b/pc/media_stream_unittest.cc index 3a8820664b..35a518f95e 100644 --- a/pc/media_stream_unittest.cc +++ b/pc/media_stream_unittest.cc @@ -37,7 +37,7 @@ class MockObserver : public ObserverInterface { notifier_->RegisterObserver(this); } - ~MockObserver() { Unregister(); } + ~MockObserver() override { Unregister(); } void Unregister() { if (notifier_) { @@ -54,7 +54,7 @@ class MockObserver : public ObserverInterface { class MediaStreamTest : public ::testing::Test { protected: - virtual void SetUp() { + void SetUp() override { stream_ = MediaStream::Create(kStreamId1); ASSERT_TRUE(stream_.get() != nullptr); diff --git a/pc/peer_connection.cc b/pc/peer_connection.cc index 630ab4db09..efc37f4cc1 100644 --- a/pc/peer_connection.cc +++ b/pc/peer_connection.cc @@ -36,7 +36,6 @@ #include "api/dtls_transport_interface.h" #include "api/environment/environment.h" #include "api/jsep.h" -#include "api/jsep_ice_candidate.h" #include "api/make_ref_counted.h" #include "api/media_stream_interface.h" #include "api/media_types.h" @@ -124,7 +123,7 @@ namespace webrtc { namespace { -static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000; +const int REPORT_USAGE_PATTERN_DELAY_MS = 60000; class CodecLookupHelperForPeerConnection : public CodecLookupHelper { public: @@ -528,6 +527,7 @@ PeerConnection::PeerConnection( async_dns_resolver_factory_( std::move(dependencies.async_dns_resolver_factory)), port_allocator_(std::move(dependencies.allocator)), + lna_permission_factory_(std::move(dependencies.lna_permission_factory)), ice_transport_factory_(std::move(dependencies.ice_transport_factory)), tls_cert_verifier_(std::move(dependencies.tls_cert_verifier)), call_(std::move(call)), @@ -717,10 +717,10 @@ JsepTransportController* PeerConnection::InitializeTransportController_n( } }; - transport_controller_.reset( - new JsepTransportController(env_, network_thread(), port_allocator_.get(), - async_dns_resolver_factory_.get(), - payload_type_picker_, std::move(config))); + transport_controller_.reset(new JsepTransportController( + env_, network_thread(), port_allocator_.get(), + async_dns_resolver_factory_.get(), lna_permission_factory_.get(), + payload_type_picker_, std::move(config))); transport_controller_->SubscribeIceConnectionState( [this](::webrtc::IceConnectionState s) { @@ -1563,16 +1563,14 @@ RTCError PeerConnection::SetConfiguration( return RTCError::OK(); } -bool PeerConnection::AddIceCandidate( - const IceCandidateInterface* ice_candidate) { +bool PeerConnection::AddIceCandidate(const IceCandidate* ice_candidate) { RTC_DCHECK_RUN_ON(signaling_thread()); ClearStatsCache(); return sdp_handler_->AddIceCandidate(ice_candidate); } -void PeerConnection::AddIceCandidate( - std::unique_ptr candidate, - std::function callback) { +void PeerConnection::AddIceCandidate(std::unique_ptr candidate, + std::function callback) { RTC_DCHECK_RUN_ON(signaling_thread()); sdp_handler_->AddIceCandidate(std::move(candidate), [this, callback](RTCError result) { @@ -2036,8 +2034,7 @@ void PeerConnection::OnIceGatheringChange( Observer()->OnIceGatheringChange(ice_gathering_state_); } -void PeerConnection::OnIceCandidate( - std::unique_ptr candidate) { +void PeerConnection::OnIceCandidate(std::unique_ptr candidate) { if (IsClosed()) { return; } @@ -2420,8 +2417,8 @@ void PeerConnection::OnTransportControllerCandidatesGathered( for (Candidates::const_iterator citer = candidates.begin(); citer != candidates.end(); ++citer) { // Use transport_name as the candidate media id. - std::unique_ptr candidate( - new JsepIceCandidate(transport_name, sdp_mline_index, *citer)); + std::unique_ptr candidate( + new IceCandidate(transport_name, sdp_mline_index, *citer)); sdp_handler_->AddLocalIceCandidate(candidate.get()); OnIceCandidate(std::move(candidate)); } diff --git a/pc/peer_connection.h b/pc/peer_connection.h index eeea50f0eb..1a4cc90a5e 100644 --- a/pc/peer_connection.h +++ b/pc/peer_connection.h @@ -34,6 +34,7 @@ #include "api/field_trials_view.h" #include "api/ice_transport_interface.h" #include "api/jsep.h" +#include "api/local_network_access_permission.h" #include "api/media_stream_interface.h" #include "api/media_types.h" #include "api/peer_connection_interface.h" @@ -231,8 +232,8 @@ class PeerConnection : public PeerConnectionInternal, PeerConnectionInterface::RTCConfiguration GetConfiguration() override; RTCError SetConfiguration( const PeerConnectionInterface::RTCConfiguration& configuration) override; - bool AddIceCandidate(const IceCandidateInterface* candidate) override; - void AddIceCandidate(std::unique_ptr candidate, + bool AddIceCandidate(const IceCandidate* candidate) override; + void AddIceCandidate(std::unique_ptr candidate, std::function callback) override; bool RemoveIceCandidates(const std::vector& candidates) override; @@ -501,7 +502,7 @@ class PeerConnection : public PeerConnectionInternal, void OnIceGatheringChange(IceGatheringState new_state) RTC_RUN_ON(signaling_thread()); // New ICE candidate has been gathered. - void OnIceCandidate(std::unique_ptr candidate) + void OnIceCandidate(std::unique_ptr candidate) RTC_RUN_ON(signaling_thread()); // Gathering of an ICE candidate failed. void OnIceCandidateError(const std::string& address, @@ -650,6 +651,9 @@ class PeerConnection : public PeerConnectionInternal, std::unique_ptr port_allocator_; // TODO(bugs.webrtc.org/9987): Accessed on both // signaling and network thread. + std::unique_ptr + lna_permission_factory_; + const std::unique_ptr ice_transport_factory_; // TODO(bugs.webrtc.org/9987): Accessed on the // signaling thread but the underlying raw diff --git a/pc/peer_connection_bundle_unittest.cc b/pc/peer_connection_bundle_unittest.cc index b3be6d85bc..95eed4e1ec 100644 --- a/pc/peer_connection_bundle_unittest.cc +++ b/pc/peer_connection_bundle_unittest.cc @@ -112,7 +112,7 @@ class PeerConnectionWrapperForBundleTest : public PeerConnectionWrapper { const auto& content = desc->contents()[i]; if (content.media_description()->type() == media_type) { candidate->set_transport_name(content.mid()); - std::unique_ptr jsep_candidate = + std::unique_ptr jsep_candidate = CreateIceCandidate(content.mid(), i, *candidate); return pc()->AddIceCandidate(jsep_candidate.get()); } @@ -294,7 +294,7 @@ SdpContentMutator RemoveRtcpMux() { } std::vector GetCandidateComponents( - const std::vector candidates) { + const std::vector candidates) { std::vector components; components.reserve(candidates.size()); for (auto* candidate : candidates) { diff --git a/pc/peer_connection_callsetup_perf_tests.cc b/pc/peer_connection_callsetup_perf_tests.cc index c8c4ff51cc..04f4462df7 100644 --- a/pc/peer_connection_callsetup_perf_tests.cc +++ b/pc/peer_connection_callsetup_perf_tests.cc @@ -14,15 +14,14 @@ #include #include #include -#include #include #include "absl/strings/str_cat.h" +#include "absl/strings/string_view.h" #include "api/audio_codecs/builtin_audio_decoder_factory.h" #include "api/audio_codecs/builtin_audio_encoder_factory.h" #include "api/data_channel_interface.h" #include "api/field_trials.h" -#include "api/field_trials_view.h" #include "api/jsep.h" #include "api/make_ref_counted.h" #include "api/rtc_error.h" @@ -39,6 +38,7 @@ #include "rtc_base/thread.h" #include "rtc_base/time_utils.h" #include "rtc_base/virtual_socket_server.h" +#include "test/create_test_field_trials.h" #include "test/gmock.h" #include "test/gtest.h" #include "test/wait_until.h" @@ -69,12 +69,13 @@ class PeerConnectionDataChannelOpenTest } scoped_refptr CreatePc( - std::unique_ptr field_trials = nullptr) { + absl::string_view field_trials = "") { auto pc_wrapper = make_ref_counted( "pc", &vss_, background_thread_.get(), background_thread_.get()); - pc_wrapper->CreatePc({}, CreateBuiltinAudioEncoderFactory(), - CreateBuiltinAudioDecoderFactory(), - std::move(field_trials)); + pc_wrapper->CreatePc( + {}, CreateBuiltinAudioEncoderFactory(), + CreateBuiltinAudioDecoderFactory(), + std::make_unique(CreateTestFieldTrials(field_trials))); return pc_wrapper; } @@ -183,10 +184,8 @@ TEST_P(PeerConnectionDataChannelOpenTest, OpenAtCaller) { std::string role_string; ASSERT_TRUE(ConnectionRoleToString(role, &role_string)); - scoped_refptr local_pc_wrapper = - CreatePc(FieldTrials::CreateNoGlobal(trials)); - scoped_refptr remote_pc_wrapper = - CreatePc(FieldTrials::CreateNoGlobal(trials)); + scoped_refptr local_pc_wrapper = CreatePc(trials); + scoped_refptr remote_pc_wrapper = CreatePc(trials); if (!skip_candidates_from_caller) { SignalIceCandidates(local_pc_wrapper, remote_pc_wrapper); diff --git a/pc/peer_connection_encodings_integrationtest.cc b/pc/peer_connection_encodings_integrationtest.cc index 86dbb44936..4de839059a 100644 --- a/pc/peer_connection_encodings_integrationtest.cc +++ b/pc/peer_connection_encodings_integrationtest.cc @@ -58,6 +58,7 @@ #include "rtc_base/logging.h" #include "rtc_base/physical_socket_server.h" #include "rtc_base/thread.h" +#include "test/create_test_field_trials.h" #include "test/gmock.h" #include "test/gtest.h" #include "test/wait_until.h" @@ -231,12 +232,13 @@ class PeerConnectionEncodingsIntegrationTest : public ::testing::Test { } scoped_refptr CreatePc( - std::unique_ptr field_trials = nullptr) { + absl::string_view field_trials = "") { auto pc_wrapper = make_ref_counted( "pc", &pss_, background_thread_.get(), background_thread_.get()); - pc_wrapper->CreatePc({}, CreateBuiltinAudioEncoderFactory(), - CreateBuiltinAudioDecoderFactory(), - std::move(field_trials)); + pc_wrapper->CreatePc( + {}, CreateBuiltinAudioEncoderFactory(), + CreateBuiltinAudioDecoderFactory(), + std::make_unique(CreateTestFieldTrials(field_trials))); return pc_wrapper; } @@ -2209,9 +2211,9 @@ TEST_F(PeerConnectionEncodingsIntegrationTest, // Enable WIP mixed codec simulcast support std::string field_trials = "WebRTC-MixedCodecSimulcast/Enabled/"; scoped_refptr local_pc_wrapper = - CreatePc(FieldTrials::CreateNoGlobal(field_trials)); + CreatePc(field_trials); scoped_refptr remote_pc_wrapper = - CreatePc(FieldTrials::CreateNoGlobal(field_trials)); + CreatePc(field_trials); ExchangeIceCandidates(local_pc_wrapper, remote_pc_wrapper); std::optional vp8 = diff --git a/pc/peer_connection_factory.cc b/pc/peer_connection_factory.cc index e42457667f..fb248a9ee9 100644 --- a/pc/peer_connection_factory.cc +++ b/pc/peer_connection_factory.cc @@ -74,19 +74,15 @@ Environment AssembleEnvironment(PeerConnectionFactoryDependencies& deps) { // Assemble Environment here rather than in ConnectionContext::Create // to avoid dependency on EnvironmentFactory by ConnectionContext and thus its // users. - EnvironmentFactory env_factory = deps.env.has_value() - ? EnvironmentFactory(*deps.env) - : EnvironmentFactory(); -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdeprecated-declarations" - env_factory.Set(std::move(deps.trials)); - env_factory.Set(std::move(deps.task_queue_factory)); -#pragma clang diagnostic pop + if (!deps.env.has_value()) { + return CreateEnvironment(); + } + Environment env = *std::move(deps.env); // Clear Environment from `deps` to avoid accidental usage of the wrong // Environment. deps.env = std::nullopt; - return env_factory.Create(); + return env; } } // namespace diff --git a/pc/peer_connection_factory_unittest.cc b/pc/peer_connection_factory_unittest.cc index 816360376f..568c123d2f 100644 --- a/pc/peer_connection_factory_unittest.cc +++ b/pc/peer_connection_factory_unittest.cc @@ -87,30 +87,27 @@ using ::testing::NotNull; using ::testing::Return; using ::testing::UnorderedElementsAre; -static const char kStunIceServer[] = "stun:stun.l.google.com:19302"; -static const char kTurnIceServer[] = "turn:test.com:1234"; -static const char kTurnIceServerWithTransport[] = - "turn:hello.com?transport=tcp"; -static const char kSecureTurnIceServer[] = "turns:hello.com?transport=tcp"; -static const char kSecureTurnIceServerWithoutTransportParam[] = - "turns:hello.com:443"; -static const char kSecureTurnIceServerWithoutTransportAndPortParam[] = +const char kStunIceServer[] = "stun:stun.l.google.com:19302"; +const char kTurnIceServer[] = "turn:test.com:1234"; +const char kTurnIceServerWithTransport[] = "turn:hello.com?transport=tcp"; +const char kSecureTurnIceServer[] = "turns:hello.com?transport=tcp"; +const char kSecureTurnIceServerWithoutTransportParam[] = "turns:hello.com:443"; +const char kSecureTurnIceServerWithoutTransportAndPortParam[] = "turns:hello.com"; -static const char kTurnIceServerWithNoUsernameInUri[] = "turn:test.com:1234"; -static const char kTurnPassword[] = "turnpassword"; -static const int kDefaultStunPort = 3478; -static const int kDefaultStunTlsPort = 5349; -static const char kTurnUsername[] = "test"; -static const char kStunIceServerWithIPv4Address[] = "stun:1.2.3.4:1234"; -static const char kStunIceServerWithIPv4AddressWithoutPort[] = "stun:1.2.3.4"; -static const char kStunIceServerWithIPv6Address[] = "stun:[2401:fa00:4::]:1234"; -static const char kStunIceServerWithIPv6AddressWithoutPort[] = - "stun:[2401:fa00:4::]"; -static const char kTurnIceServerWithIPv6Address[] = "turn:[2401:fa00:4::]:1234"; +const char kTurnIceServerWithNoUsernameInUri[] = "turn:test.com:1234"; +const char kTurnPassword[] = "turnpassword"; +const int kDefaultStunPort = 3478; +const int kDefaultStunTlsPort = 5349; +const char kTurnUsername[] = "test"; +const char kStunIceServerWithIPv4Address[] = "stun:1.2.3.4:1234"; +const char kStunIceServerWithIPv4AddressWithoutPort[] = "stun:1.2.3.4"; +const char kStunIceServerWithIPv6Address[] = "stun:[2401:fa00:4::]:1234"; +const char kStunIceServerWithIPv6AddressWithoutPort[] = "stun:[2401:fa00:4::]"; +const char kTurnIceServerWithIPv6Address[] = "turn:[2401:fa00:4::]:1234"; class NullPeerConnectionObserver : public PeerConnectionObserver { public: - virtual ~NullPeerConnectionObserver() = default; + ~NullPeerConnectionObserver() override = default; void OnSignalingChange( PeerConnectionInterface::SignalingState new_state) override {} void OnAddStream(scoped_refptr stream) override {} @@ -122,7 +119,7 @@ class NullPeerConnectionObserver : public PeerConnectionObserver { PeerConnectionInterface::IceConnectionState new_state) override {} void OnIceGatheringChange( PeerConnectionInterface::IceGatheringState new_state) override {} - void OnIceCandidate(const IceCandidateInterface* candidate) override {} + void OnIceCandidate(const IceCandidate* candidate) override {} }; class MockNetworkManager : public NetworkManager { @@ -143,7 +140,7 @@ class PeerConnectionFactoryTest : public ::testing::Test { main_thread_(socket_server_.get()) {} private: - void SetUp() { + void SetUp() override { #ifdef WEBRTC_ANDROID InitializeAndroidObjects(); #endif @@ -665,8 +662,7 @@ TEST_F(PeerConnectionFactoryTest, LocalRendering) { TEST(PeerConnectionFactoryDependenciesTest, CanInjectFieldTrialsWithEnvironment) { - std::unique_ptr field_trials = - FieldTrials::CreateNoGlobal(""); + std::unique_ptr field_trials = FieldTrials::Create(""); ASSERT_THAT(field_trials, NotNull()); FieldTrialsView* raw_field_trials = field_trials.get(); @@ -680,29 +676,6 @@ TEST(PeerConnectionFactoryDependenciesTest, EXPECT_EQ(&pcf->field_trials(), raw_field_trials); } -TEST(PeerConnectionFactoryDependenciesTest, - PreferFieldTrialsInjectedExplicetly) { - std::unique_ptr env_field_trials = - FieldTrials::CreateNoGlobal(""); - std::unique_ptr explicit_field_trials = - FieldTrials::CreateNoGlobal(""); - ASSERT_FALSE(env_field_trials.get() == explicit_field_trials.get()); - FieldTrialsView* raw_explicit_field_trials = explicit_field_trials.get(); - - PeerConnectionFactoryDependencies pcf_dependencies; - pcf_dependencies.env = CreateEnvironment(std::move(env_field_trials)); -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdeprecated-declarations" - pcf_dependencies.trials = std::move(explicit_field_trials); -#pragma clang diagnostic pop - pcf_dependencies.adm = FakeAudioCaptureModule::Create(); - EnableMediaWithDefaults(pcf_dependencies); - - scoped_refptr pcf = - PeerConnectionFactory::Create(std::move(pcf_dependencies)); - EXPECT_EQ(&pcf->field_trials(), raw_explicit_field_trials); -} - TEST(PeerConnectionFactoryDependenciesTest, UsesNetworkManager) { constexpr TimeDelta kWaitTimeout = TimeDelta::Seconds(10); auto mock_network_manager = std::make_unique>(); diff --git a/pc/peer_connection_field_trial_tests.cc b/pc/peer_connection_field_trial_tests.cc index 3d99c3020c..c2bbcf8943 100644 --- a/pc/peer_connection_field_trial_tests.cc +++ b/pc/peer_connection_field_trial_tests.cc @@ -16,10 +16,10 @@ #include #include "absl/algorithm/container.h" +#include "absl/strings/string_view.h" #include "api/enable_media_with_defaults.h" #include "api/environment/environment_factory.h" #include "api/field_trials.h" -#include "api/field_trials_view.h" #include "api/media_types.h" #include "api/peer_connection_interface.h" #include "api/rtp_parameters.h" @@ -33,6 +33,7 @@ #include "rtc_base/socket_server.h" #include "rtc_base/thread.h" #include "system_wrappers/include/clock.h" +#include "test/create_test_field_trials.h" #include "test/gtest.h" #ifdef WEBRTC_ANDROID @@ -62,10 +63,11 @@ class PeerConnectionFieldTrialTest : public ::testing::Test { void TearDown() override { pc_factory_ = nullptr; } - void CreatePCFactory(std::unique_ptr field_trials) { + void CreatePCFactory(absl::string_view field_trials) { PeerConnectionFactoryDependencies pcf_deps; pcf_deps.signaling_thread = Thread::Current(); - pcf_deps.env = CreateEnvironment(std::move(field_trials)); + pcf_deps.env = CreateEnvironment( + std::make_unique(CreateTestFieldTrials(field_trials))); pcf_deps.adm = FakeAudioCaptureModule::Create(); EnableMediaWithDefaults(pcf_deps); pc_factory_ = CreateModularPeerConnectionFactory(std::move(pcf_deps)); @@ -99,8 +101,7 @@ class PeerConnectionFieldTrialTest : public ::testing::Test { // Tests for the dependency descriptor field trial. The dependency descriptor // field trial is implemented in media/engine/webrtc_video_engine.cc. TEST_F(PeerConnectionFieldTrialTest, EnableDependencyDescriptorAdvertised) { - CreatePCFactory(FieldTrials::CreateNoGlobal( - "WebRTC-DependencyDescriptorAdvertised/Enabled/")); + CreatePCFactory("WebRTC-DependencyDescriptorAdvertised/Enabled/"); WrapperPtr caller = CreatePeerConnection(); caller->AddTransceiver(MediaType::VIDEO); @@ -132,8 +133,7 @@ TEST_F(PeerConnectionFieldTrialTest, EnableDependencyDescriptorAdvertised) { #define MAYBE_InjectDependencyDescriptor InjectDependencyDescriptor #endif TEST_F(PeerConnectionFieldTrialTest, MAYBE_InjectDependencyDescriptor) { - CreatePCFactory(FieldTrials::CreateNoGlobal( - "WebRTC-DependencyDescriptorAdvertised/Disabled/")); + CreatePCFactory("WebRTC-DependencyDescriptorAdvertised/Disabled/"); WrapperPtr caller = CreatePeerConnection(); WrapperPtr callee = CreatePeerConnection(); diff --git a/pc/peer_connection_header_extension_unittest.cc b/pc/peer_connection_header_extension_unittest.cc index def77de11d..5342b3b9f9 100644 --- a/pc/peer_connection_header_extension_unittest.cc +++ b/pc/peer_connection_header_extension_unittest.cc @@ -44,12 +44,12 @@ namespace webrtc { using ::testing::Combine; using ::testing::ElementsAre; using ::testing::Field; +using ::testing::IsEmpty; using ::testing::Return; using ::testing::Values; class PeerConnectionHeaderExtensionTest - : public ::testing::TestWithParam< - std::tuple> { + : public ::testing::TestWithParam> { protected: PeerConnectionHeaderExtensionTest() : socket_server_(CreateDefaultSocketServer()), @@ -70,10 +70,10 @@ class PeerConnectionHeaderExtensionTest RtpTransceiverDirection::kSendRecv)}) {} std::unique_ptr CreatePeerConnection( - webrtc::MediaType media_type, + MediaType media_type, std::optional semantics) { auto media_engine = std::make_unique(); - if (media_type == webrtc::MediaType::AUDIO) + if (media_type == MediaType::AUDIO) media_engine->fake_voice_engine()->SetRtpHeaderExtensions(extensions_); else media_engine->fake_video_engine()->SetRtpHeaderExtensions(extensions_); @@ -111,7 +111,7 @@ class PeerConnectionHeaderExtensionTest }; TEST_P(PeerConnectionHeaderExtensionTest, TransceiverOffersHeaderExtensions) { - webrtc::MediaType media_type; + MediaType media_type; SdpSemantics semantics; std::tie(media_type, semantics) = GetParam(); if (semantics != SdpSemantics::kUnifiedPlan) @@ -124,7 +124,7 @@ TEST_P(PeerConnectionHeaderExtensionTest, TransceiverOffersHeaderExtensions) { TEST_P(PeerConnectionHeaderExtensionTest, SenderReceiverCapabilitiesReturnNotStoppedExtensions) { - webrtc::MediaType media_type; + MediaType media_type; SdpSemantics semantics; std::tie(media_type, semantics) = GetParam(); std::unique_ptr wrapper = @@ -144,7 +144,7 @@ TEST_P(PeerConnectionHeaderExtensionTest, } TEST_P(PeerConnectionHeaderExtensionTest, OffersUnstoppedDefaultExtensions) { - webrtc::MediaType media_type; + MediaType media_type; SdpSemantics semantics; std::tie(media_type, semantics) = GetParam(); if (semantics != SdpSemantics::kUnifiedPlan) @@ -163,7 +163,7 @@ TEST_P(PeerConnectionHeaderExtensionTest, OffersUnstoppedDefaultExtensions) { } TEST_P(PeerConnectionHeaderExtensionTest, OffersUnstoppedModifiedExtensions) { - webrtc::MediaType media_type; + MediaType media_type; SdpSemantics semantics; std::tie(media_type, semantics) = GetParam(); if (semantics != SdpSemantics::kUnifiedPlan) @@ -187,7 +187,7 @@ TEST_P(PeerConnectionHeaderExtensionTest, OffersUnstoppedModifiedExtensions) { } TEST_P(PeerConnectionHeaderExtensionTest, AnswersUnstoppedModifiedExtensions) { - webrtc::MediaType media_type; + MediaType media_type; SdpSemantics semantics; std::tie(media_type, semantics) = GetParam(); if (semantics != SdpSemantics::kUnifiedPlan) @@ -220,7 +220,7 @@ TEST_P(PeerConnectionHeaderExtensionTest, AnswersUnstoppedModifiedExtensions) { } TEST_P(PeerConnectionHeaderExtensionTest, NegotiatedExtensionsAreAccessible) { - webrtc::MediaType media_type; + MediaType media_type; SdpSemantics semantics; std::tie(media_type, semantics) = GetParam(); if (semantics != SdpSemantics::kUnifiedPlan) @@ -256,7 +256,7 @@ TEST_P(PeerConnectionHeaderExtensionTest, NegotiatedExtensionsAreAccessible) { } TEST_P(PeerConnectionHeaderExtensionTest, OfferedExtensionsArePerTransceiver) { - webrtc::MediaType media_type; + MediaType media_type; SdpSemantics semantics; std::tie(media_type, semantics) = GetParam(); if (semantics != SdpSemantics::kUnifiedPlan) @@ -286,7 +286,7 @@ TEST_P(PeerConnectionHeaderExtensionTest, OfferedExtensionsArePerTransceiver) { } TEST_P(PeerConnectionHeaderExtensionTest, RemovalAfterRenegotiation) { - webrtc::MediaType media_type; + MediaType media_type; SdpSemantics semantics; std::tie(media_type, semantics) = GetParam(); if (semantics != SdpSemantics::kUnifiedPlan) @@ -318,7 +318,7 @@ TEST_P(PeerConnectionHeaderExtensionTest, RemovalAfterRenegotiation) { TEST_P(PeerConnectionHeaderExtensionTest, StoppedByDefaultExtensionCanBeActivatedByRemoteSdp) { - webrtc::MediaType media_type; + MediaType media_type; SdpSemantics semantics; std::tie(media_type, semantics) = GetParam(); if (semantics != SdpSemantics::kUnifiedPlan) @@ -353,7 +353,7 @@ TEST_P(PeerConnectionHeaderExtensionTest, TEST_P(PeerConnectionHeaderExtensionTest, UnknownExtensionInRemoteOfferDoesNotShowUp) { - webrtc::MediaType media_type; + MediaType media_type; SdpSemantics semantics; std::tie(media_type, semantics) = GetParam(); if (semantics != SdpSemantics::kUnifiedPlan) @@ -370,7 +370,7 @@ TEST_P(PeerConnectionHeaderExtensionTest, "AD:7E:77:43:2A:29:EC:93\r\n" "a=ice-ufrag:6HHHdzzeIhkE0CKj\r\n" "a=ice-pwd:XYDGVpfvklQIEnZ6YnyLsAew\r\n"; - if (media_type == webrtc::MediaType::AUDIO) { + if (media_type == MediaType::AUDIO) { sdp += "m=audio 9 RTP/AVPF 111\r\n" "a=rtpmap:111 fake_audio_codec/8000\r\n"; @@ -407,7 +407,7 @@ TEST_P(PeerConnectionHeaderExtensionTest, // of the API to only offer non-stopped extensions. TEST_P(PeerConnectionHeaderExtensionTest, SdpMungingAnswerWithoutApiUsageEnablesExtensions) { - webrtc::MediaType media_type; + MediaType media_type; SdpSemantics semantics; std::tie(media_type, semantics) = GetParam(); if (semantics != SdpSemantics::kUnifiedPlan) @@ -424,7 +424,7 @@ TEST_P(PeerConnectionHeaderExtensionTest, "AD:7E:77:43:2A:29:EC:93\r\n" "a=ice-ufrag:6HHHdzzeIhkE0CKj\r\n" "a=ice-pwd:XYDGVpfvklQIEnZ6YnyLsAew\r\n"; - if (media_type == webrtc::MediaType::AUDIO) { + if (media_type == MediaType::AUDIO) { sdp += "m=audio 9 RTP/AVPF 111\r\n" "a=rtpmap:111 fake_audio_codec/8000\r\n"; @@ -464,7 +464,7 @@ TEST_P(PeerConnectionHeaderExtensionTest, TEST_P(PeerConnectionHeaderExtensionTest, SdpMungingOfferWithoutApiUsageEnablesExtensions) { - webrtc::MediaType media_type; + MediaType media_type; SdpSemantics semantics; std::tie(media_type, semantics) = GetParam(); if (semantics != SdpSemantics::kUnifiedPlan) @@ -494,7 +494,7 @@ TEST_P(PeerConnectionHeaderExtensionTest, } TEST_P(PeerConnectionHeaderExtensionTest, EnablingExtensionsAfterRemoteOffer) { - webrtc::MediaType media_type; + MediaType media_type; SdpSemantics semantics; std::tie(media_type, semantics) = GetParam(); if (semantics != SdpSemantics::kUnifiedPlan) @@ -511,7 +511,7 @@ TEST_P(PeerConnectionHeaderExtensionTest, EnablingExtensionsAfterRemoteOffer) { "AD:7E:77:43:2A:29:EC:93\r\n" "a=ice-ufrag:6HHHdzzeIhkE0CKj\r\n" "a=ice-pwd:XYDGVpfvklQIEnZ6YnyLsAew\r\n"; - if (media_type == webrtc::MediaType::AUDIO) { + if (media_type == MediaType::AUDIO) { sdp += "m=audio 9 RTP/AVPF 111\r\n" "a=rtpmap:111 fake_audio_codec/8000\r\n"; @@ -552,21 +552,54 @@ TEST_P(PeerConnectionHeaderExtensionTest, EnablingExtensionsAfterRemoteOffer) { EXPECT_EQ(extensions[0].id, 5); } +TEST_P(PeerConnectionHeaderExtensionTest, SenderParametersReflectNegotiation) { + SdpSemantics semantics; + MediaType media_type; + std::tie(media_type, semantics) = GetParam(); + if (semantics != SdpSemantics::kUnifiedPlan) { + GTEST_SKIP() << "This test only works with Unified Plan"; + } + std::unique_ptr pc1 = + CreatePeerConnection(media_type, semantics); + std::unique_ptr pc2 = + CreatePeerConnection(media_type, semantics); + auto transceiver1 = pc1->AddTransceiver(media_type); + // Before connection, sender sender_parameters should be empty. + { + auto sender_parameters = pc1->pc()->GetSenders()[0]->GetParameters(); + EXPECT_THAT(sender_parameters.header_extensions, IsEmpty()); + } + + auto offer = pc1->CreateOfferAndSetAsLocal( + PeerConnectionInterface::RTCOfferAnswerOptions()); + pc2->SetRemoteDescription(std::move(offer)); + auto answer = pc2->CreateAnswerAndSetAsLocal( + PeerConnectionInterface::RTCOfferAnswerOptions()); + pc1->SetRemoteDescription(std::move(answer)); + { + auto sender_parameters = pc1->pc()->GetSenders()[0]->GetParameters(); + // We expect to see all send or sendrecv extensions from the answer. + EXPECT_THAT(sender_parameters.header_extensions, + UnorderedElementsAre(Field(&RtpExtension::uri, "uri4"), + Field(&RtpExtension::uri, "uri2"), + Field(&RtpExtension::uri, "uri3"))); + } +} + INSTANTIATE_TEST_SUITE_P( , PeerConnectionHeaderExtensionTest, Combine(Values(SdpSemantics::kPlanB_DEPRECATED, SdpSemantics::kUnifiedPlan), - Values(webrtc::MediaType::AUDIO, webrtc::MediaType::VIDEO)), + Values(MediaType::AUDIO, MediaType::VIDEO)), [](const testing::TestParamInfo< PeerConnectionHeaderExtensionTest::ParamType>& info) { - webrtc::MediaType media_type; + MediaType media_type; SdpSemantics semantics; std::tie(media_type, semantics) = info.param; return (StringBuilder("With") << (semantics == SdpSemantics::kPlanB_DEPRECATED ? "PlanB" : "UnifiedPlan") - << "And" - << (media_type == webrtc::MediaType::AUDIO ? "Voice" : "Video") + << "And" << (media_type == MediaType::AUDIO ? "Voice" : "Video") << "Engine") .str(); }); diff --git a/pc/peer_connection_histogram_unittest.cc b/pc/peer_connection_histogram_unittest.cc index 5b1da41863..ddc5a3face 100644 --- a/pc/peer_connection_histogram_unittest.cc +++ b/pc/peer_connection_histogram_unittest.cc @@ -12,9 +12,12 @@ #include #include #include +#include #include #include +#include "absl/strings/str_format.h" +#include "absl/strings/string_view.h" #include "api/jsep.h" #include "api/jsep_session_description.h" #include "api/peer_connection_interface.h" @@ -30,11 +33,11 @@ #include "pc/test/mock_peer_connection_observers.h" #include "pc/usage_pattern.h" #include "pc/webrtc_sdp.h" -#include "rtc_base/arraysize.h" #include "rtc_base/checks.h" #include "rtc_base/fake_mdns_responder.h" #include "rtc_base/fake_network.h" #include "rtc_base/gunit.h" +#include "rtc_base/ip_address.h" #include "rtc_base/network.h" #include "rtc_base/socket_address.h" #include "rtc_base/thread.h" @@ -46,16 +49,35 @@ namespace webrtc { +namespace { + +constexpr const char kBasicRemoteDescription[] = R"(v=0 +o=- 0 0 IN IP4 127.0.0.1 +s=- +t=0 0 +m=audio 9 UDP/TLS/RTP/SAVPF 101 +c=IN IP4 0.0.0.0 +a=ice-ufrag:fooUfrag +a=ice-pwd:someRemotePasswordGeneratedString +a=fingerprint:sha-256 0A:B1:C2:D3:E4:F5:06:07:08:09:0A:0B:0C:0D:0E:0F:10:11:12:13:14:15:16:17:18:19:1A:1B:1C:1D:1E:1F +a=candidate:1 1 UDP 2130706431 %s 57892 typ host generation 0 +a=setup:active +a=mid:0 +a=sendrecv +a=rtcp-mux +a=rtpmap:101 fake_audio_codec/8000 +)"; + using RTCConfiguration = PeerConnectionInterface::RTCConfiguration; using RTCOfferAnswerOptions = PeerConnectionInterface::RTCOfferAnswerOptions; using ::testing::NiceMock; -static const char kUsagePatternMetric[] = "WebRTC.PeerConnection.UsagePattern"; -static constexpr TimeDelta kDefaultTimeout = TimeDelta::Millis(10000); -static const SocketAddress kLocalAddrs[2] = {SocketAddress("1.1.1.1", 0), - SocketAddress("2.2.2.2", 0)}; -static const SocketAddress kPrivateLocalAddress("10.1.1.1", 0); -static const SocketAddress kPrivateIpv6LocalAddress("fd12:3456:789a:1::1", 0); +const char kUsagePatternMetric[] = "WebRTC.PeerConnection.UsagePattern"; +constexpr TimeDelta kDefaultTimeout = TimeDelta::Millis(10000); +const SocketAddress kLocalAddrs[2] = {SocketAddress("1.1.1.1", 0), + SocketAddress("2.2.2.2", 0)}; +const SocketAddress kPrivateLocalAddress("10.1.1.1", 0); +const SocketAddress kPrivateIpv6LocalAddress("fd12:3456:789a:1::1", 0); int MakeUsageFingerprint(std::set events) { int signature = 0; @@ -71,7 +93,7 @@ typedef PeerConnectionWrapperForUsageHistogramTest* RawWrapperPtr; class ObserverForUsageHistogramTest : public MockPeerConnectionObserver { public: - void OnIceCandidate(const IceCandidateInterface* candidate) override; + void OnIceCandidate(const IceCandidate* candidate) override; void OnInterestingUsage(int usage_pattern) override { interesting_usage_detected_ = usage_pattern; @@ -127,10 +149,9 @@ class PeerConnectionWrapperForUsageHistogramTest return static_cast(observer()) ->HaveDataChannel(); } - void BufferIceCandidate(const IceCandidateInterface* candidate) { - std::string sdp; - EXPECT_TRUE(candidate->ToString(&sdp)); - std::unique_ptr candidate_copy(CreateIceCandidate( + void BufferIceCandidate(const IceCandidate* candidate) { + std::string sdp = candidate->ToString(); + std::unique_ptr candidate_copy(CreateIceCandidate( candidate->sdp_mid(), candidate->sdp_mline_index(), sdp, nullptr)); buffered_candidates_.push_back(std::move(candidate_copy)); } @@ -190,12 +211,12 @@ class PeerConnectionWrapperForUsageHistogramTest private: // Candidates that have been sent but not yet configured - std::vector> buffered_candidates_; + std::vector> buffered_candidates_; }; // Buffers candidates until we add them via AddBufferedIceCandidates. void ObserverForUsageHistogramTest::OnIceCandidate( - const IceCandidateInterface* candidate) { + const IceCandidate* candidate) { // If target is not set, ignore. This happens in one-ended unit tests. if (candidate_target_) { this->candidate_target_->BufferIceCandidate(candidate); @@ -315,7 +336,7 @@ class PeerConnectionUsageHistogramTest : public ::testing::Test { } SocketAddress NextLocalAddress() { - RTC_DCHECK(next_local_address_ < (int)arraysize(kLocalAddrs)); + RTC_DCHECK_LT(next_local_address_, std::ssize(kLocalAddrs)); return kLocalAddrs[next_local_address_++]; } @@ -583,6 +604,58 @@ TEST_F(PeerConnectionUsageHistogramTest, FingerprintWithPrivateIpv6Callee) { 1, metrics::NumEvents(kUsagePatternMetric, expected_fingerprint_callee)); } +struct IPAddressTypeTestConfig { + absl::string_view address; + IPAddressType address_type; +} const kAllCandidateIPAddressTypeTestConfigs[] = { + {"127.0.0.1", IPAddressType::kLoopback}, + {"::1", IPAddressType::kLoopback}, + {"localhost", IPAddressType::kLoopback}, + {"10.0.0.3", IPAddressType::kPrivate}, + {"FE80::3", IPAddressType::kPrivate}, + {"1.1.1.1", IPAddressType::kPublic}, + {"2001:4860:4860::8888", IPAddressType::kPublic}, +}; + +// Used by the test framework to print the param value for parameterized tests. +std::string PrintToString(const IPAddressTypeTestConfig& param) { + return std::string(param.address); +} + +class PeerConnectionCandidateIPAddressTypeHistogramTest + : public PeerConnectionUsageHistogramTest, + public ::testing::WithParamInterface {}; + +// Tests that the correct IPAddressType is logged when adding candidates. +TEST_P(PeerConnectionCandidateIPAddressTypeHistogramTest, + CandidateAddressType) { + auto caller = CreatePeerConnection(); + + caller->AddAudioTrack("audio"); + ASSERT_TRUE(caller->SetLocalDescription(caller->CreateOffer())); + + // Set the remote description which includes a candidate using the IP Address + // from the test's params. + EXPECT_TRUE(caller->SetRemoteDescription(CreateSessionDescription( + SdpType::kAnswer, + absl::StrFormat(kBasicRemoteDescription, GetParam().address)))); + + ASSERT_THAT( + WaitUntil([&] { return caller->ice_gathering_state(); }, + ::testing::Eq(PeerConnectionInterface::kIceGatheringComplete)), + IsRtcOk()); + ASSERT_TRUE(caller->observer()->candidate_gathered()); + + auto samples = metrics::Samples("WebRTC.PeerConnection.CandidateAddressType"); + ASSERT_EQ(samples.size(), 1u); + EXPECT_EQ(samples[static_cast(GetParam().address_type)], 1); +} + +INSTANTIATE_TEST_SUITE_P( + All, + PeerConnectionCandidateIPAddressTypeHistogramTest, + ::testing::ValuesIn(kAllCandidateIPAddressTypeTestConfigs)); + #ifndef WEBRTC_ANDROID #ifdef WEBRTC_HAVE_SCTP // Test that the usage pattern bits for adding remote (private IPv6) candidates @@ -737,4 +810,6 @@ TEST_F(PeerConnectionUsageHistogramTest, #endif #endif +} // namespace + } // namespace webrtc diff --git a/pc/peer_connection_ice_unittest.cc b/pc/peer_connection_ice_unittest.cc index 9e70705544..fbcdb5bbd1 100644 --- a/pc/peer_connection_ice_unittest.cc +++ b/pc/peer_connection_ice_unittest.cc @@ -97,7 +97,7 @@ class PeerConnectionWrapperForIceTest : public PeerConnectionWrapper { public: using PeerConnectionWrapper::PeerConnectionWrapper; - std::unique_ptr CreateJsepCandidateForFirstTransport( + std::unique_ptr CreateJsepCandidateForFirstTransport( Candidate* candidate) { RTC_DCHECK(pc()->remote_description()); const auto* desc = pc()->remote_description()->description(); @@ -114,11 +114,10 @@ class PeerConnectionWrapperForIceTest : public PeerConnectionWrapper { } // Returns ICE candidates from the remote session description. - std::vector - GetIceCandidatesFromRemoteDescription() { + std::vector GetIceCandidatesFromRemoteDescription() { const SessionDescriptionInterface* sdesc = pc()->remote_description(); RTC_DCHECK(sdesc); - std::vector candidates; + std::vector candidates; for (size_t mline_index = 0; mline_index < sdesc->number_of_mediasections(); mline_index++) { const auto* candidate_collection = sdesc->candidates(mline_index); @@ -306,7 +305,7 @@ class PeerConnectionIceBaseTest : public ::testing::Test { RTC_DCHECK(!desc->contents().empty()); const auto& first_content = desc->contents()[0]; candidate->set_transport_name(first_content.mid()); - std::unique_ptr jsep_candidate = + std::unique_ptr jsep_candidate = CreateIceCandidate(first_content.mid(), 0, *candidate); return sdesc->AddCandidate(jsep_candidate.get()); } @@ -490,7 +489,7 @@ TEST_P(PeerConnectionIceTest, CannotAddCandidateWhenRemoteDescriptionNotSet) { auto caller = CreatePeerConnectionWithAudioVideo(); Candidate candidate = CreateLocalUdpCandidate(kCalleeAddress); - std::unique_ptr jsep_candidate = + std::unique_ptr jsep_candidate = CreateIceCandidate(CN_AUDIO, 0, candidate); EXPECT_FALSE(caller->pc()->AddIceCandidate(jsep_candidate.get())); @@ -514,7 +513,7 @@ TEST_P(PeerConnectionIceTest, CannotAddCandidateWhenPeerConnectionClosed) { Candidate candidate = CreateLocalUdpCandidate(kCalleeAddress); auto* audio_content = GetFirstAudioContent(caller->pc()->local_description()->description()); - std::unique_ptr jsep_candidate = + std::unique_ptr jsep_candidate = CreateIceCandidate(audio_content->mid(), 0, candidate); caller->pc()->Close(); @@ -568,7 +567,7 @@ TEST_P(PeerConnectionIceTest, Candidate candidate = CreateLocalUdpCandidate(kCalleeAddress); auto* audio_content = GetFirstAudioContent(caller->pc()->local_description()->description()); - std::unique_ptr ice_candidate = + std::unique_ptr ice_candidate = CreateIceCandidate(audio_content->mid(), 0, candidate); ASSERT_TRUE(caller->pc()->AddIceCandidate(ice_candidate.get())); @@ -593,7 +592,7 @@ TEST_P(PeerConnectionIceTest, Candidate candidate = CreateLocalUdpCandidate(kCalleeAddress); auto* audio_content = GetFirstAudioContent(caller->pc()->local_description()->description()); - std::unique_ptr ice_candidate = + std::unique_ptr ice_candidate = CreateIceCandidate(audio_content->mid(), 0, candidate); EXPECT_TRUE(caller->pc()->AddIceCandidate(ice_candidate.get())); EXPECT_TRUE(caller->pc()->RemoveIceCandidates({candidate})); @@ -692,7 +691,7 @@ ::testing::AssertionResult AssertIpInCandidates( const char* address_expr, const char* candidates_expr, const SocketAddress& address, - const std::vector candidates) { + const std::vector candidates) { StringBuilder candidate_hosts; for (const auto* candidate : candidates) { const auto& candidate_ip = candidate->candidate().address().ipaddr(); @@ -849,7 +848,7 @@ TEST_P(PeerConnectionIceTest, auto candidate = CreateLocalUdpCandidate(SocketAddress("1.1.1.1", 1111)); auto caller = CreatePeerConnectionWithAudioVideo(); - std::unique_ptr jsep_candidate = + std::unique_ptr jsep_candidate = CreateIceCandidate(CN_AUDIO, 0, candidate); bool operation_completed = false; @@ -1601,7 +1600,7 @@ TEST_P(PeerConnectionIceTest, PrefersMidOverMLineIndex) { Candidate candidate = CreateLocalUdpCandidate(kCalleeAddress); auto* audio_content = GetFirstAudioContent(caller->pc()->local_description()->description()); - std::unique_ptr ice_candidate = + std::unique_ptr ice_candidate = CreateIceCandidate(audio_content->mid(), 65535, candidate); EXPECT_TRUE(caller->pc()->AddIceCandidate(ice_candidate.get())); EXPECT_TRUE(caller->pc()->RemoveIceCandidates({candidate})); diff --git a/pc/peer_connection_integrationtest.cc b/pc/peer_connection_integrationtest.cc index 506495b616..3a2babda3e 100644 --- a/pc/peer_connection_integrationtest.cc +++ b/pc/peer_connection_integrationtest.cc @@ -794,7 +794,7 @@ TEST_P(PeerConnectionIntegrationTest, RotatedVideoWithoutCVOExtension) { [](std::unique_ptr& sdp) { VideoContentDescription* video = GetFirstVideoContentDescription(sdp->description()); - video->ClearRtpHeaderExtensions(); + video->set_rtp_header_extensions({}); }); // Wait for video frames to be received by both sides. caller()->CreateAndSetAndSignalOffer(); @@ -1288,6 +1288,120 @@ TEST_F(PeerConnectionIntegrationTestUnifiedPlan, NoStreamsMsidLineMissing) { callee_receivers[1]->streams()[0]); } +// Used by the CSRC tests below. +MATCHER_P(IsCsrcWithId, csrc, "") { + return arg.source_type() == RtpSourceType::CSRC && arg.source_id() == csrc; +} + +// Test that CSRCs can be set upon adding tracks and that they are received by +// the other side. +TEST_F(PeerConnectionIntegrationTestUnifiedPlan, EndToEndCallForwardsCsrcs) { + ASSERT_TRUE(CreatePeerConnectionWrappers()); + ConnectFakeSignaling(); + + constexpr uint32_t kAudioCsrc = 1234; + constexpr uint32_t kVideoCsrc = 5678; + RtpEncodingParameters audio_encoding; + RtpEncodingParameters video_encoding; + audio_encoding.csrcs = {kAudioCsrc}; + video_encoding.csrcs = {kVideoCsrc}; + ASSERT_THAT(caller()->pc()->AddTrack(caller()->CreateLocalAudioTrack(), {}, + {audio_encoding}), + IsRtcOk()); + ASSERT_THAT(caller()->pc()->AddTrack(caller()->CreateLocalVideoTrack(), {}, + {video_encoding}), + IsRtcOk()); + + caller()->CreateAndSetAndSignalOffer(); + + // Wait for some packets to arrive. + ASSERT_THAT( + WaitUntil([&] { return SignalingStateStable(); }, ::testing::IsTrue()), + IsRtcOk()); + ASSERT_THAT(WaitUntil( + [&] { + return callee()->audio_frames_received() > 0 && + callee()->min_video_frames_received_per_track() > 0; + }, + ::testing::IsTrue(), {.timeout = kMaxWaitForFrames}), + IsRtcOk()); + + std::vector> audio_receivers = + callee()->GetReceiversOfType(webrtc::MediaType::AUDIO); + ASSERT_EQ(audio_receivers.size(), 1u); + std::vector> video_receivers = + callee()->GetReceiversOfType(webrtc::MediaType::VIDEO); + ASSERT_EQ(video_receivers.size(), 1u); + + EXPECT_THAT(audio_receivers[0]->GetSources(), + Contains(IsCsrcWithId(kAudioCsrc))); + EXPECT_THAT(video_receivers[0]->GetSources(), + Contains(IsCsrcWithId(kVideoCsrc))); +} + +// Test that CSRCs can be updated on active tracks. +TEST_F(PeerConnectionIntegrationTestUnifiedPlan, EndToEndCallCanUpdateCsrcs) { + ASSERT_TRUE(CreatePeerConnectionWrappers()); + ConnectFakeSignaling(); + + RtpEncodingParameters audio_encoding; + RtpEncodingParameters video_encoding; + audio_encoding.csrcs = {1234}; + video_encoding.csrcs = {5678}; + + scoped_refptr audio_sender = + caller() + ->pc() + ->AddTrack(caller()->CreateLocalAudioTrack(), {}, {audio_encoding}) + .MoveValue(); + scoped_refptr video_sender = + caller() + ->pc() + ->AddTrack(caller()->CreateLocalVideoTrack(), {}, {video_encoding}) + .MoveValue(); + + caller()->CreateAndSetAndSignalOffer(); + + // Wait for some packets to arrive. + ASSERT_THAT( + WaitUntil([&] { return SignalingStateStable(); }, ::testing::IsTrue()), + IsRtcOk()); + ASSERT_THAT(WaitUntil( + [&] { + return callee()->audio_frames_received() > 0 && + callee()->min_video_frames_received_per_track() > 0; + }, + ::testing::IsTrue(), {.timeout = kMaxWaitForFrames}), + IsRtcOk()); + + // Update the CSRCs. + constexpr uint32_t kUpdatedAudioCsrc = 4321; + constexpr uint32_t kUpdatedVideoCsrc = 8765; + RtpParameters audio_parameters = audio_sender->GetParameters(); + RtpParameters video_parameters = video_sender->GetParameters(); + audio_parameters.encodings[0].csrcs = {kUpdatedAudioCsrc}; + video_parameters.encodings[0].csrcs = {kUpdatedVideoCsrc}; + ASSERT_THAT(audio_sender->SetParameters(audio_parameters), IsRtcOk()); + ASSERT_THAT(video_sender->SetParameters(video_parameters), IsRtcOk()); + + std::vector> audio_receivers = + callee()->GetReceiversOfType(webrtc::MediaType::AUDIO); + ASSERT_EQ(audio_receivers.size(), 1u); + std::vector> video_receivers = + callee()->GetReceiversOfType(webrtc::MediaType::VIDEO); + ASSERT_EQ(video_receivers.size(), 1u); + + // Ensure that the new CSRCs are used. + EXPECT_THAT(WaitUntil([&] { return audio_receivers[0]->GetSources(); }, + Contains(IsCsrcWithId(kUpdatedAudioCsrc)), + {.timeout = kMaxWaitForFrames}), + IsRtcOk()); + EXPECT_THAT(WaitUntil([&] { return video_receivers[0]->GetSources(); }, + Contains(IsCsrcWithId(kUpdatedVideoCsrc)), + {.timeout = kMaxWaitForFrames}), + IsRtcOk()); +} + // Test that if two video tracks are sent (from caller to callee, in this test), // they're transmitted correctly end-to-end. TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithTwoVideoTracks) { @@ -1307,7 +1421,7 @@ TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithTwoVideoTracks) { ASSERT_TRUE(ExpectNewFrames(media_expectations)); } -static void MakeSpecCompliantMaxBundleOffer( +void MakeSpecCompliantMaxBundleOffer( std::unique_ptr& sdp) { bool first = true; for (ContentInfo& content : sdp->description()->contents()) { @@ -2159,12 +2273,10 @@ TEST_P(PeerConnectionIntegrationTest, MediaContinuesFlowingAfterIceRestart) { callee()->pc()->local_description()->candidates(0); ASSERT_GT(audio_candidates_caller->count(), 0u); ASSERT_GT(audio_candidates_callee->count(), 0u); - std::string caller_candidate_pre_restart; - ASSERT_TRUE( - audio_candidates_caller->at(0)->ToString(&caller_candidate_pre_restart)); - std::string callee_candidate_pre_restart; - ASSERT_TRUE( - audio_candidates_callee->at(0)->ToString(&callee_candidate_pre_restart)); + std::string caller_candidate_pre_restart = + audio_candidates_caller->at(0)->ToString(); + std::string callee_candidate_pre_restart = + audio_candidates_callee->at(0)->ToString(); const SessionDescription* desc = caller()->pc()->local_description()->description(); std::string caller_ufrag_pre_restart = @@ -2196,12 +2308,10 @@ TEST_P(PeerConnectionIntegrationTest, MediaContinuesFlowingAfterIceRestart) { audio_candidates_callee = callee()->pc()->local_description()->candidates(0); ASSERT_GT(audio_candidates_caller->count(), 0u); ASSERT_GT(audio_candidates_callee->count(), 0u); - std::string caller_candidate_post_restart; - ASSERT_TRUE( - audio_candidates_caller->at(0)->ToString(&caller_candidate_post_restart)); - std::string callee_candidate_post_restart; - ASSERT_TRUE( - audio_candidates_callee->at(0)->ToString(&callee_candidate_post_restart)); + std::string caller_candidate_post_restart = + audio_candidates_caller->at(0)->ToString(); + std::string callee_candidate_post_restart = + audio_candidates_callee->at(0)->ToString(); desc = caller()->pc()->local_description()->description(); std::string caller_ufrag_post_restart = desc->transport_infos()[0].description.ice_ufrag; diff --git a/pc/peer_connection_interface_unittest.cc b/pc/peer_connection_interface_unittest.cc index 4e6bc33395..13fd3c393a 100644 --- a/pc/peer_connection_interface_unittest.cc +++ b/pc/peer_connection_interface_unittest.cc @@ -98,30 +98,30 @@ namespace webrtc { namespace { -static const char kStreamId1[] = "local_stream_1"; -static const char kStreamId2[] = "local_stream_2"; -static const char kStreamId3[] = "local_stream_3"; -static const int kDefaultStunPort = 3478; -static const char kStunAddressOnly[] = "stun:address"; -static const char kStunInvalidPort[] = "stun:address:-1"; -static const char kStunAddressPortAndMore1[] = "stun:address:port:more"; -static const char kStunAddressPortAndMore2[] = "stun:address:port more"; -static const char kTurnIceServerUri[] = "turn:turn.example.org"; -static const char kTurnUsername[] = "user"; -static const char kTurnPassword[] = "password"; -static const char kTurnHostname[] = "turn.example.org"; -static const uint32_t kTimeout = 10000U; - -static const char kStreams[][8] = {"stream1", "stream2"}; -static const char kAudioTracks[][32] = {"audiotrack0", "audiotrack1"}; -static const char kVideoTracks[][32] = {"videotrack0", "videotrack1"}; - -static const char kRecvonly[] = "recvonly"; -static const char kSendrecv[] = "sendrecv"; +const char kStreamId1[] = "local_stream_1"; +const char kStreamId2[] = "local_stream_2"; +const char kStreamId3[] = "local_stream_3"; +const int kDefaultStunPort = 3478; +const char kStunAddressOnly[] = "stun:address"; +const char kStunInvalidPort[] = "stun:address:-1"; +const char kStunAddressPortAndMore1[] = "stun:address:port:more"; +const char kStunAddressPortAndMore2[] = "stun:address:port more"; +const char kTurnIceServerUri[] = "turn:turn.example.org"; +const char kTurnUsername[] = "user"; +const char kTurnPassword[] = "password"; +const char kTurnHostname[] = "turn.example.org"; +const uint32_t kTimeout = 10000U; + +const char kStreams[][8] = {"stream1", "stream2"}; +const char kAudioTracks[][32] = {"audiotrack0", "audiotrack1"}; +const char kVideoTracks[][32] = {"videotrack0", "videotrack1"}; + +const char kRecvonly[] = "recvonly"; +const char kSendrecv[] = "sendrecv"; // Reference SDP with a MediaStream with label "stream1" and audio track with // id "audio_1" and a video track with id "video_1; -static const char kSdpStringWithStream1PlanB[] = +const char kSdpStringWithStream1PlanB[] = "v=0\r\n" "o=- 0 0 IN IP4 127.0.0.1\r\n" "s=-\r\n" @@ -151,7 +151,7 @@ static const char kSdpStringWithStream1PlanB[] = // Same string as above but with the MID changed to the Unified Plan default and // a=msid added. This is needed so that this SDP can be used as an answer for a // Unified Plan offer. -static const char kSdpStringWithStream1UnifiedPlan[] = +const char kSdpStringWithStream1UnifiedPlan[] = "v=0\r\n" "o=- 0 0 IN IP4 127.0.0.1\r\n" "s=-\r\n" @@ -181,7 +181,7 @@ static const char kSdpStringWithStream1UnifiedPlan[] = // Reference SDP with a MediaStream with label "stream1" and audio track with // id "audio_1"; -static const char kSdpStringWithStream1AudioTrackOnly[] = +const char kSdpStringWithStream1AudioTrackOnly[] = "v=0\r\n" "o=- 0 0 IN IP4 127.0.0.1\r\n" "s=-\r\n" @@ -201,7 +201,7 @@ static const char kSdpStringWithStream1AudioTrackOnly[] = // Reference SDP with two MediaStreams with label "stream1" and "stream2. Each // MediaStreams have one audio track and one video track. // This uses MSID. -static const char kSdpStringWithStream1And2PlanB[] = +const char kSdpStringWithStream1And2PlanB[] = "v=0\r\n" "o=- 0 0 IN IP4 127.0.0.1\r\n" "s=-\r\n" @@ -233,7 +233,7 @@ static const char kSdpStringWithStream1And2PlanB[] = "a=ssrc:2 msid:stream1 videotrack0\r\n" "a=ssrc:4 cname:stream2\r\n" "a=ssrc:4 msid:stream2 videotrack1\r\n"; -static const char kSdpStringWithStream1And2UnifiedPlan[] = +const char kSdpStringWithStream1And2UnifiedPlan[] = "v=0\r\n" "o=- 0 0 IN IP4 127.0.0.1\r\n" "s=-\r\n" @@ -285,7 +285,7 @@ static const char kSdpStringWithStream1And2UnifiedPlan[] = "a=ssrc:4 msid:stream2 videotrack1\r\n"; // Reference SDP without MediaStreams. Msid is not supported. -static const char kSdpStringWithoutStreams[] = +const char kSdpStringWithoutStreams[] = "v=0\r\n" "o=- 0 0 IN IP4 127.0.0.1\r\n" "s=-\r\n" @@ -310,7 +310,7 @@ static const char kSdpStringWithoutStreams[] = "a=rtpmap:120 VP8/90000\r\n"; // Reference SDP without MediaStreams. Msid is supported. -static const char kSdpStringWithMsidWithoutStreams[] = +const char kSdpStringWithMsidWithoutStreams[] = "v=0\r\n" "o=- 0 0 IN IP4 127.0.0.1\r\n" "s=-\r\n" @@ -336,7 +336,7 @@ static const char kSdpStringWithMsidWithoutStreams[] = "a=rtpmap:120 VP8/90000\r\n"; // Reference SDP without MediaStreams and audio only. -static const char kSdpStringWithoutStreamsAudioOnly[] = +const char kSdpStringWithoutStreamsAudioOnly[] = "v=0\r\n" "o=- 0 0 IN IP4 127.0.0.1\r\n" "s=-\r\n" @@ -352,7 +352,7 @@ static const char kSdpStringWithoutStreamsAudioOnly[] = "a=rtpmap:111 OPUS/48000/2\r\n"; // Reference SENDONLY SDP without MediaStreams. Msid is not supported. -static const char kSdpStringSendOnlyWithoutStreams[] = +const char kSdpStringSendOnlyWithoutStreams[] = "v=0\r\n" "o=- 0 0 IN IP4 127.0.0.1\r\n" "s=-\r\n" @@ -378,14 +378,14 @@ static const char kSdpStringSendOnlyWithoutStreams[] = "a=rtcp-mux\r\n" "a=rtpmap:120 VP8/90000\r\n"; -static const char kSdpStringInit[] = +const char kSdpStringInit[] = "v=0\r\n" "o=- 0 0 IN IP4 127.0.0.1\r\n" "s=-\r\n" "t=0 0\r\n" "a=msid-semantic: WMS\r\n"; -static const char kSdpStringAudio[] = +const char kSdpStringAudio[] = "m=audio 1 RTP/AVPF 111\r\n" "a=ice-ufrag:e5785931\r\n" "a=ice-pwd:36fb7878390db89481c1d46daa4278d8\r\n" @@ -396,7 +396,7 @@ static const char kSdpStringAudio[] = "a=rtcp-mux\r\n" "a=rtpmap:111 OPUS/48000/2\r\n"; -static const char kSdpStringVideo[] = +const char kSdpStringVideo[] = "m=video 1 RTP/AVPF 120\r\n" "a=ice-ufrag:e5785931\r\n" "a=ice-pwd:36fb7878390db89481c1d46daa4278d8\r\n" @@ -407,19 +407,19 @@ static const char kSdpStringVideo[] = "a=rtcp-mux\r\n" "a=rtpmap:120 VP8/90000\r\n"; -static const char kSdpStringMs1Audio0[] = +const char kSdpStringMs1Audio0[] = "a=ssrc:1 cname:stream1\r\n" "a=ssrc:1 msid:stream1 audiotrack0\r\n"; -static const char kSdpStringMs1Video0[] = +const char kSdpStringMs1Video0[] = "a=ssrc:2 cname:stream1\r\n" "a=ssrc:2 msid:stream1 videotrack0\r\n"; -static const char kSdpStringMs1Audio1[] = +const char kSdpStringMs1Audio1[] = "a=ssrc:3 cname:stream1\r\n" "a=ssrc:3 msid:stream1 audiotrack1\r\n"; -static const char kSdpStringMs1Video1[] = +const char kSdpStringMs1Video1[] = "a=ssrc:4 cname:stream1\r\n" "a=ssrc:4 msid:stream1 videotrack1\r\n"; @@ -583,7 +583,7 @@ class MockTrackObserver : public ObserverInterface { notifier_->RegisterObserver(this); } - ~MockTrackObserver() { Unregister(); } + ~MockTrackObserver() override { Unregister(); } void Unregister() { if (notifier_) { diff --git a/pc/peer_connection_proxy.h b/pc/peer_connection_proxy.h index 4f809abbce..e84c487187 100644 --- a/pc/peer_connection_proxy.h +++ b/pc/peer_connection_proxy.h @@ -153,10 +153,10 @@ PROXY_METHOD0(PeerConnectionInterface::RTCConfiguration, GetConfiguration) PROXY_METHOD1(RTCError, SetConfiguration, const PeerConnectionInterface::RTCConfiguration&) -PROXY_METHOD1(bool, AddIceCandidate, const IceCandidateInterface*) +PROXY_METHOD1(bool, AddIceCandidate, const IceCandidate*) PROXY_METHOD2(void, AddIceCandidate, - std::unique_ptr, + std::unique_ptr, std::function) PROXY_METHOD1(bool, RemoveIceCandidates, const std::vector&) PROXY_METHOD1(RTCError, SetBitrate, const BitrateSettings&) diff --git a/pc/peer_connection_rampup_tests.cc b/pc/peer_connection_rampup_tests.cc index 8b928531c6..ecf672dff6 100644 --- a/pc/peer_connection_rampup_tests.cc +++ b/pc/peer_connection_rampup_tests.cc @@ -67,18 +67,18 @@ using test::GetGlobalMetricsLogger; using test::ImprovementDirection; using test::Unit; -static const int kDefaultTestTimeMs = 15000; -static const int kRampUpTimeMs = 5000; -static const int kPollIntervalTimeMs = 50; -static const SocketAddress kDefaultLocalAddress("1.1.1.1", 0); -static const char kTurnInternalAddress[] = "88.88.88.0"; -static const char kTurnExternalAddress[] = "88.88.88.1"; -static const int kTurnInternalPort = 3478; -static const int kTurnExternalPort = 0; +const int kDefaultTestTimeMs = 15000; +const int kRampUpTimeMs = 5000; +const int kPollIntervalTimeMs = 50; +const SocketAddress kDefaultLocalAddress("1.1.1.1", 0); +const char kTurnInternalAddress[] = "88.88.88.0"; +const char kTurnExternalAddress[] = "88.88.88.1"; +const int kTurnInternalPort = 3478; +const int kTurnExternalPort = 0; // The video's configured max bitrate in webrtcvideoengine.cc is 1.7 Mbps. // Setting the network bandwidth to 1 Mbps allows the video's bitrate to push // the network's limitations. -static const int kNetworkBandwidth = 1000000; +const int kNetworkBandwidth = 1000000; } // namespace @@ -111,7 +111,7 @@ class PeerConnectionWrapperForRampUpTest : public PeerConnectionWrapper { pc, std::move(observer)) {} - bool AddIceCandidates(std::vector candidates) { + bool AddIceCandidates(std::vector candidates) { bool success = true; for (const auto candidate : candidates) { if (!pc()->AddIceCandidate(candidate)) { @@ -160,7 +160,7 @@ class PeerConnectionRampUpTest : public ::testing::Test { virtual_socket_server_.set_bandwidth(kNetworkBandwidth / 8); } - virtual ~PeerConnectionRampUpTest() { + ~PeerConnectionRampUpTest() override { SendTask(network_thread(), [this] { turn_servers_.clear(); }); } diff --git a/pc/proxy_unittest.cc b/pc/proxy_unittest.cc index a12e581548..d3d3739aa9 100644 --- a/pc/proxy_unittest.cc +++ b/pc/proxy_unittest.cc @@ -39,7 +39,7 @@ class FakeInterface : public RefCountInterface { virtual std::string Method2(std::string s1, std::string s2) = 0; protected: - virtual ~FakeInterface() {} + ~FakeInterface() override {} }; // Implementation of the test interface. @@ -60,7 +60,7 @@ class Fake : public FakeInterface { protected: Fake() {} - ~Fake() { Destroy(); } + ~Fake() override { Destroy(); } }; // Proxies for the test interface. diff --git a/pc/rtc_stats_collector.cc b/pc/rtc_stats_collector.cc index 780fe49c47..3be877c5a5 100644 --- a/pc/rtc_stats_collector.cc +++ b/pc/rtc_stats_collector.cc @@ -89,7 +89,7 @@ namespace { const char kDirectionInbound = 'I'; const char kDirectionOutbound = 'O'; -static constexpr char kAudioPlayoutSingletonId[] = "AP"; +constexpr char kAudioPlayoutSingletonId[] = "AP"; // TODO(https://crbug.com/webrtc/10656): Consider making IDs less predictable. std::string RTCCertificateIDFromFingerprint(const std::string& fingerprint) { diff --git a/pc/rtc_stats_collector_unittest.cc b/pc/rtc_stats_collector_unittest.cc index 29216e1d7f..f3f2a92e8a 100644 --- a/pc/rtc_stats_collector_unittest.cc +++ b/pc/rtc_stats_collector_unittest.cc @@ -192,7 +192,7 @@ std::unique_ptr CreateFakeCandidate( class FakeAudioProcessor : public AudioProcessorInterface { public: FakeAudioProcessor() {} - ~FakeAudioProcessor() {} + ~FakeAudioProcessor() override {} private: AudioProcessorInterface::AudioProcessorStatistics GetStats( @@ -3759,8 +3759,8 @@ class FakeRTCStatsCollector : public RTCStatsCollector, // give to scoped_refptr. // Satisfying the implementation of these methods and associating them with a // reference counter, will be done by RefCountedObject. - virtual void AddRef() const = 0; - virtual RefCountReleaseStatus Release() const = 0; + void AddRef() const override = 0; + RefCountReleaseStatus Release() const override = 0; // RTCStatsCollectorCallback implementation. void OnStatsDelivered( diff --git a/pc/rtp_sender_receiver_unittest.cc b/pc/rtp_sender_receiver_unittest.cc index 4c5722bd64..5074c1dfd9 100644 --- a/pc/rtp_sender_receiver_unittest.cc +++ b/pc/rtp_sender_receiver_unittest.cc @@ -71,15 +71,15 @@ namespace { -static const char kStreamId1[] = "local_stream_1"; -static const char kVideoTrackId[] = "video_1"; -static const char kAudioTrackId[] = "audio_1"; -static const uint32_t kVideoSsrc = 98; -static const uint32_t kVideoSsrc2 = 100; -static const uint32_t kAudioSsrc = 99; -static const uint32_t kAudioSsrc2 = 101; -static const uint32_t kVideoSsrcSimulcast = 102; -static const uint32_t kVideoSimulcastLayerCount = 2; +const char kStreamId1[] = "local_stream_1"; +const char kVideoTrackId[] = "video_1"; +const char kAudioTrackId[] = "audio_1"; +const uint32_t kVideoSsrc = 98; +const uint32_t kVideoSsrc2 = 100; +const uint32_t kAudioSsrc = 99; +const uint32_t kAudioSsrc2 = 101; +const uint32_t kVideoSsrcSimulcast = 102; +const uint32_t kVideoSimulcastLayerCount = 2; class MockSetStreamsObserver : public webrtc::RtpSenderBase::SetStreamsObserver { @@ -148,7 +148,7 @@ class RtpSenderReceiverTest StreamParams::CreateLegacy(kVideoSsrc2)); } - ~RtpSenderReceiverTest() { + ~RtpSenderReceiverTest() override { audio_rtp_sender_ = nullptr; video_rtp_sender_ = nullptr; audio_rtp_receiver_ = nullptr; diff --git a/pc/rtp_transmission_manager.cc b/pc/rtp_transmission_manager.cc index 1779ad422c..4d4f9a8666 100644 --- a/pc/rtp_transmission_manager.cc +++ b/pc/rtp_transmission_manager.cc @@ -51,8 +51,8 @@ namespace webrtc { namespace { -static const char kDefaultAudioSenderId[] = "defaulta0"; -static const char kDefaultVideoSenderId[] = "defaultv0"; +const char kDefaultAudioSenderId[] = "defaulta0"; +const char kDefaultVideoSenderId[] = "defaultv0"; } // namespace diff --git a/pc/rtp_transport_unittest.cc b/pc/rtp_transport_unittest.cc index b5fe2296bc..bdd03b9c9c 100644 --- a/pc/rtp_transport_unittest.cc +++ b/pc/rtp_transport_unittest.cc @@ -15,19 +15,20 @@ #include #include "api/test/rtc_error_matchers.h" +#include "api/transport/ecn_marking.h" #include "api/units/time_delta.h" #include "call/rtp_demuxer.h" #include "p2p/base/packet_transport_internal.h" #include "p2p/test/fake_packet_transport.h" #include "pc/test/rtp_transport_test_util.h" +#include "rtc_base/async_packet_socket.h" #include "rtc_base/buffer.h" #include "rtc_base/containers/flat_set.h" #include "rtc_base/copy_on_write_buffer.h" -#include "rtc_base/network/ecn_marking.h" #include "rtc_base/network/sent_packet.h" #include "rtc_base/network_route.h" #include "rtc_base/third_party/sigslot/sigslot.h" -#include "test/explicit_key_value_config.h" +#include "test/create_test_field_trials.h" #include "test/gmock.h" #include "test/gtest.h" #include "test/run_loop.h" @@ -35,8 +36,6 @@ namespace webrtc { -using test::ExplicitKeyValueConfig; - constexpr bool kMuxDisabled = false; constexpr bool kMuxEnabled = true; constexpr uint16_t kLocalNetId = 1; @@ -96,7 +95,7 @@ class SignalObserver : public sigslot::has_slots<> { }; TEST(RtpTransportTest, SettingRtcpAndRtpSignalsReady) { - RtpTransport transport(kMuxDisabled, ExplicitKeyValueConfig("")); + RtpTransport transport(kMuxDisabled, CreateTestFieldTrials()); SignalObserver observer(&transport); FakePacketTransport fake_rtcp("fake_rtcp"); @@ -111,7 +110,7 @@ TEST(RtpTransportTest, SettingRtcpAndRtpSignalsReady) { } TEST(RtpTransportTest, SettingRtpAndRtcpSignalsReady) { - RtpTransport transport(kMuxDisabled, ExplicitKeyValueConfig("")); + RtpTransport transport(kMuxDisabled, CreateTestFieldTrials()); SignalObserver observer(&transport); FakePacketTransport fake_rtcp("fake_rtcp"); fake_rtcp.SetWritable(true); @@ -125,7 +124,7 @@ TEST(RtpTransportTest, SettingRtpAndRtcpSignalsReady) { } TEST(RtpTransportTest, SettingRtpWithRtcpMuxEnabledSignalsReady) { - RtpTransport transport(kMuxEnabled, ExplicitKeyValueConfig("")); + RtpTransport transport(kMuxEnabled, CreateTestFieldTrials()); SignalObserver observer(&transport); FakePacketTransport fake_rtp("fake_rtp"); fake_rtp.SetWritable(true); @@ -135,7 +134,7 @@ TEST(RtpTransportTest, SettingRtpWithRtcpMuxEnabledSignalsReady) { } TEST(RtpTransportTest, DisablingRtcpMuxSignalsNotReady) { - RtpTransport transport(kMuxEnabled, ExplicitKeyValueConfig("")); + RtpTransport transport(kMuxEnabled, CreateTestFieldTrials()); SignalObserver observer(&transport); FakePacketTransport fake_rtp("fake_rtp"); fake_rtp.SetWritable(true); @@ -148,7 +147,7 @@ TEST(RtpTransportTest, DisablingRtcpMuxSignalsNotReady) { } TEST(RtpTransportTest, EnablingRtcpMuxSignalsReady) { - RtpTransport transport(kMuxDisabled, ExplicitKeyValueConfig("")); + RtpTransport transport(kMuxDisabled, CreateTestFieldTrials()); SignalObserver observer(&transport); FakePacketTransport fake_rtp("fake_rtp"); fake_rtp.SetWritable(true); @@ -162,7 +161,7 @@ TEST(RtpTransportTest, EnablingRtcpMuxSignalsReady) { // Tests the SignalNetworkRoute is fired when setting a packet transport. TEST(RtpTransportTest, SetRtpTransportWithNetworkRouteChanged) { - RtpTransport transport(kMuxDisabled, ExplicitKeyValueConfig("")); + RtpTransport transport(kMuxDisabled, CreateTestFieldTrials()); SignalObserver observer(&transport); FakePacketTransport fake_rtp("fake_rtp"); @@ -191,7 +190,7 @@ TEST(RtpTransportTest, SetRtpTransportWithNetworkRouteChanged) { } TEST(RtpTransportTest, SetRtcpTransportWithNetworkRouteChanged) { - RtpTransport transport(kMuxDisabled, ExplicitKeyValueConfig("")); + RtpTransport transport(kMuxDisabled, CreateTestFieldTrials()); SignalObserver observer(&transport); FakePacketTransport fake_rtcp("fake_rtcp"); @@ -224,7 +223,7 @@ TEST(RtpTransportTest, SetRtcpTransportWithNetworkRouteChanged) { TEST(RtpTransportTest, RtcpPacketSentOverCorrectTransport) { // If the RTCP-mux is not enabled, RTCP packets are expected to be sent over // the RtcpPacketTransport. - RtpTransport transport(kMuxDisabled, ExplicitKeyValueConfig("")); + RtpTransport transport(kMuxDisabled, CreateTestFieldTrials()); FakePacketTransport fake_rtcp("fake_rtcp"); FakePacketTransport fake_rtp("fake_rtp"); transport.SetRtcpPacketTransport(&fake_rtcp); // rtcp ready @@ -246,7 +245,7 @@ TEST(RtpTransportTest, RtcpPacketSentOverCorrectTransport) { } TEST(RtpTransportTest, ChangingReadyToSendStateOnlySignalsWhenChanged) { - RtpTransport transport(kMuxEnabled, ExplicitKeyValueConfig("")); + RtpTransport transport(kMuxEnabled, CreateTestFieldTrials()); TransportObserver observer(&transport); FakePacketTransport fake_rtp("fake_rtp"); fake_rtp.SetWritable(true); @@ -271,7 +270,7 @@ TEST(RtpTransportTest, ChangingReadyToSendStateOnlySignalsWhenChanged) { // Test that SignalPacketReceived fires with rtcp=true when a RTCP packet is // received. TEST(RtpTransportTest, SignalDemuxedRtcp) { - RtpTransport transport(kMuxDisabled, ExplicitKeyValueConfig("")); + RtpTransport transport(kMuxDisabled, CreateTestFieldTrials()); FakePacketTransport fake_rtp("fake_rtp"); fake_rtp.SetDestination(&fake_rtp, true); transport.SetRtpPacketTransport(&fake_rtp); @@ -294,7 +293,7 @@ static const int kRtpLen = 12; // Test that SignalPacketReceived fires with rtcp=false when a RTP packet with a // handled payload type is received. TEST(RtpTransportTest, SignalHandledRtpPayloadType) { - RtpTransport transport(kMuxDisabled, ExplicitKeyValueConfig("")); + RtpTransport transport(kMuxDisabled, CreateTestFieldTrials()); FakePacketTransport fake_rtp("fake_rtp"); fake_rtp.SetDestination(&fake_rtp, true); transport.SetRtpPacketTransport(&fake_rtp); @@ -317,7 +316,7 @@ TEST(RtpTransportTest, SignalHandledRtpPayloadType) { } TEST(RtpTransportTest, ReceivedPacketEcnMarkingPropagatedToDemuxedPacket) { - RtpTransport transport(kMuxDisabled, ExplicitKeyValueConfig("")); + RtpTransport transport(kMuxDisabled, CreateTestFieldTrials()); // Setup FakePacketTransport to send packets to itself. FakePacketTransport fake_rtp("fake_rtp"); fake_rtp.SetDestination(&fake_rtp, true); @@ -342,7 +341,7 @@ TEST(RtpTransportTest, ReceivedPacketEcnMarkingPropagatedToDemuxedPacket) { // Test that SignalPacketReceived does not fire when a RTP packet with an // unhandled payload type is received. TEST(RtpTransportTest, DontSignalUnhandledRtpPayloadType) { - RtpTransport transport(kMuxDisabled, ExplicitKeyValueConfig("")); + RtpTransport transport(kMuxDisabled, CreateTestFieldTrials()); FakePacketTransport fake_rtp("fake_rtp"); fake_rtp.SetDestination(&fake_rtp, true); transport.SetRtpPacketTransport(&fake_rtp); @@ -366,7 +365,7 @@ TEST(RtpTransportTest, DontSignalUnhandledRtpPayloadType) { TEST(RtpTransportTest, DontChangeReadyToSendStateOnSendFailure) { // ReadyToSendState should only care about if transport is writable unless the // field trial WebRTC-SetReadyToSendFalseIfSendFail/Enabled/ is set. - RtpTransport transport(kMuxEnabled, ExplicitKeyValueConfig("")); + RtpTransport transport(kMuxEnabled, CreateTestFieldTrials()); TransportObserver observer(&transport); FakePacketTransport fake_rtp("fake_rtp"); @@ -392,7 +391,7 @@ TEST(RtpTransportTest, RecursiveSetSendDoesNotCrash) { RtpTransport transport( kMuxEnabled, - ExplicitKeyValueConfig("WebRTC-SetReadyToSendFalseIfSendFail/Enabled/")); + CreateTestFieldTrials("WebRTC-SetReadyToSendFalseIfSendFail/Enabled/")); FakePacketTransport fake_rtp("fake_rtp"); transport.SetRtpPacketTransport(&fake_rtp); TransportObserver observer(&transport); @@ -419,7 +418,7 @@ TEST(RtpTransportTest, RecursiveSetSendDoesNotCrash) { TEST(RtpTransportTest, RecursiveOnSentPacketDoesNotCrash) { const int kShortTimeout = 100; test::RunLoop loop; - RtpTransport transport(kMuxDisabled, ExplicitKeyValueConfig("")); + RtpTransport transport(kMuxDisabled, CreateTestFieldTrials()); FakePacketTransport fake_rtp("fake_rtp"); transport.SetRtpPacketTransport(&fake_rtp); fake_rtp.SetDestination(&fake_rtp, true); diff --git a/pc/scenario_tests/BUILD.gn b/pc/scenario_tests/BUILD.gn index fa3a67c9a2..61136ff31e 100644 --- a/pc/scenario_tests/BUILD.gn +++ b/pc/scenario_tests/BUILD.gn @@ -13,12 +13,16 @@ if (rtc_include_tests) { testonly = true sources = [ "goog_cc_test.cc" ] deps = [ + "..:pc_test_utils", + "../../api:audio_options_api", + "../../api:make_ref_counted", + "../../api:rtc_error", "../../api:rtc_stats_api", - "../../modules/rtp_rtcp:rtp_rtcp", - "../../pc:pc_test_utils", - "../../test:field_trial", + "../../api:simulated_network_api", + "../../api/units:data_rate", + "../../api/units:time_delta", "../../test:test_support", - "../../test/peer_scenario:peer_scenario", + "../../test/peer_scenario", ] } } diff --git a/pc/scenario_tests/goog_cc_test.cc b/pc/scenario_tests/goog_cc_test.cc index 057267c7f9..bfe276474f 100644 --- a/pc/scenario_tests/goog_cc_test.cc +++ b/pc/scenario_tests/goog_cc_test.cc @@ -8,11 +8,14 @@ * be found in the AUTHORS file in the root of the source tree. */ -#include "api/stats/rtc_stats_collector_callback.h" +#include "api/audio_options.h" +#include "api/make_ref_counted.h" +#include "api/rtc_error.h" #include "api/stats/rtcstats_objects.h" +#include "api/test/simulated_network.h" #include "api/units/data_rate.h" +#include "api/units/time_delta.h" #include "pc/test/mock_peer_connection_observers.h" -#include "test/field_trial.h" #include "test/gtest.h" #include "test/peer_scenario/peer_scenario.h" #include "test/peer_scenario/peer_scenario_client.h" @@ -28,19 +31,20 @@ namespace test { #define MAYBE_NoBweChangeFromVideoUnmute NoBweChangeFromVideoUnmute #endif TEST(GoogCcPeerScenarioTest, MAYBE_NoBweChangeFromVideoUnmute) { + PeerScenarioClient::Config config; // If transport wide sequence numbers are used for audio, and the call // switches from audio only to video only, there will be a sharp change in // packets sizes. This will create a change in propagation time which might be // detected as an overuse. Using separate overuse detectors for audio and // video avoids the issue. - std::string audio_twcc_trials("WebRTC-Audio-AlrProbing/Disabled/"); - std::string separate_audio_video( - "WebRTC-Bwe-SeparateAudioPackets/" - "enabled:true,packet_threshold:15,time_threshold:1000ms/"); - ScopedFieldTrials field_trial(audio_twcc_trials + separate_audio_video); + config.field_trials.Set("WebRTC-Audio-AlrProbing", "Disabled"); + config.field_trials.Set( + "WebRTC-Bwe-SeparateAudioPackets", + "enabled:true,packet_threshold:15,time_threshold:1000ms"); + PeerScenario s(*test_info_); - auto* caller = s.CreateClient(PeerScenarioClient::Config()); - auto* callee = s.CreateClient(PeerScenarioClient::Config()); + auto* caller = s.CreateClient(config); + auto* callee = s.CreateClient(config); BuiltInNetworkBehaviorConfig net_conf; net_conf.link_capacity = DataRate::KilobitsPerSec(350); diff --git a/pc/sctp_data_channel.cc b/pc/sctp_data_channel.cc index 0faa6bbb65..2ee8e3574f 100644 --- a/pc/sctp_data_channel.cc +++ b/pc/sctp_data_channel.cc @@ -45,9 +45,9 @@ namespace webrtc { namespace { -static size_t kMaxQueuedReceivedDataBytes = 16 * 1024 * 1024; +size_t kMaxQueuedReceivedDataBytes = 16 * 1024 * 1024; -static std::atomic g_unique_id{0}; +std::atomic g_unique_id{0}; int GenerateUniqueId() { return ++g_unique_id; diff --git a/pc/sdp_munging_detector_unittest.cc b/pc/sdp_munging_detector_unittest.cc index caf28dd5f2..9627fd8303 100644 --- a/pc/sdp_munging_detector_unittest.cc +++ b/pc/sdp_munging_detector_unittest.cc @@ -27,7 +27,6 @@ #include "api/audio_codecs/builtin_audio_encoder_factory.h" #include "api/create_peerconnection_factory.h" #include "api/field_trials.h" -#include "api/field_trials_view.h" #include "api/jsep.h" #include "api/media_types.h" #include "api/peer_connection_interface.h" @@ -60,6 +59,7 @@ #include "rtc_base/strings/string_format.h" #include "rtc_base/thread.h" #include "system_wrappers/include/metrics.h" +#include "test/create_test_field_trials.h" #include "test/gmock.h" #include "test/gtest.h" #include "test/wait_until.h" @@ -116,7 +116,7 @@ class SdpMungingTest : public ::testing::Test { } std::unique_ptr CreatePeerConnection( - std::unique_ptr field_trials = nullptr) { + absl::string_view field_trials = "") { RTCConfiguration config; config.sdp_semantics = SdpSemantics::kUnifiedPlan; return CreatePeerConnection(config, std::move(field_trials)); @@ -124,10 +124,11 @@ class SdpMungingTest : public ::testing::Test { std::unique_ptr CreatePeerConnection( const RTCConfiguration& config, - std::unique_ptr field_trials) { + absl::string_view field_trials) { auto observer = std::make_unique(); PeerConnectionDependencies pc_deps(observer.get()); - pc_deps.trials = std::move(field_trials); + pc_deps.trials = + std::make_unique(CreateTestFieldTrials(field_trials)); auto result = pc_factory_->CreatePeerConnectionOrError(config, std::move(pc_deps)); EXPECT_TRUE(result.ok()); @@ -207,7 +208,7 @@ TEST_F(SdpMungingTest, InitialSetLocalDescriptionWithoutCreateOffer) { RTCConfiguration config; config.certificates.push_back( FakeRTCCertificateGenerator::GenerateCertificate()); - auto pc = CreatePeerConnection(config, nullptr); + auto pc = CreatePeerConnection(config, /*field_trials=*/""); std::string sdp = "v=0\r\n" "o=- 0 3 IN IP4 127.0.0.1\r\n" @@ -230,7 +231,7 @@ TEST_F(SdpMungingTest, InitialSetLocalDescriptionWithoutCreateAnswer) { RTCConfiguration config; config.certificates.push_back( FakeRTCCertificateGenerator::GenerateCertificate()); - auto pc = CreatePeerConnection(config, nullptr); + auto pc = CreatePeerConnection(config, /*field_trials=*/""); std::string sdp = "v=0\r\n" "o=- 0 3 IN IP4 127.0.0.1\r\n" @@ -261,8 +262,7 @@ TEST_F(SdpMungingTest, InitialSetLocalDescriptionWithoutCreateAnswer) { } TEST_F(SdpMungingTest, IceUfrag) { - auto pc = CreatePeerConnection( - FieldTrials::CreateNoGlobal("WebRTC-NoSdpMangleUfrag/Enabled/")); + auto pc = CreatePeerConnection("WebRTC-NoSdpMangleUfrag/Enabled/"); pc->AddAudioTrack("audio_track", {}); auto offer = pc->CreateOffer(); @@ -285,8 +285,7 @@ TEST_F(SdpMungingTest, IceUfrag) { } TEST_F(SdpMungingTest, IceUfragCheckDisabledByFieldTrial) { - auto pc = CreatePeerConnection( - FieldTrials::CreateNoGlobal("WebRTC-NoSdpMangleUfrag/Disabled/")); + auto pc = CreatePeerConnection("WebRTC-NoSdpMangleUfrag/Disabled/"); pc->AddAudioTrack("audio_track", {}); auto offer = pc->CreateOffer(); @@ -326,8 +325,7 @@ TEST_F(SdpMungingTest, IceUfragWithCheckDisabledForTesting) { } TEST_F(SdpMungingTest, IcePwdCheckDisabledByFieldTrial) { - auto pc = CreatePeerConnection( - FieldTrials::CreateNoGlobal("WebRTC-NoSdpMangleUfrag/Disabled/")); + auto pc = CreatePeerConnection("WebRTC-NoSdpMangleUfrag/Disabled/"); pc->AddAudioTrack("audio_track", {}); auto offer = pc->CreateOffer(); @@ -348,8 +346,7 @@ TEST_F(SdpMungingTest, IcePwdCheckDisabledByFieldTrial) { } TEST_F(SdpMungingTest, IcePwd) { - auto pc = CreatePeerConnection( - FieldTrials::CreateNoGlobal("WebRTC-NoSdpMangleUfrag/Enabled/")); + auto pc = CreatePeerConnection("WebRTC-NoSdpMangleUfrag/Enabled/"); pc->AddAudioTrack("audio_track", {}); auto offer = pc->CreateOffer(); @@ -373,10 +370,10 @@ TEST_F(SdpMungingTest, IceUfragRestrictedAddresses) { RTCConfiguration config; config.certificates.push_back( FakeRTCCertificateGenerator::GenerateCertificate()); - auto caller = CreatePeerConnection( - config, - FieldTrials::CreateNoGlobal("WebRTC-NoSdpMangleUfragRestrictedAddresses/" - "127.0.0.1:12345|127.0.0.*:23456|*:34567/")); + auto caller = + CreatePeerConnection(config, + "WebRTC-NoSdpMangleUfragRestrictedAddresses/" + "127.0.0.1:12345|127.0.0.*:23456|*:34567/"); auto callee = CreatePeerConnection(); caller->AddAudioTrack("audio_track", {}); auto offer = caller->CreateOffer(); @@ -408,7 +405,7 @@ TEST_F(SdpMungingTest, IceUfragRestrictedAddresses) { const std::string candidate = StringFormat( tmpl, absl::StrReplaceAll(address_test.first, {{":", " "}}).c_str()); caller->pc()->AddIceCandidate( - std::unique_ptr( + std::unique_ptr( CreateIceCandidate("", 0, candidate, nullptr)), [&result](RTCError error) { result = error; }); @@ -440,11 +437,11 @@ TEST_F(SdpMungingTest, IceUfragSdpRejectedAndRestrictedAddresses) { RTCConfiguration config; config.certificates.push_back( FakeRTCCertificateGenerator::GenerateCertificate()); - auto caller = CreatePeerConnection( - config, - FieldTrials::CreateNoGlobal("WebRTC-NoSdpMangleUfragRestrictedAddresses/" - "127.0.0.1:12345|127.0.0.*:23456|*:34567/" - "WebRTC-NoSdpMangleUfrag/Enabled/")); + auto caller = + CreatePeerConnection(config, + "WebRTC-NoSdpMangleUfragRestrictedAddresses/" + "127.0.0.1:12345|127.0.0.*:23456|*:34567/" + "WebRTC-NoSdpMangleUfrag/Enabled/"); auto callee = CreatePeerConnection(); caller->AddAudioTrack("audio_track", {}); auto offer = caller->CreateOffer(); @@ -555,8 +552,8 @@ TEST_F(SdpMungingTest, RemoveContentDefault) { } TEST_F(SdpMungingTest, RemoveContentKillswitch) { - auto pc = CreatePeerConnection(FieldTrials::CreateNoGlobal( - "WebRTC-NoSdpMangleNumberOfContents/Disabled/")); + auto pc = + CreatePeerConnection("WebRTC-NoSdpMangleNumberOfContents/Disabled/"); pc->AddAudioTrack("audio_track", {}); auto offer = pc->CreateOffer(); @@ -1004,7 +1001,7 @@ TEST_F(SdpMungingTest, HeaderExtensionRemoved) { ASSERT_EQ(contents.size(), 1u); auto* media_description = contents[0].media_description(); ASSERT_TRUE(media_description); - media_description->ClearRtpHeaderExtensions(); + media_description->set_rtp_header_extensions({}); RTCError error; EXPECT_TRUE(pc->SetLocalDescription(std::move(offer), &error)); diff --git a/pc/sdp_offer_answer.cc b/pc/sdp_offer_answer.cc index 4a56c84a6d..cfdefdc6ad 100644 --- a/pc/sdp_offer_answer.cc +++ b/pc/sdp_offer_answer.cc @@ -34,7 +34,6 @@ #include "api/candidate.h" #include "api/crypto/crypto_options.h" #include "api/jsep.h" -#include "api/jsep_ice_candidate.h" #include "api/make_ref_counted.h" #include "api/media_stream_interface.h" #include "api/media_types.h" @@ -146,15 +145,15 @@ const char kSessionError[] = "Session error code: "; const char kSessionErrorDesc[] = "Session error description: "; // The length of RTCP CNAMEs. -static const int kRtcpCnameLength = 16; +const int kRtcpCnameLength = 16; // The maximum length of the MID attribute. -static constexpr size_t kMidMaxSize = 16; +constexpr size_t kMidMaxSize = 16; const char kDefaultStreamId[] = "default"; // NOTE: Duplicated in peer_connection.cc: -static const char kDefaultAudioSenderId[] = "defaulta0"; -static const char kDefaultVideoSenderId[] = "defaultv0"; +const char kDefaultAudioSenderId[] = "defaulta0"; +const char kDefaultVideoSenderId[] = "defaultv0"; void NoteAddIceCandidateResult(int result) { RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result, @@ -2869,8 +2868,7 @@ void SdpOfferAnswerHandler::SetAssociatedRemoteStreams( RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams); } -bool SdpOfferAnswerHandler::AddIceCandidate( - const IceCandidateInterface* ice_candidate) { +bool SdpOfferAnswerHandler::AddIceCandidate(const IceCandidate* ice_candidate) { const AddIceCandidateResult result = AddIceCandidateInternal(ice_candidate); NoteAddIceCandidateResult(result); // If the return value is kAddIceCandidateFailNotReady, the candidate has @@ -2880,7 +2878,7 @@ bool SdpOfferAnswerHandler::AddIceCandidate( } AddIceCandidateResult SdpOfferAnswerHandler::AddIceCandidateInternal( - const IceCandidateInterface* ice_candidate) { + const IceCandidate* ice_candidate) { RTC_DCHECK_RUN_ON(signaling_thread()); TRACE_EVENT0("webrtc", "SdpOfferAnswerHandler::AddIceCandidate"); if (pc_->IsClosed()) { @@ -2926,7 +2924,7 @@ AddIceCandidateResult SdpOfferAnswerHandler::AddIceCandidateInternal( } void SdpOfferAnswerHandler::AddIceCandidate( - std::unique_ptr candidate, + std::unique_ptr candidate, std::function callback) { TRACE_EVENT0("webrtc", "SdpOfferAnswerHandler::AddIceCandidate"); RTC_DCHECK_RUN_ON(signaling_thread()); @@ -3023,7 +3021,7 @@ bool SdpOfferAnswerHandler::RemoveIceCandidates( } void SdpOfferAnswerHandler::AddLocalIceCandidate( - const JsepIceCandidate* candidate) { + const IceCandidate* candidate) { RTC_DCHECK_RUN_ON(signaling_thread()); if (local_description()) { mutable_local_description()->AddCandidate(candidate); @@ -5259,7 +5257,7 @@ bool SdpOfferAnswerHandler::UseCandidatesInRemoteDescription() { for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) { const IceCandidateCollection* candidates = remote_desc->candidates(m); for (size_t n = 0; n < candidates->count(); ++n) { - const IceCandidateInterface* candidate = candidates->at(n); + const IceCandidate* candidate = candidates->at(n); bool valid = false; if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) { if (valid) { @@ -5278,8 +5276,7 @@ bool SdpOfferAnswerHandler::UseCandidatesInRemoteDescription() { return ret; } -bool SdpOfferAnswerHandler::UseCandidate( - const IceCandidateInterface* candidate) { +bool SdpOfferAnswerHandler::UseCandidate(const IceCandidate* candidate) { RTC_DCHECK_RUN_ON(signaling_thread()); Thread::ScopedDisallowBlockingCalls no_blocking_calls; @@ -5307,7 +5304,7 @@ bool SdpOfferAnswerHandler::UseCandidate( // Not doing so may trigger the auto generation of transport description and // mess up DTLS identity information, ICE credential, etc. bool SdpOfferAnswerHandler::ReadyToUseRemoteCandidate( - const IceCandidateInterface* candidate, + const IceCandidate* candidate, const SessionDescriptionInterface* remote_desc, bool* valid) { RTC_DCHECK_RUN_ON(signaling_thread()); @@ -5371,7 +5368,7 @@ bool SdpOfferAnswerHandler::ReadyToUseRemoteCandidate( RTCErrorOr SdpOfferAnswerHandler::FindContentInfo( const SessionDescriptionInterface* description, - const IceCandidateInterface* candidate) { + const IceCandidate* candidate) { if (!candidate->sdp_mid().empty()) { auto& contents = description->description()->contents(); auto it = diff --git a/pc/sdp_offer_answer.h b/pc/sdp_offer_answer.h index e5604bf37d..899354107f 100644 --- a/pc/sdp_offer_answer.h +++ b/pc/sdp_offer_answer.h @@ -25,7 +25,6 @@ #include "api/audio_options.h" #include "api/candidate.h" #include "api/jsep.h" -#include "api/jsep_ice_candidate.h" #include "api/media_stream_interface.h" #include "api/media_types.h" #include "api/peer_connection_interface.h" @@ -147,12 +146,12 @@ class SdpOfferAnswerHandler : public SdpStateProvider { PeerConnectionInterface::RTCConfiguration GetConfiguration(); RTCError SetConfiguration( const PeerConnectionInterface::RTCConfiguration& configuration); - bool AddIceCandidate(const IceCandidateInterface* candidate); - void AddIceCandidate(std::unique_ptr candidate, + bool AddIceCandidate(const IceCandidate* candidate); + void AddIceCandidate(std::unique_ptr candidate, std::function callback); bool RemoveIceCandidates(const std::vector& candidates); // Adds a locally generated candidate to the local description. - void AddLocalIceCandidate(const JsepIceCandidate* candidate); + void AddLocalIceCandidate(const IceCandidate* candidate); void RemoveLocalIceCandidates(const std::vector& candidates); bool ShouldFireNegotiationNeededEvent(uint32_t event_id); @@ -502,18 +501,18 @@ class SdpOfferAnswerHandler : public SdpStateProvider { // description, the return value will be false. bool UseCandidatesInRemoteDescription(); // Uses `candidate` in this session. - bool UseCandidate(const IceCandidateInterface* candidate); + bool UseCandidate(const IceCandidate* candidate); // Returns true if we are ready to push down the remote candidate. // `remote_desc` is the new remote description, or NULL if the current remote // description should be used. Output `valid` is true if the candidate media // index is valid. - bool ReadyToUseRemoteCandidate(const IceCandidateInterface* candidate, + bool ReadyToUseRemoteCandidate(const IceCandidate* candidate, const SessionDescriptionInterface* remote_desc, bool* valid); RTCErrorOr FindContentInfo( const SessionDescriptionInterface* description, - const IceCandidateInterface* candidate) RTC_RUN_ON(signaling_thread()); + const IceCandidate* candidate) RTC_RUN_ON(signaling_thread()); // Functions for dealing with transports. // Note that cricket code uses the term "channel" for what other code @@ -557,8 +556,7 @@ class SdpOfferAnswerHandler : public SdpStateProvider { // Implements AddIceCandidate without reporting usage, but returns the // particular success/error value that should be reported (and can be utilized // for other purposes). - AddIceCandidateResult AddIceCandidateInternal( - const IceCandidateInterface* candidate); + AddIceCandidateResult AddIceCandidateInternal(const IceCandidate* candidate); void ReportInitialSdpMunging(bool had_local_description, SdpType type); diff --git a/pc/sdp_offer_answer_unittest.cc b/pc/sdp_offer_answer_unittest.cc index 35be43388f..263c684245 100644 --- a/pc/sdp_offer_answer_unittest.cc +++ b/pc/sdp_offer_answer_unittest.cc @@ -21,11 +21,11 @@ #include "absl/strings/numbers.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_replace.h" +#include "absl/strings/string_view.h" #include "api/audio_codecs/builtin_audio_decoder_factory.h" #include "api/audio_codecs/builtin_audio_encoder_factory.h" #include "api/create_peerconnection_factory.h" #include "api/field_trials.h" -#include "api/field_trials_view.h" #include "api/jsep.h" #include "api/media_types.h" #include "api/peer_connection_interface.h" @@ -55,6 +55,7 @@ #include "rtc_base/strings/string_format.h" #include "rtc_base/thread.h" #include "system_wrappers/include/metrics.h" +#include "test/create_test_field_trials.h" #include "test/gmock.h" #include "test/gtest.h" @@ -113,18 +114,19 @@ class SdpOfferAnswerTest : public ::testing::Test { } std::unique_ptr CreatePeerConnection( - std::unique_ptr field_trials = nullptr) { + absl::string_view field_trials = "") { RTCConfiguration config; config.sdp_semantics = SdpSemantics::kUnifiedPlan; - return CreatePeerConnection(config, std::move(field_trials)); + return CreatePeerConnection(config, field_trials); } std::unique_ptr CreatePeerConnection( const RTCConfiguration& config, - std::unique_ptr field_trials) { + absl::string_view field_trials) { auto observer = std::make_unique(); PeerConnectionDependencies pc_deps(observer.get()); - pc_deps.trials = std::move(field_trials); + pc_deps.trials = + std::make_unique(CreateTestFieldTrials(field_trials)); auto result = pc_factory_->CreatePeerConnectionOrError(config, std::move(pc_deps)); EXPECT_TRUE(result.ok()); @@ -650,8 +652,7 @@ TEST_F(SdpOfferAnswerTest, SimulcastAnswerWithNoRidsIsRejected) { } TEST_F(SdpOfferAnswerTest, SimulcastOfferWithMixedCodec) { - auto pc = CreatePeerConnection( - FieldTrials::CreateNoGlobal("WebRTC-MixedCodecSimulcast/Enabled/")); + auto pc = CreatePeerConnection("WebRTC-MixedCodecSimulcast/Enabled/"); std::optional vp8_codec_capability = FindFirstSendCodecWithName(MediaType::VIDEO, kVp8CodecName); @@ -704,8 +705,7 @@ TEST_F(SdpOfferAnswerTest, SimulcastOfferWithMixedCodec) { } TEST_F(SdpOfferAnswerTest, SimulcastAnswerWithPayloadType) { - auto pc = CreatePeerConnection( - FieldTrials::CreateNoGlobal("WebRTC-MixedCodecSimulcast/Enabled/")); + auto pc = CreatePeerConnection("WebRTC-MixedCodecSimulcast/Enabled/"); // A SDP offer with recv simulcast with payload type std::string sdp = diff --git a/pc/session_description.h b/pc/session_description.h index 3c9575f1a7..37272c4106 100644 --- a/pc/session_description.h +++ b/pc/session_description.h @@ -135,22 +135,10 @@ class MediaContentDescription { } void set_rtp_header_extensions(const RtpHeaderExtensions& extensions) { rtp_header_extensions_ = extensions; - rtp_header_extensions_set_ = true; } void AddRtpHeaderExtension(const RtpExtension& ext) { rtp_header_extensions_.push_back(ext); - rtp_header_extensions_set_ = true; - } - void ClearRtpHeaderExtensions() { - rtp_header_extensions_.clear(); - rtp_header_extensions_set_ = true; - } - // We can't always tell if an empty list of header extensions is - // because the other side doesn't support them, or just isn't hooked up to - // signal them. For now we assume an empty list means no signaling, but - // provide the ClearRtpHeaderExtensions method to allow "no support" to be - // clearly indicated (i.e. when derived from other information). - bool rtp_header_extensions_set() const { return rtp_header_extensions_set_; } + } const StreamParamsVec& streams() const { return send_streams_; } // TODO(pthatcher): Remove this by giving mediamessage.cc access // to MediaContentDescription @@ -266,7 +254,6 @@ class MediaContentDescription { std::string bandwidth_type_ = kApplicationSpecificBandwidth; std::vector rtp_header_extensions_; - bool rtp_header_extensions_set_ = false; StreamParamsVec send_streams_; bool conference_mode_ = false; RtpTransceiverDirection direction_ = RtpTransceiverDirection::kSendRecv; diff --git a/pc/srtp_session_unittest.cc b/pc/srtp_session_unittest.cc index 56a38dc1f0..af004104c7 100644 --- a/pc/srtp_session_unittest.cc +++ b/pc/srtp_session_unittest.cc @@ -17,6 +17,7 @@ #include #include +#include "api/field_trials.h" #include "media/base/fake_rtp.h" #include "pc/test/srtp_test_util.h" #include "rtc_base/buffer.h" @@ -24,9 +25,9 @@ #include "rtc_base/copy_on_write_buffer.h" #include "rtc_base/ssl_stream_adapter.h" // For webrtc::SRTP_* #include "system_wrappers/include/metrics.h" +#include "test/create_test_field_trials.h" #include "test/gmock.h" #include "test/gtest.h" -#include "test/scoped_key_value_config.h" #include "third_party/libsrtp/include/srtp.h" using ::testing::ElementsAre; @@ -43,7 +44,7 @@ class SrtpSessionTest : public ::testing::Test { } protected: - virtual void SetUp() { + void SetUp() override { rtp_len_ = sizeof(kPcmuFrame); rtcp_len_ = sizeof(kRtcpReport); rtp_packet_.EnsureCapacity(rtp_len_ + 10); @@ -78,7 +79,7 @@ class SrtpSessionTest : public ::testing::Test { EXPECT_EQ( 0, std::memcmp(kRtcpReport, rtcp_packet_.data(), rtcp_packet_.size())); } - test::ScopedKeyValueConfig field_trials_; + FieldTrials field_trials_ = CreateTestFieldTrials(); SrtpSession s1_; SrtpSession s2_; CopyOnWriteBuffer rtp_packet_; diff --git a/pc/srtp_transport_unittest.cc b/pc/srtp_transport_unittest.cc index 91558324fd..f0e84154ae 100644 --- a/pc/srtp_transport_unittest.cc +++ b/pc/srtp_transport_unittest.cc @@ -16,6 +16,7 @@ #include #include +#include "api/field_trials.h" #include "call/rtp_demuxer.h" #include "media/base/fake_rtp.h" #include "p2p/dtls/dtls_transport_internal.h" @@ -30,8 +31,8 @@ #include "rtc_base/copy_on_write_buffer.h" #include "rtc_base/ssl_stream_adapter.h" #include "rtc_base/third_party/sigslot/sigslot.h" +#include "test/create_test_field_trials.h" #include "test/gtest.h" -#include "test/scoped_key_value_config.h" using ::webrtc::kSrtpAeadAes128Gcm; using ::webrtc::kTestKey1; @@ -88,7 +89,7 @@ class SrtpTransportTest : public ::testing::Test, public sigslot::has_slots<> { srtp_transport2_->RegisterRtpDemuxerSink(demuxer_criteria, &rtp_sink2_); } - ~SrtpTransportTest() { + ~SrtpTransportTest() override { if (srtp_transport1_) { srtp_transport1_->UnregisterRtpDemuxerSink(&rtp_sink1_); } @@ -332,7 +333,7 @@ class SrtpTransportTest : public ::testing::Test, public sigslot::has_slots<> { TransportObserver rtp_sink2_; int sequence_number_ = 0; - test::ScopedKeyValueConfig field_trials_; + FieldTrials field_trials_ = CreateTestFieldTrials(); }; class SrtpTransportTestWithExternalAuth @@ -414,8 +415,8 @@ TEST_F(SrtpTransportTest, TestSetParamsKeyTooShort) { } TEST_F(SrtpTransportTest, RemoveSrtpReceiveStream) { - test::ScopedKeyValueConfig field_trials( - "WebRTC-SrtpRemoveReceiveStream/Enabled/"); + FieldTrials field_trials = + CreateTestFieldTrials("WebRTC-SrtpRemoveReceiveStream/Enabled/"); auto srtp_transport = std::make_unique(/*rtcp_mux_enabled=*/true, field_trials); auto rtp_packet_transport = diff --git a/pc/test/enable_fake_media.cc b/pc/test/enable_fake_media.cc index 3102e5faa1..bafc053971 100644 --- a/pc/test/enable_fake_media.cc +++ b/pc/test/enable_fake_media.cc @@ -40,7 +40,7 @@ void EnableFakeMedia( std::unique_ptr CreateMediaEngine( const Environment& /*env*/, - PeerConnectionFactoryDependencies& /*dependencies*/) { + PeerConnectionFactoryDependencies& /*dependencies*/) override { RTC_CHECK(fake_ != nullptr) << "CreateMediaEngine can be called at most once."; return std::move(fake_); diff --git a/pc/test/fake_peer_connection_base.h b/pc/test/fake_peer_connection_base.h index 10e54cab6b..fda2a03c25 100644 --- a/pc/test/fake_peer_connection_base.h +++ b/pc/test/fake_peer_connection_base.h @@ -28,6 +28,7 @@ #include "api/data_channel_event_observer_interface.h" #include "api/data_channel_interface.h" #include "api/dtls_transport_interface.h" +#include "api/field_trials.h" #include "api/field_trials_view.h" #include "api/jsep.h" #include "api/media_stream_interface.h" @@ -63,7 +64,7 @@ #include "rtc_base/ssl_certificate.h" #include "rtc_base/ssl_stream_adapter.h" #include "rtc_base/thread.h" -#include "test/scoped_key_value_config.h" +#include "test/create_test_field_trials.h" namespace webrtc { @@ -224,9 +225,7 @@ class FakePeerConnectionBase : public PeerConnectionInternal { return RTCError(); } - bool AddIceCandidate(const IceCandidateInterface* candidate) override { - return false; - } + bool AddIceCandidate(const IceCandidate* candidate) override { return false; } bool RemoveIceCandidates(const std::vector& candidates) override { return false; @@ -413,7 +412,7 @@ class FakePeerConnectionBase : public PeerConnectionInternal { CandidateStatsList GetPooledCandidateStats() const override { return {}; } protected: - test::ScopedKeyValueConfig field_trials_; + FieldTrials field_trials_ = CreateTestFieldTrials(); PayloadTypePicker payload_type_picker_; }; diff --git a/pc/test/integration_test_helpers.h b/pc/test/integration_test_helpers.h index 8eda1f5783..dc695d5e6e 100644 --- a/pc/test/integration_test_helpers.h +++ b/pc/test/integration_test_helpers.h @@ -94,6 +94,7 @@ #include "rtc_base/time_utils.h" #include "rtc_base/virtual_socket_server.h" #include "system_wrappers/include/metrics.h" +#include "test/create_test_field_trials.h" #include "test/gmock.h" #include "test/gtest.h" #include "test/wait_until.h" @@ -652,7 +653,7 @@ class PeerConnectionIntegrationWrapper : public PeerConnectionObserver, } return Candidate(); } - const IceCandidateInterface* last_gathered_ice_candidate() const { + const IceCandidate* last_gathered_ice_candidate() const { return last_gathered_ice_candidate_.get(); } const IceCandidateErrorEvent& error_event() const { return error_event_; } @@ -1068,7 +1069,7 @@ class PeerConnectionIntegrationWrapper : public PeerConnectionObserver, ice_candidate_pair_change_history_.push_back(event); } - void OnIceCandidate(const IceCandidateInterface* candidate) override { + void OnIceCandidate(const IceCandidate* candidate) override { RTC_LOG(LS_INFO) << debug_name_ << ": OnIceCandidate"; if (remote_async_dns_resolver_) { @@ -1094,8 +1095,7 @@ class PeerConnectionIntegrationWrapper : public PeerConnectionObserver, // Check if we expected to have a candidate. EXPECT_GT(candidates_expected_, 1); candidates_expected_--; - std::string ice_sdp; - EXPECT_TRUE(candidate->ToString(&ice_sdp)); + std::string ice_sdp = candidate->ToString(); if (signaling_message_receiver_ == nullptr || !signal_ice_candidates_) { // Remote party may be deleted. return; @@ -1155,7 +1155,7 @@ class PeerConnectionIntegrationWrapper : public PeerConnectionObserver, SignalingMessageReceiver* signaling_message_receiver_ = nullptr; int signaling_delay_ms_ = 0; bool signal_ice_candidates_ = true; - std::unique_ptr last_gathered_ice_candidate_; + std::unique_ptr last_gathered_ice_candidate_; IceCandidateErrorEvent error_event_; // Store references to the video sources we've created, so that we can stop @@ -1469,11 +1469,12 @@ class PeerConnectionIntegrationBaseTest : public ::testing::Test { if (it != field_trials_overrides_.end()) { field_trials = it->second; } - if (!client->Init(options, &modified_config, std::move(dependencies), - fss_.get(), network_thread_.get(), worker_thread_.get(), - FieldTrials::CreateNoGlobal(field_trials), - std::move(event_log_factory), reset_encoder_factory, - reset_decoder_factory, create_media_engine)) { + if (!client->Init( + options, &modified_config, std::move(dependencies), fss_.get(), + network_thread_.get(), worker_thread_.get(), + std::make_unique(CreateTestFieldTrials(field_trials)), + std::move(event_log_factory), reset_encoder_factory, + reset_decoder_factory, create_media_engine)) { return nullptr; } return client; diff --git a/pc/test/mock_peer_connection_internal.h b/pc/test/mock_peer_connection_internal.h index a52c9a4a18..51c4eafec7 100644 --- a/pc/test/mock_peer_connection_internal.h +++ b/pc/test/mock_peer_connection_internal.h @@ -208,10 +208,7 @@ class MockPeerConnectionInternal : public PeerConnectionInternal { SetConfiguration, (const PeerConnectionInterface::RTCConfiguration&), (override)); - MOCK_METHOD(bool, - AddIceCandidate, - (const IceCandidateInterface*), - (override)); + MOCK_METHOD(bool, AddIceCandidate, (const IceCandidate*), (override)); MOCK_METHOD(bool, RemoveIceCandidates, (const std::vector&), diff --git a/pc/test/mock_peer_connection_observers.h b/pc/test/mock_peer_connection_observers.h index 6bd77437b2..a5e668ac93 100644 --- a/pc/test/mock_peer_connection_observers.h +++ b/pc/test/mock_peer_connection_observers.h @@ -27,7 +27,6 @@ #include "api/candidate.h" #include "api/data_channel_interface.h" #include "api/jsep.h" -#include "api/jsep_ice_candidate.h" #include "api/legacy_stats_types.h" #include "api/make_ref_counted.h" #include "api/media_stream_interface.h" @@ -136,9 +135,9 @@ class MockPeerConnectionObserver : public PeerConnectionObserver { new_state == PeerConnectionInterface::kIceGatheringComplete; callback_triggered_ = true; } - void OnIceCandidate(const IceCandidateInterface* candidate) override { + void OnIceCandidate(const IceCandidate* candidate) override { RTC_DCHECK(pc_); - candidates_.push_back(std::make_unique( + candidates_.push_back(std::make_unique( candidate->sdp_mid(), candidate->sdp_mline_index(), candidate->candidate())); callback_triggered_ = true; @@ -209,7 +208,7 @@ class MockPeerConnectionObserver : public PeerConnectionObserver { return ""; } - IceCandidateInterface* last_candidate() { + IceCandidate* last_candidate() { if (candidates_.empty()) { return nullptr; } else { @@ -217,16 +216,16 @@ class MockPeerConnectionObserver : public PeerConnectionObserver { } } - std::vector GetAllCandidates() { - std::vector candidates; + std::vector GetAllCandidates() { + std::vector candidates; for (const auto& candidate : candidates_) { candidates.push_back(candidate.get()); } return candidates; } - std::vector GetCandidatesByMline(int mline_index) { - std::vector candidates; + std::vector GetCandidatesByMline(int mline_index) { + std::vector candidates; for (const auto& candidate : candidates_) { if (candidate->sdp_mline_index() == mline_index) { candidates.push_back(candidate.get()); @@ -250,7 +249,7 @@ class MockPeerConnectionObserver : public PeerConnectionObserver { scoped_refptr pc_; PeerConnectionInterface::SignalingState state_; - std::vector> candidates_; + std::vector> candidates_; scoped_refptr last_datachannel_; scoped_refptr remote_streams_; bool renegotiation_needed_ = false; diff --git a/pc/test/peer_connection_test_wrapper.cc b/pc/test/peer_connection_test_wrapper.cc index 37877d6387..95be4b30bf 100644 --- a/pc/test/peer_connection_test_wrapper.cc +++ b/pc/test/peer_connection_test_wrapper.cc @@ -19,6 +19,7 @@ #include #include "absl/strings/match.h" +#include "absl/strings/str_cat.h" #include "api/audio/audio_device.h" #include "api/audio_codecs/audio_decoder_factory.h" #include "api/audio_codecs/audio_encoder_factory.h" @@ -66,7 +67,6 @@ #include "rtc_base/logging.h" #include "rtc_base/rtc_certificate_generator.h" #include "rtc_base/socket_server.h" -#include "rtc_base/string_encode.h" #include "rtc_base/time_utils.h" #include "test/gmock.h" #include "test/gtest.h" @@ -77,7 +77,7 @@ namespace { using ::webrtc::Environment; using ::webrtc::FakeVideoTrackRenderer; using ::webrtc::FieldTrialsView; -using ::webrtc::IceCandidateInterface; +using ::webrtc::IceCandidate; using ::webrtc::MediaStreamInterface; using ::webrtc::MediaStreamTrackInterface; using ::webrtc::MockSetSessionDescriptionObserver; @@ -281,10 +281,8 @@ void PeerConnectionTestWrapper::OnAddTrack( } } -void PeerConnectionTestWrapper::OnIceCandidate( - const IceCandidateInterface* candidate) { - std::string sdp; - EXPECT_TRUE(candidate->ToString(&sdp)); +void PeerConnectionTestWrapper::OnIceCandidate(const IceCandidate* candidate) { + std::string sdp = candidate->ToString(); SignalOnIceCandidateReady(candidate->sdp_mid(), candidate->sdp_mline_index(), sdp); } @@ -358,7 +356,7 @@ void PeerConnectionTestWrapper::SetRemoteDescription(SdpType type, void PeerConnectionTestWrapper::AddIceCandidate(const std::string& sdp_mid, int sdp_mline_index, const std::string& candidate) { - std::unique_ptr owned_candidate( + std::unique_ptr owned_candidate( webrtc::CreateIceCandidate(sdp_mid, sdp_mline_index, candidate, nullptr)); EXPECT_TRUE(peer_connection_->AddIceCandidate(owned_candidate.get())); } diff --git a/pc/test/peer_connection_test_wrapper.h b/pc/test/peer_connection_test_wrapper.h index 30fa5c407f..1ca52981c6 100644 --- a/pc/test/peer_connection_test_wrapper.h +++ b/pc/test/peer_connection_test_wrapper.h @@ -98,7 +98,7 @@ class PeerConnectionTestWrapper webrtc::PeerConnectionInterface::IceConnectionState new_state) override {} void OnIceGatheringChange( webrtc::PeerConnectionInterface::IceGatheringState new_state) override {} - void OnIceCandidate(const webrtc::IceCandidateInterface* candidate) override; + void OnIceCandidate(const webrtc::IceCandidate* candidate) override; // Implements CreateSessionDescriptionObserver. void OnSuccess(webrtc::SessionDescriptionInterface* desc) override; diff --git a/pc/test/svc_e2e_tests.cc b/pc/test/svc_e2e_tests.cc index a5496822fb..c51bc9985f 100644 --- a/pc/test/svc_e2e_tests.cc +++ b/pc/test/svc_e2e_tests.cc @@ -17,6 +17,7 @@ #include #include "absl/strings/string_view.h" +#include "api/field_trials.h" #include "api/function_view.h" #include "api/rtp_parameters.h" #include "api/scoped_refptr.h" @@ -44,13 +45,10 @@ #include "rtc_base/containers/flat_map.h" #include "rtc_base/logging.h" #include "system_wrappers/include/clock.h" -#include "system_wrappers/include/field_trial.h" -#include "test/field_trial.h" #include "test/gmock.h" #include "test/gtest.h" #include "test/pc/e2e/analyzer/video/default_video_quality_analyzer.h" #include "test/pc/e2e/analyzer/video/default_video_quality_analyzer_shared_objects.h" -#include "test/testsupport/file_utils.h" namespace webrtc { namespace { @@ -88,11 +86,6 @@ CreateTestFixture(absl::string_view test_case_name, return fixture; } -// Takes the current active field trials set, and appends some new trials. -std::string AppendFieldTrials(std::string new_trial_string) { - return std::string(field_trial::GetFieldTrialString()) + new_trial_string; -} - enum class UseDependencyDescriptor { Enabled, Disabled, @@ -317,11 +310,10 @@ MATCHER_P2(HasSpatialAndTemporalLayersSMode, } TEST_P(SvcTest, ScalabilityModeSupported) { - std::string trials; + FieldTrials trials(""); if (UseDependencyDescriptor()) { - trials += "WebRTC-DependencyDescriptorAdvertised/Enabled/"; + trials.Set("WebRTC-DependencyDescriptorAdvertised", "Enabled"); } - test::ScopedFieldTrials override_trials(AppendFieldTrials(trials)); std::unique_ptr network_emulation_manager = CreateNetworkEmulationManager({.time_mode = TimeMode::kSimulated}); auto analyzer = std::make_unique( @@ -332,7 +324,7 @@ TEST_P(SvcTest, ScalabilityModeSupported) { *network_emulation_manager->time_controller(), network_emulation_manager->CreateEndpointPairWithTwoWayRoutes( BuiltInNetworkBehaviorConfig()), - [this](PeerConfigurer* alice) { + [&](PeerConfigurer* alice) { VideoConfig video(/*stream_label=*/"alice-video", /*width=*/1850, /*height=*/1110, /*fps=*/30); if (IsSMode()) { @@ -347,8 +339,10 @@ TEST_P(SvcTest, ScalabilityModeSupported) { video, ScreenShareConfig(TimeDelta::Seconds(5))); alice->AddVideoConfig(std::move(video), std::move(generator)); alice->SetVideoCodecs({video_codec_config}); + alice->AddFieldTrials(trials); }, - [](PeerConfigurer* bob) {}, std::move(analyzer)); + [&](PeerConfigurer* bob) { bob->AddFieldTrials(trials); }, + std::move(analyzer)); fixture->Run(RunParams(TimeDelta::Seconds(10))); EXPECT_THAT(analyzer_ptr->encoder_layers_seen(), HasSpatialAndTemporalLayers( diff --git a/pc/webrtc_sdp.cc b/pc/webrtc_sdp.cc index 958287c5e7..6e434676f9 100644 --- a/pc/webrtc_sdp.cc +++ b/pc/webrtc_sdp.cc @@ -33,7 +33,6 @@ #include "api/audio/audio_view.h" #include "api/candidate.h" #include "api/jsep.h" -#include "api/jsep_ice_candidate.h" #include "api/jsep_session_description.h" #include "api/media_types.h" #include "api/rtc_error.h" @@ -56,7 +55,6 @@ #include "pc/session_description.h" #include "pc/simulcast_description.h" #include "pc/simulcast_sdp_serializer.h" -#include "rtc_base/arraysize.h" #include "rtc_base/checks.h" #include "rtc_base/crypto_random.h" #include "rtc_base/ip_address.h" @@ -69,164 +67,162 @@ #include "rtc_base/string_encode.h" #include "rtc_base/strings/string_builder.h" -// TODO(deadbeef): Switch to using anonymous namespace rather than declaring -// everything "static". namespace webrtc { +namespace { // Line type // RFC 4566 // An SDP session description consists of a number of lines of text of // the form: // = // where MUST be exactly one case-significant character. - -// Check if passed character is a "token-char" from RFC 4566. -// https://datatracker.ietf.org/doc/html/rfc4566#section-9 -// token-char = %x21 / %x23-27 / %x2A-2B / %x2D-2E / %x30-39 -// / %x41-5A / %x5E-7E -bool IsTokenChar(char ch) { - return ch == 0x21 || (ch >= 0x23 && ch <= 0x27) || ch == 0x2a || ch == 0x2b || - ch == 0x2d || ch == 0x2e || (ch >= 0x30 && ch <= 0x39) || - (ch >= 0x41 && ch <= 0x5a) || (ch >= 0x5e && ch <= 0x7e); -} -static const int kLinePrefixLength = 2; // Length of = -static const char kLineTypeVersion = 'v'; -static const char kLineTypeOrigin = 'o'; -static const char kLineTypeSessionName = 's'; -static const char kLineTypeSessionInfo = 'i'; -static const char kLineTypeSessionUri = 'u'; -static const char kLineTypeSessionEmail = 'e'; -static const char kLineTypeSessionPhone = 'p'; -static const char kLineTypeSessionBandwidth = 'b'; -static const char kLineTypeTiming = 't'; -static const char kLineTypeRepeatTimes = 'r'; -static const char kLineTypeTimeZone = 'z'; -static const char kLineTypeEncryptionKey = 'k'; -static const char kLineTypeMedia = 'm'; -static const char kLineTypeConnection = 'c'; -static const char kLineTypeAttributes = 'a'; +const int kLinePrefixLength = 2; // Length of = +const char kLineTypeVersion = 'v'; +const char kLineTypeOrigin = 'o'; +const char kLineTypeSessionName = 's'; +const char kLineTypeSessionInfo = 'i'; +const char kLineTypeSessionUri = 'u'; +const char kLineTypeSessionEmail = 'e'; +const char kLineTypeSessionPhone = 'p'; +const char kLineTypeSessionBandwidth = 'b'; +const char kLineTypeTiming = 't'; +const char kLineTypeRepeatTimes = 'r'; +const char kLineTypeTimeZone = 'z'; +const char kLineTypeEncryptionKey = 'k'; +const char kLineTypeMedia = 'm'; +const char kLineTypeConnection = 'c'; +const char kLineTypeAttributes = 'a'; // Attributes -static const char kAttributeGroup[] = "group"; -static const char kAttributeMid[] = "mid"; -static const char kAttributeMsid[] = "msid"; -static const char kAttributeBundleOnly[] = "bundle-only"; -static const char kAttributeRtcpMux[] = "rtcp-mux"; -static const char kAttributeRtcpReducedSize[] = "rtcp-rsize"; -static const char kAttributeSsrc[] = "ssrc"; -static const char kSsrcAttributeCname[] = "cname"; -static const char kAttributeExtmapAllowMixed[] = "extmap-allow-mixed"; -static const char kAttributeExtmap[] = "extmap"; +const char kAttributeGroup[] = "group"; +const char kAttributeMid[] = "mid"; +const char kAttributeMsid[] = "msid"; +const char kAttributeBundleOnly[] = "bundle-only"; +const char kAttributeRtcpMux[] = "rtcp-mux"; +const char kAttributeRtcpReducedSize[] = "rtcp-rsize"; +const char kAttributeSsrc[] = "ssrc"; +const char kSsrcAttributeCname[] = "cname"; +const char kAttributeExtmapAllowMixed[] = "extmap-allow-mixed"; +const char kAttributeExtmap[] = "extmap"; // draft-alvestrand-mmusic-msid-01 // a=msid-semantic: WMS // This is a legacy field supported only for Plan B semantics. -static const char kAttributeMsidSemantics[] = "msid-semantic"; -static const char kMediaStreamSemantic[] = "WMS"; -static const char kSsrcAttributeMsid[] = "msid"; -static const char kDefaultMsid[] = "default"; -static const char kNoStreamMsid[] = "-"; -static const char kAttributeSsrcGroup[] = "ssrc-group"; -static const char kAttributeCandidate[] = "candidate"; -static const char kAttributeCandidateTyp[] = "typ"; -static const char kAttributeCandidateRaddr[] = "raddr"; -static const char kAttributeCandidateRport[] = "rport"; -static const char kAttributeCandidateUfrag[] = "ufrag"; -static const char kAttributeCandidatePwd[] = "pwd"; -static const char kAttributeCandidateGeneration[] = "generation"; -static const char kAttributeCandidateNetworkId[] = "network-id"; -static const char kAttributeCandidateNetworkCost[] = "network-cost"; -static const char kAttributeFingerprint[] = "fingerprint"; -static const char kAttributeSetup[] = "setup"; -static const char kAttributeFmtp[] = "fmtp"; -static const char kAttributeRtpmap[] = "rtpmap"; -static const char kAttributeSctpmap[] = "sctpmap"; -static const char kAttributeRtcp[] = "rtcp"; -static const char kAttributeIceUfrag[] = "ice-ufrag"; -static const char kAttributeIcePwd[] = "ice-pwd"; -static const char kAttributeIceLite[] = "ice-lite"; -static const char kAttributeIceOption[] = "ice-options"; -static const char kAttributeSendOnly[] = "sendonly"; -static const char kAttributeRecvOnly[] = "recvonly"; -static const char kAttributeRtcpFb[] = "rtcp-fb"; -static const char kAttributeSendRecv[] = "sendrecv"; -static const char kAttributeInactive[] = "inactive"; +const char kAttributeMsidSemantics[] = "msid-semantic"; +const char kMediaStreamSemantic[] = "WMS"; +const char kSsrcAttributeMsid[] = "msid"; +const char kDefaultMsid[] = "default"; +const char kNoStreamMsid[] = "-"; +const char kAttributeSsrcGroup[] = "ssrc-group"; +const char kAttributeCandidate[] = "candidate"; +const char kAttributeCandidateTyp[] = "typ"; +const char kAttributeCandidateRaddr[] = "raddr"; +const char kAttributeCandidateRport[] = "rport"; +const char kAttributeCandidateUfrag[] = "ufrag"; +const char kAttributeCandidatePwd[] = "pwd"; +const char kAttributeCandidateGeneration[] = "generation"; +const char kAttributeCandidateNetworkId[] = "network-id"; +const char kAttributeCandidateNetworkCost[] = "network-cost"; +const char kAttributeFingerprint[] = "fingerprint"; +const char kAttributeSetup[] = "setup"; +const char kAttributeFmtp[] = "fmtp"; +const char kAttributeRtpmap[] = "rtpmap"; +const char kAttributeSctpmap[] = "sctpmap"; +const char kAttributeRtcp[] = "rtcp"; +const char kAttributeIceUfrag[] = "ice-ufrag"; +const char kAttributeIcePwd[] = "ice-pwd"; +const char kAttributeIceLite[] = "ice-lite"; +const char kAttributeIceOption[] = "ice-options"; +const char kAttributeSendOnly[] = "sendonly"; +const char kAttributeRecvOnly[] = "recvonly"; +const char kAttributeRtcpFb[] = "rtcp-fb"; +const char kAttributeSendRecv[] = "sendrecv"; +const char kAttributeInactive[] = "inactive"; // draft-ietf-mmusic-sctp-sdp-26 // a=sctp-port, a=max-message-size -static const char kAttributeSctpPort[] = "sctp-port"; -static const char kAttributeMaxMessageSize[] = "max-message-size"; -static const int kDefaultSctpMaxMessageSize = 65536; +const char kAttributeSctpPort[] = "sctp-port"; +const char kAttributeMaxMessageSize[] = "max-message-size"; +const int kDefaultSctpMaxMessageSize = 65536; // draft-ietf-mmusic-sdp-simulcast-13 // a=simulcast -static const char kAttributeSimulcast[] = "simulcast"; +constexpr absl::string_view kAttributeSimulcast = "simulcast"; // draft-ietf-mmusic-rid-15 // a=rid -static const char kAttributeRid[] = "rid"; -static const char kAttributePacketization[] = "packetization"; +constexpr absl::string_view kAttributeRid = "rid"; +const char kAttributePacketization[] = "packetization"; // Experimental flags -static const char kAttributeXGoogleFlag[] = "x-google-flag"; -static const char kValueConference[] = "conference"; +const char kAttributeXGoogleFlag[] = "x-google-flag"; +const char kValueConference[] = "conference"; -static const char kAttributeRtcpRemoteEstimate[] = "remote-net-estimate"; +const char kAttributeRtcpRemoteEstimate[] = "remote-net-estimate"; // Candidate -static const char kCandidateHost[] = "host"; -static const char kCandidateSrflx[] = "srflx"; -static const char kCandidatePrflx[] = "prflx"; -static const char kCandidateRelay[] = "relay"; -static const char kTcpCandidateType[] = "tcptype"; +const char kCandidateHost[] = "host"; +const char kCandidateSrflx[] = "srflx"; +const char kCandidatePrflx[] = "prflx"; +const char kCandidateRelay[] = "relay"; +const char kTcpCandidateType[] = "tcptype"; // StringBuilder doesn't have a << overload for chars, while // split and tokenize_first both take a char delimiter. To // handle both cases these constants come in pairs of a chars and length-one // strings. -static const char kSdpDelimiterEqual[] = "="; -static const char kSdpDelimiterEqualChar = '='; -static const char kSdpDelimiterSpace[] = " "; -static const char kSdpDelimiterSpaceChar = ' '; -static const char kSdpDelimiterColon[] = ":"; -static const char kSdpDelimiterColonChar = ':'; -static const char kSdpDelimiterSemicolon[] = ";"; -static const char kSdpDelimiterSemicolonChar = ';'; -static const char kSdpDelimiterSlashChar = '/'; -static const char kNewLineChar = '\n'; -static const char kReturnChar = '\r'; -static const char kLineBreak[] = "\r\n"; +const char kSdpDelimiterEqual[] = "="; +const char kSdpDelimiterEqualChar = '='; +const char kSdpDelimiterSpace[] = " "; +const char kSdpDelimiterSpaceChar = ' '; +constexpr absl::string_view kSdpDelimiterColon = ":"; +const char kSdpDelimiterColonChar = ':'; +const char kSdpDelimiterSemicolon[] = ";"; +const char kSdpDelimiterSemicolonChar = ';'; +const char kSdpDelimiterSlashChar = '/'; +const char kNewLineChar = '\n'; +const char kReturnChar = '\r'; +const char kLineBreak[] = "\r\n"; // TODO(deadbeef): Generate the Session and Time description // instead of hardcoding. -static const char kSessionVersion[] = "v=0"; +const char kSessionVersion[] = "v=0"; // RFC 4566 -static const char kSessionOriginUsername[] = "-"; -static const char kSessionOriginSessionId[] = "0"; -static const char kSessionOriginSessionVersion[] = "0"; -static const char kSessionOriginNettype[] = "IN"; -static const char kSessionOriginAddrtype[] = "IP4"; -static const char kSessionOriginAddress[] = "127.0.0.1"; -static const char kSessionName[] = "s=-"; -static const char kTimeDescription[] = "t=0 0"; -static const char kAttrGroup[] = "a=group:BUNDLE"; -static const char kConnectionNettype[] = "IN"; -static const char kConnectionIpv4Addrtype[] = "IP4"; -static const char kConnectionIpv6Addrtype[] = "IP6"; -static const char kSdpMediaTypeVideo[] = "video"; -static const char kSdpMediaTypeAudio[] = "audio"; -static const char kSdpMediaTypeData[] = "application"; -static const char kMediaPortRejected[] = "0"; +const char kSessionOriginUsername[] = "-"; +const char kSessionOriginSessionId[] = "0"; +const char kSessionOriginSessionVersion[] = "0"; +const char kSessionOriginNettype[] = "IN"; +const char kSessionOriginAddrtype[] = "IP4"; +const char kSessionOriginAddress[] = "127.0.0.1"; +const char kSessionName[] = "s=-"; +const char kTimeDescription[] = "t=0 0"; +const char kAttrGroup[] = "a=group:BUNDLE"; +const char kConnectionNettype[] = "IN"; +const char kConnectionIpv4Addrtype[] = "IP4"; +const char kConnectionIpv6Addrtype[] = "IP6"; +const char kSdpMediaTypeVideo[] = "video"; +const char kSdpMediaTypeAudio[] = "audio"; +const char kSdpMediaTypeData[] = "application"; +const char kMediaPortRejected[] = "0"; // draft-ietf-mmusic-trickle-ice-01 // When no candidates have been gathered, set the connection // address to IP6 ::. // TODO(perkj): FF can not parse IP6 ::. See http://crbug/430333 // Use IPV4 per default. -static const char kDummyAddress[] = "0.0.0.0"; -static const char kDummyPort[] = "9"; +const char kDummyAddress[] = "0.0.0.0"; +const char kDummyPort[] = "9"; -static const char kDefaultSctpmapProtocol[] = "webrtc-datachannel"; +const char kDefaultSctpmapProtocol[] = "webrtc-datachannel"; // RTP payload type is in the 0-127 range. Use -1 to indicate "all" payload // types. const int kWildcardPayloadType = -1; +// Check if passed character is a "token-char" from RFC 4566. +// https://datatracker.ietf.org/doc/html/rfc4566#section-9 +// token-char = %x21 / %x23-27 / %x2A-2B / %x2D-2E / %x30-39 +// / %x41-5A / %x5E-7E +bool IsTokenChar(char ch) { + return ch == 0x21 || (ch >= 0x23 && ch <= 0x27) || ch == 0x2a || ch == 0x2b || + ch == 0x2d || ch == 0x2e || (ch >= 0x30 && ch <= 0x39) || + (ch >= 0x41 && ch <= 0x5a) || (ch >= 0x5e && ch <= 0x7e); +} struct SsrcInfo { uint32_t ssrc_id; std::string cname; @@ -236,129 +232,6 @@ struct SsrcInfo { using SsrcInfoVec = std::vector; using SsrcGroupVec = std::vector; -static void BuildMediaDescription(const ContentInfo* content_info, - const TransportInfo* transport_info, - const MediaType media_type, - const std::vector& candidates, - int msid_signaling, - std::string* message); -static void BuildMediaLine(const MediaType media_type, - const ContentInfo* content_info, - const MediaContentDescription* media_desc, - std::string* message); -static void BuildRtpContentAttributes(const MediaContentDescription* media_desc, - const MediaType media_type, - int msid_signaling, - std::string* message); -static void BuildRtpHeaderExtensions(const RtpHeaderExtensions& extensions, - std::string* message); -static void BuildRtpmap(const MediaContentDescription* media_desc, - const MediaType media_type, - std::string* message); -static void BuildCandidate(const std::vector& candidates, - bool include_ufrag, - std::string* message); -static void BuildIceUfragPwd(const TransportInfo* transport_info, - std::string* message); -static void BuildDtlsFingerprintSetup(const TransportInfo* transport_info, - std::string* message); -static void BuildIceOptions(const std::vector& transport_options, - std::string* message); -static bool ParseSessionDescription(absl::string_view message, - size_t* pos, - std::string* session_id, - std::string* session_version, - TransportDescription* session_td, - RtpHeaderExtensions* session_extmaps, - SocketAddress* connection_addr, - SessionDescription* desc, - SdpParseError* error); -static bool ParseMediaDescription( - absl::string_view message, - const TransportDescription& session_td, - const RtpHeaderExtensions& session_extmaps, - size_t* pos, - const SocketAddress& session_connection_addr, - SessionDescription* desc, - std::vector>* candidates, - SdpParseError* error); -static bool ParseContent( - absl::string_view message, - const MediaType media_type, - int mline_index, - absl::string_view protocol, - const std::vector& payload_types, - size_t* pos, - std::string* content_name, - bool* bundle_only, - int* msid_signaling, - MediaContentDescription* media_desc, - TransportDescription* transport, - std::vector>* candidates, - SdpParseError* error); -static bool ParseGroupAttribute(absl::string_view line, - SessionDescription* desc, - SdpParseError* error); -static bool ParseSsrcAttribute(absl::string_view line, - SsrcInfoVec* ssrc_infos, - int* msid_signaling, - SdpParseError* error); -static bool ParseSsrcGroupAttribute(absl::string_view line, - SsrcGroupVec* ssrc_groups, - SdpParseError* error); -static bool ParseRtpmapAttribute(absl::string_view line, - const MediaType media_type, - const std::vector& payload_types, - MediaContentDescription* media_desc, - SdpParseError* error); -static bool ParseFmtpAttributes(absl::string_view line, - const MediaType media_type, - MediaContentDescription* media_desc, - SdpParseError* error); -static bool ParseFmtpParam(absl::string_view line, - std::string* parameter, - std::string* value, - SdpParseError* error); -static bool ParsePacketizationAttribute(absl::string_view line, - const MediaType media_type, - MediaContentDescription* media_desc, - SdpParseError* error); -static bool ParseRtcpFbAttribute(absl::string_view line, - const MediaType media_type, - MediaContentDescription* media_desc, - SdpParseError* error); -static bool ParseIceOptions(absl::string_view line, - std::vector* transport_options, - SdpParseError* error); -static bool ParseExtmap(absl::string_view line, - RtpExtension* extmap, - SdpParseError* error); -static bool ParseFingerprintAttribute( - absl::string_view line, - std::unique_ptr* fingerprint, - SdpParseError* error); -static bool ParseDtlsSetup(absl::string_view line, - ConnectionRole* role, - SdpParseError* error); -static bool ParseMsidAttribute(absl::string_view line, - std::vector* stream_ids, - std::string* track_id, - SdpParseError* error); - -static void RemoveDuplicateRidDescriptions( - const std::vector& payload_types, - std::vector* rids); - -static SimulcastLayerList RemoveRidsFromSimulcastLayerList( - const std::set& to_remove, - const SimulcastLayerList& layers); - -static void RemoveInvalidRidsFromSimulcast( - const std::vector& rids, - SimulcastDescription* simulcast); - -// Helper functions - // Below ParseFailed*** functions output the line that caused the parsing // failure and the detailed reason (`description`) of the failure to `error`. // The functions always return false so that they can be used directly in the @@ -368,10 +241,10 @@ static void RemoveInvalidRidsFromSimulcast( // The line starting at `line_start` of `message` is the failing line. // The reason for the failure should be provided in the `description`. // An example of a description could be "unknown character". -static bool ParseFailed(absl::string_view message, - size_t line_start, - std::string description, - SdpParseError* error) { +bool ParseFailed(absl::string_view message, + size_t line_start, + std::string description, + SdpParseError* error) { // Get the first line of `message` from `line_start`. absl::string_view first_line; size_t line_end = message.find(kNewLineChar, line_start); @@ -397,23 +270,23 @@ static bool ParseFailed(absl::string_view message, // `line` is the failing line. The reason for the failure should be // provided in the `description`. -static bool ParseFailed(absl::string_view line, - std::string description, - SdpParseError* error) { +bool ParseFailed(absl::string_view line, + std::string description, + SdpParseError* error) { return ParseFailed(line, 0, std::move(description), error); } // Parses failure where the failing SDP line isn't know or there are multiple // failing lines. -static bool ParseFailed(std::string description, SdpParseError* error) { +bool ParseFailed(std::string description, SdpParseError* error) { return ParseFailed("", std::move(description), error); } // `line` is the failing line. The failure is due to the fact that `line` // doesn't have `expected_fields` fields. -static bool ParseFailedExpectFieldNum(absl::string_view line, - int expected_fields, - SdpParseError* error) { +bool ParseFailedExpectFieldNum(absl::string_view line, + int expected_fields, + SdpParseError* error) { StringBuilder description; description << "Expects " << expected_fields << " fields."; return ParseFailed(line, description.Release(), error); @@ -421,9 +294,9 @@ static bool ParseFailedExpectFieldNum(absl::string_view line, // `line` is the failing line. The failure is due to the fact that `line` has // less than `expected_min_fields` fields. -static bool ParseFailedExpectMinFieldNum(absl::string_view line, - int expected_min_fields, - SdpParseError* error) { +bool ParseFailedExpectMinFieldNum(absl::string_view line, + int expected_min_fields, + SdpParseError* error) { StringBuilder description; description << "Expects at least " << expected_min_fields << " fields."; return ParseFailed(line, description.Release(), error); @@ -431,9 +304,9 @@ static bool ParseFailedExpectMinFieldNum(absl::string_view line, // `line` is the failing line. The failure is due to the fact that it failed to // get the value of `attribute`. -static bool ParseFailedGetValue(absl::string_view line, - absl::string_view attribute, - SdpParseError* error) { +bool ParseFailedGetValue(absl::string_view line, + absl::string_view attribute, + SdpParseError* error) { StringBuilder description; description << "Failed to get the value of attribute: " << attribute; return ParseFailed(line, description.Release(), error); @@ -443,18 +316,18 @@ static bool ParseFailedGetValue(absl::string_view line, // failure is due to the line type (e.g. the "m" part of the "m-line") // not matching what is expected. The expected line type should be // provided as `line_type`. -static bool ParseFailedExpectLine(absl::string_view message, - size_t line_start, - const char line_type, - absl::string_view line_value, - SdpParseError* error) { +bool ParseFailedExpectLine(absl::string_view message, + size_t line_start, + const char line_type, + absl::string_view line_value, + SdpParseError* error) { StringBuilder description; description << "Expect line: " << std::string(1, line_type) << "=" << line_value; return ParseFailed(message, line_start, description.Release(), error); } -static bool AddLine(absl::string_view line, std::string* message) { +bool AddLine(absl::string_view line, std::string* message) { if (!message) return false; @@ -464,7 +337,7 @@ static bool AddLine(absl::string_view line, std::string* message) { } // Trim return character, if any. -static absl::string_view TrimReturnChar(absl::string_view line) { +absl::string_view TrimReturnChar(absl::string_view line) { if (!line.empty() && line.back() == kReturnChar) { line.remove_suffix(1); } @@ -473,8 +346,8 @@ static absl::string_view TrimReturnChar(absl::string_view line) { // Gets line of `message` starting at `pos`, and checks overall SDP syntax. On // success, advances `pos` to the next line. -static std::optional GetLine(absl::string_view message, - size_t* pos) { +std::optional GetLine(absl::string_view message, + size_t* pos) { size_t line_end = message.find(kNewLineChar, *pos); if (line_end == absl::string_view::npos) { return std::nullopt; @@ -505,31 +378,27 @@ static std::optional GetLine(absl::string_view message, } // Init `os` to "`type`=`value`". -static void InitLine(const char type, - absl::string_view value, - StringBuilder* os) { +void InitLine(const char type, absl::string_view value, StringBuilder* os) { os->Clear(); *os << std::string(1, type) << kSdpDelimiterEqual << value; } // Init `os` to "a=`attribute`". -static void InitAttrLine(absl::string_view attribute, StringBuilder* os) { +void InitAttrLine(absl::string_view attribute, StringBuilder* os) { InitLine(kLineTypeAttributes, attribute, os); } // Writes a SDP attribute line based on `attribute` and `value` to `message`. -static void AddAttributeLine(absl::string_view attribute, - int value, - std::string* message) { +void AddAttributeLine(absl::string_view attribute, + int value, + std::string* message) { StringBuilder os; InitAttrLine(attribute, &os); os << kSdpDelimiterColon << value; AddLine(os.str(), message); } -static bool IsLineType(absl::string_view message, - const char type, - size_t line_start) { +bool IsLineType(absl::string_view message, const char type, size_t line_start) { if (message.size() < line_start + kLinePrefixLength) { return false; } @@ -537,19 +406,20 @@ static bool IsLineType(absl::string_view message, message[line_start + 1] == kSdpDelimiterEqualChar); } -static bool IsLineType(absl::string_view line, const char type) { +bool IsLineType(absl::string_view line, const char type) { return IsLineType(line, type, 0); } -static std::optional -GetLineWithType(absl::string_view message, size_t* pos, const char type) { +std::optional GetLineWithType(absl::string_view message, + size_t* pos, + const char type) { if (IsLineType(message, type, *pos)) { return GetLine(message, pos); } return std::nullopt; } -static bool HasAttribute(absl::string_view line, absl::string_view attribute) { +bool HasAttribute(absl::string_view line, absl::string_view attribute) { if (line.compare(kLinePrefixLength, attribute.size(), attribute) == 0) { // Make sure that the match is not only a partial match. If length of // strings doesn't match, the next character of the line must be ':' or ' '. @@ -565,10 +435,10 @@ static bool HasAttribute(absl::string_view line, absl::string_view attribute) { return false; } -static bool AddSsrcLine(uint32_t ssrc_id, - absl::string_view attribute, - absl::string_view value, - std::string* message) { +bool AddSsrcLine(uint32_t ssrc_id, + absl::string_view attribute, + absl::string_view value, + std::string* message) { // RFC 5576 // a=ssrc: : StringBuilder os; @@ -579,10 +449,10 @@ static bool AddSsrcLine(uint32_t ssrc_id, } // Get value only from :. -static bool GetValue(absl::string_view message, - absl::string_view attribute, - std::string* value, - SdpParseError* error) { +bool GetValue(absl::string_view message, + absl::string_view attribute, + std::string* value, + SdpParseError* error) { std::string leftpart; if (!tokenize_first(message, kSdpDelimiterColonChar, &leftpart, value)) { return ParseFailedGetValue(message, attribute, error); @@ -598,10 +468,10 @@ static bool GetValue(absl::string_view message, } // Get a single [token] from : -static bool GetSingleTokenValue(absl::string_view message, - absl::string_view attribute, - std::string* value, - SdpParseError* error) { +bool GetSingleTokenValue(absl::string_view message, + absl::string_view attribute, + std::string* value, + SdpParseError* error) { if (!GetValue(message, attribute, value, error)) { return false; } @@ -613,17 +483,17 @@ static bool GetSingleTokenValue(absl::string_view message, return true; } -static bool CaseInsensitiveFind(std::string str1, std::string str2) { +bool CaseInsensitiveFind(std::string str1, std::string str2) { absl::c_transform(str1, str1.begin(), ::tolower); absl::c_transform(str2, str2.begin(), ::tolower); return str1.find(str2) != std::string::npos; } template -static bool GetValueFromString(absl::string_view line, - absl::string_view s, - T* t, - SdpParseError* error) { +bool GetValueFromString(absl::string_view line, + absl::string_view s, + T* t, + SdpParseError* error) { if (!FromString(s, t)) { StringBuilder description; description << "Invalid value: " << s << "."; @@ -632,10 +502,10 @@ static bool GetValueFromString(absl::string_view line, return true; } -static bool GetPayloadTypeFromString(absl::string_view line, - absl::string_view s, - int* payload_type, - SdpParseError* error) { +bool GetPayloadTypeFromString(absl::string_view line, + absl::string_view s, + int* payload_type, + SdpParseError* error) { return GetValueFromString(line, s, payload_type, error) && IsValidRtpPayloadType(*payload_type); } @@ -733,11 +603,11 @@ void GetMediaStreamIds(const ContentInfo* content, // The value of `component_id` currently supported are 1 (RTP) and 2 (RTCP). // TODO(deadbeef): Decide the default destination in webrtcsession and // pass it down via SessionDescription. -static void GetDefaultDestination(const std::vector& candidates, - int component_id, - std::string* port, - std::string* ip, - std::string* addr_type) { +void GetDefaultDestination(const std::vector& candidates, + int component_id, + std::string* port, + std::string* ip, + std::string* addr_type) { *addr_type = kConnectionIpv4Addrtype; *port = kDummyPort; *ip = kDummyAddress; @@ -774,7 +644,7 @@ static void GetDefaultDestination(const std::vector& candidates, } // Gets "a=rtcp" line if found default RTCP candidate from `candidates`. -static std::string GetRtcpLine(const std::vector& candidates) { +std::string GetRtcpLine(const std::vector& candidates) { std::string rtcp_port, rtcp_ip, addr_type; GetDefaultDestination(candidates, ICE_CANDIDATE_COMPONENT_RTCP, &rtcp_port, &rtcp_ip, &addr_type); @@ -794,744 +664,588 @@ static std::string GetRtcpLine(const std::vector& candidates) { } // Get candidates according to the mline index from SessionDescriptionInterface. -static void GetCandidatesByMindex(const SessionDescriptionInterface& desci, - int mline_index, - std::vector* candidates) { +void GetCandidatesByMindex(const SessionDescriptionInterface& desci, + int mline_index, + std::vector* candidates) { if (!candidates) { return; } const IceCandidateCollection* cc = desci.candidates(mline_index); for (size_t i = 0; i < cc->count(); ++i) { - const IceCandidateInterface* candidate = cc->at(i); + const IceCandidate* candidate = cc->at(i); candidates->push_back(candidate->candidate()); } } -static bool IsValidPort(int port) { +bool IsValidPort(int port) { return port >= 0 && port <= 65535; } -std::string SdpSerialize(const JsepSessionDescription& jdesc) { - const SessionDescription* desc = jdesc.description(); - if (!desc) { - return ""; +bool ParseIceOptions(absl::string_view line, + std::vector* transport_options, + SdpParseError* error) { + std::string ice_options; + if (!GetValue(line, kAttributeIceOption, &ice_options, error)) { + return false; } - - std::string message; - - // Session Description. - AddLine(kSessionVersion, &message); - // Session Origin - // RFC 4566 - // o= - // - StringBuilder os; - InitLine(kLineTypeOrigin, kSessionOriginUsername, &os); - const std::string& session_id = - jdesc.session_id().empty() ? kSessionOriginSessionId : jdesc.session_id(); - const std::string& session_version = jdesc.session_version().empty() - ? kSessionOriginSessionVersion - : jdesc.session_version(); - os << " " << session_id << " " << session_version << " " - << kSessionOriginNettype << " " << kSessionOriginAddrtype << " " - << kSessionOriginAddress; - AddLine(os.str(), &message); - AddLine(kSessionName, &message); - - // Time Description. - AddLine(kTimeDescription, &message); - - // BUNDLE Groups - std::vector groups = - desc->GetGroupsByName(GROUP_TYPE_BUNDLE); - for (const ContentGroup* group : groups) { - std::string group_line = kAttrGroup; - RTC_DCHECK(group != nullptr); - for (const std::string& content_name : group->content_names()) { - group_line.append(" "); - group_line.append(content_name); - } - AddLine(group_line, &message); + std::vector fields = + split(ice_options, kSdpDelimiterSpaceChar); + for (size_t i = 0; i < fields.size(); ++i) { + transport_options->emplace_back(fields[i]); } + return true; +} - // Mixed one- and two-byte header extension. - if (desc->extmap_allow_mixed()) { - InitAttrLine(kAttributeExtmapAllowMixed, &os); - AddLine(os.str(), &message); +bool ParseSctpPort(absl::string_view line, + int* sctp_port, + SdpParseError* error) { + // draft-ietf-mmusic-sctp-sdp-26 + // a=sctp-port + const size_t expected_min_fields = 2; + std::vector fields = + split(line.substr(kLinePrefixLength), kSdpDelimiterColonChar); + if (fields.size() < expected_min_fields) { + fields = split(line.substr(kLinePrefixLength), kSdpDelimiterSpaceChar); + } + if (fields.size() < expected_min_fields) { + return ParseFailedExpectMinFieldNum(line, expected_min_fields, error); + } + if (!FromString(fields[1], sctp_port)) { + return ParseFailed(line, "Invalid sctp port value.", error); } + return true; +} - // MediaStream semantics. - // TODO(bugs.webrtc.org/10421): Change to & kMsidSignalingSemantic - // when we think it's safe to do so, so that we gradually fade out this old - // line that was removed from the specification. - if (desc->msid_signaling() != kMsidSignalingNotUsed) { - InitAttrLine(kAttributeMsidSemantics, &os); - os << kSdpDelimiterColon << " " << kMediaStreamSemantic; +bool ParseSctpMaxMessageSize(absl::string_view line, + int* max_message_size, + SdpParseError* error) { + // draft-ietf-mmusic-sctp-sdp-26 + // a=max-message-size:199999 + const size_t expected_min_fields = 2; + std::vector fields = + split(line.substr(kLinePrefixLength), kSdpDelimiterColonChar); + if (fields.size() < expected_min_fields) { + return ParseFailedExpectMinFieldNum(line, expected_min_fields, error); + } + if (!FromString(fields[1], max_message_size)) { + return ParseFailed(line, "Invalid SCTP max message size.", error); + } + return true; +} - // TODO(bugs.webrtc.org/10421): this code only looks at the first - // audio/video content. Fixing that might result in much larger SDP and the - // msid-semantic line should eventually go away so this is not worth fixing. - std::set media_stream_ids; - const ContentInfo* audio_content = GetFirstAudioContent(desc); - if (audio_content) - GetMediaStreamIds(audio_content, &media_stream_ids); +bool ParseExtmap(absl::string_view line, + RtpExtension* extmap, + SdpParseError* error) { + // RFC 5285 + // a=extmap:["/"] + std::vector fields = + split(line.substr(kLinePrefixLength), kSdpDelimiterSpaceChar); + const size_t expected_min_fields = 2; + if (fields.size() < expected_min_fields) { + return ParseFailedExpectMinFieldNum(line, expected_min_fields, error); + } + absl::string_view uri = fields[1]; - const ContentInfo* video_content = GetFirstVideoContent(desc); - if (video_content) - GetMediaStreamIds(video_content, &media_stream_ids); + std::string value_direction; + if (!GetValue(fields[0], kAttributeExtmap, &value_direction, error)) { + return false; + } + std::vector sub_fields = + split(value_direction, kSdpDelimiterSlashChar); + int value = 0; + if (!GetValueFromString(line, sub_fields[0], &value, error)) { + return false; + } - for (const std::string& id : media_stream_ids) { - os << " " << id; + bool encrypted = false; + if (uri == RtpExtension::kEncryptHeaderExtensionsUri) { + // RFC 6904 + // a=extmap:] urn:ietf:params:rtp-hdrext:encrypt + // + const size_t expected_min_fields_encrypted = expected_min_fields + 1; + if (fields.size() < expected_min_fields_encrypted) { + return ParseFailedExpectMinFieldNum(line, expected_min_fields_encrypted, + error); } - AddLine(os.str(), &message); - } - // a=ice-lite - // - // TODO(deadbeef): It's weird that we need to iterate TransportInfos for - // this, when it's a session-level attribute. It really should be moved to a - // session-level structure like SessionDescription. - for (const TransportInfo& transport : desc->transport_infos()) { - if (transport.description.ice_mode == ICEMODE_LITE) { - InitAttrLine(kAttributeIceLite, &os); - AddLine(os.str(), &message); - break; + encrypted = true; + uri = fields[2]; + if (uri == RtpExtension::kEncryptHeaderExtensionsUri) { + return ParseFailed(line, "Recursive encrypted header.", error); } } - // Preserve the order of the media contents. - int mline_index = -1; - for (const ContentInfo& content : desc->contents()) { - std::vector candidates; - GetCandidatesByMindex(jdesc, ++mline_index, &candidates); - BuildMediaDescription(&content, desc->GetTransportInfoByName(content.mid()), - content.media_description()->type(), candidates, - desc->msid_signaling(), &message); - } - return message; + *extmap = RtpExtension(uri, value, encrypted); + return true; } -// Serializes the passed in IceCandidateInterface to a SDP string. -// candidate - The candidate to be serialized. -std::string SdpSerializeCandidate(const IceCandidateInterface& candidate) { - return SdpSerializeCandidate(candidate.candidate()); +void BuildSctpContentAttributes(const MediaContentDescription* media_desc, + std::string* message) { + const SctpDataContentDescription* data_desc = media_desc->as_sctp(); + if (!data_desc) { + // Ignore unsupported media types with the SCTP protocol. + return; + } + + StringBuilder os; + if (data_desc->use_sctpmap()) { + // draft-ietf-mmusic-sctp-sdp-04 + // a=sctpmap:sctpmap-number protocol [streams] + InitAttrLine(kAttributeSctpmap, &os); + os << kSdpDelimiterColon << data_desc->port() << kSdpDelimiterSpace + << kDefaultSctpmapProtocol << kSdpDelimiterSpace << kMaxSctpStreams; + AddLine(os.str(), message); + } else { + // draft-ietf-mmusic-sctp-sdp-23 + // a=sctp-port: + InitAttrLine(kAttributeSctpPort, &os); + os << kSdpDelimiterColon << data_desc->port(); + AddLine(os.str(), message); + if (data_desc->max_message_size() != kDefaultSctpMaxMessageSize) { + InitAttrLine(kAttributeMaxMessageSize, &os); + os << kSdpDelimiterColon << data_desc->max_message_size(); + AddLine(os.str(), message); + } + } } -// Serializes a cricket Candidate. -std::string SdpSerializeCandidate(const Candidate& candidate) { - std::string message; - std::vector candidates(1, candidate); - BuildCandidate(candidates, true, &message); - // From WebRTC draft section 4.8.1.1 candidate-attribute will be - // just candidate: not a=candidate:CRLF - RTC_DCHECK(message.find("a=") == 0); - message.erase(0, 2); - RTC_DCHECK(message.find(kLineBreak) == message.size() - 2); - message.resize(message.size() - 2); - return message; -} - -bool SdpDeserialize(absl::string_view message, - JsepSessionDescription* jdesc, - SdpParseError* error) { - std::string session_id; - std::string session_version; - TransportDescription session_td("", ""); - RtpHeaderExtensions session_extmaps; - SocketAddress session_connection_addr; - auto desc = std::make_unique(); - size_t current_pos = 0; - - // Session Description - if (!ParseSessionDescription(message, ¤t_pos, &session_id, - &session_version, &session_td, &session_extmaps, - &session_connection_addr, desc.get(), error)) { - return false; - } +void BuildIceUfragPwd(const TransportInfo* transport_info, + std::string* message) { + RTC_DCHECK(transport_info); - // Media Description - std::vector> candidates; - if (!ParseMediaDescription(message, session_td, session_extmaps, ¤t_pos, - session_connection_addr, desc.get(), &candidates, - error)) { - return false; + StringBuilder os; + // RFC 5245 + // ice-pwd-att = "ice-pwd" ":" password + // ice-ufrag-att = "ice-ufrag" ":" ufrag + // ice-ufrag + if (!transport_info->description.ice_ufrag.empty()) { + InitAttrLine(kAttributeIceUfrag, &os); + os << kSdpDelimiterColon << transport_info->description.ice_ufrag; + AddLine(os.str(), message); } - - jdesc->Initialize(std::move(desc), session_id, session_version); - - for (const auto& candidate : candidates) { - jdesc->AddCandidate(candidate.get()); + // ice-pwd + if (!transport_info->description.ice_pwd.empty()) { + InitAttrLine(kAttributeIcePwd, &os); + os << kSdpDelimiterColon << transport_info->description.ice_pwd; + AddLine(os.str(), message); } - return true; } -bool SdpDeserializeCandidate(absl::string_view message, - JsepIceCandidate* jcandidate, - SdpParseError* error) { - RTC_DCHECK(jcandidate != nullptr); - Candidate candidate; - if (!ParseCandidate(message, &candidate, error, true)) { - return false; +void BuildDtlsFingerprintSetup(const TransportInfo* transport_info, + std::string* message) { + RTC_DCHECK(transport_info); + + StringBuilder os; + // RFC 4572 + // fingerprint-attribute = + // "fingerprint" ":" hash-func SP fingerprint + // When using max-bundle this is already included at session level. + // Insert the fingerprint attribute. + auto fingerprint = transport_info->description.identity_fingerprint.get(); + if (!fingerprint) { + return; } - jcandidate->SetCandidate(candidate); - return true; -} + InitAttrLine(kAttributeFingerprint, &os); + os << kSdpDelimiterColon << fingerprint->algorithm << kSdpDelimiterSpace + << fingerprint->GetRfc4572Fingerprint(); + AddLine(os.str(), message); -bool SdpDeserializeCandidate(absl::string_view transport_name, - absl::string_view message, - Candidate* candidate, - SdpParseError* error) { - RTC_DCHECK(candidate != nullptr); - if (!ParseCandidate(message, candidate, error, true)) { - return false; + // Inserting setup attribute. + if (transport_info->description.connection_role != CONNECTIONROLE_NONE) { + // Making sure we are not using "passive" mode. + ConnectionRole role = transport_info->description.connection_role; + std::string dtls_role_str; + const bool success = ConnectionRoleToString(role, &dtls_role_str); + RTC_DCHECK(success); + InitAttrLine(kAttributeSetup, &os); + os << kSdpDelimiterColon << dtls_role_str; + AddLine(os.str(), message); } - candidate->set_transport_name(transport_name); - return true; } -bool ParseCandidate(absl::string_view message, - Candidate* candidate, - SdpParseError* error, - bool is_raw) { - RTC_DCHECK(candidate != nullptr); +void BuildMediaLine(const MediaType media_type, + const ContentInfo* content_info, + const MediaContentDescription* media_desc, + std::string* message) { + StringBuilder os; - // Makes sure `message` contains only one line. - absl::string_view first_line; + // RFC 4566 + // m= + // fmt is a list of payload type numbers that MAY be used in the session. + std::string type; + std::string fmt; + if (media_type == MediaType::AUDIO || media_type == MediaType::VIDEO) { + type = media_type == MediaType::AUDIO ? kSdpMediaTypeAudio + : kSdpMediaTypeVideo; + for (const Codec& codec : media_desc->codecs()) { + fmt.append(" "); + fmt.append(absl::StrCat(codec.id)); + } + } else if (media_type == MediaType::DATA) { + type = kSdpMediaTypeData; + const SctpDataContentDescription* sctp_data_desc = media_desc->as_sctp(); + if (sctp_data_desc) { + fmt.append(" "); - size_t line_end = message.find(kNewLineChar); - if (line_end == absl::string_view::npos) { - first_line = message; - } else if (line_end + 1 == message.size()) { - first_line = message.substr(0, line_end); + if (sctp_data_desc->use_sctpmap()) { + fmt.append(absl::StrCat(sctp_data_desc->port())); + } else { + fmt.append(kDefaultSctpmapProtocol); + } + } else { + RTC_DCHECK_NOTREACHED() << "Data description without SCTP"; + } + } else if (media_type == MediaType::UNSUPPORTED) { + const UnsupportedContentDescription* unsupported_desc = + media_desc->as_unsupported(); + type = unsupported_desc->media_type(); } else { - return ParseFailed(message, 0, "Expect one line only", error); + RTC_DCHECK_NOTREACHED(); + } + // The fmt must never be empty. If no codecs are found, set the fmt attribute + // to 0. + if (fmt.empty()) { + fmt = " 0"; } - // Trim return char, if any. - first_line = TrimReturnChar(first_line); - - // From WebRTC draft section 4.8.1.1 candidate-attribute should be - // candidate: when trickled, but we still support - // a=candidate:CRLF for backward compatibility and for parsing a line - // from the SDP. - if (IsLineType(first_line, kLineTypeAttributes)) { - first_line = first_line.substr(kLinePrefixLength); + // The port number in the m line will be updated later when associated with + // the candidates. + // + // A port value of 0 indicates that the m= section is rejected. + // RFC 3264 + // To reject an offered stream, the port number in the corresponding stream in + // the answer MUST be set to zero. + // + // However, the BUNDLE draft adds a new meaning to port zero, when used along + // with a=bundle-only. + std::string port = kDummyPort; + if (content_info->rejected || content_info->bundle_only) { + port = kMediaPortRejected; + } else if (!media_desc->connection_address().IsNil()) { + port = absl::StrCat(media_desc->connection_address().port()); } - std::string attribute_candidate; - std::string candidate_value; + // Add the m and c lines. + InitLine(kLineTypeMedia, type, &os); + os << " " << port << " " << media_desc->protocol() << fmt; + AddLine(os.str(), message); +} - // `first_line` must be in the form of "candidate:". - if (!tokenize_first(first_line, kSdpDelimiterColonChar, &attribute_candidate, - &candidate_value) || - attribute_candidate != kAttributeCandidate) { - if (is_raw) { - StringBuilder description; - description << "Expect line: " << kAttributeCandidate - << ":" - ""; - return ParseFailed(first_line, 0, description.Release(), error); +void BuildCandidate(const std::vector& candidates, + bool include_ufrag, + std::string* message) { + StringBuilder os; + + for (const Candidate& candidate : candidates) { + // RFC 5245 + // a=candidate: + // typ + // [raddr ] [rport ] + // *(SP extension-att-name SP extension-att-value) + std::string type; + // Map the cricket candidate type to "host" / "srflx" / "prflx" / "relay" + if (candidate.is_local()) { + type = kCandidateHost; + } else if (candidate.is_stun()) { + type = kCandidateSrflx; + } else if (candidate.is_relay()) { + type = kCandidateRelay; + } else if (candidate.is_prflx()) { + type = kCandidatePrflx; + // Peer reflexive candidate may be signaled for being removed. } else { - return ParseFailedExpectLine(first_line, 0, kLineTypeAttributes, - kAttributeCandidate, error); + RTC_DCHECK_NOTREACHED(); + // Never write out candidates if we don't know the type. + continue; } - } - std::vector fields = - split(candidate_value, kSdpDelimiterSpaceChar); + InitAttrLine(kAttributeCandidate, &os); + os << kSdpDelimiterColon << candidate.foundation() << " " + << candidate.component() << " " << candidate.protocol() << " " + << candidate.priority() << " " + << (candidate.address().ipaddr().IsNil() + ? candidate.address().hostname() + : candidate.address().ipaddr().ToString()) + << " " << candidate.address().PortAsString() << " " + << kAttributeCandidateTyp << " " << type << " "; - // RFC 5245 - // a=candidate: - // typ - // [raddr ] [rport ] - // *(SP extension-att-name SP extension-att-value) - const size_t expected_min_fields = 8; - if (fields.size() < expected_min_fields || - (fields[6] != kAttributeCandidateTyp)) { - return ParseFailedExpectMinFieldNum(first_line, expected_min_fields, error); - } - const absl::string_view foundation = fields[0]; + // Related address + if (!candidate.related_address().IsNil()) { + os << kAttributeCandidateRaddr << " " + << candidate.related_address().ipaddr().ToString() << " " + << kAttributeCandidateRport << " " + << candidate.related_address().PortAsString() << " "; + } - int component_id = 0; - if (!GetValueFromString(first_line, fields[1], &component_id, error)) { - return false; - } - const absl::string_view transport = fields[2]; - uint32_t priority = 0; - if (!GetValueFromString(first_line, fields[3], &priority, error)) { - return false; - } - const absl::string_view connection_address = fields[4]; - int port = 0; - if (!GetValueFromString(first_line, fields[5], &port, error)) { - return false; - } - if (!IsValidPort(port)) { - return ParseFailed(first_line, "Invalid port number.", error); - } - SocketAddress address(connection_address, port); + // Note that we allow the tcptype to be missing, for backwards + // compatibility; the implementation treats this as a passive candidate. + // TODO(bugs.webrtc.org/11466): Treat a missing tcptype as an error? + if (candidate.protocol() == TCP_PROTOCOL_NAME && + !candidate.tcptype().empty()) { + os << kTcpCandidateType << " " << candidate.tcptype() << " "; + } - std::optional protocol = StringToProto(transport); - if (!protocol) { - return ParseFailed(first_line, "Unsupported transport type.", error); - } - bool tcp_protocol = false; - switch (*protocol) { - // Supported protocols. - case PROTO_UDP: - break; - case PROTO_TCP: - case PROTO_SSLTCP: - tcp_protocol = true; - break; - default: - return ParseFailed(first_line, "Unsupported transport type.", error); - } + // Extensions + os << kAttributeCandidateGeneration << " " << candidate.generation(); + if (include_ufrag && !candidate.username().empty()) { + os << " " << kAttributeCandidateUfrag << " " << candidate.username(); + } + if (candidate.network_id() > 0) { + os << " " << kAttributeCandidateNetworkId << " " + << candidate.network_id(); + } + if (candidate.network_cost() > 0) { + os << " " << kAttributeCandidateNetworkCost << " " + << candidate.network_cost(); + } - IceCandidateType candidate_type; - const absl::string_view type = fields[7]; - if (type == kCandidateHost) { - candidate_type = IceCandidateType::kHost; - } else if (type == kCandidateSrflx) { - candidate_type = IceCandidateType::kSrflx; - } else if (type == kCandidateRelay) { - candidate_type = IceCandidateType::kRelay; - } else if (type == kCandidatePrflx) { - candidate_type = IceCandidateType::kPrflx; - } else { - return ParseFailed(first_line, "Unsupported candidate type.", error); + AddLine(os.str(), message); } +} - size_t current_position = expected_min_fields; - SocketAddress related_address; - // The 2 optional fields for related address - // [raddr ] [rport ] - if (fields.size() >= (current_position + 2) && - fields[current_position] == kAttributeCandidateRaddr) { - related_address.SetIP(fields[++current_position]); - ++current_position; - } - if (fields.size() >= (current_position + 2) && - fields[current_position] == kAttributeCandidateRport) { - int related_port = 0; - if (!GetValueFromString(first_line, fields[++current_position], - &related_port, error)) { - return false; - } - if (!IsValidPort(related_port)) { - return ParseFailed(first_line, "Invalid port number.", error); +void BuildIceOptions(const std::vector& transport_options, + std::string* message) { + if (!transport_options.empty()) { + StringBuilder os; + InitAttrLine(kAttributeIceOption, &os); + os << kSdpDelimiterColon << transport_options[0]; + for (size_t i = 1; i < transport_options.size(); ++i) { + os << kSdpDelimiterSpace << transport_options[i]; } - related_address.SetPort(related_port); - ++current_position; + AddLine(os.str(), message); } +} - // If this is a TCP candidate, it has additional extension as defined in - // RFC 6544. - absl::string_view tcptype; - if (fields.size() >= (current_position + 2) && - fields[current_position] == kTcpCandidateType) { - tcptype = fields[++current_position]; - ++current_position; - - if (tcptype != TCPTYPE_ACTIVE_STR && tcptype != TCPTYPE_PASSIVE_STR && - tcptype != TCPTYPE_SIMOPEN_STR) { - return ParseFailed(first_line, "Invalid TCP candidate type.", error); - } +void BuildRtpHeaderExtensions(const RtpHeaderExtensions& extensions, + std::string* message) { + StringBuilder os; - if (!tcp_protocol) { - return ParseFailed(first_line, "Invalid non-TCP candidate", error); + // RFC 8285 + // a=extmap:["/"] + // The definitions MUST be either all session level or all media level. This + // implementation uses all media level. + for (const RtpExtension& extension : extensions) { + InitAttrLine(kAttributeExtmap, &os); + os << kSdpDelimiterColon << extension.id; + if (extension.encrypt) { + os << kSdpDelimiterSpace << RtpExtension::kEncryptHeaderExtensionsUri; } - } else if (tcp_protocol) { - // We allow the tcptype to be missing, for backwards compatibility, - // treating it as a passive candidate. - // TODO(bugs.webrtc.org/11466): Treat a missing tcptype as an error? - tcptype = TCPTYPE_PASSIVE_STR; + os << kSdpDelimiterSpace << extension.uri; + AddLine(os.str(), message); } +} - // Extension - // Though non-standard, we support the ICE ufrag and pwd being signaled on - // the candidate to avoid issues with confusing which generation a candidate - // belongs to when trickling multiple generations at the same time. - absl::string_view username; - absl::string_view password; - uint32_t generation = 0; - uint16_t network_id = 0; - uint16_t network_cost = 0; - for (size_t i = current_position; i + 1 < fields.size(); ++i) { - // RFC 5245 - // *(SP extension-att-name SP extension-att-value) - if (fields[i] == kAttributeCandidateGeneration) { - if (!GetValueFromString(first_line, fields[++i], &generation, error)) { - return false; - } - } else if (fields[i] == kAttributeCandidateUfrag) { - username = fields[++i]; - } else if (fields[i] == kAttributeCandidatePwd) { - password = fields[++i]; - } else if (fields[i] == kAttributeCandidateNetworkId) { - if (!GetValueFromString(first_line, fields[++i], &network_id, error)) { - return false; - } - } else if (fields[i] == kAttributeCandidateNetworkCost) { - if (!GetValueFromString(first_line, fields[++i], &network_cost, error)) { - return false; - } - network_cost = std::min(network_cost, kNetworkCostMax); - } else { - // Skip the unknown extension. - ++i; - } +bool GetMinValue(const std::vector& values, int* value) { + if (values.empty()) { + return false; } - - *candidate = Candidate(component_id, ProtoToString(*protocol), address, - priority, username, password, candidate_type, - generation, foundation, network_id, network_cost); - candidate->set_related_address(related_address); - candidate->set_tcptype(tcptype); + auto it = absl::c_min_element(values); + *value = *it; return true; } -bool ParseIceOptions(absl::string_view line, - std::vector* transport_options, - SdpParseError* error) { - std::string ice_options; - if (!GetValue(line, kAttributeIceOption, &ice_options, error)) { +bool GetParameter(const std::string& name, + const CodecParameterMap& params, + int* value) { + std::map::const_iterator found = params.find(name); + if (found == params.end()) { return false; } - std::vector fields = - split(ice_options, kSdpDelimiterSpaceChar); - for (size_t i = 0; i < fields.size(); ++i) { - transport_options->emplace_back(fields[i]); + if (!FromString(found->second, value)) { + return false; } return true; } -bool ParseSctpPort(absl::string_view line, - int* sctp_port, - SdpParseError* error) { - // draft-ietf-mmusic-sctp-sdp-26 - // a=sctp-port - const size_t expected_min_fields = 2; - std::vector fields = - split(line.substr(kLinePrefixLength), kSdpDelimiterColonChar); - if (fields.size() < expected_min_fields) { - fields = split(line.substr(kLinePrefixLength), kSdpDelimiterSpaceChar); - } - if (fields.size() < expected_min_fields) { - return ParseFailedExpectMinFieldNum(line, expected_min_fields, error); - } - if (!FromString(fields[1], sctp_port)) { - return ParseFailed(line, "Invalid sctp port value.", error); - } - return true; +void WriteFmtpHeader(int payload_type, StringBuilder* os) { + // fmtp header: a=fmtp:`payload_type` + // Add a=fmtp + InitAttrLine(kAttributeFmtp, os); + // Add :`payload_type` + *os << kSdpDelimiterColon << payload_type; } -bool ParseSctpMaxMessageSize(absl::string_view line, - int* max_message_size, - SdpParseError* error) { - // draft-ietf-mmusic-sctp-sdp-26 - // a=max-message-size:199999 - const size_t expected_min_fields = 2; - std::vector fields = - split(line.substr(kLinePrefixLength), kSdpDelimiterColonChar); - if (fields.size() < expected_min_fields) { - return ParseFailedExpectMinFieldNum(line, expected_min_fields, error); - } - if (!FromString(fields[1], max_message_size)) { - return ParseFailed(line, "Invalid SCTP max message size.", error); - } - return true; +void WritePacketizationHeader(int payload_type, StringBuilder* os) { + // packetization header: a=packetization:`payload_type` + // Add a=packetization + InitAttrLine(kAttributePacketization, os); + // Add :`payload_type` + *os << kSdpDelimiterColon << payload_type; } -bool ParseExtmap(absl::string_view line, - RtpExtension* extmap, - SdpParseError* error) { - // RFC 5285 - // a=extmap:["/"] - std::vector fields = - split(line.substr(kLinePrefixLength), kSdpDelimiterSpaceChar); - const size_t expected_min_fields = 2; - if (fields.size() < expected_min_fields) { - return ParseFailedExpectMinFieldNum(line, expected_min_fields, error); +void WriteRtcpFbHeader(int payload_type, StringBuilder* os) { + // rtcp-fb header: a=rtcp-fb:`payload_type` + // /> + // Add a=rtcp-fb + InitAttrLine(kAttributeRtcpFb, os); + // Add : + *os << kSdpDelimiterColon; + if (payload_type == kWildcardPayloadType) { + *os << "*"; + } else { + *os << payload_type; } - absl::string_view uri = fields[1]; +} - std::string value_direction; - if (!GetValue(fields[0], kAttributeExtmap, &value_direction, error)) { - return false; - } - std::vector sub_fields = - split(value_direction, kSdpDelimiterSlashChar); - int value = 0; - if (!GetValueFromString(line, sub_fields[0], &value, error)) { - return false; +void WriteFmtpParameter(absl::string_view parameter_name, + absl::string_view parameter_value, + StringBuilder* os) { + if (parameter_name.empty()) { + // RFC 2198 and RFC 4733 don't use key-value pairs. + *os << parameter_value; + } else { + // fmtp parameters: `parameter_name`=`parameter_value` + *os << parameter_name << kSdpDelimiterEqual << parameter_value; } +} - bool encrypted = false; - if (uri == RtpExtension::kEncryptHeaderExtensionsUri) { - // RFC 6904 - // a=extmap:] urn:ietf:params:rtp-hdrext:encrypt - // - const size_t expected_min_fields_encrypted = expected_min_fields + 1; - if (fields.size() < expected_min_fields_encrypted) { - return ParseFailedExpectMinFieldNum(line, expected_min_fields_encrypted, - error); - } - - encrypted = true; - uri = fields[2]; - if (uri == RtpExtension::kEncryptHeaderExtensionsUri) { - return ParseFailed(line, "Recursive encrypted header.", error); - } +void AddFmtpLine(const Codec& codec, std::string* message) { + StringBuilder os; + WriteFmtpHeader(codec.id, &os); + os << kSdpDelimiterSpace; + // Create FMTP line and check that it's nonempty. + if (WriteFmtpParameters(codec.params, &os)) { + AddLine(os.str(), message); } - - *extmap = RtpExtension(uri, value, encrypted); - return true; + return; } -static void BuildSctpContentAttributes( - const MediaContentDescription* media_desc, - std::string* message) { - const SctpDataContentDescription* data_desc = media_desc->as_sctp(); - if (!data_desc) { - // Ignore unsupported media types with the SCTP protocol. +void AddPacketizationLine(const Codec& codec, std::string* message) { + if (!codec.packetization) { return; } - StringBuilder os; - if (data_desc->use_sctpmap()) { - // draft-ietf-mmusic-sctp-sdp-04 - // a=sctpmap:sctpmap-number protocol [streams] - InitAttrLine(kAttributeSctpmap, &os); - os << kSdpDelimiterColon << data_desc->port() << kSdpDelimiterSpace - << kDefaultSctpmapProtocol << kSdpDelimiterSpace << kMaxSctpStreams; - AddLine(os.str(), message); - } else { - // draft-ietf-mmusic-sctp-sdp-23 - // a=sctp-port: - InitAttrLine(kAttributeSctpPort, &os); - os << kSdpDelimiterColon << data_desc->port(); - AddLine(os.str(), message); - if (data_desc->max_message_size() != kDefaultSctpMaxMessageSize) { - InitAttrLine(kAttributeMaxMessageSize, &os); - os << kSdpDelimiterColon << data_desc->max_message_size(); - AddLine(os.str(), message); - } - } + WritePacketizationHeader(codec.id, &os); + os << " " << *codec.packetization; + AddLine(os.str(), message); } -void BuildIceUfragPwd(const TransportInfo* transport_info, - std::string* message) { - RTC_DCHECK(transport_info); - - StringBuilder os; - // RFC 5245 - // ice-pwd-att = "ice-pwd" ":" password - // ice-ufrag-att = "ice-ufrag" ":" ufrag - // ice-ufrag - if (!transport_info->description.ice_ufrag.empty()) { - InitAttrLine(kAttributeIceUfrag, &os); - os << kSdpDelimiterColon << transport_info->description.ice_ufrag; +void AddRtcpFbLines(const Codec& codec, std::string* message) { + for (const FeedbackParam& param : codec.feedback_params.params()) { + StringBuilder os; + WriteRtcpFbHeader(codec.id, &os); + os << " " << param.id(); + if (!param.param().empty()) { + os << " " << param.param(); + } AddLine(os.str(), message); } - // ice-pwd - if (!transport_info->description.ice_pwd.empty()) { - InitAttrLine(kAttributeIcePwd, &os); - os << kSdpDelimiterColon << transport_info->description.ice_pwd; - AddLine(os.str(), message); +} + +void AddParameters(const CodecParameterMap& parameters, Codec* codec) { + for (const auto& entry : parameters) { + const std::string& key = entry.first; + const std::string& value = entry.second; + codec->SetParam(key, value); } } -void BuildDtlsFingerprintSetup(const TransportInfo* transport_info, - std::string* message) { - RTC_DCHECK(transport_info); +void AddFeedbackParameter(const FeedbackParam& feedback_param, Codec* codec) { + codec->AddFeedbackParam(feedback_param); +} - StringBuilder os; - // RFC 4572 - // fingerprint-attribute = - // "fingerprint" ":" hash-func SP fingerprint - // When using max-bundle this is already included at session level. - // Insert the fingerprint attribute. - auto fingerprint = transport_info->description.identity_fingerprint.get(); - if (!fingerprint) { - return; +void AddFeedbackParameters(const FeedbackParams& feedback_params, + Codec* codec) { + for (const FeedbackParam& param : feedback_params.params()) { + codec->AddFeedbackParam(param); } - InitAttrLine(kAttributeFingerprint, &os); - os << kSdpDelimiterColon << fingerprint->algorithm << kSdpDelimiterSpace - << fingerprint->GetRfc4572Fingerprint(); - AddLine(os.str(), message); +} - // Inserting setup attribute. - if (transport_info->description.connection_role != CONNECTIONROLE_NONE) { - // Making sure we are not using "passive" mode. - ConnectionRole role = transport_info->description.connection_role; - std::string dtls_role_str; - const bool success = ConnectionRoleToString(role, &dtls_role_str); - RTC_DCHECK(success); - InitAttrLine(kAttributeSetup, &os); - os << kSdpDelimiterColon << dtls_role_str; - AddLine(os.str(), message); +// Updates or creates a new codec entry in the media description. +void AddOrReplaceCodec(MediaContentDescription* content_desc, + const Codec& codec) { + std::vector codecs = content_desc->codecs(); + bool found = false; + for (Codec& existing_codec : codecs) { + if (codec.id == existing_codec.id) { + // Overwrite existing codec with the new codec. + existing_codec = codec; + found = true; + break; + } + } + if (!found) { + content_desc->AddCodec(codec); + return; } + content_desc->set_codecs(codecs); } -void BuildMediaLine(const MediaType media_type, - const ContentInfo* content_info, - const MediaContentDescription* media_desc, - std::string* message) { +void BuildRtpmap(const MediaContentDescription* media_desc, + const MediaType media_type, + std::string* message) { + RTC_DCHECK(message != nullptr); + RTC_DCHECK(media_desc != nullptr); StringBuilder os; - - // RFC 4566 - // m= - // fmt is a list of payload type numbers that MAY be used in the session. - std::string type; - std::string fmt; - if (media_type == MediaType::AUDIO || media_type == MediaType::VIDEO) { - type = media_type == MediaType::AUDIO ? kSdpMediaTypeAudio - : kSdpMediaTypeVideo; + if (media_type == MediaType::VIDEO) { for (const Codec& codec : media_desc->codecs()) { - fmt.append(" "); - fmt.append(absl::StrCat(codec.id)); + // RFC 4566 + // a=rtpmap: / + // [/] + if (codec.id != kWildcardPayloadType) { + InitAttrLine(kAttributeRtpmap, &os); + os << kSdpDelimiterColon << codec.id << " " << codec.name << "/" + << kVideoCodecClockrate; + AddLine(os.str(), message); + } + AddPacketizationLine(codec, message); + AddRtcpFbLines(codec, message); + AddFmtpLine(codec, message); } - } else if (media_type == MediaType::DATA) { - type = kSdpMediaTypeData; - const SctpDataContentDescription* sctp_data_desc = media_desc->as_sctp(); - if (sctp_data_desc) { - fmt.append(" "); - - if (sctp_data_desc->use_sctpmap()) { - fmt.append(absl::StrCat(sctp_data_desc->port())); - } else { - fmt.append(kDefaultSctpmapProtocol); + } else if (media_type == MediaType::AUDIO) { + std::vector ptimes; + std::vector maxptimes; + int max_minptime = 0; + for (const Codec& codec : media_desc->codecs()) { + RTC_DCHECK(!codec.name.empty()); + // RFC 4566 + // a=rtpmap: / + // [/] + InitAttrLine(kAttributeRtpmap, &os); + os << kSdpDelimiterColon << codec.id << " "; + os << codec.name << "/" << codec.clockrate; + if (codec.channels != 1) { + os << "/" << codec.channels; + } + AddLine(os.str(), message); + AddRtcpFbLines(codec, message); + AddFmtpLine(codec, message); + int minptime = 0; + if (GetParameter(kCodecParamMinPTime, codec.params, &minptime)) { + max_minptime = std::max(minptime, max_minptime); + } + int ptime; + if (GetParameter(kCodecParamPTime, codec.params, &ptime)) { + ptimes.push_back(ptime); + } + int maxptime; + if (GetParameter(kCodecParamMaxPTime, codec.params, &maxptime)) { + maxptimes.push_back(maxptime); } - } else { - RTC_DCHECK_NOTREACHED() << "Data description without SCTP"; } - } else if (media_type == MediaType::UNSUPPORTED) { - const UnsupportedContentDescription* unsupported_desc = - media_desc->as_unsupported(); - type = unsupported_desc->media_type(); - } else { - RTC_DCHECK_NOTREACHED(); - } - // The fmt must never be empty. If no codecs are found, set the fmt attribute - // to 0. - if (fmt.empty()) { - fmt = " 0"; + // Populate the maxptime attribute with the smallest maxptime of all codecs + // under the same m-line. + int min_maxptime = INT_MAX; + if (GetMinValue(maxptimes, &min_maxptime)) { + AddAttributeLine(kCodecParamMaxPTime, min_maxptime, message); + } + RTC_DCHECK_GE(min_maxptime, max_minptime); + // Populate the ptime attribute with the smallest ptime or the largest + // minptime, whichever is the largest, for all codecs under the same m-line. + int ptime = INT_MAX; + if (GetMinValue(ptimes, &ptime)) { + ptime = std::min(ptime, min_maxptime); + ptime = std::max(ptime, max_minptime); + AddAttributeLine(kCodecParamPTime, ptime, message); + } } - - // The port number in the m line will be updated later when associated with - // the candidates. - // - // A port value of 0 indicates that the m= section is rejected. - // RFC 3264 - // To reject an offered stream, the port number in the corresponding stream in - // the answer MUST be set to zero. - // - // However, the BUNDLE draft adds a new meaning to port zero, when used along - // with a=bundle-only. - std::string port = kDummyPort; - if (content_info->rejected || content_info->bundle_only) { - port = kMediaPortRejected; - } else if (!media_desc->connection_address().IsNil()) { - port = absl::StrCat(media_desc->connection_address().port()); - } - - // Add the m and c lines. - InitLine(kLineTypeMedia, type, &os); - os << " " << port << " " << media_desc->protocol() << fmt; - AddLine(os.str(), message); -} - -void BuildMediaDescription(const ContentInfo* content_info, - const TransportInfo* transport_info, - const MediaType media_type, - const std::vector& candidates, - int msid_signaling, - std::string* message) { - RTC_DCHECK(message); - if (!content_info) { - return; - } - StringBuilder os; - const MediaContentDescription* media_desc = content_info->media_description(); - RTC_DCHECK(media_desc); - - // Add the m line. - BuildMediaLine(media_type, content_info, media_desc, message); - // Add the c line. - InitLine(kLineTypeConnection, kConnectionNettype, &os); - if (media_desc->connection_address().IsNil()) { - os << " " << kConnectionIpv4Addrtype << " " << kDummyAddress; - } else if (media_desc->connection_address().family() == AF_INET) { - os << " " << kConnectionIpv4Addrtype << " " - << media_desc->connection_address().ipaddr().ToString(); - } else if (media_desc->connection_address().family() == AF_INET6) { - os << " " << kConnectionIpv6Addrtype << " " - << media_desc->connection_address().ipaddr().ToString(); - } else { - os << " " << kConnectionIpv4Addrtype << " " << kDummyAddress; - } - AddLine(os.str(), message); - - // RFC 4566 - // b=AS: or - // b=TIAS: - int bandwidth = media_desc->bandwidth(); - std::string bandwidth_type = media_desc->bandwidth_type(); - if (bandwidth_type == kApplicationSpecificBandwidth && bandwidth >= 1000) { - InitLine(kLineTypeSessionBandwidth, bandwidth_type, &os); - bandwidth /= 1000; - os << kSdpDelimiterColon << bandwidth; - AddLine(os.str(), message); - } else if (bandwidth_type == kTransportSpecificBandwidth && bandwidth > 0) { - InitLine(kLineTypeSessionBandwidth, bandwidth_type, &os); - os << kSdpDelimiterColon << bandwidth; - AddLine(os.str(), message); - } - - // Add the a=bundle-only line. - if (content_info->bundle_only) { - InitAttrLine(kAttributeBundleOnly, &os); + if (media_desc->rtcp_fb_ack_ccfb()) { + // RFC 8888 section 6 + InitAttrLine(kAttributeRtcpFb, &os); + os << kSdpDelimiterColon; + os << "* ack ccfb"; AddLine(os.str(), message); } - - // Add the a=rtcp line. - if (IsRtpProtocol(media_desc->protocol())) { - std::string rtcp_line = GetRtcpLine(candidates); - if (!rtcp_line.empty()) { - AddLine(rtcp_line, message); - } - } - - // Build the a=candidate lines. We don't include ufrag and pwd in the - // candidates in the SDP to avoid redundancy. - BuildCandidate(candidates, false, message); - - // Use the transport_info to build the media level ice-ufrag, ice-pwd - // and DTLS fingerprint and setup attributes. - if (transport_info) { - BuildIceUfragPwd(transport_info, message); - - // draft-petithuguenin-mmusic-ice-attributes-level-03 - BuildIceOptions(transport_info->description.transport_options, message); - - // Also include the DTLS fingerprint and setup attribute if available. - BuildDtlsFingerprintSetup(transport_info, message); - } - - // RFC 3388 - // mid-attribute = "a=mid:" identification-tag - // identification-tag = token - // Use the content name as the mid identification-tag. - InitAttrLine(kAttributeMid, &os); - os << kSdpDelimiterColon << content_info->mid(); - AddLine(os.str(), message); - - if (IsDtlsSctp(media_desc->protocol())) { - BuildSctpContentAttributes(media_desc, message); - } else if (IsRtpProtocol(media_desc->protocol())) { - BuildRtpContentAttributes(media_desc, media_type, msid_signaling, message); - } } void BuildRtpContentAttributes(const MediaContentDescription* media_desc, @@ -1703,64 +1417,95 @@ void BuildRtpContentAttributes(const MediaContentDescription* media_desc, } } -void BuildRtpHeaderExtensions(const RtpHeaderExtensions& extensions, - std::string* message) { +void BuildMediaDescription(const ContentInfo* content_info, + const TransportInfo* transport_info, + const MediaType media_type, + const std::vector& candidates, + int msid_signaling, + std::string* message) { + RTC_DCHECK(message); + if (!content_info) { + return; + } StringBuilder os; + const MediaContentDescription* media_desc = content_info->media_description(); + RTC_DCHECK(media_desc); - // RFC 8285 - // a=extmap:["/"] - // The definitions MUST be either all session level or all media level. This - // implementation uses all media level. - for (const RtpExtension& extension : extensions) { - InitAttrLine(kAttributeExtmap, &os); - os << kSdpDelimiterColon << extension.id; - if (extension.encrypt) { - os << kSdpDelimiterSpace << RtpExtension::kEncryptHeaderExtensionsUri; - } - os << kSdpDelimiterSpace << extension.uri; + // Add the m line. + BuildMediaLine(media_type, content_info, media_desc, message); + // Add the c line. + InitLine(kLineTypeConnection, kConnectionNettype, &os); + if (media_desc->connection_address().IsNil()) { + os << " " << kConnectionIpv4Addrtype << " " << kDummyAddress; + } else if (media_desc->connection_address().family() == AF_INET) { + os << " " << kConnectionIpv4Addrtype << " " + << media_desc->connection_address().ipaddr().ToString(); + } else if (media_desc->connection_address().family() == AF_INET6) { + os << " " << kConnectionIpv6Addrtype << " " + << media_desc->connection_address().ipaddr().ToString(); + } else { + os << " " << kConnectionIpv4Addrtype << " " << kDummyAddress; + } + AddLine(os.str(), message); + + // RFC 4566 + // b=AS: or + // b=TIAS: + int bandwidth = media_desc->bandwidth(); + std::string bandwidth_type = media_desc->bandwidth_type(); + if (bandwidth_type == kApplicationSpecificBandwidth && bandwidth >= 1000) { + InitLine(kLineTypeSessionBandwidth, bandwidth_type, &os); + bandwidth /= 1000; + os << kSdpDelimiterColon << bandwidth; + AddLine(os.str(), message); + } else if (bandwidth_type == kTransportSpecificBandwidth && bandwidth > 0) { + InitLine(kLineTypeSessionBandwidth, bandwidth_type, &os); + os << kSdpDelimiterColon << bandwidth; AddLine(os.str(), message); } -} -void WriteFmtpHeader(int payload_type, StringBuilder* os) { - // fmtp header: a=fmtp:`payload_type` - // Add a=fmtp - InitAttrLine(kAttributeFmtp, os); - // Add :`payload_type` - *os << kSdpDelimiterColon << payload_type; -} + // Add the a=bundle-only line. + if (content_info->bundle_only) { + InitAttrLine(kAttributeBundleOnly, &os); + AddLine(os.str(), message); + } -void WritePacketizationHeader(int payload_type, StringBuilder* os) { - // packetization header: a=packetization:`payload_type` - // Add a=packetization - InitAttrLine(kAttributePacketization, os); - // Add :`payload_type` - *os << kSdpDelimiterColon << payload_type; -} + // Add the a=rtcp line. + if (IsRtpProtocol(media_desc->protocol())) { + std::string rtcp_line = GetRtcpLine(candidates); + if (!rtcp_line.empty()) { + AddLine(rtcp_line, message); + } + } -void WriteRtcpFbHeader(int payload_type, StringBuilder* os) { - // rtcp-fb header: a=rtcp-fb:`payload_type` - // /> - // Add a=rtcp-fb - InitAttrLine(kAttributeRtcpFb, os); - // Add : - *os << kSdpDelimiterColon; - if (payload_type == kWildcardPayloadType) { - *os << "*"; - } else { - *os << payload_type; + // Build the a=candidate lines. We don't include ufrag and pwd in the + // candidates in the SDP to avoid redundancy. + BuildCandidate(candidates, false, message); + + // Use the transport_info to build the media level ice-ufrag, ice-pwd + // and DTLS fingerprint and setup attributes. + if (transport_info) { + BuildIceUfragPwd(transport_info, message); + + // draft-petithuguenin-mmusic-ice-attributes-level-03 + BuildIceOptions(transport_info->description.transport_options, message); + + // Also include the DTLS fingerprint and setup attribute if available. + BuildDtlsFingerprintSetup(transport_info, message); } -} -void WriteFmtpParameter(absl::string_view parameter_name, - absl::string_view parameter_value, - StringBuilder* os) { - if (parameter_name.empty()) { - // RFC 2198 and RFC 4733 don't use key-value pairs. - *os << parameter_value; - } else { - // fmtp parameters: `parameter_name`=`parameter_value` - *os << parameter_name << kSdpDelimiterEqual << parameter_value; + // RFC 3388 + // mid-attribute = "a=mid:" identification-tag + // identification-tag = token + // Use the content name as the mid identification-tag. + InitAttrLine(kAttributeMid, &os); + os << kSdpDelimiterColon << content_info->mid(); + AddLine(os.str(), message); + + if (IsDtlsSctp(media_desc->protocol())) { + BuildSctpContentAttributes(media_desc, message); + } else if (IsRtpProtocol(media_desc->protocol())) { + BuildRtpContentAttributes(media_desc, media_type, msid_signaling, message); } } @@ -1772,243 +1517,6 @@ bool IsFmtpParam(absl::string_view name) { return name != kCodecParamPTime && name != kCodecParamMaxPTime; } -bool WriteFmtpParameters(const CodecParameterMap& parameters, - StringBuilder* os) { - bool empty = true; - const char* delimiter = ""; // No delimiter before first parameter. - for (const auto& entry : parameters) { - const std::string& key = entry.first; - const std::string& value = entry.second; - - if (IsFmtpParam(key)) { - *os << delimiter; - // A semicolon before each subsequent parameter. - delimiter = kSdpDelimiterSemicolon; - WriteFmtpParameter(key, value, os); - empty = false; - } - } - - return !empty; -} - -void AddFmtpLine(const Codec& codec, std::string* message) { - StringBuilder os; - WriteFmtpHeader(codec.id, &os); - os << kSdpDelimiterSpace; - // Create FMTP line and check that it's nonempty. - if (WriteFmtpParameters(codec.params, &os)) { - AddLine(os.str(), message); - } - return; -} - -void AddPacketizationLine(const Codec& codec, std::string* message) { - if (!codec.packetization) { - return; - } - StringBuilder os; - WritePacketizationHeader(codec.id, &os); - os << " " << *codec.packetization; - AddLine(os.str(), message); -} - -void AddRtcpFbLines(const Codec& codec, std::string* message) { - for (const FeedbackParam& param : codec.feedback_params.params()) { - StringBuilder os; - WriteRtcpFbHeader(codec.id, &os); - os << " " << param.id(); - if (!param.param().empty()) { - os << " " << param.param(); - } - AddLine(os.str(), message); - } -} - -bool GetMinValue(const std::vector& values, int* value) { - if (values.empty()) { - return false; - } - auto it = absl::c_min_element(values); - *value = *it; - return true; -} - -bool GetParameter(const std::string& name, - const CodecParameterMap& params, - int* value) { - std::map::const_iterator found = params.find(name); - if (found == params.end()) { - return false; - } - if (!FromString(found->second, value)) { - return false; - } - return true; -} - -void BuildRtpmap(const MediaContentDescription* media_desc, - const MediaType media_type, - std::string* message) { - RTC_DCHECK(message != nullptr); - RTC_DCHECK(media_desc != nullptr); - StringBuilder os; - if (media_type == MediaType::VIDEO) { - for (const Codec& codec : media_desc->codecs()) { - // RFC 4566 - // a=rtpmap: / - // [/] - if (codec.id != kWildcardPayloadType) { - InitAttrLine(kAttributeRtpmap, &os); - os << kSdpDelimiterColon << codec.id << " " << codec.name << "/" - << kVideoCodecClockrate; - AddLine(os.str(), message); - } - AddPacketizationLine(codec, message); - AddRtcpFbLines(codec, message); - AddFmtpLine(codec, message); - } - } else if (media_type == MediaType::AUDIO) { - std::vector ptimes; - std::vector maxptimes; - int max_minptime = 0; - for (const Codec& codec : media_desc->codecs()) { - RTC_DCHECK(!codec.name.empty()); - // RFC 4566 - // a=rtpmap: / - // [/] - InitAttrLine(kAttributeRtpmap, &os); - os << kSdpDelimiterColon << codec.id << " "; - os << codec.name << "/" << codec.clockrate; - if (codec.channels != 1) { - os << "/" << codec.channels; - } - AddLine(os.str(), message); - AddRtcpFbLines(codec, message); - AddFmtpLine(codec, message); - int minptime = 0; - if (GetParameter(kCodecParamMinPTime, codec.params, &minptime)) { - max_minptime = std::max(minptime, max_minptime); - } - int ptime; - if (GetParameter(kCodecParamPTime, codec.params, &ptime)) { - ptimes.push_back(ptime); - } - int maxptime; - if (GetParameter(kCodecParamMaxPTime, codec.params, &maxptime)) { - maxptimes.push_back(maxptime); - } - } - // Populate the maxptime attribute with the smallest maxptime of all codecs - // under the same m-line. - int min_maxptime = INT_MAX; - if (GetMinValue(maxptimes, &min_maxptime)) { - AddAttributeLine(kCodecParamMaxPTime, min_maxptime, message); - } - RTC_DCHECK_GE(min_maxptime, max_minptime); - // Populate the ptime attribute with the smallest ptime or the largest - // minptime, whichever is the largest, for all codecs under the same m-line. - int ptime = INT_MAX; - if (GetMinValue(ptimes, &ptime)) { - ptime = std::min(ptime, min_maxptime); - ptime = std::max(ptime, max_minptime); - AddAttributeLine(kCodecParamPTime, ptime, message); - } - } - if (media_desc->rtcp_fb_ack_ccfb()) { - // RFC 8888 section 6 - InitAttrLine(kAttributeRtcpFb, &os); - os << kSdpDelimiterColon; - os << "* ack ccfb"; - AddLine(os.str(), message); - } -} - -void BuildCandidate(const std::vector& candidates, - bool include_ufrag, - std::string* message) { - StringBuilder os; - - for (const Candidate& candidate : candidates) { - // RFC 5245 - // a=candidate: - // typ - // [raddr ] [rport ] - // *(SP extension-att-name SP extension-att-value) - std::string type; - // Map the cricket candidate type to "host" / "srflx" / "prflx" / "relay" - if (candidate.is_local()) { - type = kCandidateHost; - } else if (candidate.is_stun()) { - type = kCandidateSrflx; - } else if (candidate.is_relay()) { - type = kCandidateRelay; - } else if (candidate.is_prflx()) { - type = kCandidatePrflx; - // Peer reflexive candidate may be signaled for being removed. - } else { - RTC_DCHECK_NOTREACHED(); - // Never write out candidates if we don't know the type. - continue; - } - - InitAttrLine(kAttributeCandidate, &os); - os << kSdpDelimiterColon << candidate.foundation() << " " - << candidate.component() << " " << candidate.protocol() << " " - << candidate.priority() << " " - << (candidate.address().ipaddr().IsNil() - ? candidate.address().hostname() - : candidate.address().ipaddr().ToString()) - << " " << candidate.address().PortAsString() << " " - << kAttributeCandidateTyp << " " << type << " "; - - // Related address - if (!candidate.related_address().IsNil()) { - os << kAttributeCandidateRaddr << " " - << candidate.related_address().ipaddr().ToString() << " " - << kAttributeCandidateRport << " " - << candidate.related_address().PortAsString() << " "; - } - - // Note that we allow the tcptype to be missing, for backwards - // compatibility; the implementation treats this as a passive candidate. - // TODO(bugs.webrtc.org/11466): Treat a missing tcptype as an error? - if (candidate.protocol() == TCP_PROTOCOL_NAME && - !candidate.tcptype().empty()) { - os << kTcpCandidateType << " " << candidate.tcptype() << " "; - } - - // Extensions - os << kAttributeCandidateGeneration << " " << candidate.generation(); - if (include_ufrag && !candidate.username().empty()) { - os << " " << kAttributeCandidateUfrag << " " << candidate.username(); - } - if (candidate.network_id() > 0) { - os << " " << kAttributeCandidateNetworkId << " " - << candidate.network_id(); - } - if (candidate.network_cost() > 0) { - os << " " << kAttributeCandidateNetworkCost << " " - << candidate.network_cost(); - } - - AddLine(os.str(), message); - } -} - -void BuildIceOptions(const std::vector& transport_options, - std::string* message) { - if (!transport_options.empty()) { - StringBuilder os; - InitAttrLine(kAttributeIceOption, &os); - os << kSdpDelimiterColon << transport_options[0]; - for (size_t i = 1; i < transport_options.size(); ++i) { - os << kSdpDelimiterSpace << transport_options[i]; - } - AddLine(os.str(), message); - } -} - bool ParseConnectionData(absl::string_view line, SocketAddress* addr, SdpParseError* error) { @@ -2058,27 +1566,97 @@ bool ParseConnectionData(absl::string_view line, return true; } -bool ParseSessionDescription(absl::string_view message, - size_t* pos, - std::string* session_id, - std::string* session_version, - TransportDescription* session_td, - RtpHeaderExtensions* session_extmaps, - SocketAddress* connection_addr, - SessionDescription* desc, - SdpParseError* error) { - std::optional line; +bool ParseGroupAttribute(absl::string_view line, + SessionDescription* desc, + SdpParseError* error) { + RTC_DCHECK(desc != nullptr); - desc->set_msid_signaling(kMsidSignalingNotUsed); - desc->set_extmap_allow_mixed(false); - // RFC 4566 - // v= (protocol version) - line = GetLineWithType(message, pos, kLineTypeVersion); - if (!line) { - return ParseFailedExpectLine(message, *pos, kLineTypeVersion, std::string(), - error); + // RFC 5888 and draft-holmberg-mmusic-sdp-bundle-negotiation-00 + // a=group:BUNDLE video voice + std::vector fields = + split(line.substr(kLinePrefixLength), kSdpDelimiterSpaceChar); + std::string semantics; + if (!GetValue(fields[0], kAttributeGroup, &semantics, error)) { + return false; } - // RFC 4566 + ContentGroup group(semantics); + for (size_t i = 1; i < fields.size(); ++i) { + group.AddContentName(fields[i]); + } + desc->AddGroup(group); + return true; +} + +bool ParseFingerprintAttribute(absl::string_view line, + std::unique_ptr* fingerprint, + SdpParseError* error) { + std::vector fields = + split(line.substr(kLinePrefixLength), kSdpDelimiterSpaceChar); + const size_t expected_fields = 2; + if (fields.size() != expected_fields) { + return ParseFailedExpectFieldNum(line, expected_fields, error); + } + + // The first field here is "fingerprint:. + std::string algorithm; + if (!GetValue(fields[0], kAttributeFingerprint, &algorithm, error)) { + return false; + } + + // Downcase the algorithm. Note that we don't need to downcase the + // fingerprint because hex_decode can handle upper-case. + absl::c_transform(algorithm, algorithm.begin(), ::tolower); + + // The second field is the digest value. De-hexify it. + *fingerprint = SSLFingerprint::CreateUniqueFromRfc4572(algorithm, fields[1]); + if (!*fingerprint) { + return ParseFailed(line, "Failed to create fingerprint from the digest.", + error); + } + + return true; +} + +bool ParseDtlsSetup(absl::string_view line, + ConnectionRole* role_ptr, + SdpParseError* error) { + // setup-attr = "a=setup:" role + // role = "active" / "passive" / "actpass" / "holdconn" + std::vector fields = + split(line.substr(kLinePrefixLength), kSdpDelimiterColonChar); + const size_t expected_fields = 2; + if (fields.size() != expected_fields) { + return ParseFailedExpectFieldNum(line, expected_fields, error); + } + if (std::optional role = StringToConnectionRole(fields[1]); + role.has_value()) { + *role_ptr = *role; + return true; + } + return ParseFailed(line, "Invalid attribute value.", error); +} + +bool ParseSessionDescription(absl::string_view message, + size_t* pos, + std::string* session_id, + std::string* session_version, + TransportDescription* session_td, + RtpHeaderExtensions* session_extmaps, + SocketAddress* connection_addr, + SessionDescription* desc, + SdpParseError* error) { + std::optional line; + + desc->set_msid_signaling(kMsidSignalingNotUsed); + desc->set_extmap_allow_mixed(false); + // RFC 4566 + // v= (protocol version) + line = GetLineWithType(message, pos, kLineTypeVersion); + if (!line) { + return ParseFailedExpectLine(message, *pos, kLineTypeVersion, std::string(), + error); + } + // RFC 4566 // o= // line = GetLineWithType(message, pos, kLineTypeOrigin); @@ -2227,81 +1805,10 @@ bool ParseSessionDescription(absl::string_view message, return true; } -bool ParseGroupAttribute(absl::string_view line, - SessionDescription* desc, - SdpParseError* error) { - RTC_DCHECK(desc != nullptr); - - // RFC 5888 and draft-holmberg-mmusic-sdp-bundle-negotiation-00 - // a=group:BUNDLE video voice - std::vector fields = - split(line.substr(kLinePrefixLength), kSdpDelimiterSpaceChar); - std::string semantics; - if (!GetValue(fields[0], kAttributeGroup, &semantics, error)) { - return false; - } - ContentGroup group(semantics); - for (size_t i = 1; i < fields.size(); ++i) { - group.AddContentName(fields[i]); - } - desc->AddGroup(group); - return true; -} - -static bool ParseFingerprintAttribute( - absl::string_view line, - std::unique_ptr* fingerprint, - SdpParseError* error) { - std::vector fields = - split(line.substr(kLinePrefixLength), kSdpDelimiterSpaceChar); - const size_t expected_fields = 2; - if (fields.size() != expected_fields) { - return ParseFailedExpectFieldNum(line, expected_fields, error); - } - - // The first field here is "fingerprint:. - std::string algorithm; - if (!GetValue(fields[0], kAttributeFingerprint, &algorithm, error)) { - return false; - } - - // Downcase the algorithm. Note that we don't need to downcase the - // fingerprint because hex_decode can handle upper-case. - absl::c_transform(algorithm, algorithm.begin(), ::tolower); - - // The second field is the digest value. De-hexify it. - *fingerprint = SSLFingerprint::CreateUniqueFromRfc4572(algorithm, fields[1]); - if (!*fingerprint) { - return ParseFailed(line, "Failed to create fingerprint from the digest.", - error); - } - - return true; -} - -static bool ParseDtlsSetup(absl::string_view line, - ConnectionRole* role_ptr, - SdpParseError* error) { - // setup-attr = "a=setup:" role - // role = "active" / "passive" / "actpass" / "holdconn" - std::vector fields = - split(line.substr(kLinePrefixLength), kSdpDelimiterColonChar); - const size_t expected_fields = 2; - if (fields.size() != expected_fields) { - return ParseFailedExpectFieldNum(line, expected_fields, error); - } - if (std::optional role = StringToConnectionRole(fields[1]); - role.has_value()) { - *role_ptr = *role; - return true; - } - return ParseFailed(line, "Invalid attribute value.", error); -} - -static bool ParseMsidAttribute(absl::string_view line, - std::vector* stream_ids, - std::string* track_id, - SdpParseError* error) { +bool ParseMsidAttribute(absl::string_view line, + std::vector* stream_ids, + std::string* track_id, + SdpParseError* error) { // https://datatracker.ietf.org/doc/rfc8830/ // a=msid: // msid-value = msid-id [ SP msid-appdata ] @@ -2359,9 +1866,8 @@ static bool ParseMsidAttribute(absl::string_view line, return true; } -static void RemoveDuplicateRidDescriptions( - const std::vector& payload_types, - std::vector* rids) { +void RemoveDuplicateRidDescriptions(const std::vector& payload_types, + std::vector* rids) { RTC_DCHECK(rids); std::set to_remove; std::set unique_rids; @@ -2386,7 +1892,7 @@ static void RemoveDuplicateRidDescriptions( // layers that have a rid in the to_remove list. // If a group of alternatives is empty after removing layers, the group should // be removed altogether. -static SimulcastLayerList RemoveRidsFromSimulcastLayerList( +SimulcastLayerList RemoveRidsFromSimulcastLayerList( const std::set& to_remove, const SimulcastLayerList& layers) { SimulcastLayerList result; @@ -2409,7 +1915,7 @@ static SimulcastLayerList RemoveRidsFromSimulcastLayerList( // Will remove Simulcast Layers if: // 1. They appear in both send and receive directions. // 2. They do not appear in the list of `valid_rids`. -static void RemoveInvalidRidsFromSimulcast( +void RemoveInvalidRidsFromSimulcast( const std::vector& valid_rids, SimulcastDescription* simulcast) { RTC_DCHECK(simulcast); @@ -2485,7 +1991,7 @@ struct StaticPayloadAudioCodec { int clockrate; size_t channels; }; -static const StaticPayloadAudioCodec kStaticPayloadAudioCodecs[] = { +const StaticPayloadAudioCodec kStaticPayloadAudioCodecs[] = { {"PCMU", 8000, 1}, {"reserved", 0, 0}, {"reserved", 0, 0}, {"GSM", 8000, 1}, {"G723", 8000, 1}, {"DVI4", 8000, 1}, {"DVI4", 16000, 1}, {"LPC", 8000, 1}, {"PCMA", 8000, 1}, @@ -2503,8 +2009,7 @@ void MaybeCreateStaticPayloadAudioCodecs(const std::vector& fmts, RTC_DCHECK(media_desc->codecs().empty()); for (int payload_type : fmts) { if (!media_desc->HasCodec(payload_type) && payload_type >= 0 && - static_cast(payload_type) < - arraysize(kStaticPayloadAudioCodecs)) { + payload_type < std::ssize(kStaticPayloadAudioCodecs)) { std::string encoding_name = kStaticPayloadAudioCodecs[payload_type].name; int clock_rate = kStaticPayloadAudioCodecs[payload_type].clockrate; size_t channels = kStaticPayloadAudioCodecs[payload_type].channels; @@ -2514,7 +2019,7 @@ void MaybeCreateStaticPayloadAudioCodecs(const std::vector& fmts, } } -static void BackfillCodecParameters(std::vector& codecs) { +void BackfillCodecParameters(std::vector& codecs) { for (auto& codec : codecs) { std::string unused_value; if (absl::EqualsIgnoreCase(kVp9CodecName, codec.name)) { @@ -2552,346 +2057,343 @@ static void BackfillCodecParameters(std::vector& codecs) { } } -static std::unique_ptr ParseContentDescription( - absl::string_view message, - const MediaType media_type, - int mline_index, - absl::string_view protocol, - const std::vector& payload_types, - size_t* pos, - std::string* content_name, - bool* bundle_only, - int* msid_signaling, - TransportDescription* transport, - std::vector>* candidates, - SdpParseError* error) { - std::unique_ptr media_desc; - if (media_type == MediaType::AUDIO) { - media_desc = std::make_unique(); - } else if (media_type == MediaType::VIDEO) { - media_desc = std::make_unique(); +// Gets the current codec setting associated with `payload_type`. If there +// is no Codec associated with that payload type it returns an empty codec +// with that payload type. +Codec GetCodecWithPayloadType(MediaType type, + const std::vector& codecs, + int payload_type) { + const Codec* codec = FindCodecById(codecs, payload_type); + if (codec) + return *codec; + // Return empty codec with `payload_type`. + if (type == MediaType::AUDIO) { + return CreateAudioCodec(payload_type, "", kDefaultAudioClockRateHz, 0); } else { - RTC_DCHECK_NOTREACHED(); - return nullptr; + return CreateVideoCodec(payload_type, ""); } +} - media_desc->set_extmap_allow_mixed_enum(MediaContentDescription::kNo); - if (!ParseContent(message, media_type, mline_index, protocol, payload_types, - pos, content_name, bundle_only, msid_signaling, - media_desc.get(), transport, candidates, error)) { - return nullptr; - } - // Sort the codecs according to the m-line fmt list. - std::unordered_map payload_type_preferences; - // "size + 1" so that the lowest preference payload type has a preference of - // 1, which is greater than the default (0) for payload types not in the fmt - // list. - int preference = static_cast(payload_types.size() + 1); - for (int pt : payload_types) { - payload_type_preferences[pt] = preference--; - } - std::vector codecs = media_desc->codecs(); - absl::c_sort( - codecs, [&payload_type_preferences](const Codec& a, const Codec& b) { - return payload_type_preferences[a.id] > payload_type_preferences[b.id]; - }); - // Backfill any default parameters. - BackfillCodecParameters(codecs); +// Adds or updates existing codec corresponding to `payload_type` according +// to `parameters`. +void UpdateCodec(MediaContentDescription* content_desc, + int payload_type, + const CodecParameterMap& parameters) { + // Codec might already have been populated (from rtpmap). + Codec new_codec = GetCodecWithPayloadType( + content_desc->type(), content_desc->codecs(), payload_type); + AddParameters(parameters, &new_codec); + AddOrReplaceCodec(content_desc, new_codec); +} - media_desc->set_codecs(codecs); - return media_desc; +// Adds or updates existing codec corresponding to `payload_type` according +// to `feedback_param`. +void UpdateCodec(MediaContentDescription* content_desc, + int payload_type, + const FeedbackParam& feedback_param) { + // Codec might already have been populated (from rtpmap). + Codec new_codec = GetCodecWithPayloadType( + content_desc->type(), content_desc->codecs(), payload_type); + AddFeedbackParameter(feedback_param, &new_codec); + AddOrReplaceCodec(content_desc, new_codec); } -bool HasDuplicateMsidLines(SessionDescription* desc) { - std::set> seen_msids; - for (const ContentInfo& content : desc->contents()) { - for (const StreamParams& stream : content.media_description()->streams()) { - auto msid = std::pair(stream.first_stream_id(), stream.id); - if (seen_msids.find(msid) != seen_msids.end()) { - return true; - } - seen_msids.insert(std::move(msid)); - } +bool ParseFmtpParam(absl::string_view line, + std::string* parameter, + std::string* value, + SdpParseError* error) { + if (!tokenize_first(line, kSdpDelimiterEqualChar, parameter, value)) { + // Support for non-key-value lines like RFC 2198 or RFC 4733. + *parameter = ""; + *value = std::string(line); + return true; } - return false; + // a=fmtp: =; =; ... + return true; } -bool ParseMediaDescription( - absl::string_view message, - const TransportDescription& session_td, - const RtpHeaderExtensions& session_extmaps, - size_t* pos, - const SocketAddress& session_connection_addr, - SessionDescription* desc, - std::vector>* candidates, - SdpParseError* error) { - RTC_DCHECK(desc != nullptr); - int mline_index = -1; - int msid_signaling = desc->msid_signaling(); - - // Zero or more media descriptions - // RFC 4566 - // m= - while (std::optional mline = - GetLineWithType(message, pos, kLineTypeMedia)) { - ++mline_index; - - std::vector fields = - split(mline->substr(kLinePrefixLength), kSdpDelimiterSpaceChar); - - const size_t expected_min_fields = 4; - if (fields.size() < expected_min_fields) { - return ParseFailedExpectMinFieldNum(*mline, expected_min_fields, error); - } - bool port_rejected = false; - // RFC 3264 - // To reject an offered stream, the port number in the corresponding stream - // in the answer MUST be set to zero. - if (fields[1] == kMediaPortRejected) { - port_rejected = true; - } - - int port = 0; - if (!FromString(fields[1], &port) || !IsValidPort(port)) { - return ParseFailed(*mline, "The port number is invalid", error); - } - absl::string_view protocol = fields[2]; - - // - std::vector payload_types; - if (IsRtpProtocol(protocol)) { - for (size_t j = 3; j < fields.size(); ++j) { - int pl = 0; - if (!GetPayloadTypeFromString(*mline, fields[j], &pl, error)) { - return false; - } - payload_types.push_back(pl); - } - } - - // Make a temporary TransportDescription based on `session_td`. - // Some of this gets overwritten by ParseContent. - TransportDescription transport( - session_td.transport_options, session_td.ice_ufrag, session_td.ice_pwd, - session_td.ice_mode, session_td.connection_role, - session_td.identity_fingerprint.get()); - - std::unique_ptr content; - std::string content_name; - bool bundle_only = false; - int section_msid_signaling = kMsidSignalingNotUsed; - absl::string_view media_type = fields[0]; - if ((media_type == kSdpMediaTypeVideo || - media_type == kSdpMediaTypeAudio) && - !IsRtpProtocol(protocol)) { - return ParseFailed(*mline, "Unsupported protocol for media type", error); - } - if (media_type == kSdpMediaTypeVideo) { - content = ParseContentDescription( - message, MediaType::VIDEO, mline_index, protocol, payload_types, pos, - &content_name, &bundle_only, §ion_msid_signaling, &transport, - candidates, error); - } else if (media_type == kSdpMediaTypeAudio) { - content = ParseContentDescription( - message, MediaType::AUDIO, mline_index, protocol, payload_types, pos, - &content_name, &bundle_only, §ion_msid_signaling, &transport, - candidates, error); - } else if (media_type == kSdpMediaTypeData && IsDtlsSctp(protocol)) { - // The draft-03 format is: - // m=application DTLS/SCTP ... - // use_sctpmap should be false. - // The draft-26 format is: - // m=application UDP/DTLS/SCTP webrtc-datachannel - // use_sctpmap should be false. - auto data_desc = std::make_unique(); - // Default max message size is 64K - // according to draft-ietf-mmusic-sctp-sdp-26 - data_desc->set_max_message_size(kDefaultSctpMaxMessageSize); - int p; - if (FromString(fields[3], &p)) { - data_desc->set_port(p); - } else if (fields[3] == kDefaultSctpmapProtocol) { - data_desc->set_use_sctpmap(false); - } - if (!ParseContent(message, MediaType::DATA, mline_index, protocol, - payload_types, pos, &content_name, &bundle_only, - §ion_msid_signaling, data_desc.get(), &transport, - candidates, error)) { - return false; - } - data_desc->set_protocol(protocol); - content = std::move(data_desc); - } else { - RTC_LOG(LS_WARNING) << "Unsupported media type: " << *mline; - auto unsupported_desc = - std::make_unique(media_type); - if (!ParseContent(message, MediaType::UNSUPPORTED, mline_index, protocol, - payload_types, pos, &content_name, &bundle_only, - §ion_msid_signaling, unsupported_desc.get(), - &transport, candidates, error)) { - return false; - } - unsupported_desc->set_protocol(protocol); - content = std::move(unsupported_desc); - } - if (!content.get()) { - // ParseContentDescription returns NULL if failed. - return false; - } - - msid_signaling |= section_msid_signaling; - - bool content_rejected = false; - // A port of 0 is not interpreted as a rejected m= section when it's - // used along with a=bundle-only. - if (bundle_only) { - if (!port_rejected) { - // Usage of bundle-only with a nonzero port is unspecified. So just - // ignore bundle-only if we see this. - bundle_only = false; - RTC_LOG(LS_WARNING) - << "a=bundle-only attribute observed with a nonzero " - "port; this usage is unspecified so the attribute is being " - "ignored."; - } - } else { - // If not using bundle-only, interpret port 0 in the normal way; the m= - // section is being rejected. - content_rejected = port_rejected; - } - - if (content->as_unsupported()) { - content_rejected = true; - } else if (IsRtpProtocol(protocol) && !content->as_sctp()) { - content->set_protocol(std::string(protocol)); - // Set the extmap. - if (!session_extmaps.empty() && - !content->rtp_header_extensions().empty()) { - return ParseFailed("", - "The a=extmap MUST be either all session level or " - "all media level.", - error); - } - for (size_t i = 0; i < session_extmaps.size(); ++i) { - content->AddRtpHeaderExtension(session_extmaps[i]); - } - } else if (content->as_sctp()) { - // Do nothing, it's OK - } else { - RTC_LOG(LS_WARNING) << "Parse failed with unknown protocol " << protocol; - return false; - } +bool ParseFmtpAttributes(absl::string_view line, + const MediaType media_type, + MediaContentDescription* media_desc, + SdpParseError* error) { + if (media_type != MediaType::AUDIO && media_type != MediaType::VIDEO) { + return true; + } - // Use the session level connection address if the media level addresses are - // not specified. - SocketAddress address; - address = content->connection_address().IsNil() - ? session_connection_addr - : content->connection_address(); - address.SetPort(port); - content->set_connection_address(address); + std::string line_payload; + std::string line_params; - desc->AddContent(content_name, - IsDtlsSctp(protocol) ? MediaProtocolType::kSctp - : MediaProtocolType::kRtp, - content_rejected, bundle_only, std::move(content)); - // Create TransportInfo with the media level "ice-pwd" and "ice-ufrag". - desc->AddTransportInfo(TransportInfo(content_name, transport)); - } - // Apply whole-description sanity checks - if (HasDuplicateMsidLines(desc)) { - ParseFailed(message, *pos, "Duplicate a=msid lines detected", error); + // https://tools.ietf.org/html/rfc4566#section-6 + // a=fmtp: + // At least two fields, whereas the second one is any of the optional + // parameters. + if (!tokenize_first(line.substr(kLinePrefixLength), kSdpDelimiterSpaceChar, + &line_payload, &line_params)) { + ParseFailedExpectMinFieldNum(line, 2, error); return false; } - desc->set_msid_signaling(msid_signaling); + // Parse out the payload information. + std::string payload_type_str; + if (!GetValue(line_payload, kAttributeFmtp, &payload_type_str, error)) { + return false; + } - size_t end_of_message = message.size(); - if (mline_index == -1 && *pos != end_of_message) { - ParseFailed(message, *pos, "Expects m line.", error); + int payload_type = 0; + if (!GetPayloadTypeFromString(line_payload, payload_type_str, &payload_type, + error)) { return false; } - return true; -} -void AddParameters(const CodecParameterMap& parameters, Codec* codec) { - for (const auto& entry : parameters) { - const std::string& key = entry.first; - const std::string& value = entry.second; - codec->SetParam(key, value); + // Parse out format specific parameters. + CodecParameterMap codec_params; + if (!ParseFmtpParameterSet(line_params, codec_params, error)) { + return false; } -} -void AddFeedbackParameter(const FeedbackParam& feedback_param, Codec* codec) { - codec->AddFeedbackParam(feedback_param); + if (media_type == MediaType::AUDIO || media_type == MediaType::VIDEO) { + UpdateCodec(media_desc, payload_type, codec_params); + } + return true; } -void AddFeedbackParameters(const FeedbackParams& feedback_params, - Codec* codec) { - for (const FeedbackParam& param : feedback_params.params()) { - codec->AddFeedbackParam(param); +bool ParseSsrcGroupAttribute(absl::string_view line, + SsrcGroupVec* ssrc_groups, + SdpParseError* error) { + RTC_DCHECK(ssrc_groups != nullptr); + // RFC 5576 + // a=ssrc-group: ... + std::vector fields = + split(line.substr(kLinePrefixLength), kSdpDelimiterSpaceChar); + const size_t expected_min_fields = 2; + if (fields.size() < expected_min_fields) { + return ParseFailedExpectMinFieldNum(line, expected_min_fields, error); + } + std::string semantics; + if (!GetValue(fields[0], kAttributeSsrcGroup, &semantics, error)) { + return false; + } + std::vector ssrcs; + for (size_t i = 1; i < fields.size(); ++i) { + uint32_t ssrc = 0; + if (!GetValueFromString(line, fields[i], &ssrc, error)) { + return false; + } + // Reject duplicates. While not forbidden by RFC 5576, + // they don't make sense. + if (absl::c_linear_search(ssrcs, ssrc)) { + return ParseFailed(line, "Duplicate SSRC in ssrc-group", error); + } + ssrcs.push_back(ssrc); } + ssrc_groups->push_back(SsrcGroup(semantics, ssrcs)); + return true; } -// Gets the current codec setting associated with `payload_type`. If there -// is no Codec associated with that payload type it returns an empty codec -// with that payload type. -Codec GetCodecWithPayloadType(MediaType type, - const std::vector& codecs, - int payload_type) { - const Codec* codec = FindCodecById(codecs, payload_type); - if (codec) - return *codec; - // Return empty codec with `payload_type`. - if (type == MediaType::AUDIO) { - return CreateAudioCodec(payload_type, "", kDefaultAudioClockRateHz, 0); - } else { - return CreateVideoCodec(payload_type, ""); +bool ParseSsrcAttribute(absl::string_view line, + SsrcInfoVec* ssrc_infos, + int* msid_signaling, + SdpParseError* error) { + RTC_DCHECK(ssrc_infos != nullptr); + // RFC 5576 + // a=ssrc: + // a=ssrc: : + std::string field1, field2; + if (!tokenize_first(line.substr(kLinePrefixLength), kSdpDelimiterSpaceChar, + &field1, &field2)) { + const size_t expected_fields = 2; + return ParseFailedExpectFieldNum(line, expected_fields, error); } -} -// Updates or creates a new codec entry in the media description. -void AddOrReplaceCodec(MediaContentDescription* content_desc, - const Codec& codec) { - std::vector codecs = content_desc->codecs(); - bool found = false; - for (Codec& existing_codec : codecs) { - if (codec.id == existing_codec.id) { - // Overwrite existing codec with the new codec. - existing_codec = codec; - found = true; - break; - } + // ssrc: + std::string ssrc_id_s; + if (!GetValue(field1, kAttributeSsrc, &ssrc_id_s, error)) { + return false; } - if (!found) { - content_desc->AddCodec(codec); - return; + uint32_t ssrc_id = 0; + if (!GetValueFromString(line, ssrc_id_s, &ssrc_id, error)) { + return false; } - content_desc->set_codecs(codecs); + + std::string attribute; + std::string value; + if (!tokenize_first(field2, kSdpDelimiterColonChar, &attribute, &value)) { + StringBuilder description; + description << "Failed to get the ssrc attribute value from " << field2 + << ". Expected format :."; + return ParseFailed(line, description.Release(), error); + } + + // Check if there's already an item for this `ssrc_id`. Create a new one if + // there isn't. + auto ssrc_info_it = + absl::c_find_if(*ssrc_infos, [ssrc_id](const SsrcInfo& ssrc_info) { + return ssrc_info.ssrc_id == ssrc_id; + }); + if (ssrc_info_it == ssrc_infos->end()) { + SsrcInfo info; + info.ssrc_id = ssrc_id; + ssrc_infos->push_back(info); + ssrc_info_it = ssrc_infos->end() - 1; + } + SsrcInfo& ssrc_info = *ssrc_info_it; + + // Store the info to the `ssrc_info`. + if (attribute == kSsrcAttributeCname) { + // RFC 5576 + // cname: + ssrc_info.cname = value; + } else if (attribute == kSsrcAttributeMsid) { + // draft-alvestrand-mmusic-msid-00 + // msid:identifier [appdata] + std::vector fields = + split(value, kSdpDelimiterSpaceChar); + if (fields.size() < 1 || fields.size() > 2) { + return ParseFailed( + line, "Expected format \"msid:[ ]\".", error); + } + ssrc_info.stream_id = std::string(fields[0]); + if (fields.size() == 2) { + ssrc_info.track_id = std::string(fields[1]); + } + *msid_signaling |= kMsidSignalingSsrcAttribute; + } else { + RTC_LOG(LS_INFO) << "Ignored unknown ssrc-specific attribute: " << line; + } + return true; } -// Adds or updates existing codec corresponding to `payload_type` according -// to `parameters`. -void UpdateCodec(MediaContentDescription* content_desc, - int payload_type, - const CodecParameterMap& parameters) { - // Codec might already have been populated (from rtpmap). - Codec new_codec = GetCodecWithPayloadType( - content_desc->type(), content_desc->codecs(), payload_type); - AddParameters(parameters, &new_codec); - AddOrReplaceCodec(content_desc, new_codec); +// Updates or creates a new codec entry in the audio description with according +// to `name`, `clockrate`, `bitrate`, and `channels`. +void UpdateCodec(int payload_type, + absl::string_view name, + int clockrate, + int bitrate, + size_t channels, + MediaContentDescription* desc) { + // Codec may already be populated with (only) optional parameters + // (from an fmtp). + Codec codec = + GetCodecWithPayloadType(desc->type(), desc->codecs(), payload_type); + codec.name = std::string(name); + codec.clockrate = clockrate; + codec.bitrate = bitrate; + codec.channels = channels; + AddOrReplaceCodec(desc, codec); } -// Adds or updates existing codec corresponding to `payload_type` according -// to `feedback_param`. -void UpdateCodec(MediaContentDescription* content_desc, - int payload_type, - const FeedbackParam& feedback_param) { - // Codec might already have been populated (from rtpmap). - Codec new_codec = GetCodecWithPayloadType( - content_desc->type(), content_desc->codecs(), payload_type); - AddFeedbackParameter(feedback_param, &new_codec); - AddOrReplaceCodec(content_desc, new_codec); +// Updates or creates a new codec entry in the video description according to +// `name`, `width`, `height`, and `framerate`. +void UpdateCodec(int payload_type, + absl::string_view name, + MediaContentDescription* desc) { + // Codec may already be populated with (only) optional parameters + // (from an fmtp). + Codec codec = + GetCodecWithPayloadType(desc->type(), desc->codecs(), payload_type); + codec.name = std::string(name); + AddOrReplaceCodec(desc, codec); +} + +bool ParseRtpmapAttribute(absl::string_view line, + const MediaType media_type, + const std::vector& payload_types, + MediaContentDescription* media_desc, + SdpParseError* error) { + static const int kFirstDynamicPayloadTypeLowerRange = 35; + std::vector fields = + split(line.substr(kLinePrefixLength), kSdpDelimiterSpaceChar); + // RFC 4566 + // a=rtpmap: /[/] + const size_t expected_min_fields = 2; + if (fields.size() < expected_min_fields) { + return ParseFailedExpectMinFieldNum(line, expected_min_fields, error); + } + std::string payload_type_value; + if (!GetValue(fields[0], kAttributeRtpmap, &payload_type_value, error)) { + return false; + } + int payload_type = 0; + if (!GetPayloadTypeFromString(line, payload_type_value, &payload_type, + error)) { + return false; + } + + if (!absl::c_linear_search(payload_types, payload_type)) { + RTC_LOG(LS_WARNING) << "Ignore rtpmap line that did not appear in the " + " of the m-line: " + << line; + return true; + } + std::vector codec_params = split(fields[1], '/'); + // /[/] + // 2 mandatory fields + if (codec_params.size() < 2 || codec_params.size() > 3) { + return ParseFailed(line, + "Expected format \"/" + "[/]\".", + error); + } + const absl::string_view encoding_name = codec_params[0]; + int clock_rate = 0; + if (!GetValueFromString(line, codec_params[1], &clock_rate, error)) { + return false; + } + + if (media_type == MediaType::VIDEO) { + for (const Codec& existing_codec : media_desc->codecs()) { + if (!existing_codec.name.empty() && payload_type == existing_codec.id && + (!absl::EqualsIgnoreCase(encoding_name, existing_codec.name) || + clock_rate != existing_codec.clockrate)) { + StringBuilder description; + description + << "Duplicate " + << (payload_type < kFirstDynamicPayloadTypeLowerRange + ? "statically assigned" + : "") + << " payload type with conflicting codec name or clock rate."; + return ParseFailed(line, description.Release(), error); + } + } + UpdateCodec(payload_type, encoding_name, media_desc); + } else if (media_type == MediaType::AUDIO) { + // RFC 4566 + // For audio streams, indicates the number + // of audio channels. This parameter is OPTIONAL and may be + // omitted if the number of channels is one, provided that no + // additional parameters are needed. + size_t channels = 1; + if (codec_params.size() == 3) { + if (!GetValueFromString(line, codec_params[2], &channels, error)) { + return false; + } + } + if (channels > kMaxNumberOfAudioChannels) { + StringBuilder description; + description << "At most " << kMaxNumberOfAudioChannels + << " channels are supported."; + return ParseFailed(line, description.Release(), error); + } + + for (const Codec& existing_codec : media_desc->codecs()) { + // TODO(crbug.com/1338902) re-add checks for clockrate and number of + // channels. + if (!existing_codec.name.empty() && payload_type == existing_codec.id && + (!absl::EqualsIgnoreCase(encoding_name, existing_codec.name))) { + StringBuilder description; + description + << "Duplicate " + << (payload_type < kFirstDynamicPayloadTypeLowerRange + ? "statically assigned" + : "") + << " payload type with conflicting codec name or clock rate."; + return ParseFailed(line, description.Release(), error); + } + } + UpdateCodec(payload_type, encoding_name, clock_rate, 0, channels, + media_desc); + } + return true; } // Adds or updates existing video codec corresponding to `payload_type` @@ -2911,18 +2413,83 @@ void UpdateVideoCodecPacketization(MediaContentDescription* desc, AddOrReplaceCodec(desc, codec); } -std::optional PopWildcardCodec(std::vector* codecs) { - RTC_DCHECK(codecs); - for (auto iter = codecs->begin(); iter != codecs->end(); ++iter) { - if (iter->id == kWildcardPayloadType) { - Codec wildcard_codec = *iter; - codecs->erase(iter); - return wildcard_codec; - } +bool ParsePacketizationAttribute(absl::string_view line, + const MediaType media_type, + MediaContentDescription* media_desc, + SdpParseError* error) { + if (media_type != MediaType::VIDEO) { + return true; } - return std::nullopt; -} - + std::vector packetization_fields = + split(line, kSdpDelimiterSpaceChar); + if (packetization_fields.size() < 2) { + return ParseFailedGetValue(line, kAttributePacketization, error); + } + std::string payload_type_string; + if (!GetValue(packetization_fields[0], kAttributePacketization, + &payload_type_string, error)) { + return false; + } + int payload_type; + if (!GetPayloadTypeFromString(line, payload_type_string, &payload_type, + error)) { + return false; + } + absl::string_view packetization = packetization_fields[1]; + UpdateVideoCodecPacketization(media_desc, payload_type, packetization); + return true; +} + +bool ParseRtcpFbAttribute(absl::string_view line, + const MediaType media_type, + MediaContentDescription* media_desc, + SdpParseError* error) { + if (media_type != MediaType::AUDIO && media_type != MediaType::VIDEO) { + return true; + } + std::vector rtcp_fb_fields = + split(line, kSdpDelimiterSpaceChar); + if (rtcp_fb_fields.size() < 2) { + return ParseFailedGetValue(line, kAttributeRtcpFb, error); + } + std::string payload_type_string; + if (!GetValue(rtcp_fb_fields[0], kAttributeRtcpFb, &payload_type_string, + error)) { + return false; + } + int payload_type = kWildcardPayloadType; + if (payload_type_string != "*") { + if (!GetPayloadTypeFromString(line, payload_type_string, &payload_type, + error)) { + return false; + } + } + absl::string_view id = rtcp_fb_fields[1]; + std::string param = ""; + for (auto iter = rtcp_fb_fields.begin() + 2; iter != rtcp_fb_fields.end(); + ++iter) { + param.append(iter->data(), iter->length()); + } + const FeedbackParam feedback_param(id, param); + + if (media_type == MediaType::AUDIO || media_type == MediaType::VIDEO) { + UpdateCodec(media_desc, payload_type, feedback_param); + } + return true; +} + +std::optional PopWildcardCodec(std::vector* codecs) { + RTC_DCHECK(codecs); + for (auto iter = codecs->begin(); iter != codecs->end(); ++iter) { + if (iter->id == kWildcardPayloadType) { + Codec wildcard_codec = *iter; + codecs->erase(iter); + return wildcard_codec; + } + } + return std::nullopt; +} + void UpdateFromWildcardCodecs(MediaContentDescription* desc) { RTC_DCHECK(desc); auto codecs = desc->codecs(); @@ -2965,7 +2532,7 @@ bool ParseContent(absl::string_view message, int* msid_signaling, MediaContentDescription* media_desc, TransportDescription* transport, - std::vector>* candidates, + std::vector>* candidates, SdpParseError* error) { RTC_DCHECK(media_desc != nullptr); RTC_DCHECK(content_name != nullptr); @@ -3212,8 +2779,9 @@ bool ParseContent(absl::string_view message, } *msid_signaling |= kMsidSignalingMediaSection; } else if (HasAttribute(*line, kAttributeRid)) { - const size_t kRidPrefixLength = - kLinePrefixLength + arraysize(kAttributeRid); + constexpr size_t kRidPrefixLength = kLinePrefixLength + + kAttributeRid.size() + + kSdpDelimiterColon.size(); if (line->size() <= kRidPrefixLength) { RTC_LOG(LS_INFO) << "Ignoring empty RID attribute: " << *line; continue; @@ -3232,8 +2800,9 @@ bool ParseContent(absl::string_view message, rids.push_back(error_or_rid_description.MoveValue()); } else if (HasAttribute(*line, kAttributeSimulcast)) { - const size_t kSimulcastPrefixLength = - kLinePrefixLength + arraysize(kAttributeSimulcast); + constexpr size_t kSimulcastPrefixLength = kLinePrefixLength + + kAttributeSimulcast.size() + + kSdpDelimiterColon.size(); if (line->size() <= kSimulcastPrefixLength) { return ParseFailed(*line, "Simulcast attribute is empty.", error); } @@ -3264,369 +2833,768 @@ bool ParseContent(absl::string_view message, continue; } } else { - // Only parse lines that we are interested of. - RTC_LOG(LS_VERBOSE) << "Ignored line: " << *line; - continue; + // Only parse lines that we are interested of. + RTC_LOG(LS_VERBOSE) << "Ignored line: " << *line; + continue; + } + } + + // Remove duplicate rids. + RemoveDuplicateRidDescriptions(payload_types, &rids); + + // If simulcast is specifed, split the rids into send and receive. + // Rids that do not appear in simulcast attribute will be removed. + std::vector send_rids; + std::vector receive_rids; + if (!simulcast.empty()) { + // Verify that the rids in simulcast match rids in sdp. + RemoveInvalidRidsFromSimulcast(rids, &simulcast); + + // Use simulcast description to figure out Send / Receive RIDs. + std::map rid_map; + for (const RidDescription& rid : rids) { + rid_map[rid.rid] = rid; + } + + for (const auto& layer : simulcast.send_layers().GetAllLayers()) { + auto iter = rid_map.find(layer.rid); + RTC_DCHECK(iter != rid_map.end()); + send_rids.push_back(iter->second); + } + + for (const auto& layer : simulcast.receive_layers().GetAllLayers()) { + auto iter = rid_map.find(layer.rid); + RTC_DCHECK(iter != rid_map.end()); + receive_rids.push_back(iter->second); + } + + media_desc->set_simulcast_description(simulcast); + } else { + // RID is specified in RFC 8851, which identifies a lot of usages. + // We only support RFC 8853 usage of RID, not anything else. + // Ignore all RID parameters when a=simulcast is missing. + // In particular do NOT do send_rids = rids; + RTC_LOG(LS_VERBOSE) << "Ignoring send_rids without simulcast"; + } + + media_desc->set_receive_rids(receive_rids); + + // Create tracks from the `ssrc_infos`. + // If the stream_id/track_id for all SSRCS are identical, one StreamParams + // will be created in CreateTracksFromSsrcInfos, containing all the SSRCs from + // the m= section. + if (!ssrc_infos.empty()) { + CreateTracksFromSsrcInfos(ssrc_infos, stream_ids, track_id, &tracks, + *msid_signaling); + } else if (media_type != MediaType::DATA && + (*msid_signaling & kMsidSignalingMediaSection)) { + // If the stream_ids/track_id was signaled but SSRCs were unsignaled we + // still create a track. This isn't done for data media types because + // StreamParams aren't used for SCTP streams, and RTP data channels don't + // support unsignaled SSRCs. + // If track id was not specified, create a random one. + if (track_id.empty()) { + track_id = CreateRandomString(8); + } + CreateTrackWithNoSsrcs(stream_ids, track_id, send_rids, &tracks); + } + + // Add the ssrc group to the track. + for (const SsrcGroup& ssrc_group : ssrc_groups) { + if (ssrc_group.ssrcs.empty()) { + continue; + } + uint32_t ssrc = ssrc_group.ssrcs.front(); + for (StreamParams& track : tracks) { + if (track.has_ssrc(ssrc)) { + track.ssrc_groups.push_back(ssrc_group); + } + } + } + + // Add the new tracks to the `media_desc`. + for (StreamParams& track : tracks) { + media_desc->AddStream(track); + } + + UpdateFromWildcardCodecs(media_desc); + // Codec has not been populated correctly unless the name has been set. This + // can happen if an SDP has an fmtp or rtcp-fb with a payload type but doesn't + // have a corresponding "rtpmap" line. This should lead to a parse error. + if (!absl::c_all_of(media_desc->codecs(), + [](const Codec codec) { return !codec.name.empty(); })) { + return ParseFailed("Failed to parse codecs correctly.", error); + } + if (media_type == MediaType::AUDIO) { + AddAudioAttribute(kCodecParamMaxPTime, maxptime_as_string, media_desc); + AddAudioAttribute(kCodecParamPTime, ptime_as_string, media_desc); + } + + // RFC 5245 + // Update the candidates with the media level "ice-pwd" and "ice-ufrag". + for (Candidate& candidate : candidates_orig) { + RTC_DCHECK(candidate.username().empty() || + candidate.username() == transport->ice_ufrag); + candidate.set_username(transport->ice_ufrag); + RTC_DCHECK(candidate.password().empty()); + candidate.set_password(transport->ice_pwd); + candidates->push_back( + std::make_unique(mline_id, mline_index, candidate)); + } + + return true; +} + +std::unique_ptr ParseContentDescription( + absl::string_view message, + const MediaType media_type, + int mline_index, + absl::string_view protocol, + const std::vector& payload_types, + size_t* pos, + std::string* content_name, + bool* bundle_only, + int* msid_signaling, + TransportDescription* transport, + std::vector>* candidates, + SdpParseError* error) { + std::unique_ptr media_desc; + if (media_type == MediaType::AUDIO) { + media_desc = std::make_unique(); + } else if (media_type == MediaType::VIDEO) { + media_desc = std::make_unique(); + } else { + RTC_DCHECK_NOTREACHED(); + return nullptr; + } + + media_desc->set_extmap_allow_mixed_enum(MediaContentDescription::kNo); + if (!ParseContent(message, media_type, mline_index, protocol, payload_types, + pos, content_name, bundle_only, msid_signaling, + media_desc.get(), transport, candidates, error)) { + return nullptr; + } + // Sort the codecs according to the m-line fmt list. + std::unordered_map payload_type_preferences; + // "size + 1" so that the lowest preference payload type has a preference of + // 1, which is greater than the default (0) for payload types not in the fmt + // list. + int preference = static_cast(payload_types.size() + 1); + for (int pt : payload_types) { + payload_type_preferences[pt] = preference--; + } + std::vector codecs = media_desc->codecs(); + absl::c_sort( + codecs, [&payload_type_preferences](const Codec& a, const Codec& b) { + return payload_type_preferences[a.id] > payload_type_preferences[b.id]; + }); + // Backfill any default parameters. + BackfillCodecParameters(codecs); + + media_desc->set_codecs(codecs); + return media_desc; +} + +bool HasDuplicateMsidLines(SessionDescription* desc) { + std::set> seen_msids; + for (const ContentInfo& content : desc->contents()) { + for (const StreamParams& stream : content.media_description()->streams()) { + auto msid = std::pair(stream.first_stream_id(), stream.id); + if (seen_msids.find(msid) != seen_msids.end()) { + return true; + } + seen_msids.insert(std::move(msid)); + } + } + return false; +} + +bool ParseMediaDescription( + absl::string_view message, + const TransportDescription& session_td, + const RtpHeaderExtensions& session_extmaps, + size_t* pos, + const SocketAddress& session_connection_addr, + SessionDescription* desc, + std::vector>* candidates, + SdpParseError* error) { + RTC_DCHECK(desc != nullptr); + int mline_index = -1; + int msid_signaling = desc->msid_signaling(); + + // Zero or more media descriptions + // RFC 4566 + // m= + while (std::optional mline = + GetLineWithType(message, pos, kLineTypeMedia)) { + ++mline_index; + + std::vector fields = + split(mline->substr(kLinePrefixLength), kSdpDelimiterSpaceChar); + + const size_t expected_min_fields = 4; + if (fields.size() < expected_min_fields) { + return ParseFailedExpectMinFieldNum(*mline, expected_min_fields, error); + } + bool port_rejected = false; + // RFC 3264 + // To reject an offered stream, the port number in the corresponding stream + // in the answer MUST be set to zero. + if (fields[1] == kMediaPortRejected) { + port_rejected = true; + } + + int port = 0; + if (!FromString(fields[1], &port) || !IsValidPort(port)) { + return ParseFailed(*mline, "The port number is invalid", error); + } + absl::string_view protocol = fields[2]; + + // + std::vector payload_types; + if (IsRtpProtocol(protocol)) { + for (size_t j = 3; j < fields.size(); ++j) { + int pl = 0; + if (!GetPayloadTypeFromString(*mline, fields[j], &pl, error)) { + return false; + } + payload_types.push_back(pl); + } + } + + // Make a temporary TransportDescription based on `session_td`. + // Some of this gets overwritten by ParseContent. + TransportDescription transport( + session_td.transport_options, session_td.ice_ufrag, session_td.ice_pwd, + session_td.ice_mode, session_td.connection_role, + session_td.identity_fingerprint.get()); + + std::unique_ptr content; + std::string content_name; + bool bundle_only = false; + int section_msid_signaling = kMsidSignalingNotUsed; + absl::string_view media_type = fields[0]; + if ((media_type == kSdpMediaTypeVideo || + media_type == kSdpMediaTypeAudio) && + !IsRtpProtocol(protocol)) { + return ParseFailed(*mline, "Unsupported protocol for media type", error); + } + if (media_type == kSdpMediaTypeVideo) { + content = ParseContentDescription( + message, MediaType::VIDEO, mline_index, protocol, payload_types, pos, + &content_name, &bundle_only, §ion_msid_signaling, &transport, + candidates, error); + } else if (media_type == kSdpMediaTypeAudio) { + content = ParseContentDescription( + message, MediaType::AUDIO, mline_index, protocol, payload_types, pos, + &content_name, &bundle_only, §ion_msid_signaling, &transport, + candidates, error); + } else if (media_type == kSdpMediaTypeData && IsDtlsSctp(protocol)) { + // The draft-03 format is: + // m=application DTLS/SCTP ... + // use_sctpmap should be false. + // The draft-26 format is: + // m=application UDP/DTLS/SCTP webrtc-datachannel + // use_sctpmap should be false. + auto data_desc = std::make_unique(); + // Default max message size is 64K + // according to draft-ietf-mmusic-sctp-sdp-26 + data_desc->set_max_message_size(kDefaultSctpMaxMessageSize); + int p; + if (FromString(fields[3], &p)) { + data_desc->set_port(p); + } else if (fields[3] == kDefaultSctpmapProtocol) { + data_desc->set_use_sctpmap(false); + } + if (!ParseContent(message, MediaType::DATA, mline_index, protocol, + payload_types, pos, &content_name, &bundle_only, + §ion_msid_signaling, data_desc.get(), &transport, + candidates, error)) { + return false; + } + data_desc->set_protocol(protocol); + content = std::move(data_desc); + } else { + RTC_LOG(LS_WARNING) << "Unsupported media type: " << *mline; + auto unsupported_desc = + std::make_unique(media_type); + if (!ParseContent(message, MediaType::UNSUPPORTED, mline_index, protocol, + payload_types, pos, &content_name, &bundle_only, + §ion_msid_signaling, unsupported_desc.get(), + &transport, candidates, error)) { + return false; + } + unsupported_desc->set_protocol(protocol); + content = std::move(unsupported_desc); + } + if (!content.get()) { + // ParseContentDescription returns NULL if failed. + return false; + } + + msid_signaling |= section_msid_signaling; + + bool content_rejected = false; + // A port of 0 is not interpreted as a rejected m= section when it's + // used along with a=bundle-only. + if (bundle_only) { + if (!port_rejected) { + // Usage of bundle-only with a nonzero port is unspecified. So just + // ignore bundle-only if we see this. + bundle_only = false; + RTC_LOG(LS_WARNING) + << "a=bundle-only attribute observed with a nonzero " + "port; this usage is unspecified so the attribute is being " + "ignored."; + } + } else { + // If not using bundle-only, interpret port 0 in the normal way; the m= + // section is being rejected. + content_rejected = port_rejected; + } + + if (content->as_unsupported()) { + content_rejected = true; + } else if (IsRtpProtocol(protocol) && !content->as_sctp()) { + content->set_protocol(std::string(protocol)); + // Set the extmap. + if (!session_extmaps.empty() && + !content->rtp_header_extensions().empty()) { + return ParseFailed("", + "The a=extmap MUST be either all session level or " + "all media level.", + error); + } + for (size_t i = 0; i < session_extmaps.size(); ++i) { + content->AddRtpHeaderExtension(session_extmaps[i]); + } + } else if (content->as_sctp()) { + // Do nothing, it's OK + } else { + RTC_LOG(LS_WARNING) << "Parse failed with unknown protocol " << protocol; + return false; } - } - // Remove duplicate rids. - RemoveDuplicateRidDescriptions(payload_types, &rids); + // Use the session level connection address if the media level addresses are + // not specified. + SocketAddress address; + address = content->connection_address().IsNil() + ? session_connection_addr + : content->connection_address(); + address.SetPort(port); + content->set_connection_address(address); - // If simulcast is specifed, split the rids into send and receive. - // Rids that do not appear in simulcast attribute will be removed. - std::vector send_rids; - std::vector receive_rids; - if (!simulcast.empty()) { - // Verify that the rids in simulcast match rids in sdp. - RemoveInvalidRidsFromSimulcast(rids, &simulcast); + desc->AddContent(content_name, + IsDtlsSctp(protocol) ? MediaProtocolType::kSctp + : MediaProtocolType::kRtp, + content_rejected, bundle_only, std::move(content)); + // Create TransportInfo with the media level "ice-pwd" and "ice-ufrag". + desc->AddTransportInfo(TransportInfo(content_name, transport)); + } + // Apply whole-description sanity checks + if (HasDuplicateMsidLines(desc)) { + ParseFailed(message, *pos, "Duplicate a=msid lines detected", error); + return false; + } - // Use simulcast description to figure out Send / Receive RIDs. - std::map rid_map; - for (const RidDescription& rid : rids) { - rid_map[rid.rid] = rid; - } + desc->set_msid_signaling(msid_signaling); - for (const auto& layer : simulcast.send_layers().GetAllLayers()) { - auto iter = rid_map.find(layer.rid); - RTC_DCHECK(iter != rid_map.end()); - send_rids.push_back(iter->second); - } + size_t end_of_message = message.size(); + if (mline_index == -1 && *pos != end_of_message) { + ParseFailed(message, *pos, "Expects m line.", error); + return false; + } + return true; +} - for (const auto& layer : simulcast.receive_layers().GetAllLayers()) { - auto iter = rid_map.find(layer.rid); - RTC_DCHECK(iter != rid_map.end()); - receive_rids.push_back(iter->second); - } +} // namespace - media_desc->set_simulcast_description(simulcast); - } else { - // RID is specified in RFC 8851, which identifies a lot of usages. - // We only support RFC 8853 usage of RID, not anything else. - // Ignore all RID parameters when a=simulcast is missing. - // In particular do NOT do send_rids = rids; - RTC_LOG(LS_VERBOSE) << "Ignoring send_rids without simulcast"; +std::string SdpSerialize(const JsepSessionDescription& jdesc) { + const SessionDescription* desc = jdesc.description(); + if (!desc) { + return ""; } - media_desc->set_receive_rids(receive_rids); + std::string message; - // Create tracks from the `ssrc_infos`. - // If the stream_id/track_id for all SSRCS are identical, one StreamParams - // will be created in CreateTracksFromSsrcInfos, containing all the SSRCs from - // the m= section. - if (!ssrc_infos.empty()) { - CreateTracksFromSsrcInfos(ssrc_infos, stream_ids, track_id, &tracks, - *msid_signaling); - } else if (media_type != MediaType::DATA && - (*msid_signaling & kMsidSignalingMediaSection)) { - // If the stream_ids/track_id was signaled but SSRCs were unsignaled we - // still create a track. This isn't done for data media types because - // StreamParams aren't used for SCTP streams, and RTP data channels don't - // support unsignaled SSRCs. - // If track id was not specified, create a random one. - if (track_id.empty()) { - track_id = CreateRandomString(8); - } - CreateTrackWithNoSsrcs(stream_ids, track_id, send_rids, &tracks); - } + // Session Description. + AddLine(kSessionVersion, &message); + // Session Origin + // RFC 4566 + // o= + // + StringBuilder os; + InitLine(kLineTypeOrigin, kSessionOriginUsername, &os); + const std::string& session_id = + jdesc.session_id().empty() ? kSessionOriginSessionId : jdesc.session_id(); + const std::string& session_version = jdesc.session_version().empty() + ? kSessionOriginSessionVersion + : jdesc.session_version(); + os << " " << session_id << " " << session_version << " " + << kSessionOriginNettype << " " << kSessionOriginAddrtype << " " + << kSessionOriginAddress; + AddLine(os.str(), &message); + AddLine(kSessionName, &message); - // Add the ssrc group to the track. - for (const SsrcGroup& ssrc_group : ssrc_groups) { - if (ssrc_group.ssrcs.empty()) { - continue; - } - uint32_t ssrc = ssrc_group.ssrcs.front(); - for (StreamParams& track : tracks) { - if (track.has_ssrc(ssrc)) { - track.ssrc_groups.push_back(ssrc_group); - } + // Time Description. + AddLine(kTimeDescription, &message); + + // BUNDLE Groups + std::vector groups = + desc->GetGroupsByName(GROUP_TYPE_BUNDLE); + for (const ContentGroup* group : groups) { + std::string group_line = kAttrGroup; + RTC_DCHECK(group != nullptr); + for (const std::string& content_name : group->content_names()) { + group_line.append(" "); + group_line.append(content_name); } + AddLine(group_line, &message); } - // Add the new tracks to the `media_desc`. - for (StreamParams& track : tracks) { - media_desc->AddStream(track); + // Mixed one- and two-byte header extension. + if (desc->extmap_allow_mixed()) { + InitAttrLine(kAttributeExtmapAllowMixed, &os); + AddLine(os.str(), &message); } - UpdateFromWildcardCodecs(media_desc); - // Codec has not been populated correctly unless the name has been set. This - // can happen if an SDP has an fmtp or rtcp-fb with a payload type but doesn't - // have a corresponding "rtpmap" line. This should lead to a parse error. - if (!absl::c_all_of(media_desc->codecs(), - [](const Codec codec) { return !codec.name.empty(); })) { - return ParseFailed("Failed to parse codecs correctly.", error); + // MediaStream semantics. + // TODO(bugs.webrtc.org/10421): Change to & kMsidSignalingSemantic + // when we think it's safe to do so, so that we gradually fade out this old + // line that was removed from the specification. + if (desc->msid_signaling() != kMsidSignalingNotUsed) { + InitAttrLine(kAttributeMsidSemantics, &os); + os << kSdpDelimiterColon << " " << kMediaStreamSemantic; + + // TODO(bugs.webrtc.org/10421): this code only looks at the first + // audio/video content. Fixing that might result in much larger SDP and the + // msid-semantic line should eventually go away so this is not worth fixing. + std::set media_stream_ids; + const ContentInfo* audio_content = GetFirstAudioContent(desc); + if (audio_content) + GetMediaStreamIds(audio_content, &media_stream_ids); + + const ContentInfo* video_content = GetFirstVideoContent(desc); + if (video_content) + GetMediaStreamIds(video_content, &media_stream_ids); + + for (const std::string& id : media_stream_ids) { + os << " " << id; + } + AddLine(os.str(), &message); } - if (media_type == MediaType::AUDIO) { - AddAudioAttribute(kCodecParamMaxPTime, maxptime_as_string, media_desc); - AddAudioAttribute(kCodecParamPTime, ptime_as_string, media_desc); + + // a=ice-lite + // + // TODO(deadbeef): It's weird that we need to iterate TransportInfos for + // this, when it's a session-level attribute. It really should be moved to a + // session-level structure like SessionDescription. + for (const TransportInfo& transport : desc->transport_infos()) { + if (transport.description.ice_mode == ICEMODE_LITE) { + InitAttrLine(kAttributeIceLite, &os); + AddLine(os.str(), &message); + break; + } } - // RFC 5245 - // Update the candidates with the media level "ice-pwd" and "ice-ufrag". - for (Candidate& candidate : candidates_orig) { - RTC_DCHECK(candidate.username().empty() || - candidate.username() == transport->ice_ufrag); - candidate.set_username(transport->ice_ufrag); - RTC_DCHECK(candidate.password().empty()); - candidate.set_password(transport->ice_pwd); - candidates->push_back( - std::make_unique(mline_id, mline_index, candidate)); + // Preserve the order of the media contents. + int mline_index = -1; + for (const ContentInfo& content : desc->contents()) { + std::vector candidates; + GetCandidatesByMindex(jdesc, ++mline_index, &candidates); + BuildMediaDescription(&content, desc->GetTransportInfoByName(content.mid()), + content.media_description()->type(), candidates, + desc->msid_signaling(), &message); } + return message; +} - return true; +// Serializes the passed in IceCandidate to a SDP string. +// candidate - The candidate to be serialized. +std::string SdpSerializeCandidate(const IceCandidate& candidate) { + return SdpSerializeCandidate(candidate.candidate()); } -bool ParseSsrcAttribute(absl::string_view line, - SsrcInfoVec* ssrc_infos, - int* msid_signaling, - SdpParseError* error) { - RTC_DCHECK(ssrc_infos != nullptr); - // RFC 5576 - // a=ssrc: - // a=ssrc: : - std::string field1, field2; - if (!tokenize_first(line.substr(kLinePrefixLength), kSdpDelimiterSpaceChar, - &field1, &field2)) { - const size_t expected_fields = 2; - return ParseFailedExpectFieldNum(line, expected_fields, error); - } +// Serializes a cricket Candidate. +std::string SdpSerializeCandidate(const Candidate& candidate) { + std::string message; + std::vector candidates(1, candidate); + BuildCandidate(candidates, true, &message); + // From WebRTC draft section 4.8.1.1 candidate-attribute will be + // just candidate: not a=candidate:CRLF + RTC_DCHECK(message.find("a=") == 0); + message.erase(0, 2); + RTC_DCHECK(message.find(kLineBreak) == message.size() - 2); + message.resize(message.size() - 2); + return message; +} - // ssrc: - std::string ssrc_id_s; - if (!GetValue(field1, kAttributeSsrc, &ssrc_id_s, error)) { - return false; - } - uint32_t ssrc_id = 0; - if (!GetValueFromString(line, ssrc_id_s, &ssrc_id, error)) { +bool SdpDeserialize(absl::string_view message, + JsepSessionDescription* jdesc, + SdpParseError* error) { + std::string session_id; + std::string session_version; + TransportDescription session_td("", ""); + RtpHeaderExtensions session_extmaps; + SocketAddress session_connection_addr; + auto desc = std::make_unique(); + size_t current_pos = 0; + + // Session Description + if (!ParseSessionDescription(message, ¤t_pos, &session_id, + &session_version, &session_td, &session_extmaps, + &session_connection_addr, desc.get(), error)) { return false; } - std::string attribute; - std::string value; - if (!tokenize_first(field2, kSdpDelimiterColonChar, &attribute, &value)) { - StringBuilder description; - description << "Failed to get the ssrc attribute value from " << field2 - << ". Expected format :."; - return ParseFailed(line, description.Release(), error); + // Media Description + std::vector> candidates; + if (!ParseMediaDescription(message, session_td, session_extmaps, ¤t_pos, + session_connection_addr, desc.get(), &candidates, + error)) { + return false; } - // Check if there's already an item for this `ssrc_id`. Create a new one if - // there isn't. - auto ssrc_info_it = - absl::c_find_if(*ssrc_infos, [ssrc_id](const SsrcInfo& ssrc_info) { - return ssrc_info.ssrc_id == ssrc_id; - }); - if (ssrc_info_it == ssrc_infos->end()) { - SsrcInfo info; - info.ssrc_id = ssrc_id; - ssrc_infos->push_back(info); - ssrc_info_it = ssrc_infos->end() - 1; - } - SsrcInfo& ssrc_info = *ssrc_info_it; + jdesc->Initialize(std::move(desc), session_id, session_version); - // Store the info to the `ssrc_info`. - if (attribute == kSsrcAttributeCname) { - // RFC 5576 - // cname: - ssrc_info.cname = value; - } else if (attribute == kSsrcAttributeMsid) { - // draft-alvestrand-mmusic-msid-00 - // msid:identifier [appdata] - std::vector fields = - split(value, kSdpDelimiterSpaceChar); - if (fields.size() < 1 || fields.size() > 2) { - return ParseFailed( - line, "Expected format \"msid:[ ]\".", error); - } - ssrc_info.stream_id = std::string(fields[0]); - if (fields.size() == 2) { - ssrc_info.track_id = std::string(fields[1]); - } - *msid_signaling |= kMsidSignalingSsrcAttribute; - } else { - RTC_LOG(LS_INFO) << "Ignored unknown ssrc-specific attribute: " << line; + for (const auto& candidate : candidates) { + jdesc->AddCandidate(candidate.get()); } return true; } -bool ParseSsrcGroupAttribute(absl::string_view line, - SsrcGroupVec* ssrc_groups, +bool SdpDeserializeCandidate(absl::string_view transport_name, + absl::string_view message, + Candidate* candidate, SdpParseError* error) { - RTC_DCHECK(ssrc_groups != nullptr); - // RFC 5576 - // a=ssrc-group: ... - std::vector fields = - split(line.substr(kLinePrefixLength), kSdpDelimiterSpaceChar); - const size_t expected_min_fields = 2; - if (fields.size() < expected_min_fields) { - return ParseFailedExpectMinFieldNum(line, expected_min_fields, error); - } - std::string semantics; - if (!GetValue(fields[0], kAttributeSsrcGroup, &semantics, error)) { + RTC_DCHECK(candidate != nullptr); + if (!ParseCandidate(message, candidate, error, true)) { return false; } - std::vector ssrcs; - for (size_t i = 1; i < fields.size(); ++i) { - uint32_t ssrc = 0; - if (!GetValueFromString(line, fields[i], &ssrc, error)) { - return false; - } - // Reject duplicates. While not forbidden by RFC 5576, - // they don't make sense. - if (absl::c_linear_search(ssrcs, ssrc)) { - return ParseFailed(line, "Duplicate SSRC in ssrc-group", error); - } - ssrcs.push_back(ssrc); - } - ssrc_groups->push_back(SsrcGroup(semantics, ssrcs)); + candidate->set_transport_name(transport_name); return true; } -// Updates or creates a new codec entry in the audio description with according -// to `name`, `clockrate`, `bitrate`, and `channels`. -void UpdateCodec(int payload_type, - absl::string_view name, - int clockrate, - int bitrate, - size_t channels, - MediaContentDescription* desc) { - // Codec may already be populated with (only) optional parameters - // (from an fmtp). - Codec codec = - GetCodecWithPayloadType(desc->type(), desc->codecs(), payload_type); - codec.name = std::string(name); - codec.clockrate = clockrate; - codec.bitrate = bitrate; - codec.channels = channels; - AddOrReplaceCodec(desc, codec); -} +bool ParseCandidate(absl::string_view message, + Candidate* candidate, + SdpParseError* error, + bool is_raw) { + RTC_DCHECK(candidate != nullptr); -// Updates or creates a new codec entry in the video description according to -// `name`, `width`, `height`, and `framerate`. -void UpdateCodec(int payload_type, - absl::string_view name, - MediaContentDescription* desc) { - // Codec may already be populated with (only) optional parameters - // (from an fmtp). - Codec codec = - GetCodecWithPayloadType(desc->type(), desc->codecs(), payload_type); - codec.name = std::string(name); - AddOrReplaceCodec(desc, codec); -} + // Makes sure `message` contains only one line. + absl::string_view first_line; + + size_t line_end = message.find(kNewLineChar); + if (line_end == absl::string_view::npos) { + first_line = message; + } else if (line_end + 1 == message.size()) { + first_line = message.substr(0, line_end); + } else { + return ParseFailed(message, 0, "Expect one line only", error); + } + + // Trim return char, if any. + first_line = TrimReturnChar(first_line); + + // From WebRTC draft section 4.8.1.1 candidate-attribute should be + // candidate: when trickled, but we still support + // a=candidate:CRLF for backward compatibility and for parsing a line + // from the SDP. + if (IsLineType(first_line, kLineTypeAttributes)) { + first_line = first_line.substr(kLinePrefixLength); + } + + std::string attribute_candidate; + std::string candidate_value; + + // `first_line` must be in the form of "candidate:". + if (!tokenize_first(first_line, kSdpDelimiterColonChar, &attribute_candidate, + &candidate_value) || + attribute_candidate != kAttributeCandidate) { + if (is_raw) { + StringBuilder description; + description << "Expect line: " << kAttributeCandidate + << ":" + ""; + return ParseFailed(first_line, 0, description.Release(), error); + } else { + return ParseFailedExpectLine(first_line, 0, kLineTypeAttributes, + kAttributeCandidate, error); + } + } -bool ParseRtpmapAttribute(absl::string_view line, - const MediaType media_type, - const std::vector& payload_types, - MediaContentDescription* media_desc, - SdpParseError* error) { - static const int kFirstDynamicPayloadTypeLowerRange = 35; std::vector fields = - split(line.substr(kLinePrefixLength), kSdpDelimiterSpaceChar); - // RFC 4566 - // a=rtpmap: /[/] - const size_t expected_min_fields = 2; - if (fields.size() < expected_min_fields) { - return ParseFailedExpectMinFieldNum(line, expected_min_fields, error); + split(candidate_value, kSdpDelimiterSpaceChar); + + // RFC 5245 + // a=candidate: + // typ + // [raddr ] [rport ] + // *(SP extension-att-name SP extension-att-value) + const size_t expected_min_fields = 8; + if (fields.size() < expected_min_fields || + (fields[6] != kAttributeCandidateTyp)) { + return ParseFailedExpectMinFieldNum(first_line, expected_min_fields, error); } - std::string payload_type_value; - if (!GetValue(fields[0], kAttributeRtpmap, &payload_type_value, error)) { + const absl::string_view foundation = fields[0]; + + int component_id = 0; + if (!GetValueFromString(first_line, fields[1], &component_id, error)) { return false; } - int payload_type = 0; - if (!GetPayloadTypeFromString(line, payload_type_value, &payload_type, - error)) { + const absl::string_view transport = fields[2]; + uint32_t priority = 0; + if (!GetValueFromString(first_line, fields[3], &priority, error)) { + return false; + } + const absl::string_view connection_address = fields[4]; + int port = 0; + if (!GetValueFromString(first_line, fields[5], &port, error)) { return false; } + if (!IsValidPort(port)) { + return ParseFailed(first_line, "Invalid port number.", error); + } + SocketAddress address(connection_address, port); - if (!absl::c_linear_search(payload_types, payload_type)) { - RTC_LOG(LS_WARNING) << "Ignore rtpmap line that did not appear in the " - " of the m-line: " - << line; - return true; + std::optional protocol = StringToProto(transport); + if (!protocol) { + return ParseFailed(first_line, "Unsupported transport type.", error); } - std::vector codec_params = split(fields[1], '/'); - // /[/] - // 2 mandatory fields - if (codec_params.size() < 2 || codec_params.size() > 3) { - return ParseFailed(line, - "Expected format \"/" - "[/]\".", - error); + bool tcp_protocol = false; + switch (*protocol) { + // Supported protocols. + case PROTO_UDP: + break; + case PROTO_TCP: + case PROTO_SSLTCP: + tcp_protocol = true; + break; + default: + return ParseFailed(first_line, "Unsupported transport type.", error); + } + + IceCandidateType candidate_type; + const absl::string_view type = fields[7]; + if (type == kCandidateHost) { + candidate_type = IceCandidateType::kHost; + } else if (type == kCandidateSrflx) { + candidate_type = IceCandidateType::kSrflx; + } else if (type == kCandidateRelay) { + candidate_type = IceCandidateType::kRelay; + } else if (type == kCandidatePrflx) { + candidate_type = IceCandidateType::kPrflx; + } else { + return ParseFailed(first_line, "Unsupported candidate type.", error); + } + + size_t current_position = expected_min_fields; + SocketAddress related_address; + // The 2 optional fields for related address + // [raddr ] [rport ] + if (fields.size() >= (current_position + 2) && + fields[current_position] == kAttributeCandidateRaddr) { + related_address.SetIP(fields[++current_position]); + ++current_position; + } + if (fields.size() >= (current_position + 2) && + fields[current_position] == kAttributeCandidateRport) { + int related_port = 0; + if (!GetValueFromString(first_line, fields[++current_position], + &related_port, error)) { + return false; + } + if (!IsValidPort(related_port)) { + return ParseFailed(first_line, "Invalid port number.", error); + } + related_address.SetPort(related_port); + ++current_position; } - const absl::string_view encoding_name = codec_params[0]; - int clock_rate = 0; - if (!GetValueFromString(line, codec_params[1], &clock_rate, error)) { - return false; + + // If this is a TCP candidate, it has additional extension as defined in + // RFC 6544. + absl::string_view tcptype; + if (fields.size() >= (current_position + 2) && + fields[current_position] == kTcpCandidateType) { + tcptype = fields[++current_position]; + ++current_position; + + if (tcptype != TCPTYPE_ACTIVE_STR && tcptype != TCPTYPE_PASSIVE_STR && + tcptype != TCPTYPE_SIMOPEN_STR) { + return ParseFailed(first_line, "Invalid TCP candidate type.", error); + } + + if (!tcp_protocol) { + return ParseFailed(first_line, "Invalid non-TCP candidate", error); + } + } else if (tcp_protocol) { + // We allow the tcptype to be missing, for backwards compatibility, + // treating it as a passive candidate. + // TODO(bugs.webrtc.org/11466): Treat a missing tcptype as an error? + tcptype = TCPTYPE_PASSIVE_STR; } - if (media_type == MediaType::VIDEO) { - for (const Codec& existing_codec : media_desc->codecs()) { - if (!existing_codec.name.empty() && payload_type == existing_codec.id && - (!absl::EqualsIgnoreCase(encoding_name, existing_codec.name) || - clock_rate != existing_codec.clockrate)) { - StringBuilder description; - description - << "Duplicate " - << (payload_type < kFirstDynamicPayloadTypeLowerRange - ? "statically assigned" - : "") - << " payload type with conflicting codec name or clock rate."; - return ParseFailed(line, description.Release(), error); + // Extension + // Though non-standard, we support the ICE ufrag and pwd being signaled on + // the candidate to avoid issues with confusing which generation a candidate + // belongs to when trickling multiple generations at the same time. + absl::string_view username; + absl::string_view password; + uint32_t generation = 0; + uint16_t network_id = 0; + uint16_t network_cost = 0; + for (size_t i = current_position; i + 1 < fields.size(); ++i) { + // RFC 5245 + // *(SP extension-att-name SP extension-att-value) + if (fields[i] == kAttributeCandidateGeneration) { + if (!GetValueFromString(first_line, fields[++i], &generation, error)) { + return false; } - } - UpdateCodec(payload_type, encoding_name, media_desc); - } else if (media_type == MediaType::AUDIO) { - // RFC 4566 - // For audio streams, indicates the number - // of audio channels. This parameter is OPTIONAL and may be - // omitted if the number of channels is one, provided that no - // additional parameters are needed. - size_t channels = 1; - if (codec_params.size() == 3) { - if (!GetValueFromString(line, codec_params[2], &channels, error)) { + } else if (fields[i] == kAttributeCandidateUfrag) { + username = fields[++i]; + } else if (fields[i] == kAttributeCandidatePwd) { + password = fields[++i]; + } else if (fields[i] == kAttributeCandidateNetworkId) { + if (!GetValueFromString(first_line, fields[++i], &network_id, error)) { return false; } - } - if (channels > kMaxNumberOfAudioChannels) { - StringBuilder description; - description << "At most " << kMaxNumberOfAudioChannels - << " channels are supported."; - return ParseFailed(line, description.Release(), error); - } - - for (const Codec& existing_codec : media_desc->codecs()) { - // TODO(crbug.com/1338902) re-add checks for clockrate and number of - // channels. - if (!existing_codec.name.empty() && payload_type == existing_codec.id && - (!absl::EqualsIgnoreCase(encoding_name, existing_codec.name))) { - StringBuilder description; - description - << "Duplicate " - << (payload_type < kFirstDynamicPayloadTypeLowerRange - ? "statically assigned" - : "") - << " payload type with conflicting codec name or clock rate."; - return ParseFailed(line, description.Release(), error); + } else if (fields[i] == kAttributeCandidateNetworkCost) { + if (!GetValueFromString(first_line, fields[++i], &network_cost, error)) { + return false; } + network_cost = std::min(network_cost, kNetworkCostMax); + } else { + // Skip the unknown extension. + ++i; } - UpdateCodec(payload_type, encoding_name, clock_rate, 0, channels, - media_desc); } + + *candidate = Candidate(component_id, ProtoToString(*protocol), address, + priority, username, password, candidate_type, + generation, foundation, network_id, network_cost); + candidate->set_related_address(related_address); + candidate->set_tcptype(tcptype); return true; } -bool ParseFmtpParam(absl::string_view line, - std::string* parameter, - std::string* value, - SdpParseError* error) { - if (!tokenize_first(line, kSdpDelimiterEqualChar, parameter, value)) { - // Support for non-key-value lines like RFC 2198 or RFC 4733. - *parameter = ""; - *value = std::string(line); - return true; +bool WriteFmtpParameters(const CodecParameterMap& parameters, + StringBuilder* os) { + bool empty = true; + const char* delimiter = ""; // No delimiter before first parameter. + for (const auto& entry : parameters) { + const std::string& key = entry.first; + const std::string& value = entry.second; + + if (IsFmtpParam(key)) { + *os << delimiter; + // A semicolon before each subsequent parameter. + delimiter = kSdpDelimiterSemicolon; + WriteFmtpParameter(key, value, os); + empty = false; + } } - // a=fmtp: =; =; ... - return true; + + return !empty; } bool ParseFmtpParameterSet(absl::string_view line_params, @@ -3650,114 +3618,4 @@ bool ParseFmtpParameterSet(absl::string_view line_params, return true; } -bool ParseFmtpAttributes(absl::string_view line, - const MediaType media_type, - MediaContentDescription* media_desc, - SdpParseError* error) { - if (media_type != MediaType::AUDIO && media_type != MediaType::VIDEO) { - return true; - } - - std::string line_payload; - std::string line_params; - - // https://tools.ietf.org/html/rfc4566#section-6 - // a=fmtp: - // At least two fields, whereas the second one is any of the optional - // parameters. - if (!tokenize_first(line.substr(kLinePrefixLength), kSdpDelimiterSpaceChar, - &line_payload, &line_params)) { - ParseFailedExpectMinFieldNum(line, 2, error); - return false; - } - - // Parse out the payload information. - std::string payload_type_str; - if (!GetValue(line_payload, kAttributeFmtp, &payload_type_str, error)) { - return false; - } - - int payload_type = 0; - if (!GetPayloadTypeFromString(line_payload, payload_type_str, &payload_type, - error)) { - return false; - } - - // Parse out format specific parameters. - CodecParameterMap codec_params; - if (!ParseFmtpParameterSet(line_params, codec_params, error)) { - return false; - } - - if (media_type == MediaType::AUDIO || media_type == MediaType::VIDEO) { - UpdateCodec(media_desc, payload_type, codec_params); - } - return true; -} - -bool ParsePacketizationAttribute(absl::string_view line, - const MediaType media_type, - MediaContentDescription* media_desc, - SdpParseError* error) { - if (media_type != MediaType::VIDEO) { - return true; - } - std::vector packetization_fields = - split(line, kSdpDelimiterSpaceChar); - if (packetization_fields.size() < 2) { - return ParseFailedGetValue(line, kAttributePacketization, error); - } - std::string payload_type_string; - if (!GetValue(packetization_fields[0], kAttributePacketization, - &payload_type_string, error)) { - return false; - } - int payload_type; - if (!GetPayloadTypeFromString(line, payload_type_string, &payload_type, - error)) { - return false; - } - absl::string_view packetization = packetization_fields[1]; - UpdateVideoCodecPacketization(media_desc, payload_type, packetization); - return true; -} - -bool ParseRtcpFbAttribute(absl::string_view line, - const MediaType media_type, - MediaContentDescription* media_desc, - SdpParseError* error) { - if (media_type != MediaType::AUDIO && media_type != MediaType::VIDEO) { - return true; - } - std::vector rtcp_fb_fields = - split(line, kSdpDelimiterSpaceChar); - if (rtcp_fb_fields.size() < 2) { - return ParseFailedGetValue(line, kAttributeRtcpFb, error); - } - std::string payload_type_string; - if (!GetValue(rtcp_fb_fields[0], kAttributeRtcpFb, &payload_type_string, - error)) { - return false; - } - int payload_type = kWildcardPayloadType; - if (payload_type_string != "*") { - if (!GetPayloadTypeFromString(line, payload_type_string, &payload_type, - error)) { - return false; - } - } - absl::string_view id = rtcp_fb_fields[1]; - std::string param = ""; - for (auto iter = rtcp_fb_fields.begin() + 2; iter != rtcp_fb_fields.end(); - ++iter) { - param.append(iter->data(), iter->length()); - } - const FeedbackParam feedback_param(id, param); - - if (media_type == MediaType::AUDIO || media_type == MediaType::VIDEO) { - UpdateCodec(media_desc, payload_type, feedback_param); - } - return true; -} - } // namespace webrtc diff --git a/pc/webrtc_sdp.h b/pc/webrtc_sdp.h index f44df2aa46..835496e25a 100644 --- a/pc/webrtc_sdp.h +++ b/pc/webrtc_sdp.h @@ -25,15 +25,12 @@ #include "absl/strings/string_view.h" #include "api/candidate.h" #include "api/jsep.h" -#include "api/jsep_ice_candidate.h" #include "api/jsep_session_description.h" #include "api/rtp_parameters.h" #include "rtc_base/strings/string_builder.h" #include "rtc_base/system/rtc_export.h" namespace webrtc { -class IceCandidateInterface; -class JsepIceCandidate; class JsepSessionDescription; struct SdpParseError; @@ -44,9 +41,9 @@ struct SdpParseError; // return - SDP string serialized from the arguments. std::string SdpSerialize(const JsepSessionDescription& jdesc); -// Serializes the passed in IceCandidateInterface to a SDP string. +// Serializes the passed in IceCandidate to a SDP string. // candidate - The candidate to be serialized. -std::string SdpSerializeCandidate(const IceCandidateInterface& candidate); +std::string SdpSerializeCandidate(const IceCandidate& candidate); // Serializes a cricket Candidate. // candidate - The candidate to be serialized. @@ -61,17 +58,6 @@ bool SdpDeserialize(absl::string_view message, JsepSessionDescription* jdesc, SdpParseError* error); -// Deserializes the passed in SDP string to one JsepIceCandidate. -// The first line must be a=candidate line and only the first line will be -// parsed. -// message - The SDP string to be Deserialized. -// candidates - The JsepIceCandidate from the SDP string. -// error - The detail error information when parsing fails. -// return - true on success, false on failure. -RTC_EXPORT bool SdpDeserializeCandidate(absl::string_view message, - JsepIceCandidate* candidate, - SdpParseError* error); - // Deserializes the passed in SDP string to a cricket Candidate. // The first line must be a=candidate line and only the first line will be // parsed. diff --git a/pc/webrtc_sdp_unittest.cc b/pc/webrtc_sdp_unittest.cc index 844973a53f..5bb0a0c5b8 100644 --- a/pc/webrtc_sdp_unittest.cc +++ b/pc/webrtc_sdp_unittest.cc @@ -64,40 +64,39 @@ using ::testing::ElementsAre; using ::testing::Field; using ::testing::Property; -static const uint32_t kDefaultSctpPort = 5000; -static const uint16_t kUnusualSctpPort = 9556; -static const char kSessionTime[] = "t=0 0\r\n"; -static const uint32_t kCandidatePriority = 2130706432U; // pref = 1.0 -static const char kAttributeIceUfragVoice[] = "a=ice-ufrag:ufrag_voice\r\n"; -static const char kAttributeIcePwdVoice[] = "a=ice-pwd:pwd_voice\r\n"; -static const char kAttributeIceUfragVideo[] = "a=ice-ufrag:ufrag_video\r\n"; -static const char kAttributeIcePwdVideo[] = "a=ice-pwd:pwd_video\r\n"; -static const uint32_t kCandidateGeneration = 2; -static const char kCandidateFoundation1[] = "a0+B/1"; -static const char kCandidateFoundation2[] = "a0+B/2"; -static const char kCandidateFoundation3[] = "a0+B/3"; -static const char kCandidateFoundation4[] = "a0+B/4"; -static const char kFingerprint[] = +const uint32_t kDefaultSctpPort = 5000; +const uint16_t kUnusualSctpPort = 9556; +const char kSessionTime[] = "t=0 0\r\n"; +const uint32_t kCandidatePriority = 2130706432U; // pref = 1.0 +const char kAttributeIceUfragVoice[] = "a=ice-ufrag:ufrag_voice\r\n"; +const char kAttributeIcePwdVoice[] = "a=ice-pwd:pwd_voice\r\n"; +const char kAttributeIceUfragVideo[] = "a=ice-ufrag:ufrag_video\r\n"; +const char kAttributeIcePwdVideo[] = "a=ice-pwd:pwd_video\r\n"; +const uint32_t kCandidateGeneration = 2; +const char kCandidateFoundation1[] = "a0+B/1"; +const char kCandidateFoundation2[] = "a0+B/2"; +const char kCandidateFoundation3[] = "a0+B/3"; +const char kCandidateFoundation4[] = "a0+B/4"; +const char kFingerprint[] = "a=fingerprint:sha-1 " "4A:AD:B9:B1:3F:82:18:3B:54:02:12:DF:3E:5D:49:6B:19:E5:7C:AB\r\n"; -static const char kExtmapAllowMixed[] = "a=extmap-allow-mixed\r\n"; -static const int kExtmapId = 1; -static const char kExtmapUri[] = "http://example.com/082005/ext.htm#ttime"; -static const char kExtmap[] = - "a=extmap:1 http://example.com/082005/ext.htm#ttime\r\n"; -static const char kExtmapWithDirectionAndAttribute[] = +const char kExtmapAllowMixed[] = "a=extmap-allow-mixed\r\n"; +const int kExtmapId = 1; +const char kExtmapUri[] = "http://example.com/082005/ext.htm#ttime"; +const char kExtmap[] = "a=extmap:1 http://example.com/082005/ext.htm#ttime\r\n"; +const char kExtmapWithDirectionAndAttribute[] = "a=extmap:1/sendrecv http://example.com/082005/ext.htm#ttime a1 a2\r\n"; -static const char kExtmapWithDirectionAndAttributeEncrypted[] = +const char kExtmapWithDirectionAndAttributeEncrypted[] = "a=extmap:1/sendrecv urn:ietf:params:rtp-hdrext:encrypt " "http://example.com/082005/ext.htm#ttime a1 a2\r\n"; -static const uint8_t kIdentityDigest[] = { - 0x4A, 0xAD, 0xB9, 0xB1, 0x3F, 0x82, 0x18, 0x3B, 0x54, 0x02, - 0x12, 0xDF, 0x3E, 0x5D, 0x49, 0x6B, 0x19, 0xE5, 0x7C, 0xAB}; +const uint8_t kIdentityDigest[] = {0x4A, 0xAD, 0xB9, 0xB1, 0x3F, 0x82, 0x18, + 0x3B, 0x54, 0x02, 0x12, 0xDF, 0x3E, 0x5D, + 0x49, 0x6B, 0x19, 0xE5, 0x7C, 0xAB}; -static const char kDtlsSctp[] = "DTLS/SCTP"; -static const char kUdpDtlsSctp[] = "UDP/DTLS/SCTP"; -static const char kTcpDtlsSctp[] = "TCP/DTLS/SCTP"; +const char kDtlsSctp[] = "DTLS/SCTP"; +const char kUdpDtlsSctp[] = "UDP/DTLS/SCTP"; +const char kTcpDtlsSctp[] = "TCP/DTLS/SCTP"; struct CodecParams { int max_ptime; @@ -110,7 +109,7 @@ struct CodecParams { }; // Reference sdp string -static const char kSdpFullString[] = +const char kSdpFullString[] = "v=0\r\n" "o=- 18446744069414584320 18446462598732840960 IN IP4 127.0.0.1\r\n" "s=-\r\n" @@ -173,7 +172,7 @@ static const char kSdpFullString[] = "a=ssrc:3 cname:stream_1_cname\r\n"; // SDP reference string without the candidates. -static const char kSdpString[] = +const char kSdpString[] = "v=0\r\n" "o=- 18446744069414584320 18446462598732840960 IN IP4 127.0.0.1\r\n" "s=-\r\n" @@ -212,7 +211,7 @@ static const char kSdpString[] = "a=ssrc:3 cname:stream_1_cname\r\n"; // draft-ietf-mmusic-sctp-sdp-03 -static const char kSdpSctpDataChannelString[] = +const char kSdpSctpDataChannelString[] = "m=application 9 UDP/DTLS/SCTP 5000\r\n" "c=IN IP4 0.0.0.0\r\n" "a=ice-ufrag:ufrag_data\r\n" @@ -226,7 +225,7 @@ static const char kSdpSctpDataChannelString[] = // draft-ietf-mmusic-sctp-sdp-12 // Note - this is invalid per draft-ietf-mmusic-sctp-sdp-26, // since the separator after "sctp-port" needs to be a colon. -static const char kSdpSctpDataChannelStringWithSctpPort[] = +const char kSdpSctpDataChannelStringWithSctpPort[] = "m=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\n" "a=sctp-port 5000\r\n" "c=IN IP4 0.0.0.0\r\n" @@ -238,7 +237,7 @@ static const char kSdpSctpDataChannelStringWithSctpPort[] = "a=mid:data_content_name\r\n"; // draft-ietf-mmusic-sctp-sdp-26 -static const char kSdpSctpDataChannelStringWithSctpColonPort[] = +const char kSdpSctpDataChannelStringWithSctpColonPort[] = "m=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\n" "a=sctp-port:5000\r\n" "c=IN IP4 0.0.0.0\r\n" @@ -249,7 +248,7 @@ static const char kSdpSctpDataChannelStringWithSctpColonPort[] = "a=mid:data_content_name\r\n"; -static const char kSdpSctpDataChannelWithCandidatesString[] = +const char kSdpSctpDataChannelWithCandidatesString[] = "m=application 2345 UDP/DTLS/SCTP 5000\r\n" "c=IN IP4 74.125.127.126\r\n" "a=candidate:a0+B/1 1 udp 2130706432 192.168.1.5 1234 typ host " @@ -267,7 +266,7 @@ static const char kSdpSctpDataChannelWithCandidatesString[] = "a=mid:data_content_name\r\n" "a=sctpmap:5000 webrtc-datachannel 1024\r\n"; -static const char kSdpConferenceString[] = +const char kSdpConferenceString[] = "v=0\r\n" "o=- 18446744069414584320 18446462598732840960 IN IP4 127.0.0.1\r\n" "s=-\r\n" @@ -280,14 +279,14 @@ static const char kSdpConferenceString[] = "c=IN IP4 0.0.0.0\r\n" "a=x-google-flag:conference\r\n"; -static const char kSdpSessionString[] = +const char kSdpSessionString[] = "v=0\r\n" "o=- 18446744069414584320 18446462598732840960 IN IP4 127.0.0.1\r\n" "s=-\r\n" "t=0 0\r\n" "a=msid-semantic: WMS local_stream\r\n"; -static const char kSdpAudioString[] = +const char kSdpAudioString[] = "m=audio 9 RTP/SAVPF 111\r\n" "c=IN IP4 0.0.0.0\r\n" "a=rtcp:9 IN IP4 0.0.0.0\r\n" @@ -301,7 +300,7 @@ static const char kSdpAudioString[] = "a=ssrc:1 cname:stream_1_cname\r\n" "a=ssrc:1 msid:local_stream audio_track_id_1\r\n"; -static const char kSdpVideoString[] = +const char kSdpVideoString[] = "m=video 9 RTP/SAVPF 120\r\n" "c=IN IP4 0.0.0.0\r\n" "a=rtcp:9 IN IP4 0.0.0.0\r\n" @@ -316,7 +315,7 @@ static const char kSdpVideoString[] = "a=ssrc:2 msid:local_stream video_track_id_1\r\n"; // Reference sdp string using bundle-only. -static const char kBundleOnlySdpFullString[] = +const char kBundleOnlySdpFullString[] = "v=0\r\n" "o=- 18446744069414584320 18446462598732840960 IN IP4 127.0.0.1\r\n" "s=-\r\n" @@ -370,7 +369,7 @@ static const char kBundleOnlySdpFullString[] = // Plan B SDP reference string, with 2 streams, 2 audio tracks and 3 video // tracks. -static const char kPlanBSdpFullString[] = +const char kPlanBSdpFullString[] = "v=0\r\n" "o=- 18446744069414584320 18446462598732840960 IN IP4 127.0.0.1\r\n" "s=-\r\n" @@ -443,7 +442,7 @@ static const char kPlanBSdpFullString[] = // Unified Plan SDP reference string, with 2 streams, 2 audio tracks and 3 video // tracks. -static const char kUnifiedPlanSdpFullString[] = +const char kUnifiedPlanSdpFullString[] = "v=0\r\n" "o=- 18446744069414584320 18446462598732840960 IN IP4 127.0.0.1\r\n" "s=-\r\n" @@ -559,7 +558,7 @@ static const char kUnifiedPlanSdpFullString[] = // there are 0 media stream ids. // This Unified Plan SDP represents a SDP that signals the msid using both // a=msid and a=ssrc msid semantics. -static const char kUnifiedPlanSdpFullStringWithSpecialMsid[] = +const char kUnifiedPlanSdpFullStringWithSpecialMsid[] = "v=0\r\n" "o=- 18446744069414584320 18446462598732840960 IN IP4 127.0.0.1\r\n" "s=-\r\n" @@ -639,7 +638,7 @@ static const char kUnifiedPlanSdpFullStringWithSpecialMsid[] = "a=ssrc:7 msid:- audio_track_id_3\r\n"; // SDP string for unified plan without SSRCs -static const char kUnifiedPlanSdpFullStringNoSsrc[] = +const char kUnifiedPlanSdpFullStringNoSsrc[] = "v=0\r\n" "o=- 18446744069414584320 18446462598732840960 IN IP4 127.0.0.1\r\n" "s=-\r\n" @@ -733,134 +732,128 @@ static const char kUnifiedPlanSdpFullStringNoSsrc[] = // One candidate reference string as per W3c spec. // candidate: not a=candidate:CRLF -static const char kRawCandidate[] = +const char kRawCandidate[] = "candidate:a0+B/1 1 udp 2130706432 192.168.1.5 1234 typ host generation 2"; // One candidate reference string. -static const char kSdpOneCandidate[] = +const char kSdpOneCandidate[] = "a=candidate:a0+B/1 1 udp 2130706432 192.168.1.5 1234 typ host " "generation 2\r\n"; -static const char kSdpTcpActiveCandidate[] = +const char kSdpTcpActiveCandidate[] = "candidate:a0+B/1 1 tcp 2130706432 192.168.1.5 9 typ host " "tcptype active generation 2"; -static const char kSdpTcpPassiveCandidate[] = +const char kSdpTcpPassiveCandidate[] = "candidate:a0+B/1 1 tcp 2130706432 192.168.1.5 9 typ host " "tcptype passive generation 2"; -static const char kSdpTcpSOCandidate[] = +const char kSdpTcpSOCandidate[] = "candidate:a0+B/1 1 tcp 2130706432 192.168.1.5 9 typ host " "tcptype so generation 2"; -static const char kSdpTcpInvalidCandidate[] = +const char kSdpTcpInvalidCandidate[] = "candidate:a0+B/1 1 tcp 2130706432 192.168.1.5 9 typ host " "tcptype invalid generation 2"; // One candidate reference string with IPV6 address. -static const char kRawIPV6Candidate[] = +const char kRawIPV6Candidate[] = "candidate:a0+B/1 1 udp 2130706432 " "abcd:abcd:abcd:abcd:abcd:abcd:abcd:abcd 1234 typ host generation 2"; // One candidate reference string. -static const char kSdpOneCandidateWithUfragPwd[] = +const char kSdpOneCandidateWithUfragPwd[] = "a=candidate:a0+B/1 1 udp 2130706432 192.168.1.5 1234 typ host network_name" " eth0 ufrag user_rtp pwd password_rtp generation 2\r\n"; -static const char kRawHostnameCandidate[] = +const char kRawHostnameCandidate[] = "candidate:a0+B/1 1 udp 2130706432 a.test 1234 typ host generation 2"; // Session id and version -static const char kSessionId[] = "18446744069414584320"; -static const char kSessionVersion[] = "18446462598732840960"; +const char kSessionId[] = "18446744069414584320"; +const char kSessionVersion[] = "18446462598732840960"; // ICE options. -static const char kIceOption1[] = "iceoption1"; -static const char kIceOption2[] = "iceoption2"; -static const char kIceOption3[] = "iceoption3"; +const char kIceOption1[] = "iceoption1"; +const char kIceOption2[] = "iceoption2"; +const char kIceOption3[] = "iceoption3"; // ICE ufrags/passwords. -static const char kUfragVoice[] = "ufrag_voice"; -static const char kPwdVoice[] = "pwd_voice"; -static const char kUfragVideo[] = "ufrag_video"; -static const char kPwdVideo[] = "pwd_video"; -static const char kUfragData[] = "ufrag_data"; -static const char kPwdData[] = "pwd_data"; +const char kUfragVoice[] = "ufrag_voice"; +const char kPwdVoice[] = "pwd_voice"; +const char kUfragVideo[] = "ufrag_video"; +const char kPwdVideo[] = "pwd_video"; +const char kUfragData[] = "ufrag_data"; +const char kPwdData[] = "pwd_data"; // Extra ufrags/passwords for extra unified plan m= sections. -static const char kUfragVoice2[] = "ufrag_voice_2"; -static const char kPwdVoice2[] = "pwd_voice_2"; -static const char kUfragVoice3[] = "ufrag_voice_3"; -static const char kPwdVoice3[] = "pwd_voice_3"; -static const char kUfragVideo2[] = "ufrag_video_2"; -static const char kPwdVideo2[] = "pwd_video_2"; -static const char kUfragVideo3[] = "ufrag_video_3"; -static const char kPwdVideo3[] = "pwd_video_3"; +const char kUfragVoice2[] = "ufrag_voice_2"; +const char kPwdVoice2[] = "pwd_voice_2"; +const char kUfragVoice3[] = "ufrag_voice_3"; +const char kPwdVoice3[] = "pwd_voice_3"; +const char kUfragVideo2[] = "ufrag_video_2"; +const char kPwdVideo2[] = "pwd_video_2"; +const char kUfragVideo3[] = "ufrag_video_3"; +const char kPwdVideo3[] = "pwd_video_3"; // Content name -static const char kAudioContentName[] = "audio_content_name"; -static const char kVideoContentName[] = "video_content_name"; -static const char kDataContentName[] = "data_content_name"; +const char kAudioContentName[] = "audio_content_name"; +const char kVideoContentName[] = "video_content_name"; +const char kDataContentName[] = "data_content_name"; // Extra content names for extra unified plan m= sections. -static const char kAudioContentName2[] = "audio_content_name_2"; -static const char kAudioContentName3[] = "audio_content_name_3"; -static const char kVideoContentName2[] = "video_content_name_2"; -static const char kVideoContentName3[] = "video_content_name_3"; +const char kAudioContentName2[] = "audio_content_name_2"; +const char kAudioContentName3[] = "audio_content_name_3"; +const char kVideoContentName2[] = "video_content_name_2"; +const char kVideoContentName3[] = "video_content_name_3"; // MediaStream 1 -static const char kStreamId1[] = "local_stream_1"; -static const char kStream1Cname[] = "stream_1_cname"; -static const char kAudioTrackId1[] = "audio_track_id_1"; -static const uint32_t kAudioTrack1Ssrc = 1; -static const char kVideoTrackId1[] = "video_track_id_1"; -static const uint32_t kVideoTrack1Ssrc1 = 2; -static const uint32_t kVideoTrack1Ssrc2 = 3; +const char kStreamId1[] = "local_stream_1"; +const char kStream1Cname[] = "stream_1_cname"; +const char kAudioTrackId1[] = "audio_track_id_1"; +const uint32_t kAudioTrack1Ssrc = 1; +const char kVideoTrackId1[] = "video_track_id_1"; +const uint32_t kVideoTrack1Ssrc1 = 2; +const uint32_t kVideoTrack1Ssrc2 = 3; // MediaStream 2 -static const char kStreamId2[] = "local_stream_2"; -static const char kStream2Cname[] = "stream_2_cname"; -static const char kAudioTrackId2[] = "audio_track_id_2"; -static const uint32_t kAudioTrack2Ssrc = 4; -static const char kVideoTrackId2[] = "video_track_id_2"; -static const uint32_t kVideoTrack2Ssrc = 5; -static const char kVideoTrackId3[] = "video_track_id_3"; -static const uint32_t kVideoTrack3Ssrc = 6; -static const char kAudioTrackId3[] = "audio_track_id_3"; -static const uint32_t kAudioTrack3Ssrc = 7; +const char kStreamId2[] = "local_stream_2"; +const char kStream2Cname[] = "stream_2_cname"; +const char kAudioTrackId2[] = "audio_track_id_2"; +const uint32_t kAudioTrack2Ssrc = 4; +const char kVideoTrackId2[] = "video_track_id_2"; +const uint32_t kVideoTrack2Ssrc = 5; +const char kVideoTrackId3[] = "video_track_id_3"; +const uint32_t kVideoTrack3Ssrc = 6; +const char kAudioTrackId3[] = "audio_track_id_3"; +const uint32_t kAudioTrack3Ssrc = 7; // Candidate -static const char kDummyMid[] = "dummy_mid"; -static const int kDummyIndex = 123; +const char kDummyMid[] = "dummy_mid"; +const int kDummyIndex = 123; // Misc -static SdpType kDummyType = SdpType::kOffer; +SdpType kDummyType = SdpType::kOffer; // Helper functions -static bool SdpDeserialize(const std::string& message, - JsepSessionDescription* jdesc) { +bool SdpDeserialize(const std::string& message, JsepSessionDescription* jdesc) { return SdpDeserialize(message, jdesc, nullptr); } -static bool SdpDeserializeCandidate(const std::string& message, - JsepIceCandidate* candidate) { - return SdpDeserializeCandidate(message, candidate, nullptr); -} - // Add some extra `newlines` to the `message` after `line`. -static void InjectAfter(const std::string& line, - const std::string& newlines, - std::string* message) { +void InjectAfter(const std::string& line, + const std::string& newlines, + std::string* message) { absl::StrReplaceAll({{line, line + newlines}}, message); } -static void Replace(const std::string& line, - const std::string& newlines, - std::string* message) { +void Replace(const std::string& line, + const std::string& newlines, + std::string* message) { absl::StrReplaceAll({{line, newlines}}, message); } // Expect a parse failure on the line containing `bad_part` when attempting to // parse `bad_sdp`. -static void ExpectParseFailure(const std::string& bad_sdp, - const std::string& bad_part) { +void ExpectParseFailure(const std::string& bad_sdp, + const std::string& bad_part) { JsepSessionDescription desc(kDummyType); SdpParseError error; bool ret = SdpDeserialize(bad_sdp, &desc, &error); @@ -870,23 +863,22 @@ static void ExpectParseFailure(const std::string& bad_sdp, } // Expect fail to parse kSdpFullString if replace `good_part` with `bad_part`. -static void ExpectParseFailure(const char* good_part, const char* bad_part) { +void ExpectParseFailure(const char* good_part, const char* bad_part) { std::string bad_sdp = kSdpFullString; Replace(good_part, bad_part, &bad_sdp); ExpectParseFailure(bad_sdp, bad_part); } // Expect fail to parse kSdpFullString if add `newlines` after `injectpoint`. -static void ExpectParseFailureWithNewLines(const std::string& injectpoint, - const std::string& newlines, - const std::string& bad_part) { +void ExpectParseFailureWithNewLines(const std::string& injectpoint, + const std::string& newlines, + const std::string& bad_part) { std::string bad_sdp = kSdpFullString; InjectAfter(injectpoint, newlines, &bad_sdp); ExpectParseFailure(bad_sdp, bad_part); } -static void ReplaceDirection(RtpTransceiverDirection direction, - std::string* message) { +void ReplaceDirection(RtpTransceiverDirection direction, std::string* message) { std::string new_direction; switch (direction) { case RtpTransceiverDirection::kInactive: @@ -910,9 +902,9 @@ static void ReplaceDirection(RtpTransceiverDirection direction, Replace("a=sendrecv", new_direction, message); } -static void ReplaceRejected(bool audio_rejected, - bool video_rejected, - std::string* message) { +void ReplaceRejected(bool audio_rejected, + bool video_rejected, + std::string* message) { if (audio_rejected) { Replace("m=audio 9", "m=audio 0", message); Replace(kAttributeIceUfragVoice, "", message); @@ -925,13 +917,19 @@ static void ReplaceRejected(bool audio_rejected, } } -static TransportDescription MakeTransportDescription(std::string ufrag, - std::string pwd) { +TransportDescription MakeTransportDescription(std::string ufrag, + std::string pwd) { SSLFingerprint fingerprint(DIGEST_SHA_1, kIdentityDigest); return TransportDescription(std::vector(), ufrag, pwd, ICEMODE_FULL, CONNECTIONROLE_NONE, &fingerprint); } +std::unique_ptr NewCandidate(absl::string_view sdp, + absl::string_view mid = kDummyMid, + int index = kDummyIndex) { + return IceCandidate::Create(mid, index, sdp); +} + // WebRtcSdpTest class WebRtcSdpTest : public ::testing::Test { @@ -1057,7 +1055,7 @@ class WebRtcSdpTest : public ::testing::Test { candidates_.push_back(candidate12); jcandidate_.reset( - new JsepIceCandidate(std::string("audio_content_name"), 0, candidate1)); + new IceCandidate(std::string("audio_content_name"), 0, candidate1)); // Set up JsepSessionDescription. jdesc_.Initialize(desc_.Clone(), kSessionId, kSessionVersion); @@ -1069,7 +1067,7 @@ class WebRtcSdpTest : public ::testing::Test { bool is_video = (i > 5); mline_id = is_video ? "video_content_name" : "audio_content_name"; mline_index = is_video ? 1 : 0; - JsepIceCandidate jice(mline_id, mline_index, candidates_.at(i)); + IceCandidate jice(mline_id, mline_index, candidates_.at(i)); jdesc_.AddCandidate(&jice); } } @@ -1496,8 +1494,8 @@ class WebRtcSdpTest : public ::testing::Test { return false; } for (size_t j = 0; j < cc1->count(); ++j) { - const IceCandidateInterface* c1 = cc1->at(j); - const IceCandidateInterface* c2 = cc2->at(j); + const IceCandidate* c1 = cc1->at(j); + const IceCandidate* c2 = cc2->at(j); EXPECT_EQ(c1->sdp_mid(), c2->sdp_mid()); EXPECT_EQ(c1->sdp_mline_index(), c2->sdp_mline_index()); EXPECT_TRUE(c1->candidate().IsEquivalent(c2->candidate())); @@ -1949,7 +1947,7 @@ class WebRtcSdpTest : public ::testing::Test { VideoContentDescription* video_desc_; SctpDataContentDescription* sctp_desc_; std::vector candidates_; - std::unique_ptr jcandidate_; + std::unique_ptr jcandidate_; JsepSessionDescription jdesc_; }; @@ -2175,20 +2173,20 @@ TEST_F(WebRtcSdpTest, SerializeCandidates) { Candidate candidate_with_ufrag(candidates_.front()); candidate_with_ufrag.set_username("ABC"); - jcandidate_.reset(new JsepIceCandidate(std::string("audio_content_name"), 0, - candidate_with_ufrag)); + jcandidate_.reset(new IceCandidate(std::string("audio_content_name"), 0, + candidate_with_ufrag)); message = SdpSerializeCandidate(*jcandidate_); EXPECT_EQ(std::string(kRawCandidate) + " ufrag ABC", message); Candidate candidate_with_network_info(candidates_.front()); candidate_with_network_info.set_network_id(1); - jcandidate_.reset(new JsepIceCandidate(std::string("audio"), 0, - candidate_with_network_info)); + jcandidate_.reset( + new IceCandidate(std::string("audio"), 0, candidate_with_network_info)); message = SdpSerializeCandidate(*jcandidate_); EXPECT_EQ(std::string(kRawCandidate) + " network-id 1", message); candidate_with_network_info.set_network_cost(999); - jcandidate_.reset(new JsepIceCandidate(std::string("audio"), 0, - candidate_with_network_info)); + jcandidate_.reset( + new IceCandidate(std::string("audio"), 0, candidate_with_network_info)); message = SdpSerializeCandidate(*jcandidate_); EXPECT_EQ(std::string(kRawCandidate) + " network-id 1 network-cost 999", message); @@ -2199,7 +2197,7 @@ TEST_F(WebRtcSdpTest, SerializeHostnameCandidate) { Candidate candidate(ICE_CANDIDATE_COMPONENT_RTP, "udp", address, kCandidatePriority, "", "", IceCandidateType::kHost, kCandidateGeneration, kCandidateFoundation1); - JsepIceCandidate jcandidate(std::string("audio_content_name"), 0, candidate); + IceCandidate jcandidate(std::string("audio_content_name"), 0, candidate); std::string message = SdpSerializeCandidate(jcandidate); EXPECT_EQ(std::string(kRawHostnameCandidate), message); } @@ -2210,8 +2208,8 @@ TEST_F(WebRtcSdpTest, SerializeTcpCandidates) { "", IceCandidateType::kHost, kCandidateGeneration, kCandidateFoundation1); candidate.set_tcptype(TCPTYPE_ACTIVE_STR); - std::unique_ptr jcandidate( - new JsepIceCandidate(std::string("audio_content_name"), 0, candidate)); + std::unique_ptr jcandidate( + new IceCandidate(std::string("audio_content_name"), 0, candidate)); std::string message = SdpSerializeCandidate(*jcandidate); EXPECT_EQ(std::string(kSdpTcpActiveCandidate), message); @@ -2226,20 +2224,19 @@ TEST_F(WebRtcSdpTest, SerializeTcpCandidates) { TEST_F(WebRtcSdpTest, ParseTcpCandidateWithoutTcptype) { std::string missing_tcptype = "candidate:a0+B/1 1 tcp 2130706432 192.168.1.5 9999 typ host"; - JsepIceCandidate jcandidate(kDummyMid, kDummyIndex); - EXPECT_TRUE(SdpDeserializeCandidate(missing_tcptype, &jcandidate)); - - EXPECT_EQ(std::string(TCPTYPE_PASSIVE_STR), jcandidate.candidate().tcptype()); + std::unique_ptr jcandidate = NewCandidate(missing_tcptype); + ASSERT_TRUE(jcandidate.get()); + EXPECT_EQ(std::string(TCPTYPE_PASSIVE_STR), + jcandidate->candidate().tcptype()); } TEST_F(WebRtcSdpTest, ParseSslTcpCandidate) { std::string ssltcp = "candidate:a0+B/1 1 ssltcp 2130706432 192.168.1.5 9999 typ host tcptype " "passive"; - JsepIceCandidate jcandidate(kDummyMid, kDummyIndex); - EXPECT_TRUE(SdpDeserializeCandidate(ssltcp, &jcandidate)); - - EXPECT_EQ(std::string("ssltcp"), jcandidate.candidate().protocol()); + std::unique_ptr jcandidate = NewCandidate(ssltcp); + ASSERT_TRUE(jcandidate.get()); + EXPECT_EQ(std::string("ssltcp"), jcandidate->candidate().protocol()); } TEST_F(WebRtcSdpTest, SerializeSessionDescriptionWithH264) { @@ -2570,56 +2567,57 @@ TEST_F(WebRtcSdpTest, DeserializeMediaContentDescriptionWithExtmapAllowMixed) { } TEST_F(WebRtcSdpTest, DeserializeCandidate) { - JsepIceCandidate jcandidate(kDummyMid, kDummyIndex); - std::string sdp = kSdpOneCandidate; - EXPECT_TRUE(SdpDeserializeCandidate(sdp, &jcandidate)); - EXPECT_EQ(kDummyMid, jcandidate.sdp_mid()); - EXPECT_EQ(kDummyIndex, jcandidate.sdp_mline_index()); - EXPECT_TRUE(jcandidate.candidate().IsEquivalent(jcandidate_->candidate())); - EXPECT_EQ(0, jcandidate.candidate().network_cost()); + std::unique_ptr jcandidate = NewCandidate(sdp); + ASSERT_TRUE(jcandidate.get()); + EXPECT_EQ(kDummyMid, jcandidate->sdp_mid()); + EXPECT_EQ(kDummyIndex, jcandidate->sdp_mline_index()); + EXPECT_TRUE(jcandidate->candidate().IsEquivalent(jcandidate_->candidate())); + EXPECT_EQ(0, jcandidate->candidate().network_cost()); // Candidate line without generation extension. sdp = kSdpOneCandidate; Replace(" generation 2", "", &sdp); - EXPECT_TRUE(SdpDeserializeCandidate(sdp, &jcandidate)); - EXPECT_EQ(kDummyMid, jcandidate.sdp_mid()); - EXPECT_EQ(kDummyIndex, jcandidate.sdp_mline_index()); + jcandidate = NewCandidate(sdp); + ASSERT_TRUE(jcandidate.get()); + EXPECT_EQ(kDummyMid, jcandidate->sdp_mid()); + EXPECT_EQ(kDummyIndex, jcandidate->sdp_mline_index()); Candidate expected = jcandidate_->candidate(); expected.set_generation(0); - EXPECT_TRUE(jcandidate.candidate().IsEquivalent(expected)); + EXPECT_TRUE(jcandidate->candidate().IsEquivalent(expected)); // Candidate with network id and/or cost. sdp = kSdpOneCandidate; Replace(" generation 2", " generation 2 network-id 2", &sdp); - EXPECT_TRUE(SdpDeserializeCandidate(sdp, &jcandidate)); - EXPECT_EQ(kDummyMid, jcandidate.sdp_mid()); - EXPECT_EQ(kDummyIndex, jcandidate.sdp_mline_index()); + jcandidate = NewCandidate(sdp); + ASSERT_TRUE(jcandidate.get()); + EXPECT_EQ(kDummyMid, jcandidate->sdp_mid()); + EXPECT_EQ(kDummyIndex, jcandidate->sdp_mline_index()); expected = jcandidate_->candidate(); expected.set_network_id(2); - EXPECT_TRUE(jcandidate.candidate().IsEquivalent(expected)); - EXPECT_EQ(0, jcandidate.candidate().network_cost()); + EXPECT_TRUE(jcandidate->candidate().IsEquivalent(expected)); + EXPECT_EQ(0, jcandidate->candidate().network_cost()); // Add network cost Replace(" network-id 2", " network-id 2 network-cost 9", &sdp); - EXPECT_TRUE(SdpDeserializeCandidate(sdp, &jcandidate)); - EXPECT_TRUE(jcandidate.candidate().IsEquivalent(expected)); - EXPECT_EQ(9, jcandidate.candidate().network_cost()); + jcandidate = NewCandidate(sdp); + ASSERT_TRUE(jcandidate.get()); + EXPECT_TRUE(jcandidate->candidate().IsEquivalent(expected)); + EXPECT_EQ(9, jcandidate->candidate().network_cost()); sdp = kSdpTcpActiveCandidate; - EXPECT_TRUE(SdpDeserializeCandidate(sdp, &jcandidate)); + jcandidate = NewCandidate(sdp); + ASSERT_TRUE(jcandidate.get()); // Make a Candidate equivalent to kSdpTcpCandidate string. Candidate candidate(ICE_CANDIDATE_COMPONENT_RTP, "tcp", SocketAddress("192.168.1.5", 9), kCandidatePriority, "", "", IceCandidateType::kHost, kCandidateGeneration, kCandidateFoundation1); - std::unique_ptr jcandidate_template( - new JsepIceCandidate(std::string("audio_content_name"), 0, candidate)); + std::unique_ptr jcandidate_template( + new IceCandidate(std::string("audio_content_name"), 0, candidate)); EXPECT_TRUE( - jcandidate.candidate().IsEquivalent(jcandidate_template->candidate())); - sdp = kSdpTcpPassiveCandidate; - EXPECT_TRUE(SdpDeserializeCandidate(sdp, &jcandidate)); - sdp = kSdpTcpSOCandidate; - EXPECT_TRUE(SdpDeserializeCandidate(sdp, &jcandidate)); + jcandidate->candidate().IsEquivalent(jcandidate_template->candidate())); + ASSERT_TRUE(NewCandidate(kSdpTcpPassiveCandidate).get()); + ASSERT_TRUE(NewCandidate(kSdpTcpSOCandidate).get()); } // This test verifies the deserialization of candidate-attribute @@ -2627,56 +2625,55 @@ TEST_F(WebRtcSdpTest, DeserializeCandidate) { // candidate:. This format will be used when candidates // are trickled. TEST_F(WebRtcSdpTest, DeserializeRawCandidateAttribute) { - JsepIceCandidate jcandidate(kDummyMid, kDummyIndex); - std::string candidate_attribute = kRawCandidate; - EXPECT_TRUE(SdpDeserializeCandidate(candidate_attribute, &jcandidate)); - EXPECT_EQ(kDummyMid, jcandidate.sdp_mid()); - EXPECT_EQ(kDummyIndex, jcandidate.sdp_mline_index()); - EXPECT_TRUE(jcandidate.candidate().IsEquivalent(jcandidate_->candidate())); - EXPECT_EQ(2u, jcandidate.candidate().generation()); + auto jcandidate = NewCandidate(candidate_attribute); + ASSERT_TRUE(jcandidate.get()); + EXPECT_EQ(kDummyMid, jcandidate->sdp_mid()); + EXPECT_EQ(kDummyIndex, jcandidate->sdp_mline_index()); + EXPECT_TRUE(jcandidate->candidate().IsEquivalent(jcandidate_->candidate())); + EXPECT_EQ(2u, jcandidate->candidate().generation()); // Candidate line without generation extension. candidate_attribute = kRawCandidate; Replace(" generation 2", "", &candidate_attribute); - EXPECT_TRUE(SdpDeserializeCandidate(candidate_attribute, &jcandidate)); - EXPECT_EQ(kDummyMid, jcandidate.sdp_mid()); - EXPECT_EQ(kDummyIndex, jcandidate.sdp_mline_index()); + jcandidate = NewCandidate(candidate_attribute); + ASSERT_TRUE(jcandidate.get()); + EXPECT_EQ(kDummyMid, jcandidate->sdp_mid()); + EXPECT_EQ(kDummyIndex, jcandidate->sdp_mline_index()); Candidate expected = jcandidate_->candidate(); expected.set_generation(0); - EXPECT_TRUE(jcandidate.candidate().IsEquivalent(expected)); + EXPECT_TRUE(jcandidate->candidate().IsEquivalent(expected)); // Candidate line without candidate: candidate_attribute = kRawCandidate; Replace("candidate:", "", &candidate_attribute); - EXPECT_FALSE(SdpDeserializeCandidate(candidate_attribute, &jcandidate)); + ASSERT_FALSE(NewCandidate(candidate_attribute).get()); // Candidate line with IPV6 address. - EXPECT_TRUE(SdpDeserializeCandidate(kRawIPV6Candidate, &jcandidate)); + ASSERT_TRUE(NewCandidate(kRawIPV6Candidate).get()); // Candidate line with hostname address. - EXPECT_TRUE(SdpDeserializeCandidate(kRawHostnameCandidate, &jcandidate)); + ASSERT_TRUE(NewCandidate(kRawHostnameCandidate).get()); } // This test verifies that the deserialization of an invalid candidate string // fails. TEST_F(WebRtcSdpTest, DeserializeInvalidCandidiate) { - JsepIceCandidate jcandidate(kDummyMid, kDummyIndex); - std::string candidate_attribute = kRawCandidate; + ASSERT_TRUE(NewCandidate(candidate_attribute).get()); + candidate_attribute.replace(0, 1, "x"); - EXPECT_FALSE(SdpDeserializeCandidate(candidate_attribute, &jcandidate)); + EXPECT_FALSE(NewCandidate(candidate_attribute).get()); candidate_attribute = kSdpOneCandidate; candidate_attribute.replace(0, 1, "x"); - EXPECT_FALSE(SdpDeserializeCandidate(candidate_attribute, &jcandidate)); + EXPECT_FALSE(NewCandidate(candidate_attribute).get()); candidate_attribute = kRawCandidate; candidate_attribute.append("\r\n"); candidate_attribute.append(kRawCandidate); - EXPECT_FALSE(SdpDeserializeCandidate(candidate_attribute, &jcandidate)); - - EXPECT_FALSE(SdpDeserializeCandidate(kSdpTcpInvalidCandidate, &jcandidate)); + EXPECT_FALSE(NewCandidate(candidate_attribute).get()); + EXPECT_FALSE(NewCandidate(kSdpTcpInvalidCandidate).get()); } TEST_F(WebRtcSdpTest, DeserializeSdpWithSctpDataChannels) { @@ -2949,28 +2946,27 @@ TEST_F(WebRtcSdpTest, DeserializeSessionDescriptionWithoutEndLineBreak) { } TEST_F(WebRtcSdpTest, DeserializeCandidateWithDifferentTransport) { - JsepIceCandidate jcandidate(kDummyMid, kDummyIndex); std::string new_sdp = kSdpOneCandidate; Replace("udp", "unsupported_transport", &new_sdp); - EXPECT_FALSE(SdpDeserializeCandidate(new_sdp, &jcandidate)); + EXPECT_FALSE(NewCandidate(new_sdp).get()); new_sdp = kSdpOneCandidate; Replace("udp", "uDP", &new_sdp); - EXPECT_TRUE(SdpDeserializeCandidate(new_sdp, &jcandidate)); - EXPECT_EQ(kDummyMid, jcandidate.sdp_mid()); - EXPECT_EQ(kDummyIndex, jcandidate.sdp_mline_index()); - EXPECT_TRUE(jcandidate.candidate().IsEquivalent(jcandidate_->candidate())); + auto jcandidate = NewCandidate(new_sdp); + ASSERT_TRUE(jcandidate.get()); + EXPECT_EQ(kDummyMid, jcandidate->sdp_mid()); + EXPECT_EQ(kDummyIndex, jcandidate->sdp_mline_index()); + EXPECT_TRUE(jcandidate->candidate().IsEquivalent(jcandidate_->candidate())); } TEST_F(WebRtcSdpTest, DeserializeCandidateWithUfragPwd) { - JsepIceCandidate jcandidate(kDummyMid, kDummyIndex); - EXPECT_TRUE( - SdpDeserializeCandidate(kSdpOneCandidateWithUfragPwd, &jcandidate)); - EXPECT_EQ(kDummyMid, jcandidate.sdp_mid()); - EXPECT_EQ(kDummyIndex, jcandidate.sdp_mline_index()); + auto jcandidate = NewCandidate(kSdpOneCandidateWithUfragPwd); + ASSERT_TRUE(jcandidate.get()); + EXPECT_EQ(kDummyMid, jcandidate->sdp_mid()); + EXPECT_EQ(kDummyIndex, jcandidate->sdp_mline_index()); Candidate ref_candidate = jcandidate_->candidate(); ref_candidate.set_username("user_rtp"); ref_candidate.set_password("password_rtp"); - EXPECT_TRUE(jcandidate.candidate().IsEquivalent(ref_candidate)); + EXPECT_TRUE(jcandidate->candidate().IsEquivalent(ref_candidate)); } TEST_F(WebRtcSdpTest, DeserializeSdpWithConferenceFlag) { diff --git a/pc/webrtc_session_description_factory.cc b/pc/webrtc_session_description_factory.cc index 5c90efd063..2c59f9e5f0 100644 --- a/pc/webrtc_session_description_factory.cc +++ b/pc/webrtc_session_description_factory.cc @@ -46,16 +46,15 @@ namespace webrtc { namespace { -static const char kFailedDueToIdentityFailed[] = +const char kFailedDueToIdentityFailed[] = " failed because DTLS identity request failed"; -static const char kFailedDueToSessionShutdown[] = +const char kFailedDueToSessionShutdown[] = " failed because the session was shut down"; -static const uint64_t kInitSessionVersion = 2; +const uint64_t kInitSessionVersion = 2; // Check that each sender has a unique ID. -static bool ValidMediaSessionOptions( - const MediaSessionOptions& session_options) { +bool ValidMediaSessionOptions(const MediaSessionOptions& session_options) { std::vector sorted_senders; for (const MediaDescriptionOptions& media_description_options : session_options.media_description_options) { @@ -98,7 +97,7 @@ void WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription( return; } for (size_t n = 0; n < source_candidates->count(); ++n) { - const IceCandidateInterface* new_candidate = source_candidates->at(n); + const IceCandidate* new_candidate = source_candidates->at(n); if (!dest_candidates->HasCandidate(new_candidate)) { dest_desc->AddCandidate(source_candidates->at(n)); } diff --git a/rtc_base/BUILD.gn b/rtc_base/BUILD.gn index 1211f0c856..216b91fcfd 100644 --- a/rtc_base/BUILD.gn +++ b/rtc_base/BUILD.gn @@ -115,11 +115,8 @@ rtc_source_set("swap_queue") { } rtc_source_set("macromagic") { - sources = [ - "arraysize.h", - "thread_annotations.h", - ] - deps = [ "system:arch" ] + sources = [ "thread_annotations.h" ] + deps = [] } rtc_library("bit_buffer") { @@ -214,6 +211,7 @@ rtc_library("event_tracer") { ":timeutils", "..:tracing", "../api:sequence_checker", + "../api/units:time_delta", "synchronization:mutex", "system:rtc_export", "//third_party/abseil-cpp/absl/strings:string_view", @@ -296,6 +294,7 @@ rtc_library("rate_statistics") { deps = [ ":checks", ":logging", + ":safe_compare", ":safe_conversions", "system:rtc_export", ] @@ -356,10 +355,7 @@ rtc_library("platform_thread_types") { "platform_thread_types.cc", "platform_thread_types.h", ] - deps = [ - ":checks", - ":macromagic", - ] + deps = [ ":checks" ] } rtc_source_set("refcount") { @@ -370,7 +366,6 @@ rtc_source_set("refcount") { "ref_counter.h", ] deps = [ - ":macromagic", "../api:ref_count", "../api:scoped_refptr", ] @@ -397,7 +392,6 @@ rtc_library("platform_thread") { ] deps = [ ":checks", - ":macromagic", ":platform_thread_types", ":rtc_event", ":timeutils", @@ -607,7 +601,6 @@ rtc_library("stringutils") { ] deps = [ ":checks", - ":macromagic", ":safe_minmax", "../api:array_view", "//third_party/abseil-cpp/absl/base:core_headers", @@ -669,7 +662,6 @@ if (is_win) { deps = [ ":checks", ":logging", - ":macromagic", ":platform_thread", ":rtc_event", ":safe_conversions", @@ -698,6 +690,7 @@ rtc_library("rtc_task_queue_stdlib") { ":rtc_event", ":safe_conversions", ":timeutils", + "../api:location", "../api/task_queue", "../api/units:time_delta", "synchronization:mutex", @@ -717,11 +710,13 @@ if (rtc_include_tests) { ":rtc_event", ":rtc_task_queue_stdlib", ":threading", + "../api:field_trials_view", "../api/task_queue", "../api/task_queue:task_queue_test", "../api/units:time_delta", "../test:test_main", "../test:test_support", + "//third_party/abseil-cpp/absl/strings:string_view", ] } } @@ -799,6 +794,7 @@ rtc_library("rtc_json") { ] deps = [ ":stringutils", + "//third_party/abseil-cpp/absl/strings", "//third_party/abseil-cpp/absl/strings:string_view", ] all_dependent_configs = [ "//third_party/jsoncpp:jsoncpp_config" ] @@ -859,15 +855,26 @@ rtc_library("async_dns_resolver") { "async_dns_resolver.h", ] deps = [ + ":checks", + ":ip_address", ":logging", ":macromagic", + ":net_helpers", ":platform_thread", ":refcount", + ":socket_address", "../api:async_dns_resolver", "../api:make_ref_counted", + "../api:refcountedbase", + "../api:scoped_refptr", "../api:sequence_checker", + "../api/task_queue", "../api/task_queue:pending_task_safety_flag", + "synchronization:mutex", + "system:no_unique_address", "system:rtc_export", + "//third_party/abseil-cpp/absl/functional:any_invocable", + "//third_party/abseil-cpp/absl/strings:string_view", ] } @@ -978,6 +985,7 @@ rtc_library("threading") { ":ip_address", ":logging", ":macromagic", + ":net_helpers", ":network_constants", ":null_socket_server", ":platform_thread", @@ -1049,7 +1057,6 @@ rtc_library("socket") { ":buffer", ":checks", ":ip_address", - ":macromagic", ":net_helpers", ":socket_address", "../api/units:timestamp", @@ -1095,7 +1102,6 @@ if (is_win) { deps = [ ":byte_order", ":checks", - ":macromagic", ":stringutils", ] @@ -1115,6 +1121,7 @@ rtc_library("ifaddrs_converter") { ":checks", ":ip_address", ":logging", + ":net_helpers", ] if (is_android) { @@ -1276,6 +1283,8 @@ rtc_library("async_tcp_socket") { ":socket_address", ":timeutils", "../api:array_view", + "../api/units:timestamp", + "network:received_packet", "network:sent_packet", ] } @@ -1337,6 +1346,7 @@ if (rtc_include_tests) { deps = [ ":async_packet_socket", ":gunit_helpers", + ":socket", ":socket_address", "../test:test_support", "network:received_packet", @@ -1405,12 +1415,15 @@ rtc_library("unique_id_generator") { "unique_id_generator.h", ] deps = [ + ":checks", ":crypto_random", + ":macromagic", ":stringutils", "../api:array_view", "../api:sequence_checker", "synchronization:mutex", "system:no_unique_address", + "//third_party/abseil-cpp/absl/strings", "//third_party/abseil-cpp/absl/strings:string_view", ] } @@ -1420,10 +1433,7 @@ rtc_library("crc32") { "crc32.cc", "crc32.h", ] - deps = [ - ":macromagic", - "//third_party/abseil-cpp/absl/strings:string_view", - ] + deps = [ "//third_party/abseil-cpp/absl/strings:string_view" ] } rtc_library("stream") { @@ -1541,7 +1551,6 @@ rtc_library("ssl") { ":copy_on_write_buffer", ":digest", ":logging", - ":macromagic", ":safe_conversions", ":ssl_header", ":stringutils", @@ -1679,6 +1688,7 @@ rtc_library("testclient") { "../api/units:timestamp", "network:received_packet", "synchronization:mutex", + "third_party/sigslot", ] } @@ -1689,6 +1699,7 @@ rtc_library("callback_list_unittests") { deps = [ ":callback_list", ":gunit_helpers", + ":untyped_function", "../api:function_view", "../test:test_support", ] @@ -1760,7 +1771,6 @@ rtc_library("rtc_base_tests_utils") { "../api/task_queue:pending_task_safety_flag", "../api/units:time_delta", "../api/units:timestamp", - "../test:scoped_key_value_config", "memory:always_valid_pointer", "memory:fifo_buffer", "network:received_packet", @@ -1803,9 +1813,12 @@ rtc_library("task_queue_for_test") { ":checks", ":rtc_event", "../api:function_view", + "../api:location", "../api/task_queue", "../api/task_queue:default_task_queue_factory", + "../api/units:time_delta", "//third_party/abseil-cpp/absl/cleanup", + "//third_party/abseil-cpp/absl/functional:any_invocable", "//third_party/abseil-cpp/absl/strings:string_view", ] } @@ -1892,7 +1905,12 @@ rtc_library("cpu_info") { deps = [ ":checks", ":logging", + "system:arch", + "system:unused", ] + if (is_android) { + deps += [ "//third_party/cpu_features:ndk_compat" ] + } } if (rtc_include_tests) { @@ -1968,7 +1986,6 @@ if (rtc_include_tests) { ":gunit_helpers", ":ip_address", ":logging", - ":macromagic", ":net_helpers", ":net_test_helpers", ":null_socket_server", @@ -1986,7 +2003,6 @@ if (rtc_include_tests) { "../api/units:time_delta", "../api/units:timestamp", "../system_wrappers", - "../test:field_trial", "../test:fileutils", "../test:test_main", "../test:test_support", @@ -2272,7 +2288,9 @@ if (rtc_include_tests) { ":timeutils", ":unique_id_generator", "../api:array_view", + "../api:field_trials", "../api:field_trials_view", + "../api:location", "../api:make_ref_counted", "../api:rtc_error_matchers", "../api:scoped_refptr", @@ -2284,11 +2302,11 @@ if (rtc_include_tests) { "../api/task_queue:pending_task_safety_flag", "../api/task_queue:task_queue_test", "../api/units:time_delta", + "../api/units:timestamp", "../system_wrappers", - "../test:field_trial", + "../test:create_test_field_trials", "../test:fileutils", "../test:rtc_expect_death", - "../test:scoped_key_value_config", "../test:test_main", "../test:test_support", "../test:wait_until", diff --git a/rtc_base/arraysize.h b/rtc_base/arraysize.h deleted file mode 100644 index bf8e6d8810..0000000000 --- a/rtc_base/arraysize.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2015 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 RTC_BASE_ARRAYSIZE_H_ -#define RTC_BASE_ARRAYSIZE_H_ - -#include - -// This file defines the arraysize() macro and is derived from Chromium's -// base/macros.h. - -// The arraysize(arr) macro returns the # of elements in an array arr. -// The expression is a compile-time constant, and therefore can be -// used in defining new arrays, for example. If you use arraysize on -// a pointer by mistake, you will get a compile-time error. - -// This template function declaration is used in defining arraysize. -// Note that the function doesn't need an implementation, as we only -// use its type. -template -char (&ArraySizeHelper(T (&array)[N]))[N]; - -#define arraysize(array) (sizeof(ArraySizeHelper(array))) - -#endif // RTC_BASE_ARRAYSIZE_H_ diff --git a/rtc_base/async_dns_resolver.cc b/rtc_base/async_dns_resolver.cc index 9c9610d47d..a3d3f1e76a 100644 --- a/rtc_base/async_dns_resolver.cc +++ b/rtc_base/async_dns_resolver.cc @@ -10,14 +10,26 @@ #include "rtc_base/async_dns_resolver.h" -#include #include #include #include +#include "absl/functional/any_invocable.h" +#include "absl/strings/string_view.h" +#include "api/async_dns_resolver.h" #include "api/make_ref_counted.h" -#include "rtc_base/logging.h" +#include "api/ref_counted_base.h" +#include "api/scoped_refptr.h" +#include "api/sequence_checker.h" +#include "api/task_queue/pending_task_safety_flag.h" +#include "api/task_queue/task_queue_base.h" +#include "rtc_base/checks.h" +#include "rtc_base/ip_address.h" +#include "rtc_base/net_helpers.h" #include "rtc_base/platform_thread.h" +#include "rtc_base/socket_address.h" +#include "rtc_base/synchronization/mutex.h" +#include "rtc_base/thread_annotations.h" #if defined(WEBRTC_MAC) || defined(WEBRTC_IOS) #include @@ -30,7 +42,7 @@ namespace { #ifdef __native_client__ int ResolveHostname(absl::string_view hostname, int family, - std::vector* addresses) { + std::vector* addresses) { RTC_DCHECK_NOTREACHED(); RTC_LOG(LS_WARNING) << "ResolveHostname() is not implemented for NaCl"; return -1; diff --git a/rtc_base/async_dns_resolver.h b/rtc_base/async_dns_resolver.h index 674e140892..ec1c8ed069 100644 --- a/rtc_base/async_dns_resolver.h +++ b/rtc_base/async_dns_resolver.h @@ -12,16 +12,20 @@ #include +#include "absl/functional/any_invocable.h" #include "api/async_dns_resolver.h" +#include "api/scoped_refptr.h" #include "api/sequence_checker.h" #include "api/task_queue/pending_task_safety_flag.h" -#include "rtc_base/ref_counted_object.h" +#include "rtc_base/ip_address.h" +#include "rtc_base/socket_address.h" +#include "rtc_base/system/no_unique_address.h" #include "rtc_base/system/rtc_export.h" #include "rtc_base/thread_annotations.h" namespace webrtc { // This file contains a default implementation of -// webrtc::AsyncDnsResolverInterface, for use when there is no need for special +// AsyncDnsResolverInterface, for use when there is no need for special // treatment. class AsyncDnsResolverResultImpl : public AsyncDnsResolverResult { @@ -32,7 +36,7 @@ class AsyncDnsResolverResultImpl : public AsyncDnsResolverResult { private: friend class AsyncDnsResolver; - RTC_NO_UNIQUE_ADDRESS webrtc::SequenceChecker sequence_checker_; + RTC_NO_UNIQUE_ADDRESS SequenceChecker sequence_checker_; SocketAddress addr_ RTC_GUARDED_BY(sequence_checker_); std::vector addresses_ RTC_GUARDED_BY(sequence_checker_); int error_ RTC_GUARDED_BY(sequence_checker_); diff --git a/rtc_base/async_dns_resolver_unittest.cc b/rtc_base/async_dns_resolver_unittest.cc index 5c4d65415d..ae03b204b2 100644 --- a/rtc_base/async_dns_resolver_unittest.cc +++ b/rtc_base/async_dns_resolver_unittest.cc @@ -17,6 +17,7 @@ #include "rtc_base/logging.h" #include "rtc_base/net_helpers.h" #include "rtc_base/socket_address.h" +#include "rtc_base/thread.h" #include "test/gmock.h" #include "test/gtest.h" #include "test/run_loop.h" @@ -63,7 +64,7 @@ TEST(AsyncDnsResolver, ResolveAfterDeleteDoesNotReturn) { bool done = false; resolver->Start(address, [&done] { done = true; }); resolver.reset(); // Deletes resolver. - loop.Flush(); // Allows callback to execute + Thread::Current()->SleepMs(1); // Allows callback to execute EXPECT_FALSE(done); // Expect no result. } diff --git a/rtc_base/async_packet_socket.h b/rtc_base/async_packet_socket.h index e06de43d52..b1a20452ed 100644 --- a/rtc_base/async_packet_socket.h +++ b/rtc_base/async_packet_socket.h @@ -61,10 +61,10 @@ struct RTC_EXPORT AsyncSocketPacketOptions { // https://www.rfc-editor.org/rfc/rfc9331.html bool ecn_1 = false; - // When used with RTP packets (for example, webrtc::PacketOptions), the value + // When used with RTP packets (for example, PacketOptions), the value // should be 16 bits. A value of -1 represents "not set". int64_t packet_id = -1; - webrtc::PacketTimeUpdateParams packet_time_params; + PacketTimeUpdateParams packet_time_params; // PacketInfo is passed to SentPacket when signaling this packet is sent. PacketInfo info_signaled_after_sent; // True if this is a batchable packet. Batchable packets are collected at low @@ -127,12 +127,11 @@ class RTC_EXPORT AsyncPacketSocket : public sigslot::has_slots<> { // Register a callback to be called when the socket is closed. void SubscribeCloseEvent( const void* removal_tag, - std::function callback); + std::function callback); void UnsubscribeCloseEvent(const void* removal_tag); void RegisterReceivedPacketCallback( - absl::AnyInvocable + absl::AnyInvocable received_packet_callback); void DeregisterReceivedPacketCallback(); @@ -173,8 +172,7 @@ class RTC_EXPORT AsyncPacketSocket : public sigslot::has_slots<> { private: CallbackList on_close_ RTC_GUARDED_BY(&network_checker_); - absl::AnyInvocable + absl::AnyInvocable received_packet_callback_ RTC_GUARDED_BY(&network_checker_); }; diff --git a/rtc_base/async_packet_socket_unittest.cc b/rtc_base/async_packet_socket_unittest.cc index b37334aa4e..b00f707210 100644 --- a/rtc_base/async_packet_socket_unittest.cc +++ b/rtc_base/async_packet_socket_unittest.cc @@ -10,8 +10,11 @@ #include "rtc_base/async_packet_socket.h" +#include + +#include "rtc_base/network/received_packet.h" +#include "rtc_base/socket.h" #include "rtc_base/socket_address.h" -#include "rtc_base/third_party/sigslot/sigslot.h" #include "test/gmock.h" #include "test/gtest.h" @@ -22,7 +25,7 @@ using ::testing::MockFunction; class MockAsyncPacketSocket : public AsyncPacketSocket { public: - ~MockAsyncPacketSocket() = default; + ~MockAsyncPacketSocket() override = default; MOCK_METHOD(SocketAddress, GetLocalAddress, (), (const, override)); MOCK_METHOD(SocketAddress, GetRemoteAddress, (), (const, override)); diff --git a/rtc_base/async_socket.cc b/rtc_base/async_socket.cc index fe6c0ef2f3..1571811320 100644 --- a/rtc_base/async_socket.cc +++ b/rtc_base/async_socket.cc @@ -10,8 +10,13 @@ #include "rtc_base/async_socket.h" +#include +#include + #include "absl/memory/memory.h" #include "rtc_base/checks.h" +#include "rtc_base/socket.h" +#include "rtc_base/socket_address.h" namespace webrtc { diff --git a/rtc_base/async_tcp_socket.cc b/rtc_base/async_tcp_socket.cc index e07bfc1f20..a13549cdeb 100644 --- a/rtc_base/async_tcp_socket.cc +++ b/rtc_base/async_tcp_socket.cc @@ -17,12 +17,18 @@ #include #include #include +#include #include "api/array_view.h" +#include "api/units/timestamp.h" +#include "rtc_base/async_packet_socket.h" #include "rtc_base/byte_order.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" +#include "rtc_base/network/received_packet.h" #include "rtc_base/network/sent_packet.h" +#include "rtc_base/socket.h" +#include "rtc_base/socket_address.h" #include "rtc_base/time_utils.h" // for TimeMillis #if defined(WEBRTC_POSIX) diff --git a/rtc_base/async_tcp_socket_unittest.cc b/rtc_base/async_tcp_socket_unittest.cc index 149780de9e..f531ed9cc2 100644 --- a/rtc_base/async_tcp_socket_unittest.cc +++ b/rtc_base/async_tcp_socket_unittest.cc @@ -21,7 +21,7 @@ namespace webrtc { class AsyncTCPSocketTest : public ::testing::Test, public sigslot::has_slots<> { public: AsyncTCPSocketTest() - : vss_(new webrtc::VirtualSocketServer()), + : vss_(new VirtualSocketServer()), socket_(vss_->CreateSocket(SOCK_STREAM)), tcp_socket_(new AsyncTCPSocket(socket_, true)), ready_to_send_(false) { @@ -29,9 +29,7 @@ class AsyncTCPSocketTest : public ::testing::Test, public sigslot::has_slots<> { &AsyncTCPSocketTest::OnReadyToSend); } - void OnReadyToSend(webrtc::AsyncPacketSocket* socket) { - ready_to_send_ = true; - } + void OnReadyToSend(AsyncPacketSocket* socket) { ready_to_send_ = true; } protected: std::unique_ptr vss_; diff --git a/rtc_base/bit_buffer.cc b/rtc_base/bit_buffer.cc index e94a3c06eb..2fbcc11f2b 100644 --- a/rtc_base/bit_buffer.cc +++ b/rtc_base/bit_buffer.cc @@ -11,6 +11,8 @@ #include "rtc_base/bit_buffer.h" #include +#include +#include #include #include "absl/numeric/bits.h" diff --git a/rtc_base/bit_buffer.h b/rtc_base/bit_buffer.h index 17084a4063..870ddc883b 100644 --- a/rtc_base/bit_buffer.h +++ b/rtc_base/bit_buffer.h @@ -25,7 +25,7 @@ namespace webrtc { // Byte order is assumed big-endian/network. class BitBufferWriter { public: - static constexpr DataSize kMaxLeb128Length = webrtc::DataSize::Bytes(10); + static constexpr DataSize kMaxLeb128Length = DataSize::Bytes(10); // Constructs a bit buffer for the writable buffer of `bytes`. BitBufferWriter(uint8_t* bytes, size_t byte_count); diff --git a/rtc_base/bit_buffer_unittest.cc b/rtc_base/bit_buffer_unittest.cc index 670275c879..f703be8182 100644 --- a/rtc_base/bit_buffer_unittest.cc +++ b/rtc_base/bit_buffer_unittest.cc @@ -10,12 +10,12 @@ #include "rtc_base/bit_buffer.h" +#include +#include #include #include "api/array_view.h" -#include "rtc_base/arraysize.h" #include "rtc_base/bitstream_reader.h" -#include "rtc_base/byte_buffer.h" #include "test/gmock.h" #include "test/gtest.h" @@ -197,12 +197,12 @@ TEST(BitBufferWriterTest, SymmetricGolomb) { char test_string[] = "my precious"; uint8_t bytes[64] = {0}; BitBufferWriter buffer(bytes, 64); - for (size_t i = 0; i < arraysize(test_string); ++i) { - EXPECT_TRUE(buffer.WriteExponentialGolomb(test_string[i])); + for (char value : test_string) { + EXPECT_TRUE(buffer.WriteExponentialGolomb(value)); } BitstreamReader reader(bytes); - for (size_t i = 0; i < arraysize(test_string); ++i) { - EXPECT_EQ(int64_t{reader.ReadExponentialGolomb()}, int64_t{test_string[i]}); + for (char value : test_string) { + EXPECT_EQ(int64_t{reader.ReadExponentialGolomb()}, int64_t{value}); } EXPECT_TRUE(reader.Ok()); } diff --git a/rtc_base/bitrate_tracker.cc b/rtc_base/bitrate_tracker.cc index 0146d3c564..29efe39bf3 100644 --- a/rtc_base/bitrate_tracker.cc +++ b/rtc_base/bitrate_tracker.cc @@ -10,9 +10,11 @@ #include "rtc_base/bitrate_tracker.h" +#include #include #include "api/units/data_rate.h" +#include "api/units/time_delta.h" #include "api/units/timestamp.h" #include "rtc_base/rate_statistics.h" diff --git a/rtc_base/bitrate_tracker_unittest.cc b/rtc_base/bitrate_tracker_unittest.cc index 61f569d633..ef966bdc8d 100644 --- a/rtc_base/bitrate_tracker_unittest.cc +++ b/rtc_base/bitrate_tracker_unittest.cc @@ -10,11 +10,13 @@ #include "rtc_base/bitrate_tracker.h" +#include #include #include #include #include "api/units/data_rate.h" +#include "api/units/data_size.h" #include "api/units/time_delta.h" #include "api/units/timestamp.h" #include "test/gmock.h" diff --git a/rtc_base/bitstream_reader.cc b/rtc_base/bitstream_reader.cc index 94be1f0d8e..3a5372133f 100644 --- a/rtc_base/bitstream_reader.cc +++ b/rtc_base/bitstream_reader.cc @@ -12,7 +12,8 @@ #include -#include +#include +#include #include "absl/numeric/bits.h" #include "rtc_base/checks.h" diff --git a/rtc_base/bitstream_reader.h b/rtc_base/bitstream_reader.h index 43d7a4c8ed..622534ef70 100644 --- a/rtc_base/bitstream_reader.h +++ b/rtc_base/bitstream_reader.h @@ -13,6 +13,9 @@ #include +#include +#include + #include "absl/base/attributes.h" #include "absl/strings/string_view.h" #include "api/array_view.h" diff --git a/rtc_base/bitstream_reader_unittest.cc b/rtc_base/bitstream_reader_unittest.cc index 334218e383..c85d05452b 100644 --- a/rtc_base/bitstream_reader_unittest.cc +++ b/rtc_base/bitstream_reader_unittest.cc @@ -16,11 +16,11 @@ #include #include #include +#include #include "absl/numeric/bits.h" #include "api/array_view.h" #include "rtc_base/checks.h" -#include "test/gmock.h" #include "test/gtest.h" namespace webrtc { diff --git a/rtc_base/boringssl_certificate.cc b/rtc_base/boringssl_certificate.cc index 4a34d05448..a4f919fbbe 100644 --- a/rtc_base/boringssl_certificate.cc +++ b/rtc_base/boringssl_certificate.cc @@ -10,17 +10,6 @@ #include "rtc_base/boringssl_certificate.h" -#include -#include -#include -#include -#include - -#if defined(WEBRTC_WIN) -// Must be included first before openssl headers. -#include "rtc_base/win32.h" // NOLINT -#endif // WEBRTC_WIN - #include #include #include @@ -29,7 +18,13 @@ #include #include #include -#include + +#include +#include +#include +#include +#include +#include #include "absl/strings/string_view.h" #include "rtc_base/buffer.h" @@ -48,41 +43,39 @@ namespace { // List of OIDs of signature algorithms accepted by WebRTC. // Taken from openssl/nid.h. -static const uint8_t kMD5WithRSA[] = {0x2b, 0x0e, 0x03, 0x02, 0x03}; -static const uint8_t kMD5WithRSAEncryption[] = {0x2a, 0x86, 0x48, 0x86, 0xf7, - 0x0d, 0x01, 0x01, 0x04}; -static const uint8_t kECDSAWithSHA1[] = {0x2a, 0x86, 0x48, 0xce, - 0x3d, 0x04, 0x01}; -static const uint8_t kDSAWithSHA1[] = {0x2a, 0x86, 0x48, 0xce, - 0x38, 0x04, 0x03}; -static const uint8_t kDSAWithSHA1_2[] = {0x2b, 0x0e, 0x03, 0x02, 0x1b}; -static const uint8_t kSHA1WithRSA[] = {0x2b, 0x0e, 0x03, 0x02, 0x1d}; -static const uint8_t kSHA1WithRSAEncryption[] = {0x2a, 0x86, 0x48, 0x86, 0xf7, - 0x0d, 0x01, 0x01, 0x05}; -static const uint8_t kECDSAWithSHA224[] = {0x2a, 0x86, 0x48, 0xce, - 0x3d, 0x04, 0x03, 0x01}; -static const uint8_t kSHA224WithRSAEncryption[] = {0x2a, 0x86, 0x48, 0x86, 0xf7, - 0x0d, 0x01, 0x01, 0x0e}; -static const uint8_t kDSAWithSHA224[] = {0x60, 0x86, 0x48, 0x01, 0x65, - 0x03, 0x04, 0x03, 0x01}; -static const uint8_t kECDSAWithSHA256[] = {0x2a, 0x86, 0x48, 0xce, - 0x3d, 0x04, 0x03, 0x02}; -static const uint8_t kSHA256WithRSAEncryption[] = {0x2a, 0x86, 0x48, 0x86, 0xf7, - 0x0d, 0x01, 0x01, 0x0b}; -static const uint8_t kDSAWithSHA256[] = {0x60, 0x86, 0x48, 0x01, 0x65, - 0x03, 0x04, 0x03, 0x02}; -static const uint8_t kECDSAWithSHA384[] = {0x2a, 0x86, 0x48, 0xce, - 0x3d, 0x04, 0x03, 0x03}; -static const uint8_t kSHA384WithRSAEncryption[] = {0x2a, 0x86, 0x48, 0x86, 0xf7, - 0x0d, 0x01, 0x01, 0x0c}; -static const uint8_t kECDSAWithSHA512[] = {0x2a, 0x86, 0x48, 0xce, - 0x3d, 0x04, 0x03, 0x04}; -static const uint8_t kSHA512WithRSAEncryption[] = {0x2a, 0x86, 0x48, 0x86, 0xf7, - 0x0d, 0x01, 0x01, 0x0d}; +const uint8_t kMD5WithRSA[] = {0x2b, 0x0e, 0x03, 0x02, 0x03}; +const uint8_t kMD5WithRSAEncryption[] = {0x2a, 0x86, 0x48, 0x86, 0xf7, + 0x0d, 0x01, 0x01, 0x04}; +const uint8_t kECDSAWithSHA1[] = {0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x01}; +const uint8_t kDSAWithSHA1[] = {0x2a, 0x86, 0x48, 0xce, 0x38, 0x04, 0x03}; +const uint8_t kDSAWithSHA1_2[] = {0x2b, 0x0e, 0x03, 0x02, 0x1b}; +const uint8_t kSHA1WithRSA[] = {0x2b, 0x0e, 0x03, 0x02, 0x1d}; +const uint8_t kSHA1WithRSAEncryption[] = {0x2a, 0x86, 0x48, 0x86, 0xf7, + 0x0d, 0x01, 0x01, 0x05}; +const uint8_t kECDSAWithSHA224[] = {0x2a, 0x86, 0x48, 0xce, + 0x3d, 0x04, 0x03, 0x01}; +const uint8_t kSHA224WithRSAEncryption[] = {0x2a, 0x86, 0x48, 0x86, 0xf7, + 0x0d, 0x01, 0x01, 0x0e}; +const uint8_t kDSAWithSHA224[] = {0x60, 0x86, 0x48, 0x01, 0x65, + 0x03, 0x04, 0x03, 0x01}; +const uint8_t kECDSAWithSHA256[] = {0x2a, 0x86, 0x48, 0xce, + 0x3d, 0x04, 0x03, 0x02}; +const uint8_t kSHA256WithRSAEncryption[] = {0x2a, 0x86, 0x48, 0x86, 0xf7, + 0x0d, 0x01, 0x01, 0x0b}; +const uint8_t kDSAWithSHA256[] = {0x60, 0x86, 0x48, 0x01, 0x65, + 0x03, 0x04, 0x03, 0x02}; +const uint8_t kECDSAWithSHA384[] = {0x2a, 0x86, 0x48, 0xce, + 0x3d, 0x04, 0x03, 0x03}; +const uint8_t kSHA384WithRSAEncryption[] = {0x2a, 0x86, 0x48, 0x86, 0xf7, + 0x0d, 0x01, 0x01, 0x0c}; +const uint8_t kECDSAWithSHA512[] = {0x2a, 0x86, 0x48, 0xce, + 0x3d, 0x04, 0x03, 0x04}; +const uint8_t kSHA512WithRSAEncryption[] = {0x2a, 0x86, 0x48, 0x86, 0xf7, + 0x0d, 0x01, 0x01, 0x0d}; #if !defined(NDEBUG) // Print a certificate to the log, for debugging. -static void PrintCert(BoringSSLCertificate* cert) { +void PrintCert(BoringSSLCertificate* cert) { // Since we're using CRYPTO_BUFFER, we can't use X509_print_ex, so we'll just // print the PEM string. RTC_DLOG(LS_VERBOSE) << "PEM representation of certificate:\n" @@ -187,7 +180,7 @@ bool AddTime(CBB* cbb, time_t time) { // Generate a self-signed certificate, with the public key from the // given key pair. Caller is responsible for freeing the returned object. -static bssl::UniquePtr MakeCertificate( +bssl::UniquePtr MakeCertificate( EVP_PKEY* pkey, const SSLIdentityParams& params) { RTC_LOG(LS_INFO) << "Making certificate for " << params.common_name; diff --git a/rtc_base/bounded_inline_vector.h b/rtc_base/bounded_inline_vector.h index f8b7eb3d86..a3a66b0c2f 100644 --- a/rtc_base/bounded_inline_vector.h +++ b/rtc_base/bounded_inline_vector.h @@ -13,7 +13,6 @@ #include -#include #include #include diff --git a/rtc_base/bounded_inline_vector_unittest.cc b/rtc_base/bounded_inline_vector_unittest.cc index 50cf2e3153..3411295e77 100644 --- a/rtc_base/bounded_inline_vector_unittest.cc +++ b/rtc_base/bounded_inline_vector_unittest.cc @@ -12,9 +12,9 @@ #include #include +#include #include -#include "test/gmock.h" #include "test/gtest.h" namespace webrtc { diff --git a/rtc_base/buffer_unittest.cc b/rtc_base/buffer_unittest.cc index e6f5d8eb92..47eb2e4931 100644 --- a/rtc_base/buffer_unittest.cc +++ b/rtc_base/buffer_unittest.cc @@ -10,11 +10,14 @@ #include "rtc_base/buffer.h" +#include #include +#include #include #include "absl/strings/string_view.h" #include "api/array_view.h" +#include "rtc_base/checks.h" #include "test/gmock.h" #include "test/gtest.h" diff --git a/rtc_base/byte_buffer.h b/rtc_base/byte_buffer.h index b962f4574d..edf236a58f 100644 --- a/rtc_base/byte_buffer.h +++ b/rtc_base/byte_buffer.h @@ -61,21 +61,21 @@ class ByteBufferWriterT { WriteBytesInternal(reinterpret_cast(&val), 1); } void WriteUInt16(uint16_t val) { - uint16_t v = webrtc::HostToNetwork16(val); + uint16_t v = HostToNetwork16(val); WriteBytesInternal(reinterpret_cast(&v), 2); } void WriteUInt24(uint32_t val) { - uint32_t v = webrtc::HostToNetwork32(val); + uint32_t v = HostToNetwork32(val); value_type* start = reinterpret_cast(&v); ++start; WriteBytesInternal(start, 3); } void WriteUInt32(uint32_t val) { - uint32_t v = webrtc::HostToNetwork32(val); + uint32_t v = HostToNetwork32(val); WriteBytesInternal(reinterpret_cast(&v), 4); } void WriteUInt64(uint64_t val) { - uint64_t v = webrtc::HostToNetwork64(val); + uint64_t v = HostToNetwork64(val); WriteBytesInternal(reinterpret_cast(&v), 8); } // Serializes an unsigned varint in the format described by diff --git a/rtc_base/callback_list.cc b/rtc_base/callback_list.cc index e938f96eee..8c108a5208 100644 --- a/rtc_base/callback_list.cc +++ b/rtc_base/callback_list.cc @@ -10,7 +10,11 @@ #include "rtc_base/callback_list.h" +#include + +#include "api/function_view.h" #include "rtc_base/checks.h" +#include "rtc_base/untyped_function.h" namespace webrtc { namespace callback_list_impl { diff --git a/rtc_base/callback_list.h b/rtc_base/callback_list.h index 73a6974a84..004f149188 100644 --- a/rtc_base/callback_list.h +++ b/rtc_base/callback_list.h @@ -16,7 +16,6 @@ #include "api/function_view.h" #include "rtc_base/checks.h" -#include "rtc_base/system/assume.h" #include "rtc_base/system/inline.h" #include "rtc_base/system/rtc_export.h" #include "rtc_base/untyped_function.h" diff --git a/rtc_base/callback_list_unittest.cc b/rtc_base/callback_list_unittest.cc index 86c2009fe3..59c85fa04d 100644 --- a/rtc_base/callback_list_unittest.cc +++ b/rtc_base/callback_list_unittest.cc @@ -9,10 +9,10 @@ */ #include "rtc_base/callback_list.h" +#include #include -#include -#include "api/function_view.h" +#include "rtc_base/untyped_function.h" #include "test/gtest.h" namespace webrtc { diff --git a/rtc_base/checks.h b/rtc_base/checks.h index 91414807f6..838da2b7e5 100644 --- a/rtc_base/checks.h +++ b/rtc_base/checks.h @@ -60,10 +60,9 @@ RTC_NORETURN void rtc_FatalMessage(const char* file, int line, const char* msg); #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "api/scoped_refptr.h" -#include "rtc_base/numerics/safe_compare.h" +#include "rtc_base/numerics/safe_compare.h" // IWYU pragma: keep #include "rtc_base/system/inline.h" #include "rtc_base/system/rtc_export.h" -#include "rtc_base/type_traits.h" // The macros here print a message to stderr and abort under various // conditions. All will accept additional stream messages. For example: diff --git a/rtc_base/containers/BUILD.gn b/rtc_base/containers/BUILD.gn index c4d9f28f9f..f80dfce88f 100644 --- a/rtc_base/containers/BUILD.gn +++ b/rtc_base/containers/BUILD.gn @@ -51,5 +51,6 @@ rtc_library("unittests") { "//testing/gmock:gmock", "//testing/gtest:gtest", "//third_party/abseil-cpp/absl/algorithm:container", + "//third_party/abseil-cpp/absl/strings:string_view", ] } diff --git a/rtc_base/containers/flat_map.h b/rtc_base/containers/flat_map.h index d1f757f669..35e6c7f039 100644 --- a/rtc_base/containers/flat_map.h +++ b/rtc_base/containers/flat_map.h @@ -15,6 +15,7 @@ #include #include +#include #include #include diff --git a/rtc_base/containers/flat_map_unittest.cc b/rtc_base/containers/flat_map_unittest.cc index 98846a0206..670714e39b 100644 --- a/rtc_base/containers/flat_map_unittest.cc +++ b/rtc_base/containers/flat_map_unittest.cc @@ -12,11 +12,12 @@ #include "rtc_base/containers/flat_map.h" -#include #include -#include +#include #include +#include "absl/algorithm/container.h" +#include "absl/strings/string_view.h" #include "rtc_base/containers/move_only_int.h" #include "test/gmock.h" #include "test/gtest.h" diff --git a/rtc_base/containers/flat_tree.h b/rtc_base/containers/flat_tree.h index 480784ced4..43db5b7664 100644 --- a/rtc_base/containers/flat_tree.h +++ b/rtc_base/containers/flat_tree.h @@ -14,6 +14,9 @@ #define RTC_BASE_CONTAINERS_FLAT_TREE_H_ #include +#include +#include +#include #include #include #include diff --git a/rtc_base/containers/invoke.h b/rtc_base/containers/invoke.h index 5d17a70beb..262c01638e 100644 --- a/rtc_base/containers/invoke.h +++ b/rtc_base/containers/invoke.h @@ -13,6 +13,7 @@ #ifndef RTC_BASE_CONTAINERS_INVOKE_H_ #define RTC_BASE_CONTAINERS_INVOKE_H_ +#include #include #include diff --git a/rtc_base/copy_on_write_buffer.cc b/rtc_base/copy_on_write_buffer.cc index 51bdb17f07..ab53c9538a 100644 --- a/rtc_base/copy_on_write_buffer.cc +++ b/rtc_base/copy_on_write_buffer.cc @@ -12,7 +12,12 @@ #include +#include +#include +#include + #include "absl/strings/string_view.h" +#include "rtc_base/checks.h" namespace webrtc { diff --git a/rtc_base/copy_on_write_buffer.h b/rtc_base/copy_on_write_buffer.h index 6dfa289147..7970fa9524 100644 --- a/rtc_base/copy_on_write_buffer.h +++ b/rtc_base/copy_on_write_buffer.h @@ -15,7 +15,6 @@ #include #include -#include #include #include @@ -307,7 +306,7 @@ class RTC_EXPORT CopyOnWriteBuffer { } } - // buffer_ is either null, or points to an webrtc::Buffer with capacity > 0. + // buffer_ is either null, or points to an Buffer with capacity > 0. scoped_refptr buffer_; // This buffer may represent a slice of a original data. size_t offset_; // Offset of a current slice in the original data in buffer_. diff --git a/rtc_base/copy_on_write_buffer_unittest.cc b/rtc_base/copy_on_write_buffer_unittest.cc index 25d6d9bcba..6d73ee228e 100644 --- a/rtc_base/copy_on_write_buffer_unittest.cc +++ b/rtc_base/copy_on_write_buffer_unittest.cc @@ -10,8 +10,14 @@ #include "rtc_base/copy_on_write_buffer.h" +#include #include +#include +#include +#include +#include +#include "api/array_view.h" #include "test/gtest.h" namespace webrtc { diff --git a/rtc_base/cpu_info.cc b/rtc_base/cpu_info.cc index 99a5bc8f8a..56aba5ee63 100644 --- a/rtc_base/cpu_info.cc +++ b/rtc_base/cpu_info.cc @@ -14,16 +14,47 @@ #if defined(WEBRTC_WIN) #include -#elif defined(WEBRTC_LINUX) -#include #elif defined(WEBRTC_MAC) #include +#elif defined(WEBRTC_ANDROID) +#include +#include #elif defined(WEBRTC_FUCHSIA) #include +#elif defined(WEBRTC_LINUX) +#include +#include +#include // IWYU pragma: keep +#include + +#ifdef __GLIBC_PREREQ +#define WEBRTC_GLIBC_PREREQ(a, b) __GLIBC_PREREQ(a, b) +#else +#define WEBRTC_GLIBC_PREREQ(a, b) 0 +#endif + +#if WEBRTC_GLIBC_PREREQ(2, 16) +#include // IWYU pragma: keep +#else +#include +#include +#include #endif +#endif // WEBRTC_LINUX #include "rtc_base/checks.h" #include "rtc_base/logging.h" +#include "rtc_base/system/arch.h" +#include "rtc_base/system/unused.h" // IWYU pragma: keep + +#if defined(WEBRTC_ARCH_X86_FAMILY) && defined(_MSC_VER) +#include +#endif +#if defined(WEBRTC_ARCH_ARM_FAMILY) && defined(WEBRTC_LINUX) +#include +#endif + +// Parts of this file derived from Chromium's base/cpu.cc. namespace { @@ -60,6 +91,47 @@ uint32_t DetectNumberOfCores() { return static_cast(number_of_cores); } +#if defined(WEBRTC_ARCH_X86_FAMILY) + +#if defined(WEBRTC_ENABLE_AVX2) +// xgetbv returns the value of an Intel Extended Control Register (XCR). +// Currently only XCR0 is defined by Intel so `xcr` should always be zero. +uint64_t xgetbv(uint32_t xcr) { +#if defined(_MSC_VER) + return _xgetbv(xcr); +#else + uint32_t eax, edx; + + __asm__ volatile("xgetbv" : "=a"(eax), "=d"(edx) : "c"(xcr)); + return (static_cast(edx) << 32) | eax; +#endif // _MSC_VER +} +#endif // WEBRTC_ENABLE_AVX2 + +#ifndef _MSC_VER +// Intrinsic for "cpuid". +#if defined(__pic__) && defined(__i386__) +static inline void __cpuid(int cpu_info[4], int info_type) { + __asm__ volatile( + "mov %%ebx, %%edi\n" + "cpuid\n" + "xchg %%edi, %%ebx\n" + : "=a"(cpu_info[0]), "=D"(cpu_info[1]), "=c"(cpu_info[2]), + "=d"(cpu_info[3]) + : "a"(info_type)); +} +#else +inline void __cpuid(int cpu_info[4], int info_type) { + __asm__ volatile("cpuid\n" + : "=a"(cpu_info[0]), "=b"(cpu_info[1]), "=c"(cpu_info[2]), + "=d"(cpu_info[3]) + : "a"(info_type), "c"(0)); +} +#endif +#endif // _MSC_VER + +#endif // WEBRTC_ARCH_X86_FAMILY + } // namespace namespace webrtc { @@ -75,6 +147,87 @@ uint32_t DetectNumberOfCores() { return logical_cpus; } +bool Supports(ISA instruction_set_architecture) { +#if defined(WEBRTC_ARCH_X86_FAMILY) + int cpu_info[4]; + __cpuid(cpu_info, 1); + if (instruction_set_architecture == ISA::kSSE2) { + return 0 != (cpu_info[3] & 0x04000000); + } + if (instruction_set_architecture == ISA::kSSE3) { + return 0 != (cpu_info[2] & 0x00000001); + } +#if defined(WEBRTC_ENABLE_AVX2) + if (instruction_set_architecture == ISA::kAVX2) { + int cpu_info7[4]; + __cpuid(cpu_info7, 0); + int num_ids = cpu_info7[0]; + if (num_ids < 7) { + return false; + } + // Interpret CPU feature information. + __cpuid(cpu_info7, 7); + + // AVX instructions can be used when + // a) AVX are supported by the CPU, + // b) XSAVE is supported by the CPU, + // c) XSAVE is enabled by the kernel. + // Compiling with MSVC and /arch:AVX2 surprisingly generates BMI2 + // instructions (see crbug.com/1315519). + return (cpu_info[2] & 0x10000000) != 0 /* AVX */ && + (cpu_info[2] & 0x04000000) != 0 /* XSAVE */ && + (cpu_info[2] & 0x08000000) != 0 /* OSXSAVE */ && + (xgetbv(0) & 0x00000006) == 6 /* XSAVE enabled by kernel */ && + (cpu_info7[1] & 0x00000020) != 0 /* AVX2 */ && + (cpu_info7[1] & 0x00000100) != 0 /* BMI2 */; + } +#endif // WEBRTC_ENABLE_AVX2 + if (instruction_set_architecture == ISA::kFMA3) { + return 0 != (cpu_info[2] & 0x00001000); + } +#elif defined(WEBRTC_ARCH_ARM_FAMILY) + if (instruction_set_architecture == ISA::kNeon) { +#if defined(WEBRTC_ANDROID) + return 0 != (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON); +#elif defined(WEBRTC_LINUX) + uint64_t hwcap = 0; +#if WEBRTC_GLIBC_PREREQ(2, 16) + hwcap = getauxval(AT_HWCAP); +#else + ElfW(auxv_t) auxv; + int fd = open("/proc/self/auxv", O_RDONLY); + if (fd >= 0) { + while (hwcap == 0) { + if (read(fd, &auxv, sizeof(auxv)) < (ssize_t)sizeof(auxv)) { + if (errno == EINTR) { + continue; + } + break; + } + if (AT_HWCAP == auxv.a_type) { + hwcap = auxv.a_un.a_val; + } + } + close(fd); + } +#endif // WEBRTC_GLIBC_PREREQ(2, 16) +#if defined(__aarch64__) + if ((hwcap & HWCAP_ASIMD) != 0) { + return true; + } +#else + if ((hwcap & HWCAP_NEON) != 0) { + return true; + } +#endif +#endif // WEBRTC_LINUX + } +#else + RTC_UNUSED(instruction_set_architecture); +#endif // WEBRTC_ARCH_ARM_FAMILY + return false; +} + } // namespace cpu_info } // namespace webrtc diff --git a/rtc_base/cpu_info.h b/rtc_base/cpu_info.h index 9a4f569f3f..9a49c12d15 100644 --- a/rtc_base/cpu_info.h +++ b/rtc_base/cpu_info.h @@ -20,6 +20,11 @@ namespace cpu_info { // Returned number of cores is always >= 1. uint32_t DetectNumberOfCores(); +enum class ISA { kSSE2 = 0, kSSE3, kAVX2, kFMA3, kNeon }; + +// Returns true if the CPU supports the given instruction set. +bool Supports(ISA instruction_set_architecture); + } // namespace cpu_info } // namespace webrtc diff --git a/rtc_base/crc32.cc b/rtc_base/crc32.cc index 700a0f4952..b084522927 100644 --- a/rtc_base/crc32.cc +++ b/rtc_base/crc32.cc @@ -10,7 +10,9 @@ #include "rtc_base/crc32.h" -#include "rtc_base/arraysize.h" +#include +#include +#include namespace webrtc { @@ -22,7 +24,7 @@ static const uint32_t kCrc32Polynomial = 0xEDB88320; static uint32_t* LoadCrc32Table() { static uint32_t kCrc32Table[256]; - for (uint32_t i = 0; i < arraysize(kCrc32Table); ++i) { + for (uint32_t i = 0; i < std::size(kCrc32Table); ++i) { uint32_t c = i; for (size_t j = 0; j < 8; ++j) { if (c & 1) { diff --git a/rtc_base/crc32_unittest.cc b/rtc_base/crc32_unittest.cc index 36314f78c9..0c992c4ad7 100644 --- a/rtc_base/crc32_unittest.cc +++ b/rtc_base/crc32_unittest.cc @@ -10,6 +10,8 @@ #include "rtc_base/crc32.h" +#include +#include #include #include "test/gtest.h" diff --git a/rtc_base/crypto_random.cc b/rtc_base/crypto_random.cc index c14315cfe9..97f1778c13 100644 --- a/rtc_base/crypto_random.cc +++ b/rtc_base/crypto_random.cc @@ -12,9 +12,11 @@ #include +#include #include #include #include +#include #include #include "absl/strings/string_view.h" @@ -61,17 +63,17 @@ class TestRandomGenerator : public RandomGenerator { }; // TODO: Use Base64::Base64Table instead. -static const char kBase64[64] = { - 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', - 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', - 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', - 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'}; +const char kBase64[64] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', + 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', + 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', + 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', + 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', + '3', '4', '5', '6', '7', '8', '9', '+', '/'}; -static const char kHex[16] = {'0', '1', '2', '3', '4', '5', '6', '7', - '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; +const char kHex[16] = {'0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; -static const char kUuidDigit17[4] = {'8', '9', 'a', 'b'}; +const char kUuidDigit17[4] = {'8', '9', 'a', 'b'}; // Lock for the global random generator, only needed to serialize changing the // generator. diff --git a/rtc_base/crypto_random_unittest.cc b/rtc_base/crypto_random_unittest.cc index f3e80ce1ba..efc3617f28 100644 --- a/rtc_base/crypto_random_unittest.cc +++ b/rtc_base/crypto_random_unittest.cc @@ -12,7 +12,9 @@ #include +#include #include +#include #include #include diff --git a/rtc_base/deprecated/recursive_critical_section.h b/rtc_base/deprecated/recursive_critical_section.h index e347e483e1..e4a2053632 100644 --- a/rtc_base/deprecated/recursive_critical_section.h +++ b/rtc_base/deprecated/recursive_critical_section.h @@ -42,7 +42,7 @@ namespace webrtc { -// NOTE: This class is deprecated. Please use webrtc::Mutex instead! +// NOTE: This class is deprecated. Please use Mutex instead! // Search using https://www.google.com/?q=recursive+lock+considered+harmful // to find the reasons. // diff --git a/rtc_base/deprecated/recursive_critical_section_unittest.cc b/rtc_base/deprecated/recursive_critical_section_unittest.cc index 4090eb16a7..fedaaf5fbb 100644 --- a/rtc_base/deprecated/recursive_critical_section_unittest.cc +++ b/rtc_base/deprecated/recursive_critical_section_unittest.cc @@ -20,7 +20,6 @@ #include #include "api/units/time_delta.h" -#include "rtc_base/arraysize.h" #include "rtc_base/checks.h" #include "rtc_base/event.h" #include "rtc_base/platform_thread.h" @@ -274,7 +273,7 @@ TEST(RecursiveCriticalSectionTest, DISABLED_Performance) { Event event; static const int kThreadRepeats = 10000000; - static const int kExpectedCount = kThreadRepeats * arraysize(threads); + static const int kExpectedCount = kThreadRepeats * std::ssize(threads); PerfTestData test_data(kExpectedCount, &event); for (auto& t : threads) diff --git a/rtc_base/event.cc b/rtc_base/event.cc index 7338670d66..e7ad91c6c9 100644 --- a/rtc_base/event.cc +++ b/rtc_base/event.cc @@ -55,10 +55,9 @@ void Event::Reset() { bool Event::Wait(TimeDelta give_up_after, TimeDelta /*warn_after*/) { ScopedYieldPolicy::YieldExecution(); - const DWORD ms = - give_up_after.IsPlusInfinity() - ? INFINITE - : give_up_after.RoundUpTo(webrtc::TimeDelta::Millis(1)).ms(); + const DWORD ms = give_up_after.IsPlusInfinity() + ? INFINITE + : give_up_after.RoundUpTo(TimeDelta::Millis(1)).ms(); return (WaitForSingleObject(event_handle_, ms) == WAIT_OBJECT_0); } @@ -123,7 +122,7 @@ timespec GetTimespec(TimeDelta duration_from_now) { timeval tv; gettimeofday(&tv, nullptr); ts.tv_sec = tv.tv_sec; - ts.tv_nsec = tv.tv_usec * webrtc::kNumNanosecsPerMicrosec; + ts.tv_nsec = tv.tv_usec * kNumNanosecsPerMicrosec; #endif // Add the specified number of milliseconds to it. diff --git a/rtc_base/event.h b/rtc_base/event.h index 0f5527e411..908247aefd 100644 --- a/rtc_base/event.h +++ b/rtc_base/event.h @@ -27,8 +27,8 @@ namespace webrtc { // RTC_DISALLOW_WAIT() utility // -// Sets a stack-scoped flag that disallows use of `webrtc::Event::Wait` by means -// of raising a DCHECK when a call to `webrtc::Event::Wait()` is made.. +// Sets a stack-scoped flag that disallows use of `Event::Wait` by means +// of raising a DCHECK when a call to `Event::Wait()` is made.. // This is useful to guard synchronization-free scopes against regressions. // // Example of what this would catch (`ScopeToProtect` calls `Foo`): @@ -99,7 +99,7 @@ class Event { }; // These classes are provided for compatibility with Chromium. -// The webrtc::Event implementation is overriden inside of Chromium for the +// The Event implementation is overriden inside of Chromium for the // purposes of detecting when threads are blocked that shouldn't be as well as // to use the more accurate event implementation that's there than is provided // by default on some platforms (e.g. Windows). @@ -128,7 +128,7 @@ class ScopedDisallowWait { public: void YieldExecution() override { RTC_DCHECK_NOTREACHED(); } } handler_; - webrtc::ScopedYieldPolicy policy{&handler_}; + ScopedYieldPolicy policy{&handler_}; }; #endif diff --git a/rtc_base/event_tracer.cc b/rtc_base/event_tracer.cc index f42ee2cebf..b42757ce1f 100644 --- a/rtc_base/event_tracer.cc +++ b/rtc_base/event_tracer.cc @@ -12,6 +12,7 @@ #include +#include "api/units/time_delta.h" #include "rtc_base/trace_event.h" #if defined(RTC_USE_PERFETTO) @@ -111,7 +112,7 @@ namespace tracing { namespace { // Atomic-int fast path for avoiding logging when disabled. -static std::atomic g_event_logging_active(0); +std::atomic g_event_logging_active(0); // TODO(pbos): Log metadata for all threads, etc. class EventLogger final { @@ -354,8 +355,8 @@ class EventLogger final { bool output_file_owned_ = false; }; -static std::atomic g_event_logger(nullptr); -static const char* const kDisabledTracePrefix = TRACE_DISABLED_BY_DEFAULT(""); +std::atomic g_event_logger(nullptr); +const char* const kDisabledTracePrefix = TRACE_DISABLED_BY_DEFAULT(""); const unsigned char* InternalGetCategoryEnabled(const char* name) { const char* prefix_ptr = &kDisabledTracePrefix[0]; const char* name_ptr = name; diff --git a/rtc_base/event_unittest.cc b/rtc_base/event_unittest.cc index 44a829f7bd..8e64252012 100644 --- a/rtc_base/event_unittest.cc +++ b/rtc_base/event_unittest.cc @@ -102,7 +102,7 @@ TEST(EventTest, DISABLED_PerformanceMultiThread) { } #if RTC_DCHECK_IS_ON && GTEST_HAS_DEATH_TEST && !defined(WEBRTC_ANDROID) -// Tests that we crash if we attempt to call webrtc::Event::Wait while we're +// Tests that we crash if we attempt to call Event::Wait while we're // not allowed to (as per `RTC_DISALLOW_WAIT()`). TEST(EventTestDeathTest, DisallowEventWait) { Event event; diff --git a/rtc_base/experiments/BUILD.gn b/rtc_base/experiments/BUILD.gn index a9f5c7d5cf..925e84eb52 100644 --- a/rtc_base/experiments/BUILD.gn +++ b/rtc_base/experiments/BUILD.gn @@ -40,6 +40,7 @@ rtc_library("field_trial_parser") { "../../rtc_base:safe_conversions", "../../rtc_base:stringutils", "//third_party/abseil-cpp/absl/memory", + "//third_party/abseil-cpp/absl/strings", "//third_party/abseil-cpp/absl/strings:string_view", ] } @@ -90,8 +91,10 @@ rtc_library("balanced_degradation_settings") { ] deps = [ ":field_trial_parser", + "..:checks", "..:logging", "../../api:field_trials_view", + "../../api/video:video_frame", "../../api/video_codecs:video_codecs_api", ] } @@ -105,6 +108,7 @@ rtc_library("encoder_info_settings") { ":field_trial_parser", "..:logging", "../../api:field_trials_view", + "../../api/video:video_frame", "../../api/video_codecs:video_codecs_api", "//third_party/abseil-cpp/absl/strings:string_view", ] @@ -138,17 +142,6 @@ rtc_library("keyframe_interval_settings_experiment") { ] } -rtc_library("stable_target_rate_experiment") { - sources = [ - "stable_target_rate_experiment.cc", - "stable_target_rate_experiment.h", - ] - deps = [ - ":field_trial_parser", - "../../api:field_trials_view", - ] -} - rtc_library("min_video_bitrate_experiment") { sources = [ "min_video_bitrate_experiment.cc", @@ -180,7 +173,6 @@ if (rtc_include_tests && !build_with_chromium) { "quality_scaler_settings_unittest.cc", "quality_scaling_experiment_unittest.cc", "rate_control_settings_unittest.cc", - "stable_target_rate_experiment_unittest.cc", "struct_parameters_parser_unittest.cc", ] deps = [ @@ -193,17 +185,14 @@ if (rtc_include_tests && !build_with_chromium) { ":quality_scaler_settings", ":quality_scaling_experiment", ":rate_control_settings", - ":stable_target_rate_experiment", "..:gunit_helpers", - "../:rtc_base_tests_utils", + "../../api:field_trials", + "../../api:field_trials_view", "../../api/units:data_rate", + "../../api/units:data_size", + "../../api/units:time_delta", "../../api/video:video_frame", "../../api/video_codecs:video_codecs_api", - "../../system_wrappers:field_trial", - "../../test:explicit_key_value_config", - "../../test:field_trial", - "../../test:scoped_key_value_config", - "../../test:test_main", "../../test:test_support", "../../video/config:encoder_config", "//third_party/abseil-cpp/absl/strings:string_view", diff --git a/rtc_base/experiments/DEPS b/rtc_base/experiments/DEPS index 7c8dddef06..cb997ad8ab 100644 --- a/rtc_base/experiments/DEPS +++ b/rtc_base/experiments/DEPS @@ -1,6 +1,3 @@ -include_rules = [ - "+system_wrappers", -] specific_include_rules = { ".*rate_control_settings.*": [ "+video/config", diff --git a/rtc_base/experiments/alr_experiment.cc b/rtc_base/experiments/alr_experiment.cc index 1c5ca14abb..2138e34f90 100644 --- a/rtc_base/experiments/alr_experiment.cc +++ b/rtc_base/experiments/alr_experiment.cc @@ -13,6 +13,7 @@ #include #include +#include #include #include "absl/strings/string_view.h" diff --git a/rtc_base/experiments/balanced_degradation_settings.cc b/rtc_base/experiments/balanced_degradation_settings.cc index 8e0b513ddd..80d7fc4c66 100644 --- a/rtc_base/experiments/balanced_degradation_settings.cc +++ b/rtc_base/experiments/balanced_degradation_settings.cc @@ -10,8 +10,16 @@ #include "rtc_base/experiments/balanced_degradation_settings.h" +#include +#include #include +#include +#include +#include "api/field_trials_view.h" +#include "api/video/video_codec_type.h" +#include "api/video_codecs/video_encoder.h" +#include "rtc_base/checks.h" #include "rtc_base/experiments/field_trial_list.h" #include "rtc_base/experiments/field_trial_parser.h" #include "rtc_base/logging.h" diff --git a/rtc_base/experiments/balanced_degradation_settings.h b/rtc_base/experiments/balanced_degradation_settings.h index 6993681f5a..0a71d863b4 100644 --- a/rtc_base/experiments/balanced_degradation_settings.h +++ b/rtc_base/experiments/balanced_degradation_settings.h @@ -11,10 +11,12 @@ #ifndef RTC_BASE_EXPERIMENTS_BALANCED_DEGRADATION_SETTINGS_H_ #define RTC_BASE_EXPERIMENTS_BALANCED_DEGRADATION_SETTINGS_H_ +#include #include #include #include "api/field_trials_view.h" +#include "api/video/video_codec_type.h" #include "api/video_codecs/video_encoder.h" namespace webrtc { diff --git a/rtc_base/experiments/balanced_degradation_settings_unittest.cc b/rtc_base/experiments/balanced_degradation_settings_unittest.cc index 4f4ef11b69..9c16174af5 100644 --- a/rtc_base/experiments/balanced_degradation_settings_unittest.cc +++ b/rtc_base/experiments/balanced_degradation_settings_unittest.cc @@ -11,10 +11,12 @@ #include "rtc_base/experiments/balanced_degradation_settings.h" #include +#include -#include "rtc_base/gunit.h" +#include "api/field_trials.h" +#include "api/video/video_codec_type.h" #include "test/gmock.h" -#include "test/scoped_key_value_config.h" +#include "test/gtest.h" namespace webrtc { namespace { @@ -58,7 +60,7 @@ void VerifyIsDefault( } // namespace TEST(BalancedDegradationSettings, GetsDefaultConfigIfNoList) { - test::ScopedKeyValueConfig field_trials(""); + FieldTrials field_trials(""); BalancedDegradationSettings settings(field_trials); VerifyIsDefault(settings.GetConfigs()); EXPECT_TRUE(settings.CanAdaptUp(kVideoCodecVP8, 1, /*bitrate_bps*/ 1)); @@ -73,7 +75,7 @@ TEST(BalancedDegradationSettings, GetsDefaultConfigIfNoList) { } TEST(BalancedDegradationSettings, GetsConfig) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-BalancedDegradationSettings/" "pixels:11|22|33,fps:5|15|25,other:4|5|6/"); BalancedDegradationSettings settings(field_trials); @@ -115,7 +117,7 @@ TEST(BalancedDegradationSettings, GetsConfig) { } TEST(BalancedDegradationSettings, GetsDefaultConfigForZeroFpsValue) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-BalancedDegradationSettings/" "pixels:1000|2000|3000,fps:0|15|25/"); BalancedDegradationSettings settings(field_trials); @@ -123,7 +125,7 @@ TEST(BalancedDegradationSettings, GetsDefaultConfigForZeroFpsValue) { } TEST(BalancedDegradationSettings, GetsDefaultConfigIfPixelsDecreases) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-BalancedDegradationSettings/" "pixels:1000|999|3000,fps:5|15|25/"); BalancedDegradationSettings settings(field_trials); @@ -131,7 +133,7 @@ TEST(BalancedDegradationSettings, GetsDefaultConfigIfPixelsDecreases) { } TEST(BalancedDegradationSettings, GetsDefaultConfigIfFramerateDecreases) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-BalancedDegradationSettings/" "pixels:1000|2000|3000,fps:5|4|25/"); BalancedDegradationSettings settings(field_trials); @@ -139,7 +141,7 @@ TEST(BalancedDegradationSettings, GetsDefaultConfigIfFramerateDecreases) { } TEST(BalancedDegradationSettings, GetsConfigWithSpecificFps) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-BalancedDegradationSettings/" "pixels:1000|2000|3000,fps:5|15|25,vp8_fps:7|8|9,vp9_fps:9|10|11," "h264_fps:11|12|13,av1_fps:1|2|3,generic_fps:13|14|15/"); @@ -182,7 +184,7 @@ TEST(BalancedDegradationSettings, GetsConfigWithSpecificFps) { } TEST(BalancedDegradationSettings, GetsDefaultConfigForZeroVp8FpsValue) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-BalancedDegradationSettings/" "pixels:1000|2000|3000,fps:7|15|25,vp8_fps:0|15|25/"); BalancedDegradationSettings settings(field_trials); @@ -190,7 +192,7 @@ TEST(BalancedDegradationSettings, GetsDefaultConfigForZeroVp8FpsValue) { } TEST(BalancedDegradationSettings, GetsDefaultConfigForInvalidFpsValue) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-BalancedDegradationSettings/" "pixels:1000|2000|3000,fps:7|15|25,vp8_fps:10|15|2000/"); BalancedDegradationSettings settings(field_trials); @@ -198,7 +200,7 @@ TEST(BalancedDegradationSettings, GetsDefaultConfigForInvalidFpsValue) { } TEST(BalancedDegradationSettings, GetsDefaultConfigIfVp8FramerateDecreases) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-BalancedDegradationSettings/" "pixels:1000|2000|3000,fps:4|5|25,vp8_fps:5|4|25/"); BalancedDegradationSettings settings(field_trials); @@ -206,7 +208,7 @@ TEST(BalancedDegradationSettings, GetsDefaultConfigIfVp8FramerateDecreases) { } TEST(BalancedDegradationSettings, GetsMinFps) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-BalancedDegradationSettings/" "pixels:1000|2000|3000,fps:5|15|25/"); BalancedDegradationSettings settings(field_trials); @@ -221,7 +223,7 @@ TEST(BalancedDegradationSettings, GetsMinFps) { } TEST(BalancedDegradationSettings, GetsVp8MinFps) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-BalancedDegradationSettings/" "pixels:1000|2000|3000,fps:5|15|25,vp8_fps:7|10|12/"); BalancedDegradationSettings settings(field_trials); @@ -236,7 +238,7 @@ TEST(BalancedDegradationSettings, GetsVp8MinFps) { } TEST(BalancedDegradationSettings, GetsMaxFps) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-BalancedDegradationSettings/" "pixels:1000|2000|3000,fps:5|15|25/"); BalancedDegradationSettings settings(field_trials); @@ -249,7 +251,7 @@ TEST(BalancedDegradationSettings, GetsMaxFps) { } TEST(BalancedDegradationSettings, GetsVp8MaxFps) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-BalancedDegradationSettings/" "pixels:1000|2000|3000,fps:5|15|25,vp8_fps:7|10|12/"); BalancedDegradationSettings settings(field_trials); @@ -262,7 +264,7 @@ TEST(BalancedDegradationSettings, GetsVp8MaxFps) { } TEST(BalancedDegradationSettings, GetsVp9Fps) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-BalancedDegradationSettings/" "pixels:1000|2000|3000,fps:5|15|25,vp9_fps:7|10|12/"); BalancedDegradationSettings settings(field_trials); @@ -271,7 +273,7 @@ TEST(BalancedDegradationSettings, GetsVp9Fps) { } TEST(BalancedDegradationSettings, GetsH264Fps) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-BalancedDegradationSettings/" "pixels:1000|2000|3000,fps:5|15|25,h264_fps:8|11|13/"); BalancedDegradationSettings settings(field_trials); @@ -280,7 +282,7 @@ TEST(BalancedDegradationSettings, GetsH264Fps) { } TEST(BalancedDegradationSettings, GetsGenericFps) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-BalancedDegradationSettings/" "pixels:1000|2000|3000,fps:5|15|25,generic_fps:9|12|14/"); BalancedDegradationSettings settings(field_trials); @@ -290,7 +292,7 @@ TEST(BalancedDegradationSettings, GetsGenericFps) { } TEST(BalancedDegradationSettings, GetsUnlimitedForMaxValidFps) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-BalancedDegradationSettings/" "pixels:1000|2000|3000,fps:5|15|100,vp8_fps:30|100|100/"); const int kUnlimitedFps = std::numeric_limits::max(); @@ -302,7 +304,7 @@ TEST(BalancedDegradationSettings, GetsUnlimitedForMaxValidFps) { } TEST(BalancedDegradationSettings, GetsConfigWithBitrate) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-BalancedDegradationSettings/" "pixels:11|22|33,fps:5|15|25,kbps:44|88|99,kbps_res:55|111|222," "vp8_kbps:11|12|13,vp8_kbps_res:14|15|16," @@ -349,7 +351,7 @@ TEST(BalancedDegradationSettings, GetsConfigWithBitrate) { } TEST(BalancedDegradationSettings, GetsDefaultConfigIfBitrateDecreases) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-BalancedDegradationSettings/" "pixels:11|22|33,fps:5|15|25,kbps:44|43|99/"); BalancedDegradationSettings settings(field_trials); @@ -358,7 +360,7 @@ TEST(BalancedDegradationSettings, GetsDefaultConfigIfBitrateDecreases) { TEST(BalancedDegradationSettings, GetsDefaultConfigIfBitrateDecreasesWithUnsetValue) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-BalancedDegradationSettings/" "pixels:11|22|33,fps:5|15|25,kbps:44|0|43/"); BalancedDegradationSettings settings(field_trials); @@ -367,7 +369,7 @@ TEST(BalancedDegradationSettings, TEST(BalancedDegradationSettings, CanAdaptUp) { VideoCodecType vp8 = kVideoCodecVP8; - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-BalancedDegradationSettings/" "pixels:1000|2000|3000|4000,fps:5|15|25|30,kbps:0|80|0|90," "vp9_kbps:40|50|60|70/"); @@ -382,7 +384,7 @@ TEST(BalancedDegradationSettings, CanAdaptUp) { } TEST(BalancedDegradationSettings, CanAdaptUpWithCodecType) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-BalancedDegradationSettings/" "pixels:1000|2000|3000|4000,fps:5|15|25|30,vp8_kbps:0|30|40|50," "vp9_kbps:0|60|70|80,h264_kbps:0|55|65|75,av1_kbps:0|77|88|99," @@ -402,7 +404,7 @@ TEST(BalancedDegradationSettings, CanAdaptUpWithCodecType) { TEST(BalancedDegradationSettings, CanAdaptUpResolution) { VideoCodecType vp8 = kVideoCodecVP8; - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-BalancedDegradationSettings/" "pixels:1000|2000|3000|4000,fps:5|15|25|30,kbps_res:0|80|0|90," "vp9_kbps_res:40|50|60|70/"); @@ -417,7 +419,7 @@ TEST(BalancedDegradationSettings, CanAdaptUpResolution) { } TEST(BalancedDegradationSettings, CanAdaptUpResolutionWithCodecType) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-BalancedDegradationSettings/" "pixels:1000|2000|3000|4000,fps:5|15|25|30,vp8_kbps_res:0|30|40|50," "vp9_kbps_res:0|60|70|80,h264_kbps_res:0|55|65|75," @@ -436,7 +438,7 @@ TEST(BalancedDegradationSettings, CanAdaptUpResolutionWithCodecType) { } TEST(BalancedDegradationSettings, GetsFpsDiff) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-BalancedDegradationSettings/" "pixels:1000|2000|3000,fps:5|15|25,fps_diff:0|-2|3/"); BalancedDegradationSettings settings(field_trials); @@ -450,7 +452,7 @@ TEST(BalancedDegradationSettings, GetsFpsDiff) { } TEST(BalancedDegradationSettings, GetsNoFpsDiffIfValueBelowMinSetting) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-BalancedDegradationSettings/" "pixels:1000|2000|3000,fps:5|15|25,fps_diff:-100|-99|-101/"); // Min valid fps_diff setting: -99. @@ -461,7 +463,7 @@ TEST(BalancedDegradationSettings, GetsNoFpsDiffIfValueBelowMinSetting) { } TEST(BalancedDegradationSettings, QpThresholdsNotSetByDefault) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-BalancedDegradationSettings/" "pixels:1000|2000|3000,fps:5|15|25/"); BalancedDegradationSettings settings(field_trials); @@ -473,7 +475,7 @@ TEST(BalancedDegradationSettings, QpThresholdsNotSetByDefault) { } TEST(BalancedDegradationSettings, GetsConfigWithQpThresholds) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-BalancedDegradationSettings/" "pixels:1000|2000|3000,fps:5|15|25,vp8_qp_low:89|90|88," "vp8_qp_high:90|91|92,vp9_qp_low:27|28|29,vp9_qp_high:120|130|140," @@ -518,7 +520,7 @@ TEST(BalancedDegradationSettings, GetsConfigWithQpThresholds) { } TEST(BalancedDegradationSettings, GetsDefaultConfigIfOnlyHasLowThreshold) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-BalancedDegradationSettings/" "pixels:1000|2000|3000,fps:5|15|25,vp8_qp_low:89|90|88/"); BalancedDegradationSettings settings(field_trials); @@ -526,7 +528,7 @@ TEST(BalancedDegradationSettings, GetsDefaultConfigIfOnlyHasLowThreshold) { } TEST(BalancedDegradationSettings, GetsDefaultConfigIfOnlyHasHighThreshold) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-BalancedDegradationSettings/" "pixels:1000|2000|3000,fps:5|15|25,vp8_qp_high:90|91|92/"); BalancedDegradationSettings settings(field_trials); @@ -534,7 +536,7 @@ TEST(BalancedDegradationSettings, GetsDefaultConfigIfOnlyHasHighThreshold) { } TEST(BalancedDegradationSettings, GetsDefaultConfigIfLowEqualsHigh) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-BalancedDegradationSettings/" "pixels:1000|2000|3000,fps:5|15|25," "vp8_qp_low:89|90|88,vp8_qp_high:90|91|88/"); @@ -543,7 +545,7 @@ TEST(BalancedDegradationSettings, GetsDefaultConfigIfLowEqualsHigh) { } TEST(BalancedDegradationSettings, GetsDefaultConfigIfLowGreaterThanHigh) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-BalancedDegradationSettings/" "pixels:1000|2000|3000,fps:5|15|25," "vp8_qp_low:89|90|88,vp8_qp_high:90|91|87/"); @@ -552,7 +554,7 @@ TEST(BalancedDegradationSettings, GetsDefaultConfigIfLowGreaterThanHigh) { } TEST(BalancedDegradationSettings, GetsDefaultConfigForZeroQpValue) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-BalancedDegradationSettings/" "pixels:1000|2000|3000,fps:5|15|25," "vp8_qp_low:89|0|88,vp8_qp_high:90|91|92/"); @@ -561,7 +563,7 @@ TEST(BalancedDegradationSettings, GetsDefaultConfigForZeroQpValue) { } TEST(BalancedDegradationSettings, GetsVp8QpThresholds) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-BalancedDegradationSettings/" "pixels:1000|2000|3000,fps:5|15|25," "vp8_qp_low:89|90|88,vp8_qp_high:90|91|92/"); @@ -577,7 +579,7 @@ TEST(BalancedDegradationSettings, GetsVp8QpThresholds) { } TEST(BalancedDegradationSettings, GetsVp9QpThresholds) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-BalancedDegradationSettings/" "pixels:1000|2000|3000,fps:5|15|25," "vp9_qp_low:55|56|57,vp9_qp_high:155|156|157/"); @@ -589,7 +591,7 @@ TEST(BalancedDegradationSettings, GetsVp9QpThresholds) { } TEST(BalancedDegradationSettings, GetsH264QpThresholds) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-BalancedDegradationSettings/" "pixels:1000|2000|3000,fps:5|15|25," "h264_qp_low:21|22|23,h264_qp_high:41|43|42/"); @@ -601,7 +603,7 @@ TEST(BalancedDegradationSettings, GetsH264QpThresholds) { } TEST(BalancedDegradationSettings, GetsGenericQpThresholds) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-BalancedDegradationSettings/" "pixels:1000|2000|3000,fps:5|15|25," "generic_qp_low:2|3|4,generic_qp_high:22|23|24/"); diff --git a/rtc_base/experiments/encoder_info_settings.cc b/rtc_base/experiments/encoder_info_settings.cc index c5f544ee07..bfc55029dd 100644 --- a/rtc_base/experiments/encoder_info_settings.cc +++ b/rtc_base/experiments/encoder_info_settings.cc @@ -12,9 +12,18 @@ #include +#include +#include +#include +#include +#include + #include "absl/strings/string_view.h" #include "api/field_trials_view.h" +#include "api/video/video_codec_type.h" +#include "api/video_codecs/video_encoder.h" #include "rtc_base/experiments/field_trial_list.h" +#include "rtc_base/experiments/field_trial_parser.h" #include "rtc_base/logging.h" namespace webrtc { diff --git a/rtc_base/experiments/encoder_info_settings.h b/rtc_base/experiments/encoder_info_settings.h index a8d00bebd1..b877c30388 100644 --- a/rtc_base/experiments/encoder_info_settings.h +++ b/rtc_base/experiments/encoder_info_settings.h @@ -11,12 +11,13 @@ #ifndef RTC_BASE_EXPERIMENTS_ENCODER_INFO_SETTINGS_H_ #define RTC_BASE_EXPERIMENTS_ENCODER_INFO_SETTINGS_H_ +#include #include -#include #include #include "absl/strings/string_view.h" #include "api/field_trials_view.h" +#include "api/video/video_codec_type.h" #include "api/video_codecs/video_encoder.h" #include "rtc_base/experiments/field_trial_parser.h" diff --git a/rtc_base/experiments/encoder_info_settings_unittest.cc b/rtc_base/experiments/encoder_info_settings_unittest.cc index 70c0b7f0ba..2fa3a984bd 100644 --- a/rtc_base/experiments/encoder_info_settings_unittest.cc +++ b/rtc_base/experiments/encoder_info_settings_unittest.cc @@ -10,16 +10,19 @@ #include "rtc_base/experiments/encoder_info_settings.h" -#include "rtc_base/gunit.h" -#include "test/explicit_key_value_config.h" +#include +#include + +#include "api/field_trials.h" +#include "api/video_codecs/video_encoder.h" #include "test/gmock.h" +#include "test/gtest.h" namespace webrtc { -using test::ExplicitKeyValueConfig; TEST(SimulcastEncoderAdapterSettingsTest, NoValuesWithoutFieldTrial) { - ExplicitKeyValueConfig field_trials(""); + FieldTrials field_trials(""); SimulcastEncoderAdapterEncoderInfoSettings settings(field_trials); EXPECT_EQ(std::nullopt, settings.requested_resolution_alignment()); @@ -28,7 +31,7 @@ TEST(SimulcastEncoderAdapterSettingsTest, NoValuesWithoutFieldTrial) { } TEST(SimulcastEncoderAdapterSettingsTest, NoValueForInvalidAlignment) { - ExplicitKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-SimulcastEncoderAdapter-GetEncoderInfoOverride/" "requested_resolution_alignment:0/"); @@ -37,7 +40,7 @@ TEST(SimulcastEncoderAdapterSettingsTest, NoValueForInvalidAlignment) { } TEST(SimulcastEncoderAdapterSettingsTest, GetResolutionAlignment) { - ExplicitKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-SimulcastEncoderAdapter-GetEncoderInfoOverride/" "requested_resolution_alignment:2/"); @@ -48,7 +51,7 @@ TEST(SimulcastEncoderAdapterSettingsTest, GetResolutionAlignment) { } TEST(SimulcastEncoderAdapterSettingsTest, GetApplyAlignment) { - ExplicitKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-SimulcastEncoderAdapter-GetEncoderInfoOverride/" "requested_resolution_alignment:3," "apply_alignment_to_all_simulcast_layers/"); @@ -60,7 +63,7 @@ TEST(SimulcastEncoderAdapterSettingsTest, GetApplyAlignment) { } TEST(SimulcastEncoderAdapterSettingsTest, GetResolutionBitrateLimits) { - ExplicitKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-SimulcastEncoderAdapter-GetEncoderInfoOverride/" "frame_size_pixels:123," "min_start_bitrate_bps:11000," @@ -76,7 +79,7 @@ TEST(SimulcastEncoderAdapterSettingsTest, GetResolutionBitrateLimits) { } TEST(SimulcastEncoderAdapterSettingsTest, GetResolutionBitrateLimitsWithList) { - ExplicitKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-SimulcastEncoderAdapter-GetEncoderInfoOverride/" "frame_size_pixels:123|456|789," "min_start_bitrate_bps:11000|22000|33000," @@ -93,7 +96,7 @@ TEST(SimulcastEncoderAdapterSettingsTest, GetResolutionBitrateLimitsWithList) { } TEST(EncoderSettingsTest, CommonSettingsUsedIfEncoderNameUnspecified) { - ExplicitKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-VP8-GetEncoderInfoOverride/requested_resolution_alignment:2/" "WebRTC-GetEncoderInfoOverride/requested_resolution_alignment:3/"); diff --git a/rtc_base/experiments/field_trial_list.cc b/rtc_base/experiments/field_trial_list.cc index 26c17b50b9..776d69f692 100644 --- a/rtc_base/experiments/field_trial_list.cc +++ b/rtc_base/experiments/field_trial_list.cc @@ -9,7 +9,13 @@ */ #include "rtc_base/experiments/field_trial_list.h" +#include +#include +#include + #include "absl/strings/string_view.h" +#include "rtc_base/checks.h" +#include "rtc_base/experiments/field_trial_parser.h" namespace webrtc { diff --git a/rtc_base/experiments/field_trial_list.h b/rtc_base/experiments/field_trial_list.h index 910f25402e..d1a8133129 100644 --- a/rtc_base/experiments/field_trial_list.h +++ b/rtc_base/experiments/field_trial_list.h @@ -10,8 +10,11 @@ #ifndef RTC_BASE_EXPERIMENTS_FIELD_TRIAL_LIST_H_ #define RTC_BASE_EXPERIMENTS_FIELD_TRIAL_LIST_H_ +#include +#include #include #include +#include #include #include diff --git a/rtc_base/experiments/field_trial_list_unittest.cc b/rtc_base/experiments/field_trial_list_unittest.cc index 221a3c6929..eafbc42bf1 100644 --- a/rtc_base/experiments/field_trial_list_unittest.cc +++ b/rtc_base/experiments/field_trial_list_unittest.cc @@ -10,9 +10,12 @@ #include "rtc_base/experiments/field_trial_list.h" +#include + #include "absl/strings/string_view.h" -#include "rtc_base/gunit.h" +#include "rtc_base/experiments/field_trial_parser.h" #include "test/gmock.h" +#include "test/gtest.h" using testing::ElementsAre; using testing::IsEmpty; diff --git a/rtc_base/experiments/field_trial_parser.cc b/rtc_base/experiments/field_trial_parser.cc index fa00c4e32f..ada8f5cc5f 100644 --- a/rtc_base/experiments/field_trial_parser.cc +++ b/rtc_base/experiments/field_trial_parser.cc @@ -11,9 +11,13 @@ #include -#include +#include +#include +#include +#include #include -#include +#include +#include #include #include "absl/strings/string_view.h" diff --git a/rtc_base/experiments/field_trial_parser_unittest.cc b/rtc_base/experiments/field_trial_parser_unittest.cc index 99683507c0..0fc4882364 100644 --- a/rtc_base/experiments/field_trial_parser_unittest.cc +++ b/rtc_base/experiments/field_trial_parser_unittest.cc @@ -9,12 +9,13 @@ */ #include "rtc_base/experiments/field_trial_parser.h" +#include +#include + #include "absl/strings/string_view.h" -#include "rtc_base/experiments/field_trial_list.h" -#include "rtc_base/gunit.h" -#include "system_wrappers/include/field_trial.h" -#include "test/field_trial.h" -#include "test/gmock.h" +#include "api/field_trials.h" +#include "api/field_trials_view.h" +#include "test/gtest.h" namespace webrtc { namespace { @@ -30,12 +31,8 @@ struct DummyExperiment { FieldTrialParameter hash = FieldTrialParameter("h", "a80"); - DummyExperiment() - : DummyExperiment([] { - field_trial::FieldTrialsAllowedInScopeForTesting k{ - {kDummyExperiment}}; - return field_trial::FindFullName(kDummyExperiment); - }()) {} + explicit DummyExperiment(const FieldTrialsView& field_trials) + : DummyExperiment(field_trials.Lookup(kDummyExperiment)) {} explicit DummyExperiment(absl::string_view field_trial) { ParseFieldTrial({&enabled, &factor, &retries, &size, &ping, &hash}, @@ -60,12 +57,14 @@ TEST(FieldTrialParserTest, ParsesValidParameters) { EXPECT_EQ(exp.ping.Get(), true); EXPECT_EQ(exp.hash.Get(), "x7c"); } + TEST(FieldTrialParserTest, InitializesFromFieldTrial) { - test::ScopedFieldTrials field_trials( + FieldTrials field_trials( "WebRTC-OtherExperiment/Disabled/" "WebRTC-DummyExperiment/Enabled,f:-1.7,r:2,s:10,p:1,h:x7c/" "WebRTC-AnotherExperiment/Enabled,f:-3.1,otherstuff:beef/"); - DummyExperiment exp; + field_trials.RegisterKeysForTesting({kDummyExperiment}); + DummyExperiment exp(field_trials); EXPECT_TRUE(exp.enabled.Get()); EXPECT_EQ(exp.factor.Get(), -1.7); EXPECT_EQ(exp.retries.Get(), 2); @@ -73,6 +72,7 @@ TEST(FieldTrialParserTest, InitializesFromFieldTrial) { EXPECT_EQ(exp.ping.Get(), true); EXPECT_EQ(exp.hash.Get(), "x7c"); } + TEST(FieldTrialParserTest, UsesDefaults) { DummyExperiment exp(""); EXPECT_FALSE(exp.enabled.Get()); diff --git a/rtc_base/experiments/field_trial_units.cc b/rtc_base/experiments/field_trial_units.cc index ddb954a28d..e7a5b11fe1 100644 --- a/rtc_base/experiments/field_trial_units.cc +++ b/rtc_base/experiments/field_trial_units.cc @@ -16,6 +16,10 @@ #include #include "absl/strings/string_view.h" +#include "api/units/data_rate.h" +#include "api/units/data_size.h" +#include "api/units/time_delta.h" +#include "rtc_base/experiments/field_trial_parser.h" // Large enough to fit "seconds", the longest supported unit name. #define RTC_TRIAL_UNIT_LENGTH_STR "7" diff --git a/rtc_base/experiments/field_trial_units.h b/rtc_base/experiments/field_trial_units.h index 0bab5feeb6..068429a772 100644 --- a/rtc_base/experiments/field_trial_units.h +++ b/rtc_base/experiments/field_trial_units.h @@ -10,6 +10,8 @@ #ifndef RTC_BASE_EXPERIMENTS_FIELD_TRIAL_UNITS_H_ #define RTC_BASE_EXPERIMENTS_FIELD_TRIAL_UNITS_H_ +#include + #include "absl/strings/string_view.h" #include "api/units/data_rate.h" #include "api/units/data_size.h" diff --git a/rtc_base/experiments/field_trial_units_unittest.cc b/rtc_base/experiments/field_trial_units_unittest.cc index 82ef580017..cff12e1ba6 100644 --- a/rtc_base/experiments/field_trial_units_unittest.cc +++ b/rtc_base/experiments/field_trial_units_unittest.cc @@ -10,9 +10,11 @@ #include "rtc_base/experiments/field_trial_units.h" #include -#include #include "absl/strings/string_view.h" +#include "api/units/data_rate.h" +#include "api/units/data_size.h" +#include "api/units/time_delta.h" #include "rtc_base/experiments/field_trial_parser.h" #include "test/gtest.h" diff --git a/rtc_base/experiments/keyframe_interval_settings.cc b/rtc_base/experiments/keyframe_interval_settings.cc index 760870bc79..d1fe897b7f 100644 --- a/rtc_base/experiments/keyframe_interval_settings.cc +++ b/rtc_base/experiments/keyframe_interval_settings.cc @@ -10,7 +10,10 @@ #include "rtc_base/experiments/keyframe_interval_settings.h" +#include + #include "api/field_trials_view.h" +#include "rtc_base/experiments/field_trial_parser.h" namespace webrtc { diff --git a/rtc_base/experiments/keyframe_interval_settings_unittest.cc b/rtc_base/experiments/keyframe_interval_settings_unittest.cc index 6aca483df0..4bef351b85 100644 --- a/rtc_base/experiments/keyframe_interval_settings_unittest.cc +++ b/rtc_base/experiments/keyframe_interval_settings_unittest.cc @@ -10,26 +10,25 @@ #include "rtc_base/experiments/keyframe_interval_settings.h" -#include "test/explicit_key_value_config.h" +#include "api/field_trials.h" #include "test/gtest.h" namespace webrtc { namespace { -using test::ExplicitKeyValueConfig; TEST(KeyframeIntervalSettingsTest, ParsesMinKeyframeSendIntervalMs) { - EXPECT_FALSE(KeyframeIntervalSettings(ExplicitKeyValueConfig("")) - .MinKeyframeSendIntervalMs()); + EXPECT_FALSE( + KeyframeIntervalSettings(FieldTrials("")).MinKeyframeSendIntervalMs()); - ExplicitKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-KeyframeInterval/min_keyframe_send_interval_ms:100/"); EXPECT_EQ(KeyframeIntervalSettings(field_trials).MinKeyframeSendIntervalMs(), 100); } TEST(KeyframeIntervalSettingsTest, DoesNotParseIncorrectValues) { - ExplicitKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-KeyframeInterval/min_keyframe_send_interval_ms:a/"); EXPECT_FALSE( KeyframeIntervalSettings(field_trials).MinKeyframeSendIntervalMs()); diff --git a/rtc_base/experiments/min_video_bitrate_experiment.cc b/rtc_base/experiments/min_video_bitrate_experiment.cc index 2bd8911f36..0b67490b38 100644 --- a/rtc_base/experiments/min_video_bitrate_experiment.cc +++ b/rtc_base/experiments/min_video_bitrate_experiment.cc @@ -10,9 +10,13 @@ #include "rtc_base/experiments/min_video_bitrate_experiment.h" +#include +#include #include #include "api/field_trials_view.h" +#include "api/units/data_rate.h" +#include "api/video/video_codec_type.h" #include "rtc_base/checks.h" #include "rtc_base/experiments/field_trial_parser.h" #include "rtc_base/logging.h" diff --git a/rtc_base/experiments/min_video_bitrate_experiment_unittest.cc b/rtc_base/experiments/min_video_bitrate_experiment_unittest.cc index 182669dc02..d9cb770691 100644 --- a/rtc_base/experiments/min_video_bitrate_experiment_unittest.cc +++ b/rtc_base/experiments/min_video_bitrate_experiment_unittest.cc @@ -12,19 +12,17 @@ #include +#include "api/field_trials.h" #include "api/units/data_rate.h" #include "api/video/video_codec_type.h" -#include "test/explicit_key_value_config.h" #include "test/gtest.h" namespace webrtc { namespace { -using test::ExplicitKeyValueConfig; - TEST(GetExperimentalMinVideoBitrateTest, NulloptForAllCodecsIfFieldTrialUndefined) { - ExplicitKeyValueConfig field_trials(""); + FieldTrials field_trials(""); EXPECT_EQ(GetExperimentalMinVideoBitrate(field_trials, kVideoCodecGeneric), std::nullopt); @@ -38,8 +36,7 @@ TEST(GetExperimentalMinVideoBitrateTest, TEST(GetExperimentalMinVideoBitrateTest, NulloptForAllCodecsIfFieldTrialDisabled) { - ExplicitKeyValueConfig field_trials( - "WebRTC-Video-MinVideoBitrate/Disabled,br:123kbps/"); + FieldTrials field_trials("WebRTC-Video-MinVideoBitrate/Disabled,br:123kbps/"); EXPECT_EQ(GetExperimentalMinVideoBitrate(field_trials, kVideoCodecGeneric), std::nullopt); @@ -52,8 +49,7 @@ TEST(GetExperimentalMinVideoBitrateTest, } TEST(GetExperimentalMinVideoBitrateTest, BrForAllCodecsIfDefined) { - ExplicitKeyValueConfig field_trials( - "WebRTC-Video-MinVideoBitrate/Enabled,br:123kbps/"); + FieldTrials field_trials("WebRTC-Video-MinVideoBitrate/Enabled,br:123kbps/"); EXPECT_EQ(GetExperimentalMinVideoBitrate(field_trials, kVideoCodecGeneric), DataRate::KilobitsPerSec(123)); @@ -66,7 +62,7 @@ TEST(GetExperimentalMinVideoBitrateTest, BrForAllCodecsIfDefined) { } TEST(GetExperimentalMinVideoBitrateTest, BrTrumpsSpecificCodecConfigs) { - ExplicitKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-MinVideoBitrate/" "Enabled,br:123kbps,vp8_br:100kbps,vp9_br:200kbps,h264_br:300kbps/"); @@ -82,7 +78,7 @@ TEST(GetExperimentalMinVideoBitrateTest, BrTrumpsSpecificCodecConfigs) { TEST(GetExperimentalMinVideoBitrateTest, SpecificCodecConfigsIgnoredIfExpDisabled) { - ExplicitKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-MinVideoBitrate/" "Disabled,vp8_br:100kbps,vp9_br:200kbps,h264_br:300kbps/"); @@ -97,7 +93,7 @@ TEST(GetExperimentalMinVideoBitrateTest, } TEST(GetExperimentalMinVideoBitrateTest, SpecificCodecConfigsUsedIfExpEnabled) { - ExplicitKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-MinVideoBitrate/" "Enabled,vp8_br:100kbps,vp9_br:200kbps,h264_br:300kbps/"); @@ -113,7 +109,7 @@ TEST(GetExperimentalMinVideoBitrateTest, SpecificCodecConfigsUsedIfExpEnabled) { TEST(GetExperimentalMinVideoBitrateTest, Vp8BitrateValueTakenFromFallbackIfAvailable) { - ExplicitKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-MinVideoBitrate/" "Enabled,vp8_br:100kbps,vp9_br:200kbps,h264_br:300kbps/" "WebRTC-VP8-Forced-Fallback-Encoder-v2/" @@ -125,7 +121,7 @@ TEST(GetExperimentalMinVideoBitrateTest, TEST(GetExperimentalMinVideoBitrateTest, NonVp8BitrateValuesTakenFromMinVideoBitrate) { - ExplicitKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-MinVideoBitrate/" "Enabled,vp8_br:100kbps,vp9_br:200kbps,h264_br:300kbps/" "WebRTC-VP8-Forced-Fallback-Encoder-v2/" diff --git a/rtc_base/experiments/normalize_simulcast_size_experiment.cc b/rtc_base/experiments/normalize_simulcast_size_experiment.cc index 0e54357176..3e949c56e1 100644 --- a/rtc_base/experiments/normalize_simulcast_size_experiment.cc +++ b/rtc_base/experiments/normalize_simulcast_size_experiment.cc @@ -12,6 +12,7 @@ #include +#include #include #include "api/field_trials_view.h" diff --git a/rtc_base/experiments/normalize_simulcast_size_experiment_unittest.cc b/rtc_base/experiments/normalize_simulcast_size_experiment_unittest.cc index afafa01176..65f8fbd8ef 100644 --- a/rtc_base/experiments/normalize_simulcast_size_experiment_unittest.cc +++ b/rtc_base/experiments/normalize_simulcast_size_experiment_unittest.cc @@ -10,37 +10,32 @@ #include "rtc_base/experiments/normalize_simulcast_size_experiment.h" -#include "test/explicit_key_value_config.h" +#include "api/field_trials.h" #include "test/gtest.h" namespace webrtc { -using test::ExplicitKeyValueConfig; - TEST(NormalizeSimulcastSizeExperimentTest, GetExponent) { - ExplicitKeyValueConfig field_trials( - "WebRTC-NormalizeSimulcastResolution/Enabled-2/"); + FieldTrials field_trials("WebRTC-NormalizeSimulcastResolution/Enabled-2/"); EXPECT_EQ(2, NormalizeSimulcastSizeExperiment::GetBase2Exponent(field_trials)); } TEST(NormalizeSimulcastSizeExperimentTest, GetExponentWithTwoParameters) { - ExplicitKeyValueConfig field_trials( - "WebRTC-NormalizeSimulcastResolution/Enabled-3-4/"); + FieldTrials field_trials("WebRTC-NormalizeSimulcastResolution/Enabled-3-4/"); EXPECT_EQ(3, NormalizeSimulcastSizeExperiment::GetBase2Exponent(field_trials)); } TEST(NormalizeSimulcastSizeExperimentTest, GetExponentFailsIfNotEnabled) { - ExplicitKeyValueConfig field_trials( - "WebRTC-NormalizeSimulcastResolution/Disabled/"); + FieldTrials field_trials("WebRTC-NormalizeSimulcastResolution/Disabled/"); EXPECT_FALSE( NormalizeSimulcastSizeExperiment::GetBase2Exponent(field_trials)); } TEST(NormalizeSimulcastSizeExperimentTest, GetExponentFailsForInvalidFieldTrial) { - ExplicitKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-NormalizeSimulcastResolution/Enabled-invalid/"); EXPECT_FALSE( NormalizeSimulcastSizeExperiment::GetBase2Exponent(field_trials)); @@ -49,8 +44,7 @@ TEST(NormalizeSimulcastSizeExperimentTest, TEST(NormalizeSimulcastSizeExperimentTest, GetExponentFailsForNegativeOutOfBoundValue) { // Supported range: [0, 5]. - ExplicitKeyValueConfig field_trials( - "WebRTC-NormalizeSimulcastResolution/Enabled--1/"); + FieldTrials field_trials("WebRTC-NormalizeSimulcastResolution/Enabled--1/"); EXPECT_FALSE( NormalizeSimulcastSizeExperiment::GetBase2Exponent(field_trials)); } @@ -58,8 +52,7 @@ TEST(NormalizeSimulcastSizeExperimentTest, TEST(NormalizeSimulcastSizeExperimentTest, GetExponentFailsForPositiveOutOfBoundValue) { // Supported range: [0, 5]. - ExplicitKeyValueConfig field_trials( - "WebRTC-NormalizeSimulcastResolution/Enabled-6/"); + FieldTrials field_trials("WebRTC-NormalizeSimulcastResolution/Enabled-6/"); EXPECT_FALSE( NormalizeSimulcastSizeExperiment::GetBase2Exponent(field_trials)); } diff --git a/rtc_base/experiments/quality_scaler_settings.cc b/rtc_base/experiments/quality_scaler_settings.cc index 0193a699ef..03a5ca118c 100644 --- a/rtc_base/experiments/quality_scaler_settings.cc +++ b/rtc_base/experiments/quality_scaler_settings.cc @@ -10,7 +10,10 @@ #include "rtc_base/experiments/quality_scaler_settings.h" +#include + #include "api/field_trials_view.h" +#include "rtc_base/experiments/field_trial_parser.h" #include "rtc_base/logging.h" namespace webrtc { diff --git a/rtc_base/experiments/quality_scaler_settings_unittest.cc b/rtc_base/experiments/quality_scaler_settings_unittest.cc index 06d0dab80a..3963308f13 100644 --- a/rtc_base/experiments/quality_scaler_settings_unittest.cc +++ b/rtc_base/experiments/quality_scaler_settings_unittest.cc @@ -10,14 +10,14 @@ #include "rtc_base/experiments/quality_scaler_settings.h" +#include "api/field_trials.h" #include "test/gtest.h" -#include "test/scoped_key_value_config.h" namespace webrtc { namespace { TEST(QualityScalerSettingsTest, ValuesNotSetByDefault) { - test::ScopedKeyValueConfig field_trials(""); + FieldTrials field_trials(""); const auto settings = QualityScalerSettings(field_trials); EXPECT_FALSE(settings.MinFrames()); EXPECT_FALSE(settings.InitialScaleFactor()); @@ -27,38 +27,38 @@ TEST(QualityScalerSettingsTest, ValuesNotSetByDefault) { } TEST(QualityScalerSettingsTest, ParseMinFrames) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-QualityScalerSettings/min_frames:100/"); EXPECT_EQ(100, QualityScalerSettings(field_trials).MinFrames()); } TEST(QualityScalerSettingsTest, ParseInitialScaleFactor) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-QualityScalerSettings/initial_scale_factor:1.5/"); EXPECT_EQ(1.5, QualityScalerSettings(field_trials).InitialScaleFactor()); } TEST(QualityScalerSettingsTest, ParseScaleFactor) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-QualityScalerSettings/scale_factor:1.1/"); EXPECT_EQ(1.1, QualityScalerSettings(field_trials).ScaleFactor()); } TEST(QualityScalerSettingsTest, ParseInitialBitrateInterval) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-QualityScalerSettings/initial_bitrate_interval_ms:1000/"); EXPECT_EQ(1000, QualityScalerSettings(field_trials).InitialBitrateIntervalMs()); } TEST(QualityScalerSettingsTest, ParseInitialBitrateFactor) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-QualityScalerSettings/initial_bitrate_factor:0.75/"); EXPECT_EQ(0.75, QualityScalerSettings(field_trials).InitialBitrateFactor()); } TEST(QualityScalerSettingsTest, ParseAll) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-QualityScalerSettings/" "min_frames:100,initial_scale_factor:1.5,scale_factor:0.9," "initial_bitrate_interval_ms:5500,initial_bitrate_factor:0.7/"); @@ -71,7 +71,7 @@ TEST(QualityScalerSettingsTest, ParseAll) { } TEST(QualityScalerSettingsTest, DoesNotParseIncorrectValue) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-QualityScalerSettings/" "min_frames:a,initial_scale_factor:b,scale_factor:c," "initial_bitrate_interval_ms:d,initial_bitrate_factor:e/"); @@ -84,7 +84,7 @@ TEST(QualityScalerSettingsTest, DoesNotParseIncorrectValue) { } TEST(QualityScalerSettingsTest, DoesNotReturnTooSmallValue) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-QualityScalerSettings/" "min_frames:0,initial_scale_factor:0.0,scale_factor:0.0," "initial_bitrate_interval_ms:-1,initial_bitrate_factor:0.0/"); diff --git a/rtc_base/experiments/quality_scaling_experiment.h b/rtc_base/experiments/quality_scaling_experiment.h index 0d197c14fe..ece099a627 100644 --- a/rtc_base/experiments/quality_scaling_experiment.h +++ b/rtc_base/experiments/quality_scaling_experiment.h @@ -13,6 +13,7 @@ #include #include "api/field_trials_view.h" +#include "api/video/video_codec_type.h" #include "api/video_codecs/video_encoder.h" namespace webrtc { diff --git a/rtc_base/experiments/quality_scaling_experiment_unittest.cc b/rtc_base/experiments/quality_scaling_experiment_unittest.cc index c8dab44565..65e92539de 100644 --- a/rtc_base/experiments/quality_scaling_experiment_unittest.cc +++ b/rtc_base/experiments/quality_scaling_experiment_unittest.cc @@ -10,8 +10,9 @@ #include "rtc_base/experiments/quality_scaling_experiment.h" +#include "api/field_trials.h" +#include "api/video/video_codec_type.h" #include "test/gtest.h" -#include "test/scoped_key_value_config.h" namespace webrtc { namespace { @@ -41,26 +42,25 @@ void ExpectEqualConfig(QualityScalingExperiment::Config a, #if !defined(WEBRTC_IOS) // TODO(bugs.webrtc.org/12401): investigate why QualityScaler kicks in on iOS. TEST(QualityScalingExperimentTest, DefaultEnabledWithoutFieldTrial) { - test::ScopedKeyValueConfig field_trials(""); + FieldTrials field_trials(""); EXPECT_TRUE(QualityScalingExperiment::Enabled(field_trials)); } #else TEST(QualityScalingExperimentTest, DefaultDisabledWithoutFieldTrialIOS) { - webrtc::test::ScopedKeyValueConfig field_trials(""); + FieldTrials field_trials(""); EXPECT_FALSE(QualityScalingExperiment::Enabled(field_trials)); } #endif TEST(QualityScalingExperimentTest, EnabledWithFieldTrial) { - test::ScopedKeyValueConfig field_trials( - "WebRTC-Video-QualityScaling/Enabled/"); + FieldTrials field_trials("WebRTC-Video-QualityScaling/Enabled/"); EXPECT_TRUE(QualityScalingExperiment::Enabled(field_trials)); } TEST(QualityScalingExperimentTest, ParseSettings) { const QualityScalingExperiment::Settings kExpected = {1, 2, 3, 4, 5, 6, 7, 8, 0.9f, 0.99f, 1}; - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-QualityScaling/Enabled-1,2,3,4,5,6,7,8,0.9,0.99,1/"); const auto settings = QualityScalingExperiment::ParseSettings(field_trials); EXPECT_TRUE(settings); @@ -70,25 +70,24 @@ TEST(QualityScalingExperimentTest, ParseSettings) { #if !defined(WEBRTC_IOS) // TODO(bugs.webrtc.org/12401): investigate why QualityScaler kicks in on iOS. TEST(QualityScalingExperimentTest, ParseSettingsUsesDefaultsWithoutFieldTrial) { - test::ScopedKeyValueConfig field_trials(""); + FieldTrials field_trials(""); // Uses some default hard coded values. EXPECT_TRUE(QualityScalingExperiment::ParseSettings(field_trials)); } #else TEST(QualityScalingExperimentTest, ParseSettingsFailsWithoutFieldTrial) { - webrtc::test::ScopedKeyValueConfig field_trials(""); + FieldTrials field_trials(""); EXPECT_FALSE(QualityScalingExperiment::ParseSettings(field_trials)); } #endif TEST(QualityScalingExperimentTest, ParseSettingsFailsWithInvalidFieldTrial) { - test::ScopedKeyValueConfig field_trials( - "WebRTC-Video-QualityScaling/Enabled-invalid/"); + FieldTrials field_trials("WebRTC-Video-QualityScaling/Enabled-invalid/"); EXPECT_FALSE(QualityScalingExperiment::ParseSettings(field_trials)); } TEST(QualityScalingExperimentTest, GetConfig) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-QualityScaling/Enabled-1,2,3,4,5,6,7,8,0.9,0.99,0/"); const auto config = QualityScalingExperiment::GetConfig(field_trials); EXPECT_EQ(0.9f, config.alpha_high); @@ -97,8 +96,7 @@ TEST(QualityScalingExperimentTest, GetConfig) { } TEST(QualityScalingExperimentTest, GetsDefaultConfigForInvalidFieldTrial) { - test::ScopedKeyValueConfig field_trials( - "WebRTC-Video-QualityScaling/Enabled-invalid/"); + FieldTrials field_trials("WebRTC-Video-QualityScaling/Enabled-invalid/"); const auto config = QualityScalingExperiment::GetConfig(field_trials); ExpectEqualConfig(config, QualityScalingExperiment::Config()); } @@ -106,14 +104,14 @@ TEST(QualityScalingExperimentTest, GetsDefaultConfigForInvalidFieldTrial) { TEST(QualityScalingExperimentTest, GetsDefaultAlphaForInvalidValue) { QualityScalingExperiment::Config expected_config; expected_config.use_all_drop_reasons = true; - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-QualityScaling/Enabled-1,2,3,4,5,6,7,8,0.99,0.9,1/"); const auto config = QualityScalingExperiment::GetConfig(field_trials); ExpectEqualConfig(config, expected_config); } TEST(QualityScalingExperimentTest, GetVp8Thresholds) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-QualityScaling/Enabled-1,2,3,4,5,6,0,0,0.9,0.99,1/"); const auto thresholds = QualityScalingExperiment::GetQpThresholds(kVideoCodecVP8, field_trials); @@ -123,7 +121,7 @@ TEST(QualityScalingExperimentTest, GetVp8Thresholds) { } TEST(QualityScalingExperimentTest, GetThresholdsFailsForInvalidVp8Value) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-QualityScaling/Enabled-0,0,3,4,5,6,7,8,0.9,0.99,1/"); const auto thresholds = QualityScalingExperiment::GetQpThresholds(kVideoCodecVP8, field_trials); @@ -131,7 +129,7 @@ TEST(QualityScalingExperimentTest, GetThresholdsFailsForInvalidVp8Value) { } TEST(QualityScalingExperimentTest, GetVp9Thresholds) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-QualityScaling/Enabled-1,2,3,4,5,6,0,0,0.9,0.99,1/"); const auto thresholds = QualityScalingExperiment::GetQpThresholds(kVideoCodecVP9, field_trials); @@ -141,7 +139,7 @@ TEST(QualityScalingExperimentTest, GetVp9Thresholds) { } TEST(QualityScalingExperimentTest, GetThresholdsFailsForInvalidVp9Value) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-QualityScaling/Enabled-1,2,0,0,5,6,7,8,0.9,0.99,1/"); const auto thresholds = QualityScalingExperiment::GetQpThresholds(kVideoCodecVP9, field_trials); @@ -149,7 +147,7 @@ TEST(QualityScalingExperimentTest, GetThresholdsFailsForInvalidVp9Value) { } TEST(QualityScalingExperimentTest, GetH264Thresholds) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-QualityScaling/Enabled-1,2,3,4,5,6,0,0,0.9,0.99,1/"); const auto thresholds = QualityScalingExperiment::GetQpThresholds(kVideoCodecH264, field_trials); @@ -159,7 +157,7 @@ TEST(QualityScalingExperimentTest, GetH264Thresholds) { } TEST(QualityScalingExperimentTest, GetThresholdsFailsForInvalidH264Value) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-QualityScaling/Enabled-1,2,3,4,0,0,7,8,0.9,0.99,1/"); const auto thresholds = QualityScalingExperiment::GetQpThresholds(kVideoCodecH264, field_trials); @@ -167,7 +165,7 @@ TEST(QualityScalingExperimentTest, GetThresholdsFailsForInvalidH264Value) { } TEST(QualityScalingExperimentTest, GetGenericThresholds) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-QualityScaling/Enabled-1,2,3,4,0,0,7,8,0.9,0.99,1/"); const auto thresholds = QualityScalingExperiment::GetQpThresholds( kVideoCodecGeneric, field_trials); @@ -177,7 +175,7 @@ TEST(QualityScalingExperimentTest, GetGenericThresholds) { } TEST(QualityScalingExperimentTest, GetThresholdsFailsForInvalidGenericValue) { - test::ScopedKeyValueConfig field_trials( + FieldTrials field_trials( "WebRTC-Video-QualityScaling/Enabled-1,2,3,4,5,6,0,0,0.9,0.99,1/"); const auto thresholds = QualityScalingExperiment::GetQpThresholds( kVideoCodecGeneric, field_trials); diff --git a/rtc_base/experiments/rate_control_settings.cc b/rtc_base/experiments/rate_control_settings.cc index 2aaf0e1aca..2d37c2d3fc 100644 --- a/rtc_base/experiments/rate_control_settings.cc +++ b/rtc_base/experiments/rate_control_settings.cc @@ -10,14 +10,18 @@ #include "rtc_base/experiments/rate_control_settings.h" -#include #include +#include +#include +#include #include -#include "absl/strings/match.h" +#include "absl/strings/string_view.h" +#include "api/field_trials_view.h" +#include "api/units/data_size.h" +#include "rtc_base/experiments/struct_parameters_parser.h" #include "rtc_base/logging.h" -#include "rtc_base/numerics/safe_conversions.h" namespace webrtc { diff --git a/rtc_base/experiments/rate_control_settings.h b/rtc_base/experiments/rate_control_settings.h index d48da1c45a..e62e61b15d 100644 --- a/rtc_base/experiments/rate_control_settings.h +++ b/rtc_base/experiments/rate_control_settings.h @@ -11,13 +11,14 @@ #ifndef RTC_BASE_EXPERIMENTS_RATE_CONTROL_SETTINGS_H_ #define RTC_BASE_EXPERIMENTS_RATE_CONTROL_SETTINGS_H_ +#include +#include #include +#include "absl/strings/string_view.h" #include "api/field_trials_view.h" #include "api/units/data_size.h" -#include "api/video_codecs/video_codec.h" #include "rtc_base/experiments/struct_parameters_parser.h" -#include "video/config/video_encoder_config.h" namespace webrtc { diff --git a/rtc_base/experiments/rate_control_settings_unittest.cc b/rtc_base/experiments/rate_control_settings_unittest.cc index 72470cbd7f..5f730b47f8 100644 --- a/rtc_base/experiments/rate_control_settings_unittest.cc +++ b/rtc_base/experiments/rate_control_settings_unittest.cc @@ -10,22 +10,20 @@ #include "rtc_base/experiments/rate_control_settings.h" -#include "api/video_codecs/video_codec.h" -#include "test/explicit_key_value_config.h" +#include "absl/strings/string_view.h" +#include "api/field_trials.h" #include "test/gmock.h" #include "test/gtest.h" -#include "video/config/video_encoder_config.h" namespace webrtc { namespace { -using test::ExplicitKeyValueConfig; using ::testing::DoubleEq; using ::testing::Optional; RateControlSettings ParseFrom(absl::string_view field_trials) { - return RateControlSettings(ExplicitKeyValueConfig(field_trials)); + return RateControlSettings(FieldTrials(field_trials)); } TEST(RateControlSettingsTest, CongestionWindow) { diff --git a/rtc_base/experiments/stable_target_rate_experiment.cc b/rtc_base/experiments/stable_target_rate_experiment.cc deleted file mode 100644 index d554b5d355..0000000000 --- a/rtc_base/experiments/stable_target_rate_experiment.cc +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright 2019 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 "rtc_base/experiments/stable_target_rate_experiment.h" - -#include "api/field_trials_view.h" -#include "rtc_base/experiments/field_trial_parser.h" - -namespace webrtc { -namespace { -constexpr char kFieldTrialName[] = "WebRTC-StableTargetRate"; -} // namespace - -StableTargetRateExperiment::StableTargetRateExperiment( - const FieldTrialsView& key_value_config) - : enabled_("enabled", false), - video_hysteresis_factor_("video_hysteresis_factor", - /*default_value=*/1.2), - screenshare_hysteresis_factor_("screenshare_hysteresis_factor", - /*default_value=*/1.35) { - ParseFieldTrial( - {&enabled_, &video_hysteresis_factor_, &screenshare_hysteresis_factor_}, - key_value_config.Lookup(kFieldTrialName)); -} - -StableTargetRateExperiment::StableTargetRateExperiment( - const StableTargetRateExperiment&) = default; -StableTargetRateExperiment::StableTargetRateExperiment( - StableTargetRateExperiment&&) = default; - -bool StableTargetRateExperiment::IsEnabled() const { - return enabled_.Get(); -} - -double StableTargetRateExperiment::GetVideoHysteresisFactor() const { - return video_hysteresis_factor_.Get(); -} - -double StableTargetRateExperiment::GetScreenshareHysteresisFactor() const { - return screenshare_hysteresis_factor_.Get(); -} - -} // namespace webrtc diff --git a/rtc_base/experiments/stable_target_rate_experiment.h b/rtc_base/experiments/stable_target_rate_experiment.h deleted file mode 100644 index ced3eb8b81..0000000000 --- a/rtc_base/experiments/stable_target_rate_experiment.h +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 2019 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 RTC_BASE_EXPERIMENTS_STABLE_TARGET_RATE_EXPERIMENT_H_ -#define RTC_BASE_EXPERIMENTS_STABLE_TARGET_RATE_EXPERIMENT_H_ - -#include "api/field_trials_view.h" -#include "rtc_base/experiments/field_trial_parser.h" - -namespace webrtc { - -class StableTargetRateExperiment { - public: - explicit StableTargetRateExperiment(const FieldTrialsView& field_trials); - StableTargetRateExperiment(const StableTargetRateExperiment&); - StableTargetRateExperiment(StableTargetRateExperiment&&); - - bool IsEnabled() const; - double GetVideoHysteresisFactor() const; - double GetScreenshareHysteresisFactor() const; - - private: - FieldTrialParameter enabled_; - FieldTrialParameter video_hysteresis_factor_; - FieldTrialParameter screenshare_hysteresis_factor_; -}; - -} // namespace webrtc - -#endif // RTC_BASE_EXPERIMENTS_STABLE_TARGET_RATE_EXPERIMENT_H_ diff --git a/rtc_base/experiments/stable_target_rate_experiment_unittest.cc b/rtc_base/experiments/stable_target_rate_experiment_unittest.cc deleted file mode 100644 index f4b63c30b6..0000000000 --- a/rtc_base/experiments/stable_target_rate_experiment_unittest.cc +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright 2019 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 "rtc_base/experiments/stable_target_rate_experiment.h" - -#include "test/explicit_key_value_config.h" -#include "test/gtest.h" - -namespace webrtc { - -using test::ExplicitKeyValueConfig; - -TEST(StableBweExperimentTest, Default) { - ExplicitKeyValueConfig field_trials(""); - StableTargetRateExperiment config(field_trials); - EXPECT_FALSE(config.IsEnabled()); - EXPECT_EQ(config.GetVideoHysteresisFactor(), 1.2); - EXPECT_EQ(config.GetScreenshareHysteresisFactor(), 1.35); -} - -TEST(StableBweExperimentTest, EnabledNoHysteresis) { - ExplicitKeyValueConfig field_trials("WebRTC-StableTargetRate/enabled:true/"); - - StableTargetRateExperiment config(field_trials); - EXPECT_TRUE(config.IsEnabled()); - EXPECT_EQ(config.GetVideoHysteresisFactor(), 1.2); - EXPECT_EQ(config.GetScreenshareHysteresisFactor(), 1.35); -} - -TEST(StableBweExperimentTest, EnabledWithHysteresis) { - ExplicitKeyValueConfig field_trials( - "WebRTC-StableTargetRate/" - "enabled:true," - "video_hysteresis_factor:1.1," - "screenshare_hysteresis_factor:1.2/"); - - StableTargetRateExperiment config(field_trials); - EXPECT_TRUE(config.IsEnabled()); - EXPECT_EQ(config.GetVideoHysteresisFactor(), 1.1); - EXPECT_EQ(config.GetScreenshareHysteresisFactor(), 1.2); -} - -TEST(StableBweExperimentTest, HysteresisOverrideVideoRateHystersis) { - ExplicitKeyValueConfig field_trials( - "WebRTC-StableTargetRate/" - "enabled:true," - "video_hysteresis_factor:1.1," - "screenshare_hysteresis_factor:1.2/" - "WebRTC-VideoRateControl/video_hysteresis:1.3," - "screenshare_hysteresis:1.4/"); - - StableTargetRateExperiment config(field_trials); - EXPECT_TRUE(config.IsEnabled()); - EXPECT_EQ(config.GetVideoHysteresisFactor(), 1.1); - EXPECT_EQ(config.GetScreenshareHysteresisFactor(), 1.2); -} - -} // namespace webrtc diff --git a/rtc_base/experiments/struct_parameters_parser.cc b/rtc_base/experiments/struct_parameters_parser.cc index f999601afe..71fa1eec57 100644 --- a/rtc_base/experiments/struct_parameters_parser.cc +++ b/rtc_base/experiments/struct_parameters_parser.cc @@ -10,9 +10,21 @@ #include "rtc_base/experiments/struct_parameters_parser.h" #include +#include +#include +#include +#include +#include +#include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" +#include "api/units/data_rate.h" +#include "api/units/data_size.h" +#include "api/units/time_delta.h" +#include "rtc_base/experiments/field_trial_parser.h" +#include "rtc_base/experiments/field_trial_units.h" #include "rtc_base/logging.h" +#include "rtc_base/string_encode.h" namespace webrtc { namespace { diff --git a/rtc_base/experiments/struct_parameters_parser.h b/rtc_base/experiments/struct_parameters_parser.h index 3d0b05bdc2..d5178bb356 100644 --- a/rtc_base/experiments/struct_parameters_parser.h +++ b/rtc_base/experiments/struct_parameters_parser.h @@ -10,8 +10,6 @@ #ifndef RTC_BASE_EXPERIMENTS_STRUCT_PARAMETERS_PARSER_H_ #define RTC_BASE_EXPERIMENTS_STRUCT_PARAMETERS_PARSER_H_ -#include -#include #include #include #include @@ -20,9 +18,9 @@ #include "absl/memory/memory.h" #include "absl/strings/string_view.h" -#include "rtc_base/experiments/field_trial_parser.h" -#include "rtc_base/experiments/field_trial_units.h" -#include "rtc_base/string_encode.h" +#include "api/units/data_rate.h" +#include "api/units/data_size.h" +#include "api/units/time_delta.h" namespace webrtc { namespace struct_parser_impl { diff --git a/rtc_base/experiments/struct_parameters_parser_unittest.cc b/rtc_base/experiments/struct_parameters_parser_unittest.cc index 918bcb6e28..d5c54a04e5 100644 --- a/rtc_base/experiments/struct_parameters_parser_unittest.cc +++ b/rtc_base/experiments/struct_parameters_parser_unittest.cc @@ -9,7 +9,11 @@ */ #include "rtc_base/experiments/struct_parameters_parser.h" -#include "rtc_base/gunit.h" +#include +#include + +#include "api/units/time_delta.h" +#include "test/gtest.h" namespace webrtc { namespace { diff --git a/rtc_base/fake_clock.h b/rtc_base/fake_clock.h index 66050c766c..a529b6cebd 100644 --- a/rtc_base/fake_clock.h +++ b/rtc_base/fake_clock.h @@ -24,7 +24,7 @@ namespace webrtc { // Fake clock for use with unit tests, which does not tick on its own. // Starts at time 0. // -// TODO(deadbeef): Unify with webrtc::SimulatedClock. +// TODO(deadbeef): Unify with SimulatedClock. class FakeClock : public ClockInterface { public: FakeClock() = default; diff --git a/rtc_base/fake_clock_unittest.cc b/rtc_base/fake_clock_unittest.cc index e138b74c75..5b5607a5be 100644 --- a/rtc_base/fake_clock_unittest.cc +++ b/rtc_base/fake_clock_unittest.cc @@ -10,6 +10,11 @@ #include "rtc_base/fake_clock.h" +#include + +#include "api/units/time_delta.h" +#include "api/units/timestamp.h" +#include "rtc_base/time_utils.h" #include "test/gtest.h" namespace webrtc { diff --git a/rtc_base/fake_network.h b/rtc_base/fake_network.h index b8c22136d9..7fede142c8 100644 --- a/rtc_base/fake_network.h +++ b/rtc_base/fake_network.h @@ -109,7 +109,7 @@ class FakeNetworkManager : public NetworkManagerBase { using NetworkManagerBase::set_default_local_addresses; using NetworkManagerBase::set_enumeration_permission; - // webrtc::NetworkManager override. + // NetworkManager override. MdnsResponderInterface* GetMdnsResponder() const override { return mdns_responder_.get(); } @@ -131,8 +131,7 @@ class FakeNetworkManager : public NetworkManagerBase { } else if (it->socket_address.ipaddr().family() == AF_INET6) { prefix_length = kFakeIPv6NetworkPrefixLength; } - IPAddress prefix = - webrtc::TruncateIP(it->socket_address.ipaddr(), prefix_length); + IPAddress prefix = TruncateIP(it->socket_address.ipaddr(), prefix_length); auto net = std::make_unique( it->socket_address.hostname(), it->socket_address.hostname(), prefix, prefix_length, it->adapter_type); diff --git a/rtc_base/file_rotating_stream_unittest.cc b/rtc_base/file_rotating_stream_unittest.cc index 4ee54dc0a4..50a0fe96d6 100644 --- a/rtc_base/file_rotating_stream_unittest.cc +++ b/rtc_base/file_rotating_stream_unittest.cc @@ -18,7 +18,6 @@ #include #include "absl/strings/string_view.h" -#include "rtc_base/arraysize.h" #include "rtc_base/system/file_wrapper.h" #include "test/gtest.h" #include "test/testsupport/file_utils.h" @@ -149,20 +148,19 @@ TEST_F(MAYBE_FileRotatingStreamTest, WriteAndRead) { // The test is set up to create three log files of length 2. Write and check // contents. std::string messages[3] = {"aa", "bb", "cc"}; - for (size_t i = 0; i < arraysize(messages); ++i) { - const std::string& message = messages[i]; + for (const std::string& message : messages) { WriteAndFlush(message.c_str(), message.size()); // Since the max log size is 2, we will be causing rotation. Read from the // next file. VerifyFileContents(message, stream_->GetFilePath(1)); } // Check that exactly three files exist. - for (size_t i = 0; i < arraysize(messages); ++i) { + for (size_t i = 0; i < std::size(messages); ++i) { EXPECT_TRUE(test::FileExists(stream_->GetFilePath(i))); } std::string message("d"); WriteAndFlush(message.c_str(), message.size()); - for (size_t i = 0; i < arraysize(messages); ++i) { + for (size_t i = 0; i < std::size(messages); ++i) { EXPECT_TRUE(test::FileExists(stream_->GetFilePath(i))); } // TODO(tkchin): Maybe check all the files in the dir. @@ -183,8 +181,7 @@ TEST_F(MAYBE_FileRotatingStreamTest, WriteWithoutDelimiterAndRead) { // The test is set up to create three log files of length 2. Write and check // contents. std::string messages[3] = {"aa", "bb", "cc"}; - for (size_t i = 0; i < arraysize(messages); ++i) { - const std::string& message = messages[i]; + for (const std::string& message : messages) { WriteAndFlush(message.c_str(), message.size()); } std::string message("d"); @@ -206,8 +203,7 @@ TEST_F(MAYBE_FileRotatingStreamTest, WriteAndReadWithoutDelimiter) { // The test is set up to create three log files of length 2. Write and check // contents. std::string messages[3] = {"aa", "bb", "cc"}; - for (size_t i = 0; i < arraysize(messages); ++i) { - const std::string& message = messages[i]; + for (const std::string& message : messages) { WriteAndFlush(message.c_str(), message.size()); } std::string message("d"); @@ -338,13 +334,13 @@ TEST_F(MAYBE_CallSessionFileRotatingStreamTest, WriteAndReadLarge) { } const int expected_vals[] = {0, 1, 2, 6, 7}; - const size_t expected_size = buffer_size * arraysize(expected_vals); + const size_t expected_size = buffer_size * std::size(expected_vals); CallSessionFileRotatingStreamReader reader(dir_path_); EXPECT_EQ(reader.GetSize(), expected_size); std::unique_ptr contents(new uint8_t[expected_size + 1]); EXPECT_EQ(reader.ReadAll(contents.get(), expected_size + 1), expected_size); - for (size_t i = 0; i < arraysize(expected_vals); ++i) { + for (size_t i = 0; i < std::size(expected_vals); ++i) { const uint8_t* block = contents.get() + i * buffer_size; bool match = true; for (size_t j = 0; j < buffer_size; j++) { @@ -372,14 +368,14 @@ TEST_F(MAYBE_CallSessionFileRotatingStreamTest, WriteAndReadFirstHalf) { } const int expected_vals[] = {0, 1}; - const size_t expected_size = buffer_size * arraysize(expected_vals); + const size_t expected_size = buffer_size * std::size(expected_vals); CallSessionFileRotatingStreamReader reader(dir_path_); EXPECT_EQ(reader.GetSize(), expected_size); std::unique_ptr contents(new uint8_t[expected_size + 1]); EXPECT_EQ(reader.ReadAll(contents.get(), expected_size + 1), expected_size); - for (size_t i = 0; i < arraysize(expected_vals); ++i) { + for (size_t i = 0; i < std::size(expected_vals); ++i) { const uint8_t* block = contents.get() + i * buffer_size; bool match = true; for (size_t j = 0; j < buffer_size; j++) { diff --git a/rtc_base/firewall_socket_server.cc b/rtc_base/firewall_socket_server.cc index 24b1ec8d11..ab8c331d82 100644 --- a/rtc_base/firewall_socket_server.cc +++ b/rtc_base/firewall_socket_server.cc @@ -14,12 +14,19 @@ #include #include -#include +#include +#include #include "absl/algorithm/container.h" +#include "api/units/time_delta.h" #include "rtc_base/async_socket.h" #include "rtc_base/checks.h" +#include "rtc_base/ip_address.h" #include "rtc_base/logging.h" +#include "rtc_base/socket.h" +#include "rtc_base/socket_address.h" +#include "rtc_base/socket_server.h" +#include "rtc_base/synchronization/mutex.h" namespace webrtc { diff --git a/rtc_base/firewall_socket_server.h b/rtc_base/firewall_socket_server.h index 1aa613598a..18d6862df3 100644 --- a/rtc_base/firewall_socket_server.h +++ b/rtc_base/firewall_socket_server.h @@ -13,6 +13,7 @@ #include +#include "api/units/time_delta.h" #include "rtc_base/ip_address.h" #include "rtc_base/socket.h" #include "rtc_base/socket_address.h" diff --git a/rtc_base/frequency_tracker.cc b/rtc_base/frequency_tracker.cc index d99c67b907..930e94551b 100644 --- a/rtc_base/frequency_tracker.cc +++ b/rtc_base/frequency_tracker.cc @@ -10,6 +10,7 @@ #include "rtc_base/frequency_tracker.h" +#include #include #include "api/units/frequency.h" diff --git a/rtc_base/frequency_tracker_unittest.cc b/rtc_base/frequency_tracker_unittest.cc index af9eeffa19..dea8f3e317 100644 --- a/rtc_base/frequency_tracker_unittest.cc +++ b/rtc_base/frequency_tracker_unittest.cc @@ -10,6 +10,7 @@ #include "rtc_base/frequency_tracker.h" +#include #include #include #include diff --git a/rtc_base/ifaddrs_converter.cc b/rtc_base/ifaddrs_converter.cc index 8b50e3d508..b9b0b6c021 100644 --- a/rtc_base/ifaddrs_converter.cc +++ b/rtc_base/ifaddrs_converter.cc @@ -11,6 +11,7 @@ #include "rtc_base/ifaddrs_converter.h" #include "rtc_base/ip_address.h" +#include "rtc_base/net_helpers.h" namespace webrtc { diff --git a/rtc_base/internal/default_socket_server.cc b/rtc_base/internal/default_socket_server.cc index 043c2ce850..1ebe391a2c 100644 --- a/rtc_base/internal/default_socket_server.cc +++ b/rtc_base/internal/default_socket_server.cc @@ -24,7 +24,7 @@ namespace webrtc { std::unique_ptr CreateDefaultSocketServer() { #if defined(__native_client__) - return std::unique_ptr(new webrtc::NullSocketServer); + return std::unique_ptr(new NullSocketServer); #else return std::unique_ptr(new PhysicalSocketServer); #endif diff --git a/rtc_base/ip_address.h b/rtc_base/ip_address.h index 83074cc5a2..efcabcbaae 100644 --- a/rtc_base/ip_address.h +++ b/rtc_base/ip_address.h @@ -13,7 +13,7 @@ #include #if defined(WEBRTC_POSIX) -#include +#include // IWYU pragma: keep #include #include // IWYU pragma: export @@ -48,6 +48,23 @@ enum IPv6AddressFlag { IPV6_ADDRESS_FLAG_DEPRECATED = 1 << 1, }; +// Used for metrics; Entries should not be renumbered and numeric values should +// never be reused. +enum class IPAddressType { + // IP Address not yet resolved. + kUnknown = 0, + // Missing or any IP Address i.e. 0.0.0.0 or ::. + kAny = 1, + // 127.0.0.1 or ::1. + kLoopback = 2, + // For v4: 127.0.0.0/8 10.0.0.0/8 192.168.0.0/16 172.16.0.0/12. + // For v6: FE80::/16 and ::1. + kPrivate = 3, + // Addresses not covered by the above. + kPublic = 4, + kMaxValue = kPublic, +}; + // Version-agnostic IP address class, wraps a union of in_addr and in6_addr. class RTC_EXPORT IPAddress { public: @@ -62,7 +79,7 @@ class RTC_EXPORT IPAddress { explicit IPAddress(uint32_t ip_in_host_byte_order) : family_(AF_INET) { memset(&u_, 0, sizeof(u_)); - u_.ip4.s_addr = webrtc::HostToNetwork32(ip_in_host_byte_order); + u_.ip4.s_addr = HostToNetwork32(ip_in_host_byte_order); } IPAddress(const IPAddress& other) : family_(other.family_) { diff --git a/rtc_base/logging.h b/rtc_base/logging.h index b011acbefa..c87e707ebc 100644 --- a/rtc_base/logging.h +++ b/rtc_base/logging.h @@ -51,13 +51,13 @@ #include #include +#include #include #include // no-presubmit-check TODO(webrtc:8982) #include #include #include -#include "absl/base/attributes.h" #include "absl/strings/has_absl_stringify.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" @@ -65,7 +65,6 @@ #include "rtc_base/platform_thread_types.h" #include "rtc_base/strings/string_builder.h" #include "rtc_base/system/inline.h" -#include "rtc_base/type_traits.h" #if !defined(NDEBUG) || defined(DLOG_ALWAYS_ON) #define RTC_DLOG_IS_ON 1 diff --git a/rtc_base/logging_unittest.cc b/rtc_base/logging_unittest.cc index de250403c9..47c2deea70 100644 --- a/rtc_base/logging_unittest.cc +++ b/rtc_base/logging_unittest.cc @@ -12,10 +12,11 @@ #if RTC_LOG_ENABLED() +#include +#include #include #include "absl/strings/string_view.h" -#include "rtc_base/arraysize.h" #include "rtc_base/checks.h" #include "rtc_base/platform_thread.h" #include "rtc_base/time_utils.h" @@ -27,6 +28,7 @@ namespace webrtc { namespace { using ::testing::HasSubstr; +using ::testing::StartsWith; #if defined(WEBRTC_WIN) constexpr char kFakeFilePath[] = "some\\path\\myfile.cc"; @@ -264,10 +266,7 @@ TEST(LogTest, CheckExtraErrorField) { 0xD); log_msg.stream() << "This gets added at dtor time"; - const std::string& extra = log_msg.get_extra(); - const size_t length_to_check = arraysize("[0x12345678]") - 1; - ASSERT_GE(extra.length(), length_to_check); - EXPECT_EQ(std::string("[0x0000000D]"), extra.substr(0, length_to_check)); + EXPECT_THAT(log_msg.get_extra(), StartsWith("[0x0000000D]")); } TEST(LogTest, CheckFilePathParsed) { diff --git a/rtc_base/mdns_responder_interface.h b/rtc_base/mdns_responder_interface.h index fb4c1c94cc..efa6daf96a 100644 --- a/rtc_base/mdns_responder_interface.h +++ b/rtc_base/mdns_responder_interface.h @@ -12,7 +12,6 @@ #define RTC_BASE_MDNS_RESPONDER_INTERFACE_H_ #include -#include #include "absl/strings/string_view.h" #include "rtc_base/ip_address.h" @@ -24,7 +23,7 @@ namespace webrtc { class MdnsResponderInterface { public: using NameCreatedCallback = - std::function; + std::function; using NameRemovedCallback = std::function; MdnsResponderInterface() = default; diff --git a/rtc_base/memory/aligned_malloc_unittest.cc b/rtc_base/memory/aligned_malloc_unittest.cc index 5c3f02d15c..56ec95df1b 100644 --- a/rtc_base/memory/aligned_malloc_unittest.cc +++ b/rtc_base/memory/aligned_malloc_unittest.cc @@ -10,6 +10,7 @@ #include "rtc_base/memory/aligned_malloc.h" +#include #include #ifdef _WIN32 diff --git a/rtc_base/memory/always_valid_pointer.h b/rtc_base/memory/always_valid_pointer.h index 4e68104b55..b00d68a94f 100644 --- a/rtc_base/memory/always_valid_pointer.h +++ b/rtc_base/memory/always_valid_pointer.h @@ -10,7 +10,9 @@ #ifndef RTC_BASE_MEMORY_ALWAYS_VALID_POINTER_H_ #define RTC_BASE_MEMORY_ALWAYS_VALID_POINTER_H_ +#include #include +#include #include #include "rtc_base/checks.h" diff --git a/rtc_base/memory/always_valid_pointer_unittest.cc b/rtc_base/memory/always_valid_pointer_unittest.cc index a228c102d0..0cf6c58165 100644 --- a/rtc_base/memory/always_valid_pointer_unittest.cc +++ b/rtc_base/memory/always_valid_pointer_unittest.cc @@ -10,7 +10,9 @@ #include "rtc_base/memory/always_valid_pointer.h" +#include #include +#include #include "test/gtest.h" @@ -32,7 +34,7 @@ TEST(AlwaysValidPointerTest, DefaultToSubclass) { struct B : public A { int b = 0; explicit B(int val) : b(val) {} - virtual ~B() {} + ~B() override {} int f() override { return b; } }; AlwaysValidPointer ptr(nullptr, 3); diff --git a/rtc_base/memory/fifo_buffer.h b/rtc_base/memory/fifo_buffer.h index a36717d1cb..a153ddf9cc 100644 --- a/rtc_base/memory/fifo_buffer.h +++ b/rtc_base/memory/fifo_buffer.h @@ -84,11 +84,10 @@ class FifoBuffer final : public StreamInterface { private: void PostEvent(int events, int err) { RTC_DCHECK_RUN_ON(owner_); - owner_->PostTask( - webrtc::SafeTask(task_safety_.flag(), [this, events, err]() { - RTC_DCHECK_RUN_ON(&callback_sequence_); - FireEvent(events, err); - })); + owner_->PostTask(SafeTask(task_safety_.flag(), [this, events, err]() { + RTC_DCHECK_RUN_ON(&callback_sequence_); + FireEvent(events, err); + })); } // Helper method that implements Read. Caller must acquire a lock diff --git a/rtc_base/message_digest_unittest.cc b/rtc_base/message_digest_unittest.cc index 78962607d2..d4c6add4e8 100644 --- a/rtc_base/message_digest_unittest.cc +++ b/rtc_base/message_digest_unittest.cc @@ -13,6 +13,9 @@ #include #include +#include +#include + #include "absl/strings/string_view.h" #include "rtc_base/string_encode.h" #include "test/gtest.h" diff --git a/rtc_base/network.cc b/rtc_base/network.cc index edb78eb4a4..5a0f0df743 100644 --- a/rtc_base/network.cc +++ b/rtc_base/network.cc @@ -201,15 +201,14 @@ bool ShouldAdapterChangeTriggerNetworkChange(AdapterType old_type, } #if defined(WEBRTC_WIN) -bool IpAddressAttributesEnabled(const webrtc::FieldTrialsView* field_trials) { +bool IpAddressAttributesEnabled(const FieldTrialsView* field_trials) { // Field trial key reserved in bugs.webrtc.org/14334 if (field_trials && field_trials->IsEnabled("WebRTC-IPv6NetworkResolutionFixes")) { - webrtc::FieldTrialParameter ip_address_attributes_enabled( + FieldTrialParameter ip_address_attributes_enabled( "IpAddressAttributesEnabled", false); - webrtc::ParseFieldTrial( - {&ip_address_attributes_enabled}, - field_trials->Lookup("WebRTC-IPv6NetworkResolutionFixes")); + ParseFieldTrial({&ip_address_attributes_enabled}, + field_trials->Lookup("WebRTC-IPv6NetworkResolutionFixes")); return ip_address_attributes_enabled; } return false; @@ -628,7 +627,7 @@ void BasicNetworkManager::ConvertIfAddrs( continue; } // Convert to InterfaceAddress. - // TODO(webrtc:13114): Convert ConvertIfAddrs to use webrtc::Netmask. + // TODO(webrtc:13114): Convert ConvertIfAddrs to use Netmask. if (!ifaddrs_converter->ConvertIfAddrsToIPAddress(cursor, &ip, &mask)) { continue; } @@ -887,7 +886,7 @@ bool BasicNetworkManager::CreateNetworks( adapter_type = ADAPTER_TYPE_VPN; } if (adapter_type != ADAPTER_TYPE_VPN && - IsVpnMacAddress(webrtc::ArrayView( + IsVpnMacAddress(ArrayView( reinterpret_cast( adapter_addrs->PhysicalAddress), adapter_addrs->PhysicalAddressLength))) { diff --git a/rtc_base/network.h b/rtc_base/network.h index f8ccfc754a..c87142e500 100644 --- a/rtc_base/network.h +++ b/rtc_base/network.h @@ -52,7 +52,7 @@ extern const char kPublicIPv6Host[]; class Network; // By default, ignore loopback interfaces on the host. -const int kDefaultNetworkIgnoreMask = webrtc::ADAPTER_TYPE_LOOPBACK; +const int kDefaultNetworkIgnoreMask = ADAPTER_TYPE_LOOPBACK; namespace webrtc_network_internal { bool CompareNetworks(const std::unique_ptr& a, @@ -201,7 +201,7 @@ class RTC_EXPORT Network { description, prefix, prefix_length, - webrtc::ADAPTER_TYPE_UNKNOWN) {} + ADAPTER_TYPE_UNKNOWN) {} Network(absl::string_view name, absl::string_view description, @@ -213,7 +213,7 @@ class RTC_EXPORT Network { ~Network(); // This signal is fired whenever type() or underlying_type_for_vpn() changes. - // Mutable, to support connecting on the const Network passed to webrtc::Port + // Mutable, to support connecting on the const Network passed to Port // constructor. mutable sigslot::signal1 SignalTypeChanged; @@ -314,8 +314,8 @@ class RTC_EXPORT Network { return; } type_ = type; - if (type != webrtc::ADAPTER_TYPE_VPN) { - underlying_type_for_vpn_ = webrtc::ADAPTER_TYPE_UNKNOWN; + if (type != ADAPTER_TYPE_VPN) { + underlying_type_for_vpn_ = ADAPTER_TYPE_UNKNOWN; } SignalTypeChanged(this); } @@ -328,17 +328,17 @@ class RTC_EXPORT Network { SignalTypeChanged(this); } - bool IsVpn() const { return type_ == webrtc::ADAPTER_TYPE_VPN; } + bool IsVpn() const { return type_ == ADAPTER_TYPE_VPN; } bool IsCellular() const { return IsCellular(type_); } static bool IsCellular(AdapterType type) { switch (type) { - case webrtc::ADAPTER_TYPE_CELLULAR: - case webrtc::ADAPTER_TYPE_CELLULAR_2G: - case webrtc::ADAPTER_TYPE_CELLULAR_3G: - case webrtc::ADAPTER_TYPE_CELLULAR_4G: - case webrtc::ADAPTER_TYPE_CELLULAR_5G: + case ADAPTER_TYPE_CELLULAR: + case ADAPTER_TYPE_CELLULAR_2G: + case ADAPTER_TYPE_CELLULAR_3G: + case ADAPTER_TYPE_CELLULAR_4G: + case ADAPTER_TYPE_CELLULAR_5G: return true; default: return false; @@ -398,7 +398,7 @@ class RTC_EXPORT Network { int scope_id_; bool ignored_; AdapterType type_; - AdapterType underlying_type_for_vpn_ = webrtc::ADAPTER_TYPE_UNKNOWN; + AdapterType underlying_type_for_vpn_ = ADAPTER_TYPE_UNKNOWN; int preference_; bool active_ = true; uint16_t id_ = 0; diff --git a/rtc_base/network/received_packet.h b/rtc_base/network/received_packet.h index 5de54cd1c2..b0cee33248 100644 --- a/rtc_base/network/received_packet.h +++ b/rtc_base/network/received_packet.h @@ -38,24 +38,20 @@ class RTC_EXPORT ReceivedIpPacket { // Caller must keep memory pointed to by payload and address valid for the // lifetime of this ReceivedPacket. ReceivedIpPacket(ArrayView payload, - const webrtc::SocketAddress& source_address, - std::optional arrival_time = std::nullopt, + const SocketAddress& source_address, + std::optional arrival_time = std::nullopt, EcnMarking ecn = EcnMarking::kNotEct, DecryptionInfo decryption = kNotDecrypted); ReceivedIpPacket CopyAndSet(DecryptionInfo decryption_info) const; // Address/port of the packet sender. - const webrtc::SocketAddress& source_address() const { - return source_address_; - } + const SocketAddress& source_address() const { return source_address_; } ArrayView payload() const { return payload_; } // Timestamp when this packet was received. Not available on all socket // implementations. - std::optional arrival_time() const { - return arrival_time_; - } + std::optional arrival_time() const { return arrival_time_; } // L4S Explicit Congestion Notification. EcnMarking ecn() const { return ecn_; } @@ -66,7 +62,7 @@ class RTC_EXPORT ReceivedIpPacket { const char* data, size_t size, int64_t packet_time_us, - const webrtc::SocketAddress& addr = webrtc::SocketAddress()) { + const SocketAddress& addr = SocketAddress()) { return CreateFromLegacy(reinterpret_cast(data), size, packet_time_us, addr); } @@ -75,12 +71,12 @@ class RTC_EXPORT ReceivedIpPacket { const uint8_t* data, size_t size, int64_t packet_time_us, - const webrtc::SocketAddress& = webrtc::SocketAddress()); + const SocketAddress& = SocketAddress()); private: ArrayView payload_; - std::optional arrival_time_; - const webrtc::SocketAddress& source_address_; + std::optional arrival_time_; + const SocketAddress& source_address_; EcnMarking ecn_; DecryptionInfo decryption_info_; }; diff --git a/rtc_base/network_constants.cc b/rtc_base/network_constants.cc index 7f81951122..9c5666020b 100644 --- a/rtc_base/network_constants.cc +++ b/rtc_base/network_constants.cc @@ -10,6 +10,8 @@ #include "rtc_base/network_constants.h" +#include + #include "rtc_base/checks.h" namespace webrtc { diff --git a/rtc_base/network_monitor.h b/rtc_base/network_monitor.h index f954a4db22..02dc830bbb 100644 --- a/rtc_base/network_monitor.h +++ b/rtc_base/network_monitor.h @@ -77,7 +77,7 @@ class NetworkMonitorInterface { AdapterType adapter_type; // Is ADAPTER_TYPE_UNKNOWN unless adapter_type == ADAPTER_TYPE_VPN. - AdapterType underlying_type_for_vpn = webrtc::ADAPTER_TYPE_UNKNOWN; + AdapterType underlying_type_for_vpn = ADAPTER_TYPE_UNKNOWN; // The OS/firmware specific preference of this interface. NetworkPreference network_preference = NetworkPreference::NEUTRAL; diff --git a/rtc_base/network_route.h b/rtc_base/network_route.h index 7f437cfbcb..153836c76c 100644 --- a/rtc_base/network_route.h +++ b/rtc_base/network_route.h @@ -42,7 +42,7 @@ class RouteEndpoint { // Used by tests. static RouteEndpoint CreateWithNetworkId(uint16_t network_id) { - return RouteEndpoint(webrtc::ADAPTER_TYPE_UNKNOWN, + return RouteEndpoint(ADAPTER_TYPE_UNKNOWN, /* adapter_id = */ 0, network_id, /* uses_turn = */ false); } @@ -58,7 +58,7 @@ class RouteEndpoint { bool operator==(const RouteEndpoint& other) const; private: - AdapterType adapter_type_ = webrtc::ADAPTER_TYPE_UNKNOWN; + AdapterType adapter_type_ = ADAPTER_TYPE_UNKNOWN; uint16_t adapter_id_ = 0; uint16_t network_id_ = 0; bool uses_turn_ = false; @@ -78,10 +78,10 @@ struct NetworkRoute { StringBuilder oss; oss << "[ connected: " << connected << " local: [ " << local.adapter_id() << "/" << local.network_id() << " " - << webrtc::AdapterTypeToString(local.adapter_type()) + << AdapterTypeToString(local.adapter_type()) << " turn: " << local.uses_turn() << " ] remote: [ " << remote.adapter_id() << "/" << remote.network_id() << " " - << webrtc::AdapterTypeToString(remote.adapter_type()) + << AdapterTypeToString(remote.adapter_type()) << " turn: " << remote.uses_turn() << " ] packet_overhead_bytes: " << packet_overhead << " ]"; return oss.Release(); diff --git a/rtc_base/network_unittest.cc b/rtc_base/network_unittest.cc index 35795edd20..dde29cbdb5 100644 --- a/rtc_base/network_unittest.cc +++ b/rtc_base/network_unittest.cc @@ -25,10 +25,12 @@ #include "api/array_view.h" #include "api/environment/environment.h" #include "api/environment/environment_factory.h" +#include "api/field_trials.h" #include "api/sequence_checker.h" #include "api/test/rtc_error_matchers.h" #include "rtc_base/checks.h" #include "rtc_base/ip_address.h" +#include "rtc_base/logging.h" #include "rtc_base/net_helpers.h" #include "rtc_base/net_test_helpers.h" #include "rtc_base/network_constants.h" @@ -38,6 +40,8 @@ #include "rtc_base/socket_address.h" #include "rtc_base/third_party/sigslot/sigslot.h" #include "rtc_base/thread.h" +#include "test/create_test_field_trials.h" +#include "test/gmock.h" #include "test/gtest.h" #include "test/wait_until.h" @@ -49,23 +53,13 @@ #include "rtc_base/ifaddrs_converter.h" #endif // defined(WEBRTC_POSIX) -#include "test/gmock.h" -#if defined(WEBRTC_WIN) -#include "rtc_base/logging.h" // For RTC_LOG_GLE -#endif // IWYU pragma: end_keep -#include "test/field_trial.h" -#include "test/scoped_key_value_config.h" using ::testing::Contains; using ::testing::IsTrue; using ::testing::Not; using ::testing::UnorderedElementsAre; using ::testing::UnorderedElementsAreArray; -using ::webrtc::CreateEnvironment; -using ::webrtc::Environment; -using ::webrtc::test::ScopedFieldTrials; -using ::webrtc::test::ScopedKeyValueConfig; #define MAYBE_SKIP_IPV4 \ if (!::webrtc::HasIPv4Enabled()) { \ @@ -175,8 +169,6 @@ std::vector CopyNetworkPointers( class NetworkTest : public ::testing::Test, public sigslot::has_slots<> { public: - NetworkTest() : callback_called_(false) {} - void OnNetworksChanged() { callback_called_ = true; } NetworkManager::Stats MergeNetworkList( @@ -339,9 +331,10 @@ class NetworkTest : public ::testing::Test, public sigslot::has_slots<> { #endif // defined(WEBRTC_POSIX) protected: - ScopedKeyValueConfig field_trials_; + const FieldTrials field_trials_ = CreateTestFieldTrials(); + const Environment env_ = CreateEnvironment(&field_trials_); AutoThread main_thread_; - bool callback_called_; + bool callback_called_ = false; }; class TestBasicNetworkManager : public BasicNetworkManager { @@ -369,7 +362,7 @@ TEST_F(NetworkTest, TestIsIgnoredNetworkIgnoresIPsStartingWith0) { Network ipv4_network2("test_eth1", "Test Network Adapter 2", IPAddress(0x010000U), 24, ADAPTER_TYPE_ETHERNET); PhysicalSocketServer socket_server; - BasicNetworkManager network_manager(CreateEnvironment(), &socket_server); + BasicNetworkManager network_manager(env_, &socket_server); network_manager.StartUpdating(); EXPECT_FALSE(IsIgnoredNetwork(network_manager, ipv4_network1)); EXPECT_TRUE(IsIgnoredNetwork(network_manager, ipv4_network2)); @@ -381,14 +374,13 @@ TEST_F(NetworkTest, TestIgnoreList) { 24); Network include_me("include_me", "Include me please!", IPAddress(0x12345600U), 24); - const Environment env = CreateEnvironment(); PhysicalSocketServer socket_server; - BasicNetworkManager default_network_manager(env, &socket_server); + BasicNetworkManager default_network_manager(env_, &socket_server); default_network_manager.StartUpdating(); EXPECT_FALSE(IsIgnoredNetwork(default_network_manager, ignore_me)); EXPECT_FALSE(IsIgnoredNetwork(default_network_manager, include_me)); - BasicNetworkManager ignoring_network_manager(env, &socket_server); + BasicNetworkManager ignoring_network_manager(env_, &socket_server); std::vector ignore_list; ignore_list.push_back("ignore_me"); ignoring_network_manager.set_network_ignore_list(ignore_list); @@ -400,7 +392,7 @@ TEST_F(NetworkTest, TestIgnoreList) { // Test is failing on Windows opt: b/11288214 TEST_F(NetworkTest, DISABLED_TestCreateNetworks) { PhysicalSocketServer socket_server; - BasicNetworkManager manager(CreateEnvironment(), &socket_server); + BasicNetworkManager manager(env_, &socket_server); std::vector> result = GetNetworks(manager, true); // We should be able to bind to any addresses we find. for (auto it = result.begin(); it != result.end(); ++it) { @@ -409,7 +401,7 @@ TEST_F(NetworkTest, DISABLED_TestCreateNetworks) { IPAddress ip = (*it)->GetBestIP(); SocketAddress bindaddress(ip, 0); bindaddress.SetScopeID((*it)->scope_id()); - // TODO(thaloun): Use webrtc::Socket once it supports IPv6. + // TODO(thaloun): Use Socket once it supports IPv6. int fd = static_cast(socket(ip.family(), SOCK_STREAM, IPPROTO_TCP)); if (fd > 0) { size_t ipsize = bindaddress.ToSockAddrStorage(&storage); @@ -434,7 +426,7 @@ TEST_F(NetworkTest, DISABLED_TestCreateNetworks) { // ALLOWED. TEST_F(NetworkTest, TestUpdateNetworks) { PhysicalSocketServer socket_server; - BasicNetworkManager manager(CreateEnvironment(), &socket_server); + BasicNetworkManager manager(env_, &socket_server); manager.SignalNetworksChanged.connect(static_cast(this), &NetworkTest::OnNetworksChanged); EXPECT_EQ(NetworkManager::ENUMERATION_ALLOWED, @@ -474,7 +466,7 @@ TEST_F(NetworkTest, TestBasicMergeNetworkList) { ipv4_network1.AddIP(IPAddress(0x12345678)); ipv4_network2.AddIP(IPAddress(0x00010004)); PhysicalSocketServer socket_server; - BasicNetworkManager manager(CreateEnvironment(), &socket_server); + BasicNetworkManager manager(env_, &socket_server); // Add ipv4_network1 to the list of networks. std::vector> list; @@ -581,7 +573,7 @@ void SetupNetworks(std::vector>* list) { // Test that the basic network merging case works. TEST_F(NetworkTest, TestIPv6MergeNetworkList) { PhysicalSocketServer socket_server; - BasicNetworkManager manager(CreateEnvironment(), &socket_server); + BasicNetworkManager manager(env_, &socket_server); manager.SignalNetworksChanged.connect(static_cast(this), &NetworkTest::OnNetworksChanged); std::vector> networks; @@ -603,7 +595,7 @@ TEST_F(NetworkTest, TestIPv6MergeNetworkList) { // objects remain in the result list. TEST_F(NetworkTest, TestNoChangeMerge) { PhysicalSocketServer socket_server; - BasicNetworkManager manager(CreateEnvironment(), &socket_server); + BasicNetworkManager manager(env_, &socket_server); manager.SignalNetworksChanged.connect(static_cast(this), &NetworkTest::OnNetworksChanged); std::vector> networks; @@ -634,7 +626,7 @@ TEST_F(NetworkTest, TestNoChangeMerge) { // IP changed. TEST_F(NetworkTest, MergeWithChangedIP) { PhysicalSocketServer socket_server; - BasicNetworkManager manager(CreateEnvironment(), &socket_server); + BasicNetworkManager manager(env_, &socket_server); manager.SignalNetworksChanged.connect(static_cast(this), &NetworkTest::OnNetworksChanged); std::vector> original_list; @@ -671,7 +663,7 @@ TEST_F(NetworkTest, MergeWithChangedIP) { TEST_F(NetworkTest, TestMultipleIPMergeNetworkList) { PhysicalSocketServer socket_server; - BasicNetworkManager manager(CreateEnvironment(), &socket_server); + BasicNetworkManager manager(env_, &socket_server); manager.SignalNetworksChanged.connect(static_cast(this), &NetworkTest::OnNetworksChanged); std::vector> original_list; @@ -725,7 +717,7 @@ TEST_F(NetworkTest, TestMultipleIPMergeNetworkList) { // Test that merge correctly distinguishes multiple networks on an interface. TEST_F(NetworkTest, TestMultiplePublicNetworksOnOneInterfaceMerge) { PhysicalSocketServer socket_server; - BasicNetworkManager manager(CreateEnvironment(), &socket_server); + BasicNetworkManager manager(env_, &socket_server); manager.SignalNetworksChanged.connect(static_cast(this), &NetworkTest::OnNetworksChanged); std::vector> original_list; @@ -768,7 +760,7 @@ TEST_F(NetworkTest, TestMultiplePublicNetworksOnOneInterfaceMerge) { // Test that DumpNetworks does not crash. TEST_F(NetworkTest, TestCreateAndDumpNetworks) { PhysicalSocketServer socket_server; - BasicNetworkManager manager(CreateEnvironment(), &socket_server); + BasicNetworkManager manager(env_, &socket_server); manager.StartUpdating(); std::vector> list = GetNetworks(manager, true); bool changed; @@ -778,7 +770,7 @@ TEST_F(NetworkTest, TestCreateAndDumpNetworks) { TEST_F(NetworkTest, TestIPv6Toggle) { PhysicalSocketServer socket_server; - BasicNetworkManager manager(CreateEnvironment(), &socket_server); + BasicNetworkManager manager(env_, &socket_server); manager.StartUpdating(); bool ipv6_found = false; for (const auto& network : GetNetworks(manager, true)) { @@ -794,7 +786,7 @@ TEST_F(NetworkTest, TestIPv6Toggle) { // IPv6 comes first. TEST_F(NetworkTest, IPv6NetworksPreferredOverIPv4) { PhysicalSocketServer socket_server; - BasicNetworkManager manager(CreateEnvironment(), &socket_server); + BasicNetworkManager manager(env_, &socket_server); Network ipv4_network1("test_eth0", "Test Network Adapter 1", IPAddress(0x12345600U), 24); ipv4_network1.AddIP(IPAddress(0x12345600U)); @@ -824,7 +816,7 @@ TEST_F(NetworkTest, IPv6NetworksPreferredOverIPv4) { // to be preference-ordered by name. For example, "eth0" before "eth1". TEST_F(NetworkTest, NetworksSortedByInterfaceName) { PhysicalSocketServer socket_server; - BasicNetworkManager manager(CreateEnvironment(), &socket_server); + BasicNetworkManager manager(env_, &socket_server); auto eth0 = std::make_unique("test_eth0", "Test Network Adapter 1", IPAddress(0x65432100U), 24); eth0->AddIP(IPAddress(0x65432100U)); @@ -873,7 +865,7 @@ TEST_F(NetworkTest, TestConvertIfAddrsNoAddress) { std::vector> result; PhysicalSocketServer socket_server; - BasicNetworkManager manager(CreateEnvironment(), &socket_server); + BasicNetworkManager manager(env_, &socket_server); manager.StartUpdating(); CallConvertIfAddrs(manager, &list, true, &result); EXPECT_TRUE(result.empty()); @@ -890,7 +882,7 @@ TEST_F(NetworkTest, TestConvertIfAddrsMultiAddressesOnOneInterface) { "FFFF:FFFF:FFFF:FFFF::", 0); std::vector> result; PhysicalSocketServer socket_server; - BasicNetworkManager manager(CreateEnvironment(), &socket_server); + BasicNetworkManager manager(env_, &socket_server); manager.StartUpdating(); CallConvertIfAddrs(manager, list, true, &result); EXPECT_EQ(1U, result.size()); @@ -912,7 +904,7 @@ TEST_F(NetworkTest, TestConvertIfAddrsNotRunning) { std::vector> result; PhysicalSocketServer socket_server; - BasicNetworkManager manager(CreateEnvironment(), &socket_server); + BasicNetworkManager manager(env_, &socket_server); manager.StartUpdating(); CallConvertIfAddrs(manager, &list, true, &result); EXPECT_TRUE(result.empty()); @@ -927,7 +919,7 @@ TEST_F(NetworkTest, TestConvertIfAddrsGetsNullAddr) { std::vector> result; PhysicalSocketServer socket_server; - BasicNetworkManager manager(CreateEnvironment(), &socket_server); + BasicNetworkManager manager(env_, &socket_server); manager.StartUpdating(); CallConvertIfAddrs(manager, &list, true, &result); EXPECT_TRUE(result.empty()); @@ -939,7 +931,7 @@ TEST_F(NetworkTest, TestGetAdapterTypeFromNetworkMonitor) { char if_name[20] = "wifi0"; std::string ipv6_address = "1000:2000:3000:4000:0:0:0:1"; std::string ipv6_mask = "FFFF:FFFF:FFFF:FFFF::"; - const Environment env = CreateEnvironment(); + const Environment env = env_; PhysicalSocketServer socket_server; BasicNetworkManager manager_without_monitor( env, &socket_server, /*network_monitor_factory=*/nullptr); @@ -972,7 +964,7 @@ TEST_F(NetworkTest, TestGetAdapterTypeFromNameMatching) { std::string ipv6_address2 = "1000:2000:3000:8000:0:0:0:1"; std::string ipv6_mask = "FFFF:FFFF:FFFF:FFFF::"; PhysicalSocketServer socket_server; - BasicNetworkManager manager(CreateEnvironment(), &socket_server); + BasicNetworkManager manager(env_, &socket_server); manager.StartUpdating(); // IPSec interface; name is in form "ipsec". @@ -1050,7 +1042,7 @@ TEST_F(NetworkTest, TestNetworkMonitorIsAdapterAvailable) { // Sanity check that both interfaces are included by default. FakeNetworkMonitorFactory factory; PhysicalSocketServer socket_server; - BasicNetworkManager manager(CreateEnvironment(), &socket_server, &factory); + BasicNetworkManager manager(env_, &socket_server, &factory); manager.StartUpdating(); CallConvertIfAddrs(manager, list, /*include_ignored=*/false, &result); EXPECT_EQ(2u, result.size()); @@ -1076,7 +1068,7 @@ TEST_F(NetworkTest, TestNetworkMonitorIsAdapterAvailable) { // prefix/length into a single Network. TEST_F(NetworkTest, TestMergeNetworkList) { PhysicalSocketServer socket_server; - BasicNetworkManager manager(CreateEnvironment(), &socket_server); + BasicNetworkManager manager(env_, &socket_server); std::vector> list; // Create 2 IPAddress classes with only last digit different. @@ -1112,7 +1104,7 @@ TEST_F(NetworkTest, TestMergeNetworkList) { // a network becomes inactive and then active again. TEST_F(NetworkTest, TestMergeNetworkListWithInactiveNetworks) { PhysicalSocketServer socket_server; - BasicNetworkManager manager(CreateEnvironment(), &socket_server); + BasicNetworkManager manager(env_, &socket_server); Network network1("test_wifi", "Test Network Adapter 1", IPAddress(0x12345600U), 24); Network network2("test_eth0", "Test Network Adapter 2", @@ -1261,7 +1253,7 @@ TEST_F(NetworkTest, TestGetBestIPWithPreferGlobalIPv6ToLinkLocalEnabled) { TEST_F(NetworkTest, TestNetworkMonitoring) { FakeNetworkMonitorFactory factory; PhysicalSocketServer socket_server; - BasicNetworkManager manager(CreateEnvironment(), &socket_server, &factory); + BasicNetworkManager manager(env_, &socket_server, &factory); manager.SignalNetworksChanged.connect(static_cast(this), &NetworkTest::OnNetworksChanged); manager.StartUpdating(); @@ -1293,8 +1285,7 @@ TEST_F(NetworkTest, MAYBE_DefaultLocalAddress) { IPAddress ip; FakeNetworkMonitorFactory factory; PhysicalSocketServer socket_server; - TestBasicNetworkManager manager(CreateEnvironment(), &socket_server, - &factory); + TestBasicNetworkManager manager(env_, &socket_server, &factory); manager.SignalNetworksChanged.connect(static_cast(this), &NetworkTest::OnNetworksChanged); manager.StartUpdating(); @@ -1359,7 +1350,7 @@ TEST_F(NetworkTest, MAYBE_DefaultLocalAddress) { // when changing from cellular_X to cellular_Y. TEST_F(NetworkTest, TestWhenNetworkListChangeReturnsChangedFlag) { PhysicalSocketServer socket_server; - BasicNetworkManager manager(CreateEnvironment(), &socket_server); + BasicNetworkManager manager(env_, &socket_server); IPAddress ip1; EXPECT_TRUE(IPFromString("2400:4030:1:2c00:be30:0:0:1", &ip1)); @@ -1421,7 +1412,7 @@ TEST_F(NetworkTest, IgnoresMACBasedIPv6Address) { std::string ipv6_address = "2607:fc20:f340:1dc8:214:22ff:fe01:2345"; std::string ipv6_mask = "FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF"; PhysicalSocketServer socket_server; - BasicNetworkManager manager(CreateEnvironment(), &socket_server); + BasicNetworkManager manager(env_, &socket_server); manager.StartUpdating(); // IPSec interface; name is in form "ipsec". @@ -1435,11 +1426,12 @@ TEST_F(NetworkTest, IgnoresMACBasedIPv6Address) { } TEST_F(NetworkTest, WebRTC_AllowMACBasedIPv6Address) { - ScopedFieldTrials field_trials("WebRTC-AllowMACBasedIPv6/Enabled/"); + FieldTrials field_trials = + CreateTestFieldTrials("WebRTC-AllowMACBasedIPv6/Enabled/"); std::string ipv6_address = "2607:fc20:f340:1dc8:214:22ff:fe01:2345"; std::string ipv6_mask = "FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF"; PhysicalSocketServer socket_server; - BasicNetworkManager manager(CreateEnvironment(), &socket_server); + BasicNetworkManager manager(CreateEnvironment(&field_trials), &socket_server); manager.StartUpdating(); // IPSec interface; name is in form "ipsec". @@ -1466,7 +1458,7 @@ TEST_F(NetworkTest, WebRTC_BindUsingInterfaceName) { // Sanity check that both interfaces are included by default. FakeNetworkMonitorFactory factory; PhysicalSocketServer socket_server; - BasicNetworkManager manager(CreateEnvironment(), &socket_server, &factory); + BasicNetworkManager manager(env_, &socket_server, &factory); manager.StartUpdating(); CallConvertIfAddrs(manager, list, /*include_ignored=*/false, &result); EXPECT_EQ(2u, result.size()); @@ -1498,7 +1490,7 @@ TEST_F(NetworkTest, WebRTC_BindUsingInterfaceName) { TEST_F(NetworkTest, NetworkCostVpn_Default) { IPAddress ip1; EXPECT_TRUE(IPFromString("2400:4030:1:2c00:be30:0:0:1", &ip1)); - ScopedKeyValueConfig field_trials; + FieldTrials field_trials = CreateTestFieldTrials(); Network* net1 = new Network("em1", "em1", TruncateIP(ip1, 64), 64); net1->set_type(ADAPTER_TYPE_VPN); @@ -1513,7 +1505,8 @@ TEST_F(NetworkTest, NetworkCostVpn_Default) { } TEST_F(NetworkTest, NetworkCostVpn_VpnMoreExpensive) { - ScopedKeyValueConfig field_trials("WebRTC-AddNetworkCostToVpn/Enabled/"); + FieldTrials field_trials = + CreateTestFieldTrials("WebRTC-AddNetworkCostToVpn/Enabled/"); IPAddress ip1; EXPECT_TRUE(IPFromString("2400:4030:1:2c00:be30:0:0:1", &ip1)); @@ -1531,7 +1524,7 @@ TEST_F(NetworkTest, NetworkCostVpn_VpnMoreExpensive) { } TEST_F(NetworkTest, GuessAdapterFromNetworkCost) { - ScopedKeyValueConfig field_trials( + FieldTrials field_trials = CreateTestFieldTrials( "WebRTC-AddNetworkCostToVpn/Enabled/" "WebRTC-UseDifferentiatedCellularCosts/Enabled/"); @@ -1572,10 +1565,9 @@ TEST_F(NetworkTest, GuessAdapterFromNetworkCost) { } TEST_F(NetworkTest, VpnList) { - const Environment env = CreateEnvironment(); PhysicalSocketServer socket_server; { - BasicNetworkManager manager(env, &socket_server); + BasicNetworkManager manager(env_, &socket_server); manager.set_vpn_list({NetworkMask(IPFromString("192.168.0.0"), 16)}); manager.StartUpdating(); EXPECT_TRUE(manager.IsConfiguredVpn(IPFromString("192.168.1.1"), 32)); @@ -1587,7 +1579,7 @@ TEST_F(NetworkTest, VpnList) { EXPECT_FALSE(manager.IsConfiguredVpn(IPFromString("192.168.0.0"), 15)); } { - BasicNetworkManager manager(env, &socket_server); + BasicNetworkManager manager(env_, &socket_server); manager.set_vpn_list({NetworkMask(IPFromString("192.168.0.0"), 24)}); manager.StartUpdating(); EXPECT_FALSE(manager.IsConfiguredVpn(IPFromString("192.168.1.1"), 32)); @@ -1599,7 +1591,7 @@ TEST_F(NetworkTest, VpnList) { // TODO(webrtc:13114): Implement the InstallIpv4Network for windows. TEST_F(NetworkTest, VpnListOverrideAdapterType) { PhysicalSocketServer socket_server; - BasicNetworkManager manager(CreateEnvironment(), &socket_server); + BasicNetworkManager manager(env_, &socket_server); manager.set_vpn_list({NetworkMask(IPFromString("192.168.0.0"), 16)}); manager.StartUpdating(); diff --git a/rtc_base/numerics/safe_compare_unittest.cc b/rtc_base/numerics/safe_compare_unittest.cc index 8541ed418c..fae4c1252c 100644 --- a/rtc_base/numerics/safe_compare_unittest.cc +++ b/rtc_base/numerics/safe_compare_unittest.cc @@ -29,8 +29,8 @@ constexpr std::intmax_t m1 = -1; static_assert(static_cast(m1) == umax, ""); static_assert(m1 == static_cast(umax), ""); -static const std::pair p1(1, 1); -static const std::pair p2(1, 2); +const std::pair p1(1, 1); +const std::pair p2(1, 2); } // namespace diff --git a/rtc_base/openssl.h b/rtc_base/openssl.h index 17af84d0e4..29aca2c412 100644 --- a/rtc_base/openssl.h +++ b/rtc_base/openssl.h @@ -11,11 +11,6 @@ #ifndef RTC_BASE_OPENSSL_H_ #define RTC_BASE_OPENSSL_H_ -#if defined(WEBRTC_WIN) -// Must be included first before openssl headers. -#include "rtc_base/win32.h" // NOLINT -#endif // WEBRTC_WIN - #include // IWYU pragma: export #if (OPENSSL_VERSION_NUMBER < 0x10100000L) diff --git a/rtc_base/openssl_adapter.cc b/rtc_base/openssl_adapter.cc index b25e9fb027..4a74944be9 100644 --- a/rtc_base/openssl_adapter.cc +++ b/rtc_base/openssl_adapter.cc @@ -15,34 +15,45 @@ #include #include #include +#include #include +#include +#include +#include #include #include #include +#include "absl/memory/memory.h" #include "absl/strings/string_view.h" #include "api/task_queue/pending_task_safety_flag.h" +#include "api/units/time_delta.h" #include "rtc_base/async_socket.h" +#include "rtc_base/checks.h" +#include "rtc_base/logging.h" +#include "rtc_base/numerics/safe_conversions.h" #include "rtc_base/openssl_session_cache.h" +#include "rtc_base/openssl_utility.h" #include "rtc_base/socket.h" #include "rtc_base/socket_address.h" #include "rtc_base/ssl_adapter.h" #include "rtc_base/ssl_certificate.h" #include "rtc_base/ssl_identity.h" #include "rtc_base/ssl_stream_adapter.h" +#include "rtc_base/strings/str_join.h" #include "rtc_base/strings/string_builder.h" +#include "rtc_base/thread.h" + #ifdef OPENSSL_IS_BORINGSSL #include #include "rtc_base/boringssl_certificate.h" +#include "rtc_base/boringssl_identity.h" #include "rtc_base/openssl.h" +#else +#include "rtc_base/openssl_identity.h" #endif -#include -#include -#include - -#include // Use CRYPTO_BUFFER APIs if available and we have no dependency on X509 // objects. @@ -50,21 +61,6 @@ defined(WEBRTC_EXCLUDE_BUILT_IN_SSL_ROOT_CERTS) #define WEBRTC_USE_CRYPTO_BUFFER_CALLBACK #endif - -#include "absl/memory/memory.h" -#include "api/units/time_delta.h" -#include "rtc_base/checks.h" -#include "rtc_base/logging.h" -#include "rtc_base/numerics/safe_conversions.h" -#ifdef OPENSSL_IS_BORINGSSL -#include "rtc_base/boringssl_identity.h" -#else -#include "rtc_base/openssl_identity.h" -#endif -#include "rtc_base/openssl_utility.h" -#include "rtc_base/strings/str_join.h" -#include "rtc_base/thread.h" - ////////////////////////////////////////////////////////////////////// // SocketBIO ////////////////////////////////////////////////////////////////////// @@ -258,8 +254,8 @@ void OpenSSLAdapter::SetIdentity(std::unique_ptr identity) { identity_ = absl::WrapUnique(static_cast(identity.release())); #else - identity_ = absl::WrapUnique( - static_cast(identity.release())); + identity_ = + absl::WrapUnique(static_cast(identity.release())); #endif } @@ -912,7 +908,7 @@ int OpenSSLAdapter::SSLVerifyInternal(int previous_status, } const BoringSSLCertificate cert(std::move(crypto_buffer)); #else - const webrtc::OpenSSLCertificate cert(X509_STORE_CTX_get_current_cert(store)); + const OpenSSLCertificate cert(X509_STORE_CTX_get_current_cert(store)); #endif if (!ssl_cert_verifier_->Verify(cert)) { RTC_LOG(LS_INFO) << "Failed to verify certificate using custom callback"; diff --git a/rtc_base/openssl_adapter.h b/rtc_base/openssl_adapter.h index 479b1a679c..3f3951d434 100644 --- a/rtc_base/openssl_adapter.h +++ b/rtc_base/openssl_adapter.h @@ -148,7 +148,7 @@ class OpenSSLAdapter final : public SSLAdapter { #ifdef OPENSSL_IS_BORINGSSL std::unique_ptr identity_; #else - std::unique_ptr identity_; + std::unique_ptr identity_; #endif // Indicates whethere this is a client or a server. SSLRole role_; @@ -211,8 +211,8 @@ class OpenSSLAdapterFactory : public SSLAdapterFactory { private: // Holds the SSLMode (DTLS,TLS) that will be used to set the session cache. - SSLMode ssl_mode_ = webrtc::SSL_MODE_TLS; - SSLRole ssl_role_ = webrtc::SSL_CLIENT; + SSLMode ssl_mode_ = SSL_MODE_TLS; + SSLRole ssl_role_ = SSL_CLIENT; bool ignore_bad_cert_ = false; std::unique_ptr identity_; diff --git a/rtc_base/openssl_adapter_unittest.cc b/rtc_base/openssl_adapter_unittest.cc index d30969dee5..3c2c183911 100644 --- a/rtc_base/openssl_adapter_unittest.cc +++ b/rtc_base/openssl_adapter_unittest.cc @@ -29,7 +29,7 @@ namespace { class MockAsyncSocket : public Socket { public: - virtual ~MockAsyncSocket() = default; + ~MockAsyncSocket() override = default; MOCK_METHOD(Socket*, Accept, (SocketAddress*), (override)); MOCK_METHOD(SocketAddress, GetLocalAddress, (), (const, override)); MOCK_METHOD(SocketAddress, GetRemoteAddress, (), (const, override)); @@ -56,7 +56,7 @@ class MockAsyncSocket : public Socket { class MockCertVerifier : public SSLCertificateVerifier { public: - virtual ~MockCertVerifier() = default; + ~MockCertVerifier() override = default; MOCK_METHOD(bool, Verify, (const SSLCertificate&), (override)); }; diff --git a/rtc_base/openssl_certificate.cc b/rtc_base/openssl_certificate.cc index 64730432e3..e01625b261 100644 --- a/rtc_base/openssl_certificate.cc +++ b/rtc_base/openssl_certificate.cc @@ -10,33 +10,26 @@ #include "rtc_base/openssl_certificate.h" -#include -#include - -#include "absl/strings/string_view.h" -#include "rtc_base/buffer.h" -#include "rtc_base/ssl_certificate.h" -#include "rtc_base/ssl_identity.h" - -#if defined(WEBRTC_WIN) -// Must be included first before openssl headers. -#include "rtc_base/win32.h" // NOLINT -#endif // WEBRTC_WIN - #include #include #include -#include +#include +#include #include +#include +#include "absl/strings/string_view.h" +#include "rtc_base/buffer.h" #include "rtc_base/checks.h" #include "rtc_base/crypto_random.h" #include "rtc_base/logging.h" #include "rtc_base/message_digest.h" #include "rtc_base/openssl_digest.h" -#include "rtc_base/openssl_identity.h" +#include "rtc_base/openssl_key_pair.h" #include "rtc_base/openssl_utility.h" +#include "rtc_base/ssl_certificate.h" +#include "rtc_base/ssl_identity.h" namespace webrtc { namespace { diff --git a/rtc_base/openssl_digest.cc b/rtc_base/openssl_digest.cc index ce0c6c1cb6..c982311dc0 100644 --- a/rtc_base/openssl_digest.cc +++ b/rtc_base/openssl_digest.cc @@ -10,8 +10,12 @@ #include "rtc_base/openssl_digest.h" +#include +#include + #include "absl/strings/string_view.h" -#include "rtc_base/checks.h" // RTC_DCHECK, RTC_CHECK +#include "rtc_base/checks.h" +#include "rtc_base/message_digest.h" #include "rtc_base/openssl.h" namespace webrtc { diff --git a/rtc_base/openssl_identity.cc b/rtc_base/openssl_identity.cc index 32b8b3b2e9..94641ecf1e 100644 --- a/rtc_base/openssl_identity.cc +++ b/rtc_base/openssl_identity.cc @@ -10,26 +10,30 @@ #include "rtc_base/openssl_identity.h" -#include -#include -#include - -#if defined(WEBRTC_WIN) -// Must be included first before openssl headers. -#include "rtc_base/win32.h" // NOLINT -#endif // WEBRTC_WIN - #include +#include #include #include -#include + +#include +#include +#include +#include +#include +#include +#include #include "absl/memory/memory.h" +#include "absl/strings/string_view.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "rtc_base/numerics/safe_conversions.h" #include "rtc_base/openssl.h" +#include "rtc_base/openssl_certificate.h" +#include "rtc_base/openssl_key_pair.h" #include "rtc_base/openssl_utility.h" +#include "rtc_base/ssl_certificate.h" +#include "rtc_base/ssl_identity.h" namespace webrtc { @@ -115,9 +119,8 @@ std::unique_ptr OpenSSLIdentity::CreateFromPEMStrings( std::unique_ptr OpenSSLIdentity::CreateFromPEMChainStrings( absl::string_view private_key, absl::string_view certificate_chain) { - BIO* bio = - BIO_new_mem_buf(certificate_chain.data(), - webrtc::dchecked_cast(certificate_chain.size())); + BIO* bio = BIO_new_mem_buf(certificate_chain.data(), + dchecked_cast(certificate_chain.size())); if (!bio) return nullptr; BIO_set_mem_eof_return(bio, 0); diff --git a/rtc_base/openssl_identity.h b/rtc_base/openssl_identity.h index 2b17ae0875..68392dc19d 100644 --- a/rtc_base/openssl_identity.h +++ b/rtc_base/openssl_identity.h @@ -17,6 +17,7 @@ #include #include +#include "absl/strings/string_view.h" #include "rtc_base/openssl_certificate.h" #include "rtc_base/openssl_key_pair.h" #include "rtc_base/ssl_certificate.h" diff --git a/rtc_base/openssl_key_pair.cc b/rtc_base/openssl_key_pair.cc index e3da69f22e..697106a40e 100644 --- a/rtc_base/openssl_key_pair.cc +++ b/rtc_base/openssl_key_pair.cc @@ -10,25 +10,21 @@ #include "rtc_base/openssl_key_pair.h" -#include -#include - -#include "absl/strings/string_view.h" - -#if defined(WEBRTC_WIN) -// Must be included first before openssl headers. -#include "rtc_base/win32.h" // NOLINT -#endif // WEBRTC_WIN - #include #include #include #include +#include +#include +#include + +#include "absl/strings/string_view.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "rtc_base/openssl.h" #include "rtc_base/openssl_utility.h" +#include "rtc_base/ssl_identity.h" namespace webrtc { diff --git a/rtc_base/openssl_stream_adapter.cc b/rtc_base/openssl_stream_adapter.cc index 944567b43c..604a9465c7 100644 --- a/rtc_base/openssl_stream_adapter.cc +++ b/rtc_base/openssl_stream_adapter.cc @@ -38,9 +38,16 @@ #include "rtc_base/numerics/safe_conversions.h" #include "rtc_base/openssl_adapter.h" #include "rtc_base/openssl_digest.h" +#include "rtc_base/openssl_utility.h" +#include "rtc_base/ssl_certificate.h" #include "rtc_base/ssl_identity.h" #include "rtc_base/ssl_stream_adapter.h" +#include "rtc_base/stream.h" +#include "rtc_base/string_encode.h" #include "rtc_base/task_utils/repeating_task.h" +#include "rtc_base/thread.h" +#include "rtc_base/time_utils.h" + #ifdef OPENSSL_IS_BORINGSSL #include #include @@ -53,12 +60,6 @@ #else #include "rtc_base/openssl_identity.h" #endif -#include "rtc_base/openssl_utility.h" -#include "rtc_base/ssl_certificate.h" -#include "rtc_base/stream.h" -#include "rtc_base/string_encode.h" -#include "rtc_base/thread.h" -#include "rtc_base/time_utils.h" #if (OPENSSL_VERSION_NUMBER < 0x10100000L) #error "webrtc requires at least OpenSSL version 1.1.0, to support DTLS-SRTP" @@ -66,8 +67,7 @@ namespace { // Value specified in RFC 5764. -static constexpr absl::string_view kDtlsSrtpExporterLabel = - "EXTRACTOR-dtls_srtp"; +constexpr absl::string_view kDtlsSrtpExporterLabel = "EXTRACTOR-dtls_srtp"; } // namespace namespace webrtc { @@ -144,13 +144,15 @@ int GetForceDtls13(const FieldTrialsView* field_trials) { return kForceDtls13Off; } #ifdef DTLS1_3_VERSION - auto mode = field_trials->Lookup("WebRTC-ForceDtls13"); - RTC_LOG(LS_WARNING) << "WebRTC-ForceDtls13: " << mode; - if (mode == "Enabled") { + if (field_trials->IsEnabled("WebRTC-ForceDtls13")) { + RTC_LOG(LS_WARNING) << "WebRTC-ForceDtls13 Enabled"; return kForceDtls13Enabled; - } else if (mode == "Only") { + } + if (field_trials->Lookup("WebRTC-ForceDtls13") == "Only") { + RTC_LOG(LS_WARNING) << "WebRTC-ForceDtls13 Only"; return kForceDtls13Only; } + RTC_LOG(LS_WARNING) << "WebRTC-ForceDtls13 Disabled"; #endif return kForceDtls13Off; } @@ -317,7 +319,7 @@ void OpenSSLStreamAdapter::SetIdentity(std::unique_ptr identity) { #ifdef OPENSSL_IS_BORINGSSL identity_.reset(static_cast(identity.release())); #else - identity_.reset(static_cast(identity.release())); + identity_.reset(static_cast(identity.release())); #endif } @@ -1203,7 +1205,7 @@ int OpenSSLStreamAdapter::SSLVerifyCallback(X509_STORE_CTX* store, void* arg) { // Record the peer's certificate. X509* cert = X509_STORE_CTX_get0_cert(store); stream->peer_cert_chain_.reset( - new SSLCertChain(std::make_unique(cert))); + new SSLCertChain(std::make_unique(cert))); // If the peer certificate digest isn't known yet, we'll wait to verify // until it's known, and for now just return a success status. diff --git a/rtc_base/openssl_stream_adapter.h b/rtc_base/openssl_stream_adapter.h index 257f100ef5..2cce9c1c01 100644 --- a/rtc_base/openssl_stream_adapter.h +++ b/rtc_base/openssl_stream_adapter.h @@ -79,7 +79,7 @@ class OpenSSLStreamAdapter final : public SSLStreamAdapter { SSLIdentity* GetIdentityForTesting() const override; // Default argument is for compatibility - void SetServerRole(SSLRole role = webrtc::SSL_SERVER) override; + void SetServerRole(SSLRole role = SSL_SERVER) override; SSLPeerCertificateDigestError SetPeerCertificateDigest( absl::string_view digest_alg, ArrayView digest_val) override; @@ -232,7 +232,7 @@ class OpenSSLStreamAdapter final : public SSLStreamAdapter { #ifdef OPENSSL_IS_BORINGSSL std::unique_ptr identity_; #else - std::unique_ptr identity_; + std::unique_ptr identity_; #endif // The certificate chain that the peer presented. Initially null, until the // connection is established. diff --git a/rtc_base/openssl_stream_adapter_unittest.cc b/rtc_base/openssl_stream_adapter_unittest.cc index 9513ad60ab..4d7b985f58 100644 --- a/rtc_base/openssl_stream_adapter_unittest.cc +++ b/rtc_base/openssl_stream_adapter_unittest.cc @@ -16,14 +16,18 @@ #include #include +#include "api/field_trials.h" #include "rtc_base/logging.h" #include "rtc_base/ssl_stream_adapter.h" +#include "test/create_test_field_trials.h" #include "test/gtest.h" -#include "test/scoped_key_value_config.h" + +namespace webrtc { +namespace { TEST(OpenSSLStreamAdapterTest, GetSupportedEphemeralKeyExchangeCipherGroups) { RTC_LOG(LS_INFO) << "OpenSSLStreamAdapter::IsBoringSsl(): " - << webrtc::OpenSSLStreamAdapter::IsBoringSsl(); + << OpenSSLStreamAdapter::IsBoringSsl(); std::set expected = { #ifdef SSL_GROUP_SECP224R1 SSL_GROUP_SECP224R1, @@ -44,46 +48,44 @@ TEST(OpenSSLStreamAdapterTest, GetSupportedEphemeralKeyExchangeCipherGroups) { SSL_GROUP_X25519_MLKEM768, #endif }; - EXPECT_EQ( - webrtc::SSLStreamAdapter::GetSupportedEphemeralKeyExchangeCipherGroups(), - expected); + EXPECT_EQ(SSLStreamAdapter::GetSupportedEphemeralKeyExchangeCipherGroups(), + expected); } TEST(OpenSSLStreamAdapterTest, GetEphemeralKeyExchangeCipherGroupName) { #ifdef SSL_GROUP_SECP224R1 - EXPECT_EQ(*webrtc::SSLStreamAdapter::GetEphemeralKeyExchangeCipherGroupName( + EXPECT_EQ(*SSLStreamAdapter::GetEphemeralKeyExchangeCipherGroupName( SSL_GROUP_SECP224R1), "P-224"); #endif #ifdef SSL_GROUP_SECP256R1 - EXPECT_EQ(*webrtc::SSLStreamAdapter::GetEphemeralKeyExchangeCipherGroupName( + EXPECT_EQ(*SSLStreamAdapter::GetEphemeralKeyExchangeCipherGroupName( SSL_GROUP_SECP256R1), "P-256"); #endif #ifdef SSL_GROUP_SECP384R1 - EXPECT_EQ(*webrtc::SSLStreamAdapter::GetEphemeralKeyExchangeCipherGroupName( + EXPECT_EQ(*SSLStreamAdapter::GetEphemeralKeyExchangeCipherGroupName( SSL_GROUP_SECP384R1), "P-384"); #endif #ifdef SSL_GROUP_SECP521R1 - EXPECT_EQ(*webrtc::SSLStreamAdapter::GetEphemeralKeyExchangeCipherGroupName( + EXPECT_EQ(*SSLStreamAdapter::GetEphemeralKeyExchangeCipherGroupName( SSL_GROUP_SECP521R1), "P-521"); #endif #ifdef SSL_GROUP_X25519 - EXPECT_EQ(*webrtc::SSLStreamAdapter::GetEphemeralKeyExchangeCipherGroupName( + EXPECT_EQ(*SSLStreamAdapter::GetEphemeralKeyExchangeCipherGroupName( SSL_GROUP_X25519), "X25519"); #endif #ifdef SSL_GROUP_X25519_MLKEM768 - EXPECT_EQ(*webrtc::SSLStreamAdapter::GetEphemeralKeyExchangeCipherGroupName( + EXPECT_EQ(*SSLStreamAdapter::GetEphemeralKeyExchangeCipherGroupName( SSL_GROUP_X25519_MLKEM768), "X25519MLKEM768"); #endif EXPECT_FALSE( - webrtc::SSLStreamAdapter::GetEphemeralKeyExchangeCipherGroupName(0) - .has_value()); + SSLStreamAdapter::GetEphemeralKeyExchangeCipherGroupName(0).has_value()); } TEST(OpenSSLStreamAdapterTest, GetDefaultEphemeralKeyExchangeCipherGroups) { @@ -98,10 +100,9 @@ TEST(OpenSSLStreamAdapterTest, GetDefaultEphemeralKeyExchangeCipherGroups) { SSL_GROUP_SECP384R1, #endif }; - EXPECT_EQ( - webrtc::SSLStreamAdapter::GetDefaultEphemeralKeyExchangeCipherGroups( - /* field_trials= */ nullptr), - expected); + EXPECT_EQ(SSLStreamAdapter::GetDefaultEphemeralKeyExchangeCipherGroups( + /* field_trials= */ nullptr), + expected); } TEST(OpenSSLStreamAdapterTest, @@ -120,10 +121,12 @@ TEST(OpenSSLStreamAdapterTest, SSL_GROUP_SECP384R1, #endif }; - webrtc::test::ScopedKeyValueConfig field_trials( - "WebRTC-EnableDtlsPqc/Enabled/"); - EXPECT_EQ( - webrtc::SSLStreamAdapter::GetDefaultEphemeralKeyExchangeCipherGroups( - &field_trials), - expected); + FieldTrials field_trials = + CreateTestFieldTrials("WebRTC-EnableDtlsPqc/Enabled/"); + EXPECT_EQ(SSLStreamAdapter::GetDefaultEphemeralKeyExchangeCipherGroups( + &field_trials), + expected); } + +} // namespace +} // namespace webrtc \ No newline at end of file diff --git a/rtc_base/openssl_utility.cc b/rtc_base/openssl_utility.cc index 9c6dcf8448..be11dae28f 100644 --- a/rtc_base/openssl_utility.cc +++ b/rtc_base/openssl_utility.cc @@ -10,25 +10,23 @@ #include "rtc_base/openssl_utility.h" -#include "absl/strings/string_view.h" -#if defined(WEBRTC_WIN) -// Must be included first before openssl headers. -#include "rtc_base/win32.h" // NOLINT -#endif // WEBRTC_WIN - -#ifdef OPENSSL_IS_BORINGSSL -#include -#endif #include #include #include -#include -#include "rtc_base/arraysize.h" +#include +#include + +#include "absl/strings/string_view.h" #include "rtc_base/logging.h" #include "rtc_base/numerics/safe_conversions.h" #include "rtc_base/openssl.h" #include "rtc_base/ssl_identity.h" + +#ifdef OPENSSL_IS_BORINGSSL +#include +#endif + #ifndef WEBRTC_EXCLUDE_BUILT_IN_SSL_ROOT_CERTS #include "rtc_base/ssl_roots.h" #endif // WEBRTC_EXCLUDE_BUILT_IN_SSL_ROOT_CERTS @@ -245,7 +243,7 @@ void LogSSLErrors(absl::string_view prefix) { #ifndef WEBRTC_EXCLUDE_BUILT_IN_SSL_ROOT_CERTS bool LoadBuiltinSSLRootCertificates(SSL_CTX* ctx) { int count_of_added_certs = 0; - for (size_t i = 0; i < arraysize(kSSLCertCertificateList); i++) { + for (size_t i = 0; i < std::size(kSSLCertCertificateList); i++) { const unsigned char* cert_buffer = kSSLCertCertificateList[i]; size_t cert_buffer_len = kSSLCertCertificateSizeList[i]; X509* cert = d2i_X509(nullptr, &cert_buffer, diff --git a/rtc_base/openssl_utility.h b/rtc_base/openssl_utility.h index d3f5b0e049..bdab3ce90a 100644 --- a/rtc_base/openssl_utility.h +++ b/rtc_base/openssl_utility.h @@ -13,7 +13,7 @@ #include -#include +#include #include "absl/strings/string_view.h" diff --git a/rtc_base/openssl_utility_unittest.cc b/rtc_base/openssl_utility_unittest.cc index 3008147ac3..a2f1f5cd54 100644 --- a/rtc_base/openssl_utility_unittest.cc +++ b/rtc_base/openssl_utility_unittest.cc @@ -8,17 +8,7 @@ * be found in the AUTHORS file in the root of the source tree. */ -#include -#include - -#if defined(WEBRTC_POSIX) -#include -#endif - -#if defined(WEBRTC_WIN) -// Must be included first before openssl headers. -#include "rtc_base/win32.h" // NOLINT -#endif // WEBRTC_WIN +#include "rtc_base/openssl_utility.h" #include #include @@ -31,14 +21,15 @@ #include #endif -#include "rtc_base/arraysize.h" +#include +#include +#include +#include + #include "rtc_base/checks.h" -#include "rtc_base/gunit.h" #include "rtc_base/numerics/safe_conversions.h" #include "rtc_base/openssl.h" -#include "rtc_base/openssl_utility.h" -#include "rtc_base/ssl_roots.h" -#include "test/gmock.h" +#include "test/gtest.h" namespace webrtc { namespace { @@ -187,7 +178,7 @@ SSL* CreateSSLWithPeerCertificate(const unsigned char* cert, size_t cert_len) { const unsigned char* key_ptr = kFakeSSLPrivateKey; EVP_PKEY* key = d2i_PrivateKey( EVP_PKEY_EC, nullptr, &key_ptr, - checked_cast(arraysize(kFakeSSLPrivateKey))); // NOLINT + checked_cast(std::ssize(kFakeSSLPrivateKey))); // NOLINT RTC_CHECK(key); #ifdef OPENSSL_IS_BORINGSSL @@ -269,7 +260,7 @@ TEST(OpenSSLUtilityTest, VerifyPeerCertMatchesHostFailsOnNoPeerCertificate) { TEST(OpenSSLUtilityTest, VerifyPeerCertMatchesHost) { SSL* ssl = CreateSSLWithPeerCertificate(kFakeSSLCertificate, - arraysize(kFakeSSLCertificate)); + std::size(kFakeSSLCertificate)); // Each of the names in the SAN list is valid. EXPECT_TRUE(openssl::VerifyPeerCertMatchesHost(ssl, "foo.test")); @@ -290,7 +281,7 @@ TEST(OpenSSLUtilityTest, VerifyPeerCertMatchesHost) { TEST(OpenSSLUtilityTest, VerifyPeerCertMatchesHostLegacy) { SSL* ssl = CreateSSLWithPeerCertificate(kFakeSSLCertificateLegacy, - arraysize(kFakeSSLCertificateLegacy)); + std::size(kFakeSSLCertificateLegacy)); // If there is no SAN list, WebRTC still implements the legacy mechanism which // checks the CN, no longer supported by modern browsers. diff --git a/rtc_base/physical_socket_server.cc b/rtc_base/physical_socket_server.cc index b18052a0a7..0844b7fa66 100644 --- a/rtc_base/physical_socket_server.cc +++ b/rtc_base/physical_socket_server.cc @@ -122,7 +122,7 @@ typedef char* SockOptArg; namespace { // RFC-3168, Section 5. ECN is the two least significant bits. -static constexpr uint8_t kEcnMask = 0x03; +constexpr uint8_t kEcnMask = 0x03; #if defined(WEBRTC_POSIX) @@ -1825,7 +1825,7 @@ bool PhysicalSocketServer::WaitPoll(int cmsWait, bool process_io) { int64_t msStop = -1; if (cmsWait != kForeverMs) { msWait = cmsWait; - msStop = webrtc::TimeAfter(cmsWait); + msStop = TimeAfter(cmsWait); } std::vector pollfds; @@ -1833,7 +1833,7 @@ bool PhysicalSocketServer::WaitPoll(int cmsWait, bool process_io) { while (fWait_) { { - webrtc::CritScope cr(&crit_); + CritScope cr(&crit_); current_dispatcher_keys_.clear(); pollfds.clear(); pollfds.reserve(dispatcher_by_key_.size()); @@ -1867,7 +1867,7 @@ bool PhysicalSocketServer::WaitPoll(int cmsWait, bool process_io) { return true; } else { // We have signaled descriptors - webrtc::CritScope cr(&crit_); + CritScope cr(&crit_); // Iterate only on the dispatchers whose file descriptors were passed into // poll; this avoids the ABA problem (a socket being destroyed and a new // one created with the same file descriptor). @@ -1880,7 +1880,7 @@ bool PhysicalSocketServer::WaitPoll(int cmsWait, bool process_io) { } if (cmsWait != kForeverMs) { - msWait = webrtc::TimeDiff(msStop, webrtc::TimeMillis()); + msWait = TimeDiff(msStop, TimeMillis()); if (msWait < 0) { // Return success on timeout. return true; @@ -1896,8 +1896,7 @@ bool PhysicalSocketServer::WaitPoll(int cmsWait, bool process_io) { #endif // WEBRTC_POSIX #if defined(WEBRTC_WIN) -bool PhysicalSocketServer::Wait(webrtc::TimeDelta max_wait_duration, - bool process_io) { +bool PhysicalSocketServer::Wait(TimeDelta max_wait_duration, bool process_io) { // We don't support reentrant waiting. RTC_DCHECK(!waiting_); ScopedSetTrue set(&waiting_); @@ -1905,7 +1904,7 @@ bool PhysicalSocketServer::Wait(webrtc::TimeDelta max_wait_duration, int cmsWait = ToCmsWait(max_wait_duration); int64_t cmsTotal = cmsWait; int64_t cmsElapsed = 0; - int64_t msStart = webrtc::Time(); + int64_t msStart = Time(); fWait_ = true; while (fWait_) { @@ -1915,7 +1914,7 @@ bool PhysicalSocketServer::Wait(webrtc::TimeDelta max_wait_duration, events.push_back(socket_ev_); { - webrtc::CritScope cr(&crit_); + CritScope cr(&crit_); // Get a snapshot of all current dispatchers; this is used to avoid the // ABA problem (see later comment) and avoids the dispatcher_by_key_ // iterator being invalidated by calling CheckSignalClose, which may @@ -1971,7 +1970,7 @@ bool PhysicalSocketServer::Wait(webrtc::TimeDelta max_wait_duration, return true; } else { // Figure out which one it is and call it - webrtc::CritScope cr(&crit_); + CritScope cr(&crit_); int index = dw - WSA_WAIT_EVENT_0; if (index > 0) { --index; // The first event is the socket event @@ -2064,7 +2063,7 @@ bool PhysicalSocketServer::Wait(webrtc::TimeDelta max_wait_duration, // Break? if (!fWait_) break; - cmsElapsed = webrtc::TimeSince(msStart); + cmsElapsed = TimeSince(msStart); if ((cmsWait != kForeverMs) && (cmsElapsed >= cmsWait)) { break; } diff --git a/rtc_base/physical_socket_server.h b/rtc_base/physical_socket_server.h index 3c9eca5561..e06bd10387 100644 --- a/rtc_base/physical_socket_server.h +++ b/rtc_base/physical_socket_server.h @@ -16,6 +16,7 @@ #include "api/async_dns_resolver.h" #include "api/transport/ecn_marking.h" #include "api/units/time_delta.h" +#include "rtc_base/net_helpers.h" #include "rtc_base/socket.h" #include "rtc_base/socket_address.h" #include "rtc_base/third_party/sigslot/sigslot.h" diff --git a/rtc_base/platform_thread_types.cc b/rtc_base/platform_thread_types.cc index 9b6e7a13d8..f057d4b7c3 100644 --- a/rtc_base/platform_thread_types.cc +++ b/rtc_base/platform_thread_types.cc @@ -17,7 +17,7 @@ #endif #if defined(WEBRTC_WIN) -#include "rtc_base/arraysize.h" +#include // The SetThreadDescription API was brought in version 1607 of Windows 10. // For compatibility with various versions of winuser and avoid clashing with @@ -85,13 +85,13 @@ void SetCurrentThreadName(const char* name) { if (set_thread_description_func) { // Convert from ASCII to UTF-16. wchar_t wide_thread_name[64]; - for (size_t i = 0; i < arraysize(wide_thread_name) - 1; ++i) { + for (size_t i = 0; i < std::size(wide_thread_name) - 1; ++i) { wide_thread_name[i] = name[i]; if (wide_thread_name[i] == L'\0') break; } // Guarantee null-termination. - wide_thread_name[arraysize(wide_thread_name) - 1] = L'\0'; + wide_thread_name[std::size(wide_thread_name) - 1] = L'\0'; set_thread_description_func(::GetCurrentThread(), wide_thread_name); } diff --git a/rtc_base/random.cc b/rtc_base/random.cc index 28e48f0d3d..319ad72177 100644 --- a/rtc_base/random.cc +++ b/rtc_base/random.cc @@ -11,6 +11,7 @@ #include +#include #include #include "rtc_base/checks.h" diff --git a/rtc_base/random_unittest.cc b/rtc_base/random_unittest.cc index ffcd3ed72a..d1827cd71c 100644 --- a/rtc_base/random_unittest.cc +++ b/rtc_base/random_unittest.cc @@ -12,10 +12,12 @@ #include +#include #include #include #include +#include "rtc_base/checks.h" #include "rtc_base/numerics/math_utils.h" // unsigned difference #include "test/gtest.h" diff --git a/rtc_base/rate_limiter.cc b/rtc_base/rate_limiter.cc index 26e1c30225..ffcce44454 100644 --- a/rtc_base/rate_limiter.cc +++ b/rtc_base/rate_limiter.cc @@ -10,9 +10,13 @@ #include "rtc_base/rate_limiter.h" +#include +#include #include #include +#include "rtc_base/rate_statistics.h" +#include "rtc_base/synchronization/mutex.h" #include "system_wrappers/include/clock.h" namespace webrtc { diff --git a/rtc_base/rate_limiter_unittest.cc b/rtc_base/rate_limiter_unittest.cc index a118e46948..a15866a765 100644 --- a/rtc_base/rate_limiter_unittest.cc +++ b/rtc_base/rate_limiter_unittest.cc @@ -10,8 +10,11 @@ #include "rtc_base/rate_limiter.h" +#include +#include #include +#include "api/units/time_delta.h" #include "rtc_base/event.h" #include "rtc_base/platform_thread.h" #include "system_wrappers/include/clock.h" diff --git a/rtc_base/rate_statistics.cc b/rtc_base/rate_statistics.cc index 5870ccada3..53bf3208ff 100644 --- a/rtc_base/rate_statistics.cc +++ b/rtc_base/rate_statistics.cc @@ -11,11 +11,13 @@ #include "rtc_base/rate_statistics.h" #include +#include #include -#include +#include #include "rtc_base/checks.h" #include "rtc_base/logging.h" +#include "rtc_base/numerics/safe_compare.h" #include "rtc_base/numerics/safe_conversions.h" namespace webrtc { diff --git a/rtc_base/rate_statistics.h b/rtc_base/rate_statistics.h index 7bcb0012fd..b62e5252f7 100644 --- a/rtc_base/rate_statistics.h +++ b/rtc_base/rate_statistics.h @@ -15,7 +15,6 @@ #include #include -#include #include #include "rtc_base/system/rtc_export.h" diff --git a/rtc_base/rate_statistics_unittest.cc b/rtc_base/rate_statistics_unittest.cc index ce982b7cdf..a037b7b4ec 100644 --- a/rtc_base/rate_statistics_unittest.cc +++ b/rtc_base/rate_statistics_unittest.cc @@ -10,7 +10,10 @@ #include "rtc_base/rate_statistics.h" +#include #include +#include +#include #include "test/gtest.h" diff --git a/rtc_base/ref_counted_object.h b/rtc_base/ref_counted_object.h index 032e9ad163..5caba330f3 100644 --- a/rtc_base/ref_counted_object.h +++ b/rtc_base/ref_counted_object.h @@ -10,8 +10,9 @@ #ifndef RTC_BASE_REF_COUNTED_OBJECT_H_ #define RTC_BASE_REF_COUNTED_OBJECT_H_ -#include "api/scoped_refptr.h" -#include "rtc_base/ref_count.h" +#include + +#include "api/ref_count.h" #include "rtc_base/ref_counter.h" namespace webrtc { @@ -54,7 +55,7 @@ class RefCountedObject : public T { protected: ~RefCountedObject() override {} - mutable webrtc::webrtc_impl::RefCounter ref_count_{0}; + mutable webrtc_impl::RefCounter ref_count_{0}; }; template @@ -81,7 +82,7 @@ class FinalRefCountedObject final : public T { private: ~FinalRefCountedObject() = default; - mutable webrtc::webrtc_impl::RefCounter ref_count_{0}; + mutable webrtc_impl::RefCounter ref_count_{0}; }; } // namespace webrtc diff --git a/rtc_base/ref_counter.h b/rtc_base/ref_counter.h index 93ae3d21f2..af253914b4 100644 --- a/rtc_base/ref_counter.h +++ b/rtc_base/ref_counter.h @@ -12,7 +12,7 @@ #include -#include "rtc_base/ref_count.h" +#include "api/ref_count.h" namespace webrtc { namespace webrtc_impl { diff --git a/rtc_base/rtc_certificate_generator.cc b/rtc_base/rtc_certificate_generator.cc index c3a316e9b8..d496e2fb15 100644 --- a/rtc_base/rtc_certificate_generator.cc +++ b/rtc_base/rtc_certificate_generator.cc @@ -13,11 +13,16 @@ #include #include +#include #include +#include #include +#include "api/scoped_refptr.h" #include "rtc_base/checks.h" +#include "rtc_base/rtc_certificate.h" #include "rtc_base/ssl_identity.h" +#include "rtc_base/thread.h" namespace webrtc { diff --git a/rtc_base/rtc_certificate_generator.h b/rtc_base/rtc_certificate_generator.h index ca5d419ce1..b5be2067aa 100644 --- a/rtc_base/rtc_certificate_generator.h +++ b/rtc_base/rtc_certificate_generator.h @@ -30,8 +30,7 @@ class RTCCertificateGeneratorInterface { public: // Functor that will be called when certificate is generated asynchroniosly. // Called with nullptr as the parameter on failure. - using Callback = - absl::AnyInvocable) &&>; + using Callback = absl::AnyInvocable) &&>; virtual ~RTCCertificateGeneratorInterface() = default; diff --git a/rtc_base/rtc_certificate_unittest.cc b/rtc_base/rtc_certificate_unittest.cc index 5233a80d27..9b021ec447 100644 --- a/rtc_base/rtc_certificate_unittest.cc +++ b/rtc_base/rtc_certificate_unittest.cc @@ -12,9 +12,11 @@ #include +#include #include #include +#include "api/scoped_refptr.h" #include "rtc_base/checks.h" #include "rtc_base/numerics/safe_conversions.h" #include "rtc_base/ssl_identity.h" @@ -25,7 +27,7 @@ namespace webrtc { namespace { -static const char* kTestCertCommonName = "RTCCertificateTest's certificate"; +const char* kTestCertCommonName = "RTCCertificateTest's certificate"; } // namespace diff --git a/rtc_base/server_socket_adapters.cc b/rtc_base/server_socket_adapters.cc index e7e0e6670f..c3416e6ba0 100644 --- a/rtc_base/server_socket_adapters.cc +++ b/rtc_base/server_socket_adapters.cc @@ -10,9 +10,14 @@ #include "rtc_base/server_socket_adapters.h" -#include - -#include "rtc_base/byte_buffer.h" +#include +#include +#include + +#include "api/array_view.h" +#include "rtc_base/checks.h" +#include "rtc_base/socket.h" +#include "rtc_base/socket_adapters.h" namespace webrtc { diff --git a/rtc_base/server_socket_adapters.h b/rtc_base/server_socket_adapters.h index f9eeb1f963..93e3127e0f 100644 --- a/rtc_base/server_socket_adapters.h +++ b/rtc_base/server_socket_adapters.h @@ -11,7 +11,12 @@ #ifndef RTC_BASE_SERVER_SOCKET_ADAPTERS_H_ #define RTC_BASE_SERVER_SOCKET_ADAPTERS_H_ +#include + +#include "rtc_base/socket.h" #include "rtc_base/socket_adapters.h" +#include "rtc_base/socket_address.h" +#include "rtc_base/third_party/sigslot/sigslot.h" namespace webrtc { diff --git a/rtc_base/sigslot_unittest.cc b/rtc_base/sigslot_unittest.cc index e9fdba503c..d2829ee52b 100644 --- a/rtc_base/sigslot_unittest.cc +++ b/rtc_base/sigslot_unittest.cc @@ -33,7 +33,7 @@ template { public: SigslotReceiver() : signal_(nullptr), signal_count_(0) {} - ~SigslotReceiver() {} + ~SigslotReceiver() override {} // Provide copy constructor so that tests can exercise the has_slots copy // constructor. @@ -70,8 +70,8 @@ class SigslotSlotTest : public ::testing::Test { TemplateIsMT(&mt_policy); } - virtual void SetUp() { Connect(); } - virtual void TearDown() { Disconnect(); } + void SetUp() override { Connect(); } + void TearDown() override { Disconnect(); } void Disconnect() { st_receiver_.Disconnect(); diff --git a/rtc_base/socket_address.cc b/rtc_base/socket_address.cc index 7c08bf42ef..f9c21f92f4 100644 --- a/rtc_base/socket_address.cc +++ b/rtc_base/socket_address.cc @@ -230,6 +230,22 @@ bool SocketAddress::IsUnresolvedIP() const { return IPIsUnspec(ip_) && !literal_ && !hostname_.empty(); } +IPAddressType SocketAddress::GetIPAddressType() const { + if (IsUnresolvedIP()) { + return IPAddressType::kUnknown; + } + if (IsAnyIP()) { + return IPAddressType::kAny; + } + if (IsLoopbackIP()) { + return IPAddressType::kLoopback; + } + if (IsPrivateIP()) { + return IPAddressType::kPrivate; + } + return IPAddressType::kPublic; +} + bool SocketAddress::operator==(const SocketAddress& addr) const { return EqualIPs(addr) && EqualPorts(addr); } diff --git a/rtc_base/socket_address.h b/rtc_base/socket_address.h index 99fd6a6e81..25547b2061 100644 --- a/rtc_base/socket_address.h +++ b/rtc_base/socket_address.h @@ -11,6 +11,8 @@ #ifndef RTC_BASE_SOCKET_ADDRESS_H_ #define RTC_BASE_SOCKET_ADDRESS_H_ +#include +#include #include #include "absl/strings/string_view.h" @@ -148,6 +150,9 @@ class RTC_EXPORT SocketAddress { // Determines whether the hostname has been resolved to an IP. bool IsUnresolvedIP() const; + // Returns the IP Address type as an enum. + IPAddressType GetIPAddressType() const; + // Determines whether this address is identical to the given one. bool operator==(const SocketAddress& addr) const; inline bool operator!=(const SocketAddress& addr) const { diff --git a/rtc_base/socket_unittest.cc b/rtc_base/socket_unittest.cc index 4f5d219a4f..bd3c8606b2 100644 --- a/rtc_base/socket_unittest.cc +++ b/rtc_base/socket_unittest.cc @@ -24,7 +24,6 @@ #include "absl/strings/string_view.h" #include "api/test/rtc_error_matchers.h" #include "api/transport/ecn_marking.h" -#include "rtc_base/arraysize.h" #include "rtc_base/async_udp_socket.h" #include "rtc_base/buffer.h" #include "rtc_base/gunit.h" @@ -992,7 +991,7 @@ void SocketTest::SingleFlowControlCallbackInternal(const IPAddress& loopback) { // Fill the socket buffer. char buf[1024 * 16] = {0}; int sends = 0; - while (++sends && accepted->Send(&buf, arraysize(buf)) != -1) { + while (++sends && accepted->Send(&buf, std::size(buf)) != -1) { } EXPECT_TRUE(accepted->IsBlocking()); @@ -1003,7 +1002,7 @@ void SocketTest::SingleFlowControlCallbackInternal(const IPAddress& loopback) { // Pull data. for (int i = 0; i < sends; ++i) { - client->Recv(buf, arraysize(buf), nullptr); + client->Recv(buf, std::size(buf), nullptr); } // Expect at least one additional writable callback. @@ -1015,7 +1014,7 @@ void SocketTest::SingleFlowControlCallbackInternal(const IPAddress& loopback) { // callbacks. int extras = 0; for (int i = 0; i < 100; ++i) { - accepted->Send(&buf, arraysize(buf)); + accepted->Send(&buf, std::size(buf)); Thread::Current()->ProcessMessages(1); if (sink.Check(accepted.get(), SSE_WRITE)) { extras++; diff --git a/rtc_base/ssl_adapter_unittest.cc b/rtc_base/ssl_adapter_unittest.cc index 0861e9685e..9281474534 100644 --- a/rtc_base/ssl_adapter_unittest.cc +++ b/rtc_base/ssl_adapter_unittest.cc @@ -15,6 +15,7 @@ #include #include +#include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "api/test/rtc_error_matchers.h" #include "api/units/time_delta.h" @@ -25,7 +26,6 @@ #include "rtc_base/ssl_certificate.h" #include "rtc_base/ssl_identity.h" #include "rtc_base/ssl_stream_adapter.h" -#include "rtc_base/string_encode.h" #include "rtc_base/third_party/sigslot/sigslot.h" #include "rtc_base/thread.h" #include "rtc_base/virtual_socket_server.h" @@ -52,7 +52,7 @@ static webrtc::Socket* CreateSocket() { // Simple mock for the certificate verifier. class MockCertVerifier : public webrtc::SSLCertificateVerifier { public: - virtual ~MockCertVerifier() = default; + ~MockCertVerifier() override = default; MOCK_METHOD(bool, Verify, (const webrtc::SSLCertificate&), (override)); }; @@ -61,7 +61,7 @@ class MockCertVerifier : public webrtc::SSLCertificateVerifier { class SSLAdapterTestDummy : public sigslot::has_slots<> { public: explicit SSLAdapterTestDummy() : socket_(CreateSocket()) {} - virtual ~SSLAdapterTestDummy() = default; + ~SSLAdapterTestDummy() override = default; void CreateSSLAdapter(webrtc::Socket* socket, webrtc::SSLRole role) { ssl_adapter_.reset(webrtc::SSLAdapter::Create(socket)); diff --git a/rtc_base/ssl_certificate.cc b/rtc_base/ssl_certificate.cc index 7db106cd6b..403638cd67 100644 --- a/rtc_base/ssl_certificate.cc +++ b/rtc_base/ssl_certificate.cc @@ -20,17 +20,20 @@ #include "absl/algorithm/container.h" #include "absl/strings/string_view.h" #include "api/array_view.h" +#include "rtc_base/base64.h" #include "rtc_base/buffer.h" #include "rtc_base/openssl.h" +#include "rtc_base/ssl_fingerprint.h" + // IWYU pragma: begin_keep #ifdef OPENSSL_IS_BORINGSSL +#include "rtc_base/boringssl_certificate.h" #include "rtc_base/boringssl_identity.h" #else +#include "rtc_base/openssl_certificate.h" #include "rtc_base/openssl_identity.h" #endif // IWYU pragma: end_keep -#include "rtc_base/base64.h" -#include "rtc_base/ssl_fingerprint.h" namespace webrtc { @@ -138,7 +141,7 @@ std::unique_ptr SSLCertificate::FromPEMString( #ifdef OPENSSL_IS_BORINGSSL return BoringSSLCertificate::FromPEMString(pem_string); #else - return webrtc::OpenSSLCertificate::FromPEMString(pem_string); + return OpenSSLCertificate::FromPEMString(pem_string); #endif } diff --git a/rtc_base/ssl_identity_unittest.cc b/rtc_base/ssl_identity_unittest.cc index 3fd8ac7fe0..ec1a80078b 100644 --- a/rtc_base/ssl_identity_unittest.cc +++ b/rtc_base/ssl_identity_unittest.cc @@ -87,7 +87,7 @@ const unsigned char kTestCertSha512[] = { // and the update changes the string form of the keys, these will have to be // updated too. The fingerprint, fingerprint algorithm and base64 certificate // were created by calling `identity->certificate().GetStats()`. -static const char kRSA_PRIVATE_KEY_PEM[] = +const char kRSA_PRIVATE_KEY_PEM[] = "-----BEGIN PRI" // Linebreak to avoid detection of private "VATE KEY-----\n" // keys by linters. "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAMQPqDStRlYeDpkX\n" @@ -105,14 +105,14 @@ static const char kRSA_PRIVATE_KEY_PEM[] = "bhvEzY/fu8gEp+EzsER96/D79az5z1BaMGL5OPM2xHBPJATKlswnAa7Lp3QKGZGk\n" "TxslfL18J71s\n" "-----END PRIVATE KEY-----\n"; -static const char kRSA_PUBLIC_KEY_PEM[] = +const char kRSA_PUBLIC_KEY_PEM[] = "-----BEGIN PUBLIC KEY-----\n" "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDED6g0rUZWHg6ZF3q0Zr/mtZ2j\n" "PL0lUmNIBtqZZ656H1YlkVtzEalgvtNtDLCI94T2XkgJ7f8vxS/56+BGuzV3MHUa\n" "Nf9cRCu1P3/3I0oNWrp8rxwh8HBXDK99Ryxbx69GYHBcG4CLhSzRJe5CuRzDvQD8\n" "9Z7VI3pPAZgY/MjJfQIDAQAB\n" "-----END PUBLIC KEY-----\n"; -static const char kRSA_CERT_PEM[] = +const char kRSA_CERT_PEM[] = "-----BEGIN CERTIFICATE-----\n" "MIIBnDCCAQWgAwIBAgIJAOEHLgeWYwrpMA0GCSqGSIb3DQEBCwUAMBAxDjAMBgNV\n" "BAMMBXRlc3QxMB4XDTE2MDQyNDE4MTAyMloXDTE2MDUyNTE4MTAyMlowEDEOMAwG\n" @@ -124,11 +124,11 @@ static const char kRSA_CERT_PEM[] = "yTpU3ixErjQvoZew5ngXTEvTY8BSQUijJEaLWh8n6NDKRbEGTdAk8nPAmq9hdCFq\n" "e3UkexqNHm3g/VxG4NUC1Y+w29ai0/Rgh+VvgbDwK+Q=\n" "-----END CERTIFICATE-----\n"; -static const char kRSA_FINGERPRINT[] = +const char kRSA_FINGERPRINT[] = "3C:E8:B2:70:09:CF:A9:09:5A:F4:EF:8F:8D:8A:32:FF:EA:04:91:BA:6E:D4:17:78:16" ":2A:EE:F9:9A:DD:E2:2B"; -static const char kRSA_FINGERPRINT_ALGORITHM[] = "sha-256"; -static const char kRSA_BASE64_CERTIFICATE[] = +const char kRSA_FINGERPRINT_ALGORITHM[] = "sha-256"; +const char kRSA_BASE64_CERTIFICATE[] = "MIIBnDCCAQWgAwIBAgIJAOEHLgeWYwrpMA0GCSqGSIb3DQEBCwUAMBAxDjAMBgNVBAMMBXRlc3" "QxMB4XDTE2MDQyNDE4MTAyMloXDTE2MDUyNTE4MTAyMlowEDEOMAwGA1UEAwwFdGVzdDEwgZ8w" "DQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMQPqDStRlYeDpkXerRmv+a1naM8vSVSY0gG2plnrn" @@ -138,19 +138,19 @@ static const char kRSA_BASE64_CERTIFICATE[] = "i8dxyTpU3ixErjQvoZew5ngXTEvTY8BSQUijJEaLWh8n6NDKRbEGTdAk8nPAmq9hdCFqe3Ukex" "qNHm3g/VxG4NUC1Y+w29ai0/Rgh+VvgbDwK+Q="; -static const char kECDSA_PRIVATE_KEY_PEM[] = +const char kECDSA_PRIVATE_KEY_PEM[] = "-----BEGIN PRI" // Linebreak to avoid detection of private "VATE KEY-----\n" // keys by linters. "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg/AkEA2hklq7dQ2rN\n" "ZxYL6hOUACL4pn7P4FYlA3ZQhIChRANCAAR7YgdO3utP/8IqVRq8G4VZKreMAxeN\n" "rUa12twthv4uFjuHAHa9D9oyAjncmn+xvZZRyVmKrA56jRzENcEEHoAg\n" "-----END PRIVATE KEY-----\n"; -static const char kECDSA_PUBLIC_KEY_PEM[] = +const char kECDSA_PUBLIC_KEY_PEM[] = "-----BEGIN PUBLIC KEY-----\n" "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEe2IHTt7rT//CKlUavBuFWSq3jAMX\n" "ja1GtdrcLYb+LhY7hwB2vQ/aMgI53Jp/sb2WUclZiqwOeo0cxDXBBB6AIA==\n" "-----END PUBLIC KEY-----\n"; -static const char kECDSA_CERT_PEM[] = +const char kECDSA_CERT_PEM[] = "-----BEGIN CERTIFICATE-----\n" "MIIBFDCBu6ADAgECAgkArpkxjw62sW4wCgYIKoZIzj0EAwIwEDEOMAwGA1UEAwwF\n" "dGVzdDMwHhcNMTYwNDI0MTgxNDM4WhcNMTYwNTI1MTgxNDM4WjAQMQ4wDAYDVQQD\n" @@ -159,11 +159,11 @@ static const char kECDSA_CERT_PEM[] = "gCAwCgYIKoZIzj0EAwIDSAAwRQIhANyreQ/K5yuPPpirsd0e/4WGLHou6bIOSQks\n" "DYzo56NmAiAKOr3u8ol3LmygbUCwEvtWrS8QcJDygxHPACo99hkekw==\n" "-----END CERTIFICATE-----\n"; -static const char kECDSA_FINGERPRINT[] = +const char kECDSA_FINGERPRINT[] = "9F:47:FA:88:76:3D:18:B8:00:A0:59:9D:C3:5D:34:0B:1F:B8:99:9E:68:DA:F3:A5:DA" ":50:33:A9:FF:4D:31:89"; -static const char kECDSA_FINGERPRINT_ALGORITHM[] = "sha-256"; -static const char kECDSA_BASE64_CERTIFICATE[] = +const char kECDSA_FINGERPRINT_ALGORITHM[] = "sha-256"; +const char kECDSA_BASE64_CERTIFICATE[] = "MIIBFDCBu6ADAgECAgkArpkxjw62sW4wCgYIKoZIzj0EAwIwEDEOMAwGA1UEAwwFdGVzdDMwHh" "cNMTYwNDI0MTgxNDM4WhcNMTYwNTI1MTgxNDM4WjAQMQ4wDAYDVQQDDAV0ZXN0MzBZMBMGByqG" "SM49AgEGCCqGSM49AwEHA0IABHtiB07e60//wipVGrwbhVkqt4wDF42tRrXa3C2G/i4WO4cAdr" diff --git a/rtc_base/ssl_stream_adapter.h b/rtc_base/ssl_stream_adapter.h index f8f817337a..baa491235e 100644 --- a/rtc_base/ssl_stream_adapter.h +++ b/rtc_base/ssl_stream_adapter.h @@ -125,8 +125,7 @@ class SSLStreamAdapter : public StreamInterface { // Caller is responsible for freeing the returned object. static std::unique_ptr Create( std::unique_ptr stream, - absl::AnyInvocable handshake_error = - nullptr, + absl::AnyInvocable handshake_error = nullptr, const FieldTrialsView* field_trials = nullptr); SSLStreamAdapter() = default; diff --git a/rtc_base/ssl_stream_adapter_unittest.cc b/rtc_base/ssl_stream_adapter_unittest.cc index fe2430ee35..f78aaf17c8 100644 --- a/rtc_base/ssl_stream_adapter_unittest.cc +++ b/rtc_base/ssl_stream_adapter_unittest.cc @@ -34,6 +34,7 @@ #include "absl/strings/string_view.h" #include "api/array_view.h" #include "api/crypto/crypto_options.h" +#include "api/field_trials.h" #include "api/sequence_checker.h" #include "api/task_queue/pending_task_safety_flag.h" #include "api/test/rtc_error_matchers.h" @@ -52,20 +53,22 @@ #include "rtc_base/third_party/sigslot/sigslot.h" #include "rtc_base/thread.h" #include "rtc_base/time_utils.h" +#include "test/create_test_field_trials.h" #include "test/gmock.h" #include "test/gtest.h" -#include "test/scoped_key_value_config.h" #include "test/wait_until.h" +namespace webrtc { +namespace { + using ::testing::Combine; using ::testing::NotNull; using ::testing::tuple; using ::testing::Values; using ::testing::WithParamInterface; -using ::webrtc::SafeTask; // Generated using `openssl genrsa -out key.pem 2048` -static const char kRSA_PRIVATE_KEY_PEM[] = +const char kRSA_PRIVATE_KEY_PEM[] = "-----BEGIN RSA PRI" // Linebreak to avoid detection of private "VATE KEY-----\n" // keys by linters. "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC4XOJ6agj673j+\n" @@ -101,7 +104,7 @@ static const char kRSA_PRIVATE_KEY_PEM[] = // `openssl req -new -x509 -key key.pem -out cert.pem -days 365` // after setting the machine date to something that will ensure the // certificate is expired. -static const char kCERT_PEM[] = +const char kCERT_PEM[] = "-----BEGIN CERTIFICATE-----\n" "MIIDjTCCAnWgAwIBAgIUTkCy4o8+4W/86RYmgWc8FEhWTzYwDQYJKoZIhvcNAQEL\n" "BQAwVjELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoM\n" @@ -126,7 +129,7 @@ static const char kCERT_PEM[] = "-----END CERTIFICATE-----\n"; // Google GTS CA 1C3 certificate. Obtained from https://www.webrtc.org -static const char kIntCert1[] = +const char kIntCert1[] = "-----BEGIN CERTIFICATE-----\n" "MIIFljCCA36gAwIBAgINAgO8U1lrNMcY9QFQZjANBgkqhkiG9w0BAQsFADBHMQsw\n" "CQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExMQzEU\n" @@ -161,7 +164,7 @@ static const char kIntCert1[] = "-----END CERTIFICATE-----\n"; // Google GTS Root R1 certificate. Obtained from https://www.webrtc.org -static const char kCACert[] = +const char kCACert[] = "-----BEGIN CERTIFICATE-----\n" "MIIFWjCCA0KgAwIBAgIQbkepxUtHDA3sM9CJuRz04TANBgkqhkiG9w0BAQwFADBH\n" "MQswCQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExM\n" @@ -206,9 +209,9 @@ class SSLStreamAdapterTestBase; // This is needed because in this file, tests connect both client and server // streams (SSLDummyStream) to the same underlying `stream` objects // (see CreateClientStream() and CreateServerStream()). -class StreamWrapper : public webrtc::StreamInterface { +class StreamWrapper : public StreamInterface { public: - explicit StreamWrapper(std::unique_ptr stream) + explicit StreamWrapper(std::unique_ptr stream) : stream_(std::move(stream)) { stream_->SetEventCallback([this](int events, int err) { RTC_DCHECK_RUN_ON(&callback_sequence_); @@ -226,28 +229,28 @@ class StreamWrapper : public webrtc::StreamInterface { callbacks_.RemoveReceivers(removal_tag); } - webrtc::StreamState GetState() const override { return stream_->GetState(); } + StreamState GetState() const override { return stream_->GetState(); } void Close() override { stream_->Close(); } - webrtc::StreamResult Read(webrtc::ArrayView buffer, - size_t& read, - int& error) override { + StreamResult Read(ArrayView buffer, + size_t& read, + int& error) override { return stream_->Read(buffer, read, error); } - webrtc::StreamResult Write(webrtc::ArrayView data, - size_t& written, - int& error) override { + StreamResult Write(ArrayView data, + size_t& written, + int& error) override { return stream_->Write(data, written, error); } private: - const std::unique_ptr stream_; - webrtc::CallbackList callbacks_; + const std::unique_ptr stream_; + CallbackList callbacks_; }; -class SSLDummyStream final : public webrtc::StreamInterface { +class SSLDummyStream final : public StreamInterface { public: SSLDummyStream(SSLStreamAdapterTestBase* test, absl::string_view side, @@ -267,30 +270,30 @@ class SSLDummyStream final : public webrtc::StreamInterface { out_->UnsubscribeStreamEvent(this); } - webrtc::StreamState GetState() const override { return webrtc::SS_OPEN; } + StreamState GetState() const override { return SS_OPEN; } - webrtc::StreamResult Read(webrtc::ArrayView buffer, - size_t& read, - int& error) override { - webrtc::StreamResult r; + StreamResult Read(ArrayView buffer, + size_t& read, + int& error) override { + StreamResult r; r = in_->Read(buffer, read, error); - if (r == webrtc::SR_BLOCK) - return webrtc::SR_BLOCK; - if (r == webrtc::SR_EOS) - return webrtc::SR_EOS; + if (r == SR_BLOCK) + return SR_BLOCK; + if (r == SR_EOS) + return SR_EOS; - if (r != webrtc::SR_SUCCESS) { + if (r != SR_SUCCESS) { ADD_FAILURE(); - return webrtc::SR_ERROR; + return SR_ERROR; } - return webrtc::SR_SUCCESS; + return SR_SUCCESS; } // Catch readability events on in and pass them up. void OnEventIn(int sig, int err) { - int mask = (webrtc::SE_READ | webrtc::SE_CLOSE); + int mask = (SE_READ | SE_CLOSE); if (sig & mask) { RTC_LOG(LS_VERBOSE) << "SSLDummyStream::OnEventIn side=" << side_ @@ -301,24 +304,24 @@ class SSLDummyStream final : public webrtc::StreamInterface { // Catch writeability events on out and pass them up. void OnEventOut(int sig, int err) { - if (sig & webrtc::SE_WRITE) { + if (sig & SE_WRITE) { RTC_LOG(LS_VERBOSE) << "SSLDummyStream::OnEventOut side=" << side_ << " sig=" << sig << " forwarding upward"; - PostEvent(sig & webrtc::SE_WRITE, 0); + PostEvent(sig & SE_WRITE, 0); } } // Write to the outgoing FifoBuffer - webrtc::StreamResult WriteData(webrtc::ArrayView data, - size_t& written, - int& error) { + StreamResult WriteData(ArrayView data, + size_t& written, + int& error) { return out_->Write(data, written, error); } - webrtc::StreamResult Write(webrtc::ArrayView data, - size_t& written, - int& error) override; + StreamResult Write(ArrayView data, + size_t& written, + int& error) override; void Close() override { RTC_LOG(LS_INFO) << "Closing outbound stream"; @@ -333,8 +336,8 @@ class SSLDummyStream final : public webrtc::StreamInterface { })); } - webrtc::ScopedTaskSafety task_safety_; - webrtc::Thread* const thread_ = webrtc::Thread::Current(); + ScopedTaskSafety task_safety_; + Thread* const thread_ = Thread::Current(); SSLStreamAdapterTestBase* test_base_; const std::string side_; StreamWrapper* const in_; @@ -342,7 +345,7 @@ class SSLDummyStream final : public webrtc::StreamInterface { bool first_packet_; }; -class BufferQueueStream : public webrtc::StreamInterface { +class BufferQueueStream : public StreamInterface { public: BufferQueueStream(size_t capacity, size_t default_size) : buffer_(capacity, default_size) {} @@ -350,42 +353,42 @@ class BufferQueueStream : public webrtc::StreamInterface { // Implementation of abstract StreamInterface methods. // A buffer queue stream is always "open". - webrtc::StreamState GetState() const override { return webrtc::SS_OPEN; } + StreamState GetState() const override { return SS_OPEN; } // Reading a buffer queue stream will either succeed or block. - webrtc::StreamResult Read(webrtc::ArrayView buffer, - size_t& read, - int& error) override { + StreamResult Read(ArrayView buffer, + size_t& read, + int& error) override { const bool was_writable = buffer_.is_writable(); if (!buffer_.ReadFront(buffer.data(), buffer.size(), &read)) - return webrtc::SR_BLOCK; + return SR_BLOCK; if (!was_writable) NotifyWritableForTest(); - return webrtc::SR_SUCCESS; + return SR_SUCCESS; } // Writing to a buffer queue stream will either succeed or block. - webrtc::StreamResult Write(webrtc::ArrayView data, - size_t& written, - int& error) override { + StreamResult Write(ArrayView data, + size_t& written, + int& error) override { const bool was_readable = buffer_.is_readable(); if (!buffer_.WriteBack(data.data(), data.size(), &written)) - return webrtc::SR_BLOCK; + return SR_BLOCK; if (!was_readable) NotifyReadableForTest(); - return webrtc::SR_SUCCESS; + return SR_SUCCESS; } // A buffer queue stream can not be closed. void Close() override {} protected: - void NotifyReadableForTest() { PostEvent(webrtc::SE_READ, 0); } - void NotifyWritableForTest() { PostEvent(webrtc::SE_WRITE, 0); } + void NotifyReadableForTest() { PostEvent(SE_READ, 0); } + void NotifyWritableForTest() { PostEvent(SE_WRITE, 0); } private: void PostEvent(int events, int err) { @@ -395,25 +398,25 @@ class BufferQueueStream : public webrtc::StreamInterface { })); } - webrtc::Thread* const thread_ = webrtc::Thread::Current(); - webrtc::ScopedTaskSafety task_safety_; - webrtc::BufferQueue buffer_; + Thread* const thread_ = Thread::Current(); + ScopedTaskSafety task_safety_; + BufferQueue buffer_; }; -static const int kBufferCapacity = 1; -static const size_t kDefaultBufferSize = 2048; +const int kBufferCapacity = 1; +const size_t kDefaultBufferSize = 2048; class SSLStreamAdapterTestBase : public ::testing::Test, public sigslot::has_slots<> { public: - SSLStreamAdapterTestBase( - absl::string_view client_cert_pem, - absl::string_view client_private_key_pem, - bool dtls, - webrtc::KeyParams client_key_type = webrtc::KeyParams(webrtc::KT_DEFAULT), - webrtc::KeyParams server_key_type = webrtc::KeyParams(webrtc::KT_DEFAULT), - std::pair digest = - std::make_pair(webrtc::DIGEST_SHA_256, SHA256_DIGEST_LENGTH)) + SSLStreamAdapterTestBase(absl::string_view client_cert_pem, + absl::string_view client_private_key_pem, + bool dtls, + KeyParams client_key_type = KeyParams(KT_DEFAULT), + KeyParams server_key_type = KeyParams(KT_DEFAULT), + std::pair digest = + std::make_pair(DIGEST_SHA_256, + SHA256_DIGEST_LENGTH)) : client_cert_pem_(client_cert_pem), client_private_key_pem_(client_private_key_pem), client_key_type_(client_key_type), @@ -426,29 +429,28 @@ class SSLStreamAdapterTestBase : public ::testing::Test, lose_first_packet_(false), damage_(false), dtls_(dtls), - handshake_wait_(webrtc::TimeDelta::Millis(5000)), + handshake_wait_(TimeDelta::Millis(5000)), identities_set_(false) { // Set use of the test RNG to get predictable loss patterns. - webrtc::SetRandomTestMode(true); + SetRandomTestMode(true); } ~SSLStreamAdapterTestBase() override { // Put it back for the next test. - webrtc::SetRandomTestMode(false); + SetRandomTestMode(false); } void SetUp() override { InitializeClientAndServerStreams(); - std::unique_ptr client_identity; + std::unique_ptr client_identity; if (!client_cert_pem_.empty() && !client_private_key_pem_.empty()) { - client_identity = webrtc::SSLIdentity::CreateFromPEMStrings( + client_identity = SSLIdentity::CreateFromPEMStrings( client_private_key_pem_, client_cert_pem_); } else { - client_identity = webrtc::SSLIdentity::Create("client", client_key_type_); + client_identity = SSLIdentity::Create("client", client_key_type_); } - auto server_identity = - webrtc::SSLIdentity::Create("server", server_key_type_); + auto server_identity = SSLIdentity::Create("server", server_key_type_); client_ssl_->SetIdentity(std::move(client_identity)); server_ssl_->SetIdentity(std::move(server_identity)); @@ -459,8 +461,8 @@ class SSLStreamAdapterTestBase : public ::testing::Test, server_ssl_.reset(nullptr); } - virtual std::unique_ptr CreateClientStream() = 0; - virtual std::unique_ptr CreateServerStream() = 0; + virtual std::unique_ptr CreateClientStream() = 0; + virtual std::unique_ptr CreateServerStream() = 0; void InitializeClientAndServerStreams( absl::string_view client_experiment = "", @@ -468,22 +470,15 @@ class SSLStreamAdapterTestBase : public ::testing::Test, // Note: `client_ssl_` and `server_ssl_` may be non-nullptr. // The field trials are read when the OpenSSLStreamAdapter is initialized. - using webrtc::test::ScopedKeyValueConfig; { - std::unique_ptr trial( - client_experiment.empty() - ? nullptr - : new ScopedKeyValueConfig(client_experiment)); - client_ssl_ = webrtc::SSLStreamAdapter::Create(CreateClientStream(), - nullptr, trial.get()); + FieldTrials trial = CreateTestFieldTrials(client_experiment); + client_ssl_ = + SSLStreamAdapter::Create(CreateClientStream(), nullptr, &trial); } { - std::unique_ptr trial( - server_experiment.empty() - ? nullptr - : new ScopedKeyValueConfig(server_experiment)); - server_ssl_ = webrtc::SSLStreamAdapter::Create(CreateServerStream(), - nullptr, trial.get()); + FieldTrials trial = CreateTestFieldTrials(server_experiment); + server_ssl_ = + SSLStreamAdapter::Create(CreateServerStream(), nullptr, &trial); } client_ssl_->SetEventCallback( [this](int events, int err) { OnClientEvent(events, err); }); @@ -499,32 +494,31 @@ class SSLStreamAdapterTestBase : public ::testing::Test, time_t now = time(nullptr); - webrtc::SSLIdentityParams client_params; - client_params.key_params = webrtc::KeyParams(webrtc::KT_DEFAULT); + SSLIdentityParams client_params; + client_params.key_params = KeyParams(KT_DEFAULT); client_params.common_name = "client"; client_params.not_before = now + not_before; client_params.not_after = now + not_after; - auto client_identity = webrtc::SSLIdentity::CreateForTest(client_params); + auto client_identity = SSLIdentity::CreateForTest(client_params); - webrtc::SSLIdentityParams server_params; - server_params.key_params = webrtc::KeyParams(webrtc::KT_DEFAULT); + SSLIdentityParams server_params; + server_params.key_params = KeyParams(KT_DEFAULT); server_params.common_name = "server"; server_params.not_before = now + not_before; server_params.not_after = now + not_after; - auto server_identity = webrtc::SSLIdentity::CreateForTest(server_params); + auto server_identity = SSLIdentity::CreateForTest(server_params); client_ssl_->SetIdentity(std::move(client_identity)); server_ssl_->SetIdentity(std::move(server_identity)); } void SetPeerIdentitiesByDigest(bool correct, bool expect_success) { - webrtc::Buffer server_digest(0, EVP_MAX_MD_SIZE); - webrtc::Buffer client_digest(0, EVP_MAX_MD_SIZE); - webrtc::SSLPeerCertificateDigestError err; - webrtc::SSLPeerCertificateDigestError expected_err = - expect_success - ? webrtc::SSLPeerCertificateDigestError::NONE - : webrtc::SSLPeerCertificateDigestError::VERIFICATION_FAILED; + Buffer server_digest(0, EVP_MAX_MD_SIZE); + Buffer client_digest(0, EVP_MAX_MD_SIZE); + SSLPeerCertificateDigestError err; + SSLPeerCertificateDigestError expected_err = + expect_success ? SSLPeerCertificateDigestError::NONE + : SSLPeerCertificateDigestError::VERIFICATION_FAILED; RTC_LOG(LS_INFO) << "Setting peer identities by digest"; RTC_DCHECK(server_identity()); @@ -554,8 +548,8 @@ class SSLStreamAdapterTestBase : public ::testing::Test, identities_set_ = true; } - void SetupProtocolVersions(webrtc::SSLProtocolVersion server_version, - webrtc::SSLProtocolVersion client_version) { + void SetupProtocolVersions(SSLProtocolVersion server_version, + SSLProtocolVersion client_version) { server_ssl_->SetMaxProtocolVersion(server_version); client_ssl_->SetMaxProtocolVersion(client_version); } @@ -585,20 +579,19 @@ class SSLStreamAdapterTestBase : public ::testing::Test, // Now run the handshake if (expect_success) { - EXPECT_THAT(webrtc::WaitUntil( + EXPECT_THAT(WaitUntil( [&] { - return (client_ssl_->GetState() == webrtc::SS_OPEN) && - (server_ssl_->GetState() == webrtc::SS_OPEN); + return (client_ssl_->GetState() == SS_OPEN) && + (server_ssl_->GetState() == SS_OPEN); }, ::testing::IsTrue(), {.timeout = handshake_wait_, .clock = &clock_}), - webrtc::IsRtcOk()); + IsRtcOk()); } else { - EXPECT_THAT( - webrtc::WaitUntil([&] { return client_ssl_->GetState(); }, - ::testing::Eq(webrtc::SS_CLOSED), + EXPECT_THAT(WaitUntil([&] { return client_ssl_->GetState(); }, + ::testing::Eq(SS_CLOSED), {.timeout = handshake_wait_, .clock = &clock_}), - webrtc::IsRtcOk()); + IsRtcOk()); } } @@ -606,7 +599,7 @@ class SSLStreamAdapterTestBase : public ::testing::Test, // Only works for BoringSSL which allows advancing the fake clock. void TestHandshakeTimeout() { int64_t time_start = clock_.TimeNanos(); - webrtc::TimeDelta time_increment = webrtc::TimeDelta::Millis(1000); + TimeDelta time_increment = TimeDelta::Millis(1000); if (!dtls_) { // Make sure we simulate a reliable network for TLS. @@ -632,19 +625,19 @@ class SSLStreamAdapterTestBase : public ::testing::Test, // Now wait for the handshake to timeout (or fail after an hour of simulated // time). - while (client_ssl_->GetState() == webrtc::SS_OPENING && - (webrtc::TimeDiff(clock_.TimeNanos(), time_start) < - 3600 * webrtc::kNumNanosecsPerSec)) { - EXPECT_THAT(webrtc::WaitUntil( + while (client_ssl_->GetState() == SS_OPENING && + (TimeDiff(clock_.TimeNanos(), time_start) < + 3600 * kNumNanosecsPerSec)) { + EXPECT_THAT(WaitUntil( [&] { - return !((client_ssl_->GetState() == webrtc::SS_OPEN) && - (server_ssl_->GetState() == webrtc::SS_OPEN)); + return !((client_ssl_->GetState() == SS_OPEN) && + (server_ssl_->GetState() == SS_OPEN)); }, ::testing::IsTrue(), {.clock = &clock_}), - webrtc::IsRtcOk()); + IsRtcOk()); clock_.AdvanceTime(time_increment); } - EXPECT_EQ(client_ssl_->GetState(), webrtc::SS_CLOSED); + EXPECT_EQ(client_ssl_->GetState(), SS_CLOSED); } // This tests that the handshake can complete before the identity is verified, @@ -666,30 +659,30 @@ class SSLStreamAdapterTestBase : public ::testing::Test, ASSERT_EQ(0, client_ssl_->StartSSL()); // Now run the handshake. - EXPECT_THAT(webrtc::WaitUntil( + EXPECT_THAT(WaitUntil( [&] { return client_ssl_->IsTlsConnected() && server_ssl_->IsTlsConnected(); }, ::testing::IsTrue(), {.timeout = handshake_wait_, .clock = &clock_}), - webrtc::IsRtcOk()); + IsRtcOk()); // Until the identity has been verified, the state should still be // SS_OPENING and writes should return SR_BLOCK. - EXPECT_EQ(webrtc::SS_OPENING, client_ssl_->GetState()); - EXPECT_EQ(webrtc::SS_OPENING, server_ssl_->GetState()); + EXPECT_EQ(SS_OPENING, client_ssl_->GetState()); + EXPECT_EQ(SS_OPENING, server_ssl_->GetState()); uint8_t packet[1] = {0}; size_t sent; size_t read; int error; - EXPECT_EQ(webrtc::SR_BLOCK, client_ssl_->Write(packet, sent, error)); - EXPECT_EQ(webrtc::SR_BLOCK, server_ssl_->Write(packet, sent, error)); + EXPECT_EQ(SR_BLOCK, client_ssl_->Write(packet, sent, error)); + EXPECT_EQ(SR_BLOCK, server_ssl_->Write(packet, sent, error)); // Collect both of the certificate digests; needs to be done before calling // SetPeerCertificateDigest as that may reset the identity. - webrtc::Buffer server_digest(0, EVP_MAX_MD_SIZE); - webrtc::Buffer client_digest(0, EVP_MAX_MD_SIZE); + Buffer server_digest(0, EVP_MAX_MD_SIZE); + Buffer client_digest(0, EVP_MAX_MD_SIZE); ASSERT_THAT(server_identity(), NotNull()); ASSERT_TRUE(server_identity()->certificate().ComputeDigest( @@ -706,24 +699,23 @@ class SSLStreamAdapterTestBase : public ::testing::Test, } // Set the peer certificate digest for the client. - webrtc::SSLPeerCertificateDigestError err; - webrtc::SSLPeerCertificateDigestError expected_err = - valid_identity - ? webrtc::SSLPeerCertificateDigestError::NONE - : webrtc::SSLPeerCertificateDigestError::VERIFICATION_FAILED; + SSLPeerCertificateDigestError err; + SSLPeerCertificateDigestError expected_err = + valid_identity ? SSLPeerCertificateDigestError::NONE + : SSLPeerCertificateDigestError::VERIFICATION_FAILED; err = client_ssl_->SetPeerCertificateDigest(digest_algorithm_, server_digest); EXPECT_EQ(expected_err, err); // State should then transition to SS_OPEN or SS_CLOSED based on validation // of the identity. if (valid_identity) { - EXPECT_EQ(webrtc::SS_OPEN, client_ssl_->GetState()); + EXPECT_EQ(SS_OPEN, client_ssl_->GetState()); // If the client sends a packet while the server still hasn't verified the // client identity, the server should continue to return SR_BLOCK. - EXPECT_EQ(webrtc::SR_SUCCESS, client_ssl_->Write(packet, sent, error)); - EXPECT_EQ(webrtc::SR_BLOCK, server_ssl_->Read(packet, read, error)); + EXPECT_EQ(SR_SUCCESS, client_ssl_->Write(packet, sent, error)); + EXPECT_EQ(SR_BLOCK, server_ssl_->Read(packet, read, error)); } else { - EXPECT_EQ(webrtc::SS_CLOSED, client_ssl_->GetState()); + EXPECT_EQ(SS_CLOSED, client_ssl_->GetState()); } // Set the peer certificate digest for the server. @@ -731,27 +723,27 @@ class SSLStreamAdapterTestBase : public ::testing::Test, server_ssl_->SetPeerCertificateDigest(digest_algorithm_, client_digest); EXPECT_EQ(expected_err, err); if (valid_identity) { - EXPECT_EQ(webrtc::SS_OPEN, server_ssl_->GetState()); + EXPECT_EQ(SS_OPEN, server_ssl_->GetState()); } else { - EXPECT_EQ(webrtc::SS_CLOSED, server_ssl_->GetState()); + EXPECT_EQ(SS_CLOSED, server_ssl_->GetState()); } } - webrtc::StreamResult DataWritten(SSLDummyStream* from, - const void* data, - size_t data_len, - size_t& written, - int& error) { + StreamResult DataWritten(SSLDummyStream* from, + const void* data, + size_t data_len, + size_t& written, + int& error) { // Randomly drop loss_ percent of packets - if (webrtc::CreateRandomId() % 100 < static_cast(loss_)) { + if (CreateRandomId() % 100 < static_cast(loss_)) { RTC_LOG(LS_VERBOSE) << "Randomly dropping packet, size=" << data_len; written = data_len; - return webrtc::SR_SUCCESS; + return SR_SUCCESS; } if (dtls_ && (data_len > mtu_)) { RTC_LOG(LS_VERBOSE) << "Dropping packet > mtu, size=" << data_len; written = data_len; - return webrtc::SR_SUCCESS; + return SR_SUCCESS; } max_seen_mtu_ = std::max(max_seen_mtu_, data_len); @@ -764,12 +756,11 @@ class SSLStreamAdapterTestBase : public ::testing::Test, RTC_LOG(LS_VERBOSE) << "Damaging packet"; memcpy(&buf[0], data, data_len); buf[data_len - 1]++; - return from->WriteData(webrtc::MakeArrayView(&buf[0], data_len), written, - error); + return from->WriteData(MakeArrayView(&buf[0], data_len), written, error); } return from->WriteData( - webrtc::MakeArrayView(reinterpret_cast(data), data_len), + MakeArrayView(reinterpret_cast(data), data_len), written, error); } @@ -786,9 +777,7 @@ class SSLStreamAdapterTestBase : public ::testing::Test, void SetMtu(size_t mtu) { mtu_ = mtu; } size_t GetMaxSeenMtu() const { return max_seen_mtu_; } - void SetHandshakeWait(int wait) { - handshake_wait_ = webrtc::TimeDelta::Millis(wait); - } + void SetHandshakeWait(int wait) { handshake_wait_ = TimeDelta::Millis(wait); } void SetDtlsSrtpCryptoSuites(const std::vector& ciphers, bool client) { if (client) @@ -804,8 +793,8 @@ class SSLStreamAdapterTestBase : public ::testing::Test, return server_ssl_->GetDtlsSrtpCryptoSuite(retval); } - std::unique_ptr GetPeerCertificate(bool client) { - std::unique_ptr chain; + std::unique_ptr GetPeerCertificate(bool client) { + std::unique_ptr chain; if (client) chain = client_ssl_->GetPeerSSLCertChain(); else @@ -829,7 +818,7 @@ class SSLStreamAdapterTestBase : public ::testing::Test, // To be implemented by subclasses. virtual void WriteData() = 0; - virtual void ReadData(webrtc::StreamInterface* stream) = 0; + virtual void ReadData(StreamInterface* stream) = 0; virtual void TestTransfer(int size) = 0; private: @@ -837,11 +826,11 @@ class SSLStreamAdapterTestBase : public ::testing::Test, RTC_LOG(LS_VERBOSE) << "SSLStreamAdapterTestBase::OnClientEvent sig=" << sig; - if (sig & webrtc::SE_READ) { + if (sig & SE_READ) { ReadData(client_ssl_.get()); } - if (sig & webrtc::SE_WRITE) { + if (sig & SE_WRITE) { WriteData(); } } @@ -849,35 +838,35 @@ class SSLStreamAdapterTestBase : public ::testing::Test, void OnServerEvent(int sig, int err) { RTC_LOG(LS_VERBOSE) << "SSLStreamAdapterTestBase::OnServerEvent sig=" << sig; - if (sig & webrtc::SE_READ) { + if (sig & SE_READ) { ReadData(server_ssl_.get()); } } protected: - webrtc::SSLIdentity* client_identity() const { + SSLIdentity* client_identity() const { if (!client_ssl_) { return nullptr; } return client_ssl_->GetIdentityForTesting(); } - webrtc::SSLIdentity* server_identity() const { + SSLIdentity* server_identity() const { if (!server_ssl_) { return nullptr; } return server_ssl_->GetIdentityForTesting(); } - webrtc::AutoThread main_thread_; - webrtc::ScopedFakeClock clock_; + AutoThread main_thread_; + ScopedFakeClock clock_; std::string client_cert_pem_; std::string client_private_key_pem_; - webrtc::KeyParams client_key_type_; - webrtc::KeyParams server_key_type_; + KeyParams client_key_type_; + KeyParams server_key_type_; std::string digest_algorithm_; size_t digest_length_; - std::unique_ptr client_ssl_; - std::unique_ptr server_ssl_; + std::unique_ptr client_ssl_; + std::unique_ptr server_ssl_; int delay_; size_t mtu_; size_t max_seen_mtu_ = 0; @@ -885,14 +874,14 @@ class SSLStreamAdapterTestBase : public ::testing::Test, bool lose_first_packet_; bool damage_; bool dtls_; - webrtc::TimeDelta handshake_wait_; + TimeDelta handshake_wait_; bool identities_set_; }; class SSLStreamAdapterTestDTLSBase : public SSLStreamAdapterTestBase { public: - SSLStreamAdapterTestDTLSBase(webrtc::KeyParams param1, - webrtc::KeyParams param2, + SSLStreamAdapterTestDTLSBase(KeyParams param1, + KeyParams param2, std::pair digest) : SSLStreamAdapterTestBase("", "", true, param1, param2, digest), packet_size_(1000), @@ -906,12 +895,12 @@ class SSLStreamAdapterTestDTLSBase : public SSLStreamAdapterTestBase { count_(0), sent_(0) {} - std::unique_ptr CreateClientStream() override final { + std::unique_ptr CreateClientStream() final { return absl::WrapUnique( new SSLDummyStream(this, "c2s", &client_buffer_, &server_buffer_)); } - std::unique_ptr CreateServerStream() override final { + std::unique_ptr CreateServerStream() final { return absl::WrapUnique( new SSLDummyStream(this, "s2c", &server_buffer_, &client_buffer_)); } @@ -930,12 +919,12 @@ class SSLStreamAdapterTestDTLSBase : public SSLStreamAdapterTestBase { size_t sent; int error; - webrtc::StreamResult rv = client_ssl_->Write( - webrtc::MakeArrayView(packet, packet_size_), sent, error); - if (rv == webrtc::SR_SUCCESS) { + StreamResult rv = + client_ssl_->Write(MakeArrayView(packet, packet_size_), sent, error); + if (rv == SR_SUCCESS) { RTC_LOG(LS_VERBOSE) << "Sent: " << sent_; sent_++; - } else if (rv == webrtc::SR_BLOCK) { + } else if (rv == SR_BLOCK) { RTC_LOG(LS_VERBOSE) << "Blocked..."; break; } else { @@ -947,26 +936,26 @@ class SSLStreamAdapterTestDTLSBase : public SSLStreamAdapterTestBase { delete[] packet; } - void ReadData(webrtc::StreamInterface* stream) override final { + void ReadData(StreamInterface* stream) final { uint8_t buffer[2000]; size_t bread; int err2; - webrtc::StreamResult r; + StreamResult r; for (;;) { r = stream->Read(buffer, bread, err2); - if (r == webrtc::SR_ERROR) { + if (r == SR_ERROR) { // Unfortunately, errors are the way that the stream adapter // signals close right now stream->Close(); return; } - if (r == webrtc::SR_BLOCK) + if (r == SR_BLOCK) break; - ASSERT_EQ(webrtc::SR_SUCCESS, r); + ASSERT_EQ(SR_SUCCESS, r); RTC_LOG(LS_VERBOSE) << "Read " << bread; // Now parse the datagram @@ -988,20 +977,20 @@ class SSLStreamAdapterTestDTLSBase : public SSLStreamAdapterTestBase { WriteData(); - EXPECT_THAT(webrtc::WaitUntil([&] { return sent_; }, ::testing::Eq(count_), - {.timeout = webrtc::TimeDelta::Millis(10000), - .clock = &clock_}), - webrtc::IsRtcOk()); + EXPECT_THAT( + WaitUntil([&] { return sent_; }, ::testing::Eq(count_), + {.timeout = TimeDelta::Millis(10000), .clock = &clock_}), + IsRtcOk()); RTC_LOG(LS_INFO) << "sent_ == " << sent_; if (damage_) { - clock_.AdvanceTime(webrtc::TimeDelta::Millis(2000)); + clock_.AdvanceTime(TimeDelta::Millis(2000)); EXPECT_EQ(0U, received_.size()); } else if (loss_ == 0) { - EXPECT_THAT(webrtc::WaitUntil([&] { return received_.size(); }, - ::testing::Eq(static_cast(sent_)), - {.clock = &clock_}), - webrtc::IsRtcOk()); + EXPECT_THAT(WaitUntil([&] { return received_.size(); }, + ::testing::Eq(static_cast(sent_)), + {.clock = &clock_}), + IsRtcOk()); } else { RTC_LOG(LS_INFO) << "Sent " << sent_ << " packets; received " << received_.size(); @@ -1021,10 +1010,9 @@ class SSLStreamAdapterTestDTLSBase : public SSLStreamAdapterTestBase { std::set received_; }; -webrtc::StreamResult SSLDummyStream::Write( - webrtc::ArrayView data, - size_t& written, - int& error) { +webrtc::StreamResult SSLDummyStream::Write(ArrayView data, + size_t& written, + int& error) { RTC_LOG(LS_VERBOSE) << "Writing to loopback " << data.size(); if (first_packet_) { @@ -1032,7 +1020,7 @@ webrtc::StreamResult SSLDummyStream::Write( if (test_base_->GetLoseFirstPacket()) { RTC_LOG(LS_INFO) << "Losing initial packet of length " << data.size(); written = data.size(); // Fake successful writing also to writer. - return webrtc::SR_SUCCESS; + return SR_SUCCESS; } } @@ -1053,12 +1041,12 @@ class SSLStreamAdapterTestDTLSCertChain : public SSLStreamAdapterTestDTLSBase { client_ssl_->SetInitialRetransmissionTimeout(/*timeout_ms=*/1000); server_ssl_->SetInitialRetransmissionTimeout(/*timeout_ms=*/1000); - std::unique_ptr client_identity; + std::unique_ptr client_identity; if (!client_cert_pem_.empty() && !client_private_key_pem_.empty()) { - client_identity = webrtc::SSLIdentity::CreateFromPEMStrings( + client_identity = SSLIdentity::CreateFromPEMStrings( client_private_key_pem_, client_cert_pem_); } else { - client_identity = webrtc::SSLIdentity::Create("client", client_key_type_); + client_identity = SSLIdentity::Create("client", client_key_type_); } client_ssl_->SetIdentity(std::move(client_identity)); @@ -1066,11 +1054,11 @@ class SSLStreamAdapterTestDTLSCertChain : public SSLStreamAdapterTestDTLSBase { }; TEST_F(SSLStreamAdapterTestDTLSCertChain, TwoCertHandshake) { - auto server_identity = webrtc::SSLIdentity::CreateFromPEMChainStrings( + auto server_identity = SSLIdentity::CreateFromPEMChainStrings( kRSA_PRIVATE_KEY_PEM, std::string(kCERT_PEM) + kCACert); server_ssl_->SetIdentity(std::move(server_identity)); TestHandshake(); - std::unique_ptr peer_cert_chain = + std::unique_ptr peer_cert_chain = client_ssl_->GetPeerSSLCertChain(); ASSERT_NE(nullptr, peer_cert_chain); EXPECT_EQ(kCERT_PEM, peer_cert_chain->Get(0).ToPEMString()); @@ -1083,10 +1071,10 @@ TEST_F(SSLStreamAdapterTestDTLSCertChain, TwoCertHandshake) { } TEST_F(SSLStreamAdapterTestDTLSCertChain, TwoCertHandshakeWithCopy) { - server_ssl_->SetIdentity(webrtc::SSLIdentity::CreateFromPEMChainStrings( + server_ssl_->SetIdentity(SSLIdentity::CreateFromPEMChainStrings( kRSA_PRIVATE_KEY_PEM, std::string(kCERT_PEM) + kCACert)); TestHandshake(); - std::unique_ptr peer_cert_chain = + std::unique_ptr peer_cert_chain = client_ssl_->GetPeerSSLCertChain(); ASSERT_NE(nullptr, peer_cert_chain); EXPECT_EQ(kCERT_PEM, peer_cert_chain->Get(0).ToPEMString()); @@ -1099,10 +1087,10 @@ TEST_F(SSLStreamAdapterTestDTLSCertChain, TwoCertHandshakeWithCopy) { } TEST_F(SSLStreamAdapterTestDTLSCertChain, ThreeCertHandshake) { - server_ssl_->SetIdentity(webrtc::SSLIdentity::CreateFromPEMChainStrings( + server_ssl_->SetIdentity(SSLIdentity::CreateFromPEMChainStrings( kRSA_PRIVATE_KEY_PEM, std::string(kCERT_PEM) + kIntCert1 + kCACert)); TestHandshake(); - std::unique_ptr peer_cert_chain = + std::unique_ptr peer_cert_chain = client_ssl_->GetPeerSSLCertChain(); ASSERT_NE(nullptr, peer_cert_chain); EXPECT_EQ(kCERT_PEM, peer_cert_chain->Get(0).ToPEMString()); @@ -1117,9 +1105,8 @@ TEST_F(SSLStreamAdapterTestDTLSCertChain, ThreeCertHandshake) { class SSLStreamAdapterTestDTLSHandshake : public SSLStreamAdapterTestDTLSBase, - public WithParamInterface>> { + public WithParamInterface< + tuple>> { public: SSLStreamAdapterTestDTLSHandshake() : SSLStreamAdapterTestDTLSBase(::testing::get<0>(GetParam()), @@ -1135,8 +1122,7 @@ TEST_P(SSLStreamAdapterTestDTLSHandshake, TestDTLSConnect) { // Test getting the used DTLS ciphers. // DTLS 1.2 has different cipher suite than 1.3. TEST_P(SSLStreamAdapterTestDTLSHandshake, TestGetSslCipherSuite) { - SetupProtocolVersions(webrtc::SSL_PROTOCOL_DTLS_12, - webrtc::SSL_PROTOCOL_DTLS_12); + SetupProtocolVersions(SSL_PROTOCOL_DTLS_12, SSL_PROTOCOL_DTLS_12); TestHandshake(); int client_cipher; @@ -1145,7 +1131,7 @@ TEST_P(SSLStreamAdapterTestDTLSHandshake, TestGetSslCipherSuite) { ASSERT_TRUE(GetSslCipherSuite(false, &server_cipher)); ASSERT_EQ(client_cipher, server_cipher); - ASSERT_TRUE(webrtc::SSLStreamAdapter::IsAcceptableCipher( + ASSERT_TRUE(SSLStreamAdapter::IsAcceptableCipher( server_cipher, ::testing::get<1>(GetParam()).type())); } @@ -1156,36 +1142,33 @@ TEST_P(SSLStreamAdapterTestDTLSHandshake, TestGetSslCipherSuite) { INSTANTIATE_TEST_SUITE_P( SSLStreamAdapterTestDTLSHandshakeKeyParameters, SSLStreamAdapterTestDTLSHandshake, - Values(std::make_tuple(webrtc::KeyParams::ECDSA(webrtc::EC_NIST_P256), - webrtc::KeyParams::RSA(webrtc::kRsaDefaultModSize, - webrtc::kRsaDefaultExponent), - std::make_pair(webrtc::DIGEST_SHA_256, - SHA256_DIGEST_LENGTH)), - std::make_tuple( - webrtc::KeyParams::RSA(1152, webrtc::kRsaDefaultExponent), - webrtc::KeyParams::ECDSA(webrtc::EC_NIST_P256), - std::make_pair(webrtc::DIGEST_SHA_256, SHA256_DIGEST_LENGTH)))); + Values( + std::make_tuple(KeyParams::ECDSA(EC_NIST_P256), + KeyParams::RSA(kRsaDefaultModSize, kRsaDefaultExponent), + std::make_pair(DIGEST_SHA_256, SHA256_DIGEST_LENGTH)), + std::make_tuple(KeyParams::RSA(1152, kRsaDefaultExponent), + KeyParams::ECDSA(EC_NIST_P256), + std::make_pair(DIGEST_SHA_256, SHA256_DIGEST_LENGTH)))); INSTANTIATE_TEST_SUITE_P( SSLStreamAdapterTestDTLSHandshakeSignatureAlgorithms, SSLStreamAdapterTestDTLSHandshake, - Combine(Values(webrtc::KeyParams::ECDSA(webrtc::EC_NIST_P256)), - Values(webrtc::KeyParams::ECDSA(webrtc::EC_NIST_P256)), - Values(std::make_pair(webrtc::DIGEST_SHA_1, SHA_DIGEST_LENGTH), - std::make_pair(webrtc::DIGEST_SHA_224, SHA224_DIGEST_LENGTH), - std::make_pair(webrtc::DIGEST_SHA_256, SHA256_DIGEST_LENGTH), - std::make_pair(webrtc::DIGEST_SHA_384, SHA384_DIGEST_LENGTH), - std::make_pair(webrtc::DIGEST_SHA_512, - SHA512_DIGEST_LENGTH)))); + Combine(Values(KeyParams::ECDSA(EC_NIST_P256)), + Values(KeyParams::ECDSA(EC_NIST_P256)), + Values(std::make_pair(DIGEST_SHA_1, SHA_DIGEST_LENGTH), + std::make_pair(DIGEST_SHA_224, SHA224_DIGEST_LENGTH), + std::make_pair(DIGEST_SHA_256, SHA256_DIGEST_LENGTH), + std::make_pair(DIGEST_SHA_384, SHA384_DIGEST_LENGTH), + std::make_pair(DIGEST_SHA_512, SHA512_DIGEST_LENGTH)))); // Basic tests done with ECDSA certificates and SHA-256. class SSLStreamAdapterTestDTLS : public SSLStreamAdapterTestDTLSBase { public: SSLStreamAdapterTestDTLS() : SSLStreamAdapterTestDTLSBase( - webrtc::KeyParams::ECDSA(webrtc::EC_NIST_P256), - webrtc::KeyParams::ECDSA(webrtc::EC_NIST_P256), - std::make_pair(webrtc::DIGEST_SHA_256, SHA256_DIGEST_LENGTH)) {} + KeyParams::ECDSA(EC_NIST_P256), + KeyParams::ECDSA(EC_NIST_P256), + std::make_pair(DIGEST_SHA_256, SHA256_DIGEST_LENGTH)) {} }; #ifdef OPENSSL_IS_BORINGSSL @@ -1220,14 +1203,6 @@ TEST_F(SSLStreamAdapterTestDTLS, TestHandshake(); } -// Test a handshake with small MTU -// Disabled due to https://code.google.com/p/webrtc/issues/detail?id=3910 -TEST_F(SSLStreamAdapterTestDTLS, DISABLED_TestDTLSConnectWithSmallMtu) { - SetMtu(700); - SetHandshakeWait(20000); - TestHandshake(); -} - // Test a handshake with total loss and timing out. // Only works in BoringSSL. #ifdef OPENSSL_IS_BORINGSSL @@ -1277,7 +1252,7 @@ TEST_F(SSLStreamAdapterTestDTLS, TestDTLSDelayedIdentityWithBogusDigest) { // Test DTLS-SRTP with SrtpAes128CmSha1_80 TEST_F(SSLStreamAdapterTestDTLS, TestDTLSSrtpAes128CmSha1_80) { - const std::vector crypto_suites = {webrtc::kSrtpAes128CmSha1_80}; + const std::vector crypto_suites = {kSrtpAes128CmSha1_80}; SetDtlsSrtpCryptoSuites(crypto_suites, true); SetDtlsSrtpCryptoSuites(crypto_suites, false); TestHandshake(); @@ -1288,12 +1263,12 @@ TEST_F(SSLStreamAdapterTestDTLS, TestDTLSSrtpAes128CmSha1_80) { ASSERT_TRUE(GetDtlsSrtpCryptoSuite(false, &server_cipher)); ASSERT_EQ(client_cipher, server_cipher); - ASSERT_EQ(client_cipher, webrtc::kSrtpAes128CmSha1_80); + ASSERT_EQ(client_cipher, kSrtpAes128CmSha1_80); } // Test DTLS-SRTP with SrtpAes128CmSha1_32 TEST_F(SSLStreamAdapterTestDTLS, TestDTLSSrtpAes128CmSha1_32) { - const std::vector crypto_suites = {webrtc::kSrtpAes128CmSha1_32}; + const std::vector crypto_suites = {kSrtpAes128CmSha1_32}; SetDtlsSrtpCryptoSuites(crypto_suites, true); SetDtlsSrtpCryptoSuites(crypto_suites, false); TestHandshake(); @@ -1304,13 +1279,13 @@ TEST_F(SSLStreamAdapterTestDTLS, TestDTLSSrtpAes128CmSha1_32) { ASSERT_TRUE(GetDtlsSrtpCryptoSuite(false, &server_cipher)); ASSERT_EQ(client_cipher, server_cipher); - ASSERT_EQ(client_cipher, webrtc::kSrtpAes128CmSha1_32); + ASSERT_EQ(client_cipher, kSrtpAes128CmSha1_32); } // Test DTLS-SRTP with incompatible cipher suites -- should not converge. TEST_F(SSLStreamAdapterTestDTLS, TestDTLSSrtpIncompatibleCipherSuites) { - SetDtlsSrtpCryptoSuites({webrtc::kSrtpAes128CmSha1_80}, true); - SetDtlsSrtpCryptoSuites({webrtc::kSrtpAes128CmSha1_32}, false); + SetDtlsSrtpCryptoSuites({kSrtpAes128CmSha1_80}, true); + SetDtlsSrtpCryptoSuites({kSrtpAes128CmSha1_32}, false); TestHandshake(); int client_cipher; @@ -1322,8 +1297,8 @@ TEST_F(SSLStreamAdapterTestDTLS, TestDTLSSrtpIncompatibleCipherSuites) { // Test DTLS-SRTP with each side being mixed -- should select the stronger // cipher. TEST_F(SSLStreamAdapterTestDTLS, TestDTLSSrtpMixed) { - const std::vector crypto_suites = {webrtc::kSrtpAes128CmSha1_80, - webrtc::kSrtpAes128CmSha1_32}; + const std::vector crypto_suites = {kSrtpAes128CmSha1_80, + kSrtpAes128CmSha1_32}; SetDtlsSrtpCryptoSuites(crypto_suites, true); SetDtlsSrtpCryptoSuites(crypto_suites, false); TestHandshake(); @@ -1334,12 +1309,12 @@ TEST_F(SSLStreamAdapterTestDTLS, TestDTLSSrtpMixed) { ASSERT_TRUE(GetDtlsSrtpCryptoSuite(false, &server_cipher)); ASSERT_EQ(client_cipher, server_cipher); - ASSERT_EQ(client_cipher, webrtc::kSrtpAes128CmSha1_80); + ASSERT_EQ(client_cipher, kSrtpAes128CmSha1_80); } // Test DTLS-SRTP with SrtpAeadAes128Gcm. TEST_F(SSLStreamAdapterTestDTLS, TestDTLSSrtpAeadAes128Gcm) { - std::vector crypto_suites = {webrtc::kSrtpAeadAes128Gcm}; + std::vector crypto_suites = {kSrtpAeadAes128Gcm}; SetDtlsSrtpCryptoSuites(crypto_suites, true); SetDtlsSrtpCryptoSuites(crypto_suites, false); TestHandshake(); @@ -1350,12 +1325,12 @@ TEST_F(SSLStreamAdapterTestDTLS, TestDTLSSrtpAeadAes128Gcm) { ASSERT_TRUE(GetDtlsSrtpCryptoSuite(false, &server_cipher)); ASSERT_EQ(client_cipher, server_cipher); - ASSERT_EQ(client_cipher, webrtc::kSrtpAeadAes128Gcm); + ASSERT_EQ(client_cipher, kSrtpAeadAes128Gcm); } // Test DTLS-SRTP with all GCM-256 ciphers. TEST_F(SSLStreamAdapterTestDTLS, TestDTLSSrtpGCM256) { - std::vector crypto_suites = {webrtc::kSrtpAeadAes256Gcm}; + std::vector crypto_suites = {kSrtpAeadAes256Gcm}; SetDtlsSrtpCryptoSuites(crypto_suites, true); SetDtlsSrtpCryptoSuites(crypto_suites, false); TestHandshake(); @@ -1366,13 +1341,13 @@ TEST_F(SSLStreamAdapterTestDTLS, TestDTLSSrtpGCM256) { ASSERT_TRUE(GetDtlsSrtpCryptoSuite(false, &server_cipher)); ASSERT_EQ(client_cipher, server_cipher); - ASSERT_EQ(client_cipher, webrtc::kSrtpAeadAes256Gcm); + ASSERT_EQ(client_cipher, kSrtpAeadAes256Gcm); } // Test DTLS-SRTP with incompatbile GCM-128/-256 ciphers -- should not converge. TEST_F(SSLStreamAdapterTestDTLS, TestDTLSSrtpIncompatibleGcmCipherSuites) { - SetDtlsSrtpCryptoSuites({webrtc::kSrtpAeadAes128Gcm}, true); - SetDtlsSrtpCryptoSuites({webrtc::kSrtpAeadAes256Gcm}, false); + SetDtlsSrtpCryptoSuites({kSrtpAeadAes128Gcm}, true); + SetDtlsSrtpCryptoSuites({kSrtpAeadAes256Gcm}, false); TestHandshake(); int client_cipher; @@ -1383,8 +1358,7 @@ TEST_F(SSLStreamAdapterTestDTLS, TestDTLSSrtpIncompatibleGcmCipherSuites) { // Test DTLS-SRTP with both GCM-128/-256 ciphers -- should select GCM-256. TEST_F(SSLStreamAdapterTestDTLS, TestDTLSSrtpGCMMixed) { - std::vector crypto_suites = {webrtc::kSrtpAeadAes256Gcm, - webrtc::kSrtpAeadAes128Gcm}; + std::vector crypto_suites = {kSrtpAeadAes256Gcm, kSrtpAeadAes128Gcm}; SetDtlsSrtpCryptoSuites(crypto_suites, true); SetDtlsSrtpCryptoSuites(crypto_suites, false); TestHandshake(); @@ -1395,7 +1369,7 @@ TEST_F(SSLStreamAdapterTestDTLS, TestDTLSSrtpGCMMixed) { ASSERT_TRUE(GetDtlsSrtpCryptoSuite(false, &server_cipher)); ASSERT_EQ(client_cipher, server_cipher); - ASSERT_EQ(client_cipher, webrtc::kSrtpAeadAes256Gcm); + ASSERT_EQ(client_cipher, kSrtpAeadAes256Gcm); } // Test SRTP cipher suite lengths. @@ -1403,33 +1377,33 @@ TEST_F(SSLStreamAdapterTestDTLS, TestDTLSSrtpKeyAndSaltLengths) { int key_len; int salt_len; - ASSERT_FALSE(webrtc::GetSrtpKeyAndSaltLengths(webrtc::kSrtpInvalidCryptoSuite, - &key_len, &salt_len)); + ASSERT_FALSE( + GetSrtpKeyAndSaltLengths(kSrtpInvalidCryptoSuite, &key_len, &salt_len)); - ASSERT_TRUE(webrtc::GetSrtpKeyAndSaltLengths(webrtc::kSrtpAes128CmSha1_32, - &key_len, &salt_len)); + ASSERT_TRUE( + GetSrtpKeyAndSaltLengths(kSrtpAes128CmSha1_32, &key_len, &salt_len)); ASSERT_EQ(128 / 8, key_len); ASSERT_EQ(112 / 8, salt_len); - ASSERT_TRUE(webrtc::GetSrtpKeyAndSaltLengths(webrtc::kSrtpAes128CmSha1_80, - &key_len, &salt_len)); + ASSERT_TRUE( + GetSrtpKeyAndSaltLengths(kSrtpAes128CmSha1_80, &key_len, &salt_len)); ASSERT_EQ(128 / 8, key_len); ASSERT_EQ(112 / 8, salt_len); - ASSERT_TRUE(webrtc::GetSrtpKeyAndSaltLengths(webrtc::kSrtpAeadAes128Gcm, - &key_len, &salt_len)); + ASSERT_TRUE( + GetSrtpKeyAndSaltLengths(kSrtpAeadAes128Gcm, &key_len, &salt_len)); ASSERT_EQ(128 / 8, key_len); ASSERT_EQ(96 / 8, salt_len); - ASSERT_TRUE(webrtc::GetSrtpKeyAndSaltLengths(webrtc::kSrtpAeadAes256Gcm, - &key_len, &salt_len)); + ASSERT_TRUE( + GetSrtpKeyAndSaltLengths(kSrtpAeadAes256Gcm, &key_len, &salt_len)); ASSERT_EQ(256 / 8, key_len); ASSERT_EQ(96 / 8, salt_len); } // Test the DTLS-SRTP key exporter TEST_F(SSLStreamAdapterTestDTLS, TestDTLSSrtpExporter) { - const std::vector crypto_suites = {webrtc::kSrtpAes128CmSha1_80}; + const std::vector crypto_suites = {kSrtpAes128CmSha1_80}; SetDtlsSrtpCryptoSuites(crypto_suites, true); SetDtlsSrtpCryptoSuites(crypto_suites, false); @@ -1438,10 +1412,10 @@ TEST_F(SSLStreamAdapterTestDTLS, TestDTLSSrtpExporter) { EXPECT_TRUE(GetDtlsSrtpCryptoSuite(/*client=*/false, &selected_crypto_suite)); int key_len; int salt_len; - ASSERT_TRUE(webrtc::GetSrtpKeyAndSaltLengths(selected_crypto_suite, &key_len, - &salt_len)); - webrtc::ZeroOnFreeBuffer client_out(2 * (key_len + salt_len)); - webrtc::ZeroOnFreeBuffer server_out(2 * (key_len + salt_len)); + ASSERT_TRUE( + GetSrtpKeyAndSaltLengths(selected_crypto_suite, &key_len, &salt_len)); + ZeroOnFreeBuffer client_out(2 * (key_len + salt_len)); + ZeroOnFreeBuffer server_out(2 * (key_len + salt_len)); EXPECT_TRUE(client_ssl_->ExportSrtpKeyingMaterial(client_out)); EXPECT_TRUE(server_ssl_->ExportSrtpKeyingMaterial(server_out)); @@ -1486,8 +1460,7 @@ TEST_F(SSLStreamAdapterTestDTLSFromPEMStrings, TestDTLSGetPeerCertificate) { TestHandshake(); // The client should have a peer certificate after the handshake. - std::unique_ptr client_peer_cert = - GetPeerCertificate(true); + std::unique_ptr client_peer_cert = GetPeerCertificate(true); ASSERT_TRUE(client_peer_cert); // It's not kCERT_PEM. @@ -1495,8 +1468,7 @@ TEST_F(SSLStreamAdapterTestDTLSFromPEMStrings, TestDTLSGetPeerCertificate) { ASSERT_NE(kCERT_PEM, client_peer_string); // The server should have a peer certificate after the handshake. - std::unique_ptr server_peer_cert = - GetPeerCertificate(false); + std::unique_ptr server_peer_cert = GetPeerCertificate(false); ASSERT_TRUE(server_peer_cert); // It's kCERT_PEM @@ -1507,23 +1479,22 @@ TEST_F(SSLStreamAdapterTestDTLSFromPEMStrings, TestDTLSGetPeerCertificate) { #pragma clang diagnostic ignored "-Wdeprecated-declarations" TEST_F(SSLStreamAdapterTestDTLSFromPEMStrings, DeprecatedSetPeerCertificateDigest) { - webrtc::SSLPeerCertificateDigestError error; + SSLPeerCertificateDigestError error; // Pass in a wrong length to trigger an error. - bool ret = client_ssl_->SetPeerCertificateDigest(webrtc::DIGEST_SHA_256, {}, + bool ret = client_ssl_->SetPeerCertificateDigest(DIGEST_SHA_256, {}, /*length=*/0, &error); EXPECT_FALSE(ret); - EXPECT_EQ(error, webrtc::SSLPeerCertificateDigestError::INVALID_LENGTH); + EXPECT_EQ(error, SSLPeerCertificateDigestError::INVALID_LENGTH); } #pragma clang diagnostic pop struct SSLStreamAdapterTestDTLSHandshakeVersion : public SSLStreamAdapterTestDTLS, public WithParamInterface> { - webrtc::SSLProtocolVersion GetMin( - const std::vector& array) { - webrtc::SSLProtocolVersion min = array[0]; + /* client*/ SSLProtocolVersion, + /* server*/ SSLProtocolVersion>> { + SSLProtocolVersion GetMin(const std::vector& array) { + SSLProtocolVersion min = array[0]; for (const auto& e : array) { if (static_cast(e) < static_cast(min)) { min = e; @@ -1531,14 +1502,14 @@ struct SSLStreamAdapterTestDTLSHandshakeVersion } return min; } - uint16_t AsDtlsVersionBytes(webrtc::SSLProtocolVersion version) { + uint16_t AsDtlsVersionBytes(SSLProtocolVersion version) { switch (version) { - case webrtc::SSL_PROTOCOL_DTLS_10: - return webrtc::kDtls10VersionBytes; - case webrtc::SSL_PROTOCOL_DTLS_12: - return webrtc::kDtls12VersionBytes; - case webrtc::SSL_PROTOCOL_DTLS_13: - return webrtc::kDtls13VersionBytes; + case SSL_PROTOCOL_DTLS_10: + return kDtls10VersionBytes; + case SSL_PROTOCOL_DTLS_12: + return kDtls12VersionBytes; + case SSL_PROTOCOL_DTLS_13: + return kDtls13VersionBytes; default: break; } @@ -1546,12 +1517,11 @@ struct SSLStreamAdapterTestDTLSHandshakeVersion } }; -INSTANTIATE_TEST_SUITE_P(SSLStreamAdapterTestDTLSHandshakeVersion, - SSLStreamAdapterTestDTLSHandshakeVersion, - Combine(Values(webrtc::SSL_PROTOCOL_DTLS_12, - webrtc::SSL_PROTOCOL_DTLS_13), - Values(webrtc::SSL_PROTOCOL_DTLS_12, - webrtc::SSL_PROTOCOL_DTLS_13))); +INSTANTIATE_TEST_SUITE_P( + SSLStreamAdapterTestDTLSHandshakeVersion, + SSLStreamAdapterTestDTLSHandshakeVersion, + Combine(Values(SSL_PROTOCOL_DTLS_12, SSL_PROTOCOL_DTLS_13), + Values(SSL_PROTOCOL_DTLS_12, SSL_PROTOCOL_DTLS_13))); TEST_P(SSLStreamAdapterTestDTLSHandshakeVersion, TestGetSslVersionBytes) { auto client = ::testing::get<0>(GetParam()); @@ -1564,9 +1534,8 @@ TEST_P(SSLStreamAdapterTestDTLSHandshakeVersion, TestGetSslVersionBytes) { ASSERT_TRUE(GetSslVersionBytes(true, &client_version)); ASSERT_TRUE(GetSslVersionBytes(false, &server_version)); - webrtc::SSLProtocolVersion expect = - GetMin({client, server, - webrtc::SSLStreamAdapter::GetMaxSupportedDTLSProtocolVersion()}); + SSLProtocolVersion expect = GetMin( + {client, server, SSLStreamAdapter::GetMaxSupportedDTLSProtocolVersion()}); auto expect_bytes = AsDtlsVersionBytes(expect); EXPECT_EQ(client_version, expect_bytes); @@ -1585,8 +1554,7 @@ TEST_P(SSLStreamAdapterTestDTLSHandshakeVersion, TestGetSslCipherSuite) { ASSERT_TRUE(GetSslCipherSuite(false, &server_cipher)); ASSERT_EQ(client_cipher, server_cipher); - ASSERT_TRUE(webrtc::SSLStreamAdapter::IsAcceptableCipher(server_cipher, - webrtc::KT_DEFAULT)); + ASSERT_TRUE(SSLStreamAdapter::IsAcceptableCipher(server_cipher, KT_DEFAULT)); } #ifdef OPENSSL_IS_BORINGSSL @@ -1595,15 +1563,15 @@ TEST_P(SSLStreamAdapterTestDTLSHandshakeVersion, TestGetSslGroupIdWithPqc) { auto server_version = ::testing::get<1>(GetParam()); SetupProtocolVersions(client_version, server_version); - webrtc::CryptoOptions::EphemeralKeyExchangeCipherGroups groups; + CryptoOptions::EphemeralKeyExchangeCipherGroups groups; std::vector enabled = groups.GetEnabled(); std::vector groups_with_pqc; - if (std::find(enabled.begin(), enabled.end(), - webrtc::CryptoOptions::EphemeralKeyExchangeCipherGroups:: - kX25519_MLKEM768) == enabled.end()) { + if (std::find( + enabled.begin(), enabled.end(), + CryptoOptions::EphemeralKeyExchangeCipherGroups::kX25519_MLKEM768) == + enabled.end()) { groups_with_pqc.push_back( - webrtc::CryptoOptions::EphemeralKeyExchangeCipherGroups:: - kX25519_MLKEM768); + CryptoOptions::EphemeralKeyExchangeCipherGroups::kX25519_MLKEM768); } for (auto val : enabled) { groups_with_pqc.push_back(val); @@ -1615,19 +1583,22 @@ TEST_P(SSLStreamAdapterTestDTLSHandshakeVersion, TestGetSslGroupIdWithPqc) { EXPECT_EQ(server_ssl_->GetSslGroupId(), 0); TestHandshake(); - if (client_version == webrtc::SSL_PROTOCOL_DTLS_13 && - server_version == webrtc::SSL_PROTOCOL_DTLS_13) { - EXPECT_EQ(client_ssl_->GetSslGroupId(), - webrtc::CryptoOptions::EphemeralKeyExchangeCipherGroups:: - kX25519_MLKEM768); - EXPECT_EQ(server_ssl_->GetSslGroupId(), - webrtc::CryptoOptions::EphemeralKeyExchangeCipherGroups:: - kX25519_MLKEM768); + if (client_version == SSL_PROTOCOL_DTLS_13 && + server_version == SSL_PROTOCOL_DTLS_13) { + EXPECT_EQ( + client_ssl_->GetSslGroupId(), + CryptoOptions::EphemeralKeyExchangeCipherGroups::kX25519_MLKEM768); + EXPECT_EQ( + server_ssl_->GetSslGroupId(), + CryptoOptions::EphemeralKeyExchangeCipherGroups::kX25519_MLKEM768); } else { EXPECT_EQ(client_ssl_->GetSslGroupId(), - webrtc::CryptoOptions::EphemeralKeyExchangeCipherGroups::kX25519); + CryptoOptions::EphemeralKeyExchangeCipherGroups::kX25519); EXPECT_EQ(server_ssl_->GetSslGroupId(), - webrtc::CryptoOptions::EphemeralKeyExchangeCipherGroups::kX25519); + CryptoOptions::EphemeralKeyExchangeCipherGroups::kX25519); } } #endif + +} // namespace +} // namespace webrtc diff --git a/rtc_base/stream.h b/rtc_base/stream.h index 9bee2be056..938f70c22f 100644 --- a/rtc_base/stream.h +++ b/rtc_base/stream.h @@ -140,7 +140,7 @@ class RTC_EXPORT StreamInterface { } RTC_NO_UNIQUE_ADDRESS SequenceChecker callback_sequence_{ - webrtc::SequenceChecker::kDetached}; + SequenceChecker::kDetached}; private: absl::AnyInvocable callback_ diff --git a/rtc_base/string_encode.cc b/rtc_base/string_encode.cc index 452b7d6255..6b0b1e0049 100644 --- a/rtc_base/string_encode.cc +++ b/rtc_base/string_encode.cc @@ -11,10 +11,11 @@ #include "rtc_base/string_encode.h" #include +#include +#include #include "absl/strings/string_view.h" #include "api/array_view.h" -#include "rtc_base/arraysize.h" #include "rtc_base/checks.h" namespace webrtc { diff --git a/rtc_base/string_encode.h b/rtc_base/string_encode.h index 4d6fc0c032..4d840c6821 100644 --- a/rtc_base/string_encode.h +++ b/rtc_base/string_encode.h @@ -18,13 +18,11 @@ #include #include -#include "absl/base/macros.h" -#include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "api/array_view.h" #include "rtc_base/checks.h" #include "rtc_base/string_to_number.h" -#include "rtc_base/strings/string_format.h" +#include "rtc_base/strings/string_format.h" // IWYU pragma: keep namespace webrtc { @@ -75,7 +73,7 @@ template ::type = 0> static bool FromString(absl::string_view s, T* t) { RTC_DCHECK(t); - std::optional result = webrtc::StringToNumber(s); + std::optional result = StringToNumber(s); if (result) *t = *result; diff --git a/rtc_base/string_encode_unittest.cc b/rtc_base/string_encode_unittest.cc index d950f5774a..103d33c427 100644 --- a/rtc_base/string_encode_unittest.cc +++ b/rtc_base/string_encode_unittest.cc @@ -12,6 +12,10 @@ #include +#include +#include + +#include "absl/strings/string_view.h" #include "api/array_view.h" #include "test/gtest.h" diff --git a/rtc_base/string_to_number.cc b/rtc_base/string_to_number.cc index e88c97a739..837a6bbca3 100644 --- a/rtc_base/string_to_number.cc +++ b/rtc_base/string_to_number.cc @@ -14,8 +14,10 @@ #include #include +#include +#include -#include "rtc_base/checks.h" +#include "absl/strings/string_view.h" namespace webrtc { namespace string_to_number_internal { diff --git a/rtc_base/string_to_number.h b/rtc_base/string_to_number.h index a66473b862..cf22827b50 100644 --- a/rtc_base/string_to_number.h +++ b/rtc_base/string_to_number.h @@ -13,7 +13,6 @@ #include #include -#include #include #include "absl/strings/string_view.h" diff --git a/rtc_base/string_utils.h b/rtc_base/string_utils.h index ca2607b186..3c6d19073d 100644 --- a/rtc_base/string_utils.h +++ b/rtc_base/string_utils.h @@ -37,7 +37,7 @@ const size_t SIZE_UNKNOWN = static_cast(-1); // std::map that support heterogenous lookup. // // Example usage: -// std::map my_map; +// std::map my_map; struct AbslStringViewCmp { using is_transparent = void; bool operator()(absl::string_view a, absl::string_view b) const { diff --git a/rtc_base/strings/json.cc b/rtc_base/strings/json.cc index a7cbfeb3a3..c488304969 100644 --- a/rtc_base/strings/json.cc +++ b/rtc_base/strings/json.cc @@ -14,7 +14,12 @@ #include #include +#include +#include + +#include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" +#include "json/writer.h" #include "rtc_base/string_encode.h" namespace webrtc { diff --git a/rtc_base/strings/json_unittest.cc b/rtc_base/strings/json_unittest.cc index b0865492d8..c0579f1029 100644 --- a/rtc_base/strings/json_unittest.cc +++ b/rtc_base/strings/json_unittest.cc @@ -10,6 +10,7 @@ #include "rtc_base/strings/json.h" +#include #include #include "test/gtest.h" diff --git a/rtc_base/strings/str_join_unittest.cc b/rtc_base/strings/str_join_unittest.cc index 305bf08c6a..ad88551884 100644 --- a/rtc_base/strings/str_join_unittest.cc +++ b/rtc_base/strings/str_join_unittest.cc @@ -9,10 +9,12 @@ */ #include "rtc_base/strings/str_join.h" +#include #include #include #include +#include "rtc_base/strings/string_builder.h" #include "test/gtest.h" namespace webrtc { diff --git a/rtc_base/strings/string_builder.cc b/rtc_base/strings/string_builder.cc index fb568fbd8c..e411150fa9 100644 --- a/rtc_base/strings/string_builder.cc +++ b/rtc_base/strings/string_builder.cc @@ -16,6 +16,7 @@ #include #include "absl/strings/string_view.h" +#include "api/array_view.h" #include "rtc_base/checks.h" #include "rtc_base/numerics/safe_minmax.h" diff --git a/rtc_base/strings/string_builder.h b/rtc_base/strings/string_builder.h index 55d0b061ef..072fd1e6eb 100644 --- a/rtc_base/strings/string_builder.h +++ b/rtc_base/strings/string_builder.h @@ -18,7 +18,6 @@ #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "api/array_view.h" -#include "rtc_base/string_encode.h" namespace webrtc { diff --git a/rtc_base/strings/string_builder_unittest.cc b/rtc_base/strings/string_builder_unittest.cc index d04e0eb4d9..18d502047c 100644 --- a/rtc_base/strings/string_builder_unittest.cc +++ b/rtc_base/strings/string_builder_unittest.cc @@ -12,6 +12,8 @@ #include +#include + #include "rtc_base/checks.h" #include "test/gmock.h" #include "test/gtest.h" diff --git a/rtc_base/strings/string_format.cc b/rtc_base/strings/string_format.cc index 35661531ec..49ec29edf5 100644 --- a/rtc_base/strings/string_format.cc +++ b/rtc_base/strings/string_format.cc @@ -11,6 +11,8 @@ #include "rtc_base/strings/string_format.h" #include +#include +#include #include "rtc_base/checks.h" diff --git a/rtc_base/strings/string_format_unittest.cc b/rtc_base/strings/string_format_unittest.cc index 73a04fa183..33be2ac66c 100644 --- a/rtc_base/strings/string_format_unittest.cc +++ b/rtc_base/strings/string_format_unittest.cc @@ -10,10 +10,11 @@ #include "rtc_base/strings/string_format.h" +#include +#include #include #include "absl/strings/string_view.h" -#include "rtc_base/checks.h" #include "rtc_base/string_encode.h" #include "test/gtest.h" diff --git a/rtc_base/strong_alias.h b/rtc_base/strong_alias.h index 3f45113f63..548253de6c 100644 --- a/rtc_base/strong_alias.h +++ b/rtc_base/strong_alias.h @@ -11,7 +11,6 @@ #ifndef RTC_BASE_STRONG_ALIAS_H_ #define RTC_BASE_STRONG_ALIAS_H_ -#include #include namespace webrtc { diff --git a/rtc_base/strong_alias_unittest.cc b/rtc_base/strong_alias_unittest.cc index c663cad837..91d454ce57 100644 --- a/rtc_base/strong_alias_unittest.cc +++ b/rtc_base/strong_alias_unittest.cc @@ -18,8 +18,7 @@ #include #include "rtc_base/containers/flat_map.h" -#include "rtc_base/gunit.h" -#include "test/gmock.h" +#include "test/gtest.h" // This is a copy of // https://source.chromium.org/chromium/chromium/src/+/main:base/types/strong_alias_unittest.cc diff --git a/rtc_base/swap_queue_unittest.cc b/rtc_base/swap_queue_unittest.cc index 764a25edec..e8ce02aab0 100644 --- a/rtc_base/swap_queue_unittest.cc +++ b/rtc_base/swap_queue_unittest.cc @@ -10,9 +10,11 @@ #include "rtc_base/swap_queue.h" +#include #include #include +#include "rtc_base/checks.h" #include "test/gtest.h" namespace webrtc { diff --git a/rtc_base/synchronization/BUILD.gn b/rtc_base/synchronization/BUILD.gn index 6b05f5ce1d..934f71d31d 100644 --- a/rtc_base/synchronization/BUILD.gn +++ b/rtc_base/synchronization/BUILD.gn @@ -87,7 +87,6 @@ if (rtc_include_tests && rtc_enable_google_benchmarks) { ":yield", ":yield_policy", "..:checks", - "..:macromagic", "..:platform_thread", "..:rtc_event", "..:threading", diff --git a/rtc_base/system_time.cc b/rtc_base/system_time.cc index c6a9b7b766..83a08f64f4 100644 --- a/rtc_base/system_time.cc +++ b/rtc_base/system_time.cc @@ -56,7 +56,7 @@ int64_t SystemTimeNanos() { RTC_DCHECK_NE(b, 0); RTC_DCHECK_LE(a, std::numeric_limits::max() / b) << "The multiplication " << a << " * " << b << " overflows"; - return webrtc::dchecked_cast(a * b); + return dchecked_cast(a * b); }; ticks = mul(mach_absolute_time(), timebase.numer) / timebase.denom; #elif defined(WEBRTC_POSIX) @@ -90,7 +90,7 @@ int64_t SystemTimeNanos() { ticks = now + (num_wrap_timegettime << 32); // TODO(deadbeef): Calculate with nanosecond precision. Otherwise, we're // just wasting a multiply and divide when doing Time() on Windows. - ticks = ticks * webrtc::kNumNanosecsPerMillisec; + ticks = ticks * kNumNanosecsPerMillisec; #pragma clang diagnostic pop #else #error Unsupported platform. diff --git a/rtc_base/task_queue_for_test.cc b/rtc_base/task_queue_for_test.cc index e8993edcd1..b38456b91c 100644 --- a/rtc_base/task_queue_for_test.cc +++ b/rtc_base/task_queue_for_test.cc @@ -13,8 +13,10 @@ #include #include +#include "absl/strings/string_view.h" #include "api/task_queue/default_task_queue_factory.h" #include "api/task_queue/task_queue_base.h" +#include "api/task_queue/task_queue_factory.h" namespace webrtc { diff --git a/rtc_base/task_queue_for_test.h b/rtc_base/task_queue_for_test.h index 2f1ca08da4..d4879e0ba6 100644 --- a/rtc_base/task_queue_for_test.h +++ b/rtc_base/task_queue_for_test.h @@ -11,13 +11,17 @@ #ifndef RTC_BASE_TASK_QUEUE_FOR_TEST_H_ #define RTC_BASE_TASK_QUEUE_FOR_TEST_H_ +#include #include #include "absl/cleanup/cleanup.h" +#include "absl/functional/any_invocable.h" #include "absl/strings/string_view.h" #include "api/function_view.h" +#include "api/location.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/checks.h" #include "rtc_base/event.h" @@ -52,21 +56,19 @@ class TaskQueueForTest { // Returns non-owning pointer to the task queue implementation. TaskQueueBase* Get() { return impl_.get(); } - void PostTask( - absl::AnyInvocable task, - const webrtc::Location& location = webrtc::Location::Current()) { + void PostTask(absl::AnyInvocable task, + const Location& location = Location::Current()) { impl_->PostTask(std::move(task), location); } - void PostDelayedTask( - absl::AnyInvocable task, - webrtc::TimeDelta delay, - const webrtc::Location& location = webrtc::Location::Current()) { + void PostDelayedTask(absl::AnyInvocable task, + TimeDelta delay, + const Location& location = Location::Current()) { impl_->PostDelayedTask(std::move(task), delay, location); } void PostDelayedHighPrecisionTask( absl::AnyInvocable task, - webrtc::TimeDelta delay, - const webrtc::Location& location = webrtc::Location::Current()) { + TimeDelta delay, + const Location& location = Location::Current()) { impl_->PostDelayedHighPrecisionTask(std::move(task), delay, location); } diff --git a/rtc_base/task_queue_stdlib.cc b/rtc_base/task_queue_stdlib.cc index 0895eb18cc..7fdb1fa1c8 100644 --- a/rtc_base/task_queue_stdlib.cc +++ b/rtc_base/task_queue_stdlib.cc @@ -10,9 +10,7 @@ #include "rtc_base/task_queue_stdlib.h" -#include - -#include +#include #include #include #include @@ -21,11 +19,12 @@ #include "absl/functional/any_invocable.h" #include "absl/strings/string_view.h" +#include "api/location.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/checks.h" #include "rtc_base/event.h" -#include "rtc_base/logging.h" #include "rtc_base/numerics/divide_round.h" #include "rtc_base/platform_thread.h" #include "rtc_base/synchronization/mutex.h" diff --git a/rtc_base/task_queue_stdlib_unittest.cc b/rtc_base/task_queue_stdlib_unittest.cc index 3218a08cb7..dc675910ad 100644 --- a/rtc_base/task_queue_stdlib_unittest.cc +++ b/rtc_base/task_queue_stdlib_unittest.cc @@ -13,6 +13,8 @@ #include #include +#include "absl/strings/string_view.h" +#include "api/field_trials_view.h" #include "api/task_queue/task_queue_factory.h" #include "api/task_queue/task_queue_test.h" #include "api/units/time_delta.h" diff --git a/rtc_base/task_queue_win.cc b/rtc_base/task_queue_win.cc index 56d079b186..490ea8315d 100644 --- a/rtc_base/task_queue_win.cc +++ b/rtc_base/task_queue_win.cc @@ -35,7 +35,6 @@ #include "api/task_queue/task_queue_base.h" #include "api/units/time_delta.h" #include "api/units/timestamp.h" -#include "rtc_base/arraysize.h" #include "rtc_base/checks.h" #include "rtc_base/event.h" #include "rtc_base/logging.h" @@ -51,7 +50,7 @@ namespace { void CALLBACK InitializeQueueThread(ULONG_PTR param) { MSG msg; ::PeekMessage(&msg, nullptr, WM_USER, WM_USER, PM_NOREMOVE); - webrtc::Event* data = reinterpret_cast(param); + Event* data = reinterpret_cast(param); data->Set(); } @@ -198,9 +197,9 @@ TaskQueueWin::TaskQueueWin(absl::string_view queue_name, ThreadPriority priority) : in_queue_(::CreateEvent(nullptr, true, false, nullptr)) { RTC_DCHECK(in_queue_); - thread_ = webrtc::PlatformThread::SpawnJoinable( - [this] { RunThreadMain(); }, queue_name, - webrtc::ThreadAttributes().SetPriority(priority)); + thread_ = + PlatformThread::SpawnJoinable([this] { RunThreadMain(); }, queue_name, + ThreadAttributes().SetPriority(priority)); Event event(false, false); RTC_CHECK(thread_.QueueAPC(&InitializeQueueThread, @@ -270,7 +269,7 @@ void TaskQueueWin::RunThreadMain() { // (e.g. required for InitializeQueueThread and stopping the thread in // PlatformThread). DWORD result = ::MsgWaitForMultipleObjectsEx( - arraysize(handles), handles, INFINITE, QS_ALLEVENTS, MWMO_ALERTABLE); + std::size(handles), handles, INFINITE, QS_ALLEVENTS, MWMO_ALERTABLE); RTC_CHECK_NE(WAIT_FAILED, result); if (result == (WAIT_OBJECT_0 + 2)) { // There are messages in the message queue that need to be handled. diff --git a/rtc_base/task_utils/BUILD.gn b/rtc_base/task_utils/BUILD.gn index ee6abc3758..6a5db79a2d 100644 --- a/rtc_base/task_utils/BUILD.gn +++ b/rtc_base/task_utils/BUILD.gn @@ -14,8 +14,12 @@ rtc_library("repeating_task") { "repeating_task.h", ] deps = [ + "..:checks", "..:logging", + "..:macromagic", "..:timeutils", + "../../api:location", + "../../api:scoped_refptr", "../../api:sequence_checker", "../../api/task_queue", "../../api/task_queue:pending_task_safety_flag", @@ -34,6 +38,7 @@ if (rtc_include_tests) { ":repeating_task", "..:rtc_event", "..:task_queue_for_test", + "../../api:location", "../../api/task_queue", "../../api/task_queue/test:mock_task_queue_base", "../../api/units:time_delta", diff --git a/rtc_base/task_utils/repeating_task.cc b/rtc_base/task_utils/repeating_task.cc index 284bfa2474..d3e82c1bab 100644 --- a/rtc_base/task_utils/repeating_task.cc +++ b/rtc_base/task_utils/repeating_task.cc @@ -10,9 +10,20 @@ #include "rtc_base/task_utils/repeating_task.h" +#include +#include + #include "absl/functional/any_invocable.h" +#include "api/location.h" +#include "api/scoped_refptr.h" +#include "api/sequence_checker.h" #include "api/task_queue/pending_task_safety_flag.h" -#include "rtc_base/logging.h" +#include "api/task_queue/task_queue_base.h" +#include "api/units/time_delta.h" +#include "api/units/timestamp.h" +#include "rtc_base/checks.h" +#include "rtc_base/thread_annotations.h" +#include "system_wrappers/include/clock.h" namespace webrtc { namespace { diff --git a/rtc_base/task_utils/repeating_task.h b/rtc_base/task_utils/repeating_task.h index 5779fc1a8b..3f738fcebc 100644 --- a/rtc_base/task_utils/repeating_task.h +++ b/rtc_base/task_utils/repeating_task.h @@ -11,11 +11,11 @@ #ifndef RTC_BASE_TASK_UTILS_REPEATING_TASK_H_ #define RTC_BASE_TASK_UTILS_REPEATING_TASK_H_ -#include -#include #include #include "absl/functional/any_invocable.h" +#include "api/location.h" +#include "api/scoped_refptr.h" #include "api/task_queue/pending_task_safety_flag.h" #include "api/task_queue/task_queue_base.h" #include "api/units/time_delta.h" diff --git a/rtc_base/task_utils/repeating_task_unittest.cc b/rtc_base/task_utils/repeating_task_unittest.cc index f85078e7d3..adf91aee14 100644 --- a/rtc_base/task_utils/repeating_task_unittest.cc +++ b/rtc_base/task_utils/repeating_task_unittest.cc @@ -13,8 +13,10 @@ #include #include #include +#include #include "absl/functional/any_invocable.h" +#include "api/location.h" #include "api/task_queue/task_queue_base.h" #include "api/task_queue/test/mock_task_queue_base.h" #include "api/units/time_delta.h" diff --git a/rtc_base/test_certificate_verifier.h b/rtc_base/test_certificate_verifier.h index 1252a3c0ee..2fcbc921bd 100644 --- a/rtc_base/test_certificate_verifier.h +++ b/rtc_base/test_certificate_verifier.h @@ -11,6 +11,8 @@ #ifndef RTC_BASE_TEST_CERTIFICATE_VERIFIER_H_ #define RTC_BASE_TEST_CERTIFICATE_VERIFIER_H_ +#include + #include "rtc_base/ssl_certificate.h" namespace webrtc { diff --git a/rtc_base/test_client.h b/rtc_base/test_client.h index 1be26c8fff..ab3fbd0cb9 100644 --- a/rtc_base/test_client.h +++ b/rtc_base/test_client.h @@ -11,15 +11,20 @@ #ifndef RTC_BASE_TEST_CLIENT_H_ #define RTC_BASE_TEST_CLIENT_H_ +#include #include +#include #include #include "api/units/timestamp.h" -#include "rtc_base/async_udp_socket.h" +#include "rtc_base/async_packet_socket.h" #include "rtc_base/buffer.h" #include "rtc_base/fake_clock.h" #include "rtc_base/network/received_packet.h" +#include "rtc_base/socket.h" +#include "rtc_base/socket_address.h" #include "rtc_base/synchronization/mutex.h" +#include "rtc_base/third_party/sigslot/sigslot.h" namespace webrtc { diff --git a/rtc_base/thread.cc b/rtc_base/thread.cc index 6599615233..815ac34694 100644 --- a/rtc_base/thread.cc +++ b/rtc_base/thread.cc @@ -906,7 +906,7 @@ AutoThread::AutoThread() : Thread(CreateDefaultSocketServer(), /*do_init=*/false) { if (!ThreadManager::Instance()->CurrentThread()) { // DoInit registers with ThreadManager. Do that only if we intend to - // be webrtc::Thread::Current(), otherwise ProcessAllMessageQueuesInternal + // be Thread::Current(), otherwise ProcessAllMessageQueuesInternal // will post a message to a queue that no running thread is serving. DoInit(); ThreadManager::Instance()->SetCurrentThread(this); diff --git a/rtc_base/thread.h b/rtc_base/thread.h index 69c74febaf..ef970b40e5 100644 --- a/rtc_base/thread.h +++ b/rtc_base/thread.h @@ -366,7 +366,7 @@ class RTC_LOCKABLE RTC_EXPORT Thread : public TaskQueueBase { // These functions are public to avoid injecting test hooks. Don't call them // outside of tests. // This method should be called when thread is created using non standard - // method, like derived implementation of webrtc::Thread and it can not be + // method, like derived implementation of Thread and it can not be // started by calling Start(). This will set started flag to true and // owned to false. This must be called from the current thread. bool WrapCurrent(); diff --git a/rtc_base/thread_unittest.cc b/rtc_base/thread_unittest.cc index 24e7106cf5..c01e42a090 100644 --- a/rtc_base/thread_unittest.cc +++ b/rtc_base/thread_unittest.cc @@ -490,9 +490,8 @@ TEST(ThreadTest, ThreeThreadsBlockingCall) { IsRtcOk()); } -static void DelayedPostsWithIdenticalTimesAreProcessedInFifoOrder( - FakeClock& clock, - Thread& q) { +void DelayedPostsWithIdenticalTimesAreProcessedInFifoOrder(FakeClock& clock, + Thread& q) { std::vector run_order; Event done; diff --git a/rtc_base/time_utils.h b/rtc_base/time_utils.h index 30cb8b8656..d4dbb2b57f 100644 --- a/rtc_base/time_utils.h +++ b/rtc_base/time_utils.h @@ -127,7 +127,7 @@ int64_t TmToSeconds(const tm& tm); // Note that this function obeys the system's idea about what the time // is. It is not guaranteed to be monotonic; it will jump in case the // system time is changed, e.g., by some other process calling -// settimeofday. Always use webrtc::TimeMicros(), not this function, for +// settimeofday. Always use TimeMicros(), not this function, for // measuring time intervals and timeouts. RTC_EXPORT int64_t TimeUTCMicros(); diff --git a/rtc_base/timestamp_aligner.cc b/rtc_base/timestamp_aligner.cc index d3ce44a323..5239c67313 100644 --- a/rtc_base/timestamp_aligner.cc +++ b/rtc_base/timestamp_aligner.cc @@ -10,12 +10,12 @@ #include "rtc_base/timestamp_aligner.h" +#include #include #include #include "rtc_base/checks.h" #include "rtc_base/logging.h" -#include "rtc_base/time_utils.h" namespace webrtc { diff --git a/rtc_base/timestamp_aligner.h b/rtc_base/timestamp_aligner.h index d060a354e9..a3eda6c964 100644 --- a/rtc_base/timestamp_aligner.h +++ b/rtc_base/timestamp_aligner.h @@ -19,13 +19,13 @@ namespace webrtc { // The TimestampAligner class helps translating timestamps of a capture system -// into the same timescale as is used by webrtc::TimeMicros(). Some capture +// into the same timescale as is used by TimeMicros(). Some capture // systems provide timestamps, which comes from the capturing hardware (camera // or sound card) or stamped close to the capturing hardware. Such timestamps // are more accurate (less jittery) than reading the system clock, but may have // a different epoch and unknown clock drift. Frame timestamps in webrtc should -// use webrtc::TimeMicros (system monotonic time), and this class provides a -// filter which lets us use the webrtc::TimeMicros timescale, and at the same +// use TimeMicros (system monotonic time), and this class provides a +// filter which lets us use the TimeMicros timescale, and at the same // time take advantage of higher accuracy of the capturer's clock. // This class is not thread safe, so all calls to it must be synchronized @@ -46,9 +46,9 @@ class RTC_EXPORT TimestampAligner { static constexpr int64_t kMinFrameIntervalUs = kNumMicrosecsPerMillisec; // Translates timestamps of a capture system to the same timescale as is used - // by webrtc::TimeMicros(). `capturer_time_us` is assumed to be accurate, but + // by TimeMicros(). `capturer_time_us` is assumed to be accurate, but // with an unknown epoch and clock drift. `system_time_us` is - // time according to webrtc::TimeMicros(), preferably read as soon as + // time according to TimeMicros(), preferably read as soon as // possible when the frame is captured. It may have poor accuracy // due to poor resolution or scheduling delays. Returns the // translated timestamp. diff --git a/rtc_base/timestamp_aligner_unittest.cc b/rtc_base/timestamp_aligner_unittest.cc index b280e36911..2582c78812 100644 --- a/rtc_base/timestamp_aligner_unittest.cc +++ b/rtc_base/timestamp_aligner_unittest.cc @@ -13,6 +13,7 @@ #include #include +#include #include #include "rtc_base/random.h" diff --git a/rtc_base/trace_event.h b/rtc_base/trace_event.h index 3329abd66c..9ec70884db 100644 --- a/rtc_base/trace_event.h +++ b/rtc_base/trace_event.h @@ -11,6 +11,7 @@ #ifndef RTC_BASE_TRACE_EVENT_H_ #define RTC_BASE_TRACE_EVENT_H_ +#include #if defined(RTC_DISABLE_TRACE_EVENTS) #define RTC_TRACE_EVENTS_ENABLED 0 #else diff --git a/rtc_base/type_traits.h b/rtc_base/type_traits.h index 9f17acb522..4247d7c9f2 100644 --- a/rtc_base/type_traits.h +++ b/rtc_base/type_traits.h @@ -12,7 +12,6 @@ #define RTC_BASE_TYPE_TRAITS_H_ #include -#include #include namespace webrtc { diff --git a/rtc_base/unique_id_generator.cc b/rtc_base/unique_id_generator.cc index 6bd47d32ed..d09f35bedf 100644 --- a/rtc_base/unique_id_generator.cc +++ b/rtc_base/unique_id_generator.cc @@ -10,13 +10,18 @@ #include "rtc_base/unique_id_generator.h" +#include #include -#include +#include +#include +#include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" +#include "api/array_view.h" +#include "rtc_base/checks.h" #include "rtc_base/crypto_random.h" -#include "rtc_base/string_encode.h" #include "rtc_base/string_to_number.h" +#include "rtc_base/synchronization/mutex.h" namespace webrtc { diff --git a/rtc_base/unique_id_generator.h b/rtc_base/unique_id_generator.h index 5fe3366edd..e08742b9b7 100644 --- a/rtc_base/unique_id_generator.h +++ b/rtc_base/unique_id_generator.h @@ -11,15 +11,19 @@ #ifndef RTC_BASE_UNIQUE_ID_GENERATOR_H_ #define RTC_BASE_UNIQUE_ID_GENERATOR_H_ +#include #include #include #include +#include #include "absl/strings/string_view.h" #include "api/array_view.h" #include "api/sequence_checker.h" +#include "rtc_base/checks.h" #include "rtc_base/synchronization/mutex.h" #include "rtc_base/system/no_unique_address.h" +#include "rtc_base/thread_annotations.h" namespace webrtc { @@ -54,7 +58,7 @@ class UniqueNumberGenerator { private: RTC_NO_UNIQUE_ADDRESS SequenceChecker sequence_checker_{ - webrtc::SequenceChecker::kDetached}; + SequenceChecker::kDetached}; static_assert(std::is_integral::value, "Must be integral type."); TIntegral counter_ RTC_GUARDED_BY(sequence_checker_); std::set known_ids_ RTC_GUARDED_BY(sequence_checker_); diff --git a/rtc_base/unique_id_generator_unittest.cc b/rtc_base/unique_id_generator_unittest.cc index 661ba58bdf..b640fd913c 100644 --- a/rtc_base/unique_id_generator_unittest.cc +++ b/rtc_base/unique_id_generator_unittest.cc @@ -10,17 +10,20 @@ #include "rtc_base/unique_id_generator.h" -#include +#include +#include +#include #include #include "absl/algorithm/container.h" #include "absl/functional/any_invocable.h" -#include "api/array_view.h" +#include "api/location.h" #include "api/task_queue/task_queue_base.h" #include "api/units/time_delta.h" +#include "rtc_base/checks.h" #include "rtc_base/crypto_random.h" -#include "rtc_base/gunit.h" #include "test/gmock.h" +#include "test/gtest.h" using ::testing::IsEmpty; using ::testing::Test; diff --git a/rtc_base/units/BUILD.gn b/rtc_base/units/BUILD.gn index bbb87a009a..98ff7c9265 100644 --- a/rtc_base/units/BUILD.gn +++ b/rtc_base/units/BUILD.gn @@ -28,6 +28,7 @@ if (rtc_include_tests) { sources = [ "unit_base_unittest.cc" ] deps = [ ":unit_base", + "..:checks", "../../test:test_support", ] } diff --git a/rtc_base/units/unit_base.h b/rtc_base/units/unit_base.h index 2820c13b2d..b9a8df1d33 100644 --- a/rtc_base/units/unit_base.h +++ b/rtc_base/units/unit_base.h @@ -14,6 +14,7 @@ #include #include +#include #include #include diff --git a/rtc_base/units/unit_base_unittest.cc b/rtc_base/units/unit_base_unittest.cc index 6003f4b754..cfb9667307 100644 --- a/rtc_base/units/unit_base_unittest.cc +++ b/rtc_base/units/unit_base_unittest.cc @@ -10,6 +10,11 @@ #include "rtc_base/units/unit_base.h" +#include +#include +#include + +#include "rtc_base/checks.h" #include "test/gtest.h" namespace webrtc { diff --git a/rtc_base/untyped_function.h b/rtc_base/untyped_function.h index b7e1de1551..229e17d3c2 100644 --- a/rtc_base/untyped_function.h +++ b/rtc_base/untyped_function.h @@ -12,8 +12,8 @@ #define RTC_BASE_UNTYPED_FUNCTION_H_ #include +#include #include -#include #include #include diff --git a/rtc_base/untyped_function_unittest.cc b/rtc_base/untyped_function_unittest.cc index 8ea26e7a43..6ff64f4cd1 100644 --- a/rtc_base/untyped_function_unittest.cc +++ b/rtc_base/untyped_function_unittest.cc @@ -11,6 +11,7 @@ #include "rtc_base/untyped_function.h" #include +#include #include #include "test/gmock.h" diff --git a/rtc_base/virtual_socket_unittest.cc b/rtc_base/virtual_socket_unittest.cc index c6237303a9..22988a540f 100644 --- a/rtc_base/virtual_socket_unittest.cc +++ b/rtc_base/virtual_socket_unittest.cc @@ -19,7 +19,6 @@ #include "absl/memory/memory.h" #include "api/units/time_delta.h" -#include "rtc_base/arraysize.h" #include "rtc_base/async_packet_socket.h" #include "rtc_base/async_udp_socket.h" #include "rtc_base/fake_clock.h" @@ -1084,17 +1083,16 @@ TEST_F(VirtualSocketServerTest, CreatesStandardDistribution) { const double kTestDev[] = {0.25, 0.1, 0.01}; // TODO(deadbeef): The current code only works for 1000 data points or more. const uint32_t kTestSamples[] = {/*10, 100,*/ 1000}; - for (size_t midx = 0; midx < arraysize(kTestMean); ++midx) { - for (size_t didx = 0; didx < arraysize(kTestDev); ++didx) { - for (size_t sidx = 0; sidx < arraysize(kTestSamples); ++sidx) { - ASSERT_LT(0u, kTestSamples[sidx]); - const uint32_t kStdDev = - static_cast(kTestDev[didx] * kTestMean[midx]); + for (uint32_t test_mean : kTestMean) { + for (double test_dev : kTestDev) { + for (uint32_t test_sample : kTestSamples) { + ASSERT_LT(0u, test_sample); + const uint32_t kStdDev = static_cast(test_dev * test_mean); std::unique_ptr f = - VirtualSocketServer::CreateDistribution(kTestMean[midx], kStdDev, - kTestSamples[sidx]); + VirtualSocketServer::CreateDistribution(test_mean, kStdDev, + test_sample); ASSERT_TRUE(nullptr != f.get()); - ASSERT_EQ(kTestSamples[sidx], f->size()); + ASSERT_EQ(test_sample, f->size()); double sum = 0; for (uint32_t i = 0; i < f->size(); ++i) { sum += (*f)[i].second; @@ -1106,12 +1104,10 @@ TEST_F(VirtualSocketServerTest, CreatesStandardDistribution) { sum_sq_dev += dev * dev; } const double stddev = sqrt(sum_sq_dev / f->size()); - EXPECT_NEAR(kTestMean[midx], mean, 0.1 * kTestMean[midx]) - << "M=" << kTestMean[midx] << " SD=" << kStdDev - << " N=" << kTestSamples[sidx]; + EXPECT_NEAR(test_mean, mean, 0.1 * test_mean) + << "M=" << test_mean << " SD=" << kStdDev << " N=" << test_sample; EXPECT_NEAR(kStdDev, stddev, 0.1 * kStdDev) - << "M=" << kTestMean[midx] << " SD=" << kStdDev - << " N=" << kTestSamples[sidx]; + << "M=" << test_mean << " SD=" << kStdDev << " N=" << test_sample; } } } diff --git a/rtc_base/weak_ptr.cc b/rtc_base/weak_ptr.cc index d67472d264..80c25a7294 100644 --- a/rtc_base/weak_ptr.cc +++ b/rtc_base/weak_ptr.cc @@ -10,6 +10,8 @@ #include "rtc_base/weak_ptr.h" +#include "api/sequence_checker.h" + // The implementation is borrowed from chromium except that it does not // implement SupportsWeakPtr. diff --git a/rtc_base/weak_ptr.h b/rtc_base/weak_ptr.h index 00b77fd63f..5ed82ac1d6 100644 --- a/rtc_base/weak_ptr.h +++ b/rtc_base/weak_ptr.h @@ -11,13 +11,12 @@ #ifndef RTC_BASE_WEAK_PTR_H_ #define RTC_BASE_WEAK_PTR_H_ -#include +#include #include #include "api/scoped_refptr.h" #include "api/sequence_checker.h" #include "rtc_base/checks.h" -#include "rtc_base/ref_count.h" #include "rtc_base/ref_counted_object.h" #include "rtc_base/system/no_unique_address.h" #include "rtc_base/thread_annotations.h" diff --git a/rtc_base/weak_ptr_unittest.cc b/rtc_base/weak_ptr_unittest.cc index 3bff8add88..b7f3b5c5ba 100644 --- a/rtc_base/weak_ptr_unittest.cc +++ b/rtc_base/weak_ptr_unittest.cc @@ -12,8 +12,8 @@ #include #include +#include -#include "rtc_base/event.h" #include "rtc_base/task_queue_for_test.h" #include "test/gtest.h" diff --git a/rtc_base/win32.cc b/rtc_base/win32.cc index fce3e07650..a50501750f 100644 --- a/rtc_base/win32.cc +++ b/rtc_base/win32.cc @@ -14,8 +14,8 @@ #include #include +#include -#include "rtc_base/arraysize.h" #include "rtc_base/byte_order.h" #include "rtc_base/checks.h" #include "rtc_base/string_utils.h" @@ -88,7 +88,7 @@ const char* inet_ntop_v6(const void* src, char* dst, socklen_t size) { int current = 1; int max = 0; int maxpos = -1; - int run_array_size = arraysize(runpos); + int run_array_size = std::ssize(runpos); // Run over the address marking runs of 0s. for (int i = 0; i < run_array_size; ++i) { if (as_shorts[i] == 0) { @@ -137,7 +137,7 @@ const char* inet_ntop_v6(const void* src, char* dst, socklen_t size) { for (int i = 0; i < run_array_size; ++i) { if (runpos[i] == -1) { cursor += snprintf(cursor, INET6_ADDRSTRLEN - (cursor - dst), "%x", - webrtc::NetworkToHost16(as_shorts[i])); + NetworkToHost16(as_shorts[i])); if (i != 7 && runpos[i + 1] != 1) { *cursor++ = ':'; } @@ -292,7 +292,7 @@ int inet_pton_v6(const char* src, void* dst) { if (sscanf(readcursor, "%4hx%n", &word, &bytesread) != 1) { return 0; } else { - *addr_cursor = webrtc::HostToNetwork16(word); + *addr_cursor = HostToNetwork16(word); ++addr_cursor; readcursor += bytesread; if (*readcursor != ':' && *readcursor != '\0') { diff --git a/rtc_base/zero_memory_unittest.cc b/rtc_base/zero_memory_unittest.cc index b75e3795ad..f333266d92 100644 --- a/rtc_base/zero_memory_unittest.cc +++ b/rtc_base/zero_memory_unittest.cc @@ -12,6 +12,8 @@ #include +#include + #include "api/array_view.h" #include "test/gtest.h" diff --git a/rtc_tools/data_channel_benchmark/BUILD.gn b/rtc_tools/data_channel_benchmark/BUILD.gn index a8804a8dda..28a8df9c61 100644 --- a/rtc_tools/data_channel_benchmark/BUILD.gn +++ b/rtc_tools/data_channel_benchmark/BUILD.gn @@ -25,7 +25,10 @@ rtc_library("grpc_signaling") { ":signaling_grpc_proto", ":signaling_interface", "../../api:libjingle_peerconnection_api", + "../../rtc_base:checks", + "../../rtc_base:logging", "../../rtc_base:threading", + "//third_party/abseil-cpp/absl/time", "//third_party/grpc:grpc++", ] @@ -43,16 +46,13 @@ rtc_executable("data_channel_benchmark") { ":grpc_signaling", ":signaling_interface", "../../api:create_peerconnection_factory", + "../../api:field_trials", + "../../api:field_trials_view", "../../api:libjingle_peerconnection_api", "../../api:rtc_error", "../../api:scoped_refptr", - "../../api/audio:audio_device", - "../../api/audio:audio_mixer_api", - "../../api/audio:audio_processing", "../../api/audio_codecs:builtin_audio_decoder_factory", "../../api/audio_codecs:builtin_audio_encoder_factory", - "../../api/video_codecs:video_codecs_api", - "../../api/video_codecs:video_codecs_api", "../../api/video_codecs:video_decoder_factory_template", "../../api/video_codecs:video_decoder_factory_template_dav1d_adapter", "../../api/video_codecs:video_decoder_factory_template_libvpx_vp8_adapter", @@ -72,11 +72,9 @@ rtc_executable("data_channel_benchmark") { "../../rtc_base:stringutils", "../../rtc_base:threading", "../../system_wrappers", - "../../system_wrappers:field_trial", - "//third_party/abseil-cpp/absl/cleanup:cleanup", + "//third_party/abseil-cpp/absl/cleanup", "//third_party/abseil-cpp/absl/flags:flag", "//third_party/abseil-cpp/absl/flags:parse", "//third_party/abseil-cpp/absl/strings:string_view", - "//third_party/abseil-cpp/absl/time", ] } diff --git a/rtc_tools/data_channel_benchmark/data_channel_benchmark.cc b/rtc_tools/data_channel_benchmark/data_channel_benchmark.cc index 7c5d05e336..e4a4f5aec0 100644 --- a/rtc_tools/data_channel_benchmark/data_channel_benchmark.cc +++ b/rtc_tools/data_channel_benchmark/data_channel_benchmark.cc @@ -33,6 +33,7 @@ #include "absl/flags/parse.h" #include "absl/strings/string_view.h" #include "api/data_channel_interface.h" +#include "api/field_trials.h" #include "api/peer_connection_interface.h" #include "api/rtc_error.h" #include "api/scoped_refptr.h" @@ -48,7 +49,6 @@ #include "rtc_tools/data_channel_benchmark/peer_connection_client.h" #include "rtc_tools/data_channel_benchmark/signaling_interface.h" #include "system_wrappers/include/clock.h" -#include "system_wrappers/include/field_trial.h" ABSL_FLAG(int, verbose, 0, "verbosity level (0-5)"); ABSL_FLAG(bool, server, false, "Server mode"); @@ -249,7 +249,8 @@ int RunServer() { signaling_thread->Start(); { auto factory = webrtc::PeerConnectionClient::CreateDefaultFactory( - signaling_thread.get()); + signaling_thread.get(), std::make_unique( + absl::GetFlag(FLAGS_force_fieldtrials))); auto grpc_server = webrtc::GrpcSignalingServerInterface::Create( [factory = @@ -281,7 +282,7 @@ int RunServer() { // Wait for the sender and receiver peers to stabilize (send all ACKs) // This makes it easier to isolate the sending part when profiling. - absl::SleepFor(absl::Seconds(1)); + webrtc::Thread::SleepMs(/*millis=*/1'000); auto begin_time = webrtc::Clock::GetRealTimeClock()->CurrentTime(); @@ -320,7 +321,8 @@ int RunClient() { signaling_thread->Start(); { auto factory = webrtc::PeerConnectionClient::CreateDefaultFactory( - signaling_thread.get()); + signaling_thread.get(), std::make_unique( + absl::GetFlag(FLAGS_force_fieldtrials))); auto grpc_client = webrtc::GrpcSignalingClientInterface::Create( server_address + ":" + std::to_string(port)); webrtc::PeerConnectionClient client(factory.get(), @@ -390,9 +392,6 @@ int main(int argc, char** argv) { static_cast(logging_severity)); bool is_server = absl::GetFlag(FLAGS_server); - std::string field_trials = absl::GetFlag(FLAGS_force_fieldtrials); - - webrtc::field_trial::InitFieldTrialsFromString(field_trials.c_str()); return is_server ? RunServer() : RunClient(); } diff --git a/rtc_tools/data_channel_benchmark/grpc_signaling.cc b/rtc_tools/data_channel_benchmark/grpc_signaling.cc index 9073b0078b..e158a4b2a2 100644 --- a/rtc_tools/data_channel_benchmark/grpc_signaling.cc +++ b/rtc_tools/data_channel_benchmark/grpc_signaling.cc @@ -9,16 +9,24 @@ */ #include "rtc_tools/data_channel_benchmark/grpc_signaling.h" -#include #include +#include +#include +#include +#include +#include +#include #include #include #include "api/jsep.h" -#include "api/jsep_ice_candidate.h" +#include "rtc_base/checks.h" +#include "rtc_base/logging.h" #include "rtc_base/thread.h" #include "rtc_tools/data_channel_benchmark/peer_connection_signaling.grpc.pb.h" +#include "rtc_tools/data_channel_benchmark/peer_connection_signaling.pb.h" +#include "rtc_tools/data_channel_benchmark/signaling_interface.h" namespace webrtc { namespace { @@ -35,14 +43,9 @@ class SessionData : public SignalingInterface { explicit SessionData(T* stream) : stream_(stream) {} void SetStream(T* stream) { stream_ = stream; } - void SendIceCandidate(const IceCandidateInterface* candidate) override { + void SendIceCandidate(const ::webrtc::IceCandidate* candidate) override { RTC_LOG(LS_INFO) << "SendIceCandidate"; - std::string serialized_candidate; - if (!candidate->ToString(&serialized_candidate)) { - RTC_LOG(LS_ERROR) << "Failed to serialize ICE candidate"; - return; - } - + std::string serialized_candidate = candidate->ToString(); SignalingMessage message; IceCandidate* proto_candidate = message.mutable_candidate(); proto_candidate->set_description(serialized_candidate); @@ -76,7 +79,7 @@ class SessionData : public SignalingInterface { } void OnIceCandidate( - std::function candidate)> + std::function candidate)> callback) override { RTC_LOG(LS_INFO) << "OnIceCandidate"; ice_candidate_callback_ = callback; @@ -84,9 +87,9 @@ class SessionData : public SignalingInterface { T* stream_; - std::function)> + std::function)> ice_candidate_callback_; - std::function)> + std::function)> remote_description_callback_; }; @@ -103,10 +106,10 @@ void ProcessMessages(StreamReader* stream, SessionData* session) { switch (message.Content_case()) { case SignalingMessage::ContentCase::kCandidate: { SdpParseError error; - auto jsep_candidate = std::make_unique( - message.candidate().mid(), message.candidate().mline_index()); - if (!jsep_candidate->Initialize(message.candidate().description(), - &error)) { + auto jsep_candidate = ::webrtc::IceCandidate::Create( + message.candidate().mid(), message.candidate().mline_index(), + message.candidate().description(), &error); + if (!jsep_candidate) { RTC_LOG(LS_ERROR) << "Failed to deserialize ICE candidate '" << message.candidate().description() << "'"; RTC_LOG(LS_ERROR) diff --git a/rtc_tools/data_channel_benchmark/grpc_signaling.h b/rtc_tools/data_channel_benchmark/grpc_signaling.h index 15799d22b7..3c0bb12731 100644 --- a/rtc_tools/data_channel_benchmark/grpc_signaling.h +++ b/rtc_tools/data_channel_benchmark/grpc_signaling.h @@ -40,7 +40,7 @@ class GrpcSignalingServerInterface { // Create a gRPC server listening on |port| that will run |callback| on each // request. If |oneshot| is true, it will terminate after serving one request. static std::unique_ptr Create( - std::function callback, + std::function callback, int port, bool oneshot); }; @@ -53,7 +53,7 @@ class GrpcSignalingClientInterface { // Connect the client to the gRPC server. virtual bool Start() = 0; - virtual webrtc::SignalingInterface* signaling_client() = 0; + virtual SignalingInterface* signaling_client() = 0; // Create a client to connnect to a server at |server_address|. static std::unique_ptr Create( diff --git a/rtc_tools/data_channel_benchmark/peer_connection_client.cc b/rtc_tools/data_channel_benchmark/peer_connection_client.cc index 74f1216e2b..7be633151b 100644 --- a/rtc_tools/data_channel_benchmark/peer_connection_client.cc +++ b/rtc_tools/data_channel_benchmark/peer_connection_client.cc @@ -9,29 +9,27 @@ */ #include "rtc_tools/data_channel_benchmark/peer_connection_client.h" +#include +#include #include -#include #include -#include "api/audio/audio_device.h" -#include "api/audio/audio_mixer.h" -#include "api/audio/audio_processing.h" #include "api/audio_codecs/builtin_audio_decoder_factory.h" #include "api/audio_codecs/builtin_audio_encoder_factory.h" #include "api/create_peerconnection_factory.h" +#include "api/data_channel_interface.h" +#include "api/field_trials_view.h" #include "api/jsep.h" #include "api/peer_connection_interface.h" #include "api/rtc_error.h" #include "api/scoped_refptr.h" #include "api/set_local_description_observer_interface.h" #include "api/set_remote_description_observer_interface.h" -#include "api/video_codecs/video_decoder_factory.h" #include "api/video_codecs/video_decoder_factory_template.h" #include "api/video_codecs/video_decoder_factory_template_dav1d_adapter.h" #include "api/video_codecs/video_decoder_factory_template_libvpx_vp8_adapter.h" #include "api/video_codecs/video_decoder_factory_template_libvpx_vp9_adapter.h" #include "api/video_codecs/video_decoder_factory_template_open_h264_adapter.h" -#include "api/video_codecs/video_encoder_factory.h" #include "api/video_codecs/video_encoder_factory_template.h" #include "api/video_codecs/video_encoder_factory_template_libaom_av1_adapter.h" #include "api/video_codecs/video_encoder_factory_template_libvpx_vp8_adapter.h" @@ -41,6 +39,7 @@ #include "rtc_base/logging.h" #include "rtc_base/ref_counted_object.h" #include "rtc_base/thread.h" +#include "rtc_tools/data_channel_benchmark/signaling_interface.h" namespace { @@ -131,10 +130,9 @@ PeerConnectionClient::PeerConnectionClient( PeerConnectionFactoryInterface* factory, SignalingInterface* signaling) : signaling_(signaling) { - signaling_->OnIceCandidate( - [&](std::unique_ptr candidate) { - AddIceCandidate(std::move(candidate)); - }); + signaling_->OnIceCandidate([&](std::unique_ptr candidate) { + AddIceCandidate(std::move(candidate)); + }); signaling_->OnRemoteDescription( [&](std::unique_ptr sdp) { SetRemoteDescription(std::move(sdp)); @@ -147,7 +145,9 @@ PeerConnectionClient::~PeerConnectionClient() { } scoped_refptr -PeerConnectionClient::CreateDefaultFactory(Thread* signaling_thread) { +PeerConnectionClient::CreateDefaultFactory( + Thread* signaling_thread, + std::unique_ptr field_trials) { auto factory = CreatePeerConnectionFactory( /*network_thread=*/nullptr, /*worker_thread=*/nullptr, /*signaling_thread*/ signaling_thread, @@ -159,7 +159,8 @@ PeerConnectionClient::CreateDefaultFactory(Thread* signaling_thread) { std::make_unique>(), - /*audio_mixer=*/nullptr, /*audio_processing=*/nullptr); + /*audio_mixer=*/nullptr, /*audio_processing=*/nullptr, + /*audio_frame_processor=*/nullptr, std::move(field_trials)); if (!factory) { RTC_LOG(LS_ERROR) << "Failed to initialize PeerConnectionFactory"; @@ -251,8 +252,7 @@ void PeerConnectionClient::OnIceGatheringChange( } } -void PeerConnectionClient::OnIceCandidate( - const IceCandidateInterface* candidate) { +void PeerConnectionClient::OnIceCandidate(const IceCandidate* candidate) { signaling_->SendIceCandidate(candidate); } @@ -305,11 +305,11 @@ bool PeerConnectionClient::SetRemoteDescription( } void PeerConnectionClient::AddIceCandidate( - std::unique_ptr candidate) { + std::unique_ptr candidate) { RTC_LOG(LS_INFO) << "AddIceCandidate"; peer_connection_->AddIceCandidate( - std::move(candidate), [](const webrtc::RTCError& error) { + std::move(candidate), [](const RTCError& error) { RTC_LOG(LS_INFO) << "Failed to add candidate: " << error.message(); }); } diff --git a/rtc_tools/data_channel_benchmark/peer_connection_client.h b/rtc_tools/data_channel_benchmark/peer_connection_client.h index f8f42e6037..c7e71b4e1a 100644 --- a/rtc_tools/data_channel_benchmark/peer_connection_client.h +++ b/rtc_tools/data_channel_benchmark/peer_connection_client.h @@ -14,15 +14,13 @@ #include #include -#include #include #include "api/data_channel_interface.h" +#include "api/field_trials_view.h" #include "api/jsep.h" #include "api/peer_connection_interface.h" -#include "api/rtp_receiver_interface.h" #include "api/scoped_refptr.h" -#include "api/set_local_description_observer_interface.h" #include "rtc_base/logging.h" #include "rtc_base/thread.h" #include "rtc_tools/data_channel_benchmark/signaling_interface.h" @@ -31,10 +29,10 @@ namespace webrtc { // Handles all the details for creating a PeerConnection and negotiation using a // SignalingInterface object. -class PeerConnectionClient : public webrtc::PeerConnectionObserver { +class PeerConnectionClient : public PeerConnectionObserver { public: - explicit PeerConnectionClient(webrtc::PeerConnectionFactoryInterface* factory, - webrtc::SignalingInterface* signaling); + explicit PeerConnectionClient(PeerConnectionFactoryInterface* factory, + SignalingInterface* signaling); ~PeerConnectionClient() override; @@ -51,56 +49,52 @@ class PeerConnectionClient : public webrtc::PeerConnectionObserver { // Disconnect from the call. void Disconnect(); - scoped_refptr peerConnection() { + scoped_refptr peerConnection() { return peer_connection_; } // Set a callback to run when a DataChannel is created by the remote peer. void SetOnDataChannel( - std::function)> - callback); + std::function)> callback); - std::vector>& dataChannels() { + std::vector>& dataChannels() { return data_channels_; } // Creates a default PeerConnectionFactory object. - static scoped_refptr - CreateDefaultFactory(Thread* signaling_thread); + static scoped_refptr CreateDefaultFactory( + Thread* signaling_thread, + std::unique_ptr field_trials); private: - void AddIceCandidate( - std::unique_ptr candidate); - bool SetRemoteDescription( - std::unique_ptr desc); + void AddIceCandidate(std::unique_ptr candidate); + bool SetRemoteDescription(std::unique_ptr desc); // Initialize the PeerConnection with a given PeerConnectionFactory. - bool InitializePeerConnection( - webrtc::PeerConnectionFactoryInterface* factory); + bool InitializePeerConnection(PeerConnectionFactoryInterface* factory); void DeletePeerConnection(); // PeerConnectionObserver implementation. void OnSignalingChange( - webrtc::PeerConnectionInterface::SignalingState new_state) override { + PeerConnectionInterface::SignalingState new_state) override { RTC_LOG(LS_INFO) << __FUNCTION__ << " new state: " << new_state; } - void OnDataChannel( - scoped_refptr channel) override; + void OnDataChannel(scoped_refptr channel) override; void OnNegotiationNeededEvent(uint32_t event_id) override; void OnIceConnectionChange( - webrtc::PeerConnectionInterface::IceConnectionState new_state) override; + PeerConnectionInterface::IceConnectionState new_state) override; void OnIceGatheringChange( - webrtc::PeerConnectionInterface::IceGatheringState new_state) override; - void OnIceCandidate(const webrtc::IceCandidateInterface* candidate) override; + PeerConnectionInterface::IceGatheringState new_state) override; + void OnIceCandidate(const IceCandidate* candidate) override; void OnIceConnectionReceivingChange(bool receiving) override { RTC_LOG(LS_INFO) << __FUNCTION__ << " receiving? " << receiving; } - scoped_refptr peer_connection_; - std::function)> + scoped_refptr peer_connection_; + std::function)> on_data_channel_callback_; - std::vector> data_channels_; - webrtc::SignalingInterface* signaling_; + std::vector> data_channels_; + SignalingInterface* signaling_; }; } // namespace webrtc diff --git a/rtc_tools/data_channel_benchmark/signaling_interface.h b/rtc_tools/data_channel_benchmark/signaling_interface.h index 77c811acb3..dcc126e5d5 100644 --- a/rtc_tools/data_channel_benchmark/signaling_interface.h +++ b/rtc_tools/data_channel_benchmark/signaling_interface.h @@ -20,22 +20,20 @@ class SignalingInterface { virtual ~SignalingInterface() = default; // Send an ICE candidate over the transport. - virtual void SendIceCandidate( - const webrtc::IceCandidateInterface* candidate) = 0; + virtual void SendIceCandidate(const IceCandidate* candidate) = 0; // Send a local description over the transport. - virtual void SendDescription( - const webrtc::SessionDescriptionInterface* sdp) = 0; + virtual void SendDescription(const SessionDescriptionInterface* sdp) = 0; // Set a callback when receiving a description from the transport. virtual void OnRemoteDescription( - std::function - sdp)> callback) = 0; + std::function sdp)> + callback) = 0; // Set a callback when receiving an ICE candidate from the transport. virtual void OnIceCandidate( - std::function - candidate)> callback) = 0; + std::function candidate)> + callback) = 0; }; } // namespace webrtc diff --git a/rtc_tools/frame_analyzer/video_color_aligner_unittest.cc b/rtc_tools/frame_analyzer/video_color_aligner_unittest.cc index 90b2f92cc1..f175a4e23b 100644 --- a/rtc_tools/frame_analyzer/video_color_aligner_unittest.cc +++ b/rtc_tools/frame_analyzer/video_color_aligner_unittest.cc @@ -44,7 +44,7 @@ void ExpectNear(const ColorTransformationMatrix& expected, class VideoColorAlignerTest : public ::testing::Test { protected: - void SetUp() { + void SetUp() override { reference_video_ = OpenYuvFile(ResourcePath("foreman_128x96", "yuv"), 128, 96); ASSERT_TRUE(reference_video_); diff --git a/rtc_tools/frame_analyzer/video_geometry_aligner_unittest.cc b/rtc_tools/frame_analyzer/video_geometry_aligner_unittest.cc index 62f853c625..4cc5af8518 100644 --- a/rtc_tools/frame_analyzer/video_geometry_aligner_unittest.cc +++ b/rtc_tools/frame_analyzer/video_geometry_aligner_unittest.cc @@ -23,7 +23,7 @@ namespace test { class VideoGeometryAlignerTest : public ::testing::Test { protected: - void SetUp() { + void SetUp() override { reference_video_ = OpenYuvFile(ResourcePath("foreman_128x96", "yuv"), 128, 96); ASSERT_TRUE(reference_video_); diff --git a/rtc_tools/frame_analyzer/video_temporal_aligner_unittest.cc b/rtc_tools/frame_analyzer/video_temporal_aligner_unittest.cc index 1fcbd9c444..0fe03e8924 100644 --- a/rtc_tools/frame_analyzer/video_temporal_aligner_unittest.cc +++ b/rtc_tools/frame_analyzer/video_temporal_aligner_unittest.cc @@ -22,7 +22,7 @@ namespace test { class VideoTemporalAlignerTest : public ::testing::Test { protected: - void SetUp() { + void SetUp() override { reference_video = OpenYuvFile(ResourcePath("foreman_128x96", "yuv"), 128, 96); ASSERT_TRUE(reference_video); diff --git a/rtc_tools/network_tester/network_tester_unittest.cc b/rtc_tools/network_tester/network_tester_unittest.cc index 8f522afa36..c9fb87fec2 100644 --- a/rtc_tools/network_tester/network_tester_unittest.cc +++ b/rtc_tools/network_tester/network_tester_unittest.cc @@ -27,17 +27,16 @@ TEST(NetworkTesterTest, ServerClient) { // running the test in parallel in stress runs. Skipping all reserved ports. const int MIN_PORT = 49152; const int MAX_PORT = 65535; - int port = webrtc::Random(webrtc::TimeMicros()).Rand(MIN_PORT, MAX_PORT); + int port = Random(TimeMicros()).Rand(MIN_PORT, MAX_PORT); - webrtc::AutoThread main_thread; + AutoThread main_thread; TestController client( - 0, 0, webrtc::test::ResourcePath("network_tester/client_config", "dat"), - webrtc::test::OutputPath() + "client_packet_log.dat"); + 0, 0, test::ResourcePath("network_tester/client_config", "dat"), + test::OutputPath() + "client_packet_log.dat"); TestController server( - port, port, - webrtc::test::ResourcePath("network_tester/server_config", "dat"), - webrtc::test::OutputPath() + "server_packet_log.dat"); + port, port, test::ResourcePath("network_tester/server_config", "dat"), + test::OutputPath() + "server_packet_log.dat"); client.SendConnectTo("127.0.0.1", port); EXPECT_THAT( WaitUntil([&] { return server.IsTestDone() && client.IsTestDone(); }, diff --git a/rtc_tools/network_tester/packet_sender.h b/rtc_tools/network_tester/packet_sender.h index 832ee49097..84df00e513 100644 --- a/rtc_tools/network_tester/packet_sender.h +++ b/rtc_tools/network_tester/packet_sender.h @@ -33,8 +33,8 @@ class TestController; class PacketSender { public: PacketSender(TestController* test_controller, - webrtc::TaskQueueBase* worker_queue, - scoped_refptr task_safety_flag, + TaskQueueBase* worker_queue, + scoped_refptr task_safety_flag, const std::string& config_file_path); ~PacketSender(); @@ -58,8 +58,8 @@ class PacketSender { bool sending_ RTC_GUARDED_BY(worker_queue_checker_); const std::string config_file_path_; TestController* const test_controller_; - webrtc::TaskQueueBase* worker_queue_; - scoped_refptr task_safety_flag_; + TaskQueueBase* worker_queue_; + scoped_refptr task_safety_flag_; }; } // namespace webrtc diff --git a/rtc_tools/network_tester/test_controller.h b/rtc_tools/network_tester/test_controller.h index 8a29c5db11..0e99ade343 100644 --- a/rtc_tools/network_tester/test_controller.h +++ b/rtc_tools/network_tester/test_controller.h @@ -83,7 +83,7 @@ class TestController { SocketAddress remote_address_; std::unique_ptr packet_sender_ RTC_GUARDED_BY(packet_sender_thread_); - scoped_refptr task_safety_flag_; + scoped_refptr task_safety_flag_; }; } // namespace webrtc diff --git a/rtc_tools/rtc_event_log_visualizer/plot_base.h b/rtc_tools/rtc_event_log_visualizer/plot_base.h index 722a79d119..150d890996 100644 --- a/rtc_tools/rtc_event_log_visualizer/plot_base.h +++ b/rtc_tools/rtc_event_log_visualizer/plot_base.h @@ -172,7 +172,7 @@ class Plot { absl::string_view figure_output_path = absl::string_view()) const; // Replaces ProtobufPlot::Draw() - void ExportProtobuf(webrtc::analytics::Chart* chart) const; + void ExportProtobuf(analytics::Chart* chart) const; protected: float xaxis_min_; @@ -209,7 +209,7 @@ class PlotCollection { absl::string_view figure_output_path = absl::string_view()) const; // Replaces ProtobufPlotCollections::Draw() - void ExportProtobuf(webrtc::analytics::ChartCollection* collection) const; + void ExportProtobuf(analytics::ChartCollection* collection) const; protected: std::vector> plots_; diff --git a/rtc_tools/rtp_generator/rtp_generator.h b/rtc_tools/rtp_generator/rtp_generator.h index cd7ad29848..4510b06e91 100644 --- a/rtc_tools/rtp_generator/rtp_generator.h +++ b/rtc_tools/rtp_generator/rtp_generator.h @@ -75,7 +75,7 @@ std::optional ParseRtpGeneratorOptionsFromFile( // to a file instead of out of the network. It then uses this sender // configuration to generate a mirror receiver configuration that can be read by // the video_replay program. -class RtpGenerator final : public webrtc::Transport { +class RtpGenerator final : public Transport { public: // Construct a new RtpGenerator using the specified options. explicit RtpGenerator(const RtpGeneratorOptions& options); @@ -90,7 +90,7 @@ class RtpGenerator final : public webrtc::Transport { void GenerateRtpDump(const std::string& rtp_dump_path); private: - // webrtc::Transport implementation + // Transport implementation // Captured RTP packets are written to the RTPDump file instead of over the // network. bool SendRtp(ArrayView packet, diff --git a/rtc_tools/video_encoder/video_encoder.cc b/rtc_tools/video_encoder/video_encoder.cc index b252162bcf..59fb7582ad 100644 --- a/rtc_tools/video_encoder/video_encoder.cc +++ b/rtc_tools/video_encoder/video_encoder.cc @@ -302,7 +302,7 @@ class BitstreamProcessor final : public EncodedImageCallback, return true; } - ~BitstreamProcessor() = default; + ~BitstreamProcessor() override = default; private: // DecodedImageCallback diff --git a/sdk/BUILD.gn b/sdk/BUILD.gn index 61199255ae..0d4c83800b 100644 --- a/sdk/BUILD.gn +++ b/sdk/BUILD.gn @@ -37,6 +37,7 @@ rtc_library("media_constraints") { deps = [ "../api:audio_options_api", "../api:libjingle_peerconnection_api", + "../rtc_base:stringutils", ] } @@ -1212,6 +1213,7 @@ if (is_ios || is_mac) { ":videoframebuffer_objc", ":videosource_objc", ":videotoolbox_objc", + "../api:array_view", "../api:libjingle_peerconnection_api", "../api:rtc_error_matchers", "../api:scoped_refptr", @@ -1230,7 +1232,6 @@ if (is_ios || is_mac) { "../media:rtc_media_tests_utils", "../modules/video_coding:video_codec_interface", "../rtc_base:gunit_helpers", - "../rtc_base:macromagic", "../rtc_base:refcount", "../rtc_base:rtc_event", "../rtc_base/system:unused", @@ -1749,6 +1750,7 @@ if (is_ios || is_mac) { "objc/components/video_codec/nalu_rewriter.h", ] deps = [ + "../api:array_view", "../common_video", "../modules/video_coding:webrtc_h264", "../rtc_base:buffer", @@ -1787,6 +1789,8 @@ if (is_ios || is_mac) { ":video_toolbox_cc", ":videocodec_objc", ":videoframebuffer_objc", + "../api:array_view", + "../api/video:video_rtp_headers", "../api/video_codecs:video_codecs_api", "../common_video", "../modules/video_coding:video_codec_interface", diff --git a/sdk/android/BUILD.gn b/sdk/android/BUILD.gn index 9c9cd415db..1d680923e5 100644 --- a/sdk/android/BUILD.gn +++ b/sdk/android/BUILD.gn @@ -1265,7 +1265,6 @@ if (current_os == "linux" || is_android) { "../../modules/audio_device:audio_device_buffer", "../../rtc_base:checks", "../../rtc_base:logging", - "../../rtc_base:macromagic", "../../rtc_base:platform_thread", "../../rtc_base:timeutils", "../../system_wrappers:metrics", @@ -1296,7 +1295,6 @@ if (current_os == "linux" || is_android) { "../../modules/audio_device:audio_device_buffer", "../../rtc_base:checks", "../../rtc_base:logging", - "../../rtc_base:macromagic", "../../rtc_base:stringutils", "../../rtc_base:timeutils", "../../system_wrappers", @@ -1327,7 +1325,6 @@ if (current_os == "linux" || is_android) { "../../modules/audio_device:audio_device_buffer", "../../rtc_base:checks", "../../rtc_base:logging", - "../../rtc_base:macromagic", "../../rtc_base:platform_thread", "../../rtc_base:timeutils", ] @@ -1741,7 +1738,6 @@ if (is_android) { "../../rtc_base:checks", "../../rtc_base:ip_address", "../../rtc_base:logging", - "../../rtc_base:macromagic", "../../rtc_base:platform_thread", "../../rtc_base:rtc_event", "../../rtc_base:stringutils", diff --git a/sdk/android/api/org/webrtc/AudioProcessingFactory.java b/sdk/android/api/org/webrtc/AudioProcessingFactory.java index e0aa25b87f..91d12cdc81 100644 --- a/sdk/android/api/org/webrtc/AudioProcessingFactory.java +++ b/sdk/android/api/org/webrtc/AudioProcessingFactory.java @@ -13,17 +13,10 @@ /** Factory for creating webrtc::AudioProcessing instances. */ public interface AudioProcessingFactory { /** - * Dynamically allocates a webrtc::AudioProcessing instance and returns a pointer to it. - * The caller takes ownership of the object. + * Dynamically allocates a {@code webrtc::AudioProcessing} instance. + * + * @param webrtcEnvRef non-null non-owning pointer to {@code webrtc::Environment} + * @return non-null owning scoped_refptr pointer to {@code webrtc::AudioProcessing} */ - // TODO: bugs.webrtc.org/369904700 - Remove when implementations switch to - // another variant. - @Deprecated - public default long createNative() { - return 0; - } - - public default long createNative(long webrtcEnvRef) { - return createNative(); - } + long createNative(long webrtcEnvRef); } diff --git a/sdk/android/api/org/webrtc/IceCandidate.java b/sdk/android/api/org/webrtc/IceCandidate.java index 5f00b2a5f4..9278f1bef6 100644 --- a/sdk/android/api/org/webrtc/IceCandidate.java +++ b/sdk/android/api/org/webrtc/IceCandidate.java @@ -16,7 +16,7 @@ /** * Representation of a single ICE Candidate, mirroring - * {@code IceCandidateInterface} in the C++ API. + * {@code IceCandidate} in the C++ API. */ public class IceCandidate { public final String sdpMid; diff --git a/sdk/android/api/org/webrtc/audio/AudioDeviceModule.java b/sdk/android/api/org/webrtc/audio/AudioDeviceModule.java index ba5097d6c8..c8ea22de87 100644 --- a/sdk/android/api/org/webrtc/audio/AudioDeviceModule.java +++ b/sdk/android/api/org/webrtc/audio/AudioDeviceModule.java @@ -19,17 +19,13 @@ */ public interface AudioDeviceModule { /** - * Returns a C++ pointer to a webrtc::AudioDeviceModule. Caller does _not_ take ownership and - * lifetime is handled through the release() call. + * Returns a C++ pointer to a {@code webrtc::AudioDeviceModule} instance. + * Lifetime of the returned object is handled through the release() call. + * + * @param webrtcEnvRef non-null non-owning pointer to {@code webrtc::Environment} + * @return non-null non-owning pointer to {@code webrtc::AudioDeviceModule} */ - @Deprecated - default long getNativeAudioDeviceModulePointer() { - return 0; - } - - public default long getNative(long webrtcEnvRef) { - return getNativeAudioDeviceModulePointer(); - } + long getNative(long webrtcEnvRef); /** * Release resources for this AudioDeviceModule, including native resources. The object should not diff --git a/sdk/android/native_unittests/audio_device/audio_device_unittest.cc b/sdk/android/native_unittests/audio_device/audio_device_unittest.cc index e8e5ad7c6b..62c81c4ee1 100644 --- a/sdk/android/native_unittests/audio_device/audio_device_unittest.cc +++ b/sdk/android/native_unittests/audio_device/audio_device_unittest.cc @@ -18,7 +18,6 @@ #include "api/environment/environment_factory.h" #include "api/scoped_refptr.h" #include "modules/audio_device/include/mock_audio_transport.h" -#include "rtc_base/arraysize.h" #include "rtc_base/event.h" #include "rtc_base/synchronization/mutex.h" #include "rtc_base/time_utils.h" diff --git a/sdk/android/src/jni/audio_device/audio_record_jni.cc b/sdk/android/src/jni/audio_device/audio_record_jni.cc index 195950bbc6..43706e9a6d 100644 --- a/sdk/android/src/jni/audio_device/audio_record_jni.cc +++ b/sdk/android/src/jni/audio_device/audio_record_jni.cc @@ -13,7 +13,6 @@ #include #include -#include "rtc_base/arraysize.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "rtc_base/platform_thread.h" diff --git a/sdk/android/src/jni/audio_device/opensles_common.cc b/sdk/android/src/jni/audio_device/opensles_common.cc index 300019a161..8225518a11 100644 --- a/sdk/android/src/jni/audio_device/opensles_common.cc +++ b/sdk/android/src/jni/audio_device/opensles_common.cc @@ -12,7 +12,8 @@ #include -#include "rtc_base/arraysize.h" +#include + #include "rtc_base/checks.h" namespace webrtc { @@ -42,7 +43,7 @@ const char* GetSLErrorString(size_t code) { "SL_RESULT_CONTROL_LOST", // 16 }; - if (code >= arraysize(sl_error_strings)) { + if (code >= std::size(sl_error_strings)) { return "SL_RESULT_UNKNOWN_ERROR"; } return sl_error_strings[code]; diff --git a/sdk/android/src/jni/audio_device/opensles_player.cc b/sdk/android/src/jni/audio_device/opensles_player.cc index efb6766afc..674e6e006e 100644 --- a/sdk/android/src/jni/audio_device/opensles_player.cc +++ b/sdk/android/src/jni/audio_device/opensles_player.cc @@ -12,11 +12,11 @@ #include +#include #include #include "api/array_view.h" #include "modules/audio_device/fine_audio_buffer.h" -#include "rtc_base/arraysize.h" #include "rtc_base/checks.h" #include "rtc_base/platform_thread.h" #include "rtc_base/time_utils.h" @@ -307,7 +307,7 @@ bool OpenSLESPlayer::CreateAudioPlayer() { RETURN_ON_ERROR( (*engine_)->CreateAudioPlayer( engine_, player_object_.Receive(), &audio_source, &audio_sink, - arraysize(interface_ids), interface_ids, interface_required), + std::size(interface_ids), interface_ids, interface_required), false); // Use the Android configuration interface to set platform-specific diff --git a/sdk/android/src/jni/audio_device/opensles_recorder.cc b/sdk/android/src/jni/audio_device/opensles_recorder.cc index 8e9bfaabe0..b34cba9f23 100644 --- a/sdk/android/src/jni/audio_device/opensles_recorder.cc +++ b/sdk/android/src/jni/audio_device/opensles_recorder.cc @@ -12,11 +12,11 @@ #include +#include #include #include "api/array_view.h" #include "modules/audio_device/fine_audio_buffer.h" -#include "rtc_base/arraysize.h" #include "rtc_base/checks.h" #include "rtc_base/platform_thread.h" #include "rtc_base/time_utils.h" @@ -264,7 +264,7 @@ bool OpenSLESRecorder::CreateAudioRecorder() { const SLboolean interface_required[] = {SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE}; if (LOG_ON_ERROR((*engine_)->CreateAudioRecorder( engine_, recorder_object_.Receive(), &audio_source, &audio_sink, - arraysize(interface_id), interface_id, interface_required))) { + std::size(interface_id), interface_id, interface_required))) { return false; } diff --git a/sdk/android/src/jni/pc/ice_candidate.cc b/sdk/android/src/jni/pc/ice_candidate.cc index 4e6e5706c7..0187927454 100644 --- a/sdk/android/src/jni/pc/ice_candidate.cc +++ b/sdk/android/src/jni/pc/ice_candidate.cc @@ -62,12 +62,10 @@ ScopedJavaLocalRef NativeToJavaCandidate(JNIEnv* env, ScopedJavaLocalRef NativeToJavaIceCandidate( JNIEnv* env, - const IceCandidateInterface& candidate) { - std::string sdp; - RTC_CHECK(candidate.ToString(&sdp)) << "got so far: " << sdp; - return CreateJavaIceCandidate(env, candidate.sdp_mid(), - candidate.sdp_mline_index(), sdp, - candidate.candidate().url(), 0); + const IceCandidate& candidate) { + return CreateJavaIceCandidate( + env, candidate.sdp_mid(), candidate.sdp_mline_index(), + candidate.ToString(), candidate.candidate().url(), 0); } ScopedJavaLocalRef NativeToJavaCandidateArray( diff --git a/sdk/android/src/jni/pc/ice_candidate.h b/sdk/android/src/jni/pc/ice_candidate.h index 4146ea33dc..608e8dcfe3 100644 --- a/sdk/android/src/jni/pc/ice_candidate.h +++ b/sdk/android/src/jni/pc/ice_candidate.h @@ -15,7 +15,6 @@ #include "api/data_channel_interface.h" #include "api/jsep.h" -#include "api/jsep_ice_candidate.h" #include "api/peer_connection_interface.h" #include "api/rtp_parameters.h" #include "rtc_base/ssl_identity.h" @@ -32,7 +31,7 @@ ScopedJavaLocalRef NativeToJavaCandidate(JNIEnv* env, ScopedJavaLocalRef NativeToJavaIceCandidate( JNIEnv* env, - const IceCandidateInterface& candidate); + const IceCandidate& candidate); ScopedJavaLocalRef NativeToJavaCandidateArray( JNIEnv* jni, diff --git a/sdk/android/src/jni/pc/peer_connection.cc b/sdk/android/src/jni/pc/peer_connection.cc index 51dd8d7e1e..bdf8a8176b 100644 --- a/sdk/android/src/jni/pc/peer_connection.cc +++ b/sdk/android/src/jni/pc/peer_connection.cc @@ -304,8 +304,7 @@ PeerConnectionObserverJni::PeerConnectionObserverJni( PeerConnectionObserverJni::~PeerConnectionObserverJni() = default; -void PeerConnectionObserverJni::OnIceCandidate( - const IceCandidateInterface* candidate) { +void PeerConnectionObserverJni::OnIceCandidate(const IceCandidate* candidate) { JNIEnv* env = AttachCurrentThreadIfNeeded(); Java_Observer_onIceCandidate(env, j_observer_global_, NativeToJavaIceCandidate(env, *candidate)); @@ -678,7 +677,7 @@ static jboolean JNI_PeerConnection_AddIceCandidate( const jni_zero::JavaParamRef& j_candidate_sdp) { std::string sdp_mid = JavaToNativeString(jni, j_sdp_mid); std::string sdp = JavaToNativeString(jni, j_candidate_sdp); - std::unique_ptr candidate( + std::unique_ptr candidate( CreateIceCandidate(sdp_mid, j_sdp_mline_index, sdp, nullptr)); return ExtractNativePC(jni, j_pc)->AddIceCandidate(candidate.get()); } @@ -692,7 +691,7 @@ static void JNI_PeerConnection_AddIceCandidateWithObserver( const jni_zero::JavaParamRef& j_observer) { std::string sdp_mid = JavaToNativeString(jni, j_sdp_mid); std::string sdp = JavaToNativeString(jni, j_candidate_sdp); - std::unique_ptr candidate( + std::unique_ptr candidate( CreateIceCandidate(sdp_mid, j_sdp_mline_index, sdp, nullptr)); scoped_refptr observer( diff --git a/sdk/android/src/jni/pc/peer_connection.h b/sdk/android/src/jni/pc/peer_connection.h index 61e9c4605b..d48ca47e3a 100644 --- a/sdk/android/src/jni/pc/peer_connection.h +++ b/sdk/android/src/jni/pc/peer_connection.h @@ -46,7 +46,7 @@ class PeerConnectionObserverJni : public PeerConnectionObserver { // Implementation of PeerConnectionObserver interface, which propagates // the callbacks to the Java observer. - void OnIceCandidate(const IceCandidateInterface* candidate) override; + void OnIceCandidate(const IceCandidate* candidate) override; void OnIceCandidateError(const std::string& address, int port, const std::string& url, diff --git a/sdk/media_constraints.cc b/sdk/media_constraints.cc index 0623071a90..8b5f063200 100644 --- a/sdk/media_constraints.cc +++ b/sdk/media_constraints.cc @@ -10,9 +10,13 @@ #include "sdk/media_constraints.h" +#include #include +#include +#include "api/audio_options.h" #include "api/peer_connection_interface.h" +#include "rtc_base/string_encode.h" namespace webrtc { namespace { diff --git a/sdk/objc/api/peerconnection/RTCIceCandidate+Private.h b/sdk/objc/api/peerconnection/RTCIceCandidate+Private.h index 8399877838..840c8c809a 100644 --- a/sdk/objc/api/peerconnection/RTCIceCandidate+Private.h +++ b/sdk/objc/api/peerconnection/RTCIceCandidate+Private.h @@ -20,18 +20,17 @@ NS_ASSUME_NONNULL_BEGIN () /** - * The native IceCandidateInterface representation of this RTCIceCandidate + * The native IceCandidate representation of this RTCIceCandidate * object. This is needed to pass to the underlying C++ APIs. */ - @property(nonatomic, readonly) - std::unique_ptr nativeCandidate; + @property(nonatomic, readonly) std::unique_ptr + nativeCandidate; /** - * Initialize an RTCIceCandidate from a native IceCandidateInterface. No + * Initialize an RTCIceCandidate from a native IceCandidate. No * ownership is taken of the native candidate. */ -- (instancetype)initWithNativeCandidate: - (const webrtc::IceCandidateInterface *)candidate; +- (instancetype)initWithNativeCandidate:(const webrtc::IceCandidate *)candidate; @end diff --git a/sdk/objc/api/peerconnection/RTCIceCandidate.mm b/sdk/objc/api/peerconnection/RTCIceCandidate.mm index 241af297e7..025601b295 100644 --- a/sdk/objc/api/peerconnection/RTCIceCandidate.mm +++ b/sdk/objc/api/peerconnection/RTCIceCandidate.mm @@ -47,10 +47,9 @@ - (NSString *)description { #pragma mark - Private - (instancetype)initWithNativeCandidate: - (const webrtc::IceCandidateInterface *)candidate { + (const webrtc::IceCandidate *)candidate { NSParameterAssert(candidate); - std::string sdp; - candidate->ToString(&sdp); + std::string sdp = candidate->ToString(); RTC_OBJC_TYPE(RTCIceCandidate) *rtcCandidate = [self initWithSdp:[NSString stringForStdString:sdp] @@ -61,10 +60,10 @@ - (instancetype)initWithNativeCandidate: return rtcCandidate; } -- (std::unique_ptr)nativeCandidate { +- (std::unique_ptr)nativeCandidate { webrtc::SdpParseError error; - webrtc::IceCandidateInterface *candidate = webrtc::CreateIceCandidate( + webrtc::IceCandidate *candidate = webrtc::CreateIceCandidate( _sdpMid.stdString, _sdpMLineIndex, _sdp.stdString, &error); if (!candidate) { @@ -73,7 +72,7 @@ - (instancetype)initWithNativeCandidate: error.line.c_str()); } - return std::unique_ptr(candidate); + return std::unique_ptr(candidate); } @end diff --git a/sdk/objc/api/peerconnection/RTCPeerConnection+Private.h b/sdk/objc/api/peerconnection/RTCPeerConnection+Private.h index c9a955ec63..d14a7ebc7b 100644 --- a/sdk/objc/api/peerconnection/RTCPeerConnection+Private.h +++ b/sdk/objc/api/peerconnection/RTCPeerConnection+Private.h @@ -54,7 +54,7 @@ class PeerConnectionDelegateAdapter : public PeerConnectionObserver { void OnIceGatheringChange( PeerConnectionInterface::IceGatheringState new_state) override; - void OnIceCandidate(const IceCandidateInterface *candidate) override; + void OnIceCandidate(const IceCandidate *candidate) override; void OnIceCandidateError(const std::string &address, int port, diff --git a/sdk/objc/api/peerconnection/RTCPeerConnection.mm b/sdk/objc/api/peerconnection/RTCPeerConnection.mm index cc92c6b51f..7b6b3bfc27 100644 --- a/sdk/objc/api/peerconnection/RTCPeerConnection.mm +++ b/sdk/objc/api/peerconnection/RTCPeerConnection.mm @@ -28,7 +28,7 @@ #include -#include "api/jsep_ice_candidate.h" +#include "api/jsep.h" #include "api/rtc_event_log_output_file.h" #include "api/set_local_description_observer_interface.h" #include "api/set_remote_description_observer_interface.h" @@ -309,7 +309,7 @@ void OnFailure(RTCError error) override { } void PeerConnectionDelegateAdapter::OnIceCandidate( - const IceCandidateInterface *candidate) { + const IceCandidate *candidate) { RTC_OBJC_TYPE(RTCPeerConnection) *peer_connection = peer_connection_; if (peer_connection == nil) { return; @@ -368,8 +368,7 @@ void OnFailure(RTCError error) override { NSMutableArray *ice_candidates = [NSMutableArray arrayWithCapacity:candidates.size()]; for (const auto &candidate : candidates) { - JsepIceCandidate candidate_wrapper( - candidate.transport_name(), -1, candidate); + IceCandidate candidate_wrapper(candidate.transport_name(), -1, candidate); RTC_OBJC_TYPE(RTCIceCandidate) *ice_candidate = [[RTC_OBJC_TYPE(RTCIceCandidate) alloc] initWithNativeCandidate:&candidate_wrapper]; @@ -391,14 +390,14 @@ JsepIceCandidate candidate_wrapper( return; } const auto &selected_pair = event.selected_candidate_pair; - JsepIceCandidate local_candidate_wrapper( + IceCandidate local_candidate_wrapper( selected_pair.local_candidate().transport_name(), -1, selected_pair.local_candidate()); RTC_OBJC_TYPE(RTCIceCandidate) *local_candidate = [[RTC_OBJC_TYPE(RTCIceCandidate) alloc] initWithNativeCandidate:&local_candidate_wrapper]; - JsepIceCandidate remote_candidate_wrapper( + IceCandidate remote_candidate_wrapper( selected_pair.remote_candidate().transport_name(), -1, selected_pair.remote_candidate()); @@ -614,7 +613,7 @@ - (void)close { } - (void)addIceCandidate:(RTC_OBJC_TYPE(RTCIceCandidate) *)candidate { - std::unique_ptr iceCandidate( + std::unique_ptr iceCandidate( candidate.nativeCandidate); _peerConnection->AddIceCandidate(iceCandidate.get()); } @@ -639,7 +638,7 @@ - (void)removeIceCandidates: (NSArray *)iceCandidates { std::vector candidates; for (RTC_OBJC_TYPE(RTCIceCandidate) * iceCandidate in iceCandidates) { - std::unique_ptr candidate( + std::unique_ptr candidate( iceCandidate.nativeCandidate); if (candidate) { candidates.push_back(candidate->candidate()); diff --git a/sdk/objc/components/video_codec/RTCVideoDecoderH264.mm b/sdk/objc/components/video_codec/RTCVideoDecoderH264.mm index 89802d19d4..429d69b82e 100644 --- a/sdk/objc/components/video_codec/RTCVideoDecoderH264.mm +++ b/sdk/objc/components/video_codec/RTCVideoDecoderH264.mm @@ -23,6 +23,7 @@ #import "helpers/UIDevice+RTCDevice.h" #endif +#include "api/array_view.h" #include "modules/video_coding/include/video_error_codes.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" @@ -114,8 +115,9 @@ - (NSInteger)decode:(RTC_OBJC_TYPE(RTCEncodedImage) *)inputImage } webrtc::ScopedCFTypeRef inputFormat = - webrtc::ScopedCF(webrtc::CreateVideoFormatDescription( - (uint8_t *)inputImage.buffer.bytes, inputImage.buffer.length)); + webrtc::ScopedCF( + webrtc::CreateVideoFormatDescription(webrtc::MakeArrayView( + (uint8_t *)inputImage.buffer.bytes, inputImage.buffer.length))); if (inputFormat) { // Check if the video format has changed, and reinitialize decoder if // needed. @@ -138,8 +140,8 @@ - (NSInteger)decode:(RTC_OBJC_TYPE(RTCEncodedImage) *)inputImage } CMSampleBufferRef sampleBuffer = nullptr; if (!webrtc::H264AnnexBBufferToCMSampleBuffer( - (uint8_t *)inputImage.buffer.bytes, - inputImage.buffer.length, + webrtc::MakeArrayView((uint8_t *)inputImage.buffer.bytes, + inputImage.buffer.length), _videoFormat, &sampleBuffer, _memoryPool)) { diff --git a/sdk/objc/components/video_codec/RTCVideoEncoderH264.mm b/sdk/objc/components/video_codec/RTCVideoEncoderH264.mm index d1a10dc9b6..eeb7d606fe 100644 --- a/sdk/objc/components/video_codec/RTCVideoEncoderH264.mm +++ b/sdk/objc/components/video_codec/RTCVideoEncoderH264.mm @@ -28,6 +28,7 @@ #import "components/video_frame_buffer/RTCCVPixelBuffer.h" #import "helpers.h" +#include "api/video/video_timing.h" #include "api/video_codecs/h264_profile_level_id.h" #include "common_video/h264/h264_bitstream_parser.h" #include "common_video/include/bitrate_adjuster.h" diff --git a/sdk/objc/components/video_codec/nalu_rewriter.cc b/sdk/objc/components/video_codec/nalu_rewriter.cc index 1d5a34758f..236ef32d08 100644 --- a/sdk/objc/components/video_codec/nalu_rewriter.cc +++ b/sdk/objc/components/video_codec/nalu_rewriter.cc @@ -13,9 +13,14 @@ #include -#include +#include +#include +#include #include +#include "api/array_view.h" +#include "common_video/h264/h264_common.h" +#include "rtc_base/buffer.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" @@ -132,26 +137,23 @@ bool H264CMSampleBufferToAnnexBBuffer(CMSampleBufferRef avcc_sample_buffer, return true; } -bool H264AnnexBBufferToCMSampleBuffer(const uint8_t* annexb_buffer, - size_t annexb_buffer_size, +bool H264AnnexBBufferToCMSampleBuffer(ArrayView annexb_buffer, CMVideoFormatDescriptionRef video_format, CMSampleBufferRef* out_sample_buffer, CMMemoryPoolRef memory_pool) { - RTC_DCHECK(annexb_buffer); RTC_DCHECK(out_sample_buffer); RTC_DCHECK(video_format); *out_sample_buffer = nullptr; - AnnexBBufferReader reader(annexb_buffer, annexb_buffer_size); + AnnexBBufferReader reader(annexb_buffer); if (reader.SeekToNextNaluOfType(kSps)) { // Buffer contains an SPS NALU - skip it and the following PPS - const uint8_t* data; - size_t data_len; - if (!reader.ReadNalu(&data, &data_len)) { + ArrayView data; + if (!reader.ReadNalu(data)) { RTC_LOG(LS_ERROR) << "Failed to read SPS"; return false; } - if (!reader.ReadNalu(&data, &data_len)) { + if (!reader.ReadNalu(data)) { RTC_LOG(LS_ERROR) << "Failed to read PPS"; return false; } @@ -202,13 +204,12 @@ bool H264AnnexBBufferToCMSampleBuffer(const uint8_t* annexb_buffer, RTC_DCHECK(block_buffer_size == reader.BytesRemaining()); // Write Avcc NALUs into block buffer memory. - AvccBufferWriter writer(reinterpret_cast(data_ptr), - block_buffer_size); + AvccBufferWriter writer( + MakeArrayView(reinterpret_cast(data_ptr), block_buffer_size)); while (reader.BytesRemaining() > 0) { - const uint8_t* nalu_data_ptr = nullptr; - size_t nalu_data_size = 0; - if (reader.ReadNalu(&nalu_data_ptr, &nalu_data_size)) { - writer.WriteNalu(nalu_data_ptr, nalu_data_size); + ArrayView nalu_data; + if (reader.ReadNalu(nalu_data)) { + writer.WriteNalu(nalu_data); } } @@ -226,20 +227,26 @@ bool H264AnnexBBufferToCMSampleBuffer(const uint8_t* annexb_buffer, } CMVideoFormatDescriptionRef CreateVideoFormatDescription( - const uint8_t* annexb_buffer, - size_t annexb_buffer_size) { + ArrayView annexb_buffer) { const uint8_t* param_set_ptrs[2] = {}; size_t param_set_sizes[2] = {}; - AnnexBBufferReader reader(annexb_buffer, annexb_buffer_size); + AnnexBBufferReader reader(annexb_buffer); // Skip everyting before the SPS, then read the SPS and PPS if (!reader.SeekToNextNaluOfType(kSps)) { return nullptr; } - if (!reader.ReadNalu(¶m_set_ptrs[0], ¶m_set_sizes[0])) { + ArrayView param_set; + if (reader.ReadNalu(param_set)) { + param_set_ptrs[0] = param_set.data(); + param_set_sizes[0] = param_set.size(); + } else { RTC_LOG(LS_ERROR) << "Failed to read SPS"; return nullptr; } - if (!reader.ReadNalu(¶m_set_ptrs[1], ¶m_set_sizes[1])) { + if (reader.ReadNalu(param_set)) { + param_set_ptrs[1] = param_set.data(); + param_set_sizes[1] = param_set.size(); + } else { RTC_LOG(LS_ERROR) << "Failed to read PPS"; return nullptr; } @@ -255,29 +262,20 @@ CMVideoFormatDescriptionRef CreateVideoFormatDescription( return description; } -AnnexBBufferReader::AnnexBBufferReader(const uint8_t* annexb_buffer, - size_t length) - : start_(annexb_buffer), length_(length) { - RTC_DCHECK(annexb_buffer); - offsets_ = - H264::FindNaluIndices(webrtc::MakeArrayView(annexb_buffer, length)); +AnnexBBufferReader::AnnexBBufferReader(ArrayView annexb_buffer) + : buffer_(annexb_buffer) { + offsets_ = H264::FindNaluIndices(annexb_buffer); offset_ = offsets_.begin(); } AnnexBBufferReader::~AnnexBBufferReader() = default; -bool AnnexBBufferReader::ReadNalu(const uint8_t** out_nalu, - size_t* out_length) { - RTC_DCHECK(out_nalu); - RTC_DCHECK(out_length); - *out_nalu = nullptr; - *out_length = 0; - +bool AnnexBBufferReader::ReadNalu(ArrayView& out_nalu) { if (offset_ == offsets_.end()) { return false; } - *out_nalu = start_ + offset_->payload_start_offset; - *out_length = offset_->payload_size; + out_nalu = + buffer_.subview(offset_->payload_start_offset, offset_->payload_size); ++offset_; return true; } @@ -286,7 +284,7 @@ size_t AnnexBBufferReader::BytesRemaining() const { if (offset_ == offsets_.end()) { return 0; } - return length_ - offset_->start_offset; + return buffer_.size() - offset_->start_offset; } void AnnexBBufferReader::SeekToStart() { @@ -297,33 +295,32 @@ bool AnnexBBufferReader::SeekToNextNaluOfType(NaluType type) { for (; offset_ != offsets_.end(); ++offset_) { if (offset_->payload_size < 1) continue; - if (ParseNaluType(*(start_ + offset_->payload_start_offset)) == type) + if (ParseNaluType(buffer_[offset_->payload_start_offset]) == type) return true; } return false; } -AvccBufferWriter::AvccBufferWriter(uint8_t* const avcc_buffer, size_t length) - : start_(avcc_buffer), offset_(0), length_(length) { - RTC_DCHECK(avcc_buffer); -} -bool AvccBufferWriter::WriteNalu(const uint8_t* data, size_t data_size) { +AvccBufferWriter::AvccBufferWriter(ArrayView avcc_buffer) + : buffer_(avcc_buffer) {} + +bool AvccBufferWriter::WriteNalu(ArrayView data) { // Check if we can write this length of data. - if (data_size + kAvccHeaderByteSize > BytesRemaining()) { + if (data.size() + kAvccHeaderByteSize > BytesRemaining()) { return false; } // Write length header, which needs to be big endian. - uint32_t big_endian_length = CFSwapInt32HostToBig(data_size); - memcpy(start_ + offset_, &big_endian_length, sizeof(big_endian_length)); - offset_ += sizeof(big_endian_length); + uint32_t big_endian_length = CFSwapInt32HostToBig(data.size()); + memcpy(buffer_.data(), &big_endian_length, sizeof(big_endian_length)); + buffer_ = buffer_.subview(sizeof(big_endian_length)); // Write data. - memcpy(start_ + offset_, data, data_size); - offset_ += data_size; + memcpy(buffer_.data(), data.data(), data.size()); + buffer_ = buffer_.subview(data.size()); return true; } size_t AvccBufferWriter::BytesRemaining() const { - return length_ - offset_; + return buffer_.size(); } } // namespace webrtc diff --git a/sdk/objc/components/video_codec/nalu_rewriter.h b/sdk/objc/components/video_codec/nalu_rewriter.h index fb1d98ce8d..507aa67a69 100644 --- a/sdk/objc/components/video_codec/nalu_rewriter.h +++ b/sdk/objc/components/video_codec/nalu_rewriter.h @@ -14,10 +14,12 @@ #include +#include +#include #include +#include "api/array_view.h" #include "common_video/h264/h264_common.h" -#include "modules/video_coding/codecs/h264/include/h264.h" #include "rtc_base/buffer.h" using webrtc::H264::NaluIndex; @@ -37,8 +39,7 @@ bool H264CMSampleBufferToAnnexBBuffer(CMSampleBufferRef avcc_sample_buffer, // If `is_keyframe` is true then `video_format` is ignored since the format will // be read from the buffer. Otherwise `video_format` must be provided. // Caller is responsible for releasing the created sample buffer. -bool H264AnnexBBufferToCMSampleBuffer(const uint8_t* annexb_buffer, - size_t annexb_buffer_size, +bool H264AnnexBBufferToCMSampleBuffer(ArrayView annexb_buffer, CMVideoFormatDescriptionRef video_format, CMSampleBufferRef* out_sample_buffer, CMMemoryPoolRef memory_pool); @@ -47,20 +48,19 @@ bool H264AnnexBBufferToCMSampleBuffer(const uint8_t* annexb_buffer, // the Annex B buffer. If there is no such information, nullptr is returned. // The caller is responsible for releasing the description. CMVideoFormatDescriptionRef CreateVideoFormatDescription( - const uint8_t* annexb_buffer, - size_t annexb_buffer_size); + ArrayView annexb_buffer); // Helper class for reading NALUs from an RTP Annex B buffer. class AnnexBBufferReader final { public: - AnnexBBufferReader(const uint8_t* annexb_buffer, size_t length); + explicit AnnexBBufferReader(ArrayView annexb_buffer); ~AnnexBBufferReader(); AnnexBBufferReader(const AnnexBBufferReader& other) = delete; void operator=(const AnnexBBufferReader& other) = delete; // Returns a pointer to the beginning of the next NALU slice without the // header bytes and its length. Returns false if no more slices remain. - bool ReadNalu(const uint8_t** out_nalu, size_t* out_length); + bool ReadNalu(ArrayView& out_nalu); // Returns the number of unread NALU bytes, including the size of the header. // If the buffer has no remaining NALUs this will return zero. @@ -81,31 +81,28 @@ class AnnexBBufferReader final { size_t length, size_t offset) const; - const uint8_t* const start_; + const ArrayView buffer_; std::vector offsets_; std::vector::iterator offset_; - const size_t length_; }; // Helper class for writing NALUs using avcc format into a buffer. class AvccBufferWriter final { public: - AvccBufferWriter(uint8_t* const avcc_buffer, size_t length); + explicit AvccBufferWriter(ArrayView avcc_buffer); ~AvccBufferWriter() {} AvccBufferWriter(const AvccBufferWriter& other) = delete; void operator=(const AvccBufferWriter& other) = delete; // Writes the data slice into the buffer. Returns false if there isn't // enough space left. - bool WriteNalu(const uint8_t* data, size_t data_size); + bool WriteNalu(ArrayView data); // Returns the unused bytes in the buffer. size_t BytesRemaining() const; private: - uint8_t* const start_; - size_t offset_; - const size_t length_; + ArrayView buffer_; }; } // namespace webrtc diff --git a/sdk/objc/unittests/RTCIceCandidateTest.mm b/sdk/objc/unittests/RTCIceCandidateTest.mm index 4cdd317a3c..c000be5a1b 100644 --- a/sdk/objc/unittests/RTCIceCandidateTest.mm +++ b/sdk/objc/unittests/RTCIceCandidateTest.mm @@ -34,7 +34,7 @@ - (void)testCandidate { sdpMLineIndex:0 sdpMid:@"audio"]; - std::unique_ptr nativeCandidate = + std::unique_ptr nativeCandidate = candidate.nativeCandidate; EXPECT_EQ("audio", nativeCandidate->sdp_mid()); EXPECT_EQ(0, nativeCandidate->sdp_mline_index()); @@ -48,7 +48,7 @@ - (void)testInitFromNativeCandidate { std::string sdp("candidate:4025901590 1 udp 2122265343 " "fdff:2642:12a6:fe38:c001:beda:fcf9:51aa " "59052 typ host generation 0"); - std::unique_ptr nativeCandidate( + std::unique_ptr nativeCandidate( webrtc::CreateIceCandidate("audio", 0, sdp, nullptr)); RTC_OBJC_TYPE(RTCIceCandidate) *iceCandidate = diff --git a/sdk/objc/unittests/nalu_rewriter_xctest.mm b/sdk/objc/unittests/nalu_rewriter_xctest.mm index 76a52de474..33b54e4856 100644 --- a/sdk/objc/unittests/nalu_rewriter_xctest.mm +++ b/sdk/objc/unittests/nalu_rewriter_xctest.mm @@ -8,9 +8,9 @@ * be found in the AUTHORS file in the root of the source tree. */ +#include "api/array_view.h" #include "common_video/h264/h264_common.h" #include "components/video_codec/nalu_rewriter.h" -#include "rtc_base/arraysize.h" #include "rtc_base/gunit.h" #import @@ -40,8 +40,7 @@ @implementation NaluRewriterTests - (void)testCreateVideoFormatDescription { CMVideoFormatDescriptionRef description = - webrtc::CreateVideoFormatDescription(SPS_PPS_BUFFER, - arraysize(SPS_PPS_BUFFER)); + webrtc::CreateVideoFormatDescription(SPS_PPS_BUFFER); XCTAssertTrue(description); if (description) { CFRelease(description); @@ -59,8 +58,8 @@ - (void)testCreateVideoFormatDescription { // PPS nalu. 0x00, 0x00, 0x01, 0x28, 0xCE, 0x3C, 0x30}; // clang-format on - description = webrtc::CreateVideoFormatDescription( - sps_pps_not_at_start_buffer, arraysize(sps_pps_not_at_start_buffer)); + description = + webrtc::CreateVideoFormatDescription(sps_pps_not_at_start_buffer); XCTAssertTrue(description); @@ -70,51 +69,38 @@ - (void)testCreateVideoFormatDescription { } const uint8_t other_buffer[] = {0x00, 0x00, 0x00, 0x01, 0x28}; - XCTAssertFalse(webrtc::CreateVideoFormatDescription(other_buffer, - arraysize(other_buffer))); + XCTAssertFalse(webrtc::CreateVideoFormatDescription(other_buffer)); } - (void)testReadEmptyInput { - const uint8_t annex_b_test_data[] = {0x00}; - webrtc::AnnexBBufferReader reader(annex_b_test_data, 0); - const uint8_t* nalu = nullptr; - size_t nalu_length = 0; + webrtc::AnnexBBufferReader reader({}); + webrtc::ArrayView nalu; XCTAssertEqual(0u, reader.BytesRemaining()); - XCTAssertFalse(reader.ReadNalu(&nalu, &nalu_length)); - XCTAssertEqual(nullptr, nalu); - XCTAssertEqual(0u, nalu_length); + XCTAssertFalse(reader.ReadNalu(nalu)); } - (void)testReadSingleNalu { const uint8_t annex_b_test_data[] = {0x00, 0x00, 0x00, 0x01, 0xAA}; - webrtc::AnnexBBufferReader reader(annex_b_test_data, - arraysize(annex_b_test_data)); - const uint8_t* nalu = nullptr; - size_t nalu_length = 0; - XCTAssertEqual(arraysize(annex_b_test_data), reader.BytesRemaining()); - XCTAssertTrue(reader.ReadNalu(&nalu, &nalu_length)); - XCTAssertEqual(annex_b_test_data + 4, nalu); - XCTAssertEqual(1u, nalu_length); + webrtc::AnnexBBufferReader reader(annex_b_test_data); + webrtc::ArrayView nalu; + XCTAssertEqual(std::size(annex_b_test_data), reader.BytesRemaining()); + XCTAssertTrue(reader.ReadNalu(nalu)); + XCTAssertEqual(annex_b_test_data + 4, nalu.data()); + XCTAssertEqual(1u, nalu.size()); XCTAssertEqual(0u, reader.BytesRemaining()); - XCTAssertFalse(reader.ReadNalu(&nalu, &nalu_length)); - XCTAssertEqual(nullptr, nalu); - XCTAssertEqual(0u, nalu_length); + XCTAssertFalse(reader.ReadNalu(nalu)); } - (void)testReadSingleNalu3ByteHeader { const uint8_t annex_b_test_data[] = {0x00, 0x00, 0x01, 0xAA}; - webrtc::AnnexBBufferReader reader(annex_b_test_data, - arraysize(annex_b_test_data)); - const uint8_t* nalu = nullptr; - size_t nalu_length = 0; - XCTAssertEqual(arraysize(annex_b_test_data), reader.BytesRemaining()); - XCTAssertTrue(reader.ReadNalu(&nalu, &nalu_length)); - XCTAssertEqual(annex_b_test_data + 3, nalu); - XCTAssertEqual(1u, nalu_length); + webrtc::AnnexBBufferReader reader(annex_b_test_data); + webrtc::ArrayView nalu; + XCTAssertEqual(std::size(annex_b_test_data), reader.BytesRemaining()); + XCTAssertTrue(reader.ReadNalu(nalu)); + XCTAssertEqual(annex_b_test_data + 3, nalu.data()); + XCTAssertEqual(1u, nalu.size()); XCTAssertEqual(0u, reader.BytesRemaining()); - XCTAssertFalse(reader.ReadNalu(&nalu, &nalu_length)); - XCTAssertEqual(nullptr, nalu); - XCTAssertEqual(0u, nalu_length); + XCTAssertFalse(reader.ReadNalu(nalu)); } - (void)testReadMissingNalu { @@ -123,14 +109,10 @@ - (void)testReadMissingNalu { 0x00, 0x01, 0x00, 0x00, 0x00, 0xFF}; // clang-format on - webrtc::AnnexBBufferReader reader(annex_b_test_data, - arraysize(annex_b_test_data)); - const uint8_t* nalu = nullptr; - size_t nalu_length = 0; + webrtc::AnnexBBufferReader reader(annex_b_test_data); + webrtc::ArrayView nalu; XCTAssertEqual(0u, reader.BytesRemaining()); - XCTAssertFalse(reader.ReadNalu(&nalu, &nalu_length)); - XCTAssertEqual(nullptr, nalu); - XCTAssertEqual(0u, nalu_length); + XCTAssertFalse(reader.ReadNalu(nalu)); } - (void)testReadMultipleNalus { @@ -141,50 +123,37 @@ - (void)testReadMultipleNalus { 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x01, 0xAA, 0xBB}; // clang-format on - webrtc::AnnexBBufferReader reader(annex_b_test_data, - arraysize(annex_b_test_data)); - const uint8_t* nalu = nullptr; - size_t nalu_length = 0; - XCTAssertEqual(arraysize(annex_b_test_data), reader.BytesRemaining()); - XCTAssertTrue(reader.ReadNalu(&nalu, &nalu_length)); - XCTAssertEqual(annex_b_test_data + 4, nalu); - XCTAssertEqual(8u, nalu_length); + webrtc::AnnexBBufferReader reader(annex_b_test_data); + webrtc::ArrayView nalu; + XCTAssertEqual(std::size(annex_b_test_data), reader.BytesRemaining()); + XCTAssertTrue(reader.ReadNalu(nalu)); + XCTAssertEqual(annex_b_test_data + 4, nalu.data()); + XCTAssertEqual(8u, nalu.size()); XCTAssertEqual(5u, reader.BytesRemaining()); - XCTAssertTrue(reader.ReadNalu(&nalu, &nalu_length)); - XCTAssertEqual(annex_b_test_data + 15, nalu); - XCTAssertEqual(2u, nalu_length); + XCTAssertTrue(reader.ReadNalu(nalu)); + XCTAssertEqual(annex_b_test_data + 15, nalu.data()); + XCTAssertEqual(2u, nalu.size()); XCTAssertEqual(0u, reader.BytesRemaining()); - XCTAssertFalse(reader.ReadNalu(&nalu, &nalu_length)); - XCTAssertEqual(nullptr, nalu); - XCTAssertEqual(0u, nalu_length); + XCTAssertFalse(reader.ReadNalu(nalu)); } - (void)testEmptyOutputBuffer { - const uint8_t expected_buffer[] = {0x00}; - const size_t buffer_size = 1; - std::unique_ptr buffer(new uint8_t[buffer_size]); - memset(buffer.get(), 0, buffer_size); - webrtc::AvccBufferWriter writer(buffer.get(), 0); + webrtc::AvccBufferWriter writer({}); XCTAssertEqual(0u, writer.BytesRemaining()); - XCTAssertFalse( - writer.WriteNalu(NALU_TEST_DATA_0, arraysize(NALU_TEST_DATA_0))); - XCTAssertEqual( - 0, memcmp(expected_buffer, buffer.get(), arraysize(expected_buffer))); + XCTAssertFalse(writer.WriteNalu(NALU_TEST_DATA_0)); } - (void)testWriteSingleNalu { const uint8_t expected_buffer[] = {0x00, 0x00, 0x00, 0x03, 0xAA, 0xBB, 0xCC}; - const size_t buffer_size = arraysize(NALU_TEST_DATA_0) + 4; - std::unique_ptr buffer(new uint8_t[buffer_size]); - webrtc::AvccBufferWriter writer(buffer.get(), buffer_size); + constexpr size_t buffer_size = std::size(NALU_TEST_DATA_0) + 4; + uint8_t buffer[buffer_size]; + webrtc::AvccBufferWriter writer(buffer); XCTAssertEqual(buffer_size, writer.BytesRemaining()); - XCTAssertTrue( - writer.WriteNalu(NALU_TEST_DATA_0, arraysize(NALU_TEST_DATA_0))); + XCTAssertTrue(writer.WriteNalu(NALU_TEST_DATA_0)); XCTAssertEqual(0u, writer.BytesRemaining()); - XCTAssertFalse( - writer.WriteNalu(NALU_TEST_DATA_1, arraysize(NALU_TEST_DATA_1))); - XCTAssertEqual( - 0, memcmp(expected_buffer, buffer.get(), arraysize(expected_buffer))); + XCTAssertFalse(writer.WriteNalu(NALU_TEST_DATA_1)); + XCTAssertEqual(0, + memcmp(expected_buffer, buffer, std::size(expected_buffer))); } - (void)testWriteMultipleNalus { @@ -194,34 +163,30 @@ - (void)testWriteMultipleNalus { 0x00, 0x00, 0x00, 0x04, 0xDE, 0xAD, 0xBE, 0xEF }; // clang-format on - const size_t buffer_size = - arraysize(NALU_TEST_DATA_0) + arraysize(NALU_TEST_DATA_1) + 8; - std::unique_ptr buffer(new uint8_t[buffer_size]); - webrtc::AvccBufferWriter writer(buffer.get(), buffer_size); + constexpr size_t buffer_size = + std::size(NALU_TEST_DATA_0) + std::size(NALU_TEST_DATA_1) + 8; + uint8_t buffer[buffer_size]; + webrtc::AvccBufferWriter writer(buffer); XCTAssertEqual(buffer_size, writer.BytesRemaining()); - XCTAssertTrue( - writer.WriteNalu(NALU_TEST_DATA_0, arraysize(NALU_TEST_DATA_0))); - XCTAssertEqual(buffer_size - (arraysize(NALU_TEST_DATA_0) + 4), + XCTAssertTrue(writer.WriteNalu(NALU_TEST_DATA_0)); + XCTAssertEqual(buffer_size - (std::size(NALU_TEST_DATA_0) + 4), writer.BytesRemaining()); - XCTAssertTrue( - writer.WriteNalu(NALU_TEST_DATA_1, arraysize(NALU_TEST_DATA_1))); + XCTAssertTrue(writer.WriteNalu(NALU_TEST_DATA_1)); XCTAssertEqual(0u, writer.BytesRemaining()); - XCTAssertEqual( - 0, memcmp(expected_buffer, buffer.get(), arraysize(expected_buffer))); + XCTAssertEqual(0, + memcmp(expected_buffer, buffer, std::size(expected_buffer))); } - (void)testOverflow { const uint8_t expected_buffer[] = {0x00, 0x00, 0x00}; - const size_t buffer_size = arraysize(NALU_TEST_DATA_0); - std::unique_ptr buffer(new uint8_t[buffer_size]); - memset(buffer.get(), 0, buffer_size); - webrtc::AvccBufferWriter writer(buffer.get(), buffer_size); + constexpr size_t buffer_size = std::size(NALU_TEST_DATA_0); + uint8_t buffer[buffer_size] = {}; + webrtc::AvccBufferWriter writer(buffer); XCTAssertEqual(buffer_size, writer.BytesRemaining()); - XCTAssertFalse( - writer.WriteNalu(NALU_TEST_DATA_0, arraysize(NALU_TEST_DATA_0))); + XCTAssertFalse(writer.WriteNalu(NALU_TEST_DATA_0)); XCTAssertEqual(buffer_size, writer.BytesRemaining()); - XCTAssertEqual( - 0, memcmp(expected_buffer, buffer.get(), arraysize(expected_buffer))); + XCTAssertEqual(0, + memcmp(expected_buffer, buffer, std::size(expected_buffer))); } - (void)testH264AnnexBBufferToCMSampleBuffer { @@ -248,7 +213,6 @@ - (void)testH264AnnexBBufferToCMSampleBuffer { Boolean result = webrtc::H264AnnexBBufferToCMSampleBuffer(annex_b_test_data, - arraysize(annex_b_test_data), description, &out_sample_buffer, memory_pool); @@ -263,10 +227,10 @@ - (void)testH264AnnexBBufferToCMSampleBuffer { CMSampleBufferGetDataBuffer(out_sample_buffer); size_t block_buffer_size = CMBlockBufferGetDataLength(block_buffer); CMBlockBufferGetDataPointer(block_buffer, 0, nullptr, nullptr, &data_ptr); - XCTAssertEqual(block_buffer_size, arraysize(annex_b_test_data)); + XCTAssertEqual(block_buffer_size, std::size(annex_b_test_data)); int data_comparison_result = memcmp( - expected_cmsample_data, data_ptr, arraysize(expected_cmsample_data)); + expected_cmsample_data, data_ptr, std::size(expected_cmsample_data)); XCTAssertEqual(0, data_comparison_result); @@ -294,10 +258,10 @@ - (void)testH264CMSampleBufferToAnnexBBuffer { 0xAA, 0xFF}; // second chunk, 2 bytes // clang-format on - webrtc::Buffer annexb_buffer(arraysize(cmsample_data)); + webrtc::Buffer annexb_buffer(std::size(cmsample_data)); CMSampleBufferRef sample_buffer = [self createCMSampleBufferRef:(void*)cmsample_data - cmsampleSize:arraysize(cmsample_data)]; + cmsampleSize:std::size(cmsample_data)]; Boolean result = webrtc::H264CMSampleBufferToAnnexBBuffer(sample_buffer, @@ -306,13 +270,11 @@ - (void)testH264CMSampleBufferToAnnexBBuffer { XCTAssertTrue(result); - XCTAssertEqual(arraysize(expected_annex_b_data), annexb_buffer.size()); - - int data_comparison_result = memcmp(expected_annex_b_data, - annexb_buffer.data(), - arraysize(expected_annex_b_data)); - - XCTAssertEqual(0, data_comparison_result); + XCTAssertEqual(std::size(expected_annex_b_data), annexb_buffer.size()); + XCTAssertEqual( + 0, + memcmp( + expected_annex_b_data, annexb_buffer.data(), annexb_buffer.size())); } - (void)testH264CMSampleBufferToAnnexBBufferWithKeyframe { @@ -330,10 +292,10 @@ - (void)testH264CMSampleBufferToAnnexBBufferWithKeyframe { 0xAA, 0xFF}; // second chunk, 2 bytes // clang-format on - webrtc::Buffer annexb_buffer(arraysize(cmsample_data)); + webrtc::Buffer annexb_buffer(std::size(cmsample_data)); CMSampleBufferRef sample_buffer = [self createCMSampleBufferRef:(void*)cmsample_data - cmsampleSize:arraysize(cmsample_data)]; + cmsampleSize:std::size(cmsample_data)]; Boolean result = webrtc::H264CMSampleBufferToAnnexBBuffer(sample_buffer, @@ -342,23 +304,22 @@ - (void)testH264CMSampleBufferToAnnexBBufferWithKeyframe { XCTAssertTrue(result); - XCTAssertEqual(arraysize(SPS_PPS_BUFFER) + arraysize(expected_annex_b_data), + XCTAssertEqual(std::size(SPS_PPS_BUFFER) + std::size(expected_annex_b_data), annexb_buffer.size()); XCTAssertEqual( 0, - memcmp(SPS_PPS_BUFFER, annexb_buffer.data(), arraysize(SPS_PPS_BUFFER))); + memcmp(SPS_PPS_BUFFER, annexb_buffer.data(), std::size(SPS_PPS_BUFFER))); XCTAssertEqual(0, memcmp(expected_annex_b_data, - annexb_buffer.data() + arraysize(SPS_PPS_BUFFER), - arraysize(expected_annex_b_data))); + annexb_buffer.data() + std::size(SPS_PPS_BUFFER), + std::size(expected_annex_b_data))); } - (CMVideoFormatDescriptionRef)createDescription { CMVideoFormatDescriptionRef description = - webrtc::CreateVideoFormatDescription(SPS_PPS_BUFFER, - arraysize(SPS_PPS_BUFFER)); + webrtc::CreateVideoFormatDescription(SPS_PPS_BUFFER); XCTAssertTrue(description); return description; } diff --git a/stats/BUILD.gn b/stats/BUILD.gn index 99c554ce10..24a7e3c900 100644 --- a/stats/BUILD.gn +++ b/stats/BUILD.gn @@ -27,7 +27,6 @@ rtc_library("rtc_stats") { "../api:scoped_refptr", "../api/units:timestamp", "../rtc_base:checks", - "../rtc_base:macromagic", "../rtc_base:stringutils", ] } diff --git a/stats/attribute.cc b/stats/attribute.cc index d0b3706b09..ef0c161c1d 100644 --- a/stats/attribute.cc +++ b/stats/attribute.cc @@ -19,7 +19,6 @@ #include #include -#include "rtc_base/arraysize.h" #include "rtc_base/checks.h" #include "rtc_base/string_encode.h" #include "rtc_base/strings/string_builder.h" @@ -64,9 +63,9 @@ struct VisitToString { bool> = true> std::string ValueToString(const T& value) { char buf[32]; - const int len = std::snprintf(&buf[0], arraysize(buf), "%.16g", + const int len = std::snprintf(&buf[0], std::size(buf), "%.16g", static_cast(value)); - RTC_DCHECK_LE(len, arraysize(buf)); + RTC_DCHECK_LE(len, std::ssize(buf)); return std::string(&buf[0], len); } diff --git a/system_wrappers/BUILD.gn b/system_wrappers/BUILD.gn index a1fab28ad8..8222263e1f 100644 --- a/system_wrappers/BUILD.gn +++ b/system_wrappers/BUILD.gn @@ -16,10 +16,8 @@ rtc_library("system_wrappers") { visibility = [ "*" ] sources = [ "include/clock.h", - "include/cpu_features_wrapper.h", "include/ntp_time.h", "source/clock.cc", - "source/cpu_features.cc", ] defines = [] @@ -27,39 +25,14 @@ rtc_library("system_wrappers") { deps = [ "../api:array_view", "../api/units:timestamp", - "../modules:module_api_public", "../rtc_base:checks", "../rtc_base:logging", + "../rtc_base:rtc_numerics", "../rtc_base:safe_conversions", "../rtc_base:timeutils", "../rtc_base/synchronization:mutex", - "../rtc_base/system:arch", "../rtc_base/system:rtc_export", ] - - if (is_android) { - if (build_with_mozilla) { - include_dirs = [ - "/config/external/nspr", - "/nsprpub/lib/ds", - "/nsprpub/pr/include", - ] - } else { - sources += [ "source/cpu_features_android.cc" ] - deps += [ "//third_party/cpu_features:ndk_compat" ] - } - - libs += [ "log" ] - } - - if (is_linux || is_chromeos) { - if (!build_with_chromium) { - sources += [ "source/cpu_features_linux.cc" ] - } - - libs += [ "rt" ] - } - if (is_win) { libs += [ "winmm.lib" ] @@ -67,8 +40,6 @@ rtc_library("system_wrappers") { # webrtc/rtc_base/win32.h in source/clock.cc. deps += [ "../rtc_base:win32" ] } - - deps += [ "../rtc_base:rtc_numerics" ] } rtc_library("field_trial") { diff --git a/system_wrappers/include/cpu_features_wrapper.h b/system_wrappers/include/cpu_features_wrapper.h deleted file mode 100644 index d73b12abe8..0000000000 --- a/system_wrappers/include/cpu_features_wrapper.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2011 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 SYSTEM_WRAPPERS_INCLUDE_CPU_FEATURES_WRAPPER_H_ -#define SYSTEM_WRAPPERS_INCLUDE_CPU_FEATURES_WRAPPER_H_ - -#include - -namespace webrtc { - -// List of features in x86. -typedef enum { kSSE2, kSSE3, kAVX2, kFMA3 } CPUFeature; - -// List of features in ARM. -enum { - kCPUFeatureARMv7 = (1 << 0), - kCPUFeatureVFPv3 = (1 << 1), - kCPUFeatureNEON = (1 << 2), - kCPUFeatureLDREXSTREX = (1 << 3) -}; - -// Returns true if the CPU supports the feature. -int GetCPUInfo(CPUFeature feature); - -// Return the features in an ARM device. -// It detects the features in the hardware platform, and returns supported -// values in the above enum definition as a bitmask. -uint64_t GetCPUFeaturesARM(void); - -} // namespace webrtc - -#endif // SYSTEM_WRAPPERS_INCLUDE_CPU_FEATURES_WRAPPER_H_ diff --git a/system_wrappers/include/ntp_time.h b/system_wrappers/include/ntp_time.h index c1990362bd..5b7e023d63 100644 --- a/system_wrappers/include/ntp_time.h +++ b/system_wrappers/include/ntp_time.h @@ -65,7 +65,7 @@ inline bool operator!=(const NtpTime& n1, const NtpTime& n2) { // Converts `int64_t` milliseconds to Q32.32-formatted fixed-point seconds. // Performs clamping if the result overflows or underflows. inline int64_t Int64MsToQ32x32(int64_t milliseconds) { - // TODO(bugs.webrtc.org/10893): Change to use `webrtc::saturated_cast` once + // TODO(bugs.webrtc.org/10893): Change to use `saturated_cast` once // the bug has been fixed. double result = std::round(milliseconds * (NtpTime::kFractionsPerSecond / 1000.0)); @@ -88,7 +88,7 @@ inline int64_t Int64MsToQ32x32(int64_t milliseconds) { // Converts `int64_t` milliseconds to UQ32.32-formatted fixed-point seconds. // Performs clamping if the result overflows or underflows. inline uint64_t Int64MsToUQ32x32(int64_t milliseconds) { - // TODO(bugs.webrtc.org/10893): Change to use `webrtc::saturated_cast` once + // TODO(bugs.webrtc.org/10893): Change to use `saturated_cast` once // the bug has been fixed. double result = std::round(milliseconds * (NtpTime::kFractionsPerSecond / 1000.0)); diff --git a/system_wrappers/source/cpu_features.cc b/system_wrappers/source/cpu_features.cc deleted file mode 100644 index 3050ad8f09..0000000000 --- a/system_wrappers/source/cpu_features.cc +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright (c) 2011 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. - */ - -// Parts of this file derived from Chromium's base/cpu.cc. - -#include "rtc_base/system/arch.h" -#include "system_wrappers/include/cpu_features_wrapper.h" - -#if defined(WEBRTC_ARCH_X86_FAMILY) && defined(_MSC_VER) -#include -#endif - -namespace webrtc { - -#if defined(WEBRTC_ARCH_X86_FAMILY) - -#if defined(WEBRTC_ENABLE_AVX2) -// xgetbv returns the value of an Intel Extended Control Register (XCR). -// Currently only XCR0 is defined by Intel so `xcr` should always be zero. -static uint64_t xgetbv(uint32_t xcr) { -#if defined(_MSC_VER) - return _xgetbv(xcr); -#else - uint32_t eax, edx; - - __asm__ volatile("xgetbv" : "=a"(eax), "=d"(edx) : "c"(xcr)); - return (static_cast(edx) << 32) | eax; -#endif // _MSC_VER -} -#endif // WEBRTC_ENABLE_AVX2 - -#ifndef _MSC_VER -// Intrinsic for "cpuid". -#if defined(__pic__) && defined(__i386__) -static inline void __cpuid(int cpu_info[4], int info_type) { - __asm__ volatile( - "mov %%ebx, %%edi\n" - "cpuid\n" - "xchg %%edi, %%ebx\n" - : "=a"(cpu_info[0]), "=D"(cpu_info[1]), "=c"(cpu_info[2]), - "=d"(cpu_info[3]) - : "a"(info_type)); -} -#else -static inline void __cpuid(int cpu_info[4], int info_type) { - __asm__ volatile("cpuid\n" - : "=a"(cpu_info[0]), "=b"(cpu_info[1]), "=c"(cpu_info[2]), - "=d"(cpu_info[3]) - : "a"(info_type), "c"(0)); -} -#endif -#endif // _MSC_VER -#endif // WEBRTC_ARCH_X86_FAMILY - -#if defined(WEBRTC_ARCH_X86_FAMILY) -// Actual feature detection for x86. -int GetCPUInfo(CPUFeature feature) { - int cpu_info[4]; - __cpuid(cpu_info, 1); - if (feature == kSSE2) { - return 0 != (cpu_info[3] & 0x04000000); - } - if (feature == kSSE3) { - return 0 != (cpu_info[2] & 0x00000001); - } -#if defined(WEBRTC_ENABLE_AVX2) - if (feature == kAVX2) { - int cpu_info7[4]; - __cpuid(cpu_info7, 0); - int num_ids = cpu_info7[0]; - if (num_ids < 7) { - return 0; - } - // Interpret CPU feature information. - __cpuid(cpu_info7, 7); - - // AVX instructions can be used when - // a) AVX are supported by the CPU, - // b) XSAVE is supported by the CPU, - // c) XSAVE is enabled by the kernel. - // Compiling with MSVC and /arch:AVX2 surprisingly generates BMI2 - // instructions (see crbug.com/1315519). - return (cpu_info[2] & 0x10000000) != 0 /* AVX */ && - (cpu_info[2] & 0x04000000) != 0 /* XSAVE */ && - (cpu_info[2] & 0x08000000) != 0 /* OSXSAVE */ && - (xgetbv(0) & 0x00000006) == 6 /* XSAVE enabled by kernel */ && - (cpu_info7[1] & 0x00000020) != 0 /* AVX2 */ && - (cpu_info7[1] & 0x00000100) != 0 /* BMI2 */; - } -#endif // WEBRTC_ENABLE_AVX2 - if (feature == kFMA3) { - return 0 != (cpu_info[2] & 0x00001000); - } - return 0; -} -#else -// Default to straight C for other platforms. -int GetCPUInfo(CPUFeature feature) { - (void)feature; - return 0; -} -#endif - -} // namespace webrtc diff --git a/system_wrappers/source/cpu_features_android.cc b/system_wrappers/source/cpu_features_android.cc deleted file mode 100644 index 95cc609b09..0000000000 --- a/system_wrappers/source/cpu_features_android.cc +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright (c) 2012 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 - -namespace webrtc { - -uint64_t GetCPUFeaturesARM(void) { - return android_getCpuFeatures(); -} - -} // namespace webrtc diff --git a/system_wrappers/source/cpu_features_linux.cc b/system_wrappers/source/cpu_features_linux.cc deleted file mode 100644 index 2d79dde111..0000000000 --- a/system_wrappers/source/cpu_features_linux.cc +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (c) 2016 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 -#include -#include - -#ifdef __GLIBC_PREREQ -#define WEBRTC_GLIBC_PREREQ(a, b) __GLIBC_PREREQ(a, b) -#else -#define WEBRTC_GLIBC_PREREQ(a, b) 0 -#endif - -#if WEBRTC_GLIBC_PREREQ(2, 16) -#include -#else -#include -#include -#include -#include -#endif - -#include "rtc_base/system/arch.h" -#include "system_wrappers/include/cpu_features_wrapper.h" - -#if defined(WEBRTC_ARCH_ARM_FAMILY) -#include - -namespace webrtc { - -uint64_t GetCPUFeaturesARM(void) { - uint64_t result = 0; - int architecture = 0; - uint64_t hwcap = 0; - const char* platform = NULL; -#if WEBRTC_GLIBC_PREREQ(2, 16) - hwcap = getauxval(AT_HWCAP); - platform = (const char*)getauxval(AT_PLATFORM); -#else - ElfW(auxv_t) auxv; - int fd = open("/proc/self/auxv", O_RDONLY); - if (fd >= 0) { - while (hwcap == 0 || platform == NULL) { - if (read(fd, &auxv, sizeof(auxv)) < (ssize_t)sizeof(auxv)) { - if (errno == EINTR) - continue; - break; - } - switch (auxv.a_type) { - case AT_HWCAP: - hwcap = auxv.a_un.a_val; - break; - case AT_PLATFORM: - platform = (const char*)auxv.a_un.a_val; - break; - } - } - close(fd); - } -#endif // WEBRTC_GLIBC_PREREQ(2, 16) -#if defined(__aarch64__) - (void)platform; - architecture = 8; - if ((hwcap & HWCAP_FP) != 0) - result |= kCPUFeatureVFPv3; - if ((hwcap & HWCAP_ASIMD) != 0) - result |= kCPUFeatureNEON; -#else - if (platform != NULL) { - /* expect a string in the form "v6l" or "v7l", etc. - */ - if (platform[0] == 'v' && '0' <= platform[1] && platform[1] <= '9' && - (platform[2] == 'l' || platform[2] == 'b')) { - architecture = platform[1] - '0'; - } - } - if ((hwcap & HWCAP_VFPv3) != 0) - result |= kCPUFeatureVFPv3; - if ((hwcap & HWCAP_NEON) != 0) - result |= kCPUFeatureNEON; -#endif - if (architecture >= 7) - result |= kCPUFeatureARMv7; - if (architecture >= 6) - result |= kCPUFeatureLDREXSTREX; - return result; -} - -} // namespace webrtc -#endif // WEBRTC_ARCH_ARM_FAMILY diff --git a/system_wrappers/source/metrics.cc b/system_wrappers/source/metrics.cc index bf39770f99..e90d541599 100644 --- a/system_wrappers/source/metrics.cc +++ b/system_wrappers/source/metrics.cc @@ -197,7 +197,7 @@ class RtcHistogramMap { // The histogram getter functions, which return pointer values to the histograms // in the map, are cached in WebRTC. Therefore, this memory is not freed by the // application (the memory will be reclaimed by the OS). -static std::atomic g_rtc_histogram_map(nullptr); +std::atomic g_rtc_histogram_map(nullptr); void CreateMap() { RtcHistogramMap* map = g_rtc_histogram_map.load(std::memory_order_acquire); @@ -211,7 +211,7 @@ void CreateMap() { // Set the first time we start using histograms. Used to make sure Enable() is // not called thereafter. #if RTC_DCHECK_IS_ON -static std::atomic g_rtc_histogram_called(0); +std::atomic g_rtc_histogram_called(0); #endif // Gets the map (or nullptr). diff --git a/test/BUILD.gn b/test/BUILD.gn index 85e65b3785..61c56738f6 100644 --- a/test/BUILD.gn +++ b/test/BUILD.gn @@ -55,6 +55,7 @@ rtc_library("frame_generator_impl") { "../api:scoped_refptr", "../api:sequence_checker", "../api/environment", + "../api/units:time_delta", "../api/video:encoded_image", "../api/video:video_frame", "../api/video:video_frame_i010", @@ -71,6 +72,7 @@ rtc_library("frame_generator_impl") { "../rtc_base:checks", "../rtc_base:criticalsection", "../rtc_base:logging", + "../rtc_base:macromagic", "../rtc_base:random", "../rtc_base:rtc_event", "../rtc_base/synchronization:mutex", @@ -122,6 +124,7 @@ rtc_library("test_video_capturer") { "../api/video:video_rtp_headers", "../media:video_adapter", "../media:video_broadcaster", + "../rtc_base:macromagic", "../rtc_base/synchronization:mutex", ] } @@ -146,6 +149,22 @@ rtc_library("create_frame_generator_capturer") { ] } +rtc_library("create_test_field_trials") { + testonly = true + sources = [ "create_test_field_trials.h" ] + deps = [ + "../api:field_trials", + "//third_party/abseil-cpp/absl/strings:string_view", + ] + + if (build_with_chromium) { + sources += [ "create_test_field_trials_without_absl_flag.cc" ] + } else { + sources += [ "create_test_field_trials.cc" ] + deps += [ "//third_party/abseil-cpp/absl/flags:flag" ] + } +} + rtc_library("frame_generator_capturer") { visibility = [ "*" ] testonly = true @@ -196,17 +215,24 @@ rtc_library("video_test_common") { ":test_video_capturer", "../api:array_view", "../api:create_frame_generator", + "../api:fec_controller_api", "../api:frame_generator_api", + "../api:make_ref_counted", "../api:scoped_refptr", "../api/environment", "../api/task_queue", + "../api/units:data_rate", + "../api/video:encoded_image", + "../api/video:render_resolution", "../api/video:video_frame", + "../api/video:video_frame_type", "../api/video:video_rtp_headers", "../api/video_codecs:video_codecs_api", "../common_video", "../rtc_base:checks", "../rtc_base:criticalsection", "../rtc_base:logging", + "../rtc_base:macromagic", "../rtc_base:refcount", "../rtc_base:timeutils", "../rtc_base/synchronization:mutex", @@ -246,6 +272,7 @@ if (!build_with_chromium) { "../api:libjingle_peerconnection_api", "../api:media_stream_interface", "../api:scoped_refptr", + "../api/video:video_frame", "../modules/video_capture:video_capture_module", "../rtc_base:logging", "../rtc_base:threading", @@ -266,6 +293,8 @@ if (!build_with_chromium) { deps = [ ":test_video_capturer", ":video_test_common", + "../api/video:video_frame", + "../common_video", "//third_party/abseil-cpp/absl/memory", ] if (is_mac || is_ios) { @@ -366,6 +395,7 @@ rtc_library("perf_test") { "../rtc_base:checks", "../rtc_base:criticalsection", "../rtc_base:logging", + "../rtc_base:macromagic", "../rtc_base:rtc_numerics", "../rtc_base:stringutils", "../rtc_base/synchronization:mutex", @@ -485,6 +515,7 @@ rtc_library("fixed_fps_video_frame_writer_adapter") { ":video_frame_writer", "../api/test/video:video_frame_writer", "../api/units:time_delta", + "../api/units:timestamp", "../api/video:video_frame", "../rtc_base:checks", "../system_wrappers", @@ -553,6 +584,7 @@ rtc_library("video_test_support") { "../rtc_base:rtc_event", "../rtc_base:stringutils", "../rtc_base/system:file_wrapper", + "//third_party/abseil-cpp/absl/strings:string_view", ] } @@ -675,9 +707,12 @@ if (rtc_include_tests) { ":fixed_fps_video_frame_writer_adapter", ":test_support", ":video_frame_writer", + "../api:time_controller", + "../api/test/video:video_frame_writer", "../api/units:time_delta", "../api/units:timestamp", "../api/video:video_frame", + "../rtc_base:macromagic", "../rtc_base/synchronization:mutex", "time_controller", ] @@ -688,6 +723,7 @@ if (rtc_include_tests) { ":call_config_utils", ":copy_to_file_audio_capturer_unittest", ":create_frame_generator_capturer", + ":create_test_field_trials", ":direct_transport", ":fake_video_codecs", ":fileutils", @@ -713,17 +749,21 @@ if (rtc_include_tests) { "../api:create_frame_generator", "../api:create_simulcast_test_fixture_api", "../api:create_time_controller", + "../api:field_trials", "../api:frame_generator_api", "../api:mock_video_codec_factory", "../api:mock_video_decoder", "../api:mock_video_encoder", "../api:rtc_error", "../api:rtc_error_matchers", + "../api:rtp_headers", + "../api:rtp_parameters", "../api:scoped_refptr", "../api:simulcast_test_fixture_api", "../api:time_controller", "../api/environment", "../api/environment:environment_factory", + "../api/numerics", "../api/task_queue", "../api/task_queue:task_queue_test", "../api/test/video:function_video_factory", @@ -734,6 +774,8 @@ if (rtc_include_tests) { "../api/units:time_delta", "../api/units:timestamp", "../api/video:encoded_image", + "../api/video:resolution", + "../api/video:video_bitrate_allocation", "../api/video:video_frame", "../api/video:video_frame_type", "../api/video_codecs:builtin_video_decoder_factory", @@ -752,7 +794,9 @@ if (rtc_include_tests) { "../modules/video_coding:webrtc_vp8", "../modules/video_coding:webrtc_vp9", "../modules/video_coding/svc:scalability_mode_util", + "../rtc_base:checks", "../rtc_base:criticalsection", + "../rtc_base:macromagic", "../rtc_base:rtc_base_tests_utils", "../rtc_base:rtc_event", "../rtc_base:threading", @@ -773,6 +817,7 @@ if (rtc_include_tests) { ] sources = [ "call_config_utils_unittest.cc", + "create_test_field_trials_unittest.cc", "direct_transport_unittest.cc", "fake_vp8_encoder_unittest.cc", "frame_generator_capturer_unittest.cc", @@ -890,7 +935,6 @@ rtc_library("fileutils_override_impl") { deps = [ ":fileutils_override_api", "../rtc_base:checks", - "../rtc_base:macromagic", "../rtc_base:stringutils", "//third_party/abseil-cpp/absl/strings:string_view", ] @@ -1001,9 +1045,12 @@ rtc_library("fake_video_codecs") { "../api:sequence_checker", "../api/environment", "../api/task_queue", + "../api/units:time_delta", "../api/video:encoded_image", "../api/video:video_bitrate_allocation", + "../api/video:video_codec_constants", "../api/video:video_frame", + "../api/video:video_frame_type", "../api/video:video_rtp_headers", "../api/video_codecs:video_codecs_api", "../api/video_codecs:vp8_temporal_layers_factory", @@ -1040,7 +1087,10 @@ rtc_library("encoder_settings") { "encoder_settings.h", ] deps = [ + "../api:field_trials_view", + "../api:make_ref_counted", "../api:scoped_refptr", + "../api/video:video_frame", "../api/video_codecs:video_codecs_api", "../call:rtp_interfaces", "../call:video_receive_stream_api", @@ -1065,6 +1115,9 @@ rtc_library("run_loop") { ] deps = [ "../api/task_queue", + "../api/units:time_delta", + "../rtc_base:socket", + "../rtc_base:socket_server", "../rtc_base:threading", "../rtc_base:timeutils", "//third_party/abseil-cpp/absl/functional:any_invocable", @@ -1193,6 +1246,10 @@ rtc_library("audio_codec_mocks") { "../api/audio_codecs:audio_codecs_api", "../api/audio_codecs:builtin_audio_decoder_factory", "../api/environment", + "../api/units:data_rate", + "../api/units:time_delta", + "../rtc_base:buffer", + "../rtc_base:checks", ] } @@ -1219,6 +1276,7 @@ if (!build_with_chromium) { ":fileutils", ":test_support", "../modules/audio_device:test_audio_device_module", + "../rtc_base:buffer", ] } @@ -1228,7 +1286,14 @@ if (!build_with_chromium) { "test_flags.cc", "test_flags.h", ] - deps = [ "//third_party/abseil-cpp/absl/flags:flag" ] + + # TODO: bugs.webrtc.org/419453427 - remove dependency on + # `create_test_field_trials` when force_fieldtrials flags declaration + # is removed from the header. + deps = [ + ":create_test_field_trials", + "//third_party/abseil-cpp/absl/flags:flag", + ] } rtc_library("test_common") { @@ -1260,13 +1325,16 @@ if (!build_with_chromium) { "..//test/network:simulated_network", "../api:array_view", "../api:create_frame_generator", + "../api:fec_controller_api", "../api:frame_generator_api", + "../api:network_state_predictor_api", "../api:rtp_headers", "../api:rtp_parameters", "../api:scoped_refptr", "../api:simulated_network_api", "../api:transport_api", "../api/audio:audio_device", + "../api/audio:audio_processing", "../api/audio:builtin_audio_processing_builder", "../api/audio_codecs:audio_codecs_api", "../api/audio_codecs:builtin_audio_decoder_factory", @@ -1278,7 +1346,9 @@ if (!build_with_chromium) { "../api/test/video:function_video_factory", "../api/transport:bitrate_settings", "../api/transport:field_trial_based_config", + "../api/transport:network_control", "../api/units:time_delta", + "../api/units:timestamp", "../api/video:builtin_video_bitrate_allocator_factory", "../api/video:video_bitrate_allocator_factory", "../api/video:video_frame", @@ -1287,6 +1357,7 @@ if (!build_with_chromium) { "../call", "../call:call_interfaces", "../call:fake_network", + "../call:rtp_interfaces", "../call:simulated_packet_receiver", "../call:video_receive_stream_api", "../call:video_send_stream_api", @@ -1303,9 +1374,9 @@ if (!build_with_chromium) { "../rtc_base:threading", "../rtc_base:timeutils", "../system_wrappers", - "../system_wrappers:field_trial", "../video/config:encoder_config", "//third_party/abseil-cpp/absl/flags:flag", + "//third_party/abseil-cpp/absl/strings:string_view", ] if (!is_android && !build_with_chromium) { deps += [ "../modules/video_capture:video_capture_internal_impl" ] @@ -1367,7 +1438,11 @@ rtc_library("call_config_utils") { "call_config_utils.h", ] deps = [ + "../api:rtp_headers", + "../api:transport_api", + "../api/video_codecs:video_codecs_api", "../call:video_receive_stream_api", + "../rtc_base:checks", "../rtc_base:rtc_json", ] } @@ -1381,10 +1456,12 @@ rtc_library("fake_encoded_frame") { deps = [ ":test_support", "../api:rtp_packet_info", + "../api/units:timestamp", "../api/video:encoded_frame", "../api/video:encoded_image", "../api/video:video_frame_type", "../api/video:video_rtp_headers", + "../rtc_base:checks", ] } @@ -1440,7 +1517,6 @@ rtc_library("video_codec_tester") { "../rtc_base:timeutils", "../rtc_base/synchronization:mutex", "../rtc_base/system:file_wrapper", - "../test:fileutils", "../video/config:encoder_config", "../video/config:streams_config", "//third_party/abseil-cpp/absl/functional:any_invocable", diff --git a/test/android/native_test_util.cc b/test/android/native_test_util.cc index 529ffbe651..31cb564d2e 100644 --- a/test/android/native_test_util.cc +++ b/test/android/native_test_util.cc @@ -16,8 +16,8 @@ #include "test/android/native_test_util.h" #include -#include +#include #include #include diff --git a/test/call_config_utils.cc b/test/call_config_utils.cc index ff586821f7..c6349bb622 100644 --- a/test/call_config_utils.cc +++ b/test/call_config_utils.cc @@ -13,6 +13,13 @@ #include #include +#include "api/call/transport.h" +#include "api/rtp_headers.h" +#include "api/video_codecs/sdp_video_format.h" +#include "call/video_receive_stream.h" +#include "rtc_base/checks.h" +#include "rtc_base/strings/json.h" + namespace webrtc { namespace test { diff --git a/test/call_config_utils.h b/test/call_config_utils.h index 97cfdc3396..72ba67168b 100644 --- a/test/call_config_utils.h +++ b/test/call_config_utils.h @@ -11,6 +11,7 @@ #ifndef TEST_CALL_CONFIG_UTILS_H_ #define TEST_CALL_CONFIG_UTILS_H_ +#include "api/call/transport.h" #include "call/video_receive_stream.h" #include "rtc_base/strings/json.h" diff --git a/test/call_config_utils_unittest.cc b/test/call_config_utils_unittest.cc index 46ebf18e78..8c9598e41b 100644 --- a/test/call_config_utils_unittest.cc +++ b/test/call_config_utils_unittest.cc @@ -10,6 +10,7 @@ #include "test/call_config_utils.h" +#include "api/rtp_headers.h" #include "call/video_receive_stream.h" #include "test/gtest.h" diff --git a/test/call_test.cc b/test/call_test.cc index 4d55cde9ef..9f6f5b911f 100644 --- a/test/call_test.cc +++ b/test/call_test.cc @@ -20,6 +20,7 @@ #include #include +#include "absl/strings/string_view.h" #include "api/audio/audio_device.h" #include "api/audio/builtin_audio_processing_builder.h" #include "api/audio_codecs/audio_decoder_factory.h" @@ -65,15 +66,15 @@ #include "test/gtest.h" #include "test/network/simulated_network.h" #include "test/rtp_rtcp_observer.h" -#include "test/testsupport/file_utils.h" #include "test/video_test_constants.h" #include "video/config/video_encoder_config.h" namespace webrtc { namespace test { -CallTest::CallTest() - : env_(CreateEnvironment(&field_trials_)), +CallTest::CallTest(absl::string_view field_trials) + : field_trials_(field_trials), + env_(CreateEnvironment(&field_trials_)), send_env_(env_), recv_env_(env_), audio_send_config_(/*send_transport=*/nullptr), diff --git a/test/call_test.h b/test/call_test.h index 37c27c8429..d8cae8c452 100644 --- a/test/call_test.h +++ b/test/call_test.h @@ -10,35 +10,57 @@ #ifndef TEST_CALL_TEST_H_ #define TEST_CALL_TEST_H_ +#include +#include #include #include #include #include #include +#include "absl/strings/string_view.h" #include "api/array_view.h" #include "api/audio/audio_device.h" +#include "api/audio/audio_processing.h" +#include "api/audio_codecs/audio_decoder_factory.h" +#include "api/audio_codecs/audio_encoder_factory.h" +#include "api/call/transport.h" #include "api/environment/environment.h" +#include "api/fec_controller.h" +#include "api/media_types.h" +#include "api/network_state_predictor.h" #include "api/rtc_event_log/rtc_event_log.h" +#include "api/rtp_parameters.h" +#include "api/scoped_refptr.h" #include "api/task_queue/task_queue_base.h" -#include "api/task_queue/task_queue_factory.h" #include "api/test/simulated_network.h" #include "api/test/video/function_video_decoder_factory.h" #include "api/test/video/function_video_encoder_factory.h" +#include "api/transport/bitrate_settings.h" +#include "api/transport/network_control.h" #include "api/units/time_delta.h" #include "api/video/video_bitrate_allocator_factory.h" +#include "api/video/video_rotation.h" +#include "api/video_codecs/video_decoder_factory.h" +#include "call/audio_receive_stream.h" +#include "call/audio_send_stream.h" #include "call/call.h" +#include "call/call_config.h" +#include "call/flexfec_receive_stream.h" +#include "call/rtp_packet_sink_interface.h" +#include "call/video_receive_stream.h" +#include "call/video_send_stream.h" #include "modules/audio_device/include/test_audio_device.h" -#include "test/encoder_settings.h" -#include "test/fake_decoder.h" +#include "modules/rtp_rtcp/source/rtp_packet_received.h" +#include "system_wrappers/include/clock.h" #include "test/fake_videorenderer.h" -#include "test/fake_vp8_encoder.h" #include "test/frame_generator_capturer.h" +#include "test/gtest.h" #include "test/rtp_rtcp_observer.h" #include "test/run_loop.h" #include "test/scoped_key_value_config.h" #include "test/test_video_capturer.h" -#include "test/video_test_constants.h" +#include "video/config/video_encoder_config.h" namespace webrtc { namespace test { @@ -47,7 +69,7 @@ class BaseTest; class CallTest : public ::testing::Test, public RtpPacketSinkInterface { public: - CallTest(); + explicit CallTest(absl::string_view field_trials = ""); virtual ~CallTest(); static const std::map payload_type_map_; diff --git a/test/configurable_frame_size_encoder.cc b/test/configurable_frame_size_encoder.cc index 51274f49db..3bd3b5b349 100644 --- a/test/configurable_frame_size_encoder.cc +++ b/test/configurable_frame_size_encoder.cc @@ -10,16 +10,21 @@ #include "test/configurable_frame_size_encoder.h" -#include - #include -#include +#include +#include #include +#include +#include "api/fec_controller_override.h" #include "api/video/encoded_image.h" +#include "api/video/video_codec_type.h" +#include "api/video/video_frame.h" +#include "api/video/video_frame_type.h" +#include "api/video_codecs/video_codec.h" +#include "api/video_codecs/video_encoder.h" #include "modules/video_coding/include/video_codec_interface.h" #include "modules/video_coding/include/video_error_codes.h" -#include "rtc_base/checks.h" namespace webrtc { namespace test { diff --git a/test/configurable_frame_size_encoder.h b/test/configurable_frame_size_encoder.h index 1fa032a61b..bc90efbc99 100644 --- a/test/configurable_frame_size_encoder.h +++ b/test/configurable_frame_size_encoder.h @@ -15,15 +15,15 @@ #include #include -#include #include #include -#include "api/video/video_bitrate_allocation.h" +#include "api/fec_controller_override.h" +#include "api/video/video_codec_type.h" #include "api/video/video_frame.h" +#include "api/video/video_frame_type.h" #include "api/video_codecs/video_codec.h" #include "api/video_codecs/video_encoder.h" -#include "modules/video_coding/include/video_codec_interface.h" namespace webrtc { namespace test { diff --git a/test/create_frame_generator_capturer.cc b/test/create_frame_generator_capturer.cc index 0eb2e69265..7268ca8198 100644 --- a/test/create_frame_generator_capturer.cc +++ b/test/create_frame_generator_capturer.cc @@ -22,6 +22,7 @@ #include "api/units/time_delta.h" #include "rtc_base/checks.h" #include "system_wrappers/include/clock.h" +#include "test/frame_generator_capturer.h" #include "test/testsupport/file_utils.h" namespace webrtc { diff --git a/test/create_test_field_trials.cc b/test/create_test_field_trials.cc new file mode 100644 index 0000000000..f95e9a1431 --- /dev/null +++ b/test/create_test_field_trials.cc @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2025 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 "test/create_test_field_trials.h" + +#include + +#include "absl/flags/flag.h" +#include "absl/strings/string_view.h" +#include "api/field_trials.h" + +ABSL_FLAG(std::string, + force_fieldtrials, + "", + "Field trials control experimental feature code which can be forced. " + "E.g. running with --force_fieldtrials=WebRTC-FooFeature/Enable/" + " will assign the group Enable to field trial WebRTC-FooFeature."); + +namespace webrtc { + +FieldTrials CreateTestFieldTrials(absl::string_view s) { + FieldTrials result(absl::GetFlag(FLAGS_force_fieldtrials)); + result.Merge(FieldTrials(s)); + return result; +} + +} // namespace webrtc diff --git a/test/create_test_field_trials.h b/test/create_test_field_trials.h new file mode 100644 index 0000000000..10e40f595f --- /dev/null +++ b/test/create_test_field_trials.h @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2025 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 TEST_CREATE_TEST_FIELD_TRIALS_H_ +#define TEST_CREATE_TEST_FIELD_TRIALS_H_ + +#include "absl/strings/string_view.h" +#include "api/field_trials.h" + +namespace webrtc { + +// Creates field trials from command line flag --force_fieldtrials +// and passed field trial string. Field trials in the `s` take priority over +// the command line flag. +// Crashes if command line flag or the `s` are not a valid field trial string. +// +// The intention of this function is to be the default source of field trials +// in tests so that tests always use the command line flag. +FieldTrials CreateTestFieldTrials(absl::string_view s = ""); + +} // namespace webrtc + +#endif // TEST_CREATE_TEST_FIELD_TRIALS_H_ diff --git a/test/create_test_field_trials_unittest.cc b/test/create_test_field_trials_unittest.cc new file mode 100644 index 0000000000..661cc0659b --- /dev/null +++ b/test/create_test_field_trials_unittest.cc @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2025 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 "test/create_test_field_trials.h" + +#include + +#include "absl/flags/declare.h" +#include "absl/flags/flag.h" +#include "absl/strings/string_view.h" +#include "api/field_trials.h" +#include "test/gtest.h" + +// Declare but do not explicitly include the definition of this flag as +// `CreateTestFieldTrials` has to depend on the definition of this flag. +ABSL_DECLARE_FLAG(std::string, force_fieldtrials); + +namespace webrtc { +namespace { + +// Flags are globals. To prevent altering behavior of other tests in the same +// binary when --force_fieldtrials flag is used, ensure flag is reset to the +// previous value after unit tests here runs. +class ScopedSetFlag { + public: + explicit ScopedSetFlag(absl::string_view value) { + old_value_ = absl::GetFlag(FLAGS_force_fieldtrials); + absl::SetFlag(&FLAGS_force_fieldtrials, value); + } + + ~ScopedSetFlag() { absl::SetFlag(&FLAGS_force_fieldtrials, old_value_); } + + private: + std::string old_value_; +}; + +TEST(CreateTestFieldTrialsTest, UsesCommandLineFlag) { + ScopedSetFlag override_flag("Trial1/Value1/Trial2/Value2/"); + FieldTrials field_trials = CreateTestFieldTrials(); + + field_trials.RegisterKeysForTesting({"Trial1", "Trial2"}); + EXPECT_EQ(field_trials.Lookup("Trial1"), "Value1"); + EXPECT_EQ(field_trials.Lookup("Trial2"), "Value2"); +} + +TEST(CreateTestFieldTrialsTest, UsesConstructionParameter) { + FieldTrials field_trials = + CreateTestFieldTrials("Trial1/Value1/Trial2/Value2/"); + + field_trials.RegisterKeysForTesting({"Trial1", "Trial2"}); + EXPECT_EQ(field_trials.Lookup("Trial1"), "Value1"); + EXPECT_EQ(field_trials.Lookup("Trial2"), "Value2"); +} + +TEST(CreateTestFieldTrialsTest, + ConstructionParameterTakesPrecedenceOverCommandLine) { + ScopedSetFlag override_flag("TrialCommon/ValueF/TrialFlag/FlagValue/"); + FieldTrials field_trials = CreateTestFieldTrials( + "TrialCommon/ValueC/TrialConstructor/ConstructorValue/"); + + field_trials.RegisterKeysForTesting( + {"TrialCommon", "TrialFlag", "TrialConstructor"}); + EXPECT_EQ(field_trials.Lookup("TrialCommon"), "ValueC"); + EXPECT_EQ(field_trials.Lookup("TrialFlag"), "FlagValue"); + EXPECT_EQ(field_trials.Lookup("TrialConstructor"), "ConstructorValue"); +} + +} // namespace +} // namespace webrtc diff --git a/test/create_test_field_trials_without_absl_flag.cc b/test/create_test_field_trials_without_absl_flag.cc new file mode 100644 index 0000000000..f14f8ed525 --- /dev/null +++ b/test/create_test_field_trials_without_absl_flag.cc @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 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. + */ + +// absl flags are not allowed when building with chromium, so if this helper +// happend to be used from chromium tests, disable populating field trials from +// the command line flag by default. + +#include "absl/strings/string_view.h" +#include "api/field_trials.h" +#include "test/create_test_field_trials.h" + +namespace webrtc { + +FieldTrials CreateTestFieldTrials(absl::string_view s) { + return FieldTrials(s); +} + +} // namespace webrtc diff --git a/test/direct_transport_unittest.cc b/test/direct_transport_unittest.cc index ab00971089..4fbc11cb6c 100644 --- a/test/direct_transport_unittest.cc +++ b/test/direct_transport_unittest.cc @@ -9,8 +9,10 @@ */ #include "test/direct_transport.h" -#include +#include +#include +#include "api/media_types.h" #include "test/gtest.h" namespace webrtc { diff --git a/test/drifting_clock.cc b/test/drifting_clock.cc index 47c8e56916..fc476233a7 100644 --- a/test/drifting_clock.cc +++ b/test/drifting_clock.cc @@ -10,7 +10,13 @@ #include "test/drifting_clock.h" +#include + +#include "api/units/time_delta.h" +#include "api/units/timestamp.h" #include "rtc_base/checks.h" +#include "system_wrappers/include/clock.h" +#include "system_wrappers/include/ntp_time.h" namespace webrtc { namespace test { diff --git a/test/drifting_clock.h b/test/drifting_clock.h index 4a2500ba30..0b71a9cd33 100644 --- a/test/drifting_clock.h +++ b/test/drifting_clock.h @@ -10,8 +10,8 @@ #ifndef TEST_DRIFTING_CLOCK_H_ #define TEST_DRIFTING_CLOCK_H_ -#include - +#include "api/units/time_delta.h" +#include "api/units/timestamp.h" #include "system_wrappers/include/clock.h" #include "system_wrappers/include/ntp_time.h" diff --git a/test/encoder_settings.cc b/test/encoder_settings.cc index d8c9348c43..5e154c870d 100644 --- a/test/encoder_settings.cc +++ b/test/encoder_settings.cc @@ -10,11 +10,20 @@ #include "test/encoder_settings.h" #include +#include +#include +#include +#include "api/field_trials_view.h" +#include "api/make_ref_counted.h" #include "api/scoped_refptr.h" +#include "api/video/video_codec_type.h" #include "api/video_codecs/sdp_video_format.h" #include "call/rtp_config.h" +#include "call/video_receive_stream.h" +#include "call/video_send_stream.h" #include "rtc_base/checks.h" +#include "video/config/video_encoder_config.h" namespace webrtc { namespace test { diff --git a/test/encoder_settings.h b/test/encoder_settings.h index aa3954a381..d920ceb189 100644 --- a/test/encoder_settings.h +++ b/test/encoder_settings.h @@ -10,11 +10,12 @@ #ifndef TEST_ENCODER_SETTINGS_H_ #define TEST_ENCODER_SETTINGS_H_ -#include - +#include #include #include +#include "api/field_trials_view.h" +#include "api/video/video_codec_type.h" #include "call/video_receive_stream.h" #include "call/video_send_stream.h" #include "video/config/video_encoder_config.h" diff --git a/test/fake_decoder.cc b/test/fake_decoder.cc index d077ae7b5a..e2362a0efd 100644 --- a/test/fake_decoder.cc +++ b/test/fake_decoder.cc @@ -10,19 +10,20 @@ #include "test/fake_decoder.h" -#include - +#include +#include #include #include "api/scoped_refptr.h" #include "api/task_queue/task_queue_factory.h" +#include "api/units/time_delta.h" +#include "api/video/encoded_image.h" #include "api/video/i420_buffer.h" #include "api/video/video_frame.h" -#include "api/video/video_frame_buffer.h" #include "api/video/video_rotation.h" +#include "api/video_codecs/video_decoder.h" #include "modules/video_coding/include/video_error_codes.h" #include "rtc_base/checks.h" -#include "rtc_base/time_utils.h" namespace webrtc { namespace test { diff --git a/test/fake_decoder.h b/test/fake_decoder.h index 8487e36086..e8f9462bc0 100644 --- a/test/fake_decoder.h +++ b/test/fake_decoder.h @@ -11,15 +11,13 @@ #ifndef TEST_FAKE_DECODER_H_ #define TEST_FAKE_DECODER_H_ -#include - +#include #include #include "api/task_queue/task_queue_base.h" #include "api/task_queue/task_queue_factory.h" #include "api/video/encoded_image.h" #include "api/video_codecs/video_decoder.h" -#include "modules/video_coding/include/video_codec_interface.h" namespace webrtc { namespace test { diff --git a/test/fake_encoded_frame.cc b/test/fake_encoded_frame.cc index 7a74bf98e9..021abc0251 100644 --- a/test/fake_encoded_frame.cc +++ b/test/fake_encoded_frame.cc @@ -10,9 +10,19 @@ #include "test/fake_encoded_frame.h" +#include +#include #include +#include +#include "api/rtp_packet_infos.h" +#include "api/units/timestamp.h" +#include "api/video/encoded_frame.h" +#include "api/video/encoded_image.h" #include "api/video/video_frame_type.h" +#include "api/video/video_rotation.h" +#include "api/video/video_timing.h" +#include "rtc_base/checks.h" namespace webrtc { namespace test { diff --git a/test/fake_encoded_frame.h b/test/fake_encoded_frame.h index cfac3d9966..484bd3168b 100644 --- a/test/fake_encoded_frame.h +++ b/test/fake_encoded_frame.h @@ -11,12 +11,17 @@ #ifndef TEST_FAKE_ENCODED_FRAME_H_ #define TEST_FAKE_ENCODED_FRAME_H_ +#include +#include #include +#include #include #include "api/rtp_packet_infos.h" +#include "api/units/timestamp.h" #include "api/video/encoded_frame.h" #include "api/video/video_rotation.h" +#include "api/video/video_timing.h" #include "test/gmock.h" namespace webrtc { diff --git a/test/fake_encoder.cc b/test/fake_encoder.cc index e069b4b4a3..51ca50e8d4 100644 --- a/test/fake_encoder.cc +++ b/test/fake_encoder.cc @@ -10,20 +10,36 @@ #include "test/fake_encoder.h" -#include - #include +#include #include +#include #include +#include #include +#include +#include "absl/strings/string_view.h" #include "api/environment/environment.h" +#include "api/fec_controller_override.h" +#include "api/scoped_refptr.h" +#include "api/sequence_checker.h" +#include "api/task_queue/task_queue_base.h" #include "api/task_queue/task_queue_factory.h" -#include "api/video/video_content_type.h" +#include "api/video/encoded_image.h" +#include "api/video/video_bitrate_allocation.h" +#include "api/video/video_codec_constants.h" +#include "api/video/video_codec_type.h" +#include "api/video/video_frame.h" +#include "api/video/video_frame_type.h" +#include "api/video_codecs/simulcast_stream.h" +#include "api/video_codecs/video_codec.h" +#include "api/video_codecs/video_encoder.h" #include "modules/video_coding/codecs/h264/include/h264_globals.h" #include "modules/video_coding/include/video_codec_interface.h" #include "modules/video_coding/include/video_error_codes.h" #include "rtc_base/checks.h" +#include "rtc_base/synchronization/mutex.h" #include "rtc_base/thread.h" namespace webrtc { diff --git a/test/fake_encoder.h b/test/fake_encoder.h index e77f8aad6c..4e8b7969d5 100644 --- a/test/fake_encoder.h +++ b/test/fake_encoder.h @@ -11,26 +11,30 @@ #ifndef TEST_FAKE_ENCODER_H_ #define TEST_FAKE_ENCODER_H_ -#include -#include - +#include +#include #include #include +#include #include #include "absl/strings/string_view.h" #include "api/environment/environment.h" #include "api/fec_controller_override.h" +#include "api/scoped_refptr.h" #include "api/sequence_checker.h" +#include "api/task_queue/task_queue_base.h" #include "api/video/encoded_image.h" #include "api/video/video_bitrate_allocation.h" +#include "api/video/video_codec_constants.h" #include "api/video/video_frame.h" +#include "api/video/video_frame_type.h" +#include "api/video_codecs/simulcast_stream.h" #include "api/video_codecs/video_codec.h" #include "api/video_codecs/video_encoder.h" #include "modules/video_coding/include/video_codec_interface.h" #include "rtc_base/synchronization/mutex.h" #include "rtc_base/thread_annotations.h" -#include "system_wrappers/include/clock.h" namespace webrtc { namespace test { diff --git a/test/fake_texture_frame.cc b/test/fake_texture_frame.cc index 95e84c7d6a..1f27b4f8a3 100644 --- a/test/fake_texture_frame.cc +++ b/test/fake_texture_frame.cc @@ -10,7 +10,14 @@ #include "test/fake_texture_frame.h" +#include + +#include "api/make_ref_counted.h" +#include "api/scoped_refptr.h" #include "api/video/i420_buffer.h" +#include "api/video/video_frame.h" +#include "api/video/video_frame_buffer.h" +#include "api/video/video_rotation.h" namespace webrtc { namespace test { diff --git a/test/fake_texture_frame.h b/test/fake_texture_frame.h index b0329651b6..c0fc36c21d 100644 --- a/test/fake_texture_frame.h +++ b/test/fake_texture_frame.h @@ -10,10 +10,12 @@ #ifndef TEST_FAKE_TEXTURE_FRAME_H_ #define TEST_FAKE_TEXTURE_FRAME_H_ -#include "api/video/i420_buffer.h" +#include + +#include "api/scoped_refptr.h" #include "api/video/video_frame.h" -#include "common_video/include/video_frame_buffer.h" -#include "rtc_base/checks.h" +#include "api/video/video_frame_buffer.h" +#include "api/video/video_rotation.h" namespace webrtc { namespace test { diff --git a/test/fake_vp8_decoder.cc b/test/fake_vp8_decoder.cc index 9471d11280..8e953fefef 100644 --- a/test/fake_vp8_decoder.cc +++ b/test/fake_vp8_decoder.cc @@ -10,17 +10,17 @@ #include "test/fake_vp8_decoder.h" -#include - +#include +#include #include #include "api/scoped_refptr.h" +#include "api/video/encoded_image.h" #include "api/video/i420_buffer.h" #include "api/video/video_frame.h" -#include "api/video/video_frame_buffer.h" #include "api/video/video_rotation.h" +#include "api/video_codecs/video_decoder.h" #include "modules/video_coding/include/video_error_codes.h" -#include "rtc_base/time_utils.h" namespace webrtc { namespace test { diff --git a/test/fake_vp8_decoder.h b/test/fake_vp8_decoder.h index 5bfe3a4974..0ce9b4b4cc 100644 --- a/test/fake_vp8_decoder.h +++ b/test/fake_vp8_decoder.h @@ -11,11 +11,10 @@ #ifndef TEST_FAKE_VP8_DECODER_H_ #define TEST_FAKE_VP8_DECODER_H_ -#include +#include #include "api/video/encoded_image.h" #include "api/video_codecs/video_decoder.h" -#include "modules/video_coding/include/video_codec_interface.h" namespace webrtc { namespace test { diff --git a/test/fake_vp8_encoder.cc b/test/fake_vp8_encoder.cc index 597d01e5a9..f3e95ccb3f 100644 --- a/test/fake_vp8_encoder.cc +++ b/test/fake_vp8_encoder.cc @@ -10,16 +10,24 @@ #include "test/fake_vp8_encoder.h" -#include +#include +#include #include +#include "api/environment/environment.h" +#include "api/scoped_refptr.h" +#include "api/sequence_checker.h" +#include "api/video/encoded_image.h" +#include "api/video/video_codec_type.h" +#include "api/video/video_frame_type.h" +#include "api/video_codecs/video_codec.h" #include "api/video_codecs/video_encoder.h" -#include "api/video_codecs/vp8_temporal_layers.h" #include "api/video_codecs/vp8_temporal_layers_factory.h" #include "modules/video_coding/codecs/interface/common_constants.h" #include "modules/video_coding/include/video_codec_interface.h" #include "modules/video_coding/include/video_error_codes.h" -#include "modules/video_coding/utility/simulcast_utility.h" +#include "rtc_base/synchronization/mutex.h" +#include "test/fake_encoder.h" namespace { diff --git a/test/fake_vp8_encoder.h b/test/fake_vp8_encoder.h index 53288a19f4..9147dfa278 100644 --- a/test/fake_vp8_encoder.h +++ b/test/fake_vp8_encoder.h @@ -11,19 +11,19 @@ #ifndef TEST_FAKE_VP8_ENCODER_H_ #define TEST_FAKE_VP8_ENCODER_H_ -#include -#include - +#include +#include #include #include "api/environment/environment.h" #include "api/fec_controller_override.h" +#include "api/scoped_refptr.h" #include "api/sequence_checker.h" #include "api/video/encoded_image.h" +#include "api/video/video_frame_type.h" #include "api/video_codecs/video_codec.h" #include "api/video_codecs/video_encoder.h" #include "api/video_codecs/vp8_frame_buffer_controller.h" -#include "api/video_codecs/vp8_temporal_layers.h" #include "modules/video_coding/include/video_codec_interface.h" #include "rtc_base/thread_annotations.h" #include "system_wrappers/include/clock.h" diff --git a/test/fake_vp8_encoder_unittest.cc b/test/fake_vp8_encoder_unittest.cc index 08982438af..d54fbc5383 100644 --- a/test/fake_vp8_encoder_unittest.cc +++ b/test/fake_vp8_encoder_unittest.cc @@ -13,12 +13,16 @@ #include #include +#include "api/environment/environment.h" #include "api/test/create_simulcast_test_fixture.h" #include "api/test/simulcast_test_fixture.h" #include "api/test/video/function_video_decoder_factory.h" #include "api/test/video/function_video_encoder_factory.h" -#include "modules/video_coding/utility/simulcast_test_fixture_impl.h" +#include "api/video_codecs/sdp_video_format.h" +#include "api/video_codecs/video_decoder_factory.h" +#include "api/video_codecs/video_encoder_factory.h" #include "test/fake_vp8_decoder.h" +#include "test/gtest.h" namespace webrtc { namespace test { diff --git a/test/frame_forwarder.cc b/test/frame_forwarder.cc index 944fbf4f9d..c7230894df 100644 --- a/test/frame_forwarder.cc +++ b/test/frame_forwarder.cc @@ -9,7 +9,11 @@ */ #include "test/frame_forwarder.h" +#include "api/video/video_frame.h" +#include "api/video/video_sink_interface.h" +#include "api/video/video_source_interface.h" #include "rtc_base/checks.h" +#include "rtc_base/synchronization/mutex.h" namespace webrtc { namespace test { diff --git a/test/frame_forwarder.h b/test/frame_forwarder.h index 59b36a4140..b27267b68a 100644 --- a/test/frame_forwarder.h +++ b/test/frame_forwarder.h @@ -11,8 +11,10 @@ #define TEST_FRAME_FORWARDER_H_ #include "api/video/video_frame.h" +#include "api/video/video_sink_interface.h" #include "api/video/video_source_interface.h" #include "rtc_base/synchronization/mutex.h" +#include "rtc_base/thread_annotations.h" namespace webrtc { namespace test { diff --git a/test/frame_generator.cc b/test/frame_generator.cc index aab3991c36..15faf25798 100644 --- a/test/frame_generator.cc +++ b/test/frame_generator.cc @@ -9,18 +9,25 @@ */ #include "test/frame_generator.h" -#include - +#include #include #include +#include +#include #include +#include +#include +#include "api/scoped_refptr.h" +#include "api/test/frame_generator_interface.h" #include "api/video/i010_buffer.h" #include "api/video/nv12_buffer.h" -#include "api/video/video_rotation.h" +#include "api/video/video_frame_buffer.h" #include "common_video/include/video_frame_buffer.h" #include "common_video/libyuv/include/webrtc_libyuv.h" #include "rtc_base/checks.h" +#include "rtc_base/synchronization/mutex.h" +#include "system_wrappers/include/clock.h" #include "test/frame_utils.h" namespace webrtc { diff --git a/test/frame_generator.h b/test/frame_generator.h index 089caaa76c..e2bb768275 100644 --- a/test/frame_generator.h +++ b/test/frame_generator.h @@ -10,20 +10,22 @@ #ifndef TEST_FRAME_GENERATOR_H_ #define TEST_FRAME_GENERATOR_H_ +#include +#include +#include #include -#include +#include #include #include "api/scoped_refptr.h" #include "api/test/frame_generator_interface.h" #include "api/video/i420_buffer.h" #include "api/video/nv12_buffer.h" -#include "api/video/video_frame.h" #include "api/video/video_frame_buffer.h" -#include "api/video/video_source_interface.h" #include "rtc_base/logging.h" #include "rtc_base/random.h" #include "rtc_base/synchronization/mutex.h" +#include "rtc_base/thread_annotations.h" #include "system_wrappers/include/clock.h" namespace webrtc { diff --git a/test/frame_generator_capturer_unittest.cc b/test/frame_generator_capturer_unittest.cc index 94b9d70c10..8f60cd7d2f 100644 --- a/test/frame_generator_capturer_unittest.cc +++ b/test/frame_generator_capturer_unittest.cc @@ -10,6 +10,11 @@ #include "test/frame_generator_capturer.h" +#include "api/units/time_delta.h" +#include "api/units/timestamp.h" +#include "api/video/video_frame.h" +#include "api/video/video_sink_interface.h" +#include "api/video/video_source_interface.h" #include "test/create_frame_generator_capturer.h" #include "test/gmock.h" #include "test/gtest.h" diff --git a/test/frame_generator_unittest.cc b/test/frame_generator_unittest.cc index 8de5241c93..dcd546dd81 100644 --- a/test/frame_generator_unittest.cc +++ b/test/frame_generator_unittest.cc @@ -8,19 +8,20 @@ * be found in the AUTHORS file in the root of the source tree. */ -#include "test/frame_generator.h" - #include -#include #include +#include +#include #include #include +#include #include "api/scoped_refptr.h" #include "api/test/create_frame_generator.h" #include "api/test/frame_generator_interface.h" #include "api/video/video_frame_buffer.h" +#include "rtc_base/checks.h" #include "test/gtest.h" #include "test/testsupport/file_utils.h" diff --git a/test/frame_utils.cc b/test/frame_utils.cc index 1a45c04a2a..2ea921f5a8 100644 --- a/test/frame_utils.cc +++ b/test/frame_utils.cc @@ -10,12 +10,15 @@ #include "test/frame_utils.h" -#include -#include +#include +#include +#include +#include "api/scoped_refptr.h" #include "api/video/i420_buffer.h" #include "api/video/nv12_buffer.h" #include "api/video/video_frame.h" +#include "api/video/video_frame_buffer.h" namespace webrtc { namespace test { diff --git a/test/frame_utils.h b/test/frame_utils.h index c537fc68ef..71430c0d83 100644 --- a/test/frame_utils.h +++ b/test/frame_utils.h @@ -10,7 +10,8 @@ #ifndef TEST_FRAME_UTILS_H_ #define TEST_FRAME_UTILS_H_ -#include +#include +#include #include "api/scoped_refptr.h" #include "api/video/nv12_buffer.h" diff --git a/test/function_audio_decoder_factory.h b/test/function_audio_decoder_factory.h index c31424956f..6d1141b3f4 100644 --- a/test/function_audio_decoder_factory.h +++ b/test/function_audio_decoder_factory.h @@ -13,10 +13,12 @@ #include #include +#include #include #include -#include "absl/memory/memory.h" +#include "api/audio_codecs/audio_codec_pair_id.h" +#include "api/audio_codecs/audio_decoder.h" #include "api/audio_codecs/audio_decoder_factory.h" #include "api/audio_codecs/audio_format.h" #include "api/environment/environment.h" diff --git a/test/fuzzers/BUILD.gn b/test/fuzzers/BUILD.gn index acf6db2a6a..3c2038d64b 100644 --- a/test/fuzzers/BUILD.gn +++ b/test/fuzzers/BUILD.gn @@ -38,6 +38,7 @@ rtc_library("fuzz_data_helper") { deps = [ "../../api:array_view", "../../modules/rtp_rtcp:rtp_rtcp_format", + "../../rtc_base:checks", ] visibility = [ ":*" ] # Only targets in this file can depend on this. } @@ -351,7 +352,7 @@ webrtc_fuzzer_test("audio_decoder_opus_fuzzer") { sources = [ "audio_decoder_opus_fuzzer.cc" ] deps = [ ":audio_decoder_fuzzer", - "..:explicit_key_value_config", + "../../api:field_trials", "../../modules/audio_coding:webrtc_opus", ] } @@ -360,7 +361,7 @@ webrtc_fuzzer_test("audio_decoder_opus_redundant_fuzzer") { sources = [ "audio_decoder_opus_redundant_fuzzer.cc" ] deps = [ ":audio_decoder_fuzzer", - "..:explicit_key_value_config", + "../../api:field_trials", "../../modules/audio_coding:webrtc_opus", ] } @@ -584,7 +585,6 @@ webrtc_fuzzer_test("audio_processing_sample_rate_fuzzer") { "../../modules/audio_processing:audio_frame_proxies", "../../modules/audio_processing:audioproc_test_utils", "../../rtc_base:checks", - "../../rtc_base:macromagic", "../../rtc_base:safe_minmax", ] } @@ -598,7 +598,6 @@ webrtc_fuzzer_test("agc_fuzzer") { "../../modules/audio_processing", "../../modules/audio_processing:audio_buffer", "../../modules/audio_processing/agc:gain_control_interface", - "../../rtc_base:macromagic", "../../rtc_base:safe_minmax", ] @@ -712,7 +711,10 @@ webrtc_fuzzer_test("frame_buffer_fuzzer") { webrtc_fuzzer_test("field_trial_fuzzer") { sources = [ "field_trial_fuzzer.cc" ] - deps = [ "../../system_wrappers:field_trial" ] + deps = [ + "../../api:field_trials", + "//third_party/abseil-cpp/absl/strings:string_view", + ] seed_corpus = "corpora/field_trial-corpus" } @@ -790,7 +792,6 @@ if (rtc_build_libvpx) { "../../rtc_base:checks", "../../rtc_base:safe_compare", "//third_party/abseil-cpp/absl/algorithm:container", - "//third_party/abseil-cpp/absl/base:core_headers", "//third_party/abseil-cpp/absl/container:inlined_vector", "//third_party/abseil-cpp/absl/strings:string_view", rtc_libvpx_dir, diff --git a/test/fuzzers/audio_decoder_opus_fuzzer.cc b/test/fuzzers/audio_decoder_opus_fuzzer.cc index be4d62dbd7..bfca95512f 100644 --- a/test/fuzzers/audio_decoder_opus_fuzzer.cc +++ b/test/fuzzers/audio_decoder_opus_fuzzer.cc @@ -11,16 +11,15 @@ #include #include +#include "api/field_trials.h" #include "modules/audio_coding/codecs/opus/audio_decoder_opus.h" -#include "test/explicit_key_value_config.h" #include "test/fuzzers/audio_decoder_fuzzer.h" namespace webrtc { void FuzzOneInput(const uint8_t* data, size_t size) { const size_t channels = (size % 2) + 1; // 1 or 2 channels. const int kSampleRateHz = 48'000; - AudioDecoderOpusImpl dec(test::ExplicitKeyValueConfig(""), channels, - kSampleRateHz); + AudioDecoderOpusImpl dec(FieldTrials(""), channels, kSampleRateHz); const size_t kAllocatedOuputSizeSamples = kSampleRateHz / 10; // 100 ms. int16_t output[kAllocatedOuputSizeSamples]; FuzzAudioDecoder(DecoderFunctionType::kNormalDecode, data, size, &dec, diff --git a/test/fuzzers/audio_decoder_opus_redundant_fuzzer.cc b/test/fuzzers/audio_decoder_opus_redundant_fuzzer.cc index ad1787c267..1c2d56efa0 100644 --- a/test/fuzzers/audio_decoder_opus_redundant_fuzzer.cc +++ b/test/fuzzers/audio_decoder_opus_redundant_fuzzer.cc @@ -11,16 +11,15 @@ #include #include +#include "api/field_trials.h" #include "modules/audio_coding/codecs/opus/audio_decoder_opus.h" -#include "test/explicit_key_value_config.h" #include "test/fuzzers/audio_decoder_fuzzer.h" namespace webrtc { void FuzzOneInput(const uint8_t* data, size_t size) { const size_t channels = (size % 2) + 1; // 1 or 2 channels. const int kSampleRateHz = 48'000; - AudioDecoderOpusImpl dec(test::ExplicitKeyValueConfig(""), channels, - kSampleRateHz); + AudioDecoderOpusImpl dec(FieldTrials(""), channels, kSampleRateHz); const size_t kAllocatedOuputSizeSamples = kSampleRateHz / 10; // 100 ms. int16_t output[kAllocatedOuputSizeSamples]; FuzzAudioDecoder(DecoderFunctionType::kRedundantDecode, data, size, &dec, diff --git a/test/fuzzers/audio_encoder_fuzzer.h b/test/fuzzers/audio_encoder_fuzzer.h index 69ef08f9fa..de0609dff8 100644 --- a/test/fuzzers/audio_encoder_fuzzer.h +++ b/test/fuzzers/audio_encoder_fuzzer.h @@ -11,6 +11,7 @@ #ifndef TEST_FUZZERS_AUDIO_ENCODER_FUZZER_H_ #define TEST_FUZZERS_AUDIO_ENCODER_FUZZER_H_ +#include #include #include "api/array_view.h" diff --git a/test/fuzzers/audio_processing_fuzzer_helper.h b/test/fuzzers/audio_processing_fuzzer_helper.h index 9437a4a7cb..fc216f2e45 100644 --- a/test/fuzzers/audio_processing_fuzzer_helper.h +++ b/test/fuzzers/audio_processing_fuzzer_helper.h @@ -11,9 +11,9 @@ #ifndef TEST_FUZZERS_AUDIO_PROCESSING_FUZZER_HELPER_H_ #define TEST_FUZZERS_AUDIO_PROCESSING_FUZZER_HELPER_H_ -#include #include "api/audio/audio_processing.h" +#include "api/scoped_refptr.h" #include "test/fuzzers/fuzz_data_helper.h" namespace webrtc { diff --git a/test/fuzzers/field_trial_fuzzer.cc b/test/fuzzers/field_trial_fuzzer.cc index 74fe65ce56..ee9d845608 100644 --- a/test/fuzzers/field_trial_fuzzer.cc +++ b/test/fuzzers/field_trial_fuzzer.cc @@ -8,19 +8,20 @@ * be found in the AUTHORS file in the root of the source tree. */ -#include -#include +#include +#include -#include - -#include "system_wrappers/include/field_trial.h" +#include "absl/strings/string_view.h" +#include "api/field_trials.h" namespace webrtc { void FuzzOneInput(const uint8_t* data, size_t size) { - std::string field_trial(reinterpret_cast(data), size); - field_trial::InitFieldTrialsFromString(field_trial.c_str()); - field_trial::FindFullName(field_trial); + // FieldTrials constructor crashes on invalid input. + // FieldTrials::Create validates input and returns nullptr when it is invalid, + // but should never crash. + FieldTrials::Create( + absl::string_view(reinterpret_cast(data), size)); } } // namespace webrtc diff --git a/test/fuzzers/fuzz_data_helper.h b/test/fuzzers/fuzz_data_helper.h index 42617f1426..c93f6b7679 100644 --- a/test/fuzzers/fuzz_data_helper.h +++ b/test/fuzzers/fuzz_data_helper.h @@ -11,10 +11,15 @@ #ifndef TEST_FUZZERS_FUZZ_DATA_HELPER_H_ #define TEST_FUZZERS_FUZZ_DATA_HELPER_H_ +#include +#include +#include #include +#include #include "api/array_view.h" #include "modules/rtp_rtcp/source/byte_io.h" +#include "rtc_base/checks.h" namespace webrtc { namespace test { diff --git a/test/fuzzers/utils/BUILD.gn b/test/fuzzers/utils/BUILD.gn index d0901831f1..3082b84adf 100644 --- a/test/fuzzers/utils/BUILD.gn +++ b/test/fuzzers/utils/BUILD.gn @@ -15,12 +15,15 @@ rtc_library("rtp_replayer") { "rtp_replayer.h", ] deps = [ + "../../../api:transport_api", "../../../api/environment:environment_factory", "../../../api/test/video:function_video_factory", "../../../api/units:timestamp", + "../../../api/video:video_frame", "../../../api/video_codecs:video_codecs_api", "../../../call", "../../../call:call_interfaces", + "../../../call:video_receive_stream_api", "../../../common_video", "../../../media:rtc_internal_video_codecs", "../../../modules/rtp_rtcp:rtp_rtcp_format", diff --git a/test/fuzzers/utils/rtp_replayer.cc b/test/fuzzers/utils/rtp_replayer.cc index 081d31ba80..d6d3b4a826 100644 --- a/test/fuzzers/utils/rtp_replayer.cc +++ b/test/fuzzers/utils/rtp_replayer.cc @@ -18,6 +18,7 @@ #include "absl/memory/memory.h" #include "api/environment/environment_factory.h" #include "api/units/timestamp.h" +#include "media/engine/internal_decoder_factory.h" #include "modules/rtp_rtcp/source/rtp_packet.h" #include "modules/rtp_rtcp/source/rtp_packet_received.h" #include "rtc_base/strings/json.h" diff --git a/test/fuzzers/utils/rtp_replayer.h b/test/fuzzers/utils/rtp_replayer.h index c6fa74f0f6..6646245ac2 100644 --- a/test/fuzzers/utils/rtp_replayer.h +++ b/test/fuzzers/utils/rtp_replayer.h @@ -11,22 +11,21 @@ #ifndef TEST_FUZZERS_UTILS_RTP_REPLAYER_H_ #define TEST_FUZZERS_UTILS_RTP_REPLAYER_H_ -#include - -#include +#include +#include #include #include #include -#include "api/test/video/function_video_decoder_factory.h" -#include "api/video_codecs/video_decoder.h" +#include "api/call/transport.h" +#include "api/video/video_sink_interface.h" +#include "api/video_codecs/video_decoder_factory.h" #include "call/call.h" -#include "media/engine/internal_decoder_factory.h" +#include "call/video_receive_stream.h" +#include "modules/rtp_rtcp/include/rtp_header_extension_map.h" #include "rtc_base/fake_clock.h" -#include "rtc_base/time_utils.h" #include "test/null_transport.h" #include "test/rtp_file_reader.h" -#include "test/test_video_capturer.h" #include "test/video_renderer.h" namespace webrtc { diff --git a/test/fuzzers/vp9_encoder_references_fuzzer.cc b/test/fuzzers/vp9_encoder_references_fuzzer.cc index 8f6fcbd7b2..80af5138b3 100644 --- a/test/fuzzers/vp9_encoder_references_fuzzer.cc +++ b/test/fuzzers/vp9_encoder_references_fuzzer.cc @@ -16,7 +16,6 @@ #include #include "absl/algorithm/container.h" -#include "absl/base/macros.h" #include "absl/container/inlined_vector.h" #include "absl/strings/string_view.h" #include "api/array_view.h" @@ -195,7 +194,7 @@ class FieldTrials : public FieldTrialsView { static constexpr absl::string_view kBinaryFieldTrials[] = { "WebRTC-Vp9IssueKeyFrameOnLayerDeactivation", }; - for (size_t i = 0; i < ABSL_ARRAYSIZE(kBinaryFieldTrials); ++i) { + for (size_t i = 0; i < std::size(kBinaryFieldTrials); ++i) { if (key == kBinaryFieldTrials[i]) { return (flags_ & (1u << i)) ? "Enabled" : "Disabled"; } @@ -313,7 +312,7 @@ struct LibvpxState { LibvpxState() { pkt.kind = VPX_CODEC_CX_FRAME_PKT; pkt.data.frame.buf = pkt_buffer; - pkt.data.frame.sz = ABSL_ARRAYSIZE(pkt_buffer); + pkt.data.frame.sz = std::size(pkt_buffer); layer_id.spatial_layer_id = -1; } diff --git a/test/gl/gl_renderer.cc b/test/gl/gl_renderer.cc index 4a16419b8a..1b923bdd9a 100644 --- a/test/gl/gl_renderer.cc +++ b/test/gl/gl_renderer.cc @@ -10,11 +10,19 @@ #include "test/gl/gl_renderer.h" -#include +#include +#include +#include "api/video/video_frame.h" #include "common_video/libyuv/include/webrtc_libyuv.h" #include "rtc_base/checks.h" +#ifdef WEBRTC_MAC +#include +#else +#include +#endif + namespace webrtc { namespace test { diff --git a/test/jitter/BUILD.gn b/test/jitter/BUILD.gn index c14c94c55a..08d298b4b9 100644 --- a/test/jitter/BUILD.gn +++ b/test/jitter/BUILD.gn @@ -36,7 +36,10 @@ rtc_library("logging_delay_variation_calculator") { deps = [ ":delay_variation_calculator", "../../api/test/metrics:global_metrics_logger_and_exporter", + "../../api/test/metrics:metric", + "../../api/test/metrics:metrics_logger", "../../api/units:data_size", + "../../api/units:timestamp", "../../api/video:video_frame_type", "../../rtc_base:logging", "//third_party/abseil-cpp/absl/strings:string_view", @@ -54,8 +57,11 @@ if (rtc_include_tests) { ":delay_variation_calculator", ":logging_delay_variation_calculator", "../../api/numerics", + "../../api/test/metrics:metric", "../../api/test/metrics:metrics_logger", + "../../api/units:data_size", "../../api/units:timestamp", + "../../api/video:video_frame_type", "../../system_wrappers", "../../test:test_support", ] diff --git a/test/jitter/delay_variation_calculator.cc b/test/jitter/delay_variation_calculator.cc index 2d409f88d8..9098ef6aa3 100644 --- a/test/jitter/delay_variation_calculator.cc +++ b/test/jitter/delay_variation_calculator.cc @@ -10,13 +10,16 @@ #include "test/jitter/delay_variation_calculator.h" +#include #include #include +#include "api/numerics/samples_stats_counter.h" +#include "api/units/data_size.h" #include "api/units/frequency.h" #include "api/units/time_delta.h" #include "api/units/timestamp.h" -#include "rtc_base/logging.h" +#include "api/video/video_frame_type.h" namespace webrtc { namespace test { diff --git a/test/jitter/delay_variation_calculator.h b/test/jitter/delay_variation_calculator.h index 6b06afe86d..dcf10a22d5 100644 --- a/test/jitter/delay_variation_calculator.h +++ b/test/jitter/delay_variation_calculator.h @@ -11,14 +11,12 @@ #ifndef TEST_JITTER_DELAY_VARIATION_CALCULATOR_H_ #define TEST_JITTER_DELAY_VARIATION_CALCULATOR_H_ -#include - +#include #include #include #include #include "api/numerics/samples_stats_counter.h" -#include "api/test/metrics/metrics_logger.h" #include "api/units/data_size.h" #include "api/units/timestamp.h" #include "api/video/video_frame_type.h" diff --git a/test/jitter/delay_variation_calculator_unittest.cc b/test/jitter/delay_variation_calculator_unittest.cc index 41db376ed6..e3ca861616 100644 --- a/test/jitter/delay_variation_calculator_unittest.cc +++ b/test/jitter/delay_variation_calculator_unittest.cc @@ -10,8 +10,12 @@ #include "test/jitter/delay_variation_calculator.h" +#include + #include "api/numerics/samples_stats_counter.h" +#include "api/units/data_size.h" #include "api/units/timestamp.h" +#include "api/video/video_frame_type.h" #include "test/gmock.h" #include "test/gtest.h" diff --git a/test/jitter/logging_delay_variation_calculator.cc b/test/jitter/logging_delay_variation_calculator.cc index dc08a173c8..854b55524b 100644 --- a/test/jitter/logging_delay_variation_calculator.cc +++ b/test/jitter/logging_delay_variation_calculator.cc @@ -10,8 +10,14 @@ #include "test/jitter/logging_delay_variation_calculator.h" -#include "api/test/metrics/global_metrics_logger_and_exporter.h" -#include "rtc_base/logging.h" +#include +#include + +#include "api/test/metrics/metric.h" +#include "api/units/data_size.h" +#include "api/units/timestamp.h" +#include "api/video/video_frame_type.h" +#include "test/jitter/delay_variation_calculator.h" namespace webrtc { namespace test { diff --git a/test/jitter/logging_delay_variation_calculator.h b/test/jitter/logging_delay_variation_calculator.h index a3a67af59c..7438026acd 100644 --- a/test/jitter/logging_delay_variation_calculator.h +++ b/test/jitter/logging_delay_variation_calculator.h @@ -11,11 +11,16 @@ #ifndef TEST_JITTER_LOGGING_DELAY_VARIATION_CALCULATOR_H_ #define TEST_JITTER_LOGGING_DELAY_VARIATION_CALCULATOR_H_ +#include +#include #include #include "absl/strings/string_view.h" #include "api/test/metrics/global_metrics_logger_and_exporter.h" +#include "api/test/metrics/metrics_logger.h" #include "api/units/data_size.h" +#include "api/units/timestamp.h" +#include "api/video/video_frame_type.h" #include "test/jitter/delay_variation_calculator.h" namespace webrtc { diff --git a/test/jitter/logging_delay_variation_calculator_unittest.cc b/test/jitter/logging_delay_variation_calculator_unittest.cc index d28a235804..de1f6828ca 100644 --- a/test/jitter/logging_delay_variation_calculator_unittest.cc +++ b/test/jitter/logging_delay_variation_calculator_unittest.cc @@ -11,11 +11,15 @@ #include "test/jitter/logging_delay_variation_calculator.h" #include +#include #include #include +#include #include +#include "api/test/metrics/metric.h" #include "api/test/metrics/metrics_logger.h" +#include "api/units/data_size.h" #include "api/units/timestamp.h" #include "system_wrappers/include/clock.h" #include "test/gtest.h" diff --git a/test/layer_filtering_transport.cc b/test/layer_filtering_transport.cc index bc68d3af1c..109ef8bb21 100644 --- a/test/layer_filtering_transport.cc +++ b/test/layer_filtering_transport.cc @@ -10,13 +10,20 @@ #include "test/layer_filtering_transport.h" -#include - #include +#include +#include #include #include -#include "api/rtp_headers.h" +#include "api/array_view.h" +#include "api/call/transport.h" +#include "api/media_types.h" +#include "api/rtp_parameters.h" +#include "api/task_queue/task_queue_base.h" +#include "api/video/video_codec_type.h" +#include "call/call.h" +#include "call/simulated_packet_receiver.h" #include "modules/rtp_rtcp/include/rtp_rtcp_defines.h" #include "modules/rtp_rtcp/source/create_video_rtp_depacketizer.h" #include "modules/rtp_rtcp/source/rtp_video_header.h" @@ -25,6 +32,7 @@ #include "modules/video_coding/codecs/vp8/include/vp8_globals.h" #include "modules/video_coding/codecs/vp9/include/vp9_globals.h" #include "rtc_base/checks.h" +#include "test/direct_transport.h" namespace webrtc { namespace test { diff --git a/test/layer_filtering_transport.h b/test/layer_filtering_transport.h index e0a23a200e..24c3c1d143 100644 --- a/test/layer_filtering_transport.h +++ b/test/layer_filtering_transport.h @@ -10,14 +10,15 @@ #ifndef TEST_LAYER_FILTERING_TRANSPORT_H_ #define TEST_LAYER_FILTERING_TRANSPORT_H_ -#include -#include - +#include #include #include +#include "api/array_view.h" #include "api/call/transport.h" #include "api/media_types.h" +#include "api/rtp_parameters.h" +#include "api/task_queue/task_queue_base.h" #include "call/call.h" #include "call/simulated_packet_receiver.h" #include "modules/rtp_rtcp/source/video_rtp_depacketizer.h" diff --git a/test/linux/glx_renderer.cc b/test/linux/glx_renderer.cc index 8e66b9272c..12659de5b2 100644 --- a/test/linux/glx_renderer.cc +++ b/test/linux/glx_renderer.cc @@ -10,10 +10,18 @@ #include "test/linux/glx_renderer.h" +#include +#include #include #include #include +#include + +#include "api/video/video_frame.h" +#include "rtc_base/checks.h" +#include "test/gl/gl_renderer.h" + namespace webrtc { namespace test { diff --git a/test/linux/video_renderer_linux.cc b/test/linux/video_renderer_linux.cc index 3d07bd0326..43281d3803 100644 --- a/test/linux/video_renderer_linux.cc +++ b/test/linux/video_renderer_linux.cc @@ -7,7 +7,7 @@ * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ -#include +#include #include "test/linux/glx_renderer.h" #include "test/video_renderer.h" diff --git a/test/logging/file_log_writer.cc b/test/logging/file_log_writer.cc index 9189e1630d..f953147c76 100644 --- a/test/logging/file_log_writer.cc +++ b/test/logging/file_log_writer.cc @@ -9,11 +9,15 @@ */ #include "test/logging/file_log_writer.h" +#include +#include +#include #include +#include #include "absl/strings/string_view.h" +#include "api/rtc_event_log_output.h" #include "rtc_base/checks.h" -#include "rtc_base/logging.h" #include "test/testsupport/file_utils.h" namespace webrtc { diff --git a/test/logging/file_log_writer.h b/test/logging/file_log_writer.h index c49b96ceff..6cbc2535c1 100644 --- a/test/logging/file_log_writer.h +++ b/test/logging/file_log_writer.h @@ -16,6 +16,7 @@ #include #include "absl/strings/string_view.h" +#include "api/rtc_event_log_output.h" #include "test/logging/log_writer.h" namespace webrtc { diff --git a/test/logging/log_writer.cc b/test/logging/log_writer.cc index d9b8c1e68f..79a35d4be8 100644 --- a/test/logging/log_writer.cc +++ b/test/logging/log_writer.cc @@ -9,7 +9,11 @@ */ #include "test/logging/log_writer.h" +#include +#include + #include "absl/strings/string_view.h" +#include "api/rtc_event_log_output.h" namespace webrtc { diff --git a/test/logging/log_writer.h b/test/logging/log_writer.h index 335dab353f..c26925ef39 100644 --- a/test/logging/log_writer.h +++ b/test/logging/log_writer.h @@ -10,15 +10,14 @@ #ifndef TEST_LOGGING_LOG_WRITER_H_ #define TEST_LOGGING_LOG_WRITER_H_ -#include - +#include +#include #include #include -#include #include "absl/strings/string_view.h" #include "api/rtc_event_log_output.h" -#include "rtc_base/strings/string_builder.h" +#include "rtc_base/checks.h" namespace webrtc { template diff --git a/test/logging/memory_log_writer.cc b/test/logging/memory_log_writer.cc index eae9223c77..e121e5d043 100644 --- a/test/logging/memory_log_writer.cc +++ b/test/logging/memory_log_writer.cc @@ -9,11 +9,14 @@ */ #include "test/logging/memory_log_writer.h" +#include #include +#include +#include #include "absl/strings/string_view.h" -#include "rtc_base/checks.h" -#include "rtc_base/logging.h" +#include "api/rtc_event_log_output.h" +#include "test/logging/log_writer.h" namespace webrtc { namespace { diff --git a/test/logging/memory_log_writer.h b/test/logging/memory_log_writer.h index e795b2fd10..3918923274 100644 --- a/test/logging/memory_log_writer.h +++ b/test/logging/memory_log_writer.h @@ -13,7 +13,6 @@ #include #include #include -#include #include "test/logging/log_writer.h" diff --git a/test/mac_capturer.h b/test/mac_capturer.h index 8e53cd5a74..edf5e8f1df 100644 --- a/test/mac_capturer.h +++ b/test/mac_capturer.h @@ -11,14 +11,10 @@ #define TEST_MAC_CAPTURER_H_ #include -#include -#include -#include "api/media_stream_interface.h" -#include "api/scoped_refptr.h" -#include "modules/video_capture/video_capture.h" +#include "api/video/video_frame.h" +#include "api/video/video_sink_interface.h" #include "rtc_base/logging.h" -#include "rtc_base/thread.h" #include "test/test_video_capturer.h" namespace webrtc { diff --git a/test/mappable_native_buffer.cc b/test/mappable_native_buffer.cc index 8a2380959d..4a8f6ca8c0 100644 --- a/test/mappable_native_buffer.cc +++ b/test/mappable_native_buffer.cc @@ -10,13 +10,21 @@ #include "test/mappable_native_buffer.h" +#include +#include +#include + #include "absl/algorithm/container.h" +#include "api/array_view.h" +#include "api/make_ref_counted.h" +#include "api/scoped_refptr.h" #include "api/video/i420_buffer.h" #include "api/video/nv12_buffer.h" #include "api/video/video_frame.h" +#include "api/video/video_frame_buffer.h" #include "api/video/video_rotation.h" -#include "common_video/include/video_frame_buffer.h" #include "rtc_base/checks.h" +#include "rtc_base/synchronization/mutex.h" namespace webrtc { namespace test { diff --git a/test/mappable_native_buffer.h b/test/mappable_native_buffer.h index c2b4cec627..ddbc657ef4 100644 --- a/test/mappable_native_buffer.h +++ b/test/mappable_native_buffer.h @@ -11,14 +11,16 @@ #ifndef TEST_MAPPABLE_NATIVE_BUFFER_H_ #define TEST_MAPPABLE_NATIVE_BUFFER_H_ -#include +#include #include #include "api/array_view.h" +#include "api/scoped_refptr.h" #include "api/video/video_frame.h" -#include "common_video/include/video_frame_buffer.h" +#include "api/video/video_frame_buffer.h" #include "rtc_base/ref_counted_object.h" #include "rtc_base/synchronization/mutex.h" +#include "rtc_base/thread_annotations.h" namespace webrtc { namespace test { diff --git a/test/mock_audio_decoder.h b/test/mock_audio_decoder.h index 8f44bf891d..abc3246359 100644 --- a/test/mock_audio_decoder.h +++ b/test/mock_audio_decoder.h @@ -11,6 +11,9 @@ #ifndef TEST_MOCK_AUDIO_DECODER_H_ #define TEST_MOCK_AUDIO_DECODER_H_ +#include +#include + #include "api/audio_codecs/audio_decoder.h" #include "test/gmock.h" diff --git a/test/mock_audio_decoder_factory.h b/test/mock_audio_decoder_factory.h index d14a7dcc6d..f5d6790136 100644 --- a/test/mock_audio_decoder_factory.h +++ b/test/mock_audio_decoder_factory.h @@ -12,10 +12,13 @@ #define TEST_MOCK_AUDIO_DECODER_FACTORY_H_ #include +#include #include +#include "api/audio_codecs/audio_codec_pair_id.h" +#include "api/audio_codecs/audio_decoder.h" #include "api/audio_codecs/audio_decoder_factory.h" -#include "api/audio_codecs/builtin_audio_decoder_factory.h" +#include "api/audio_codecs/audio_format.h" #include "api/environment/environment.h" #include "api/make_ref_counted.h" #include "api/scoped_refptr.h" diff --git a/test/mock_audio_encoder.cc b/test/mock_audio_encoder.cc index 74f6a29f5b..817bcc4c96 100644 --- a/test/mock_audio_encoder.cc +++ b/test/mock_audio_encoder.cc @@ -10,6 +10,14 @@ #include "test/mock_audio_encoder.h" +#include +#include + +#include "api/array_view.h" +#include "api/audio_codecs/audio_encoder.h" +#include "rtc_base/buffer.h" +#include "rtc_base/checks.h" + namespace webrtc { MockAudioEncoder::MockAudioEncoder() = default; diff --git a/test/mock_audio_encoder.h b/test/mock_audio_encoder.h index df0089653b..f643c67315 100644 --- a/test/mock_audio_encoder.h +++ b/test/mock_audio_encoder.h @@ -11,10 +11,17 @@ #ifndef TEST_MOCK_AUDIO_ENCODER_H_ #define TEST_MOCK_AUDIO_ENCODER_H_ +#include +#include +#include #include +#include #include "api/array_view.h" #include "api/audio_codecs/audio_encoder.h" +#include "api/units/data_rate.h" +#include "api/units/time_delta.h" +#include "rtc_base/buffer.h" #include "test/gmock.h" namespace webrtc { diff --git a/test/mock_audio_encoder_factory.h b/test/mock_audio_encoder_factory.h index 0d3c96a3f8..d978f51ed0 100644 --- a/test/mock_audio_encoder_factory.h +++ b/test/mock_audio_encoder_factory.h @@ -12,9 +12,12 @@ #define TEST_MOCK_AUDIO_ENCODER_FACTORY_H_ #include +#include #include +#include "api/audio_codecs/audio_encoder.h" #include "api/audio_codecs/audio_encoder_factory.h" +#include "api/audio_codecs/audio_format.h" #include "api/environment/environment.h" #include "api/make_ref_counted.h" #include "api/scoped_refptr.h" diff --git a/test/network/cross_traffic.cc b/test/network/cross_traffic.cc index d35a83014d..3d8d5776dd 100644 --- a/test/network/cross_traffic.cc +++ b/test/network/cross_traffic.cc @@ -10,8 +10,6 @@ #include "test/network/cross_traffic.h" -#include - #include #include #include diff --git a/test/network/emulated_turn_server.cc b/test/network/emulated_turn_server.cc index fe001d6f8d..37e0a424fa 100644 --- a/test/network/emulated_turn_server.cc +++ b/test/network/emulated_turn_server.cc @@ -35,8 +35,8 @@ namespace { -static const char kTestRealm[] = "example.org"; -static const char kTestSoftware[] = "TestTurnServer"; +const char kTestRealm[] = "example.org"; +const char kTestSoftware[] = "TestTurnServer"; // A wrapper class for webrtc::TurnServer to allocate sockets. class PacketSocketFactoryWrapper : public webrtc::PacketSocketFactory { @@ -93,7 +93,7 @@ class EmulatedTURNServer::AsyncPacketSocketWrapper : public AsyncPacketSocket { : turn_server_(turn_server), endpoint_(endpoint), local_address_(SocketAddress(endpoint_->GetPeerLocalAddress(), port)) {} - ~AsyncPacketSocketWrapper() { turn_server_->Unbind(local_address_); } + ~AsyncPacketSocketWrapper() override { turn_server_->Unbind(local_address_); } SocketAddress GetLocalAddress() const override { return local_address_; } SocketAddress GetRemoteAddress() const override { return SocketAddress(); } diff --git a/test/network/fake_network_socket_server.cc b/test/network/fake_network_socket_server.cc index 26e8911d98..910da6129e 100644 --- a/test/network/fake_network_socket_server.cc +++ b/test/network/fake_network_socket_server.cc @@ -31,6 +31,7 @@ #include "rtc_base/event.h" #include "rtc_base/ip_address.h" #include "rtc_base/logging.h" +#include "rtc_base/net_helpers.h" #include "rtc_base/socket.h" #include "rtc_base/socket_address.h" #include "rtc_base/synchronization/mutex.h" diff --git a/test/network/network_emulation.cc b/test/network/network_emulation.cc index 3dfe3d0035..c46b36f733 100644 --- a/test/network/network_emulation.cc +++ b/test/network/network_emulation.cc @@ -10,10 +10,9 @@ #include "test/network/network_emulation.h" -#include - #include #include +#include #include #include #include diff --git a/test/network/network_emulation_pc_unittest.cc b/test/network/network_emulation_pc_unittest.cc index 376471bbfc..5e62cc383c 100644 --- a/test/network/network_emulation_pc_unittest.cc +++ b/test/network/network_emulation_pc_unittest.cc @@ -50,7 +50,7 @@ constexpr int kSamplingFrequency = 48000; constexpr char kSignalThreadName[] = "signaling_thread"; bool AddIceCandidates(PeerConnectionWrapper* peer, - std::vector candidates) { + std::vector candidates) { bool success = true; for (const auto candidate : candidates) { if (!peer->pc()->AddIceCandidate(candidate)) { diff --git a/test/null_platform_renderer.cc b/test/null_platform_renderer.cc index 7ea604ead8..db768409f9 100644 --- a/test/null_platform_renderer.cc +++ b/test/null_platform_renderer.cc @@ -8,6 +8,8 @@ * be found in the AUTHORS file in the root of the source tree. */ +#include + #include "test/video_renderer.h" namespace webrtc { diff --git a/test/pc/e2e/BUILD.gn b/test/pc/e2e/BUILD.gn index 7899fc1465..4c23f1574c 100644 --- a/test/pc/e2e/BUILD.gn +++ b/test/pc/e2e/BUILD.gn @@ -48,10 +48,14 @@ if (!build_with_chromium) { "echo/echo_emulation.h", ] deps = [ + "../../../api:array_view", "../../../api:sequence_checker", "../../../api/test/pclf:media_configuration", "../../../modules/audio_device:test_audio_device_module", + "../../../rtc_base:buffer", + "../../../rtc_base:checks", "../../../rtc_base:logging", + "../../../rtc_base:macromagic", "../../../rtc_base:swap_queue", ] } @@ -110,7 +114,6 @@ if (!build_with_chromium) { "../../../api/environment", "../../../api/environment:environment_factory", "../../../api/rtc_event_log:rtc_event_log_factory", - "../../../api/task_queue", "../../../api/test/pclf:media_configuration", "../../../api/test/pclf:media_quality_test_params", "../../../api/test/pclf:peer_configurer", @@ -134,9 +137,11 @@ if (!build_with_chromium) { sources = [ "media/test_video_capturer_video_track_source.h" ] deps = [ "../..:test_video_capturer", + "../../../api:media_stream_interface", "../../../api:sequence_checker", "../../../api/test/video:test_video_track_source", "../../../api/video:video_frame", + "../../../rtc_base:macromagic", ] } @@ -152,16 +157,27 @@ if (!build_with_chromium) { "../..:fileutils", "../..:frame_generator_capturer", "../..:platform_video_capturer", + "../..:test_video_capturer", "../../../api:create_frame_generator", "../../../api:frame_generator_api", + "../../../api:make_ref_counted", "../../../api:media_stream_interface", + "../../../api:rtc_error", + "../../../api:rtp_parameters", + "../../../api:rtp_sender_interface", + "../../../api:scoped_refptr", "../../../api:sequence_checker", + "../../../api/task_queue", "../../../api/test/pclf:media_configuration", + "../../../api/test/pclf:media_quality_test_params", "../../../api/test/pclf:peer_configurer", "../../../api/test/video:test_video_track_source", "../../../api/video:video_frame", "../../../pc:session_description", "../../../pc:video_track_source", + "../../../rtc_base:checks", + "../../../rtc_base:logging", + "../../../system_wrappers", "analyzer/video:video_quality_analyzer_injection_helper", ] } @@ -204,6 +220,7 @@ if (!build_with_chromium) { "../../../rtc_base:checks", "../../../rtc_base:criticalsection", "../../../rtc_base:logging", + "../../../rtc_base:macromagic", "../../../rtc_base:task_queue_for_test", "../../../rtc_base/synchronization:mutex", "../../../rtc_base/task_utils:repeating_task", @@ -233,9 +250,6 @@ if (!build_with_chromium) { ":test_peer", ":test_peer_factory", ":test_video_capturer_video_track_source", - "../..:field_trial", - "../..:fileutils", - "../..:perf_test", "../..:test_flags", "../..:test_support", "../../../api:audio_quality_analyzer_api", @@ -262,23 +276,16 @@ if (!build_with_chromium) { "../../../api/video:video_frame", "../../../media:media_constants", "../../../pc:pc_test_utils", - "../../../pc:sdp_utils", "../../../rtc_base:checks", "../../../rtc_base:cpu_info", - "../../../rtc_base:gunit_helpers", "../../../rtc_base:logging", "../../../rtc_base:macromagic", - "../../../rtc_base:safe_conversions", - "../../../rtc_base:stringutils", "../../../rtc_base:task_queue_for_test", "../../../rtc_base:threading", "../../../rtc_base/synchronization:mutex", "../../../rtc_base/task_utils:repeating_task", - "../../../system_wrappers", - "../../../system_wrappers:field_trial", "analyzer/video:default_video_quality_analyzer", "analyzer/video:single_process_encoded_image_data_injector", - "analyzer/video:video_frame_tracking_id_injector", "analyzer/video:video_quality_analyzer_injection_helper", "analyzer/video:video_quality_metrics_reporter", "//third_party/abseil-cpp/absl/flags:flag", @@ -310,18 +317,23 @@ if (!build_with_chromium) { "../../../api:create_network_emulation_manager", "../../../api:create_peer_connection_quality_test_frame_generator", "../../../api:create_peerconnection_quality_test_fixture", + "../../../api:function_view", "../../../api:libjingle_peerconnection_api", "../../../api:media_stream_interface", "../../../api:network_emulation_manager_api", "../../../api:peer_connection_quality_test_fixture_api", + "../../../api:rtp_parameters", "../../../api:scoped_refptr", "../../../api:simulated_network_api", "../../../api/audio_codecs:builtin_audio_decoder_factory", "../../../api/audio_codecs:builtin_audio_encoder_factory", "../../../api/test/metrics:global_metrics_logger_and_exporter", + "../../../api/test/network_emulation", "../../../api/test/pclf:media_configuration", "../../../api/test/pclf:media_quality_test_params", "../../../api/test/pclf:peer_configurer", + "../../../api/transport:bitrate_settings", + "../../../api/units:time_delta", "../../../api/video_codecs:builtin_video_decoder_factory", "../../../api/video_codecs:builtin_video_encoder_factory", "../../../media:media_constants", @@ -390,12 +402,17 @@ if (!build_with_chromium) { "../../../api:create_peer_connection_quality_test_frame_generator", "../../../api:network_emulation_manager_api", "../../../api:peer_connection_quality_test_fixture_api", + "../../../api:simulated_network_api", + "../../../api/test/metrics:metric", "../../../api/test/metrics:metrics_logger", "../../../api/test/metrics:stdout_metrics_exporter", + "../../../api/test/network_emulation", "../../../api/test/pclf:media_configuration", "../../../api/test/pclf:media_quality_test_params", "../../../api/test/pclf:peer_configurer", + "../../../api/units:data_rate", "../../../api/units:time_delta", + "../../../media:media_constants", "//third_party/abseil-cpp/absl/strings:string_view", ] } @@ -412,11 +429,13 @@ if (!build_with_chromium) { "../../../api:network_emulation_manager_api", "../../../api:peer_connection_quality_test_fixture_api", "../../../api/test/metrics:global_metrics_logger_and_exporter", + "../../../api/test/network_emulation", "../../../api/test/pclf:media_configuration", "../../../api/test/pclf:media_quality_test_params", "../../../api/test/pclf:peer_configurer", "../../../api/units:time_delta", "../../../rtc_base:timeutils", + "//third_party/abseil-cpp/absl/strings:string_view", ] } @@ -436,11 +455,14 @@ if (!build_with_chromium) { ":stats_provider", ":test_peer", "../../../api:libjingle_peerconnection_api", + "../../../api:make_ref_counted", "../../../api:rtc_stats_api", + "../../../api:scoped_refptr", "../../../api:stats_observer_interface", "../../../rtc_base:logging", "../../../rtc_base:macromagic", "../../../rtc_base/synchronization:mutex", + "//third_party/abseil-cpp/absl/strings:string_view", ] } @@ -449,8 +471,12 @@ if (!build_with_chromium) { sources = [ "stats_poller_test.cc" ] deps = [ ":stats_poller", + ":stats_provider", "../..:test_support", "../../../api:rtc_stats_api", + "../../../api:scoped_refptr", + "../../../api:stats_observer_interface", + "//third_party/abseil-cpp/absl/strings:string_view", ] } } @@ -463,6 +489,7 @@ if (!build_with_chromium) { deps = [ "../../../api:sequence_checker", "../../../api:track_id_stream_info_map", + "../../../rtc_base:checks", "../../../rtc_base:macromagic", "//third_party/abseil-cpp/absl/strings:string_view", ] @@ -492,6 +519,7 @@ if (!build_with_chromium) { "../../../rtc_base:checks", "../../../rtc_base:criticalsection", "../../../rtc_base:logging", + "../../../rtc_base:macromagic", "../../../rtc_base:rtc_numerics", "../../../rtc_base/synchronization:mutex", "//third_party/abseil-cpp/absl/flags:flag", @@ -510,12 +538,16 @@ if (!build_with_chromium) { "../../../api:network_emulation_manager_api", "../../../api:peer_connection_quality_test_fixture_api", "../../../api:rtc_stats_api", + "../../../api:scoped_refptr", "../../../api:track_id_stream_info_map", "../../../api/test/metrics:metric", "../../../api/test/metrics:metrics_logger", + "../../../api/test/network_emulation", "../../../api/units:data_size", + "../../../api/units:time_delta", "../../../rtc_base:checks", "../../../rtc_base:criticalsection", + "../../../rtc_base:macromagic", "../../../rtc_base:rtc_event", "../../../rtc_base/synchronization:mutex", "../../../system_wrappers:field_trial", @@ -556,6 +588,7 @@ if (!build_with_chromium) { "../../../rtc_base:stringutils", "../../../rtc_base/synchronization:mutex", "../../../rtc_base/system:no_unique_address", + "../../../system_wrappers", "../../../system_wrappers:field_trial", "//third_party/abseil-cpp/absl/flags:flag", "//third_party/abseil-cpp/absl/strings:string_view", @@ -583,6 +616,7 @@ if (!build_with_chromium) { "../../../api/units:timestamp", "../../../rtc_base:checks", "../../../rtc_base:criticalsection", + "../../../rtc_base:macromagic", "../../../rtc_base:rtc_event", "../../../rtc_base:rtc_numerics", "../../../rtc_base/synchronization:mutex", diff --git a/test/pc/e2e/analyzer/audio/default_audio_quality_analyzer.h b/test/pc/e2e/analyzer/audio/default_audio_quality_analyzer.h index 6e7487d14e..4ba5138d0a 100644 --- a/test/pc/e2e/analyzer/audio/default_audio_quality_analyzer.h +++ b/test/pc/e2e/analyzer/audio/default_audio_quality_analyzer.h @@ -11,16 +11,20 @@ #ifndef TEST_PC_E2E_ANALYZER_AUDIO_DEFAULT_AUDIO_QUALITY_ANALYZER_H_ #define TEST_PC_E2E_ANALYZER_AUDIO_DEFAULT_AUDIO_QUALITY_ANALYZER_H_ +#include #include #include #include "absl/strings/string_view.h" #include "api/numerics/samples_stats_counter.h" +#include "api/scoped_refptr.h" +#include "api/stats/rtc_stats_report.h" #include "api/test/audio_quality_analyzer_interface.h" #include "api/test/metrics/metrics_logger.h" #include "api/test/track_id_stream_info_map.h" #include "api/units/time_delta.h" #include "rtc_base/synchronization/mutex.h" +#include "rtc_base/thread_annotations.h" namespace webrtc { namespace webrtc_pc_e2e { diff --git a/test/pc/e2e/analyzer/video/BUILD.gn b/test/pc/e2e/analyzer/video/BUILD.gn index 8eb5c1acfb..9d0ab440a4 100644 --- a/test/pc/e2e/analyzer/video/BUILD.gn +++ b/test/pc/e2e/analyzer/video/BUILD.gn @@ -66,6 +66,7 @@ rtc_library("video_dumping") { "../../../..:video_frame_writer", "../../../../../api/test/video:video_frame_writer", "../../../../../api/video:video_frame", + "../../../../../rtc_base:checks", "../../../../../rtc_base:logging", "../../../../../system_wrappers", "//third_party/abseil-cpp/absl/strings:string_view", @@ -90,6 +91,7 @@ rtc_library("single_process_encoded_image_data_injector") { ":encoded_image_data_injector_api", "../../../../../api/video:encoded_image", "../../../../../rtc_base:checks", + "../../../../../rtc_base:macromagic", "../../../../../rtc_base/synchronization:mutex", "//third_party/abseil-cpp/absl/memory", ] @@ -116,7 +118,10 @@ rtc_library("simulcast_dummy_buffer_helper") { "simulcast_dummy_buffer_helper.cc", "simulcast_dummy_buffer_helper.h", ] - deps = [ "../../../../../api/video:video_frame" ] + deps = [ + "../../../../../api:scoped_refptr", + "../../../../../api/video:video_frame", + ] } rtc_library("quality_analyzing_video_decoder") { @@ -128,13 +133,16 @@ rtc_library("quality_analyzing_video_decoder") { deps = [ ":encoded_image_data_injector_api", ":simulcast_dummy_buffer_helper", + "../../../../../api:scoped_refptr", "../../../../../api:video_quality_analyzer_api", "../../../../../api/environment", "../../../../../api/video:encoded_image", "../../../../../api/video:video_frame", "../../../../../api/video_codecs:video_codecs_api", "../../../../../modules/video_coding:video_codec_interface", + "../../../../../rtc_base:checks", "../../../../../rtc_base:logging", + "../../../../../rtc_base:macromagic", "../../../../../rtc_base/synchronization:mutex", "//third_party/abseil-cpp/absl/strings:string_view", ] @@ -148,14 +156,22 @@ rtc_library("quality_analyzing_video_encoder") { ] deps = [ ":encoded_image_data_injector_api", + "../../../../../api:fec_controller_api", "../../../../../api:video_quality_analyzer_api", "../../../../../api/environment", "../../../../../api/test/pclf:media_configuration", + "../../../../../api/video:encoded_image", + "../../../../../api/video:video_bitrate_allocation", + "../../../../../api/video:video_codec_constants", "../../../../../api/video:video_frame", + "../../../../../api/video:video_frame_type", "../../../../../api/video_codecs:video_codecs_api", "../../../../../modules/video_coding:video_codec_interface", "../../../../../modules/video_coding/svc:scalability_mode_util", + "../../../../../rtc_base:checks", "../../../../../rtc_base:logging", + "../../../../../rtc_base:macromagic", + "../../../../../rtc_base:safe_conversions", "../../../../../rtc_base/synchronization:mutex", "//third_party/abseil-cpp/absl/strings:string_view", ] @@ -188,8 +204,12 @@ rtc_library("example_video_quality_analyzer") { "../../../../../api:video_quality_analyzer_api", "../../../../../api/video:encoded_image", "../../../../../api/video:video_frame", + "../../../../../api/video_codecs:video_codecs_api", + "../../../../../rtc_base:checks", "../../../../../rtc_base:logging", + "../../../../../rtc_base:macromagic", "../../../../../rtc_base/synchronization:mutex", + "//third_party/abseil-cpp/absl/strings:string_view", ] } @@ -234,6 +254,7 @@ rtc_library("default_video_quality_analyzer_internal") { "../../../../../api/video:video_frame_type", "../../../../../common_video", "../../../../../rtc_base:checks", + "../../../../../rtc_base:macromagic", "../../../../../rtc_base:platform_thread", "../../../../../rtc_base:rtc_base_tests_utils", "../../../../../rtc_base:rtc_event", @@ -298,7 +319,9 @@ if (!build_with_chromium) { "../..:metric_metadata_keys", "../../../..:test_flags", "../../../../../api:array_view", + "../../../../../api:rtc_stats_api", "../../../../../api:rtp_packet_info", + "../../../../../api:scoped_refptr", "../../../../../api:video_quality_analyzer_api", "../../../../../api/numerics", "../../../../../api/test/metrics:metric", @@ -375,9 +398,12 @@ if (!build_with_chromium) { "../../../..:video_frame_writer", "../../../..:video_test_common", "../../../../../api:array_view", + "../../../../../api:rtc_stats_api", + "../../../../../api:scoped_refptr", "../../../../../api:stats_observer_interface", "../../../../../api:video_quality_analyzer_api", "../../../../../api/test/pclf:media_configuration", + "../../../../../api/test/video:video_frame_writer", "../../../../../api/video:video_frame", "../../../../../api/video_codecs:video_codecs_api", "../../../../../rtc_base:checks", @@ -404,6 +430,7 @@ rtc_library("default_video_quality_analyzer_shared") { "../../../../../api/units:timestamp", "../../../../../rtc_base:checks", "../../../../../rtc_base:stringutils", + "//third_party/abseil-cpp/absl/strings:string_view", ] } @@ -414,6 +441,7 @@ if (rtc_include_tests) { deps = [ ":simulcast_dummy_buffer_helper", "../../../..:test_support", + "../../../../../api:scoped_refptr", "../../../../../api/video:video_frame", "../../../../../rtc_base:random", ] @@ -424,6 +452,7 @@ if (rtc_include_tests) { sources = [ "analyzing_video_sink_test.cc" ] deps = [ ":analyzing_video_sink", + ":analyzing_video_sinks_helper", ":example_video_quality_analyzer", "../../../..:fileutils", "../../../..:test_support", @@ -450,6 +479,8 @@ if (rtc_include_tests) { ":analyzing_video_sinks_helper", "../../../..:test_support", "../../../../../api/test/pclf:media_configuration", + "../../../../../api/test/video:video_frame_writer", + "../../../../../api/video:video_frame", ] } @@ -461,7 +492,13 @@ if (rtc_include_tests) { ":default_video_quality_analyzer_shared", "../../../..:test_support", "../../../../../api:create_frame_generator", + "../../../../../api:frame_generator_api", + "../../../../../api/numerics", + "../../../../../api/units:data_size", + "../../../../../api/units:time_delta", "../../../../../api/units:timestamp", + "../../../../../api/video:video_frame", + "../../../../../api/video:video_frame_type", "../../../../../rtc_base:stringutils", "../../../../../system_wrappers", ] @@ -504,9 +541,14 @@ if (rtc_include_tests) { ":default_video_quality_analyzer", ":default_video_quality_analyzer_shared", "../../../..:test_support", + "../../../../../api:array_view", "../../../../../api:create_frame_generator", + "../../../../../api:frame_generator_api", "../../../../../api:rtp_packet_info", + "../../../../../api:scoped_refptr", "../../../../../api:time_controller", + "../../../../../api:video_quality_analyzer_api", + "../../../../../api/numerics", "../../../../../api/test/metrics:global_metrics_logger_and_exporter", "../../../../../api/units:time_delta", "../../../../../api/units:timestamp", @@ -516,7 +558,9 @@ if (rtc_include_tests) { "../../../../../rtc_base:stringutils", "../../../../../rtc_base:threading", "../../../../../rtc_tools:video_quality_analysis", + "../../../../../system_wrappers", "../../../../time_controller", + "//third_party/abseil-cpp/absl/strings:string_view", ] } @@ -559,6 +603,7 @@ if (rtc_include_tests) { "../../../..:video_frame_writer", "../../../..:video_test_support", "../../../../../api:scoped_refptr", + "../../../../../api/test/video:video_frame_writer", "../../../../../api/video:video_frame", "../../../../../rtc_base:random", ] @@ -568,10 +613,13 @@ if (rtc_include_tests) { testonly = true sources = [ "single_process_encoded_image_data_injector_unittest.cc" ] deps = [ + ":encoded_image_data_injector_api", ":single_process_encoded_image_data_injector", "../../../..:test_support", + "../../../../../api:scoped_refptr", "../../../../../api/video:encoded_image", "../../../../../rtc_base:buffer", + "../../../../../rtc_base:checks", ] } @@ -579,8 +627,10 @@ if (rtc_include_tests) { testonly = true sources = [ "video_frame_tracking_id_injector_unittest.cc" ] deps = [ + ":encoded_image_data_injector_api", ":video_frame_tracking_id_injector", "../../../..:test_support", + "../../../../../api:scoped_refptr", "../../../../../api/video:encoded_image", "../../../../../rtc_base:buffer", ] diff --git a/test/pc/e2e/analyzer/video/analyzing_video_sink_test.cc b/test/pc/e2e/analyzer/video/analyzing_video_sink_test.cc index 078fb18fd0..7555ee4ead 100644 --- a/test/pc/e2e/analyzer/video/analyzing_video_sink_test.cc +++ b/test/pc/e2e/analyzer/video/analyzing_video_sink_test.cc @@ -9,8 +9,9 @@ */ #include "test/pc/e2e/analyzer/video/analyzing_video_sink.h" -#include - +#include +#include +#include #include #include #include @@ -24,11 +25,12 @@ #include "api/units/timestamp.h" #include "api/video/i420_buffer.h" #include "api/video/video_frame.h" +#include "api/video/video_frame_buffer.h" #include "common_video/libyuv/include/webrtc_libyuv.h" -#include "rtc_base/time_utils.h" #include "system_wrappers/include/clock.h" #include "test/gmock.h" #include "test/gtest.h" +#include "test/pc/e2e/analyzer/video/analyzing_video_sinks_helper.h" #include "test/pc/e2e/analyzer/video/example_video_quality_analyzer.h" #include "test/testsupport/file_utils.h" #include "test/testsupport/frame_reader.h" diff --git a/test/pc/e2e/analyzer/video/analyzing_video_sinks_helper.cc b/test/pc/e2e/analyzer/video/analyzing_video_sinks_helper.cc index cf4b1bb583..f4ac8f8458 100644 --- a/test/pc/e2e/analyzer/video/analyzing_video_sinks_helper.cc +++ b/test/pc/e2e/analyzer/video/analyzing_video_sinks_helper.cc @@ -10,6 +10,7 @@ #include "test/pc/e2e/analyzer/video/analyzing_video_sinks_helper.h" #include +#include #include #include #include diff --git a/test/pc/e2e/analyzer/video/analyzing_video_sinks_helper_test.cc b/test/pc/e2e/analyzer/video/analyzing_video_sinks_helper_test.cc index 792f44f1d4..90bf09b4c7 100644 --- a/test/pc/e2e/analyzer/video/analyzing_video_sinks_helper_test.cc +++ b/test/pc/e2e/analyzer/video/analyzing_video_sinks_helper_test.cc @@ -15,6 +15,8 @@ #include #include "api/test/pclf/media_configuration.h" +#include "api/test/video/video_frame_writer.h" +#include "api/video/video_frame.h" #include "test/gmock.h" #include "test/gtest.h" diff --git a/test/pc/e2e/analyzer/video/default_video_quality_analyzer.h b/test/pc/e2e/analyzer/video/default_video_quality_analyzer.h index 943cf8cbcf..0e041431ed 100644 --- a/test/pc/e2e/analyzer/video/default_video_quality_analyzer.h +++ b/test/pc/e2e/analyzer/video/default_video_quality_analyzer.h @@ -11,9 +11,8 @@ #ifndef TEST_PC_E2E_ANALYZER_VIDEO_DEFAULT_VIDEO_QUALITY_ANALYZER_H_ #define TEST_PC_E2E_ANALYZER_VIDEO_DEFAULT_VIDEO_QUALITY_ANALYZER_H_ -#include +#include #include -#include #include #include #include @@ -21,13 +20,16 @@ #include #include +#include "absl/strings/string_view.h" #include "api/array_view.h" +#include "api/scoped_refptr.h" +#include "api/stats/rtc_stats_report.h" #include "api/test/metrics/metrics_logger.h" #include "api/test/video_quality_analyzer_interface.h" -#include "api/units/data_size.h" #include "api/units/timestamp.h" #include "api/video/encoded_image.h" #include "api/video/video_frame.h" +#include "api/video_codecs/video_encoder.h" #include "rtc_base/synchronization/mutex.h" #include "rtc_base/thread_annotations.h" #include "system_wrappers/include/clock.h" diff --git a/test/pc/e2e/analyzer/video/default_video_quality_analyzer_cpu_measurer.h b/test/pc/e2e/analyzer/video/default_video_quality_analyzer_cpu_measurer.h index 28ca48a725..a3bf38a23e 100644 --- a/test/pc/e2e/analyzer/video/default_video_quality_analyzer_cpu_measurer.h +++ b/test/pc/e2e/analyzer/video/default_video_quality_analyzer_cpu_measurer.h @@ -11,7 +11,10 @@ #ifndef TEST_PC_E2E_ANALYZER_VIDEO_DEFAULT_VIDEO_QUALITY_ANALYZER_CPU_MEASURER_H_ #define TEST_PC_E2E_ANALYZER_VIDEO_DEFAULT_VIDEO_QUALITY_ANALYZER_CPU_MEASURER_H_ +#include + #include "rtc_base/synchronization/mutex.h" +#include "rtc_base/thread_annotations.h" namespace webrtc { diff --git a/test/pc/e2e/analyzer/video/default_video_quality_analyzer_frame_in_flight.cc b/test/pc/e2e/analyzer/video/default_video_quality_analyzer_frame_in_flight.cc index 6dbdfdc58e..eade0fd1b1 100644 --- a/test/pc/e2e/analyzer/video/default_video_quality_analyzer_frame_in_flight.cc +++ b/test/pc/e2e/analyzer/video/default_video_quality_analyzer_frame_in_flight.cc @@ -10,17 +10,23 @@ #include "test/pc/e2e/analyzer/video/default_video_quality_analyzer_frame_in_flight.h" +#include +#include #include +#include #include #include #include +#include "api/numerics/samples_stats_counter.h" #include "api/units/data_size.h" #include "api/units/time_delta.h" #include "api/units/timestamp.h" #include "api/video/video_frame.h" #include "api/video/video_frame_type.h" +#include "rtc_base/checks.h" #include "test/pc/e2e/analyzer/video/default_video_quality_analyzer_internal_shared_objects.h" +#include "test/pc/e2e/analyzer/video/default_video_quality_analyzer_shared_objects.h" namespace webrtc { namespace { diff --git a/test/pc/e2e/analyzer/video/default_video_quality_analyzer_frame_in_flight.h b/test/pc/e2e/analyzer/video/default_video_quality_analyzer_frame_in_flight.h index c116cf69b2..b384d0bfeb 100644 --- a/test/pc/e2e/analyzer/video/default_video_quality_analyzer_frame_in_flight.h +++ b/test/pc/e2e/analyzer/video/default_video_quality_analyzer_frame_in_flight.h @@ -11,11 +11,12 @@ #ifndef TEST_PC_E2E_ANALYZER_VIDEO_DEFAULT_VIDEO_QUALITY_ANALYZER_FRAME_IN_FLIGHT_H_ #define TEST_PC_E2E_ANALYZER_VIDEO_DEFAULT_VIDEO_QUALITY_ANALYZER_FRAME_IN_FLIGHT_H_ +#include +#include #include #include #include #include -#include #include #include "api/numerics/samples_stats_counter.h" @@ -25,6 +26,7 @@ #include "api/video/video_frame.h" #include "api/video/video_frame_type.h" #include "test/pc/e2e/analyzer/video/default_video_quality_analyzer_internal_shared_objects.h" +#include "test/pc/e2e/analyzer/video/default_video_quality_analyzer_shared_objects.h" namespace webrtc { diff --git a/test/pc/e2e/analyzer/video/default_video_quality_analyzer_frames_comparator.cc b/test/pc/e2e/analyzer/video/default_video_quality_analyzer_frames_comparator.cc index de277e5983..a8c537231b 100644 --- a/test/pc/e2e/analyzer/video/default_video_quality_analyzer_frames_comparator.cc +++ b/test/pc/e2e/analyzer/video/default_video_quality_analyzer_frames_comparator.cc @@ -11,6 +11,7 @@ #include "test/pc/e2e/analyzer/video/default_video_quality_analyzer_frames_comparator.h" #include +#include #include #include #include @@ -18,8 +19,12 @@ #include #include "api/array_view.h" +#include "api/numerics/samples_stats_counter.h" #include "api/scoped_refptr.h" -#include "api/video/i420_buffer.h" +#include "api/units/time_delta.h" +#include "api/units/timestamp.h" +#include "api/video/video_frame.h" +#include "api/video/video_frame_buffer.h" #include "api/video/video_frame_type.h" #include "common_video/libyuv/include/webrtc_libyuv.h" #include "rtc_base/checks.h" diff --git a/test/pc/e2e/analyzer/video/default_video_quality_analyzer_frames_comparator.h b/test/pc/e2e/analyzer/video/default_video_quality_analyzer_frames_comparator.h index e64642716b..8b7bab6555 100644 --- a/test/pc/e2e/analyzer/video/default_video_quality_analyzer_frames_comparator.h +++ b/test/pc/e2e/analyzer/video/default_video_quality_analyzer_frames_comparator.h @@ -11,15 +11,22 @@ #ifndef TEST_PC_E2E_ANALYZER_VIDEO_DEFAULT_VIDEO_QUALITY_ANALYZER_FRAMES_COMPARATOR_H_ #define TEST_PC_E2E_ANALYZER_VIDEO_DEFAULT_VIDEO_QUALITY_ANALYZER_FRAMES_COMPARATOR_H_ +#include +#include #include #include +#include #include #include #include "api/array_view.h" +#include "api/numerics/samples_stats_counter.h" +#include "api/units/timestamp.h" +#include "api/video/video_frame.h" #include "rtc_base/event.h" #include "rtc_base/platform_thread.h" #include "rtc_base/synchronization/mutex.h" +#include "rtc_base/thread_annotations.h" #include "system_wrappers/include/clock.h" #include "test/pc/e2e/analyzer/video/default_video_quality_analyzer_cpu_measurer.h" #include "test/pc/e2e/analyzer/video/default_video_quality_analyzer_internal_shared_objects.h" diff --git a/test/pc/e2e/analyzer/video/default_video_quality_analyzer_frames_comparator_test.cc b/test/pc/e2e/analyzer/video/default_video_quality_analyzer_frames_comparator_test.cc index 9540840717..f670576bf6 100644 --- a/test/pc/e2e/analyzer/video/default_video_quality_analyzer_frames_comparator_test.cc +++ b/test/pc/e2e/analyzer/video/default_video_quality_analyzer_frames_comparator_test.cc @@ -10,17 +10,29 @@ #include "test/pc/e2e/analyzer/video/default_video_quality_analyzer_frames_comparator.h" +#include +#include #include +#include +#include #include +#include #include +#include "api/numerics/samples_stats_counter.h" #include "api/test/create_frame_generator.h" +#include "api/test/frame_generator_interface.h" +#include "api/units/data_size.h" +#include "api/units/time_delta.h" #include "api/units/timestamp.h" +#include "api/video/video_frame.h" +#include "api/video/video_frame_type.h" #include "rtc_base/strings/string_builder.h" #include "system_wrappers/include/clock.h" #include "test/gmock.h" #include "test/gtest.h" #include "test/pc/e2e/analyzer/video/default_video_quality_analyzer_cpu_measurer.h" +#include "test/pc/e2e/analyzer/video/default_video_quality_analyzer_internal_shared_objects.h" #include "test/pc/e2e/analyzer/video/default_video_quality_analyzer_shared_objects.h" namespace webrtc { diff --git a/test/pc/e2e/analyzer/video/default_video_quality_analyzer_internal_shared_objects.cc b/test/pc/e2e/analyzer/video/default_video_quality_analyzer_internal_shared_objects.cc index 4689729f3e..c400f831b3 100644 --- a/test/pc/e2e/analyzer/video/default_video_quality_analyzer_internal_shared_objects.cc +++ b/test/pc/e2e/analyzer/video/default_video_quality_analyzer_internal_shared_objects.cc @@ -9,6 +9,10 @@ */ #include "test/pc/e2e/analyzer/video/default_video_quality_analyzer_internal_shared_objects.h" +#include +#include +#include + #include "api/video/video_frame.h" #include "rtc_base/strings/string_builder.h" diff --git a/test/pc/e2e/analyzer/video/default_video_quality_analyzer_internal_shared_objects.h b/test/pc/e2e/analyzer/video/default_video_quality_analyzer_internal_shared_objects.h index c6887488c7..46f529347e 100644 --- a/test/pc/e2e/analyzer/video/default_video_quality_analyzer_internal_shared_objects.h +++ b/test/pc/e2e/analyzer/video/default_video_quality_analyzer_internal_shared_objects.h @@ -11,14 +11,15 @@ #ifndef TEST_PC_E2E_ANALYZER_VIDEO_DEFAULT_VIDEO_QUALITY_ANALYZER_INTERNAL_SHARED_OBJECTS_H_ #define TEST_PC_E2E_ANALYZER_VIDEO_DEFAULT_VIDEO_QUALITY_ANALYZER_INTERNAL_SHARED_OBJECTS_H_ -#include +#include +#include +#include #include #include -#include -#include #include "api/numerics/samples_stats_counter.h" #include "api/units/data_size.h" +#include "api/units/time_delta.h" #include "api/units/timestamp.h" #include "api/video/video_frame.h" #include "api/video/video_frame_type.h" diff --git a/test/pc/e2e/analyzer/video/default_video_quality_analyzer_shared_objects.cc b/test/pc/e2e/analyzer/video/default_video_quality_analyzer_shared_objects.cc index 70345dd6bc..bfd329fb2a 100644 --- a/test/pc/e2e/analyzer/video/default_video_quality_analyzer_shared_objects.cc +++ b/test/pc/e2e/analyzer/video/default_video_quality_analyzer_shared_objects.cc @@ -11,9 +11,14 @@ #include #include +#include +#include #include +#include #include +#include +#include "absl/strings/string_view.h" #include "api/units/timestamp.h" #include "rtc_base/checks.h" #include "rtc_base/strings/string_builder.h" diff --git a/test/pc/e2e/analyzer/video/default_video_quality_analyzer_shared_objects.h b/test/pc/e2e/analyzer/video/default_video_quality_analyzer_shared_objects.h index 5f529dd4a3..272abba45b 100644 --- a/test/pc/e2e/analyzer/video/default_video_quality_analyzer_shared_objects.h +++ b/test/pc/e2e/analyzer/video/default_video_quality_analyzer_shared_objects.h @@ -13,7 +13,6 @@ #include #include -#include #include #include #include @@ -21,6 +20,7 @@ #include #include +#include "absl/strings/string_view.h" #include "api/numerics/samples_stats_counter.h" #include "api/units/time_delta.h" #include "api/units/timestamp.h" diff --git a/test/pc/e2e/analyzer/video/default_video_quality_analyzer_stream_state.cc b/test/pc/e2e/analyzer/video/default_video_quality_analyzer_stream_state.cc index 610230d02f..eca2af7206 100644 --- a/test/pc/e2e/analyzer/video/default_video_quality_analyzer_stream_state.cc +++ b/test/pc/e2e/analyzer/video/default_video_quality_analyzer_stream_state.cc @@ -10,9 +10,12 @@ #include "test/pc/e2e/analyzer/video/default_video_quality_analyzer_stream_state.h" +#include +#include #include #include #include +#include #include "api/units/timestamp.h" #include "rtc_base/checks.h" diff --git a/test/pc/e2e/analyzer/video/default_video_quality_analyzer_stream_state.h b/test/pc/e2e/analyzer/video/default_video_quality_analyzer_stream_state.h index 6004e8aab3..882daff8f2 100644 --- a/test/pc/e2e/analyzer/video/default_video_quality_analyzer_stream_state.h +++ b/test/pc/e2e/analyzer/video/default_video_quality_analyzer_stream_state.h @@ -11,6 +11,8 @@ #ifndef TEST_PC_E2E_ANALYZER_VIDEO_DEFAULT_VIDEO_QUALITY_ANALYZER_STREAM_STATE_H_ #define TEST_PC_E2E_ANALYZER_VIDEO_DEFAULT_VIDEO_QUALITY_ANALYZER_STREAM_STATE_H_ +#include +#include #include #include #include diff --git a/test/pc/e2e/analyzer/video/default_video_quality_analyzer_stream_state_test.cc b/test/pc/e2e/analyzer/video/default_video_quality_analyzer_stream_state_test.cc index 7a79452121..1de2f3b6a4 100644 --- a/test/pc/e2e/analyzer/video/default_video_quality_analyzer_stream_state_test.cc +++ b/test/pc/e2e/analyzer/video/default_video_quality_analyzer_stream_state_test.cc @@ -10,6 +10,7 @@ #include "test/pc/e2e/analyzer/video/default_video_quality_analyzer_stream_state.h" +#include #include #include "api/units/timestamp.h" diff --git a/test/pc/e2e/analyzer/video/default_video_quality_analyzer_test.cc b/test/pc/e2e/analyzer/video/default_video_quality_analyzer_test.cc index 449247f3a7..53d46a6e77 100644 --- a/test/pc/e2e/analyzer/video/default_video_quality_analyzer_test.cc +++ b/test/pc/e2e/analyzer/video/default_video_quality_analyzer_test.cc @@ -11,24 +11,39 @@ #include "test/pc/e2e/analyzer/video/default_video_quality_analyzer.h" #include +#include +#include +#include #include #include +#include +#include +#include +#include #include +#include "absl/strings/string_view.h" +#include "api/array_view.h" +#include "api/numerics/samples_stats_counter.h" #include "api/rtp_packet_info.h" #include "api/rtp_packet_infos.h" +#include "api/scoped_refptr.h" #include "api/test/create_frame_generator.h" +#include "api/test/frame_generator_interface.h" #include "api/test/metrics/global_metrics_logger_and_exporter.h" #include "api/test/time_controller.h" +#include "api/test/video_quality_analyzer_interface.h" #include "api/units/time_delta.h" #include "api/units/timestamp.h" #include "api/video/encoded_image.h" #include "api/video/i420_buffer.h" #include "api/video/video_frame.h" +#include "api/video/video_frame_buffer.h" #include "common_video/libyuv/include/webrtc_libyuv.h" #include "rtc_base/strings/string_builder.h" #include "rtc_base/thread.h" #include "rtc_tools/frame_analyzer/video_geometry_aligner.h" +#include "system_wrappers/include/clock.h" #include "test/gmock.h" #include "test/gtest.h" #include "test/pc/e2e/analyzer/video/default_video_quality_analyzer_shared_objects.h" diff --git a/test/pc/e2e/analyzer/video/dvqa/BUILD.gn b/test/pc/e2e/analyzer/video/dvqa/BUILD.gn index fd250f4f73..26d3ad9228 100644 --- a/test/pc/e2e/analyzer/video/dvqa/BUILD.gn +++ b/test/pc/e2e/analyzer/video/dvqa/BUILD.gn @@ -71,6 +71,7 @@ rtc_library("frames_storage") { "../../../../../../api/units:time_delta", "../../../../../../api/units:timestamp", "../../../../../../api/video:video_frame", + "../../../../../../rtc_base:checks", "../../../../../../system_wrappers", ] } diff --git a/test/pc/e2e/analyzer/video/dvqa/frames_storage.cc b/test/pc/e2e/analyzer/video/dvqa/frames_storage.cc index 369295f3fa..ac582bad43 100644 --- a/test/pc/e2e/analyzer/video/dvqa/frames_storage.cc +++ b/test/pc/e2e/analyzer/video/dvqa/frames_storage.cc @@ -10,12 +10,14 @@ #include "test/pc/e2e/analyzer/video/dvqa/frames_storage.h" +#include #include #include #include #include "api/units/timestamp.h" #include "api/video/video_frame.h" +#include "rtc_base/checks.h" namespace webrtc { diff --git a/test/pc/e2e/analyzer/video/dvqa/frames_storage.h b/test/pc/e2e/analyzer/video/dvqa/frames_storage.h index 05012e6402..8a0a50cc99 100644 --- a/test/pc/e2e/analyzer/video/dvqa/frames_storage.h +++ b/test/pc/e2e/analyzer/video/dvqa/frames_storage.h @@ -11,6 +11,7 @@ #ifndef TEST_PC_E2E_ANALYZER_VIDEO_DVQA_FRAMES_STORAGE_H_ #define TEST_PC_E2E_ANALYZER_VIDEO_DVQA_FRAMES_STORAGE_H_ +#include #include #include #include diff --git a/test/pc/e2e/analyzer/video/dvqa/frames_storage_test.cc b/test/pc/e2e/analyzer/video/dvqa/frames_storage_test.cc index 23d4525140..2ab601b1f6 100644 --- a/test/pc/e2e/analyzer/video/dvqa/frames_storage_test.cc +++ b/test/pc/e2e/analyzer/video/dvqa/frames_storage_test.cc @@ -11,7 +11,9 @@ #include "test/pc/e2e/analyzer/video/dvqa/frames_storage.h" #include +#include #include +#include #include "api/scoped_refptr.h" #include "api/test/time_controller.h" diff --git a/test/pc/e2e/analyzer/video/dvqa/pausable_state.cc b/test/pc/e2e/analyzer/video/dvqa/pausable_state.cc index ac191b8d89..61187c3e8a 100644 --- a/test/pc/e2e/analyzer/video/dvqa/pausable_state.cc +++ b/test/pc/e2e/analyzer/video/dvqa/pausable_state.cc @@ -14,7 +14,6 @@ #include "api/units/time_delta.h" #include "api/units/timestamp.h" -#include "rtc_base/checks.h" namespace webrtc { diff --git a/test/pc/e2e/analyzer/video/encoded_image_data_injector.h b/test/pc/e2e/analyzer/video/encoded_image_data_injector.h index 307470168b..85ac7c7207 100644 --- a/test/pc/e2e/analyzer/video/encoded_image_data_injector.h +++ b/test/pc/e2e/analyzer/video/encoded_image_data_injector.h @@ -13,7 +13,6 @@ #include #include -#include #include "api/video/encoded_image.h" diff --git a/test/pc/e2e/analyzer/video/example_video_quality_analyzer.cc b/test/pc/e2e/analyzer/video/example_video_quality_analyzer.cc index 3946b9c0bd..d68db34033 100644 --- a/test/pc/e2e/analyzer/video/example_video_quality_analyzer.cc +++ b/test/pc/e2e/analyzer/video/example_video_quality_analyzer.cc @@ -10,8 +10,17 @@ #include "test/pc/e2e/analyzer/video/example_video_quality_analyzer.h" +#include +#include + +#include "absl/strings/string_view.h" #include "api/array_view.h" +#include "api/video/encoded_image.h" +#include "api/video/video_frame.h" +#include "api/video_codecs/video_encoder.h" +#include "rtc_base/checks.h" #include "rtc_base/logging.h" +#include "rtc_base/synchronization/mutex.h" namespace webrtc { diff --git a/test/pc/e2e/analyzer/video/example_video_quality_analyzer.h b/test/pc/e2e/analyzer/video/example_video_quality_analyzer.h index 78e44d8c0f..e347524439 100644 --- a/test/pc/e2e/analyzer/video/example_video_quality_analyzer.h +++ b/test/pc/e2e/analyzer/video/example_video_quality_analyzer.h @@ -11,16 +11,19 @@ #ifndef TEST_PC_E2E_ANALYZER_VIDEO_EXAMPLE_VIDEO_QUALITY_ANALYZER_H_ #define TEST_PC_E2E_ANALYZER_VIDEO_EXAMPLE_VIDEO_QUALITY_ANALYZER_H_ -#include +#include #include #include #include +#include "absl/strings/string_view.h" #include "api/array_view.h" #include "api/test/video_quality_analyzer_interface.h" #include "api/video/encoded_image.h" #include "api/video/video_frame.h" +#include "api/video_codecs/video_encoder.h" #include "rtc_base/synchronization/mutex.h" +#include "rtc_base/thread_annotations.h" namespace webrtc { diff --git a/test/pc/e2e/analyzer/video/multi_reader_queue.h b/test/pc/e2e/analyzer/video/multi_reader_queue.h index 99c53d06f6..db405420de 100644 --- a/test/pc/e2e/analyzer/video/multi_reader_queue.h +++ b/test/pc/e2e/analyzer/video/multi_reader_queue.h @@ -11,8 +11,8 @@ #ifndef TEST_PC_E2E_ANALYZER_VIDEO_MULTI_READER_QUEUE_H_ #define TEST_PC_E2E_ANALYZER_VIDEO_MULTI_READER_QUEUE_H_ +#include #include -#include #include #include #include diff --git a/test/pc/e2e/analyzer/video/multi_reader_queue_test.cc b/test/pc/e2e/analyzer/video/multi_reader_queue_test.cc index a035f44d7a..92a440ae8e 100644 --- a/test/pc/e2e/analyzer/video/multi_reader_queue_test.cc +++ b/test/pc/e2e/analyzer/video/multi_reader_queue_test.cc @@ -10,6 +10,7 @@ #include "test/pc/e2e/analyzer/video/multi_reader_queue.h" +#include #include #include "test/gtest.h" diff --git a/test/pc/e2e/analyzer/video/names_collection.cc b/test/pc/e2e/analyzer/video/names_collection.cc index d7129d0ef9..7a5548c510 100644 --- a/test/pc/e2e/analyzer/video/names_collection.cc +++ b/test/pc/e2e/analyzer/video/names_collection.cc @@ -10,10 +10,14 @@ #include "test/pc/e2e/analyzer/video/names_collection.h" +#include #include #include +#include +#include #include "absl/strings/string_view.h" +#include "api/array_view.h" namespace webrtc { diff --git a/test/pc/e2e/analyzer/video/names_collection.h b/test/pc/e2e/analyzer/video/names_collection.h index 7a2d59d1e8..5ba0729f1c 100644 --- a/test/pc/e2e/analyzer/video/names_collection.h +++ b/test/pc/e2e/analyzer/video/names_collection.h @@ -11,6 +11,7 @@ #ifndef TEST_PC_E2E_ANALYZER_VIDEO_NAMES_COLLECTION_H_ #define TEST_PC_E2E_ANALYZER_VIDEO_NAMES_COLLECTION_H_ +#include #include #include #include diff --git a/test/pc/e2e/analyzer/video/names_collection_test.cc b/test/pc/e2e/analyzer/video/names_collection_test.cc index e67c23f3fd..dc99b0f4e3 100644 --- a/test/pc/e2e/analyzer/video/names_collection_test.cc +++ b/test/pc/e2e/analyzer/video/names_collection_test.cc @@ -10,6 +10,7 @@ #include "test/pc/e2e/analyzer/video/names_collection.h" +#include #include #include #include diff --git a/test/pc/e2e/analyzer/video/quality_analyzing_video_decoder.cc b/test/pc/e2e/analyzer/video/quality_analyzing_video_decoder.cc index f990adf472..46519c46b2 100644 --- a/test/pc/e2e/analyzer/video/quality_analyzing_video_decoder.cc +++ b/test/pc/e2e/analyzer/video/quality_analyzing_video_decoder.cc @@ -14,13 +14,26 @@ #include #include #include +#include #include +#include #include "absl/strings/string_view.h" -#include "api/video/i420_buffer.h" +#include "api/environment/environment.h" +#include "api/scoped_refptr.h" +#include "api/test/video_quality_analyzer_interface.h" +#include "api/video/encoded_image.h" #include "api/video/video_frame.h" +#include "api/video/video_frame_buffer.h" +#include "api/video_codecs/sdp_video_format.h" +#include "api/video_codecs/video_codec.h" +#include "api/video_codecs/video_decoder.h" +#include "api/video_codecs/video_decoder_factory.h" #include "modules/video_coding/include/video_error_codes.h" +#include "rtc_base/checks.h" #include "rtc_base/logging.h" +#include "rtc_base/synchronization/mutex.h" +#include "test/pc/e2e/analyzer/video/encoded_image_data_injector.h" #include "test/pc/e2e/analyzer/video/simulcast_dummy_buffer_helper.h" namespace webrtc { diff --git a/test/pc/e2e/analyzer/video/quality_analyzing_video_decoder.h b/test/pc/e2e/analyzer/video/quality_analyzing_video_decoder.h index 2e567e1c35..9a33286803 100644 --- a/test/pc/e2e/analyzer/video/quality_analyzing_video_decoder.h +++ b/test/pc/e2e/analyzer/video/quality_analyzing_video_decoder.h @@ -11,6 +11,7 @@ #ifndef TEST_PC_E2E_ANALYZER_VIDEO_QUALITY_ANALYZING_VIDEO_DECODER_H_ #define TEST_PC_E2E_ANALYZER_VIDEO_QUALITY_ANALYZING_VIDEO_DECODER_H_ +#include #include #include #include @@ -19,13 +20,16 @@ #include "absl/strings/string_view.h" #include "api/environment/environment.h" +#include "api/scoped_refptr.h" #include "api/test/video_quality_analyzer_interface.h" #include "api/video/encoded_image.h" #include "api/video/video_frame.h" +#include "api/video/video_frame_buffer.h" #include "api/video_codecs/sdp_video_format.h" #include "api/video_codecs/video_decoder.h" #include "api/video_codecs/video_decoder_factory.h" #include "rtc_base/synchronization/mutex.h" +#include "rtc_base/thread_annotations.h" #include "test/pc/e2e/analyzer/video/encoded_image_data_injector.h" namespace webrtc { diff --git a/test/pc/e2e/analyzer/video/quality_analyzing_video_encoder.cc b/test/pc/e2e/analyzer/video/quality_analyzing_video_encoder.cc index c11a0e942c..40b4a25f51 100644 --- a/test/pc/e2e/analyzer/video/quality_analyzing_video_encoder.cc +++ b/test/pc/e2e/analyzer/video/quality_analyzing_video_encoder.cc @@ -10,17 +10,38 @@ #include "test/pc/e2e/analyzer/video/quality_analyzing_video_encoder.h" +#include #include +#include +#include #include +#include +#include +#include #include +#include #include "absl/strings/string_view.h" #include "api/environment/environment.h" +#include "api/fec_controller_override.h" +#include "api/test/video_quality_analyzer_interface.h" +#include "api/video/encoded_image.h" +#include "api/video/video_bitrate_allocation.h" +#include "api/video/video_codec_constants.h" #include "api/video/video_codec_type.h" +#include "api/video/video_frame.h" +#include "api/video/video_frame_type.h" +#include "api/video_codecs/sdp_video_format.h" +#include "api/video_codecs/video_codec.h" #include "api/video_codecs/video_encoder.h" +#include "api/video_codecs/video_encoder_factory.h" #include "modules/video_coding/include/video_error_codes.h" #include "modules/video_coding/svc/scalability_mode_util.h" +#include "rtc_base/checks.h" #include "rtc_base/logging.h" +#include "rtc_base/numerics/safe_conversions.h" +#include "rtc_base/synchronization/mutex.h" +#include "test/pc/e2e/analyzer/video/encoded_image_data_injector.h" namespace webrtc { namespace webrtc_pc_e2e { diff --git a/test/pc/e2e/analyzer/video/quality_analyzing_video_encoder.h b/test/pc/e2e/analyzer/video/quality_analyzing_video_encoder.h index 02159d74c8..2be4bdffc7 100644 --- a/test/pc/e2e/analyzer/video/quality_analyzing_video_encoder.h +++ b/test/pc/e2e/analyzer/video/quality_analyzing_video_encoder.h @@ -11,21 +11,30 @@ #ifndef TEST_PC_E2E_ANALYZER_VIDEO_QUALITY_ANALYZING_VIDEO_ENCODER_H_ #define TEST_PC_E2E_ANALYZER_VIDEO_QUALITY_ANALYZING_VIDEO_ENCODER_H_ +#include #include +#include #include +#include +#include #include #include #include "absl/strings/string_view.h" #include "api/environment/environment.h" +#include "api/fec_controller_override.h" #include "api/test/pclf/media_configuration.h" #include "api/test/video_quality_analyzer_interface.h" +#include "api/video/encoded_image.h" +#include "api/video/video_bitrate_allocation.h" #include "api/video/video_frame.h" +#include "api/video/video_frame_type.h" #include "api/video_codecs/sdp_video_format.h" #include "api/video_codecs/video_codec.h" #include "api/video_codecs/video_encoder.h" #include "api/video_codecs/video_encoder_factory.h" #include "rtc_base/synchronization/mutex.h" +#include "rtc_base/thread_annotations.h" #include "test/pc/e2e/analyzer/video/encoded_image_data_injector.h" namespace webrtc { diff --git a/test/pc/e2e/analyzer/video/simulcast_dummy_buffer_helper.cc b/test/pc/e2e/analyzer/video/simulcast_dummy_buffer_helper.cc index e6925466e6..e318b4dc33 100644 --- a/test/pc/e2e/analyzer/video/simulcast_dummy_buffer_helper.cc +++ b/test/pc/e2e/analyzer/video/simulcast_dummy_buffer_helper.cc @@ -10,6 +10,9 @@ #include "test/pc/e2e/analyzer/video/simulcast_dummy_buffer_helper.h" +#include + +#include "api/scoped_refptr.h" #include "api/video/i420_buffer.h" #include "api/video/video_frame.h" #include "api/video/video_frame_buffer.h" diff --git a/test/pc/e2e/analyzer/video/simulcast_dummy_buffer_helper.h b/test/pc/e2e/analyzer/video/simulcast_dummy_buffer_helper.h index 911d9d22e0..9cf8179a05 100644 --- a/test/pc/e2e/analyzer/video/simulcast_dummy_buffer_helper.h +++ b/test/pc/e2e/analyzer/video/simulcast_dummy_buffer_helper.h @@ -11,6 +11,7 @@ #ifndef TEST_PC_E2E_ANALYZER_VIDEO_SIMULCAST_DUMMY_BUFFER_HELPER_H_ #define TEST_PC_E2E_ANALYZER_VIDEO_SIMULCAST_DUMMY_BUFFER_HELPER_H_ +#include "api/scoped_refptr.h" #include "api/video/video_frame.h" #include "api/video/video_frame_buffer.h" diff --git a/test/pc/e2e/analyzer/video/simulcast_dummy_buffer_helper_test.cc b/test/pc/e2e/analyzer/video/simulcast_dummy_buffer_helper_test.cc index cdf778c96c..ed2fccea72 100644 --- a/test/pc/e2e/analyzer/video/simulcast_dummy_buffer_helper_test.cc +++ b/test/pc/e2e/analyzer/video/simulcast_dummy_buffer_helper_test.cc @@ -9,11 +9,13 @@ */ #include "test/pc/e2e/analyzer/video/simulcast_dummy_buffer_helper.h" +#include +#include + +#include "api/scoped_refptr.h" #include "api/video/i420_buffer.h" #include "api/video/video_frame.h" -#include "api/video/video_frame_buffer.h" #include "rtc_base/random.h" -#include "test/gmock.h" #include "test/gtest.h" namespace webrtc { diff --git a/test/pc/e2e/analyzer/video/single_process_encoded_image_data_injector.cc b/test/pc/e2e/analyzer/video/single_process_encoded_image_data_injector.cc index 3bc40a5dad..9824acf830 100644 --- a/test/pc/e2e/analyzer/video/single_process_encoded_image_data_injector.cc +++ b/test/pc/e2e/analyzer/video/single_process_encoded_image_data_injector.cc @@ -10,12 +10,16 @@ #include "test/pc/e2e/analyzer/video/single_process_encoded_image_data_injector.h" -#include #include +#include +#include +#include +#include -#include "absl/memory/memory.h" #include "api/video/encoded_image.h" #include "rtc_base/checks.h" +#include "rtc_base/synchronization/mutex.h" +#include "test/pc/e2e/analyzer/video/encoded_image_data_injector.h" namespace webrtc { namespace webrtc_pc_e2e { diff --git a/test/pc/e2e/analyzer/video/single_process_encoded_image_data_injector.h b/test/pc/e2e/analyzer/video/single_process_encoded_image_data_injector.h index 1082440e2f..004c6c03c8 100644 --- a/test/pc/e2e/analyzer/video/single_process_encoded_image_data_injector.h +++ b/test/pc/e2e/analyzer/video/single_process_encoded_image_data_injector.h @@ -11,14 +11,13 @@ #ifndef TEST_PC_E2E_ANALYZER_VIDEO_SINGLE_PROCESS_ENCODED_IMAGE_DATA_INJECTOR_H_ #define TEST_PC_E2E_ANALYZER_VIDEO_SINGLE_PROCESS_ENCODED_IMAGE_DATA_INJECTOR_H_ +#include #include #include -#include -#include -#include #include "api/video/encoded_image.h" #include "rtc_base/synchronization/mutex.h" +#include "rtc_base/thread_annotations.h" #include "test/pc/e2e/analyzer/video/encoded_image_data_injector.h" namespace webrtc { diff --git a/test/pc/e2e/analyzer/video/single_process_encoded_image_data_injector_unittest.cc b/test/pc/e2e/analyzer/video/single_process_encoded_image_data_injector_unittest.cc index 4cc09f097f..35c2531ac5 100644 --- a/test/pc/e2e/analyzer/video/single_process_encoded_image_data_injector_unittest.cc +++ b/test/pc/e2e/analyzer/video/single_process_encoded_image_data_injector_unittest.cc @@ -10,11 +10,15 @@ #include "test/pc/e2e/analyzer/video/single_process_encoded_image_data_injector.h" -#include +#include +#include +#include "api/scoped_refptr.h" #include "api/video/encoded_image.h" #include "rtc_base/buffer.h" +#include "rtc_base/checks.h" #include "test/gtest.h" +#include "test/pc/e2e/analyzer/video/encoded_image_data_injector.h" namespace webrtc { namespace webrtc_pc_e2e { diff --git a/test/pc/e2e/analyzer/video/video_dumping.cc b/test/pc/e2e/analyzer/video/video_dumping.cc index 6acacec106..1a8bf2379e 100644 --- a/test/pc/e2e/analyzer/video/video_dumping.cc +++ b/test/pc/e2e/analyzer/video/video_dumping.cc @@ -9,8 +9,7 @@ */ #include "test/pc/e2e/analyzer/video/video_dumping.h" -#include - +#include #include #include #include @@ -19,9 +18,8 @@ #include "absl/strings/string_view.h" #include "api/test/video/video_frame_writer.h" #include "api/video/video_frame.h" +#include "rtc_base/checks.h" #include "rtc_base/logging.h" -#include "system_wrappers/include/clock.h" -#include "test/testsupport/video_frame_writer.h" namespace webrtc { namespace webrtc_pc_e2e { diff --git a/test/pc/e2e/analyzer/video/video_dumping.h b/test/pc/e2e/analyzer/video/video_dumping.h index 304a991266..517236335d 100644 --- a/test/pc/e2e/analyzer/video/video_dumping.h +++ b/test/pc/e2e/analyzer/video/video_dumping.h @@ -11,14 +11,13 @@ #ifndef TEST_PC_E2E_ANALYZER_VIDEO_VIDEO_DUMPING_H_ #define TEST_PC_E2E_ANALYZER_VIDEO_VIDEO_DUMPING_H_ +#include #include -#include #include "absl/strings/string_view.h" #include "api/test/video/video_frame_writer.h" #include "api/video/video_frame.h" #include "api/video/video_sink_interface.h" -#include "test/testsupport/video_frame_writer.h" namespace webrtc { namespace webrtc_pc_e2e { diff --git a/test/pc/e2e/analyzer/video/video_dumping_test.cc b/test/pc/e2e/analyzer/video/video_dumping_test.cc index 3688fe5b8a..06933e89b7 100644 --- a/test/pc/e2e/analyzer/video/video_dumping_test.cc +++ b/test/pc/e2e/analyzer/video/video_dumping_test.cc @@ -11,12 +11,15 @@ #include +#include +#include +#include #include -#include #include #include #include "api/scoped_refptr.h" +#include "api/test/video/video_frame_writer.h" #include "api/video/i420_buffer.h" #include "api/video/video_frame.h" #include "api/video/video_frame_buffer.h" diff --git a/test/pc/e2e/analyzer/video/video_frame_tracking_id_injector.cc b/test/pc/e2e/analyzer/video/video_frame_tracking_id_injector.cc index 5a74d60250..166bf6cef2 100644 --- a/test/pc/e2e/analyzer/video/video_frame_tracking_id_injector.cc +++ b/test/pc/e2e/analyzer/video/video_frame_tracking_id_injector.cc @@ -10,9 +10,11 @@ #include "test/pc/e2e/analyzer/video/video_frame_tracking_id_injector.h" -#include "absl/memory/memory.h" +#include + #include "api/video/encoded_image.h" #include "rtc_base/checks.h" +#include "test/pc/e2e/analyzer/video/encoded_image_data_injector.h" namespace webrtc { namespace webrtc_pc_e2e { diff --git a/test/pc/e2e/analyzer/video/video_frame_tracking_id_injector_unittest.cc b/test/pc/e2e/analyzer/video/video_frame_tracking_id_injector_unittest.cc index 6ef6597649..449651e6a8 100644 --- a/test/pc/e2e/analyzer/video/video_frame_tracking_id_injector_unittest.cc +++ b/test/pc/e2e/analyzer/video/video_frame_tracking_id_injector_unittest.cc @@ -10,9 +10,13 @@ #include "test/pc/e2e/analyzer/video/video_frame_tracking_id_injector.h" +#include +#include + +#include "api/scoped_refptr.h" #include "api/video/encoded_image.h" -#include "rtc_base/buffer.h" #include "test/gtest.h" +#include "test/pc/e2e/analyzer/video/encoded_image_data_injector.h" namespace webrtc { namespace webrtc_pc_e2e { diff --git a/test/pc/e2e/analyzer/video/video_quality_analyzer_injection_helper.cc b/test/pc/e2e/analyzer/video/video_quality_analyzer_injection_helper.cc index c175859bfa..b311c2acfa 100644 --- a/test/pc/e2e/analyzer/video/video_quality_analyzer_injection_helper.cc +++ b/test/pc/e2e/analyzer/video/video_quality_analyzer_injection_helper.cc @@ -10,27 +10,31 @@ #include "test/pc/e2e/analyzer/video/video_quality_analyzer_injection_helper.h" -#include - +#include #include +#include #include #include #include "absl/memory/memory.h" #include "absl/strings/string_view.h" #include "api/array_view.h" +#include "api/scoped_refptr.h" +#include "api/stats/rtc_stats_report.h" #include "api/test/pclf/media_configuration.h" -#include "api/video/i420_buffer.h" +#include "api/test/video/video_frame_writer.h" +#include "api/test/video_quality_analyzer_interface.h" +#include "api/video/video_sink_interface.h" +#include "api/video_codecs/video_decoder_factory.h" +#include "api/video_codecs/video_encoder_factory.h" #include "rtc_base/checks.h" -#include "rtc_base/logging.h" -#include "rtc_base/strings/string_builder.h" #include "system_wrappers/include/clock.h" #include "test/pc/e2e/analyzer/video/analyzing_video_sink.h" +#include "test/pc/e2e/analyzer/video/encoded_image_data_injector.h" #include "test/pc/e2e/analyzer/video/quality_analyzing_video_decoder.h" #include "test/pc/e2e/analyzer/video/quality_analyzing_video_encoder.h" -#include "test/pc/e2e/analyzer/video/simulcast_dummy_buffer_helper.h" #include "test/pc/e2e/analyzer/video/video_dumping.h" -#include "test/testsupport/fixed_fps_video_frame_writer_adapter.h" +#include "test/test_video_capturer.h" #include "test/video_renderer.h" namespace webrtc { diff --git a/test/pc/e2e/analyzer/video/video_quality_analyzer_injection_helper.h b/test/pc/e2e/analyzer/video/video_quality_analyzer_injection_helper.h index 6bba004a00..99b2580e58 100644 --- a/test/pc/e2e/analyzer/video/video_quality_analyzer_injection_helper.h +++ b/test/pc/e2e/analyzer/video/video_quality_analyzer_injection_helper.h @@ -11,30 +11,26 @@ #ifndef TEST_PC_E2E_ANALYZER_VIDEO_VIDEO_QUALITY_ANALYZER_INJECTION_HELPER_H_ #define TEST_PC_E2E_ANALYZER_VIDEO_VIDEO_QUALITY_ANALYZER_INJECTION_HELPER_H_ -#include - -#include #include #include #include #include "absl/strings/string_view.h" #include "api/array_view.h" +#include "api/scoped_refptr.h" +#include "api/stats/rtc_stats_report.h" #include "api/test/pclf/media_configuration.h" #include "api/test/stats_observer_interface.h" +#include "api/test/video/video_frame_writer.h" #include "api/test/video_quality_analyzer_interface.h" -#include "api/video/video_frame.h" -#include "api/video/video_sink_interface.h" #include "api/video_codecs/video_decoder_factory.h" #include "api/video_codecs/video_encoder_factory.h" -#include "rtc_base/synchronization/mutex.h" #include "system_wrappers/include/clock.h" #include "test/pc/e2e/analyzer/video/analyzing_video_sink.h" #include "test/pc/e2e/analyzer/video/analyzing_video_sinks_helper.h" #include "test/pc/e2e/analyzer/video/encoded_image_data_injector.h" #include "test/pc/e2e/analyzer/video/quality_analyzing_video_encoder.h" #include "test/test_video_capturer.h" -#include "test/testsupport/video_frame_writer.h" namespace webrtc { namespace webrtc_pc_e2e { diff --git a/test/pc/e2e/analyzer/video/video_quality_metrics_reporter.h b/test/pc/e2e/analyzer/video/video_quality_metrics_reporter.h index 2abc6b9c4f..b750a74cef 100644 --- a/test/pc/e2e/analyzer/video/video_quality_metrics_reporter.h +++ b/test/pc/e2e/analyzer/video/video_quality_metrics_reporter.h @@ -14,7 +14,6 @@ #include #include #include -#include #include "absl/strings/string_view.h" #include "api/numerics/samples_stats_counter.h" diff --git a/test/pc/e2e/analyzer_helper.cc b/test/pc/e2e/analyzer_helper.cc index 0987f8c42a..818a20a7e1 100644 --- a/test/pc/e2e/analyzer_helper.cc +++ b/test/pc/e2e/analyzer_helper.cc @@ -10,9 +10,14 @@ #include "test/pc/e2e/analyzer_helper.h" +#include #include #include +#include "absl/strings/string_view.h" +#include "api/sequence_checker.h" +#include "rtc_base/checks.h" + namespace webrtc { namespace webrtc_pc_e2e { diff --git a/test/pc/e2e/cross_media_metrics_reporter.h b/test/pc/e2e/cross_media_metrics_reporter.h index a385d4a219..5edca7e8f5 100644 --- a/test/pc/e2e/cross_media_metrics_reporter.h +++ b/test/pc/e2e/cross_media_metrics_reporter.h @@ -12,16 +12,17 @@ #define TEST_PC_E2E_CROSS_MEDIA_METRICS_REPORTER_H_ #include -#include #include #include "absl/strings/string_view.h" #include "api/numerics/samples_stats_counter.h" +#include "api/scoped_refptr.h" +#include "api/stats/rtc_stats_report.h" #include "api/test/metrics/metrics_logger.h" #include "api/test/peerconnection_quality_test_fixture.h" #include "api/test/track_id_stream_info_map.h" -#include "api/units/timestamp.h" #include "rtc_base/synchronization/mutex.h" +#include "rtc_base/thread_annotations.h" namespace webrtc { namespace webrtc_pc_e2e { diff --git a/test/pc/e2e/echo/echo_emulation.cc b/test/pc/e2e/echo/echo_emulation.cc index 89357094a0..34d53f47e6 100644 --- a/test/pc/e2e/echo/echo_emulation.cc +++ b/test/pc/e2e/echo/echo_emulation.cc @@ -9,10 +9,18 @@ */ #include "test/pc/e2e/echo/echo_emulation.h" +#include +#include #include +#include #include +#include "api/array_view.h" +#include "api/sequence_checker.h" #include "api/test/pclf/media_configuration.h" +#include "modules/audio_device/include/test_audio_device.h" +#include "rtc_base/buffer.h" +#include "rtc_base/checks.h" #include "rtc_base/logging.h" namespace webrtc { diff --git a/test/pc/e2e/echo/echo_emulation.h b/test/pc/e2e/echo/echo_emulation.h index f26d8118bc..9e0aaba05e 100644 --- a/test/pc/e2e/echo/echo_emulation.h +++ b/test/pc/e2e/echo/echo_emulation.h @@ -11,15 +11,17 @@ #ifndef TEST_PC_E2E_ECHO_ECHO_EMULATION_H_ #define TEST_PC_E2E_ECHO_ECHO_EMULATION_H_ -#include -#include +#include #include #include +#include "api/array_view.h" #include "api/sequence_checker.h" #include "api/test/pclf/media_configuration.h" #include "modules/audio_device/include/test_audio_device.h" +#include "rtc_base/buffer.h" #include "rtc_base/swap_queue.h" +#include "rtc_base/thread_annotations.h" namespace webrtc { namespace webrtc_pc_e2e { diff --git a/test/pc/e2e/media/media_helper.cc b/test/pc/e2e/media/media_helper.cc index ad83e8d091..d5576270cc 100644 --- a/test/pc/e2e/media/media_helper.cc +++ b/test/pc/e2e/media/media_helper.cc @@ -9,17 +9,30 @@ */ #include "test/pc/e2e/media/media_helper.h" +#include +#include #include #include #include +#include +#include "api/make_ref_counted.h" #include "api/media_stream_interface.h" -#include "api/test/create_frame_generator.h" +#include "api/rtc_error.h" +#include "api/rtp_parameters.h" +#include "api/rtp_sender_interface.h" +#include "api/scoped_refptr.h" +#include "api/test/frame_generator_interface.h" #include "api/test/pclf/media_configuration.h" +#include "api/test/pclf/media_quality_test_params.h" #include "api/test/pclf/peer_configurer.h" +#include "rtc_base/checks.h" +#include "rtc_base/logging.h" #include "test/frame_generator_capturer.h" +#include "test/pc/e2e/media/test_video_capturer_video_track_source.h" +#include "test/pc/e2e/test_peer.h" #include "test/platform_video_capturer.h" -#include "test/testsupport/file_utils.h" +#include "test/test_video_capturer.h" namespace webrtc { namespace webrtc_pc_e2e { diff --git a/test/pc/e2e/media/media_helper.h b/test/pc/e2e/media/media_helper.h index 9dbabe5f39..4686c8f9ed 100644 --- a/test/pc/e2e/media/media_helper.h +++ b/test/pc/e2e/media/media_helper.h @@ -14,12 +14,15 @@ #include #include -#include "api/test/frame_generator_interface.h" +#include "api/scoped_refptr.h" +#include "api/task_queue/task_queue_factory.h" #include "api/test/pclf/media_configuration.h" #include "api/test/pclf/peer_configurer.h" +#include "system_wrappers/include/clock.h" #include "test/pc/e2e/analyzer/video/video_quality_analyzer_injection_helper.h" #include "test/pc/e2e/media/test_video_capturer_video_track_source.h" #include "test/pc/e2e/test_peer.h" +#include "test/test_video_capturer.h" namespace webrtc { namespace webrtc_pc_e2e { diff --git a/test/pc/e2e/media/test_video_capturer_video_track_source.h b/test/pc/e2e/media/test_video_capturer_video_track_source.h index 6e691a5737..d5c16ac5c0 100644 --- a/test/pc/e2e/media/test_video_capturer_video_track_source.h +++ b/test/pc/e2e/media/test_video_capturer_video_track_source.h @@ -13,12 +13,15 @@ #include #include +#include #include +#include "api/media_stream_interface.h" #include "api/sequence_checker.h" #include "api/test/video/test_video_track_source.h" #include "api/video/video_frame.h" #include "api/video/video_source_interface.h" +#include "rtc_base/thread_annotations.h" #include "test/test_video_capturer.h" namespace webrtc { diff --git a/test/pc/e2e/network_quality_metrics_reporter.cc b/test/pc/e2e/network_quality_metrics_reporter.cc index 3cb820eb62..ad813811ae 100644 --- a/test/pc/e2e/network_quality_metrics_reporter.cc +++ b/test/pc/e2e/network_quality_metrics_reporter.cc @@ -9,14 +9,24 @@ */ #include "test/pc/e2e/network_quality_metrics_reporter.h" +#include +#include #include -#include "api/stats/rtc_stats.h" +#include "absl/strings/string_view.h" +#include "api/scoped_refptr.h" +#include "api/stats/rtc_stats_report.h" #include "api/stats/rtcstats_objects.h" #include "api/test/metrics/metric.h" +#include "api/test/metrics/metrics_logger.h" +#include "api/test/network_emulation/network_emulation_interfaces.h" +#include "api/test/network_emulation_manager.h" +#include "api/test/track_id_stream_info_map.h" +#include "api/units/data_size.h" +#include "api/units/time_delta.h" #include "rtc_base/checks.h" #include "rtc_base/event.h" -#include "system_wrappers/include/field_trial.h" +#include "rtc_base/synchronization/mutex.h" namespace webrtc { namespace webrtc_pc_e2e { diff --git a/test/pc/e2e/network_quality_metrics_reporter.h b/test/pc/e2e/network_quality_metrics_reporter.h index 73bbd30c40..eea956f134 100644 --- a/test/pc/e2e/network_quality_metrics_reporter.h +++ b/test/pc/e2e/network_quality_metrics_reporter.h @@ -11,16 +11,21 @@ #ifndef TEST_PC_E2E_NETWORK_QUALITY_METRICS_REPORTER_H_ #define TEST_PC_E2E_NETWORK_QUALITY_METRICS_REPORTER_H_ -#include +#include +#include #include #include "absl/strings/string_view.h" +#include "api/scoped_refptr.h" +#include "api/stats/rtc_stats_report.h" #include "api/test/metrics/metrics_logger.h" +#include "api/test/network_emulation/network_emulation_interfaces.h" #include "api/test/network_emulation_manager.h" #include "api/test/peerconnection_quality_test_fixture.h" #include "api/test/track_id_stream_info_map.h" #include "api/units/data_size.h" #include "rtc_base/synchronization/mutex.h" +#include "rtc_base/thread_annotations.h" namespace webrtc { namespace webrtc_pc_e2e { diff --git a/test/pc/e2e/peer_connection_e2e_smoke_test.cc b/test/pc/e2e/peer_connection_e2e_smoke_test.cc index 57be393461..6dcc4f1537 100644 --- a/test/pc/e2e/peer_connection_e2e_smoke_test.cc +++ b/test/pc/e2e/peer_connection_e2e_smoke_test.cc @@ -9,25 +9,31 @@ */ #include +#include #include #include +#include +#include +#include "api/function_view.h" #include "api/media_stream_interface.h" +#include "api/rtp_parameters.h" #include "api/test/create_network_emulation_manager.h" #include "api/test/create_peer_connection_quality_test_frame_generator.h" #include "api/test/create_peerconnection_quality_test_fixture.h" #include "api/test/metrics/global_metrics_logger_and_exporter.h" +#include "api/test/network_emulation/network_emulation_interfaces.h" #include "api/test/network_emulation_manager.h" #include "api/test/pclf/media_configuration.h" #include "api/test/pclf/media_quality_test_params.h" #include "api/test/pclf/peer_configurer.h" #include "api/test/peerconnection_quality_test_fixture.h" +#include "api/test/simulated_network.h" +#include "api/transport/bitrate_settings.h" +#include "api/units/time_delta.h" #include "media/base/media_constants.h" -#include "system_wrappers/include/field_trial.h" -#include "test/field_trial.h" #include "test/gtest.h" #include "test/network/simulated_network.h" -#include "test/pc/e2e/analyzer/audio/default_audio_quality_analyzer.h" #include "test/pc/e2e/analyzer/video/default_video_quality_analyzer.h" #include "test/pc/e2e/analyzer/video/default_video_quality_analyzer_shared_objects.h" #include "test/pc/e2e/stats_based_network_quality_metrics_reporter.h" @@ -176,7 +182,6 @@ TEST_F(PeerConnectionE2EQualityTestSmokeTest, MAYBE_Smoke) { {"charlie", network_links.second->endpoints()}}), network_emulation(), test::GetGlobalMetricsLogger())); RunParams run_params(TimeDelta::Seconds(2)); - run_params.enable_flex_fec_support = true; RunAndCheckEachVideoStreamReceivedFrames(run_params); } @@ -226,7 +231,6 @@ TEST_F(PeerConnectionE2EQualityTestSmokeTest, SmokeH264) { {"charlie", network_links.second->endpoints()}}), network_emulation(), test::GetGlobalMetricsLogger())); RunParams run_params(TimeDelta::Seconds(2)); - run_params.enable_flex_fec_support = true; RunAndCheckEachVideoStreamReceivedFrames(run_params); } #endif @@ -300,7 +304,6 @@ TEST_F(PeerConnectionE2EQualityTestSmokeTest, MAYBE_ChangeNetworkConditions) { }); RunParams run_params(TimeDelta::Seconds(2)); - run_params.enable_flex_fec_support = true; RunAndCheckEachVideoStreamReceivedFrames(run_params); } diff --git a/test/pc/e2e/peer_connection_quality_test.cc b/test/pc/e2e/peer_connection_quality_test.cc index f6e7cf2b57..c5a6d066cd 100644 --- a/test/pc/e2e/peer_connection_quality_test.cc +++ b/test/pc/e2e/peer_connection_quality_test.cc @@ -53,18 +53,13 @@ #include "rtc_base/checks.h" #include "rtc_base/cpu_info.h" #include "rtc_base/logging.h" -#include "rtc_base/strings/string_builder.h" #include "rtc_base/synchronization/mutex.h" #include "rtc_base/task_queue_for_test.h" #include "rtc_base/task_utils/repeating_task.h" #include "rtc_base/thread.h" -#include "system_wrappers/include/field_trial.h" -#include "test/field_trial.h" #include "test/gtest.h" #include "test/pc/e2e/analyzer/audio/default_audio_quality_analyzer.h" #include "test/pc/e2e/analyzer/video/default_video_quality_analyzer.h" -#include "test/pc/e2e/analyzer/video/single_process_encoded_image_data_injector.h" -#include "test/pc/e2e/analyzer/video/video_frame_tracking_id_injector.h" #include "test/pc/e2e/analyzer/video/video_quality_analyzer_injection_helper.h" #include "test/pc/e2e/analyzer/video/video_quality_metrics_reporter.h" #include "test/pc/e2e/cross_media_metrics_reporter.h" @@ -79,7 +74,6 @@ #include "test/pc/e2e/test_peer.h" #include "test/pc/e2e/test_peer_factory.h" #include "test/test_flags.h" -#include "test/testsupport/file_utils.h" namespace webrtc { namespace webrtc_pc_e2e { @@ -103,10 +97,6 @@ constexpr TimeDelta kAliveMessageLogInterval = TimeDelta::Seconds(30); constexpr TimeDelta kQuickTestModeRunDuration = TimeDelta::Millis(100); -// Field trials to enable Flex FEC advertising and receiving. -constexpr char kFlexFecEnabledFieldTrials[] = - "WebRTC-FlexFEC-03-Advertised/Enabled/WebRTC-FlexFEC-03/Enabled/"; - class FixturePeerConnectionObserver : public MockPeerConnectionObserver { public: // `on_track_callback` will be called when any new track will be added to peer @@ -189,18 +179,10 @@ PeerConnectionE2EQualityTest::PeerConnectionE2EQualityTest( video_quality_analyzer = std::make_unique( time_controller_.GetClock(), metrics_logger_); } - if (field_trial::IsEnabled("WebRTC-VideoFrameTrackingIdAdvertised")) { - encoded_image_data_propagator_ = - std::make_unique(); - } else { - encoded_image_data_propagator_ = - std::make_unique(); - } video_quality_analyzer_injection_helper_ = std::make_unique( time_controller_.GetClock(), std::move(video_quality_analyzer), - encoded_image_data_propagator_.get(), - encoded_image_data_propagator_.get()); + &encoded_image_data_propagator_, &encoded_image_data_propagator_); if (audio_quality_analyzer == nullptr) { audio_quality_analyzer = @@ -259,8 +241,6 @@ void PeerConnectionE2EQualityTest::Run(RunParams run_params) { << "Only simulcast stream from first peer is supported"; } - test::ScopedFieldTrials field_trials(GetFieldTrials(run_params)); - // Print test summary RTC_LOG(LS_INFO) << "Media quality test: " << *alice_configurer->params()->name @@ -466,20 +446,6 @@ void PeerConnectionE2EQualityTest::Run(RunParams run_params) { RTC_CHECK(bob_video_sources_.empty()); } -std::string PeerConnectionE2EQualityTest::GetFieldTrials( - const RunParams& run_params) { - std::vector default_field_trials = {}; - if (run_params.enable_flex_fec_support) { - default_field_trials.push_back(kFlexFecEnabledFieldTrials); - } - StringBuilder sb; - sb << field_trial::GetFieldTrialString(); - for (const absl::string_view& field_trial : default_field_trials) { - sb << field_trial; - } - return sb.Release(); -} - void PeerConnectionE2EQualityTest::OnTrackCallback( absl::string_view peer_name, VideoSubscription peer_subscription, @@ -716,23 +682,21 @@ void PeerConnectionE2EQualityTest::ExchangeOfferAnswer( void PeerConnectionE2EQualityTest::ExchangeIceCandidates( SignalingInterceptor* signaling_interceptor) { // Connect an ICE candidate pairs. - std::vector> alice_candidates = + std::vector> alice_candidates = signaling_interceptor->PatchOffererIceCandidates( alice_->observer()->GetAllCandidates()); for (auto& candidate : alice_candidates) { - std::string candidate_str; - RTC_CHECK(candidate->ToString(&candidate_str)); + std::string candidate_str = candidate->ToString(); RTC_LOG(LS_INFO) << *alice_->params().name << " ICE candidate(mid= " << candidate->sdp_mid() << "): " << candidate_str; } ASSERT_TRUE(bob_->AddIceCandidates(std::move(alice_candidates))); - std::vector> bob_candidates = + std::vector> bob_candidates = signaling_interceptor->PatchAnswererIceCandidates( bob_->observer()->GetAllCandidates()); for (auto& candidate : bob_candidates) { - std::string candidate_str; - RTC_CHECK(candidate->ToString(&candidate_str)); + std::string candidate_str = candidate->ToString(); RTC_LOG(LS_INFO) << *bob_->params().name << " ICE candidate(mid= " << candidate->sdp_mid() << "): " << candidate_str; diff --git a/test/pc/e2e/peer_connection_quality_test.h b/test/pc/e2e/peer_connection_quality_test.h index efcc02c5ce..77bf73507b 100644 --- a/test/pc/e2e/peer_connection_quality_test.h +++ b/test/pc/e2e/peer_connection_quality_test.h @@ -10,12 +10,14 @@ #ifndef TEST_PC_E2E_PEER_CONNECTION_QUALITY_TEST_H_ #define TEST_PC_E2E_PEER_CONNECTION_QUALITY_TEST_H_ +#include #include -#include #include #include #include "absl/strings/string_view.h" +#include "api/rtp_transceiver_interface.h" +#include "api/scoped_refptr.h" #include "api/task_queue/task_queue_factory.h" #include "api/test/audio_quality_analyzer_interface.h" #include "api/test/metrics/metrics_logger.h" @@ -24,17 +26,21 @@ #include "api/test/pclf/peer_configurer.h" #include "api/test/peerconnection_quality_test_fixture.h" #include "api/test/time_controller.h" +#include "api/test/video_quality_analyzer_interface.h" #include "api/units/time_delta.h" #include "api/units/timestamp.h" +#include "api/video/video_frame.h" +#include "api/video/video_sink_interface.h" +#include "rtc_base/checks.h" #include "rtc_base/synchronization/mutex.h" #include "rtc_base/task_queue_for_test.h" #include "rtc_base/thread.h" #include "rtc_base/thread_annotations.h" -#include "system_wrappers/include/clock.h" #include "test/pc/e2e/analyzer/video/single_process_encoded_image_data_injector.h" #include "test/pc/e2e/analyzer/video/video_quality_analyzer_injection_helper.h" #include "test/pc/e2e/analyzer_helper.h" #include "test/pc/e2e/media/media_helper.h" +#include "test/pc/e2e/media/test_video_capturer_video_track_source.h" #include "test/pc/e2e/sdp/sdp_changer.h" #include "test/pc/e2e/test_activities_executor.h" #include "test/pc/e2e/test_peer.h" @@ -86,9 +92,6 @@ class PeerConnectionE2EQualityTest ~PeerHandleImpl() override = default; }; - // For some functionality some field trials have to be enabled, they will be - // enabled in Run(). - std::string GetFieldTrials(const RunParams& run_params); void OnTrackCallback(absl::string_view peer_name, VideoSubscription peer_subscription, scoped_refptr transceiver, @@ -116,7 +119,7 @@ class PeerConnectionE2EQualityTest std::unique_ptr video_quality_analyzer_injection_helper_; std::unique_ptr media_helper_; - std::unique_ptr encoded_image_data_propagator_; + SingleProcessEncodedImageDataInjector encoded_image_data_propagator_; std::unique_ptr audio_quality_analyzer_; std::unique_ptr executor_; test::MetricsLogger* const metrics_logger_; diff --git a/test/pc/e2e/peer_connection_quality_test_test.cc b/test/pc/e2e/peer_connection_quality_test_test.cc index a945b0491f..94e2d58c31 100644 --- a/test/pc/e2e/peer_connection_quality_test_test.cc +++ b/test/pc/e2e/peer_connection_quality_test_test.cc @@ -10,20 +10,22 @@ #include "test/pc/e2e/peer_connection_quality_test.h" -#include +#include #include +#include #include #include +#include +#include "absl/strings/string_view.h" #include "api/test/create_network_emulation_manager.h" #include "api/test/metrics/global_metrics_logger_and_exporter.h" +#include "api/test/network_emulation/network_emulation_interfaces.h" #include "api/test/network_emulation_manager.h" #include "api/test/pclf/media_configuration.h" #include "api/test/pclf/media_quality_test_params.h" #include "api/test/pclf/peer_configurer.h" -#include "api/test/peerconnection_quality_test_fixture.h" #include "api/units/time_delta.h" -#include "rtc_base/time_utils.h" #include "test/gmock.h" #include "test/gtest.h" #include "test/testsupport/file_utils.h" diff --git a/test/pc/e2e/peer_params_preprocessor.cc b/test/pc/e2e/peer_params_preprocessor.cc index 50938a8a1a..5cfbab3f94 100644 --- a/test/pc/e2e/peer_params_preprocessor.cc +++ b/test/pc/e2e/peer_params_preprocessor.cc @@ -10,8 +10,8 @@ #include "test/pc/e2e/peer_params_preprocessor.h" -#include - +#include +#include #include #include #include diff --git a/test/pc/e2e/sdp/sdp_changer.cc b/test/pc/e2e/sdp/sdp_changer.cc index 6aa774bf69..29a8317a88 100644 --- a/test/pc/e2e/sdp/sdp_changer.cc +++ b/test/pc/e2e/sdp/sdp_changer.cc @@ -268,7 +268,6 @@ LocalAndRemoteSdp SignalingInterceptor::PatchVp8Offer( ++ext_it; } - prototype_media_desc->ClearRtpHeaderExtensions(); prototype_media_desc->set_rtp_header_extensions(extensions); // We support only single stream inside video section with simulcast @@ -447,7 +446,6 @@ LocalAndRemoteSdp SignalingInterceptor::PatchVp8Answer( extensions.push_back(info.mid_extension); extensions.push_back(info.rid_extension); // extensions.push_back(info.rrid_extension); - media_desc->ClearRtpHeaderExtensions(); media_desc->set_rtp_header_extensions(extensions); // Add StreamParams with rids for receive. @@ -535,10 +533,10 @@ LocalAndRemoteSdp SignalingInterceptor::PatchVp9Answer( return LocalAndRemoteSdp(std::move(answer), std::move(answer_for_remote)); } -std::vector> +std::vector> SignalingInterceptor::PatchOffererIceCandidates( - ArrayView candidates) { - std::vector> out; + ArrayView candidates) { + std::vector> out; for (auto* candidate : candidates) { auto simulcast_info_it = context_.simulcast_infos_by_mid.find(candidate->sdp_mid()); @@ -559,10 +557,10 @@ SignalingInterceptor::PatchOffererIceCandidates( return out; } -std::vector> +std::vector> SignalingInterceptor::PatchAnswererIceCandidates( - ArrayView candidates) { - std::vector> out; + ArrayView candidates) { + std::vector> out; for (auto* candidate : candidates) { auto simulcast_info_it = context_.simulcast_infos_by_rid.find(candidate->sdp_mid()); diff --git a/test/pc/e2e/sdp/sdp_changer.h b/test/pc/e2e/sdp/sdp_changer.h index 62a13e45b4..8c7d68d762 100644 --- a/test/pc/e2e/sdp/sdp_changer.h +++ b/test/pc/e2e/sdp/sdp_changer.h @@ -12,16 +12,17 @@ #define TEST_PC_E2E_SDP_SDP_CHANGER_H_ #include -#include +#include #include +#include #include -#include "absl/strings/string_view.h" #include "api/array_view.h" #include "api/jsep.h" #include "api/rtp_parameters.h" #include "api/test/pclf/media_configuration.h" #include "media/base/rid_description.h" +#include "p2p/base/transport_description.h" #include "pc/session_description.h" #include "pc/simulcast_description.h" @@ -81,11 +82,10 @@ class SignalingInterceptor { std::unique_ptr answer, const VideoCodecConfig& first_codec); - std::vector> PatchOffererIceCandidates( - ArrayView candidates); - std::vector> - PatchAnswererIceCandidates( - ArrayView candidates); + std::vector> PatchOffererIceCandidates( + ArrayView candidates); + std::vector> PatchAnswererIceCandidates( + ArrayView candidates); private: // Contains information about simulcast section, that is required to perform diff --git a/test/pc/e2e/stats_based_network_quality_metrics_reporter.h b/test/pc/e2e/stats_based_network_quality_metrics_reporter.h index f401f10946..80fba75ed8 100644 --- a/test/pc/e2e/stats_based_network_quality_metrics_reporter.h +++ b/test/pc/e2e/stats_based_network_quality_metrics_reporter.h @@ -13,22 +13,24 @@ #include #include -#include #include #include -#include #include #include "absl/strings/string_view.h" -#include "api/numerics/samples_stats_counter.h" +#include "api/scoped_refptr.h" +#include "api/stats/rtc_stats_report.h" #include "api/test/metrics/metrics_logger.h" #include "api/test/network_emulation/network_emulation_interfaces.h" #include "api/test/network_emulation_manager.h" #include "api/test/peerconnection_quality_test_fixture.h" +#include "api/test/track_id_stream_info_map.h" #include "api/units/data_size.h" #include "api/units/timestamp.h" #include "rtc_base/ip_address.h" #include "rtc_base/synchronization/mutex.h" +#include "rtc_base/thread_annotations.h" +#include "system_wrappers/include/clock.h" namespace webrtc { namespace webrtc_pc_e2e { diff --git a/test/pc/e2e/stats_based_network_quality_metrics_reporter_test.cc b/test/pc/e2e/stats_based_network_quality_metrics_reporter_test.cc index b06324361e..d4044f0ec0 100644 --- a/test/pc/e2e/stats_based_network_quality_metrics_reporter_test.cc +++ b/test/pc/e2e/stats_based_network_quality_metrics_reporter_test.cc @@ -14,23 +14,26 @@ #include #include #include +#include #include #include "absl/strings/string_view.h" #include "api/array_view.h" #include "api/test/create_network_emulation_manager.h" -#include "api/test/create_peer_connection_quality_test_frame_generator.h" +#include "api/test/metrics/metric.h" #include "api/test/metrics/metrics_logger.h" -#include "api/test/metrics/stdout_metrics_exporter.h" +#include "api/test/network_emulation/network_emulation_interfaces.h" #include "api/test/network_emulation_manager.h" #include "api/test/pclf/media_configuration.h" #include "api/test/pclf/media_quality_test_params.h" #include "api/test/pclf/peer_configurer.h" #include "api/test/peerconnection_quality_test_fixture.h" +#include "api/test/simulated_network.h" +#include "api/units/data_rate.h" #include "api/units/time_delta.h" +#include "media/base/media_constants.h" #include "test/gmock.h" #include "test/gtest.h" -#include "test/pc/e2e/metric_metadata_keys.h" #include "test/pc/e2e/peer_connection_quality_test.h" namespace webrtc { diff --git a/test/pc/e2e/stats_poller.cc b/test/pc/e2e/stats_poller.cc index 23db7acbd3..29533ac637 100644 --- a/test/pc/e2e/stats_poller.cc +++ b/test/pc/e2e/stats_poller.cc @@ -10,10 +10,19 @@ #include "test/pc/e2e/stats_poller.h" +#include +#include #include +#include -#include "rtc_base/logging.h" +#include "absl/strings/string_view.h" +#include "api/make_ref_counted.h" +#include "api/scoped_refptr.h" +#include "api/stats/rtc_stats_report.h" +#include "api/test/stats_observer_interface.h" #include "rtc_base/synchronization/mutex.h" +#include "test/pc/e2e/stats_provider.h" +#include "test/pc/e2e/test_peer.h" namespace webrtc { namespace webrtc_pc_e2e { diff --git a/test/pc/e2e/stats_poller.h b/test/pc/e2e/stats_poller.h index d2487b0a11..f9b8890652 100644 --- a/test/pc/e2e/stats_poller.h +++ b/test/pc/e2e/stats_poller.h @@ -16,8 +16,10 @@ #include #include -#include "api/peer_connection_interface.h" +#include "absl/strings/string_view.h" +#include "api/scoped_refptr.h" #include "api/stats/rtc_stats_collector_callback.h" +#include "api/stats/rtc_stats_report.h" #include "api/test/stats_observer_interface.h" #include "rtc_base/synchronization/mutex.h" #include "rtc_base/thread_annotations.h" diff --git a/test/pc/e2e/stats_poller_test.cc b/test/pc/e2e/stats_poller_test.cc index ce6ea2476c..76e206d73f 100644 --- a/test/pc/e2e/stats_poller_test.cc +++ b/test/pc/e2e/stats_poller_test.cc @@ -10,9 +10,14 @@ #include "test/pc/e2e/stats_poller.h" +#include "absl/strings/string_view.h" +#include "api/scoped_refptr.h" #include "api/stats/rtc_stats_collector_callback.h" +#include "api/stats/rtc_stats_report.h" +#include "api/test/stats_observer_interface.h" #include "test/gmock.h" #include "test/gtest.h" +#include "test/pc/e2e/stats_provider.h" namespace webrtc { namespace webrtc_pc_e2e { diff --git a/test/pc/e2e/test_activities_executor.cc b/test/pc/e2e/test_activities_executor.cc index cad4f63249..9fcf0eafd8 100644 --- a/test/pc/e2e/test_activities_executor.cc +++ b/test/pc/e2e/test_activities_executor.cc @@ -10,13 +10,18 @@ #include "test/pc/e2e/test_activities_executor.h" -#include +#include +#include #include -#include "absl/memory/memory.h" +#include "api/task_queue/task_queue_base.h" +#include "api/units/time_delta.h" +#include "api/units/timestamp.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" +#include "rtc_base/synchronization/mutex.h" #include "rtc_base/task_queue_for_test.h" +#include "rtc_base/task_utils/repeating_task.h" namespace webrtc { namespace webrtc_pc_e2e { diff --git a/test/pc/e2e/test_activities_executor.h b/test/pc/e2e/test_activities_executor.h index 1d9d7ca1c5..7e7f6e31db 100644 --- a/test/pc/e2e/test_activities_executor.h +++ b/test/pc/e2e/test_activities_executor.h @@ -11,6 +11,7 @@ #ifndef TEST_PC_E2E_TEST_ACTIVITIES_EXECUTOR_H_ #define TEST_PC_E2E_TEST_ACTIVITIES_EXECUTOR_H_ +#include #include #include #include @@ -21,6 +22,7 @@ #include "rtc_base/synchronization/mutex.h" #include "rtc_base/task_queue_for_test.h" #include "rtc_base/task_utils/repeating_task.h" +#include "rtc_base/thread_annotations.h" #include "system_wrappers/include/clock.h" namespace webrtc { diff --git a/test/pc/e2e/test_peer.cc b/test/pc/e2e/test_peer.cc index 9028f947dc..a414656873 100644 --- a/test/pc/e2e/test_peer.cc +++ b/test/pc/e2e/test_peer.cc @@ -113,14 +113,12 @@ bool TestPeer::SetRemoteDescription( } bool TestPeer::AddIceCandidates( - std::vector> candidates) { + std::vector> candidates) { RTC_CHECK(wrapper_) << "TestPeer is already closed"; bool success = true; for (auto& candidate : candidates) { if (!pc()->AddIceCandidate(candidate.get())) { - std::string candidate_str; - bool res = candidate->ToString(&candidate_str); - RTC_CHECK(res); + std::string candidate_str = candidate->ToString(); RTC_LOG(LS_ERROR) << "Failed to add ICE candidate, candidate_str=" << candidate_str; success = false; diff --git a/test/pc/e2e/test_peer.h b/test/pc/e2e/test_peer.h index db13e8986b..f9c09e93dc 100644 --- a/test/pc/e2e/test_peer.h +++ b/test/pc/e2e/test_peer.h @@ -151,8 +151,7 @@ class TestPeer final : public StatsProvider { } // Adds provided `candidates` to the owned peer connection. - bool AddIceCandidates( - std::vector> candidates); + bool AddIceCandidates(std::vector> candidates); // Closes underlying peer connection and destroys all related objects freeing // up related resources. @@ -185,7 +184,7 @@ class TestPeer final : public StatsProvider { std::unique_ptr wrapper_; std::vector video_sources_; - std::vector> remote_ice_candidates_; + std::vector> remote_ice_candidates_; }; } // namespace webrtc_pc_e2e diff --git a/test/pc/e2e/test_peer_factory.cc b/test/pc/e2e/test_peer_factory.cc index 85d356a182..ca78fa4be6 100644 --- a/test/pc/e2e/test_peer_factory.cc +++ b/test/pc/e2e/test_peer_factory.cc @@ -12,6 +12,7 @@ #include #include #include +#include #include #include @@ -282,6 +283,7 @@ std::unique_ptr TestPeerFactory::CreateTestPeer( std::vector video_sources = configurer->ReleaseVideoSources(); RTC_DCHECK(components); + RTC_DCHECK(components->pcf_dependencies->field_trials); RTC_DCHECK(params); RTC_DCHECK(configurable_params); RTC_DCHECK_EQ(configurable_params->video_configs.size(), @@ -290,7 +292,7 @@ std::unique_ptr TestPeerFactory::CreateTestPeer( params->rtc_configuration.sdp_semantics = SdpSemantics::kUnifiedPlan; const Environment env = CreateEnvironment( - std::move(components->pcf_dependencies->trials), + std::move(components->pcf_dependencies->field_trials), time_controller_.GetClock(), time_controller_.GetTaskQueueFactory()); // Create peer connection factory. diff --git a/test/peer_scenario/BUILD.gn b/test/peer_scenario/BUILD.gn index b56607f80a..8edf94aeda 100644 --- a/test/peer_scenario/BUILD.gn +++ b/test/peer_scenario/BUILD.gn @@ -23,6 +23,7 @@ if (rtc_include_tests) { ] deps = [ "..:create_frame_generator_capturer", + "..:create_test_field_trials", "..:fake_video_codecs", "..:fileutils", "..:frame_generator_capturer", @@ -32,6 +33,7 @@ if (rtc_include_tests) { "../../api:audio_options_api", "../../api:candidate", "../../api:enable_media_with_defaults", + "../../api:field_trials", "../../api:libjingle_peerconnection_api", "../../api:make_ref_counted", "../../api:media_stream_interface", @@ -46,6 +48,7 @@ if (rtc_include_tests) { "../../api/test/network_emulation", "../../api/transport:datagram_transport_interface", "../../api/transport:enums", + "../../api/units:time_delta", "../../api/video:video_frame", "../../api/video_codecs:scalability_mode", "../../api/video_codecs:video_codecs_api", @@ -77,6 +80,7 @@ if (rtc_include_tests) { "../../pc:pc_test_utils", "../../pc:rtp_transport_internal", "../../pc:session_description", + "../../rtc_base:async_packet_socket", "../../rtc_base:checks", "../../rtc_base:copy_on_write_buffer", "../../rtc_base:crypto_random", @@ -97,6 +101,7 @@ if (rtc_include_tests) { "//third_party/abseil-cpp/absl/container:inlined_vector", "//third_party/abseil-cpp/absl/flags:flag", "//third_party/abseil-cpp/absl/memory", + "//third_party/abseil-cpp/absl/strings", ] } } diff --git a/test/peer_scenario/peer_scenario.cc b/test/peer_scenario/peer_scenario.cc index 8dca6bae26..4aa1aa6a3b 100644 --- a/test/peer_scenario/peer_scenario.cc +++ b/test/peer_scenario/peer_scenario.cc @@ -9,16 +9,30 @@ */ #include "test/peer_scenario/peer_scenario.h" +#include +#include +#include +#include +#include + #include "absl/flags/flag.h" -#include "absl/memory/memory.h" -#include "rtc_base/null_socket_server.h" -#include "rtc_base/string_encode.h" -#include "rtc_base/strings/string_builder.h" +#include "absl/strings/str_cat.h" +#include "api/jsep.h" +#include "api/media_stream_interface.h" +#include "api/test/network_emulation_manager.h" +#include "api/units/time_delta.h" +#include "api/video/video_source_interface.h" +#include "rtc_base/checks.h" +#include "rtc_base/logging.h" +#include "test/gtest.h" #include "test/logging/file_log_writer.h" +#include "test/logging/log_writer.h" +#include "test/network/network_emulation.h" #include "test/network/network_emulation_manager.h" +#include "test/peer_scenario/peer_scenario_client.h" +#include "test/peer_scenario/signaling_route.h" +#include "test/scenario/stats_collection.h" #include "test/testsupport/file_utils.h" -#include "test/time_controller/real_time_controller.h" -#include "test/time_controller/simulated_time_controller.h" ABSL_FLAG(bool, peer_logs, false, "Save logs from peer scenario framework."); ABSL_FLAG(std::string, diff --git a/test/peer_scenario/peer_scenario.h b/test/peer_scenario/peer_scenario.h index f9cf063cb3..01f7152189 100644 --- a/test/peer_scenario/peer_scenario.h +++ b/test/peer_scenario/peer_scenario.h @@ -18,12 +18,20 @@ // for media input and networking. Additionally it provides direct access to the // underlying peer connection class. +#include #include +#include +#include #include -#include "api/test/time_controller.h" +#include "api/media_stream_interface.h" +#include "api/test/network_emulation_manager.h" +#include "api/units/time_delta.h" +#include "rtc_base/thread.h" +#include "system_wrappers/include/clock.h" #include "test/gtest.h" #include "test/logging/log_writer.h" +#include "test/network/network_emulation.h" #include "test/network/network_emulation_manager.h" #include "test/peer_scenario/peer_scenario_client.h" #include "test/peer_scenario/signaling_route.h" diff --git a/test/peer_scenario/peer_scenario_client.cc b/test/peer_scenario/peer_scenario_client.cc index f5a207c4e9..417cada52f 100644 --- a/test/peer_scenario/peer_scenario_client.cc +++ b/test/peer_scenario/peer_scenario_client.cc @@ -26,6 +26,7 @@ #include "api/enable_media_with_defaults.h" #include "api/environment/environment.h" #include "api/environment/environment_factory.h" +#include "api/field_trials.h" #include "api/jsep.h" #include "api/make_ref_counted.h" #include "api/media_stream_interface.h" @@ -122,7 +123,7 @@ class LambdaPeerConnectionObserver final : public PeerConnectionObserver { for (const auto& handler : handlers_->on_ice_gathering_change) handler(new_state); } - void OnIceCandidate(const IceCandidateInterface* candidate) override { + void OnIceCandidate(const IceCandidate* candidate) override { for (const auto& handler : handlers_->on_ice_candidate) handler(candidate); } @@ -240,8 +241,10 @@ PeerScenarioClient::PeerScenarioClient( Thread* signaling_thread, std::unique_ptr log_writer_factory, PeerScenarioClient::Config config) - : env_(CreateEnvironment(net->time_controller()->GetClock(), - net->time_controller()->GetTaskQueueFactory())), + : env_(CreateEnvironment( + std::make_unique(std::move(config.field_trials)), + net->time_controller()->GetClock(), + net->time_controller()->GetTaskQueueFactory())), endpoints_(CreateEndpoints(net, config.endpoints)), signaling_thread_(signaling_thread), log_writer_factory_(std::move(log_writer_factory)), @@ -464,7 +467,7 @@ void PeerScenarioClient::SetSdpAnswer( } void PeerScenarioClient::AddIceCandidate( - std::unique_ptr candidate) { + std::unique_ptr candidate) { RTC_DCHECK_RUN_ON(signaling_thread_); if (peer_connection_->signaling_state() == PeerConnectionInterface::SignalingState::kStable && diff --git a/test/peer_scenario/peer_scenario_client.h b/test/peer_scenario/peer_scenario_client.h index 6e2510fda1..a4c4b48aea 100644 --- a/test/peer_scenario/peer_scenario_client.h +++ b/test/peer_scenario/peer_scenario_client.h @@ -22,6 +22,7 @@ #include "api/candidate.h" #include "api/data_channel_interface.h" #include "api/environment/environment.h" +#include "api/field_trials.h" #include "api/jsep.h" #include "api/media_stream_interface.h" #include "api/peer_connection_interface.h" @@ -39,6 +40,7 @@ #include "rtc_base/thread_annotations.h" #include "system_wrappers/include/clock.h" #include "test/create_frame_generator_capturer.h" +#include "test/create_test_field_trials.h" #include "test/frame_generator_capturer.h" #include "test/logging/log_writer.h" @@ -66,8 +68,7 @@ class PeerScenarioClient { on_connection_change; std::vector> on_ice_gathering_change; - std::vector> - on_ice_candidate; + std::vector> on_ice_candidate; std::vector candidate); + void AddIceCandidate(std::unique_ptr candidate); private: const Environment env_; @@ -185,7 +187,7 @@ class PeerScenarioClient { const std::unique_ptr observer_; std::map*>> track_id_to_video_sinks_ RTC_GUARDED_BY(signaling_thread_); - std::list> pending_ice_candidates_ + std::list> pending_ice_candidates_ RTC_GUARDED_BY(signaling_thread_); scoped_refptr pc_factory_; diff --git a/test/peer_scenario/scenario_connection.cc b/test/peer_scenario/scenario_connection.cc index bdbba3b9f0..4787b9036d 100644 --- a/test/peer_scenario/scenario_connection.cc +++ b/test/peer_scenario/scenario_connection.cc @@ -41,6 +41,7 @@ #include "pc/jsep_transport_controller.h" #include "pc/rtp_transport_internal.h" #include "pc/session_description.h" +#include "rtc_base/async_packet_socket.h" #include "rtc_base/checks.h" #include "rtc_base/copy_on_write_buffer.h" #include "rtc_base/crypto_random.h" @@ -146,6 +147,7 @@ ScenarioIceConnectionImpl::ScenarioIceConnectionImpl( network_thread_, port_allocator_.get(), /*async_resolver_factory*/ nullptr, + /*lna_permission_factory*/ nullptr, payload_type_picker_, CreateJsepConfig())) { SendTask(network_thread_, [this] { diff --git a/test/peer_scenario/scenario_connection.h b/test/peer_scenario/scenario_connection.h index 3b00542c27..4f24ce4d62 100644 --- a/test/peer_scenario/scenario_connection.h +++ b/test/peer_scenario/scenario_connection.h @@ -10,17 +10,19 @@ #ifndef TEST_PEER_SCENARIO_SCENARIO_CONNECTION_H_ #define TEST_PEER_SCENARIO_SCENARIO_CONNECTION_H_ -#include +#include #include #include #include +#include "api/array_view.h" #include "api/candidate.h" #include "api/environment/environment.h" #include "api/jsep.h" +#include "api/test/network_emulation/network_emulation_interfaces.h" #include "p2p/base/transport_description.h" +#include "rtc_base/copy_on_write_buffer.h" #include "test/network/network_emulation_manager.h" -#include "test/scoped_key_value_config.h" namespace webrtc { @@ -57,8 +59,6 @@ class ScenarioIceConnection { virtual EmulatedEndpoint* endpoint() = 0; virtual const TransportDescription& transport_description() const = 0; - - webrtc::test::ScopedKeyValueConfig field_trials; }; } // namespace webrtc diff --git a/test/peer_scenario/signaling_route.cc b/test/peer_scenario/signaling_route.cc index 8688c1abd8..7fe3b859e0 100644 --- a/test/peer_scenario/signaling_route.cc +++ b/test/peer_scenario/signaling_route.cc @@ -9,9 +9,16 @@ */ #include "test/peer_scenario/signaling_route.h" +#include +#include #include +#include +#include -#include "test/network/network_emulation_manager.h" +#include "api/jsep.h" +#include "api/test/network_emulation/cross_traffic.h" +#include "rtc_base/checks.h" +#include "test/peer_scenario/peer_scenario_client.h" namespace webrtc { namespace test { @@ -21,14 +28,13 @@ constexpr size_t kSdpPacketSize = 1200; struct IceMessage { IceMessage() = default; - explicit IceMessage(const IceCandidateInterface* candidate) + explicit IceMessage(const IceCandidate* candidate) : sdp_mid(candidate->sdp_mid()), - sdp_mline_index(candidate->sdp_mline_index()) { - RTC_CHECK(candidate->ToString(&sdp_line)); - } - std::unique_ptr AsCandidate() const { + sdp_mline_index(candidate->sdp_mline_index()), + sdp_line(candidate->ToString()) {} + std::unique_ptr AsCandidate() const { SdpParseError err; - std::unique_ptr candidate( + std::unique_ptr candidate( CreateIceCandidate(sdp_mid, sdp_mline_index, sdp_line, &err)); RTC_CHECK(candidate) << "Failed to parse: \"" << err.line << "\". Reason: " << err.description; @@ -43,7 +49,7 @@ void StartIceSignalingForRoute(PeerScenarioClient* caller, PeerScenarioClient* callee, CrossTrafficRoute* send_route) { caller->handlers()->on_ice_candidate.push_back( - [=](const IceCandidateInterface* candidate) { + [=](const IceCandidate* candidate) { IceMessage msg(candidate); send_route->NetworkDelayedAction(kIcePacketSize, [callee, msg]() { callee->thread()->PostTask( diff --git a/test/peer_scenario/signaling_route.h b/test/peer_scenario/signaling_route.h index 9b317d2552..a2f7381286 100644 --- a/test/peer_scenario/signaling_route.h +++ b/test/peer_scenario/signaling_route.h @@ -10,10 +10,10 @@ #ifndef TEST_PEER_SCENARIO_SIGNALING_ROUTE_H_ #define TEST_PEER_SCENARIO_SIGNALING_ROUTE_H_ -#include -#include +#include -#include "test/network/network_emulation_manager.h" +#include "api/jsep.h" +#include "api/test/network_emulation/cross_traffic.h" #include "test/peer_scenario/peer_scenario_client.h" namespace webrtc { diff --git a/test/peer_scenario/tests/BUILD.gn b/test/peer_scenario/tests/BUILD.gn index 2ad8c8572a..85a30dee65 100644 --- a/test/peer_scenario/tests/BUILD.gn +++ b/test/peer_scenario/tests/BUILD.gn @@ -20,27 +20,31 @@ if (rtc_include_tests) { ] deps = [ "..:peer_scenario", - "../../:create_frame_generator_capturer", - "../../:field_trial", - "../../:test_support", + "../..:create_frame_generator_capturer", + "../..:test_support", + "../../../api:audio_options_api", "../../../api:libjingle_peerconnection_api", "../../../api:make_ref_counted", "../../../api:rtc_stats_api", "../../../api:rtp_parameters", - "../../../api:rtp_sender_interface", "../../../api:rtp_transceiver_direction", "../../../api:scoped_refptr", "../../../api/test/network_emulation", "../../../api/transport:ecn_marking", "../../../api/units:data_rate", "../../../api/units:time_delta", + "../../../api/video:video_frame", "../../../media:stream_params", "../../../modules/rtp_rtcp:rtp_rtcp_format", "../../../pc:media_session", "../../../pc:pc_test_utils", "../../../pc:session_description", "../../../rtc_base:checks", + "../../../rtc_base:copy_on_write_buffer", "../../../rtc_base:logging", + "../../../rtc_base:network_constants", + "../../scenario", + "//third_party/abseil-cpp/absl/strings", ] if (rtc_enable_protobuf) { deps += [ diff --git a/test/peer_scenario/tests/l4s_test.cc b/test/peer_scenario/tests/l4s_test.cc index b68fba2658..f65a24fff9 100644 --- a/test/peer_scenario/tests/l4s_test.cc +++ b/test/peer_scenario/tests/l4s_test.cc @@ -9,8 +9,16 @@ */ #include +#include +#include "absl/strings/str_cat.h" +#include "api/jsep.h" +#include "api/make_ref_counted.h" +#include "api/scoped_refptr.h" +#include "api/stats/rtc_stats_report.h" #include "api/stats/rtcstats_objects.h" +#include "api/test/network_emulation/network_emulation_interfaces.h" +#include "api/transport/ecn_marking.h" #include "api/units/data_rate.h" #include "api/units/time_delta.h" #include "modules/rtp_rtcp/include/rtp_rtcp_defines.h" @@ -19,8 +27,10 @@ #include "modules/rtp_rtcp/source/rtcp_packet/transport_feedback.h" #include "modules/rtp_rtcp/source/rtp_util.h" #include "pc/test/mock_peer_connection_observers.h" +#include "rtc_base/checks.h" +#include "rtc_base/logging.h" +#include "rtc_base/network_constants.h" #include "test/create_frame_generator_capturer.h" -#include "test/field_trial.h" #include "test/gmock.h" #include "test/gtest.h" #include "test/peer_scenario/peer_scenario.h" @@ -110,12 +120,11 @@ DataRate GetAvailableSendBitrate( return DataRate::BitsPerSec(*stats[0]->available_outgoing_bitrate); } -TEST(L4STest, NegotiateAndUseCcfbIfEnabled) { - test::ScopedFieldTrials trials( - "WebRTC-RFC8888CongestionControlFeedback/Enabled/"); +TEST(L4STest, DISABLED_NegotiateAndUseCcfbIfEnabled) { PeerScenario s(*test_info_); - PeerScenarioClient::Config config = PeerScenarioClient::Config(); + PeerScenarioClient::Config config; + config.field_trials.Set("WebRTC-RFC8888CongestionControlFeedback", "Enabled"); config.disable_encryption = true; PeerScenarioClient* caller = s.CreateClient(config); PeerScenarioClient* callee = s.CreateClient(config); @@ -176,22 +185,17 @@ TEST(L4STest, NegotiateAndUseCcfbIfEnabled) { s.ProcessMessages(TimeDelta::Seconds(2)); EXPECT_GT(send_node_feedback_counter.FeedbackAccordingToRfc8888(), 0); - // TODO: bugs.webrtc.org/42225697 - Fix bug. Caller sends both transport - // sequence number feedback and congestion control feedback. So - // callee still send packets with transport sequence number header extensions - // even though it has been removed from the answer. - // EXPECT_EQ(send_node_feedback_counter.FeedbackAccordingToTransportCc(), 0); + EXPECT_EQ(send_node_feedback_counter.FeedbackAccordingToTransportCc(), 0); EXPECT_GT(ret_node_feedback_counter.FeedbackAccordingToRfc8888(), 0); EXPECT_EQ(ret_node_feedback_counter.FeedbackAccordingToTransportCc(), 0); } TEST(L4STest, CallerAdaptToLinkCapacityWithoutEcn) { - test::ScopedFieldTrials trials( - "WebRTC-RFC8888CongestionControlFeedback/Enabled/"); PeerScenario s(*test_info_); - PeerScenarioClient::Config config = PeerScenarioClient::Config(); + PeerScenarioClient::Config config; + config.field_trials.Set("WebRTC-RFC8888CongestionControlFeedback", "Enabled"); PeerScenarioClient* caller = s.CreateClient(config); PeerScenarioClient* callee = s.CreateClient(config); @@ -226,11 +230,10 @@ TEST(L4STest, CallerAdaptToLinkCapacityWithoutEcn) { } TEST(L4STest, SendsEct1UntilFirstFeedback) { - test::ScopedFieldTrials trials( - "WebRTC-RFC8888CongestionControlFeedback/Enabled/"); PeerScenario s(*test_info_); - PeerScenarioClient::Config config = PeerScenarioClient::Config(); + PeerScenarioClient::Config config; + config.field_trials.Set("WebRTC-RFC8888CongestionControlFeedback", "Enabled"); config.disable_encryption = true; PeerScenarioClient* caller = s.CreateClient(config); PeerScenarioClient* callee = s.CreateClient(config); @@ -281,11 +284,10 @@ TEST(L4STest, SendsEct1UntilFirstFeedback) { } TEST(L4STest, SendsEct1AfterRouteChange) { - test::ScopedFieldTrials trials( - "WebRTC-RFC8888CongestionControlFeedback/Enabled/"); PeerScenario s(*test_info_); PeerScenarioClient::Config config; + config.field_trials.Set("WebRTC-RFC8888CongestionControlFeedback", "Enabled"); config.disable_encryption = true; config.endpoints = {{0, {.type = AdapterType::ADAPTER_TYPE_WIFI}}}; PeerScenarioClient* caller = s.CreateClient(config); diff --git a/test/peer_scenario/tests/peer_scenario_quality_test.cc b/test/peer_scenario/tests/peer_scenario_quality_test.cc index 911a68720f..4ec88ef430 100644 --- a/test/peer_scenario/tests/peer_scenario_quality_test.cc +++ b/test/peer_scenario/tests/peer_scenario_quality_test.cc @@ -8,9 +8,11 @@ * be found in the AUTHORS file in the root of the source tree. */ +#include "api/units/time_delta.h" #include "test/gtest.h" #include "test/peer_scenario/peer_scenario.h" #include "test/peer_scenario/peer_scenario_client.h" +#include "test/scenario/stats_collection.h" namespace webrtc { namespace test { diff --git a/test/peer_scenario/tests/remote_estimate_test.cc b/test/peer_scenario/tests/remote_estimate_test.cc index 8dee3435a7..d8dddcbc79 100644 --- a/test/peer_scenario/tests/remote_estimate_test.cc +++ b/test/peer_scenario/tests/remote_estimate_test.cc @@ -8,15 +8,21 @@ * be found in the AUTHORS file in the root of the source tree. */ +#include + +#include "api/audio_options.h" +#include "api/jsep.h" +#include "api/test/network_emulation/network_emulation_interfaces.h" #include "modules/rtp_rtcp/include/rtp_header_extension_map.h" +#include "modules/rtp_rtcp/include/rtp_rtcp_defines.h" #include "modules/rtp_rtcp/source/rtp_header_extensions.h" #include "modules/rtp_rtcp/source/rtp_packet.h" -#include "modules/rtp_rtcp/source/rtp_util.h" #include "pc/media_session.h" #include "pc/session_description.h" -#include "test/field_trial.h" +#include "rtc_base/checks.h" #include "test/gtest.h" #include "test/peer_scenario/peer_scenario.h" +#include "test/peer_scenario/peer_scenario_client.h" namespace webrtc { namespace test { diff --git a/test/peer_scenario/tests/unsignaled_stream_test.cc b/test/peer_scenario/tests/unsignaled_stream_test.cc index 32bccbd939..4c818fa18f 100644 --- a/test/peer_scenario/tests/unsignaled_stream_test.cc +++ b/test/peer_scenario/tests/unsignaled_stream_test.cc @@ -8,13 +8,30 @@ * be found in the AUTHORS file in the root of the source tree. */ +#include +#include +#include +#include +#include +#include +#include + +#include "api/jsep.h" +#include "api/rtp_parameters.h" +#include "api/test/network_emulation/network_emulation_interfaces.h" +#include "api/video/video_frame.h" +#include "api/video/video_sink_interface.h" #include "media/base/stream_params.h" +#include "modules/rtp_rtcp/include/rtp_header_extension_map.h" #include "modules/rtp_rtcp/source/byte_io.h" #include "modules/rtp_rtcp/source/rtp_header_extensions.h" +#include "modules/rtp_rtcp/source/rtp_packet.h" #include "modules/rtp_rtcp/source/rtp_util.h" #include "pc/session_description.h" +#include "rtc_base/copy_on_write_buffer.h" #include "test/gtest.h" #include "test/peer_scenario/peer_scenario.h" +#include "test/peer_scenario/peer_scenario_client.h" namespace webrtc { namespace test { diff --git a/test/platform_video_capturer.cc b/test/platform_video_capturer.cc index fb3392a052..4bc9183209 100644 --- a/test/platform_video_capturer.cc +++ b/test/platform_video_capturer.cc @@ -9,7 +9,11 @@ */ #include "test/platform_video_capturer.h" +#include +#include + #include "absl/memory/memory.h" +#include "test/test_video_capturer.h" #if defined(WEBRTC_MAC) #include "test/mac_capturer.h" #else diff --git a/test/platform_video_capturer.h b/test/platform_video_capturer.h index 241ba87df8..2c5ba84bfe 100644 --- a/test/platform_video_capturer.h +++ b/test/platform_video_capturer.h @@ -10,6 +10,7 @@ #ifndef TEST_PLATFORM_VIDEO_CAPTURER_H_ #define TEST_PLATFORM_VIDEO_CAPTURER_H_ +#include #include #include "test/test_video_capturer.h" diff --git a/test/rtcp_packet_parser.cc b/test/rtcp_packet_parser.cc index f0a7465290..eb74ad96b9 100644 --- a/test/rtcp_packet_parser.cc +++ b/test/rtcp_packet_parser.cc @@ -10,8 +10,25 @@ #include "test/rtcp_packet_parser.h" +#include + +#include "api/array_view.h" +#include "modules/rtp_rtcp/source/rtcp_packet/app.h" +#include "modules/rtp_rtcp/source/rtcp_packet/bye.h" +#include "modules/rtp_rtcp/source/rtcp_packet/common_header.h" +#include "modules/rtp_rtcp/source/rtcp_packet/extended_reports.h" +#include "modules/rtp_rtcp/source/rtcp_packet/fir.h" +#include "modules/rtp_rtcp/source/rtcp_packet/nack.h" +#include "modules/rtp_rtcp/source/rtcp_packet/pli.h" #include "modules/rtp_rtcp/source/rtcp_packet/psfb.h" +#include "modules/rtp_rtcp/source/rtcp_packet/rapid_resync_request.h" +#include "modules/rtp_rtcp/source/rtcp_packet/receiver_report.h" #include "modules/rtp_rtcp/source/rtcp_packet/rtpfb.h" +#include "modules/rtp_rtcp/source/rtcp_packet/sdes.h" +#include "modules/rtp_rtcp/source/rtcp_packet/sender_report.h" +#include "modules/rtp_rtcp/source/rtcp_packet/tmmbn.h" +#include "modules/rtp_rtcp/source/rtcp_packet/tmmbr.h" +#include "modules/rtp_rtcp/source/rtcp_packet/transport_feedback.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" diff --git a/test/rtp_file_reader.cc b/test/rtp_file_reader.cc index d1718f6345..e7f5845cfb 100644 --- a/test/rtp_file_reader.cc +++ b/test/rtp_file_reader.cc @@ -10,15 +10,21 @@ #include "test/rtp_file_reader.h" +#include +#include +#include +#include #include +#include +#include #include #include #include "absl/strings/string_view.h" +#include "api/array_view.h" #include "modules/rtp_rtcp/source/rtp_util.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" -#include "rtc_base/system/arch.h" #include "rtc_base/time_utils.h" namespace { diff --git a/test/rtp_file_reader.h b/test/rtp_file_reader.h index 4af704d202..c7224af108 100644 --- a/test/rtp_file_reader.h +++ b/test/rtp_file_reader.h @@ -10,9 +10,9 @@ #ifndef TEST_RTP_FILE_READER_H_ #define TEST_RTP_FILE_READER_H_ +#include #include #include -#include #include "absl/strings/string_view.h" diff --git a/test/rtp_file_reader_unittest.cc b/test/rtp_file_reader_unittest.cc index eb15d873f0..7236f6c9d3 100644 --- a/test/rtp_file_reader_unittest.cc +++ b/test/rtp_file_reader_unittest.cc @@ -10,8 +10,10 @@ #include "test/rtp_file_reader.h" +#include #include #include +#include #include "api/array_view.h" #include "modules/rtp_rtcp/source/rtp_util.h" diff --git a/test/rtp_file_writer.cc b/test/rtp_file_writer.cc index 118d8cdd29..e11a3ac099 100644 --- a/test/rtp_file_writer.cc +++ b/test/rtp_file_writer.cc @@ -10,13 +10,13 @@ #include "test/rtp_file_writer.h" -#include -#include - +#include +#include #include #include #include "rtc_base/checks.h" +#include "test/rtp_file_reader.h" namespace webrtc { namespace test { diff --git a/test/rtp_file_writer_unittest.cc b/test/rtp_file_writer_unittest.cc index 5d51e46ef4..e21dd433d8 100644 --- a/test/rtp_file_writer_unittest.cc +++ b/test/rtp_file_writer_unittest.cc @@ -10,10 +10,10 @@ #include "test/rtp_file_writer.h" -#include -#include - +#include +#include #include +#include #include "test/gtest.h" #include "test/rtp_file_reader.h" diff --git a/test/run_loop.cc b/test/run_loop.cc index 7bcde87022..b3e0c4a5f8 100644 --- a/test/run_loop.cc +++ b/test/run_loop.cc @@ -9,6 +9,11 @@ */ #include "test/run_loop.h" +#include "api/task_queue/task_queue_base.h" +#include "api/units/time_delta.h" +#include "rtc_base/socket.h" +#include "rtc_base/socket_server.h" +#include "rtc_base/thread.h" #include "rtc_base/time_utils.h" namespace webrtc { diff --git a/test/run_loop.h b/test/run_loop.h index 17638f624e..29b77af0d0 100644 --- a/test/run_loop.h +++ b/test/run_loop.h @@ -14,6 +14,9 @@ #include "absl/functional/any_invocable.h" #include "api/task_queue/task_queue_base.h" +#include "api/units/time_delta.h" +#include "rtc_base/socket.h" +#include "rtc_base/socket_server.h" #include "rtc_base/thread.h" namespace webrtc { diff --git a/test/scenario/BUILD.gn b/test/scenario/BUILD.gn index b7fd6a3506..7616dc237d 100644 --- a/test/scenario/BUILD.gn +++ b/test/scenario/BUILD.gn @@ -15,6 +15,8 @@ rtc_library("column_printer") { "column_printer.h", ] deps = [ + "../../api:libjingle_logging_api", + "../../rtc_base:checks", "../../rtc_base:macromagic", "../../rtc_base:stringutils", "../logging:log_writer", @@ -69,6 +71,8 @@ if (rtc_include_tests && !build_with_chromium) { ] deps = [ ":column_printer", + "..:create_test_field_trials", + "..:encoder_settings", "..:frame_generator_capturer", "..:test_video_capturer", "..:video_test_constants", @@ -81,9 +85,12 @@ if (rtc_include_tests && !build_with_chromium) { "../../api:array_view", "../../api:create_frame_generator", "../../api:fec_controller_api", + "../../api:field_trials", "../../api:frame_generator_api", "../../api:libjingle_logging_api", "../../api:libjingle_peerconnection_api", + "../../api:make_ref_counted", + "../../api:network_emulation_manager_api", "../../api:rtc_event_log_output_file", "../../api:rtp_headers", "../../api:rtp_parameters", @@ -92,6 +99,7 @@ if (rtc_include_tests && !build_with_chromium) { "../../api:time_controller", "../../api:transport_api", "../../api/audio:audio_device", + "../../api/audio:audio_processing", "../../api/audio:builtin_audio_processing_builder", "../../api/audio_codecs:audio_codecs_api", "../../api/audio_codecs:builtin_audio_decoder_factory", @@ -110,6 +118,7 @@ if (rtc_include_tests && !build_with_chromium) { "../../api/units:time_delta", "../../api/units:timestamp", "../../api/video:builtin_video_bitrate_allocator_factory", + "../../api/video:video_bitrate_allocator_factory", "../../api/video:video_frame", "../../api/video:video_rtp_headers", "../../api/video_codecs:scalability_mode", @@ -161,6 +170,7 @@ if (rtc_include_tests && !build_with_chromium) { "../../rtc_base/synchronization:mutex", "../../rtc_base/task_utils:repeating_task", "../../system_wrappers", + "../../video/config:encoder_config", "../../video/config:streams_config", "../logging:log_writer", "../network:emulated_network", @@ -199,8 +209,17 @@ if (rtc_include_tests && !build_with_chromium) { ":scenario", "../../api/test/network_emulation", "../../api/test/network_emulation:create_cross_traffic", + "../../api/transport:bitrate_settings", + "../../api/units:data_rate", + "../../api/units:time_delta", + "../../api/units:timestamp", + "../../api/video_codecs:scalability_mode", + "../../call:call_interfaces", + "../../call:video_receive_stream_api", + "../../call:video_send_stream_api", "../../logging:mocks", "../../rtc_base:checks", + "../../rtc_base:rtc_stats_counters", "../../system_wrappers", "../../system_wrappers:field_trial", "../../test:field_trial", diff --git a/test/scenario/audio_stream.h b/test/scenario/audio_stream.h index de011170f4..8cc8a4e6e7 100644 --- a/test/scenario/audio_stream.h +++ b/test/scenario/audio_stream.h @@ -9,13 +9,18 @@ */ #ifndef TEST_SCENARIO_AUDIO_STREAM_H_ #define TEST_SCENARIO_AUDIO_STREAM_H_ -#include -#include +#include #include +#include "api/audio_codecs/audio_decoder_factory.h" +#include "api/audio_codecs/audio_encoder_factory.h" +#include "api/call/transport.h" +#include "api/rtp_parameters.h" +#include "api/scoped_refptr.h" +#include "call/audio_receive_stream.h" +#include "call/audio_send_stream.h" #include "test/scenario/call_client.h" #include "test/scenario/column_printer.h" -#include "test/scenario/network_node.h" #include "test/scenario/scenario_config.h" namespace webrtc { diff --git a/test/scenario/call_client.cc b/test/scenario/call_client.cc index 1f6719d88d..332facbe15 100644 --- a/test/scenario/call_client.cc +++ b/test/scenario/call_client.cc @@ -20,6 +20,7 @@ #include "api/audio/builtin_audio_processing_builder.h" #include "api/environment/environment.h" #include "api/environment/environment_factory.h" +#include "api/field_trials.h" #include "api/media_types.h" #include "api/rtc_event_log/rtc_event_log.h" #include "api/rtc_event_log/rtc_event_log_factory.h" @@ -55,7 +56,7 @@ namespace webrtc { namespace test { namespace { -static constexpr size_t kNumSsrcs = 6; +constexpr size_t kNumSsrcs = 6; const uint32_t kSendRtxSsrcs[kNumSsrcs] = {0xBADCAFD, 0xBADCAFE, 0xBADCAFF, 0xBADCB00, 0xBADCB01, 0xBADCB02}; const uint32_t kVideoSendSsrcs[kNumSsrcs] = {0xC0FFED, 0xC0FFEE, 0xC0FFEF, @@ -234,8 +235,10 @@ CallClient::CallClient( std::unique_ptr log_writer_factory, CallClientConfig config) : time_controller_(time_controller), - env_(CreateEnvironment(time_controller_->CreateTaskQueueFactory(), - time_controller_->GetClock())), + env_(CreateEnvironment( + std::make_unique(std::move(config.field_trials)), + time_controller_->CreateTaskQueueFactory(), + time_controller_->GetClock())), log_writer_factory_(std::move(log_writer_factory)), network_controller_factory_(log_writer_factory_.get(), config.transport), task_queue_(env_.task_queue_factory().CreateTaskQueue( diff --git a/test/scenario/call_client.h b/test/scenario/call_client.h index 6237584a6c..9691ef3073 100644 --- a/test/scenario/call_client.h +++ b/test/scenario/call_client.h @@ -10,6 +10,8 @@ #ifndef TEST_SCENARIO_CALL_CLIENT_H_ #define TEST_SCENARIO_CALL_CLIENT_H_ +#include +#include #include #include #include @@ -18,17 +20,26 @@ #include "api/array_view.h" #include "api/audio/audio_device.h" +#include "api/audio/audio_processing.h" #include "api/environment/environment.h" -#include "api/rtc_event_log/rtc_event_log.h" +#include "api/media_types.h" +#include "api/rtc_event_log_output.h" #include "api/rtp_parameters.h" +#include "api/scoped_refptr.h" +#include "api/test/network_emulation/network_emulation_interfaces.h" #include "api/test/time_controller.h" +#include "api/transport/bitrate_settings.h" +#include "api/transport/network_control.h" +#include "api/transport/network_types.h" #include "api/units/data_rate.h" +#include "api/units/time_delta.h" +#include "api/units/timestamp.h" +#include "call/audio_state.h" #include "call/call.h" #include "modules/congestion_controller/goog_cc/test/goog_cc_printer.h" #include "modules/rtp_rtcp/include/rtp_header_extension_map.h" #include "rtc_base/task_queue_for_test.h" #include "test/logging/log_writer.h" -#include "test/network/network_emulation.h" #include "test/scenario/column_printer.h" #include "test/scenario/network_node.h" #include "test/scenario/scenario_config.h" diff --git a/test/scenario/column_printer.cc b/test/scenario/column_printer.cc index 76746869c0..ecc7d36df8 100644 --- a/test/scenario/column_printer.cc +++ b/test/scenario/column_printer.cc @@ -9,6 +9,17 @@ */ #include "test/scenario/column_printer.h" +#include +#include +#include +#include +#include +#include + +#include "api/rtc_event_log_output.h" +#include "rtc_base/checks.h" +#include "rtc_base/strings/string_builder.h" + namespace webrtc { namespace test { diff --git a/test/scenario/column_printer.h b/test/scenario/column_printer.h index 0f31b651c8..28b75c8b82 100644 --- a/test/scenario/column_printer.h +++ b/test/scenario/column_printer.h @@ -9,13 +9,14 @@ */ #ifndef TEST_SCENARIO_COLUMN_PRINTER_H_ #define TEST_SCENARIO_COLUMN_PRINTER_H_ +#include #include #include #include #include +#include "api/rtc_event_log_output.h" #include "rtc_base/strings/string_builder.h" -#include "test/logging/log_writer.h" namespace webrtc { namespace test { diff --git a/test/scenario/hardware_codecs.cc b/test/scenario/hardware_codecs.cc index cac0f10dc9..0b11ed15f8 100644 --- a/test/scenario/hardware_codecs.cc +++ b/test/scenario/hardware_codecs.cc @@ -9,6 +9,10 @@ */ #include "test/scenario/hardware_codecs.h" +#include + +#include "api/video_codecs/video_decoder_factory.h" +#include "api/video_codecs/video_encoder_factory.h" #include "rtc_base/checks.h" #ifdef WEBRTC_ANDROID diff --git a/test/scenario/performance_stats.cc b/test/scenario/performance_stats.cc index e12be8a003..9a60bb862d 100644 --- a/test/scenario/performance_stats.cc +++ b/test/scenario/performance_stats.cc @@ -11,6 +11,10 @@ #include +#include "api/units/timestamp.h" +#include "api/video/video_frame_buffer.h" +#include "rtc_base/checks.h" + namespace webrtc { namespace test { void VideoFramesStats::AddFrameInfo(const VideoFrameBuffer& frame, diff --git a/test/scenario/performance_stats.h b/test/scenario/performance_stats.h index 7025ae6003..aa0ae7f069 100644 --- a/test/scenario/performance_stats.h +++ b/test/scenario/performance_stats.h @@ -10,6 +10,7 @@ #ifndef TEST_SCENARIO_PERFORMANCE_STATS_H_ #define TEST_SCENARIO_PERFORMANCE_STATS_H_ +#include "api/scoped_refptr.h" #include "api/units/data_rate.h" #include "api/units/time_delta.h" #include "api/units/timestamp.h" diff --git a/test/scenario/performance_stats_unittest.cc b/test/scenario/performance_stats_unittest.cc index 8d87c87745..f4bfaec772 100644 --- a/test/scenario/performance_stats_unittest.cc +++ b/test/scenario/performance_stats_unittest.cc @@ -7,8 +7,10 @@ * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ -#include "test/scenario/performance_stats.h" +#include "api/units/time_delta.h" +#include "api/units/timestamp.h" +#include "rtc_base/numerics/event_rate_counter.h" #include "test/gtest.h" namespace webrtc { diff --git a/test/scenario/probing_test.cc b/test/scenario/probing_test.cc index f3cbe977c0..b328e90a9a 100644 --- a/test/scenario/probing_test.cc +++ b/test/scenario/probing_test.cc @@ -7,8 +7,13 @@ * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ +#include "api/transport/bitrate_settings.h" +#include "api/units/data_rate.h" +#include "api/units/time_delta.h" +#include "api/video_codecs/scalability_mode.h" #include "test/gtest.h" #include "test/scenario/scenario.h" +#include "test/scenario/scenario_config.h" namespace webrtc { namespace test { diff --git a/test/scenario/scenario.cc b/test/scenario/scenario.cc index 0201d069ce..ae45c85fdf 100644 --- a/test/scenario/scenario.cc +++ b/test/scenario/scenario.cc @@ -9,18 +9,41 @@ */ #include "test/scenario/scenario.h" -#include +#include +#include +#include #include +#include +#include +#include #include "absl/flags/flag.h" -#include "absl/flags/parse.h" +#include "absl/functional/any_invocable.h" #include "absl/strings/string_view.h" #include "api/audio_codecs/builtin_audio_decoder_factory.h" #include "api/audio_codecs/builtin_audio_encoder_factory.h" +#include "api/rtp_parameters.h" +#include "api/task_queue/task_queue_factory.h" +#include "api/test/network_emulation_manager.h" +#include "api/units/data_size.h" +#include "api/units/time_delta.h" +#include "api/units/timestamp.h" +#include "rtc_base/checks.h" +#include "rtc_base/logging.h" #include "rtc_base/socket_address.h" +#include "rtc_base/strings/string_builder.h" +#include "rtc_base/task_utils/repeating_task.h" +#include "test/gtest.h" #include "test/logging/file_log_writer.h" +#include "test/logging/log_writer.h" #include "test/network/network_emulation.h" #include "test/network/network_emulation_manager.h" +#include "test/network/simulated_network.h" +#include "test/scenario/audio_stream.h" +#include "test/scenario/call_client.h" +#include "test/scenario/column_printer.h" +#include "test/scenario/network_node.h" +#include "test/scenario/scenario_config.h" #include "test/scenario/video_stream.h" #include "test/testsupport/file_utils.h" diff --git a/test/scenario/scenario.h b/test/scenario/scenario.h index 92ce202c1e..bfb14454ed 100644 --- a/test/scenario/scenario.h +++ b/test/scenario/scenario.h @@ -9,19 +9,26 @@ */ #ifndef TEST_SCENARIO_SCENARIO_H_ #define TEST_SCENARIO_SCENARIO_H_ +#include +#include #include -#include #include #include #include "absl/functional/any_invocable.h" #include "absl/strings/string_view.h" +#include "api/audio_codecs/audio_decoder_factory.h" +#include "api/audio_codecs/audio_encoder_factory.h" +#include "api/rtc_event_log_output.h" +#include "api/scoped_refptr.h" #include "api/task_queue/task_queue_base.h" -#include "api/test/time_controller.h" -#include "rtc_base/fake_clock.h" -#include "rtc_base/task_utils/repeating_task.h" +#include "api/units/data_size.h" +#include "api/units/time_delta.h" +#include "api/units/timestamp.h" +#include "system_wrappers/include/clock.h" #include "test/gtest.h" #include "test/logging/log_writer.h" +#include "test/network/network_emulation.h" #include "test/network/network_emulation_manager.h" #include "test/scenario/audio_stream.h" #include "test/scenario/call_client.h" diff --git a/test/scenario/scenario_config.h b/test/scenario/scenario_config.h index b47a220cc7..3ad7b6ab4b 100644 --- a/test/scenario/scenario_config.h +++ b/test/scenario/scenario_config.h @@ -12,10 +12,13 @@ #include +#include #include #include +#include #include "api/fec_controller.h" +#include "api/field_trials.h" #include "api/rtp_parameters.h" #include "api/test/frame_generator_interface.h" #include "api/transport/network_control.h" @@ -24,6 +27,7 @@ #include "api/units/time_delta.h" #include "api/video/video_codec_type.h" #include "api/video_codecs/scalability_mode.h" +#include "test/create_test_field_trials.h" #include "test/scenario/performance_stats.h" namespace webrtc { @@ -53,6 +57,7 @@ struct TransportControllerConfig { struct CallClientConfig { TransportControllerConfig transport; + FieldTrials field_trials = CreateTestFieldTrials(); // Allows the pacer to send out multiple packets in a burst. // The number of bites that can be sent in one burst is pacer_burst_interval * // current bwe. 40ms is the default Chrome setting. diff --git a/test/scenario/scenario_unittest.cc b/test/scenario/scenario_unittest.cc index 6861151a2d..cb957fd8b4 100644 --- a/test/scenario/scenario_unittest.cc +++ b/test/scenario/scenario_unittest.cc @@ -13,9 +13,12 @@ #include "api/test/network_emulation/create_cross_traffic.h" #include "api/test/network_emulation/cross_traffic.h" -#include "test/field_trial.h" +#include "api/units/data_rate.h" +#include "api/units/time_delta.h" +#include "call/video_send_stream.h" #include "test/gtest.h" #include "test/logging/memory_log_writer.h" +#include "test/scenario/scenario_config.h" #include "test/scenario/stats_collection.h" namespace webrtc { @@ -146,12 +149,10 @@ TEST(ScenarioTest, WritesToRtcEventLog) { TEST(ScenarioTest, RetransmitsVideoPacketsInAudioAndVideoCallWithSendSideBweAndLoss) { - // Make sure audio packets are included in transport feedback. - test::ScopedFieldTrials override_field_trials( - "WebRTC-Audio-ABWENoTWCC/Disabled/"); - Scenario s; CallClientConfig call_client_config; + // Make sure audio packets are included in transport feedback. + call_client_config.field_trials.Set("WebRTC-Audio-ABWENoTWCC", "Disabled"); call_client_config.transport.rates.start_rate = DataRate::KilobitsPerSec(300); auto* alice = s.CreateClient("alice", call_client_config); auto* bob = s.CreateClient("bob", call_client_config); diff --git a/test/scenario/stats_collection.h b/test/scenario/stats_collection.h index 1be0508060..61e87abb48 100644 --- a/test/scenario/stats_collection.h +++ b/test/scenario/stats_collection.h @@ -10,13 +10,20 @@ #ifndef TEST_SCENARIO_STATS_COLLECTION_H_ #define TEST_SCENARIO_STATS_COLLECTION_H_ +#include +#include #include #include #include +#include +#include "api/rtc_event_log_output.h" +#include "api/units/timestamp.h" +#include "call/audio_receive_stream.h" #include "call/call.h" +#include "call/video_receive_stream.h" +#include "call/video_send_stream.h" #include "rtc_base/thread.h" -#include "test/logging/log_writer.h" #include "test/scenario/performance_stats.h" namespace webrtc { diff --git a/test/scenario/stats_collection_unittest.cc b/test/scenario/stats_collection_unittest.cc index 9f46f10073..1c46c23f3a 100644 --- a/test/scenario/stats_collection_unittest.cc +++ b/test/scenario/stats_collection_unittest.cc @@ -9,8 +9,15 @@ */ #include "test/scenario/stats_collection.h" +#include "api/units/data_rate.h" +#include "api/units/time_delta.h" +#include "call/audio_receive_stream.h" +#include "call/video_receive_stream.h" +#include "call/video_send_stream.h" #include "test/gtest.h" #include "test/scenario/scenario.h" +#include "test/scenario/scenario_config.h" +#include "test/scenario/video_stream.h" namespace webrtc { namespace test { diff --git a/test/scenario/video_frame_matcher.cc b/test/scenario/video_frame_matcher.cc index 27e580e3ec..93fb54afc8 100644 --- a/test/scenario/video_frame_matcher.cc +++ b/test/scenario/video_frame_matcher.cc @@ -9,11 +9,20 @@ */ #include "test/scenario/video_frame_matcher.h" +#include +#include #include +#include +#include "api/scoped_refptr.h" +#include "api/units/timestamp.h" +#include "api/video/video_frame.h" +#include "api/video/video_sink_interface.h" +#include "api/video/video_source_interface.h" #include "common_video/libyuv/include/webrtc_libyuv.h" #include "rtc_base/checks.h" -#include "rtc_base/event.h" +#include "system_wrappers/include/clock.h" +#include "test/scenario/performance_stats.h" namespace webrtc { namespace test { diff --git a/test/scenario/video_frame_matcher.h b/test/scenario/video_frame_matcher.h index 343909a654..5f34bcd292 100644 --- a/test/scenario/video_frame_matcher.h +++ b/test/scenario/video_frame_matcher.h @@ -10,15 +10,16 @@ #ifndef TEST_SCENARIO_VIDEO_FRAME_MATCHER_H_ #define TEST_SCENARIO_VIDEO_FRAME_MATCHER_H_ +#include #include +#include #include -#include -#include -#include #include +#include "api/scoped_refptr.h" #include "api/units/timestamp.h" #include "api/video/video_frame.h" +#include "api/video/video_frame_buffer.h" #include "api/video/video_sink_interface.h" #include "api/video/video_source_interface.h" #include "rtc_base/ref_counted_object.h" diff --git a/test/scenario/video_stream.cc b/test/scenario/video_stream.cc index 0fe68161b2..5c15b620e0 100644 --- a/test/scenario/video_stream.cc +++ b/test/scenario/video_stream.cc @@ -10,25 +10,61 @@ #include "test/scenario/video_stream.h" #include +#include +#include +#include #include +#include +#include #include +#include #include "absl/strings/match.h" +#include "api/call/transport.h" +#include "api/environment/environment.h" +#include "api/make_ref_counted.h" +#include "api/media_types.h" +#include "api/rtp_headers.h" +#include "api/rtp_parameters.h" +#include "api/scoped_refptr.h" #include "api/test/create_frame_generator.h" #include "api/test/frame_generator_interface.h" +#include "api/test/video/function_video_decoder_factory.h" #include "api/test/video/function_video_encoder_factory.h" +#include "api/units/data_rate.h" +#include "api/units/time_delta.h" #include "api/video/builtin_video_bitrate_allocator_factory.h" -#include "media/base/media_constants.h" +#include "api/video/video_codec_type.h" +#include "api/video/video_frame.h" +#include "api/video/video_sink_interface.h" +#include "api/video_codecs/scalability_mode.h" +#include "api/video_codecs/sdp_video_format.h" +#include "api/video_codecs/video_codec.h" +#include "api/video_codecs/video_encoder.h" +#include "call/flexfec_receive_stream.h" +#include "call/video_receive_stream.h" +#include "call/video_send_stream.h" #include "media/engine/internal_decoder_factory.h" #include "media/engine/internal_encoder_factory.h" #include "media/engine/webrtc_video_engine.h" #include "modules/video_coding/svc/scalability_mode_util.h" -#include "test/call_test.h" +#include "rtc_base/checks.h" +#include "rtc_base/strings/string_builder.h" +#include "rtc_base/synchronization/mutex.h" +#include "system_wrappers/include/clock.h" +#include "test/encoder_settings.h" +#include "test/fake_decoder.h" #include "test/fake_encoder.h" +#include "test/fake_vp8_encoder.h" +#include "test/frame_generator_capturer.h" +#include "test/scenario/call_client.h" +#include "test/scenario/column_printer.h" #include "test/scenario/hardware_codecs.h" +#include "test/scenario/scenario_config.h" +#include "test/scenario/video_frame_matcher.h" #include "test/testsupport/file_utils.h" #include "test/video_test_constants.h" -#include "video/config/encoder_stream_factory.h" +#include "video/config/video_encoder_config.h" namespace webrtc { namespace test { diff --git a/test/scenario/video_stream.h b/test/scenario/video_stream.h index 7e774182df..0ae6b0d5ad 100644 --- a/test/scenario/video_stream.h +++ b/test/scenario/video_stream.h @@ -9,21 +9,30 @@ */ #ifndef TEST_SCENARIO_VIDEO_STREAM_H_ #define TEST_SCENARIO_VIDEO_STREAM_H_ +#include +#include +#include #include -#include #include +#include "api/call/transport.h" +#include "api/rtp_parameters.h" +#include "api/video/video_bitrate_allocator_factory.h" +#include "api/video/video_frame.h" +#include "api/video/video_sink_interface.h" +#include "api/video_codecs/video_encoder_factory.h" +#include "call/flexfec_receive_stream.h" +#include "call/video_receive_stream.h" +#include "call/video_send_stream.h" #include "rtc_base/synchronization/mutex.h" +#include "rtc_base/thread_annotations.h" #include "test/fake_encoder.h" #include "test/fake_videorenderer.h" #include "test/frame_generator_capturer.h" -#include "test/logging/log_writer.h" #include "test/scenario/call_client.h" #include "test/scenario/column_printer.h" -#include "test/scenario/network_node.h" #include "test/scenario/scenario_config.h" #include "test/scenario/video_frame_matcher.h" -#include "test/test_video_capturer.h" namespace webrtc { namespace test { diff --git a/test/scenario/video_stream_unittest.cc b/test/scenario/video_stream_unittest.cc index 0ece8b0eff..3eef42ac9a 100644 --- a/test/scenario/video_stream_unittest.cc +++ b/test/scenario/video_stream_unittest.cc @@ -8,12 +8,23 @@ * be found in the AUTHORS file in the root of the source tree. */ #include +#include +#include +#include +#include #include "api/test/network_emulation/create_cross_traffic.h" #include "api/test/network_emulation/cross_traffic.h" -#include "test/field_trial.h" +#include "api/units/data_rate.h" +#include "api/units/time_delta.h" +#include "api/units/timestamp.h" +#include "api/video_codecs/scalability_mode.h" +#include "call/video_send_stream.h" +#include "rtc_base/checks.h" #include "test/gtest.h" +#include "test/scenario/performance_stats.h" #include "test/scenario/scenario.h" +#include "test/scenario/scenario_config.h" #include "test/video_test_constants.h" namespace webrtc { diff --git a/test/scoped_key_value_config.cc b/test/scoped_key_value_config.cc index 6f1230da4b..3e0497730b 100644 --- a/test/scoped_key_value_config.cc +++ b/test/scoped_key_value_config.cc @@ -10,6 +10,12 @@ #include "test/scoped_key_value_config.h" +#include +#include +#include +#include + +#include "absl/strings/string_view.h" #include "rtc_base/checks.h" #include "system_wrappers/include/field_trial.h" #include "test/field_trial.h" diff --git a/test/test_flags.cc b/test/test_flags.cc index 4df2583672..b53e60dc6b 100644 --- a/test/test_flags.cc +++ b/test/test_flags.cc @@ -15,13 +15,6 @@ #include "absl/flags/flag.h" -ABSL_FLAG(std::string, - force_fieldtrials, - "", - "Field trials control experimental feature code which can be forced. " - "E.g. running with --force_fieldtrials=WebRTC-FooFeature/Enable/" - " will assign the group Enable to field trial WebRTC-FooFeature."); - ABSL_FLAG(std::vector, plot, {}, diff --git a/test/test_flags.h b/test/test_flags.h index 84f1c29503..1eab5babfd 100644 --- a/test/test_flags.h +++ b/test/test_flags.h @@ -15,7 +15,11 @@ #include "absl/flags/declare.h" +// TODO: bugs.webrtc.org/419453427 - Remove this flag declaration from the +// header when tests are migrated to use this flag through the +// CreateTestFieldTrials function bypassing global field trials string. ABSL_DECLARE_FLAG(std::string, force_fieldtrials); + ABSL_DECLARE_FLAG(std::vector, plot); ABSL_DECLARE_FLAG(std::string, isolated_script_test_perf_output); ABSL_DECLARE_FLAG(std::string, webrtc_test_metrics_output_path); diff --git a/test/test_main.cc b/test/test_main.cc index d811fd0e6d..9dcc57c2d5 100644 --- a/test/test_main.cc +++ b/test/test_main.cc @@ -8,8 +8,9 @@ * be found in the AUTHORS file in the root of the source tree. */ +#include +#include #include -#include #include #include diff --git a/test/test_main_lib.cc b/test/test_main_lib.cc index 5348d1c0be..c665cc731c 100644 --- a/test/test_main_lib.cc +++ b/test/test_main_lib.cc @@ -10,6 +10,8 @@ #include "test/test_main_lib.h" +#include + #include #include #include diff --git a/test/test_video_capturer.cc b/test/test_video_capturer.cc index 42d8c3db2b..e63f604d89 100644 --- a/test/test_video_capturer.cc +++ b/test/test_video_capturer.cc @@ -10,12 +10,17 @@ #include "test/test_video_capturer.h" -#include +#include +#include #include "api/scoped_refptr.h" #include "api/video/i420_buffer.h" +#include "api/video/video_frame.h" #include "api/video/video_frame_buffer.h" #include "api/video/video_rotation.h" +#include "api/video/video_sink_interface.h" +#include "api/video/video_source_interface.h" +#include "rtc_base/synchronization/mutex.h" namespace webrtc { namespace test { diff --git a/test/test_video_capturer.h b/test/test_video_capturer.h index 41ffdb79c5..66f0c8b2f4 100644 --- a/test/test_video_capturer.h +++ b/test/test_video_capturer.h @@ -10,15 +10,17 @@ #ifndef TEST_TEST_VIDEO_CAPTURER_H_ #define TEST_TEST_VIDEO_CAPTURER_H_ -#include - #include +#include +#include #include "api/video/video_frame.h" +#include "api/video/video_sink_interface.h" #include "api/video/video_source_interface.h" #include "media/base/video_adapter.h" #include "media/base/video_broadcaster.h" #include "rtc_base/synchronization/mutex.h" +#include "rtc_base/thread_annotations.h" namespace webrtc { namespace test { diff --git a/test/testsupport/copy_to_file_audio_capturer.cc b/test/testsupport/copy_to_file_audio_capturer.cc index df93f26f4b..afb7175a5e 100644 --- a/test/testsupport/copy_to_file_audio_capturer.cc +++ b/test/testsupport/copy_to_file_audio_capturer.cc @@ -10,9 +10,15 @@ #include "test/testsupport/copy_to_file_audio_capturer.h" +#include #include +#include #include +#include "common_audio/wav_file.h" +#include "modules/audio_device/include/test_audio_device.h" +#include "rtc_base/buffer.h" + namespace webrtc { namespace test { diff --git a/test/testsupport/copy_to_file_audio_capturer.h b/test/testsupport/copy_to_file_audio_capturer.h index 2f7859ff0b..2ecd914601 100644 --- a/test/testsupport/copy_to_file_audio_capturer.h +++ b/test/testsupport/copy_to_file_audio_capturer.h @@ -11,11 +11,10 @@ #ifndef TEST_TESTSUPPORT_COPY_TO_FILE_AUDIO_CAPTURER_H_ #define TEST_TESTSUPPORT_COPY_TO_FILE_AUDIO_CAPTURER_H_ +#include #include -#include #include -#include "api/array_view.h" #include "common_audio/wav_file.h" #include "modules/audio_device/include/test_audio_device.h" #include "rtc_base/buffer.h" diff --git a/test/testsupport/copy_to_file_audio_capturer_unittest.cc b/test/testsupport/copy_to_file_audio_capturer_unittest.cc index 023b61da2b..236ecd3032 100644 --- a/test/testsupport/copy_to_file_audio_capturer_unittest.cc +++ b/test/testsupport/copy_to_file_audio_capturer_unittest.cc @@ -10,10 +10,15 @@ #include "test/testsupport/copy_to_file_audio_capturer.h" +#include + +#include #include +#include #include #include "modules/audio_device/include/test_audio_device.h" +#include "rtc_base/buffer.h" #include "test/gtest.h" #include "test/testsupport/file_utils.h" diff --git a/test/testsupport/file_utils.cc b/test/testsupport/file_utils.cc index 27bb59cbaa..491dcdecdb 100644 --- a/test/testsupport/file_utils.cc +++ b/test/testsupport/file_utils.cc @@ -10,6 +10,8 @@ #include "test/testsupport/file_utils.h" +#include + #include #include #include @@ -21,7 +23,6 @@ #include "absl/strings/string_view.h" #include "rtc_base/checks.h" #include "rtc_base/crypto_random.h" -#include "rtc_base/string_utils.h" #include "rtc_base/strings/string_builder.h" #include "test/testsupport/file_utils_override.h" @@ -30,6 +31,8 @@ #endif #if defined(WEBRTC_WIN) +#include +#include #include #include #include @@ -37,8 +40,7 @@ #include #include -#include "Shlwapi.h" -#include "WinDef.h" +#include "rtc_base/string_utils.h" #include "rtc_base/win32.h" #define GET_CURRENT_DIR _getcwd diff --git a/test/testsupport/file_utils_override.cc b/test/testsupport/file_utils_override.cc index 40c0bd60a7..f90d7224e7 100644 --- a/test/testsupport/file_utils_override.cc +++ b/test/testsupport/file_utils_override.cc @@ -10,10 +10,20 @@ #include "test/testsupport/file_utils_override.h" -#include #include +#include +#include +#include +#include + +#include "absl/strings/string_view.h" +#include "rtc_base/checks.h" +#include "rtc_base/strings/string_builder.h" + #if defined(WEBRTC_WIN) +#include +#include #include #include #include @@ -21,8 +31,7 @@ #include #include -#include "Shlwapi.h" -#include "WinDef.h" +#include "rtc_base/string_utils.h" #include "rtc_base/win32.h" #define GET_CURRENT_DIR _getcwd @@ -40,13 +49,9 @@ #include "test/testsupport/mac_file_utils.h" #endif -#include - -#include "absl/strings/string_view.h" -#include "rtc_base/arraysize.h" -#include "rtc_base/checks.h" -#include "rtc_base/string_utils.h" -#include "rtc_base/strings/string_builder.h" +#if defined(WEBRTC_POSIX) && !defined(WEBRTC_MAC) && !defined(WEBRTC_FUCHSIA) +#include +#endif namespace webrtc { namespace test { @@ -100,7 +105,7 @@ std::optional ProjectRootPath() { return std::string(kFuchsiaTestRoot); #else char buf[PATH_MAX]; - ssize_t count = ::readlink("/proc/self/exe", buf, arraysize(buf)); + ssize_t count = ::readlink("/proc/self/exe", buf, std::size(buf)); if (count <= 0) { RTC_DCHECK_NOTREACHED() << "Unable to resolve /proc/self/exe."; return std::nullopt; diff --git a/test/testsupport/file_utils_unittest.cc b/test/testsupport/file_utils_unittest.cc index 62745cb0fa..bbf0445f57 100644 --- a/test/testsupport/file_utils_unittest.cc +++ b/test/testsupport/file_utils_unittest.cc @@ -13,9 +13,11 @@ #include #include +#include #include #include #include +#include #include "absl/strings/string_view.h" #include "rtc_base/checks.h" @@ -27,6 +29,10 @@ #define chdir _chdir #endif +#if defined(WEBRTC_POSIX) +#include +#endif + using ::testing::EndsWith; namespace webrtc { diff --git a/test/testsupport/fixed_fps_video_frame_writer_adapter.cc b/test/testsupport/fixed_fps_video_frame_writer_adapter.cc index 4b90d21c42..84bb85ea1a 100644 --- a/test/testsupport/fixed_fps_video_frame_writer_adapter.cc +++ b/test/testsupport/fixed_fps_video_frame_writer_adapter.cc @@ -10,14 +10,16 @@ #include "test/testsupport/fixed_fps_video_frame_writer_adapter.h" -#include +#include #include #include +#include "api/test/video/video_frame_writer.h" #include "api/units/time_delta.h" -#include "api/video/video_sink_interface.h" +#include "api/units/timestamp.h" +#include "api/video/video_frame.h" #include "rtc_base/checks.h" -#include "test/testsupport/video_frame_writer.h" +#include "system_wrappers/include/clock.h" namespace webrtc { namespace test { diff --git a/test/testsupport/fixed_fps_video_frame_writer_adapter.h b/test/testsupport/fixed_fps_video_frame_writer_adapter.h index 6d966bf4cf..00909a4f4b 100644 --- a/test/testsupport/fixed_fps_video_frame_writer_adapter.h +++ b/test/testsupport/fixed_fps_video_frame_writer_adapter.h @@ -15,9 +15,10 @@ #include #include "api/test/video/video_frame_writer.h" -#include "api/video/video_sink_interface.h" +#include "api/units/time_delta.h" +#include "api/units/timestamp.h" +#include "api/video/video_frame.h" #include "system_wrappers/include/clock.h" -#include "test/testsupport/video_frame_writer.h" namespace webrtc { namespace test { diff --git a/test/testsupport/fixed_fps_video_frame_writer_adapter_test.cc b/test/testsupport/fixed_fps_video_frame_writer_adapter_test.cc index 473e63dae3..faf40e8cad 100644 --- a/test/testsupport/fixed_fps_video_frame_writer_adapter_test.cc +++ b/test/testsupport/fixed_fps_video_frame_writer_adapter_test.cc @@ -10,18 +10,21 @@ #include "test/testsupport/fixed_fps_video_frame_writer_adapter.h" +#include #include #include #include +#include "api/test/time_controller.h" +#include "api/test/video/video_frame_writer.h" #include "api/units/time_delta.h" #include "api/units/timestamp.h" #include "api/video/i420_buffer.h" #include "api/video/video_frame.h" #include "rtc_base/synchronization/mutex.h" +#include "rtc_base/thread_annotations.h" #include "test/gmock.h" #include "test/gtest.h" -#include "test/testsupport/video_frame_writer.h" #include "test/time_controller/simulated_time_controller.h" namespace webrtc { diff --git a/test/testsupport/frame_reader.h b/test/testsupport/frame_reader.h index c18ea7f5c6..c2b913d576 100644 --- a/test/testsupport/frame_reader.h +++ b/test/testsupport/frame_reader.h @@ -11,8 +11,7 @@ #ifndef TEST_TESTSUPPORT_FRAME_READER_H_ #define TEST_TESTSUPPORT_FRAME_READER_H_ -#include - +#include #include #include #include diff --git a/test/testsupport/frame_writer.h b/test/testsupport/frame_writer.h index 5f85d8bcd4..3959a5df72 100644 --- a/test/testsupport/frame_writer.h +++ b/test/testsupport/frame_writer.h @@ -11,8 +11,9 @@ #ifndef TEST_TESTSUPPORT_FRAME_WRITER_H_ #define TEST_TESTSUPPORT_FRAME_WRITER_H_ -#include - +#include +#include +#include #include #include "api/video/video_frame.h" diff --git a/test/testsupport/ivf_video_frame_generator.cc b/test/testsupport/ivf_video_frame_generator.cc index a50779d25a..704a277253 100644 --- a/test/testsupport/ivf_video_frame_generator.cc +++ b/test/testsupport/ivf_video_frame_generator.cc @@ -10,19 +10,31 @@ #include "test/testsupport/ivf_video_frame_generator.h" +#include +#include #include +#include +#include +#include "absl/strings/string_view.h" #include "api/environment/environment.h" +#include "api/scoped_refptr.h" +#include "api/test/frame_generator_interface.h" +#include "api/units/time_delta.h" #include "api/video/encoded_image.h" #include "api/video/i420_buffer.h" -#include "api/video_codecs/video_codec.h" -#include "media/base/media_constants.h" +#include "api/video/video_codec_type.h" +#include "api/video/video_frame.h" +#include "api/video/video_frame_buffer.h" +#include "api/video_codecs/video_decoder.h" #include "modules/video_coding/codecs/av1/dav1d_decoder.h" #include "modules/video_coding/codecs/h264/include/h264.h" #include "modules/video_coding/codecs/vp8/include/vp8.h" #include "modules/video_coding/codecs/vp9/include/vp9.h" #include "modules/video_coding/include/video_error_codes.h" +#include "modules/video_coding/utility/ivf_file_reader.h" #include "rtc_base/checks.h" +#include "rtc_base/synchronization/mutex.h" #include "rtc_base/system/file_wrapper.h" namespace webrtc { diff --git a/test/testsupport/ivf_video_frame_generator.h b/test/testsupport/ivf_video_frame_generator.h index cb0b97f9b2..237e76b045 100644 --- a/test/testsupport/ivf_video_frame_generator.h +++ b/test/testsupport/ivf_video_frame_generator.h @@ -11,20 +11,20 @@ #ifndef TEST_TESTSUPPORT_IVF_VIDEO_FRAME_GENERATOR_H_ #define TEST_TESTSUPPORT_IVF_VIDEO_FRAME_GENERATOR_H_ +#include +#include #include #include -#include #include "absl/strings/string_view.h" #include "api/environment/environment.h" -#include "api/sequence_checker.h" #include "api/test/frame_generator_interface.h" -#include "api/video/video_codec_type.h" #include "api/video/video_frame.h" #include "api/video_codecs/video_decoder.h" #include "modules/video_coding/utility/ivf_file_reader.h" #include "rtc_base/event.h" #include "rtc_base/synchronization/mutex.h" +#include "rtc_base/thread_annotations.h" namespace webrtc { namespace test { diff --git a/test/testsupport/ivf_video_frame_generator_unittest.cc b/test/testsupport/ivf_video_frame_generator_unittest.cc index a2c3fea3c2..fb5ede5c2f 100644 --- a/test/testsupport/ivf_video_frame_generator_unittest.cc +++ b/test/testsupport/ivf_video_frame_generator_unittest.cc @@ -10,27 +10,36 @@ #include "test/testsupport/ivf_video_frame_generator.h" +#include +#include #include #include +#include #include #include "api/environment/environment.h" #include "api/environment/environment_factory.h" +#include "api/scoped_refptr.h" #include "api/test/create_frame_generator.h" +#include "api/test/frame_generator_interface.h" #include "api/units/time_delta.h" #include "api/video/encoded_image.h" +#include "api/video/video_bitrate_allocation.h" #include "api/video/video_codec_type.h" +#include "api/video/video_frame.h" +#include "api/video/video_frame_buffer.h" #include "api/video_codecs/video_codec.h" #include "api/video_codecs/video_encoder.h" #include "common_video/libyuv/include/webrtc_libyuv.h" -#include "media/base/codec.h" -#include "media/base/media_constants.h" #include "modules/rtp_rtcp/include/rtp_rtcp_defines.h" #include "modules/video_coding/codecs/vp8/include/vp8.h" #include "modules/video_coding/codecs/vp9/include/vp9.h" #include "modules/video_coding/include/video_error_codes.h" #include "modules/video_coding/utility/ivf_file_writer.h" +#include "rtc_base/checks.h" #include "rtc_base/event.h" +#include "rtc_base/system/file_wrapper.h" +#include "rtc_base/thread_annotations.h" #include "test/gtest.h" #include "test/testsupport/file_utils.h" #include "test/video_codec_settings.h" @@ -50,7 +59,7 @@ constexpr int kHeight = 240; constexpr int kVideoFramesCount = 30; constexpr int kMaxFramerate = 30; constexpr TimeDelta kMaxFrameEncodeWaitTimeout = TimeDelta::Seconds(2); -static const VideoEncoder::Capabilities kCapabilities(false); +const VideoEncoder::Capabilities kCapabilities(false); #if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS) || defined(WEBRTC_ARCH_ARM64) constexpr double kExpectedMinPsnr = 35; @@ -69,7 +78,9 @@ class IvfFileWriterEncodedCallback : public EncodedImageCallback { expected_frames_count_(expected_frames_count) { EXPECT_TRUE(file_writer_.get()); } - ~IvfFileWriterEncodedCallback() { EXPECT_TRUE(file_writer_->Close()); } + ~IvfFileWriterEncodedCallback() override { + EXPECT_TRUE(file_writer_->Close()); + } Result OnEncodedImage(const EncodedImage& encoded_image, const CodecSpecificInfo* codec_specific_info) override { diff --git a/test/testsupport/jpeg_frame_writer.cc b/test/testsupport/jpeg_frame_writer.cc index 8bf1ee4630..3b6e417dc3 100644 --- a/test/testsupport/jpeg_frame_writer.cc +++ b/test/testsupport/jpeg_frame_writer.cc @@ -8,10 +8,13 @@ * be found in the AUTHORS file in the root of the source tree. */ -#include +#include +#include +#include +#include +#include "api/video/video_frame.h" #include "common_video/libyuv/include/webrtc_libyuv.h" -#include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "test/testsupport/frame_writer.h" diff --git a/test/testsupport/jpeg_frame_writer_ios.cc b/test/testsupport/jpeg_frame_writer_ios.cc index e72fea102f..150ab8b6e1 100644 --- a/test/testsupport/jpeg_frame_writer_ios.cc +++ b/test/testsupport/jpeg_frame_writer_ios.cc @@ -8,7 +8,9 @@ * be found in the AUTHORS file in the root of the source tree. */ -#include "rtc_base/checks.h" +#include + +#include "api/video/video_frame.h" #include "rtc_base/logging.h" #include "test/testsupport/frame_writer.h" diff --git a/test/testsupport/mock/mock_frame_reader.h b/test/testsupport/mock/mock_frame_reader.h index 1be387b443..9015008065 100644 --- a/test/testsupport/mock/mock_frame_reader.h +++ b/test/testsupport/mock/mock_frame_reader.h @@ -11,7 +11,9 @@ #ifndef TEST_TESTSUPPORT_MOCK_MOCK_FRAME_READER_H_ #define TEST_TESTSUPPORT_MOCK_MOCK_FRAME_READER_H_ +#include "api/scoped_refptr.h" #include "api/video/i420_buffer.h" +#include "api/video/resolution.h" #include "test/gmock.h" #include "test/testsupport/frame_reader.h" diff --git a/test/testsupport/perf_test.cc b/test/testsupport/perf_test.cc index 4c5e0f447e..5bf873b3a3 100644 --- a/test/testsupport/perf_test.cc +++ b/test/testsupport/perf_test.cc @@ -10,21 +10,25 @@ #include "test/testsupport/perf_test.h" -#include - #include -#include +#include +#include +#include #include #include +#include #include #include "absl/strings/string_view.h" +#include "api/array_view.h" #include "api/numerics/samples_stats_counter.h" #include "rtc_base/checks.h" #include "rtc_base/strings/string_builder.h" #include "rtc_base/synchronization/mutex.h" +#include "rtc_base/thread_annotations.h" #include "test/testsupport/file_utils.h" #include "test/testsupport/perf_test_histogram_writer.h" +#include "test/testsupport/perf_test_result_writer.h" namespace webrtc { namespace test { diff --git a/test/testsupport/perf_test.h b/test/testsupport/perf_test.h index 0f48b683ce..f151340021 100644 --- a/test/testsupport/perf_test.h +++ b/test/testsupport/perf_test.h @@ -11,7 +11,7 @@ #ifndef TEST_TESTSUPPORT_PERF_TEST_H_ #define TEST_TESTSUPPORT_PERF_TEST_H_ -#include +#include #include #include diff --git a/test/testsupport/perf_test_histogram_writer.cc b/test/testsupport/perf_test_histogram_writer.cc index de771b9654..b93a9a4b31 100644 --- a/test/testsupport/perf_test_histogram_writer.cc +++ b/test/testsupport/perf_test_histogram_writer.cc @@ -10,16 +10,21 @@ #include "test/testsupport/perf_test_histogram_writer.h" -#include - +#include #include #include +#include +#include #include "absl/strings/string_view.h" -#include "api/numerics/samples_stats_counter.h" +#include "api/array_view.h" +#include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "rtc_base/strings/string_builder.h" #include "rtc_base/synchronization/mutex.h" +#include "rtc_base/thread_annotations.h" +#include "test/testsupport/perf_test.h" +#include "test/testsupport/perf_test_result_writer.h" #include "third_party/catapult/tracing/tracing/value/diagnostics/reserved_infos.h" #include "third_party/catapult/tracing/tracing/value/histogram.h" diff --git a/test/testsupport/perf_test_histogram_writer_no_protobuf.cc b/test/testsupport/perf_test_histogram_writer_no_protobuf.cc index 6bc810b94d..956cbe10a9 100644 --- a/test/testsupport/perf_test_histogram_writer_no_protobuf.cc +++ b/test/testsupport/perf_test_histogram_writer_no_protobuf.cc @@ -8,7 +8,9 @@ * be found in the AUTHORS file in the root of the source tree. */ +#include "rtc_base/checks.h" #include "test/testsupport/perf_test_histogram_writer.h" +#include "test/testsupport/perf_test_result_writer.h" namespace webrtc { namespace test { diff --git a/test/testsupport/perf_test_histogram_writer_unittest.cc b/test/testsupport/perf_test_histogram_writer_unittest.cc index 83025a7447..1d04557762 100644 --- a/test/testsupport/perf_test_histogram_writer_unittest.cc +++ b/test/testsupport/perf_test_histogram_writer_unittest.cc @@ -11,9 +11,11 @@ #include "test/testsupport/perf_test_histogram_writer.h" #include -#include +#include #include "test/gtest.h" +#include "test/testsupport/perf_test.h" +#include "test/testsupport/perf_test_result_writer.h" #include "third_party/catapult/tracing/tracing/value/histogram.h" namespace webrtc { diff --git a/test/testsupport/perf_test_result_writer.h b/test/testsupport/perf_test_result_writer.h index 5ec31de4d2..a4c52e9763 100644 --- a/test/testsupport/perf_test_result_writer.h +++ b/test/testsupport/perf_test_result_writer.h @@ -11,11 +11,10 @@ #ifndef TEST_TESTSUPPORT_PERF_TEST_RESULT_WRITER_H_ #define TEST_TESTSUPPORT_PERF_TEST_RESULT_WRITER_H_ -#include - #include #include "absl/strings/string_view.h" +#include "api/array_view.h" #include "test/testsupport/perf_test.h" namespace webrtc { diff --git a/test/testsupport/perf_test_unittest.cc b/test/testsupport/perf_test_unittest.cc index 509882db08..fad4916a3f 100644 --- a/test/testsupport/perf_test_unittest.cc +++ b/test/testsupport/perf_test_unittest.cc @@ -10,10 +10,10 @@ #include "test/testsupport/perf_test.h" -#include #include #include +#include "api/numerics/samples_stats_counter.h" #include "test/gmock.h" #include "test/gtest.h" #include "test/testsupport/rtc_expect_death.h" diff --git a/test/testsupport/resources_dir_flag.cc b/test/testsupport/resources_dir_flag.cc index 87a449a401..876da1a9d5 100644 --- a/test/testsupport/resources_dir_flag.cc +++ b/test/testsupport/resources_dir_flag.cc @@ -10,6 +10,8 @@ #include "test/testsupport/resources_dir_flag.h" +#include + #include "absl/flags/flag.h" ABSL_FLAG(std::string, diff --git a/test/testsupport/test_artifacts.cc b/test/testsupport/test_artifacts.cc index b0ab046e63..c700ddc4c0 100644 --- a/test/testsupport/test_artifacts.cc +++ b/test/testsupport/test_artifacts.cc @@ -10,10 +10,11 @@ #include "test/testsupport/test_artifacts.h" -#include +#include +#include +#include #include "absl/flags/flag.h" -#include "absl/flags/parse.h" #include "rtc_base/logging.h" #include "rtc_base/system/file_wrapper.h" #include "test/testsupport/file_utils.h" diff --git a/test/testsupport/test_artifacts_unittest.cc b/test/testsupport/test_artifacts_unittest.cc index fb577610fb..fb5d8a4c0b 100644 --- a/test/testsupport/test_artifacts_unittest.cc +++ b/test/testsupport/test_artifacts_unittest.cc @@ -10,8 +10,8 @@ #include "test/testsupport/test_artifacts.h" -#include - +#include +#include #include #include "absl/flags/declare.h" diff --git a/test/testsupport/video_frame_writer.cc b/test/testsupport/video_frame_writer.cc index 96f1b0d810..96c856da59 100644 --- a/test/testsupport/video_frame_writer.cc +++ b/test/testsupport/video_frame_writer.cc @@ -14,12 +14,16 @@ #include #include #include +#include #include #include "api/scoped_refptr.h" #include "api/video/i420_buffer.h" +#include "api/video/video_frame.h" #include "common_video/libyuv/include/webrtc_libyuv.h" -#include "rtc_base/logging.h" +#include "rtc_base/buffer.h" +#include "rtc_base/checks.h" +#include "test/testsupport/frame_writer.h" namespace webrtc { namespace test { diff --git a/test/testsupport/video_frame_writer.h b/test/testsupport/video_frame_writer.h index 1cc4e56284..bc5525e439 100644 --- a/test/testsupport/video_frame_writer.h +++ b/test/testsupport/video_frame_writer.h @@ -16,7 +16,6 @@ #include "api/test/video/video_frame_writer.h" #include "api/video/video_frame.h" -#include "rtc_base/buffer.h" #include "test/testsupport/frame_writer.h" namespace webrtc { diff --git a/test/testsupport/video_frame_writer_unittest.cc b/test/testsupport/video_frame_writer_unittest.cc index de8c618216..2c32409f4c 100644 --- a/test/testsupport/video_frame_writer_unittest.cc +++ b/test/testsupport/video_frame_writer_unittest.cc @@ -10,16 +10,20 @@ #include "test/testsupport/video_frame_writer.h" -#include #include -#include +#include +#include #include #include #include "absl/strings/string_view.h" +#include "api/scoped_refptr.h" #include "api/test/video/video_frame_writer.h" #include "api/video/i420_buffer.h" +#include "api/video/resolution.h" +#include "api/video/video_frame.h" +#include "api/video/video_frame_buffer.h" #include "test/gtest.h" #include "test/testsupport/file_utils.h" #include "test/testsupport/frame_reader.h" diff --git a/test/testsupport/y4m_frame_generator.cc b/test/testsupport/y4m_frame_generator.cc index f7b0eb0f88..462c9a8b23 100644 --- a/test/testsupport/y4m_frame_generator.cc +++ b/test/testsupport/y4m_frame_generator.cc @@ -10,14 +10,15 @@ #include "test/testsupport/y4m_frame_generator.h" -#include -#include - +#include +#include #include #include "absl/strings/string_view.h" #include "api/scoped_refptr.h" +#include "api/test/frame_generator_interface.h" #include "api/video/i420_buffer.h" +#include "api/video/video_frame.h" #include "rtc_base/checks.h" #include "test/testsupport/frame_reader.h" diff --git a/test/testsupport/y4m_frame_generator.h b/test/testsupport/y4m_frame_generator.h index dfffb4a732..774e775481 100644 --- a/test/testsupport/y4m_frame_generator.h +++ b/test/testsupport/y4m_frame_generator.h @@ -18,7 +18,6 @@ #include "absl/strings/string_view.h" #include "api/test/frame_generator_interface.h" -#include "rtc_base/checks.h" #include "test/testsupport/frame_reader.h" namespace webrtc { diff --git a/test/testsupport/y4m_frame_generator_test.cc b/test/testsupport/y4m_frame_generator_test.cc index 24d10c8992..aeaab023bb 100644 --- a/test/testsupport/y4m_frame_generator_test.cc +++ b/test/testsupport/y4m_frame_generator_test.cc @@ -10,13 +10,15 @@ #include "test/testsupport/y4m_frame_generator.h" -#include +#include + #include #include #include #include #include "absl/strings/string_view.h" +#include "api/test/frame_generator_interface.h" #include "test/gtest.h" #include "test/testsupport/file_utils.h" @@ -26,9 +28,9 @@ namespace test { class Y4mFrameGeneratorTest : public testing::Test { protected: Y4mFrameGeneratorTest() = default; - ~Y4mFrameGeneratorTest() = default; + ~Y4mFrameGeneratorTest() override = default; - void SetUp() { + void SetUp() override { input_filepath_ = TempFilename(OutputPath(), "2x2.y4m"); FILE* y4m_file = fopen(input_filepath_.c_str(), "wb"); @@ -43,7 +45,7 @@ class Y4mFrameGeneratorTest : public testing::Test { fclose(y4m_file); } - void TearDown() { remove(input_filepath_.c_str()); } + void TearDown() override { remove(input_filepath_.c_str()); } std::string input_filepath_; }; diff --git a/test/testsupport/y4m_frame_reader.cc b/test/testsupport/y4m_frame_reader.cc index 6d9649d707..8ce849417b 100644 --- a/test/testsupport/y4m_frame_reader.cc +++ b/test/testsupport/y4m_frame_reader.cc @@ -8,17 +8,18 @@ * be found in the AUTHORS file in the root of the source tree. */ -#include - #include +#include +#include +#include #include +#include -#include "api/scoped_refptr.h" -#include "api/video/i420_buffer.h" +#include "absl/strings/string_view.h" +#include "api/video/resolution.h" #include "common_video/libyuv/include/webrtc_libyuv.h" -#include "rtc_base/logging.h" +#include "rtc_base/checks.h" #include "rtc_base/string_encode.h" -#include "rtc_base/strings/string_builder.h" #include "test/testsupport/file_utils.h" #include "test/testsupport/frame_reader.h" diff --git a/test/testsupport/y4m_frame_reader_unittest.cc b/test/testsupport/y4m_frame_reader_unittest.cc index 406c69eee3..70be4420ce 100644 --- a/test/testsupport/y4m_frame_reader_unittest.cc +++ b/test/testsupport/y4m_frame_reader_unittest.cc @@ -8,15 +8,17 @@ * be found in the AUTHORS file in the root of the source tree. */ -#include #include +#include #include #include +#include +#include #include "absl/strings/string_view.h" #include "api/scoped_refptr.h" -#include "api/video/i420_buffer.h" +#include "api/video/resolution.h" #include "api/video/video_frame_buffer.h" #include "test/gtest.h" #include "test/testsupport/file_utils.h" diff --git a/test/testsupport/y4m_frame_writer.cc b/test/testsupport/y4m_frame_writer.cc index 1bb4543963..7309f99e84 100644 --- a/test/testsupport/y4m_frame_writer.cc +++ b/test/testsupport/y4m_frame_writer.cc @@ -8,8 +8,8 @@ * be found in the AUTHORS file in the root of the source tree. */ -#include - +#include +#include #include #include "rtc_base/logging.h" diff --git a/test/testsupport/y4m_frame_writer_unittest.cc b/test/testsupport/y4m_frame_writer_unittest.cc index ebb34f53ce..f2acc00777 100644 --- a/test/testsupport/y4m_frame_writer_unittest.cc +++ b/test/testsupport/y4m_frame_writer_unittest.cc @@ -8,10 +8,11 @@ * be found in the AUTHORS file in the root of the source tree. */ -#include #include -#include +#include +#include +#include #include #include diff --git a/test/testsupport/yuv_frame_reader.cc b/test/testsupport/yuv_frame_reader.cc index 4a7273520d..b3383295e3 100644 --- a/test/testsupport/yuv_frame_reader.cc +++ b/test/testsupport/yuv_frame_reader.cc @@ -8,14 +8,16 @@ * be found in the AUTHORS file in the root of the source tree. */ -#include - +#include +#include +#include #include #include "api/scoped_refptr.h" #include "api/video/i420_buffer.h" +#include "api/video/resolution.h" #include "common_video/libyuv/include/webrtc_libyuv.h" -#include "rtc_base/logging.h" +#include "rtc_base/checks.h" #include "test/frame_utils.h" #include "test/testsupport/file_utils.h" #include "test/testsupport/frame_reader.h" diff --git a/test/testsupport/yuv_frame_reader_unittest.cc b/test/testsupport/yuv_frame_reader_unittest.cc index 9d633d7006..28f6fd0693 100644 --- a/test/testsupport/yuv_frame_reader_unittest.cc +++ b/test/testsupport/yuv_frame_reader_unittest.cc @@ -8,14 +8,17 @@ * be found in the AUTHORS file in the root of the source tree. */ -#include #include +#include +#include #include #include +#include +#include #include "api/scoped_refptr.h" -#include "api/video/i420_buffer.h" +#include "api/video/resolution.h" #include "api/video/video_frame_buffer.h" #include "test/gtest.h" #include "test/testsupport/file_utils.h" diff --git a/test/testsupport/yuv_frame_writer.cc b/test/testsupport/yuv_frame_writer.cc index e5e0a6ba7f..1cef6d6279 100644 --- a/test/testsupport/yuv_frame_writer.cc +++ b/test/testsupport/yuv_frame_writer.cc @@ -8,8 +8,8 @@ * be found in the AUTHORS file in the root of the source tree. */ -#include - +#include +#include #include #include "rtc_base/checks.h" diff --git a/test/testsupport/yuv_frame_writer_unittest.cc b/test/testsupport/yuv_frame_writer_unittest.cc index 22a048b7a2..63c3cd14e3 100644 --- a/test/testsupport/yuv_frame_writer_unittest.cc +++ b/test/testsupport/yuv_frame_writer_unittest.cc @@ -8,10 +8,11 @@ * be found in the AUTHORS file in the root of the source tree. */ -#include #include -#include +#include +#include +#include #include #include diff --git a/test/time_controller/BUILD.gn b/test/time_controller/BUILD.gn index 3255594797..0cf531fa29 100644 --- a/test/time_controller/BUILD.gn +++ b/test/time_controller/BUILD.gn @@ -23,6 +23,8 @@ rtc_library("time_controller") { deps = [ "../../api:field_trials_view", + "../../api:function_view", + "../../api:location", "../../api:sequence_checker", "../../api:time_controller", "../../api/task_queue", @@ -30,10 +32,12 @@ rtc_library("time_controller") { "../../api/units:time_delta", "../../api/units:timestamp", "../../rtc_base:checks", + "../../rtc_base:macromagic", "../../rtc_base:null_socket_server", "../../rtc_base:platform_thread_types", "../../rtc_base:rtc_base_tests_utils", "../../rtc_base:rtc_event", + "../../rtc_base:socket", "../../rtc_base:socket_server", "../../rtc_base:threading", "../../rtc_base:timeutils", @@ -58,6 +62,8 @@ if (rtc_include_tests) { "../../api:time_controller", "../../api/task_queue", "../../api/units:time_delta", + "../../api/units:timestamp", + "../../rtc_base:checks", "../../rtc_base:macromagic", "../../rtc_base:rtc_event", "../../rtc_base:task_queue_for_test", diff --git a/test/time_controller/real_time_controller.cc b/test/time_controller/real_time_controller.cc index 5a27d25996..3a9bff9c0d 100644 --- a/test/time_controller/real_time_controller.cc +++ b/test/time_controller/real_time_controller.cc @@ -9,9 +9,18 @@ */ #include "test/time_controller/real_time_controller.h" +#include +#include +#include + #include "api/field_trials_view.h" #include "api/task_queue/default_task_queue_factory.h" +#include "api/task_queue/task_queue_factory.h" +#include "api/units/time_delta.h" #include "rtc_base/null_socket_server.h" +#include "rtc_base/socket_server.h" +#include "rtc_base/thread.h" +#include "system_wrappers/include/clock.h" namespace webrtc { namespace { @@ -22,7 +31,7 @@ class MainThread : public Thread { current_setter_(this) { DoInit(); } - ~MainThread() { + ~MainThread() override { Stop(); DoDestroy(); } diff --git a/test/time_controller/real_time_controller.h b/test/time_controller/real_time_controller.h index 99eb72ece5..73650677da 100644 --- a/test/time_controller/real_time_controller.h +++ b/test/time_controller/real_time_controller.h @@ -10,13 +10,15 @@ #ifndef TEST_TIME_CONTROLLER_REAL_TIME_CONTROLLER_H_ #define TEST_TIME_CONTROLLER_REAL_TIME_CONTROLLER_H_ -#include #include +#include #include "api/field_trials_view.h" #include "api/task_queue/task_queue_factory.h" #include "api/test/time_controller.h" #include "api/units/time_delta.h" +#include "rtc_base/socket_server.h" +#include "rtc_base/thread.h" #include "system_wrappers/include/clock.h" namespace webrtc { diff --git a/test/time_controller/simulated_task_queue.cc b/test/time_controller/simulated_task_queue.cc index 3d786dfdcc..44065fc5cb 100644 --- a/test/time_controller/simulated_task_queue.cc +++ b/test/time_controller/simulated_task_queue.cc @@ -10,7 +10,18 @@ #include "test/time_controller/simulated_task_queue.h" #include +#include +#include #include +#include + +#include "absl/functional/any_invocable.h" +#include "absl/strings/string_view.h" +#include "api/location.h" +#include "api/units/time_delta.h" +#include "api/units/timestamp.h" +#include "rtc_base/synchronization/mutex.h" +#include "test/time_controller/simulated_time_controller.h" namespace webrtc { diff --git a/test/time_controller/simulated_task_queue.h b/test/time_controller/simulated_task_queue.h index 6ca46327b2..5f3d174152 100644 --- a/test/time_controller/simulated_task_queue.h +++ b/test/time_controller/simulated_task_queue.h @@ -12,12 +12,16 @@ #include #include -#include #include #include "absl/functional/any_invocable.h" +#include "absl/strings/string_view.h" +#include "api/location.h" +#include "api/task_queue/task_queue_base.h" #include "api/units/time_delta.h" +#include "api/units/timestamp.h" #include "rtc_base/synchronization/mutex.h" +#include "rtc_base/thread_annotations.h" #include "test/time_controller/simulated_time_controller.h" namespace webrtc { diff --git a/test/time_controller/simulated_thread.cc b/test/time_controller/simulated_thread.cc index d8ff5d9804..16e7d69d60 100644 --- a/test/time_controller/simulated_thread.cc +++ b/test/time_controller/simulated_thread.cc @@ -10,8 +10,24 @@ #include "test/time_controller/simulated_thread.h" #include +#include #include +#include "absl/functional/any_invocable.h" +#include "absl/strings/string_view.h" +#include "api/function_view.h" +#include "api/location.h" +#include "api/task_queue/task_queue_base.h" +#include "api/units/time_delta.h" +#include "api/units/timestamp.h" +#include "rtc_base/checks.h" +#include "rtc_base/socket.h" +#include "rtc_base/socket_server.h" +#include "rtc_base/synchronization/mutex.h" +#include "rtc_base/thread.h" +#include "rtc_base/time_utils.h" +#include "test/time_controller/simulated_time_controller.h" + namespace webrtc { namespace { diff --git a/test/time_controller/simulated_thread.h b/test/time_controller/simulated_thread.h index 2c370a031d..51fe6612a0 100644 --- a/test/time_controller/simulated_thread.h +++ b/test/time_controller/simulated_thread.h @@ -12,7 +12,17 @@ #include +#include "absl/functional/any_invocable.h" +#include "absl/strings/string_view.h" +#include "api/function_view.h" +#include "api/location.h" +#include "api/task_queue/task_queue_base.h" +#include "api/units/time_delta.h" +#include "api/units/timestamp.h" +#include "rtc_base/socket_server.h" #include "rtc_base/synchronization/mutex.h" +#include "rtc_base/thread.h" +#include "rtc_base/thread_annotations.h" #include "test/time_controller/simulated_time_controller.h" namespace webrtc { diff --git a/test/time_controller/simulated_time_controller.h b/test/time_controller/simulated_time_controller.h index a458b97204..b934941fc6 100644 --- a/test/time_controller/simulated_time_controller.h +++ b/test/time_controller/simulated_time_controller.h @@ -12,18 +12,27 @@ #include #include +#include #include -#include #include +#include "absl/functional/any_invocable.h" #include "absl/strings/string_view.h" -#include "api/sequence_checker.h" +#include "api/location.h" +#include "api/task_queue/task_queue_base.h" +#include "api/task_queue/task_queue_factory.h" #include "api/test/time_controller.h" +#include "api/units/time_delta.h" #include "api/units/timestamp.h" +#include "rtc_base/checks.h" #include "rtc_base/fake_clock.h" #include "rtc_base/platform_thread_types.h" +#include "rtc_base/socket_server.h" #include "rtc_base/synchronization/mutex.h" #include "rtc_base/synchronization/yield_policy.h" +#include "rtc_base/thread.h" +#include "rtc_base/thread_annotations.h" +#include "system_wrappers/include/clock.h" namespace webrtc { namespace sim_time_impl { diff --git a/test/time_controller/simulated_time_controller_unittest.cc b/test/time_controller/simulated_time_controller_unittest.cc index 10d741beb4..c68a81d542 100644 --- a/test/time_controller/simulated_time_controller_unittest.cc +++ b/test/time_controller/simulated_time_controller_unittest.cc @@ -12,9 +12,12 @@ #include #include +#include #include "api/task_queue/task_queue_base.h" +#include "api/task_queue/task_queue_factory.h" #include "api/units/time_delta.h" +#include "api/units/timestamp.h" #include "rtc_base/event.h" #include "rtc_base/task_queue_for_test.h" #include "rtc_base/task_utils/repeating_task.h" diff --git a/test/time_controller/time_controller_conformance_test.cc b/test/time_controller/time_controller_conformance_test.cc index 265404156e..19f4216a8b 100644 --- a/test/time_controller/time_controller_conformance_test.cc +++ b/test/time_controller/time_controller_conformance_test.cc @@ -9,10 +9,14 @@ */ #include +#include #include +#include "api/task_queue/task_queue_factory.h" #include "api/test/time_controller.h" #include "api/units/time_delta.h" +#include "api/units/timestamp.h" +#include "rtc_base/checks.h" #include "rtc_base/event.h" #include "rtc_base/synchronization/mutex.h" #include "rtc_base/thread.h" diff --git a/test/vcm_capturer.cc b/test/vcm_capturer.cc index bc022c1a80..b7933130bd 100644 --- a/test/vcm_capturer.cc +++ b/test/vcm_capturer.cc @@ -10,13 +10,17 @@ #include "test/vcm_capturer.h" -#include - +#include +#include #include +#include "api/video/video_frame.h" +#include "common_video/libyuv/include/webrtc_libyuv.h" +#include "modules/video_capture/video_capture.h" #include "modules/video_capture/video_capture_factory.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" +#include "test/test_video_capturer.h" namespace webrtc { namespace test { diff --git a/test/vcm_capturer.h b/test/vcm_capturer.h index 433cb48159..722f2c8181 100644 --- a/test/vcm_capturer.h +++ b/test/vcm_capturer.h @@ -10,11 +10,13 @@ #ifndef TEST_VCM_CAPTURER_H_ #define TEST_VCM_CAPTURER_H_ -#include -#include +#include #include "api/scoped_refptr.h" +#include "api/video/video_frame.h" +#include "api/video/video_sink_interface.h" #include "modules/video_capture/video_capture.h" +#include "modules/video_capture/video_capture_defines.h" #include "rtc_base/logging.h" #include "test/test_video_capturer.h" diff --git a/test/video_codec_settings.h b/test/video_codec_settings.h index 5ef4ed3e4a..4d8ae7e810 100644 --- a/test/video_codec_settings.h +++ b/test/video_codec_settings.h @@ -10,6 +10,10 @@ #ifndef TEST_VIDEO_CODEC_SETTINGS_H_ #define TEST_VIDEO_CODEC_SETTINGS_H_ +#include + +#include "api/video/video_codec_type.h" +#include "api/video_codecs/video_codec.h" #include "api/video_codecs/video_encoder.h" namespace webrtc { diff --git a/test/video_codec_tester.cc b/test/video_codec_tester.cc index 7c8d21019d..dbfb6b10ad 100644 --- a/test/video_codec_tester.cc +++ b/test/video_codec_tester.cc @@ -85,7 +85,6 @@ #include "rtc_base/thread.h" #include "rtc_base/thread_annotations.h" #include "rtc_base/time_utils.h" -#include "test/testsupport/file_utils.h" #include "test/testsupport/frame_reader.h" #include "test/testsupport/video_frame_writer.h" #include "third_party/libyuv/include/libyuv/compare.h" @@ -537,7 +536,7 @@ class VideoCodecAnalyzer : public VideoCodecTester::VideoCodecStats { } } - std::vector Slice(Filter filter, bool merge) const { + std::vector Slice(Filter filter, bool merge) const override { std::vector slice; for (const auto& [timestamp_rtp, temporal_unit_frames] : frames_) { if (temporal_unit_frames.empty()) { @@ -615,7 +614,7 @@ class VideoCodecAnalyzer : public VideoCodecTester::VideoCodecStats { return slice; } - Stream Aggregate(Filter filter) const { + Stream Aggregate(Filter filter) const override { std::vector frames = Slice(filter, /*merge=*/true); Stream stream; LeakyBucket leaky_bucket; @@ -709,7 +708,7 @@ class VideoCodecAnalyzer : public VideoCodecTester::VideoCodecStats { void LogMetrics(absl::string_view csv_path, std::vector frames, - std::map metadata) const { + std::map metadata) const override { RTC_LOG(LS_INFO) << "Write metrics to " << csv_path; FILE* csv_file = fopen(csv_path.data(), "w"); const std::string delimiter = ";"; @@ -1189,19 +1188,45 @@ class Encoder : public EncodedImageCallback { if (is_simulcast) { vc.numberOfSimulcastStreams = num_spatial_layers; for (int sidx = 0; sidx < num_spatial_layers; ++sidx) { - auto tl0_settings = es.layers_settings.find( - LayerId{.spatial_idx = sidx, .temporal_idx = 0}); - auto tlx_settings = es.layers_settings.find(LayerId{ - .spatial_idx = sidx, .temporal_idx = num_temporal_layers - 1}); - DataRate total_layer_bitrate = std::accumulate( - tl0_settings, tlx_settings, DataRate::Zero(), - [](DataRate acc, - const std::pair layer) { - return acc + layer.second.bitrate; - }); + const Resolution& resolution = + es.layers_settings + .at(LayerId{.spatial_idx = sidx, .temporal_idx = 0}) + .resolution; + DataRate total_layer_bitrate = DataRate::Zero(); + for (int tidx = 0; tidx < num_temporal_layers; ++tidx) { + total_layer_bitrate += + es.layers_settings + .at(LayerId{.spatial_idx = sidx, .temporal_idx = tidx}) + .bitrate; + } SimulcastStream& ss = vc.simulcastStream[sidx]; - ss.width = tl0_settings->second.resolution.width; - ss.height = tl0_settings->second.resolution.height; + ss.width = resolution.width; + ss.height = resolution.height; + ss.numberOfTemporalLayers = num_temporal_layers; + ss.maxBitrate = total_layer_bitrate.kbps(); + ss.targetBitrate = total_layer_bitrate.kbps(); + ss.minBitrate = 0; + ss.maxFramerate = vc.maxFramerate; + ss.qpMax = vc.qpMax; + ss.active = true; + } + } else if (vc.codecType == kVideoCodecVP9 || + vc.codecType == kVideoCodecAV1) { + for (int sidx = 0; sidx < num_spatial_layers; ++sidx) { + const Resolution& resolution = + es.layers_settings + .at(LayerId{.spatial_idx = sidx, .temporal_idx = 0}) + .resolution; + DataRate total_layer_bitrate = DataRate::Zero(); + for (int tidx = 0; tidx < num_temporal_layers; ++tidx) { + total_layer_bitrate += + es.layers_settings + .at(LayerId{.spatial_idx = sidx, .temporal_idx = tidx}) + .bitrate; + } + SpatialLayer& ss = vc.spatialLayers[sidx]; + ss.width = resolution.width; + ss.height = resolution.height; ss.numberOfTemporalLayers = num_temporal_layers; ss.maxBitrate = total_layer_bitrate.kbps(); ss.targetBitrate = total_layer_bitrate.kbps(); diff --git a/test/video_codec_tester.h b/test/video_codec_tester.h index fcec47e702..e62ab06c03 100644 --- a/test/video_codec_tester.h +++ b/test/video_codec_tester.h @@ -11,6 +11,7 @@ #ifndef TEST_VIDEO_CODEC_TESTER_H_ #define TEST_VIDEO_CODEC_TESTER_H_ +#include #include #include #include @@ -18,15 +19,20 @@ #include #include +#include "absl/strings/string_view.h" #include "api/environment/environment.h" #include "api/numerics/samples_stats_counter.h" -#include "api/test/metrics/metric.h" #include "api/test/metrics/metrics_logger.h" #include "api/units/data_rate.h" #include "api/units/data_size.h" #include "api/units/frequency.h" +#include "api/units/time_delta.h" +#include "api/units/timestamp.h" #include "api/video/encoded_image.h" #include "api/video/resolution.h" +#include "api/video_codecs/scalability_mode.h" +#include "api/video_codecs/sdp_video_format.h" +#include "api/video_codecs/video_codec.h" #include "api/video_codecs/video_decoder_factory.h" #include "api/video_codecs/video_encoder_factory.h" diff --git a/test/video_codec_tester_unittest.cc b/test/video_codec_tester_unittest.cc index a24a1db072..ff863e0ab4 100644 --- a/test/video_codec_tester_unittest.cc +++ b/test/video_codec_tester_unittest.cc @@ -169,7 +169,7 @@ class TestVideoEncoder : public MockVideoEncoder { class TestVideoDecoder : public MockVideoDecoder { public: - int32_t Decode(const EncodedImage& encoded_frame, int64_t) { + int32_t Decode(const EncodedImage& encoded_frame, int64_t) override { uint8_t y = (encoded_frame.size() + 0) & 255; uint8_t u = (encoded_frame.size() + 2) & 255; uint8_t v = (encoded_frame.size() + 4) & 255; @@ -184,7 +184,8 @@ class TestVideoDecoder : public MockVideoDecoder { return WEBRTC_VIDEO_CODEC_OK; } - int32_t RegisterDecodeCompleteCallback(DecodedImageCallback* callback) { + int32_t RegisterDecodeCompleteCallback( + DecodedImageCallback* callback) override { callback_ = callback; return WEBRTC_VIDEO_CODEC_OK; } @@ -228,10 +229,11 @@ class VideoCodecTesterTest : public ::testing::Test { explicit DecoderWrapper(TestVideoDecoder* decoder) : decoder_(decoder) {} int32_t Decode(const EncodedImage& encoded_frame, - int64_t render_time_ms) { + int64_t render_time_ms) override { return decoder_->Decode(encoded_frame, render_time_ms); } - int32_t RegisterDecodeCompleteCallback(DecodedImageCallback* callback) { + int32_t RegisterDecodeCompleteCallback( + DecodedImageCallback* callback) override { return decoder_->RegisterDecodeCompleteCallback(callback); } TestVideoDecoder* decoder_; diff --git a/test/video_decoder_proxy_factory.h b/test/video_decoder_proxy_factory.h index 2a22f66f2d..72f5691aad 100644 --- a/test/video_decoder_proxy_factory.h +++ b/test/video_decoder_proxy_factory.h @@ -11,11 +11,16 @@ #ifndef TEST_VIDEO_DECODER_PROXY_FACTORY_H_ #define TEST_VIDEO_DECODER_PROXY_FACTORY_H_ +#include #include #include +#include "api/environment/environment.h" +#include "api/video/encoded_image.h" +#include "api/video_codecs/sdp_video_format.h" #include "api/video_codecs/video_decoder.h" #include "api/video_codecs/video_decoder_factory.h" +#include "rtc_base/checks.h" namespace webrtc { namespace test { diff --git a/test/video_encoder_nullable_proxy_factory.h b/test/video_encoder_nullable_proxy_factory.h index d27afb4caf..001d006311 100644 --- a/test/video_encoder_nullable_proxy_factory.h +++ b/test/video_encoder_nullable_proxy_factory.h @@ -12,9 +12,9 @@ #define TEST_VIDEO_ENCODER_NULLABLE_PROXY_FACTORY_H_ #include -#include #include "api/environment/environment.h" +#include "api/video_codecs/sdp_video_format.h" #include "api/video_codecs/video_encoder.h" #include "api/video_codecs/video_encoder_factory.h" #include "test/video_encoder_proxy_factory.h" diff --git a/test/video_encoder_proxy_factory.h b/test/video_encoder_proxy_factory.h index 5560fb8918..a2e8dca901 100644 --- a/test/video_encoder_proxy_factory.h +++ b/test/video_encoder_proxy_factory.h @@ -11,12 +11,23 @@ #ifndef TEST_VIDEO_ENCODER_PROXY_FACTORY_H_ #define TEST_VIDEO_ENCODER_PROXY_FACTORY_H_ +#include +#include #include +#include #include #include "api/environment/environment.h" +#include "api/fec_controller_override.h" +#include "api/units/data_rate.h" +#include "api/video/render_resolution.h" +#include "api/video/video_frame.h" +#include "api/video/video_frame_type.h" +#include "api/video_codecs/sdp_video_format.h" +#include "api/video_codecs/video_codec.h" #include "api/video_codecs/video_encoder.h" #include "api/video_codecs/video_encoder_factory.h" +#include "rtc_base/checks.h" namespace webrtc { namespace test { diff --git a/test/video_renderer.cc b/test/video_renderer.cc index 75ab72a883..abd76fd6a0 100644 --- a/test/video_renderer.cc +++ b/test/video_renderer.cc @@ -9,6 +9,8 @@ */ #include "test/video_renderer.h" +#include + // TODO(pbos): Android renderer namespace webrtc { diff --git a/test/video_test_constants.h b/test/video_test_constants.h index b9083987ed..f3bf34f229 100644 --- a/test/video_test_constants.h +++ b/test/video_test_constants.h @@ -10,6 +10,7 @@ #ifndef TEST_VIDEO_TEST_CONSTANTS_H_ #define TEST_VIDEO_TEST_CONSTANTS_H_ +#include #include #include "api/units/time_delta.h" diff --git a/tools_webrtc/iwyu/apply_include_cleaner.py b/tools_webrtc/iwyu/apply_include_cleaner.py index 7f89b85bd2..25fc3613ad 100755 --- a/tools_webrtc/iwyu/apply_include_cleaner.py +++ b/tools_webrtc/iwyu/apply_include_cleaner.py @@ -51,12 +51,29 @@ "-I../../third_party/googletest/src/googlemock/include/", "-I../../third_party/googletest/src/googletest/include/", ] +_GTEST_KEY = '"gtest/gtest.h"' +_GTEST_VALUE = '"test/gtest.h"' _IWYU_MAPPING = { '"gmock/gmock.h"': '"test/gmock.h"', - '"gtest/gtest.h"': '"test/gtest.h"', - "": '"rtc_base/net_helpers.h"', + _GTEST_KEY: _GTEST_VALUE, + '': '"rtc_base/net_helpers.h"', + + # IWYU does not refer to the complete third_party/ path. + '"libyuv/': '"third_party/libyuv/include/libyuv/', + '"aom/': '"third_party/libaom/source/libaom/aom/', + '"vpx/': '"third_party/libvpx/source/libvpx/vpx/', } +# Supported file suffices. +_SUFFICES = [".cc", ".h"] + +# Ignored headers, used with `clang-include-cleaner --ignore-headers=` +_IGNORED_HEADERS = [ + ".pb.h", # generated protobuf files. + "pipewire/.*.h", # pipewire. + "spa/.*.h", # pipewire. + "openssl/.*.h", # openssl/boringssl. +] def _parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser( @@ -148,11 +165,37 @@ def _generate_compile_commands(work_dir: pathlib.Path) -> None: ) +def _modified_output(output: str, content: str) -> str: + """ Returns a modified output in case the cleaner made a mistake. For + example gtest.h is included again when using features like TEST_P.""" + if _GTEST_VALUE in content: + # Remove _GTEST_KEY from output if _GTEST_VALUE is included. + return re.sub(rf'^\+ {_GTEST_KEY}$', '', output) + return output + + +def _modified_content(content: str) -> str: + """Returns a modified content based on the includes from _IWYU_MAPPING.""" + modified_content = content + if _GTEST_VALUE in modified_content: + # Remove _GTEST_KEY from content if _GTEST_VALUE is included. + modified_content = re.sub(rf'^#include {_GTEST_KEY}\n', + '', + modified_content, + flags=re.MULTILINE) + for key, value in _IWYU_MAPPING.items(): + modified_content = re.sub(rf'^#include {re.escape(key)}', + f'#include {value}', + modified_content, + flags=re.MULTILINE) + return modified_content + + + # Transitioning the cmd type to tuple to prevent modification of # the original command from the callsite in main... -def _apply_include_cleaner_to_file(file_path: pathlib.Path, - should_modify: bool, - cmd: Tuple[str, ...]) -> bool: +def apply_include_cleaner_to_file(file_path: pathlib.Path, should_modify: bool, + cmd: Tuple[str, ...]) -> str: """Applies the include cleaner binary to a given file. Other than that, make sure to do include substitutions following the _IWYU_MAPPING variable and clear the tool output from redundant additions @@ -166,8 +209,7 @@ def _apply_include_cleaner_to_file(file_path: pathlib.Path, arguments but the file path Returns: - True if include cleaner provided a substitution that was actually - required in code (wasn't removed by the _IWYU_MAPPING) + The output produced by the cleaner. """ cmd += (str(file_path), ) result = subprocess.run(cmd, capture_output=True, text=True, check=False) @@ -175,35 +217,19 @@ def _apply_include_cleaner_to_file(file_path: pathlib.Path, print(f"Failed to run include cleaner on {file_path}, stderr:", f"{result.stderr.strip()}") output = result.stdout.strip() - content = file_path.read_text() - modified_content = content - for key, value in _IWYU_MAPPING.items(): - if value in modified_content: - # If the required include is already in the file, clear it from the - # cleaner output and remove what the cleaner added to the file - output = output.replace(f'+ {key.replace("#include ", "")}', "") - if should_modify: - modified_content = re.sub(rf"^#include {re.escape(key)}.*\n?", - "", - modified_content, - flags=re.MULTILINE) - - elif should_modify: - # Otherwise, change what the cleaner added to the correct include - # from _IWYU_MAPPING - modified_content = re.sub(rf"^#include {re.escape(key)}", - f"#include {value}", - modified_content, - flags=re.MULTILINE) - if should_modify and content != modified_content: - file_path.write_text(modified_content) + output = _modified_output(output, content) + + if should_modify: + modified_content = _modified_content(content) + if content != modified_content: + file_path.write_text(modified_content) if output: print(output) else: - print(f"Successfuly ran include cleaner on {file_path}") - return bool(output) + print(f"Successfully ran include cleaner on {file_path}") + return output def main() -> None: @@ -220,6 +246,8 @@ def main() -> None: # Build the execution command cmd = [str(_CLEANER_BINARY_PATH), "-p", str(args.work_dir)] + # Ignore some headers. + cmd.append("--ignore-headers=" + ",".join(_IGNORED_HEADERS)) for extra_arg in _EXTRA_ARGS: cmd.append(f"--extra-arg={extra_arg}") if args.print or args.check_for_changes: @@ -236,8 +264,11 @@ def main() -> None: # e.g instead of `cleaner foo.cc && cleaner bar.cc` # do `cleaner foo.cc bar.cc` for file in args.files: - changes_generated = (_apply_include_cleaner_to_file( - file, should_modify, tuple(cmd)) or changes_generated) + if not file.suffix in _SUFFICES: + continue + changes_generated = bool( + apply_include_cleaner_to_file(file, should_modify, tuple(cmd)) + or changes_generated) print("Finished. Check diff, compile, gn gen --check", "(tools_webrtc/gn_check_autofix.py can fix most of the issues)") diff --git a/tools_webrtc/iwyu/apply_include_cleaner_test.py b/tools_webrtc/iwyu/apply_include_cleaner_test.py new file mode 100755 index 0000000000..c3415910a2 --- /dev/null +++ b/tools_webrtc/iwyu/apply_include_cleaner_test.py @@ -0,0 +1,73 @@ +#!/usr/bin/env vpython3 + +# Copyright (c) 2025 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 unittest +from unittest import mock + +import apply_include_cleaner + +_GTEST_KEY = '"gtest/gtest.h"' +_GTEST_VALUE = '"test/gtest.h"' + + +class ApplyIncludeCleanerTest(unittest.TestCase): + + _OUTPUT = 'cleaner output' + + @mock.patch('subprocess.run', + return_value=mock.Mock(stdout=_OUTPUT, returncode=0)) + def test_no_modification(self, mock_subprocess): + file = mock.Mock() + file.read_text.return_value = '#include stuff' + output = apply_include_cleaner.apply_include_cleaner_to_file( + file, should_modify=True, cmd=[]) + self.assertEqual(output, self._OUTPUT) + mock_subprocess.assert_called_once() + file.write_text.assert_not_called() + + @mock.patch('subprocess.run', + return_value=mock.Mock(stdout=_OUTPUT, returncode=0)) + def test_content_modification(self, mock_subprocess): + file = mock.Mock() + file.read_text.return_value = '#include "libyuv/something.h"' + output = apply_include_cleaner.apply_include_cleaner_to_file( + file, should_modify=True, cmd=[]) + self.assertEqual(output, self._OUTPUT) + mock_subprocess.assert_called_once() + file.write_text.assert_called_once_with( + '#include "third_party/libyuv/include/libyuv/something.h"') + + @mock.patch('subprocess.run', + return_value=mock.Mock(stdout=f'+ {_GTEST_KEY}\n', + returncode=0)) + def test_gtest_output_modification(self, mock_subprocess): + file = mock.Mock() + file.read_text.return_value = f'#include {_GTEST_VALUE}' + output = apply_include_cleaner.apply_include_cleaner_to_file( + file, should_modify=True, cmd=[]) + self.assertEqual(output, '') + mock_subprocess.assert_called_once() + file.write_text.assert_not_called() + + @mock.patch('subprocess.run', + return_value=mock.Mock(stdout=f'+ {_GTEST_KEY}\n', + returncode=0)) + def test_gtest_output_no_modification(self, mock_subprocess): + file = mock.Mock() + file.read_text.return_value = '#include stuff' + output = apply_include_cleaner.apply_include_cleaner_to_file( + file, should_modify=True, cmd=[]) + self.assertEqual(output, f'+ {_GTEST_KEY}') + mock_subprocess.assert_called_once() + file.write_text.assert_not_called() + + +if (__name__) == '__main__': + unittest.main() diff --git a/tools_webrtc/mb/mb_config.pyl b/tools_webrtc/mb/mb_config.pyl index 1fdaaf5c84..8c3e8f97e5 100644 --- a/tools_webrtc/mb/mb_config.pyl +++ b/tools_webrtc/mb/mb_config.pyl @@ -57,8 +57,11 @@ 'dummy_audio_file_devices_no_protobuf': 'dummy_audio_file_devices_no_protobuf_x64', 'rtti_no_sctp': 'rtti_no_sctp_x64', + 'disable_trace_events': 'disable_trace_events_x64', + 'perfetto': 'perfetto_x64', 'openssl': 'openssl_x64', 'libstdcpp': 'libstdcpp_x64', + 'no_lld': 'no_lld_x64', }, 'Linux Asan': 'asan_lsan_clang_release_bot_x64', 'Linux MSan': 'msan_clang_release_bot_x64', @@ -189,6 +192,7 @@ 'perfetto': 'perfetto_x64', 'openssl': 'openssl_x64', 'libstdcpp': 'libstdcpp_x64', + 'no_lld': 'no_lld_x64', }, 'linux_msan': 'msan_clang_release_bot_x64', 'linux_rel': 'release_bot_x64', @@ -387,7 +391,6 @@ ], 'libfuzzer_asan_release_bot_x64': [ 'asan', - 'chromium_base_dependency', 'h265', 'libfuzzer', 'openh264', @@ -407,6 +410,7 @@ 'msan_clang_release_bot_x64': ['msan', 'clang', 'openh264', 'pure_release_bot', 'x64', 'h265'], 'no_h264_debug_bot_x86': ['debug_bot', 'x86'], + 'no_lld_x64': ['debug_bot', 'x64', 'no_lld'], 'openssl_x64': ['debug_bot', 'x64', 'no_build_ssl'], 'perfetto_android_arm': [ 'android', @@ -501,10 +505,6 @@ 'asan': { 'gn_args': 'is_asan=true', }, - # TODO(b/42223878): Remove this code when the dependency on base is gone. - 'chromium_base_dependency': { - 'mixins': ['enable_chromium_prelude', 'enable_rust'] - }, # is_clang=true by default, this is only to guard from upstream changes. 'clang': { 'gn_args': 'is_clang=true', @@ -548,12 +548,6 @@ 'dummy_audio_file_devices': { 'gn_args': 'rtc_use_dummy_audio_file_devices=true', }, - 'enable_chromium_prelude': { - 'gn_args': 'enable_chromium_prelude=true', - }, - 'enable_rust': { - 'gn_args': 'enable_rust=true enable_rust_cxx=true', - }, 'fuchsia': { 'gn_args': 'target_os="fuchsia"' }, @@ -576,8 +570,8 @@ 'gn_args': 'target_environment="simulator"' }, 'libfuzzer': { - # TODO(b/42223878): use_fuzztest_wrapper adds a dependency to //base. - 'gn_args': 'use_libfuzzer=true use_fuzztest_wrapper=true', + # use_fuzztest_wrapper=false by default, this is only for visibility. + 'gn_args': 'use_libfuzzer=true use_fuzztest_wrapper=false', }, 'lsan': { 'gn_args': 'is_lsan=true', @@ -597,6 +591,9 @@ 'no_ios_code_signing': { 'gn_args': 'ios_enable_code_signing=false', }, + 'no_lld': { + 'gn_args': 'use_lld=false', + }, 'no_protobuf': { 'gn_args': 'rtc_enable_protobuf=false', }, diff --git a/tools_webrtc/remove_extra_namespace.py b/tools_webrtc/remove_extra_namespace.py index 21ac2d1aa2..d6bbb2cfdd 100755 --- a/tools_webrtc/remove_extra_namespace.py +++ b/tools_webrtc/remove_extra_namespace.py @@ -36,7 +36,8 @@ def remove_extra_namespace_from_file(namespace, filename): match = re.match(r'}\s+// namespace (\S+)$', line) if match is not None: if match.group(1) != namespaces[0]: - print('Namespace mismatch') + print('Namespace mismatch:', match.group(1), "vs", + namespaces[0]) raise RuntimeError('Namespace mismatch') del namespaces[0] newfile.write(line) diff --git a/video/BUILD.gn b/video/BUILD.gn index bf77b139ca..af02a74467 100644 --- a/video/BUILD.gn +++ b/video/BUILD.gn @@ -577,7 +577,6 @@ if (rtc_include_tests) { "../api/audio:builtin_audio_processing_builder", "../api/audio:create_audio_device_module", "../api/environment", - "../api/environment:environment_factory", "../api/numerics", "../api/rtc_event_log", "../api/rtc_event_log:rtc_event_log_factory", @@ -667,22 +666,14 @@ if (rtc_include_tests) { ":video_quality_test", "../api:rtp_parameters", "../api:simulated_network_api", - "../api:test_dependency_factory", "../api:video_quality_test_fixture_api", "../api/units:data_rate", "../api/video_codecs:video_codecs_api", - "../modules/pacing", "../modules/video_coding:webrtc_vp9", - "../rtc_base/experiments:alr_experiment", - "../system_wrappers:field_trial", - "../test:field_trial", "../test:fileutils", - "../test:test_common", "../test:test_support", - "../video/config:encoder_config", - "//testing/gtest", + "config:encoder_config", "//third_party/abseil-cpp/absl/flags:flag", - "//third_party/abseil-cpp/absl/flags:parse", ] } @@ -691,10 +682,10 @@ if (rtc_include_tests) { sources = [ "pc_full_stack_tests.cc" ] deps = [ - "..//test/network:simulated_network", "../api:create_network_emulation_manager", "../api:create_peer_connection_quality_test_frame_generator", "../api:create_peerconnection_quality_test_fixture", + "../api:field_trials", "../api:frame_generator_api", "../api:function_view", "../api:media_stream_interface", @@ -711,9 +702,6 @@ if (rtc_include_tests) { "../api/units:time_delta", "../api/video_codecs:video_codecs_api", "../media:media_constants", - "../modules/video_coding:webrtc_vp9", - "../system_wrappers:field_trial", - "../test:field_trial", "../test:fileutils", "../test:test_support", "../test/pc/e2e:network_quality_metrics_reporter", diff --git a/video/adaptation/overuse_frame_detector_unittest.cc b/video/adaptation/overuse_frame_detector_unittest.cc index f1b522f105..b836cc3844 100644 --- a/video/adaptation/overuse_frame_detector_unittest.cc +++ b/video/adaptation/overuse_frame_detector_unittest.cc @@ -46,7 +46,7 @@ const int kProcessTimeUs = 5 * kNumMicrosecsPerMillisec; class MockCpuOveruseObserver : public OveruseFrameDetectorObserverInterface { public: MockCpuOveruseObserver() {} - virtual ~MockCpuOveruseObserver() {} + ~MockCpuOveruseObserver() override {} MOCK_METHOD(void, AdaptUp, (), (override)); MOCK_METHOD(void, AdaptDown, (), (override)); @@ -55,7 +55,7 @@ class MockCpuOveruseObserver : public OveruseFrameDetectorObserverInterface { class CpuOveruseObserverImpl : public OveruseFrameDetectorObserverInterface { public: CpuOveruseObserverImpl() : overuse_(0), normaluse_(0) {} - virtual ~CpuOveruseObserverImpl() {} + ~CpuOveruseObserverImpl() override {} void AdaptDown() override { ++overuse_; } void AdaptUp() override { ++normaluse_; } @@ -70,7 +70,7 @@ class OveruseFrameDetectorUnderTest : public OveruseFrameDetector { const Environment& env, CpuOveruseMetricsObserver* metrics_observer) : OveruseFrameDetector(env, metrics_observer) {} - ~OveruseFrameDetectorUnderTest() {} + ~OveruseFrameDetectorUnderTest() override {} using OveruseFrameDetector::CheckForOveruse; using OveruseFrameDetector::SetOptions; diff --git a/video/adaptation/pixel_limit_resource.h b/video/adaptation/pixel_limit_resource.h index 38d20f7bfe..278a348028 100644 --- a/video/adaptation/pixel_limit_resource.h +++ b/video/adaptation/pixel_limit_resource.h @@ -52,7 +52,7 @@ class PixelLimitResource : public Resource { TaskQueueBase* const task_queue_; VideoStreamInputStateProvider* const input_state_provider_; std::optional max_pixels_ RTC_GUARDED_BY(task_queue_); - webrtc::ResourceListener* listener_ RTC_GUARDED_BY(task_queue_); + ResourceListener* listener_ RTC_GUARDED_BY(task_queue_); RepeatingTaskHandle repeating_task_ RTC_GUARDED_BY(task_queue_); }; diff --git a/video/alignment_adjuster.cc b/video/alignment_adjuster.cc index c51d530422..88a5df98c8 100644 --- a/video/alignment_adjuster.cc +++ b/video/alignment_adjuster.cc @@ -84,8 +84,8 @@ int AlignmentAdjuster::GetAlignmentAndMaybeAdjustScaleFactors( } // Update alignment to also apply to simulcast layers. - const bool has_scale_resolution_down_by = absl::c_any_of( - config->simulcast_layers, [](const webrtc::VideoStream& layer) { + const bool has_scale_resolution_down_by = + absl::c_any_of(config->simulcast_layers, [](const VideoStream& layer) { return layer.scale_resolution_down_by >= 1.0; }); diff --git a/video/buffered_frame_decryptor_unittest.cc b/video/buffered_frame_decryptor_unittest.cc index 781de7512c..f037d62e23 100644 --- a/video/buffered_frame_decryptor_unittest.cc +++ b/video/buffered_frame_decryptor_unittest.cc @@ -58,7 +58,8 @@ class BufferedFrameDecryptorTest : public ::testing::Test, decrypted_frame_call_count_++; } - void OnDecryptionStatusChange(FrameDecryptorInterface::Status status) { + void OnDecryptionStatusChange( + FrameDecryptorInterface::Status status) override { ++decryption_status_change_count_; } diff --git a/video/call_stats2_unittest.cc b/video/call_stats2_unittest.cc index dd49adf68d..d2cc56f5e0 100644 --- a/video/call_stats2_unittest.cc +++ b/video/call_stats2_unittest.cc @@ -34,7 +34,7 @@ namespace internal { class MockStatsObserver : public CallStatsObserver { public: MockStatsObserver() {} - virtual ~MockStatsObserver() {} + ~MockStatsObserver() override {} MOCK_METHOD(void, OnRttUpdate, (int64_t, int64_t), (override)); }; diff --git a/video/config/encoder_stream_factory.cc b/video/config/encoder_stream_factory.cc index 8820c98944..21eef9a7b4 100644 --- a/video/config/encoder_stream_factory.cc +++ b/video/config/encoder_stream_factory.cc @@ -90,9 +90,7 @@ size_t FindRequiredActiveLayers(const VideoEncoderConfig& encoder_config) { // The selected thresholds for QVGA and VGA corresponded to a QP around 10. // The change in QP declined above the selected bitrates. -static int GetMaxDefaultVideoBitrateKbps(int width, - int height, - bool is_screenshare) { +int GetMaxDefaultVideoBitrateKbps(int width, int height, bool is_screenshare) { int max_bitrate; if (width * height <= 320 * 240) { max_bitrate = 600; @@ -581,7 +579,7 @@ std::vector EncoderStreamFactory::GetStreamResolutions( } const bool has_scale_resolution_down_by = absl::c_any_of( - encoder_config.simulcast_layers, [](const webrtc::VideoStream& layer) { + encoder_config.simulcast_layers, [](const VideoStream& layer) { return layer.scale_resolution_down_by != -1.; }); diff --git a/video/config/encoder_stream_factory.h b/video/config/encoder_stream_factory.h index abf196bdae..430e3c089e 100644 --- a/video/config/encoder_stream_factory.h +++ b/video/config/encoder_stream_factory.h @@ -23,10 +23,10 @@ namespace webrtc { class EncoderStreamFactory - : public webrtc::VideoEncoderConfig::VideoStreamFactoryInterface { + : public VideoEncoderConfig::VideoStreamFactoryInterface { public: EncoderStreamFactory( - const webrtc::VideoEncoder::EncoderInfo& encoder_info, + const VideoEncoder::EncoderInfo& encoder_info, std::optional restrictions = std::nullopt); std::vector CreateEncoderStreams( diff --git a/video/config/simulcast.cc b/video/config/simulcast.cc index acc2e15d51..8cca79a413 100644 --- a/video/config/simulcast.cc +++ b/video/config/simulcast.cc @@ -303,7 +303,7 @@ std::vector GetScreenshareLayers(size_t max_layers, std::vector layers(num_simulcast_layers); // For legacy screenshare in conference mode, tl0 and tl1 bitrates are // piggybacked on the VideoCodec struct as target and max bitrates, - // respectively. See eg. webrtc::LibvpxVp8Encoder::SetRates(). + // respectively. See eg. LibvpxVp8Encoder::SetRates(). layers[0].width = width; layers[0].height = height; layers[0].max_framerate = 5; diff --git a/video/corruption_detection/evaluation/BUILD.gn b/video/corruption_detection/evaluation/BUILD.gn index 20ad2dcad4..d0b2afb6f2 100644 --- a/video/corruption_detection/evaluation/BUILD.gn +++ b/video/corruption_detection/evaluation/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright 2025 The WebRTC project authors. All rights reserved. +# Copyright (c) 2025 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 @@ -42,6 +42,8 @@ rtc_library("utils") { ] deps = [ "../../../api:array_view", + "../../../api/video:video_frame", + "../../../api/video_codecs:video_codecs_api", "../../../rtc_base:checks", "../../../rtc_base:stringutils", "../../../rtc_base/system:file_wrapper", @@ -50,6 +52,40 @@ rtc_library("utils") { ] } +rtc_library("webrtc_picture_pair_provider") { + testonly = true + sources = [ + "webrtc_picture_pair_provider.cc", + "webrtc_picture_pair_provider.h", + ] + deps = [ + ":picture_pair_provider", + ":test_clip", + ":utils", + "../../../api:scoped_refptr", + "../../../api:sequence_checker", + "../../../api/environment", + "../../../api/environment:environment_factory", + "../../../api/units:data_rate", + "../../../api/video:encoded_image", + "../../../api/video:resolution", + "../../../api/video:video_frame", + "../../../api/video:video_frame_type", + "../../../api/video_codecs:scalability_mode", + "../../../api/video_codecs:video_codecs_api", + "../../../modules/video_coding:video_codec_interface", + "../../../modules/video_coding:video_coding_utility", + "../../../modules/video_coding/svc:svc_rate_allocator", + "../../../rtc_base:checks", + "../../../rtc_base:logging", + "../../../rtc_base:macromagic", + "../../../rtc_base/system:no_unique_address", + "../../../test:fileutils", + "../../../test:test_support", + "../../../test:video_test_support", + ] +} + if (rtc_include_tests) { rtc_library("test_clip_unittest") { testonly = true @@ -79,12 +115,51 @@ if (rtc_include_tests) { ] } + rtc_library("webrtc_picture_pair_provider_unittest") { + testonly = true + sources = [ "webrtc_picture_pair_provider_unittest.cc" ] + data = [ "../../../resources/ConferenceMotion_1280_720_50.yuv" ] + deps = [ + ":picture_pair_provider", + ":utils", + ":webrtc_picture_pair_provider", + "../../../api:field_trials_view", + "../../../api:mock_video_codec_factory", + "../../../api:mock_video_decoder", + "../../../api:mock_video_encoder", + "../../../api:scoped_refptr", + "../../../api/environment:environment_factory", + "../../../api/units:data_rate", + "../../../api/video:encoded_image", + "../../../api/video:video_frame", + "../../../api/video:video_frame_type", + "../../../api/video_codecs:builtin_video_decoder_factory", + "../../../api/video_codecs:builtin_video_encoder_factory", + "../../../api/video_codecs:scalability_mode", + "../../../api/video_codecs:video_codecs_api", + "../../../api/video_codecs:video_decoder_factory_template", + "../../../api/video_codecs:video_decoder_factory_template_dav1d_adapter", + "../../../api/video_codecs:video_encoder_factory_template", + "../../../api/video_codecs:video_encoder_factory_template_libaom_av1_adapter", + "../../../common_video", + "../../../modules/video_coding:video_codec_interface", + "../../../modules/video_coding:video_coding_utility", + "../../../modules/video_coding/svc:svc_rate_allocator", + "../../../rtc_base:checks", + "../../../test:fileutils", + "../../../test:test_support", + "../../../video/corruption_detection/evaluation:test_clip", + "//third_party/abseil-cpp/absl/strings:string_view", + ] + } + rtc_library("corruption_detection_eval_tests") { testonly = true sources = [] deps = [ ":test_clip_unittest", ":utils_unittest", + ":webrtc_picture_pair_provider_unittest", ] } } diff --git a/video/corruption_detection/evaluation/utils.cc b/video/corruption_detection/evaluation/utils.cc index affdcc912a..a2ab54c1fc 100644 --- a/video/corruption_detection/evaluation/utils.cc +++ b/video/corruption_detection/evaluation/utils.cc @@ -17,6 +17,9 @@ #include "absl/strings/string_view.h" #include "api/array_view.h" +#include "api/video/video_codec_type.h" +#include "api/video_codecs/sdp_video_format.h" +#include "api/video_codecs/video_codec.h" #include "rtc_base/checks.h" #include "rtc_base/strings/string_builder.h" #include "rtc_base/system/file_wrapper.h" @@ -45,7 +48,7 @@ TempY4mFileCreator::TempY4mFileCreator(int width, int height, int framerate) } TempY4mFileCreator::~TempY4mFileCreator() { - RTC_CHECK(test::RemoveFile(y4m_filepath_.c_str())); + RTC_CHECK(test::RemoveFile(y4m_filepath_)); } void TempY4mFileCreator::CreateTempY4mFile( @@ -85,7 +88,6 @@ Y4mMetadata ReadMetadataFromY4mHeader(absl::string_view clip_path) { RTC_CHECK(fgets(header, sizeof(header), file) != nullptr) << "File " << clip_path << " is too small"; fclose(file); - int fps_numerator; int fps_denominator; int width; @@ -99,4 +101,20 @@ Y4mMetadata ReadMetadataFromY4mHeader(absl::string_view clip_path) { .framerate = fps_numerator / fps_denominator}; } +SdpVideoFormat GetSdpVideoFormat(VideoCodecType type) { + switch (type) { + case VideoCodecType::kVideoCodecVP8: + return SdpVideoFormat::VP8(); + case VideoCodecType::kVideoCodecVP9: + return SdpVideoFormat::VP9Profile0(); + case VideoCodecType::kVideoCodecAV1: + return SdpVideoFormat::AV1Profile0(); + case VideoCodecType::kVideoCodecH264: + return SdpVideoFormat::H264(); + default: + RTC_FATAL() << "Codec type " << CodecTypeToPayloadString(type) + << " is not supported."; + } +} + } // namespace webrtc diff --git a/video/corruption_detection/evaluation/utils.h b/video/corruption_detection/evaluation/utils.h index f4cac20cbf..65af4cf8e1 100644 --- a/video/corruption_detection/evaluation/utils.h +++ b/video/corruption_detection/evaluation/utils.h @@ -16,6 +16,8 @@ #include "absl/strings/string_view.h" #include "api/array_view.h" +#include "api/video/video_codec_type.h" +#include "api/video_codecs/sdp_video_format.h" #include "rtc_base/system/file_wrapper.h" namespace webrtc { @@ -60,6 +62,8 @@ struct Y4mMetadata { Y4mMetadata ReadMetadataFromY4mHeader(absl::string_view clip_path); +SdpVideoFormat GetSdpVideoFormat(VideoCodecType type); + } // namespace webrtc #endif // VIDEO_CORRUPTION_DETECTION_EVALUATION_UTILS_H_ diff --git a/video/corruption_detection/evaluation/webrtc_picture_pair_provider.cc b/video/corruption_detection/evaluation/webrtc_picture_pair_provider.cc new file mode 100644 index 0000000000..b5b82be9e8 --- /dev/null +++ b/video/corruption_detection/evaluation/webrtc_picture_pair_provider.cc @@ -0,0 +1,370 @@ +/* + * Copyright 2025 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 "video/corruption_detection/evaluation/webrtc_picture_pair_provider.h" + +#include +#include +#include +#include +#include +#include + +#include "api/environment/environment_factory.h" +#include "api/scoped_refptr.h" +#include "api/sequence_checker.h" +#include "api/units/data_rate.h" +#include "api/video/encoded_image.h" +#include "api/video/i420_buffer.h" +#include "api/video/resolution.h" +#include "api/video/video_codec_type.h" +#include "api/video/video_frame.h" +#include "api/video/video_frame_type.h" +#include "api/video_codecs/scalability_mode.h" +#include "api/video_codecs/video_codec.h" +#include "api/video_codecs/video_decoder.h" +#include "api/video_codecs/video_decoder_factory.h" +#include "api/video_codecs/video_encoder.h" +#include "api/video_codecs/video_encoder_factory.h" +#include "modules/video_coding/include/video_error_codes.h" +#include "modules/video_coding/svc/svc_rate_allocator.h" +#include "modules/video_coding/utility/simulcast_rate_allocator.h" +#include "modules/video_coding/utility/simulcast_utility.h" +#include "rtc_base/checks.h" +#include "rtc_base/logging.h" +#include "test/gtest.h" +#include "test/testsupport/file_utils.h" +#include "test/testsupport/frame_reader.h" +#include "video/corruption_detection/evaluation/picture_pair_provider.h" +#include "video/corruption_detection/evaluation/test_clip.h" +#include "video/corruption_detection/evaluation/utils.h" + +namespace webrtc { + +namespace { + +// Chosen inspired from third_party/webrtc/video/video_stream_encoder.cc +constexpr int32_t kMaxPayloadSize = 1500; + +// 90kHz clock for video. +constexpr int kRtpTimestampFreq = 90'000; + +} // namespace + +WebRtcEncoderDecoderPicturePairProvider:: + WebRtcEncoderDecoderPicturePairProvider( + VideoCodecType type, + std::unique_ptr encoder_factory, + std::unique_ptr decoder_factory) + : env_(CreateEnvironment()), + type_(type), + encoder_factory_(std::move(encoder_factory)), + encoder_(encoder_factory_->Create(env_, GetSdpVideoFormat(type))), + decoder_(decoder_factory->Create(env_, GetSdpVideoFormat(type))), + is_initialized_(false) { + RTC_CHECK(encoder_) << "encoder_ could not be initialized correctly."; + RTC_CHECK(decoder_) << "decoder_ could not be initialized correctly."; + + int32_t status = encoder_->RegisterEncodeCompleteCallback(this); + RTC_CHECK_EQ(status, WEBRTC_VIDEO_CODEC_OK) + << "RegisterEncodeCompleteCallback could not succesfully be called on " + "encoder_."; + + status = decoder_->RegisterDecodeCompleteCallback(this); + RTC_CHECK_EQ(status, WEBRTC_VIDEO_CODEC_OK) + << "RegisterDecodeCompleteCallback could not succesfully be called on " + "decoder_."; +} + +WebRtcEncoderDecoderPicturePairProvider:: + ~WebRtcEncoderDecoderPicturePairProvider() { + encoder_->Release(); + decoder_->Release(); + encoder_->RegisterEncodeCompleteCallback(nullptr); + decoder_->RegisterDecodeCompleteCallback(nullptr); +} + +bool WebRtcEncoderDecoderPicturePairProvider::InitializeFrameGenerator( + const TestClip& clip) { + // Check if the file exists + std::string clip_path = std::string(clip.clip_path()); + if (!test::FileExists(clip_path)) { + RTC_LOG(LS_ERROR) << "Could not find clip " << clip_path; + return false; + } + + if (clip.is_yuv()) { + frame_generator_ = CreateYuvFrameReader( + clip_path, Resolution{.width = clip.width(), .height = clip.height()}, + test::YuvFrameReaderImpl::RepeatMode::kPingPong); + } else { + frame_generator_ = CreateY4mFrameReader( + clip_path, test::YuvFrameReaderImpl::RepeatMode::kPingPong); + } + + return true; +} + +bool WebRtcEncoderDecoderPicturePairProvider::ConfigureEncoderSettings( + const TestClip& clip, + const DataRate bitrate) { + codec_config_.width = clip.width(); + codec_config_.height = clip.height(); + codec_config_.maxFramerate = clip.framerate(); + codec_config_.codecType = type_; + codec_config_.minBitrate = bitrate.kbps(); + codec_config_.startBitrate = bitrate.kbps(); + codec_config_.maxBitrate = bitrate.kbps(); + codec_config_.mode = clip.codec_mode(); + + // `qpMax` values are chosen based on the limits in libaom, libvpx and + // openh264 libraries' API limits respectively. + switch (type_) { + case VideoCodecType::kVideoCodecAV1: + [[fallthrough]]; + case VideoCodecType::kVideoCodecVP9: + codec_config_.SetScalabilityMode(ScalabilityMode::kL1T3); + codec_config_.qpMax = 63; + + // Need to set the bitrates for each spatial layer manually. In the case + // of L1T3 we only have 1 spatial layer, hence only setting index `0`. + // This must be done such that the rate allocator can allocate correct + // bitrates to each spatial and temporal layer. + codec_config_.spatialLayers[0].targetBitrate = + static_cast(bitrate.kbps()); + codec_config_.spatialLayers[0].maxBitrate = + static_cast(bitrate.kbps()); + codec_config_.spatialLayers[0].active = true; + break; + case VideoCodecType::kVideoCodecVP8: + codec_config_.VP8()->numberOfTemporalLayers = 3; + codec_config_.qpMax = 63; + break; + case VideoCodecType::kVideoCodecH264: + codec_config_.H264()->numberOfTemporalLayers = 3; + codec_config_.qpMax = 51; + + // A simple hack because of how + // `SimulcastRateAllocator::NumTemporalStreams` looks in + // modules/video_coding/utility/simulcast_rate_allocator.cc. + codec_config_.simulcastStream[0].numberOfTemporalLayers = 3; + break; + default: + RTC_LOG(LS_ERROR) << "Codec type " << CodecTypeToPayloadString(type_) + << " is not supported."; + RTC_DCHECK_NOTREACHED(); + return false; + } + return true; +} + +bool WebRtcEncoderDecoderPicturePairProvider::InitializeEncoder() { + const VideoEncoder::Settings encoder_settings( + VideoEncoder::Capabilities(/*loss_notification = */ false), + /*number_of_cores = */ 1, /*max_payload_size = */ kMaxPayloadSize); + + if (encoder_->InitEncode(&codec_config_, encoder_settings) == + WEBRTC_VIDEO_CODEC_OK) { + return true; + } else { + RTC_LOG(LS_ERROR) << "Failed to initialize encoder."; + return false; + } +} + +void WebRtcEncoderDecoderPicturePairProvider::SetEncoderRate( + const TestClip& clip, + const DataRate bitrate) { + VideoEncoder::RateControlParameters rate_params; + + switch (type_) { + case VideoCodecType::kVideoCodecAV1: + [[fallthrough]]; + case VideoCodecType::kVideoCodecVP9: { + SvcRateAllocator svc_rate_allocator(codec_config_, env_.field_trials()); + rate_params = VideoEncoder::RateControlParameters( + svc_rate_allocator.GetAllocation(bitrate.bps(), clip.framerate()), + clip.framerate(), bitrate); + break; + } + case VideoCodecType::kVideoCodecVP8: + [[fallthrough]]; + case VideoCodecType::kVideoCodecH264: { + SimulcastRateAllocator simulcast_rate_allocator(env_, codec_config_); + rate_params = VideoEncoder::RateControlParameters( + simulcast_rate_allocator.GetAllocation(bitrate.bps(), + clip.framerate()), + clip.framerate(), bitrate); + break; + } + default: + RTC_LOG(LS_ERROR) << "Given codec type is not supported."; + break; + } + + // TODO: b/337750641 - For AV1 and VP9 screensharing, the bitrate is not set + // for each temporal layer, hence the following check is needed to prevent + // this from failing. Remove the following check once the bitrate is set + // properly for each temporal layer in screensharing. + if (!(clip.codec_mode() == VideoCodecMode::kScreensharing && + (type_ == VideoCodecType::kVideoCodecVP9 || + type_ == VideoCodecType::kVideoCodecAV1))) { + // A simple check that the bitrate has been set for each temporal layer. + const int num_temporal_layers = + SimulcastUtility::NumberOfTemporalLayers(codec_config_, + /*spatial_id=*/0); + for (int ti = 0; ti < num_temporal_layers; ++ti) { + EXPECT_GT(rate_params.bitrate.GetBitrate(/*si=*/0, ti), 0u); + } + } + + encoder_->SetRates(rate_params); +} + +bool WebRtcEncoderDecoderPicturePairProvider::InitializeDecoder() { + VideoDecoder::Settings decoder_settings; + decoder_settings.set_codec_type(type_); + + if (decoder_->Configure(decoder_settings)) { + return true; + } else { + RTC_LOG(LS_ERROR) << "Failed to configure decoder."; + return false; + } +} + +bool WebRtcEncoderDecoderPicturePairProvider::Configure( + const TestClip& clip, + const DataRate bitrate) { + RTC_DCHECK_RUN_ON(&sequence_checker_); + + if (is_initialized_) { + encoder_->Release(); + decoder_->Release(); + is_initialized_ = false; + } + + if (!InitializeFrameGenerator(clip)) { + return false; + } + if (!ConfigureEncoderSettings(clip, bitrate)) { + return false; + } + if (!InitializeEncoder()) { + return false; + } + SetEncoderRate(clip, bitrate); + if (!InitializeDecoder()) { + return false; + } + + // Operates at a 90kHz clock. + rtp_timestamp_interval_ = kRtpTimestampFreq / clip.framerate(); + + // Encoder & decoder have been initialized. + is_initialized_ = true; + + return true; +} + +std::optional +WebRtcEncoderDecoderPicturePairProvider::GetNextPicturePair() { + RTC_DCHECK_RUN_ON(&sequence_checker_); + + RTC_CHECK(is_initialized_) << "Encoder and decoder have not been initialized." + " Try calling Configure first."; + encoded_image_.reset(); + decoded_image_.reset(); + qp_.reset(); + + // Read next frame. + scoped_refptr buffer = frame_generator_->PullFrame(); + if (buffer == nullptr) { + return std::nullopt; + } + VideoFrame input = VideoFrame::Builder() + .set_video_frame_buffer(buffer) + .set_rtp_timestamp(rtp_timestamp_) + .build(); + + const std::vector frame_type{ + is_keyframe_ ? VideoFrameType::kVideoFrameKey + : VideoFrameType::kVideoFrameDelta}; + // Set only the first frame to be a keyframe. If more keyframes are needed, + // update this part. + if (is_keyframe_) { + is_keyframe_ = false; + } + + // Update the RTP timestamp for the next frame. Needs to be done before the + // `Encode` call. Because if the `Encode` call arises an error the + // `rtp_timestamp_` should be updated to the next one. + rtp_timestamp_ += rtp_timestamp_interval_; + + // Note: Only works for synchronous encoders/decoders. + // This particular class only uses the built-in software encoders/decoders + // which are all synchronous implementations. + // If this class will be used for asynchronous encoder/decoders a wait logic + // needs to be implemented after the `Encode` call so that we can be sure that + // `encoded_image_` is set. + if (encoder_->Encode(input, &frame_type) != WEBRTC_VIDEO_CODEC_OK) { + RTC_LOG(LS_WARNING) << "Failed to encode input."; + return std::nullopt; + } + + if (!encoded_image_.has_value()) { + // Encoder dropped the frame. + return std::nullopt; + } + + if (decoder_->Decode(*encoded_image_, /*render_time_ms=*/0) != + WEBRTC_VIDEO_CODEC_OK) { + RTC_LOG(LS_WARNING) << "Failed to decode input."; + return std::nullopt; + } + RTC_CHECK(decoded_image_.has_value()) << "Decoded image is not set."; + decoded_image_->set_rtp_timestamp(input.rtp_timestamp()); + + if (!qp_.has_value() && encoded_image_->qp_ > 0) { + qp_ = encoded_image_->qp_; + } + RTC_CHECK(qp_.has_value()) << "QP is not set."; + + return OriginalCompressedPicturePair{.original_image = input, + .compressed_image = *decoded_image_, + .frame_average_qp = *qp_}; +} + +EncodedImageCallback::Result +WebRtcEncoderDecoderPicturePairProvider::OnEncodedImage( + const EncodedImage& encoded_image, + const CodecSpecificInfo*) { + RTC_DCHECK_RUN_ON(&sequence_checker_); + + encoded_image_.emplace(encoded_image); + return EncodedImageCallback::Result(EncodedImageCallback::Result::Error::OK); +} + +void WebRtcEncoderDecoderPicturePairProvider::OnDroppedFrame( + DropReason reason) { + RTC_DCHECK_RUN_ON(&sequence_checker_); + + encoded_image_.reset(); +} + +int32_t WebRtcEncoderDecoderPicturePairProvider::Decoded( + VideoFrame& decoded_image) { + RTC_DCHECK_RUN_ON(&sequence_checker_); + + decoded_image_.emplace(decoded_image); + return 0; +} + +} // namespace webrtc diff --git a/video/corruption_detection/evaluation/webrtc_picture_pair_provider.h b/video/corruption_detection/evaluation/webrtc_picture_pair_provider.h new file mode 100644 index 0000000000..5b9b80b4a6 --- /dev/null +++ b/video/corruption_detection/evaluation/webrtc_picture_pair_provider.h @@ -0,0 +1,103 @@ +/* + * Copyright 2025 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 VIDEO_CORRUPTION_DETECTION_EVALUATION_WEBRTC_PICTURE_PAIR_PROVIDER_H_ +#define VIDEO_CORRUPTION_DETECTION_EVALUATION_WEBRTC_PICTURE_PAIR_PROVIDER_H_ + +#include +#include +#include + +#include "api/environment/environment.h" +#include "api/sequence_checker.h" +#include "api/units/data_rate.h" +#include "api/video/encoded_image.h" +#include "api/video/video_codec_type.h" +#include "api/video/video_frame.h" +#include "api/video_codecs/video_codec.h" +#include "api/video_codecs/video_decoder.h" +#include "api/video_codecs/video_decoder_factory.h" +#include "api/video_codecs/video_encoder.h" +#include "api/video_codecs/video_encoder_factory.h" +#include "rtc_base/system/no_unique_address.h" +#include "rtc_base/thread_annotations.h" +#include "test/testsupport/frame_reader.h" +#include "video/corruption_detection/evaluation/picture_pair_provider.h" +#include "video/corruption_detection/evaluation/test_clip.h" + +namespace webrtc { + +// Provides a picture pair where one of the pairs is the original raw frame and +// the other pair is the corresponding compressed frame that has gone through an +// encoding/decoding pipeline as implemented in this class. The compressed frame +// is obtained through the standard VideoEncoder and VideoDecoder instances. +// +// This particular class is meant to only be used with the built-in software +// encoders/decoders which are all synchronous implementations. Hence, only +// works for synchronous encoders/decoders. If the class is to be expanded to +// include asynchronous encoders/decoders, see the guidance in the .cc file. +class WebRtcEncoderDecoderPicturePairProvider : public PicturePairProvider, + public EncodedImageCallback, + public DecodedImageCallback { + public: + WebRtcEncoderDecoderPicturePairProvider( + VideoCodecType type, + std::unique_ptr encoder_factory, + std::unique_ptr decoder_factory); + + ~WebRtcEncoderDecoderPicturePairProvider() override; + + bool Configure(const TestClip& clip, DataRate bitrate) override; + + std::optional GetNextPicturePair() override; + + private: + bool ConfigureEncoderSettings(const TestClip& clip, DataRate bitrate); + bool InitializeEncoder(); + void SetEncoderRate(const TestClip& clip, DataRate bitrate); + bool InitializeDecoder(); + bool InitializeFrameGenerator(const TestClip& clip); + + // Callback methods + // Overridden from EncodedImageCallback. + Result OnEncodedImage(const EncodedImage& encoded_image, + const CodecSpecificInfo*) override; + void OnDroppedFrame(DropReason reason) override; + + // Overridden from DecodedImageCallback. + int32_t Decoded(VideoFrame& decoded_image) override; + + // Variables + const Environment env_; + const VideoCodecType type_; + + // Because of how `BuiltinVideoEncoderFactory` is constructed, this class + // needs to take ownership of the encoder factory. + const std::unique_ptr encoder_factory_; + const std::unique_ptr encoder_; + const std::unique_ptr decoder_; + + RTC_NO_UNIQUE_ADDRESS SequenceChecker sequence_checker_; + std::optional encoded_image_ RTC_GUARDED_BY(sequence_checker_); + std::optional decoded_image_ RTC_GUARDED_BY(sequence_checker_); + std::optional qp_ RTC_GUARDED_BY(sequence_checker_); + + bool is_initialized_ = false; + VideoCodec codec_config_; + bool is_keyframe_ RTC_GUARDED_BY(sequence_checker_) = true; + uint32_t rtp_timestamp_ RTC_GUARDED_BY(sequence_checker_) = 0; + uint32_t rtp_timestamp_interval_ RTC_GUARDED_BY(sequence_checker_) = 0; + + std::unique_ptr frame_generator_; +}; + +} // namespace webrtc + +#endif // VIDEO_CORRUPTION_DETECTION_EVALUATION_WEBRTC_PICTURE_PAIR_PROVIDER_H_ diff --git a/video/corruption_detection/evaluation/webrtc_picture_pair_provider_unittest.cc b/video/corruption_detection/evaluation/webrtc_picture_pair_provider_unittest.cc new file mode 100644 index 0000000000..cc11ec0aa6 --- /dev/null +++ b/video/corruption_detection/evaluation/webrtc_picture_pair_provider_unittest.cc @@ -0,0 +1,731 @@ +/* + * Copyright 2025 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 "video/corruption_detection/evaluation/webrtc_picture_pair_provider.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "absl/strings/string_view.h" +#include "api/environment/environment_factory.h" +#include "api/field_trials_view.h" +#include "api/scoped_refptr.h" +#include "api/test/mock_video_decoder.h" +#include "api/test/mock_video_decoder_factory.h" +#include "api/test/mock_video_encoder.h" +#include "api/test/mock_video_encoder_factory.h" +#include "api/units/data_rate.h" +#include "api/video/encoded_image.h" +#include "api/video/i420_buffer.h" +#include "api/video/video_codec_type.h" +#include "api/video/video_frame.h" +#include "api/video/video_frame_type.h" +#include "api/video_codecs/builtin_video_decoder_factory.h" +#include "api/video_codecs/builtin_video_encoder_factory.h" +#include "api/video_codecs/scalability_mode.h" +#include "api/video_codecs/video_codec.h" +#include "api/video_codecs/video_decoder.h" +#include "api/video_codecs/video_decoder_factory_template.h" +#include "api/video_codecs/video_decoder_factory_template_dav1d_adapter.h" +#include "api/video_codecs/video_encoder.h" +#include "api/video_codecs/video_encoder_factory_template.h" +#include "api/video_codecs/video_encoder_factory_template_libaom_av1_adapter.h" +#include "common_video/libyuv/include/webrtc_libyuv.h" +#include "modules/video_coding/include/video_codec_interface.h" +#include "modules/video_coding/include/video_error_codes.h" +#include "modules/video_coding/svc/svc_rate_allocator.h" +#include "modules/video_coding/utility/simulcast_rate_allocator.h" +#include "rtc_base/checks.h" +#include "test/gmock.h" +#include "test/gtest.h" +#include "video/corruption_detection/evaluation/picture_pair_provider.h" +#include "video/corruption_detection/evaluation/test_clip.h" +#include "video/corruption_detection/evaluation/utils.h" + +namespace webrtc { +namespace { + +using ::testing::_; +using ::testing::AllOf; +using ::testing::ElementsAre; +using ::testing::Field; +using ::testing::HasSubstr; +using ::testing::InSequence; +using ::testing::Pointee; +using ::testing::Property; +using ::testing::Return; +using ::testing::TestWithParam; +using ::testing::Values; +using ::testing::WithoutArgs; + +// An arbitrary byte sequence which is used to represent an encoded frame. +constexpr uint8_t kEncodedFrame[] = {0x12, 0x0, 0xa, 0xa, 0x0, 0x0, 0x0, + 0x2, 0x27, 0xfe, 0xff, 0xfc, 0xc0, 0x20, + 0x32, 0x93, 0x2, 0x10, 0x0, 0xa8, 0x80, + 0x0, 0x3, 0x0, 0x10, 0x10, 0x30}; +constexpr size_t kEncodedFrameSize = + sizeof(kEncodedFrame) / sizeof(kEncodedFrame[0]); +// An arbitrary QP value. It is not connected with the `kEncodedFrame`. +constexpr int kQp = 31; + +// An arbitrary byte sequence which is used to represent a 2x2 decoded raw +// YUV420 frame. +constexpr uint8_t kDecodedChannelYContent[4] = {0x16, 0x21, 0x59, 0x11}; +constexpr uint8_t kDecodedChannelUContent[1] = {0x65}; +constexpr uint8_t kDecodedChannelVContent[1] = {0x89}; +constexpr int kDecodedWidth = 2; +constexpr int kDecodedHeight = 2; +constexpr int kDecodedStrideY = 2; +constexpr int kDecodedStrideU = 1; +constexpr int kDecodedStrideV = 1; + +constexpr int kDummyVideoWidth = 2; +constexpr int kDummyVideoHeight = 2; +constexpr int kNumFrames = 2; +// Two frames of dummy video. +constexpr uint8_t kDummyFileContent[kDummyVideoWidth * kDummyVideoHeight * 3] = + {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; + +// Test file name and information about it. +constexpr absl::string_view kFilename = "ConferenceMotion_1280_720_50"; +constexpr int kWidth = 1280; +constexpr int kHeight = 720; +constexpr int kFramerate = 50; + +// 90kHz clock for video. +constexpr uint32_t kRtpTimestampInterval = 90'000 / kFramerate; +constexpr VideoCodecMode kCodecMode = VideoCodecMode::kRealtimeVideo; + +constexpr float kBitsPerPixel = 0.1; +constexpr DataRate kDefaultBitrate = + DataRate::BitsPerSec(kWidth * kHeight * kFramerate * kBitsPerPixel); + +constexpr int kFramesToLoop = 5; + +// According to "Bankoski, J., Wilkins, P., & Xu, Y. (2011, July). Technical +// overview of VP8, an open source video codec for the web. In 2011 IEEE +// International Conference on Multimedia and Expo (pp. 1-6). IEEE.", a +// compressed video should have a PSNR higher than ~30 dB to be watchable. +// Hence, with `kBitsPerPixel` given to be 0.1 we should expect to have a PSNR > +// 30 dB. +constexpr double kWatchablePsnrDb = 30.0; +constexpr double kGoodPsnrDb = 40.0; + +TestClip GetTestClip() { + return TestClip::CreateYuvClip(kFilename, kWidth, kHeight, kFramerate, + kCodecMode); +} + +class EmptyFieldTrials : public FieldTrialsView { + public: + std::string Lookup(absl::string_view key) const override { return ""; } +}; + +class WebRtcPicturePairProviderTest : public TestWithParam { + protected: + WebRtcPicturePairProviderTest() + : encoder_factory_(std::make_unique()), + decoder_factory_(std::make_unique()), + codec_type_(GetParam()) {} + + ~WebRtcPicturePairProviderTest() override = default; + + void ExpectedCallsInConstructor() { + RTC_CHECK(encoder_factory_); + RTC_CHECK(decoder_factory_); + + EXPECT_CALL(*encoder_factory_, Create).WillOnce(WithoutArgs([&] { + std::unique_ptr encoder = + std::make_unique(); + encoder_ = static_cast(encoder.get()); + + EXPECT_CALL(*encoder_, RegisterEncodeCompleteCallback) + .WillOnce([&](EncodedImageCallback* callback) { + encode_callback_ = callback; + return WEBRTC_VIDEO_CODEC_OK; + }); + + return encoder; + })); + + EXPECT_CALL(*decoder_factory_, Create).WillOnce(WithoutArgs([&] { + std::unique_ptr decoder = + std::make_unique(); + decoder_ = static_cast(decoder.get()); + + EXPECT_CALL(*decoder_, RegisterDecodeCompleteCallback) + .WillOnce([&](DecodedImageCallback* callback) { + decode_callback_ = callback; + return WEBRTC_VIDEO_CODEC_OK; + }); + + return decoder; + })); + } + + void CreatePicturePairProvider(VideoCodecType codec_type) { + picture_pair_provider_ = + std::make_unique( + codec_type, std::move(encoder_factory_), + std::move(decoder_factory_)); + } + + void TearDown() override { + if (!skipped_test_) { + RTC_DCHECK(picture_pair_provider_ != nullptr); + + EXPECT_CALL(*encoder_, Release); + EXPECT_CALL(*decoder_, Release); + + EXPECT_CALL(*encoder_, RegisterEncodeCompleteCallback(nullptr)); + EXPECT_CALL(*decoder_, RegisterDecodeCompleteCallback(nullptr)); + } + } + + std::unique_ptr + picture_pair_provider_ = nullptr; + + std::unique_ptr encoder_factory_; + std::unique_ptr decoder_factory_; + + MockVideoEncoder* encoder_ = nullptr; + MockVideoDecoder* decoder_ = nullptr; + + EncodedImageCallback* encode_callback_ = nullptr; + DecodedImageCallback* decode_callback_ = nullptr; + + const VideoCodecType codec_type_; + bool skipped_test_ = false; +}; + +INSTANTIATE_TEST_SUITE_P(DifferentCodecTypes, + WebRtcPicturePairProviderTest, + Values(VideoCodecType::kVideoCodecVP8, + VideoCodecType::kVideoCodecVP9, + VideoCodecType::kVideoCodecAV1, + VideoCodecType::kVideoCodecH264)); + +#if GTEST_HAS_DEATH_TEST +TEST_P(WebRtcPicturePairProviderTest, RaiseErrorIfConfigureHasNotBeenCalled) { + ExpectedCallsInConstructor(); + CreatePicturePairProvider(codec_type_); + EXPECT_DEATH(picture_pair_provider_->GetNextPicturePair(), + HasSubstr("Encoder and decoder have not been initialized. Try " + "calling Configure first")); +} +#endif // GTEST_HAS_DEATH_TEST + +TEST_P(WebRtcPicturePairProviderTest, ConfigurationIsSuccesfull) { + ExpectedCallsInConstructor(); + CreatePicturePairProvider(codec_type_); + EXPECT_TRUE( + picture_pair_provider_->Configure(GetTestClip(), kDefaultBitrate)); +} + +TEST_P(WebRtcPicturePairProviderTest, ConfigureWhenInitialized) { + ExpectedCallsInConstructor(); + CreatePicturePairProvider(VideoCodecType::kVideoCodecAV1); + + ASSERT_TRUE( + picture_pair_provider_->Configure(GetTestClip(), kDefaultBitrate)); + + // If initiated encoder_ and decoder_ would have been released, still the + // configuration would work. + EXPECT_CALL(*encoder_, Release); + EXPECT_CALL(*decoder_, Release); + EXPECT_TRUE( + picture_pair_provider_->Configure(GetTestClip(), kDefaultBitrate)); +} + +#if GTEST_HAS_DEATH_TEST +TEST_P(WebRtcPicturePairProviderTest, NonExistentFileShouldRaiseError) { + ExpectedCallsInConstructor(); + CreatePicturePairProvider(codec_type_); + EXPECT_DEATH(TestClip::CreateY4mClip("does_not_exist", kCodecMode), _); +} +#endif // GTEST_HAS_DEATH_TEST + +TEST_P(WebRtcPicturePairProviderTest, InitializeEncoder) { + ExpectedCallsInConstructor(); + CreatePicturePairProvider(codec_type_); + + // Tests that ConfigureEncoderSettings() and InitializeEncoder() work + // properly. Need to compare fields because the VideoCodec class has + // deleted the equality operator. + if (codec_type_ == kVideoCodecVP9 || codec_type_ == kVideoCodecAV1) { + EXPECT_CALL( + *encoder_, + InitEncode( + AllOf(Field(&VideoCodec::width, kWidth), + Field(&VideoCodec::height, kHeight), + Field(&VideoCodec::maxFramerate, kFramerate), + Field(&VideoCodec::codecType, codec_type_), + Field(&VideoCodec::minBitrate, kDefaultBitrate.kbps()), + Field(&VideoCodec::startBitrate, kDefaultBitrate.kbps()), + Field(&VideoCodec::maxBitrate, kDefaultBitrate.kbps()), + Field(&VideoCodec::mode, kCodecMode), + Property(&VideoCodec::GetScalabilityMode, + ScalabilityMode::kL1T3), + Field(&VideoCodec::qpMax, 63)), + AllOf(Field(&VideoEncoder::Settings::number_of_cores, 1), + Field(&VideoEncoder::Settings::max_payload_size, 1500)))); + } else { + EXPECT_CALL( + *encoder_, + InitEncode( + AllOf(Field(&VideoCodec::width, kWidth), + Field(&VideoCodec::height, kHeight), + Field(&VideoCodec::maxFramerate, kFramerate), + Field(&VideoCodec::codecType, codec_type_), + Field(&VideoCodec::minBitrate, kDefaultBitrate.kbps()), + Field(&VideoCodec::startBitrate, kDefaultBitrate.kbps()), + Field(&VideoCodec::maxBitrate, kDefaultBitrate.kbps()), + Field(&VideoCodec::mode, kCodecMode), + Field(&VideoCodec::qpMax, + codec_type_ == kVideoCodecH264 ? 51 : 63)), + AllOf(Field(&VideoEncoder::Settings::number_of_cores, 1), + Field(&VideoEncoder::Settings::max_payload_size, 1500)))); + } + + EXPECT_TRUE( + picture_pair_provider_->Configure(GetTestClip(), kDefaultBitrate)); +} + +TEST_P(WebRtcPicturePairProviderTest, FailEncoderInitialization) { + ExpectedCallsInConstructor(); + CreatePicturePairProvider(codec_type_); + EXPECT_CALL(*encoder_, InitEncode(_, _)) + .WillOnce(Return(WEBRTC_VIDEO_CODEC_ERROR)); + EXPECT_FALSE( + picture_pair_provider_->Configure(GetTestClip(), kDefaultBitrate)); +} + +TEST_P(WebRtcPicturePairProviderTest, SetRatesWithSimulcastRateAllocator) { + if (codec_type_ != VideoCodecType::kVideoCodecVP8 && + codec_type_ != VideoCodecType::kVideoCodecH264) { + skipped_test_ = true; + GTEST_SKIP() << "SimulcastRateAllocator is only used for VP8 and H264."; + } + ExpectedCallsInConstructor(); + CreatePicturePairProvider(codec_type_); + + VideoCodec codec_config; + codec_config.width = kWidth; + codec_config.height = kHeight; + codec_config.maxFramerate = kFramerate; + codec_config.codecType = codec_type_; + codec_config.minBitrate = kDefaultBitrate.kbps(); + codec_config.startBitrate = kDefaultBitrate.kbps(); + codec_config.maxBitrate = kDefaultBitrate.kbps(); + codec_config.mode = kCodecMode; + + if (codec_type_ == VideoCodecType::kVideoCodecH264) { + codec_config.H264()->numberOfTemporalLayers = 3; + codec_config.qpMax = 51; + // For H264 one needs to specify the number of temporal layers for each + // spatial layer, which we specifically test here. This is because of how + // `SimulcastRateAllocator::NumTemporalStreams` is in + // modules/video_coding/utility/simulcast_rate_allocator.cc. + codec_config.simulcastStream[0].numberOfTemporalLayers = 3; + } else { + codec_config.VP8()->numberOfTemporalLayers = 3; + codec_config.qpMax = 63; + } + + SimulcastRateAllocator simulcast_rate_allocator(CreateEnvironment(), + codec_config); + VideoEncoder::RateControlParameters rate_params( + simulcast_rate_allocator.GetAllocation(kDefaultBitrate.bps(), kFramerate), + kFramerate, kDefaultBitrate); + + // Tests that SetRates() works properly with SimulcastRateAllocator. + EXPECT_CALL(*encoder_, SetRates(rate_params)); + + EXPECT_TRUE( + picture_pair_provider_->Configure(GetTestClip(), kDefaultBitrate)); +} + +TEST_P(WebRtcPicturePairProviderTest, SetRatesWithSvcRateAllocator) { + if (codec_type_ != VideoCodecType::kVideoCodecVP9 && + codec_type_ != VideoCodecType::kVideoCodecAV1) { + skipped_test_ = true; + GTEST_SKIP() << "SvcRateAllocator is only used for VP9 and AV1."; + } + ExpectedCallsInConstructor(); + CreatePicturePairProvider(codec_type_); + + VideoCodec codec_config; + codec_config.width = kWidth; + codec_config.height = kHeight; + codec_config.maxFramerate = kFramerate; + codec_config.codecType = codec_type_; + codec_config.minBitrate = kDefaultBitrate.kbps(); + codec_config.startBitrate = kDefaultBitrate.kbps(); + codec_config.maxBitrate = kDefaultBitrate.kbps(); + codec_config.mode = kCodecMode; + codec_config.SetScalabilityMode(ScalabilityMode::kL1T3); + codec_config.qpMax = 63; + + unsigned int bitrate_kbps = static_cast(kDefaultBitrate.kbps()); + codec_config.spatialLayers[0].targetBitrate = bitrate_kbps; + codec_config.spatialLayers[0].maxBitrate = bitrate_kbps; + codec_config.spatialLayers[0].active = true; + + SvcRateAllocator svc_rate_allocator(codec_config, EmptyFieldTrials()); + VideoEncoder::RateControlParameters rate_params = + VideoEncoder::RateControlParameters( + svc_rate_allocator.GetAllocation(kDefaultBitrate.bps(), kFramerate), + kFramerate, kDefaultBitrate); + + // Tests that SetRates() works properly with SvcRateAllocator. + EXPECT_CALL(*encoder_, SetRates(rate_params)); + + EXPECT_TRUE( + picture_pair_provider_->Configure(GetTestClip(), kDefaultBitrate)); +} + +TEST_P(WebRtcPicturePairProviderTest, ConfigureDecoderTest) { + ExpectedCallsInConstructor(); + CreatePicturePairProvider(codec_type_); + + EXPECT_CALL(*decoder_, + Configure(AllOf( + Property(&VideoDecoder::Settings::codec_type, codec_type_)))); + + EXPECT_TRUE( + picture_pair_provider_->Configure(GetTestClip(), kDefaultBitrate)); +} + +TEST_P(WebRtcPicturePairProviderTest, ConfigureDecoderFailure) { + ExpectedCallsInConstructor(); + CreatePicturePairProvider(codec_type_); + + EXPECT_CALL(*decoder_, Configure).WillOnce(Return(false)); + + EXPECT_FALSE( + picture_pair_provider_->Configure(GetTestClip(), kDefaultBitrate)); +} + +TEST_P(WebRtcPicturePairProviderTest, EncodeTest) { + ExpectedCallsInConstructor(); + CreatePicturePairProvider(codec_type_); + ASSERT_TRUE( + picture_pair_provider_->Configure(GetTestClip(), kDefaultBitrate)); + + constexpr int call_picture_pair_provider = 3; + + { + InSequence s; + + // VideoFrame does not have a Matcher operator, hence fields need to + // be checked. + EXPECT_CALL(*encoder_, + Encode(AllOf(Property(&VideoFrame::width, kWidth), + Property(&VideoFrame::height, kHeight), + Property(&VideoFrame::rtp_timestamp, 0)), + // Only the first frame should be a key frame. + Pointee(ElementsAre(VideoFrameType::kVideoFrameKey)))); + + EXPECT_CALL(*encoder_, + Encode(AllOf(Property(&VideoFrame::width, kWidth), + Property(&VideoFrame::height, kHeight), + Property(&VideoFrame::rtp_timestamp, + kRtpTimestampInterval)), + Pointee(ElementsAre(VideoFrameType::kVideoFrameDelta)))); + + EXPECT_CALL(*encoder_, + Encode(AllOf(Property(&VideoFrame::width, kWidth), + Property(&VideoFrame::height, kHeight), + Property(&VideoFrame::rtp_timestamp, + kRtpTimestampInterval * 2)), + Pointee(ElementsAre(VideoFrameType::kVideoFrameDelta)))); + } + + for (int i = 0; i < call_picture_pair_provider; ++i) { + // `encoded_image_` should not have a value, and therefore `std::nullopt` + // is expected to be returned. + EXPECT_EQ(picture_pair_provider_->GetNextPicturePair(), std::nullopt); + } +} + +TEST_P(WebRtcPicturePairProviderTest, EncodeFailure) { + ExpectedCallsInConstructor(); + CreatePicturePairProvider(codec_type_); + ASSERT_TRUE( + picture_pair_provider_->Configure(GetTestClip(), kDefaultBitrate)); + + EXPECT_CALL(*encoder_, Encode(_, _)) + .WillOnce(Return(WEBRTC_VIDEO_CODEC_ERROR)); + + EXPECT_EQ(picture_pair_provider_->GetNextPicturePair(), std::nullopt); +} + +// Populates `encoded_image` with arbitrary values. +void PopulateEncodedImage(EncodedImage* encoded_image, + VideoCodecType codec_type) { + scoped_refptr encoded_image_buffer = + EncodedImageBuffer::Create(kEncodedFrame, kEncodedFrameSize); + + encoded_image->SetEncodedData(encoded_image_buffer); +} + +TEST_P(WebRtcPicturePairProviderTest, DecodeFailureTest) { + ExpectedCallsInConstructor(); + CreatePicturePairProvider(codec_type_); + ASSERT_TRUE( + picture_pair_provider_->Configure(GetTestClip(), kDefaultBitrate)); + + EncodedImage encoded_image; + PopulateEncodedImage(&encoded_image, codec_type_); + CodecSpecificInfo codec_specific_info; + + EXPECT_CALL(*encoder_, Encode(_, _)) + .WillOnce([&](const VideoFrame& frame, + const std::vector* frame_types) { + encode_callback_->OnEncodedImage(encoded_image, &codec_specific_info); + return WEBRTC_VIDEO_CODEC_OK; + }); + + EXPECT_CALL(*decoder_, Decode(_, _)) + .WillOnce(Return(WEBRTC_VIDEO_CODEC_ERROR)); + + EXPECT_EQ(picture_pair_provider_->GetNextPicturePair(), std::nullopt); +} + +TEST_P(WebRtcPicturePairProviderTest, ProperDecodeTest) { + ExpectedCallsInConstructor(); + CreatePicturePairProvider(codec_type_); + ASSERT_TRUE( + picture_pair_provider_->Configure(GetTestClip(), kDefaultBitrate)); + + EncodedImage encoded_image; + PopulateEncodedImage(&encoded_image, codec_type_); + CodecSpecificInfo codec_specific_info; + + EXPECT_CALL(*encoder_, Encode(_, _)) + .WillOnce([&](const VideoFrame& frame, + const std::vector* frame_types) { + encoded_image.qp_ = kQp; + encode_callback_->OnEncodedImage(encoded_image, &codec_specific_info); + return WEBRTC_VIDEO_CODEC_OK; + }); + + scoped_refptr decoded_frame = I420Buffer::Copy( + kDecodedWidth, kDecodedHeight, kDecodedChannelYContent, kDecodedStrideY, + kDecodedChannelUContent, kDecodedStrideU, kDecodedChannelVContent, + kDecodedStrideV); + + VideoFrame decoded_image = VideoFrame::Builder() + .set_video_frame_buffer(decoded_frame) + .set_rtp_timestamp(0) + .build(); + + EXPECT_CALL(*decoder_, Decode(_, _)) + .WillOnce([&](const EncodedImage& input_image, int64_t render_time_ms) { + decode_callback_->Decoded(decoded_image); + return WEBRTC_VIDEO_CODEC_OK; + }); + + std::optional picture_pair = + picture_pair_provider_->GetNextPicturePair(); + ASSERT_NE(picture_pair, std::nullopt); + + // `picture_pair->compressed_image` must be the same as the toy decoded raw + // video. + for (int i = 0; i < kDecodedWidth * kDecodedHeight; ++i) { + EXPECT_EQ(picture_pair->compressed_image.video_frame_buffer() + ->ToI420() + ->DataY()[i], + kDecodedChannelYContent[i]); + } + EXPECT_EQ( + picture_pair->compressed_image.video_frame_buffer()->ToI420()->DataU()[0], + kDecodedChannelUContent[0]); + EXPECT_EQ( + picture_pair->compressed_image.video_frame_buffer()->ToI420()->DataV()[0], + kDecodedChannelVContent[0]); + EXPECT_EQ(picture_pair->frame_average_qp, kQp); +} + +class WebRtcPicturePairProviderEnd2EndTest + : public TestWithParam { + protected: + WebRtcPicturePairProviderEnd2EndTest() : codec_type_(GetParam()) {} + + ~WebRtcPicturePairProviderEnd2EndTest() override = default; + + int GetMapQP() { + switch (codec_type_) { + case VideoCodecType::kVideoCodecVP8: + return 127; + case VideoCodecType::kVideoCodecAV1: + case VideoCodecType::kVideoCodecVP9: + return 255; + case VideoCodecType::kVideoCodecH264: + return 51; + default: + RTC_DCHECK_NOTREACHED(); + return 0; + } + } + + VideoCodecType codec_type_; +}; + +// H264 is not built in WebRTC. +INSTANTIATE_TEST_SUITE_P(DifferentCodecTypes, + WebRtcPicturePairProviderEnd2EndTest, + Values(VideoCodecType::kVideoCodecVP8, + VideoCodecType::kVideoCodecVP9, + // VideoCodecType::kVideoCodecH264, + VideoCodecType::kVideoCodecAV1)); + +TEST_P(WebRtcPicturePairProviderEnd2EndTest, PsnrIsInExpectedRange) { + std::unique_ptr webrtc_provider; + if (codec_type_ != VideoCodecType::kVideoCodecAV1) { + webrtc_provider = std::make_unique( + codec_type_, CreateBuiltinVideoEncoderFactory(), + CreateBuiltinVideoDecoderFactory()); + } else { + // AV1 is injectible + webrtc_provider = std::make_unique( + codec_type_, + std::make_unique< + VideoEncoderFactoryTemplate>(), + std::make_unique< + VideoDecoderFactoryTemplate>()); + } + + ASSERT_TRUE(webrtc_provider->Configure(GetTestClip(), kDefaultBitrate)); + + for (int i = 0; i < kFramesToLoop; ++i) { + std::optional picture_pair = + webrtc_provider->GetNextPicturePair(); + + EXPECT_NE(picture_pair, std::nullopt); + EXPECT_GE(picture_pair->frame_average_qp, 0); + EXPECT_LE(picture_pair->frame_average_qp, GetMapQP()); + + // Calculate the PSNR between the original and compressed image. + double psnr = I420PSNR( + *picture_pair->original_image.video_frame_buffer()->GetI420(), + *picture_pair->compressed_image.video_frame_buffer()->GetI420()); + EXPECT_GE(psnr, kWatchablePsnrDb); + + // Test timestamp. + EXPECT_EQ(picture_pair->original_image.rtp_timestamp(), + kRtpTimestampInterval * i); + EXPECT_EQ(picture_pair->compressed_image.rtp_timestamp(), + kRtpTimestampInterval * i); + } +} + +TEST_P(WebRtcPicturePairProviderEnd2EndTest, PsnrIsGoodWhenBitrateIsHigh) { + std::unique_ptr webrtc_provider; + if (codec_type_ != VideoCodecType::kVideoCodecAV1) { + webrtc_provider = std::make_unique( + codec_type_, CreateBuiltinVideoEncoderFactory(), + CreateBuiltinVideoDecoderFactory()); + } else { + // AV1 is injectible + webrtc_provider = std::make_unique( + codec_type_, + std::make_unique< + VideoEncoderFactoryTemplate>(), + std::make_unique< + VideoDecoderFactoryTemplate>()); + } + + const DataRate high_bitrate = + DataRate::BitsPerSec(kWidth * kHeight * kFramerate * 10); + + ASSERT_TRUE(webrtc_provider->Configure(GetTestClip(), high_bitrate)); + + for (int i = 0; i < kFramesToLoop; ++i) { + std::optional picture_pair = + webrtc_provider->GetNextPicturePair(); + + EXPECT_NE(picture_pair, std::nullopt); + EXPECT_GE(picture_pair->frame_average_qp, 0); + EXPECT_LE(picture_pair->frame_average_qp, GetMapQP()); + + double psnr = I420PSNR( + *picture_pair->original_image.video_frame_buffer()->GetI420(), + *picture_pair->compressed_image.video_frame_buffer()->GetI420()); + + // For high enough bitrate the `I420PSNR` should return quite high PSNR + // score. + EXPECT_GE(psnr, kGoodPsnrDb); + } +} + +TEST_P(WebRtcPicturePairProviderEnd2EndTest, Y4mVideoTest) { + std::unique_ptr webrtc_provider; + if (codec_type_ != VideoCodecType::kVideoCodecAV1) { + webrtc_provider = std::make_unique( + codec_type_, CreateBuiltinVideoEncoderFactory(), + CreateBuiltinVideoDecoderFactory()); + } else { + // AV1 is injectible + webrtc_provider = std::make_unique( + codec_type_, + std::make_unique< + VideoEncoderFactoryTemplate>(), + std::make_unique< + VideoDecoderFactoryTemplate>()); + } + + // An Y4M file with two frames. + TempY4mFileCreator temp_y4m_file_creator(kDummyVideoWidth, kDummyVideoHeight, + kFramerate); + temp_y4m_file_creator.CreateTempY4mFile(kDummyFileContent); + const absl::string_view y4m_filepath = temp_y4m_file_creator.y4m_filepath(); + const TestClip y4m_test_clip = + TestClip::CreateY4mClip(y4m_filepath, kCodecMode); + ASSERT_TRUE(webrtc_provider->Configure(y4m_test_clip, kDefaultBitrate)); + + for (int i = 0; i < kNumFrames; ++i) { + std::optional picture_pair = + webrtc_provider->GetNextPicturePair(); + + EXPECT_NE(picture_pair, std::nullopt); + EXPECT_GE(picture_pair->frame_average_qp, 0); + std::cout << "Avg QP: " << picture_pair->frame_average_qp << std::endl; + EXPECT_LE(picture_pair->frame_average_qp, GetMapQP()); + + // Calculate the PSNR between the original and compressed image. + double psnr = I420PSNR( + *picture_pair->original_image.video_frame_buffer()->GetI420(), + *picture_pair->compressed_image.video_frame_buffer()->GetI420()); + EXPECT_GE(psnr, kWatchablePsnrDb); + std::cout << "PSNR: " << psnr << std::endl; + + // Test timestamp. + EXPECT_EQ(picture_pair->original_image.rtp_timestamp(), + kRtpTimestampInterval * i); + EXPECT_EQ(picture_pair->compressed_image.rtp_timestamp(), + kRtpTimestampInterval * i); + } + + // We need to destruct the `webrtc_provider` because of it keeping the + // read video file open. If we don't do this, we get an error when trying to + // delete the file on Windows + webrtc_provider.reset(); +} + +} // namespace +} // namespace webrtc diff --git a/video/corruption_detection/frame_pair_corruption_score.cc b/video/corruption_detection/frame_pair_corruption_score.cc index a6d21c23e9..fb7679fa11 100644 --- a/video/corruption_detection/frame_pair_corruption_score.cc +++ b/video/corruption_detection/frame_pair_corruption_score.cc @@ -28,7 +28,7 @@ namespace { constexpr float kDefaultSampleFraction = 0.5; -} +} // namespace FramePairCorruptionScorer::FramePairCorruptionScorer( absl::string_view codec_name, diff --git a/video/corruption_detection/halton_sequence.cc b/video/corruption_detection/halton_sequence.cc index c41647340a..4285b2ece0 100644 --- a/video/corruption_detection/halton_sequence.cc +++ b/video/corruption_detection/halton_sequence.cc @@ -18,7 +18,7 @@ namespace webrtc { namespace { -static constexpr int kMaxDimensions = 5; +constexpr int kMaxDimensions = 5; const int kBases[kMaxDimensions] = {2, 3, 5, 7, 11}; double GetVanDerCorputSequenceElement(int sequence_idx, int base) { diff --git a/video/encoder_overshoot_detector.cc b/video/encoder_overshoot_detector.cc index b31b6be9ee..f464d2d0bc 100644 --- a/video/encoder_overshoot_detector.cc +++ b/video/encoder_overshoot_detector.cc @@ -26,7 +26,7 @@ namespace { // The buffer level for media-rate utilization is allowed to go below zero, // down to // -(`kMaxMediaUnderrunFrames` / `target_framerate_fps_`) * `target_bitrate_`. -static constexpr double kMaxMediaUnderrunFrames = 5.0; +constexpr double kMaxMediaUnderrunFrames = 5.0; } // namespace EncoderOvershootDetector::EncoderOvershootDetector(int64_t window_size_ms, diff --git a/video/encoder_overshoot_detector_unittest.cc b/video/encoder_overshoot_detector_unittest.cc index 2dc8e4f24e..ab2a4ab5a3 100644 --- a/video/encoder_overshoot_detector_unittest.cc +++ b/video/encoder_overshoot_detector_unittest.cc @@ -31,7 +31,7 @@ namespace { using ::testing::TestWithParam; using ::testing::ValuesIn; -static std::string CodecTypeToHistogramSuffix(VideoCodecType codec) { +std::string CodecTypeToHistogramSuffix(VideoCodecType codec) { switch (codec) { case kVideoCodecVP8: return "Vp8"; diff --git a/video/end_to_end_tests/codec_tests.cc b/video/end_to_end_tests/codec_tests.cc index e1d440e06c..e4ae7fb079 100644 --- a/video/end_to_end_tests/codec_tests.cc +++ b/video/end_to_end_tests/codec_tests.cc @@ -256,8 +256,8 @@ TEST_P(EndToEndTestH264, SendsAndReceivesH264VideoRotation90) { } TEST_P(EndToEndTestH264, SendsAndReceivesH264PacketizationMode0) { - SdpVideoFormat codec(webrtc::kH264CodecName); - codec.parameters[webrtc::kH264FmtpPacketizationMode] = "0"; + SdpVideoFormat codec(kH264CodecName); + codec.parameters[kH264FmtpPacketizationMode] = "0"; test::FunctionVideoEncoderFactory encoder_factory( [codec](const Environment& env, const SdpVideoFormat& format) { return CreateH264Encoder(env, H264EncoderSettings::Parse(codec)); @@ -270,8 +270,8 @@ TEST_P(EndToEndTestH264, SendsAndReceivesH264PacketizationMode0) { } TEST_P(EndToEndTestH264, SendsAndReceivesH264PacketizationMode1) { - SdpVideoFormat codec(webrtc::kH264CodecName); - codec.parameters[webrtc::kH264FmtpPacketizationMode] = "1"; + SdpVideoFormat codec(kH264CodecName); + codec.parameters[kH264FmtpPacketizationMode] = "1"; test::FunctionVideoEncoderFactory encoder_factory( [codec](const Environment& env, const SdpVideoFormat& format) { return CreateH264Encoder(env, H264EncoderSettings::Parse(codec)); diff --git a/video/end_to_end_tests/multi_codec_receive_tests.cc b/video/end_to_end_tests/multi_codec_receive_tests.cc index d958c7749d..a72e7a3a4f 100644 --- a/video/end_to_end_tests/multi_codec_receive_tests.cc +++ b/video/end_to_end_tests/multi_codec_receive_tests.cc @@ -158,7 +158,7 @@ class MultiCodecReceiveTest : public test::CallTest { }); } - virtual ~MultiCodecReceiveTest() { + ~MultiCodecReceiveTest() override { SendTask(task_queue(), [this]() { send_transport_.reset(); receive_transport_.reset(); diff --git a/video/end_to_end_tests/network_state_tests.cc b/video/end_to_end_tests/network_state_tests.cc index 35b802b7e2..d41df836da 100644 --- a/video/end_to_end_tests/network_state_tests.cc +++ b/video/end_to_end_tests/network_state_tests.cc @@ -46,7 +46,7 @@ namespace webrtc { namespace { constexpr int kSilenceTimeoutMs = 2000; -} +} // namespace class NetworkStateEndToEndTest : public test::CallTest { protected: @@ -68,7 +68,7 @@ class NetworkStateEndToEndTest : public test::CallTest { public: RequiredTransport(bool rtp_required, bool rtcp_required) : need_rtp_(rtp_required), need_rtcp_(rtcp_required) {} - ~RequiredTransport() { + ~RequiredTransport() override { if (need_rtp_) { ADD_FAILURE() << "Expected RTP packet not sent."; } @@ -410,7 +410,7 @@ TEST_F(NetworkStateEndToEndTest, NewVideoSendStreamsIgnoreAudioNetworkDown) { public: explicit RequiredEncoder(const Environment& env) : FakeEncoder(env), encoded_frame_(false) {} - ~RequiredEncoder() { + ~RequiredEncoder() override { if (!encoded_frame_) { ADD_FAILURE() << "Didn't encode an expected frame"; } diff --git a/video/end_to_end_tests/transport_feedback_tests.cc b/video/end_to_end_tests/transport_feedback_tests.cc index 84f2d56d23..333cc0c534 100644 --- a/video/end_to_end_tests/transport_feedback_tests.cc +++ b/video/end_to_end_tests/transport_feedback_tests.cc @@ -89,7 +89,7 @@ TEST(TransportFeedbackMultiStreamTest, AssignsTransportSequenceNumbers) { extensions_.Register( kTransportSequenceNumberExtensionId); } - virtual ~RtpExtensionHeaderObserver() {} + ~RtpExtensionHeaderObserver() override {} bool SendRtp(ArrayView data, const PacketOptions& options) override { diff --git a/video/frame_cadence_adapter.cc b/video/frame_cadence_adapter.cc index 7e151f6d22..63feaee95e 100644 --- a/video/frame_cadence_adapter.cc +++ b/video/frame_cadence_adapter.cc @@ -42,7 +42,6 @@ #include "rtc_base/thread_annotations.h" #include "rtc_base/trace_event.h" #include "system_wrappers/include/clock.h" -#include "system_wrappers/include/metrics.h" namespace webrtc { namespace { @@ -109,9 +108,8 @@ class ZeroHertzAdapterMode : public AdapterMode { Clock* clock, FrameCadenceAdapterInterface::Callback* callback, double max_fps, - std::atomic& frames_scheduled_for_processing, - bool zero_hertz_queue_overload); - ~ZeroHertzAdapterMode() { refresh_frame_requester_.Stop(); } + std::atomic& frames_scheduled_for_processing); + ~ZeroHertzAdapterMode() override { refresh_frame_requester_.Stop(); } // Reconfigures according to parameters. // All spatial layer trackers are initialized as unconverged by this method. @@ -228,9 +226,6 @@ class ZeroHertzAdapterMode : public AdapterMode { // `queue_`. const std::atomic& frames_scheduled_for_processing_; - // Can be used as kill-switch for the queue overload mechanism. - const bool zero_hertz_queue_overload_enabled_; - // How much the incoming frame sequence is delayed by. const TimeDelta frame_delay_ = TimeDelta::Seconds(1) / max_fps_; @@ -350,7 +345,7 @@ class FrameCadenceAdapterImpl : public FrameCadenceAdapterInterface { Metronome* metronome, TaskQueueBase* worker_queue, const FieldTrialsView& field_trials); - ~FrameCadenceAdapterImpl(); + ~FrameCadenceAdapterImpl() override; // FrameCadenceAdapterInterface overrides. void Initialize(Callback* callback) override; @@ -394,15 +389,8 @@ class FrameCadenceAdapterImpl : public FrameCadenceAdapterInterface { Clock* const clock_; TaskQueueBase* const queue_; - // Kill-switch for the queue overload mechanism in zero-hertz mode. - const bool frame_cadence_adapter_zero_hertz_queue_overload_enabled_; - - // Field trial for using timestamp from video frames, rather than clock when - // calculating input frame rate. - const bool use_video_frame_timestamp_; // Used for verifying that timestamps are monotonically increasing. std::optional last_incoming_frame_timestamp_; - bool incoming_frame_timestamp_monotonically_increasing_ = true; // The three possible modes we're under. std::optional passthrough_adapter_; @@ -419,10 +407,6 @@ class FrameCadenceAdapterImpl : public FrameCadenceAdapterInterface { Metronome* const metronome_; TaskQueueBase* const worker_queue_; - // Timestamp for statistics reporting. - std::optional zero_hertz_adapter_created_timestamp_ - RTC_GUARDED_BY(queue_); - // Set up during Initialize. Callback* callback_ = nullptr; @@ -451,14 +435,12 @@ ZeroHertzAdapterMode::ZeroHertzAdapterMode( Clock* clock, FrameCadenceAdapterInterface::Callback* callback, double max_fps, - std::atomic& frames_scheduled_for_processing, - bool zero_hertz_queue_overload_enabled) + std::atomic& frames_scheduled_for_processing) : queue_(queue), clock_(clock), callback_(callback), max_fps_(max_fps), - frames_scheduled_for_processing_(frames_scheduled_for_processing), - zero_hertz_queue_overload_enabled_(zero_hertz_queue_overload_enabled) { + frames_scheduled_for_processing_(frames_scheduled_for_processing) { sequence_checker_.Detach(); MaybeStartRefreshFrameRequester(); } @@ -718,10 +700,6 @@ void ZeroHertzAdapterMode::SendFrameNow(std::optional post_time, TRACE_EVENT0("webrtc", __func__); Timestamp encode_start_time = clock_->CurrentTime(); - if (post_time.has_value()) { - TimeDelta delay = (encode_start_time - *post_time); - RTC_HISTOGRAM_COUNTS_10000("WebRTC.Screenshare.ZeroHz.DelayMs", delay.ms()); - } // Forward the frame and set `queue_overload` if is has been detected that it // is not possible to deliver frames at the expected rate due to slow @@ -729,10 +707,6 @@ void ZeroHertzAdapterMode::SendFrameNow(std::optional post_time, callback_->OnFrame(/*post_time=*/encode_start_time, queue_overload_count_ > 0, frame); - // WebRTC-ZeroHertzQueueOverload kill-switch. - if (!zero_hertz_queue_overload_enabled_) - return; - // `queue_overload_count_` determines for how many future frames the // `queue_overload` flag will be set and it is only increased if: // o We are not already in an overload state. @@ -759,8 +733,6 @@ void ZeroHertzAdapterMode::SendFrameNow(std::optional post_time, } else { queue_overload_count_--; } - RTC_HISTOGRAM_BOOLEAN("WebRTC.Screenshare.ZeroHz.QueueOverload", - queue_overload_count_ > 0); } TimeDelta ZeroHertzAdapterMode::FrameDuration() const { @@ -867,10 +839,6 @@ FrameCadenceAdapterImpl::FrameCadenceAdapterImpl( const FieldTrialsView& field_trials) : clock_(clock), queue_(queue), - frame_cadence_adapter_zero_hertz_queue_overload_enabled_( - !field_trials.IsDisabled("WebRTC-ZeroHertzQueueOverload")), - use_video_frame_timestamp_(field_trials.IsEnabled( - "WebRTC-FrameCadenceAdapter-UseVideoFrameTimestamp")), metronome_(metronome), worker_queue_(worker_queue) {} @@ -884,10 +852,6 @@ FrameCadenceAdapterImpl::~FrameCadenceAdapterImpl() { absl::Cleanup cleanup = [adapter = std::move(vsync_encode_adapter_)] {}; worker_queue_->PostTask([cleanup = std::move(cleanup)] {}); } - - RTC_HISTOGRAM_BOOLEAN( - "WebRTC.Video.InputFrameTimestampMonotonicallyIncreasing", - incoming_frame_timestamp_monotonically_increasing_); } void FrameCadenceAdapterImpl::Initialize(Callback* callback) { @@ -973,14 +937,6 @@ void FrameCadenceAdapterImpl::OnFrame(const VideoFrame& frame) { frames_scheduled_for_processing_.fetch_add(1, std::memory_order_relaxed); queue_->PostTask(SafeTask(safety_.flag(), [this, post_time, frame] { RTC_DCHECK_RUN_ON(queue_); - if (zero_hertz_adapter_created_timestamp_.has_value()) { - TimeDelta time_until_first_frame = - clock_->CurrentTime() - *zero_hertz_adapter_created_timestamp_; - zero_hertz_adapter_created_timestamp_ = std::nullopt; - RTC_HISTOGRAM_COUNTS_10000( - "WebRTC.Screenshare.ZeroHz.TimeUntilFirstFrameMs", - time_until_first_frame.ms()); - } const int frames_scheduled_for_processing = frames_scheduled_for_processing_.fetch_sub(1, @@ -1025,12 +981,9 @@ void FrameCadenceAdapterImpl::OnFrameOnMainQueue(Timestamp post_time, << "Incoming frame timestamp is not monotonically increasing" << " current: " << frame.timestamp_us() << " last: " << last_incoming_frame_timestamp_.value().us(); - incoming_frame_timestamp_monotonically_increasing_ = false; } last_incoming_frame_timestamp_ = Timestamp::Micros(frame.timestamp_us()); - Timestamp update_frame_rate_timestamp = - use_video_frame_timestamp_ ? *last_incoming_frame_timestamp_ : post_time; - UpdateFrameRate(update_frame_rate_timestamp); + UpdateFrameRate(post_time); } bool FrameCadenceAdapterImpl::IsZeroHertzScreenshareEnabled() const { @@ -1062,13 +1015,11 @@ void FrameCadenceAdapterImpl::MaybeReconfigureAdapters( if (!was_zero_hertz_enabled || max_fps_has_changed) { RTC_LOG(LS_INFO) << "Zero hertz mode enabled (max_fps=" << source_constraints_->max_fps.value() << ")"; - zero_hertz_adapter_.emplace( - queue_, clock_, callback_, source_constraints_->max_fps.value(), - frames_scheduled_for_processing_, - frame_cadence_adapter_zero_hertz_queue_overload_enabled_); + zero_hertz_adapter_.emplace(queue_, clock_, callback_, + source_constraints_->max_fps.value(), + frames_scheduled_for_processing_); zero_hertz_adapter_->UpdateVideoSourceRestrictions( restricted_max_frame_rate_); - zero_hertz_adapter_created_timestamp_ = clock_->CurrentTime(); } zero_hertz_adapter_->ReconfigureParameters(zero_hertz_params_.value()); current_adapter_mode_ = &zero_hertz_adapter_.value(); diff --git a/video/frame_cadence_adapter_unittest.cc b/video/frame_cadence_adapter_unittest.cc index 37f73eedfb..4bee5194cd 100644 --- a/video/frame_cadence_adapter_unittest.cc +++ b/video/frame_cadence_adapter_unittest.cc @@ -1012,40 +1012,6 @@ class FrameCadenceAdapterMetricsTest : public ::testing::Test { GlobalSimulatedTimeController time_controller_; }; -TEST_F(FrameCadenceAdapterMetricsTest, RecordsTimeUntilFirstFrame) { - MockCallback callback; - test::ScopedKeyValueConfig no_field_trials; - auto adapter = CreateAdapter(no_field_trials, time_controller_.GetClock()); - adapter->Initialize(&callback); - adapter->SetZeroHertzModeEnabled( - FrameCadenceAdapterInterface::ZeroHertzModeParams{}); - adapter->OnConstraintsChanged(VideoTrackSourceConstraints{0, 5.0}); - time_controller_.AdvanceTime(TimeDelta::Millis(666)); - adapter->OnFrame(CreateFrame()); - DepleteTaskQueues(); - EXPECT_THAT( - metrics::Samples("WebRTC.Screenshare.ZeroHz.TimeUntilFirstFrameMs"), - ElementsAre(Pair(666, 1))); -} - -TEST_F(FrameCadenceAdapterMetricsTest, - RecordsFrameTimestampMonotonicallyIncreasing) { - MockCallback callback; - test::ScopedKeyValueConfig no_field_trials; - std::unique_ptr adapter = - CreateAdapter(no_field_trials, time_controller_.GetClock()); - adapter->Initialize(&callback); - time_controller_.AdvanceTime(TimeDelta::Millis(666)); - adapter->OnFrame(CreateFrameWithTimestamps(&time_controller_)); - adapter->OnFrame(CreateFrameWithTimestamps(&time_controller_)); - time_controller_.AdvanceTime(TimeDelta::Zero()); - adapter = nullptr; - DepleteTaskQueues(); - EXPECT_THAT(metrics::Samples( - "WebRTC.Video.InputFrameTimestampMonotonicallyIncreasing"), - ElementsAre(Pair(false, 1))); -} - TEST(FrameCadenceAdapterRealTimeTest, TimestampsDoNotDrift) { // This regression test must be performed in realtime because of limitations // in GlobalSimulatedTimeController. @@ -1154,167 +1120,5 @@ TEST(FrameCadenceAdapterRealTimeTest, ScheduledRepeatAllowsForSlowEncode) { }); finalized.Wait(Event::kForever); } - -class ZeroHertzQueueOverloadTest : public ::testing::Test { - public: - static constexpr int kMaxFps = 10; - - ZeroHertzQueueOverloadTest() { - Initialize(); - metrics::Reset(); - } - - void Initialize() { - adapter_->Initialize(&callback_); - adapter_->SetZeroHertzModeEnabled( - FrameCadenceAdapterInterface::ZeroHertzModeParams{ - /*num_simulcast_layers=*/1}); - adapter_->OnConstraintsChanged( - VideoTrackSourceConstraints{/*min_fps=*/0, kMaxFps}); - time_controller_.AdvanceTime(TimeDelta::Zero()); - } - - void ScheduleDelayed(TimeDelta delay, absl::AnyInvocable task) { - TaskQueueBase::Current()->PostDelayedTask(std::move(task), delay); - } - - void PassFrame() { adapter_->OnFrame(CreateFrame()); } - - void AdvanceTime(TimeDelta duration) { - time_controller_.AdvanceTime(duration); - } - - void SkipForwardBy(TimeDelta duration) { - time_controller_.SkipForwardBy(duration); - } - - Timestamp CurrentTime() { return time_controller_.GetClock()->CurrentTime(); } - - protected: - test::ScopedKeyValueConfig field_trials_; - NiceMock callback_; - GlobalSimulatedTimeController time_controller_{Timestamp::Zero()}; - std::unique_ptr adapter_{ - CreateAdapter(field_trials_, time_controller_.GetClock())}; -}; - -TEST_F(ZeroHertzQueueOverloadTest, - ForwardedFramesDuringTooLongEncodeTimeAreFlaggedWithQueueOverload) { - InSequence s; - PassFrame(); - EXPECT_CALL(callback_, OnFrame(_, false, _)).WillOnce(InvokeWithoutArgs([&] { - PassFrame(); - PassFrame(); - PassFrame(); - SkipForwardBy(TimeDelta::Millis(301)); - })); - EXPECT_CALL(callback_, OnFrame(_, true, _)).Times(3); - AdvanceTime(TimeDelta::Millis(100)); - EXPECT_THAT(metrics::Samples("WebRTC.Screenshare.ZeroHz.QueueOverload"), - ElementsAre(Pair(false, 1), Pair(true, 3))); -} - -TEST_F(ZeroHertzQueueOverloadTest, - ForwardedFramesAfterOverloadBurstAreNotFlaggedWithQueueOverload) { - InSequence s; - PassFrame(); - EXPECT_CALL(callback_, OnFrame(_, false, _)).WillOnce(InvokeWithoutArgs([&] { - PassFrame(); - PassFrame(); - PassFrame(); - SkipForwardBy(TimeDelta::Millis(301)); - })); - EXPECT_CALL(callback_, OnFrame(_, true, _)).Times(3); - AdvanceTime(TimeDelta::Millis(100)); - EXPECT_CALL(callback_, OnFrame(_, false, _)).Times(2); - PassFrame(); - PassFrame(); - AdvanceTime(TimeDelta::Millis(100)); - EXPECT_THAT(metrics::Samples("WebRTC.Screenshare.ZeroHz.QueueOverload"), - ElementsAre(Pair(false, 3), Pair(true, 3))); -} - -TEST_F(ZeroHertzQueueOverloadTest, - ForwardedFramesDuringNormalEncodeTimeAreNotFlaggedWithQueueOverload) { - InSequence s; - PassFrame(); - EXPECT_CALL(callback_, OnFrame(_, false, _)).WillOnce(InvokeWithoutArgs([&] { - PassFrame(); - PassFrame(); - PassFrame(); - // Long but not too long encode time. - SkipForwardBy(TimeDelta::Millis(99)); - })); - EXPECT_CALL(callback_, OnFrame(_, false, _)).Times(3); - AdvanceTime(TimeDelta::Millis(199)); - EXPECT_THAT(metrics::Samples("WebRTC.Screenshare.ZeroHz.QueueOverload"), - ElementsAre(Pair(false, 4))); -} - -TEST_F( - ZeroHertzQueueOverloadTest, - AvoidSettingQueueOverloadAndSendRepeatWhenNoNewPacketsWhileTooLongEncode) { - // Receive one frame only and let OnFrame take such a long time that an - // overload normally is warranted. But the fact that no new frames arrive - // while being blocked should trigger a non-idle repeat to ensure that the - // video stream does not freeze and queue overload should be false. - PassFrame(); - EXPECT_CALL(callback_, OnFrame(_, false, _)) - .WillOnce( - InvokeWithoutArgs([&] { SkipForwardBy(TimeDelta::Millis(101)); })) - .WillOnce(InvokeWithoutArgs([&] { - // Non-idle repeat. - EXPECT_EQ(CurrentTime(), Timestamp::Zero() + TimeDelta::Millis(201)); - })); - AdvanceTime(TimeDelta::Millis(100)); - EXPECT_THAT(metrics::Samples("WebRTC.Screenshare.ZeroHz.QueueOverload"), - ElementsAre(Pair(false, 2))); -} - -TEST_F(ZeroHertzQueueOverloadTest, - EnterFastRepeatAfterQueueOverloadWhenReceivedOnlyOneFrameDuringEncode) { - InSequence s; - // - Forward one frame frame during high load which triggers queue overload. - // - Receive only one new frame while being blocked and verify that the - // cancelled repeat was for the first frame and not the second. - // - Fast repeat mode should happen after second frame. - PassFrame(); - EXPECT_CALL(callback_, OnFrame(_, false, _)).WillOnce(InvokeWithoutArgs([&] { - PassFrame(); - SkipForwardBy(TimeDelta::Millis(101)); - })); - EXPECT_CALL(callback_, OnFrame(_, true, _)); - AdvanceTime(TimeDelta::Millis(100)); - - // Fast repeats should take place from here on. - EXPECT_CALL(callback_, OnFrame(_, false, _)).Times(5); - AdvanceTime(TimeDelta::Millis(500)); - EXPECT_THAT(metrics::Samples("WebRTC.Screenshare.ZeroHz.QueueOverload"), - ElementsAre(Pair(false, 6), Pair(true, 1))); -} - -TEST_F(ZeroHertzQueueOverloadTest, - QueueOverloadIsDisabledForZeroHerzWhenKillSwitchIsEnabled) { - test::ScopedKeyValueConfig field_trials( - field_trials_, "WebRTC-ZeroHertzQueueOverload/Disabled/"); - adapter_.reset(); - adapter_ = CreateAdapter(field_trials, time_controller_.GetClock()); - Initialize(); - - // Same as ForwardedFramesDuringTooLongEncodeTimeAreFlaggedWithQueueOverload - // but this time the queue overload mechanism is disabled. - InSequence s; - PassFrame(); - EXPECT_CALL(callback_, OnFrame(_, false, _)).WillOnce(InvokeWithoutArgs([&] { - PassFrame(); - PassFrame(); - PassFrame(); - SkipForwardBy(TimeDelta::Millis(301)); - })); - EXPECT_CALL(callback_, OnFrame(_, false, _)).Times(3); - AdvanceTime(TimeDelta::Millis(100)); - EXPECT_EQ(metrics::NumSamples("WebRTC.Screenshare.ZeroHz.QueueOverload"), 0); -} - } // namespace } // namespace webrtc diff --git a/video/frame_decode_timing.h b/video/frame_decode_timing.h index 1679bf524f..f4e7106a84 100644 --- a/video/frame_decode_timing.h +++ b/video/frame_decode_timing.h @@ -24,7 +24,7 @@ namespace webrtc { class FrameDecodeTiming { public: - FrameDecodeTiming(Clock* clock, webrtc::VCMTiming const* timing); + FrameDecodeTiming(Clock* clock, VCMTiming const* timing); ~FrameDecodeTiming() = default; FrameDecodeTiming(const FrameDecodeTiming&) = delete; FrameDecodeTiming& operator=(const FrameDecodeTiming&) = delete; @@ -46,7 +46,7 @@ class FrameDecodeTiming { private: Clock* const clock_; - webrtc::VCMTiming const* const timing_; + VCMTiming const* const timing_; }; } // namespace webrtc diff --git a/video/frame_encode_metadata_writer.cc b/video/frame_encode_metadata_writer.cc index dbc303ce0b..32c15b0174 100644 --- a/video/frame_encode_metadata_writer.cc +++ b/video/frame_encode_metadata_writer.cc @@ -201,7 +201,7 @@ void FrameEncodeMetadataWriter::FillMetadataAndTimingInfo( // If encode start is not available that means that encoder uses internal // source. In that case capture timestamp may be from a different clock with a - // drift relative to webrtc::TimeMillis(). We can't use it for Timing frames, + // drift relative to TimeMillis(). We can't use it for Timing frames, // because to being sent in the network capture time required to be less than // all the other timestamps. if (encode_start_ms) { diff --git a/video/full_stack_tests.cc b/video/full_stack_tests.cc index f8c809c970..d3bbf70813 100644 --- a/video/full_stack_tests.cc +++ b/video/full_stack_tests.cc @@ -7,16 +7,13 @@ * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ -#include #include #include -#include #include #include "absl/flags/flag.h" #include "api/rtp_parameters.h" #include "api/test/simulated_network.h" -#include "api/test/test_dependency_factory.h" #include "api/test/video_quality_test_fixture.h" #include "api/units/data_rate.h" #include "api/video_codecs/sdp_video_format.h" @@ -24,8 +21,6 @@ #include "api/video_codecs/video_codec.h" #include "api/video_codecs/vp9_profile.h" #include "modules/video_coding/codecs/vp9/include/vp9.h" -#include "system_wrappers/include/field_trial.h" -#include "test/field_trial.h" #include "test/gtest.h" #include "test/testsupport/file_utils.h" #include "video/config/video_encoder_config.h" @@ -49,7 +44,7 @@ ABSL_FLAG(std::string, namespace webrtc { namespace { -static const int kFullStackTestDurationSecs = 45; +const int kFullStackTestDurationSecs = 45; struct ParamsWithLogging : public VideoQualityTest::Params { public: @@ -62,19 +57,6 @@ struct ParamsWithLogging : public VideoQualityTest::Params { } }; -std::unique_ptr -CreateVideoQualityTestFixture() { - // The components will normally be nullptr (= use defaults), but it's possible - // for external test runners to override the list of injected components. - auto components = TestDependencyFactory::GetInstance().CreateComponents(); - return std::make_unique(std::move(components)); -} - -// Takes the current active field trials set, and appends some new trials. -std::string AppendFieldTrials(std::string new_trial_string) { - return std::string(field_trial::GetFieldTrialString()) + new_trial_string; -} - std::string ClipNameToClipPath(const char* clip_name) { return test::ResourcePath(clip_name, "yuv"); } @@ -92,7 +74,7 @@ std::string ClipNameToClipPath(const char* clip_name) { #if defined(RTC_ENABLE_VP9) TEST(FullStackTest, Foreman_Cif_Net_Delay_0_0_Plr_0_VP9) { - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture; ParamsWithLogging foreman_cif; foreman_cif.call.send_side_bwe = true; foreman_cif.video[0] = { @@ -102,12 +84,12 @@ TEST(FullStackTest, Foreman_Cif_Net_Delay_0_0_Plr_0_VP9) { false, false, true, ClipNameToClipPath("foreman_cif")}; foreman_cif.analyzer = {"foreman_cif_net_delay_0_0_plr_0_VP9", 0.0, 0.0, kFullStackTestDurationSecs}; - fixture->RunWithAnalyzer(foreman_cif); + fixture.RunWithAnalyzer(foreman_cif); } TEST(GenericDescriptorTest, Foreman_Cif_Delay_50_0_Plr_5_VP9_Generic_Descriptor) { - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture; ParamsWithLogging foreman_cif; foreman_cif.call.send_side_bwe = true; foreman_cif.video[0] = { @@ -120,7 +102,7 @@ TEST(GenericDescriptorTest, foreman_cif.config->loss_percent = 5; foreman_cif.config->queue_delay_ms = 50; foreman_cif.call.generic_descriptor = true; - fixture->RunWithAnalyzer(foreman_cif); + fixture.RunWithAnalyzer(foreman_cif); } TEST(FullStackTest, Generator_Net_Delay_0_0_Plr_0_VP9Profile2) { @@ -135,7 +117,7 @@ TEST(FullStackTest, Generator_Net_Delay_0_0_Plr_0_VP9Profile2) { } if (!profile_2_is_supported) return; - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture; CodecParameterMap vp92 = { {kVP9FmtpProfileId, VP9ProfileToString(VP9Profile::kProfile2)}}; @@ -146,7 +128,7 @@ TEST(FullStackTest, Generator_Net_Delay_0_0_Plr_0_VP9Profile2) { 1, 0, 0, false, false, true, "GeneratorI010", 0, vp92}; generator.analyzer = {"generator_net_delay_0_0_plr_0_VP9Profile2", 0.0, 0.0, kFullStackTestDurationSecs}; - fixture->RunWithAnalyzer(generator); + fixture.RunWithAnalyzer(generator); } #endif // defined(RTC_ENABLE_VP9) @@ -158,7 +140,7 @@ TEST(FullStackTest, Generator_Net_Delay_0_0_Plr_0_VP9Profile2) { #define MAYBE_Net_Delay_0_0_Plr_0 Net_Delay_0_0_Plr_0 #endif TEST(FullStackTest, MAYBE_Net_Delay_0_0_Plr_0) { - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture; ParamsWithLogging paris_qcif; paris_qcif.call.send_side_bwe = true; paris_qcif.video[0] = { @@ -168,12 +150,12 @@ TEST(FullStackTest, MAYBE_Net_Delay_0_0_Plr_0) { false, false, true, ClipNameToClipPath("paris_qcif")}; paris_qcif.analyzer = {"net_delay_0_0_plr_0", 36.0, 0.96, kFullStackTestDurationSecs}; - fixture->RunWithAnalyzer(paris_qcif); + fixture.RunWithAnalyzer(paris_qcif); } TEST(GenericDescriptorTest, Foreman_Cif_Net_Delay_0_0_Plr_0_Generic_Descriptor) { - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture; // TODO(pbos): Decide on psnr/ssim thresholds for foreman_cif. ParamsWithLogging foreman_cif; foreman_cif.call.send_side_bwe = true; @@ -185,12 +167,12 @@ TEST(GenericDescriptorTest, foreman_cif.analyzer = {"foreman_cif_net_delay_0_0_plr_0_generic_descriptor", 0.0, 0.0, kFullStackTestDurationSecs}; foreman_cif.call.generic_descriptor = true; - fixture->RunWithAnalyzer(foreman_cif); + fixture.RunWithAnalyzer(foreman_cif); } TEST(GenericDescriptorTest, Foreman_Cif_30kbps_Net_Delay_0_0_Plr_0_Generic_Descriptor) { - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture; ParamsWithLogging foreman_cif; foreman_cif.call.send_side_bwe = true; foreman_cif.video[0] = { @@ -202,12 +184,12 @@ TEST(GenericDescriptorTest, "foreman_cif_30kbps_net_delay_0_0_plr_0_generic_descriptor", 0.0, 0.0, kFullStackTestDurationSecs}; foreman_cif.call.generic_descriptor = true; - fixture->RunWithAnalyzer(foreman_cif); + fixture.RunWithAnalyzer(foreman_cif); } // Link capacity below default start rate. TEST(FullStackTest, Foreman_Cif_Link_150kbps_Net_Delay_0_0_Plr_0) { - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture; ParamsWithLogging foreman_cif; foreman_cif.call.send_side_bwe = true; foreman_cif.video[0] = { @@ -218,13 +200,13 @@ TEST(FullStackTest, Foreman_Cif_Link_150kbps_Net_Delay_0_0_Plr_0) { foreman_cif.analyzer = {"foreman_cif_link_150kbps_net_delay_0_0_plr_0", 0.0, 0.0, kFullStackTestDurationSecs}; foreman_cif.config->link_capacity = DataRate::KilobitsPerSec(150); - fixture->RunWithAnalyzer(foreman_cif); + fixture.RunWithAnalyzer(foreman_cif); } // Restricted network and encoder overproducing by 30%. TEST(FullStackTest, Foreman_Cif_Link_150kbps_Delay100ms_30pkts_Queue_Overshoot30) { - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture; ParamsWithLogging foreman_cif; foreman_cif.call.send_side_bwe = true; foreman_cif.video[0] = { @@ -239,7 +221,7 @@ TEST(FullStackTest, foreman_cif.config->link_capacity = DataRate::KilobitsPerSec(150); foreman_cif.config->queue_length_packets = 30; foreman_cif.config->queue_delay_ms = 100; - fixture->RunWithAnalyzer(foreman_cif); + fixture.RunWithAnalyzer(foreman_cif); } // Weak 3G-style link: 250kbps, 1% loss, 100ms delay, 15 packets queue. @@ -247,7 +229,7 @@ TEST(FullStackTest, // This triggers protection overhead to toggle between zero and non-zero. // Link queue is restrictive enough to trigger loss on probes. TEST(FullStackTest, Foreman_Cif_Link_250kbps_Delay100ms_10pkts_Loss1) { - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture; ParamsWithLogging foreman_cif; foreman_cif.call.send_side_bwe = true; foreman_cif.video[0] = { @@ -262,11 +244,11 @@ TEST(FullStackTest, Foreman_Cif_Link_250kbps_Delay100ms_10pkts_Loss1) { foreman_cif.config->queue_length_packets = 10; foreman_cif.config->queue_delay_ms = 100; foreman_cif.config->loss_percent = 1; - fixture->RunWithAnalyzer(foreman_cif); + fixture.RunWithAnalyzer(foreman_cif); } TEST(GenericDescriptorTest, Foreman_Cif_Delay_50_0_Plr_5_Generic_Descriptor) { - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture; ParamsWithLogging foreman_cif; foreman_cif.call.send_side_bwe = true; foreman_cif.video[0] = { @@ -279,12 +261,12 @@ TEST(GenericDescriptorTest, Foreman_Cif_Delay_50_0_Plr_5_Generic_Descriptor) { foreman_cif.config->loss_percent = 5; foreman_cif.config->queue_delay_ms = 50; foreman_cif.call.generic_descriptor = true; - fixture->RunWithAnalyzer(foreman_cif); + fixture.RunWithAnalyzer(foreman_cif); } TEST(GenericDescriptorTest, Foreman_Cif_Delay_50_0_Plr_5_Ulpfec_Generic_Descriptor) { - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture; ParamsWithLogging foreman_cif; foreman_cif.call.send_side_bwe = true; foreman_cif.video[0] = { @@ -298,11 +280,11 @@ TEST(GenericDescriptorTest, foreman_cif.config->loss_percent = 5; foreman_cif.config->queue_delay_ms = 50; foreman_cif.call.generic_descriptor = true; - fixture->RunWithAnalyzer(foreman_cif); + fixture.RunWithAnalyzer(foreman_cif); } TEST(FullStackTest, Foreman_Cif_Delay_50_0_Plr_5_Flexfec) { - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture; ParamsWithLogging foreman_cif; foreman_cif.call.send_side_bwe = true; foreman_cif.video[0] = { @@ -314,11 +296,11 @@ TEST(FullStackTest, Foreman_Cif_Delay_50_0_Plr_5_Flexfec) { kFullStackTestDurationSecs}; foreman_cif.config->loss_percent = 5; foreman_cif.config->queue_delay_ms = 50; - fixture->RunWithAnalyzer(foreman_cif); + fixture.RunWithAnalyzer(foreman_cif); } TEST(FullStackTest, Foreman_Cif_500kbps_Delay_50_0_Plr_3_Flexfec) { - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture; ParamsWithLogging foreman_cif; foreman_cif.call.send_side_bwe = true; foreman_cif.video[0] = { @@ -331,11 +313,11 @@ TEST(FullStackTest, Foreman_Cif_500kbps_Delay_50_0_Plr_3_Flexfec) { foreman_cif.config->loss_percent = 3; foreman_cif.config->link_capacity = DataRate::KilobitsPerSec(500); foreman_cif.config->queue_delay_ms = 50; - fixture->RunWithAnalyzer(foreman_cif); + fixture.RunWithAnalyzer(foreman_cif); } TEST(FullStackTest, Foreman_Cif_500kbps_Delay_50_0_Plr_3_Ulpfec) { - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture; ParamsWithLogging foreman_cif; foreman_cif.call.send_side_bwe = true; foreman_cif.video[0] = { @@ -348,12 +330,12 @@ TEST(FullStackTest, Foreman_Cif_500kbps_Delay_50_0_Plr_3_Ulpfec) { foreman_cif.config->loss_percent = 3; foreman_cif.config->link_capacity = DataRate::KilobitsPerSec(500); foreman_cif.config->queue_delay_ms = 50; - fixture->RunWithAnalyzer(foreman_cif); + fixture.RunWithAnalyzer(foreman_cif); } #if defined(WEBRTC_USE_H264) TEST(FullStackTest, Foreman_Cif_Net_Delay_0_0_Plr_0_H264) { - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture; // TODO(pbos): Decide on psnr/ssim thresholds for foreman_cif. ParamsWithLogging foreman_cif; foreman_cif.call.send_side_bwe = true; @@ -364,11 +346,11 @@ TEST(FullStackTest, Foreman_Cif_Net_Delay_0_0_Plr_0_H264) { false, false, true, ClipNameToClipPath("foreman_cif")}; foreman_cif.analyzer = {"foreman_cif_net_delay_0_0_plr_0_H264", 0.0, 0.0, kFullStackTestDurationSecs}; - fixture->RunWithAnalyzer(foreman_cif); + fixture.RunWithAnalyzer(foreman_cif); } TEST(FullStackTest, Foreman_Cif_30kbps_Net_Delay_0_0_Plr_0_H264) { - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture; ParamsWithLogging foreman_cif; foreman_cif.call.send_side_bwe = true; foreman_cif.video[0] = { @@ -378,12 +360,12 @@ TEST(FullStackTest, Foreman_Cif_30kbps_Net_Delay_0_0_Plr_0_H264) { false, false, true, ClipNameToClipPath("foreman_cif")}; foreman_cif.analyzer = {"foreman_cif_30kbps_net_delay_0_0_plr_0_H264", 0.0, 0.0, kFullStackTestDurationSecs}; - fixture->RunWithAnalyzer(foreman_cif); + fixture.RunWithAnalyzer(foreman_cif); } TEST(GenericDescriptorTest, Foreman_Cif_Delay_50_0_Plr_5_H264_Generic_Descriptor) { - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture; ParamsWithLogging foreman_cif; foreman_cif.call.send_side_bwe = true; foreman_cif.video[0] = { @@ -397,13 +379,12 @@ TEST(GenericDescriptorTest, foreman_cif.config->loss_percent = 5; foreman_cif.config->queue_delay_ms = 50; foreman_cif.call.generic_descriptor = true; - fixture->RunWithAnalyzer(foreman_cif); + fixture.RunWithAnalyzer(foreman_cif); } TEST(FullStackTest, Foreman_Cif_Delay_50_0_Plr_5_H264_Sps_Pps_Idr) { - test::ScopedFieldTrials override_field_trials( - AppendFieldTrials("WebRTC-SpsPpsIdrIsH264Keyframe/Enabled/")); - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture( + {.field_trials = "WebRTC-SpsPpsIdrIsH264Keyframe/Enabled/"}); ParamsWithLogging foreman_cif; foreman_cif.call.send_side_bwe = true; @@ -416,12 +397,12 @@ TEST(FullStackTest, Foreman_Cif_Delay_50_0_Plr_5_H264_Sps_Pps_Idr) { 0.0, kFullStackTestDurationSecs}; foreman_cif.config->loss_percent = 5; foreman_cif.config->queue_delay_ms = 50; - fixture->RunWithAnalyzer(foreman_cif); + fixture.RunWithAnalyzer(foreman_cif); } // Verify that this is worth the bot time, before enabling. TEST(FullStackTest, Foreman_Cif_Delay_50_0_Plr_5_H264_Flexfec) { - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture; ParamsWithLogging foreman_cif; foreman_cif.call.send_side_bwe = true; foreman_cif.video[0] = { @@ -433,13 +414,13 @@ TEST(FullStackTest, Foreman_Cif_Delay_50_0_Plr_5_H264_Flexfec) { kFullStackTestDurationSecs}; foreman_cif.config->loss_percent = 5; foreman_cif.config->queue_delay_ms = 50; - fixture->RunWithAnalyzer(foreman_cif); + fixture.RunWithAnalyzer(foreman_cif); } // Ulpfec with H264 is an unsupported combination, so this test is only useful // for debugging. It is therefore disabled by default. TEST(FullStackTest, DISABLED_Foreman_Cif_Delay_50_0_Plr_5_H264_Ulpfec) { - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture; ParamsWithLogging foreman_cif; foreman_cif.call.send_side_bwe = true; foreman_cif.video[0] = { @@ -451,12 +432,12 @@ TEST(FullStackTest, DISABLED_Foreman_Cif_Delay_50_0_Plr_5_H264_Ulpfec) { kFullStackTestDurationSecs}; foreman_cif.config->loss_percent = 5; foreman_cif.config->queue_delay_ms = 50; - fixture->RunWithAnalyzer(foreman_cif); + fixture.RunWithAnalyzer(foreman_cif); } #endif // defined(WEBRTC_USE_H264) TEST(FullStackTest, Foreman_Cif_500kbps) { - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture; ParamsWithLogging foreman_cif; foreman_cif.call.send_side_bwe = true; foreman_cif.video[0] = { @@ -469,11 +450,11 @@ TEST(FullStackTest, Foreman_Cif_500kbps) { foreman_cif.config->queue_length_packets = 0; foreman_cif.config->queue_delay_ms = 0; foreman_cif.config->link_capacity = DataRate::KilobitsPerSec(500); - fixture->RunWithAnalyzer(foreman_cif); + fixture.RunWithAnalyzer(foreman_cif); } TEST(FullStackTest, Foreman_Cif_500kbps_32pkts_Queue) { - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture; ParamsWithLogging foreman_cif; foreman_cif.call.send_side_bwe = true; foreman_cif.video[0] = { @@ -486,11 +467,11 @@ TEST(FullStackTest, Foreman_Cif_500kbps_32pkts_Queue) { foreman_cif.config->queue_length_packets = 32; foreman_cif.config->queue_delay_ms = 0; foreman_cif.config->link_capacity = DataRate::KilobitsPerSec(500); - fixture->RunWithAnalyzer(foreman_cif); + fixture.RunWithAnalyzer(foreman_cif); } TEST(FullStackTest, Foreman_Cif_500kbps_100ms) { - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture; ParamsWithLogging foreman_cif; foreman_cif.call.send_side_bwe = true; foreman_cif.video[0] = { @@ -503,12 +484,12 @@ TEST(FullStackTest, Foreman_Cif_500kbps_100ms) { foreman_cif.config->queue_length_packets = 0; foreman_cif.config->queue_delay_ms = 100; foreman_cif.config->link_capacity = DataRate::KilobitsPerSec(500); - fixture->RunWithAnalyzer(foreman_cif); + fixture.RunWithAnalyzer(foreman_cif); } TEST(GenericDescriptorTest, Foreman_Cif_500kbps_100ms_32pkts_Queue_Generic_Descriptor) { - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture; ParamsWithLogging foreman_cif; foreman_cif.call.send_side_bwe = true; foreman_cif.video[0] = { @@ -523,11 +504,11 @@ TEST(GenericDescriptorTest, foreman_cif.config->queue_delay_ms = 100; foreman_cif.config->link_capacity = DataRate::KilobitsPerSec(500); foreman_cif.call.generic_descriptor = true; - fixture->RunWithAnalyzer(foreman_cif); + fixture.RunWithAnalyzer(foreman_cif); } TEST(FullStackTest, Foreman_Cif_500kbps_100ms_32pkts_Queue_Recv_Bwe) { - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture; ParamsWithLogging foreman_cif; foreman_cif.call.send_side_bwe = false; foreman_cif.video[0] = { @@ -540,11 +521,11 @@ TEST(FullStackTest, Foreman_Cif_500kbps_100ms_32pkts_Queue_Recv_Bwe) { foreman_cif.config->queue_length_packets = 32; foreman_cif.config->queue_delay_ms = 100; foreman_cif.config->link_capacity = DataRate::KilobitsPerSec(500); - fixture->RunWithAnalyzer(foreman_cif); + fixture.RunWithAnalyzer(foreman_cif); } TEST(FullStackTest, Foreman_Cif_1000kbps_100ms_32pkts_Queue) { - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture; ParamsWithLogging foreman_cif; foreman_cif.call.send_side_bwe = true; foreman_cif.video[0] = { @@ -557,12 +538,12 @@ TEST(FullStackTest, Foreman_Cif_1000kbps_100ms_32pkts_Queue) { foreman_cif.config->queue_length_packets = 32; foreman_cif.config->queue_delay_ms = 100; foreman_cif.config->link_capacity = DataRate::KilobitsPerSec(1000); - fixture->RunWithAnalyzer(foreman_cif); + fixture.RunWithAnalyzer(foreman_cif); } // TODO(sprang): Remove this if we have the similar ModerateLimits below? TEST(FullStackTest, Conference_Motion_Hd_2000kbps_100ms_32pkts_Queue) { - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture; ParamsWithLogging conf_motion_hd; conf_motion_hd.call.send_side_bwe = true; conf_motion_hd.video[0] = { @@ -579,12 +560,12 @@ TEST(FullStackTest, Conference_Motion_Hd_2000kbps_100ms_32pkts_Queue) { conf_motion_hd.config->queue_length_packets = 32; conf_motion_hd.config->queue_delay_ms = 100; conf_motion_hd.config->link_capacity = DataRate::KilobitsPerSec(2000); - fixture->RunWithAnalyzer(conf_motion_hd); + fixture.RunWithAnalyzer(conf_motion_hd); } TEST(GenericDescriptorTest, Conference_Motion_Hd_2tl_Moderate_Limits_Generic_Descriptor) { - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture; ParamsWithLogging conf_motion_hd; conf_motion_hd.call.send_side_bwe = true; conf_motion_hd.video[0] = { @@ -604,11 +585,11 @@ TEST(GenericDescriptorTest, conf_motion_hd.config->queue_delay_ms = 100; conf_motion_hd.config->link_capacity = DataRate::KilobitsPerSec(2000); conf_motion_hd.call.generic_descriptor = true; - fixture->RunWithAnalyzer(conf_motion_hd); + fixture.RunWithAnalyzer(conf_motion_hd); } TEST(FullStackTest, Conference_Motion_Hd_3tl_Moderate_Limits) { - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture; ParamsWithLogging conf_motion_hd; conf_motion_hd.call.send_side_bwe = true; conf_motion_hd.video[0] = { @@ -626,11 +607,11 @@ TEST(FullStackTest, Conference_Motion_Hd_3tl_Moderate_Limits) { conf_motion_hd.config->loss_percent = 3; conf_motion_hd.config->queue_delay_ms = 100; conf_motion_hd.config->link_capacity = DataRate::KilobitsPerSec(2000); - fixture->RunWithAnalyzer(conf_motion_hd); + fixture.RunWithAnalyzer(conf_motion_hd); } TEST(FullStackTest, Conference_Motion_Hd_4tl_Moderate_Limits) { - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture; ParamsWithLogging conf_motion_hd; conf_motion_hd.call.send_side_bwe = true; conf_motion_hd.video[0] = { @@ -648,11 +629,11 @@ TEST(FullStackTest, Conference_Motion_Hd_4tl_Moderate_Limits) { conf_motion_hd.config->loss_percent = 3; conf_motion_hd.config->queue_delay_ms = 100; conf_motion_hd.config->link_capacity = DataRate::KilobitsPerSec(2000); - fixture->RunWithAnalyzer(conf_motion_hd); + fixture.RunWithAnalyzer(conf_motion_hd); } TEST(FullStackTest, Foreman_Cif_30kbps_AV1) { - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture; ParamsWithLogging foreman_cif; foreman_cif.call.send_side_bwe = true; foreman_cif.video[0] = {.enabled = true, @@ -670,11 +651,11 @@ TEST(FullStackTest, Foreman_Cif_30kbps_AV1) { .test_durations_secs = kFullStackTestDurationSecs}; foreman_cif.config->link_capacity = DataRate::KilobitsPerSec(30); foreman_cif.call.generic_descriptor = true; - fixture->RunWithAnalyzer(foreman_cif); + fixture.RunWithAnalyzer(foreman_cif); } TEST(FullStackTest, Conference_Motion_Hd_3tl_AV1) { - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture; ParamsWithLogging conf_motion_hd; conf_motion_hd.call.send_side_bwe = true; conf_motion_hd.video[0] = { @@ -696,7 +677,7 @@ TEST(FullStackTest, Conference_Motion_Hd_3tl_AV1) { conf_motion_hd.config->queue_delay_ms = 100; conf_motion_hd.config->link_capacity = DataRate::KilobitsPerSec(1000); conf_motion_hd.call.generic_descriptor = true; - fixture->RunWithAnalyzer(conf_motion_hd); + fixture.RunWithAnalyzer(conf_motion_hd); } #if defined(WEBRTC_MAC) @@ -707,7 +688,7 @@ TEST(FullStackTest, Conference_Motion_Hd_3tl_AV1) { #define MAYBE_Screenshare_Slides_Simulcast_AV1 Screenshare_Slides_Simulcast_AV1 #endif TEST(FullStackTest, MAYBE_Screenshare_Slides_Simulcast_AV1) { - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture; ParamsWithLogging screenshare; screenshare.analyzer = {.test_label = "screenshare_slides_simulcast_AV1", .test_durations_secs = kFullStackTestDurationSecs}; @@ -754,12 +735,12 @@ TEST(FullStackTest, MAYBE_Screenshare_Slides_Simulcast_AV1) { .streams = streams, .selected_stream = 1, }; - fixture->RunWithAnalyzer(screenshare); + fixture.RunWithAnalyzer(screenshare); } #if defined(RTC_ENABLE_VP9) TEST(FullStackTest, Conference_Motion_Hd_2000kbps_100ms_32pkts_Queue_Vp9) { - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture; ParamsWithLogging conf_motion_hd; conf_motion_hd.call.send_side_bwe = true; conf_motion_hd.video[0] = { @@ -777,12 +758,12 @@ TEST(FullStackTest, Conference_Motion_Hd_2000kbps_100ms_32pkts_Queue_Vp9) { conf_motion_hd.config->queue_length_packets = 32; conf_motion_hd.config->queue_delay_ms = 100; conf_motion_hd.config->link_capacity = DataRate::KilobitsPerSec(2000); - fixture->RunWithAnalyzer(conf_motion_hd); + fixture.RunWithAnalyzer(conf_motion_hd); } #endif TEST(FullStackTest, Screenshare_Slides) { - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture; ParamsWithLogging screenshare; screenshare.call.send_side_bwe = true; screenshare.video[0] = {true, 1850, 1110, 5, 50000, 200000, @@ -791,13 +772,13 @@ TEST(FullStackTest, Screenshare_Slides) { screenshare.screenshare[0] = {true, false, 10}; screenshare.analyzer = {"screenshare_slides", 0.0, 0.0, kFullStackTestDurationSecs}; - fixture->RunWithAnalyzer(screenshare); + fixture.RunWithAnalyzer(screenshare); } #if !defined(WEBRTC_MAC) && !defined(WEBRTC_WIN) // TODO(bugs.webrtc.org/9840): Investigate why is this test flaky on Win/Mac. TEST(FullStackTest, Screenshare_Slides_Simulcast) { - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture; ParamsWithLogging screenshare; screenshare.call.send_side_bwe = true; screenshare.screenshare[0] = {true, false, 10}; @@ -821,13 +802,13 @@ TEST(FullStackTest, Screenshare_Slides_Simulcast) { screenshare.ss[0] = { streams, 1, 1, 0, InterLayerPredMode::kOn, std::vector(), false}; - fixture->RunWithAnalyzer(screenshare); + fixture.RunWithAnalyzer(screenshare); } #endif // !defined(WEBRTC_MAC) && !defined(WEBRTC_WIN) TEST(FullStackTest, Screenshare_Slides_Scrolling) { - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture; ParamsWithLogging config; config.call.send_side_bwe = true; config.video[0] = {true, 1850, 1110 / 2, 5, 50000, 200000, @@ -836,11 +817,11 @@ TEST(FullStackTest, Screenshare_Slides_Scrolling) { config.screenshare[0] = {true, false, 10, 2}; config.analyzer = {"screenshare_slides_scrolling", 0.0, 0.0, kFullStackTestDurationSecs}; - fixture->RunWithAnalyzer(config); + fixture.RunWithAnalyzer(config); } TEST(GenericDescriptorTest, Screenshare_Slides_Lossy_Net_Generic_Descriptor) { - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture; ParamsWithLogging screenshare; screenshare.call.send_side_bwe = true; screenshare.video[0] = {true, 1850, 1110, 5, 50000, 200000, @@ -853,11 +834,11 @@ TEST(GenericDescriptorTest, Screenshare_Slides_Lossy_Net_Generic_Descriptor) { screenshare.config->queue_delay_ms = 200; screenshare.config->link_capacity = DataRate::KilobitsPerSec(500); screenshare.call.generic_descriptor = true; - fixture->RunWithAnalyzer(screenshare); + fixture.RunWithAnalyzer(screenshare); } TEST(FullStackTest, Screenshare_Slides_Very_Lossy) { - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture; ParamsWithLogging screenshare; screenshare.call.send_side_bwe = true; screenshare.video[0] = {true, 1850, 1110, 5, 50000, 200000, @@ -869,11 +850,11 @@ TEST(FullStackTest, Screenshare_Slides_Very_Lossy) { screenshare.config->loss_percent = 10; screenshare.config->queue_delay_ms = 200; screenshare.config->link_capacity = DataRate::KilobitsPerSec(500); - fixture->RunWithAnalyzer(screenshare); + fixture.RunWithAnalyzer(screenshare); } TEST(FullStackTest, Screenshare_Slides_Lossy_Limited) { - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture; ParamsWithLogging screenshare; screenshare.call.send_side_bwe = true; screenshare.video[0] = {true, 1850, 1110, 5, 50000, 200000, @@ -886,11 +867,11 @@ TEST(FullStackTest, Screenshare_Slides_Lossy_Limited) { screenshare.config->link_capacity = DataRate::KilobitsPerSec(200); screenshare.config->queue_length_packets = 30; - fixture->RunWithAnalyzer(screenshare); + fixture.RunWithAnalyzer(screenshare); } TEST(FullStackTest, Screenshare_Slides_Moderately_Restricted) { - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture; ParamsWithLogging screenshare; screenshare.call.send_side_bwe = true; screenshare.video[0] = {true, 1850, 1110, 5, 50000, 200000, @@ -903,7 +884,7 @@ TEST(FullStackTest, Screenshare_Slides_Moderately_Restricted) { screenshare.config->link_capacity = DataRate::KilobitsPerSec(1200); screenshare.config->queue_length_packets = 30; - fixture->RunWithAnalyzer(screenshare); + fixture.RunWithAnalyzer(screenshare); } // Since ParamsWithLogging::Video is not trivially destructible, we can't @@ -959,7 +940,7 @@ ParamsWithLogging::Video SimulcastVp8VideoLow() { #if defined(RTC_ENABLE_VP9) TEST(FullStackTest, Screenshare_Slides_Vp9_3sl_High_Fps) { - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture; ParamsWithLogging screenshare; screenshare.call.send_side_bwe = true; screenshare.video[0] = {true, 1850, 1110, 30, 50000, 200000, @@ -971,16 +952,15 @@ TEST(FullStackTest, Screenshare_Slides_Vp9_3sl_High_Fps) { screenshare.ss[0] = { std::vector(), 0, 3, 2, InterLayerPredMode::kOn, std::vector(), true}; - fixture->RunWithAnalyzer(screenshare); + fixture.RunWithAnalyzer(screenshare); } // TODO(http://bugs.webrtc.org/9506): investigate. #if !defined(WEBRTC_MAC) TEST(FullStackTest, Vp9ksvc_3sl_High) { - test::ScopedFieldTrials override_trials( - AppendFieldTrials("WebRTC-Vp9IssueKeyFrameOnLayerDeactivation/Enabled/")); - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture( + {.field_trials = "WebRTC-Vp9IssueKeyFrameOnLayerDeactivation/Enabled/"}); ParamsWithLogging simulcast; simulcast.call.send_side_bwe = true; simulcast.video[0] = SvcVp9Video(); @@ -989,13 +969,12 @@ TEST(FullStackTest, Vp9ksvc_3sl_High) { simulcast.ss[0] = { std::vector(), 0, 3, 2, InterLayerPredMode::kOnKeyPic, std::vector(), false}; - fixture->RunWithAnalyzer(simulcast); + fixture.RunWithAnalyzer(simulcast); } TEST(FullStackTest, Vp9ksvc_3sl_Low) { - test::ScopedFieldTrials override_trials( - AppendFieldTrials("WebRTC-Vp9IssueKeyFrameOnLayerDeactivation/Enabled/")); - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture( + {.field_trials = "WebRTC-Vp9IssueKeyFrameOnLayerDeactivation/Enabled/"}); ParamsWithLogging simulcast; simulcast.call.send_side_bwe = true; simulcast.video[0] = SvcVp9Video(); @@ -1004,13 +983,12 @@ TEST(FullStackTest, Vp9ksvc_3sl_Low) { simulcast.ss[0] = { std::vector(), 0, 3, 0, InterLayerPredMode::kOnKeyPic, std::vector(), false}; - fixture->RunWithAnalyzer(simulcast); + fixture.RunWithAnalyzer(simulcast); } TEST(FullStackTest, Vp9ksvc_3sl_Low_Bw_Limited) { - test::ScopedFieldTrials override_trials( - AppendFieldTrials("WebRTC-Vp9IssueKeyFrameOnLayerDeactivation/Enabled/")); - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture( + {.field_trials = "WebRTC-Vp9IssueKeyFrameOnLayerDeactivation/Enabled/"}); ParamsWithLogging simulcast; simulcast.config->link_capacity = DataRate::KilobitsPerSec(500); simulcast.call.send_side_bwe = true; @@ -1020,13 +998,12 @@ TEST(FullStackTest, Vp9ksvc_3sl_Low_Bw_Limited) { simulcast.ss[0] = { std::vector(), 0, 3, 0, InterLayerPredMode::kOnKeyPic, std::vector(), false}; - fixture->RunWithAnalyzer(simulcast); + fixture.RunWithAnalyzer(simulcast); } TEST(FullStackTest, Vp9ksvc_3sl_Medium_Network_Restricted) { - test::ScopedFieldTrials override_trials( - AppendFieldTrials("WebRTC-Vp9IssueKeyFrameOnLayerDeactivation/Enabled/")); - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture( + {.field_trials = "WebRTC-Vp9IssueKeyFrameOnLayerDeactivation/Enabled/"}); ParamsWithLogging simulcast; simulcast.call.send_side_bwe = true; simulcast.video[0] = SvcVp9Video(); @@ -1037,14 +1014,13 @@ TEST(FullStackTest, Vp9ksvc_3sl_Medium_Network_Restricted) { std::vector(), false}; simulcast.config->link_capacity = DataRate::KilobitsPerSec(1000); simulcast.config->queue_delay_ms = 100; - fixture->RunWithAnalyzer(simulcast); + fixture.RunWithAnalyzer(simulcast); } // TODO(webrtc:9722): Remove when experiment is cleaned up. TEST(FullStackTest, Vp9ksvc_3sl_Medium_Network_Restricted_Trusted_Rate) { - test::ScopedFieldTrials override_trials( - AppendFieldTrials("WebRTC-Vp9IssueKeyFrameOnLayerDeactivation/Enabled/")); - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture( + {.field_trials = "WebRTC-Vp9IssueKeyFrameOnLayerDeactivation/Enabled/"}); ParamsWithLogging simulcast; simulcast.call.send_side_bwe = true; simulcast.video[0] = SvcVp9Video(); @@ -1055,7 +1031,7 @@ TEST(FullStackTest, Vp9ksvc_3sl_Medium_Network_Restricted_Trusted_Rate) { std::vector(), false}; simulcast.config->link_capacity = DataRate::KilobitsPerSec(1000); simulcast.config->queue_delay_ms = 100; - fixture->RunWithAnalyzer(simulcast); + fixture.RunWithAnalyzer(simulcast); } #endif // !defined(WEBRTC_MAC) @@ -1070,7 +1046,9 @@ TEST(FullStackTest, Vp9ksvc_3sl_Medium_Network_Restricted_Trusted_Rate) { #endif TEST(FullStackTest, MAYBE_Simulcast_HD_High) { - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture( + {.field_trials = + "WebRTC-ForceSimulatedOveruseIntervalMs/1000-50000-300/"}); ParamsWithLogging simulcast; simulcast.call.send_side_bwe = true; simulcast.video[0] = {true, 1920, 1080, 30, 800000, 2500000, @@ -1087,13 +1065,11 @@ TEST(FullStackTest, MAYBE_Simulcast_HD_High) { simulcast.ss[0] = { streams, 2, 1, 0, InterLayerPredMode::kOn, std::vector(), true}; - test::ScopedFieldTrials override_trials(AppendFieldTrials( - "WebRTC-ForceSimulatedOveruseIntervalMs/1000-50000-300/")); - fixture->RunWithAnalyzer(simulcast); + fixture.RunWithAnalyzer(simulcast); } TEST(FullStackTest, Simulcast_Vp8_3sl_High) { - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture; ParamsWithLogging simulcast; simulcast.call.send_side_bwe = true; simulcast.video[0] = SimulcastVp8VideoHigh(); @@ -1115,11 +1091,11 @@ TEST(FullStackTest, Simulcast_Vp8_3sl_High) { simulcast.ss[0] = { streams, 2, 1, 0, InterLayerPredMode::kOn, std::vector(), false}; - fixture->RunWithAnalyzer(simulcast); + fixture.RunWithAnalyzer(simulcast); } TEST(FullStackTest, Simulcast_Vp8_3sl_Low) { - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture; ParamsWithLogging simulcast; simulcast.call.send_side_bwe = true; simulcast.video[0] = SimulcastVp8VideoHigh(); @@ -1141,7 +1117,7 @@ TEST(FullStackTest, Simulcast_Vp8_3sl_Low) { simulcast.ss[0] = { streams, 0, 1, 0, InterLayerPredMode::kOn, std::vector(), false}; - fixture->RunWithAnalyzer(simulcast); + fixture.RunWithAnalyzer(simulcast); } // This test assumes ideal network conditions with target bandwidth being @@ -1153,7 +1129,7 @@ TEST(FullStackTest, Simulcast_Vp8_3sl_Low) { #define MAYBE_High_Bitrate_With_Fake_Codec High_Bitrate_With_Fake_Codec #endif // defined(WEBRTC_ANDROID) TEST(FullStackTest, MAYBE_High_Bitrate_With_Fake_Codec) { - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture; const int target_bitrate = 100000000; ParamsWithLogging generator; generator.call.send_side_bwe = true; @@ -1178,7 +1154,7 @@ TEST(FullStackTest, MAYBE_High_Bitrate_With_Fake_Codec) { "Generator"}; generator.analyzer = {"high_bitrate_with_fake_codec", 0.0, 0.0, kFullStackTestDurationSecs}; - fixture->RunWithAnalyzer(generator); + fixture.RunWithAnalyzer(generator); } #if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS) @@ -1190,7 +1166,7 @@ TEST(FullStackTest, MAYBE_High_Bitrate_With_Fake_Codec) { #endif TEST(FullStackTest, MAYBE_Largeroom_50thumb) { - auto fixture = CreateVideoQualityTestFixture(); + VideoQualityTest fixture; ParamsWithLogging large_room; large_room.call.send_side_bwe = true; large_room.video[0] = SimulcastVp8VideoHigh(); @@ -1213,7 +1189,7 @@ TEST(FullStackTest, MAYBE_Largeroom_50thumb) { large_room.ss[0] = { streams, 2, 1, 0, InterLayerPredMode::kOn, std::vector(), false}; - fixture->RunWithAnalyzer(large_room); + fixture.RunWithAnalyzer(large_room); } } // namespace webrtc diff --git a/video/pc_full_stack_tests.cc b/video/pc_full_stack_tests.cc index f0c4c0ebf7..1d039d702c 100644 --- a/video/pc_full_stack_tests.cc +++ b/video/pc_full_stack_tests.cc @@ -12,6 +12,7 @@ #include #include +#include "api/field_trials.h" #include "api/function_view.h" #include "api/media_stream_interface.h" #include "api/test/create_network_emulation_manager.h" @@ -31,14 +32,14 @@ #include "api/units/time_delta.h" #include "api/video_codecs/vp9_profile.h" #include "media/base/media_constants.h" -#include "system_wrappers/include/field_trial.h" -#include "test/field_trial.h" #include "test/gtest.h" #include "test/pc/e2e/network_quality_metrics_reporter.h" #include "test/testsupport/file_utils.h" namespace webrtc { +namespace { +using ::testing::TestWithParam; using webrtc_pc_e2e::AudioConfig; using webrtc_pc_e2e::EmulatedSFUConfig; using webrtc_pc_e2e::PeerConfigurer; @@ -48,8 +49,6 @@ using webrtc_pc_e2e::VideoCodecConfig; using webrtc_pc_e2e::VideoConfig; using webrtc_pc_e2e::VideoSimulcastConfig; -namespace { - constexpr int kTestDurationSec = 45; std::unique_ptr @@ -75,11 +74,6 @@ CreateTestFixture(const std::string& test_case_name, return fixture; } -// Takes the current active field trials set, and appends some new trials. -std::string AppendFieldTrials(std::string new_trial_string) { - return std::string(field_trial::GetFieldTrialString()) + new_trial_string; -} - std::string ClipNameToClipPath(const char* clip_name) { return test::ResourcePath(clip_name, "yuv"); } @@ -88,29 +82,20 @@ std::string ClipNameToClipPath(const char* clip_name) { struct PCFullStackTestParams { bool use_network_thread_as_worker_thread = false; - std::string field_trials; std::string test_case_name_postfix; }; std::vector ParameterizedTestParams() { - return {// Run with default parameters and field trials. + return {// Run with default parameters. {}, // Use the network thread as worker thread. // Use the worker thread for sending packets. // https://bugs.chromium.org/p/webrtc/issues/detail?id=14502 {.use_network_thread_as_worker_thread = true, - .field_trials = "", .test_case_name_postfix = "_ReducedThreads"}}; } -class ParameterizedPCFullStackTest - : public ::testing::TestWithParam { - public: - ParameterizedPCFullStackTest() : field_trials_(GetParam().field_trials) {} - - private: - test::ScopedFieldTrials field_trials_; -}; +using ParameterizedPCFullStackTest = TestWithParam; INSTANTIATE_TEST_SUITE_P( ParameterizedPCFullStackTest, @@ -470,7 +455,6 @@ TEST(PCFullStackTest, Pc_Foreman_Cif_Delay_50_0_Plr_5_Flexfec) { }, [](PeerConfigurer* bob) { bob->SetUseFlexFEC(true); }); RunParams run_params(TimeDelta::Seconds(kTestDurationSec)); - run_params.enable_flex_fec_support = true; fixture->Run(std::move(run_params)); } @@ -495,7 +479,6 @@ TEST(PCFullStackTest, Pc_Foreman_Cif_500kbps_Delay_50_0_Plr_3_Flexfec) { }, [](PeerConfigurer* bob) { bob->SetUseFlexFEC(true); }); RunParams run_params(TimeDelta::Seconds(kTestDurationSec)); - run_params.enable_flex_fec_support = true; fixture->Run(std::move(run_params)); } @@ -537,10 +520,10 @@ TEST(PCFullStackTest, Pc_Foreman_Cif_Net_Delay_0_0_Plr_0_H264) { auto frame_generator = CreateFromYuvFileFrameGenerator( video, ClipNameToClipPath("foreman_cif")); alice->AddVideoConfig(std::move(video), std::move(frame_generator)); - alice->SetVideoCodecs({VideoCodecConfig(webrtc::kH264CodecName)}); + alice->SetVideoCodecs({VideoCodecConfig(kH264CodecName)}); }, [](PeerConfigurer* bob) { - bob->SetVideoCodecs({VideoCodecConfig(webrtc::kH264CodecName)}); + bob->SetVideoCodecs({VideoCodecConfig(kH264CodecName)}); }); fixture->Run(RunParams(TimeDelta::Seconds(kTestDurationSec))); } @@ -565,10 +548,10 @@ TEST(PCFullStackTest, Pc_Foreman_Cif_30kbps_Net_Delay_0_0_Plr_0_H264) { bitrate_settings.start_bitrate_bps = 30000; bitrate_settings.max_bitrate_bps = 30000; alice->SetBitrateSettings(bitrate_settings); - alice->SetVideoCodecs({VideoCodecConfig(webrtc::kH264CodecName)}); + alice->SetVideoCodecs({VideoCodecConfig(kH264CodecName)}); }, [](PeerConfigurer* bob) { - bob->SetVideoCodecs({VideoCodecConfig(webrtc::kH264CodecName)}); + bob->SetVideoCodecs({VideoCodecConfig(kH264CodecName)}); }); fixture->Run(RunParams(TimeDelta::Seconds(kTestDurationSec))); } @@ -590,18 +573,15 @@ TEST(PCGenericDescriptorTest, auto frame_generator = CreateFromYuvFileFrameGenerator( video, ClipNameToClipPath("foreman_cif")); alice->AddVideoConfig(std::move(video), std::move(frame_generator)); - alice->SetVideoCodecs({VideoCodecConfig(webrtc::kH264CodecName)}); + alice->SetVideoCodecs({VideoCodecConfig(kH264CodecName)}); }, [](PeerConfigurer* bob) { - bob->SetVideoCodecs({VideoCodecConfig(webrtc::kH264CodecName)}); + bob->SetVideoCodecs({VideoCodecConfig(kH264CodecName)}); }); fixture->Run(RunParams(TimeDelta::Seconds(kTestDurationSec))); } TEST(PCFullStackTest, Pc_Foreman_Cif_Delay_50_0_Plr_5_H264_Sps_Pps_Idr) { - test::ScopedFieldTrials override_field_trials( - AppendFieldTrials("WebRTC-SpsPpsIdrIsH264Keyframe/Enabled/")); - std::unique_ptr network_emulation_manager = CreateNetworkEmulationManager(); BuiltInNetworkBehaviorConfig config; @@ -617,10 +597,12 @@ TEST(PCFullStackTest, Pc_Foreman_Cif_Delay_50_0_Plr_5_H264_Sps_Pps_Idr) { auto frame_generator = CreateFromYuvFileFrameGenerator( video, ClipNameToClipPath("foreman_cif")); alice->AddVideoConfig(std::move(video), std::move(frame_generator)); - alice->SetVideoCodecs({VideoCodecConfig(webrtc::kH264CodecName)}); + alice->SetVideoCodecs({VideoCodecConfig(kH264CodecName)}); }, [](PeerConfigurer* bob) { - bob->SetVideoCodecs({VideoCodecConfig(webrtc::kH264CodecName)}); + bob->AddFieldTrials( + FieldTrials("WebRTC-SpsPpsIdrIsH264Keyframe/Enabled/")); + bob->SetVideoCodecs({VideoCodecConfig(kH264CodecName)}); }); fixture->Run(RunParams(TimeDelta::Seconds(kTestDurationSec))); } @@ -641,15 +623,14 @@ TEST(PCFullStackTest, Pc_Foreman_Cif_Delay_50_0_Plr_5_H264_Flexfec) { auto frame_generator = CreateFromYuvFileFrameGenerator( video, ClipNameToClipPath("foreman_cif")); alice->AddVideoConfig(std::move(video), std::move(frame_generator)); - alice->SetVideoCodecs({VideoCodecConfig(webrtc::kH264CodecName)}); + alice->SetVideoCodecs({VideoCodecConfig(kH264CodecName)}); alice->SetUseFlexFEC(true); }, [](PeerConfigurer* bob) { - bob->SetVideoCodecs({VideoCodecConfig(webrtc::kH264CodecName)}); + bob->SetVideoCodecs({VideoCodecConfig(kH264CodecName)}); bob->SetUseFlexFEC(true); }); RunParams run_params(TimeDelta::Seconds(kTestDurationSec)); - run_params.enable_flex_fec_support = true; fixture->Run(std::move(run_params)); } @@ -671,11 +652,11 @@ TEST(PCFullStackTest, DISABLED_Pc_Foreman_Cif_Delay_50_0_Plr_5_H264_Ulpfec) { auto frame_generator = CreateFromYuvFileFrameGenerator( video, ClipNameToClipPath("foreman_cif")); alice->AddVideoConfig(std::move(video), std::move(frame_generator)); - alice->SetVideoCodecs({VideoCodecConfig(webrtc::kH264CodecName)}); + alice->SetVideoCodecs({VideoCodecConfig(kH264CodecName)}); alice->SetUseUlpFEC(true); }, [](PeerConfigurer* bob) { - bob->SetVideoCodecs({VideoCodecConfig(webrtc::kH264CodecName)}); + bob->SetVideoCodecs({VideoCodecConfig(kH264CodecName)}); bob->SetUseUlpFEC(true); }); fixture->Run(RunParams(TimeDelta::Seconds(kTestDurationSec))); @@ -1235,9 +1216,6 @@ ParamsWithLogging::Video SimulcastVp8VideoLow() { #if defined(RTC_ENABLE_VP9) TEST(PCFullStackTest, Pc_Screenshare_Slides_Vp9_3sl_High_Fps) { - test::ScopedFieldTrials override_trials( - AppendFieldTrials("WebRTC-Vp9InterLayerPred/" - "Enabled,inter_layer_pred_mode:on/")); std::unique_ptr network_emulation_manager = CreateNetworkEmulationManager(); auto fixture = CreateTestFixture( @@ -1246,6 +1224,8 @@ TEST(PCFullStackTest, Pc_Screenshare_Slides_Vp9_3sl_High_Fps) { network_emulation_manager->CreateEndpointPairWithTwoWayRoutes( BuiltInNetworkBehaviorConfig()), [](PeerConfigurer* alice) { + alice->AddFieldTrials(FieldTrials( + "WebRTC-Vp9InterLayerPred/Enabled,inter_layer_pred_mode:on/")); VideoConfig video(1850, 1110, 30); video.stream_label = "alice-video"; video.simulcast_config = VideoSimulcastConfig(3); @@ -1269,9 +1249,6 @@ TEST(PCFullStackTest, Pc_Screenshare_Slides_Vp9_3sl_High_Fps) { } TEST(PCFullStackTest, Pc_Vp9svc_3sl_High) { - test::ScopedFieldTrials override_trials( - AppendFieldTrials("WebRTC-Vp9InterLayerPred/" - "Enabled,inter_layer_pred_mode:on/")); std::unique_ptr network_emulation_manager = CreateNetworkEmulationManager(); auto fixture = CreateTestFixture( @@ -1279,6 +1256,8 @@ TEST(PCFullStackTest, Pc_Vp9svc_3sl_High) { network_emulation_manager->CreateEndpointPairWithTwoWayRoutes( BuiltInNetworkBehaviorConfig()), [](PeerConfigurer* alice) { + alice->AddFieldTrials(FieldTrials( + "WebRTC-Vp9InterLayerPred/Enabled,inter_layer_pred_mode:on/")); VideoConfig video(1280, 720, 30); video.stream_label = "alice-video"; video.simulcast_config = VideoSimulcastConfig(3); @@ -1302,9 +1281,6 @@ TEST(PCFullStackTest, Pc_Vp9svc_3sl_High) { } TEST(PCFullStackTest, Pc_Vp9svc_3sl_Low) { - test::ScopedFieldTrials override_trials( - AppendFieldTrials("WebRTC-Vp9InterLayerPred/" - "Enabled,inter_layer_pred_mode:on/")); std::unique_ptr network_emulation_manager = CreateNetworkEmulationManager(); auto fixture = CreateTestFixture( @@ -1312,6 +1288,8 @@ TEST(PCFullStackTest, Pc_Vp9svc_3sl_Low) { network_emulation_manager->CreateEndpointPairWithTwoWayRoutes( BuiltInNetworkBehaviorConfig()), [](PeerConfigurer* alice) { + alice->AddFieldTrials(FieldTrials( + "WebRTC-Vp9InterLayerPred/Enabled,inter_layer_pred_mode:on/")); VideoConfig video(1280, 720, 30); video.stream_label = "alice-video"; video.simulcast_config = VideoSimulcastConfig(3); @@ -1342,7 +1320,7 @@ TEST(PCFullStackTest, Pc_Vp9svc_3sl_Low) { // TODO(bugs.webrtc.org/10639) requires simulcast/SVC support in PC framework TEST(PCFullStackTest, VP9KSVC_3SL_High) { - webrtc::test::ScopedFieldTrials override_trials( + test::ScopedFieldTrials override_trials( AppendFieldTrials("WebRTC-Vp9IssueKeyFrameOnLayerDeactivation/Enabled/")); auto fixture = CreateVideoQualityTestFixture(); ParamsWithLogging simulcast; @@ -1357,7 +1335,7 @@ TEST(PCFullStackTest, VP9KSVC_3SL_High) { // TODO(bugs.webrtc.org/10639) requires simulcast/SVC support in PC framework TEST(PCFullStackTest, VP9KSVC_3SL_Medium) { - webrtc::test::ScopedFieldTrials override_trials( + test::ScopedFieldTrials override_trials( AppendFieldTrials("WebRTC-Vp9IssueKeyFrameOnLayerDeactivation/Enabled/")); auto fixture = CreateVideoQualityTestFixture(); ParamsWithLogging simulcast; @@ -1372,7 +1350,7 @@ TEST(PCFullStackTest, VP9KSVC_3SL_Medium) { // TODO(bugs.webrtc.org/10639) requires simulcast/SVC support in PC framework TEST(PCFullStackTest, VP9KSVC_3SL_Low) { - webrtc::test::ScopedFieldTrials override_trials( + test::ScopedFieldTrials override_trials( AppendFieldTrials("WebRTC-Vp9IssueKeyFrameOnLayerDeactivation/Enabled/")); auto fixture = CreateVideoQualityTestFixture(); ParamsWithLogging simulcast; @@ -1387,7 +1365,7 @@ TEST(PCFullStackTest, VP9KSVC_3SL_Low) { // TODO(bugs.webrtc.org/10639) requires simulcast/SVC support in PC framework TEST(PCFullStackTest, VP9KSVC_3SL_Medium_Network_Restricted) { - webrtc::test::ScopedFieldTrials override_trials( + test::ScopedFieldTrials override_trials( AppendFieldTrials("WebRTC-Vp9IssueKeyFrameOnLayerDeactivation/Enabled/")); auto fixture = CreateVideoQualityTestFixture(); ParamsWithLogging simulcast; @@ -1406,7 +1384,7 @@ TEST(PCFullStackTest, VP9KSVC_3SL_Medium_Network_Restricted) { // TODO(bugs.webrtc.org/10639) requires simulcast/SVC support in PC framework // TODO(webrtc:9722): Remove when experiment is cleaned up. TEST(PCFullStackTest, VP9KSVC_3SL_Medium_Network_Restricted_Trusted_Rate) { - webrtc::test::ScopedFieldTrials override_trials( + test::ScopedFieldTrials override_trials( AppendFieldTrials("WebRTC-Vp9IssueKeyFrameOnLayerDeactivation/Enabled/")); auto fixture = CreateVideoQualityTestFixture(); ParamsWithLogging simulcast; @@ -1434,8 +1412,6 @@ TEST(PCFullStackTest, VP9KSVC_3SL_Medium_Network_Restricted_Trusted_Rate) { #define MAYBE_Pc_Simulcast_HD_High Pc_Simulcast_HD_High #endif TEST(PCFullStackTest, MAYBE_Pc_Simulcast_HD_High) { - test::ScopedFieldTrials override_trials(AppendFieldTrials( - "WebRTC-ForceSimulatedOveruseIntervalMs/1000-50000-300/")); std::unique_ptr network_emulation_manager = CreateNetworkEmulationManager(); BuiltInNetworkBehaviorConfig config; @@ -1445,6 +1421,8 @@ TEST(PCFullStackTest, MAYBE_Pc_Simulcast_HD_High) { "pc_simulcast_HD_high", *network_emulation_manager->time_controller(), network_emulation_manager->CreateEndpointPairWithTwoWayRoutes(config), [](PeerConfigurer* alice) { + alice->AddFieldTrials(FieldTrials( + "WebRTC-ForceSimulatedOveruseIntervalMs/1000-50000-300/")); VideoConfig video(1920, 1080, 30); video.simulcast_config = VideoSimulcastConfig(3); video.emulated_sfu_config = EmulatedSFUConfig(2); diff --git a/video/picture_id_tests.cc b/video/picture_id_tests.cc index 4e76e5d676..0c6ab9201d 100644 --- a/video/picture_id_tests.cc +++ b/video/picture_id_tests.cc @@ -240,7 +240,7 @@ class PictureIdTest : public test::CallTest, public: PictureIdTest() : num_temporal_layers_(GetParam()) {} - virtual ~PictureIdTest() { + ~PictureIdTest() override { SendTask(task_queue(), [this]() { send_transport_.reset(); receive_transport_.reset(); diff --git a/video/rtp_video_stream_receiver2.cc b/video/rtp_video_stream_receiver2.cc index 2fccb605cb..66d213592d 100644 --- a/video/rtp_video_stream_receiver2.cc +++ b/video/rtp_video_stream_receiver2.cc @@ -185,7 +185,7 @@ std::unique_ptr MaybeConstructUlpfecReceiver( callback, clock); } -static const int kPacketLogIntervalMs = 10000; +const int kPacketLogIntervalMs = 10000; } // namespace diff --git a/video/rtp_video_stream_receiver2.h b/video/rtp_video_stream_receiver2.h index bb0e8a42eb..c4a3c7a68a 100644 --- a/video/rtp_video_stream_receiver2.h +++ b/video/rtp_video_stream_receiver2.h @@ -119,7 +119,7 @@ class RtpVideoStreamReceiver2 : public LossNotificationSender, void AddReceiveCodec(uint8_t payload_type, VideoCodecType video_codec, - const webrtc::CodecParameterMap& codec_params, + const CodecParameterMap& codec_params, bool raw_payload); // Clears state for all receive codecs added via `AddReceiveCodec`. @@ -430,11 +430,11 @@ class RtpVideoStreamReceiver2 : public LossNotificationSender, // TODO(johan): Remove pt_codec_params_ once // https://bugs.chromium.org/p/webrtc/issues/detail?id=6883 is resolved. // Maps a payload type to a map of out-of-band supplied codec parameters. - std::map pt_codec_params_ + std::map pt_codec_params_ RTC_GUARDED_BY(packet_sequence_checker_); // Maps payload type to the VideoCodecType. - std::map pt_codec_ + std::map pt_codec_ RTC_GUARDED_BY(packet_sequence_checker_); int16_t last_payload_type_ RTC_GUARDED_BY(packet_sequence_checker_) = -1; diff --git a/video/screenshare_loopback.cc b/video/screenshare_loopback.cc index a0bf6e9cf5..cc78ee98ee 100644 --- a/video/screenshare_loopback.cc +++ b/video/screenshare_loopback.cc @@ -10,7 +10,6 @@ #include -#include #include #include #include @@ -367,7 +366,7 @@ void Loopback() { SL_descriptors.push_back(SL0()); SL_descriptors.push_back(SL1()); - VideoQualityTest fixture(nullptr); + VideoQualityTest fixture; fixture.FillScalabilitySettings( ¶ms, 0, stream_descriptors, NumStreams(), SelectedStream(), NumSpatialLayers(), SelectedSL(), InterLayerPred(), SL_descriptors); diff --git a/video/send_delay_stats_unittest.cc b/video/send_delay_stats_unittest.cc index c564562e54..5bd0d98262 100644 --- a/video/send_delay_stats_unittest.cc +++ b/video/send_delay_stats_unittest.cc @@ -37,10 +37,10 @@ const int kProcessIntervalMs = 2000; class SendDelayStatsTest : public ::testing::Test { public: SendDelayStatsTest() : clock_(1234), config_(CreateConfig()) {} - virtual ~SendDelayStatsTest() {} + ~SendDelayStatsTest() override {} protected: - virtual void SetUp() { + void SetUp() override { stats_.reset(new SendDelayStats(&clock_)); stats_->AddSsrcs(config_); } diff --git a/video/send_statistics_proxy_unittest.cc b/video/send_statistics_proxy_unittest.cc index c41a9cdec4..07ef0fe36f 100644 --- a/video/send_statistics_proxy_unittest.cc +++ b/video/send_statistics_proxy_unittest.cc @@ -87,10 +87,10 @@ class SendStatisticsProxyTest : public ::testing::Test { : override_field_trials_(field_trials), fake_clock_(Timestamp::Seconds(1234)), config_(GetTestConfig()) {} - virtual ~SendStatisticsProxyTest() {} + ~SendStatisticsProxyTest() override {} protected: - virtual void SetUp() { + void SetUp() override { metrics::Reset(); statistics_proxy_.reset( new SendStatisticsProxy(&fake_clock_, GetTestConfig(), @@ -471,10 +471,10 @@ TEST_F(SendStatisticsProxyTest, // SendStatisticsProxy uses a RateTracker internally. SendStatisticsProxy uses // `fake_clock_` for testing, but the RateTracker relies on a global clock. - // This test relies on webrtc::ScopedFakeClock to synchronize these two + // This test relies on ScopedFakeClock to synchronize these two // clocks. // TODO(https://crbug.com/webrtc/10640): When the RateTracker uses a Clock - // this test can stop relying on webrtc::ScopedFakeClock. + // this test can stop relying on ScopedFakeClock. ScopedFakeClock fake_global_clock; fake_global_clock.SetTime( Timestamp::Millis(fake_clock_.TimeInMilliseconds())); diff --git a/video/sv_loopback.cc b/video/sv_loopback.cc index 4e9e3c0a91..8f0f4572f5 100644 --- a/video/sv_loopback.cc +++ b/video/sv_loopback.cc @@ -10,7 +10,6 @@ #include -#include #include #include #include @@ -666,7 +665,7 @@ void Loopback() { params.ss[screenshare_idx].infer_streams = true; } - VideoQualityTest fixture(nullptr); + VideoQualityTest fixture; std::vector stream_descriptors; stream_descriptors.push_back(ScreenshareStream0()); diff --git a/video/test/mock_video_stream_encoder.h b/video/test/mock_video_stream_encoder.h index 13a6b8fa80..adacbe2d0d 100644 --- a/video/test/mock_video_stream_encoder.h +++ b/video/test/mock_video_stream_encoder.h @@ -34,7 +34,7 @@ class MockVideoStreamEncoder : public VideoStreamEncoderInterface { public: MOCK_METHOD(void, AddAdaptationResource, - (webrtc::scoped_refptr), + (scoped_refptr), (override)); MOCK_METHOD(std::vector>, GetAdaptationResources, @@ -42,8 +42,7 @@ class MockVideoStreamEncoder : public VideoStreamEncoderInterface { (override)); MOCK_METHOD(void, SetSource, - (webrtc::VideoSourceInterface*, - const DegradationPreference&), + (VideoSourceInterface*, const DegradationPreference&), (override)); MOCK_METHOD(void, SetSink, (EncoderSink*, bool), (override)); MOCK_METHOD(void, SetStartBitrate, (int), (override)); @@ -57,7 +56,7 @@ class MockVideoStreamEncoder : public VideoStreamEncoderInterface { (override)); MOCK_METHOD(void, OnBitrateUpdated, - (DataRate, DataRate, DataRate, uint8_t, int64_t, double), + (DataRate, DataRate, uint8_t, int64_t, double), (override)); MOCK_METHOD(void, SetFecControllerOverride, diff --git a/video/video_analyzer.h b/video/video_analyzer.h index 8ccd353fc0..6dca47205e 100644 --- a/video/video_analyzer.h +++ b/video/video_analyzer.h @@ -227,14 +227,14 @@ class VideoAnalyzer : public PacketReceiver, RTC_LOCKS_EXCLUDED(comparison_lock_); void PrintResult(absl::string_view result_type, const SamplesStatsCounter& stats, - webrtc::test::Unit unit, - webrtc::test::ImprovementDirection improvement_direction); + test::Unit unit, + test::ImprovementDirection improvement_direction); void PrintResultWithExternalMean( absl::string_view result_type, double mean, const SamplesStatsCounter& stats, - webrtc::test::Unit unit, - webrtc::test::ImprovementDirection improvement_direction); + test::Unit unit, + test::ImprovementDirection improvement_direction); void PrintSamplesToFile(void) RTC_LOCKS_EXCLUDED(comparison_lock_); void AddCapturedFrameForComparison(const VideoFrame& video_frame) RTC_LOCKS_EXCLUDED(lock_, comparison_lock_); diff --git a/video/video_loopback.cc b/video/video_loopback.cc index f2ab82509a..bee8b0c1d7 100644 --- a/video/video_loopback.cc +++ b/video/video_loopback.cc @@ -11,7 +11,6 @@ #include -#include #include #include #include @@ -421,7 +420,7 @@ void Loopback() { SL_descriptors.push_back(SL1()); SL_descriptors.push_back(SL2()); - VideoQualityTest fixture(nullptr); + VideoQualityTest fixture; fixture.FillScalabilitySettings( ¶ms, 0, stream_descriptors, NumStreams(), SelectedStream(), NumSpatialLayers(), SelectedSL(), InterLayerPred(), SL_descriptors); diff --git a/video/video_quality_test.cc b/video/video_quality_test.cc index d4e1754f04..9386e7387c 100644 --- a/video/video_quality_test.cc +++ b/video/video_quality_test.cc @@ -20,7 +20,6 @@ #include "api/audio/create_audio_device_module.h" #include "api/call/transport.h" #include "api/environment/environment.h" -#include "api/environment/environment_factory.h" #include "api/field_trials_view.h" #include "api/make_ref_counted.h" #include "api/rtc_event_log/rtc_event_log.h" @@ -52,6 +51,7 @@ #include "rtc_base/logging.h" #include "rtc_base/numerics/safe_conversions.h" #include "rtc_base/system/file_wrapper.h" +#include "test/call_test.h" #include "test/direct_transport.h" #include "test/frame_generator_capturer.h" #include "test/gtest.h" @@ -186,7 +186,7 @@ class QualityTestVideoEncoder : public VideoEncoder, // Implement VideoEncoder void SetFecControllerOverride( - FecControllerOverride* fec_controller_override) { + FecControllerOverride* fec_controller_override) override { // Ignored. } @@ -205,7 +205,7 @@ class QualityTestVideoEncoder : public VideoEncoder, int32_t Release() override { return encoder_->Release(); } int32_t Encode(const VideoFrame& frame, - const std::vector* frame_types) { + const std::vector* frame_types) override { if (analyzer_) { analyzer_->PreEncodeOnFrame(frame); } @@ -407,9 +407,8 @@ std::unique_ptr VideoQualityTest::CreateVideoEncoder( return encoder; } -VideoQualityTest::VideoQualityTest( - std::unique_ptr injection_components) - : env_(CreateEnvironment()), +VideoQualityTest::VideoQualityTest(InjectionComponents injection_components) + : CallTest(injection_components.field_trials), video_decoder_factory_( [this](const Environment& env, const SdpVideoFormat& format) { return this->CreateVideoDecoder(env, format); @@ -428,26 +427,23 @@ VideoQualityTest::VideoQualityTest( send_logs_(0), injection_components_(std::move(injection_components)), num_video_streams_(0) { - if (injection_components_ == nullptr) { - injection_components_ = std::make_unique(); - } - if (injection_components_->video_decoder_factory != nullptr) { - decoder_factory_ = std::move(injection_components_->video_decoder_factory); + if (injection_components_.video_decoder_factory != nullptr) { + decoder_factory_ = std::move(injection_components_.video_decoder_factory); } else { decoder_factory_ = std::make_unique(); } - if (injection_components_->video_encoder_factory != nullptr) { - encoder_factory_ = std::move(injection_components_->video_encoder_factory); + if (injection_components_.video_encoder_factory != nullptr) { + encoder_factory_ = std::move(injection_components_.video_encoder_factory); } else { encoder_factory_ = std::make_unique(); } fec_controller_factory_ = - std::move(injection_components_->fec_controller_factory); + std::move(injection_components_.fec_controller_factory); network_state_predictor_factory_ = - std::move(injection_components_->network_state_predictor_factory); + std::move(injection_components_.network_state_predictor_factory); network_controller_factory_ = - std::move(injection_components_->network_controller_factory); + std::move(injection_components_.network_controller_factory); // Register header extensions that are used by transport to identify // extensions when parsing incomig packets. @@ -465,10 +461,6 @@ VideoQualityTest::VideoQualityTest( RtpExtension(RtpExtension::kVideoTimingUri, kVideoTimingExtensionId)); } -VideoQualityTest::InjectionComponents::InjectionComponents() = default; - -VideoQualityTest::InjectionComponents::~InjectionComponents() = default; - void VideoQualityTest::TestBody() {} std::string VideoQualityTest::GenerateGraphTitle() const { @@ -487,18 +479,15 @@ std::string VideoQualityTest::GenerateGraphTitle() const { } void VideoQualityTest::CheckParamsAndInjectionComponents() { - if (injection_components_ == nullptr) { - injection_components_ = std::make_unique(); - } - if (!params_.config && injection_components_->sender_network == nullptr && - injection_components_->receiver_network == nullptr) { + if (!params_.config && injection_components_.sender_network == nullptr && + injection_components_.receiver_network == nullptr) { params_.config = BuiltInNetworkBehaviorConfig(); } RTC_CHECK( - (params_.config && injection_components_->sender_network == nullptr && - injection_components_->receiver_network == nullptr) || - (!params_.config && injection_components_->sender_network != nullptr && - injection_components_->receiver_network != nullptr)); + (params_.config && injection_components_.sender_network == nullptr && + injection_components_.receiver_network == nullptr) || + (!params_.config && injection_components_.sender_network != nullptr && + injection_components_.receiver_network != nullptr)); for (size_t video_idx = 0; video_idx < num_video_streams_; ++video_idx) { // Iterate over primary and secondary video streams. if (!params_.video[video_idx].enabled) @@ -1200,10 +1189,10 @@ void VideoQualityTest::StopThumbnails() { std::unique_ptr VideoQualityTest::CreateSendTransport() { std::unique_ptr network_behavior = nullptr; - if (injection_components_->sender_network == nullptr) { + if (injection_components_.sender_network == nullptr) { network_behavior = std::make_unique(*params_.config); } else { - network_behavior = std::move(injection_components_->sender_network); + network_behavior = std::move(injection_components_.sender_network); } return std::make_unique( task_queue(), @@ -1221,10 +1210,10 @@ VideoQualityTest::CreateSendTransport() { std::unique_ptr VideoQualityTest::CreateReceiveTransport() { std::unique_ptr network_behavior = nullptr; - if (injection_components_->receiver_network == nullptr) { + if (injection_components_.receiver_network == nullptr) { network_behavior = std::make_unique(*params_.config); } else { - network_behavior = std::move(injection_components_->receiver_network); + network_behavior = std::move(injection_components_.receiver_network); } return std::make_unique( task_queue(), diff --git a/video/video_quality_test.h b/video/video_quality_test.h index ce9260cd0b..e6cd6256d9 100644 --- a/video/video_quality_test.h +++ b/video/video_quality_test.h @@ -55,13 +55,12 @@ namespace webrtc { class VideoQualityTest : public test::CallTest, public VideoQualityTestFixtureInterface { public: - explicit VideoQualityTest( - std::unique_ptr injection_components); + explicit VideoQualityTest(InjectionComponents injection_components = {}); void RunWithAnalyzer(const Params& params) override; void RunWithRenderers(const Params& params) override; - const std::map& payload_type_map() override { + const std::map& payload_type_map() override { return payload_type_map_; } @@ -119,7 +118,6 @@ class VideoQualityTest : public test::CallTest, virtual std::unique_ptr CreateSendTransport(); virtual std::unique_ptr CreateReceiveTransport(); - const Environment env_; std::vector>> thumbnail_capturers_; RtcEventLogFactory rtc_event_log_factory_; @@ -141,7 +139,7 @@ class VideoQualityTest : public test::CallTest, int send_logs_; Params params_; - std::unique_ptr injection_components_; + InjectionComponents injection_components_; // Set non-null when running with analyzer. std::unique_ptr analyzer_; diff --git a/video/video_send_stream_impl.cc b/video/video_send_stream_impl.cc index c0c8dff453..9164f530ad 100644 --- a/video/video_send_stream_impl.cc +++ b/video/video_send_stream_impl.cc @@ -22,6 +22,7 @@ #include "absl/algorithm/container.h" #include "api/adaptation/resource.h" +#include "api/array_view.h" #include "api/call/bitrate_allocation.h" #include "api/crypto/crypto_options.h" #include "api/environment/environment.h" @@ -84,9 +85,9 @@ namespace internal { namespace { // Max positive size difference to treat allocations as "similar". -static constexpr int kMaxVbaSizeDifferencePercent = 10; +constexpr int kMaxVbaSizeDifferencePercent = 10; // Max time we will throttle similar video bitrate allocations. -static constexpr int64_t kMaxVbaThrottleTimeMs = 500; +constexpr int64_t kMaxVbaThrottleTimeMs = 500; constexpr TimeDelta kEncoderTimeOut = TimeDelta::Seconds(2); @@ -101,7 +102,7 @@ constexpr int kMinDefaultAv1BitrateBps = // bandwidth rampup with less risk of overshoots causing adverse effects like // packet loss. Not used for receive side BWE, since there we lack the probing // feature and so may result in too slow initial rampup. -static constexpr double kStrictPacingMultiplier = 1.1; +constexpr double kStrictPacingMultiplier = 1.1; bool TransportSeqNumExtensionConfigured(const VideoSendStream::Config& config) { const std::vector& extensions = config.rtp.extensions; @@ -580,6 +581,11 @@ void VideoSendStreamImpl::SetStats(const Stats& stats) { stats_proxy_.SetStats(stats); } +void VideoSendStreamImpl::SetCsrcs(ArrayView csrcs) { + RTC_DCHECK_RUN_ON(&thread_checker_); + rtp_video_sender_->SetCsrcs(csrcs); +} + std::optional VideoSendStreamImpl::GetPacingFactorOverride() const { return configured_pacing_factor_; } @@ -698,8 +704,8 @@ void VideoSendStreamImpl::StopVideoSendStream() { RTC_DCHECK_RUN_ON(&thread_checker_); bitrate_allocator_->RemoveObserver(this); check_encoder_activity_task_.Stop(); - video_stream_encoder_->OnBitrateUpdated(DataRate::Zero(), DataRate::Zero(), - DataRate::Zero(), 0, 0, 0); + video_stream_encoder_->OnBitrateUpdated(DataRate::Zero(), DataRate::Zero(), 0, + 0, 0); stats_proxy_.OnSetEncoderTargetRate(0); } @@ -911,12 +917,6 @@ uint32_t VideoSendStreamImpl::OnBitrateUpdated(BitrateAllocationUpdate update) { RTC_DCHECK(rtp_video_sender_->IsActive()) << "VideoSendStream::Start has not been called."; - // When the BWE algorithm doesn't pass a stable estimate, we'll use the - // unstable one instead. - if (update.stable_target_bitrate.IsZero()) { - update.stable_target_bitrate = update.target_bitrate; - } - rtp_video_sender_->OnBitrateUpdated(update, stats_proxy_.GetSendFrameRate()); encoder_target_rate_bps_ = rtp_video_sender_->GetPayloadBitrateBps(); const uint32_t protection_bitrate_bps = @@ -926,26 +926,12 @@ uint32_t VideoSendStreamImpl::OnBitrateUpdated(BitrateAllocationUpdate update) { link_allocation = DataRate::BitsPerSec(encoder_target_rate_bps_ - protection_bitrate_bps); } - DataRate overhead = - update.target_bitrate - DataRate::BitsPerSec(encoder_target_rate_bps_); - DataRate encoder_stable_target_rate = update.stable_target_bitrate; - if (encoder_stable_target_rate > overhead) { - encoder_stable_target_rate = encoder_stable_target_rate - overhead; - } else { - encoder_stable_target_rate = DataRate::BitsPerSec(encoder_target_rate_bps_); - } - encoder_target_rate_bps_ = std::min(encoder_max_bitrate_bps_, encoder_target_rate_bps_); - - encoder_stable_target_rate = - std::min(DataRate::BitsPerSec(encoder_max_bitrate_bps_), - encoder_stable_target_rate); - DataRate encoder_target_rate = DataRate::BitsPerSec(encoder_target_rate_bps_); link_allocation = std::max(encoder_target_rate, link_allocation); video_stream_encoder_->OnBitrateUpdated( - encoder_target_rate, encoder_stable_target_rate, link_allocation, + encoder_target_rate, link_allocation, dchecked_cast(update.packet_loss_ratio * 256), update.round_trip_time.ms(), update.cwnd_reduce_ratio); stats_proxy_.OnSetEncoderTargetRate(encoder_target_rate_bps_); diff --git a/video/video_send_stream_impl.h b/video/video_send_stream_impl.h index 646d4e4c53..a8e7858042 100644 --- a/video/video_send_stream_impl.h +++ b/video/video_send_stream_impl.h @@ -21,6 +21,7 @@ #include #include "api/adaptation/resource.h" +#include "api/array_view.h" #include "api/call/bitrate_allocation.h" #include "api/environment/environment.h" #include "api/fec_controller.h" @@ -122,6 +123,8 @@ class VideoSendStreamImpl : public webrtc::VideoSendStream, Stats GetStats() override; void SetStats(const Stats& stats) override; + void SetCsrcs(ArrayView csrcs) override; + void StopPermanentlyAndGetRtpStates(RtpStateMap* rtp_state_map, RtpPayloadStateMap* payload_state_map); void GenerateKeyFrame(const std::vector& rids) override; diff --git a/video/video_send_stream_impl_unittest.cc b/video/video_send_stream_impl_unittest.cc index f0023f12b9..216907d778 100644 --- a/video/video_send_stream_impl_unittest.cc +++ b/video/video_send_stream_impl_unittest.cc @@ -71,6 +71,7 @@ namespace { using ::testing::_; using ::testing::AllOf; using ::testing::AnyNumber; +using ::testing::ElementsAreArray; using ::testing::Eq; using ::testing::Field; using ::testing::Invoke; @@ -124,6 +125,7 @@ class MockRtpVideoSender : public RtpVideoSenderInterface { MOCK_METHOD(uint32_t, GetPayloadBitrateBps, (), (const, override)); MOCK_METHOD(uint32_t, GetProtectionBitrateBps, (), (const, override)); MOCK_METHOD(void, SetEncodingData, (size_t, size_t, size_t), (override)); + MOCK_METHOD(void, SetCsrcs, (ArrayView csrcs), (override)); MOCK_METHOD(std::vector, GetSentRtpPacketInfos, (uint32_t ssrc, ArrayView sequence_numbers), @@ -168,7 +170,7 @@ class VideoSendStreamImplTest : public ::testing::Test { ON_CALL(rtp_video_sender_, SetSending) .WillByDefault(SaveArg<0>(&rtp_sending_)); } - ~VideoSendStreamImplTest() {} + ~VideoSendStreamImplTest() override {} VideoEncoderConfig TestVideoEncoderConfig( VideoEncoderConfig::ContentType content_type = @@ -937,15 +939,13 @@ TEST_F(VideoSendStreamImplTest, CallsVideoStreamEncoderOnBitrateUpdate) { DataRate::BitsPerSec(qvga_stream.target_bitrate_bps); BitrateAllocationUpdate update; update.target_bitrate = network_constrained_rate; - update.stable_target_bitrate = network_constrained_rate; update.round_trip_time = TimeDelta::Millis(1); EXPECT_CALL(rtp_video_sender_, OnBitrateUpdated(update, _)); EXPECT_CALL(rtp_video_sender_, GetPayloadBitrateBps()) .WillOnce(Return(network_constrained_rate.bps())); - EXPECT_CALL( - *video_stream_encoder_, - OnBitrateUpdated(network_constrained_rate, network_constrained_rate, - network_constrained_rate, 0, _, 0)); + EXPECT_CALL(*video_stream_encoder_, + OnBitrateUpdated(network_constrained_rate, + network_constrained_rate, 0, _, 0)); static_cast(vss_impl.get()) ->OnBitrateUpdated(update); @@ -956,13 +956,11 @@ TEST_F(VideoSendStreamImplTest, CallsVideoStreamEncoderOnBitrateUpdate) { const DataRate headroom = DataRate::BitsPerSec(50000); const DataRate rate_with_headroom = qvga_max_bitrate + headroom; update.target_bitrate = rate_with_headroom; - update.stable_target_bitrate = rate_with_headroom; EXPECT_CALL(rtp_video_sender_, OnBitrateUpdated(update, _)); EXPECT_CALL(rtp_video_sender_, GetPayloadBitrateBps()) .WillOnce(Return(rate_with_headroom.bps())); EXPECT_CALL(*video_stream_encoder_, - OnBitrateUpdated(qvga_max_bitrate, qvga_max_bitrate, - rate_with_headroom, 0, _, 0)); + OnBitrateUpdated(qvga_max_bitrate, rate_with_headroom, 0, _, 0)); static_cast(vss_impl.get()) ->OnBitrateUpdated(update); @@ -977,9 +975,9 @@ TEST_F(VideoSendStreamImplTest, CallsVideoStreamEncoderOnBitrateUpdate) { .WillOnce(Return(rate_with_headroom.bps())); const DataRate headroom_minus_protection = rate_with_headroom - DataRate::BitsPerSec(protection_bitrate_bps); - EXPECT_CALL(*video_stream_encoder_, - OnBitrateUpdated(qvga_max_bitrate, qvga_max_bitrate, - headroom_minus_protection, 0, _, 0)); + EXPECT_CALL( + *video_stream_encoder_, + OnBitrateUpdated(qvga_max_bitrate, headroom_minus_protection, 0, _, 0)); static_cast(vss_impl.get()) ->OnBitrateUpdated(update); @@ -991,18 +989,23 @@ TEST_F(VideoSendStreamImplTest, CallsVideoStreamEncoderOnBitrateUpdate) { EXPECT_CALL(rtp_video_sender_, GetPayloadBitrateBps()) .WillOnce(Return(rate_with_headroom.bps())); EXPECT_CALL(*video_stream_encoder_, - OnBitrateUpdated(qvga_max_bitrate, qvga_max_bitrate, - qvga_max_bitrate, 0, _, 0)); + OnBitrateUpdated(qvga_max_bitrate, qvga_max_bitrate, 0, _, 0)); static_cast(vss_impl.get()) ->OnBitrateUpdated(update); // Set rates to zero on stop. EXPECT_CALL(*video_stream_encoder_, - OnBitrateUpdated(DataRate::Zero(), DataRate::Zero(), - DataRate::Zero(), 0, 0, 0)); + OnBitrateUpdated(DataRate::Zero(), DataRate::Zero(), 0, 0, 0)); vss_impl->Stop(); } +TEST_F(VideoSendStreamImplTest, ForwardsCsrcsToRtpVideoSender) { + auto vss_impl = CreateVideoSendStreamImpl(TestVideoEncoderConfig()); + std::vector csrcs = {1, 2, 3}; + EXPECT_CALL(rtp_video_sender_, SetCsrcs(ElementsAreArray(csrcs))); + vss_impl->SetCsrcs(csrcs); +} + TEST_F(VideoSendStreamImplTest, DisablesPaddingOnPausedEncoder) { int padding_bitrate = 0; auto vss_impl = CreateVideoSendStreamImpl(TestVideoEncoderConfig()); diff --git a/video/video_send_stream_tests.cc b/video/video_send_stream_tests.cc index 9b0b57763d..25b525486f 100644 --- a/video/video_send_stream_tests.cc +++ b/video/video_send_stream_tests.cc @@ -862,7 +862,7 @@ class FlexfecObserver : public test::EndToEndTest { return SEND_PACKET; } - BuiltInNetworkBehaviorConfig GetSendTransportConfig() const { + BuiltInNetworkBehaviorConfig GetSendTransportConfig() const override { // At low RTT (< kLowRttNackMs) -> NACK only, no FEC. // Therefore we need some network delay. const int kNetworkDelayMs = 100; @@ -872,7 +872,7 @@ class FlexfecObserver : public test::EndToEndTest { return config; } - BuiltInNetworkBehaviorConfig GetReceiveTransportConfig() const { + BuiltInNetworkBehaviorConfig GetReceiveTransportConfig() const override { // We need the RTT to be >200 ms to send FEC and the network delay for the // send transport is 100 ms, so add 100 ms (but no loss) on the return link. BuiltInNetworkBehaviorConfig config; @@ -1088,8 +1088,7 @@ void VideoSendStreamTest::TestNackRetransmission( RTCPSender::FeedbackState feedback_state; EXPECT_EQ(0, rtcp_sender.SendRTCP(feedback_state, kRtcpNack, - sequence_numbers.size(), - sequence_numbers.data())); + sequence_numbers)); } // Drop media packet, otherwise transport feeback may indirectly ack the @@ -1668,7 +1667,7 @@ TEST_F(VideoSendStreamTest, ChangingNetworkRoute) { extensions_.Register(kExtensionId); } - ~ChangingNetworkRouteTest() { + ~ChangingNetworkRouteTest() override { // Block until all already posted tasks run to avoid 'use after free' // when such task accesses `this`. SendTask(task_queue_, [] {}); @@ -1787,7 +1786,7 @@ TEST_F(VideoSendStreamTest, DISABLED_RelayToDirectRoute) { task_queue_thread_.Detach(); } - ~RelayToDirectRouteTest() { + ~RelayToDirectRouteTest() override { // Block until all already posted tasks run to avoid 'use after free' // when such task accesses `this`. SendTask(task_queue_, [] {}); @@ -1958,7 +1957,7 @@ class MaxPaddingSetTest : public test::SendTest { task_queue_thread_.Detach(); } - ~MaxPaddingSetTest() { + ~MaxPaddingSetTest() override { // Block until all already posted tasks run to avoid 'use after free' // when such task accesses `this`. SendTask(task_queue_, [] {}); diff --git a/video/video_source_sink_controller.h b/video/video_source_sink_controller.h index 53d2638c47..47b1a9a4c1 100644 --- a/video/video_source_sink_controller.h +++ b/video/video_source_sink_controller.h @@ -26,8 +26,8 @@ namespace webrtc { // Responsible for configuring source/sink settings, i.e. performing -// webrtc::VideoSourceInterface::AddOrUpdateSink(). It does this by -// storing settings internally which are converted to webrtc::VideoSinkWants +// VideoSourceInterface::AddOrUpdateSink(). It does this by +// storing settings internally which are converted to VideoSinkWants // when PushSourceSinkSettings() is performed. class VideoSourceSinkController { public: diff --git a/video/video_stream_buffer_controller.cc b/video/video_stream_buffer_controller.cc index 93bb147802..ff778633c9 100644 --- a/video/video_stream_buffer_controller.cc +++ b/video/video_stream_buffer_controller.cc @@ -46,13 +46,13 @@ namespace webrtc { namespace { // Max number of frames the buffer will hold. -static constexpr size_t kMaxFramesBuffered = 800; +constexpr size_t kMaxFramesBuffered = 800; // Max number of decoded frame info that will be saved. -static constexpr int kMaxFramesHistory = 1 << 13; +constexpr int kMaxFramesHistory = 1 << 13; // Default value for the maximum decode queue size that is used when the // low-latency renderer is used. -static constexpr size_t kZeroPlayoutDelayDefaultMaxDecodeQueueSize = 8; +constexpr size_t kZeroPlayoutDelayDefaultMaxDecodeQueueSize = 8; struct FrameMetadata { explicit FrameMetadata(const EncodedFrame& frame) diff --git a/video/video_stream_buffer_controller_unittest.cc b/video/video_stream_buffer_controller_unittest.cc index 08a15338c1..681c934c45 100644 --- a/video/video_stream_buffer_controller_unittest.cc +++ b/video/video_stream_buffer_controller_unittest.cc @@ -197,7 +197,7 @@ class VideoStreamBufferControllerFixture } Timestamp now = clock_->CurrentTime(); - // TODO(bugs.webrtc.org/13756): Remove this when webrtc::Thread uses uses + // TODO(bugs.webrtc.org/13756): Remove this when Thread uses uses // Timestamp instead of an integer milliseconds. This extra wait is needed // for some tests that use the metronome. This is due to rounding // milliseconds, affecting the precision of simulated time controller uses diff --git a/video/video_stream_encoder.cc b/video/video_stream_encoder.cc index 53125ff373..3f7ae8141f 100644 --- a/video/video_stream_encoder.cc +++ b/video/video_stream_encoder.cc @@ -602,25 +602,20 @@ std::optional ParseEncoderThreadLimit(const FieldTrialsView& trials) { } // namespace VideoStreamEncoder::EncoderRateSettings::EncoderRateSettings() - : rate_control(), - encoder_target(DataRate::Zero()), - stable_encoder_target(DataRate::Zero()) {} + : rate_control(), encoder_target(DataRate::Zero()) {} VideoStreamEncoder::EncoderRateSettings::EncoderRateSettings( const VideoBitrateAllocation& bitrate, double framerate_fps, DataRate bandwidth_allocation, - DataRate encoder_target, - DataRate stable_encoder_target) + DataRate encoder_target) : rate_control(bitrate, framerate_fps, bandwidth_allocation), - encoder_target(encoder_target), - stable_encoder_target(stable_encoder_target) {} + encoder_target(encoder_target) {} bool VideoStreamEncoder::EncoderRateSettings::operator==( const EncoderRateSettings& rhs) const { return rate_control == rhs.rate_control && - encoder_target == rhs.encoder_target && - stable_encoder_target == rhs.stable_encoder_target; + encoder_target == rhs.encoder_target; } bool VideoStreamEncoder::EncoderRateSettings::operator!=( @@ -1094,7 +1089,7 @@ void VideoStreamEncoder::ReconfigureEncoder() { // Stream dimensions may be not equal to given because of a simulcast // restrictions. auto highest_stream = absl::c_max_element( - streams, [](const webrtc::VideoStream& a, const webrtc::VideoStream& b) { + streams, [](const VideoStream& a, const VideoStream& b) { return std::tie(a.width, a.height) < std::tie(b.width, b.height); }); int highest_stream_width = static_cast(highest_stream->width); @@ -1372,6 +1367,7 @@ void VideoStreamEncoder::ReconfigureEncoder() { frame_encode_metadata_writer_.Reset(); last_encode_info_ms_ = std::nullopt; was_encode_called_since_last_initialization_ = false; + encoder_fallback_requested_ = false; } // Inform dependents of updated encoder settings. @@ -1694,7 +1690,7 @@ VideoStreamEncoder::UpdateBitrateAllocation( // might cap the bitrate to the min bitrate configured. if (rate_allocator_ && rate_settings.encoder_target > DataRate::Zero()) { new_allocation = rate_allocator_->Allocate(VideoBitrateAllocationParameters( - rate_settings.encoder_target, rate_settings.stable_encoder_target, + rate_settings.encoder_target, rate_settings.rate_control.framerate_fps)); } @@ -2083,7 +2079,7 @@ void VideoStreamEncoder::EncodeVideoFrame(const VideoFrame& video_frame, << send_codec_.height << " received a too small frame " << out_frame.width() << "x" << out_frame.height(); - TRACE_EVENT2("webrtc", "webrtc::VideoEncoder::Encode", "rtp_timestamp", + TRACE_EVENT2("webrtc", "VideoEncoder::Encode", "rtp_timestamp", out_frame.rtp_timestamp(), "storage_representation", out_frame.video_frame_buffer()->storage_representation()); @@ -2350,21 +2346,19 @@ DataRate VideoStreamEncoder::UpdateTargetBitrate(DataRate target_bitrate, } void VideoStreamEncoder::OnBitrateUpdated(DataRate target_bitrate, - DataRate stable_target_bitrate, DataRate link_allocation, uint8_t fraction_lost, int64_t round_trip_time_ms, double cwnd_reduce_ratio) { RTC_DCHECK_GE(link_allocation, target_bitrate); if (!encoder_queue_->IsCurrent()) { - encoder_queue_->PostTask([this, target_bitrate, stable_target_bitrate, - link_allocation, fraction_lost, - round_trip_time_ms, cwnd_reduce_ratio] { + encoder_queue_->PostTask([this, target_bitrate, link_allocation, + fraction_lost, round_trip_time_ms, + cwnd_reduce_ratio] { DataRate updated_target_bitrate = UpdateTargetBitrate(target_bitrate, cwnd_reduce_ratio); - OnBitrateUpdated(updated_target_bitrate, stable_target_bitrate, - link_allocation, fraction_lost, round_trip_time_ms, - cwnd_reduce_ratio); + OnBitrateUpdated(updated_target_bitrate, link_allocation, fraction_lost, + round_trip_time_ms, cwnd_reduce_ratio); }); return; } @@ -2384,7 +2378,6 @@ void VideoStreamEncoder::OnBitrateUpdated(DataRate target_bitrate, RTC_DCHECK(sink_) << "sink_ must be set before the encoder is active."; RTC_LOG(LS_VERBOSE) << "OnBitrateUpdated, bitrate " << target_bitrate.bps() - << " stable bitrate = " << stable_target_bitrate.bps() << " link allocation bitrate = " << link_allocation.bps() << " packet loss " << static_cast(fraction_lost) << " rtt " << round_trip_time_ms; @@ -2397,9 +2390,9 @@ void VideoStreamEncoder::OnBitrateUpdated(DataRate target_bitrate, uint32_t framerate_fps = GetInputFramerateFps(); frame_dropper_.SetRates((target_bitrate.bps() + 500) / 1000, framerate_fps); - EncoderRateSettings new_rate_settings{ - VideoBitrateAllocation(), static_cast(framerate_fps), - link_allocation, target_bitrate, stable_target_bitrate}; + EncoderRateSettings new_rate_settings{VideoBitrateAllocation(), + static_cast(framerate_fps), + link_allocation, target_bitrate}; SetEncoderRates(UpdateBitrateAllocation(new_rate_settings)); if (target_bitrate.bps() != 0) diff --git a/video/video_stream_encoder.h b/video/video_stream_encoder.h index 8c0f2ca04d..4d2d49e360 100644 --- a/video/video_stream_encoder.h +++ b/video/video_stream_encoder.h @@ -92,10 +92,9 @@ class VideoStreamEncoder : public VideoStreamEncoderInterface, const VideoStreamEncoderSettings& settings, std::unique_ptr overuse_detector, std::unique_ptr frame_cadence_adapter, - std::unique_ptr - encoder_queue, + std::unique_ptr encoder_queue, BitrateAllocationCallbackType allocation_cb_type, - webrtc::VideoEncoderFactory::EncoderSelectorInterface* encoder_selector = + VideoEncoderFactory::EncoderSelectorInterface* encoder_selector = nullptr); ~VideoStreamEncoder() override; @@ -132,8 +131,7 @@ class VideoStreamEncoder : public VideoStreamEncoderInterface, const VideoEncoder::LossNotification& loss_notification) override; void OnBitrateUpdated(DataRate target_bitrate, - DataRate stable_target_bitrate, - DataRate target_headroom, + DataRate link_allocation, uint8_t fraction_lost, int64_t round_trip_time_ms, double cwnd_reduce_ratio) override; @@ -202,8 +200,7 @@ class VideoStreamEncoder : public VideoStreamEncoderInterface, EncoderRateSettings(const VideoBitrateAllocation& bitrate, double framerate_fps, DataRate bandwidth_allocation, - DataRate encoder_target, - DataRate stable_encoder_target); + DataRate encoder_target); bool operator==(const EncoderRateSettings& rhs) const; bool operator!=(const EncoderRateSettings& rhs) const; @@ -215,7 +212,6 @@ class VideoStreamEncoder : public VideoStreamEncoderInterface, // |using last_encoder_rate_setings_->bitrate.get_sum_bps()|, may trick it // into thinking the available bitrate has decreased since the last call. DataRate encoder_target; - DataRate stable_encoder_target; }; class DegradationPreferenceManager; @@ -287,7 +283,7 @@ class VideoStreamEncoder : public VideoStreamEncoderInterface, const BitrateAllocationCallbackType allocation_cb_type_; const RateControlSettings rate_control_settings_; - webrtc::VideoEncoderFactory::EncoderSelectorInterface* const + VideoEncoderFactory::EncoderSelectorInterface* const encoder_selector_from_constructor_; std::unique_ptr const encoder_selector_from_factory_; diff --git a/video/video_stream_encoder_interface.h b/video/video_stream_encoder_interface.h index 234ef33d88..d31eec977a 100644 --- a/video/video_stream_encoder_interface.h +++ b/video/video_stream_encoder_interface.h @@ -111,14 +111,10 @@ class VideoStreamEncoderInterface { // Set the currently estimated network properties. A `target_bitrate` // of zero pauses the encoder. - // `stable_target_bitrate` is a filtered version of `target_bitrate`. It is - // always less or equal to it. It can be used to avoid rapid changes of - // expensive encoding settings, such as resolution. // `link_allocation` is the bandwidth available for this video stream on the // network link. It is always at least `target_bitrate` but may be higher // if we are not network constrained. virtual void OnBitrateUpdated(DataRate target_bitrate, - DataRate stable_target_bitrate, DataRate link_allocation, uint8_t fraction_lost, int64_t round_trip_time_ms, diff --git a/video/video_stream_encoder_unittest.cc b/video/video_stream_encoder_unittest.cc index bbae05d0df..d5c2634025 100644 --- a/video/video_stream_encoder_unittest.cc +++ b/video/video_stream_encoder_unittest.cc @@ -194,7 +194,7 @@ void PassAFrame( }); } -class TestBuffer : public webrtc::I420Buffer { +class TestBuffer : public I420Buffer { public: TestBuffer(Event* event, int width, int height) : I420Buffer(width, height), event_(event) {} @@ -210,16 +210,14 @@ class TestBuffer : public webrtc::I420Buffer { // A fake native buffer that can't be converted to I420. Upon scaling, it // produces another FakeNativeBuffer. -class FakeNativeBuffer : public webrtc::VideoFrameBuffer { +class FakeNativeBuffer : public VideoFrameBuffer { public: FakeNativeBuffer(Event* event, int width, int height) : event_(event), width_(width), height_(height) {} - webrtc::VideoFrameBuffer::Type type() const override { return Type::kNative; } + VideoFrameBuffer::Type type() const override { return Type::kNative; } int width() const override { return width_; } int height() const override { return height_; } - scoped_refptr ToI420() override { - return nullptr; - } + scoped_refptr ToI420() override { return nullptr; } scoped_refptr CropAndScale(int offset_x, int offset_y, int crop_width, @@ -242,15 +240,15 @@ class FakeNativeBuffer : public webrtc::VideoFrameBuffer { }; // A fake native buffer that is backed by an NV12 buffer. -class FakeNV12NativeBuffer : public webrtc::VideoFrameBuffer { +class FakeNV12NativeBuffer : public VideoFrameBuffer { public: FakeNV12NativeBuffer(Event* event, int width, int height) : nv12_buffer_(NV12Buffer::Create(width, height)), event_(event) {} - webrtc::VideoFrameBuffer::Type type() const override { return Type::kNative; } + VideoFrameBuffer::Type type() const override { return Type::kNative; } int width() const override { return nv12_buffer_->width(); } int height() const override { return nv12_buffer_->height(); } - scoped_refptr ToI420() override { + scoped_refptr ToI420() override { return nv12_buffer_->ToI420(); } scoped_refptr GetMappedFrameBuffer( @@ -280,7 +278,7 @@ class CpuOveruseDetectorProxy : public OveruseFrameDetector { last_target_framerate_fps_(-1), framerate_updated_event_(true /* manual_reset */, false /* initially_signaled */) {} - virtual ~CpuOveruseDetectorProxy() {} + ~CpuOveruseDetectorProxy() override {} void OnTargetFramerateUpdated(int framerate_fps) override { MutexLock lock(&lock_); @@ -437,8 +435,7 @@ class VideoStreamEncoderUnderTest : public VideoStreamEncoder { const Environment& env, TimeController* time_controller, std::unique_ptr cadence_adapter, - std::unique_ptr - encoder_queue, + std::unique_ptr encoder_queue, SendStatisticsProxy* stats_proxy, const VideoStreamEncoderSettings& settings, VideoStreamEncoder::BitrateAllocationCallbackType @@ -484,15 +481,13 @@ class VideoStreamEncoderUnderTest : public VideoStreamEncoder { TimeDelta::Seconds(5)); } - void OnBitrateUpdatedAndWaitForManagedResources( - DataRate target_bitrate, - DataRate stable_target_bitrate, - DataRate link_allocation, - uint8_t fraction_lost, - int64_t round_trip_time_ms, - double cwnd_reduce_ratio) { - OnBitrateUpdated(target_bitrate, stable_target_bitrate, link_allocation, - fraction_lost, round_trip_time_ms, cwnd_reduce_ratio); + void OnBitrateUpdatedAndWaitForManagedResources(DataRate target_bitrate, + DataRate link_allocation, + uint8_t fraction_lost, + int64_t round_trip_time_ms, + double cwnd_reduce_ratio) { + OnBitrateUpdated(target_bitrate, link_allocation, fraction_lost, + round_trip_time_ms, cwnd_reduce_ratio); // Bitrate is updated on the encoder queue. WaitUntilTaskQueueIsIdle(); } @@ -587,7 +582,7 @@ class AdaptingFrameForwarder : public test::FrameForwarder { return adaptation_enabled_; } - // The "last wants" is a snapshot of the previous webrtc::VideoSinkWants where + // The "last wants" is a snapshot of the previous VideoSinkWants where // the resolution or frame rate was different than it is currently. If // something else is modified, such as encoder resolutions, but the resolution // and frame rate stays the same, last wants is not updated. @@ -733,7 +728,7 @@ class SimpleVideoStreamEncoderFactory { class AdaptedVideoStreamEncoder : public VideoStreamEncoder { public: using VideoStreamEncoder::VideoStreamEncoder; - ~AdaptedVideoStreamEncoder() { Stop(); } + ~AdaptedVideoStreamEncoder() override { Stop(); } }; class MockFakeEncoder : public test::FakeEncoder { @@ -742,7 +737,7 @@ class SimpleVideoStreamEncoderFactory { MOCK_METHOD(CodecSpecificInfo, EncodeHook, (EncodedImage & encoded_image, - webrtc::scoped_refptr buffer), + scoped_refptr buffer), (override)); MOCK_METHOD(VideoEncoder::EncoderInfo, GetEncoderInfo, @@ -824,7 +819,7 @@ class SimpleVideoStreamEncoderFactory { std::make_unique( time_controller_.GetClock(), VideoSendStream::Config(nullptr), - webrtc::VideoEncoderConfig::ContentType::kRealtimeVideo, + VideoEncoderConfig::ContentType::kRealtimeVideo, field_trials_); std::unique_ptr bitrate_allocator_factory_ = CreateBuiltinVideoBitrateAllocatorFactory(); @@ -881,13 +876,9 @@ class MockVideoSourceInterface : public VideoSourceInterface { public: MOCK_METHOD(void, AddOrUpdateSink, - (webrtc::VideoSinkInterface*, - const webrtc::VideoSinkWants&), - (override)); - MOCK_METHOD(void, - RemoveSink, - (webrtc::VideoSinkInterface*), + (VideoSinkInterface*, const VideoSinkWants&), (override)); + MOCK_METHOD(void, RemoveSink, (VideoSinkInterface*), (override)); MOCK_METHOD(void, RequestRefreshFrame, (), (override)); }; @@ -907,7 +898,7 @@ class VideoStreamEncoderTest : public ::testing::Test { stats_proxy_(new MockableSendStatisticsProxy( time_controller_.GetClock(), video_send_config_, - webrtc::VideoEncoderConfig::ContentType::kRealtimeVideo, + VideoEncoderConfig::ContentType::kRealtimeVideo, field_trials_)), sink_(&time_controller_, &fake_encoder_) {} @@ -952,8 +943,8 @@ class VideoStreamEncoderTest : public ::testing::Test { video_send_config_.encoder_settings, allocation_callback_type, num_cores); video_stream_encoder_->SetSink(&sink_, /*rotation_applied=*/false); - video_stream_encoder_->SetSource( - &video_source_, webrtc::DegradationPreference::MAINTAIN_FRAMERATE); + video_stream_encoder_->SetSource(&video_source_, + DegradationPreference::MAINTAIN_FRAMERATE); video_stream_encoder_->SetStartBitrate(kTargetBitrate.bps()); video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config), kMaxPayloadLength, nullptr); @@ -1076,7 +1067,7 @@ class VideoStreamEncoderTest : public ::testing::Test { void VerifyAllocatedBitrate(const VideoBitrateAllocation& expected_bitrate) { video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); video_source_.IncomingCapturedFrame( CreateFrame(1, codec_width_, codec_height_)); @@ -1374,7 +1365,7 @@ class VideoStreamEncoderTest : public ::testing::Test { return FakeEncoder::Release(); } - void SetRates(const RateControlParameters& parameters) { + void SetRates(const RateControlParameters& parameters) override { MutexLock lock(&local_mutex_); num_set_rates_++; VideoBitrateAllocation adjusted_rate_allocation; @@ -1725,7 +1716,7 @@ class VideoStreamEncoderTest : public ::testing::Test { TEST_F(VideoStreamEncoderTest, EncodeOneFrame) { video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); Event frame_destroyed_event; video_source_.IncomingCapturedFrame(CreateFrame(1, &frame_destroyed_event)); WaitForEncodedFrame(1); @@ -1738,7 +1729,7 @@ TEST_F(VideoStreamEncoderTest, PopulatesFrameInstrumentationDataWhenSetTo) { true; ConfigureEncoder(video_encoder_config_.Copy()); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); // We need a QP for the encoded frame. fake_encoder_.SetEncodedImageData(EncodedImageBuffer::Create( @@ -1763,7 +1754,7 @@ TEST_F(VideoStreamEncoderTest, true; ConfigureEncoder(video_encoder_config_.Copy()); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kLowRate, kLowRate, kLowRate, 0, 0, 0); + kLowRate, kLowRate, 0, 0, 0); Event frame_destroyed_event; // Insert two frames, so that the first one isn't stored in the encoder queue. @@ -1783,7 +1774,7 @@ TEST_F(VideoStreamEncoderTest, // Mark stream as suspended. video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - DataRate::Zero(), DataRate::Zero(), DataRate::Zero(), 0, 0, 0); + DataRate::Zero(), DataRate::Zero(), 0, 0, 0); video_stream_encoder_->WaitUntilTaskQueueIsIdle(); // We need a QP for the encoded frame. @@ -1798,7 +1789,7 @@ TEST_F(VideoStreamEncoderTest, // Resume and increase bitrate budget, process stashed frames. video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); WaitForEncodedFrame(1); EXPECT_TRUE(sink_.GetLastFrameInstrumentationData().has_value()); @@ -1812,7 +1803,7 @@ TEST_F(VideoStreamEncoderTest, false; ConfigureEncoder(video_encoder_config_.Copy()); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); // We need a QP for the encoded frame. fake_encoder_.SetEncodedImageData(EncodedImageBuffer::Create( @@ -1832,7 +1823,7 @@ TEST_F(VideoStreamEncoderTest, true; ConfigureEncoder(video_encoder_config_.Copy()); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); // We need a QP for the encoded frame. fake_encoder_.SetEncodedImageData(EncodedImageBuffer::Create( @@ -1880,7 +1871,7 @@ TEST_F(VideoStreamEncoderTest, DropsFramesBeforeFirstOnBitrateUpdated) { EXPECT_TRUE(frame_destroyed_event.Wait(kDefaultTimeout)); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); // The pending frame should be encoded. WaitForEncodedFrame(kFrame2TimestampMs); @@ -1895,12 +1886,12 @@ TEST_F(VideoStreamEncoderTest, DropsFramesBeforeFirstOnBitrateUpdated) { TEST_F(VideoStreamEncoderTest, DropsFramesWhenRateSetToZero) { int64_t time_ms = 123; video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); video_source_.IncomingCapturedFrame(CreateFrame(time_ms, nullptr)); WaitForEncodedFrame(time_ms); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - DataRate::Zero(), DataRate::Zero(), DataRate::Zero(), 0, 0, 0); + DataRate::Zero(), DataRate::Zero(), 0, 0, 0); // The encoder will cache up to one frame for a short duration. Adding two // frames means that the first frame will be dropped and the second frame will @@ -1911,7 +1902,7 @@ TEST_F(VideoStreamEncoderTest, DropsFramesWhenRateSetToZero) { video_source_.IncomingCapturedFrame(CreateFrame(time_ms, nullptr)); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); WaitForEncodedFrame(time_ms); time_ms += 20; video_source_.IncomingCapturedFrame(CreateFrame(time_ms, nullptr)); @@ -1921,7 +1912,7 @@ TEST_F(VideoStreamEncoderTest, DropsFramesWhenRateSetToZero) { TEST_F(VideoStreamEncoderTest, DropsFramesWithSameOrOldNtpTimestamp) { video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr)); WaitForEncodedFrame(1); @@ -1935,7 +1926,7 @@ TEST_F(VideoStreamEncoderTest, DropsFramesWithSameOrOldNtpTimestamp) { TEST_F(VideoStreamEncoderTest, DropsFrameAfterStop) { video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr)); WaitForEncodedFrame(1); @@ -1952,7 +1943,7 @@ TEST_F(VideoStreamEncoderTest, DropsPendingFramesOnSlowEncode) { video_stream_encoder_->SetSource(&source, DegradationPreference::MAINTAIN_FRAMERATE); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); int dropped_count = 0; stats_proxy_->SetDroppedFrameCallback( @@ -1969,7 +1960,7 @@ TEST_F(VideoStreamEncoderTest, DropsPendingFramesOnSlowEncode) { TEST_F(VideoStreamEncoderTest, NativeFrameWithoutI420SupportGetsDelivered) { video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); Event frame_destroyed_event; video_source_.IncomingCapturedFrame( @@ -1993,7 +1984,7 @@ TEST_F(VideoStreamEncoderTest, // Capture a frame at codec_width_/codec_height_. video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr)); WaitForEncodedFrame(1); // The encoder will have been configured once. @@ -2016,7 +2007,7 @@ TEST_F(VideoStreamEncoderTest, TEST_F(VideoStreamEncoderTest, NonI420FramesShouldNotBeConvertedToI420) { video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); video_source_.IncomingCapturedFrame( CreateNV12Frame(1, codec_width_, codec_height_)); @@ -2028,7 +2019,7 @@ TEST_F(VideoStreamEncoderTest, NonI420FramesShouldNotBeConvertedToI420) { TEST_F(VideoStreamEncoderTest, NativeFrameGetsDelivered_NoFrameTypePreference) { video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); fake_encoder_.SetPreferredPixelFormats({}); @@ -2044,7 +2035,7 @@ TEST_F(VideoStreamEncoderTest, NativeFrameGetsDelivered_NoFrameTypePreference) { TEST_F(VideoStreamEncoderTest, NativeFrameGetsDelivered_PixelFormatPreferenceMatches) { video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); fake_encoder_.SetPreferredPixelFormats({VideoFrameBuffer::Type::kNV12}); @@ -2059,7 +2050,7 @@ TEST_F(VideoStreamEncoderTest, TEST_F(VideoStreamEncoderTest, NativeFrameGetsDelivered_MappingIsNotFeasible) { video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); // Fake NV12 native frame does not allow mapping to I444. fake_encoder_.SetPreferredPixelFormats({VideoFrameBuffer::Type::kI444}); @@ -2075,7 +2066,7 @@ TEST_F(VideoStreamEncoderTest, NativeFrameGetsDelivered_MappingIsNotFeasible) { TEST_F(VideoStreamEncoderTest, NativeFrameGetsDelivered_BackedByNV12) { video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); Event frame_destroyed_event; video_source_.IncomingCapturedFrame(CreateFakeNV12NativeFrame( @@ -2088,12 +2079,12 @@ TEST_F(VideoStreamEncoderTest, NativeFrameGetsDelivered_BackedByNV12) { TEST_F(VideoStreamEncoderTest, DropsFramesWhenCongestionWindowPushbackSet) { video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr)); WaitForEncodedFrame(1); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0.5); + kTargetBitrate, kTargetBitrate, 0, 0, 0.5); // The congestion window pushback is set to 0.5, which will drop 1/2 of // frames. Adding two frames means that the first frame will be dropped and // the second frame will be sent to the encoder. @@ -2110,7 +2101,7 @@ TEST_F(VideoStreamEncoderTest, DropsFramesWhenCongestionWindowPushbackSet) { TEST_F(VideoStreamEncoderTest, ConfigureEncoderTriggersOnEncoderConfigurationChanged) { video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); EXPECT_EQ(0, sink_.number_of_reconfigurations()); // Capture a frame and wait for it to synchronize with the encoder thread. @@ -2137,7 +2128,7 @@ TEST_F(VideoStreamEncoderTest, TEST_F(VideoStreamEncoderTest, FrameResolutionChangeReconfigureEncoder) { video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); // Capture a frame and wait for it to synchronize with the encoder thread. video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr)); @@ -2163,7 +2154,7 @@ TEST_F(VideoStreamEncoderTest, FrameResolutionChangeReconfigureEncoder) { TEST_F(VideoStreamEncoderTest, EncoderInstanceDestroyedBeforeAnotherInstanceCreated) { video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); // Capture a frame and wait for it to synchronize with the encoder thread. video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr)); @@ -2185,7 +2176,7 @@ TEST_F(VideoStreamEncoderTest, TEST_F(VideoStreamEncoderTest, BitrateLimitsChangeReconfigureRateAllocator) { video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); VideoEncoderConfig video_encoder_config; test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config); @@ -2230,7 +2221,7 @@ TEST_F(VideoStreamEncoderTest, BitrateLimitsChangeReconfigureRateAllocator) { TEST_F(VideoStreamEncoderTest, IntersectionOfEncoderAndAppBitrateLimitsUsedWhenBothProvided) { video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); const uint32_t kMinEncBitrateKbps = 100; const uint32_t kMaxEncBitrateKbps = 1000; @@ -2280,7 +2271,7 @@ TEST_F(VideoStreamEncoderTest, TEST_F(VideoStreamEncoderTest, ApplyDefaultBitrateLimitsWhenEncoderInfoResolutionBitrateLimitsAreZero) { video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); const uint32_t kMinEncBitrateKbps = 100; const uint32_t kMaxEncBitrateKbps = 1000; const VideoEncoder::ResolutionBitrateLimits encoder_bitrate_limits_180p( @@ -2313,7 +2304,7 @@ TEST_F(VideoStreamEncoderTest, TEST_F(VideoStreamEncoderTest, EncoderAndAppLimitsDontIntersectEncoderLimitsIgnored) { video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); const uint32_t kMinAppBitrateKbps = 100; const uint32_t kMaxAppBitrateKbps = 200; @@ -2347,7 +2338,7 @@ TEST_F(VideoStreamEncoderTest, TEST_F(VideoStreamEncoderTest, EncoderRecommendedMaxAndMinBitratesUsedForGivenResolution) { video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); const VideoEncoder::ResolutionBitrateLimits encoder_bitrate_limits_270p( 480 * 270, 34 * 1000, 12 * 1000, 1234 * 1000); @@ -2415,7 +2406,7 @@ TEST_F(VideoStreamEncoderTest, TEST_F(VideoStreamEncoderTest, EncoderRecommendedMaxBitrateCapsTargetBitrate) { video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); VideoEncoderConfig video_encoder_config; test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config); @@ -2705,8 +2696,8 @@ TEST_F(VideoStreamEncoderTest, TEST_F(VideoStreamEncoderTest, SwitchSourceDeregisterEncoderAsSink) { EXPECT_TRUE(video_source_.has_sinks()); test::FrameForwarder new_video_source; - video_stream_encoder_->SetSource( - &new_video_source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE); + video_stream_encoder_->SetSource(&new_video_source, + DegradationPreference::MAINTAIN_FRAMERATE); EXPECT_FALSE(video_source_.has_sinks()); EXPECT_TRUE(new_video_source.has_sinks()); @@ -2775,7 +2766,7 @@ TEST_F(VideoStreamEncoderTest, RequestInSinkWantsBeforeFirstFrame) { video_encoder_config_.video_stream_factory = nullptr; ConfigureEncoder(video_encoder_config_.Copy()); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); ASSERT_THAT(video_encoder_config_.simulcast_layers, SizeIs(1)); video_encoder_config_.simulcast_layers[0].scale_resolution_down_to.emplace( @@ -2806,13 +2797,13 @@ TEST_F(VideoStreamEncoderTest, RequestInWrongAspectRatioWithAdapter) { video_encoder_config_.video_stream_factory = nullptr; ConfigureEncoder(video_encoder_config_.Copy()); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); // Use a source that adapts resolution based on OnSinkWants. AdaptingFrameForwarder source(&time_controller_); source.set_adaptation_enabled(true); - video_stream_encoder_->SetSource( - &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE); + video_stream_encoder_->SetSource(&source, + DegradationPreference::MAINTAIN_FRAMERATE); ASSERT_THAT(video_encoder_config_.simulcast_layers, SizeIs(1)); video_encoder_config_.simulcast_layers[0].scale_resolution_down_to = { @@ -2855,7 +2846,7 @@ TEST_F(VideoStreamEncoderTest, CorrectlyAdjustsAv1Bitrate) { // Let link allocation and stable bitrate be 2x the target bitrate. video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, 2 * kTargetBitrate, 2 * kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); video_source_.IncomingCapturedFrame( CreateFrame(CurrentTimeMs(), codec_width_, codec_height_)); @@ -2883,8 +2874,7 @@ TEST_F(VideoStreamEncoderTest, CorrectlyAdjustsAv1Bitrate) { // Make sure rate has been reallocated. video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate - DataRate::BitsPerSec(500), 2 * kTargetBitrate, - 2 * kTargetBitrate, 0, 0, 0); + kTargetBitrate - DataRate::BitsPerSec(500), kTargetBitrate, 0, 0, 0); video_source_.IncomingCapturedFrame( CreateFrame(CurrentTimeMs(), codec_width_, codec_height_)); WaitForEncodedFrame(CurrentTimeMs()); @@ -2948,7 +2938,7 @@ TEST_P(ResolutionAlignmentTest, SinkWantsAlignmentApplied) { // available bitrate large enough to get all streams encoded. const DataRate kAvailableBitrate = 3 * kSimulcastTargetBitrate; video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kAvailableBitrate, kAvailableBitrate, kAvailableBitrate, 0, 0, 0); + kAvailableBitrate, kAvailableBitrate, 0, 0, 0); // Wait for all layers before triggering event. sink_.SetNumExpectedLayers(num_streams); @@ -2998,9 +2988,9 @@ TEST_F(VideoStreamEncoderTest, TestCpuDowngrades_BalancedMode) { // Enable BALANCED preference, no initial limitation. video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); video_stream_encoder_->SetSource(&video_source_, - webrtc::DegradationPreference::BALANCED); + DegradationPreference::BALANCED); EXPECT_THAT(video_source_.sink_wants(), WantsFps(Eq(kFramerateFps))); EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution); EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate); @@ -3084,8 +3074,8 @@ TEST_F(VideoStreamEncoderTest, TestCpuDowngrades_BalancedMode) { TEST_F(VideoStreamEncoderTest, SinkWantsNotChangedByResourceLimitedBeforeDegradationPreferenceChange) { - video_stream_encoder_->OnBitrateUpdated(kTargetBitrate, kTargetBitrate, - kTargetBitrate, 0, 0, 0); + video_stream_encoder_->OnBitrateUpdated(kTargetBitrate, kTargetBitrate, 0, 0, + 0); EXPECT_THAT(video_source_.sink_wants(), UnlimitedSinkWants()); const int kFrameWidth = 1280; @@ -3101,8 +3091,8 @@ TEST_F(VideoStreamEncoderTest, stats_proxy_->SetMockStats(stats); video_source_.set_adaptation_enabled(true); - video_stream_encoder_->SetSource( - &video_source_, webrtc::DegradationPreference::MAINTAIN_RESOLUTION); + video_stream_encoder_->SetSource(&video_source_, + DegradationPreference::MAINTAIN_RESOLUTION); EXPECT_THAT(video_source_.sink_wants(), UnlimitedSinkWants()); video_source_.IncomingCapturedFrame( CreateFrame(ntp_time, kFrameWidth, kFrameHeight)); @@ -3128,7 +3118,7 @@ TEST_F(VideoStreamEncoderTest, ntp_time += 100; video_stream_encoder_->SetSourceAndWaitForRestrictionsUpdated( - &video_source_, webrtc::DegradationPreference::MAINTAIN_FRAMERATE); + &video_source_, DegradationPreference::MAINTAIN_FRAMERATE); // Give the encoder queue time to process the change in degradation preference // by waiting for an encoded frame. video_source_.IncomingCapturedFrame( @@ -3163,7 +3153,7 @@ TEST_F(VideoStreamEncoderTest, // Change the degradation preference back. CPU underuse should not adapt since // QP is most limited. video_stream_encoder_->SetSourceAndWaitForRestrictionsUpdated( - &video_source_, webrtc::DegradationPreference::MAINTAIN_RESOLUTION); + &video_source_, DegradationPreference::MAINTAIN_RESOLUTION); video_source_.IncomingCapturedFrame( CreateFrame(ntp_time, kFrameWidth, kFrameHeight)); sink_.WaitForEncodedFrame(ntp_time); @@ -3196,7 +3186,7 @@ TEST_F(VideoStreamEncoderTest, TEST_F(VideoStreamEncoderTest, SinkWantsStoredByDegradationPreference) { video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); EXPECT_THAT(video_source_.sink_wants(), UnlimitedSinkWants()); const int kFrameWidth = 1280; @@ -3226,7 +3216,7 @@ TEST_F(VideoStreamEncoderTest, SinkWantsStoredByDegradationPreference) { // Set new source, switch to maintain-resolution. test::FrameForwarder new_video_source; video_stream_encoder_->SetSourceAndWaitForRestrictionsUpdated( - &new_video_source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION); + &new_video_source, DegradationPreference::MAINTAIN_RESOLUTION); // Give the encoder queue time to process the change in degradation preference // by waiting for an encoded frame. new_video_source.IncomingCapturedFrame( @@ -3257,7 +3247,7 @@ TEST_F(VideoStreamEncoderTest, SinkWantsStoredByDegradationPreference) { // Turn off degradation completely. video_stream_encoder_->SetSourceAndWaitForRestrictionsUpdated( - &new_video_source, webrtc::DegradationPreference::DISABLED); + &new_video_source, DegradationPreference::DISABLED); // Give the encoder queue time to process the change in degradation preference // by waiting for an encoded frame. new_video_source.IncomingCapturedFrame( @@ -3277,7 +3267,7 @@ TEST_F(VideoStreamEncoderTest, SinkWantsStoredByDegradationPreference) { // Calling SetSource with resolution scaling enabled apply the old SinkWants. video_stream_encoder_->SetSourceAndWaitForRestrictionsUpdated( - &new_video_source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE); + &new_video_source, DegradationPreference::MAINTAIN_FRAMERATE); // Give the encoder queue time to process the change in degradation preference // by waiting for an encoded frame. new_video_source.IncomingCapturedFrame( @@ -3291,7 +3281,7 @@ TEST_F(VideoStreamEncoderTest, SinkWantsStoredByDegradationPreference) { // Calling SetSource with framerate scaling enabled apply the old SinkWants. video_stream_encoder_->SetSourceAndWaitForRestrictionsUpdated( - &new_video_source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION); + &new_video_source, DegradationPreference::MAINTAIN_RESOLUTION); // Give the encoder queue time to process the change in degradation preference // by waiting for an encoded frame. new_video_source.IncomingCapturedFrame( @@ -3308,7 +3298,7 @@ TEST_F(VideoStreamEncoderTest, SinkWantsStoredByDegradationPreference) { TEST_F(VideoStreamEncoderTest, StatsTracksQualityAdaptationStats) { video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); const int kWidth = 1280; const int kHeight = 720; @@ -3342,7 +3332,7 @@ TEST_F(VideoStreamEncoderTest, StatsTracksQualityAdaptationStats) { TEST_F(VideoStreamEncoderTest, StatsTracksCpuAdaptationStats) { video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); const int kWidth = 1280; const int kHeight = 720; @@ -3376,7 +3366,7 @@ TEST_F(VideoStreamEncoderTest, StatsTracksCpuAdaptationStats) { TEST_F(VideoStreamEncoderTest, SwitchingSourceKeepsCpuAdaptation) { video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); const int kWidth = 1280; const int kHeight = 720; @@ -3398,8 +3388,8 @@ TEST_F(VideoStreamEncoderTest, SwitchingSourceKeepsCpuAdaptation) { // Set new source with adaptation still enabled. test::FrameForwarder new_video_source; - video_stream_encoder_->SetSource( - &new_video_source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE); + video_stream_encoder_->SetSource(&new_video_source, + DegradationPreference::MAINTAIN_FRAMERATE); new_video_source.IncomingCapturedFrame(CreateFrame(3, kWidth, kHeight)); WaitForEncodedFrame(3); @@ -3410,7 +3400,7 @@ TEST_F(VideoStreamEncoderTest, SwitchingSourceKeepsCpuAdaptation) { // Set adaptation disabled. video_stream_encoder_->SetSource(&new_video_source, - webrtc::DegradationPreference::DISABLED); + DegradationPreference::DISABLED); new_video_source.IncomingCapturedFrame(CreateFrame(4, kWidth, kHeight)); WaitForEncodedFrame(4); @@ -3420,8 +3410,8 @@ TEST_F(VideoStreamEncoderTest, SwitchingSourceKeepsCpuAdaptation) { EXPECT_EQ(1, stats.number_of_cpu_adapt_changes); // Set adaptation back to enabled. - video_stream_encoder_->SetSource( - &new_video_source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE); + video_stream_encoder_->SetSource(&new_video_source, + DegradationPreference::MAINTAIN_FRAMERATE); new_video_source.IncomingCapturedFrame(CreateFrame(5, kWidth, kHeight)); WaitForEncodedFrame(5); @@ -3445,7 +3435,7 @@ TEST_F(VideoStreamEncoderTest, SwitchingSourceKeepsCpuAdaptation) { TEST_F(VideoStreamEncoderTest, SwitchingSourceKeepsQualityAdaptation) { video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); const int kWidth = 1280; const int kHeight = 720; @@ -3459,7 +3449,7 @@ TEST_F(VideoStreamEncoderTest, SwitchingSourceKeepsQualityAdaptation) { // Set new source with adaptation still enabled. test::FrameForwarder new_video_source; video_stream_encoder_->SetSource(&new_video_source, - webrtc::DegradationPreference::BALANCED); + DegradationPreference::BALANCED); new_video_source.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight)); WaitForEncodedFrame(2); @@ -3479,7 +3469,7 @@ TEST_F(VideoStreamEncoderTest, SwitchingSourceKeepsQualityAdaptation) { // Set new source with adaptation still enabled. video_stream_encoder_->SetSource(&new_video_source, - webrtc::DegradationPreference::BALANCED); + DegradationPreference::BALANCED); new_video_source.IncomingCapturedFrame(CreateFrame(4, kWidth, kHeight)); WaitForEncodedFrame(4); @@ -3489,8 +3479,8 @@ TEST_F(VideoStreamEncoderTest, SwitchingSourceKeepsQualityAdaptation) { EXPECT_EQ(1, stats.number_of_quality_adapt_changes); // Disable resolution scaling. - video_stream_encoder_->SetSource( - &new_video_source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION); + video_stream_encoder_->SetSource(&new_video_source, + DegradationPreference::MAINTAIN_RESOLUTION); new_video_source.IncomingCapturedFrame(CreateFrame(5, kWidth, kHeight)); WaitForEncodedFrame(5); @@ -3506,7 +3496,7 @@ TEST_F(VideoStreamEncoderTest, SwitchingSourceKeepsQualityAdaptation) { TEST_F(VideoStreamEncoderTest, QualityAdaptationStatsAreResetWhenScalerIsDisabled) { video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); const int kWidth = 1280; const int kHeight = 720; @@ -3562,7 +3552,7 @@ TEST_F(VideoStreamEncoderTest, TEST_F(VideoStreamEncoderTest, StatsTracksCpuAdaptationStatsWhenSwitchingSource_Balanced) { video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); const int kWidth = 1280; const int kHeight = 720; @@ -3570,8 +3560,7 @@ TEST_F(VideoStreamEncoderTest, // Enable BALANCED preference, no initial limitation. test::FrameForwarder source; - video_stream_encoder_->SetSource(&source, - webrtc::DegradationPreference::BALANCED); + video_stream_encoder_->SetSource(&source, DegradationPreference::BALANCED); source.IncomingCapturedFrame(CreateFrame(sequence, kWidth, kHeight)); WaitForEncodedFrame(sequence++); VideoSendStream::Stats stats = stats_proxy_->GetStats(); @@ -3589,7 +3578,7 @@ TEST_F(VideoStreamEncoderTest, // Set new degradation preference should clear restrictions since we changed // from BALANCED. video_stream_encoder_->SetSourceAndWaitForRestrictionsUpdated( - &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE); + &source, DegradationPreference::MAINTAIN_FRAMERATE); source.IncomingCapturedFrame(CreateFrame(sequence, kWidth, kHeight)); WaitForEncodedFrame(sequence++); stats = stats_proxy_->GetStats(); @@ -3613,7 +3602,7 @@ TEST_F(VideoStreamEncoderTest, // Back to BALANCED, should clear the restrictions again. video_stream_encoder_->SetSourceAndWaitForRestrictionsUpdated( - &source, webrtc::DegradationPreference::BALANCED); + &source, DegradationPreference::BALANCED); source.IncomingCapturedFrame(CreateFrame(sequence, kWidth, kHeight)); WaitForEncodedFrame(sequence++); stats = stats_proxy_->GetStats(); @@ -3627,7 +3616,7 @@ TEST_F(VideoStreamEncoderTest, TEST_F(VideoStreamEncoderTest, StatsTracksCpuAdaptationStatsWhenSwitchingSource) { video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); const int kWidth = 1280; const int kHeight = 720; @@ -3651,8 +3640,8 @@ TEST_F(VideoStreamEncoderTest, // Set new source with adaptation still enabled. test::FrameForwarder new_video_source; - video_stream_encoder_->SetSource( - &new_video_source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE); + video_stream_encoder_->SetSource(&new_video_source, + DegradationPreference::MAINTAIN_FRAMERATE); new_video_source.IncomingCapturedFrame( CreateFrame(sequence, kWidth, kHeight)); @@ -3663,8 +3652,8 @@ TEST_F(VideoStreamEncoderTest, EXPECT_EQ(1, stats.number_of_cpu_adapt_changes); // Set cpu adaptation by frame dropping. - video_stream_encoder_->SetSource( - &new_video_source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION); + video_stream_encoder_->SetSource(&new_video_source, + DegradationPreference::MAINTAIN_RESOLUTION); new_video_source.IncomingCapturedFrame( CreateFrame(sequence, kWidth, kHeight)); WaitForEncodedFrame(sequence++); @@ -3694,7 +3683,7 @@ TEST_F(VideoStreamEncoderTest, // Disable CPU adaptation. video_stream_encoder_->SetSource(&new_video_source, - webrtc::DegradationPreference::DISABLED); + DegradationPreference::DISABLED); new_video_source.IncomingCapturedFrame( CreateFrame(sequence, kWidth, kHeight)); WaitForEncodedFrame(sequence++); @@ -3715,8 +3704,8 @@ TEST_F(VideoStreamEncoderTest, EXPECT_EQ(2, stats.number_of_cpu_adapt_changes); // Switch back the source with resolution adaptation enabled. - video_stream_encoder_->SetSource( - &video_source_, webrtc::DegradationPreference::MAINTAIN_FRAMERATE); + video_stream_encoder_->SetSource(&video_source_, + DegradationPreference::MAINTAIN_FRAMERATE); video_source_.IncomingCapturedFrame(CreateFrame(sequence, kWidth, kHeight)); WaitForEncodedFrame(sequence++); stats = stats_proxy_->GetStats(); @@ -3734,8 +3723,8 @@ TEST_F(VideoStreamEncoderTest, EXPECT_EQ(3, stats.number_of_cpu_adapt_changes); // Back to the source with adaptation off, set it back to maintain-resolution. - video_stream_encoder_->SetSource( - &new_video_source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION); + video_stream_encoder_->SetSource(&new_video_source, + DegradationPreference::MAINTAIN_RESOLUTION); new_video_source.IncomingCapturedFrame( CreateFrame(sequence, kWidth, kHeight)); WaitForEncodedFrame(sequence++); @@ -3764,7 +3753,7 @@ TEST_F(VideoStreamEncoderTest, const int kWidth = 1280; const int kHeight = 720; video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); // Expect no scaling to begin with. EXPECT_THAT(video_source_.sink_wants(), UnlimitedSinkWants()); @@ -3784,8 +3773,8 @@ TEST_F(VideoStreamEncoderTest, // Set resolution scaling disabled. test::FrameForwarder new_video_source; - video_stream_encoder_->SetSource( - &new_video_source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION); + video_stream_encoder_->SetSource(&new_video_source, + DegradationPreference::MAINTAIN_RESOLUTION); // Trigger scale down. video_stream_encoder_->TriggerQualityLow(); @@ -3813,12 +3802,12 @@ TEST_F(VideoStreamEncoderTest, const int kWidth = 1280; const int kHeight = 720; video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); // Enable MAINTAIN_FRAMERATE preference, no initial limitation. test::FrameForwarder source; - video_stream_encoder_->SetSource( - &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE); + video_stream_encoder_->SetSource(&source, + DegradationPreference::MAINTAIN_FRAMERATE); source.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight)); WaitForEncodedFrame(1); @@ -3847,12 +3836,11 @@ TEST_F(VideoStreamEncoderTest, SkipsSameOrLargerAdaptDownRequest_BalancedMode) { const int kWidth = 1280; const int kHeight = 720; video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); // Enable BALANCED preference, no initial limitation. test::FrameForwarder source; - video_stream_encoder_->SetSource(&source, - webrtc::DegradationPreference::BALANCED); + video_stream_encoder_->SetSource(&source, DegradationPreference::BALANCED); source.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight)); sink_.WaitForEncodedFrame(1); EXPECT_THAT(source.sink_wants(), UnlimitedSinkWants()); @@ -3890,13 +3878,12 @@ TEST_F(VideoStreamEncoderTest, const int kWidth = 640; const int kHeight = 360; video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); // Enable BALANCED preference, no initial limitation. AdaptingFrameForwarder source(&time_controller_); source.set_adaptation_enabled(true); - video_stream_encoder_->SetSource(&source, - webrtc::DegradationPreference::BALANCED); + video_stream_encoder_->SetSource(&source, DegradationPreference::BALANCED); int64_t timestamp_ms = kFrameInterval150Ms; source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight)); @@ -3997,13 +3984,12 @@ TEST_F(VideoStreamEncoderTest, const int kHeight = 720; const int64_t kFrameInterval150Ms = 150; video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); // Enable BALANCED preference, no initial limitation. AdaptingFrameForwarder source(&time_controller_); source.set_adaptation_enabled(true); - video_stream_encoder_->SetSource(&source, - webrtc::DegradationPreference::BALANCED); + video_stream_encoder_->SetSource(&source, DegradationPreference::BALANCED); int64_t timestamp_ms = kFrameInterval150Ms; source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight)); @@ -4137,12 +4123,12 @@ TEST_F(VideoStreamEncoderTest, const int kWidth = 1280; const int kHeight = 720; video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); // Enable MAINTAIN_FRAMERATE preference, no initial limitation. test::FrameForwarder source; - video_stream_encoder_->SetSource( - &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE); + video_stream_encoder_->SetSource(&source, + DegradationPreference::MAINTAIN_FRAMERATE); source.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight)); WaitForEncodedFrame(kWidth, kHeight); @@ -4164,12 +4150,12 @@ TEST_F(VideoStreamEncoderTest, const int kWidth = 1280; const int kHeight = 720; video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); // Enable MAINTAIN_RESOLUTION preference, no initial limitation. test::FrameForwarder source; - video_stream_encoder_->SetSource( - &source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION); + video_stream_encoder_->SetSource(&source, + DegradationPreference::MAINTAIN_RESOLUTION); source.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight)); WaitForEncodedFrame(kWidth, kHeight); @@ -4190,12 +4176,11 @@ TEST_F(VideoStreamEncoderTest, NoChangeForInitialNormalUsage_BalancedMode) { const int kWidth = 1280; const int kHeight = 720; video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); // Enable BALANCED preference, no initial limitation. test::FrameForwarder source; - video_stream_encoder_->SetSource(&source, - webrtc::DegradationPreference::BALANCED); + video_stream_encoder_->SetSource(&source, DegradationPreference::BALANCED); source.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight)); sink_.WaitForEncodedFrame(kWidth, kHeight); @@ -4218,12 +4203,11 @@ TEST_F(VideoStreamEncoderTest, NoChangeForInitialNormalUsage_DisabledMode) { const int kWidth = 1280; const int kHeight = 720; video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); // Enable DISABLED preference, no initial limitation. test::FrameForwarder source; - video_stream_encoder_->SetSource(&source, - webrtc::DegradationPreference::DISABLED); + video_stream_encoder_->SetSource(&source, DegradationPreference::DISABLED); source.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight)); sink_.WaitForEncodedFrame(kWidth, kHeight); @@ -4247,13 +4231,13 @@ TEST_F(VideoStreamEncoderTest, const int kWidth = 1280; const int kHeight = 720; video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); // Enable MAINTAIN_FRAMERATE preference, no initial limitation. AdaptingFrameForwarder source(&time_controller_); source.set_adaptation_enabled(true); - video_stream_encoder_->SetSource( - &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE); + video_stream_encoder_->SetSource(&source, + DegradationPreference::MAINTAIN_FRAMERATE); source.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight)); WaitForEncodedFrame(1); @@ -4286,7 +4270,7 @@ TEST_F(VideoStreamEncoderTest, const int kHeight = 720; const int kInputFps = 30; video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); VideoSendStream::Stats stats = stats_proxy_->GetStats(); stats.input_frame_rate = kInputFps; @@ -4307,7 +4291,7 @@ TEST_F(VideoStreamEncoderTest, // Enable MAINTAIN_RESOLUTION preference. test::FrameForwarder new_video_source; video_stream_encoder_->SetSourceAndWaitForRestrictionsUpdated( - &new_video_source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION); + &new_video_source, DegradationPreference::MAINTAIN_RESOLUTION); // Give the encoder queue time to process the change in degradation preference // by waiting for an encoded frame. new_video_source.IncomingCapturedFrame(CreateFrame(3, kWidth, kHeight)); @@ -4334,7 +4318,7 @@ TEST_F(VideoStreamEncoderTest, DoesNotScaleBelowSetResolutionLimit) { const size_t kNumFrames = 10; video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); // Enable adapter, expected input resolutions when downscaling: // 1280x720 -> 960x540 -> 640x360 -> 480x270 -> 320x180 (kMinPixelsPerFrame) @@ -4370,13 +4354,13 @@ TEST_F(VideoStreamEncoderTest, const int kWidth = 1280; const int kHeight = 720; video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); // Enable MAINTAIN_FRAMERATE preference, no initial limitation. AdaptingFrameForwarder source(&time_controller_); source.set_adaptation_enabled(true); - video_stream_encoder_->SetSource( - &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE); + video_stream_encoder_->SetSource(&source, + DegradationPreference::MAINTAIN_FRAMERATE); int64_t timestamp_ms = kFrameIntervalMs; source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight)); @@ -4431,13 +4415,12 @@ TEST_F(VideoStreamEncoderTest, const int kWidth = 1280; const int kHeight = 720; video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); // Enable BALANCED preference, no initial limitation. AdaptingFrameForwarder source(&time_controller_); source.set_adaptation_enabled(true); - video_stream_encoder_->SetSource(&source, - webrtc::DegradationPreference::BALANCED); + video_stream_encoder_->SetSource(&source, DegradationPreference::BALANCED); int64_t timestamp_ms = kFrameIntervalMs; source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight)); @@ -4492,7 +4475,6 @@ TEST_F(VideoStreamEncoderTest, AdaptUpIfBwEstimateIsHigherThanMinBitrate) { {kEncoderBitrateLimits540p, kEncoderBitrateLimits720p}); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - DataRate::BitsPerSec(kEncoderBitrateLimits720p.min_start_bitrate_bps), DataRate::BitsPerSec(kEncoderBitrateLimits720p.min_start_bitrate_bps), DataRate::BitsPerSec(kEncoderBitrateLimits720p.min_start_bitrate_bps), 0, 0, 0); @@ -4500,8 +4482,8 @@ TEST_F(VideoStreamEncoderTest, AdaptUpIfBwEstimateIsHigherThanMinBitrate) { // Enable MAINTAIN_FRAMERATE preference, no initial limitation. AdaptingFrameForwarder source(&time_controller_); source.set_adaptation_enabled(true); - video_stream_encoder_->SetSource( - &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE); + video_stream_encoder_->SetSource(&source, + DegradationPreference::MAINTAIN_FRAMERATE); // Insert 720p frame. int64_t timestamp_ms = kFrameIntervalMs; @@ -4510,7 +4492,6 @@ TEST_F(VideoStreamEncoderTest, AdaptUpIfBwEstimateIsHigherThanMinBitrate) { // Reduce bitrate and trigger adapt down. video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - DataRate::BitsPerSec(kEncoderBitrateLimits540p.min_start_bitrate_bps), DataRate::BitsPerSec(kEncoderBitrateLimits540p.min_start_bitrate_bps), DataRate::BitsPerSec(kEncoderBitrateLimits540p.min_start_bitrate_bps), 0, 0, 0); @@ -4529,7 +4510,6 @@ TEST_F(VideoStreamEncoderTest, AdaptUpIfBwEstimateIsHigherThanMinBitrate) { // Increase bitrate. video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - DataRate::BitsPerSec(kEncoderBitrateLimits720p.min_start_bitrate_bps), DataRate::BitsPerSec(kEncoderBitrateLimits720p.min_start_bitrate_bps), DataRate::BitsPerSec(kEncoderBitrateLimits720p.min_start_bitrate_bps), 0, 0, 0); @@ -4547,7 +4527,6 @@ TEST_F(VideoStreamEncoderTest, DropFirstFramesIfBwEstimateIsTooLow) { // Set bitrate equal to min bitrate of 540p. video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - DataRate::BitsPerSec(kEncoderBitrateLimits540p.min_start_bitrate_bps), DataRate::BitsPerSec(kEncoderBitrateLimits540p.min_start_bitrate_bps), DataRate::BitsPerSec(kEncoderBitrateLimits540p.min_start_bitrate_bps), 0, 0, 0); @@ -4555,8 +4534,8 @@ TEST_F(VideoStreamEncoderTest, DropFirstFramesIfBwEstimateIsTooLow) { // Enable MAINTAIN_FRAMERATE preference, no initial limitation. AdaptingFrameForwarder source(&time_controller_); source.set_adaptation_enabled(true); - video_stream_encoder_->SetSource( - &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE); + video_stream_encoder_->SetSource(&source, + DegradationPreference::MAINTAIN_FRAMERATE); // Insert 720p frame. It should be dropped and lower resolution should be // requested. @@ -4589,7 +4568,7 @@ class BalancedDegradationTest : public VideoStreamEncoderTest { void OnBitrateUpdated(DataRate bitrate) { video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - bitrate, bitrate, bitrate, 0, 0, 0); + bitrate, bitrate, 0, 0, 0); } void InsertFrame() { @@ -4882,13 +4861,13 @@ TEST_F(VideoStreamEncoderTest, const int kWidth = 1280; const int kHeight = 720; video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); // Enable MAINTAIN_FRAMERATE preference, no initial limitation. AdaptingFrameForwarder source(&time_controller_); source.set_adaptation_enabled(true); - video_stream_encoder_->SetSource( - &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE); + video_stream_encoder_->SetSource(&source, + DegradationPreference::MAINTAIN_FRAMERATE); int64_t timestamp_ms = kFrameIntervalMs; source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight)); @@ -5035,7 +5014,7 @@ TEST_F(VideoStreamEncoderTest, CpuLimitedHistogramIsReported) { int64_t ntp_timestamp_ms = 123; video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); for (int i = 1; i <= SendStatisticsProxy::kMinRequiredMetricsSamples; ++i) { video_source_.IncomingCapturedFrame( @@ -5065,13 +5044,13 @@ TEST_F(VideoStreamEncoderTest, CpuLimitedHistogramIsReported) { TEST_F(VideoStreamEncoderTest, CpuLimitedHistogramIsNotReportedForDisabledDegradation) { video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); const int kWidth = 640; const int kHeight = 360; int64_t ntp_timestamp_ms = 123; video_stream_encoder_->SetSource(&video_source_, - webrtc::DegradationPreference::DISABLED); + DegradationPreference::DISABLED); for (int i = 1; i <= SendStatisticsProxy::kMinRequiredMetricsSamples; ++i) { video_source_.IncomingCapturedFrame( @@ -5100,7 +5079,7 @@ TEST_F(VideoStreamEncoderTest, ReportsVideoBitrateAllocation) { kDefaultFps)); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kLowTargetBitrate, kLowTargetBitrate, kLowTargetBitrate, 0, 0, 0); + kLowTargetBitrate, kLowTargetBitrate, 0, 0, 0); video_source_.IncomingCapturedFrame( CreateFrame(CurrentTimeMs(), codec_width_, codec_height_)); @@ -5141,7 +5120,7 @@ TEST_F(VideoStreamEncoderTest, ReportsVideoLayersAllocationForVP8Simulcast) { const int kDefaultFps = 30; video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kLowTargetBitrate, kLowTargetBitrate, kLowTargetBitrate, 0, 0, 0); + kLowTargetBitrate, kLowTargetBitrate, 0, 0, 0); video_source_.IncomingCapturedFrame( CreateFrame(CurrentTimeMs(), codec_width_, codec_height_)); @@ -5209,7 +5188,7 @@ TEST_F(VideoStreamEncoderTest, kVideoLayersAllocation); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); video_source_.IncomingCapturedFrame(CreateFrame(CurrentTimeMs(), 1280, 720)); WaitForEncodedFrame(CurrentTimeMs()); @@ -5252,7 +5231,7 @@ TEST_F(VideoStreamEncoderTest, kVideoLayersAllocation); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); video_source_.IncomingCapturedFrame(CreateFrame(CurrentTimeMs(), 1280, 720)); WaitForEncodedFrame(CurrentTimeMs()); @@ -5292,7 +5271,7 @@ TEST_F(VideoStreamEncoderTest, kVideoLayersAllocation); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); video_source_.IncomingCapturedFrame(CreateFrame(CurrentTimeMs(), 1280, 720)); WaitForEncodedFrame(CurrentTimeMs()); @@ -5345,7 +5324,7 @@ TEST_F(VideoStreamEncoderTest, kVideoLayersAllocation); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); video_source_.IncomingCapturedFrame(CreateFrame(CurrentTimeMs(), 1280, 720)); WaitForEncodedFrame(CurrentTimeMs()); @@ -5391,7 +5370,7 @@ TEST_F(VideoStreamEncoderTest, kVideoLayersAllocation); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); video_source_.IncomingCapturedFrame(CreateFrame(CurrentTimeMs(), 1280, 720)); WaitForEncodedFrame(CurrentTimeMs()); @@ -5442,7 +5421,7 @@ TEST_F(VideoStreamEncoderTest, kVideoLayersAllocation); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); video_source_.IncomingCapturedFrame(CreateFrame(CurrentTimeMs(), 1280, 720)); WaitForEncodedFrame(CurrentTimeMs()); @@ -5497,7 +5476,7 @@ TEST_F(VideoStreamEncoderTest, kVideoLayersAllocation); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); video_source_.IncomingCapturedFrame(CreateFrame(CurrentTimeMs(), 1280, 720)); WaitForEncodedFrame(CurrentTimeMs()); @@ -5549,7 +5528,7 @@ TEST_F(VideoStreamEncoderTest, kVideoLayersAllocation); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); video_source_.IncomingCapturedFrame(CreateFrame(CurrentTimeMs(), 1280, 720)); WaitForEncodedFrame(CurrentTimeMs()); @@ -5574,7 +5553,7 @@ TEST_F(VideoStreamEncoderTest, ReportsVideoLayersAllocationForH264) { VideoStreamEncoder::BitrateAllocationCallbackType:: kVideoLayersAllocation); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); video_source_.IncomingCapturedFrame(CreateFrame(CurrentTimeMs(), 1280, 720)); WaitForEncodedFrame(CurrentTimeMs()); @@ -5603,7 +5582,7 @@ TEST_F(VideoStreamEncoderTest, kVideoLayersAllocation); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kLowTargetBitrate, kLowTargetBitrate, kLowTargetBitrate, 0, 0, 0); + kLowTargetBitrate, kLowTargetBitrate, 0, 0, 0); video_source_.IncomingCapturedFrame( CreateFrame(CurrentTimeMs(), codec_width_, codec_height_)); @@ -5618,8 +5597,7 @@ TEST_F(VideoStreamEncoderTest, kLowTargetBitrate); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kSimulcastTargetBitrate, kSimulcastTargetBitrate, kSimulcastTargetBitrate, - 0, 0, 0); + kSimulcastTargetBitrate, kSimulcastTargetBitrate, 0, 0, 0); video_source_.IncomingCapturedFrame( CreateFrame(CurrentTimeMs(), codec_width_, codec_height_)); WaitForEncodedFrame(CurrentTimeMs()); @@ -5642,8 +5620,7 @@ TEST_F(VideoStreamEncoderTest, kVideoLayersAllocation); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kSimulcastTargetBitrate, kSimulcastTargetBitrate, kSimulcastTargetBitrate, - 0, 0, 0); + kSimulcastTargetBitrate, kSimulcastTargetBitrate, 0, 0, 0); video_source_.IncomingCapturedFrame( CreateFrame(CurrentTimeMs(), codec_width_, codec_height_)); @@ -5682,14 +5659,14 @@ TEST_F(VideoStreamEncoderTest, TemporalLayersNotDisabledIfSupported) { fake_encoder_.SetTemporalLayersSupported(0, true); // Bitrate allocated across temporal layers. - const int kTl0Bps = kTargetBitrate.bps() * - webrtc::SimulcastRateAllocator::GetTemporalRateAllocation( - kNumTemporalLayers, /*temporal_id*/ 0, - /*base_heavy_tl3_alloc*/ false); - const int kTl1Bps = kTargetBitrate.bps() * - webrtc::SimulcastRateAllocator::GetTemporalRateAllocation( - kNumTemporalLayers, /*temporal_id*/ 1, - /*base_heavy_tl3_alloc*/ false); + const int kTl0Bps = + kTargetBitrate.bps() * SimulcastRateAllocator::GetTemporalRateAllocation( + kNumTemporalLayers, /*temporal_id*/ 0, + /*base_heavy_tl3_alloc*/ false); + const int kTl1Bps = + kTargetBitrate.bps() * SimulcastRateAllocator::GetTemporalRateAllocation( + kNumTemporalLayers, /*temporal_id*/ 1, + /*base_heavy_tl3_alloc*/ false); VideoBitrateAllocation expected_bitrate; expected_bitrate.SetBitrate(/*si*/ 0, /*ti*/ 0, kTl0Bps); expected_bitrate.SetBitrate(/*si*/ 0, /*ti*/ 1, kTl1Bps - kTl0Bps); @@ -5716,7 +5693,7 @@ TEST_F(VideoStreamEncoderTest, TemporalLayersDisabledIfNotSupported) { } TEST_F(VideoStreamEncoderTest, VerifyBitrateAllocationForTwoStreams) { - webrtc::test::ScopedKeyValueConfig field_trials( + test::ScopedKeyValueConfig field_trials( field_trials_, "WebRTC-Video-QualityScalerSettings/" "initial_bitrate_interval_ms:1000,initial_bitrate_factor:0.2/"); @@ -5734,11 +5711,11 @@ TEST_F(VideoStreamEncoderTest, VerifyBitrateAllocationForTwoStreams) { const int kS0Bps = 150000; const int kS0Tl0Bps = kS0Bps * - webrtc::SimulcastRateAllocator::GetTemporalRateAllocation( + SimulcastRateAllocator::GetTemporalRateAllocation( /*num_layers*/ 2, /*temporal_id*/ 0, /*base_heavy_tl3_alloc*/ false); const int kS0Tl1Bps = kS0Bps * - webrtc::SimulcastRateAllocator::GetTemporalRateAllocation( + SimulcastRateAllocator::GetTemporalRateAllocation( /*num_layers*/ 2, /*temporal_id*/ 1, /*base_heavy_tl3_alloc*/ false); const int kS1Bps = kTargetBitrate.bps() - kS0Tl1Bps; // Temporal layers not supported by si:1. @@ -5757,10 +5734,10 @@ TEST_F(VideoStreamEncoderTest, OveruseDetectorUpdatedOnReconfigureAndAdaption) { const int kFramerate = 24; video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); test::FrameForwarder source; - video_stream_encoder_->SetSource( - &source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION); + video_stream_encoder_->SetSource(&source, + DegradationPreference::MAINTAIN_RESOLUTION); // Insert a single frame, triggering initial configuration. source.IncomingCapturedFrame(CreateFrame(1, kFrameWidth, kFrameHeight)); @@ -5816,10 +5793,10 @@ TEST_F(VideoStreamEncoderTest, const int kHighFramerate = 25; video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); test::FrameForwarder source; - video_stream_encoder_->SetSource( - &source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION); + video_stream_encoder_->SetSource(&source, + DegradationPreference::MAINTAIN_RESOLUTION); // Trigger initial configuration. VideoEncoderConfig video_encoder_config; @@ -5877,10 +5854,10 @@ TEST_F(VideoStreamEncoderTest, const int kFramerate = 24; video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); test::FrameForwarder source; - video_stream_encoder_->SetSource( - &source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION); + video_stream_encoder_->SetSource(&source, + DegradationPreference::MAINTAIN_RESOLUTION); // Trigger initial configuration. VideoEncoderConfig video_encoder_config; @@ -5909,7 +5886,7 @@ TEST_F(VideoStreamEncoderTest, // Change degradation preference to not enable framerate scaling. Target // framerate should be changed to codec defined limit. video_stream_encoder_->SetSourceAndWaitForFramerateUpdated( - &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE); + &source, DegradationPreference::MAINTAIN_FRAMERATE); EXPECT_EQ( video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate(), kFramerate); @@ -5920,7 +5897,6 @@ TEST_F(VideoStreamEncoderTest, TEST_F(VideoStreamEncoderTest, DropsFramesAndScalesWhenBitrateIsTooLow) { const int kTooLowBitrateForFrameSizeBps = 10000; video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps), DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps), DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps), 0, 0, 0); const int kWidth = 640; @@ -5958,7 +5934,6 @@ TEST_F(VideoStreamEncoderTest, NumberOfDroppedFramesLimitedWhenBitrateIsTooLow) { const int kTooLowBitrateForFrameSizeBps = 10000; video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps), DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps), DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps), 0, 0, 0); const int kWidth = 640; @@ -5985,11 +5960,11 @@ TEST_F(VideoStreamEncoderTest, const int kWidth = 640; const int kHeight = 360; video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kLowTargetBitrate, kLowTargetBitrate, kLowTargetBitrate, 0, 0, 0); + kLowTargetBitrate, kLowTargetBitrate, 0, 0, 0); // Set degradation preference. - video_stream_encoder_->SetSource( - &video_source_, webrtc::DegradationPreference::MAINTAIN_RESOLUTION); + video_stream_encoder_->SetSource(&video_source_, + DegradationPreference::MAINTAIN_RESOLUTION); video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight)); // Frame should not be dropped, even if it's too large. @@ -6010,11 +5985,11 @@ TEST_F(VideoStreamEncoderTest, InitialFrameDropOffWhenEncoderDisabledScaling) { video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config), kMaxPayloadLength); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kLowTargetBitrate, kLowTargetBitrate, kLowTargetBitrate, 0, 0, 0); + kLowTargetBitrate, kLowTargetBitrate, 0, 0, 0); // Force quality scaler reconfiguration by resetting the source. video_stream_encoder_->SetSource(&video_source_, - webrtc::DegradationPreference::BALANCED); + DegradationPreference::BALANCED); video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight)); // Frame should not be dropped, even if it's too large. @@ -6025,7 +6000,7 @@ TEST_F(VideoStreamEncoderTest, InitialFrameDropOffWhenEncoderDisabledScaling) { } TEST_F(VideoStreamEncoderTest, InitialFrameDropActivatesWhenBweDrops) { - webrtc::test::ScopedKeyValueConfig field_trials( + test::ScopedKeyValueConfig field_trials( field_trials_, "WebRTC-Video-QualityScalerSettings/" "initial_bitrate_interval_ms:1000,initial_bitrate_factor:0.2/"); @@ -6037,13 +6012,12 @@ TEST_F(VideoStreamEncoderTest, InitialFrameDropActivatesWhenBweDrops) { const int kHeight = 360; video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight)); // Frame should not be dropped. WaitForEncodedFrame(1); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - DataRate::BitsPerSec(kNotTooLowBitrateForFrameSizeBps), DataRate::BitsPerSec(kNotTooLowBitrateForFrameSizeBps), DataRate::BitsPerSec(kNotTooLowBitrateForFrameSizeBps), 0, 0, 0); video_source_.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight)); @@ -6051,7 +6025,6 @@ TEST_F(VideoStreamEncoderTest, InitialFrameDropActivatesWhenBweDrops) { WaitForEncodedFrame(2); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps), DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps), DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps), 0, 0, 0); video_source_.IncomingCapturedFrame(CreateFrame(3, kWidth, kHeight)); @@ -6068,7 +6041,7 @@ TEST_F(VideoStreamEncoderTest, InitialFrameDropActivatesWhenBweDrops) { TEST_F(VideoStreamEncoderTest, InitialFrameDropNotReactivatedWhenBweDropsWhenScalingDisabled) { - webrtc::test::ScopedKeyValueConfig field_trials( + test::ScopedKeyValueConfig field_trials( field_trials_, "WebRTC-Video-QualityScalerSettings/" "initial_bitrate_interval_ms:1000,initial_bitrate_factor:0.2/"); @@ -6080,13 +6053,12 @@ TEST_F(VideoStreamEncoderTest, const int kHeight = 360; video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight)); // Frame should not be dropped. WaitForEncodedFrame(1); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - DataRate::BitsPerSec(kNotTooLowBitrateForFrameSizeBps), DataRate::BitsPerSec(kNotTooLowBitrateForFrameSizeBps), DataRate::BitsPerSec(kNotTooLowBitrateForFrameSizeBps), 0, 0, 0); video_source_.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight)); @@ -6094,7 +6066,6 @@ TEST_F(VideoStreamEncoderTest, WaitForEncodedFrame(2); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps), DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps), DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps), 0, 0, 0); video_source_.IncomingCapturedFrame(CreateFrame(3, kWidth, kHeight)); @@ -6130,8 +6101,7 @@ TEST_F(VideoStreamEncoderTest, InitialFrameDropAccountsForResolutionScaling) { // Bitrate is not enough for 720p. video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - DataRate::KilobitsPerSec(30), DataRate::KilobitsPerSec(30), - DataRate::KilobitsPerSec(30), 0, 0, 0); + DataRate::KilobitsPerSec(30), DataRate::KilobitsPerSec(30), 0, 0, 0); // Pass 720p frame. Resolution scaling factor is set to 4 which means that // the target encode resolution is 180p. The default initial frame dropping @@ -6150,7 +6120,6 @@ TEST_F(VideoStreamEncoderTest, InitialFrameDropActivatesWhenLayersChange) { const int kHeight = 720; video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( /*target_bitrate=*/DataRate::KilobitsPerSec(400), - /*stable_target_bitrate=*/DataRate::KilobitsPerSec(400), /*link_allocation=*/DataRate::KilobitsPerSec(400), /*fraction_lost=*/0, /*round_trip_time_ms=*/0, @@ -6214,7 +6183,7 @@ TEST_F(VideoStreamEncoderTest, InitialFrameDropActivatesWhenSVCLayersChange) { const int kHeight = 720; video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( /*target_bitrate=*/DataRate::KilobitsPerSec(400), - /*stable_target_bitrate=*/DataRate::KilobitsPerSec(400), + /*link_allocation=*/DataRate::KilobitsPerSec(400), /*fraction_lost=*/0, /*round_trip_time_ms=*/0, @@ -6401,7 +6370,7 @@ TEST_F(VideoStreamEncoderTest, } TEST_F(VideoStreamEncoderTest, DefaultMaxAndMinBitratesNotUsedIfDisabled) { - webrtc::test::ScopedKeyValueConfig field_trials( + test::ScopedKeyValueConfig field_trials( field_trials_, "WebRTC-DefaultBitrateLimitsKillSwitch/Enabled/"); VideoEncoderConfig video_encoder_config; test::FillEncoderConfiguration(PayloadStringToCodecType("VP9"), 1, @@ -6596,14 +6565,14 @@ TEST_P(VideoStreamEncoderInitialFrameDropperTest, SetEncoderFrameSize(kWidth / 2, kHeight / 2); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); video_source_.IncomingCapturedFrame( CreateFrame(1, captureWidth, captureHeight)); // Frame should not be dropped. WaitForEncodedFrame(1); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kLowTargetBitrate, kLowTargetBitrate, kLowTargetBitrate, 0, 0, 0); + kLowTargetBitrate, kLowTargetBitrate, 0, 0, 0); video_source_.IncomingCapturedFrame( CreateFrame(2, captureWidth, captureHeight)); // Frame should not be dropped, bitrate not too low for frame. @@ -6634,8 +6603,8 @@ TEST_P(VideoStreamEncoderInitialFrameDropperTest, AdaptingFrameForwarder source(&time_controller_); source.set_adaptation_enabled(true); - video_stream_encoder_->SetSource( - &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE); + video_stream_encoder_->SetSource(&source, + DegradationPreference::MAINTAIN_FRAMERATE); int timestamp = 1; @@ -6644,7 +6613,7 @@ TEST_P(VideoStreamEncoderInitialFrameDropperTest, SetEncoderFrameSize(kWidth, kHeight); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); source.IncomingCapturedFrame( CreateFrame(timestamp, captureWidth, captureHeight)); WaitForEncodedFrame(timestamp); @@ -6653,7 +6622,7 @@ TEST_P(VideoStreamEncoderInitialFrameDropperTest, AdvanceTime(TimeDelta::Millis(1000)); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kLowTargetBitrate, kLowTargetBitrate, kLowTargetBitrate, 0, 0, 0); + kLowTargetBitrate, kLowTargetBitrate, 0, 0, 0); source.IncomingCapturedFrame( CreateFrame(timestamp, captureWidth, captureHeight)); // Not dropped frame, as initial frame drop is disabled by now. @@ -6702,7 +6671,6 @@ TEST_P(VideoStreamEncoderInitialFrameDropperTest, video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( DataRate::BitsPerSec(kMinStartBps360p - 1), // target_bitrate - DataRate::BitsPerSec(kMinStartBps360p - 1), // stable_target_bitrate DataRate::BitsPerSec(kMinStartBps360p - 1), // link_allocation 0, 0, 0); @@ -6739,7 +6707,6 @@ TEST_P(VideoStreamEncoderInitialFrameDropperTest, video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( DataRate::BitsPerSec(kMinStartBps360p - 1), // target_bitrate - DataRate::BitsPerSec(kMinStartBps360p - 1), // stable_target_bitrate DataRate::BitsPerSec(kMinStartBps360p), // link_allocation 0, 0, 0); @@ -6766,14 +6733,14 @@ TEST_P(VideoStreamEncoderInitialFrameDropperTest, TEST_F(VideoStreamEncoderTest, QualityScalerAdaptationsRemovedWhenQualityScalingDisabled) { - webrtc::test::ScopedKeyValueConfig field_trials( + test::ScopedKeyValueConfig field_trials( field_trials_, "WebRTC-Video-QualityScaling/Disabled/"); AdaptingFrameForwarder source(&time_controller_); source.set_adaptation_enabled(true); video_stream_encoder_->SetSource(&source, DegradationPreference::MAINTAIN_FRAMERATE); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); fake_encoder_.SetQp(kQpHigh + 1); const int kWidth = 1280; const int kHeight = 720; @@ -6790,8 +6757,7 @@ TEST_F(VideoStreamEncoderTest, // time. EXPECT_THAT( WaitUntil([&] { return stats_proxy_->GetStats().bw_limited_resolution; }, - IsTrue(), - {.timeout = webrtc::TimeDelta::Millis(2000 * 2.5 * 2)}), + IsTrue(), {.timeout = TimeDelta::Millis(2000 * 2.5 * 2)}), IsRtcOk()); timestamp_ms += kFrameInterval100Ms; source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight)); @@ -6820,12 +6786,12 @@ TEST_F(VideoStreamEncoderTest, const int kTooSmallWidth = 10; const int kTooSmallHeight = 10; video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); // Enable MAINTAIN_FRAMERATE preference, no initial limitation. test::FrameForwarder source; - video_stream_encoder_->SetSource( - &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE); + video_stream_encoder_->SetSource(&source, + DegradationPreference::MAINTAIN_FRAMERATE); EXPECT_THAT(source.sink_wants(), UnlimitedSinkWants()); EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution); @@ -6846,12 +6812,11 @@ TEST_F(VideoStreamEncoderTest, const int kTooSmallHeight = 10; const int kFpsLimit = 7; video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); // Enable BALANCED preference, no initial limitation. test::FrameForwarder source; - video_stream_encoder_->SetSource(&source, - webrtc::DegradationPreference::BALANCED); + video_stream_encoder_->SetSource(&source, DegradationPreference::BALANCED); EXPECT_THAT(source.sink_wants(), UnlimitedSinkWants()); EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution); EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate); @@ -6880,7 +6845,7 @@ TEST_F(VideoStreamEncoderTest, TEST_F(VideoStreamEncoderTest, FailingInitEncodeDoesntCauseCrash) { fake_encoder_.ForceInitEncodeFailure(true); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); ResetEncoder("VP8", 2, 1, 1, false); const int kFrameWidth = 1280; const int kFrameHeight = 720; @@ -6894,7 +6859,7 @@ TEST_F(VideoStreamEncoderTest, FailingInitEncodeDoesntCauseCrash) { TEST_F(VideoStreamEncoderTest, AdaptsResolutionOnOveruse_MaintainFramerateMode) { video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); const int kFrameWidth = 1280; const int kFrameHeight = 720; @@ -6928,9 +6893,9 @@ TEST_F(VideoStreamEncoderTest, const int kFrameHeight = 720; video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); - video_stream_encoder_->SetSource( - &video_source_, webrtc::DegradationPreference::MAINTAIN_RESOLUTION); + kTargetBitrate, kTargetBitrate, 0, 0, 0); + video_stream_encoder_->SetSource(&video_source_, + DegradationPreference::MAINTAIN_RESOLUTION); video_source_.set_adaptation_enabled(true); int64_t timestamp_ms = CurrentTimeMs(); @@ -7030,9 +6995,9 @@ TEST_F(VideoStreamEncoderTest, DoesntAdaptDownPastMinFramerate) { ResetEncoder("VP8", 1, 2, 1, true); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); - video_stream_encoder_->SetSource( - &video_source_, webrtc::DegradationPreference::MAINTAIN_RESOLUTION); + kTargetBitrate, kTargetBitrate, 0, 0, 0); + video_stream_encoder_->SetSource(&video_source_, + DegradationPreference::MAINTAIN_RESOLUTION); video_source_.set_adaptation_enabled(true); int64_t timestamp_ms = CurrentTimeMs(); @@ -7075,13 +7040,12 @@ TEST_F(VideoStreamEncoderTest, video_encoder_config_.simulcast_layers[0].max_framerate = kDefaultFramerate; ConfigureEncoder(video_encoder_config_.Copy()); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); // Enable BALANCED preference, no initial limitation. AdaptingFrameForwarder source(&time_controller_); source.set_adaptation_enabled(true); - video_stream_encoder_->SetSource(&source, - webrtc::DegradationPreference::BALANCED); + video_stream_encoder_->SetSource(&source, DegradationPreference::BALANCED); timestamp_ms += kFrameInterval150Ms; source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight)); WaitForEncodedFrame(kWidth, kHeight); @@ -7264,13 +7228,12 @@ TEST_F(VideoStreamEncoderTest, AdaptWithTwoReasonsAndDifferentOrder_Framerate) { video_encoder_config_.simulcast_layers[0].max_framerate = kDefaultFramerate; ConfigureEncoder(video_encoder_config_.Copy()); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); // Enable BALANCED preference, no initial limitation. AdaptingFrameForwarder source(&time_controller_); source.set_adaptation_enabled(true); - video_stream_encoder_->SetSource(&source, - webrtc::DegradationPreference::BALANCED); + video_stream_encoder_->SetSource(&source, DegradationPreference::BALANCED); timestamp_ms += kFrameInterval150Ms; source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight)); WaitForEncodedFrame(kWidth, kHeight); @@ -7402,13 +7365,12 @@ TEST_F(VideoStreamEncoderTest, ConfigureEncoder(video_encoder_config_.Copy()); int64_t timestamp_ms = kFrameInterval150Ms; video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); // Enable BALANCED preference, no initial limitation. AdaptingFrameForwarder source(&time_controller_); source.set_adaptation_enabled(true); - video_stream_encoder_->SetSource(&source, - webrtc::DegradationPreference::BALANCED); + video_stream_encoder_->SetSource(&source, DegradationPreference::BALANCED); timestamp_ms += kFrameInterval150Ms; source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight)); WaitForEncodedFrame(kWidth, kHeight); @@ -7507,7 +7469,7 @@ TEST_F(VideoStreamEncoderTest, AcceptsFullHdAdaptedDownSimulcastFrames) { uint64_t ntp_time_ms = 123; video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); // Trigger reconfigure encoder (without resetting the entire instance). VideoEncoderConfig video_encoder_config; test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config); @@ -7542,7 +7504,7 @@ TEST_F(VideoStreamEncoderTest, PeriodicallyUpdatesChannelParameters) { const int kHighFps = 30; video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); int64_t timestamp_ms = CurrentTimeMs(); max_framerate_ = kLowFps; @@ -7557,7 +7519,7 @@ TEST_F(VideoStreamEncoderTest, PeriodicallyUpdatesChannelParameters) { // Make sure encoder is updated with new target. video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); video_source_.IncomingCapturedFrame( CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight)); WaitForEncodedFrame(timestamp_ms); @@ -7595,7 +7557,7 @@ TEST_F(VideoStreamEncoderTest, DoesNotUpdateBitrateAllocationWhenSuspended) { kVideoBitrateAllocation); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); video_stream_encoder_->WaitUntilTaskQueueIsIdle(); // Insert a first video frame, causes another bitrate update. @@ -7607,7 +7569,7 @@ TEST_F(VideoStreamEncoderTest, DoesNotUpdateBitrateAllocationWhenSuspended) { // Next, simulate video suspension due to pacer queue overrun. video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - DataRate::Zero(), DataRate::Zero(), DataRate::Zero(), 0, 1, 0); + DataRate::Zero(), DataRate::Zero(), 0, 1, 0); // Skip ahead until a new periodic parameter update should have occured. timestamp_ms += kProcessIntervalMs; @@ -7628,7 +7590,7 @@ TEST_F(VideoStreamEncoderTest, const int kFrameHeight = 720; const CpuOveruseOptions default_options; video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); video_source_.IncomingCapturedFrame( CreateFrame(1, kFrameWidth, kFrameHeight)); WaitForEncodedFrame(1); @@ -7651,7 +7613,7 @@ TEST_F(VideoStreamEncoderTest, fake_encoder_.SetIsHardwareAccelerated(true); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); video_source_.IncomingCapturedFrame( CreateFrame(1, kFrameWidth, kFrameHeight)); WaitForEncodedFrame(1); @@ -7671,7 +7633,7 @@ TEST_F(VideoStreamEncoderTest, const CpuOveruseOptions default_options; video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); video_source_.IncomingCapturedFrame( CreateFrame(1, kFrameWidth, kFrameHeight)); WaitForEncodedFrame(1); @@ -7709,7 +7671,7 @@ TEST_F(VideoStreamEncoderTest, DropsFramesWhenEncoderOvershoots) { video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( /*target_bitrate=*/DataRate::KilobitsPerSec(120), - /*stable_target_bitrate=*/DataRate::KilobitsPerSec(120), + /*link_allocation=*/DataRate::KilobitsPerSec(120), /*fraction_lost=*/0, /*round_trip_time_ms=*/0, @@ -7788,7 +7750,7 @@ TEST_F(VideoStreamEncoderTest, ConfiguresCorrectFrameRate) { max_framerate_ = kActualInputFps; video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( /*target_bitrate=*/DataRate::KilobitsPerSec(120), - /*stable_target_bitrate=*/DataRate::KilobitsPerSec(120), + /*link_allocation=*/DataRate::KilobitsPerSec(120), /*fraction_lost=*/0, /*round_trip_time_ms=*/0, @@ -7814,7 +7776,7 @@ TEST_F(VideoStreamEncoderTest, AccumulatesUpdateRectOnDroppedFrames) { video_stream_encoder_->SetSource(&source, DegradationPreference::MAINTAIN_FRAMERATE); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); source.IncomingCapturedFrame(CreateFrameWithUpdatedPixel(1, nullptr, 0)); WaitForEncodedFrame(1); @@ -7850,7 +7812,7 @@ TEST_F(VideoStreamEncoderTest, AccumulatesUpdateRectOnDroppedFrames) { TEST_F(VideoStreamEncoderTest, SetsFrameTypes) { video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); // First frame is always keyframe. video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr)); @@ -7881,8 +7843,7 @@ TEST_F(VideoStreamEncoderTest, SetsFrameTypesSimulcast) { // Setup simulcast with three streams. ResetEncoder("VP8", 3, 1, 1, false); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kSimulcastTargetBitrate, kSimulcastTargetBitrate, kSimulcastTargetBitrate, - 0, 0, 0); + kSimulcastTargetBitrate, kSimulcastTargetBitrate, 0, 0, 0); // Wait for all three layers before triggering event. sink_.SetNumExpectedLayers(3); @@ -7925,7 +7886,7 @@ TEST_F(VideoStreamEncoderTest, DoesNotRewriteH264BitstreamWithOptimalSps) { ResetEncoder("H264", 1, 1, 1, false); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); video_stream_encoder_->WaitUntilTaskQueueIsIdle(); fake_encoder_.SetEncodedImageData( @@ -7950,7 +7911,7 @@ TEST_F(VideoStreamEncoderTest, RewritesH264BitstreamWithNonOptimalSps) { ResetEncoder("H264", 1, 1, 1, false); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); video_stream_encoder_->WaitUntilTaskQueueIsIdle(); fake_encoder_.SetEncodedImageData( @@ -7971,7 +7932,7 @@ TEST_F(VideoStreamEncoderTest, CopiesVideoFrameMetadataAfterDownscale) { video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( /*target_bitrate=*/DataRate::KilobitsPerSec(300), - /*stable_target_bitrate=*/DataRate::KilobitsPerSec(300), + /*link_allocation=*/DataRate::KilobitsPerSec(300), /*fraction_lost=*/0, /*round_trip_time_ms=*/0, @@ -8015,7 +7976,7 @@ TEST_F(VideoStreamEncoderTest, BandwidthAllocationLowerBound) { // Initial rate. video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( /*target_bitrate=*/DataRate::KilobitsPerSec(300), - /*stable_target_bitrate=*/DataRate::KilobitsPerSec(300), + /*link_allocation=*/DataRate::KilobitsPerSec(300), /*fraction_lost=*/0, /*round_trip_time_ms=*/0, @@ -8034,7 +7995,7 @@ TEST_F(VideoStreamEncoderTest, BandwidthAllocationLowerBound) { DataRate target_rate = min_rate - DataRate::KilobitsPerSec(1); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( /*target_bitrate=*/target_rate, - /*stable_target_bitrate=*/target_rate, + /*link_allocation=*/target_rate, /*fraction_lost=*/0, /*round_trip_time_ms=*/0, @@ -8054,7 +8015,7 @@ TEST_F(VideoStreamEncoderTest, BandwidthAllocationLowerBound) { TEST_F(VideoStreamEncoderTest, EncoderRatesPropagatedOnReconfigure) { video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); // Capture a frame and wait for it to synchronize with the encoder thread. int64_t timestamp_ms = CurrentTimeMs(); video_source_.IncomingCapturedFrame(CreateFrame(timestamp_ms, nullptr)); @@ -8096,8 +8057,7 @@ struct MockEncoderSwitchRequestCallback : public EncoderSwitchRequestCallback { MOCK_METHOD(void, RequestEncoderFallback, (), (override)); MOCK_METHOD(void, RequestEncoderSwitch, - (const webrtc::SdpVideoFormat& format, - bool allow_default_fallback), + (const SdpVideoFormat& format, bool allow_default_fallback), (override)); }; @@ -8147,7 +8107,7 @@ TEST_F(VideoStreamEncoderTest, EncoderSelectorBitrateSwitch) { video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( /*target_bitrate=*/DataRate::KilobitsPerSec(50), - /*stable_target_bitrate=*/DataRate::KilobitsPerSec(kDontCare), + /*link_allocation=*/DataRate::KilobitsPerSec(kDontCare), /*fraction_lost=*/0, /*round_trip_time_ms=*/0, @@ -8179,7 +8139,7 @@ TEST_F(VideoStreamEncoderTest, EncoderSelectorResolutionSwitch) { video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( /*target_bitrate=*/DataRate::KilobitsPerSec(800), - /*stable_target_bitrate=*/DataRate::KilobitsPerSec(1000), + /*link_allocation=*/DataRate::KilobitsPerSec(1000), /*fraction_lost=*/0, /*round_trip_time_ms=*/0, @@ -8215,8 +8175,7 @@ TEST_F(VideoStreamEncoderTest, EncoderSelectorBrokenEncoderSwitch) { // not fail. video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( /*target_bitrate=*/DataRate::KilobitsPerSec(kSufficientBitrateToNotDrop), - /*stable_target_bitrate=*/ - DataRate::KilobitsPerSec(kSufficientBitrateToNotDrop), + /*link_allocation=*/DataRate::KilobitsPerSec(kSufficientBitrateToNotDrop), /*fraction_lost=*/0, /*round_trip_time_ms=*/0, @@ -8261,7 +8220,7 @@ TEST_F(VideoStreamEncoderTest, SwitchEncoderOnInitFailureWithEncoderSelector) { ConfigureEncoder(video_encoder_config_.Copy()); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, /*fraction_lost=*/0, + kTargetBitrate, kTargetBitrate, /*fraction_lost=*/0, /*round_trip_time_ms=*/0, /*cwnd_reduce_ratio=*/0); ASSERT_EQ(0, sink_.number_of_reconfigurations()); @@ -8305,7 +8264,7 @@ TEST_F(VideoStreamEncoderTest, ConfigureEncoder(video_encoder_config_.Copy()); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, /*fraction_lost=*/0, + kTargetBitrate, kTargetBitrate, /*fraction_lost=*/0, /*round_trip_time_ms=*/0, /*cwnd_reduce_ratio=*/0); ASSERT_EQ(0, sink_.number_of_reconfigurations()); @@ -8356,8 +8315,7 @@ TEST_F(VideoStreamEncoderTest, NullEncoderReturnSwitch) { // not fail. video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( /*target_bitrate=*/DataRate::KilobitsPerSec(kSufficientBitrateToNotDrop), - /*stable_target_bitrate=*/ - DataRate::KilobitsPerSec(kSufficientBitrateToNotDrop), + /*link_allocation=*/DataRate::KilobitsPerSec(kSufficientBitrateToNotDrop), /*fraction_lost=*/0, /*round_trip_time_ms=*/0, @@ -8389,7 +8347,7 @@ TEST_F(VideoStreamEncoderTest, NoPreferenceDefaultFallbackToVP8Disabled) { constexpr int kDontCare = 100; constexpr int kNumFrames = 8; - webrtc::test::ScopedKeyValueConfig field_trials( + test::ScopedKeyValueConfig field_trials( field_trials_, "WebRTC-SwitchEncoderFollowCodecPreferenceOrder/Enabled/"); NiceMock video_encoder; @@ -8408,8 +8366,7 @@ TEST_F(VideoStreamEncoderTest, NoPreferenceDefaultFallbackToVP8Disabled) { // not fail. video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( /*target_bitrate=*/DataRate::KilobitsPerSec(kSufficientBitrateToNotDrop), - /*stable_target_bitrate=*/ - DataRate::KilobitsPerSec(kSufficientBitrateToNotDrop), + /*link_allocation=*/DataRate::KilobitsPerSec(kSufficientBitrateToNotDrop), /*fraction_lost=*/0, /*round_trip_time_ms=*/0, @@ -8445,6 +8402,80 @@ TEST_F(VideoStreamEncoderTest, NoPreferenceDefaultFallbackToVP8Disabled) { video_stream_encoder_.reset(); } +TEST_F(VideoStreamEncoderTest, + NoPreferenceDefaultFallbackToVP8DisabledReconfigureEncoder) { + constexpr int kSufficientBitrateToNotDrop = 1000; + constexpr int kDontCare = 100; + constexpr int kNumFrames = 8; + + test::ScopedKeyValueConfig field_trials( + field_trials_, "WebRTC-SwitchEncoderFollowCodecPreferenceOrder/Enabled/"); + + NiceMock video_encoder; + StrictMock switch_callback; + video_send_config_.encoder_settings.encoder_switch_request_callback = + &switch_callback; + auto encoder_factory = std::make_unique( + &video_encoder, /*encoder_selector=*/nullptr); + video_send_config_.encoder_settings.encoder_factory = encoder_factory.get(); + + // Reset encoder for new configuration to take effect. + ConfigureEncoder(video_encoder_config_.Copy()); + + // The VideoStreamEncoder needs some bitrate before it can start encoding, + // setting some bitrate so that subsequent calls to WaitForEncodedFrame does + // not fail. + video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( + /*target_bitrate=*/DataRate::KilobitsPerSec(kSufficientBitrateToNotDrop), + + /*link_allocation=*/DataRate::KilobitsPerSec(kSufficientBitrateToNotDrop), + /*fraction_lost=*/0, + /*round_trip_time_ms=*/0, + /*cwnd_reduce_ratio=*/0); + + EXPECT_CALL(video_encoder, Encode) + .Times(kNumFrames + 1) + .WillOnce(Return(WEBRTC_VIDEO_CODEC_ENCODER_FAILURE)) + .WillRepeatedly(Return(WEBRTC_VIDEO_CODEC_OK)); + + EXPECT_CALL(switch_callback, RequestEncoderFallback()); + + // Encode() will be called once and will return a failure code. All subsequent + // frames will be dropped. + VideoFrame frame = CreateFrame(1, kDontCare, kDontCare); + for (int i = 0; i < kNumFrames; ++i) { + int64_t timestamp_ms = CurrentTimeMs(); + frame.set_ntp_time_ms(timestamp_ms); + frame.set_timestamp_us(timestamp_ms * 1000); + video_source_.IncomingCapturedFrame(frame); + time_controller_.AdvanceTime(TimeDelta::Millis(33)); + } + + // Encoder reconfiguration is triggered by frame size change. After the + // encoder is reconfigured, frame encoding will resume. + frame = CreateFrame(1, 2 * kDontCare, 2 * kDontCare); + for (int i = 0; i < kNumFrames; ++i) { + int64_t timestamp_ms = CurrentTimeMs(); + frame.set_ntp_time_ms(timestamp_ms); + frame.set_timestamp_us(timestamp_ms * 1000); + video_source_.IncomingCapturedFrame(frame); + time_controller_.AdvanceTime(TimeDelta::Millis(33)); + } + + video_stream_encoder_->WaitUntilTaskQueueIsIdle(); + + // After requesting fallback failure, the encoder will be released. + EXPECT_CALL(video_encoder, Release()).Times(1); + + AdvanceTime(TimeDelta::Zero()); + video_stream_encoder_->Stop(); + // The encoders produced by the VideoEncoderProxyFactory have a pointer back + // to it's factory, so in order for the encoder instance in the + // `video_stream_encoder_` to be destroyed before the `encoder_factory` we + // reset the `video_stream_encoder_` here. + video_stream_encoder_.reset(); +} + TEST_F(VideoStreamEncoderTest, NoPreferenceDefaultFallbackToVP8Enabled) { constexpr int kSufficientBitrateToNotDrop = 1000; constexpr int kDontCare = 100; @@ -8466,8 +8497,7 @@ TEST_F(VideoStreamEncoderTest, NoPreferenceDefaultFallbackToVP8Enabled) { // not fail. video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( /*target_bitrate=*/DataRate::KilobitsPerSec(kSufficientBitrateToNotDrop), - /*stable_target_bitrate=*/ - DataRate::KilobitsPerSec(kSufficientBitrateToNotDrop), + /*link_allocation=*/DataRate::KilobitsPerSec(kSufficientBitrateToNotDrop), /*fraction_lost=*/0, /*round_trip_time_ms=*/0, @@ -8501,7 +8531,7 @@ TEST_F(VideoStreamEncoderTest, auto rate = DataRate::KilobitsPerSec(100); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( /*target_bitrate=*/rate, - /*stable_target_bitrate=*/rate, + /*link_allocation=*/rate, /*fraction_lost=*/0, /*round_trip_time_ms=*/0, @@ -8519,7 +8549,7 @@ TEST_F(VideoStreamEncoderTest, auto new_stable_rate = rate - DataRate::KilobitsPerSec(5); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( /*target_bitrate=*/new_stable_rate, - /*stable_target_bitrate=*/new_stable_rate, + /*link_allocation=*/rate, /*fraction_lost=*/0, /*round_trip_time_ms=*/0, @@ -8538,7 +8568,7 @@ TEST_F(VideoStreamEncoderTest, auto rate = DataRate::KilobitsPerSec(100); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( /*target_bitrate=*/rate, - /*stable_target_bitrate=*/rate, + /*link_allocation=*/rate, /*fraction_lost=*/0, /*round_trip_time_ms=*/0, @@ -8554,10 +8584,8 @@ TEST_F(VideoStreamEncoderTest, // Set a higher target rate without changing the link_allocation. Should not // reset encoder's rate. - auto new_stable_rate = rate - DataRate::KilobitsPerSec(5); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( /*target_bitrate=*/rate, - /*stable_target_bitrate=*/new_stable_rate, /*link_allocation=*/rate, /*fraction_lost=*/0, /*round_trip_time_ms=*/0, @@ -8578,7 +8606,7 @@ TEST_F(VideoStreamEncoderTest, ConfiguresVp9SvcAtOddResolutions) { video_source_.set_adaptation_enabled(true); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); VideoFrame frame = CreateFrame(1, kWidth, kHeight); @@ -8606,8 +8634,7 @@ TEST_F(VideoStreamEncoderTest, EncoderResetAccordingToParameterChange) { } config.video_stream_factory = nullptr; video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kSimulcastTargetBitrate, kSimulcastTargetBitrate, kSimulcastTargetBitrate, - 0, 0, 0); + kSimulcastTargetBitrate, kSimulcastTargetBitrate, 0, 0, 0); // First initialization. // Encoder should be initialized. Next frame should be key frame. @@ -8686,7 +8713,7 @@ TEST_F(VideoStreamEncoderTest, EncoderResolutionsExposedInSinglecast) { SetUp(); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); // Capturing a frame should reconfigure the encoder and expose the encoder // resolution, which is the same as the input frame. @@ -8728,8 +8755,7 @@ TEST_F(VideoStreamEncoderTest, EncoderResolutionsExposedInSimulcast) { } config.video_stream_factory = nullptr; video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kSimulcastTargetBitrate, kSimulcastTargetBitrate, kSimulcastTargetBitrate, - 0, 0, 0); + kSimulcastTargetBitrate, kSimulcastTargetBitrate, 0, 0, 0); // Capture a frame with all layers active. int64_t timestamp_ms = kFrameIntervalMs; @@ -8821,7 +8847,7 @@ TEST_F(VideoStreamEncoderTest, QpAbsent_QpParsed) { } TEST_F(VideoStreamEncoderTest, QpAbsentParsingDisabled_QpAbsent) { - webrtc::test::ScopedKeyValueConfig field_trials( + test::ScopedKeyValueConfig field_trials( field_trials_, "WebRTC-QpParsingKillSwitch/Enabled/"); ResetEncoder("VP8", 1, 1, 1, false); @@ -8856,11 +8882,11 @@ TEST_F(VideoStreamEncoderTest, ConfigureEncoder(std::move(video_encoder_config)); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); test::FrameForwarder source; - video_stream_encoder_->SetSource( - &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE); + video_stream_encoder_->SetSource(&source, + DegradationPreference::MAINTAIN_FRAMERATE); EXPECT_THAT(source.sink_wants(), UnlimitedSinkWants()); EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution); @@ -8884,11 +8910,11 @@ TEST_F(VideoStreamEncoderTest, QualityScalingNotAllowed_IsQpTrustedSetTrue) { ConfigureEncoder(std::move(video_encoder_config)); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); test::FrameForwarder source; - video_stream_encoder_->SetSource( - &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE); + video_stream_encoder_->SetSource(&source, + DegradationPreference::MAINTAIN_FRAMERATE); EXPECT_THAT(source.sink_wants(), UnlimitedSinkWants()); EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution); @@ -8913,11 +8939,11 @@ TEST_F(VideoStreamEncoderTest, ConfigureEncoder(std::move(video_encoder_config)); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); test::FrameForwarder source; - video_stream_encoder_->SetSource( - &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE); + video_stream_encoder_->SetSource(&source, + DegradationPreference::MAINTAIN_FRAMERATE); EXPECT_THAT(source.sink_wants(), UnlimitedSinkWants()); EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution); @@ -8942,11 +8968,11 @@ TEST_F(VideoStreamEncoderTest, ConfigureEncoder(std::move(video_encoder_config)); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); test::FrameForwarder source; - video_stream_encoder_->SetSource( - &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE); + video_stream_encoder_->SetSource(&source, + DegradationPreference::MAINTAIN_FRAMERATE); EXPECT_THAT(source.sink_wants(), UnlimitedSinkWants()); EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution); @@ -8972,7 +8998,7 @@ TEST_F(VideoStreamEncoderTest, EncoderProvideLimitsWhenQPIsNotTrusted) { /*max_bitrate_bps=*/MaxEncBitrateKbps * 1000); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); fake_encoder_.SetResolutionBitrateLimits({encoder_bitrate_limits}); @@ -9013,7 +9039,6 @@ TEST_F(VideoStreamEncoderTest, EncoderDoesnotProvideLimitsWhenQPIsNotTrusted) { const int min_encoder_bitrate = suitable_bitrate_limit->min_bitrate_bps; const int target_encoder_bitrate = max_encoder_bitrate; video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - DataRate::BitsPerSec(target_encoder_bitrate), DataRate::BitsPerSec(target_encoder_bitrate), DataRate::BitsPerSec(target_encoder_bitrate), 0, 0, 0); @@ -9055,7 +9080,6 @@ TEST_F(VideoStreamEncoderTest, const int min_encoder_bitrate = suitable_bitrate_limit->min_bitrate_bps; const int target_encoder_bitrate = max_encoder_bitrate; video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - DataRate::BitsPerSec(target_encoder_bitrate), DataRate::BitsPerSec(target_encoder_bitrate), DataRate::BitsPerSec(target_encoder_bitrate), 0, 0, 0); @@ -9092,7 +9116,7 @@ TEST_F(VideoStreamEncoderTest, NormalComplexityWithMoreThanTwoCores) { /*num_cores=*/3); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); video_source_.IncomingCapturedFrame( CreateFrame(1, /*width=*/320, /*height=*/180)); WaitForEncodedFrame(1); @@ -9103,7 +9127,7 @@ TEST_F(VideoStreamEncoderTest, NormalComplexityWithMoreThanTwoCores) { TEST_F(VideoStreamEncoderTest, NormalComplexityWhenLowTierOptimizationsAreDisabled) { - webrtc::test::ScopedKeyValueConfig field_trials( + test::ScopedKeyValueConfig field_trials( field_trials_, "WebRTC-VP9-LowTierOptimizations/Disabled/"); ResetEncoder("VP9", /*num_streams=*/1, /*num_temporal_layers=*/1, @@ -9115,7 +9139,7 @@ TEST_F(VideoStreamEncoderTest, /*num_cores=*/2); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); video_source_.IncomingCapturedFrame( CreateFrame(1, /*width=*/320, /*height=*/180)); WaitForEncodedFrame(1); @@ -9134,7 +9158,7 @@ TEST_F(VideoStreamEncoderTest, LowComplexityWithTwoCores) { /*num_cores=*/2); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); video_source_.IncomingCapturedFrame( CreateFrame(1, /*width=*/320, /*height=*/180)); WaitForEncodedFrame(1); @@ -9156,11 +9180,11 @@ TEST_F(VideoStreamEncoderTest, QualityScalingAllowed_QualityScalingEnabled) { ConfigureEncoder(std::move(video_encoder_config)); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); test::FrameForwarder source; - video_stream_encoder_->SetSource( - &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE); + video_stream_encoder_->SetSource(&source, + DegradationPreference::MAINTAIN_FRAMERATE); EXPECT_THAT(source.sink_wants(), UnlimitedSinkWants()); EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution); @@ -9184,11 +9208,11 @@ TEST_F(VideoStreamEncoderTest, QualityScalingAllowed_IsQpTrustedSetTrue) { ConfigureEncoder(std::move(video_encoder_config)); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); test::FrameForwarder source; - video_stream_encoder_->SetSource( - &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE); + video_stream_encoder_->SetSource(&source, + DegradationPreference::MAINTAIN_FRAMERATE); EXPECT_THAT(source.sink_wants(), UnlimitedSinkWants()); EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution); @@ -9212,11 +9236,11 @@ TEST_F(VideoStreamEncoderTest, QualityScalingAllowed_IsQpTrustedSetFalse) { ConfigureEncoder(std::move(video_encoder_config)); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); test::FrameForwarder source; - video_stream_encoder_->SetSource( - &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE); + video_stream_encoder_->SetSource(&source, + DegradationPreference::MAINTAIN_FRAMERATE); EXPECT_THAT(source.sink_wants(), UnlimitedSinkWants()); EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution); @@ -9243,11 +9267,11 @@ TEST_F(VideoStreamEncoderTest, ConfigureEncoder(std::move(video_encoder_config)); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); test::FrameForwarder source; - video_stream_encoder_->SetSource( - &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE); + video_stream_encoder_->SetSource(&source, + DegradationPreference::MAINTAIN_FRAMERATE); EXPECT_THAT(source.sink_wants(), UnlimitedSinkWants()); EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution); @@ -9273,11 +9297,11 @@ TEST_F(VideoStreamEncoderTest, ConfigureEncoder(std::move(video_encoder_config)); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); test::FrameForwarder source; - video_stream_encoder_->SetSource( - &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE); + video_stream_encoder_->SetSource(&source, + DegradationPreference::MAINTAIN_FRAMERATE); EXPECT_THAT(source.sink_wants(), UnlimitedSinkWants()); EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution); @@ -9305,7 +9329,7 @@ TEST_F(VideoStreamEncoderTest, // Set bitrates, unpausing the encoder and triggering a request for a refresh // frame. video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); video_stream_encoder_->WaitUntilTaskQueueIsIdle(); EXPECT_EQ(video_source_.refresh_frames_requested_, 1); @@ -9341,7 +9365,7 @@ TEST_F(VideoStreamEncoderTest, RecreatesEncoderWhenEnableVp9SpatialLayer) { kVideoLayersAllocation); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); video_source_.IncomingCapturedFrame(CreateFrame(CurrentTimeMs(), 1280, 720)); WaitForEncodedFrame(CurrentTimeMs()); @@ -9432,7 +9456,7 @@ class VideoStreamEncoderWithRealEncoderTest // Set bitrate to ensure frame is not dropped. video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTargetBitrate, kTargetBitrate, kTargetBitrate, 0, 0, 0); + kTargetBitrate, kTargetBitrate, 0, 0, 0); } const VideoCodecType codec_type_; @@ -9543,8 +9567,7 @@ TEST_P(VideoStreamEncoderWithRealEncoderTest, HandlesLayerToggling) { config.video_stream_factory = nullptr; video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kSimulcastTargetBitrate, kSimulcastTargetBitrate, kSimulcastTargetBitrate, - 0, 0, 0); + kSimulcastTargetBitrate, kSimulcastTargetBitrate, 0, 0, 0); // Capture a frame with all layers active. sink_.SetNumExpectedLayers(kNumSpatialLayers); @@ -9568,7 +9591,7 @@ TEST_P(VideoStreamEncoderWithRealEncoderTest, HandlesLayerToggling) { // New target bitrates signaled based on lower resolution. DataRate kTwoLayerBitrate = DataRate::KilobitsPerSec(833); video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - kTwoLayerBitrate, kTwoLayerBitrate, kTwoLayerBitrate, 0, 0, 0); + kTwoLayerBitrate, kTwoLayerBitrate, 0, 0, 0); video_stream_encoder_->WaitUntilTaskQueueIsIdle(); // Re-enable the top layer. @@ -9579,8 +9602,7 @@ TEST_P(VideoStreamEncoderWithRealEncoderTest, HandlesLayerToggling) { // Bitrate target adjusted back up to enable HD layer... video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - DataRate::KilobitsPerSec(1800), DataRate::KilobitsPerSec(1800), - DataRate::KilobitsPerSec(1800), 0, 0, 0); + DataRate::KilobitsPerSec(1800), DataRate::KilobitsPerSec(1800), 0, 0, 0); video_stream_encoder_->WaitUntilTaskQueueIsIdle(); // ...then add a new frame. @@ -9674,7 +9696,7 @@ class ReconfigureSimulcastEncoderTest : public VideoStreamEncoderTest { void OnBitrateUpdated(DataRate bitrate) { video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources( - bitrate, bitrate, bitrate, 0, 0, 0); + bitrate, bitrate, 0, 0, 0); } void InsertFrameAndWaitForEncoded() { @@ -9818,7 +9840,7 @@ TEST_F(ReconfigureEncoderTest, // The purpose of the test is to make sure that nothing bad happens if the // initialization step on the encoder queue, doesn't run. TEST(VideoStreamEncoderSimpleTest, CreateDestroy) { - class SuperLazyTaskQueue : public webrtc::TaskQueueBase { + class SuperLazyTaskQueue : public TaskQueueBase { public: SuperLazyTaskQueue() = default; ~SuperLazyTaskQueue() override = default; @@ -9843,8 +9865,7 @@ TEST(VideoStreamEncoderSimpleTest, CreateDestroy) { Environment env = CreateEnvironment(time_controller.GetClock()); MockableSendStatisticsProxy stats_proxy( &env.clock(), VideoSendStream::Config(nullptr), - webrtc::VideoEncoderConfig::ContentType::kRealtimeVideo, - env.field_trials()); + VideoEncoderConfig::ContentType::kRealtimeVideo, env.field_trials()); SimpleVideoStreamEncoderFactory::MockFakeEncoder mock_fake_encoder(env); test::VideoEncoderProxyFactory encoder_factory(&mock_fake_encoder); std::unique_ptr bitrate_allocator_factory = @@ -9857,8 +9878,8 @@ TEST(VideoStreamEncoderSimpleTest, CreateDestroy) { auto adapter = std::make_unique(); EXPECT_CALL((*adapter.get()), Initialize).WillOnce(Return()); - std::unique_ptr - encoder_queue(new SuperLazyTaskQueue()); + std::unique_ptr encoder_queue( + new SuperLazyTaskQueue()); // Construct a VideoStreamEncoder instance and let it go out of scope without // doing anything else. This should be fine since the posted init task will @@ -9930,8 +9951,8 @@ TEST(VideoStreamEncoderFrameCadenceTest, test::FrameForwarder video_source; SimpleVideoStreamEncoderFactory factory; auto video_stream_encoder = factory.Create(std::move(adapter)); - video_stream_encoder->SetSource( - &video_source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE); + video_stream_encoder->SetSource(&video_source, + DegradationPreference::MAINTAIN_FRAMERATE); EXPECT_CALL(*adapter_ptr, OnFrame); auto buffer = make_ref_counted(/*width=*/16, /*height=*/16); @@ -9957,8 +9978,8 @@ TEST(VideoStreamEncoderFrameCadenceTest, UsesFrameCadenceAdapterForFrameRate) { // This is just to make the VSE operational. We'll feed a frame directly by // the callback interface. - video_stream_encoder->SetSource( - &video_source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE); + video_stream_encoder->SetSource(&video_source, + DegradationPreference::MAINTAIN_FRAMERATE); VideoEncoderConfig video_encoder_config; test::FillEncoderConfiguration(kVideoCodecGeneric, 1, &video_encoder_config); @@ -9997,8 +10018,7 @@ TEST(VideoStreamEncoderFrameCadenceTest, // Both layers enabled at 1 MBit/s. video_stream_encoder->OnBitrateUpdated( - DataRate::KilobitsPerSec(1000), DataRate::KilobitsPerSec(1000), - DataRate::KilobitsPerSec(1000), 0, 0, 0); + DataRate::KilobitsPerSec(1000), DataRate::KilobitsPerSec(1000), 0, 0, 0); EXPECT_CALL(*adapter_ptr, UpdateLayerStatus(0, /*enabled=*/true)); EXPECT_CALL(*adapter_ptr, UpdateLayerStatus(1, /*enabled=*/true)); factory.DepleteTaskQueues(); @@ -10006,16 +10026,15 @@ TEST(VideoStreamEncoderFrameCadenceTest, // Layer 1 disabled at 200 KBit/s. video_stream_encoder->OnBitrateUpdated( - DataRate::KilobitsPerSec(200), DataRate::KilobitsPerSec(200), - DataRate::KilobitsPerSec(200), 0, 0, 0); + DataRate::KilobitsPerSec(200), DataRate::KilobitsPerSec(200), 0, 0, 0); EXPECT_CALL(*adapter_ptr, UpdateLayerStatus(0, /*enabled=*/true)); EXPECT_CALL(*adapter_ptr, UpdateLayerStatus(1, /*enabled=*/false)); factory.DepleteTaskQueues(); Mock::VerifyAndClearExpectations(adapter_ptr); // All layers off at suspended video. - video_stream_encoder->OnBitrateUpdated(DataRate::Zero(), DataRate::Zero(), - DataRate::Zero(), 0, 0, 0); + video_stream_encoder->OnBitrateUpdated(DataRate::Zero(), DataRate::Zero(), 0, + 0, 0); EXPECT_CALL(*adapter_ptr, UpdateLayerStatus(0, /*enabled=*/false)); EXPECT_CALL(*adapter_ptr, UpdateLayerStatus(1, /*enabled=*/false)); factory.DepleteTaskQueues(); @@ -10023,8 +10042,7 @@ TEST(VideoStreamEncoderFrameCadenceTest, // Both layers enabled again back at 1 MBit/s. video_stream_encoder->OnBitrateUpdated( - DataRate::KilobitsPerSec(1000), DataRate::KilobitsPerSec(1000), - DataRate::KilobitsPerSec(1000), 0, 0, 0); + DataRate::KilobitsPerSec(1000), DataRate::KilobitsPerSec(1000), 0, 0, 0); EXPECT_CALL(*adapter_ptr, UpdateLayerStatus(0, /*enabled=*/true)); EXPECT_CALL(*adapter_ptr, UpdateLayerStatus(1, /*enabled=*/true)); factory.DepleteTaskQueues(); @@ -10057,8 +10075,7 @@ TEST(VideoStreamEncoderFrameCadenceTest, UpdatesQualityConvergence) { video_stream_encoder->ConfigureEncoder(video_encoder_config.Copy(), kMaxPayloadLength); video_stream_encoder->OnBitrateUpdated( - DataRate::KilobitsPerSec(1000), DataRate::KilobitsPerSec(1000), - DataRate::KilobitsPerSec(1000), 0, 0, 0); + DataRate::KilobitsPerSec(1000), DataRate::KilobitsPerSec(1000), 0, 0, 0); // Pass a frame which has unconverged results. PassAFrame(encoder_queue, video_stream_encoder_callback, /*ntp_time_ms=*/1); @@ -10112,8 +10129,8 @@ TEST(VideoStreamEncoderFrameCadenceTest, TaskQueueBase* encoder_queue = nullptr; auto video_stream_encoder = factory.Create(std::move(adapter), &encoder_queue); - video_stream_encoder->SetSource( - &mock_source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE); + video_stream_encoder->SetSource(&mock_source, + DegradationPreference::MAINTAIN_FRAMERATE); VideoEncoderConfig config; config.content_type = VideoEncoderConfig::ContentType::kScreen; test::FillEncoderConfiguration(kVideoCodecVP8, 1, &config); @@ -10155,8 +10172,8 @@ TEST(VideoStreamEncoderFrameCadenceTest, auto video_stream_encoder = factory.CreateWithEncoderQueue( std::move(adapter), std::move(encoder_queue), &field_trials); - video_stream_encoder->SetSource( - &mock_source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE); + video_stream_encoder->SetSource(&mock_source, + DegradationPreference::MAINTAIN_FRAMERATE); VideoEncoderConfig config; config.content_type = VideoEncoderConfig::ContentType::kScreen; test::FillEncoderConfiguration(kVideoCodecVP8, 1, &config); @@ -10184,7 +10201,7 @@ class VideoStreamEncoderFrameCadenceRestrictionTest : public ::testing::Test { video_stream_encoder_( factory_.Create(std::move(adapter_), &encoder_queue_)) {} - ~VideoStreamEncoderFrameCadenceRestrictionTest() { + ~VideoStreamEncoderFrameCadenceRestrictionTest() override { factory_.DepleteTaskQueues(); } diff --git a/webrtc_lib_link_test.cc b/webrtc_lib_link_test.cc index b5ba086f55..997cc0f206 100644 --- a/webrtc_lib_link_test.cc +++ b/webrtc_lib_link_test.cc @@ -42,9 +42,9 @@ void CreateSomeMediaDeps(PeerConnectionFactoryDependencies& media_deps) { media_deps.adm = CreateAudioDeviceModule(*media_deps.env, AudioDeviceModule::kDummyAudio); media_deps.audio_encoder_factory = - webrtc::CreateAudioEncoderFactory(); + CreateAudioEncoderFactory(); media_deps.audio_decoder_factory = - webrtc::CreateAudioDecoderFactory(); + CreateAudioDecoderFactory(); media_deps.video_encoder_factory = std::make_unique(); + pcf_deps.signaling_thread = Thread::Current(); + pcf_deps.network_thread = Thread::Current(); + pcf_deps.worker_thread = Thread::Current(); + pcf_deps.event_log_factory = std::make_unique(); CreateSomeMediaDeps(pcf_deps); EnableMedia(pcf_deps); return pcf_deps; @@ -76,8 +76,8 @@ webrtc::PeerConnectionFactoryDependencies CreateSomePcfDeps() { void TestCase1ModularFactory() { auto pcf_deps = CreateSomePcfDeps(); auto peer_connection_factory = - webrtc::CreateModularPeerConnectionFactory(std::move(pcf_deps)); - webrtc::PeerConnectionInterface::RTCConfiguration rtc_config; + CreateModularPeerConnectionFactory(std::move(pcf_deps)); + PeerConnectionInterface::RTCConfiguration rtc_config; auto result = peer_connection_factory->CreatePeerConnectionOrError( rtc_config, PeerConnectionDependencies(nullptr)); // Creation will fail because of null observer, but that's OK. @@ -89,14 +89,13 @@ void TestCase2RegularFactory() { media_deps.env = CreateEnvironment(); CreateSomeMediaDeps(media_deps); - auto peer_connection_factory = webrtc::CreatePeerConnectionFactory( - webrtc::Thread::Current(), webrtc::Thread::Current(), - webrtc::Thread::Current(), std::move(media_deps.adm), - std::move(media_deps.audio_encoder_factory), + auto peer_connection_factory = CreatePeerConnectionFactory( + Thread::Current(), Thread::Current(), Thread::Current(), + std::move(media_deps.adm), std::move(media_deps.audio_encoder_factory), std::move(media_deps.audio_decoder_factory), std::move(media_deps.video_encoder_factory), std::move(media_deps.video_decoder_factory), nullptr, nullptr); - webrtc::PeerConnectionInterface::RTCConfiguration rtc_config; + PeerConnectionInterface::RTCConfiguration rtc_config; auto result = peer_connection_factory->CreatePeerConnectionOrError( rtc_config, PeerConnectionDependencies(nullptr)); // Creation will fail because of null observer, but that's OK.