tdesktop/Telegram/SourceFiles/calls/calls_call.cpp

1104 lines
32 KiB
C++
Raw Normal View History

/*
This file is part of Telegram Desktop,
the official desktop application for the Telegram messaging service.
For license and copyright information please follow this link:
https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
*/
#include "calls/calls_call.h"
2019-07-24 11:45:24 +00:00
#include "main/main_session.h"
2020-07-09 17:38:26 +00:00
#include "main/main_account.h"
#include "main/main_app_config.h"
#include "apiwrap.h"
2017-04-13 08:27:10 +00:00
#include "lang/lang_keys.h"
#include "boxes/confirm_box.h"
#include "boxes/rate_call_box.h"
#include "calls/calls_instance.h"
#include "base/openssl_help.h"
2019-11-13 14:12:04 +00:00
#include "mtproto/mtproto_dh_utils.h"
#include "mtproto/mtproto_config.h"
#include "core/application.h"
#include "core/core_settings.h"
#include "media/audio/media_audio_track.h"
2019-09-17 16:13:12 +00:00
#include "base/platform/base_platform_info.h"
#include "calls/calls_panel.h"
2020-07-17 18:59:38 +00:00
#include "webrtc/webrtc_video_track.h"
#include "webrtc/webrtc_media_devices.h"
#include "data/data_user.h"
2019-01-18 12:27:37 +00:00
#include "data/data_session.h"
#include "facades.h"
2020-07-10 13:55:46 +00:00
#include <tgcalls/Instance.h>
2020-07-16 16:23:55 +00:00
#include <tgcalls/VideoCaptureInterface.h>
2020-07-09 17:38:26 +00:00
namespace tgcalls {
class InstanceImpl;
class InstanceImplLegacy;
class InstanceImplReference;
2020-07-09 17:38:26 +00:00
void SetLegacyGlobalServerConfig(const std::string &serverConfig);
} // namespace tgcalls
namespace Calls {
namespace {
constexpr auto kMinLayer = 65;
constexpr auto kHangupTimeoutMs = 5000;
constexpr auto kSha256Size = 32;
const auto kDefaultVersion = "2.4.4"_q;
2020-08-11 13:31:27 +00:00
#ifndef DESKTOP_APP_DISABLE_WEBRTC_INTEGRATION
2020-07-09 17:38:26 +00:00
const auto RegisterTag = tgcalls::Register<tgcalls::InstanceImpl>();
2020-07-31 14:36:35 +00:00
//const auto RegisterTagReference = tgcalls::Register<tgcalls::InstanceImplReference>();
2020-08-11 13:31:27 +00:00
#endif // DESKTOP_APP_DISABLE_WEBRTC_INTEGRATION
const auto RegisterTagLegacy = tgcalls::Register<tgcalls::InstanceImplLegacy>();
2020-07-09 17:38:26 +00:00
void AppendEndpoint(
2020-07-09 17:38:26 +00:00
std::vector<tgcalls::Endpoint> &list,
const MTPPhoneConnection &connection) {
connection.match([&](const MTPDphoneConnection &data) {
2019-07-05 13:38:38 +00:00
if (data.vpeer_tag().v.length() != 16) {
return;
}
tgcalls::Endpoint endpoint = {
.endpointId = (int64_t)data.vid().v,
2020-07-09 17:38:26 +00:00
.host = tgcalls::EndpointHost{
.ipv4 = data.vip().v.toStdString(),
.ipv6 = data.vipv6().v.toStdString() },
.port = (uint16_t)data.vport().v,
2020-08-04 18:31:30 +00:00
.type = tgcalls::EndpointType::UdpRelay,
};
const auto tag = data.vpeer_tag().v;
if (tag.size() >= 16) {
memcpy(endpoint.peerTag, tag.data(), 16);
}
list.push_back(std::move(endpoint));
2020-08-04 18:31:30 +00:00
}, [&](const MTPDphoneConnectionWebrtc &data) {
});
}
void AppendServer(
std::vector<tgcalls::RtcServer> &list,
const MTPPhoneConnection &connection) {
connection.match([&](const MTPDphoneConnection &data) {
}, [&](const MTPDphoneConnectionWebrtc &data) {
const auto host = qs(data.vip());
const auto hostv6 = qs(data.vipv6());
const auto port = uint16_t(data.vport().v);
if (data.is_stun()) {
const auto pushStun = [&](const QString &host) {
if (host.isEmpty()) {
return;
}
2020-08-11 09:59:48 +00:00
list.push_back(tgcalls::RtcServer{
2020-08-04 18:31:30 +00:00
.host = host.toStdString(),
.port = port,
.isTurn = false
});
};
pushStun(host);
pushStun(hostv6);
}
const auto username = qs(data.vusername());
const auto password = qs(data.vpassword());
if (data.is_turn() && !username.isEmpty() && !password.isEmpty()) {
const auto pushTurn = [&](const QString &host) {
2020-08-11 09:59:48 +00:00
list.push_back(tgcalls::RtcServer{
2020-08-04 18:31:30 +00:00
.host = host.toStdString(),
.port = port,
.login = username.toStdString(),
.password = password.toStdString(),
.isTurn = true,
});
};
pushTurn(host);
pushTurn(hostv6);
}
});
}
constexpr auto kFingerprintDataSize = 256;
uint64 ComputeFingerprint(bytes::const_span authKey) {
Expects(authKey.size() == kFingerprintDataSize);
auto hash = openssl::Sha1(authKey);
return (gsl::to_integer<uint64>(hash[19]) << 56)
| (gsl::to_integer<uint64>(hash[18]) << 48)
| (gsl::to_integer<uint64>(hash[17]) << 40)
| (gsl::to_integer<uint64>(hash[16]) << 32)
| (gsl::to_integer<uint64>(hash[15]) << 24)
| (gsl::to_integer<uint64>(hash[14]) << 16)
| (gsl::to_integer<uint64>(hash[13]) << 8)
| (gsl::to_integer<uint64>(hash[12]));
}
[[nodiscard]] QVector<MTPstring> WrapVersions(
const std::vector<std::string> &data) {
auto result = QVector<MTPstring>();
result.reserve(data.size());
for (const auto &version : data) {
result.push_back(MTP_string(version));
2018-05-24 16:42:57 +00:00
}
return result;
2018-05-24 16:42:57 +00:00
}
[[nodiscard]] QVector<MTPstring> CollectVersionsForApi() {
2020-07-09 17:38:26 +00:00
return WrapVersions(tgcalls::Meta::Versions() | ranges::action::reverse);
}
2020-08-11 09:59:48 +00:00
[[nodiscard]] Webrtc::VideoState StartVideoState(bool enabled) {
using State = Webrtc::VideoState;
2020-08-05 12:11:18 +00:00
return enabled ? State::Active : State::Inactive;
}
} // namespace
2018-05-24 16:42:57 +00:00
2018-05-06 21:29:53 +00:00
Call::Call(
not_null<Delegate*> delegate,
not_null<UserData*> user,
Type type,
bool video)
: _delegate(delegate)
, _user(user)
, _api(&_user->session().mtp())
2020-07-31 14:36:35 +00:00
, _type(type)
2020-08-11 09:59:48 +00:00
, _videoIncoming(std::make_unique<Webrtc::VideoTrack>(StartVideoState(video)))
, _videoOutgoing(std::make_unique<Webrtc::VideoTrack>(StartVideoState(video))) {
2020-07-31 14:36:35 +00:00
_discardByTimeoutTimer.setCallback([=] { hangup(); });
if (_type == Type::Outgoing) {
setState(State::Requesting);
} else {
startWaitingTrack();
}
setupOutgoingVideo();
}
void Call::generateModExpFirst(bytes::const_span randomSeed) {
auto first = MTP::CreateModExp(_dhConfig.g, _dhConfig.p, randomSeed);
if (first.modexp.empty()) {
LOG(("Call Error: Could not compute mod-exp first."));
finish(FinishType::Failed);
return;
}
_randomPower = std::move(first.randomPower);
if (_type == Type::Incoming) {
_gb = std::move(first.modexp);
} else {
_ga = std::move(first.modexp);
_gaHash = openssl::Sha256(_ga);
}
}
bool Call::isIncomingWaiting() const {
if (type() != Call::Type::Incoming) {
return false;
}
2020-06-25 17:57:36 +00:00
return (state() == State::Starting)
|| (state() == State::WaitingIncoming);
}
void Call::start(bytes::const_span random) {
// Save config here, because it is possible that it changes between
// different usages inside the same call.
_dhConfig = _delegate->getDhConfig();
Assert(_dhConfig.g != 0);
Assert(!_dhConfig.p.empty());
generateModExpFirst(random);
2020-06-25 17:57:36 +00:00
const auto state = _state.current();
if (state == State::Starting || state == State::Requesting) {
if (_type == Type::Outgoing) {
startOutgoing();
} else {
startIncoming();
}
2020-06-25 17:57:36 +00:00
} else if (state == State::ExchangingKeys
2018-12-25 08:21:00 +00:00
&& _answerAfterDhConfigReceived) {
answer();
}
}
void Call::startOutgoing() {
Expects(_type == Type::Outgoing);
2020-06-25 17:57:36 +00:00
Expects(_state.current() == State::Requesting);
Expects(_gaHash.size() == kSha256Size);
const auto flags = _videoCapture
? MTPphone_RequestCall::Flag::f_video
: MTPphone_RequestCall::Flag(0);
2019-11-27 08:02:56 +00:00
_api.request(MTPphone_RequestCall(
MTP_flags(flags),
2018-04-07 06:28:01 +00:00
_user->inputUser,
MTP_int(rand_value<int32>()),
MTP_bytes(_gaHash),
MTP_phoneCallProtocol(
MTP_flags(MTPDphoneCallProtocol::Flag::f_udp_p2p
| MTPDphoneCallProtocol::Flag::f_udp_reflector),
MTP_int(kMinLayer),
2020-07-09 17:38:26 +00:00
MTP_int(tgcalls::Meta::MaxLayer()),
MTP_vector(CollectVersionsForApi()))
2019-03-22 13:42:03 +00:00
)).done([=](const MTPphone_PhoneCall &result) {
Expects(result.type() == mtpc_phone_phoneCall);
setState(State::Waiting);
auto &call = result.c_phone_phoneCall();
2019-08-06 16:40:08 +00:00
_user->session().data().processUsers(call.vusers());
2019-07-05 13:38:38 +00:00
if (call.vphone_call().type() != mtpc_phoneCallWaiting) {
LOG(("Call Error: Expected phoneCallWaiting in response to phone.requestCall()"));
finish(FinishType::Failed);
return;
}
2019-07-05 13:38:38 +00:00
auto &phoneCall = call.vphone_call();
auto &waitingCall = phoneCall.c_phoneCallWaiting();
2019-07-05 13:38:38 +00:00
_id = waitingCall.vid().v;
_accessHash = waitingCall.vaccess_hash().v;
if (_finishAfterRequestingCall != FinishType::None) {
if (_finishAfterRequestingCall == FinishType::Failed) {
finish(_finishAfterRequestingCall);
} else {
hangup();
}
return;
}
const auto &config = _user->session().serverConfig();
_discardByTimeoutTimer.callOnce(config.callReceiveTimeoutMs);
handleUpdate(phoneCall);
}).fail([this](const RPCError &error) {
handleRequestError(error);
}).send();
}
void Call::startIncoming() {
Expects(_type == Type::Incoming);
2020-06-25 17:57:36 +00:00
Expects(_state.current() == State::Starting);
2019-11-27 08:02:56 +00:00
_api.request(MTPphone_ReceivedCall(
MTP_inputPhoneCall(MTP_long(_id), MTP_long(_accessHash))
)).done([=](const MTPBool &result) {
2020-06-25 17:57:36 +00:00
if (_state.current() == State::Starting) {
setState(State::WaitingIncoming);
}
2019-11-27 08:02:56 +00:00
}).fail([=](const RPCError &error) {
handleRequestError(error);
}).send();
}
void Call::answer() {
2020-05-17 09:12:27 +00:00
_delegate->requestPermissionsOrFail(crl::guard(this, [=] {
2018-10-17 06:09:59 +00:00
actuallyAnswer();
}));
}
2018-10-17 06:09:59 +00:00
void Call::actuallyAnswer() {
Expects(_type == Type::Incoming);
2020-06-25 17:57:36 +00:00
const auto state = _state.current();
if (state != State::Starting && state != State::WaitingIncoming) {
if (state != State::ExchangingKeys
|| !_answerAfterDhConfigReceived) {
return;
}
}
setState(State::ExchangingKeys);
if (_gb.empty()) {
_answerAfterDhConfigReceived = true;
return;
} else {
_answerAfterDhConfigReceived = false;
}
2019-11-27 08:02:56 +00:00
_api.request(MTPphone_AcceptCall(
2018-04-07 06:28:01 +00:00
MTP_inputPhoneCall(MTP_long(_id), MTP_long(_accessHash)),
MTP_bytes(_gb),
MTP_phoneCallProtocol(
MTP_flags(MTPDphoneCallProtocol::Flag::f_udp_p2p
| MTPDphoneCallProtocol::Flag::f_udp_reflector),
MTP_int(kMinLayer),
2020-07-09 17:38:26 +00:00
MTP_int(tgcalls::Meta::MaxLayer()),
MTP_vector(CollectVersionsForApi()))
)).done([=](const MTPphone_PhoneCall &result) {
Expects(result.type() == mtpc_phone_phoneCall);
2020-07-31 14:36:35 +00:00
auto &call = result.c_phone_phoneCall();
2019-08-06 16:40:08 +00:00
_user->session().data().processUsers(call.vusers());
2019-07-05 13:38:38 +00:00
if (call.vphone_call().type() != mtpc_phoneCallWaiting) {
LOG(("Call Error: "
"Not phoneCallWaiting in response to phone.acceptCall."));
finish(FinishType::Failed);
return;
}
2019-07-05 13:38:38 +00:00
handleUpdate(call.vphone_call());
}).fail([=](const RPCError &error) {
handleRequestError(error);
}).send();
}
2020-07-16 16:23:55 +00:00
void Call::setMuted(bool mute) {
_muted = mute;
2020-07-09 17:38:26 +00:00
if (_instance) {
2020-07-16 16:23:55 +00:00
_instance->setMuteMicrophone(mute);
}
}
2020-07-31 14:36:35 +00:00
void Call::setupOutgoingVideo() {
static const auto hasDevices = [] {
return !Webrtc::GetVideoInputList().empty();
};
2020-08-05 12:11:18 +00:00
const auto started = _videoOutgoing->state();
if (!hasDevices()) {
_videoOutgoing->setState(Webrtc::VideoState::Inactive);
}
2020-08-05 12:11:18 +00:00
_videoOutgoing->stateValue(
2020-08-11 09:59:48 +00:00
) | rpl::start_with_next([=](Webrtc::VideoState state) {
if (state != Webrtc::VideoState::Inactive && !hasDevices()) {
_errors.fire({ ErrorType::NoCamera });
_videoOutgoing->setState(Webrtc::VideoState::Inactive);
} else if (_state.current() != State::Established
2020-08-05 12:11:18 +00:00
&& state != started
&& !_videoCapture) {
_errors.fire({ ErrorType::NotStartedCall });
2020-08-05 12:11:18 +00:00
_videoOutgoing->setState(started);
} else if (state != Webrtc::VideoState::Inactive
&& _instance
&& !_instance->supportsVideo()) {
_errors.fire({ ErrorType::NotVideoCall });
_videoOutgoing->setState(Webrtc::VideoState::Inactive);
2020-08-11 09:59:48 +00:00
} else if (state != Webrtc::VideoState::Inactive) {
2020-08-05 12:11:18 +00:00
// Paused not supported right now.
2020-08-11 13:31:27 +00:00
#ifndef DESKTOP_APP_DISABLE_WEBRTC_INTEGRATION
2020-08-11 09:59:48 +00:00
Assert(state == Webrtc::VideoState::Active);
2020-07-31 14:36:35 +00:00
if (!_videoCapture) {
_videoCapture = _delegate->getVideoCapture();
2020-08-05 12:11:18 +00:00
_videoCapture->setOutput(_videoOutgoing->sink());
2020-07-31 14:36:35 +00:00
}
if (_instance) {
2020-08-05 12:11:18 +00:00
_instance->setVideoCapture(_videoCapture);
2020-07-31 14:36:35 +00:00
}
2020-08-05 12:11:18 +00:00
_videoCapture->setState(tgcalls::VideoState::Active);
2020-08-11 13:31:27 +00:00
#endif // DESKTOP_APP_DISABLE_WEBRTC_INTEGRATION
2020-07-31 14:36:35 +00:00
} else if (_videoCapture) {
2020-08-05 12:11:18 +00:00
_videoCapture->setState(tgcalls::VideoState::Inactive);
2020-07-16 16:23:55 +00:00
}
2020-07-31 14:36:35 +00:00
}, _lifetime);
}
2020-08-11 09:59:48 +00:00
not_null<Webrtc::VideoTrack*> Call::videoIncoming() const {
2020-07-31 14:36:35 +00:00
return _videoIncoming.get();
}
2020-08-11 09:59:48 +00:00
not_null<Webrtc::VideoTrack*> Call::videoOutgoing() const {
2020-07-31 14:36:35 +00:00
return _videoOutgoing.get();
}
crl::time Call::getDurationMs() const {
return _startTime ? (crl::now() - _startTime) : 0;
}
void Call::hangup() {
2020-06-25 17:57:36 +00:00
const auto state = _state.current();
if (state == State::Busy) {
2017-05-04 13:32:56 +00:00
_delegate->callFinished(this);
} else {
2020-06-25 17:57:36 +00:00
auto missed = (state == State::Ringing || (state == State::Waiting && _type == Type::Outgoing));
auto declined = isIncomingWaiting();
auto reason = missed ? MTP_phoneCallDiscardReasonMissed() :
declined ? MTP_phoneCallDiscardReasonBusy() : MTP_phoneCallDiscardReasonHangup();
finish(FinishType::Ended, reason);
}
}
void Call::redial() {
2020-06-25 17:57:36 +00:00
if (_state.current() != State::Busy) {
return;
}
2020-07-09 17:38:26 +00:00
Assert(_instance == nullptr);
_type = Type::Outgoing;
setState(State::Requesting);
_answerAfterDhConfigReceived = false;
2017-05-03 13:43:01 +00:00
startWaitingTrack();
_delegate->callRedial(this);
}
QString Call::getDebugLog() const {
return _instance
? QString::fromStdString(_instance->getDebugInfo())
: QString();
}
2017-05-03 13:43:01 +00:00
void Call::startWaitingTrack() {
_waitingTrack = Media::Audio::Current().createTrack();
auto trackFileName = Core::App().settings().getSoundPath(
(_type == Type::Outgoing)
? qsl("call_outgoing")
: qsl("call_incoming"));
_waitingTrack->samplePeakEach(kSoundSampleMs);
2017-05-03 13:43:01 +00:00
_waitingTrack->fillFromFile(trackFileName);
_waitingTrack->playInLoop();
}
void Call::sendSignalingData(const QByteArray &data) {
_api.request(MTPphone_SendSignalingData(
MTP_inputPhoneCall(
MTP_long(_id),
MTP_long(_accessHash)),
MTP_bytes(data)
)).done([=](const MTPBool &result) {
if (!mtpIsTrue(result)) {
finish(FinishType::Failed);
}
}).fail([=](const RPCError &error) {
handleRequestError(error);
}).send();
}
float64 Call::getWaitingSoundPeakValue() const {
if (_waitingTrack) {
auto when = crl::now() + kSoundSampleMs / 4;
return _waitingTrack->getPeakValue(when);
}
return 0.;
}
bool Call::isKeyShaForFingerprintReady() const {
return (_keyFingerprint != 0);
}
bytes::vector Call::getKeyShaForFingerprint() const {
Expects(isKeyShaForFingerprintReady());
Expects(!_ga.empty());
auto encryptedChatAuthKey = bytes::vector(_authKey.size() + _ga.size(), gsl::byte {});
bytes::copy(gsl::make_span(encryptedChatAuthKey).subspan(0, _authKey.size()), _authKey);
bytes::copy(gsl::make_span(encryptedChatAuthKey).subspan(_authKey.size(), _ga.size()), _ga);
return openssl::Sha256(encryptedChatAuthKey);
}
bool Call::handleUpdate(const MTPPhoneCall &call) {
switch (call.type()) {
case mtpc_phoneCallRequested: {
auto &data = call.c_phoneCallRequested();
if (_type != Type::Incoming
|| _id != 0
2019-07-05 13:38:38 +00:00
|| peerToUser(_user->id) != data.vadmin_id().v) {
Unexpected("phoneCallRequested call inside an existing call handleUpdate()");
}
2019-08-06 16:40:08 +00:00
if (_user->session().userId() != data.vparticipant_id().v) {
LOG(("Call Error: Wrong call participant_id %1, expected %2."
2019-07-05 13:38:38 +00:00
).arg(data.vparticipant_id().v
2019-08-06 16:40:08 +00:00
).arg(_user->session().userId()));
finish(FinishType::Failed);
return true;
}
2020-07-31 14:36:35 +00:00
2019-07-05 13:38:38 +00:00
_id = data.vid().v;
_accessHash = data.vaccess_hash().v;
auto gaHashBytes = bytes::make_span(data.vg_a_hash().v);
if (gaHashBytes.size() != kSha256Size) {
LOG(("Call Error: Wrong g_a_hash size %1, expected %2."
).arg(gaHashBytes.size()
).arg(kSha256Size));
finish(FinishType::Failed);
return true;
}
_gaHash = bytes::make_vector(gaHashBytes);
} return true;
case mtpc_phoneCallEmpty: {
auto &data = call.c_phoneCallEmpty();
2019-07-05 13:38:38 +00:00
if (data.vid().v != _id) {
return false;
}
LOG(("Call Error: phoneCallEmpty received."));
finish(FinishType::Failed);
} return true;
case mtpc_phoneCallWaiting: {
auto &data = call.c_phoneCallWaiting();
2019-07-05 13:38:38 +00:00
if (data.vid().v != _id) {
return false;
}
if (_type == Type::Outgoing
2020-06-25 17:57:36 +00:00
&& _state.current() == State::Waiting
2019-07-05 13:38:38 +00:00
&& data.vreceive_date().value_or_empty() != 0) {
const auto &config = _user->session().serverConfig();
_discardByTimeoutTimer.callOnce(config.callRingTimeoutMs);
setState(State::Ringing);
startWaitingTrack();
}
} return true;
case mtpc_phoneCall: {
auto &data = call.c_phoneCall();
2019-07-05 13:38:38 +00:00
if (data.vid().v != _id) {
return false;
}
2018-12-25 08:21:00 +00:00
if (_type == Type::Incoming
2020-06-25 17:57:36 +00:00
&& _state.current() == State::ExchangingKeys
2020-07-09 17:38:26 +00:00
&& !_instance) {
startConfirmedCall(data);
}
} return true;
case mtpc_phoneCallDiscarded: {
auto &data = call.c_phoneCallDiscarded();
2019-07-05 13:38:38 +00:00
if (data.vid().v != _id) {
return false;
}
if (data.is_need_debug()) {
2020-07-09 17:38:26 +00:00
auto debugLog = _instance
? _instance->getDebugInfo()
: std::string();
if (!debugLog.empty()) {
2020-06-11 13:07:14 +00:00
user()->session().api().request(MTPphone_SaveCallDebug(
MTP_inputPhoneCall(
MTP_long(_id),
MTP_long(_accessHash)),
MTP_dataJSON(MTP_string(debugLog))
)).send();
}
}
if (data.is_need_rating() && _id && _accessHash) {
2019-08-06 16:40:08 +00:00
Ui::show(Box<RateCallBox>(&_user->session(), _id, _accessHash));
}
2019-07-05 13:38:38 +00:00
const auto reason = data.vreason();
if (reason && reason->type() == mtpc_phoneCallDiscardReasonDisconnect) {
LOG(("Call Info: Discarded with DISCONNECT reason."));
}
2019-07-05 13:38:38 +00:00
if (reason && reason->type() == mtpc_phoneCallDiscardReasonBusy) {
setState(State::Busy);
2020-06-25 17:57:36 +00:00
} else if (_type == Type::Outgoing
|| _state.current() == State::HangingUp) {
setState(State::Ended);
} else {
setState(State::EndedByOtherDevice);
}
} return true;
case mtpc_phoneCallAccepted: {
auto &data = call.c_phoneCallAccepted();
2019-07-05 13:38:38 +00:00
if (data.vid().v != _id) {
return false;
}
if (_type != Type::Outgoing) {
LOG(("Call Error: "
"Unexpected phoneCallAccepted for an incoming call."));
finish(FinishType::Failed);
} else if (checkCallFields(data)) {
confirmAcceptedCall(data);
}
} return true;
}
Unexpected("phoneCall type inside an existing call handleUpdate()");
}
2020-08-05 12:11:18 +00:00
void Call::updateRemoteMediaState(
tgcalls::AudioState audio,
tgcalls::VideoState video) {
_remoteAudioState = [&] {
using From = tgcalls::AudioState;
using To = RemoteAudioState;
switch (audio) {
case From::Active: return To::Active;
case From::Muted: return To::Muted;
}
Unexpected("Audio state in remoteMediaStateUpdated.");
}();
_videoIncoming->setState([&] {
using From = tgcalls::VideoState;
2020-08-11 09:59:48 +00:00
using To = Webrtc::VideoState;
2020-08-05 12:11:18 +00:00
switch (video) {
case From::Inactive: return To::Inactive;
case From::Paused: return To::Paused;
case From::Active: return To::Active;
}
Unexpected("Video state in remoteMediaStateUpdated.");
}());
}
bool Call::handleSignalingData(
const MTPDupdatePhoneCallSignalingData &data) {
2020-07-09 17:38:26 +00:00
if (data.vphone_call_id().v != _id || !_instance) {
return false;
}
2020-07-09 17:38:26 +00:00
auto prepared = ranges::view::all(
data.vdata().v
) | ranges::view::transform([](char byte) {
return static_cast<uint8_t>(byte);
}) | ranges::to_vector;
_instance->receiveSignalingData(std::move(prepared));
return true;
}
void Call::confirmAcceptedCall(const MTPDphoneCallAccepted &call) {
Expects(_type == Type::Outgoing);
2020-06-25 17:57:36 +00:00
if (_state.current() == State::ExchangingKeys
2020-07-09 17:38:26 +00:00
|| _instance) {
LOG(("Call Warning: Unexpected confirmAcceptedCall."));
return;
}
2019-07-05 13:38:38 +00:00
const auto firstBytes = bytes::make_span(call.vg_b().v);
const auto computedAuthKey = MTP::CreateAuthKey(
firstBytes,
_randomPower,
_dhConfig.p);
if (computedAuthKey.empty()) {
LOG(("Call Error: Could not compute mod-exp final."));
finish(FinishType::Failed);
return;
}
MTP::AuthKey::FillData(_authKey, computedAuthKey);
_keyFingerprint = ComputeFingerprint(_authKey);
setState(State::ExchangingKeys);
2019-11-27 08:02:56 +00:00
_api.request(MTPphone_ConfirmCall(
2018-04-07 06:28:01 +00:00
MTP_inputPhoneCall(MTP_long(_id), MTP_long(_accessHash)),
MTP_bytes(_ga),
MTP_long(_keyFingerprint),
MTP_phoneCallProtocol(
MTP_flags(MTPDphoneCallProtocol::Flag::f_udp_p2p
| MTPDphoneCallProtocol::Flag::f_udp_reflector),
MTP_int(kMinLayer),
2020-07-09 17:38:26 +00:00
MTP_int(tgcalls::Meta::MaxLayer()),
MTP_vector(CollectVersionsForApi()))
)).done([=](const MTPphone_PhoneCall &result) {
Expects(result.type() == mtpc_phone_phoneCall);
2019-01-18 12:27:37 +00:00
auto &call = result.c_phone_phoneCall();
2019-08-06 16:40:08 +00:00
_user->session().data().processUsers(call.vusers());
2019-07-05 13:38:38 +00:00
if (call.vphone_call().type() != mtpc_phoneCall) {
LOG(("Call Error: Expected phoneCall in response to phone.confirmCall()"));
finish(FinishType::Failed);
return;
}
2019-07-05 13:38:38 +00:00
createAndStartController(call.vphone_call().c_phoneCall());
}).fail([=](const RPCError &error) {
handleRequestError(error);
}).send();
}
void Call::startConfirmedCall(const MTPDphoneCall &call) {
Expects(_type == Type::Incoming);
2019-07-05 13:38:38 +00:00
auto firstBytes = bytes::make_span(call.vg_a_or_b().v);
if (_gaHash != openssl::Sha256(firstBytes)) {
LOG(("Call Error: Wrong g_a hash received."));
finish(FinishType::Failed);
return;
}
_ga = bytes::vector(firstBytes.begin(), firstBytes.end());
auto computedAuthKey = MTP::CreateAuthKey(firstBytes, _randomPower, _dhConfig.p);
if (computedAuthKey.empty()) {
LOG(("Call Error: Could not compute mod-exp final."));
finish(FinishType::Failed);
return;
}
MTP::AuthKey::FillData(_authKey, computedAuthKey);
_keyFingerprint = ComputeFingerprint(_authKey);
createAndStartController(call);
}
void Call::createAndStartController(const MTPDphoneCall &call) {
_discardByTimeoutTimer.cancel();
2020-07-21 17:20:36 +00:00
if (!checkCallFields(call) || _authKey.size() != 256) {
return;
}
const auto &protocol = call.vprotocol().c_phoneCallProtocol();
const auto &serverConfig = _user->session().serverConfig();
2020-07-21 17:20:36 +00:00
auto encryptionKeyValue = std::make_shared<std::array<uint8_t, 256>>();
memcpy(encryptionKeyValue->data(), _authKey.data(), 256);
2020-07-14 17:45:34 +00:00
const auto &settings = Core::App().settings();
2020-07-09 17:38:26 +00:00
const auto weak = base::make_weak(this);
tgcalls::Descriptor descriptor = {
2020-07-09 17:38:26 +00:00
.config = tgcalls::Config{
.initializationTimeout = serverConfig.callConnectTimeoutMs / 1000.,
.receiveTimeout = serverConfig.callPacketTimeoutMs / 1000.,
.dataSaving = tgcalls::DataSaving::Never,
.enableP2P = call.is_p2p_allowed(),
.enableAEC = !Platform::IsMac10_7OrGreater(),
.enableNS = true,
.enableAGC = true,
.enableVolumeControl = true,
.maxApiLayer = protocol.vmax_layer().v,
},
2020-07-14 17:45:34 +00:00
.encryptionKey = tgcalls::EncryptionKey(
std::move(encryptionKeyValue),
(_type == Type::Outgoing)),
.mediaDevicesConfig = tgcalls::MediaDevicesConfig{
.audioInputId = settings.callInputDeviceId().toStdString(),
.audioOutputId = settings.callOutputDeviceId().toStdString(),
.inputVolume = 1.f,//settings.callInputVolume() / 100.f,
.outputVolume = 1.f,//settings.callOutputVolume() / 100.f,
},
2020-08-05 12:11:18 +00:00
.videoCapture = _videoCapture,
.stateUpdated = [=](tgcalls::State state) {
2020-07-09 17:38:26 +00:00
crl::on_main(weak, [=] {
2020-08-05 12:11:18 +00:00
handleControllerStateChange(state);
2020-07-09 17:38:26 +00:00
});
},
.signalBarsUpdated = [=](int count) {
crl::on_main(weak, [=] {
handleControllerBarCountChange(count);
});
},
2020-08-05 12:11:18 +00:00
.remoteMediaStateUpdated = [=](tgcalls::AudioState audio, tgcalls::VideoState video) {
2020-07-16 16:23:55 +00:00
crl::on_main(weak, [=] {
2020-08-05 12:11:18 +00:00
updateRemoteMediaState(audio, video);
2020-07-16 16:23:55 +00:00
});
2020-07-09 17:38:26 +00:00
},
.signalingDataEmitted = [=](const std::vector<uint8_t> &data) {
const auto bytes = QByteArray(
reinterpret_cast<const char*>(data.data()),
data.size());
crl::on_main(weak, [=] {
sendSignalingData(bytes);
});
},
};
if (Logs::DebugEnabled()) {
auto callLogFolder = cWorkingDir() + qsl("DebugLogs");
auto callLogPath = callLogFolder + qsl("/last_call_log.txt");
2018-08-30 11:56:35 +00:00
auto callLogNative = QDir::toNativeSeparators(callLogPath);
#ifdef Q_OS_WIN
2020-07-09 17:38:26 +00:00
descriptor.config.logPath = callLogNative.toStdWString();
2018-08-30 11:56:35 +00:00
#else // Q_OS_WIN
const auto callLogUtf = QFile::encodeName(callLogNative);
2020-07-09 17:38:26 +00:00
descriptor.config.logPath.resize(callLogUtf.size());
2020-07-13 14:04:02 +00:00
ranges::copy(callLogUtf, descriptor.config.logPath.begin());
2018-08-30 11:56:35 +00:00
#endif // Q_OS_WIN
QFile(callLogPath).remove();
QDir().mkpath(callLogFolder);
}
2019-07-05 13:38:38 +00:00
for (const auto &connection : call.vconnections().v) {
2020-07-09 17:38:26 +00:00
AppendEndpoint(descriptor.endpoints, connection);
}
2020-08-04 18:31:30 +00:00
for (const auto &connection : call.vconnections().v) {
AppendServer(descriptor.rtcServers, connection);
}
2020-07-09 17:38:26 +00:00
if (Global::UseProxyForCalls()
2019-11-13 14:12:04 +00:00
&& (Global::ProxySettings() == MTP::ProxyData::Settings::Enabled)) {
const auto &selected = Global::SelectedProxy();
2020-07-09 17:38:26 +00:00
if (selected.supportsCalls() && !selected.host.isEmpty()) {
Assert(selected.type == MTP::ProxyData::Type::Socks5);
2020-07-09 17:38:26 +00:00
descriptor.proxy = std::make_unique<tgcalls::Proxy>();
descriptor.proxy->host = selected.host.toStdString();
descriptor.proxy->port = selected.port;
descriptor.proxy->login = selected.user.toStdString();
descriptor.proxy->password = selected.password.toStdString();
2018-05-06 21:29:53 +00:00
}
}
const auto version = call.vprotocol().match([&](
const MTPDphoneCallProtocol &data) {
return data.vlibrary_versions().v;
}).value(0, MTP_bytes(kDefaultVersion)).v;
2020-07-09 17:38:26 +00:00
LOG(("Call Info: Creating instance with version '%1', allowP2P: %2"
).arg(QString::fromUtf8(version)
).arg(Logs::b(descriptor.config.enableP2P)));
_instance = tgcalls::Meta::Create(
version.toStdString(),
2020-07-09 17:38:26 +00:00
std::move(descriptor));
if (!_instance) {
LOG(("Call Error: Wrong library version: %1."
).arg(QString::fromUtf8(version)));
finish(FinishType::Failed);
return;
}
const auto raw = _instance.get();
2020-07-16 16:23:55 +00:00
if (_muted.current()) {
raw->setMuteMicrophone(_muted.current());
}
2020-07-17 18:59:38 +00:00
2020-07-31 14:36:35 +00:00
raw->setIncomingVideoOutput(_videoIncoming->sink());
raw->setAudioOutputDuckingEnabled(settings.callAudioDuckingEnabled());
}
2020-08-05 12:11:18 +00:00
void Call::handleControllerStateChange(tgcalls::State state) {
switch (state) {
2020-07-09 17:38:26 +00:00
case tgcalls::State::WaitInit: {
DEBUG_LOG(("Call Info: State changed to WaitingInit."));
2020-07-09 17:38:26 +00:00
setState(State::WaitingInit);
} break;
2020-07-09 17:38:26 +00:00
case tgcalls::State::WaitInitAck: {
DEBUG_LOG(("Call Info: State changed to WaitingInitAck."));
2020-07-09 17:38:26 +00:00
setState(State::WaitingInitAck);
} break;
2020-07-09 17:38:26 +00:00
case tgcalls::State::Established: {
DEBUG_LOG(("Call Info: State changed to Established."));
2020-07-09 17:38:26 +00:00
setState(State::Established);
} break;
2020-07-09 17:38:26 +00:00
case tgcalls::State::Failed: {
auto error = _instance
? QString::fromStdString(_instance->getLastError())
: QString();
LOG(("Call Info: State changed to Failed, error: %1.").arg(error));
2020-07-09 17:38:26 +00:00
handleControllerError(error);
} break;
default: LOG(("Call Error: Unexpected state in handleStateChange: %1"
).arg(int(state)));
}
}
void Call::handleControllerBarCountChange(int count) {
2020-07-09 17:38:26 +00:00
setSignalBarCount(count);
2018-05-27 08:24:47 +00:00
}
void Call::setSignalBarCount(int count) {
2020-07-16 16:23:55 +00:00
_signalBarCount = count;
2018-05-27 08:24:47 +00:00
}
template <typename T>
bool Call::checkCallCommonFields(const T &call) {
auto checkFailed = [this] {
finish(FinishType::Failed);
return false;
};
2019-07-05 13:38:38 +00:00
if (call.vaccess_hash().v != _accessHash) {
LOG(("Call Error: Wrong call access_hash."));
return checkFailed();
}
2019-08-06 16:40:08 +00:00
auto adminId = (_type == Type::Outgoing) ? _user->session().userId() : peerToUser(_user->id);
auto participantId = (_type == Type::Outgoing) ? peerToUser(_user->id) : _user->session().userId();
2019-07-05 13:38:38 +00:00
if (call.vadmin_id().v != adminId) {
LOG(("Call Error: Wrong call admin_id %1, expected %2.").arg(call.vadmin_id().v).arg(adminId));
return checkFailed();
}
2019-07-05 13:38:38 +00:00
if (call.vparticipant_id().v != participantId) {
LOG(("Call Error: Wrong call participant_id %1, expected %2.").arg(call.vparticipant_id().v).arg(participantId));
return checkFailed();
}
return true;
}
bool Call::checkCallFields(const MTPDphoneCall &call) {
if (!checkCallCommonFields(call)) {
return false;
}
2019-07-05 13:38:38 +00:00
if (call.vkey_fingerprint().v != _keyFingerprint) {
LOG(("Call Error: Wrong call fingerprint."));
finish(FinishType::Failed);
return false;
}
return true;
}
bool Call::checkCallFields(const MTPDphoneCallAccepted &call) {
return checkCallCommonFields(call);
}
void Call::setState(State state) {
2020-06-25 17:57:36 +00:00
if (_state.current() == State::Failed) {
return;
}
2020-06-25 17:57:36 +00:00
if (_state.current() == State::FailedHangingUp && state != State::Failed) {
return;
}
2020-06-25 17:57:36 +00:00
if (_state.current() != state) {
_state = state;
2017-05-03 13:43:01 +00:00
if (true
2020-06-25 17:57:36 +00:00
&& state != State::Starting
&& state != State::Requesting
&& state != State::Waiting
&& state != State::WaitingIncoming
&& state != State::Ringing) {
2017-05-03 13:43:01 +00:00
_waitingTrack.reset();
}
2017-05-05 11:49:23 +00:00
if (false
2020-06-25 17:57:36 +00:00
|| state == State::Ended
|| state == State::EndedByOtherDevice
|| state == State::Failed
|| state == State::Busy) {
2017-05-05 11:49:23 +00:00
// Destroy controller before destroying Call Panel,
// so that the panel hide animation is smooth.
destroyController();
}
2020-06-25 17:57:36 +00:00
switch (state) {
case State::Established:
_startTime = crl::now();
break;
2017-05-03 13:43:01 +00:00
case State::ExchangingKeys:
_delegate->playSound(Delegate::Sound::Connecting);
break;
case State::Ended:
2017-05-04 13:32:56 +00:00
_delegate->playSound(Delegate::Sound::Ended);
[[fallthrough]];
case State::EndedByOtherDevice:
_delegate->callFinished(this);
break;
case State::Failed:
2017-05-04 13:32:56 +00:00
_delegate->playSound(Delegate::Sound::Ended);
_delegate->callFailed(this);
break;
case State::Busy:
2017-05-03 13:43:01 +00:00
_delegate->playSound(Delegate::Sound::Busy);
break;
}
}
}
void Call::setCurrentAudioDevice(bool input, const QString &deviceId) {
2020-07-09 17:38:26 +00:00
if (_instance) {
const auto id = deviceId.toStdString();
2019-01-05 11:08:02 +00:00
if (input) {
_instance->setAudioInputDevice(id);
2019-01-05 11:08:02 +00:00
} else {
_instance->setAudioOutputDevice(id);
2019-01-05 11:08:02 +00:00
}
}
}
void Call::setCurrentVideoDevice(const QString &deviceId) {
if (_videoCapture) {
_videoCapture->switchToDevice(deviceId.toStdString());
}
}
void Call::setAudioVolume(bool input, float level) {
2020-07-09 17:38:26 +00:00
if (_instance) {
if (input) {
2020-07-09 17:38:26 +00:00
_instance->setInputVolume(level);
2019-01-05 11:08:02 +00:00
} else {
2020-07-09 17:38:26 +00:00
_instance->setOutputVolume(level);
2019-01-05 11:08:02 +00:00
}
}
}
void Call::setAudioDuckingEnabled(bool enabled) {
2020-07-09 17:38:26 +00:00
if (_instance) {
_instance->setAudioOutputDuckingEnabled(enabled);
2019-01-05 11:08:02 +00:00
}
}
void Call::finish(FinishType type, const MTPPhoneCallDiscardReason &reason) {
Expects(type != FinishType::None);
2018-05-27 08:24:47 +00:00
setSignalBarCount(kSignalBarFinished);
auto finalState = (type == FinishType::Ended) ? State::Ended : State::Failed;
auto hangupState = (type == FinishType::Ended) ? State::HangingUp : State::FailedHangingUp;
2020-06-25 17:57:36 +00:00
const auto state = _state.current();
if (state == State::Requesting) {
_finishByTimeoutTimer.call(kHangupTimeoutMs, [this, finalState] { setState(finalState); });
_finishAfterRequestingCall = type;
return;
}
2020-06-25 17:57:36 +00:00
if (state == State::HangingUp
|| state == State::FailedHangingUp
|| state == State::EndedByOtherDevice
|| state == State::Ended
|| state == State::Failed) {
return;
}
if (!_id) {
setState(finalState);
return;
}
setState(hangupState);
auto duration = getDurationMs() / 1000;
2020-07-09 17:38:26 +00:00
auto connectionId = _instance ? _instance->getPreferredRelayId() : 0;
_finishByTimeoutTimer.call(kHangupTimeoutMs, [this, finalState] { setState(finalState); });
2020-08-11 09:59:48 +00:00
const auto flags = ((_videoIncoming->state() != Webrtc::VideoState::Inactive)
|| (_videoOutgoing->state() != Webrtc::VideoState::Inactive))
? MTPphone_DiscardCall::Flag::f_video
: MTPphone_DiscardCall::Flag(0);
2019-11-27 08:02:56 +00:00
_api.request(MTPphone_DiscardCall(
MTP_flags(flags),
MTP_inputPhoneCall(
MTP_long(_id),
MTP_long(_accessHash)),
MTP_int(duration),
reason,
MTP_long(connectionId)
)).done([=](const MTPUpdates &result) {
2019-08-06 16:40:08 +00:00
// Here 'this' could be destroyed by updates, so we set Ended after
// updates being handled, but in a guarded way.
crl::on_main(this, [=] { setState(finalState); });
2019-08-06 16:40:08 +00:00
_user->session().api().applyUpdates(result);
}).fail([this, finalState](const RPCError &error) {
setState(finalState);
}).send();
}
void Call::setStateQueued(State state) {
crl::on_main(this, [=] {
2018-05-27 08:24:47 +00:00
setState(state);
});
}
void Call::setFailedQueued(const QString &error) {
crl::on_main(this, [=] {
2018-05-27 08:24:47 +00:00
handleControllerError(error);
});
}
void Call::handleRequestError(const RPCError &error) {
if (error.type() == qstr("USER_PRIVACY_RESTRICTED")) {
Ui::show(Box<InformBox>(tr::lng_call_error_not_available(tr::now, lt_user, _user->name)));
} else if (error.type() == qstr("PARTICIPANT_VERSION_OUTDATED")) {
Ui::show(Box<InformBox>(tr::lng_call_error_outdated(tr::now, lt_user, _user->name)));
} else if (error.type() == qstr("CALL_PROTOCOL_LAYER_INVALID")) {
Ui::show(Box<InformBox>(Lang::Hard::CallErrorIncompatible().replace("{user}", _user->name)));
}
finish(FinishType::Failed);
}
void Call::handleControllerError(const QString &error) {
if (error == u"ERROR_INCOMPATIBLE"_q) {
2018-05-24 16:42:57 +00:00
Ui::show(Box<InformBox>(
Lang::Hard::CallErrorIncompatible().replace(
"{user}",
_user->name)));
} else if (error == u"ERROR_AUDIO_IO"_q) {
2019-06-19 15:09:03 +00:00
Ui::show(Box<InformBox>(tr::lng_call_error_audio_io(tr::now)));
}
finish(FinishType::Failed);
}
void Call::destroyController() {
2020-07-09 17:38:26 +00:00
if (_instance) {
2020-08-25 18:03:41 +00:00
_instance->stop([](tgcalls::FinalState) {
});
2020-07-09 17:38:26 +00:00
DEBUG_LOG(("Call Info: Destroying call controller.."));
2020-07-09 17:38:26 +00:00
_instance.reset();
DEBUG_LOG(("Call Info: Call controller destroyed."));
}
2018-05-27 08:24:47 +00:00
setSignalBarCount(kSignalBarFinished);
}
Call::~Call() {
destroyController();
}
void UpdateConfig(const std::string &data) {
2020-07-09 17:38:26 +00:00
tgcalls::SetLegacyGlobalServerConfig(data);
}
} // namespace Calls