1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545
|
// Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/modules/mediastream/media_stream_constraints_util_audio.h"
#include <algorithm>
#include <cmath>
#include <string>
#include <tuple>
#include <utility>
#include "base/strings/string_number_conversions.h"
#include "build/build_config.h"
#include "media/audio/audio_features.h"
#include "media/base/audio_parameters.h"
#include "media/base/limits.h"
#include "media/base/media_switches.h"
#include "media/webrtc/constants.h"
#include "media/webrtc/webrtc_features.h"
#include "third_party/blink/public/common/mediastream/media_stream_controls.h"
#include "third_party/blink/public/platform/web_string.h"
#include "third_party/blink/public/web/modules/mediastream/media_stream_video_source.h"
#include "third_party/blink/renderer/modules/mediastream/media_constraints.h"
#include "third_party/blink/renderer/modules/mediastream/media_stream_constraints_util_sets.h"
#include "third_party/blink/renderer/modules/mediastream/processed_local_audio_source.h"
#include "third_party/blink/renderer/platform/mediastream/media_stream_audio_processor_options.h"
#include "third_party/blink/renderer/platform/mediastream/media_stream_audio_source.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
using blink::AudioCaptureSettings;
using blink::AudioProcessingProperties;
using ConstraintSet = MediaTrackConstraintSetPlatform;
using BooleanConstraint = blink::BooleanConstraint;
using EchoCancellationType = AudioProcessingProperties::EchoCancellationType;
using VoiceIsolationType = AudioProcessingProperties::VoiceIsolationType;
using ProcessingType = AudioCaptureSettings::ProcessingType;
using StringConstraint = blink::StringConstraint;
template <class T>
using NumericRangeSet = blink::media_constraints::NumericRangeSet<T>;
namespace {
using BoolSet = blink::media_constraints::DiscreteSet<bool>;
using DoubleRangeSet = blink::media_constraints::NumericRangeSet<double>;
using EchoCancellationTypeSet =
blink::media_constraints::DiscreteSet<EchoCancellationType>;
using VoiceIsolationTypeSet =
blink::media_constraints::DiscreteSet<VoiceIsolationType>;
using IntRangeSet = blink::media_constraints::NumericRangeSet<int>;
using StringSet = blink::media_constraints::DiscreteSet<std::string>;
// The sample size is set to 16 due to the Signed-16 format representation.
int32_t GetSampleSize() {
return media::SampleFormatToBitsPerChannel(media::kSampleFormatS16);
}
// This class encapsulates two values that together build up the score of each
// processed candidate.
// - Fitness, similarly defined by the W3C specification
// (https://w3c.github.io/mediacapture-main/#dfn-fitness-distance);
// - Distance from the default device ID;
// - The priority associated to the echo cancellation type selected.
// - The priority of the associated processing-based container.
//
// Differently from the definition in the W3C specification, the present
// algorithm maximizes the score.
struct Score {
public:
enum class EcModeScore : int {
kDisabled = 1,
kSystem = 2,
kAec3 = 3,
};
explicit Score(double fitness,
bool is_default_device_id = false,
EcModeScore ec_mode_score = EcModeScore::kDisabled,
int processing_priority = -1) {
score = std::make_tuple(fitness, is_default_device_id, ec_mode_score,
processing_priority);
}
bool operator>(const Score& other) const { return score > other.score; }
Score& operator+=(const Score& other) {
std::get<0>(score) += std::get<0>(other.score);
std::get<1>(score) |= std::get<1>(other.score);
// Among the priorities in the two score objects, we store the highest one.
std::get<2>(score) = std::max(std::get<2>(score), std::get<2>(other.score));
// Select the highest processing priority.
std::get<3>(score) = std::max(std::get<3>(score), std::get<3>(other.score));
return *this;
}
Score& operator+=(double fitness) {
std::get<0>(score) += fitness;
return *this;
}
Score& operator+=(bool is_default_device) {
std::get<1>(score) |= is_default_device;
return *this;
}
void set_ec_mode_score(EcModeScore ec_mode_score) {
std::get<2>(score) = ec_mode_score;
}
void set_processing_priority(int priority) { std::get<3>(score) = priority; }
std::tuple<double, bool, EcModeScore, int> score;
};
// Information regarding an active source, if that exists.
class SourceInfo {
public:
static std::optional<SourceInfo> FromSource(
blink::MediaStreamAudioSource* source) {
if (!source) {
return std::nullopt;
}
media::AudioParameters source_parameters = source->GetAudioParameters();
std::optional<AudioProcessingProperties> properties =
source->GetAudioProcessingProperties();
CHECK(properties);
return SourceInfo(*properties, source_parameters.channels(),
source_parameters.sample_rate(),
source_parameters.GetBufferDuration().InSecondsF());
}
const AudioProcessingProperties& properties() const { return properties_; }
int channels() const { return channels_; }
int sample_rate() const { return sample_rate_; }
double latency() const { return latency_; }
private:
SourceInfo(const AudioProcessingProperties& properties,
int channels,
int sample_rate,
double latency)
: properties_(properties),
channels_(std::move(channels)),
sample_rate_(std::move(sample_rate)),
latency_(latency) {}
const AudioProcessingProperties properties_;
const int channels_;
const int sample_rate_;
const double latency_;
};
// Container for each independent boolean constrainable property.
class BooleanContainer {
public:
explicit BooleanContainer(BoolSet allowed_values = BoolSet())
: allowed_values_(std::move(allowed_values)) {}
const char* ApplyConstraintSet(const BooleanConstraint& constraint) {
allowed_values_ = allowed_values_.Intersection(
blink::media_constraints::BoolSetFromConstraint(constraint));
return allowed_values_.IsEmpty() ? constraint.GetName() : nullptr;
}
std::tuple<double, bool> SelectSettingsAndScore(
const BooleanConstraint& constraint,
bool default_setting) const {
DCHECK(!IsEmpty());
if (constraint.HasIdeal() && allowed_values_.Contains(constraint.Ideal()))
return std::make_tuple(1.0, constraint.Ideal());
if (allowed_values_.is_universal())
return std::make_tuple(0.0, default_setting);
DCHECK_EQ(allowed_values_.elements().size(), 1U);
return std::make_tuple(0.0, allowed_values_.FirstElement());
}
bool IsEmpty() const { return allowed_values_.IsEmpty(); }
private:
BoolSet allowed_values_;
};
// Container for each independent string constrainable property.
class StringContainer {
public:
explicit StringContainer(StringSet allowed_values = StringSet())
: allowed_values_(std::move(allowed_values)) {}
const char* ApplyConstraintSet(const StringConstraint& constraint) {
allowed_values_ = allowed_values_.Intersection(
blink::media_constraints::StringSetFromConstraint(constraint));
return allowed_values_.IsEmpty() ? constraint.GetName() : nullptr;
}
// Selects the best value from the nonempty |allowed_values_|, subject to
// |constraint_set.*constraint_member_| and determines the associated fitness.
// The first selection criteria is inclusion in the constraint's ideal value,
// followed by equality to |default_value|. There is always a single best
// value.
std::tuple<double, std::string> SelectSettingsAndScore(
const StringConstraint& constraint,
std::string default_setting) const {
DCHECK(!IsEmpty());
if (constraint.HasIdeal()) {
for (const WTF::String& ideal_candidate : constraint.Ideal()) {
std::string candidate = ideal_candidate.Utf8();
if (allowed_values_.Contains(candidate))
return std::make_tuple(1.0, candidate);
}
}
std::string setting = allowed_values_.Contains(default_setting)
? default_setting
: allowed_values_.FirstElement();
return std::make_tuple(0.0, setting);
}
bool IsEmpty() const { return allowed_values_.IsEmpty(); }
private:
StringSet allowed_values_;
};
// Container for each independent numeric constrainable property.
template <class T, class C>
class NumericRangeSetContainer {
public:
explicit NumericRangeSetContainer(
NumericRangeSet<T> allowed_values = NumericRangeSet<T>())
: allowed_values_(std::move(allowed_values)) {}
const char* ApplyConstraintSet(const C& constraint) {
auto constraint_set = NumericRangeSet<T>::FromConstraint(constraint);
allowed_values_ = allowed_values_.Intersection(constraint_set);
return IsEmpty() ? constraint.GetName() : nullptr;
}
// This function will return a fitness with the associated setting.
// The setting will be the ideal value, if such value is provided and
// admitted, or the closest value to it.
// When no ideal is available and |default_setting| is provided, the setting
// will be |default_setting| or the closest value to it.
// When |default_setting| is **not** provided, the setting will be a value iff
// |allowed_values_| contains only a single value, otherwise std::nullopt is
// returned to signal that it was not possible to make a decision.
std::tuple<double, std::optional<T>> SelectSettingsAndScore(
const C& constraint,
const std::optional<T>& default_setting = std::nullopt) const {
DCHECK(!IsEmpty());
if (constraint.HasIdeal()) {
if (allowed_values_.Contains(constraint.Ideal()))
return std::make_tuple(1.0, constraint.Ideal());
T value = SelectClosestValueTo(constraint.Ideal());
double fitness = 1.0 - blink::NumericConstraintFitnessDistance(
value, constraint.Ideal());
return std::make_tuple(fitness, value);
}
if (default_setting) {
if (allowed_values_.Contains(*default_setting))
return std::make_tuple(0.0, *default_setting);
// If the default value provided is not contained, select the value
// closest to it.
return std::make_tuple(0.0, SelectClosestValueTo(*default_setting));
}
if (allowed_values_.Min() && allowed_values_.Max() &&
*allowed_values_.Min() == *allowed_values_.Max()) {
return std::make_tuple(0.0, *allowed_values_.Min());
}
return std::make_tuple(0.0, std::nullopt);
}
bool IsEmpty() const { return allowed_values_.IsEmpty(); }
private:
T SelectClosestValueTo(T value) const {
DCHECK(allowed_values_.Min() || allowed_values_.Max());
DCHECK(!allowed_values_.Contains(value));
return allowed_values_.Min() && value < *allowed_values_.Min()
? *allowed_values_.Min()
: *allowed_values_.Max();
}
NumericRangeSet<T> allowed_values_;
};
using IntegerRangeContainer =
NumericRangeSetContainer<int, blink::LongConstraint>;
using DoubleRangeContainer =
NumericRangeSetContainer<double, blink::DoubleConstraint>;
// Container for numeric constrainable properties that allow a fixed set of
// values.
template <class T, class C>
class NumericDiscreteSetContainer {
public:
// It's the responsibility of the caller to ensure there are no repeated
// values.
explicit NumericDiscreteSetContainer(Vector<T> allowed_values)
: allowed_values_(std::move(allowed_values)) {}
const char* ApplyConstraintSet(const C& constraint) {
auto constraint_set = NumericRangeSet<T>::FromConstraint(constraint);
auto to_remove = std::ranges::remove_if(
allowed_values_, [&constraint_set](const auto& t) {
return !constraint_set.Contains(t);
});
allowed_values_.erase(to_remove.begin(), to_remove.end());
return IsEmpty() ? constraint.GetName() : nullptr;
}
// This function will return a fitness with the associated setting. The
// setting will be the ideal value, if ideal is provided and
// allowed, or the closest value to it (using fitness distance).
// When no ideal is available and |default_setting| is provided, the setting
// will be |default_setting| or the closest value to it (using fitness
// distance).
// When |default_setting| is **not** provided, the setting will be a value iff
// |allowed_values_| contains only a single value, otherwise std::nullopt is
// returned to signal that it was not possible to make a decision.
std::tuple<double, std::optional<T>> SelectSettingsAndScore(
const C& constraint,
const std::optional<T>& default_setting = std::nullopt) const {
DCHECK(!IsEmpty());
if (constraint.HasIdeal()) {
if (allowed_values_.Contains(constraint.Ideal()))
return std::make_tuple(1.0, constraint.Ideal());
T value = SelectClosestValueTo(constraint.Ideal());
double fitness =
1.0 - NumericConstraintFitnessDistance(value, constraint.Ideal());
return std::make_tuple(fitness, value);
}
if (default_setting) {
if (allowed_values_.Contains(*default_setting))
return std::make_tuple(0.0, *default_setting);
// If the default value provided is not contained, select the value
// closest to it.
return std::make_tuple(0.0, SelectClosestValueTo(*default_setting));
}
if (allowed_values_.size() == 1) {
return std::make_tuple(0.0, *allowed_values_.begin());
}
return std::make_tuple(0.0, std::nullopt);
}
bool IsEmpty() const { return allowed_values_.empty(); }
private:
T SelectClosestValueTo(T target) const {
DCHECK(!IsEmpty());
T best_value = *allowed_values_.begin();
double best_distance = HUGE_VAL;
for (auto value : allowed_values_) {
double distance = blink::NumericConstraintFitnessDistance(value, target);
if (distance < best_distance) {
best_value = value;
best_distance = distance;
}
}
return best_value;
}
Vector<T> allowed_values_;
};
using IntegerDiscreteContainer =
NumericDiscreteSetContainer<int, blink::LongConstraint>;
// Container to manage the properties related to echo cancellation:
// echoCancellation and echoCancellationType.
class EchoCancellationContainer {
public:
// Default constructor intended to temporarily create an empty object.
EchoCancellationContainer()
: ec_mode_allowed_values_(EchoCancellationTypeSet::EmptySet()),
device_parameters_(media::AudioParameters::UnavailableDeviceParams()),
is_device_capture_(true) {}
EchoCancellationContainer(Vector<EchoCancellationType> allowed_values,
std::optional<SourceInfo> source_info,
bool is_device_capture,
media::AudioParameters device_parameters,
bool is_reconfiguration_allowed)
: ec_mode_allowed_values_(
EchoCancellationTypeSet(std::move(allowed_values))),
device_parameters_(device_parameters),
is_device_capture_(is_device_capture) {
if (!source_info) {
return;
}
// If HW echo cancellation is used, reconfiguration is not always supported
// and only the current values are allowed. Otherwise, allow all possible
// values for echo cancellation.
// TODO(crbug.com/1481032): Consider extending to other platforms. It is not
// known at the moment what OSes support this behavior.
const bool is_aec_reconfiguration_supported =
#if BUILDFLAG(IS_CHROMEOS)
// ChromeOS is currently the only platform where we have confirmed
// support for simultaneous streams with and without hardware AEC on the
// same device.
true;
#else
// Allowing it when the system echo cancellation is enforced via flag,
// for evaluation purposes.
media::IsSystemEchoCancellationEnforced() ||
source_info->properties().echo_cancellation_type !=
EchoCancellationType::kEchoCancellationSystem;
#endif
if (is_reconfiguration_allowed && is_aec_reconfiguration_supported) {
return;
}
ec_mode_allowed_values_ = EchoCancellationTypeSet(
{source_info->properties().echo_cancellation_type});
ec_allowed_values_ =
BoolSet({source_info->properties().echo_cancellation_type !=
EchoCancellationType::kEchoCancellationDisabled});
}
const char* ApplyConstraintSet(const ConstraintSet& constraint_set) {
// Convert the constraints into discrete sets.
BoolSet ec_set = blink::media_constraints::BoolSetFromConstraint(
constraint_set.echo_cancellation);
// Apply echoCancellation constraint.
ec_allowed_values_ = ec_allowed_values_.Intersection(ec_set);
if (ec_allowed_values_.IsEmpty())
return constraint_set.echo_cancellation.GetName();
// Translate the boolean values into EC modes.
ec_mode_allowed_values_ = ec_mode_allowed_values_.Intersection(
ToEchoCancellationTypes(ec_allowed_values_));
// Finally, if this container is empty, fail due to contradiction of the
// resulting allowed values for ec and/or ec_type.
return IsEmpty() ? constraint_set.echo_cancellation.GetName() : nullptr;
}
std::tuple<Score, EchoCancellationType> SelectSettingsAndScore(
const ConstraintSet& constraint_set) const {
EchoCancellationType selected_ec_mode = SelectBestEcMode(constraint_set);
double fitness =
Fitness(selected_ec_mode, constraint_set.echo_cancellation);
Score score(fitness);
score.set_ec_mode_score(GetEcModeScore(selected_ec_mode));
return std::make_tuple(score, selected_ec_mode);
}
bool IsEmpty() const { return ec_mode_allowed_values_.IsEmpty(); }
// Audio-processing properties are disabled by default for content capture,
// or if the |echo_cancellation| constraint is false.
void UpdateDefaultValues(
const BooleanConstraint& echo_cancellation_constraint,
AudioProcessingProperties* properties) const {
bool default_audio_processing_value =
GetDefaultValueForAudioProperties(echo_cancellation_constraint);
properties->auto_gain_control &= default_audio_processing_value;
properties->noise_suppression &= default_audio_processing_value;
properties->voice_isolation = VoiceIsolationType::kVoiceIsolationDefault;
}
bool GetDefaultValueForAudioProperties(
const BooleanConstraint& ec_constraint) const {
DCHECK(!ec_mode_allowed_values_.is_universal());
if (ec_constraint.HasIdeal() &&
ec_allowed_values_.Contains(ec_constraint.Ideal()))
return is_device_capture_ && ec_constraint.Ideal();
if (ec_allowed_values_.Contains(true))
return is_device_capture_;
return false;
}
private:
static Score::EcModeScore GetEcModeScore(EchoCancellationType mode) {
switch (mode) {
case EchoCancellationType::kEchoCancellationDisabled:
return Score::EcModeScore::kDisabled;
case EchoCancellationType::kEchoCancellationSystem:
return Score::EcModeScore::kSystem;
case EchoCancellationType::kEchoCancellationAec3:
return Score::EcModeScore::kAec3;
}
}
static EchoCancellationTypeSet ToEchoCancellationTypes(const BoolSet ec_set) {
Vector<EchoCancellationType> types;
if (ec_set.Contains(false))
types.push_back(EchoCancellationType::kEchoCancellationDisabled);
if (ec_set.Contains(true)) {
types.push_back(EchoCancellationType::kEchoCancellationAec3);
types.push_back(EchoCancellationType::kEchoCancellationSystem);
}
return EchoCancellationTypeSet(std::move(types));
}
EchoCancellationType SelectBestEcMode(
const ConstraintSet& constraint_set) const {
DCHECK(!IsEmpty());
DCHECK(!ec_mode_allowed_values_.is_universal());
// Try to use an ideal candidate, if supplied.
bool is_ec_preferred =
ShouldUseEchoCancellation(constraint_set.echo_cancellation);
if (!is_ec_preferred &&
ec_mode_allowed_values_.Contains(
EchoCancellationType::kEchoCancellationDisabled)) {
return EchoCancellationType::kEchoCancellationDisabled;
}
// If no ideal could be selected and the set contains only one value, pick
// that one.
if (ec_mode_allowed_values_.elements().size() == 1)
return ec_mode_allowed_values_.FirstElement();
// If no type has been selected, choose system if the device has the
// ECHO_CANCELLER flag set. Never automatically enable an experimental
// system echo canceller.
if (device_parameters_.IsValid() &&
ec_mode_allowed_values_.Contains(
EchoCancellationType::kEchoCancellationSystem) &&
(device_parameters_.effects() &
media::AudioParameters::ECHO_CANCELLER)) {
return EchoCancellationType::kEchoCancellationSystem;
}
// At this point we have at least two elements, hence the only two options
// from which to select are either AEC3 or System, where AEC3 has higher
// priority.
if (ec_mode_allowed_values_.Contains(
EchoCancellationType::kEchoCancellationAec3)) {
return EchoCancellationType::kEchoCancellationAec3;
}
DCHECK(ec_mode_allowed_values_.Contains(
EchoCancellationType::kEchoCancellationDisabled));
return EchoCancellationType::kEchoCancellationDisabled;
}
// This function computes the fitness score of the given |ec_mode|. The
// fitness is determined by the ideal values of |ec_constraint|. If |ec_mode|
// satisfies the constraint, the fitness score results in a value of 1, and 0
// otherwise. If no ideal value is specified, the fitness is 1.
double Fitness(const EchoCancellationType& ec_mode,
const BooleanConstraint& ec_constraint) const {
return ec_constraint.HasIdeal()
? ((ec_constraint.Ideal() &&
ec_mode !=
EchoCancellationType::kEchoCancellationDisabled) ||
(!ec_constraint.Ideal() &&
ec_mode == EchoCancellationType::kEchoCancellationDisabled))
: 1.0;
}
bool EchoCancellationModeContains(bool ec) const {
DCHECK(!ec_mode_allowed_values_.is_universal());
if (ec) {
return ec_mode_allowed_values_.Contains(
EchoCancellationType::kEchoCancellationAec3) ||
ec_mode_allowed_values_.Contains(
EchoCancellationType::kEchoCancellationSystem);
}
return ec_mode_allowed_values_.Contains(
EchoCancellationType::kEchoCancellationDisabled);
}
bool ShouldUseEchoCancellation(const BooleanConstraint& ec_constraint) const {
DCHECK(!ec_mode_allowed_values_.is_universal());
if (ec_constraint.HasIdeal() &&
EchoCancellationModeContains(ec_constraint.Ideal()))
return ec_constraint.Ideal();
// Echo cancellation is enabled by default for device capture and disabled
// by default for content capture.
if (EchoCancellationModeContains(true) &&
EchoCancellationModeContains(false))
return is_device_capture_;
return EchoCancellationModeContains(true);
}
BoolSet ec_allowed_values_;
EchoCancellationTypeSet ec_mode_allowed_values_;
media::AudioParameters device_parameters_;
bool is_device_capture_;
};
class AutoGainControlContainer {
public:
explicit AutoGainControlContainer(BoolSet allowed_values = BoolSet())
: allowed_values_(std::move(allowed_values)) {}
const char* ApplyConstraintSet(const ConstraintSet& constraint_set) {
BoolSet agc_set = blink::media_constraints::BoolSetFromConstraint(
constraint_set.auto_gain_control);
// Apply autoGainControl constraint.
allowed_values_ = allowed_values_.Intersection(agc_set);
return IsEmpty() ? constraint_set.auto_gain_control.GetName() : nullptr;
}
std::tuple<double, bool> SelectSettingsAndScore(
const ConstraintSet& constraint_set,
bool default_setting) const {
BooleanConstraint agc_constraint = constraint_set.auto_gain_control;
if (agc_constraint.HasIdeal()) {
bool agc_ideal = agc_constraint.Ideal();
if (allowed_values_.Contains(agc_ideal))
return std::make_tuple(1.0, agc_ideal);
}
if (allowed_values_.is_universal()) {
return std::make_tuple(0.0, default_setting);
}
return std::make_tuple(0.0, allowed_values_.FirstElement());
}
bool IsEmpty() const { return allowed_values_.IsEmpty(); }
private:
BoolSet allowed_values_;
};
class VoiceIsolationContainer {
public:
// Default constructor intended to temporarily create an empty object.
VoiceIsolationContainer(BoolSet allowed_values = BoolSet())
: allowed_values_(std::move(allowed_values)) {}
const char* ApplyConstraintSet(const ConstraintSet& constraint_set) {
BoolSet voice_isolation_set =
blink::media_constraints::BoolSetFromConstraint(
constraint_set.voice_isolation);
// Apply voice isolation constraint.
allowed_values_ = allowed_values_.Intersection(voice_isolation_set);
return IsEmpty() ? constraint_set.voice_isolation.GetName() : nullptr;
}
std::tuple<double, VoiceIsolationType> SelectSettingsAndScore(
const ConstraintSet& constraint_set,
VoiceIsolationType default_setting) const {
BooleanConstraint voice_isolation_constraint =
constraint_set.voice_isolation;
if (voice_isolation_constraint.HasIdeal()) {
VoiceIsolationType voice_isolation_type_ideal =
voice_isolation_constraint.Ideal()
? VoiceIsolationType::kVoiceIsolationEnabled
: VoiceIsolationType::kVoiceIsolationDisabled;
return std::make_tuple(1.0, voice_isolation_type_ideal);
}
if (allowed_values_.is_universal()) {
return std::make_tuple(0.0, default_setting);
}
VoiceIsolationType voice_isolation_first =
allowed_values_.FirstElement()
? VoiceIsolationType::kVoiceIsolationEnabled
: VoiceIsolationType::kVoiceIsolationDisabled;
return std::make_tuple(0.0, voice_isolation_first);
}
bool IsEmpty() const { return allowed_values_.IsEmpty(); }
private:
BoolSet allowed_values_;
};
Vector<int> GetApmSupportedChannels(
const media::AudioParameters& device_params) {
Vector<int> result;
// APM always supports mono output;
result.push_back(1);
const int channels = device_params.channels();
if (channels > 1)
result.push_back(channels);
return result;
}
// This container represents the supported audio settings for a given type of
// audio source. In practice, there are three types of sources: processed using
// APM, processed without APM, and unprocessed. Processing using APM has two
// flavors: one for the systems where audio processing is done in the renderer,
// another for the systems where audio processing is done in the audio service.
class ProcessingBasedContainer {
public:
// Creates an instance of ProcessingBasedContainer for the WebRTC processed
// source type. The source type allows (a) any type of echo cancellation,
// though the system echo cancellation type depends on the availability of the
// related |parameters.effects()|, and (b) any combination of processing
// properties settings.
static ProcessingBasedContainer CreateApmProcessedContainer(
std::optional<SourceInfo> source_info,
mojom::blink::MediaStreamType stream_type,
bool is_device_capture,
const media::AudioParameters& device_parameters,
bool is_reconfiguration_allowed) {
return ProcessingBasedContainer(
ProcessingType::kApmProcessed,
{EchoCancellationType::kEchoCancellationAec3,
EchoCancellationType::kEchoCancellationDisabled},
BoolSet(), /* auto_gain_control_set */
BoolSet(), /* noise_suppression_set */
BoolSet(), /* voice_isolation_set */
IntRangeSet::FromValue(GetSampleSize()), /* sample_size_range */
GetApmSupportedChannels(device_parameters), /* channels_set */
IntRangeSet::FromValue(
media::WebRtcAudioProcessingSampleRateHz()), /* sample_rate_range */
source_info, is_device_capture, device_parameters,
is_reconfiguration_allowed);
}
// Creates an instance of ProcessingBasedContainer for the processed source
// type. The source type allows (a) either system echo cancellation, if
// allowed by the |parameters.effects()|, or none, while (b) all other
// processing properties settings cannot be enabled.
static ProcessingBasedContainer CreateNoApmProcessedContainer(
std::optional<SourceInfo> source_info,
bool is_device_capture,
const media::AudioParameters& device_parameters,
bool is_reconfiguration_allowed) {
return ProcessingBasedContainer(
ProcessingType::kNoApmProcessed,
{EchoCancellationType::kEchoCancellationDisabled},
BoolSet({false}), /* auto_gain_control_set */
BoolSet({false}), /* noise_suppression_set */
BoolSet(), /* voice_isolation_set */
IntRangeSet::FromValue(GetSampleSize()), /* sample_size_range */
{device_parameters.channels()}, /* channels_set */
IntRangeSet::FromValue(
device_parameters.sample_rate()), /* sample_rate_range */
source_info, is_device_capture, device_parameters,
is_reconfiguration_allowed);
}
// Creates an instance of ProcessingBasedContainer for the unprocessed source
// type. The source type allows (a) either system echo cancellation, if
// allowed by the |parameters.effects()|, or none, while (c) all processing
// properties settings cannot be enabled.
static ProcessingBasedContainer CreateUnprocessedContainer(
std::optional<SourceInfo> source_info,
bool is_device_capture,
const media::AudioParameters& device_parameters,
bool is_reconfiguration_allowed) {
return ProcessingBasedContainer(
ProcessingType::kUnprocessed,
{EchoCancellationType::kEchoCancellationDisabled},
BoolSet({false}), /* auto_gain_control_set */
BoolSet({false}), /* noise_suppression_set */
BoolSet({false}), /* voice_isolation_set */
IntRangeSet::FromValue(GetSampleSize()), /* sample_size_range */
{device_parameters.channels()}, /* channels_set */
IntRangeSet::FromValue(
device_parameters.sample_rate()), /* sample_rate_range */
source_info, is_device_capture, device_parameters,
is_reconfiguration_allowed);
}
const char* ApplyConstraintSet(const ConstraintSet& constraint_set) {
const char* failed_constraint_name = nullptr;
failed_constraint_name =
echo_cancellation_container_.ApplyConstraintSet(constraint_set);
if (failed_constraint_name)
return failed_constraint_name;
failed_constraint_name =
auto_gain_control_container_.ApplyConstraintSet(constraint_set);
if (failed_constraint_name)
return failed_constraint_name;
failed_constraint_name =
voice_isolation_container_.ApplyConstraintSet(constraint_set);
if (failed_constraint_name) {
return failed_constraint_name;
}
failed_constraint_name =
sample_size_container_.ApplyConstraintSet(constraint_set.sample_size);
if (failed_constraint_name)
return failed_constraint_name;
failed_constraint_name =
channels_container_.ApplyConstraintSet(constraint_set.channel_count);
if (failed_constraint_name)
return failed_constraint_name;
failed_constraint_name =
sample_rate_container_.ApplyConstraintSet(constraint_set.sample_rate);
if (failed_constraint_name)
return failed_constraint_name;
failed_constraint_name =
latency_container_.ApplyConstraintSet(constraint_set.latency);
if (failed_constraint_name)
return failed_constraint_name;
failed_constraint_name = noise_suppression_container_.ApplyConstraintSet(
constraint_set.noise_suppression);
if (failed_constraint_name) {
return failed_constraint_name;
}
return failed_constraint_name;
}
std::tuple<Score,
AudioProcessingProperties,
std::optional<int> /* requested_buffer_size */,
int /* num_channels */>
SelectSettingsAndScore(const ConstraintSet& constraint_set,
const media::AudioParameters& parameters) const {
DCHECK(!IsEmpty());
Score score(0.0);
double sub_score(0.0);
std::tie(sub_score, std::ignore) =
sample_size_container_.SelectSettingsAndScore(
constraint_set.sample_size, GetSampleSize());
score += sub_score;
std::optional<int> num_channels;
std::tie(sub_score, num_channels) =
channels_container_.SelectSettingsAndScore(constraint_set.channel_count,
/*default_setting=*/1);
DCHECK(num_channels);
score += sub_score;
std::optional<int> sample_size;
std::tie(sub_score, sample_size) =
sample_rate_container_.SelectSettingsAndScore(
constraint_set.sample_rate);
DCHECK(sample_size != std::nullopt);
score += sub_score;
std::optional<double> latency;
std::tie(sub_score, latency) =
latency_container_.SelectSettingsAndScore(constraint_set.latency);
score += sub_score;
// Only request an explicit change to the buffer size for the unprocessed
// container, and only if it's based on a specific user constraint.
std::optional<int> requested_buffer_size;
if (processing_type_ == ProcessingType::kUnprocessed && latency &&
!constraint_set.latency.IsUnconstrained()) {
auto [min_buffer_size, max_buffer_size] =
GetMinMaxBufferSizesForAudioParameters(parameters);
requested_buffer_size = media::AudioLatency::GetExactBufferSize(
base::Seconds(*latency), parameters.sample_rate(),
parameters.frames_per_buffer(), min_buffer_size, max_buffer_size,
max_buffer_size);
}
AudioProcessingProperties properties;
Score ec_score(0.0);
std::tie(ec_score, properties.echo_cancellation_type) =
echo_cancellation_container_.SelectSettingsAndScore(constraint_set);
score += ec_score;
// Update the default settings for each audio-processing properties
// according to |echo_cancellation| and whether the source considered is
// device capture.
echo_cancellation_container_.UpdateDefaultValues(
constraint_set.echo_cancellation, &properties);
std::tie(sub_score, properties.auto_gain_control) =
auto_gain_control_container_.SelectSettingsAndScore(
constraint_set, properties.auto_gain_control);
score += sub_score;
std::tie(sub_score, properties.voice_isolation) =
voice_isolation_container_.SelectSettingsAndScore(
constraint_set, properties.voice_isolation);
score += sub_score;
std::tie(sub_score, properties.noise_suppression) =
noise_suppression_container_.SelectSettingsAndScore(
constraint_set.noise_suppression, properties.noise_suppression);
score += sub_score;
score.set_processing_priority(
GetProcessingPriority(constraint_set.echo_cancellation));
return std::make_tuple(score, properties, requested_buffer_size,
*num_channels);
}
// The ProcessingBasedContainer is considered empty if at least one of the
// containers owned by it is empty.
bool IsEmpty() const {
return echo_cancellation_container_.IsEmpty() ||
auto_gain_control_container_.IsEmpty() ||
noise_suppression_container_.IsEmpty() ||
sample_size_container_.IsEmpty() || channels_container_.IsEmpty() ||
sample_rate_container_.IsEmpty() || latency_container_.IsEmpty();
}
ProcessingType processing_type() const { return processing_type_; }
private:
// Private constructor intended to instantiate different variants of this
// class based on the initial values provided. The appropriate way to
// instantiate this class is via the three factory methods provided.
// System echo cancellation should not be explicitly included in
// |echo_cancellation_type|. It is added automatically based on the value of
// |device_parameters|.
ProcessingBasedContainer(ProcessingType processing_type,
Vector<EchoCancellationType> echo_cancellation_types,
BoolSet auto_gain_control_set,
BoolSet noise_suppression_set,
BoolSet voice_isolation_set,
IntRangeSet sample_size_range,
Vector<int> channels_set,
IntRangeSet sample_rate_range,
std::optional<SourceInfo> source_info,
bool is_device_capture,
media::AudioParameters device_parameters,
bool is_reconfiguration_allowed)
: processing_type_(processing_type),
sample_size_container_(sample_size_range),
channels_container_(std::move(channels_set)),
sample_rate_container_(sample_rate_range),
latency_container_(
GetAllowedLatency(processing_type, device_parameters)) {
// If the parameters indicate that system echo cancellation is available, we
// add such value in the allowed values for the EC type.
if (device_parameters.effects() & media::AudioParameters::ECHO_CANCELLER) {
echo_cancellation_types.push_back(
EchoCancellationType::kEchoCancellationSystem);
}
echo_cancellation_container_ = EchoCancellationContainer(
std::move(echo_cancellation_types), source_info, is_device_capture,
device_parameters, is_reconfiguration_allowed);
auto_gain_control_container_ =
AutoGainControlContainer(auto_gain_control_set);
voice_isolation_container_ = VoiceIsolationContainer(voice_isolation_set);
noise_suppression_container_ = BooleanContainer(noise_suppression_set);
// Allow the full set of supported values when the device is not open or
// when the candidate settings would open the device using an unprocessed
// source.
if (!source_info || (is_reconfiguration_allowed &&
processing_type_ == ProcessingType::kUnprocessed)) {
return;
}
// If the device is already opened, restrict supported values for
// non-reconfigurable settings to what is already configured. The rationale
// for this is that opening multiple instances of the APM is costly.
// TODO(crbug.com/1147928): Consider removing this restriction.
auto_gain_control_container_ = AutoGainControlContainer(
BoolSet({source_info->properties().auto_gain_control}));
noise_suppression_container_ = BooleanContainer(
BoolSet({source_info->properties().noise_suppression}));
channels_container_ = IntegerDiscreteContainer({source_info->channels()});
sample_rate_container_ = IntegerRangeContainer(
IntRangeSet::FromValue(source_info->sample_rate()));
latency_container_ =
DoubleRangeContainer(DoubleRangeSet::FromValue(source_info->latency()));
}
// The allowed latency is expressed in a range latencies in seconds.
static const DoubleRangeSet GetAllowedLatency(
ProcessingType processing_type,
const media::AudioParameters& device_parameters) {
double fallback_latency =
static_cast<double>(blink::kFallbackAudioLatencyMs) / 1000;
double device_latency = device_parameters.GetBufferDuration().InSecondsF();
double allowed_latency = device_parameters.frames_per_buffer() > 0
? device_latency
: fallback_latency;
switch (processing_type) {
case ProcessingType::kApmProcessed:
return DoubleRangeSet::FromValue(fallback_latency);
case ProcessingType::kNoApmProcessed:
return DoubleRangeSet::FromValue(allowed_latency);
case ProcessingType::kUnprocessed:
auto [min_latency, max_latency] =
GetMinMaxLatenciesForAudioParameters(device_parameters);
return DoubleRangeSet(min_latency, max_latency);
}
}
// The priority of each processing-based container depends on the default
// value assigned to the audio processing properties. When the value is true
// the preference gives higher priority to the WebRTC processing.
// On the contrary, if the value is false the preference is flipped towards
// the option without processing.
int GetProcessingPriority(const BooleanConstraint& ec_constraint) const {
bool use_processing_by_default =
echo_cancellation_container_.GetDefaultValueForAudioProperties(
ec_constraint);
switch (processing_type_) {
case ProcessingType::kUnprocessed:
return use_processing_by_default ? 1 : 3;
case ProcessingType::kNoApmProcessed:
return 2;
case ProcessingType::kApmProcessed:
return use_processing_by_default ? 3 : 1;
}
}
ProcessingType processing_type_;
EchoCancellationContainer echo_cancellation_container_;
AutoGainControlContainer auto_gain_control_container_;
BooleanContainer noise_suppression_container_;
VoiceIsolationContainer voice_isolation_container_;
IntegerRangeContainer sample_size_container_;
IntegerDiscreteContainer channels_container_;
IntegerRangeContainer sample_rate_container_;
DoubleRangeContainer latency_container_;
};
// Container for the constrainable properties of a single audio device.
class DeviceContainer {
public:
DeviceContainer(const AudioDeviceCaptureCapability& capability,
mojom::blink::MediaStreamType stream_type,
bool is_device_capture,
bool is_reconfiguration_allowed)
: device_parameters_(capability.Parameters()) {
if (!capability.DeviceID().empty()) {
device_id_container_ =
StringContainer(StringSet({capability.DeviceID().Utf8()}));
}
if (!capability.GroupID().empty()) {
group_id_container_ =
StringContainer(StringSet({capability.GroupID().Utf8()}));
}
// If the device is in use, a source will be provided and all containers
// must be initialized such that their only supported values correspond to
// the source settings. Otherwise, the containers are initialized to contain
// all possible values.
std::optional<SourceInfo> source_info =
SourceInfo::FromSource(capability.source());
// Three variations of the processing-based container. Each variant is
// associated to a different type of audio processing configuration, namely
// unprocessed, processed by WebRTC, or processed by other means.
processing_based_containers_.push_back(
ProcessingBasedContainer::CreateUnprocessedContainer(
source_info, is_device_capture, device_parameters_,
is_reconfiguration_allowed));
processing_based_containers_.push_back(
ProcessingBasedContainer::CreateNoApmProcessedContainer(
source_info, is_device_capture, device_parameters_,
is_reconfiguration_allowed));
processing_based_containers_.push_back(
ProcessingBasedContainer::CreateApmProcessedContainer(
source_info, stream_type, is_device_capture, device_parameters_,
is_reconfiguration_allowed));
DCHECK_EQ(processing_based_containers_.size(), 3u);
if (!source_info) {
return;
}
blink::MediaStreamAudioSource* source = capability.source();
boolean_containers_[kDisableLocalEcho] =
BooleanContainer(BoolSet({source->disable_local_echo()}));
boolean_containers_[kRenderToAssociatedSink] =
BooleanContainer(BoolSet({source->RenderToAssociatedSinkEnabled()}));
#if DCHECK_IS_ON()
for (const auto& container : boolean_containers_)
DCHECK(!container.IsEmpty());
#endif
}
const char* ApplyConstraintSet(const ConstraintSet& constraint_set) {
const char* failed_constraint_name;
failed_constraint_name =
device_id_container_.ApplyConstraintSet(constraint_set.device_id);
if (failed_constraint_name)
return failed_constraint_name;
failed_constraint_name =
group_id_container_.ApplyConstraintSet(constraint_set.group_id);
if (failed_constraint_name)
return failed_constraint_name;
for (const auto& info : kBooleanPropertyContainerInfoMap) {
failed_constraint_name =
boolean_containers_[info.index].ApplyConstraintSet(
constraint_set.*(info.constraint_member));
if (failed_constraint_name)
return failed_constraint_name;
}
// For each processing based container, apply the constraints and only fail
// if all of them failed.
auto to_remove = std::ranges::remove_if(
processing_based_containers_,
[&constraint_set, &failed_constraint_name](auto& t) {
DCHECK(!t.IsEmpty());
failed_constraint_name = t.ApplyConstraintSet(constraint_set);
return !!failed_constraint_name;
});
processing_based_containers_.erase(to_remove.begin(), to_remove.end());
if (processing_based_containers_.empty()) {
DCHECK_NE(failed_constraint_name, nullptr);
return failed_constraint_name;
}
return nullptr;
}
std::tuple<Score, AudioCaptureSettings> SelectSettingsAndScore(
const ConstraintSet& constraint_set,
bool is_destkop_source,
std::string default_device_id) const {
DCHECK(!IsEmpty());
Score score(0.0);
auto [sub_score, device_id] = device_id_container_.SelectSettingsAndScore(
constraint_set.device_id, default_device_id);
score += sub_score;
std::tie(sub_score, std::ignore) =
group_id_container_.SelectSettingsAndScore(constraint_set.group_id,
std::string());
score += sub_score;
bool disable_local_echo;
std::tie(sub_score, disable_local_echo) =
boolean_containers_[kDisableLocalEcho].SelectSettingsAndScore(
constraint_set.disable_local_echo, !is_destkop_source);
score += sub_score;
bool render_to_associated_sink;
std::tie(sub_score, render_to_associated_sink) =
boolean_containers_[kRenderToAssociatedSink].SelectSettingsAndScore(
constraint_set.render_to_associated_sink, false);
score += sub_score;
// To determine which properties to use, we have to compare and compute the
// scores of each properties set and use the best performing one. In this
// loop we are also determining the best settings that should be applied to
// the best performing candidate.
Score best_score(-1.0);
AudioProcessingProperties best_properties;
const ProcessingBasedContainer* best_container = nullptr;
std::optional<int> best_requested_buffer_size;
int best_num_channels = 1;
for (const auto& container : processing_based_containers_) {
if (container.IsEmpty())
continue;
auto [container_score, container_properties, requested_buffer_size,
num_channels] =
container.SelectSettingsAndScore(constraint_set, device_parameters_);
if (container_score > best_score) {
best_score = container_score;
best_properties = container_properties;
best_container = &container;
best_requested_buffer_size = requested_buffer_size;
best_num_channels = num_channels;
}
}
DCHECK_NE(best_container, nullptr);
score += best_score;
// The score at this point can be considered complete only when the settings
// are compared against the default device id, which is used as arbitrator
// in case multiple candidates are available.
return std::make_tuple(
score, AudioCaptureSettings(
device_id, best_requested_buffer_size, disable_local_echo,
render_to_associated_sink, best_container->processing_type(),
best_properties, best_num_channels));
}
// The DeviceContainer is considered empty if at least one of the
// containers owned is empty.
bool IsEmpty() const {
DCHECK(!boolean_containers_.empty());
for (auto& container : boolean_containers_) {
if (container.IsEmpty())
return true;
}
return device_id_container_.IsEmpty() || group_id_container_.IsEmpty();
}
private:
enum BooleanContainerId {
kDisableLocalEcho,
kRenderToAssociatedSink,
kNumBooleanContainerIds
};
// This struct groups related fields or entries from
// DeviceContainer::boolean_containers_ and MediaTrackConstraintSetPlatform.
struct BooleanPropertyContainerInfo {
BooleanContainerId index;
BooleanConstraint ConstraintSet::*constraint_member;
};
static constexpr BooleanPropertyContainerInfo
kBooleanPropertyContainerInfoMap[] = {
{kDisableLocalEcho, &ConstraintSet::disable_local_echo},
{kRenderToAssociatedSink, &ConstraintSet::render_to_associated_sink}};
media::AudioParameters device_parameters_;
StringContainer device_id_container_;
StringContainer group_id_container_;
std::array<BooleanContainer, kNumBooleanContainerIds> boolean_containers_;
Vector<ProcessingBasedContainer> processing_based_containers_;
};
constexpr DeviceContainer::BooleanPropertyContainerInfo
DeviceContainer::kBooleanPropertyContainerInfoMap[];
// This class represents a set of possible candidate settings. The
// SelectSettings algorithm starts with a set containing all possible candidates
// based on system/hardware capabilities and/or allowed values for supported
// properties. The set is then reduced progressively as the basic and advanced
// constraint sets are applied. In the end, if the set of candidates is empty,
// SelectSettings fails. If not, the ideal values (if any) or tie breaker rules
// are used to select the final settings based on the candidates that survived
// the application of the constraint sets. This class is implemented as a
// collection of more specific sets for the various supported properties. If any
// of the specific sets is empty, the whole CandidatesContainer is considered
// empty as well.
class CandidatesContainer {
public:
CandidatesContainer(const AudioDeviceCaptureCapabilities& capabilities,
mojom::blink::MediaStreamType stream_type,
std::string& media_stream_source,
std::string& default_device_id,
bool is_reconfiguration_allowed)
: default_device_id_(default_device_id) {
const bool is_device_capture = media_stream_source.empty();
for (const auto& capability : capabilities) {
devices_.emplace_back(capability, stream_type, is_device_capture,
is_reconfiguration_allowed);
DCHECK(!devices_.back().IsEmpty());
}
}
const char* ApplyConstraintSet(const ConstraintSet& constraint_set) {
const char* latest_failed_constraint_name = nullptr;
auto to_remove = std::ranges::remove_if(
devices_, [&constraint_set, &latest_failed_constraint_name](auto& t) {
DCHECK(!t.IsEmpty());
const auto* failed_constraint_name =
t.ApplyConstraintSet(constraint_set);
if (failed_constraint_name) {
latest_failed_constraint_name = failed_constraint_name;
}
return !!failed_constraint_name;
});
devices_.erase(to_remove.begin(), to_remove.end());
return IsEmpty() ? latest_failed_constraint_name : nullptr;
}
std::tuple<Score, AudioCaptureSettings> SelectSettingsAndScore(
const ConstraintSet& constraint_set,
bool is_desktop_source) const {
DCHECK(!IsEmpty());
// Make a copy of the settings initially provided, to track the default
// settings.
AudioCaptureSettings best_settings;
Score best_score(-1.0);
for (const auto& candidate : devices_) {
auto [score, settings] = candidate.SelectSettingsAndScore(
constraint_set, is_desktop_source, default_device_id_);
score += default_device_id_ == settings.device_id();
if (score > best_score) {
best_score = score;
best_settings = std::move(settings);
}
}
return std::make_tuple(best_score, best_settings);
}
bool IsEmpty() const { return devices_.empty(); }
private:
std::string default_device_id_;
Vector<DeviceContainer> devices_;
};
std::string GetMediaStreamSource(const MediaConstraints& constraints) {
std::string source;
if (constraints.Basic().media_stream_source.HasIdeal() &&
constraints.Basic().media_stream_source.Ideal().size() > 0) {
source = constraints.Basic().media_stream_source.Ideal()[0].Utf8();
}
if (constraints.Basic().media_stream_source.HasExact() &&
constraints.Basic().media_stream_source.Exact().size() > 0) {
source = constraints.Basic().media_stream_source.Exact()[0].Utf8();
}
return source;
}
} // namespace
AudioDeviceCaptureCapability::AudioDeviceCaptureCapability()
: parameters_(media::AudioParameters::UnavailableDeviceParams()) {}
AudioDeviceCaptureCapability::AudioDeviceCaptureCapability(
blink::MediaStreamAudioSource* source)
: source_(source) {}
AudioDeviceCaptureCapability::AudioDeviceCaptureCapability(
String device_id,
String group_id,
const media::AudioParameters& parameters)
: device_id_(std::move(device_id)),
group_id_(std::move(group_id)),
parameters_(parameters) {
DCHECK(!device_id_.empty());
}
AudioDeviceCaptureCapability::AudioDeviceCaptureCapability(
const AudioDeviceCaptureCapability&) = default;
AudioDeviceCaptureCapability& AudioDeviceCaptureCapability::operator=(
const AudioDeviceCaptureCapability&) = default;
String AudioDeviceCaptureCapability::DeviceID() const {
return source_ ? String(source_->device().id.data()) : device_id_;
}
String AudioDeviceCaptureCapability::GroupID() const {
return source_ && source_->device().group_id
? String(source_->device().group_id->data())
: group_id_;
}
const media::AudioParameters& AudioDeviceCaptureCapability::Parameters() const {
return source_ ? source_->device().input : parameters_;
}
AudioCaptureSettings SelectSettingsAudioCapture(
const AudioDeviceCaptureCapabilities& capabilities,
const MediaConstraints& constraints,
mojom::blink::MediaStreamType stream_type,
bool is_reconfiguration_allowed) {
if (capabilities.empty())
return AudioCaptureSettings();
std::string media_stream_source = GetMediaStreamSource(constraints);
std::string default_device_id;
bool is_device_capture = media_stream_source.empty();
if (is_device_capture)
default_device_id = capabilities.begin()->DeviceID().Utf8();
CandidatesContainer candidates(capabilities, stream_type, media_stream_source,
default_device_id, is_reconfiguration_allowed);
DCHECK(!candidates.IsEmpty());
auto* failed_constraint_name =
candidates.ApplyConstraintSet(constraints.Basic());
if (failed_constraint_name)
return AudioCaptureSettings(failed_constraint_name);
for (const auto& advanced_set : constraints.Advanced()) {
CandidatesContainer copy = candidates;
failed_constraint_name = candidates.ApplyConstraintSet(advanced_set);
if (failed_constraint_name)
candidates = std::move(copy);
}
DCHECK(!candidates.IsEmpty());
// Score is ignored as it is no longer needed.
AudioCaptureSettings settings;
std::tie(std::ignore, settings) = candidates.SelectSettingsAndScore(
constraints.Basic(),
media_stream_source == blink::kMediaStreamSourceDesktop);
return settings;
}
AudioCaptureSettings SelectSettingsAudioCapture(
blink::MediaStreamAudioSource* source,
const MediaConstraints& constraints) {
DCHECK(source);
if (source->device().type !=
blink::mojom::MediaStreamType::DEVICE_AUDIO_CAPTURE &&
source->device().type !=
blink::mojom::MediaStreamType::GUM_TAB_AUDIO_CAPTURE &&
source->device().type !=
blink::mojom::MediaStreamType::GUM_DESKTOP_AUDIO_CAPTURE) {
return AudioCaptureSettings();
}
std::string media_stream_source = GetMediaStreamSource(constraints);
if (source->device().type ==
blink::mojom::MediaStreamType::DEVICE_AUDIO_CAPTURE &&
!media_stream_source.empty()) {
return AudioCaptureSettings(
constraints.Basic().media_stream_source.GetName());
}
if (source->device().type ==
blink::mojom::MediaStreamType::GUM_TAB_AUDIO_CAPTURE &&
!media_stream_source.empty() &&
media_stream_source != blink::kMediaStreamSourceTab) {
return AudioCaptureSettings(
constraints.Basic().media_stream_source.GetName());
}
if (source->device().type ==
blink::mojom::MediaStreamType::GUM_DESKTOP_AUDIO_CAPTURE &&
!media_stream_source.empty() &&
media_stream_source != blink::kMediaStreamSourceSystem &&
media_stream_source != blink::kMediaStreamSourceDesktop) {
return AudioCaptureSettings(
constraints.Basic().media_stream_source.GetName());
}
AudioDeviceCaptureCapabilities capabilities = {
AudioDeviceCaptureCapability(source)};
return SelectSettingsAudioCapture(capabilities, constraints,
source->device().type,
/*is_reconfiguration_allowed=*/false);
}
MODULES_EXPORT base::expected<Vector<blink::AudioCaptureSettings>, std::string>
SelectEligibleSettingsAudioCapture(
const AudioDeviceCaptureCapabilities& capabilities,
const MediaConstraints& constraints,
mojom::blink::MediaStreamType stream_type,
bool is_reconfiguration_allowed) {
Vector<AudioCaptureSettings> settings;
std::string failed_constraint_name;
for (const auto& device : capabilities) {
const auto device_settings = SelectSettingsAudioCapture(
{device}, constraints, stream_type, is_reconfiguration_allowed);
if (device_settings.HasValue()) {
settings.push_back(device_settings);
} else {
failed_constraint_name = device_settings.failed_constraint_name();
}
}
if (settings.empty()) {
return base::unexpected(failed_constraint_name);
}
return settings;
}
std::tuple<int, int> GetMinMaxBufferSizesForAudioParameters(
const media::AudioParameters& parameters) {
const int default_buffer_size = parameters.frames_per_buffer();
DCHECK_GT(default_buffer_size, 0);
const std::optional<media::AudioParameters::HardwareCapabilities>
hardware_capabilities = parameters.hardware_capabilities();
// Only support platforms where we have both fixed min and max buffer size
// values in order to simplify comparison logic.
DCHECK(!hardware_capabilities ||
(hardware_capabilities &&
// Windows returns a HardwareCapabilities with both values set to 0 if
// they're unknown rather than returning null.
((hardware_capabilities->min_frames_per_buffer == 0 &&
hardware_capabilities->max_frames_per_buffer == 0) ||
(hardware_capabilities->min_frames_per_buffer > 0 &&
hardware_capabilities->max_frames_per_buffer > 0))))
<< "Variable input latency requires both a min and max to be set";
return (hardware_capabilities &&
hardware_capabilities->min_frames_per_buffer > 0 &&
hardware_capabilities->max_frames_per_buffer > 0)
? std::make_tuple(hardware_capabilities->min_frames_per_buffer,
hardware_capabilities->max_frames_per_buffer)
: std::make_tuple(default_buffer_size, default_buffer_size);
}
std::tuple<double, double> GetMinMaxLatenciesForAudioParameters(
const media::AudioParameters& parameters) {
auto [min_buffer_size, max_buffer_size] =
GetMinMaxBufferSizesForAudioParameters(parameters);
// Doing the microseconds conversion to match what is done in
// AudioParameters::GetBufferDuration() so that values reported to the user
// are truncated consistently to the microseconds decimal place.
return std::make_tuple(
base::Microseconds(
static_cast<int64_t>(min_buffer_size *
base::Time::kMicrosecondsPerSecond /
static_cast<float>(parameters.sample_rate())))
.InSecondsF(),
base::Microseconds(
static_cast<int64_t>(max_buffer_size *
base::Time::kMicrosecondsPerSecond /
static_cast<float>(parameters.sample_rate())))
.InSecondsF());
}
} // namespace blink
|