id
int64
0
755k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
65
repo_stars
int64
100
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
9 values
repo_extraction_date
stringclasses
92 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
751,663
typers.cpp
savoirfairelinux_jami-daemon/test/unitTest/conversation/typers.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <cppunit/TestAssert.h> #include <cppunit/TestFixture.h> #include <cppunit/extensions/HelperMacros.h> #include <condition_variable> #include <string> #include <fstream> #include <streambuf> #include <filesystem> #include <msgpack.hpp> #include "../../test_runner.h" #include "account_const.h" #include "archiver.h" #include "base64.h" #include "common.h" #include "conversation/conversationcommon.h" #include "fileutils.h" #include "jami.h" #include "manager.h" #include <dhtnet/certstore.h> using namespace std::string_literals; using namespace std::literals::chrono_literals; using namespace libjami::Account; namespace jami { namespace test { struct UserData { std::string conversationId; bool registered {false}; bool stopped {false}; bool requestReceived {false}; bool deviceAnnounced {false}; std::map<std::string, int> composing; }; class TypersTest : public CppUnit::TestFixture { public: ~TypersTest() { libjami::fini(); } static std::string name() { return "Typers"; } void setUp(); void tearDown(); std::string aliceId; UserData aliceData; std::string bobId; UserData bobData; std::mutex mtx; std::unique_lock<std::mutex> lk {mtx}; std::condition_variable cv; void connectSignals(); void testSetIsComposing(); void testTimeout(); void testTypingRemovedOnMemberRemoved(); void testAccountConfig(); private: CPPUNIT_TEST_SUITE(TypersTest); CPPUNIT_TEST(testSetIsComposing); CPPUNIT_TEST(testTimeout); CPPUNIT_TEST(testTypingRemovedOnMemberRemoved); CPPUNIT_TEST(testAccountConfig); CPPUNIT_TEST_SUITE_END(); }; CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(TypersTest, TypersTest::name()); void TypersTest::setUp() { // Init daemon libjami::init( libjami::InitFlag(libjami::LIBJAMI_FLAG_DEBUG | libjami::LIBJAMI_FLAG_CONSOLE_LOG)); if (not Manager::instance().initialized) CPPUNIT_ASSERT(libjami::start("jami-sample.yml")); auto actors = load_actors("actors/alice-bob.yml"); aliceId = actors["alice"]; bobId = actors["bob"]; aliceData = {}; bobData = {}; wait_for_announcement_of({aliceId, bobId}); } void TypersTest::connectSignals() { std::map<std::string, std::shared_ptr<libjami::CallbackWrapperBase>> confHandlers; confHandlers.insert( libjami::exportable_callback<libjami::ConfigurationSignal::VolatileDetailsChanged>( [&](const std::string& accountId, const std::map<std::string, std::string>&) { if (accountId == aliceId) { auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto details = aliceAccount->getVolatileAccountDetails(); auto daemonStatus = details[libjami::Account::ConfProperties::Registration::STATUS]; if (daemonStatus == "REGISTERED") { aliceData.registered = true; } else if (daemonStatus == "UNREGISTERED") { aliceData.stopped = true; } auto deviceAnnounced = details[libjami::Account::VolatileProperties::DEVICE_ANNOUNCED]; aliceData.deviceAnnounced = deviceAnnounced == "true"; } else if (accountId == bobId) { auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto details = bobAccount->getVolatileAccountDetails(); auto daemonStatus = details[libjami::Account::ConfProperties::Registration::STATUS]; if (daemonStatus == "REGISTERED") { bobData.registered = true; } else if (daemonStatus == "UNREGISTERED") { bobData.stopped = true; } auto deviceAnnounced = details[libjami::Account::VolatileProperties::DEVICE_ANNOUNCED]; bobData.deviceAnnounced = deviceAnnounced == "true"; } cv.notify_one(); })); confHandlers.insert(libjami::exportable_callback<libjami::ConversationSignal::ConversationReady>( [&](const std::string& accountId, const std::string& conversationId) { if (accountId == aliceId) { aliceData.conversationId = conversationId; } else if (accountId == bobId) { bobData.conversationId = conversationId; } cv.notify_one(); })); confHandlers.insert( libjami::exportable_callback<libjami::ConversationSignal::ConversationRequestReceived>( [&](const std::string& accountId, const std::string& /* conversationId */, std::map<std::string, std::string> /*metadatas*/) { if (accountId == aliceId) { aliceData.requestReceived = true; } else if (accountId == bobId) { bobData.requestReceived = true; } cv.notify_one(); })); confHandlers.insert( libjami::exportable_callback<libjami::ConfigurationSignal::ComposingStatusChanged>( [&](const std::string& accountId, const std::string& /* conversationId */, const std::string& contactUri, int status) { if (accountId == aliceId) { aliceData.composing[contactUri] = status; } else if (accountId == bobId) { bobData.composing[contactUri] = status; } cv.notify_one(); })); libjami::registerSignalHandlers(confHandlers); } void TypersTest::tearDown() { wait_for_removal_of({aliceId, bobId}); } void TypersTest::testSetIsComposing() { connectSignals(); auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto aliceUri = aliceAccount->getUsername(); auto bobUri = bobAccount->getUsername(); aliceAccount->addContact(bobUri); aliceAccount->sendTrustRequest(bobUri, {}); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.requestReceived; })); CPPUNIT_ASSERT(bobAccount->getTrustRequests().size() == 1); libjami::acceptConversationRequest(bobId, aliceData.conversationId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return !bobData.conversationId.empty(); })); std::this_thread::sleep_for(5s); // Wait a bit to ensure that everything is updated libjami::setIsComposing(aliceId, "swarm:" + aliceData.conversationId, true); CPPUNIT_ASSERT(cv.wait_for(lk, 5s, [&]() { return bobData.composing[aliceUri]; })); libjami::setIsComposing(aliceId, "swarm:" + aliceData.conversationId, false); CPPUNIT_ASSERT(cv.wait_for(lk, 12s, [&]() { return !bobData.composing[aliceUri]; })); } void TypersTest::testTimeout() { connectSignals(); auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto aliceUri = aliceAccount->getUsername(); auto bobUri = bobAccount->getUsername(); aliceAccount->addContact(bobUri); aliceAccount->sendTrustRequest(bobUri, {}); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.requestReceived; })); CPPUNIT_ASSERT(bobAccount->getTrustRequests().size() == 1); libjami::acceptConversationRequest(bobId, aliceData.conversationId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return !bobData.conversationId.empty(); })); std::this_thread::sleep_for(5s); // Wait a bit to ensure that everything is updated libjami::setIsComposing(aliceId, "swarm:" + aliceData.conversationId, true); CPPUNIT_ASSERT(cv.wait_for(lk, 5s, [&]() { return bobData.composing[aliceUri]; })); // After 12s, it should be false CPPUNIT_ASSERT(cv.wait_for(lk, 12s, [&]() { return !bobData.composing[aliceUri]; })); } void TypersTest::testTypingRemovedOnMemberRemoved() { connectSignals(); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto bobUri = bobAccount->getUsername(); auto convId = libjami::startConversation(aliceId); libjami::addConversationMember(aliceId, convId, bobUri); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.requestReceived; })); libjami::acceptConversationRequest(bobId, aliceData.conversationId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return !bobData.conversationId.empty(); })); std::this_thread::sleep_for(5s); // Wait a bit to ensure that everything is updated libjami::setIsComposing(bobId, "swarm:" + bobData.conversationId, true); CPPUNIT_ASSERT(cv.wait_for(lk, 5s, [&]() { return aliceData.composing[bobUri]; })); libjami::removeConversationMember(aliceId, convId, bobUri); CPPUNIT_ASSERT(cv.wait_for(lk, 5s, [&]() { return !aliceData.composing[bobUri]; })); } void TypersTest::testAccountConfig() { connectSignals(); auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto aliceUri = aliceAccount->getUsername(); auto bobUri = bobAccount->getUsername(); std::map<std::string, std::string> details; details[ConfProperties::SENDCOMPOSING] = "false"; libjami::setAccountDetails(aliceId, details); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return aliceData.registered; })); aliceAccount->addContact(bobUri); aliceAccount->sendTrustRequest(bobUri, {}); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.requestReceived; })); CPPUNIT_ASSERT(bobAccount->getTrustRequests().size() == 1); libjami::acceptConversationRequest(bobId, aliceData.conversationId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return !bobData.conversationId.empty(); })); std::this_thread::sleep_for(5s); // Wait a bit to ensure that everything is updated // Should not receive composing status libjami::setIsComposing(aliceId, "swarm:" + aliceData.conversationId, true); CPPUNIT_ASSERT(!cv.wait_for(lk, 5s, [&]() { return bobData.composing[aliceUri] ; })); } } // namespace test } // namespace jami RING_TEST_RUNNER(jami::test::TypersTest::name())
11,089
C++
.cpp
250
37.392
107
0.666975
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,664
conversationMembersEvent.cpp
savoirfairelinux_jami-daemon/test/unitTest/conversation/conversationMembersEvent.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <cppunit/TestAssert.h> #include <cppunit/TestFixture.h> #include <cppunit/extensions/HelperMacros.h> #include <condition_variable> #include <string> #include <fstream> #include <streambuf> #include <git2.h> #include <filesystem> #include <msgpack.hpp> #include "manager.h" #include "../../test_runner.h" #include "jami.h" #include "base64.h" #include "fileutils.h" #include "account_const.h" #include "common.h" #include "conversation/conversationcommon.h" using namespace std::string_literals; using namespace std::literals::chrono_literals; using namespace libjami::Account; namespace jami { namespace test { struct UserData { std::string conversationId; bool removed {false}; bool requestReceived {false}; bool requestRemoved {false}; bool errorDetected {false}; bool registered {false}; bool stopped {false}; bool deviceAnnounced {false}; bool contactRemoved {false}; bool contactAdded {false}; Conversation::BootstrapStatus bootstrap {Conversation::BootstrapStatus::FAILED}; std::string payloadTrustRequest; std::vector<libjami::SwarmMessage> messages; std::vector<libjami::SwarmMessage> messagesUpdated; std::map<std::string, int> members; }; class ConversationMembersEventTest : public CppUnit::TestFixture { public: ~ConversationMembersEventTest() { libjami::fini(); } static std::string name() { return "ConversationMembersEventTest"; } void setUp(); void tearDown(); void generateFakeInvite(std::shared_ptr<JamiAccount> account, const std::string& convId, const std::string& uri); void testAddInvalidUri(); void testRemoveConversationNoMember(); void testRemoveConversationWithMember(); void testAddMember(); void testMemberAddedNoBadFile(); void testAddOfflineMemberThenConnects(); void testAddAcceptOfflineThenConnects(); void testGetMembers(); void testRemoveMember(); void testRemovedMemberDoesNotReceiveMessageFromAdmin(); void testRemovedMemberDoesNotReceiveMessageFromPeer(); void testRemoveInvitedMember(); void testMemberBanNoBadFile(); void testMemberTryToRemoveAdmin(); void testBannedMemberCannotSendMessage(); void testAdminCanReAddMember(); void testMemberCannotBanOther(); void testMemberCannotUnBanOther(); void testCheckAdminFakeAVoteIsDetected(); void testAdminCannotKickTheirself(); void testCommitUnauthorizedUser(); void testMemberJoinsNoBadFile(); void testMemberAddedNoCertificate(); void testMemberJoinsInviteRemoved(); void testFailAddMemberInOneToOne(); void testOneToOneFetchWithNewMemberRefused(); void testConversationMemberEvent(); void testGetConversationsMembersWhileSyncing(); void testGetConversationMembersWithSelfOneOne(); void testAvoidTwoOneToOne(); void testAvoidTwoOneToOneMultiDevices(); void testRemoveRequestBannedMultiDevices(); void testBanUnbanMultiDevice(); void testBanUnbanGotFirstConv(); void testBanHostWhileHosting(); void testAddContactTwice(); void testBanFromNewDevice(); std::string aliceId; UserData aliceData; std::string bobId; UserData bobData; std::string bob2Id; UserData bob2Data; std::string carlaId; UserData carlaData; std::mutex mtx; std::unique_lock<std::mutex> lk {mtx}; std::condition_variable cv; void connectSignals(); private: CPPUNIT_TEST_SUITE(ConversationMembersEventTest); CPPUNIT_TEST(testAddInvalidUri); CPPUNIT_TEST(testRemoveConversationNoMember); CPPUNIT_TEST(testRemoveConversationWithMember); CPPUNIT_TEST(testAddMember); CPPUNIT_TEST(testMemberAddedNoBadFile); CPPUNIT_TEST(testAddOfflineMemberThenConnects); CPPUNIT_TEST(testAddAcceptOfflineThenConnects); CPPUNIT_TEST(testGetMembers); CPPUNIT_TEST(testRemoveMember); CPPUNIT_TEST(testRemovedMemberDoesNotReceiveMessageFromAdmin); CPPUNIT_TEST(testRemovedMemberDoesNotReceiveMessageFromPeer); CPPUNIT_TEST(testRemoveInvitedMember); CPPUNIT_TEST(testMemberBanNoBadFile); CPPUNIT_TEST(testMemberTryToRemoveAdmin); CPPUNIT_TEST(testBannedMemberCannotSendMessage); CPPUNIT_TEST(testAdminCanReAddMember); CPPUNIT_TEST(testMemberCannotBanOther); CPPUNIT_TEST(testMemberCannotUnBanOther); CPPUNIT_TEST(testCheckAdminFakeAVoteIsDetected); CPPUNIT_TEST(testAdminCannotKickTheirself); CPPUNIT_TEST(testCommitUnauthorizedUser); CPPUNIT_TEST(testMemberJoinsNoBadFile); CPPUNIT_TEST(testMemberAddedNoCertificate); CPPUNIT_TEST(testMemberJoinsInviteRemoved); CPPUNIT_TEST(testFailAddMemberInOneToOne); CPPUNIT_TEST(testOneToOneFetchWithNewMemberRefused); CPPUNIT_TEST(testConversationMemberEvent); CPPUNIT_TEST(testGetConversationsMembersWhileSyncing); CPPUNIT_TEST(testGetConversationMembersWithSelfOneOne); CPPUNIT_TEST(testAvoidTwoOneToOne); CPPUNIT_TEST(testAvoidTwoOneToOneMultiDevices); CPPUNIT_TEST(testRemoveRequestBannedMultiDevices); CPPUNIT_TEST(testBanUnbanMultiDevice); CPPUNIT_TEST(testBanUnbanGotFirstConv); CPPUNIT_TEST(testBanHostWhileHosting); CPPUNIT_TEST(testAddContactTwice); CPPUNIT_TEST(testBanFromNewDevice); CPPUNIT_TEST_SUITE_END(); }; CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(ConversationMembersEventTest, ConversationMembersEventTest::name()); void ConversationMembersEventTest::setUp() { connectSignals(); // Init daemon libjami::init( libjami::InitFlag(libjami::LIBJAMI_FLAG_DEBUG | libjami::LIBJAMI_FLAG_CONSOLE_LOG)); if (not Manager::instance().initialized) CPPUNIT_ASSERT(libjami::start("jami-sample.yml")); auto actors = load_actors("actors/alice-bob-carla.yml"); aliceId = actors["alice"]; bobId = actors["bob"]; carlaId = actors["carla"]; aliceData = {}; bobData = {}; bob2Data = {}; carlaData = {}; Manager::instance().sendRegister(carlaId, false); wait_for_announcement_of({aliceId, bobId}); } void ConversationMembersEventTest::tearDown() { connectSignals(); auto bobArchive = std::filesystem::current_path().string() + "/bob.gz"; std::remove(bobArchive.c_str()); if (bob2Id.empty()) { wait_for_removal_of({aliceId, bobId, carlaId}); } else { wait_for_removal_of({aliceId, bobId, carlaId, bob2Id}); } } void ConversationMembersEventTest::connectSignals() { std::map<std::string, std::shared_ptr<libjami::CallbackWrapperBase>> confHandlers; confHandlers.insert( libjami::exportable_callback<libjami::ConfigurationSignal::VolatileDetailsChanged>( [&](const std::string& accountId, const std::map<std::string, std::string>&) { if (accountId == aliceId) { auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto details = aliceAccount->getVolatileAccountDetails(); auto daemonStatus = details[libjami::Account::ConfProperties::Registration::STATUS]; if (daemonStatus == "REGISTERED") { aliceData.registered = true; } else if (daemonStatus == "UNREGISTERED") { aliceData.stopped = true; } auto deviceAnnounced = details[libjami::Account::VolatileProperties::DEVICE_ANNOUNCED]; aliceData.deviceAnnounced = deviceAnnounced == "true"; } else if (accountId == bobId) { auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto details = bobAccount->getVolatileAccountDetails(); auto daemonStatus = details[libjami::Account::ConfProperties::Registration::STATUS]; if (daemonStatus == "REGISTERED") { bobData.registered = true; } else if (daemonStatus == "UNREGISTERED") { bobData.stopped = true; } auto deviceAnnounced = details[libjami::Account::VolatileProperties::DEVICE_ANNOUNCED]; bobData.deviceAnnounced = deviceAnnounced == "true"; } else if (accountId == bob2Id) { auto bob2Account = Manager::instance().getAccount<JamiAccount>(bob2Id); auto details = bob2Account->getVolatileAccountDetails(); auto daemonStatus = details[libjami::Account::ConfProperties::Registration::STATUS]; if (daemonStatus == "REGISTERED") { bob2Data.registered = true; } else if (daemonStatus == "UNREGISTERED") { bob2Data.stopped = true; } auto deviceAnnounced = details[libjami::Account::VolatileProperties::DEVICE_ANNOUNCED]; bob2Data.deviceAnnounced = deviceAnnounced == "true"; } else if (accountId == carlaId) { auto carlaAccount = Manager::instance().getAccount<JamiAccount>(carlaId); auto details = carlaAccount->getVolatileAccountDetails(); auto daemonStatus = details[libjami::Account::ConfProperties::Registration::STATUS]; if (daemonStatus == "REGISTERED") { carlaData.registered = true; } else if (daemonStatus == "UNREGISTERED") { carlaData.stopped = true; } auto deviceAnnounced = details[libjami::Account::VolatileProperties::DEVICE_ANNOUNCED]; carlaData.deviceAnnounced = deviceAnnounced == "true"; } cv.notify_one(); })); confHandlers.insert(libjami::exportable_callback<libjami::ConversationSignal::ConversationReady>( [&](const std::string& accountId, const std::string& conversationId) { if (accountId == aliceId) { aliceData.conversationId = conversationId; } else if (accountId == bobId) { bobData.conversationId = conversationId; } else if (accountId == bob2Id) { bob2Data.conversationId = conversationId; } else if (accountId == carlaId) { carlaData.conversationId = conversationId; } cv.notify_one(); })); confHandlers.insert(libjami::exportable_callback<libjami::ConversationSignal::ConversationMemberEvent>( [&](const std::string& accountId, const std::string& conversationId, const auto& member, auto status) { if (accountId == aliceId) { aliceData.members[member] = status; } else if (accountId == bobId) { bobData.members[member] = status; } else if (accountId == bob2Id) { bob2Data.members[member] = status; } else if (accountId == carlaId) { carlaData.members[member] = status; } cv.notify_one(); })); confHandlers.insert( libjami::exportable_callback<libjami::ConfigurationSignal::IncomingTrustRequest>( [&](const std::string& account_id, const std::string& /*from*/, const std::string& /*conversationId*/, const std::vector<uint8_t>& payload, time_t /*received*/) { auto payloadStr = std::string(payload.data(), payload.data() + payload.size()); if (account_id == aliceId) aliceData.payloadTrustRequest = payloadStr; else if (account_id == bobId) bobData.payloadTrustRequest = payloadStr; cv.notify_one(); })); confHandlers.insert( libjami::exportable_callback<libjami::ConversationSignal::ConversationRequestReceived>( [&](const std::string& accountId, const std::string& /* conversationId */, std::map<std::string, std::string> /*metadatas*/) { if (accountId == aliceId) { aliceData.requestReceived = true; } else if (accountId == bobId) { bobData.requestReceived = true; } else if (accountId == bob2Id) { bob2Data.requestReceived = true; } else if (accountId == carlaId) { carlaData.requestReceived = true; } cv.notify_one(); })); confHandlers.insert( libjami::exportable_callback<libjami::ConversationSignal::ConversationRequestDeclined>( [&](const std::string& accountId, const std::string&) { if (accountId == bobId) { bobData.requestRemoved = true; } else if (accountId == bob2Id) { bob2Data.requestRemoved = true; } cv.notify_one(); })); confHandlers.insert(libjami::exportable_callback<libjami::ConversationSignal::SwarmMessageReceived>( [&](const std::string& accountId, const std::string& /* conversationId */, libjami::SwarmMessage message) { if (accountId == aliceId) { aliceData.messages.emplace_back(message); } else if (accountId == bobId) { bobData.messages.emplace_back(message); } else if (accountId == bob2Id) { bob2Data.messages.emplace_back(message); } else if (accountId == carlaId) { carlaData.messages.emplace_back(message); } cv.notify_one(); })); confHandlers.insert(libjami::exportable_callback<libjami::ConversationSignal::SwarmMessageUpdated>( [&](const std::string& accountId, const std::string& /* conversationId */, libjami::SwarmMessage message) { if (accountId == aliceId) { aliceData.messagesUpdated.emplace_back(message); } else if (accountId == bobId) { bobData.messagesUpdated.emplace_back(message); } else if (accountId == carlaId) { carlaData.messagesUpdated.emplace_back(message); } cv.notify_one(); })); confHandlers.insert( libjami::exportable_callback<libjami::ConversationSignal::OnConversationError>( [&](const std::string& accountId, const std::string& /* conversationId */, int /*code*/, const std::string& /* what */) { if (accountId == aliceId) aliceData.errorDetected = true; else if (accountId == bobId) bobData.errorDetected = true; else if (accountId == carlaId) carlaData.errorDetected = true; cv.notify_one(); })); confHandlers.insert( libjami::exportable_callback<libjami::ConversationSignal::ConversationRemoved>( [&](const std::string& accountId, const std::string&) { if (accountId == aliceId) aliceData.removed = true; else if (accountId == bobId) bobData.removed = true; else if (accountId == bob2Id) bob2Data.removed = true; cv.notify_one(); })); confHandlers.insert(libjami::exportable_callback<libjami::ConfigurationSignal::ContactRemoved>( [&](const std::string& accountId, const std::string&, bool) { if (accountId == bobId) { bobData.contactRemoved = true; } else if (accountId == bob2Id) { bob2Data.contactRemoved = true; } cv.notify_one(); })); confHandlers.insert(libjami::exportable_callback<libjami::ConfigurationSignal::ContactAdded>( [&](const std::string& accountId, const std::string&, bool) { if (accountId == aliceId) { aliceData.contactAdded = true; } else if (accountId == bobId) { bobData.contactAdded = true; } else if (accountId == bob2Id) { bob2Data.contactAdded = true; } cv.notify_one(); })); libjami::registerSignalHandlers(confHandlers); } void ConversationMembersEventTest::generateFakeInvite(std::shared_ptr<JamiAccount> account, const std::string& convId, const std::string& uri) { auto repoPath = fileutils::get_data_dir() / account->getAccountID() / "conversations" / convId; // remove from member & add into banned without voting for the ban auto memberFile = repoPath / "invited" / uri; std::ofstream file(memberFile); if (file.is_open()) { file.close(); } git_repository* repo = nullptr; if (git_repository_open(&repo, repoPath.c_str()) != 0) return; GitRepository rep = {std::move(repo), git_repository_free}; // git add -A git_index* index_ptr = nullptr; if (git_repository_index(&index_ptr, repo) < 0) return; GitIndex index {index_ptr, git_index_free}; git_strarray array = {nullptr, 0}; git_index_add_all(index.get(), &array, 0, nullptr, nullptr); git_index_write(index.get()); git_strarray_dispose(&array); ConversationRepository cr(account, convId); Json::Value json; json["action"] = "add"; json["uri"] = uri; json["type"] = "member"; Json::StreamWriterBuilder wbuilder; wbuilder["commentStyle"] = "None"; wbuilder["indentation"] = ""; cr.commitMessage(Json::writeString(wbuilder, json)); libjami::sendMessage(account->getAccountID(), convId, "trigger the fake history to be pulled"s, ""); } void ConversationMembersEventTest::testAddInvalidUri() { connectSignals(); auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); aliceAccount->addContact("Shitty/Uri"); CPPUNIT_ASSERT(!cv.wait_for(lk, 5s, [&]() { return aliceData.contactAdded; })); CPPUNIT_ASSERT(aliceData.conversationId.empty()); } void ConversationMembersEventTest::testRemoveConversationNoMember() { connectSignals(); // Start conversation auto convId = libjami::startConversation(aliceId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return !aliceData.conversationId.empty(); })); // Assert that repository exists auto repoPath = fileutils::get_data_dir() / aliceId / "conversations" / convId; auto dataPath = fileutils::get_data_dir() / aliceId / "conversation_data" / convId; CPPUNIT_ASSERT(std::filesystem::is_directory(repoPath)); CPPUNIT_ASSERT(std::filesystem::is_directory(dataPath)); auto conversations = libjami::getConversations(aliceId); CPPUNIT_ASSERT(conversations.size() == 1); // Removing the conversation will erase all related files CPPUNIT_ASSERT(libjami::removeConversation(aliceId, convId)); conversations = libjami::getConversations(aliceId); CPPUNIT_ASSERT(conversations.size() == 0); CPPUNIT_ASSERT(!std::filesystem::is_directory(repoPath)); CPPUNIT_ASSERT(!std::filesystem::is_directory(dataPath)); } void ConversationMembersEventTest::testRemoveConversationWithMember() { connectSignals(); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto bobUri = bobAccount->getUsername(); auto convId = libjami::startConversation(aliceId); libjami::addConversationMember(aliceId, convId, bobUri); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.requestReceived; })); // Assert that repository exists auto repoPath = fileutils::get_data_dir() / aliceId / "conversations" / convId; CPPUNIT_ASSERT(std::filesystem::is_directory(repoPath)); // Check created files auto bobInvitedFile = repoPath / "invited" / bobUri; CPPUNIT_ASSERT(std::filesystem::is_regular_file(bobInvitedFile)); auto aliceMsgSize = aliceData.messages.size(); libjami::acceptConversationRequest(bobId, convId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return aliceMsgSize + 1 == aliceData.messages.size(); })); auto clonedPath = fileutils::get_data_dir() / bobId / "conversations" / convId; bobInvitedFile = clonedPath / "invited" / bobUri; CPPUNIT_ASSERT(!std::filesystem::is_regular_file(bobInvitedFile)); // Remove conversation from alice once member confirmed auto bobMsgSize = bobData.messages.size(); libjami::removeConversation(aliceId, convId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobMsgSize + 1 == bobData.messages.size() && bobData.messages.rbegin()->type == "member"; })); std::this_thread::sleep_for(3s); CPPUNIT_ASSERT(!std::filesystem::is_directory(repoPath)); } void ConversationMembersEventTest::testAddMember() { connectSignals(); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto bobUri = bobAccount->getUsername(); auto convId = libjami::startConversation(aliceId); libjami::addConversationMember(aliceId, convId, bobUri); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.requestReceived; })); // Assert that repository exists auto repoPath = fileutils::get_data_dir() / aliceId / "conversations" / convId; CPPUNIT_ASSERT(std::filesystem::is_directory(repoPath)); // Check created files auto bobInvited = repoPath / "invited" / bobUri; CPPUNIT_ASSERT(std::filesystem::is_regular_file(bobInvited)); libjami::acceptConversationRequest(bobId, convId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return !bobData.conversationId.empty(); })); auto clonedPath = fileutils::get_data_dir() / bobId / "conversations" / convId; CPPUNIT_ASSERT(std::filesystem::is_directory(clonedPath)); bobInvited = clonedPath / "invited" / bobUri; CPPUNIT_ASSERT(!std::filesystem::is_regular_file(bobInvited)); auto bobMember = clonedPath / "members" / (bobUri + ".crt"); CPPUNIT_ASSERT(std::filesystem::is_regular_file(bobMember)); } void ConversationMembersEventTest::testMemberAddedNoBadFile() { connectSignals(); auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto bobUri = bobAccount->getUsername(); auto convId = libjami::startConversation(aliceId); addFile(aliceAccount, convId, "BADFILE"); // NOTE: Add certificate because no DHT lookup aliceAccount->certStore().pinCertificate(bobAccount->identity().second); generateFakeInvite(aliceAccount, convId, bobUri); // Generate conv request aliceAccount->sendTextMessage(bobUri, std::string(bobAccount->currentDeviceId()), {{"application/invite+json", "{\"conversationId\":\"" + convId + "\"}"}}); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.requestReceived; })); libjami::acceptConversationRequest(bobId, convId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.errorDetected; })); } void ConversationMembersEventTest::testAddOfflineMemberThenConnects() { connectSignals(); auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto carlaAccount = Manager::instance().getAccount<JamiAccount>(carlaId); auto carlaUri = carlaAccount->getUsername(); aliceAccount->trackBuddyPresence(carlaUri, true); auto convId = libjami::startConversation(aliceId); CPPUNIT_ASSERT(cv.wait_for(lk, 10s, [&] { return !aliceData.conversationId.empty(); })); auto aliceMsgSize = aliceData.messages.size(); libjami::addConversationMember(aliceId, convId, carlaUri); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return aliceMsgSize + 1 == aliceData.messages.size(); })); CPPUNIT_ASSERT(!cv.wait_for(lk, 30s, [&] { return carlaData.requestReceived; })); Manager::instance().sendRegister(carlaId, true); CPPUNIT_ASSERT(cv.wait_for(lk, 60s, [&] { return carlaData.requestReceived; })); libjami::acceptConversationRequest(carlaId, convId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return !carlaData.conversationId.empty(); })); auto clonedPath = fileutils::get_data_dir() / carlaId / "conversations" / convId; CPPUNIT_ASSERT(std::filesystem::is_directory(clonedPath)); } void ConversationMembersEventTest::testAddAcceptOfflineThenConnects() { connectSignals(); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto bobUri = bobAccount->getUsername(); libjami::startConversation(aliceId); CPPUNIT_ASSERT(cv.wait_for(lk, 10s, [&] { return !aliceData.conversationId.empty(); })); libjami::addConversationMember(aliceId, aliceData.conversationId, bobUri); CPPUNIT_ASSERT(cv.wait_for(lk, 60s, [&] { return bobData.requestReceived; })); Manager::instance().sendRegister(aliceId, false); // This avoid to sync immediately CPPUNIT_ASSERT(cv.wait_for(lk, 60s, [&] { return aliceData.stopped; })); // Accepts libjami::acceptConversationRequest(bobId, aliceData.conversationId); CPPUNIT_ASSERT(!cv.wait_for(lk, 30s, [&]() { return !bobData.conversationId.empty(); })); Manager::instance().sendRegister(aliceId, true); // This avoid to sync immediately CPPUNIT_ASSERT(cv.wait_for(lk, 60s, [&]() { return !bobData.conversationId.empty(); })); } void ConversationMembersEventTest::testGetMembers() { connectSignals(); auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto bobUri = bobAccount->getUsername(); // Start a conversation and add member auto convId = libjami::startConversation(aliceId); libjami::addConversationMember(aliceId, convId, bobUri); CPPUNIT_ASSERT(cv.wait_for(lk, 60s, [&]() { return bobData.requestReceived; })); // Assert that repository exists auto repoPath = fileutils::get_data_dir() / aliceId / "conversations" / convId; CPPUNIT_ASSERT(std::filesystem::is_directory(repoPath)); auto members = libjami::getConversationMembers(aliceId, convId); CPPUNIT_ASSERT(members.size() == 2); CPPUNIT_ASSERT(members[0]["uri"] == aliceAccount->getUsername()); CPPUNIT_ASSERT(members[0]["role"] == "admin"); CPPUNIT_ASSERT(members[1]["uri"] == bobUri); CPPUNIT_ASSERT(members[1]["role"] == "invited"); auto aliceMsgSize = aliceData.messages.size(); libjami::acceptConversationRequest(bobId, convId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return !bobData.conversationId.empty(); })); members = libjami::getConversationMembers(bobId, convId); CPPUNIT_ASSERT(members.size() == 2); CPPUNIT_ASSERT(cv.wait_for(lk, 60s, [&]() { return aliceMsgSize + 1 == aliceData.messages.size(); })); members = libjami::getConversationMembers(aliceId, convId); CPPUNIT_ASSERT(members.size() == 2); CPPUNIT_ASSERT(members[0]["uri"] == aliceAccount->getUsername()); CPPUNIT_ASSERT(members[0]["role"] == "admin"); CPPUNIT_ASSERT(members[1]["uri"] == bobUri); CPPUNIT_ASSERT(members[1]["role"] == "member"); } void ConversationMembersEventTest::testRemoveMember() { connectSignals(); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto bobUri = bobAccount->getUsername(); auto convId = libjami::startConversation(aliceId); libjami::addConversationMember(aliceId, convId, bobUri); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.requestReceived; })); auto aliceMsgSize = aliceData.messages.size(); libjami::acceptConversationRequest(bobId, convId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return aliceMsgSize + 1 == aliceData.messages.size(); })); // Now check that alice, has the only admin, can remove bob libjami::removeConversationMember(aliceId, convId, bobUri); CPPUNIT_ASSERT( cv.wait_for(lk, 30s, [&]() { return aliceData.messages.size() == aliceMsgSize + 3 /* vote + ban */; })); auto members = libjami::getConversationMembers(aliceId, convId); auto bobBanned = false; for (auto& member : members) { if (member["uri"] == bobUri) bobBanned = member["role"] == "banned"; } CPPUNIT_ASSERT(bobBanned); } void ConversationMembersEventTest::testRemovedMemberDoesNotReceiveMessageFromAdmin() { connectSignals(); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto bobUri = bobAccount->getUsername(); auto convId = libjami::startConversation(aliceId); libjami::addConversationMember(aliceId, convId, bobUri); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.requestReceived; })); auto aliceMsgSize = aliceData.messages.size(); libjami::acceptConversationRequest(bobId, convId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return aliceMsgSize + 1 == aliceData.messages.size(); })); // Now check that alice, as the only admin, can remove bob libjami::removeConversationMember(aliceId, convId, bobUri); CPPUNIT_ASSERT( cv.wait_for(lk, 30s, [&]() { return aliceData.messages.size() == aliceMsgSize + 3 /* vote + ban */; })); // Now, bob is banned so they shoud not receive any message auto bobMsgSize = bobData.messages.size(); libjami::sendMessage(aliceId, convId, "hi"s, ""); CPPUNIT_ASSERT(!cv.wait_for(lk, 10s, [&]() { return bobMsgSize + 1 == bobData.messages.size(); })); } void ConversationMembersEventTest::testRemovedMemberDoesNotReceiveMessageFromPeer() { connectSignals(); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto bobUri = bobAccount->getUsername(); auto carlaAccount = Manager::instance().getAccount<JamiAccount>(carlaId); auto carlaUri = carlaAccount->getUsername(); Manager::instance().sendRegister(carlaId, true); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return carlaData.deviceAnnounced; })); // Make Carla send a contact request to Bob and wait until she receives a message from // him confirming that he has accepted the request. The point of this is to make sure // that Bob and Carla are connected; otherwise the test below where we check that Bob // hasn't received a message from Carla could pass for the wrong reason. carlaAccount->addContact(bobUri); carlaAccount->sendTrustRequest(bobUri, {}); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.requestReceived; })); auto carlaMsgSize = carlaData.messages.size(); CPPUNIT_ASSERT(bobAccount->acceptTrustRequest(carlaUri)); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return carlaMsgSize + 1 == carlaData.messages.size(); })); // Alice creates a swarm and adds Bob and Carla to it bobData.requestReceived = false; auto convId = libjami::startConversation(aliceId); libjami::addConversationMember(aliceId, convId, bobUri); libjami::addConversationMember(aliceId, convId, carlaUri); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.requestReceived && carlaData.requestReceived; })); libjami::acceptConversationRequest(bobId, convId); libjami::acceptConversationRequest(carlaId, convId); auto messageReceived = [](UserData& userData, const std::string& action, const std::string& uri) { for (auto& message : userData.messages) { if (message.type == "member" && message.body["action"] == action && message.body["uri"] == uri) return true; } return false; }; CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return messageReceived(aliceData, "join", bobUri); })); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return messageReceived(carlaData, "join", bobUri); })); // Alice bans Bob libjami::removeConversationMember(aliceId, convId, bobUri); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return messageReceived(aliceData, "ban", bobUri); })); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return messageReceived(carlaData, "ban", bobUri); })); // Carla's messages should now be received by Alice, but not Bob auto aliceMsgSize = aliceData.messages.size(); auto bobMsgSize = bobData.messages.size(); libjami::sendMessage(carlaId, convId, "hello"s, ""); CPPUNIT_ASSERT(!cv.wait_for(lk, 10s, [&]() { return bobMsgSize < bobData.messages.size(); })); CPPUNIT_ASSERT(cv.wait_for(lk, 10s, [&]() { return aliceMsgSize + 1 == aliceData.messages.size(); })); } void ConversationMembersEventTest::testRemoveInvitedMember() { connectSignals(); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto carlaAccount = Manager::instance().getAccount<JamiAccount>(carlaId); auto bobUri = bobAccount->getUsername(); auto carlaUri = carlaAccount->getUsername(); auto convId = libjami::startConversation(aliceId); // Add carla Manager::instance().sendRegister(carlaId, true); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return carlaData.deviceAnnounced; })); auto aliceMsgSize = aliceData.messages.size(); libjami::addConversationMember(aliceId, convId, carlaUri); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return carlaData.requestReceived && aliceMsgSize + 1 == aliceData.messages.size(); })); libjami::acceptConversationRequest(carlaId, convId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return !carlaData.conversationId.empty() && aliceMsgSize + 2 == aliceData.messages.size(); })); // Invite Alice auto carlaMsgSize = carlaData.messages.size(); libjami::addConversationMember(aliceId, convId, bobUri); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return aliceMsgSize + 3 == aliceData.messages.size() && carlaMsgSize + 1 == carlaData.messages.size() && bobData.requestReceived; })); auto members = libjami::getConversationMembers(aliceId, convId); CPPUNIT_ASSERT(members.size() == 3); members = libjami::getConversationMembers(carlaId, convId); CPPUNIT_ASSERT(members.size() == 3); // Now check that alice, has the only admin, can remove bob aliceMsgSize = aliceData.messages.size(); carlaMsgSize = carlaData.messages.size(); libjami::removeConversationMember(aliceId, convId, bobUri); CPPUNIT_ASSERT( cv.wait_for(lk, 30s, [&]() { return aliceMsgSize + 2 == aliceData.messages.size() && carlaMsgSize + 2 == carlaData.messages.size(); })); members = libjami::getConversationMembers(aliceId, convId); auto bobBanned = false; for (auto& member : members) { if (member["uri"] == bobUri) bobBanned = member["role"] == "banned"; } CPPUNIT_ASSERT(bobBanned); members = libjami::getConversationMembers(carlaId, convId); bobBanned = false; for (auto& member : members) { if (member["uri"] == bobUri) bobBanned = member["role"] == "banned"; } CPPUNIT_ASSERT(bobBanned); // Check that Carla is still able to sync carlaMsgSize = carlaData.messages.size(); libjami::sendMessage(aliceId, convId, "hi"s, ""); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return carlaMsgSize + 1 == carlaData.messages.size(); })); } void ConversationMembersEventTest::testMemberBanNoBadFile() { connectSignals(); auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto aliceUri = aliceAccount->getUsername(); auto bobUri = bobAccount->getUsername(); auto convId = libjami::startConversation(aliceId); auto carlaAccount = Manager::instance().getAccount<JamiAccount>(carlaId); auto carlaUri = carlaAccount->getUsername(); aliceAccount->trackBuddyPresence(carlaUri, true); Manager::instance().sendRegister(carlaId, true); CPPUNIT_ASSERT(cv.wait_for(lk, 60s, [&] { return carlaData.deviceAnnounced; })); libjami::addConversationMember(aliceId, convId, bobUri); CPPUNIT_ASSERT( cv.wait_for(lk, 30s, [&]() { return bobData.requestReceived; })); auto aliceMsgSize = aliceData.messages.size(); libjami::acceptConversationRequest(bobId, convId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return aliceMsgSize + 1 == aliceData.messages.size(); })); libjami::addConversationMember(aliceId, convId, carlaUri); CPPUNIT_ASSERT( cv.wait_for(lk, 30s, [&]() { return carlaData.requestReceived; })); aliceMsgSize = aliceData.messages.size(); auto bobMsgSize = bobData.messages.size(); libjami::acceptConversationRequest(carlaId, convId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return aliceMsgSize + 1 == aliceData.messages.size() && bobMsgSize + 1 == bobData.messages.size(); })); addFile(aliceAccount, convId, "BADFILE"); libjami::removeConversationMember(aliceId, convId, carlaUri); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.errorDetected; })); } void ConversationMembersEventTest::testMemberTryToRemoveAdmin() { connectSignals(); auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto aliceUri = aliceAccount->getUsername(); auto bobUri = bobAccount->getUsername(); auto convId = libjami::startConversation(aliceId); libjami::addConversationMember(aliceId, convId, bobUri); CPPUNIT_ASSERT( cv.wait_for(lk, 30s, [&]() { return bobData.requestReceived; })); auto aliceMsgSize = aliceData.messages.size(); libjami::acceptConversationRequest(bobId, convId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return aliceMsgSize + 1 == aliceData.messages.size(); })); // Now check that alice, has the only admin, can remove bob libjami::removeConversationMember(bobId, convId, aliceUri); auto members = libjami::getConversationMembers(aliceId, convId); CPPUNIT_ASSERT(members.size() == 2 && aliceMsgSize + 2 != aliceData.messages.size()); } void ConversationMembersEventTest::testBannedMemberCannotSendMessage() { connectSignals(); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto bobUri = bobAccount->getUsername(); auto convId = libjami::startConversation(aliceId); libjami::addConversationMember(aliceId, convId, bobUri); CPPUNIT_ASSERT( cv.wait_for(lk, 30s, [&]() { return bobData.requestReceived; })); auto aliceMsgSize = aliceData.messages.size(); libjami::acceptConversationRequest(bobId, convId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return aliceMsgSize + 1 == aliceData.messages.size(); })); libjami::removeConversationMember(aliceId, convId, bobUri); CPPUNIT_ASSERT( cv.wait_for(lk, 30s, [&]() { return aliceMsgSize + 3 == aliceData.messages.size(); })); auto members = libjami::getConversationMembers(aliceId, convId); auto bobBanned = false; for (auto& member : members) { if (member["uri"] == bobUri) bobBanned = member["role"] == "banned"; } CPPUNIT_ASSERT(bobBanned); // Now check that alice doesn't receive a message from Bob libjami::sendMessage(bobId, convId, "hi"s, ""); CPPUNIT_ASSERT(!cv.wait_for(lk, 30s, [&]() { return aliceMsgSize + 4 == aliceData.messages.size(); })); } void ConversationMembersEventTest::testAdminCanReAddMember() { connectSignals(); auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto aliceUri = aliceAccount->getUsername(); auto bobUri = bobAccount->getUsername(); auto convId = libjami::startConversation(aliceId); libjami::addConversationMember(aliceId, convId, bobUri); CPPUNIT_ASSERT( cv.wait_for(lk, 30s, [&]() { return bobData.requestReceived; })); auto aliceMsgSize = aliceData.messages.size(); libjami::acceptConversationRequest(bobId, convId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return aliceMsgSize + 1 == aliceData.messages.size(); })); // Now check that alice, has the only admin, can remove bob libjami::removeConversationMember(aliceId, convId, bobUri); CPPUNIT_ASSERT( cv.wait_for(lk, 30s, [&]() { return aliceMsgSize + 3 == aliceData.messages.size(); })); auto members = libjami::getConversationMembers(aliceId, convId); auto bobBanned = false; for (auto& member : members) { if (member["uri"] == bobUri) bobBanned = member["role"] == "banned"; } CPPUNIT_ASSERT(bobBanned); // Then check that bobUri can be re-added aliceMsgSize = aliceData.messages.size(); libjami::addConversationMember(aliceId, convId, bobUri); CPPUNIT_ASSERT( cv.wait_for(lk, 30s, [&]() { return aliceMsgSize + 2 == aliceData.messages.size(); })); members = libjami::getConversationMembers(aliceId, convId); CPPUNIT_ASSERT(members.size() == 2); } void ConversationMembersEventTest::testMemberCannotBanOther() { connectSignals(); auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto bobUri = bobAccount->getUsername(); auto convId = libjami::startConversation(aliceId); auto carlaAccount = Manager::instance().getAccount<JamiAccount>(carlaId); auto carlaUri = carlaAccount->getUsername(); aliceAccount->trackBuddyPresence(carlaUri, true); Manager::instance().sendRegister(carlaId, true); CPPUNIT_ASSERT(cv.wait_for(lk, 60s, [&] { return carlaData.deviceAnnounced; })); libjami::addConversationMember(aliceId, convId, bobUri); CPPUNIT_ASSERT( cv.wait_for(lk, 30s, [&]() { return bobData.requestReceived; })); libjami::acceptConversationRequest(bobId, convId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return !bobData.conversationId.empty() && aliceData.members[bobUri] == 1; })); libjami::addConversationMember(aliceId, convId, carlaUri); CPPUNIT_ASSERT( cv.wait_for(lk, 30s, [&]() { return aliceData.members.find(carlaUri) != aliceData.members.end() && bobData.members.find(carlaUri) != bobData.members.end() && carlaData.requestReceived; })); libjami::acceptConversationRequest(carlaId, convId); CPPUNIT_ASSERT( cv.wait_for(lk, 30s, [&]() { return !carlaData.conversationId.empty() && aliceData.members[carlaUri] == 1 && bobData.members[carlaUri] == 1; })); // Now Carla remove Bob as a member // remove from member & add into banned without voting for the ban simulateRemoval(carlaAccount, convId, bobUri); // Note: it may be possible that alice doesn't get the error if they got messages from bob (and bob rejects due to an error) CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return aliceData.errorDetected || bobData.errorDetected; })); auto bobMsgSize = bobData.messages.size(); libjami::sendMessage(aliceId, convId, "hi"s, ""); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobMsgSize + 1 == bobData.messages.size(); })); } void ConversationMembersEventTest::testMemberCannotUnBanOther() { connectSignals(); auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto bobUri = bobAccount->getUsername(); auto convId = libjami::startConversation(aliceId); auto carlaAccount = Manager::instance().getAccount<JamiAccount>(carlaId); auto carlaUri = carlaAccount->getUsername(); aliceAccount->trackBuddyPresence(carlaUri, true); Manager::instance().sendRegister(carlaId, true); CPPUNIT_ASSERT(cv.wait_for(lk, 60s, [&] { return carlaData.deviceAnnounced; })); libjami::addConversationMember(aliceId, convId, bobUri); CPPUNIT_ASSERT( cv.wait_for(lk, 30s, [&]() { return bobData.requestReceived; })); auto aliceMsgSize = aliceData.messages.size(); libjami::acceptConversationRequest(bobId, convId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return aliceMsgSize + 1 == aliceData.messages.size(); })); libjami::addConversationMember(aliceId, convId, carlaUri); CPPUNIT_ASSERT( cv.wait_for(lk, 30s, [&]() { return carlaData.requestReceived; })); aliceMsgSize = aliceData.messages.size(); libjami::acceptConversationRequest(carlaId, convId); CPPUNIT_ASSERT( cv.wait_for(lk, 30s, [&]() { return !carlaData.conversationId.empty() && aliceData.members[carlaUri] == 1 && bobData.members[carlaUri] == 1; })); std::this_thread::sleep_for(3s); // Wait that carla finish the clone // Now check that alice, has the only admin, can remove bob libjami::removeConversationMember(aliceId, convId, bobUri); CPPUNIT_ASSERT( cv.wait_for(lk, 30s, [&]() { return aliceData.members[bobUri] == 3 && carlaData.members[bobUri] == 3; })); libjami::addConversationMember(carlaId, convId, bobUri); CPPUNIT_ASSERT( !cv.wait_for(lk, 10s, [&]() { return aliceData.members[bobUri] == 1 && carlaData.members[bobUri] == 1; })); auto members = libjami::getConversationMembers(aliceId, convId); auto bobBanned = false; for (auto& member : members) { if (member["uri"] == bobUri) bobBanned = member["role"] == "banned"; } CPPUNIT_ASSERT(bobBanned); } void ConversationMembersEventTest::testCheckAdminFakeAVoteIsDetected() { connectSignals(); auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto bobUri = bobAccount->getUsername(); auto convId = libjami::startConversation(aliceId); auto carlaAccount = Manager::instance().getAccount<JamiAccount>(carlaId); auto carlaUri = carlaAccount->getUsername(); aliceAccount->trackBuddyPresence(carlaUri, true); Manager::instance().sendRegister(carlaId, true); CPPUNIT_ASSERT(cv.wait_for(lk, 60s, [&] { return carlaData.deviceAnnounced; })); libjami::addConversationMember(aliceId, convId, bobUri); CPPUNIT_ASSERT( cv.wait_for(lk, 30s, [&]() { return bobData.requestReceived; })); auto aliceMsgSize = aliceData.messages.size(); libjami::acceptConversationRequest(bobId, convId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return aliceMsgSize + 1 == aliceData.messages.size(); })); libjami::addConversationMember(aliceId, convId, carlaUri); CPPUNIT_ASSERT( cv.wait_for(lk, 30s, [&]() { return carlaData.requestReceived; })); aliceMsgSize = aliceData.messages.size(); auto bobMsgSize = bobData.messages.size(); libjami::acceptConversationRequest(carlaId, convId); CPPUNIT_ASSERT( cv.wait_for(lk, 30s, [&]() { return aliceMsgSize + 1 == aliceData.messages.size() && bobMsgSize + 1 == bobData.messages.size(); })); // Now Alice remove Carla without a vote. Bob will not receive the message simulateRemoval(aliceAccount, convId, carlaUri); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.errorDetected; })); } void ConversationMembersEventTest::testAdminCannotKickTheirself() { connectSignals(); auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto aliceUri = aliceAccount->getUsername(); auto convId = libjami::startConversation(aliceId); auto members = libjami::getConversationMembers(aliceId, convId); CPPUNIT_ASSERT(members.size() == 1); libjami::removeConversationMember(aliceId, convId, aliceUri); members = libjami::getConversationMembers(aliceId, convId); CPPUNIT_ASSERT(members.size() == 1); } void ConversationMembersEventTest::testCommitUnauthorizedUser() { connectSignals(); auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto carlaAccount = Manager::instance().getAccount<JamiAccount>(carlaId); auto bobUri = bobAccount->getUsername(); auto convId = libjami::startConversation(aliceId); libjami::addConversationMember(aliceId, convId, bobUri); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.requestReceived; })); auto aliceMsgSize = aliceData.messages.size(); libjami::acceptConversationRequest(bobId, convId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return aliceMsgSize + 1 == aliceData.messages.size();; })); // Assert that repository exists auto repoPath = fileutils::get_data_dir() / bobId / "conversations" / convId; CPPUNIT_ASSERT(std::filesystem::is_directory(repoPath)); // Add commit from invalid user Json::Value root; root["type"] = "text/plain"; root["body"] = "hi"; Json::StreamWriterBuilder wbuilder; wbuilder["commentStyle"] = "None"; wbuilder["indentation"] = ""; auto message = Json::writeString(wbuilder, root); commitInRepo(repoPath, carlaAccount, message); libjami::sendMessage(bobId, convId, "hi"s, ""); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return aliceData.errorDetected; })); } void ConversationMembersEventTest::testMemberJoinsNoBadFile() { connectSignals(); auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto carlaAccount = Manager::instance().getAccount<JamiAccount>(carlaId); auto carlaUri = carlaAccount->getUsername(); aliceAccount->trackBuddyPresence(carlaUri, true); auto convId = libjami::startConversation(aliceId); auto aliceMsgSize = aliceData.messages.size(); aliceAccount->convModule()->addConversationMember(convId, dht::InfoHash(carlaUri), false); CPPUNIT_ASSERT(cv.wait_for(lk, 5s, [&] { return aliceMsgSize + 1 == aliceData.messages.size(); })); // Cp conversations & convInfo auto repoPathAlice = fileutils::get_data_dir() / aliceId / "conversations"; auto repoPathCarla = fileutils::get_data_dir() / carlaId / "conversations"; std::filesystem::copy(repoPathAlice, repoPathCarla, std::filesystem::copy_options::recursive); auto ciPathAlice = fileutils::get_data_dir() / aliceId / "convInfo"; auto ciPathCarla = fileutils::get_data_dir() / carlaId / "convInfo"; std::remove(ciPathCarla.c_str()); std::filesystem::copy(ciPathAlice, ciPathCarla); // Accept for alice and makes different heads addFile(carlaAccount, convId, "BADFILE"); // add /members + /devices auto cert = carlaAccount->identity().second; auto parentCert = cert->issuer; auto uri = parentCert->getId().toString(); auto membersPath = repoPathCarla / convId / "members"; auto devicesPath = repoPathCarla / convId / "devices"; auto memberFile = membersPath / fmt::format("{}.crt", carlaUri); // Add members/uri.crt dhtnet::fileutils::recursive_mkdir(membersPath, 0700); dhtnet::fileutils::recursive_mkdir(devicesPath, 0700); std::ofstream file(memberFile, std::ios::trunc | std::ios::binary); file << parentCert->toString(true); file.close(); auto invitedPath = repoPathCarla / convId / "invited" / carlaUri; dhtnet::fileutils::remove(invitedPath); auto devicePath = devicesPath / fmt::format("{}.crt", carlaAccount->currentDeviceId()); file = std::ofstream(devicePath, std::ios::trunc | std::ios::binary); file << cert->toString(false); addAll(carlaAccount, convId); ConversationRepository repo(carlaAccount, convId); // Start Carla, should merge and all messages should be there carlaAccount->convModule()->loadConversations(); // Because of the copy Manager::instance().sendRegister(carlaId, true); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&] { return carlaData.deviceAnnounced; })); libjami::sendMessage(carlaId, convId, "hi"s, ""); CPPUNIT_ASSERT(cv.wait_for(lk, 60s, [&] { return aliceData.errorDetected; })); } void ConversationMembersEventTest::testMemberAddedNoCertificate() { connectSignals(); auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto carlaAccount = Manager::instance().getAccount<JamiAccount>(carlaId); auto carlaUri = carlaAccount->getUsername(); aliceAccount->trackBuddyPresence(carlaUri, true); auto convId = libjami::startConversation(aliceId); auto aliceMsgSize = aliceData.messages.size(); aliceAccount->convModule()->addConversationMember(convId, dht::InfoHash(carlaUri), false); CPPUNIT_ASSERT(cv.wait_for(lk, 5s, [&] { return aliceMsgSize + 1 == aliceData.messages.size(); })); // Cp conversations & convInfo auto repoPathAlice = fileutils::get_data_dir() / aliceId / "conversations"; auto repoPathCarla = fileutils::get_data_dir() / carlaId / "conversations"; std::filesystem::copy(repoPathAlice, repoPathCarla, std::filesystem::copy_options::recursive); auto ciPathAlice = fileutils::get_data_dir() / aliceId / "convInfo"; auto ciPathCarla = fileutils::get_data_dir() / carlaId / "convInfo"; std::remove(ciPathCarla.c_str()); std::filesystem::copy(ciPathAlice, ciPathCarla); // Remove invite but do not add member certificate std::string invitedPath = repoPathCarla / "invited"; dhtnet::fileutils::remove(fileutils::getFullPath(invitedPath, carlaUri)); Json::Value json; json["action"] = "join"; json["uri"] = carlaUri; json["type"] = "member"; Json::StreamWriterBuilder wbuilder; wbuilder["commentStyle"] = "None"; wbuilder["indentation"] = ""; ConversationRepository cr(carlaAccount, convId); cr.commitMessage(Json::writeString(wbuilder, json), false); // Start Carla, should merge and all messages should be there carlaAccount->convModule()->loadConversations(); // Because of the copy Manager::instance().sendRegister(carlaId, true); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&] { return carlaData.deviceAnnounced; })); libjami::sendMessage(carlaId, convId, "hi"s, ""); CPPUNIT_ASSERT(cv.wait_for(lk, 60s, [&] { return aliceData.errorDetected; })); } void ConversationMembersEventTest::testMemberJoinsInviteRemoved() { connectSignals(); auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto carlaAccount = Manager::instance().getAccount<JamiAccount>(carlaId); auto carlaUri = carlaAccount->getUsername(); aliceAccount->trackBuddyPresence(carlaUri, true); auto convId = libjami::startConversation(aliceId); auto aliceMsgSize = aliceData.messages.size(); aliceAccount->convModule()->addConversationMember(convId, dht::InfoHash(carlaUri), false); CPPUNIT_ASSERT(cv.wait_for(lk, 5s, [&] { return aliceMsgSize + 1 == aliceData.messages.size(); })); // Cp conversations & convInfo auto repoPathAlice = fileutils::get_data_dir() / aliceId / "conversations"; auto repoPathCarla = fileutils::get_data_dir() / carlaId / "conversations"; std::filesystem::copy(repoPathAlice, repoPathCarla, std::filesystem::copy_options::recursive); auto ciPathAlice = fileutils::get_data_dir() / aliceId / "convInfo"; auto ciPathCarla = fileutils::get_data_dir() / carlaId / "convInfo"; std::remove(ciPathCarla.c_str()); std::filesystem::copy(ciPathAlice, ciPathCarla); // add /members + /devices auto cert = carlaAccount->identity().second; auto parentCert = cert->issuer; auto uri = parentCert->getId().toString(); auto membersPath = repoPathCarla / convId / "members"; auto devicesPath = repoPathCarla / convId / "devices"; auto memberFile = membersPath / fmt::format("{}.crt", carlaUri); // Add members/uri.crt dhtnet::fileutils::recursive_mkdir(membersPath, 0700); dhtnet::fileutils::recursive_mkdir(devicesPath, 0700); std::ofstream file(memberFile, std::ios::trunc | std::ios::binary); file << parentCert->toString(true); file.close(); auto devicePath = devicesPath / fmt::format("{}.crt", carlaAccount->currentDeviceId()); file = std::ofstream(devicePath, std::ios::trunc | std::ios::binary); file << cert->toString(false); addAll(carlaAccount, convId); Json::Value json; json["action"] = "join"; json["uri"] = carlaUri; json["type"] = "member"; commit(carlaAccount, convId, json); // Start Carla, should merge and all messages should be there carlaAccount->convModule()->loadConversations(); // Because of the copy Manager::instance().sendRegister(carlaId, true); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&] { return carlaData.deviceAnnounced; })); libjami::sendMessage(carlaId, convId, "hi"s, ""); CPPUNIT_ASSERT(cv.wait_for(lk, 60s, [&] { return aliceData.errorDetected; })); } void ConversationMembersEventTest::testFailAddMemberInOneToOne() { connectSignals(); auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto carlaAccount = Manager::instance().getAccount<JamiAccount>(carlaId); auto bobUri = bobAccount->getUsername(); auto carlaUri = carlaAccount->getUsername(); aliceAccount->addContact(bobUri); aliceAccount->sendTrustRequest(bobUri, {}); CPPUNIT_ASSERT(cv.wait_for(lk, 5s, [&]() { return bobData.requestReceived; })); auto aliceMsgSize = aliceData.messages.size(); libjami::addConversationMember(aliceId, aliceData.conversationId, carlaUri); CPPUNIT_ASSERT(!cv.wait_for(lk, 5s, [&]() { return aliceMsgSize + 1 == aliceData.messages.size(); })); } void ConversationMembersEventTest::testOneToOneFetchWithNewMemberRefused() { connectSignals(); auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto carlaAccount = Manager::instance().getAccount<JamiAccount>(carlaId); auto bobUri = bobAccount->getUsername(); auto aliceUri = aliceAccount->getUsername(); auto carlaUri = carlaAccount->getUsername(); aliceAccount->addContact(bobUri); aliceAccount->sendTrustRequest(bobUri, {}); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.requestReceived; })); auto aliceMsgSize = aliceData.messages.size(); CPPUNIT_ASSERT(bobAccount->acceptTrustRequest(aliceUri)); CPPUNIT_ASSERT( cv.wait_for(lk, 30s, [&]() { return aliceMsgSize + 1 == aliceData.messages.size();; })); // NOTE: Add certificate because no DHT lookup aliceAccount->certStore().pinCertificate(carlaAccount->identity().second); generateFakeInvite(aliceAccount, aliceData.conversationId, carlaUri); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.errorDetected; })); } void ConversationMembersEventTest::testConversationMemberEvent() { connectSignals(); auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto bobUri = bobAccount->getUsername(); auto convId = libjami::startConversation(aliceId); libjami::addConversationMember(aliceId, convId, bobUri); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.requestReceived; })); // Assert that repository exists auto repoPath = fileutils::get_data_dir() / aliceId / "conversations" / convId; CPPUNIT_ASSERT(std::filesystem::is_directory(repoPath)); // Check created files auto bobInvited = repoPath / "invited" / bobUri; CPPUNIT_ASSERT(std::filesystem::is_regular_file(bobInvited)); libjami::acceptConversationRequest(bobId, convId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return !bobData.conversationId.empty(); })); auto clonedPath = fileutils::get_data_dir() / bobId / "conversations" / convId; CPPUNIT_ASSERT(std::filesystem::is_directory(clonedPath)); bobInvited = clonedPath / "invited" / bobUri; CPPUNIT_ASSERT(!std::filesystem::is_regular_file(bobInvited)); auto bobMember = clonedPath / "members" / (bobUri + ".crt"); CPPUNIT_ASSERT(std::filesystem::is_regular_file(bobMember)); } void ConversationMembersEventTest::testGetConversationsMembersWhileSyncing() { connectSignals(); auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto bobUri = bobAccount->getUsername(); auto aliceUri = aliceAccount->getUsername(); aliceAccount->addContact(bobUri); aliceAccount->sendTrustRequest(bobUri, {}); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.requestReceived; })); Manager::instance().sendRegister(aliceId, false); // This avoid to sync immediately CPPUNIT_ASSERT(bobAccount->acceptTrustRequest(aliceUri)); auto members = libjami::getConversationMembers(bobId, aliceData.conversationId); CPPUNIT_ASSERT(std::find_if(members.begin(), members.end(), [&](auto memberInfo) { return memberInfo["uri"] == aliceUri; }) != members.end()); CPPUNIT_ASSERT(std::find_if(members.begin(), members.end(), [&](auto memberInfo) { return memberInfo["uri"] == bobUri; }) != members.end()); } void ConversationMembersEventTest::testGetConversationMembersWithSelfOneOne() { connectSignals(); auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto aliceUri = aliceAccount->getUsername(); std::map<std::string, std::shared_ptr<libjami::CallbackWrapperBase>> confHandlers; std::string convId = ""; confHandlers.insert(libjami::exportable_callback<libjami::ConversationSignal::ConversationReady>( [&](const std::string& accountId, const std::string& conversationId) { if (accountId == aliceId) convId = conversationId; cv.notify_one(); })); libjami::registerSignalHandlers(confHandlers); aliceAccount->addContact(aliceUri); CPPUNIT_ASSERT(cv.wait_for(lk, 5s, [&]() { return !convId.empty(); })); auto members = libjami::getConversationMembers(aliceId, convId); CPPUNIT_ASSERT(members.size() == 1); CPPUNIT_ASSERT(members[0]["uri"] == aliceUri); } void ConversationMembersEventTest::testAvoidTwoOneToOne() { connectSignals(); auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto bobUri = bobAccount->getUsername(); auto aliceUri = aliceAccount->getUsername(); // Alice adds bob aliceAccount->addContact(bobUri); aliceAccount->sendTrustRequest(bobUri, {}); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.requestReceived; })); auto aliceMsgSize = aliceData.messages.size(); libjami::acceptConversationRequest(bobId, aliceData.conversationId); CPPUNIT_ASSERT( cv.wait_for(lk, 30s, [&]() { return aliceData.messages.size() == aliceMsgSize + 1; })); // Remove contact bobAccount->removeContact(aliceUri, false); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.removed; })); // wait that connections are closed. std::this_thread::sleep_for(10s); // Bob add Alice, this should re-add old conversation bobAccount->addContact(aliceUri); bobAccount->sendTrustRequest(aliceUri, {}); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.conversationId == aliceData.conversationId; })); } void ConversationMembersEventTest::testAvoidTwoOneToOneMultiDevices() { connectSignals(); auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto bobUri = bobAccount->getUsername(); auto aliceUri = aliceAccount->getUsername(); // Bob creates a second device auto bobArchive = std::filesystem::current_path().string() + "/bob.gz"; std::remove(bobArchive.c_str()); bobAccount->exportArchive(bobArchive); std::map<std::string, std::string> details = libjami::getAccountTemplate("RING"); details[ConfProperties::TYPE] = "RING"; details[ConfProperties::DISPLAYNAME] = "BOB2"; details[ConfProperties::ALIAS] = "BOB2"; details[ConfProperties::UPNP_ENABLED] = "true"; details[ConfProperties::ARCHIVE_PASSWORD] = ""; details[ConfProperties::ARCHIVE_PIN] = ""; details[ConfProperties::ARCHIVE_PATH] = bobArchive; bob2Id = Manager::instance().addAccount(details); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bob2Data.deviceAnnounced; })); // Alice adds bob aliceAccount->addContact(bobUri); aliceAccount->sendTrustRequest(bobUri, {}); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.requestReceived && bob2Data.requestReceived; })); auto aliceMsgSize = aliceData.messages.size(); libjami::acceptConversationRequest(bobId, aliceData.conversationId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return !bobData.conversationId.empty() && !bob2Data.conversationId.empty() && aliceMsgSize + 1 == aliceData.messages.size(); })); // Remove contact bobAccount->removeContact(aliceUri, false); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.removed && bob2Data.removed; })); // wait that connections are closed. std::this_thread::sleep_for(10s); // Bob add Alice, this should re-add old conversation bobAccount->addContact(aliceUri); bobAccount->sendTrustRequest(aliceUri, {}); CPPUNIT_ASSERT( cv.wait_for(lk, 30s, [&]() { return bobData.conversationId == aliceData.conversationId && bob2Data.conversationId == aliceData.conversationId; })); } void ConversationMembersEventTest::testRemoveRequestBannedMultiDevices() { connectSignals(); auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto bobUri = bobAccount->getUsername(); auto aliceUri = aliceAccount->getUsername(); // Bob creates a second device auto bobArchive = std::filesystem::current_path().string() + "/bob.gz"; std::remove(bobArchive.c_str()); bobAccount->exportArchive(bobArchive); std::map<std::string, std::string> details = libjami::getAccountTemplate("RING"); details[ConfProperties::TYPE] = "RING"; details[ConfProperties::DISPLAYNAME] = "BOB2"; details[ConfProperties::ALIAS] = "BOB2"; details[ConfProperties::UPNP_ENABLED] = "true"; details[ConfProperties::ARCHIVE_PASSWORD] = ""; details[ConfProperties::ARCHIVE_PIN] = ""; details[ConfProperties::ARCHIVE_PATH] = bobArchive; bob2Id = Manager::instance().addAccount(details); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bob2Data.deviceAnnounced; })); // Alice adds bob aliceAccount->addContact(bobUri); aliceAccount->sendTrustRequest(bobUri, {}); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.requestReceived && bob2Data.requestReceived; })); CPPUNIT_ASSERT(libjami::getConversationRequests(bob2Id).size() == 1); // Bob bans alice, should update bob2 bobAccount->removeContact(aliceUri, true); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bob2Data.contactRemoved; })); CPPUNIT_ASSERT(libjami::getConversationRequests(bob2Id).size() == 0); } void ConversationMembersEventTest::testBanUnbanMultiDevice() { connectSignals(); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto bobUri = bobAccount->getUsername(); auto convId = libjami::startConversation(aliceId); // Bob creates a second device auto bobArchive = std::filesystem::current_path().string() + "/bob.gz"; std::remove(bobArchive.c_str()); bobAccount->exportArchive(bobArchive); std::map<std::string, std::string> details = libjami::getAccountTemplate("RING"); details[ConfProperties::TYPE] = "RING"; details[ConfProperties::DISPLAYNAME] = "BOB2"; details[ConfProperties::ALIAS] = "BOB2"; details[ConfProperties::UPNP_ENABLED] = "true"; details[ConfProperties::ARCHIVE_PASSWORD] = ""; details[ConfProperties::ARCHIVE_PIN] = ""; details[ConfProperties::ARCHIVE_PATH] = bobArchive; bob2Id = Manager::instance().addAccount(details); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bob2Data.deviceAnnounced; })); // Alice adds bob libjami::addConversationMember(aliceId, convId, bobUri); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.requestReceived && bob2Data.requestReceived; })); // Alice kick Bob while invited auto aliceMsgSize = aliceData.messages.size(); libjami::removeConversationMember(aliceId, convId, bobUri); CPPUNIT_ASSERT( cv.wait_for(lk, 30s, [&]() { return aliceMsgSize + 2 == aliceData.messages.size(); })); // Alice re-add Bob while invited aliceMsgSize = aliceData.messages.size(); libjami::addConversationMember(aliceId, convId, bobUri); CPPUNIT_ASSERT( cv.wait_for(lk, 30s, [&]() { return aliceMsgSize + 2 == aliceData.messages.size(); })); // bob accepts libjami::acceptConversationRequest(bobId, convId); CPPUNIT_ASSERT( cv.wait_for(lk, 30s, [&]() { return bobData.conversationId == aliceData.conversationId && bob2Data.conversationId == aliceData.conversationId; })); } void ConversationMembersEventTest::testBanUnbanGotFirstConv() { connectSignals(); auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto bobUri = bobAccount->getUsername(); auto aliceUri = aliceAccount->getUsername(); // Bob creates a second device auto bobArchive = std::filesystem::current_path().string() + "/bob.gz"; std::remove(bobArchive.c_str()); bobAccount->exportArchive(bobArchive); std::map<std::string, std::string> details = libjami::getAccountTemplate("RING"); details[ConfProperties::TYPE] = "RING"; details[ConfProperties::DISPLAYNAME] = "BOB2"; details[ConfProperties::ALIAS] = "BOB2"; details[ConfProperties::UPNP_ENABLED] = "true"; details[ConfProperties::ARCHIVE_PASSWORD] = ""; details[ConfProperties::ARCHIVE_PIN] = ""; details[ConfProperties::ARCHIVE_PATH] = bobArchive; bob2Id = Manager::instance().addAccount(details); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bob2Data.deviceAnnounced; })); // Alice adds bob aliceAccount->addContact(bobUri); aliceAccount->sendTrustRequest(bobUri, {}); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.requestReceived && bob2Data.requestReceived; })); CPPUNIT_ASSERT(libjami::getConversationRequests(bob2Id).size() == 1); // Accepts requests auto aliceMsgSize = aliceData.messages.size(); libjami::acceptConversationRequest(bobId, aliceData.conversationId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return !bobData.conversationId.empty() && !bob2Data.conversationId.empty() && aliceMsgSize + 1 == aliceData.messages.size(); })); bobAccount->removeContact(aliceUri, true); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.contactRemoved && bob2Data.contactRemoved; })); // Alice sends messages, bob & bob2 should not get it! aliceMsgSize = aliceData.messages.size(); libjami::sendMessage(aliceId, aliceData.conversationId, "hi"s, ""); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return aliceMsgSize != aliceData.messages.size(); })); auto msgId = aliceData.messages.rbegin()->id; auto getMessage = [](const auto& data, const auto& mid) -> bool { return std::find_if(data.messages.begin(), data.messages.end(), [&](auto& msg) { return msg.id == mid; }) != data.messages.end(); }; // Connection MUST fail CPPUNIT_ASSERT(!cv.wait_for(lk, 20s, [&]() { return getMessage(bobData, msgId) && getMessage(bob2Data, msgId); })); // Bobs re-add Alice bobData.contactAdded = false; bob2Data.contactAdded = false; bobAccount->addContact(aliceUri); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.contactAdded && bob2Data.contactAdded && bobData.conversationId == bob2Data.conversationId && bobData.conversationId == aliceData.conversationId; })); } void ConversationMembersEventTest::testBanHostWhileHosting() { connectSignals(); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto bobUri = bobAccount->getUsername(); auto convId = libjami::startConversation(aliceId); libjami::addConversationMember(aliceId, convId, bobUri); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.requestReceived; })); auto aliceMsgSize = aliceData.messages.size(); libjami::acceptConversationRequest(bobId, convId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return aliceMsgSize + 1 == aliceData.messages.size(); })); // Now, Bob starts a call aliceMsgSize = aliceData.messages.size(); auto callId = libjami::placeCallWithMedia(bobId, "swarm:" + convId, {}); // should get message CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return aliceMsgSize != aliceData.messages.size(); })); // get active calls = 1 CPPUNIT_ASSERT(libjami::getActiveCalls(aliceId, convId).size() == 1); // Now check that alice, has the only admin, can remove bob aliceMsgSize = aliceData.messages.size(); libjami::removeConversationMember(aliceId, convId, bobUri); CPPUNIT_ASSERT( cv.wait_for(lk, 30s, [&]() { return aliceMsgSize + 2 == aliceData.messages.size(); })); auto members = libjami::getConversationMembers(aliceId, convId); auto bobBanned = false; for (auto& member : members) { if (member["uri"] == bobUri) bobBanned = member["role"] == "banned"; } CPPUNIT_ASSERT(bobBanned); } void ConversationMembersEventTest::testAddContactTwice() { connectSignals(); std::cout << "\nRunning test: " << __func__ << std::endl; auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto aliceUri = aliceAccount->getUsername(); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto bobUri = bobAccount->getUsername(); // Add contact aliceAccount->addContact(bobUri); aliceAccount->sendTrustRequest(bobUri, {}); CPPUNIT_ASSERT(cv.wait_for(lk, 10s, [&]() { return bobData.requestReceived; })); auto oldConversationId = aliceData.conversationId; CPPUNIT_ASSERT(!oldConversationId.empty()); // Check that the trust request's data is correct auto bobTrustRequests = bobAccount->getTrustRequests(); CPPUNIT_ASSERT(bobTrustRequests.size() == 1); auto request = bobTrustRequests[0]; CPPUNIT_ASSERT(request["from"] == aliceUri); CPPUNIT_ASSERT(request["conversationId"] == oldConversationId); // Remove and re-add contact aliceAccount->removeContact(bobUri, false); CPPUNIT_ASSERT(cv.wait_for(lk, 10s, [&]() { return aliceData.removed; })); // wait that connections are closed. std::this_thread::sleep_for(10s); bobData.requestReceived = false; aliceAccount->addContact(bobUri); aliceAccount->sendTrustRequest(bobUri, {}); CPPUNIT_ASSERT(cv.wait_for(lk, 10s, [&]() { return bobData.requestRemoved && bobData.requestReceived; })); auto newConversationId = aliceData.conversationId; CPPUNIT_ASSERT(!newConversationId.empty()); CPPUNIT_ASSERT(newConversationId != oldConversationId); // Check that the trust request's data was correctly // updated when we received the second request bobTrustRequests = bobAccount->getTrustRequests(); CPPUNIT_ASSERT(bobTrustRequests.size() == 1); request = bobTrustRequests[0]; CPPUNIT_ASSERT(request["from"] == aliceUri); CPPUNIT_ASSERT(request["conversationId"] == newConversationId); } void ConversationMembersEventTest::testBanFromNewDevice() { connectSignals(); auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto carlaAccount = Manager::instance().getAccount<JamiAccount>(carlaId); auto aliceUri = aliceAccount->getUsername(); auto bobUri = bobAccount->getUsername(); auto carlaUri = carlaAccount->getUsername(); Manager::instance().sendRegister(carlaId, true); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&] { return carlaData.deviceAnnounced; })); auto convId = libjami::startConversation(bobId); libjami::addConversationMember(bobId, convId, aliceUri); libjami::addConversationMember(bobId, convId, carlaUri); CPPUNIT_ASSERT(cv.wait_for(lk, 60s, [&] { return carlaData.requestReceived; })); libjami::acceptConversationRequest(carlaId, convId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return !carlaData.conversationId.empty(); })); Manager::instance().sendRegister(carlaId, false); // Bob creates a second device auto bobArchive = std::filesystem::current_path().string() + "/bob.gz"; std::remove(bobArchive.c_str()); bobAccount->exportArchive(bobArchive); std::map<std::string, std::string> details = libjami::getAccountTemplate("RING"); details[ConfProperties::TYPE] = "RING"; details[ConfProperties::DISPLAYNAME] = "BOB2"; details[ConfProperties::ALIAS] = "BOB2"; details[ConfProperties::UPNP_ENABLED] = "true"; details[ConfProperties::ARCHIVE_PASSWORD] = ""; details[ConfProperties::ARCHIVE_PIN] = ""; details[ConfProperties::ARCHIVE_PATH] = bobArchive; bob2Id = Manager::instance().addAccount(details); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bob2Data.deviceAnnounced; })); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return !bob2Data.conversationId.empty(); })); auto bobMsgSize = bobData.messages.size(); libjami::removeConversationMember(bob2Id, convId, aliceUri); CPPUNIT_ASSERT( cv.wait_for(lk, 30s, [&]() { return bobData.messages.size() == bobMsgSize + 2 /* vote + ban */; })); Manager::instance().sendRegister(bob2Id, false); auto carlaMsgSize = carlaData.messages.size(); Manager::instance().sendRegister(carlaId, true); // Should sync! CPPUNIT_ASSERT( cv.wait_for(lk, 30s, [&]() { return carlaData.messages.size() > carlaMsgSize; })); } } // namespace test } // namespace jami RING_TEST_RUNNER(jami::test::ConversationMembersEventTest::name())
80,092
C++
.cpp
1,584
43.738005
172
0.682857
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,665
conversationcommon.cpp
savoirfairelinux_jami-daemon/test/unitTest/conversation/conversationcommon.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <cppunit/TestAssert.h> #include <cppunit/TestFixture.h> #include <cppunit/extensions/HelperMacros.h> #include <yaml-cpp/yaml.h> #include <filesystem> #include "common.h" /* Jami */ #include "account_const.h" #include "base64.h" #include "jami.h" #include "fileutils.h" #include "manager.h" #include "jamidht/conversation.h" #include "jamidht/conversationrepository.h" #include "conversation/conversationcommon.h" using namespace std::string_literals; /* Make GCC quiet about unused functions */ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-function" namespace jami { void addVote(std::shared_ptr<JamiAccount> account, const std::string& convId, const std::string& votedUri, const std::string& content) { ConversationRepository::DISABLE_RESET = true; auto repoPath = fileutils::get_data_dir() / account->getAccountID() / "conversations" / convId; auto voteDirectory = repoPath / "votes" / "members"; auto voteFile = voteDirectory / votedUri; if (!dhtnet::fileutils::recursive_mkdir(voteDirectory, 0700)) { return; } std::ofstream file(voteFile); if (file.is_open()) { file << content; file.close(); } Json::Value json; json["uri"] = votedUri; json["type"] = "vote"; Json::StreamWriterBuilder wbuilder; wbuilder["commentStyle"] = "None"; wbuilder["indentation"] = ""; ConversationRepository cr(account, convId); cr.commitMessage(Json::writeString(wbuilder, json), false); } void simulateRemoval(std::shared_ptr<JamiAccount> account, const std::string& convId, const std::string& votedUri) { ConversationRepository::DISABLE_RESET = true; auto repoPath = fileutils::get_data_dir() / account->getAccountID() / "conversations" / convId; auto memberFile = repoPath / "members" / (votedUri + ".crt"); auto bannedFile = repoPath / "banned" / "members" / (votedUri + ".crt"); std::rename(memberFile.c_str(), bannedFile.c_str()); git_repository* repo = nullptr; if (git_repository_open(&repo, repoPath.c_str()) != 0) return; GitRepository rep = {std::move(repo), git_repository_free}; // git add -A git_index* index_ptr = nullptr; if (git_repository_index(&index_ptr, repo) < 0) return; GitIndex index {index_ptr, git_index_free}; git_strarray array = {nullptr, 0}; git_index_add_all(index.get(), &array, 0, nullptr, nullptr); git_index_write(index.get()); git_strarray_dispose(&array); ConversationRepository cr(account, convId); Json::Value json; json["action"] = "ban"; json["uri"] = votedUri; json["type"] = "member"; Json::StreamWriterBuilder wbuilder; wbuilder["commentStyle"] = "None"; wbuilder["indentation"] = ""; cr.commitMessage(Json::writeString(wbuilder, json)); libjami::sendMessage(account->getAccountID(), convId, "trigger the fake history to be pulled"s, ""); } void addFile(std::shared_ptr<JamiAccount> account, const std::string& convId, const std::string& relativePath, const std::string& content) { ConversationRepository::DISABLE_RESET = true; auto repoPath = fileutils::get_data_dir() / account->getAccountID() / "conversations" / convId; // Add file auto p = std::filesystem::path(fileutils::getFullPath(repoPath, relativePath)); dhtnet::fileutils::recursive_mkdir(p.parent_path()); std::ofstream file(p); if (file.is_open()) { file << content; file.close(); } git_repository* repo = nullptr; if (git_repository_open(&repo, repoPath.c_str()) != 0) return; GitRepository rep = {std::move(repo), git_repository_free}; // git add -A git_index* index_ptr = nullptr; if (git_repository_index(&index_ptr, repo) < 0) return; GitIndex index {index_ptr, git_index_free}; git_strarray array = {nullptr, 0}; git_index_add_all(index.get(), &array, 0, nullptr, nullptr); git_index_write(index.get()); git_strarray_dispose(&array); } void addAll(std::shared_ptr<JamiAccount> account, const std::string& convId) { ConversationRepository::DISABLE_RESET = true; auto repoPath = fileutils::get_data_dir() / account->getAccountID() / "conversations" / convId; git_repository* repo = nullptr; if (git_repository_open(&repo, repoPath.c_str()) != 0) return; GitRepository rep = {std::move(repo), git_repository_free}; // git add -A git_index* index_ptr = nullptr; if (git_repository_index(&index_ptr, repo) < 0) return; GitIndex index {index_ptr, git_index_free}; git_strarray array = {nullptr, 0}; git_index_add_all(index.get(), &array, 0, nullptr, nullptr); git_index_write(index.get()); git_strarray_dispose(&array); } void commit(std::shared_ptr<JamiAccount> account, const std::string& convId, Json::Value& message) { ConversationRepository::DISABLE_RESET = true; ConversationRepository cr(account, convId); Json::StreamWriterBuilder wbuilder; wbuilder["commentStyle"] = "None"; wbuilder["indentation"] = ""; cr.commitMessage(Json::writeString(wbuilder, message)); } std::string commitInRepo(const std::string& path, std::shared_ptr<JamiAccount> account, const std::string& msg) { ConversationRepository::DISABLE_RESET = true; auto deviceId = std::string(account->currentDeviceId()); auto name = account->getDisplayName(); if (name.empty()) name = deviceId; git_signature* sig_ptr = nullptr; // Sign commit's buffer if (git_signature_new(&sig_ptr, name.c_str(), deviceId.c_str(), std::time(nullptr), 0) < 0) { JAMI_ERROR("Unable to create a commit signature."); return {}; } GitSignature sig {sig_ptr, git_signature_free}; // Retrieve current index git_index* index_ptr = nullptr; git_repository* repo = nullptr; // TODO share this repo with GitServer if (git_repository_open(&repo, path.c_str()) != 0) { JAMI_ERROR("Unable to open repository"); return {}; } if (git_repository_index(&index_ptr, repo) < 0) { JAMI_ERROR("Unable to open repository index"); return {}; } GitIndex index {index_ptr, git_index_free}; git_oid tree_id; if (git_index_write_tree(&tree_id, index.get()) < 0) { JAMI_ERROR("Unable to write initial tree from index"); return {}; } git_tree* tree_ptr = nullptr; if (git_tree_lookup(&tree_ptr, repo, &tree_id) < 0) { JAMI_ERROR("Unable to look up initial tree"); return {}; } GitTree tree = {tree_ptr, git_tree_free}; git_oid commit_id; if (git_reference_name_to_id(&commit_id, repo, "HEAD") < 0) { JAMI_ERROR("Unable to get reference for HEAD"); return {}; } git_commit* head_ptr = nullptr; if (git_commit_lookup(&head_ptr, repo, &commit_id) < 0) { JAMI_ERROR("Unable to look up HEAD commit"); return {}; } GitCommit head_commit {head_ptr, git_commit_free}; git_buf to_sign = {}; #if( LIBGIT2_VER_MAJOR > 1 ) || ( LIBGIT2_VER_MAJOR == 1 && LIBGIT2_VER_MINOR >= 8 ) // For libgit2 version 1.8.0 and above git_commit* const head_ref[1] = {head_commit.get()}; #else // For libgit2 versions older than 1.8.0 const git_commit* head_ref[1] = {head_commit.get()}; #endif if (git_commit_create_buffer( &to_sign, repo, sig.get(), sig.get(), nullptr, msg.c_str(), tree.get(), 1, &head_ref[0]) < 0) { JAMI_ERROR("Unable to create commit buffer"); return {}; } // git commit -S auto to_sign_vec = std::vector<uint8_t>(to_sign.ptr, to_sign.ptr + to_sign.size); auto signed_buf = account->identity().first->sign(to_sign_vec); std::string signed_str = base64::encode(signed_buf); if (git_commit_create_with_signature(&commit_id, repo, to_sign.ptr, signed_str.c_str(), "signature") < 0) { const git_error* err = giterr_last(); if (err) JAMI_ERROR("Unable to sign commit: {}", err->message); return {}; } // Move commit to main branch git_reference* ref_ptr = nullptr; if (git_reference_create(&ref_ptr, repo, "refs/heads/main", &commit_id, true, nullptr) < 0) { const git_error* err = giterr_last(); if (err) JAMI_ERROR("Unable to move commit to main: {}", err->message); return {}; } git_reference_free(ref_ptr); git_repository_free(repo); auto commit_str = git_oid_tostr_s(&commit_id); if (commit_str) { JAMI_LOG("New message added with id: {}", commit_str); return commit_str; } return {}; } } // namespace jami #pragma GCC diagnostic pop
9,831
C++
.cpp
262
31.358779
100
0.636306
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,666
syncHistory.cpp
savoirfairelinux_jami-daemon/test/unitTest/syncHistory/syncHistory.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "fileutils.h" #include "manager.h" #include "jamidht/jamiaccount.h" #include "../../test_runner.h" #include "jami.h" #include "account_const.h" #include "common.h" #include <dhtnet/connectionmanager.h> #include <dhtnet/multiplexed_socket.h> #include <cppunit/TestAssert.h> #include <cppunit/TestFixture.h> #include <cppunit/extensions/HelperMacros.h> #include <chrono> #include <condition_variable> #include <filesystem> using namespace libjami::Account; using namespace std::literals::chrono_literals; namespace jami { namespace test { struct UserData { std::string conversationId; bool removed {false}; bool requestReceived {false}; bool requestRemoved {false}; bool errorDetected {false}; bool registered {false}; bool stopped {false}; bool deviceAnnounced {false}; bool sending {false}; bool sent {false}; std::string profilePath; std::string payloadTrustRequest; std::vector<libjami::SwarmMessage> messages; std::vector<libjami::SwarmMessage> messagesLoaded; std::vector<libjami::SwarmMessage> messagesUpdated; std::map<std::string, int> members; }; class SyncHistoryTest : public CppUnit::TestFixture { public: SyncHistoryTest() { // Init daemon libjami::init(libjami::InitFlag(libjami::LIBJAMI_FLAG_DEBUG | libjami::LIBJAMI_FLAG_CONSOLE_LOG)); if (not Manager::instance().initialized) CPPUNIT_ASSERT(libjami::start("jami-sample.yml")); } ~SyncHistoryTest() { libjami::fini(); } static std::string name() { return "SyncHistory"; } void setUp(); void tearDown(); std::string aliceId; UserData aliceData; std::string bobId; UserData bobData; std::string alice2Id; UserData alice2Data; std::mutex mtx; std::unique_lock<std::mutex> lk {mtx}; std::condition_variable cv; void connectSignals(); private: void testCreateConversationThenSync(); void testCreateConversationWithOnlineDevice(); void testCreateConversationWithMessagesThenAddDevice(); void testCreateMultipleConversationThenAddDevice(); void testReceivesInviteThenAddDevice(); void testRemoveConversationOnAllDevices(); void testSyncCreateAccountExportDeleteReimportOldBackup(); void testSyncCreateAccountExportDeleteReimportWithConvId(); void testSyncCreateAccountExportDeleteReimportWithConvReq(); void testSyncOneToOne(); void testConversationRequestRemoved(); void testProfileReceivedMultiDevice(); void testLastInteractionAfterClone(); void testLastInteractionAfterSomeMessages(); CPPUNIT_TEST_SUITE(SyncHistoryTest); CPPUNIT_TEST(testCreateConversationThenSync); CPPUNIT_TEST(testCreateConversationWithOnlineDevice); CPPUNIT_TEST(testCreateConversationWithMessagesThenAddDevice); CPPUNIT_TEST(testCreateMultipleConversationThenAddDevice); CPPUNIT_TEST(testReceivesInviteThenAddDevice); CPPUNIT_TEST(testRemoveConversationOnAllDevices); CPPUNIT_TEST(testSyncCreateAccountExportDeleteReimportOldBackup); CPPUNIT_TEST(testSyncCreateAccountExportDeleteReimportWithConvId); CPPUNIT_TEST(testSyncCreateAccountExportDeleteReimportWithConvReq); CPPUNIT_TEST(testSyncOneToOne); CPPUNIT_TEST(testConversationRequestRemoved); CPPUNIT_TEST(testProfileReceivedMultiDevice); CPPUNIT_TEST(testLastInteractionAfterClone); CPPUNIT_TEST(testLastInteractionAfterSomeMessages); CPPUNIT_TEST_SUITE_END(); }; CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(SyncHistoryTest, SyncHistoryTest::name()); void SyncHistoryTest::setUp() { auto actors = load_actors_and_wait_for_announcement("actors/alice-bob.yml"); aliceId = actors["alice"]; bobId = actors["bob"]; alice2Id = ""; aliceData = {}; bobData = {}; alice2Data = {}; } void SyncHistoryTest::tearDown() { auto aliceArchive = std::filesystem::current_path().string() + "/alice.gz"; std::remove(aliceArchive.c_str()); if (alice2Id.empty()) { wait_for_removal_of({aliceId, bobId}); } else { wait_for_removal_of({aliceId, bobId, alice2Id}); } } void SyncHistoryTest::connectSignals() { std::map<std::string, std::shared_ptr<libjami::CallbackWrapperBase>> confHandlers; confHandlers.insert( libjami::exportable_callback<libjami::ConfigurationSignal::VolatileDetailsChanged>( [&](const std::string& accountId, const std::map<std::string, std::string>&) { if (accountId == aliceId) { auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto details = aliceAccount->getVolatileAccountDetails(); auto daemonStatus = details[libjami::Account::ConfProperties::Registration::STATUS]; if (daemonStatus == "REGISTERED") { aliceData.registered = true; } else if (daemonStatus == "UNREGISTERED") { aliceData.stopped = true; } auto deviceAnnounced = details[libjami::Account::VolatileProperties::DEVICE_ANNOUNCED]; aliceData.deviceAnnounced = deviceAnnounced == "true"; } else if (accountId == bobId) { auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto details = bobAccount->getVolatileAccountDetails(); auto daemonStatus = details[libjami::Account::ConfProperties::Registration::STATUS]; if (daemonStatus == "REGISTERED") { bobData.registered = true; } else if (daemonStatus == "UNREGISTERED") { bobData.stopped = true; } auto deviceAnnounced = details[libjami::Account::VolatileProperties::DEVICE_ANNOUNCED]; bobData.deviceAnnounced = deviceAnnounced == "true"; } else if (accountId == alice2Id) { auto alice2Account = Manager::instance().getAccount<JamiAccount>(alice2Id); auto details = alice2Account->getVolatileAccountDetails(); auto daemonStatus = details[libjami::Account::ConfProperties::Registration::STATUS]; if (daemonStatus == "REGISTERED") { alice2Data.registered = true; } else if (daemonStatus == "UNREGISTERED") { alice2Data.stopped = true; } auto deviceAnnounced = details[libjami::Account::VolatileProperties::DEVICE_ANNOUNCED]; alice2Data.deviceAnnounced = deviceAnnounced == "true"; } cv.notify_one(); })); confHandlers.insert(libjami::exportable_callback<libjami::ConversationSignal::ConversationReady>( [&](const std::string& accountId, const std::string& conversationId) { if (accountId == aliceId) { aliceData.conversationId = conversationId; } else if (accountId == bobId) { bobData.conversationId = conversationId; } else if (accountId == alice2Id) { alice2Data.conversationId = conversationId; } cv.notify_one(); })); confHandlers.insert(libjami::exportable_callback<libjami::ConfigurationSignal::ProfileReceived>( [&](const std::string& accountId, const std::string& peerId, const std::string& path) { if (accountId == bobId) bobData.profilePath = path; else if (accountId == aliceId) aliceData.profilePath = path; else if (accountId == alice2Id) alice2Data.profilePath = path; cv.notify_one(); })); confHandlers.insert(libjami::exportable_callback<libjami::ConversationSignal::ConversationMemberEvent>( [&](const std::string& accountId, const std::string& conversationId, const auto& member, auto status) { if (accountId == aliceId) { aliceData.members[member] = status; } else if (accountId == bobId) { bobData.members[member] = status; } else if (accountId == alice2Id) { alice2Data.members[member] = status; } cv.notify_one(); })); confHandlers.insert( libjami::exportable_callback<libjami::ConfigurationSignal::AccountMessageStatusChanged>( [&](const std::string& accountId, const std::string& /*conversationId*/, const std::string& /*peer*/, const std::string& /*msgId*/, int status) { if (accountId == aliceId) { if (status == 2) aliceData.sending = true; if (status == 3) aliceData.sent = true; } else if (accountId == alice2Id) { if (status == 2) alice2Data.sending = true; if (status == 3) alice2Data.sent = true; } else if (accountId == bobId) { if (status == 2) bobData.sending = true; if (status == 3) bobData.sent = true; } cv.notify_one(); })); confHandlers.insert( libjami::exportable_callback<libjami::ConfigurationSignal::IncomingTrustRequest>( [&](const std::string& account_id, const std::string& /*from*/, const std::string& /*conversationId*/, const std::vector<uint8_t>& payload, time_t /*received*/) { auto payloadStr = std::string(payload.data(), payload.data() + payload.size()); if (account_id == aliceId) aliceData.payloadTrustRequest = payloadStr; else if (account_id == bobId) bobData.payloadTrustRequest = payloadStr; cv.notify_one(); })); confHandlers.insert( libjami::exportable_callback<libjami::ConversationSignal::ConversationRequestReceived>( [&](const std::string& accountId, const std::string& /* conversationId */, std::map<std::string, std::string> /*metadatas*/) { if (accountId == aliceId) { aliceData.requestReceived = true; } else if (accountId == bobId) { bobData.requestReceived = true; } else if (accountId == alice2Id) { alice2Data.requestReceived = true; } cv.notify_one(); })); confHandlers.insert( libjami::exportable_callback<libjami::ConversationSignal::ConversationRequestDeclined>( [&](const std::string& accountId, const std::string&) { if (accountId == bobId) { bobData.requestRemoved = true; } else if (accountId == aliceId) { aliceData.requestRemoved = true; } else if (accountId == alice2Id) { alice2Data.requestRemoved = true; } cv.notify_one(); })); confHandlers.insert(libjami::exportable_callback<libjami::ConversationSignal::SwarmMessageReceived>( [&](const std::string& accountId, const std::string& /* conversationId */, libjami::SwarmMessage message) { if (accountId == aliceId) { aliceData.messages.emplace_back(message); } else if (accountId == bobId) { bobData.messages.emplace_back(message); } else if (accountId == alice2Id) { alice2Data.messages.emplace_back(message); } cv.notify_one(); })); confHandlers.insert(libjami::exportable_callback<libjami::ConversationSignal::SwarmLoaded>( [&](uint32_t, const std::string& accountId, const std::string& /* conversationId */, std::vector<libjami::SwarmMessage> messages) { if (accountId == aliceId) { aliceData.messagesLoaded.insert(aliceData.messagesLoaded.end(), messages.begin(), messages.end()); } else if (accountId == alice2Id) { alice2Data.messagesLoaded.insert(alice2Data.messagesLoaded.end(), messages.begin(), messages.end()); } else if (accountId == bobId) { bobData.messagesLoaded.insert(bobData.messagesLoaded.end(), messages.begin(), messages.end()); } cv.notify_one(); })); confHandlers.insert(libjami::exportable_callback<libjami::ConversationSignal::SwarmMessageUpdated>( [&](const std::string& accountId, const std::string& /* conversationId */, libjami::SwarmMessage message) { if (accountId == aliceId) { aliceData.messagesUpdated.emplace_back(message); } else if (accountId == bobId) { bobData.messagesUpdated.emplace_back(message); } cv.notify_one(); })); confHandlers.insert( libjami::exportable_callback<libjami::ConversationSignal::OnConversationError>( [&](const std::string& accountId, const std::string& /* conversationId */, int /*code*/, const std::string& /* what */) { if (accountId == aliceId) aliceData.errorDetected = true; else if (accountId == bobId) bobData.errorDetected = true; cv.notify_one(); })); confHandlers.insert( libjami::exportable_callback<libjami::ConversationSignal::ConversationRemoved>( [&](const std::string& accountId, const std::string&) { if (accountId == aliceId) aliceData.removed = true; else if (accountId == bobId) bobData.removed = true; else if (accountId == alice2Id) alice2Data.removed = true; cv.notify_one(); })); libjami::registerSignalHandlers(confHandlers); } void SyncHistoryTest::testCreateConversationThenSync() { connectSignals(); auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); // Start conversation auto convId = libjami::startConversation(aliceId); // Now create alice2 auto aliceArchive = std::filesystem::current_path().string() + "/alice.gz"; aliceAccount->exportArchive(aliceArchive); std::map<std::string, std::string> details = libjami::getAccountTemplate("RING"); details[ConfProperties::TYPE] = "RING"; details[ConfProperties::DISPLAYNAME] = "ALICE2"; details[ConfProperties::ALIAS] = "ALICE2"; details[ConfProperties::UPNP_ENABLED] = "true"; details[ConfProperties::ARCHIVE_PASSWORD] = ""; details[ConfProperties::ARCHIVE_PIN] = ""; details[ConfProperties::ARCHIVE_PATH] = aliceArchive; alice2Id = Manager::instance().addAccount(details); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&] { return !alice2Data.conversationId.empty(); })); } void SyncHistoryTest::testCreateConversationWithOnlineDevice() { connectSignals(); auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); // Now create alice2 auto aliceArchive = std::filesystem::current_path().string() + "/alice.gz"; aliceAccount->exportArchive(aliceArchive); std::map<std::string, std::string> details = libjami::getAccountTemplate("RING"); details[ConfProperties::TYPE] = "RING"; details[ConfProperties::DISPLAYNAME] = "ALICE2"; details[ConfProperties::ALIAS] = "ALICE2"; details[ConfProperties::UPNP_ENABLED] = "true"; details[ConfProperties::ARCHIVE_PASSWORD] = ""; details[ConfProperties::ARCHIVE_PIN] = ""; details[ConfProperties::ARCHIVE_PATH] = aliceArchive; auto convId = libjami::startConversation(aliceId); alice2Id = Manager::instance().addAccount(details); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&] { return !alice2Data.conversationId.empty(); })); } void SyncHistoryTest::testCreateConversationWithMessagesThenAddDevice() { connectSignals(); auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto convId = libjami::startConversation(aliceId); // Start conversation auto aliceMsgSize = aliceData.messages.size(); libjami::sendMessage(aliceId, convId, std::string("Message 1"), ""); CPPUNIT_ASSERT(cv.wait_for(lk, 10s, [&] { return aliceMsgSize + 1 == aliceData.messages.size(); })); libjami::sendMessage(aliceId, convId, std::string("Message 2"), ""); CPPUNIT_ASSERT(cv.wait_for(lk, 10s, [&] { return aliceMsgSize + 2 == aliceData.messages.size(); })); libjami::sendMessage(aliceId, convId, std::string("Message 3"), ""); CPPUNIT_ASSERT(cv.wait_for(lk, 10s, [&] { return aliceMsgSize + 3 == aliceData.messages.size(); })); // Now create alice2 auto aliceArchive = std::filesystem::current_path().string() + "/alice.gz"; aliceAccount->exportArchive(aliceArchive); std::map<std::string, std::string> details = libjami::getAccountTemplate("RING"); details[ConfProperties::TYPE] = "RING"; details[ConfProperties::DISPLAYNAME] = "ALICE2"; details[ConfProperties::ALIAS] = "ALICE2"; details[ConfProperties::UPNP_ENABLED] = "true"; details[ConfProperties::ARCHIVE_PASSWORD] = ""; details[ConfProperties::ARCHIVE_PIN] = ""; details[ConfProperties::ARCHIVE_PATH] = aliceArchive; alice2Id = Manager::instance().addAccount(details); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&] { return !alice2Data.conversationId.empty(); })); libjami::loadConversation(alice2Id, convId, "", 0); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&] { return alice2Data.messagesLoaded.size() == 4; })); // Check messages CPPUNIT_ASSERT(alice2Data.messagesLoaded[0].body["body"] == "Message 3"); CPPUNIT_ASSERT(alice2Data.messagesLoaded[1].body["body"] == "Message 2"); CPPUNIT_ASSERT(alice2Data.messagesLoaded[2].body["body"] == "Message 1"); } void SyncHistoryTest::testCreateMultipleConversationThenAddDevice() { auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); // Start conversation auto convId = libjami::startConversation(aliceId); libjami::sendMessage(aliceId, convId, std::string("Message 1"), ""); libjami::sendMessage(aliceId, convId, std::string("Message 2"), ""); libjami::sendMessage(aliceId, convId, std::string("Message 3"), ""); std::this_thread::sleep_for(1s); auto convId2 = libjami::startConversation(aliceId); libjami::sendMessage(aliceId, convId2, std::string("Message 1"), ""); libjami::sendMessage(aliceId, convId2, std::string("Message 2"), ""); libjami::sendMessage(aliceId, convId2, std::string("Message 3"), ""); std::this_thread::sleep_for(1s); auto convId3 = libjami::startConversation(aliceId); libjami::sendMessage(aliceId, convId3, std::string("Message 1"), ""); libjami::sendMessage(aliceId, convId3, std::string("Message 2"), ""); libjami::sendMessage(aliceId, convId3, std::string("Message 3"), ""); std::this_thread::sleep_for(1s); auto convId4 = libjami::startConversation(aliceId); libjami::sendMessage(aliceId, convId4, std::string("Message 1"), ""); libjami::sendMessage(aliceId, convId4, std::string("Message 2"), ""); libjami::sendMessage(aliceId, convId4, std::string("Message 3"), ""); // Now create alice2 auto aliceArchive = std::filesystem::current_path().string() + "/alice.gz"; aliceAccount->exportArchive(aliceArchive); std::map<std::string, std::string> details = libjami::getAccountTemplate("RING"); details[ConfProperties::TYPE] = "RING"; details[ConfProperties::DISPLAYNAME] = "ALICE2"; details[ConfProperties::ALIAS] = "ALICE2"; details[ConfProperties::UPNP_ENABLED] = "true"; details[ConfProperties::ARCHIVE_PASSWORD] = ""; details[ConfProperties::ARCHIVE_PIN] = ""; details[ConfProperties::ARCHIVE_PATH] = aliceArchive; alice2Id = Manager::instance().addAccount(details); std::mutex mtx; std::unique_lock lk {mtx}; std::condition_variable cv; std::map<std::string, std::shared_ptr<libjami::CallbackWrapperBase>> confHandlers; std::atomic_int conversationReady = 0; confHandlers.insert(libjami::exportable_callback<libjami::ConversationSignal::ConversationReady>( [&](const std::string& accountId, const std::string&) { if (accountId == alice2Id) { conversationReady += 1; cv.notify_one(); } })); libjami::registerSignalHandlers(confHandlers); confHandlers.clear(); // Check if conversation is ready CPPUNIT_ASSERT(cv.wait_for(lk, 60s, [&]() { return conversationReady == 4; })); } void SyncHistoryTest::testReceivesInviteThenAddDevice() { connectSignals(); auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); // Export alice auto aliceArchive = std::filesystem::current_path().string() + "/alice.gz"; aliceAccount->exportArchive(aliceArchive); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto uri = aliceAccount->getUsername(); // Start conversation for Alice auto convId = libjami::startConversation(bobId); libjami::addConversationMember(bobId, convId, uri); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&] { return aliceData.requestReceived; })); // Now create alice2 std::map<std::string, std::string> details = libjami::getAccountTemplate("RING"); details[ConfProperties::TYPE] = "RING"; details[ConfProperties::DISPLAYNAME] = "ALICE2"; details[ConfProperties::ALIAS] = "ALICE2"; details[ConfProperties::UPNP_ENABLED] = "true"; details[ConfProperties::ARCHIVE_PASSWORD] = ""; details[ConfProperties::ARCHIVE_PIN] = ""; details[ConfProperties::ARCHIVE_PATH] = aliceArchive; alice2Id = Manager::instance().addAccount(details); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&] { return alice2Data.requestReceived; })); } void SyncHistoryTest::testRemoveConversationOnAllDevices() { connectSignals(); auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); // Now create alice2 auto aliceArchive = std::filesystem::current_path().string() + "/alice.gz"; aliceAccount->exportArchive(aliceArchive); std::map<std::string, std::string> details = libjami::getAccountTemplate("RING"); details[ConfProperties::TYPE] = "RING"; details[ConfProperties::DISPLAYNAME] = "ALICE2"; details[ConfProperties::ALIAS] = "ALICE2"; details[ConfProperties::UPNP_ENABLED] = "true"; details[ConfProperties::ARCHIVE_PASSWORD] = ""; details[ConfProperties::ARCHIVE_PIN] = ""; details[ConfProperties::ARCHIVE_PATH] = aliceArchive; auto convId = libjami::startConversation(aliceId); alice2Id = Manager::instance().addAccount(details); CPPUNIT_ASSERT(cv.wait_for(lk, 60s, [&] { return !alice2Data.conversationId.empty(); })); libjami::removeConversation(aliceId, aliceData.conversationId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&] { return alice2Data.removed; })); } void SyncHistoryTest::testSyncCreateAccountExportDeleteReimportOldBackup() { connectSignals(); auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto bobUri = bobAccount->getUsername(); // Backup alice before start conversation, worst scenario for invites auto aliceArchive = std::filesystem::current_path().string() + "/alice.gz"; aliceAccount->exportArchive(aliceArchive); // Start conversation auto convId = libjami::startConversation(aliceId); libjami::addConversationMember(aliceId, convId, bobUri); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.requestReceived; })); auto aliceMsgSize = aliceData.messages.size(); libjami::acceptConversationRequest(bobId, convId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return aliceMsgSize + 1 == aliceData.messages.size() && !bobData.conversationId.empty(); })); // disable account (same as removed) Manager::instance().sendRegister(aliceId, false); std::this_thread::sleep_for(5s); std::map<std::string, std::string> details = libjami::getAccountTemplate("RING"); details[ConfProperties::TYPE] = "RING"; details[ConfProperties::DISPLAYNAME] = "ALICE2"; details[ConfProperties::ALIAS] = "ALICE2"; details[ConfProperties::UPNP_ENABLED] = "true"; details[ConfProperties::ARCHIVE_PASSWORD] = ""; details[ConfProperties::ARCHIVE_PIN] = ""; details[ConfProperties::ARCHIVE_PATH] = aliceArchive; alice2Id = Manager::instance().addAccount(details); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&] { return alice2Data.deviceAnnounced; })); // This will trigger a conversation request. Cause alice2 is unable to know of first conversation libjami::sendMessage(bobId, convId, std::string("hi"), ""); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&] { return alice2Data.requestReceived; })); libjami::acceptConversationRequest(alice2Id, convId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&] { return !alice2Data.conversationId.empty(); })); auto bobMsgSize = bobData.messages.size(); libjami::sendMessage(alice2Id, convId, std::string("hi"), ""); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobMsgSize + 1 == bobData.messages.size(); })); } void SyncHistoryTest::testSyncCreateAccountExportDeleteReimportWithConvId() { connectSignals(); auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto aliceUri = aliceAccount->getUsername(); auto bobUri = bobAccount->getUsername(); // Start conversation auto convId = libjami::startConversation(aliceId); libjami::addConversationMember(aliceId, convId, bobUri); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.requestReceived; })); auto aliceMsgSize = aliceData.messages.size(); libjami::acceptConversationRequest(bobId, convId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return aliceMsgSize + 1 == aliceData.messages.size(); })); // We need to track presence to know when to sync bobAccount->trackBuddyPresence(aliceUri, true); // Backup alice after startConversation with member auto aliceArchive = std::filesystem::current_path().string() + "/alice.gz"; aliceAccount->exportArchive(aliceArchive); // disable account (same as removed) Manager::instance().sendRegister(aliceId, false); std::this_thread::sleep_for(5s); std::map<std::string, std::string> details = libjami::getAccountTemplate("RING"); details[ConfProperties::TYPE] = "RING"; details[ConfProperties::DISPLAYNAME] = "ALICE2"; details[ConfProperties::ALIAS] = "ALICE2"; details[ConfProperties::UPNP_ENABLED] = "true"; details[ConfProperties::ARCHIVE_PASSWORD] = ""; details[ConfProperties::ARCHIVE_PIN] = ""; details[ConfProperties::ARCHIVE_PATH] = aliceArchive; alice2Id = Manager::instance().addAccount(details); // Should retrieve conversation, no need for action as the convInfos is in the archive CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&] { return !alice2Data.conversationId.empty(); })); auto bobMsgSize = bobData.messages.size(); libjami::sendMessage(alice2Id, convId, std::string("hi"), ""); cv.wait_for(lk, 30s, [&]() { return bobMsgSize + 1 == bobData.messages.size(); }); } void SyncHistoryTest::testSyncCreateAccountExportDeleteReimportWithConvReq() { connectSignals(); auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto aliceUri = aliceAccount->getUsername(); // Start conversation auto convId = libjami::startConversation(bobId); libjami::addConversationMember(bobId, convId, aliceUri); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return aliceData.requestReceived; })); // Backup alice after startConversation with member auto aliceArchive = std::filesystem::current_path().string() + "/alice.gz"; aliceAccount->exportArchive(aliceArchive); // disable account (same as removed) Manager::instance().sendRegister(aliceId, false); std::this_thread::sleep_for(5s); std::map<std::string, std::string> details = libjami::getAccountTemplate("RING"); details[ConfProperties::TYPE] = "RING"; details[ConfProperties::DISPLAYNAME] = "ALICE2"; details[ConfProperties::ALIAS] = "ALICE2"; details[ConfProperties::UPNP_ENABLED] = "true"; details[ConfProperties::ARCHIVE_PASSWORD] = ""; details[ConfProperties::ARCHIVE_PIN] = ""; details[ConfProperties::ARCHIVE_PATH] = aliceArchive; alice2Id = Manager::instance().addAccount(details); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&] { return alice2Data.deviceAnnounced; })); // Should get the same request as before. auto bobMsgSize = bobData.messages.size(); libjami::acceptConversationRequest(alice2Id, convId); CPPUNIT_ASSERT( cv.wait_for(lk, 30s, [&]() { return bobMsgSize + 1 == bobData.messages.size(); })); } void SyncHistoryTest::testSyncOneToOne() { connectSignals(); auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); aliceAccount->addContact(bobAccount->getUsername()); // Now create alice2 auto aliceArchive = std::filesystem::current_path().string() + "/alice.gz"; aliceAccount->exportArchive(aliceArchive); std::map<std::string, std::string> details = libjami::getAccountTemplate("RING"); details[ConfProperties::TYPE] = "RING"; details[ConfProperties::DISPLAYNAME] = "ALICE2"; details[ConfProperties::ALIAS] = "ALICE2"; details[ConfProperties::UPNP_ENABLED] = "true"; details[ConfProperties::ARCHIVE_PASSWORD] = ""; details[ConfProperties::ARCHIVE_PIN] = ""; details[ConfProperties::ARCHIVE_PATH] = aliceArchive; alice2Id = Manager::instance().addAccount(details); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&] { return !alice2Data.conversationId.empty(); })); } void SyncHistoryTest::testConversationRequestRemoved() { connectSignals(); auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto uri = aliceAccount->getUsername(); // Export alice auto aliceArchive = std::filesystem::current_path().string() + "/alice.gz"; aliceAccount->exportArchive(aliceArchive); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); // Start conversation for Alice auto convId = libjami::startConversation(bobId); // Check that alice receives the request libjami::addConversationMember(bobId, convId, uri); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&] { return aliceData.requestReceived; })); // Now create alice2 std::map<std::string, std::string> details = libjami::getAccountTemplate("RING"); details[ConfProperties::TYPE] = "RING"; details[ConfProperties::DISPLAYNAME] = "ALICE2"; details[ConfProperties::ALIAS] = "ALICE2"; details[ConfProperties::UPNP_ENABLED] = "true"; details[ConfProperties::ARCHIVE_PASSWORD] = ""; details[ConfProperties::ARCHIVE_PIN] = ""; details[ConfProperties::ARCHIVE_PATH] = aliceArchive; alice2Id = Manager::instance().addAccount(details); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&] { return aliceData.requestReceived; })); // Now decline trust request, this should trigger ConversationRequestDeclined both sides for Alice libjami::declineConversationRequest(aliceId, convId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&] { return aliceData.requestRemoved && alice2Data.requestRemoved; })); } void SyncHistoryTest::testProfileReceivedMultiDevice() { connectSignals(); auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto aliceUri = aliceAccount->getUsername(); auto bobUri = bobAccount->getUsername(); // Export alice auto aliceArchive = std::filesystem::current_path().string() + "/alice.gz"; aliceAccount->exportArchive(aliceArchive); // Set VCards std::string vcard = "BEGIN:VCARD\n\ VERSION:2.1\n\ FN:TITLE\n\ DESCRIPTION:DESC\n\ END:VCARD"; auto alicePath = fileutils::get_data_dir() / aliceId / "profile.vcf"; auto bobPath = fileutils::get_data_dir() / bobId / "profile.vcf"; // Save VCard auto p = std::filesystem::path(alicePath); dhtnet::fileutils::recursive_mkdir(p.parent_path()); std::ofstream aliceFile(alicePath); if (aliceFile.is_open()) { aliceFile << vcard; aliceFile.close(); } p = std::filesystem::path(bobPath); dhtnet::fileutils::recursive_mkdir(p.parent_path()); std::ofstream bobFile(bobPath); if (bobFile.is_open()) { bobFile << vcard; bobFile.close(); } aliceAccount->addContact(bobUri); aliceAccount->sendTrustRequest(bobUri, {}); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.requestReceived; })); CPPUNIT_ASSERT(bobAccount->acceptTrustRequest(aliceUri)); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return !bobData.profilePath.empty() && !aliceData.profilePath.empty() && !bobData.conversationId.empty(); })); CPPUNIT_ASSERT(std::filesystem::is_regular_file(bobData.profilePath)); // Now create alice2 std::map<std::string, std::string> details = libjami::getAccountTemplate("RING"); details[ConfProperties::TYPE] = "RING"; details[ConfProperties::DISPLAYNAME] = "ALICE2"; details[ConfProperties::ALIAS] = "ALICE2"; details[ConfProperties::UPNP_ENABLED] = "true"; details[ConfProperties::ARCHIVE_PASSWORD] = ""; details[ConfProperties::ARCHIVE_PIN] = ""; details[ConfProperties::ARCHIVE_PATH] = aliceArchive; bobData.profilePath = {}; alice2Data.profilePath = {}; alice2Id = Manager::instance().addAccount(details); CPPUNIT_ASSERT(cv.wait_for(lk, 60s, [&] { return alice2Data.deviceAnnounced && !bobData.profilePath.empty() && !alice2Data.profilePath.empty(); })); } void SyncHistoryTest::testLastInteractionAfterClone() { connectSignals(); auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto aliceUri = aliceAccount->getUsername(); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto bobUri = bobAccount->getUsername(); aliceAccount->addContact(bobUri); aliceAccount->sendTrustRequest(bobUri, {}); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.requestReceived; })); auto aliceMsgSize = aliceData.messages.size(); CPPUNIT_ASSERT(bobAccount->acceptTrustRequest(aliceUri)); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return aliceMsgSize + 1 == aliceData.messages.size(); })); // Start conversation libjami::sendMessage(bobId, aliceData.conversationId, std::string("Message 1"), ""); CPPUNIT_ASSERT(cv.wait_for(lk, 10s, [&] { return aliceMsgSize + 2 == aliceData.messages.size(); })); libjami::sendMessage(bobId, aliceData.conversationId, std::string("Message 2"), ""); CPPUNIT_ASSERT(cv.wait_for(lk, 10s, [&] { return aliceMsgSize + 3 == aliceData.messages.size(); })); libjami::sendMessage(bobId, aliceData.conversationId, std::string("Message 3"), ""); CPPUNIT_ASSERT(cv.wait_for(lk, 10s, [&] { return aliceMsgSize + 4 == aliceData.messages.size(); })); auto msgId = aliceData.messages.rbegin()->id; libjami::setMessageDisplayed(aliceId, "swarm:" + aliceData.conversationId, msgId, 3); CPPUNIT_ASSERT(cv.wait_for(lk, 10s, [&] { return aliceData.sent; })); // Now create alice2 auto aliceArchive = std::filesystem::current_path().string() + "/alice.gz"; aliceAccount->exportArchive(aliceArchive); std::map<std::string, std::string> details = libjami::getAccountTemplate("RING"); details[ConfProperties::TYPE] = "RING"; details[ConfProperties::DISPLAYNAME] = "ALICE2"; details[ConfProperties::ALIAS] = "ALICE2"; details[ConfProperties::UPNP_ENABLED] = "true"; details[ConfProperties::ARCHIVE_PASSWORD] = ""; details[ConfProperties::ARCHIVE_PIN] = ""; details[ConfProperties::ARCHIVE_PATH] = aliceArchive; alice2Id = Manager::instance().addAccount(details); // Check if conversation is ready CPPUNIT_ASSERT(cv.wait_for(lk, 60s, [&]() { return !alice2Data.conversationId.empty(); })); // Check that last displayed is synched auto membersInfos = libjami::getConversationMembers(alice2Id, alice2Data.conversationId); CPPUNIT_ASSERT(std::find_if(membersInfos.begin(), membersInfos.end(), [&](auto infos) { return infos["uri"] == aliceUri && infos["lastDisplayed"] == msgId; }) != membersInfos.end()); } void SyncHistoryTest::testLastInteractionAfterSomeMessages() { connectSignals(); auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto aliceUri = aliceAccount->getUsername(); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto bobUri = bobAccount->getUsername(); // Creates alice2 auto aliceArchive = std::filesystem::current_path().string() + "/alice.gz"; aliceAccount->exportArchive(aliceArchive); std::map<std::string, std::string> details = libjami::getAccountTemplate("RING"); details[ConfProperties::TYPE] = "RING"; details[ConfProperties::DISPLAYNAME] = "ALICE2"; details[ConfProperties::ALIAS] = "ALICE2"; details[ConfProperties::UPNP_ENABLED] = "true"; details[ConfProperties::ARCHIVE_PASSWORD] = ""; details[ConfProperties::ARCHIVE_PIN] = ""; details[ConfProperties::ARCHIVE_PATH] = aliceArchive; alice2Id = Manager::instance().addAccount(details); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() {return alice2Data.deviceAnnounced; })); auto getMessageFromBody = [](const auto& data, const auto& body) -> std::string { auto it = std::find_if(data.messages.begin(), data.messages.end(), [&](auto& msg) { return msg.body.find("body") != msg.body.end() && msg.body.at("body") == body; }); if (it != data.messages.end()) { return it->id; } return {}; }; auto getMessage = [](const auto& data, const auto& mid) -> bool { return std::find_if(data.messages.begin(), data.messages.end(), [&](auto& msg) { return msg.id == mid; }) != data.messages.end(); }; aliceAccount->addContact(bobUri); aliceAccount->sendTrustRequest(bobUri, {}); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.requestReceived && !alice2Data.conversationId.empty(); })); CPPUNIT_ASSERT(bobAccount->acceptTrustRequest(aliceUri)); CPPUNIT_ASSERT( cv.wait_for(lk, 30s, [&]() { return aliceData.members[bobUri] == 1 && alice2Data.members[bobUri] == 1; })); // Start conversation bobData.messages.clear(); libjami::sendMessage(bobId, aliceData.conversationId, std::string("Message 1"), ""); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return !getMessageFromBody(bobData, "Message 1").empty(); })); auto msgId = getMessageFromBody(bobData, "Message 1"); CPPUNIT_ASSERT(cv.wait_for(lk, 20s, [&] { return getMessage(aliceData, msgId) && getMessage(alice2Data, msgId); })); bobData.messages.clear(); libjami::sendMessage(bobId, aliceData.conversationId, std::string("Message 2"), ""); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return !getMessageFromBody(bobData, "Message 2").empty(); })); msgId = getMessageFromBody(bobData, "Message 2"); CPPUNIT_ASSERT(cv.wait_for(lk, 10s, [&] { return getMessage(aliceData, msgId) && getMessage(alice2Data, msgId); })); bobData.messages.clear(); libjami::sendMessage(bobId, aliceData.conversationId, std::string("Message 3"), ""); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return !getMessageFromBody(bobData, "Message 3").empty(); })); msgId = getMessageFromBody(bobData, "Message 3"); CPPUNIT_ASSERT(cv.wait_for(lk, 10s, [&] { return getMessage(aliceData, msgId) && getMessage(alice2Data, msgId); })); libjami::setMessageDisplayed(aliceId, "swarm:" + aliceData.conversationId, msgId, 3); CPPUNIT_ASSERT(cv.wait_for(lk, 20s, [&] { return aliceData.sent && alice2Data.sent; })); auto membersInfos = libjami::getConversationMembers(alice2Id, alice2Data.conversationId); CPPUNIT_ASSERT(std::find_if(membersInfos.begin(), membersInfos.end(), [&](auto infos) { return infos["uri"] == aliceUri && infos["lastDisplayed"] == msgId; }) != membersInfos.end()); } } // namespace test } // namespace jami RING_TEST_RUNNER(jami::test::SyncHistoryTest::name())
42,240
C++
.cpp
846
42.229314
141
0.664834
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,667
test_media_player.cpp
savoirfairelinux_jami-daemon/test/unitTest/media/test_media_player.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <cppunit/TestAssert.h> #include <cppunit/TestFixture.h> #include <cppunit/extensions/HelperMacros.h> #include <cmath> #include "jami.h" #include "manager.h" #include "../../test_runner.h" #include "client/videomanager.h" namespace jami { namespace test { class MediaPlayerTest : public CppUnit::TestFixture { public: static std::string name() { return "media_player"; } void setUp(); void tearDown(); private: void testCreate(); void testJPG(); void testAudioFile(); void testPause(); void testSeekWhilePaused(); void testSeekWhilePlaying(); bool isWithinUsec(int64_t currentTime, int64_t seekTime, int64_t margin); CPPUNIT_TEST_SUITE(MediaPlayerTest); CPPUNIT_TEST(testCreate); CPPUNIT_TEST(testJPG); CPPUNIT_TEST(testAudioFile); CPPUNIT_TEST(testPause); CPPUNIT_TEST(testSeekWhilePaused); CPPUNIT_TEST(testSeekWhilePlaying); CPPUNIT_TEST_SUITE_END(); std::string playerId1_ {}; std::string playerId2_ {}; int64_t duration_ {}; int audio_stream_ {}; int video_stream_ {}; std::shared_ptr<MediaPlayer> mediaPlayer {}; std::mutex mtx; std::unique_lock<std::mutex> lk {mtx}; std::condition_variable cv; }; CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(MediaPlayerTest, MediaPlayerTest::name()); void MediaPlayerTest::setUp() { libjami::init(libjami::InitFlag(libjami::LIBJAMI_FLAG_DEBUG | libjami::LIBJAMI_FLAG_CONSOLE_LOG)); if (not Manager::instance().initialized) CPPUNIT_ASSERT(libjami::start("jami-sample.yml")); std::map<std::string, std::shared_ptr<libjami::CallbackWrapperBase>> handler; handler.insert(libjami::exportable_callback<libjami::MediaPlayerSignal::FileOpened>( [=](const std::string& playerId, const std::map<std::string, std::string>& info) { duration_ = std::stol(info.at("duration")); audio_stream_ = std::stoi(info.at("audio_stream")); video_stream_ = std::stoi(info.at("video_stream")); playerId2_ = playerId; cv.notify_all(); })); libjami::registerSignalHandlers(handler); } void MediaPlayerTest::tearDown() { jami::closeMediaPlayer(playerId1_); mediaPlayer.reset(); playerId1_ = {}; playerId2_ = {}; libjami::fini(); } void MediaPlayerTest::testCreate() { JAMI_INFO("Start testCreate"); playerId1_ = jami::createMediaPlayer("./media/test_video_file.mp4"); mediaPlayer = jami::getMediaPlayer(playerId1_); cv.wait_for(lk, 5s); CPPUNIT_ASSERT(playerId1_ == playerId2_); CPPUNIT_ASSERT(mediaPlayer->getId() == playerId1_); CPPUNIT_ASSERT(mediaPlayer->isInputValid()); CPPUNIT_ASSERT(audio_stream_ != -1); CPPUNIT_ASSERT(video_stream_ != -1); CPPUNIT_ASSERT(mediaPlayer->isPaused()); CPPUNIT_ASSERT(mediaPlayer->getPlayerPosition() == 0); JAMI_INFO("End testCreate"); } void MediaPlayerTest::testJPG() { JAMI_INFO("Start testJpg"); playerId1_ = jami::createMediaPlayer("./media/jami.jpg"); mediaPlayer = jami::getMediaPlayer(playerId1_); cv.wait_for(lk, 5s); CPPUNIT_ASSERT(playerId1_ == playerId2_); CPPUNIT_ASSERT(mediaPlayer->getId() == playerId1_); CPPUNIT_ASSERT(mediaPlayer->isInputValid()); CPPUNIT_ASSERT(video_stream_ != -1); CPPUNIT_ASSERT(mediaPlayer->isPaused()); CPPUNIT_ASSERT(mediaPlayer->getPlayerPosition() == 0); JAMI_INFO("End testJpg"); } void MediaPlayerTest::testAudioFile() { JAMI_INFO("Start testAudioFile"); playerId1_ = jami::createMediaPlayer("./media/test.mp3"); mediaPlayer = jami::getMediaPlayer(playerId1_); cv.wait_for(lk, 5s); CPPUNIT_ASSERT(playerId1_ == playerId2_); CPPUNIT_ASSERT(mediaPlayer->getId() == playerId1_); CPPUNIT_ASSERT(mediaPlayer->isInputValid()); CPPUNIT_ASSERT(audio_stream_ != -1); CPPUNIT_ASSERT(mediaPlayer->isPaused()); CPPUNIT_ASSERT(mediaPlayer->getPlayerPosition() == 0); JAMI_INFO("End testAudioFile"); } void MediaPlayerTest::testPause() { playerId1_ = jami::createMediaPlayer("./media/test_video_file.mp4"); mediaPlayer = jami::getMediaPlayer(playerId1_); cv.wait_for(lk, 5s); JAMI_INFO("Start testPause"); // should start paused CPPUNIT_ASSERT(mediaPlayer->isPaused()); mediaPlayer->pause(false); CPPUNIT_ASSERT(!mediaPlayer->isPaused()); JAMI_INFO("End testPause"); } bool MediaPlayerTest::isWithinUsec(int64_t currentTime, int64_t seekTime, int64_t margin) { return std::abs(currentTime-seekTime) <= margin; } void MediaPlayerTest::testSeekWhilePaused() { JAMI_INFO("Start testSeekWhilePaused"); playerId1_ = jami::createMediaPlayer("./media/test_video_file.mp4"); mediaPlayer = jami::getMediaPlayer(playerId1_); cv.wait_for(lk, 5s); int64_t startTime = mediaPlayer->getPlayerPosition(); CPPUNIT_ASSERT(mediaPlayer->seekToTime(startTime+100)); CPPUNIT_ASSERT(isWithinUsec(mediaPlayer->getPlayerPosition(), startTime+100, 1)); CPPUNIT_ASSERT(mediaPlayer->seekToTime(startTime+1000)); CPPUNIT_ASSERT(isWithinUsec(mediaPlayer->getPlayerPosition(), startTime+1000, 1)); CPPUNIT_ASSERT(mediaPlayer->seekToTime(startTime+500)); CPPUNIT_ASSERT(isWithinUsec(mediaPlayer->getPlayerPosition(), startTime+500, 1)); CPPUNIT_ASSERT(mediaPlayer->seekToTime(duration_-1)); CPPUNIT_ASSERT(isWithinUsec(mediaPlayer->getPlayerPosition(), duration_-1, 1)); CPPUNIT_ASSERT(mediaPlayer->seekToTime(0)); CPPUNIT_ASSERT(isWithinUsec(mediaPlayer->getPlayerPosition(), 0, 1)); CPPUNIT_ASSERT(!(mediaPlayer->seekToTime(duration_+1))); JAMI_INFO("End testSeekWhilePaused"); } void MediaPlayerTest::testSeekWhilePlaying() { JAMI_INFO("Start testSeekWhilePlaying"); playerId1_ = jami::createMediaPlayer("./media/test_video_file.mp4"); mediaPlayer = jami::getMediaPlayer(playerId1_); cv.wait_for(lk, 5s); mediaPlayer->pause(false); int64_t startTime = mediaPlayer->getPlayerPosition(); CPPUNIT_ASSERT(mediaPlayer->seekToTime(startTime+10000)); CPPUNIT_ASSERT(isWithinUsec(mediaPlayer->getPlayerPosition(), startTime+10000, 50)); startTime = mediaPlayer->getPlayerPosition(); CPPUNIT_ASSERT(mediaPlayer->seekToTime(startTime-5000)); CPPUNIT_ASSERT(isWithinUsec(mediaPlayer->getPlayerPosition(), startTime-5000, 50)); CPPUNIT_ASSERT(mediaPlayer->seekToTime(10000)); CPPUNIT_ASSERT(isWithinUsec(mediaPlayer->getPlayerPosition(), 10000, 50)); CPPUNIT_ASSERT(mediaPlayer->seekToTime(0)); CPPUNIT_ASSERT(isWithinUsec(mediaPlayer->getPlayerPosition(), 0, 50)); CPPUNIT_ASSERT(!(mediaPlayer->seekToTime(duration_+1))); JAMI_INFO("End testSeekWhilePlaying"); } }} // namespace jami::test RING_TEST_RUNNER(jami::test::MediaPlayerTest::name());
7,499
C++
.cpp
192
34.901042
102
0.719059
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,668
test_media_filter.cpp
savoirfairelinux_jami-daemon/test/unitTest/media/test_media_filter.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <cppunit/TestAssert.h> #include <cppunit/TestFixture.h> #include <cppunit/extensions/HelperMacros.h> #include "jami.h" #include "media/libav_deps.h" #include "media/media_buffer.h" #include "media/media_filter.h" #include "../../test_runner.h" namespace jami { namespace test { class MediaFilterTest : public CppUnit::TestFixture { public: static std::string name() { return "media_filter"; } void setUp(); void tearDown(); private: void testAudioFilter(); void testAudioMixing(); void testVideoFilter(); void testFilterParams(); void testReinit(); CPPUNIT_TEST_SUITE(MediaFilterTest); CPPUNIT_TEST(testAudioFilter); CPPUNIT_TEST(testAudioMixing); CPPUNIT_TEST(testVideoFilter); CPPUNIT_TEST(testFilterParams); CPPUNIT_TEST(testReinit); CPPUNIT_TEST_SUITE_END(); std::unique_ptr<MediaFilter> filter_; }; CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(MediaFilterTest, MediaFilterTest::name()); void MediaFilterTest::setUp() { libjami::init(libjami::InitFlag(libjami::LIBJAMI_FLAG_DEBUG | libjami::LIBJAMI_FLAG_CONSOLE_LOG)); libav_utils::av_init(); filter_.reset(new MediaFilter); } void MediaFilterTest::tearDown() { libjami::fini(); } static void fill_yuv_image(uint8_t *data[4], int linesize[4], int width, int height, int frame_index) { int x, y; /* Y */ for (y = 0; y < height; y++) for (x = 0; x < width; x++) data[0][y * linesize[0] + x] = x + y + frame_index * 3; /* Cb and Cr */ for (y = 0; y < height / 2; y++) { for (x = 0; x < width / 2; x++) { data[1][y * linesize[1] + x] = 128 + y + frame_index * 2; data[2][y * linesize[2] + x] = 64 + x + frame_index * 5; } } } static void fill_samples(uint16_t* samples, int sampleRate, int nbSamples, int nbChannels, float tone, float& t) { const constexpr double pi = 3.14159265358979323846264338327950288; // M_PI const float tincr = 2 * pi * tone / sampleRate; for (int j = 0; j < nbSamples; ++j) { samples[2 * j] = (int)(sin(t) * 10000); for (int k = 1; k < nbChannels; ++k) samples[2 * j + k] = samples[2 * j]; t += tincr; } } static void fill_samples(uint16_t* samples, int sampleRate, int nbSamples, int nbChannels, float tone) { float t = 0; fill_samples(samples, sampleRate, nbSamples, nbChannels, tone, t); } static void fillAudioFrameProps(AVFrame* frame, const MediaStream& ms) { frame->format = ms.format; av_channel_layout_default(&frame->ch_layout, ms.nbChannels); frame->nb_samples = ms.frameSize; frame->sample_rate = ms.sampleRate; CPPUNIT_ASSERT(frame->format > AV_SAMPLE_FMT_NONE); CPPUNIT_ASSERT(frame->nb_samples > 0); CPPUNIT_ASSERT(frame->ch_layout.u.mask != 0); } void MediaFilterTest::testAudioFilter() { std::string filterSpec = "[in1] aformat=sample_fmts=u8"; // constants const constexpr int nbSamples = 100; const constexpr int sampleRate = 44100; const constexpr enum AVSampleFormat format = AV_SAMPLE_FMT_S16; // prepare audio frame AudioFrame af; auto frame = af.pointer(); frame->format = format; av_channel_layout_from_mask(&frame->ch_layout, AV_CH_LAYOUT_STEREO); frame->nb_samples = nbSamples; frame->sample_rate = sampleRate; // construct the filter parameters auto params = MediaStream("in1", format, rational<int>(1, sampleRate), sampleRate, frame->ch_layout.nb_channels, nbSamples); // allocate and fill frame buffers CPPUNIT_ASSERT(av_frame_get_buffer(frame, 0) >= 0); fill_samples(reinterpret_cast<uint16_t*>(frame->data[0]), sampleRate, nbSamples, frame->ch_layout.nb_channels, 440.0); // prepare filter std::vector<MediaStream> vec; vec.push_back(params); CPPUNIT_ASSERT(filter_->initialize(filterSpec, vec) >= 0); // apply filter CPPUNIT_ASSERT(filter_->feedInput(frame, "in1") >= 0); auto out = filter_->readOutput(); CPPUNIT_ASSERT(out); CPPUNIT_ASSERT(out->pointer()); // check if the filter worked CPPUNIT_ASSERT(out->pointer()->format == AV_SAMPLE_FMT_U8); } void MediaFilterTest::testAudioMixing() { std::string filterSpec = "[a1] [a2] [a3] amix=inputs=3,aformat=sample_fmts=s16"; AudioFrame af1; auto frame1 = af1.pointer(); AudioFrame af2; auto frame2 = af2.pointer(); AudioFrame af3; auto frame3 = af3.pointer(); std::vector<MediaStream> vec; vec.emplace_back("a1", AV_SAMPLE_FMT_S16, rational<int>(1, 48000), 48000, 2, 960); vec.emplace_back("a2", AV_SAMPLE_FMT_S16, rational<int>(1, 48000), 48000, 2, 960); vec.emplace_back("a3", AV_SAMPLE_FMT_S16, rational<int>(1, 48000), 48000, 2, 960); CPPUNIT_ASSERT(filter_->initialize(filterSpec, vec) >= 0); float t1 = 0, t2 = 0, t3 = 0; for (int i = 0; i < 100; ++i) { fillAudioFrameProps(frame1, vec[0]); frame1->pts = i * frame1->nb_samples; CPPUNIT_ASSERT(av_frame_get_buffer(frame1, 0) >= 0); fill_samples(reinterpret_cast<uint16_t*>(frame1->data[0]), frame1->sample_rate, frame1->nb_samples, frame1->ch_layout.nb_channels, 440.0, t1); fillAudioFrameProps(frame2, vec[1]); frame2->pts = i * frame2->nb_samples; CPPUNIT_ASSERT(av_frame_get_buffer(frame2, 0) >= 0); fill_samples(reinterpret_cast<uint16_t*>(frame2->data[0]), frame2->sample_rate, frame2->nb_samples, frame2->ch_layout.nb_channels, 329.6276, t2); fillAudioFrameProps(frame3, vec[2]); frame3->pts = i * frame3->nb_samples; CPPUNIT_ASSERT(av_frame_get_buffer(frame3, 0) >= 0); fill_samples(reinterpret_cast<uint16_t*>(frame3->data[0]), frame3->sample_rate, frame3->nb_samples, frame3->ch_layout.nb_channels, 349.2282, t3); // apply filter CPPUNIT_ASSERT(filter_->feedInput(frame1, "a1") >= 0); CPPUNIT_ASSERT(filter_->feedInput(frame2, "a2") >= 0); CPPUNIT_ASSERT(filter_->feedInput(frame3, "a3") >= 0); // read output auto out = filter_->readOutput(); CPPUNIT_ASSERT(out); CPPUNIT_ASSERT(out->pointer()); av_frame_unref(frame1); av_frame_unref(frame2); av_frame_unref(frame3); } } void MediaFilterTest::testVideoFilter() { std::string filterSpec = "[main] [top] overlay=main_w-overlay_w-10:main_h-overlay_h-10"; std::string main = "main"; std::string top = "top"; // constants const constexpr int width1 = 320; const constexpr int height1 = 240; const constexpr int width2 = 30; const constexpr int height2 = 30; const constexpr AVPixelFormat format = AV_PIX_FMT_YUV420P; // prepare video frame libjami::VideoFrame vf1; auto frame = vf1.pointer(); frame->format = format; frame->width = width1; frame->height = height1; libjami::VideoFrame vf2; auto extra = vf2.pointer(); extra->format = format; extra->width = width2; extra->height = height2; // construct the filter parameters rational<int> one = rational<int>(1); auto params1 = MediaStream("main", format, one, width1, height1, one.real<int>(), one); auto params2 = MediaStream("top", format, one, width2, height2, one.real<int>(), one); // allocate and fill frame buffers CPPUNIT_ASSERT(av_frame_get_buffer(frame, 32) >= 0); fill_yuv_image(frame->data, frame->linesize, frame->width, frame->height, 0); CPPUNIT_ASSERT(av_frame_get_buffer(extra, 32) >= 0); fill_yuv_image(extra->data, extra->linesize, extra->width, extra->height, 0); // prepare filter auto vec = std::vector<MediaStream>(); vec.push_back(params2); // order does not matter, as long as names match vec.push_back(params1); CPPUNIT_ASSERT(filter_->initialize(filterSpec, vec) >= 0); // apply filter CPPUNIT_ASSERT(filter_->feedInput(frame, main) >= 0); CPPUNIT_ASSERT(filter_->feedInput(extra, top) >= 0); auto out = filter_->readOutput(); CPPUNIT_ASSERT(out); CPPUNIT_ASSERT(out->pointer()); // check if the filter worked CPPUNIT_ASSERT(out->pointer()->width == width1 && out->pointer()->height == height1); } void MediaFilterTest::testFilterParams() { std::string filterSpec = "[main] [top] overlay=main_w-overlay_w-10:main_h-overlay_h-10"; // constants const constexpr int width1 = 320; const constexpr int height1 = 240; const constexpr int width2 = 30; const constexpr int height2 = 30; const constexpr AVPixelFormat format = AV_PIX_FMT_YUV420P; // construct the filter parameters rational<int> one = rational<int>(1); auto params1 = MediaStream("main", format, one, width1, height1, one.real<int>(), one); auto params2 = MediaStream("top", format, one, width2, height2, one.real<int>(), one); // returned params should be invalid CPPUNIT_ASSERT(filter_->getOutputParams().format < 0); // prepare filter auto vec = std::vector<MediaStream>(); vec.push_back(params2); // order does not matter, as long as names match vec.push_back(params1); CPPUNIT_ASSERT(filter_->initialize(filterSpec, vec) >= 0); // check input params auto main = filter_->getInputParams("main"); CPPUNIT_ASSERT(main.format == format && main.width == width1 && main.height == height1); auto top = filter_->getInputParams("top"); CPPUNIT_ASSERT(top.format == format && top.width == width2 && top.height == height2); // output params should now be valid auto ms = filter_->getOutputParams(); CPPUNIT_ASSERT(ms.format >= 0 && ms.width == width1 && ms.height == height1); } void MediaFilterTest::testReinit() { std::string filterSpec = "[in1] aresample=48000"; // prepare audio frame AudioFrame af; auto frame = af.pointer(); frame->format = AV_SAMPLE_FMT_S16; av_channel_layout_from_mask(&frame->ch_layout, AV_CH_LAYOUT_STEREO); frame->nb_samples = 100; frame->sample_rate = 44100; // construct the filter parameters with different sample rate auto params = MediaStream("in1", frame->format, rational<int>(1, 16000), 16000, frame->ch_layout.nb_channels, frame->nb_samples); // allocate and fill frame buffers CPPUNIT_ASSERT(av_frame_get_buffer(frame, 0) >= 0); fill_samples(reinterpret_cast<uint16_t*>(frame->data[0]), frame->sample_rate, frame->nb_samples, frame->ch_layout.nb_channels, 440.0); // prepare filter std::vector<MediaStream> vec; vec.push_back(params); CPPUNIT_ASSERT(filter_->initialize(filterSpec, vec) >= 0); // filter should reinitialize on feedInput CPPUNIT_ASSERT(filter_->feedInput(frame, "in1") >= 0); } }} // namespace jami::test RING_TEST_RUNNER(jami::test::MediaFilterTest::name());
11,448
C++
.cpp
278
36.47482
153
0.673387
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,669
test_media_encoder.cpp
savoirfairelinux_jami-daemon/test/unitTest/media/test_media_encoder.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <cppunit/TestAssert.h> #include <cppunit/TestFixture.h> #include <cppunit/extensions/HelperMacros.h> #include "jami.h" #include "fileutils.h" #include "media/libav_deps.h" #include "media/media_encoder.h" #include "media/media_io_handle.h" #include "media/system_codec_container.h" #include "../../test_runner.h" namespace jami { namespace test { class MediaEncoderTest : public CppUnit::TestFixture { public: static std::string name() { return "media_encoder"; } void setUp(); void tearDown(); private: void testMultiStream(); CPPUNIT_TEST_SUITE(MediaEncoderTest); CPPUNIT_TEST(testMultiStream); CPPUNIT_TEST_SUITE_END(); std::unique_ptr<MediaEncoder> encoder_; std::vector<std::string> files_; }; CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(MediaEncoderTest, MediaEncoderTest::name()); void MediaEncoderTest::setUp() { libjami::init(libjami::InitFlag(libjami::LIBJAMI_FLAG_DEBUG | libjami::LIBJAMI_FLAG_CONSOLE_LOG)); libav_utils::av_init(); encoder_.reset(new MediaEncoder); files_.push_back("test.mkv"); } void MediaEncoderTest::tearDown() { // clean up behind ourselves for (const auto& file : files_) dhtnet::fileutils::remove(file); libjami::fini(); } static AVFrame* getVideoFrame(int width, int height, int frame_index) { int x, y; AVFrame* frame = av_frame_alloc(); if (!frame) return nullptr; frame->format = AV_PIX_FMT_YUV420P; frame->width = width; frame->height = height; if (av_frame_get_buffer(frame, 32) < 0) { av_frame_free(&frame); return nullptr; } /* Y */ for (y = 0; y < height; y++) for (x = 0; x < width; x++) frame->data[0][y * frame->linesize[0] + x] = x + y + frame_index * 3; /* Cb and Cr */ for (y = 0; y < height / 2; y++) { for (x = 0; x < width / 2; x++) { frame->data[1][y * frame->linesize[1] + x] = 128 + y + frame_index * 2; frame->data[2][y * frame->linesize[2] + x] = 64 + x + frame_index * 5; } } return frame; } static AVFrame* getAudioFrame(int sampleRate, int nbSamples, int nbChannels) { const constexpr float pi = 3.14159265358979323846264338327950288; // M_PI const float tincr = 2 * pi * 440.0 / sampleRate; float t = 0; AVFrame* frame = av_frame_alloc(); if (!frame) return nullptr; frame->format = AV_SAMPLE_FMT_S16; av_channel_layout_default(&frame->ch_layout, nbChannels); frame->nb_samples = nbSamples; frame->sample_rate = sampleRate; if (av_frame_get_buffer(frame, 0) < 0) { av_frame_free(&frame); return nullptr; } auto samples = reinterpret_cast<uint16_t*>(frame->data[0]); for (int i = 0; i < 200; ++i) { for (int j = 0; j < nbSamples; ++j) { samples[2 * j] = static_cast<int>(sin(t) * 10000); for (int k = 1; k < nbChannels; ++k) { samples[2 * j + k] = samples[2 * j]; } t += tincr; } } return frame; } void MediaEncoderTest::testMultiStream() { const constexpr int sampleRate = 48000; const constexpr int nbChannels = 2; const constexpr int width = 320; const constexpr int height = 240; auto vp8Codec = std::static_pointer_cast<jami::SystemVideoCodecInfo>( getSystemCodecContainer()->searchCodecByName("VP8", jami::MEDIA_VIDEO) ); auto opusCodec = std::static_pointer_cast<SystemAudioCodecInfo>( getSystemCodecContainer()->searchCodecByName("opus", jami::MEDIA_AUDIO) ); auto v = MediaStream("v", AV_PIX_FMT_YUV420P, rational<int>(1, 30), width, height, 1, 30); auto a = MediaStream("a", AV_SAMPLE_FMT_S16, rational<int>(1, sampleRate), sampleRate, nbChannels, 960); try { encoder_->openOutput("test.mkv"); encoder_->setOptions(a); CPPUNIT_ASSERT(encoder_->getStreamCount() == 1); int audioIdx = encoder_->addStream(*opusCodec.get()); CPPUNIT_ASSERT(audioIdx >= 0); encoder_->setOptions(v); CPPUNIT_ASSERT(encoder_->getStreamCount() == 2); int videoIdx = encoder_->addStream(*vp8Codec.get()); CPPUNIT_ASSERT(videoIdx >= 0); CPPUNIT_ASSERT(videoIdx != audioIdx); encoder_->setIOContext(nullptr); int sentSamples = 0; AVFrame* audio = nullptr; AVFrame* video = nullptr; for (int i = 0; i < 25; ++i) { audio = getAudioFrame(sampleRate, 0.02*sampleRate, nbChannels); CPPUNIT_ASSERT(audio); audio->pts = sentSamples; video = getVideoFrame(width, height, i); CPPUNIT_ASSERT(video); video->pts = i; CPPUNIT_ASSERT(encoder_->encode(audio, audioIdx) >= 0); sentSamples += audio->nb_samples; CPPUNIT_ASSERT(encoder_->encode(video, videoIdx) >= 0); av_frame_free(&audio); av_frame_free(&video); } CPPUNIT_ASSERT(encoder_->flush() >= 0); } catch (const MediaEncoderException& e) { CPPUNIT_FAIL(e.what()); } } }} // namespace jami::test RING_TEST_RUNNER(jami::test::MediaEncoderTest::name());
5,908
C++
.cpp
163
30.558282
108
0.637334
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,670
test_media_decoder.cpp
savoirfairelinux_jami-daemon/test/unitTest/media/test_media_decoder.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <cppunit/TestAssert.h> #include <cppunit/TestFixture.h> #include <cppunit/extensions/HelperMacros.h> #include "jami.h" #include "fileutils.h" #include "media/libav_deps.h" #include "media/media_buffer.h" #include "media/media_decoder.h" #include "media/media_device.h" #include "media/media_io_handle.h" #include "../../test_runner.h" namespace jami { namespace test { class MediaDecoderTest : public CppUnit::TestFixture { public: static std::string name() { return "media_decoder"; } void setUp(); void tearDown(); private: void testAudioFile(); CPPUNIT_TEST_SUITE(MediaDecoderTest); CPPUNIT_TEST(testAudioFile); CPPUNIT_TEST_SUITE_END(); void writeWav(); // writes a minimal wav file to test decoding std::unique_ptr<MediaDecoder> decoder_; std::string filename_ = "test.wav"; }; CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(MediaDecoderTest, MediaDecoderTest::name()); void MediaDecoderTest::setUp() { libjami::init(libjami::InitFlag(libjami::LIBJAMI_FLAG_DEBUG | libjami::LIBJAMI_FLAG_CONSOLE_LOG)); libav_utils::av_init(); } void MediaDecoderTest::tearDown() { dhtnet::fileutils::remove(filename_); libjami::fini(); } void MediaDecoderTest::testAudioFile() { if (!avcodec_find_decoder(AV_CODEC_ID_PCM_S16LE) || !avcodec_find_decoder(AV_CODEC_ID_PCM_S16BE)) return; // no way to test the wav file, since it is in pcm signed 16 writeWav(); decoder_.reset(new MediaDecoder([this](const std::shared_ptr<MediaFrame>&& f) mutable { CPPUNIT_ASSERT(f->pointer()->sample_rate == decoder_->getStream().sampleRate); CPPUNIT_ASSERT(f->pointer()->ch_layout.nb_channels == decoder_->getStream().nbChannels); })); DeviceParams dev; dev.input = filename_; CPPUNIT_ASSERT(decoder_->openInput(dev) >= 0); CPPUNIT_ASSERT(decoder_->setupAudio() >= 0); bool done = false; while (!done) { switch (decoder_->decode()) { case MediaDemuxer::Status::ReadError: CPPUNIT_ASSERT_MESSAGE("Decode error", false); done = true; break; case MediaDemuxer::Status::EndOfFile: done = true; break; case MediaDemuxer::Status::Success: default: break; } } CPPUNIT_ASSERT(done); } // write bytes to file using native endianness template<typename Word> static std::ostream& write(std::ostream& os, Word value, unsigned size) { for (; size; --size, value >>= 8) os.put(static_cast<char>(value & 0xFF)); return os; } void MediaDecoderTest::writeWav() { auto f = std::ofstream(filename_, std::ios::binary); f << "RIFF----WAVEfmt "; write(f, 16, 4); // no extension data write(f, 1, 2); // PCM integer samples write(f, 1, 2); // channels write(f, 8000, 4); // sample rate write(f, 8000 * 1 * 2, 4); // sample rate * channels * bytes per sample write(f, 4, 2); // data block size write(f, 2 * 8, 2); // bits per sample size_t dataChunk = f.tellp(); f << "data----"; // fill file with silence // make sure there is more than 1 AVFrame in the file for (int i = 0; i < 8192; ++i) write(f, 0, 2); size_t length = f.tellp(); f.seekp(dataChunk + 4); write(f, length - dataChunk + 8, 4); f.seekp(4); write(f, length - 8, 4); } }} // namespace jami::test RING_TEST_RUNNER(jami::test::MediaDecoderTest::name());
4,160
C++
.cpp
121
30.123967
102
0.671066
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,671
test_media_frame.cpp
savoirfairelinux_jami-daemon/test/unitTest/media/test_media_frame.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <cppunit/TestAssert.h> #include <cppunit/TestFixture.h> #include <cppunit/extensions/HelperMacros.h> extern "C" { #include <libavutil/frame.h> #include <libavutil/pixfmt.h> } #include "jami.h" #include "videomanager_interface.h" #include "media/audio/audio_format.h" #include "../../test_runner.h" namespace jami { namespace test { class MediaFrameTest : public CppUnit::TestFixture { public: static std::string name() { return "media_frame"; } void setUp(); void tearDown(); private: void testCopy(); void testMix(); CPPUNIT_TEST_SUITE(MediaFrameTest); CPPUNIT_TEST(testCopy); CPPUNIT_TEST(testMix); CPPUNIT_TEST_SUITE_END(); }; CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(MediaFrameTest, MediaFrameTest::name()); void MediaFrameTest::setUp() { libjami::init(libjami::InitFlag(libjami::LIBJAMI_FLAG_DEBUG | libjami::LIBJAMI_FLAG_CONSOLE_LOG)); } void MediaFrameTest::tearDown() { libjami::fini(); } void MediaFrameTest::testCopy() { // test allocation libjami::VideoFrame v1; v1.reserve(AV_PIX_FMT_YUV420P, 100, 100); v1.pointer()->data[0][0] = 42; CPPUNIT_ASSERT(v1.pointer()); // test frame referencing (different pointers, but same data) libjami::VideoFrame v2; v2.copyFrom(v1); CPPUNIT_ASSERT(v1.format() == v2.format()); CPPUNIT_ASSERT(v1.width() == v2.width()); CPPUNIT_ASSERT(v1.height() == v2.height()); CPPUNIT_ASSERT(v1.pointer() != v2.pointer()); CPPUNIT_ASSERT(v1.pointer()->data[0][0] == 42); CPPUNIT_ASSERT(v2.pointer()->data[0][0] == 42); } void MediaFrameTest::testMix() { const AudioFormat& format = AudioFormat::STEREO(); const int nbSamples = format.sample_rate / 50; auto a1 = std::make_unique<libjami::AudioFrame>(format, nbSamples); auto d1 = reinterpret_cast<int16_t*>(a1->pointer()->extended_data[0]); d1[0] = 0; d1[1] = 1; d1[2] = 3; d1[3] = -2; d1[4] = 5; d1[5] = std::numeric_limits<int16_t>::min(); d1[6] = std::numeric_limits<int16_t>::max(); auto a2 = std::make_unique<libjami::AudioFrame>(format, nbSamples); auto d2 = reinterpret_cast<int16_t*>(a2->pointer()->extended_data[0]); d2[0] = 0; d2[1] = 3; d2[2] = -1; d2[3] = 3; d2[4] = -6; d2[5] = -101; d2[6] = 101; a2->mix(*a1); CPPUNIT_ASSERT(d2[0] == 0); CPPUNIT_ASSERT(d2[1] == 4); CPPUNIT_ASSERT(d2[2] == 2); CPPUNIT_ASSERT(d2[3] == 1); CPPUNIT_ASSERT(d2[4] == -1); CPPUNIT_ASSERT(d2[5] == std::numeric_limits<int16_t>::min()); CPPUNIT_ASSERT(d2[6] == std::numeric_limits<int16_t>::max()); } }} // namespace jami::test RING_TEST_RUNNER(jami::test::MediaFrameTest::name());
3,408
C++
.cpp
104
29.413462
102
0.676202
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,672
testVideo_input.cpp
savoirfairelinux_jami-daemon/test/unitTest/media/video/testVideo_input.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <cppunit/TestAssert.h> #include <cppunit/TestFixture.h> #include <cppunit/extensions/HelperMacros.h> #include "test_runner.h" #include "media/video/video_input.h" #include "media_const.h" #include "jami.h" #include "manager.h" #include <map> #include <string> namespace jami { namespace test { class VideoInputTest : public CppUnit::TestFixture { public: static std::string name() { return "video_input"; } VideoInputTest() { libjami::init(libjami::InitFlag(libjami::LIBJAMI_FLAG_DEBUG | libjami::LIBJAMI_FLAG_CONSOLE_LOG)); libjami::start("jami-sample.yml"); } ~VideoInputTest() { libjami::fini(); } private: void testInput(); CPPUNIT_TEST_SUITE(VideoInputTest); CPPUNIT_TEST(testInput); CPPUNIT_TEST_SUITE_END(); }; CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(VideoInputTest, VideoInputTest::name()); void VideoInputTest::testInput() { static const std::string sep = libjami::Media::VideoProtocolPrefix::SEPARATOR; std::string resource = libjami::Media::VideoProtocolPrefix::DISPLAY + sep + std::string(getenv("DISPLAY") ?: ":0.0"); video::VideoInput video; libjami::switchInput("", "", resource); } } // namespace test } // namespace jami RING_TEST_RUNNER(jami::test::VideoInputTest::name());
2,025
C++
.cpp
57
32.350877
106
0.724156
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,673
test_video_scaler.cpp
savoirfairelinux_jami-daemon/test/unitTest/media/video/test_video_scaler.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <cppunit/TestAssert.h> #include <cppunit/TestFixture.h> #include <cppunit/extensions/HelperMacros.h> #include "jami.h" #include "videomanager_interface.h" #include "media/video/video_scaler.h" #include "../../../test_runner.h" namespace jami { namespace video { namespace test { class VideoScalerTest : public CppUnit::TestFixture { public: static std::string name() { return "video_scaler"; } void setUp(); void tearDown(); private: void testConvertFrame(); void testScale(); void testScaleWithAspect(); CPPUNIT_TEST_SUITE(VideoScalerTest); CPPUNIT_TEST(testConvertFrame); CPPUNIT_TEST(testScale); CPPUNIT_TEST(testScaleWithAspect); CPPUNIT_TEST_SUITE_END(); std::unique_ptr<VideoScaler> scaler_; }; CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(VideoScalerTest, VideoScalerTest::name()); void VideoScalerTest::setUp() { libjami::init(libjami::InitFlag(libjami::LIBJAMI_FLAG_DEBUG | libjami::LIBJAMI_FLAG_CONSOLE_LOG)); } void VideoScalerTest::tearDown() { libjami::fini(); } void VideoScalerTest::testConvertFrame() { scaler_.reset(new VideoScaler); libjami::VideoFrame input; input.reserve(AV_PIX_FMT_YUV420P, 100, 100); auto output = scaler_->convertFormat(input, AV_PIX_FMT_RGB24); CPPUNIT_ASSERT(static_cast<AVPixelFormat>(output->format()) == AV_PIX_FMT_RGB24); } void VideoScalerTest::testScale() { scaler_.reset(new VideoScaler); libjami::VideoFrame input, output; input.reserve(AV_PIX_FMT_YUV420P, 100, 100); output.reserve(AV_PIX_FMT_YUV420P, 200, 200); scaler_->scale(input, output); CPPUNIT_ASSERT(static_cast<AVPixelFormat>(output.format()) == AV_PIX_FMT_YUV420P); CPPUNIT_ASSERT(output.width() == 200); CPPUNIT_ASSERT(output.height() == 200); } void VideoScalerTest::testScaleWithAspect() { scaler_.reset(new VideoScaler); libjami::VideoFrame input, output; input.reserve(AV_PIX_FMT_YUV420P, 320, 240); // 4:3 output.reserve(AV_PIX_FMT_YUV420P, 640, 360); // 16:9 scaler_->scale_with_aspect(input, output); CPPUNIT_ASSERT(static_cast<AVPixelFormat>(output.format()) == AV_PIX_FMT_YUV420P); CPPUNIT_ASSERT(output.width() == 640); CPPUNIT_ASSERT(output.height() == 360); } }}} // namespace jami::test RING_TEST_RUNNER(jami::video::test::VideoScalerTest::name());
3,055
C++
.cpp
86
32.476744
102
0.732361
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,674
test_resampler.cpp
savoirfairelinux_jami-daemon/test/unitTest/media/audio/test_resampler.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <cppunit/TestAssert.h> #include <cppunit/TestFixture.h> #include <cppunit/extensions/HelperMacros.h> #include "jami.h" #include "videomanager_interface.h" #include "media/libav_deps.h" #include "media/audio/resampler.h" #include "../test_runner.h" namespace jami { namespace test { class ResamplerTest : public CppUnit::TestFixture { public: static std::string name() { return "resampler"; } void setUp(); void tearDown(); private: void testAudioFrame(); void testRematrix(); CPPUNIT_TEST_SUITE(ResamplerTest); CPPUNIT_TEST(testAudioFrame); CPPUNIT_TEST(testRematrix); CPPUNIT_TEST_SUITE_END(); std::unique_ptr<Resampler> resampler_; }; CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(ResamplerTest, ResamplerTest::name()); void ResamplerTest::setUp() { libjami::init(libjami::InitFlag(libjami::LIBJAMI_FLAG_DEBUG | libjami::LIBJAMI_FLAG_CONSOLE_LOG)); } void ResamplerTest::tearDown() { libjami::fini(); } void ResamplerTest::testAudioFrame() { const constexpr AudioFormat infmt(44100, 1); resampler_.reset(new Resampler); auto input = std::make_unique<libjami::AudioFrame>(infmt, 1024); CPPUNIT_ASSERT(input->pointer() && input->pointer()->data[0]); CPPUNIT_ASSERT(input->pointer()->data[0][0] == 0); libjami::AudioFrame out; auto output = out.pointer(); output->format = AV_SAMPLE_FMT_FLT; output->sample_rate = 48000; av_channel_layout_from_mask(&output->ch_layout, AV_CH_LAYOUT_STEREO); int ret = resampler_->resample(input->pointer(), output); CPPUNIT_ASSERT_MESSAGE(libav_utils::getError(ret).c_str(), ret >= 0); CPPUNIT_ASSERT(output && output->data[0]); CPPUNIT_ASSERT(output->data[0][0] == 0); } void ResamplerTest::testRematrix() { int ret = 0; const constexpr AudioFormat inFormat = AudioFormat(44100, 6); resampler_.reset(new Resampler); auto input = std::make_unique<libjami::AudioFrame>(inFormat, 882); CPPUNIT_ASSERT(input->pointer() && input->pointer()->data[0]); auto output1 = std::make_unique<libjami::AudioFrame>(AudioFormat::STEREO(), 960); CPPUNIT_ASSERT(output1->pointer() && output1->pointer()->data[0]); ret = resampler_->resample(input->pointer(), output1->pointer()); CPPUNIT_ASSERT_MESSAGE(libav_utils::getError(ret).c_str(), ret >= 0); CPPUNIT_ASSERT(output1->pointer() && output1->pointer()->data[0]); auto output2 = std::make_unique<libjami::AudioFrame>(AudioFormat::MONO(), 960); CPPUNIT_ASSERT(output2->pointer() && output2->pointer()->data[0]); ret = resampler_->resample(input->pointer(), output2->pointer()); CPPUNIT_ASSERT_MESSAGE(libav_utils::getError(ret).c_str(), ret >= 0); CPPUNIT_ASSERT(output2->pointer() && output2->pointer()->data[0]); } }} // namespace jami::test RING_TEST_RUNNER(jami::test::ResamplerTest::name());
3,570
C++
.cpp
89
36.820225
102
0.71441
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,675
test_audio_frame_resizer.cpp
savoirfairelinux_jami-daemon/test/unitTest/media/audio/test_audio_frame_resizer.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <cppunit/TestAssert.h> #include <cppunit/TestFixture.h> #include <cppunit/extensions/HelperMacros.h> #include "media/audio/audio_frame_resizer.h" #include "jami.h" #include "media/libav_deps.h" #include "media/media_buffer.h" #include "../../../test_runner.h" #include <stdexcept> namespace jami { namespace test { class AudioFrameResizerTest : public CppUnit::TestFixture { public: static std::string name() { return "audio_frame_resizer"; } private: void testSameSize(); void testBiggerInput(); void testBiggerOutput(); void testDifferentFormat(); void gotFrame(std::shared_ptr<AudioFrame>&& framePtr); std::shared_ptr<AudioFrame> getFrame(int n); CPPUNIT_TEST_SUITE(AudioFrameResizerTest); CPPUNIT_TEST(testSameSize); CPPUNIT_TEST(testBiggerInput); CPPUNIT_TEST(testBiggerOutput); CPPUNIT_TEST(testDifferentFormat); CPPUNIT_TEST_SUITE_END(); std::shared_ptr<AudioFrameResizer> q_; AudioFormat format_ = AudioFormat::STEREO(); int outputSize_ = 960; }; CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(AudioFrameResizerTest, AudioFrameResizerTest::name()); void AudioFrameResizerTest::gotFrame(std::shared_ptr<AudioFrame>&& framePtr) { CPPUNIT_ASSERT(framePtr && framePtr->pointer()); CPPUNIT_ASSERT(framePtr->pointer()->nb_samples == outputSize_); } std::shared_ptr<AudioFrame> AudioFrameResizerTest::getFrame(int n) { auto frame = std::make_shared<AudioFrame>(); frame->pointer()->format = format_.sampleFormat; frame->pointer()->sample_rate = format_.sample_rate; av_channel_layout_default(&frame->pointer()->ch_layout, format_.nb_channels); frame->pointer()->nb_samples = n; CPPUNIT_ASSERT(av_frame_get_buffer(frame->pointer(), 0) >= 0); return frame; } void AudioFrameResizerTest::testSameSize() { // input.nb_samples == output.nb_samples q_.reset(new AudioFrameResizer(format_, outputSize_, [this](std::shared_ptr<AudioFrame>&& f){ gotFrame(std::move(f)); })); auto in = getFrame(outputSize_); // gotFrame should be called after this CPPUNIT_ASSERT_NO_THROW(q_->enqueue(std::move(in))); CPPUNIT_ASSERT(q_->samples() == 0); } void AudioFrameResizerTest::testBiggerInput() { // input.nb_samples > output.nb_samples q_.reset(new AudioFrameResizer(format_, outputSize_, [this](std::shared_ptr<AudioFrame>&& f){ gotFrame(std::move(f)); })); auto in = getFrame(outputSize_ + 100); // gotFrame should be called after this CPPUNIT_ASSERT_NO_THROW(q_->enqueue(std::move(in))); CPPUNIT_ASSERT(q_->samples() == 100); } void AudioFrameResizerTest::testBiggerOutput() { // input.nb_samples < output.nb_samples q_.reset(new AudioFrameResizer(format_, outputSize_, [this](std::shared_ptr<AudioFrame>&& f){ gotFrame(std::move(f)); })); auto in = getFrame(outputSize_ - 100); CPPUNIT_ASSERT_NO_THROW(q_->enqueue(std::move(in))); CPPUNIT_ASSERT(q_->samples() == outputSize_ - 100); // gotFrame should be called after this CPPUNIT_ASSERT_NO_THROW(q_->enqueue(std::move(in))); // pushed 2 frames of (outputSize_ - 100) samples and got 1 frame CPPUNIT_ASSERT(q_->samples() == outputSize_ - 200); } void AudioFrameResizerTest::testDifferentFormat() { // frame format != q_->format_ q_.reset(new AudioFrameResizer(format_, outputSize_, [this](std::shared_ptr<AudioFrame>&& f){ gotFrame(std::move(f)); })); auto in = getFrame(outputSize_-27); q_->enqueue(std::move(in)); CPPUNIT_ASSERT(q_->samples()==outputSize_-27); q_->setFormat(AudioFormat::MONO(), 960); CPPUNIT_ASSERT(q_->samples() == 0); } }} // namespace jami::test RING_TEST_RUNNER(jami::test::AudioFrameResizerTest::name());
4,415
C++
.cpp
110
36.9
126
0.714652
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,676
presence.cpp
savoirfairelinux_jami-daemon/test/unitTest/presence/presence.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <cppunit/TestAssert.h> #include <cppunit/TestFixture.h> #include <cppunit/extensions/HelperMacros.h> #include <condition_variable> #include <filesystem> #include <string> #include "../../test_runner.h" #include "account_const.h" #include "common.h" #include "conversation/conversationcommon.h" #include "manager.h" #include "media_const.h" #include "sip/sipcall.h" using namespace std::literals::chrono_literals; namespace jami { namespace test { struct UserData { std::map<std::string, int> status; std::map<std::string, std::string> statusNote; std::string conversationId; bool requestReceived {false}; }; class PresenceTest : public CppUnit::TestFixture { public: ~PresenceTest() { libjami::fini(); } static std::string name() { return "PresenceTest"; } void setUp(); void tearDown(); std::string aliceId; std::string bobId; std::string carlaId; UserData aliceData_; UserData bobData_; UserData carlaData_; std::mutex mtx; std::unique_lock<std::mutex> lk {mtx}; std::condition_variable cv; private: void connectSignals(); void enableCarla(); void testGetSetSubscriptions(); void testPresenceStatus(); void testPresenceStatusNote(); void testPresenceInvalidStatusNote(); void testPresenceStatusNoteBeforeConnection(); CPPUNIT_TEST_SUITE(PresenceTest); CPPUNIT_TEST(testGetSetSubscriptions); CPPUNIT_TEST(testPresenceStatus); CPPUNIT_TEST(testPresenceStatusNote); CPPUNIT_TEST(testPresenceInvalidStatusNote); CPPUNIT_TEST(testPresenceStatusNoteBeforeConnection); CPPUNIT_TEST_SUITE_END(); }; CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(PresenceTest, PresenceTest::name()); void PresenceTest::setUp() { // Init daemon libjami::init( libjami::InitFlag(libjami::LIBJAMI_FLAG_DEBUG | libjami::LIBJAMI_FLAG_CONSOLE_LOG)); if (not Manager::instance().initialized) CPPUNIT_ASSERT(libjami::start("jami-sample.yml")); auto actors = load_actors("actors/alice-bob-carla.yml"); aliceId = actors["alice"]; bobId = actors["bob"]; carlaId = actors["carla"]; aliceData_ = {}; bobData_ = {}; carlaData_ = {}; Manager::instance().sendRegister(carlaId, false); wait_for_announcement_of({aliceId, bobId}); } void PresenceTest::tearDown() { wait_for_removal_of({aliceId, bobId, carlaId}); } void PresenceTest::connectSignals() { std::map<std::string, std::shared_ptr<libjami::CallbackWrapperBase>> confHandlers; confHandlers.insert(libjami::exportable_callback<libjami::ConversationSignal::ConversationReady>( [&](const std::string& accountId, const std::string& conversationId) { if (accountId == aliceId) aliceData_.conversationId = conversationId; else if (accountId == bobId) bobData_.conversationId = conversationId; else if (accountId == carlaId) carlaData_.conversationId = conversationId; cv.notify_one(); })); confHandlers.insert( libjami::exportable_callback<libjami::ConversationSignal::ConversationRequestReceived>( [&](const std::string& accountId, const std::string& /*conversationId*/, std::map<std::string, std::string> /*metadatas*/) { if (accountId == aliceId) aliceData_.requestReceived = true; if (accountId == bobId) bobData_.requestReceived = true; if (accountId == carlaId) carlaData_.requestReceived = true; cv.notify_one(); })); confHandlers.insert( libjami::exportable_callback<libjami::PresenceSignal::NewBuddyNotification>( [&](const std::string& accountId, const std::string& peerId, int status, const std::string& note) { if (accountId == aliceId) { aliceData_.status[peerId] = status; aliceData_.statusNote[peerId] = note; } else if (accountId == bobId) { bobData_.status[peerId] = status; bobData_.statusNote[peerId] = note; } else if (accountId == carlaId) { carlaData_.status[peerId] = status; carlaData_.statusNote[peerId] = note; } cv.notify_one(); })); libjami::registerSignalHandlers(confHandlers); } void PresenceTest::enableCarla() { auto carlaAccount = Manager::instance().getAccount<JamiAccount>(carlaId); // Enable carla std::map<std::string, std::shared_ptr<libjami::CallbackWrapperBase>> confHandlers; bool carlaConnected = false; confHandlers.insert( libjami::exportable_callback<libjami::ConfigurationSignal::VolatileDetailsChanged>( [&](const std::string&, const std::map<std::string, std::string>&) { auto details = carlaAccount->getVolatileAccountDetails(); auto deviceAnnounced = details[libjami::Account::VolatileProperties::DEVICE_ANNOUNCED]; if (deviceAnnounced == "true") { carlaConnected = true; cv.notify_one(); } })); libjami::registerSignalHandlers(confHandlers); Manager::instance().sendRegister(carlaId, true); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&] { return carlaConnected; })); confHandlers.clear(); libjami::unregisterSignalHandlers(); } void PresenceTest::testGetSetSubscriptions() { auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto bobUri = bobAccount->getUsername(); auto carlaAccount = Manager::instance().getAccount<JamiAccount>(carlaId); auto carlaUri = carlaAccount->getUsername(); connectSignals(); CPPUNIT_ASSERT(libjami::getSubscriptions(aliceId).empty()); libjami::setSubscriptions(aliceId, {bobUri, carlaUri}); auto subscriptions = libjami::getSubscriptions(aliceId); CPPUNIT_ASSERT(subscriptions.size() == 2); auto checkSub = [&](const std::string& uri) { return std::find_if(subscriptions.begin(), subscriptions.end(), [&](const auto& sub) { return sub.at("Buddy") == uri; }) != subscriptions.end(); }; CPPUNIT_ASSERT(checkSub(bobUri) && checkSub(carlaUri)); } void PresenceTest::testPresenceStatus() { connectSignals(); auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto aliceUri = aliceAccount->getUsername(); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto bobUri = bobAccount->getUsername(); auto carlaAccount = Manager::instance().getAccount<JamiAccount>(carlaId); auto carlaUri = carlaAccount->getUsername(); // Track Presence aliceAccount->trackBuddyPresence(bobUri, true); aliceAccount->trackBuddyPresence(carlaUri, true); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return aliceData_.status.find(bobUri) != aliceData_.status.end() && aliceData_.status[bobUri] == 1; })); CPPUNIT_ASSERT(aliceData_.status.find(carlaUri) == aliceData_.status.end()); // For now, still offline so no change // Carla is now online Manager::instance().sendRegister(carlaId, true); CPPUNIT_ASSERT(cv.wait_for(lk, 60s, [&]() { return aliceData_.status.find(carlaUri) != aliceData_.status.end() && aliceData_.status[carlaUri] == 1; })); // Start conversation libjami::startConversation(aliceId); cv.wait_for(lk, 30s, [&]() { return !aliceData_.conversationId.empty(); }); libjami::addConversationMember(aliceId, aliceData_.conversationId, bobUri); libjami::addConversationMember(aliceId, aliceData_.conversationId, carlaUri); CPPUNIT_ASSERT(cv.wait_for(lk, 60s, [&]() { return bobData_.requestReceived && carlaData_.requestReceived; })); libjami::acceptConversationRequest(bobId, aliceData_.conversationId); libjami::acceptConversationRequest(carlaId, aliceData_.conversationId); // Should connect to peers CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return aliceData_.status[bobUri] == 2 && aliceData_.status[carlaUri] == 2; })); // Carla disconnects, should just let the presence on the DHT for a few minutes Manager::instance().sendRegister(carlaId, false); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return aliceData_.status[carlaUri] == 1; })); } void PresenceTest::testPresenceStatusNote() { enableCarla(); connectSignals(); auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto aliceUri = aliceAccount->getUsername(); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto bobUri = bobAccount->getUsername(); auto carlaAccount = Manager::instance().getAccount<JamiAccount>(carlaId); auto carlaUri = carlaAccount->getUsername(); // Track Presence aliceAccount->trackBuddyPresence(bobUri, true); bobAccount->trackBuddyPresence(aliceUri, true); aliceAccount->trackBuddyPresence(carlaUri, true); carlaAccount->trackBuddyPresence(aliceUri, true); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return aliceData_.status.find(bobUri) != aliceData_.status.end() && aliceData_.status[bobUri] == 1 && aliceData_.status.find(carlaUri) != aliceData_.status.end() && aliceData_.status[carlaUri] == 1; })); // Start conversation libjami::startConversation(aliceId); cv.wait_for(lk, 30s, [&]() { return !aliceData_.conversationId.empty(); }); libjami::addConversationMember(aliceId, aliceData_.conversationId, bobUri); libjami::addConversationMember(aliceId, aliceData_.conversationId, carlaUri); CPPUNIT_ASSERT(cv.wait_for(lk, 60s, [&]() { return bobData_.requestReceived && carlaData_.requestReceived; })); libjami::acceptConversationRequest(bobId, aliceData_.conversationId); libjami::acceptConversationRequest(carlaId, aliceData_.conversationId); // Should connect to peers CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return aliceData_.status[bobUri] == 2 && aliceData_.status[carlaUri] == 2; })); // Alice sends a status note, should be received by Bob and Carla libjami::publish(aliceId, true, "Testing Jami"); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData_.statusNote.find(aliceUri) != bobData_.statusNote.end() && bobData_.statusNote[aliceUri] == "Testing Jami" && carlaData_.statusNote.find(aliceUri) != carlaData_.statusNote.end() && carlaData_.statusNote[aliceUri] == "Testing Jami"; })); } void PresenceTest::testPresenceInvalidStatusNote() { enableCarla(); connectSignals(); auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto aliceUri = aliceAccount->getUsername(); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto bobUri = bobAccount->getUsername(); auto carlaAccount = Manager::instance().getAccount<JamiAccount>(carlaId); auto carlaUri = carlaAccount->getUsername(); // Track Presence aliceAccount->trackBuddyPresence(bobUri, true); bobAccount->trackBuddyPresence(aliceUri, true); aliceAccount->trackBuddyPresence(carlaUri, true); carlaAccount->trackBuddyPresence(aliceUri, true); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return aliceData_.status.find(bobUri) != aliceData_.status.end() && aliceData_.status[bobUri] == 1 && aliceData_.status.find(carlaUri) != aliceData_.status.end() && aliceData_.status[carlaUri] == 1; })); // Start conversation libjami::startConversation(aliceId); cv.wait_for(lk, 30s, [&]() { return !aliceData_.conversationId.empty(); }); libjami::addConversationMember(aliceId, aliceData_.conversationId, bobUri); libjami::addConversationMember(aliceId, aliceData_.conversationId, carlaUri); CPPUNIT_ASSERT(cv.wait_for(lk, 60s, [&]() { return bobData_.requestReceived && carlaData_.requestReceived; })); libjami::acceptConversationRequest(bobId, aliceData_.conversationId); libjami::acceptConversationRequest(carlaId, aliceData_.conversationId); // Should connect to peers CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return aliceData_.status[bobUri] == 2 && aliceData_.status[carlaUri] == 2; })); // Alice sends a status note that will generate an invalid XML message libjami::publish(aliceId, true, "Testing<BAD>"); CPPUNIT_ASSERT(!cv.wait_for(lk, 10s, [&]() { return bobData_.statusNote.find(aliceUri) != bobData_.statusNote.end() && bobData_.statusNote[aliceUri] == "Testing<BAD>" && carlaData_.statusNote.find(aliceUri) != carlaData_.statusNote.end() && carlaData_.statusNote[aliceUri] == "Testing<BAD>"; })); } void PresenceTest::testPresenceStatusNoteBeforeConnection() { enableCarla(); connectSignals(); auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto aliceUri = aliceAccount->getUsername(); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto bobUri = bobAccount->getUsername(); auto carlaAccount = Manager::instance().getAccount<JamiAccount>(carlaId); auto carlaUri = carlaAccount->getUsername(); // Track Presence aliceAccount->trackBuddyPresence(bobUri, true); bobAccount->trackBuddyPresence(aliceUri, true); aliceAccount->trackBuddyPresence(carlaUri, true); carlaAccount->trackBuddyPresence(aliceUri, true); libjami::publish(aliceId, true, "Testing Jami"); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return aliceData_.status.find(bobUri) != aliceData_.status.end() && aliceData_.status[bobUri] == 1 && aliceData_.status.find(carlaUri) != aliceData_.status.end() && aliceData_.status[carlaUri] == 1; })); // Start conversation libjami::startConversation(aliceId); cv.wait_for(lk, 30s, [&]() { return !aliceData_.conversationId.empty(); }); libjami::addConversationMember(aliceId, aliceData_.conversationId, bobUri); libjami::addConversationMember(aliceId, aliceData_.conversationId, carlaUri); CPPUNIT_ASSERT(cv.wait_for(lk, 60s, [&]() { return bobData_.requestReceived && carlaData_.requestReceived; })); libjami::acceptConversationRequest(bobId, aliceData_.conversationId); libjami::acceptConversationRequest(carlaId, aliceData_.conversationId); // Should connect to peers CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return aliceData_.status[bobUri] == 2 && aliceData_.status[carlaUri] == 2; })); // Alice sends a status note, should be received by Bob and Carla CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData_.statusNote.find(aliceUri) != bobData_.statusNote.end() && bobData_.statusNote[aliceUri] == "Testing Jami" && carlaData_.statusNote.find(aliceUri) != carlaData_.statusNote.end() && carlaData_.statusNote[aliceUri] == "Testing Jami"; })); } } // namespace test } // namespace jami RING_TEST_RUNNER(jami::test::PresenceTest::name())
15,958
C++
.cpp
353
38.923513
136
0.683049
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,677
plugins.cpp
savoirfairelinux_jami-daemon/test/unitTest/plugins/plugins.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <cppunit/TestAssert.h> #include <cppunit/TestFixture.h> #include <cppunit/extensions/HelperMacros.h> #include <condition_variable> #include <opendht/crypto.h> #include <filesystem> #include <memory> #include <string> #include "manager.h" #include "plugin/jamipluginmanager.h" #include "plugin/pluginsutils.h" #include "jamidht/jamiaccount.h" #include "../../test_runner.h" #include "jami.h" #include "fileutils.h" #include "jami/media_const.h" #include "account_const.h" #include "sip/sipcall.h" #include "call_const.h" #include "common.h" #include <yaml-cpp/yaml.h> using namespace libjami::Account; namespace jami { namespace test { struct CallData { struct Signal { Signal(const std::string& name, const std::string& event = {}) : name_(std::move(name)) , event_(std::move(event)) {}; std::string name_ {}; std::string event_ {}; }; CallData() = default; CallData(CallData&& other) = delete; CallData(const CallData& other) { accountId_ = std::move(other.accountId_); listeningPort_ = other.listeningPort_; userName_ = std::move(other.userName_); alias_ = std::move(other.alias_); callId_ = std::move(other.callId_); signals_ = std::move(other.signals_); }; std::string accountId_ {}; std::string userName_ {}; std::string alias_ {}; uint16_t listeningPort_ {0}; std::string toUri_ {}; std::string callId_ {}; std::vector<Signal> signals_; std::condition_variable cv_ {}; std::mutex mtx_; }; class PluginsTest : public CppUnit::TestFixture { public: PluginsTest() { // Init daemon libjami::init(libjami::InitFlag(libjami::LIBJAMI_FLAG_DEBUG | libjami::LIBJAMI_FLAG_CONSOLE_LOG)); if (not Manager::instance().initialized) CPPUNIT_ASSERT(libjami::start("jami-sample.yml")); } ~PluginsTest() { libjami::fini(); } static std::string name() { return "Plugins"; } void setUp(); void tearDown(); CallData aliceData; CallData bobData; private: static bool waitForSignal(CallData& callData, const std::string& signal, const std::string& expectedEvent = {}); // Event/Signal handlers static void onCallStateChange(const std::string& accountId, const std::string& callId, const std::string& state, CallData& callData); static void onIncomingCallWithMedia(const std::string& accountId, const std::string& callId, const std::vector<libjami::MediaMap> mediaList, CallData& callData); std::string name_{}; std::string jplPath_{}; std::string certPath_{}; std::string pluginCertNotFound_{}; std::string pluginNotSign_{}; std::string pluginFileNotSign_{}; std::string pluginManifestChanged_{}; std::string pluginNotSignByIssuer_{}; std::string pluginNotFoundPath_{}; std::unique_ptr<dht::crypto::Certificate> cert_{}; std::string installationPath_{}; std::vector<std::string> mediaHandlers_{}; std::vector<std::string> chatHandlers_{}; void testEnable(); void testCertificateVerification(); void testSignatureVerification(); void testLoad(); void testInstallAndLoad(); void testHandlers(); void testDetailsAndPreferences(); void testTranslations(); void testCall(); void testMessage(); CPPUNIT_TEST_SUITE(PluginsTest); CPPUNIT_TEST(testEnable); CPPUNIT_TEST(testCertificateVerification); CPPUNIT_TEST(testSignatureVerification); CPPUNIT_TEST(testLoad); CPPUNIT_TEST(testInstallAndLoad); CPPUNIT_TEST(testHandlers); CPPUNIT_TEST(testDetailsAndPreferences); CPPUNIT_TEST(testTranslations); CPPUNIT_TEST(testCall); CPPUNIT_TEST(testMessage); CPPUNIT_TEST_SUITE_END(); }; CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(PluginsTest, PluginsTest::name()); void PluginsTest::onIncomingCallWithMedia(const std::string& accountId, const std::string& callId, const std::vector<libjami::MediaMap> mediaList, CallData& callData) { CPPUNIT_ASSERT_EQUAL(callData.accountId_, accountId); JAMI_INFO("Signal [%s] - user [%s] - call [%s] - media count [%lu]", libjami::CallSignal::IncomingCallWithMedia::name, callData.alias_.c_str(), callId.c_str(), mediaList.size()); // NOTE. // We shouldn't access shared_ptr<Call> as this event is supposed to mimic // the client, and the client have no access to this type. But here, we only // needed to check if the call exists. This is the most straightforward and // reliable way to do it until we add a new API (like hasCall(id)). if (not Manager::instance().getCallFromCallID(callId)) { JAMI_WARN("Call with ID [%s] does not exist!", callId.c_str()); callData.callId_ = {}; return; } std::unique_lock lock {callData.mtx_}; callData.callId_ = callId; callData.signals_.emplace_back(CallData::Signal(libjami::CallSignal::IncomingCallWithMedia::name)); callData.cv_.notify_one(); } void PluginsTest::onCallStateChange(const std::string& accountId, const std::string& callId, const std::string& state, CallData& callData) { JAMI_INFO("Signal [%s] - user [%s] - call [%s] - state [%s]", libjami::CallSignal::StateChange::name, callData.alias_.c_str(), callId.c_str(), state.c_str()); CPPUNIT_ASSERT(accountId == callData.accountId_); { std::unique_lock lock {callData.mtx_}; callData.signals_.emplace_back( CallData::Signal(libjami::CallSignal::StateChange::name, state)); } // NOTE. Only states that we are interested in will notify the CV. // If this unit test is modified to process other states, they must // be added here. if (state == "CURRENT" or state == "OVER" or state == "HUNGUP" or state == "RINGING") { callData.cv_.notify_one(); } } void PluginsTest::setUp() { auto actors = load_actors_and_wait_for_announcement("actors/alice-bob-no-upnp.yml"); aliceData.accountId_ = actors["alice"]; bobData.accountId_ = actors["bob"]; // Configure Alice { CPPUNIT_ASSERT(not aliceData.accountId_.empty()); auto const& account = Manager::instance().getAccount<Account>( aliceData.accountId_); aliceData.userName_ = account->getAccountDetails()[ConfProperties::USERNAME]; aliceData.alias_ = account->getAccountDetails()[ConfProperties::ALIAS]; } // Configure Bob { CPPUNIT_ASSERT(not bobData.accountId_.empty()); auto const& account = Manager::instance().getAccount<Account>( bobData.accountId_); bobData.userName_ = account->getAccountDetails()[ConfProperties::USERNAME]; bobData.alias_ = account->getAccountDetails()[ConfProperties::ALIAS]; } std::map<std::string, std::shared_ptr<libjami::CallbackWrapperBase>> signalHandlers; // Insert needed signal handlers. signalHandlers.insert(libjami::exportable_callback<libjami::CallSignal::IncomingCallWithMedia>( [&](const std::string& accountId, const std::string& callId, const std::string&, const std::vector<libjami::MediaMap> mediaList) { if (aliceData.accountId_ == accountId) onIncomingCallWithMedia(accountId, callId, mediaList, aliceData); else if (bobData.accountId_ == accountId) onIncomingCallWithMedia(accountId, callId, mediaList, bobData); })); signalHandlers.insert( libjami::exportable_callback<libjami::CallSignal::StateChange>([&](const std::string& accountId, const std::string& callId, const std::string& state, signed) { if (aliceData.accountId_ == accountId) onCallStateChange(accountId, callId, state, aliceData); else if (bobData.accountId_ == accountId) onCallStateChange(accountId, callId, state, bobData); })); libjami::registerSignalHandlers(signalHandlers); std::ifstream file("plugins/plugin.yml"); assert(file.is_open()); YAML::Node node = YAML::Load(file); assert(node.IsMap()); name_ = node["plugin"].as<std::string>(); certPath_ = node["cert"].as<std::string>(); cert_ = std::make_unique<dht::crypto::Certificate>(fileutils::loadFile(node["jplDirectory"].as<std::string>() + DIR_SEPARATOR_CH + certPath_)); dht::crypto::TrustList trust; trust.add(*cert_); jplPath_ = node["jplDirectory"].as<std::string>() + DIR_SEPARATOR_CH + name_ + ".jpl"; installationPath_ = fileutils::get_data_dir() / "plugins" / name_; mediaHandlers_ = node["mediaHandlers"].as<std::vector<std::string>>(); chatHandlers_ = node["chatHandlers"].as<std::vector<std::string>>(); pluginNotFoundPath_ = node["jplDirectory"].as<std::string>() + DIR_SEPARATOR_CH + "fakePlugin.jpl"; pluginCertNotFound_ = node["jplDirectory"].as<std::string>() + DIR_SEPARATOR_CH + node["pluginCertNotFound"].as<std::string>() + ".jpl"; pluginNotSign_ = node["jplDirectory"].as<std::string>() + DIR_SEPARATOR_CH + node["pluginNotSign"].as<std::string>() + ".jpl"; pluginFileNotSign_ = node["jplDirectory"].as<std::string>() + DIR_SEPARATOR_CH + node["pluginFileNotSign"].as<std::string>() + ".jpl"; pluginManifestChanged_ = node["jplDirectory"].as<std::string>() + DIR_SEPARATOR_CH + node["pluginManifestChanged"].as<std::string>() + ".jpl"; pluginNotSignByIssuer_ = node["jplDirectory"].as<std::string>() + DIR_SEPARATOR_CH + node["pluginNotSignByIssuer"].as<std::string>() + ".jpl"; } void PluginsTest::tearDown() { libjami::unregisterSignalHandlers(); wait_for_removal_of({aliceData.accountId_, bobData.accountId_}); } void PluginsTest::testEnable() { Manager::instance().pluginPreferences.setPluginsEnabled(true); CPPUNIT_ASSERT(Manager::instance().pluginPreferences.getPluginsEnabled()); Manager::instance().pluginPreferences.setPluginsEnabled(false); CPPUNIT_ASSERT(!Manager::instance().pluginPreferences.getPluginsEnabled()); } void PluginsTest::testSignatureVerification() { // Test valid case Manager::instance().pluginPreferences.setPluginsEnabled(true); CPPUNIT_ASSERT(Manager::instance().getJamiPluginManager().checkPluginSignatureValidity(jplPath_, cert_.get())); CPPUNIT_ASSERT(Manager::instance().getJamiPluginManager().checkPluginSignatureFile(jplPath_)); CPPUNIT_ASSERT(Manager::instance().getJamiPluginManager().checkPluginSignature(jplPath_, cert_.get())); std::string pluginNotFoundPath = "fakePlugin.jpl"; // Test with a plugin that does not exist CPPUNIT_ASSERT(!Manager::instance().getJamiPluginManager().checkPluginSignatureFile(pluginNotFoundPath_)); CPPUNIT_ASSERT(!Manager::instance().getJamiPluginManager().checkPluginSignature(pluginNotFoundPath_, cert_.get())); // Test with a plugin that does not have a signature CPPUNIT_ASSERT(!Manager::instance().getJamiPluginManager().checkPluginSignatureFile(pluginNotSign_)); // Test with a plugin that does not have a file not signed CPPUNIT_ASSERT(!Manager::instance().getJamiPluginManager().checkPluginSignatureFile(pluginFileNotSign_)); auto notCertSign = std::make_unique<dht::crypto::Certificate>(); // Test with wrong certificate CPPUNIT_ASSERT(!Manager::instance().getJamiPluginManager().checkPluginSignatureValidity(jplPath_, notCertSign.get())); // Test with wrong signature CPPUNIT_ASSERT(!Manager::instance().getJamiPluginManager().checkPluginSignatureValidity(pluginManifestChanged_, cert_.get())); } void PluginsTest::testCertificateVerification() { std::string pluginNotFoundPath = "fakePlugin.jpl"; Manager::instance().pluginPreferences.setPluginsEnabled(true); auto pluginCert = PluginUtils::readPluginCertificateFromArchive(jplPath_); Manager::instance().getJamiPluginManager().addPluginAuthority(*pluginCert); CPPUNIT_ASSERT(Manager::instance().getJamiPluginManager().checkPluginCertificate(jplPath_, true)->toString() == pluginCert->toString()); CPPUNIT_ASSERT(Manager::instance().getJamiPluginManager().checkPluginCertificate(jplPath_, false)->toString() == pluginCert->toString()); // create a plugin with not the same certificate auto pluginCertNotSignByIssuer = PluginUtils::readPluginCertificateFromArchive(pluginNotSignByIssuer_); CPPUNIT_ASSERT(Manager::instance().getJamiPluginManager().checkPluginCertificate(pluginNotSignByIssuer_, true)->toString() == pluginCertNotSignByIssuer->toString()); // Test with a plugin that does not exist CPPUNIT_ASSERT(!Manager::instance().getJamiPluginManager().checkPluginCertificate(pluginNotFoundPath, false)); // Test with a plugin that does not have a certificate CPPUNIT_ASSERT(!Manager::instance().getJamiPluginManager().checkPluginCertificate(pluginCertNotFound_, false)); CPPUNIT_ASSERT(!Manager::instance().getJamiPluginManager().checkPluginCertificate(pluginNotSignByIssuer_, false)); } void PluginsTest::testLoad() { Manager::instance().pluginPreferences.setPluginsEnabled(true); auto loadedPlugins = Manager::instance().getJamiPluginManager().getLoadedPlugins(); CPPUNIT_ASSERT(loadedPlugins.empty()); Manager::instance().getJamiPluginManager().installPlugin(jplPath_, true); Manager::instance().getJamiPluginManager().loadPlugins(); loadedPlugins = Manager::instance().getJamiPluginManager().getLoadedPlugins(); CPPUNIT_ASSERT(!loadedPlugins.empty()); } void PluginsTest::testInstallAndLoad() { Manager::instance().pluginPreferences.setPluginsEnabled(true); CPPUNIT_ASSERT(!Manager::instance().getJamiPluginManager().installPlugin(jplPath_, true)); auto installedPlugins = Manager::instance().getJamiPluginManager().getInstalledPlugins(); CPPUNIT_ASSERT(!installedPlugins.empty()); CPPUNIT_ASSERT(std::find(installedPlugins.begin(), installedPlugins.end(), installationPath_) != installedPlugins.end()); auto loadedPlugins = Manager::instance().getJamiPluginManager().getLoadedPlugins(); CPPUNIT_ASSERT(!loadedPlugins.empty()); CPPUNIT_ASSERT(std::find(loadedPlugins.begin(), loadedPlugins.end(), installationPath_) != loadedPlugins.end()); CPPUNIT_ASSERT(Manager::instance().getJamiPluginManager().unloadPlugin(installationPath_)); loadedPlugins = Manager::instance().getJamiPluginManager().getLoadedPlugins(); CPPUNIT_ASSERT(std::find(loadedPlugins.begin(), loadedPlugins.end(), installationPath_) == loadedPlugins.end()); CPPUNIT_ASSERT(!Manager::instance().getJamiPluginManager().uninstallPlugin(installationPath_)); installedPlugins = Manager::instance().getJamiPluginManager().getInstalledPlugins(); CPPUNIT_ASSERT(std::find(installedPlugins.begin(), installedPlugins.end(), installationPath_) == installedPlugins.end()); } void PluginsTest::testHandlers() { Manager::instance().pluginPreferences.setPluginsEnabled(true); Manager::instance().getJamiPluginManager().installPlugin(jplPath_, true); auto mediaHandlers = Manager::instance().getJamiPluginManager().getCallServicesManager().getCallMediaHandlers(); auto chatHandlers = Manager::instance().getJamiPluginManager().getChatServicesManager().getChatHandlers(); auto handlerLoaded = mediaHandlers_.size() + chatHandlers_.size(); // number of handlers expected for (auto handler : mediaHandlers) { auto details = Manager::instance().getJamiPluginManager().getCallServicesManager().getCallMediaHandlerDetails(handler); // check details expected for the test plugin if(std::find(mediaHandlers_.begin(), mediaHandlers_.end(), details["name"]) != mediaHandlers_.end()) { handlerLoaded--; } } for (auto handler : chatHandlers) { auto details = Manager::instance().getJamiPluginManager().getChatServicesManager().getChatHandlerDetails(handler); // check details expected for the test plugin if(std::find(chatHandlers_.begin(), chatHandlers_.end(), details["name"]) != chatHandlers_.end()) { handlerLoaded--; } } CPPUNIT_ASSERT(!handlerLoaded); // All expected handlers were found CPPUNIT_ASSERT(!Manager::instance().getJamiPluginManager().uninstallPlugin(installationPath_)); } void PluginsTest::testDetailsAndPreferences() { Manager::instance().pluginPreferences.setPluginsEnabled(true); Manager::instance().getJamiPluginManager().installPlugin(jplPath_, true); // Unload now to avoid reloads when changing the preferences Manager::instance().getJamiPluginManager().unloadPlugin(installationPath_); // Details auto details = Manager::instance().getJamiPluginManager().getPluginDetails(installationPath_); CPPUNIT_ASSERT(details["name"] == name_); // Get-set-reset - no account auto preferences = Manager::instance().getJamiPluginManager().getPluginPreferences(installationPath_, ""); CPPUNIT_ASSERT(!preferences.empty()); auto preferencesValuesOrig = Manager::instance().getJamiPluginManager().getPluginPreferencesValuesMap(installationPath_, ""); std::string preferenceNewValue = aliceData.accountId_; auto key = preferences[0]["key"]; CPPUNIT_ASSERT(Manager::instance().getJamiPluginManager().setPluginPreference(installationPath_, "", key, preferenceNewValue)); // Test global preference change auto preferencesValuesNew = Manager::instance().getJamiPluginManager().getPluginPreferencesValuesMap(installationPath_, ""); CPPUNIT_ASSERT(preferencesValuesOrig[key] != preferencesValuesNew[key]); CPPUNIT_ASSERT(preferencesValuesNew[key] == preferenceNewValue); // Test global preference change in an account preferencesValuesNew = Manager::instance().getJamiPluginManager().getPluginPreferencesValuesMap(installationPath_, aliceData.accountId_); CPPUNIT_ASSERT(preferencesValuesOrig[key] != preferencesValuesNew[key]); CPPUNIT_ASSERT(preferencesValuesNew[key] == preferenceNewValue); // Test reset global preference change Manager::instance().getJamiPluginManager().resetPluginPreferencesValuesMap(installationPath_, ""); preferencesValuesNew = Manager::instance().getJamiPluginManager().getPluginPreferencesValuesMap(installationPath_, ""); CPPUNIT_ASSERT(preferencesValuesOrig[key] == preferencesValuesNew[key]); CPPUNIT_ASSERT(preferencesValuesNew[key] != preferenceNewValue); // Get-set-reset - alice account preferences = Manager::instance().getJamiPluginManager().getPluginPreferences(installationPath_, aliceData.accountId_); CPPUNIT_ASSERT(!preferences.empty()); preferencesValuesOrig = Manager::instance().getJamiPluginManager().getPluginPreferencesValuesMap(installationPath_, aliceData.accountId_); auto preferencesValuesBobOrig = Manager::instance().getJamiPluginManager().getPluginPreferencesValuesMap(installationPath_, bobData.accountId_); key = preferences[0]["key"]; CPPUNIT_ASSERT(Manager::instance().getJamiPluginManager().setPluginPreference(installationPath_, aliceData.accountId_, key, preferenceNewValue)); // Test account preference change preferencesValuesNew = Manager::instance().getJamiPluginManager().getPluginPreferencesValuesMap(installationPath_, aliceData.accountId_); auto preferencesValuesBobNew = Manager::instance().getJamiPluginManager().getPluginPreferencesValuesMap(installationPath_, bobData.accountId_); CPPUNIT_ASSERT(preferencesValuesBobNew[key] == preferencesValuesBobOrig[key]); CPPUNIT_ASSERT(preferencesValuesOrig[key] != preferencesValuesNew[key]); CPPUNIT_ASSERT(preferencesValuesOrig[key] == preferencesValuesBobOrig[key]); CPPUNIT_ASSERT(preferencesValuesNew[key] != preferencesValuesBobOrig[key]); CPPUNIT_ASSERT(preferencesValuesNew[key] == preferenceNewValue); // Test account preference change with global preference reset Manager::instance().getJamiPluginManager().resetPluginPreferencesValuesMap(installationPath_, ""); preferencesValuesNew = Manager::instance().getJamiPluginManager().getPluginPreferencesValuesMap(installationPath_, aliceData.accountId_); preferencesValuesBobNew = Manager::instance().getJamiPluginManager().getPluginPreferencesValuesMap(installationPath_, bobData.accountId_); CPPUNIT_ASSERT(preferencesValuesBobNew[key] == preferencesValuesBobOrig[key]); CPPUNIT_ASSERT(preferencesValuesOrig[key] != preferencesValuesNew[key]); CPPUNIT_ASSERT(preferencesValuesOrig[key] == preferencesValuesBobOrig[key]); CPPUNIT_ASSERT(preferencesValuesNew[key] != preferencesValuesBobOrig[key]); CPPUNIT_ASSERT(preferencesValuesNew[key] == preferenceNewValue); // Test account preference reset Manager::instance().getJamiPluginManager().resetPluginPreferencesValuesMap(installationPath_, aliceData.accountId_); preferencesValuesNew = Manager::instance().getJamiPluginManager().getPluginPreferencesValuesMap(installationPath_, aliceData.accountId_); preferencesValuesBobNew = Manager::instance().getJamiPluginManager().getPluginPreferencesValuesMap(installationPath_, bobData.accountId_); CPPUNIT_ASSERT(preferencesValuesBobNew[key] == preferencesValuesBobOrig[key]); CPPUNIT_ASSERT(preferencesValuesOrig[key] == preferencesValuesNew[key]); CPPUNIT_ASSERT(preferencesValuesOrig[key] == preferencesValuesBobOrig[key]); CPPUNIT_ASSERT(preferencesValuesNew[key] == preferencesValuesBobOrig[key]); CPPUNIT_ASSERT(preferencesValuesNew[key] != preferenceNewValue); CPPUNIT_ASSERT(!Manager::instance().getJamiPluginManager().uninstallPlugin(installationPath_)); } void PluginsTest::testTranslations() { Manager::instance().pluginPreferences.setPluginsEnabled(true); setenv("JAMI_LANG", "en", true); Manager::instance().getJamiPluginManager().installPlugin(jplPath_, true); auto preferencesValuesEN = Manager::instance().getJamiPluginManager().getPluginPreferencesValuesMap(installationPath_, ""); auto detailsValuesEN = Manager::instance().getJamiPluginManager().getPluginDetails(installationPath_, true); CPPUNIT_ASSERT(!preferencesValuesEN.empty()); CPPUNIT_ASSERT(!detailsValuesEN.empty()); setenv("JAMI_LANG", "fr", true); CPPUNIT_ASSERT(Manager::instance().getJamiPluginManager().getPluginPreferencesValuesMap(installationPath_, "") != preferencesValuesEN); CPPUNIT_ASSERT(Manager::instance().getJamiPluginManager().getPluginDetails(installationPath_, true) != detailsValuesEN); setenv("JAMI_LANG", "en", true); CPPUNIT_ASSERT(Manager::instance().getJamiPluginManager().getPluginPreferencesValuesMap(installationPath_, "") == preferencesValuesEN); CPPUNIT_ASSERT(Manager::instance().getJamiPluginManager().getPluginDetails(installationPath_, true) == detailsValuesEN); CPPUNIT_ASSERT(!Manager::instance().getJamiPluginManager().uninstallPlugin(installationPath_)); } bool PluginsTest::waitForSignal(CallData& callData, const std::string& expectedSignal, const std::string& expectedEvent) { const std::chrono::seconds TIME_OUT {30}; std::unique_lock lock {callData.mtx_}; // Combined signal + event (if any). std::string sigEvent(expectedSignal); if (not expectedEvent.empty()) sigEvent += "::" + expectedEvent; JAMI_INFO("[%s] is waiting for [%s] signal/event", callData.alias_.c_str(), sigEvent.c_str()); auto res = callData.cv_.wait_for(lock, TIME_OUT, [&] { // Search for the expected signal in list of received signals. bool pred = false; for (auto it = callData.signals_.begin(); it != callData.signals_.end(); it++) { // The predicate is true if the signal names match, and if the // expectedEvent is not empty, the events must also match. if (it->name_ == expectedSignal and (expectedEvent.empty() or it->event_ == expectedEvent)) { pred = true; // Done with this signal. callData.signals_.erase(it); break; } } return pred; }); if (not res) { JAMI_ERR("[%s] waiting for signal/event [%s] timed-out!", callData.alias_.c_str(), sigEvent.c_str()); JAMI_INFO("[%s] currently has the following signals:", callData.alias_.c_str()); for (auto const& sig : callData.signals_) { JAMI_INFO() << "\tSignal [" << sig.name_ << (sig.event_.empty() ? "" : ("::" + sig.event_)) << "]"; } } return res; } void PluginsTest::testCall() { Manager::instance().pluginPreferences.setPluginsEnabled(true); Manager::instance().getJamiPluginManager().installPlugin(jplPath_, true); // alice calls bob // for handler available, toggle - check status - untoggle - checkstatus // end call MediaAttribute defaultAudio(MediaType::MEDIA_AUDIO); defaultAudio.label_ = "audio_0"; defaultAudio.enabled_ = true; MediaAttribute defaultVideo(MediaType::MEDIA_VIDEO); defaultVideo.label_ = "video_0"; defaultVideo.enabled_ = true; std::vector<MediaAttribute> request; std::vector<MediaAttribute> answer; // First offer/answer request.emplace_back(MediaAttribute(defaultAudio)); request.emplace_back(MediaAttribute(defaultVideo)); answer.emplace_back(MediaAttribute(defaultAudio)); answer.emplace_back(MediaAttribute(defaultVideo)); JAMI_INFO("Start call between alice and Bob"); aliceData.callId_ = libjami::placeCallWithMedia(aliceData.accountId_, bobData.userName_, MediaAttribute::mediaAttributesToMediaMaps(request)); CPPUNIT_ASSERT(not aliceData.callId_.empty()); auto aliceCall = std::static_pointer_cast<SIPCall>( Manager::instance().getCallFromCallID(aliceData.callId_)); CPPUNIT_ASSERT(aliceCall); aliceData.callId_ = aliceCall->getCallId(); JAMI_INFO("ALICE [%s] started a call with BOB [%s] and wait for answer", aliceData.accountId_.c_str(), bobData.accountId_.c_str()); // Wait for incoming call signal. CPPUNIT_ASSERT(waitForSignal(bobData, libjami::CallSignal::IncomingCallWithMedia::name)); // Answer the call. { libjami::acceptWithMedia(bobData.accountId_, bobData.callId_, MediaAttribute::mediaAttributesToMediaMaps(answer)); } CPPUNIT_ASSERT_EQUAL(true, waitForSignal(bobData, libjami::CallSignal::StateChange::name, libjami::Call::StateEvent::CURRENT)); JAMI_INFO("BOB answered the call [%s]", bobData.callId_.c_str()); std::this_thread::sleep_for(std::chrono::seconds(3)); auto mediaHandlers = Manager::instance().getJamiPluginManager().getCallServicesManager().getCallMediaHandlers(); for (auto handler : mediaHandlers) { auto details = Manager::instance().getJamiPluginManager().getCallServicesManager().getCallMediaHandlerDetails(handler); // check details expected for the test plugin if(std::find(mediaHandlers_.begin(), mediaHandlers_.end(), details["name"]) != mediaHandlers_.end()) { Manager::instance().getJamiPluginManager().getCallServicesManager().toggleCallMediaHandler(handler, aliceData.callId_, true); auto statusMap = Manager::instance().getJamiPluginManager().getCallServicesManager().getCallMediaHandlerStatus(aliceData.callId_); CPPUNIT_ASSERT(std::find(statusMap.begin(), statusMap.end(), handler) != statusMap.end()); Manager::instance().getJamiPluginManager().getCallServicesManager().toggleCallMediaHandler(handler, aliceData.callId_, false); statusMap = Manager::instance().getJamiPluginManager().getCallServicesManager().getCallMediaHandlerStatus(aliceData.callId_); CPPUNIT_ASSERT(std::find(statusMap.begin(), statusMap.end(), handler) == statusMap.end()); } } std::this_thread::sleep_for(std::chrono::seconds(3)); // Bob hang-up. JAMI_INFO("Hang up BOB's call and wait for ALICE to hang up"); libjami::hangUp(bobData.accountId_, bobData.callId_); CPPUNIT_ASSERT_EQUAL(true, waitForSignal(aliceData, libjami::CallSignal::StateChange::name, libjami::Call::StateEvent::HUNGUP)); JAMI_INFO("Call terminated on both sides"); CPPUNIT_ASSERT(!Manager::instance().getJamiPluginManager().uninstallPlugin(installationPath_)); } void PluginsTest::testMessage() { Manager::instance().pluginPreferences.setPluginsEnabled(true); Manager::instance().getJamiPluginManager().installPlugin(jplPath_, true); // alice and bob chat // for handler available, toggle - check status - untoggle - checkstatus // end call std::mutex mtx; std::unique_lock lk {mtx}; std::condition_variable cv; std::map<std::string, std::shared_ptr<libjami::CallbackWrapperBase>> confHandlers; auto messageBobReceived = 0, messageAliceReceived = 0; bool requestReceived = false; bool conversationReady = false; confHandlers.insert(libjami::exportable_callback<libjami::ConversationSignal::MessageReceived>( [&](const std::string& accountId, const std::string& /* conversationId */, std::map<std::string, std::string> /*message*/) { if (accountId == bobData.accountId_) { messageBobReceived += 1; } else { messageAliceReceived += 1; } cv.notify_one(); })); confHandlers.insert( libjami::exportable_callback<libjami::ConversationSignal::ConversationRequestReceived>( [&](const std::string& /*accountId*/, const std::string& /* conversationId */, std::map<std::string, std::string> /*metadatas*/) { requestReceived = true; cv.notify_one(); })); confHandlers.insert(libjami::exportable_callback<libjami::ConversationSignal::ConversationReady>( [&](const std::string& accountId, const std::string& /* conversationId */) { if (accountId == bobData.accountId_) { conversationReady = true; cv.notify_one(); } })); libjami::registerSignalHandlers(confHandlers); auto convId = libjami::startConversation(aliceData.accountId_); libjami::addConversationMember(aliceData.accountId_, convId, bobData.userName_); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return requestReceived; })); libjami::acceptConversationRequest(bobData.accountId_, convId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return conversationReady; })); // Assert that repository exists auto repoPath = fileutils::get_data_dir() / bobData.accountId_ / "conversations" / convId; CPPUNIT_ASSERT(std::filesystem::is_directory(repoPath)); // Wait that alice sees Bob cv.wait_for(lk, 30s, [&]() { return messageAliceReceived == 2; }); auto chatHandlers = Manager::instance().getJamiPluginManager().getChatServicesManager().getChatHandlers(); for (auto handler : chatHandlers) { auto details = Manager::instance().getJamiPluginManager().getChatServicesManager().getChatHandlerDetails(handler); // check details expected for the test plugin if(std::find(chatHandlers_.begin(), chatHandlers_.end(), details["name"]) != chatHandlers_.end()) { Manager::instance().getJamiPluginManager().getChatServicesManager().toggleChatHandler(handler, aliceData.accountId_, convId, true); auto statusMap = Manager::instance().getJamiPluginManager().getChatServicesManager().getChatHandlerStatus(aliceData.accountId_, convId); CPPUNIT_ASSERT(std::find(statusMap.begin(), statusMap.end(), handler) != statusMap.end()); libjami::sendMessage(aliceData.accountId_, convId, "hi"s, ""); cv.wait_for(lk, 30s, [&]() { return messageBobReceived == 1; }); Manager::instance().getJamiPluginManager().getChatServicesManager().toggleChatHandler(handler, aliceData.accountId_, convId, false); statusMap = Manager::instance().getJamiPluginManager().getChatServicesManager().getChatHandlerStatus(aliceData.accountId_, convId); CPPUNIT_ASSERT(std::find(statusMap.begin(), statusMap.end(), handler) == statusMap.end()); } } CPPUNIT_ASSERT(!Manager::instance().getJamiPluginManager().uninstallPlugin(installationPath_)); } } // namespace test } // namespace jami RING_TEST_RUNNER(jami::test::PluginsTest::name())
34,720
C++
.cpp
652
45.170245
169
0.685086
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,678
revoke.cpp
savoirfairelinux_jami-daemon/test/unitTest/revoke/revoke.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <cppunit/TestAssert.h> #include <cppunit/TestFixture.h> #include <cppunit/extensions/HelperMacros.h> #include <condition_variable> #include <string> #include <fstream> #include <streambuf> #include "manager.h" #include "jamidht/jamiaccount.h" #include "../../test_runner.h" #include "jami.h" #include "fileutils.h" #include "account_const.h" #include "common.h" using namespace std::string_literals; using namespace libjami::Account; namespace jami { namespace test { class RevokeTest : public CppUnit::TestFixture { public: RevokeTest() { // Init daemon libjami::init(libjami::InitFlag(libjami::LIBJAMI_FLAG_DEBUG | libjami::LIBJAMI_FLAG_CONSOLE_LOG)); if (not Manager::instance().initialized) CPPUNIT_ASSERT(libjami::start("dring-sample.yml")); } ~RevokeTest() { libjami::fini(); } static std::string name() { return "Revoke"; } void setUp(); void tearDown(); std::string aliceId; std::string bobId; private: void testRevokeDevice(); void testRevokeInvalidDevice(); CPPUNIT_TEST_SUITE(RevokeTest); CPPUNIT_TEST(testRevokeDevice); CPPUNIT_TEST(testRevokeInvalidDevice); CPPUNIT_TEST_SUITE_END(); }; CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(RevokeTest, RevokeTest::name()); void RevokeTest::setUp() { auto actors = load_actors_and_wait_for_announcement("actors/alice-bob-password.yml"); aliceId = actors["alice"]; bobId = actors["bob"]; } void RevokeTest::tearDown() { wait_for_removal_of({aliceId, bobId}); } void RevokeTest::testRevokeDevice() { auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); CPPUNIT_ASSERT(aliceAccount->exportArchive("test.gz")); std::map<std::string, std::string> details = libjami::getAccountTemplate("RING"); details[ConfProperties::ARCHIVE_PATH] = "test.gz"; std::mutex mtx; std::unique_lock lk {mtx}; std::condition_variable cv; std::map<std::string, std::shared_ptr<libjami::CallbackWrapperBase>> confHandlers; auto deviceRevoked = false; auto knownChanged = false; std::string alice2Device; confHandlers.insert( libjami::exportable_callback<libjami::ConfigurationSignal::DeviceRevocationEnded>( [&](const std::string& accountId, const std::string& deviceId, int status) { if (accountId == aliceId && deviceId == alice2Device && status == 0) deviceRevoked = true; cv.notify_one(); })); confHandlers.insert(libjami::exportable_callback<libjami::ConfigurationSignal::KnownDevicesChanged>( [&](const std::string& accountId, auto devices) { if (accountId == aliceId && devices.size() == 2) knownChanged = true; cv.notify_one(); })); libjami::registerSignalHandlers(confHandlers); auto alice2Id = jami::Manager::instance().addAccount(details); auto alice2Account = Manager::instance().getAccount<JamiAccount>(alice2Id); CPPUNIT_ASSERT(cv.wait_for(lk, std::chrono::seconds(60), [&] { return knownChanged; })); alice2Device = std::string(alice2Account->currentDeviceId()); aliceAccount->revokeDevice(alice2Device); CPPUNIT_ASSERT(cv.wait_for(lk, std::chrono::seconds(10), [&] { return deviceRevoked; })); std::remove("test.gz"); wait_for_removal_of(alice2Id); } void RevokeTest::testRevokeInvalidDevice() { auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); std::mutex mtx; std::unique_lock lk {mtx}; std::condition_variable cv; std::map<std::string, std::shared_ptr<libjami::CallbackWrapperBase>> confHandlers; auto revokeFailed = false; confHandlers.insert( libjami::exportable_callback<libjami::ConfigurationSignal::DeviceRevocationEnded>( [&](const std::string& accountId, const std::string& deviceId, int status) { if (accountId == aliceId && deviceId == "foo" && status == 2) revokeFailed = true; cv.notify_one(); })); libjami::registerSignalHandlers(confHandlers); aliceAccount->revokeDevice("foo"); CPPUNIT_ASSERT(cv.wait_for(lk, std::chrono::seconds(10), [&] { return revokeFailed; })); } } // namespace test } // namespace jami RING_TEST_RUNNER(jami::test::RevokeTest::name())
5,065
C++
.cpp
131
33.847328
106
0.695705
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,679
namedirectory.cpp
savoirfairelinux_jami-daemon/test/unitTest/namedirectory/namedirectory.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <cppunit/TestAssert.h> #include <cppunit/TestFixture.h> #include <cppunit/extensions/HelperMacros.h> #include <condition_variable> #include <string> #include <thread> #include <restinio/all.hpp> #include "manager.h" #include "jamidht/jamiaccount.h" #include "../../test_runner.h" #include "account_const.h" #include "common.h" using namespace libjami::Account; using namespace restinio; using namespace std::literals::chrono_literals; namespace jami { namespace test { using RestRouter = restinio::router::express_router_t<>; struct RestRouterTraits : public restinio::default_traits_t { using request_handler_t = RestRouter; }; class NameDirectoryTest : public CppUnit::TestFixture { public: NameDirectoryTest() { // Init daemon libjami::init( libjami::InitFlag(libjami::LIBJAMI_FLAG_DEBUG | libjami::LIBJAMI_FLAG_CONSOLE_LOG)); if (not Manager::instance().initialized) { CPPUNIT_ASSERT(libjami::start("jami-sample.yml")); // Create express router for our service. auto router = std::make_unique<router::express_router_t<>>(); router->http_post( R"(/name/:name)", [](auto req, auto params) { const auto qp = parse_query(req->header().query()); return req->create_response() .set_body( fmt::format("{{\"success\":true}}") ) .done(); }); router->http_get( R"(/name/:name)", [](auto req, auto params) { const auto qp = parse_query(req->header().query()); if (params["name"] == "taken") { return req->create_response() .set_body( fmt::format("{{\"name\":\"taken\",\"addr\":\"c0dec0dec0dec0dec0dec0dec0dec0dec0dec0de\"}}") ) .done(); } return req->create_response(restinio::status_not_found()) .set_body( fmt::format("{{\"error\":\"name not registered\"}}") ) .done(); }); router->http_get( R"(/addr/:addr)", [](auto req, auto params) { const auto qp = parse_query(req->header().query()); if (params["addr"] == "c0dec0dec0dec0dec0dec0dec0dec0dec0dec0de") { return req->create_response() .set_body( fmt::format("{{\"name\":\"taken\",\"addr\":\"c0dec0dec0dec0dec0dec0dec0dec0dec0dec0de\"}}") ) .done(); } return req->create_response(restinio::status_not_found()) .set_body( fmt::format("{{\"error\":\"address not registered\"}}") ) .done(); }); router->non_matched_request_handler( [](auto req){ return req->create_response(restinio::status_not_found()).connection_close().done(); }); auto settings = restinio::run_on_this_thread_settings_t<RestRouterTraits>(); settings.address("localhost"); settings.port(1412); settings.request_handler(std::move(router)); httpServer_ = std::make_unique<restinio::http_server_t<RestRouterTraits>>( Manager::instance().ioContext(), std::forward<restinio::run_on_this_thread_settings_t<RestRouterTraits>>(std::move(settings)) ); // run http server serverThread_ = std::thread([this](){ httpServer_->open_async([]{/*ok*/}, [](std::exception_ptr ex){ std::rethrow_exception(ex); }); httpServer_->io_context().run(); }); } } ~NameDirectoryTest() { libjami::fini(); if (serverThread_.joinable()) serverThread_.join(); } static std::string name() { return "NameDirectory"; } void setUp(); void tearDown(); std::string aliceId; // http server std::thread serverThread_; std::unique_ptr<restinio::http_server_t<RestRouterTraits>> httpServer_; private: void testRegisterName(); void testLookupName(); void testLookupNameInvalid(); void testLookupNameNotFound(); void testLookupAddr(); void testLookupAddrInvalid(); void testLookupAddrNotFound(); CPPUNIT_TEST_SUITE(NameDirectoryTest); CPPUNIT_TEST(testRegisterName); CPPUNIT_TEST(testLookupName); CPPUNIT_TEST(testLookupNameInvalid); CPPUNIT_TEST(testLookupNameNotFound); CPPUNIT_TEST(testLookupAddr); CPPUNIT_TEST(testLookupAddrInvalid); CPPUNIT_TEST(testLookupAddrNotFound); CPPUNIT_TEST_SUITE_END(); }; CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(NameDirectoryTest, NameDirectoryTest::name()); void NameDirectoryTest::setUp() { auto actors = load_actors_and_wait_for_announcement("actors/alice.yml"); aliceId = actors["alice"]; std::map<std::string, std::string> details; details[ConfProperties::RingNS::URI] = "http://localhost:1412"; libjami::setAccountDetails(aliceId, details); } void NameDirectoryTest::tearDown() { wait_for_removal_of({aliceId}); } void NameDirectoryTest::testRegisterName() { std::mutex mtx; std::unique_lock lk {mtx}; std::condition_variable cv; std::map<std::string, std::shared_ptr<libjami::CallbackWrapperBase>> confHandlers; bool nameRegistered {false}; // Watch signals confHandlers.insert(libjami::exportable_callback<libjami::ConfigurationSignal::NameRegistrationEnded>( [&](const std::string&, int status, const std::string&) { nameRegistered = status == 0; cv.notify_one(); })); libjami::registerSignalHandlers(confHandlers); CPPUNIT_ASSERT(libjami::registerName(aliceId, "foo")); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&] { return nameRegistered; })); } void NameDirectoryTest::testLookupName() { std::mutex mtx; std::unique_lock lk {mtx}; std::condition_variable cv; std::map<std::string, std::shared_ptr<libjami::CallbackWrapperBase>> confHandlers; bool nameFound {false}; // Watch signals confHandlers.insert(libjami::exportable_callback<libjami::ConfigurationSignal::RegisteredNameFound>( [&](const std::string&, int status, const std::string&, const std::string&) { nameFound = status == 0; cv.notify_one(); })); libjami::registerSignalHandlers(confHandlers); CPPUNIT_ASSERT(libjami::lookupName(aliceId, "", "taken")); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&] { return nameFound; })); } void NameDirectoryTest::testLookupNameInvalid() { std::mutex mtx; std::unique_lock lk {mtx}; std::condition_variable cv; std::map<std::string, std::shared_ptr<libjami::CallbackWrapperBase>> confHandlers; bool nameInvalid {false}; // Watch signals confHandlers.insert(libjami::exportable_callback<libjami::ConfigurationSignal::RegisteredNameFound>( [&](const std::string&, int status, const std::string&, const std::string&) { nameInvalid = status == 1; cv.notify_one(); })); libjami::registerSignalHandlers(confHandlers); CPPUNIT_ASSERT(libjami::lookupName(aliceId, "", "====")); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&] { return nameInvalid; })); } void NameDirectoryTest::testLookupNameNotFound() { std::mutex mtx; std::unique_lock lk {mtx}; std::condition_variable cv; std::map<std::string, std::shared_ptr<libjami::CallbackWrapperBase>> confHandlers; bool nameNotFound {false}; // Watch signals confHandlers.insert(libjami::exportable_callback<libjami::ConfigurationSignal::RegisteredNameFound>( [&](const std::string&, int status, const std::string&, const std::string&) { nameNotFound = status == 2; cv.notify_one(); })); libjami::registerSignalHandlers(confHandlers); CPPUNIT_ASSERT(libjami::lookupName(aliceId, "", "nottaken")); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&] { return nameNotFound; })); } void NameDirectoryTest::testLookupAddr() { std::mutex mtx; std::unique_lock lk {mtx}; std::condition_variable cv; std::map<std::string, std::shared_ptr<libjami::CallbackWrapperBase>> confHandlers; bool addrFound {false}; // Watch signals confHandlers.insert(libjami::exportable_callback<libjami::ConfigurationSignal::RegisteredNameFound>( [&](const std::string&, int status, const std::string&, const std::string&) { addrFound = status == 0; cv.notify_one(); })); libjami::registerSignalHandlers(confHandlers); CPPUNIT_ASSERT(libjami::lookupAddress(aliceId, "", "c0dec0dec0dec0dec0dec0dec0dec0dec0dec0de")); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&] { return addrFound; })); } void NameDirectoryTest::testLookupAddrInvalid() { std::mutex mtx; std::unique_lock lk {mtx}; std::condition_variable cv; std::map<std::string, std::shared_ptr<libjami::CallbackWrapperBase>> confHandlers; bool addrInvalid {false}; // Watch signals confHandlers.insert(libjami::exportable_callback<libjami::ConfigurationSignal::RegisteredNameFound>( [&](const std::string&, int status, const std::string&, const std::string&) { addrInvalid = status == 1; cv.notify_one(); })); libjami::registerSignalHandlers(confHandlers); CPPUNIT_ASSERT(libjami::lookupName(aliceId, "", "====")); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&] { return addrInvalid; })); } void NameDirectoryTest::testLookupAddrNotFound() { std::mutex mtx; std::unique_lock lk {mtx}; std::condition_variable cv; std::map<std::string, std::shared_ptr<libjami::CallbackWrapperBase>> confHandlers; bool addrNotFound {false}; // Watch signals confHandlers.insert(libjami::exportable_callback<libjami::ConfigurationSignal::RegisteredNameFound>( [&](const std::string&, int status, const std::string&, const std::string&) { addrNotFound = status == 2; cv.notify_one(); })); libjami::registerSignalHandlers(confHandlers); CPPUNIT_ASSERT(libjami::lookupAddress(aliceId, "", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&] { return addrNotFound; })); } } // namespace test } // namespace jami RING_TEST_RUNNER(jami::test::NameDirectoryTest::name())
12,120
C++
.cpp
309
29.809061
135
0.597352
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,680
conversationRepository.cpp
savoirfairelinux_jami-daemon/test/unitTest/conversationRepository/conversationRepository.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "manager.h" #include "jamidht/conversationrepository.h" #include "jamidht/gitserver.h" #include "jamidht/jamiaccount.h" #include "../../test_runner.h" #include "jami.h" #include "base64.h" #include "fileutils.h" #include "account_const.h" #include "common.h" #include <git2.h> #include <dhtnet/connectionmanager.h> #include <cppunit/TestAssert.h> #include <cppunit/TestFixture.h> #include <cppunit/extensions/HelperMacros.h> #include <condition_variable> #include <string> #include <fstream> #include <streambuf> #include <filesystem> using namespace std::string_literals; using namespace libjami::Account; namespace jami { namespace test { class ConversationRepositoryTest : public CppUnit::TestFixture { public: ConversationRepositoryTest() { // Init daemon libjami::init( libjami::InitFlag(libjami::LIBJAMI_FLAG_DEBUG | libjami::LIBJAMI_FLAG_CONSOLE_LOG)); if (not Manager::instance().initialized) CPPUNIT_ASSERT(libjami::start("jami-sample.yml")); } ~ConversationRepositoryTest() { libjami::fini(); } static std::string name() { return "ConversationRepository"; } void setUp(); void tearDown(); std::string aliceId; std::string bobId; private: void testCreateRepository(); void testAddSomeMessages(); void testLogMessages(); void testMerge(); void testFFMerge(); void testDiff(); void testMergeProfileWithConflict(); std::string addCommit(git_repository* repo, const std::shared_ptr<JamiAccount> account, const std::string& branch, const std::string& commit_msg); void addAll(git_repository* repo); bool merge_in_main(const std::shared_ptr<JamiAccount> account, git_repository* repo, const std::string& commit_ref); CPPUNIT_TEST_SUITE(ConversationRepositoryTest); CPPUNIT_TEST(testCreateRepository); CPPUNIT_TEST(testAddSomeMessages); CPPUNIT_TEST(testLogMessages); CPPUNIT_TEST(testMerge); CPPUNIT_TEST(testFFMerge); CPPUNIT_TEST(testDiff); CPPUNIT_TEST(testMergeProfileWithConflict); CPPUNIT_TEST_SUITE_END(); }; CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(ConversationRepositoryTest, ConversationRepositoryTest::name()); void ConversationRepositoryTest::setUp() { auto actors = load_actors_and_wait_for_announcement("actors/alice-bob.yml"); aliceId = actors["alice"]; bobId = actors["bob"]; } void ConversationRepositoryTest::tearDown() { wait_for_removal_of({aliceId, bobId}); } void ConversationRepositoryTest::testCreateRepository() { auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto aliceDeviceId = DeviceId(std::string(aliceAccount->currentDeviceId())); auto uri = aliceAccount->getUsername(); auto repository = ConversationRepository::createConversation(aliceAccount); // Assert that repository exists CPPUNIT_ASSERT(repository != nullptr); auto repoPath = fileutils::get_data_dir() / aliceAccount->getAccountID() / "conversations" / repository->id(); CPPUNIT_ASSERT(std::filesystem::is_directory(repoPath)); // Assert that first commit is signed by alice git_repository* repo; CPPUNIT_ASSERT(git_repository_open(&repo, repoPath.c_str()) == 0); // 1. Verify that last commit is correctly signed by alice git_oid commit_id; CPPUNIT_ASSERT(git_reference_name_to_id(&commit_id, repo, "HEAD") == 0); git_buf signature = {}, signed_data = {}; git_commit_extract_signature(&signature, &signed_data, repo, &commit_id, "signature"); auto pk = base64::decode(std::string(signature.ptr, signature.ptr + signature.size)); auto data = std::vector<uint8_t>(signed_data.ptr, signed_data.ptr + signed_data.size); git_repository_free(repo); CPPUNIT_ASSERT(aliceAccount->identity().second->getPublicKey().checkSignature(data, pk)); // 2. Check created files auto CRLsPath = repoPath / "CRLs" / aliceDeviceId.toString(); CPPUNIT_ASSERT(std::filesystem::is_directory(repoPath)); auto adminCrt = repoPath / "admins" / (uri + ".crt"); CPPUNIT_ASSERT(std::filesystem::is_regular_file(adminCrt)); auto crt = std::ifstream(adminCrt); std::string adminCrtStr((std::istreambuf_iterator<char>(crt)), std::istreambuf_iterator<char>()); auto cert = aliceAccount->identity().second; auto deviceCert = cert->toString(false); auto parentCert = cert->issuer->toString(true); CPPUNIT_ASSERT(adminCrtStr == parentCert); auto deviceCrt = repoPath / "devices" / (aliceDeviceId.toString() + ".crt"); CPPUNIT_ASSERT(std::filesystem::is_regular_file(deviceCrt)); crt = std::ifstream(deviceCrt); std::string deviceCrtStr((std::istreambuf_iterator<char>(crt)), std::istreambuf_iterator<char>()); CPPUNIT_ASSERT(deviceCrtStr == deviceCert); } void ConversationRepositoryTest::testAddSomeMessages() { auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto repository = ConversationRepository::createConversation(aliceAccount); auto id1 = repository->commitMessage("Commit 1"); auto id2 = repository->commitMessage("Commit 2"); auto id3 = repository->commitMessage("Commit 3"); auto messages = repository->log(); CPPUNIT_ASSERT(messages.size() == 4 /* 3 + initial */); CPPUNIT_ASSERT(messages[0].id == id3); CPPUNIT_ASSERT(messages[0].parents.front() == id2); CPPUNIT_ASSERT(messages[0].commit_msg == "Commit 3"); CPPUNIT_ASSERT(messages[0].author.name == messages[3].author.name); CPPUNIT_ASSERT(messages[0].author.email == messages[3].author.email); CPPUNIT_ASSERT(messages[1].id == id2); CPPUNIT_ASSERT(messages[1].parents.front() == id1); CPPUNIT_ASSERT(messages[1].commit_msg == "Commit 2"); CPPUNIT_ASSERT(messages[1].author.name == messages[3].author.name); CPPUNIT_ASSERT(messages[1].author.email == messages[3].author.email); CPPUNIT_ASSERT(messages[2].id == id1); CPPUNIT_ASSERT(messages[2].commit_msg == "Commit 1"); CPPUNIT_ASSERT(messages[2].author.name == messages[3].author.name); CPPUNIT_ASSERT(messages[2].author.email == messages[3].author.email); CPPUNIT_ASSERT(messages[2].parents.front() == repository->id()); // Check sig CPPUNIT_ASSERT( aliceAccount->identity().second->getPublicKey().checkSignature(messages[0].signed_content, messages[0].signature)); CPPUNIT_ASSERT( aliceAccount->identity().second->getPublicKey().checkSignature(messages[1].signed_content, messages[1].signature)); CPPUNIT_ASSERT( aliceAccount->identity().second->getPublicKey().checkSignature(messages[2].signed_content, messages[2].signature)); } void ConversationRepositoryTest::testLogMessages() { auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto repository = ConversationRepository::createConversation(aliceAccount); auto id1 = repository->commitMessage("Commit 1"); auto id2 = repository->commitMessage("Commit 2"); auto id3 = repository->commitMessage("Commit 3"); LogOptions options; options.from = repository->id(); options.nbOfCommits = 1; auto messages = repository->log(options); CPPUNIT_ASSERT(messages.size() == 1); CPPUNIT_ASSERT(messages[0].id == repository->id()); options.from = id2; options.nbOfCommits = 2; messages = repository->log(options); CPPUNIT_ASSERT(messages.size() == 2); CPPUNIT_ASSERT(messages[0].id == id2); CPPUNIT_ASSERT(messages[1].id == id1); options.from = repository->id(); options.nbOfCommits = 3; messages = repository->log(options); CPPUNIT_ASSERT(messages.size() == 1); CPPUNIT_ASSERT(messages[0].id == repository->id()); } std::string ConversationRepositoryTest::addCommit(git_repository* repo, const std::shared_ptr<JamiAccount> account, const std::string& branch, const std::string& commit_msg) { auto deviceId = DeviceId(std::string(account->currentDeviceId())); auto name = account->getDisplayName(); if (name.empty()) name = deviceId.toString(); git_signature* sig_ptr = nullptr; // Sign commit's buffer if (git_signature_new(&sig_ptr, name.c_str(), deviceId.to_c_str(), std::time(nullptr), 0) < 0) { JAMI_ERR("Unable to create a commit signature."); return {}; } GitSignature sig {sig_ptr, git_signature_free}; // Retrieve current HEAD git_oid commit_id; if (git_reference_name_to_id(&commit_id, repo, "HEAD") < 0) { JAMI_ERR("Unable to get reference for HEAD"); return {}; } git_commit* head_ptr = nullptr; if (git_commit_lookup(&head_ptr, repo, &commit_id) < 0) { JAMI_ERR("Unable to look up HEAD commit"); return {}; } GitCommit head_commit {head_ptr, git_commit_free}; // Retrieve current index git_index* index_ptr = nullptr; if (git_repository_index(&index_ptr, repo) < 0) { JAMI_ERR("Unable to open repository index"); return {}; } GitIndex index {index_ptr, git_index_free}; git_oid tree_id; if (git_index_write_tree(&tree_id, index.get()) < 0) { JAMI_ERR("Unable to write initial tree from index"); return {}; } git_tree* tree_ptr = nullptr; if (git_tree_lookup(&tree_ptr, repo, &tree_id) < 0) { JAMI_ERR("Unable to look up initial tree"); return {}; } GitTree tree = {tree_ptr, git_tree_free}; git_buf to_sign = {}; #if( LIBGIT2_VER_MAJOR > 1 ) || ( LIBGIT2_VER_MAJOR == 1 && LIBGIT2_VER_MINOR >= 8 ) // For libgit2 version 1.8.0 and above git_commit* const head_ref[1] = {head_commit.get()}; #else const git_commit* head_ref[1] = {head_commit.get()}; #endif if (git_commit_create_buffer(&to_sign, repo, sig.get(), sig.get(), nullptr, commit_msg.c_str(), tree.get(), 1, &head_ref[0]) < 0) { JAMI_ERR("Unable to create commit buffer"); return {}; } // git commit -S auto to_sign_vec = std::vector<uint8_t>(to_sign.ptr, to_sign.ptr + to_sign.size); auto signed_buf = account->identity().first->sign(to_sign_vec); std::string signed_str = base64::encode(signed_buf); if (git_commit_create_with_signature(&commit_id, repo, to_sign.ptr, signed_str.c_str(), "signature") < 0) { JAMI_ERR("Unable to sign commit"); return {}; } auto commit_str = git_oid_tostr_s(&commit_id); if (commit_str) { JAMI_INFO("New commit added with id: %s", commit_str); // Move commit to main branch git_reference* ref_ptr = nullptr; std::string branch_name = "refs/heads/" + branch; if (git_reference_create(&ref_ptr, repo, branch_name.c_str(), &commit_id, true, nullptr) < 0) { JAMI_WARN("Unable to move commit to main"); } git_reference_free(ref_ptr); } return commit_str ? commit_str : ""; } void ConversationRepositoryTest::addAll(git_repository* repo) { // git add -A git_index* index_ptr = nullptr; if (git_repository_index(&index_ptr, repo) < 0) return; GitIndex index {index_ptr, git_index_free}; git_strarray array = {nullptr, 0}; git_index_add_all(index.get(), &array, 0, nullptr, nullptr); git_index_write(index.get()); git_strarray_free(&array); } void ConversationRepositoryTest::testMerge() { auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto repository = ConversationRepository::createConversation(aliceAccount); // Assert that repository exists CPPUNIT_ASSERT(repository != nullptr); auto repoPath = fileutils::get_data_dir() / aliceAccount->getAccountID() / "conversations" / repository->id(); CPPUNIT_ASSERT(std::filesystem::is_directory(repoPath)); // Assert that first commit is signed by alice git_repository* repo; CPPUNIT_ASSERT(git_repository_open(&repo, repoPath.c_str()) == 0); auto id1 = addCommit(repo, aliceAccount, "main", "Commit 1"); git_reference* ref = nullptr; git_commit* commit = nullptr; git_oid commit_id; git_oid_fromstr(&commit_id, repository->id().c_str()); git_commit_lookup(&commit, repo, &commit_id); git_branch_create(&ref, repo, "to_merge", commit, false); git_reference_free(ref); git_repository_set_head(repo, "refs/heads/to_merge"); auto id2 = addCommit(repo, aliceAccount, "to_merge", "Commit 2"); git_repository_free(repo); // This will create a merge commit repository->merge(id2); CPPUNIT_ASSERT(repository->log().size() == 4 /* Initial, commit 1, 2, merge */); } void ConversationRepositoryTest::testFFMerge() { auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto repository = ConversationRepository::createConversation(aliceAccount); // Assert that repository exists CPPUNIT_ASSERT(repository != nullptr); auto repoPath = fileutils::get_data_dir() / aliceAccount->getAccountID() / "conversations" / repository->id(); CPPUNIT_ASSERT(std::filesystem::is_directory(repoPath)); // Assert that first commit is signed by alice git_repository* repo; CPPUNIT_ASSERT(git_repository_open(&repo, repoPath.c_str()) == 0); auto id1 = addCommit(repo, aliceAccount, "main", "Commit 1"); git_reference* ref = nullptr; git_commit* commit = nullptr; git_oid commit_id; git_oid_fromstr(&commit_id, id1.c_str()); git_commit_lookup(&commit, repo, &commit_id); git_branch_create(&ref, repo, "to_merge", commit, false); git_reference_free(ref); git_repository_set_head(repo, "refs/heads/to_merge"); auto id2 = addCommit(repo, aliceAccount, "to_merge", "Commit 2"); git_repository_free(repo); // This will use a fast forward merge repository->merge(id2); CPPUNIT_ASSERT(repository->log().size() == 3 /* Initial, commit 1, 2 */); } void ConversationRepositoryTest::testDiff() { auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto aliceDeviceId = DeviceId(std::string(aliceAccount->currentDeviceId())); auto uri = aliceAccount->getUsername(); auto repository = ConversationRepository::createConversation(aliceAccount); auto id1 = repository->commitMessage("Commit 1"); auto id2 = repository->commitMessage("Commit 2"); auto id3 = repository->commitMessage("Commit 3"); auto diff = repository->diffStats(id2, id1); CPPUNIT_ASSERT(ConversationRepository::changedFiles(diff).empty()); diff = repository->diffStats(id1); auto changedFiles = ConversationRepository::changedFiles(diff); CPPUNIT_ASSERT(!changedFiles.empty()); CPPUNIT_ASSERT(changedFiles[0] == "admins/" + uri + ".crt"); CPPUNIT_ASSERT(changedFiles[1] == "devices/" + aliceDeviceId.toString() + ".crt"); } void ConversationRepositoryTest::testMergeProfileWithConflict() { auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto repository = ConversationRepository::createConversation(aliceAccount); // Assert that repository exists CPPUNIT_ASSERT(repository != nullptr); auto repoPath = fileutils::get_data_dir() / aliceAccount->getAccountID() / "conversations" / repository->id(); CPPUNIT_ASSERT(std::filesystem::is_directory(repoPath)); // Assert that first commit is signed by alice git_repository* repo; CPPUNIT_ASSERT(git_repository_open(&repo, repoPath.c_str()) == 0); auto profile = std::ofstream(repoPath / "profile.vcf"); if (profile.is_open()) { profile << "TITLE: SWARM\n"; profile << "SUBTITLE: Some description\n"; profile << "AVATAR: BASE64\n"; profile.close(); } addAll(repo); auto id1 = addCommit(repo, aliceAccount, "main", "add profile"); profile = std::ofstream(repoPath / "profile.vcf"); if (profile.is_open()) { profile << "TITLE: SWARM\n"; profile << "SUBTITLE: New description\n"; profile << "AVATAR: BASE64\n"; profile.close(); } addAll(repo); auto id2 = addCommit(repo, aliceAccount, "main", "modify profile"); git_reference* ref = nullptr; git_commit* commit = nullptr; git_oid commit_id; git_oid_fromstr(&commit_id, id1.c_str()); git_commit_lookup(&commit, repo, &commit_id); git_branch_create(&ref, repo, "to_merge", commit, false); git_reference_free(ref); git_repository_set_head(repo, "refs/heads/to_merge"); profile = std::ofstream(repoPath / "profile.vcf"); if (profile.is_open()) { profile << "TITLE: SWARM\n"; profile << "SUBTITLE: Another description\n"; profile << "AVATAR: BASE64\n"; profile.close(); } addAll(repo); auto id3 = addCommit(repo, aliceAccount, "to_merge", "modify profile merge"); // This will create a merge commit repository->merge(id3); CPPUNIT_ASSERT(repository->log().size() == 5 /* Initial, add, modify 1, modify 2, merge */); } } // namespace test } // namespace jami RING_TEST_RUNNER(jami::test::ConversationRepositoryTest::name())
18,745
C++
.cpp
437
36
101
0.654253
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,681
testMap_utils.cpp
savoirfairelinux_jami-daemon/test/unitTest/map_utils/testMap_utils.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <cppunit/TestAssert.h> #include <cppunit/TestFixture.h> #include <cppunit/extensions/HelperMacros.h> #include "map_utils.h" #include <vector> #include <map> #include <string> #include "../../test_runner.h" namespace jami { namespace map_utils { namespace test { class MapUtilsTest : public CppUnit::TestFixture { public: static std::string name() { return "map_utils"; } void setUp(); private: void test_extractKeys(); void test_extractValues(); CPPUNIT_TEST_SUITE(MapUtilsTest); CPPUNIT_TEST(test_extractKeys); CPPUNIT_TEST(test_extractValues); CPPUNIT_TEST_SUITE_END(); const int NUMBERMAPVALUE = 5; std::map<int, std::string> m; }; CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(MapUtilsTest, MapUtilsTest::name()); void MapUtilsTest::setUp() { for (int i = 0; i < NUMBERMAPVALUE; i++) { std::string string_i = std::to_string(i); m[i] = "value " + string_i; } } void MapUtilsTest::test_extractKeys() { auto result = extractKeys(m); CPPUNIT_ASSERT(result.size() == m.size()); int i = 0; for (auto& key : result) { CPPUNIT_ASSERT(key == i); ++i; } } void MapUtilsTest::test_extractValues() { auto result = extractValues(m); CPPUNIT_ASSERT(result.size() == m.size()); int i = 0; for (auto& value : result) { CPPUNIT_ASSERT(value.compare("value " + std::to_string(i)) == 0); ++i; } } }}} // namespace jami::map_utils::test RING_TEST_RUNNER(jami::map_utils::test::MapUtilsTest::name());
2,258
C++
.cpp
72
27.986111
74
0.690212
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
751,682
sip_srtp.cpp
savoirfairelinux_jami-daemon/test/unitTest/sip_account/sip_srtp.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <cppunit/TestAssert.h> #include <cppunit/TestFixture.h> #include <cppunit/extensions/HelperMacros.h> #include <condition_variable> #include <string> #include "callmanager_interface.h" #include "manager.h" #include "sip/sipaccount.h" #include "../../test_runner.h" #include "jami.h" #include "jami/media_const.h" #include "call_const.h" #include "account_const.h" #include "sip/sipcall.h" #include "sip/sdp.h" using namespace libjami::Account; using namespace libjami::Call; namespace jami { namespace test { struct CallData { struct Signal { Signal(const std::string& name, const std::string& event = {}) : name_(std::move(name)) , event_(std::move(event)) {}; std::string name_ {}; std::string event_ {}; }; std::string accountId_ {}; uint16_t listeningPort_ {0}; std::string userName_ {}; std::string alias_ {}; std::string callId_ {}; std::vector<Signal> signals_; std::condition_variable cv_ {}; std::mutex mtx_; }; /** * Call tests for SIP accounts. */ class SipSrtpTest : public CppUnit::TestFixture { public: SipSrtpTest() { // Init daemon libjami::init(libjami::InitFlag(libjami::LIBJAMI_FLAG_DEBUG | libjami::LIBJAMI_FLAG_CONSOLE_LOG)); if (not Manager::instance().initialized) CPPUNIT_ASSERT(libjami::start("dring-sample.yml")); } ~SipSrtpTest() { libjami::fini(); } static std::string name() { return "SipSrtpTest"; } void setUp(); void tearDown(); private: // Test cases. void audio_video_srtp_enabled_test(); CPPUNIT_TEST_SUITE(SipSrtpTest); CPPUNIT_TEST(audio_video_srtp_enabled_test); CPPUNIT_TEST_SUITE_END(); // Event/Signal handlers static void onCallStateChange(const std::string& accountId, const std::string& callId, const std::string& state, CallData& callData); static void onIncomingCallWithMedia(const std::string& accountId, const std::string& callId, const std::vector<libjami::MediaMap> mediaList, CallData& callData); static void onMediaNegotiationStatus(const std::string& callId, const std::string& event, CallData& callData); // Helpers void audio_video_call(std::vector<MediaAttribute> offer, std::vector<MediaAttribute> answer, bool validateMedia = true); static void configureTest(CallData& bob, CallData& alice); static std::string getUserAlias(const std::string& callId); // Wait for a signal from the callbacks. Some signals also report the event that // triggered the signal a like the StateChange signal. static bool waitForSignal(CallData& callData, const std::string& signal, const std::string& expectedEvent = {}); private: CallData aliceData_; CallData bobData_; }; CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(SipSrtpTest, SipSrtpTest::name()); void SipSrtpTest::setUp() { aliceData_.listeningPort_ = 5080; std::map<std::string, std::string> details = libjami::getAccountTemplate("SIP"); details[ConfProperties::TYPE] = "SIP"; details[ConfProperties::DISPLAYNAME] = "ALICE"; details[ConfProperties::ALIAS] = "ALICE"; details[ConfProperties::LOCAL_PORT] = std::to_string(aliceData_.listeningPort_); details[ConfProperties::UPNP_ENABLED] = "false"; details[ConfProperties::SRTP::KEY_EXCHANGE] = "sdes"; aliceData_.accountId_ = Manager::instance().addAccount(details); bobData_.listeningPort_ = 5082; details = libjami::getAccountTemplate("SIP"); details[ConfProperties::TYPE] = "SIP"; details[ConfProperties::DISPLAYNAME] = "BOB"; details[ConfProperties::ALIAS] = "BOB"; details[ConfProperties::LOCAL_PORT] = std::to_string(bobData_.listeningPort_); details[ConfProperties::UPNP_ENABLED] = "false"; details[ConfProperties::SRTP::KEY_EXCHANGE] = "sdes"; bobData_.accountId_ = Manager::instance().addAccount(details); JAMI_INFO("Initialize accounts ..."); auto aliceAccount = Manager::instance().getAccount<SIPAccount>(aliceData_.accountId_); auto bobAccount = Manager::instance().getAccount<SIPAccount>(bobData_.accountId_); } void SipSrtpTest::tearDown() { JAMI_INFO("Remove created accounts..."); std::map<std::string, std::shared_ptr<libjami::CallbackWrapperBase>> confHandlers; std::mutex mtx; std::unique_lock lk {mtx}; std::condition_variable cv; auto currentAccSize = Manager::instance().getAccountList().size(); std::atomic_bool accountsRemoved {false}; confHandlers.insert( libjami::exportable_callback<libjami::ConfigurationSignal::AccountsChanged>([&]() { if (Manager::instance().getAccountList().size() <= currentAccSize - 2) { accountsRemoved = true; cv.notify_one(); } })); libjami::registerSignalHandlers(confHandlers); Manager::instance().removeAccount(aliceData_.accountId_, true); Manager::instance().removeAccount(bobData_.accountId_, true); // Because cppunit is not linked with dbus, just poll if removed CPPUNIT_ASSERT( cv.wait_for(lk, std::chrono::seconds(30), [&] { return accountsRemoved.load(); })); libjami::unregisterSignalHandlers(); } std::string SipSrtpTest::getUserAlias(const std::string& callId) { auto call = Manager::instance().getCallFromCallID(callId); if (not call) { JAMI_WARN("Call with ID [%s] does not exist anymore!", callId.c_str()); return {}; } auto const& account = call->getAccount().lock(); if (not account) { return {}; } return account->getAccountDetails()[ConfProperties::ALIAS]; } void SipSrtpTest::onIncomingCallWithMedia(const std::string& accountId, const std::string& callId, const std::vector<libjami::MediaMap> mediaList, CallData& callData) { CPPUNIT_ASSERT_EQUAL(callData.accountId_, accountId); JAMI_INFO("Signal [%s] - user [%s] - call [%s] - media count [%lu]", libjami::CallSignal::IncomingCallWithMedia::name, callData.alias_.c_str(), callId.c_str(), mediaList.size()); // NOTE. // We shouldn't access shared_ptr<Call> as this event is supposed to mimic // the client, and the client have no access to this type. But here, we only // needed to check if the call exists. This is the most straightforward and // reliable way to do it until we add a new API (like hasCall(id)). if (not Manager::instance().getCallFromCallID(callId)) { JAMI_WARN("Call with ID [%s] does not exist!", callId.c_str()); callData.callId_ = {}; return; } std::unique_lock lock {callData.mtx_}; callData.callId_ = callId; callData.signals_.emplace_back(CallData::Signal(libjami::CallSignal::IncomingCallWithMedia::name)); callData.cv_.notify_one(); } void SipSrtpTest::onCallStateChange(const std::string&, const std::string& callId, const std::string& state, CallData& callData) { auto call = Manager::instance().getCallFromCallID(callId); if (not call) { JAMI_WARN("Call with ID [%s] does not exist anymore!", callId.c_str()); return; } auto account = call->getAccount().lock(); if (not account) { JAMI_WARN("Account owning the call [%s] does not exist!", callId.c_str()); return; } JAMI_INFO("Signal [%s] - user [%s] - call [%s] - state [%s]", libjami::CallSignal::StateChange::name, callData.alias_.c_str(), callId.c_str(), state.c_str()); if (account->getAccountID() != callData.accountId_) return; { std::unique_lock lock {callData.mtx_}; callData.signals_.emplace_back( CallData::Signal(libjami::CallSignal::StateChange::name, state)); } // NOTE. Only states that we are interested on will notify the CV. If this // unit test is modified to process other states, they must be added here. if (state == "CURRENT" or state == "OVER" or state == "HUNGUP" or state == "RINGING") { callData.cv_.notify_one(); } } void SipSrtpTest::onMediaNegotiationStatus(const std::string& callId, const std::string& event, CallData& callData) { auto call = Manager::instance().getCallFromCallID(callId); if (not call) { JAMI_WARN("Call with ID [%s] does not exist!", callId.c_str()); return; } auto account = call->getAccount().lock(); if (not account) { JAMI_WARN("Account owning the call [%s] does not exist!", callId.c_str()); return; } JAMI_INFO("Signal [%s] - user [%s] - call [%s] - state [%s]", libjami::CallSignal::MediaNegotiationStatus::name, account->getAccountDetails()[ConfProperties::ALIAS].c_str(), call->getCallId().c_str(), event.c_str()); if (account->getAccountID() != callData.accountId_) return; { std::unique_lock lock {callData.mtx_}; callData.signals_.emplace_back( CallData::Signal(libjami::CallSignal::MediaNegotiationStatus::name, event)); } callData.cv_.notify_one(); } bool SipSrtpTest::waitForSignal(CallData& callData, const std::string& expectedSignal, const std::string& expectedEvent) { const std::chrono::seconds TIME_OUT {30}; std::unique_lock lock {callData.mtx_}; // Combined signal + event (if any). std::string sigEvent(expectedSignal); if (not expectedEvent.empty()) sigEvent += "::" + expectedEvent; JAMI_INFO("[%s] is waiting for [%s] signal/event", callData.alias_.c_str(), sigEvent.c_str()); auto res = callData.cv_.wait_for(lock, TIME_OUT, [&] { // Search for the expected signal in list of received signals. bool pred = false; for (auto it = callData.signals_.begin(); it != callData.signals_.end(); it++) { // The predicate is true if the signal names match, and if the // expectedEvent is not empty, the events must also match. if (it->name_ == expectedSignal and (expectedEvent.empty() or it->event_ == expectedEvent)) { pred = true; // Done with this signal. callData.signals_.erase(it); break; } } return pred; }); if (not res) { JAMI_ERR("[%s] waiting for signal/event [%s] timed-out!", callData.alias_.c_str(), sigEvent.c_str()); JAMI_INFO("[%s] currently has the following signals:", callData.alias_.c_str()); for (auto const& sig : callData.signals_) { JAMI_INFO() << "Signal [" << sig.name_ << (sig.event_.empty() ? "" : ("::" + sig.event_)) << "]"; } } return res; } void SipSrtpTest::configureTest(CallData& aliceData, CallData& bobData) { { CPPUNIT_ASSERT(not aliceData.accountId_.empty()); auto const& account = Manager::instance().getAccount<SIPAccount>(aliceData.accountId_); aliceData.userName_ = account->getAccountDetails()[ConfProperties::USERNAME]; aliceData.alias_ = account->getAccountDetails()[ConfProperties::ALIAS]; account->setLocalPort(aliceData.listeningPort_); } { CPPUNIT_ASSERT(not bobData.accountId_.empty()); auto const& account = Manager::instance().getAccount<SIPAccount>(bobData.accountId_); bobData.userName_ = account->getAccountDetails()[ConfProperties::USERNAME]; bobData.alias_ = account->getAccountDetails()[ConfProperties::ALIAS]; account->setLocalPort(bobData.listeningPort_); } std::map<std::string, std::shared_ptr<libjami::CallbackWrapperBase>> signalHandlers; // Insert needed signal handlers. signalHandlers.insert(libjami::exportable_callback<libjami::CallSignal::IncomingCallWithMedia>( [&](const std::string& accountId, const std::string& callId, const std::string&, const std::vector<libjami::MediaMap> mediaList) { auto user = getUserAlias(callId); if (not user.empty()) onIncomingCallWithMedia(accountId, callId, mediaList, user == aliceData.alias_ ? aliceData : bobData); })); signalHandlers.insert( libjami::exportable_callback<libjami::CallSignal::StateChange>([&](const std::string& accountId, const std::string& callId, const std::string& state, signed) { auto user = getUserAlias(callId); if (not user.empty()) onCallStateChange(accountId, callId, state, user == aliceData.alias_ ? aliceData : bobData); })); signalHandlers.insert(libjami::exportable_callback<libjami::CallSignal::MediaNegotiationStatus>( [&](const std::string& callId, const std::string& event, const std::vector<std::map<std::string, std::string>>& /* mediaList */) { auto user = getUserAlias(callId); if (not user.empty()) onMediaNegotiationStatus(callId, event, user == aliceData.alias_ ? aliceData : bobData); })); libjami::registerSignalHandlers(signalHandlers); } void SipSrtpTest::audio_video_call(std::vector<MediaAttribute> offer, std::vector<MediaAttribute> answer, bool validateMedia) { JAMI_INFO("=== Begin test %s ===", __FUNCTION__); configureTest(aliceData_, bobData_); JAMI_INFO("=== Start a call and validate ==="); std::string bobUri = "127.0.0.1:" + std::to_string(bobData_.listeningPort_); aliceData_.callId_ = libjami::placeCallWithMedia(aliceData_.accountId_, bobUri, MediaAttribute::mediaAttributesToMediaMaps( offer)); CPPUNIT_ASSERT(not aliceData_.callId_.empty()); JAMI_INFO("ALICE [%s] started a call with BOB [%s] and wait for answer", aliceData_.accountId_.c_str(), bobData_.accountId_.c_str()); // Give it some time to ring std::this_thread::sleep_for(std::chrono::seconds(2)); // Wait for call to be processed. CPPUNIT_ASSERT( waitForSignal(aliceData_, libjami::CallSignal::StateChange::name, StateEvent::RINGING)); // Wait for incoming call signal. CPPUNIT_ASSERT(waitForSignal(bobData_, libjami::CallSignal::IncomingCallWithMedia::name)); // Answer the call. libjami::acceptWithMedia(bobData_.accountId_, bobData_.callId_, MediaAttribute::mediaAttributesToMediaMaps(answer)); // Wait for media negotiation complete signal. CPPUNIT_ASSERT(waitForSignal(bobData_, libjami::CallSignal::MediaNegotiationStatus::name, libjami::Media::MediaNegotiationStatusEvents::NEGOTIATION_SUCCESS)); // Wait for the StateChange signal. CPPUNIT_ASSERT( waitForSignal(bobData_, libjami::CallSignal::StateChange::name, StateEvent::CURRENT)); JAMI_INFO("BOB answered the call [%s]", bobData_.callId_.c_str()); // Wait for media negotiation complete signal. CPPUNIT_ASSERT(waitForSignal(aliceData_, libjami::CallSignal::MediaNegotiationStatus::name, libjami::Media::MediaNegotiationStatusEvents::NEGOTIATION_SUCCESS)); // Validate Alice's media if (validateMedia) { auto call = Manager::instance().getCallFromCallID(aliceData_.callId_); auto activeMediaList = call->getMediaAttributeList(); CPPUNIT_ASSERT_EQUAL(offer.size(), activeMediaList.size()); // Audio CPPUNIT_ASSERT_EQUAL(MediaType::MEDIA_AUDIO, activeMediaList[0].type_); CPPUNIT_ASSERT_EQUAL(offer[0].enabled_, activeMediaList[0].enabled_); // Video if (offer.size() > 1) { CPPUNIT_ASSERT_EQUAL(MediaType::MEDIA_VIDEO, activeMediaList[1].type_); CPPUNIT_ASSERT_EQUAL(offer[1].enabled_, activeMediaList[1].enabled_); } } // Validate Bob's media if (validateMedia) { auto call = Manager::instance().getCallFromCallID(bobData_.callId_); auto activeMediaList = call->getMediaAttributeList(); CPPUNIT_ASSERT_EQUAL(answer.size(), activeMediaList.size()); // Audio CPPUNIT_ASSERT_EQUAL(MediaType::MEDIA_AUDIO, activeMediaList[0].type_); CPPUNIT_ASSERT_EQUAL(answer[0].enabled_, activeMediaList[0].enabled_); // Video if (offer.size() > 1) { CPPUNIT_ASSERT_EQUAL(MediaType::MEDIA_VIDEO, activeMediaList[1].type_); CPPUNIT_ASSERT_EQUAL(answer[1].enabled_, activeMediaList[1].enabled_); } } // Give some time to media to start and flow std::this_thread::sleep_for(std::chrono::seconds(3)); // Bob hang-up. JAMI_INFO("Hang up BOB's call and wait for ALICE to hang up"); libjami::hangUp(bobData_.accountId_, bobData_.callId_); CPPUNIT_ASSERT( waitForSignal(aliceData_, libjami::CallSignal::StateChange::name, StateEvent::HUNGUP)); JAMI_INFO("Call terminated on both sides"); } void SipSrtpTest::audio_video_srtp_enabled_test() { // Test with video enabled on Alice's side and disabled // on Bob's side. auto const aliceAcc = Manager::instance().getAccount<SIPAccount>(aliceData_.accountId_); CPPUNIT_ASSERT(aliceAcc->isSrtpEnabled()); auto const bobAcc = Manager::instance().getAccount<SIPAccount>(bobData_.accountId_); CPPUNIT_ASSERT(bobAcc->isSrtpEnabled()); std::vector<MediaAttribute> offer; std::vector<MediaAttribute> answer; MediaAttribute audio(MediaType::MEDIA_AUDIO); MediaAttribute video(MediaType::MEDIA_VIDEO); // Configure Alice audio.enabled_ = true; audio.label_ = "audio_0"; offer.emplace_back(audio); video.enabled_ = true; video.label_ = "video_0"; aliceAcc->enableVideo(true); offer.emplace_back(video); // Configure Bob audio.enabled_ = true; audio.label_ = "audio_0"; answer.emplace_back(audio); video.enabled_ = false; video.label_ = "video_0"; bobAcc->enableVideo(false); answer.emplace_back(video); // Run the scenario audio_video_call(offer, answer); } } // namespace test } // namespace jami RING_TEST_RUNNER(jami::test::SipSrtpTest::name())
20,413
C++
.cpp
466
34.360515
106
0.613862
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,683
sip_basic_calls.cpp
savoirfairelinux_jami-daemon/test/unitTest/sip_account/sip_basic_calls.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <cppunit/TestAssert.h> #include <cppunit/TestFixture.h> #include <cppunit/extensions/HelperMacros.h> #include <condition_variable> #include <string> #include "callmanager_interface.h" #include "manager.h" #include "sip/sipaccount.h" #include "../../test_runner.h" #include "jami.h" #include "jami/media_const.h" #include "call_const.h" #include "account_const.h" #include "sip/sipcall.h" #include "sip/sdp.h" using namespace libjami::Account; using namespace libjami::Call; namespace jami { namespace test { struct CallData { struct Signal { Signal(const std::string& name, const std::string& event = {}) : name_(std::move(name)) , event_(std::move(event)) {}; std::string name_ {}; std::string event_ {}; }; CallData() = default; CallData(CallData&& other) = delete; CallData(const CallData& other) { accountId_ = std::move(other.accountId_); listeningPort_ = other.listeningPort_; userName_ = std::move(other.userName_); alias_ = std::move(other.alias_); callId_ = std::move(other.callId_); signals_ = std::move(other.signals_); }; std::string accountId_ {}; uint16_t listeningPort_ {0}; std::string userName_ {}; std::string alias_ {}; std::string callId_ {}; std::vector<Signal> signals_; std::condition_variable cv_ {}; std::mutex mtx_; }; /** * Call tests for SIP accounts. */ class SipBasicCallTest : public CppUnit::TestFixture { public: SipBasicCallTest() { // Init daemon libjami::init(libjami::InitFlag(libjami::LIBJAMI_FLAG_DEBUG | libjami::LIBJAMI_FLAG_CONSOLE_LOG)); if (not Manager::instance().initialized) CPPUNIT_ASSERT(libjami::start("dring-sample.yml")); } ~SipBasicCallTest() { libjami::fini(); } static std::string name() { return "SipBasicCallTest"; } void setUp(); void tearDown(); private: // Test cases. void audio_only_test(); void audio_video_test(); void peer_answer_with_all_media_disabled(); void hold_resume_test(); void blind_transfer_test(); CPPUNIT_TEST_SUITE(SipBasicCallTest); CPPUNIT_TEST(audio_only_test); CPPUNIT_TEST(audio_video_test); // Test when the peer answers with all the media disabled (RTP port = 0) CPPUNIT_TEST(peer_answer_with_all_media_disabled); CPPUNIT_TEST(hold_resume_test); CPPUNIT_TEST(blind_transfer_test); CPPUNIT_TEST_SUITE_END(); // Event/Signal handlers static void onCallStateChange(const std::string& accountId, const std::string& callId, const std::string& state, CallData& callData); static void onIncomingCallWithMedia(const std::string& accountId, const std::string& callId, const std::vector<libjami::MediaMap> mediaList, CallData& callData); static void onMediaNegotiationStatus(const std::string& callId, const std::string& event, CallData& callData); // Helpers bool addTestAccount(const std::string& alias, uint16_t port); void audio_video_call(std::vector<MediaAttribute> offer, std::vector<MediaAttribute> answer, bool expectedToSucceed = true, bool validateMedia = true); void configureTest(); std::string getAccountId(const std::string& callId); std::string getUserAlias(const std::string& accountId); CallData& getCallData(const std::string& account); // Wait for a signal from the callbacks. Some signals also report the event that // triggered the signal a like the StateChange signal. static bool waitForSignal(CallData& callData, const std::string& signal, const std::string& expectedEvent = {}); std::map<std::string, CallData> callDataMap_; std::set<std::string> testAccounts_; }; CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(SipBasicCallTest, SipBasicCallTest::name()); bool SipBasicCallTest::addTestAccount(const std::string& alias, uint16_t port) { CallData callData; callData.alias_ = alias; callData.userName_ = alias; callData.listeningPort_ = port; std::map<std::string, std::string> details = libjami::getAccountTemplate("SIP"); details[ConfProperties::TYPE] = "SIP"; details[ConfProperties::USERNAME] = alias; details[ConfProperties::DISPLAYNAME] = alias; details[ConfProperties::ALIAS] = alias; details[ConfProperties::LOCAL_PORT] = std::to_string(port); details[ConfProperties::UPNP_ENABLED] = "false"; callData.accountId_ = Manager::instance().addAccount(details); testAccounts_.insert(callData.accountId_); callDataMap_.emplace(alias, std::move(callData)); return (not callDataMap_[alias].accountId_.empty()); } void SipBasicCallTest::setUp() { JAMI_INFO("Initialize accounts ..."); CPPUNIT_ASSERT(addTestAccount("ALICE", 5080)); CPPUNIT_ASSERT(addTestAccount("BOB", 5082)); CPPUNIT_ASSERT(addTestAccount("CARLA", 5084)); } void SipBasicCallTest::tearDown() { JAMI_INFO("Remove created accounts..."); std::map<std::string, std::shared_ptr<libjami::CallbackWrapperBase>> confHandlers; std::mutex mtx; std::unique_lock lk {mtx}; std::condition_variable cv; std::atomic_bool accountsRemoved {false}; confHandlers.insert( libjami::exportable_callback<libjami::ConfigurationSignal::AccountsChanged>([&]() { auto currAccounts = Manager::instance().getAccountList(); for (auto iter = testAccounts_.begin(); iter != testAccounts_.end();) { auto item = std::find(currAccounts.begin(), currAccounts.end(), *iter); if (item == currAccounts.end()) { JAMI_INFO("Removing account %s", (*iter).c_str()); iter = testAccounts_.erase(iter); } else { iter++; } } if (testAccounts_.empty()) { accountsRemoved = true; JAMI_INFO("All accounts removed..."); cv.notify_one(); } })); libjami::registerSignalHandlers(confHandlers); Manager::instance().removeAccount(callDataMap_["ALICE"].accountId_, true); Manager::instance().removeAccount(callDataMap_["BOB"].accountId_, true); Manager::instance().removeAccount(callDataMap_["CARLA"].accountId_, true); CPPUNIT_ASSERT( cv.wait_for(lk, std::chrono::seconds(30), [&] { return accountsRemoved.load(); })); libjami::unregisterSignalHandlers(); } std::string SipBasicCallTest::getAccountId(const std::string& callId) { auto call = Manager::instance().getCallFromCallID(callId); if (not call) { JAMI_WARN("Call [%s] does not exist anymore!", callId.c_str()); return {}; } auto const& account = call->getAccount().lock(); if (account) { return account->getAccountID(); } JAMI_WARN("Account owning the call [%s] does not exist anymore!", callId.c_str()); return {}; } std::string SipBasicCallTest::getUserAlias(const std::string& accountId) { if (accountId.empty()) { JAMI_WARN("No account ID is empty"); return {}; } auto ret = std::find_if(callDataMap_.begin(), callDataMap_.end(), [accountId](auto const& item) { return item.second.accountId_ == accountId; }); if (ret != callDataMap_.end()) return ret->first; JAMI_WARN("No matching test account %s", accountId.c_str()); return {}; } void SipBasicCallTest::onIncomingCallWithMedia(const std::string& accountId, const std::string& callId, const std::vector<libjami::MediaMap> mediaList, CallData& callData) { CPPUNIT_ASSERT_EQUAL(callData.accountId_, accountId); JAMI_INFO("Signal [%s] - user [%s] - call [%s] - media count [%lu]", libjami::CallSignal::IncomingCallWithMedia::name, callData.alias_.c_str(), callId.c_str(), mediaList.size()); if (not Manager::instance().getCallFromCallID(callId)) { JAMI_WARN("Call with ID [%s] does not exist!", callId.c_str()); callData.callId_ = {}; return; } std::unique_lock lock {callData.mtx_}; callData.callId_ = callId; callData.signals_.emplace_back(CallData::Signal(libjami::CallSignal::IncomingCallWithMedia::name)); callData.cv_.notify_one(); } void SipBasicCallTest::onCallStateChange(const std::string& accountId, const std::string& callId, const std::string& state, CallData& callData) { JAMI_INFO("Signal [%s] - user [%s] - call [%s] - state [%s]", libjami::CallSignal::StateChange::name, callData.alias_.c_str(), callId.c_str(), state.c_str()); CPPUNIT_ASSERT(accountId == callData.accountId_); { std::unique_lock lock {callData.mtx_}; callData.signals_.emplace_back( CallData::Signal(libjami::CallSignal::StateChange::name, state)); } // NOTE. Only states that we are interested on will notify the CV. If this // unit test is modified to process other states, they must be added here. if (state == "CURRENT" or state == "OVER" or state == "HUNGUP" or state == "RINGING") { callData.cv_.notify_one(); } } void SipBasicCallTest::onMediaNegotiationStatus(const std::string& callId, const std::string& event, CallData& callData) { auto call = Manager::instance().getCallFromCallID(callId); if (not call) { JAMI_WARN("Call with ID [%s] does not exist!", callId.c_str()); return; } auto account = call->getAccount().lock(); if (not account) { JAMI_WARN("Account owning the call [%s] does not exist!", callId.c_str()); return; } JAMI_INFO("Signal [%s] - user [%s] - call [%s] - state [%s]", libjami::CallSignal::MediaNegotiationStatus::name, account->getAccountDetails()[ConfProperties::ALIAS].c_str(), call->getCallId().c_str(), event.c_str()); if (account->getAccountID() != callData.accountId_) return; { std::unique_lock lock {callData.mtx_}; callData.signals_.emplace_back( CallData::Signal(libjami::CallSignal::MediaNegotiationStatus::name, event)); } callData.cv_.notify_one(); } bool SipBasicCallTest::waitForSignal(CallData& callData, const std::string& expectedSignal, const std::string& expectedEvent) { const std::chrono::seconds TIME_OUT {10}; std::unique_lock lock {callData.mtx_}; // Combined signal + event (if any). std::string sigEvent(expectedSignal); if (not expectedEvent.empty()) sigEvent += "::" + expectedEvent; JAMI_INFO("[%s] is waiting for [%s] signal/event", callData.alias_.c_str(), sigEvent.c_str()); auto res = callData.cv_.wait_for(lock, TIME_OUT, [&] { // Search for the expected signal in list of received signals. bool pred = false; for (auto it = callData.signals_.begin(); it != callData.signals_.end(); it++) { // The predicate is true if the signal names match, and if the // expectedEvent is not empty, the events must also match. if (it->name_ == expectedSignal and (expectedEvent.empty() or it->event_ == expectedEvent)) { pred = true; // Done with this signal. callData.signals_.erase(it); break; } } return pred; }); if (not res) { JAMI_ERR("[%s] waiting for signal/event [%s] timed-out!", callData.alias_.c_str(), sigEvent.c_str()); JAMI_INFO("[%s] currently has the following signals:", callData.alias_.c_str()); for (auto const& sig : callData.signals_) { JAMI_INFO() << "\tSignal [" << sig.name_ << (sig.event_.empty() ? "" : ("::" + sig.event_)) << "]"; } } return res; } void SipBasicCallTest::configureTest() { { CPPUNIT_ASSERT(not callDataMap_["ALICE"].accountId_.empty()); auto const& account = Manager::instance().getAccount<SIPAccount>( callDataMap_["ALICE"].accountId_); account->setLocalPort(callDataMap_["ALICE"].listeningPort_); } { CPPUNIT_ASSERT(not callDataMap_["BOB"].accountId_.empty()); auto const& account = Manager::instance().getAccount<SIPAccount>( callDataMap_["BOB"].accountId_); account->setLocalPort(callDataMap_["BOB"].listeningPort_); } { CPPUNIT_ASSERT(not callDataMap_["CARLA"].accountId_.empty()); auto const& account = Manager::instance().getAccount<SIPAccount>( callDataMap_["CARLA"].accountId_); account->setLocalPort(callDataMap_["CARLA"].listeningPort_); } std::map<std::string, std::shared_ptr<libjami::CallbackWrapperBase>> signalHandlers; // Insert needed signal handlers. signalHandlers.insert(libjami::exportable_callback<libjami::CallSignal::IncomingCallWithMedia>( [&](const std::string& accountId, const std::string& callId, const std::string&, const std::vector<libjami::MediaMap> mediaList) { auto alias = getUserAlias(accountId); if (not alias.empty()) { onIncomingCallWithMedia(accountId, callId, mediaList, callDataMap_[alias]); } })); signalHandlers.insert( libjami::exportable_callback<libjami::CallSignal::StateChange>([&](const std::string& accountId, const std::string& callId, const std::string& state, signed) { auto alias = getUserAlias(accountId); if (not alias.empty()) onCallStateChange(accountId, callId, state, callDataMap_[alias]); })); signalHandlers.insert(libjami::exportable_callback<libjami::CallSignal::MediaNegotiationStatus>( [&](const std::string& callId, const std::string& event, const std::vector<std::map<std::string, std::string>>& /* mediaList */) { auto alias = getUserAlias(getAccountId(callId)); if (not alias.empty()) onMediaNegotiationStatus(callId, event, callDataMap_[alias]); })); libjami::registerSignalHandlers(signalHandlers); } void SipBasicCallTest::audio_video_call(std::vector<MediaAttribute> offer, std::vector<MediaAttribute> answer, bool expectedToSucceed, bool validateMedia) { configureTest(); JAMI_INFO("=== Start a call and validate ==="); std::string bobUri = callDataMap_["BOB"].userName_ + "@127.0.0.1:" + std::to_string(callDataMap_["BOB"].listeningPort_); callDataMap_["ALICE"].callId_ = libjami::placeCallWithMedia(callDataMap_["ALICE"].accountId_, bobUri, MediaAttribute::mediaAttributesToMediaMaps(offer)); CPPUNIT_ASSERT(not callDataMap_["ALICE"].callId_.empty()); JAMI_INFO("ALICE [%s] started a call with BOB [%s] and wait for answer", callDataMap_["ALICE"].accountId_.c_str(), callDataMap_["BOB"].accountId_.c_str()); // Give it some time to ring std::this_thread::sleep_for(std::chrono::seconds(2)); // Wait for call to be processed. CPPUNIT_ASSERT(waitForSignal(callDataMap_["ALICE"], libjami::CallSignal::StateChange::name, StateEvent::RINGING)); // Wait for incoming call signal. CPPUNIT_ASSERT( waitForSignal(callDataMap_["BOB"], libjami::CallSignal::IncomingCallWithMedia::name)); // Answer the call. libjami::acceptWithMedia(callDataMap_["BOB"].accountId_, callDataMap_["BOB"].callId_, MediaAttribute::mediaAttributesToMediaMaps(answer)); if (expectedToSucceed) { // Wait for media negotiation complete signal. CPPUNIT_ASSERT( waitForSignal(callDataMap_["BOB"], libjami::CallSignal::MediaNegotiationStatus::name, libjami::Media::MediaNegotiationStatusEvents::NEGOTIATION_SUCCESS)); // Wait for the StateChange signal. CPPUNIT_ASSERT(waitForSignal(callDataMap_["BOB"], libjami::CallSignal::StateChange::name, StateEvent::CURRENT)); JAMI_INFO("BOB answered the call [%s]", callDataMap_["BOB"].callId_.c_str()); // Wait for media negotiation complete signal. CPPUNIT_ASSERT( waitForSignal(callDataMap_["ALICE"], libjami::CallSignal::MediaNegotiationStatus::name, libjami::Media::MediaNegotiationStatusEvents::NEGOTIATION_SUCCESS)); // Validate Alice's media if (validateMedia) { auto call = Manager::instance().getCallFromCallID(callDataMap_["ALICE"].callId_); auto activeMediaList = call->getMediaAttributeList(); CPPUNIT_ASSERT_EQUAL(offer.size(), activeMediaList.size()); // Audio CPPUNIT_ASSERT_EQUAL(MediaType::MEDIA_AUDIO, activeMediaList[0].type_); CPPUNIT_ASSERT_EQUAL(offer[0].enabled_, activeMediaList[0].enabled_); // Video if (offer.size() > 1) { CPPUNIT_ASSERT_EQUAL(MediaType::MEDIA_VIDEO, activeMediaList[1].type_); CPPUNIT_ASSERT_EQUAL(offer[1].enabled_, activeMediaList[1].enabled_); } } // Validate Bob's media if (validateMedia) { auto call = Manager::instance().getCallFromCallID(callDataMap_["BOB"].callId_); auto activeMediaList = call->getMediaAttributeList(); CPPUNIT_ASSERT_EQUAL(answer.size(), activeMediaList.size()); // Audio CPPUNIT_ASSERT_EQUAL(MediaType::MEDIA_AUDIO, activeMediaList[0].type_); CPPUNIT_ASSERT_EQUAL(answer[0].enabled_, activeMediaList[0].enabled_); // Video if (offer.size() > 1) { CPPUNIT_ASSERT_EQUAL(MediaType::MEDIA_VIDEO, activeMediaList[1].type_); CPPUNIT_ASSERT_EQUAL(answer[1].enabled_, activeMediaList[1].enabled_); } } // Give some time to media to start and flow std::this_thread::sleep_for(std::chrono::seconds(3)); // Bob hang-up. JAMI_INFO("Hang up BOB's call and wait for ALICE to hang up"); libjami::hangUp(callDataMap_["BOB"].accountId_, callDataMap_["BOB"].callId_); } else { // The media negotiation for the call is expected to fail, so we // should receive the signal. CPPUNIT_ASSERT(waitForSignal(callDataMap_["BOB"], libjami::CallSignal::StateChange::name, StateEvent::FAILURE)); } // The hang-up signal will be emitted on caller's side (Alice) in both // success failure scenarios. CPPUNIT_ASSERT(waitForSignal(callDataMap_["ALICE"], libjami::CallSignal::StateChange::name, StateEvent::HUNGUP)); JAMI_INFO("Call terminated on both sides"); } void SipBasicCallTest::audio_only_test() { // Test with video enabled on Alice's side and disabled // on Bob's side. JAMI_INFO("=== Begin test %s ===", __FUNCTION__); auto const aliceAcc = Manager::instance().getAccount<SIPAccount>( callDataMap_["ALICE"].accountId_); auto const bobAcc = Manager::instance().getAccount<SIPAccount>(callDataMap_["BOB"].accountId_); std::vector<MediaAttribute> offer; std::vector<MediaAttribute> answer; MediaAttribute audio(MediaType::MEDIA_AUDIO); MediaAttribute video(MediaType::MEDIA_VIDEO); // Configure Alice audio.enabled_ = true; audio.label_ = "audio_0"; offer.emplace_back(audio); video.enabled_ = true; video.label_ = "video_0"; aliceAcc->enableVideo(true); offer.emplace_back(video); // Configure Bob audio.enabled_ = true; audio.label_ = "audio_0"; answer.emplace_back(audio); video.enabled_ = false; video.label_ = "video_0"; bobAcc->enableVideo(false); answer.emplace_back(video); // Run the scenario audio_video_call(offer, answer); } void SipBasicCallTest::audio_video_test() { JAMI_INFO("=== Begin test %s ===", __FUNCTION__); auto const aliceAcc = Manager::instance().getAccount<SIPAccount>( callDataMap_["ALICE"].accountId_); auto const bobAcc = Manager::instance().getAccount<SIPAccount>(callDataMap_["BOB"].accountId_); std::vector<MediaAttribute> offer; std::vector<MediaAttribute> answer; MediaAttribute audio(MediaType::MEDIA_AUDIO); MediaAttribute video(MediaType::MEDIA_VIDEO); // Configure Alice audio.enabled_ = true; audio.label_ = "audio_0"; offer.emplace_back(audio); video.enabled_ = true; video.label_ = "video_0"; aliceAcc->enableVideo(true); offer.emplace_back(video); // Configure Bob audio.enabled_ = true; audio.label_ = "audio_0"; answer.emplace_back(audio); video.enabled_ = true; video.label_ = "video_0"; bobAcc->enableVideo(true); answer.emplace_back(video); // Run the scenario audio_video_call(offer, answer); } void SipBasicCallTest::peer_answer_with_all_media_disabled() { JAMI_INFO("=== Begin test %s ===", __FUNCTION__); auto const bobAcc = Manager::instance().getAccount<SIPAccount>(callDataMap_["BOB"].accountId_); std::vector<MediaAttribute> offer; std::vector<MediaAttribute> answer; MediaAttribute video(MediaType::MEDIA_VIDEO); // Configure Alice video.enabled_ = true; video.label_ = "video_0"; video.secure_ = false; offer.emplace_back(video); // Configure Bob video.enabled_ = false; video.label_ = "video_0"; video.secure_ = false; bobAcc->enableVideo(false); answer.emplace_back(video); // Run the scenario audio_video_call(offer, answer, false, false); } void SipBasicCallTest::hold_resume_test() { JAMI_INFO("=== Begin test %s ===", __FUNCTION__); auto const aliceAcc = Manager::instance().getAccount<SIPAccount>( callDataMap_["ALICE"].accountId_); auto const bobAcc = Manager::instance().getAccount<SIPAccount>(callDataMap_["BOB"].accountId_); std::vector<MediaAttribute> offer; std::vector<MediaAttribute> answer; MediaAttribute audio(MediaType::MEDIA_AUDIO); MediaAttribute video(MediaType::MEDIA_VIDEO); audio.enabled_ = true; audio.label_ = "audio_0"; video.enabled_ = true; video.label_ = "video_0"; // Alice's media offer.emplace_back(audio); offer.emplace_back(video); // Bob's media answer.emplace_back(audio); answer.emplace_back(video); { configureTest(); JAMI_INFO("=== Start a call and validate ==="); std::string bobUri = callDataMap_["BOB"].userName_ + "@127.0.0.1:" + std::to_string(callDataMap_["BOB"].listeningPort_); callDataMap_["ALICE"].callId_ = libjami::placeCallWithMedia(callDataMap_["ALICE"].accountId_, bobUri, MediaAttribute::mediaAttributesToMediaMaps(offer)); CPPUNIT_ASSERT(not callDataMap_["ALICE"].callId_.empty()); JAMI_INFO("ALICE [%s] started a call with BOB [%s] and wait for answer", callDataMap_["ALICE"].accountId_.c_str(), callDataMap_["BOB"].accountId_.c_str()); // Give it some time to ring std::this_thread::sleep_for(std::chrono::seconds(2)); // Wait for call to be processed. CPPUNIT_ASSERT(waitForSignal(callDataMap_["ALICE"], libjami::CallSignal::StateChange::name, StateEvent::RINGING)); // Wait for incoming call signal. CPPUNIT_ASSERT( waitForSignal(callDataMap_["BOB"], libjami::CallSignal::IncomingCallWithMedia::name)); // Answer the call. libjami::acceptWithMedia(callDataMap_["BOB"].accountId_, callDataMap_["BOB"].callId_, MediaAttribute::mediaAttributesToMediaMaps(answer)); // Wait for media negotiation complete signal. CPPUNIT_ASSERT( waitForSignal(callDataMap_["BOB"], libjami::CallSignal::MediaNegotiationStatus::name, libjami::Media::MediaNegotiationStatusEvents::NEGOTIATION_SUCCESS)); // Wait for the StateChange signal. CPPUNIT_ASSERT(waitForSignal(callDataMap_["BOB"], libjami::CallSignal::StateChange::name, StateEvent::CURRENT)); JAMI_INFO("BOB answered the call [%s]", callDataMap_["BOB"].callId_.c_str()); // Wait for media negotiation complete signal. CPPUNIT_ASSERT( waitForSignal(callDataMap_["ALICE"], libjami::CallSignal::MediaNegotiationStatus::name, libjami::Media::MediaNegotiationStatusEvents::NEGOTIATION_SUCCESS)); // Validate Alice's side of media direction { auto call = std::static_pointer_cast<SIPCall>( Manager::instance().getCallFromCallID(callDataMap_["ALICE"].callId_)); auto& sdp = call->getSDP(); auto mediaStreams = sdp.getMediaSlots(); for (auto const& media : mediaStreams) { CPPUNIT_ASSERT_EQUAL(MediaDirection::SENDRECV, media.first.direction_); CPPUNIT_ASSERT_EQUAL(MediaDirection::SENDRECV, media.second.direction_); } } // Validate Bob's side of media direction { auto call = std::static_pointer_cast<SIPCall>( Manager::instance().getCallFromCallID(callDataMap_["BOB"].callId_)); auto& sdp = call->getSDP(); auto mediaStreams = sdp.getMediaSlots(); for (auto const& media : mediaStreams) { CPPUNIT_ASSERT_EQUAL(MediaDirection::SENDRECV, media.first.direction_); CPPUNIT_ASSERT_EQUAL(MediaDirection::SENDRECV, media.second.direction_); } } // Give some time to media to start and flow std::this_thread::sleep_for(std::chrono::seconds(2)); // Hold/Resume the call JAMI_INFO("Hold Alice's call"); libjami::hold(callDataMap_["ALICE"].accountId_, callDataMap_["ALICE"].callId_); // Wait for the StateChange signal. CPPUNIT_ASSERT(waitForSignal(callDataMap_["ALICE"], libjami::CallSignal::StateChange::name, StateEvent::HOLD)); // Wait for media negotiation complete signal. CPPUNIT_ASSERT( waitForSignal(callDataMap_["ALICE"], libjami::CallSignal::MediaNegotiationStatus::name, libjami::Media::MediaNegotiationStatusEvents::NEGOTIATION_SUCCESS)); { // Validate hold state. auto call = Manager::instance().getCallFromCallID(callDataMap_["ALICE"].callId_); auto activeMediaList = call->getMediaAttributeList(); for (const auto& mediaAttr : activeMediaList) { CPPUNIT_ASSERT(mediaAttr.onHold_); } } // Validate Alice's side of media direction { auto call = std::static_pointer_cast<SIPCall>( Manager::instance().getCallFromCallID(callDataMap_["ALICE"].callId_)); auto& sdp = call->getSDP(); auto mediaStreams = sdp.getMediaSlots(); for (auto const& media : mediaStreams) { if (media.first.type == MediaType::MEDIA_AUDIO) { CPPUNIT_ASSERT_EQUAL(MediaDirection::SENDRECV, media.first.direction_); CPPUNIT_ASSERT_EQUAL(MediaDirection::SENDRECV, media.second.direction_); } else { CPPUNIT_ASSERT_EQUAL(MediaDirection::SENDONLY, media.first.direction_); CPPUNIT_ASSERT_EQUAL(MediaDirection::RECVONLY, media.second.direction_); } } } // Validate Bob's side of media direction { auto call = std::static_pointer_cast<SIPCall>( Manager::instance().getCallFromCallID(callDataMap_["BOB"].callId_)); auto& sdp = call->getSDP(); auto mediaStreams = sdp.getMediaSlots(); for (auto const& media : mediaStreams) { if (media.first.type == MediaType::MEDIA_AUDIO) { CPPUNIT_ASSERT_EQUAL(MediaDirection::SENDRECV, media.first.direction_); CPPUNIT_ASSERT_EQUAL(MediaDirection::SENDRECV, media.second.direction_); } else { CPPUNIT_ASSERT_EQUAL(MediaDirection::RECVONLY, media.first.direction_); CPPUNIT_ASSERT_EQUAL(MediaDirection::SENDONLY, media.second.direction_); } } } std::this_thread::sleep_for(std::chrono::seconds(2)); JAMI_INFO("Resume Alice's call"); libjami::unhold(callDataMap_["ALICE"].accountId_, callDataMap_["ALICE"].callId_); // Wait for the StateChange signal. CPPUNIT_ASSERT(waitForSignal(callDataMap_["ALICE"], libjami::CallSignal::StateChange::name, StateEvent::CURRENT)); // Wait for media negotiation complete signal. CPPUNIT_ASSERT( waitForSignal(callDataMap_["ALICE"], libjami::CallSignal::MediaNegotiationStatus::name, libjami::Media::MediaNegotiationStatusEvents::NEGOTIATION_SUCCESS)); std::this_thread::sleep_for(std::chrono::seconds(2)); { // Validate hold state. auto call = Manager::instance().getCallFromCallID(callDataMap_["ALICE"].callId_); auto activeMediaList = call->getMediaAttributeList(); for (const auto& mediaAttr : activeMediaList) { CPPUNIT_ASSERT(not mediaAttr.onHold_); } } // Bob hang-up. JAMI_INFO("Hang up BOB's call and wait for ALICE to hang up"); libjami::hangUp(callDataMap_["BOB"].accountId_, callDataMap_["BOB"].callId_); // The hang-up signal will be emitted on caller's side (Alice) in both // success and failure scenarios. CPPUNIT_ASSERT(waitForSignal(callDataMap_["ALICE"], libjami::CallSignal::StateChange::name, StateEvent::HUNGUP)); JAMI_INFO("Call terminated on both sides"); } } void SipBasicCallTest::blind_transfer_test() { // Test a "blind" (a.k.a. unattended) transfer as described in // https://datatracker.ietf.org/doc/html/rfc5589 /** Call transfer scenario: * * Alice and Bob are in an active call * Alice performs a call transfer (SIP REFER method) to Carla * Bob automatically accepts the transfer request * Alice ends the call with Bob * Bob send a new call invite to Carla * Carla accepts the call * Carl ends the call * * Here is a simplified version of a call flow from * rfc5589 * * Alice Bob Carla | REFER | | |----------------------->| | | 202 Accepted | | |<-----------------------| | | BYE | | |<-----------------------| | | 200 OK | | |----------------------->| | | | INVITE | | |----------------------->| | | 200 OK | | |<-----------------------| */ JAMI_INFO("=== Begin test %s ===", __FUNCTION__); auto const aliceAcc = Manager::instance().getAccount<SIPAccount>( callDataMap_["ALICE"].accountId_); auto const bobAcc = Manager::instance().getAccount<SIPAccount>(callDataMap_["BOB"].accountId_); auto const carlaAcc = Manager::instance().getAccount<SIPAccount>( callDataMap_["CARLA"].accountId_); aliceAcc->enableIceForMedia(false); bobAcc->enableIceForMedia(false); carlaAcc->enableIceForMedia(false); std::vector<MediaAttribute> offer; std::vector<MediaAttribute> answer; MediaAttribute audio(MediaType::MEDIA_AUDIO); MediaAttribute video(MediaType::MEDIA_VIDEO); audio.enabled_ = true; audio.label_ = "audio_0"; // Alice's media offer.emplace_back(audio); // Bob's media answer.emplace_back(audio); configureTest(); JAMI_INFO("=== Start a call and validate ==="); std::string bobUri = callDataMap_["BOB"].userName_ + "@127.0.0.1:" + std::to_string(callDataMap_["BOB"].listeningPort_); callDataMap_["ALICE"].callId_ = libjami::placeCallWithMedia(callDataMap_["ALICE"].accountId_, bobUri, MediaAttribute::mediaAttributesToMediaMaps(offer)); CPPUNIT_ASSERT(not callDataMap_["ALICE"].callId_.empty()); JAMI_INFO("ALICE [%s] started a call with BOB [%s] and wait for answer", callDataMap_["ALICE"].accountId_.c_str(), callDataMap_["BOB"].accountId_.c_str()); // Give it some time to ring std::this_thread::sleep_for(std::chrono::seconds(2)); // Wait for call to be processed. CPPUNIT_ASSERT(waitForSignal(callDataMap_["ALICE"], libjami::CallSignal::StateChange::name, StateEvent::RINGING)); // Wait for incoming call signal. CPPUNIT_ASSERT( waitForSignal(callDataMap_["BOB"], libjami::CallSignal::IncomingCallWithMedia::name)); // Answer the call. libjami::acceptWithMedia(callDataMap_["BOB"].accountId_, callDataMap_["BOB"].callId_, MediaAttribute::mediaAttributesToMediaMaps(answer)); // Wait for media negotiation complete signal. CPPUNIT_ASSERT(waitForSignal(callDataMap_["BOB"], libjami::CallSignal::MediaNegotiationStatus::name, libjami::Media::MediaNegotiationStatusEvents::NEGOTIATION_SUCCESS)); // Wait for the StateChange signal. CPPUNIT_ASSERT(waitForSignal(callDataMap_["BOB"], libjami::CallSignal::StateChange::name, StateEvent::CURRENT)); JAMI_INFO("BOB answered the call [%s]", callDataMap_["BOB"].callId_.c_str()); // Wait for media negotiation complete signal. CPPUNIT_ASSERT(waitForSignal(callDataMap_["ALICE"], libjami::CallSignal::MediaNegotiationStatus::name, libjami::Media::MediaNegotiationStatusEvents::NEGOTIATION_SUCCESS)); // Give some time to media to start and flow std::this_thread::sleep_for(std::chrono::seconds(2)); // Transfer the call to Carla std::string carlaUri = carlaAcc->getUsername() + "@127.0.0.1:" + std::to_string(callDataMap_["CARLA"].listeningPort_); libjami::transfer(callDataMap_["ALICE"].accountId_, callDataMap_["ALICE"].callId_, carlaUri); // TODO. Check trim // Expect Alice's call to end. CPPUNIT_ASSERT(waitForSignal(callDataMap_["ALICE"], libjami::CallSignal::StateChange::name, StateEvent::HUNGUP)); // Wait for the new call to be processed. CPPUNIT_ASSERT(waitForSignal(callDataMap_["BOB"], libjami::CallSignal::StateChange::name, StateEvent::RINGING)); // Wait for incoming call signal. CPPUNIT_ASSERT( waitForSignal(callDataMap_["CARLA"], libjami::CallSignal::IncomingCallWithMedia::name)); // Let it ring std::this_thread::sleep_for(std::chrono::seconds(2)); // Carla answers the call. libjami::acceptWithMedia(callDataMap_["CARLA"].accountId_, callDataMap_["CARLA"].callId_, MediaAttribute::mediaAttributesToMediaMaps(answer)); // Wait for media negotiation complete signal. CPPUNIT_ASSERT(waitForSignal(callDataMap_["CARLA"], libjami::CallSignal::MediaNegotiationStatus::name, libjami::Media::MediaNegotiationStatusEvents::NEGOTIATION_SUCCESS)); // Wait for the StateChange signal. CPPUNIT_ASSERT(waitForSignal(callDataMap_["CARLA"], libjami::CallSignal::StateChange::name, StateEvent::CURRENT)); JAMI_INFO("CARLA answered the call [%s]", callDataMap_["BOB"].callId_.c_str()); // Wait for media negotiation complete signal. CPPUNIT_ASSERT(waitForSignal(callDataMap_["BOB"], libjami::CallSignal::MediaNegotiationStatus::name, libjami::Media::MediaNegotiationStatusEvents::NEGOTIATION_SUCCESS)); // Wait for the StateChange signal. CPPUNIT_ASSERT(waitForSignal(callDataMap_["BOB"], libjami::CallSignal::StateChange::name, StateEvent::CURRENT)); // Validate Carla's side of media direction { auto call = std::static_pointer_cast<SIPCall>( Manager::instance().getCallFromCallID(callDataMap_["CARLA"].callId_)); auto& sdp = call->getSDP(); auto mediaStreams = sdp.getMediaSlots(); for (auto const& media : mediaStreams) { CPPUNIT_ASSERT_EQUAL(MediaDirection::SENDRECV, media.first.direction_); CPPUNIT_ASSERT_EQUAL(MediaDirection::SENDRECV, media.second.direction_); } } // NOTE: // For now, we dont validate Bob's media because currently // test does not update BOB's call ID (callDataMap_["BOB"].callId_ // still point to the first call). // It seems there is no easy way to get the ID of the new call // made by Bob to Carla. // Give some time to media to start and flow std::this_thread::sleep_for(std::chrono::seconds(2)); // Bob hang-up. JAMI_INFO("Hang up CARLA's call and wait for CARLA to hang up"); libjami::hangUp(callDataMap_["CARLA"].accountId_, callDataMap_["CARLA"].callId_); // Expect end call on Carla's side. CPPUNIT_ASSERT(waitForSignal(callDataMap_["CARLA"], libjami::CallSignal::StateChange::name, StateEvent::HUNGUP)); JAMI_INFO("Calls normally ended on both sides"); } } // namespace test } // namespace jami RING_TEST_RUNNER(jami::test::SipBasicCallTest::name())
41,318
C++
.cpp
897
35.459309
106
0.592965
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,684
account_archive.cpp
savoirfairelinux_jami-daemon/test/unitTest/account_archive/account_archive.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "manager.h" #include "jamidht/conversationrepository.h" #include "jamidht/gitserver.h" #include "jamidht/jamiaccount.h" #include "../../test_runner.h" #include "archiver.h" #include "base64.h" #include "jami.h" #include "fileutils.h" #include "account_const.h" #include "account_schema.h" #include "common.h" #include <dhtnet/connectionmanager.h> #include <cppunit/TestAssert.h> #include <cppunit/TestFixture.h> #include <cppunit/extensions/HelperMacros.h> #include <git2.h> #include <condition_variable> #include <string> #include <fstream> #include <streambuf> #include <filesystem> using namespace std::string_literals; using namespace std::literals::chrono_literals; using namespace libjami::Account; namespace jami { namespace test { class AccountArchiveTest : public CppUnit::TestFixture { public: AccountArchiveTest() { // Init daemon libjami::init(libjami::InitFlag(libjami::LIBJAMI_FLAG_DEBUG | libjami::LIBJAMI_FLAG_CONSOLE_LOG)); if (not Manager::instance().initialized) CPPUNIT_ASSERT(libjami::start("dring-sample.yml")); } ~AccountArchiveTest() { libjami::fini(); } static std::string name() { return "AccountArchive"; } void setUp(); void tearDown(); std::string aliceId; std::string bobId; std::string bob2Id; std::map<std::string, std::shared_ptr<libjami::CallbackWrapperBase>> confHandlers; std::mutex mtx; std::unique_lock<std::mutex> lk {mtx}; std::condition_variable cv; bool aliceReady = false; private: void testExportImportNoPassword(); void testExportImportNoPasswordDoubleGunzip(); void testExportImportPassword(); void testExportImportPasswordDoubleGunzip(); void testExportDht(); void testExportDhtWrongPassword(); void testChangePassword(); void testChangeDhtPort(); CPPUNIT_TEST_SUITE(AccountArchiveTest); CPPUNIT_TEST(testExportImportNoPassword); CPPUNIT_TEST(testExportImportNoPasswordDoubleGunzip); CPPUNIT_TEST(testExportImportPassword); CPPUNIT_TEST(testExportImportPasswordDoubleGunzip); CPPUNIT_TEST(testExportDht); CPPUNIT_TEST(testExportDhtWrongPassword); CPPUNIT_TEST(testChangePassword); CPPUNIT_TEST(testChangeDhtPort); CPPUNIT_TEST_SUITE_END(); }; CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(AccountArchiveTest, AccountArchiveTest::name()); void AccountArchiveTest::setUp() { auto actors = load_actors_and_wait_for_announcement("actors/alice-bob-password.yml"); aliceId = actors["alice"]; bobId = actors["bob"]; confHandlers.insert( libjami::exportable_callback<libjami::ConfigurationSignal::VolatileDetailsChanged>( [&](const std::string& accountId, const std::map<std::string, std::string>& details) { if (accountId != aliceId) { return; } try { aliceReady |= accountId == aliceId && details.at(jami::Conf::CONFIG_ACCOUNT_REGISTRATION_STATUS) == "REGISTERED" && details.at(libjami::Account::VolatileProperties::DEVICE_ANNOUNCED) == "true"; } catch (const std::out_of_range&) {} cv.notify_one(); })); libjami::registerSignalHandlers(confHandlers); } void AccountArchiveTest::tearDown() { if (!bob2Id.empty()) wait_for_removal_of({aliceId, bob2Id, bobId}); else wait_for_removal_of({aliceId, bobId}); } void AccountArchiveTest::testExportImportNoPassword() { auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); CPPUNIT_ASSERT(aliceAccount->exportArchive("test.gz")); std::map<std::string, std::string> details = libjami::getAccountTemplate("RING"); details[ConfProperties::ARCHIVE_PATH] = "test.gz"; auto accountId = jami::Manager::instance().addAccount(details); wait_for_announcement_of(accountId); auto alice2Account = Manager::instance().getAccount<JamiAccount>(accountId); CPPUNIT_ASSERT(alice2Account->getUsername() == aliceAccount->getUsername()); std::remove("test.gz"); wait_for_removal_of(accountId); } void AccountArchiveTest::testExportImportNoPasswordDoubleGunzip() { auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); CPPUNIT_ASSERT(aliceAccount->exportArchive("test.gz")); auto dat = fileutils::loadFile("test.gz"); archiver::compressGzip(dat, "test.gz"); std::map<std::string, std::string> details = libjami::getAccountTemplate("RING"); details[ConfProperties::ARCHIVE_PATH] = "test.gz"; auto accountId = jami::Manager::instance().addAccount(details); wait_for_announcement_of(accountId); auto alice2Account = Manager::instance().getAccount<JamiAccount>(accountId); CPPUNIT_ASSERT(alice2Account->getUsername() == aliceAccount->getUsername()); std::remove("test.gz"); wait_for_removal_of(accountId); } void AccountArchiveTest::testExportImportPassword() { auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); CPPUNIT_ASSERT(bobAccount->exportArchive("test.gz", "password", "test")); std::map<std::string, std::string> details = libjami::getAccountTemplate("RING"); details[ConfProperties::ARCHIVE_PATH] = "test.gz"; details[ConfProperties::ARCHIVE_PASSWORD] = "test"; auto accountId = jami::Manager::instance().addAccount(details); wait_for_announcement_of(accountId); auto bob2Account = Manager::instance().getAccount<JamiAccount>(accountId); CPPUNIT_ASSERT(bob2Account->getUsername() == bobAccount->getUsername()); std::remove("test.gz"); wait_for_removal_of(accountId); } void AccountArchiveTest::testExportImportPasswordDoubleGunzip() { auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); CPPUNIT_ASSERT(bobAccount->exportArchive("test.gz", "password", "test")); auto dat = fileutils::loadFile("test.gz"); archiver::compressGzip(dat, "test.gz"); std::map<std::string, std::string> details = libjami::getAccountTemplate("RING"); details[ConfProperties::ARCHIVE_PATH] = "test.gz"; details[ConfProperties::ARCHIVE_PASSWORD] = "test"; auto accountId = jami::Manager::instance().addAccount(details); wait_for_announcement_of(accountId); auto bob2Account = Manager::instance().getAccount<JamiAccount>(accountId); CPPUNIT_ASSERT(bob2Account->getUsername() == bobAccount->getUsername()); std::remove("test.gz"); wait_for_removal_of(accountId); } void AccountArchiveTest::testExportDht() { std::mutex mtx; std::unique_lock lk {mtx}; std::condition_variable cv; std::map<std::string, std::shared_ptr<libjami::CallbackWrapperBase>> confHandlers; std::string pin; confHandlers.insert(libjami::exportable_callback<libjami::ConfigurationSignal::ExportOnRingEnded>( [&](const std::string& accountId, int status, const std::string& p) { if (accountId == bobId && status == 0) pin = p; cv.notify_one(); })); libjami::registerSignalHandlers(confHandlers); CPPUNIT_ASSERT(libjami::exportOnRing(bobId, "test")); CPPUNIT_ASSERT(cv.wait_for(lk, 20s, [&] { return !pin.empty(); })); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); std::map<std::string, std::string> details = libjami::getAccountTemplate("RING"); details[ConfProperties::ARCHIVE_PIN] = pin; details[ConfProperties::ARCHIVE_PASSWORD] = "test"; bob2Id = jami::Manager::instance().addAccount(details); wait_for_announcement_of(bob2Id); auto bob2Account = Manager::instance().getAccount<JamiAccount>(bob2Id); CPPUNIT_ASSERT(bob2Account->getUsername() == bobAccount->getUsername()); } void AccountArchiveTest::testExportDhtWrongPassword() { std::mutex mtx; std::unique_lock lk {mtx}; std::condition_variable cv; std::map<std::string, std::shared_ptr<libjami::CallbackWrapperBase>> confHandlers; int status; confHandlers.insert(libjami::exportable_callback<libjami::ConfigurationSignal::ExportOnRingEnded>( [&](const std::string& accountId, int s, const std::string&) { if (accountId == bobId) status = s; cv.notify_one(); })); libjami::registerSignalHandlers(confHandlers); CPPUNIT_ASSERT(libjami::exportOnRing(bobId, "wrong")); CPPUNIT_ASSERT(cv.wait_for(lk, 10s, [&] { return status == 1; })); } void AccountArchiveTest::testChangePassword() { // Test incorrect password, should fail CPPUNIT_ASSERT(!libjami::changeAccountPassword(aliceId, "wrong", "new")); // Test correct password, should succeed CPPUNIT_ASSERT(libjami::changeAccountPassword(aliceId, "", "new")); // Now it should fail CPPUNIT_ASSERT(!libjami::changeAccountPassword(aliceId, "", "new")); // Remove password again (should succeed) CPPUNIT_ASSERT(libjami::changeAccountPassword(aliceId, "new", "")); } void AccountArchiveTest::testChangeDhtPort() { auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); std::map<std::string, std::string> newDetails; newDetails[libjami::Account::ConfProperties::DHT_PORT] = "1412"; aliceReady = false; libjami::setAccountDetails(aliceId, newDetails); cv.wait_for(lk, 20s, [&] { return aliceReady; }); CPPUNIT_ASSERT(aliceAccount->dht()->getBoundPort() == 1412); newDetails[libjami::Account::ConfProperties::DHT_PORT] = "1413"; aliceReady = false; libjami::setAccountDetails(aliceId, newDetails); cv.wait_for(lk, 20s, [&] { return aliceReady; }); CPPUNIT_ASSERT(aliceAccount->dht()->getBoundPort() == 1413); } } // namespace test } // namespace jami RING_TEST_RUNNER(jami::test::AccountArchiveTest::name())
10,519
C++
.cpp
253
36.687747
112
0.710694
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,685
migration.cpp
savoirfairelinux_jami-daemon/test/unitTest/account_archive/migration.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <cppunit/TestAssert.h> #include <cppunit/TestFixture.h> #include <cppunit/extensions/HelperMacros.h> #include <condition_variable> #include <string> #include <filesystem> #include <fstream> #include <streambuf> #include <fmt/format.h> #include "manager.h" #include "jamidht/accountarchive.h" #include "jamidht/jamiaccount.h" #include "../../test_runner.h" #include "account_const.h" #include "common.h" #include "fileutils.h" using namespace std::string_literals; using namespace std::literals::chrono_literals; using namespace libjami::Account; namespace jami { namespace test { class MigrationTest : public CppUnit::TestFixture { public: MigrationTest() { // Init daemon libjami::init(libjami::InitFlag(libjami::LIBJAMI_FLAG_DEBUG | libjami::LIBJAMI_FLAG_CONSOLE_LOG)); if (not Manager::instance().initialized) CPPUNIT_ASSERT(libjami::start("dring-sample.yml")); } ~MigrationTest() { libjami::fini(); } static std::string name() { return "AccountArchive"; } void setUp(); void tearDown(); std::string aliceId; std::string bobId; std::string bob2Id; private: void testLoadExpiredAccount(); void testMigrationAfterRevokation(); void testExpiredDeviceInSwarm(); CPPUNIT_TEST_SUITE(MigrationTest); CPPUNIT_TEST(testLoadExpiredAccount); CPPUNIT_TEST(testMigrationAfterRevokation); CPPUNIT_TEST(testExpiredDeviceInSwarm); CPPUNIT_TEST_SUITE_END(); }; CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(MigrationTest, MigrationTest::name()); void MigrationTest::setUp() { auto actors = load_actors("actors/alice-bob.yml"); aliceId = actors["alice"]; bobId = actors["bob"]; } void MigrationTest::tearDown() { auto bobArchive = std::filesystem::current_path().string() + "/bob.gz"; std::remove(bobArchive.c_str()); if (!bob2Id.empty()) wait_for_removal_of({aliceId, bob2Id, bobId}); else wait_for_removal_of({aliceId, bobId}); } void MigrationTest::testLoadExpiredAccount() { wait_for_announcement_of({aliceId, bobId}); auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto aliceUri = aliceAccount->getUsername(); auto aliceDevice = std::string(aliceAccount->currentDeviceId()); // Get alice's expiration auto archivePath = fileutils::get_data_dir() / aliceAccount->getAccountID() / "archive.gz"; auto devicePath = fileutils::get_data_dir() / aliceAccount->getAccountID() / "ring_device.crt"; auto archive = AccountArchive(archivePath); auto deviceCert = dht::crypto::Certificate(fileutils::loadFile(devicePath)); auto deviceExpiration = deviceCert.getExpiration(); auto accountExpiration = archive.id.second->getExpiration(); // Update validity CPPUNIT_ASSERT(aliceAccount->setValidity("", "", {}, 9)); archive = AccountArchive(archivePath); deviceCert = dht::crypto::Certificate(fileutils::loadFile(devicePath)); auto newDeviceExpiration = deviceCert.getExpiration(); auto newAccountExpiration = archive.id.second->getExpiration(); // Check expiration is changed CPPUNIT_ASSERT(newDeviceExpiration < deviceExpiration && newAccountExpiration < accountExpiration); // Sleep and wait that certificate is expired std::this_thread::sleep_for(10s); // reload account, check migration signals std::mutex mtx; std::unique_lock lk {mtx}; std::condition_variable cv; std::map<std::string, std::shared_ptr<libjami::CallbackWrapperBase>> confHandlers; auto aliceMigrated = false; confHandlers.insert(libjami::exportable_callback<libjami::ConfigurationSignal::MigrationEnded>( [&](const std::string& accountId, const std::string& state) { if (accountId == aliceId && state == "SUCCESS") { aliceMigrated = true; } cv.notify_one(); })); libjami::registerSignalHandlers(confHandlers); // Check migration is triggered and expiration updated aliceAccount->forceReloadAccount(); CPPUNIT_ASSERT(cv.wait_for(lk, 15s, [&]() { return aliceMigrated; })); archive = AccountArchive(archivePath); deviceCert = dht::crypto::Certificate(fileutils::loadFile(devicePath)); deviceExpiration = deviceCert.getExpiration(); accountExpiration = archive.id.second->getExpiration(); CPPUNIT_ASSERT(newDeviceExpiration < deviceExpiration && newAccountExpiration < accountExpiration); CPPUNIT_ASSERT(aliceUri == aliceAccount->getUsername()); CPPUNIT_ASSERT(aliceDevice == aliceAccount->currentDeviceId()); } void MigrationTest::testMigrationAfterRevokation() { wait_for_announcement_of({aliceId, bobId}); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto bobUri = bobAccount->getUsername(); // Generate bob2 std::mutex mtx; std::unique_lock lk {mtx}; std::condition_variable cv; // Add second device for Bob std::map<std::string, std::shared_ptr<libjami::CallbackWrapperBase>> confHandlers; auto bobArchive = std::filesystem::current_path().string() + "/bob.gz"; std::remove(bobArchive.c_str()); bobAccount->exportArchive(bobArchive); std::map<std::string, std::string> details = libjami::getAccountTemplate("RING"); details[ConfProperties::TYPE] = "RING"; details[ConfProperties::DISPLAYNAME] = "BOB2"; details[ConfProperties::ALIAS] = "BOB2"; details[ConfProperties::UPNP_ENABLED] = "true"; details[ConfProperties::ARCHIVE_PASSWORD] = ""; details[ConfProperties::ARCHIVE_PIN] = ""; details[ConfProperties::ARCHIVE_PATH] = bobArchive; auto deviceRevoked = false; confHandlers.insert( libjami::exportable_callback<libjami::ConfigurationSignal::DeviceRevocationEnded>( [&](const std::string& accountId, const std::string&, int status) { if (accountId == bobId && status == 0) deviceRevoked = true; cv.notify_one(); })); auto bobMigrated = false; confHandlers.insert(libjami::exportable_callback<libjami::ConfigurationSignal::MigrationEnded>( [&](const std::string& accountId, const std::string& state) { if (accountId == bob2Id && state == "SUCCESS") { bobMigrated = true; } cv.notify_one(); })); auto knownChanged = false; confHandlers.insert(libjami::exportable_callback<libjami::ConfigurationSignal::KnownDevicesChanged>( [&](const std::string& accountId, auto devices) { if (accountId == bobId && devices.size() == 2) knownChanged = true; cv.notify_one(); })); libjami::registerSignalHandlers(confHandlers); bob2Id = Manager::instance().addAccount(details); auto bob2Account = Manager::instance().getAccount<JamiAccount>(bob2Id); CPPUNIT_ASSERT(cv.wait_for(lk, 20s, [&]() { return knownChanged; })); // Revoke bob2 auto bob2Device = std::string(bob2Account->currentDeviceId()); bobAccount->revokeDevice(bob2Device); CPPUNIT_ASSERT(cv.wait_for(lk, 10s, [&]() { return deviceRevoked; })); // Note: bob2 will need some seconds to get the revokation list std::this_thread::sleep_for(10s); // Check migration is triggered and expiration updated bob2Account->forceReloadAccount(); CPPUNIT_ASSERT(cv.wait_for(lk, 15s, [&]() { return bobMigrated; })); // Because the device was revoked, a new ID must be generated there CPPUNIT_ASSERT(bob2Device != bob2Account->currentDeviceId()); } void MigrationTest::testExpiredDeviceInSwarm() { auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); std::mutex mtx; std::unique_lock lk {mtx}; std::condition_variable cv; std::map<std::string, std::shared_ptr<libjami::CallbackWrapperBase>> confHandlers; auto messageBobReceived = 0, messageAliceReceived = 0; confHandlers.insert(libjami::exportable_callback<libjami::ConversationSignal::MessageReceived>( [&](const std::string& accountId, const std::string& /* conversationId */, std::map<std::string, std::string> /*message*/) { if (accountId == bobId) { messageBobReceived += 1; } else { messageAliceReceived += 1; } cv.notify_one(); })); bool requestReceived = false; confHandlers.insert( libjami::exportable_callback<libjami::ConversationSignal::ConversationRequestReceived>( [&](const std::string& /*accountId*/, const std::string& /* conversationId */, std::map<std::string, std::string> /*metadatas*/) { requestReceived = true; cv.notify_one(); })); bool conversationReady = false; confHandlers.insert(libjami::exportable_callback<libjami::ConversationSignal::ConversationReady>( [&](const std::string& accountId, const std::string& /* conversationId */) { if (accountId == bobId) { conversationReady = true; cv.notify_one(); } })); auto aliceMigrated = false; confHandlers.insert(libjami::exportable_callback<libjami::ConfigurationSignal::MigrationEnded>( [&](const std::string& accountId, const std::string& state) { if (accountId == aliceId && state == "SUCCESS") { aliceMigrated = true; } cv.notify_one(); })); bool aliceStopped = false, aliceAnnounced = false, aliceRegistered = false, aliceRegistering = false; confHandlers.insert( libjami::exportable_callback<libjami::ConfigurationSignal::VolatileDetailsChanged>( [&](const std::string&, const std::map<std::string, std::string>&) { auto details = aliceAccount->getVolatileAccountDetails(); auto daemonStatus = details[libjami::Account::ConfProperties::Registration::STATUS]; if (daemonStatus == "UNREGISTERED") aliceStopped = true; else if (daemonStatus == "REGISTERED") aliceRegistered = true; else if (daemonStatus == "TRYING") aliceRegistering = true; auto announced = details[libjami::Account::VolatileProperties::DEVICE_ANNOUNCED]; if (announced == "true") aliceAnnounced = true; cv.notify_one(); })); libjami::registerSignalHandlers(confHandlers); // NOTE: We must update certificate before announcing, else, there will be several // certificates on the DHT CPPUNIT_ASSERT(cv.wait_for(lk, 10s, [&]() { return aliceRegistering; })); auto aliceDevice = std::string(aliceAccount->currentDeviceId()); CPPUNIT_ASSERT(aliceAccount->setValidity("", "", {}, 90)); auto now = std::chrono::system_clock::now(); aliceRegistered = false; aliceAccount->forceReloadAccount(); CPPUNIT_ASSERT(cv.wait_for(lk, 10s, [&]() { return aliceRegistered; })); CPPUNIT_ASSERT(aliceAccount->currentDeviceId() == aliceDevice); aliceStopped = false; Manager::instance().sendRegister(aliceId, false); CPPUNIT_ASSERT(cv.wait_for(lk, 15s, [&]() { return aliceStopped; })); aliceAnnounced = false; Manager::instance().sendRegister(aliceId, true); CPPUNIT_ASSERT(cv.wait_for(lk, 20s, [&]() { return aliceAnnounced; })); CPPUNIT_ASSERT(aliceAccount->currentDeviceId() == aliceDevice); // Create conversation auto convId = libjami::startConversation(aliceId); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto bobUri = bobAccount->getUsername(); libjami::addConversationMember(aliceId, convId, bobUri); CPPUNIT_ASSERT(cv.wait_for(lk, 20s, [&]() { return requestReceived; })); messageAliceReceived = 0; libjami::acceptConversationRequest(bobId, convId); CPPUNIT_ASSERT(cv.wait_for(lk, 20s, [&]() { return conversationReady; })); // Assert that repository exists auto repoPath = fileutils::get_data_dir() / bobAccount->getAccountID() / "conversations" / convId; CPPUNIT_ASSERT(std::filesystem::is_directory(repoPath)); // Wait that alice sees Bob cv.wait_for(lk, 20s, [&]() { return messageAliceReceived == 1; }); messageBobReceived = 0; libjami::sendMessage(aliceId, convId, "hi"s, ""); CPPUNIT_ASSERT(cv.wait_for(lk, 20s, [&]() { return messageBobReceived == 1; })); // Wait for certificate to expire std::this_thread::sleep_until(now + 100s); // Check migration is triggered and expiration updated aliceAnnounced = false; aliceAccount->forceReloadAccount(); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return aliceAnnounced; })); CPPUNIT_ASSERT(aliceAccount->currentDeviceId() == aliceDevice); // check that certificate in conversation is expired auto devicePath = repoPath / "devices" / fmt::format("{}.crt", aliceAccount->currentDeviceId()); CPPUNIT_ASSERT(std::filesystem::is_regular_file(devicePath)); auto cert = dht::crypto::Certificate(fileutils::loadFile(devicePath)); now = std::chrono::system_clock::now(); CPPUNIT_ASSERT(cert.getExpiration() < now); // Resend a new message messageBobReceived = 0; libjami::sendMessage(aliceId, convId, "hi again"s, ""); CPPUNIT_ASSERT(cv.wait_for(lk, 20s, [&]() { return messageBobReceived == 1; })); messageAliceReceived = 0; libjami::sendMessage(bobId, convId, "hi!"s, ""); CPPUNIT_ASSERT(cv.wait_for(lk, 20s, [&]() { return messageAliceReceived == 1; })); // check that certificate in conversation is updated CPPUNIT_ASSERT(std::filesystem::is_regular_file(devicePath)); cert = dht::crypto::Certificate(fileutils::loadFile(devicePath)); now = std::chrono::system_clock::now(); CPPUNIT_ASSERT(cert.getExpiration() > now); // Check same device as begining CPPUNIT_ASSERT(aliceAccount->currentDeviceId() == aliceDevice); } } // namespace test } // namespace jami RING_TEST_RUNNER(jami::test::MigrationTest::name())
14,900
C++
.cpp
324
39.515432
106
0.678414
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,686
fileTransfer.cpp
savoirfairelinux_jami-daemon/test/unitTest/fileTransfer/fileTransfer.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "fileutils.h" #include "manager.h" #include "jamidht/jamiaccount.h" #include "../../test_runner.h" #include "jami.h" #include "data_transfer.h" #include "jami/datatransfer_interface.h" #include "account_const.h" #include "common.h" #include <dhtnet/connectionmanager.h> #include <cppunit/TestAssert.h> #include <cppunit/TestFixture.h> #include <cppunit/extensions/HelperMacros.h> #include <condition_variable> #include <string> #include <filesystem> using namespace std::literals::chrono_literals; using namespace libjami::Account; using namespace std::literals::chrono_literals; namespace jami { namespace test { struct UserData { std::string conversationId; bool removed {false}; bool requestReceived {false}; bool registered {false}; bool stopped {false}; bool deviceAnnounced {false}; int code {0}; std::vector<libjami::SwarmMessage> messages; std::vector<libjami::SwarmMessage> messagesUpdated; }; class FileTransferTest : public CppUnit::TestFixture { public: FileTransferTest() { // Init daemon libjami::init( libjami::InitFlag(libjami::LIBJAMI_FLAG_DEBUG | libjami::LIBJAMI_FLAG_CONSOLE_LOG)); if (not Manager::instance().initialized) CPPUNIT_ASSERT(libjami::start("jami-sample.yml")); } ~FileTransferTest() { libjami::fini(); } static std::string name() { return "Call"; } bool compare(const std::string& fileA, const std::string& fileB) const; void setUp(); void tearDown(); std::string aliceId; UserData aliceData; std::string bobId; UserData bobData; std::string carlaId; UserData carlaData; std::filesystem::path sendPath {std::filesystem::current_path() / "SEND"}; std::filesystem::path recvPath {std::filesystem::current_path() / "RECV"}; std::filesystem::path recv2Path {std::filesystem::current_path() / "RECV2"}; std::mutex mtx; std::unique_lock<std::mutex> lk {mtx}; std::condition_variable cv; void connectSignals(); private: void testConversationFileTransfer(); void testFileTransferInConversation(); void testVcfFileTransferInConversation(); void testBadSha3sumOut(); void testBadSha3sumIn(); void testAskToMultipleParticipants(); void testCancelInTransfer(); void testCancelOutTransfer(); void testTransferInfo(); void testRemoveHardLink(); void testTooLarge(); void testDeleteFile(); CPPUNIT_TEST_SUITE(FileTransferTest); CPPUNIT_TEST(testConversationFileTransfer); CPPUNIT_TEST(testFileTransferInConversation); CPPUNIT_TEST(testVcfFileTransferInConversation); CPPUNIT_TEST(testBadSha3sumOut); CPPUNIT_TEST(testBadSha3sumIn); CPPUNIT_TEST(testAskToMultipleParticipants); CPPUNIT_TEST(testCancelInTransfer); CPPUNIT_TEST(testTransferInfo); CPPUNIT_TEST(testRemoveHardLink); CPPUNIT_TEST(testTooLarge); CPPUNIT_TEST(testDeleteFile); CPPUNIT_TEST_SUITE_END(); }; CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(FileTransferTest, FileTransferTest::name()); bool FileTransferTest::compare(const std::string& fileA, const std::string& fileB) const { std::ifstream f1(fileA, std::ifstream::binary | std::ifstream::ate); std::ifstream f2(fileB, std::ifstream::binary | std::ifstream::ate); if (f1.fail() || f2.fail() || f1.tellg() != f2.tellg()) { return false; } f1.seekg(0, std::ifstream::beg); f2.seekg(0, std::ifstream::beg); return std::equal(std::istreambuf_iterator<char>(f1.rdbuf()), std::istreambuf_iterator<char>(), std::istreambuf_iterator<char>(f2.rdbuf())); } void FileTransferTest::setUp() { auto actors = load_actors_and_wait_for_announcement("actors/alice-bob-carla.yml"); aliceId = actors["alice"]; bobId = actors["bob"]; carlaId = actors["carla"]; aliceData = {}; bobData = {}; carlaData = {}; } void FileTransferTest::tearDown() { std::filesystem::remove(sendPath); std::filesystem::remove(recvPath); std::filesystem::remove(recv2Path); wait_for_removal_of({aliceId, bobId, carlaId}); } void FileTransferTest::connectSignals() { std::map<std::string, std::shared_ptr<libjami::CallbackWrapperBase>> confHandlers; confHandlers.insert(libjami::exportable_callback<libjami::ConversationSignal::ConversationReady>( [&](const std::string& accountId, const std::string& conversationId) { if (accountId == aliceId) { aliceData.conversationId = conversationId; } else if (accountId == bobId) { bobData.conversationId = conversationId; } else if (accountId == carlaId) { carlaData.conversationId = conversationId; } cv.notify_one(); })); confHandlers.insert( libjami::exportable_callback<libjami::ConversationSignal::ConversationRequestReceived>( [&](const std::string& accountId, const std::string& /* conversationId */, std::map<std::string, std::string> /*metadatas*/) { if (accountId == aliceId) { aliceData.requestReceived = true; } else if (accountId == bobId) { bobData.requestReceived = true; } else if (accountId == carlaId) { carlaData.requestReceived = true; } cv.notify_one(); })); confHandlers.insert(libjami::exportable_callback<libjami::ConversationSignal::SwarmMessageReceived>( [&](const std::string& accountId, const std::string& /* conversationId */, libjami::SwarmMessage message) { std::unique_lock<std::mutex> lk {mtx}; if (accountId == aliceId) { aliceData.messages.emplace_back(message); } else if (accountId == bobId) { bobData.messages.emplace_back(message); } else if (accountId == carlaId) { carlaData.messages.emplace_back(message); } cv.notify_one(); })); confHandlers.insert(libjami::exportable_callback<libjami::ConversationSignal::SwarmMessageUpdated>( [&](const std::string& accountId, const std::string& /* conversationId */, libjami::SwarmMessage message) { if (accountId == aliceId) { aliceData.messagesUpdated.emplace_back(message); } else if (accountId == bobId) { bobData.messagesUpdated.emplace_back(message); } else if (accountId == carlaId) { carlaData.messagesUpdated.emplace_back(message); } cv.notify_one(); })); confHandlers.insert( libjami::exportable_callback<libjami::ConversationSignal::ConversationRemoved>( [&](const std::string& accountId, const std::string&) { if (accountId == aliceId) aliceData.removed = true; else if (accountId == bobId) bobData.removed = true; cv.notify_one(); })); confHandlers.insert(libjami::exportable_callback<libjami::DataTransferSignal::DataTransferEvent>( [&](const std::string& accountId, const std::string& conversationId, const std::string&, const std::string& fileId, int code) { if (conversationId.empty()) return; if (accountId == aliceId) aliceData.code = code; else if (accountId == bobId) bobData.code = code; else if (accountId == carlaId) carlaData.code = code; cv.notify_one(); })); libjami::registerSignalHandlers(confHandlers); } void FileTransferTest::testConversationFileTransfer() { auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto bobUri = bobAccount->getUsername(); auto carlaAccount = Manager::instance().getAccount<JamiAccount>(carlaId); auto carlaUri = carlaAccount->getUsername(); aliceAccount->trackBuddyPresence(carlaUri, true); // Enable carla Manager::instance().sendRegister(carlaId, true); wait_for_announcement_of(carlaId); connectSignals(); auto convId = libjami::startConversation(aliceId); libjami::addConversationMember(aliceId, convId, bobUri); libjami::addConversationMember(aliceId, convId, carlaUri); CPPUNIT_ASSERT(cv.wait_for(lk, 60s, [&]() { return bobData.requestReceived && carlaData.requestReceived; })); auto aliceMsgSize = aliceData.messages.size(); libjami::acceptConversationRequest(bobId, convId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return aliceMsgSize + 1 == aliceData.messages.size(); })); aliceMsgSize = aliceData.messages.size(); auto bobMsgSize = bobData.messages.size(); libjami::acceptConversationRequest(carlaId, convId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return aliceMsgSize + 1 == aliceData.messages.size() && bobMsgSize + 1 == bobData.messages.size(); })); // Send file std::ofstream sendFile(sendPath); CPPUNIT_ASSERT(sendFile.is_open()); sendFile << std::string(64000, 'A'); sendFile.close(); bobMsgSize = bobData.messages.size(); auto carlaMsgSize = carlaData.messages.size(); libjami::sendFile(aliceId, convId, sendPath, "SEND", ""); CPPUNIT_ASSERT(cv.wait_for(lk, 45s, [&]() { return bobData.messages.size() == bobMsgSize + 1 && carlaData.messages.size() == carlaMsgSize + 1; })); auto id = bobData.messages.rbegin()->id; auto fileId = bobData.messages.rbegin()->body["fileId"]; libjami::downloadFile(bobId, convId, id, fileId, recvPath); libjami::downloadFile(carlaId, convId, id, fileId, recv2Path); CPPUNIT_ASSERT(cv.wait_for(lk, 45s, [&]() { return carlaData.code == static_cast<int>(libjami::DataTransferEventCode::finished) && bobData.code == static_cast<int>(libjami::DataTransferEventCode::finished); })); } void FileTransferTest::testFileTransferInConversation() { auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto bobUri = bobAccount->getUsername(); auto aliceUri = aliceAccount->getUsername(); connectSignals(); auto convId = libjami::startConversation(aliceId); libjami::addConversationMember(aliceId, convId, bobUri); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.requestReceived; })); auto aliceMsgSize = aliceData.messages.size(); libjami::acceptConversationRequest(bobId, convId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return aliceMsgSize + 1 == aliceData.messages.size(); })); // Create file to send std::ofstream sendFile(sendPath); CPPUNIT_ASSERT(sendFile.is_open()); sendFile << std::string(64000, 'A'); sendFile.close(); auto bobMsgSize = bobData.messages.size(); libjami::sendFile(aliceId, convId, sendPath, "SEND", ""); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobMsgSize + 1== bobData.messages.size(); })); auto id = bobData.messages.rbegin()->id; auto fileId = bobData.messages.rbegin()->body["fileId"]; libjami::downloadFile(bobId, convId, id, fileId, recvPath); CPPUNIT_ASSERT(cv.wait_for(lk, 45s, [&]() { return aliceData.code == static_cast<int>(libjami::DataTransferEventCode::finished) && bobData.code == static_cast<int>(libjami::DataTransferEventCode::finished); })); } void FileTransferTest::testVcfFileTransferInConversation() { auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto bobUri = bobAccount->getUsername(); auto aliceUri = aliceAccount->getUsername(); connectSignals(); auto convId = libjami::startConversation(aliceId); libjami::addConversationMember(aliceId, convId, bobUri); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.requestReceived; })); auto aliceMsgSize = aliceData.messages.size(); libjami::acceptConversationRequest(bobId, convId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return aliceMsgSize + 1 == aliceData.messages.size(); })); // Create file to send std::ofstream sendFile(sendPath); CPPUNIT_ASSERT(sendFile.is_open()); sendFile << std::string(64000, 'A'); sendFile.close(); auto bobMsgSize = bobData.messages.size(); libjami::sendFile(aliceId, convId, sendPath, "SEND", ""); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobMsgSize + 1 == bobData.messages.size(); })); auto id = bobData.messages.rbegin()->id; auto fileId = bobData.messages.rbegin()->body["fileId"]; libjami::downloadFile(bobId, convId, id, fileId, recvPath); CPPUNIT_ASSERT(cv.wait_for(lk, 45s, [&]() { return aliceData.code == static_cast<int>(libjami::DataTransferEventCode::finished) && bobData.code == static_cast<int>(libjami::DataTransferEventCode::finished); })); } void FileTransferTest::testBadSha3sumOut() { auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto bobUri = bobAccount->getUsername(); auto aliceUri = aliceAccount->getUsername(); connectSignals(); auto convId = libjami::startConversation(aliceId); libjami::addConversationMember(aliceId, convId, bobUri); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.requestReceived; })); auto aliceMsgSize = aliceData.messages.size(); libjami::acceptConversationRequest(bobId, convId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return aliceMsgSize + 1 == aliceData.messages.size(); })); // Create file to send std::ofstream sendFile(sendPath); CPPUNIT_ASSERT(sendFile.is_open()); sendFile << std::string(64000, 'A'); sendFile.close(); auto bobMsgSize = bobData.messages.size(); libjami::sendFile(aliceId, convId, sendPath, "SEND", ""); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobMsgSize + 1 == bobData.messages.size(); })); // modifiy file sendFile = std::ofstream(sendPath, std::ios::trunc); CPPUNIT_ASSERT(sendFile.is_open()); sendFile << std::string(64000, 'B'); sendFile.close(); auto id = bobData.messages.rbegin()->id; auto fileId = bobData.messages.rbegin()->body["fileId"]; libjami::downloadFile(bobId, convId, id, fileId, recvPath); CPPUNIT_ASSERT(!cv.wait_for(lk, 45s, [&]() { return aliceData.code == static_cast<int>(libjami::DataTransferEventCode::finished) || bobData.code == static_cast<int>(libjami::DataTransferEventCode::finished); })); } void FileTransferTest::testBadSha3sumIn() { auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto bobUri = bobAccount->getUsername(); auto aliceUri = aliceAccount->getUsername(); connectSignals(); auto convId = libjami::startConversation(aliceId); libjami::addConversationMember(aliceId, convId, bobUri); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.requestReceived; })); auto aliceMsgSize = aliceData.messages.size(); libjami::acceptConversationRequest(bobId, convId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return aliceMsgSize + 1 == aliceData.messages.size(); })); // Create file to send std::ofstream sendFile(sendPath); CPPUNIT_ASSERT(sendFile.is_open()); sendFile << std::string(64000, 'A'); sendFile.close(); aliceAccount->noSha3sumVerification(true); auto bobMsgSize = bobData.messages.size(); libjami::sendFile(aliceId, convId, sendPath, "SEND", ""); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobMsgSize + 1 == bobData.messages.size(); })); // modifiy file sendFile = std::ofstream(sendPath); CPPUNIT_ASSERT(sendFile.is_open()); // Avoid ASAN error on big alloc sendFile << std::string("B", 64000); sendFile << std::string(64000, 'B'); sendFile.close(); auto id = bobData.messages.rbegin()->id; auto fileId = bobData.messages.rbegin()->body["fileId"]; libjami::downloadFile(bobId, convId, id, fileId, recvPath); // The file transfer will be sent but refused by bob CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return aliceData.code == static_cast<int>(libjami::DataTransferEventCode::finished); })); CPPUNIT_ASSERT(!cv.wait_for(lk, 30s, [&]() { return bobData.code == static_cast<int>(libjami::DataTransferEventCode::finished); })); std::filesystem::remove(sendPath); } void FileTransferTest::testAskToMultipleParticipants() { auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto carlaAccount = Manager::instance().getAccount<JamiAccount>(carlaId); auto aliceUri = aliceAccount->getUsername(); auto bobUri = bobAccount->getUsername(); auto carlaUri = carlaAccount->getUsername(); connectSignals(); auto convId = libjami::startConversation(aliceId); libjami::addConversationMember(aliceId, convId, bobUri); libjami::addConversationMember(aliceId, convId, carlaUri); CPPUNIT_ASSERT(cv.wait_for(lk, 60s, [&]() { return bobData.requestReceived && carlaData.requestReceived; })); auto aliceMsgSize = aliceData.messages.size(); libjami::acceptConversationRequest(bobId, convId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return aliceMsgSize + 1 == aliceData.messages.size(); })); aliceMsgSize = aliceData.messages.size(); auto bobMsgSize = bobData.messages.size(); libjami::acceptConversationRequest(carlaId, convId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return aliceMsgSize + 1 == aliceData.messages.size() && bobMsgSize + 1 == bobData.messages.size(); })); // Create file to send std::ofstream sendFile(sendPath); CPPUNIT_ASSERT(sendFile.is_open()); sendFile << std::string(64000, 'A'); sendFile.close(); bobMsgSize = bobData.messages.size(); auto carlaMsgSize = carlaData.messages.size(); libjami::sendFile(aliceId, convId, sendPath, "SEND", ""); CPPUNIT_ASSERT(cv.wait_for(lk, 45s, [&]() { return bobData.messages.size() == bobMsgSize + 1 && carlaData.messages.size() == carlaMsgSize + 1; })); auto id = bobData.messages.rbegin()->id; auto fileId = bobData.messages.rbegin()->body["fileId"]; libjami::downloadFile(carlaId, convId, id, fileId, recv2Path); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return carlaData.code == static_cast<int>(libjami::DataTransferEventCode::finished); })); CPPUNIT_ASSERT(dhtnet::fileutils::isFile(recv2Path)); libjami::downloadFile(bobId, convId, id, fileId, recvPath); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.code == static_cast<int>(libjami::DataTransferEventCode::finished); })); CPPUNIT_ASSERT(dhtnet::fileutils::isFile(recvPath)); } void FileTransferTest::testCancelInTransfer() { auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto bobUri = bobAccount->getUsername(); auto aliceUri = aliceAccount->getUsername(); connectSignals(); auto convId = libjami::startConversation(aliceId); libjami::addConversationMember(aliceId, convId, bobUri); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.requestReceived; })); auto aliceMsgSize = aliceData.messages.size(); libjami::acceptConversationRequest(bobId, convId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return aliceMsgSize + 1 == aliceData.messages.size(); })); // Create file to send std::ofstream sendFile(sendPath); CPPUNIT_ASSERT(sendFile.is_open()); sendFile << std::string(640000, 'A'); sendFile.close(); auto bobMsgSize = bobData.messages.size(); libjami::sendFile(aliceId, convId, sendPath, "SEND", ""); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobMsgSize + 1 == bobData.messages.size(); })); auto id = bobData.messages.rbegin()->id; auto fileId = bobData.messages.rbegin()->body["fileId"]; libjami::downloadFile(bobId, convId, id, fileId, recvPath); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.code == static_cast<int>(libjami::DataTransferEventCode::ongoing); })); libjami::cancelDataTransfer(bobId, convId, fileId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.code == static_cast<int>(libjami::DataTransferEventCode::closed_by_peer); })); CPPUNIT_ASSERT(!dhtnet::fileutils::isFile(recvPath)); CPPUNIT_ASSERT(!bobAccount->dataTransfer(convId)->isWaiting(fileId)); } void FileTransferTest::testTransferInfo() { auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto bobUri = bobAccount->getUsername(); auto aliceUri = aliceAccount->getUsername(); connectSignals(); auto convId = libjami::startConversation(aliceId); libjami::addConversationMember(aliceId, convId, bobUri); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.requestReceived; })); auto aliceMsgSize = aliceData.messages.size(); libjami::acceptConversationRequest(bobId, convId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return aliceMsgSize + 1 == aliceData.messages.size(); })); // Create file to send std::ofstream sendFile(sendPath); CPPUNIT_ASSERT(sendFile.is_open()); sendFile << std::string(640000, 'A'); sendFile.close(); auto bobMsgSize = bobData.messages.size(); libjami::sendFile(aliceId, convId, sendPath, "SEND", ""); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobMsgSize + 1 == bobData.messages.size(); })); auto id = bobData.messages.rbegin()->id; auto fileId = bobData.messages.rbegin()->body["fileId"]; int64_t totalSize, bytesProgress; std::string path; CPPUNIT_ASSERT(libjami::fileTransferInfo(bobId, convId, fileId, path, totalSize, bytesProgress) == libjami::DataTransferError::invalid_argument); CPPUNIT_ASSERT(bytesProgress == 0); CPPUNIT_ASSERT(!std::filesystem::is_regular_file(path)); // No check for total as not started libjami::downloadFile(bobId, convId, id, fileId, recvPath); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.code == static_cast<int>(libjami::DataTransferEventCode::finished); })); CPPUNIT_ASSERT(libjami::fileTransferInfo(bobId, convId, fileId, path, totalSize, bytesProgress) == libjami::DataTransferError::success); CPPUNIT_ASSERT(bytesProgress == 640000); CPPUNIT_ASSERT(totalSize == 640000); CPPUNIT_ASSERT(dhtnet::fileutils::isFile(path)); } void FileTransferTest::testRemoveHardLink() { auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); connectSignals(); auto convId = libjami::startConversation(aliceId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return !aliceData.conversationId.empty(); })); // Send file std::ofstream sendFile(sendPath); CPPUNIT_ASSERT(sendFile.is_open()); sendFile << std::string(64000, 'A'); sendFile.close(); libjami::sendFile(aliceId, convId, sendPath, std::filesystem::absolute("SEND"), ""); auto aliceMsgSize = aliceData.messages.size(); CPPUNIT_ASSERT(cv.wait_for(lk, 45s, [&]() { return aliceMsgSize + 1 == aliceData.messages.size(); })); CPPUNIT_ASSERT(libjami::removeConversation(aliceId, convId)); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return aliceData.removed; })); auto content = fileutils::loadTextFile(sendPath); CPPUNIT_ASSERT(content.find("AAA") != std::string::npos); } void FileTransferTest::testTooLarge() { auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobId); auto bobUri = bobAccount->getUsername(); connectSignals(); auto convId = libjami::startConversation(aliceId); libjami::addConversationMember(aliceId, convId, bobUri); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.requestReceived; })); auto aliceMsgSize = aliceData.messages.size(); libjami::acceptConversationRequest(bobId, convId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return aliceMsgSize + 1 == aliceData.messages.size(); })); // Send file std::ofstream sendFile(sendPath); CPPUNIT_ASSERT(sendFile.is_open()); sendFile << std::string(64000, 'A'); sendFile.close(); auto bobMsgSize = bobData.messages.size(); libjami::sendFile(aliceId, convId, sendPath, "SEND", ""); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobMsgSize + 1 == bobData.messages.size(); })); auto id = bobData.messages.rbegin()->id; auto fileId = bobData.messages.rbegin()->body["fileId"]; // Add some data for the reception. This will break the final shasum std::ofstream recvFile(recvPath + std::string(".tmp")); CPPUNIT_ASSERT(recvFile.is_open()); recvFile << std::string(1000, 'B'); recvFile.close(); libjami::downloadFile(bobId, convId, id, fileId, recvPath); CPPUNIT_ASSERT(cv.wait_for(lk, 20s, [&]() { return bobData.code == static_cast<int>(libjami::DataTransferEventCode::closed_by_host); })); CPPUNIT_ASSERT(!dhtnet::fileutils::isFile(recvPath)); } void FileTransferTest::testDeleteFile() { auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceId); auto convId = libjami::startConversation(aliceId); std::map<std::string, std::shared_ptr<libjami::CallbackWrapperBase>> confHandlers; bool conversationReady = false; std::string iid, tid; confHandlers.insert(libjami::exportable_callback<libjami::ConversationSignal::SwarmMessageReceived>( [&](const std::string& accountId, const std::string& /* conversationId */, libjami::SwarmMessage message) { if (message.type == "application/data-transfer+json") { if (accountId == aliceId) { iid = message.id; tid = message.body["tid"]; } } cv.notify_one(); })); confHandlers.insert(libjami::exportable_callback<libjami::ConversationSignal::ConversationReady>( [&](const std::string& accountId, const std::string& /* conversationId */) { if (accountId == bobId) { conversationReady = true; cv.notify_one(); } })); bool messageUpdated = false; confHandlers.insert(libjami::exportable_callback<libjami::ConversationSignal::SwarmMessageUpdated>( [&](const std::string& accountId, const std::string& /* conversationId */, libjami::SwarmMessage message) { if (accountId == aliceId && message.type == "application/data-transfer+json" && message.body["tid"].empty()) { messageUpdated = true; } cv.notify_one(); })); libjami::registerSignalHandlers(confHandlers); // Create file to send std::ofstream sendFile(sendPath); CPPUNIT_ASSERT(sendFile.is_open()); sendFile << std::string(64000, 'A'); sendFile.close(); libjami::sendFile(aliceId, convId, sendPath, "SEND", ""); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return !iid.empty(); })); auto dataPath = fileutils::get_data_dir() / aliceId / "conversation_data" / convId; CPPUNIT_ASSERT(dhtnet::fileutils::isFile(dataPath / fmt::format("{}_{}", iid, tid))); // Delete file libjami::sendMessage(aliceId, convId, ""s, iid, 1); // Verify message is updated CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return messageUpdated; })); // Verify file is deleted CPPUNIT_ASSERT(!dhtnet::fileutils::isFile(dataPath / fmt::format("{}_{}", iid, tid))); libjami::unregisterSignalHandlers(); std::this_thread::sleep_for(5s); } } // namespace test } // namespace jami RING_TEST_RUNNER(jami::test::FileTransferTest::name())
29,068
C++
.cpp
604
42.019868
216
0.680669
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,687
routing_table.cpp
savoirfairelinux_jami-daemon/test/unitTest/swarm/routing_table.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <cppunit/TestAssert.h> #include <cppunit/TestFixture.h> #include <cppunit/extensions/HelperMacros.h> #include "../../test_runner.h" #include "jami.h" #include "../common.h" #include "jamidht/swarm/swarm_manager.h" #include <algorithm> #include <dhtnet/multiplexed_socket.h> #include "nodes.h" #include <opendht/thread_pool.h> using namespace std::string_literals; using namespace std::chrono_literals; using namespace dht; using NodeId = dht::PkId; namespace jami { namespace test { constexpr size_t nNodes = 6; constexpr size_t mNodes = 3; constexpr size_t kNodes = 4; constexpr size_t BOOTSTRAP_SIZE = 2; constexpr int time = 10; struct Counter { Counter(unsigned t) : target(t) {} const unsigned target; unsigned added {0}; std::mutex mutex; std::condition_variable cv; void count() { std::lock_guard lock(mutex); ++added; if (added == target) cv.notify_one(); } bool wait(std::chrono::steady_clock::duration timeout) { std::unique_lock lock(mutex); return cv.wait_for(lock, timeout, [&] { return added == target; }); } void wait() { std::unique_lock lock(mutex); return cv.wait(lock, [&] { return added == target; }); } }; class RoutingTableTest : public CppUnit::TestFixture { public: ~RoutingTableTest() { libjami::fini(); } static std::string name() { return "RoutingTable"; } void setUp(); void tearDown(); private: // ################# METHODS AND VARIABLES GENERATING DATA #################// std::mt19937_64 rd {dht::crypto::getSeededRandomEngine<std::mt19937_64>()}; std::mutex channelSocketsMtx_; std::vector<NodeId> randomNodeIds; std::map<NodeId, std::map<NodeId, std::shared_ptr<dhtnet::ChannelSocketTest>>> channelSockets_; std::map<NodeId, std::shared_ptr<jami::SwarmManager>> swarmManagers; std::map<NodeId, std::set<NodeId>> nodesToConnect; std::set<NodeId> messageNode; void generaterandomNodeIds(); void generateSwarmManagers(); std::shared_ptr<jami::SwarmManager> getManager(const NodeId& id) { auto it = swarmManagers.find(id); return it == swarmManagers.end() ? nullptr : it->second; } void setKnownNodesToManager(const std::shared_ptr<SwarmManager>& sm); void needSocketCallBack(const std::shared_ptr<SwarmManager>& sm); // ################# METHODS AND VARIABLES TO TEST DATA #################// std::map<std::shared_ptr<jami::SwarmManager>, std::vector<NodeId>> knownNodesSwarmManager; std::map<NodeId, std::shared_ptr<jami::SwarmManager>> swarmManagersTest_; std::vector<NodeId> discoveredNodes; void crossNodes(NodeId nodeId); void distribution(); // ################# UNIT TEST METHODES #################// void testBucketMainFunctions(); void testRoutingTableMainFunctions(); void testBucketKnownNodes(); void testSwarmManagerConnectingNodes_1b(); void testClosestNodes_1b(); void testClosestNodes_multipleb(); void testSendKnownNodes_1b(); void testSendKnownNodes_multipleb(); void testMobileNodeFunctions(); void testMobileNodeAnnouncement(); void testMobileNodeSplit(); void testSendMobileNodes(); void testBucketSplit_1n(); void testSwarmManagersSmallBootstrapList(); void testRoutingTableForConnectingNode(); void testRoutingTableForShuttingNode(); void testRoutingTableForMassShuttingsNodes(); void testSwarmManagersWMobileModes(); CPPUNIT_TEST_SUITE(RoutingTableTest); CPPUNIT_TEST(testBucketMainFunctions); CPPUNIT_TEST(testRoutingTableMainFunctions); CPPUNIT_TEST(testClosestNodes_multipleb); CPPUNIT_TEST(testBucketSplit_1n); CPPUNIT_TEST(testBucketKnownNodes); CPPUNIT_TEST(testSendKnownNodes_1b); CPPUNIT_TEST(testSendKnownNodes_multipleb); CPPUNIT_TEST(testClosestNodes_1b); CPPUNIT_TEST(testSwarmManagersSmallBootstrapList); CPPUNIT_TEST(testSwarmManagerConnectingNodes_1b); CPPUNIT_TEST(testRoutingTableForConnectingNode); CPPUNIT_TEST(testMobileNodeFunctions); CPPUNIT_TEST(testMobileNodeAnnouncement); CPPUNIT_TEST(testMobileNodeSplit); CPPUNIT_TEST(testSendMobileNodes); CPPUNIT_TEST(testSwarmManagersWMobileModes); CPPUNIT_TEST(testRoutingTableForMassShuttingsNodes); CPPUNIT_TEST(testRoutingTableForShuttingNode); CPPUNIT_TEST_SUITE_END(); }; CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(RoutingTableTest, RoutingTableTest::name()); void RoutingTableTest::setUp() { libjami::init( libjami::InitFlag(libjami::LIBJAMI_FLAG_DEBUG | libjami::LIBJAMI_FLAG_CONSOLE_LOG)); if (not Manager::instance().initialized) { CPPUNIT_ASSERT(libjami::start("jami-sample.yml")); } generaterandomNodeIds(); generateSwarmManagers(); } void RoutingTableTest::tearDown() { discoveredNodes.clear(); swarmManagersTest_.clear(); } void RoutingTableTest::generaterandomNodeIds() { auto total = nNodes + mNodes; randomNodeIds.reserve(total); for (size_t i = 0; i < total; i++) { NodeId node = Hash<32>::getRandom(); randomNodeIds.emplace_back(node); } } void RoutingTableTest::generateSwarmManagers() { auto total = nNodes + mNodes; for (size_t i = 0; i < total; i++) { const NodeId& node = randomNodeIds.at(i); auto sm = std::make_shared<SwarmManager>(node, rd, std::move([](auto) {return false;})); i >= nNodes ? sm->setMobility(true) : sm->setMobility(false); swarmManagers[node] = sm; } } void RoutingTableTest::setKnownNodesToManager(const std::shared_ptr<SwarmManager>& sm) { std::uniform_int_distribution<> distrib(1, kNodes - 1); int numberKnownNodesToAdd = distrib(rd); std::uniform_int_distribution<> distribBis(0, kNodes - 1); int indexNodeIdToAdd; std::vector<NodeId> kNodesToAdd; knownNodesSwarmManager.insert({sm, {}}); int counter = 0; while (counter < numberKnownNodesToAdd) { indexNodeIdToAdd = distribBis(rd); NodeId node = randomNodeIds.at(indexNodeIdToAdd); auto it = find(kNodesToAdd.begin(), kNodesToAdd.end(), node); if (sm->getId() != node && it == kNodesToAdd.end()) { kNodesToAdd.push_back(node); knownNodesSwarmManager.at(sm).push_back(node); counter++; } } sm->setKnownNodes(kNodesToAdd); } void RoutingTableTest::needSocketCallBack(const std::shared_ptr<SwarmManager>& sm) { sm->needSocketCb_ = [this, wsm = std::weak_ptr<SwarmManager>(sm)](const std::string& nodeId, auto&& onSocket) { Manager::instance().ioContext()->post([this, wsm, nodeId, onSocket = std::move(onSocket)] { auto sm = wsm.lock(); if (!sm || sm->isShutdown()) return; NodeId node = dhtnet::DeviceId(nodeId); std::lock_guard lk(channelSocketsMtx_); if (auto smRemote = getManager(node)) { if (sm->isShutdown()) { std::cout << "SWARMMANAGER " << sm->getId() << " IS SHUTDOWN" << std::endl; return; } auto myId = sm->getId(); auto& cstRemote = channelSockets_[node][myId]; auto& cstMe = channelSockets_[myId][node]; if (!cstRemote) { cstRemote = std::make_shared<dhtnet::ChannelSocketTest>(Manager::instance().ioContext(), myId, "test1", 0); } if (!cstMe) { cstMe = std::make_shared<dhtnet::ChannelSocketTest>(Manager::instance().ioContext(), node, "test1", 0); } dhtnet::ChannelSocketTest::link(cstMe, cstRemote); onSocket(cstMe); smRemote->addChannel(cstRemote); } }); }; } void RoutingTableTest::distribution() { std::vector<unsigned> dist(8); for (const auto& sm : swarmManagers) { auto val = sm.second->getRoutingTable().getRoutingTableNodeCount(); if (dist.size() <= val) dist.resize(val + 1); dist[val]++; } for (size_t i = 0; i < dist.size(); i++) { std::cout << "Swarm Managers with " << i << " nodes: " << dist[i] << std::endl; } } void RoutingTableTest::testBucketMainFunctions() { std::cout << "\nRunning test: " << __func__ << std::endl; NodeId node0 = nodeTestIds1.at(0); NodeId node1 = nodeTestIds1.at(1); NodeId node2 = nodeTestIds1.at(2); NodeId node3 = nodeTestIds1.at(3); auto sNode1 = nodeTestChannels1.at(1); auto sNode2 = nodeTestChannels1.at(2); auto sNode3 = nodeTestChannels1.at(3); NodeInfo InfoNode1(true, sNode2); std::set<std::shared_ptr<dhtnet::ChannelSocketInterface>> socketsCheck {sNode1, sNode2}; std::set<NodeId> nodesCheck {node1, node2}; Bucket bucket(node0); CPPUNIT_ASSERT_EQUAL_MESSAGE("Lower limit error", node0, bucket.getLowerLimit()); bucket.addNode(sNode1); bucket.addNode(std::move(InfoNode1)); //bucket.printBucket(0); CPPUNIT_ASSERT_EQUAL_MESSAGE("Supposed to have node", true, bucket.hasNode(sNode1->deviceId())); CPPUNIT_ASSERT_EQUAL_MESSAGE("Supposed to have node", true, bucket.hasNode(sNode2->deviceId())); CPPUNIT_ASSERT_EQUAL_MESSAGE("Supposed to have nodes", true, socketsCheck == bucket.getNodeSockets()); CPPUNIT_ASSERT_EQUAL_MESSAGE("Supposed to have nodes", true, nodesCheck == bucket.getNodeIds()); CPPUNIT_ASSERT_EQUAL_MESSAGE("Supposed to have nodes", true, bucket.isFull()); CPPUNIT_ASSERT_EQUAL_MESSAGE("Not supposed to have known node", false, bucket.hasKnownNode(node1)); CPPUNIT_ASSERT_EQUAL_MESSAGE("Not supposed to have known node", false, bucket.hasKnownNode(node2)); CPPUNIT_ASSERT_EQUAL_MESSAGE("Not supposed to have connecting node", false, bucket.hasConnectingNode(node1)); CPPUNIT_ASSERT_EQUAL_MESSAGE("Not supposed to have connecting node", false, bucket.hasConnectingNode(node2)); CPPUNIT_ASSERT_THROW_MESSAGE("Supposed to be out of range", bucket.getKnownNode(5), std::out_of_range); bucket.removeNode(sNode1->deviceId()); bucket.shutdownNode(sNode2->deviceId()); CPPUNIT_ASSERT_EQUAL_MESSAGE("Not supposed to have node", false, bucket.hasNode(node1)); CPPUNIT_ASSERT_EQUAL_MESSAGE("Not supposed to have node", false, bucket.hasNode(node2)); CPPUNIT_ASSERT_EQUAL_MESSAGE("Supposed to have known node", true, bucket.hasKnownNode(node1)); CPPUNIT_ASSERT_EQUAL_MESSAGE("Supposed to have known node", false, bucket.hasKnownNode(node2)); CPPUNIT_ASSERT_EQUAL_MESSAGE("Supposed to have known node", false, bucket.hasMobileNode(node1)); CPPUNIT_ASSERT_EQUAL_MESSAGE("Supposed to have known node", true, bucket.hasMobileNode(node2)); CPPUNIT_ASSERT_EQUAL_MESSAGE("Not supposed to have connecting node", false, bucket.hasConnectingNode(node1)); CPPUNIT_ASSERT_EQUAL_MESSAGE("Not supposed to have connecting node", false, bucket.hasConnectingNode(node2)); auto nodeTest = bucket.randomId(rd); CPPUNIT_ASSERT_EQUAL_MESSAGE("One of the two nodes", true, nodeTest == node1 || nodeTest == node2); bucket.addNode(sNode1); bucket.addNode(sNode2); CPPUNIT_ASSERT_EQUAL_MESSAGE("Supposed to be 2", 2u, bucket.getNodesSize()); CPPUNIT_ASSERT_EQUAL_MESSAGE("Supposed to return zero, node already added", false, bucket.addNode(sNode2)); bucket.removeNode(node1); bucket.removeNode(node2); CPPUNIT_ASSERT_EQUAL_MESSAGE("Not supposed to have node", false, bucket.hasNode(node1)); CPPUNIT_ASSERT_EQUAL_MESSAGE("Not supposed to have node", false, bucket.hasNode(node2)); bucket.addKnownNode(node3); CPPUNIT_ASSERT_EQUAL_MESSAGE("Supposed to have known node", true, bucket.hasKnownNode(node3)); CPPUNIT_ASSERT_EQUAL_MESSAGE("Not supposed to have connecting node", false, bucket.hasConnectingNode(node3)); CPPUNIT_ASSERT_EQUAL_MESSAGE("Supposed to be 3", 3u, bucket.getKnownNodesSize()); bucket.removeKnownNode(node3); CPPUNIT_ASSERT_EQUAL_MESSAGE("Not supposed to have known node", false, bucket.hasKnownNode(node3)); CPPUNIT_ASSERT_EQUAL_MESSAGE("Not supposed to have connecting node", false, bucket.hasConnectingNode(node3)); bucket.addConnectingNode(node1); bucket.addConnectingNode(node2); CPPUNIT_ASSERT_EQUAL_MESSAGE("Supposed to have connecting node", true, bucket.hasConnectingNode(node1)); CPPUNIT_ASSERT_EQUAL_MESSAGE("Supposed to have nodes", true, nodesCheck == bucket.getConnectingNodes()); CPPUNIT_ASSERT_EQUAL_MESSAGE("Supposed to be 2", 2u, bucket.getConnectingNodesSize()); bucket.removeConnectingNode(node2); CPPUNIT_ASSERT_EQUAL_MESSAGE("Not upposed to have connecting node", false, bucket.hasConnectingNode(node2)); CPPUNIT_ASSERT_EQUAL_MESSAGE("Supposed to be 1", 1u, bucket.getConnectingNodesSize()); } void RoutingTableTest::testBucketKnownNodes() { std::cout << "\nRunning test: " << __func__ << std::endl; Bucket bucket(randomNodeIds.at(0)); for (size_t i = 0; i < randomNodeIds.size(); i++) { bucket.addKnownNode(randomNodeIds.at(i)); } CPPUNIT_ASSERT_EQUAL_MESSAGE("Supposed to have the known node", true, bucket.hasKnownNode(randomNodeIds.at(randomNodeIds.size() - 1))); CPPUNIT_ASSERT_EQUAL_MESSAGE("Error with bucket size", true, bucket.getKnownNodesSize() == randomNodeIds.size()); } void RoutingTableTest::testRoutingTableMainFunctions() { std::cout << "\nRunning test: " << __func__ << std::endl; RoutingTable rt; NodeId node1 = nodeTestIds1.at(0); NodeId node2 = nodeTestIds1.at(1); NodeId node3 = nodeTestIds1.at(2); rt.setId(node1); rt.addKnownNode(node1); rt.addKnownNode(node2); rt.addKnownNode(node3); CPPUNIT_ASSERT(!rt.hasKnownNode(node1)); CPPUNIT_ASSERT(rt.hasKnownNode(node2)); auto knownNodes = rt.getKnownNodes(); CPPUNIT_ASSERT_EQUAL_MESSAGE("Supposed to have 2 nodes", true, knownNodes.size() == 2); auto bucket1 = rt.findBucket(node1); auto bucket2 = rt.findBucket(node2); auto bucket3 = rt.findBucket(node3); rt.addNode(nodeTestChannels1.at(0), bucket1); rt.addNode(nodeTestChannels1.at(1), bucket2); rt.addNode(nodeTestChannels1.at(2), bucket3); CPPUNIT_ASSERT(!rt.hasNode(node1)); CPPUNIT_ASSERT(rt.hasNode(node2)); CPPUNIT_ASSERT(rt.hasNode(node3)); CPPUNIT_ASSERT_EQUAL_MESSAGE("Not supposed to exist 0", false, rt.removeNode(node1)); CPPUNIT_ASSERT_EQUAL_MESSAGE("Not supposed to exist 1", true, rt.removeNode(node2)); rt.removeNode(node1); rt.removeNode(node2); rt.removeNode(node3); rt.addConnectingNode(node1); rt.addConnectingNode(node2); rt.addConnectingNode(node3); std::vector<NodeId> nodesCheck({node2, node3}); const auto& nodes = rt.getConnectingNodes(); std::vector<NodeId> connectingNode; connectingNode.insert(connectingNode.end(), nodes.begin(), nodes.end()); CPPUNIT_ASSERT_EQUAL_MESSAGE("Not supposed to exist 3", false, rt.hasNode(node3)); CPPUNIT_ASSERT_EQUAL_MESSAGE("Not supposed to exist 1", false, rt.hasConnectingNode(node1)); CPPUNIT_ASSERT_EQUAL_MESSAGE("Not supposed to exist 3", true, rt.hasConnectingNode(node3)); std::vector<NodeId> diff; std::set_difference(connectingNode.begin(), connectingNode.end(), nodes.begin(), nodes.end(), std::inserter(diff, diff.begin())); CPPUNIT_ASSERT_EQUAL_MESSAGE("Supposed to be equal", true, diff.size() == 0); rt.shutdownNode(node2); rt.shutdownNode(node3); CPPUNIT_ASSERT_EQUAL_MESSAGE("Not supposed to exist", true, rt.hasConnectingNode(node2)); CPPUNIT_ASSERT_EQUAL_MESSAGE("Not supposed to exist", true, rt.hasConnectingNode(node3)); } void RoutingTableTest::testSwarmManagerConnectingNodes_1b() { std::cout << "\nRunning test: " << __func__ << std::endl; std::vector<NodeId> tryConnect; std::vector<std::string> needSocketNodes; std::condition_variable cv; std::mutex mutex; auto sm1 = std::make_shared<SwarmManager>(nodeTestIds1.at(0), rd, std::move([&](auto n) { std::lock_guard<std::mutex> lk(mutex); tryConnect.emplace_back(n); cv.notify_one(); return false; })); sm1->needSocketCb_ = [&](const auto& n, auto) { std::lock_guard<std::mutex> lk(mutex); needSocketNodes.emplace_back(n); cv.notify_one(); }; auto& rt1 = sm1->getRoutingTable(); std::vector<NodeId> toTest( {NodeId("053927d831827a9f7e606d4c9c9fe833922c0d35b3960dd2250085f46c0e4f41"), NodeId("41a05179e4b3e42c3409b10280bb448d5bbd5ef64784b997d2d1663457bb6ba8")}); std::unique_lock lk(mutex); sm1->setKnownNodes(toTest); CPPUNIT_ASSERT(cv.wait_for(lk, 10s, [&](){return tryConnect.size() != 0 && needSocketNodes.size() != 0;})); CPPUNIT_ASSERT(!rt1.hasConnectingNode(nodeTestIds1.at(0))); CPPUNIT_ASSERT(rt1.hasConnectingNode(nodeTestIds1.at(1))); CPPUNIT_ASSERT(!rt1.hasKnownNode(nodeTestIds1.at(0))); CPPUNIT_ASSERT(!rt1.hasKnownNode(nodeTestIds1.at(1))); } void RoutingTableTest::testClosestNodes_1b() { std::cout << "\nRunning test: " << __func__ << std::endl; auto sm1 = std::make_shared<SwarmManager>(nodeTestIds1.at(0), rd, std::move([](auto) {return false;})); auto sm2 = std::make_shared<SwarmManager>(nodeTestIds2.at(0), rd, std::move([](auto) {return false;})); auto& rt1 = sm1->getRoutingTable(); auto& rt2 = sm2->getRoutingTable(); auto bucket1 = rt1.findBucket(nodeTestIds1.at(0)); auto bucket2 = rt2.findBucket(nodeTestIds2.at(0)); for (size_t i = 0; i < nodeTestIds2.size(); i++) { bucket1->addNode(nodeTestChannels1.at(i)); bucket2->addNode(nodeTestChannels2.at(i)); } std::vector<NodeId> closestNodes1 {NodeId("41a05179e4b3e42c3409b10280bb448d5bbd5ef64784b997d2d1663457bb6ba8"), NodeId("28f4c7e34eb4310b2e1ea3b139ee6993e6b021770ee98895a54cdd1e372bd78e"), NodeId("2dd1dd976c7dc234ca737c85e4ea48ad09423067a77405254424c4cdd845720d"), NodeId("33f280d8208f42ac34321e6e6871aecd100c2bfd4f1848482e7a7ed8ae895414") }; std::vector<NodeId> closestNodes2 {NodeId("053927d831827a9f7e606d4c9c9fe833922c0d35b3960dd2250085f46c0e4f41"), NodeId("4f76e769061f343b2caf9eea35632d28cde8d7a67e5e0f59857733cabc538997"), NodeId("41a05179e4b3e42c3409b10280bb448d5bbd5ef64784b997d2d1663457bb6ba8"), NodeId("77a9fba2c5a65812d9290c567897131b20a723e0ca2f65ef5c6b421585e4da2b") }; auto closestNodes1_ = rt1.closestNodes(nodeTestIds2.at(4), 4); auto closestNodes2_ = rt2.closestNodes(nodeTestIds1.at(4), 4); auto sameIdTest = rt2.closestNodes(nodeTestIds2.at(0), 1); CPPUNIT_ASSERT_EQUAL_MESSAGE("ERROR", true, closestNodes1 == closestNodes1_); CPPUNIT_ASSERT_EQUAL_MESSAGE("ERROR", true, closestNodes2 == closestNodes2_); CPPUNIT_ASSERT_EQUAL_MESSAGE("ERROR", false, nodeTestIds1.at(0) == sameIdTest.at(0)); } void RoutingTableTest::testClosestNodes_multipleb() { std::cout << "\nRunning test: " << __func__ << std::endl; auto sm1 = std::make_shared<SwarmManager>(nodeTestIds1.at(2), rd, std::move([](auto) {return false;})); auto sm2 = std::make_shared<SwarmManager>(nodeTestIds1.at(6), rd, std::move([](auto) {return false;})); for (size_t i = 0; i < nodeTestChannels1.size(); i++) { sm1->addChannel(nodeTestChannels1.at(i)); sm2->addChannel(nodeTestChannels1.at(i)); } std::vector<NodeId> closestNodes1 {NodeId("2dd1dd976c7dc234ca737c85e4ea48ad09423067a77405254424c4cdd845720d"), NodeId("30e177a56bd1a7969e1973ad8b210a556f6a2b15debc972661a8f555d52edbe2"), NodeId("312226d8fa653704758a681c8c21ec81cec914d0b8aa19e1142d3cf900e3f3b4")}; std::vector<NodeId> closestNodes2 {NodeId("30e177a56bd1a7969e1973ad8b210a556f6a2b15debc972661a8f555d52edbe2"), NodeId("312226d8fa653704758a681c8c21ec81cec914d0b8aa19e1142d3cf900e3f3b4"), NodeId("33f280d8208f42ac34321e6e6871aecd100c2bfd4f1848482e7a7ed8ae895414")}; auto closestNodes1_ = sm1->getRoutingTable().closestNodes(nodeTestIds1.at(5), 3); auto closestNodes2_ = sm2->getRoutingTable().closestNodes(nodeTestIds1.at(5), 3); CPPUNIT_ASSERT_EQUAL_MESSAGE("ERROR", true, closestNodes1 == closestNodes1_); CPPUNIT_ASSERT_EQUAL_MESSAGE("ERROR", true, closestNodes2 == closestNodes2_); } void RoutingTableTest::testBucketSplit_1n() { std::cout << "\nRunning test: " << __func__ << std::endl; SwarmManager sm1(nodeTestIds2.at(0), rd, std::move([](auto) {return false;})); SwarmManager sm2(nodeTestIds2.at(nodeTestIds2.size() - 1), rd, std::move([](auto) {return false;})); SwarmManager sm3(nodeTestIds2.at(nodeTestIds2.size() / 2), rd, std::move([](auto) {return false;})); auto& rt1 = sm1.getRoutingTable(); auto& rt2 = sm2.getRoutingTable(); auto& rt3 = sm3.getRoutingTable(); auto& b1 = rt1.getBuckets(); auto& b2 = rt2.getBuckets(); auto& b3 = rt3.getBuckets(); for (size_t i = 0; i < nodeTestIds2.size(); i++) { auto bucket1 = rt1.findBucket(nodeTestIds2.at(i)); auto bucket2 = rt2.findBucket(nodeTestIds2.at(i)); auto bucket3 = rt3.findBucket(nodeTestIds2.at(i)); rt1.addNode(nodeTestChannels2.at(i), bucket1); rt2.addNode(nodeTestChannels2.at(i), bucket2); rt3.addNode(nodeTestChannels2.at(i), bucket3); } // SM1 CPPUNIT_ASSERT_EQUAL_MESSAGE("Not supposed to have node ntc2 0", false, rt1.hasNode(nodeTestChannels2.at(0)->deviceId())); int sm1BucketCounter = 1; for (const auto& buckIt : b1) { switch (sm1BucketCounter) { case 1: CPPUNIT_ASSERT_EQUAL_MESSAGE("Size error", 0u, buckIt.getNodesSize()); break; case 2: { std::set<NodeId> nodesCheck {nodeTestIds2.at(1), nodeTestIds2.at(2), nodeTestIds2.at(3), nodeTestIds2.at(4), nodeTestIds2.at(8)}; CPPUNIT_ASSERT_EQUAL_MESSAGE("Not supposed to have known nodes", true, nodesCheck == buckIt.getNodeIds()); } break; case 3: { std::set<NodeId> nodesCheck {nodeTestIds2.at(5), nodeTestIds2.at(6), nodeTestIds2.at(7), nodeTestIds2.at(9)}; CPPUNIT_ASSERT_EQUAL_MESSAGE("Not supposed to have known nodes", true, nodesCheck == buckIt.getNodeIds()); } break; } sm1BucketCounter++; } CPPUNIT_ASSERT_EQUAL_MESSAGE("ERROR", 3, sm1BucketCounter - 1); // SM2 CPPUNIT_ASSERT_EQUAL_MESSAGE("Not supposed to have node ntc2 9", false, rt2.hasNode(nodeTestChannels2.at(9)->deviceId())); int sm2BucketCounter = 1; for (const auto& buckIt : b2) { switch (sm2BucketCounter) { case 1: { std::set<NodeId> nodesCheck {nodeTestIds2.at(0), nodeTestIds2.at(1), nodeTestIds2.at(2), nodeTestIds2.at(3), nodeTestIds2.at(4), nodeTestIds2.at(8)}; CPPUNIT_ASSERT_EQUAL_MESSAGE("Not supposed to have known nodes", true, nodesCheck == buckIt.getNodeIds()); } break; case 2: { std::set<NodeId> nodesCheck {nodeTestIds2.at(6), nodeTestIds2.at(7)}; CPPUNIT_ASSERT_EQUAL_MESSAGE("Not supposed to have known nodes", true, nodesCheck == buckIt.getNodeIds()); } break; case 3: CPPUNIT_ASSERT_EQUAL_MESSAGE("Supposed to have node ntc2 5", true, buckIt.hasNode(nodeTestChannels2.at(5)->deviceId())); break; } sm2BucketCounter++; } CPPUNIT_ASSERT_EQUAL_MESSAGE("ERROR", 3, sm2BucketCounter - 1); // SM3 CPPUNIT_ASSERT_EQUAL_MESSAGE("Not supposed to have node ntc2 5", false, rt3.hasNode(nodeTestChannels2.at(5)->deviceId())); int sm3BucketCounter = 1; for (const auto& buckIt : b3) { switch (sm3BucketCounter) { case 1: { std::set<NodeId> nodesCheck {nodeTestIds2.at(0), nodeTestIds2.at(1), nodeTestIds2.at(2), nodeTestIds2.at(3), nodeTestIds2.at(4), nodeTestIds2.at(8)}; CPPUNIT_ASSERT_EQUAL_MESSAGE("Not supposed to have known nodes", true, nodesCheck == buckIt.getNodeIds()); } break; case 2: { std::set<NodeId> nodesCheck {nodeTestIds2.at(6), nodeTestIds2.at(7)}; CPPUNIT_ASSERT_EQUAL_MESSAGE("Not supposed to have known nodes", true, nodesCheck == buckIt.getNodeIds()); } break; case 3: CPPUNIT_ASSERT_EQUAL_MESSAGE("Supposed to have node ntc2 9", true, buckIt.hasNode(nodeTestChannels2.at(9)->deviceId())); break; } sm3BucketCounter++; } CPPUNIT_ASSERT_EQUAL_MESSAGE("ERROR", 3, sm3BucketCounter - 1); } void RoutingTableTest::testSendKnownNodes_1b() { std::cout << "\nRunning test: " << __func__ << std::endl; auto sm1 = std::make_shared<SwarmManager>(nodeTestIds2.at(0), rd, std::move([](auto) {return false;})); auto sm2 = std::make_shared<SwarmManager>(nodeTestIds3.at(0), rd, std::move([](auto) {return false;})); swarmManagers.insert({sm1->getId(), sm1}); swarmManagers.insert({sm2->getId(), sm2}); auto& rt1 = sm1->getRoutingTable(); auto& rt2 = sm2->getRoutingTable(); auto bucket1 = rt1.findBucket(nodeTestIds2.at(0)); auto bucket2 = rt2.findBucket(nodeTestIds3.at(0)); for (size_t i = 0; i < nodeTestChannels3.size(); i++) { auto node = nodeTestChannels3.at(i)->deviceId(); if (node != sm1->getId() && node != sm2->getId()) { bucket2->addNode(nodeTestChannels3.at(i)); } } std::vector<NodeId> node2Co = { NodeId("41a05179e4b3e42c3409b10280bb448d5bbd5ef64784b997d2d1663457bb6ba8")}; needSocketCallBack(sm1); sm1->setKnownNodes(node2Co); auto start = std::chrono::steady_clock::now(); bool cn1 {false}, cn2 {false}; auto isGood = [&] { return (cn1 and cn2); }; do { std::this_thread::sleep_for(1s); cn1 = bucket1->hasConnectingNode(nodeTestIds3.at(2)); cn2 = bucket1->hasConnectingNode(nodeTestIds3.at(3)); if (isGood()) break; } while (std::chrono::steady_clock::now() - start < 10s); CPPUNIT_ASSERT(isGood()); } void RoutingTableTest::testSendKnownNodes_multipleb() { std::cout << "\nRunning test: " << __func__ << std::endl; auto sm1 = std::make_shared<SwarmManager>(nodeTestIds2.at(8), rd, std::move([](auto) {return false;})); auto sm2 = std::make_shared<SwarmManager>(nodeTestIds3.at(0), rd, std::move([](auto) {return false;})); swarmManagers.insert({sm1->getId(), sm1}); swarmManagers.insert({sm2->getId(), sm2}); auto& rt1 = sm1->getRoutingTable(); auto& rt2 = sm2->getRoutingTable(); for (size_t i = 0; i < nodeTestIds2.size(); i++) { if (i != 1 && i != 0) { auto bucket1 = rt1.findBucket(nodeTestIds2.at(i)); rt1.addNode(nodeTestChannels2.at(i), bucket1); } auto bucket2 = rt2.findBucket(nodeTestIds3.at(i)); rt2.addNode(nodeTestChannels3.at(i), bucket2); } std::vector<NodeId> node2Co = { NodeId("41a05179e4b3e42c3409b10280bb448d5bbd5ef64784b997d2d1663457bb6ba8")}; needSocketCallBack(sm1); sm1->setKnownNodes(node2Co); auto bucket1 = rt1.findBucket(nodeTestIds3.at(1)); auto bucket2 = rt1.findBucket(nodeTestIds3.at(3)); auto start = std::chrono::steady_clock::now(); bool cn1 {false}, cn2 {false}; auto isGood = [&] { return (cn1 or cn2); }; do { std::this_thread::sleep_for(1s); cn1 = bucket1->hasConnectingNode(nodeTestIds3.at(1)); cn2 = bucket2->hasConnectingNode(nodeTestIds3.at(3)); } while (not isGood() and std::chrono::steady_clock::now() - start < 10s); CPPUNIT_ASSERT(isGood()); } void RoutingTableTest::testMobileNodeFunctions() { std::cout << "\nRunning test: " << __func__ << std::endl; RoutingTable rt; NodeId node1 = nodeTestIds1.at(0); NodeId node2 = nodeTestIds1.at(1); NodeId node3 = nodeTestIds1.at(2); rt.setId(node1); rt.addMobileNode(node1); rt.addMobileNode(node2); rt.addMobileNode(node3); CPPUNIT_ASSERT(!rt.hasMobileNode(node1)); CPPUNIT_ASSERT(rt.hasMobileNode(node2)); CPPUNIT_ASSERT(rt.hasMobileNode(node3)); auto mobileNodes = rt.getMobileNodes(); CPPUNIT_ASSERT(mobileNodes.size() == 2); rt.removeMobileNode(node2); rt.removeMobileNode(node3); CPPUNIT_ASSERT(!rt.hasMobileNode(node2)); CPPUNIT_ASSERT(!rt.hasMobileNode(node3)); } void RoutingTableTest::testMobileNodeAnnouncement() { std::cout << "\nRunning test: " << __func__ << std::endl; auto sm1 = std::make_shared<SwarmManager>(nodeTestIds1.at(0), rd, std::move([](auto) {return false;})); auto sm2 = std::make_shared<SwarmManager>(nodeTestIds2.at(1), rd, std::move([](auto) {return false;})); swarmManagers.insert({sm1->getId(), sm1}); swarmManagers.insert({sm2->getId(), sm2}); sm2->setMobility(true); std::vector<NodeId> node2Co = { NodeId("41a05179e4b3e42c3409b10280bb448d5bbd5ef64784b997d2d1663457bb6ba8")}; needSocketCallBack(sm1); sm1->setKnownNodes(node2Co); sleep(1); auto& rt1 = sm1->getRoutingTable(); CPPUNIT_ASSERT_EQUAL_MESSAGE( "Supposed to have", true, rt1.hasNode(NodeId("41a05179e4b3e42c3409b10280bb448d5bbd5ef64784b997d2d1663457bb6ba8"))); sm2->shutdown(); sleep(5); auto mb1 = rt1.getMobileNodes(); std::vector<NodeId> node2Test = { NodeId("41a05179e4b3e42c3409b10280bb448d5bbd5ef64784b997d2d1663457bb6ba8")}; CPPUNIT_ASSERT_EQUAL_MESSAGE("Supposed to be identical", true, node2Test == mb1); } void RoutingTableTest::testMobileNodeSplit() { std::cout << "\nRunning test: " << __func__ << std::endl; SwarmManager sm1(nodeTestIds1.at(0), rd, std::move([](auto) {return false;})); auto& rt1 = sm1.getRoutingTable(); for (size_t i = 0; i < nodeTestIds1.size(); i++) { rt1.addNode(nodeTestChannels1.at(i)); } sm1.setMobileNodes(nodeTestIds2); auto& buckets = rt1.getBuckets(); unsigned counter = 1; for (auto& buckIt : buckets) { switch (counter) { case 1: CPPUNIT_ASSERT_EQUAL_MESSAGE("Not supposed to have", false, buckIt.hasMobileNode(nodeTestIds2.at(0))); break; case 4: { std::set<NodeId> nodesCheck {nodeTestIds2.at(2), nodeTestIds2.at(3), nodeTestIds2.at(4), nodeTestIds2.at(8)}; CPPUNIT_ASSERT_EQUAL_MESSAGE("Not supposed to have known nodes", true, nodesCheck == buckIt.getMobileNodes()); } break; case 5: { std::set<NodeId> nodesCheck {nodeTestIds2.at(5), nodeTestIds2.at(6), nodeTestIds2.at(7), nodeTestIds2.at(9)}; CPPUNIT_ASSERT_EQUAL_MESSAGE("Not supposed to have known nodes", true, nodesCheck == buckIt.getMobileNodes()); } break; } counter++; } } void RoutingTableTest::testSendMobileNodes() { std::cout << "\nRunning test: " << __func__ << std::endl; auto sm1 = std::make_shared<SwarmManager>(nodeTestIds2.at(8), rd, std::move([](auto) {return false;})); auto sm2 = std::make_shared<SwarmManager>(nodeTestIds3.at(0), rd, std::move([](auto) {return false;})); std::cout << sm1->getId() << std::endl; swarmManagers.insert({sm1->getId(), sm1}); swarmManagers.insert({sm2->getId(), sm2}); auto& rt1 = sm1->getRoutingTable(); auto& rt2 = sm2->getRoutingTable(); for (size_t i = 0; i < nodeTestIds2.size(); i++) { if (i != 1 && i != 0) { auto bucket1 = rt1.findBucket(nodeTestIds2.at(i)); rt1.addNode(nodeTestChannels2.at(i), bucket1); } auto bucket2 = rt2.findBucket(nodeTestIds3.at(i)); rt2.addNode(nodeTestChannels3.at(i), bucket2); } std::vector<NodeId> mobileNodes = {NodeId("4000000000000000000000000000000000000000000000000000000000000000"), NodeId("8000000000000000000000000000000000000000000000000000000000000000")}; sm2->setMobileNodes(mobileNodes); std::vector<NodeId> node2Co = { NodeId("41a05179e4b3e42c3409b10280bb448d5bbd5ef64784b997d2d1663457bb6ba8")}; needSocketCallBack(sm1); sm1->setKnownNodes(node2Co); sleep(4); auto bucket1 = rt1.findBucket(sm1->getId()); auto bucket2 = rt2.findBucket(sm2->getId()); CPPUNIT_ASSERT_EQUAL_MESSAGE("Supposed to have", true, bucket1->hasMobileNode(mobileNodes.at(0))); CPPUNIT_ASSERT_EQUAL_MESSAGE("Supposed to have", false, bucket1->hasMobileNode(mobileNodes.at(1))); CPPUNIT_ASSERT_EQUAL_MESSAGE("Supposed to have", false, rt1.hasMobileNode(mobileNodes.at(1))); CPPUNIT_ASSERT_EQUAL_MESSAGE("Supposed to have", true, bucket2->hasMobileNode(mobileNodes.at(0))); CPPUNIT_ASSERT_EQUAL_MESSAGE("Supposed to have", true, rt2.hasMobileNode(mobileNodes.at(1))); } void RoutingTableTest::crossNodes(NodeId nodeId) { std::list<NodeId> pendingNodes {nodeId}; discoveredNodes.clear(); for (const auto& curNode : pendingNodes) { if (std::find(discoveredNodes.begin(), discoveredNodes.end(), curNode) == discoveredNodes.end()) { if (discoveredNodes.emplace_back(curNode)) { if (auto sm = getManager(curNode)) for (auto const& node : sm->getRoutingTable().getNodes()) { pendingNodes.emplace_back(node); } } } } } void RoutingTableTest::testSwarmManagersSmallBootstrapList() { std::cout << "\nRunning test: " << __func__ << std::endl; for (const auto& sm : swarmManagers) { needSocketCallBack(sm.second); } Counter counter(swarmManagers.size()); for (const auto& sm : swarmManagers) { dht::ThreadPool::computation().run([&] { std::vector<NodeId> randIds(BOOTSTRAP_SIZE); std::uniform_int_distribution<size_t> distribution(0, randomNodeIds.size() - 1); std::generate(randIds.begin(), randIds.end(), [&] { return randomNodeIds[distribution(rd)]; }); sm.second->setKnownNodes(randIds); counter.count(); }); } counter.wait(); sleep(time * 2); crossNodes(swarmManagers.begin()->first); // distribution(); CPPUNIT_ASSERT_EQUAL(swarmManagers.size(), discoveredNodes.size()); } void RoutingTableTest::testRoutingTableForConnectingNode() { std::cout << "\nRunning test: " << __func__ << std::endl; for (const auto& sm : swarmManagers) { needSocketCallBack(sm.second); } Counter counter(swarmManagers.size()); for (const auto& sm : swarmManagers) { dht::ThreadPool::computation().run([&] { std::vector<NodeId> randIds(BOOTSTRAP_SIZE); std::uniform_int_distribution<size_t> distribution(0, randomNodeIds.size() - 1); std::generate(randIds.begin(), randIds.end(), [&] { return randomNodeIds[distribution(rd)]; }); sm.second->setKnownNodes(randIds); counter.count(); }); } counter.wait(); auto sm1 = std::make_shared<SwarmManager>(nodeTestIds3.at(0), rd, std::move([](auto) {return false;})); auto sm2 = std::make_shared<SwarmManager>(nodeTestIds3.at(1), rd, std::move([](auto) {return false;})); swarmManagers.insert({sm1->getId(), sm1}); swarmManagers.insert({sm2->getId(), sm2}); needSocketCallBack(sm1); needSocketCallBack(sm2); std::vector<NodeId> knownNodesSm1({randomNodeIds.at(2), randomNodeIds.at(3)}); std::vector<NodeId> knownNodesSm2({randomNodeIds.at(4), randomNodeIds.at(5)}); sm1->setKnownNodes(knownNodesSm1); sm2->setKnownNodes(knownNodesSm2); sleep(10); crossNodes(swarmManagers.begin()->first); CPPUNIT_ASSERT_EQUAL(swarmManagers.size(), discoveredNodes.size()); } void RoutingTableTest::testRoutingTableForShuttingNode() { std::cout << "\nRunning test: " << __func__ << std::endl; for (const auto& sm : swarmManagers) { needSocketCallBack(sm.second); } Counter counter(swarmManagers.size()); for (const auto& sm : swarmManagers) { dht::ThreadPool::computation().run([&] { std::vector<NodeId> randIds(BOOTSTRAP_SIZE); std::uniform_int_distribution<size_t> distribution(0, randomNodeIds.size() - 1); std::generate(randIds.begin(), randIds.end(), [&] { return randomNodeIds[distribution(rd)]; }); sm.second->setKnownNodes(randIds); counter.count(); }); } counter.wait(); auto sm1 = std::make_shared<SwarmManager>(nodeTestIds3.at(0), rd, std::move([](auto) {return false;})); auto sm1Id = sm1->getId(); swarmManagers.emplace(sm1->getId(), sm1); needSocketCallBack(sm1); std::vector<NodeId> knownNodesSm1({randomNodeIds.at(2), randomNodeIds.at(3)}); sm1->setKnownNodes(knownNodesSm1); sleep(10); crossNodes(swarmManagers.begin()->first); CPPUNIT_ASSERT_EQUAL(swarmManagers.size(), discoveredNodes.size()); for (const auto& sm : swarmManagers) { if (sm.first != nodeTestIds3.at(0)) { swarmManagersTest_.emplace(sm); } } auto it1 = swarmManagers.find(sm1Id); swarmManagers.erase(it1); auto it2 = channelSockets_.find(sm1Id); channelSockets_.erase(it2); sm1 = {}; sleep(5); for (const auto& sm : swarmManagersTest_) { auto& a = sm.second->getRoutingTable(); CPPUNIT_ASSERT(!a.hasNode(sm1Id)); } } void RoutingTableTest::testRoutingTableForMassShuttingsNodes() { std::cout << "\nRunning test: " << __func__ << std::endl; std::vector<NodeId> swarmToCompare; for (const auto& sm : swarmManagers) { needSocketCallBack(sm.second); swarmManagersTest_.emplace(sm); swarmToCompare.emplace_back(sm.first); } Counter counter(swarmManagers.size()); for (const auto& sm : swarmManagers) { dht::ThreadPool::computation().run([&] { std::vector<NodeId> randIds(BOOTSTRAP_SIZE); std::uniform_int_distribution<size_t> distribution(0, randomNodeIds.size() - 1); std::generate(randIds.begin(), randIds.end(), [&] { return randomNodeIds[distribution(rd)]; }); sm.second->setKnownNodes(randIds); counter.count(); }); } counter.wait(); sleep(time * 2); crossNodes(swarmManagers.begin()->first); CPPUNIT_ASSERT_EQUAL(swarmManagers.size(), discoveredNodes.size()); // ADDING NEW NODES TO NETWORK for (size_t i = 0; i < nodeTestIds1.size(); i++) { auto sm = std::make_shared<SwarmManager>(nodeTestIds1.at(i), rd, std::move([](auto) {return false;})); auto smId = sm->getId(); swarmManagers.emplace(smId, sm); needSocketCallBack(sm); std::vector<NodeId> knownNodesSm({randomNodeIds.at(2), randomNodeIds.at(3)}); sm->setKnownNodes(knownNodesSm); } sleep(time * 3); crossNodes(swarmManagers.begin()->first); CPPUNIT_ASSERT_EQUAL(swarmManagers.size(), discoveredNodes.size()); // SHUTTING DOWN ADDED NODES std::lock_guard lk(channelSocketsMtx_); for (auto& nodes : nodeTestIds1) { auto it = swarmManagers.find(nodes); if (it != swarmManagers.end()) { it->second->shutdown(); channelSockets_.erase(it->second->getId()); swarmManagers.erase(it); } } sleep(time * 2); crossNodes(swarmManagers.begin()->first); CPPUNIT_ASSERT_EQUAL(swarmManagers.size(), discoveredNodes.size()); for (const auto& sm : swarmManagersTest_) { for (size_t i = 0; i < nodeTestIds1.size(); i++) { auto& a = sm.second->getRoutingTable(); if (!a.hasNode(nodeTestIds1.at(i))) { CPPUNIT_ASSERT(true); } else { CPPUNIT_ASSERT(false); } } } } void RoutingTableTest::testSwarmManagersWMobileModes() { std::cout << "\nRunning test: " << __func__ << std::endl; for (const auto& sm : swarmManagers) { needSocketCallBack(sm.second); } Counter counter(swarmManagers.size()); for (const auto& sm : swarmManagers) { dht::ThreadPool::computation().run([&] { std::vector<NodeId> randIds(BOOTSTRAP_SIZE); std::uniform_int_distribution<size_t> distribution(0, randomNodeIds.size() - 1); std::generate(randIds.begin(), randIds.end(), [&] { return randomNodeIds[distribution(rd)]; }); sm.second->setKnownNodes(randIds); counter.count(); }); } counter.wait(); sleep(time); // distribution(); crossNodes(swarmManagers.begin()->first); sleep(2); CPPUNIT_ASSERT_EQUAL_MESSAGE("Supposed to be equal with mobile nodes", swarmManagers.size(), discoveredNodes.size()); // Shutting down Mobile Nodes { std::lock_guard lk(channelSocketsMtx_); for (auto it = swarmManagers.begin(); it != swarmManagers.end();) { if (it->second->isMobile()) { it->second->shutdown(); channelSockets_.erase(it->second->getId()); it = swarmManagers.erase(it); } else { ++it; } } } sleep(20); { if (!swarmManagers.empty()) { crossNodes(swarmManagers.begin()->first); // distribution(); } } sleep(10); CPPUNIT_ASSERT_EQUAL_MESSAGE("Supposed to be equal without mobile nodes", swarmManagers.size(), discoveredNodes.size()); } }; // namespace test } // namespace jami RING_TEST_RUNNER(jami::test::RoutingTableTest::name())
46,493
C++
.cpp
1,063
34.079022
127
0.613203
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,688
swarm_conversation.cpp
savoirfairelinux_jami-daemon/test/unitTest/swarm/swarm_conversation.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <cppunit/TestAssert.h> #include <cppunit/TestFixture.h> #include <cppunit/extensions/HelperMacros.h> #include <condition_variable> #include <filesystem> #include <string> #include "jami.h" #include "../common.h" #include "jamidht/swarm/swarm_manager.h" #include <dhtnet/multiplexed_socket.h> #include <opendht/thread_pool.h> #include "../../test_runner.h" #include "account_const.h" #include "conversation/conversationcommon.h" #include "manager.h" using namespace dht; using NodeId = dht::PkId; using namespace std::literals::chrono_literals; namespace jami { namespace test { struct ConvData { std::string id {}; bool requestReceived {false}; bool needsHost {false}; bool conferenceChanged {false}; bool conferenceRemoved {false}; std::string hostState {}; std::vector<std::map<std::string, std::string>> messages {}; }; class SwarmConversationTest : public CppUnit::TestFixture { public: ~SwarmConversationTest(); static std::string name() { return "SwarmConversationTest"; } void setUp(); std::map<std::string, ConvData> accountMap; std::vector<std::string> accountIds; std::mutex mtx; std::unique_lock<std::mutex> lk {mtx}; std::condition_variable cv; private: void connectSignals(); std::map<std::string, std::shared_ptr<libjami::CallbackWrapperBase>> confHandlers; void testSendMessage(); CPPUNIT_TEST_SUITE(SwarmConversationTest); CPPUNIT_TEST(testSendMessage); CPPUNIT_TEST_SUITE_END(); }; CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(SwarmConversationTest, SwarmConversationTest::name()); void SwarmConversationTest::setUp() { libjami::init( libjami::InitFlag(libjami::LIBJAMI_FLAG_DEBUG | libjami::LIBJAMI_FLAG_CONSOLE_LOG)); if (not Manager::instance().initialized) CPPUNIT_ASSERT(libjami::start("jami-sample.yml")); auto actors = load_actors("actors/account_list.yml"); for (const auto& act : actors) { auto id = act.second; accountIds.emplace_back(id); std::cout << act.second << std::endl; accountMap.insert({id, {}}); } wait_for_announcement_of(accountIds, 60s); } SwarmConversationTest::~SwarmConversationTest() { wait_for_removal_of(accountIds); libjami::fini(); } void SwarmConversationTest::connectSignals() { std::map<std::string, std::shared_ptr<libjami::CallbackWrapperBase>> confHandlers; confHandlers.insert(libjami::exportable_callback<libjami::ConversationSignal::ConversationReady>( [&](const std::string& accountId, const std::string& conversationId) { for (const auto& accId : accountIds) { if (accountId == accId) { accountMap[accId].id = conversationId; } } cv.notify_one(); })); confHandlers.insert(libjami::exportable_callback<libjami::ConversationSignal::MessageReceived>( [&](const std::string& accountId, const std::string& conversationId, std::map<std::string, std::string> message) { for (const auto& accId : accountIds) { if (accountId == accId && accountMap[accId].id == conversationId) { accountMap[accId].messages.emplace_back(message); } } cv.notify_one(); })); confHandlers.insert( libjami::exportable_callback<libjami::ConversationSignal::ConversationRequestReceived>( [&](const std::string& accountId, const std::string&, std::map<std::string, std::string>) { for (const auto& accId : accountIds) { if (accountId == accId) { accountMap[accId].requestReceived = true; } } cv.notify_one(); })); libjami::registerSignalHandlers(confHandlers); } void SwarmConversationTest::testSendMessage() { std::map<std::string, std::shared_ptr<JamiAccount>> jamiAccounts; for (const auto& accId : accountIds) { jamiAccounts.insert({accId, Manager::instance().getAccount<JamiAccount>(accId)}); std::cout << "created account for: " << accId << std::endl; } std::mutex mtx; std::unique_lock lk {mtx}; std::condition_variable cv; connectSignals(); auto aliceId = jamiAccounts.begin()->first; auto convId = libjami::startConversation(aliceId); std::cout << "started conversation: " << convId << std::endl; for (auto it = std::next(jamiAccounts.begin()); it != jamiAccounts.end(); ++it) { auto userUri = it->second->getUsername(); std::cout << "adding member: " << userUri << std::endl; libjami::addConversationMember(aliceId, convId, userUri); CPPUNIT_ASSERT_EQUAL_MESSAGE("ERROR", true, cv.wait_for(lk, 40s, [&]() { return accountMap[it->first].requestReceived == true; })); libjami::acceptConversationRequest(it->first, convId); std::this_thread::sleep_for(std::chrono::seconds(10)); } std::cout << "waiting for conversation ready" << std::endl; for (size_t i = 1; i < accountIds.size(); i++) { CPPUNIT_ASSERT( cv.wait_for(lk, 40s, [&]() { return accountMap[accountIds.at(i)].id == convId; })); } std::cout << "messages size " << accountMap[accountIds.at(0)].messages.size() << std::endl; CPPUNIT_ASSERT( cv.wait_for(lk, 70s, [&]() { return accountMap[accountIds.at(0)].messages.size() >= 2; })); libjami::sendMessage(aliceId, convId, "hi"s, ""); for (size_t i = 1; i < accountIds.size(); i++) { std::cout << "COUNTER: " << i << " messages size " << accountMap[accountIds.at(i)].messages.size() << std::endl; if (accountMap[accountIds.at(i)].messages.size() >= 105) { for (const auto& msg : accountMap[accountIds.at(i)].messages) { std::cout << "Message id: " << msg.at("id") << " type: " << msg.at("type") << std::endl; } } CPPUNIT_ASSERT(cv.wait_for(lk, 40s, [&]() { return accountMap[accountIds.at(i)].messages.size() >= 1; })); } libjami::unregisterSignalHandlers(); } } // namespace test } // namespace jami RING_TEST_RUNNER(jami::test::SwarmConversationTest::name())
7,087
C++
.cpp
177
33.497175
101
0.644438
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,689
bootstrap.cpp
savoirfairelinux_jami-daemon/test/unitTest/swarm/bootstrap.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <cppunit/TestAssert.h> #include <cppunit/TestFixture.h> #include <cppunit/extensions/HelperMacros.h> #include <condition_variable> #include <msgpack.hpp> #include <filesystem> #include "../../test_runner.h" #include "account_const.h" #include "common.h" #include "conversation_interface.h" #include "fileutils.h" #include "jami.h" #include "jamidht/conversation.h" #include "jamidht/jamiaccount.h" #include "jamidht/swarm/swarm_channel_handler.h" #include "manager.h" using namespace std::string_literals; using namespace std::literals::chrono_literals; using namespace libjami::Account; namespace jami { struct ConvInfoTest { std::string accountId; std::string convId; bool requestReceived = false; bool conversationReady = false; std::vector<std::map<std::string, std::string>> messages; Conversation::BootstrapStatus bootstrap {Conversation::BootstrapStatus::FAILED}; }; namespace test { class BootstrapTest : public CppUnit::TestFixture { public: ~BootstrapTest() { libjami::fini(); } static std::string name() { return "Bootstrap"; } void setUp(); void tearDown(); ConvInfoTest aliceData; ConvInfoTest bobData; ConvInfoTest bob2Data; ConvInfoTest carlaData; std::mutex mtx; std::condition_variable cv; private: void connectSignals(); void testBootstrapOk(); void testBootstrapFailed(); void testBootstrapNeverNewDevice(); void testBootstrapCompat(); CPPUNIT_TEST_SUITE(BootstrapTest); CPPUNIT_TEST(testBootstrapOk); CPPUNIT_TEST(testBootstrapFailed); CPPUNIT_TEST(testBootstrapNeverNewDevice); CPPUNIT_TEST(testBootstrapCompat); CPPUNIT_TEST_SUITE_END(); }; CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(BootstrapTest, BootstrapTest::name()); void BootstrapTest::setUp() { aliceData = {}; bobData = {}; bob2Data = {}; carlaData = {}; // Init daemon libjami::init( libjami::InitFlag(libjami::LIBJAMI_FLAG_DEBUG | libjami::LIBJAMI_FLAG_CONSOLE_LOG)); if (not Manager::instance().initialized) CPPUNIT_ASSERT(libjami::start("jami-sample.yml")); auto actors = load_actors("actors/alice-bob-carla.yml"); aliceData.accountId = actors["alice"]; bobData.accountId = actors["bob"]; carlaData.accountId = actors["carla"]; Manager::instance().sendRegister(carlaData.accountId, false); wait_for_announcement_of({aliceData.accountId, bobData.accountId}); connectSignals(); } void BootstrapTest::tearDown() { libjami::unregisterSignalHandlers(); auto bobArchive = std::filesystem::current_path().string() + "/bob.gz"; std::remove(bobArchive.c_str()); if (bob2Data.accountId.empty()) { wait_for_removal_of({aliceData.accountId, bobData.accountId, carlaData.accountId}); } else { wait_for_removal_of( {aliceData.accountId, bobData.accountId, carlaData.accountId, bob2Data.accountId}); } } void BootstrapTest::connectSignals() { std::map<std::string, std::shared_ptr<libjami::CallbackWrapperBase>> confHandlers; confHandlers.insert(libjami::exportable_callback<libjami::ConversationSignal::ConversationReady>( [&](const std::string& accountId, const std::string& convId) { if (accountId == aliceData.accountId) { aliceData.convId = convId; aliceData.conversationReady = true; } else if (accountId == bobData.accountId) { bobData.convId = convId; bobData.conversationReady = true; } else if (accountId == bob2Data.accountId) { bob2Data.convId = convId; bob2Data.conversationReady = true; } else if (accountId == carlaData.accountId) { carlaData.convId = convId; carlaData.conversationReady = true; } cv.notify_one(); })); confHandlers.insert( libjami::exportable_callback<libjami::ConversationSignal::ConversationRequestReceived>( [&](const std::string& accountId, const std::string& /* conversationId */, std::map<std::string, std::string> /*metadatas*/) { if (accountId == aliceData.accountId) { aliceData.requestReceived = true; } else if (accountId == bobData.accountId) { bobData.requestReceived = true; } else if (accountId == bob2Data.accountId) { bob2Data.requestReceived = true; } else if (accountId == carlaData.accountId) { carlaData.requestReceived = true; } cv.notify_one(); })); confHandlers.insert(libjami::exportable_callback<libjami::ConversationSignal::MessageReceived>( [&](const std::string& accountId, const std::string& /*conversationId*/, std::map<std::string, std::string> message) { if (accountId == aliceData.accountId) { aliceData.messages.emplace_back(message); } else if (accountId == bobData.accountId) { bobData.messages.emplace_back(message); } else if (accountId == bob2Data.accountId) { bob2Data.messages.emplace_back(message); } else if (accountId == carlaData.accountId) { carlaData.messages.emplace_back(message); } cv.notify_one(); })); libjami::registerSignalHandlers(confHandlers); // Link callback for convModule() auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceData.accountId); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobData.accountId); auto carlaAccount = Manager::instance().getAccount<JamiAccount>(carlaData.accountId); aliceAccount->convModule()->onBootstrapStatus( [&](std::string /*convId*/, Conversation::BootstrapStatus status) { aliceData.bootstrap = status; cv.notify_one(); }); bobAccount->convModule()->onBootstrapStatus( [&](std::string /*convId*/, Conversation::BootstrapStatus status) { bobData.bootstrap = status; cv.notify_one(); }); carlaAccount->convModule()->onBootstrapStatus( [&](std::string /*convId*/, Conversation::BootstrapStatus status) { carlaData.bootstrap = status; cv.notify_one(); }); } void BootstrapTest::testBootstrapOk() { auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceData.accountId); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobData.accountId); auto bobUri = bobAccount->getUsername(); aliceAccount->convModule()->onBootstrapStatus( [&](std::string /*convId*/, Conversation::BootstrapStatus status) { aliceData.bootstrap = status; cv.notify_one(); }); std::unique_lock lk {mtx}; auto convId = libjami::startConversation(aliceData.accountId); libjami::addConversationMember(aliceData.accountId, convId, bobUri); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.requestReceived; })); auto aliceMsgSize = aliceData.messages.size(); libjami::acceptConversationRequest(bobData.accountId, convId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.conversationReady && aliceData.messages.size() == aliceMsgSize + 1 && aliceData.bootstrap == Conversation::BootstrapStatus::SUCCESS && bobData.bootstrap == Conversation::BootstrapStatus::SUCCESS; })); } void BootstrapTest::testBootstrapFailed() { auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceData.accountId); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobData.accountId); auto bobUri = bobAccount->getUsername(); aliceAccount->convModule()->onBootstrapStatus( [&](std::string /*convId*/, Conversation::BootstrapStatus status) { aliceData.bootstrap = status; cv.notify_one(); }); std::unique_lock lk {mtx}; auto convId = libjami::startConversation(aliceData.accountId); libjami::addConversationMember(aliceData.accountId, convId, bobUri); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.requestReceived; })); auto aliceMsgSize = aliceData.messages.size(); libjami::acceptConversationRequest(bobData.accountId, convId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.conversationReady && aliceData.messages.size() == aliceMsgSize + 1 && aliceData.bootstrap == Conversation::BootstrapStatus::SUCCESS && bobData.bootstrap == Conversation::BootstrapStatus::SUCCESS; })); // Now bob goes offline, it should disconnect alice Manager::instance().sendRegister(bobData.accountId, false); // Alice will try to maintain before failing (so will take 30secs to fail) CPPUNIT_ASSERT(cv.wait_for(lk, 60s, [&]() { return aliceData.bootstrap == Conversation::BootstrapStatus::FAILED; })); } void BootstrapTest::testBootstrapNeverNewDevice() { auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceData.accountId); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobData.accountId); auto bobUri = bobAccount->getUsername(); aliceAccount->convModule()->onBootstrapStatus( [&](std::string /*convId*/, Conversation::BootstrapStatus status) { aliceData.bootstrap = status; cv.notify_one(); }); std::unique_lock lk {mtx}; auto convId = libjami::startConversation(aliceData.accountId); libjami::addConversationMember(aliceData.accountId, convId, bobUri); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.requestReceived; })); auto aliceMsgSize = aliceData.messages.size(); libjami::acceptConversationRequest(bobData.accountId, convId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.conversationReady && aliceData.messages.size() == aliceMsgSize + 1 && aliceData.bootstrap == Conversation::BootstrapStatus::SUCCESS && bobData.bootstrap == Conversation::BootstrapStatus::SUCCESS; })); // Alice offline Manager::instance().sendRegister(aliceData.accountId, false); // Bob will try to maintain before failing (so will take 30secs to fail) CPPUNIT_ASSERT(cv.wait_for(lk, 60s, [&]() { return bobData.bootstrap == Conversation::BootstrapStatus::FAILED; })); // Create bob2 auto bobArchive = std::filesystem::current_path().string() + "/bob.gz"; std::remove(bobArchive.c_str()); bobAccount->exportArchive(bobArchive); std::map<std::string, std::string> details = libjami::getAccountTemplate("RING"); details[ConfProperties::TYPE] = "RING"; details[ConfProperties::DISPLAYNAME] = "BOB2"; details[ConfProperties::ALIAS] = "BOB2"; details[ConfProperties::UPNP_ENABLED] = "true"; details[ConfProperties::ARCHIVE_PASSWORD] = ""; details[ConfProperties::ARCHIVE_PIN] = ""; details[ConfProperties::ARCHIVE_PATH] = bobArchive; bob2Data.accountId = Manager::instance().addAccount(details); auto bob2Account = Manager::instance().getAccount<JamiAccount>(bob2Data.accountId); std::map<std::string, std::shared_ptr<libjami::CallbackWrapperBase>> confHandlers; bool bob2Connected = false; confHandlers.insert( libjami::exportable_callback<libjami::ConfigurationSignal::VolatileDetailsChanged>( [&](const std::string&, const std::map<std::string, std::string>&) { auto details = bob2Account->getVolatileAccountDetails(); auto daemonStatus = details[libjami::Account::ConfProperties::Registration::STATUS]; if (daemonStatus != "UNREGISTERED") bob2Connected = true; cv.notify_one(); })); libjami::registerSignalHandlers(confHandlers); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bob2Connected; })); bob2Account->convModule()->onBootstrapStatus( [&](std::string /*convId*/, Conversation::BootstrapStatus status) { bob2Data.bootstrap = status; cv.notify_one(); }); // Disconnect bob2, to create a valid conv betwen Alice and Bob1 CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.bootstrap == Conversation::BootstrapStatus::SUCCESS && bob2Data.bootstrap == Conversation::BootstrapStatus::SUCCESS; })); // Bob offline Manager::instance().sendRegister(bobData.accountId, false); // Bob2 will try to maintain before failing (so will take 30secs to fail) CPPUNIT_ASSERT(cv.wait_for(lk, 60s, [&]() { return bob2Data.bootstrap == Conversation::BootstrapStatus::FAILED; })); // Alice bootstrap should go to fallback (because bob2 never wrote into the conversation) & Connected Manager::instance().sendRegister(aliceData.accountId, true); // Wait for announcement, ICE fallback + delay CPPUNIT_ASSERT(cv.wait_for(lk, 60s, [&]() { return aliceData.bootstrap == Conversation::BootstrapStatus::SUCCESS; })); } void BootstrapTest::testBootstrapCompat() { auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceData.accountId); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobData.accountId); auto bobUri = bobAccount->getUsername(); dynamic_cast<SwarmChannelHandler*>(aliceAccount->channelHandlers()[Uri::Scheme::SWARM].get()) ->disableSwarmManager = true; std::unique_lock lk {mtx}; auto convId = libjami::startConversation(aliceData.accountId); libjami::addConversationMember(aliceData.accountId, convId, bobUri); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.requestReceived; })); auto aliceMsgSize = aliceData.messages.size(); libjami::acceptConversationRequest(bobData.accountId, convId); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]() { return bobData.conversationReady && aliceData.messages.size() == aliceMsgSize + 1; })); auto bobMsgSize = bobData.messages.size(); libjami::sendMessage(aliceData.accountId, convId, "hi"s, ""); cv.wait_for(lk, 30s, [&]() { return bobData.messages.size() == bobMsgSize + 1 && bobData.bootstrap == Conversation::BootstrapStatus::FAILED; }); } } // namespace test } // namespace jami RING_TEST_RUNNER(jami::test::BootstrapTest::name())
15,277
C++
.cpp
337
38.477745
105
0.679363
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,690
swarm_spread.cpp
savoirfairelinux_jami-daemon/test/unitTest/swarm/swarm_spread.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <cppunit/TestAssert.h> #include <cppunit/TestFixture.h> #include <cppunit/extensions/HelperMacros.h> #include <algorithm> #include <msgpack.hpp> #include <opendht/thread_pool.h> #include <opendht/utils.h> #include <iostream> #include <fstream> #include <string> #include "../../test_runner.h" #include "jami.h" #include "../common.h" #include "jamidht/swarm/swarm_manager.h" #include <dhtnet/multiplexed_socket.h> #include "nodes.h" using namespace std::string_literals; using namespace std::chrono_literals; using namespace dht; using NodeId = dht::PkId; namespace jami { namespace test { constexpr size_t nNodes = 10; constexpr size_t BOOTSTRAP_SIZE = 2; auto time = 30s; int TOTAL_HOPS = 0; int moyenne = 0; int max = 0; int min = 10000; struct Message { int identifier_; // message identifier int hops_ = 0; // number of hops MSGPACK_DEFINE_MAP(identifier_, hops_); }; struct Counter { Counter(unsigned t) : target(t) {} const unsigned target; unsigned added {0}; std::mutex mutex; std::condition_variable cv; void count() { std::lock_guard lock(mutex); ++added; if (added == target) cv.notify_one(); } bool wait(std::chrono::steady_clock::duration timeout) { std::unique_lock lock(mutex); return cv.wait_for(lock, timeout, [&] { return added == target; }); } void wait() { std::unique_lock lock(mutex); return cv.wait(lock, [&] { return added == target; }); } }; class SwarmMessageSpread : public CppUnit::TestFixture { public: ~SwarmMessageSpread() { libjami::fini(); } static std::string name() { return "SwarmMessageSpread"; } void setUp(); void tearDown(); private: std::mt19937_64 rd {dht::crypto::getSeededRandomEngine<std::mt19937_64>()}; std::mutex channelSocketsMtx_; std::condition_variable channelSocketsCv_; std::map<NodeId, std::shared_ptr<jami::SwarmManager>> swarmManagers; std::map<NodeId, std::map<NodeId, std::pair<std::shared_ptr<dhtnet::ChannelSocketTest>, std::shared_ptr<dhtnet::ChannelSocketTest>>>> channelSockets_; std::vector<NodeId> randomNodeIds; std::vector<std::shared_ptr<jami::SwarmManager>> swarmManagersShuffled; std::set<NodeId> discoveredNodes; std::map<NodeId, int> numberTimesReceived; std::map<NodeId, int> requestsReceived; std::map<NodeId, int> answersSent; int iterations = 0; void generateSwarmManagers(); void needSocketCallBack(const std::shared_ptr<SwarmManager>& sm); void sendMessage(const std::shared_ptr<dhtnet::ChannelSocketInterface>& socket, Message msg); void receiveMessage(const NodeId nodeId, const std::shared_ptr<dhtnet::ChannelSocketInterface>& socket); void relayMessageToRoutingTable(const NodeId nodeId, const NodeId sourceId, const Message msg); void updateHops(int hops); void crossNodes(NodeId nodeId); void displayBucketDistribution(const NodeId& id); void distribution(); std::shared_ptr<jami::SwarmManager> getManager(const NodeId& id); void testWriteMessage(); CPPUNIT_TEST_SUITE(SwarmMessageSpread); CPPUNIT_TEST(testWriteMessage); CPPUNIT_TEST_SUITE_END(); }; CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(SwarmMessageSpread, SwarmMessageSpread::name()); void SwarmMessageSpread::setUp() { libjami::init( libjami::InitFlag(libjami::LIBJAMI_FLAG_DEBUG | libjami::LIBJAMI_FLAG_CONSOLE_LOG)); if (not Manager::instance().initialized) { CPPUNIT_ASSERT(libjami::start("jami-sample.yml")); } generateSwarmManagers(); } void SwarmMessageSpread::tearDown() {} void SwarmMessageSpread::generateSwarmManagers() { for (size_t i = 0; i < nNodes; i++) { const NodeId node = Hash<32>::getRandom(); auto sm = std::make_shared<SwarmManager>(node, rd, std::move([](auto) {return false;})); swarmManagers[node] = sm; randomNodeIds.emplace_back(node); swarmManagersShuffled.emplace_back(sm); } } std::shared_ptr<jami::SwarmManager> SwarmMessageSpread::getManager(const NodeId& id) { auto it = swarmManagers.find(id); return it == swarmManagers.end() ? nullptr : it->second; } void SwarmMessageSpread::crossNodes(NodeId nodeId) { std::list<NodeId> pendingNodes {nodeId}; discoveredNodes.clear(); for (const auto& curNode : pendingNodes) { if (discoveredNodes.emplace(curNode).second) { if (auto sm = getManager(curNode)) for (const auto& node : sm->getRoutingTable().getNodes()) { pendingNodes.emplace_back(node); } } } } void SwarmMessageSpread::sendMessage(const std::shared_ptr<dhtnet::ChannelSocketInterface>& socket, Message msg) { auto buffer = std::make_shared<msgpack::sbuffer>(32); msgpack::packer<msgpack::sbuffer> pk(buffer.get()); pk.pack(msg); dht::ThreadPool::io().run([socket, buffer = std::move(buffer)] { std::error_code ec; // std::this_thread::sleep_for(std::chrono::milliseconds(50)); socket->write(reinterpret_cast<const unsigned char*>(buffer->data()), buffer->size(), ec); }); } void SwarmMessageSpread::receiveMessage(const NodeId nodeId, const std::shared_ptr<dhtnet::ChannelSocketInterface>& socket) { struct DecodingContext { msgpack::unpacker pac {[](msgpack::type::object_type, std::size_t, void*) { return true; }, nullptr, 32}; }; socket->setOnRecv([this, wsocket = std::weak_ptr<dhtnet::ChannelSocketInterface>(socket), ctx = std::make_shared<DecodingContext>(), nodeId](const uint8_t* buf, size_t len) { auto socket = wsocket.lock(); if (!socket) return 0lu; ctx->pac.reserve_buffer(len); std::copy_n(buf, len, ctx->pac.buffer()); ctx->pac.buffer_consumed(len); msgpack::object_handle oh; while (ctx->pac.next(oh)) { try { Message msg; oh.get().convert(msg); if (msg.identifier_ == 1) { std::lock_guard lk(channelSocketsMtx_); auto var = numberTimesReceived.find(nodeId); iterations = iterations + 1; if (var != numberTimesReceived.end()) { var->second += 1; } else { Message msgToSend; msgToSend.identifier_ = 1; msgToSend.hops_ = msg.hops_ + 1; numberTimesReceived[nodeId] = 1; updateHops(msgToSend.hops_); relayMessageToRoutingTable(nodeId, socket->deviceId(), msgToSend); } channelSocketsCv_.notify_all(); } } catch (const std::exception& e) { JAMI_WARNING("Error DRT recv: {}", e.what()); return 0lu; } } return 0lu; }); }; void SwarmMessageSpread::updateHops(int hops) { if (hops > TOTAL_HOPS) { TOTAL_HOPS = hops; } } void SwarmMessageSpread::needSocketCallBack(const std::shared_ptr<SwarmManager>& sm) { sm->needSocketCb_ = [this, wsm = std::weak_ptr<SwarmManager>(sm)](const std::string& nodeId, auto&& onSocket) { dht::ThreadPool::io().run( [this, wsm = std::move(wsm), nodeId, onSocket = std::move(onSocket)] { auto sm = wsm.lock(); if (!sm) return; NodeId node = dhtnet::DeviceId(nodeId); if (auto smRemote = getManager(node)) { auto myId = sm->getId(); std::unique_lock lk(channelSocketsMtx_); auto& cstRemote = channelSockets_[node][myId]; auto& cstMe = channelSockets_[myId][node]; if (cstMe.second && cstMe.first) return; if (!cstMe.second) { cstMe.second = std::make_shared<dhtnet::ChannelSocketTest>(Manager::instance().ioContext(), node, "test1", 1); cstRemote.second = std::make_shared<dhtnet::ChannelSocketTest>(Manager::instance().ioContext(), myId, "test1", 1); } if (!cstMe.first) { cstRemote.first = std::make_shared<dhtnet::ChannelSocketTest>(Manager::instance().ioContext(), myId, "swarm1", 0); cstMe.first = std::make_shared<dhtnet::ChannelSocketTest>(Manager::instance().ioContext(), node, "swarm1", 0); } lk.unlock(); dhtnet::ChannelSocketTest::link(cstMe.second, cstRemote.second); receiveMessage(myId, cstMe.second); receiveMessage(node, cstRemote.second); // std::this_thread::sleep_for(std::chrono::seconds(5)); dhtnet::ChannelSocketTest::link(cstMe.first, cstRemote.first); smRemote->addChannel(cstRemote.first); onSocket(cstMe.first); } }); }; } void SwarmMessageSpread::relayMessageToRoutingTable(const NodeId nodeId, const NodeId sourceId, const Message msg) { auto swarmManager = getManager(nodeId); const auto& routingtable = swarmManager->getRoutingTable().getNodes(); for (auto& node : routingtable) { if (node != sourceId) { auto channelToSend = channelSockets_[nodeId][node].second; sendMessage(channelToSend, msg); } } } void SwarmMessageSpread::distribution() { std::string const fileName("distrib_nodes_" + std::to_string(nNodes) + ".txt"); std::ofstream myStream(fileName.c_str()); std::vector<unsigned> dist(10); int mean = 0; for (const auto& sm : swarmManagers) { auto val = sm.second->getRoutingTable().getRoutingTableNodeCount(); if (dist.size() <= val) dist.resize(val + 1); dist[val]++; } for (size_t i = 0; i < dist.size(); i++) { // std::cout << "Swarm Managers with " << i << " nodes: " << dist[i] << std::endl; if (myStream) { myStream << i << "," << dist[i] << std::endl; } mean += i * dist[i]; } std::cout << "Le noeud avec le plus de noeuds dans sa routing table: " << dist.size() << std::endl; std::cout << "Moyenne de nombre de noeuds par Swarm: " << mean / (float) swarmManagers.size() << std::endl; } void SwarmMessageSpread::displayBucketDistribution(const NodeId& id) { std::string const fileName("distrib_rt_" + std::to_string(nNodes) + "_" + id.toString() + ".txt"); std::ofstream myStream(fileName.c_str()); const auto& routingtable = swarmManagers[id]->getRoutingTable().getBuckets(); std::cout << "Bucket distribution for node " << id << std::endl; for (auto it = routingtable.begin(); it != routingtable.end(); ++it) { auto lowerLimit = it->getLowerLimit().toString(); std::string hex_prefix = lowerLimit.substr(0, 4); // extraire les deux premiers caractères std::cout << "Bucket " << hex_prefix << " has " << it->getNodesSize() << " nodes" << std::endl; if (myStream) { myStream << hex_prefix << "," << it->getNodesSize() << std::endl; } } } void SwarmMessageSpread::testWriteMessage() { std::cout << "\ntestWriteMessage()" << std::endl; for (const auto& sm : swarmManagersShuffled) { needSocketCallBack(sm); } Counter counter(swarmManagers.size()); for (const auto& sm : swarmManagers) { dht::ThreadPool::computation().run([&] { std::vector<NodeId> randIds(BOOTSTRAP_SIZE); std::uniform_int_distribution<size_t> distribution(0, randomNodeIds.size() - 1); std::generate(randIds.begin(), randIds.end(), [&] { auto dev = randomNodeIds[distribution(rd)]; return dev; }); sm.second->setKnownNodes(randIds); counter.count(); }); } counter.wait(); std::this_thread::sleep_for(time); auto& firstNode = *channelSockets_.begin(); crossNodes(swarmManagers.begin()->first); CPPUNIT_ASSERT_EQUAL(swarmManagers.size(), discoveredNodes.size()); std::cout << "Sending First Message to " << firstNode.second.size() << std::endl; auto start = std::chrono::steady_clock::now(); numberTimesReceived[firstNode.first] = 1; for (const auto& channel : firstNode.second) { if (channel.second.second) { sendMessage(channel.second.second, {1, 0}); } } std::unique_lock lk(channelSocketsMtx_); bool ok = channelSocketsCv_.wait_for(lk, 1200s, [&] { std::cout << "\r" << "Size of Received " << numberTimesReceived.size(); return numberTimesReceived.size() == swarmManagers.size(); }); auto now = std::chrono::steady_clock::now(); std::cout << "#########################################################################" << std::endl; std::cout << "Time for everyone to receive the message " << dht::print_duration(now - start) << std::endl; std::cout << " IS OK " << ok << std::endl; // ############################################################################## for (const auto& count : numberTimesReceived) { moyenne = moyenne + count.second; if (count.second > max) { max = count.second; } if (count.second < min) { min = count.second; } } auto it = channelSockets_.begin(); displayBucketDistribution((*it).first); std::advance(it, swarmManagers.size() / 2); displayBucketDistribution((*it).first); std::advance(it, swarmManagers.size() / 2 - 1); displayBucketDistribution((*it).first); std::cout << "MOYENNE DE RECEPTION PAR NOEUD [ " << moyenne / (float) numberTimesReceived.size() << " ] " << std::endl; std::cout << "MAX DE RECEPTION PAR NOEUD [ " << max << " ] " << std::endl; std::cout << "MIN DE RECEPTION PAR NOEUD [ " << min << " ] " << std::endl; std::cout << "NOMBRE DE SAUTS DIRECTS [ " << TOTAL_HOPS << " ] " << std::endl; std::cout << "NOMBRE D'ITERATIONS [ " << iterations << " ] " << std::endl; distribution(); std::cout << "#########################################################################" << std::endl; std::cout << "Number of times received " << numberTimesReceived.size() << std::endl; std::cout << "Number of swarm managers " << swarmManagers.size() << std::endl; CPPUNIT_ASSERT(true); } }; // namespace test } // namespace jami RING_TEST_RUNNER(jami::test::SwarmMessageSpread::name())
16,056
C++
.cpp
402
31.562189
138
0.58842
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,691
testString_utils.cpp
savoirfairelinux_jami-daemon/test/unitTest/string_utils/testString_utils.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <cppunit/TestAssert.h> #include <cppunit/TestFixture.h> #include <cppunit/extensions/HelperMacros.h> #include "string_utils.h" #include "account.h" #include <string> #include <string_view> #include "../../test_runner.h" using namespace std::literals; namespace jami { namespace test { class StringUtilsTest : public CppUnit::TestFixture { public: static std::string name() { return "string_utils"; } private: void bool_to_str_test(); void to_string_test(); void to_number_test(); void split_string_test(); void version_test(); CPPUNIT_TEST_SUITE(StringUtilsTest); CPPUNIT_TEST(bool_to_str_test); CPPUNIT_TEST(to_string_test); CPPUNIT_TEST(to_number_test); CPPUNIT_TEST(split_string_test); CPPUNIT_TEST(version_test); CPPUNIT_TEST_SUITE_END(); const double DOUBLE = 3.14159265359; const int INT = 42; const std::string PI_DOUBLE = "3.14159265359"; const std::string PI_FLOAT = "3.14159265359"; const std::string PI_42 = "42"; }; CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(StringUtilsTest, StringUtilsTest::name()); void StringUtilsTest::bool_to_str_test() { CPPUNIT_ASSERT(bool_to_str(true) == TRUE_STR); CPPUNIT_ASSERT(bool_to_str(false) == FALSE_STR); } void StringUtilsTest::to_string_test() { // test with double CPPUNIT_ASSERT(to_string(DOUBLE) == PI_DOUBLE); // test with float float varFloat = 3.14; std::string sVarFloat = to_string(varFloat); CPPUNIT_ASSERT(sVarFloat.at(0) == '3' && sVarFloat.at(1) == '.' && sVarFloat.at(2) == '1' && sVarFloat.at(3) == '4'); // test with int CPPUNIT_ASSERT(std::to_string(INT).compare(PI_42) == 0); CPPUNIT_ASSERT_EQUAL("0000000000000010"s, to_hex_string(16)); CPPUNIT_ASSERT_EQUAL((uint64_t)16, from_hex_string("0000000000000010"s)); } void StringUtilsTest::to_number_test() { // test with int CPPUNIT_ASSERT(jami::stoi(PI_42) == INT); // test with double CPPUNIT_ASSERT(jami::stod(PI_DOUBLE) == DOUBLE); } void StringUtilsTest::split_string_test() { auto data = "*fdg454()**{&xcx*"sv; auto split_string_result = split_string(data, '*'); CPPUNIT_ASSERT(split_string_result.size() == 2); CPPUNIT_ASSERT(split_string_result.at(0) == "fdg454()"sv && split_string_result.at(1) == "{&xcx"sv); auto split_string_to_unsigned_result = split_string_to_unsigned("/4545497//45454/", '/'); CPPUNIT_ASSERT(split_string_to_unsigned_result.size() == 2); CPPUNIT_ASSERT(split_string_to_unsigned_result.at(0) == 4545497 && split_string_to_unsigned_result.at(1) == 45454); std::string_view line; split_string_result.clear(); while (jami::getline(data, line, '*')) { split_string_result.emplace_back(line); } CPPUNIT_ASSERT(split_string_result.size() == 2); CPPUNIT_ASSERT(split_string_result.at(0) == "fdg454()"sv && split_string_result.at(1) == "{&xcx"sv); } void StringUtilsTest::version_test() { CPPUNIT_ASSERT(Account::meetMinimumRequiredVersion({}, {})); CPPUNIT_ASSERT(Account::meetMinimumRequiredVersion({1, 2, 3}, {})); CPPUNIT_ASSERT(Account::meetMinimumRequiredVersion({1, 2, 3}, {1, 2, 3})); CPPUNIT_ASSERT(Account::meetMinimumRequiredVersion({1, 2, 3, 4}, {1, 2, 3})); CPPUNIT_ASSERT(Account::meetMinimumRequiredVersion({2}, {1, 2, 3})); CPPUNIT_ASSERT(Account::meetMinimumRequiredVersion( split_string_to_unsigned("1.2.3.5", '.'), split_string_to_unsigned("1.2.3.4", '.'))); CPPUNIT_ASSERT(!Account::meetMinimumRequiredVersion({}, {1, 2, 3})); CPPUNIT_ASSERT(!Account::meetMinimumRequiredVersion({1, 2, 2}, {1, 2, 3})); CPPUNIT_ASSERT(!Account::meetMinimumRequiredVersion({1, 2, 3}, {1, 2, 3, 4})); CPPUNIT_ASSERT(!Account::meetMinimumRequiredVersion({1, 2, 3}, {2})); CPPUNIT_ASSERT(!Account::meetMinimumRequiredVersion( split_string_to_unsigned("1.2.3.4", '.'), split_string_to_unsigned("1.2.3.5", '.'))); } } // namespace test } // namespace jami RING_TEST_RUNNER(jami::test::StringUtilsTest::name());
4,839
C++
.cpp
123
35.186992
93
0.679812
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
751,692
testAccount_factory.cpp
savoirfairelinux_jami-daemon/test/unitTest/account_factory/testAccount_factory.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <cppunit/TestAssert.h> #include <cppunit/TestFixture.h> #include <cppunit/extensions/HelperMacros.h> #include <condition_variable> #include "account_factory.h" #include "../../test_runner.h" #include "jami.h" #include "account_const.h" #include "manager.h" #include "account_const.h" #include "account_schema.h" #include "common.h" #include "jamidht/jamiaccount.h" using namespace std::literals::chrono_literals; namespace jami { namespace test { class Account_factoryTest : public CppUnit::TestFixture { public: Account_factoryTest() { // Init daemon libjami::init(libjami::InitFlag(libjami::LIBJAMI_FLAG_DEBUG | libjami::LIBJAMI_FLAG_CONSOLE_LOG)); if (not Manager::instance().initialized) CPPUNIT_ASSERT(libjami::start("dring-sample.yml")); } ~Account_factoryTest() { libjami::fini(); } static std::string name() { return "Account_factory"; } void setUp(); void tearDown(); private: void testAddRemoveSIPAccount(); void testAddRemoveRINGAccount(); void testClear(); CPPUNIT_TEST_SUITE(Account_factoryTest); CPPUNIT_TEST(testAddRemoveSIPAccount); CPPUNIT_TEST(testAddRemoveRINGAccount); CPPUNIT_TEST(testClear); CPPUNIT_TEST_SUITE_END(); const std::string SIP_ID = "SIP_ID"; const std::string JAMI_ID = "JAMI_ID"; bool sipReady, ringReady, accountsRemoved, knownDevicesChanged; size_t initialAccounts; std::map<std::string, std::shared_ptr<libjami::CallbackWrapperBase>> confHandlers; std::mutex mtx; std::unique_lock<std::mutex> lk {mtx}; std::condition_variable cv; }; CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(Account_factoryTest, Account_factoryTest::name()); void Account_factoryTest::setUp() { sipReady = false; ringReady = false; accountsRemoved = false; initialAccounts = Manager::instance().accountCount(); confHandlers.insert( libjami::exportable_callback<libjami::ConfigurationSignal::VolatileDetailsChanged>( [&](const std::string& accountID, const std::map<std::string, std::string>& details) { if (accountID != JAMI_ID && accountID != SIP_ID) { return; } try { ringReady |= accountID == JAMI_ID && details.at(jami::Conf::CONFIG_ACCOUNT_REGISTRATION_STATUS) == "REGISTERED" && details.at(libjami::Account::VolatileProperties::DEVICE_ANNOUNCED) == "true"; sipReady |= accountID == SIP_ID && details.at(jami::Conf::CONFIG_ACCOUNT_REGISTRATION_STATUS) == "READY"; } catch (const std::out_of_range&) {} })); confHandlers.insert( libjami::exportable_callback<libjami::ConfigurationSignal::AccountsChanged>([&]() { if (jami::Manager::instance().getAccountList().size() <= initialAccounts) { accountsRemoved = true; } })); confHandlers.insert( libjami::exportable_callback<libjami::ConfigurationSignal::KnownDevicesChanged>([&](auto, auto) { knownDevicesChanged = true; })); libjami::registerSignalHandlers(confHandlers); } void Account_factoryTest::tearDown() { libjami::unregisterSignalHandlers(); } void Account_factoryTest::testAddRemoveSIPAccount() { AccountFactory* accountFactory = &Manager::instance().accountFactory; auto accDetails = libjami::getAccountTemplate("SIP"); auto newAccount = Manager::instance().addAccount(accDetails, SIP_ID); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&] { return sipReady; })); CPPUNIT_ASSERT(accountFactory->hasAccount(SIP_ID)); CPPUNIT_ASSERT(!accountFactory->hasAccount(JAMI_ID)); CPPUNIT_ASSERT(!accountFactory->empty()); CPPUNIT_ASSERT(accountFactory->accountCount() == 1 + initialAccounts); auto details = Manager::instance().getVolatileAccountDetails(SIP_ID); CPPUNIT_ASSERT(details.find(libjami::Account::ConfProperties::DEVICE_ID) == details.end()); Manager::instance().removeAccount(SIP_ID, true); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&] { return accountsRemoved; })); } void Account_factoryTest::testAddRemoveRINGAccount() { AccountFactory* accountFactory = &Manager::instance().accountFactory; auto accDetails = libjami::getAccountTemplate("RING"); auto newAccount = Manager::instance().addAccount(accDetails, JAMI_ID); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&] { return ringReady; })); CPPUNIT_ASSERT(accountFactory->hasAccount(JAMI_ID)); CPPUNIT_ASSERT(!accountFactory->hasAccount(SIP_ID)); CPPUNIT_ASSERT(!accountFactory->empty()); CPPUNIT_ASSERT(accountFactory->accountCount() == 1 + initialAccounts); auto details = Manager::instance().getVolatileAccountDetails(JAMI_ID); CPPUNIT_ASSERT(details.find(libjami::Account::ConfProperties::DEVICE_ID) != details.end()); std::map<std::string, std::string> newDetails; newDetails[libjami::Account::ConfProperties::DEVICE_NAME] = "foo"; knownDevicesChanged = false; libjami::setAccountDetails(JAMI_ID, newDetails); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&] { return knownDevicesChanged; })); details = Manager::instance().getAccountDetails(JAMI_ID); CPPUNIT_ASSERT(details[libjami::Account::ConfProperties::DEVICE_NAME] == "foo"); Manager::instance().removeAccount(JAMI_ID, true); CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&] { return accountsRemoved; })); } void Account_factoryTest::testClear() { AccountFactory accountFactory; // verify if there is no account at the beginning CPPUNIT_ASSERT(accountFactory.empty()); CPPUNIT_ASSERT(accountFactory.accountCount() == 0); const int nbrAccount = 5; for(int i = 0; i < nbrAccount ; ++i) { accountFactory.createAccount(libjami::Account::ProtocolNames::RING, JAMI_ID+std::to_string(i)); } CPPUNIT_ASSERT(accountFactory.accountCount()==nbrAccount); CPPUNIT_ASSERT(!accountFactory.empty()); accountFactory.clear(); CPPUNIT_ASSERT(accountFactory.empty()); CPPUNIT_ASSERT(accountFactory.accountCount()==0); } }} // namespace jami::test RING_TEST_RUNNER(jami::test::Account_factoryTest::name())
7,006
C++
.cpp
164
37.02439
112
0.693845
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,693
testFileutils.cpp
savoirfairelinux_jami-daemon/test/unitTest/fileutils/testFileutils.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <cppunit/TestAssert.h> #include <cppunit/TestFixture.h> #include <cppunit/extensions/HelperMacros.h> #include "../../test_runner.h" #include "fileutils.h" #include "jami.h" #include <string> #include <iostream> #include <cstdlib> #include <unistd.h> namespace jami { namespace fileutils { namespace test { class FileutilsTest : public CppUnit::TestFixture { public: static std::string name() { return "fileutils"; } void setUp(); void tearDown(); private: void testPath(); void testLoadFile(); void testIsDirectoryWritable(); void testGetCleanPath(); void testFullPath(); CPPUNIT_TEST_SUITE(FileutilsTest); CPPUNIT_TEST(testPath); CPPUNIT_TEST(testLoadFile); CPPUNIT_TEST(testIsDirectoryWritable); CPPUNIT_TEST(testGetCleanPath); CPPUNIT_TEST(testFullPath); CPPUNIT_TEST_SUITE_END(); static constexpr auto tmpFileName = "temp_file"; std::string TEST_PATH; std::string NON_EXISTANT_PATH_BASE; std::string NON_EXISTANT_PATH; std::string EXISTANT_FILE; }; CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(FileutilsTest, FileutilsTest::name()); void FileutilsTest::setUp() { char template_name[] = {"ring_unit_tests_XXXXXX"}; // Generate a temporary directory with a file inside auto directory = mkdtemp(template_name); CPPUNIT_ASSERT(directory); TEST_PATH = directory; EXISTANT_FILE = TEST_PATH + DIR_SEPARATOR_STR + tmpFileName; NON_EXISTANT_PATH_BASE = TEST_PATH + DIR_SEPARATOR_STR + "not_existing_path"; NON_EXISTANT_PATH = NON_EXISTANT_PATH_BASE + DIR_SEPARATOR_STR + "test"; auto* fd = fopen(EXISTANT_FILE.c_str(), "w"); fwrite("RING", 1, 4, fd); fclose(fd); } void FileutilsTest::tearDown() { unlink(EXISTANT_FILE.c_str()); rmdir(TEST_PATH.c_str()); } void FileutilsTest::testPath() { CPPUNIT_ASSERT(isPathRelative("relativePath")); CPPUNIT_ASSERT(std::filesystem::is_regular_file(EXISTANT_FILE)); CPPUNIT_ASSERT(!std::filesystem::is_directory(EXISTANT_FILE)); CPPUNIT_ASSERT(std::filesystem::is_directory(TEST_PATH)); } void FileutilsTest::testLoadFile() { auto file = loadFile(EXISTANT_FILE); CPPUNIT_ASSERT(file.size() == 4); CPPUNIT_ASSERT(file.at(0) == 'R'); CPPUNIT_ASSERT(file.at(1) == 'I'); CPPUNIT_ASSERT(file.at(2) == 'N'); CPPUNIT_ASSERT(file.at(3) == 'G'); } void FileutilsTest::testIsDirectoryWritable() { CPPUNIT_ASSERT(dhtnet::fileutils::recursive_mkdir(NON_EXISTANT_PATH_BASE)); CPPUNIT_ASSERT(isDirectoryWritable(NON_EXISTANT_PATH_BASE)); CPPUNIT_ASSERT(dhtnet::fileutils::removeAll(NON_EXISTANT_PATH_BASE) == 0); // Create directory with permission: read by owner CPPUNIT_ASSERT(dhtnet::fileutils::recursive_mkdir(NON_EXISTANT_PATH_BASE, 0400)); CPPUNIT_ASSERT(!isDirectoryWritable(NON_EXISTANT_PATH_BASE)); CPPUNIT_ASSERT(dhtnet::fileutils::removeAll(NON_EXISTANT_PATH_BASE) == 0); } void FileutilsTest::testGetCleanPath() { //empty base CPPUNIT_ASSERT(getCleanPath("", NON_EXISTANT_PATH).compare(NON_EXISTANT_PATH) == 0); //the base is not contain in the path CPPUNIT_ASSERT(getCleanPath(NON_EXISTANT_PATH, NON_EXISTANT_PATH_BASE).compare(NON_EXISTANT_PATH_BASE) == 0); //the method is use correctly CPPUNIT_ASSERT(getCleanPath(NON_EXISTANT_PATH_BASE, NON_EXISTANT_PATH).compare("test") == 0); } void FileutilsTest::testFullPath() { //empty base CPPUNIT_ASSERT(getFullPath("", "relativePath").compare("relativePath") == 0); //the path is not relative CPPUNIT_ASSERT(getFullPath(NON_EXISTANT_PATH_BASE, "/tmp").compare("/tmp") == 0); //the method is use correctly CPPUNIT_ASSERT(getFullPath(NON_EXISTANT_PATH_BASE, "test").compare(NON_EXISTANT_PATH) == 0); } }}} // namespace jami::test::fileutils RING_TEST_RUNNER(jami::fileutils::test::FileutilsTest::name());
4,572
C++
.cpp
124
33.556452
113
0.725588
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,694
hold_resume.cpp
savoirfairelinux_jami-daemon/test/unitTest/media_negotiation/hold_resume.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "manager.h" #include "jamidht/jamiaccount.h" #include "../../test_runner.h" #include "jami.h" #include "jami/media_const.h" #include "call_const.h" #include "account_const.h" #include "sip/sipcall.h" #include "sip/sdp.h" #include "common.h" #include <dhtnet/connectionmanager.h> #include <cppunit/TestAssert.h> #include <cppunit/TestFixture.h> #include <cppunit/extensions/HelperMacros.h> #include <condition_variable> #include <string> using namespace libjami::Account; using namespace libjami::Call; namespace jami { namespace test { struct TestScenario { TestScenario(const std::vector<MediaAttribute>& offer, const std::vector<MediaAttribute>& answer, const std::vector<MediaAttribute>& offerUpdate, const std::vector<MediaAttribute>& answerUpdate) : offer_(std::move(offer)) , answer_(std::move(answer)) , offerUpdate_(std::move(offerUpdate)) , answerUpdate_(std::move(answerUpdate)) {} TestScenario() {}; std::vector<MediaAttribute> offer_; std::vector<MediaAttribute> answer_; std::vector<MediaAttribute> offerUpdate_; std::vector<MediaAttribute> answerUpdate_; // Determine if we should expect the MediaNegotiationStatus signal. bool expectMediaRenegotiation_ {false}; }; struct CallData { struct Signal { Signal(const std::string& name, const std::string& event = {}) : name_(std::move(name)) , event_(std::move(event)) {}; std::string name_ {}; std::string event_ {}; }; std::string accountId_ {}; std::string userName_ {}; std::string alias_ {}; std::string callId_ {}; std::vector<Signal> signals_; std::condition_variable cv_ {}; std::mutex mtx_; }; /** * Basic tests for media negotiation. */ class HoldResumeTest : public CppUnit::TestFixture { public: HoldResumeTest() { // Init daemon libjami::init(libjami::InitFlag(libjami::LIBJAMI_FLAG_DEBUG | libjami::LIBJAMI_FLAG_CONSOLE_LOG)); if (not Manager::instance().initialized) CPPUNIT_ASSERT(libjami::start("jami-sample.yml")); } ~HoldResumeTest() { libjami::fini(); } static std::string name() { return "HoldResumeTest"; } void setUp(); void tearDown(); private: // Test cases. void audio_and_video_then_hold_resume(); void audio_only_then_hold_resume(); CPPUNIT_TEST_SUITE(HoldResumeTest); CPPUNIT_TEST(audio_and_video_then_hold_resume); CPPUNIT_TEST(audio_only_then_hold_resume); CPPUNIT_TEST_SUITE_END(); // Event/Signal handlers static void onCallStateChange(const std::string& callId, const std::string& state, CallData& callData); static void onIncomingCallWithMedia(const std::string& accountId, const std::string& callId, const std::vector<libjami::MediaMap> mediaList, CallData& callData); // For backward compatibility test cases static void onIncomingCall(const std::string& accountId, const std::string& callId, CallData& callData); static void onMediaChangeRequested(const std::string& accountId, const std::string& callId, const std::vector<libjami::MediaMap> mediaList, CallData& callData); static void onMediaNegotiationStatus(const std::string& callId, const std::string& event, CallData& callData); // Helpers static void configureScenario(CallData& bob, CallData& alice); void testWithScenario(CallData& aliceData, CallData& bobData, const TestScenario& scenario); static std::string getUserAlias(const std::string& callId); // Wait for a signal from the callbacks. Some signals also report the event that // triggered the signal a like the StateChange signal. static bool waitForSignal(CallData& callData, const std::string& signal, const std::string& expectedEvent = {}); private: CallData aliceData_; CallData bobData_; }; CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(HoldResumeTest, HoldResumeTest::name()); void HoldResumeTest::setUp() { auto actors = load_actors("actors/alice-bob-no-upnp.yml"); aliceData_.accountId_ = actors["alice"]; bobData_.accountId_ = actors["bob"]; JAMI_INFO("Initialize account..."); auto aliceAccount = Manager::instance().getAccount<JamiAccount>(aliceData_.accountId_); auto bobAccount = Manager::instance().getAccount<JamiAccount>(bobData_.accountId_); wait_for_announcement_of({aliceAccount->getAccountID(), bobAccount->getAccountID()}); } void HoldResumeTest::tearDown() { wait_for_removal_of({aliceData_.accountId_, bobData_.accountId_}); } std::string HoldResumeTest::getUserAlias(const std::string& callId) { auto call = Manager::instance().getCallFromCallID(callId); if (not call) { JAMI_WARN("Call with ID [%s] does not exist anymore!", callId.c_str()); return {}; } auto const& account = call->getAccount().lock(); if (not account) { return {}; } return account->getAccountDetails()[ConfProperties::ALIAS]; } void HoldResumeTest::onIncomingCallWithMedia(const std::string& accountId, const std::string& callId, const std::vector<libjami::MediaMap> mediaList, CallData& callData) { CPPUNIT_ASSERT_EQUAL(callData.accountId_, accountId); JAMI_INFO("Signal [%s] - user [%s] - call [%s] - media count [%lu]", libjami::CallSignal::IncomingCallWithMedia::name, callData.alias_.c_str(), callId.c_str(), mediaList.size()); if (not Manager::instance().getCallFromCallID(callId)) { JAMI_WARN("Call with ID [%s] does not exist!", callId.c_str()); callData.callId_ = {}; return; } std::unique_lock lock {callData.mtx_}; callData.callId_ = callId; callData.signals_.emplace_back(CallData::Signal(libjami::CallSignal::IncomingCallWithMedia::name)); callData.cv_.notify_one(); } void HoldResumeTest::onIncomingCall(const std::string& accountId, const std::string& callId, CallData& callData) { CPPUNIT_ASSERT_EQUAL(callData.accountId_, accountId); JAMI_INFO("Signal [%s] - user [%s] - call [%s]", libjami::CallSignal::IncomingCall::name, callData.alias_.c_str(), callId.c_str()); if (not Manager::instance().getCallFromCallID(callId)) { JAMI_WARN("Call with ID [%s] does not exist!", callId.c_str()); callData.callId_ = {}; return; } std::unique_lock lock {callData.mtx_}; callData.callId_ = callId; callData.signals_.emplace_back(CallData::Signal(libjami::CallSignal::IncomingCall::name)); callData.cv_.notify_one(); } void HoldResumeTest::onMediaChangeRequested(const std::string& accountId, const std::string& callId, const std::vector<libjami::MediaMap> mediaList, CallData& callData) { CPPUNIT_ASSERT_EQUAL(callData.accountId_, accountId); JAMI_INFO("Signal [%s] - user [%s] - call [%s] - media count [%lu]", libjami::CallSignal::MediaChangeRequested::name, callData.alias_.c_str(), callId.c_str(), mediaList.size()); if (not Manager::instance().getCallFromCallID(callId)) { JAMI_WARN("Call with ID [%s] does not exist!", callId.c_str()); callData.callId_ = {}; return; } std::unique_lock lock {callData.mtx_}; callData.callId_ = callId; callData.signals_.emplace_back(CallData::Signal(libjami::CallSignal::MediaChangeRequested::name)); callData.cv_.notify_one(); } void HoldResumeTest::onCallStateChange(const std::string& callId, const std::string& state, CallData& callData) { auto call = Manager::instance().getCallFromCallID(callId); if (not call) { JAMI_WARN("Call with ID [%s] does not exist anymore!", callId.c_str()); return; } auto account = call->getAccount().lock(); if (not account) { JAMI_WARN("Account owning the call [%s] does not exist!", callId.c_str()); return; } JAMI_INFO("Signal [%s] - user [%s] - call [%s] - state [%s]", libjami::CallSignal::StateChange::name, callData.alias_.c_str(), callId.c_str(), state.c_str()); if (account->getAccountID() != callData.accountId_) return; { std::unique_lock lock {callData.mtx_}; callData.signals_.emplace_back( CallData::Signal(libjami::CallSignal::StateChange::name, state)); } if (state == "CURRENT" or state == "OVER" or state == "HUNGUP") { callData.cv_.notify_one(); } } void HoldResumeTest::onMediaNegotiationStatus(const std::string& callId, const std::string& event, CallData& callData) { auto call = Manager::instance().getCallFromCallID(callId); if (not call) { JAMI_WARN("Call with ID [%s] does not exist!", callId.c_str()); return; } auto account = call->getAccount().lock(); if (not account) { JAMI_WARN("Account owning the call [%s] does not exist!", callId.c_str()); return; } JAMI_INFO("Signal [%s] - user [%s] - call [%s] - state [%s]", libjami::CallSignal::MediaNegotiationStatus::name, account->getAccountDetails()[ConfProperties::ALIAS].c_str(), call->getCallId().c_str(), event.c_str()); if (account->getAccountID() != callData.accountId_) return; { std::unique_lock lock {callData.mtx_}; callData.signals_.emplace_back( CallData::Signal(libjami::CallSignal::MediaNegotiationStatus::name, event)); } callData.cv_.notify_one(); } bool HoldResumeTest::waitForSignal(CallData& callData, const std::string& expectedSignal, const std::string& expectedEvent) { const std::chrono::seconds TIME_OUT {30}; std::unique_lock lock {callData.mtx_}; // Combined signal + event (if any). std::string sigEvent(expectedSignal); if (not expectedEvent.empty()) sigEvent += "::" + expectedEvent; JAMI_INFO("[%s] is waiting for [%s] signal/event", callData.alias_.c_str(), sigEvent.c_str()); auto res = callData.cv_.wait_for(lock, TIME_OUT, [&] { // Search for the expected signal in list of received signals. bool pred = false; for (auto it = callData.signals_.begin(); it != callData.signals_.end(); it++) { // The predicate is true if the signal names match, and if the // expectedEvent is not empty, the events must also match. if (it->name_ == expectedSignal and (expectedEvent.empty() or it->event_ == expectedEvent)) { pred = true; // Done with this signal. callData.signals_.erase(it); break; } } return pred; }); if (not res) { JAMI_ERR("[%s] waiting for signal/event [%s] timed-out!", callData.alias_.c_str(), sigEvent.c_str()); JAMI_INFO("[%s] currently has the following signals:", callData.alias_.c_str()); for (auto const& sig : callData.signals_) { JAMI_INFO() << "Signal [" << sig.name_ << (sig.event_.empty() ? "" : ("::" + sig.event_)) << "]"; } } return res; } void HoldResumeTest::configureScenario(CallData& aliceData, CallData& bobData) { { CPPUNIT_ASSERT(not aliceData.accountId_.empty()); auto const& account = Manager::instance().getAccount<JamiAccount>(aliceData.accountId_); aliceData.userName_ = account->getAccountDetails()[ConfProperties::USERNAME]; aliceData.alias_ = account->getAccountDetails()[ConfProperties::ALIAS]; } { CPPUNIT_ASSERT(not bobData.accountId_.empty()); auto const& account = Manager::instance().getAccount<JamiAccount>(bobData.accountId_); bobData.userName_ = account->getAccountDetails()[ConfProperties::USERNAME]; bobData.alias_ = account->getAccountDetails()[ConfProperties::ALIAS]; } std::map<std::string, std::shared_ptr<libjami::CallbackWrapperBase>> signalHandlers; // Insert needed signal handlers. signalHandlers.insert(libjami::exportable_callback<libjami::CallSignal::IncomingCallWithMedia>( [&](const std::string& accountId, const std::string& callId, const std::string&, const std::vector<libjami::MediaMap> mediaList) { auto user = getUserAlias(callId); if (not user.empty()) onIncomingCallWithMedia(accountId, callId, mediaList, user == aliceData.alias_ ? aliceData : bobData); })); signalHandlers.insert(libjami::exportable_callback<libjami::CallSignal::IncomingCall>( [&](const std::string& accountId, const std::string& callId, const std::string&) { auto user = getUserAlias(callId); if (not user.empty()) { onIncomingCall(accountId, callId, user == aliceData.alias_ ? aliceData : bobData); } })); signalHandlers.insert(libjami::exportable_callback<libjami::CallSignal::MediaChangeRequested>( [&](const std::string& accountId, const std::string& callId, const std::vector<libjami::MediaMap> mediaList) { auto user = getUserAlias(callId); if (not user.empty()) onMediaChangeRequested(accountId, callId, mediaList, user == aliceData.alias_ ? aliceData : bobData); })); signalHandlers.insert(libjami::exportable_callback<libjami::CallSignal::StateChange>( [&](const std::string&, const std::string& callId, const std::string& state, signed) { auto user = getUserAlias(callId); if (not user.empty()) onCallStateChange(callId, state, user == aliceData.alias_ ? aliceData : bobData); })); signalHandlers.insert(libjami::exportable_callback<libjami::CallSignal::MediaNegotiationStatus>( [&](const std::string& callId, const std::string& event, const std::vector<std::map<std::string, std::string>>&) { auto user = getUserAlias(callId); if (not user.empty()) onMediaNegotiationStatus(callId, event, user == aliceData.alias_ ? aliceData : bobData); })); libjami::registerSignalHandlers(signalHandlers); } void HoldResumeTest::testWithScenario(CallData& aliceData, CallData& bobData, const TestScenario& scenario) { JAMI_INFO("=== Start a call and validate ==="); // The media count of the offer and answer must match (RFC-3264). auto mediaCount = scenario.offer_.size(); CPPUNIT_ASSERT_EQUAL(mediaCount, scenario.answer_.size()); auto const& aliceCall = std::dynamic_pointer_cast<SIPCall>( (Manager::instance().getAccount<JamiAccount>(aliceData.accountId_)) ->newOutgoingCall(bobData.userName_, MediaAttribute::mediaAttributesToMediaMaps(scenario.offer_))); CPPUNIT_ASSERT(aliceCall); aliceData.callId_ = aliceCall->getCallId(); JAMI_INFO("ALICE [%s] started a call with BOB [%s] and wait for answer", aliceData.accountId_.c_str(), bobData.accountId_.c_str()); // Wait for incoming call signal. CPPUNIT_ASSERT(waitForSignal(bobData, libjami::CallSignal::IncomingCallWithMedia::name)); // Answer the call. { auto const& mediaList = MediaAttribute::mediaAttributesToMediaMaps(scenario.answer_); Manager::instance().answerCall(bobData.accountId_, bobData.callId_, mediaList); } // Wait for media negotiation complete signal. CPPUNIT_ASSERT_EQUAL( true, waitForSignal(bobData, libjami::CallSignal::MediaNegotiationStatus::name, libjami::Media::MediaNegotiationStatusEvents::NEGOTIATION_SUCCESS)); // Wait for the StateChange signal. CPPUNIT_ASSERT_EQUAL(true, waitForSignal(bobData, libjami::CallSignal::StateChange::name, StateEvent::CURRENT)); JAMI_INFO("BOB answered the call [%s]", bobData.callId_.c_str()); // Wait for media negotiation complete signal. CPPUNIT_ASSERT_EQUAL( true, waitForSignal(aliceData, libjami::CallSignal::MediaNegotiationStatus::name, libjami::Media::MediaNegotiationStatusEvents::NEGOTIATION_SUCCESS)); // Validate Alice's media and SDP { auto mediaAttr = aliceCall->getMediaAttributeList(); CPPUNIT_ASSERT_EQUAL(mediaCount, mediaAttr.size()); for (size_t idx = 0; idx < mediaCount; idx++) { CPPUNIT_ASSERT_EQUAL(scenario.offer_[idx].muted_, mediaAttr[idx].muted_); } // Check media direction auto& sdp = aliceCall->getSDP(); auto mediaStreams = sdp.getMediaSlots(); for (auto const& media : mediaStreams) { CPPUNIT_ASSERT_EQUAL(media.first.direction_, MediaDirection::SENDRECV); CPPUNIT_ASSERT_EQUAL(media.second.direction_, MediaDirection::SENDRECV); } } // Validate Bob's media { auto const& bobCall = std::dynamic_pointer_cast<SIPCall>( Manager::instance().getCallFromCallID(bobData.callId_)); auto mediaAttr = bobCall->getMediaAttributeList(); CPPUNIT_ASSERT_EQUAL(mediaCount, mediaAttr.size()); for (size_t idx = 0; idx < mediaCount; idx++) { CPPUNIT_ASSERT_EQUAL(scenario.answer_[idx].muted_, mediaAttr[idx].muted_); } // Check media direction auto& sdp = bobCall->getSDP(); auto mediaStreams = sdp.getMediaSlots(); for (auto const& media : mediaStreams) { CPPUNIT_ASSERT_EQUAL(media.first.direction_, MediaDirection::SENDRECV); CPPUNIT_ASSERT_EQUAL(media.second.direction_, MediaDirection::SENDRECV); } } std::this_thread::sleep_for(std::chrono::seconds(3)); JAMI_INFO("=== Hold the call and validate ==="); { auto const& mediaList = MediaAttribute::mediaAttributesToMediaMaps(scenario.offerUpdate_); libjami::hold(aliceData.accountId_, aliceData.callId_); } // Update and validate media count. mediaCount = scenario.offerUpdate_.size(); CPPUNIT_ASSERT_EQUAL(mediaCount, scenario.answerUpdate_.size()); if (scenario.expectMediaRenegotiation_) { // Wait for media negotiation complete signal. CPPUNIT_ASSERT_EQUAL( true, waitForSignal(aliceData, libjami::CallSignal::MediaNegotiationStatus::name, libjami::Media::MediaNegotiationStatusEvents::NEGOTIATION_SUCCESS)); // Validate Alice's media { auto mediaAttr = aliceCall->getMediaAttributeList(); CPPUNIT_ASSERT_EQUAL(mediaCount, mediaAttr.size()); for (size_t idx = 0; idx < mediaCount; idx++) { CPPUNIT_ASSERT(mediaAttr[idx].onHold_); CPPUNIT_ASSERT_EQUAL(scenario.offerUpdate_[idx].muted_, mediaAttr[idx].muted_); // Check isCaptureDeviceMuted API CPPUNIT_ASSERT_EQUAL(mediaAttr[idx].muted_, aliceCall->isCaptureDeviceMuted(mediaAttr[idx].type_)); } } // Validate Bob's media { auto const& bobCall = std::dynamic_pointer_cast<SIPCall>( Manager::instance().getCallFromCallID(bobData.callId_)); auto mediaAttr = bobCall->getMediaAttributeList(); CPPUNIT_ASSERT_EQUAL(mediaCount, mediaAttr.size()); for (size_t idx = 0; idx < mediaCount; idx++) { CPPUNIT_ASSERT(not mediaAttr[idx].onHold_); CPPUNIT_ASSERT_EQUAL(scenario.answerUpdate_[idx].muted_, mediaAttr[idx].muted_); // Check isCaptureDeviceMuted API CPPUNIT_ASSERT_EQUAL(mediaAttr[idx].muted_, bobCall->isCaptureDeviceMuted(mediaAttr[idx].type_)); } } } std::this_thread::sleep_for(std::chrono::seconds(2)); JAMI_INFO("=== Resume the call and validate ==="); { auto const& mediaList = MediaAttribute::mediaAttributesToMediaMaps(scenario.offerUpdate_); libjami::unhold(aliceData.accountId_, aliceData.callId_); } // Update and validate media count. mediaCount = scenario.offerUpdate_.size(); CPPUNIT_ASSERT_EQUAL(mediaCount, scenario.answerUpdate_.size()); if (scenario.expectMediaRenegotiation_) { // Wait for media negotiation complete signal. CPPUNIT_ASSERT_EQUAL( true, waitForSignal(aliceData, libjami::CallSignal::MediaNegotiationStatus::name, libjami::Media::MediaNegotiationStatusEvents::NEGOTIATION_SUCCESS)); // Validate Alice's media { auto mediaAttr = aliceCall->getMediaAttributeList(); CPPUNIT_ASSERT_EQUAL(mediaCount, mediaAttr.size()); for (size_t idx = 0; idx < mediaCount; idx++) { CPPUNIT_ASSERT(not mediaAttr[idx].onHold_); CPPUNIT_ASSERT_EQUAL(scenario.offerUpdate_[idx].muted_, mediaAttr[idx].muted_); // Check isCaptureDeviceMuted API CPPUNIT_ASSERT_EQUAL(mediaAttr[idx].muted_, aliceCall->isCaptureDeviceMuted(mediaAttr[idx].type_)); } } // Validate Bob's media { auto const& bobCall = std::dynamic_pointer_cast<SIPCall>( Manager::instance().getCallFromCallID(bobData.callId_)); auto mediaAttr = bobCall->getMediaAttributeList(); CPPUNIT_ASSERT_EQUAL(mediaCount, mediaAttr.size()); for (size_t idx = 0; idx < mediaCount; idx++) { CPPUNIT_ASSERT(not mediaAttr[idx].onHold_); CPPUNIT_ASSERT_EQUAL(scenario.answerUpdate_[idx].muted_, mediaAttr[idx].muted_); // Check isCaptureDeviceMuted API CPPUNIT_ASSERT_EQUAL(mediaAttr[idx].muted_, bobCall->isCaptureDeviceMuted(mediaAttr[idx].type_)); } } } std::this_thread::sleep_for(std::chrono::seconds(2)); // Bob hang-up. JAMI_INFO("Hang up BOB's call and wait for ALICE to hang up"); Manager::instance().hangupCall(bobData.accountId_, bobData.callId_); CPPUNIT_ASSERT_EQUAL(true, waitForSignal(aliceData, libjami::CallSignal::StateChange::name, StateEvent::HUNGUP)); JAMI_INFO("Call terminated on both sides"); } void HoldResumeTest::audio_and_video_then_hold_resume() { JAMI_INFO("=== Begin test %s ===", __FUNCTION__); configureScenario(aliceData_, bobData_); MediaAttribute defaultAudio(MediaType::MEDIA_AUDIO); defaultAudio.label_ = "audio_0"; defaultAudio.enabled_ = true; MediaAttribute defaultVideo(MediaType::MEDIA_VIDEO); defaultVideo.label_ = "video_0"; defaultVideo.enabled_ = true; MediaAttribute audio(defaultAudio); MediaAttribute video(defaultVideo); TestScenario scenario; // First offer/answer scenario.offer_.emplace_back(audio); scenario.offer_.emplace_back(video); scenario.answer_.emplace_back(audio); scenario.answer_.emplace_back(video); // Updated offer/answer scenario.offerUpdate_.emplace_back(audio); scenario.offerUpdate_.emplace_back(video); scenario.answerUpdate_.emplace_back(audio); scenario.answerUpdate_.emplace_back(video); scenario.expectMediaRenegotiation_ = true; testWithScenario(aliceData_, bobData_, scenario); libjami::unregisterSignalHandlers(); JAMI_INFO("=== End test %s ===", __FUNCTION__); } void HoldResumeTest::audio_only_then_hold_resume() { JAMI_INFO("=== Begin test %s ===", __FUNCTION__); configureScenario(aliceData_, bobData_); MediaAttribute defaultAudio(MediaType::MEDIA_AUDIO); defaultAudio.label_ = "audio_0"; defaultAudio.enabled_ = true; MediaAttribute audio(defaultAudio); TestScenario scenario; // First offer/answer scenario.offer_.emplace_back(audio); scenario.answer_.emplace_back(audio); // Updated offer/answer scenario.offerUpdate_.emplace_back(audio); scenario.answerUpdate_.emplace_back(audio); scenario.expectMediaRenegotiation_ = true; testWithScenario(aliceData_, bobData_, scenario); libjami::unregisterSignalHandlers(); JAMI_INFO("=== End test %s ===", __FUNCTION__); } } // namespace test } // namespace jami RING_TEST_RUNNER(jami::test::HoldResumeTest::name())
26,944
C++
.cpp
614
33.995114
106
0.613286
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,695
media_negotiation.cpp
savoirfairelinux_jami-daemon/test/unitTest/media_negotiation/media_negotiation.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "manager.h" #include "jamidht/jamiaccount.h" #include "sip/sipaccount.h" #include "../../test_runner.h" #include "jami.h" #include "jami/media_const.h" #include "call_const.h" #include "account_const.h" #include "sip/sipcall.h" #include "sip/sdp.h" #include "common.h" #include <dhtnet/connectionmanager.h> #include <cppunit/TestAssert.h> #include <cppunit/TestFixture.h> #include <cppunit/extensions/HelperMacros.h> #include <condition_variable> #include <string> using namespace libjami::Account; using namespace libjami::Call; namespace jami { namespace test { struct TestScenario { TestScenario(const std::vector<MediaAttribute>& offer, const std::vector<MediaAttribute>& answer, const std::vector<MediaAttribute>& offerUpdate, const std::vector<MediaAttribute>& answerUpdate) : offer_(std::move(offer)) , answer_(std::move(answer)) , offerUpdate_(std::move(offerUpdate)) , answerUpdate_(std::move(answerUpdate)) {} TestScenario() {}; std::vector<MediaAttribute> offer_; std::vector<MediaAttribute> answer_; std::vector<MediaAttribute> offerUpdate_; std::vector<MediaAttribute> answerUpdate_; // Determine if we should expect the MediaNegotiationStatus signal. bool expectMediaRenegotiation_ {false}; // Determine if we should expect the MediaChangeRequested signal. bool expectMediaChangeRequest_ {false}; }; struct CallData { struct Signal { Signal(const std::string& name, const std::string& event = {}) : name_(std::move(name)) , event_(std::move(event)) {}; std::string name_ {}; std::string event_ {}; }; CallData() = default; CallData(CallData&& other) = delete; CallData(const CallData& other) { accountId_ = std::move(other.accountId_); listeningPort_ = other.listeningPort_; userName_ = std::move(other.userName_); alias_ = std::move(other.alias_); callId_ = std::move(other.callId_); signals_ = std::move(other.signals_); }; std::string accountId_ {}; std::string userName_ {}; std::string alias_ {}; uint16_t listeningPort_ {0}; std::string toUri_ {}; std::string callId_ {}; std::vector<Signal> signals_; std::condition_variable cv_ {}; std::mutex mtx_; }; /** * Basic tests for media negotiation. */ class MediaNegotiationTest { public: MediaNegotiationTest() { // Init daemon libjami::init(libjami::InitFlag(libjami::LIBJAMI_FLAG_DEBUG | libjami::LIBJAMI_FLAG_CONSOLE_LOG)); if (not Manager::instance().initialized) CPPUNIT_ASSERT(libjami::start("jami-sample.yml")); } ~MediaNegotiationTest() { libjami::fini(); } static std::string name() { return "MediaNegotiationTest"; } protected: // Test cases. void audio_and_video_then_caller_mute_video(); void audio_only_then_caller_add_video(); void audio_and_video_then_caller_mute_audio(); void audio_and_video_answer_muted_video_then_mute_video(); void audio_and_video_then_change_video_source(); void negotiate_2_videos_1_audio(); // Event/Signal handlers static void onCallStateChange(const std::string& accountId, const std::string& callId, const std::string& state, CallData& callData); static void onIncomingCallWithMedia(const std::string& accountId, const std::string& callId, const std::vector<libjami::MediaMap> mediaList, CallData& callData); // For backward compatibility test cases. // TODO. Do we still need this? static void onIncomingCall(const std::string& accountId, const std::string& callId, CallData& callData); static void onMediaChangeRequested(const std::string& accountId, const std::string& callId, const std::vector<libjami::MediaMap> mediaList, CallData& callData); static void onVideoMuted(const std::string& callId, bool muted, CallData& callData); static void onMediaNegotiationStatus(const std::string& callId, const std::string& event, CallData& callData); // Helpers void configureScenario(); void testWithScenario(CallData& aliceData, CallData& bobData, const TestScenario& scenario); std::string getAccountId(const std::string& callId); std::string getUserAlias(const std::string& callId); // Infer media direction of an offer. static uint8_t directionToBitset(MediaDirection direction, bool isLocal); static MediaDirection bitsetToDirection(uint8_t val); static MediaDirection inferInitialDirection(const MediaAttribute& offer); // Infer media direction of an answer. static MediaDirection inferNegotiatedDirection(MediaDirection local, MediaDirection answer); // Wait for a signal from the callbacks. Some signals also report the event that // triggered the signal a like the StateChange signal. static bool validateMuteState(std::vector<MediaAttribute> expected, std::vector<MediaAttribute> actual); static bool validateMediaDirection(std::vector<MediaDescription> descrList, std::vector<MediaAttribute> listInOffer, std::vector<MediaAttribute> listInAnswer); static bool waitForSignal(CallData& callData, const std::string& signal, const std::string& expectedEvent = {}); bool isSipAccount_ {false}; std::map<std::string, CallData> callDataMap_; std::set<std::string> testAccounts_; }; // Specialized test case for Jami accounts class MediaNegotiationTestJami : public MediaNegotiationTest, public CppUnit::TestFixture { public: MediaNegotiationTestJami() { isSipAccount_ = false; } static std::string name() { return "MediaNegotiationTestJami"; } void setUp() override { auto actors = load_actors("actors/alice-bob-no-upnp.yml"); callDataMap_["ALICE"].accountId_ = actors["alice"]; callDataMap_["BOB"].accountId_ = actors["bob"]; JAMI_INFO("Initialize account..."); auto aliceAccount = Manager::instance().getAccount<JamiAccount>( callDataMap_["ALICE"].accountId_); auto bobAccount = Manager::instance().getAccount<JamiAccount>( callDataMap_["BOB"].accountId_); wait_for_announcement_of({aliceAccount->getAccountID(), bobAccount->getAccountID()}); } void tearDown() override { wait_for_removal_of({callDataMap_["ALICE"].accountId_, callDataMap_["BOB"].accountId_}); } private: CPPUNIT_TEST_SUITE(MediaNegotiationTestJami); CPPUNIT_TEST(audio_and_video_then_caller_mute_video); CPPUNIT_TEST(audio_only_then_caller_add_video); CPPUNIT_TEST(audio_and_video_then_caller_mute_audio); CPPUNIT_TEST(audio_and_video_answer_muted_video_then_mute_video); CPPUNIT_TEST(audio_and_video_then_change_video_source); CPPUNIT_TEST(negotiate_2_videos_1_audio); CPPUNIT_TEST_SUITE_END(); }; // Specialized test case for SIP accounts class MediaNegotiationTestSip : public MediaNegotiationTest, public CppUnit::TestFixture { public: MediaNegotiationTestSip() { isSipAccount_ = true; } static std::string name() { return "MediaNegotiationTestSip"; } bool addTestAccount(const std::string& alias, uint16_t port) { CallData callData; callData.alias_ = alias; callData.userName_ = alias; callData.listeningPort_ = port; std::map<std::string, std::string> details = libjami::getAccountTemplate("SIP"); details[ConfProperties::TYPE] = "SIP"; details[ConfProperties::USERNAME] = alias; details[ConfProperties::DISPLAYNAME] = alias; details[ConfProperties::ALIAS] = alias; details[ConfProperties::LOCAL_PORT] = std::to_string(port); details[ConfProperties::UPNP_ENABLED] = "false"; callData.accountId_ = Manager::instance().addAccount(details); testAccounts_.insert(callData.accountId_); callDataMap_.emplace(alias, std::move(callData)); return (not callDataMap_[alias].accountId_.empty()); } void setUp() override { CPPUNIT_ASSERT(addTestAccount("ALICE", 5080)); CPPUNIT_ASSERT(addTestAccount("BOB", 5082)); } void tearDown() override { std::map<std::string, std::shared_ptr<libjami::CallbackWrapperBase>> confHandlers; std::mutex mtx; std::unique_lock lk {mtx}; std::condition_variable cv; std::atomic_bool accountsRemoved {false}; confHandlers.insert( libjami::exportable_callback<libjami::ConfigurationSignal::AccountsChanged>([&]() { auto currAccounts = Manager::instance().getAccountList(); for (auto iter = testAccounts_.begin(); iter != testAccounts_.end();) { auto item = std::find(currAccounts.begin(), currAccounts.end(), *iter); if (item == currAccounts.end()) { JAMI_INFO("Removing account %s", (*iter).c_str()); iter = testAccounts_.erase(iter); } else { iter++; } } if (testAccounts_.empty()) { accountsRemoved = true; JAMI_INFO("All accounts removed..."); cv.notify_one(); } })); libjami::registerSignalHandlers(confHandlers); Manager::instance().removeAccount(callDataMap_["ALICE"].accountId_, true); Manager::instance().removeAccount(callDataMap_["BOB"].accountId_, true); CPPUNIT_ASSERT( cv.wait_for(lk, std::chrono::seconds(30), [&] { return accountsRemoved.load(); })); libjami::unregisterSignalHandlers(); } private: CPPUNIT_TEST_SUITE(MediaNegotiationTestSip); CPPUNIT_TEST(audio_and_video_then_caller_mute_video); CPPUNIT_TEST(audio_only_then_caller_add_video); CPPUNIT_TEST(audio_and_video_then_caller_mute_audio); CPPUNIT_TEST(audio_and_video_answer_muted_video_then_mute_video); CPPUNIT_TEST(audio_and_video_then_change_video_source); CPPUNIT_TEST(negotiate_2_videos_1_audio); CPPUNIT_TEST_SUITE_END(); }; std::string MediaNegotiationTest::getAccountId(const std::string& callId) { auto call = Manager::instance().getCallFromCallID(callId); if (not call) { JAMI_WARN("Call [%s] does not exist anymore!", callId.c_str()); return {}; } auto const& account = call->getAccount().lock(); if (account) { return account->getAccountID(); } JAMI_WARN("Account owning the call [%s] does not exist anymore!", callId.c_str()); return {}; } std::string MediaNegotiationTest::getUserAlias(const std::string& accountId) { if (accountId.empty()) { JAMI_WARN("No account ID is empty"); return {}; } auto ret = std::find_if(callDataMap_.begin(), callDataMap_.end(), [accountId](auto const& item) { return item.second.accountId_ == accountId; }); if (ret != callDataMap_.end()) return ret->first; JAMI_WARN("No matching test account %s", accountId.c_str()); return {}; } MediaDirection MediaNegotiationTest::inferInitialDirection(const MediaAttribute& mediaAttr) { if (not mediaAttr.enabled_) return MediaDirection::INACTIVE; if (mediaAttr.muted_) { if (mediaAttr.onHold_) return MediaDirection::INACTIVE; return MediaDirection::RECVONLY; } if (mediaAttr.onHold_) return MediaDirection::SENDONLY; return MediaDirection::SENDRECV; } uint8_t MediaNegotiationTest::directionToBitset(MediaDirection direction, bool isLocal) { if (direction == MediaDirection::SENDRECV) return 3; if (direction == MediaDirection::RECVONLY) return isLocal ? 2 : 1; if (direction == MediaDirection::SENDONLY) return isLocal ? 1 : 2; return 0; } MediaDirection MediaNegotiationTest::bitsetToDirection(uint8_t val) { if (val == 3) return MediaDirection::SENDRECV; if (val == 2) return MediaDirection::RECVONLY; if (val == 1) return MediaDirection::SENDONLY; return MediaDirection::INACTIVE; } MediaDirection MediaNegotiationTest::inferNegotiatedDirection(MediaDirection local, MediaDirection remote) { uint8_t val = directionToBitset(local, true) & directionToBitset(remote, false); return bitsetToDirection(val); } bool MediaNegotiationTest::validateMuteState(std::vector<MediaAttribute> expected, std::vector<MediaAttribute> actual) { CPPUNIT_ASSERT_EQUAL(expected.size(), actual.size()); return std::equal(expected.begin(), expected.end(), actual.begin(), actual.end(), [](auto const& expAttr, auto const& actAttr) { return expAttr.muted_ == actAttr.muted_; }); } bool MediaNegotiationTest::validateMediaDirection(std::vector<MediaDescription> descrList, std::vector<MediaAttribute> localMediaList, std::vector<MediaAttribute> remoteMediaList) { CPPUNIT_ASSERT_EQUAL(descrList.size(), localMediaList.size()); CPPUNIT_ASSERT_EQUAL(descrList.size(), remoteMediaList.size()); for (size_t idx = 0; idx < descrList.size(); idx++) { auto local = inferInitialDirection(localMediaList[idx]); auto remote = inferInitialDirection(remoteMediaList[idx]); auto negotiated = inferNegotiatedDirection(local, remote); if (descrList[idx].direction_ != negotiated) { JAMI_WARN("Media [%lu] direction mismatch: expected %i - found %i", idx, static_cast<int>(negotiated), static_cast<int>(descrList[idx].direction_)); return false; } } return true; } void MediaNegotiationTest::onIncomingCallWithMedia(const std::string& accountId, const std::string& callId, const std::vector<libjami::MediaMap> mediaList, CallData& callData) { CPPUNIT_ASSERT_EQUAL(callData.accountId_, accountId); JAMI_INFO("Signal [%s] - user [%s] - call [%s] - media count [%lu]", libjami::CallSignal::IncomingCallWithMedia::name, callData.alias_.c_str(), callId.c_str(), mediaList.size()); // NOTE. // We shouldn't access shared_ptr<Call> as this event is supposed to mimic // the client, and the client have no access to this type. But here, we only // needed to check if the call exists. This is the most straightforward and // reliable way to do it until we add a new API (like hasCall(id)). if (not Manager::instance().getCallFromCallID(callId)) { JAMI_WARN("Call with ID [%s] does not exist!", callId.c_str()); callData.callId_ = {}; return; } std::unique_lock lock {callData.mtx_}; callData.callId_ = callId; callData.signals_.emplace_back(CallData::Signal(libjami::CallSignal::IncomingCallWithMedia::name)); callData.cv_.notify_one(); } void MediaNegotiationTest::onIncomingCall(const std::string& accountId, const std::string& callId, CallData& callData) { CPPUNIT_ASSERT_EQUAL(callData.accountId_, accountId); JAMI_INFO("Signal [%s] - user [%s] - call [%s]", libjami::CallSignal::IncomingCall::name, callData.alias_.c_str(), callId.c_str()); // NOTE. // We shouldn't access shared_ptr<Call> as this event is supposed to mimic // the client, and the client have no access to this type. But here, we only // needed to check if the call exists. This is the most straightforward and // reliable way to do it until we add a new API (like hasCall(id)). if (not Manager::instance().getCallFromCallID(callId)) { JAMI_WARN("Call with ID [%s] does not exist!", callId.c_str()); callData.callId_ = {}; return; } std::unique_lock lock {callData.mtx_}; callData.callId_ = callId; callData.signals_.emplace_back(CallData::Signal(libjami::CallSignal::IncomingCall::name)); callData.cv_.notify_one(); } void MediaNegotiationTest::onMediaChangeRequested(const std::string& accountId, const std::string& callId, const std::vector<libjami::MediaMap> mediaList, CallData& callData) { CPPUNIT_ASSERT_EQUAL(callData.accountId_, accountId); JAMI_INFO("Signal [%s] - user [%s] - call [%s] - media count [%lu]", libjami::CallSignal::MediaChangeRequested::name, callData.alias_.c_str(), callId.c_str(), mediaList.size()); // TODO // We shouldn't access shared_ptr<Call> as this event is supposed to mimic // the client, and the client have no access to this type. But here, we only // needed to check if the call exists. This is the most straightforward and // reliable way to do it until we add a new API (like hasCall(id)). if (not Manager::instance().getCallFromCallID(callId)) { JAMI_WARN("Call with ID [%s] does not exist!", callId.c_str()); callData.callId_ = {}; return; } std::unique_lock lock {callData.mtx_}; callData.callId_ = callId; callData.signals_.emplace_back(CallData::Signal(libjami::CallSignal::MediaChangeRequested::name)); callData.cv_.notify_one(); } void MediaNegotiationTest::onCallStateChange(const std::string& accountId, const std::string& callId, const std::string& state, CallData& callData) { JAMI_INFO("Signal [%s] - user [%s] - call [%s] - state [%s]", libjami::CallSignal::StateChange::name, callData.alias_.c_str(), callId.c_str(), state.c_str()); CPPUNIT_ASSERT(accountId == callData.accountId_); { std::unique_lock lock {callData.mtx_}; callData.signals_.emplace_back( CallData::Signal(libjami::CallSignal::StateChange::name, state)); } // NOTE. Only states that we are interested in will notify the CV. // If this unit test is modified to process other states, they must // be added here. if (state == "CURRENT" or state == "OVER" or state == "HUNGUP" or state == "RINGING") { callData.cv_.notify_one(); } } void MediaNegotiationTest::onVideoMuted(const std::string& callId, bool muted, CallData& callData) { auto call = Manager::instance().getCallFromCallID(callId); if (not call) { JAMI_WARN("Call with ID [%s] does not exist anymore!", callId.c_str()); return; } auto account = call->getAccount().lock(); if (not account) { JAMI_WARN("Account owning the call [%s] does not exist!", callId.c_str()); return; } JAMI_INFO("Signal [%s] - user [%s] - call [%s] - state [%s]", libjami::CallSignal::VideoMuted::name, account->getAccountDetails()[ConfProperties::ALIAS].c_str(), call->getCallId().c_str(), muted ? "Mute" : "Un-mute"); if (account->getAccountID() != callData.accountId_) return; { std::unique_lock lock {callData.mtx_}; callData.signals_.emplace_back( CallData::Signal(libjami::CallSignal::VideoMuted::name, muted ? "muted" : "un-muted")); } callData.cv_.notify_one(); } void MediaNegotiationTest::onMediaNegotiationStatus(const std::string& callId, const std::string& event, CallData& callData) { auto call = Manager::instance().getCallFromCallID(callId); if (not call) { JAMI_WARN("Call with ID [%s] does not exist!", callId.c_str()); return; } auto account = call->getAccount().lock(); if (not account) { JAMI_WARN("Account owning the call [%s] does not exist!", callId.c_str()); return; } JAMI_INFO("Signal [%s] - user [%s] - call [%s] - state [%s]", libjami::CallSignal::MediaNegotiationStatus::name, account->getAccountDetails()[ConfProperties::ALIAS].c_str(), call->getCallId().c_str(), event.c_str()); if (account->getAccountID() != callData.accountId_) return; { std::unique_lock lock {callData.mtx_}; callData.signals_.emplace_back( CallData::Signal(libjami::CallSignal::MediaNegotiationStatus::name, event)); } callData.cv_.notify_one(); } bool MediaNegotiationTest::waitForSignal(CallData& callData, const std::string& expectedSignal, const std::string& expectedEvent) { const std::chrono::seconds TIME_OUT {30}; std::unique_lock lock {callData.mtx_}; // Combined signal + event (if any). std::string sigEvent(expectedSignal); if (not expectedEvent.empty()) sigEvent += "::" + expectedEvent; JAMI_INFO("[%s] is waiting for [%s] signal/event", callData.alias_.c_str(), sigEvent.c_str()); auto res = callData.cv_.wait_for(lock, TIME_OUT, [&] { // Search for the expected signal in list of received signals. bool pred = false; for (auto it = callData.signals_.begin(); it != callData.signals_.end(); it++) { // The predicate is true if the signal names match, and if the // expectedEvent is not empty, the events must also match. if (it->name_ == expectedSignal and (expectedEvent.empty() or it->event_ == expectedEvent)) { pred = true; // Done with this signal. callData.signals_.erase(it); break; } } return pred; }); if (not res) { JAMI_ERR("[%s] waiting for signal/event [%s] timed-out!", callData.alias_.c_str(), sigEvent.c_str()); JAMI_INFO("[%s] currently has the following signals:", callData.alias_.c_str()); for (auto const& sig : callData.signals_) { JAMI_INFO() << "\tSignal [" << sig.name_ << (sig.event_.empty() ? "" : ("::" + sig.event_)) << "]"; } } return res; } void MediaNegotiationTest::configureScenario() { // Configure Alice { CPPUNIT_ASSERT(not callDataMap_["ALICE"].accountId_.empty()); auto const& account = Manager::instance().getAccount<Account>( callDataMap_["ALICE"].accountId_); callDataMap_["ALICE"].userName_ = account->getAccountDetails()[ConfProperties::USERNAME]; callDataMap_["ALICE"].alias_ = account->getAccountDetails()[ConfProperties::ALIAS]; if (isSipAccount_) { auto sipAccount = std::dynamic_pointer_cast<SIPAccount>(account); CPPUNIT_ASSERT(sipAccount); sipAccount->setLocalPort(callDataMap_["ALICE"].listeningPort_); } } // Configure Bob { CPPUNIT_ASSERT(not callDataMap_["BOB"].accountId_.empty()); auto const& account = Manager::instance().getAccount<Account>( callDataMap_["BOB"].accountId_); callDataMap_["BOB"].userName_ = account->getAccountDetails()[ConfProperties::USERNAME]; callDataMap_["BOB"].alias_ = account->getAccountDetails()[ConfProperties::ALIAS]; if (isSipAccount_) { auto sipAccount = std::dynamic_pointer_cast<SIPAccount>(account); CPPUNIT_ASSERT(sipAccount); sipAccount->setLocalPort(callDataMap_["BOB"].listeningPort_); callDataMap_["BOB"].toUri_ = fmt::format("127.0.0.1:{}", callDataMap_["BOB"].listeningPort_); } } std::map<std::string, std::shared_ptr<libjami::CallbackWrapperBase>> signalHandlers; // Insert needed signal handlers. signalHandlers.insert(libjami::exportable_callback<libjami::CallSignal::IncomingCallWithMedia>( [&](const std::string& accountId, const std::string& callId, const std::string&, const std::vector<libjami::MediaMap> mediaList) { auto user = getUserAlias(accountId); if (not user.empty()) onIncomingCallWithMedia(accountId, callId, mediaList, callDataMap_[user]); })); signalHandlers.insert(libjami::exportable_callback<libjami::CallSignal::MediaChangeRequested>( [&](const std::string& accountId, const std::string& callId, const std::vector<libjami::MediaMap> mediaList) { auto user = getUserAlias(accountId); if (not user.empty()) onMediaChangeRequested(accountId, callId, mediaList, callDataMap_[user]); })); signalHandlers.insert( libjami::exportable_callback<libjami::CallSignal::StateChange>([&](const std::string& accountId, const std::string& callId, const std::string& state, signed) { auto user = getUserAlias(accountId); if (not user.empty()) onCallStateChange(accountId, callId, state, callDataMap_[user]); })); signalHandlers.insert(libjami::exportable_callback<libjami::CallSignal::VideoMuted>( [&](const std::string& callId, bool muted) { auto user = getUserAlias(getAccountId(callId)); if (not user.empty()) onVideoMuted(callId, muted, callDataMap_[user]); })); signalHandlers.insert(libjami::exportable_callback<libjami::CallSignal::MediaNegotiationStatus>( [&](const std::string& callId, const std::string& event, const std::vector<std::map<std::string, std::string>>&) { auto user = getUserAlias(getAccountId(callId)); if (not user.empty()) onMediaNegotiationStatus(callId, event, callDataMap_[user]); })); libjami::registerSignalHandlers(signalHandlers); } void MediaNegotiationTest::testWithScenario(CallData& aliceData, CallData& bobData, const TestScenario& scenario) { JAMI_INFO("=== Start a call and validate ==="); // The media count of the offer and answer must match (RFC-3264). auto mediaCount = scenario.offer_.size(); CPPUNIT_ASSERT_EQUAL(mediaCount, scenario.answer_.size()); aliceData.callId_ = libjami::placeCallWithMedia(aliceData.accountId_, isSipAccount_ ? bobData.toUri_ : callDataMap_["BOB"].userName_, MediaAttribute::mediaAttributesToMediaMaps( scenario.offer_)); CPPUNIT_ASSERT(not aliceData.callId_.empty()); auto aliceCall = std::static_pointer_cast<SIPCall>( Manager::instance().getCallFromCallID(aliceData.callId_)); CPPUNIT_ASSERT(aliceCall); aliceData.callId_ = aliceCall->getCallId(); JAMI_INFO("ALICE [%s] started a call with BOB [%s] and wait for answer", aliceData.accountId_.c_str(), bobData.accountId_.c_str()); // Wait for incoming call signal. CPPUNIT_ASSERT(waitForSignal(bobData, libjami::CallSignal::IncomingCallWithMedia::name)); // Answer the call. { auto const& mediaList = MediaAttribute::mediaAttributesToMediaMaps(scenario.answer_); libjami::acceptWithMedia(bobData.accountId_, bobData.callId_, mediaList); } // Wait for media negotiation complete signal. CPPUNIT_ASSERT_EQUAL( true, waitForSignal(bobData, libjami::CallSignal::MediaNegotiationStatus::name, libjami::Media::MediaNegotiationStatusEvents::NEGOTIATION_SUCCESS)); // Wait for the StateChange signal. CPPUNIT_ASSERT_EQUAL(true, waitForSignal(bobData, libjami::CallSignal::StateChange::name, StateEvent::CURRENT)); JAMI_INFO("BOB answered the call [%s]", bobData.callId_.c_str()); // Wait for media negotiation complete signal. CPPUNIT_ASSERT_EQUAL( true, waitForSignal(aliceData, libjami::CallSignal::MediaNegotiationStatus::name, libjami::Media::MediaNegotiationStatusEvents::NEGOTIATION_SUCCESS)); // Validate Alice's media { auto mediaList = aliceCall->getMediaAttributeList(); CPPUNIT_ASSERT_EQUAL(mediaCount, mediaList.size()); // Validate mute state CPPUNIT_ASSERT(validateMuteState(scenario.offer_, mediaList)); auto& sdp = aliceCall->getSDP(); // Validate local media direction auto descrList = sdp.getActiveMediaDescription(false); CPPUNIT_ASSERT_EQUAL(mediaCount, descrList.size()); // For Alice, local is the offer and remote is the answer. CPPUNIT_ASSERT(validateMediaDirection(descrList, scenario.offer_, scenario.answer_)); } // Validate Bob's media { auto const& bobCall = std::dynamic_pointer_cast<SIPCall>( Manager::instance().getCallFromCallID(bobData.callId_)); auto mediaList = bobCall->getMediaAttributeList(); CPPUNIT_ASSERT_EQUAL(mediaCount, mediaList.size()); // Validate mute state CPPUNIT_ASSERT(validateMuteState(scenario.answer_, mediaList)); auto& sdp = bobCall->getSDP(); // Validate local media direction auto descrList = sdp.getActiveMediaDescription(false); CPPUNIT_ASSERT_EQUAL(mediaCount, descrList.size()); // For Bob, local is the answer and remote is the offer. CPPUNIT_ASSERT(validateMediaDirection(descrList, scenario.answer_, scenario.offer_)); } std::this_thread::sleep_for(std::chrono::seconds(3)); JAMI_INFO("=== Request Media Change and validate ==="); { auto const& mediaList = MediaAttribute::mediaAttributesToMediaMaps(scenario.offerUpdate_); libjami::requestMediaChange(aliceData.accountId_, aliceData.callId_, mediaList); } // Update and validate media count. mediaCount = scenario.offerUpdate_.size(); CPPUNIT_ASSERT_EQUAL(mediaCount, scenario.answerUpdate_.size()); // Not all media change requests requires validation from client. if (scenario.expectMediaChangeRequest_) { // Wait for media change request signal. CPPUNIT_ASSERT_EQUAL(true, waitForSignal(bobData, libjami::CallSignal::MediaChangeRequested::name)); // Answer the change request. auto const& mediaList = MediaAttribute::mediaAttributesToMediaMaps(scenario.answerUpdate_); libjami::answerMediaChangeRequest(bobData.accountId_, bobData.callId_, mediaList); } if (scenario.expectMediaRenegotiation_) { // Wait for media negotiation complete signal. CPPUNIT_ASSERT_EQUAL( true, waitForSignal(aliceData, libjami::CallSignal::MediaNegotiationStatus::name, libjami::Media::MediaNegotiationStatusEvents::NEGOTIATION_SUCCESS)); // Validate Alice's media { auto mediaList = aliceCall->getMediaAttributeList(); CPPUNIT_ASSERT_EQUAL(mediaCount, mediaList.size()); // Validate mute state CPPUNIT_ASSERT(validateMuteState(scenario.offerUpdate_, mediaList)); auto& sdp = aliceCall->getSDP(); // Validate local media direction auto descrList = sdp.getActiveMediaDescription(false); CPPUNIT_ASSERT_EQUAL(mediaCount, descrList.size()); CPPUNIT_ASSERT( validateMediaDirection(descrList, scenario.offerUpdate_, scenario.answerUpdate_)); // Validate remote media direction descrList = sdp.getActiveMediaDescription(true); CPPUNIT_ASSERT_EQUAL(mediaCount, descrList.size()); CPPUNIT_ASSERT( validateMediaDirection(descrList, scenario.answerUpdate_, scenario.offerUpdate_)); } // Validate Bob's media { auto const& bobCall = std::dynamic_pointer_cast<SIPCall>( Manager::instance().getCallFromCallID(bobData.callId_)); auto mediaList = bobCall->getMediaAttributeList(); CPPUNIT_ASSERT_EQUAL(mediaCount, mediaList.size()); // Validate mute state CPPUNIT_ASSERT(validateMuteState(scenario.answerUpdate_, mediaList)); // NOTE: // It should be enough to validate media direction on Alice's side } } std::this_thread::sleep_for(std::chrono::seconds(3)); // Bob hang-up. JAMI_INFO("Hang up BOB's call and wait for ALICE to hang up"); libjami::hangUp(bobData.accountId_, bobData.callId_); CPPUNIT_ASSERT_EQUAL(true, waitForSignal(aliceData, libjami::CallSignal::StateChange::name, StateEvent::HUNGUP)); JAMI_INFO("Call terminated on both sides"); } void MediaNegotiationTest::audio_and_video_then_caller_mute_video() { JAMI_INFO("=== Begin test %s ===", __FUNCTION__); configureScenario(); MediaAttribute defaultAudio(MediaType::MEDIA_AUDIO); defaultAudio.label_ = "audio_0"; defaultAudio.enabled_ = true; MediaAttribute defaultVideo(MediaType::MEDIA_VIDEO); defaultVideo.label_ = "video_0"; defaultVideo.enabled_ = true; MediaAttribute audio(defaultAudio); MediaAttribute video(defaultVideo); TestScenario scenario; // First offer/answer scenario.offer_.emplace_back(audio); scenario.offer_.emplace_back(video); scenario.answer_.emplace_back(audio); scenario.answer_.emplace_back(video); // Updated offer/answer scenario.offerUpdate_.emplace_back(audio); video.muted_ = true; scenario.offerUpdate_.emplace_back(video); scenario.answerUpdate_.emplace_back(audio); video.muted_ = false; scenario.answerUpdate_.emplace_back(video); scenario.expectMediaRenegotiation_ = true; scenario.expectMediaChangeRequest_ = false; testWithScenario(callDataMap_["ALICE"], callDataMap_["BOB"], scenario); libjami::unregisterSignalHandlers(); JAMI_INFO("=== End test %s ===", __FUNCTION__); } void MediaNegotiationTest::audio_only_then_caller_add_video() { JAMI_INFO("=== Begin test %s ===", __FUNCTION__); configureScenario(); MediaAttribute defaultAudio(MediaType::MEDIA_AUDIO); defaultAudio.label_ = "audio_0"; defaultAudio.enabled_ = true; MediaAttribute defaultVideo(MediaType::MEDIA_VIDEO); defaultVideo.label_ = "video_0"; defaultVideo.enabled_ = true; MediaAttribute audio(defaultAudio); MediaAttribute video(defaultVideo); TestScenario scenario; // First offer/answer scenario.offer_.emplace_back(audio); scenario.answer_.emplace_back(audio); // Updated offer/answer scenario.offerUpdate_.emplace_back(audio); scenario.offerUpdate_.emplace_back(video); scenario.answerUpdate_.emplace_back(audio); video.muted_ = true; scenario.answerUpdate_.emplace_back(video); scenario.expectMediaRenegotiation_ = true; scenario.expectMediaChangeRequest_ = true; testWithScenario(callDataMap_["ALICE"], callDataMap_["BOB"], scenario); libjami::unregisterSignalHandlers(); JAMI_INFO("=== End test %s ===", __FUNCTION__); } void MediaNegotiationTest::audio_and_video_then_caller_mute_audio() { JAMI_INFO("=== Begin test %s ===", __FUNCTION__); configureScenario(); MediaAttribute defaultAudio(MediaType::MEDIA_AUDIO); defaultAudio.label_ = "audio_0"; defaultAudio.enabled_ = true; MediaAttribute defaultVideo(MediaType::MEDIA_VIDEO); defaultVideo.label_ = "video_0"; defaultVideo.enabled_ = true; MediaAttribute audio(defaultAudio); MediaAttribute video(defaultVideo); TestScenario scenario; // First offer/answer scenario.offer_.emplace_back(audio); scenario.offer_.emplace_back(video); scenario.answer_.emplace_back(audio); scenario.answer_.emplace_back(video); // Updated offer/answer audio.muted_ = true; scenario.offerUpdate_.emplace_back(audio); scenario.offerUpdate_.emplace_back(video); audio.muted_ = false; scenario.answerUpdate_.emplace_back(audio); scenario.answerUpdate_.emplace_back(video); scenario.expectMediaRenegotiation_ = false; scenario.expectMediaChangeRequest_ = false; testWithScenario(callDataMap_["ALICE"], callDataMap_["BOB"], scenario); libjami::unregisterSignalHandlers(); JAMI_INFO("=== End test %s ===", __FUNCTION__); } void MediaNegotiationTest::audio_and_video_answer_muted_video_then_mute_video() { JAMI_INFO("=== Begin test %s ===", __FUNCTION__); configureScenario(); MediaAttribute defaultAudio(MediaType::MEDIA_AUDIO); defaultAudio.label_ = "audio_0"; defaultAudio.enabled_ = true; MediaAttribute defaultVideo(MediaType::MEDIA_VIDEO); defaultVideo.label_ = "video_0"; defaultVideo.enabled_ = true; MediaAttribute audio(defaultAudio); MediaAttribute video(defaultVideo); TestScenario scenario; // First offer/answer scenario.offer_.emplace_back(audio); scenario.offer_.emplace_back(video); video.muted_ = true; scenario.answer_.emplace_back(audio); scenario.answer_.emplace_back(video); // Updated offer/answer video.muted_ = true; scenario.offerUpdate_.emplace_back(audio); scenario.offerUpdate_.emplace_back(video); video.muted_ = true; scenario.answerUpdate_.emplace_back(audio); scenario.answerUpdate_.emplace_back(video); scenario.expectMediaChangeRequest_ = false; scenario.expectMediaRenegotiation_ = true; testWithScenario(callDataMap_["ALICE"], callDataMap_["BOB"], scenario); libjami::unregisterSignalHandlers(); JAMI_INFO("=== End test %s ===", __FUNCTION__); } void MediaNegotiationTest::audio_and_video_then_change_video_source() { JAMI_INFO("=== Begin test %s ===", __FUNCTION__); configureScenario(); MediaAttribute defaultAudio(MediaType::MEDIA_AUDIO); defaultAudio.label_ = "audio_0"; defaultAudio.enabled_ = true; MediaAttribute defaultVideo(MediaType::MEDIA_VIDEO); defaultVideo.label_ = "video_0"; defaultVideo.enabled_ = true; MediaAttribute audio(defaultAudio); MediaAttribute video(defaultVideo); TestScenario scenario; // First offer/answer scenario.offer_.emplace_back(audio); scenario.offer_.emplace_back(video); scenario.answer_.emplace_back(audio); scenario.answer_.emplace_back(video); // Updated offer/answer scenario.offerUpdate_.emplace_back(audio); // Just change the media source to validate that a new // media negotiation (re-invite) will be triggered. video.sourceUri_ = "Fake source"; scenario.offerUpdate_.emplace_back(video); scenario.answerUpdate_.emplace_back(audio); scenario.answerUpdate_.emplace_back(video); scenario.expectMediaRenegotiation_ = true; scenario.expectMediaChangeRequest_ = false; testWithScenario(callDataMap_["ALICE"], callDataMap_["BOB"], scenario); libjami::unregisterSignalHandlers(); JAMI_INFO("=== End test %s ===", __FUNCTION__); } void MediaNegotiationTest::negotiate_2_videos_1_audio() { JAMI_INFO("=== Begin test %s ===", __FUNCTION__); configureScenario(); MediaAttribute defaultAudio(MediaType::MEDIA_AUDIO); defaultAudio.label_ = "audio_0"; defaultAudio.enabled_ = true; MediaAttribute defaultVideo(MediaType::MEDIA_VIDEO); defaultVideo.label_ = "video_0"; defaultVideo.sourceUri_ = "foo"; defaultVideo.enabled_ = true; MediaAttribute defaultVideo2(MediaType::MEDIA_VIDEO); defaultVideo2.label_ = "video_1"; defaultVideo2.sourceUri_ = "bar"; defaultVideo2.enabled_ = true; MediaAttribute audio(defaultAudio); MediaAttribute video(defaultVideo); MediaAttribute video2(defaultVideo2); TestScenario scenario; // First offer/answer scenario.offer_.emplace_back(audio); scenario.offer_.emplace_back(video); scenario.answer_.emplace_back(audio); scenario.answer_.emplace_back(video); // Update offer/answer with 2 videos scenario.offerUpdate_.emplace_back(audio); scenario.offerUpdate_.emplace_back(video); scenario.offerUpdate_.emplace_back(video2); scenario.answerUpdate_.emplace_back(audio); scenario.answerUpdate_.emplace_back(video); scenario.answerUpdate_.emplace_back(video2); scenario.expectMediaRenegotiation_ = true; scenario.expectMediaChangeRequest_ = true; testWithScenario(callDataMap_["ALICE"], callDataMap_["BOB"], scenario); libjami::unregisterSignalHandlers(); JAMI_INFO("=== End test %s ===", __FUNCTION__); } CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(MediaNegotiationTestJami, MediaNegotiationTestJami::name()); CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(MediaNegotiationTestSip, MediaNegotiationTestSip::name()); } // namespace test } // namespace jami JAMI_TEST_RUNNER(jami::test::MediaNegotiationTestJami::name())
43,376
C++
.cpp
984
35.172764
106
0.638909
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,696
auto_answer.cpp
savoirfairelinux_jami-daemon/test/unitTest/media_negotiation/auto_answer.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "../../test_runner.h" #include "manager.h" #include "account.h" #include "sip/sipaccount.h" #include "jami.h" #include "jami/media_const.h" #include "call_const.h" #include "account_const.h" #include "sip/sipcall.h" #include "sip/sdp.h" #include "common.h" #include <dhtnet/connectionmanager.h> #include <cppunit/TestAssert.h> #include <cppunit/TestFixture.h> #include <cppunit/extensions/HelperMacros.h> #include <condition_variable> #include <string> using namespace libjami::Account; using namespace libjami::Call; namespace jami { namespace test { struct TestScenario { TestScenario(const std::vector<MediaAttribute>& offer, const std::vector<MediaAttribute>& answer, const std::vector<MediaAttribute>& offerUpdate, const std::vector<MediaAttribute>& answerUpdate) : offer_(std::move(offer)) , answer_(std::move(answer)) , offerUpdate_(std::move(offerUpdate)) , answerUpdate_(std::move(answerUpdate)) {} TestScenario() {}; std::vector<MediaAttribute> offer_; std::vector<MediaAttribute> answer_; std::vector<MediaAttribute> offerUpdate_; std::vector<MediaAttribute> answerUpdate_; // Determine if we should expect the MediaNegotiationStatus signal. bool expectMediaRenegotiation_ {false}; }; struct CallData { struct Signal { Signal(const std::string& name, const std::string& event = {}) : name_(std::move(name)) , event_(std::move(event)) {}; std::string name_ {}; std::string event_ {}; }; std::string accountId_ {}; std::string userName_ {}; std::string alias_ {}; std::string callId_ {}; uint16_t listeningPort_ {0}; std::string toUri_ {}; std::vector<Signal> signals_; std::condition_variable cv_ {}; std::mutex mtx_; }; class AutoAnswerMediaNegoTest { public: AutoAnswerMediaNegoTest() { // Init daemon libjami::init(libjami::InitFlag(libjami::LIBJAMI_FLAG_DEBUG | libjami::LIBJAMI_FLAG_CONSOLE_LOG)); if (not Manager::instance().initialized) CPPUNIT_ASSERT(libjami::start("jami-sample.yml")); } ~AutoAnswerMediaNegoTest() { libjami::fini(); } protected: // Test cases. void audio_and_video_then_caller_mute_video(); void audio_only_then_caller_add_video(); void audio_and_video_then_caller_mute_audio(); void audio_and_video_then_change_video_source(); // Event/Signal handlers static void onCallStateChange(const std::string& accountId, const std::string& callId, const std::string& state, CallData& callData); static void onIncomingCallWithMedia(const std::string& accountId, const std::string& callId, const std::vector<libjami::MediaMap> mediaList, CallData& callData); static void onMediaChangeRequested(const std::string& accountId, const std::string& callId, const std::vector<libjami::MediaMap> mediaList, CallData& callData); static void onVideoMuted(const std::string& callId, bool muted, CallData& callData); static void onMediaNegotiationStatus(const std::string& callId, const std::string& event, CallData& callData); // Helpers void configureScenario(); void testWithScenario(CallData& aliceData, CallData& bobData, const TestScenario& scenario); static std::string getUserAlias(const std::string& callId); // Infer media direction of an offer. static uint8_t directionToBitset(MediaDirection direction, bool isLocal); static MediaDirection bitsetToDirection(uint8_t val); static MediaDirection inferInitialDirection(const MediaAttribute& offer); // Infer media direction of an answer. static MediaDirection inferNegotiatedDirection(MediaDirection local, MediaDirection answer); // Wait for a signal from the callbacks. Some signals also report the event that // triggered the signal like the StateChange signal. static bool validateMuteState(std::vector<MediaAttribute> expected, std::vector<MediaAttribute> actual); static bool validateMediaDirection(std::vector<MediaDescription> descrList, std::vector<MediaAttribute> listInOffer, std::vector<MediaAttribute> listInAnswer); static bool waitForSignal(CallData& callData, const std::string& signal, const std::string& expectedEvent = {}); bool isSipAccount_ {false}; CallData aliceData_; CallData bobData_; }; class AutoAnswerMediaNegoTestSip : public AutoAnswerMediaNegoTest, public CppUnit::TestFixture { public: AutoAnswerMediaNegoTestSip() { isSipAccount_ = true; }; ~AutoAnswerMediaNegoTestSip() {}; static std::string name() { return "AutoAnswerMediaNegoTestSip"; } void setUp() override; void tearDown() override; private: CPPUNIT_TEST_SUITE(AutoAnswerMediaNegoTestSip); CPPUNIT_TEST(audio_and_video_then_caller_mute_video); CPPUNIT_TEST(audio_only_then_caller_add_video); CPPUNIT_TEST(audio_and_video_then_caller_mute_audio); CPPUNIT_TEST(audio_and_video_then_change_video_source); CPPUNIT_TEST_SUITE_END(); }; void AutoAnswerMediaNegoTestSip::setUp() { aliceData_.listeningPort_ = 5080; std::map<std::string, std::string> details = libjami::getAccountTemplate("SIP"); details[ConfProperties::TYPE] = "SIP"; details[ConfProperties::DISPLAYNAME] = "ALICE"; details[ConfProperties::ALIAS] = "ALICE"; details[ConfProperties::LOCAL_PORT] = std::to_string(aliceData_.listeningPort_); details[ConfProperties::UPNP_ENABLED] = "false"; aliceData_.accountId_ = Manager::instance().addAccount(details); bobData_.listeningPort_ = 5082; details = libjami::getAccountTemplate("SIP"); details[ConfProperties::TYPE] = "SIP"; details[ConfProperties::DISPLAYNAME] = "BOB"; details[ConfProperties::ALIAS] = "BOB"; details[ConfProperties::AUTOANSWER] = "true"; details[ConfProperties::LOCAL_PORT] = std::to_string(bobData_.listeningPort_); details[ConfProperties::UPNP_ENABLED] = "false"; bobData_.accountId_ = Manager::instance().addAccount(details); JAMI_INFO("Initialize accounts ..."); auto aliceAccount = Manager::instance().getAccount<Account>(aliceData_.accountId_); auto bobAccount = Manager::instance().getAccount<Account>(bobData_.accountId_); } void AutoAnswerMediaNegoTestSip::tearDown() { JAMI_INFO("Remove created accounts..."); std::map<std::string, std::shared_ptr<libjami::CallbackWrapperBase>> confHandlers; std::mutex mtx; std::unique_lock lk {mtx}; std::condition_variable cv; auto currentAccSize = Manager::instance().getAccountList().size(); std::atomic_bool accountsRemoved {false}; confHandlers.insert( libjami::exportable_callback<libjami::ConfigurationSignal::AccountsChanged>([&]() { if (Manager::instance().getAccountList().size() <= currentAccSize - 2) { accountsRemoved = true; cv.notify_one(); } })); libjami::registerSignalHandlers(confHandlers); Manager::instance().removeAccount(aliceData_.accountId_, true); Manager::instance().removeAccount(bobData_.accountId_, true); CPPUNIT_ASSERT( cv.wait_for(lk, std::chrono::seconds(30), [&] { return accountsRemoved.load(); })); libjami::unregisterSignalHandlers(); } class AutoAnswerMediaNegoTestJami : public AutoAnswerMediaNegoTest, public CppUnit::TestFixture { public: AutoAnswerMediaNegoTestJami() { isSipAccount_ = false; }; ~AutoAnswerMediaNegoTestJami() {}; static std::string name() { return "AutoAnswerMediaNegoTestJami"; } void setUp() override; void tearDown() override; private: CPPUNIT_TEST_SUITE(AutoAnswerMediaNegoTestJami); CPPUNIT_TEST(audio_and_video_then_caller_mute_video); CPPUNIT_TEST(audio_only_then_caller_add_video); CPPUNIT_TEST(audio_and_video_then_caller_mute_audio); CPPUNIT_TEST(audio_and_video_then_change_video_source); CPPUNIT_TEST_SUITE_END(); }; void AutoAnswerMediaNegoTestJami::setUp() { auto actors = load_actors("actors/alice-bob-no-upnp.yml"); aliceData_.accountId_ = actors["alice"]; bobData_.accountId_ = actors["bob"]; JAMI_INFO("Initialize account..."); auto aliceAccount = Manager::instance().getAccount<Account>(aliceData_.accountId_); auto bobAccount = Manager::instance().getAccount<Account>(bobData_.accountId_); auto details = bobAccount->getAccountDetails(); details[ConfProperties::AUTOANSWER] = "true"; bobAccount->setAccountDetails(details); wait_for_announcement_of({aliceAccount->getAccountID(), bobAccount->getAccountID()}); } void AutoAnswerMediaNegoTestJami::tearDown() { wait_for_removal_of({aliceData_.accountId_, bobData_.accountId_}); } std::string AutoAnswerMediaNegoTest::getUserAlias(const std::string& callId) { auto call = Manager::instance().getCallFromCallID(callId); if (not call) { JAMI_WARN("Call with ID [%s] does not exist anymore!", callId.c_str()); return {}; } auto const& account = call->getAccount().lock(); if (not account) { return {}; } return account->getAccountDetails()[ConfProperties::ALIAS]; } MediaDirection AutoAnswerMediaNegoTest::inferInitialDirection(const MediaAttribute& mediaAttr) { if (not mediaAttr.enabled_) return MediaDirection::INACTIVE; if (mediaAttr.muted_) { if (mediaAttr.onHold_) return MediaDirection::INACTIVE; return MediaDirection::RECVONLY; } if (mediaAttr.onHold_) return MediaDirection::SENDONLY; return MediaDirection::SENDRECV; } uint8_t AutoAnswerMediaNegoTest::directionToBitset(MediaDirection direction, bool isLocal) { if (direction == MediaDirection::SENDRECV) return 3; if (direction == MediaDirection::RECVONLY) return isLocal ? 2 : 1; if (direction == MediaDirection::SENDONLY) return isLocal ? 1 : 2; return 0; } MediaDirection AutoAnswerMediaNegoTest::bitsetToDirection(uint8_t val) { if (val == 3) return MediaDirection::SENDRECV; if (val == 2) return MediaDirection::RECVONLY; if (val == 1) return MediaDirection::SENDONLY; return MediaDirection::INACTIVE; } MediaDirection AutoAnswerMediaNegoTest::inferNegotiatedDirection(MediaDirection local, MediaDirection remote) { uint8_t val = directionToBitset(local, true) & directionToBitset(remote, false); auto dir = bitsetToDirection(val); return dir; } bool AutoAnswerMediaNegoTest::validateMuteState(std::vector<MediaAttribute> expected, std::vector<MediaAttribute> actual) { CPPUNIT_ASSERT_EQUAL(expected.size(), actual.size()); for (size_t idx = 0; idx < expected.size(); idx++) { if (expected[idx].muted_ != actual[idx].muted_) return false; } return true; } bool AutoAnswerMediaNegoTest::validateMediaDirection(std::vector<MediaDescription> descrList, std::vector<MediaAttribute> localMediaList, std::vector<MediaAttribute> remoteMediaList) { CPPUNIT_ASSERT_EQUAL(descrList.size(), localMediaList.size()); CPPUNIT_ASSERT_EQUAL(descrList.size(), remoteMediaList.size()); for (size_t idx = 0; idx < descrList.size(); idx++) { auto local = inferInitialDirection(localMediaList[idx]); auto remote = inferInitialDirection(remoteMediaList[idx]); auto negotiated = inferNegotiatedDirection(local, remote); if (descrList[idx].direction_ != negotiated) { JAMI_WARN("Media [%lu] direction mismatch: expected %i - found %i", idx, static_cast<int>(negotiated), static_cast<int>(descrList[idx].direction_)); return false; } } return true; } void AutoAnswerMediaNegoTest::onIncomingCallWithMedia(const std::string& accountId, const std::string& callId, const std::vector<libjami::MediaMap> mediaList, CallData& callData) { CPPUNIT_ASSERT_EQUAL(callData.accountId_, accountId); JAMI_INFO("Signal [%s] - user [%s] - call [%s] - media count [%lu]", libjami::CallSignal::IncomingCallWithMedia::name, callData.alias_.c_str(), callId.c_str(), mediaList.size()); if (not Manager::instance().getCallFromCallID(callId)) { JAMI_WARN("Call with ID [%s] does not exist!", callId.c_str()); callData.callId_ = {}; return; } std::unique_lock lock {callData.mtx_}; callData.callId_ = callId; callData.signals_.emplace_back(CallData::Signal(libjami::CallSignal::IncomingCallWithMedia::name)); callData.cv_.notify_one(); } void AutoAnswerMediaNegoTest::onMediaChangeRequested(const std::string& accountId, const std::string& callId, const std::vector<libjami::MediaMap> mediaList, CallData& callData) { CPPUNIT_ASSERT_EQUAL(callData.accountId_, accountId); JAMI_INFO("Signal [%s] - user [%s] - call [%s] - media count [%lu]", libjami::CallSignal::MediaChangeRequested::name, callData.alias_.c_str(), callId.c_str(), mediaList.size()); if (not Manager::instance().getCallFromCallID(callId)) { JAMI_WARN("Call with ID [%s] does not exist!", callId.c_str()); callData.callId_ = {}; return; } std::unique_lock lock {callData.mtx_}; callData.callId_ = callId; callData.signals_.emplace_back(CallData::Signal(libjami::CallSignal::MediaChangeRequested::name)); callData.cv_.notify_one(); } void AutoAnswerMediaNegoTest::onCallStateChange(const std::string& accountId UNUSED, const std::string& callId, const std::string& state, CallData& callData) { // TODO. rewrite me using accountId. auto call = Manager::instance().getCallFromCallID(callId); if (not call) { JAMI_WARN("Call with ID [%s] does not exist anymore!", callId.c_str()); return; } auto account = call->getAccount().lock(); if (not account) { JAMI_WARN("Account owning the call [%s] does not exist!", callId.c_str()); return; } JAMI_INFO("Signal [%s] - user [%s] - call [%s] - state [%s]", libjami::CallSignal::StateChange::name, callData.alias_.c_str(), callId.c_str(), state.c_str()); if (account->getAccountID() != callData.accountId_) return; { std::unique_lock lock {callData.mtx_}; callData.signals_.emplace_back( CallData::Signal(libjami::CallSignal::StateChange::name, state)); } if (state == "CURRENT" or state == "OVER" or state == "HUNGUP") { callData.cv_.notify_one(); } } void AutoAnswerMediaNegoTest::onVideoMuted(const std::string& callId, bool muted, CallData& callData) { auto call = Manager::instance().getCallFromCallID(callId); if (not call) { JAMI_WARN("Call with ID [%s] does not exist anymore!", callId.c_str()); return; } auto account = call->getAccount().lock(); if (not account) { JAMI_WARN("Account owning the call [%s] does not exist!", callId.c_str()); return; } JAMI_INFO("Signal [%s] - user [%s] - call [%s] - state [%s]", libjami::CallSignal::VideoMuted::name, account->getAccountDetails()[ConfProperties::ALIAS].c_str(), call->getCallId().c_str(), muted ? "Mute" : "Un-mute"); if (account->getAccountID() != callData.accountId_) return; { std::unique_lock lock {callData.mtx_}; callData.signals_.emplace_back( CallData::Signal(libjami::CallSignal::VideoMuted::name, muted ? "muted" : "un-muted")); } callData.cv_.notify_one(); } void AutoAnswerMediaNegoTest::onMediaNegotiationStatus(const std::string& callId, const std::string& event, CallData& callData) { auto call = Manager::instance().getCallFromCallID(callId); if (not call) { JAMI_WARN("Call with ID [%s] does not exist!", callId.c_str()); return; } auto account = call->getAccount().lock(); if (not account) { JAMI_WARN("Account owning the call [%s] does not exist!", callId.c_str()); return; } JAMI_INFO("Signal [%s] - user [%s] - call [%s] - state [%s]", libjami::CallSignal::MediaNegotiationStatus::name, account->getAccountDetails()[ConfProperties::ALIAS].c_str(), call->getCallId().c_str(), event.c_str()); if (account->getAccountID() != callData.accountId_) return; { std::unique_lock lock {callData.mtx_}; callData.signals_.emplace_back( CallData::Signal(libjami::CallSignal::MediaNegotiationStatus::name, event)); } callData.cv_.notify_one(); } bool AutoAnswerMediaNegoTest::waitForSignal(CallData& callData, const std::string& expectedSignal, const std::string& expectedEvent) { const std::chrono::seconds TIME_OUT {15}; std::unique_lock lock {callData.mtx_}; // Combined signal + event (if any). std::string sigEvent(expectedSignal); if (not expectedEvent.empty()) sigEvent += "::" + expectedEvent; JAMI_INFO("[%s] is waiting for [%s] signal/event", callData.alias_.c_str(), sigEvent.c_str()); auto res = callData.cv_.wait_for(lock, TIME_OUT, [&] { // Search for the expected signal in list of received signals. bool pred = false; for (auto it = callData.signals_.begin(); it != callData.signals_.end(); it++) { // The predicate is true if the signal names match, and if the // expectedEvent is not empty, the events must also match. if (it->name_ == expectedSignal and (expectedEvent.empty() or it->event_ == expectedEvent)) { pred = true; // Done with this signal. callData.signals_.erase(it); break; } } return pred; }); if (not res) { JAMI_ERR("[%s] waiting for signal/event [%s] timed-out!", callData.alias_.c_str(), sigEvent.c_str()); JAMI_INFO("[%s] currently has the following signals:", callData.alias_.c_str()); for (auto const& sig : callData.signals_) { JAMI_INFO() << "Signal [" << sig.name_ << (sig.event_.empty() ? "" : ("::" + sig.event_)) << "]"; } } return res; } void AutoAnswerMediaNegoTest::configureScenario() { // Configure Alice { CPPUNIT_ASSERT(not aliceData_.accountId_.empty()); auto const& account = Manager::instance().getAccount<Account>(aliceData_.accountId_); aliceData_.userName_ = account->getAccountDetails()[ConfProperties::USERNAME]; aliceData_.alias_ = account->getAccountDetails()[ConfProperties::ALIAS]; if (isSipAccount_) { auto sipAccount = std::dynamic_pointer_cast<SIPAccount>(account); CPPUNIT_ASSERT(sipAccount); sipAccount->setLocalPort(aliceData_.listeningPort_); } } // Configure Bob { CPPUNIT_ASSERT(not bobData_.accountId_.empty()); auto const& account = Manager::instance().getAccount<Account>(bobData_.accountId_); bobData_.userName_ = account->getAccountDetails()[ConfProperties::USERNAME]; bobData_.alias_ = account->getAccountDetails()[ConfProperties::ALIAS]; CPPUNIT_ASSERT(account->isAutoAnswerEnabled()); if (isSipAccount_) { auto sipAccount = std::dynamic_pointer_cast<SIPAccount>(account); CPPUNIT_ASSERT(sipAccount); sipAccount->setLocalPort(bobData_.listeningPort_); bobData_.toUri_ = "127.0.0.1:" + std::to_string(bobData_.listeningPort_); } } std::map<std::string, std::shared_ptr<libjami::CallbackWrapperBase>> signalHandlers; // Insert needed signal handlers. signalHandlers.insert(libjami::exportable_callback<libjami::CallSignal::IncomingCallWithMedia>( [&](const std::string& accountId, const std::string& callId, const std::string&, const std::vector<libjami::MediaMap> mediaList) { auto user = getUserAlias(callId); if (not user.empty()) onIncomingCallWithMedia(accountId, callId, mediaList, user == aliceData_.alias_ ? aliceData_ : bobData_); })); signalHandlers.insert(libjami::exportable_callback<libjami::CallSignal::MediaChangeRequested>( [&](const std::string& accountId, const std::string& callId, const std::vector<libjami::MediaMap> mediaList) { auto user = getUserAlias(callId); if (not user.empty()) onMediaChangeRequested(accountId, callId, mediaList, user == aliceData_.alias_ ? aliceData_ : bobData_); })); signalHandlers.insert( libjami::exportable_callback<libjami::CallSignal::StateChange>([&](const std::string& accountId, const std::string& callId, const std::string& state, signed) { auto user = getUserAlias(callId); if (not user.empty()) onCallStateChange(accountId, callId, state, user == aliceData_.alias_ ? aliceData_ : bobData_); })); signalHandlers.insert(libjami::exportable_callback<libjami::CallSignal::VideoMuted>( [&](const std::string& callId, bool muted) { auto user = getUserAlias(callId); if (not user.empty()) onVideoMuted(callId, muted, user == aliceData_.alias_ ? aliceData_ : bobData_); })); signalHandlers.insert(libjami::exportable_callback<libjami::CallSignal::MediaNegotiationStatus>( [&](const std::string& callId, const std::string& event, const std::vector<std::map<std::string, std::string>>&) { auto user = getUserAlias(callId); if (not user.empty()) onMediaNegotiationStatus(callId, event, user == aliceData_.alias_ ? aliceData_ : bobData_); })); libjami::registerSignalHandlers(signalHandlers); } void AutoAnswerMediaNegoTest::testWithScenario(CallData& aliceData, CallData& bobData, const TestScenario& scenario) { JAMI_INFO("=== Start a call and validate ==="); // The media count of the offer and answer must match (RFC-3264). auto mediaCount = scenario.offer_.size(); CPPUNIT_ASSERT_EQUAL(mediaCount, scenario.answer_.size()); aliceData.callId_ = libjami::placeCallWithMedia(aliceData.accountId_, isSipAccount_ ? bobData.toUri_ : bobData_.userName_, MediaAttribute::mediaAttributesToMediaMaps( scenario.offer_)); CPPUNIT_ASSERT(not aliceData.callId_.empty()); auto aliceCall = std::static_pointer_cast<SIPCall>( Manager::instance().getCallFromCallID(aliceData.callId_)); CPPUNIT_ASSERT(aliceCall); JAMI_INFO("ALICE [%s] started a call with BOB [%s] and wait for answer", aliceData.accountId_.c_str(), bobData.accountId_.c_str()); // Wait for incoming call signal. CPPUNIT_ASSERT(waitForSignal(bobData, libjami::CallSignal::IncomingCallWithMedia::name)); // Bob automatically answers the call. // Wait for media negotiation complete signal. CPPUNIT_ASSERT_EQUAL( true, waitForSignal(bobData, libjami::CallSignal::MediaNegotiationStatus::name, libjami::Media::MediaNegotiationStatusEvents::NEGOTIATION_SUCCESS)); // Wait for the StateChange signal. CPPUNIT_ASSERT_EQUAL(true, waitForSignal(bobData, libjami::CallSignal::StateChange::name, StateEvent::CURRENT)); JAMI_INFO("BOB answered the call [%s]", bobData.callId_.c_str()); // Wait for media negotiation complete signal. CPPUNIT_ASSERT_EQUAL( true, waitForSignal(aliceData, libjami::CallSignal::MediaNegotiationStatus::name, libjami::Media::MediaNegotiationStatusEvents::NEGOTIATION_SUCCESS)); // Validate Alice's media { auto mediaList = aliceCall->getMediaAttributeList(); CPPUNIT_ASSERT_EQUAL(mediaCount, mediaList.size()); // Validate mute state CPPUNIT_ASSERT(validateMuteState(scenario.offer_, mediaList)); auto& sdp = aliceCall->getSDP(); // Validate local media direction { auto descrList = sdp.getActiveMediaDescription(false); CPPUNIT_ASSERT_EQUAL(mediaCount, descrList.size()); // For Alice, local is the offer and remote is the answer. CPPUNIT_ASSERT(validateMediaDirection(descrList, scenario.offer_, scenario.answer_)); } } // Validate Bob's media { auto const& bobCall = std::dynamic_pointer_cast<SIPCall>( Manager::instance().getCallFromCallID(bobData.callId_)); auto mediaList = bobCall->getMediaAttributeList(); CPPUNIT_ASSERT_EQUAL(mediaCount, mediaList.size()); // Validate mute state CPPUNIT_ASSERT(validateMuteState(scenario.answer_, mediaList)); auto& sdp = bobCall->getSDP(); // Validate local media direction { auto descrList = sdp.getActiveMediaDescription(false); CPPUNIT_ASSERT_EQUAL(mediaCount, descrList.size()); // For Bob, local is the answer and remote is the offer. CPPUNIT_ASSERT(validateMediaDirection(descrList, scenario.answer_, scenario.offer_)); } } std::this_thread::sleep_for(std::chrono::seconds(3)); JAMI_INFO("=== Request Media Change and validate ==="); { auto const& mediaList = MediaAttribute::mediaAttributesToMediaMaps(scenario.offerUpdate_); libjami::requestMediaChange(aliceData.accountId_, aliceData.callId_, mediaList); } // Update and validate media count. mediaCount = scenario.offerUpdate_.size(); CPPUNIT_ASSERT_EQUAL(mediaCount, scenario.answerUpdate_.size()); if (scenario.expectMediaRenegotiation_) { // Wait for media negotiation complete signal. CPPUNIT_ASSERT_EQUAL( true, waitForSignal(aliceData, libjami::CallSignal::MediaNegotiationStatus::name, libjami::Media::MediaNegotiationStatusEvents::NEGOTIATION_SUCCESS)); // Validate Alice's media { auto mediaList = aliceCall->getMediaAttributeList(); CPPUNIT_ASSERT_EQUAL(mediaCount, mediaList.size()); // Validate mute state CPPUNIT_ASSERT(validateMuteState(scenario.offerUpdate_, mediaList)); auto& sdp = aliceCall->getSDP(); // Validate local media direction { auto descrList = sdp.getActiveMediaDescription(false); CPPUNIT_ASSERT_EQUAL(mediaCount, descrList.size()); CPPUNIT_ASSERT(validateMediaDirection(descrList, scenario.offerUpdate_, scenario.answerUpdate_)); } // Validate remote media direction { auto descrList = sdp.getActiveMediaDescription(true); CPPUNIT_ASSERT_EQUAL(mediaCount, descrList.size()); CPPUNIT_ASSERT(validateMediaDirection(descrList, scenario.answerUpdate_, scenario.offerUpdate_)); } } // Validate Bob's media { auto const& bobCall = std::dynamic_pointer_cast<SIPCall>( Manager::instance().getCallFromCallID(bobData.callId_)); auto mediaList = bobCall->getMediaAttributeList(); CPPUNIT_ASSERT_EQUAL(mediaCount, mediaList.size()); // Validate mute state CPPUNIT_ASSERT(validateMuteState(scenario.answerUpdate_, mediaList)); // NOTE: // It should be enough to validate media direction on Alice's side } } std::this_thread::sleep_for(std::chrono::seconds(3)); // Bob hang-up. JAMI_INFO("Hang up BOB's call and wait for ALICE to hang up"); libjami::hangUp(bobData.accountId_, bobData.callId_); CPPUNIT_ASSERT_EQUAL(true, waitForSignal(aliceData, libjami::CallSignal::StateChange::name, StateEvent::HUNGUP)); JAMI_INFO("Call terminated on both sides"); } void AutoAnswerMediaNegoTest::audio_and_video_then_caller_mute_video() { JAMI_INFO("=== Begin test %s ===", __FUNCTION__); configureScenario(); MediaAttribute defaultAudio(MediaType::MEDIA_AUDIO); defaultAudio.label_ = "audio_0"; defaultAudio.enabled_ = true; MediaAttribute defaultVideo(MediaType::MEDIA_VIDEO); defaultVideo.label_ = "video_0"; defaultVideo.enabled_ = true; MediaAttribute audio(defaultAudio); MediaAttribute video(defaultVideo); TestScenario scenario; // First offer/answer scenario.offer_.emplace_back(audio); scenario.offer_.emplace_back(video); scenario.answer_.emplace_back(audio); scenario.answer_.emplace_back(video); // Updated offer/answer scenario.offerUpdate_.emplace_back(audio); video.muted_ = true; scenario.offerUpdate_.emplace_back(video); scenario.answerUpdate_.emplace_back(audio); video.muted_ = false; scenario.answerUpdate_.emplace_back(video); scenario.expectMediaRenegotiation_ = true; testWithScenario(aliceData_, bobData_, scenario); libjami::unregisterSignalHandlers(); JAMI_INFO("=== End test %s ===", __FUNCTION__); } void AutoAnswerMediaNegoTest::audio_only_then_caller_add_video() { JAMI_INFO("=== Begin test %s ===", __FUNCTION__); configureScenario(); MediaAttribute defaultAudio(MediaType::MEDIA_AUDIO); defaultAudio.label_ = "audio_0"; defaultAudio.enabled_ = true; MediaAttribute defaultVideo(MediaType::MEDIA_VIDEO); defaultVideo.label_ = "video_0"; defaultVideo.enabled_ = true; MediaAttribute audio(defaultAudio); MediaAttribute video(defaultVideo); TestScenario scenario; // First offer/answer scenario.offer_.emplace_back(audio); scenario.answer_.emplace_back(audio); // Updated offer/answer scenario.offerUpdate_.emplace_back(audio); scenario.offerUpdate_.emplace_back(video); scenario.answerUpdate_.emplace_back(audio); scenario.answerUpdate_.emplace_back(video); testWithScenario(aliceData_, bobData_, scenario); libjami::unregisterSignalHandlers(); JAMI_INFO("=== End test %s ===", __FUNCTION__); } void AutoAnswerMediaNegoTest::audio_and_video_then_caller_mute_audio() { JAMI_INFO("=== Begin test %s ===", __FUNCTION__); configureScenario(); MediaAttribute defaultAudio(MediaType::MEDIA_AUDIO); defaultAudio.label_ = "audio_0"; defaultAudio.enabled_ = true; MediaAttribute defaultVideo(MediaType::MEDIA_VIDEO); defaultVideo.label_ = "video_0"; defaultVideo.enabled_ = true; MediaAttribute audio(defaultAudio); MediaAttribute video(defaultVideo); TestScenario scenario; // First offer/answer scenario.offer_.emplace_back(audio); scenario.offer_.emplace_back(video); scenario.answer_.emplace_back(audio); scenario.answer_.emplace_back(video); // Updated offer/answer audio.muted_ = true; scenario.offerUpdate_.emplace_back(audio); scenario.offerUpdate_.emplace_back(video); audio.muted_ = false; scenario.answerUpdate_.emplace_back(audio); scenario.answerUpdate_.emplace_back(video); scenario.expectMediaRenegotiation_ = false; testWithScenario(aliceData_, bobData_, scenario); libjami::unregisterSignalHandlers(); JAMI_INFO("=== End test %s ===", __FUNCTION__); } void AutoAnswerMediaNegoTest::audio_and_video_then_change_video_source() { JAMI_INFO("=== Begin test %s ===", __FUNCTION__); configureScenario(); MediaAttribute defaultAudio(MediaType::MEDIA_AUDIO); defaultAudio.label_ = "audio_0"; defaultAudio.enabled_ = true; MediaAttribute defaultVideo(MediaType::MEDIA_VIDEO); defaultVideo.label_ = "video_0"; defaultVideo.enabled_ = true; MediaAttribute audio(defaultAudio); MediaAttribute video(defaultVideo); TestScenario scenario; // First offer/answer scenario.offer_.emplace_back(audio); scenario.offer_.emplace_back(video); scenario.answer_.emplace_back(audio); scenario.answer_.emplace_back(video); // Updated offer/answer scenario.offerUpdate_.emplace_back(audio); // Just change the media source to validate that a new // media negotiation (re-invite) will be triggered. video.sourceUri_ = "Fake source"; scenario.offerUpdate_.emplace_back(video); scenario.answerUpdate_.emplace_back(audio); scenario.answerUpdate_.emplace_back(video); scenario.expectMediaRenegotiation_ = true; testWithScenario(aliceData_, bobData_, scenario); libjami::unregisterSignalHandlers(); JAMI_INFO("=== End test %s ===", __FUNCTION__); } CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(AutoAnswerMediaNegoTestSip, AutoAnswerMediaNegoTestSip::name()); CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(AutoAnswerMediaNegoTestJami, AutoAnswerMediaNegoTestJami::name()); } // namespace test } // namespace jami JAMI_TEST_RUNNER(jami::test::AutoAnswerMediaNegoTestJami::name())
36,656
C++
.cpp
842
33.960808
106
0.626652
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,697
guile-wrapper.cpp
savoirfairelinux_jami-daemon/test/agent/build-aux/guile-wrapper.cpp
/* * Copyright (C) 2021-2023 Savoir-faire Linux Inc. * * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <libguile.h> void inner_main(void *, int argc, char **argv) { scm_shell(argc, argv); } int main(int argc, char *argv[]) { (void) scm_boot_guile(argc, argv, inner_main, NULL); __builtin_unreachable(); }
946
C++
.cpp
27
32.888889
73
0.725983
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,698
main.cpp
savoirfairelinux_jami-daemon/test/agent/src/main.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "bindings/bindings.h" #include "jami.h" #include <libguile.h> extern "C" { LIBJAMI_PUBLIC void bootstrap(); } void bootstrap() { install_scheme_primitives(); }
895
C++
.cpp
27
31.259259
73
0.747393
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,699
bindings.cpp
savoirfairelinux_jami-daemon/test/agent/src/bindings/bindings.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ /* Agent */ #include "bindings/bindings.h" /* Include module's bindings here */ #include "bindings/account.h" #include "bindings/call.h" #include "bindings/conversation.h" #include "bindings/jami.h" #include "bindings/logger.h" #include "bindings/signal.h" void install_scheme_primitives() { /* Define modules here */ auto load_module = [](auto name, auto init){ scm_c_define_module(name, init, NULL); }; load_module("jami", install_jami_primitives); load_module("jami account", install_account_primitives); load_module("jami call", install_call_primitives); load_module("jami conversation", install_conversation_primitives); load_module("jami logger bindings", install_logger_primitives); load_module("jami signal bindings", install_signal_primitives); } /* * Register Guile bindings here. * * 1. Name of the binding * 2. Number of required argument to binding * 3. Number of optional argument to binding * 4. Number of rest argument to binding * 5. Pointer to C function to call * * See info guile: * * Function: SCM scm_c_define_gsubr(const char *name, int req, int opt, int rst, fcn): * * Register a C procedure FCN as a “subr” — a primitive subroutine that can be * called from Scheme. It will be associated with the given NAME and bind it in * the "current environment". The arguments REQ, OPT and RST specify the number * of required, optional and “rest” arguments respectively. The total number of * these arguments should match the actual number of arguments to FCN, but may * not exceed 10. The number of rest arguments should be 0 or 1. * ‘scm_c_make_gsubr’ returns a value of type ‘SCM’ which is a “handle” for the * procedure. */ void define_primitive(const char* name, int req, int opt, int rst, void* func) { scm_c_define_gsubr(name, req, opt, rst, func); scm_c_export(name, NULL); }
2,628
C++
.cpp
67
36.38806
86
0.73086
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,700
signal.cpp
savoirfairelinux_jami-daemon/test/agent/src/bindings/signal.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ /* Std */ #include <condition_variable> #include <functional> #include <mutex> #include <queue> #include <thread> #include <tuple> #include <vector> /* Guile */ #include <libguile.h> /* Jami */ #include "account_const.h" #include "jami/callmanager_interface.h" #include "jami/configurationmanager_interface.h" #include "jami/conversation_interface.h" #include "jami/datatransfer_interface.h" #include "jami/presencemanager_interface.h" /* Agent */ #include "bindings/bindings.h" #include "utils.h" static SCM signal_alist = SCM_EOL; template<typename... Args> class Handler { std::mutex mutex_; std::vector<SCM> callbacks_; public: Handler(const char* symbol_name) { signal_alist = scm_cons(scm_cons(scm_from_utf8_symbol(symbol_name), scm_cons(scm_from_pointer(static_cast<void*>(&callbacks_), nullptr), scm_from_pointer(static_cast<void*>(&mutex_), nullptr))), signal_alist); } struct cb_ctx { Handler<Args...>& me; std::tuple<Args...>& args; }; void doExecuteInGuile(Args... args) { std::unique_lock lck(mutex_); std::vector<SCM> old; std::vector<SCM> to_keep; old = std::move(callbacks_); lck.unlock(); for (SCM cb : old) { using namespace std::placeholders; using std::bind; SCM ret = apply_to_guile(cb, args...); if (scm_is_true(ret)) { to_keep.emplace_back(cb); } else { scm_gc_unprotect_object(cb); } } lck.lock(); for (SCM cb : to_keep) { callbacks_.push_back(cb); } } static void* executeInGuile(void* ctx_raw) { cb_ctx* ctx = static_cast<cb_ctx*>(ctx_raw); auto apply_wrapper = [&](Args... args) { ctx->me.doExecuteInGuile(args...); }; std::apply(apply_wrapper, ctx->args); return nullptr; } void execute(Args... args) { std::tuple<Args...> tuple(args...); cb_ctx ctx = {*this, tuple}; scm_with_guile(executeInGuile, &ctx); } }; static SCM on_signal_binding(SCM signal_sym, SCM handler_proc) { static SCM bad_signal_sym = scm_from_utf8_symbol("bad-signal"); SCM handler_pair; std::vector<SCM>* callbacks; std::mutex* mutex; if (scm_is_false(scm_procedure_p(handler_proc))) { scm_wrong_type_arg_msg("on_signal_binding", 0, handler_proc, "procedure"); } handler_pair = scm_assq_ref(signal_alist, signal_sym); if (scm_is_false(handler_pair)) { scm_throw(bad_signal_sym, scm_list_2(signal_sym, handler_proc)); } callbacks = static_cast<std::vector<SCM>*>(scm_to_pointer(scm_car(handler_pair))); mutex = static_cast<std::mutex*>(scm_to_pointer(scm_cdr(handler_pair))); std::unique_lock lck(*mutex); scm_gc_protect_object(handler_proc); callbacks->push_back(handler_proc); return SCM_UNDEFINED; } template<typename T, typename... Args> void add_handler(std::map<std::string, std::shared_ptr<libjami::CallbackWrapperBase>>& handlers, const char* name) { static Handler<Args...> handler(name); auto fn = [=](Args... args) { handler.execute(args...); }; handlers.insert(libjami::exportable_callback<T>(std::move(fn))); } void install_signal_primitives(void*) { define_primitive("on-signal", 2, 0, 0, (void*) on_signal_binding); std::map<std::string, std::shared_ptr<libjami::CallbackWrapperBase>> handlers; add_handler<libjami::CallSignal::StateChange, const std::string&, const std::string&, const std::string&, signed>(handlers, "state-changed"); add_handler<libjami::CallSignal::TransferFailed>(handlers, "transfer-failed"); add_handler<libjami::CallSignal::TransferSucceeded>(handlers, "transfer-succeeded"); add_handler<libjami::CallSignal::RecordPlaybackStopped, const std::string&>(handlers, "record-playback-stopped"); add_handler<libjami::CallSignal::VoiceMailNotify, const std::string&, int32_t, int32_t, int32_t>( handlers, "voice-mail-notify"); add_handler<libjami::CallSignal::IncomingMessage, const std::string&, const std::string&, const std::string&, const std::map<std::string, std::string>&>(handlers, "incoming-message"); add_handler<libjami::CallSignal::IncomingCall, const std::string&, const std::string&, const std::string&>(handlers, "incoming-call"); add_handler<libjami::CallSignal::IncomingCallWithMedia, const std::string&, const std::string&, const std::string&, const std::vector<libjami::MediaMap>>(handlers, "incoming-call/media"); add_handler<libjami::CallSignal::MediaChangeRequested, const std::string&, const std::string&, const std::vector<std::map<std::string, std::string>>&>(handlers, "media-change-requested"); add_handler<libjami::CallSignal::RecordPlaybackFilepath, const std::string&, const std::string&>( handlers, "record-playback-filepath"); add_handler<libjami::CallSignal::ConferenceCreated, const std::string&, const std::string&, const std::string&>( handlers, "conference-created"); add_handler<libjami::CallSignal::ConferenceChanged, const std::string&, const std::string&, const std::string&>(handlers, "conference-changed"); add_handler<libjami::CallSignal::UpdatePlaybackScale, const std::string&, unsigned, unsigned>( handlers, "update-playback-scale"); add_handler<libjami::CallSignal::ConferenceRemoved, const std::string&, const std::string&>( handlers, "conference-removed"); add_handler<libjami::CallSignal::RecordingStateChanged, const std::string&, int>( handlers, "recording-state-changed"); add_handler<libjami::CallSignal::RtcpReportReceived, const std::string&, const std::map<std::string, int>&>(handlers, "rtcp-report-received"); add_handler<libjami::CallSignal::PeerHold, const std::string&, bool>(handlers, "peer-hold"); add_handler<libjami::CallSignal::VideoMuted, const std::string&, bool>(handlers, "video-muted"); add_handler<libjami::CallSignal::AudioMuted, const std::string&, bool>(handlers, "audio-muted"); add_handler<libjami::CallSignal::SmartInfo, const std::map<std::string, std::string>&>(handlers, "smart-info"); add_handler<libjami::CallSignal::ConnectionUpdate, const std::string&, int>( handlers, "connection-update"); add_handler<libjami::CallSignal::OnConferenceInfosUpdated, const std::string&, const std::vector<std::map<std::string, std::string>>&>(handlers, "conference-infos-updated"); add_handler<libjami::CallSignal::RemoteRecordingChanged, const std::string&, const std::string&, bool>(handlers, "remote-recording-changed"); add_handler<libjami::CallSignal::MediaNegotiationStatus, const std::string&, const std::string&, const std::vector<std::map<std::string, std::string>>&>(handlers, "media-negotiation-status"); /* Configuration */ add_handler<libjami::ConfigurationSignal::VolumeChanged, const std::string&, double>( handlers, "volume-changed"); add_handler<libjami::ConfigurationSignal::Error, int>(handlers, "configuration-error"); add_handler<libjami::ConfigurationSignal::AccountsChanged>(handlers, "accounts-changed"); add_handler<libjami::ConfigurationSignal::AccountDetailsChanged, const std::string&, const std::map<std::string, std::string>&>(handlers, "account-details-changed"); add_handler<libjami::ConfigurationSignal::StunStatusFailed, const std::string&>(handlers, "stun-status-failed"); add_handler<libjami::ConfigurationSignal::RegistrationStateChanged, const std::string&, const std::string&, int, const std::string&>(handlers, "registration-state-changed"); add_handler<libjami::ConfigurationSignal::VolatileDetailsChanged, const std::string&, const std::map<std::string, std::string>&>(handlers, "volatile-details-changed"); add_handler<libjami::ConfigurationSignal::IncomingAccountMessage, const std::string&, const std::string&, const std::string&, const std::map<std::string, std::string>&>(handlers, "incoming-account-message"); add_handler<libjami::ConfigurationSignal::AccountMessageStatusChanged, const std::string&, const std::string&, const std::string&, const std::string&, int>(handlers, "account-message-status-changed"); add_handler<libjami::ConfigurationSignal::ProfileReceived, const std::string&, const std::string&, const std::string&>(handlers, "profile-received"); add_handler<libjami::ConfigurationSignal::ComposingStatusChanged, const std::string&, const std::string&, const std::string&, int>(handlers, "composing-status-changed"); add_handler<libjami::ConfigurationSignal::IncomingTrustRequest, const std::string&, const std::string&, const std::string&, const std::vector<uint8_t>&, time_t>(handlers, "incoming-trust-request"); add_handler<libjami::ConfigurationSignal::ContactAdded, const std::string&, const std::string&, bool>(handlers, "contact-added"); add_handler<libjami::ConfigurationSignal::ContactRemoved, const std::string&, const std::string&, bool>(handlers, "contact-removed"); add_handler<libjami::ConfigurationSignal::ExportOnRingEnded, const std::string&, int, const std::string&>(handlers, "export-on-ring-ended"); add_handler<libjami::ConfigurationSignal::NameRegistrationEnded, const std::string&, int, const std::string&>(handlers, "name-registration-ended"); add_handler<libjami::ConfigurationSignal::KnownDevicesChanged, const std::string&, const std::map<std::string, std::string>&>(handlers, "known-devices-changed"); add_handler<libjami::ConfigurationSignal::RegisteredNameFound, const std::string&, int, const std::string&, const std::string&>(handlers, "registered-name-found"); add_handler<libjami::ConfigurationSignal::UserSearchEnded, const std::string&, int, const std::string&, const std::vector<std::map<std::string, std::string>>&>(handlers, "user-search-ended"); add_handler<libjami::ConfigurationSignal::CertificatePinned, const std::string&>(handlers, "certificate-pinned"); add_handler<libjami::ConfigurationSignal::CertificatePathPinned, const std::string&, const std::vector<std::string>&>(handlers, "certificate-path-pinned"); add_handler<libjami::ConfigurationSignal::CertificateExpired, const std::string&>(handlers, "certificate-expired"); add_handler<libjami::ConfigurationSignal::CertificateStateChanged, const std::string&, const std::string&, const std::string&>(handlers, "certificate-state-changed"); add_handler<libjami::ConfigurationSignal::MediaParametersChanged, const std::string&>(handlers, "media-parameters-changed"); add_handler<libjami::ConfigurationSignal::MigrationEnded, const std::string&, const std::string&>( handlers, "migration-ended"); add_handler<libjami::ConfigurationSignal::DeviceRevocationEnded, const std::string&, const std::string&, int>(handlers, "device-revocation-ended"); add_handler<libjami::ConfigurationSignal::AccountProfileReceived, const std::string&, const std::string&, const std::string&>(handlers, "account-profile-received"); #if defined(__ANDROID__) || (defined(TARGET_OS_IOS) && TARGET_OS_IOS) add_handler<libjami::ConfigurationSignal::GetHardwareAudioFormat, std::vector<int32_t>*>(handlers, "get-hardware-audio-format"); #endif #if defined(__ANDROID__) || (defined(TARGET_OS_IOS) && TARGET_OS_IOS) add_handler<libjami::ConfigurationSignal::GetAppDataPath, const std::string&, std::vector<std::string>*>(handlers, "get-app-data-path"); add_handler<libjami::ConfigurationSignal::GetDeviceName, std::vector<std::string>*>(handlers, "get-device-name"); #endif add_handler<libjami::ConfigurationSignal::HardwareDecodingChanged, bool>(handlers, "hardware-decoding-changed"); add_handler<libjami::ConfigurationSignal::HardwareEncodingChanged, bool>(handlers, "hardware-encoding-changed"); add_handler<libjami::ConfigurationSignal::MessageSend, const std::string&>(handlers, "message-send"); /* Presence */ add_handler<libjami::PresenceSignal::NewServerSubscriptionRequest, const std::string&>(handlers, "new-server-subscription-request"); add_handler<libjami::PresenceSignal::ServerError, const std::string&, const std::string&, const std::string&>(handlers, "server-error"); add_handler<libjami::PresenceSignal::NewBuddyNotification, const std::string&, const std::string&, int, const std::string&>(handlers, "new-buddy-notification"); add_handler<libjami::PresenceSignal::NearbyPeerNotification, const std::string&, const std::string&, int, const std::string&>(handlers, "nearby-peer-notification"); add_handler<libjami::PresenceSignal::SubscriptionStateChanged, const std::string&, const std::string&, int>(handlers, "subscription-state-changed"); /* Audio */ add_handler<libjami::AudioSignal::DeviceEvent>(handlers, "audio-device-event"); add_handler<libjami::AudioSignal::AudioMeter, const std::string&, float>(handlers, "audio-meter"); /* DataTransfer */ add_handler<libjami::DataTransferSignal::DataTransferEvent, const std::string&, const std::string&, const std::string&, const std::string&, int>(handlers, "data-transfer-event"); #ifdef ENABLE_VIDEO /* MediaPlayer */ add_handler<libjami::MediaPlayerSignal::FileOpened, const std::string&, std::map<std::string, std::string>>(handlers, "media-file-opened"); /* Video */ add_handler<libjami::VideoSignal::DeviceEvent>(handlers, "device-event"); add_handler<libjami::VideoSignal::DecodingStarted, const std::string&, const std::string&, int, int, bool>(handlers, "video-decoding-started"); add_handler<libjami::VideoSignal::DecodingStopped, const std::string&, const std::string&, bool>( handlers, "video-decoding-stopped"); #ifdef __ANDROID__ add_handler<libjami::VideoSignal::GetCameraInfo, const std::string&, std::vector<int>*, std::vector<unsigned>*, std::vector<unsigned>*>(handlers, "video-get-camera-info"); add_handler<libjami::VideoSignal::SetParameters, const std::string&, const int, const int, const int, const int>(handlers, "video-set-parameters"); add_handler<libjami::VideoSignal::RequestKeyFrame>(handlers, "video-request-key-frame"); add_handler<libjami::VideoSignal::SetBitrate, const std::string&, const int>( handlers, "video-set-bitrate"); #endif add_handler<libjami::VideoSignal::StartCapture, const std::string&>(handlers, "video-start-capture"); add_handler<libjami::VideoSignal::StopCapture>(handlers, "video-stop-capture"); add_handler<libjami::VideoSignal::DeviceAdded, const std::string&>(handlers, "video-device-added"); add_handler<libjami::VideoSignal::ParametersChanged, const std::string&>(handlers, "video-parameters-changed"); #endif /* Conversation */ add_handler<libjami::ConversationSignal::ConversationLoaded, uint32_t, const std::string&, const std::string&, std::vector<std::map<std::string, std::string>>>(handlers, "conversation-loaded"); add_handler<libjami::ConversationSignal::MessagesFound, uint32_t, const std::string&, const std::string&, std::vector<std::map<std::string, std::string>>>(handlers, "messages-found"); add_handler<libjami::ConversationSignal::MessageReceived, const std::string&, const std::string&, std::map<std::string, std::string>>(handlers, "message-received"); add_handler<libjami::ConversationSignal::ConversationRequestReceived, const std::string&, const std::string&, std::map<std::string, std::string>>(handlers, "conversation-request-received"); add_handler<libjami::ConversationSignal::ConversationRequestDeclined, const std::string&, const std::string&>(handlers, "conversation-request-declined"); add_handler<libjami::ConversationSignal::ConversationReady, const std::string&, const std::string&>(handlers, "conversation-ready"); add_handler<libjami::ConversationSignal::ConversationRemoved, const std::string&, const std::string&>(handlers, "conversation-removed"); add_handler<libjami::ConversationSignal::ConversationMemberEvent, const std::string&, const std::string&, const std::string&, int>(handlers, "conversation-member-event"); add_handler<libjami::ConversationSignal::OnConversationError, const std::string&, const std::string&, int, const std::string&>(handlers, "conversation-error"); add_handler<libjami::ConversationSignal::ConversationPreferencesUpdated, const std::string&, const std::string&, std::map<std::string, std::string>>(handlers, "conversation-preferences-updated"); libjami::registerSignalHandlers(handlers); }
20,771
C++
.cpp
427
36.983607
116
0.608199
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,701
archiver.cpp
savoirfairelinux_jami-daemon/src/archiver.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "archiver.h" #include "client/ring_signal.h" #include "account_const.h" #include "configurationmanager_interface.h" #include "manager.h" #include "fileutils.h" #include "logger.h" #include <opendht/crypto.h> #include <json/json.h> #include <zlib.h> #ifdef ENABLE_PLUGIN extern "C" { #if defined(__APPLE__) #include <minizip/mz.h> #include <minizip/mz_strm.h> #include <minizip/mz_strm_os.h> #include <minizip/mz_zip.h> #include <minizip/mz_zip_rw.h> #else #include <archive.h> #include <archive_entry.h> #endif } #endif #include <sys/stat.h> #include <fstream> using namespace std::literals; namespace jami { namespace archiver { std::vector<uint8_t> compress(const std::string& str) { auto destSize = compressBound(str.size()); std::vector<uint8_t> outbuffer(destSize); int ret = ::compress(reinterpret_cast<Bytef*>(outbuffer.data()), &destSize, (Bytef*) str.data(), str.size()); outbuffer.resize(destSize); if (ret != Z_OK) { std::ostringstream oss; oss << "Exception during zlib compression: (" << ret << ") "; throw std::runtime_error(oss.str()); } return outbuffer; } void compressGzip(const std::string& str, const std::string& path) { auto fi = openGzip(path, "wb"); gzwrite(fi, str.data(), str.size()); gzclose(fi); } void compressGzip(const std::vector<uint8_t>& dat, const std::string& path) { auto fi = openGzip(path, "wb"); gzwrite(fi, dat.data(), dat.size()); gzclose(fi); } std::vector<uint8_t> decompressGzip(const std::string& path) { std::vector<uint8_t> out; auto fi = openGzip(path, "rb"); gzrewind(fi); while (not gzeof(fi)) { std::array<uint8_t, 32768> outbuffer; int len = gzread(fi, outbuffer.data(), outbuffer.size()); if (len == -1) { gzclose(fi); throw std::runtime_error("Exception during gzip decompression"); } out.insert(out.end(), outbuffer.begin(), outbuffer.begin() + len); } gzclose(fi); return out; } std::vector<uint8_t> decompress(const std::vector<uint8_t>& str) { z_stream zs; // z_stream is zlib's control structure memset(&zs, 0, sizeof(zs)); if (inflateInit2(&zs, 32+MAX_WBITS) != Z_OK) throw std::runtime_error("inflateInit failed while decompressing."); zs.next_in = (Bytef*) str.data(); zs.avail_in = str.size(); int ret; std::vector<uint8_t> out; // get the decompressed bytes blockwise using repeated calls to inflate do { std::array<uint8_t, 32768> outbuffer; zs.next_out = reinterpret_cast<Bytef*>(outbuffer.data()); zs.avail_out = outbuffer.size(); ret = inflate(&zs, 0); if (ret == Z_DATA_ERROR || ret == Z_MEM_ERROR) break; if (out.size() < zs.total_out) { // append the block to the output string out.insert(out.end(), outbuffer.begin(), outbuffer.begin() + zs.total_out - out.size()); } } while (ret == Z_OK); inflateEnd(&zs); // an error occurred that was not EOF if (ret != Z_STREAM_END) { std::ostringstream oss; oss << "Exception during zlib decompression: (" << ret << ") " << zs.msg; throw(std::runtime_error(oss.str())); } return out; } gzFile openGzip(const std::string& path, const char* mode) { #ifdef _WIN32 return gzopen_w(jami::to_wstring(path).c_str(), mode); #else return gzopen(path.c_str(), mode); #endif } #ifdef ENABLE_PLUGIN #if !defined(__APPLE__) // LIBARCHIVE DEFINITIONS //========================== using ArchivePtr = std::unique_ptr<archive, void (*)(archive*)>; using ArchiveEntryPtr = std::unique_ptr<archive_entry, void (*)(archive_entry*)>; struct DataBlock { const void* buff; size_t size; int64_t offset; }; long readDataBlock(const ArchivePtr& a, DataBlock& b) { return archive_read_data_block(a.get(), &b.buff, &b.size, &b.offset); } long writeDataBlock(const ArchivePtr& a, DataBlock& b) { return archive_write_data_block(a.get(), b.buff, b.size, b.offset); } ArchivePtr createArchiveReader() { ArchivePtr archivePtr {archive_read_new(), [](archive* a) { archive_read_close(a); archive_read_free(a); }}; return archivePtr; } static ArchivePtr createArchiveDiskWriter() { return {archive_write_disk_new(), [](archive* a) { archive_write_close(a); archive_write_free(a); }}; } //========================== #endif #endif void uncompressArchive(const std::string& archivePath, const std::string& dir, const FileMatchPair& f) { #ifdef ENABLE_PLUGIN #if defined(__APPLE__) mz_zip_file* info = NULL; dhtnet::fileutils::check_dir(dir.c_str()); void* zip_handle = mz_zip_create(); auto status = mz_zip_reader_open_file(zip_handle, archivePath.c_str()); status |= mz_zip_reader_goto_first_entry(zip_handle); while (status == MZ_OK) { status |= mz_zip_reader_entry_get_info(zip_handle, &info); if (status != MZ_OK) { dhtnet::fileutils::removeAll(dir, true); break; } std::string_view filename(info->filename, (size_t) info->filename_size); const auto& fileMatchPair = f(filename); if (fileMatchPair.first) { auto filePath = dir + DIR_SEPARATOR_STR + fileMatchPair.second; std::string directory = filePath.substr(0, filePath.find_last_of(DIR_SEPARATOR_CH)); dhtnet::fileutils::check_dir(directory.c_str()); mz_zip_reader_entry_open(zip_handle); void* buffStream = mz_stream_os_create(); if (mz_stream_os_open(buffStream, filePath.c_str(), MZ_OPEN_MODE_WRITE | MZ_OPEN_MODE_CREATE) == MZ_OK) { int chunkSize = 8192; std::vector<uint8_t> fileContent; fileContent.resize(chunkSize); while (auto ret = mz_zip_reader_entry_read(zip_handle, (void*) fileContent.data(), chunkSize)) { ret = mz_stream_os_write(buffStream, (void*) fileContent.data(), ret); if (ret < 0) { dhtnet::fileutils::removeAll(dir, true); status = 1; } } mz_stream_os_close(buffStream); mz_stream_os_delete(&buffStream); } else { dhtnet::fileutils::removeAll(dir, true); status = 1; } mz_zip_reader_entry_close(zip_handle); } status |= mz_zip_reader_goto_next_entry(zip_handle); } mz_zip_reader_close(zip_handle); mz_zip_delete(&zip_handle); #else int r; ArchivePtr archiveReader = createArchiveReader(); ArchivePtr archiveDiskWriter = createArchiveDiskWriter(); struct archive_entry* entry; int flags = ARCHIVE_EXTRACT_TIME | ARCHIVE_EXTRACT_NO_HFS_COMPRESSION; // Set reader formats(archive) and filters(compression) archive_read_support_filter_all(archiveReader.get()); archive_read_support_format_all(archiveReader.get()); // Set written files flags and standard lookup(uid/gid) archive_write_disk_set_options(archiveDiskWriter.get(), flags); archive_write_disk_set_standard_lookup(archiveDiskWriter.get()); // Try to read the archive if ((r = archive_read_open_filename(archiveReader.get(), archivePath.c_str(), 10240))) { throw std::runtime_error("Open Archive: " + archivePath + "\t" + archive_error_string(archiveReader.get())); } while (true) { // Read headers until End of File r = archive_read_next_header(archiveReader.get(), &entry); if (r == ARCHIVE_EOF) { break; } if (r != ARCHIVE_OK && r != ARCHIVE_WARN) { throw std::runtime_error("Error reading archive: "s + archive_error_string(archiveReader.get())); } std::string_view fileEntry(archive_entry_pathname(entry)); // File is ok, copy its header to the ext writer const auto& fileMatchPair = f(fileEntry); if (fileMatchPair.first) { std::string entryDestinationPath = dir + DIR_SEPARATOR_CH + fileMatchPair.second; archive_entry_set_pathname(entry, entryDestinationPath.c_str()); r = archive_write_header(archiveDiskWriter.get(), entry); if (r != ARCHIVE_OK) { // Rollback if failed at a write operation dhtnet::fileutils::removeAll(dir); throw std::runtime_error("Write file header: " + fileEntry + "\t" + archive_error_string(archiveDiskWriter.get())); } else { // Here both the reader and the writer have moved past the headers // Copying the data content DataBlock db; while (true) { r = readDataBlock(archiveReader, db); if (r == ARCHIVE_EOF) { break; } if (r != ARCHIVE_OK) { throw std::runtime_error("Read file data: " + fileEntry + "\t" + archive_error_string(archiveReader.get())); } r = writeDataBlock(archiveDiskWriter, db); if (r != ARCHIVE_OK) { // Rollback if failed at a write operation dhtnet::fileutils::removeAll(dir); throw std::runtime_error("Write file data: " + fileEntry + "\t" + archive_error_string(archiveDiskWriter.get())); } } } } } #endif #endif } std::vector<uint8_t> readFileFromArchive(const std::string& archivePath, const std::string& fileRelativePathName) { std::vector<uint8_t> fileContent; #ifdef ENABLE_PLUGIN #if defined(__APPLE__) mz_zip_file* info; void* zip_handle = mz_zip_create(); auto status = mz_zip_reader_open_file(zip_handle, archivePath.c_str()); status |= mz_zip_reader_goto_first_entry(zip_handle); while (status == MZ_OK) { status = mz_zip_reader_entry_get_info(zip_handle, &info); if (status != MZ_OK) break; std::string_view filename(info->filename, (size_t) info->filename_size); if (filename == fileRelativePathName) { mz_zip_reader_entry_open(zip_handle); fileContent.resize(info->uncompressed_size); mz_zip_reader_entry_read(zip_handle, (void*) fileContent.data(), info->uncompressed_size); mz_zip_reader_entry_close(zip_handle); status = -1; } else { status = mz_zip_reader_goto_next_entry(zip_handle); } } mz_zip_reader_close(zip_handle); mz_zip_delete(&zip_handle); #else long r; ArchivePtr archiveReader = createArchiveReader(); struct archive_entry* entry; // Set reader formats(archive) and filters(compression) archive_read_support_filter_all(archiveReader.get()); archive_read_support_format_all(archiveReader.get()); // Try to read the archive if ((r = archive_read_open_filename(archiveReader.get(), archivePath.c_str(), 10240))) { throw std::runtime_error("Open Archive: " + archivePath + "\t" + archive_error_string(archiveReader.get())); } while (true) { // Read headers until End of File r = archive_read_next_header(archiveReader.get(), &entry); if (r == ARCHIVE_EOF) { break; } std::string fileEntry = archive_entry_pathname(entry) ? archive_entry_pathname(entry) : ""; if (r != ARCHIVE_OK) { throw std::runtime_error(fmt::format("Read file pathname: {}: {}", fileEntry, archive_error_string(archiveReader.get()))); } // File is ok and the reader has moved past the header if (fileEntry == fileRelativePathName) { // Copying the data content DataBlock db; while (true) { r = readDataBlock(archiveReader, db); if (r == ARCHIVE_EOF) { return fileContent; } if (r != ARCHIVE_OK) { throw std::runtime_error("Read file data: " + fileEntry + "\t" + archive_error_string(archiveReader.get())); } if (fileContent.size() < static_cast<size_t>(db.offset)) { fileContent.resize(db.offset); } auto dat = static_cast<const uint8_t*>(db.buff); // push the buffer data in the string stream fileContent.insert(fileContent.end(), dat, dat + db.size); } } } throw std::runtime_error("File " + fileRelativePathName + " not found in the archive"); #endif #endif return fileContent; } std::vector<std::string> listFilesFromArchive(const std::string& path) { std::vector<std::string> filePaths; #ifdef ENABLE_PLUGIN #if defined(__APPLE__) mz_zip_file* info = NULL; void* zip_handle = mz_zip_create(); auto status = mz_zip_reader_open_file(zip_handle, path.c_str()); status |= mz_zip_reader_goto_first_entry(zip_handle); // read all the file path of the archive while (status == MZ_OK) { status = mz_zip_reader_entry_get_info(zip_handle, &info); if (status != MZ_OK) break; std::string filename(info->filename, (size_t) info->filename_size); filePaths.push_back(filename); status = mz_zip_reader_goto_next_entry(zip_handle); } mz_zip_reader_close(zip_handle); mz_zip_delete(&zip_handle); #else ArchivePtr archiveReader = createArchiveReader(); struct archive_entry* entry; archive_read_support_format_all(archiveReader.get()); if(archive_read_open_filename(archiveReader.get(), path.c_str(), 10240)) { throw std::runtime_error("Open Archive: " + path + "\t" + archive_error_string(archiveReader.get())); } while (archive_read_next_header(archiveReader.get(), &entry) == ARCHIVE_OK) { const char* name = archive_entry_pathname(entry); filePaths.push_back(name); } #endif #endif return filePaths; } } // namespace archiver } // namespace jami
15,689
C++
.cpp
413
29.302663
134
0.587744
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,702
call.cpp
savoirfairelinux_jami-daemon/src/call.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "call.h" #include "account.h" #include "jamidht/jamiaccount.h" #include "manager.h" #ifdef ENABLE_PLUGIN #include "plugin/jamipluginmanager.h" #include "plugin/streamdata.h" #endif #include "audio/ringbufferpool.h" #include "jami/call_const.h" #include "client/ring_signal.h" #include "connectivity/sip_utils.h" #include "map_utils.h" #include "call_factory.h" #include "string_utils.h" #include "enumclass_utils.h" #include "errno.h" #include <dhtnet/ip_utils.h> #include <opendht/thread_pool.h> #include <stdexcept> #include <system_error> #include <algorithm> #include <functional> #include <utility> namespace jami { /// Hangup many calls with same error code, filtered by a predicate /// /// For each call pointer given by iterating on given \a callptr_list /// calls the unary predicate \a pred with this call pointer and hangup the call with given error /// code \a errcode when the predicate return true. /// The predicate should have <code>bool(Call*) signature</code>. template<typename T> inline void hangupCallsIf(Call::SubcallSet&& calls, int errcode, T pred) { for (auto& call : calls) { if (not pred(call.get())) continue; dht::ThreadPool::io().run([call = std::move(call), errcode] { call->hangup(errcode); }); } } /// Hangup many calls with same error code. /// /// Works as hangupCallsIf() with a predicate that always return true. inline void hangupCalls(Call::SubcallSet&& callptr_list, int errcode) { hangupCallsIf(std::move(callptr_list), errcode, [](Call*) { return true; }); } //============================================================================== Call::Call(const std::shared_ptr<Account>& account, const std::string& id, Call::CallType type, const std::map<std::string, std::string>& details) : id_(id) , type_(type) , account_(account) { addStateListener([this](Call::CallState call_state, Call::ConnectionState cnx_state, int code) { checkPendingIM(); runOnMainThread([callWkPtr = weak()] { if (auto call = callWkPtr.lock()) call->checkAudio(); }); // if call just started ringing, schedule call timeout if (type_ == CallType::INCOMING and cnx_state == ConnectionState::RINGING) { auto timeout = Manager::instance().getRingingTimeout(); JAMI_DBG("Scheduling call timeout in %d seconds", timeout); Manager::instance().scheduler().scheduleIn( [callWkPtr = weak()] { if (auto callShPtr = callWkPtr.lock()) { if (callShPtr->getConnectionState() == Call::ConnectionState::RINGING) { JAMI_DBG( "Call %s is still ringing after timeout, setting state to BUSY", callShPtr->getCallId().c_str()); callShPtr->hangup(PJSIP_SC_BUSY_HERE); Manager::instance().callFailure(*callShPtr); } } }, std::chrono::seconds(timeout)); } if (!isSubcall()) { if (code == static_cast<int>(std::errc::no_such_device_or_address)) { reason_ = "no_device"; } if (cnx_state == ConnectionState::CONNECTED && duration_start_ == time_point::min()) duration_start_ = clock::now(); else if (cnx_state == ConnectionState::DISCONNECTED && call_state == CallState::OVER) { if (auto jamiAccount = std::dynamic_pointer_cast<JamiAccount>(getAccount().lock())) { if (toUsername().find('/') == std::string::npos && getCallType() == CallType::OUTGOING) { if (auto cm = jamiAccount->convModule(true)) cm->addCallHistoryMessage(getPeerNumber(), getCallDuration().count(), reason_); } monitor(); } } } // kill pending subcalls at disconnect if (call_state == CallState::OVER) hangupCalls(safePopSubcalls(), 0); return true; }); time(&timestamp_start_); } Call::~Call() {} void Call::removeCall() { auto this_ = shared_from_this(); Manager::instance().callFactory.removeCall(*this); setState(CallState::OVER); if (Recordable::isRecording()) Recordable::stopRecording(); if (auto account = account_.lock()) account->detach(this_); parent_.reset(); subcalls_.clear(); } std::string Call::getAccountId() const { if (auto shared = account_.lock()) return shared->getAccountID(); JAMI_ERR("No account detected"); return {}; } Call::ConnectionState Call::getConnectionState() const { std::lock_guard lock(callMutex_); return connectionState_; } Call::CallState Call::getState() const { std::lock_guard lock(callMutex_); return callState_; } bool Call::validStateTransition(CallState newState) { // Notice to developper: // - list only permitted transition (return true) // - let non permitted ones as default case (return false) // always permited if (newState == CallState::OVER) return true; switch (callState_) { case CallState::INACTIVE: switch (newState) { case CallState::ACTIVE: case CallState::BUSY: case CallState::PEER_BUSY: case CallState::MERROR: return true; default: // INACTIVE, HOLD return false; } case CallState::ACTIVE: switch (newState) { case CallState::BUSY: case CallState::PEER_BUSY: case CallState::HOLD: case CallState::MERROR: return true; default: // INACTIVE, ACTIVE return false; } case CallState::HOLD: switch (newState) { case CallState::ACTIVE: case CallState::MERROR: return true; default: // INACTIVE, HOLD, BUSY, PEER_BUSY, MERROR return false; } case CallState::BUSY: switch (newState) { case CallState::MERROR: return true; default: // INACTIVE, ACTIVE, HOLD, BUSY, PEER_BUSY return false; } default: // MERROR return false; } } bool Call::setState(CallState call_state, ConnectionState cnx_state, signed code) { std::unique_lock<std::recursive_mutex> lock(callMutex_); JAMI_DBG("[call:%s] state change %u/%u, cnx %u/%u, code %d", id_.c_str(), (unsigned) callState_, (unsigned) call_state, (unsigned) connectionState_, (unsigned) cnx_state, code); if (callState_ != call_state) { if (not validStateTransition(call_state)) { JAMI_ERR("[call:%s] invalid call state transition from %u to %u", id_.c_str(), (unsigned) callState_, (unsigned) call_state); return false; } } else if (connectionState_ == cnx_state) return true; // no changes as no-op // Emit client state only if changed auto old_client_state = getStateStr(); callState_ = call_state; connectionState_ = cnx_state; auto new_client_state = getStateStr(); for (auto it = stateChangedListeners_.begin(); it != stateChangedListeners_.end();) { if ((*it)(callState_, connectionState_, code)) ++it; else it = stateChangedListeners_.erase(it); } if (old_client_state != new_client_state) { if (not parent_) { JAMI_DBG("[call:%s] emit client call state change %s, code %d", id_.c_str(), new_client_state.c_str(), code); lock.unlock(); emitSignal<libjami::CallSignal::StateChange>(getAccountId(), id_, new_client_state, code); } } return true; } bool Call::setState(CallState call_state, signed code) { std::lock_guard lock(callMutex_); return setState(call_state, connectionState_, code); } bool Call::setState(ConnectionState cnx_state, signed code) { std::lock_guard lock(callMutex_); return setState(callState_, cnx_state, code); } std::string Call::getStateStr() const { using namespace libjami::Call; switch (getState()) { case CallState::ACTIVE: switch (getConnectionState()) { case ConnectionState::PROGRESSING: return StateEvent::CONNECTING; case ConnectionState::RINGING: return isIncoming() ? StateEvent::INCOMING : StateEvent::RINGING; case ConnectionState::DISCONNECTED: return StateEvent::HUNGUP; case ConnectionState::CONNECTED: default: return StateEvent::CURRENT; } case CallState::HOLD: if (getConnectionState() == ConnectionState::DISCONNECTED) return StateEvent::HUNGUP; return StateEvent::HOLD; case CallState::BUSY: return StateEvent::BUSY; case CallState::PEER_BUSY: return StateEvent::PEER_BUSY; case CallState::INACTIVE: switch (getConnectionState()) { case ConnectionState::PROGRESSING: return StateEvent::CONNECTING; case ConnectionState::RINGING: return isIncoming() ? StateEvent::INCOMING : StateEvent::RINGING; case ConnectionState::CONNECTED: return StateEvent::CURRENT; default: return StateEvent::INACTIVE; } case CallState::OVER: return StateEvent::OVER; case CallState::MERROR: default: return StateEvent::FAILURE; } } bool Call::toggleRecording() { const bool startRecording = Recordable::toggleRecording(); return startRecording; } std::map<std::string, std::string> Call::getDetails() const { auto conference = conf_.lock(); return { {libjami::Call::Details::CALL_TYPE, std::to_string((unsigned) type_)}, {libjami::Call::Details::PEER_NUMBER, peerNumber_}, {libjami::Call::Details::DISPLAY_NAME, peerDisplayName_}, {libjami::Call::Details::CALL_STATE, getStateStr()}, {libjami::Call::Details::CONF_ID, conference ? conference->getConfId() : ""}, {libjami::Call::Details::TIMESTAMP_START, std::to_string(timestamp_start_)}, {libjami::Call::Details::ACCOUNTID, getAccountId()}, {libjami::Call::Details::TO_USERNAME, toUsername()}, {libjami::Call::Details::AUDIO_MUTED, std::string(bool_to_str(isCaptureDeviceMuted(MediaType::MEDIA_AUDIO)))}, {libjami::Call::Details::VIDEO_MUTED, std::string(bool_to_str(isCaptureDeviceMuted(MediaType::MEDIA_VIDEO)))}, {libjami::Call::Details::AUDIO_ONLY, std::string(bool_to_str(not hasVideo()))}, }; } void Call::onTextMessage(std::map<std::string, std::string>&& messages) { auto it = messages.find("application/confInfo+json"); if (it != messages.end()) { setConferenceInfo(it->second); return; } it = messages.find("application/confOrder+json"); if (it != messages.end()) { if (auto conf = conf_.lock()) conf->onConfOrder(getCallId(), it->second); return; } { std::lock_guard lk {callMutex_}; if (parent_) { pendingInMessages_.emplace_back(std::move(messages), ""); return; } } #ifdef ENABLE_PLUGIN auto& pluginChatManager = Manager::instance().getJamiPluginManager().getChatServicesManager(); if (pluginChatManager.hasHandlers()) { pluginChatManager.publishMessage( std::make_shared<JamiMessage>(getAccountId(), getPeerNumber(), true, messages, false)); } #endif Manager::instance().incomingMessage(getAccountId(), getCallId(), getPeerNumber(), messages); } void Call::peerHungup() { const auto state = getState(); const auto aborted = state == CallState::ACTIVE or state == CallState::HOLD; setState(ConnectionState::DISCONNECTED, aborted ? ECONNABORTED : ECONNREFUSED); } void Call::addSubCall(Call& subcall) { std::lock_guard lk {callMutex_}; // Add subCall only if call is not connected or terminated // Because we only want to addSubCall if the peer didn't answer // So till it's <= RINGING if (connectionState_ == ConnectionState::CONNECTED || connectionState_ == ConnectionState::DISCONNECTED || callState_ == CallState::OVER) { subcall.removeCall(); return; } if (not subcalls_.emplace(getPtr(subcall)).second) { JAMI_ERR("[call:%s] add twice subcall %s", getCallId().c_str(), subcall.getCallId().c_str()); return; } JAMI_DBG("[call:%s] add subcall %s", getCallId().c_str(), subcall.getCallId().c_str()); subcall.parent_ = getPtr(*this); for (const auto& msg : pendingOutMessages_) subcall.sendTextMessage(msg.first, msg.second); subcall.addStateListener( [sub = subcall.weak(), parent = weak()](Call::CallState new_state, Call::ConnectionState new_cstate, int /* code */) { runOnMainThread([sub, parent, new_state, new_cstate]() { if (auto p = parent.lock()) { if (auto s = sub.lock()) { p->subcallStateChanged(*s, new_state, new_cstate); } } }); return true; }); } /// Called by a subcall when its states change (multidevice) /// /// Its purpose is to manage per device call and try to found the first responding. /// Parent call states are managed by these subcalls. /// \note this method may decrease the given \a subcall ref count. void Call::subcallStateChanged(Call& subcall, Call::CallState new_state, Call::ConnectionState new_cstate) { { // This condition happens when a subcall hangups/fails after removed from parent's list. // This is normal to keep parent_ != nullptr on the subcall, as it's the way to flag it // as an subcall and not a master call. // XXX: having a way to unsubscribe the state listener could be better than such test std::lock_guard lk {callMutex_}; auto sit = subcalls_.find(getPtr(subcall)); if (sit == subcalls_.end()) return; } // We found a responding device: hangup all other subcalls and merge if (new_state == CallState::ACTIVE and new_cstate == ConnectionState::CONNECTED) { JAMI_DBG("[call:%s] subcall %s answered by peer", getCallId().c_str(), subcall.getCallId().c_str()); hangupCallsIf(safePopSubcalls(), 0, [&](const Call* call) { return call != &subcall; }); merge(subcall); Manager::instance().peerAnsweredCall(*this); return; } // Hangup the call if any device hangup or send busy if ((new_state == CallState::ACTIVE or new_state == CallState::PEER_BUSY) and new_cstate == ConnectionState::DISCONNECTED) { JAMI_WARN("[call:%s] subcall %s hangup by peer", getCallId().c_str(), subcall.getCallId().c_str()); reason_ = new_state == CallState::ACTIVE ? "declined" : "busy"; hangupCalls(safePopSubcalls(), 0); Manager::instance().peerHungupCall(*this); removeCall(); return; } // Subcall is busy or failed if (new_state >= CallState::BUSY) { if (new_state == CallState::BUSY || new_state == CallState::PEER_BUSY) JAMI_WARN("[call:%s] subcall %s busy", getCallId().c_str(), subcall.getCallId().c_str()); else JAMI_WARN("[call:%s] subcall %s failed", getCallId().c_str(), subcall.getCallId().c_str()); std::lock_guard lk {callMutex_}; subcalls_.erase(getPtr(subcall)); // Parent call fails if last subcall is busy or failed if (subcalls_.empty()) { if (new_state == CallState::BUSY) { setState(CallState::BUSY, ConnectionState::DISCONNECTED, static_cast<int>(std::errc::device_or_resource_busy)); } else if (new_state == CallState::PEER_BUSY) { setState(CallState::PEER_BUSY, ConnectionState::DISCONNECTED, static_cast<int>(std::errc::device_or_resource_busy)); } else { // XXX: first idea was to use std::errc::host_unreachable, but it's not available on // some platforms like mingw. setState(CallState::MERROR, ConnectionState::DISCONNECTED, static_cast<int>(std::errc::io_error)); } removeCall(); } else { JAMI_DBG("[call:%s] remains %zu subcall(s)", getCallId().c_str(), subcalls_.size()); } return; } // Copy call/cnx states (forward only) if (new_state == CallState::ACTIVE && callState_ == CallState::INACTIVE) { setState(new_state); } if (static_cast<unsigned>(connectionState_) < static_cast<unsigned>(new_cstate) and static_cast<unsigned>(new_cstate) <= static_cast<unsigned>(ConnectionState::RINGING)) { setState(new_cstate); } } /// Replace current call data with ones from the given \a subcall. /// Must be called while locked by subclass void Call::merge(Call& subcall) { JAMI_DBG("[call:%s] merge subcall %s", getCallId().c_str(), subcall.getCallId().c_str()); // Merge data pendingInMessages_ = std::move(subcall.pendingInMessages_); if (peerNumber_.empty()) peerNumber_ = std::move(subcall.peerNumber_); peerDisplayName_ = std::move(subcall.peerDisplayName_); setState(subcall.getState(), subcall.getConnectionState()); std::weak_ptr<Call> subCallWeak = subcall.shared_from_this(); runOnMainThread([subCallWeak] { if (auto subcall = subCallWeak.lock()) subcall->removeCall(); }); } /// Handle pending IM message /// /// Used in multi-device context to send pending IM when the master call is connected. void Call::checkPendingIM() { std::lock_guard lk {callMutex_}; auto state = getStateStr(); // Let parent call handles IM after the merge if (not parent_) { if (state == libjami::Call::StateEvent::CURRENT) { for (const auto& msg : pendingInMessages_) Manager::instance().incomingMessage(getAccountId(), getCallId(), getPeerNumber(), msg.first); pendingInMessages_.clear(); std::weak_ptr<Call> callWkPtr = shared_from_this(); runOnMainThread([callWkPtr, pending = std::move(pendingOutMessages_)] { if (auto call = callWkPtr.lock()) for (const auto& msg : pending) call->sendTextMessage(msg.first, msg.second); }); } } } /// Handle tones for RINGING and BUSY calls /// void Call::checkAudio() { using namespace libjami::Call; auto state = getStateStr(); if (state == StateEvent::RINGING) { Manager::instance().peerRingingCall(*this); } else if (state == StateEvent::BUSY) { Manager::instance().callBusy(*this); } } // Helper to safely pop subcalls list Call::SubcallSet Call::safePopSubcalls() { std::lock_guard lk {callMutex_}; // std::exchange is C++14 auto old_value = std::move(subcalls_); subcalls_.clear(); return old_value; } void Call::setConferenceInfo(const std::string& msg) { ConfInfo newInfo; Json::Value json; std::string err; Json::CharReaderBuilder rbuilder; auto reader = std::unique_ptr<Json::CharReader>(rbuilder.newCharReader()); if (reader->parse(msg.data(), msg.data() + msg.size(), &json, &err)) { if (json.isObject()) { // new confInfo if (json.isMember("p")) { for (const auto& participantInfo : json["p"]) { ParticipantInfo pInfo; if (!participantInfo.isMember("uri")) continue; pInfo.fromJson(participantInfo); newInfo.emplace_back(pInfo); } } if (json.isMember("v")) { newInfo.v = json["v"].asInt(); peerConfProtocol_ = newInfo.v; } if (json.isMember("w")) newInfo.w = json["w"].asInt(); if (json.isMember("h")) newInfo.h = json["h"].asInt(); } else { // old confInfo for (const auto& participantInfo : json) { ParticipantInfo pInfo; if (!participantInfo.isMember("uri")) continue; pInfo.fromJson(participantInfo); newInfo.emplace_back(pInfo); } } } { std::lock_guard lk(confInfoMutex_); if (not isConferenceParticipant()) { // confID_ empty -> participant set confInfo with the received one confInfo_ = std::move(newInfo); // Create sink for each participant #ifdef ENABLE_VIDEO createSinks(confInfo_); #endif // Inform client that layout has changed jami::emitSignal<libjami::CallSignal::OnConferenceInfosUpdated>( id_, confInfo_.toVectorMapStringString()); } else if (auto conf = conf_.lock()) { conf->mergeConfInfo(newInfo, getPeerNumber()); } } } void Call::sendConfOrder(const Json::Value& root) { std::map<std::string, std::string> messages; Json::StreamWriterBuilder wbuilder; wbuilder["commentStyle"] = "None"; wbuilder["indentation"] = ""; messages["application/confOrder+json"] = Json::writeString(wbuilder, root); auto w = getAccount(); auto account = w.lock(); if (account) sendTextMessage(messages, account->getFromUri()); } void Call::sendConfInfo(const std::string& json) { std::map<std::string, std::string> messages; Json::StreamWriterBuilder wbuilder; wbuilder["commentStyle"] = "None"; wbuilder["indentation"] = ""; messages["application/confInfo+json"] = json; auto w = getAccount(); auto account = w.lock(); if (account) sendTextMessage(messages, account->getFromUri()); } void Call::resetConfInfo() { sendConfInfo("{}"); } } // namespace jami
23,804
C++
.cpp
642
28.626168
109
0.59571
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,703
conference.cpp
savoirfairelinux_jami-daemon/src/conference.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <regex> #include <sstream> #include "conference.h" #include "manager.h" #include "audio/audiolayer.h" #include "jamidht/jamiaccount.h" #include "string_utils.h" #include "sip/siptransport.h" #include "client/videomanager.h" #include "tracepoint.h" #ifdef ENABLE_VIDEO #include "call.h" #include "video/video_input.h" #include "video/video_mixer.h" #endif #ifdef ENABLE_PLUGIN #include "plugin/jamipluginmanager.h" #endif #include "call_factory.h" #include "logger.h" #include "jami/media_const.h" #include "audio/ringbufferpool.h" #include "sip/sipcall.h" #include <opendht/thread_pool.h> using namespace std::literals; namespace jami { Conference::Conference(const std::shared_ptr<Account>& account, const std::string& confId) : id_(confId.empty() ? Manager::instance().callFactory.getNewCallID() : confId) , account_(account) #ifdef ENABLE_VIDEO , videoEnabled_(account->isVideoEnabled()) #endif { JAMI_LOG("Create new conference {}", id_); duration_start_ = clock::now(); #ifdef ENABLE_VIDEO videoMixer_ = std::make_shared<video::VideoMixer>(id_); videoMixer_->setOnSourcesUpdated([this](std::vector<video::SourceInfo>&& infos) { runOnMainThread([w = weak(), infos = std::move(infos)] { auto shared = w.lock(); if (!shared) return; auto acc = std::dynamic_pointer_cast<JamiAccount>(shared->account_.lock()); if (!acc) return; ConfInfo newInfo; { std::lock_guard lock(shared->confInfoMutex_); newInfo.w = shared->confInfo_.w; newInfo.h = shared->confInfo_.h; newInfo.layout = shared->confInfo_.layout; } auto hostAdded = false; // Handle participants showing their video for (const auto& info : infos) { std::string uri {}; bool isLocalMuted = false, isPeerRecording = false; std::string deviceId {}; auto active = false; if (!info.callId.empty()) { std::string callId = info.callId; if (auto call = std::dynamic_pointer_cast<SIPCall>(getCall(callId))) { uri = call->getPeerNumber(); isLocalMuted = call->isPeerMuted(); isPeerRecording = call->isPeerRecording(); if (auto* transport = call->getTransport()) deviceId = transport->deviceId(); } std::string_view peerId = string_remove_suffix(uri, '@'); auto isModerator = shared->isModerator(peerId); auto isHandRaised = shared->isHandRaised(deviceId); auto isModeratorMuted = shared->isMuted(callId); auto isVoiceActive = shared->isVoiceActive(info.streamId); if (auto videoMixer = shared->videoMixer_) active = videoMixer->verifyActive(info.streamId); newInfo.emplace_back(ParticipantInfo {std::move(uri), deviceId, std::move(info.streamId), active, info.x, info.y, info.w, info.h, !info.hasVideo, isLocalMuted, isModeratorMuted, isModerator, isHandRaised, isVoiceActive, isPeerRecording}); } else { auto isModeratorMuted = false; // If not local auto streamInfo = shared->videoMixer_->streamInfo(info.source); std::string streamId = streamInfo.streamId; if (!streamId.empty()) { // Retrieve calls participants // TODO: this is a first version, we assume that the peer is not // a master of a conference and there is only one remote // In the future, we should retrieve confInfo from the call // To merge layout information isModeratorMuted = shared->isMuted(streamId); if (auto videoMixer = shared->videoMixer_) active = videoMixer->verifyActive(streamId); if (auto call = std::dynamic_pointer_cast<SIPCall>( getCall(streamInfo.callId))) { uri = call->getPeerNumber(); isLocalMuted = call->isPeerMuted(); isPeerRecording = call->isPeerRecording(); if (auto* transport = call->getTransport()) deviceId = transport->deviceId(); } } else { streamId = sip_utils::streamId("", sip_utils::DEFAULT_VIDEO_STREAMID); if (auto videoMixer = shared->videoMixer_) active = videoMixer->verifyActive(streamId); } std::string_view peerId = string_remove_suffix(uri, '@'); auto isModerator = shared->isModerator(peerId); if (uri.empty() && !hostAdded) { hostAdded = true; peerId = "host"sv; deviceId = acc->currentDeviceId(); isLocalMuted = shared->isMediaSourceMuted(MediaType::MEDIA_AUDIO); isPeerRecording = shared->isRecording(); } auto isHandRaised = shared->isHandRaised(deviceId); auto isVoiceActive = shared->isVoiceActive(streamId); newInfo.emplace_back(ParticipantInfo {std::move(uri), deviceId, std::move(streamId), active, info.x, info.y, info.w, info.h, !info.hasVideo, isLocalMuted, isModeratorMuted, isModerator, isHandRaised, isVoiceActive, isPeerRecording}); } } if (auto videoMixer = shared->videoMixer_) { newInfo.h = videoMixer->getHeight(); newInfo.w = videoMixer->getWidth(); } if (!hostAdded) { ParticipantInfo pi; pi.videoMuted = true; pi.audioLocalMuted = shared->isMediaSourceMuted(MediaType::MEDIA_AUDIO); pi.isModerator = true; newInfo.emplace_back(pi); } shared->updateConferenceInfo(std::move(newInfo)); }); }); auto conf_res = split_string_to_unsigned(jami::Manager::instance() .videoPreferences.getConferenceResolution(), 'x'); if (conf_res.size() == 2u) { #if defined(__APPLE__) && TARGET_OS_MAC videoMixer_->setParameters(conf_res[0], conf_res[1], AV_PIX_FMT_NV12); #else videoMixer_->setParameters(conf_res[0], conf_res[1]); #endif } else { JAMI_ERR("Conference resolution is invalid"); } #endif parser_.onVersion([&](uint32_t) {}); // TODO parser_.onCheckAuthorization([&](std::string_view peerId) { return isModerator(peerId); }); parser_.onHangupParticipant([&](const auto& accountUri, const auto& deviceId) { hangupParticipant(accountUri, deviceId); }); parser_.onRaiseHand([&](const auto& deviceId, bool state) { setHandRaised(deviceId, state); }); parser_.onSetActiveStream( [&](const auto& streamId, bool state) { setActiveStream(streamId, state); }); parser_.onMuteStreamAudio( [&](const auto& accountUri, const auto& deviceId, const auto& streamId, bool state) { muteStream(accountUri, deviceId, streamId, state); }); parser_.onSetLayout([&](int layout) { setLayout(layout); }); // Version 0, deprecated parser_.onKickParticipant([&](const auto& participantId) { hangupParticipant(participantId); }); parser_.onSetActiveParticipant( [&](const auto& participantId) { setActiveParticipant(participantId); }); parser_.onMuteParticipant( [&](const auto& participantId, bool state) { muteParticipant(participantId, state); }); parser_.onRaiseHandUri([&](const auto& uri, bool state) { if (auto call = std::dynamic_pointer_cast<SIPCall>(getCallFromPeerID(uri))) if (auto* transport = call->getTransport()) setHandRaised(std::string(transport->deviceId()), state); }); parser_.onVoiceActivity( [&](const auto& streamId, bool state) { setVoiceActivity(streamId, state); }); jami_tracepoint(conference_begin, id_.c_str()); } Conference::~Conference() { JAMI_INFO("Destroying conference %s", id_.c_str()); #ifdef ENABLE_VIDEO foreachCall([&](auto call) { call->exitConference(); // Reset distant callInfo call->resetConfInfo(); // Trigger the SIP negotiation to update the resolution for the remaining call // ideally this sould be done without renegotiation call->switchInput( Manager::instance().getVideoManager().videoDeviceMonitor.getMRLForDefaultDevice()); // Continue the recording for the call if the conference was recorded if (isRecording()) { JAMI_DEBUG("Stop recording for conf {:s}", getConfId()); toggleRecording(); if (not call->isRecording()) { JAMI_DEBUG("Conference was recorded, start recording for conf {:s}", call->getCallId()); call->toggleRecording(); } } // Notify that the remaining peer is still recording after conference if (call->isPeerRecording()) call->peerRecording(true); }); if (videoMixer_) { auto& sink = videoMixer_->getSink(); for (auto it = confSinksMap_.begin(); it != confSinksMap_.end();) { sink->detach(it->second.get()); it->second->stop(); it = confSinksMap_.erase(it); } } #endif // ENABLE_VIDEO #ifdef ENABLE_PLUGIN { std::lock_guard lk(avStreamsMtx_); jami::Manager::instance() .getJamiPluginManager() .getCallServicesManager() .clearCallHandlerMaps(getConfId()); Manager::instance().getJamiPluginManager().getCallServicesManager().clearAVSubject( getConfId()); confAVStreams.clear(); } #endif // ENABLE_PLUGIN if (shutdownCb_) shutdownCb_(getDuration().count()); // do not propagate sharing from conf host to calls closeMediaPlayer(mediaPlayerId_); jami_tracepoint(conference_end, id_.c_str()); } Conference::State Conference::getState() const { return confState_; } void Conference::setState(State state) { JAMI_DEBUG("[conf {:s}] Set state to [{:s}] (was [{:s}])", id_, getStateStr(state), getStateStr()); confState_ = state; } void Conference::initSourcesForHost() { hostSources_.clear(); // Setup local audio source MediaAttribute audioAttr; if (confState_ == State::ACTIVE_ATTACHED) { audioAttr = {MediaType::MEDIA_AUDIO, false, false, true, {}, sip_utils::DEFAULT_AUDIO_STREAMID}; } JAMI_DEBUG("[conf {:s}] Setting local host audio source to [{:s}]", id_, audioAttr.toString()); hostSources_.emplace_back(audioAttr); #ifdef ENABLE_VIDEO if (isVideoEnabled()) { MediaAttribute videoAttr; // Setup local video source if (confState_ == State::ACTIVE_ATTACHED) { videoAttr = {MediaType::MEDIA_VIDEO, false, false, true, Manager::instance().getVideoManager().videoDeviceMonitor.getMRLForDefaultDevice(), sip_utils::DEFAULT_VIDEO_STREAMID}; } JAMI_DEBUG("[conf {:s}] Setting local host video source to [{:s}]", id_, videoAttr.toString()); hostSources_.emplace_back(videoAttr); } #endif reportMediaNegotiationStatus(); } void Conference::reportMediaNegotiationStatus() { emitSignal<libjami::CallSignal::MediaNegotiationStatus>( getConfId(), libjami::Media::MediaNegotiationStatusEvents::NEGOTIATION_SUCCESS, currentMediaList()); } std::vector<std::map<std::string, std::string>> Conference::currentMediaList() const { return MediaAttribute::mediaAttributesToMediaMaps(hostSources_); } #ifdef ENABLE_PLUGIN void Conference::createConfAVStreams() { std::string accountId = getAccountId(); auto audioMap = [](const std::shared_ptr<jami::MediaFrame>& m) -> AVFrame* { return std::static_pointer_cast<AudioFrame>(m)->pointer(); }; // Preview and Received if ((audioMixer_ = jami::getAudioInput(getConfId()))) { auto audioSubject = std::make_shared<MediaStreamSubject>(audioMap); StreamData previewStreamData {getConfId(), false, StreamType::audio, getConfId(), accountId}; createConfAVStream(previewStreamData, *audioMixer_, audioSubject); StreamData receivedStreamData {getConfId(), true, StreamType::audio, getConfId(), accountId}; createConfAVStream(receivedStreamData, *audioMixer_, audioSubject); } #ifdef ENABLE_VIDEO if (videoMixer_) { // Review auto receiveSubject = std::make_shared<MediaStreamSubject>(pluginVideoMap_); StreamData receiveStreamData {getConfId(), true, StreamType::video, getConfId(), accountId}; createConfAVStream(receiveStreamData, *videoMixer_, receiveSubject); // Preview if (auto videoPreview = videoMixer_->getVideoLocal()) { auto previewSubject = std::make_shared<MediaStreamSubject>(pluginVideoMap_); StreamData previewStreamData {getConfId(), false, StreamType::video, getConfId(), accountId}; createConfAVStream(previewStreamData, *videoPreview, previewSubject); } } #endif // ENABLE_VIDEO } void Conference::createConfAVStream(const StreamData& StreamData, AVMediaStream& streamSource, const std::shared_ptr<MediaStreamSubject>& mediaStreamSubject, bool force) { std::lock_guard lk(avStreamsMtx_); const std::string AVStreamId = StreamData.id + std::to_string(static_cast<int>(StreamData.type)) + std::to_string(StreamData.direction); auto it = confAVStreams.find(AVStreamId); if (!force && it != confAVStreams.end()) return; confAVStreams.erase(AVStreamId); confAVStreams[AVStreamId] = mediaStreamSubject; streamSource.attachPriorityObserver(mediaStreamSubject); jami::Manager::instance() .getJamiPluginManager() .getCallServicesManager() .createAVSubject(StreamData, mediaStreamSubject); } #endif // ENABLE_PLUGIN void Conference::setLocalHostMuteState(MediaType type, bool muted) { for (auto& source : hostSources_) if (source.type_ == type) source.muted_ = muted; } bool Conference::isMediaSourceMuted(MediaType type) const { if (getState() != State::ACTIVE_ATTACHED) { // Assume muted if not attached. return true; } if (type != MediaType::MEDIA_AUDIO and type != MediaType::MEDIA_VIDEO) { JAMI_ERR("Unsupported media type"); return true; } // if one is muted, then consider that all are for (const auto& source : hostSources_) { if (source.muted_ && source.type_ == type) return true; if (source.type_ == MediaType::MEDIA_NONE) { JAMI_WARN("The host source for %s is not set. The mute state is meaningless", source.mediaTypeToString(source.type_)); // Assume muted if the media is not present. return true; } } return false; } void Conference::takeOverMediaSourceControl(const std::string& callId) { auto call = getCall(callId); if (not call) { JAMI_ERR("No call matches participant %s", callId.c_str()); return; } auto account = call->getAccount().lock(); if (not account) { JAMI_ERR("No account detected for call %s", callId.c_str()); return; } auto mediaList = call->getMediaAttributeList(); std::vector<MediaType> mediaTypeList {MediaType::MEDIA_AUDIO, MediaType::MEDIA_VIDEO}; for (auto mediaType : mediaTypeList) { // Try to find a media with a valid source type auto check = [mediaType](auto const& mediaAttr) { return (mediaAttr.type_ == mediaType); }; auto iter = std::find_if(mediaList.begin(), mediaList.end(), check); if (iter == mediaList.end()) { // Nothing to do if the call does not have a stream with // the requested media. JAMI_DEBUG("[Call: {:s}] Does not have an active [{:s}] media source", callId, MediaAttribute::mediaTypeToString(mediaType)); continue; } if (getState() == State::ACTIVE_ATTACHED) { // To mute the local source, all the sources of the participating // calls must be muted. If it's the first participant, just use // its mute state. if (subCalls_.size() == 1) { setLocalHostMuteState(iter->type_, iter->muted_); } else { setLocalHostMuteState(iter->type_, iter->muted_ or isMediaSourceMuted(iter->type_)); } } } // Update the media states in the newly added call. call->requestMediaChange(MediaAttribute::mediaAttributesToMediaMaps(mediaList)); // Notify the client for (auto mediaType : mediaTypeList) { if (mediaType == MediaType::MEDIA_AUDIO) { bool muted = isMediaSourceMuted(MediaType::MEDIA_AUDIO); JAMI_WARN("Take over [AUDIO] control from call %s - current local source state [%s]", callId.c_str(), muted ? "muted" : "un-muted"); emitSignal<libjami::CallSignal::AudioMuted>(id_, muted); } else { bool muted = isMediaSourceMuted(MediaType::MEDIA_VIDEO); JAMI_WARN("Take over [VIDEO] control from call %s - current local source state [%s]", callId.c_str(), muted ? "muted" : "un-muted"); emitSignal<libjami::CallSignal::VideoMuted>(id_, muted); } } } bool Conference::requestMediaChange(const std::vector<libjami::MediaMap>& mediaList) { if (getState() != State::ACTIVE_ATTACHED) { JAMI_ERROR("[conf {}] Request media change can be performed only in attached mode", getConfId()); return false; } JAMI_DEBUG("[conf {:s}] Request media change", getConfId()); auto mediaAttrList = MediaAttribute::buildMediaAttributesList(mediaList, false); bool hasFileSharing {false}; for (const auto& media : mediaAttrList) { if (!media.enabled_ || media.sourceUri_.empty()) continue; // Supported MRL schemes static const std::string sep = libjami::Media::VideoProtocolPrefix::SEPARATOR; const auto pos = media.sourceUri_.find(sep); if (pos == std::string::npos) continue; const auto prefix = media.sourceUri_.substr(0, pos); if ((pos + sep.size()) >= media.sourceUri_.size()) continue; if (prefix == libjami::Media::VideoProtocolPrefix::FILE) { hasFileSharing = true; mediaPlayerId_ = media.sourceUri_; createMediaPlayer(mediaPlayerId_); } } if (!hasFileSharing) { closeMediaPlayer(mediaPlayerId_); mediaPlayerId_ = ""; } for (auto const& mediaAttr : mediaAttrList) { JAMI_DEBUG("[conf {:s}] New requested media: {:s}", getConfId(), mediaAttr.toString(true)); } std::vector<std::string> newVideoInputs; for (auto const& mediaAttr : mediaAttrList) { // Find media auto oldIdx = std::find_if(hostSources_.begin(), hostSources_.end(), [&](auto oldAttr) { return oldAttr.sourceUri_ == mediaAttr.sourceUri_ && oldAttr.type_ == mediaAttr.type_ && oldAttr.label_ == mediaAttr.label_; }); // If video, add to newVideoInputs #ifdef ENABLE_VIDEO if (mediaAttr.type_ == MediaType::MEDIA_VIDEO) { auto srcUri = mediaAttr.sourceUri_.empty() ? Manager::instance().getVideoManager().videoDeviceMonitor.getMRLForDefaultDevice() : mediaAttr.sourceUri_; newVideoInputs.emplace_back(srcUri); } else { #endif hostAudioInputs_[mediaAttr.label_] = jami::getAudioInput(mediaAttr.label_); #ifdef ENABLE_VIDEO } #endif if (oldIdx != hostSources_.end()) { // Check if muted status changes if (mediaAttr.muted_ != oldIdx->muted_) { // If the current media source is muted, just call un-mute, it // will set the new source as input. muteLocalHost(mediaAttr.muted_, mediaAttr.type_ == MediaType::MEDIA_AUDIO ? libjami::Media::Details::MEDIA_TYPE_AUDIO : libjami::Media::Details::MEDIA_TYPE_VIDEO); } } } #ifdef ENABLE_VIDEO if (videoMixer_) { if (newVideoInputs.empty()) { videoMixer_->addAudioOnlySource("", sip_utils::streamId("", sip_utils::DEFAULT_AUDIO_STREAMID)); } else { videoMixer_->switchInputs(newVideoInputs); } } #endif hostSources_ = mediaAttrList; // New medias if (!isMuted("host"sv) && !isMediaSourceMuted(MediaType::MEDIA_AUDIO)) bindHostAudio(); // It's host medias, so no need to negotiate anything, but inform the client. reportMediaNegotiationStatus(); return true; } void Conference::handleMediaChangeRequest(const std::shared_ptr<Call>& call, const std::vector<libjami::MediaMap>& remoteMediaList) { JAMI_DEBUG("Conf [{:s}] Answer to media change request", getConfId()); auto currentMediaList = hostSources_; #ifdef ENABLE_VIDEO // If the new media list has video, remove the participant from audioonlylist. auto remoteHasVideo = MediaAttribute::hasMediaType(MediaAttribute::buildMediaAttributesList(remoteMediaList, false), MediaType::MEDIA_VIDEO); if (videoMixer_ && remoteHasVideo) { auto callId = call->getCallId(); videoMixer_->removeAudioOnlySource( callId, std::string(sip_utils::streamId(callId, sip_utils::DEFAULT_AUDIO_STREAMID))); } #endif auto remoteList = remoteMediaList; for (auto it = remoteList.begin(); it != remoteList.end();) { if (it->at(libjami::Media::MediaAttributeKey::MUTED) == TRUE_STR or it->at(libjami::Media::MediaAttributeKey::ENABLED) == FALSE_STR) { it = remoteList.erase(it); } else { ++it; } } // Create minimum media list (ignore muted and disabled medias) std::vector<libjami::MediaMap> newMediaList; newMediaList.reserve(remoteMediaList.size()); for (auto const& media : currentMediaList) { if (media.enabled_ and not media.muted_) newMediaList.emplace_back(MediaAttribute::toMediaMap(media)); } for (auto idx = newMediaList.size(); idx < remoteMediaList.size(); idx++) newMediaList.emplace_back(remoteMediaList[idx]); // NOTE: // Since this is a conference, newly added media will be also // accepted. // This also means that if original call was an audio-only call, // the local camera will be enabled, unless the video is disabled // in the account settings. call->answerMediaChangeRequest(newMediaList); call->enterConference(shared_from_this()); } void Conference::addSubCall(const std::string& callId) { JAMI_DEBUG("Adding call {:s} to conference {:s}", callId, id_); jami_tracepoint(conference_add_participant, id_.c_str(), callId.c_str()); { std::lock_guard lk(subcallsMtx_); if (!subCalls_.insert(callId).second) return; } if (auto call = std::dynamic_pointer_cast<SIPCall>(getCall(callId))) { // Check if participant was muted before conference if (call->isPeerMuted()) participantsMuted_.emplace(call->getCallId()); // NOTE: // When a call joins a conference, the media source of the call // will be set to the output of the conference mixer. takeOverMediaSourceControl(callId); auto w = call->getAccount(); auto account = w.lock(); if (account) { // Add defined moderators for the account link to the call for (const auto& mod : account->getDefaultModerators()) { moderators_.emplace(mod); } // Check for localModeratorsEnabled preference if (account->isLocalModeratorsEnabled() && not localModAdded_) { auto accounts = jami::Manager::instance().getAllAccounts<JamiAccount>(); for (const auto& account : accounts) { moderators_.emplace(account->getUsername()); } localModAdded_ = true; } // Check for allModeratorEnabled preference if (account->isAllModerators()) moderators_.emplace(getRemoteId(call)); } #ifdef ENABLE_VIDEO // In conference, if a participant joins with an audio only // call, it must be listed in the audioonlylist. auto mediaList = call->getMediaAttributeList(); if (call->peerUri().find("swarm:") != 0) { // We're hosting so it's already ourself. if (videoMixer_ && not MediaAttribute::hasMediaType(mediaList, MediaType::MEDIA_VIDEO)) { videoMixer_->addAudioOnlySource(call->getCallId(), sip_utils::streamId(call->getCallId(), sip_utils::DEFAULT_AUDIO_STREAMID)); } } call->enterConference(shared_from_this()); // Continue the recording for the conference if one participant was recording if (call->isRecording()) { JAMI_DEBUG("Stop recording for call {:s}", call->getCallId()); call->toggleRecording(); if (not this->isRecording()) { JAMI_DEBUG("One participant was recording, start recording for conference {:s}", getConfId()); this->toggleRecording(); } } bindSubCallAudio(callId); #endif // ENABLE_VIDEO } else JAMI_ERROR("no call associate to participant {}", callId.c_str()); #ifdef ENABLE_PLUGIN createConfAVStreams(); #endif } void Conference::removeSubCall(const std::string& callId) { JAMI_DEBUG("Remove call {:s} in conference {:s}", callId, id_); { std::lock_guard lk(subcallsMtx_); if (!subCalls_.erase(callId)) return; } if (auto call = std::dynamic_pointer_cast<SIPCall>(getCall(callId))) { const auto& peerId = getRemoteId(call); participantsMuted_.erase(call->getCallId()); if (auto* transport = call->getTransport()) handsRaised_.erase(std::string(transport->deviceId())); #ifdef ENABLE_VIDEO if (videoMixer_) { for (auto const& rtpSession : call->getRtpSessionList()) { if (rtpSession->getMediaType() == MediaType::MEDIA_AUDIO) videoMixer_->removeAudioOnlySource(callId, rtpSession->streamId()); if (videoMixer_->verifyActive(rtpSession->streamId())) videoMixer_->resetActiveStream(); } } auto sinkId = getConfId() + peerId; unbindSubCallAudio(callId); call->exitConference(); if (call->isPeerRecording()) call->peerRecording(false); #endif // ENABLE_VIDEO } } void Conference::setActiveParticipant(const std::string& participant_id) { #ifdef ENABLE_VIDEO if (!videoMixer_) return; if (isHost(participant_id)) { videoMixer_->setActiveStream(sip_utils::streamId("", sip_utils::DEFAULT_VIDEO_STREAMID)); return; } if (auto call = getCallFromPeerID(participant_id)) { videoMixer_->setActiveStream( sip_utils::streamId(call->getCallId(), sip_utils::DEFAULT_VIDEO_STREAMID)); return; } auto remoteHost = findHostforRemoteParticipant(participant_id); if (not remoteHost.empty()) { // This logic will be handled client side JAMI_WARN("Change remote layout is not supported"); return; } // Unset active participant by default videoMixer_->resetActiveStream(); #endif } void Conference::setActiveStream(const std::string& streamId, bool state) { #ifdef ENABLE_VIDEO if (!videoMixer_) return; if (state) videoMixer_->setActiveStream(streamId); else videoMixer_->resetActiveStream(); #endif } void Conference::setLayout(int layout) { #ifdef ENABLE_VIDEO if (layout < 0 || layout > 2) { JAMI_ERR("Unknown layout %u", layout); return; } if (!videoMixer_) return; { std::lock_guard lk(confInfoMutex_); confInfo_.layout = layout; } videoMixer_->setVideoLayout(static_cast<video::Layout>(layout)); #endif } std::vector<std::map<std::string, std::string>> ConfInfo::toVectorMapStringString() const { std::vector<std::map<std::string, std::string>> infos; infos.reserve(size()); for (const auto& info : *this) infos.emplace_back(info.toMap()); return infos; } std::string ConfInfo::toString() const { Json::Value val = {}; for (const auto& info : *this) { val["p"].append(info.toJson()); } val["w"] = w; val["h"] = h; val["v"] = v; val["layout"] = layout; return Json::writeString(Json::StreamWriterBuilder {}, val); } void Conference::sendConferenceInfos() { // Inform calls that the layout has changed foreachCall([&](auto call) { // Produce specific JSON for each participant (2 separate accounts can host ... // a conference on a same device, the conference is not link to one account). auto w = call->getAccount(); auto account = w.lock(); if (!account) return; dht::ThreadPool::io().run( [call, confInfo = getConfInfoHostUri(account->getUsername() + "@ring.dht", call->getPeerNumber())] { call->sendConfInfo(confInfo.toString()); }); }); auto confInfo = getConfInfoHostUri("", ""); #ifdef ENABLE_VIDEO createSinks(confInfo); #endif // Inform client that layout has changed jami::emitSignal<libjami::CallSignal::OnConferenceInfosUpdated>(id_, confInfo .toVectorMapStringString()); } #ifdef ENABLE_VIDEO void Conference::createSinks(const ConfInfo& infos) { std::lock_guard lk(sinksMtx_); if (!videoMixer_) return; auto& sink = videoMixer_->getSink(); Manager::instance().createSinkClients(getConfId(), infos, {std::static_pointer_cast<video::VideoFrameActiveWriter>( sink)}, confSinksMap_); } #endif void Conference::attachHost(const std::vector<libjami::MediaMap>& mediaList) { JAMI_LOG("Attach local participant to conference {}", id_); if (getState() == State::ACTIVE_DETACHED) { setState(State::ACTIVE_ATTACHED); if (mediaList.empty()) { initSourcesForHost(); bindHostAudio(); #ifdef ENABLE_VIDEO if (videoMixer_) { std::vector<std::string> videoInputs; for (const auto& source : hostSources_) { if (source.type_ == MediaType::MEDIA_VIDEO) videoInputs.emplace_back(source.sourceUri_); } if (videoInputs.empty()) { videoMixer_->addAudioOnlySource("", sip_utils::streamId("", sip_utils::DEFAULT_AUDIO_STREAMID)); } else { videoMixer_->switchInputs(videoInputs); } } #endif } else { requestMediaChange(mediaList); } } else { JAMI_WARNING( "Invalid conference state in attach participant: current \"{}\" - expected \"{}\"", getStateStr(), "ACTIVE_DETACHED"); } } void Conference::detachHost() { JAMI_LOG("Detach local participant from conference {}", id_); if (getState() == State::ACTIVE_ATTACHED) { unbindHostAudio(); #ifdef ENABLE_VIDEO if (videoMixer_) videoMixer_->stopInputs(); #endif } else { JAMI_WARNING( "Invalid conference state in detach participant: current \"{}\" - expected \"{}\"", getStateStr(), "ACTIVE_ATTACHED"); return; } initSourcesForHost(); setState(State::ACTIVE_DETACHED); } CallIdSet Conference::getSubCalls() const { std::lock_guard lk(subcallsMtx_); return subCalls_; } bool Conference::toggleRecording() { bool newState = not isRecording(); if (newState) initRecorder(recorder_); else if (recorder_) deinitRecorder(recorder_); // Notify each participant foreachCall([&](auto call) { call->updateRecState(newState); }); auto res = Recordable::toggleRecording(); updateRecording(); return res; } std::string Conference::getAccountId() const { if (auto account = getAccount()) return account->getAccountID(); return {}; } void Conference::switchInput(const std::string& input) { #ifdef ENABLE_VIDEO JAMI_DEBUG("[Conf:{:s}] Setting video input to {:s}", id_, input); std::vector<MediaAttribute> newSources; auto firstVideo = true; // Rewrite hostSources (remove all except one video input) // This method is replaced by requestMediaChange for (auto& source : hostSources_) { if (source.type_ == MediaType::MEDIA_VIDEO) { if (firstVideo) { firstVideo = false; source.sourceUri_ = input; newSources.emplace_back(source); } } else { newSources.emplace_back(source); } } // Done if the video is disabled if (not isVideoEnabled()) return; if (auto mixer = videoMixer_) { mixer->switchInputs({input}); #ifdef ENABLE_PLUGIN // Preview if (auto videoPreview = mixer->getVideoLocal()) { auto previewSubject = std::make_shared<MediaStreamSubject>(pluginVideoMap_); StreamData previewStreamData {getConfId(), false, StreamType::video, getConfId(), getAccountId()}; createConfAVStream(previewStreamData, *videoPreview, previewSubject, true); } #endif } #endif } bool Conference::isVideoEnabled() const { if (auto shared = account_.lock()) return shared->isVideoEnabled(); return false; } #ifdef ENABLE_VIDEO std::shared_ptr<video::VideoMixer> Conference::getVideoMixer() { return videoMixer_; } std::string Conference::getVideoInput() const { for (const auto& source : hostSources_) { if (source.type_ == MediaType::MEDIA_VIDEO) return source.sourceUri_; } return {}; } #endif void Conference::initRecorder(std::shared_ptr<MediaRecorder>& rec) { #ifdef ENABLE_VIDEO // Video if (videoMixer_) { if (auto ob = rec->addStream(videoMixer_->getStream("v:mixer"))) { videoMixer_->attach(ob); } } #endif // Audio // Create ghost participant for ringbufferpool auto& rbPool = Manager::instance().getRingBufferPool(); ghostRingBuffer_ = rbPool.createRingBuffer(getConfId()); // Bind it to ringbufferpool in order to get the all mixed frames bindSubCallAudio(getConfId()); // Add stream to recorder audioMixer_ = jami::getAudioInput(getConfId()); if (auto ob = rec->addStream(audioMixer_->getInfo("a:mixer"))) { audioMixer_->attach(ob); } } void Conference::deinitRecorder(std::shared_ptr<MediaRecorder>& rec) { #ifdef ENABLE_VIDEO // Video if (videoMixer_) { if (auto ob = rec->getStream("v:mixer")) { videoMixer_->detach(ob); } } #endif // Audio if (auto ob = rec->getStream("a:mixer")) audioMixer_->detach(ob); audioMixer_.reset(); Manager::instance().getRingBufferPool().unBindAll(getConfId()); ghostRingBuffer_.reset(); } void Conference::onConfOrder(const std::string& callId, const std::string& confOrder) { // Check if the peer is a master if (auto call = getCall(callId)) { const auto& peerId = getRemoteId(call); std::string err; Json::Value root; Json::CharReaderBuilder rbuilder; auto reader = std::unique_ptr<Json::CharReader>(rbuilder.newCharReader()); if (!reader->parse(confOrder.c_str(), confOrder.c_str() + confOrder.size(), &root, &err)) { JAMI_WARN("Unable to parse conference order from %s", peerId.c_str()); return; } parser_.initData(std::move(root), peerId); parser_.parse(); } } std::shared_ptr<Call> Conference::getCall(const std::string& callId) { return Manager::instance().callFactory.getCall(callId); } bool Conference::isModerator(std::string_view uri) const { return moderators_.find(uri) != moderators_.end() or isHost(uri); } bool Conference::isHandRaised(std::string_view deviceId) const { return isHostDevice(deviceId) ? handsRaised_.find("host"sv) != handsRaised_.end() : handsRaised_.find(deviceId) != handsRaised_.end(); } void Conference::setHandRaised(const std::string& deviceId, const bool& state) { if (isHostDevice(deviceId)) { auto isPeerRequiringAttention = isHandRaised("host"sv); if (state and not isPeerRequiringAttention) { JAMI_DBG("Raise host hand"); handsRaised_.emplace("host"sv); updateHandsRaised(); } else if (not state and isPeerRequiringAttention) { JAMI_DBG("Lower host hand"); handsRaised_.erase("host"); updateHandsRaised(); } } else { for (const auto& p : getSubCalls()) { if (auto call = std::dynamic_pointer_cast<SIPCall>(getCall(p))) { auto isPeerRequiringAttention = isHandRaised(deviceId); std::string callDeviceId; if (auto* transport = call->getTransport()) callDeviceId = transport->deviceId(); if (deviceId == callDeviceId) { if (state and not isPeerRequiringAttention) { JAMI_DEBUG("Raise {:s} hand", deviceId); handsRaised_.emplace(deviceId); updateHandsRaised(); } else if (not state and isPeerRequiringAttention) { JAMI_DEBUG("Remove {:s} raised hand", deviceId); handsRaised_.erase(deviceId); updateHandsRaised(); } return; } } } JAMI_WARN("Fail to raise %s hand (participant not found)", deviceId.c_str()); } } bool Conference::isVoiceActive(std::string_view streamId) const { return streamsVoiceActive.find(streamId) != streamsVoiceActive.end(); } void Conference::setVoiceActivity(const std::string& streamId, const bool& newState) { // verify that streamID exists in our confInfo bool exists = false; for (auto& participant : confInfo_) { if (participant.sinkId == streamId) { exists = true; break; } } if (!exists) { JAMI_ERR("participant not found with streamId: %s", streamId.c_str()); return; } auto previousState = isVoiceActive(streamId); if (previousState == newState) { // no change, do not send out updates return; } if (newState and not previousState) { // voice going from inactive to active streamsVoiceActive.emplace(streamId); updateVoiceActivity(); return; } if (not newState and previousState) { // voice going from active to inactive streamsVoiceActive.erase(streamId); updateVoiceActivity(); return; } } void Conference::setModerator(const std::string& participant_id, const bool& state) { for (const auto& p : getSubCalls()) { if (auto call = getCall(p)) { auto isPeerModerator = isModerator(participant_id); if (participant_id == getRemoteId(call)) { if (state and not isPeerModerator) { JAMI_DEBUG("Add {:s} as moderator", participant_id); moderators_.emplace(participant_id); updateModerators(); } else if (not state and isPeerModerator) { JAMI_DEBUG("Remove {:s} as moderator", participant_id); moderators_.erase(participant_id); updateModerators(); } return; } } } JAMI_WARN("Fail to set %s as moderator (participant not found)", participant_id.c_str()); } void Conference::updateModerators() { std::lock_guard lk(confInfoMutex_); for (auto& info : confInfo_) { info.isModerator = isModerator(string_remove_suffix(info.uri, '@')); } sendConferenceInfos(); } void Conference::updateHandsRaised() { std::lock_guard lk(confInfoMutex_); for (auto& info : confInfo_) info.handRaised = isHandRaised(info.device); sendConferenceInfos(); } void Conference::updateVoiceActivity() { std::lock_guard lk(confInfoMutex_); // streamId is actually sinkId for (ParticipantInfo& participantInfo : confInfo_) { bool newActivity; if (auto call = getCallWith(std::string(string_remove_suffix(participantInfo.uri, '@')), participantInfo.device)) { // if this participant is in a direct call with us // grab voice activity info directly from the call newActivity = call->hasPeerVoice(); } else { // check for it newActivity = isVoiceActive(participantInfo.sinkId); } if (participantInfo.voiceActivity != newActivity) { participantInfo.voiceActivity = newActivity; } } sendConferenceInfos(); // also emits signal to client } void Conference::foreachCall(const std::function<void(const std::shared_ptr<Call>& call)>& cb) { for (const auto& p : getSubCalls()) if (auto call = getCall(p)) cb(call); } bool Conference::isMuted(std::string_view callId) const { return participantsMuted_.find(callId) != participantsMuted_.end(); } void Conference::muteStream(const std::string& accountUri, const std::string& deviceId, const std::string&, const bool& state) { if (auto acc = std::dynamic_pointer_cast<JamiAccount>(account_.lock())) { if (accountUri == acc->getUsername() && deviceId == acc->currentDeviceId()) { muteHost(state); } else if (auto call = getCallWith(accountUri, deviceId)) { muteCall(call->getCallId(), state); } else { JAMI_WARN("No call with %s - %s", accountUri.c_str(), deviceId.c_str()); } } } void Conference::muteHost(bool state) { auto isHostMuted = isMuted("host"sv); if (state and not isHostMuted) { participantsMuted_.emplace("host"sv); if (not isMediaSourceMuted(MediaType::MEDIA_AUDIO)) { JAMI_DBG("Mute host"); unbindHostAudio(); } } else if (not state and isHostMuted) { participantsMuted_.erase("host"); if (not isMediaSourceMuted(MediaType::MEDIA_AUDIO)) { JAMI_DBG("Unmute host"); bindHostAudio(); } } updateMuted(); } void Conference::muteCall(const std::string& callId, bool state) { auto isPartMuted = isMuted(callId); if (state and not isPartMuted) { JAMI_DEBUG("Mute participant {:s}", callId); participantsMuted_.emplace(callId); unbindSubCallAudio(callId); updateMuted(); } else if (not state and isPartMuted) { JAMI_DEBUG("Unmute participant {:s}", callId); participantsMuted_.erase(callId); bindSubCallAudio(callId); updateMuted(); } } void Conference::muteParticipant(const std::string& participant_id, const bool& state) { // Prioritize remote mute, otherwise the mute info is lost during // the conference merge (we don't send back info to remoteHost, // cf. getConfInfoHostUri method) // Transfert remote participant mute auto remoteHost = findHostforRemoteParticipant(participant_id); if (not remoteHost.empty()) { if (auto call = getCallFromPeerID(string_remove_suffix(remoteHost, '@'))) { auto w = call->getAccount(); auto account = w.lock(); if (!account) return; Json::Value root; root["muteParticipant"] = participant_id; root["muteState"] = state ? TRUE_STR : FALSE_STR; call->sendConfOrder(root); return; } } // NOTE: For now we have no way to mute only one stream if (isHost(participant_id)) muteHost(state); else if (auto call = getCallFromPeerID(participant_id)) muteCall(call->getCallId(), state); } void Conference::updateRecording() { std::lock_guard lk(confInfoMutex_); for (auto& info : confInfo_) { if (info.uri.empty()) { info.recording = isRecording(); } else if (auto call = getCallWith(std::string(string_remove_suffix(info.uri, '@')), info.device)) { info.recording = call->isPeerRecording(); } } sendConferenceInfos(); } void Conference::updateMuted() { std::lock_guard lk(confInfoMutex_); for (auto& info : confInfo_) { if (info.uri.empty()) { info.audioModeratorMuted = isMuted("host"sv); info.audioLocalMuted = isMediaSourceMuted(MediaType::MEDIA_AUDIO); } else if (auto call = getCallWith(std::string(string_remove_suffix(info.uri, '@')), info.device)) { info.audioModeratorMuted = isMuted(call->getCallId()); info.audioLocalMuted = call->isPeerMuted(); } } sendConferenceInfos(); } ConfInfo Conference::getConfInfoHostUri(std::string_view localHostURI, std::string_view destURI) { ConfInfo newInfo = confInfo_; for (auto it = newInfo.begin(); it != newInfo.end();) { bool isRemoteHost = remoteHosts_.find(it->uri) != remoteHosts_.end(); if (it->uri.empty() and not destURI.empty()) { // fill the empty uri with the local host URI, let void for local client it->uri = localHostURI; // If we're detached, remove the host if (getState() == State::ACTIVE_DETACHED) { it = newInfo.erase(it); continue; } } if (isRemoteHost) { // Don't send back the ParticipantInfo for remote Host // For other than remote Host, the new info is in remoteHosts_ it = newInfo.erase(it); } else { ++it; } } // Add remote Host info for (const auto& [hostUri, confInfo] : remoteHosts_) { // Add remote info for remote host destination // Example: ConfA, ConfB & ConfC // ConfA send ConfA and ConfB for ConfC // ConfA send ConfA and ConfC for ConfB // ... if (destURI != hostUri) newInfo.insert(newInfo.end(), confInfo.begin(), confInfo.end()); } return newInfo; } bool Conference::isHost(std::string_view uri) const { if (uri.empty()) return true; // Check if the URI is a local URI (AccountID) for at least one of the subcall // (a local URI can be in the call with another device) for (const auto& p : getSubCalls()) { if (auto call = getCall(p)) { if (auto account = call->getAccount().lock()) { if (account->getUsername() == uri) return true; } } } return false; } bool Conference::isHostDevice(std::string_view deviceId) const { if (auto acc = std::dynamic_pointer_cast<JamiAccount>(account_.lock())) return deviceId == acc->currentDeviceId(); return false; } void Conference::updateConferenceInfo(ConfInfo confInfo) { std::lock_guard lk(confInfoMutex_); confInfo_ = std::move(confInfo); sendConferenceInfos(); } void Conference::hangupParticipant(const std::string& accountUri, const std::string& deviceId) { if (auto acc = std::dynamic_pointer_cast<JamiAccount>(account_.lock())) { if (deviceId.empty()) { // If deviceId is empty, hangup all calls with device while (auto call = getCallFromPeerID(accountUri)) { Manager::instance().hangupCall(acc->getAccountID(), call->getCallId()); } return; } else { if (accountUri == acc->getUsername() && deviceId == acc->currentDeviceId()) { Manager::instance().detachHost(shared_from_this()); return; } else if (auto call = getCallWith(accountUri, deviceId)) { Manager::instance().hangupCall(acc->getAccountID(), call->getCallId()); return; } } // Else, it may be a remote host auto remoteHost = findHostforRemoteParticipant(accountUri, deviceId); if (remoteHost.empty()) { JAMI_WARN("Unable to hangup %s, peer not found", accountUri.c_str()); return; } if (auto call = getCallFromPeerID(string_remove_suffix(remoteHost, '@'))) { // Forward to the remote host. libjami::hangupParticipant(acc->getAccountID(), call->getCallId(), accountUri, deviceId); } } } void Conference::muteLocalHost(bool is_muted, const std::string& mediaType) { if (mediaType.compare(libjami::Media::Details::MEDIA_TYPE_AUDIO) == 0) { if (is_muted == isMediaSourceMuted(MediaType::MEDIA_AUDIO)) { JAMI_DEBUG("Local audio source already in [{:s}] state", is_muted ? "muted" : "un-muted"); return; } auto isHostMuted = isMuted("host"sv); if (is_muted and not isMediaSourceMuted(MediaType::MEDIA_AUDIO) and not isHostMuted) { JAMI_DBG("Muting local audio source"); unbindHostAudio(); } else if (not is_muted and isMediaSourceMuted(MediaType::MEDIA_AUDIO) and not isHostMuted) { JAMI_DBG("Un-muting local audio source"); bindHostAudio(); } setLocalHostMuteState(MediaType::MEDIA_AUDIO, is_muted); updateMuted(); emitSignal<libjami::CallSignal::AudioMuted>(id_, is_muted); return; } else if (mediaType.compare(libjami::Media::Details::MEDIA_TYPE_VIDEO) == 0) { #ifdef ENABLE_VIDEO if (not isVideoEnabled()) { JAMI_ERR("Unable to stop camera, the camera is disabled!"); return; } if (is_muted == isMediaSourceMuted(MediaType::MEDIA_VIDEO)) { JAMI_DEBUG("Local camera source already in [{:s}] state", is_muted ? "stopped" : "started"); return; } setLocalHostMuteState(MediaType::MEDIA_VIDEO, is_muted); if (is_muted) { if (auto mixer = videoMixer_) { JAMI_DBG("Stopping local camera sources"); mixer->stopInputs(); } } else { if (auto mixer = videoMixer_) { JAMI_DBG("Starting local camera sources"); std::vector<std::string> videoInputs; for (const auto& source : hostSources_) { if (source.type_ == MediaType::MEDIA_VIDEO) videoInputs.emplace_back(source.sourceUri_); } mixer->switchInputs(videoInputs); } } emitSignal<libjami::CallSignal::VideoMuted>(id_, is_muted); return; #endif } } #ifdef ENABLE_VIDEO void Conference::resizeRemoteParticipants(ConfInfo& confInfo, std::string_view peerURI) { int remoteFrameHeight = confInfo.h; int remoteFrameWidth = confInfo.w; if (remoteFrameHeight == 0 or remoteFrameWidth == 0) { // get the size of the remote frame from receiveThread // if the one from confInfo is empty if (auto call = std::dynamic_pointer_cast<SIPCall>( getCallFromPeerID(string_remove_suffix(peerURI, '@')))) { for (auto const& videoRtp : call->getRtpSessionList(MediaType::MEDIA_VIDEO)) { auto recv = std::static_pointer_cast<video::VideoRtpSession>(videoRtp) ->getVideoReceive(); remoteFrameHeight = recv->getHeight(); remoteFrameWidth = recv->getWidth(); // NOTE: this may be not the behavior we want, but this is only called // when we receive conferences information from a call, so the peer is // mixing the video and send only one stream, so we can break here break; } } } if (remoteFrameHeight == 0 or remoteFrameWidth == 0) { JAMI_WARN("Remote frame size not found."); return; } // get the size of the local frame ParticipantInfo localCell; for (const auto& p : confInfo_) { if (p.uri == peerURI) { localCell = p; break; } } const float zoomX = (float) remoteFrameWidth / localCell.w; const float zoomY = (float) remoteFrameHeight / localCell.h; // Do the resize for each remote participant for (auto& remoteCell : confInfo) { remoteCell.x = remoteCell.x / zoomX + localCell.x; remoteCell.y = remoteCell.y / zoomY + localCell.y; remoteCell.w = remoteCell.w / zoomX; remoteCell.h = remoteCell.h / zoomY; } } #endif void Conference::mergeConfInfo(ConfInfo& newInfo, const std::string& peerURI) { if (newInfo.empty()) { JAMI_DBG("confInfo empty, remove remoteHost"); std::lock_guard lk(confInfoMutex_); remoteHosts_.erase(peerURI); sendConferenceInfos(); return; } #ifdef ENABLE_VIDEO resizeRemoteParticipants(newInfo, peerURI); #endif bool updateNeeded = false; auto it = remoteHosts_.find(peerURI); if (it != remoteHosts_.end()) { // Compare confInfo before update if (it->second != newInfo) { it->second = newInfo; updateNeeded = true; } else JAMI_WARN("No change in confInfo, don't update"); } else { remoteHosts_.emplace(peerURI, newInfo); updateNeeded = true; } // Send confInfo only if needed to avoid loops #ifdef ENABLE_VIDEO if (updateNeeded and videoMixer_) { // Trigger the layout update in the mixer because the frame resolution may // change from participant to conference and cause a mismatch between // confInfo layout and rendering layout. videoMixer_->updateLayout(); } #endif } std::string_view Conference::findHostforRemoteParticipant(std::string_view uri, std::string_view deviceId) { for (const auto& host : remoteHosts_) { for (const auto& p : host.second) { if (uri == string_remove_suffix(p.uri, '@') && (deviceId == "" || deviceId == p.device)) return host.first; } } return ""; } std::shared_ptr<Call> Conference::getCallFromPeerID(std::string_view peerID) { for (const auto& p : getSubCalls()) { auto call = getCall(p); if (call && getRemoteId(call) == peerID) { return call; } } return nullptr; } std::shared_ptr<Call> Conference::getCallWith(const std::string& accountUri, const std::string& deviceId) { for (const auto& p : getSubCalls()) { if (auto call = std::dynamic_pointer_cast<SIPCall>(getCall(p))) { auto* transport = call->getTransport(); if (accountUri == string_remove_suffix(call->getPeerNumber(), '@') && transport && deviceId == transport->deviceId()) { return call; } } } return {}; } std::string Conference::getRemoteId(const std::shared_ptr<jami::Call>& call) const { if (auto* transport = std::dynamic_pointer_cast<SIPCall>(call)->getTransport()) if (auto cert = transport->getTlsInfos().peerCert) if (cert->issuer) return cert->issuer->getId().toString(); return {}; } void Conference::stopRecording() { Recordable::stopRecording(); updateRecording(); } bool Conference::startRecording(const std::string& path) { auto res = Recordable::startRecording(path); updateRecording(); return res; } /// PRIVATE void Conference::bindHostAudio() { JAMI_LOG("Bind host to conference {}", id_); auto& rbPool = Manager::instance().getRingBufferPool(); for (const auto& item : getSubCalls()) { if (auto call = getCall(item)) { auto medias = call->getAudioStreams(); for (const auto& [id, muted] : medias) { for (const auto& source : hostSources_) { if (source.type_ == MediaType::MEDIA_AUDIO) { // Start audio input auto hostAudioInput = hostAudioInputs_.find(source.label_); if (hostAudioInput == hostAudioInputs_.end()) { hostAudioInput = hostAudioInputs_ .emplace(source.label_, std::make_shared<AudioInput>(source.label_)) .first; } if (hostAudioInput != hostAudioInputs_.end()) { hostAudioInput->second->switchInput(source.sourceUri_); } // Bind audio if (source.label_ == sip_utils::DEFAULT_AUDIO_STREAMID) { rbPool.bindRingbuffers(id, RingBufferPool::DEFAULT_ID); } else { auto buffer = source.sourceUri_; static const std::string& sep = libjami::Media::VideoProtocolPrefix::SEPARATOR; const auto pos = source.sourceUri_.find(sep); if (pos != std::string::npos) buffer = source.sourceUri_.substr(pos + sep.size()); rbPool.bindRingbuffers(id, buffer); } } } rbPool.flush(id); } } } rbPool.flush(RingBufferPool::DEFAULT_ID); } void Conference::unbindHostAudio() { JAMI_LOG("Unbind host from conference {}", id_); for (const auto& source : hostSources_) { if (source.type_ == MediaType::MEDIA_AUDIO) { // Stop audio input auto hostAudioInput = hostAudioInputs_.find(source.label_); if (hostAudioInput != hostAudioInputs_.end()) { hostAudioInput->second->switchInput(""); } // Unbind audio if (source.label_ == sip_utils::DEFAULT_AUDIO_STREAMID) { Manager::instance().getRingBufferPool().unBindAllHalfDuplexOut(RingBufferPool::DEFAULT_ID); } else { auto buffer = source.sourceUri_; static const std::string& sep = libjami::Media::VideoProtocolPrefix::SEPARATOR; const auto pos = source.sourceUri_.find(sep); if (pos != std::string::npos) buffer = source.sourceUri_.substr(pos + sep.size()); Manager::instance().getRingBufferPool().unBindAllHalfDuplexOut(buffer); } } } } void Conference::bindSubCallAudio(const std::string& callId) { JAMI_LOG("Bind participant {} to conference {}", callId, id_); auto& rbPool = Manager::instance().getRingBufferPool(); // Bind each of the new participant's audio streams to each of the other participants audio streams if (auto participantCall = getCall(callId)) { auto participantStreams = participantCall->getAudioStreams(); for (auto stream : participantStreams) { for (const auto& other : getSubCalls()) { auto otherCall = other != callId ? getCall(other) : nullptr; if (otherCall) { auto otherStreams = otherCall->getAudioStreams(); for (auto otherStream : otherStreams) { if (isMuted(other)) rbPool.bindHalfDuplexOut(otherStream.first, stream.first); else rbPool.bindRingbuffers(stream.first, otherStream.first); rbPool.flush(otherStream.first); } } } // Bind local participant to other participants only if the // local is attached to the conference. if (getState() == State::ACTIVE_ATTACHED) { if (isMediaSourceMuted(MediaType::MEDIA_AUDIO)) rbPool.bindHalfDuplexOut(RingBufferPool::DEFAULT_ID, stream.first); else rbPool.bindRingbuffers(stream.first, RingBufferPool::DEFAULT_ID); rbPool.flush(RingBufferPool::DEFAULT_ID); } } } } void Conference::unbindSubCallAudio(const std::string& callId) { JAMI_LOG("Unbind participant {} from conference {}", callId, id_); if (auto call = getCall(callId)) { auto medias = call->getAudioStreams(); auto& rbPool = Manager::instance().getRingBufferPool(); for (const auto& [id, muted] : medias) { rbPool.unBindAllHalfDuplexOut(id); } } } } // namespace jami
66,130
C++
.cpp
1,699
28.728075
162
0.579275
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,704
threadloop.cpp
savoirfairelinux_jami-daemon/src/threadloop.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "threadloop.h" #include "logger.h" #include <ciso646> // fix windows compiler bug namespace jami { void ThreadLoop::mainloop(std::thread::id& tid, const std::function<bool()> setup, const std::function<void()> process, const std::function<void()> cleanup) { tid = std::this_thread::get_id(); try { if (setup()) { while (state_ == ThreadState::RUNNING) process(); cleanup(); } else { JAMI_ERR("setup failed"); } } catch (const ThreadLoopException& e) { JAMI_ERR("[threadloop:%p] ThreadLoopException: %s", this, e.what()); } catch (const std::exception& e) { JAMI_ERR("[threadloop:%p] Unwaited exception: %s", this, e.what()); } stop(); } ThreadLoop::ThreadLoop(const std::function<bool()>& setup, const std::function<void()>& process, const std::function<void()>& cleanup) : setup_(setup) , process_(process) , cleanup_(cleanup) , thread_() {} ThreadLoop::~ThreadLoop() { if (isRunning()) { JAMI_ERR("join() should be explicitly called in owner's destructor"); join(); } } void ThreadLoop::start() { const auto s = state_.load(); if (s == ThreadState::RUNNING) { JAMI_ERR("already started"); return; } // stop pending but not processed by thread yet? if (s == ThreadState::STOPPING and thread_.joinable()) { JAMI_DBG("stop pending"); thread_.join(); } state_ = ThreadState::RUNNING; thread_ = std::thread(&ThreadLoop::mainloop, this, std::ref(threadId_), setup_, process_, cleanup_); threadId_ = thread_.get_id(); } void ThreadLoop::stop() { auto expected = ThreadState::RUNNING; state_.compare_exchange_strong(expected, ThreadState::STOPPING); } void ThreadLoop::join() { stop(); if (thread_.joinable()) thread_.join(); } void ThreadLoop::waitForCompletion() { if (thread_.joinable()) thread_.join(); } void ThreadLoop::exit() { stop(); throw ThreadLoopException(); } bool ThreadLoop::isRunning() const noexcept { #ifdef _WIN32 return state_ == ThreadState::RUNNING; #else return thread_.joinable() and state_ == ThreadState::RUNNING; #endif } void InterruptedThreadLoop::stop() { ThreadLoop::stop(); cv_.notify_one(); } } // namespace jami
3,176
C++
.cpp
115
22.930435
104
0.638752
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,705
logger.cpp
savoirfairelinux_jami-daemon/src/logger.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <cstdio> #include <cstring> #include <cerrno> #include <ctime> #include <ciso646> // fix windows compiler bug #include "client/ring_signal.h" #include <fmt/core.h> #include <fmt/format.h> #include <fmt/compile.h> #ifdef _MSC_VER #include <sys_time.h> #else #include <sys/time.h> #endif #include <atomic> #include <condition_variable> #include <functional> #include <fstream> #include <string> #include <ios> #include <mutex> #include <thread> #include <array> #include "fileutils.h" #include "logger.h" #ifdef __linux__ #include <unistd.h> #include <syslog.h> #include <sys/syscall.h> #endif // __linux__ #ifdef __ANDROID__ #ifndef APP_NAME #define APP_NAME "libjami" #endif /* APP_NAME */ #endif #define END_COLOR "\033[0m" #ifndef _WIN32 #define RED "\033[22;31m" #define YELLOW "\033[01;33m" #define CYAN "\033[22;36m" #else #define FOREGROUND_WHITE 0x000f #define RED FOREGROUND_RED + 0x0008 #define YELLOW FOREGROUND_RED + FOREGROUND_GREEN + 0x0008 #define CYAN FOREGROUND_BLUE + FOREGROUND_GREEN + 0x0008 #define LIGHT_GREEN FOREGROUND_GREEN + 0x0008 #endif // _WIN32 #define LOGFILE "jami" namespace jami { static constexpr auto ENDL = '\n'; #ifndef __GLIBC__ static const char* check_error(int result, char* buffer) { switch (result) { case 0: return buffer; case ERANGE: /* should never happen */ return "unknown (too big to display)"; default: return "unknown (invalid error number)"; } } static const char* check_error(char* result, char*) { return result; } #endif void strErr() { #ifdef __GLIBC__ JAMI_ERR("%m"); #else char buf[1000]; JAMI_ERR("%s", check_error(strerror_r(errno, buf, sizeof(buf)), buf)); #endif } // extract the last component of a pathname (extract a filename from its dirname) static const char* stripDirName(const char* path) { if (path) { const char* occur = strrchr(path, DIR_SEPARATOR_CH); return occur ? occur + 1 : path; } else return nullptr; } std::string formatHeader(const char* const file, int line) { #ifdef __linux__ auto tid = syscall(__NR_gettid) & 0xffff; #else auto tid = std::this_thread::get_id(); #endif // __linux__ unsigned int secs, milli; struct timeval tv; if (!gettimeofday(&tv, NULL)) { secs = tv.tv_sec; milli = tv.tv_usec / 1000; // suppose that milli < 1000 } else { secs = time(NULL); milli = 0; } if (file) { return fmt::format(FMT_COMPILE("[{: >3d}.{:0<3d}|{: >4}|{: <24s}:{: <4d}] "), secs, milli, tid, stripDirName(file), line); } else { return fmt::format(FMT_COMPILE("[{: >3d}.{:0<3d}|{: >4}] "), secs, milli, tid); } } std::string formatPrintfArgs(const char* format, va_list ap) { std::string ret; /* A good guess of what we might encounter. */ static constexpr size_t default_buf_size = 80; ret.resize(default_buf_size); /* Necessary if we don't have enough space in buf. */ va_list cp; va_copy(cp, ap); int size = vsnprintf(ret.data(), ret.size(), format, ap); /* Not enough space? Well try again. */ if ((size_t) size >= ret.size()) { ret.resize(size + 1); vsnprintf((char*) ret.data(), ret.size(), format, cp); } ret.resize(size); va_end(cp); return ret; } struct Logger::Msg { Msg() = delete; Msg(int level, const char* file, int line, bool linefeed, std::string&& message) : file_(stripDirName(file)) , line_(line) , payload_(std::move(message)) , level_(level) , linefeed_(linefeed) {} Msg(int level, const char* file, int line, bool linefeed, const char* fmt, va_list ap) : file_(stripDirName(file)) , line_(line) , payload_(formatPrintfArgs(fmt, ap)) , level_(level) , linefeed_(linefeed) {} Msg(Msg&& other) { file_ = other.file_; line_ = other.line_; payload_ = std::move(other.payload_); level_ = other.level_; linefeed_ = other.linefeed_; } inline std::string header() const { return formatHeader(file_, line_); } const char* file_; unsigned line_; std::string payload_; int level_; bool linefeed_; }; class Logger::Handler { public: virtual ~Handler() = default; virtual void consume(Msg& msg) = 0; void enable(bool en) { enabled_.store(en, std::memory_order_relaxed); } bool isEnable() { return enabled_.load(std::memory_order_relaxed); } private: std::atomic_bool enabled_ {false}; }; class ConsoleLog : public Logger::Handler { public: static ConsoleLog& instance() { // Intentional memory leak: // Some thread can still be logging even during static destructors. static ConsoleLog* self = new ConsoleLog(); return *self; } #ifdef _WIN32 void printLogImpl(Logger::Msg& msg, bool with_color) { // If we are using Visual Studio, we can use OutputDebugString to print // to the "Output" window. Otherwise, we just use fputs to stderr. static std::function<void(const char* str)> fputsFunc = [](const char* str) { fputs(str, stderr); }; static std::function<void(const char* str)> outputDebugStringFunc = [](const char* str) { OutputDebugStringA(str); }; static std::function<void()> putcFunc = []() { putc(ENDL, stderr); }; // These next two functions will be used to print the message and line ending. static auto printFunc = IsDebuggerPresent() ? outputDebugStringFunc : fputsFunc; static auto endlFunc = IsDebuggerPresent() ? []() { OutputDebugStringA("\n"); } : putcFunc; WORD saved_attributes; static HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); auto header = msg.header(); if (with_color) { static WORD color_header = CYAN; WORD color_prefix = LIGHT_GREEN; CONSOLE_SCREEN_BUFFER_INFO consoleInfo; switch (msg.level_) { case LOG_ERR: color_prefix = RED; break; case LOG_WARNING: color_prefix = YELLOW; break; } GetConsoleScreenBufferInfo(hConsole, &consoleInfo); saved_attributes = consoleInfo.wAttributes; SetConsoleTextAttribute(hConsole, color_header); printFunc(header.c_str()); SetConsoleTextAttribute(hConsole, saved_attributes); SetConsoleTextAttribute(hConsole, color_prefix); } else { printFunc(header.c_str()); } printFunc(msg.payload_.c_str()); if (msg.linefeed_) { endlFunc(); } if (with_color) { SetConsoleTextAttribute(hConsole, saved_attributes); } } #else void printLogImpl(const Logger::Msg& msg, bool with_color) { auto header = msg.header(); if (with_color) { const char* color_header = CYAN; const char* color_prefix = ""; switch (msg.level_) { case LOG_ERR: color_prefix = RED; break; case LOG_WARNING: color_prefix = YELLOW; break; } fputs(color_header, stderr); fwrite(header.c_str(), 1, header.size(), stderr); fputs(END_COLOR, stderr); fputs(color_prefix, stderr); } else { fwrite(header.c_str(), 1, header.size(), stderr); } fputs(msg.payload_.c_str(), stderr); if (with_color) { fputs(END_COLOR, stderr); } if (msg.linefeed_) { putc(ENDL, stderr); } } #endif /* _WIN32 */ void consume(Logger::Msg& msg) override { static bool with_color = !(getenv("NO_COLOR") || getenv("NO_COLORS") || getenv("NO_COLOUR") || getenv("NO_COLOURS")); printLogImpl(msg, with_color); } }; void Logger::setConsoleLog(bool en) { ConsoleLog::instance().enable(en); #ifdef _WIN32 static WORD original_attributes; if (en) { if (AttachConsole(ATTACH_PARENT_PROCESS) || AllocConsole()) { FILE *fpstdout = stdout, *fpstderr = stderr; freopen_s(&fpstdout, "CONOUT$", "w", stdout); freopen_s(&fpstderr, "CONOUT$", "w", stderr); // Save the original state of the console window(in case AttachConsole worked). CONSOLE_SCREEN_BUFFER_INFO consoleInfo; GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &consoleInfo); original_attributes = consoleInfo.wAttributes; SetConsoleCP(CP_UTF8); SetConsoleMode(GetStdHandle(STD_OUTPUT_HANDLE), ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS); } } else { // Restore the original state of the console window in case we attached. SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), original_attributes); FreeConsole(); } #endif } class SysLog : public Logger::Handler { public: static SysLog& instance() { // Intentional memory leak: // Some thread can still be logging even during static destructors. static SysLog* self = new SysLog(); return *self; } SysLog() { #ifdef _WIN32 ::openlog(LOGFILE, WINLOG_PID, WINLOG_MAIL); #else #ifndef __ANDROID__ ::openlog(LOGFILE, LOG_NDELAY, LOG_USER); #endif #endif /* _WIN32 */ } void consume(Logger::Msg& msg) override { #ifdef __ANDROID__ __android_log_write(msg.level_, msg.file_, msg.payload_.c_str()); #else ::syslog(msg.level_, "%.*s", (int) msg.payload_.size(), msg.payload_.data()); #endif } }; void Logger::setSysLog(bool en) { SysLog::instance().enable(en); } class MonitorLog : public Logger::Handler { public: static MonitorLog& instance() { // Intentional memory leak // Some thread can still be logging even during static destructors. static MonitorLog* self = new MonitorLog(); return *self; } void consume(Logger::Msg& msg) override { auto message = msg.header() + msg.payload_; emitSignal<libjami::ConfigurationSignal::MessageSend>(message); } }; void Logger::setMonitorLog(bool en) { MonitorLog::instance().enable(en); } class FileLog : public Logger::Handler { public: static FileLog& instance() { // Intentional memory leak: // Some thread can still be logging even during static destructors. static FileLog* self = new FileLog(); return *self; } void setFile(const std::string& path) { if (thread_.joinable()) { notify([this] { enable(false); }); thread_.join(); } std::ofstream file; if (not path.empty()) { file.open(path, std::ofstream::out | std::ofstream::app); enable(true); } else { enable(false); return; } thread_ = std::thread([this, file = std::move(file)]() mutable { std::vector<Logger::Msg> pendingQ_; while (isEnable()) { { std::unique_lock lk(mtx_); cv_.wait(lk, [&] { return not isEnable() or not currentQ_.empty(); }); if (not isEnable()) break; std::swap(currentQ_, pendingQ_); } do_consume(file, pendingQ_); pendingQ_.clear(); } file.close(); }); } ~FileLog() { notify([=] { enable(false); }); if (thread_.joinable()) thread_.join(); } void consume(Logger::Msg& msg) override { notify([&, this] { currentQ_.emplace_back(std::move(msg)); }); } private: template<typename T> void notify(T func) { std::lock_guard lk(mtx_); func(); cv_.notify_one(); } void do_consume(std::ofstream& file, const std::vector<Logger::Msg>& messages) { for (const auto& msg : messages) { file << msg.header() << msg.payload_; if (msg.linefeed_) file << ENDL; } file.flush(); } std::vector<Logger::Msg> currentQ_; std::mutex mtx_; std::condition_variable cv_; std::thread thread_; }; void Logger::setFileLog(const std::string& path) { FileLog::instance().setFile(path); } LIBJAMI_PUBLIC void Logger::log(int level, const char* file, int line, bool linefeed, const char* fmt, ...) { va_list ap; va_start(ap, fmt); vlog(level, file, line, linefeed, fmt, ap); va_end(ap); } template<typename T> void log_to_if_enabled(T& handler, Logger::Msg& msg) { if (handler.isEnable()) { handler.consume(msg); } } static std::atomic_bool debugEnabled_ {false}; void Logger::setDebugMode(bool enable) { debugEnabled_.store(enable, std::memory_order_relaxed); } bool Logger::debugEnabled() { return debugEnabled_.load(std::memory_order_relaxed); } void Logger::vlog(int level, const char* file, int line, bool linefeed, const char* fmt, va_list ap) { if (level < LOG_WARNING and not debugEnabled_.load(std::memory_order_relaxed)) { return; } if (not(ConsoleLog::instance().isEnable() or SysLog::instance().isEnable() or MonitorLog::instance().isEnable() or FileLog::instance().isEnable())) { return; } /* Timestamp is generated here. */ Msg msg(level, file, line, linefeed, fmt, ap); log_to_if_enabled(ConsoleLog::instance(), msg); log_to_if_enabled(SysLog::instance(), msg); log_to_if_enabled(MonitorLog::instance(), msg); log_to_if_enabled(FileLog::instance(), msg); // Takes ownership of msg if enabled } void Logger::write(int level, const char* file, int line, std::string&& message) { /* Timestamp is generated here. */ Msg msg(level, file, line, true, std::move(message)); log_to_if_enabled(ConsoleLog::instance(), msg); log_to_if_enabled(SysLog::instance(), msg); log_to_if_enabled(MonitorLog::instance(), msg); log_to_if_enabled(FileLog::instance(), msg); // Takes ownership of msg if enabled } void Logger::fini() { // Force close on file and join thread FileLog::instance().setFile({}); #ifdef _WIN32 Logger::setConsoleLog(false); #endif /* _WIN32 */ } } // namespace jami
15,539
C++
.cpp
515
23.908738
99
0.604595
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,706
vcard.cpp
savoirfairelinux_jami-daemon/src/vcard.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "vcard.h" #include "string_utils.h" namespace vCard { namespace utils { std::map<std::string, std::string> toMap(std::string_view content) { std::map<std::string, std::string> vCard; std::string_view line; while (jami::getline(content, line)) { if (line.size()) { const auto dblptPos = line.find(':'); if (dblptPos == std::string::npos) continue; vCard.emplace(line.substr(0, dblptPos), line.substr(dblptPos + 1)); } } return vCard; } std::map<std::string, std::string> initVcard() { return { {std::string(Property::VCARD_VERSION), "2.1"}, {std::string(Property::FORMATTED_NAME), ""}, {std::string(Property::PHOTO_PNG), ""}, }; } std::string toString(const std::map<std::string, std::string>& vCard) { size_t estimatedSize = 0; for (const auto& [key, value] : vCard) { if (Delimiter::BEGIN_TOKEN_KEY == key || Delimiter::END_TOKEN_KEY == key) continue; estimatedSize += key.size() + value.size() + 2; } std::string result; result.reserve(estimatedSize + Delimiter::BEGIN_TOKEN.size() + Delimiter::END_LINE_TOKEN.size() + Delimiter::END_TOKEN.size() + Delimiter::END_LINE_TOKEN.size()); result += Delimiter::BEGIN_TOKEN; result += Delimiter::END_LINE_TOKEN; for (const auto& [key, value] : vCard) { if (Delimiter::BEGIN_TOKEN_KEY == key || Delimiter::END_TOKEN_KEY == key) continue; result += key + ':' + value + '\n'; } result += Delimiter::END_TOKEN; result += Delimiter::END_LINE_TOKEN; return result; } } // namespace utils } // namespace vCard
2,411
C++
.cpp
68
30.75
166
0.650644
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,707
call_factory.cpp
savoirfairelinux_jami-daemon/src/call_factory.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <stdexcept> #include "call_factory.h" #include "sip/sipcall.h" #include "sip/sipaccountbase.h" #include "string_utils.h" namespace jami { // generate something like 7ea037947eb9fb2f std::string CallFactory::getNewCallID() const { std::string random_id; do { random_id = std::to_string( std::uniform_int_distribution<uint64_t>(1, JAMI_ID_MAX_VAL)(rand_)); } while (hasCall(random_id)); return random_id; } std::shared_ptr<SIPCall> CallFactory::newSipCall(const std::shared_ptr<SIPAccountBase>& account, Call::CallType type, const std::vector<libjami::MediaMap>& mediaList) { if (not allowNewCall_) { JAMI_WARN("Creation of new calls is not allowed"); return {}; } std::lock_guard lk(callMapsMutex_); auto id = getNewCallID(); auto call = std::make_shared<SIPCall>(account, id, type, mediaList); callMaps_[call->getLinkType()].emplace(id, call); account->attach(call); return call; } void CallFactory::forbid() { allowNewCall_ = false; } void CallFactory::removeCall(Call& call) { std::lock_guard lk(callMapsMutex_); const auto& id = call.getCallId(); JAMI_DBG("Removing call %s", id.c_str()); auto& map = callMaps_.at(call.getLinkType()); map.erase(id); JAMI_DBG("Remaining %zu call", map.size()); } void CallFactory::removeCall(const std::string& id) { std::lock_guard lk(callMapsMutex_); if (auto call = getCall(id)) { removeCall(*call); } else JAMI_ERR("No call with ID %s", id.c_str()); } bool CallFactory::hasCall(const std::string& id) const { std::lock_guard lk(callMapsMutex_); for (const auto& item : callMaps_) { const auto& map = item.second; if (map.find(id) != map.cend()) return true; } return false; } bool CallFactory::empty() const { std::lock_guard lk(callMapsMutex_); for (const auto& item : callMaps_) { if (not item.second.empty()) return false; } return true; } void CallFactory::clear() { std::lock_guard lk(callMapsMutex_); callMaps_.clear(); } std::shared_ptr<Call> CallFactory::getCall(const std::string& id) const { std::lock_guard lk(callMapsMutex_); for (const auto& item : callMaps_) { const auto& map = item.second; const auto& iter = map.find(id); if (iter != map.cend()) return iter->second; } return nullptr; } std::vector<std::shared_ptr<Call>> CallFactory::getAllCalls() const { std::lock_guard lk(callMapsMutex_); std::vector<std::shared_ptr<Call>> v; for (const auto& itemmap : callMaps_) { const auto& map = itemmap.second; v.reserve(v.size() + map.size()); for (const auto& item : map) v.push_back(item.second); } return v; } std::vector<std::string> CallFactory::getCallIDs() const { std::vector<std::string> v; for (const auto& item : callMaps_) { const auto& map = item.second; for (const auto& it : map) v.push_back(it.first); } v.shrink_to_fit(); return v; } std::size_t CallFactory::callCount() const { std::lock_guard lk(callMapsMutex_); std::size_t count = 0; for (const auto& itemmap : callMaps_) count += itemmap.second.size(); return count; } bool CallFactory::hasCall(const std::string& id, Call::LinkType link) const { std::lock_guard lk(callMapsMutex_); auto const map = getMap_(link); return map and map->find(id) != map->cend(); } bool CallFactory::empty(Call::LinkType link) const { std::lock_guard lk(callMapsMutex_); const auto map = getMap_(link); return !map or map->empty(); } std::shared_ptr<Call> CallFactory::getCall(const std::string& id, Call::LinkType link) const { std::lock_guard lk(callMapsMutex_); const auto map = getMap_(link); if (!map) return nullptr; const auto& it = map->find(id); if (it == map->cend()) return nullptr; return it->second; } std::vector<std::shared_ptr<Call>> CallFactory::getAllCalls(Call::LinkType link) const { std::lock_guard lk(callMapsMutex_); std::vector<std::shared_ptr<Call>> v; const auto map = getMap_(link); if (map) { for (const auto& it : *map) v.push_back(it.second); } v.shrink_to_fit(); return v; } std::vector<std::string> CallFactory::getCallIDs(Call::LinkType link) const { std::lock_guard lk(callMapsMutex_); std::vector<std::string> v; const auto map = getMap_(link); if (map) { for (const auto& it : *map) v.push_back(it.first); } v.shrink_to_fit(); return v; } std::size_t CallFactory::callCount(Call::LinkType link) const { std::lock_guard lk(callMapsMutex_); const auto map = getMap_(link); if (!map) return 0; return map->size(); } } // namespace jami
5,687
C++
.cpp
208
22.961538
80
0.650709
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,708
data_transfer.cpp
savoirfairelinux_jami-daemon/src/data_transfer.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "data_transfer.h" #include "base64.h" #include "fileutils.h" #include "manager.h" #include "client/ring_signal.h" #include <mutex> #include <cstdlib> // mkstemp #include <filesystem> #include <opendht/rng.h> #include <opendht/thread_pool.h> namespace jami { libjami::DataTransferId generateUID(std::mt19937_64& engine) { return std::uniform_int_distribution<libjami::DataTransferId> {1, JAMI_ID_MAX_VAL}(engine); } FileInfo::FileInfo(const std::shared_ptr<dhtnet::ChannelSocket>& channel, const std::string& fileId, const std::string& interactionId, const libjami::DataTransferInfo& info) : fileId_(fileId) , interactionId_(interactionId) , info_(info) , channel_(channel) {} void FileInfo::emit(libjami::DataTransferEventCode code) { if (finishedCb_ && code >= libjami::DataTransferEventCode::finished) finishedCb_(uint32_t(code)); if (interactionId_ != "") { // Else it's an internal transfer runOnMainThread([info = info_, iid = interactionId_, fid = fileId_, code]() { emitSignal<libjami::DataTransferSignal::DataTransferEvent>(info.accountId, info.conversationId, iid, fid, uint32_t(code)); }); } } OutgoingFile::OutgoingFile(const std::shared_ptr<dhtnet::ChannelSocket>& channel, const std::string& fileId, const std::string& interactionId, const libjami::DataTransferInfo& info, size_t start, size_t end) : FileInfo(channel, fileId, interactionId, info) , start_(start) , end_(end) { std::filesystem::path fpath(info_.path); if (!std::filesystem::is_regular_file(fpath)) { channel_->shutdown(); return; } stream_.open(fpath, std::ios::binary | std::ios::in); if (!stream_ || !stream_.is_open()) { channel_->shutdown(); return; } } OutgoingFile::~OutgoingFile() { if (stream_ && stream_.is_open()) stream_.close(); if (channel_) channel_->shutdown(); } void OutgoingFile::process() { if (!channel_ or !stream_ or !stream_.is_open()) return; auto correct = false; stream_.seekg(start_, std::ios::beg); try { std::vector<char> buffer(UINT16_MAX, 0); std::error_code ec; auto pos = start_; while (!stream_.eof()) { stream_.read(buffer.data(), end_ > start_ ? std::min(end_ - pos, buffer.size()) : buffer.size()); auto gcount = stream_.gcount(); pos += gcount; channel_->write(reinterpret_cast<const uint8_t*>(buffer.data()), gcount, ec); if (ec) break; } if (!ec) correct = true; stream_.close(); } catch (...) { } if (!isUserCancelled_) { // NOTE: emit(code) MUST be changed to improve handling of multiple destinations // But for now, we can just avoid to emit errors to the client, because for outgoing // transfer in a swarm, for outgoingFiles, we know that the file is ok. And the peer // will retry the transfer if they need, so we don't need to show errors. if (!interactionId_.empty() && !correct) return; auto code = correct ? libjami::DataTransferEventCode::finished : libjami::DataTransferEventCode::closed_by_peer; emit(code); } } void OutgoingFile::cancel() { // Remove link, not original file auto path = fileutils::get_data_dir() / "conversation_data" / info_.accountId / info_.conversationId / fileId_; if (std::filesystem::is_symlink(path)) dhtnet::fileutils::remove(path); isUserCancelled_ = true; emit(libjami::DataTransferEventCode::closed_by_host); } IncomingFile::IncomingFile(const std::shared_ptr<dhtnet::ChannelSocket>& channel, const libjami::DataTransferInfo& info, const std::string& fileId, const std::string& interactionId, const std::string& sha3Sum) : FileInfo(channel, fileId, interactionId, info) , sha3Sum_(sha3Sum) , path_(info.path + ".tmp") { stream_.open(path_, std::ios::binary | std::ios::out | std::ios::app); if (!stream_) return; emit(libjami::DataTransferEventCode::ongoing); } IncomingFile::~IncomingFile() { if (channel_) channel_->setOnRecv({}); { std::lock_guard<std::mutex> lk(streamMtx_); if (stream_ && stream_.is_open()) stream_.close(); } if (channel_) channel_->shutdown(); } void IncomingFile::cancel() { isUserCancelled_ = true; emit(libjami::DataTransferEventCode::closed_by_peer); if (channel_) channel_->shutdown(); } void IncomingFile::process() { channel_->setOnRecv([w = weak_from_this()](const uint8_t* buf, size_t len) { if (auto shared = w.lock()) { // No need to lock, setOnRecv is resetted before closing if (shared->stream_.is_open()) shared->stream_.write(reinterpret_cast<const char*>(buf), len); shared->info_.bytesProgress = shared->stream_.tellp(); } return len; }); channel_->onShutdown([w = weak_from_this()] { auto shared = w.lock(); if (!shared) return; { std::lock_guard<std::mutex> lk(shared->streamMtx_); if (shared->stream_ && shared->stream_.is_open()) shared->stream_.close(); } auto correct = shared->sha3Sum_.empty(); std::error_code ec; if (!correct) { if (shared->isUserCancelled_) { std::filesystem::remove(shared->path_, ec); } else { auto sha3Sum = fileutils::sha3File(shared->path_); if (shared->sha3Sum_ == sha3Sum) { JAMI_LOG("New file received: {}", shared->info_.path); correct = true; } else { if (shared->info_.totalSize != 0 && shared->info_.totalSize < shared->info_.bytesProgress) { JAMI_WARNING("Removing {} larger than announced: {}/{}", shared->info_.path, shared->info_.bytesProgress, shared->info_.totalSize); std::filesystem::remove(shared->path_, ec); } else { JAMI_WARNING("Invalid sha3sum detected for {}, incomplete file: {}/{}", shared->info_.path, shared->info_.bytesProgress, shared->info_.totalSize); } } } if (ec) { JAMI_ERROR("Failed to remove file {}: {}", shared->path_, ec.message()); } } if (correct) { std::filesystem::rename(shared->path_, shared->info_.path, ec); if (ec) { JAMI_ERROR("Failed to rename file from {} to {}: {}", shared->path_, shared->info_.path, ec.message()); correct = false; } } if (shared->isUserCancelled_) return; auto code = correct ? libjami::DataTransferEventCode::finished : libjami::DataTransferEventCode::closed_by_host; shared->emit(code); }); } //============================================================================== class TransferManager::Impl { public: Impl(const std::string& accountId, const std::string& accountUri, const std::string& to, const std::mt19937_64& rand) : accountId_(accountId) , accountUri_(accountUri) , to_(to) , rand_(rand) { if (!to_.empty()) { conversationDataPath_ = fileutils::get_data_dir() / accountId_ / "conversation_data" / to_; dhtnet::fileutils::check_dir(conversationDataPath_); waitingPath_ = conversationDataPath_ / "waiting"; } profilesPath_ = fileutils::get_data_dir() / accountId_ / "profiles"; accountProfilePath_ = fileutils::get_data_dir() / accountId / "profile.vcf"; loadWaiting(); } ~Impl() { std::lock_guard lk {mapMutex_}; for (const auto& [channel, _of] : outgoings_) { channel->shutdown(); } outgoings_.clear(); incomings_.clear(); vcards_.clear(); } void loadWaiting() { try { // read file auto file = fileutils::loadFile(waitingPath_); // load values msgpack::object_handle oh = msgpack::unpack((const char*) file.data(), file.size()); std::lock_guard lk {mapMutex_}; oh.get().convert(waitingIds_); } catch (const std::exception& e) { return; } } void saveWaiting() { std::ofstream file(waitingPath_, std::ios::trunc | std::ios::binary); msgpack::pack(file, waitingIds_); } std::string accountId_ {}; std::string accountUri_ {}; std::string to_ {}; std::filesystem::path waitingPath_ {}; std::filesystem::path profilesPath_ {}; std::filesystem::path accountProfilePath_ {}; std::filesystem::path conversationDataPath_ {}; std::mutex mapMutex_ {}; std::map<std::string, WaitingRequest> waitingIds_ {}; std::map<std::shared_ptr<dhtnet::ChannelSocket>, std::shared_ptr<OutgoingFile>> outgoings_ {}; std::map<std::string, std::shared_ptr<IncomingFile>> incomings_ {}; std::map<std::pair<std::string, std::string>, std::shared_ptr<IncomingFile>> vcards_ {}; std::mt19937_64 rand_; }; TransferManager::TransferManager(const std::string& accountId, const std::string& accountUri, const std::string& to, const std::mt19937_64& rand) : pimpl_ {std::make_unique<Impl>(accountId, accountUri, to, rand)} {} TransferManager::~TransferManager() {} void TransferManager::transferFile(const std::shared_ptr<dhtnet::ChannelSocket>& channel, const std::string& fileId, const std::string& interactionId, const std::string& path, size_t start, size_t end, OnFinishedCb onFinished) { std::lock_guard lk {pimpl_->mapMutex_}; if (pimpl_->outgoings_.find(channel) != pimpl_->outgoings_.end()) return; libjami::DataTransferInfo info; info.accountId = pimpl_->accountId_; info.conversationId = pimpl_->to_; info.path = path; auto f = std::make_shared<OutgoingFile>(channel, fileId, interactionId, info, start, end); f->onFinished([w = weak(), channel, onFinished = std::move(onFinished)](uint32_t code) { if (code == uint32_t(libjami::DataTransferEventCode::finished) && onFinished) { onFinished(); } // schedule destroy outgoing transfer as not needed dht::ThreadPool().computation().run([w, channel] { if (auto sthis_ = w.lock()) { auto& pimpl = sthis_->pimpl_; std::lock_guard lk {pimpl->mapMutex_}; auto itO = pimpl->outgoings_.find(channel); if (itO != pimpl->outgoings_.end()) pimpl->outgoings_.erase(itO); } }); }); pimpl_->outgoings_.emplace(channel, f); dht::ThreadPool::io().run([w = std::weak_ptr<OutgoingFile>(f)] { if (auto of = w.lock()) of->process(); }); } bool TransferManager::cancel(const std::string& fileId) { std::lock_guard lk {pimpl_->mapMutex_}; // Remove from waiting, this avoid auto-download auto itW = pimpl_->waitingIds_.find(fileId); if (itW != pimpl_->waitingIds_.end()) { pimpl_->waitingIds_.erase(itW); JAMI_DBG() << "Cancel " << fileId; pimpl_->saveWaiting(); } auto itC = pimpl_->incomings_.find(fileId); if (itC == pimpl_->incomings_.end()) return false; itC->second->cancel(); return true; } bool TransferManager::info(const std::string& fileId, std::string& path, int64_t& total, int64_t& progress) const noexcept { std::unique_lock lk {pimpl_->mapMutex_}; if (pimpl_->to_.empty()) return false; auto itI = pimpl_->incomings_.find(fileId); auto itW = pimpl_->waitingIds_.find(fileId); path = this->path(fileId).string(); if (itI != pimpl_->incomings_.end()) { total = itI->second->info().totalSize; progress = itI->second->info().bytesProgress; return true; } else if (std::filesystem::is_regular_file(path)) { std::ifstream transfer(path, std::ios::binary); transfer.seekg(0, std::ios::end); progress = transfer.tellg(); if (itW != pimpl_->waitingIds_.end()) { total = itW->second.totalSize; } else { // If not waiting it's finished total = progress; } return true; } else if (itW != pimpl_->waitingIds_.end()) { total = itW->second.totalSize; progress = 0; return true; } // Else we don't know infos there. progress = 0; return false; } void TransferManager::waitForTransfer(const std::string& fileId, const std::string& interactionId, const std::string& sha3sum, const std::string& path, std::size_t total) { std::unique_lock lk(pimpl_->mapMutex_); auto itW = pimpl_->waitingIds_.find(fileId); if (itW != pimpl_->waitingIds_.end()) return; pimpl_->waitingIds_[fileId] = {fileId, interactionId, sha3sum, path, total}; pimpl_->saveWaiting(); } void TransferManager::onIncomingFileTransfer(const std::string& fileId, const std::shared_ptr<dhtnet::ChannelSocket>& channel) { std::lock_guard lk(pimpl_->mapMutex_); // Check if not already an incoming file for this id and that we are waiting this file auto itC = pimpl_->incomings_.find(fileId); if (itC != pimpl_->incomings_.end()) { channel->shutdown(); return; } auto itW = pimpl_->waitingIds_.find(fileId); if (itW == pimpl_->waitingIds_.end()) { channel->shutdown(); return; } libjami::DataTransferInfo info; info.accountId = pimpl_->accountId_; info.conversationId = pimpl_->to_; info.path = itW->second.path; info.totalSize = itW->second.totalSize; // Generate the file path within the conversation data directory // using the file id if no path has been specified, otherwise create // a symlink(Note: this will not work on Windows). auto filePath = path(fileId); if (info.path.empty()) { info.path = filePath.string(); } else { // We don't need to check if this is an existing symlink here, as // the attempt to create one should report the error string correctly. fileutils::createFileLink(filePath, info.path); } info.bytesProgress = fileutils::size(info.path); if (info.bytesProgress < 0) info.bytesProgress = 0; auto ifile = std::make_shared<IncomingFile>(std::move(channel), info, fileId, itW->second.interactionId, itW->second.sha3sum); auto res = pimpl_->incomings_.emplace(fileId, std::move(ifile)); if (res.second) { res.first->second->onFinished([w = weak(), fileId](uint32_t code) { // schedule destroy transfer as not needed dht::ThreadPool().computation().run([w, fileId, code] { if (auto sthis_ = w.lock()) { auto& pimpl = sthis_->pimpl_; std::lock_guard lk {pimpl->mapMutex_}; auto itO = pimpl->incomings_.find(fileId); if (itO != pimpl->incomings_.end()) pimpl->incomings_.erase(itO); if (code == uint32_t(libjami::DataTransferEventCode::finished)) { auto itW = pimpl->waitingIds_.find(fileId); if (itW != pimpl->waitingIds_.end()) { pimpl->waitingIds_.erase(itW); pimpl->saveWaiting(); } } } }); }); res.first->second->process(); } } std::filesystem::path TransferManager::path(const std::string& fileId) const { return pimpl_->conversationDataPath_ / fileId; } void TransferManager::onIncomingProfile(const std::shared_ptr<dhtnet::ChannelSocket>& channel, const std::string& sha3Sum) { if (!channel) return; auto chName = channel->name(); std::string_view name = chName; auto sep = name.find_last_of('?'); if (sep != std::string::npos) name = name.substr(0, sep); auto lastSep = name.find_last_of('/'); auto fileId = name.substr(lastSep + 1); auto deviceId = channel->deviceId().toString(); auto cert = channel->peerCertificate(); if (!cert || !cert->issuer || fileId.find(".vcf") == std::string::npos) return; auto uri = fileId == "profile.vcf" ? cert->issuer->getId().toString() : std::string(fileId.substr(0, fileId.size() - 4 /*.vcf*/)); std::lock_guard lk(pimpl_->mapMutex_); auto idx = std::make_pair(deviceId, uri); // Check if not already an incoming file for this id and that we are waiting this file auto itV = pimpl_->vcards_.find(idx); if (itV != pimpl_->vcards_.end()) { channel->shutdown(); return; } auto tid = generateUID(pimpl_->rand_); libjami::DataTransferInfo info; info.accountId = pimpl_->accountId_; info.conversationId = pimpl_->to_; auto recvDir = fileutils::get_cache_dir() / pimpl_->accountId_ / "vcard"; dhtnet::fileutils::recursive_mkdir(recvDir); info.path = (recvDir / fmt::format("{:s}_{:s}_{}", deviceId, uri, tid)).string(); auto ifile = std::make_shared<IncomingFile>(std::move(channel), info, "profile.vcf", "", sha3Sum); auto res = pimpl_->vcards_.emplace(idx, std::move(ifile)); if (res.second) { res.first->second->onFinished([w = weak(), uri = std::move(uri), deviceId = std::move(deviceId), accountId = pimpl_->accountId_, cert = std::move(cert), path = info.path](uint32_t code) { dht::ThreadPool().computation().run([w, uri = std::move(uri), deviceId = std::move(deviceId), accountId = std::move(accountId), path = std::move(path), code] { if (auto sthis_ = w.lock()) { auto& pimpl = sthis_->pimpl_; auto destPath = sthis_->profilePath(uri); try { // Move profile to destination path std::lock_guard lock(dhtnet::fileutils::getFileLock(destPath)); dhtnet::fileutils::recursive_mkdir(destPath.parent_path()); std::filesystem::rename(path, destPath); if (!pimpl->accountUri_.empty() && uri == pimpl->accountUri_) { // If this is the account profile, link or copy it to the account profile path if (!fileutils::createFileLink(pimpl->accountProfilePath_, destPath)) { std::error_code ec; std::filesystem::copy_file(destPath, pimpl->accountProfilePath_, ec); } } } catch (const std::exception& e) { JAMI_ERROR("{}", e.what()); } std::lock_guard lk {pimpl->mapMutex_}; auto itO = pimpl->vcards_.find({deviceId, uri}); if (itO != pimpl->vcards_.end()) pimpl->vcards_.erase(itO); if (code == uint32_t(libjami::DataTransferEventCode::finished)) { emitSignal<libjami::ConfigurationSignal::ProfileReceived>(accountId, uri, destPath.string()); } } }); }); res.first->second->process(); } } std::filesystem::path TransferManager::profilePath(const std::string& contactId) const { return pimpl_->profilesPath_ / fmt::format("{}.vcf", base64::encode(contactId)); } std::vector<WaitingRequest> TransferManager::waitingRequests() const { std::vector<WaitingRequest> res; std::lock_guard lk(pimpl_->mapMutex_); for (const auto& [fileId, req] : pimpl_->waitingIds_) { auto itC = pimpl_->incomings_.find(fileId); if (itC == pimpl_->incomings_.end()) res.emplace_back(req); } return res; } bool TransferManager::isWaiting(const std::string& fileId) const { std::lock_guard lk(pimpl_->mapMutex_); return pimpl_->waitingIds_.find(fileId) != pimpl_->waitingIds_.end(); } } // namespace jami
23,205
C++
.cpp
579
29.098446
170
0.54175
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,709
base64.cpp
savoirfairelinux_jami-daemon/src/base64.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "base64.h" #include "connectivity/sip_utils.h" #include <pjlib.h> #include <pjlib-util/base64.h> namespace jami { namespace base64 { std::string encode(std::string_view dat) { if (dat.empty() || dat.size() > INT_MAX) return {}; int input_length = (int)dat.size(); int output_length = PJ_BASE256_TO_BASE64_LEN(input_length); std::string out; out.resize(output_length); if (pj_base64_encode((const uint8_t*)dat.data(), input_length, &(*out.begin()), &output_length) != PJ_SUCCESS) { throw base64_exception(); } out.resize(output_length); return out; } std::vector<uint8_t> decode(std::string_view str) { if (str.empty()) return {}; int output_length = PJ_BASE64_TO_BASE256_LEN(str.length()); auto input = sip_utils::CONST_PJ_STR(str); std::vector<uint8_t> out; out.resize(output_length); if (pj_base64_decode(&input, &(*out.begin()), &output_length) != PJ_SUCCESS) { throw base64_exception(); } out.resize(output_length); return out; } } // namespace base64 } // namespace jami
1,819
C++
.cpp
54
30.240741
116
0.69121
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,710
fileutils.cpp
savoirfairelinux_jami-daemon/src/fileutils.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "fileutils.h" #include "logger.h" #include "archiver.h" #include "compiler_intrinsics.h" #include "base64.h" #include <opendht/crypto.h> #ifdef __APPLE__ #include <TargetConditionals.h> #endif #if defined(__ANDROID__) || (defined(TARGET_OS_IOS) && TARGET_OS_IOS) #include "client/ring_signal.h" #endif #ifdef _WIN32 #include <windows.h> #include "string_utils.h" #endif #include <sys/types.h> #include <sys/stat.h> #ifndef _MSC_VER #include <libgen.h> #endif #ifdef _MSC_VER #include "windirent.h" #else #include <dirent.h> #endif #include <signal.h> #include <unistd.h> #include <fcntl.h> #ifndef _WIN32 #include <pwd.h> #else #include <shlobj.h> #define NAME_MAX 255 #endif #if !defined __ANDROID__ && !defined _WIN32 #include <wordexp.h> #endif #include <nettle/sha3.h> #include <sstream> #include <fstream> #include <iostream> #include <stdexcept> #include <limits> #include <array> #include <cstdlib> #include <cstring> #include <cerrno> #include <cstddef> #include <ciso646> #include <pj/ctype.h> #include <pjlib-util/md5.h> #ifndef _MSC_VER #define PROTECTED_GETENV(str) \ ({ \ char* envvar_ = getenv((str)); \ envvar_ ? envvar_ : ""; \ }) #define XDG_DATA_HOME (PROTECTED_GETENV("XDG_DATA_HOME")) #define XDG_CONFIG_HOME (PROTECTED_GETENV("XDG_CONFIG_HOME")) #define XDG_CACHE_HOME (PROTECTED_GETENV("XDG_CACHE_HOME")) #else const wchar_t* winGetEnv(const wchar_t* name) { const DWORD buffSize = 65535; static wchar_t buffer[buffSize]; if (GetEnvironmentVariable(name, buffer, buffSize)) { return buffer; } else { return L""; } } #define PROTECTED_GETENV(str) winGetEnv(str) #define JAMI_DATA_HOME PROTECTED_GETENV(L"JAMI_DATA_HOME") #define JAMI_CONFIG_HOME PROTECTED_GETENV(L"JAMI_CONFIG_HOME") #define JAMI_CACHE_HOME PROTECTED_GETENV(L"JAMI_CACHE_HOME") #endif #define PIDFILE ".ring.pid" #define ERASE_BLOCK 4096 namespace jami { namespace fileutils { static std::filesystem::path resource_dir_path; void set_resource_dir_path(const std::filesystem::path& resourceDirPath) { resource_dir_path = resourceDirPath; } const std::filesystem::path& get_resource_dir_path() { static const std::filesystem::path jami_default_data_dir(JAMI_DATADIR); return resource_dir_path.empty() ? jami_default_data_dir : resource_dir_path; } std::string expand_path(const std::string& path) { #if defined __ANDROID__ || defined _MSC_VER || defined WIN32 || defined __APPLE__ JAMI_ERR("Path expansion not implemented, returning original"); return path; #else std::string result; wordexp_t p; int ret = wordexp(path.c_str(), &p, 0); switch (ret) { case WRDE_BADCHAR: JAMI_ERR("Illegal occurrence of newline or one of |, &, ;, <, >, " "(, ), {, }."); return result; case WRDE_BADVAL: JAMI_ERR("An undefined shell variable was referenced"); return result; case WRDE_CMDSUB: JAMI_ERR("Command substitution occurred"); return result; case WRDE_SYNTAX: JAMI_ERR("Shell syntax error"); return result; case WRDE_NOSPACE: JAMI_ERR("Out of memory."); // This is the only error where we must call wordfree break; default: if (p.we_wordc > 0) result = std::string(p.we_wordv[0]); break; } wordfree(&p); return result; #endif } bool isDirectoryWritable(const std::string& directory) { return accessFile(directory, W_OK) == 0; } bool createSymlink(const std::filesystem::path& linkFile, const std::filesystem::path& target) { std::error_code ec; std::filesystem::create_symlink(target, linkFile, ec); if (ec) { JAMI_WARNING("Unable to create soft link from {} to {}: {}", linkFile, target, ec.message()); return false; } else { JAMI_LOG("Created soft link from {} to {}", linkFile, target); } return true; } bool createHardlink(const std::filesystem::path& linkFile, const std::filesystem::path& target) { std::error_code ec; std::filesystem::create_hard_link(target, linkFile, ec); if (ec) { JAMI_WARNING("Unable to create hard link from {} to {}: {}", linkFile, target, ec.message()); return false; } else { JAMI_LOG("Created hard link from {} to {}", linkFile, target); } return true; } bool createFileLink(const std::filesystem::path& linkFile, const std::filesystem::path& target, bool hard) { if (linkFile == target) return true; std::error_code ec; if (std::filesystem::exists(linkFile, ec)) { if (std::filesystem::is_symlink(linkFile, ec) && std::filesystem::read_symlink(linkFile, ec) == target) return true; std::filesystem::remove(linkFile, ec); } if (not hard or not createHardlink(linkFile, target)) return createSymlink(linkFile, target); return true; } std::string_view getFileExtension(std::string_view filename) { std::string_view result; auto sep = filename.find_last_of('.'); if (sep != std::string_view::npos && sep != filename.size() - 1) result = filename.substr(sep + 1); if (result.size() >= 8) return {}; return result; } bool isPathRelative(const std::filesystem::path& path) { return not path.empty() and path.is_relative(); } std::string getCleanPath(const std::string& base, const std::string& path) { if (base.empty() or path.size() < base.size()) return path; auto base_sep = base + DIR_SEPARATOR_STR; if (path.compare(0, base_sep.size(), base_sep) == 0) return path.substr(base_sep.size()); else return path; } std::filesystem::path getFullPath(const std::filesystem::path& base, const std::filesystem::path& path) { bool isRelative {not base.empty() and isPathRelative(path)}; return isRelative ? base / path : path; } std::vector<uint8_t> loadFile(const std::filesystem::path& path, const std::filesystem::path& default_dir) { return dhtnet::fileutils::loadFile(getFullPath(default_dir, path)); } std::string loadTextFile(const std::filesystem::path& path, const std::filesystem::path& default_dir) { std::string buffer; std::ifstream file(getFullPath(default_dir, path)); if (!file) throw std::runtime_error("Unable to read file: " + path.string()); file.seekg(0, std::ios::end); auto size = file.tellg(); if (size > std::numeric_limits<unsigned>::max()) throw std::runtime_error("File is too big: " + path.string()); buffer.resize(size); file.seekg(0, std::ios::beg); if (!file.read((char*) buffer.data(), size)) throw std::runtime_error("Unable to load file: " + path.string()); return buffer; } void saveFile(const std::filesystem::path& path, const uint8_t* data, size_t data_size, mode_t UNUSED mode) { std::ofstream file(path, std::ios::trunc | std::ios::binary); if (!file.is_open()) { JAMI_ERROR("Unable to write data to {}", path); return; } file.write((char*) data, data_size); #ifndef _WIN32 file.close(); if (chmod(path.c_str(), mode) < 0) JAMI_WARNING("fileutils::saveFile(): chmod() failed on {}, {}", path, strerror(errno)); #endif } std::vector<uint8_t> loadCacheFile(const std::filesystem::path& path, std::chrono::system_clock::duration maxAge) { // last_write_time throws exception if file doesn't exist auto writeTime = std::filesystem::last_write_time(path); if (decltype(writeTime)::clock::now() - writeTime > maxAge) throw std::runtime_error("file too old"); JAMI_LOG("Loading cache file '{}'", path); return dhtnet::fileutils::loadFile(path); } std::string loadCacheTextFile(const std::filesystem::path& path, std::chrono::system_clock::duration maxAge) { // last_write_time throws exception if file doesn't exist auto writeTime = std::filesystem::last_write_time(path); if (decltype(writeTime)::clock::now() - writeTime > maxAge) throw std::runtime_error("file too old"); JAMI_LOG("Loading cache file '{}'", path); return loadTextFile(path); } ArchiveStorageData readArchive(const std::filesystem::path& path, std::string_view scheme, const std::string& pwd) { JAMI_LOG("Reading archive from {} with scheme '{}'", path, scheme); auto isUnencryptedGzip = [](const std::vector<uint8_t>& data) { // NOTE: some webserver modify gzip files and this can end with a gunzip in a gunzip // file. So, to make the readArchive more robust, we can support this case by detecting // gzip header via 1f8b 08 // We don't need to support more than 2 level, else somebody may be able to send // gunzip in loops and abuse. return data.size() > 3 && data[0] == 0x1f && data[1] == 0x8b && data[2] == 0x08; }; auto decompress = [](std::vector<uint8_t>& data) { try { data = archiver::decompress(data); } catch (const std::exception& e) { JAMI_ERROR("Error decrypting archive: {}", e.what()); throw e; } }; ArchiveStorageData ret; // Read file try { ret.data = dhtnet::fileutils::loadFile(path); } catch (const std::exception& e) { JAMI_ERR("Error loading archive: %s", e.what()); throw e; } if (isUnencryptedGzip(ret.data)) { if (!pwd.empty()) JAMI_WARNING("A gunzip in a gunzip is detected. A webserver may have a bad config"); decompress(ret.data); } if (!pwd.empty()) { // Decrypt if (scheme == ARCHIVE_AUTH_SCHEME_KEY) { try { ret.salt = dht::crypto::aesGetSalt(ret.data); ret.data = dht::crypto::aesDecrypt(dht::crypto::aesGetEncrypted(ret.data), base64::decode(pwd)); } catch (const std::exception& e) { JAMI_ERROR("Error decrypting archive: {}", e.what()); throw e; } } else if (scheme == ARCHIVE_AUTH_SCHEME_PASSWORD) { try { ret.salt = dht::crypto::aesGetSalt(ret.data); ret.data = dht::crypto::aesDecrypt(ret.data, pwd); } catch (const std::exception& e) { JAMI_ERROR("Error decrypting archive: {}", e.what()); throw e; } } decompress(ret.data); } else if (isUnencryptedGzip(ret.data)) { JAMI_WARNING("A gunzip in a gunzip is detected. A webserver may have a bad config"); decompress(ret.data); } return ret; } void writeArchive(const std::string& archive_str, const std::filesystem::path& path, std::string_view scheme, const std::string& password, const std::vector<uint8_t>& password_salt) { JAMI_LOG("Writing archive to {}", path); if (scheme == ARCHIVE_AUTH_SCHEME_KEY) { // Encrypt using provided key try { auto key = base64::decode(password); auto newArchive = dht::crypto::aesEncrypt(archiver::compress(archive_str), key); saveFile(path, dht::crypto::aesBuildEncrypted(newArchive, password_salt)); } catch (const std::runtime_error& ex) { JAMI_ERROR("Export failed: {}", ex.what()); return; } } else if (scheme == ARCHIVE_AUTH_SCHEME_PASSWORD and not password.empty()) { // Encrypt using provided password try { saveFile(path, dht::crypto::aesEncrypt(archiver::compress(archive_str), password, password_salt)); } catch (const std::runtime_error& ex) { JAMI_ERROR("Export failed: {}", ex.what()); return; } } else { JAMI_WARNING("Unsecured archiving (no password)"); archiver::compressGzip(archive_str, path.string()); } } std::filesystem::path get_cache_dir(const char* pkg) { #if defined(__ANDROID__) || (defined(TARGET_OS_IOS) && TARGET_OS_IOS) std::vector<std::string> paths; paths.reserve(1); emitSignal<libjami::ConfigurationSignal::GetAppDataPath>("cache", &paths); if (not paths.empty()) return paths[0]; return {}; #elif defined(__APPLE__) return get_home_dir() / "Library" / "Caches" / pkg; #else #ifdef _WIN32 const std::wstring cache_home(JAMI_CACHE_HOME); if (not cache_home.empty()) return jami::to_string(cache_home); #else const std::string cache_home(XDG_CACHE_HOME); if (not cache_home.empty()) return cache_home; #endif return get_home_dir() / ".cache" / pkg; #endif } const std::filesystem::path& get_cache_dir() { static const std::filesystem::path cache_dir = get_cache_dir(PACKAGE); return cache_dir; } std::filesystem::path get_home_dir_impl() { #if defined(__ANDROID__) || (defined(TARGET_OS_IOS) && TARGET_OS_IOS) std::vector<std::string> paths; paths.reserve(1); emitSignal<libjami::ConfigurationSignal::GetAppDataPath>("files", &paths); if (not paths.empty()) return paths[0]; return {}; #elif defined _WIN32 TCHAR path[MAX_PATH]; if (SUCCEEDED(SHGetFolderPath(nullptr, CSIDL_PROFILE, nullptr, 0, path))) { return jami::to_string(path); } return {}; #else // 1) try getting user's home directory from the environment std::string home(PROTECTED_GETENV("HOME")); if (not home.empty()) return home; // 2) try getting it from getpwuid_r (i.e. /etc/passwd) const long max = sysconf(_SC_GETPW_R_SIZE_MAX); if (max != -1) { char buf[max]; struct passwd pwbuf, *pw; if (getpwuid_r(getuid(), &pwbuf, buf, sizeof(buf), &pw) == 0 and pw != NULL) return pw->pw_dir; } return {}; #endif } const std::filesystem::path& get_home_dir() { static const std::filesystem::path home_dir = get_home_dir_impl(); return home_dir; } std::filesystem::path get_data_dir(const char* pkg) { #if defined(__ANDROID__) || (defined(TARGET_OS_IOS) && TARGET_OS_IOS) std::vector<std::string> paths; paths.reserve(1); emitSignal<libjami::ConfigurationSignal::GetAppDataPath>("files", &paths); if (not paths.empty()) return paths[0]; return {}; #elif defined(__APPLE__) return get_home_dir() / "Library" / "Application Support" / pkg; #elif defined(_WIN32) std::wstring data_home(JAMI_DATA_HOME); if (not data_home.empty()) return std::filesystem::path(data_home) / pkg; if (!strcmp(pkg, "ring")) { return get_home_dir() / ".local" / "share" / pkg; } else { return get_home_dir() / "AppData" / "Local" / pkg; } #else std::string_view data_home(XDG_DATA_HOME); if (not data_home.empty()) return std::filesystem::path(data_home) / pkg; // "If $XDG_DATA_HOME is either not set or empty, a default equal to // $HOME/.local/share should be used." return get_home_dir() / ".local" / "share" / pkg; #endif } const std::filesystem::path& get_data_dir() { static const std::filesystem::path data_dir = get_data_dir(PACKAGE); return data_dir; } std::filesystem::path get_config_dir(const char* pkg) { std::filesystem::path configdir; #if defined(__ANDROID__) || (defined(TARGET_OS_IOS) && TARGET_OS_IOS) std::vector<std::string> paths; emitSignal<libjami::ConfigurationSignal::GetAppDataPath>("config", &paths); if (not paths.empty()) configdir = std::filesystem::path(paths[0]); #elif defined(__APPLE__) configdir = fileutils::get_home_dir() / "Library" / "Application Support" / pkg; #elif defined(_WIN32) std::wstring xdg_env(JAMI_CONFIG_HOME); if (not xdg_env.empty()) { configdir = std::filesystem::path(xdg_env) / pkg; } else if (!strcmp(pkg, "ring")) { configdir = fileutils::get_home_dir() / ".config" / pkg; } else { configdir = fileutils::get_home_dir() / "AppData" / "Local" / pkg; } #else std::string xdg_env(XDG_CONFIG_HOME); if (not xdg_env.empty()) configdir = std::filesystem::path(xdg_env) / pkg; else configdir = fileutils::get_home_dir() / ".config" / pkg; #endif if (!dhtnet::fileutils::recursive_mkdir(configdir, 0700)) { // If directory creation failed if (errno != EEXIST) JAMI_DBG("Unable to create directory: %s!", configdir.c_str()); } return configdir; } const std::filesystem::path& get_config_dir() { static const std::filesystem::path config_dir = get_config_dir(PACKAGE); return config_dir; } #ifdef _WIN32 bool eraseFile_win32(const std::string& path, bool dosync) { // Note: from // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-deletefilea#remarks To // delete a read-only file, first you must remove the read-only attribute. SetFileAttributesA(path.c_str(), GetFileAttributesA(path.c_str()) & ~FILE_ATTRIBUTE_READONLY); HANDLE h = CreateFileA(path.c_str(), GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if (h == INVALID_HANDLE_VALUE) { JAMI_WARN("Unable to open file %s for erasing.", path.c_str()); return false; } LARGE_INTEGER size; if (!GetFileSizeEx(h, &size)) { JAMI_WARN("Unable to erase file %s: GetFileSizeEx() failed.", path.c_str()); CloseHandle(h); return false; } if (size.QuadPart == 0) { CloseHandle(h); return false; } uint64_t size_blocks = size.QuadPart / ERASE_BLOCK; if (size.QuadPart % ERASE_BLOCK) size_blocks++; char* buffer; try { buffer = new char[ERASE_BLOCK]; } catch (std::bad_alloc& ba) { JAMI_WARN("Unable to allocate buffer for erasing %s.", path.c_str()); CloseHandle(h); return false; } memset(buffer, 0x00, ERASE_BLOCK); OVERLAPPED ovlp; if (size.QuadPart < (1024 - 42)) { // a small file can be stored in the MFT record ovlp.Offset = 0; ovlp.OffsetHigh = 0; WriteFile(h, buffer, (DWORD) size.QuadPart, 0, &ovlp); FlushFileBuffers(h); } for (uint64_t i = 0; i < size_blocks; i++) { uint64_t offset = i * ERASE_BLOCK; ovlp.Offset = offset & 0x00000000FFFFFFFF; ovlp.OffsetHigh = offset >> 32; WriteFile(h, buffer, ERASE_BLOCK, 0, &ovlp); } delete[] buffer; if (dosync) FlushFileBuffers(h); CloseHandle(h); return true; } #else bool eraseFile_posix(const std::string& path, bool dosync) { struct stat st; if (stat(path.c_str(), &st) == -1) { JAMI_WARN("Unable to erase file %s: fstat() failed.", path.c_str()); return false; } // Remove read-only flag if possible chmod(path.c_str(), st.st_mode | (S_IWGRP + S_IWUSR)); int fd = open(path.c_str(), O_WRONLY); if (fd == -1) { JAMI_WARN("Unable to open file %s for erasing.", path.c_str()); return false; } if (st.st_size == 0) { close(fd); return false; } lseek(fd, 0, SEEK_SET); std::array<char, ERASE_BLOCK> buffer; buffer.fill(0); decltype(st.st_size) written(0); while (written < st.st_size) { auto ret = write(fd, buffer.data(), buffer.size()); if (ret < 0) { JAMI_WARNING("Error while overriding file with zeros."); break; } else written += ret; } if (dosync) fsync(fd); close(fd); return written >= st.st_size; } #endif bool eraseFile(const std::string& path, bool dosync) { #ifdef _WIN32 return eraseFile_win32(path, dosync); #else return eraseFile_posix(path, dosync); #endif } int remove(const std::filesystem::path& path, bool erase) { if (erase and dhtnet::fileutils::isFile(path, false) and !dhtnet::fileutils::hasHardLink(path)) eraseFile(path.string(), true); #ifdef _WIN32 // use Win32 api since std::remove will not unlink directory in use if (std::filesystem::is_directory(path)) return !RemoveDirectory(path.c_str()); #endif return std::remove(path.string().c_str()); } int64_t size(const std::filesystem::path& path) { int64_t size = 0; try { std::ifstream file(path, std::ios::binary | std::ios::in); file.seekg(0, std::ios_base::end); size = file.tellg(); file.close(); } catch (...) { } return size; } std::string sha3File(const std::filesystem::path& path) { sha3_512_ctx ctx; sha3_512_init(&ctx); try { if (not std::filesystem::is_regular_file(path)) return {}; std::ifstream file(path, std::ios::binary | std::ios::in); if (!file) return {}; std::vector<char> buffer(8192, 0); while (!file.eof()) { file.read(buffer.data(), buffer.size()); std::streamsize readSize = file.gcount(); sha3_512_update(&ctx, readSize, (const uint8_t*) buffer.data()); } } catch (...) { return {}; } unsigned char digest[SHA3_512_DIGEST_SIZE]; sha3_512_digest(&ctx, SHA3_512_DIGEST_SIZE, digest); char hash[SHA3_512_DIGEST_SIZE * 2]; for (int i = 0; i < SHA3_512_DIGEST_SIZE; ++i) pj_val_to_hex_digit(digest[i], &hash[2 * i]); return {hash, SHA3_512_DIGEST_SIZE * 2}; } std::string sha3sum(const uint8_t* data, size_t size) { sha3_512_ctx ctx; sha3_512_init(&ctx); sha3_512_update(&ctx, size, data); unsigned char digest[SHA3_512_DIGEST_SIZE]; sha3_512_digest(&ctx, SHA3_512_DIGEST_SIZE, digest); return dht::toHex(digest, SHA3_512_DIGEST_SIZE); } int accessFile(const std::string& file, int mode) { #ifdef _WIN32 return _waccess(jami::to_wstring(file).c_str(), mode); #else return access(file.c_str(), mode); #endif } uint64_t lastWriteTimeInSeconds(const std::filesystem::path& filePath) { return std::chrono::duration_cast<std::chrono::seconds>( std::filesystem::last_write_time(filePath).time_since_epoch()) .count(); } } // namespace fileutils } // namespace jami
22,839
C++
.cpp
706
27.347025
112
0.639561
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,711
preferences.cpp
savoirfairelinux_jami-daemon/src/preferences.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "preferences.h" #include "logger.h" #include "audio/audiolayer.h" #if HAVE_OPENSL #include "audio/opensl/opensllayer.h" #else #if HAVE_ALSA #include "audio/alsa/alsalayer.h" #endif #if HAVE_JACK #include "audio/jack/jacklayer.h" #endif #if HAVE_PULSE #include "audio/pulseaudio/pulselayer.h" #endif #if HAVE_COREAUDIO #ifdef __APPLE__ #include <TargetConditionals.h> #endif #if TARGET_OS_IOS #include "audio/coreaudio/ios/corelayer.h" #else #include "audio/coreaudio/osx/corelayer.h" #endif /* TARGET_OS_IOS */ #endif /* HAVE_COREAUDIO */ #if HAVE_PORTAUDIO #include "audio/portaudio/portaudiolayer.h" #endif #endif /* HAVE_OPENSL */ #ifdef ENABLE_VIDEO #include "client/videomanager.h" #endif #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #include <yaml-cpp/yaml.h> #pragma GCC diagnostic pop #include "config/yamlparser.h" #include "connectivity/sip_utils.h" #include <sstream> #include <algorithm> #include <stdexcept> #include "fileutils.h" #include "string_utils.h" namespace jami { using yaml_utils::parseValue; constexpr const char* const Preferences::CONFIG_LABEL; const char* const Preferences::DFT_ZONE = "North America"; const char* const Preferences::REGISTRATION_EXPIRE_KEY = "registrationexpire"; constexpr std::string_view DEFAULT_CONFERENCE_RESOLUTION {"1280x720"}; // general preferences static constexpr const char* ORDER_KEY {"order"}; static constexpr const char* AUDIO_API_KEY {"audioApi"}; static constexpr const char* HISTORY_LIMIT_KEY {"historyLimit"}; static constexpr const char* RINGING_TIMEOUT {"ringingTimeout"}; static constexpr const char* HISTORY_MAX_CALLS_KEY {"historyMaxCalls"}; static constexpr const char* ZONE_TONE_CHOICE_KEY {"zoneToneChoice"}; static constexpr const char* PORT_NUM_KEY {"portNum"}; static constexpr const char* SEARCH_BAR_DISPLAY_KEY {"searchBarDisplay"}; static constexpr const char* MD5_HASH_KEY {"md5Hash"}; // voip preferences constexpr const char* const VoipPreference::CONFIG_LABEL; static constexpr const char* PLAY_DTMF_KEY {"playDtmf"}; static constexpr const char* PLAY_TONES_KEY {"playTones"}; static constexpr const char* PULSE_LENGTH_KEY {"pulseLength"}; // audio preferences constexpr const char* const AudioPreference::CONFIG_LABEL; static constexpr const char* ALSAMAP_KEY {"alsa"}; static constexpr const char* PULSEMAP_KEY {"pulse"}; static constexpr const char* PORTAUDIO_KEY {"portaudio"}; static constexpr const char* CARDIN_KEY {"cardIn"}; static constexpr const char* CARDOUT_KEY {"cardOut"}; static constexpr const char* CARLIBJAMI_KEY {"cardRing"}; static constexpr const char* PLUGIN_KEY {"plugin"}; static constexpr const char* SMPLRATE_KEY {"smplRate"}; static constexpr const char* DEVICE_PLAYBACK_KEY {"devicePlayback"}; static constexpr const char* DEVICE_RECORD_KEY {"deviceRecord"}; static constexpr const char* DEVICE_RINGTONE_KEY {"deviceRingtone"}; static constexpr const char* RECORDPATH_KEY {"recordPath"}; static constexpr const char* ALWAYS_RECORDING_KEY {"alwaysRecording"}; static constexpr const char* VOLUMEMIC_KEY {"volumeMic"}; static constexpr const char* VOLUMESPKR_KEY {"volumeSpkr"}; static constexpr const char* AUDIO_PROCESSOR_KEY {"audioProcessor"}; static constexpr const char* NOISE_REDUCE_KEY {"noiseReduce"}; static constexpr const char* AGC_KEY {"automaticGainControl"}; static constexpr const char* CAPTURE_MUTED_KEY {"captureMuted"}; static constexpr const char* PLAYBACK_MUTED_KEY {"playbackMuted"}; static constexpr const char* VAD_KEY {"voiceActivityDetection"}; static constexpr const char* ECHO_CANCEL_KEY {"echoCancel"}; #ifdef ENABLE_VIDEO // video preferences constexpr const char* const VideoPreferences::CONFIG_LABEL; static constexpr const char* DECODING_ACCELERATED_KEY {"decodingAccelerated"}; static constexpr const char* ENCODING_ACCELERATED_KEY {"encodingAccelerated"}; static constexpr const char* RECORD_PREVIEW_KEY {"recordPreview"}; static constexpr const char* RECORD_QUALITY_KEY {"recordQuality"}; static constexpr const char* CONFERENCE_RESOLUTION_KEY {"conferenceResolution"}; #endif #ifdef ENABLE_PLUGIN // plugin preferences constexpr const char* const PluginPreferences::CONFIG_LABEL; static constexpr const char* JAMI_PLUGIN_KEY {"pluginsEnabled"}; static constexpr const char* JAMI_PLUGINS_INSTALLED_KEY {"installedPlugins"}; static constexpr const char* JAMI_PLUGINS_LOADED_KEY {"loadedPlugins"}; #endif static constexpr int PULSE_LENGTH_DEFAULT {250}; /** Default DTMF length */ #ifndef _MSC_VER static constexpr const char* ALSA_DFT_CARD {"0"}; /** Default sound card index */ #else static constexpr const char* ALSA_DFT_CARD {"-1"}; /** Default sound card index (Portaudio) */ #endif // _MSC_VER Preferences::Preferences() : accountOrder_("") , historyLimit_(0) , historyMaxCalls_(20) , ringingTimeout_(30) , zoneToneChoice_(DFT_ZONE) // DFT_ZONE , portNum_(sip_utils::DEFAULT_SIP_PORT) , searchBarDisplay_(true) , md5Hash_(false) {} void Preferences::verifyAccountOrder(const std::vector<std::string>& accountIDs) { std::vector<std::string> tokens; std::string token; bool drop = false; for (const auto c : accountOrder_) { if (c != '/') { token += c; } else { if (find(accountIDs.begin(), accountIDs.end(), token) != accountIDs.end()) tokens.push_back(token); else { JAMI_DBG("Dropping nonexistent account %s", token.c_str()); drop = true; } token.clear(); } } if (drop) { accountOrder_.clear(); for (const auto& t : tokens) accountOrder_ += t + '/'; } } void Preferences::addAccount(const std::string& newAccountID) { // Add the newly created account in the account order list if (not accountOrder_.empty()) accountOrder_.insert(0, newAccountID + "/"); else accountOrder_ = newAccountID + "/"; } void Preferences::removeAccount(const std::string& oldAccountID) { // include the slash since we don't want to remove a partial match const size_t start = accountOrder_.find(oldAccountID + "/"); if (start != std::string::npos) accountOrder_.erase(start, oldAccountID.length() + 1); } void Preferences::serialize(YAML::Emitter& out) const { out << YAML::Key << CONFIG_LABEL << YAML::Value << YAML::BeginMap; out << YAML::Key << HISTORY_LIMIT_KEY << YAML::Value << historyLimit_; out << YAML::Key << RINGING_TIMEOUT << YAML::Value << ringingTimeout_; out << YAML::Key << HISTORY_MAX_CALLS_KEY << YAML::Value << historyMaxCalls_; out << YAML::Key << MD5_HASH_KEY << YAML::Value << md5Hash_; out << YAML::Key << ORDER_KEY << YAML::Value << accountOrder_; out << YAML::Key << PORT_NUM_KEY << YAML::Value << portNum_; out << YAML::Key << SEARCH_BAR_DISPLAY_KEY << YAML::Value << searchBarDisplay_; out << YAML::Key << ZONE_TONE_CHOICE_KEY << YAML::Value << zoneToneChoice_; out << YAML::EndMap; } void Preferences::unserialize(const YAML::Node& in) { const auto& node = in[CONFIG_LABEL]; parseValue(node, ORDER_KEY, accountOrder_); parseValue(node, HISTORY_LIMIT_KEY, historyLimit_); parseValue(node, RINGING_TIMEOUT, ringingTimeout_); parseValue(node, HISTORY_MAX_CALLS_KEY, historyMaxCalls_); parseValue(node, ZONE_TONE_CHOICE_KEY, zoneToneChoice_); parseValue(node, PORT_NUM_KEY, portNum_); parseValue(node, SEARCH_BAR_DISPLAY_KEY, searchBarDisplay_); parseValue(node, MD5_HASH_KEY, md5Hash_); } VoipPreference::VoipPreference() : playDtmf_(true) , playTones_(true) , pulseLength_(PULSE_LENGTH_DEFAULT) {} void VoipPreference::serialize(YAML::Emitter& out) const { out << YAML::Key << CONFIG_LABEL << YAML::Value << YAML::BeginMap; out << YAML::Key << PLAY_DTMF_KEY << YAML::Value << playDtmf_; out << YAML::Key << PLAY_TONES_KEY << YAML::Value << playTones_; out << YAML::Key << PULSE_LENGTH_KEY << YAML::Value << pulseLength_; out << YAML::EndMap; } void VoipPreference::unserialize(const YAML::Node& in) { const auto& node = in[CONFIG_LABEL]; parseValue(node, PLAY_DTMF_KEY, playDtmf_); parseValue(node, PLAY_TONES_KEY, playTones_); parseValue(node, PULSE_LENGTH_KEY, pulseLength_); } AudioPreference::AudioPreference() : audioApi_(PULSEAUDIO_API_STR) , alsaCardin_(atoi(ALSA_DFT_CARD)) , alsaCardout_(atoi(ALSA_DFT_CARD)) , alsaCardRingtone_(atoi(ALSA_DFT_CARD)) , alsaPlugin_("default") , alsaSmplrate_(44100) , pulseDevicePlayback_("") , pulseDeviceRecord_("") , pulseDeviceRingtone_("") , recordpath_("") , alwaysRecording_(false) , volumemic_(1.0) , volumespkr_(1.0) , audioProcessor_("webrtc") , denoise_("auto") , agcEnabled_(true) , vadEnabled_(true) , echoCanceller_("auto") , captureMuted_(false) , playbackMuted_(false) {} #if HAVE_ALSA static const int ALSA_DFT_CARD_ID = 0; // Index of the default soundcard static void checkSoundCard(int& card, AudioDeviceType type) { if (not AlsaLayer::soundCardIndexExists(card, type)) { JAMI_WARN(" Card with index %d doesn't exist or is unusable.", card); card = ALSA_DFT_CARD_ID; } } #endif AudioLayer* AudioPreference::createAudioLayer() { #if HAVE_OPENSL return new OpenSLLayer(*this); #else #if HAVE_JACK if (audioApi_ == JACK_API_STR) { try { if (auto ret = system("jack_lsp > /dev/null")) throw std::runtime_error("Error running jack_lsp: " + std::to_string(ret)); return new JackLayer(*this); } catch (const std::runtime_error& e) { JAMI_ERR("%s", e.what()); #if HAVE_PULSE audioApi_ = PULSEAUDIO_API_STR; #elif HAVE_ALSA audioApi_ = ALSA_API_STR; #elif HAVE_COREAUDIO audioApi_ = COREAUDIO_API_STR; #elif HAVE_PORTAUDIO audioApi_ = PORTAUDIO_API_STR; #else throw; #endif // HAVE_PULSE } } #endif // HAVE_JACK #if HAVE_PULSE if (audioApi_ == PULSEAUDIO_API_STR) { try { return new PulseLayer(*this); } catch (const std::runtime_error& e) { JAMI_WARN("Unable to create pulseaudio layer, falling back to ALSA"); } } #endif #if HAVE_ALSA audioApi_ = ALSA_API_STR; checkSoundCard(alsaCardin_, AudioDeviceType::CAPTURE); checkSoundCard(alsaCardout_, AudioDeviceType::PLAYBACK); checkSoundCard(alsaCardRingtone_, AudioDeviceType::RINGTONE); return new AlsaLayer(*this); #endif #if HAVE_COREAUDIO audioApi_ = COREAUDIO_API_STR; try { return new CoreLayer(*this); } catch (const std::runtime_error& e) { JAMI_WARN("Unable to create coreaudio layer. There will be no sound."); } return NULL; #endif #if HAVE_PORTAUDIO audioApi_ = PORTAUDIO_API_STR; try { return new PortAudioLayer(*this); } catch (const std::runtime_error& e) { JAMI_WARN("Unable to create PortAudio layer. There will be no sound."); } return nullptr; #endif #endif // HAVE_OPENSL JAMI_WARN("No audio layer provided"); return nullptr; } std::vector<std::string> AudioPreference::getSupportedAudioManagers() { return { #if HAVE_OPENSL OPENSL_API_STR, #endif #if HAVE_ALSA ALSA_API_STR, #endif #if HAVE_PULSE PULSEAUDIO_API_STR, #endif #if HAVE_JACK JACK_API_STR, #endif #if HAVE_COREAUDIO COREAUDIO_API_STR, #endif #if HAVE_PORTAUDIO PORTAUDIO_API_STR, #endif }; } void AudioPreference::serialize(YAML::Emitter& out) const { out << YAML::Key << CONFIG_LABEL << YAML::Value << YAML::BeginMap; // alsa submap out << YAML::Key << ALSAMAP_KEY << YAML::Value << YAML::BeginMap; out << YAML::Key << CARDIN_KEY << YAML::Value << alsaCardin_; out << YAML::Key << CARDOUT_KEY << YAML::Value << alsaCardout_; out << YAML::Key << CARLIBJAMI_KEY << YAML::Value << alsaCardRingtone_; out << YAML::Key << PLUGIN_KEY << YAML::Value << alsaPlugin_; out << YAML::Key << SMPLRATE_KEY << YAML::Value << alsaSmplrate_; out << YAML::EndMap; // common options out << YAML::Key << ALWAYS_RECORDING_KEY << YAML::Value << alwaysRecording_; out << YAML::Key << AUDIO_API_KEY << YAML::Value << audioApi_; out << YAML::Key << CAPTURE_MUTED_KEY << YAML::Value << captureMuted_; out << YAML::Key << PLAYBACK_MUTED_KEY << YAML::Value << playbackMuted_; // pulse submap out << YAML::Key << PULSEMAP_KEY << YAML::Value << YAML::BeginMap; out << YAML::Key << DEVICE_PLAYBACK_KEY << YAML::Value << pulseDevicePlayback_; out << YAML::Key << DEVICE_RECORD_KEY << YAML::Value << pulseDeviceRecord_; out << YAML::Key << DEVICE_RINGTONE_KEY << YAML::Value << pulseDeviceRingtone_; out << YAML::EndMap; // portaudio submap out << YAML::Key << PORTAUDIO_KEY << YAML::Value << YAML::BeginMap; out << YAML::Key << DEVICE_PLAYBACK_KEY << YAML::Value << portaudioDevicePlayback_; out << YAML::Key << DEVICE_RECORD_KEY << YAML::Value << portaudioDeviceRecord_; out << YAML::Key << DEVICE_RINGTONE_KEY << YAML::Value << portaudioDeviceRingtone_; out << YAML::EndMap; // more common options! out << YAML::Key << RECORDPATH_KEY << YAML::Value << recordpath_; out << YAML::Key << VOLUMEMIC_KEY << YAML::Value << volumemic_; out << YAML::Key << VOLUMESPKR_KEY << YAML::Value << volumespkr_; // audio processor options, not in a submap out << YAML::Key << AUDIO_PROCESSOR_KEY << YAML::Value << audioProcessor_; out << YAML::Key << AGC_KEY << YAML::Value << agcEnabled_; out << YAML::Key << VAD_KEY << YAML::Value << vadEnabled_; out << YAML::Key << NOISE_REDUCE_KEY << YAML::Value << denoise_; out << YAML::Key << ECHO_CANCEL_KEY << YAML::Value << echoCanceller_; out << YAML::EndMap; } bool AudioPreference::setRecordPath(const std::string& r) { std::string path = fileutils::expand_path(r); if (fileutils::isDirectoryWritable(path)) { recordpath_ = path; return true; } else { JAMI_ERR("%s is not writable, unable to be the recording path", path.c_str()); return false; } } void AudioPreference::unserialize(const YAML::Node& in) { const auto& node = in[CONFIG_LABEL]; // alsa submap const auto& alsa = node[ALSAMAP_KEY]; parseValue(alsa, CARDIN_KEY, alsaCardin_); parseValue(alsa, CARDOUT_KEY, alsaCardout_); parseValue(alsa, CARLIBJAMI_KEY, alsaCardRingtone_); parseValue(alsa, PLUGIN_KEY, alsaPlugin_); parseValue(alsa, SMPLRATE_KEY, alsaSmplrate_); // common options parseValue(node, ALWAYS_RECORDING_KEY, alwaysRecording_); parseValue(node, AUDIO_API_KEY, audioApi_); parseValue(node, AGC_KEY, agcEnabled_); parseValue(node, CAPTURE_MUTED_KEY, captureMuted_); parseValue(node, NOISE_REDUCE_KEY, denoise_); parseValue(node, PLAYBACK_MUTED_KEY, playbackMuted_); // pulse submap const auto& pulse = node[PULSEMAP_KEY]; parseValue(pulse, DEVICE_PLAYBACK_KEY, pulseDevicePlayback_); parseValue(pulse, DEVICE_RECORD_KEY, pulseDeviceRecord_); parseValue(pulse, DEVICE_RINGTONE_KEY, pulseDeviceRingtone_); // portaudio submap const auto& portaudio = node[PORTAUDIO_KEY]; parseValue(portaudio, DEVICE_PLAYBACK_KEY, portaudioDevicePlayback_); parseValue(portaudio, DEVICE_RECORD_KEY, portaudioDeviceRecord_); parseValue(portaudio, DEVICE_RINGTONE_KEY, portaudioDeviceRingtone_); // more common options! parseValue(node, RECORDPATH_KEY, recordpath_); parseValue(node, VOLUMEMIC_KEY, volumemic_); parseValue(node, VOLUMESPKR_KEY, volumespkr_); parseValue(node, AUDIO_PROCESSOR_KEY, audioProcessor_); parseValue(node, VAD_KEY, vadEnabled_); parseValue(node, ECHO_CANCEL_KEY, echoCanceller_); } #ifdef ENABLE_VIDEO VideoPreferences::VideoPreferences() : decodingAccelerated_(true) , encodingAccelerated_(false) , recordPreview_(true) , recordQuality_(0) , conferenceResolution_(DEFAULT_CONFERENCE_RESOLUTION) {} void VideoPreferences::serialize(YAML::Emitter& out) const { out << YAML::Key << CONFIG_LABEL << YAML::Value << YAML::BeginMap; out << YAML::Key << RECORD_PREVIEW_KEY << YAML::Value << recordPreview_; out << YAML::Key << RECORD_QUALITY_KEY << YAML::Value << recordQuality_; #ifdef RING_ACCEL out << YAML::Key << DECODING_ACCELERATED_KEY << YAML::Value << decodingAccelerated_; out << YAML::Key << ENCODING_ACCELERATED_KEY << YAML::Value << encodingAccelerated_; #endif out << YAML::Key << CONFERENCE_RESOLUTION_KEY << YAML::Value << conferenceResolution_; getVideoDeviceMonitor().serialize(out); out << YAML::EndMap; } void VideoPreferences::unserialize(const YAML::Node& in) { // values may or may not be present const auto& node = in[CONFIG_LABEL]; try { parseValue(node, RECORD_PREVIEW_KEY, recordPreview_); parseValue(node, RECORD_QUALITY_KEY, recordQuality_); } catch (...) { recordPreview_ = true; recordQuality_ = 0; } #ifdef RING_ACCEL try { parseValue(node, DECODING_ACCELERATED_KEY, decodingAccelerated_); parseValue(node, ENCODING_ACCELERATED_KEY, encodingAccelerated_); } catch (...) { decodingAccelerated_ = true; encodingAccelerated_ = false; } #endif try { parseValue(node, CONFERENCE_RESOLUTION_KEY, conferenceResolution_); } catch (...) { conferenceResolution_ = DEFAULT_CONFERENCE_RESOLUTION; } getVideoDeviceMonitor().unserialize(in); } #endif // ENABLE_VIDEO #ifdef ENABLE_PLUGIN PluginPreferences::PluginPreferences() : pluginsEnabled_(false) {} void PluginPreferences::serialize(YAML::Emitter& out) const { out << YAML::Key << CONFIG_LABEL << YAML::Value << YAML::BeginMap; out << YAML::Key << JAMI_PLUGIN_KEY << YAML::Value << pluginsEnabled_; out << YAML::Key << JAMI_PLUGINS_INSTALLED_KEY << YAML::Value << installedPlugins_; out << YAML::Key << JAMI_PLUGINS_LOADED_KEY << YAML::Value << loadedPlugins_; out << YAML::EndMap; } void PluginPreferences::unserialize(const YAML::Node& in) { // values may or may not be present const auto& node = in[CONFIG_LABEL]; try { parseValue(node, JAMI_PLUGIN_KEY, pluginsEnabled_); } catch (...) { pluginsEnabled_ = false; } const auto& installedPluginsNode = node[JAMI_PLUGINS_INSTALLED_KEY]; try { installedPlugins_ = yaml_utils::parseVector(installedPluginsNode); } catch (...) { } const auto& loadedPluginsNode = node[JAMI_PLUGINS_LOADED_KEY]; try { loadedPlugins_ = yaml_utils::parseVector(loadedPluginsNode); } catch (...) { // loadedPlugins_ = {}; } } #endif // ENABLE_PLUGIN } // namespace jami
19,662
C++
.cpp
531
33.050847
94
0.692893
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,712
ring_api.cpp
savoirfairelinux_jami-daemon/src/ring_api.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <asio.hpp> #include <string> #include <vector> #include <map> #include <cstdlib> #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "manager.h" #include "logger.h" #include "jami.h" #include "callmanager_interface.h" #include "configurationmanager_interface.h" #include "presencemanager_interface.h" #include "client/ring_signal.h" #ifdef ENABLE_VIDEO #include "client/videomanager.h" #endif // ENABLE_VIDEO namespace libjami { InitFlag initFlags = {}; bool init(enum InitFlag flags) noexcept { initFlags = flags; jami::Logger::setDebugMode(LIBJAMI_FLAG_DEBUG == (flags & LIBJAMI_FLAG_DEBUG)); jami::Logger::setSysLog(true); jami::Logger::setConsoleLog(LIBJAMI_FLAG_CONSOLE_LOG == (flags & LIBJAMI_FLAG_CONSOLE_LOG)); const char* log_file = getenv("JAMI_LOG_FILE"); if (log_file) { jami::Logger::setFileLog(log_file); } // Following function create a local static variable inside // This var must have the same live as Manager. // So we call it now to create this var. jami::getSignalHandlers(); try { // current implementation use static variable auto& manager = jami::Manager::instance(); manager.setAutoAnswer(flags & LIBJAMI_FLAG_AUTOANSWER); #if TARGET_OS_IOS if (flags & LIBJAMI_FLAG_IOS_EXTENSION) manager.isIOSExtension = true; #endif if (flags & LIBJAMI_FLAG_NO_AUTOSYNC) manager.syncOnRegister = false; return true; } catch (...) { return false; } } bool start(const std::filesystem::path& config_file) noexcept { try { jami::Manager::instance().init(config_file, initFlags); } catch (...) { return false; } return true; } bool initialized() noexcept { return jami::Manager::initialized; } void fini() noexcept { jami::Manager::instance().finish(); jami::Logger::fini(); } void logging(const std::string& whom, const std::string& action) noexcept { if ("syslog" == whom) { jami::Logger::setSysLog(not action.empty()); } else if ("console" == whom) { jami::Logger::setConsoleLog(not action.empty()); } else if ("monitor" == whom) { jami::Logger::setMonitorLog(not action.empty()); } else if ("file" == whom) { jami::Logger::setFileLog(action); } else { JAMI_ERR("Bad log handler %s", whom.c_str()); } } void CallbackWrapperBase::post(std::function<void()> cb) { if (auto io = jami::Manager::instance().ioContext()) io->post(std::move(cb)); } } // namespace libjami
3,289
C++
.cpp
109
26.440367
96
0.685543
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,713
gittransport.cpp
savoirfairelinux_jami-daemon/src/gittransport.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "gittransport.h" #include "manager.h" #include <dhtnet/multiplexed_socket.h> #include <dhtnet/connectionmanager.h> using namespace std::string_view_literals; // NOTE: THIS MUST BE IN THE ROOT NAMESPACE FOR LIBGIT2 int generateRequest(git_buf* request, const std::string& cmd, const std::string_view& url) { if (cmd.empty()) { giterr_set_str(GITERR_NET, "empty command"); return -1; } // url format = deviceId/conversationId auto delim = url.find('/'); if (delim == std::string::npos) { giterr_set_str(GITERR_NET, "malformed URL"); return -1; } auto deviceId = url.substr(0, delim); auto conversationId = url.substr(delim, url.size()); auto nullSeparator = "\0"sv; auto total = 4 /* 4 bytes for the len len */ + cmd.size() /* followed by the command */ + 1 /* space */ + conversationId.size() /* conversation */ + 1 /* \0 */ + HOST_TAG.size() + deviceId.size() /* device */ + nullSeparator.size() /* \0 */; std::ostringstream streamed; streamed << std::setw(4) << std::setfill('0') << std::hex << (total & 0x0FFFF) << cmd; streamed << " " << conversationId; streamed << nullSeparator << HOST_TAG << deviceId << nullSeparator; auto str = streamed.str(); git_buf_set(request, str.c_str(), str.size()); return 0; } int sendCmd(P2PStream* s) { auto res = 0; git_buf request = {}; if ((res = generateRequest(&request, s->cmd, s->url)) < 0) { git_buf_dispose(&request); return res; } std::error_code ec; auto sock = s->socket.lock(); if (!sock) { git_buf_dispose(&request); return -1; } if ((res = sock->write(reinterpret_cast<const unsigned char*>(request.ptr), request.size, ec))) { s->sent_command = 1; git_buf_dispose(&request); return res; } s->sent_command = 1; git_buf_dispose(&request); return res; } int P2PStreamRead(git_smart_subtransport_stream* stream, char* buffer, size_t buflen, size_t* read) { *read = 0; auto* fs = reinterpret_cast<P2PStream*>(stream); auto sock = fs->socket.lock(); if (!sock) { giterr_set_str(GITERR_NET, "unavailable socket"); return -1; } int res = 0; // If it's the first read, we need to send // the upload-pack command if (!fs->sent_command && (res = sendCmd(fs)) < 0) return res; std::error_code ec; // TODO ChannelSocket needs a blocking read operation size_t datalen = sock->waitForData(std::chrono::milliseconds(3600 * 1000 * 24), ec); if (datalen > 0) *read = sock->read(reinterpret_cast<unsigned char*>(buffer), std::min(datalen, buflen), ec); return res; } int P2PStreamWrite(git_smart_subtransport_stream* stream, const char* buffer, size_t len) { auto* fs = reinterpret_cast<P2PStream*>(stream); auto sock = fs->socket.lock(); if (!sock) { giterr_set_str(GITERR_NET, "unavailable socket"); return -1; } std::error_code ec; sock->write(reinterpret_cast<const unsigned char*>(buffer), len, ec); if (ec) { giterr_set_str(GITERR_NET, ec.message().c_str()); return -1; } return 0; } void P2PStreamFree(git_smart_subtransport_stream*) {} int P2PSubTransportAction(git_smart_subtransport_stream** out, git_smart_subtransport* transport, const char* url, git_smart_service_t action) { auto* sub = reinterpret_cast<P2PSubTransport*>(transport); if (!sub || !sub->remote) { JAMI_ERROR("Invalid subtransport"); return -1; } auto repo = git_remote_owner(sub->remote); if (!repo) { JAMI_ERROR("No repository linked to the transport"); return -1; } const auto* workdir = git_repository_workdir(repo); if (!workdir) { JAMI_ERROR("No working linked to the repository"); return -1; } std::string_view path = workdir; auto delimConv = path.rfind("/conversations"); if (delimConv == std::string::npos) { JAMI_ERROR("No conversation id found"); return -1; } auto delimAccount = path.rfind('/', delimConv - 1); if (delimAccount == std::string::npos && delimConv - 1 - delimAccount == 16) { JAMI_ERROR("No account id found"); return -1; } auto accountId = path.substr(delimAccount + 1, delimConv - 1 - delimAccount); std::string_view gitUrl = url + ("git://"sv).size(); auto delim = gitUrl.find('/'); if (delim == std::string::npos) { JAMI_ERROR("Incorrect url {:s}", gitUrl); return -1; } auto deviceId = gitUrl.substr(0, delim); auto conversationId = gitUrl.substr(delim + 1, gitUrl.size()); if (action == GIT_SERVICE_UPLOADPACK_LS) { auto gitSocket = jami::Manager::instance().gitSocket(accountId, deviceId, conversationId); if (!gitSocket) { JAMI_ERROR("Unable to find related socket for {:s}, {:s}, {:s}", accountId, deviceId, conversationId); return -1; } auto stream = std::make_unique<P2PStream>(); stream->socket = gitSocket; stream->base.read = P2PStreamRead; stream->base.write = P2PStreamWrite; stream->base.free = P2PStreamFree; stream->cmd = UPLOAD_PACK_CMD; stream->url = gitUrl; sub->stream = std::move(stream); *out = &sub->stream->base; return 0; } else if (action == GIT_SERVICE_UPLOADPACK) { if (sub->stream) { *out = &sub->stream->base; return 0; } return -1; } return 0; } int P2PSubTransportClose(git_smart_subtransport*) { return 0; } void P2PSubTransportFree(git_smart_subtransport* transport) { jami::Manager::instance().eraseGitTransport(transport); } int P2PSubTransportNew(P2PSubTransport** out, git_transport*, void* payload) { auto sub = std::make_unique<P2PSubTransport>(); sub->remote = reinterpret_cast<git_remote*>(payload); auto* base = &sub->base; base->action = P2PSubTransportAction; base->close = P2PSubTransportClose; base->free = P2PSubTransportFree; *out = sub.get(); jami::Manager::instance().insertGitTransport(base, std::move(sub)); return 0; } int p2p_subtransport_cb(git_smart_subtransport** out, git_transport* owner, void* payload) { P2PSubTransport* sub; if (P2PSubTransportNew(&sub, owner, payload) < 0) return -1; *out = &sub->base; return 0; } int p2p_transport_cb(git_transport** out, git_remote* owner, void*) { git_smart_subtransport_definition def = {p2p_subtransport_cb, 0, /* Because we use an already existing channel socket, we use a permanent transport */ reinterpret_cast<void*>(owner)}; return git_transport_smart(out, owner, &def); }
7,895
C++
.cpp
229
28.545852
101
0.613038
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,714
manager.cpp
savoirfairelinux_jami-daemon/src/manager.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "manager.h" #include "logger.h" #include "account_schema.h" #include "fileutils.h" #include "gittransport.h" #include "map_utils.h" #include "account.h" #include "string_utils.h" #include "jamidht/jamiaccount.h" #include "account.h" #include <opendht/rng.h> #include "call_factory.h" #include "connectivity/sip_utils.h" #include "sip/sipvoiplink.h" #include "sip/sipaccount_config.h" #include "im/instant_messaging.h" #include "config/yamlparser.h" #if HAVE_ALSA #include "audio/alsa/alsalayer.h" #endif #include "media/localrecordermanager.h" #include "audio/sound/tonelist.h" #include "audio/sound/dtmf.h" #include "audio/ringbufferpool.h" #ifdef ENABLE_PLUGIN #include "plugin/jamipluginmanager.h" #include "plugin/streamdata.h" #endif #include "client/videomanager.h" #include "conference.h" #include "client/ring_signal.h" #include "jami/call_const.h" #include "jami/account_const.h" #include "libav_utils.h" #ifdef ENABLE_VIDEO #include "video/video_scaler.h" #include "video/sinkclient.h" #include "video/video_base.h" #include "media/video/video_mixer.h" #endif #include "audio/tonecontrol.h" #include "data_transfer.h" #include "jami/media_const.h" #include <dhtnet/ice_transport_factory.h> #include <dhtnet/ice_transport.h> #include <dhtnet/upnp/upnp_context.h> #include <libavutil/ffversion.h> #include <opendht/thread_pool.h> #include <asio/io_context.hpp> #include <asio/executor_work_guard.hpp> #include <git2.h> #ifndef WIN32 #include <sys/time.h> #include <sys/resource.h> #endif #ifdef TARGET_OS_IOS #include <CoreFoundation/CoreFoundation.h> #endif #include <cerrno> #include <ctime> #include <cstdlib> #include <iostream> #include <fstream> #include <sstream> #include <algorithm> #include <memory> #include <mutex> #include <list> #include <random> #ifndef JAMI_DATADIR #error "Define the JAMI_DATADIR macro as the data installation prefix of the package" #endif namespace jami { /** To store uniquely a list of Call ids */ using CallIDSet = std::set<std::string>; static constexpr const char* PACKAGE_OLD = "ring"; std::atomic_bool Manager::initialized = {false}; #if TARGET_OS_IOS bool Manager::isIOSExtension = {false}; #endif bool Manager::syncOnRegister = {true}; bool Manager::autoLoad = {true}; static void copy_over(const std::filesystem::path& srcPath, const std::filesystem::path& destPath) { std::ifstream src(srcPath); std::ofstream dest(destPath); dest << src.rdbuf(); src.close(); dest.close(); } // Creates a backup of the file at "path" with a .bak suffix appended static void make_backup(const std::filesystem::path& path) { auto backup_path = path; backup_path.replace_extension(".bak"); copy_over(path, backup_path); } // Restore last backup of the configuration file static void restore_backup(const std::filesystem::path& path) { auto backup_path = path; backup_path.replace_extension(".bak"); copy_over(backup_path, path); } void check_rename(const std::filesystem::path& old_dir, const std::filesystem::path& new_dir) { if (old_dir == new_dir or not std::filesystem::is_directory(old_dir)) return; std::error_code ec; if (not std::filesystem::is_directory(new_dir)) { JAMI_WARNING("Migrating {} to {}", old_dir, new_dir); std::filesystem::rename(old_dir, new_dir, ec); if (ec) JAMI_ERROR("Failed to rename {} to {}: {}", old_dir, new_dir, ec.message()); } else { for (const auto& file_iterator : std::filesystem::directory_iterator(old_dir, ec)) { const auto& file_path = file_iterator.path(); auto new_path = new_dir / file_path.filename(); if (file_iterator.is_directory() and std::filesystem::is_directory(new_path)) { check_rename(file_path, new_path); } else { JAMI_WARNING("Migrating {} to {}", old_dir, new_path); std::filesystem::rename(file_path, new_path, ec); if (ec) JAMI_ERROR("Failed to rename {} to {}: {}", file_path, new_path, ec.message()); } } std::filesystem::remove_all(old_dir, ec); } } /** * Set OpenDHT's log level based on the DHTLOGLEVEL environment variable. * DHTLOGLEVEL = 0 minimum logging (=disable) * DHTLOGLEVEL = 1 (=ERROR only) * DHTLOGLEVEL = 2 (+=WARN) * DHTLOGLEVEL = 3 maximum logging (+=DEBUG) */ /** Environment variable used to set OpenDHT's logging level */ static constexpr const char* DHTLOGLEVEL = "DHTLOGLEVEL"; static void setDhtLogLevel() { int level = 0; if (auto envvar = getenv(DHTLOGLEVEL)) { level = to_int<int>(envvar, 0); level = std::clamp(level, 0, 3); JAMI_DBG("DHTLOGLEVEL=%u", level); } Manager::instance().dhtLogLevel = level; } /** * Set pjsip's log level based on the SIPLOGLEVEL environment variable. * SIPLOGLEVEL = 0 minimum logging * SIPLOGLEVEL = 6 maximum logging */ /** Environment variable used to set pjsip's logging level */ static constexpr const char* SIPLOGLEVEL = "SIPLOGLEVEL"; static void setSipLogLevel() { char* envvar = getenv(SIPLOGLEVEL); int level = 0; if (envvar != nullptr) { level = to_int<int>(envvar, 0); // From 0 (min) to 6 (max) level = std::max(0, std::min(level, 6)); } pj_log_set_level(level); pj_log_set_log_func([](int level, const char* data, int /*len*/) { if (level < 2) JAMI_ERR() << data; else if (level < 4) JAMI_WARN() << data; else JAMI_DBG() << data; }); } /** * Set gnutls's log level based on the RING_TLS_LOGLEVEL environment variable. * RING_TLS_LOGLEVEL = 0 minimum logging (default) * RING_TLS_LOGLEVEL = 9 maximum logging */ static constexpr int RING_TLS_LOGLEVEL = 0; static void tls_print_logs(int level, const char* msg) { JAMI_XDBG("[%d]GnuTLS: %s", level, msg); } static void setGnuTlsLogLevel() { char* envvar = getenv("RING_TLS_LOGLEVEL"); int level = RING_TLS_LOGLEVEL; if (envvar != nullptr) { level = to_int<int>(envvar); // From 0 (min) to 9 (max) level = std::max(0, std::min(level, 9)); } gnutls_global_set_log_level(level); gnutls_global_set_log_function(tls_print_logs); } //============================================================================== struct Manager::ManagerPimpl { explicit ManagerPimpl(Manager& base); bool parseConfiguration(); /* * Play one tone * @return false if the driver is uninitialize */ void playATone(Tone::ToneId toneId); int getCurrentDeviceIndex(AudioDeviceType type); /** * Process remaining participant given a conference and the current call id. * Mainly called when a participant is detached or hagned up * @param current call id * @param conference pointer */ void processRemainingParticipants(Conference& conf); /** * Create config directory in home user and return configuration file path */ std::filesystem::path retrieveConfigPath() const; void unsetCurrentCall(); void switchCall(const std::string& id); /** * Add incoming callid to the waiting list * @param id std::string to add */ void addWaitingCall(const std::string& id); /** * Remove incoming callid to the waiting list * @param id std::string to remove */ void removeWaitingCall(const std::string& id); void loadAccount(const YAML::Node& item, int& errorCount); void sendTextMessageToConference(const Conference& conf, const std::map<std::string, std::string>& messages, const std::string& from) const noexcept; void bindCallToConference(Call& call, Conference& conf); void addMainParticipant(Conference& conf); bool hangupConference(Conference& conf); template<class T> std::shared_ptr<T> findAccount(const std::function<bool(const std::shared_ptr<T>&)>&); void initAudioDriver(); void processIncomingCall(const std::string& accountId, Call& incomCall); static void stripSipPrefix(Call& incomCall); Manager& base_; // pimpl back-pointer std::shared_ptr<asio::io_context> ioContext_; std::thread ioContextRunner_; std::shared_ptr<dhtnet::upnp::UPnPContext> upnpContext_; /** Main scheduler */ ScheduledExecutor scheduler_ {"manager"}; std::atomic_bool autoAnswer_ {false}; /** Application wide tone controller */ ToneControl toneCtrl_; std::unique_ptr<AudioDeviceGuard> toneDeviceGuard_; /** Current Call ID */ std::string currentCall_; /** Protected current call access */ std::mutex currentCallMutex_; /** Protected sinks access */ std::mutex sinksMutex_; /** Audio layer */ std::shared_ptr<AudioLayer> audiodriver_ {nullptr}; std::array<std::atomic_uint, 3> audioStreamUsers_ {}; // Main thread std::unique_ptr<DTMF> dtmfKey_; /** Buffer to generate DTMF */ std::shared_ptr<AudioFrame> dtmfBuf_; // To handle volume control // short speakerVolume_; // short micVolume_; // End of sound variable /** * Mutex used to protect audio layer */ std::mutex audioLayerMutex_; /** * Waiting Call Vectors */ CallIDSet waitingCalls_; /** * Protect waiting call list, access by many voip/audio threads */ std::mutex waitingCallsMutex_; /** * Path of the ConfigFile */ std::filesystem::path path_; /** * Instance of the RingBufferPool for the whole application * * In order to send signal to other parts of the application, one must pass through the * RingBufferMananger. Audio instances must be registered into the RingBufferMananger and bound * together via the Manager. * */ std::unique_ptr<RingBufferPool> ringbufferpool_; std::atomic_bool finished_ {false}; /* ICE support */ std::shared_ptr<dhtnet::IceTransportFactory> ice_tf_; /* Sink ID mapping */ std::map<std::string, std::weak_ptr<video::SinkClient>> sinkMap_; std::unique_ptr<VideoManager> videoManager_; std::unique_ptr<SIPVoIPLink> sipLink_; #ifdef ENABLE_PLUGIN /* Jami Plugin Manager */ std::unique_ptr<JamiPluginManager> jami_plugin_manager; #endif std::mutex gitTransportsMtx_ {}; std::map<git_smart_subtransport*, std::unique_ptr<P2PSubTransport>> gitTransports_ {}; }; Manager::ManagerPimpl::ManagerPimpl(Manager& base) : base_(base) , ioContext_(std::make_shared<asio::io_context>()) , upnpContext_(std::make_shared<dhtnet::upnp::UPnPContext>(nullptr, Logger::dhtLogger())) , toneCtrl_(base.preferences) , dtmfBuf_(std::make_shared<AudioFrame>()) , ringbufferpool_(new RingBufferPool) #ifdef ENABLE_VIDEO , videoManager_(new VideoManager) #endif { jami::libav_utils::av_init(); ioContextRunner_ = std::thread([context = ioContext_]() { try { auto work = asio::make_work_guard(*context); context->run(); } catch (const std::exception& ex) { JAMI_ERR("Unexpected io_context thread exception: %s", ex.what()); } }); } bool Manager::ManagerPimpl::parseConfiguration() { bool result = true; try { std::ifstream file(path_); YAML::Node parsedFile = YAML::Load(file); file.close(); const int error_count = base_.loadAccountMap(parsedFile); if (error_count > 0) { JAMI_WARN("Errors while parsing %s", path_.c_str()); result = false; } } catch (const YAML::BadFile& e) { JAMI_WARN("Unable to open configuration file"); result = false; } return result; } /** * Multi Thread */ void Manager::ManagerPimpl::playATone(Tone::ToneId toneId) { if (not base_.voipPreferences.getPlayTones()) return; std::lock_guard lock(audioLayerMutex_); if (not audiodriver_) { JAMI_ERR("Audio layer not initialized"); return; } auto oldGuard = std::move(toneDeviceGuard_); toneDeviceGuard_ = base_.startAudioStream(AudioDeviceType::PLAYBACK); audiodriver_->flushUrgent(); toneCtrl_.play(toneId); } int Manager::ManagerPimpl::getCurrentDeviceIndex(AudioDeviceType type) { if (not audiodriver_) return -1; switch (type) { case AudioDeviceType::PLAYBACK: return audiodriver_->getIndexPlayback(); case AudioDeviceType::RINGTONE: return audiodriver_->getIndexRingtone(); case AudioDeviceType::CAPTURE: return audiodriver_->getIndexCapture(); default: return -1; } } void Manager::ManagerPimpl::processRemainingParticipants(Conference& conf) { const std::string current_callId(base_.getCurrentCallId()); CallIdSet subcalls(conf.getSubCalls()); const size_t n = subcalls.size(); JAMI_DEBUG("Process remaining {} participant(s) from conference {}", n, conf.getConfId()); if (n > 1) { // Reset ringbuffer's readpointers for (const auto& p : subcalls) { if (auto call = base_.getCallFromCallID(p)) { auto medias = call->getAudioStreams(); for (const auto& media : medias) { JAMI_DEBUG("[call:{}] Remove local audio {}", p, media.first); base_.getRingBufferPool().flush(media.first); } } } base_.getRingBufferPool().flush(RingBufferPool::DEFAULT_ID); } else { if (auto acc = std::dynamic_pointer_cast<JamiAccount>(conf.getAccount())) { // Stay in a conference if 1 participants for swarm and rendezvous if (auto cm = acc->convModule(true)) { if (acc->isRendezVous() || cm->isHosting("", conf.getConfId())) { // Check if attached if (conf.getState() == Conference::State::ACTIVE_ATTACHED) { return; } } } } if (n == 1) { // this call is the last participant (non swarm-call), hence // the conference is over auto p = subcalls.begin(); if (auto call = base_.getCallFromCallID(*p)) { // if we are not listening to this conference and not a rendez-vous auto w = call->getAccount(); auto account = w.lock(); if (!account) { JAMI_ERR("No account detected"); return; } if (current_callId != conf.getConfId()) base_.onHoldCall(account->getAccountID(), call->getCallId()); else switchCall(call->getCallId()); } JAMI_DBG("No remaining participants, remove conference"); if (auto account = conf.getAccount()) account->removeConference(conf.getConfId()); } else { JAMI_DBG("No remaining participants, remove conference"); if (auto account = conf.getAccount()) account->removeConference(conf.getConfId()); unsetCurrentCall(); } } } /** * Initialization: Main Thread */ std::filesystem::path Manager::ManagerPimpl::retrieveConfigPath() const { // TODO: Migrate config filename from dring.yml to jami.yml. return fileutils::get_config_dir() / "dring.yml"; } void Manager::ManagerPimpl::unsetCurrentCall() { currentCall_ = ""; } void Manager::ManagerPimpl::switchCall(const std::string& id) { std::lock_guard m(currentCallMutex_); JAMI_DBG("----- Switch current call id to '%s' -----", not id.empty() ? id.c_str() : "none"); currentCall_ = id; } void Manager::ManagerPimpl::addWaitingCall(const std::string& id) { std::lock_guard m(waitingCallsMutex_); // Enable incoming call beep if needed. if (audiodriver_ and waitingCalls_.empty() and not currentCall_.empty()) audiodriver_->playIncomingCallNotification(true); waitingCalls_.insert(id); } void Manager::ManagerPimpl::removeWaitingCall(const std::string& id) { std::lock_guard m(waitingCallsMutex_); waitingCalls_.erase(id); if (audiodriver_ and waitingCalls_.empty()) audiodriver_->playIncomingCallNotification(false); } void Manager::ManagerPimpl::loadAccount(const YAML::Node& node, int& errorCount) { using yaml_utils::parseValue; using yaml_utils::parseValueOptional; std::string accountid; parseValue(node, "id", accountid); std::string accountType(ACCOUNT_TYPE_SIP); parseValueOptional(node, "type", accountType); if (!accountid.empty()) { if (auto a = base_.accountFactory.createAccount(accountType, accountid)) { auto config = a->buildConfig(); config->unserialize(node); a->setConfig(std::move(config)); } else { JAMI_ERROR("Failed to create account of type \"{:s}\"", accountType); ++errorCount; } } } // THREAD=VoIP void Manager::ManagerPimpl::sendTextMessageToConference(const Conference& conf, const std::map<std::string, std::string>& messages, const std::string& from) const noexcept { CallIdSet subcalls(conf.getSubCalls()); for (const auto& callId : subcalls) { try { auto call = base_.getCallFromCallID(callId); if (not call) throw std::runtime_error("no associated call"); call->sendTextMessage(messages, from); } catch (const std::exception& e) { JAMI_ERR("Failed to send message to conference participant %s: %s", callId.c_str(), e.what()); } } } void Manager::bindCallToConference(Call& call, Conference& conf) { pimpl_->bindCallToConference(call, conf); } void Manager::ManagerPimpl::bindCallToConference(Call& call, Conference& conf) { const auto& callId = call.getCallId(); const auto& confId = conf.getConfId(); const auto& state = call.getStateStr(); // ensure that calls are only in one conference at a time if (call.isConferenceParticipant()) base_.detachParticipant(callId); JAMI_DEBUG("[call:{}] bind to conference {} (callState={})", callId, confId, state); auto medias = call.getAudioStreams(); for (const auto& media : medias) { JAMI_DEBUG("[call:{}] Remove local audio {}", callId, media.first); base_.getRingBufferPool().unBindAll(media.first); } conf.addSubCall(callId); if (state == "HOLD") { base_.offHoldCall(call.getAccountId(), callId); } else if (state == "INCOMING") { base_.answerCall(call); } else if (state == "CURRENT") { } else if (state == "INACTIVE") { base_.answerCall(call); } else JAMI_WARNING("[call:{}] call state {} not recognized for conference", callId, state); } //============================================================================== Manager& Manager::instance() { // Meyers singleton static Manager instance; // This will give a warning that can be ignored the first time instance() // is called...subsequent warnings are more serious if (not Manager::initialized) JAMI_DBG("Not initialized"); return instance; } Manager::Manager() : rand_(dht::crypto::getSeededRandomEngine<std::mt19937_64>()) , preferences() , voipPreferences() , audioPreference() #ifdef ENABLE_PLUGIN , pluginPreferences() #endif #ifdef ENABLE_VIDEO , videoPreferences() #endif , callFactory(rand_) , accountFactory() { #if defined _MSC_VER gnutls_global_init(); #endif pimpl_ = std::make_unique<ManagerPimpl>(*this); } Manager::~Manager() {} void Manager::setAutoAnswer(bool enable) { pimpl_->autoAnswer_ = enable; } void Manager::init(const std::filesystem::path& config_file, libjami::InitFlag flags) { // FIXME: this is no good initialized = true; git_libgit2_init(); auto res = git_transport_register("git", p2p_transport_cb, nullptr); if (res < 0) { const git_error* error = giterr_last(); JAMI_ERROR("Unable to initialize git transport: {}", error ? error->message : "(unknown)"); } #ifndef WIN32 // Set the max number of open files. struct rlimit nofiles; if (getrlimit(RLIMIT_NOFILE, &nofiles) == 0) { if (nofiles.rlim_cur < nofiles.rlim_max && nofiles.rlim_cur <= 1024u) { nofiles.rlim_cur = std::min<rlim_t>(nofiles.rlim_max, 8192u); setrlimit(RLIMIT_NOFILE, &nofiles); } } #endif #define PJSIP_TRY(ret) \ do { \ if ((ret) != PJ_SUCCESS) \ throw std::runtime_error(#ret " failed"); \ } while (0) srand(time(nullptr)); // to get random number for RANDOM_PORT // Initialize PJSIP (SIP and ICE implementation) PJSIP_TRY(pj_init()); setSipLogLevel(); PJSIP_TRY(pjlib_util_init()); PJSIP_TRY(pjnath_init()); #undef PJSIP_TRY setGnuTlsLogLevel(); JAMI_LOG("Using PJSIP version {:s} for {:s}", pj_get_version(), PJ_OS_NAME); JAMI_LOG("Using GnuTLS version {:s}", gnutls_check_version(nullptr)); JAMI_LOG("Using OpenDHT version {:s}", dht::version()); JAMI_LOG("Using FFmpeg version {:s}", av_version_info()); int git2_major = 0, git2_minor = 0, git2_rev = 0; if (git_libgit2_version(&git2_major, &git2_minor, &git2_rev) == 0) { JAMI_LOG("Using Libgit2 version {:d}.{:d}.{:d}", git2_major, git2_minor, git2_rev); } setDhtLogLevel(); // Manager can restart without being recreated (Unit tests) // So only create the SipLink once pimpl_->sipLink_ = std::make_unique<SIPVoIPLink>(); check_rename(fileutils::get_cache_dir(PACKAGE_OLD), fileutils::get_cache_dir()); check_rename(fileutils::get_data_dir(PACKAGE_OLD), fileutils::get_data_dir()); check_rename(fileutils::get_config_dir(PACKAGE_OLD), fileutils::get_config_dir()); pimpl_->ice_tf_ = std::make_shared<dhtnet::IceTransportFactory>(Logger::dhtLogger()); pimpl_->path_ = config_file.empty() ? pimpl_->retrieveConfigPath() : config_file; JAMI_LOG("Configuration file path: {}", pimpl_->path_); #ifdef ENABLE_PLUGIN pimpl_->jami_plugin_manager = std::make_unique<JamiPluginManager>(); #endif bool no_errors = true; // manager can restart without being recreated (Unit tests) pimpl_->finished_ = false; if (libjami::LIBJAMI_FLAG_NO_AUTOLOAD & flags) { autoLoad = false; JAMI_DBG("LIBJAMI_FLAG_NO_AUTOLOAD is set, accounts will neither be loaded nor backed up"); } else { try { no_errors = pimpl_->parseConfiguration(); } catch (const YAML::Exception& e) { JAMI_ERR("%s", e.what()); no_errors = false; } // always back up last error-free configuration if (no_errors) { make_backup(pimpl_->path_); } else { // restore previous configuration JAMI_WARNING("Restoring last working configuration"); try { // remove accounts from broken configuration removeAccounts(); restore_backup(pimpl_->path_); pimpl_->parseConfiguration(); } catch (const YAML::Exception& e) { JAMI_ERROR("{}", e.what()); JAMI_WARNING("Restoring backup failed"); } } } if (!(flags & libjami::LIBJAMI_FLAG_NO_LOCAL_AUDIO)) { std::lock_guard lock(pimpl_->audioLayerMutex_); pimpl_->initAudioDriver(); if (pimpl_->audiodriver_) { auto format = pimpl_->audiodriver_->getFormat(); pimpl_->toneCtrl_.setSampleRate(format.sample_rate, format.sampleFormat); pimpl_->dtmfKey_.reset( new DTMF(getRingBufferPool().getInternalSamplingRate(), getRingBufferPool().getInternalAudioFormat().sampleFormat)); } } if (libjami::LIBJAMI_FLAG_NO_AUTOLOAD & flags) { JAMI_DBG("LIBJAMI_FLAG_NO_AUTOLOAD is set, accounts and conversations will not be loaded"); return; } else { registerAccounts(); } } void Manager::finish() noexcept { bool expected = false; if (not pimpl_->finished_.compare_exchange_strong(expected, true)) return; try { // Terminate UPNP context upnpContext()->shutdown(); // Forbid call creation callFactory.forbid(); // Hangup all remaining active calls JAMI_DBG("Hangup %zu remaining call(s)", callFactory.callCount()); for (const auto& call : callFactory.getAllCalls()) hangupCall(call->getAccountId(), call->getCallId()); callFactory.clear(); for (const auto& account : getAllAccounts<JamiAccount>()) { if (account->getRegistrationState() == RegistrationState::INITIALIZING) removeAccount(account->getAccountID(), true); } saveConfig(); // Disconnect accounts, close link stacks and free allocated ressources unregisterAccounts(); accountFactory.clear(); { std::lock_guard lock(pimpl_->audioLayerMutex_); pimpl_->audiodriver_.reset(); } JAMI_DBG("Stopping schedulers and worker threads"); // Flush remaining tasks (free lambda' with capture) pimpl_->scheduler_.stop(); dht::ThreadPool::io().join(); dht::ThreadPool::computation().join(); // IceTransportFactory should be stopped after the io pool // as some ICE are destroyed in a ioPool (see ConnectionManager) // Also, it must be called before pj_shutdown to avoid any problem pimpl_->ice_tf_.reset(); // NOTE: sipLink_->shutdown() is needed because this will perform // sipTransportBroker->shutdown(); which will call Manager::instance().sipVoIPLink() // so the pointer MUST NOT be resetted at this point if (pimpl_->sipLink_) { pimpl_->sipLink_->shutdown(); pimpl_->sipLink_.reset(); } pj_shutdown(); pimpl_->gitTransports_.clear(); git_libgit2_shutdown(); if (!pimpl_->ioContext_->stopped()) { pimpl_->ioContext_->reset(); // allow to finish pimpl_->ioContext_->stop(); // make thread stop } if (pimpl_->ioContextRunner_.joinable()) pimpl_->ioContextRunner_.join(); #if defined _MSC_VER gnutls_global_deinit(); #endif } catch (const VoipLinkException& err) { JAMI_ERR("%s", err.what()); } } void Manager::monitor(bool continuous) { Logger::setMonitorLog(true); JAMI_DBG("############## START MONITORING ##############"); JAMI_DBG("Using PJSIP version %s for %s", pj_get_version(), PJ_OS_NAME); JAMI_DBG("Using GnuTLS version %s", gnutls_check_version(nullptr)); JAMI_DBG("Using OpenDHT version %s", dht::version()); #ifdef __linux__ #if defined(__ANDROID__) #else auto opened_files = dhtnet::fileutils::readDirectory("/proc/" + std::to_string(getpid()) + "/fd").size(); JAMI_DBG("Opened files: %lu", opened_files); #endif #endif for (const auto& call : callFactory.getAllCalls()) call->monitor(); for (const auto& account : getAllAccounts()) if (auto acc = std::dynamic_pointer_cast<JamiAccount>(account)) acc->monitor(); JAMI_DBG("############## END MONITORING ##############"); Logger::setMonitorLog(continuous); } std::vector<std::map<std::string, std::string>> Manager::getConnectionList(const std::string& accountId, const std::string& conversationId) { std::vector<std::map<std::string, std::string>> connectionsList; if (accountId.empty()) { for (const auto& account : getAllAccounts<JamiAccount>()) { if (account->getRegistrationState() != RegistrationState::INITIALIZING) { const auto& cnl = account->getConnectionList(conversationId); connectionsList.insert(connectionsList.end(), cnl.begin(), cnl.end()); } } } else { auto account = getAccount(accountId); if (account) { if (auto acc = std::dynamic_pointer_cast<JamiAccount>(account)) { if (acc->getRegistrationState() != RegistrationState::INITIALIZING) { const auto& cnl = acc->getConnectionList(conversationId); connectionsList.insert(connectionsList.end(), cnl.begin(), cnl.end()); } } } } return connectionsList; } std::vector<std::map<std::string, std::string>> Manager::getChannelList(const std::string& accountId, const std::string& connectionId) { // if account id is empty, return all channels // else return only for specific accountid std::vector<std::map<std::string, std::string>> channelsList; if (accountId.empty()) { for (const auto& account : getAllAccounts<JamiAccount>()) { if (account->getRegistrationState() != RegistrationState::INITIALIZING) { // add to channelsList all channels for this account const auto& cnl = account->getChannelList(connectionId); channelsList.insert(channelsList.end(), cnl.begin(), cnl.end()); } } } else { // get the jamiaccount for this accountid and return its channels auto account = getAccount(accountId); if (account) { if (auto acc = std::dynamic_pointer_cast<JamiAccount>(account)) { if (acc->getRegistrationState() != RegistrationState::INITIALIZING) { const auto& cnl = acc->getChannelList(connectionId); channelsList.insert(channelsList.end(), cnl.begin(), cnl.end()); } } } } return channelsList; } bool Manager::isCurrentCall(const Call& call) const { return pimpl_->currentCall_ == call.getCallId(); } bool Manager::hasCurrentCall() const { for (const auto& call : callFactory.getAllCalls()) { if (!call->isSubcall() && call->getStateStr() == libjami::Call::StateEvent::CURRENT) return true; } return false; } std::shared_ptr<Call> Manager::getCurrentCall() const { return getCallFromCallID(pimpl_->currentCall_); } const std::string& Manager::getCurrentCallId() const { return pimpl_->currentCall_; } void Manager::unregisterAccounts() { for (const auto& account : getAllAccounts()) { if (account->isEnabled()) { if (auto acc = std::dynamic_pointer_cast<JamiAccount>(account)) { // Note: shutdown the connections as doUnregister will not do it (because the // account is enabled) acc->shutdownConnections(); } account->doUnregister(); } } } /////////////////////////////////////////////////////////////////////////////// // Management of events' IP-phone user /////////////////////////////////////////////////////////////////////////////// /* Main Thread */ std::string Manager::outgoingCall(const std::string& account_id, const std::string& to, const std::vector<libjami::MediaMap>& mediaList) { JAMI_DBG() << "try outgoing call to '" << to << "'" << " with account '" << account_id << "'"; std::shared_ptr<Call> call; try { call = newOutgoingCall(trim(to), account_id, mediaList); } catch (const std::exception& e) { JAMI_ERROR("{}", e.what()); return {}; } if (not call) return {}; stopTone(); pimpl_->switchCall(call->getCallId()); return call->getCallId(); } // THREAD=Main : for outgoing Call bool Manager::answerCall(const std::string& accountId, const std::string& callId, const std::vector<libjami::MediaMap>& mediaList) { if (auto account = getAccount(accountId)) { if (auto call = account->getCall(callId)) { return answerCall(*call, mediaList); } } return false; } bool Manager::answerCall(Call& call, const std::vector<libjami::MediaMap>& mediaList) { JAMI_LOG("Answer call {}", call.getCallId()); if (call.getConnectionState() != Call::ConnectionState::RINGING) { // The call is already answered return true; } // If ringing stopTone(); pimpl_->removeWaitingCall(call.getCallId()); try { call.answer(mediaList); } catch (const std::runtime_error& e) { JAMI_ERR("%s", e.what()); return false; } // if we dragged this call into a conference already if (auto conf = call.getConference()) pimpl_->switchCall(conf->getConfId()); else pimpl_->switchCall(call.getCallId()); addAudio(call); // Start recording if set in preference if (audioPreference.getIsAlwaysRecording()) { auto recResult = call.toggleRecording(); emitSignal<libjami::CallSignal::RecordPlaybackFilepath>(call.getCallId(), call.getPath()); emitSignal<libjami::CallSignal::RecordingStateChanged>(call.getCallId(), recResult); } return true; } // THREAD=Main bool Manager::hangupCall(const std::string& accountId, const std::string& callId) { auto account = getAccount(accountId); if (not account) return false; // store the current call id stopTone(); pimpl_->removeWaitingCall(callId); /* We often get here when the call was hungup before being created */ auto call = account->getCall(callId); if (not call) { JAMI_WARN("Unable to hang up non-existant call %s", callId.c_str()); return false; } // Disconnect streams removeAudio(*call); if (call->isConferenceParticipant()) { removeParticipant(*call); } else { // we are not participating in a conference, current call switched to "" if (isCurrentCall(*call)) pimpl_->unsetCurrentCall(); } try { call->hangup(0); } catch (const VoipLinkException& e) { JAMI_ERR("%s", e.what()); return false; } return true; } bool Manager::hangupConference(const std::string& accountId, const std::string& confId) { if (auto account = getAccount(accountId)) { if (auto conference = account->getConference(confId)) { return pimpl_->hangupConference(*conference); } else { JAMI_ERROR("No such conference {}", confId); } } return false; } // THREAD=Main bool Manager::onHoldCall(const std::string&, const std::string& callId) { bool result = true; stopTone(); std::string current_callId(getCurrentCallId()); if (auto call = getCallFromCallID(callId)) { try { result = call->onhold([=](bool ok) { if (!ok) { JAMI_ERR("hold failed for call %s", callId.c_str()); return; } removeAudio(*call); // Unbind calls in main buffer // Remove call from the queue if it was still there pimpl_->removeWaitingCall(callId); // keeps current call id if the action is not holding this call // or a new outgoing call. This could happen in case of a conference if (current_callId == callId) pimpl_->unsetCurrentCall(); }); } catch (const VoipLinkException& e) { JAMI_ERR("%s", e.what()); result = false; } } else { JAMI_DBG("CallID %s doesn't exist in call onHold", callId.c_str()); return false; } return result; } // THREAD=Main bool Manager::offHoldCall(const std::string&, const std::string& callId) { bool result = true; stopTone(); std::shared_ptr<Call> call = getCallFromCallID(callId); if (!call) return false; try { result = call->offhold([=](bool ok) { if (!ok) { JAMI_ERR("off hold failed for call %s", callId.c_str()); return; } if (auto conf = call->getConference()) pimpl_->switchCall(conf->getConfId()); else pimpl_->switchCall(call->getCallId()); addAudio(*call); }); } catch (const VoipLinkException& e) { JAMI_ERR("%s", e.what()); return false; } return result; } // THREAD=Main bool Manager::transferCall(const std::string& accountId, const std::string& callId, const std::string& to) { auto account = getAccount(accountId); if (not account) return false; if (auto call = account->getCall(callId)) { if (call->isConferenceParticipant()) removeParticipant(*call); call->transfer(to); } else return false; // remove waiting call in case we make transfer without even answer pimpl_->removeWaitingCall(callId); return true; } void Manager::transferFailed() { emitSignal<libjami::CallSignal::TransferFailed>(); } void Manager::transferSucceeded() { emitSignal<libjami::CallSignal::TransferSucceeded>(); } // THREAD=Main : Call:Incoming bool Manager::refuseCall(const std::string& accountId, const std::string& id) { if (auto account = getAccount(accountId)) { if (auto call = account->getCall(id)) { stopTone(); call->refuse(); pimpl_->removeWaitingCall(id); removeAudio(*call); return true; } } return false; } bool Manager::holdConference(const std::string& accountId, const std::string& confId) { JAMI_INFO("Hold conference %s", confId.c_str()); if (const auto account = getAccount(accountId)) { if (auto conf = account->getConference(confId)) { conf->detachHost(); emitSignal<libjami::CallSignal::ConferenceChanged>(accountId, conf->getConfId(), conf->getStateStr()); return true; } } return false; } bool Manager::unHoldConference(const std::string& accountId, const std::string& confId) { JAMI_DBG("[conf:%s] un-holding conference", confId.c_str()); if (const auto account = getAccount(accountId)) { if (auto conf = account->getConference(confId)) { // Unhold conf only if it was in hold state otherwise... // all participants are restarted if (conf->getState() == Conference::State::HOLD) { for (const auto& item : conf->getSubCalls()) offHoldCall(accountId, item); pimpl_->switchCall(confId); conf->setState(Conference::State::ACTIVE_ATTACHED); emitSignal<libjami::CallSignal::ConferenceChanged>(accountId, conf->getConfId(), conf->getStateStr()); return true; } else if (conf->getState() == Conference::State::ACTIVE_DETACHED) { pimpl_->addMainParticipant(*conf); } } } return false; } bool Manager::addSubCall(const std::string& accountId, const std::string& callId, const std::string& account2Id, const std::string& conferenceId) { auto account = getAccount(accountId); auto account2 = getAccount(account2Id); if (account && account2) { auto call = account->getCall(callId); auto conf = account2->getConference(conferenceId); if (!call or !conf) return false; auto callConf = call->getConference(); if (callConf != conf) return addSubCall(*call, *conf); } return false; } bool Manager::addSubCall(Call& call, Conference& conference) { JAMI_DEBUG("Add participant {} to conference {}", call.getCallId(), conference.getConfId()); // store the current call id (it will change in offHoldCall or in answerCall) pimpl_->bindCallToConference(call, conference); // Don't attach current user yet if (conference.getState() == Conference::State::ACTIVE_DETACHED) { return true; } // TODO: remove this ugly hack => There should be different calls when double clicking // a conference to add main participant to it, or (in this case) adding a participant // to conference pimpl_->unsetCurrentCall(); pimpl_->addMainParticipant(conference); pimpl_->switchCall(conference.getConfId()); addAudio(call); return true; } void Manager::ManagerPimpl::addMainParticipant(Conference& conf) { conf.attachHost(); emitSignal<libjami::CallSignal::ConferenceChanged>(conf.getAccountId(), conf.getConfId(), conf.getStateStr()); switchCall(conf.getConfId()); } bool Manager::ManagerPimpl::hangupConference(Conference& conference) { JAMI_DEBUG("Hangup conference {}", conference.getConfId()); CallIdSet subcalls(conference.getSubCalls()); conference.detachHost(); if (subcalls.empty()) { if (auto account = conference.getAccount()) account->removeConference(conference.getConfId()); } for (const auto& callId : subcalls) { if (auto call = base_.getCallFromCallID(callId)) base_.hangupCall(call->getAccountId(), callId); } unsetCurrentCall(); return true; } bool Manager::addMainParticipant(const std::string& accountId, const std::string& conferenceId) { JAMI_INFO("Add main participant to conference %s", conferenceId.c_str()); if (auto account = getAccount(accountId)) { if (auto conf = account->getConference(conferenceId)) { pimpl_->addMainParticipant(*conf); JAMI_DBG("Successfully added main participant to conference %s", conferenceId.c_str()); return true; } else JAMI_WARN("Failed to add main participant to conference %s", conferenceId.c_str()); } return false; } std::shared_ptr<Call> Manager::getCallFromCallID(const std::string& callID) const { return callFactory.getCall(callID); } bool Manager::joinParticipant(const std::string& accountId, const std::string& callId1, const std::string& account2Id, const std::string& callId2, bool attached) { JAMI_INFO("JoinParticipant(%s, %s, %i)", callId1.c_str(), callId2.c_str(), attached); auto account = getAccount(accountId); auto account2 = getAccount(account2Id); if (not account or not account2) { return false; } JAMI_INFO("Creating conference for participants %s and %s. Attach host [%s]", callId1.c_str(), callId2.c_str(), attached ? "YES" : "NO"); if (callId1 == callId2) { JAMI_ERR("Unable to join participant %s to itself", callId1.c_str()); return false; } // Set corresponding conference ids for call 1 auto call1 = account->getCall(callId1); if (!call1) { JAMI_ERR("Unable to find call %s", callId1.c_str()); return false; } // Set corresponding conference details auto call2 = account2->getCall(callId2); if (!call2) { JAMI_ERR("Unable to find call %s", callId2.c_str()); return false; } auto mediaAttr = call1->getMediaAttributeList(); if (mediaAttr.empty()) mediaAttr = call2->getMediaAttributeList(); auto conf = std::make_shared<Conference>(account); conf->attachHost(); account->attach(conf); emitSignal<libjami::CallSignal::ConferenceCreated>(account->getAccountID(), "", conf->getConfId()); // Bind calls according to their state pimpl_->bindCallToConference(*call1, *conf); pimpl_->bindCallToConference(*call2, *conf); // Switch current call id to this conference if (attached) { pimpl_->switchCall(conf->getConfId()); conf->setState(Conference::State::ACTIVE_ATTACHED); } else { conf->detachHost(); } emitSignal<libjami::CallSignal::ConferenceChanged>(account->getAccountID(), conf->getConfId(), conf->getStateStr()); return true; } void Manager::createConfFromParticipantList(const std::string& accountId, const std::vector<std::string>& participantList) { auto account = getAccount(accountId); if (not account) { JAMI_WARN("Unable to find account"); return; } // we must at least have 2 participant for a conference if (participantList.size() <= 1) { JAMI_ERR("Participant number must be higher or equal to 2"); return; } auto conf = std::make_shared<Conference>(account); conf->attachHost(); unsigned successCounter = 0; for (const auto& numberaccount : participantList) { std::string tostr(numberaccount.substr(0, numberaccount.find(','))); std::string account(numberaccount.substr(numberaccount.find(',') + 1, numberaccount.size())); pimpl_->unsetCurrentCall(); // Create call auto callId = outgoingCall(account, tostr, {}); if (callId.empty()) continue; // Manager methods may behave differently if the call id participates in a conference conf->addSubCall(callId); successCounter++; } // Create the conference if and only if at least 2 calls have been successfully created if (successCounter >= 2) { account->attach(conf); emitSignal<libjami::CallSignal::ConferenceCreated>(accountId, "", conf->getConfId()); } } bool Manager::detachHost(const std::shared_ptr<Conference>& conf) { if (not conf) return false; JAMI_LOG("Detach local participant from conference {}", conf->getConfId()); conf->detachHost(); emitSignal<libjami::CallSignal::ConferenceChanged>(conf->getAccountId(), conf->getConfId(), conf->getStateStr()); pimpl_->unsetCurrentCall(); return true; } bool Manager::detachParticipant(const std::string& callId) { JAMI_DBG("Detach participant %s", callId.c_str()); auto call = getCallFromCallID(callId); if (!call) { JAMI_ERR("Unable to find call %s", callId.c_str()); return false; } // Don't hold ringing calls when detaching them from conferences if (call->getStateStr() != "RINGING") onHoldCall(call->getAccountId(), callId); removeParticipant(*call); return true; } void Manager::removeParticipant(Call& call) { JAMI_DBG("Remove participant %s", call.getCallId().c_str()); auto conf = call.getConference(); if (not conf) { JAMI_ERR("No conference, unable to remove participant"); return; } conf->removeSubCall(call.getCallId()); removeAudio(call); emitSignal<libjami::CallSignal::ConferenceChanged>(conf->getAccountId(), conf->getConfId(), conf->getStateStr()); pimpl_->processRemainingParticipants(*conf); } bool Manager::joinConference(const std::string& accountId, const std::string& confId1, const std::string& account2Id, const std::string& confId2) { auto account = getAccount(accountId); auto account2 = getAccount(account2Id); if (not account) { JAMI_ERR("Unable to find account: %s", accountId.c_str()); return false; } if (not account2) { JAMI_ERR("Unable to find account: %s", account2Id.c_str()); return false; } auto conf = account->getConference(confId1); if (not conf) { JAMI_ERR("Not a valid conference ID: %s", confId1.c_str()); return false; } auto conf2 = account2->getConference(confId2); if (not conf2) { JAMI_ERR("Not a valid conference ID: %s", confId2.c_str()); return false; } CallIdSet subcalls(conf->getSubCalls()); std::vector<std::shared_ptr<Call>> calls; calls.reserve(subcalls.size()); // Detach and remove all participant from conf1 before add // ... to conf2 for (const auto& callId : subcalls) { JAMI_DEBUG("Detach participant {}", callId); if (auto call = account->getCall(callId)) { conf->removeSubCall(callId); removeAudio(*call); calls.emplace_back(std::move(call)); } else { JAMI_ERROR("Unable to find call {}", callId); } } // Remove conf1 account->removeConference(confId1); for (const auto& c : calls) addSubCall(*c, *conf2); return true; } void Manager::addAudio(Call& call) { if (call.isConferenceParticipant()) return; const auto& callId = call.getCallId(); JAMI_LOG("Add audio to call {}", callId); // bind to main auto medias = call.getAudioStreams(); for (const auto& media : medias) { JAMI_DEBUG("[call:{}] Attach audio", media.first); getRingBufferPool().bindRingbuffers(media.first, RingBufferPool::DEFAULT_ID); } auto oldGuard = std::move(call.audioGuard); call.audioGuard = startAudioStream(AudioDeviceType::PLAYBACK); std::lock_guard lock(pimpl_->audioLayerMutex_); if (!pimpl_->audiodriver_) { JAMI_ERROR("Audio driver not initialized"); return; } pimpl_->audiodriver_->flushUrgent(); getRingBufferPool().flushAllBuffers(); } void Manager::removeAudio(Call& call) { const auto& callId = call.getCallId(); auto medias = call.getAudioStreams(); for (const auto& media : medias) { JAMI_DEBUG("[call:{}] Remove local audio {}", callId, media.first); getRingBufferPool().unBindAll(media.first); } } ScheduledExecutor& Manager::scheduler() { return pimpl_->scheduler_; } std::shared_ptr<asio::io_context> Manager::ioContext() const { return pimpl_->ioContext_; } std::shared_ptr<dhtnet::upnp::UPnPContext> Manager::upnpContext() const { return pimpl_->upnpContext_; } std::shared_ptr<Task> Manager::scheduleTask(std::function<void()>&& task, std::chrono::steady_clock::time_point when, const char* filename, uint32_t linum) { return pimpl_->scheduler_.schedule(std::move(task), when, filename, linum); } std::shared_ptr<Task> Manager::scheduleTaskIn(std::function<void()>&& task, std::chrono::steady_clock::duration timeout, const char* filename, uint32_t linum) { return pimpl_->scheduler_.scheduleIn(std::move(task), timeout, filename, linum); } void Manager::saveConfig(const std::shared_ptr<Account>& acc) { if (auto ringAcc = std::dynamic_pointer_cast<JamiAccount>(acc)) ringAcc->saveConfig(); else saveConfig(); } void Manager::saveConfig() { JAMI_DBG("Saving Configuration to XDG directory %s", pimpl_->path_.c_str()); if (pimpl_->audiodriver_) { audioPreference.setVolumemic(pimpl_->audiodriver_->getCaptureGain()); audioPreference.setVolumespkr(pimpl_->audiodriver_->getPlaybackGain()); audioPreference.setCaptureMuted(pimpl_->audiodriver_->isCaptureMuted()); audioPreference.setPlaybackMuted(pimpl_->audiodriver_->isPlaybackMuted()); } try { YAML::Emitter out; // FIXME maybe move this into accountFactory? out << YAML::BeginMap << YAML::Key << "accounts"; out << YAML::Value << YAML::BeginSeq; for (const auto& account : accountFactory.getAllAccounts()) { if (auto jamiAccount = std::dynamic_pointer_cast<JamiAccount>(account)) { auto accountConfig = jamiAccount->getPath() / "config.yml"; if (not std::filesystem::is_regular_file(accountConfig)) { saveConfig(jamiAccount); } } else { account->config().serialize(out); } } out << YAML::EndSeq; // FIXME: this is a hack until we get rid of accountOrder preferences.verifyAccountOrder(getAccountList()); preferences.serialize(out); voipPreferences.serialize(out); audioPreference.serialize(out); #ifdef ENABLE_VIDEO videoPreferences.serialize(out); #endif #ifdef ENABLE_PLUGIN pluginPreferences.serialize(out); #endif std::lock_guard lock(dhtnet::fileutils::getFileLock(pimpl_->path_)); std::ofstream fout(pimpl_->path_); fout.write(out.c_str(), out.size()); } catch (const YAML::Exception& e) { JAMI_ERR("%s", e.what()); } catch (const std::runtime_error& e) { JAMI_ERR("%s", e.what()); } } // THREAD=Main | VoIPLink void Manager::playDtmf(char code) { stopTone(); if (not voipPreferences.getPlayDtmf()) { JAMI_DBG("Do not have to play a tone..."); return; } // length in milliseconds int pulselen = voipPreferences.getPulseLength(); if (pulselen == 0) { JAMI_DBG("Pulse length is not set..."); return; } std::lock_guard lock(pimpl_->audioLayerMutex_); // fast return, no sound, so no dtmf if (not pimpl_->audiodriver_ or not pimpl_->dtmfKey_) { JAMI_DBG("No audio layer..."); return; } std::shared_ptr<AudioDeviceGuard> audioGuard = startAudioStream(AudioDeviceType::PLAYBACK); if (not pimpl_->audiodriver_->waitForStart(std::chrono::seconds(1))) { JAMI_ERR("Failed to start audio layer..."); return; } // number of data sampling in one pulselen depends on samplerate // size (n sampling) = time_ms * sampling/s // --------------------- // ms/s unsigned size = (unsigned) ((pulselen * (long) pimpl_->audiodriver_->getSampleRate()) / 1000ul); if (!pimpl_->dtmfBuf_ or pimpl_->dtmfBuf_->getFrameSize() != size) pimpl_->dtmfBuf_ = std::make_shared<AudioFrame>(pimpl_->audiodriver_->getFormat(), size); // Handle dtmf pimpl_->dtmfKey_->startTone(code); // copy the sound if (pimpl_->dtmfKey_->generateDTMF(pimpl_->dtmfBuf_->pointer())) { // Put buffer to urgentRingBuffer // put the size in bytes... // so size * 1 channel (mono) * sizeof (bytes for the data) // audiolayer->flushUrgent(); pimpl_->audiodriver_->putUrgent(pimpl_->dtmfBuf_); } scheduler().scheduleIn([audioGuard] { JAMI_WARN("End of dtmf"); }, std::chrono::milliseconds(pulselen)); // TODO Cache the DTMF } // Multi-thread bool Manager::incomingCallsWaiting() { std::lock_guard m(pimpl_->waitingCallsMutex_); return not pimpl_->waitingCalls_.empty(); } void Manager::incomingCall(const std::string& accountId, Call& call) { if (not accountId.empty()) { pimpl_->stripSipPrefix(call); } std::string from("<" + call.getPeerNumber() + ">"); auto const& account = getAccount(accountId); if (not account) { JAMI_ERR("Incoming call %s on unknown account %s", call.getCallId().c_str(), accountId.c_str()); return; } // Process the call. pimpl_->processIncomingCall(accountId, call); } void Manager::incomingMessage(const std::string& accountId, const std::string& callId, const std::string& from, const std::map<std::string, std::string>& messages) { auto account = getAccount(accountId); if (not account) { return; } if (auto call = account->getCall(callId)) { if (call->isConferenceParticipant()) { if (auto conf = call->getConference()) { JAMI_DBG("Is a conference, send incoming message to everyone"); // filter out vcards messages as they could be resent by master as its own vcard // TODO. Implement a protocol to handle vcard messages bool sendToOtherParicipants = true; for (auto& message : messages) { if (message.first.find("x-ring/ring.profile.vcard") != std::string::npos) { sendToOtherParicipants = false; } } if (sendToOtherParicipants) { pimpl_->sendTextMessageToConference(*conf, messages, from); } // in case of a conference we must notify client using conference id emitSignal<libjami::CallSignal::IncomingMessage>(accountId, conf->getConfId(), from, messages); } else { JAMI_ERR("no conference associated to ID %s", callId.c_str()); } } else { emitSignal<libjami::CallSignal::IncomingMessage>(accountId, callId, from, messages); } } } void Manager::sendCallTextMessage(const std::string& accountId, const std::string& callID, const std::map<std::string, std::string>& messages, const std::string& from, bool /*isMixed TODO: use it */) { auto account = getAccount(accountId); if (not account) { return; } if (auto conf = account->getConference(callID)) { JAMI_DBG("Is a conference, send instant message to everyone"); pimpl_->sendTextMessageToConference(*conf, messages, from); } else if (auto call = account->getCall(callID)) { if (call->isConferenceParticipant()) { if (auto conf = call->getConference()) { JAMI_DBG("Call is participant in a conference, send instant message to everyone"); pimpl_->sendTextMessageToConference(*conf, messages, from); } else { JAMI_ERR("no conference associated to call ID %s", callID.c_str()); } } else { try { call->sendTextMessage(messages, from); } catch (const im::InstantMessageException& e) { JAMI_ERR("Failed to send message to call %s: %s", call->getCallId().c_str(), e.what()); } } } else { JAMI_ERR("Failed to send message to %s: inexistent call ID", callID.c_str()); } } // THREAD=VoIP CALL=Outgoing void Manager::peerAnsweredCall(Call& call) { const auto& callId = call.getCallId(); JAMI_DBG("[call:%s] Peer answered", callId.c_str()); // The if statement is useful only if we sent two calls at the same time. if (isCurrentCall(call)) stopTone(); addAudio(call); if (pimpl_->audiodriver_) { std::lock_guard lock(pimpl_->audioLayerMutex_); getRingBufferPool().flushAllBuffers(); pimpl_->audiodriver_->flushUrgent(); } if (audioPreference.getIsAlwaysRecording()) { auto result = call.toggleRecording(); emitSignal<libjami::CallSignal::RecordPlaybackFilepath>(callId, call.getPath()); emitSignal<libjami::CallSignal::RecordingStateChanged>(callId, result); } } // THREAD=VoIP Call=Outgoing void Manager::peerRingingCall(Call& call) { JAMI_DBG("[call:%s] Peer ringing", call.getCallId().c_str()); if (!hasCurrentCall()) ringback(); } // THREAD=VoIP Call=Outgoing/Ingoing void Manager::peerHungupCall(Call& call) { const auto& callId = call.getCallId(); JAMI_DBG("[call:%s] Peer hung up", callId.c_str()); if (call.isConferenceParticipant()) { removeParticipant(call); } else if (isCurrentCall(call)) { stopTone(); pimpl_->unsetCurrentCall(); } call.peerHungup(); pimpl_->removeWaitingCall(callId); if (not incomingCallsWaiting()) stopTone(); removeAudio(call); } // THREAD=VoIP void Manager::callBusy(Call& call) { JAMI_DBG("[call:%s] Busy", call.getCallId().c_str()); if (isCurrentCall(call)) { pimpl_->unsetCurrentCall(); } pimpl_->removeWaitingCall(call.getCallId()); if (not incomingCallsWaiting()) stopTone(); } // THREAD=VoIP void Manager::callFailure(Call& call) { JAMI_DBG("[call:%s] %s failed", call.getCallId().c_str(), call.isSubcall() ? "Sub-call" : "Parent call"); if (isCurrentCall(call)) { pimpl_->unsetCurrentCall(); } if (call.isConferenceParticipant()) { JAMI_DBG("[call %s] Participating in a conference. Remove", call.getCallId().c_str()); // remove this participant removeParticipant(call); } pimpl_->removeWaitingCall(call.getCallId()); if (not call.isSubcall() && not incomingCallsWaiting()) stopTone(); removeAudio(call); } /** * Multi Thread */ void Manager::stopTone() { if (not voipPreferences.getPlayTones()) return; pimpl_->toneCtrl_.stop(); pimpl_->toneDeviceGuard_.reset(); } /** * Multi Thread */ void Manager::playTone() { pimpl_->playATone(Tone::ToneId::DIALTONE); } /** * Multi Thread */ void Manager::playToneWithMessage() { pimpl_->playATone(Tone::ToneId::CONGESTION); } /** * Multi Thread */ void Manager::congestion() { pimpl_->playATone(Tone::ToneId::CONGESTION); } /** * Multi Thread */ void Manager::ringback() { pimpl_->playATone(Tone::ToneId::RINGTONE); } /** * Multi Thread */ void Manager::playRingtone(const std::string& accountID) { const auto account = getAccount(accountID); if (!account) { JAMI_WARN("Invalid account in ringtone"); return; } if (!account->getRingtoneEnabled()) { ringback(); return; } { std::lock_guard lock(pimpl_->audioLayerMutex_); if (not pimpl_->audiodriver_) { JAMI_ERR("no audio layer in ringtone"); return; } // start audio if not started AND flush all buffers (main and urgent) auto oldGuard = std::move(pimpl_->toneDeviceGuard_); pimpl_->toneDeviceGuard_ = startAudioStream(AudioDeviceType::RINGTONE); auto format = pimpl_->audiodriver_->getFormat(); pimpl_->toneCtrl_.setSampleRate(format.sample_rate, format.sampleFormat); } if (not pimpl_->toneCtrl_.setAudioFile(account->getRingtonePath().string())) ringback(); } std::shared_ptr<AudioLoop> Manager::getTelephoneTone() { return pimpl_->toneCtrl_.getTelephoneTone(); } std::shared_ptr<AudioLoop> Manager::getTelephoneFile() { return pimpl_->toneCtrl_.getTelephoneFile(); } /** * Set input audio plugin */ void Manager::setAudioPlugin(const std::string& audioPlugin) { { std::lock_guard lock(pimpl_->audioLayerMutex_); audioPreference.setAlsaPlugin(audioPlugin); pimpl_->audiodriver_.reset(); pimpl_->initAudioDriver(); } // Recreate audio driver with new settings saveConfig(); } /** * Set audio output device */ void Manager::setAudioDevice(int index, AudioDeviceType type) { std::lock_guard lock(pimpl_->audioLayerMutex_); if (not pimpl_->audiodriver_) { JAMI_ERR("Audio driver not initialized"); return; } if (pimpl_->getCurrentDeviceIndex(type) == index) { JAMI_WARN("Audio device already selected ; doing nothing."); return; } pimpl_->audiodriver_->updatePreference(audioPreference, index, type); // Recreate audio driver with new settings pimpl_->audiodriver_.reset(); pimpl_->initAudioDriver(); saveConfig(); } /** * Get list of supported audio output device */ std::vector<std::string> Manager::getAudioOutputDeviceList() { std::lock_guard lock(pimpl_->audioLayerMutex_); if (not pimpl_->audiodriver_) { JAMI_ERR("Audio layer not initialized"); return {}; } return pimpl_->audiodriver_->getPlaybackDeviceList(); } /** * Get list of supported audio input device */ std::vector<std::string> Manager::getAudioInputDeviceList() { std::lock_guard lock(pimpl_->audioLayerMutex_); if (not pimpl_->audiodriver_) { JAMI_ERR("Audio layer not initialized"); return {}; } return pimpl_->audiodriver_->getCaptureDeviceList(); } /** * Get string array representing integer indexes of output and input device */ std::vector<std::string> Manager::getCurrentAudioDevicesIndex() { std::lock_guard lock(pimpl_->audioLayerMutex_); if (not pimpl_->audiodriver_) { JAMI_ERR("Audio layer not initialized"); return {}; } return {std::to_string(pimpl_->audiodriver_->getIndexPlayback()), std::to_string(pimpl_->audiodriver_->getIndexCapture()), std::to_string(pimpl_->audiodriver_->getIndexRingtone())}; } void Manager::startAudio() { if (!pimpl_->audiodriver_) pimpl_->audiodriver_.reset(pimpl_->base_.audioPreference.createAudioLayer()); constexpr std::array<AudioDeviceType, 3> TYPES {AudioDeviceType::CAPTURE, AudioDeviceType::PLAYBACK, AudioDeviceType::RINGTONE}; for (const auto& type : TYPES) if (pimpl_->audioStreamUsers_[(unsigned) type]) pimpl_->audiodriver_->startStream(type); } AudioDeviceGuard::AudioDeviceGuard(Manager& manager, AudioDeviceType type) : manager_(manager) , type_(type) { auto streamId = (unsigned) type; if (streamId >= manager_.pimpl_->audioStreamUsers_.size()) throw std::invalid_argument("Invalid audio device type"); if (manager_.pimpl_->audioStreamUsers_[streamId]++ == 0) { if (auto layer = manager_.getAudioDriver()) layer->startStream(type); } } AudioDeviceGuard::~AudioDeviceGuard() { auto streamId = (unsigned) type_; if (--manager_.pimpl_->audioStreamUsers_[streamId] == 0) { if (auto layer = manager_.getAudioDriver()) layer->stopStream(type_); } } bool Manager::getIsAlwaysRecording() const { return audioPreference.getIsAlwaysRecording(); } void Manager::setIsAlwaysRecording(bool isAlwaysRec) { audioPreference.setIsAlwaysRecording(isAlwaysRec); saveConfig(); } bool Manager::toggleRecordingCall(const std::string& accountId, const std::string& id) { bool result = false; if (auto account = getAccount(accountId)) { std::shared_ptr<Recordable> rec; if (auto conf = account->getConference(id)) { JAMI_DBG("toggle recording for conference %s", id.c_str()); rec = conf; } else if (auto call = account->getCall(id)) { JAMI_DBG("toggle recording for call %s", id.c_str()); rec = call; } else { JAMI_ERR("Unable to find recordable instance %s", id.c_str()); return false; } result = rec->toggleRecording(); emitSignal<libjami::CallSignal::RecordPlaybackFilepath>(id, rec->getPath()); emitSignal<libjami::CallSignal::RecordingStateChanged>(id, result); } return result; } bool Manager::startRecordedFilePlayback(const std::string& filepath) { JAMI_DBG("Start recorded file playback %s", filepath.c_str()); { std::lock_guard lock(pimpl_->audioLayerMutex_); if (not pimpl_->audiodriver_) { JAMI_ERR("No audio layer in start recorded file playback"); return false; } auto oldGuard = std::move(pimpl_->toneDeviceGuard_); pimpl_->toneDeviceGuard_ = startAudioStream(AudioDeviceType::RINGTONE); auto format = pimpl_->audiodriver_->getFormat(); pimpl_->toneCtrl_.setSampleRate(format.sample_rate, format.sampleFormat); } return pimpl_->toneCtrl_.setAudioFile(filepath); } void Manager::recordingPlaybackSeek(const double value) { pimpl_->toneCtrl_.seek(value); } void Manager::stopRecordedFilePlayback() { JAMI_DBG("Stop recorded file playback"); pimpl_->toneCtrl_.stopAudioFile(); pimpl_->toneDeviceGuard_.reset(); } void Manager::setHistoryLimit(int days) { JAMI_DBG("Set history limit"); preferences.setHistoryLimit(days); saveConfig(); } int Manager::getHistoryLimit() const { return preferences.getHistoryLimit(); } void Manager::setRingingTimeout(int timeout) { JAMI_DBG("Set ringing timeout"); preferences.setRingingTimeout(timeout); saveConfig(); } int Manager::getRingingTimeout() const { return preferences.getRingingTimeout(); } bool Manager::setAudioManager(const std::string& api) { { std::lock_guard lock(pimpl_->audioLayerMutex_); if (not pimpl_->audiodriver_) return false; if (api == audioPreference.getAudioApi()) { JAMI_DBG("Audio manager chosen already in use. No changes made. "); return true; } } { std::lock_guard lock(pimpl_->audioLayerMutex_); audioPreference.setAudioApi(api); pimpl_->audiodriver_.reset(); pimpl_->initAudioDriver(); } saveConfig(); // ensure that we completed the transition (i.e. no fallback was used) return api == audioPreference.getAudioApi(); } std::string Manager::getAudioManager() const { return audioPreference.getAudioApi(); } int Manager::getAudioInputDeviceIndex(const std::string& name) { std::lock_guard lock(pimpl_->audioLayerMutex_); if (not pimpl_->audiodriver_) { JAMI_ERR("Audio layer not initialized"); return 0; } return pimpl_->audiodriver_->getAudioDeviceIndex(name, AudioDeviceType::CAPTURE); } int Manager::getAudioOutputDeviceIndex(const std::string& name) { std::lock_guard lock(pimpl_->audioLayerMutex_); if (not pimpl_->audiodriver_) { JAMI_ERR("Audio layer not initialized"); return 0; } return pimpl_->audiodriver_->getAudioDeviceIndex(name, AudioDeviceType::PLAYBACK); } std::string Manager::getCurrentAudioOutputPlugin() const { return audioPreference.getAlsaPlugin(); } std::string Manager::getNoiseSuppressState() const { return audioPreference.getNoiseReduce(); } void Manager::setNoiseSuppressState(const std::string& state) { audioPreference.setNoiseReduce(state); } bool Manager::isAGCEnabled() const { return audioPreference.isAGCEnabled(); } void Manager::setAGCState(bool state) { audioPreference.setAGCState(state); } /** * Initialization: Main Thread */ void Manager::ManagerPimpl::initAudioDriver() { audiodriver_.reset(base_.audioPreference.createAudioLayer()); constexpr std::array<AudioDeviceType, 3> TYPES {AudioDeviceType::CAPTURE, AudioDeviceType::PLAYBACK, AudioDeviceType::RINGTONE}; for (const auto& type : TYPES) if (audioStreamUsers_[(unsigned) type]) audiodriver_->startStream(type); } // Internal helper method void Manager::ManagerPimpl::stripSipPrefix(Call& incomCall) { // strip sip: which is not required and bring confusion with ip to ip calls // when placing new call from history. std::string peerNumber(incomCall.getPeerNumber()); const char SIP_PREFIX[] = "sip:"; size_t startIndex = peerNumber.find(SIP_PREFIX); if (startIndex != std::string::npos) incomCall.setPeerNumber(peerNumber.substr(startIndex + sizeof(SIP_PREFIX) - 1)); } // Internal helper method void Manager::ManagerPimpl::processIncomingCall(const std::string& accountId, Call& incomCall) { base_.stopTone(); auto incomCallId = incomCall.getCallId(); auto currentCall = base_.getCurrentCall(); auto w = incomCall.getAccount(); auto account = w.lock(); if (!account) { JAMI_ERR("No account detected"); return; } auto username = incomCall.toUsername(); if (username.find('/') != std::string::npos) { // Avoid to do heavy stuff in SIPVoIPLink's transaction_request_cb dht::ThreadPool::io().run([account, incomCallId, username]() { if (auto jamiAccount = std::dynamic_pointer_cast<JamiAccount>(account)) jamiAccount->handleIncomingConversationCall(incomCallId, username); }); return; } auto const& mediaList = MediaAttribute::mediaAttributesToMediaMaps( incomCall.getMediaAttributeList()); if (mediaList.empty()) JAMI_WARNING("Incoming call {} has an empty media list", incomCallId); JAMI_DEBUG("Incoming call {} on account {} with {} media", incomCallId, accountId, mediaList.size()); emitSignal<libjami::CallSignal::IncomingCallWithMedia>(accountId, incomCallId, incomCall.getPeerNumber(), mediaList); if (not base_.hasCurrentCall()) { incomCall.setState(Call::ConnectionState::RINGING); #if !(defined(TARGET_OS_IOS) && TARGET_OS_IOS) if (not account->isRendezVous()) base_.playRingtone(accountId); #endif } addWaitingCall(incomCallId); if (account->isRendezVous()) { dht::ThreadPool::io().run([this, account, incomCall = incomCall.shared_from_this()] { base_.answerCall(*incomCall); for (const auto& callId : account->getCallList()) { if (auto call = account->getCall(callId)) { if (call->getState() != Call::CallState::ACTIVE) continue; if (call != incomCall) { if (auto conf = call->getConference()) { base_.addSubCall(*incomCall, *conf); } else { base_.joinParticipant(account->getAccountID(), incomCall->getCallId(), account->getAccountID(), call->getCallId(), false); } return; } } } // First call auto conf = std::make_shared<Conference>(account); account->attach(conf); emitSignal<libjami::CallSignal::ConferenceCreated>(account->getAccountID(), "", conf->getConfId()); // Bind calls according to their state bindCallToConference(*incomCall, *conf); conf->detachHost(); emitSignal<libjami::CallSignal::ConferenceChanged>(account->getAccountID(), conf->getConfId(), conf->getStateStr()); }); } else if (autoAnswer_ || account->isAutoAnswerEnabled()) { dht::ThreadPool::io().run( [this, incomCall = incomCall.shared_from_this()] { base_.answerCall(*incomCall); }); } else if (currentCall && currentCall->getCallId() != incomCallId) { // Test if already calling this person auto peerNumber = incomCall.getPeerNumber(); auto currentPeerNumber = currentCall->getPeerNumber(); string_replace(peerNumber, "@ring.dht", ""); string_replace(currentPeerNumber, "@ring.dht", ""); if (currentCall->getAccountId() == account->getAccountID() && currentPeerNumber == peerNumber) { auto answerToCall = false; auto downgradeToAudioOnly = currentCall->isAudioOnly() != incomCall.isAudioOnly(); if (downgradeToAudioOnly) // Accept the incoming audio only answerToCall = incomCall.isAudioOnly(); else // Accept the incoming call from the higher id number answerToCall = (account->getUsername().compare(peerNumber) < 0); if (answerToCall) { runOnMainThread([accountId = currentCall->getAccountId(), currentCallID = currentCall->getCallId(), incomCall = incomCall.shared_from_this()] { auto& mgr = Manager::instance(); mgr.answerCall(*incomCall); mgr.hangupCall(accountId, currentCallID); }); } } } } AudioFormat Manager::hardwareAudioFormatChanged(AudioFormat format) { return audioFormatUsed(format); } AudioFormat Manager::audioFormatUsed(AudioFormat format) { AudioFormat currentFormat = pimpl_->ringbufferpool_->getInternalAudioFormat(); format.nb_channels = std::max(currentFormat.nb_channels, std::min(format.nb_channels, 2u)); // max 2 channels. format.sample_rate = std::max(currentFormat.sample_rate, format.sample_rate); if (currentFormat == format) return format; JAMI_DEBUG("Audio format changed: {} -> {}", currentFormat.toString(), format.toString()); pimpl_->ringbufferpool_->setInternalAudioFormat(format); pimpl_->toneCtrl_.setSampleRate(format.sample_rate, format.sampleFormat); pimpl_->dtmfKey_.reset(new DTMF(format.sample_rate, format.sampleFormat)); return format; } void Manager::setAccountsOrder(const std::string& order) { JAMI_DBG("Set accounts order : %s", order.c_str()); // Set the new config preferences.setAccountOrder(order); saveConfig(); emitSignal<libjami::ConfigurationSignal::AccountsChanged>(); } std::vector<std::string> Manager::getAccountList() const { // Concatenate all account pointers in a single map std::vector<std::string> v; v.reserve(accountCount()); for (const auto& account : getAllAccounts()) { v.emplace_back(account->getAccountID()); } return v; } std::map<std::string, std::string> Manager::getAccountDetails(const std::string& accountID) const { const auto account = getAccount(accountID); if (account) { return account->getAccountDetails(); } else { JAMI_ERR("Unable to get account details on a non-existing accountID %s", accountID.c_str()); // return an empty map since unable to throw an exception to D-Bus return {}; } } std::map<std::string, std::string> Manager::getVolatileAccountDetails(const std::string& accountID) const { const auto account = getAccount(accountID); if (account) { return account->getVolatileAccountDetails(); } else { JAMI_ERR("Unable to get volatile account details on a non-existing accountID %s", accountID.c_str()); return {}; } } void Manager::setAccountDetails(const std::string& accountID, const std::map<std::string, std::string>& details) { JAMI_DBG("Set account details for %s", accountID.c_str()); auto account = getAccount(accountID); if (not account) { JAMI_ERR("Unable to find account %s", accountID.c_str()); return; } // Ignore if nothing has changed if (details == account->getAccountDetails()) return; // Unregister before modifying any account information account->doUnregister([&](bool /* transport_free */) { account->setAccountDetails(details); if (account->isUsable()) account->doRegister(); else account->doUnregister(); // Update account details to the client side emitSignal<libjami::ConfigurationSignal::AccountDetailsChanged>(accountID, details); }); } std::mt19937_64 Manager::getSeededRandomEngine() { return dht::crypto::getDerivedRandomEngine(rand_); } std::string Manager::getNewAccountId() { std::string random_id; do { random_id = to_hex_string(std::uniform_int_distribution<uint64_t>()(rand_)); } while (getAccount(random_id)); return random_id; } std::string Manager::addAccount(const std::map<std::string, std::string>& details, const std::string& accountId) { /** @todo Deal with both the accountMap_ and the Configuration */ auto newAccountID = accountId.empty() ? getNewAccountId() : accountId; // Get the type std::string_view accountType; auto typeIt = details.find(Conf::CONFIG_ACCOUNT_TYPE); if (typeIt != details.end()) accountType = typeIt->second; else accountType = AccountFactory::DEFAULT_ACCOUNT_TYPE; JAMI_DEBUG("Adding account {:s} with type {}", newAccountID, accountType); auto newAccount = accountFactory.createAccount(accountType, newAccountID); if (!newAccount) { JAMI_ERROR("Unknown {:s} param when calling addAccount(): {:s}", Conf::CONFIG_ACCOUNT_TYPE, accountType); return ""; } newAccount->setAccountDetails(details); saveConfig(newAccount); newAccount->doRegister(); preferences.addAccount(newAccountID); saveConfig(); emitSignal<libjami::ConfigurationSignal::AccountsChanged>(); return newAccountID; } void Manager::removeAccount(const std::string& accountID, bool flush) { // Get it down and dying if (const auto& remAccount = getAccount(accountID)) { // Force stopping connection before doUnregister as it will // wait for dht threads to finish if (auto acc = std::dynamic_pointer_cast<JamiAccount>(remAccount)) { acc->hangupCalls(); acc->shutdownConnections(); } remAccount->doUnregister(); if (flush) remAccount->flush(); accountFactory.removeAccount(*remAccount); } preferences.removeAccount(accountID); saveConfig(); emitSignal<libjami::ConfigurationSignal::AccountsChanged>(); } void Manager::removeAccounts() { for (const auto& acc : getAccountList()) removeAccount(acc); } std::vector<std::string_view> Manager::loadAccountOrder() const { return split_string(preferences.getAccountOrder(), '/'); } int Manager::loadAccountMap(const YAML::Node& node) { int errorCount = 0; try { // build preferences preferences.unserialize(node); voipPreferences.unserialize(node); audioPreference.unserialize(node); #ifdef ENABLE_VIDEO videoPreferences.unserialize(node); #endif #ifdef ENABLE_PLUGIN pluginPreferences.unserialize(node); #endif } catch (const YAML::Exception& e) { JAMI_ERR("Preferences node unserialize YAML exception: %s", e.what()); ++errorCount; } catch (const std::exception& e) { JAMI_ERR("Preferences node unserialize standard exception: %s", e.what()); ++errorCount; } catch (...) { JAMI_ERR("Preferences node unserialize unknown exception"); ++errorCount; } const std::string accountOrder = preferences.getAccountOrder(); // load saved preferences for IP2IP account from configuration file const auto& accountList = node["accounts"]; for (auto& a : accountList) { pimpl_->loadAccount(a, errorCount); } auto accountBaseDir = fileutils::get_data_dir(); auto dirs = dhtnet::fileutils::readDirectory(accountBaseDir); std::condition_variable cv; std::mutex lock; size_t remaining {0}; std::unique_lock l(lock); for (const auto& dir : dirs) { if (accountFactory.hasAccount<JamiAccount>(dir)) { continue; } remaining++; dht::ThreadPool::computation().run( [this, dir, &cv, &remaining, &lock, configFile = accountBaseDir / dir / "config.yml"] { if (std::filesystem::is_regular_file(configFile)) { try { auto configNode = YAML::LoadFile(configFile.string()); if (auto a = accountFactory.createAccount(JamiAccount::ACCOUNT_TYPE, dir)) { auto config = a->buildConfig(); config->unserialize(configNode); a->setConfig(std::move(config)); } } catch (const std::exception& e) { JAMI_ERR("Unable to import account %s: %s", dir.c_str(), e.what()); } } std::lock_guard l(lock); remaining--; cv.notify_one(); }); } cv.wait(l, [&remaining] { return remaining == 0; }); #ifdef ENABLE_PLUGIN if (pluginPreferences.getPluginsEnabled()) { jami::Manager::instance().getJamiPluginManager().loadPlugins(); } #endif return errorCount; } std::vector<std::string> Manager::getCallList() const { std::vector<std::string> results; for (const auto& call : callFactory.getAllCalls()) { if (!call->isSubcall()) results.push_back(call->getCallId()); } return results; } void Manager::registerAccounts() { auto allAccounts(getAccountList()); for (auto& item : allAccounts) { const auto a = getAccount(item); if (!a) continue; a->loadConfig(); if (a->isUsable()) a->doRegister(); } } void Manager::sendRegister(const std::string& accountID, bool enable) { const auto acc = getAccount(accountID); if (!acc) return; acc->setEnabled(enable); saveConfig(acc); if (acc->isEnabled()) { acc->doRegister(); } else acc->doUnregister(); } uint64_t Manager::sendTextMessage(const std::string& accountID, const std::string& to, const std::map<std::string, std::string>& payloads, bool fromPlugin, bool onlyConnected) { if (const auto acc = getAccount(accountID)) { try { #ifdef ENABLE_PLUGIN // modifies send message auto& pluginChatManager = getJamiPluginManager().getChatServicesManager(); if (pluginChatManager.hasHandlers()) { auto cm = std::make_shared<JamiMessage>(accountID, to, false, payloads, fromPlugin); pluginChatManager.publishMessage(cm); return acc->sendTextMessage(cm->peerId, "", cm->data, 0, onlyConnected); } else #endif // ENABLE_PLUGIN return acc->sendTextMessage(to, "", payloads, 0, onlyConnected); } catch (const std::exception& e) { JAMI_ERR("Exception during text message sending: %s", e.what()); } } return 0; } int Manager::getMessageStatus(uint64_t) const { JAMI_ERROR("Deprecated method. Please use status from message"); return 0; } int Manager::getMessageStatus(const std::string&, uint64_t) const { JAMI_ERROR("Deprecated method. Please use status from message"); return 0; } void Manager::setAccountActive(const std::string& accountID, bool active, bool shutdownConnections) { const auto acc = getAccount(accountID); if (!acc || acc->isActive() == active) return; acc->setActive(active); if (acc->isEnabled()) { if (active) { acc->doRegister(); } else { acc->doUnregister(); if (shutdownConnections) { if (auto jamiAcc = std::dynamic_pointer_cast<JamiAccount>(acc)) { jamiAcc->shutdownConnections(); } } } } emitSignal<libjami::ConfigurationSignal::VolatileDetailsChanged>( accountID, acc->getVolatileAccountDetails()); } void Manager::loadAccountAndConversation(const std::string& accountId, bool loadAll, const std::string& convId) { auto account = getAccount(accountId); if (!account && !autoLoad) { /* With the LIBJAMI_FLAG_NO_AUTOLOAD flag active, accounts are not automatically created during manager initialization, nor are their configurations set or backed up. This is because account creation triggers the initialization of the certStore. There why account creation now occurs here in response to a received notification. */ auto accountBaseDir = fileutils::get_data_dir(); auto configFile = accountBaseDir / accountId / "config.yml"; try { if ((account = accountFactory.createAccount(JamiAccount::ACCOUNT_TYPE, accountId))) { account->enableAutoLoadConversations(false); auto configNode = YAML::LoadFile(configFile.string()); auto config = account->buildConfig(); config->unserialize(configNode); account->setConfig(std::move(config)); } } catch (const std::runtime_error& e) { JAMI_WARN("Account loading failed: %s", e.what()); return; } } if (!account) { JAMI_WARN("Unable to load account %s", accountId.c_str()); return; } if (auto jamiAcc = std::dynamic_pointer_cast<JamiAccount>(account)) { jamiAcc->setActive(true); jamiAcc->reloadContacts(); if (jamiAcc->isUsable()) jamiAcc->doRegister(); if (auto convModule = jamiAcc->convModule()) { convModule->reloadRequests(); if (loadAll) { convModule->loadConversations(); } else { jamiAcc->loadConversation(convId); } } } } std::shared_ptr<AudioLayer> Manager::getAudioDriver() { return pimpl_->audiodriver_; } std::shared_ptr<Call> Manager::newOutgoingCall(std::string_view toUrl, const std::string& accountId, const std::vector<libjami::MediaMap>& mediaList) { auto account = getAccount(accountId); if (not account) { JAMI_WARN("No account matches ID %s", accountId.c_str()); return {}; } if (not account->isUsable()) { JAMI_WARN("Account %s is not usable", accountId.c_str()); return {}; } return account->newOutgoingCall(toUrl, mediaList); } #ifdef ENABLE_VIDEO std::shared_ptr<video::SinkClient> Manager::createSinkClient(const std::string& id, bool mixer) { const auto& iter = pimpl_->sinkMap_.find(id); if (iter != std::end(pimpl_->sinkMap_)) { if (auto sink = iter->second.lock()) return sink; pimpl_->sinkMap_.erase(iter); // remove expired weak_ptr } auto sink = std::make_shared<video::SinkClient>(id, mixer); pimpl_->sinkMap_.emplace(id, sink); return sink; } void Manager::createSinkClients( const std::string& callId, const ConfInfo& infos, const std::vector<std::shared_ptr<video::VideoFrameActiveWriter>>& videoStreams, std::map<std::string, std::shared_ptr<video::SinkClient>>& sinksMap, const std::string& accountId) { std::lock_guard lk(pimpl_->sinksMutex_); std::set<std::string> sinkIdsList {}; // create video sinks for (const auto& participant : infos) { std::string sinkId = participant.sinkId; if (sinkId.empty()) { sinkId = callId; sinkId += string_remove_suffix(participant.uri, '@') + participant.device; } if (participant.w && participant.h && !participant.videoMuted) { auto currentSink = getSinkClient(sinkId); if (!accountId.empty() && currentSink && string_remove_suffix(participant.uri, '@') == getAccount(accountId)->getUsername() && participant.device == getAccount<JamiAccount>(accountId)->currentDeviceId()) { // This is a local sink that must already exist continue; } if (currentSink) { // If sink exists, update it currentSink->setCrop(participant.x, participant.y, participant.w, participant.h); sinkIdsList.emplace(sinkId); continue; } auto newSink = createSinkClient(sinkId); newSink->start(); newSink->setCrop(participant.x, participant.y, participant.w, participant.h); newSink->setFrameSize(participant.w, participant.h); for (auto& videoStream : videoStreams) videoStream->attach(newSink.get()); sinksMap.emplace(sinkId, newSink); sinkIdsList.emplace(sinkId); } else { sinkIdsList.erase(sinkId); } } // remove any non used video sink for (auto it = sinksMap.begin(); it != sinksMap.end();) { if (sinkIdsList.find(it->first) == sinkIdsList.end()) { for (auto& videoStream : videoStreams) videoStream->detach(it->second.get()); it->second->stop(); it = sinksMap.erase(it); } else { it++; } } } std::shared_ptr<video::SinkClient> Manager::getSinkClient(const std::string& id) { const auto& iter = pimpl_->sinkMap_.find(id); if (iter != std::end(pimpl_->sinkMap_)) if (auto sink = iter->second.lock()) return sink; return nullptr; } #endif // ENABLE_VIDEO RingBufferPool& Manager::getRingBufferPool() { return *pimpl_->ringbufferpool_; } bool Manager::hasAccount(const std::string& accountID) { return accountFactory.hasAccount(accountID); } const std::shared_ptr<dhtnet::IceTransportFactory>& Manager::getIceTransportFactory() { return pimpl_->ice_tf_; } VideoManager& Manager::getVideoManager() const { return *pimpl_->videoManager_; } std::vector<libjami::Message> Manager::getLastMessages(const std::string& accountID, const uint64_t& base_timestamp) { if (const auto acc = getAccount(accountID)) return acc->getLastMessages(base_timestamp); return {}; } SIPVoIPLink& Manager::sipVoIPLink() const { return *pimpl_->sipLink_; } #ifdef ENABLE_PLUGIN JamiPluginManager& Manager::getJamiPluginManager() const { return *pimpl_->jami_plugin_manager; } #endif std::shared_ptr<dhtnet::ChannelSocket> Manager::gitSocket(std::string_view accountId, std::string_view deviceId, std::string_view conversationId) { if (const auto acc = getAccount<JamiAccount>(accountId)) if (auto convModule = acc->convModule(true)) return convModule->gitSocket(deviceId, conversationId); return nullptr; } std::map<std::string, std::string> Manager::getNearbyPeers(const std::string& accountID) { if (const auto acc = getAccount<JamiAccount>(accountID)) return acc->getNearbyPeers(); return {}; } void Manager::updateProfile(const std::string& accountID,const std::string& displayName, const std::string& avatar,const uint64_t& flag) { if (const auto acc = getAccount<JamiAccount>(accountID)) acc->updateProfile(displayName,avatar,flag); } void Manager::setDefaultModerator(const std::string& accountID, const std::string& peerURI, bool state) { auto acc = getAccount(accountID); if (!acc) { JAMI_ERR("Fail to change default moderator, account %s not found", accountID.c_str()); return; } if (state) acc->addDefaultModerator(peerURI); else acc->removeDefaultModerator(peerURI); saveConfig(acc); } std::vector<std::string> Manager::getDefaultModerators(const std::string& accountID) { auto acc = getAccount(accountID); if (!acc) { JAMI_ERR("Fail to get default moderators, account %s not found", accountID.c_str()); return {}; } auto set = acc->getDefaultModerators(); return std::vector<std::string>(set.begin(), set.end()); } void Manager::enableLocalModerators(const std::string& accountID, bool isModEnabled) { if (auto acc = getAccount(accountID)) acc->editConfig( [&](AccountConfig& config) { config.localModeratorsEnabled = isModEnabled; }); } bool Manager::isLocalModeratorsEnabled(const std::string& accountID) { auto acc = getAccount(accountID); if (!acc) { JAMI_ERR("Fail to get local moderators, account %s not found", accountID.c_str()); return true; // Default value } return acc->isLocalModeratorsEnabled(); } void Manager::setAllModerators(const std::string& accountID, bool allModerators) { if (auto acc = getAccount(accountID)) acc->editConfig([&](AccountConfig& config) { config.allModeratorsEnabled = allModerators; }); } bool Manager::isAllModerators(const std::string& accountID) { auto acc = getAccount(accountID); if (!acc) { JAMI_ERR("Fail to get all moderators, account %s not found", accountID.c_str()); return true; // Default value } return acc->isAllModerators(); } void Manager::insertGitTransport(git_smart_subtransport* tr, std::unique_ptr<P2PSubTransport>&& sub) { std::lock_guard lk(pimpl_->gitTransportsMtx_); pimpl_->gitTransports_[tr] = std::move(sub); } void Manager::eraseGitTransport(git_smart_subtransport* tr) { std::lock_guard lk(pimpl_->gitTransportsMtx_); pimpl_->gitTransports_.erase(tr); } dhtnet::tls::CertificateStore& Manager::certStore(const std::string& accountId) const { if (const auto& account = getAccount<JamiAccount>(accountId)) { return account->certStore(); } throw std::runtime_error("No account found"); } } // namespace jami
99,246
C++
.cpp
2,846
27.748067
131
0.623151
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,715
conference_protocol.cpp
savoirfairelinux_jami-daemon/src/conference_protocol.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "conference_protocol.h" #include "string_utils.h" namespace jami { namespace ProtocolKeys { constexpr static const char* PROTOVERSION = "version"; constexpr static const char* LAYOUT = "layout"; // V0 constexpr static const char* HANDRAISED = "handRaised"; constexpr static const char* HANDSTATE = "handState"; constexpr static const char* ACTIVEPART = "activeParticipant"; constexpr static const char* MUTEPART = "muteParticipant"; constexpr static const char* MUTESTATE = "muteState"; constexpr static const char* HANGUPPART = "hangupParticipant"; // V1 constexpr static const char* DEVICES = "devices"; constexpr static const char* MEDIAS = "medias"; constexpr static const char* RAISEHAND = "raiseHand"; constexpr static const char* HANGUP = "hangup"; constexpr static const char* ACTIVE = "active"; constexpr static const char* MUTEAUDIO = "muteAudio"; // Future constexpr static const char* MUTEVIDEO = "muteVideo"; constexpr static const char* VOICEACTIVITY = "voiceActivity"; } // namespace ProtocolKeys void ConfProtocolParser::parse() { if (data_.isMember(ProtocolKeys::PROTOVERSION)) { uint32_t version = data_[ProtocolKeys::PROTOVERSION].asUInt(); if (version_) version_(version); if (version == 1) { parseV1(); } else { JAMI_WARN() << "Unsupported protocol version " << version; } } else { parseV0(); } } void ConfProtocolParser::parseV0() { if (!checkAuthorization_ || !raiseHandUri_ || !setLayout_ || !setActiveParticipant_ || !muteParticipant_ || !kickParticipant_) { JAMI_ERR() << "Missing methods for ConfProtocolParser"; return; } // Check if all lambdas set auto isPeerModerator = checkAuthorization_(peerId_); if (data_.isMember(ProtocolKeys::HANDRAISED)) { auto state = data_[ProtocolKeys::HANDSTATE].asString() == TRUE_STR; auto uri = data_[ProtocolKeys::HANDRAISED].asString(); if (peerId_ == uri) { // In this case, the user want to change their state raiseHandUri_(uri, state); } else if (!state && isPeerModerator) { // In this case a moderator can lower the hand raiseHandUri_(uri, state); } } if (!isPeerModerator) { JAMI_WARN("Received conference order from a non master (%.*s)", (int) peerId_.size(), peerId_.data()); return; } if (data_.isMember(ProtocolKeys::LAYOUT)) { setLayout_(data_[ProtocolKeys::LAYOUT].asInt()); } if (data_.isMember(ProtocolKeys::ACTIVEPART)) { setActiveParticipant_(data_[ProtocolKeys::ACTIVEPART].asString()); } if (data_.isMember(ProtocolKeys::MUTEPART) && data_.isMember(ProtocolKeys::MUTESTATE)) { muteParticipant_(data_[ProtocolKeys::MUTEPART].asString(), data_[ProtocolKeys::MUTESTATE].asString() == TRUE_STR); } if (data_.isMember(ProtocolKeys::HANGUPPART)) { kickParticipant_(data_[ProtocolKeys::HANGUPPART].asString()); } } void ConfProtocolParser::parseV1() { if (!checkAuthorization_ || !setLayout_ || !raiseHand_ || !hangupParticipant_ || !muteStreamAudio_ || !setActiveStream_) { JAMI_ERR() << "Missing methods for ConfProtocolParser"; return; } auto isPeerModerator = checkAuthorization_(peerId_); for (Json::Value::const_iterator itr = data_.begin(); itr != data_.end(); itr++) { auto key = itr.key(); if (key == ProtocolKeys::LAYOUT) { // Note: can be removed soon if (isPeerModerator) setLayout_(itr->asInt()); } else if (key == ProtocolKeys::PROTOVERSION) { continue; } else { auto accValue = *itr; if (accValue.isMember(ProtocolKeys::DEVICES)) { auto accountUri = key.asString(); for (Json::Value::const_iterator itrd = accValue[ProtocolKeys::DEVICES].begin(); itrd != accValue[ProtocolKeys::DEVICES].end(); itrd++) { auto deviceId = itrd.key().asString(); auto deviceValue = *itrd; if (deviceValue.isMember(ProtocolKeys::RAISEHAND)) { auto newState = deviceValue[ProtocolKeys::RAISEHAND].asBool(); if (peerId_ == accountUri || (!newState && isPeerModerator)) raiseHand_(deviceId, newState); } if (isPeerModerator && deviceValue.isMember(ProtocolKeys::HANGUP)) { hangupParticipant_(accountUri, deviceId); } if (deviceValue.isMember(ProtocolKeys::MEDIAS)) { for (Json::Value::const_iterator itrm = accValue[ProtocolKeys::MEDIAS] .begin(); itrm != accValue[ProtocolKeys::MEDIAS].end(); itrm++) { auto streamId = itrm.key().asString(); auto mediaVal = *itrm; if (mediaVal.isMember(ProtocolKeys::VOICEACTIVITY)) { voiceActivity_(streamId, mediaVal[ProtocolKeys::VOICEACTIVITY].asBool()); } if (isPeerModerator) { if (mediaVal.isMember(ProtocolKeys::MUTEVIDEO) && !muteStreamVideo_) { // Note: For now, it's not implemented so not set muteStreamVideo_(accountUri, deviceId, streamId, mediaVal[ProtocolKeys::MUTEVIDEO].asBool()); } if (mediaVal.isMember(ProtocolKeys::MUTEAUDIO)) { muteStreamAudio_(accountUri, deviceId, streamId, mediaVal[ProtocolKeys::MUTEAUDIO].asBool()); } if (mediaVal.isMember(ProtocolKeys::ACTIVE)) { setActiveStream_(streamId, mediaVal[ProtocolKeys::ACTIVE].asBool()); } } } } } } } } } } // namespace jami
7,607
C++
.cpp
170
31.435294
97
0.546728
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,716
string_utils.cpp
savoirfairelinux_jami-daemon/src/string_utils.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "string_utils.h" #include <fmt/core.h> #include <fmt/ranges.h> #include <sstream> #include <cctype> #include <algorithm> #include <ostream> #include <iomanip> #include <stdexcept> #include <ios> #include <charconv> #include <string_view> #ifdef _WIN32 #include <windows.h> #include <oleauto.h> #endif #include <ciso646> // fix windows compiler bug namespace jami { std::string_view userAgent() { static const std::string USER_AGENT = fmt::format("{:s} ({:s}/{:s})", PACKAGE_NAME, platform(), arch()); return USER_AGENT; } #ifdef _WIN32 std::wstring to_wstring(const std::string& str, int codePage) { int srcLength = (int) str.length(); int requiredSize = MultiByteToWideChar(codePage, 0, str.c_str(), srcLength, nullptr, 0); if (!requiredSize) { throw std::runtime_error("Unable to convert string to wstring"); } std::wstring result((size_t) requiredSize, 0); if (!MultiByteToWideChar(codePage, 0, str.c_str(), srcLength, &(*result.begin()), requiredSize)) { throw std::runtime_error("Unable to convert string to wstring"); } return result; } std::string to_string(const std::wstring& wstr, int codePage) { int srcLength = (int) wstr.length(); int requiredSize = WideCharToMultiByte(codePage, 0, wstr.c_str(), srcLength, nullptr, 0, 0, 0); if (!requiredSize) { throw std::runtime_error("Unable to convert wstring to string"); } std::string result((size_t) requiredSize, 0); if (!WideCharToMultiByte( codePage, 0, wstr.c_str(), srcLength, &(*result.begin()), requiredSize, 0, 0)) { throw std::runtime_error("Unable to convert wstring to string"); } return result; } #endif std::string to_string(double value) { char buf[64]; int len = snprintf(buf, sizeof(buf), "%-.*G", 16, value); if (len <= 0) throw std::invalid_argument {"Unable to parse double"}; return {buf, (size_t) len}; } std::string to_hex_string(uint64_t id) { return fmt::format("{:016x}", id); } uint64_t from_hex_string(const std::string& str) { uint64_t id; if (auto [p, ec] = std::from_chars(str.data(), str.data()+str.size(), id, 16); ec != std::errc()) { throw std::invalid_argument("Unable to parse id: " + str); } return id; } std::string_view trim(std::string_view s) { auto wsfront = std::find_if_not(s.cbegin(), s.cend(), [](int c) { return std::isspace(c); }); return std::string_view(&*wsfront, std::find_if_not(s.rbegin(), std::string_view::const_reverse_iterator(wsfront), [](int c) { return std::isspace(c); }) .base() - wsfront); } std::vector<unsigned> split_string_to_unsigned(std::string_view str, char delim) { std::vector<unsigned> output; for (auto first = str.data(), second = str.data(), last = first + str.size(); second != last && first != last; first = second + 1) { second = std::find(first, last, delim); if (first != second) { unsigned result; auto [p, ec] = std::from_chars(first, second, result); if (ec == std::errc()) output.emplace_back(result); } } return output; } void string_replace(std::string& str, const std::string& from, const std::string& to) { size_t start_pos = 0; while ((start_pos = str.find(from, start_pos)) != std::string::npos) { str.replace(start_pos, from.length(), to); start_pos += to.length(); // Handles case where 'to' is a substring of 'from' } } std::string_view string_remove_suffix(std::string_view str, char separator) { auto it = str.find(separator); if (it != std::string_view::npos) str = str.substr(0, it); return str; } std::string string_join(const std::set<std::string>& set, std::string_view separator) { return fmt::format("{}", fmt::join(set, separator)); } std::set<std::string> string_split_set(std::string& str, std::string_view separator) { std::set<std::string> output; for (auto first = str.data(), second = str.data(), last = first + str.size(); second != last && first != last; first = second + 1) { second = std::find_first_of(first, last, std::cbegin(separator), std::cend(separator)); if (first != second) output.emplace(first, second - first); } return output; } } // namespace jami
5,198
C++
.cpp
155
29.283871
136
0.646965
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,717
buildinfo.cpp
savoirfairelinux_jami-daemon/src/buildinfo.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "jami.h" #include "string_utils.h" #include <string> #include <ciso646> // fix windows compiler bug #ifndef JAMI_REVISION #define JAMI_REVISION "" #endif #ifndef JAMI_DIRTY_REPO #define JAMI_DIRTY_REPO "" #endif #ifndef PACKAGE_VERSION #define PACKAGE_VERSION "unknown" #endif namespace libjami { const char* version() noexcept { return JAMI_REVISION[0] and JAMI_DIRTY_REPO[0] ? PACKAGE_VERSION "-" JAMI_REVISION "-" JAMI_DIRTY_REPO : (JAMI_REVISION[0] ? PACKAGE_VERSION "-" JAMI_REVISION : PACKAGE_VERSION); } std::string_view platform() noexcept { return jami::platform(); } std::string_view arch() noexcept { return jami::arch(); } } // namespace libjami
1,485
C++
.cpp
51
26.784314
90
0.733661
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,718
account.cpp
savoirfairelinux_jami-daemon/src/account.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "media/media_codec.h" #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "account.h" #include <algorithm> #include <iterator> #include <mutex> #ifdef ENABLE_VIDEO #include "libav_utils.h" #endif #include "logger.h" #include "manager.h" #include <opendht/rng.h> #include "client/ring_signal.h" #include "account_schema.h" #include "jami/account_const.h" #include "string_utils.h" #include "fileutils.h" #include "config/yamlparser.h" #include "system_codec_container.h" #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #include <yaml-cpp/yaml.h> #pragma GCC diagnostic pop #include "compiler_intrinsics.h" #include "jami/account_const.h" #include <dhtnet/upnp/upnp_control.h> #include <dhtnet/ip_utils.h> #include <fmt/ranges.h> using namespace std::literals; namespace jami { // For portability, do not specify the absolute filename of the ringtone. // Instead, specify its base name to be looked in // JAMI_DATADIR/ringtones/, where JAMI_DATADIR is a preprocessor macro denoting // the data directory prefix that must be set at build time. const std::string Account::DEFAULT_USER_AGENT = Account::getDefaultUserAgent(); Account::Account(const std::string& accountID) : rand(Manager::instance().getSeededRandomEngine()) , accountID_(accountID) , systemCodecContainer_(getSystemCodecContainer()) { // Initialize the codec order, used when creating a new account loadDefaultCodecs(); } Account::~Account() {} void Account::hangupCalls() { for (const auto& callId : callSet_.getCallIds()) Manager::instance().hangupCall(getAccountID(), callId); } void Account::updateUpnpController() { std::lock_guard lk {upnp_mtx}; if (not config().upnpEnabled or not isUsable()) { upnpCtrl_.reset(); return; } // UPNP enabled. Create new controller if needed. if (not upnpCtrl_) { upnpCtrl_ = std::make_shared<dhtnet::upnp::Controller>(Manager::instance().upnpContext()); if (not upnpCtrl_) { throw std::runtime_error("Failed to create a UPNP Controller instance!"); } } } void Account::setRegistrationState(RegistrationState state, int detail_code, const std::string& detail_str) { if (state != registrationState_) { registrationState_ = state; // Notify the client runOnMainThread([accountId = accountID_, state = mapStateNumberToString(registrationState_), detail_code, detail_str, details = getVolatileAccountDetails()] { emitSignal<libjami::ConfigurationSignal::RegistrationStateChanged>(accountId, state, detail_code, detail_str); emitSignal<libjami::ConfigurationSignal::VolatileDetailsChanged>(accountId, details); }); } } void Account::loadDefaultCodecs() { // default codec are system codecs const auto& systemCodecList = systemCodecContainer_->getSystemCodecInfoList(); accountCodecInfoList_.clear(); accountCodecInfoList_.reserve(systemCodecList.size()); for (const auto& systemCodec : systemCodecList) { // As defined in SDP RFC, only select a codec if it can encode and decode if ((systemCodec->codecType & CODEC_ENCODER_DECODER) != CODEC_ENCODER_DECODER) continue; if (systemCodec->mediaType & MEDIA_AUDIO) { accountCodecInfoList_.emplace_back(std::make_shared<SystemAudioCodecInfo>( *std::static_pointer_cast<SystemAudioCodecInfo>(systemCodec))); } if (systemCodec->mediaType & MEDIA_VIDEO) { accountCodecInfoList_.emplace_back(std::make_shared<SystemVideoCodecInfo>( *std::static_pointer_cast<SystemVideoCodecInfo>(systemCodec))); } } } void Account::loadConfig() { setActiveCodecs(config_->activeCodecs); // Try to get the client-defined resource base directory, if any. If not set, use the default // JAMI_DATADIR that was set at build time. auto ringtoneDir = fileutils::get_resource_dir_path() / RINGDIR; ringtonePath_ = fileutils::getFullPath(ringtoneDir, config_->ringtonePath); // If the user defined a custom ringtone, the file may not exists // In this case, fallback on the default ringtone path if (not std::filesystem::is_regular_file(ringtonePath_)) { JAMI_WARNING("Ringtone {} is not a valid file", ringtonePath_); config_->ringtonePath = DEFAULT_RINGTONE_PATH; ringtonePath_ = fileutils::getFullPath(ringtoneDir, config_->ringtonePath); } updateUpnpController(); } void Account::saveConfig() const { Manager::instance().saveConfig(); } std::map<std::string, std::string> Account::getVolatileAccountDetails() const { return {{Conf::CONFIG_ACCOUNT_REGISTRATION_STATUS, mapStateNumberToString(registrationState_)}, {libjami::Account::VolatileProperties::ACTIVE, active_ ? TRUE_STR : FALSE_STR}}; } bool Account::hasActiveCodec(MediaType mediaType) const { for (auto& codecIt : accountCodecInfoList_) if ((codecIt->mediaType & mediaType) && codecIt->isActive) return true; return false; } void Account::setActiveCodecs(const std::vector<unsigned>& list) { // first clear the previously stored codecs // TODO: mutex to protect isActive setAllCodecsActive(MEDIA_ALL, false); // list contains the ordered payload of active codecs picked by the user for this account // we used the codec vector to save the order. uint16_t order = 1; for (const auto& item : list) { if (auto accCodec = searchCodecById(item, MEDIA_ALL)) { accCodec->isActive = true; accCodec->order = order; ++order; } } sortCodec(); } void Account::sortCodec() { std::sort(std::begin(accountCodecInfoList_), std::end(accountCodecInfoList_), [](const std::shared_ptr<SystemCodecInfo>& a, const std::shared_ptr<SystemCodecInfo>& b) { return a->order < b->order; }); } std::string Account::mapStateNumberToString(RegistrationState state) { #define CASE_STATE(X) \ case RegistrationState::X: \ return #X switch (state) { CASE_STATE(UNLOADED); CASE_STATE(UNREGISTERED); CASE_STATE(TRYING); CASE_STATE(REGISTERED); CASE_STATE(ERROR_GENERIC); CASE_STATE(ERROR_AUTH); CASE_STATE(ERROR_NETWORK); CASE_STATE(ERROR_HOST); CASE_STATE(ERROR_SERVICE_UNAVAILABLE); CASE_STATE(ERROR_NEED_MIGRATION); CASE_STATE(INITIALIZING); default: return libjami::Account::States::ERROR_GENERIC; } #undef CASE_STATE } std::vector<unsigned> Account::getDefaultCodecsId() { return getSystemCodecContainer()->getSystemCodecInfoIdList(MEDIA_ALL); } std::map<std::string, std::string> Account::getDefaultCodecDetails(const unsigned& codecId) { auto codec = jami::getSystemCodecContainer()->searchCodecById(codecId, jami::MEDIA_ALL); if (codec) { if (codec->mediaType & jami::MEDIA_AUDIO) { auto audioCodec = std::static_pointer_cast<jami::SystemAudioCodecInfo>(codec); return audioCodec->getCodecSpecifications(); } if (codec->mediaType & jami::MEDIA_VIDEO) { auto videoCodec = std::static_pointer_cast<jami::SystemVideoCodecInfo>(codec); return videoCodec->getCodecSpecifications(); } } return {}; } /** * Get the UPnP IP (external router) address. * If use UPnP is set to false, the address will be empty. */ dhtnet::IpAddr Account::getUPnPIpAddress() const { std::lock_guard lk(upnp_mtx); if (upnpCtrl_) return upnpCtrl_->getExternalIP(); return {}; } /** * returns whether or not UPnP is enabled and active_ * ie: if it is able to make port mappings */ bool Account::getUPnPActive() const { std::lock_guard lk(upnp_mtx); if (upnpCtrl_) return upnpCtrl_->isReady(); return false; } /* * private account codec searching functions * * */ std::shared_ptr<SystemCodecInfo> Account::searchCodecById(unsigned codecId, MediaType mediaType) { if (mediaType != MEDIA_NONE) { for (auto& codecIt : accountCodecInfoList_) { if ((codecIt->id == codecId) && (codecIt->mediaType & mediaType)) return codecIt; } } return {}; } std::shared_ptr<SystemCodecInfo> Account::searchCodecByName(const std::string& name, MediaType mediaType) { if (mediaType != MEDIA_NONE) { for (auto& codecIt : accountCodecInfoList_) { if (codecIt->name == name && (codecIt->mediaType & mediaType)) return codecIt; } } return {}; } std::shared_ptr<SystemCodecInfo> Account::searchCodecByPayload(unsigned payload, MediaType mediaType) { if (mediaType != MEDIA_NONE) { for (auto& codecIt : accountCodecInfoList_) { if ((codecIt->payloadType == payload) && (codecIt->mediaType & mediaType)) return codecIt; } } return {}; } std::vector<unsigned> Account::getActiveCodecs(MediaType mediaType) const { if (mediaType == MEDIA_NONE) return {}; std::vector<unsigned> idList; for (auto& codecIt : accountCodecInfoList_) { if ((codecIt->mediaType & mediaType) && (codecIt->isActive)) idList.push_back(codecIt->id); } return idList; } std::vector<unsigned> Account::getAccountCodecInfoIdList(MediaType mediaType) const { if (mediaType == MEDIA_NONE) return {}; std::vector<unsigned> idList; for (auto& codecIt : accountCodecInfoList_) { if (codecIt->mediaType & mediaType) idList.push_back(codecIt->id); } return idList; } void Account::setAllCodecsActive(MediaType mediaType, bool active) { if (mediaType == MEDIA_NONE) return; for (auto& codecIt : accountCodecInfoList_) { if (codecIt->mediaType & mediaType) codecIt->isActive = active; } } void Account::setCodecActive(unsigned codecId) { for (auto& codecIt : accountCodecInfoList_) { if (codecIt->avcodecId == codecId) codecIt->isActive = true; } } void Account::setCodecInactive(unsigned codecId) { for (auto& codecIt : accountCodecInfoList_) { if (codecIt->avcodecId == codecId) codecIt->isActive = false; } } std::vector<std::shared_ptr<SystemCodecInfo>> Account::getActiveAccountCodecInfoList(MediaType mediaType) const { if (mediaType == MEDIA_NONE) return {}; std::vector<std::shared_ptr<SystemCodecInfo>> accountCodecList; for (auto& codecIt : accountCodecInfoList_) { if ((codecIt->mediaType & mediaType) && (codecIt->isActive)) accountCodecList.push_back(codecIt); } return accountCodecList; } const std::string& Account::getUserAgentName() { return config_->customUserAgent.empty() ? DEFAULT_USER_AGENT : config_->customUserAgent; } std::string Account::getDefaultUserAgent() { return fmt::format("{:s} {:s} ({:s})", PACKAGE_NAME, libjami::version(), jami::platform()); } void Account::addDefaultModerator(const std::string& uri) { config_->defaultModerators.insert(uri); } void Account::removeDefaultModerator(const std::string& uri) { config_->defaultModerators.erase(uri); } bool Account::meetMinimumRequiredVersion(const std::vector<unsigned>& version, const std::vector<unsigned>& minRequiredVersion) { for (size_t i = 0; i < minRequiredVersion.size(); i++) { if (i == version.size() or version[i] < minRequiredVersion[i]) return false; if (version[i] > minRequiredVersion[i]) return true; } return true; } bool Account::setPushNotificationConfig(const std::map<std::string, std::string>& data) { std::lock_guard lock(configurationMutex_); auto platform = data.find("platform"); auto topic = data.find("topic"); auto token = data.find("token"); bool changed = false; if (platform != data.end() && config_->platform != platform->second) { config_->platform = platform->second; changed = true; } if (topic != data.end() && config_->notificationTopic != topic->second) { config_->notificationTopic = topic->second; changed = true; } if (token != data.end() && config_->deviceKey != token->second) { config_->deviceKey = token->second; changed = true; } if (changed) saveConfig(); return changed; } } // namespace jami
13,695
C++
.cpp
414
27.335749
99
0.663944
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,719
account_factory.cpp
savoirfairelinux_jami-daemon/src/account_factory.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "account_factory.h" #include "sip/sipaccount.h" #include "jamidht/jamiaccount.h" #include <stdexcept> namespace jami { const std::string_view AccountFactory::DEFAULT_ACCOUNT_TYPE = SIPAccount::ACCOUNT_TYPE; AccountFactory::AccountFactory() { generators_.emplace(SIPAccount::ACCOUNT_TYPE, [](const std::string& id) { return std::make_shared<SIPAccount>(id, true); }); generators_.emplace(JamiAccount::ACCOUNT_TYPE, [](const std::string& id) { return std::make_shared<JamiAccount>(id); }); } std::shared_ptr<Account> AccountFactory::createAccount(std::string_view accountType, const std::string& id) { if (hasAccount(id)) { JAMI_ERROR("Existing account {}", id); return nullptr; } const auto& it = generators_.find(accountType); if (it == generators_.cend()) return {}; std::shared_ptr<Account> account = it->second(id); { std::lock_guard lock(mutex_); auto m = accountMaps_.find(accountType); if (m == accountMaps_.end()) m = accountMaps_.emplace(std::string(accountType), AccountMap<Account>{}).first; m->second.emplace(id, account); } return account; } bool AccountFactory::isSupportedType(std::string_view name) const { return generators_.find(name) != generators_.cend(); } void AccountFactory::removeAccount(Account& account) { std::string_view account_type = account.getAccountType(); std::lock_guard lock(mutex_); const auto& id = account.getAccountID(); JAMI_DEBUG("Removing account {:s}", id); auto m = accountMaps_.find(account_type); if (m != accountMaps_.end()) { m->second.erase(id); JAMI_DEBUG("Remaining {:d} {:s} account(s)", m->second.size(), account_type); } } void AccountFactory::removeAccount(std::string_view id) { std::lock_guard lock(mutex_); if (auto account = getAccount(id)) { removeAccount(*account); } else JAMI_ERROR("No account with ID {:s}", id); } template<> bool AccountFactory::hasAccount(std::string_view id) const { std::lock_guard lk(mutex_); for (const auto& item : accountMaps_) { const auto& map = item.second; if (map.find(id) != map.cend()) return true; } return false; } template<> void AccountFactory::clear() { std::lock_guard lk(mutex_); accountMaps_.clear(); } template<> std::vector<std::shared_ptr<Account>> AccountFactory::getAllAccounts() const { std::lock_guard lock(mutex_); std::vector<std::shared_ptr<Account>> v; for (const auto& itemmap : accountMaps_) { const auto& map = itemmap.second; v.reserve(v.size() + map.size()); for (const auto& item : map) v.push_back(item.second); } return v; } template<> std::shared_ptr<Account> AccountFactory::getAccount(std::string_view id) const { std::lock_guard lock(mutex_); for (const auto& item : accountMaps_) { const auto& map = item.second; const auto& iter = map.find(id); if (iter != map.cend()) return iter->second; } return nullptr; } template<> bool AccountFactory::empty() const { std::lock_guard lock(mutex_); for (const auto& item : accountMaps_) { const auto& map = item.second; if (!map.empty()) return false; } return true; } template<> std::size_t AccountFactory::accountCount() const { std::lock_guard lock(mutex_); std::size_t count = 0; for (const auto& it : accountMaps_) count += it.second.size(); return count; } } // namespace jami
4,393
C++
.cpp
150
25.073333
92
0.666429
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,720
scheduled_executor.cpp
savoirfairelinux_jami-daemon/src/scheduled_executor.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "scheduled_executor.h" #include "logger.h" namespace jami { std::atomic<uint64_t> task_cookie = {0}; ScheduledExecutor::ScheduledExecutor(const std::string& name) : name_(name) , running_(std::make_shared<std::atomic<bool>>(true)) , thread_([this, is_running = running_] { // The thread needs its own reference of `running_` in case the // scheduler is destroyed within the thread because of a job while (*is_running) loop(); }) {} ScheduledExecutor::~ScheduledExecutor() { stop(); if (not thread_.joinable()) { return; } // Avoid deadlock if (std::this_thread::get_id() == thread_.get_id()) { thread_.detach(); } else { thread_.join(); } } void ScheduledExecutor::stop() { std::lock_guard lock(jobLock_); *running_ = false; jobs_.clear(); cv_.notify_all(); } void ScheduledExecutor::run(std::function<void()>&& job, const char* filename, uint32_t linum) { std::lock_guard lock(jobLock_); auto now = clock::now(); jobs_[now].emplace_back(std::move(job), filename, linum); cv_.notify_all(); } std::shared_ptr<Task> ScheduledExecutor::schedule(std::function<void()>&& job, time_point t, const char* filename, uint32_t linum) { auto ret = std::make_shared<Task>(std::move(job), filename, linum); schedule(ret, t); return ret; } std::shared_ptr<Task> ScheduledExecutor::scheduleIn(std::function<void()>&& job, duration dt, const char* filename, uint32_t linum) { return schedule(std::move(job), clock::now() + dt, filename, linum); } std::shared_ptr<RepeatedTask> ScheduledExecutor::scheduleAtFixedRate(std::function<bool()>&& job, duration dt, const char* filename, uint32_t linum) { auto ret = std::make_shared<RepeatedTask>(std::move(job), filename, linum); reschedule(ret, clock::now(), dt); return ret; } void ScheduledExecutor::reschedule(std::shared_ptr<RepeatedTask> task, time_point t, duration dt) { const char* filename = task->job().filename; uint32_t linenum = task->job().linum; schedule(std::make_shared<Task>([this, task = std::move(task), t, dt]() mutable { if (task->run(name_.c_str())) reschedule(std::move(task), t + dt, dt); }, filename, linenum), t); } void ScheduledExecutor::schedule(std::shared_ptr<Task> task, time_point t) { const char* filename = task->job().filename; uint32_t linenum = task->job().linum; std::lock_guard lock(jobLock_); jobs_[t].emplace_back([task = std::move(task), this] { task->run(name_.c_str()); }, filename, linenum); cv_.notify_all(); } void ScheduledExecutor::loop() { std::vector<Job> jobs; { std::unique_lock lock(jobLock_); while (*running_ and (jobs_.empty() or jobs_.begin()->first > clock::now())) { if (jobs_.empty()) cv_.wait(lock); else { auto nextJob = jobs_.begin()->first; cv_.wait_until(lock, nextJob); } } if (not *running_) return; jobs = std::move(jobs_.begin()->second); jobs_.erase(jobs_.begin()); } for (auto& job : jobs) { try { job.fn(); } catch (const std::exception& e) { JAMI_ERR("Exception running job: %s", e.what()); } } } } // namespace jami
4,321
C++
.cpp
133
26.323308
92
0.607143
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,721
account_config.cpp
savoirfairelinux_jami-daemon/src/account_config.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "account_config.h" #include "account_const.h" #include "account_schema.h" #include "string_utils.h" #include "fileutils.h" #include "config/account_config_utils.h" #include <fmt/compile.h> #include <fmt/ranges.h> namespace jami { constexpr const char* RINGTONE_PATH_KEY = "ringtonePath"; constexpr const char* RINGTONE_ENABLED_KEY = "ringtoneEnabled"; constexpr const char* VIDEO_ENABLED_KEY = "videoEnabled"; constexpr const char* DISPLAY_NAME_KEY = "displayName"; constexpr const char* ALIAS_KEY = "alias"; constexpr const char* TYPE_KEY = "type"; constexpr const char* AUTHENTICATION_USERNAME_KEY = "authenticationUsername"; constexpr const char* USERNAME_KEY = "username"; constexpr const char* PASSWORD_KEY = "password"; constexpr const char* HOSTNAME_KEY = "hostname"; constexpr const char* ACCOUNT_ENABLE_KEY = "enable"; constexpr const char* ACCOUNT_AUTOANSWER_KEY = "autoAnswer"; constexpr const char* ACCOUNT_READRECEIPT_KEY = "sendReadReceipt"; constexpr const char* ACCOUNT_COMPOSING_KEY = "sendComposing"; constexpr const char* ACCOUNT_ISRENDEZVOUS_KEY = "rendezVous"; constexpr const char* ACCOUNT_ACTIVE_CALL_LIMIT_KEY = "activeCallLimit"; constexpr const char* MAILBOX_KEY = "mailbox"; constexpr const char* USER_AGENT_KEY = "useragent"; constexpr const char* HAS_CUSTOM_USER_AGENT_KEY = "hasCustomUserAgent"; constexpr const char* UPNP_ENABLED_KEY = "upnpEnabled"; constexpr const char* ACTIVE_CODEC_KEY = "activeCodecs"; constexpr const char* DEFAULT_MODERATORS_KEY = "defaultModerators"; constexpr const char* LOCAL_MODERATORS_ENABLED_KEY = "localModeratorsEnabled"; constexpr const char* ALL_MODERATORS_ENABLED_KEY = "allModeratorsEnabled"; constexpr const char* PROXY_PUSH_TOKEN_KEY = "proxyPushToken"; constexpr const char* PROXY_PUSH_PLATFORM_KEY = "proxyPushPlatform"; constexpr const char* PROXY_PUSH_TOPIC_KEY = "proxyPushiOSTopic"; constexpr const char* UI_CUSTOMIZATION = "uiCustomization"; using yaml_utils::parseValueOptional; void AccountConfig::serializeDiff(YAML::Emitter& out, const AccountConfig& DEFAULT_CONFIG) const { SERIALIZE_CONFIG(ACCOUNT_ENABLE_KEY, enabled); SERIALIZE_CONFIG(TYPE_KEY, type); SERIALIZE_CONFIG(ALIAS_KEY, alias); SERIALIZE_CONFIG(HOSTNAME_KEY, hostname); SERIALIZE_CONFIG(USERNAME_KEY, username); SERIALIZE_CONFIG(MAILBOX_KEY, mailbox); out << YAML::Key << ACTIVE_CODEC_KEY << YAML::Value << fmt::format(FMT_COMPILE("{}"), fmt::join(activeCodecs, "/")); SERIALIZE_CONFIG(ACCOUNT_AUTOANSWER_KEY, autoAnswerEnabled); SERIALIZE_CONFIG(ACCOUNT_READRECEIPT_KEY, sendReadReceipt); SERIALIZE_CONFIG(ACCOUNT_COMPOSING_KEY, sendComposing); SERIALIZE_CONFIG(ACCOUNT_ISRENDEZVOUS_KEY, isRendezVous); SERIALIZE_CONFIG(ACCOUNT_ACTIVE_CALL_LIMIT_KEY, activeCallLimit); SERIALIZE_CONFIG(RINGTONE_ENABLED_KEY, ringtoneEnabled); SERIALIZE_CONFIG(RINGTONE_PATH_KEY, ringtonePath); SERIALIZE_CONFIG(USER_AGENT_KEY, customUserAgent); SERIALIZE_CONFIG(DISPLAY_NAME_KEY, displayName); SERIALIZE_CONFIG(UPNP_ENABLED_KEY, upnpEnabled); out << YAML::Key << DEFAULT_MODERATORS_KEY << YAML::Value << fmt::format(FMT_COMPILE("{}"), fmt::join(defaultModerators, "/")); SERIALIZE_CONFIG(LOCAL_MODERATORS_ENABLED_KEY, localModeratorsEnabled); SERIALIZE_CONFIG(ALL_MODERATORS_ENABLED_KEY, allModeratorsEnabled); SERIALIZE_CONFIG(PROXY_PUSH_TOKEN_KEY, deviceKey); SERIALIZE_CONFIG(PROXY_PUSH_PLATFORM_KEY, platform); SERIALIZE_CONFIG(PROXY_PUSH_TOPIC_KEY, notificationTopic); SERIALIZE_CONFIG(VIDEO_ENABLED_KEY, videoEnabled); SERIALIZE_CONFIG(UI_CUSTOMIZATION, uiCustomization); } void AccountConfig::unserialize(const YAML::Node& node) { parseValueOptional(node, ALIAS_KEY, alias); // parseValueOptional(node, TYPE_KEY, type); parseValueOptional(node, ACCOUNT_ENABLE_KEY, enabled); parseValueOptional(node, HOSTNAME_KEY, hostname); parseValueOptional(node, ACCOUNT_AUTOANSWER_KEY, autoAnswerEnabled); parseValueOptional(node, ACCOUNT_READRECEIPT_KEY, sendReadReceipt); parseValueOptional(node, ACCOUNT_COMPOSING_KEY, sendComposing); parseValueOptional(node, ACCOUNT_ISRENDEZVOUS_KEY, isRendezVous); parseValueOptional(node, ACCOUNT_ACTIVE_CALL_LIMIT_KEY, activeCallLimit); parseValueOptional(node, MAILBOX_KEY, mailbox); std::string codecs; if (parseValueOptional(node, ACTIVE_CODEC_KEY, codecs)) activeCodecs = split_string_to_unsigned(codecs, '/'); parseValueOptional(node, DISPLAY_NAME_KEY, displayName); parseValueOptional(node, USER_AGENT_KEY, customUserAgent); parseValueOptional(node, RINGTONE_PATH_KEY, ringtonePath); parseValueOptional(node, RINGTONE_ENABLED_KEY, ringtoneEnabled); parseValueOptional(node, VIDEO_ENABLED_KEY, videoEnabled); parseValueOptional(node, UPNP_ENABLED_KEY, upnpEnabled); std::string defMod; parseValueOptional(node, DEFAULT_MODERATORS_KEY, defMod); defaultModerators = string_split_set(defMod); parseValueOptional(node, LOCAL_MODERATORS_ENABLED_KEY, localModeratorsEnabled); parseValueOptional(node, ALL_MODERATORS_ENABLED_KEY, allModeratorsEnabled); parseValueOptional(node, PROXY_PUSH_TOKEN_KEY, deviceKey); parseValueOptional(node, PROXY_PUSH_PLATFORM_KEY, platform); parseValueOptional(node, PROXY_PUSH_TOPIC_KEY, notificationTopic); parseValueOptional(node, UI_CUSTOMIZATION, uiCustomization); } std::map<std::string, std::string> AccountConfig::toMap() const { return {{Conf::CONFIG_ACCOUNT_ALIAS, alias}, {Conf::CONFIG_ACCOUNT_DISPLAYNAME, displayName}, {Conf::CONFIG_ACCOUNT_ENABLE, enabled ? TRUE_STR : FALSE_STR}, {Conf::CONFIG_ACCOUNT_TYPE, type}, {Conf::CONFIG_ACCOUNT_USERNAME, username}, {Conf::CONFIG_ACCOUNT_HOSTNAME, hostname}, {Conf::CONFIG_ACCOUNT_MAILBOX, mailbox}, {Conf::CONFIG_ACCOUNT_USERAGENT, customUserAgent}, {Conf::CONFIG_ACCOUNT_AUTOANSWER, autoAnswerEnabled ? TRUE_STR : FALSE_STR}, {Conf::CONFIG_ACCOUNT_SENDREADRECEIPT, sendReadReceipt ? TRUE_STR : FALSE_STR}, {Conf::CONFIG_ACCOUNT_SENDCOMPOSING, sendComposing ? TRUE_STR : FALSE_STR}, {Conf::CONFIG_ACCOUNT_ISRENDEZVOUS, isRendezVous ? TRUE_STR : FALSE_STR}, {libjami::Account::ConfProperties::ACTIVE_CALL_LIMIT, std::to_string(activeCallLimit)}, {Conf::CONFIG_RINGTONE_ENABLED, ringtoneEnabled ? TRUE_STR : FALSE_STR}, {Conf::CONFIG_RINGTONE_PATH, ringtonePath}, {Conf::CONFIG_VIDEO_ENABLED, videoEnabled ? TRUE_STR : FALSE_STR}, {Conf::CONFIG_UPNP_ENABLED, upnpEnabled ? TRUE_STR : FALSE_STR}, {Conf::CONFIG_DEFAULT_MODERATORS, string_join(defaultModerators)}, {Conf::CONFIG_LOCAL_MODERATORS_ENABLED, localModeratorsEnabled ? TRUE_STR : FALSE_STR}, {Conf::CONFIG_ALL_MODERATORS_ENABLED, allModeratorsEnabled ? TRUE_STR : FALSE_STR}, {Conf::CONFIG_ACCOUNT_UICUSTOMIZATION, uiCustomization}}; } void AccountConfig::fromMap(const std::map<std::string, std::string>& details) { parseString(details, Conf::CONFIG_ACCOUNT_ALIAS, alias); parseString(details, Conf::CONFIG_ACCOUNT_DISPLAYNAME, displayName); parseBool(details, Conf::CONFIG_ACCOUNT_ENABLE, enabled); parseBool(details, Conf::CONFIG_VIDEO_ENABLED, videoEnabled); parseString(details, Conf::CONFIG_ACCOUNT_HOSTNAME, hostname); parseString(details, Conf::CONFIG_ACCOUNT_MAILBOX, mailbox); parseBool(details, Conf::CONFIG_ACCOUNT_AUTOANSWER, autoAnswerEnabled); parseBool(details, Conf::CONFIG_ACCOUNT_SENDREADRECEIPT, sendReadReceipt); parseBool(details, Conf::CONFIG_ACCOUNT_SENDCOMPOSING, sendComposing); parseBool(details, Conf::CONFIG_ACCOUNT_ISRENDEZVOUS, isRendezVous); parseInt(details, libjami::Account::ConfProperties::ACTIVE_CALL_LIMIT, activeCallLimit); parseBool(details, Conf::CONFIG_RINGTONE_ENABLED, ringtoneEnabled); parseString(details, Conf::CONFIG_RINGTONE_PATH, ringtonePath); parseString(details, Conf::CONFIG_ACCOUNT_USERAGENT, customUserAgent); parseBool(details, Conf::CONFIG_UPNP_ENABLED, upnpEnabled); std::string defMod; parseString(details, Conf::CONFIG_DEFAULT_MODERATORS, defMod); defaultModerators = string_split_set(defMod); parseBool(details, Conf::CONFIG_LOCAL_MODERATORS_ENABLED, localModeratorsEnabled); parseBool(details, Conf::CONFIG_ALL_MODERATORS_ENABLED, allModeratorsEnabled); parseString(details, libjami::Account::ConfProperties::PROXY_PUSH_TOKEN, deviceKey); parseString(details, PROXY_PUSH_PLATFORM_KEY, platform); parseString(details, PROXY_PUSH_TOPIC_KEY, notificationTopic); parseString(details, Conf::CONFIG_ACCOUNT_UICUSTOMIZATION, uiCustomization); } void parsePath(const std::map<std::string, std::string>& details, const char* key, std::string& s, const std::filesystem::path& base) { auto it = details.find(key); if (it != details.end()) s = fileutils::getFullPath(base, it->second).string(); } } // namespace jami
9,838
C++
.cpp
181
49.762431
99
0.750934
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,722
uri.cpp
savoirfairelinux_jami-daemon/src/uri.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "uri.h" #include <fmt/format.h> #include <fmt/compile.h> namespace jami { Uri::Uri(std::string_view uri) { // TODO better handling of Uri, for now it's only used for // setMessageDisplayed to differentiate swarm:xxx scheme_ = Uri::Scheme::JAMI; auto posSep = uri.find(':'); if (posSep != std::string::npos) { auto scheme_str = uri.substr(0, posSep); if (scheme_str == "sip") scheme_ = Uri::Scheme::SIP; else if (scheme_str == "swarm") scheme_ = Uri::Scheme::SWARM; else if (scheme_str == "jami") scheme_ = Uri::Scheme::JAMI; else if (scheme_str == "data-transfer") scheme_ = Uri::Scheme::DATA_TRANSFER; else if (scheme_str == "git") scheme_ = Uri::Scheme::GIT; else if (scheme_str == "rdv") scheme_ = Uri::Scheme::RENDEZVOUS; else if (scheme_str == "sync") scheme_ = Uri::Scheme::SYNC; else if (scheme_str == "msg") scheme_ = Uri::Scheme::MESSAGE; else scheme_ = Uri::Scheme::UNRECOGNIZED; authority_ = uri.substr(posSep + 1); } else { authority_ = uri; } auto posParams = authority_.find(';'); if (posParams != std::string::npos) { authority_ = authority_.substr(0, posParams); } } const std::string& Uri::authority() const { return authority_; } Uri::Scheme Uri::scheme() const { return scheme_; } std::string Uri::toString() const { return fmt::format(FMT_COMPILE("{}:{}"), schemeToString(), authority_); } constexpr std::string_view Uri::schemeToString() const { switch (scheme_) { case Uri::Scheme::SIP: return "sip"sv; case Uri::Scheme::SWARM: return "swarm"sv; case Uri::Scheme::RENDEZVOUS: return "rdv"sv; case Uri::Scheme::GIT: return "git"sv; case Uri::Scheme::SYNC: return "sync"sv; case Uri::Scheme::MESSAGE: return "msg"sv; case Uri::Scheme::JAMI: case Uri::Scheme::UNRECOGNIZED: default: return "jami"sv; } } } // namespace jami
2,841
C++
.cpp
93
25.387097
75
0.626277
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,724
sip_utils.cpp
savoirfairelinux_jami-daemon/src/connectivity/sip_utils.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "connectivity/sip_utils.h" #include "logger.h" #include "connectivity/utf8_utils.h" #include <pjsip.h> #include <pjsip_ua.h> #include <pjlib-util.h> #include <pjnath.h> #include <pjnath/stun_config.h> #include <pj/string.h> #include <pjsip/sip_types.h> #include <pjsip/sip_uri.h> #include <pj/list.h> #ifndef _WIN32 #include <netdb.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #endif #include <vector> #include <algorithm> using namespace std::literals; namespace jami { namespace sip_utils { constexpr pj_str_t USER_AGENT_STR = CONST_PJ_STR("User-Agent"); std::string PjsipErrorCategory::message(int condition) const { std::string err_msg; err_msg.reserve(PJ_ERR_MSG_SIZE); err_msg.resize(pj_strerror(condition, &err_msg[0], err_msg.capacity()).slen); return err_msg; } std::string fetchHeaderValue(pjsip_msg* msg, const std::string& field) { pj_str_t name = pj_str((char*) field.c_str()); pjsip_generic_string_hdr* hdr = static_cast<pjsip_generic_string_hdr*>( pjsip_msg_find_hdr_by_name(msg, &name, NULL)); if (!hdr) return ""; std::string value(hdr->hvalue.ptr, hdr->hvalue.slen); size_t pos = value.find('\n'); if (pos != std::string::npos) return value.substr(0, pos); else return ""; } pjsip_route_hdr* createRouteSet(const std::string& route, pj_pool_t* hdr_pool) { pjsip_route_hdr* route_set = pjsip_route_hdr_create(hdr_pool); std::string host; int port = 0; size_t found = route.find(':'); if (found != std::string::npos) { host = route.substr(0, found); port = atoi(route.substr(found + 1, route.length() - found).c_str()); } else host = route; pjsip_route_hdr* routing = pjsip_route_hdr_create(hdr_pool); pjsip_sip_uri* url = pjsip_sip_uri_create(hdr_pool, 0); url->lr_param = 1; routing->name_addr.uri = (pjsip_uri*) url; pj_strdup2(hdr_pool, &url->host, host.c_str()); url->port = port; JAMI_DBG("Adding route %s", host.c_str()); pj_list_push_back(route_set, pjsip_hdr_clone(hdr_pool, routing)); return route_set; } std::string parseDisplayName(const pjsip_name_addr* sip_name_addr) { if (not sip_name_addr->display.ptr or not sip_name_addr->display.slen) return {}; auto displayName = as_view(sip_name_addr->display); // Filter out invalid UTF-8 characters to avoid getting kicked from D-Bus if (not utf8_validate(displayName)) return utf8_make_valid(displayName); return std::string(displayName); } std::string parseDisplayName(const pjsip_from_hdr* header) { // PJSIP return a pjsip_name_addr for To, From and Contact headers return parseDisplayName(reinterpret_cast<pjsip_name_addr*>(header->uri)); } std::string parseDisplayName(const pjsip_contact_hdr* header) { // PJSIP return a pjsip_name_addr for To, From and Contact headers return parseDisplayName(reinterpret_cast<pjsip_name_addr*>(header->uri)); } std::string_view stripSipUriPrefix(std::string_view sipUri) { // Remove sip: prefix static constexpr auto SIP_PREFIX = "sip:"sv; size_t found = sipUri.find(SIP_PREFIX); if (found != std::string_view::npos) sipUri = sipUri.substr(found + SIP_PREFIX.size()); // URI may or may not be between brackets found = sipUri.find('<'); if (found != std::string_view::npos) sipUri = sipUri.substr(found + 1); found = sipUri.find('@'); if (found != std::string_view::npos) sipUri = sipUri.substr(0, found); found = sipUri.find('>'); if (found != std::string_view::npos) sipUri = sipUri.substr(0, found); return sipUri; } std::string_view getHostFromUri(std::string_view uri) { auto found = uri.find('@'); if (found != std::string_view::npos) uri = uri.substr(found + 1); found = uri.find('>'); if (found != std::string_view::npos) uri = uri.substr(0, found); return uri; } void addContactHeader(const std::string& contactHdr, pjsip_tx_data* tdata) { if (contactHdr.empty()) { JAMI_WARN("Contact header won't be added (empty string)"); return; } /* * Duplicate contact header because tdata->msg keep a reference to it and * can be used in a callback after destruction of the contact header in * Jami. Bind lifetime of the duplicated string to the pool allocator of * tdata. */ auto pjContact = pj_strdup3(tdata->pool, contactHdr.c_str()); pjsip_contact_hdr* contact = pjsip_contact_hdr_create(tdata->pool); contact->uri = pjsip_parse_uri(tdata->pool, pjContact.ptr, pjContact.slen, PJSIP_PARSE_URI_AS_NAMEADDR); // remove old contact header (if present) pjsip_msg_find_remove_hdr(tdata->msg, PJSIP_H_CONTACT, NULL); pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*) contact); } void addUserAgentHeader(const std::string& userAgent, pjsip_tx_data* tdata) { if (tdata == nullptr or userAgent.empty()) return; auto pjUserAgent = CONST_PJ_STR(userAgent); // Do nothing if user-agent header is present. if (pjsip_msg_find_hdr_by_name(tdata->msg, &USER_AGENT_STR, nullptr) != nullptr) { return; } // Add Header auto hdr = reinterpret_cast<pjsip_hdr*>( pjsip_user_agent_hdr_create(tdata->pool, &USER_AGENT_STR, &pjUserAgent)); if (hdr != nullptr) { pjsip_msg_add_hdr(tdata->msg, hdr); } } std::string_view getPeerUserAgent(const pjsip_rx_data* rdata) { if (rdata == nullptr or rdata->msg_info.msg == nullptr) { JAMI_ERR("Unexpected null pointer!"); return {}; } if (auto uaHdr = (pjsip_generic_string_hdr*) pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &USER_AGENT_STR, nullptr)) { return as_view(uaHdr->hvalue); } return {}; } std::vector<std::string> getPeerAllowMethods(const pjsip_rx_data* rdata) { if (rdata == nullptr or rdata->msg_info.msg == nullptr) { JAMI_ERR("Unexpected null pointer!"); return {}; } std::vector<std::string> methods; pjsip_allow_hdr* allow = static_cast<pjsip_allow_hdr*>( pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_ALLOW, nullptr)); if (allow != nullptr) { methods.reserve(allow->count); for (unsigned i = 0; i < allow->count; i++) { methods.emplace_back(allow->values[i].ptr, allow->values[i].slen); } } return methods; } void logMessageHeaders(const pjsip_hdr* hdr_list) { const pjsip_hdr* hdr = hdr_list->next; const pjsip_hdr* end = hdr_list; std::string msgHdrStr("Message headers:\n"); for (; hdr != end; hdr = hdr->next) { char buf[1024]; int size = pjsip_hdr_print_on((void*) hdr, buf, sizeof(buf)); if (size > 0) { msgHdrStr.append(buf, size); msgHdrStr.push_back('\n'); } } JAMI_INFO("%.*s", (int) msgHdrStr.size(), msgHdrStr.c_str()); } std::string sip_strerror(pj_status_t code) { char err_msg[PJ_ERR_MSG_SIZE]; auto ret = pj_strerror(code, err_msg, sizeof err_msg); return std::string {ret.ptr, ret.ptr + ret.slen}; } std::string streamId(const std::string& callId, std::string_view label) { if (callId.empty()) return fmt::format("host_{}", label); return fmt::format("{}_{}", callId, label); } void sockaddr_to_host_port(pj_pool_t* pool, pjsip_host_port* host_port, const pj_sockaddr* addr) { host_port->host.ptr = (char*) pj_pool_alloc(pool, PJ_INET6_ADDRSTRLEN + 4); pj_sockaddr_print(addr, host_port->host.ptr, PJ_INET6_ADDRSTRLEN + 4, 0); host_port->host.slen = pj_ansi_strlen(host_port->host.ptr); host_port->port = pj_sockaddr_get_port(addr); } } // namespace sip_utils } // namespace jami
8,743
C++
.cpp
251
29.629482
96
0.648376
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,725
ip_utils.cpp
savoirfairelinux_jami-daemon/src/connectivity/ip_utils.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "ip_utils.h" #if defined(__ANDROID__) || (defined(TARGET_OS_IOS) && TARGET_OS_IOS) #define JAMI_DEVICE_SIGNAL 1 #endif #if JAMI_DEVICE_SIGNAL #include "client/ring_signal.h" #endif #include <dhtnet/ip_utils.h> namespace jami { std::string ip_utils::getDeviceName() { #if JAMI_DEVICE_SIGNAL std::vector<std::string> deviceNames; emitSignal<libjami::ConfigurationSignal::GetDeviceName>(&deviceNames); if (not deviceNames.empty()) { return deviceNames[0]; } #endif return dhtnet::ip_utils::getHostname(); } } // namespace jami
1,285
C++
.cpp
38
31.5
74
0.73871
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,726
memory.cpp
savoirfairelinux_jami-daemon/src/connectivity/security/memory.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "memory.h" #ifdef _WIN32 #include <windows.h> #include <wincrypt.h> #endif #include <algorithm> namespace jami { namespace secure { void memzero(void* ptr, std::size_t length) { #ifdef _WIN32 SecureZeroMemory(ptr, length); #else volatile auto* p = static_cast<unsigned char*>(ptr); std::fill_n(p, length, 0); #endif } } // namespace secure } // namespace jami extern "C" void ring_secure_memzero(void* ptr, size_t length) { jami::secure::memzero(ptr, length); }
1,211
C++
.cpp
41
27.609756
73
0.737747
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
751,727
tlsvalidator.cpp
savoirfairelinux_jami-daemon/src/connectivity/security/tlsvalidator.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "tlsvalidator.h" #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <opendht/infohash.h> // for toHex #include <dhtnet/certstore.h> #include "fileutils.h" #include "logger.h" #include "security_const.h" #include <sstream> #include <iomanip> #include <cstdio> #include <cerrno> #include <cassert> #include <ctime> #include <sys/types.h> #include <sys/stat.h> #ifndef _MSC_VER #include <libgen.h> #endif #ifndef _WIN32 #include <sys/socket.h> #include <netinet/tcp.h> #include <netinet/in.h> #include <netdb.h> #else #ifndef _MSC_VER #define close(x) closesocket(x) #endif #endif #include <unistd.h> #include <fcntl.h> #ifdef _MSC_VER #include "windirent.h" #endif namespace jami { namespace tls { // Map the internal ring Enum class of the exported names const EnumClassNames<TlsValidator::CheckValues> TlsValidator::CheckValuesNames = {{ /* CheckValues Name */ /* PASSED */ libjami::Certificate::CheckValuesNames::PASSED, /* FAILED */ libjami::Certificate::CheckValuesNames::FAILED, /* UNSUPPORTED */ libjami::Certificate::CheckValuesNames::UNSUPPORTED, /* ISO_DATE */ libjami::Certificate::CheckValuesNames::ISO_DATE, /* CUSTOM */ libjami::Certificate::CheckValuesNames::CUSTOM, /* CUSTOM */ libjami::Certificate::CheckValuesNames::DATE, }}; const CallbackMatrix1D<TlsValidator::CertificateCheck, TlsValidator, TlsValidator::CheckResult> TlsValidator::checkCallback = {{ /* CertificateCheck Callback */ /*HAS_PRIVATE_KEY */ &TlsValidator::hasPrivateKey, /*EXPIRED */ &TlsValidator::notExpired, /*STRONG_SIGNING */ &TlsValidator::strongSigning, /*NOT_SELF_SIGNED */ &TlsValidator::notSelfSigned, /*KEY_MATCH */ &TlsValidator::keyMatch, /*PRIVATE_KEY_STORAGE_PERMISSION */ &TlsValidator::privateKeyStoragePermissions, /*PUBLIC_KEY_STORAGE_PERMISSION */ &TlsValidator::publicKeyStoragePermissions, /*PRIVATEKEY_DIRECTORY_PERMISSIONS */ &TlsValidator::privateKeyDirectoryPermissions, /*PUBLICKEY_DIRECTORY_PERMISSIONS */ &TlsValidator::publicKeyDirectoryPermissions, /*PRIVATE_KEY_STORAGE_LOCATION */ &TlsValidator::privateKeyStorageLocation, /*PUBLIC_KEY_STORAGE_LOCATION */ &TlsValidator::publicKeyStorageLocation, /*PRIVATE_KEY_SELINUX_ATTRIBUTES */ &TlsValidator::privateKeySelinuxAttributes, /*PUBLIC_KEY_SELINUX_ATTRIBUTES */ &TlsValidator::publicKeySelinuxAttributes, /*EXIST */ &TlsValidator::exist, /*VALID */ &TlsValidator::valid, /*VALID_AUTHORITY */ &TlsValidator::validAuthority, /*KNOWN_AUTHORITY */ &TlsValidator::knownAuthority, /*NOT_REVOKED */ &TlsValidator::notRevoked, /*AUTHORITY_MISMATCH */ &TlsValidator::authorityMatch, /*UNEXPECTED_OWNER */ &TlsValidator::expectedOwner, /*NOT_ACTIVATED */ &TlsValidator::activated, }}; const CallbackMatrix1D<TlsValidator::CertificateDetails, TlsValidator, TlsValidator::CheckResult> TlsValidator::getterCallback = {{ /* EXPIRATION_DATE */ &TlsValidator::getExpirationDate, /* ACTIVATION_DATE */ &TlsValidator::getActivationDate, /* REQUIRE_PRIVATE_KEY_PASSWORD */ &TlsValidator::requirePrivateKeyPassword, /* PUBLIC_SIGNATURE */ &TlsValidator::getPublicSignature, /* VERSION_NUMBER */ &TlsValidator::getVersionNumber, /* SERIAL_NUMBER */ &TlsValidator::getSerialNumber, /* ISSUER */ &TlsValidator::getIssuer, /* SUBJECT_KEY_ALGORITHM */ &TlsValidator::getSubjectKeyAlgorithm, /* SUBJECT_KEY */ &TlsValidator::getSubjectKey, /* CN */ &TlsValidator::getCN, /* UID */ &TlsValidator::getUID, /* N */ &TlsValidator::getN, /* O */ &TlsValidator::getO, /* SIGNATURE_ALGORITHM */ &TlsValidator::getSignatureAlgorithm, /* MD5_FINGERPRINT */ &TlsValidator::getMd5Fingerprint, /* SHA1_FINGERPRINT */ &TlsValidator::getSha1Fingerprint, /* PUBLIC_KEY_ID */ &TlsValidator::getPublicKeyId, /* ISSUER_DN */ &TlsValidator::getIssuerDN, /* ISSUER_CN */ &TlsValidator::getIssuerCN, /* ISSUER_UID */ &TlsValidator::getIssuerUID, /* ISSUER_N */ &TlsValidator::getIssuerN, /* ISSUER_O */ &TlsValidator::getIssuerO, /* NEXT_EXPECTED_UPDATE_DATE */ &TlsValidator::getIssuerDN, // TODO /* OUTGOING_SERVER */ &TlsValidator::outgoingServer, /* IS_CA */ &TlsValidator::isCA, }}; const Matrix1D<TlsValidator::CertificateCheck, TlsValidator::CheckValuesType> TlsValidator::enforcedCheckType = {{ /* CertificateCheck Callback */ /*HAS_PRIVATE_KEY */ CheckValuesType::BOOLEAN, /*EXPIRED */ CheckValuesType::BOOLEAN, /*STRONG_SIGNING */ CheckValuesType::BOOLEAN, /*NOT_SELF_SIGNED */ CheckValuesType::BOOLEAN, /*KEY_MATCH */ CheckValuesType::BOOLEAN, /*PRIVATE_KEY_STORAGE_PERMISSION */ CheckValuesType::BOOLEAN, /*PUBLIC_KEY_STORAGE_PERMISSION */ CheckValuesType::BOOLEAN, /*PRIVATEKEY_DIRECTORY_PERMISSIONS */ CheckValuesType::BOOLEAN, /*PUBLICKEY_DIRECTORY_PERMISSIONS */ CheckValuesType::BOOLEAN, /*PRIVATE_KEY_STORAGE_LOCATION */ CheckValuesType::BOOLEAN, /*PUBLIC_KEY_STORAGE_LOCATION */ CheckValuesType::BOOLEAN, /*PRIVATE_KEY_SELINUX_ATTRIBUTES */ CheckValuesType::BOOLEAN, /*PUBLIC_KEY_SELINUX_ATTRIBUTES */ CheckValuesType::BOOLEAN, /*EXIST */ CheckValuesType::BOOLEAN, /*VALID */ CheckValuesType::BOOLEAN, /*VALID_AUTHORITY */ CheckValuesType::BOOLEAN, /*KNOWN_AUTHORITY */ CheckValuesType::BOOLEAN, /*NOT_REVOKED */ CheckValuesType::BOOLEAN, /*AUTHORITY_MISMATCH */ CheckValuesType::BOOLEAN, /*UNEXPECTED_OWNER */ CheckValuesType::BOOLEAN, /*NOT_ACTIVATED */ CheckValuesType::BOOLEAN, }}; const EnumClassNames<TlsValidator::CertificateCheck> TlsValidator::CertificateCheckNames = {{ /* CertificateCheck Name */ /*HAS_PRIVATE_KEY */ libjami::Certificate::ChecksNames::HAS_PRIVATE_KEY, /*EXPIRED */ libjami::Certificate::ChecksNames::EXPIRED, /*STRONG_SIGNING */ libjami::Certificate::ChecksNames::STRONG_SIGNING, /*NOT_SELF_SIGNED */ libjami::Certificate::ChecksNames::NOT_SELF_SIGNED, /*KEY_MATCH */ libjami::Certificate::ChecksNames::KEY_MATCH, /*PRIVATE_KEY_STORAGE_PERMISSION */ libjami::Certificate::ChecksNames::PRIVATE_KEY_STORAGE_PERMISSION, /*PUBLIC_KEY_STORAGE_PERMISSION */ libjami::Certificate::ChecksNames::PUBLIC_KEY_STORAGE_PERMISSION, /*PRIVATEKEY_DIRECTORY_PERMISSIONS */ libjami::Certificate::ChecksNames::PRIVATE_KEY_DIRECTORY_PERMISSIONS, /*PUBLICKEY_DIRECTORY_PERMISSIONS */ libjami::Certificate::ChecksNames::PUBLIC_KEY_DIRECTORY_PERMISSIONS, /*PRIVATE_KEY_STORAGE_LOCATION */ libjami::Certificate::ChecksNames::PRIVATE_KEY_STORAGE_LOCATION, /*PUBLIC_KEY_STORAGE_LOCATION */ libjami::Certificate::ChecksNames::PUBLIC_KEY_STORAGE_LOCATION, /*PRIVATE_KEY_SELINUX_ATTRIBUTES */ libjami::Certificate::ChecksNames::PRIVATE_KEY_SELINUX_ATTRIBUTES, /*PUBLIC_KEY_SELINUX_ATTRIBUTES */ libjami::Certificate::ChecksNames::PUBLIC_KEY_SELINUX_ATTRIBUTES, /*EXIST */ libjami::Certificate::ChecksNames::EXIST, /*VALID */ libjami::Certificate::ChecksNames::VALID, /*VALID_AUTHORITY */ libjami::Certificate::ChecksNames::VALID_AUTHORITY, /*KNOWN_AUTHORITY */ libjami::Certificate::ChecksNames::KNOWN_AUTHORITY, /*NOT_REVOKED */ libjami::Certificate::ChecksNames::NOT_REVOKED, /*AUTHORITY_MISMATCH */ libjami::Certificate::ChecksNames::AUTHORITY_MISMATCH, /*UNEXPECTED_OWNER */ libjami::Certificate::ChecksNames::UNEXPECTED_OWNER, /*NOT_ACTIVATED */ libjami::Certificate::ChecksNames::NOT_ACTIVATED, }}; const EnumClassNames<TlsValidator::CertificateDetails> TlsValidator::CertificateDetailsNames = {{ /* EXPIRATION_DATE */ libjami::Certificate::DetailsNames::EXPIRATION_DATE, /* ACTIVATION_DATE */ libjami::Certificate::DetailsNames::ACTIVATION_DATE, /* REQUIRE_PRIVATE_KEY_PASSWORD */ libjami::Certificate::DetailsNames::REQUIRE_PRIVATE_KEY_PASSWORD, /* PUBLIC_SIGNATURE */ libjami::Certificate::DetailsNames::PUBLIC_SIGNATURE, /* VERSION_NUMBER */ libjami::Certificate::DetailsNames::VERSION_NUMBER, /* SERIAL_NUMBER */ libjami::Certificate::DetailsNames::SERIAL_NUMBER, /* ISSUER */ libjami::Certificate::DetailsNames::ISSUER, /* SUBJECT_KEY_ALGORITHM */ libjami::Certificate::DetailsNames::SUBJECT_KEY_ALGORITHM, /* SUBJECT_KEY */ libjami::Certificate::DetailsNames::SUBJECT_KEY, /* CN */ libjami::Certificate::DetailsNames::CN, /* UID */ libjami::Certificate::DetailsNames::UID, /* N */ libjami::Certificate::DetailsNames::N, /* O */ libjami::Certificate::DetailsNames::O, /* SIGNATURE_ALGORITHM */ libjami::Certificate::DetailsNames::SIGNATURE_ALGORITHM, /* MD5_FINGERPRINT */ libjami::Certificate::DetailsNames::MD5_FINGERPRINT, /* SHA1_FINGERPRINT */ libjami::Certificate::DetailsNames::SHA1_FINGERPRINT, /* PUBLIC_KEY_ID */ libjami::Certificate::DetailsNames::PUBLIC_KEY_ID, /* ISSUER_DN */ libjami::Certificate::DetailsNames::ISSUER_DN, /* ISSUER_CN */ libjami::Certificate::DetailsNames::ISSUER_CN, /* ISSUER_UID */ libjami::Certificate::DetailsNames::ISSUER_UID, /* ISSUER_N */ libjami::Certificate::DetailsNames::ISSUER_N, /* ISSUER_O */ libjami::Certificate::DetailsNames::ISSUER_O, /* NEXT_EXPECTED_UPDATE_DATE */ libjami::Certificate::DetailsNames::NEXT_EXPECTED_UPDATE_DATE, /* OUTGOING_SERVER */ libjami::Certificate::DetailsNames::OUTGOING_SERVER, /* IS_CA */ libjami::Certificate::DetailsNames::IS_CA, }}; const EnumClassNames<const TlsValidator::CheckValuesType> TlsValidator::CheckValuesTypeNames = {{ /* Type Name */ /* BOOLEAN */ libjami::Certificate::ChecksValuesTypesNames::BOOLEAN, /* ISO_DATE */ libjami::Certificate::ChecksValuesTypesNames::ISO_DATE, /* CUSTOM */ libjami::Certificate::ChecksValuesTypesNames::CUSTOM, /* NUMBER */ libjami::Certificate::ChecksValuesTypesNames::NUMBER, }}; const Matrix2D<TlsValidator::CheckValuesType, TlsValidator::CheckValues, bool> TlsValidator::acceptedCheckValuesResult = {{ /* Type PASSED FAILED UNSUPPORTED ISO_DATE CUSTOM NUMBER */ /* BOOLEAN */ {{true, true, true, false, false, false}}, /* ISO_DATE */ {{false, false, true, true, false, false}}, /* CUSTOM */ {{false, false, true, false, true, false}}, /* NUMBER */ {{false, false, true, false, false, true}}, }}; TlsValidator::TlsValidator(const dhtnet::tls::CertificateStore& certStore, const std::vector<std::vector<uint8_t>>& crtChain) : TlsValidator(certStore, std::make_shared<dht::crypto::Certificate>(crtChain.begin(), crtChain.end())) {} TlsValidator::TlsValidator(const dhtnet::tls::CertificateStore& certStore, const std::string& certificate, const std::string& privatekey, const std::string& privatekeyPasswd, const std::string& caList) : certStore_(certStore) , certificatePath_(certificate) , privateKeyPath_(privatekey) , caListPath_(caList) , certificateFound_(false) { std::vector<uint8_t> certificate_raw; try { certificate_raw = fileutils::loadFile(certificatePath_); certificateFileFound_ = true; } catch (const std::exception& e) { } if (not certificate_raw.empty()) { try { x509crt_ = std::make_shared<dht::crypto::Certificate>(certificate_raw); certificateContent_ = x509crt_->getPacked(); certificateFound_ = true; } catch (const std::exception& e) { } } try { auto privateKeyContent = fileutils::loadFile(privateKeyPath_); dht::crypto::PrivateKey key_tmp(privateKeyContent, privatekeyPasswd); privateKeyFound_ = true; privateKeyPassword_ = not privatekeyPasswd.empty(); privateKeyMatch_ = key_tmp.getPublicKey().getId() == x509crt_->getId(); } catch (const dht::crypto::DecryptError& d) { // If we encounter a DecryptError, it means the private key exists and is encrypted, // otherwise we would get some other exception. JAMI_WARN("decryption error: %s", d.what()); privateKeyFound_ = true; privateKeyPassword_ = true; } catch (const std::exception& e) { JAMI_WARN("creation failed: %s", e.what()); } } TlsValidator::TlsValidator(const dhtnet::tls::CertificateStore& certStore, const std::vector<uint8_t>& certificate_raw) : certStore_(certStore) { try { x509crt_ = std::make_shared<dht::crypto::Certificate>(certificate_raw); certificateContent_ = x509crt_->getPacked(); certificateFound_ = true; } catch (const std::exception& e) { throw TlsValidatorException("Unable to load certificate"); } } TlsValidator::TlsValidator(const dhtnet::tls::CertificateStore& certStore, const std::shared_ptr<dht::crypto::Certificate>& crt) : certStore_(certStore) , certificateFound_(true) { try { if (not crt) throw std::invalid_argument("Certificate must be set"); x509crt_ = crt; certificateContent_ = x509crt_->getPacked(); } catch (const std::exception& e) { throw TlsValidatorException("Unable to load certificate"); } } TlsValidator::~TlsValidator() {} /** * This method convert results into validated strings * * @todo The date should be validated, this is currently not an issue */ std::string TlsValidator::getStringValue(const TlsValidator::CertificateCheck check, const TlsValidator::CheckResult result) { assert(acceptedCheckValuesResult[enforcedCheckType[check]][result.first]); switch (result.first) { case CheckValues::PASSED: case CheckValues::FAILED: case CheckValues::UNSUPPORTED: return std::string(CheckValuesNames[result.first]); case CheckValues::ISO_DATE: // TODO validate date // return CheckValues::FAILED; return result.second; case CheckValues::NUMBER: // TODO Validate numbers case CheckValues::CUSTOM: return result.second; default: // Consider any other case (such as forced int->CheckValues casting) as failed return std::string(CheckValuesNames[CheckValues::FAILED]); }; } /** * Check if all boolean check passed * return true if there was no ::FAILED checks * * Checks functions are not "const", so this function isn't */ bool TlsValidator::isValid(bool verbose) { for (const CertificateCheck check : Matrix0D<CertificateCheck>()) { if (enforcedCheckType[check] == CheckValuesType::BOOLEAN) { if (((this->*(checkCallback[check]))()).first == CheckValues::FAILED) { if (verbose) JAMI_WARNING("Check failed: {}", CertificateCheckNames[check]); return false; } } } return true; } /** * Convert all checks results into a string map */ std::map<std::string, std::string> TlsValidator::getSerializedChecks() { std::map<std::string, std::string> ret; if (not certificateFound_) { // Instead of checking `certificateFound` everywhere, handle it once ret[std::string(CertificateCheckNames[CertificateCheck::EXIST])] = getStringValue(CertificateCheck::EXIST, exist()); } else { for (const CertificateCheck check : Matrix0D<CertificateCheck>()) ret[std::string(CertificateCheckNames[check])] = getStringValue(check, (this->*(checkCallback[check]))()); } return ret; } /** * Get a map with all common certificate details */ std::map<std::string, std::string> TlsValidator::getSerializedDetails() { std::map<std::string, std::string> ret; if (certificateFound_) { for (const CertificateDetails& det : Matrix0D<CertificateDetails>()) { const CheckResult r = (this->*(getterCallback[det]))(); std::string val; // TODO move this to a fuction switch (r.first) { case CheckValues::PASSED: case CheckValues::FAILED: case CheckValues::UNSUPPORTED: val = CheckValuesNames[r.first]; break; case CheckValues::ISO_DATE: // TODO validate date case CheckValues::NUMBER: // TODO Validate numbers case CheckValues::CUSTOM: default: val = r.second; break; } ret[std::string(CertificateDetailsNames[det])] = val; } } return ret; } /** * Helper method to return UNSUPPORTED when an error is detected */ static TlsValidator::CheckResult checkError(int err, char* copy_buffer, size_t size) { return TlsValidator::TlsValidator::CheckResult(err == GNUTLS_E_SUCCESS ? TlsValidator::CheckValues::CUSTOM : TlsValidator::CheckValues::UNSUPPORTED, err == GNUTLS_E_SUCCESS ? std::string(copy_buffer, size) : ""); } /** * Convert a time_t to an ISO date string */ static TlsValidator::CheckResult formatDate(const time_t time) { char buffer[12]; struct tm* timeinfo = localtime(&time); strftime(buffer, sizeof(buffer), "%F", timeinfo); return TlsValidator::CheckResult(TlsValidator::CheckValues::ISO_DATE, buffer); } /** * Helper method to return UNSUPPORTED when an error is detected * * This method also convert the output to binary */ static TlsValidator::CheckResult checkBinaryError(int err, char* copy_buffer, size_t resultSize) { if (err == GNUTLS_E_SUCCESS) return TlsValidator::CheckResult(TlsValidator::CheckValues::CUSTOM, dht::toHex(reinterpret_cast<uint8_t*>(copy_buffer), resultSize)); else return TlsValidator::CheckResult(TlsValidator::CheckValues::UNSUPPORTED, ""); } /** * Check if a certificate has been signed with the authority */ unsigned int TlsValidator::compareToCa() { // Don't check unless the certificate changed if (caChecked_) return caValidationOutput_; // build the CA trusted list gnutls_x509_trust_list_t trust; gnutls_x509_trust_list_init(&trust, 0); auto root_cas = certStore_.getTrustedCertificates(); auto err = gnutls_x509_trust_list_add_cas(trust, root_cas.data(), root_cas.size(), 0); if (err) JAMI_WARN("gnutls_x509_trust_list_add_cas failed: %s", gnutls_strerror(err)); if (not caListPath_.empty()) { if (std::filesystem::is_directory(caListPath_)) gnutls_x509_trust_list_add_trust_dir(trust, caListPath_.c_str(), nullptr, GNUTLS_X509_FMT_PEM, 0, 0); else gnutls_x509_trust_list_add_trust_file(trust, caListPath_.c_str(), nullptr, GNUTLS_X509_FMT_PEM, 0, 0); } // build the certificate chain auto crts = x509crt_->getChain(); err = gnutls_x509_trust_list_verify_crt2(trust, crts.data(), crts.size(), nullptr, 0, GNUTLS_PROFILE_TO_VFLAGS(GNUTLS_PROFILE_MEDIUM), &caValidationOutput_, nullptr); gnutls_x509_trust_list_deinit(trust, true); if (err) { JAMI_WARN("gnutls_x509_trust_list_verify_crt2 failed: %s", gnutls_strerror(err)); return GNUTLS_CERT_SIGNER_NOT_FOUND; } caChecked_ = true; return caValidationOutput_; } #if 0 // disabled, see .h for reason /** * Verify if a hostname is valid * * @warning This function is blocking * * Mainly based on Fedora Defensive Coding tutorial * https://docs.fedoraproject.org/en-US/Fedora_Security_Team/1/html/Defensive_Coding/sect-Defensive_Coding-TLS-Client-GNUTLS.html */ int TlsValidator::verifyHostnameCertificate(const std::string& host, const uint16_t port) { int err, arg, res = -1; unsigned int status = (unsigned) -1; const char *errptr = nullptr; gnutls_session_t session = nullptr; gnutls_certificate_credentials_t cred = nullptr; unsigned int certslen = 0; const gnutls_datum_t *certs = nullptr; gnutls_x509_crt_t cert = nullptr; char buf[4096]; int sockfd; struct sockaddr_in name; struct hostent *hostinfo; const int one = 1; fd_set fdset; struct timeval tv; if (!host.size() || !port) { JAMI_ERR("Wrong parameters used - host %s, port %d.", host.c_str(), port); return res; } /* Create the socket. */ sockfd = socket (PF_INET, SOCK_STREAM, 0); if (sockfd < 0) { JAMI_ERR("Unable to create socket."); return res; } /* Set non-blocking so we can dected timeouts. */ arg = fcntl(sockfd, F_GETFL, nullptr); if (arg < 0) goto out; arg |= O_NONBLOCK; if (fcntl(sockfd, F_SETFL, arg) < 0) goto out; /* Give the socket a name. */ memset(&name, 0, sizeof(name)); name.sin_family = AF_INET; name.sin_port = htons(port); hostinfo = gethostbyname(host.c_str()); if (hostinfo == nullptr) { JAMI_ERR("Unknown host %s.", host.c_str()); goto out; } name.sin_addr = *(struct in_addr *)hostinfo->h_addr; /* Connect to the address specified in name struct. */ err = connect(sockfd, (struct sockaddr *)&name, sizeof(name)); if (err < 0) { /* Connection in progress, use select to see if timeout is reached. */ if (errno == EINPROGRESS) { do { FD_ZERO(&fdset); FD_SET(sockfd, &fdset); tv.tv_sec = 10; // 10 second timeout tv.tv_usec = 0; err = select(sockfd + 1, nullptr, &fdset, nullptr, &tv); if (err < 0 && errno != EINTR) { JAMI_ERR("Unable to connect to hostname %s at port %d", host.c_str(), port); goto out; } else if (err > 0) { /* Select returned, if so_error is clean we are ready. */ int so_error; socklen_t len = sizeof(so_error); getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &so_error, &len); if (so_error) { JAMI_ERR("Connection delayed."); goto out; } break; // exit do-while loop } else { JAMI_ERR("Connection timeout."); goto out; } } while(1); } else { JAMI_ERR("Unable to connect to hostname %s at port %d", host.c_str(), port); goto out; } } /* Set the socked blocking again. */ arg = fcntl(sockfd, F_GETFL, nullptr); if (arg < 0) goto out; arg &= ~O_NONBLOCK; if (fcntl(sockfd, F_SETFL, arg) < 0) goto out; /* Disable Nagle algorithm that slows down the SSL handshake. */ err = setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one)); if (err < 0) { JAMI_ERR("Unable to set TCP_NODELAY."); goto out; } /* Load the trusted CA certificates. */ err = gnutls_certificate_allocate_credentials(&cred); if (err != GNUTLS_E_SUCCESS) { JAMI_ERR("Unable to allocate credentials - %s", gnutls_strerror(err)); goto out; } err = gnutls_certificate_set_x509_system_trust(cred); if (err != GNUTLS_E_SUCCESS) { JAMI_ERR("Unable to load credentials."); goto out; } /* Create the session object. */ err = gnutls_init(&session, GNUTLS_CLIENT); if (err != GNUTLS_E_SUCCESS) { JAMI_ERR("Unable to init session -%s\n", gnutls_strerror(err)); goto out; } /* Configure the cipher preferences. The default set should be good enough. */ err = gnutls_priority_set_direct(session, "NORMAL", &errptr); if (err != GNUTLS_E_SUCCESS) { JAMI_ERR("Unable to set up ciphers - %s (%s)", gnutls_strerror(err), errptr); goto out; } /* Install the trusted certificates. */ err = gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, cred); if (err != GNUTLS_E_SUCCESS) { JAMI_ERR("Unable to set up credentials - %s", gnutls_strerror(err)); goto out; } /* Associate the socket with the session object and set the server name. */ gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) (uintptr_t) sockfd); err = gnutls_server_name_set(session, GNUTLS_NAME_DNS, host.c_str(), host.size()); if (err != GNUTLS_E_SUCCESS) { JAMI_ERR("Unable to set server name - %s", gnutls_strerror(err)); goto out; } /* Establish the connection. */ err = gnutls_handshake(session); if (err != GNUTLS_E_SUCCESS) { JAMI_ERR("Handshake failed - %s", gnutls_strerror(err)); goto out; } /* Obtain the server certificate chain. The server certificate * itself is stored in the first element of the array. */ certs = gnutls_certificate_get_peers(session, &certslen); if (certs == nullptr || certslen == 0) { JAMI_ERR("Unable to obtain peer certificate - %s", gnutls_strerror(err)); goto out; } /* Validate the certificate chain. */ err = gnutls_certificate_verify_peers2(session, &status); if (err != GNUTLS_E_SUCCESS) { JAMI_ERR("Unable to verify the certificate chain - %s", gnutls_strerror(err)); goto out; } if (status != 0) { gnutls_datum_t msg; #if GNUTLS_VERSION_AT_LEAST_3_1_4 int type = gnutls_certificate_type_get(session); err = gnutls_certificate_verification_status_print(status, type, &out, 0); #else err = -1; #endif if (err == 0) { JAMI_ERR("Certificate validation failed - %s\n", msg.data); gnutls_free(msg.data); goto out; } else { JAMI_ERR("Certificate validation failed with code 0x%x.", status); goto out; } } /* Match the peer certificate against the hostname. * We can only obtain a set of DER-encoded certificates from the * session object, so we have to re-parse the peer certificate into * a certificate object. */ err = gnutls_x509_crt_init(&cert); if (err != GNUTLS_E_SUCCESS) { JAMI_ERR("Unable to init certificate - %s", gnutls_strerror(err)); goto out; } /* The peer certificate is the first certificate in the list. */ err = gnutls_x509_crt_import(cert, certs, GNUTLS_X509_FMT_PEM); if (err != GNUTLS_E_SUCCESS) err = gnutls_x509_crt_import(cert, certs, GNUTLS_X509_FMT_DER); if (err != GNUTLS_E_SUCCESS) { JAMI_ERR("Unable to read peer certificate - %s", gnutls_strerror(err)); goto out; } /* Finally check if the hostnames match. */ err = gnutls_x509_crt_check_hostname(cert, host.c_str()); if (err == 0) { JAMI_ERR("Hostname %s does not match certificate.", host.c_str()); goto out; } /* Try sending and receiving some data through. */ snprintf(buf, sizeof(buf), "GET / HTTP/1.0\r\nHost: %s\r\n\r\n", host.c_str()); err = gnutls_record_send(session, buf, strlen(buf)); if (err < 0) { JAMI_ERR("Send failed - %s", gnutls_strerror(err)); goto out; } err = gnutls_record_recv(session, buf, sizeof(buf)); if (err < 0) { JAMI_ERR("Recv failed - %s", gnutls_strerror(err)); goto out; } JAMI_DBG("Hostname %s seems to point to a valid server.", host.c_str()); res = 0; out: if (session) { gnutls_bye(session, GNUTLS_SHUT_RDWR); gnutls_deinit(session); } if (cert) gnutls_x509_crt_deinit(cert); if (cred) gnutls_certificate_free_credentials(cred); close(sockfd); return res; } #endif /** * Check if the Validator have access to a private key */ TlsValidator::CheckResult TlsValidator::hasPrivateKey() { if (privateKeyFound_) return TlsValidator::CheckResult(CheckValues::PASSED, ""); try { dht::crypto::PrivateKey key_tmp(certificateContent_); } catch (const std::exception& e) { return CheckResult(CheckValues::FAILED, e.what()); } JAMI_DBG("Key from %s seems valid.", certificatePath_.c_str()); return CheckResult(CheckValues::PASSED, ""); } /** * Check if the certificate is not expired * * The double negative is used because all boolean checks need to have * a consistent return value semantic * * @fixme Handle both "with ca" and "without ca" case */ TlsValidator::CheckResult TlsValidator::notExpired() { if (exist().first == CheckValues::FAILED) TlsValidator::CheckResult(CheckValues::UNSUPPORTED, ""); // time_t expirationTime = gnutls_x509_crt_get_expiration_time(cert); return TlsValidator::CheckResult(compareToCa() & GNUTLS_CERT_EXPIRED ? CheckValues::FAILED : CheckValues::PASSED, ""); } /** * If the activation value is in the past * * @fixme Handle both "with ca" and "without ca" case */ TlsValidator::CheckResult TlsValidator::activated() { if (exist().first == CheckValues::FAILED) TlsValidator::CheckResult(CheckValues::UNSUPPORTED, ""); // time_t activationTime = gnutls_x509_crt_get_activation_time(cert); return TlsValidator::CheckResult(compareToCa() & GNUTLS_CERT_NOT_ACTIVATED ? CheckValues::FAILED : CheckValues::PASSED, ""); } /** * If the algorithm used to sign the certificate is considered weak by modern * standard */ TlsValidator::CheckResult TlsValidator::strongSigning() { if (exist().first == CheckValues::FAILED) TlsValidator::CheckResult(CheckValues::UNSUPPORTED, ""); // Doesn't seem to have the same value as // certtool --infile /home/etudiant/Téléchargements/mynsauser.pem --key-inf // TODO figure out why return TlsValidator::CheckResult(compareToCa() & GNUTLS_CERT_INSECURE_ALGORITHM ? CheckValues::FAILED : CheckValues::PASSED, ""); } /** * The certificate is not self signed */ TlsValidator::CheckResult TlsValidator::notSelfSigned() { return TlsValidator::CheckResult(CheckValues::UNSUPPORTED, ""); } /** * The provided key can be used along with the certificate */ TlsValidator::CheckResult TlsValidator::keyMatch() { if (exist().first == CheckValues::FAILED) return TlsValidator::CheckResult(CheckValues::UNSUPPORTED, ""); if (not privateKeyFound_) return TlsValidator::CheckResult(CheckValues::UNSUPPORTED, ""); return TlsValidator::CheckResult(privateKeyMatch_ ? CheckValues::PASSED : CheckValues::FAILED, ""); } TlsValidator::CheckResult TlsValidator::privateKeyStoragePermissions() { struct stat statbuf; int err = stat(privateKeyPath_.c_str(), &statbuf); if (err) return TlsValidator::CheckResult(CheckValues::UNSUPPORTED, ""); // clang-format off return TlsValidator::CheckResult( (statbuf.st_mode & S_IFREG) && /* Regular file only */ /* READ WRITE EXECUTE */ /* Owner */ ( (statbuf.st_mode & S_IRUSR) /* write is not relevant */ && !(statbuf.st_mode & S_IXUSR)) /* Group */ && (!(statbuf.st_mode & S_IRGRP) && !(statbuf.st_mode & S_IWGRP) && !(statbuf.st_mode & S_IXGRP)) /* Other */ && (!(statbuf.st_mode & S_IROTH) && !(statbuf.st_mode & S_IWOTH) && !(statbuf.st_mode & S_IXOTH)) ? CheckValues::PASSED:CheckValues::FAILED, ""); // clang-format on } TlsValidator::CheckResult TlsValidator::publicKeyStoragePermissions() { struct stat statbuf; int err = stat(certificatePath_.c_str(), &statbuf); if (err) return TlsValidator::CheckResult(CheckValues::UNSUPPORTED, ""); // clang-format off return TlsValidator::CheckResult( (statbuf.st_mode & S_IFREG) && /* Regular file only */ /* READ WRITE EXECUTE */ /* Owner */ ( (statbuf.st_mode & S_IRUSR) /* write is not relevant */ && !(statbuf.st_mode & S_IXUSR)) /* Group */ && ( /* read is not relevant */ !(statbuf.st_mode & S_IWGRP) && !(statbuf.st_mode & S_IXGRP)) /* Other */ && ( /* read is not relevant */ !(statbuf.st_mode & S_IWOTH) && !(statbuf.st_mode & S_IXOTH)) ? CheckValues::PASSED:CheckValues::FAILED, ""); // clang-format on } TlsValidator::CheckResult TlsValidator::privateKeyDirectoryPermissions() { if (privateKeyPath_.empty()) return TlsValidator::CheckResult(CheckValues::UNSUPPORTED, ""); #ifndef _MSC_VER auto path = std::unique_ptr<char, decltype(free)&>(strdup(privateKeyPath_.c_str()), free); const char* dir = dirname(path.get()); #else char* dir; _splitpath(certificatePath_.c_str(), nullptr, dir, nullptr, nullptr); #endif struct stat statbuf; int err = stat(dir, &statbuf); if (err) return TlsValidator::CheckResult(CheckValues::UNSUPPORTED, ""); return TlsValidator::CheckResult( /* READ WRITE EXECUTE */ /* Owner */ ( (statbuf.st_mode & S_IRUSR) /* write is not relevant */ && (statbuf.st_mode & S_IXUSR)) /* Group */ && (!(statbuf.st_mode & S_IRGRP) && !(statbuf.st_mode & S_IWGRP) && !(statbuf.st_mode & S_IXGRP)) /* Other */ && (!(statbuf.st_mode & S_IROTH) && !(statbuf.st_mode & S_IWOTH) && !(statbuf.st_mode & S_IXOTH)) && S_ISDIR(statbuf.st_mode) ? CheckValues::PASSED : CheckValues::FAILED, ""); } TlsValidator::CheckResult TlsValidator::publicKeyDirectoryPermissions() { #ifndef _MSC_VER auto path = std::unique_ptr<char, decltype(free)&>(strdup(certificatePath_.c_str()), free); const char* dir = dirname(path.get()); #else char* dir; _splitpath(certificatePath_.c_str(), nullptr, dir, nullptr, nullptr); #endif struct stat statbuf; int err = stat(dir, &statbuf); if (err) return TlsValidator::CheckResult(CheckValues::UNSUPPORTED, ""); return TlsValidator::CheckResult( /* READ WRITE EXECUTE */ /* Owner */ ( (statbuf.st_mode & S_IRUSR) /* write is not relevant */ && (statbuf.st_mode & S_IXUSR)) /* Group */ && (!(statbuf.st_mode & S_IRGRP) && !(statbuf.st_mode & S_IWGRP) && !(statbuf.st_mode & S_IXGRP)) /* Other */ && (!(statbuf.st_mode & S_IROTH) && !(statbuf.st_mode & S_IWOTH) && !(statbuf.st_mode & S_IXOTH)) && S_ISDIR(statbuf.st_mode) ? CheckValues::PASSED : CheckValues::FAILED, ""); } /** * Certificate should be located in specific path on some operating systems */ TlsValidator::CheckResult TlsValidator::privateKeyStorageLocation() { // TODO return TlsValidator::CheckResult(CheckValues::UNSUPPORTED, ""); } /** * Certificate should be located in specific path on some operating systems */ TlsValidator::CheckResult TlsValidator::publicKeyStorageLocation() { // TODO return TlsValidator::CheckResult(CheckValues::UNSUPPORTED, ""); } /** * SELinux provide additional key protection mechanism */ TlsValidator::CheckResult TlsValidator::privateKeySelinuxAttributes() { // TODO return TlsValidator::CheckResult(CheckValues::UNSUPPORTED, ""); } /** * SELinux provide additional key protection mechanism */ TlsValidator::CheckResult TlsValidator::publicKeySelinuxAttributes() { // TODO return TlsValidator::CheckResult(CheckValues::UNSUPPORTED, ""); } /** * If the key need decryption * * Double factor authentication is recommended */ TlsValidator::CheckResult TlsValidator::requirePrivateKeyPassword() { return TlsValidator::CheckResult(privateKeyPassword_ ? CheckValues::PASSED : CheckValues::FAILED, ""); } /** * The CA and certificate provide conflicting ownership information */ TlsValidator::CheckResult TlsValidator::expectedOwner() { return TlsValidator::CheckResult(compareToCa() & GNUTLS_CERT_UNEXPECTED_OWNER ? CheckValues::FAILED : CheckValues::PASSED, ""); } /** * The file has been found */ TlsValidator::CheckResult TlsValidator::exist() { return TlsValidator::CheckResult((certificateFound_ or certificateFileFound_) ? CheckValues::PASSED : CheckValues::FAILED, ""); } /** * The certificate is invalid compared to the authority * * @todo Handle case when there is facultative authority, such as DHT */ TlsValidator::CheckResult TlsValidator::valid() { return TlsValidator::CheckResult(certificateFound_ ? CheckValues::PASSED : CheckValues::FAILED, ""); } /** * The provided authority is invalid */ TlsValidator::CheckResult TlsValidator::validAuthority() { // TODO Merge with either above or bellow return TlsValidator::CheckResult((compareToCa() & GNUTLS_CERT_SIGNER_NOT_FOUND) ? CheckValues::FAILED : CheckValues::PASSED, ""); } /** * Check if the authority match the certificate */ TlsValidator::CheckResult TlsValidator::authorityMatch() { return TlsValidator::CheckResult(compareToCa() & GNUTLS_CERT_SIGNER_NOT_CA ? CheckValues::FAILED : CheckValues::PASSED, ""); } /** * When an account require an authority known by the system (like /usr/share/ssl/certs) * then the whole chain of trust need be to checked * * @fixme port crypto_cert_load_trusted * @fixme add account settings * @todo implement the check */ TlsValidator::CheckResult TlsValidator::knownAuthority() { // TODO need a new boolean account setting "require trusted authority" or something defaulting // to true using GNUTLS_CERT_SIGNER_NOT_FOUND is a temporary placeholder as it is close enough return TlsValidator::CheckResult(compareToCa() & GNUTLS_CERT_SIGNER_NOT_FOUND ? CheckValues::FAILED : CheckValues::PASSED, ""); } /** * Check if the certificate has been revoked */ TlsValidator::CheckResult TlsValidator::notRevoked() { return TlsValidator::CheckResult((compareToCa() & GNUTLS_CERT_REVOKED) || (compareToCa() & GNUTLS_CERT_REVOCATION_DATA_ISSUED_IN_FUTURE) ? CheckValues::FAILED : CheckValues::PASSED, ""); } /** * A certificate authority has been provided */ bool TlsValidator::hasCa() const { return (x509crt_ and x509crt_->issuer); /* or (caCert_ != nullptr and caCert_->certificateFound_);*/ } // // Certificate details // // TODO gnutls_x509_crl_get_this_update /** * An hexadecimal representation of the signature */ TlsValidator::CheckResult TlsValidator::getPublicSignature() { size_t resultSize = sizeof(copy_buffer); int err = gnutls_x509_crt_get_signature(x509crt_->cert, copy_buffer, &resultSize); return checkBinaryError(err, copy_buffer, resultSize); } /** * Return the certificate version */ TlsValidator::CheckResult TlsValidator::getVersionNumber() { int version = gnutls_x509_crt_get_version(x509crt_->cert); if (version < 0) return TlsValidator::CheckResult(CheckValues::UNSUPPORTED, ""); std::ostringstream convert; convert << version; return TlsValidator::CheckResult(CheckValues::NUMBER, convert.str()); } /** * Return the certificate serial number */ TlsValidator::CheckResult TlsValidator::getSerialNumber() { // gnutls_x509_crl_iter_crt_serial // gnutls_x509_crt_get_authority_key_gn_serial size_t resultSize = sizeof(copy_buffer); int err = gnutls_x509_crt_get_serial(x509crt_->cert, copy_buffer, &resultSize); return checkBinaryError(err, copy_buffer, resultSize); } /** * If the certificate is not self signed, return the issuer */ TlsValidator::CheckResult TlsValidator::getIssuer() { if (not x509crt_->issuer) { auto icrt = certStore_.findIssuer(x509crt_); if (icrt) return TlsValidator::CheckResult(CheckValues::CUSTOM, icrt->getId().toString()); return TlsValidator::CheckResult(CheckValues::UNSUPPORTED, ""); } return TlsValidator::CheckResult(CheckValues::CUSTOM, x509crt_->issuer->getId().toString()); } /** * The algorithm used to sign the certificate details (rather than the certificate itself) */ TlsValidator::CheckResult TlsValidator::getSubjectKeyAlgorithm() { unsigned key_length = 0; gnutls_pk_algorithm_t algo = (gnutls_pk_algorithm_t) gnutls_x509_crt_get_pk_algorithm(x509crt_->cert, &key_length); if (algo < 0) return TlsValidator::CheckResult(CheckValues::UNSUPPORTED, ""); const char* name = gnutls_pk_get_name(algo); if (!name) return TlsValidator::CheckResult(CheckValues::UNSUPPORTED, ""); if (key_length) return TlsValidator::CheckResult(CheckValues::CUSTOM, fmt::format("{} ({} bits)", name, key_length)); else return TlsValidator::CheckResult(CheckValues::CUSTOM, name); } /** * The subject public key */ TlsValidator::CheckResult TlsValidator::getSubjectKey() { try { std::vector<uint8_t> data; x509crt_->getPublicKey().pack(data); return TlsValidator::CheckResult(CheckValues::CUSTOM, dht::toHex(data)); } catch (const dht::crypto::CryptoException& e) { return TlsValidator::CheckResult(CheckValues::UNSUPPORTED, e.what()); } } /** * The 'CN' section of a DN (RFC4514) */ TlsValidator::CheckResult TlsValidator::getCN() { // TODO split, cache size_t resultSize = sizeof(copy_buffer); int err = gnutls_x509_crt_get_dn_by_oid(x509crt_->cert, GNUTLS_OID_X520_COMMON_NAME, 0, 0, copy_buffer, &resultSize); return checkError(err, copy_buffer, resultSize); } /** * The 'UID' section of a DN (RFC4514) */ TlsValidator::CheckResult TlsValidator::getUID() { size_t resultSize = sizeof(copy_buffer); int err = gnutls_x509_crt_get_dn_by_oid(x509crt_->cert, GNUTLS_OID_LDAP_UID, 0, 0, copy_buffer, &resultSize); return checkError(err, copy_buffer, resultSize); } /** * The 'N' section of a DN (RFC4514) */ TlsValidator::CheckResult TlsValidator::getN() { // TODO split, cache size_t resultSize = sizeof(copy_buffer); int err = gnutls_x509_crt_get_dn_by_oid(x509crt_->cert, GNUTLS_OID_X520_NAME, 0, 0, copy_buffer, &resultSize); return checkError(err, copy_buffer, resultSize); } /** * The 'O' section of a DN (RFC4514) */ TlsValidator::CheckResult TlsValidator::getO() { // TODO split, cache size_t resultSize = sizeof(copy_buffer); int err = gnutls_x509_crt_get_dn_by_oid(x509crt_->cert, GNUTLS_OID_X520_ORGANIZATION_NAME, 0, 0, copy_buffer, &resultSize); return checkError(err, copy_buffer, resultSize); } /** * Return the algorithm used to sign the Key * * For example: RSA */ TlsValidator::CheckResult TlsValidator::getSignatureAlgorithm() { gnutls_sign_algorithm_t algo = (gnutls_sign_algorithm_t) gnutls_x509_crt_get_signature_algorithm( x509crt_->cert); if (algo < 0) return TlsValidator::CheckResult(CheckValues::UNSUPPORTED, ""); const char* algoName = gnutls_sign_get_name(algo); return TlsValidator::CheckResult(CheckValues::CUSTOM, algoName); } /** *Compute the key fingerprint * * This need to be used along with getSha1Fingerprint() to avoid collisions */ TlsValidator::CheckResult TlsValidator::getMd5Fingerprint() { size_t resultSize = sizeof(copy_buffer); int err = gnutls_x509_crt_get_fingerprint(x509crt_->cert, GNUTLS_DIG_MD5, copy_buffer, &resultSize); return checkBinaryError(err, copy_buffer, resultSize); } /** * Compute the key fingerprint * * This need to be used along with getMd5Fingerprint() to avoid collisions */ TlsValidator::CheckResult TlsValidator::getSha1Fingerprint() { size_t resultSize = sizeof(copy_buffer); int err = gnutls_x509_crt_get_fingerprint(x509crt_->cert, GNUTLS_DIG_SHA1, copy_buffer, &resultSize); return checkBinaryError(err, copy_buffer, resultSize); } /** * Return an hexadecimal identifier */ TlsValidator::CheckResult TlsValidator::getPublicKeyId() { static unsigned char unsigned_copy_buffer[4096]; size_t resultSize = sizeof(unsigned_copy_buffer); int err = gnutls_x509_crt_get_key_id(x509crt_->cert, 0, unsigned_copy_buffer, &resultSize); // TODO check for GNUTLS_E_SHORT_MEMORY_BUFFER and increase the buffer size // TODO get rid of the cast, display a HEX or something, need research return checkBinaryError(err, (char*) unsigned_copy_buffer, resultSize); } // gnutls_x509_crt_get_authority_key_id /** * If the certificate is not self signed, return the issuer DN (RFC4514) */ TlsValidator::CheckResult TlsValidator::getIssuerDN() { size_t resultSize = sizeof(copy_buffer); int err = gnutls_x509_crt_get_issuer_dn(x509crt_->cert, copy_buffer, &resultSize); return checkError(err, copy_buffer, resultSize); } /** * If the certificate is not self signed, return the issuer CN */ TlsValidator::CheckResult TlsValidator::getIssuerCN() { size_t resultSize = sizeof(copy_buffer); int err = gnutls_x509_crt_get_issuer_dn_by_oid(x509crt_->cert, GNUTLS_OID_X520_COMMON_NAME, 0, 0, copy_buffer, &resultSize); return checkError(err, copy_buffer, resultSize); } /** * If the certificate is not self signed, return the issuer UID */ TlsValidator::CheckResult TlsValidator::getIssuerUID() { size_t resultSize = sizeof(copy_buffer); int err = gnutls_x509_crt_get_issuer_dn_by_oid(x509crt_->cert, GNUTLS_OID_LDAP_UID, 0, 0, copy_buffer, &resultSize); return checkError(err, copy_buffer, resultSize); } /** * If the certificate is not self signed, return the issuer N */ TlsValidator::CheckResult TlsValidator::getIssuerN() { size_t resultSize = sizeof(copy_buffer); int err = gnutls_x509_crt_get_issuer_dn_by_oid(x509crt_->cert, GNUTLS_OID_X520_NAME, 0, 0, copy_buffer, &resultSize); return checkError(err, copy_buffer, resultSize); } /** * If the certificate is not self signed, return the issuer O */ TlsValidator::CheckResult TlsValidator::getIssuerO() { size_t resultSize = sizeof(copy_buffer); int err = gnutls_x509_crt_get_issuer_dn_by_oid(x509crt_->cert, GNUTLS_OID_X520_ORGANIZATION_NAME, 0, 0, copy_buffer, &resultSize); return checkError(err, copy_buffer, resultSize); } /** * Get the expiration date * * @todo Move to "certificateDetails()" method once completed */ TlsValidator::CheckResult TlsValidator::getExpirationDate() { if (not certificateFound_) return TlsValidator::CheckResult(CheckValues::UNSUPPORTED, ""); time_t expiration = gnutls_x509_crt_get_expiration_time(x509crt_->cert); return formatDate(expiration); } /** * Get the activation date * * @todo Move to "certificateDetails()" method once completed */ TlsValidator::CheckResult TlsValidator::getActivationDate() { if (not certificateFound_) return TlsValidator::CheckResult(CheckValues::UNSUPPORTED, ""); time_t expiration = gnutls_x509_crt_get_activation_time(x509crt_->cert); return formatDate(expiration); } /** * The expected outgoing server domain * * @todo Move to "certificateDetails()" method once completed * @todo extract information for the certificate */ TlsValidator::CheckResult TlsValidator::outgoingServer() { // TODO return TlsValidator::CheckResult(CheckValues::CUSTOM, ""); } /** * If the certificate is not self signed, return the issuer */ TlsValidator::CheckResult TlsValidator::isCA() { return TlsValidator::CheckResult(CheckValues::CUSTOM, x509crt_->isCA() ? TRUE_STR : FALSE_STR); } } // namespace tls } // namespace jami
54,958
C++
.cpp
1,337
32.693343
129
0.591765
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,728
media_decoder.cpp
savoirfairelinux_jami-daemon/src/media/media_decoder.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "libav_deps.h" // MUST BE INCLUDED FIRST #include "media_decoder.h" #include "media_device.h" #include "media_buffer.h" #include "media_const.h" #include "media_io_handle.h" #include "audio/ringbuffer.h" #include "audio/resampler.h" #include "audio/ringbufferpool.h" #include "decoder_finder.h" #include "manager.h" #ifdef RING_ACCEL #include "video/accel.h" #endif #include "string_utils.h" #include "logger.h" #include "client/ring_signal.h" #include <iostream> #include <unistd.h> #include <thread> // hardware_concurrency #include <chrono> #include <algorithm> namespace jami { // maximum number of packets the jitter buffer can queue const unsigned jitterBufferMaxSize_ {1500}; // maximum time a packet can be queued const constexpr auto jitterBufferMaxDelay_ = std::chrono::milliseconds(50); // maximum number of times accelerated decoding can fail in a row before falling back to software const constexpr unsigned MAX_ACCEL_FAILURES {5}; MediaDemuxer::MediaDemuxer() : inputCtx_(avformat_alloc_context()) , startTime_(AV_NOPTS_VALUE) {} MediaDemuxer::~MediaDemuxer() { if (inputCtx_) avformat_close_input(&inputCtx_); av_dict_free(&options_); } const char* MediaDemuxer::getStatusStr(Status status) { switch (status) { case Status::Success: return "Success"; case Status::EndOfFile: return "End of file"; case Status::ReadBufferOverflow: return "Read overflow"; case Status::ReadError: return "Read error"; case Status::FallBack: return "Fallback"; case Status::RestartRequired: return "Restart required"; default: return "Undefined"; } } int MediaDemuxer::openInput(const DeviceParams& params) { inputParams_ = params; auto iformat = av_find_input_format(params.format.c_str()); if (!iformat && !params.format.empty()) JAMI_WARN("Unable to find format \"%s\"", params.format.c_str()); std::string input; if (params.input == "pipewiregrab") { // // We rely on pipewiregrab for screen/window sharing on Wayland. // Because pipewiregrab is a "video source filter" (part of FFmpeg's libavfilter // library), its options must all be passed as part of the `input` string. // input = fmt::format("pipewiregrab=draw_mouse=1:fd={}:node={}", params.fd, params.node); JAMI_LOG("Attempting to open input {}", input); // // In all other cases, we use the `options_` AVDictionary to pass options to FFmpeg. // // NOTE: We rely on the "lavfi" virtual input device to read pipewiregrab's output // and create a corresponding stream (cf. the getDeviceParams function in // daemon/src/media/video/v4l2/video_device_impl.cpp). The `options_` dictionary // could be used to set lavfi's parameters if that was ever needed, but it isn't at // the moment. (Doc: https://ffmpeg.org/ffmpeg-devices.html#lavfi) // } else { if (params.width and params.height) { auto sizeStr = fmt::format("{}x{}", params.width, params.height); av_dict_set(&options_, "video_size", sizeStr.c_str(), 0); } if (params.framerate) { #ifdef _WIN32 // On windows, framerate settings don't reduce to avrational values // that correspond to valid video device formats. // e.g. A the rational<double>(10000000, 333333) or 30.000030000 // will be reduced by av_reduce to 999991/33333 or 30.00003000003 // which cause the device opening routine to fail. // So we treat this imprecise reduction and adjust the value, // or let dshow choose the framerate, which is, unfortunately, // NOT the highest according to our experimentations. auto framerate {params.framerate.real()}; framerate = params.framerate.numerator() / (params.framerate.denominator() + 0.5); if (params.framerate.denominator() != 4999998) av_dict_set(&options_, "framerate", jami::to_string(framerate).c_str(), 0); #else av_dict_set(&options_, "framerate", jami::to_string(params.framerate.real()).c_str(), 0); #endif } if (params.offset_x || params.offset_y) { av_dict_set(&options_, "offset_x", std::to_string(params.offset_x).c_str(), 0); av_dict_set(&options_, "offset_y", std::to_string(params.offset_y).c_str(), 0); } if (params.channel) av_dict_set(&options_, "channel", std::to_string(params.channel).c_str(), 0); av_dict_set(&options_, "loop", params.loop.c_str(), 0); av_dict_set(&options_, "sdp_flags", params.sdp_flags.c_str(), 0); // Set jitter buffer options av_dict_set(&options_, "reorder_queue_size", std::to_string(jitterBufferMaxSize_).c_str(), 0); auto us = std::chrono::duration_cast<std::chrono::microseconds>(jitterBufferMaxDelay_).count(); av_dict_set(&options_, "max_delay", std::to_string(us).c_str(), 0); if (!params.pixel_format.empty()) { av_dict_set(&options_, "pixel_format", params.pixel_format.c_str(), 0); } if (!params.window_id.empty()) { av_dict_set(&options_, "window_id", params.window_id.c_str(), 0); } av_dict_set(&options_, "draw_mouse", "1", 0); av_dict_set(&options_, "is_area", std::to_string(params.is_area).c_str(), 0); #if defined(__APPLE__) && TARGET_OS_MAC input = params.name; #else input = params.input; #endif JAMI_LOG("Attempting to open input {} with format {}, pixel format {}, size {}x{}, rate {}", input, params.format, params.pixel_format, params.width, params.height, params.framerate.real()); } // Ask FFmpeg to open the input using the options set above av_opt_set_int( inputCtx_, "fpsprobesize", 1, AV_OPT_SEARCH_CHILDREN); // Don't waste time fetching framerate when finding stream info int ret = avformat_open_input(&inputCtx_, input.c_str(), iformat, options_ ? &options_ : NULL); if (ret) { JAMI_ERROR("avformat_open_input failed: {}", libav_utils::getError(ret)); } else if (inputCtx_->nb_streams > 0 && inputCtx_->streams[0]->codecpar) { baseWidth_ = inputCtx_->streams[0]->codecpar->width; baseHeight_ = inputCtx_->streams[0]->codecpar->height; JAMI_LOG("Opened input Using format {:s} and resolution {:d}x{:d}", params.format, baseWidth_, baseHeight_); } return ret; } int64_t MediaDemuxer::getDuration() const { return inputCtx_->duration; } bool MediaDemuxer::seekFrame(int, int64_t timestamp) { if (av_seek_frame(inputCtx_, -1, timestamp, AVSEEK_FLAG_BACKWARD) >= 0) { clearFrames(); return true; } return false; } void MediaDemuxer::findStreamInfo() { if (not streamInfoFound_) { inputCtx_->max_analyze_duration = 30 * AV_TIME_BASE; int err; if ((err = avformat_find_stream_info(inputCtx_, nullptr)) < 0) { JAMI_ERR() << "Unable to find stream info: " << libav_utils::getError(err); } streamInfoFound_ = true; } } int MediaDemuxer::selectStream(AVMediaType type) { auto sti = av_find_best_stream(inputCtx_, type, -1, -1, nullptr, 0); if (type == AVMEDIA_TYPE_VIDEO && sti >= 0) { auto st = inputCtx_->streams[sti]; auto disposition = st->disposition; if (disposition & AV_DISPOSITION_ATTACHED_PIC) { JAMI_DBG("Skipping attached picture stream"); sti = -1; } } return sti; } void MediaDemuxer::setInterruptCallback(int (*cb)(void*), void* opaque) { if (cb) { inputCtx_->interrupt_callback.callback = cb; inputCtx_->interrupt_callback.opaque = opaque; } else { inputCtx_->interrupt_callback.callback = 0; } } void MediaDemuxer::setNeedFrameCb(std::function<void()> cb) { needFrameCb_ = std::move(cb); } void MediaDemuxer::setFileFinishedCb(std::function<void(bool)> cb) { fileFinishedCb_ = std::move(cb); } void MediaDemuxer::clearFrames() { { std::lock_guard lk {videoBufferMutex_}; while (!videoBuffer_.empty()) { videoBuffer_.pop(); } } { std::lock_guard lk {audioBufferMutex_}; while (!audioBuffer_.empty()) { audioBuffer_.pop(); } } } bool MediaDemuxer::emitFrame(bool isAudio) { if (isAudio) { return pushFrameFrom(audioBuffer_, isAudio, audioBufferMutex_); } else { return pushFrameFrom(videoBuffer_, isAudio, videoBufferMutex_); } } bool MediaDemuxer::pushFrameFrom( std::queue<std::unique_ptr<AVPacket, std::function<void(AVPacket*)>>>& buffer, bool isAudio, std::mutex& mutex) { std::unique_lock lock(mutex); if (buffer.empty()) { if (currentState_ == MediaDemuxer::CurrentState::Finished) { fileFinishedCb_(isAudio); } else { needFrameCb_(); } return false; } auto packet = std::move(buffer.front()); if (!packet) { return false; } auto streamIndex = packet->stream_index; if (static_cast<unsigned>(streamIndex) >= streams_.size() || streamIndex < 0) { return false; } if (auto& cb = streams_[streamIndex]) { buffer.pop(); lock.unlock(); cb(*packet.get()); } return true; } MediaDemuxer::Status MediaDemuxer::demuxe() { auto packet = std::unique_ptr<AVPacket, std::function<void(AVPacket*)>>(av_packet_alloc(), [](AVPacket* p) { if (p) av_packet_free( &p); }); int ret = av_read_frame(inputCtx_, packet.get()); if (ret == AVERROR(EAGAIN)) { return Status::Success; } else if (ret == AVERROR_EOF) { return Status::EndOfFile; } else if (ret < 0) { JAMI_ERR("Unable to read frame: %s\n", libav_utils::getError(ret).c_str()); return Status::ReadError; } auto streamIndex = packet->stream_index; if (static_cast<unsigned>(streamIndex) >= streams_.size() || streamIndex < 0) { return Status::Success; } AVStream* stream = inputCtx_->streams[streamIndex]; if (stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { std::lock_guard lk {videoBufferMutex_}; videoBuffer_.push(std::move(packet)); if (videoBuffer_.size() >= 90) { return Status::ReadBufferOverflow; } } else { std::lock_guard lk {audioBufferMutex_}; audioBuffer_.push(std::move(packet)); if (audioBuffer_.size() >= 300) { return Status::ReadBufferOverflow; } } return Status::Success; } void MediaDemuxer::setIOContext(MediaIOHandle* ioctx) { inputCtx_->pb = ioctx->getContext(); } MediaDemuxer::Status MediaDemuxer::decode() { if (inputParams_.format == "x11grab" || inputParams_.format == "dxgigrab") { auto ret = inputCtx_->iformat->read_header(inputCtx_); if (ret == AVERROR_EXTERNAL) { JAMI_ERR("Unable to read frame: %s\n", libav_utils::getError(ret).c_str()); return Status::ReadError; } auto codecpar = inputCtx_->streams[0]->codecpar; if (baseHeight_ != codecpar->height || baseWidth_ != codecpar->width) { baseHeight_ = codecpar->height; baseWidth_ = codecpar->width; inputParams_.height = ((baseHeight_ >> 3) << 3); inputParams_.width = ((baseWidth_ >> 3) << 3); return Status::RestartRequired; } } libjami::PacketBuffer packet(av_packet_alloc()); int ret = av_read_frame(inputCtx_, packet.get()); if (ret == AVERROR(EAGAIN)) { /*no data available. Calculate time until next frame. We do not use the emulated frame mechanism from the decoder because it will affect all platforms. With the current implementation, the demuxer will be waiting just in case when av_read_frame returns EAGAIN. For some platforms, av_read_frame is blocking and it will never happen. */ if (inputParams_.framerate.numerator() == 0) return Status::Success; rational<double> frameTime = 1e6 / inputParams_.framerate; int64_t timeToSleep = lastReadPacketTime_ - av_gettime_relative() + frameTime.real<int64_t>(); if (timeToSleep <= 0) { return Status::Success; } std::this_thread::sleep_for(std::chrono::microseconds(timeToSleep)); return Status::Success; } else if (ret == AVERROR_EOF) { return Status::EndOfFile; } else if (ret == AVERROR(EACCES)) { return Status::RestartRequired; } else if (ret < 0) { auto media = inputCtx_->streams[0]->codecpar->codec_type; const auto type = media == AVMediaType::AVMEDIA_TYPE_AUDIO ? "AUDIO" : (media == AVMediaType::AVMEDIA_TYPE_VIDEO ? "VIDEO" : "UNSUPPORTED"); JAMI_ERR("Unable to read [%s] frame: %s\n", type, libav_utils::getError(ret).c_str()); return Status::ReadError; } auto streamIndex = packet->stream_index; if (static_cast<unsigned>(streamIndex) >= streams_.size() || streamIndex < 0) { return Status::Success; } lastReadPacketTime_ = av_gettime_relative(); auto& cb = streams_[streamIndex]; if (cb) { DecodeStatus ret = cb(*packet.get()); if (ret == DecodeStatus::FallBack) return Status::FallBack; } return Status::Success; } MediaDecoder::MediaDecoder(const std::shared_ptr<MediaDemuxer>& demuxer, int index) : demuxer_(demuxer) , avStream_(demuxer->getStream(index)) { demuxer->setStreamCallback(index, [this](AVPacket& packet) { return decode(packet); }); setupStream(); } MediaDecoder::MediaDecoder(const std::shared_ptr<MediaDemuxer>& demuxer, int index, MediaObserver observer) : demuxer_(demuxer) , avStream_(demuxer->getStream(index)) , callback_(std::move(observer)) { demuxer->setStreamCallback(index, [this](AVPacket& packet) { return decode(packet); }); setupStream(); } bool MediaDecoder::emitFrame(bool isAudio) { return demuxer_->emitFrame(isAudio); } MediaDecoder::MediaDecoder() : demuxer_(new MediaDemuxer) {} MediaDecoder::MediaDecoder(MediaObserver o) : demuxer_(new MediaDemuxer) , callback_(std::move(o)) {} MediaDecoder::~MediaDecoder() { #ifdef RING_ACCEL if (decoderCtx_ && decoderCtx_->hw_device_ctx) av_buffer_unref(&decoderCtx_->hw_device_ctx); #endif if (decoderCtx_) avcodec_free_context(&decoderCtx_); } void MediaDecoder::flushBuffers() { avcodec_flush_buffers(decoderCtx_); } int MediaDecoder::openInput(const DeviceParams& p) { return demuxer_->openInput(p); } void MediaDecoder::setInterruptCallback(int (*cb)(void*), void* opaque) { demuxer_->setInterruptCallback(cb, opaque); } void MediaDecoder::setIOContext(MediaIOHandle* ioctx) { demuxer_->setIOContext(ioctx); } int MediaDecoder::setup(AVMediaType type) { demuxer_->findStreamInfo(); auto stream = demuxer_->selectStream(type); if (stream < 0) { JAMI_ERR("No stream found for type %i", static_cast<int>(type)); return -1; } avStream_ = demuxer_->getStream(stream); if (avStream_ == nullptr) { JAMI_ERR("No stream found at index %i", stream); return -1; } demuxer_->setStreamCallback(stream, [this](AVPacket& packet) { return decode(packet); }); return setupStream(); } int MediaDecoder::setupStream() { int ret = 0; avcodec_free_context(&decoderCtx_); if (prepareDecoderContext() < 0) return -1; // failed #ifdef RING_ACCEL // if there was a fallback to software decoding, do not enable accel // it has been disabled already by the video_receive_thread/video_input enableAccel_ &= Manager::instance().videoPreferences.getDecodingAccelerated(); if (enableAccel_ and not fallback_) { auto APIs = video::HardwareAccel::getCompatibleAccel(decoderCtx_->codec_id, decoderCtx_->width, decoderCtx_->height, CODEC_DECODER); for (const auto& it : APIs) { accel_ = std::make_unique<video::HardwareAccel>(it); // save accel auto ret = accel_->initAPI(false, nullptr); if (ret < 0) { accel_.reset(); continue; } if (prepareDecoderContext() < 0) return -1; // failed accel_->setDetails(decoderCtx_); decoderCtx_->opaque = accel_.get(); decoderCtx_->pix_fmt = accel_->getFormat(); if (avcodec_open2(decoderCtx_, inputDecoder_, &options_) < 0) { // Failed to open codec JAMI_WARN("Fail to open hardware decoder for %s with %s", avcodec_get_name(decoderCtx_->codec_id), it.getName().c_str()); avcodec_free_context(&decoderCtx_); decoderCtx_ = nullptr; accel_.reset(); continue; } else { // Succeed to open codec JAMI_WARN("Using hardware decoding for %s with %s", avcodec_get_name(decoderCtx_->codec_id), it.getName().c_str()); break; } } } #endif JAMI_LOG("Using {} ({}) decoder for {}", inputDecoder_->long_name, inputDecoder_->name, av_get_media_type_string(avStream_->codecpar->codec_type)); decoderCtx_->thread_count = std::max(1u, std::min(8u, std::thread::hardware_concurrency() / 2)); if (emulateRate_) JAMI_DBG() << "Using framerate emulation"; startTime_ = av_gettime(); // used to set pts after decoding, and for rate emulation #ifdef RING_ACCEL if (!accel_) { JAMI_WARN("Not using hardware decoding for %s", avcodec_get_name(decoderCtx_->codec_id)); ret = avcodec_open2(decoderCtx_, inputDecoder_, nullptr); } #else ret = avcodec_open2(decoderCtx_, inputDecoder_, nullptr); #endif if (ret < 0) { JAMI_ERR() << "Unable to open codec: " << libav_utils::getError(ret); return -1; } return 0; } int MediaDecoder::prepareDecoderContext() { inputDecoder_ = findDecoder(avStream_->codecpar->codec_id); if (!inputDecoder_) { JAMI_ERROR("Unsupported codec"); return -1; } decoderCtx_ = avcodec_alloc_context3(inputDecoder_); if (!decoderCtx_) { JAMI_ERROR("Failed to create decoder context"); return -1; } avcodec_parameters_to_context(decoderCtx_, avStream_->codecpar); width_ = decoderCtx_->width; height_ = decoderCtx_->height; decoderCtx_->framerate = avStream_->avg_frame_rate; if (avStream_->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { if (decoderCtx_->framerate.num == 0 || decoderCtx_->framerate.den == 0) decoderCtx_->framerate = inputParams_.framerate; if (decoderCtx_->framerate.num == 0 || decoderCtx_->framerate.den == 0) decoderCtx_->framerate = {30, 1}; } else if (avStream_->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) { if (decoderCtx_->codec_id == AV_CODEC_ID_OPUS) { av_opt_set_int(decoderCtx_, "decode_fec", fecEnabled_ ? 1 : 0, AV_OPT_SEARCH_CHILDREN); } auto format = libav_utils::choose_sample_fmt_default(inputDecoder_, Manager::instance().getRingBufferPool().getInternalAudioFormat().sampleFormat); decoderCtx_->sample_fmt = format; decoderCtx_->request_sample_fmt = format; } return 0; } void MediaDecoder::updateStartTime(int64_t startTime) { startTime_ = startTime; } DecodeStatus MediaDecoder::decode(AVPacket& packet) { int frameFinished = 0; auto ret = avcodec_send_packet(decoderCtx_, &packet); if (ret < 0 && ret != AVERROR(EAGAIN)) { #ifdef RING_ACCEL if (accel_) { JAMI_WARN("Decoding error falling back to software"); fallback_ = true; accel_.reset(); avcodec_flush_buffers(decoderCtx_); setupStream(); return DecodeStatus::FallBack; } #endif avcodec_flush_buffers(decoderCtx_); return ret == AVERROR_EOF ? DecodeStatus::Success : DecodeStatus::DecodeError; } #ifdef ENABLE_VIDEO auto f = (inputDecoder_->type == AVMEDIA_TYPE_VIDEO) ? std::static_pointer_cast<MediaFrame>(std::make_shared<VideoFrame>()) : std::static_pointer_cast<MediaFrame>(std::make_shared<AudioFrame>()); #else auto f = std::static_pointer_cast<MediaFrame>(std::make_shared<AudioFrame>()); #endif auto frame = f->pointer(); ret = avcodec_receive_frame(decoderCtx_, frame); // time_base is not set in AVCodecContext for decoding // fail to set it causes pts to be incorrectly computed down in the function if (inputDecoder_->type == AVMEDIA_TYPE_VIDEO) { decoderCtx_->time_base.num = decoderCtx_->framerate.den; decoderCtx_->time_base.den = decoderCtx_->framerate.num; } else { decoderCtx_->time_base.num = 1; decoderCtx_->time_base.den = decoderCtx_->sample_rate; } frame->time_base = decoderCtx_->time_base; if (resolutionChangedCallback_) { if (decoderCtx_->width != width_ or decoderCtx_->height != height_) { JAMI_DBG("Resolution changed from %dx%d to %dx%d", width_, height_, decoderCtx_->width, decoderCtx_->height); width_ = decoderCtx_->width; height_ = decoderCtx_->height; resolutionChangedCallback_(width_, height_); } } if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF) { return DecodeStatus::DecodeError; } if (ret >= 0) frameFinished = 1; if (frameFinished) { if (inputDecoder_->type == AVMEDIA_TYPE_VIDEO) frame->format = (AVPixelFormat) correctPixFmt(frame->format); auto packetTimestamp = frame->pts; // in stream time base frame->pts = av_rescale_q_rnd(av_gettime() - startTime_, {1, AV_TIME_BASE}, decoderCtx_->time_base, static_cast<AVRounding>(AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX)); lastTimestamp_ = frame->pts; if (emulateRate_ and packetTimestamp != AV_NOPTS_VALUE) { auto startTime = avStream_->start_time == AV_NOPTS_VALUE ? 0 : avStream_->start_time; rational<double> frame_time = rational<double>(getTimeBase()) * (packetTimestamp - startTime); auto target_relative = static_cast<std::int64_t>(frame_time.real() * 1e6); auto target_absolute = startTime_ + target_relative; if (target_relative < seekTime_) { return DecodeStatus::Success; } // required frame found. Reset seek time if (target_relative >= seekTime_) { resetSeekTime(); } auto now = av_gettime(); if (target_absolute > now) { std::this_thread::sleep_for(std::chrono::microseconds(target_absolute - now)); } } if (callback_) callback_(std::move(f)); if (contextCallback_ && firstDecode_.load()) { firstDecode_.exchange(false); contextCallback_(); } return DecodeStatus::FrameFinished; } return DecodeStatus::Success; } void MediaDecoder::setSeekTime(int64_t time) { seekTime_ = time; } MediaDemuxer::Status MediaDecoder::decode() { auto ret = demuxer_->decode(); if (ret == MediaDemuxer::Status::RestartRequired) { avcodec_flush_buffers(decoderCtx_); setupStream(); ret = MediaDemuxer::Status::EndOfFile; } return ret; } #ifdef ENABLE_VIDEO #ifdef RING_ACCEL void MediaDecoder::enableAccel(bool enableAccel) { enableAccel_ = enableAccel; emitSignal<libjami::ConfigurationSignal::HardwareDecodingChanged>(enableAccel_); if (!enableAccel) { accel_.reset(); if (decoderCtx_) decoderCtx_->opaque = nullptr; } } #endif DecodeStatus MediaDecoder::flush() { AVPacket inpacket; av_init_packet(&inpacket); int frameFinished = 0; int ret = 0; ret = avcodec_send_packet(decoderCtx_, &inpacket); if (ret < 0 && ret != AVERROR(EAGAIN)) return ret == AVERROR_EOF ? DecodeStatus::Success : DecodeStatus::DecodeError; auto result = std::make_shared<MediaFrame>(); ret = avcodec_receive_frame(decoderCtx_, result->pointer()); if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF) return DecodeStatus::DecodeError; if (ret >= 0) frameFinished = 1; if (frameFinished) { av_packet_unref(&inpacket); if (callback_) callback_(std::move(result)); return DecodeStatus::FrameFinished; } return DecodeStatus::Success; } #endif // ENABLE_VIDEO int MediaDecoder::getWidth() const { return decoderCtx_ ? decoderCtx_->width : 0; } int MediaDecoder::getHeight() const { return decoderCtx_ ? decoderCtx_->height : 0; } std::string MediaDecoder::getDecoderName() const { return decoderCtx_ ? decoderCtx_->codec->name : ""; } rational<double> MediaDecoder::getFps() const { return {(double) avStream_->avg_frame_rate.num, (double) avStream_->avg_frame_rate.den}; } rational<unsigned> MediaDecoder::getTimeBase() const { return {(unsigned) avStream_->time_base.num, (unsigned) avStream_->time_base.den}; } AVPixelFormat MediaDecoder::getPixelFormat() const { return decoderCtx_->pix_fmt; } int MediaDecoder::correctPixFmt(int input_pix_fmt) { // https://ffmpeg.org/pipermail/ffmpeg-user/2014-February/020152.html int pix_fmt; switch (input_pix_fmt) { case AV_PIX_FMT_YUVJ420P: pix_fmt = AV_PIX_FMT_YUV420P; break; case AV_PIX_FMT_YUVJ422P: pix_fmt = AV_PIX_FMT_YUV422P; break; case AV_PIX_FMT_YUVJ444P: pix_fmt = AV_PIX_FMT_YUV444P; break; case AV_PIX_FMT_YUVJ440P: pix_fmt = AV_PIX_FMT_YUV440P; break; default: pix_fmt = input_pix_fmt; break; } return pix_fmt; } MediaStream MediaDecoder::getStream(std::string name) const { if (!decoderCtx_) { JAMI_WARN("No decoder context"); return {}; } auto ms = MediaStream(name, decoderCtx_, lastTimestamp_); #ifdef RING_ACCEL // accel_ is null if not using accelerated codecs if (accel_) ms.format = accel_->getSoftwareFormat(); #endif return ms; } } // namespace jami
28,532
C++
.cpp
793
28.501892
155
0.609727
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,729
media_encoder.cpp
savoirfairelinux_jami-daemon/src/media/media_encoder.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "libav_deps.h" // MUST BE INCLUDED FIRST #include "media_codec.h" #include "media_encoder.h" #include "media_buffer.h" #include "client/ring_signal.h" #include "fileutils.h" #include "logger.h" #include "manager.h" #include "string_utils.h" #include "system_codec_container.h" #ifdef RING_ACCEL #include "video/accel.h" #endif extern "C" { #include <libavutil/parseutils.h> } #include <algorithm> #include <fstream> #include <iostream> #include <json/json.h> #include <sstream> #include <thread> // hardware_concurrency #include <string_view> #include <cmath> // Define following line if you need to debug libav SDP //#define DEBUG_SDP 1 using namespace std::literals; namespace jami { constexpr double LOGREG_PARAM_A {101}; constexpr double LOGREG_PARAM_B {-5.}; constexpr double LOGREG_PARAM_A_HEVC {96}; constexpr double LOGREG_PARAM_B_HEVC {-5.}; MediaEncoder::MediaEncoder() : outputCtx_(avformat_alloc_context()) { JAMI_DBG("[%p] New instance created", this); } MediaEncoder::~MediaEncoder() { if (outputCtx_) { if (outputCtx_->priv_data && outputCtx_->pb) av_write_trailer(outputCtx_); if (fileIO_) { avio_close(outputCtx_->pb); } for (auto encoderCtx : encoders_) { if (encoderCtx) { #ifndef _MSC_VER avcodec_free_context(&encoderCtx); #else avcodec_close(encoderCtx); #endif } } avformat_free_context(outputCtx_); } av_dict_free(&options_); JAMI_DBG("[%p] Instance destroyed", this); } void MediaEncoder::setOptions(const MediaStream& opts) { if (!opts.isValid()) { JAMI_ERR() << "Invalid options"; return; } if (opts.isVideo) { videoOpts_ = opts; // Make sure width and height are even (required by x264) // This is especially for image/gif streaming, as video files and cameras usually have even // resolutions videoOpts_.width = ((videoOpts_.width >> 3) << 3); videoOpts_.height = ((videoOpts_.height >> 3) << 3); if (!videoOpts_.frameRate) videoOpts_.frameRate = 30; if (!videoOpts_.bitrate) { videoOpts_.bitrate = SystemCodecInfo::DEFAULT_VIDEO_BITRATE; } } else { audioOpts_ = opts; } } void MediaEncoder::setOptions(const MediaDescription& args) { int ret; if (args.payload_type and (ret = av_opt_set_int(reinterpret_cast<void*>(outputCtx_), "payload_type", args.payload_type, AV_OPT_SEARCH_CHILDREN) < 0)) JAMI_ERR() << "Failed to set payload type: " << libav_utils::getError(ret); if (not args.parameters.empty()) libav_utils::setDictValue(&options_, "parameters", args.parameters); mode_ = args.mode; linkableHW_ = args.linkableHW; fecEnabled_ = args.fecEnabled; } void MediaEncoder::setMetadata(const std::string& title, const std::string& description) { if (not title.empty()) libav_utils::setDictValue(&outputCtx_->metadata, "title", title); if (not description.empty()) libav_utils::setDictValue(&outputCtx_->metadata, "description", description); } void MediaEncoder::setInitSeqVal(uint16_t seqVal) { // only set not default value (!=0) if (seqVal != 0) av_opt_set_int(outputCtx_, "seq", seqVal, AV_OPT_SEARCH_CHILDREN); } uint16_t MediaEncoder::getLastSeqValue() { int64_t retVal; if (av_opt_get_int(outputCtx_, "seq", AV_OPT_SEARCH_CHILDREN, &retVal) >= 0) return (uint16_t) retVal; else return 0; } void MediaEncoder::openOutput(const std::string& filename, const std::string& format) { avformat_free_context(outputCtx_); int result = avformat_alloc_output_context2(&outputCtx_, nullptr, format.empty() ? nullptr : format.c_str(), filename.c_str()); if (result < 0) JAMI_ERR() << "Unable to open " << filename << ": " << libav_utils::getError(-result); } int MediaEncoder::addStream(const SystemCodecInfo& systemCodecInfo) { if (systemCodecInfo.mediaType == MEDIA_AUDIO) { audioCodec_ = systemCodecInfo.name; } else { videoCodec_ = systemCodecInfo.name; } auto stream = avformat_new_stream(outputCtx_, outputCodec_); if (stream == nullptr) { JAMI_ERR("[%p] Failed to create coding instance for %s", this, systemCodecInfo.name.c_str()); return -1; } JAMI_DBG("[%p] Created new coding instance for %s @ index %d", this, systemCodecInfo.name.c_str(), stream->index); // Only init audio now, video will be intialized when // encoding the first frame. if (systemCodecInfo.mediaType == MEDIA_AUDIO) { return initStream(systemCodecInfo); } // If audio options are valid, it means this session is used // for both audio and video streams, thus the video will be // at index 1, otherwise it will be at index 0. // TODO. Hacky, needs better solution. if (audioOpts_.isValid()) return 1; else return 0; } int MediaEncoder::initStream(const std::string& codecName, AVBufferRef* framesCtx) { const auto codecInfo = getSystemCodecContainer()->searchCodecByName(codecName, MEDIA_ALL); if (codecInfo) return initStream(*codecInfo, framesCtx); else return -1; } int MediaEncoder::initStream(const SystemCodecInfo& systemCodecInfo, AVBufferRef* framesCtx) { JAMI_DBG("[%p] Initializing stream: codec type %d, name %s, lib %s", this, systemCodecInfo.codecType, systemCodecInfo.name.c_str(), systemCodecInfo.libName.c_str()); std::lock_guard lk(encMutex_); if (!outputCtx_) throw MediaEncoderException("Unable to allocate stream"); // Must already have codec instance(s) if (outputCtx_->nb_streams == 0) { JAMI_ERR("[%p] Unable to init, output context has no coding sessions!", this); throw MediaEncoderException("Unable to init, output context has no coding sessions!"); } AVCodecContext* encoderCtx = nullptr; AVMediaType mediaType; if (systemCodecInfo.mediaType == MEDIA_VIDEO) mediaType = AVMEDIA_TYPE_VIDEO; else if (systemCodecInfo.mediaType == MEDIA_AUDIO) mediaType = AVMEDIA_TYPE_AUDIO; else throw MediaEncoderException("Unsuported media type"); AVStream* stream {nullptr}; // Only supports one audio and one video streams at most per instance. for (unsigned i = 0; i < outputCtx_->nb_streams; i++) { stream = outputCtx_->streams[i]; if (stream->codecpar->codec_type == mediaType) { if (mediaType == AVMEDIA_TYPE_VIDEO) { stream->codecpar->width = videoOpts_.width; stream->codecpar->height = videoOpts_.height; } break; } } if (stream == nullptr) { JAMI_ERR("[%p] Unable to init, output context has no coding sessions for %s", this, systemCodecInfo.name.c_str()); throw MediaEncoderException("Unable to allocate stream"); } currentStreamIdx_ = stream->index; #ifdef RING_ACCEL // Get compatible list of Hardware API if (enableAccel_ && mediaType == AVMEDIA_TYPE_VIDEO) { auto APIs = video::HardwareAccel::getCompatibleAccel(static_cast<AVCodecID>( systemCodecInfo.avcodecId), videoOpts_.width, videoOpts_.height, CODEC_ENCODER); for (const auto& it : APIs) { accel_ = std::make_unique<video::HardwareAccel>(it); // save accel // Init codec need accel_ to init encoderCtx accelerated encoderCtx = initCodec(mediaType, static_cast<AVCodecID>(systemCodecInfo.avcodecId), videoOpts_.bitrate); encoderCtx->opaque = accel_.get(); // Check if pixel format from encoder match pixel format from decoder frame context // if it mismatch, it means that we are using two different hardware API (nvenc and // vaapi for example) in this case we don't want link the APIs if (framesCtx) { auto hw = reinterpret_cast<AVHWFramesContext*>(framesCtx->data); if (encoderCtx->pix_fmt != hw->format) linkableHW_ = false; } auto ret = accel_->initAPI(linkableHW_, framesCtx); if (ret < 0) { accel_.reset(); encoderCtx = nullptr; continue; } accel_->setDetails(encoderCtx); if (avcodec_open2(encoderCtx, outputCodec_, &options_) < 0) { // Failed to open codec JAMI_WARN("Fail to open hardware encoder %s with %s ", avcodec_get_name(static_cast<AVCodecID>(systemCodecInfo.avcodecId)), it.getName().c_str()); avcodec_free_context(&encoderCtx); encoderCtx = nullptr; accel_ = nullptr; continue; } else { // Succeed to open codec JAMI_WARN("Using hardware encoding for %s with %s ", avcodec_get_name(static_cast<AVCodecID>(systemCodecInfo.avcodecId)), it.getName().c_str()); encoders_.emplace_back(encoderCtx); break; } } } #endif if (!encoderCtx) { JAMI_WARN("Not using hardware encoding for %s", avcodec_get_name(static_cast<AVCodecID>(systemCodecInfo.avcodecId))); encoderCtx = initCodec(mediaType, static_cast<AVCodecID>(systemCodecInfo.avcodecId), videoOpts_.bitrate); readConfig(encoderCtx); encoders_.emplace_back(encoderCtx); if (avcodec_open2(encoderCtx, outputCodec_, &options_) < 0) throw MediaEncoderException("Unable to open encoder"); } avcodec_parameters_from_context(stream->codecpar, encoderCtx); // framerate is not copied from encoderCtx to stream stream->avg_frame_rate = encoderCtx->framerate; #ifdef ENABLE_VIDEO if (systemCodecInfo.mediaType == MEDIA_VIDEO) { // allocate buffers for both scaled (pre-encoder) and encoded frames const int width = encoderCtx->width; const int height = encoderCtx->height; int format = encoderCtx->pix_fmt; #ifdef RING_ACCEL if (accel_) { // hardware encoders require a specific pixel format auto desc = av_pix_fmt_desc_get(encoderCtx->pix_fmt); if (desc && (desc->flags & AV_PIX_FMT_FLAG_HWACCEL)) format = accel_->getSoftwareFormat(); } #endif scaledFrameBufferSize_ = videoFrameSize(format, width, height); if (scaledFrameBufferSize_ < 0) throw MediaEncoderException( ("Unable to compute buffer size: " + libav_utils::getError(scaledFrameBufferSize_)) .c_str()); else if (scaledFrameBufferSize_ <= AV_INPUT_BUFFER_MIN_SIZE) throw MediaEncoderException("buffer too small"); scaledFrameBuffer_.resize(scaledFrameBufferSize_); scaledFrame_ = std::make_shared<VideoFrame>(); scaledFrame_->setFromMemory(scaledFrameBuffer_.data(), format, width, height); } #endif // ENABLE_VIDEO return stream->index; } void MediaEncoder::openIOContext() { if (ioCtx_) { outputCtx_->pb = ioCtx_; outputCtx_->packet_size = outputCtx_->pb->buffer_size; } else { int ret = 0; #if LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(58, 7, 100) const char* filename = outputCtx_->url; #else const char* filename = outputCtx_->filename; #endif if (!(outputCtx_->oformat->flags & AVFMT_NOFILE)) { fileIO_ = true; if ((ret = avio_open(&outputCtx_->pb, filename, AVIO_FLAG_WRITE)) < 0) { throw MediaEncoderException(fmt::format("Unable to open IO context for '{}': {}", filename, libav_utils::getError(ret))); } } } } void MediaEncoder::startIO() { if (!outputCtx_->pb) openIOContext(); if (avformat_write_header(outputCtx_, options_ ? &options_ : nullptr)) { JAMI_ERR("Unable to write header for output file... check codec parameters"); throw MediaEncoderException("Failed to write output file header"); } #if LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(58, 7, 100) av_dump_format(outputCtx_, 0, outputCtx_->url, 1); #else av_dump_format(outputCtx_, 0, outputCtx_->filename, 1); #endif initialized_ = true; } #ifdef ENABLE_VIDEO int MediaEncoder::encode(const std::shared_ptr<VideoFrame>& input, bool is_keyframe, int64_t frame_number) { auto width = (input->width() >> 3) << 3; auto height = (input->height() >> 3) << 3; if (initialized_ && (getWidth() != width || getHeight() != height)) { resetStreams(width, height); is_keyframe = true; } if (!initialized_) { initStream(videoCodec_, input->pointer()->hw_frames_ctx); startIO(); } std::shared_ptr<VideoFrame> output; #ifdef RING_ACCEL if (getHWFrame(input, output) < 0) { JAMI_ERR("Fail to get hardware frame"); return -1; } #else output = getScaledSWFrame(*input.get()); #endif // RING_ACCEL if (!output) { JAMI_ERR("Fail to get frame"); return -1; } auto avframe = output->pointer(); AVCodecContext* enc = encoders_[currentStreamIdx_]; avframe->pts = frame_number; if (enc->framerate.num != enc->time_base.den || enc->framerate.den != enc->time_base.num) avframe->pts /= (rational<int64_t>(enc->framerate) * rational<int64_t>(enc->time_base)) .real<int64_t>(); if (is_keyframe) { avframe->pict_type = AV_PICTURE_TYPE_I; avframe->key_frame = 1; } else { avframe->pict_type = AV_PICTURE_TYPE_NONE; avframe->key_frame = 0; } return encode(avframe, currentStreamIdx_); } #endif // ENABLE_VIDEO int MediaEncoder::encodeAudio(AudioFrame& frame) { if (!initialized_) { // Initialize on first video frame, or first audio frame if no video stream if (not videoOpts_.isValid()) startIO(); else return 0; } frame.pointer()->pts = sent_samples; sent_samples += frame.pointer()->nb_samples; encode(frame.pointer(), currentStreamIdx_); return 0; } int MediaEncoder::encode(AVFrame* frame, int streamIdx) { if (!initialized_ && frame) { // Initialize on first video frame, or first audio frame if no video stream bool isVideo = (frame->width > 0 && frame->height > 0); if (isVideo and videoOpts_.isValid()) { // Has video stream, so init with video frame streamIdx = initStream(videoCodec_, frame->hw_frames_ctx); startIO(); } else if (!isVideo and !videoOpts_.isValid()) { // Only audio, for MediaRecorder, which doesn't use encodeAudio startIO(); } else { return 0; } } int ret = 0; if (static_cast<size_t>(streamIdx) >= encoders_.size()) return -1; AVCodecContext* encoderCtx = encoders_[streamIdx]; AVPacket pkt; av_init_packet(&pkt); pkt.data = nullptr; // packet data will be allocated by the encoder pkt.size = 0; if (!encoderCtx) return -1; ret = avcodec_send_frame(encoderCtx, frame); if (ret < 0) return -1; while (ret >= 0) { ret = avcodec_receive_packet(encoderCtx, &pkt); if (ret == AVERROR(EAGAIN)) break; if (ret < 0 && ret != AVERROR_EOF) { // we still want to write our frame on EOF JAMI_ERR() << "Failed to encode frame: " << libav_utils::getError(ret); return ret; } if (pkt.size) { if (send(pkt, streamIdx)) break; } } av_packet_unref(&pkt); return 0; } bool MediaEncoder::send(AVPacket& pkt, int streamIdx) { if (!initialized_) { streamIdx = initStream(videoCodec_); startIO(); } if (streamIdx < 0) streamIdx = currentStreamIdx_; if (streamIdx >= 0 and static_cast<size_t>(streamIdx) < encoders_.size() and static_cast<unsigned int>(streamIdx) < outputCtx_->nb_streams) { auto encoderCtx = encoders_[streamIdx]; pkt.stream_index = streamIdx; if (pkt.pts != AV_NOPTS_VALUE) pkt.pts = av_rescale_q(pkt.pts, encoderCtx->time_base, outputCtx_->streams[streamIdx]->time_base); if (pkt.dts != AV_NOPTS_VALUE) pkt.dts = av_rescale_q(pkt.dts, encoderCtx->time_base, outputCtx_->streams[streamIdx]->time_base); } // write the compressed frame auto ret = av_write_frame(outputCtx_, &pkt); if (ret < 0) { JAMI_ERR() << "av_write_frame failed: " << libav_utils::getError(ret); } return ret >= 0; } int MediaEncoder::flush() { int ret = 0; for (size_t i = 0; i < outputCtx_->nb_streams; ++i) { if (encode(nullptr, i) < 0) { JAMI_ERR() << "Unable to flush stream #" << i; ret |= 1u << i; // provide a way for caller to know which streams failed } } return -ret; } std::string MediaEncoder::print_sdp() { /* theora sdp can be huge */ const auto sdp_size = outputCtx_->streams[currentStreamIdx_]->codecpar->extradata_size + 2048; std::string sdp(sdp_size, '\0'); av_sdp_create(&outputCtx_, 1, &(*sdp.begin()), sdp_size); std::string result; result.reserve(sdp_size); std::string_view steam(sdp), line; while (jami::getline(steam, line)) { /* strip windows line ending */ result += line.substr(0, line.length() - 1); result += "\n"sv; } #ifdef DEBUG_SDP JAMI_DBG("Sending SDP:\n%s", result.c_str()); #endif return result; } AVCodecContext* MediaEncoder::prepareEncoderContext(const AVCodec* outputCodec, bool is_video) { AVCodecContext* encoderCtx = avcodec_alloc_context3(outputCodec); auto encoderName = outputCodec->name; // guaranteed to be non null if AVCodec is not null encoderCtx->thread_count = std::min(std::thread::hardware_concurrency(), is_video ? 16u : 4u); JAMI_DBG("[%s] Using %d threads", encoderName, encoderCtx->thread_count); if (is_video) { // resolution must be a multiple of two encoderCtx->width = videoOpts_.width; encoderCtx->height = videoOpts_.height; // satisfy ffmpeg: denominator must be 16bit or less value // time base = 1/FPS av_reduce(&encoderCtx->framerate.num, &encoderCtx->framerate.den, videoOpts_.frameRate.numerator(), videoOpts_.frameRate.denominator(), (1U << 16) - 1); encoderCtx->time_base = av_inv_q(encoderCtx->framerate); // emit one intra frame every gop_size frames encoderCtx->max_b_frames = 0; encoderCtx->pix_fmt = AV_PIX_FMT_YUV420P; // Keep YUV format for macOS #ifdef RING_ACCEL #if defined(TARGET_OS_IOS) && TARGET_OS_IOS if (accel_) encoderCtx->pix_fmt = accel_->getSoftwareFormat(); #elif !defined(__APPLE__) if (accel_) encoderCtx->pix_fmt = accel_->getFormat(); #endif #endif // Fri Jul 22 11:37:59 EDT 2011:tmatth:XXX: DON'T set this, we want our // pps and sps to be sent in-band for RTP // This is to place global headers in extradata instead of every // keyframe. // encoderCtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; } else { JAMI_WARNING("Codec format: {} {} {} {}", encoderName, audioOpts_.format, audioOpts_.sampleRate, audioOpts_.nbChannels); encoderCtx->sample_fmt = (AVSampleFormat)audioOpts_.format; encoderCtx->sample_rate = std::max(8000, audioOpts_.sampleRate); encoderCtx->time_base = AVRational {1, encoderCtx->sample_rate}; if (audioOpts_.nbChannels > 2 || audioOpts_.nbChannels < 1) { audioOpts_.nbChannels = std::clamp(audioOpts_.nbChannels, 1, 2); JAMI_ERR() << "[" << encoderName << "] Clamping invalid channel count: " << audioOpts_.nbChannels; } av_channel_layout_default(&encoderCtx->ch_layout, audioOpts_.nbChannels); if (audioOpts_.frameSize) { encoderCtx->frame_size = audioOpts_.frameSize; JAMI_DBG() << "[" << encoderName << "] Frame size " << encoderCtx->frame_size; } else { JAMI_WARN() << "[" << encoderName << "] Frame size not set"; } } return encoderCtx; } void MediaEncoder::forcePresetX2645(AVCodecContext* encoderCtx) { #ifdef RING_ACCEL if (accel_ && accel_->getName() == "nvenc") { if (av_opt_set(encoderCtx, "preset", "fast", AV_OPT_SEARCH_CHILDREN)) JAMI_WARN("Failed to set preset to 'fast'"); if (av_opt_set(encoderCtx, "level", "auto", AV_OPT_SEARCH_CHILDREN)) JAMI_WARN("Failed to set level to 'auto'"); if (av_opt_set_int(encoderCtx, "zerolatency", 1, AV_OPT_SEARCH_CHILDREN)) JAMI_WARN("Failed to set zerolatency to '1'"); } else #endif { #if (defined(TARGET_OS_IOS) && TARGET_OS_IOS) const char* speedPreset = "ultrafast"; #else const char* speedPreset = "veryfast"; #endif if (av_opt_set(encoderCtx, "preset", speedPreset, AV_OPT_SEARCH_CHILDREN)) JAMI_WARN("Failed to set preset '%s'", speedPreset); const char* tune = "zerolatency"; if (av_opt_set(encoderCtx, "tune", tune, AV_OPT_SEARCH_CHILDREN)) JAMI_WARN("Failed to set tune '%s'", tune); } } void MediaEncoder::extractProfileLevelID(const std::string& parameters, AVCodecContext* ctx) { // From RFC3984: // If no profile-level-id is present, the Baseline Profile without // additional constraints at Level 1 MUST be implied. ctx->profile = FF_PROFILE_H264_CONSTRAINED_BASELINE; ctx->level = 0x0d; // ctx->level = 0x0d; // => 13 aka 1.3 if (parameters.empty()) return; const std::string target("profile-level-id="); size_t needle = parameters.find(target); if (needle == std::string::npos) return; needle += target.length(); const size_t id_length = 6; /* digits */ const std::string profileLevelID(parameters.substr(needle, id_length)); if (profileLevelID.length() != id_length) return; int result; std::stringstream ss; ss << profileLevelID; ss >> std::hex >> result; // profile-level id consists of three bytes const unsigned char profile_idc = result >> 16; // 42xxxx -> 42 const unsigned char profile_iop = ((result >> 8) & 0xff); // xx80xx -> 80 ctx->level = result & 0xff; // xxxx0d -> 0d switch (profile_idc) { case FF_PROFILE_H264_BASELINE: // check constraint_set_1_flag if ((profile_iop & 0x40) >> 6) ctx->profile |= FF_PROFILE_H264_CONSTRAINED; break; case FF_PROFILE_H264_HIGH_10: case FF_PROFILE_H264_HIGH_422: case FF_PROFILE_H264_HIGH_444_PREDICTIVE: // check constraint_set_3_flag if ((profile_iop & 0x10) >> 4) ctx->profile |= FF_PROFILE_H264_INTRA; break; } JAMI_DBG("Using profile %s (%x) and level %d", avcodec_profile_name(AV_CODEC_ID_H264, ctx->profile), ctx->profile, ctx->level); } #ifdef RING_ACCEL void MediaEncoder::enableAccel(bool enableAccel) { enableAccel_ = enableAccel; emitSignal<libjami::ConfigurationSignal::HardwareEncodingChanged>(enableAccel_); if (!enableAccel_) { accel_.reset(); for (auto enc : encoders_) enc->opaque = nullptr; } } #endif unsigned MediaEncoder::getStreamCount() const { return (audioOpts_.isValid() + videoOpts_.isValid()); } MediaStream MediaEncoder::getStream(const std::string& name, int streamIdx) const { // if streamIdx is negative, use currentStreamIdx_ if (streamIdx < 0) streamIdx = currentStreamIdx_; // make sure streamIdx is valid if (getStreamCount() <= 0 || streamIdx < 0 || encoders_.size() < (unsigned) (streamIdx + 1)) return {}; auto enc = encoders_[streamIdx]; // TODO set firstTimestamp auto ms = MediaStream(name, enc); #ifdef RING_ACCEL if (accel_) ms.format = accel_->getSoftwareFormat(); #endif return ms; } AVCodecContext* MediaEncoder::initCodec(AVMediaType mediaType, AVCodecID avcodecId, uint64_t br) { outputCodec_ = nullptr; #ifdef RING_ACCEL if (mediaType == AVMEDIA_TYPE_VIDEO) { if (enableAccel_) { if (accel_) { outputCodec_ = avcodec_find_encoder_by_name(accel_->getCodecName().c_str()); } } else { JAMI_WARN() << "Hardware encoding disabled"; } } #endif if (!outputCodec_) { /* find the video encoder */ if (avcodecId == AV_CODEC_ID_H263) // For H263 encoding, we force the use of AV_CODEC_ID_H263P (H263-1998) // H263-1998 can manage all frame sizes while H263 don't // AV_CODEC_ID_H263 decoder will be used for decoding outputCodec_ = avcodec_find_encoder(AV_CODEC_ID_H263P); else outputCodec_ = avcodec_find_encoder(static_cast<AVCodecID>(avcodecId)); if (!outputCodec_) { throw MediaEncoderException("No output encoder"); } } AVCodecContext* encoderCtx = prepareEncoderContext(outputCodec_, mediaType == AVMEDIA_TYPE_VIDEO); // Only clamp video bitrate if (mediaType == AVMEDIA_TYPE_VIDEO && br > 0) { if (br < SystemCodecInfo::DEFAULT_MIN_BITRATE) { JAMI_WARNING("Requested bitrate {:d} too low, setting to {:d}", br, SystemCodecInfo::DEFAULT_MIN_BITRATE); br = SystemCodecInfo::DEFAULT_MIN_BITRATE; } else if (br > SystemCodecInfo::DEFAULT_MAX_BITRATE) { JAMI_WARNING("Requested bitrate {:d} too high, setting to {:d}", br, SystemCodecInfo::DEFAULT_MAX_BITRATE); br = SystemCodecInfo::DEFAULT_MAX_BITRATE; } } /* Enable libopus FEC encoding support */ if (mediaType == AVMEDIA_TYPE_AUDIO) { if (avcodecId == AV_CODEC_ID_OPUS) { initOpus(encoderCtx); } } /* let x264 preset override our encoder settings */ if (avcodecId == AV_CODEC_ID_H264) { auto profileLevelId = libav_utils::getDictValue(options_, "parameters"); extractProfileLevelID(profileLevelId, encoderCtx); forcePresetX2645(encoderCtx); initH264(encoderCtx, br); } else if (avcodecId == AV_CODEC_ID_HEVC) { encoderCtx->profile = FF_PROFILE_HEVC_MAIN; forcePresetX2645(encoderCtx); initH265(encoderCtx, br); av_opt_set_int(encoderCtx, "b_ref_mode", 0, AV_OPT_SEARCH_CHILDREN); } else if (avcodecId == AV_CODEC_ID_VP8) { initVP8(encoderCtx, br); } else if (avcodecId == AV_CODEC_ID_MPEG4) { initMPEG4(encoderCtx, br); } else if (avcodecId == AV_CODEC_ID_H263) { initH263(encoderCtx, br); } initAccel(encoderCtx, br); return encoderCtx; } int MediaEncoder::setBitrate(uint64_t br) { std::lock_guard lk(encMutex_); AVCodecContext* encoderCtx = getCurrentVideoAVCtx(); if (not encoderCtx) return -1; // NOK AVCodecID codecId = encoderCtx->codec_id; if (not isDynBitrateSupported(codecId)) return 0; // Restart needed // No need to restart encoder for h264, h263 and MPEG4 // Change parameters on the fly if (codecId == AV_CODEC_ID_H264) initH264(encoderCtx, br); if (codecId == AV_CODEC_ID_HEVC) initH265(encoderCtx, br); else if (codecId == AV_CODEC_ID_H263P) initH263(encoderCtx, br); else if (codecId == AV_CODEC_ID_MPEG4) initMPEG4(encoderCtx, br); else { // restart encoder on runtime doesn't work for VP8 // stopEncoder(); // encoderCtx = initCodec(codecType, codecId, br); // if (avcodec_open2(encoderCtx, outputCodec_, &options_) < 0) // throw MediaEncoderException("Unable to open encoder"); } initAccel(encoderCtx, br); return 1; // OK } int MediaEncoder::setPacketLoss(uint64_t pl) { std::lock_guard lk(encMutex_); AVCodecContext* encoderCtx = getCurrentAudioAVCtx(); if (not encoderCtx) return -1; // NOK AVCodecID codecId = encoderCtx->codec_id; if (not isDynPacketLossSupported(codecId)) return 0; // Restart needed // Cap between 0 and 100 pl = std::clamp((int) pl, 0, 100); // Change parameters on the fly if (codecId == AV_CODEC_ID_OPUS) av_opt_set_int(encoderCtx, "packet_loss", (int64_t) pl, AV_OPT_SEARCH_CHILDREN); return 1; // OK } void MediaEncoder::initH264(AVCodecContext* encoderCtx, uint64_t br) { uint64_t maxBitrate = 1000 * br; // 200 Kbit/s -> CRF40 // 6 Mbit/s -> CRF23 uint8_t crf = (uint8_t) std::round(LOGREG_PARAM_A + LOGREG_PARAM_B * std::log(maxBitrate)); // bufsize parameter impact the variation of the bitrate, reduce to half the maxrate to limit // peak and congestion // https://trac.ffmpeg.org/wiki/Limiting%20the%20output%20bitrate uint64_t bufSize = maxBitrate / 2; // If auto quality disabled use CRF mode if (mode_ == RateMode::CRF_CONSTRAINED) { av_opt_set_int(encoderCtx, "crf", crf, AV_OPT_SEARCH_CHILDREN); av_opt_set_int(encoderCtx, "maxrate", maxBitrate, AV_OPT_SEARCH_CHILDREN); av_opt_set_int(encoderCtx, "bufsize", bufSize, AV_OPT_SEARCH_CHILDREN); JAMI_DEBUG("H264 encoder setup: crf={:d}, maxrate={:d} kbit/s, bufsize={:d} kbit", crf, maxBitrate / 1000, bufSize / 1000); } else if (mode_ == RateMode::CBR) { av_opt_set_int(encoderCtx, "b", maxBitrate, AV_OPT_SEARCH_CHILDREN); av_opt_set_int(encoderCtx, "maxrate", maxBitrate, AV_OPT_SEARCH_CHILDREN); av_opt_set_int(encoderCtx, "minrate", maxBitrate, AV_OPT_SEARCH_CHILDREN); av_opt_set_int(encoderCtx, "bufsize", bufSize, AV_OPT_SEARCH_CHILDREN); av_opt_set_int(encoderCtx, "crf", -1, AV_OPT_SEARCH_CHILDREN); JAMI_DEBUG("H264 encoder setup cbr: bitrate={:d} kbit/s", br); } } void MediaEncoder::initH265(AVCodecContext* encoderCtx, uint64_t br) { // If auto quality disabled use CRF mode if (mode_ == RateMode::CRF_CONSTRAINED) { uint64_t maxBitrate = 1000 * br; // H265 use 50% less bitrate compared to H264 (half bitrate is equivalent to a change 6 for // CRF) https://slhck.info/video/2017/02/24/crf-guide.html // 200 Kbit/s -> CRF35 // 6 Mbit/s -> CRF18 uint8_t crf = (uint8_t) std::round(LOGREG_PARAM_A_HEVC + LOGREG_PARAM_B_HEVC * std::log(maxBitrate)); uint64_t bufSize = maxBitrate / 2; av_opt_set_int(encoderCtx, "crf", crf, AV_OPT_SEARCH_CHILDREN); av_opt_set_int(encoderCtx, "maxrate", maxBitrate, AV_OPT_SEARCH_CHILDREN); av_opt_set_int(encoderCtx, "bufsize", bufSize, AV_OPT_SEARCH_CHILDREN); JAMI_DEBUG("H265 encoder setup: crf={:d}, maxrate={:d} kbit/s, bufsize={:d} kbit", crf, maxBitrate / 1000, bufSize / 1000); } else if (mode_ == RateMode::CBR) { av_opt_set_int(encoderCtx, "b", br * 1000, AV_OPT_SEARCH_CHILDREN); av_opt_set_int(encoderCtx, "maxrate", br * 1000, AV_OPT_SEARCH_CHILDREN); av_opt_set_int(encoderCtx, "minrate", br * 1000, AV_OPT_SEARCH_CHILDREN); av_opt_set_int(encoderCtx, "bufsize", br * 500, AV_OPT_SEARCH_CHILDREN); av_opt_set_int(encoderCtx, "crf", -1, AV_OPT_SEARCH_CHILDREN); JAMI_DEBUG("H265 encoder setup cbr: bitrate={:d} kbit/s", br); } } void MediaEncoder::initVP8(AVCodecContext* encoderCtx, uint64_t br) { if (mode_ == RateMode::CQ) { av_opt_set_int(encoderCtx, "g", 120, AV_OPT_SEARCH_CHILDREN); av_opt_set_int(encoderCtx, "lag-in-frames", 0, AV_OPT_SEARCH_CHILDREN); av_opt_set(encoderCtx, "deadline", "good", AV_OPT_SEARCH_CHILDREN); av_opt_set_int(encoderCtx, "cpu-used", 0, AV_OPT_SEARCH_CHILDREN); av_opt_set_int(encoderCtx, "vprofile", 0, AV_OPT_SEARCH_CHILDREN); av_opt_set_int(encoderCtx, "qmax", 23, AV_OPT_SEARCH_CHILDREN); av_opt_set_int(encoderCtx, "qmin", 0, AV_OPT_SEARCH_CHILDREN); av_opt_set_int(encoderCtx, "slices", 4, AV_OPT_SEARCH_CHILDREN); av_opt_set_int(encoderCtx, "crf", 18, AV_OPT_SEARCH_CHILDREN); JAMI_DEBUG("VP8 encoder setup: crf=18"); } else { // 1- if quality is set use it // bitrate need to be set. The target bitrate becomes the maximum allowed bitrate // 2- otherwise set rc_max_rate and rc_buffer_size // Using information given on this page: // http://www.webmproject.org/docs/encoder-parameters/ uint64_t maxBitrate = 1000 * br; // 200 Kbit/s -> CRF40 // 6 Mbit/s -> CRF23 uint8_t crf = (uint8_t) std::round(LOGREG_PARAM_A + LOGREG_PARAM_B * std::log(maxBitrate)); uint64_t bufSize = maxBitrate / 2; av_opt_set(encoderCtx, "quality", "realtime", AV_OPT_SEARCH_CHILDREN); av_opt_set_int(encoderCtx, "error-resilient", 1, AV_OPT_SEARCH_CHILDREN); av_opt_set_int(encoderCtx, "cpu-used", 7, AV_OPT_SEARCH_CHILDREN); // value obtained from testing av_opt_set_int(encoderCtx, "lag-in-frames", 0, AV_OPT_SEARCH_CHILDREN); // allow encoder to drop frames if buffers are full and // to undershoot target bitrate to lessen strain on resources av_opt_set_int(encoderCtx, "drop-frame", 25, AV_OPT_SEARCH_CHILDREN); av_opt_set_int(encoderCtx, "undershoot-pct", 95, AV_OPT_SEARCH_CHILDREN); // don't set encoderCtx->gop_size: let libvpx decide when to insert a keyframe av_opt_set_int(encoderCtx, "slices", 2, AV_OPT_SEARCH_CHILDREN); // VP8E_SET_TOKEN_PARTITIONS av_opt_set_int(encoderCtx, "qmax", 56, AV_OPT_SEARCH_CHILDREN); av_opt_set_int(encoderCtx, "qmin", 4, AV_OPT_SEARCH_CHILDREN); crf = std::clamp((int) crf, 4, 56); av_opt_set_int(encoderCtx, "crf", crf, AV_OPT_SEARCH_CHILDREN); av_opt_set_int(encoderCtx, "b", maxBitrate, AV_OPT_SEARCH_CHILDREN); av_opt_set_int(encoderCtx, "maxrate", maxBitrate, AV_OPT_SEARCH_CHILDREN); av_opt_set_int(encoderCtx, "bufsize", bufSize, AV_OPT_SEARCH_CHILDREN); JAMI_DEBUG("VP8 encoder setup: crf={:d}, maxrate={:d}, bufsize={:d}", crf, maxBitrate / 1000, bufSize / 1000); } } void MediaEncoder::initMPEG4(AVCodecContext* encoderCtx, uint64_t br) { uint64_t maxBitrate = 1000 * br; uint64_t bufSize = maxBitrate / 2; // Use CBR (set bitrate) encoderCtx->rc_buffer_size = bufSize; encoderCtx->bit_rate = encoderCtx->rc_min_rate = encoderCtx->rc_max_rate = maxBitrate; JAMI_DEBUG("MPEG4 encoder setup: maxrate={:d}, bufsize={:d}", maxBitrate, bufSize); } void MediaEncoder::initH263(AVCodecContext* encoderCtx, uint64_t br) { uint64_t maxBitrate = 1000 * br; uint64_t bufSize = maxBitrate / 2; // Use CBR (set bitrate) encoderCtx->rc_buffer_size = bufSize; encoderCtx->bit_rate = encoderCtx->rc_min_rate = encoderCtx->rc_max_rate = maxBitrate; JAMI_DEBUG("H263 encoder setup: maxrate={:d}, bufsize={:d}", maxBitrate, bufSize); } void MediaEncoder::initOpus(AVCodecContext* encoderCtx) { // Enable FEC support by default with 10% packet loss av_opt_set_int(encoderCtx, "fec", fecEnabled_ ? 1 : 0, AV_OPT_SEARCH_CHILDREN); av_opt_set_int(encoderCtx, "packet_loss", 10, AV_OPT_SEARCH_CHILDREN); } void MediaEncoder::initAccel(AVCodecContext* encoderCtx, uint64_t br) { #ifdef RING_ACCEL if (not accel_) return; if (accel_->getName() == "nvenc"sv) { // Use same parameters as software } else if (accel_->getName() == "vaapi"sv) { // Use VBR encoding with bitrate target set to 80% of the maxrate av_opt_set_int(encoderCtx, "crf", -1, AV_OPT_SEARCH_CHILDREN); av_opt_set_int(encoderCtx, "b", br * 1000 * 0.8f, AV_OPT_SEARCH_CHILDREN); } else if (accel_->getName() == "videotoolbox"sv) { av_opt_set_int(encoderCtx, "b", br * 1000 * 0.8f, AV_OPT_SEARCH_CHILDREN); } else if (accel_->getName() == "qsv"sv) { // Use Video Conferencing Mode av_opt_set_int(encoderCtx, "vcm", 1, AV_OPT_SEARCH_CHILDREN); av_opt_set_int(encoderCtx, "b", br * 1000 * 0.8f, AV_OPT_SEARCH_CHILDREN); } #endif } AVCodecContext* MediaEncoder::getCurrentVideoAVCtx() { for (auto it : encoders_) { if (it->codec_type == AVMEDIA_TYPE_VIDEO) return it; } return nullptr; } AVCodecContext* MediaEncoder::getCurrentAudioAVCtx() { for (auto it : encoders_) { if (it->codec_type == AVMEDIA_TYPE_AUDIO) return it; } return nullptr; } void MediaEncoder::stopEncoder() { flush(); for (auto it = encoders_.begin(); it != encoders_.end(); it++) { if ((*it)->codec_type == AVMEDIA_TYPE_VIDEO) { encoders_.erase(it); break; } } AVCodecContext* encoderCtx = getCurrentVideoAVCtx(); avcodec_close(encoderCtx); avcodec_free_context(&encoderCtx); av_free(encoderCtx); } bool MediaEncoder::isDynBitrateSupported(AVCodecID codecid) { #ifdef RING_ACCEL if (accel_) { return accel_->dynBitrate(); } #endif if (codecid != AV_CODEC_ID_VP8) return true; return false; } bool MediaEncoder::isDynPacketLossSupported(AVCodecID codecid) { if (codecid == AV_CODEC_ID_OPUS) return true; return false; } void MediaEncoder::readConfig(AVCodecContext* encoderCtx) { auto path = fileutils::get_config_dir() / "encoder.json"; std::string name = encoderCtx->codec->name; if (std::filesystem::is_regular_file(path)) { JAMI_WARN("encoder.json file found, default settings will be erased"); try { Json::Value root; std::ifstream file(path); file >> root; if (!root.isObject()) { JAMI_ERR() << "Invalid encoder configuration: root is not an object"; return; } const auto& config = root[name]; if (config.isNull()) { JAMI_WARN() << "Encoder '" << name << "' not found in configuration file"; return; } if (!config.isObject()) { JAMI_ERR() << "Invalid encoder configuration: '" << name << "' is not an object"; return; } for (Json::Value::const_iterator it = config.begin(); it != config.end(); ++it) { Json::Value v = *it; if (!it.key().isConvertibleTo(Json::ValueType::stringValue) || !v.isConvertibleTo(Json::ValueType::stringValue)) { JAMI_ERR() << "Invalid configuration for '" << name << "'"; return; } const auto& key = it.key().asString(); const auto& value = v.asString(); int ret = av_opt_set(reinterpret_cast<void*>(encoderCtx), key.c_str(), value.c_str(), AV_OPT_SEARCH_CHILDREN); if (ret < 0) { JAMI_ERR() << "Failed to set option " << key << " in " << name << " context: " << libav_utils::getError(ret) << "\n"; } } } catch (const Json::Exception& e) { JAMI_ERR() << "Failed to load encoder configuration file: " << e.what(); } } } std::string MediaEncoder::testH265Accel() { #ifdef RING_ACCEL if (jami::Manager::instance().videoPreferences.getEncodingAccelerated()) { // Get compatible list of Hardware API auto APIs = video::HardwareAccel::getCompatibleAccel(AV_CODEC_ID_H265, 1280, 720, CODEC_ENCODER); std::unique_ptr<video::HardwareAccel> accel; for (const auto& it : APIs) { accel = std::make_unique<video::HardwareAccel>(it); // save accel // Init codec need accel to init encoderCtx accelerated auto outputCodec = avcodec_find_encoder_by_name(accel->getCodecName().c_str()); AVCodecContext* encoderCtx = avcodec_alloc_context3(outputCodec); encoderCtx->thread_count = std::min(std::thread::hardware_concurrency(), 16u); encoderCtx->width = 1280; encoderCtx->height = 720; AVRational framerate; framerate.num = 30; framerate.den = 1; encoderCtx->time_base = av_inv_q(framerate); encoderCtx->pix_fmt = accel->getFormat(); encoderCtx->profile = FF_PROFILE_HEVC_MAIN; encoderCtx->opaque = accel.get(); auto br = SystemCodecInfo::DEFAULT_VIDEO_BITRATE; av_opt_set_int(encoderCtx, "b", br * 1000, AV_OPT_SEARCH_CHILDREN); av_opt_set_int(encoderCtx, "maxrate", br * 1000, AV_OPT_SEARCH_CHILDREN); av_opt_set_int(encoderCtx, "minrate", br * 1000, AV_OPT_SEARCH_CHILDREN); av_opt_set_int(encoderCtx, "bufsize", br * 500, AV_OPT_SEARCH_CHILDREN); av_opt_set_int(encoderCtx, "crf", -1, AV_OPT_SEARCH_CHILDREN); auto ret = accel->initAPI(false, nullptr); if (ret < 0) { accel.reset(); ; encoderCtx = nullptr; continue; } accel->setDetails(encoderCtx); if (avcodec_open2(encoderCtx, outputCodec, nullptr) < 0) { // Failed to open codec JAMI_WARN("Fail to open hardware encoder H265 with %s ", it.getName().c_str()); avcodec_free_context(&encoderCtx); encoderCtx = nullptr; accel = nullptr; continue; } else { // Succeed to open codec avcodec_free_context(&encoderCtx); encoderCtx = nullptr; accel = nullptr; return it.getName(); } } } #endif return ""; } #ifdef ENABLE_VIDEO int MediaEncoder::getHWFrame(const std::shared_ptr<VideoFrame>& input, std::shared_ptr<VideoFrame>& output) { try { #if defined(TARGET_OS_IOS) && TARGET_OS_IOS // iOS if (accel_) { auto pix = accel_->getSoftwareFormat(); if (input->format() != pix) { output = scaler_.convertFormat(*input.get(), pix); } else { // Fully accelerated pipeline, skip main memory output = input; } } else { output = getScaledSWFrame(*input.get()); } #elif !defined(__APPLE__) && defined(RING_ACCEL) // Other Platforms auto desc = av_pix_fmt_desc_get(static_cast<AVPixelFormat>(input->format())); bool isHardware = desc && (desc->flags & AV_PIX_FMT_FLAG_HWACCEL); if (accel_ && accel_->isLinked() && isHardware) { // Fully accelerated pipeline, skip main memory output = input; } else if (isHardware) { // Hardware decoded frame, transfer back to main memory // Transfer to GPU if we have a hardware encoder // Hardware decoders decode to NV12, but Jami's supported software encoders want YUV420P output = getUnlinkedHWFrame(*input.get()); } else if (accel_) { // Software decoded frame with a hardware encoder, convert to accepted format first output = getHWFrameFromSWFrame(*input.get()); } else { output = getScaledSWFrame(*input.get()); } #else // macOS output = getScaledSWFrame(*input.get()); #endif } catch (const std::runtime_error& e) { JAMI_ERR("Accel failure: %s", e.what()); return -1; } return 0; } #ifdef RING_ACCEL std::shared_ptr<VideoFrame> MediaEncoder::getUnlinkedHWFrame(const VideoFrame& input) { AVPixelFormat pix = (accel_ ? accel_->getSoftwareFormat() : AV_PIX_FMT_NV12); std::shared_ptr<VideoFrame> framePtr = video::HardwareAccel::transferToMainMemory(input, pix); if (!accel_) { framePtr = scaler_.convertFormat(*framePtr, AV_PIX_FMT_YUV420P); } else { framePtr = accel_->transfer(*framePtr); } return framePtr; } std::shared_ptr<VideoFrame> MediaEncoder::getHWFrameFromSWFrame(const VideoFrame& input) { std::shared_ptr<VideoFrame> framePtr; auto pix = accel_->getSoftwareFormat(); if (input.format() != pix) { framePtr = scaler_.convertFormat(input, pix); framePtr = accel_->transfer(*framePtr); } else { framePtr = accel_->transfer(input); } return framePtr; } #endif std::shared_ptr<VideoFrame> MediaEncoder::getScaledSWFrame(const VideoFrame& input) { libav_utils::fillWithBlack(scaledFrame_->pointer()); scaler_.scale_with_aspect(input, *scaledFrame_); return scaledFrame_; } #endif void MediaEncoder::resetStreams(int width, int height) { videoOpts_.width = width; videoOpts_.height = height; try { flush(); initialized_ = false; if (outputCtx_) { for (auto encoderCtx : encoders_) { if (encoderCtx) { #ifndef _MSC_VER avcodec_free_context(&encoderCtx); #else avcodec_close(encoderCtx); #endif } } encoders_.clear(); } } catch (...) { } } } // namespace jami
48,040
C++
.cpp
1,234
30.735818
137
0.602438
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,730
localrecorder.cpp
savoirfairelinux_jami-daemon/src/media/localrecorder.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "localrecorder.h" #include "audio/ringbufferpool.h" #include "audio/ringbuffer.h" #include "client/videomanager.h" #include "media_stream.h" #include "manager.h" #include "logger.h" #include "client/videomanager.h" namespace jami { LocalRecorder::LocalRecorder(const std::string& inputUri) { inputUri_ = inputUri; isAudioOnly_ = inputUri_.empty(); recorder_->audioOnly(isAudioOnly_); } LocalRecorder::~LocalRecorder() { if (isRecording()) stopRecording(); } void LocalRecorder::setPath(const std::string& path) { if (isRecording()) { JAMI_ERR("Unable to set path while recording"); return; } recorder_->setPath(path); path_ = path; } bool LocalRecorder::startRecording() { if (isRecording()) { JAMI_ERR("Recording already started!"); return false; } if (path_.empty()) { JAMI_ERR("Unable to start recording (path not set)"); return false; } if (!recorder_) { JAMI_ERR("Unable to start recording (no recorder)"); return false; } // audio recording // create read offset in RingBuffer Manager::instance().getRingBufferPool().bindHalfDuplexOut(path_, RingBufferPool::DEFAULT_ID); audioInput_ = getAudioInput(path_); audioInput_->setFormat(AudioFormat::STEREO()); audioInput_->attach(recorder_->addStream(audioInput_->getInfo())); audioInput_->switchInput(""); #ifdef ENABLE_VIDEO // video recording if (!isAudioOnly_) { videoInput_ = std::static_pointer_cast<video::VideoInput>(getVideoInput(inputUri_)); if (videoInput_) { videoInput_->attach(recorder_->addStream(videoInput_->getInfo())); } else { JAMI_ERR() << "Unable to record video (no video input)"; return false; } } #endif return Recordable::startRecording(path_); } void LocalRecorder::stopRecording() { if (auto ob = recorder_->getStream(audioInput_->getInfo().name)) audioInput_->detach(ob); #ifdef ENABLE_VIDEO if (videoInput_) if (auto ob = recorder_->getStream(videoInput_->getInfo().name)) videoInput_->detach(ob); #endif Manager::instance().getRingBufferPool().unBindHalfDuplexOut(path_, RingBufferPool::DEFAULT_ID); // NOTE stopRecording should be last call to avoid data races Recordable::stopRecording(); } } // namespace jami
3,123
C++
.cpp
97
27.917526
99
0.68914
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,731
recordable.cpp
savoirfairelinux_jami-daemon/src/media/recordable.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "audio/ringbufferpool.h" #include "fileutils.h" #include "logger.h" #include "manager.h" #include "recordable.h" #include <iomanip> namespace jami { Recordable::Recordable() : recorder_(std::make_shared<MediaRecorder>()) {} Recordable::~Recordable() {} std::string Recordable::getPath() const { if (recorder_) return recorder_->getPath(); else return ""; } bool Recordable::toggleRecording() { if (!recorder_) { JAMI_ERR("Unable to toggle recording, non existent recorder"); return false; } if (!recording_) { const auto& audioPath = Manager::instance().audioPreference.getRecordPath(); auto dir = audioPath.empty() ? fileutils::get_home_dir() : std::filesystem::path(audioPath); dhtnet::fileutils::check_dir(dir); auto timeStamp = fmt::format("{:%Y%m%d-%H%M%S}", std::chrono::system_clock::now()); startRecording((dir / timeStamp).string()); } else { stopRecording(); } return recording_; } bool Recordable::startRecording(const std::string& path) { std::lock_guard lk {apiMutex_}; if (!recorder_) { JAMI_ERR("Unable to start recording, non existent recorder"); return false; } if (!recording_) { if (path.empty()) { JAMI_ERR("Unable to start recording, path is empty"); return false; } recorder_->audioOnly(isAudioOnly_); recorder_->setPath(path); recorder_->startRecording(); recording_ = recorder_->isRecording(); } return recording_; } void Recordable::stopRecording() { std::lock_guard lk {apiMutex_}; if (!recorder_) { JAMI_WARN("Unable to stop recording, non existent recorder"); return; } if (not recording_) { JAMI_WARN("Unable to stop non-running recording"); return; } recorder_->stopRecording(); recording_ = false; } bool Recordable::isAudioOnly() const { return isAudioOnly_; } } // namespace jami
2,745
C++
.cpp
94
24.787234
100
0.666287
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,732
media_recorder.cpp
savoirfairelinux_jami-daemon/src/media/media_recorder.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "libav_deps.h" // MUST BE INCLUDED FIRST #include "client/ring_signal.h" #include "fileutils.h" #include "logger.h" #include "manager.h" #include "media_io_handle.h" #include "media_recorder.h" #include "system_codec_container.h" #include "video/filter_transpose.h" #ifdef ENABLE_VIDEO #ifdef RING_ACCEL #include "video/accel.h" #endif #endif #include <opendht/thread_pool.h> #include <algorithm> #include <iomanip> #include <sstream> #include <sys/types.h> #include <ctime> namespace jami { const constexpr char ROTATION_FILTER_INPUT_NAME[] = "in"; // Replaces every occurrence of @from with @to in @str static std::string replaceAll(const std::string& str, const std::string& from, const std::string& to) { if (from.empty()) return str; std::string copy(str); size_t startPos = 0; while ((startPos = str.find(from, startPos)) != std::string::npos) { copy.replace(startPos, from.length(), to); startPos += to.length(); } return copy; } struct MediaRecorder::StreamObserver : public Observer<std::shared_ptr<MediaFrame>> { const MediaStream info; StreamObserver(const MediaStream& ms, std::function<void(const std::shared_ptr<MediaFrame>&)> func) : info(ms) , cb_(func) {}; ~StreamObserver() { while (observablesFrames_.size() > 0) { auto obs = observablesFrames_.begin(); (*obs)->detach(this); // it should be erased from observablesFrames_ in detach. If it does not happens erase frame to avoid infinite loop. auto it = observablesFrames_.find(*obs); if (it != observablesFrames_.end()) observablesFrames_.erase(it); } }; void update(Observable<std::shared_ptr<MediaFrame>>* /*ob*/, const std::shared_ptr<MediaFrame>& m) override { if (not isEnabled) return; #ifdef ENABLE_VIDEO if (info.isVideo) { std::shared_ptr<VideoFrame> framePtr; #ifdef RING_ACCEL auto desc = av_pix_fmt_desc_get( (AVPixelFormat) (std::static_pointer_cast<VideoFrame>(m))->format()); if (desc && (desc->flags & AV_PIX_FMT_FLAG_HWACCEL)) { try { framePtr = jami::video::HardwareAccel::transferToMainMemory( *std::static_pointer_cast<VideoFrame>(m), AV_PIX_FMT_NV12); } catch (const std::runtime_error& e) { JAMI_ERR("Accel failure: %s", e.what()); return; } } else #endif framePtr = std::static_pointer_cast<VideoFrame>(m); int angle = framePtr->getOrientation(); if (angle != rotation_) { videoRotationFilter_ = jami::video::getTransposeFilter(angle, ROTATION_FILTER_INPUT_NAME, framePtr->width(), framePtr->height(), framePtr->format(), true); rotation_ = angle; } if (videoRotationFilter_) { videoRotationFilter_->feedInput(framePtr->pointer(), ROTATION_FILTER_INPUT_NAME); auto rotated = videoRotationFilter_->readOutput(); av_frame_remove_side_data(rotated->pointer(), AV_FRAME_DATA_DISPLAYMATRIX); cb_(std::move(rotated)); } else { cb_(m); } } else { #endif cb_(m); #ifdef ENABLE_VIDEO } #endif } void attached(Observable<std::shared_ptr<MediaFrame>>* obs) override { observablesFrames_.insert(obs); } void detached(Observable<std::shared_ptr<MediaFrame>>* obs) override { auto it = observablesFrames_.find(obs); if (it != observablesFrames_.end()) observablesFrames_.erase(it); } bool isEnabled = false; private: std::function<void(const std::shared_ptr<MediaFrame>&)> cb_; std::unique_ptr<MediaFilter> videoRotationFilter_ {}; int rotation_ = 0; std::set<Observable<std::shared_ptr<MediaFrame>>*> observablesFrames_; }; MediaRecorder::MediaRecorder() {} MediaRecorder::~MediaRecorder() { flush(); reset(); } bool MediaRecorder::isRecording() const { return isRecording_; } std::string MediaRecorder::getPath() const { if (audioOnly_) return path_ + ".ogg"; else return path_ + ".webm"; } void MediaRecorder::audioOnly(bool audioOnly) { audioOnly_ = audioOnly; } void MediaRecorder::setPath(const std::string& path) { path_ = path; } void MediaRecorder::setMetadata(const std::string& title, const std::string& desc) { title_ = title; description_ = desc; } int MediaRecorder::startRecording() { std::time_t t = std::time(nullptr); startTime_ = *std::localtime(&t); startTimeStamp_ = av_gettime(); std::lock_guard lk(encoderMtx_); encoder_.reset(new MediaEncoder); JAMI_LOG("Start recording '{}'", getPath()); if (initRecord() >= 0) { isRecording_ = true; { std::lock_guard lk(mutexStreamSetup_); for (auto& media : streams_) { if (media.second->info.isVideo) { std::lock_guard lk2(mutexFilterVideo_); setupVideoOutput(); } else { std::lock_guard lk2(mutexFilterAudio_); setupAudioOutput(); } media.second->isEnabled = true; } } // start thread after isRecording_ is set to true dht::ThreadPool::computation().run([rec = shared_from_this()] { std::lock_guard lk(rec->encoderMtx_); while (rec->isRecording()) { std::shared_ptr<MediaFrame> frame; // get frame from queue { std::unique_lock lk(rec->mutexFrameBuff_); rec->cv_.wait(lk, [rec] { return rec->interrupted_ or not rec->frameBuff_.empty(); }); if (rec->interrupted_) { break; } frame = std::move(rec->frameBuff_.front()); rec->frameBuff_.pop_front(); } try { // encode frame if (rec->encoder_ && frame && frame->pointer()) { #ifdef ENABLE_VIDEO bool isVideo = (frame->pointer()->width > 0 && frame->pointer()->height > 0); rec->encoder_->encode(frame->pointer(), isVideo ? rec->videoIdx_ : rec->audioIdx_); #else rec->encoder_->encode(frame->pointer(), rec->audioIdx_); #endif // ENABLE_VIDEO } } catch (const MediaEncoderException& e) { JAMI_ERR() << "Failed to record frame: " << e.what(); } } rec->flush(); rec->reset(); // allows recorder to be reused in same call }); } interrupted_ = false; return 0; } void MediaRecorder::stopRecording() { interrupted_ = true; cv_.notify_all(); if (isRecording_) { JAMI_DBG() << "Stop recording '" << getPath() << "'"; isRecording_ = false; { std::lock_guard lk(mutexStreamSetup_); for (auto& media : streams_) { media.second->isEnabled = false; } } emitSignal<libjami::CallSignal::RecordPlaybackStopped>(getPath()); } } Observer<std::shared_ptr<MediaFrame>>* MediaRecorder::addStream(const MediaStream& ms) { std::lock_guard lk(mutexStreamSetup_); if (audioOnly_ && ms.isVideo) { JAMI_ERR() << "Attempting to add video stream to audio only recording"; return nullptr; } if (ms.format < 0 || ms.name.empty()) { JAMI_ERR() << "Attempting to add invalid stream to recording"; return nullptr; } auto it = streams_.find(ms.name); if (it == streams_.end()) { auto streamPtr = std::make_unique<StreamObserver>(ms, [this, ms](const std::shared_ptr<MediaFrame>& frame) { onFrame(ms.name, frame); }); it = streams_.insert(std::make_pair(ms.name, std::move(streamPtr))).first; JAMI_LOG("[Recorder: {:p}] Recorder input #{}: {:s}", fmt::ptr(this), streams_.size(), ms.name); } else { if (ms == it->second->info) JAMI_LOG("[Recorder: {:p}] Recorder already has '{:s}' as input", fmt::ptr(this), ms.name); else { it->second = std::make_unique<StreamObserver>(ms, [this, ms](const std::shared_ptr<MediaFrame>& frame) { onFrame(ms.name, frame); }); } } it->second->isEnabled = isRecording_; return it->second.get(); } void MediaRecorder::removeStream(const MediaStream& ms) { std::lock_guard lk(mutexStreamSetup_); auto it = streams_.find(ms.name); if (it == streams_.end()) { JAMI_LOG("[Recorder: {:p}] Recorder no stream to remove", fmt::ptr(this)); } else { JAMI_LOG("[Recorder: {:p}] Recorder removing '{:s}'", fmt::ptr(this), ms.name); streams_.erase(it); if (ms.isVideo) setupVideoOutput(); else setupAudioOutput(); } return; } Observer<std::shared_ptr<MediaFrame>>* MediaRecorder::getStream(const std::string& name) const { const auto it = streams_.find(name); if (it != streams_.cend()) return it->second.get(); return nullptr; } void MediaRecorder::onFrame(const std::string& name, const std::shared_ptr<MediaFrame>& frame) { if (not isRecording_ || interrupted_) return; std::lock_guard lk(mutexStreamSetup_); // copy frame to not mess with the original frame's pts (does not actually copy frame data) std::unique_ptr<MediaFrame> clone; const auto& ms = streams_[name]->info; #if defined(ENABLE_VIDEO) && defined(RING_ACCEL) if (ms.isVideo) { auto desc = av_pix_fmt_desc_get( (AVPixelFormat) (std::static_pointer_cast<VideoFrame>(frame))->format()); if (desc && (desc->flags & AV_PIX_FMT_FLAG_HWACCEL)) { try { clone = video::HardwareAccel::transferToMainMemory( *std::static_pointer_cast<VideoFrame>(frame), static_cast<AVPixelFormat>(ms.format)); } catch (const std::runtime_error& e) { JAMI_ERR("Accel failure: %s", e.what()); return; } } else { clone = std::make_unique<MediaFrame>(); clone->copyFrom(*frame); } } else { #endif // ENABLE_VIDEO && RING_ACCEL clone = std::make_unique<MediaFrame>(); clone->copyFrom(*frame); #if defined(ENABLE_VIDEO) && defined(RING_ACCEL) } #endif // ENABLE_VIDEO && RING_ACCEL clone->pointer()->pts = av_rescale_q_rnd(av_gettime() - startTimeStamp_, {1, AV_TIME_BASE}, ms.timeBase, static_cast<AVRounding>(AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX)); std::vector<std::unique_ptr<MediaFrame>> filteredFrames; #ifdef ENABLE_VIDEO if (ms.isVideo && videoFilter_ && outputVideoFilter_) { std::lock_guard lk(mutexFilterVideo_); videoFilter_->feedInput(clone->pointer(), name); auto videoFilterOutput = videoFilter_->readOutput(); if (videoFilterOutput) { outputVideoFilter_->feedInput(videoFilterOutput->pointer(), "input"); while (auto fFrame = outputVideoFilter_->readOutput()) { filteredFrames.emplace_back(std::move(fFrame)); } } } else if (audioFilter_ && outputAudioFilter_) { #endif // ENABLE_VIDEO std::lock_guard lkA(mutexFilterAudio_); audioFilter_->feedInput(clone->pointer(), name); auto audioFilterOutput = audioFilter_->readOutput(); if (audioFilterOutput) { outputAudioFilter_->feedInput(audioFilterOutput->pointer(), "input"); filteredFrames.emplace_back(outputAudioFilter_->readOutput()); } #ifdef ENABLE_VIDEO } #endif // ENABLE_VIDEO for (auto& fFrame : filteredFrames) { std::lock_guard lk(mutexFrameBuff_); frameBuff_.emplace_back(std::move(fFrame)); cv_.notify_one(); } } int MediaRecorder::initRecord() { // need to get encoder parameters before calling openFileOutput // openFileOutput needs to be called before adding any streams std::stringstream timestampString; timestampString << std::put_time(&startTime_, "%Y-%m-%d %H:%M:%S"); if (title_.empty()) { title_ = "Conversation at %TIMESTAMP"; } title_ = replaceAll(title_, "%TIMESTAMP", timestampString.str()); if (description_.empty()) { description_ = "Recorded with Jami https://jami.net"; } description_ = replaceAll(description_, "%TIMESTAMP", timestampString.str()); encoder_->setMetadata(title_, description_); encoder_->openOutput(getPath()); #ifdef ENABLE_VIDEO #ifdef RING_ACCEL encoder_->enableAccel(false); // TODO recorder has problems with hardware encoding #endif #endif // ENABLE_VIDEO { MediaStream audioStream; audioStream.name = "audioOutput"; audioStream.format = 1; audioStream.timeBase = rational<int>(1, 48000); audioStream.sampleRate = 48000; audioStream.nbChannels = 2; encoder_->setOptions(audioStream); auto audioCodec = std::static_pointer_cast<jami::SystemAudioCodecInfo>( getSystemCodecContainer()->searchCodecByName("opus", jami::MEDIA_AUDIO)); audioIdx_ = encoder_->addStream(*audioCodec.get()); if (audioIdx_ < 0) { JAMI_ERR() << "Failed to add audio stream to encoder"; return -1; } } #ifdef ENABLE_VIDEO if (!audioOnly_) { MediaStream videoStream; videoStream.name = "videoOutput"; videoStream.format = 0; videoStream.isVideo = true; videoStream.timeBase = rational<int>(0, 1); videoStream.width = 1280; videoStream.height = 720; videoStream.frameRate = rational<int>(30, 1); videoStream.bitrate = Manager::instance().videoPreferences.getRecordQuality(); MediaDescription args; args.mode = RateMode::CQ; encoder_->setOptions(videoStream); encoder_->setOptions(args); auto videoCodec = std::static_pointer_cast<jami::SystemVideoCodecInfo>( getSystemCodecContainer()->searchCodecByName("VP8", jami::MEDIA_VIDEO)); videoIdx_ = encoder_->addStream(*videoCodec.get()); if (videoIdx_ < 0) { JAMI_ERR() << "Failed to add video stream to encoder"; return -1; } } #endif // ENABLE_VIDEO encoder_->setIOContext(nullptr); JAMI_DBG() << "Recording initialized"; return 0; } void MediaRecorder::setupVideoOutput() { MediaStream encoderStream, peer, local, mixer; auto it = std::find_if(streams_.begin(), streams_.end(), [](const auto& pair) { return pair.second->info.isVideo && pair.second->info.name.find("remote") != std::string::npos; }); if (it != streams_.end()) peer = it->second->info; it = std::find_if(streams_.begin(), streams_.end(), [](const auto& pair) { return pair.second->info.isVideo && pair.second->info.name.find("local") != std::string::npos; }); if (it != streams_.end()) local = it->second->info; it = std::find_if(streams_.begin(), streams_.end(), [](const auto& pair) { return pair.second->info.isVideo && pair.second->info.name.find("mixer") != std::string::npos; }); if (it != streams_.end()) mixer = it->second->info; // vp8 supports only yuv420p videoFilter_.reset(new MediaFilter); int ret = -1; int streams = peer.isValid() + local.isValid() + mixer.isValid(); switch (streams) { case 0: { JAMI_WARN() << "Attempting to record a video stream but none is valid"; return; } case 1: { MediaStream inputStream; if (peer.isValid()) inputStream = peer; else if (local.isValid()) inputStream = local; else if (mixer.isValid()) inputStream = mixer; else { JAMI_ERR("Attempting to record a stream but none is valid"); break; } ret = videoFilter_->initialize(buildVideoFilter({}, inputStream), {inputStream}); break; } case 2: // overlay local video over peer video ret = videoFilter_->initialize(buildVideoFilter({peer}, local), {peer, local}); break; default: JAMI_ERR() << "Recording more than 2 video streams is not supported"; break; } #ifdef ENABLE_VIDEO if (ret < 0) { JAMI_ERR() << "Failed to initialize video filter"; } // setup output filter if (!videoFilter_) return; MediaStream secondaryFilter = videoFilter_->getOutputParams(); secondaryFilter.name = "input"; if (outputVideoFilter_) { outputVideoFilter_->flush(); outputVideoFilter_.reset(); } outputVideoFilter_.reset(new MediaFilter); float scaledHeight = 1280 * (float)secondaryFilter.height / (float)secondaryFilter.width; std::string scaleFilter = "scale=1280:-2"; if (scaledHeight > 720) scaleFilter += ",scale=-2:720"; std::ostringstream f; f << "[input]" << scaleFilter << ",pad=1280:720:(ow-iw)/2:(oh-ih)/2,format=pix_fmts=yuv420p,fps=30"; ret = outputVideoFilter_->initialize(f.str(), {secondaryFilter}); if (ret < 0) { JAMI_ERR() << "Failed to initialize output video filter"; } #endif return; } std::string MediaRecorder::buildVideoFilter(const std::vector<MediaStream>& peers, const MediaStream& local) const { std::ostringstream v; switch (peers.size()) { case 0: v << "[" << local.name << "] fps=30, format=pix_fmts=yuv420p"; break; case 1: { auto p = peers[0]; const constexpr int minHeight = 720; const bool needScale = (p.height < minHeight); const int newHeight = (needScale ? minHeight : p.height); // NOTE -2 means preserve aspect ratio and have the new number be even if (needScale) v << "[" << p.name << "] fps=30, scale=-2:" << newHeight << " [v:m]; "; else v << "[" << p.name << "] fps=30 [v:m]; "; v << "[" << local.name << "] fps=30, scale=-2:" << newHeight / 5 << " [v:o]; "; v << "[v:m] [v:o] overlay=main_w-overlay_w:main_h-overlay_h" << ", format=pix_fmts=yuv420p"; } break; default: JAMI_ERR() << "Video recordings with more than 2 video streams are not supported"; break; } return v.str(); } void MediaRecorder::setupAudioOutput() { MediaStream encoderStream; // resample to common audio format, so any player can play the file audioFilter_.reset(new MediaFilter); int ret = -1; if (streams_.empty()) { JAMI_WARN() << "Attempting to record a audio stream but none is valid"; return; } std::vector<MediaStream> peers {}; for (const auto& media : streams_) { if (!media.second->info.isVideo && media.second->info.isValid()) peers.emplace_back(media.second->info); } ret = audioFilter_->initialize(buildAudioFilter(peers), peers); if (ret < 0) { JAMI_ERR() << "Failed to initialize audio filter"; return; } // setup output filter if (!audioFilter_) return; MediaStream secondaryFilter = audioFilter_->getOutputParams(); secondaryFilter.name = "input"; if (outputAudioFilter_) { outputAudioFilter_->flush(); outputAudioFilter_.reset(); } outputAudioFilter_.reset(new MediaFilter); ret = outputAudioFilter_->initialize( "[input]aformat=sample_fmts=s16:sample_rates=48000:channel_layouts=stereo", {secondaryFilter}); if (ret < 0) { JAMI_ERR() << "Failed to initialize output audio filter"; } return; } std::string MediaRecorder::buildAudioFilter(const std::vector<MediaStream>& peers) const { std::string baseFilter = "aresample=osr=48000:ochl=stereo:osf=s16"; std::ostringstream a; for (const auto& ms : peers) a << "[" << ms.name << "] "; a << " amix=inputs=" << peers.size() << ", " << baseFilter; return a.str(); } void MediaRecorder::flush() { { std::lock_guard lk(mutexFilterVideo_); if (videoFilter_) videoFilter_->flush(); if (outputVideoFilter_) outputVideoFilter_->flush(); } { std::lock_guard lk(mutexFilterAudio_); if (audioFilter_) audioFilter_->flush(); if (outputAudioFilter_) outputAudioFilter_->flush(); } if (encoder_) encoder_->flush(); } void MediaRecorder::reset() { { std::lock_guard lk(mutexFrameBuff_); frameBuff_.clear(); } videoIdx_ = audioIdx_ = -1; { std::lock_guard lk(mutexStreamSetup_); { std::lock_guard lk2(mutexFilterVideo_); videoFilter_.reset(); outputVideoFilter_.reset(); } { std::lock_guard lk2(mutexFilterAudio_); audioFilter_.reset(); outputAudioFilter_.reset(); } } encoder_.reset(); } } // namespace jami
23,348
C++
.cpp
649
27.007704
128
0.570873
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,733
congestion_control.cpp
savoirfairelinux_jami-daemon/src/media/congestion_control.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "logger.h" #include "media/congestion_control.h" #include <cstdint> #include <utility> #include <cmath> namespace jami { static constexpr uint8_t packetVersion = 2; static constexpr uint8_t packetFMT = 15; static constexpr uint8_t packetType = 206; static constexpr uint32_t uniqueIdentifier = 0x52454D42; // 'R' 'E' 'M' 'B'. static constexpr float Q = 0.5f; static constexpr float beta = 0.95f; static constexpr float ku = 0.004f; static constexpr float kd = 0.002f; constexpr auto OVERUSE_THRESH = std::chrono::milliseconds(100); // Receiver Estimated Max Bitrate (REMB) (draft-alvestrand-rmcat-remb). // // 0 1 2 3 // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // |V=2|P| FMT=15 | PT=206 | length | // +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // 0 | SSRC of packet sender | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // 4 | Unused = 0 | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // 8 | Unique identifier 'R' 'E' 'M' 'B' | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // 12 | Num SSRC | BR Exp | BR Mantissa | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // 16 | SSRC feedback | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // : ... : CongestionControl::CongestionControl() {} CongestionControl::~CongestionControl() {} static void insert2Byte(std::vector<uint8_t>& v, uint16_t val) { v.insert(v.end(), val >> 8); v.insert(v.end(), val & 0xff); } static void insert4Byte(std::vector<uint8_t>& v, uint32_t val) { v.insert(v.end(), val >> 24); v.insert(v.end(), (val >> 16) & 0xff); v.insert(v.end(), (val >> 8) & 0xff); v.insert(v.end(), val & 0xff); } uint64_t CongestionControl::parseREMB(const rtcpREMBHeader& packet) { if (packet.fmt != 15 || packet.pt != 206) { JAMI_ERR("Unable to parse REMB packet."); return 0; } uint64_t bitrate_bps = (packet.br_mantis << packet.br_exp); bool shift_overflow = (bitrate_bps >> packet.br_exp) != packet.br_mantis; if (shift_overflow) { JAMI_ERR("Invalid remb bitrate value : %u*2^%u", packet.br_mantis, packet.br_exp); return false; } return bitrate_bps; } std::vector<uint8_t> CongestionControl::createREMB(uint64_t bitrate_bps) { std::vector<uint8_t> remb; remb.reserve(24); remb.insert(remb.end(), packetVersion << 6 | packetFMT); remb.insert(remb.end(), packetType); insert2Byte(remb, 5); // (sizeof(rtcpREMBHeader)/4)-1 -> not safe insert4Byte(remb, 0x12345678); // ssrc insert4Byte(remb, 0x0); // ssrc source insert4Byte(remb, uniqueIdentifier); // uid remb.insert(remb.end(), 1); // n_ssrc const uint32_t maxMantissa = 0x3ffff; // 18 bits. uint64_t mantissa = bitrate_bps; uint8_t exponenta = 0; while (mantissa > maxMantissa) { mantissa >>= 1; ++exponenta; } remb.insert(remb.end(), (exponenta << 2) | (mantissa >> 16)); insert2Byte(remb, mantissa & 0xffff); insert4Byte(remb, 0x2345678b); return remb; } float CongestionControl::kalmanFilter(uint64_t gradiant_delay) { float var_n = get_var_n(gradiant_delay); float k = get_gain_k(Q, var_n); float m = get_estimate_m(k, gradiant_delay); last_var_p_ = get_sys_var_p(k, Q); last_estimate_m_ = m; last_var_n_ = var_n; return m; } float CongestionControl::get_estimate_m(float k, int d_m) { // JAMI_WARN("[get_estimate_m]k:%f, last_estimate_m_:%f, d_m:%f", k, last_estimate_m_, d_m); // JAMI_WARN("m: %f", ((1-k) * last_estimate_m_) + (k * d_m)); return ((1 - k) * last_estimate_m_) + (k * d_m); } float CongestionControl::get_gain_k(float q, float dev_n) { // JAMI_WARN("k: %f", (last_var_p_ + q) / (last_var_p_ + q + dev_n)); return (last_var_p_ + q) / (last_var_p_ + q + dev_n); } float CongestionControl::get_sys_var_p(float k, float q) { // JAMI_WARN("var_p: %f", ((1-k) * (last_var_p_ + q))); return ((1 - k) * (last_var_p_ + q)); } float CongestionControl::get_var_n(int d_m) { float z = get_residual_z(d_m); // JAMI_WARN("var_n: %f", (beta * last_var_n_) + ((1.0f - beta) * z * z)); return (beta * last_var_n_) + ((1.0f - beta) * z * z); } float CongestionControl::get_residual_z(float d_m) { // JAMI_WARN("z: %f", d_m - last_estimate_m_); return (d_m - last_estimate_m_); } float CongestionControl::update_thresh(float m, int deltaT) { float ky = 0.0f; if (std::fabs(m) < last_thresh_y_) ky = kd; else ky = ku; float res = last_thresh_y_ + ((deltaT * ky) * (std::fabs(m) - last_thresh_y_)); last_thresh_y_ = res; return res; } float CongestionControl::get_thresh() { return last_thresh_y_; } BandwidthUsage CongestionControl::get_bw_state(float estimation, float thresh) { if (estimation > thresh) { // JAMI_WARN("Enter overuse state"); if (not overuse_counter_) { t0_overuse = clock::now(); overuse_counter_++; return bwNormal; } overuse_counter_++; time_point now = clock::now(); auto overuse_timer = now - t0_overuse; if ((overuse_timer >= OVERUSE_THRESH) and (overuse_counter_ > 1)) { overuse_counter_ = 0; last_state_ = bwOverusing; } } else if (estimation < -thresh) { // JAMI_WARN("Enter underuse state"); overuse_counter_ = 0; last_state_ = bwUnderusing; } else { overuse_counter_ = 0; last_state_ = bwNormal; } return last_state_; } } // namespace jami
6,858
C++
.cpp
192
32.020833
96
0.54948
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
751,734
media_attribute.cpp
savoirfairelinux_jami-daemon/src/media/media_attribute.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "media/media_attribute.h" #include "jami/media_const.h" #include "logger.h" #include "string_utils.h" namespace jami { MediaAttribute::MediaAttribute(const libjami::MediaMap& mediaMap, bool secure) { std::pair<bool, MediaType> pairType = getMediaType(mediaMap); if (pairType.first) type_ = pairType.second; std::pair<bool, bool> pairBool; pairBool = getBoolValue(mediaMap, libjami::Media::MediaAttributeKey::MUTED); if (pairBool.first) muted_ = pairBool.second; pairBool = getBoolValue(mediaMap, libjami::Media::MediaAttributeKey::ENABLED); if (pairBool.first) enabled_ = pairBool.second; std::pair<bool, std::string> pairString; pairString = getStringValue(mediaMap, libjami::Media::MediaAttributeKey::SOURCE); if (pairBool.first) sourceUri_ = pairString.second; pairString = getStringValue(mediaMap, libjami::Media::MediaAttributeKey::LABEL); if (pairBool.first) label_ = pairString.second; pairBool = getBoolValue(mediaMap, libjami::Media::MediaAttributeKey::ON_HOLD); if (pairBool.first) onHold_ = pairBool.second; secure_ = secure; } std::vector<MediaAttribute> MediaAttribute::buildMediaAttributesList(const std::vector<libjami::MediaMap>& mediaList, bool secure) { std::vector<MediaAttribute> mediaAttrList; mediaAttrList.reserve(mediaList.size()); for (auto const& mediaMap : mediaList) { mediaAttrList.emplace_back(MediaAttribute(mediaMap, secure)); } return mediaAttrList; } MediaType MediaAttribute::stringToMediaType(const std::string& mediaType) { if (mediaType.compare(libjami::Media::MediaAttributeValue::AUDIO) == 0) return MediaType::MEDIA_AUDIO; if (mediaType.compare(libjami::Media::MediaAttributeValue::VIDEO) == 0) return MediaType::MEDIA_VIDEO; return MediaType::MEDIA_NONE; } std::pair<bool, MediaType> MediaAttribute::getMediaType(const libjami::MediaMap& map) { const auto& iter = map.find(libjami::Media::MediaAttributeKey::MEDIA_TYPE); if (iter == map.end()) { return {false, MediaType::MEDIA_NONE}; } auto type = stringToMediaType(iter->second); if (type == MediaType::MEDIA_NONE) { JAMI_ERR("Invalid value [%s] for a media type key in media map", iter->second.c_str()); return {false, type}; } return {true, type}; } std::pair<bool, bool> MediaAttribute::getBoolValue(const libjami::MediaMap& map, const std::string& key) { const auto& iter = map.find(key); if (iter == map.end()) { return {false, false}; } auto const& value = iter->second; if (value.compare(TRUE_STR) == 0) return {true, true}; if (value.compare(FALSE_STR) == 0) return {true, false}; JAMI_ERR("Invalid value %s for a boolean key", value.c_str()); return {false, false}; } std::pair<bool, std::string> MediaAttribute::getStringValue(const libjami::MediaMap& map, const std::string& key) { const auto& iter = map.find(key); if (iter == map.end()) { return {false, {}}; } return {true, iter->second}; } char const* MediaAttribute::boolToString(bool val) { return val ? TRUE_STR : FALSE_STR; } char const* MediaAttribute::mediaTypeToString(MediaType type) { if (type == MediaType::MEDIA_AUDIO) return libjami::Media::MediaAttributeValue::AUDIO; if (type == MediaType::MEDIA_VIDEO) return libjami::Media::MediaAttributeValue::VIDEO; return nullptr; } bool MediaAttribute::hasMediaType(const std::vector<MediaAttribute>& mediaList, MediaType type) { return mediaList.end() != std::find_if(mediaList.begin(), mediaList.end(), [type](const MediaAttribute& media) { return media.type_ == type; }); } libjami::MediaMap MediaAttribute::toMediaMap(const MediaAttribute& mediaAttr) { libjami::MediaMap mediaMap; mediaMap.emplace(libjami::Media::MediaAttributeKey::MEDIA_TYPE, mediaTypeToString(mediaAttr.type_)); mediaMap.emplace(libjami::Media::MediaAttributeKey::LABEL, mediaAttr.label_); mediaMap.emplace(libjami::Media::MediaAttributeKey::ENABLED, boolToString(mediaAttr.enabled_)); mediaMap.emplace(libjami::Media::MediaAttributeKey::MUTED, boolToString(mediaAttr.muted_)); mediaMap.emplace(libjami::Media::MediaAttributeKey::SOURCE, mediaAttr.sourceUri_); mediaMap.emplace(libjami::Media::MediaAttributeKey::ON_HOLD, boolToString(mediaAttr.onHold_)); return mediaMap; } std::vector<libjami::MediaMap> MediaAttribute::mediaAttributesToMediaMaps(std::vector<MediaAttribute> mediaAttrList) { std::vector<libjami::MediaMap> mediaList; mediaList.reserve(mediaAttrList.size()); for (auto const& media : mediaAttrList) { mediaList.emplace_back(toMediaMap(media)); } return mediaList; } std::string MediaAttribute::toString(bool full) const { std::ostringstream descr; descr << "type " << (type_ == MediaType::MEDIA_AUDIO ? "[AUDIO]" : "[VIDEO]"); descr << " "; descr << "enabled " << (enabled_ ? "[YES]" : "[NO]"); descr << " "; descr << "muted " << (muted_ ? "[YES]" : "[NO]"); descr << " "; descr << "label [" << label_ << "]"; if (full) { descr << " "; descr << "source [" << sourceUri_ << "]"; descr << " "; descr << "secure " << (secure_ ? "[YES]" : "[NO]"); } return descr.str(); } bool MediaAttribute::hasValidVideo() { return type_ == MediaType::MEDIA_VIDEO && enabled_&& !muted_ && !onHold_; } } // namespace jami
6,304
C++
.cpp
172
32.25
102
0.689242
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,735
media_player.cpp
savoirfairelinux_jami-daemon/src/media/media_player.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "media_player.h" #include "client/videomanager.h" #include "client/ring_signal.h" #include "jami/media_const.h" #include "manager.h" #include <string> namespace jami { static constexpr auto MS_PER_PACKET = std::chrono::milliseconds(20); MediaPlayer::MediaPlayer(const std::string& resource) : loop_(std::bind(&MediaPlayer::configureMediaInputs, this), std::bind(&MediaPlayer::process, this), [] {}) { auto suffix = resource; static const std::string& sep = libjami::Media::VideoProtocolPrefix::SEPARATOR; const auto pos = resource.find(sep); if (pos != std::string::npos) { suffix = resource.substr(pos + sep.size()); } path_ = suffix; audioInput_ = jami::getAudioInput(path_); audioInput_->setPaused(paused_); #ifdef ENABLE_VIDEO videoInput_ = jami::getVideoInput(path_, video::VideoInputMode::ManagedByDaemon, resource); videoInput_->setPaused(paused_); #endif demuxer_ = std::make_shared<MediaDemuxer>(); loop_.start(); } MediaPlayer::~MediaPlayer() { pause(true); loop_.join(); audioInput_.reset(); #ifdef ENABLE_VIDEO videoInput_.reset(); #endif } bool MediaPlayer::configureMediaInputs() { DeviceParams devOpts = {}; devOpts.input = path_; devOpts.name = path_; devOpts.loop = "1"; size_t dot = path_.find_last_of('.'); std::string ext = dot == std::string::npos ? "" : path_.substr(dot + 1); bool decodeImg = (ext == "jpeg" || ext == "jpg" || ext == "png" || ext == "pdf"); // Force 1fps for static image if (decodeImg) { devOpts.format = "image2"; devOpts.framerate = 1; } else { JAMI_WARNING("Guessing file type for {}", path_); } if (demuxer_->openInput(devOpts) < 0) { emitInfo(); return false; } demuxer_->findStreamInfo(); pauseInterval_ = 0; startTime_ = av_gettime(); lastPausedTime_ = startTime_; try { audioStream_ = demuxer_->selectStream(AVMEDIA_TYPE_AUDIO); if (hasAudio()) { audioInput_->configureFilePlayback(path_, demuxer_, audioStream_); audioInput_->updateStartTime(startTime_); audioInput_->start(); } } catch (const std::exception& e) { JAMI_ERROR("MediaPlayer {} open audio input failed: {}", path_, e.what()); } #ifdef ENABLE_VIDEO try { videoStream_ = demuxer_->selectStream(AVMEDIA_TYPE_VIDEO); if (hasVideo()) { videoInput_->configureFilePlayback(path_, demuxer_, videoStream_); videoInput_->updateStartTime(startTime_); } } catch (const std::exception& e) { videoInput_ = nullptr; JAMI_ERROR("MediaPlayer {} open video input failed: {}", path_, e.what()); } #endif demuxer_->setNeedFrameCb([this]() -> void { readBufferOverflow_ = false; }); demuxer_->setFileFinishedCb([this](bool isAudio) -> void { if (isAudio) { audioStreamEnded_ = true; } else { videoStreamEnded_ = true; } }); if (decodeImg) { fileDuration_ = 0; } else { fileDuration_ = demuxer_->getDuration(); if (fileDuration_ <= 0) { emitInfo(); return false; } } emitInfo(); demuxer_->updateCurrentState(MediaDemuxer::CurrentState::Demuxing); return true; } void MediaPlayer::process() { if (!demuxer_) return; if (fileDuration_ > 0 && streamsFinished()) { audioStreamEnded_ = false; videoStreamEnded_ = false; playFileFromBeginning(); } if (paused_ || readBufferOverflow_) { std::this_thread::sleep_for(MS_PER_PACKET); return; } const auto ret = demuxer_->demuxe(); switch (ret) { case MediaDemuxer::Status::Success: case MediaDemuxer::Status::FallBack: break; case MediaDemuxer::Status::EndOfFile: demuxer_->updateCurrentState(MediaDemuxer::CurrentState::Finished); break; case MediaDemuxer::Status::ReadError: JAMI_ERROR("Failed to decode frame"); break; case MediaDemuxer::Status::ReadBufferOverflow: readBufferOverflow_ = true; break; case MediaDemuxer::Status::RestartRequired: default: break; } } void MediaPlayer::emitInfo() { std::map<std::string, std::string> info {{"duration", std::to_string(fileDuration_)}, {"audio_stream", std::to_string(audioStream_)}, {"video_stream", std::to_string(videoStream_)}}; emitSignal<libjami::MediaPlayerSignal::FileOpened>(path_, info); } bool MediaPlayer::isInputValid() { return !path_.empty(); } void MediaPlayer::muteAudio(bool mute) { if (hasAudio()) { audioInput_->setMuted(mute); } } void MediaPlayer::pause(bool pause) { if (pause == paused_) { return; } paused_ = pause; if (!pause) { pauseInterval_ += av_gettime() - lastPausedTime_; } else { lastPausedTime_ = av_gettime(); } auto newTime = startTime_ + pauseInterval_; if (hasAudio()) { audioInput_->setPaused(paused_); audioInput_->updateStartTime(newTime); } #ifdef ENABLE_VIDEO if (hasVideo()) { videoInput_->setPaused(paused_); videoInput_->updateStartTime(newTime); } #endif } bool MediaPlayer::seekToTime(int64_t time) { if (time < 0 || time > fileDuration_) { return false; } if (time >= fileDuration_) { playFileFromBeginning(); return true; } if (!demuxer_->seekFrame(-1, time)) { return false; } flushMediaBuffers(); demuxer_->updateCurrentState(MediaDemuxer::CurrentState::Demuxing); int64_t currentTime = av_gettime(); if (paused_){ pauseInterval_ += currentTime - lastPausedTime_; lastPausedTime_ = currentTime; } startTime_ = currentTime - pauseInterval_ - time; if (hasAudio()) { audioInput_->setSeekTime(time); audioInput_->updateStartTime(startTime_); } #ifdef ENABLE_VIDEO if (hasVideo()) { videoInput_->setSeekTime(time); videoInput_->updateStartTime(startTime_); } #endif return true; } void MediaPlayer::playFileFromBeginning() { pause(true); demuxer_->updateCurrentState(MediaDemuxer::CurrentState::Demuxing); if (!demuxer_->seekFrame(-1, 0)) { return; } flushMediaBuffers(); startTime_ = av_gettime(); lastPausedTime_ = startTime_; pauseInterval_ = 0; if (hasAudio()) { audioInput_->updateStartTime(startTime_); } #ifdef ENABLE_VIDEO if (hasVideo()) { videoInput_->updateStartTime(startTime_); } #endif if (autoRestart_) pause(false); } void MediaPlayer::flushMediaBuffers() { #ifdef ENABLE_VIDEO if (hasVideo()) { videoInput_->flushBuffers(); } #endif if (hasAudio()) { audioInput_->flushBuffers(); } } const std::string& MediaPlayer::getId() const { return path_; } int64_t MediaPlayer::getPlayerPosition() const { if (paused_) { return lastPausedTime_ - startTime_ - pauseInterval_; } return av_gettime() - startTime_ - pauseInterval_; } int64_t MediaPlayer::getPlayerDuration() const { return fileDuration_; } bool MediaPlayer::isPaused() const { return paused_; } bool MediaPlayer::streamsFinished() { bool audioFinished = hasAudio() ? audioStreamEnded_ : true; bool videoFinished = hasVideo() ? videoStreamEnded_ : true; return audioFinished && videoFinished; } } // namespace jami
8,378
C++
.cpp
298
22.912752
95
0.637787
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,736
system_codec_container.cpp
savoirfairelinux_jami-daemon/src/media/system_codec_container.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "libav_deps.h" // MUST BE INCLUDED FIRST #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "logger.h" #include "system_codec_container.h" #include "media_encoder.h" #include <sstream> #ifdef APPLE #include <TargetConditionals.h> #endif namespace jami { decltype(getGlobalInstance<SystemCodecContainer>)& getSystemCodecContainer = getGlobalInstance<SystemCodecContainer>; SystemCodecContainer::SystemCodecContainer() { initCodecConfig(); } SystemCodecContainer::~SystemCodecContainer() { // TODO } void SystemCodecContainer::initCodecConfig() { #ifdef ENABLE_VIDEO auto minH264 = SystemCodecInfo::DEFAULT_H264_MIN_QUALITY; auto maxH264 = SystemCodecInfo::DEFAULT_H264_MAX_QUALITY; auto minH265 = SystemCodecInfo::DEFAULT_H264_MIN_QUALITY; auto maxH265 = SystemCodecInfo::DEFAULT_H264_MAX_QUALITY; auto minVP8 = SystemCodecInfo::DEFAULT_VP8_MIN_QUALITY; auto maxVP8 = SystemCodecInfo::DEFAULT_VP8_MAX_QUALITY; auto defaultBitrate = SystemCodecInfo::DEFAULT_VIDEO_BITRATE; #endif availableCodecList_ = { #ifdef ENABLE_VIDEO /* Define supported video codec*/ std::make_shared<SystemVideoCodecInfo>(AV_CODEC_ID_HEVC, AV_CODEC_ID_HEVC, "H.265/HEVC", "H265", "", CODEC_ENCODER_DECODER, defaultBitrate, minH265, maxH265), std::make_shared<SystemVideoCodecInfo>(AV_CODEC_ID_H264, AV_CODEC_ID_H264, "H.264/AVC", "H264", "libx264", CODEC_ENCODER_DECODER, defaultBitrate, minH264, maxH264), std::make_shared<SystemVideoCodecInfo>(AV_CODEC_ID_VP8, AV_CODEC_ID_VP8, "VP8", "VP8", "libvpx", CODEC_ENCODER_DECODER, defaultBitrate, minVP8, maxVP8), #if !(defined(TARGET_OS_IOS) && TARGET_OS_IOS) std::make_shared<SystemVideoCodecInfo>(AV_CODEC_ID_MPEG4, AV_CODEC_ID_MPEG4, "MP4V-ES", "MP4V-ES", "mpeg4", CODEC_ENCODER_DECODER, defaultBitrate), std::make_shared<SystemVideoCodecInfo>(AV_CODEC_ID_H263, AV_CODEC_ID_H263, "H.263", "H263-1998", "h263", CODEC_ENCODER_DECODER, defaultBitrate), #endif #endif /* Define supported audio codec*/ std::make_shared<SystemAudioCodecInfo>(AV_CODEC_ID_OPUS, AV_CODEC_ID_OPUS, "Opus", "opus", "libopus", CODEC_ENCODER_DECODER, 0, 48000, 2, 104, AV_SAMPLE_FMT_FLT), std::make_shared<SystemAudioCodecInfo>(AV_CODEC_ID_ADPCM_G722, AV_CODEC_ID_ADPCM_G722, "G.722", "G722", "g722", CODEC_ENCODER_DECODER, 0, 16000, 1, 9), std::make_shared<SystemAudioCodecInfo>(AV_CODEC_ID_ADPCM_G726, AV_CODEC_ID_ADPCM_G726, "G.726", "G726-32", "g726", CODEC_ENCODER_DECODER, 0, 8000, 1, 2), std::make_shared<SystemAudioCodecInfo>(AV_CODEC_ID_SPEEX | 0x20000000, AV_CODEC_ID_SPEEX, "Speex", "speex", "libspeex", CODEC_ENCODER_DECODER, 0, 32000, 1, 112), std::make_shared<SystemAudioCodecInfo>(AV_CODEC_ID_SPEEX | 0x10000000, AV_CODEC_ID_SPEEX, "Speex", "speex", "libspeex", CODEC_ENCODER_DECODER, 0, 16000, 1, 111), std::make_shared<SystemAudioCodecInfo>(AV_CODEC_ID_SPEEX, AV_CODEC_ID_SPEEX, "Speex", "speex", "libspeex", CODEC_ENCODER_DECODER, 0, 8000, 1, 110), std::make_shared<SystemAudioCodecInfo>(AV_CODEC_ID_PCM_ALAW, AV_CODEC_ID_PCM_ALAW, "G.711a", "PCMA", "pcm_alaw", CODEC_ENCODER_DECODER, 64, 8000, 1, 8), std::make_shared<SystemAudioCodecInfo>(AV_CODEC_ID_PCM_MULAW, AV_CODEC_ID_PCM_MULAW, "G.711u", "PCMU", "pcm_mulaw", CODEC_ENCODER_DECODER, 64, 8000, 1, 0), }; setActiveH265(); checkInstalledCodecs(); } bool SystemCodecContainer::setActiveH265() { #if (defined(TARGET_OS_IOS) && TARGET_OS_IOS) removeCodecByName("H265"); return false; #endif auto apiName = MediaEncoder::testH265Accel(); if (apiName != "") { JAMI_WARN("Found a usable accelerated H265/HEVC codec: %s, enabling.", apiName.c_str()); return true; } else { JAMI_ERR("Unable to find a usable accelerated H265/HEVC codec, disabling."); removeCodecByName("H265"); } return false; } void SystemCodecContainer::checkInstalledCodecs() { std::ostringstream enc_ss; std::ostringstream dec_ss; for (const auto& codecIt : availableCodecList_) { AVCodecID codecId = (AVCodecID) codecIt->avcodecId; CodecType codecType = codecIt->codecType; if (codecType & CODEC_ENCODER) { if (avcodec_find_encoder(codecId) != nullptr) enc_ss << codecIt->name << ' '; else codecIt->codecType = (CodecType)((unsigned) codecType & ~CODEC_ENCODER); } if (codecType & CODEC_DECODER) { if (avcodec_find_decoder(codecId) != nullptr) dec_ss << codecIt->name << ' '; else codecIt->codecType = (CodecType)((unsigned) codecType & ~CODEC_DECODER); } } JAMI_INFO("Encoders found: %s", enc_ss.str().c_str()); JAMI_INFO("Decoders found: %s", dec_ss.str().c_str()); } std::vector<std::shared_ptr<SystemCodecInfo>> SystemCodecContainer::getSystemCodecInfoList(MediaType mediaType) { if (mediaType & MEDIA_ALL) return availableCodecList_; // otherwise we have to instantiate a new list containing filtered objects // must be destroyed by the caller... std::vector<std::shared_ptr<SystemCodecInfo>> systemCodecList; for (const auto& codecIt : availableCodecList_) { if (codecIt->mediaType & mediaType) systemCodecList.push_back(codecIt); } return systemCodecList; } std::vector<unsigned> SystemCodecContainer::getSystemCodecInfoIdList(MediaType mediaType) { std::vector<unsigned> idList; for (const auto& codecIt : availableCodecList_) { if (codecIt->mediaType & mediaType) idList.push_back(codecIt->id); } return idList; } std::shared_ptr<SystemCodecInfo> SystemCodecContainer::searchCodecById(unsigned codecId, MediaType mediaType) { for (const auto& codecIt : availableCodecList_) { if ((codecIt->id == codecId) && (codecIt->mediaType & mediaType)) return codecIt; } return {}; } std::shared_ptr<SystemCodecInfo> SystemCodecContainer::searchCodecByName(const std::string& name, MediaType mediaType) { for (const auto& codecIt : availableCodecList_) { if (codecIt->name == name && (codecIt->mediaType & mediaType)) return codecIt; } return {}; } std::shared_ptr<SystemCodecInfo> SystemCodecContainer::searchCodecByPayload(unsigned payload, MediaType mediaType) { for (const auto& codecIt : availableCodecList_) { if ((codecIt->payloadType == payload) && (codecIt->mediaType & mediaType)) return codecIt; } return {}; } void SystemCodecContainer::removeCodecByName(const std::string& name, MediaType mediaType) { for (auto codecIt = availableCodecList_.begin(); codecIt != availableCodecList_.end(); ++codecIt) { if ((*codecIt)->mediaType & mediaType and (*codecIt)->name == name) { availableCodecList_.erase(codecIt); break; } } } } // namespace jami
12,835
C++
.cpp
287
23.393728
96
0.417832
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,737
socket_pair.cpp
savoirfairelinux_jami-daemon/src/media/socket_pair.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * Copyright (c) 2007 The FFmpeg Project * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <dhtnet/ip_utils.h> // MUST BE INCLUDED FIRST #include "libav_deps.h" // THEN THIS ONE AFTER #include "socket_pair.h" #include "libav_utils.h" #include "logger.h" #include "connectivity/security/memory.h" #include <dhtnet/ice_socket.h> #include <iostream> #include <string> #include <algorithm> #include <iterator> extern "C" { #include "srtp.h" } #include <cstring> #include <stdexcept> #include <unistd.h> #include <sys/types.h> #include <ciso646> // fix windows compiler bug #ifdef _WIN32 #define SOCK_NONBLOCK FIONBIO #define poll WSAPoll #define close(x) closesocket(x) #endif #ifdef __ANDROID__ #include <asm-generic/fcntl.h> #define SOCK_NONBLOCK O_NONBLOCK #endif #ifdef __APPLE__ #include <fcntl.h> #endif // Swap 2 byte, 16 bit values: #define Swap2Bytes(val) ((((val) >> 8) & 0x00FF) | (((val) << 8) & 0xFF00)) // Swap 4 byte, 32 bit values: #define Swap4Bytes(val) \ ((((val) >> 24) & 0x000000FF) | (((val) >> 8) & 0x0000FF00) | (((val) << 8) & 0x00FF0000) \ | (((val) << 24) & 0xFF000000)) // Swap 8 byte, 64 bit values: #define Swap8Bytes(val) \ ((((val) >> 56) & 0x00000000000000FF) | (((val) >> 40) & 0x000000000000FF00) \ | (((val) >> 24) & 0x0000000000FF0000) | (((val) >> 8) & 0x00000000FF000000) \ | (((val) << 8) & 0x000000FF00000000) | (((val) << 24) & 0x0000FF0000000000) \ | (((val) << 40) & 0x00FF000000000000) | (((val) << 56) & 0xFF00000000000000)) namespace jami { static constexpr int NET_POLL_TIMEOUT = 100; /* poll() timeout in ms */ static constexpr int RTP_MAX_PACKET_LENGTH = 2048; static constexpr auto UDP_HEADER_SIZE = 8; static constexpr auto SRTP_OVERHEAD = 10; static constexpr uint32_t RTCP_RR_FRACTION_MASK = 0xFF000000; static constexpr unsigned MINIMUM_RTP_HEADER_SIZE = 16; enum class DataType : unsigned { RTP = 1 << 0, RTCP = 1 << 1 }; class SRTPProtoContext { public: SRTPProtoContext(const char* out_suite, const char* out_key, const char* in_suite, const char* in_key) { ring_secure_memzero(&srtp_out, sizeof(srtp_out)); ring_secure_memzero(&srtp_in, sizeof(srtp_in)); if (out_suite && out_key) { // XXX: see srtp_open from libavformat/srtpproto.c if (ff_srtp_set_crypto(&srtp_out, out_suite, out_key) < 0) { srtp_close(); throw std::runtime_error("Unable to set crypto on output"); } } if (in_suite && in_key) { if (ff_srtp_set_crypto(&srtp_in, in_suite, in_key) < 0) { srtp_close(); throw std::runtime_error("Unable to set crypto on input"); } } } ~SRTPProtoContext() { srtp_close(); } SRTPContext srtp_out {}; SRTPContext srtp_in {}; uint8_t encryptbuf[RTP_MAX_PACKET_LENGTH]; private: void srtp_close() noexcept { ff_srtp_free(&srtp_out); ff_srtp_free(&srtp_in); } }; static int ff_network_wait_fd(int fd) { struct pollfd p = {fd, POLLOUT, 0}; auto ret = poll(&p, 1, NET_POLL_TIMEOUT); return ret < 0 ? errno : p.revents & (POLLOUT | POLLERR | POLLHUP) ? 0 : -EAGAIN; } static int udp_socket_create(int family, int port) { int udp_fd = -1; #ifdef __APPLE__ udp_fd = socket(family, SOCK_DGRAM, 0); if (udp_fd >= 0 && fcntl(udp_fd, F_SETFL, O_NONBLOCK) < 0) { close(udp_fd); udp_fd = -1; } #elif defined _WIN32 udp_fd = socket(family, SOCK_DGRAM, 0); u_long block = 1; if (udp_fd >= 0 && ioctlsocket(udp_fd, FIONBIO, &block) < 0) { close(udp_fd); udp_fd = -1; } #else udp_fd = socket(family, SOCK_DGRAM | SOCK_NONBLOCK, 0); #endif if (udp_fd < 0) { JAMI_ERR("socket() failed"); strErr(); return -1; } auto bind_addr = dhtnet::ip_utils::getAnyHostAddr(family); if (not bind_addr.isIpv4() and not bind_addr.isIpv6()) { JAMI_ERR("No IPv4/IPv6 host found for family %u", family); close(udp_fd); return -1; } bind_addr.setPort(port); JAMI_DBG("use local address: %s", bind_addr.toString(true, true).c_str()); if (::bind(udp_fd, bind_addr, bind_addr.getLength()) < 0) { JAMI_ERR("bind() failed"); strErr(); close(udp_fd); udp_fd = -1; } return udp_fd; } SocketPair::SocketPair(const char* uri, int localPort) { openSockets(uri, localPort); } SocketPair::SocketPair(std::unique_ptr<dhtnet::IceSocket> rtp_sock, std::unique_ptr<dhtnet::IceSocket> rtcp_sock) : rtp_sock_(std::move(rtp_sock)) , rtcp_sock_(std::move(rtcp_sock)) { JAMI_DBG("[%p] Creating instance using ICE sockets for comp %d and %d", this, rtp_sock_->getCompId(), rtcp_sock_->getCompId()); rtp_sock_->setOnRecv([this](uint8_t* buf, size_t len) { std::lock_guard l(dataBuffMutex_); rtpDataBuff_.emplace_back(buf, buf + len); cv_.notify_one(); return len; }); rtcp_sock_->setOnRecv([this](uint8_t* buf, size_t len) { std::lock_guard l(dataBuffMutex_); rtcpDataBuff_.emplace_back(buf, buf + len); cv_.notify_one(); return len; }); } SocketPair::~SocketPair() { interrupt(); closeSockets(); JAMI_DBG("[%p] Instance destroyed", this); } bool SocketPair::waitForRTCP(std::chrono::seconds interval) { std::unique_lock lock(rtcpInfo_mutex_); return cvRtcpPacketReadyToRead_.wait_for(lock, interval, [this] { return interrupted_ or not listRtcpRRHeader_.empty() or not listRtcpREMBHeader_.empty(); }); } void SocketPair::saveRtcpRRPacket(uint8_t* buf, size_t len) { if (len < sizeof(rtcpRRHeader)) return; auto header = reinterpret_cast<rtcpRRHeader*>(buf); if (header->pt != 201) // 201 = RR PT return; std::lock_guard lock(rtcpInfo_mutex_); if (listRtcpRRHeader_.size() >= MAX_LIST_SIZE) { listRtcpRRHeader_.pop_front(); } listRtcpRRHeader_.emplace_back(*header); cvRtcpPacketReadyToRead_.notify_one(); } void SocketPair::saveRtcpREMBPacket(uint8_t* buf, size_t len) { if (len < sizeof(rtcpREMBHeader)) return; auto header = reinterpret_cast<rtcpREMBHeader*>(buf); if (header->pt != 206) // 206 = REMB PT return; if (header->uid != 0x424D4552) // uid must be "REMB" return; std::lock_guard lock(rtcpInfo_mutex_); if (listRtcpREMBHeader_.size() >= MAX_LIST_SIZE) { listRtcpREMBHeader_.pop_front(); } listRtcpREMBHeader_.push_back(*header); cvRtcpPacketReadyToRead_.notify_one(); } std::list<rtcpRRHeader> SocketPair::getRtcpRR() { std::lock_guard lock(rtcpInfo_mutex_); return std::move(listRtcpRRHeader_); } std::list<rtcpREMBHeader> SocketPair::getRtcpREMB() { std::lock_guard lock(rtcpInfo_mutex_); return std::move(listRtcpREMBHeader_); } void SocketPair::createSRTP(const char* out_suite, const char* out_key, const char* in_suite, const char* in_key) { srtpContext_.reset(new SRTPProtoContext(out_suite, out_key, in_suite, in_key)); } void SocketPair::interrupt() { JAMI_WARN("[%p] Interrupting RTP sockets", this); interrupted_ = true; if (rtp_sock_) rtp_sock_->setOnRecv(nullptr); if (rtcp_sock_) rtcp_sock_->setOnRecv(nullptr); cv_.notify_all(); cvRtcpPacketReadyToRead_.notify_all(); } void SocketPair::setReadBlockingMode(bool block) { JAMI_DBG("[%p] Read operations in blocking mode [%s]", this, block ? "YES" : "NO"); readBlockingMode_ = block; cv_.notify_all(); cvRtcpPacketReadyToRead_.notify_all(); } void SocketPair::stopSendOp(bool state) { noWrite_ = state; } void SocketPair::closeSockets() { if (rtcpHandle_ > 0 and close(rtcpHandle_)) strErr(); if (rtpHandle_ > 0 and close(rtpHandle_)) strErr(); } void SocketPair::openSockets(const char* uri, int local_rtp_port) { JAMI_DBG("Creating rtp socket for uri %s on port %d", uri, local_rtp_port); char hostname[256]; char path[1024]; int dst_rtp_port; av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &dst_rtp_port, path, sizeof(path), uri); const int local_rtcp_port = local_rtp_port + 1; const int dst_rtcp_port = dst_rtp_port + 1; rtpDestAddr_ = dhtnet::IpAddr {hostname}; rtpDestAddr_.setPort(dst_rtp_port); rtcpDestAddr_ = dhtnet::IpAddr {hostname}; rtcpDestAddr_.setPort(dst_rtcp_port); // Open local sockets (RTP/RTCP) if ((rtpHandle_ = udp_socket_create(rtpDestAddr_.getFamily(), local_rtp_port)) == -1 or (rtcpHandle_ = udp_socket_create(rtcpDestAddr_.getFamily(), local_rtcp_port)) == -1) { closeSockets(); JAMI_ERR("[%p] Sockets creation failed", this); throw std::runtime_error("Sockets creation failed"); } JAMI_WARN("SocketPair: local{%d,%d} / %s{%d,%d}", local_rtp_port, local_rtcp_port, hostname, dst_rtp_port, dst_rtcp_port); } MediaIOHandle* SocketPair::createIOContext(const uint16_t mtu) { unsigned ip_header_size; if (rtp_sock_) ip_header_size = rtp_sock_->getTransportOverhead(); else if (rtpDestAddr_.getFamily() == AF_INET6) ip_header_size = 40; else ip_header_size = 20; return new MediaIOHandle( mtu - (srtpContext_ ? SRTP_OVERHEAD : 0) - UDP_HEADER_SIZE - ip_header_size, true, [](void* sp, uint8_t* buf, int len) { return static_cast<SocketPair*>(sp)->readCallback(buf, len); }, [](void* sp, uint8_t* buf, int len) { return static_cast<SocketPair*>(sp)->writeCallback(buf, len); }, 0, reinterpret_cast<void*>(this)); } int SocketPair::waitForData() { // System sockets if (rtpHandle_ >= 0) { int ret; do { if (interrupted_) { errno = EINTR; return -1; } if (not readBlockingMode_) { return 0; } // work with system socket struct pollfd p[2] = {{rtpHandle_, POLLIN, 0}, {rtcpHandle_, POLLIN, 0}}; ret = poll(p, 2, NET_POLL_TIMEOUT); if (ret > 0) { ret = 0; if (p[0].revents & POLLIN) ret |= static_cast<int>(DataType::RTP); if (p[1].revents & POLLIN) ret |= static_cast<int>(DataType::RTCP); } } while (!ret or (ret < 0 and errno == EAGAIN)); return ret; } // work with IceSocket { std::unique_lock lk(dataBuffMutex_); cv_.wait(lk, [this] { return interrupted_ or not rtpDataBuff_.empty() or not rtcpDataBuff_.empty() or not readBlockingMode_; }); } if (interrupted_) { errno = EINTR; return -1; } return static_cast<int>(DataType::RTP) | static_cast<int>(DataType::RTCP); } int SocketPair::readRtpData(void* buf, int buf_size) { // handle system socket if (rtpHandle_ >= 0) { struct sockaddr_storage from; socklen_t from_len = sizeof(from); return recvfrom(rtpHandle_, static_cast<char*>(buf), buf_size, 0, reinterpret_cast<struct sockaddr*>(&from), &from_len); } // handle ICE std::unique_lock lk(dataBuffMutex_); if (not rtpDataBuff_.empty()) { auto pkt = std::move(rtpDataBuff_.front()); rtpDataBuff_.pop_front(); lk.unlock(); // to not block our ICE callbacks int pkt_size = pkt.size(); int len = std::min(pkt_size, buf_size); std::copy_n(pkt.begin(), len, static_cast<char*>(buf)); return len; } return 0; } int SocketPair::readRtcpData(void* buf, int buf_size) { // handle system socket if (rtcpHandle_ >= 0) { struct sockaddr_storage from; socklen_t from_len = sizeof(from); return recvfrom(rtcpHandle_, static_cast<char*>(buf), buf_size, 0, reinterpret_cast<struct sockaddr*>(&from), &from_len); } // handle ICE std::unique_lock lk(dataBuffMutex_); if (not rtcpDataBuff_.empty()) { auto pkt = std::move(rtcpDataBuff_.front()); rtcpDataBuff_.pop_front(); lk.unlock(); int pkt_size = pkt.size(); int len = std::min(pkt_size, buf_size); std::copy_n(pkt.begin(), len, static_cast<char*>(buf)); return len; } return 0; } int SocketPair::readCallback(uint8_t* buf, int buf_size) { auto datatype = waitForData(); if (datatype < 0) return datatype; int len = 0; bool fromRTCP = false; if (datatype & static_cast<int>(DataType::RTCP)) { len = readRtcpData(buf, buf_size); if (len > 0) { auto header = reinterpret_cast<rtcpRRHeader*>(buf); // 201 = RR PT if (header->pt == 201) { lastDLSR_ = Swap4Bytes(header->dlsr); // JAMI_WARN("Read RR, lastDLSR : %d", lastDLSR_); lastRR_time = std::chrono::steady_clock::now(); saveRtcpRRPacket(buf, len); } // 206 = REMB PT else if (header->pt == 206) saveRtcpREMBPacket(buf, len); // 200 = SR PT else if (header->pt == 200) { // not used yet } else { JAMI_DBG("Unable to read RTCP: unknown packet type %u", header->pt); } fromRTCP = true; } } // No RTCP... try RTP if (!len and (datatype & static_cast<int>(DataType::RTP))) { len = readRtpData(buf, buf_size); fromRTCP = false; } if (len <= 0) return len; if (not fromRTCP && (buf_size < static_cast<int>(MINIMUM_RTP_HEADER_SIZE))) return len; // SRTP decrypt if (not fromRTCP and srtpContext_ and srtpContext_->srtp_in.aes) { int32_t gradient = 0; int32_t deltaT = 0; float abs = 0.0f; bool res_parse = false; bool res_delay = false; res_parse = parse_RTP_ext(buf, &abs); bool marker = (buf[1] & 0x80) >> 7; if (res_parse) res_delay = getOneWayDelayGradient(abs, marker, &gradient, &deltaT); // rtpDelayCallback_ is not set for audio if (rtpDelayCallback_ and res_delay) rtpDelayCallback_(gradient, deltaT); auto err = ff_srtp_decrypt(&srtpContext_->srtp_in, buf, &len); if (packetLossCallback_ and (buf[2] << 8 | buf[3]) != lastSeqNumIn_ + 1) packetLossCallback_(); lastSeqNumIn_ = buf[2] << 8 | buf[3]; if (err < 0) JAMI_WARN("decrypt error %d", err); } if (len != 0) return len; else return AVERROR_EOF; } int SocketPair::writeData(uint8_t* buf, int buf_size) { bool isRTCP = RTP_PT_IS_RTCP(buf[1]); // System sockets? if (rtpHandle_ >= 0) { int fd; dhtnet::IpAddr* dest_addr; if (isRTCP) { fd = rtcpHandle_; dest_addr = &rtcpDestAddr_; } else { fd = rtpHandle_; dest_addr = &rtpDestAddr_; } auto ret = ff_network_wait_fd(fd); if (ret < 0) return ret; if (noWrite_) return buf_size; return ::sendto(fd, reinterpret_cast<const char*>(buf), buf_size, 0, *dest_addr, dest_addr->getLength()); } if (noWrite_) return buf_size; // IceSocket if (isRTCP) return rtcp_sock_->send(buf, buf_size); else return rtp_sock_->send(buf, buf_size); } int SocketPair::writeCallback(uint8_t* buf, int buf_size) { if (noWrite_) return 0; int ret; bool isRTCP = RTP_PT_IS_RTCP(buf[1]); unsigned int ts_LSB, ts_MSB; double currentSRTS, currentLatency; // Encrypt? if (not isRTCP and srtpContext_ and srtpContext_->srtp_out.aes) { buf_size = ff_srtp_encrypt(&srtpContext_->srtp_out, buf, buf_size, srtpContext_->encryptbuf, sizeof(srtpContext_->encryptbuf)); if (buf_size < 0) { JAMI_WARN("encrypt error %d", buf_size); return buf_size; } buf = srtpContext_->encryptbuf; } // check if we're sending an RR, if so, detect packet loss // buf_size gives length of buffer, not just header if (isRTCP && static_cast<unsigned>(buf_size) >= sizeof(rtcpRRHeader)) { auto header = reinterpret_cast<rtcpRRHeader*>(buf); rtcpPacketLoss_ = (header->pt == 201 && ntohl(header->fraction_lost) & RTCP_RR_FRACTION_MASK); } do { if (interrupted_) return -EINTR; ret = writeData(buf, buf_size); } while (ret < 0 and errno == EAGAIN); if (buf[1] == 200) // Sender Report { auto header = reinterpret_cast<rtcpSRHeader*>(buf); ts_LSB = Swap4Bytes(header->timestampLSB); ts_MSB = Swap4Bytes(header->timestampMSB); currentSRTS = ts_MSB + (ts_LSB / pow(2, 32)); if (lastSRTS_ != 0 && lastDLSR_ != 0) { if (histoLatency_.size() >= MAX_LIST_SIZE) histoLatency_.pop_front(); currentLatency = (currentSRTS - lastSRTS_) / 2; // JAMI_WARN("Current Latency : %f from sender %X", currentLatency, header->ssrc); histoLatency_.push_back(currentLatency); } lastSRTS_ = currentSRTS; // JAMI_WARN("SENDING NEW RTCP SR !! "); } else if (buf[1] == 201) // Receiver Report { // auto header = reinterpret_cast<rtcpRRHeader*>(buf); // JAMI_WARN("SENDING NEW RTCP RR !! "); } return ret < 0 ? -errno : ret; } double SocketPair::getLastLatency() { if (not histoLatency_.empty()) return histoLatency_.back(); else return -1; } void SocketPair::setRtpDelayCallback(std::function<void(int, int)> cb) { rtpDelayCallback_ = std::move(cb); } bool SocketPair::getOneWayDelayGradient(float sendTS, bool marker, int32_t* gradient, int32_t* deltaT) { // Keep only last packet of each frame if (not marker) { return 0; } // 1st frame if (not lastSendTS_) { lastSendTS_ = sendTS; lastReceiveTS_ = std::chrono::steady_clock::now(); return 0; } int32_t deltaS = (sendTS - lastSendTS_) * 1000; // milliseconds if (deltaS < 0) deltaS += 64000; lastSendTS_ = sendTS; std::chrono::steady_clock::time_point arrival_TS = std::chrono::steady_clock::now(); auto deltaR = std::chrono::duration_cast<std::chrono::milliseconds>(arrival_TS - lastReceiveTS_) .count(); lastReceiveTS_ = arrival_TS; *gradient = deltaR - deltaS; *deltaT = deltaR; return true; } bool SocketPair::parse_RTP_ext(uint8_t* buf, float* abs) { if (not(buf[0] & 0x10)) return false; uint16_t magic_word = (buf[12] << 8) + buf[13]; if (magic_word != 0xBEDE) return false; uint8_t sec = buf[17] >> 2; uint32_t fract = ((buf[17] & 0x3) << 16 | (buf[18] << 8) | buf[19]) << 14; float milli = fract / pow(2, 32); *abs = sec + (milli); return true; } uint16_t SocketPair::lastSeqValOut() { if (srtpContext_) return srtpContext_->srtp_out.seq_largest; JAMI_ERR("SRTP context not found."); return 0; } } // namespace jami
20,807
C++
.cpp
638
25.584639
113
0.584697
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,738
media_buffer.cpp
savoirfairelinux_jami-daemon/src/media/media_buffer.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "libav_deps.h" // MUST BE INCLUDED FIRST #include "libav_utils.h" #include "media_buffer.h" #include "jami/videomanager_interface.h" #include <new> // std::bad_alloc #include <cstdlib> #include <cstring> // std::memset #include <ciso646> // fix windows compiler bug namespace jami { #ifdef ENABLE_VIDEO //=== HELPERS ================================================================== int videoFrameSize(int format, int width, int height) { return av_image_get_buffer_size((AVPixelFormat) format, width, height, 1); } #endif // ENABLE_VIDEO } // namespace jami
1,298
C++
.cpp
34
36.382353
80
0.707006
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
751,739
localrecordermanager.cpp
savoirfairelinux_jami-daemon/src/media/localrecordermanager.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "localrecordermanager.h" namespace jami { LocalRecorderManager& LocalRecorderManager::instance() { static LocalRecorderManager instance; return instance; } void LocalRecorderManager::removeRecorderByPath(const std::string& path) { std::lock_guard lock(recorderMapMutex_); recorderMap_.erase(path); } void LocalRecorderManager::insertRecorder(const std::string& path, std::unique_ptr<LocalRecorder> rec) { if (!rec) { throw std::invalid_argument("Unable to insert null recorder"); } std::lock_guard lock(recorderMapMutex_); auto ret = recorderMap_.emplace(path, std::move(rec)); if (!ret.second) { throw std::invalid_argument( "Unable to insert recorder (passed path is already used as key)"); } } LocalRecorder* LocalRecorderManager::getRecorderByPath(const std::string& path) { auto rec = recorderMap_.find(path); return (rec == recorderMap_.end()) ? nullptr : rec->second.get(); } bool LocalRecorderManager::hasRunningRecorders() { for (auto it = recorderMap_.begin(); it != recorderMap_.end(); ++it) { if (it->second->isRecording()) return true; } return false; } } // namespace jami
1,932
C++
.cpp
59
29.474576
97
0.722342
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,740
libav_utils.cpp
savoirfairelinux_jami-daemon/src/media/libav_utils.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "libav_deps.h" // MUST BE INCLUDED FIRST #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "video/video_base.h" #include "logger.h" #include <vector> #include <algorithm> #include <string> #include <iostream> #include <thread> #include <mutex> #include <exception> #include <ciso646> // fix windows compiler bug extern "C" { #if LIBAVUTIL_VERSION_MAJOR < 56 AVFrameSideData* av_frame_new_side_data_from_buf(AVFrame* frame, enum AVFrameSideDataType type, AVBufferRef* buf) { auto side_data = av_frame_new_side_data(frame, type, 0); av_buffer_unref(&side_data->buf); side_data->buf = buf; side_data->data = side_data->buf->data; side_data->size = side_data->buf->size; return side_data; } #endif } namespace jami { namespace libav_utils { AVSampleFormat choose_sample_fmt(const AVCodec* codec, const AVSampleFormat* preferred_formats, int preferred_formats_count) { if (codec->sample_fmts) for (int i = 0; i < preferred_formats_count; ++i) { for (auto it = codec->sample_fmts; *it != -1; ++it) { if (*it == preferred_formats[i]) return preferred_formats[i]; } } return AV_SAMPLE_FMT_NONE; } AVSampleFormat choose_sample_fmt_default(const AVCodec* codec, AVSampleFormat defaultFormat) { // List of supported formats, current default first const AVSampleFormat preferred_formats[] = {defaultFormat, AV_SAMPLE_FMT_FLTP, AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_S16P, AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_DBLP, AV_SAMPLE_FMT_DBL, AV_SAMPLE_FMT_S32P, AV_SAMPLE_FMT_S32}; return choose_sample_fmt(codec, preferred_formats, sizeof(preferred_formats) / sizeof(preferred_formats[0])); } #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(58, 9, 100) // protect libav/ffmpeg access static int avcodecManageMutex(void** data, enum AVLockOp op) { auto mutex = reinterpret_cast<std::mutex**>(data); int ret = 0; switch (op) { case AV_LOCK_CREATE: try { *mutex = new std::mutex; } catch (const std::bad_alloc& e) { return AVERROR(ENOMEM); } break; case AV_LOCK_OBTAIN: (*mutex)->lock(); break; case AV_LOCK_RELEASE: (*mutex)->unlock(); break; case AV_LOCK_DESTROY: delete *mutex; *mutex = nullptr; break; default: #ifdef AVERROR_BUG return AVERROR_BUG; #else break; #endif } return AVERROR(ret); } #endif static constexpr const char* AVLOGLEVEL = "AVLOGLEVEL"; static void setAvLogLevel() { char* envvar = getenv(AVLOGLEVEL); signed level = AV_LOG_WARNING; if (envvar != nullptr) { level = to_int<int>(envvar, AV_LOG_ERROR); level = std::max(AV_LOG_QUIET, std::min(level, AV_LOG_DEBUG)); } av_log_set_level(level); } #ifdef __ANDROID__ static void androidAvLogCb(void* ptr, int level, const char* fmt, va_list vl) { if (level > av_log_get_level()) return; char line[1024]; int print_prefix = 1; int android_level; va_list vl2; va_copy(vl2, vl); av_log_format_line(ptr, level, fmt, vl2, line, sizeof(line), &print_prefix); va_end(vl2); // replace unprintable characters with '?' int idx = 0; while (line[idx]) { if (line[idx] < 0x08 || (line[idx] > 0x0D && line[idx] < 0x20)) line[idx] = '?'; ++idx; } switch (level) { case AV_LOG_QUIET: android_level = ANDROID_LOG_SILENT; break; case AV_LOG_PANIC: android_level = ANDROID_LOG_FATAL; break; case AV_LOG_FATAL: android_level = ANDROID_LOG_FATAL; break; case AV_LOG_ERROR: android_level = ANDROID_LOG_ERROR; break; case AV_LOG_WARNING: android_level = ANDROID_LOG_WARN; break; case AV_LOG_INFO: android_level = ANDROID_LOG_INFO; break; case AV_LOG_VERBOSE: android_level = ANDROID_LOG_INFO; break; case AV_LOG_DEBUG: android_level = ANDROID_LOG_DEBUG; break; case AV_LOG_TRACE: android_level = ANDROID_LOG_VERBOSE; break; default: android_level = ANDROID_LOG_DEFAULT; break; } __android_log_print(android_level, "FFmpeg", "%s", line); } #endif static void init_once() { #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(58, 9, 100) av_register_all(); #endif avdevice_register_all(); avformat_network_init(); #if LIBAVFILTER_VERSION_INT < AV_VERSION_INT(7, 13, 100) avfilter_register_all(); #endif #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(58, 9, 100) av_lockmgr_register(avcodecManageMutex); #endif setAvLogLevel(); #ifdef __ANDROID__ // android doesn't like stdout and stderr :( av_log_set_callback(androidAvLogCb); #endif } static std::once_flag already_called; void av_init() { std::call_once(already_called, init_once); } bool is_yuv_planar(const AVPixFmtDescriptor& desc) { if (not(desc.flags & AV_PIX_FMT_FLAG_PLANAR) or desc.flags & AV_PIX_FMT_FLAG_RGB) return false; /* handle formats that do not use all planes */ unsigned used_bit_mask = (1u << desc.nb_components) - 1; for (unsigned i = 0; i < desc.nb_components; ++i) used_bit_mask &= ~(1u << desc.comp[i].plane); return not used_bit_mask; } std::string getError(int err) { std::string ret(AV_ERROR_MAX_STRING_SIZE, '\0'); av_strerror(err, (char*) ret.data(), ret.size()); return ret; } const char* getDictValue(const AVDictionary* d, const std::string& key, int flags) { auto kv = av_dict_get(d, key.c_str(), nullptr, flags); if (kv) return kv->value; else return ""; } void setDictValue(AVDictionary** d, const std::string& key, const std::string& value, int flags) { av_dict_set(d, key.c_str(), value.c_str(), flags); } void fillWithBlack(AVFrame* frame) { const AVPixelFormat format = static_cast<AVPixelFormat>(frame->format); const int planes = av_pix_fmt_count_planes(format); // workaround for casting pointers to different sizes // on 64 bit machines: sizeof(ptrdiff_t) != sizeof(int) ptrdiff_t linesizes[4]; for (int i = 0; i < planes; ++i) linesizes[i] = frame->linesize[i]; int ret = av_image_fill_black(frame->data, linesizes, format, frame->color_range, frame->width, frame->height); if (ret < 0) { JAMI_ERR() << "Failed to blacken frame"; } } void fillWithSilence(AVFrame* frame) { int ret = av_samples_set_silence(frame->extended_data, 0, frame->nb_samples, frame->ch_layout.nb_channels, (AVSampleFormat) frame->format); if (ret < 0) JAMI_ERR() << "Failed to fill frame with silence"; } } // namespace libav_utils } // namespace jami
8,285
C++
.cpp
270
23.592593
96
0.596994
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,741
media_codec.cpp
savoirfairelinux_jami-daemon/src/media/media_codec.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "libav_deps.h" // MUST BE INCLUDED FIRST #include "media_codec.h" #include "account_const.h" #include "string_utils.h" #include "logger.h" #include <string> #include <sstream> namespace jami { /* * SystemCodecInfo */ SystemCodecInfo::SystemCodecInfo(unsigned codecId, unsigned avcodecId, const std::string& longName, const std::string& name, const std::string& libName, MediaType mediaType, CodecType codecType, unsigned bitrate, unsigned payloadType, unsigned minQuality, unsigned maxQuality) : id(codecId) , avcodecId(avcodecId) , longName(longName) , name(name) , libName(libName) , codecType(codecType) , mediaType(mediaType) , payloadType(payloadType) , bitrate(bitrate) , minQuality(minQuality) , maxQuality(maxQuality) {} SystemCodecInfo::~SystemCodecInfo() {} std::map<std::string, std::string> SystemCodecInfo::getCodecSpecifications() const { return {{libjami::Account::ConfProperties::CodecInfo::NAME, longName}, {libjami::Account::ConfProperties::CodecInfo::TYPE, (mediaType & MEDIA_AUDIO ? "AUDIO" : "VIDEO")}, {libjami::Account::ConfProperties::CodecInfo::BITRATE, std::to_string(bitrate)}}; } /* * SystemAudioCodecInfo */ SystemAudioCodecInfo::SystemAudioCodecInfo(unsigned codecId, unsigned m_avcodecId, const std::string& longName, const std::string& m_name, const std::string& m_libName, CodecType m_type, unsigned m_bitrate, unsigned m_sampleRate, unsigned m_nbChannels, unsigned m_payloadType, AVSampleFormat sampleFormat) : SystemCodecInfo(codecId, m_avcodecId, longName, m_name, m_libName, MEDIA_AUDIO, m_type, m_bitrate, m_payloadType) , audioformat {m_sampleRate, m_nbChannels, sampleFormat} {} SystemAudioCodecInfo::~SystemAudioCodecInfo() {} std::map<std::string, std::string> SystemAudioCodecInfo::getCodecSpecifications() const { return {{libjami::Account::ConfProperties::CodecInfo::NAME, longName}, {libjami::Account::ConfProperties::CodecInfo::TYPE, (mediaType & MEDIA_AUDIO ? "AUDIO" : "VIDEO")}, {libjami::Account::ConfProperties::CodecInfo::BITRATE, std::to_string(bitrate)}, {libjami::Account::ConfProperties::CodecInfo::SAMPLE_RATE, std::to_string(audioformat.sample_rate)}, {libjami::Account::ConfProperties::CodecInfo::CHANNEL_NUMBER, std::to_string(audioformat.nb_channels)}}; } bool SystemAudioCodecInfo::isPCMG722() const { return avcodecId == AV_CODEC_ID_ADPCM_G722; } void SystemAudioCodecInfo::setCodecSpecifications(const std::map<std::string, std::string>& details) { decltype(bitrate) tmp_bitrate = jami::stoi( details.at(libjami::Account::ConfProperties::CodecInfo::BITRATE)); decltype(audioformat) tmp_audioformat = audioformat; tmp_audioformat.sample_rate = jami::stoi( details.at(libjami::Account::ConfProperties::CodecInfo::SAMPLE_RATE)); // copy back if no exception was raised bitrate = tmp_bitrate; audioformat = tmp_audioformat; } /* * SystemVideoCodecInfo */ SystemVideoCodecInfo::SystemVideoCodecInfo(unsigned codecId, unsigned m_avcodecId, const std::string& longName, const std::string& m_name, const std::string& m_libName, CodecType m_type, unsigned m_bitrate, unsigned m_minQuality, unsigned m_maxQuality, unsigned m_payloadType, unsigned m_frameRate, unsigned m_profileId) : SystemCodecInfo(codecId, m_avcodecId, longName, m_name, m_libName, MEDIA_VIDEO, m_type, m_bitrate, m_payloadType, m_minQuality, m_maxQuality) , frameRate(m_frameRate) , profileId(m_profileId) {} SystemVideoCodecInfo::~SystemVideoCodecInfo() {} std::map<std::string, std::string> SystemVideoCodecInfo::getCodecSpecifications() const { return { {libjami::Account::ConfProperties::CodecInfo::NAME, longName}, {libjami::Account::ConfProperties::CodecInfo::TYPE, (mediaType & MEDIA_AUDIO ? "AUDIO" : "VIDEO")}, {libjami::Account::ConfProperties::CodecInfo::BITRATE, std::to_string(bitrate)}, {libjami::Account::ConfProperties::CodecInfo::FRAME_RATE, std::to_string(frameRate)}, {libjami::Account::ConfProperties::CodecInfo::MIN_BITRATE, std::to_string(minBitrate)}, {libjami::Account::ConfProperties::CodecInfo::MAX_BITRATE, std::to_string(maxBitrate)}, }; } void SystemVideoCodecInfo::setCodecSpecifications(const std::map<std::string, std::string>& details) { auto copy = *this; auto it = details.find(libjami::Account::ConfProperties::CodecInfo::BITRATE); if (it != details.end()) copy.bitrate = jami::stoi(it->second); it = details.find(libjami::Account::ConfProperties::CodecInfo::FRAME_RATE); if (it != details.end()) copy.frameRate = jami::stoi(it->second); it = details.find(libjami::Account::ConfProperties::CodecInfo::QUALITY); if (it != details.end()) copy.quality = jami::stoi(it->second); it = details.find(libjami::Account::ConfProperties::CodecInfo::AUTO_QUALITY_ENABLED); if (it != details.end()) copy.isAutoQualityEnabled = (it->second == TRUE_STR) ? true : false; // copy back if no exception was raised *this = std::move(copy); } } // namespace jami
7,568
C++
.cpp
177
30.152542
95
0.568947
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,742
media_io_handle.cpp
savoirfairelinux_jami-daemon/src/media/media_io_handle.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "libav_deps.h" // MUST BE INCLUDED FIRST #include "media_io_handle.h" namespace jami { MediaIOHandle::MediaIOHandle(std::size_t buffer_size, bool writeable, io_readcallback read_cb, io_writecallback write_cb, io_seekcallback seek_cb, void* opaque) : ctx_(0) { /* FFmpeg doesn't alloc the buffer for the first time, but it does free and * alloc it afterwards. * Don't directly use malloc because av_malloc is optimized for memory alignment. */ auto buf = static_cast<uint8_t*>(av_malloc(buffer_size)); ctx_ = avio_alloc_context(buf, buffer_size, writeable, opaque, read_cb, write_cb, seek_cb); ctx_->max_packet_size = buffer_size; } MediaIOHandle::~MediaIOHandle() { av_free(ctx_->buffer); av_free(ctx_); } } // namespace jami
1,646
C++
.cpp
41
34.04878
95
0.664165
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
751,743
media_filter.cpp
savoirfairelinux_jami-daemon/src/media/media_filter.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "libav_deps.h" // MUST BE INCLUDED FIRST #include "logger.h" #include "media_filter.h" #include "media_buffer.h" extern "C" { #include <libavfilter/buffersink.h> #include <libavfilter/buffersrc.h> } #include <algorithm> #include <functional> #include <memory> #include <sstream> #include <thread> namespace jami { MediaFilter::MediaFilter() {} MediaFilter::~MediaFilter() { clean(); } std::string MediaFilter::getFilterDesc() const { return desc_; } int MediaFilter::initialize(const std::string& filterDesc, const std::vector<MediaStream>& msps) { int ret = 0; desc_ = filterDesc; graph_ = avfilter_graph_alloc(); if (!graph_) return fail("Failed to allocate filter graph", AVERROR(ENOMEM)); graph_->nb_threads = std::max(1u, std::min(8u, std::thread::hardware_concurrency() / 2)); AVFilterInOut* in; AVFilterInOut* out; if ((ret = avfilter_graph_parse2(graph_, desc_.c_str(), &in, &out)) < 0) return fail("Failed to parse filter graph", ret); using AVFilterInOutPtr = std::unique_ptr<AVFilterInOut, std::function<void(AVFilterInOut*)>>; AVFilterInOutPtr outputs(out, [](AVFilterInOut* f) { avfilter_inout_free(&f); }); AVFilterInOutPtr inputs(in, [](AVFilterInOut* f) { avfilter_inout_free(&f); }); if (outputs && outputs->next) return fail("Filters with multiple outputs are not supported", AVERROR(ENOTSUP)); if ((ret = initOutputFilter(outputs.get())) < 0) return fail("Failed to create output for filter graph", ret); // make sure inputs linked list is the same size as msps size_t count = 0; AVFilterInOut* dummyInput = inputs.get(); while (dummyInput && ++count) // increment count before evaluating its value dummyInput = dummyInput->next; if (count != msps.size()) return fail( "Size mismatch between number of inputs in filter graph and input parameter array", AVERROR(EINVAL)); for (AVFilterInOut* current = inputs.get(); current; current = current->next) { if (!current->name) return fail("Filters require non empty names", AVERROR(EINVAL)); std::string_view name = current->name; auto it = std::find_if(msps.begin(), msps.end(), [name](const MediaStream& msp) { return msp.name == name; }); if (it != msps.end()) { if ((ret = initInputFilter(current, *it)) < 0) { return fail(fmt::format("Failed to initialize input: {}", name), ret); } } else { return fail(fmt::format("Failed to find matching parameters for: {}", name), ret); } } if ((ret = avfilter_graph_config(graph_, nullptr)) < 0) return fail("Failed to configure filter graph", ret); JAMI_DBG() << "Filter graph initialized with: " << desc_; initialized_ = true; return 0; } const MediaStream& MediaFilter::getInputParams(const std::string& inputName) const { for (const auto& ms : inputParams_) if (ms.name == inputName) return ms; throw std::out_of_range("Input '" + inputName + "' not found"); } MediaStream MediaFilter::getOutputParams() const { MediaStream output; if (!output_ || !initialized_) { fail("Filter not initialized", -1); return output; } switch (av_buffersink_get_type(output_)) { case AVMEDIA_TYPE_VIDEO: output.name = "videoOutput"; output.format = av_buffersink_get_format(output_); output.isVideo = true; output.timeBase = av_buffersink_get_time_base(output_); output.width = av_buffersink_get_w(output_); output.height = av_buffersink_get_h(output_); output.bitrate = 0; output.frameRate = av_buffersink_get_frame_rate(output_); break; case AVMEDIA_TYPE_AUDIO: output.name = "audioOutput"; output.format = av_buffersink_get_format(output_); output.isVideo = false; output.timeBase = av_buffersink_get_time_base(output_); output.sampleRate = av_buffersink_get_sample_rate(output_); output.nbChannels = av_buffersink_get_channels(output_); break; default: output.format = -1; break; } return output; } int MediaFilter::feedInput(AVFrame* frame, const std::string& inputName) { int ret = 0; if (!initialized_) return fail("Filter not initialized", -1); if (!frame) return 0; for (size_t i = 0; i < inputs_.size(); ++i) { auto& ms = inputParams_[i]; if (ms.name != inputName) continue; if (ms.format != frame->format || (ms.isVideo && (ms.width != frame->width || ms.height != frame->height)) || (!ms.isVideo && (ms.sampleRate != frame->sample_rate || ms.nbChannels != frame->ch_layout.nb_channels))) { ms.update(frame); if ((ret = reinitialize()) < 0) return fail("Failed to reinitialize filter with new input parameters", ret); } int flags = AV_BUFFERSRC_FLAG_KEEP_REF; if ((ret = av_buffersrc_add_frame_flags(inputs_[i], frame, flags)) < 0) return fail("Unable to pass frame to filters", ret); else return 0; } return fail(fmt::format("Specified filter '{}' not found", inputName), AVERROR(EINVAL)); } std::unique_ptr<MediaFrame> MediaFilter::readOutput() { if (!initialized_) { fail("Not properly initialized", -1); return {}; } std::unique_ptr<MediaFrame> frame; switch (av_buffersink_get_type(output_)) { #ifdef ENABLE_VIDEO case AVMEDIA_TYPE_VIDEO: frame = std::make_unique<libjami::VideoFrame>(); break; #endif case AVMEDIA_TYPE_AUDIO: frame = std::make_unique<AudioFrame>(); break; default: return {}; } auto err = av_buffersink_get_frame(output_, frame->pointer()); if (err >= 0) { return frame; } else if (err == AVERROR(EAGAIN)) { // no data available right now, try again } else if (err == AVERROR_EOF) { JAMI_WARN() << "Filters have reached EOF, no more frames will be output"; } else { fail("Error occurred while pulling from filter graph", err); } return {}; } void MediaFilter::flush() { for (size_t i = 0; i < inputs_.size(); ++i) { int ret = av_buffersrc_add_frame_flags(inputs_[i], nullptr, 0); if (ret < 0) { JAMI_ERR() << "Failed to flush filter '" << inputParams_[i].name << "': " << libav_utils::getError(ret); } } } int MediaFilter::initOutputFilter(AVFilterInOut* out) { int ret = 0; const AVFilter* buffersink; AVFilterContext* buffersinkCtx = nullptr; AVMediaType mediaType = avfilter_pad_get_type(out->filter_ctx->input_pads, out->pad_idx); if (mediaType == AVMEDIA_TYPE_VIDEO) buffersink = avfilter_get_by_name("buffersink"); else buffersink = avfilter_get_by_name("abuffersink"); if ((ret = avfilter_graph_create_filter(&buffersinkCtx, buffersink, "out", nullptr, nullptr, graph_)) < 0) { avfilter_free(buffersinkCtx); return fail("Failed to create buffer sink", ret); } if ((ret = avfilter_link(out->filter_ctx, out->pad_idx, buffersinkCtx, 0)) < 0) { avfilter_free(buffersinkCtx); return fail("Unable to link buffer sink to graph", ret); } output_ = buffersinkCtx; return ret; } int MediaFilter::initInputFilter(AVFilterInOut* in, const MediaStream& msp) { int ret = 0; AVBufferSrcParameters* params = av_buffersrc_parameters_alloc(); if (!params) return -1; const AVFilter* buffersrc; AVMediaType mediaType = avfilter_pad_get_type(in->filter_ctx->input_pads, in->pad_idx); params->format = msp.format; params->time_base = msp.timeBase; if (mediaType == AVMEDIA_TYPE_VIDEO) { params->width = msp.width; params->height = msp.height; params->frame_rate = msp.frameRate; buffersrc = avfilter_get_by_name("buffer"); } else { params->sample_rate = msp.sampleRate; av_channel_layout_default(&params->ch_layout, msp.nbChannels); buffersrc = avfilter_get_by_name("abuffer"); } AVFilterContext* buffersrcCtx = nullptr; if (buffersrc) { char name[128]; snprintf(name, sizeof(name), "buffersrc_%s_%d", in->name, in->pad_idx); buffersrcCtx = avfilter_graph_alloc_filter(graph_, buffersrc, name); } if (!buffersrcCtx) { av_free(params); return fail("Failed to allocate filter graph input", AVERROR(ENOMEM)); } ret = av_buffersrc_parameters_set(buffersrcCtx, params); av_free(params); if (ret < 0) return fail("Failed to set filter graph input parameters", ret); if ((ret = avfilter_init_str(buffersrcCtx, nullptr)) < 0) return fail("Failed to initialize buffer source", ret); if ((ret = avfilter_link(buffersrcCtx, 0, in->filter_ctx, in->pad_idx)) < 0) return fail("Failed to link buffer source to graph", ret); inputs_.push_back(buffersrcCtx); inputParams_.emplace_back(msp); inputParams_.back().name = in->name; return ret; } int MediaFilter::reinitialize() { // keep parameters needed for initialization before clearing filter auto params = std::move(inputParams_); auto desc = std::move(desc_); clean(); auto ret = initialize(desc, params); if (ret >= 0) JAMI_DBG() << "Filter graph reinitialized"; return ret; } int MediaFilter::fail(std::string_view msg, int err) const { if (!msg.empty()) JAMI_ERR() << msg << ": " << libav_utils::getError(err); return err; } void MediaFilter::clean() { initialized_ = false; avfilter_graph_free(&graph_); // frees inputs_ and output_ desc_.clear(); inputs_.clear(); // don't point to freed memory output_ = nullptr; // don't point to freed memory inputParams_.clear(); } } // namespace jami
10,797
C++
.cpp
300
30.193333
109
0.638955
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,744
sinkclient.cpp
savoirfairelinux_jami-daemon/src/media/video/sinkclient.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "sinkclient.h" #ifdef ENABLE_SHM #include "shm_header.h" #endif // ENABLE_SHM #include "media_buffer.h" #include "logger.h" #include "noncopyable.h" #include "client/ring_signal.h" #include "jami/videomanager_interface.h" #include "libav_utils.h" #include "video_scaler.h" #include "media_filter.h" #include "filter_transpose.h" #ifdef RING_ACCEL #include "accel.h" #endif #ifndef _WIN32 #include <sys/mman.h> #endif #include <ciso646> // fix windows compiler bug #include <fcntl.h> #include <cstdio> #include <sstream> #include <unistd.h> #include <cerrno> #include <cstring> #include <stdexcept> #include <cmath> namespace jami { namespace video { const constexpr char FILTER_INPUT_NAME[] = "in"; #ifdef ENABLE_SHM // RAII class helper on sem_wait/sem_post sempahore operations class SemGuardLock { public: explicit SemGuardLock(sem_t& mutex) : m_(mutex) { auto ret = ::sem_wait(&m_); if (ret < 0) { std::ostringstream msg; msg << "SHM mutex@" << &m_ << " lock failed (" << ret << ")"; throw std::logic_error {msg.str()}; } } ~SemGuardLock() { ::sem_post(&m_); } private: sem_t& m_; }; class ShmHolder { public: ShmHolder(const std::string& name = {}); ~ShmHolder(); std::string name() const noexcept { return openedName_; } void renderFrame(const VideoFrame& src) noexcept; private: bool resizeArea(std::size_t desired_length) noexcept; char* getShmAreaDataPtr() noexcept; void unMapShmArea() noexcept { if (area_ != MAP_FAILED and ::munmap(area_, areaSize_) < 0) { JAMI_ERR("[ShmHolder:%s] munmap(%zu) failed with errno %d", openedName_.c_str(), areaSize_, errno); } } SHMHeader* area_ {static_cast<SHMHeader*>(MAP_FAILED)}; std::size_t areaSize_ {0}; std::string openedName_; int fd_ {-1}; }; ShmHolder::ShmHolder(const std::string& name) { static constexpr int flags = O_RDWR | O_CREAT | O_TRUNC | O_EXCL; static constexpr int perms = S_IRUSR | S_IWUSR; static auto shmFailedWithErrno = [this](const std::string& what) { std::ostringstream msg; msg << "ShmHolder[" << openedName_ << "]: " << what << " failed, errno=" << errno; throw std::runtime_error {msg.str()}; }; if (not name.empty()) { openedName_ = name; fd_ = ::shm_open(openedName_.c_str(), flags, perms); if (fd_ < 0) shmFailedWithErrno("shm_open"); } else { for (int i = 0; fd_ < 0; ++i) { std::ostringstream tmpName; tmpName << PACKAGE_NAME << "_shm_" << getpid() << "_" << i; openedName_ = tmpName.str(); fd_ = ::shm_open(openedName_.c_str(), flags, perms); if (fd_ < 0 and errno != EEXIST) shmFailedWithErrno("shm_open"); } } // Set size enough for header only (no frame data) if (!resizeArea(0)) shmFailedWithErrno("resizeArea"); // Header fields initialization std::memset(area_, 0, areaSize_); if (::sem_init(&area_->mutex, 1, 1) < 0) shmFailedWithErrno("sem_init(mutex)"); if (::sem_init(&area_->frameGenMutex, 1, 0) < 0) shmFailedWithErrno("sem_init(frameGenMutex)"); JAMI_DBG("[ShmHolder:%s] New holder created", openedName_.c_str()); } ShmHolder::~ShmHolder() { if (fd_ < 0) return; ::close(fd_); ::shm_unlink(openedName_.c_str()); if (area_ == MAP_FAILED) return; ::sem_wait(&area_->mutex); area_->frameSize = 0; ::sem_post(&area_->mutex); ::sem_post(&area_->frameGenMutex); // unlock waiting client before leaving unMapShmArea(); } bool ShmHolder::resizeArea(std::size_t frameSize) noexcept { // aligned on 16-byte boundary frameSize frameSize = (frameSize + 15) & ~15; if (area_ != MAP_FAILED and frameSize == area_->frameSize) return true; // full area size: +15 to take care of maximum padding size const auto areaSize = sizeof(SHMHeader) + 2 * frameSize + 15; JAMI_DBG("[ShmHolder:%s] New size: f=%zu, a=%zu", openedName_.c_str(), frameSize, areaSize); unMapShmArea(); if (::ftruncate(fd_, areaSize) < 0) { JAMI_ERR("[ShmHolder:%s] ftruncate(%zu) failed with errno %d", openedName_.c_str(), areaSize, errno); return false; } area_ = static_cast<SHMHeader*>( ::mmap(nullptr, areaSize, PROT_READ | PROT_WRITE, MAP_SHARED, fd_, 0)); if (area_ == MAP_FAILED) { areaSize_ = 0; JAMI_ERR("[ShmHolder:%s] mmap(%zu) failed with errno %d", openedName_.c_str(), areaSize, errno); return false; } areaSize_ = areaSize; if (frameSize) { SemGuardLock lk {area_->mutex}; area_->frameSize = frameSize; area_->mapSize = areaSize; // Compute aligned IO pointers // Note: we not using std::align as not implemented in 4.9 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=57350 auto p = reinterpret_cast<std::uintptr_t>(area_->data); area_->writeOffset = ((p + 15) & ~15) - p; area_->readOffset = area_->writeOffset + frameSize; } return true; } void ShmHolder::renderFrame(const VideoFrame& src) noexcept { const auto width = src.width(); const auto height = src.height(); const auto format = AV_PIX_FMT_BGRA; const auto frameSize = videoFrameSize(format, width, height); if (!resizeArea(frameSize)) { JAMI_ERR("[ShmHolder:%s] Unable to resize area size: %dx%d, format: %d", openedName_.c_str(), width, height, format); return; } { VideoFrame dst; VideoScaler scaler; dst.setFromMemory(area_->data + area_->writeOffset, format, width, height); scaler.scale(src, dst); } { SemGuardLock lk {area_->mutex}; ++area_->frameGen; std::swap(area_->readOffset, area_->writeOffset); ::sem_post(&area_->frameGenMutex); } } std::string SinkClient::openedName() const noexcept { if (shm_) return shm_->name(); return {}; } bool SinkClient::start() noexcept { if (not shm_) { try { char* envvar = getenv("JAMI_DISABLE_SHM"); if (envvar) // Do not use SHM if set return true; shm_ = std::make_shared<ShmHolder>(); JAMI_DBG("[Sink:%p] Shared memory [%s] created", this, openedName().c_str()); } catch (const std::runtime_error& e) { JAMI_ERR("[Sink:%p] Failed to create shared memory: %s", this, e.what()); } } return static_cast<bool>(shm_); } bool SinkClient::stop() noexcept { setFrameSize(0, 0); setCrop(0, 0, 0, 0); shm_.reset(); return true; } #else // ENABLE_SHM std::string SinkClient::openedName() const noexcept { return {}; } bool SinkClient::start() noexcept { return true; } bool SinkClient::stop() noexcept { setFrameSize(0, 0); setCrop(0, 0, 0, 0); return true; } #endif // !ENABLE_SHM SinkClient::SinkClient(const std::string& id, bool mixer) : id_ {id} , mixer_(mixer) , scaler_(new VideoScaler()) #ifdef DEBUG_FPS , frameCount_(0u) , lastFrameDebug_(std::chrono::steady_clock::now()) #endif { JAMI_DBG("[Sink:%p] Sink [%s] created", this, getId().c_str()); } void SinkClient::sendFrameDirect(const std::shared_ptr<jami::MediaFrame>& frame_p) { notify(frame_p); libjami::FrameBuffer outFrame(av_frame_alloc()); av_frame_ref(outFrame.get(), std::static_pointer_cast<VideoFrame>(frame_p)->pointer()); if (crop_.w || crop_.h) { #ifdef RING_ACCEL auto desc = av_pix_fmt_desc_get( (AVPixelFormat) std::static_pointer_cast<VideoFrame>(frame_p)->format()); /* Cropping does not work for hardware-decoded frames. They need to be transferred to main memory. */ if (desc && (desc->flags & AV_PIX_FMT_FLAG_HWACCEL)) { std::shared_ptr<VideoFrame> frame = std::make_shared<VideoFrame>(); try { frame = HardwareAccel::transferToMainMemory(*std::static_pointer_cast<VideoFrame>( frame_p), AV_PIX_FMT_NV12); } catch (const std::runtime_error& e) { JAMI_ERR("[Sink:%p] Transfert to hardware acceleration memory failed: %s", this, e.what()); return; } if (not frame) return; av_frame_unref(outFrame.get()); av_frame_ref(outFrame.get(), frame->pointer()); } #endif outFrame->crop_top = crop_.y; outFrame->crop_bottom = (size_t) outFrame->height - crop_.y - crop_.h; outFrame->crop_left = crop_.x; outFrame->crop_right = (size_t) outFrame->width - crop_.x - crop_.w; av_frame_apply_cropping(outFrame.get(), AV_FRAME_CROP_UNALIGNED); } if (outFrame->height != height_ || outFrame->width != width_) { setFrameSize(outFrame->width, outFrame->height); return; } target_.push(std::move(outFrame)); } void SinkClient::sendFrameTransformed(AVFrame* frame) { if (frame->width > 0 and frame->height > 0) { if (auto buffer_ptr = target_.pull()) { scaler_->scale(frame, buffer_ptr.get()); target_.push(std::move(buffer_ptr)); } } } std::shared_ptr<VideoFrame> SinkClient::applyTransform(VideoFrame& frame_p) { std::shared_ptr<VideoFrame> frame = std::make_shared<VideoFrame>(); #ifdef RING_ACCEL auto desc = av_pix_fmt_desc_get((AVPixelFormat) frame_p.format()); if (desc && (desc->flags & AV_PIX_FMT_FLAG_HWACCEL)) { try { frame = HardwareAccel::transferToMainMemory(frame_p, AV_PIX_FMT_NV12); } catch (const std::runtime_error& e) { JAMI_ERR("[Sink:%p] Transfert to hardware acceleration memory failed: %s", this, e.what()); return {}; } } else #endif frame->copyFrom(frame_p); int angle = frame->getOrientation(); if (angle != rotation_) { filter_ = getTransposeFilter(angle, FILTER_INPUT_NAME, frame->width(), frame->height(), frame->format(), false); rotation_ = angle; } if (filter_) { filter_->feedInput(frame->pointer(), FILTER_INPUT_NAME); frame = std::static_pointer_cast<VideoFrame>( std::shared_ptr<MediaFrame>(filter_->readOutput())); } if (crop_.w || crop_.h) { frame->pointer()->crop_top = crop_.y; frame->pointer()->crop_bottom = (size_t) frame->height() - crop_.y - crop_.h; frame->pointer()->crop_left = crop_.x; frame->pointer()->crop_right = (size_t) frame->width() - crop_.x - crop_.w; av_frame_apply_cropping(frame->pointer(), AV_FRAME_CROP_UNALIGNED); } return frame; } void SinkClient::update(Observable<std::shared_ptr<MediaFrame>>* /*obs*/, const std::shared_ptr<MediaFrame>& frame_p) { #ifdef DEBUG_FPS auto currentTime = std::chrono::steady_clock::now(); auto seconds = currentTime - lastFrameDebug_; ++frameCount_; if (seconds > std::chrono::seconds(1)) { auto fps = frameCount_ / std::chrono::duration<double>(seconds).count(); JAMI_WARNING("Sink {}, {} FPS", id_, fps); frameCount_ = 0; lastFrameDebug_ = currentTime; } #endif std::unique_lock lock(mtx_); bool hasObservers = getObserversCount() != 0; bool hasDirectListener = target_.push and not target_.pull; bool hasTransformedListener = target_.push and target_.pull; if (hasDirectListener) { sendFrameDirect(frame_p); return; } bool doTransfer = hasTransformedListener or hasObservers; #ifdef ENABLE_SHM doTransfer |= (shm_ && doShmTransfer_); #endif if (doTransfer) { auto frame = applyTransform(*std::static_pointer_cast<VideoFrame>(frame_p)); if (not frame) return; notify(std::static_pointer_cast<MediaFrame>(frame)); if (frame->height() != height_ || frame->width() != width_) { lock.unlock(); setFrameSize(frame->width(), frame->height()); return; } #ifdef ENABLE_SHM if (shm_ && doShmTransfer_) shm_->renderFrame(*frame); #endif if (hasTransformedListener) sendFrameTransformed(frame->pointer()); } } void SinkClient::setFrameSize(int width, int height) { width_ = width; height_ = height; if (width > 0 and height > 0) { JAMI_DBG("[Sink:%p] Started - size=%dx%d, mixer=%s", this, width, height, mixer_ ? "Yes" : "No"); emitSignal<libjami::VideoSignal::DecodingStarted>(getId(), openedName(), width, height, mixer_); started_ = true; } else if (started_) { JAMI_DBG("[Sink:%p] Stopped - size=%dx%d, mixer=%s", this, width, height, mixer_ ? "Yes" : "No"); emitSignal<libjami::VideoSignal::DecodingStopped>(getId(), openedName(), mixer_); started_ = false; } } void SinkClient::setCrop(int x, int y, int w, int h) { JAMI_DBG("[Sink:%p] Change crop to [%dx%d at (%d, %d)]", this, w, h, x, y); crop_.x = x; crop_.y = y; crop_.w = w; crop_.h = h; } } // namespace video } // namespace jami
15,013
C++
.cpp
452
25.707965
98
0.575896
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,745
video_mixer.cpp
savoirfairelinux_jami-daemon/src/media/video/video_mixer.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "libav_deps.h" // MUST BE INCLUDED FIRST #include "video_mixer.h" #include "media_buffer.h" #include "client/videomanager.h" #include "manager.h" #include "media_filter.h" #include "sinkclient.h" #include "logger.h" #include "filter_transpose.h" #ifdef RING_ACCEL #include "accel.h" #endif #include "connectivity/sip_utils.h" #include <cmath> #include <unistd.h> #include <mutex> #include "videomanager_interface.h" #include <opendht/thread_pool.h> static constexpr auto MIN_LINE_ZOOM = 6; // Used by the ONE_BIG_WITH_SMALL layout for the small previews namespace jami { namespace video { struct VideoMixer::VideoMixerSource { Observable<std::shared_ptr<MediaFrame>>* source {nullptr}; int rotation {0}; std::unique_ptr<MediaFilter> rotationFilter {nullptr}; std::shared_ptr<VideoFrame> render_frame; void atomic_copy(const VideoFrame& other) { std::lock_guard lock(mutex_); auto newFrame = std::make_shared<VideoFrame>(); newFrame->copyFrom(other); render_frame = newFrame; } std::shared_ptr<VideoFrame> getRenderFrame() { std::lock_guard lock(mutex_); return render_frame; } // Current render information int x {}; int y {}; int w {}; int h {}; bool hasVideo {true}; private: std::mutex mutex_; }; static constexpr const auto MIXER_FRAMERATE = 30; static constexpr const auto FRAME_DURATION = std::chrono::duration<double>(1. / MIXER_FRAMERATE); VideoMixer::VideoMixer(const std::string& id, const std::string& localInput, bool attachHost) : VideoGenerator::VideoGenerator() , id_(id) , sink_(Manager::instance().createSinkClient(id, true)) , loop_([] { return true; }, std::bind(&VideoMixer::process, this), [] {}) { // Local video camera is the main participant if (not localInput.empty() && attachHost) { auto videoInput = getVideoInput(localInput); localInputs_.emplace_back(videoInput); attachVideo(videoInput.get(), "", sip_utils::streamId("", sip_utils::DEFAULT_VIDEO_STREAMID)); } loop_.start(); nextProcess_ = std::chrono::steady_clock::now(); JAMI_DBG("[mixer:%s] New instance created", id_.c_str()); } VideoMixer::~VideoMixer() { stopSink(); stopInputs(); loop_.join(); JAMI_DBG("[mixer:%s] Instance destroyed", id_.c_str()); } void VideoMixer::switchInputs(const std::vector<std::string>& inputs) { // Do not stop video inputs that are already there // But only detach it to get new index std::lock_guard lk(localInputsMtx_); decltype(localInputs_) newInputs; for (auto i = 0u; i != inputs.size(); ++i) { auto videoInput = getVideoInput(inputs[i]); // Note, video can be a previously stopped device (eg. restart a screen sharing) // in this case, the videoInput will be found and must be restarted videoInput->restart(); auto onlyDetach = false; auto it = std::find(localInputs_.cbegin(), localInputs_.cend(), videoInput); onlyDetach = it != localInputs_.cend(); newInputs.emplace_back(videoInput); if (onlyDetach) { videoInput->detach(this); localInputs_.erase(it); } } // Stop other video inputs stopInputs(); localInputs_ = std::move(newInputs); // Re-attach videoInput to mixer for (auto i = 0u; i != localInputs_.size(); ++i) attachVideo(localInputs_[i].get(), "", sip_utils::streamId("", fmt::format("video_{}", i))); } void VideoMixer::stopInput(const std::shared_ptr<VideoFrameActiveWriter>& input) { // Detach videoInputs from mixer input->detach(this); #if !VIDEO_CLIENT_INPUT // Stop old VideoInput if (auto oldInput = std::dynamic_pointer_cast<VideoInput>(input)) oldInput->stopInput(); #endif } void VideoMixer::stopInputs() { for (auto& input : localInputs_) stopInput(input); localInputs_.clear(); } void VideoMixer::setActiveStream(const std::string& id) { activeStream_ = id; updateLayout(); } void VideoMixer::updateLayout() { if (activeStream_ == "") currentLayout_ = Layout::GRID; layoutUpdated_ += 1; } void VideoMixer::attachVideo(Observable<std::shared_ptr<MediaFrame>>* frame, const std::string& callId, const std::string& streamId) { if (!frame) return; JAMI_DBG("Attaching video with streamId %s", streamId.c_str()); { std::lock_guard lk(videoToStreamInfoMtx_); videoToStreamInfo_[frame] = StreamInfo {callId, streamId}; } frame->attach(this); } void VideoMixer::detachVideo(Observable<std::shared_ptr<MediaFrame>>* frame) { if (!frame) return; bool detach = false; std::unique_lock lk(videoToStreamInfoMtx_); auto it = videoToStreamInfo_.find(frame); if (it != videoToStreamInfo_.end()) { JAMI_DBG("Detaching video of call %s", it->second.callId.c_str()); detach = true; // Handle the case where the current shown source leave the conference // Note, do not call resetActiveStream() to avoid multiple updates if (verifyActive(it->second.streamId)) activeStream_ = {}; videoToStreamInfo_.erase(it); } lk.unlock(); if (detach) frame->detach(this); } void VideoMixer::attached(Observable<std::shared_ptr<MediaFrame>>* ob) { std::unique_lock lock(rwMutex_); auto src = std::unique_ptr<VideoMixerSource>(new VideoMixerSource); src->render_frame = std::make_shared<VideoFrame>(); src->source = ob; JAMI_DBG("Add new source [%p]", src.get()); sources_.emplace_back(std::move(src)); JAMI_DEBUG("Total sources: {:d}", sources_.size()); updateLayout(); } void VideoMixer::detached(Observable<std::shared_ptr<MediaFrame>>* ob) { std::unique_lock lock(rwMutex_); for (const auto& x : sources_) { if (x->source == ob) { JAMI_DBG("Remove source [%p]", x.get()); sources_.remove(x); JAMI_DEBUG("Total sources: {:d}", sources_.size()); updateLayout(); break; } } } void VideoMixer::update(Observable<std::shared_ptr<MediaFrame>>* ob, const std::shared_ptr<MediaFrame>& frame_p) { std::shared_lock lock(rwMutex_); for (const auto& x : sources_) { if (x->source == ob) { #ifdef RING_ACCEL std::shared_ptr<VideoFrame> frame; try { frame = HardwareAccel::transferToMainMemory(*std::static_pointer_cast<VideoFrame>( frame_p), AV_PIX_FMT_NV12); x->atomic_copy(*std::static_pointer_cast<VideoFrame>(frame)); } catch (const std::runtime_error& e) { JAMI_ERR("[mixer:%s] Accel failure: %s", id_.c_str(), e.what()); return; } #else x->atomic_copy(*std::static_pointer_cast<VideoFrame>(frame_p)); #endif return; } } } void VideoMixer::process() { nextProcess_ += std::chrono::duration_cast<std::chrono::microseconds>(FRAME_DURATION); const auto delay = nextProcess_ - std::chrono::steady_clock::now(); if (delay.count() > 0) std::this_thread::sleep_for(delay); // Nothing to do. if (width_ == 0 or height_ == 0) { return; } VideoFrame& output = getNewFrame(); try { output.reserve(format_, width_, height_); } catch (const std::bad_alloc& e) { JAMI_ERR("[mixer:%s] VideoFrame::allocBuffer() failed", id_.c_str()); return; } libav_utils::fillWithBlack(output.pointer()); { std::lock_guard lk(audioOnlySourcesMtx_); std::shared_lock lock(rwMutex_); int i = 0; bool activeFound = false; bool needsUpdate = layoutUpdated_ > 0; bool successfullyRendered = audioOnlySources_.size() != 0 && sources_.size() == 0; std::vector<SourceInfo> sourcesInfo; sourcesInfo.reserve(sources_.size() + audioOnlySources_.size()); // add all audioonlysources for (auto& [callId, streamId] : audioOnlySources_) { auto active = verifyActive(streamId); if (currentLayout_ != Layout::ONE_BIG or active) { sourcesInfo.emplace_back(SourceInfo {{}, 0, 0, 10, 10, false, callId, streamId}); } if (currentLayout_ == Layout::ONE_BIG) { if (active) successfullyRendered = true; else sourcesInfo.emplace_back(SourceInfo {{}, 0, 0, 0, 0, false, callId, streamId}); // Add all participants info even in ONE_BIG layout. // The width and height set to 0 here will led the peer to filter them out. } } // add video sources for (auto& x : sources_) { /* thread stop pending? */ if (!loop_.isRunning()) return; auto sinfo = streamInfo(x->source); auto activeSource = verifyActive(sinfo.streamId); if (currentLayout_ != Layout::ONE_BIG or activeSource) { // make rendered frame temporarily unavailable for update() // to avoid concurrent access. std::shared_ptr<VideoFrame> input = x->getRenderFrame(); std::shared_ptr<VideoFrame> fooInput = std::make_shared<VideoFrame>(); auto wantedIndex = i; if (currentLayout_ == Layout::ONE_BIG) { wantedIndex = 0; activeFound = true; } else if (currentLayout_ == Layout::ONE_BIG_WITH_SMALL) { if (activeSource) { wantedIndex = 0; activeFound = true; } else if (not activeFound) { wantedIndex += 1; } } auto hasVideo = x->hasVideo; bool blackFrame = false; if (!input->height() or !input->width()) { successfullyRendered = true; fooInput->reserve(format_, width_, height_); blackFrame = true; } else { fooInput.swap(input); } // If orientation changed or if the first valid frame for source // is received -> trigger layout calculation and confInfo update if (x->rotation != fooInput->getOrientation() or !x->w or !x->h) { updateLayout(); needsUpdate = true; } if (needsUpdate) calc_position(x, fooInput, wantedIndex); if (!blackFrame) { if (fooInput) successfullyRendered |= render_frame(output, fooInput, x); else JAMI_WARN("[mixer:%s] Nothing to render for %p", id_.c_str(), x->source); } x->hasVideo = !blackFrame && successfullyRendered; if (hasVideo != x->hasVideo) { updateLayout(); needsUpdate = true; } } else if (needsUpdate) { x->x = 0; x->y = 0; x->w = 0; x->h = 0; x->hasVideo = false; } ++i; } if (needsUpdate and successfullyRendered) { layoutUpdated_ -= 1; if (layoutUpdated_ == 0) { for (auto& x : sources_) { auto sinfo = streamInfo(x->source); sourcesInfo.emplace_back(SourceInfo {x->source, x->x, x->y, x->w, x->h, x->hasVideo, sinfo.callId, sinfo.streamId}); } if (onSourcesUpdated_) onSourcesUpdated_(std::move(sourcesInfo)); } } } output.pointer()->pts = av_rescale_q_rnd(av_gettime() - startTime_, {1, AV_TIME_BASE}, {1, MIXER_FRAMERATE}, static_cast<AVRounding>(AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX)); lastTimestamp_ = output.pointer()->pts; publishFrame(); } bool VideoMixer::render_frame(VideoFrame& output, const std::shared_ptr<VideoFrame>& input, std::unique_ptr<VideoMixerSource>& source) { if (!width_ or !height_ or !input->pointer() or input->pointer()->format == -1) return false; int cell_width = source->w; int cell_height = source->h; int xoff = source->x; int yoff = source->y; int angle = input->getOrientation(); const constexpr char filterIn[] = "mixin"; if (angle != source->rotation) { source->rotationFilter = video::getTransposeFilter(angle, filterIn, input->width(), input->height(), input->format(), false); source->rotation = angle; } std::shared_ptr<VideoFrame> frame; if (source->rotationFilter) { source->rotationFilter->feedInput(input->pointer(), filterIn); frame = std::static_pointer_cast<VideoFrame>( std::shared_ptr<MediaFrame>(source->rotationFilter->readOutput())); } else { frame = input; } scaler_.scale_and_pad(*frame, output, xoff, yoff, cell_width, cell_height, true); return true; } void VideoMixer::calc_position(std::unique_ptr<VideoMixerSource>& source, const std::shared_ptr<VideoFrame>& input, int index) { if (!width_ or !height_) return; // Compute cell size/position int cell_width, cell_height, cellW_off, cellH_off; const int n = currentLayout_ == Layout::ONE_BIG ? 1 : sources_.size(); const int zoom = currentLayout_ == Layout::ONE_BIG_WITH_SMALL ? std::max(MIN_LINE_ZOOM, n) : ceil(sqrt(n)); if (currentLayout_ == Layout::ONE_BIG_WITH_SMALL && index == 0) { // In ONE_BIG_WITH_SMALL, the first line at the top is the previews // The rest is the active source cell_width = width_; cell_height = height_ - height_ / zoom; } else { cell_width = width_ / zoom; cell_height = height_ / zoom; if (n == 1) { // On some platforms (at least macOS/android) - Having one frame at the same // size of the mixer cause it to be grey. // Removing some pixels solve this. We use 16 because it's a multiple of 8 // (value that we prefer for video management) cell_width -= 16; cell_height -= 16; } } if (currentLayout_ == Layout::ONE_BIG_WITH_SMALL) { if (index == 0) { cellW_off = 0; cellH_off = height_ / zoom; // First line height } else { cellW_off = (index - 1) * cell_width; // Show sources in center cellW_off += (width_ - (n - 1) * cell_width) / 2; cellH_off = 0; } } else { cellW_off = (index % zoom) * cell_width; if (currentLayout_ == Layout::GRID && n % zoom != 0 && index >= (zoom * ((n - 1) / zoom))) { // Last line, center participants if not full cellW_off += (width_ - (n % zoom) * cell_width) / 2; } cellH_off = (index / zoom) * cell_height; if (n == 1) { // Centerize (cellwidth = width_ - 16) cellW_off += 8; cellH_off += 8; } } // Compute frame size/position float zoomW, zoomH; int frameW, frameH, frameW_off, frameH_off; if (input->getOrientation() % 180) { // Rotated frame zoomW = (float) input->height() / cell_width; zoomH = (float) input->width() / cell_height; frameH = std::round(input->width() / std::max(zoomW, zoomH)); frameW = std::round(input->height() / std::max(zoomW, zoomH)); } else { zoomW = (float) input->width() / cell_width; zoomH = (float) input->height() / cell_height; frameW = std::round(input->width() / std::max(zoomW, zoomH)); frameH = std::round(input->height() / std::max(zoomW, zoomH)); } // Center the frame in the cell frameW_off = cellW_off + (cell_width - frameW) / 2; frameH_off = cellH_off + (cell_height - frameH) / 2; // Update source's cache source->w = frameW; source->h = frameH; source->x = frameW_off; source->y = frameH_off; } void VideoMixer::setParameters(int width, int height, AVPixelFormat format) { std::unique_lock lock(rwMutex_); width_ = width; height_ = height; format_ = format; // cleanup the previous frame to have a nice copy in rendering method std::shared_ptr<VideoFrame> previous_p(obtainLastFrame()); if (previous_p) libav_utils::fillWithBlack(previous_p->pointer()); startSink(); updateLayout(); startTime_ = av_gettime(); } void VideoMixer::startSink() { stopSink(); if (width_ == 0 or height_ == 0) { JAMI_WARN("[mixer:%s] MX: unable to start with zero-sized output", id_.c_str()); return; } if (not sink_->start()) { JAMI_ERR("[mixer:%s] MX: sink startup failed", id_.c_str()); return; } if (this->attach(sink_.get())) sink_->setFrameSize(width_, height_); } void VideoMixer::stopSink() { this->detach(sink_.get()); sink_->stop(); } int VideoMixer::getWidth() const { return width_; } int VideoMixer::getHeight() const { return height_; } AVPixelFormat VideoMixer::getPixelFormat() const { return format_; } MediaStream VideoMixer::getStream(const std::string& name) const { MediaStream ms; ms.name = name; ms.format = format_; ms.isVideo = true; ms.height = height_; ms.width = width_; ms.frameRate = {MIXER_FRAMERATE, 1}; ms.timeBase = {1, MIXER_FRAMERATE}; ms.firstTimestamp = lastTimestamp_; return ms; } } // namespace video } // namespace jami
19,835
C++
.cpp
544
26.990809
100
0.557469
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,746
filter_transpose.cpp
savoirfairelinux_jami-daemon/src/media/video/filter_transpose.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "filter_transpose.h" #include "logger.h" namespace jami { namespace video { std::unique_ptr<MediaFilter> getTransposeFilter( int rotation, std::string inputName, int width, int height, int format, bool rescale) { JAMI_WARN("Rotation set to %d", rotation); if (rotation == 0) { return {}; } std::stringstream ss; ss << "[" << inputName << "] "; switch (rotation) { case 90: case -270: ss << "transpose=2"; if (rescale) { if (width > height) ss << ", scale=w=-1:h=" << height << ", pad=" << width << ":" << height << ":(ow-iw)/2"; else ss << ", scale=w=" << width << ":h=-1" << ", pad=" << width << ":" << height << ":0:(oh-ih)/2"; } break; case 180: case -180: ss << "transpose=1, transpose=1"; break; case 270: case -90: ss << "transpose=1"; if (rescale) { if (width > height) ss << ", scale=w=-1:h=" << height << ", pad=" << width << ":" << height << ":(ow-iw)/2"; else ss << ", scale=w=" << width << ":h=-1" << ", pad=" << width << ":" << height << ":0:(oh-ih)/2"; } break; default: return {}; } constexpr auto one = rational<int>(1); std::vector<MediaStream> msv; msv.emplace_back(inputName, format, one, width, height, 0, one); std::unique_ptr<MediaFilter> filter(new MediaFilter); auto ret = filter->initialize(ss.str(), msv); if (ret < 0) { JAMI_ERR() << "filter init fail"; return {}; } return filter; } } // namespace video } // namespace jami
2,478
C++
.cpp
75
26.506667
89
0.556994
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
751,747
video_device_monitor.cpp
savoirfairelinux_jami-daemon/src/media/video/video_device_monitor.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <algorithm> #include <cassert> #include <sstream> #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #include <yaml-cpp/yaml.h> #pragma GCC diagnostic pop #include "manager.h" #include "media_const.h" #include "client/videomanager.h" #include "client/ring_signal.h" #include "config/yamlparser.h" #include "logger.h" #include "video_device_monitor.h" namespace jami { namespace video { constexpr const char* const VideoDeviceMonitor::CONFIG_LABEL; using std::map; using std::string; using std::vector; vector<string> VideoDeviceMonitor::getDeviceList() const { std::lock_guard l(lock_); vector<string> ids; ids.reserve(devices_.size()); for (const auto& dev : devices_) { if (dev.name != DEVICE_DESKTOP) ids.emplace_back(dev.getDeviceId()); } return ids; } libjami::VideoCapabilities VideoDeviceMonitor::getCapabilities(const string& id) const { std::lock_guard l(lock_); const auto iter = findDeviceById(id); if (iter == devices_.end()) return libjami::VideoCapabilities(); return iter->getCapabilities(); } VideoSettings VideoDeviceMonitor::getSettings(const string& id) { std::lock_guard l(lock_); const auto prefIter = findPreferencesById(id); if (prefIter == preferences_.end()) return VideoSettings(); return *prefIter; } void VideoDeviceMonitor::applySettings(const string& id, const VideoSettings& settings) { std::lock_guard l(lock_); const auto iter = findDeviceById(id); if (iter == devices_.end()) return; iter->applySettings(settings); auto it = findPreferencesById(settings.unique_id); if (it != preferences_.end()) (*it) = settings; } string VideoDeviceMonitor::getDefaultDevice() const { std::lock_guard l(lock_); const auto it = findDeviceById(defaultDevice_); if (it == std::end(devices_) || it->getDeviceId() == DEVICE_DESKTOP) return {}; return it->getDeviceId(); } std::string VideoDeviceMonitor::getMRLForDefaultDevice() const { std::lock_guard l(lock_); const auto it = findDeviceById(defaultDevice_); if (it == std::end(devices_) || it->getDeviceId() == DEVICE_DESKTOP) return {}; static const std::string sep = libjami::Media::VideoProtocolPrefix::SEPARATOR; return libjami::Media::VideoProtocolPrefix::CAMERA + sep + it->getDeviceId(); } bool VideoDeviceMonitor::setDefaultDevice(const std::string& id) { std::lock_guard l(lock_); const auto itDev = findDeviceById(id); if (itDev != devices_.end()) { if (defaultDevice_ == itDev->getDeviceId()) return false; defaultDevice_ = itDev->getDeviceId(); // place it at the begining of the prefs auto itPref = findPreferencesById(itDev->getDeviceId()); if (itPref != preferences_.end()) { auto settings = *itPref; preferences_.erase(itPref); preferences_.insert(preferences_.begin(), settings); } else { preferences_.insert(preferences_.begin(), itDev->getSettings()); } return true; } return false; } void VideoDeviceMonitor::setDeviceOrientation(const std::string& id, int angle) { std::lock_guard l(lock_); const auto itd = findDeviceById(id); if (itd != devices_.cend()) { itd->setOrientation(angle); } else { JAMI_WARN("Unable to find device %s to set orientation %d", id.c_str(), angle); } } DeviceParams VideoDeviceMonitor::getDeviceParams(const std::string& id) const { std::lock_guard l(lock_); const auto itd = findDeviceById(id); if (itd == devices_.cend()) return DeviceParams(); return itd->getDeviceParams(); } static void giveUniqueName(VideoDevice& dev, const vector<VideoDevice>& devices) { std::string suffix; uint64_t number = 2; auto unique = true; for (;; unique = static_cast<bool>(++number)) { for (const auto& s : devices) unique &= static_cast<bool>(s.name.compare(dev.name + suffix)); if (unique) return (void) (dev.name += suffix); suffix = " (" + std::to_string(number) + ")"; } } static void notify() { if (Manager::initialized) { emitSignal<libjami::VideoSignal::DeviceEvent>(); } } bool VideoDeviceMonitor::addDevice(const string& id, const std::vector<std::map<std::string, std::string>>& devInfo) { try { std::lock_guard l(lock_); if (findDeviceById(id) != devices_.end()) return false; // instantiate a new unique device VideoDevice dev {id, devInfo}; if (dev.getChannelList().empty()) return false; giveUniqueName(dev, devices_); // restore its preferences if any, or store the defaults auto it = findPreferencesById(id); if (it != preferences_.end()) { dev.applySettings(*it); } else { dev.applySettings(dev.getDefaultSettings()); preferences_.emplace_back(dev.getSettings()); } // in case there is no default device on a fresh run if (defaultDevice_.empty() && id != DEVICE_DESKTOP) defaultDevice_ = dev.getDeviceId(); devices_.emplace_back(std::move(dev)); } catch (const std::exception& e) { JAMI_ERR("Failed to add device %s: %s", id.c_str(), e.what()); return false; } notify(); return true; } void VideoDeviceMonitor::removeDevice(const string& id) { { std::lock_guard l(lock_); const auto it = findDeviceById(id); if (it == devices_.end()) return; devices_.erase(it); if (defaultDevice_.find(id) != std::string::npos) { defaultDevice_.clear(); for (const auto& dev : devices_) if (dev.name != DEVICE_DESKTOP) { defaultDevice_ = dev.getDeviceId(); break; } } } notify(); } vector<VideoDevice>::iterator VideoDeviceMonitor::findDeviceById(const string& id) { for (auto it = devices_.begin(); it != devices_.end(); ++it) if (it->getDeviceId().find(id) != std::string::npos) return it; return devices_.end(); } vector<VideoDevice>::const_iterator VideoDeviceMonitor::findDeviceById(const string& id) const { for (auto it = devices_.cbegin(); it != devices_.cend(); ++it) if (it->getDeviceId().find(id) != std::string::npos) return it; return devices_.end(); } vector<VideoSettings>::iterator VideoDeviceMonitor::findPreferencesById(const string& id) { for (auto it = preferences_.begin(); it != preferences_.end(); ++it) if (it->unique_id.find(id) != std::string::npos) return it; return preferences_.end(); } void VideoDeviceMonitor::overwritePreferences(const VideoSettings& settings) { auto it = findPreferencesById(settings.unique_id); if (it != preferences_.end()) preferences_.erase(it); preferences_.emplace_back(settings); } void VideoDeviceMonitor::serialize(YAML::Emitter& out) const { std::lock_guard l(lock_); out << YAML::Key << "devices" << YAML::Value << preferences_; } void VideoDeviceMonitor::unserialize(const YAML::Node& in) { std::lock_guard l(lock_); const auto& node = in[CONFIG_LABEL]; /* load the device list from the "video" YAML section */ const auto& devices = node["devices"]; for (const auto& dev : devices) { VideoSettings pref = dev.as<VideoSettings>(); if (pref.unique_id.empty()) continue; // discard malformed section overwritePreferences(pref); auto itd = findDeviceById(pref.unique_id); if (itd != devices_.end()) itd->applySettings(pref); } // Restore the default device if present, or select the first one const string prefId = preferences_.empty() ? "" : preferences_[0].unique_id; const auto devIter = findDeviceById(prefId); if (devIter != devices_.end() && prefId != DEVICE_DESKTOP) { defaultDevice_ = devIter->getDeviceId(); } else { defaultDevice_.clear(); for (const auto& dev : devices_) if (dev.name != DEVICE_DESKTOP) { defaultDevice_ = dev.getDeviceId(); break; } } } } // namespace video } // namespace jami
9,164
C++
.cpp
282
27.06383
93
0.647551
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,748
accel.cpp
savoirfairelinux_jami-daemon/src/media/video/accel.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <algorithm> #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "media_buffer.h" #include "string_utils.h" #include "fileutils.h" #include "logger.h" #include "accel.h" namespace jami { namespace video { struct HardwareAPI { std::string name; AVHWDeviceType hwType; AVPixelFormat format; AVPixelFormat swFormat; std::vector<AVCodecID> supportedCodecs; std::list<std::pair<std::string, DeviceState>> possible_devices; bool dynBitrate; }; static std::list<HardwareAPI> apiListDec = { {"nvdec", AV_HWDEVICE_TYPE_CUDA, AV_PIX_FMT_CUDA, AV_PIX_FMT_NV12, {AV_CODEC_ID_H264, AV_CODEC_ID_HEVC, AV_CODEC_ID_VP8, AV_CODEC_ID_MJPEG}, {{"default", DeviceState::NOT_TESTED}, {"1", DeviceState::NOT_TESTED}, {"2", DeviceState::NOT_TESTED}}, false}, {"vaapi", AV_HWDEVICE_TYPE_VAAPI, AV_PIX_FMT_VAAPI, AV_PIX_FMT_NV12, {AV_CODEC_ID_H264, AV_CODEC_ID_MPEG4, AV_CODEC_ID_VP8}, {{"default", DeviceState::NOT_TESTED}, {"/dev/dri/renderD128", DeviceState::NOT_TESTED}, {"/dev/dri/renderD129", DeviceState::NOT_TESTED}, {":0", DeviceState::NOT_TESTED}}, false}, {"vdpau", AV_HWDEVICE_TYPE_VDPAU, AV_PIX_FMT_VDPAU, AV_PIX_FMT_NV12, {AV_CODEC_ID_H264, AV_CODEC_ID_MPEG4}, {{"default", DeviceState::NOT_TESTED}}, false}, {"videotoolbox", AV_HWDEVICE_TYPE_VIDEOTOOLBOX, AV_PIX_FMT_VIDEOTOOLBOX, AV_PIX_FMT_NV12, {AV_CODEC_ID_H264, AV_CODEC_ID_HEVC, AV_CODEC_ID_MPEG4}, {{"default", DeviceState::NOT_TESTED}}, false}, {"qsv", AV_HWDEVICE_TYPE_QSV, AV_PIX_FMT_QSV, AV_PIX_FMT_NV12, {AV_CODEC_ID_H264, AV_CODEC_ID_HEVC, AV_CODEC_ID_MJPEG, AV_CODEC_ID_VP8, AV_CODEC_ID_VP9}, {{"default", DeviceState::NOT_TESTED}}, false}, }; static std::list<HardwareAPI> apiListEnc = { {"nvenc", AV_HWDEVICE_TYPE_CUDA, AV_PIX_FMT_CUDA, AV_PIX_FMT_NV12, {AV_CODEC_ID_H264, AV_CODEC_ID_HEVC}, {{"default", DeviceState::NOT_TESTED}, {"1", DeviceState::NOT_TESTED}, {"2", DeviceState::NOT_TESTED}}, true}, {"vaapi", AV_HWDEVICE_TYPE_VAAPI, AV_PIX_FMT_VAAPI, AV_PIX_FMT_NV12, {AV_CODEC_ID_H264, AV_CODEC_ID_HEVC, AV_CODEC_ID_VP8}, {{"default", DeviceState::NOT_TESTED}, {"/dev/dri/renderD128", DeviceState::NOT_TESTED}, {"/dev/dri/renderD129", DeviceState::NOT_TESTED}, {":0", DeviceState::NOT_TESTED}}, false}, {"videotoolbox", AV_HWDEVICE_TYPE_VIDEOTOOLBOX, AV_PIX_FMT_VIDEOTOOLBOX, AV_PIX_FMT_NV12, {AV_CODEC_ID_H264, AV_CODEC_ID_HEVC}, {{"default", DeviceState::NOT_TESTED}}, false}, // Disable temporarily QSVENC // {"qsv", // AV_HWDEVICE_TYPE_QSV, // AV_PIX_FMT_QSV, // AV_PIX_FMT_NV12, // {AV_CODEC_ID_H264, AV_CODEC_ID_HEVC, AV_CODEC_ID_MJPEG, AV_CODEC_ID_VP8}, // {{"default", DeviceState::NOT_TESTED}}, // false}, }; HardwareAccel::HardwareAccel(AVCodecID id, const std::string& name, AVHWDeviceType hwType, AVPixelFormat format, AVPixelFormat swFormat, CodecType type, bool dynBitrate) : id_(id) , name_(name) , hwType_(hwType) , format_(format) , swFormat_(swFormat) , type_(type) , dynBitrate_(dynBitrate) {} HardwareAccel::~HardwareAccel() { if (deviceCtx_) av_buffer_unref(&deviceCtx_); if (framesCtx_) av_buffer_unref(&framesCtx_); } static AVPixelFormat getFormatCb(AVCodecContext* codecCtx, const AVPixelFormat* formats) { auto accel = static_cast<HardwareAccel*>(codecCtx->opaque); for (int i = 0; formats[i] != AV_PIX_FMT_NONE; ++i) { if (accel && formats[i] == accel->getFormat()) { // found hardware format for codec with api JAMI_DBG() << "Found compatible hardware format for " << avcodec_get_name(static_cast<AVCodecID>(accel->getCodecId())) << " decoder with " << accel->getName(); // hardware tends to under-report supported levels codecCtx->hwaccel_flags |= AV_HWACCEL_FLAG_IGNORE_LEVEL; return formats[i]; } } return AV_PIX_FMT_NONE; } int HardwareAccel::init_device(const char* name, const char* device, int flags) { const AVHWDeviceContext* dev = nullptr; // Create device ctx int err; err = av_hwdevice_ctx_create(&deviceCtx_, hwType_, device, NULL, flags); if (err < 0) { JAMI_DBG("Failed to create %s device: %d.\n", name, err); return 1; } // Verify that the device create correspond to api dev = (AVHWDeviceContext*) deviceCtx_->data; if (dev->type != hwType_) { JAMI_DBG("Device created as type %d has type %d.", hwType_, dev->type); av_buffer_unref(&deviceCtx_); return -1; } JAMI_DBG("Device type %s successfully created.", name); return 0; } int HardwareAccel::init_device_type(std::string& dev) { AVHWDeviceType check; const char* name; int err; name = av_hwdevice_get_type_name(hwType_); if (!name) { JAMI_DBG("No name available for device type %d.", hwType_); return -1; } check = av_hwdevice_find_type_by_name(name); if (check != hwType_) { JAMI_DBG("Type %d maps to name %s maps to type %d.", hwType_, name, check); return -1; } JAMI_WARN("-- Starting %s init for %s with default device.", (type_ == CODEC_ENCODER) ? "encoding" : "decoding", name); if (possible_devices_->front().second != DeviceState::NOT_USABLE) { if (name_ == "qsv") err = init_device(name, "auto", 0); else err = init_device(name, nullptr, 0); if (err == 0) { JAMI_DBG("-- Init passed for %s with default device.", name); possible_devices_->front().second = DeviceState::USABLE; dev = "default"; return 0; } else { possible_devices_->front().second = DeviceState::NOT_USABLE; JAMI_DBG("-- Init failed for %s with default device.", name); } } for (auto& device : *possible_devices_) { if (device.second == DeviceState::NOT_USABLE) continue; JAMI_WARN("-- Init %s for %s with device %s.", (type_ == CODEC_ENCODER) ? "encoding" : "decoding", name, device.first.c_str()); err = init_device(name, device.first.c_str(), 0); if (err == 0) { JAMI_DBG("-- Init passed for %s with device %s.", name, device.first.c_str()); device.second = DeviceState::USABLE; dev = device.first; return 0; } else { device.second = DeviceState::NOT_USABLE; JAMI_DBG("-- Init failed for %s with device %s.", name, device.first.c_str()); } } return -1; } std::string HardwareAccel::getCodecName() const { if (type_ == CODEC_DECODER) { return avcodec_get_name(id_); } else if (type_ == CODEC_ENCODER) { return fmt::format("{}_{}", avcodec_get_name(id_), name_); } return {}; } std::unique_ptr<VideoFrame> HardwareAccel::transfer(const VideoFrame& frame) { int ret = 0; if (type_ == CODEC_DECODER) { auto input = frame.pointer(); if (input->format != format_) { JAMI_ERR() << "Frame format mismatch: expected " << av_get_pix_fmt_name(format_) << ", got " << av_get_pix_fmt_name(static_cast<AVPixelFormat>(input->format)); return nullptr; } return transferToMainMemory(frame, swFormat_); } else if (type_ == CODEC_ENCODER) { auto input = frame.pointer(); if (input->format != swFormat_) { JAMI_ERR() << "Frame format mismatch: expected " << av_get_pix_fmt_name(swFormat_) << ", got " << av_get_pix_fmt_name(static_cast<AVPixelFormat>(input->format)); return nullptr; } auto framePtr = std::make_unique<VideoFrame>(); auto hwFrame = framePtr->pointer(); if ((ret = av_hwframe_get_buffer(framesCtx_, hwFrame, 0)) < 0) { JAMI_ERR() << "Failed to allocate hardware buffer: " << libav_utils::getError(ret).c_str(); return nullptr; } if (!hwFrame->hw_frames_ctx) { JAMI_ERR() << "Failed to allocate hardware buffer: Unable to allocate memory"; return nullptr; } if ((ret = av_hwframe_transfer_data(hwFrame, input, 0)) < 0) { JAMI_ERR() << "Failed to push frame to GPU: " << libav_utils::getError(ret).c_str(); return nullptr; } hwFrame->pts = input->pts; // transfer does not copy timestamp return framePtr; } else { JAMI_ERR() << "Invalid hardware accelerator"; return nullptr; } } void HardwareAccel::setDetails(AVCodecContext* codecCtx) { if (type_ == CODEC_DECODER) { codecCtx->hw_device_ctx = av_buffer_ref(deviceCtx_); codecCtx->get_format = getFormatCb; } else if (type_ == CODEC_ENCODER) { if (framesCtx_) // encoder doesn't need a device context, only a frame context codecCtx->hw_frames_ctx = av_buffer_ref(framesCtx_); } } bool HardwareAccel::initFrame() { int ret = 0; if (!deviceCtx_) { JAMI_ERR() << "Unable to initialize hardware frames without a valid hardware device"; return false; } framesCtx_ = av_hwframe_ctx_alloc(deviceCtx_); if (!framesCtx_) return false; auto ctx = reinterpret_cast<AVHWFramesContext*>(framesCtx_->data); ctx->format = format_; ctx->sw_format = swFormat_; ctx->width = width_; ctx->height = height_; ctx->initial_pool_size = 20; // TODO try other values if ((ret = av_hwframe_ctx_init(framesCtx_)) < 0) { JAMI_ERR("Failed to initialize hardware frame context: %s (%d)", libav_utils::getError(ret).c_str(), ret); av_buffer_unref(&framesCtx_); } return ret >= 0; } bool HardwareAccel::linkHardware(AVBufferRef* framesCtx) { if (framesCtx) { // Force sw_format to match swFormat_. Frame is never transferred to main // memory when hardware is linked, so the sw_format doesn't matter. auto hw = reinterpret_cast<AVHWFramesContext*>(framesCtx->data); hw->sw_format = swFormat_; if (framesCtx_) av_buffer_unref(&framesCtx_); framesCtx_ = av_buffer_ref(framesCtx); if ((linked_ = (framesCtx_ != nullptr))) { JAMI_DBG() << "Hardware transcoding pipeline successfully set up for" << " encoder '" << getCodecName() << "'"; } return linked_; } else { return false; } } std::unique_ptr<VideoFrame> HardwareAccel::transferToMainMemory(const VideoFrame& frame, AVPixelFormat desiredFormat) { auto input = frame.pointer(); if (not input) throw std::runtime_error("Unable to transfer null frame"); auto desc = av_pix_fmt_desc_get(static_cast<AVPixelFormat>(input->format)); if (!desc) { throw std::runtime_error("Unable to transfer frame with invalid format"); } auto out = std::make_unique<VideoFrame>(); if (not(desc->flags & AV_PIX_FMT_FLAG_HWACCEL)) { out->copyFrom(frame); return out; } auto output = out->pointer(); output->format = desiredFormat; int ret = av_hwframe_transfer_data(output, input, 0); if (ret < 0) { throw std::runtime_error("Unable to transfer the frame from GPU"); } output->pts = input->pts; if (AVFrameSideData* side_data = av_frame_get_side_data(input, AV_FRAME_DATA_DISPLAYMATRIX)) av_frame_new_side_data_from_buf(output, AV_FRAME_DATA_DISPLAYMATRIX, av_buffer_ref(side_data->buf)); return out; } int HardwareAccel::initAPI(bool linkable, AVBufferRef* framesCtx) { const auto& codecName = getCodecName(); std::string device; auto ret = init_device_type(device); if (ret == 0) { bool link = false; if (linkable && framesCtx) link = linkHardware(framesCtx); // we don't need frame context for videotoolbox if (hwType_ == AV_HWDEVICE_TYPE_VIDEOTOOLBOX || link || initFrame()) { return 0; } } return -1; } std::list<HardwareAccel> HardwareAccel::getCompatibleAccel(AVCodecID id, int width, int height, CodecType type) { std::list<HardwareAccel> l; const auto& list = (type == CODEC_ENCODER) ? &apiListEnc : &apiListDec; for (auto& api : *list) { const auto& it = std::find(api.supportedCodecs.begin(), api.supportedCodecs.end(), id); if (it != api.supportedCodecs.end()) { auto hwtype = AV_HWDEVICE_TYPE_NONE; while ((hwtype = av_hwdevice_iterate_types(hwtype)) != AV_HWDEVICE_TYPE_NONE) { if (hwtype == api.hwType) { auto accel = HardwareAccel(id, api.name, api.hwType, api.format, api.swFormat, type, api.dynBitrate); accel.height_ = height; accel.width_ = width; accel.possible_devices_ = &api.possible_devices; l.emplace_back(std::move(accel)); } } } } return l; } } // namespace video } // namespace jami
14,755
C++
.cpp
407
28.257985
108
0.586002
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,749
video_scaler.cpp
savoirfairelinux_jami-daemon/src/media/video/video_scaler.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "libav_deps.h" // MUST BE INCLUDED FIRST #include "libav_utils.h" #include "video_scaler.h" #include "media_buffer.h" #include "logger.h" #include <cassert> namespace jami { namespace video { VideoScaler::VideoScaler() : ctx_(0) , mode_(SWS_FAST_BILINEAR) , tmp_data_() {} VideoScaler::~VideoScaler() { sws_freeContext(ctx_); } void VideoScaler::scale(const VideoFrame& input, VideoFrame& output){ scale(input.pointer(), output.pointer()); } void VideoScaler::scale(const AVFrame* input_frame, AVFrame* output_frame) { ctx_ = sws_getCachedContext(ctx_, input_frame->width, input_frame->height, (AVPixelFormat) input_frame->format, output_frame->width, output_frame->height, (AVPixelFormat) output_frame->format, mode_, NULL, NULL, NULL); if (!ctx_) { JAMI_ERR("Unable to create a scaler context"); return; } sws_scale(ctx_, input_frame->data, input_frame->linesize, 0, input_frame->height, output_frame->data, output_frame->linesize); } void VideoScaler::scale_with_aspect(const VideoFrame& input, VideoFrame& output) { if (input.width() == output.width() && input.height() == output.height()) { if (input.format() != output.format()) { auto outPtr = convertFormat(input, (AVPixelFormat) output.format()); output.copyFrom(*outPtr); } else { output.copyFrom(input); } } else { auto output_frame = output.pointer(); scale_and_pad(input, output, 0, 0, output_frame->width, output_frame->height, true); } } void VideoScaler::scale_and_pad(const VideoFrame& input, VideoFrame& output, unsigned xoff, unsigned yoff, unsigned dest_width, unsigned dest_height, bool keep_aspect) { const auto input_frame = input.pointer(); auto output_frame = output.pointer(); /* Correct destination width/height and offset if we need to keep input * frame aspect. */ if (keep_aspect) { const float local_ratio = (float) dest_width / dest_height; const float input_ratio = (float) input_frame->width / input_frame->height; if (local_ratio > input_ratio) { auto old_dest_width = dest_width; dest_width = dest_height * input_ratio; xoff += (old_dest_width - dest_width) / 2; } else { auto old_dest_heigth = dest_height; dest_height = dest_width / input_ratio; yoff += (old_dest_heigth - dest_height) / 2; } } // buffer overflow checks if ((xoff + dest_width > (unsigned) output_frame->width) || (yoff + dest_height > (unsigned) output_frame->height)) { JAMI_ERR("Unable to scale video"); return; } ctx_ = sws_getCachedContext(ctx_, input_frame->width, input_frame->height, (AVPixelFormat) input_frame->format, dest_width, dest_height, (AVPixelFormat) output_frame->format, mode_, NULL, NULL, NULL); if (!ctx_) { JAMI_ERR("Unable to create a scaler context"); return; } // Make an offset'ed copy of output data from xoff and yoff const auto out_desc = av_pix_fmt_desc_get((AVPixelFormat) output_frame->format); memset(tmp_data_, 0, sizeof(tmp_data_)); for (int i = 0; i < 4 && output_frame->linesize[i]; i++) { signed x_shift = xoff, y_shift = yoff; if (i == 1 || i == 2) { x_shift = -((-x_shift) >> out_desc->log2_chroma_w); y_shift = -((-y_shift) >> out_desc->log2_chroma_h); } auto x_step = out_desc->comp[i].step; tmp_data_[i] = output_frame->data[i] + y_shift * output_frame->linesize[i] + x_shift * x_step; } sws_scale(ctx_, input_frame->data, input_frame->linesize, 0, input_frame->height, tmp_data_, output_frame->linesize); } std::unique_ptr<VideoFrame> VideoScaler::convertFormat(const VideoFrame& input, AVPixelFormat pix) { auto output = std::make_unique<VideoFrame>(); output->reserve(pix, input.width(), input.height()); scale(input, *output); av_frame_copy_props(output->pointer(), input.pointer()); return output; } void VideoScaler::reset() { if (ctx_) { sws_freeContext(ctx_); ctx_ = nullptr; } } } // namespace video } // namespace jami
5,945
C++
.cpp
166
25.746988
92
0.547743
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,750
video_sender.cpp
savoirfairelinux_jami-daemon/src/media/video/video_sender.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "video_sender.h" #include "video_mixer.h" #include "socket_pair.h" #include "client/videomanager.h" #include "logger.h" #include "manager.h" #include "media_device.h" #include "sip/sipcall.h" #ifdef RING_ACCEL #include "accel.h" #endif #include <map> #include <unistd.h> namespace jami { namespace video { using std::string; VideoSender::VideoSender(const std::string& dest, const MediaStream& opts, const MediaDescription& args, SocketPair& socketPair, const uint16_t seqVal, uint16_t mtu, bool enableHwAccel) : muxContext_(socketPair.createIOContext(mtu)) , videoEncoder_(new MediaEncoder) { keyFrameFreq_ = opts.frameRate.numerator() * KEY_FRAME_PERIOD; videoEncoder_->openOutput(dest, "rtp"); videoEncoder_->setOptions(opts); videoEncoder_->setOptions(args); #ifdef RING_ACCEL videoEncoder_->enableAccel(enableHwAccel and Manager::instance().videoPreferences.getEncodingAccelerated()); #endif videoEncoder_->addStream(*args.codec); videoEncoder_->setInitSeqVal(seqVal); videoEncoder_->setIOContext(muxContext_->getContext()); } void VideoSender::encodeAndSendVideo(const std::shared_ptr<VideoFrame>& input_frame) { int angle = input_frame->getOrientation(); if (rotation_ != angle) { rotation_ = angle; if (changeOrientationCallback_) changeOrientationCallback_(rotation_); } if (auto packet = input_frame->packet()) { videoEncoder_->send(*packet); } else { bool is_keyframe = forceKeyFrame_ > 0 or (keyFrameFreq_ > 0 and (frameNumber_ % keyFrameFreq_) == 0); if (is_keyframe) --forceKeyFrame_; if (videoEncoder_->encode(input_frame, is_keyframe, frameNumber_++) < 0) JAMI_ERR("encoding failed"); } #ifdef DEBUG_SDP if (frameNumber_ == 1) // video stream is lazy initialized, wait for first frame videoEncoder_->print_sdp(); #endif } void VideoSender::update(Observable<std::shared_ptr<MediaFrame>>* /*obs*/, const std::shared_ptr<MediaFrame>& frame_p) { encodeAndSendVideo(std::dynamic_pointer_cast<VideoFrame>(frame_p)); } void VideoSender::forceKeyFrame() { JAMI_DBG("Key frame requested"); ++forceKeyFrame_; } uint16_t VideoSender::getLastSeqValue() { return videoEncoder_->getLastSeqValue(); } void VideoSender::setChangeOrientationCallback(std::function<void(int)> cb) { changeOrientationCallback_ = std::move(cb); } int VideoSender::setBitrate(uint64_t br) { // The encoder may be destroy during a bitrate change // when a codec parameter like auto quality change if (!videoEncoder_) return -1; // NOK return videoEncoder_->setBitrate(br); } } // namespace video } // namespace jami
3,668
C++
.cpp
111
27.873874
98
0.679187
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,751
video_receive_thread.cpp
savoirfairelinux_jami-daemon/src/media/video/video_receive_thread.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "libav_deps.h" // MUST BE INCLUDED FIRST #include "video_receive_thread.h" #include "media/media_decoder.h" #include "socket_pair.h" #include "manager.h" #include "client/videomanager.h" #include "sinkclient.h" #include "logger.h" extern "C" { #include <libavutil/display.h> } #include <unistd.h> #include <map> namespace jami { namespace video { using std::string; VideoReceiveThread::VideoReceiveThread(const std::string& id, bool useSink, const std::string& sdp, uint16_t mtu) : VideoGenerator::VideoGenerator() , args_() , id_(id) , useSink_(useSink) , stream_(sdp) , sdpContext_(stream_.str().size(), false, &readFunction, 0, 0, this) , sink_ {Manager::instance().createSinkClient(id)} , mtu_(mtu) , loop_(std::bind(&VideoReceiveThread::setup, this), std::bind(&VideoReceiveThread::decodeFrame, this), std::bind(&VideoReceiveThread::cleanup, this)) { JAMI_DBG("[%p] Instance created", this); } VideoReceiveThread::~VideoReceiveThread() { loop_.join(); JAMI_DBG("[%p] Instance destroyed", this); } void VideoReceiveThread::startLoop() { JAMI_DBG("[%p] Starting receiver's loop", this); loop_.start(); } void VideoReceiveThread::stopLoop() { if (loop_.isStopping()) return; JAMI_DBG("[%p] Stopping receiver's loop and waiting for the thread to exit ...", this); loop_.stop(); loop_.join(); JAMI_DBG("[%p] Receiver's thread exited", this); } // We do this setup here instead of the constructor because we don't want the // main thread to block while this executes, so it happens in the video thread. bool VideoReceiveThread::setup() { JAMI_DBG("[%p] Setupping video receiver", this); videoDecoder_.reset(new MediaDecoder([this](const std::shared_ptr<MediaFrame>& frame) mutable { libav_utils::AVBufferPtr displayMatrix; { std::lock_guard l(rotationMtx_); if (displayMatrix_) displayMatrix.reset(av_buffer_ref(displayMatrix_.get())); } if (displayMatrix) av_frame_new_side_data_from_buf(frame->pointer(), AV_FRAME_DATA_DISPLAYMATRIX, displayMatrix.release()); publishFrame(std::static_pointer_cast<VideoFrame>(frame)); })); videoDecoder_->setContextCallback([this]() { if (recorderCallback_) recorderCallback_(getInfo()); }); videoDecoder_->setResolutionChangedCallback([this](int width, int height) { dstWidth_ = width; dstHeight_ = height; sink_->setFrameSize(dstWidth_, dstHeight_); }); dstWidth_ = args_.width; dstHeight_ = args_.height; static const std::string SDP_FILENAME = "dummyFilename"; if (args_.input.empty()) { args_.format = "sdp"; args_.input = SDP_FILENAME; } else if (args_.input.substr(0, strlen("/dev/video")) == "/dev/video") { // it's a v4l device if starting with /dev/video // FIXME: This is not a robust way of checking if we mean to use a // v4l2 device args_.format = "video4linux2"; } videoDecoder_->setInterruptCallback(interruptCb, this); if (args_.input == SDP_FILENAME) { // Force custom_io so the SDP demuxer will not open any UDP connections // We need it to use ICE transport. args_.sdp_flags = "custom_io"; if (stream_.str().empty()) { JAMI_ERR("No SDP loaded"); return false; } videoDecoder_->setIOContext(&sdpContext_); } if (videoDecoder_->openInput(args_)) { JAMI_ERR("Unable to open input \"%s\"", args_.input.c_str()); return false; } if (args_.input == SDP_FILENAME) { // Now replace our custom AVIOContext with one that will read packets videoDecoder_->setIOContext(demuxContext_.get()); } return true; } void VideoReceiveThread::cleanup() { JAMI_DBG("[%p] Stopping receiver", this); detach(sink_.get()); sink_->stop(); videoDecoder_.reset(); } // This callback is used by libav internally to break out of blocking calls int VideoReceiveThread::interruptCb(void* data) { const auto context = static_cast<VideoReceiveThread*>(data); return not context->loop_.isRunning(); } int VideoReceiveThread::readFunction(void* opaque, uint8_t* buf, int buf_size) { std::istream& is = static_cast<VideoReceiveThread*>(opaque)->stream_; is.read(reinterpret_cast<char*>(buf), buf_size); auto count = is.gcount(); if (count != 0) return count; else return AVERROR_EOF; } void VideoReceiveThread::addIOContext(SocketPair& socketPair) { demuxContext_.reset(socketPair.createIOContext(mtu_)); } void VideoReceiveThread::setRecorderCallback( const std::function<void(const MediaStream& ms)>& cb) { recorderCallback_ = cb; if (videoDecoder_) videoDecoder_->setContextCallback([this]() { if (recorderCallback_) recorderCallback_(getInfo()); }); } void VideoReceiveThread::decodeFrame() { if (not loop_.isRunning()) return; if (not isVideoConfigured_) { if (!configureVideoOutput()) { JAMI_ERROR("[{:p}] Failed to configure video output", fmt::ptr(this)); return; } else { JAMI_LOG("[{:p}] Decoder configured, starting decoding", fmt::ptr(this)); } } auto status = videoDecoder_->decode(); if (status == MediaDemuxer::Status::EndOfFile) { JAMI_LOG("[{:p}] End of file", fmt::ptr(this)); loop_.stop(); } else if (status == MediaDemuxer::Status::ReadError) { JAMI_ERROR("[{:p}] Decoding error: %s", fmt::ptr(this), MediaDemuxer::getStatusStr(status)); } else if (status == MediaDemuxer::Status::FallBack) { if (keyFrameRequestCallback_) keyFrameRequestCallback_(); } } bool VideoReceiveThread::configureVideoOutput() { assert(not isVideoConfigured_); JAMI_DBG("[%p] Configuring video output", this); if (not loop_.isRunning()) { JAMI_WARN("[%p] Unable to configure video output, the loop is not running!", this); return false; } if (videoDecoder_->setupVideo() < 0) { JAMI_ERR("decoder IO startup failed"); stopLoop(); return false; } // Default size from input video if (dstWidth_ == 0 and dstHeight_ == 0) { dstWidth_ = videoDecoder_->getWidth(); dstHeight_ = videoDecoder_->getHeight(); } if (not sink_->start()) { JAMI_ERR("RX: sink startup failed"); stopLoop(); return false; } if (useSink_) startSink(); if (onSuccessfulSetup_) onSuccessfulSetup_(MEDIA_VIDEO, 1); return isVideoConfigured_ = true; } void VideoReceiveThread::stopSink() { JAMI_DBG("[%p] Stopping sink", this); if (!loop_.isRunning()) return; detach(sink_.get()); sink_->setFrameSize(0, 0); } void VideoReceiveThread::startSink() { JAMI_DBG("[%p] Starting sink", this); if (!loop_.isRunning()) return; if (dstWidth_ > 0 and dstHeight_ > 0 and attach(sink_.get())) sink_->setFrameSize(dstWidth_, dstHeight_); } int VideoReceiveThread::getWidth() const { return dstWidth_; } int VideoReceiveThread::getHeight() const { return dstHeight_; } AVPixelFormat VideoReceiveThread::getPixelFormat() const { if (videoDecoder_) return videoDecoder_->getPixelFormat(); return {}; } MediaStream VideoReceiveThread::getInfo() const { if (videoDecoder_) return videoDecoder_->getStream("v:remote"); return {}; } void VideoReceiveThread::setRotation(int angle) { libav_utils::AVBufferPtr displayMatrix(av_buffer_alloc(sizeof(int32_t) * 9)); av_display_rotation_set(reinterpret_cast<int32_t*>(displayMatrix->data), angle); std::lock_guard l(rotationMtx_); displayMatrix_ = std::move(displayMatrix); } } // namespace video } // namespace jami
8,910
C++
.cpp
282
26.049645
100
0.643623
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,752
video_input.cpp
savoirfairelinux_jami-daemon/src/media/video/video_input.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "video_input.h" #include "media_decoder.h" #include "media_const.h" #include "manager.h" #include "client/videomanager.h" #include "client/ring_signal.h" #include "sinkclient.h" #include "logger.h" #include "media/media_buffer.h" #include <libavformat/avio.h> #include <string> #include <sstream> #include <cassert> #ifdef _MSC_VER #include <io.h> // for access #else #include <sys/syscall.h> #include <unistd.h> #endif extern "C" { #include <libavutil/display.h> } namespace jami { namespace video { static constexpr unsigned default_grab_width = 640; static constexpr unsigned default_grab_height = 480; VideoInput::VideoInput(VideoInputMode inputMode, const std::string& resource, const std::string& sink) : VideoGenerator::VideoGenerator() , loop_(std::bind(&VideoInput::setup, this), std::bind(&VideoInput::process, this), std::bind(&VideoInput::cleanup, this)) { inputMode_ = inputMode; if (inputMode_ == VideoInputMode::Undefined) { #if (defined(__ANDROID__) || (defined(TARGET_OS_IOS) && TARGET_OS_IOS)) inputMode_ = VideoInputMode::ManagedByClient; #else inputMode_ = VideoInputMode::ManagedByDaemon; #endif } sink_ = Manager::instance().createSinkClient(sink.empty() ? resource : sink); switchInput(resource); } VideoInput::~VideoInput() { isStopped_ = true; if (videoManagedByClient()) { // Stop the video sink for videos that are managed by the client. cleanup(); emitSignal<libjami::VideoSignal::StopCapture>(decOpts_.input); capturing_ = false; return; } loop_.join(); } void VideoInput::startLoop() { if (videoManagedByClient()) { switchDevice(); return; } if (!loop_.isRunning()) loop_.start(); } void VideoInput::switchDevice() { if (switchPending_.exchange(false)) { JAMI_DBG("Switching input to '%s'", decOpts_.input.c_str()); if (decOpts_.input.empty()) { capturing_ = false; return; } emitSignal<libjami::VideoSignal::StartCapture>(decOpts_.input); capturing_ = true; } } int VideoInput::getWidth() const { if (videoManagedByClient()) { return decOpts_.width; } return decoder_ ? decoder_->getWidth() : 0; } int VideoInput::getHeight() const { if (videoManagedByClient()) { return decOpts_.height; } return decoder_ ? decoder_->getHeight() : 0; } AVPixelFormat VideoInput::getPixelFormat() const { if (!videoManagedByClient()) { return decoder_->getPixelFormat(); } return (AVPixelFormat) std::stoi(decOpts_.format); } void VideoInput::setRotation(int angle) { std::shared_ptr<AVBufferRef> displayMatrix {av_buffer_alloc(sizeof(int32_t) * 9), [](AVBufferRef* buf) { av_buffer_unref(&buf); }}; if (displayMatrix) { av_display_rotation_set(reinterpret_cast<int32_t*>(displayMatrix->data), angle); displayMatrix_ = std::move(displayMatrix); } } bool VideoInput::setup() { if (not attach(sink_.get())) { JAMI_ERR("attach sink failed"); return false; } if (!sink_->start()) JAMI_ERR("start sink failed"); JAMI_DBG("VideoInput ready to capture"); return true; } void VideoInput::process() { if (playingFile_) { if (paused_ || !decoder_->emitFrame(false)) { std::this_thread::sleep_for(std::chrono::milliseconds(20)); } return; } if (switchPending_) createDecoder(); if (not captureFrame()) { loop_.stop(); return; } } void VideoInput::setSeekTime(int64_t time) { if (decoder_) { decoder_->setSeekTime(time); } } void VideoInput::cleanup() { deleteDecoder(); // do it first to let a chance to last frame to be displayed stopSink(); JAMI_DBG("VideoInput closed"); } bool VideoInput::captureFrame() { // Return true if capture could continue, false if must be stop if (not decoder_) return false; switch (decoder_->decode()) { case MediaDemuxer::Status::EndOfFile: createDecoder(); return static_cast<bool>(decoder_); case MediaDemuxer::Status::ReadError: JAMI_ERR() << "Failed to decode frame"; return false; default: return true; } } void VideoInput::flushBuffers() { if (decoder_) { decoder_->flushBuffers(); } } void VideoInput::configureFilePlayback(const std::string&, std::shared_ptr<MediaDemuxer>& demuxer, int index) { deleteDecoder(); clearOptions(); auto decoder = std::make_unique<MediaDecoder>(demuxer, index, [this](std::shared_ptr<MediaFrame>&& frame) { publishFrame( std::static_pointer_cast<VideoFrame>( frame)); }); decoder->setInterruptCallback( [](void* data) -> int { return not static_cast<VideoInput*>(data)->isCapturing(); }, this); decoder->emulateRate(); decoder_ = std::move(decoder); playingFile_ = true; // For DBUS it is imperative that we start the sink before setting the frame size sink_->start(); /* Signal the client about readable sink */ sink_->setFrameSize(decoder_->getWidth(), decoder_->getHeight()); loop_.start(); decOpts_.width = ((decoder_->getWidth() >> 3) << 3); decOpts_.height = ((decoder_->getHeight() >> 3) << 3); decOpts_.framerate = decoder_->getFps(); AVPixelFormat fmt = decoder_->getPixelFormat(); if (fmt != AV_PIX_FMT_NONE) { decOpts_.pixel_format = av_get_pix_fmt_name(fmt); } else { JAMI_WARN("Unable to determine pixel format, using default"); decOpts_.pixel_format = av_get_pix_fmt_name(AV_PIX_FMT_YUV420P); } if (onSuccessfulSetup_) onSuccessfulSetup_(MEDIA_VIDEO, 0); foundDecOpts(decOpts_); futureDecOpts_ = foundDecOpts_.get_future().share(); } void VideoInput::setRecorderCallback(const std::function<void(const MediaStream& ms)>& cb) { recorderCallback_ = cb; if (decoder_) decoder_->setContextCallback([this]() { if (recorderCallback_) recorderCallback_(getInfo()); }); } void VideoInput::createDecoder() { deleteDecoder(); switchPending_ = false; if (decOpts_.input.empty()) { foundDecOpts(decOpts_); return; } auto decoder = std::make_unique<MediaDecoder>( [this](const std::shared_ptr<MediaFrame>& frame) mutable { publishFrame(std::static_pointer_cast<VideoFrame>(frame)); }); if (emulateRate_) decoder->emulateRate(); decoder->setInterruptCallback( [](void* data) -> int { return not static_cast<VideoInput*>(data)->isCapturing(); }, this); bool ready = false, restartSink = false; if ((decOpts_.format == "x11grab" || decOpts_.format == "dxgigrab" || decOpts_.format == "pipewiregrab") && !decOpts_.is_area) { decOpts_.width = 0; decOpts_.height = 0; } while (!ready && !isStopped_) { // Retry to open the video till the input is opened int ret = decoder->openInput(decOpts_); ready = ret >= 0; if (ret < 0 && -ret != EBUSY) { JAMI_ERR("Unable to open input \"%s\" with status %i", decOpts_.input.c_str(), ret); foundDecOpts(decOpts_); return; } else if (-ret == EBUSY) { // If the device is busy, this means that it can be used by another call. // If this is the case, cleanup() can occurs and this will erase shmPath_ // So, be sure to regenerate a correct shmPath for clients. restartSink = true; } std::this_thread::sleep_for(std::chrono::milliseconds(10)); } if (isStopped_) return; if (restartSink && !isStopped_) { sink_->start(); } /* Data available, finish the decoding */ if (decoder->setupVideo() < 0) { JAMI_ERR("decoder IO startup failed"); foundDecOpts(decOpts_); return; } auto ret = decoder->decode(); // Populate AVCodecContext fields if (ret == MediaDemuxer::Status::ReadError) { JAMI_INFO() << "Decoder error"; return; } decOpts_.width = ((decoder->getWidth() >> 3) << 3); decOpts_.height = ((decoder->getHeight() >> 3) << 3); decOpts_.framerate = decoder->getFps(); AVPixelFormat fmt = decoder->getPixelFormat(); if (fmt != AV_PIX_FMT_NONE) { decOpts_.pixel_format = av_get_pix_fmt_name(fmt); } else { JAMI_WARN("Unable to determine pixel format, using default"); decOpts_.pixel_format = av_get_pix_fmt_name(AV_PIX_FMT_YUV420P); } JAMI_DBG("created decoder with video params : size=%dX%d, fps=%lf pix=%s", decOpts_.width, decOpts_.height, decOpts_.framerate.real(), decOpts_.pixel_format.c_str()); if (onSuccessfulSetup_) onSuccessfulSetup_(MEDIA_VIDEO, 0); decoder_ = std::move(decoder); foundDecOpts(decOpts_); /* Signal the client about readable sink */ sink_->setFrameSize(decoder_->getWidth(), decoder_->getHeight()); decoder_->setContextCallback([this]() { if (recorderCallback_) recorderCallback_(getInfo()); }); } void VideoInput::deleteDecoder() { if (not decoder_) return; flushFrames(); decoder_.reset(); } void VideoInput::stopInput() { clearOptions(); loop_.stop(); } void VideoInput::clearOptions() { decOpts_ = {}; emulateRate_ = false; } bool VideoInput::isCapturing() const noexcept { if (videoManagedByClient()) { return capturing_; } return loop_.isRunning(); } bool VideoInput::initCamera(const std::string& device) { decOpts_ = jami::getVideoDeviceMonitor().getDeviceParams(device); return true; } static constexpr unsigned round2pow(unsigned i, unsigned n) { return (i >> n) << n; } #if !defined(WIN32) && !defined(__APPLE__) bool VideoInput::initLinuxGrab(const std::string& display) { // Patterns (all platforms except Linux with Wayland) // full screen sharing: :1+0,0 2560x1440 (SCREEN 1, POSITION 0X0, RESOLUTION 2560X1440) // area sharing: :1+882,211 1532x779 (SCREEN 1, POSITION 882x211, RESOLUTION 1532x779) // window sharing: :+1,0 0x0 window-id:0x0340021e (POSITION 0X0) // // Pattern (Linux with Wayland) // full screen or window sharing: pipewire pid:2861 fd:23 node:68 size_t space = display.find(' '); std::string windowIdStr = "window-id:"; size_t winIdPos = display.find(windowIdStr); DeviceParams p = jami::getVideoDeviceMonitor().getDeviceParams(DEVICE_DESKTOP); if (winIdPos != std::string::npos) { p.window_id = display.substr(winIdPos + windowIdStr.size()); // "0x0340021e"; p.is_area = 0; } if (display.find("pipewire") != std::string::npos) { std::string pidStr = "pid:"; std::string fdStr = "fd:"; std::string nodeStr = "node:"; size_t pidPos = display.find(pidStr) + pidStr.size(); size_t fdPos = display.find(fdStr) + fdStr.size(); size_t nodePos = display.find(nodeStr) + nodeStr.size(); pid_t pid = std::stol(display.substr(pidPos)); int fd = std::stoi(display.substr(fdPos)); if (pid != getpid()) { #ifdef SYS_pidfd_getfd // We are unable to directly use a file descriptor that was opened in a different // process, so we try to duplicate it in the current process. int pidfd = syscall(SYS_pidfd_open, pid, 0); if (pidfd < 0) { JAMI_ERROR("Unable to duplicate PipeWire fd: call to pidfd_open failed (errno = {})", errno); return false; } fd = syscall(SYS_pidfd_getfd, pidfd, fd, 0); if (fd < 0) { JAMI_ERROR("Unable to duplicate PipeWire fd: call to pidfd_getfd failed (errno = {})", errno); return false; } #else JAMI_ERROR("Unable to duplicate PipeWire fd: pidfd_getfd syscall not available"); return false; #endif } p.fd = fd; p.node = display.substr(nodePos); } else if (space != std::string::npos) { p.input = display.substr(1, space); if (p.window_id.empty()) { p.input = display.substr(0, space); auto splits = jami::split_string_to_unsigned(display.substr(space + 1), 'x'); // round to 8 pixel block p.width = round2pow(splits[0], 3); p.height = round2pow(splits[1], 3); p.is_area = 1; } } else { p.input = display; p.width = default_grab_width; p.height = default_grab_height; p.is_area = 1; } decOpts_ = p; emulateRate_ = false; return true; } #endif #ifdef __APPLE__ bool VideoInput::initAVFoundation(const std::string& display) { size_t space = display.find(' '); clearOptions(); decOpts_.format = "avfoundation"; decOpts_.pixel_format = "nv12"; decOpts_.name = "Capture screen 0"; decOpts_.input = "Capture screen 0"; decOpts_.framerate = jami::getVideoDeviceMonitor().getDeviceParams(DEVICE_DESKTOP).framerate; if (space != std::string::npos) { std::istringstream iss(display.substr(space + 1)); char sep; unsigned w, h; iss >> w >> sep >> h; decOpts_.width = round2pow(w, 3); decOpts_.height = round2pow(h, 3); } else { decOpts_.width = default_grab_width; decOpts_.height = default_grab_height; } return true; } #endif #ifdef WIN32 bool VideoInput::initWindowsGrab(const std::string& display) { // Patterns // full screen sharing : :1+0,0 2560x1440 - SCREEN 1, POSITION 0X0, RESOLUTION 2560X1440 // area sharing : :1+882,211 1532x779 - SCREEN 1, POSITION 882x211, RESOLUTION 1532x779 // window sharing : :+1,0 0x0 window-id:HANDLE - POSITION 0X0 size_t space = display.find(' '); std::string windowIdStr = "window-id:"; size_t winHandlePos = display.find(windowIdStr); DeviceParams p = jami::getVideoDeviceMonitor().getDeviceParams(DEVICE_DESKTOP); if (winHandlePos != std::string::npos) { p.input = display.substr(winHandlePos + windowIdStr.size()); // "HANDLE"; p.name = display.substr(winHandlePos + windowIdStr.size()); // "HANDLE"; p.is_area = 0; } else { p.input = display.substr(1); p.name = display.substr(1); p.is_area = 1; if (space != std::string::npos) { auto splits = jami::split_string_to_unsigned(display.substr(space + 1), 'x'); if (splits.size() != 2) return false; // round to 8 pixel block p.width = splits[0]; p.height = splits[1]; size_t plus = display.find('+'); auto position = display.substr(plus + 1, space - plus - 1); splits = jami::split_string_to_unsigned(position, ','); if (splits.size() != 2) return false; p.offset_x = splits[0]; p.offset_y = splits[1]; } else { p.width = default_grab_width; p.height = default_grab_height; } } auto dec = std::make_unique<MediaDecoder>(); if (dec->openInput(p) < 0 || dec->setupVideo() < 0) return initCamera(jami::getVideoDeviceMonitor().getDefaultDevice()); clearOptions(); decOpts_ = p; decOpts_.width = dec->getStream().width; decOpts_.height = dec->getStream().height; return true; } #endif bool VideoInput::initFile(std::string path) { size_t dot = path.find_last_of('.'); std::string ext = dot == std::string::npos ? "" : path.substr(dot + 1); /* File exists? */ if (access(path.c_str(), R_OK) != 0) { JAMI_ERR("file '%s' unavailable\n", path.c_str()); return false; } // check if file has video, fall back to default device if none // FIXME the way this is done is hackish, but it is unable to be done in createDecoder // because that would break the promise returned in switchInput DeviceParams p; p.input = path; p.name = path; auto dec = std::make_unique<MediaDecoder>(); if (dec->openInput(p) < 0 || dec->setupVideo() < 0) { return initCamera(jami::getVideoDeviceMonitor().getDefaultDevice()); } clearOptions(); emulateRate_ = true; decOpts_.input = path; decOpts_.name = path; decOpts_.loop = "1"; // Force 1fps for static image if (ext == "jpeg" || ext == "jpg" || ext == "png") { decOpts_.format = "image2"; decOpts_.framerate = 1; } else { JAMI_WARN("Guessing file type for %s", path.c_str()); } return false; } void VideoInput::restart() { if (loop_.isStopping()) switchInput(resource_); } std::shared_future<DeviceParams> VideoInput::switchInput(const std::string& resource) { JAMI_DBG("MRL: '%s'", resource.c_str()); if (switchPending_.exchange(true)) { JAMI_ERR("Video switch already requested"); return {}; } resource_ = resource; decOptsFound_ = false; std::promise<DeviceParams> p; foundDecOpts_.swap(p); // Switch off video input? if (resource_.empty()) { clearOptions(); futureDecOpts_ = foundDecOpts_.get_future(); startLoop(); return futureDecOpts_; } // Supported MRL schemes static const std::string sep = libjami::Media::VideoProtocolPrefix::SEPARATOR; const auto pos = resource_.find(sep); if (pos == std::string::npos) return {}; const auto prefix = resource_.substr(0, pos); if ((pos + sep.size()) >= resource_.size()) return {}; const auto suffix = resource_.substr(pos + sep.size()); bool ready = false; if (prefix == libjami::Media::VideoProtocolPrefix::CAMERA) { /* Video4Linux2 */ ready = initCamera(suffix); } else if (prefix == libjami::Media::VideoProtocolPrefix::DISPLAY) { /* X11 display name */ #ifdef __APPLE__ ready = initAVFoundation(suffix); #elif defined(WIN32) ready = initWindowsGrab(suffix); #else ready = initLinuxGrab(suffix); #endif } else if (prefix == libjami::Media::VideoProtocolPrefix::FILE) { /* Pathname */ ready = initFile(suffix); } if (ready) { foundDecOpts(decOpts_); } futureDecOpts_ = foundDecOpts_.get_future().share(); startLoop(); return futureDecOpts_; } MediaStream VideoInput::getInfo() const { if (!videoManagedByClient()) { if (decoder_) return decoder_->getStream("v:local"); } auto opts = futureDecOpts_.get(); rational<int> fr(opts.framerate.numerator(), opts.framerate.denominator()); return MediaStream("v:local", av_get_pix_fmt(opts.pixel_format.c_str()), 1 / fr, opts.width, opts.height, 0, fr); } void VideoInput::foundDecOpts(const DeviceParams& params) { if (not decOptsFound_) { decOptsFound_ = true; foundDecOpts_.set_value(params); } } void VideoInput::setSink(const std::string& sinkId) { sink_ = Manager::instance().createSinkClient(sinkId); } void VideoInput::setupSink(const int width, const int height) { setup(); /* Signal the client about readable sink */ sink_->setFrameSize(width, height); } void VideoInput::stopSink() { detach(sink_.get()); sink_->stop(); } void VideoInput::updateStartTime(int64_t startTime) { if (decoder_) { decoder_->updateStartTime(startTime); } } } // namespace video } // namespace jami
21,166
C++
.cpp
655
25.848855
132
0.607584
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,753
video_base.cpp
savoirfairelinux_jami-daemon/src/media/video/video_base.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "libav_deps.h" // MUST BE INCLUDED FIRST #include "video_base.h" #include "media_buffer.h" #include "string_utils.h" #include "logger.h" #include <cassert> namespace jami { namespace video { /*=== VideoGenerator =========================================================*/ VideoFrame& VideoGenerator::getNewFrame() { std::lock_guard lk(mutex_); writableFrame_.reset(new VideoFrame()); return *writableFrame_.get(); } void VideoGenerator::publishFrame() { std::lock_guard lk(mutex_); lastFrame_ = std::move(writableFrame_); notify(std::static_pointer_cast<MediaFrame>(lastFrame_)); } void VideoGenerator::publishFrame(std::shared_ptr<VideoFrame> frame) { std::lock_guard lk(mutex_); lastFrame_ = std::move(frame); notify(std::static_pointer_cast<MediaFrame>(lastFrame_)); } void VideoGenerator::flushFrames() { std::lock_guard lk(mutex_); writableFrame_.reset(); lastFrame_.reset(); } std::shared_ptr<VideoFrame> VideoGenerator::obtainLastFrame() { std::lock_guard lk(mutex_); return lastFrame_; } /*=== VideoSettings =========================================================*/ static std::string extractString(const std::map<std::string, std::string>& settings, const std::string& key) { auto i = settings.find(key); if (i != settings.cend()) return i->second; return {}; } VideoSettings::VideoSettings(const std::map<std::string, std::string>& settings) { name = extractString(settings, "name"); unique_id = extractString(settings, "id"); input = extractString(settings, "input"); if (input.empty()) { input = unique_id; } channel = extractString(settings, "channel"); video_size = extractString(settings, "size"); framerate = extractString(settings, "rate"); } std::map<std::string, std::string> VideoSettings::to_map() const { return {{"name", name}, {"id", unique_id}, {"input", input}, {"size", video_size}, {"channel", channel}, {"rate", framerate}}; } } // namespace video } // namespace jami namespace YAML { Node convert<jami::video::VideoSettings>::encode(const jami::video::VideoSettings& rhs) { Node node; node["name"] = rhs.name; node["id"] = rhs.unique_id; node["input"] = rhs.input; node["video_size"] = rhs.video_size; node["channel"] = rhs.channel; node["framerate"] = rhs.framerate; return node; } bool convert<jami::video::VideoSettings>::decode(const Node& node, jami::video::VideoSettings& rhs) { if (not node.IsMap()) { JAMI_WARN("Unable to decode VideoSettings YAML node"); return false; } rhs.name = node["name"].as<std::string>(); rhs.unique_id = node["id"].as<std::string>(); rhs.input = node["input"].as<std::string>(); rhs.video_size = node["video_size"].as<std::string>(); rhs.channel = node["channel"].as<std::string>(); rhs.framerate = node["framerate"].as<std::string>(); return true; } Emitter& operator<<(Emitter& out, const jami::video::VideoSettings& v) { out << convert<jami::video::VideoSettings>::encode(v); return out; } } // namespace YAML
3,897
C++
.cpp
127
27.275591
94
0.659824
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,754
video_rtp_session.cpp
savoirfairelinux_jami-daemon/src/media/video/video_rtp_session.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "client/videomanager.h" #include "video_rtp_session.h" #include "video_sender.h" #include "video_receive_thread.h" #include "video_mixer.h" #include "socket_pair.h" #include "sip/sipvoiplink.h" // for enqueueKeyframeRequest #include "manager.h" #include "media_const.h" #ifdef ENABLE_PLUGIN #include "plugin/streamdata.h" #include "plugin/jamipluginmanager.h" #endif #include "logger.h" #include "string_utils.h" #include "call.h" #include "conference.h" #include "congestion_control.h" #include "account_const.h" #include <dhtnet/ice_socket.h> #include <asio/io_context.hpp> #include <sstream> #include <map> #include <string> #include <thread> #include <chrono> namespace jami { namespace video { using std::string; static constexpr unsigned MAX_REMB_DEC {1}; constexpr auto DELAY_AFTER_RESTART = std::chrono::milliseconds(1000); constexpr auto EXPIRY_TIME_RTCP = std::chrono::seconds(2); constexpr auto DELAY_AFTER_REMB_INC = std::chrono::seconds(1); constexpr auto DELAY_AFTER_REMB_DEC = std::chrono::milliseconds(500); VideoRtpSession::VideoRtpSession(const string& callId, const string& streamId, const DeviceParams& localVideoParams, const std::shared_ptr<MediaRecorder>& rec) : RtpSession(callId, streamId, MediaType::MEDIA_VIDEO) , localVideoParams_(localVideoParams) , videoBitrateInfo_ {} , rtcpCheckerThread_([] { return true; }, [this] { processRtcpChecker(); }, [] {}) , cc(std::make_unique<CongestionControl>()) { recorder_ = rec; setupVideoBitrateInfo(); // reset bitrate JAMI_LOG("[{:p}] Video RTP session created for call {} (recorder {:p})", fmt::ptr(this), callId_, fmt::ptr(recorder_)); } VideoRtpSession::~VideoRtpSession() { deinitRecorder(); stop(); JAMI_LOG("[{:p}] Video RTP session destroyed", fmt::ptr(this)); } const VideoBitrateInfo& VideoRtpSession::getVideoBitrateInfo() { return videoBitrateInfo_; } /// Setup internal VideoBitrateInfo structure from media descriptors. /// void VideoRtpSession::updateMedia(const MediaDescription& send, const MediaDescription& receive) { BaseType::updateMedia(send, receive); // adjust send->codec bitrate info for higher video resolutions auto codecVideo = std::static_pointer_cast<jami::SystemVideoCodecInfo>(send_.codec); if (codecVideo) { auto const pixels = localVideoParams_.height * localVideoParams_.width; codecVideo->bitrate = std::max((unsigned int)(pixels * 0.001), SystemCodecInfo::DEFAULT_VIDEO_BITRATE); codecVideo->maxBitrate = std::max((unsigned int)(pixels * 0.0015), SystemCodecInfo::DEFAULT_MAX_BITRATE); } setupVideoBitrateInfo(); } void VideoRtpSession::setRequestKeyFrameCallback(std::function<void(void)> cb) { cbKeyFrameRequest_ = std::move(cb); } void VideoRtpSession::startSender() { std::lock_guard lock(mutex_); JAMI_DBG("[%p] Start video RTP sender: input [%s] - muted [%s]", this, conference_ ? "Video Mixer" : input_.c_str(), send_.onHold ? "YES" : "NO"); if (not socketPair_) { // Ignore if the transport is not set yet JAMI_WARN("[%p] Transport not set yet", this); return; } if (send_.enabled and not send_.onHold) { if (sender_) { if (videoLocal_) videoLocal_->detach(sender_.get()); if (videoMixer_) videoMixer_->detach(sender_.get()); JAMI_WARN("[%p] Restarting video sender", this); } if (not conference_) { videoLocal_ = getVideoInput(input_); if (videoLocal_) { videoLocal_->setRecorderCallback( [w=weak_from_this()](const MediaStream& ms) { Manager::instance().ioContext()->post([w=std::move(w), ms]() { if (auto shared = w.lock()) shared->attachLocalRecorder(ms); }); }); auto newParams = videoLocal_->getParams(); try { if (newParams.valid() && newParams.wait_for(NEWPARAMS_TIMEOUT) == std::future_status::ready) { localVideoParams_ = newParams.get(); } else { JAMI_ERR("[%p] No valid new video parameters", this); return; } } catch (const std::exception& e) { JAMI_ERR("Exception during retrieving video parameters: %s", e.what()); return; } } else { JAMI_WARN("Unable to lock video input"); return; } #if (defined(__ANDROID__) || (defined(TARGET_OS_IOS) && TARGET_OS_IOS)) videoLocal_->setupSink(localVideoParams_.width, localVideoParams_.height); #endif } // be sure to not send any packets before saving last RTP seq value socketPair_->stopSendOp(); auto codecVideo = std::static_pointer_cast<jami::SystemVideoCodecInfo>(send_.codec); auto autoQuality = codecVideo->isAutoQualityEnabled; send_.linkableHW = conference_ == nullptr; send_.bitrate = videoBitrateInfo_.videoBitrateCurrent; // NOTE: // Current implementation does not handle resolution change // (needed by window sharing feature) with HW codecs, so HW // codecs will be disabled for now. bool allowHwAccel = (localVideoParams_.format != "x11grab" && localVideoParams_.format != "dxgigrab" && localVideoParams_.format != "lavfi"); if (socketPair_) initSeqVal_ = socketPair_->lastSeqValOut(); try { sender_.reset(); socketPair_->stopSendOp(false); MediaStream ms = !videoMixer_ ? MediaStream("video sender", AV_PIX_FMT_YUV420P, 1 / static_cast<rational<int>>(localVideoParams_.framerate), localVideoParams_.width == 0 ? 1080u : localVideoParams_.width, localVideoParams_.height == 0 ? 720u : localVideoParams_.height, send_.bitrate, static_cast<rational<int>>(localVideoParams_.framerate)) : videoMixer_->getStream("Video Sender"); sender_.reset(new VideoSender( getRemoteRtpUri(), ms, send_, *socketPair_, initSeqVal_ + 1, mtu_, allowHwAccel)); if (changeOrientationCallback_) sender_->setChangeOrientationCallback(changeOrientationCallback_); if (socketPair_) socketPair_->setPacketLossCallback([this]() { cbKeyFrameRequest_(); }); } catch (const MediaEncoderException& e) { JAMI_ERR("%s", e.what()); send_.enabled = false; } lastMediaRestart_ = clock::now(); last_REMB_inc_ = clock::now(); last_REMB_dec_ = clock::now(); if (autoQuality and not rtcpCheckerThread_.isRunning()) rtcpCheckerThread_.start(); else if (not autoQuality and rtcpCheckerThread_.isRunning()) rtcpCheckerThread_.join(); // Block reads to received feedback packets if(socketPair_) socketPair_->setReadBlockingMode(true); } } void VideoRtpSession::restartSender() { std::lock_guard lock(mutex_); // ensure that start has been called before restart if (not socketPair_) return; startSender(); if (conference_) setupConferenceVideoPipeline(*conference_, Direction::SEND); else setupVideoPipeline(); } void VideoRtpSession::stopSender(bool forceStopSocket) { // Concurrency protection must be done by caller. JAMI_DBG("[%p] Stop video RTP sender: input [%s] - muted [%s]", this, conference_ ? "Video Mixer" : input_.c_str(), send_.onHold ? "YES" : "NO"); if (sender_) { if (videoLocal_) videoLocal_->detach(sender_.get()); if (videoMixer_) videoMixer_->detach(sender_.get()); sender_.reset(); } if (socketPair_) { bool const isReceivingVideo = receive_.enabled && !receive_.onHold; if(forceStopSocket || !isReceivingVideo) { socketPair_->stopSendOp(); socketPair_->setReadBlockingMode(false); } } } void VideoRtpSession::startReceiver() { // Concurrency protection must be done by caller. JAMI_DBG("[%p] Starting receiver", this); if (receive_.enabled and not receive_.onHold) { if (receiveThread_) JAMI_WARN("[%p] Already has a receiver, restarting", this); receiveThread_.reset( new VideoReceiveThread(callId_, !conference_, receive_.receiving_sdp, mtu_)); // ensure that start has been called if (not socketPair_) return; // XXX keyframe requests can timeout if unanswered receiveThread_->addIOContext(*socketPair_); receiveThread_->setSuccessfulSetupCb(onSuccessfulSetup_); receiveThread_->startLoop(); receiveThread_->setRequestKeyFrameCallback([this]() { cbKeyFrameRequest_(); }); receiveThread_->setRotation(rotation_.load()); if (videoMixer_ and conference_) { // Note, this should be managed differently, this is a bit hacky auto audioId = streamId_; string_replace(audioId, "video", "audio"); auto activeStream = videoMixer_->verifyActive(audioId); videoMixer_->removeAudioOnlySource(callId_, audioId); if (activeStream) videoMixer_->setActiveStream(streamId_); } receiveThread_->setRecorderCallback([w=weak_from_this()](const MediaStream& ms) { Manager::instance().ioContext()->post([w=std::move(w), ms]() { if (auto shared = w.lock()) shared->attachRemoteRecorder(ms); }); }); } else { JAMI_DBG("[%p] Video receiver disabled", this); if (receiveThread_ and videoMixer_ and conference_) { // Note, this should be managed differently, this is a bit hacky auto audioId_ = streamId_; string_replace(audioId_, "video", "audio"); auto activeStream = videoMixer_->verifyActive(streamId_); videoMixer_->addAudioOnlySource(callId_, audioId_); receiveThread_->detach(videoMixer_.get()); if (activeStream) videoMixer_->setActiveStream(audioId_); } } if (socketPair_) socketPair_->setReadBlockingMode(true); } void VideoRtpSession::stopReceiver(bool forceStopSocket) { // Concurrency protection must be done by caller. JAMI_DBG("[%p] Stopping receiver", this); if (not receiveThread_) return; if (videoMixer_) { auto activeStream = videoMixer_->verifyActive(streamId_); auto audioId = streamId_; string_replace(audioId, "video", "audio"); videoMixer_->addAudioOnlySource(callId_, audioId); receiveThread_->detach(videoMixer_.get()); if (activeStream) videoMixer_->setActiveStream(audioId); } // We need to disable the read operation, otherwise the // receiver thread will block since the peer stopped sending // RTP packets. bool const isSendingVideo = send_.enabled && !send_.onHold; if (socketPair_) { if (forceStopSocket || !isSendingVideo) { socketPair_->setReadBlockingMode(false); socketPair_->stopSendOp(); } } auto ms = receiveThread_->getInfo(); if (auto ob = recorder_->getStream(ms.name)) { receiveThread_->detach(ob); recorder_->removeStream(ms); } if(forceStopSocket || !isSendingVideo) receiveThread_->stopLoop(); receiveThread_->stopSink(); } void VideoRtpSession::start(std::unique_ptr<dhtnet::IceSocket> rtp_sock, std::unique_ptr<dhtnet::IceSocket> rtcp_sock) { std::lock_guard lock(mutex_); if (not send_.enabled and not receive_.enabled) { stop(); return; } try { if (rtp_sock and rtcp_sock) { if (send_.addr) { rtp_sock->setDefaultRemoteAddress(send_.addr); } auto& rtcpAddr = send_.rtcp_addr ? send_.rtcp_addr : send_.addr; if (rtcpAddr) { rtcp_sock->setDefaultRemoteAddress(rtcpAddr); } socketPair_.reset(new SocketPair(std::move(rtp_sock), std::move(rtcp_sock))); } else { socketPair_.reset(new SocketPair(getRemoteRtpUri().c_str(), receive_.addr.getPort())); } last_REMB_inc_ = clock::now(); last_REMB_dec_ = clock::now(); socketPair_->setRtpDelayCallback( [&](int gradient, int deltaT) { delayMonitor(gradient, deltaT); }); if (send_.crypto and receive_.crypto) { socketPair_->createSRTP(receive_.crypto.getCryptoSuite().c_str(), receive_.crypto.getSrtpKeyInfo().c_str(), send_.crypto.getCryptoSuite().c_str(), send_.crypto.getSrtpKeyInfo().c_str()); } } catch (const std::runtime_error& e) { JAMI_ERR("[%p] Socket creation failed: %s", this, e.what()); return; } startSender(); startReceiver(); if (conference_) { if (send_.enabled and not send_.onHold) { setupConferenceVideoPipeline(*conference_, Direction::SEND); } if (receive_.enabled and not receive_.onHold) { setupConferenceVideoPipeline(*conference_, Direction::RECV); } } else { setupVideoPipeline(); } } void VideoRtpSession::stop() { std::lock_guard lock(mutex_); stopSender(true); stopReceiver(true); if (socketPair_) socketPair_->interrupt(); rtcpCheckerThread_.join(); // reset default video quality if exist if (videoBitrateInfo_.videoQualityCurrent != SystemCodecInfo::DEFAULT_NO_QUALITY) videoBitrateInfo_.videoQualityCurrent = SystemCodecInfo::DEFAULT_CODEC_QUALITY; videoBitrateInfo_.videoBitrateCurrent = SystemCodecInfo::DEFAULT_VIDEO_BITRATE; storeVideoBitrateInfo(); socketPair_.reset(); videoLocal_.reset(); } void VideoRtpSession::setMuted(bool mute, Direction dir) { std::lock_guard lock(mutex_); // Sender if (dir == Direction::SEND) { if (send_.onHold == mute) { JAMI_DBG("[%p] Local already %s", this, mute ? "muted" : "un-muted"); return; } if ((send_.onHold = mute)) { if (videoLocal_) { auto ms = videoLocal_->getInfo(); if (auto ob = recorder_->getStream(ms.name)) { videoLocal_->detach(ob); recorder_->removeStream(ms); } } stopSender(); } else { restartSender(); } return; } // Receiver if (receive_.onHold == mute) { JAMI_DBG("[%p] Remote already %s", this, mute ? "muted" : "un-muted"); return; } if ((receive_.onHold = mute)) { if (receiveThread_) { auto ms = receiveThread_->getInfo(); if (auto ob = recorder_->getStream(ms.name)) { receiveThread_->detach(ob); recorder_->removeStream(ms); } } stopReceiver(); } else { startReceiver(); if (conference_ and not receive_.onHold) { setupConferenceVideoPipeline(*conference_, Direction::RECV); } } } void VideoRtpSession::forceKeyFrame() { std::lock_guard lock(mutex_); #if __ANDROID__ if (videoLocal_) emitSignal<libjami::VideoSignal::RequestKeyFrame>(videoLocal_->getName()); #else if (sender_) sender_->forceKeyFrame(); #endif } void VideoRtpSession::setRotation(int rotation) { rotation_.store(rotation); if (receiveThread_) receiveThread_->setRotation(rotation); } void VideoRtpSession::setupVideoPipeline() { if (sender_) { if (videoLocal_) { JAMI_DBG("[%p] Setup video pipeline on local capture device", this); videoLocal_->attach(sender_.get()); } } else { videoLocal_.reset(); } } void VideoRtpSession::setupConferenceVideoPipeline(Conference& conference, Direction dir) { if (dir == Direction::SEND) { JAMI_DBG("[%p] Setup video sender pipeline on conference %s for call %s", this, conference.getConfId().c_str(), callId_.c_str()); videoMixer_ = conference.getVideoMixer(); if (sender_) { // Swap sender from local video to conference video mixer if (videoLocal_) videoLocal_->detach(sender_.get()); if (videoMixer_) videoMixer_->attach(sender_.get()); } else { JAMI_WARN("[%p] no sender", this); } } else { JAMI_DBG("[%p] Setup video receiver pipeline on conference %s for call %s", this, conference.getConfId().c_str(), callId_.c_str()); if (receiveThread_) { receiveThread_->stopSink(); if (videoMixer_) videoMixer_->attachVideo(receiveThread_.get(), callId_, streamId_); } else { JAMI_WARN("[%p] no receiver", this); } } } void VideoRtpSession::enterConference(Conference& conference) { std::lock_guard lock(mutex_); exitConference(); conference_ = &conference; videoMixer_ = conference.getVideoMixer(); JAMI_DBG("[%p] enterConference (conf: %s)", this, conference.getConfId().c_str()); if (send_.enabled or receiveThread_) { // Restart encoder with conference parameter ON in order to unlink HW encoder // from HW decoder. restartSender(); if (conference_) { setupConferenceVideoPipeline(conference, Direction::RECV); } } } void VideoRtpSession::exitConference() { std::lock_guard lock(mutex_); if (!conference_) return; JAMI_DBG("[%p] exitConference (conf: %s)", this, conference_->getConfId().c_str()); if (videoMixer_) { if (sender_) videoMixer_->detach(sender_.get()); if (receiveThread_) { auto activeStream = videoMixer_->verifyActive(streamId_); videoMixer_->detachVideo(receiveThread_.get()); receiveThread_->startSink(); if (activeStream) videoMixer_->setActiveStream(streamId_); } videoMixer_.reset(); } conference_ = nullptr; } bool VideoRtpSession::check_RCTP_Info_RR(RTCPInfo& rtcpi) { auto rtcpInfoVect = socketPair_->getRtcpRR(); unsigned totalLost = 0; unsigned totalJitter = 0; unsigned nbDropNotNull = 0; auto vectSize = rtcpInfoVect.size(); if (vectSize != 0) { for (const auto& it : rtcpInfoVect) { if (it.fraction_lost != 0) // Exclude null drop nbDropNotNull++; totalLost += it.fraction_lost; totalJitter += ntohl(it.jitter); } rtcpi.packetLoss = nbDropNotNull ? (float) (100 * totalLost) / (256.0 * nbDropNotNull) : 0; // Jitter is expressed in timestamp unit -> convert to milliseconds // https://stackoverflow.com/questions/51956520/convert-jitter-from-rtp-timestamp-unit-to-millisseconds rtcpi.jitter = (totalJitter / vectSize / 90000.0f) * 1000; rtcpi.nb_sample = vectSize; rtcpi.latency = socketPair_->getLastLatency(); return true; } return false; } bool VideoRtpSession::check_RCTP_Info_REMB(uint64_t* br) { auto rtcpInfoVect = socketPair_->getRtcpREMB(); if (!rtcpInfoVect.empty()) { auto pkt = rtcpInfoVect.back(); auto temp = cc->parseREMB(pkt); *br = (temp >> 10) | ((temp << 6) & 0xff00) | ((temp << 16) & 0x30000); return true; } return false; } void VideoRtpSession::adaptQualityAndBitrate() { setupVideoBitrateInfo(); uint64_t br; if (check_RCTP_Info_REMB(&br)) { delayProcessing(br); } RTCPInfo rtcpi {}; if (check_RCTP_Info_RR(rtcpi)) { dropProcessing(&rtcpi); } } void VideoRtpSession::dropProcessing(RTCPInfo* rtcpi) { // If bitrate has changed, let time to receive fresh RTCP packets auto now = clock::now(); auto restartTimer = now - lastMediaRestart_; if (restartTimer < DELAY_AFTER_RESTART) { return; } #ifndef __ANDROID__ // Do nothing if jitter is more than 1 second if (rtcpi->jitter > 1000) { return; } #endif auto pondLoss = getPonderateLoss(rtcpi->packetLoss); auto oldBitrate = videoBitrateInfo_.videoBitrateCurrent; int newBitrate = oldBitrate; // Fill histoLoss and histoJitter_ with samples if (restartTimer < DELAY_AFTER_RESTART + std::chrono::seconds(1)) { return; } else { // If ponderate drops are inferior to 10% that mean drop are not from congestion but from // network... // ... we can increase if (pondLoss >= 5.0f && rtcpi->packetLoss > 0.0f) { newBitrate *= 1.0f - rtcpi->packetLoss / 150.0f; histoLoss_.clear(); lastMediaRestart_ = now; JAMI_DBG( "[BandwidthAdapt] Detected transmission bandwidth overuse, decrease bitrate from " "%u Kbps to %d Kbps, ratio %f (ponderate loss: %f%%, packet loss rate: %f%%)", oldBitrate, newBitrate, (float) newBitrate / oldBitrate, pondLoss, rtcpi->packetLoss); } } setNewBitrate(newBitrate); } void VideoRtpSession::delayProcessing(int br) { int newBitrate = videoBitrateInfo_.videoBitrateCurrent; if (br == 0x6803) newBitrate *= 0.85f; else if (br == 0x7378) { auto now = clock::now(); auto msSinceLastDecrease = std::chrono::duration_cast<std::chrono::milliseconds>( now - lastBitrateDecrease); auto increaseCoefficient = std::min(msSinceLastDecrease.count() / 600000.0f + 1.0f, 1.05f); newBitrate *= increaseCoefficient; } else return; setNewBitrate(newBitrate); } void VideoRtpSession::setNewBitrate(unsigned int newBR) { newBR = std::max(newBR, videoBitrateInfo_.videoBitrateMin); newBR = std::min(newBR, videoBitrateInfo_.videoBitrateMax); if (newBR < videoBitrateInfo_.videoBitrateCurrent) lastBitrateDecrease = clock::now(); if (videoBitrateInfo_.videoBitrateCurrent != newBR) { videoBitrateInfo_.videoBitrateCurrent = newBR; storeVideoBitrateInfo(); #if __ANDROID__ if (auto input_device = std::dynamic_pointer_cast<VideoInput>(videoLocal_)) emitSignal<libjami::VideoSignal::SetBitrate>(input_device->getConfig().name, (int) newBR); #endif if (sender_) { auto ret = sender_->setBitrate(newBR); if (ret == -1) JAMI_ERR("Fail to access the encoder"); else if (ret == 0) restartSender(); } else { JAMI_ERR("Fail to access the sender"); } } } void VideoRtpSession::setupVideoBitrateInfo() { auto codecVideo = std::static_pointer_cast<jami::SystemVideoCodecInfo>(send_.codec); if (codecVideo) { videoBitrateInfo_ = { codecVideo->bitrate, codecVideo->minBitrate, codecVideo->maxBitrate, codecVideo->quality, codecVideo->minQuality, codecVideo->maxQuality, videoBitrateInfo_.cptBitrateChecking, videoBitrateInfo_.maxBitrateChecking, videoBitrateInfo_.packetLostThreshold, }; } else { videoBitrateInfo_ = {0, 0, 0, 0, 0, 0, 0, MAX_ADAPTATIVE_BITRATE_ITERATION, PACKET_LOSS_THRESHOLD}; } } void VideoRtpSession::storeVideoBitrateInfo() { if (auto codecVideo = std::static_pointer_cast<jami::SystemVideoCodecInfo>(send_.codec)) { codecVideo->bitrate = videoBitrateInfo_.videoBitrateCurrent; codecVideo->quality = videoBitrateInfo_.videoQualityCurrent; } } void VideoRtpSession::processRtcpChecker() { adaptQualityAndBitrate(); socketPair_->waitForRTCP(std::chrono::seconds(rtcp_checking_interval)); } void VideoRtpSession::attachRemoteRecorder(const MediaStream& ms) { std::lock_guard lock(mutex_); if (!recorder_ || !receiveThread_) return; if (auto ob = recorder_->addStream(ms)) { receiveThread_->attach(ob); } } void VideoRtpSession::attachLocalRecorder(const MediaStream& ms) { std::lock_guard lock(mutex_); if (!recorder_ || !videoLocal_ || !Manager::instance().videoPreferences.getRecordPreview()) return; if (auto ob = recorder_->addStream(ms)) { videoLocal_->attach(ob); } } void VideoRtpSession::initRecorder() { if (!recorder_) return; if (receiveThread_) { receiveThread_->setRecorderCallback([w=weak_from_this()](const MediaStream& ms) { Manager::instance().ioContext()->post([w=std::move(w), ms]() { if (auto shared = w.lock()) shared->attachRemoteRecorder(ms); }); }); } if (videoLocal_ && !send_.onHold) { videoLocal_->setRecorderCallback([w=weak_from_this()](const MediaStream& ms) { Manager::instance().ioContext()->post([w=std::move(w), ms]() { if (auto shared = w.lock()) shared->attachLocalRecorder(ms); }); }); } } void VideoRtpSession::deinitRecorder() { if (!recorder_) return; if (receiveThread_) { auto ms = receiveThread_->getInfo(); if (auto ob = recorder_->getStream(ms.name)) { receiveThread_->detach(ob); recorder_->removeStream(ms); } } if (videoLocal_) { auto ms = videoLocal_->getInfo(); if (auto ob = recorder_->getStream(ms.name)) { videoLocal_->detach(ob); recorder_->removeStream(ms); } } } void VideoRtpSession::setChangeOrientationCallback(std::function<void(int)> cb) { changeOrientationCallback_ = std::move(cb); if (sender_) sender_->setChangeOrientationCallback(changeOrientationCallback_); } float VideoRtpSession::getPonderateLoss(float lastLoss) { float pond = 0.0f, pondLoss = 0.0f, totalPond = 0.0f; constexpr float coefficient_a = -1 / 100.0f; constexpr float coefficient_b = 100.0f; auto now = clock::now(); histoLoss_.emplace_back(now, lastLoss); for (auto it = histoLoss_.begin(); it != histoLoss_.end();) { auto delay = std::chrono::duration_cast<std::chrono::milliseconds>(now - it->first); // 1ms -> 100% // 2000ms -> 80% if (delay <= EXPIRY_TIME_RTCP) { if (it->second == 0.0f) pond = 20.0f; // Reduce weight of null drop else pond = std::min(delay.count() * coefficient_a + coefficient_b, 100.0f); totalPond += pond; pondLoss += it->second * pond; ++it; } else it = histoLoss_.erase(it); } if (totalPond == 0) return 0.0f; return pondLoss / totalPond; } void VideoRtpSession::delayMonitor(int gradient, int deltaT) { float estimation = cc->kalmanFilter(gradient); float thresh = cc->get_thresh(); cc->update_thresh(estimation, deltaT); BandwidthUsage bwState = cc->get_bw_state(estimation, thresh); auto now = clock::now(); if (bwState == BandwidthUsage::bwOverusing) { auto remb_timer_dec = now - last_REMB_dec_; if ((not remb_dec_cnt_) or (remb_timer_dec > DELAY_AFTER_REMB_DEC)) { last_REMB_dec_ = now; remb_dec_cnt_ = 0; } // Limit REMB decrease to MAX_REMB_DEC every DELAY_AFTER_REMB_DEC ms if (remb_dec_cnt_ < MAX_REMB_DEC && remb_timer_dec < DELAY_AFTER_REMB_DEC) { remb_dec_cnt_++; JAMI_WARN("[BandwidthAdapt] Detected reception bandwidth overuse"); uint8_t* buf = nullptr; uint64_t br = 0x6803; // Decrease 3 auto v = cc->createREMB(br); buf = &v[0]; socketPair_->writeData(buf, v.size()); last_REMB_inc_ = clock::now(); } } else if (bwState == BandwidthUsage::bwNormal) { auto remb_timer_inc = now - last_REMB_inc_; if (remb_timer_inc > DELAY_AFTER_REMB_INC) { uint8_t* buf = nullptr; uint64_t br = 0x7378; // INcrease auto v = cc->createREMB(br); buf = &v[0]; socketPair_->writeData(buf, v.size()); last_REMB_inc_ = clock::now(); } } } } // namespace video } // namespace jami
30,114
C++
.cpp
829
28.180941
149
0.604087
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,755
video_device_impl.cpp
savoirfairelinux_jami-daemon/src/media/video/winvideo/video_device_impl.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <algorithm> #include <cassert> #include <climits> #include <map> #include <string> #include <sstream> #include <stdexcept> #include <string> #include <vector> #include <memory> #include "logger.h" #include "../video_device.h" #include "capture_graph_interfaces.h" #include <dshow.h> namespace jami { namespace video { class VideoDeviceImpl { public: /** * @throw std::runtime_error */ VideoDeviceImpl(const std::string& id); std::string id; std::string name; std::vector<std::string> getChannelList() const; std::vector<VideoSize> getSizeList(const std::string& channel) const; std::vector<VideoSize> getSizeList() const; std::vector<FrameRate> getRateList(const std::string& channel, VideoSize size) const; DeviceParams getDeviceParams() const; void setDeviceParams(const DeviceParams&); private: std::unique_ptr<CaptureGraphInterfaces> cInterface; void setup(); std::vector<VideoSize> sizeList_; std::map<VideoSize, std::vector<FrameRate>> rateList_; std::map<VideoSize, AM_MEDIA_TYPE*> capMap_; FrameRate desktopFrameRate_ = {30}; void fail(const std::string& error); }; VideoDeviceImpl::VideoDeviceImpl(const std::string& id) : id(id) , name() , cInterface(new CaptureGraphInterfaces()) { setup(); } void VideoDeviceImpl::setup() { if (id == DEVICE_DESKTOP) { name = DEVICE_DESKTOP; VideoSize size {0, 0}; sizeList_.emplace_back(size); rateList_[size] = {FrameRate(5), FrameRate(10), FrameRate(15), FrameRate(20), FrameRate(25), FrameRate(30), FrameRate(60), FrameRate(120), FrameRate(144)}; return; } HRESULT hr = CoCreateInstance(CLSID_CaptureGraphBuilder2, nullptr, CLSCTX_INPROC_SERVER, IID_ICaptureGraphBuilder2, (void**) &cInterface->captureGraph_); if (FAILED(hr)) return fail("Unable to create the Filter Graph Manager"); hr = CoCreateInstance(CLSID_FilterGraph, nullptr, CLSCTX_INPROC_SERVER, IID_IGraphBuilder, (void**) &cInterface->graph_); if (FAILED(hr)) return fail("Unable to add the graph builder!"); hr = cInterface->captureGraph_->SetFiltergraph(cInterface->graph_); if (FAILED(hr)) return fail("Unable to set filtergraph."); ICreateDevEnum* pDevEnum; hr = CoCreateInstance(CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pDevEnum)); IEnumMoniker* pEnum = NULL; hr = pDevEnum->CreateClassEnumerator(CLSID_VideoInputDeviceCategory, &pEnum, 0); if (hr == S_FALSE) { hr = VFW_E_NOT_FOUND; } pDevEnum->Release(); if (FAILED(hr) || pEnum == nullptr) { JAMI_ERR() << "No webcam found"; return; } // Auto-deletion at exception auto IEnumMonikerDeleter = [](IEnumMoniker* p) { p->Release(); }; std::unique_ptr<IEnumMoniker, decltype(IEnumMonikerDeleter)&> pEnumGuard {pEnum, IEnumMonikerDeleter}; IMoniker* pMoniker = NULL; while ((pEnumGuard->Next(1, &pMoniker, NULL) == S_OK)) { IPropertyBag* pPropBag; hr = pMoniker->BindToStorage(0, 0, IID_IPropertyBag, (void**) &pPropBag); if (FAILED(hr)) { pMoniker->Release(); continue; } IBindCtx* bind_ctx = NULL; LPOLESTR olestr = NULL; hr = CreateBindCtx(0, &bind_ctx); if (hr != S_OK) { continue; } hr = pMoniker->GetDisplayName(bind_ctx, NULL, &olestr); if (hr != S_OK) { continue; } auto unique_name = to_string(olestr); if (unique_name.empty()) { continue; } // replace ':' with '_' since ffmpeg uses : to delineate between sources */ std::replace(unique_name.begin(), unique_name.end(), ':', '_'); unique_name = std::string("video=") + unique_name; // We want to get the capabilities of a device with the unique_name // that corresponds to what was enumerated by the video device monitor. if (unique_name.find(this->id) == std::string::npos) { continue; } this->id = unique_name; // get friendly name VARIANT var; VariantInit(&var); hr = pPropBag->Read(L"Description", &var, 0); if (FAILED(hr)) { hr = pPropBag->Read(L"FriendlyName", &var, 0); } if (SUCCEEDED(hr)) { this->name = to_string(var.bstrVal); } pPropBag->Write(L"FriendlyName", &var); hr = pMoniker->BindToObject(nullptr, nullptr, IID_IBaseFilter, (void**) &cInterface->videoInputFilter_); if (SUCCEEDED(hr)) hr = cInterface->graph_->AddFilter(cInterface->videoInputFilter_, var.bstrVal); else { fail("Unable to add filter to video device."); } hr = cInterface->captureGraph_->FindInterface(&PIN_CATEGORY_PREVIEW, &MEDIATYPE_Video, cInterface->videoInputFilter_, IID_IAMStreamConfig, (void**) &cInterface->streamConf_); if (FAILED(hr)) { hr = cInterface->captureGraph_->FindInterface(&PIN_CATEGORY_CAPTURE, &MEDIATYPE_Video, cInterface->videoInputFilter_, IID_IAMStreamConfig, (void**) &cInterface->streamConf_); if (FAILED(hr)) { fail("Unable to config the stream!"); } } VariantClear(&var); pPropBag->Release(); // Device found. break; } pMoniker->Release(); if (FAILED(hr) || cInterface->streamConf_ == NULL) { fail("Unable to find the video device."); } int piCount; int piSize; cInterface->streamConf_->GetNumberOfCapabilities(&piCount, &piSize); AM_MEDIA_TYPE* pmt; VIDEO_STREAM_CONFIG_CAPS pSCC; std::map<std::pair<jami::video::VideoSize, jami::video::FrameRate>, LONG> bitrateList; for (int i = 0; i < piCount; i++) { cInterface->streamConf_->GetStreamCaps(i, &pmt, (BYTE*) &pSCC); if (pmt->formattype != FORMAT_VideoInfo) { continue; } auto videoInfo = (VIDEOINFOHEADER*) pmt->pbFormat; auto size = jami::video::VideoSize(videoInfo->bmiHeader.biWidth, videoInfo->bmiHeader.biHeight); // use 1e7 / MinFrameInterval to get maximum fps auto rate = jami::video::FrameRate(1e7, pSCC.MinFrameInterval); auto bitrate = videoInfo->dwBitRate; // Only add configurations with positive bitrates. if (bitrate == 0) continue; // Avoid adding multiple rates with different bitrates. auto ratesIt = rateList_.find(size); if (ratesIt != rateList_.end() && std::find(ratesIt->second.begin(), ratesIt->second.end(), rate) != ratesIt->second.end()) { // Update bitrate and cap map if the bitrate is greater. auto key = std::make_pair(size, rate); if (bitrate > bitrateList[key]) { bitrateList[key] = bitrate; capMap_[size] = pmt; } continue; } // Add new size, rate, bitrate, and cap map. sizeList_.emplace_back(size); rateList_[size].emplace_back(rate); bitrateList[std::make_pair(size, rate)] = bitrate; capMap_[size] = pmt; } } void VideoDeviceImpl::fail(const std::string& error) { throw std::runtime_error(error); } DeviceParams VideoDeviceImpl::getDeviceParams() const { DeviceParams params; params.name = name; params.unique_id = id; params.input = id; if (id == DEVICE_DESKTOP) { params.format = "dxgigrab"; params.framerate = desktopFrameRate_; return params; } params.format = "dshow"; AM_MEDIA_TYPE* pmt; HRESULT hr = cInterface->streamConf_->GetFormat(&pmt); if (SUCCEEDED(hr)) { if (pmt->formattype == FORMAT_VideoInfo) { auto videoInfo = (VIDEOINFOHEADER*) pmt->pbFormat; params.width = videoInfo->bmiHeader.biWidth; params.height = videoInfo->bmiHeader.biHeight; params.framerate = {1e7, static_cast<double>(videoInfo->AvgTimePerFrame)}; } } return params; } void VideoDeviceImpl::setDeviceParams(const DeviceParams& params) { if (id == DEVICE_DESKTOP) { desktopFrameRate_ = params.framerate; return; } if (params.width and params.height) { auto pmt = capMap_.at(std::make_pair(params.width, params.height)); if (pmt != nullptr) { ((VIDEOINFOHEADER*) pmt->pbFormat)->AvgTimePerFrame = (FrameRate(1e7) / params.framerate).real(); if (FAILED(cInterface->streamConf_->SetFormat(pmt))) { JAMI_ERR("Unable to set settings."); } } } } std::vector<VideoSize> VideoDeviceImpl::getSizeList() const { return sizeList_; } std::vector<FrameRate> VideoDeviceImpl::getRateList(const std::string& channel, VideoSize size) const { (void) channel; return rateList_.at(size); } std::vector<VideoSize> VideoDeviceImpl::getSizeList(const std::string& channel) const { (void) channel; return sizeList_; } std::vector<std::string> VideoDeviceImpl::getChannelList() const { return {"default"}; } VideoDevice::VideoDevice(const std::string& path, const std::vector<std::map<std::string, std::string>>&) : deviceImpl_(new VideoDeviceImpl(path)) { id_ = path; name = deviceImpl_->name; } DeviceParams VideoDevice::getDeviceParams() const { return deviceImpl_->getDeviceParams(); } void VideoDevice::setDeviceParams(const DeviceParams& params) { return deviceImpl_->setDeviceParams(params); } std::vector<std::string> VideoDevice::getChannelList() const { return deviceImpl_->getChannelList(); } std::vector<VideoSize> VideoDevice::getSizeList(const std::string& channel) const { return deviceImpl_->getSizeList(channel); } std::vector<FrameRate> VideoDevice::getRateList(const std::string& channel, VideoSize size) const { return deviceImpl_->getRateList(channel, size); } VideoDevice::~VideoDevice() {} } // namespace video } // namespace jami
12,049
C++
.cpp
339
26.368732
99
0.582697
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,756
video_device_monitor_impl.cpp
savoirfairelinux_jami-daemon/src/media/video/winvideo/video_device_monitor_impl.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "../video_device_monitor.h" #include "logger.h" #include "noncopyable.h" #include "string_utils.h" #include <dshow.h> #include <dbt.h> #include <SetupAPI.h> #include <algorithm> #include <string> #include <thread> #include <vector> #include <cctype> namespace jami { namespace video { constexpr GUID guidCamera = {0xe5323777, 0xf976, 0x4f5b, 0x9b, 0x55, 0xb9, 0x46, 0x99, 0xc4, 0x6e, 0x44}; class VideoDeviceMonitorImpl { public: VideoDeviceMonitorImpl(VideoDeviceMonitor* monitor); ~VideoDeviceMonitorImpl(); void start(); private: NON_COPYABLE(VideoDeviceMonitorImpl); VideoDeviceMonitor* monitor_; void run(); std::vector<std::string> enumerateVideoInputDevices(); std::thread thread_; HWND hWnd_; static LRESULT CALLBACK WinProcCallback(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); }; VideoDeviceMonitorImpl::VideoDeviceMonitorImpl(VideoDeviceMonitor* monitor) : monitor_(monitor) , thread_() {} void VideoDeviceMonitorImpl::start() { // Enumerate the initial capture device list. auto captureDeviceList = enumerateVideoInputDevices(); for (auto node : captureDeviceList) { monitor_->addDevice(node); } thread_ = std::thread(&VideoDeviceMonitorImpl::run, this); } VideoDeviceMonitorImpl::~VideoDeviceMonitorImpl() { SendMessage(hWnd_, WM_DESTROY, 0, 0); if (thread_.joinable()) thread_.join(); } std::string getDeviceUniqueName(PDEV_BROADCAST_DEVICEINTERFACE_A pbdi) { std::string unique_name = pbdi->dbcc_name; std::transform(unique_name.begin(), unique_name.end(), unique_name.begin(), [](unsigned char c) { return std::tolower(c); }); auto pos = unique_name.find_last_of("#"); unique_name = unique_name.substr(0, pos); return unique_name; } bool registerDeviceInterfaceToHwnd(HWND hWnd, HDEVNOTIFY* hDeviceNotify) { // Use a guid for cameras specifically in order to not get spammed // with device messages. // These are pertinent GUIDs for media devices: // // usb interfaces { 0xa5dcbf10l, 0x6530, 0x11d2, 0x90, 0x1f, 0x00, 0xc0, 0x4f, 0xb9, 0x51, // 0xed }; image devices { 0x6bdd1fc6, 0x810f, 0x11d0, 0xbe, 0xc7, 0x08, 0x00, 0x2b, 0xe2, // 0x09, 0x2f }; capture devices { 0x65e8773d, 0x8f56, 0x11d0, 0xa3, 0xb9, 0x00, 0xa0, 0xc9, // 0x22, 0x31, 0x96 }; camera devices { 0xe5323777, 0xf976, 0x4f5b, 0x9b, 0x55, 0xb9, 0x46, // 0x99, 0xc4, 0x6e, 0x44 }; audio devices { 0x6994ad04, 0x93ef, 0x11d0, 0xa3, 0xcc, 0x00, // 0xa0, 0xc9, 0x22, 0x31, 0x96 }; DEV_BROADCAST_DEVICEINTERFACE NotificationFilter; ZeroMemory(&NotificationFilter, sizeof(NotificationFilter)); NotificationFilter.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE); NotificationFilter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; NotificationFilter.dbcc_classguid = guidCamera; *hDeviceNotify = RegisterDeviceNotification(hWnd, &NotificationFilter, DEVICE_NOTIFY_WINDOW_HANDLE); if (nullptr == *hDeviceNotify) { return false; } return true; } LRESULT CALLBACK VideoDeviceMonitorImpl::WinProcCallback(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { LRESULT lRet = 1; static HDEVNOTIFY hDeviceNotify; VideoDeviceMonitorImpl* pThis; switch (message) { case WM_CREATE: { // Store object pointer passed from CreateWindowEx. auto createParams = reinterpret_cast<CREATESTRUCT*>(lParam)->lpCreateParams; pThis = static_cast<VideoDeviceMonitorImpl*>(createParams); SetLastError(0); SetWindowLongPtr(hWnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(pThis)); if (!registerDeviceInterfaceToHwnd(hWnd, &hDeviceNotify)) { JAMI_ERR() << "Cannot register for device change notifications"; SendMessage(hWnd, WM_DESTROY, 0, 0); } } break; case WM_DEVICECHANGE: { switch (wParam) { case DBT_DEVICEREMOVECOMPLETE: case DBT_DEVICEARRIVAL: { PDEV_BROADCAST_DEVICEINTERFACE_A pbdi = (PDEV_BROADCAST_DEVICEINTERFACE_A) lParam; auto unique_name = getDeviceUniqueName(pbdi); if (!unique_name.empty()) { JAMI_DBG() << unique_name << ((wParam == DBT_DEVICEARRIVAL) ? " plugged" : " unplugged"); if (pThis = reinterpret_cast<VideoDeviceMonitorImpl*>( GetWindowLongPtr(hWnd, GWLP_USERDATA))) { if (wParam == DBT_DEVICEARRIVAL) { auto captureDeviceList = pThis->enumerateVideoInputDevices(); for (auto id : captureDeviceList) { if (id.find(unique_name) != std::string::npos) pThis->monitor_->addDevice(id); } } else if (wParam == DBT_DEVICEREMOVECOMPLETE) { pThis->monitor_->removeDevice(unique_name); } } } } break; default: break; } break; } break; case WM_CLOSE: UnregisterDeviceNotification(hDeviceNotify); DestroyWindow(hWnd); break; case WM_DESTROY: PostQuitMessage(0); break; default: lRet = DefWindowProc(hWnd, message, wParam, lParam); break; } return lRet; } void VideoDeviceMonitorImpl::run() { // Create a dummy window with the sole purpose to receive device change messages. static const char* className = "Message"; WNDCLASSEX wx = {}; wx.cbSize = sizeof(WNDCLASSEX); wx.lpfnWndProc = WinProcCallback; wx.hInstance = reinterpret_cast<HINSTANCE>(GetModuleHandle(0)); wx.lpszClassName = className; if (RegisterClassEx(&wx)) { // Pass this as lpParam so WinProcCallback can access members of VideoDeviceMonitorImpl. hWnd_ = CreateWindowEx( 0, className, "devicenotifications", 0, 0, 0, 0, 0, HWND_MESSAGE, NULL, NULL, this); } // Run the message loop that will finish once a WM_DESTROY message // has been sent, allowing the thread to join. MSG msg; int retVal; while ((retVal = GetMessage(&msg, NULL, 0, 0)) != 0) { if (retVal != -1) { TranslateMessage(&msg); DispatchMessage(&msg); } } } std::vector<std::string> VideoDeviceMonitorImpl::enumerateVideoInputDevices() { std::vector<std::string> deviceList; ICreateDevEnum* pDevEnum; HRESULT hr = CoCreateInstance(CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pDevEnum)); if (FAILED(hr)) { JAMI_ERR() << "Unable to enumerate webcams"; return {}; } IEnumMoniker* pEnum = nullptr; hr = pDevEnum->CreateClassEnumerator(CLSID_VideoInputDeviceCategory, &pEnum, 0); if (hr == S_FALSE) { hr = VFW_E_NOT_FOUND; } pDevEnum->Release(); if (FAILED(hr) || pEnum == nullptr) { JAMI_ERR() << "No webcam found"; return {}; } IMoniker* pMoniker = NULL; while (pEnum->Next(1, &pMoniker, NULL) == S_OK) { IPropertyBag* pPropBag; HRESULT hr = pMoniker->BindToStorage(0, 0, IID_PPV_ARGS(&pPropBag)); if (FAILED(hr)) { pMoniker->Release(); continue; } IBindCtx* bind_ctx = NULL; LPOLESTR olestr = NULL; hr = CreateBindCtx(0, &bind_ctx); if (hr != S_OK) { continue; } hr = pMoniker->GetDisplayName(bind_ctx, NULL, &olestr); if (hr != S_OK) { continue; } auto unique_name = to_string(olestr); if (!unique_name.empty()) { // replace ':' with '_' since ffmpeg uses : to delineate between sources std::replace(unique_name.begin(), unique_name.end(), ':', '_'); deviceList.push_back(std::string("video=") + unique_name); } pPropBag->Release(); } pEnum->Release(); return deviceList; } VideoDeviceMonitor::VideoDeviceMonitor() : preferences_() , devices_() , monitorImpl_(new VideoDeviceMonitorImpl(this)) { monitorImpl_->start(); addDevice(DEVICE_DESKTOP, {}); } VideoDeviceMonitor::~VideoDeviceMonitor() {} } // namespace video } // namespace jami
9,250
C++
.cpp
252
29.519841
101
0.636689
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,757
video_device_impl.cpp
savoirfairelinux_jami-daemon/src/media/video/v4l2/video_device_impl.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <algorithm> #include <cassert> #include <climits> #include <cstring> #include <map> #include <sstream> #include <stdexcept> #include <string> #include <vector> extern "C" { #include <linux/videodev2.h> #if !defined(VIDIOC_ENUM_FRAMESIZES) || !defined(VIDIOC_ENUM_FRAMEINTERVALS) #error You need at least Linux 2.6.19 #endif #include <fcntl.h> #include <unistd.h> #include <sys/ioctl.h> } #include "logger.h" #include "../video_device.h" #include "string_utils.h" #define ZEROVAR(x) std::memset(&(x), 0, sizeof(x)) namespace jami { namespace video { class VideoV4l2Rate { public: VideoV4l2Rate(unsigned rate_numerator = 0, unsigned rate_denominator = 0, unsigned format = 0) : frame_rate(rate_denominator, rate_numerator) , pixel_format(format) {} FrameRate frame_rate; unsigned pixel_format; std::string libAvPixelformat() const; }; class VideoV4l2Size { public: VideoV4l2Size(const unsigned width, const unsigned height) : width(width) , height(height) , rates_() {} /** * @throw std::runtime_error */ void readFrameRates(int fd, unsigned int pixel_format); std::vector<FrameRate> getRateList() const; VideoV4l2Rate getRate(const FrameRate& rate) const; unsigned width; unsigned height; private: void addRate(VideoV4l2Rate proposed_rate); std::vector<VideoV4l2Rate> rates_; }; bool operator==(VideoV4l2Size& a, VideoV4l2Size& b) { return a.height == b.height && a.width == b.width; } class VideoV4l2Channel { public: VideoV4l2Channel(unsigned idx, const char* s); /** * @throw std::runtime_error */ void readFormats(int fd); /** * @throw std::runtime_error */ unsigned int readSizes(int fd, unsigned int pixel_format); std::vector<VideoSize> getSizeList() const; const VideoV4l2Size& getSize(VideoSize name) const; unsigned idx; std::string name; private: void putCIFFirst(); std::vector<VideoV4l2Size> sizes_; }; class VideoDeviceImpl { public: /** * @throw std::runtime_error */ VideoDeviceImpl(const std::string& id, const std::string& path); std::string unique_id; std::string path; std::string name; std::vector<std::string> getChannelList() const; std::vector<VideoSize> getSizeList(const std::string& channel) const; std::vector<FrameRate> getRateList(const std::string& channel, VideoSize size) const; DeviceParams getDeviceParams() const; void setDeviceParams(const DeviceParams&); private: std::vector<VideoV4l2Channel> channels_; const VideoV4l2Channel& getChannel(const std::string& name) const; /* Preferences */ VideoV4l2Channel channel_; VideoV4l2Size size_; VideoV4l2Rate rate_; }; static const unsigned pixelformats_supported[] = { /* pixel format depth description */ /* preferred formats, they can be fed directly to the video encoder */ V4L2_PIX_FMT_YUV420, /* 12 YUV 4:2:0 */ V4L2_PIX_FMT_YUV422P, /* 16 YVU422 planar */ V4L2_PIX_FMT_YUV444, /* 16 xxxxyyyy uuuuvvvv */ /* Luminance+Chrominance formats */ V4L2_PIX_FMT_YVU410, /* 9 YVU 4:1:0 */ V4L2_PIX_FMT_YVU420, /* 12 YVU 4:2:0 */ V4L2_PIX_FMT_YUYV, /* 16 YUV 4:2:2 */ V4L2_PIX_FMT_YYUV, /* 16 YUV 4:2:2 */ V4L2_PIX_FMT_YVYU, /* 16 YVU 4:2:2 */ V4L2_PIX_FMT_UYVY, /* 16 YUV 4:2:2 */ V4L2_PIX_FMT_VYUY, /* 16 YUV 4:2:2 */ V4L2_PIX_FMT_YUV411P, /* 16 YVU411 planar */ V4L2_PIX_FMT_Y41P, /* 12 YUV 4:1:1 */ V4L2_PIX_FMT_YUV555, /* 16 YUV-5-5-5 */ V4L2_PIX_FMT_YUV565, /* 16 YUV-5-6-5 */ V4L2_PIX_FMT_YUV32, /* 32 YUV-8-8-8-8 */ V4L2_PIX_FMT_YUV410, /* 9 YUV 4:1:0 */ V4L2_PIX_FMT_HI240, /* 8 8-bit color */ V4L2_PIX_FMT_HM12, /* 8 YUV 4:2:0 16x16 macroblocks */ /* two planes -- one Y, one Cr + Cb interleaved */ V4L2_PIX_FMT_NV12, /* 12 Y/CbCr 4:2:0 */ V4L2_PIX_FMT_NV21, /* 12 Y/CrCb 4:2:0 */ V4L2_PIX_FMT_NV16, /* 16 Y/CbCr 4:2:2 */ V4L2_PIX_FMT_NV61, /* 16 Y/CrCb 4:2:2 */ /* Compressed formats */ V4L2_PIX_FMT_MJPEG, V4L2_PIX_FMT_JPEG, V4L2_PIX_FMT_DV, V4L2_PIX_FMT_MPEG, V4L2_PIX_FMT_H264, V4L2_PIX_FMT_H264_NO_SC, V4L2_PIX_FMT_H264_MVC, V4L2_PIX_FMT_H263, V4L2_PIX_FMT_MPEG1, V4L2_PIX_FMT_MPEG2, V4L2_PIX_FMT_MPEG4, V4L2_PIX_FMT_XVID, V4L2_PIX_FMT_VC1_ANNEX_G, V4L2_PIX_FMT_VC1_ANNEX_L, V4L2_PIX_FMT_VP8, #if 0 /* RGB formats */ V4L2_PIX_FMT_RGB332, /* 8 RGB-3-3-2 */ V4L2_PIX_FMT_RGB444, /* 16 xxxxrrrr ggggbbbb */ V4L2_PIX_FMT_RGB555, /* 16 RGB-5-5-5 */ V4L2_PIX_FMT_RGB565, /* 16 RGB-5-6-5 */ V4L2_PIX_FMT_RGB555X, /* 16 RGB-5-5-5 BE */ V4L2_PIX_FMT_RGB565X, /* 16 RGB-5-6-5 BE */ V4L2_PIX_FMT_BGR666, /* 18 BGR-6-6-6 */ V4L2_PIX_FMT_BGR24, /* 24 BGR-8-8-8 */ V4L2_PIX_FMT_RGB24, /* 24 RGB-8-8-8 */ V4L2_PIX_FMT_BGR32, /* 32 BGR-8-8-8-8 */ V4L2_PIX_FMT_RGB32, /* 32 RGB-8-8-8-8 */ /* Grey formats */ V4L2_PIX_FMT_GREY, /* 8 Greyscale */ V4L2_PIX_FMT_Y4, /* 4 Greyscale */ V4L2_PIX_FMT_Y6, /* 6 Greyscale */ V4L2_PIX_FMT_Y10, /* 10 Greyscale */ V4L2_PIX_FMT_Y16, /* 16 Greyscale */ /* Palette formats */ V4L2_PIX_FMT_PAL8, /* 8 8-bit palette */ #endif }; /* Returns a score for the given pixelformat * * Lowest score is the best, the first entries in the array are the formats * supported as an input for the video encoders. * * See pixelformats_supported array for the support list. */ static unsigned int pixelformat_score(unsigned pixelformat) { unsigned int formats_count = std::size(pixelformats_supported); for (unsigned int i = 0; i < formats_count; ++i) { if (pixelformats_supported[i] == pixelformat) return i; } return UINT_MAX - 1; } using std::vector; using std::string; vector<FrameRate> VideoV4l2Size::getRateList() const { vector<FrameRate> rates; rates.reserve(rates_.size()); for (const auto& r : rates_) rates.emplace_back(r.frame_rate); return rates; } void VideoV4l2Size::readFrameRates(int fd, unsigned int pixel_format) { VideoV4l2Rate fallback_rate {1, 25, pixel_format}; v4l2_frmivalenum frmival; ZEROVAR(frmival); frmival.pixel_format = pixel_format; frmival.width = width; frmival.height = height; if (ioctl(fd, VIDIOC_ENUM_FRAMEINTERVALS, &frmival)) { addRate(fallback_rate); JAMI_ERR("Unable to query frame interval for size"); return; } if (frmival.type != V4L2_FRMIVAL_TYPE_DISCRETE) { addRate(fallback_rate); JAMI_ERR("Continuous and stepwise Frame Intervals are not supported"); return; } do { addRate({frmival.discrete.numerator, frmival.discrete.denominator, pixel_format}); ++frmival.index; } while (!ioctl(fd, VIDIOC_ENUM_FRAMEINTERVALS, &frmival)); } VideoV4l2Rate VideoV4l2Size::getRate(const FrameRate& rate) const { for (const auto& item : rates_) { if (std::fabs((item.frame_rate - rate).real()) < 0.0001) return item; } return rates_.back(); } void VideoV4l2Size::addRate(VideoV4l2Rate new_rate) { bool rate_found = false; for (auto& item : rates_) { if (item.frame_rate == new_rate.frame_rate) { if (pixelformat_score(item.pixel_format) > pixelformat_score(new_rate.pixel_format)) { // Make sure we will use the prefered pixelformat (lower score means prefered format) item.pixel_format = new_rate.pixel_format; } rate_found = true; } } if (!rate_found) rates_.push_back(new_rate); } VideoV4l2Channel::VideoV4l2Channel(unsigned idx, const char* s) : idx(idx) , name(s) , sizes_() {} std::vector<VideoSize> VideoV4l2Channel::getSizeList() const { vector<VideoSize> v; v.reserve(sizes_.size()); for (const auto& item : sizes_) v.emplace_back(item.width, item.height); return v; } unsigned int VideoV4l2Channel::readSizes(int fd, unsigned int pixelformat) { v4l2_frmsizeenum frmsize; ZEROVAR(frmsize); frmsize.index = 0; frmsize.pixel_format = pixelformat; if (ioctl(fd, VIDIOC_ENUM_FRAMESIZES, &frmsize) < 0) { v4l2_format fmt; ZEROVAR(fmt); fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; if (ioctl(fd, VIDIOC_G_FMT, &fmt) < 0) throw std::runtime_error("Unable to get format"); VideoV4l2Size size(fmt.fmt.pix.width, fmt.fmt.pix.height); size.readFrameRates(fd, fmt.fmt.pix.pixelformat); sizes_.push_back(size); return fmt.fmt.pix.pixelformat; } if (frmsize.type != V4L2_FRMSIZE_TYPE_DISCRETE) { // We do not take care of V4L2_FRMSIZE_TYPE_CONTINUOUS or V4L2_FRMSIZE_TYPE_STEPWISE JAMI_ERR("Continuous Frame sizes not supported"); return pixelformat; } // Real work starts here: attach framerates to sizes and update pixelformat information do { bool size_exists = false; VideoV4l2Size size(frmsize.discrete.width, frmsize.discrete.height); for (auto& item : sizes_) { if (item == size) { size_exists = true; // If a size already exist we add frame rates since there may be some // frame rates available in one format that are not availabe in another. item.readFrameRates(fd, frmsize.pixel_format); } } if (!size_exists) { size.readFrameRates(fd, frmsize.pixel_format); sizes_.push_back(size); } ++frmsize.index; } while (!ioctl(fd, VIDIOC_ENUM_FRAMESIZES, &frmsize)); return pixelformat; } // Put CIF resolution (352x288) first in the list since it is more prevalent in // VoIP void VideoV4l2Channel::putCIFFirst() { const auto iter = std::find_if(sizes_.begin(), sizes_.end(), [](const VideoV4l2Size& size) { return size.width == 352 and size.height == 258; }); if (iter != sizes_.end() and iter != sizes_.begin()) std::swap(*iter, *sizes_.begin()); } void VideoV4l2Channel::readFormats(int fd) { if (ioctl(fd, VIDIOC_S_INPUT, &idx)) throw std::runtime_error("VIDIOC_S_INPUT failed"); v4l2_fmtdesc fmt; ZEROVAR(fmt); unsigned fmt_index = 0; fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; while (!ioctl(fd, VIDIOC_ENUM_FMT, &fmt)) { if (fmt_index != fmt.index) break; readSizes(fd, fmt.pixelformat); fmt.index = ++fmt_index; } if (fmt_index == 0) throw std::runtime_error("Unable to enumerate formats"); putCIFFirst(); } const VideoV4l2Size& VideoV4l2Channel::getSize(VideoSize s) const { for (const auto& item : sizes_) { if (item.width == s.first && item.height == s.second) return item; } assert(not sizes_.empty()); return sizes_.front(); } VideoDeviceImpl::VideoDeviceImpl(const string& id, const std::string& path) : unique_id(id) , path(path) , name() , channels_() , channel_(-1, "") , size_(-1, -1) , rate_(-1, 1, 0) { if (id == DEVICE_DESKTOP) { name = DEVICE_DESKTOP; rate_.frame_rate = 30; return; } int fd = open(path.c_str(), O_RDWR); if (fd == -1) throw std::runtime_error("Unable to open device"); v4l2_capability cap; if (ioctl(fd, VIDIOC_QUERYCAP, &cap)) throw std::runtime_error("Unable to query capabilities"); if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)) throw std::runtime_error("Not a capture device"); if (cap.capabilities & V4L2_CAP_TOUCH) throw std::runtime_error("Touch device, ignoring it"); name = string(reinterpret_cast<const char*>(cap.card)); v4l2_input input; ZEROVAR(input); unsigned idx; input.index = idx = 0; while (!ioctl(fd, VIDIOC_ENUMINPUT, &input)) { if (idx != input.index) break; if (input.type & V4L2_INPUT_TYPE_CAMERA) { VideoV4l2Channel channel(idx, (const char*) input.name); channel.readFormats(fd); if (not channel.getSizeList().empty()) channels_.push_back(channel); } input.index = ++idx; } ::close(fd); } string VideoV4l2Rate::libAvPixelformat() const { switch (pixel_format) { // Set codec name for those pixelformats. // Those names can be found in libavcodec/codec_desc.c case V4L2_PIX_FMT_MJPEG: return "mjpeg"; case V4L2_PIX_FMT_DV: return "dvvideo"; case V4L2_PIX_FMT_MPEG: case V4L2_PIX_FMT_MPEG1: return "mpeg1video"; case V4L2_PIX_FMT_H264: case V4L2_PIX_FMT_H264_NO_SC: case V4L2_PIX_FMT_H264_MVC: return "h264"; case V4L2_PIX_FMT_H263: return "h263"; case V4L2_PIX_FMT_MPEG2: return "mpeg2video"; case V4L2_PIX_FMT_MPEG4: return "mpeg4"; case V4L2_PIX_FMT_VC1_ANNEX_G: case V4L2_PIX_FMT_VC1_ANNEX_L: return "vc1"; case V4L2_PIX_FMT_VP8: return "vp8"; default: // Most pixel formats do not need any codec return ""; } } vector<string> VideoDeviceImpl::getChannelList() const { if (unique_id == DEVICE_DESKTOP) return {"default"}; vector<string> v; v.reserve(channels_.size()); for (const auto& itr : channels_) v.push_back(itr.name); return v; } vector<VideoSize> VideoDeviceImpl::getSizeList(const string& channel) const { if (unique_id == DEVICE_DESKTOP) { return {VideoSize(0, 0)}; } return getChannel(channel).getSizeList(); } vector<FrameRate> VideoDeviceImpl::getRateList(const string& channel, VideoSize size) const { if (unique_id == DEVICE_DESKTOP) { return {FrameRate(5), FrameRate(10), FrameRate(15), FrameRate(20), FrameRate(25), FrameRate(30), FrameRate(60), FrameRate(120), FrameRate(144)}; } return getChannel(channel).getSize(size).getRateList(); } const VideoV4l2Channel& VideoDeviceImpl::getChannel(const string& name) const { for (const auto& item : channels_) if (item.name == name) return item; assert(not channels_.empty()); return channels_.front(); } DeviceParams VideoDeviceImpl::getDeviceParams() const { DeviceParams params; params.name = name; params.unique_id = unique_id; params.input = path; if (unique_id == DEVICE_DESKTOP) { const auto* env = std::getenv("WAYLAND_DISPLAY"); if (!env || strlen(env) == 0) { params.format = "x11grab"; } else { params.format = "lavfi"; params.input = "pipewiregrab"; } params.framerate = rate_.frame_rate; return params; } params.format = "video4linux2"; params.channel_name = channel_.name; params.channel = channel_.idx; params.width = size_.width; params.height = size_.height; params.framerate = rate_.frame_rate; params.pixel_format = rate_.libAvPixelformat(); return params; } void VideoDeviceImpl::setDeviceParams(const DeviceParams& params) { if (unique_id == DEVICE_DESKTOP) { rate_.frame_rate = params.framerate; return; } // Set preferences or fallback to defaults. channel_ = getChannel(params.channel_name); size_ = channel_.getSize({params.width, params.height}); try { rate_ = size_.getRate(params.framerate); } catch (...) { rate_ = {}; } } VideoDevice::VideoDevice(const std::string& id, const std::vector<std::map<std::string, std::string>>& devInfo) : id_(id) { deviceImpl_ = std::make_shared<VideoDeviceImpl>(id, devInfo.empty() ? id : devInfo.at(0).at("devPath")); name = deviceImpl_->name; } DeviceParams VideoDevice::getDeviceParams() const { auto params = deviceImpl_->getDeviceParams(); params.orientation = orientation_; return params; } void VideoDevice::setDeviceParams(const DeviceParams& params) { return deviceImpl_->setDeviceParams(params); } std::vector<std::string> VideoDevice::getChannelList() const { return deviceImpl_->getChannelList(); } std::vector<VideoSize> VideoDevice::getSizeList(const std::string& channel) const { return deviceImpl_->getSizeList(channel); } std::vector<FrameRate> VideoDevice::getRateList(const std::string& channel, VideoSize size) const { return deviceImpl_->getRateList(channel, size); } VideoDevice::~VideoDevice() {} } // namespace video } // namespace jami
17,781
C++
.cpp
559
26.420394
101
0.634145
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,758
video_device_monitor_impl.cpp
savoirfairelinux_jami-daemon/src/media/video/v4l2/video_device_monitor_impl.cpp
/* * Copyright (C) 2009 Rémi Denis-Courmont * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <algorithm> #include <cerrno> #include <cstdio> #include <cstring> #include <libudev.h> #include <mutex> #include <sstream> #include <stdexcept> // for std::runtime_error #include <string> #include <thread> #include <unistd.h> #include <vector> #include "../video_device_monitor.h" #include "logger.h" #include "noncopyable.h" extern "C" { #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> } namespace jami { namespace video { using std::vector; using std::string; class VideoDeviceMonitorImpl { public: /* * This is the only restriction to the pImpl design: * as the Linux implementation has a thread, it needs a way to notify * devices addition and deletion. * * This class should maybe inherit from VideoDeviceMonitor instead of * being its pImpl. */ VideoDeviceMonitorImpl(VideoDeviceMonitor* monitor); ~VideoDeviceMonitorImpl(); void start(); std::map<std::string, std::string> currentPathToId_ {}; private: NON_COPYABLE(VideoDeviceMonitorImpl); VideoDeviceMonitor* monitor_; void run(); std::thread thread_; mutable std::mutex mutex_; udev* udev_; udev_monitor* udev_mon_; bool probing_; }; std::string getDeviceString(struct udev_device* udev_device) { if (auto serial = udev_device_get_property_value(udev_device, "ID_SERIAL")) return serial; throw std::invalid_argument("No ID_SERIAL detected"); } static int is_v4l2(struct udev_device* dev) { const char* version = udev_device_get_property_value(dev, "ID_V4L_VERSION"); /* we do not support video4linux 1 */ return version and strcmp(version, "1"); } VideoDeviceMonitorImpl::VideoDeviceMonitorImpl(VideoDeviceMonitor* monitor) : monitor_(monitor) , thread_() , mutex_() , udev_(0) , udev_mon_(0) , probing_(false) { udev_list_entry* devlist; udev_enumerate* devenum; udev_ = udev_new(); if (!udev_) goto udev_failed; udev_mon_ = udev_monitor_new_from_netlink(udev_, "udev"); if (!udev_mon_) goto udev_failed; if (udev_monitor_filter_add_match_subsystem_devtype(udev_mon_, "video4linux", NULL)) goto udev_failed; /* Enumerate existing devices */ devenum = udev_enumerate_new(udev_); if (devenum == NULL) goto udev_failed; if (udev_enumerate_add_match_subsystem(devenum, "video4linux")) { udev_enumerate_unref(devenum); goto udev_failed; } udev_monitor_enable_receiving(udev_mon_); /* Note that we enumerate _after_ monitoring is enabled so that we do not * loose device events occuring while we are enumerating. We could still * loose events if the Netlink socket receive buffer overflows. */ udev_enumerate_scan_devices(devenum); devlist = udev_enumerate_get_list_entry(devenum); struct udev_list_entry* deventry; udev_list_entry_foreach(deventry, devlist) { const char* path = udev_list_entry_get_name(deventry); struct udev_device* dev = udev_device_new_from_syspath(udev_, path); if (is_v4l2(dev)) { const char* path = udev_device_get_devnode(dev); if (path && std::string(path).find("/dev") != 0) { // udev_device_get_devnode will fail continue; } try { auto unique_name = getDeviceString(dev); JAMI_DBG("udev: adding device with id %s", unique_name.c_str()); if (monitor_->addDevice(unique_name, {{{"devPath", path}}})) currentPathToId_.emplace(path, unique_name); } catch (const std::exception& e) { JAMI_WARN("udev: %s, fallback on path (your camera may be a fake camera)", e.what()); if (monitor_->addDevice(path, {{{"devPath", path}}})) currentPathToId_.emplace(path, path); } } udev_device_unref(dev); } udev_enumerate_unref(devenum); return; udev_failed: JAMI_ERR("udev enumeration failed"); if (udev_mon_) udev_monitor_unref(udev_mon_); if (udev_) udev_unref(udev_); udev_mon_ = NULL; udev_ = NULL; /* fallback : go through /dev/video* */ for (int idx = 0;; ++idx) { try { if (!monitor_->addDevice("/dev/video" + std::to_string(idx))) break; } catch (const std::runtime_error& e) { JAMI_ERR("%s", e.what()); return; } } } void VideoDeviceMonitorImpl::start() { probing_ = true; thread_ = std::thread(&VideoDeviceMonitorImpl::run, this); } VideoDeviceMonitorImpl::~VideoDeviceMonitorImpl() { probing_ = false; if (thread_.joinable()) thread_.join(); if (udev_mon_) udev_monitor_unref(udev_mon_); if (udev_) udev_unref(udev_); } void VideoDeviceMonitorImpl::run() { if (!udev_mon_) { probing_ = false; return; } const int udev_fd = udev_monitor_get_fd(udev_mon_); while (probing_) { timeval timeout = {0 /* sec */, 500000 /* usec */}; fd_set set; FD_ZERO(&set); FD_SET(udev_fd, &set); int ret = select(udev_fd + 1, &set, NULL, NULL, &timeout); switch (ret) { case 0: break; case 1: { udev_device* dev = udev_monitor_receive_device(udev_mon_); if (is_v4l2(dev)) { const char* path = udev_device_get_devnode(dev); if (path && std::string(path).find("/dev") != 0) { // udev_device_get_devnode will fail break; } try { auto unique_name = getDeviceString(dev); const char* action = udev_device_get_action(dev); if (!strcmp(action, "add")) { JAMI_DBG("udev: adding device with id %s", unique_name.c_str()); if (monitor_->addDevice(unique_name, {{{"devPath", path}}})) currentPathToId_.emplace(path, unique_name); } else if (!strcmp(action, "remove")) { auto it = currentPathToId_.find(path); if (it != currentPathToId_.end()) { JAMI_DBG("udev: removing %s", it->second.c_str()); monitor_->removeDevice(it->second); currentPathToId_.erase(it); } else { // In case of fallback JAMI_DBG("udev: removing %s", path); monitor_->removeDevice(path); } } } catch (const std::exception& e) { JAMI_ERR("%s", e.what()); } } udev_device_unref(dev); break; } case -1: if (errno == EAGAIN) continue; JAMI_ERR("udev monitoring thread: select failed (%m)"); probing_ = false; return; default: JAMI_ERR("select() returned %d (%m)", ret); probing_ = false; return; } } } VideoDeviceMonitor::VideoDeviceMonitor() : preferences_() , devices_() , monitorImpl_(new VideoDeviceMonitorImpl(this)) { monitorImpl_->start(); addDevice(DEVICE_DESKTOP, {}); } VideoDeviceMonitor::~VideoDeviceMonitor() {} } // namespace video } // namespace jami
8,341
C++
.cpp
248
25.806452
101
0.586571
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,759
video_device_impl.cpp
savoirfairelinux_jami-daemon/src/media/video/iosvideo/video_device_impl.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <array> extern "C" { #include <libavutil/pixfmt.h> } #include "logger.h" #include "../video_device.h" #include "client/ring_signal.h" namespace jami { namespace video { typedef struct { std::string name; enum AVPixelFormat pixfmt; } ios_fmt; static const std::array<ios_fmt, 4> ios_formats {ios_fmt {"RGBA", AV_PIX_FMT_RGBA}, ios_fmt {"BGRA", AV_PIX_FMT_BGRA}, ios_fmt {"YUV420P", AV_PIX_FMT_YUV420P}}; class VideoDeviceImpl { public: VideoDeviceImpl(const std::string& path, const std::vector<std::map<std::string, std::string>>& devInfo); std::string name; DeviceParams getDeviceParams() const; void setDeviceParams(const DeviceParams&); void selectFormat(); std::vector<VideoSize> getSizeList() const; std::vector<FrameRate> getRateList() const; private: VideoSize getSize(VideoSize size) const; FrameRate getRate(FrameRate rate) const; std::vector<std::string> formats_ {}; std::vector<VideoSize> sizes_ {}; std::vector<FrameRate> rates_ {}; const ios_fmt* fmt_ {nullptr}; VideoSize size_ {}; FrameRate rate_ {}; }; void VideoDeviceImpl::selectFormat() { unsigned best = UINT_MAX; for (auto fmt : formats_) { auto f = ios_formats.begin(); for (; f != ios_formats.end(); ++f) { if (f->name == fmt) { auto pos = std::distance(ios_formats.begin(), f); if (pos < best) best = pos; break; } } if (f == ios_formats.end()) JAMI_WARN("Video: No format matching %s", fmt.c_str()); } if (best != UINT_MAX) { fmt_ = &ios_formats[best]; JAMI_DBG("Video: picked format %s", fmt_->name.c_str()); } else { fmt_ = &ios_formats[0]; JAMI_ERR("Video: Unable to find a known format to use"); } } VideoDeviceImpl::VideoDeviceImpl(const std::string& path, const std::vector<std::map<std::string, std::string>>& devInfo) : name(path) { for (auto& setting : devInfo) { formats_.emplace_back(setting.at("format")); sizes_.emplace_back(std::stoi(setting.at("width")), std::stoi(setting.at("height"))); rates_.emplace_back(std::stoi(setting.at("rate")), 1); } selectFormat(); } VideoSize VideoDeviceImpl::getSize(VideoSize size) const { for (const auto& iter : sizes_) { if (iter == size) return iter; } return sizes_.empty() ? VideoSize {0, 0} : sizes_.back(); } FrameRate VideoDeviceImpl::getRate(FrameRate rate) const { for (const auto& iter : rates_) { if (iter == rate) return iter; } return rates_.empty() ? FrameRate {0, 0} : rates_.back(); } std::vector<VideoSize> VideoDeviceImpl::getSizeList() const { return sizes_; } std::vector<FrameRate> VideoDeviceImpl::getRateList() const { return rates_; } DeviceParams VideoDeviceImpl::getDeviceParams() const { DeviceParams params; params.format = std::to_string(fmt_->pixfmt); params.name = name; params.input = name; params.unique_id = name; params.channel = 0; params.pixel_format = "nv12"; params.width = size_.first; params.height = size_.second; params.framerate = rate_; return params; } void VideoDeviceImpl::setDeviceParams(const DeviceParams& params) { size_ = getSize({params.width, params.height}); rate_ = getRate(params.framerate); emitSignal<libjami::VideoSignal::ParametersChanged>(name); } VideoDevice::VideoDevice(const std::string& path, const std::vector<std::map<std::string, std::string>>& devInfo) : deviceImpl_(new VideoDeviceImpl(path, devInfo)) { id_ = path; name = deviceImpl_->name; } DeviceParams VideoDevice::getDeviceParams() const { return deviceImpl_->getDeviceParams(); } void VideoDevice::setDeviceParams(const DeviceParams& params) { return deviceImpl_->setDeviceParams(params); } std::vector<std::string> VideoDevice::getChannelList() const { return {"default"}; } std::vector<VideoSize> VideoDevice::getSizeList(const std::string& channel) const { return deviceImpl_->getSizeList(); } std::vector<FrameRate> VideoDevice::getRateList(const std::string& channel, VideoSize size) const { return deviceImpl_->getRateList(); } VideoDevice::~VideoDevice() {} } // namespace video } // namespace jami
5,259
C++
.cpp
175
25.131429
96
0.653001
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,760
video_device_monitor_impl.cpp
savoirfairelinux_jami-daemon/src/media/video/iosvideo/video_device_monitor_impl.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <mutex> #include <thread> #include "../video_device_monitor.h" #include "logger.h" #include "noncopyable.h" namespace jami { namespace video { class VideoDeviceMonitorImpl { public: /* * This is the only restriction to the pImpl design: * as the Linux implementation has a thread, it needs a way to notify * devices addition and deletion. * * This class should maybe inherit from VideoDeviceMonitor instead of * being its pImpl. */ VideoDeviceMonitorImpl(VideoDeviceMonitor* monitor); ~VideoDeviceMonitorImpl(); void start(); private: NON_COPYABLE(VideoDeviceMonitorImpl); VideoDeviceMonitor* monitor_; void run(); mutable std::mutex mutex_; bool probing_; std::thread thread_; }; VideoDeviceMonitorImpl::VideoDeviceMonitorImpl(VideoDeviceMonitor* monitor) : monitor_(monitor) , mutex_() , thread_() {} void VideoDeviceMonitorImpl::start() { probing_ = true; thread_ = std::thread(&VideoDeviceMonitorImpl::run, this); } VideoDeviceMonitorImpl::~VideoDeviceMonitorImpl() { probing_ = false; if (thread_.joinable()) thread_.join(); } void VideoDeviceMonitorImpl::run() {} VideoDeviceMonitor::VideoDeviceMonitor() : preferences_() , devices_() , monitorImpl_(new VideoDeviceMonitorImpl(this)) { monitorImpl_->start(); } VideoDeviceMonitor::~VideoDeviceMonitor() {} } // namespace video } // namespace jami
2,172
C++
.cpp
75
25.853333
75
0.729457
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
751,761
video_device_impl.cpp
savoirfairelinux_jami-daemon/src/media/video/androidvideo/video_device_impl.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "logger.h" #include "../video_device.h" #include "client/ring_signal.h" #include <algorithm> #include <map> #include <sstream> #include <stdexcept> #include <string> #include <vector> #include <array> namespace jami { namespace video { /* * Array to match Android formats. List formats in ascending * preferrence: the format with the lower index will be picked. */ struct android_fmt { int code; std::string name; int ring_format; }; static const std::array<android_fmt, 2> and_formats { android_fmt {17, "NV21", AV_PIX_FMT_NV21}, android_fmt {842094169, "YUV420", AV_PIX_FMT_YUV420P}, }; class VideoDeviceImpl { public: /** * @throw std::runtime_error */ VideoDeviceImpl(const std::string& path); std::string name; DeviceParams getDeviceParams() const; void setDeviceParams(const DeviceParams&); std::vector<VideoSize> getSizeList() const; std::vector<FrameRate> getRateList() const; private: void selectFormat(); VideoSize getSize(const VideoSize& size) const; FrameRate getRate(const FrameRate& rate) const; std::vector<int> formats_ {}; std::vector<VideoSize> sizes_ {}; std::vector<FrameRate> rates_ {}; const android_fmt* fmt_ {nullptr}; VideoSize size_ {}; FrameRate rate_ {}; }; void VideoDeviceImpl::selectFormat() { /* * formats_ contains camera parameters as returned by the GetCameraInfo * signal, find the matching V4L2 formats */ unsigned best = UINT_MAX; for (auto fmt : formats_) { auto f = and_formats.begin(); for (; f != and_formats.end(); ++f) { if (f->code == fmt) { auto pos = std::distance(and_formats.begin(), f); if (pos < best) best = pos; break; } } if (f == and_formats.end()) JAMI_WARN("AndroidVideo: No format matching %d", fmt); } if (best != UINT_MAX) { fmt_ = &and_formats[best]; JAMI_DBG("AndroidVideo: picked format %s", fmt_->name.c_str()); } else { fmt_ = &and_formats[0]; JAMI_ERR("AndroidVideo: Unable to find a known format to use"); } } VideoDeviceImpl::VideoDeviceImpl(const std::string& path) : name(path) { std::vector<unsigned> sizes; std::vector<unsigned> rates; formats_.reserve(16); sizes.reserve(16); rates.reserve(16); emitSignal<libjami::VideoSignal::GetCameraInfo>(name, &formats_, &sizes, &rates); for (size_t i = 0, n = sizes.size(); i < n; i += 2) sizes_.emplace_back(sizes[i], sizes[i + 1]); for (const auto& r : rates) rates_.emplace_back(r, 1000); selectFormat(); } VideoSize VideoDeviceImpl::getSize(const VideoSize& size) const { for (const auto& iter : sizes_) { if (iter == size) return iter; } return sizes_.empty() ? VideoSize {0, 0} : sizes_.back(); } FrameRate VideoDeviceImpl::getRate(const FrameRate& rate) const { for (const auto& iter : rates_) { if (iter == rate) return iter; } return rates_.empty() ? FrameRate {} : rates_.back(); } std::vector<VideoSize> VideoDeviceImpl::getSizeList() const { return sizes_; } std::vector<FrameRate> VideoDeviceImpl::getRateList() const { return rates_; } DeviceParams VideoDeviceImpl::getDeviceParams() const { DeviceParams params; params.format = std::to_string(fmt_->ring_format); params.unique_id = name; params.name = name; params.input = name; params.channel = 0; params.width = size_.first; params.height = size_.second; params.framerate = rate_; return params; } void VideoDeviceImpl::setDeviceParams(const DeviceParams& params) { size_ = getSize({params.width, params.height}); rate_ = getRate(params.framerate); emitSignal<libjami::VideoSignal::SetParameters>(name, fmt_->code, size_.first, size_.second, rate_.real()); } VideoDevice::VideoDevice(const std::string& id, const std::vector<std::map<std::string, std::string>>&) : deviceImpl_(new VideoDeviceImpl(id)) { id_ = id; name = deviceImpl_->name; } DeviceParams VideoDevice::getDeviceParams() const { return deviceImpl_->getDeviceParams(); } void VideoDevice::setDeviceParams(const DeviceParams& params) { return deviceImpl_->setDeviceParams(params); } std::vector<std::string> VideoDevice::getChannelList() const { return {"default"}; } std::vector<VideoSize> VideoDevice::getSizeList(const std::string& /* channel */) const { return deviceImpl_->getSizeList(); } std::vector<FrameRate> VideoDevice::getRateList(const std::string& /* channel */, VideoSize /* size */) const { return deviceImpl_->getRateList(); } VideoDevice::~VideoDevice() {} } // namespace video } // namespace jami
5,764
C++
.cpp
197
24.233503
86
0.646729
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,762
video_device_monitor_impl.cpp
savoirfairelinux_jami-daemon/src/media/video/androidvideo/video_device_monitor_impl.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "../video_device_monitor.h" #include "logger.h" #include "noncopyable.h" #include "client/ring_signal.h" #include <algorithm> #include <mutex> #include <sstream> #include <stdexcept> // for std::runtime_error #include <string> #include <thread> #include <vector> namespace jami { namespace video { using std::vector; using std::string; class VideoDeviceMonitorImpl { /* * This class is instantiated in VideoDeviceMonitor's constructor. The * daemon has a global VideoManager, and it contains a VideoDeviceMonitor. * So, when the library is loaded on Android, VideoDeviceMonitorImpl will * be instantiated before we get a chance to register callbacks. At this * point, if we use emitSignal to get a list of cameras, it will simply * do nothing. * To work around this issue, functions have been added in the video * manager interface to allow to add/remove devices from Java code. * To conclude, this class is just an empty stub. */ public: VideoDeviceMonitorImpl(VideoDeviceMonitor* monitor); ~VideoDeviceMonitorImpl(); void start(); private: NON_COPYABLE(VideoDeviceMonitorImpl); }; VideoDeviceMonitorImpl::VideoDeviceMonitorImpl(VideoDeviceMonitor* monitor) {} void VideoDeviceMonitorImpl::start() {} VideoDeviceMonitorImpl::~VideoDeviceMonitorImpl() {} VideoDeviceMonitor::VideoDeviceMonitor() : preferences_() , devices_() , monitorImpl_(new VideoDeviceMonitorImpl(this)) {} VideoDeviceMonitor::~VideoDeviceMonitor() {} } // namespace video } // namespace jami
2,286
C++
.cpp
64
32.984375
78
0.754982
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
751,763
tonecontrol.cpp
savoirfairelinux_jami-daemon/src/media/audio/tonecontrol.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "audio/tonecontrol.h" #include "sound/tonelist.h" #include "client/ring_signal.h" #include "jami/callmanager_interface.h" // for CallSignal namespace jami { static constexpr unsigned DEFAULT_SAMPLE_RATE = 8000; ToneControl::ToneControl(const Preferences& preferences) : prefs_(preferences) , sampleRate_(DEFAULT_SAMPLE_RATE) {} ToneControl::~ToneControl() {} void ToneControl::setSampleRate(unsigned rate, AVSampleFormat sampleFormat) { std::lock_guard lk(mutex_); sampleRate_ = rate; sampleFormat_ = sampleFormat; if (!telephoneTone_) telephoneTone_.reset(new TelephoneTone(prefs_.getZoneToneChoice(), rate, sampleFormat)); else telephoneTone_->setSampleRate(rate, sampleFormat); if (!audioFile_) { return; } auto path = audioFile_->getFilePath(); try { audioFile_.reset(new AudioFile(path, sampleRate_, sampleFormat)); } catch (const AudioFileException& e) { JAMI_WARN("Audio file error: %s", e.what()); } } std::shared_ptr<AudioLoop> ToneControl::getTelephoneTone() { std::lock_guard lk(mutex_); if (telephoneTone_) return telephoneTone_->getCurrentTone(); return nullptr; } std::shared_ptr<AudioLoop> ToneControl::getTelephoneFile(void) { std::lock_guard lk(mutex_); return audioFile_; } bool ToneControl::setAudioFile(const std::string& file) { std::lock_guard lk(mutex_); if (audioFile_) { emitSignal<libjami::CallSignal::RecordPlaybackStopped>(audioFile_->getFilePath()); audioFile_.reset(); } try { audioFile_.reset(new AudioFile(file, sampleRate_, sampleFormat_)); } catch (const AudioFileException& e) { JAMI_WARN("Audio file error: %s", e.what()); } return static_cast<bool>(audioFile_); } void ToneControl::stopAudioFile() { std::lock_guard lk(mutex_); if (audioFile_) { emitSignal<libjami::CallSignal::RecordPlaybackStopped>(audioFile_->getFilePath()); audioFile_.reset(); } } void ToneControl::stop() { std::lock_guard lk(mutex_); if (telephoneTone_) telephoneTone_->setCurrentTone(Tone::ToneId::TONE_NULL); if (audioFile_) { emitSignal<libjami::CallSignal::RecordPlaybackStopped>(audioFile_->getFilePath()); audioFile_.reset(); } } void ToneControl::play(Tone::ToneId toneId) { std::lock_guard lk(mutex_); if (telephoneTone_) telephoneTone_->setCurrentTone(toneId); } void ToneControl::seek(double value) { std::lock_guard lk(mutex_); if (audioFile_) audioFile_->seek(value); } } // namespace jami
3,390
C++
.cpp
114
25.947368
96
0.704888
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false