Skip to content

Commit

Permalink
Update to 7.0.0 (2064)
Browse files Browse the repository at this point in the history
  • Loading branch information
DrKLO committed Aug 15, 2020
1 parent 6e495f5 commit 4c5f32b
Show file tree
Hide file tree
Showing 67 changed files with 2,381 additions and 1,217 deletions.
2 changes: 1 addition & 1 deletion TMessagesProj/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,7 @@ android {
}
}

defaultConfig.versionCode = 2061
defaultConfig.versionCode = 2064

applicationVariants.all { variant ->
variant.outputs.all { output ->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,10 @@ struct InstanceHolder {
std::shared_ptr<tgcalls::VideoCaptureInterface> _videoCapture;
};

jclass TrafficStatsClass;
jclass FinalStateClass;
jmethodID FinalStateInitMethod;

jlong getInstanceHolderId(JNIEnv *env, jobject obj) {
return env->GetLongField(obj, env->GetFieldID(env->GetObjectClass(obj), "nativePtr", "J"));
}
Expand Down Expand Up @@ -200,19 +204,16 @@ jint asJavaState(const State &state) {
}

jobject asJavaTrafficStats(JNIEnv *env, const TrafficStats &trafficStats) {
jclass clazz = env->FindClass("org/telegram/messenger/voip/Instance$TrafficStats");
jmethodID initMethodId = env->GetMethodID(clazz, "<init>", "(JJJJ)V");
return env->NewObject(clazz, initMethodId, (jlong) trafficStats.bytesSentWifi, (jlong) trafficStats.bytesReceivedWifi, (jlong) trafficStats.bytesSentMobile, (jlong) trafficStats.bytesReceivedMobile);
jmethodID initMethodId = env->GetMethodID(TrafficStatsClass, "<init>", "(JJJJ)V");
return env->NewObject(TrafficStatsClass, initMethodId, (jlong) trafficStats.bytesSentWifi, (jlong) trafficStats.bytesReceivedWifi, (jlong) trafficStats.bytesSentMobile, (jlong) trafficStats.bytesReceivedMobile);
}

jobject asJavaFinalState(JNIEnv *env, const FinalState &finalState) {
jbyteArray persistentState = copyVectorToJavaByteArray(env, finalState.persistentState.value);
jstring debugLog = env->NewStringUTF(finalState.debugLog.c_str());
jobject trafficStats = asJavaTrafficStats(env, finalState.trafficStats);
auto isRatingSuggested = static_cast<jboolean>(finalState.isRatingSuggested);
jclass finalStateClass = env->FindClass("org/telegram/messenger/voip/Instance$FinalState");
jmethodID finalStateInitMethodId = env->GetMethodID(finalStateClass, "<init>", "([BLjava/lang/String;Lorg/telegram/messenger/voip/Instance$TrafficStats;Z)V");
return env->NewObject(finalStateClass, finalStateInitMethodId, persistentState, debugLog, trafficStats, isRatingSuggested);
return env->NewObject(FinalStateClass, FinalStateInitMethod, persistentState, debugLog, trafficStats, isRatingSuggested);
}

extern "C" {
Expand All @@ -229,6 +230,10 @@ void initWebRTC(JNIEnv *env) {
webrtc::JVM::Initialize(vm);
rtc::InitializeSSL();
webrtcLoaded = true;

TrafficStatsClass = static_cast<jclass>(env->NewGlobalRef(env->FindClass("org/telegram/messenger/voip/Instance$TrafficStats")));
FinalStateClass = static_cast<jclass>(env->NewGlobalRef(env->FindClass("org/telegram/messenger/voip/Instance$FinalState")));
FinalStateInitMethod = env->GetMethodID(FinalStateClass, "<init>", "([BLjava/lang/String;Lorg/telegram/messenger/voip/Instance$TrafficStats;Z)V");
}

JNIEXPORT jlong JNICALL Java_org_telegram_messenger_voip_NativeInstance_makeNativeInstance(JNIEnv *env, jclass clazz, jstring version, jobject instanceObj, jobject config, jstring persistentStateFilePath, jobjectArray endpoints, jobject proxyClass, jint networkType, jobject encryptionKey, jobject remoteSink, jlong videoCapturer, jfloat aspectRatio) {
Expand Down Expand Up @@ -259,7 +264,7 @@ JNIEXPORT jlong JNICALL Java_org_telegram_messenger_voip_NativeInstance_makeNati
.enableVolumeControl = true,
.logPath = tgvoip::jni::JavaStringToStdString(env, configObject.getStringField("logPath")),
.maxApiLayer = configObject.getIntField("maxApiLayer"),
/*.preferredAspectRatio = aspectRatio*/
.preferredAspectRatio = aspectRatio
},
.encryptionKey = EncryptionKey(
std::move(encryptionKeyValue),
Expand Down Expand Up @@ -332,6 +337,7 @@ JNIEXPORT jlong JNICALL Java_org_telegram_messenger_voip_NativeInstance_makeNati
holder->javaInstance = globalRef;
holder->_videoCapture = videoCapture;
holder->nativeInstance->setIncomingVideoOutput(webrtc::JavaToNativeVideoSink(env, remoteSink));
holder->nativeInstance->setNetworkType(parseNetworkType(networkType));
return reinterpret_cast<jlong>(holder);
}

Expand Down Expand Up @@ -384,19 +390,16 @@ JNIEXPORT jbyteArray JNICALL Java_org_telegram_messenger_voip_NativeInstance_get
return copyVectorToJavaByteArray(env, getInstance(env, obj)->getPersistentState().value);
}

JNIEXPORT jobject JNICALL Java_org_telegram_messenger_voip_NativeInstance_stop(JNIEnv *env, jobject obj) {
JNIEXPORT void JNICALL Java_org_telegram_messenger_voip_NativeInstance_stopNative(JNIEnv *env, jobject obj) {
InstanceHolder *instance = getInstanceHolder(env, obj);
FinalState finalState = instance->nativeInstance->stop();

// saving persistent state
const std::string &path = tgvoip::jni::JavaStringToStdString(env, JavaObject(env, obj).getStringField("persistentStateFilePath"));
savePersistentState(path.c_str(), finalState.persistentState);

// clean
env->DeleteGlobalRef(instance->javaInstance);
delete instance;

return asJavaFinalState(env, finalState);
instance->nativeInstance->stop([instance](FinalState finalState) {
JNIEnv *env = webrtc::AttachCurrentThreadIfNeeded();
const std::string &path = tgvoip::jni::JavaStringToStdString(env, JavaObject(env, instance->javaInstance).getStringField("persistentStateFilePath"));
savePersistentState(path.c_str(), finalState.persistentState);
env->CallVoidMethod(instance->javaInstance, env->GetMethodID(env->GetObjectClass(instance->javaInstance), "onStop", "(Lorg/telegram/messenger/voip/Instance$FinalState;)V"), asJavaFinalState(env, finalState));
env->DeleteGlobalRef(instance->javaInstance);
delete instance;
});
}

JNIEXPORT long JNICALL Java_org_telegram_messenger_voip_NativeInstance_createVideoCapturer(JNIEnv *env, jclass clazz, jobject localSink) {
Expand Down
35 changes: 23 additions & 12 deletions TMessagesProj/jni/tgcalls/CodecSelectHelper.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@ bool CompareFormats(const VideoFormat &a, const VideoFormat &b) {
}
}

int FormatPriority(const VideoFormat &format) {
int FormatPriority(const VideoFormat &format, const std::vector<std::string> &preferredCodecs) {
static const auto kCodecs = {
std::string(cricket::kAv1CodecName),
std::string(cricket::kVp9CodecName),
std::string(cricket::kVp9CodecName),
std::string(cricket::kH265CodecName),
std::string(cricket::kH264CodecName),
std::string(cricket::kVp8CodecName),
Expand All @@ -43,8 +43,16 @@ int FormatPriority(const VideoFormat &format) {
}
return result;
}();

auto result = 0;

for (int i = 0; i < preferredCodecs.size(); i++) {
for (const auto &name : kSupported) {
if (absl::EqualsIgnoreCase(format.name, preferredCodecs[i]) && absl::EqualsIgnoreCase(format.name, name)) {
return i;
}
}
}

auto result = (int)preferredCodecs.size();
for (const auto &name : kSupported) {
if (absl::EqualsIgnoreCase(format.name, name)) {
return result;
Expand All @@ -54,17 +62,19 @@ int FormatPriority(const VideoFormat &format) {
return -1;
}

bool ComparePriorities(const VideoFormat &a, const VideoFormat &b) {
return FormatPriority(a) < FormatPriority(b);
bool ComparePriorities(const VideoFormat &a, const VideoFormat &b, const std::vector<std::string> &preferredCodecs) {
return FormatPriority(a, preferredCodecs) < FormatPriority(b, preferredCodecs);
}

std::vector<VideoFormat> FilterAndSortEncoders(std::vector<VideoFormat> list) {
std::vector<VideoFormat> FilterAndSortEncoders(std::vector<VideoFormat> list, const std::vector<std::string> &preferredCodecs) {
const auto listBegin = begin(list);
const auto listEnd = end(list);
std::sort(listBegin, listEnd, ComparePriorities);
std::sort(listBegin, listEnd, [&preferredCodecs](const VideoFormat &lhs, const VideoFormat &rhs) {
return ComparePriorities(lhs, rhs, preferredCodecs);
});
auto eraseFrom = listBegin;
auto eraseTill = eraseFrom;
while (eraseTill != listEnd && FormatPriority(*eraseTill) == -1) {
while (eraseTill != listEnd && FormatPriority(*eraseTill, preferredCodecs) == -1) {
++eraseTill;
}
if (eraseTill != eraseFrom) {
Expand Down Expand Up @@ -131,11 +141,12 @@ void AddDefaultFeedbackParams(cricket::VideoCodec *codec) {

VideoFormatsMessage ComposeSupportedFormats(
std::vector<VideoFormat> encoders,
std::vector<VideoFormat> decoders) {
encoders = FilterAndSortEncoders(std::move(encoders));
std::vector<VideoFormat> decoders,
const std::vector<std::string> &preferredCodecs) {
encoders = FilterAndSortEncoders(std::move(encoders), preferredCodecs);

auto result = VideoFormatsMessage();
result.encodersCount = encoders.size();
result.encodersCount = (int)encoders.size();
result.formats = AppendUnique(std::move(encoders), std::move(decoders));
for (const auto &format : result.formats) {
RTC_LOG(LS_INFO) << "Format: " << format.ToString();
Expand Down
3 changes: 2 additions & 1 deletion TMessagesProj/jni/tgcalls/CodecSelectHelper.h
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ struct CommonCodecs {

VideoFormatsMessage ComposeSupportedFormats(
std::vector<webrtc::SdpVideoFormat> encoders,
std::vector<webrtc::SdpVideoFormat> decoders);
std::vector<webrtc::SdpVideoFormat> decoders,
const std::vector<std::string> &preferredCodecs);

CommonFormats ComputeCommonFormats(
const VideoFormatsMessage &my,
Expand Down
2 changes: 2 additions & 0 deletions TMessagesProj/jni/tgcalls/CryptoHelper.cpp
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
#include "CryptoHelper.h"

#include <cstring>

namespace tgcalls {

AesKeyIv PrepareAesKeyIv(const uint8_t *key, const uint8_t *msgKey, int x) {
Expand Down
18 changes: 17 additions & 1 deletion TMessagesProj/jni/tgcalls/EncryptedConnection.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,16 @@ absl::nullopt_t LogError(
return absl::nullopt;
}

bool ConstTimeIsDifferent(const void *a, const void *b, size_t size) {
auto ca = reinterpret_cast<const char*>(a);
auto cb = reinterpret_cast<const char*>(b);
volatile auto different = false;
for (const auto ce = ca + size; ca != ce; ++ca, ++cb) {
different |= (*ca != *cb);
}
return different;
}

} // namespace

EncryptedConnection::EncryptedConnection(
Expand Down Expand Up @@ -326,7 +336,7 @@ auto EncryptedConnection::handleIncomingPacket(const char *bytes, size_t size)
const auto msgKeyLarge = ConcatSHA256(
MemorySpan{ key + 88 + x, 32 },
MemorySpan{ decryptionBuffer.data(), decryptionBuffer.size() });
if (memcmp(msgKeyLarge.data() + 8, msgKey, 16)) {
if (ConstTimeIsDifferent(msgKeyLarge.data() + 8, msgKey, 16)) {
return LogError("Bad incoming data hash.");
}

Expand Down Expand Up @@ -364,10 +374,16 @@ auto EncryptedConnection::processPacket(
}

if (type == kEmptyId) {
if (additionalMessage) {
return LogError("Empty message should be only the first one in the packet.");
}
RTC_LOG(LS_INFO) << logHeader()
<< "Got RECV:empty" << "#" << currentCounter;
reader.Consume(1);
} else if (type == kAckId) {
if (!additionalMessage) {
return LogError("Ack message must not be the first one in the packet.");
}
ackMyMessage(currentSeq);
reader.Consume(1);
} else if (auto message = DeserializeMessage(reader, singleMessagePacket)) {
Expand Down
14 changes: 7 additions & 7 deletions TMessagesProj/jni/tgcalls/Instance.cpp
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
#include "Instance.h"

#include "VideoCaptureInterfaceImpl.h"

#include <algorithm>
#include <stdarg.h>

Expand All @@ -10,8 +8,8 @@ namespace {

std::function<void(std::string const &)> globalLoggingFunction;

std::map<std::string, std::unique_ptr<Meta>> &MetaMap() {
static auto result = std::map<std::string, std::unique_ptr<Meta>>();
std::map<std::string, std::shared_ptr<Meta>> &MetaMap() {
static auto result = std::map<std::string, std::shared_ptr<Meta>>();
return result;
}

Expand Down Expand Up @@ -44,10 +42,12 @@ std::unique_ptr<Instance> Meta::Create(
: nullptr;
}

void Meta::RegisterOne(std::unique_ptr<Meta> meta) {
void Meta::RegisterOne(std::shared_ptr<Meta> meta) {
if (meta) {
const auto version = meta->version();
MetaMap().emplace(version, std::move(meta));
const auto versions = meta->versions();
for (auto &it : versions) {
MetaMap().emplace(it, meta);
}
}
}

Expand Down
19 changes: 13 additions & 6 deletions TMessagesProj/jni/tgcalls/Instance.h
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,11 @@ struct Endpoint {
unsigned char peerTag[16] = { 0 };
};

enum class ProtocolVersion {
V0,
V1 // Low-cost network negotiation
};

enum class NetworkType {
Unknown,
Gprs,
Expand Down Expand Up @@ -98,6 +103,8 @@ struct Config {
int maxApiLayer = 0;
float preferredAspectRatio;
bool enableHighBitrateVideo = false;
std::vector<std::string> preferredVideoCodecs;
ProtocolVersion protocolVersion = ProtocolVersion::V0;
};

struct EncryptionKey {
Expand Down Expand Up @@ -174,7 +181,7 @@ class Instance {
virtual void receiveSignalingData(const std::vector<uint8_t> &data) = 0;
virtual void setVideoCapture(std::shared_ptr<VideoCaptureInterface> videoCapture) = 0;

virtual FinalState stop() = 0;
virtual void stop(std::function<void(FinalState)> completion) = 0;

};

Expand Down Expand Up @@ -204,7 +211,7 @@ class Meta {

virtual std::unique_ptr<Instance> construct(Descriptor &&descriptor) = 0;
virtual int connectionMaxLayer() = 0;
virtual std::string version() = 0;
virtual std::vector<std::string> versions() = 0;

static std::unique_ptr<Instance> Create(
const std::string &version,
Expand All @@ -218,7 +225,7 @@ class Meta {

template <typename Implementation>
static bool RegisterOne();
static void RegisterOne(std::unique_ptr<Meta> meta);
static void RegisterOne(std::shared_ptr<Meta> meta);

};

Expand All @@ -229,14 +236,14 @@ bool Meta::RegisterOne() {
int connectionMaxLayer() override {
return Implementation::GetConnectionMaxLayer();
}
std::string version() override {
return Implementation::GetVersion();
std::vector<std::string> versions() override {
return Implementation::GetVersions();
}
std::unique_ptr<Instance> construct(Descriptor &&descriptor) override {
return std::make_unique<Implementation>(std::move(descriptor));
}
};
RegisterOne(std::make_unique<MetaImpl>());
RegisterOne(std::make_shared<MetaImpl>());
return true;
}

Expand Down
Loading

0 comments on commit 4c5f32b

Please sign in to comment.