From eadf7abfe420bf04a28749a67c9dc2550f6c640d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miko=C5=82aj=20Ma=C5=82ecki?= Date: Fri, 18 Sep 2020 09:07:03 +0200 Subject: [PATCH 01/11] Added basic unit test for bonding groups --- srtcore/api.cpp | 3 + test/filelist.maf | 1 + test/test_bonding.cpp | 335 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 339 insertions(+) create mode 100644 test/test_bonding.cpp diff --git a/srtcore/api.cpp b/srtcore/api.cpp index dd226f9d0..06a87523e 100644 --- a/srtcore/api.cpp +++ b/srtcore/api.cpp @@ -1695,6 +1695,9 @@ int CUDTUnited::groupConnect(CUDTGroup* pg, SRT_SOCKGROUPCONFIG* targets, int ar if (retval == -1) throw CUDTException(MJ_CONNECTION, MN_CONNLOST, 0); + if (!block_new_opened) + return 0; + return retval; } diff --git a/test/filelist.maf b/test/filelist.maf index d136a3c87..808ab7ffd 100644 --- a/test/filelist.maf +++ b/test/filelist.maf @@ -1,6 +1,7 @@ SOURCES test_buffer.cpp +test_bonding.cpp test_connection_timeout.cpp test_many_connections.cpp test_cryspr.cpp diff --git a/test/test_bonding.cpp b/test/test_bonding.cpp new file mode 100644 index 000000000..12a5fb4b7 --- /dev/null +++ b/test/test_bonding.cpp @@ -0,0 +1,335 @@ + +#include +#include +#include +#include +#include +#include +#ifdef _WIN32 +#define usleep(x) Sleep(x / 1000) +#else +#include +#endif + +#include "gtest/gtest.h" + +#include "srt.h" +#include "netinet_any.h" + +TEST(Bonding, ConnectBlind) +{ + struct sockaddr_in sa; + + srt_startup(); + + const int ss = srt_create_group(SRT_GTYPE_BROADCAST); + ASSERT_NE(ss, SRT_ERROR); + + std::vector targets; + for (int i = 0; i < 2; ++i) + { + sa.sin_family = AF_INET; + sa.sin_port = htons(4200 + i); + ASSERT_EQ(inet_pton(AF_INET, "192.168.1.237", &sa.sin_addr), 1); + + const SRT_SOCKGROUPCONFIG gd = srt_prepare_endpoint(NULL, (struct sockaddr*)&sa, sizeof sa); + targets.push_back(gd); + } + + std::future closing_promise = std::async(std::launch::async, [](int ss) { + std::this_thread::sleep_for(std::chrono::seconds(2)); + std::cerr << "Closing group" << std::endl; + srt_close(ss); + }, ss); + + std::cout << "srt_connect_group calling " << std::endl; + const int st = srt_connect_group(ss, targets.data(), targets.size()); + std::cout << "srt_connect_group returned " << st << std::endl; + + closing_promise.wait(); + EXPECT_EQ(st, -1); + + // Delete config objects before prospective exception + for (auto& gd: targets) + srt_delete_config(gd.config); + + srt_cleanup(); +} + +SRTSOCKET g_listen_socket = -1; + +void listening_thread() +{ + + + //this_thread::sleep_for(seconds(7)); +} + +int g_nconnected = 0; +int g_nfailed = 0; + +void ConnectCallback(void* , SRTSOCKET sock, int error, const sockaddr* /*peer*/, int token) +{ + std::cout << "Connect callback. Socket: " << sock + << ", error: " << error + << ", token: " << token << '\n'; + + if (error == SRT_SUCCESS) + ++g_nconnected; + else + ++g_nfailed; +} + +TEST(Bonding, ConnectNonBlocking) +{ + using namespace std; + using namespace std::chrono; + + srt_startup(); + + g_listen_socket = srt_create_socket(); + sockaddr_in bind_sa; + memset(&bind_sa, 0, sizeof bind_sa); + bind_sa.sin_family = AF_INET; + ASSERT_EQ(inet_pton(AF_INET, "127.0.0.1", &bind_sa.sin_addr), 1); + bind_sa.sin_port = htons(4200); + + ASSERT_NE(srt_bind(g_listen_socket, (sockaddr*)&bind_sa, sizeof bind_sa), -1); + const int yes = 1; + srt_setsockflag(g_listen_socket, SRTO_GROUPCONNECT, &yes, sizeof yes); + ASSERT_NE(srt_listen(g_listen_socket, 5), -1); + + int lsn_eid = srt_epoll_create(); + int lsn_events = SRT_EPOLL_IN | SRT_EPOLL_ERR | SRT_EPOLL_UPDATE; + srt_epoll_add_usock(lsn_eid, g_listen_socket, &lsn_events); + + // Caller part + + const int ss = srt_create_group(SRT_GTYPE_BROADCAST); + ASSERT_NE(ss, SRT_ERROR); + std::cout << "Created group socket: " << ss << '\n'; + + int no = 0; + ASSERT_NE(srt_setsockopt(ss, 0, SRTO_RCVSYN, &no, sizeof no), SRT_ERROR); // non-blocking mode + ASSERT_NE(srt_setsockopt(ss, 0, SRTO_SNDSYN, &no, sizeof no), SRT_ERROR); // non-blocking mode + + const int poll_id = srt_epoll_create(); + // Will use this epoll to wait for srt_accept(...) + const int epoll_out = SRT_EPOLL_OUT | SRT_EPOLL_ERR; + ASSERT_NE(srt_epoll_add_usock(poll_id, ss, &epoll_out), SRT_ERROR); + + srt_connect_callback(ss, &ConnectCallback, this); + + sockaddr_in sa; + sa.sin_family = AF_INET; + sa.sin_port = htons(4200); + ASSERT_EQ(inet_pton(AF_INET, "127.0.0.1", &sa.sin_addr), 1); + + auto acthr = std::thread([&lsn_eid]() { + SRT_EPOLL_EVENT ev[3]; + + cout << "[A] Waiting for accept\n"; + + // This can wait in infinity; worst case it will be killed in process. + int uwait_res = srt_epoll_uwait(lsn_eid, ev, 3, -1); + ASSERT_EQ(uwait_res, 1); + ASSERT_EQ(ev[0].fd, g_listen_socket); + ASSERT_EQ(ev[0].events, SRT_EPOLL_IN); + + sockaddr_any adr; + int accept_id = srt_accept(g_listen_socket, adr.get(), &adr.len); + + // Expected: group reporting + EXPECT_NE(accept_id & SRTGROUP_MASK, 0); + + cout << "[A] Waiting for update\n"; + // Now another waiting is required and expected the update event + uwait_res = srt_epoll_uwait(lsn_eid, ev, 3, -1); + ASSERT_EQ(uwait_res, 1); + ASSERT_EQ(ev[0].fd, g_listen_socket); + ASSERT_EQ(ev[0].events, SRT_EPOLL_UPDATE); + + cout << "[A] Waitig for close (up to 5s)\n"; + // Wait up to 5s for an error + srt_epoll_uwait(lsn_eid, ev, 3, 5000); + + srt_close(accept_id); + cout << "[A] thread finished\n"; + }); + + cout << "Connecting two sockets\n"; + + SRT_SOCKGROUPCONFIG cc[2]; + cc[0] = srt_prepare_endpoint(NULL, (sockaddr*)&sa, sizeof sa); + cc[1] = srt_prepare_endpoint(NULL, (sockaddr*)&sa, sizeof sa); + + ASSERT_NE(srt_epoll_add_usock(poll_id, ss, &epoll_out), SRT_ERROR); + + int result = srt_connect_group(ss, cc, 2); + ASSERT_EQ(result, 0); + + // Wait up to 2s + SRT_EPOLL_EVENT ev[3]; + const int uwait_result = srt_epoll_uwait(poll_id, ev, 3, 2000); + std::cout << "Returned from connecting two sockets " << std::endl; + + ASSERT_EQ(uwait_result, 1); // Expect the group reported + EXPECT_EQ(ev[0].fd, ss); + + // One second to make sure that both links are connected. + this_thread::sleep_for(seconds(1)); + + EXPECT_EQ(srt_close(ss), 0); + acthr.join(); + + srt_cleanup(); +} + + +TEST(Bonding, BackupPriorityBegin) +{ + using namespace std; + using namespace std::chrono; + + g_nconnected = 0; + g_nfailed = 0; + + srt_startup(); + + g_listen_socket = srt_create_socket(); + sockaddr_in bind_sa; + memset(&bind_sa, 0, sizeof bind_sa); + bind_sa.sin_family = AF_INET; + ASSERT_EQ(inet_pton(AF_INET, "127.0.0.1", &bind_sa.sin_addr), 1); + bind_sa.sin_port = htons(4200); + + ASSERT_NE(srt_bind(g_listen_socket, (sockaddr*)&bind_sa, sizeof bind_sa), -1); + const int yes = 1; + srt_setsockflag(g_listen_socket, SRTO_GROUPCONNECT, &yes, sizeof yes); + ASSERT_NE(srt_listen(g_listen_socket, 5), -1); + + int lsn_eid = srt_epoll_create(); + int lsn_events = SRT_EPOLL_IN | SRT_EPOLL_ERR | SRT_EPOLL_UPDATE; + srt_epoll_add_usock(lsn_eid, g_listen_socket, &lsn_events); + + // Caller part + + const int ss = srt_create_group(SRT_GTYPE_BACKUP); + ASSERT_NE(ss, SRT_ERROR); + + srt_connect_callback(ss, &ConnectCallback, this); + + sockaddr_in sa; + sa.sin_family = AF_INET; + sa.sin_port = htons(4200); + ASSERT_EQ(inet_pton(AF_INET, "127.0.0.1", &sa.sin_addr), 1); + + auto acthr = std::thread([&lsn_eid]() { + sockaddr_any adr; + cout << "[A] Accepting a connection...\n"; + int accept_id = srt_accept(g_listen_socket, adr.get(), &adr.len); + + // Expected: group reporting + EXPECT_NE(accept_id & SRTGROUP_MASK, 0); + + SRT_SOCKGROUPDATA gdata[2]; + SRT_MSGCTRL mc = srt_msgctrl_default; + mc.grpdata = gdata; + mc.grpdata_size = 2; + long long data[1320/8]; + + cout << "[A] Receiving...\n"; + int ds = srt_recvmsg2(accept_id, (char*)data, sizeof data, (&mc)); + ASSERT_EQ(ds, 8); + + cout << "[A] Closing\n"; + srt_close(accept_id); + cout << "[A] thread finished\n"; + }); + + cout << "Connecting two sockets\n"; + + SRT_SOCKGROUPCONFIG cc[2]; + cc[0] = srt_prepare_endpoint(NULL, (sockaddr*)&sa, sizeof sa); + cc[0].token = 0; + cc[1] = srt_prepare_endpoint(NULL, (sockaddr*)&sa, sizeof sa); + cc[1].token = 1; + cc[1].weight = 1; // higher than the default 0 + + int result = srt_connect_group(ss, cc, 2); + ASSERT_EQ(result, 0); + + // Make sure both links are connected + SRT_SOCKGROUPDATA gdata[2]; + size_t psize = 2; + size_t nwait = 10; + cout << "Waiting for getting 2 links:\n"; + while (--nwait) + { + srt_group_data(ss, gdata, &psize); + if (psize == 2) + { + int l1, l2; + l1 = gdata[0].memberstate; + l2 = gdata[1].memberstate; + + if (l1 > SRT_GST_PENDING && l2 > SRT_GST_PENDING) + { + cout << "Both up: [0]=" << l1 << " [1]=" << l2 << "\n"; + break; + } + else + { + cout << "Still link states [0]=" << l1 << " [1]=" << l2 << "\n"; + } + } + else + { + cout << "Still " << psize << endl; + } + this_thread::sleep_for(milliseconds(500)); + } + ASSERT_NE(nwait, 0); + + // Now send one packet + long long data = 0x1234123412341234; + + SRT_MSGCTRL mc = srt_msgctrl_default; + mc.grpdata = gdata; + mc.grpdata_size = 2; + + // This call should retrieve the group information + // AFTER the transition has happened + int sendret = srt_sendmsg2(ss, (char*)&data, sizeof data, (&mc)); + EXPECT_EQ(sendret, sizeof data); + + // So, let's check which link is in RUNNING state + // TOKEN value is the index in cc array, and we should + // also have the weight value there. + + SRT_SOCKGROUPDATA* mane, * backup; + if (gdata[0].weight == 0) + { + backup = &gdata[0]; + mane = &gdata[1]; + } + else + { + mane = &gdata[0]; + backup = &gdata[1]; + } + + cout << "MAIN:[" << mane->token << "] weight=" << mane->weight << endl; + cout << "BACKUP:[" << backup->token << "] weight=" << backup->weight << endl; + + // Ok, now mane link should be active, backup idle + EXPECT_EQ(mane->memberstate, SRT_GST_RUNNING); + EXPECT_EQ(backup->memberstate, SRT_GST_IDLE); + + acthr.join(); + + srt_cleanup(); +} + + + From f7e9c7702a038f8b0826045bb117597859d8eb6c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miko=C5=82aj=20Ma=C5=82ecki?= Date: Fri, 18 Sep 2020 12:34:58 +0200 Subject: [PATCH 02/11] Added 2 tests and a description --- test/test_bonding.cpp | 535 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 521 insertions(+), 14 deletions(-) diff --git a/test/test_bonding.cpp b/test/test_bonding.cpp index 12a5fb4b7..99d8c5fc4 100644 --- a/test/test_bonding.cpp +++ b/test/test_bonding.cpp @@ -16,6 +16,17 @@ #include "srt.h" #include "netinet_any.h" +// General idea: +// This should try to connect to two nonexistent links, +// the connecting function (working in blocking mode) +// should exit with error, after the group has been closed +// in a separate thread. +// +// Steps: +// 1. Create group +// 2. Use a nonexistent endpoints 192.168.1.237:4200 and *:4201 +// 3. Close the group in a thread +// 4. Wait for error TEST(Bonding, ConnectBlind) { struct sockaddr_in sa; @@ -57,17 +68,11 @@ TEST(Bonding, ConnectBlind) } SRTSOCKET g_listen_socket = -1; - -void listening_thread() -{ - - - //this_thread::sleep_for(seconds(7)); -} - int g_nconnected = 0; int g_nfailed = 0; +// This ConnectCallback is mainly informative, but it also collects the +// number of succeeded and failed links. void ConnectCallback(void* , SRTSOCKET sock, int error, const sockaddr* /*peer*/, int token) { std::cout << "Connect callback. Socket: " << sock @@ -80,6 +85,26 @@ void ConnectCallback(void* , SRTSOCKET sock, int error, const sockaddr* /*peer*/ ++g_nfailed; } +// TEST IDEA: +// This uses srt_connect_group in non-blocking mode. The listener +// is also created to respond to the connection. Expected is to +// continue the connecting in background and report a success, +// and report the epoll IN on listener for the first connection, +// and UPDATE For the second one. +// +// TEST STEPS: +// 1. Create a listener socket and a group. +// 2. Set the group and the listener socket non-blocking mode +// 3. Start the accepting thread +// - wait for IN event ready on the listener socket +// - accept a connection +// - wait for UPDATE event ready on the listener socket +// - wait for any event up to 5s (possibly ERR) +// - close the listener socket +// 4. Prepare two connections and start connecting +// 5. Wait for the OUT readiness event on the group +// 6. Close the group. +// 7. Join the thread TEST(Bonding, ConnectNonBlocking) { using namespace std; @@ -185,7 +210,26 @@ TEST(Bonding, ConnectNonBlocking) srt_cleanup(); } - +// TEST IDEA: +// In this test there is created a working listener socket to +// accept the connection, and we use a Backup-type group with +// two links, but different weights. We connect them both and +// make sure that both are ready for use. Then we send a packet +// over the group and see, which link got activated and which +// remained idle. Expected is to have the link with higher +// priority (greater weight) to be activated. +// +// TEST STEPS: +// 1. Create a listener socket and a group. +// 3. Start the accepting thread +// - accept a connection +// - read one packet from the accepted entity +// - close the listener socket +// 4. Prepare two connections (one with weight=1) and connect the group +// 5. Wait for having all links connected +// 6. Send one packet and check which link was activated +// 6. Close the group. +// 7. Join the thread TEST(Bonding, BackupPriorityBegin) { using namespace std; @@ -208,10 +252,6 @@ TEST(Bonding, BackupPriorityBegin) srt_setsockflag(g_listen_socket, SRTO_GROUPCONNECT, &yes, sizeof yes); ASSERT_NE(srt_listen(g_listen_socket, 5), -1); - int lsn_eid = srt_epoll_create(); - int lsn_events = SRT_EPOLL_IN | SRT_EPOLL_ERR | SRT_EPOLL_UPDATE; - srt_epoll_add_usock(lsn_eid, g_listen_socket, &lsn_events); - // Caller part const int ss = srt_create_group(SRT_GTYPE_BACKUP); @@ -224,7 +264,7 @@ TEST(Bonding, BackupPriorityBegin) sa.sin_port = htons(4200); ASSERT_EQ(inet_pton(AF_INET, "127.0.0.1", &sa.sin_addr), 1); - auto acthr = std::thread([&lsn_eid]() { + auto acthr = std::thread([]() { sockaddr_any adr; cout << "[A] Accepting a connection...\n"; int accept_id = srt_accept(g_listen_socket, adr.get(), &adr.len); @@ -332,4 +372,471 @@ TEST(Bonding, BackupPriorityBegin) } +// TEST IDEA: +// In this test there is created a working listener socket to +// accept the connection, and we use a Backup-type group with +// two links, but different weights. We connect the first link +// with less weight and send one packet to make sure this only +// link was activated. Then we connect a second link with weight=1. +// Then we send the packet again and see if the new link was +// immediately activated. The first link should be silenced after +// time, but there's no possibility to check this in such a +// simple test. +// +// TEST STEPS: +// 1. Create a listener socket and a group. +// 3. Start the accepting thread +// - accept a connection +// - read one packet from the accepted entity +// - read the second packet from the accepted entity +// - close the listener socket +// 4. Prepare one connection with weight=0 and connect the group +// 5. Send a packet to enforce activation of one link +// 6. Prepare another connection with weight=1 and connect the group +// 7. Send a packet +// 8. Check member status - both links should be running. +// 9. Close the group. +// 10. Join the thread +TEST(Bonding, BackupPriorityTakeover) +{ + using namespace std; + using namespace std::chrono; + + g_nconnected = 0; + g_nfailed = 0; + + srt_startup(); + + g_listen_socket = srt_create_socket(); + sockaddr_in bind_sa; + memset(&bind_sa, 0, sizeof bind_sa); + bind_sa.sin_family = AF_INET; + ASSERT_EQ(inet_pton(AF_INET, "127.0.0.1", &bind_sa.sin_addr), 1); + bind_sa.sin_port = htons(4200); + + ASSERT_NE(srt_bind(g_listen_socket, (sockaddr*)&bind_sa, sizeof bind_sa), -1); + const int yes = 1; + srt_setsockflag(g_listen_socket, SRTO_GROUPCONNECT, &yes, sizeof yes); + ASSERT_NE(srt_listen(g_listen_socket, 5), -1); + + // Caller part + + const int ss = srt_create_group(SRT_GTYPE_BACKUP); + ASSERT_NE(ss, SRT_ERROR); + + srt_connect_callback(ss, &ConnectCallback, this); + + sockaddr_in sa; + sa.sin_family = AF_INET; + sa.sin_port = htons(4200); + ASSERT_EQ(inet_pton(AF_INET, "127.0.0.1", &sa.sin_addr), 1); + + auto acthr = std::thread([]() { + sockaddr_any adr; + cout << "[A] Accepting a connection...\n"; + int accept_id = srt_accept(g_listen_socket, adr.get(), &adr.len); + + // Expected: group reporting + EXPECT_NE(accept_id & SRTGROUP_MASK, 0); + + SRT_SOCKGROUPDATA gdata[2]; + SRT_MSGCTRL mc = srt_msgctrl_default; + mc.grpdata = gdata; + mc.grpdata_size = 2; + long long data[1320/8]; + + cout << "[A] Receiving 1...\n"; + int ds = srt_recvmsg2(accept_id, (char*)data, sizeof data, (&mc)); + ASSERT_EQ(ds, 8); + + cout << "[A] Receiving 2...\n"; + ds = srt_recvmsg2(accept_id, (char*)data, sizeof data, (&mc)); + ASSERT_EQ(ds, 8); + + // To make it possible that the state is checked before it is closed. + this_thread::sleep_for(seconds(1)); + + cout << "[A] Closing\n"; + srt_close(accept_id); + cout << "[A] thread finished\n"; + }); + + cout << "Connecting first link weight=0:\n"; + + SRT_SOCKGROUPCONFIG cc[2]; + cc[0] = srt_prepare_endpoint(NULL, (sockaddr*)&sa, sizeof sa); + cc[0].token = 0; + + int result = srt_connect_group(ss, cc, 1); + ASSERT_EQ(result, 0); + + // As we have one link, after `srt_connect_group` returns, we have + // this link now connected. Send one data portion. + + SRT_SOCKGROUPDATA gdata[2]; + + long long data = 0x1234123412341234; + SRT_MSGCTRL mc = srt_msgctrl_default; + mc.grpdata = gdata; + mc.grpdata_size = 2; + + cout << "Sending (1)\n"; + // This call should retrieve the group information + // AFTER the transition has happened + int sendret = srt_sendmsg2(ss, (char*)&data, sizeof data, (&mc)); + EXPECT_EQ(sendret, sizeof data); + ASSERT_EQ(mc.grpdata_size, 1); + EXPECT_EQ(gdata[0].memberstate, SRT_GST_RUNNING); + + cout << "Connecting second link weight=1:\n"; + // Now prepare the second connection + cc[0].token = 1; + cc[0].weight = 1; // higher than the default 0 + result = srt_connect_group(ss, cc, 1); + ASSERT_EQ(result, 0); + + // Make sure both links are connected + size_t psize = 2; + size_t nwait = 10; + cout << "Waiting for getting 2 links:\n"; + while (--nwait) + { + srt_group_data(ss, gdata, &psize); + if (psize == 2) + { + int l1, l2; + l1 = gdata[0].memberstate; + l2 = gdata[1].memberstate; + + if (l1 > SRT_GST_PENDING && l2 > SRT_GST_PENDING) + { + cout << "Both up: [0]=" << l1 << " [1]=" << l2 << "\n"; + break; + } + else + { + cout << "Still link states [0]=" << l1 << " [1]=" << l2 << "\n"; + } + } + else + { + cout << "Still " << psize << endl; + } + this_thread::sleep_for(milliseconds(500)); + } + ASSERT_NE(nwait, 0); + + // Now send one packet (again) + mc = srt_msgctrl_default; + mc.grpdata = gdata; + mc.grpdata_size = 2; + + cout << "Sending (2)\n"; + // This call should retrieve the group information + // AFTER the transition has happened + sendret = srt_sendmsg2(ss, (char*)&data, sizeof data, (&mc)); + EXPECT_EQ(sendret, sizeof data); + + // So, let's check which link is in RUNNING state + // TOKEN value is the index in cc array, and we should + // also have the weight value there. + + SRT_SOCKGROUPDATA* mane, * backup; + if (gdata[0].weight == 0) + { + backup = &gdata[0]; + mane = &gdata[1]; + } + else + { + mane = &gdata[0]; + backup = &gdata[1]; + } + + cout << "MAIN:[" << mane->token << "] weight=" << mane->weight << endl; + cout << "BACKUP:[" << backup->token << "] weight=" << backup->weight << endl; + + // Ok, now both links should be running (this state lasts + // for the "temporary activation" period. + EXPECT_EQ(mane->memberstate, SRT_GST_RUNNING); + EXPECT_EQ(backup->memberstate, SRT_GST_RUNNING); + + acthr.join(); + + srt_cleanup(); +} + + +// TEST IDEA: +// In this test there is created a working listener socket to +// accept the connection, and we use a Backup-type group with +// two links, but different weights. We connect then two links +// both with weight=1. Then we send a packet to make sure that +// exactly one of them got activated. Then we connect another +// link with weight=0. Then we send a packet again, which should +// not change the link usage. Then we check which link was +// active so far, and we close the socket for that link to make +// it broken, then we wait for having only two links connected. +// Then a packet is sent to activate a link. We expect the link +// with higher weight is activated. +// +// TEST STEPS: +// 1. Create a listener socket and a group. +// 3. Start the accepting thread +// - accept a connection +// - read one packet from the accepted entity +// - read the second packet from the accepted entity +// - read the third packet from the accepted entity +// - close the listener socket +// 4. Prepare two connections with weight=1 and connect the group +// 5. Send a packet to enforce activation of one link +// 6. Prepare another connection with weight=0 and connect the group +// 7. Wait for having all 3 links connected. +// 8. Send a packet +// 9. Find which link is currently active and close it +// 10. Wait for having only two links. +// 11. Send a packet. +// 12. Find one link active and one idle +// 13. Check if the link with weight=1 is active and the one with weight=0 is idle. +// 14. Close the group. +// 15. Join the thread +TEST(Bonding, BackupPrioritySelection) +{ + using namespace std; + using namespace std::chrono; + + g_nconnected = 0; + g_nfailed = 0; + + srt_startup(); + + g_listen_socket = srt_create_socket(); + sockaddr_in bind_sa; + memset(&bind_sa, 0, sizeof bind_sa); + bind_sa.sin_family = AF_INET; + ASSERT_EQ(inet_pton(AF_INET, "127.0.0.1", &bind_sa.sin_addr), 1); + bind_sa.sin_port = htons(4200); + + ASSERT_NE(srt_bind(g_listen_socket, (sockaddr*)&bind_sa, sizeof bind_sa), -1); + const int yes = 1; + srt_setsockflag(g_listen_socket, SRTO_GROUPCONNECT, &yes, sizeof yes); + ASSERT_NE(srt_listen(g_listen_socket, 5), -1); + + // Caller part + const int ss = srt_create_group(SRT_GTYPE_BACKUP); + ASSERT_NE(ss, SRT_ERROR); + + srt_connect_callback(ss, &ConnectCallback, this); + + sockaddr_in sa; + sa.sin_family = AF_INET; + sa.sin_port = htons(4200); + ASSERT_EQ(inet_pton(AF_INET, "127.0.0.1", &sa.sin_addr), 1); + + auto acthr = std::thread([]() { + sockaddr_any adr; + cout << "[A] Accepting a connection...\n"; + int accept_id = srt_accept(g_listen_socket, adr.get(), &adr.len); + + // Expected: group reporting + EXPECT_NE(accept_id & SRTGROUP_MASK, 0); + + SRT_SOCKGROUPDATA gdata[2]; + SRT_MSGCTRL mc = srt_msgctrl_default; + mc.grpdata = gdata; + mc.grpdata_size = 2; + long long data[1320/8]; + + cout << "[A] Receiving 1...\n"; + int ds = srt_recvmsg2(accept_id, (char*)data, sizeof data, (&mc)); + ASSERT_EQ(ds, 8); + + cout << "[A] Receiving 2...\n"; + ds = srt_recvmsg2(accept_id, (char*)data, sizeof data, (&mc)); + ASSERT_EQ(ds, 8); + + cout << "[A] Receiving 3...\n"; + ds = srt_recvmsg2(accept_id, (char*)data, sizeof data, (&mc)); + ASSERT_EQ(ds, 8); + + // To make it possible that the state is checked before it is closed. + this_thread::sleep_for(seconds(1)); + + cout << "[A] Closing\n"; + srt_close(accept_id); + cout << "[A] thread finished\n"; + }); + + cout << "Connecting first 2 links weight=1:\n"; + + SRT_SOCKGROUPCONFIG cc[2]; + cc[0] = srt_prepare_endpoint(NULL, (sockaddr*)&sa, sizeof sa); + cc[0].token = 0; + cc[0].weight = 1; + cc[1] = srt_prepare_endpoint(NULL, (sockaddr*)&sa, sizeof sa); + cc[1].token = 1; + cc[1].weight = 1; + + int result = srt_connect_group(ss, cc, 2); + ASSERT_EQ(result, 0); + + // As we have one link, after `srt_connect_group` returns, we have + // this link now connected. Send one data portion. + + SRT_SOCKGROUPDATA gdata[3]; + + long long data = 0x1234123412341234; + SRT_MSGCTRL mc = srt_msgctrl_default; + mc.grpdata = gdata; + mc.grpdata_size = 3; + + // We can send now. We know that we have at least one + // link connected and it already has the same priority + // as the other. + + cout << "Sending (1)\n"; + // This call should retrieve the group information + // AFTER the transition has happened + int sendret = srt_sendmsg2(ss, (char*)&data, sizeof data, (&mc)); + EXPECT_EQ(sendret, sizeof data); + ASSERT_EQ(mc.grpdata_size, 2); + EXPECT_EQ(gdata[0].memberstate, SRT_GST_RUNNING); + + cout << "Connecting third link weight=0:\n"; + // Now prepare the second connection + cc[0].token = 2; + cc[0].weight = 0; // higher than the default 0 + result = srt_connect_group(ss, cc, 1); + ASSERT_EQ(result, 0); + + // Make sure all 3 links are connected + size_t psize = 3; + size_t nwait = 10; + set states; + + cout << "Waiting for getting 3 links:\n"; + while (--nwait) + { + srt_group_data(ss, gdata, &psize); + if (psize == 3) + { + states.clear(); + for (int i = 0; i < 3; ++i) + states.insert(gdata[i].memberstate); + + if (states.count(SRT_GST_PENDING)) + { + cout << "Still not all links...\n"; + } + else + { + cout << "All links up\n"; + break; + } + } + else + { + cout << "Still " << psize << endl; + } + this_thread::sleep_for(milliseconds(500)); + } + ASSERT_NE(nwait, 0); + + // Now send one packet (again) + mc = srt_msgctrl_default; + mc.grpdata = gdata; + mc.grpdata_size = 2; + + cout << "Sending (2)\n"; + // This call should retrieve the group information + // AFTER the transition has happened + sendret = srt_sendmsg2(ss, (char*)&data, sizeof data, (&mc)); + EXPECT_EQ(sendret, sizeof data); + ASSERT_EQ(mc.grpdata_size, 3); + + // So, let's check which link is in RUNNING state + // TOKEN value is the index in cc array, and we should + // also have the weight value there. + + SRT_SOCKGROUPDATA* mane = nullptr; + + for (size_t i = 0; i < mc.grpdata_size; ++i) + { + if (gdata[i].memberstate == SRT_GST_RUNNING) + { + mane = &gdata[i]; + break; + } + } + + ASSERT_NE(mane, nullptr); + ASSERT_EQ(mane->weight, 1); + + cout << "Found activated link: [" << mane->token << "] - closing...\n"; + + ASSERT_NE(srt_close(mane->id), -1); + + // Now expect to have only 2 links, wait for it if needed. + psize = 2; + nwait = 10; + + cout << "Waiting for ONLY 2 links:\n"; + while (--nwait) + { + srt_group_data(ss, gdata, &psize); + if (psize == 2) + { + break; + } + else + { + cout << "Still " << psize << endl; + } + this_thread::sleep_for(milliseconds(500)); + } + ASSERT_NE(nwait, 0); + + // Now send one packet (again) + mc = srt_msgctrl_default; + mc.grpdata = gdata; + mc.grpdata_size = 2; + + cout << "Sending (3)\n"; + // This call should retrieve the group information + // AFTER the transition has happened + sendret = srt_sendmsg2(ss, (char*)&data, sizeof data, (&mc)); + EXPECT_EQ(sendret, sizeof data); + + mane = nullptr; + SRT_SOCKGROUPDATA* backup = nullptr; + for (size_t i = 0; i < mc.grpdata_size; ++i) + { + if (gdata[i].memberstate == SRT_GST_RUNNING) + { + mane = &gdata[i]; + } + else + { + backup = &gdata[i]; + } + } + + ASSERT_NE(mane, nullptr); + ASSERT_NE(backup, nullptr); + ASSERT_EQ(mane->weight, 1); + ASSERT_EQ(backup->weight, 0); + + cout << "MAIN (expected active):[" << mane->token << "] weight=" << mane->weight << endl; + cout << "BACKUP (expected idle):[" << backup->token << "] weight=" << backup->weight << endl; + + // Ok, now both links should be running (this state lasts + // for the "temporary activation" period. + EXPECT_EQ(mane->memberstate, SRT_GST_RUNNING); + EXPECT_EQ(backup->memberstate, SRT_GST_IDLE); + + acthr.join(); + + srt_cleanup(); +} + From 910cf70b01f04d0d9e8038b6429f2f0050b6b0d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miko=C5=82aj=20Ma=C5=82ecki?= Date: Fri, 18 Sep 2020 16:56:51 +0200 Subject: [PATCH 03/11] Fixed: one uwait call may report both IN and UPDATE --- test/test_bonding.cpp | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/test/test_bonding.cpp b/test/test_bonding.cpp index 99d8c5fc4..54e0a5761 100644 --- a/test/test_bonding.cpp +++ b/test/test_bonding.cpp @@ -159,7 +159,10 @@ TEST(Bonding, ConnectNonBlocking) int uwait_res = srt_epoll_uwait(lsn_eid, ev, 3, -1); ASSERT_EQ(uwait_res, 1); ASSERT_EQ(ev[0].fd, g_listen_socket); - ASSERT_EQ(ev[0].events, SRT_EPOLL_IN); + + // Check if the IN event is set, even if it's not the only event + ASSERT_EQ(ev[0].events & SRT_EPOLL_IN, SRT_EPOLL_IN); + bool have_also_update = ev[0].events & SRT_EPOLL_UPDATE; sockaddr_any adr; int accept_id = srt_accept(g_listen_socket, adr.get(), &adr.len); @@ -167,12 +170,19 @@ TEST(Bonding, ConnectNonBlocking) // Expected: group reporting EXPECT_NE(accept_id & SRTGROUP_MASK, 0); - cout << "[A] Waiting for update\n"; - // Now another waiting is required and expected the update event - uwait_res = srt_epoll_uwait(lsn_eid, ev, 3, -1); - ASSERT_EQ(uwait_res, 1); - ASSERT_EQ(ev[0].fd, g_listen_socket); - ASSERT_EQ(ev[0].events, SRT_EPOLL_UPDATE); + if (have_also_update) + { + cout << "[A] NOT waiting for update - already reported previously\n"; + } + else + { + cout << "[A] Waiting for update\n"; + // Now another waiting is required and expected the update event + uwait_res = srt_epoll_uwait(lsn_eid, ev, 3, -1); + ASSERT_EQ(uwait_res, 1); + ASSERT_EQ(ev[0].fd, g_listen_socket); + ASSERT_EQ(ev[0].events, SRT_EPOLL_UPDATE); + } cout << "[A] Waitig for close (up to 5s)\n"; // Wait up to 5s for an error From 0645bb71b26cda9d3171ef25a3f0a3c994e56903 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miko=C5=82aj=20Ma=C5=82ecki?= Date: Fri, 18 Sep 2020 17:43:21 +0200 Subject: [PATCH 04/11] BackupPrioritySelection: allow any link to be activated first --- test/test_bonding.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/test/test_bonding.cpp b/test/test_bonding.cpp index 54e0a5761..ab3945118 100644 --- a/test/test_bonding.cpp +++ b/test/test_bonding.cpp @@ -710,7 +710,12 @@ TEST(Bonding, BackupPrioritySelection) int sendret = srt_sendmsg2(ss, (char*)&data, sizeof data, (&mc)); EXPECT_EQ(sendret, sizeof data); ASSERT_EQ(mc.grpdata_size, 2); - EXPECT_EQ(gdata[0].memberstate, SRT_GST_RUNNING); + + int state0 = gdata[0].memberstate; + int state1 = gdata[1].memberstate; + + cout << "States: [0]=" << state0 << " [1]=" << state1 << endl; + EXPECT_TRUE(state0 == SRT_GST_RUNNING || state1 == SRT_GST_RUNNING); cout << "Connecting third link weight=0:\n"; // Now prepare the second connection From b53a64b612df02b2de2e3e37b1c7cfe1fa3cf599 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miko=C5=82aj=20Ma=C5=82ecki?= Date: Fri, 18 Sep 2020 19:59:55 +0200 Subject: [PATCH 05/11] Added more trace for the failing Travis test --- test/test_bonding.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/test/test_bonding.cpp b/test/test_bonding.cpp index ab3945118..0e4f8232f 100644 --- a/test/test_bonding.cpp +++ b/test/test_bonding.cpp @@ -849,6 +849,10 @@ TEST(Bonding, BackupPrioritySelection) EXPECT_EQ(mane->memberstate, SRT_GST_RUNNING); EXPECT_EQ(backup->memberstate, SRT_GST_IDLE); + this_thread::sleep_for(seconds(1)); + + cout << "Closing receiver thread [A]\n"; + acthr.join(); srt_cleanup(); From a7a6316bb6658ae2415a74a2d332b0cb6d4cefe5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miko=C5=82aj=20Ma=C5=82ecki?= Date: Wed, 21 Oct 2020 16:34:28 +0200 Subject: [PATCH 06/11] Some fixes. --- test/filelist.maf | 5 ++++- test/test_bonding.cpp | 11 ++++++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/test/filelist.maf b/test/filelist.maf index 808ab7ffd..1ea0ed84a 100644 --- a/test/filelist.maf +++ b/test/filelist.maf @@ -1,7 +1,6 @@ SOURCES test_buffer.cpp -test_bonding.cpp test_connection_timeout.cpp test_many_connections.cpp test_cryspr.cpp @@ -18,3 +17,7 @@ test_sync.cpp test_timer.cpp test_unitqueue.cpp test_utilities.cpp + +SOURCES - ENABLE_EXPERIMENTAL_BONDING +test_bonding.cpp + diff --git a/test/test_bonding.cpp b/test/test_bonding.cpp index 0e4f8232f..1c6beab3e 100644 --- a/test/test_bonding.cpp +++ b/test/test_bonding.cpp @@ -617,6 +617,7 @@ TEST(Bonding, BackupPrioritySelection) g_nconnected = 0; g_nfailed = 0; + volatile bool recvd = false; srt_startup(); @@ -643,7 +644,7 @@ TEST(Bonding, BackupPrioritySelection) sa.sin_port = htons(4200); ASSERT_EQ(inet_pton(AF_INET, "127.0.0.1", &sa.sin_addr), 1); - auto acthr = std::thread([]() { + auto acthr = std::thread([&recvd]() { sockaddr_any adr; cout << "[A] Accepting a connection...\n"; int accept_id = srt_accept(g_listen_socket, adr.get(), &adr.len); @@ -664,6 +665,7 @@ TEST(Bonding, BackupPrioritySelection) cout << "[A] Receiving 2...\n"; ds = srt_recvmsg2(accept_id, (char*)data, sizeof data, (&mc)); ASSERT_EQ(ds, 8); + recvd = true; cout << "[A] Receiving 3...\n"; ds = srt_recvmsg2(accept_id, (char*)data, sizeof data, (&mc)); @@ -787,6 +789,13 @@ TEST(Bonding, BackupPrioritySelection) ASSERT_NE(mane, nullptr); ASSERT_EQ(mane->weight, 1); + // Spin-wait for making sure the reception succeeded before + // closing. This shouldn't be a problem in general, but + int ntry = 100; + while (!recvd && --ntry) + this_thread::sleep_for(milliseconds(200)); + ASSERT_NE(ntry, 0); + cout << "Found activated link: [" << mane->token << "] - closing...\n"; ASSERT_NE(srt_close(mane->id), -1); From 5834866aa5f9a86d8bc29f03b04b24e570bc5655 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miko=C5=82aj=20Ma=C5=82ecki?= Date: Mon, 7 Dec 2020 10:48:01 +0100 Subject: [PATCH 07/11] Added fixes for proper report blocking. Testing all group types in ConnectNonBlocking --- srtcore/group.cpp | 78 ++++++++++++++---- srtcore/group.h | 2 +- test/test_bonding.cpp | 183 ++++++++++++++++++++++-------------------- 3 files changed, 160 insertions(+), 103 deletions(-) diff --git a/srtcore/group.cpp b/srtcore/group.cpp index c10a5adf1..e7d50a7ec 100644 --- a/srtcore/group.cpp +++ b/srtcore/group.cpp @@ -1365,6 +1365,10 @@ int CUDTGroup::sendBroadcast(const char* buf, int len, SRT_MSGCTRL& w_mc) m_iLastSchedSeqNo = curseq; } + // } + + // { send_CheckBrokenSockets() + // Make an extra loop check to see if we could be // in a condition of "all sockets either blocked or pending" @@ -1384,10 +1388,6 @@ int CUDTGroup::sendBroadcast(const char* buf, int len, SRT_MSGCTRL& w_mc) } } - // } - - // { send_CheckBrokenSockets() - if (!pending.empty() || nblocked) { HLOGC(gslog.Debug, log << "grp/sendBroadcast: found pending sockets, polling them."); @@ -1462,7 +1462,6 @@ int CUDTGroup::sendBroadcast(const char* buf, int len, SRT_MSGCTRL& w_mc) // writable (connected) before this function had a chance // to check them. m_pGlobal->m_EPoll.clear_ready_usocks(*m_SndEpolld, SRT_EPOLL_CONNECT); - } } @@ -1598,7 +1597,6 @@ int CUDTGroup::sendBroadcast(const char* buf, int len, SRT_MSGCTRL& w_mc) int ercode = 0; - // XXX WITH BLOCKED CHECK ALSO PENDING!!! if (was_blocked) { m_pGlobal->m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_OUT, false); @@ -3372,7 +3370,7 @@ size_t CUDTGroup::sendBackup_CheckNeedActivate(const vector& idler } // [[using locked(this->m_GroupLock)]] -void CUDTGroup::send_CheckPendingSockets(const vector& pending, vector& w_wipeme) +bool CUDTGroup::send_CheckPendingSockets(const vector& pending, int nsuccessful, int nblocked, vector& w_wipeme) { // If we have at least one stable link, then select a link that have the // highest priority and silence the rest. @@ -3384,7 +3382,8 @@ void CUDTGroup::send_CheckPendingSockets(const vector& pending, vecto // we have one link that is stable and the freshly activated link is actually // stable too, we'll check this next time. // - if (!pending.empty()) + bool is_pending_blocked = false; + if (!pending.empty() || nblocked) { HLOGC(gslog.Debug, log << "grp/send*: found pending sockets, polling them."); @@ -3400,6 +3399,18 @@ void CUDTGroup::send_CheckPendingSockets(const vector& pending, vecto } else { + int swait_timeout = 0; + + // There's also a hidden condition here that is the upper if condition. + is_pending_blocked = (nsuccessful == 0); + + // If this is the case when + if (m_bSynSending && is_pending_blocked) + { + HLOGC(gslog.Debug, log << "grp/sendBroadcast: will block for " << m_iSndTimeOut << " - waiting for any writable in blocking mode"); + swait_timeout = m_iSndTimeOut; + } + // Some sockets could have been closed in the meantime. if (m_SndEpolld->watch_empty()) { @@ -3410,7 +3421,7 @@ void CUDTGroup::send_CheckPendingSockets(const vector& pending, vecto { InvertedLock ug(m_GroupLock); m_pGlobal->m_EPoll.swait( - *m_SndEpolld, sready, 0, false /*report by retval*/); // Just check if anything happened + *m_SndEpolld, sready, swait_timeout, false /*report by retval*/); // Just check if anything happened } if (m_bClosing) @@ -3432,6 +3443,9 @@ void CUDTGroup::send_CheckPendingSockets(const vector& pending, vecto int no_events = 0; m_pGlobal->m_EPoll.update_usock(m_SndEID, *i, &no_events); } + + if (CEPoll::isready(sready, *i, SRT_EPOLL_OUT)) + is_pending_blocked = false; } // After that, all sockets that have been reported @@ -3443,6 +3457,8 @@ void CUDTGroup::send_CheckPendingSockets(const vector& pending, vecto m_pGlobal->m_EPoll.clear_ready_usocks(*m_SndEpolld, SRT_EPOLL_OUT); } } + + return is_pending_blocked; } // [[using locked(this->m_GroupLock)]] @@ -3951,6 +3967,10 @@ int CUDTGroup::sendBackup(const char* buf, int len, SRT_MSGCTRL& w_mc) // and therefore need to be activated. set sendable_pri; + // Likely will need to survive unlock-lock cycle on the group, + // so keep this by IDs. + vector blocked; + // We believe that we need to send the payload over every sendable link anyway. for (vector::iterator snd = sendable.begin(); snd != sendable.end(); ++snd) { @@ -3992,6 +4012,9 @@ int CUDTGroup::sendBackup(const char* buf, int len, SRT_MSGCTRL& w_mc) if (is_unstable && is_zero(u.m_tsUnstableSince)) // Add to unstable only if it wasn't unstable already insert_uniq((unstable), d); + if (is_unstable) + blocked.push_back(d->id); + const Sendstate cstate = {d->id, d, stat, erc}; sendstates.push_back(cstate); d->sndresult = stat; @@ -4164,7 +4187,22 @@ int CUDTGroup::sendBackup(const char* buf, int len, SRT_MSGCTRL& w_mc) << " unstable=" << unstable.size()); } - send_CheckPendingSockets(pending, (wipeme)); + int nsuccess = 0; + int nblocked = 0; + for (vector::iterator is = sendstates.begin(); is != sendstates.end(); ++is) + { + if (is->stat == -1) + { + if (is->code == SRT_EASYNCSND) + ++nblocked; + } + else + { + nsuccess++; + } + } + + bool is_pending_blocked = send_CheckPendingSockets(pending, nsuccess, nblocked, (wipeme)); // Re-check after the waiting lock has been reacquired if (m_bClosing) @@ -4187,14 +4225,22 @@ int CUDTGroup::sendBackup(const char* buf, int len, SRT_MSGCTRL& w_mc) if (none_succeeded) { - HLOGC(gslog.Debug, log << "grp/sendBackup: all links broken (none succeeded to send a payload)"); m_pGlobal->m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_OUT, false); - m_pGlobal->m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_ERR, true); - // Reparse error code, if set. - // It might be set, if the last operation was failed. - // If any operation succeeded, this will not be executed anyway. + if (!m_bSynSending && (is_pending_blocked || nblocked)) + { + HLOGC(gslog.Debug, log << "grp/sendBackup: no links are ready for sending"); + throw CUDTException(MJ_AGAIN, MN_WRAVAIL); + } + else + { + HLOGC(gslog.Debug, log << "grp/sendBackup: all links broken (none succeeded to send a payload)"); + m_pGlobal->m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_ERR, true); + // Reparse error code, if set. + // It might be set, if the last operation was failed. + // If any operation succeeded, this will not be executed anyway. - throw CUDTException(MJ_CONNECTION, MN_CONNLOST, 0); + throw CUDTException(MJ_CONNECTION, MN_CONNLOST, 0); + } } // Now fill in the socket table. Check if the size is enough, if not, diff --git a/srtcore/group.h b/srtcore/group.h index 75d58eac6..2465d0cbb 100644 --- a/srtcore/group.h +++ b/srtcore/group.h @@ -260,7 +260,7 @@ class CUDTGroup std::vector& w_parallel, std::vector& w_wipeme, const std::string& activate_reason); - void send_CheckPendingSockets(const std::vector& pending, std::vector& w_wipeme); + bool send_CheckPendingSockets(const std::vector& pending, int nsuccessful, int nblocked, std::vector& w_wipeme); void send_CloseBrokenSockets(std::vector& w_wipeme); void sendBackup_CheckParallelLinks(const std::vector& unstable, std::vector& w_parallel, diff --git a/test/test_bonding.cpp b/test/test_bonding.cpp index 17e863f40..cdcd5b9da 100644 --- a/test/test_bonding.cpp +++ b/test/test_bonding.cpp @@ -123,117 +123,128 @@ TEST(Bonding, ConnectNonBlocking) srt_startup(); - g_listen_socket = srt_create_socket(); - sockaddr_in bind_sa; - memset(&bind_sa, 0, sizeof bind_sa); - bind_sa.sin_family = AF_INET; - ASSERT_EQ(inet_pton(AF_INET, ADDR.c_str(), &bind_sa.sin_addr), 1); - bind_sa.sin_port = htons(PORT); + // NOTE: Add more group types, if implemented! + vector types { SRT_GTYPE_BROADCAST, SRT_GTYPE_BACKUP }; - ASSERT_NE(srt_bind(g_listen_socket, (sockaddr*)&bind_sa, sizeof bind_sa), -1); - const int yes = 1; - srt_setsockflag(g_listen_socket, SRTO_GROUPCONNECT, &yes, sizeof yes); - ASSERT_NE(srt_listen(g_listen_socket, 5), -1); + for (const auto GTYPE: types) + { + g_listen_socket = srt_create_socket(); + sockaddr_in bind_sa; + memset(&bind_sa, 0, sizeof bind_sa); + bind_sa.sin_family = AF_INET; + ASSERT_EQ(inet_pton(AF_INET, ADDR.c_str(), &bind_sa.sin_addr), 1); + bind_sa.sin_port = htons(PORT); - int lsn_eid = srt_epoll_create(); - int lsn_events = SRT_EPOLL_IN | SRT_EPOLL_ERR | SRT_EPOLL_UPDATE; - srt_epoll_add_usock(lsn_eid, g_listen_socket, &lsn_events); + ASSERT_NE(srt_bind(g_listen_socket, (sockaddr*)&bind_sa, sizeof bind_sa), -1); + const int yes = 1; + srt_setsockflag(g_listen_socket, SRTO_GROUPCONNECT, &yes, sizeof yes); + ASSERT_NE(srt_listen(g_listen_socket, 5), -1); - // Caller part + int lsn_eid = srt_epoll_create(); + int lsn_events = SRT_EPOLL_IN | SRT_EPOLL_ERR | SRT_EPOLL_UPDATE; + srt_epoll_add_usock(lsn_eid, g_listen_socket, &lsn_events); - const int ss = srt_create_group(SRT_GTYPE_BROADCAST); - ASSERT_NE(ss, SRT_ERROR); - std::cout << "Created group socket: " << ss << '\n'; + // Caller part - int no = 0; - ASSERT_NE(srt_setsockopt(ss, 0, SRTO_RCVSYN, &no, sizeof no), SRT_ERROR); // non-blocking mode - ASSERT_NE(srt_setsockopt(ss, 0, SRTO_SNDSYN, &no, sizeof no), SRT_ERROR); // non-blocking mode + const int ss = srt_create_group(GTYPE); + ASSERT_NE(ss, SRT_ERROR); + std::cout << "Created group socket: " << ss << '\n'; - const int poll_id = srt_epoll_create(); - // Will use this epoll to wait for srt_accept(...) - const int epoll_out = SRT_EPOLL_OUT | SRT_EPOLL_ERR; - ASSERT_NE(srt_epoll_add_usock(poll_id, ss, &epoll_out), SRT_ERROR); + int no = 0; + ASSERT_NE(srt_setsockopt(ss, 0, SRTO_RCVSYN, &no, sizeof no), SRT_ERROR); // non-blocking mode + ASSERT_NE(srt_setsockopt(ss, 0, SRTO_SNDSYN, &no, sizeof no), SRT_ERROR); // non-blocking mode - srt_connect_callback(ss, &ConnectCallback, this); + const int poll_id = srt_epoll_create(); + // Will use this epoll to wait for srt_accept(...) + const int epoll_out = SRT_EPOLL_OUT | SRT_EPOLL_ERR; + ASSERT_NE(srt_epoll_add_usock(poll_id, ss, &epoll_out), SRT_ERROR); - sockaddr_in sa; - sa.sin_family = AF_INET; - sa.sin_port = htons(PORT); - ASSERT_EQ(inet_pton(AF_INET, "127.0.0.1", &sa.sin_addr), 1); + srt_connect_callback(ss, &ConnectCallback, this); - srt_setloglevel(LOG_DEBUG); + sockaddr_in sa; + sa.sin_family = AF_INET; + sa.sin_port = htons(PORT); + ASSERT_EQ(inet_pton(AF_INET, "127.0.0.1", &sa.sin_addr), 1); - auto acthr = std::thread([&lsn_eid]() { - SRT_EPOLL_EVENT ev[3]; + //srt_setloglevel(LOG_DEBUG); - cout << "[A] Waiting for accept\n"; + auto acthr = std::thread([&lsn_eid]() { + SRT_EPOLL_EVENT ev[3]; - // This can wait in infinity; worst case it will be killed in process. - int uwait_res = srt_epoll_uwait(lsn_eid, ev, 3, -1); - ASSERT_EQ(uwait_res, 1); - ASSERT_EQ(ev[0].fd, g_listen_socket); + cout << "[A] Waiting for accept\n"; - // Check if the IN event is set, even if it's not the only event - ASSERT_EQ(ev[0].events & SRT_EPOLL_IN, SRT_EPOLL_IN); - bool have_also_update = ev[0].events & SRT_EPOLL_UPDATE; + // This can wait in infinity; worst case it will be killed in process. + int uwait_res = srt_epoll_uwait(lsn_eid, ev, 3, -1); + ASSERT_EQ(uwait_res, 1); + ASSERT_EQ(ev[0].fd, g_listen_socket); - sockaddr_any adr; - int accept_id = srt_accept(g_listen_socket, adr.get(), &adr.len); + // Check if the IN event is set, even if it's not the only event + ASSERT_EQ(ev[0].events & SRT_EPOLL_IN, SRT_EPOLL_IN); + bool have_also_update = ev[0].events & SRT_EPOLL_UPDATE; - // Expected: group reporting - EXPECT_NE(accept_id & SRTGROUP_MASK, 0); + sockaddr_any adr; + int accept_id = srt_accept(g_listen_socket, adr.get(), &adr.len); - if (have_also_update) - { - cout << "[A] NOT waiting for update - already reported previously\n"; - } - else - { - cout << "[A] Waiting for update\n"; - // Now another waiting is required and expected the update event - uwait_res = srt_epoll_uwait(lsn_eid, ev, 3, -1); - ASSERT_EQ(uwait_res, 1); - ASSERT_EQ(ev[0].fd, g_listen_socket); - ASSERT_EQ(ev[0].events, SRT_EPOLL_UPDATE); - } + // Expected: group reporting + EXPECT_NE(accept_id & SRTGROUP_MASK, 0); - cout << "[A] Waitig for close (up to 5s)\n"; - // Wait up to 5s for an error - srt_epoll_uwait(lsn_eid, ev, 3, 5000); + if (have_also_update) + { + cout << "[A] NOT waiting for update - already reported previously\n"; + } + else + { + cout << "[A] Waiting for update\n"; + // Now another waiting is required and expected the update event + uwait_res = srt_epoll_uwait(lsn_eid, ev, 3, -1); + ASSERT_EQ(uwait_res, 1); + ASSERT_EQ(ev[0].fd, g_listen_socket); + ASSERT_EQ(ev[0].events, SRT_EPOLL_UPDATE); + } - srt_close(accept_id); - cout << "[A] thread finished\n"; - }); + cout << "[A] Waitig for close (up to 5s)\n"; + // Wait up to 5s for an error + srt_epoll_uwait(lsn_eid, ev, 3, 5000); - cout << "Connecting two sockets\n"; + srt_close(accept_id); + cout << "[A] thread finished\n"; + }); - SRT_SOCKGROUPCONFIG cc[2]; - cc[0] = srt_prepare_endpoint(NULL, (sockaddr*)&sa, sizeof sa); - cc[1] = srt_prepare_endpoint(NULL, (sockaddr*)&sa, sizeof sa); + cout << "Connecting two sockets\n"; - ASSERT_NE(srt_epoll_add_usock(poll_id, ss, &epoll_out), SRT_ERROR); + SRT_SOCKGROUPCONFIG cc[2]; + cc[0] = srt_prepare_endpoint(NULL, (sockaddr*)&sa, sizeof sa); + cc[1] = srt_prepare_endpoint(NULL, (sockaddr*)&sa, sizeof sa); - int result = srt_connect_group(ss, cc, 2); - ASSERT_EQ(result, 0); - char data[4] = { 1, 2, 3, 4}; - int wrong_send = srt_send(ss, data, sizeof data); - int errorcode = srt_getlasterror(NULL); - EXPECT_EQ(wrong_send, -1); - EXPECT_EQ(errorcode, SRT_EASYNCSND); + ASSERT_NE(srt_epoll_add_usock(poll_id, ss, &epoll_out), SRT_ERROR); - // Wait up to 2s - SRT_EPOLL_EVENT ev[3]; - const int uwait_result = srt_epoll_uwait(poll_id, ev, 3, 2000); - std::cout << "Returned from connecting two sockets " << std::endl; + int result = srt_connect_group(ss, cc, 2); + ASSERT_EQ(result, 0); + char data[4] = { 1, 2, 3, 4}; + int wrong_send = srt_send(ss, data, sizeof data); + int errorcode = srt_getlasterror(NULL); + EXPECT_EQ(wrong_send, -1); + EXPECT_EQ(errorcode, SRT_EASYNCSND); - ASSERT_EQ(uwait_result, 1); // Expect the group reported - EXPECT_EQ(ev[0].fd, ss); + // Wait up to 2s + SRT_EPOLL_EVENT ev[3]; + const int uwait_result = srt_epoll_uwait(poll_id, ev, 3, 2000); + std::cout << "Returned from connecting two sockets " << std::endl; - // One second to make sure that both links are connected. - this_thread::sleep_for(seconds(1)); + ASSERT_EQ(uwait_result, 1); // Expect the group reported + EXPECT_EQ(ev[0].fd, ss); - EXPECT_EQ(srt_close(ss), 0); - acthr.join(); + // One second to make sure that both links are connected. + this_thread::sleep_for(seconds(1)); + + EXPECT_EQ(srt_close(ss), 0); + acthr.join(); + + srt_epoll_release(lsn_eid); + srt_epoll_release(poll_id); + + srt_close(g_listen_socket); + } srt_cleanup(); } @@ -665,7 +676,7 @@ TEST(Bonding, BackupPrioritySelection) int stabtimeo = 1000; srt_setsockflag(ss, SRTO_GROUPSTABTIMEO, &stabtimeo, sizeof stabtimeo); - srt_setloglevel(LOG_DEBUG); + //srt_setloglevel(LOG_DEBUG); srt::resetlogfa( std::set { SRT_LOGFA_GRP_SEND, SRT_LOGFA_GRP_MGMT, From 4a95481eab58f0eab3d8d8649014fb54b5009b79 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miko=C5=82aj=20Ma=C5=82ecki?= Date: Mon, 7 Dec 2020 10:57:13 +0100 Subject: [PATCH 08/11] [core] Fixed proper reporting of sending blocked state. Fixed API value for connect-non-blocking --- srtcore/api.cpp | 3 + srtcore/group.cpp | 151 ++++++++++++++++++++++++++++++++++++++++------ srtcore/group.h | 2 +- 3 files changed, 136 insertions(+), 20 deletions(-) diff --git a/srtcore/api.cpp b/srtcore/api.cpp index 2a23dace2..eac0da84b 100644 --- a/srtcore/api.cpp +++ b/srtcore/api.cpp @@ -1839,6 +1839,9 @@ int CUDTUnited::groupConnect(CUDTGroup* pg, SRT_SOCKGROUPCONFIG* targets, int ar if (retval == -1) throw CUDTException(MJ_CONNECTION, MN_CONNLOST, 0); + if (!block_new_opened) + return 0; + return retval; } #endif diff --git a/srtcore/group.cpp b/srtcore/group.cpp index 9b3a26a01..e7d50a7ec 100644 --- a/srtcore/group.cpp +++ b/srtcore/group.cpp @@ -1369,7 +1369,26 @@ int CUDTGroup::sendBroadcast(const char* buf, int len, SRT_MSGCTRL& w_mc) // { send_CheckBrokenSockets() - if (!pending.empty()) + // Make an extra loop check to see if we could be + // in a condition of "all sockets either blocked or pending" + + int nsuccessful = 0; + int nblocked = 0; + bool is_pending_blocked = false; + for (vector::iterator is = sendstates.begin(); is != sendstates.end(); ++is) + { + if (is->stat == -1) + { + if (is->code == SRT_EASYNCSND) + ++nblocked; + } + else + { + nsuccessful++; + } + } + + if (!pending.empty() || nblocked) { HLOGC(gslog.Debug, log << "grp/sendBroadcast: found pending sockets, polling them."); @@ -1386,12 +1405,24 @@ int CUDTGroup::sendBroadcast(const char* buf, int len, SRT_MSGCTRL& w_mc) } else { + int swait_timeout = 0; + + // There's also a hidden condition here that is the upper if condition. + is_pending_blocked = (nsuccessful == 0); + + // If this is the case when + if (m_bSynSending && is_pending_blocked) + { + HLOGC(gslog.Debug, log << "grp/sendBroadcast: will block for " << m_iSndTimeOut << " - waiting for any writable in blocking mode"); + swait_timeout = m_iSndTimeOut; + } + { InvertedLock ug(m_GroupLock); THREAD_PAUSED(); m_pGlobal->m_EPoll.swait( - *m_SndEpolld, sready, 0, false /*report by retval*/); // Just check if anything happened + *m_SndEpolld, (sready), swait_timeout, false /*report by retval*/); // Just check if anything happened THREAD_RESUMED(); } @@ -1404,6 +1435,10 @@ int CUDTGroup::sendBroadcast(const char* buf, int len, SRT_MSGCTRL& w_mc) HLOGC(gslog.Debug, log << "grp/sendBroadcast: RDY: " << DisplayEpollResults(sready)); // sockets in EX: should be moved to wipeme. + // IMPORTANT: we check only PENDING sockets (not blocked) because only + // pending sockets might report ERR epoll without being explicitly broken. + // Sockets that did connect and just have buffer full will be always broken, + // if they're going to report ERR in epoll. for (vector::iterator i = pending.begin(); i != pending.end(); ++i) { if (CEPoll::isready(sready, *i, SRT_EPOLL_ERR)) @@ -1415,6 +1450,9 @@ int CUDTGroup::sendBroadcast(const char* buf, int len, SRT_MSGCTRL& w_mc) int no_events = 0; m_pGlobal->m_EPoll.update_usock(m_SndEID, *i, &no_events); } + + if (CEPoll::isready(sready, *i, SRT_EPOLL_OUT)) + is_pending_blocked = false; } // After that, all sockets that have been reported @@ -1431,7 +1469,10 @@ int CUDTGroup::sendBroadcast(const char* buf, int len, SRT_MSGCTRL& w_mc) if (m_bClosing) throw CUDTException(MJ_CONNECTION, MN_CONNLOST, 0); - send_CloseBrokenSockets(wipeme); + // Just for a case, when a socket that was blocked or pending + // had switched to write-enabled, + + send_CloseBrokenSockets((wipeme)); // wipeme will be cleared by this function // Re-check after the waiting lock has been reacquired if (m_bClosing) @@ -1693,9 +1734,18 @@ int CUDTGroup::sendBroadcast(const char* buf, int len, SRT_MSGCTRL& w_mc) if (none_succeeded) { - HLOGC(gslog.Debug, log << "grp/sendBroadcast: all links broken (none succeeded to send a payload)"); m_pGlobal->m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_OUT, false); - m_pGlobal->m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_ERR, true); + if (!m_bSynSending && (is_pending_blocked || was_blocked)) + { + HLOGC(gslog.Debug, log << "grp/sendBroadcast: no links are ready for sending"); + ercode = SRT_EASYNCSND; + } + else + { + HLOGC(gslog.Debug, log << "grp/sendBroadcast: all links broken (none succeeded to send a payload)"); + m_pGlobal->m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_ERR, true); + } + // Reparse error code, if set. // It might be set, if the last operation was failed. // If any operation succeeded, this will not be executed anyway. @@ -3320,7 +3370,7 @@ size_t CUDTGroup::sendBackup_CheckNeedActivate(const vector& idler } // [[using locked(this->m_GroupLock)]] -void CUDTGroup::send_CheckPendingSockets(const vector& pending, vector& w_wipeme) +bool CUDTGroup::send_CheckPendingSockets(const vector& pending, int nsuccessful, int nblocked, vector& w_wipeme) { // If we have at least one stable link, then select a link that have the // highest priority and silence the rest. @@ -3332,7 +3382,8 @@ void CUDTGroup::send_CheckPendingSockets(const vector& pending, vecto // we have one link that is stable and the freshly activated link is actually // stable too, we'll check this next time. // - if (!pending.empty()) + bool is_pending_blocked = false; + if (!pending.empty() || nblocked) { HLOGC(gslog.Debug, log << "grp/send*: found pending sockets, polling them."); @@ -3348,19 +3399,34 @@ void CUDTGroup::send_CheckPendingSockets(const vector& pending, vecto } else { + int swait_timeout = 0; + + // There's also a hidden condition here that is the upper if condition. + is_pending_blocked = (nsuccessful == 0); + + // If this is the case when + if (m_bSynSending && is_pending_blocked) + { + HLOGC(gslog.Debug, log << "grp/sendBroadcast: will block for " << m_iSndTimeOut << " - waiting for any writable in blocking mode"); + swait_timeout = m_iSndTimeOut; + } + // Some sockets could have been closed in the meantime. if (m_SndEpolld->watch_empty()) + { + LOGC(gslog.Error, log << "grp/send*: IPE: reported pending sockets, but EID is empty - ERROR!"); throw CUDTException(MJ_CONNECTION, MN_CONNLOST, 0); + } { InvertedLock ug(m_GroupLock); m_pGlobal->m_EPoll.swait( - *m_SndEpolld, sready, 0, false /*report by retval*/); // Just check if anything happened + *m_SndEpolld, sready, swait_timeout, false /*report by retval*/); // Just check if anything happened } if (m_bClosing) { - HLOGC(gslog.Debug, log << "grp/send...: GROUP CLOSED, ABANDONING"); + LOGC(gslog.Error, log << "grp/send...: GROUP CLOSED, ABANDONING"); throw CUDTException(MJ_CONNECTION, MN_CONNLOST, 0); } @@ -3377,6 +3443,9 @@ void CUDTGroup::send_CheckPendingSockets(const vector& pending, vecto int no_events = 0; m_pGlobal->m_EPoll.update_usock(m_SndEID, *i, &no_events); } + + if (CEPoll::isready(sready, *i, SRT_EPOLL_OUT)) + is_pending_blocked = false; } // After that, all sockets that have been reported @@ -3388,6 +3457,8 @@ void CUDTGroup::send_CheckPendingSockets(const vector& pending, vecto m_pGlobal->m_EPoll.clear_ready_usocks(*m_SndEpolld, SRT_EPOLL_OUT); } } + + return is_pending_blocked; } // [[using locked(this->m_GroupLock)]] @@ -3489,13 +3560,13 @@ void CUDTGroup::sendBackup_CheckParallelLinks(const vector& unstable, { // wipeme wiped, pending sockets checked, it can only mean that // all sockets are broken. - HLOGC(gslog.Debug, log << "grp/sendBackup: epolld empty - all sockets broken?"); + LOGC(gslog.Error, log << "grp/sendBackup: epolld empty - all sockets broken?"); throw CUDTException(MJ_CONNECTION, MN_CONNLOST, 0); } if (!m_bSynSending) { - HLOGC(gslog.Debug, log << "grp/sendBackup: non-blocking mode - exit with no-write-ready"); + LOGC(gslog.Error , log << "grp/sendBackup: non-blocking mode - exit with no-write-ready"); throw CUDTException(MJ_AGAIN, MN_WRAVAIL, 0); } // Here is the situation that the only links left here are: @@ -3523,7 +3594,7 @@ void CUDTGroup::sendBackup_CheckParallelLinks(const vector& unstable, // Some sockets could have been closed in the meantime. if (m_SndEpolld->watch_empty()) { - HLOGC(gslog.Debug, log << "grp/sendBackup: no more sendable sockets - group broken"); + LOGC(gslog.Error, log << "grp/sendBackup: no more sendable sockets - group broken"); throw CUDTException(MJ_CONNECTION, MN_CONNLOST, 0); } @@ -3536,6 +3607,7 @@ void CUDTGroup::sendBackup_CheckParallelLinks(const vector& unstable, if (brdy == 0) // SND timeout exceeded { + LOGC(gslog.Error, log << "grp/sendBackup: not ready to write"); throw CUDTException(MJ_AGAIN, MN_WRAVAIL, 0); } @@ -3572,7 +3644,10 @@ void CUDTGroup::sendBackup_CheckParallelLinks(const vector& unstable, // Re-check after the waiting lock has been reacquired if (m_bClosing) + { + LOGC(gslog.Error, log << "grp/sendBackup: group closed in the meantime"); throw CUDTException(MJ_CONNECTION, MN_CONNLOST, 0); + } if (brdy == -1 || ndead >= nlinks) { @@ -3738,6 +3813,7 @@ int CUDTGroup::sendBackup(const char* buf, int len, SRT_MSGCTRL& w_mc) // Avoid stupid errors in the beginning. if (len <= 0) { + LOGC(gslog.Error, log << "grp/send(backup): negative length: " << len); throw CUDTException(MJ_NOTSUP, MN_INVAL, 0); } @@ -3772,6 +3848,7 @@ int CUDTGroup::sendBackup(const char* buf, int len, SRT_MSGCTRL& w_mc) if (m_bClosing) { leaveCS(m_pGlobal->m_GlobControlLock); + LOGC(gslog.Error, log << "grp/send(backup): Cannot send, connection lost!"); throw CUDTException(MJ_CONNECTION, MN_CONNLOST, 0); } @@ -3890,6 +3967,10 @@ int CUDTGroup::sendBackup(const char* buf, int len, SRT_MSGCTRL& w_mc) // and therefore need to be activated. set sendable_pri; + // Likely will need to survive unlock-lock cycle on the group, + // so keep this by IDs. + vector blocked; + // We believe that we need to send the payload over every sendable link anyway. for (vector::iterator snd = sendable.begin(); snd != sendable.end(); ++snd) { @@ -3931,6 +4012,9 @@ int CUDTGroup::sendBackup(const char* buf, int len, SRT_MSGCTRL& w_mc) if (is_unstable && is_zero(u.m_tsUnstableSince)) // Add to unstable only if it wasn't unstable already insert_uniq((unstable), d); + if (is_unstable) + blocked.push_back(d->id); + const Sendstate cstate = {d->id, d, stat, erc}; sendstates.push_back(cstate); d->sndresult = stat; @@ -4103,31 +4187,60 @@ int CUDTGroup::sendBackup(const char* buf, int len, SRT_MSGCTRL& w_mc) << " unstable=" << unstable.size()); } - send_CheckPendingSockets(pending, (wipeme)); + int nsuccess = 0; + int nblocked = 0; + for (vector::iterator is = sendstates.begin(); is != sendstates.end(); ++is) + { + if (is->stat == -1) + { + if (is->code == SRT_EASYNCSND) + ++nblocked; + } + else + { + nsuccess++; + } + } + + bool is_pending_blocked = send_CheckPendingSockets(pending, nsuccess, nblocked, (wipeme)); // Re-check after the waiting lock has been reacquired if (m_bClosing) + { + LOGC(gslog.Error, log << "grp/sendBackup: closing the group during operation"); throw CUDTException(MJ_CONNECTION, MN_CONNLOST, 0); + } send_CloseBrokenSockets((wipeme)); // Re-check after the waiting lock has been reacquired if (m_bClosing) + { + LOGC(gslog.Error, log << "grp/sendBackup: closing the group during operation"); throw CUDTException(MJ_CONNECTION, MN_CONNLOST, 0); + } sendBackup_CheckParallelLinks(unstable, (parallel), (final_stat), (none_succeeded), (w_mc), (cx)); // (closing condition checked inside this call) if (none_succeeded) { - HLOGC(gslog.Debug, log << "grp/sendBackup: all links broken (none succeeded to send a payload)"); m_pGlobal->m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_OUT, false); - m_pGlobal->m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_ERR, true); - // Reparse error code, if set. - // It might be set, if the last operation was failed. - // If any operation succeeded, this will not be executed anyway. + if (!m_bSynSending && (is_pending_blocked || nblocked)) + { + HLOGC(gslog.Debug, log << "grp/sendBackup: no links are ready for sending"); + throw CUDTException(MJ_AGAIN, MN_WRAVAIL); + } + else + { + HLOGC(gslog.Debug, log << "grp/sendBackup: all links broken (none succeeded to send a payload)"); + m_pGlobal->m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_ERR, true); + // Reparse error code, if set. + // It might be set, if the last operation was failed. + // If any operation succeeded, this will not be executed anyway. - throw CUDTException(MJ_CONNECTION, MN_CONNLOST, 0); + throw CUDTException(MJ_CONNECTION, MN_CONNLOST, 0); + } } // Now fill in the socket table. Check if the size is enough, if not, diff --git a/srtcore/group.h b/srtcore/group.h index 75d58eac6..2465d0cbb 100644 --- a/srtcore/group.h +++ b/srtcore/group.h @@ -260,7 +260,7 @@ class CUDTGroup std::vector& w_parallel, std::vector& w_wipeme, const std::string& activate_reason); - void send_CheckPendingSockets(const std::vector& pending, std::vector& w_wipeme); + bool send_CheckPendingSockets(const std::vector& pending, int nsuccessful, int nblocked, std::vector& w_wipeme); void send_CloseBrokenSockets(std::vector& w_wipeme); void sendBackup_CheckParallelLinks(const std::vector& unstable, std::vector& w_parallel, From c272a059dc192878ca92e8c75170d041b6c53180 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miko=C5=82aj=20Ma=C5=82ecki?= Date: Tue, 8 Dec 2020 11:40:49 +0100 Subject: [PATCH 09/11] Fixed return 0 on multi-connect call. Added lock-preventive emergency exit checks in tsbpd. Suppressed IPE log when unsubscribing --- srtcore/api.cpp | 2 +- srtcore/core.cpp | 36 +++++++++++++++++++++++++++++++----- srtcore/epoll.cpp | 12 +++++++++--- 3 files changed, 41 insertions(+), 9 deletions(-) diff --git a/srtcore/api.cpp b/srtcore/api.cpp index eac0da84b..5d320bcc2 100644 --- a/srtcore/api.cpp +++ b/srtcore/api.cpp @@ -1839,7 +1839,7 @@ int CUDTUnited::groupConnect(CUDTGroup* pg, SRT_SOCKGROUPCONFIG* targets, int ar if (retval == -1) throw CUDTException(MJ_CONNECTION, MN_CONNLOST, 0); - if (!block_new_opened) + if (!block_new_opened && arraysize > 1) return 0; return retval; diff --git a/srtcore/core.cpp b/srtcore/core.cpp index e39bbce32..4278becac 100644 --- a/srtcore/core.cpp +++ b/srtcore/core.cpp @@ -5744,6 +5744,12 @@ void *CUDT::tsbpd(void *param) tsbpdtime = steady_clock::time_point(); } + if (self->m_bClosing) + { + HLOGC(tslog.Debug, log << "tsbpd: IPE? Closing flag set in the meantime of checking. Exiting"); + break; + } + if (!is_zero(tsbpdtime)) { const steady_clock::duration timediff = tsbpdtime - steady_clock::now(); @@ -5774,13 +5780,25 @@ void *CUDT::tsbpd(void *param) */ HLOGC(tslog.Debug, log << self->CONID() << "tsbpd: no data, scheduling wakeup at ack"); self->m_bTsbPdAckWakeup = true; - THREAD_PAUSED(); - tsbpd_cc.wait(); - THREAD_RESUMED(); + + bool signaled = false; + while (!signaled) + { + // For safety reasons, do wakeup once per 1s and re-check the flag. + THREAD_PAUSED(); + signaled = tsbpd_cc.wait_for(seconds_from(1)); + THREAD_RESUMED(); + if (self->m_bClosing) + { + HLOGC(tslog.Debug, log << "tsbpd: IPE? Closing flag set in the meantime of waiting. Exiting"); + goto ExitLoops; + } + } } HLOGC(tslog.Debug, log << self->CONID() << "tsbpd: WAKE UP!!!"); } +ExitLoops: THREAD_EXIT(); HLOGC(tslog.Debug, log << self->CONID() << "tsbpd: EXITING"); return NULL; @@ -7819,6 +7837,13 @@ void CUDT::destroySynch() void CUDT::releaseSynch() { SRT_ASSERT(m_bClosing); +#if ENABLE_HEAVY_LOGGING + if (!m_bClosing) + { + LOGC(smlog.Debug, log << "releaseSynch: IPE: m_bClosing not set to false, TSBPD might hangup!"); + } +#endif + m_bClosing = true; // wake up user calls CSync::lock_signal(m_SendBlockCond, m_SendBlockLock); @@ -7826,8 +7851,8 @@ void CUDT::releaseSynch() leaveCS(m_SendLock); // Awake tsbpd() and srt_recv*(..) threads for them to check m_bClosing. - CSync::lock_signal(m_RecvDataCond, m_RecvLock); - CSync::lock_signal(m_RcvTsbPdCond, m_RecvLock); + CSync::lock_broadcast(m_RecvDataCond, m_RecvLock); + CSync::lock_broadcast(m_RcvTsbPdCond, m_RecvLock); // Azquiring m_RcvTsbPdStartupLock protects race in starting // the tsbpd() thread in CUDT::processData(). @@ -11192,6 +11217,7 @@ void CUDT::checkTimers() void CUDT::updateBrokenConnection() { + m_bClosing = true; releaseSynch(); // app can call any UDT API to learn the connection_broken error s_UDTUnited.m_EPoll.update_events(m_SocketID, m_sPollID, SRT_EPOLL_IN | SRT_EPOLL_OUT | SRT_EPOLL_ERR, true); diff --git a/srtcore/epoll.cpp b/srtcore/epoll.cpp index 9d2317c0d..3c021a672 100644 --- a/srtcore/epoll.cpp +++ b/srtcore/epoll.cpp @@ -864,9 +864,15 @@ int CEPoll::update_events(const SRTSOCKET& uid, std::set& eids, const int e CEPollDesc::Wait* pwait = ed.watch_find(uid); if (!pwait) { - // As this is mapped in the socket's data, it should be impossible. - LOGC(eilog.Error, log << "epoll/update: IPE: update struck E" - << (*i) << " which is NOT SUBSCRIBED to @" << uid); + // Don't print this error, if the intention was to clear the readiness. + // This is being usually done together with unsubscription, so this error + // would be misleading and unnecessary here. Report only cases when setting readiness. + if (enable) + { + // As this is mapped in the socket's data, it should be impossible. + LOGC(eilog.Error, log << "epoll/update: IPE: update struck E" + << (*i) << " which is NOT SUBSCRIBED to @" << uid); + } continue; } From 834b702c8e0864094ce7036c3e0bbb209f365375 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miko=C5=82aj=20Ma=C5=82ecki?= Date: Tue, 8 Dec 2020 14:44:44 +0100 Subject: [PATCH 10/11] Fixed TSBPD deadlock-prone continuation. Demoted epoll IPE log. Made tsbpd_cc wait 125ms interrupt for sanity check --- srtcore/api.cpp | 2 +- srtcore/core.cpp | 49 +++++++++++++++++++++++++++++++---------------- srtcore/epoll.cpp | 12 +++--------- 3 files changed, 37 insertions(+), 26 deletions(-) diff --git a/srtcore/api.cpp b/srtcore/api.cpp index 5d320bcc2..6d8050158 100644 --- a/srtcore/api.cpp +++ b/srtcore/api.cpp @@ -2711,7 +2711,7 @@ void CUDTUnited::checkBrokenSockets() || (0 == j->second->m_pUDT->m_pSndBuffer->getCurrBufSize()) || (j->second->m_pUDT->m_tsLingerExpiration <= steady_clock::now())) { - HLOGC(smlog.Debug, log << "checkBrokenSockets: marking CLOSED qualified @" << j->second->m_SocketID); + HLOGC(smlog.Debug, log << "checkBrokenSockets: marking CLOSED (closing=true) qualified @" << j->second->m_SocketID); j->second->m_pUDT->m_tsLingerExpiration = steady_clock::time_point(); j->second->m_pUDT->m_bClosing = true; j->second->m_tsClosureTimeStamp = steady_clock::now(); diff --git a/srtcore/core.cpp b/srtcore/core.cpp index 4278becac..b5c4269c9 100644 --- a/srtcore/core.cpp +++ b/srtcore/core.cpp @@ -5739,6 +5739,12 @@ void *CUDT::tsbpd(void *param) gkeeper.group->updateLatestRcv(self->m_parent); } } + + // After re-acquisition of the m_RecvLock, re-check the closing flag + if (self->m_bClosing) + { + break; + } #endif CGlobEvent::triggerEvent(); tsbpdtime = steady_clock::time_point(); @@ -5762,8 +5768,9 @@ void *CUDT::tsbpd(void *param) log << self->CONID() << "tsbpd: FUTURE PACKET seq=" << current_pkt_seq << " T=" << FormatTime(tsbpdtime) << " - waiting " << count_milliseconds(timediff) << "ms"); THREAD_PAUSED(); - tsbpd_cc.wait_for(timediff); + const bool ATR_UNUSED signaled = tsbpd_cc.wait_for(timediff); THREAD_RESUMED(); + HLOGC(tslog.Debug, log << self->CONID() << "tsbpd: WAKE UP on " << (signaled? "SIGNAL" : "TIMEOUIT") << "!!!"); } else { @@ -5784,21 +5791,31 @@ void *CUDT::tsbpd(void *param) bool signaled = false; while (!signaled) { - // For safety reasons, do wakeup once per 1s and re-check the flag. + // For safety reasons, do wakeup once per 1/8s and re-check the flag. + // This should be enough long time that during a normal transmission + // the TSBPD thread would be woken up much earlier when required by + // ACK per ACK timer (at most 10ms since the last check) and in case + // when this might result in a deadlock, it would only hold up to 125ms, + // which should be little harmful for the application. NOTE THAT THIS + // IS A SANITY CHECK FOR A SITUATION THAT SHALL NEVER HAPPEN. THREAD_PAUSED(); - signaled = tsbpd_cc.wait_for(seconds_from(1)); + signaled = tsbpd_cc.wait_for(milliseconds_from(125)); THREAD_RESUMED(); - if (self->m_bClosing) + if (self->m_bClosing && !signaled) { - HLOGC(tslog.Debug, log << "tsbpd: IPE? Closing flag set in the meantime of waiting. Exiting"); - goto ExitLoops; + HLOGC(tslog.Debug, log << "tsbpd: IPE: Closing flag set in the meantime of waiting. Continue to EXIT"); + + // This break doesn't have to be done in case when signaled + // because if so this current loop will be interrupted anyway, + // and the outer loop will be terminated at the check of self->m_bClosing. + // This is only a sanity check. + break; } } + HLOGC(tslog.Debug, log << self->CONID() << "tsbpd: WAKE UP on " << (signaled? "SIGNAL" : "TIMEOUIT") << "!!!"); } - - HLOGC(tslog.Debug, log << self->CONID() << "tsbpd: WAKE UP!!!"); } -ExitLoops: + THREAD_EXIT(); HLOGC(tslog.Debug, log << self->CONID() << "tsbpd: EXITING"); return NULL; @@ -6372,7 +6389,7 @@ bool CUDT::closeInternal() // Inform the threads handler to stop. m_bClosing = true; - HLOGC(smlog.Debug, log << CONID() << "CLOSING STATE. Acquiring connection lock"); + HLOGC(smlog.Debug, log << CONID() << "CLOSING STATE (closing=true). Acquiring connection lock"); ScopedLock connectguard(m_ConnectionLock); @@ -7837,13 +7854,11 @@ void CUDT::destroySynch() void CUDT::releaseSynch() { SRT_ASSERT(m_bClosing); -#if ENABLE_HEAVY_LOGGING if (!m_bClosing) { - LOGC(smlog.Debug, log << "releaseSynch: IPE: m_bClosing not set to false, TSBPD might hangup!"); + HLOGC(smlog.Debug, log << "releaseSynch: IPE: m_bClosing not set to false, TSBPD might hangup!"); + m_bClosing = true; } -#endif - m_bClosing = true; // wake up user calls CSync::lock_signal(m_SendBlockCond, m_SendBlockLock); @@ -9545,7 +9560,7 @@ void CUDT::processClose() m_bBroken = true; m_iBrokenCounter = 60; - HLOGP(smlog.Debug, "processClose: sent message and set flags"); + HLOGP(smlog.Debug, "processClose: (closing=true) sent message and set flags"); if (m_bTsbPd) { @@ -11057,7 +11072,8 @@ bool CUDT::checkExpTimer(const steady_clock::time_point& currtime, int check_rea // Application will detect this when it calls any UDT methods next time. // HLOGC(xtlog.Debug, - log << "CONNECTION EXPIRED after " << count_milliseconds(currtime - m_tsLastRspTime) << "ms"); + log << "CONNECTION EXPIRED after " << count_milliseconds(currtime - m_tsLastRspTime) + << "ms (closing=true)"); m_bClosing = true; m_bBroken = true; m_iBrokenCounter = 30; @@ -11217,6 +11233,7 @@ void CUDT::checkTimers() void CUDT::updateBrokenConnection() { + HLOGC(smlog.Debug, log << "updateBrokenConnection: setting closing=true and taking out epoll events"); m_bClosing = true; releaseSynch(); // app can call any UDT API to learn the connection_broken error diff --git a/srtcore/epoll.cpp b/srtcore/epoll.cpp index 3c021a672..f74d6cd6c 100644 --- a/srtcore/epoll.cpp +++ b/srtcore/epoll.cpp @@ -864,15 +864,9 @@ int CEPoll::update_events(const SRTSOCKET& uid, std::set& eids, const int e CEPollDesc::Wait* pwait = ed.watch_find(uid); if (!pwait) { - // Don't print this error, if the intention was to clear the readiness. - // This is being usually done together with unsubscription, so this error - // would be misleading and unnecessary here. Report only cases when setting readiness. - if (enable) - { - // As this is mapped in the socket's data, it should be impossible. - LOGC(eilog.Error, log << "epoll/update: IPE: update struck E" - << (*i) << " which is NOT SUBSCRIBED to @" << uid); - } + // As this is mapped in the socket's data, it should be impossible. + HLOGC(eilog.Debug, log << "epoll/update: IPE: update struck E" + << (*i) << " which is NOT SUBSCRIBED to @" << uid); continue; } From f48362b371fb5bbd1a630e1f91408c27ac0233ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miko=C5=82aj=20Ma=C5=82ecki?= Date: Wed, 9 Dec 2020 10:44:16 +0100 Subject: [PATCH 11/11] TEMPORARY CHECKIN OF UNKNOWN PURPOSE (likely merge issues) --- docs/API-functions.md | 3473 ++++++++++++++++++------------ srtcore/core.cpp | 3 +- test/test_connection_timeout.cpp | 27 +- test/test_file_transmission.cpp | 78 +- 4 files changed, 2147 insertions(+), 1434 deletions(-) diff --git a/docs/API-functions.md b/docs/API-functions.md index 0c50c62de..1f4834c83 100644 --- a/docs/API-functions.md +++ b/docs/API-functions.md @@ -1,85 +1,232 @@ # SRT API Functions -- [**Library Initialization**](#Library-Initialization) - * [srt_startup](#srt_startup) - * [srt_cleanup](#srt_cleanup) -- [**Creating and configuring sockets**](#Creating-and-configuring-sockets) - * [srt_socket](#srt_socket) - * [srt_create_socket](#srt_create_socket) - * [srt_bind](#srt_bind) - * [srt_bind_acquire](#srt_bind_acquire) - * [srt_getsockstate](#srt_getsockstate) - * [srt_getsndbuffer](#srt_getsndbuffer) - * [srt_close](#srt_close) -- [**Connecting**](#Connecting) - * [srt_listen](#srt_listen) - * [srt_accept](#srt_accept) - * [srt_accept_bond](#srt_accept_bond) - * [srt_listen_callback](#srt_listen_callback) - * [srt_connect](#srt_connect) - * [srt_connect_bind](#srt_connect_bind) - * [srt_connect_debug](#srt_connect_debug) - * [srt_rendezvous](#srt_rendezvous) - * [srt_connect_callback](#srt_connect_callback) -- [**Socket group management**](#Socket-group-management) - * [SRT_GROUP_TYPE](#SRT_GROUP_TYPE) - * [SRT_SOCKGROUPCONFIG](#SRT_SOCKGROUPCONFIG) - * [SRT_SOCKGROUPDATA](#SRT_SOCKGROUPDATA) - * [SRT_MEMBERSTATUS](#SRT_MEMBERSTATUS) - * [srt_create_group](#srt_create_group) - * [srt_include](#srt_include) - * [srt_exclude](#srt_exclude) - * [srt_groupof](#srt_groupof) - * [srt_group_data](#srt_group_data) - * [srt_connect_group](#srt_connect_group) - * [srt_prepare_endpoint](#srt_prepare_endpoint) - * [srt_create_config](#srt_create_config) - * [srt_delete_config](#srt_delete_config) - * [srt_config_add](#srt_config_add) -- [**Options and properties**](#Options-and-properties) - * [srt_getpeername](#srt_getpeername) - * [srt_getsockname](#srt_getsockname) - * [srt_getsockopt, srt_getsockflag](#srt_getsockopt-srt_getsockflag) - * [srt_setsockopt, srt_setsockflag](#srt_setsockopt-srt_setsockflag) - * [srt_getversion](#srt_getversion) -- [**Helper data types for transmission**](#Helper-data-types-for-transmission) - * [SRT_MSGCTRL](#SRT_MSGCTRL) -- [**Transmission**](#Transmission) - * [srt_send, srt_sendmsg, srt_sendmsg2](#srt_send-srt_sendmsg-srt_sendmsg2) - * [srt_recv, srt_recvmsg, srt_recvmsg2](#srt_recv-srt_recvmsg-srt_recvmsg2) - * [srt_sendfile, srt_recvfile](#srt_sendfile-srt_recvfile) -- [**Diagnostics**](#Diagnostics) - * [srt_getlasterror_str](#srt_getlasterror_str) - * [srt_getlasterror](#srt_getlasterror) - * [srt_strerror](#srt_strerror) - * [srt_clearlasterror](#srt_clearlasterror) - * [srt_getrejectreason](#srt_getrejectreason) - * [srt_rejectreason_str](#srt_rejectreason_str) - * [srt_setrejectreason](#srt_setrejectreason) - * [Error Codes](#error-codes) -- [**Performance tracking**](#Performance-tracking) - * [srt_bstats, srt_bistats](#srt_bstats-srt_bistats) -- [**Asynchronous operations (epoll)**](#Asynchronous-operations-epoll) - * [srt_epoll_create](#srt_epoll_create) - * [srt_epoll_add_usock, srt_epoll_add_ssock, srt_epoll_update_usock, srt_epoll_update_ssock](#srt_epoll_add_usock-srt_epoll_add_ssock-srt_epoll_update_usock-srt_epoll_update_ssock) - * [srt_epoll_remove_usock, srt_epoll_remove_ssock](#srt_epoll_remove_usock-srt_epoll_remove_ssock) - * [srt_epoll_wait](#srt_epoll_wait) - * [srt_epoll_uwait](#srt_epoll_uwait) - * [srt_epoll_clear_usocks](#srt_epoll_clear_usocks) - * [srt_epoll_set](#srt_epoll_set) - * [srt_epoll_release](#srt_epoll_release) -- [**Logging control**](#Logging-control) - * [srt_setloglevel](#srt_setloglevel) - * [srt_addlogfa, srt_dellogfa, srt_resetlogfa](#srt_addlogfa-srt_dellogfa-srt_resetlogfa) - * [srt_setloghandler](#srt_setloghandler) - * [srt_setlogflags](#srt_setlogflags) -- [**Time Access**](#time-access) - * [srt_time_now](#srt_time_now) - * [srt_connection_time](#srt_connection_time) +

Library Initialization

+ +| *Function / Structure* | *Description* | +|:------------------------------------------------- |:-------------------------------------------------------------------------------------------------------------- | +| [srt_startup](#srt_startup) | Called at the start of an application that uses the SRT library | +| [srt_cleanup](#srt_cleanup) | Cleans up global SRT resources before exiting an application | +| | | + + +

Creating and Configuring Sockets

+ +| *Function / Structure* | *Description* | +|:------------------------------------------------- |:-------------------------------------------------------------------------------------------------------------- | +| [srt_socket](#srt_socket) | Deprecated | +| [srt_create_socket](#srt_create_socket) | Creates an SRT socket | +| [srt_bind](#srt_bind) | Binds a socket to a local address and port | +| [srt_bind_acquire](#srt_bind_acquire) | Acquires a given UDP socket instead of creating one | +| [srt_getsockstate](#srt_getsockstate) | Gets the current status of the socket | +| [srt_getsndbuffer](#srt_getsndbuffer) | Retrieves information about the sender buffer | +| [srt_close](#srt_close) | Closes the socket or group and frees all used resources | +| | | + +

Connecting

+ +| *Function / Structure* | *Description* | +|:------------------------------------------------- |:-------------------------------------------------------------------------------------------------------------- | +| [srt_listen](#srt_listen) | Sets up the listening state on a socket | +| [srt_accept](#srt_accept) | Accepts a connection; creates/returns a new socket or group ID | +| [srt_accept_bond](#srt_accept_bond) | Accepts a connection pending on any sockets passed in the `listeners` array
of `nlisteners` size | +| [srt_listen_callback](#srt_listen_callback) | Installs/executes a callback hook on a socket created to handle the incoming connection
on a listening socket | +| [srt_connect](#srt_connect) | Connects a socket or a group to a remote party with a specified address and port | +| [srt_connect_bind](#srt_connect_bind) | Same as [`srt_bind`](#srt_bind) then [`srt_connect`](#srt_connect) if called with socket [`u`](#u) | +| [srt_connect_debug](#srt_connect_debug) | Same as [`srt_connect`](#srt_connect)but allows specifying ISN (developers only) | +| [srt_rendezvous](#srt_rendezvous) | Performs a rendezvous connection | +| [srt_connect_callback](#srt_connect_callback) | Installs/executes a callback hook on socket/group [`u`](#u) after connection resolution/failure | +| | | + +

Socket Group Management

+ +| *Function / Structure* | *Description* | +|:------------------------------------------------- |:-------------------------------------------------------------------------------------------------------------- | +| [SRT_GROUP_TYPE](#SRT_GROUP_TYPE) | Group types collected in an [`SRT_GROUP_TYPE`](#SRT_GROUP_TYPE) enum | +| [SRT_SOCKGROUPCONFIG](#SRT_SOCKGROUPCONFIG) | Structure used to define entry points for connections for [`srt_connect_group`](#srt_connect_group) | +| [SRT_SOCKGROUPDATA](#SRT_SOCKGROUPDATA) | Most important structure for group member status | +| [SRT_MEMBERSTATUS](#SRT_MEMBERSTATUS) | Enumeration type that defines the state of a member connection in the group | +| [srt_create_group](#srt_create_group) | Creates a new group of type `type` | +| [srt_include](#srt_include) | Adds a socket to a group | +| [srt_exclude](#srt_exclude) | Removes a socket from a group to which it currently belongs | +| [srt_groupof](#srt_groupof) | Returns the group ID of a socket, or `SRT_INVALID_SOCK` | +| [srt_group_data](#srt_group_data) | Obtains the current member state of the group specified in `socketgroup` | +| [srt_connect_group](#srt_connect_group) | Similar to calling [`srt_connect`](#srt_connect) or [`srt_connect_bind`](#srt_connect_bind)
in a loop for every item in an array. | +| [srt_prepare_endpoint](#srt_prepare_endpoint) | Prepares a default [`SRT_SOCKGROUPCONFIG`](#SRT_SOCKGROUPCONFIG) object as an element of
an array for [`srt_connect_group`](#srt_connect_group) | +| [srt_create_config](#srt_create_config) | Creates a dynamic object for specifying socket options | +| [srt_delete_config](#srt_delete_config) | Deletes the configuration object | +| [srt_config_add](#srt_config_add) | Adds a configuration option to the configuration object | +| | | + +

Options and Properties

+ +| *Function / Structure* | *Description* | +|:------------------------------------------------- |:-------------------------------------------------------------------------------------------------------------- | +| [srt_getpeername](#srt_getpeername) | Retrieves the remote address to which the socket is connected | +| [srt_getsockname](#srt_getsockname) | Extracts the address to which the socket was bound | +| [srt_getsockopt](#srt_getsockopt) | Gets the value of the given socket option (from a socket or a group) | +| [srt_getsockflag](#srt_getsockflag) | Gets the value of the given socket option (from a socket or a group) | +| [srt_setsockopt](#srt_setsockopt) | Sets a value for a socket option in the socket or group | +| [srt_setsockflag](#srt_setsockflag) | Sets a value for a socket option in the socket or group | +| [srt_getversion](#srt_getversion) | Get SRT version value | +| | | + +

Helper Data Types for Transmission

+ +| *Function / Structure* | *Description* | +|:------------------------------------------------- |:-------------------------------------------------------------------------------------------------------------- | +| [SRT_MSGCTRL](#SRT_MSGCTRL) | Used in [`srt_sendmsg2`](#srt_sendmsg) and [`srt_recvmsg2`](#srt_recvmsg2) calls;
specifies some extra parameters | +| | | + +

Transmission

+ +| *Function / Structure* | *Description* | +|:------------------------------------------------- |:-------------------------------------------------------------------------------------------------------------- | +| [srt_send](#srt_send) | Sends a payload to a remote party over a given socket | +| [srt_sendmsg](#srt_sendmsg) | Sends a payload to a remote party over a given socket | +| [srt_sendmsg2](#srt_sendmsg2) | Sends a payload to a remote party over a given socket | +| [srt_recv](#srt_recv) | Extracts the payload waiting to be received | +| [srt_recvmsg](#srt_recvmsg) | Extracts the payload waiting to be received | +| [srt_recvmsg2](#srt_recvmsg2) | Extracts the payload waiting to be received | +| [srt_sendfile](#srt_sendfile) | Function dedicated to sending a file | +| [srt_recvfile](#srt_recvfile) | Function dedicated to receiving a file | +| | | + +

Performance Tracking

+ +| *Function / Structure* | *Description* | +|:------------------------------------------------- |:-------------------------------------------------------------------------------------------------------------- | +| [srt_bstats](#srt_bstats) | Reports the current statistics | +| [srt_bistats](#srt_bistats) | Reports the current statistics | +| | | + +

Asynchronous Operations (epoll)

+ +| *Function / Structure* | *Description* | +|:------------------------------------------------- |:-------------------------------------------------------------------------------------------------------------- | +| [srt_epoll_create](#srt_epoll_create) | Creates a new epoll container | +| [srt_epoll_add_usock](#srt_epoll_add_usock) | Adds a user socket to a container, or updates an existing socket subscription | +| [srt_epoll_add_ssock](#srt_epoll_add_ssock) | Adds a system socket to a container, or updates an existing socket subscription | +| [srt_epoll_update_usock](#srt_epoll_update_usock) | Adds a user socket to a container, or updates an existing socket subscription | +| [srt_epoll_update_ssock](#srt_epoll_update_ssock) | Adds a system socket to a container, or updates an existing socket subscription | +| [srt_epoll_remove_usock](#srt_epoll_remove_usock) | Removes a specified user socket from an epoll container; clears all readiness states for that socket | +| [srt_epoll_remove_ssock](#srt_epoll_remove_ssock) | Removes a specified system socket from an epoll container; clears all readiness states for that socket | +| [srt_epoll_wait](#srt_epoll_wait) | Blocks the call until any readiness state occurs in the epoll container | +| [srt_epoll_uwait](#srt_epoll_uwait) | Blocks a call until any readiness state occurs in the epoll container | +| [srt_epoll_clear_usocks](#srt_epoll_clear_usocks) | removes all SRT ("user") socket subscriptions from the epoll container identified by [`eid`](#eid) | +| [srt_epoll_set](#srt_epoll_set) | Allows setting or retrieving flags that change the default behavior of the epoll functions | +| [srt_epoll_release](#srt_epoll_release) | Deletes the epoll container | +| | | + +

Logging Control

+ +| *Function / Structure* | *Description* | +|:------------------------------------------------- |:-------------------------------------------------------------------------------------------------------------- | +| [srt_setloglevel](#srt_setloglevel) | Sets the minimum severity for logging | +| [srt_addlogfa](#srt_addlogfa) | Add a functional area (FA), which is an additional filtering mechanism for logging | +| [srt_dellogfa](#srt_dellogfa) | Delete a functional area (FA), which is an additional filtering mechanism for logging | +| [srt_resetlogfa](#srt_resetlogfa) | Reset a functional area (FA), which is an additional filtering mechanism for logging | +| [srt_setloghandler](#srt_setloghandler) | Replaces default standard stream for error logging | +| [srt_setlogflags](#srt_setlogflags) | Allows configuring parts of log information that are not to be passed | +| | | + +

Time Access

+ +| *Function / Structure* | *Description* | +|:------------------------------------------------- |:-------------------------------------------------------------------------------------------------------------- | +| [srt_time_now](#srt_time_now) | Get time in microseconds elapsed since epoch using SRT internal clock
(steady or monotonic clock) | +| [srt_connection_time](#srt_connection_time) | Get connection time in microseconds elapsed since epoch using SRT internal clock
(steady or monotonic clock) | +| | | + +

Diagnostics

+ +| *Function / Structure* | *Description* | +|:------------------------------------------------- |:-------------------------------------------------------------------------------------------------------------- | +| [srt_getlasterror](#srt_getlasterror) | Get the numeric code of the last error | +| [srt_strerror](#srt_strerror) | Returns a string message that represents a given SRT error code and possibly
the `errno` value, if not 0 | +| [srt_getlasterror_str](#srt_getlasterror_str) | Gets the text message for the last error | +| [srt_clearlasterror](#srt_clearlasterror) | Clears the last error | +| [srt_rejectreason_str](#srt_rejectreason_str) | Returns a constant string for the reason of the connection rejected, as per given code ID | +| [srt_setrejectreason](#srt_setrejectreason) | Sets the rejection code on the socket | +| [srt_getrejectreason](#srt_getrejectreason) | Provides a detailed reason for a failed connection attempt | +| | | + +

Rejection Reasons

+ +| *Rejection Reason* | *Description* | +|:------------------------------------------------- |:-------------------------------------------------------------------------------------------------------------- | +| [SRT_REJ_UNKNOWN](#SRT_REJ_UNKNOWN) | A fallback value for cases when there was no connection rejected | +| [SRT_REJ_SYSTEM](#SRT_REJ_SYSTEM) | A system function reported a failure | +| [SRT_REJ_PEER](#SRT_REJ_PEER) | The connection has been rejected by peer, but no further details are available | +| [SRT_REJ_RESOURCE](#SRT_REJ_RESOURCE) | A problem with resource allocation (usually memory) | +| [SRT_REJ_ROGUE](#SRT_REJ_ROGUE) | The data sent by one party to another cannot be properly interpreted | +| [SRT_REJ_BACKLOG](#SRT_REJ_BACKLOG) | The listener's backlog has exceeded | +| [SRT_REJ_IPE](#SRT_REJ_IPE) | Internal Program Error | +| [SRT_REJ_CLOSE](#SRT_REJ_CLOSE) | The listener socket received a request as it is being closed | +| [SRT_REJ_VERSION](#SRT_REJ_VERSION) | A party did not satisfy the minimum version requirement that had been set up for a connection | +| [SRT_REJ_RDVCOOKIE](#SRT_REJ_RDVCOOKIE) | Rendezvous cookie collision | +| [SRT_REJ_BADSECRET](#SRT_REJ_BADSECRET) | Both parties have defined a passprhase for connection and they differ | +| [SRT_REJ_UNSECURE](#SRT_REJ_UNSECURE) | Only one connection party has set up a password | +| [SRT_REJ_MESSAGEAPI](#SRT_REJ_MESSAGEAPI) | The value for [`SRTO_MESSAGEAPI`](../docs/APISocketOptions.md#SRTO_MESSAGEAPI) flag is different on both connection parties | +| [SRT_REJ_FILTER](#SRT_REJ_FILTER) | The [`SRTO_PACKETFILTER`](../docs/APISocketOptions.md#SRTO_PACKETFILTER) option has been set differently on both connection parties | +| [SRT_REJ_GROUP](#SRT_REJ_GROUP) | The group type or some group settings are incompatible for both connection parties | +| [SRT_REJ_TIMEOUT](#SRT_REJ_TIMEOUT) | The connection wasn't rejected, but it timed out | +| | | + +

Error Codes

+ +| *Error Code* | *Description* | +|:------------------------------------------------- |:-------------------------------------------------------------------------------------------------------------- | +[`SRT_EUNKNOWN`](#srt_eunknown) | Internal error when setting the right error code | +[`SRT_SUCCESS`](#srt_success) | The value set when the last error was cleared and no error has occurred since then | +[`SRT_ECONNSETUP`](#srt_econnsetup) | General setup error resulting from internal system state | +[`SRT_ENOSERVER`](#srt_enoserver) | Connection timed out while attempting to connect to the remote address | +[`SRT_ECONNREJ`](#srt_econnrej) | Connection has been rejected | +[`SRT_ESOCKFAIL`](#srt_esockfail) | An error occurred when trying to call a system function on an internally used UDP socket | +[`SRT_ESECFAIL`](#srt_esecfail) | A possible tampering with the handshake packets was detected, or encryption request
wasn't properly fulfilled. | +[`SRT_ESCLOSED`](#srt_esclosed) | A socket that was vital for an operation called in blocking mode has been closed
during the operation | +[`SRT_ECONNFAIL`](#srt_econnfail) | General connection failure of unknown details | +[`SRT_ECONNLOST`](#srt_econnlost) | The socket was properly connected, but the connection has been broken | +[`SRT_ENOCONN`](#srt_enoconn) | The socket is not connected | +[`SRT_ERESOURCE`](#srt_eresource) | System or standard library error reported unexpectedly for unknown purpose | +[`SRT_ETHREAD`](#srt_ethread) | System was unable to spawn a new thread when requried | +[`SRT_ENOBUF`](#srt_enobuf) | System was unable to allocate memory for buffers | +[`SRT_ESYSOBJ`](#srt_esysobj) | System was unable to allocate system specific objects | +[`SRT_EFILE`](#srt_efile) | General filesystem error (for functions operating with file transmission) | +[`SRT_EINVRDOFF`](#srt_einvrdoff) | Failure when trying to read from a given position in the file | +[`SRT_ERDPERM`](#srt_erdperm) | Read permission was denied when trying to read from file | +[`SRT_EINVWROFF`](#srt_einvwroff) | Failed to set position in the written file | +[`SRT_EWRPERM`](#srt_ewrperm) | Write permission was denied when trying to write to a file | +[`SRT_EINVOP`](#srt_einvop) | Invalid operation performed for the current state of a socket | +[`SRT_EBOUNDSOCK`](#srt_eboundsock) | The socket is currently bound and the required operation cannot be performed in this state | +[`SRT_ECONNSOCK`](#srt_econnsock) | The socket is currently connected and therefore performing the required operation is not possible | +[`SRT_EINVPARAM`](#srt_einvparam) | Call parameters for API functions have some requirements that were not satisfied | +[`SRT_EINVSOCK`](#srt_einvsock) | The API function required an ID of an entity (socket or group) and it was invalid | +[`SRT_EUNBOUNDSOCK`](#srt_eunboundsock) | The operation to be performed on a socket requires that it first be explicitly bound | +[`SRT_ENOLISTEN`](#srt_enolisten) | The socket passed for the operation is required to be in the listen state | +[`SRT_ERDVNOSERV`](#srt_erdvnoserv) | The required operation cannot be performed when the socket is set to rendezvous mode | +[`SRT_ERDVUNBOUND`](#srt_erdvunbound) | An attempt was made to connect to a socket set to rendezvous mode that was not first bound | +[`SRT_EINVALMSGAPI`](#srt_einvalmsgapi) | The function was used incorrectly in the message API | +[`SRT_EINVALBUFFERAPI`](#srt_einvalbufferapi) | The function was used incorrectly in the stream (buffer) API | +[`SRT_EDUPLISTEN`](#srt_eduplisten) | The port tried to be bound for listening is already busy | +[`SRT_ELARGEMSG`](#srt_elargemsg) | Size exceeded | +[`SRT_EINVPOLLID`](#srt_einvpollid) | The epoll ID passed to an epoll function is invalid | +[`SRT_EPOLLEMPTY`](#srt_epollempty) | The epoll container currently has no subscribed sockets | +[`SRT_EASYNCFAIL`](#srt_easyncfail) | General asynchronous failure (not in use currently) | +[`SRT_EASYNCSND`](#srt_easyncsnd) | Sending operation is not ready to perform | +[`SRT_EASYNCRCV`](#srt_easyncrcv) | Receiving operation is not ready to perform | +[`SRT_ETIMEOUT`](#srt_etimeout) | The operation timed out | +[`SRT_ECONGEST`](#srt_econgest) | With [`SRTO_TSBPDMODE`](../docs/APISocketOptions.md#SRTO_TSBPDMODE) and [`SRTO_TLPKTDROP`](../docs/APISocketOptions.md#SRTO_TLPKTDROP) set to true,
some packets were dropped by sender | +[`SRT_EPEERERR`](#srt_epeererr) | Receiver peer is writing to a file that the agent is sending | +| | | + ## Library initialization +* [srt_startup](#srt_startup) +* [srt_cleanup](#srt_cleanup) + + ### srt_startup ``` int srt_startup(void); @@ -91,18 +238,23 @@ global data, and starts the SRT GC thread. If this function isn't explicitly called, it will be called automatically when creating the first socket. However, relying on this behavior is strongly discouraged. -- Returns: +| Returns | | +|:----------------------------- |:--------------------------------------------------------------- | +| 0 | Successfully run, or already started | +| 1 | This is the first startup, but the GC thread is already running | +| -1 | Failed | +| | | - * 0 = successfully run, or already started - * 1 = this is the first startup, but the GC thread is already running - * -1 = failed +| Errors | | +|:----------------------------- |:--------------------------------------------------------------- | +| [`SRT_ECONNSETUP`](#srt_econnsetup) | With error code set, reported when required system resource(s) failed to initialize.
This is currently used only on Windows to report a failure from `WSAStartup`. | +| | | -- Errors: - * `SRT_ECONNSETUP` (with error code set): Reported when required system -resource(s) failed to initialize. This is currently used only on Windows to -report a failure from `WSAStartup`. +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) +--- + ### srt_cleanup ``` int srt_cleanup(void); @@ -111,41 +263,56 @@ int srt_cleanup(void); This function cleans up all global SRT resources and shall be called just before exiting the application that uses the SRT library. This cleanup function will still be called from the C++ global destructor, if not called by the application, although -relying on this behavior is stronly discouraged. - -- Returns: +relying on this behavior is strongly discouraged. - * 0 (A possibility to return other values is reserved for future use) +| Returns | | +|:----------------------------- |:--------------------------------------------------------------- | +| 0 | A possibility to return other values is reserved for future use | +| | | **IMPORTANT**: Note that the startup/cleanup calls have an instance counter. -This means that if you call `srt_startup` multiple times, you need to call the +This means that if you call [`srt_startup`](#srt_startup) multiple times, you need to call the `srt_cleanup` function exactly the same number of times. + ## Creating and configuring sockets +* [srt_socket](#srt_socket) +* [srt_create_socket](#srt_create_socket) +* [srt_bind](#srt_bind) +* [srt_bind_acquire](#srt_bind_acquire) +* [srt_getsockstate](#srt_getsockstate) +* [srt_getsndbuffer](#srt_getsndbuffer) +* [srt_close](#srt_close) + + ### srt_socket ``` SRTSOCKET srt_socket(int af, int type, int protocol); ``` -Old and deprecated version of `srt_create_socket`. All arguments are ignored. +Old and deprecated version of [`srt_create_socket`](#srt_create_socket). All arguments are ignored. **NOTE** changes with respect to UDT version: * In UDT (and SRT versions before 1.4.2) the `af` parameter was specifying the socket family (`AF_INET` or `AF_INET6`). This is now not required; this parameter -is decided at the call of `srt_conenct` or `srt_bind`. +is decided at the call of [`srt_connect`](#srt_connect) or [`srt_bind`](#srt_bind). * In UDT the `type` parameter was used to specify the file or message mode using `SOCK_STREAM` or `SOCK_DGRAM` symbols (with the latter being misleading, as the message mode has nothing to do with UDP datagrams and it's rather similar to the SCTP protocol). In SRT these two modes are available by setting -`SRTO_TRANSTYPE`. The default is `SRTT_LIVE`. If, however, you set -`SRTO_TRANSTYPE` to `SRTT_FILE` for file mode, you can then leave the -`SRTO_MESSAGEAPI` option as false (default), which corresponds to "stream" mode +[`SRTO_TRANSTYPE`](../docs/APISocketOptions.md#SRTO_TRANSTYPE). The default is `SRTT_LIVE`. If, however, you set +[`SRTO_TRANSTYPE`](../docs/APISocketOptions.md#SRTO_TRANSTYPE) to `SRTT_FILE` for file mode, you can then leave the +[`SRTO_MESSAGEAPI`](../docs/APISocketOptions.md#SRTO_MESSAGEAPI) option as false (default), which corresponds to "stream" mode (TCP-like), or set it to true, which corresponds to "message" mode (SCTP-like). +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) + +--- + ### srt_create_socket ``` SRTSOCKET srt_create_socket(); @@ -155,19 +322,26 @@ Creates an SRT socket. Note that socket IDs always have the `SRTGROUP_MASK` bit clear. -- Returns: +| Returns | | +|:----------------------------- |:------------------------------------------------------- | +| Socket ID | A valid socket ID on success | +| `SRT_INVALID_SOCK` | (`-1`) on error | +| | | - * a valid socket ID on success - * `SRT_INVALID_SOCK` (`-1`) on error +| Errors | | +|:----------------------------- |:------------------------------------------------------------ | +| [`SRT_ENOBUF`](#srt_enobuf) | Not enough memory to allocate required resources . | +| | | -- Errors: +**NOTE:** This is probably a design flaw (:warning:   **BUG?**). Usually underlying system +errors are reported by [`SRT_ECONNSETUP`](#srt_econnsetup). - * `SRT_ENOTBUF`: not enough memory to allocate required resources -**NOTE:** This is probably a design flaw (**BUG?**). Usually underlying system -errors are reported by `SRT_ECONNSETUP`. +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) +--- + ### srt_bind ``` int srt_bind(SRTSOCKET u, const struct sockaddr* name, int namelen); @@ -178,42 +352,59 @@ interface and the UDP port number to be used for the socket. When the local address is a form of `INADDR_ANY`, then it's bound to all interfaces. When the port number is 0, then the port number will be system-allocated if necessary. -This call is obligatory for a listening socket before calling `srt_listen` -and for rendezvous mode before calling `srt_connect`, otherwise it's optional. -For a listening socket it defines the network interface and the port where the -listener should expect a call request. In case of rendezvous mode (when the -socket has set `SRTO_RENDEZVOUS` to true, in this mode both parties connect -to one another) it defines the network interface and port from which packets -will be sent to the peer and to which the peer is expected to send packets. +This call is obligatory for a listening socket before calling [`srt_listen`](#srt_listen) +and for rendezvous mode before calling [`srt_connect`](#srt_connect); otherwise it's +optional. For a listening socket it defines the network interface and the port where +the listener should expect a call request. In the case of rendezvous mode (when the +socket has set [`SRTO_RENDEZVOUS`](../docs/APISocketOptions.md#SRTO_RENDEZVOUS) to +true both parties connect to one another) it defines the network interface and port +from which packets will be sent to the peer, and the port to which the peer is +expected to send packets. + +For a connecting socket this call can set up the outgoing port to be used in the +communication. It is allowed that multiple SRT sockets share one local outgoing +port, as long as [`SRTO_REUSEADDR`](../docs/APISocketOptions.md#SRTO_REUSEADDRS) +is set to *true* (default). Without this call the port will be automatically +selected by the system. + +**NOTE**: This function cannot be called on a socket group. If you need to +have the group-member socket bound to the specified source address before +connecting, use [`srt_connect_bind`](#srt_connect_bind) for that purpose. -For a connecting socket this call can set up the outgoing port to be used in -the communication. It is allowed that multiple SRT sockets share one local -outgoing port, as long as `SRTO_REUSEADDR` is set to *true* (default). Without -this call the port will be automatically selected by the system. +| Returns | | +|:----------------------------- |:--------------------------------------------------------- | +| `SRT_ERROR` | (-1) on error, otherwise 0 | +| | | -NOTE: This function cannot be called on socket group. If you need to -have the group-member socket bound to the specified source address before -connecting, use `srt_connect_bind` for that purpose. +| Errors | | +|:----------------------------------- |:-------------------------------------------------------------------- | +| [`SRT_EINVSOCK`](#srt_einvsock) | Socket passed as [`u`](#u) designates no valid socket | +| [`SRT_EINVOP`](#srt_einvop) | Socket already bound | +| [`SRT_ECONNSETUP`](#srt_econnsetup) | Internal creation of a UDP socket failed | +| [`SRT_ESOCKFAIL`](#srt_esockfail) | Internal configuration of a UDP socket (`bind`, `setsockopt`) failed | +| | | -- Returns: - * `SRT_ERROR` (-1) on error, otherwise 0 -- Errors: - * `SRT_EINVSOCK`: Socket passed as `u` designates no valid socket - * `SRT_EINVOP`: Socket already bound - * `SRT_ECONNSETUP`: Internal creation of a UDP socket failed - * `SRT_ESOCKFAIL`: Internal configuration of a UDP socket (`bind`, `setsockopt`) failed +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) +--- + ### srt_bind_acquire ``` int srt_bind_acquire(SRTSOCKET u, UDPSOCKET udpsock); ``` -A version of `srt_bind` that acquires a given UDP socket instead of creating one. +A version of [`srt_bind`](#srt_bind) that acquires a given UDP socket instead of creating one. + + + +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) +--- + ### srt_getsockstate ``` @@ -222,23 +413,25 @@ SRT_SOCKSTATUS srt_getsockstate(SRTSOCKET u); Gets the current status of the socket. Possible states are: -* `SRTS_INIT`: Created, but not bound -* `SRTS_OPENED`: Created and bound, but not in use yet. -* `SRTS_LISTENING`: Socket is in listening state -* `SRTS_CONNECTING`: The connect operation was initiated, but not yet -finished. This may also mean that it has timed out; you can only know -that after getting a socket error report from `srt_epoll_wait`. In blocking -mode it's not possible because `srt_connect` does not return until the -socket is connected or failed due to timeout or interrupted call. -* `SRTS_CONNECTED`: The socket is connected and ready for transmission. -* `SRTS_BROKEN`: The socket was connected, but the connection was broken -* `SRTS_CLOSING`: The socket may still be open and active, but closing -is requested, so no further operations will be accepted (active operations will -be completed before closing) -* `SRTS_CLOSED`: The socket has been closed, but not yet removed by the GC -thread -* `SRTS_NONEXIST`: The specified number does not correspond to a valid socket. +| State | Description | +|:----------------------------------------------- |:----------------------------------------------------------------- | +| `SRTS_INIT` | Created, but not bound. | +| `SRTS_OPENED` | Created and bound, but not in use yet. | +| `SRTS_LISTENING` | Socket is in listening state. | +| `SRTS_CONNECTING` | The connect operation was initiated, but not yet finished. This may also mean that it has timed out;
you can only know that after getting a socket error report from [`srt_epoll_wait`](#srt_epoll_wait). In blocking mode
it's not possible because [`srt_connect`](#srt_connect) does not return until the socket is connected or failed due
to timeout or interrupted call. | +| `SRTS_CONNECTED` | The socket is connected and ready for transmission. | +| `SRTS_BROKEN` | The socket was connected, but the connection was broken. | +| `SRTS_CLOSING` | The socket may still be open and active, but closing is requested, so no further operations will
be accepted (active operations will be completed before closing) | +| `SRTS_CLOSED` | The socket has been closed, but not yet removed by the GC thread. | +| `SRTS_NONEXIST` | The specified number does not correspond to a valid socket. | +| | | + + +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) + +--- + ### srt_getsndbuffer ``` @@ -247,6 +440,8 @@ int srt_getsndbuffer(SRTSOCKET sock, size_t* blocks, size_t* bytes); Retrieves information about the sender buffer. +**Arguments**: + * `sock`: Socket to test * `blocks`: Written information about buffer blocks in use * `bytes`: Written information about bytes in use @@ -254,6 +449,12 @@ Retrieves information about the sender buffer. This function can be used for diagnostics. It is especially useful when the socket needs to be closed asynchronously. + + +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) + +--- + ### srt_close ``` @@ -264,16 +465,30 @@ Closes the socket or group and frees all used resources. Note that underlying UDP sockets may be shared between sockets, so these are freed only with the last user closed. -- Returns: +| Returns | | +|:----------------------------- |:--------------------------------------------------------- | +| `SRT_ERROR` | (-1) in case of error, otherwise 0 | +| | | - * `SRT_ERROR` (-1) in case of error, otherwise 0 +| Errors | | +|:------------------------------- |:----------------------------------------------- | +| [`SRT_EINVSOCK`](#srt_einvsock) | Socket [`u`](#u) indicates no valid socket ID | +| | | -- Errors: - * `SRT_EINVSOCK`: Socket `u` indicates no valid socket ID ## Connecting +* [srt_listen](#srt_listen) +* [srt_accept](#srt_accept) +* [srt_accept_bond](#srt_accept_bond) +* [srt_listen_callback](#srt_listen_callback) +* [srt_connect](#srt_connect) +* [srt_connect_bind](#srt_connect_bind) +* [srt_connect_debug](#srt_connect_debug) +* [srt_rendezvous](#srt_rendezvous) +* [srt_connect_callback](#srt_connect_callback) + ### srt_listen ``` int srt_listen(SRTSOCKET u, int backlog); @@ -284,30 +499,35 @@ defines how many sockets may be allowed to wait until they are accepted (excessive connection requests are rejected in advance). The following important options may change the behavior of the listener -socket and the `srt_accept` function: +socket and the [`srt_accept`](#srt_accept) function: -* `srt_listen_callback` installs a user function that will be called -before `srt_accept` can happen -* `SRTO_GROUPCONNECT` option allows the listener socket to accept group -connections +* [`srt_listen_callback`](#srt_listen_callback) installs a user function that will +be called before [`srt_accept`](#srt_accept) can happen +* [`SRTO_GROUPCONNECT`](../docs/APISocketOptions.md#SRTO_GROUPCONNECT) option allows +the listener socket to accept group connections -- Returns: +| Returns | | +|:----------------------------- |:--------------------------------------------------------- | +| `SRT_ERROR` | (-1) in case of error, otherwise 0. | +| | | - * `SRT_ERROR` (-1) in case of error, otherwise 0. +| Errors | | +|:--------------------------------------- |:-------------------------------------------------------------------------------------------- | +| [`SRT_EINVPARAM`](#srt_einvparam) | Value of `backlog` is 0 or negative. | +| [`SRT_EINVSOCK`](#srt_einvsock) | Socket [`u`](#u) indicates no valid SRT socket. | +| [`SRT_EUNBOUNDSOCK`](#srt_eunboundsock) | [`srt_bind`](#srt_bind) has not yet been called on that socket. | +| [`SRT_ERDVNOSERV`](#srt_erdvnoserv) | [`SRTO_RENDEZVOUS`](../docs/APISocketOptions.md#SRTO_RENDEZVOUS) flag is set to true on specified socket. | +| [`SRT_EINVOP`](#srt_einvop) | Internal error (should not happen when [`SRT_EUNBOUNDSOCK`](#srt_eunboundsock) is reported). | +| [`SRT_ECONNSOCK`](#srt_econnsock) | The socket is already connected. | +| [`SRT_EDUPLISTEN`](#srt_eduplisten) | The address used in [`srt_bind`](#srt_bind) by this socket is already occupied by another listening socket.
Binding multiple sockets to one IP address and port is allowed, as long as
[`SRTO_REUSEADDR`](../docs/APISocketOptions.md#SRTO_REUSEADDRS) is set to true, but only one of these sockets can be set up as a listener. | +| | | -- Errors: - * `SRT_EINVPARAM`: Value of `backlog` is 0 or negative. - * `SRT_EINVSOCK`: Socket `u` indicates no valid SRT socket. - * `SRT_EUNBOUNDSOCK`: `srt_bind` has not yet been called on that socket. - * `SRT_ERDVNOSERV`: `SRTO_RENDEZVOUS` flag is set to true on specified socket. - * `SRT_EINVOP`: Internal error (should not happen when `SRT_EUNBOUNDSOCK` is reported). - * `SRT_ECONNSOCK`: The socket is already connected. - * `SRT_EDUPLISTEN`: The address used in `srt_bind` by this socket is already -occupied by another listening socket. Binding multiple sockets to one IP address -and port is allowed, as long as `SRTO_REUSEADDR` is set to true, but only one of -these sockets can be set up as a listener. +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) + +--- + ### srt_accept ``` @@ -318,7 +538,7 @@ Accepts a pending connection, then creates and returns a new socket or group ID that handles this connection. The group and socket can be distinguished by checking the `SRTGROUP_MASK` bit on the returned ID. -* `lsn`: the listener socket previously configured by `srt_listen` +* `lsn`: the listener socket previously configured by [`srt_listen`](#srt_listen) * `addr`: the IP address and port specification for the remote party * `addrlen`: INPUT: size of `addr` pointed object. OUTPUT: real size of the returned object @@ -330,95 +550,97 @@ and `addrlen` must also specify a variable to contain the object size. Note also that in the case of group connection only the initial connection that establishes the group connection is returned, together with its address. As member connections are added or broken within the group, you can obtain this -information through `srt_group_data` or the data filled by `srt_sendmsg2` and -`srt_recvmsg2`. - -If the pending connection is a group connection (initiated on the peer side -by calling the connection function using a group ID, and permitted on the -listener socket by `SRTO_GROUPCONNECT` flag), then the value returned is a -group ID. This function then creates a new group, as well as a new socket for -this very connection, that will be added to the group. Once the group is -created this way, further connections within the same group, as well as sockets -for them, will be created in the background. The `SRT_EPOLL_UPDATE` event is -raised on the `lsn` socket when a new background connection is attached to the -group, although it's usually for internal use only. - -- Returns: - - * On success, a valid SRT socket or group ID to be used for transmission - * `SRT_ERROR` (-1) on failure - -- Errors: - - * `SRT_EINVPARAM`: NULL specified as `addrlen`, when `addr` is not NULL - * `SRT_EINVSOCK`: `lsn` designates no valid socket ID. - * `SRT_ENOLISTEN`: `lsn` is not set up as a listener (`srt_listen` not called) - * `SRT_EASYNCRCV`: No connection reported so far. This error is reported only -when the `lsn` listener socket was configured as non-blocking for reading -(`SRTO_RCVSYN` set to false); otherwise the call blocks until a connection -is reported or an error occurs - * `SRT_ESCLOSED`: The `lsn` socket has been closed while the function was -blocking the call (if `SRTO_RCVSYN` is set to default true). This includes a -situation when the socket was closed just at the moment when a connection was -made and the socket got closed during processing - - +information through [`srt_group_data`](#srt_group_data) or the data filled by +[`srt_sendmsg2`](#srt_sendmsg) and [`srt_recvmsg2`](#srt_recvmsg2). + +If the pending connection is a group connection (initiated on the peer side by +calling the connection function using a group ID, and permitted on the listener +socket by the [`SRTO_GROUPCONNECT`](../docs/APISocketOptions.md#SRTO_GROUPCONNECT) +flag), then the value returned is a group ID. This function then creates a new +group, as well as a new socket for this connection, that will be added to the +group. Once the group is created this way, further connections within the same +group, as well as sockets for them, will be created in the background. The +[`SRT_EPOLL_UPDATE`](#SRT_EPOLL_UPDATE) event is raised on the `lsn` socket when +a new background connection is attached to the group, although it's usually for +internal use only. + +| Returns | | +|:----------------------------- |:----------------------------------------------------------------------- | +| socket/group ID | On success, a valid SRT socket or group ID to be used for transmission. | +| `SRT_ERROR` | (-1) on failure | +| | | + +| Errors | | +|:--------------------------------- |:----------------------------------------------------------------------- | +| [`SRT_EINVPARAM`](#srt_einvparam) | NULL specified as `addrlen`, when `addr` is not NULL | +| [`SRT_EINVSOCK`](#srt_einvsock) | `lsn` designates no valid socket ID. | +| [`SRT_ENOLISTEN`](#srt_enolisten) | `lsn` is not set up as a listener ([`srt_listen`](#srt_listen) not called). | +| [`SRT_EASYNCRCV`](#srt_easyncrcv) | No connection reported so far. This error is reported only when the `lsn` listener socket was
configured as non-blocking for reading ([`SRTO_RCVSYN`](../docs/APISocketOptions.md#SRTO_RCVSYN) set to false); otherwise the call blocks
until a connection is reported or an error occurs | +| [`SRT_ESCLOSED`](#srt_esclosed) | The `lsn` socket has been closed while the function was blocking the call (if [`SRTO_RCVSYN`](../docs/APISocketOptions.md#SRTO_RCVSYN)
is set to default true). This includes a situation when the socket was closed just at the
moment when a connection was made and the socket got closed during processing | +| | | + + + +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) + +--- + ### srt_accept_bond ``` SRTSOCKET srt_accept_bond(const SRTSOCKET listeners[], int nlisteners, int msTimeOut); ``` -Accepts a pending connection, like `srt_accept`, but pending on any of the +Accepts a pending connection, like [`srt_accept`](#srt_accept), but pending on any of the listener sockets passed in the `listeners` array of `nlisteners` size. -* `listeners`: array of listener sockets (all must be setup by `srt_listen`) +**Arguments**: + +* `listeners`: array of listener sockets (all must be setup by [`srt_listen`](#srt_listen)) * `nlisteners`: size of the `listeners` array * `msTimeOut`: timeout in [ms] or -1 to block forever -This function is for blocking mode only - for non-blocking mode you should -simply call `srt_accept` on the first listener socket that reports readiness, -and this function is actually a friendly shortcut that uses waiting on epoll -and `srt_accept` internally. This function supports an important use case for -accepting a group connection, for which every member connection is expected to -be established over a different listener socket. - -Note that there's no special set of settings required or rejected for this -function. The group-member connections for the same group can be established -over various different listener sockets always when all those listeners are -hosted by the same application, as the group management is global for the -application, so a connection reporting in for an already connected group -gets discovered and the connection will be handled in the background, -regardless to which listener socket the call was done - as long as the -connection is accepted according to any additional conditions. - -This function has still nothing to do with the groups - you can use it in -any case when you have one service that accepts connections to multiple -endpoints. Note also that the settings as to whether listeners should -accept or reject socket or group connections, should be applied to the -listener sockets appropriately prior to calling this function. - -- Returns: - - * On success, a valid SRT socket or group ID to be used for transmission - * `SRT_ERROR` (-1) on failure - -- Errors: - - * `SRT_EINVPARAM`: NULL specified as `listeners` or `nlisteners` < 1 - - * `SRT_EINVSOCK`: any socket in `listeners` designates no valid socket ID. -Can also mean Internal Error when an error occurred while creating an -accepted socket (**BUG?**) - - * `SRT_ENOLISTEN`: any socket in `listeners` is not set up as a listener -(`srt_listen` not called, or the listener socket has already been closed) - - * `SRT_EASYNCRCV`: No connection reported on any listener socket as the -timeout has been reached. This error is only reported when msTimeOut is -not -1 - - +This function is for blocking mode only - for non-blocking mode you should simply +call [`srt_accept`](#srt_accept) on the first listener socket that reports readiness, +and this function is actually a friendly shortcut that uses waiting on epoll and +[`srt_accept`](#srt_accept) internally. This function supports an important use +case for accepting a group connection, for which every member connection is expected +to be established over a different listener socket. + +Note that there's no special set of settings required or rejected for this function. +Group-member connections for the same group can always be established over various +different listener sockets when all those listeners are hosted by the same application. +The group management is global for the application, so a connection reporting in for +an already connected group gets discovered, and the connection will be handled in the +background. This occurs regardless of which listener socket the call was made to, +as long as the connection is accepted according to any additional conditions. + +This function has nothing to do with the groups. You can use it in any case when +you have one service that accepts connections to multiple endpoints. Note also +that the settings as to whether listeners should accept or reject socket or group +connections should be applied to the listener sockets appropriately prior to +calling this function. + +| Returns | | +|:----------------------------- |:---------------------------------------------------------------------- | +| SRT socket
group ID | On success, a valid SRT socket or group ID to be used for transmission | +| `SRT_ERROR` | (-1) on failure | +| | | + +| Errors | | +|:--------------------------------- |:------------------------------------------------------------ | +| [`SRT_EINVPARAM`](#srt_einvparam) | NULL specified as `listeners` or `nlisteners` < 1 | +| [`SRT_EINVSOCK`](#srt_einvsock) | Any socket in `listeners` designates no valid socket ID. Can also mean *Internal Error* when
an error occurred while creating an accepted socket (:warning:   **BUG?**) | +| [`SRT_ENOLISTEN`](#srt_enolisten) | Any socket in `listeners` is not set up as a listener ([`srt_listen`](#srt_listen) not called, or the listener socket
has already been closed) | +| [`SRT_EASYNCRCV`](#srt_easyncrcv) | No connection reported on any listener socket as the timeout has been reached. This error is only
reported when `msTimeOut` is not -1 | +| | | + + + +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) + +--- + ### srt_listen_callback ``` @@ -426,22 +648,26 @@ int srt_listen_callback(SRTSOCKET lsn, srt_listen_callback_fn* hook_fn, void* ho ``` This call installs a callback hook, which will be executed on a socket that is -automatically created to handle the incoming connection on the listening -socket (and is about to be returned by `srt_accept`), but before the connection -has been accepted. +automatically created to handle the incoming connection on the listening socket +(and is about to be returned by [`srt_accept`](#srt_accept)), but before the +connection has been accepted. + +**Arguments**: * `lsn`: Listening socket where you want to install the callback hook * `hook_fn`: The callback hook function pointer * `hook_opaque`: The pointer value that will be passed to the callback function -- Returns: +| Returns | | +|:----------------------------- |:---------------------------------------------------------- | +| 0 | Successful | +| -1 | Error | +| | | - * 0, if successful - * -1, on error - -- Errors: - - * `SRT_EINVPARAM` reported when `hook_fn` is a null pointer +| Errors | | +|:--------------------------------- |:----------------------------------------- | +| [`SRT_EINVPARAM`](#srt_einvparam) | Reported when `hook_fn` is a null pointer | +| | | The callback function has the signature as per this type definition: ``` @@ -453,50 +679,54 @@ The callback function gets the following parameters passed: * `opaque`: The pointer passed as `hook_opaque` when registering * `ns`: The freshly created socket to handle the incoming connection -* `hs_version`: The handshake version (usually 5, pre-1.3 versions use 4) +* `hs_version`: The handshake version (usually 5, pre-1.3 versions of SRT use 4) * `peeraddr`: The address of the incoming connection -* `streamid`: The value set to `SRTO_STREAMID` option set on the peer side +* `streamid`: The value set to [`SRTO_STREAMID`](../docs/APISocketOptions.md#SRTO_STREAMID) option set on the peer side -(Note that versions that use handshake version 4 are incapable of using -any extensions, such as streamid, however they do support encryption. -Note also that the SRT version isn't yet extracted, however you can -prevent too old version connections using `SRTO_MINVERSION` option). +Note that SRT versions that use handshake version 4 are incapable of using +any extensions, such as `streamid`. However they do support encryption. +Note also that the SRT version isn't extracted at this point. However you can +prevent connections with versions that are too old by using the +[`SRTO_MINVERSION`](../docs/APISocketOptions.md#SRTO_MINVERSION) option. The callback function is given an opportunity to: -* use the passed information (streamid and peer address) to decide +* use the passed information (`streamid` and peer address) to decide what to do with this connection * alter any options on the socket, which could not be set properly - before on the listening socket to be derived by the accepted socket, + beforehand on the listening socket to be derived by the accepted socket, and won't be allowed to be altered after the socket is returned by - `srt_accept` + [`srt_accept`](#srt_accept) -Note that the returned socket has already set all derived options from the -listener socket, as it happens normally, and the moment when this callback is -called is when the conclusion handshake has been already received from the -caller party, but not yet interpreted (the streamid field is extracted from it -prematurely). When you, for example, set a passphrase on the socket at this -very moment, the Key Material processing will happen against this already set -passphrase, after the callback function is finished. +Note that normally the returned socket has already set all derived options from +the listener socket. The moment when this callback is called is when the conclusion +handshake has been already received from the caller party, but not yet interpreted +(the `streamid` field is extracted from it prematurely). When, for example, you set +a passphrase on the socket at this point, the Key Material processing will happen +against this passphrase, after the callback function is finished. The callback function shall return 0, if the connection is to be accepted. If you return -1, **or** if the function throws an exception, this will be -understood as a request to reject the incoming connection - in which case the -about-to-be-accepted socket will be silently deleted and `srt_accept` will not -report it. Note that in case of non-blocking mode the epoll bits for read-ready -on the listener socket will not be set if the connection is rejected, including -when rejected from this user function. +understood as a request to reject the incoming connection. In this case the +about-to-be-accepted socket will be silently deleted and [`srt_accept`](#srt_accept) +will not report it. Note that in case of non-blocking mode the epoll bits for +read-ready on the listener socket will not be set if the connection is rejected, +including when rejected from this user function. **IMPORTANT**: This function is called in the receiver worker thread, which -means that it must do its checks and operations as quickly as possible and keep -the minimum possible time, as every delay you do in this function will burden -the processing of the incoming data on the associated UDP socket, which in case -of a listener socket means the listener socket itself and every socket accepted -off this listener socket. Avoid any extensive search operations, best cache in -memory whatever database you have to check against the data received in -streamid or peeraddr. +means that it must do its checks and operations as quickly as possible. Every +delay you create in this function will burden the processing of the incoming data +on the associated UDP socket. In the case of a listener socket this means the +listener socket itself and every socket accepted off this listener socket. +Avoid any extensive search operations. It is best to cache in memory whatever +database you have to check against the data received in `streamid` or `peeraddr`. + + +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) +--- + ### srt_connect ``` @@ -505,53 +735,60 @@ int srt_connect(SRTSOCKET u, const struct sockaddr* name, int namelen); Connects a socket or a group to a remote party with a specified address and port. -* `u`: can be an SRT socket or SRT group, both freshly created and not yet - used for any connection, except possibly `srt_bind` on the socket +**Arguments**: + +* [`u`](#u): can be an SRT socket or SRT group, both freshly created and not yet + used for any connection, except possibly [`srt_bind`](#srt_bind) on the socket * `name`: specification of the remote address and port * `namelen`: size of the object passed by `name` -**NOTES:** +**NOTES:** + 1. The socket used here may be bound from upside (or binding and connection can -be done in one function, `srt_connect_bind`) so that it uses a predefined -network interface or local outgoing port. If not, it behaves as if it was -bound to `INADDR_ANY` (which binds on all interfaces) and port 0 (which +be done in one function, [`srt_connect_bind`](#srt_connect_bind)) so that it uses +a predefined network interface or local outgoing port. If not, it behaves as if +it was bound to `INADDR_ANY` (which binds on all interfaces) and port 0 (which makes the system assign the port automatically). -2. When `u` is a group, then this call can be done multiple times, each time +2. When [`u`](#u) is a group, then this call can be done multiple times, each time for another member connection, and a new member SRT socket will be created automatically for every call of this function. 3. If you want to connect a group to multiple links at once and use blocking -mode, you might want to use `srt_connect_group` instead. - -- Returns: - - * `SRT_ERROR` (-1) in case of error - * 0 in case when used for `u` socket - * Socket ID created for connection for `u` group - -- Errors: - - * `SRT_EINVSOCK`: Socket `u` indicates no valid socket ID - * `SRT_ERDVUNBOUND`: Socket `u` has set `SRTO_RENDEZVOUS` to true, but `srt_bind` -hasn't yet been called on it. The `srt_connect` function is also used to connect a -rendezvous socket, but rendezvous sockets must be explicitly bound to a local -interface prior to connecting. Non-rendezvous sockets (caller sockets) can be -left without binding - the call to `srt_connect` will bind them automatically. - * `SRT_ECONNSOCK`: Socket `u` is already connected - * `SRT_ECONNREJ`: Connection has been rejected - * `SRT_ENOSERVER`: Connection has been timed out (see `SRTO_CONNTIMEO`) - * `SRT_ESCLOSED`: The socket `u` has been closed while the function was -blocking the call (if `SRTO_RCVSYN` is set to default true) - -When `SRT_ECONNREJ` error is reported, you can get the reason for -a rejected connection from `srt_getrejectreason`. In non-blocking -mode (when `SRTO_RCVSYN` is set to false), only `SRT_EINVSOCK`, -`SRT_ERDVUNBOUND` and `SRT_ECONNSOCK` can be reported. In all other cases -the function returns immediately with a success, and the only way to obtain -the connecting status is through the epoll flag with `SRT_EPOLL_ERR`. -In this case you can also call `srt_getrejectreason` to get the detailed -reason for the error, including connection timeout (`SRT_REJ_TIMEOUT`). - - +mode, you might want to use [`srt_connect_group`](#srt_connect_group) instead. + +| Returns | | +|:----------------------------- |:--------------------------------------------------------- | +| `SRT_ERROR` | (-1) in case of error | +| 0 | In case when used for [`u`](#u) socket | +| Socket ID | Created for connection for [`u`](#u) group | +| | | + +| Errors | | +|:------------------------------------- |:----------------------------------------------------------- | +| [`SRT_EINVSOCK`](#srt_einvsock) | Socket [`u`](#u) indicates no valid socket ID | +| [`SRT_ERDVUNBOUND`](#srt_erdvunbound) | Socket [`u`](#u) has set [`SRTO_RENDEZVOUS`](../docs/APISocketOptions.md#SRTO_RENDEZVOUS) to true, but [`srt_bind`](#srt_bind) hasn't yet been called on it.
The [`srt_connect`](#srt_connect) function is also used to connect a rendezvous socket, but rendezvous sockets
must be explicitly bound to a local interface prior to connecting. Non-rendezvous sockets (caller
sockets) can be left without binding - the call to [`srt_connect`](#srt_connect) will bind them automatically. | +| [`SRT_ECONNSOCK`](#srt_econnsock) | Socket [`u`](#u) is already connected | +| [`SRT_ECONNREJ`](#srt_econnrej) | Connection has been rejected | +| [`SRT_ENOSERVER`](#srt_enoserver) | Connection has been timed out (see [`SRTO_CONNTIMEO`](../docs/APISocketOptions.md#SRTO_CONNTIMEO)) | +| [`SRT_ESCLOSED`](#srt_esclosed) | The socket [`u`](#u) has been closed while the function was blocking the call (if [`SRTO_RCVSYN`](../docs/APISocketOptions.md#SRTO_RCVSYN) is set to
default true) | +| | | + + +When the [`SRT_ECONNREJ`](#srt_econnrej) error is reported, you can get the reason +for a rejected connection from [`srt_getrejectreason`](#srt_getrejectreason). In +non-blocking mode (when [`SRTO_RCVSYN`](../docs/APISocketOptions.md#SRTO_RCVSYN) +is set to false), only [`SRT_EINVSOCK`](#srt_einvsock), [`SRT_ERDVUNBOUND`](#srt_erdvunbound) +and [`SRT_ECONNSOCK`](#srt_econnsock) can be reported. In all other cases the function +returns immediately with a success, and the only way to obtain the connecting status +is through the epoll flag with [`SRT_EPOLL_ERR`](#SRT_EPOLL_ERR). In this case you can +also call [`srt_getrejectreason`](#srt_getrejectreason) to get the detailed reason for +the error, including connection timeout ([`SRT_REJ_TIMEOUT`](#SRT_REJ_TIMEOUT)). + + + +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) + +--- + ### srt_connect_bind ``` @@ -559,35 +796,47 @@ int srt_connect_bind(SRTSOCKET u, const struct sockaddr* source, const struct sockaddr* target, int len); ``` -This function does the same as first `srt_bind` then `srt_connect`, if called -with `u` being a socket. If `u` is a group, then it will execute `srt_bind` +This function does the same as first [`srt_bind`](#srt_bind) then +[`srt_connect`](#srt_connect), if called with [`u`](#u) being a socket. +If [`u`](#u) is a group, then it will execute [`srt_bind`](#srt_bind) first on the automatically created socket for the connection. -* `u`: Socket or group to connect -* `source`: Address to bind `u` to +**Arguments**: + +* [`u`](#u): Socket or group to connect +* `source`: Address to bind [`u`](#u) to * `target`: Address to connect * `len`: size of the original structure of `source` and `target` -- Returns: - - * `SRT_ERROR` (-1) in case of error - * 0 in case when used for `u` socket - * Socket ID created for connection for `u` group +| Returns | | +|:----------------------------- |:-------------------------------------------------------- | +| `SRT_ERROR` | (-1) in case of error | +| 0 | In case when used for [`u`](#u) socket | +| Socket ID | Created for connection for [`u`](#u) group | +| | | + +| Errors | | +|:------------------------------------- |:-------------------------------------------------------- | +| [`SRT_EINVSOCK`](#srt_einvsock) | Socket passed as [`u`](#u) designates no valid socket | +| [`SRT_EINVOP`](#srt_einvop) | Socket already bound | +| [`SRT_ECONNSETUP`](#srt_econnsetup) | Internal creation of a UDP socket failed | +| [`SRT_ESOCKFAIL`](#srt_esockfail) | Internal configuration of a UDP socket (`bind`, `setsockopt`) failed | +| [`SRT_ERDVUNBOUND`](#srt_erdvunbound) | Internal error ([`srt_connect`](#srt_connect) should not report it after [`srt_bind`](#srt_bind) was called) | +| [`SRT_ECONNSOCK`](#srt_econnsock) | Socket [`u`](#u) is already connected | +| [`SRT_ECONNREJ`](#srt_econnrej) | Connection has been rejected | +| | | + + +**IMPORTANT**: It's not allowed to bind and connect the same socket to two +different families (that is, both `source` and `target` must be `AF_INET` or +`AF_INET6`), although you may mix links over IPv4 and IPv6 in one group. -- Errors: - * `SRT_EINVSOCK`: Socket passed as `u` designates no valid socket - * `SRT_EINVOP`: Socket already bound - * `SRT_ECONNSETUP`: Internal creation of a UDP socket failed - * `SRT_ESOCKFAIL`: Internal configuration of a UDP socket (`bind`, `setsockopt`) failed - * `SRT_ERDVUNBOUND`: Internal error (`srt_connect` should not report it after `srt_bind` was called) - * `SRT_ECONNSOCK`: Socket `u` is already connected - * `SRT_ECONNREJ`: Connection has been rejected -IMPORTANT: It's not allowed to bind and connect the same socket to two -different families (that is, both `source` and `target` must be `AF_INET` or -`AF_INET6`), although you may mix links over IPv4 and IPv6 in one group. +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) +--- + ### srt_connect_debug ``` @@ -599,57 +848,74 @@ same thing as [`srt_connect`](#srt_connect), with the exception that it allows specifying the Initial Sequence Number for data transmission. Normally this value is generated randomly. + + +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) + +--- + ### srt_rendezvous ``` int srt_rendezvous(SRTSOCKET u, const struct sockaddr* local_name, int local_namelen, const struct sockaddr* remote_name, int remote_namelen); ``` Performs a rendezvous connection. This is a shortcut for doing bind locally, -setting the `SRTO_RENDEZVOUS` option to true, and doing `srt_connect`. +setting the [`SRTO_RENDEZVOUS`](../docs/APISocketOptions.md#SRTO_RENDEZVOUS) option +to true, and doing [`srt_connect`](#srt_connect). -* `u`: socket to connect +**Arguments**: + +* [`u`](#u): socket to connect * `local_name`: specifies the local network interface and port to bind * `remote_name`: specifies the remote party's IP address and port -- Returns: +| Returns | | +|:----------------------------- |:-------------------------------------------------------- | +| `SRT_ERROR` | (-1) in case of error, otherwise 0 | +| | | + +| Errors | | +|:------------------------------------- |:-------------------------------------------------------- | +| [`SRT_EINVSOCK`](#srt_einvsock) | Socket passed as [`u`](#u) designates no valid socket | +| [`SRT_EINVOP`](#srt_einvop) | Socket already bound | +| [`SRT_ECONNSETUP`](#srt_econnsetup) | Internal creation of a UDP socket failed | +| [`SRT_ESOCKFAIL`](#srt_esockfail) | Internal configuration of a UDP socket (`bind`, `setsockopt`) failed | +| [`SRT_ERDVUNBOUND`](#srt_erdvunbound) | Internal error ([`srt_connect`](#srt_connect) should not report it after [`srt_bind`](#srt_bind) was called) | +| [`SRT_ECONNSOCK`](#srt_econnsock) | Socket [`u`](#u) is already connected | +| [`SRT_ECONNREJ`](#srt_econnrej) | Connection has been rejected | +| | | - * `SRT_ERROR` (-1) in case of error, otherwise 0 +**IMPORTANT**: Establishing a rendezvous connection to two different families is not +allowed (that is, both `local_name` and `remote_name` must be `AF_INET` or `AF_INET6`). -- Errors: - * `SRT_EINVSOCK`: Socket passed as `u` designates no valid socket - * `SRT_EINVOP`: Socket already bound - * `SRT_ECONNSETUP`: Internal creation of a UDP socket failed - * `SRT_ESOCKFAIL`: Internal configuration of a UDP socket (`bind`, `setsockopt`) failed - * `SRT_ERDVUNBOUND`: Internal error (`srt_connect` should not report it after `srt_bind` was called) - * `SRT_ECONNSOCK`: Socket `u` is already connected - * `SRT_ECONNREJ`: Connection has been rejected -IMPORTANT: It's not allowed to perform a rendezvous connection to two -different families (that is, both `local_name` and `remote_name` must be `AF_INET` or -`AF_INET6`). +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) +--- + ### srt_connect_callback ``` int srt_connect_callback(SRTSOCKET u, srt_connect_callback_fn* hook_fn, void* hook_opaque); ``` -This call installs a callback hook, which will be executed on a given `u` -socket or all member sockets of `u` group, just after the pending connection -situation in the background has been resolved and the connection has failed. -Note that this function is not guaranteed to be called if the `u` socket is set -to blocking mode (`SRTO_RCVSYN` option set to true). It is guaranteed to be -called when a socket is in non-blocking mode, or when you use a group. - -This function is mainly intended to be used with group connections. Note that -even if you use a group connection in blocking mode, after the group is considered -connected the member connections still continue in background. Also, when -some connections are still pending and others have failed, the blocking -call for `srt_connect_group` will not exit until at least one of them succeeds -or all fail - in such a case those failures also happen only in the background, -while the connecting function blocks until all connections are resolved. -When all links fail, you will only get a general error code for the group. -This mechanism allows you to get individual errors for particular member +This call installs a callback hook, which will be executed on a given [`u`](#u) +socket or all member sockets of a [`u`](#u) group, just after a pending connection +in the background has been resolved and the connection has failed. Note that this +function is not guaranteed to be called if the [`u`](#u) socket is set to blocking +mode ([`SRTO_RCVSYN`](../docs/APISocketOptions.md#SRTO_RCVSYN) option set to true). +It is guaranteed to be called when a socket is in non-blocking mode, or when you +use a group. + +This function is mainly intended to be used with group connections. Note that even +if you use a group connection in blocking mode, after the group is considered +connected the member connections still continue in background. Also, when some +connections are still pending and others have failed, the blocking call for +[`srt_connect_group`](#srt_connect_group) will not exit until at least one of +them succeeds or all fail - in such a case those failures also happen only in +the background, while the connecting function blocks until all connections are +resolved. When all links fail, you will only get a general error code for the +group. This mechanism allows you to get individual errors for particular member connection failures. You can also use this mechanism as an alternative method for a single-socket @@ -658,47 +924,79 @@ process is finished. It is recommended, however, that you use this callback only to collect failure information, as the call will happen in one of the internal SRT threads. -* `u`: Socket or group that will be used for connecting and for which the hook is installed +**Arguments**: + +* [`u`](#u): Socket or group that will be used for connecting and for which the hook is installed * `hook_fn`: The callback hook function pointer * `hook_opaque`: The pointer value that will be passed to the callback function -- Returns: - * 0, if successful - * -1, on error +| Returns | | +|:----------------------------- |:--------------------------------------------------------- | +| 0 | Successful | +| -1 | Error | +| | | -- Errors: +| Errors | | +|:---------------------------------- |:------------------------------------------| +| [`SRT_EINVPARAM`](#srt_einvparam) | Reported when `hook_fn` is a null pointer | +| | | - * `SRT_EINVPARAM` reported when `hook_fn` is a null pointer The callback function signature has the following type definition: ``` typedef void srt_connect_callback_fn(void* opaq, SRTSOCKET ns, int errorcode, const struct sockaddr* peeraddr, int token); ``` -where: + +**Arguments**: * `opaq`: The pointer passed as `hook_opaque` when registering * `ns`: The socket for which the connection process was resolved -* `errorcode`: The error code, same as for `srt_connect` for blocking mode -* `peeraddr`: The target address passed to `srt_connect` call +* [`errorcode`](#error-codes): The error code, same as for [`srt_connect`](#srt_connect) for blocking mode +* `peeraddr`: The target address passed to [`srt_connect`](#srt_connect) call * `token`: The token value, if it was used for group connection, otherwise -1 ## Socket group management + * [SRT_GROUP_TYPE](#SRT_GROUP_TYPE) + * [SRT_SOCKGROUPCONFIG](#SRT_SOCKGROUPCONFIG) + * [SRT_SOCKGROUPDATA](#SRT_SOCKGROUPDATA) + * [SRT_MEMBERSTATUS](#SRT_MEMBERSTATUS) + +[Functions to be used on groups](#functions-to-be-used-on-groups): + + * [srt_create_group](#srt_create_group) + * [srt_include](#srt_include) + * [srt_exclude](#srt_exclude) + * [srt_groupof](#srt_groupof) + * [srt_group_data](#srt_group_data) + * [srt_connect_group](#srt_connect_group) + * [srt_prepare_endpoint](#srt_prepare_endpoint) + * [srt_create_config](#srt_create_config) + * [srt_delete_config](#srt_delete_config) + * [srt_config_add](#srt_config_add) + + + ### SRT_GROUP_TYPE -The following group types are collected in an `SRT_GROUP_TYPE` enum: +The following group types are collected in an [`SRT_GROUP_TYPE`](#SRT_GROUP_TYPE) enum: * `SRT_GTYPE_BROADCAST`: broadcast type, all links are actively used at once * `SRT_GTYPE_BACKUP`: backup type, idle links take over connection on disturbance * `SRT_GTYPE_BALANCING`: balancing type, share bandwidth usage between links + +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) + +--- + ### SRT_SOCKGROUPCONFIG This structure is used to define entry points for connections for the -`srt_connect_group` function: +[`srt_connect_group`](#srt_connect_group) function: ``` typedef struct SRT_GroupMemberConfig_ @@ -720,10 +1018,10 @@ where: * `peeraddr`: address to which `id` should be connected * `weight`: the weight parameter for the link (group-type dependent) * `config`: the configuration object, if used (see [`srt_create_config()`](#srt_create_config)) -* `errorcode`: status of the connecting operation +* [`errorcode`](#error-codes): status of the connecting operation * `token`: An integer value unique for every connection, or -1 if unused -The `srt_perpare_endpoint` sets these fields to default values. After that +The `srt_prepare_endpoint` sets these fields to default values. After that you can change the value of `weight` and `config` and `token` fields. The `weight` parameter's meaning is dependent on the group type: @@ -731,10 +1029,10 @@ you can change the value of `weight` and `config` and `token` fields. The * BACKUP: positive value of link priority (the greater, the more preferred) * BALANCING: relative expected load on this link for fixed algorithm -In any case, the allowed value ranges for `weight` is between 0 and 32767. +In any case, the allowed value for `weight` is between 0 and 32767. -The `config` parameter is used to provide options to be set separately -on a socket for a particular connection (see [`srt_create_config()`](#srt_create_config)). +The `config` parameter is used to provide options to be set separately on a socket +for a particular connection (see [`srt_create_config()`](#srt_create_config)). The `token` value is intended to allow the application to more easily identify a particular connection. If you don't use it and leave the default value of -1, @@ -744,9 +1042,13 @@ The application can also set a unique value by itself and keep the same value for the same connection. +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) + +--- + ### SRT_SOCKGROUPDATA -The most important structure for the group member status is `SRT_SOCKGROUPDATA`: +The most important structure for the group member status is [`SRT_SOCKGROUPDATA`](#SRT_SOCKGROUPDATA): ```c++ typedef struct SRT_SocketGroupData_ @@ -765,16 +1067,21 @@ where: * `id`: member socket ID * `peeraddr`: address to which `id` should be connected -* `sockstate`: current connection status (see [`srt_getsockstate`](#srt_getsockstate)) +* `sockstate`: current connection status (see [`srt_getsockstate`](#srt_getsockstate) * `weight`: current weight value set on the link * `memberstate`: current state of the member (see below) * `result`: result of the operation (if this operation recently updated this structure) -* `token`: A token value set for that connection (see [`SRT_SOCKGROUPCONFIG`](#srt_sockgroupconfig)) +* `token`: A token value set for that connection (see [`SRT_SOCKGROUPCONFIG`](#SRT_SOCKGROUPCONFIG)) + +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) + +--- + ### SRT_MEMBERSTATUS -The enumeration type that defines the state of the member -connection in the group: +The enumeration type that defines the state of a member +connection in a group: * `SRT_GST_PENDING`: The connection is in progress, so the socket is not currently being used for transmission, even potentially, @@ -783,35 +1090,36 @@ without turning into `SRT_GST_IDLE` * `SRT_GST_IDLE`: The connection is established and ready to take over transmission, but it's not used for transmission at -the moment. This state may last for a short moment in case of +the moment. This state may last for a short moment in the case of broadcast or balancing groups. In backup groups this state defines a backup link that is ready to take over when the -currently active (running) link gets unstable. +currently active (running) link becomes unstable. * `SRT_GST_RUNNING`: The connection is established and at least one packet has already been sent or received over it. -* `SRT_GST_BROKEN`: The connection was broken. Broken connections -are not to be revived. Note also that it is only possible to see this -state if it is read by `srt_sendmsg2` or `srt_recvmsg2` just after +* `SRT_GST_BROKEN`: The connection was broken. Broken connections are not to be +revived. Note also that it is only possible to see this state if it is read by +[`srt_sendmsg2`](#srt_sendmsg) or [`srt_recvmsg2`](#srt_recvmsg2) just after the link failure has been detected. Otherwise, the broken link simply disappears from the member list. -Note that internally the member state is separate for sending and -receiving. If the `memberstate` field of `SRT_SOCKGROUPDATA` is +Note that internally the member state is separate for sending and receiving. If +the `memberstate` field of [`SRT_SOCKGROUPDATA`](#SRT_SOCKGROUPDATA) is `SRT_GST_RUNNING`, it means that this is the state in at least one direction, while in the other direction it may be `SRT_GST_IDLE`. In all other cases the states should be the same in both directions. -States should normally start with `SRT_GST_PENDING` and then -turn into `SRT_GST_IDLE`. Once a new link is used for sending data, -the state becomes `SRT_GST_RUNNING`. -In case of `SRT_GTYPE_BACKUP` type group, if a link is in -`SRT_GST_RUNNING` state, but another link is chosen to remain +States should normally start with `SRT_GST_PENDING` and then turn into +`SRT_GST_IDLE`. Once a new link is used for sending data, the state becomes +`SRT_GST_RUNNING`. In the case of the `SRT_GTYPE_BACKUP` type group, if a link +is in the `SRT_GST_RUNNING` state, but another link is chosen to remain as the only active one, this link will be "silenced" (its state will become `SRT_GST_IDLE`). + + ## Functions to be used on groups: ### srt_create_group @@ -822,9 +1130,14 @@ SRTSOCKET srt_create_group(SRT_GROUP_TYPE type); Creates a new group of type `type`. This is typically called on the caller side to be next used for connecting to the listener peer side. -The group ID is of the same domain as socket ID, with the exception that +The group ID is of the same domain as the socket ID, with the exception that the `SRTGROUP_MASK` bit is set on it, unlike for socket ID. + +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) + +--- + ### srt_include ``` @@ -834,6 +1147,12 @@ int srt_include(SRTSOCKET socket, SRTSOCKET group); This function adds a socket to a group. This is only allowed for unmanaged groups. No such group type is currently implemented. + + +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) + +--- + ### srt_exclude ``` @@ -843,6 +1162,12 @@ This function removes a socket from a group to which it currently belongs. This is only allowed for unmanaged groups. No such group type is currently implemented. + + +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) + +--- + ### srt_groupof ``` @@ -852,50 +1177,67 @@ SRTSOCKET srt_groupof(SRTSOCKET socket); Returns the group ID of the socket, or `SRT_INVALID_SOCK` if the socket doesn't exist or it's not a member of any group. + + +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) + +--- + ### srt_group_data ``` int srt_group_data(SRTSOCKET socketgroup, SRT_SOCKGROUPDATA output[], size_t* inoutlen); ``` +**Arguments**: + * `socketgroup` an existing socket group ID * `output` points to an output array * `inoutlen` points to a variable that stores the size of the `output` array, and is set to the filled array's size This function obtains the current member state of the group specified in -`socketgroup`. The `output` should point to an array large enough to hold -all the elements. The `inoutlen` should point to a variable initially set -to the size of the `output` array. -The current number of members will be written back to `inoutlen`. +`socketgroup`. The `output` should point to an array large enough to hold all +the elements. The `inoutlen` should point to a variable initially set to the size +of the `output` array. The current number of members will be written back to `inoutlen`. If the size of the `output` array is enough for the current number of members, the `output` array will be filled with group data and the function will return -the number of elements filled. -Otherwise the array will not be filled and `SRT_ERROR` will be returned. +the number of elements filled. Otherwise the array will not be filled and +`SRT_ERROR` will be returned. This function can be used to get the group size by setting `output` to `NULL`, and providing `socketgroup` and `inoutlen`. -- Returns: +| Returns | | +|:----------------------------- |:--------------------------------------------------------- | +| # of elements | The number of data elements filled, on success | +| -1 | Error | +| | | + +| Errors | | +|:---------------------------------- |:--------------------------------------------------------- | +| [`SRT_EINVPARAM`](#srt_einvparam) | Reported if `socketgroup` is not an existing group ID | +| [`SRT_ELARGEMSG`](#srt_elargemsg) | Reported if `inoutlen` if less than the size of the group | +| | | - * the number of data elements filled, on success - * -1, on error + + -- Errors: +| in:output | in:inoutlen | returns | out:output | out:inoutlen | Error | +|:---------:|:--------------:|:------------:|:----------:|:------------:|:---------------------------------:| +| NULL | NULL | -1 | NULL | NULL | [`SRT_EINVPARAM`](#srt_einvparam) | +| NULL | ptr | 0 | NULL | group.size() | ✖️ | +| ptr | NULL | -1 | ✖️ | NULL | [`SRT_EINVPARAM`](#srt_einvparam) | +| ptr | ≥ group.size | group.size() | group.data | group.size | ✖️ | +| ptr | < group.size | -1 | ✖️ | group.size | [`SRT_ELARGEMSG`](#srt_elargemsg) | - * `SRT_EINVPARAM` reported if `socketgroup` is not an existing group ID - * `SRT_ELARGEMSG` reported if `inoutlen` if less than the size of the group -| in:output | in:inoutlen | returns | out:output | out:inoutlen | Error | -|-----------|----------------|--------------|-----------|--------------|--------| -| NULL | NULL | -1 | NULL | NULL | `SRT_EINVPARAM` | -| NULL | ptr | 0 | NULL | group.size() | ✖️ | -| ptr | NULL | -1 | ✖️ | NULL | `SRT_EINVPARAM` | -| ptr | ≥ group.size | group.size() | group.data | group.size | ✖️ | -| ptr | < group.size | -1 | ✖️ | group.size | `SRT_ELARGEMSG` | +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) +--- + ### srt_connect_group ``` @@ -903,49 +1245,49 @@ int srt_connect_group(SRTSOCKET group, SRT_SOCKGROUPCONFIG name [], int arraysize); ``` -This function does almost the same as calling `srt_connect` or `srt_connect_bind` -(when the source was specified for `srt_prepare_endpoint`) in a loop for every -item specified in `name` array. However if you did this in blocking mode, the -first call to `srt_connect` would block until the connection is established, -whereas this function blocks until any of the specified connections is -established. +This function does almost the same as calling [`srt_connect`](#srt_connect) or +[`srt_connect_bind`](#srt_connect_bind) (when the source was specified for +[`srt_prepare_endpoint`](#srt_prepare_endpoint)) in a loop for every item specified +in `name` array. However if you did this in blocking mode, the first call to +[`srt_connect`](#srt_connect) would block until the connection is established, +whereas this function blocks until any of the specified connections is established. -If you set the group nonblocking mode (`SRTO_RCVSYN` option), there's no -difference, except that the `SRT_SOCKGROUPCONFIG` structure allows you -to add extra configuration data used by groups. Note also that this function -accepts only groups, not sockets. +If you set the group nonblocking mode ([`SRTO_RCVSYN`](../docs/APISocketOptions.md#SRTO_RCVSYN) +option), there's no difference, except that the [`SRT_SOCKGROUPCONFIG`](#SRT_SOCKGROUPCONFIG) +structure allows you to add extra configuration data used by groups. Note also that +this function accepts only groups, not sockets. The elements of the `name` array need to be prepared with the use of the [`srt_prepare_endpoint`](#srt_prepare_endpoint) function. Note that it is **NOT** required that every target address you specify for it is of the same family. -Return value and errors in this function are the same as in `srt_connect`, +Return value and errors in this function are the same as in [`srt_connect`](#srt_connect), although this function reports success when at least one connection has -succeeded. If none has succeeded, this function reports `SRT_ECONNLOST` +succeeded. If none has succeeded, this function reports an [`SRT_ECONNLOST`](#srt_econnlost) error. Particular connection states can be obtained from the `name` -array upon return from the `errorcode` field. +array upon return from the [`errorcode`](#error-codes) field. -The fields of `SRT_SOCKGROUPCONFIG` structure have the following meaning: +The fields of [`SRT_SOCKGROUPCONFIG`](#SRT_SOCKGROUPCONFIG) structure have the following meaning: -Input: +**Input**: -* `id`: unused, should be -1 (default when created by `srt_prepare_endpoint`) +* `id`: unused, should be -1 (default when created by [`srt_prepare_endpoint`](#srt_prepare_endpoint)) * `srcaddr`: address to bind before connecting, if specified (see below for details) * `peeraddr`: target address to connect * `weight`: weight value to be set on the link * `config`: socket options to be set on the socket before connecting -* `errorcode`: unused, should be `SRT_SUCCESS` (default) +* [`errorcode`](#error-codes): unused, should be [`SRT_SUCCESS`](#srt_success) (default) * `token`: An integer value unique for every connection, or -1 if unused -Output: +**Output**: * `id`: The socket created for that connection (-1 if failed to create) * `srcaddr`: unchanged * `peeraddr`: unchanged * `weight`: unchanged * `config`: unchanged (the object should be manually deleted upon return) -* `errorcode`: status of connection for that link (`SRT_SUCCESS` if succeeded) +* [`errorcode`](#error-codes): status of connection for that link ([`SRT_SUCCESS`](#srt_success) if succeeded) * `token`: same as in input, or a newly created token value if input was -1 The procedure of connecting for every connection definition specified @@ -958,12 +1300,12 @@ in the `name` array is performed the following way: 3. If `config` is not NULL, configuration options stored there are set on that socket. 4. If source address is specified (that is `srcaddr` value is **not** -default empty, as described in [`SRT_SOCKGROUPCONFIG`](#SRT_SOCKGROUPCONFIG)), -then the binding operation is being done on the socket (see `srt_bind`). +default empty, as described in [`SRT_SOCKGROUPCONFIG`](#SRT_SOCKGROUPCONFIG), +then the binding operation is done on the socket (see [`srt_bind`](#srt_bind)). 5. The socket is added to the group as a member. -6. The socket is being connected to the target address, as specified +6. The socket is connected to the target address, as specified in the `peeraddr` field. During this process there can be errors at any stage. There are two @@ -976,18 +1318,18 @@ then, and for which the connection attempt has at least successfully started, remain group members, although the function will return immediately with an error status (that is, without waiting for the first successful connection). If your application wants to do any partial recovery from this situation, it can -only use epoll mechanism to wait for readiness. +only use the epoll mechanism to wait for readiness. 2. In any other case, if an error occurs at any stage of the above process, the processing is interrupted for this very array item only, the socket used for it -is immediately closed, and the processing of the next elements continues. In case -of connection process, it also passes two stages - parameter check and the process -itself. Failure at the parameter check breaks this process, while if this check -passed, this item is considered correctly processed, even if the connection -attempt is going to fail later. If this function is called in the blocking mode, -it then blocks until at least one connection reports success or if all of them -fail. Connections that continue in the background after this function exits can -be then checked status by [`srt_group_data`](#srt_group_data). +is immediately closed, and the processing of the next elements continues. In the case +of a connection process, it also passes two stages - parameter check and the process +itself. Failure at the parameter check breaks this process, while if the check +passes, this item is considered correctly processed, even if the connection +attempt is going to fail later. If this function is called in blocking mode, +it then blocks until at least one connection reports success, or if all of them +fail. The status of connections that continue in the background after this function +exits can then be checked by [`srt_group_data`](#srt_group_data). As member socket connections are running in the background, for determining if a particular connection has succeeded or failed it is recommended @@ -1001,6 +1343,12 @@ define a unique value for the `token`. Your application can also set unique valu in which case the `token` value will be preserved. + + +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) + +--- + ### srt_prepare_endpoint ``` @@ -1008,10 +1356,12 @@ SRT_SOCKGROUPCONFIG srt_prepare_endpoint(const struct sockaddr* src /*nullable*/ const struct sockaddr* adr, int namelen); ``` -This function prepares a default `SRT_SOCKGROUPCONFIG` object as an element -of the array you can prepare for `srt_connect_group` function, filled with +This function prepares a default [`SRT_SOCKGROUPCONFIG`](#SRT_SOCKGROUPCONFIG) object as an element +of the array you can prepare for [`srt_connect_group`](#srt_connect_group) function, filled with additional data: +**Arguments**: + * `src`: address to which the newly created socket should be bound * `adr`: address to which the newly created socket should connect * `namelen`: size of both `src` and `adr` @@ -1023,7 +1373,7 @@ The following fields are set by this function: * `peeraddr`: copied from `adr` * `weight`: 0 * `config`: `NULL` -* `errorcode`: `SRT_SUCCESS` +* [`errorcode`](#error-codes): [`SRT_SUCCESS`](#srt_success) The default empty `srcaddr` is set the following way: @@ -1038,36 +1388,50 @@ The `adr` parameter is obligatory. If `src` parameter is not NULL, then both `adr` and `src` must have the same value of `sa_family`. Note though that this function has no possibility of reporting errors - these -would be reported only by `srt_connect_group`, separately for every individual -connection, and the status can be obtained from `errorcode` field. +would be reported only by [`srt_connect_group`](#srt_connect_group), separately +for every individual connection, and the status can be obtained from +the [`errorcode`](#error-codes) field. +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) + +--- + ### srt_create_config ``` SRT_SOCKOPT_CONFIG* srt_create_config(); ``` -Creates a dynamic object for specifying the socket options. You can -add options to be set on the socket by `srt_config_add` and then -mount this object into the `config` field in `SRT_SOCKGROUPCONFIG` -object for that particular connection. After the object is no -longer needed, you should delete it using `srt_delete_config`. +Creates a dynamic object for specifying the socket options. You can add options +to be set on the socket by [`srt_config_add`](#srt_config_add) and then mount this +object into the `config` field in [`SRT_SOCKGROUPCONFIG`](#SRT_SOCKGROUPCONFIG) +object for that particular connection. After the object is no longer needed, you +should delete it using [`srt_delete_config`](#srt_delete_config). -Returns: +| Returns | | +|:----------------------------- |:------------------------------------------------------------------ | +| Pointer | The pointer to the created object (memory allocation errors apply) | +| | | -* The pointer to the created object (memory allocation errors apply) +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) +--- + ### srt_delete_config ``` void srt_delete_config(SRT_SOCKOPT_CONFIG* c); ``` -Deletes the configurartion object. +Deletes the configuration object. + +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) +--- + ### srt_config_add ``` @@ -1075,41 +1439,59 @@ int srt_config_add(SRT_SOCKOPT_CONFIG* c, SRT_SOCKOPT opt, void* val, int len); ``` Adds a configuration option to the configuration object. -Parameters have meanings similar to `srt_setsockflag`. Note -that not every option is allowed to be set this way. However, -the option (if allowed) isn't checked if it doesn't -violate other preconditions. This will be checked when the -option is being set on the socket, which may fail as a part -of the connection process done by `srt_connect_group`. - -This function should be used when this option must be set -individually on a socket and differently for particular link. -If you need to set some option the same way on every socket, -you should rather set this option on the whole group. + +Parameters have meanings similar to [`srt_setsockflag`](#srt_setsockflag). Note +that not every option is allowed to be set this way. However, the option (if allowed) +isn't checked if it doesn't violate other preconditions. This will be checked when +the option is being set on the socket, which may fail as a part of the connection +process done by [`srt_connect_group`](#srt_connect_group). + +This function should be used when this option must be set individually on a socket +and differently for a particular link. If you need to set some option the same way +on every socket, you should instead set this option on the whole group. The following options are allowed to be set on the member socket: -* `SRTO_SNDBUF`: Allows for larger sender buffer for slower links -* `SRTO_RCVBUF`: Allows for larger receiver buffer for longer recovery -* `SRTO_UDP_RCVBUF`: UDP receiver buffer, if this link has a big flight window -* `SRTO_UDP_SNDBUF`: UDP sender buffer, if this link has a big flight window -* `SRTO_SNDDROPDELAY`: When particular link tends to drop too eagerly -* `SRTO_NAKREPORT`: If you don't want NAKREPORT to work for this link -* `SRTO_CONNTIMEO`: If you want to give more time to connect on this link -* `SRTO_LOSSMAXTTL`: If this link tends to suffer from UDP reordering -* `SRTO_PEERIDLETIMEO`: If you want to be more tolerant for temporary outages -* `SRTO_GROUPSTABTIMEO`: To set ACK jitter tolerance per individual link +* [`SRTO_SNDBUF`](../docs/APISocketOptions.md#SRTO_SNDBUF): Allows for larger sender buffer for slower links +* [`SRTO_RCVBUF`](../docs/APISocketOptions.md#SRTO_RCVBUF): Allows for larger receiver buffer for longer recovery +* [`SRTO_UDP_RCVBUF`](../docs/APISocketOptions.md#SRTO_UDP_RCVBUF): UDP receiver buffer, if this link has a big flight window +* [`SRTO_UDP_SNDBUF`](../docs/APISocketOptions.md#SRTO_UDP_SNDBUF): UDP sender buffer, if this link has a big flight window +* [`SRTO_SNDDROPDELAY`](../docs/APISocketOptions.md#SRTO_SNDDROPDELAY): When particular link tends to drop too eagerly +* [`SRTO_NAKREPORT`](../docs/APISocketOptions.md#SRTO_NAKREPORT): If you don't want NAKREPORT to work for this link +* [`SRTO_CONNTIMEO`](../docs/APISocketOptions.md#SRTO_CONNTIMEO): If you want to give more time to connect on this link +* [`SRTO_LOSSMAXTTL`](../docs/APISocketOptions.md#SRTO_LOSSMAXTTL): If this link tends to suffer from UDP reordering +* [`SRTO_PEERIDLETIMEO`](../docs/APISocketOptions.md#SRTO_PEERIDLETIMEO): If you want to be more tolerant for temporary outages +* [`SRTO_GROUPSTABTIMEO`](../docs/APISocketOptions.md#SRTO_GROUPSTABTIMEO): To set ACK jitter tolerance per individual link + + +| Returns | | +|:----------------------------- |:--------------------------------------------------------- | +| 0 | Success | +| -1 | Failure | +| | | +| Errors | | +|:---------------------------------- |:--------------------------------------------------------------------- | +| [`SRT_EINVPARAM`](#srt_einvparam) | This option is not allowed to be set on a socket being a group member | +| | | -Returns: 0 if succeeded, -1 when failed -Errors: +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) + -* `SRT_EINVPARAM`: this option is not allowed to be set on a socket -being a group member ## Options and properties +* [srt_getpeername](#srt_getpeername) +* [srt_getsockname](#srt_getsockname) +* [srt_getsockopt, srt_getsockflag](#srt_getsockopt-srt_getsockflag) +* [srt_setsockopt, srt_setsockflag](#srt_setsockopt-srt_setsockflag) +* [srt_getversion](#srt_getversion) + + +**NOTE**: For more information, see [Getting and Setting Options](../docs/APISocketOptions.md#getting-and-setting-options) + + ### srt_getpeername ``` int srt_getpeername(SRTSOCKET u, struct sockaddr* name, int* namelen); @@ -1117,72 +1499,95 @@ int srt_getpeername(SRTSOCKET u, struct sockaddr* name, int* namelen); Retrieves the remote address to which the socket is connected. -- Returns: +| Returns | | +|:----------------------------- |:--------------------------------------------------------- | +| `SRT_ERROR` | (-1) in case of error, otherwise 0 | +| | | - * `SRT_ERROR` (-1) in case of error, otherwise 0 +| Errors | | +|:------------------------------- |:------------------------------------------------------------------------ | +| [`SRT_EINVSOCK`](#srt_einvsock) | Socket [`u`](#u) indicates no valid socket ID | +| [`SRT_ENOCONN`](#srt_enoconn) | Socket [`u`](#u) isn't connected, so there's no remote address to return | +| | | -- Errors: - * `SRT_EINVSOCK`: Socket `u` indicates no valid socket ID - * `SRT_ENOCONN`: Socket `u` isn't connected, so there's no remote address to return +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) +--- + ### srt_getsockname ``` int srt_getsockname(SRTSOCKET u, struct sockaddr* name, int* namelen); ``` -Extracts the address to which the socket was bound. Although you should know +Extracts the address to which the socket was bound. Although you should know the address(es) that you have used for binding yourself, this function can be useful for extracting the local outgoing port number when it was specified as 0 with binding for system autoselection. With this function you can extract the port number after it has been autoselected. -- Returns: +| Returns | | +|:----------------------------- |:--------------------------------------------------------- | +| `SRT_ERROR` | (-1) in case of error, otherwise 0 | +| | | - * `SRT_ERROR` (-1) in case of error, otherwise 0 +| Errors | | +|:------------------------------- |:---------------------------------------------- | +| [`SRT_EINVSOCK`](#srt_einvsock) | Socket [`u`](#u) indicates no valid socket ID | +| [`SRT_ENOCONN`](#srt_enoconn) | Socket [`u`](#u) isn't bound, so there's no local address to return
(:warning:   **BUG?** It should rather be [`SRT_EUNBOUNDSOCK`](#srt_eunboundsock)) | +| | | -- Errors: - * `SRT_EINVSOCK`: Socket `u` indicates no valid socket ID - * `SRT_ENOCONN`: Socket `u` isn't bound, so there's no local -address to return (**BUG?** It should rather be `SRT_EUNBOUNDSOCK`) +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) -### srt_getsockopt, srt_getsockflag +--- + +### srt_getsockopt +### srt_getsockflag ``` int srt_getsockopt(SRTSOCKET u, int level /*ignored*/, SRT_SOCKOPT opt, void* optval, int* optlen); int srt_getsockflag(SRTSOCKET u, SRT_SOCKOPT opt, void* optval, int* optlen); ``` -Gets the value of the given socket option (from a socket or a group). The first -version (`srt_getsockopt`) respects the BSD socket API convention, although the -"level" parameter is ignored. The second version (`srt_getsockflag`) omits the -"level" parameter completely. +Gets the value of the given socket option (from a socket or a group). + +The first version ([`srt_getsockopt`](#srt_getsockopt)) respects the BSD socket +API convention, although the "level" parameter is ignored. The second version +([`srt_getsockflag`](#srt_getsockflag)) omits the "level" parameter completely. Options correspond to various data types, so you need to know what data type is assigned to a particular option, and to pass a variable of the appropriate data type. Specifications are provided in the `apps/socketoptions.hpp` file at the `srt_options` object declaration. -- Returns: +| Returns | | +|:----------------------------- |:--------------------------------------------------------- | +| `SRT_ERROR` | (-1) in case of error, otherwise 0 | +| | | - * `SRT_ERROR` (-1) in case of error, otherwise 0 +| Errors | | +|:-------------------------------- |:---------------------------------------------- | +| [`SRT_EINVSOCK`](#srt_einvsock) | Socket [`u`](#u) indicates no valid socket ID | +| [`SRT_EINVOP`](#srt_einvop) | Option `opt` indicates no valid option | +| | | -- Errors: - * `SRT_EINVSOCK`: Socket `u` indicates no valid socket ID - * `SRT_EINVOP`: Option `opt` indicates no valid option +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) -### srt_setsockopt, srt_setsockflag +--- +### srt_setsockopt +### srt_setsockflag ``` int srt_setsockopt(SRTSOCKET u, int level /*ignored*/, SRT_SOCKOPT opt, const void* optval, int optlen); int srt_setsockflag(SRTSOCKET u, SRT_SOCKOPT opt, const void* optval, int optlen); ``` -Sets a value for a socket option in the socket or group. The first version -(`srt_setsockopt`) respects the BSD socket API convention, although the "level" -parameter is ignored. The second version (`srt_setsockflag`) omits the "level" -parameter completely. +Sets a value for a socket option in the socket or group. + +The first version ([`srt_setsockopt`](#srt_setsockopt)) respects the BSD socket +API convention, although the "level" parameter is ignored. The second version +([`srt_setsockflag`](#srt_setsockflag)) omits the "level" parameter completely. Options correspond to various data types, so you need to know what data type is assigned to a particular option, and to pass a variable of the appropriate data @@ -1192,43 +1597,56 @@ Please note that some of the options can only be set on sockets or only on groups, although most of the options can be set on the groups so that they are then derived by the member sockets. -- Returns: +| Returns | | +|:----------------------------- |:----------------------------------------------- | +| `SRT_ERROR` | (-1) in case of error, otherwise 0 | +| | | + +| Errors | | +|:------------------------------- |:--------------------------------------------- | +| [`SRT_EINVSOCK`](#srt_einvsock) | Socket [`u`](#u) indicates no valid socket ID | +| [`SRT_EINVOP`](#srt_einvop) | Option `opt` indicates no valid option | +| | | + +**NOTE*: Various other errors may result from problems when setting a +specific option (see option description for details). - * `SRT_ERROR` (-1) in case of error, otherwise 0 --Errors: - * `SRT_EINVSOCK`: Socket `u` indicates no valid socket ID - * `SRT_EINVOP`: Option `opt` indicates no valid option - * Various other errors that may result from problems when setting a specific - option (see option description for details). +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) +--- + ### srt_getversion ``` uint32_t srt_getversion(); ``` -Get SRT version value. The version format in hex is 0xXXYYZZ for x.y.z in human readable form, -where x = ("%d", (version>>16) & 0xff), etc. +Get SRT version value. The version format in hex is 0xXXYYZZ for x.y.z in human +readable form, where x = ("%d", (version>>16) & 0xff), etc. + +| Returns | | +|:----------------------------- |:--------------------------------------------------------- | +| SRT Version | Unsigned 32-bit integer | +| | | -- Returns: - * srt version as an unsigned 32-bit integer ## Helper data types for transmission + ### SRT_MSGCTRL -The `SRT_MSGCTRL` structure: +The [`SRT_MSGCTRL`](#SRT_MSGCTRL) structure: ```c++ typedef struct SRT_MsgCtrl_ { int flags; // Left for future int msgttl; // TTL for a message, default -1 (no TTL limitation) - int inorder; // Whether a message is allowed to supersede partially lost one. Unused in stream and live mode. + int inorder; // Whether a message is allowed to supersede a partially lost one. Unused in stream and live mode. int boundary; // 0:mid pkt, 1(01b):end of frame, 2(11b):complete frame, 3(10b): start of frame int64_t srctime; // source time (microseconds since SRT internal clock epoch) int32_t pktseq; // sequence number of the first packet in received message (unused for sending) @@ -1238,8 +1656,8 @@ typedef struct SRT_MsgCtrl_ } SRT_MSGCTRL; ``` -The `SRT_MSGCTRL` structure is used in `srt_sendmsg2` and `srt_recvmsg2` calls -and specifies some special extra parameters: +The [`SRT_MSGCTRL`](#SRT_MSGCTRL) structure is used in [`srt_sendmsg2`](#srt_sendmsg) +and [`srt_recvmsg2`](#srt_recvmsg2) calls and specifies some special extra parameters: - `flags`: [IN, OUT]. RESERVED FOR FUTURE USE (should be 0). This is intended to specify some special options controlling the details of how the @@ -1267,10 +1685,10 @@ when you are allowed to send or retrieve a part of the message. - `srctime`: - [OUT] Receiver only. Specifies the time when the packet was intended to be delivered to the receiving application (in microseconds since SRT clock epoch). - - [IN] Sender only. Specifies the application-provided timestamp to be asociated -with the packet. If not provided (specified as 0), the current time of SRT internal clock -is used. - - For details on how to use `srctime` please refer to (Time Access)[#time-access] section. + - [IN] Sender only. Specifies the application-provided timestamp to be associated +with the packet. If not provided (specified as 0), the current time of +SRT internal clock is used. + - For details on how to use `srctime` please refer to the (Time Access)[#time-access] section. - `pktseq`: Receiver only. Reports the sequence number for the packet carrying out the payload being returned. If the payload is carried out by more than one @@ -1281,31 +1699,42 @@ UDP packet, only the sequence of the first one is reported. Note that in although it is required that this value remain monotonic in subsequent send calls. Normally message numbers start with 1 and increase with every message sent. -- 'grpdata' and 'grpdata_size': Pointer and size of the group array. For single +- `grpdata` and `grpdata_size`: Pointer and size of the group array. For single socket connections these values should remain NULL and 0 respectively. When you -call `srt_sendmsg2` or `srt_recvmsg2` function for a group, you should pass an -array here so that you can retrieve the status of particular member sockets. -If you pass an array that is too small, your `grpdata_size` field will be rewritten with -the current number of members, but without filling in the array. For details, -see (Bonding introduction)[bonding-intro.md] and (Socket Groups)[socket-groups.md] -documents. +call [`srt_sendmsg2`](#srt_sendmsg) or [`srt_recvmsg2`](#srt_recvmsg2) function +for a group, you should pass an array here so that you can retrieve the status of +particular member sockets. If you pass an array that is too small, your `grpdata_size` +field will be rewritten with the current number of members, but without filling in +the array. For details, see the (Bonding introduction)[bonding-intro.md] and +(Socket Groups)[socket-groups.md] documents. -**Helpers for `SRT_MSGCTRL`:** +**Helpers for [`SRT_MSGCTRL`](#SRT_MSGCTRL):** ``` void srt_msgctrl_init(SRT_MSGCTRL* mctrl); const SRT_MSGCTRL srt_msgctrl_default; ``` -Helpers for getting an object of `SRT_MSGCTRL` type ready to use. The first is -a function that fills the object with default values. The second is a constant -object and can be used as a source for assignment. Note that you cannot pass -this constant object into any of the API functions because they require it to be -mutable, as they use some fields to output values. +Helpers for getting an object of [`SRT_MSGCTRL`](#SRT_MSGCTRL) type ready to use. +The first is a function that fills the object with default values. The second is +a constant object and can be used as a source for assignment. Note that you cannot +pass this constant object into any of the API functions because they require it +to be mutable, as they use some fields to output values. + + + ## Transmission -### srt_send, srt_sendmsg, srt_sendmsg2 +* [srt_send, srt_sendmsg, srt_sendmsg2](#srt_send-srt_sendmsg-srt_sendmsg2) +* [srt_recv, srt_recvmsg, srt_recvmsg2](#srt_recv-srt_recvmsg-srt_recvmsg2) +* [srt_sendfile, srt_recvfile](#srt_sendfile-srt_recvfile) + + +### srt_send +### srt_sendmsg +### srt_sendmsg2 + ``` int srt_send(SRTSOCKET u, const char* buf, int len); int srt_sendmsg(SRTSOCKET u, const char* buf, int len, int ttl/* = -1*/, int inorder/* = false*/); @@ -1314,7 +1743,10 @@ int srt_sendmsg2(SRTSOCKET u, const char* buf, int len, SRT_MSGCTRL *mctrl); Sends a payload to a remote party over a given socket. -* `u`: Socket used to send. The socket must be connected for this operation. + +**Arguments**: + +* [`u`](#u): Socket used to send. The socket must be connected for this operation. * `buf`: Points to the buffer containing the payload to send. * `len`: Size of the payload specified in `buf`. * `ttl`: Time (in `[ms]`) to wait for a successful delivery. See description of @@ -1338,44 +1770,40 @@ single call to this function determines a message's boundaries. 3. In **live mode**, you are only allowed to send up to the length of `SRTO_PAYLOADSIZE`, which can't be larger than 1456 bytes (1316 default). -- Returns: - - * Size of the data sent, if successful. Note that in **file/stream mode** the -returned size may be less than `len`, which means that it didn't send the -whole contents of the buffer. You would need to call this function again -with the rest of the buffer next time to send it completely. In both -**file/message** and **live mode** the successful return is always equal to `len` - * In case of error, `SRT_ERROR` (-1) - -- Errors: - - * `SRT_ENOCONN`: Socket `u` used when the operation is not connected. - * `SRT_ECONNLOST`: Socket `u` used for the operation has lost its connection. - * `SRT_EINVALMSGAPI`: Incorrect API usage in **message mode**: - * **live mode**: trying to send more bytes at once than `SRTO_PAYLOADSIZE` - or wrong source time was provided. - * `SRT_EINVALBUFFERAPI`: Incorrect API usage in **stream mode**: - * Reserved for future use. The congestion controller object - used for this mode doesn't use any restrictions on this call for now, - but this may change in future. - * `SRT_ELARGEMSG`: Message to be sent can't fit in the sending buffer (that is, -it exceeds the current total space in the sending buffer in bytes). This means -that the sender buffer is too small, or the application is trying to send -a larger message than initially predicted. - * `SRT_EASYNCSND`: There's no free space currently in the buffer to schedule -the payload. This is only reported in non-blocking mode (`SRTO_SNDSYN` set -to false); in blocking mode the call is blocked until enough free space in -the sending buffer becomes available. - * `SRT_ETIMEOUT`: The condition described above still persists and the timeout -has passed. This is only reported in blocking mode when `SRTO_SNDTIMEO` is -set to a value other than -1. - * `SRT_EPEERERR`: This is reported only in the case where, as a stream is being - received by a peer, the `srt_recvfile` function encounters an error during a - write operation on a file. This is reported by a `UMSG_PEERERROR` message from - the peer, and the agent sets the appropriate flag internally. This flag - persists up to the moment when the connection is broken or closed. - -### srt_recv, srt_recvmsg, srt_recvmsg2 +| Returns | | +|:----------------------------- |:--------------------------------------------------------- | +| Size | Size of the data sent, if successful | +| `SRT_ERROR` | In case of error (-1) | +| | | + +**NOTE**: Note that in **file/stream mode** the returned size may be less than `len`, +which means that it didn't send the whole contents of the buffer. You would need to +call this function again with the rest of the buffer next time to send it completely. +In both **file/message** and **live mode** the successful return is always equal to `len`. + +| Errors | | +|:--------------------------------------------- |:------------------------------------------------------------------------------------------------------------------- | +| [`SRT_ENOCONN`](#srt_enoconn) | Socket [`u`](#u) used when the operation is not connected. | +| [`SRT_ECONNLOST`](#srt_econnlost) | Socket [`u`](#u) used for the operation has lost its connection. | +| [`SRT_EINVALMSGAPI`](#srt_einvalmsgapi) | Incorrect API usage in **message mode**:
**live mode**: trying to send more bytes at once than `SRTO_PAYLOADSIZE` or wrong source time
was provided. | +| [`SRT_EINVALBUFFERAPI`](#srt_einvalbufferapi) | Incorrect API usage in **stream mode** (reserved for future use):
The congestion controller object used for this mode doesn't use any restrictions on this call,
but this may change. | +| [`SRT_ELARGEMSG`](#srt_elargemsg) | Message to be sent can't fit in the sending buffer (that is, it exceeds the current total space in the
sending buffer in bytes). This means that the sender buffer is too small, or the application is
trying to send a larger message than initially predicted. | +| [`SRT_EASYNCSND`](#srt_easyncsnd) | There's no free space currently in the buffer to schedule the payload. This is only reported in
non-blocking mode ([`SRTO_SNDSYN`](../docs/APISocketOptions.md#SRTO_SNDSYN) set to false); in blocking mode the call is blocked until
enough free space in the sending buffer becomes available. | +| [`SRT_ETIMEOUT`](#srt_etimeout) | The condition described above still persists and the timeout has passed. This is only reported in
blocking mode when [`SRTO_SNDTIMEO`](../docs/APISocketOptions.md#SRTO_SNDTIMEO) is set to a value other than -1. | +| [`SRT_EPEERERR`](#srt_epeererr) | This is reported only in the case where, as a stream is being received by a peer, the
[`srt_recvfile`](#srt_recvfile) function encounters an error during a write operation on a file. This is reported by
a `UMSG_PEERERROR` message from the peer, and the agent sets the appropriate flag internally.
This flag persists up to the moment when the connection is broken or closed. | +| | | + + + + +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) + +--- + +### srt_recv +### srt_recvmsg +### srt_recvmsg2 + ``` int srt_recv(SRTSOCKET u, char* buf, int len); @@ -1383,17 +1811,20 @@ int srt_recvmsg(SRTSOCKET u, char* buf, int len); int srt_recvmsg2(SRTSOCKET u, char *buf, int len, SRT_MSGCTRL *mctrl); ``` -Extracts the payload waiting to be received. Note that `srt_recv` and `srt_recvmsg` -are identical functions, two different names being kept for historical reasons. -In the UDT predecessor the application was required to use either the `UDT::recv` -version for **stream mode** and `UDT::recvmsg` for **message mode**. In SRT this -distinction is resolved internally by the `SRTO_MESSAGEAPI` flag. +Extracts the payload waiting to be received. Note that [`srt_recv`](#srt_recv) and +[`srt_recvmsg`](#srt_recvmsg) are identical functions, two different names being +kept for historical reasons. In the UDT predecessor the application was required +to use either the `UDT::recv` version for **stream mode** and `UDT::recvmsg` for +**message mode**. In SRT this distinction is resolved internally by the +[`SRTO_MESSAGEAPI`](../docs/APISocketOptions.md#SRTO_MESSAGEAPI) flag. -* `u`: Socket used to send. The socket must be connected for this operation. -* `buf`: Points to the buffer to which the payload is copied -* `len`: Size of the payload specified in `buf` +**Arguments**: + +* [`u`](#u): Socket used to send. The socket must be connected for this operation. +* `buf`: Points to the buffer to which the payload is copied. +* `len`: Size of the payload specified in `buf`. * `mctrl`: An object of [`SRT_MSGCTRL`](#SRT_MSGCTRL) type that contains extra -parameters +parameters. The way this function works is determined by the mode set in options, and it has specific requirements: @@ -1405,54 +1836,44 @@ data that is available but not extracted this time will be available next time. 2. In **file/message mode**, exactly one message is retrieved, with the boundaries defined at the moment of sending. If some parts of the messages are already retrieved, but not the whole message, nothing will be received (the -function blocks or returns `SRT_EASYNCRCV`). If the message to be returned does -not fit in the buffer, nothing will be received and the error is reported. - -3. In **live mode**, the function behaves as in **file/message mode**, although -the number of bytes retrieved will be at most the size of `SRTO_PAYLOADSIZE`. In -this mode, however, with default settings of `SRTO_TSBPDMODE` and `SRTO_TLPKTDROP`, -the message will be received only when its time to play has come, and until then -it will be kept in the receiver buffer; also, when the time to play has come -for a message that is next to the currently lost one, it will be delivered -and the lost one dropped. - -- Returns: - - * Size (\>0) of the data received, if successful. - * 0, if the connection has been closed - * `SRT_ERROR` (-1) when an error occurs - -- Errors: - - * `SRT_ENOCONN`: Socket `u` used for the operation is not connected. - * `SRT_ECONNLOST`: Socket `u` used for the operation has lost connection -(this is reported only if the connection was unexpectedly broken, not -when it was closed by the foreign host). - * `SRT_EINVALMSGAPI`: Incorrect API usage in **message mode**: - * **live mode**: size of the buffer is less than `SRTO_PAYLOADSIZE` - * `SRT_EINVALBUFFERAPI`: Incorrect API usage in **stream mode**: - * Currently not in use. File congestion control used for **stream mode** - does not restrict the parameters. **???** - * `SRT_ELARGEMSG`: Message to be sent can't fit in the sending buffer (that is, -it exceeds the current total space in the sending buffer in bytes). This means -that the sender buffer is too small, or the application is trying to send -a larger message than initially intended. - * `SRT_EASYNCRCV`: There are no data currently waiting for delivery. This -happens only in non-blocking mode (when `SRTO_RCVSYN` is set to false). In -blocking mode the call is blocked until the data are ready. How this is defined, -depends on the mode: - * In **live mode** (with `SRTO_TSBPDMODE` on), at least one packet must - be present in the receiver buffer and its time to play be in the past - * In **file/message mode**, one full message must be available, - * the next one waiting if there are no messages with `inorder` = false, or - possibly the first message ready with `inorder` = false - * In **file/stream mode**, it is expected to have at least one byte of data - still not extracted - * `SRT_ETIMEOUT`: The readiness condition described above is still not achieved -and the timeout has passed. This is only reported in blocking mode when -`SRTO_RCVTIMEO` is set to a value other than -1. - -### srt_sendfile, srt_recvfile +function blocks or returns [`SRT_EASYNCRCV`](#srt_easyncrcv)). If the message +to be returned does not fit in the buffer, nothing will be received and +the error is reported. + +3. In **live mode**, the function behaves as in **file/message mode**, although the +number of bytes retrieved will be at most the size of `SRTO_PAYLOADSIZE`. In this mode, +however, with default settings of [`SRTO_TSBPDMODE`](../docs/APISocketOptions.md#SRTO_TSBPDMODE) +and [`SRTO_TLPKTDROP`](../docs/APISocketOptions.md#SRTO_TLPKTDROP), the message will be +received only when its time to play has come, and until then it will be kept in the +receiver buffer. Also, when the time to play has come for a message that is next to +the currently lost one, it will be delivered and the lost one dropped. + +| Returns | | +|:----------------------------- |:--------------------------------------------------------- | +| Size | Size (\>0) of the data received, if successful. | +| 0 | If the connection has been closed | +| `SRT_ERROR` | (-1) when an error occurs | +| | | + +| Errors | | +|:--------------------------------------------- |:--------------------------------------------------------- | +| [`SRT_ENOCONN`](#srt_enoconn) | Socket [`u`](#u) used for the operation is not connected. | +| [`SRT_ECONNLOST`](#srt_econnlost) | Socket [`u`](#u) used for the operation has lost connection (this is reported only if the connection
was unexpectedly broken, not when it was closed by the foreign host). | +| [`SRT_EINVALMSGAPI`](#srt_einvalmsgapi) | Incorrect API usage in **message mode**:
-- **live mode**: size of the buffer is less than [`SRTO_PAYLOADSIZE`](../docs/APISocketOptions.md#SRTO_PAYLOADSIZE) | +| [`SRT_EINVALBUFFERAPI`](#srt_einvalbufferapi) | Incorrect API usage in **stream mode**:
• Currently not in use. File congestion control used for **stream mode** does not restrict
the parameters. :warning:   **???** | +| [`SRT_ELARGEMSG`](#srt_elargemsg) | Message to be sent can't fit in the sending buffer (that is, it exceeds the current total space in
the sending buffer in bytes). This means that the sender buffer is too small, or the application
is trying to send a larger message than initially intended. | +| [`SRT_EASYNCRCV`](#srt_easyncrcv) | There are no data currently waiting for delivery. This happens only in non-blocking mode
(when [`SRTO_RCVSYN`](../docs/APISocketOptions.md#SRTO_RCVSYN) is set to false). In blocking mode the call is blocked until the data are ready.
How this is defined, depends on the mode:
• In **live mode** (with [`SRTO_TSBPDMODE`](../docs/APISocketOptions.md#SRTO_TSBPDMODE) on), at least one packet must be present in the receiver
buffer and its time to play be in the past
• In **file/message mode**, one full message must be available, the next one waiting if there are no
messages with `inorder` = false, or possibly the first message ready with `inorder` = false
• In **file/stream mode**, it is expected to have at least one byte of data still not extracted | +| [`SRT_ETIMEOUT`](#srt_etimeout) | The readiness condition described above is still not achieved and the timeout has passed.
This is only reported in blocking mode when[`SRTO_RCVTIMEO`](../docs/APISocketOptions.md#SRTO_RCVTIMEO) is set to a value other than -1. | +| | | + + + +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) + +--- + +### srt_sendfile +### srt_recvfile ``` int64_t srt_sendfile(SRTSOCKET u, const char* path, int64_t* offset, int64_t size, int block); @@ -1461,12 +1882,14 @@ int64_t srt_recvfile(SRTSOCKET u, const char* path, int64_t* offset, int64_t siz These are functions dedicated to sending and receiving a file. You need to call this function just once for the whole file, although you need to know the size of -the file prior to sending and also define the size of a single block that should +the file prior to sending, and also define the size of a single block that should be internally retrieved and written into a file in a single step. This influences only the performance of the internal operations; from the application perspective you just have one call that exits only when the transmission is complete. -* `u`: Socket used for transmission. The socket must be connected. +**Arguments**: + +* [`u`](#u): Socket used for transmission. The socket must be connected. * `path`: Path to the file that should be read or written. * `offset`: Needed to pass or retrieve the offset used to read or write to a file * `size`: Size of transfer (file size, if offset is at 0) @@ -1479,1071 +1902,1329 @@ The following values are recommended for the `block` parameter: #define SRT_DEFAULT_RECVFILE_BLOCK 7280000 ``` -You need to pass them to the `srt_sendfile` or `srt_recvfile` function if you -don't know what value to chose. +You need to pass them to the [`srt_sendfile`](#srt_sendfile) or +[`srt_recvfile`](#srt_recvfile) function if you don't know what value to chose. -- Returns: +| Returns | | +|:----------------------------- |:--------------------------------------------------------- | +| Size | The size (\>0) of the transmitted data of a file. It may be less than `size`, if the size was greater
than the free space in the buffer, in which case you have to send rest of the file next time. | +| -1 | in case of error | +| | | - * Size (\>0) of the transmitted data of a file. It may be less than `size`, if - the size was greater than the free space in the buffer, in which case you have - to send rest of the file next time. - * -1 in case of error. +| Errors | | +|:--------------------------------------------- |:----------------------------------------------------------------------------- | +| [`SRT_ENOCONN`](#srt_enoconn) | Socket [`u`](#u) used for the operation is not connected. | +| [`SRT_ECONNLOST`](#srt_econnlost) | Socket [`u`](#u) used for the operation has lost its connection. | +| [`SRT_EINVALBUFFERAPI`](#srt_einvalbufferapi) | When socket has [`SRTO_MESSAGEAPI`](../docs/APISocketOptions.md#SRTO_MESSAGEAPI) = true or [`SRTO_TSBPDMODE`](../docs/APISocketOptions.md#SRTO_TSBPDMODE) = true.
(:warning:   **BUG?**: Looxlike MESSAGEAPI isn't checked) | +| [`SRT_EINVRDOFF`](#srt_einvrdoff) | There is a mistake in `offset` or `size` parameters, which should match the index availability
and size of the bytes available since `offset` index. This is actually reported for [`srt_sendfile`](#srt_sendfile)
when the `seekg` or `tellg` operations resulted in error. | +| [`SRT_EINVWROFF`](#srt_einvwroff) | Like above, reported for [`srt_recvfile`](#srt_recvfile) and `seekp`/`tellp`. | +| [`SRT_ERDPERM`](#srt_erdperm) | The read from file operation has failed ([`srt_sendfile`](#srt_sendfile)). | +| [`SRT_EWRPERM`](#srt_ewrperm) | The write to file operation has failed ([`srt_recvfile`](#srt_recvfile)). | +| | | -- Errors: - * `SRT_ENOCONN`: Socket `u` used for the operation is not connected. - * `SRT_ECONNLOST`: Socket `u` used for the operation has lost its connection. - * `SRT_EINVALBUFFERAPI`: When socket has `SRTO_MESSAGEAPI` = true or - `SRTO_TSBPDMODE` = true. -(**BUG?**: Looxlike MESSAGEAPI isn't checked) - * `SRT_EINVRDOFF`: There is a mistake in `offset` or `size` parameters, which - should match the index availability and size of the bytes available since - `offset` index. This is actually reported for `srt_sendfile` when the `seekg` - or `tellg` operations resulted in error. - * `SRT_EINVWROFF`: Like above, reported for `srt_recvfile` and `seekp`/`tellp`. - * `SRT_ERDPERM`: The read from file operation has failed (`srt_sendfile`). - * `SRT_EWRPERM`: The write to file operation has failed (`srt_recvfile`). -## Diagnostics +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) -General notes concerning the "getlasterror" diagnostic functions: when an API -function ends up with error, this error information is stored in a thread-local -storage. This means that you'll get the error of the operation that was last -performed as long as you call this diagnostic function just after the failed -function has returned. In any other situation the information provided by the -diagnostic function is undefined. -### srt_getlasterror -``` -int srt_getlasterror(int* errno_loc); -``` +## Performance tracking -Get the numeric code of the last error. Additionally, in the variable passed as -`errno_loc` the system error value is returned, or 0 if there was no system error -associated with the last error. The system error is: +**Sequence Numbers** +The sequence numbers used in SRT are 32-bit "circular numbers" with the most significant +bit not included. For example 0x7FFFFFFF shifted forward by 3 becomes 2. As far as +any comparison is concerned, it can be thought of as a "distance" which is an integer +value expressing an offset to be added to one sequence number in order to get the +second one. This distance is only valid as long as the threshold value isn't exceeded, +so it's understood that all sequence numbers that are anywhere taken into account are +systematically updated and kept in the range between 0 and half of the maximum 0x7FFFFFFF. +Hence, the distance counting procedure always assumes that the sequence number are in +the required range already, so for a numbers like 0x7FFFFFF0 and 0x10, for which the +"numeric difference" would be 0x7FFFFFE0, the "distance" is 0x20. - * On POSIX systems, the value from `errno` - * On Windows, the result from `GetLastError()` call +* [srt_bstats, srt_bistats](#srt_bstats-srt_bistats) -### srt_strerror + +### srt_bstats +### srt_bistats ``` -const char* srt_strerror(int code, int errnoval); +// Performance monitor with Byte counters for better bitrate estimation. +int srt_bstats(SRTSOCKET u, SRT_TRACEBSTATS * perf, int clear); + +// Performance monitor with Byte counters and instantaneous stats instead of moving averages for Snd/Rcvbuffer sizes. +int srt_bistats(SRTSOCKET u, SRT_TRACEBSTATS * perf, int clear, int instantaneous); ``` -Returns a string message that represents a given SRT error code and possibly the -`errno` value, if not 0. +Reports the current statistics -**NOTE:** *This function isn't thread safe. It uses a static variable to hold the -error description. There's no problem with using it in a multithreaded environment, -as long as only one thread in the whole application calls this function at the -moment* +**Arguments**: -### srt_getlasterror_str -``` -const char* srt_getlasterror_str(void); -``` +* [`u`](#u): Socket from which to get statistics +* `perf`: Pointer to an object to be written with the statistics +* `clear`: 1 if the statistics should be cleared after retrieval +* `instantaneous`: 1 if the statistics should use instant data, not moving averages -Get the text message for the last error. It's a shortcut to calling first -`srt_getlasterror` and then passing the returned value into `srt_strerror`. -Note that, in contradiction to `srt_strerror`, this function is thread safe. +`SRT_TRACEBSTATS` is an alias to `struct CBytePerfMon`. For a complete description +of the fields please refer to the document [statistics.md](statistics.md). -### srt_clearlasterror -``` -void srt_clearlasterror(void); -``` +## Asynchronous operations (epoll) -This function clears the last error. After this call, the `srt_getlasterror` will -report a "successful" code. +* [srt_epoll_create](#srt_epoll_create) +* [srt_epoll_add_usock, srt_epoll_add_ssock, srt_epoll_update_usock, srt_epoll_update_ssock](#srt_epoll_add_usock-srt_epoll_add_ssock-srt_epoll_update_usock-srt_epoll_update_ssock) +* [srt_epoll_remove_usock, srt_epoll_remove_ssock](#srt_epoll_remove_usock-srt_epoll_remove_ssock) +* [srt_epoll_wait](#srt_epoll_wait) +* [srt_epoll_uwait](#srt_epoll_uwait) +* [srt_epoll_clear_usocks](#srt_epoll_clear_usocks) +* [srt_epoll_set](#srt_epoll_set) +* [srt_epoll_release](#srt_epoll_release) -### srt_getrejectreason +The epoll system is currently the only method for using multiple sockets in one +thread with having the blocking operation moved to epoll waiting so that it can +block on multiple sockets at once. That is, instead of blocking a single reading +or writing operation, as it's in blocking mode, it blocks until at least one of +the sockets subscribed for a single waiting call in given operation mode is ready +to do this operation without blocking. It's usually combined with setting the +nonblocking mode on a socket. In SRT this is set separately for reading and +writing ([`SRTO_RCVSYN`](../docs/APISocketOptions.md#SRTO_RCVSYN) and +[`SRTO_SNDSYN`](../docs/APISocketOptions.md#SRTO_SNDSYN) respectively). This is +to ensure that if there is internal error in the application (or even possibly +a bug in SRT that has reported a spurious readiness report) the operation will end +up with an error rather than cause blocking, which would be more dangerous for the +application ([`SRT_EASYNCRCV`](#srt_easyncrcv) and [`SRT_EASYNCSND`](#srt_easyncsnd) +respectively). + +The epoll system, similar to the one on Linux, relies on [`eid`](#eid) objects +managed internally in SRT, which can be subscribed to particular sockets and the +readiness status of particular operations. The [`srt_epoll_wait`](#srt_epoll_wait) +function can then be used to block until any readiness status in the whole +[`eid`](#eid) is set. + +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) + + +### srt_epoll_create ``` -int srt_getrejectreason(SRTSOCKET sock); +int srt_epoll_create(void); ``` -This function provides a more detailed reason for the failed connection attempt. -It shall be called after a connecting function (such as `srt_connect`) -has returned an error, the code for which is `SRT_ECONNREJ`. If `SRTO_RCVSYN` -has been set on the socket used for the connection, the function should also be -called when the `SRT_EPOLL_ERR` event is set for this socket. It returns a -numeric code, which can be translated into a message by `srt_rejectreason_str`. -The following codes are currently reported: -#### SRT_REJ_UNKNOWN +Creates a new epoll container. -A fallback value for cases when there was no connection rejected. +| Returns | | +|:----------------------------- |:--------------------------------------------------------- | +| valid EID | Success | +| -1 | Failure | +| | | -#### SRT_REJ_SYSTEM +| Errors | | +|:----------------------------------- |:--------------------------------------------------------------------- | +| [`SRT_ECONNSETUP`](#srt_econnsetup) | System operation failed or not enough space to create a new epoll. System error might happen on
systems that use a special method for the system part of epoll (`epoll_create()`, `kqueue()`),
and therefore associated resources, like epoll on Linux. | +| | | -One of system function reported a failure. Usually this means some system -error or lack of system resources to complete the task. -#### SRT_REJ_PEER +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) -The connection has been rejected by peer, but no further details are available. -This usually means that the peer doesn't support rejection reason reporting. +--- + +### srt_epoll_add_usock +### srt_epoll_add_ssock +### srt_epoll_update_usock +### srt_epoll_update_ssock -#### SRT_REJ_RESOURCE +``` +int srt_epoll_add_usock(int eid, SRTSOCKET u, const int* events); +int srt_epoll_add_ssock(int eid, SYSSOCKET s, const int* events); +int srt_epoll_update_usock(int eid, SRTSOCKET u, const int* events); +int srt_epoll_update_ssock(int eid, SYSSOCKET s, const int* events); +``` -A problem with resource allocation (usually memory). +Adds a socket to a container, or updates an existing socket subscription. -#### SRT_REJ_ROGUE +The `_usock` suffix refers to a user socket (SRT socket). +The `_ssock` suffix refers to a system socket. -The data sent by one party to another cannot be properly interpreted. This -should not happen during normal usage, unless it's a bug, or some weird -events are happening on the network. +The `_add_` functions add new sockets. The `_update_` functions act on a socket that +is in the container already and just allow changes in the subscription details. For +example, if you have already subscribed a socket with [`SRT_EPOLL_OUT`](#SRT_EPOLL_OUT) +to wait until it's connected, to change it into poll for read-readiness, you use this +function on that same socket with a variable set to [`SRT_EPOLL_IN`](#SRT_EPOLL_IN). +This will not only change the event type which is polled on the socket, but also +remove any readiness status for flags that are no longer set. It is discouraged +to perform socket removal and adding back (instead of using `_update_`) because +this way you may miss an event that could happen in the brief moment between +these two calls. -#### SRT_REJ_BACKLOG +**Arguments**: -The listener's backlog has exceeded (there are many other callers waiting for -the opportunity of being connected and wait in the queue, which has reached -its limit). +* `eid`: epoll container id +* `u`: SRT socket +* `s`(#s): system socket +* `events`: points to + * a variable set to epoll flags (see below) to use only selected events + * NULL if you want to subscribe a socket for all events in level-triggered mode -#### SRT_REJ_IPE +Possible epoll flags are the following: -Internal Program Error. This should not happen during normal usage and it -usually means a bug in the software (although this can be reported by both -local and foreign host). + * `SRT_EPOLL_IN`: report readiness for reading or incoming connection on a listener socket + * `SRT_EPOLL_OUT`: report readiness for writing or a successful connection + * `SRT_EPOLL_ERR`: report errors on the socket + * `SRT_EPOLL_UPDATE`: an important event has happened that requires attention + * `SRT_EPOLL_ET`: the event will be edge-triggered -#### SRT_REJ_CLOSE +All flags except [`SRT_EPOLL_ET`](#SRT_EPOLL_ET) are event type flags (important for functions +that expect only event types and not other flags). -The listener socket was able to receive your request, but at this moment it -is being closed. It's likely that your next attempt will result with timeout. +The [`SRT_EPOLL_IN`](#SRT_EPOLL_IN), [`SRT_EPOLL_OUT`](#SRT_EPOLL_OUT) and +[`SRT_EPOLL_ERR`](#SRT_EPOLL_ERR) events are by default **level-triggered**. +With [`SRT_EPOLL_ET`](#SRT_EPOLL_ET) flag they become **edge-triggered**. -#### SRT_REJ_VERSION +The [`SRT_EPOLL_UPDATE`](#SRT_EPOLL_UPDATE) flag is always edge-triggered. It +designates a special event that happens on a group, or on a listener socket that +has the [`SRTO_GROUPCONNECT`](../docs/APISocketOptions.md#SRTO_GROUPCONNECT) flag +set to allow group connections. This flag is triggered in the following situations: -Any party of the connection has set up minimum version that is required for -that connection, and the other party didn't satisfy this requirement. +* for group connections, when a new link has been established for a group that +is already connected (that is, has at least one connection established), +[`SRT_EPOLL_UPDATE`](#SRT_EPOLL_UPDATE) is reported for the listener socket +accepting the connection. This is intended for internal use only. An initial +connection results in reporting the group connection on that listener. But +when the group is already connected, [`SRT_EPOLL_UPDATE`](#SRT_EPOLL_UPDATE) +is reported instead. -#### SRT_REJ_RDVCOOKIE +* when one of a group's member connection has been broken -Rendezvous cookie collision. This normally should never happen, or the -probability that this will really happen is negligible. However this can -be also a result of a misconfiguration that you are trying to make a -rendezvous connection where both parties try to bind to the same IP -address, or both are local addresses of the same host - in which case -the sent handshake packets are returning to the same host as if they -were sent by the peer, who is this party itself. When this happens, -this reject reason will be reported by every attempt. +Note that at this time the edge-triggered mode is supported only for SRT +sockets, not for system sockets. -#### SRT_REJ_BADSECRET +In the **edge-triggered** mode the function will only return socket states that +have changed since the last call of the waiting function. All events reported +in a particular call of the waiting function will be cleared in the internal +flags and will not be reported until the internal signalling logic clears this +state and raises it again. -Both parties have defined a passprhase for connection and they differ. +In the **level-triggered** mode the function will always return the readiness +state as long as it lasts, until the internal signalling logic clears it. -#### SRT_REJ_UNSECURE +Note that when you use [`SRT_EPOLL_ET`](#SRT_EPOLL_ET) flag in one subscription +call, it defines edge-triggered mode for all events passed together with it. +However, if you want to have some events reported as edge-triggered and others +as level-triggered, you can do two separate subscriptions for the same socket. -Only one connection party has set up a password. See also -`SRTO_ENFORCEDENCRYPTION` flag in API.md. +**IMPORTANT**: The [`srt_epoll_wait`](#srt_epoll_wait) function does not report +[`SRT_EPOLL_UPDATE`](#SRT_EPOLL_UPDATE) events. If you need the ability to get +any possible flag, you must use [`srt_epoll_wait`](#srt_epoll_wait). Note that +this function doesn't work with system file descriptors. -#### SRT_REJ_MESSAGEAPI +| Returns | | +|:----------------------------- |:--------------------------------------------------------- | +| 0 | Success | +| -1 | Failure | +| | | -The value for `SRTO_MESSAGEAPI` flag is different on both connection -parties. +| Errors | | +|:----------------------------------- |:----------------------------------------------------------------- | +| [`SRT_EINVPOLLID`](#srt_einvpollid) | [`eid`](#eid) parameter doesn't refer to a valid epoll container | +| | | -#### SRT_REJ_CONGESTION +:warning:   **BUG?**: for `add_ssock` the system error results in an empty `CUDTException()` +call which actually results in [`SRT_SUCCESS`](#srt_success). For cases like that +the [`SRT_ECONNSETUP`](#srt_econnsetup) code is predicted. -The `SRTO_CONGESTION` option has been set up differently on both -connection parties. -#### SRT_REJ_FILTER +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) -The `SRTO_PACKETFILTER` option has been set differently on both connection -parties. +--- + +### srt_epoll_remove_usock +### srt_epoll_remove_ssock -#### SRT_REJ_GROUP +``` +int srt_epoll_remove_usock(int eid, SRTSOCKET u); +int srt_epoll_remove_ssock(int eid, SYSSOCKET s); +``` -The group type or some group settings are incompatible for both connection parties. -While every connection within a bonding group may have different target addresses, -they should all designate the same endpoint and the same SRT application. If this -condition isn't satisfied, then the peer will respond with a different peer group -ID for the connection that is trying to contact a machine/application that is -completely different from the existing connections in the bonding group. +Removes a specified socket from an epoll container and clears all readiness +states recorded for that socket. -#### SRT_REJ_TIMEOUT +The `_usock` suffix refers to a user socket (SRT socket). +The `_ssock` suffix refers to a system socket. -The connection wasn't rejected, but it timed out. This code is always set on -connection timeout, but this is the only way to get this state in non-blocking -mode (see `SRTO_RCVSYN`). +| Returns | | +|:----------------------------- |:--------------------------------------------------------- | +| 0 | Success | +| -1 | Failure | +| | | -There may also be server and user rejection codes, -as defined by the `SRT_REJC_INTERNAL`, `SRT_REJC_PREDEFINED` and `SRT_REJC_USERDEFINED` -constants. Note that the number space from the value of `SRT_REJC_PREDEFINED` -and above is reserved for "predefined codes" (`SRT_REJC_PREDEFINED` value plus -adopted HTTP codes). Values above `SRT_REJC_USERDEFINED` are freely defined by -the application. +| Errors | | +|:----------------------------------- |:----------------------------------------------------------------- | +| [`SRT_EINVPOLLID`](#srt_einvpollid) | [`eid`](#eid) parameter doesn't refer to a valid epoll container | +| | | -### srt_rejectreason_str +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) + +--- + +### srt_epoll_wait ``` -const char* srt_rejectreason_str(enum SRT_REJECT_REASON id); +int srt_epoll_wait(int eid, SRTSOCKET* readfds, int* rnum, SRTSOCKET* writefds, int* wnum, int64_t msTimeOut, + SYSSOCKET* lrfds, int* lrnum, SYSSOCKET* lwfds, int* lwnum); ``` -Returns a constant string for the reason of the connection rejected, -as per given code ID. It provides a system-defined message for -values below `SRT_REJ_E_SIZE`. For other values below -`SRT_REJC_PREDEFINED` it returns the string for `SRT_REJ_UNKNOWN`. -For values since `SRT_REJC_PREDEFINED` on, returns -"Application-defined rejection reason". +Blocks the call until any readiness state occurs in the epoll container. -The actual messages assigned to the internal rejection codes, that is, -less than `SRT_REJ_E_SIZE`, can be also obtained from `srt_rejectreason_msg` -array. +Readiness can be on a socket in the container for the event type as per +subscription. Note that in the case when a particular event was subscribed with +[`SRT_EPOLL_ET`](#SRT_EPOLL_ET) flag, this event, once reported in this function, +will be cleared internally. -### srt_setrejectreason +The first readiness state causes this function to exit, but all ready sockets +are reported. This function blocks until the timeout specified in the `msTimeOut` +parameter. If timeout is 0, it exits immediately after checking. If timeout is +-1, it blocks indefinitely until a readiness state occurs. + +**Arguments**: + +* `eid`: epoll container +* `readfds` and `rnum`: A pointer and length of an array to write SRT sockets that are read-ready +* `writefds` and `wnum`: A pointer and length of an array to write SRT sockets that are write-ready +* `msTimeOut`: Timeout specified in milliseconds, or special values (0 or -1) +* `lwfds` and `lwnum`: A pointer and length of an array to write system sockets that are read-ready +* `lwfds` and `lwnum`: A pointer and length of an array to write system sockets that are write-ready +Note that the following flags are reported: + +* [`SRT_EPOLL_IN`](#SRT_EPOLL_IN) as read-ready (also a listener socket ready to accept) +* [`SRT_EPOLL_OUT`](#SRT_EPOLL_OUT) as write-ready (also a connected socket) +* [`SRT_EPOLL_ERR`](#SRT_EPOLL_ERR) as both read-ready and write-ready +* [`SRT_EPOLL_UPDATE`](#SRT_EPOLL_UPDATE) is not reported + +There is no space here to report sockets for which it's already known that the operation +will end up with error (although such a state is known internally). If an error occurred +on a socket then that socket is reported in both read-ready and write-ready arrays, +regardless of what event types it was subscribed for. Usually then you subscribe the +given socket for only read readiness, for example ([`SRT_EPOLL_IN`](#SRT_EPOLL_IN)), +but pass both arrays for read and write readiness.This socket will not be reported +in the write readiness array even if it's write ready (because this isn't what it +was subscribed for), but it will be reported there, if the next operation on this +socket is about to be erroneous. On such sockets you can still perform an operation, +just you should expect that it will always report an error. On the other hand that's +the only way to know what kind of error has occurred on the socket. + +| Returns | | +|:----------------------------- |:------------------------------------------------------------ | +| Number | The number (\>0) of ready sockets, of whatever kind (if any) | +| -1 | Error | +| | | + +| Errors | | +|:----------------------------------- |:------------------------------------------------------------------- | +| [`SRT_EINVPOLLID`](#srt_einvpollid) | [`eid`](#eid) parameter doesn't refer to a valid epoll container | +| [`SRT_ETIMEOUT`](#srt_etimeout) | Up to `msTimeOut` no sockets subscribed in [`eid`](#eid) were ready. This is reported only if `msTimeOut`
was \>=0, otherwise the function waits indefinitely. | +| | | + + + +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) + +--- + +### srt_epoll_uwait ``` -int srt_setrejectreason(SRTSOCKET sock, int value); +int srt_epoll_uwait(int eid, SRT_EPOLL_EVENT* fdsSet, int fdsSize, int64_t msTimeOut); ``` -Sets the rejection code on the socket. This call is only useful in the -listener callback. The code from `value` set this way will be set as a -rejection reason for the socket. After the callback rejects -the connection, the code will be passed back to the caller peer with the -handshake response. +This function blocks a call until any readiness state occurs in the epoll container. +Unlike [`srt_epoll_wait`](#srt_epoll_wait), it can only be used with [`eid`](#eid) +subscribed to user sockets (SRT sockets), not system sockets. -Note that allowed values for this function begin with `SRT_REJC_PREDEFINED` -(that is, you cannot set a system rejection code). -For example, your application can inform the calling side that the resource -specified under the `r` key in the StreamID string (see `SRTO_STREAMID`) -is not availble - it then sets the value to `SRT_REJC_PREDEFINED + 404`. +This function blocks until the timeout specified in `msTimeOut` parameter. If +timeout is 0, it exits immediately after checking. If timeout is -1, it blocks +indefinitely until a readiness state occurs. -- Returns: - * 0 in case of success. - * -1 in case of error. +**Arguments**: -- Errors: +* `eid`: epoll container +* `fdsSet` : A pointer to an array of `SRT_EPOLL_EVENT` +* `fdsSize` : The size of the fdsSet array +* `msTimeOut` : Timeout specified in milliseconds, or special values (0 or -1): + * 0: Don't wait, return immediately (report any sockets currently ready) + * -1: Wait indefinitely. - * `SRT_EINVSOCK`: Socket `sock` is not an ID of a valid socket - * `SRT_EINVPARAM`: `value` is less than `SRT_REJC_PREDEFINED` +| Returns | | +|:----------------------------- |:-------------------------------------------------------------------------------------------------------------------------------------- | +| Number | The number of user socket (SRT socket) state changes that have been reported in `fdsSet`,
if this number isn't greater than `fdsSize` | +| `fdsSize` + 1 | This means that there was not enough space in the output array to report all events.
For events subscribed with the [`SRT_EPOLL_ET`](#SRT_EPOLL_ET) flag only those will be cleared that were reported.
Others will wait for the next call. | +| 0 | If no readiness state was found on any socket and the timeout has passed
(this is not possible when waiting indefinitely) | +| -1 | Error | +| | | -### Error codes +| Errors | | +|:----------------------------------- |:----------------------------------------------------------------- | +| [`SRT_EINVPOLLID`](#srt_einvpollid) | [`eid`](#eid) parameter doesn't refer to a valid epoll container | +| [`SRT_EINVPARAM`](#srt_einvparam) | One of possible usage errors:
* `fdsSize` is < 0
* `fdsSize` is > 0 and `fdsSet` is a null pointer
* [`eid`](#eid) was subscribed to any system socket | +| | | -All functions that return the status via `int` value return -1 (designated as -`SRT_ERROR`) always when the call has failed (in case of resource creation -functions an appropriate symbol is defined, like `SRT_INVALID_SOCK` for -`SRTSOCKET`). When this happens, the error code can be obtained from the -`srt_getlasterror` function. The values for the error are collected in an -`SRT_ERRNO` enum: +**IMPORTANT**: This function reports timeout by returning 0, not by [`SRT_ETIMEOUT`](#srt_etimeout) error. -#### `SRT_EUNKNOWN` +The `SRT_EPOLL_EVENT` structure: -Internal error when setting the right error code. +``` +typedef struct SRT_EPOLL_EVENT_ +{ + SRTSOCKET fd; + int events; +} SRT_EPOLL_EVENT; +``` -#### `SRT_SUCCESS` +* `fd`: the user socket (SRT socket) +* [`events`](#events): event flags that report readiness of this socket - a combination +of [`SRT_EPOLL_IN`](#SRT_EPOLL_IN), [`SRT_EPOLL_OUT`](#SRT_EPOLL_OUT) and [`SRT_EPOLL_ERR`](#SRT_EPOLL_ERR). +See [srt_epoll_add_usock](#srt_epoll_add_usock) for details. -The value set when the last error was cleared and no error has occurred since then. +Note that when [`SRT_EPOLL_ERR`](#SRT_EPOLL_ERR) is set, the underlying socket error +can't be retrieved with `srt_getlasterror()`. The socket will be automatically +closed and its state can be verified with a call to [`srt_getsockstate`](#srt_getsockstate). -#### `SRT_ECONNSETUP` -General setup error resulting from internal system state. +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) -#### `SRT_ENOSERVER` +--- + +### srt_epoll_clear_usocks +``` +int srt_epoll_clear_usocks(int eid); +``` -Connection timed out while attempting to connect to the remote address. Note -that when this happens, `srt_getrejectreason` also reports the timeout reason. +This function removes all SRT ("user") socket subscriptions from the epoll +container identified by [`eid`](#eid). -#### `SRT_ECONNREJ` +| Returns | | +|:----------------------------- |:--------------------------------------------------------- | +| 0 | Success | +| -1 | Failure | +| | | -Connection has been rejected. Additional reject reason can be obtained through -`srt_getrejectreason` (see above). +| Errors | | +|:----------------------------------- |:----------------------------------------------------------------- | +| [`SRT_EINVPOLLID`](#srt_einvpollid) | [`eid`](#eid) parameter doesn't refer to a valid epoll container | +| | | -#### `SRT_ESOCKFAIL` -An error occurred when trying to call a system function on an internally used -UDP socket. Note that the detailed system error is available in the extra variable -passed by pointer to `srt_getlasterror`. -#### `SRT_ESECFAIL` +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) -A possible tampering with the handshake packets was detected, or encryption -request wasn't properly fulfilled. +--- + +### srt_epoll_set +``` +int32_t srt_epoll_set(int eid, int32_t flags); +``` -#### `SRT_ESCLOSED` +This function allows setting or retrieving flags that change the default +behavior of the epoll functions. All default values for these flags are 0. +The following flags are available: -A socket that was vital for an operation called in blocking mode -has been closed during the operation. Please note that this situation is -handled differently than the system calls for `connect` and `accept` -functions for TCP, which simply block indefinitely (or until the standard -timeout) when the key socket was closed during an operation. When this -error is reported, it usually means that the socket passed as the first -parameter to `srt_connect*` or `srt_accept` is no longer usable. +* `SRT_EPOLL_ENABLE_EMPTY`: allows the [`srt_epoll_wait`](#srt_epoll_wait) and +[`srt_epoll_uwait`](#srt_epoll_uwait) functions to be called with the EID not +subscribed to any socket. The default behavior of these function is to report +error in this case. +* `SRT_EPOLL_ENABLE_OUTPUTCHECK`: Forces the [`srt_epoll_wait`](#srt_epoll_wait) +and [`srt_epoll_uwait`](#srt_epoll_uwait) functions to check if the output array +is not empty. For [`srt_epoll_wait`](#srt_epoll_wait) it is still allowed that +either system or user array is empty, as long as EID isn't subscribed to this +type of socket/fd. [`srt_epoll_uwait`](#srt_epoll_uwait) only checks if +the general output array is not empty. -#### `SRT_ECONNFAIL` +**Arguments**: -General connection failure of unknown details. + * `eid`: the epoll container id + * `flags`: a nonzero set of the above flags, or special values: + * 0: clear all flags (set all defaults) + * -1: do not modify any flags -#### `SRT_ECONNLOST` +| Returns | | +|:----------------------------- |:-------------------------------------------------------------------------- | +| | This function returns the state of the flags at the time before the call. | +| -1 | Special value in case when an error occurred. | +| | | -The socket was properly connected, but the connection has been broken. -This specialzation is reported from the transmission functions. +| Errors | | +|:----------------------------------- |:----------------------------------------------------------------- | +| [`SRT_EINVPOLLID`](#srt_einvpollid) | [`eid`](#eid) parameter doesn't refer to a valid epoll container | +| | | -#### `SRT_ENOCONN` -The socket is not connected. This can be reported also when the -connection was broken for a function that checks some characteristic -socket data. +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) -#### `SRT_ERESOURCE` +--- + +### srt_epoll_release +``` +int srt_epoll_release(int eid); +``` -System or standard library error reported unexpectedly for unknown purpose. -Usually it means some internal error. +Deletes the epoll container. -#### `SRT_ETHREAD` +| Returns | | +|:----------------------------- |:-------------------------------------------------------------- | +| | The number (\>0) of ready sockets, of whatever kind (if any). | +| -1 | Error . | +| | | -System was unable to spawn a new thread when requried. +| Errors | | +|:----------------------------------- |:----------------------------------------------------------------- | +| [`SRT_EINVPOLLID`](#srt_einvpollid) | [`eid`](#eid) parameter doesn't refer to a valid epoll container | +| | | -#### `SRT_ENOBUF` -System was unable to allocate memory for buffers. -#### `SRT_ESYSOBJ` -System was unable to allocate system specific objects (such as -sockets, mutexes or condition variables). +## Logging control -#### `SRT_EFILE` +* [srt_setloglevel](#srt_setloglevel) +* [srt_addlogfa, srt_dellogfa, srt_resetlogfa](#srt_addlogfa-srt_dellogfa-srt_resetlogfa) +* [srt_setloghandler](#srt_setloghandler) +* [srt_setlogflags](#srt_setlogflags) -General filesystem error (for functions operating with file transmission). +SRT has a widely used system of logs, as this is usually the only way to determine +how the internals are working without changing the rules by the act of tracing. +Logs are split into levels (5 levels out of those defined by syslog are in use) +and additional filtering is possible on an FA (functional area). By default only +entries up to the *Note* log level are displayed and from all FAs. -#### `SRT_EINVRDOFF` +Logging can only be manipulated globally, with no regard to a specific +socket. This is because lots of operations in SRT are not dedicated to any +particular socket, and some are shared between sockets. -Failure when trying to read from a given position in the file (file could -be modified while it was read from). -#### `SRT_ERDPERM` +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) -Read permission was denied when trying to read from file. + +### srt_setloglevel -#### `SRT_EINVWROFF` +``` +void srt_setloglevel(int ll); +``` -Failed to set position in the written file. +Sets the minimum severity for logging. A particular log entry is displayed only +if it has a severity greater than or equal to the minimum. Setting this value +to `LOG_DEBUG` turns on all levels. -#### `SRT_EWRPERM` +The constants for this value are those from `` +(for Windows, refer to `common/win/syslog_defs.h`). The only meaningful ones are: -Write permission was denied when trying to write to a file. +* `LOG_DEBUG`: Highly detailed and very frequent messages +* `LOG_NOTICE`: Occasionally displayed information +* `LOG_WARNING`: Unusual behavior +* `LOG_ERR`: Abnormal behavior +* `LOG_CRIT`: Error that makes the current socket unusable -#### `SRT_EINVOP` -Invalid operation performed for the current state of a socket. This mainly -concerns performing `srt_bind*` operations on a socket that -is already bound. Once a socket has been been bound, it cannot be bound -again. +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) -#### `SRT_EBOUNDSOCK` +--- + +### srt_addlogfa +### srt_dellogfa +### srt_resetlogfa -The socket is currently bound and the required operation cannot be -performed in this state. Usually it's about an option that can only -be set on the socket before binding (`srt_bind*`). Note that a socket -that is currently connected is also considered bound. +```c++ +void srt_addlogfa(int fa); +void srt_dellogfa(int fa); +void srt_resetlogfa(const int* fara, size_t fara_size); +``` -#### `SRT_ECONNSOCK` +A functional area (FA) is an additional filtering mechanism for logging. You can +set up logging to display logs only from selected FAs. The list of FAs is +collected in the `srt.h` file, as identified by the `SRT_LOGFA_` prefix. They are +not enumerated here because they may be changed very often. -The socket is currently connected and therefore performing the required -operation is not possible. Usually concerns setting an option that must -be set before connecting (although it is allowed to be altered after -binding), or when trying to start a connecting operation (`srt_connect*`) -while the socket isn't in a state that allows it (only `SRTS_INIT` or -`SRTS_OPENED` are allowed). +All FAs are turned on by default, except potentially dangerous ones +(such as `SRT_LOGFA_HAICRYPT`). The reason is that they may display either +some security information that shall remain in memory only (so, only +if strictly required for development), or some duplicated information +(so you may want to turn one FA on, while turning off the others). -#### `SRT_EINVPARAM` -This error is reported in a variety of situations when call parameters -for API functions have some requirements defined and these were not -satisfied. This error should be reported after an initial check of the -parameters of the call before even performing any operation. This error -can be easily avoided if you set the values correctly. +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) -#### `SRT_EINVSOCK` +--- + +### srt_setloghandler -The API function required an ID of an entity (socket or group) and -it was invalid. Note that some API functions work only with socket or -only with group, so they would also return this error if inappropriate -type of entity was passed, even if it was valid. +```c++ +void srt_setloghandler(void* opaque, SRT_LOG_HANDLER_FN* handler); +typedef void SRT_LOG_HANDLER_FN(void* opaque, int level, const char* file, int line, const char* area, const char* message); +``` -#### `SRT_EUNBOUNDSOCK` +By default logs are printed to standard error stream. This function replaces +the sending to a stream with a handler function that will receive them. -The operation to be performed on a socket requires that it first be -explicitly bound (using `srt_bind*` functions). Currently it applies when -calling `srt_listen`, which cannot work with an implicitly bound socket. -#### `SRT_ENOLISTEN` +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) -The socket passed for the operation is required to be in the listen -state (`srt_listen` must be called first). +--- + +### srt_setlogflags -#### `SRT_ERDVNOSERV` +```c++ +void srt_setlogflags(int flags); +``` -The required operation cannot be performed when the socket is set to -rendezvous mode (`SRTO_RENDEZVOUS` set to true). Usually applies when -trying to call `srt_listen` on such a socket. +When you set a log handler with [`srt_setloghandler`](#srt_setloghandler), you +may also want to configure which parts of the log information you do not wish to +be passed in the log line (the `message` parameter). A user's logging facility may, +for example, not wish to get the current time or log level marker, as it +will provide this information on its own. -#### `SRT_ERDVUNBOUND` +The following flags are available, as collected in the `logging_api.h` public header: -An attempt was made to connect to a socket set to rendezvous mode -(`SRTO_RENDEZVOUS` set to true) that was not first bound. A -rendezvous connection requires setting up two addresses and ports -on both sides of the connection, then setting the local one with `srt_bind` -and using the remote one with `srt_connect` (or you can simply -use `srt_rendezvous`). Calling `srt_connect*` on an unbound socket -(in `SRTS_INIT` state) that is to be bound implicitly is only allowed -for regular caller sockets (not rendezvous). +- `SRT_LOGF_DISABLE_TIME`: Do not provide the time in the header +- `SRT_LOGF_DISABLE_THREADNAME`: Do not provide the thread name in the header +- `SRT_LOGF_DISABLE_SEVERITY`: Do not provide severity information in the header +- `SRT_LOGF_DISABLE_EOL`: Do not add the end-of-line character to the log line -#### `SRT_EINVALMSGAPI` -The function was used incorrectly in the message API. This can happen if: -* The parameters specific for the message API in `SRT_MSGCTRL` type parameter -were incorrectly specified +## Time Access -* The extra parameter check performed by the congestion controller has -failed +* [srt_time_now](#srt_time_now) +* [srt_connection_time](#srt_connection_time) -* The socket is a member of a self-managing group, therefore you should -perform the operation on the group, not on this socket +The following set of functions is intended to retrieve timestamps from the clock +used by SRT. +The sender can pass the timestamp in `MSGCTRL::srctime` of the `srt_sendmsg2(..)` +function together with the packet being submitted to SRT. If the `srctime` value +is not provided (the default value of 0 is set), SRT will use the internal clock +and assign packet submission time as the packet timestamp. If the sender wants to +explicitly assign a timestamp to a certain packet this timestamp MUST be taken +from SRT Time Access functions. The time value provided MUST equal or exceed the +connection start time (`srt_connection_time(..)`) of the SRT socket passed +to `srt_sendmsg2(..)`. -#### `SRT_EINVALBUFFERAPI` +The current time value of the SRT internal clock can be retrieved using +the `srt_time_now()` function. -The function was used incorrectly in the stream (buffer) API, that is, -either the stream-only functions were used with set message API -(`srt_sendfile`/`srt_recvfile`) or TSBPD mode was used with buffer API -(`SRTO_TSBPDMODE` set to true) or the congestion controller has failed -to check call parameters. +There are two known cases where you might want to use `srctime`: -#### `SRT_EDUPLISTEN` +1. SRT passthrough (for stream gateways). +You may wish to simply retrieve packets from an SRT source and pass them transparently +to an SRT output (possibly re-encrypting). In that case, every packet you read should +preserve the original value of `srctime` as obtained from [`srt_recvmsg2`](#srt_recvmsg2), +and the original `srctime` for each packet should be then passed to [`srt_sendmsg2`](#srt_sendmsg). +This mechanism could be used to avoid jitter resulting from varying differences between +the time of receiving and sending the same packet. -The port tried to be bound for listening is already busy. Note that binding -to the same port is allowed in general (when `SRTO_REUSEADDR` is true on -every socket that bound it), but only one such socket can be a listener. +2. Stable timing source. +In the case of a live streaming procedure, when spreading packets evenly into the stream, +you might want to predefine times for every single packet to keep time intervals perfectly equal. +Or, if you believe that your input signal delivers packets at the exact times that should be +assigned to them, you might want to preserve these times at the SRT receiving side +to avoid jitter that may result from varying time differences between the packet arrival +and the moment when sending it over SRT. In such cases you might do the following: -#### `SRT_ELARGEMSG` + - At the packet arrival time, grab the current time at that moment using `srt_time_now()`. -Size exceeded. This is reported in the following situations: + - When you want a pre-calculated packet time, use a private relative time counter + set at the moment when the connection was made. From the moment when your first packet + is ready, start pre-calculating packet times relative to the connection start time obtained + from `srt_connection_time()`. Although you still have to synchronize sending times with these + predefined times, by explicitly specifying the source time you avoid the jitter + resulting from a lost accuracy due to waiting time and unfortunate thread scheduling. -* Trying to receive a message, but the read-ready message is larger than -the buffer passed to the receiving function +Note that `srctime` uses an internally defined clock that is intended to be monotonic +(the definition depends on the build flags, see below). Because of that **the application +should not define this time basing on values obtained from the system functions for getting +the current system time** (such as `time`, `ftime` or `gettimeofday`). To avoid problems and +misunderstanding you should rely exclusively on time values provided by the +`srt_time_now()` and `srt_connection_time()` functions. -* Trying to send a message, but the size of this message exceeds the -size of the preset sender buffer, so it cannot be stored in the sender buffer. +The clock used by the SRT internal clock is determined by the following build flags: +- `ENABLE_MONOTONIC` makes use of `CLOCK_MONOTONIC` with `clock_gettime` function. +- `ENABLE_STDXXX_SYNC` makes use of `std::chrono::steady_clock`. -* With getting group data, the array to be filled is too small. +The default is currently to use the system clock as the internal SRT clock, +although it's highly recommended to use one of the above monotonic clocks, +as system clock is vulnerable to time modifications during transmission. -#### `SRT_EINVPOLLID` -The epoll ID passed to an epoll function is invalid +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) -#### `SRT_EPOLLEMPTY` + +### srt_time_now -The epoll container currently has no subscribed sockets. This is reported by an -epoll waiting function that would in this case block forever. This problem -might be reported both in a situation where you have created a new epoll -container and didn't subscribe any sockets to it, or you did, but these -sockets have been closed (including when closed in a separate thread while the -waiting function was blocking). Note that this situation can be prevented -by setting the `SRT_EPOLL_ENABLE_EMPTY` flag, which may be useful when -you use multiple threads and start waiting without subscribed sockets, so that -you can subscribe them later from another thread. +```c++ +int64_t srt_time_now(); +``` -#### `SRT_EASYNCFAIL` +Get time in microseconds elapsed since epoch using SRT internal clock (steady or monotonic clock). -General asynchronous failure (not in use currently). +| Returns | | +|:----------------------------- |:------------------------------------------------------------------------ | +| | Current time in microseconds elapsed since epoch of SRT internal clock. | +| | | -#### `SRT_EASYNCSND` +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) -Sending operation is not ready to perform. This error is reported -when trying to perform a sending operation on a socket that is not -ready for sending, but `SRTO_SNDSYN` was set to false (when true, -the function would block the call otherwise). +--- + +### srt_connection_time -#### `SRT_EASYNCRCV` +```c++ +int64_t srt_connection_time(SRTSOCKET sock); +``` -Receiving operation is not ready to perform. This error is reported -when trying to perform a receiving operation or accept a new socket from the -listener socket, when the socket is not ready for that operation, but -`SRTO_RCVSYN` was set to false (when true, the function would block -the call otherwise). +Get connection time in microseconds elapsed since epoch using SRT internal clock +(steady or monotonic clock). The connection time represents the time when SRT socket +was open to establish a connection. Milliseconds elapsed since connection start time +can be determined using [**Performance tracking**](#Performance-tracking) functions +and `msTimeStamp` value of the `SRT_TRACEBSTATS` (see [statistics.md](statistics.md)). -#### `SRT_ETIMEOUT` +| Returns | | +|:----------------------------- |:--------------------------------------------------------------------------- | +| | Connection time in microseconds elapsed since epoch of SRT internal clock. | +| -1 | Error | +| | | -The operation timed out. This can happen if you have a timeout -set by an option (`SRTO_RCVTIMEO` or `SRTO_SNDTIMEO`), or passed -as an extra argument (`srt_epoll_wait` or `srt_accept_bond`) and -the function call was blocking, but the required timeout time has passed. +| Errors | | +|:--------------------------------- |:---------------------------------------------------------- | +| [`SRT_EINVSOCK`](#srt_einvsock) | Socket `sock` is not an ID of a valid SRT socket | +| | | -#### `SRT_ECONGEST` + +--- + + ## Diagnostics -NOTE: This error is used only in an experimental version that requires -setting the `SRT_ENABLE_ECN` macro at compile time. Otherwise the -situation described below results in the usual successful report. +General notes concerning the `getlasterror` diagnostic functions: when an API +function ends up with error, this error information is stored in a thread-local +storage. This means that you'll get the error of the operation that was last +performed as long as you call this diagnostic function just after the failed +function has returned. In any other situation the information provided by the +diagnostic function is undefined. -This error should be reported by the sending function when, with -`SRTO_TSBPDMODE` and `SRTO_TLPKTDROP` set to true, some packets were dropped at -the sender side (see the description of `SRTO_TLPKTDROP` for details). This -doesn't concern the data that were passed for sending by the sending function -(these data are placed at the back of the sender buffer, while the dropped -packets are at the front). In other words, the operation done by the sending -function is successful, but the application might want to slow down the sending -rate to avoid congestion. +**NOTE**: There is a list of [Error Codes](#error-codes) at the bottom of this document. -#### `SRT_EPEERERR` -This error is reported in a situation when the receiver peer is -writing to a file that the agent is sending. When the peer encounters -an error when writing the received data to a file, it sends the -`UMSG_PEERERROR` message back to the sender, and the sender reports -this error from the API sending function. +* [srt_getlasterror_str](#srt_getlasterror_str) +* [srt_getlasterror](#srt_getlasterror) +* [srt_strerror](#srt_strerror) +* [srt_clearlasterror](#srt_clearlasterror) +* [srt_getrejectreason](#srt_getrejectreason) +* [srt_rejectreason_str](#srt_rejectreason_str) +* [srt_setrejectreason](#srt_setrejectreason) + + +### srt_getlasterror + +``` +int srt_getlasterror(int* errno_loc); +``` + +Get the numeric code of the last error. Additionally, in the variable passed as +`errno_loc` the system error value is returned, or 0 if there was no system error +associated with the last error. The system error is: + * On POSIX systems, the value from `errno` + * On Windows, the result from `GetLastError()` call -## Performance tracking +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) -General note concerning sequence numbers used in SRT: they are 32-bit "circular -numbers" with the most significant bit not included. For example 0x7FFFFFFF -shifted forward by 3 becomes 2. As far as any comparison is concerned, it can -be thought of as a "distance" which is an integer -value expressing an offset to be added to one sequence in order to get the -second one. This distance is only valid as long as the threshold value isn't -exceeded, so it's stated that all sequence numbers that are anywhere taken into -account were systematically updated and they are kept in the range between 0 -and half of the maximum 0x7FFFFFFF. Hence the distance counting procedure -always assumes that the sequence number are in the required range already, so -for a numbers like 0x7FFFFFF0 and 0x10, for which the "numeric difference" -would be 0x7FFFFFE0, the "distance" is 0x20. - -### srt_bstats, srt_bistats +--- + +### srt_strerror +``` +const char* srt_strerror(int code, int errnoval); ``` -// Performance monitor with Byte counters for better bitrate estimation. -int srt_bstats(SRTSOCKET u, SRT_TRACEBSTATS * perf, int clear); -// Performance monitor with Byte counters and instantaneous stats instead of moving averages for Snd/Rcvbuffer sizes. -int srt_bistats(SRTSOCKET u, SRT_TRACEBSTATS * perf, int clear, int instantaneous); +Returns a string message that represents a given SRT error code and possibly the +`errno` value, if not 0. + +**NOTE:** *This function isn't thread safe. It uses a static variable to hold the +error description. There's no problem with using it in a multithreaded environment, +as long as only one thread in the whole application calls this function at the +moment* + + + +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) + +--- + +### srt_getlasterror_str +``` +const char* srt_getlasterror_str(void); ``` -Reports the current statistics +Get the text message for the last error. It's a shortcut to calling first +`srt_getlasterror` and then passing the returned value into [`srt_strerror`](#srt_strerror). +Note that, contrary to [`srt_strerror`](#srt_strerror), this function is thread safe. -* `u`: Socket from which to get statistics -* `perf`: Pointer to an object to be written with the statistics -* `clear`: 1 if the statistics should be cleared after retrieval -* `instantaneous`: 1 if the statistics should use instant data, not moving averages -`SRT_TRACEBSTATS` is an alias to `struct CBytePerfMon`. For a complete description -of the fields please refer to the document [statistics.md](statistics.md). +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) -## Asynchronous operations (epoll) +--- + +### srt_clearlasterror -The epoll system is currently the only method for using multiple sockets in one -thread with having the blocking operation moved to epoll waiting so that it can -block on multiple sockets at once. That is, instead of blocking a single reading -or writing operation, as it's in blocking mode, it blocks until at least one of -the sockets subscribed for a single waiting call in given operation mode is ready -to do this operation without blocking. It's usually combined with setting the -nonblocking mode on a socket, which in SRT is set separately for reading and -writing (`SRTO_RCVSYN` and `SRTO_SNDSYN` respectively) in order to ensure that -in case of some internal error in the application (or even possibly a bug in SRT -that has reported a spurious readiness report) the operation will end up with -error rather than cause blocking, which would be more dangerous for the application -in this case (`SRT_EASYNCRCV` and `SRT_EASYNCRCV` respectively). - -The epoll system, similar to the one on Linux, relies on `eid` objects managed -internally in SRT, which can be subscribed to particular sockets and the -readiness status of particular operations. The `srt_epoll_wait` function can -then be used to block until any readiness status in the whole `eid` is set. +``` +void srt_clearlasterror(void); +``` + +This function clears the last error. After this call, `srt_getlasterror` will +report a "successful" code. + + +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) + + +--- + +### srt_rejectreason_str -### srt_epoll_create ``` -int srt_epoll_create(void); +const char* srt_rejectreason_str(enum SRT_REJECT_REASON id); ``` -Creates a new epoll container. +Returns a constant string for the reason of the connection rejected, as per given +code ID. It provides a system-defined message for values below `SRT_REJ_E_SIZE`. +For other values below `SRT_REJC_PREDEFINED` it returns the string for +[`SRT_REJ_UNKNOWN`](#SRT_REJ_UNKNOWN). For values since `SRT_REJC_PREDEFINED` on, +returns "Application-defined rejection reason". + +The actual messages assigned to the internal rejection codes, that is, less than +`SRT_REJ_E_SIZE`, can be also obtained from the `srt_rejectreason_msg` array. -- Returns: - * valid EID on success - * -1 on failure +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) -- Errors: +--- + +### srt_setrejectreason - * `SRT_ECONNSETUP`: System operation failed or not enough space to create a new epoll. -System error might happen on systems that use a -special method for the system part of epoll (`epoll_create()`, `kqueue()`), and therefore associated resources, -like epoll on Linux. +``` +int srt_setrejectreason(SRTSOCKET sock, int value); +``` + +Sets the rejection code on the socket. This call is only useful in the listener +callback. The code from `value` set this way will be set as a rejection reason +for the socket. After the callback rejects the connection, the code will be passed +back to the caller peer with the handshake response. + +Note that allowed values for this function begin with `SRT_REJC_PREDEFINED` +(that is, you cannot set a system rejection code). For example, your application +can inform the calling side that the resource specified under the `r` key in the +StreamID string (see [`SRTO_STREAMID`](../docs/APISocketOptions.md#SRTO_STREAMID)) +is not available - it then sets the value to `SRT_REJC_PREDEFINED + 404`. -### srt_epoll_add_usock, srt_epoll_add_ssock, srt_epoll_update_usock, srt_epoll_update_ssock +| Returns | | +|:----------------------------- |:--------------------------------------------------------- | +| 0 | Error | +| -1 | Success | +| | | + +| Errors | | +|:--------------------------------- |:-------------------------------------------- | +| [`SRT_EINVSOCK`](#srt_einvsock) | Socket `sock` is not an ID of a valid socket | +| [`SRT_EINVPARAM`](#srt_einvparam) | `value` is less than `SRT_REJC_PREDEFINED` | +| | | + +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) + + +--- + +### srt_getrejectreason ``` -int srt_epoll_add_usock(int eid, SRTSOCKET u, const int* events); -int srt_epoll_add_ssock(int eid, SYSSOCKET s, const int* events); -int srt_epoll_update_usock(int eid, SRTSOCKET u, const int* events); -int srt_epoll_update_ssock(int eid, SYSSOCKET s, const int* events); +int srt_getrejectreason(SRTSOCKET sock); ``` +This function provides a more detailed reason for a failed connection attempt. It +shall be called after a connecting function (such as [`srt_connect`](#srt_connect)) +has returned an error, the code for which is [`SRT_ECONNREJ`](#srt_econnrej). If +[`SRTO_RCVSYN`](../docs/APISocketOptions.md#SRTO_RCVSYN) has been set on the socket +used for the connection, the function should also be called when the +[`SRT_EPOLL_ERR`](#SRT_EPOLL_ERR) event is set for this socket. It returns +a numeric code, which can be translated into a message by +[`srt_rejectreason_str`](#srt_rejectreason_str). -Adds a socket to a container, or updates an existing socket subscription. + +## Rejection Reasons -The `_usock` suffix refers to a user socket (SRT socket). -The `_ssock` suffix refers to a system socket. + +#### SRT_REJ_UNKNOWN -The `_add_` functions add new sockets. The `_update_` functions act on a socket -that is in the container already and just allow changes in the subscription -details. For example, if you have already subscribed a socket with `SRT_EPOLL_OUT` -to wait until it's connected, to change it into poll for read-readiness, you use -this function on that same socket with a variable set to `SRT_EPOLL_IN`. This -will not only change the event type which is polled on the socket, but also -remove any readiness status for flags that are no longer set. It is discouraged -to perform socket removal and adding back (instead of using `_update_`) because -this way you may miss an event that could happen in a short moment between -these two calls. +A fallback value for cases when there was no connection rejected. -* `eid`: epoll container id -* `u`: SRT socket -* `s`: system socket -* `events`: points to - * a variable set to epoll flags (see below) to use only selected events - * NULL if you want to subscribe a socket for all events in level-triggered mode -Possible epoll flags are the following: +#### SRT_REJ_SYSTEM - * `SRT_EPOLL_IN`: report readiness for reading or incoming connection on a listener socket - * `SRT_EPOLL_OUT`: report readiness for writing or a successful connection - * `SRT_EPOLL_ERR`: report errors on the socket - * `SRT_EPOLL_UPDATE`: an important event has happened that requires attention - * `SRT_EPOLL_ET`: the event will be edge-triggered +One system function reported a failure. Usually this means some system +error or lack of system resources to complete the task. -All flags except `SRT_EPOLL_ET` are event type flags (important for functions -that expect only event types and not other flags). + +#### SRT_REJ_PEER -The `SRT_EPOLL_IN`, `SRT_EPOLL_OUT` and `SRT_EPOLL_ERR` events are by default -**level-triggered**. With `SRT_EPOLL_ET` flag they become **edge-triggered**. +The connection has been rejected by peer, but no further details are available. +This usually means that the peer doesn't support rejection reason reporting. -The `SRT_EPOLL_UPDATE` flag is always edge-triggered. It designates a -special event that happens on a group, or on a listener socket that has the -`SRTO_GROUPCONNECT` flag set to allow group connections. This flag -is triggered in the following situations: + +#### SRT_REJ_RESOURCE -* for group connections, when a new link has been established for a group that is already -connected (that is, has at least one connection established), `SRT_EPOLL_UPDATE` is -reported for the listener socket accepting the connection. This is intended for internal -use only. An initial connection results in reporting the group connection on that listener. -But when the group is already connected, `SRT_EPOLL_UPDATE` is reported instead. +A problem with resource allocation (usually memory). -* when one of group member connection has been broken + +#### SRT_REJ_ROGUE -Note that at this time the edge-triggered mode is supported only for SRT -sockets, not for system sockets. +The data sent by one party to another cannot be properly interpreted. This +should not happen during normal usage, unless it's a bug, or some weird +events are happening on the network. -In the **edge-triggered** mode the function will only return socket states that -have changed since the last call of the waiting function. All events reported -in particular call of the waiting function will be cleared in the internal -flags and will not be reported until the internal signaling logic clears this -state and raises it again. +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) -In the **level-triggered** mode the function will always return the readiness -state as long as it lasts, until the internal signaling logic clear it. + +#### SRT_REJ_BACKLOG -Note that when you use `SRT_EPOLL_ET` flag in one subscription call, it defines -edge-triggered mode for all events passed together with it. However, if you -want to have some events reported as edge-triggered and others as -level-triggered, you can do two separate subscriptions for the same socket. +The listener's backlog has exceeded its queue limit (there are many other callers +waiting for the opportunity of being connected and wait in the queue, which has +reached its limit). -**IMPORTANT**: The `srt_epoll_wait` function does not report -`SRT_EPOLL_UPDATE` events. If you need the ability to get any possible flag, -you must use `srt_epoll_uwait`. Note that this function doesn't work with -system file descriptors. + +#### SRT_REJ_IPE -- Returns: +Internal Program Error. This should not happen during normal usage and it +usually means a bug in the software (although this can be reported by both +local and foreign host). - * 0 if successful, otherwise -1 + +#### SRT_REJ_CLOSE -- Errors: +The listener socket was able to receive your request, but at this moment it +is being closed. It's likely that your next attempt will result in a timeout. - * `SRT_EINVPOLLID`: `eid` parameter doesn't refer to a valid epoll container + +#### SRT_REJ_VERSION -**BUG?**: for `add_ssock` the system error results in an empty `CUDTException()` -call which actually results in `SRT_SUCCESS`. For cases like that the -`SRT_ECONNSETUP` code is predicted. +One party of the connection has set up a minimum version that is required for +that connection, but the other party didn't satisfy this requirement. -### srt_epoll_remove_usock, srt_epoll_remove_ssock + +#### SRT_REJ_RDVCOOKIE -``` -int srt_epoll_remove_usock(int eid, SRTSOCKET u); -int srt_epoll_remove_ssock(int eid, SYSSOCKET s); -``` +Rendezvous cookie collision. This normally should never happen, or the +probability that it will happen is negligible. However this can also be +a result of a misconfiguration in that you are trying to make a +rendezvous connection where both parties try to bind to the same IP +address, or both are local addresses of the same host. In such a case +the sent handshake packets are returning to the same host as if they +were sent by the peer (i.e. a party is sending to itself). When this happens, +this reject reason will be reported by every attempt. -Removes a specified socket from an epoll container and clears all readiness -states recorded for that socket. +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) -The `_usock` suffix refers to a user socket (SRT socket). -The `_ssock` suffix refers to a system socket. + +#### SRT_REJ_BADSECRET -- Returns: +Both parties have defined a passphrase for connection, but they differ. - * 0 if successful, otherwise -1 + +#### SRT_REJ_UNSECURE -- Errors: +Only one connection party has set up a password. See also the +[`SRTO_ENFORCEDENCRYPTION`](../docs/APISocketOptions.md#SRTO_ENFORCEDENCRYPTION) flag. - * `SRT_EINVPOLLID`: `eid` parameter doesn't refer to a valid epoll container + +#### SRT_REJ_MESSAGEAPI -### srt_epoll_wait -``` -int srt_epoll_wait(int eid, SRTSOCKET* readfds, int* rnum, SRTSOCKET* writefds, int* wnum, int64_t msTimeOut, - SYSSOCKET* lrfds, int* lrnum, SYSSOCKET* lwfds, int* lwnum); -``` +The value of the [`SRTO_MESSAGEAPI`](../docs/APISocketOptions.md#SRTO_MESSAGEAPI) +flag is different on both connection parties. -Blocks the call until any readiness state occurs in the epoll container. + +#### SRT_REJ_CONGESTION -Readiness can be on a socket in the container for the event type as per -subscription. Note that in case when particular event was subscribed with -`SRT_EPOLL_ET` flag, this event, when once reported in this function, will -be cleared internally. +The [`SRTO_CONGESTION`](../docs/APISocketOptions.md#SRTO_CONGESTION)option has +been set up differently on both connection parties. -The first readiness state causes this function to exit, but all ready sockets -are reported. This function blocks until the timeout specified in `msTimeOut` -parameter. If timeout is 0, it exits immediately after checking. If timeout is --1, it blocks indefinitely until a readiness state occurs. + +#### SRT_REJ_FILTER -* `eid`: epoll container -* `readfds` and `rnum`: A pointer and length of an array to write SRT sockets that are read-ready -* `writefds` and `wnum`: A pointer and length of an array to write SRT sockets that are write-ready -* `msTimeOut`: Timeout specified in milliseconds, or special values (0 or -1) -* `lwfds` and `lwnum`:A pointer and length of an array to write system sockets that are read-ready -* `lwfds` and `lwnum`:A pointer and length of an array to write system sockets that are write-ready +The [`SRTO_PACKETFILTER`](../docs/APISocketOptions.md#SRTO_PACKETFILTER) option +has been set differently on both connection parties. -Note that the following flags are reported: +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) -* `SRT_EPOLL_IN` as read-ready (also a listener socket ready to accept) -* `SRT_EPOLL_OUT` as write-ready (also a connected socket) -* `SRT_EPOLL_ERR` as both read-ready and write-ready -* `SRT_EPOLL_UPDATE` is not reported + +#### SRT_REJ_GROUP -There is no space here to report sockets for which it's already known -that the operation will end up with error (athough such a state is known -internally). If an error occurred on a socket then that socket is reported in -both read-ready and write-ready arrays, regardless of what event types it was -subscribed for. Usually then you subscribe given socket for only read readiness, -for example (`SRT_EPOLL_IN`), but pass both arrays for read and write readiness. -This socket will not be reported in the write readiness array even if it's write -ready (because this isn't what it was subscribed for), but it will be reported -there, if the next operation on this socket is about to be erroneous. On such -sockets you can still perform an operation, just you should expect that it will -always report and error. On the other hand that's the only way to know what kind -of error has occurred on the socket. +The group type or some group settings are incompatible for both connection parties. +While every connection within a bonding group may have different target addresses, +they should all designate the same endpoint and the same SRT application. If this +condition isn't satisfied, then the peer will respond with a different peer group +ID for the connection that is trying to contact a machine/application that is +completely different from the existing connections in the bonding group. -- Returns: + +#### SRT_REJ_TIMEOUT - * The number (\>0) of ready sockets, of whatever kind (if any) - * -1 in case of error +The connection wasn't rejected, but it timed out. This code is always set on +connection timeout, but this is the only way to get this state in non-blocking +mode (see [`SRTO_RCVSYN`](../docs/APISocketOptions.md#SRTO_RCVSYN)). -- Errors: +There may also be server and user rejection codes, as defined by the +`SRT_REJC_INTERNAL`, `SRT_REJC_PREDEFINED` and `SRT_REJC_USERDEFINED` +constants. Note that the number space from the value of `SRT_REJC_PREDEFINED` +and above is reserved for "predefined codes" (`SRT_REJC_PREDEFINED` value plus +adopted HTTP codes). Values above `SRT_REJC_USERDEFINED` are freely defined by +the application. - * `SRT_EINVPOLLID`: `eid` parameter doesn't refer to a valid epoll container - * `SRT_ETIMEOUT`: Up to `msTimeOut` no sockets subscribed in `eid` were ready. -This is reported only if `msTimeOut` was \>=0, otherwise the function waits -indefinitely. -### srt_epoll_uwait -``` -int srt_epoll_uwait(int eid, SRT_EPOLL_EVENT* fdsSet, int fdsSize, int64_t msTimeOut); -``` +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) -This function blocks a call until any readiness state occurs in the epoll -container. Unlike `srt_epoll_wait`, it can only be used with `eid` subscribed -to user sockets (SRT sockets), not system sockets. + + +## Error Codes -This function blocks until the timeout specified in `msTimeOut` parameter. If -timeout is 0, it exits immediately after checking. If timeout is -1, it blocks -indefinitely until a readiness state occurs. +All functions that return the status via `int` value return -1 (designated as +`SRT_ERROR`) always when the call has failed (in case of resource creation +functions an appropriate symbol is defined, like `SRT_INVALID_SOCK` for +`SRTSOCKET`). When this happens, the error code can be obtained from the +`srt_getlasterror` function. The values for the error are collected in an +`SRT_ERRNO` enum: -* `eid`: epoll container -* `fdsSet` : A pointer to an array of `SRT_EPOLL_EVENT` -* `fdsSize` : The size of the fdsSet array -* `msTimeOut` : Timeout specified in milliseconds, or special values (0 or -1): - * 0: Don't wait, return immediately (report any sockets currently ready) - * -1: Wait indefinitely. + +#### `SRT_EUNKNOWN` -- Returns: +Internal error when setting the right error code. - * The number of user socket (SRT socket) state changes that have been reported -in `fdsSet`, if this number isn't greater than `fdsSize` + +#### `SRT_SUCCESS` - * Otherwise the return value is `fdsSize` + 1. This means that there was not -enough space in the output array to report all events. For events subscribed with -`SRT_EPOLL_ET` flag only those will be cleared that were reported. Others will -wait for the next call. +The value set when the last error was cleared and no error has occurred since then. - * If no readiness state was found on any socket and the timeout has passed, 0 -is returned (this is not possible when waiting indefinitely) + +#### `SRT_ECONNSETUP` - * -1 in case of error +General setup error resulting from internal system state. + +#### `SRT_ENOSERVER` -- Errors: +Connection timed out while attempting to connect to the remote address. Note +that when this happens, [`srt_getrejectreason`](#srt_getrejectreason) also reports +the timeout reason. - * `SRT_EINVPOLLID`: `eid` parameter doesn't refer to a valid epoll container - * `SRT_EINVPARAM`: One of possible usage errors: - * `fdsSize` is < 0 - * `fdsSize` is > 0 and `fdsSet` is a null pointer - * `eid` was subscribed to any system socket + +#### `SRT_ECONNREJ` -(IMPORTANT: this function reports timeout by returning 0, not by `SRT_ETIMEOUT` error.) +Connection has been rejected. Additional reject reason can be obtained through +[`srt_getrejectreason`](#srt_getrejectreason) (see above). -The `SRT_EPOLL_EVENT` structure: +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) -``` -typedef struct SRT_EPOLL_EVENT_ -{ - SRTSOCKET fd; - int events; -} SRT_EPOLL_EVENT; -``` + +#### `SRT_ESOCKFAIL` -* `fd` : the user socket (SRT socket) -* `events` : event flags that report readiness of this socket - a combination -of `SRT_EPOLL_IN`, `SRT_EPOLL_OUT` and `SRT_EPOLL_ERR` - see [srt_epoll_add_usock](#srt_epoll_add_usock) -for details +An error occurred when trying to call a system function on an internally used +UDP socket. Note that the detailed system error is available in the extra variable +passed by pointer to `srt_getlasterror`. -Note that when the `SRT_EPOLL_ERR` is set, the underlying socket error -can't be retrieved with `srt_getlasterror()`. The socket will be automatically -closed and its state can be verified with a call to `srt_getsockstate`. + +#### `SRT_ESECFAIL` -### srt_epoll_clear_usocks -``` -int srt_epoll_clear_usocks(int eid); -``` +A possible tampering with the handshake packets was detected, or an encryption +request wasn't properly fulfilled. -This function removes all SRT ("user") socket subscriptions from the epoll -container identified by `eid`. + +#### `SRT_ESCLOSED` -- Returns: - * 0 on success - * -1 in case of error +A socket that was vital for an operation called in blocking mode +has been closed during the operation. Please note that this situation is +handled differently than the system calls for `connect` and `accept` +functions for TCP, which simply block indefinitely (or until the standard +timeout) when the key socket was closed during an operation. When this +error is reported, it usually means that the socket passed as the first +parameter to [`srt_connect*`](#srt_connect) or [`srt_accept`](#srt_accept) +is no longer usable. -- Errors: + +#### `SRT_ECONNFAIL` - * `SRT_EINVPOLLID`: `eid` parameter doesn't refer to a valid epoll container +General connection failure of unknown details. -### srt_epoll_set -``` -int32_t srt_epoll_set(int eid, int32_t flags); -``` + +#### `SRT_ECONNLOST` -This function allows to set or retrieve flags that change the default -behavior of the epoll functions. All default values for these flags are 0. -The following flags are available: +The socket was properly connected, but the connection has been broken. +This specialization is reported from the transmission functions. -* `SRT_EPOLL_ENABLE_EMPTY`: allows the `srt_epoll_wait` and `srt_epoll_uwait` -functions to be called with the EID not subscribed to any socket. The default -behavior of these function is to report error in this case. +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) -* `SRT_EPOLL_ENABLE_OUTPUTCHECK`: Forces the `srt_epoll_wait` and `srt_epoll_uwait` -functions to check if the output array is not empty. For `srt_epoll_wait` it -is still allowed that either system or user array is empty, as long as EID -isn't subscribed to this type of socket/fd. `srt_epoll_uwait` only checks if -the general output array is not empty. + +#### `SRT_ENOCONN` -- Parameters: +The socket is not connected. This can be reported also when the connection was +broken for a function that checks some characteristic socket data. - * `eid`: the epoll container id - * `flags`: a nonzero set of the above flags, or special values: - * 0: clear all flags (set all defaults) - * -1: do not modify any flags + +#### `SRT_ERESOURCE` -- Returns: +System or standard library error reported unexpectedly for unknown purpose. +Usually it means some internal error. -This function returns the state of the flags at the time before the call, -or a special value -1 in case when an error occurred. + +#### `SRT_ETHREAD` -- Errors: +System was unable to spawn a new thread when required. - * `SRT_EINVPOLLID`: `eid` parameter doesn't refer to a valid epoll container + +#### `SRT_ENOBUF` +System was unable to allocate memory for buffers. -### srt_epoll_release -``` -int srt_epoll_release(int eid); -``` + +#### `SRT_ESYSOBJ` -Deletes the epoll container. +System was unable to allocate system specific objects (such as +sockets, mutexes or condition variables). -- Returns: +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) - * The number (\>0) of ready sockets, of whatever kind (if any) - * -1 in case of error + +#### `SRT_EFILE` -- Errors: +General filesystem error (for functions operating with file transmission). + +#### `SRT_EINVRDOFF` - * `SRT_EINVPOLLID`: `eid` parameter doesn't refer to a valid epoll container +Failure when trying to read from a given position in the file (file could +be modified while it was read from). -## Logging control + +#### `SRT_ERDPERM` -SRT has a widely used system of logs, as this is usually the only way to determine -how the internals are working, without changing the rules by the act of tracing. -Logs are split into levels (5 levels out of those defined by syslog are in use) -and additional filtering is possible on FA (functional area). By default only -up to the *Note* log level are displayed and from all FAs. +Read permission was denied when trying to read from file. -Logging can only be manipulated globally, with no regard to a specific -socket. This is because lots of operations in SRT are not dedicated to any -particular socket, and some are shared between sockets. + +#### `SRT_EINVWROFF` -### srt_setloglevel +Failed to set position in the written file. -``` -void srt_setloglevel(int ll); -``` + +#### `SRT_EWRPERM` -Sets the minimum severity for logging. A particular log entry is displayed only -if it has a severity greater than or equal to the minimum. Setting this value -to `LOG_DEBUG` turns on all levels. +Write permission was denied when trying to write to a file. -The constants for this value are those from `` -(for Windows, refer to `common/win/syslog_defs.h`). The only meaningful are: +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) -* `LOG_DEBUG`: Highly detailed and very frequent messages -* `LOG_NOTICE`: Occasionally displayed information -* `LOG_WARNING`: Unusual behavior -* `LOG_ERR`: Abnormal behavior -* `LOG_CRIT`: Error that makes the current socket unusable + +#### `SRT_EINVOP` -### srt_addlogfa, srt_dellogfa, srt_resetlogfa +Invalid operation performed for the current state of a socket. This mainly +concerns performing `srt_bind*` operations on a socket that is already bound. +Once a socket has been been bound, it cannot be bound again. -```c++ -void srt_addlogfa(int fa); -void srt_dellogfa(int fa); -void srt_resetlogfa(const int* fara, size_t fara_size); -``` + +#### `SRT_EBOUNDSOCK` -A functional area (FA) is an additional filtering mechanism for logging. You can -set up logging to display logs only from selected FAs. The list of FAs is -collected in `srt.h` file, as identified by the `SRT_LOGFA_` prefix. They are not -enumerated here because they may be changed very often. +The socket is currently bound and the required operation cannot be +performed in this state. Usually it's about an option that can only +be set on the socket before binding (`srt_bind*`). Note that a socket +that is currently connected is also considered bound. + +#### `SRT_ECONNSOCK` -All FAs are turned on by default, except potentially dangerous ones -(such as `SRT_LOGFA_HAICRYPT`). The reaons is that they may display either -some security information that shall remain in the memory only (so, only -if strictly required for the development), or some duplicated information -(so you may want to turn this FA on, while turning off the others). +The socket is currently connected and therefore performing the required operation +is not possible. Usually concerns setting an option that must be set before +connecting (although it is allowed to be altered after binding), or when trying +to start a connecting operation ([`srt_connect*`](#srt_connect)) while the socket +isn't in a state that allows it (only [`SRTS_INIT`](#SRTS_INIT) or +[`SRTS_OPENED`](#SRTS_OPENED) are allowed). -### srt_setloghandler + +#### `SRT_EINVPARAM` -```c++ -void srt_setloghandler(void* opaque, SRT_LOG_HANDLER_FN* handler); -typedef void SRT_LOG_HANDLER_FN(void* opaque, int level, const char* file, int line, const char* area, const char* message); -``` +This error is reported in a variety of situations when call parameters +for API functions have some requirements defined and these were not +satisfied. This error should be reported after an initial check of the +parameters of the call before even performing any operation. This error +can be easily avoided if you set the values correctly. -By default logs are printed to standard error stream. This function replaces -the sending to a stream with a handler function that will receive them. + +#### `SRT_EINVSOCK` -### srt_setlogflags +The API function required an ID of an entity (socket or group) and +it was invalid. Note that some API functions work only with socket or +only with group, so they would also return this error if inappropriate +type of entity was passed, even if it was valid. -```c++ -void srt_setlogflags(int flags); -``` +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) -When you set a log handler with `srt_setloghandler`, you may also want to -configure which parts of the log information you do not wish to be passed -in the log line (the `message` parameter). A user's logging facility may, -for example, not wish to get the current time or log level marker, as it -will provide this information on its own. + +#### `SRT_EUNBOUNDSOCK` +The operation to be performed on a socket requires that it first be explicitly +bound (using [`srt_bind*`](#srt_bind) functions). Currently it applies when +calling [`srt_listen`](#srt_listen), which cannot work with an implicitly +bound socket. -The following flags are available, as collected in `logging_api.h` public header: + +#### `SRT_ENOLISTEN` -- `SRT_LOGF_DISABLE_TIME`: Do not provide the time in the header -- `SRT_LOGF_DISABLE_THREADNAME`: Do not provide the thread name in the header -- `SRT_LOGF_DISABLE_SEVERITY`: Do not provide severity information in the header -- `SRT_LOGF_DISABLE_EOL`: Do not add the end-of-line character to the log line +The socket passed for the operation is required to be in the listen +state ([`srt_listen`](#srt_listen) must be called first). -## Time Access + +#### `SRT_ERDVNOSERV` -The following set of functions is intended to retrieve timestamps from the clock used by SRT. -The sender can pass the timestamp in `MSGCTRL::srctime` of the `srt_sendmsg2(..)` -function together with the packet being submitted to SRT. -If the `srctime` value is not provided (the default value of 0 is set), SRT will use internal -clock and assign the packet submission time as the packet timestamp. -If the sender wants to explicitly assign a timestamp -to a certain packet. this timestamp MUST be taken from SRT Time Access functions. -The time value provided MUST equal or exceed the connection start time (`srt_connection_time(..)`) -of the SRT socket passed to `srt_sendmsg2(..)`. +The required operation cannot be performed when the socket is set to rendezvous +mode ([`SRTO_RENDEZVOUS`](../docs/APISocketOptions.md#SRTO_RENDEZVOUS) set to true). +Usually applies when trying to call [`srt_listen`](#srt_listen) on such a socket. -The current time value as of the SRT internal clock can be retrieved using the `srt_time_now()` function. + +#### `SRT_ERDVUNBOUND` -There are two known cases where you might want to use `srctime`: +An attempt was made to connect to a socket set to rendezvous mode +([`SRTO_RENDEZVOUS`](../docs/APISocketOptions.md#SRTO_RENDEZVOUS) set to true) +that was not first bound. A rendezvous connection requires setting up two addresses +and ports on both sides of the connection, then setting the local one with +[`srt_bind`](#srt_bind) and using the remote one with [`srt_connect`](#srt_connect) +(or you can simply use [`srt_rendezvous`](#srt_rendezvous)). Calling +[`srt_connect*`](#srt_connect) on an unbound socket (in [`SRTS_INIT`](#SRTS_INIT) +state) that is to be bound implicitly is only allowed for regular caller sockets +(not rendezvous). + + +#### `SRT_EINVALMSGAPI` -1. SRT passthrough (for stream gateways). -You may wish to simply retrieve packets from an SRT source and pass them transparently -to an SRT output (possibly re-encrypting). In that case, every packet you read -should preserve the original value of `srctime` as obtained from `srt_recvmsg2`, -and the original `srctime` for each packet should be then passed to `srt_sendmsg2`. -This mechanism could be used to avoid jitter resulting from varying differences between -the time of receiving and sending the same packet. +The function was used incorrectly in the message API. This can happen if: -2. Stable timing source. -In the case of a live streaming procedure, when spreading packets evenly into the stream, -you might want to predefine times for every single packet to keep time intervals perfectly equal. -Or, if you believe that your input signal delivers packets at the exact times that should be -assigned to them, you might want to preserve these times at the SRT receiving side -to avoid jitter that may result from varying time differences between the packet arrival -and the moment when sending it over SRT. In such cases you might do the following: +* The parameters specific for the message API in [`SRT_MSGCTRL`](#SRT_MSGCTRL) +type parameter were incorrectly specified - - At the packet arrival time, grab the current time at that moment using `srt_time_now()`. +* The extra parameter check performed by the congestion controller has failed - - When you want a precalculated packet time, use a private relative time counter - set at the moment when the connection was made. From the moment when your first packet - is ready, start precalculating packet times relative to the connection start time obtained - from `srt_connection_time()`. Although you still have to synchronize sending times with these - predefined times, by explicitly specifying the source time you avoid the jitter - resulting from a lost accuracy due to waiting time and unfortunate thread scheduling. +* The socket is a member of a self-managing group, therefore you should +perform the operation on the group, not on this socket -Note that `srctime` uses an internally defined clock -that is intended to be monotonic (the definition depends on the build flags, -see below). Because of that **the application should not define this time basing -on values obtained from the system functions for getting the current system time** -(such as `time`, `ftime` or `gettimeofday`). To avoid problems and -misunderstanding you should rely exclusively on time values provided by -`srt_time_now()` and `srt_connection_time()` functions. +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) -The clock used by SRT internal clock, is determined by the following build flags: -- `ENABLE_MONOTONIC` makes use of `CLOCK_MONOTONIC` with `clock_gettime` function. -- `ENABLE_STDXXX_SYNC` makes use of `std::chrono::steady_clock`. + +#### `SRT_EINVALBUFFERAPI` -The default is currently to use the system clock as internal SRT clock, -although it's highly recommended to use one of the above monotonic clocks, -as system clock is vulnerable to time modifications during transmission. +The function was used incorrectly in the stream (buffer) API, that is, either the +stream-only functions were used with set message API ([`srt_sendfile`](#srt_sendfile)/[`srt_recvfile`](#srt_recvfile)) +or TSBPD mode was used with buffer API ([`SRTO_TSBPDMODE`](../docs/APISocketOptions.md#SRTO_TSBPDMODE) set to true) +or the congestion controller has failed to check call parameters. -### srt_time_now + +#### `SRT_EDUPLISTEN` -```c++ -int64_t srt_time_now(); -``` +The port tried to be bound for listening is already busy. Note that binding to the same port +is allowed in general (when [`SRTO_REUSEADDR`](../docs/APISocketOptions.md#SRTO_REUSEADDRS) +is true on every socket that has bound it), but only one such socket can be a listener. -Get time in microseconds elapsed since epoch using SRT internal clock (steady or monotonic clock). + +#### `SRT_ELARGEMSG` -- Returns: - - Current time in microseconds elapsed since epoch of SRT internal clock. +Size exceeded. This is reported in the following situations: -### srt_connection_time +* Trying to receive a message, but the read-ready message is larger than +the buffer passed to the receiving function -```c++ -int64_t srt_connection_time(SRTSOCKET sock); -``` +* Trying to send a message, but the size of this message exceeds the +size of the preset sender buffer, so it cannot be stored in the sender buffer. + +* When getting group data, the array to be filled is too small. + + +#### `SRT_EINVPOLLID` + +The epoll ID passed to an epoll function is invalid + + +#### `SRT_EPOLLEMPTY` + +The epoll container currently has no subscribed sockets. This is reported by an +epoll waiting function that would in this case block forever. This problem +might be reported both in a situation where you have created a new epoll +container and didn't subscribe any sockets to it, or you did, but these +sockets have been closed (including when closed in a separate thread while the +waiting function was blocking). Note that this situation can be prevented +by setting the `SRT_EPOLL_ENABLE_EMPTY` flag, which may be useful when +you use multiple threads and start waiting without subscribed sockets, so that +you can subscribe them later from another thread. + +[:arrow_up:   Back to List of Functions & Structures](#srt-api-functions) + + +#### `SRT_EASYNCFAIL` + +General asynchronous failure (not in use currently). + + +#### `SRT_EASYNCSND` + +Sending operation is not ready to perform. This error is reported when trying to +perform a sending operation on a socket that is not ready for sending, but +[`SRTO_SNDSYN`](../docs/APISocketOptions.md#SRTO_SNDSYN) was set to false (when +true, the function would block the call otherwise). + + +#### `SRT_EASYNCRCV` + +Receiving operation is not ready to perform. This error is reported when trying to +perform a receiving operation or accept a new socket from the listener socket, when +the socket is not ready for that operation, but [`SRTO_RCVSYN`](../docs/APISocketOptions.md#SRTO_RCVSYN) +was set to false (when true, the function would block the call otherwise). + + +#### `SRT_ETIMEOUT` + +The operation timed out. This can happen if you have a timeout set by an option +([`SRTO_RCVTIMEO`](../docs/APISocketOptions.md#SRTO_RCVTIMEO) or +[`SRTO_SNDTIMEO`](../docs/APISocketOptions.md#SRTO_SNDTIMEO)), or passed as an +extra argument ([`srt_epoll_wait`](#srt_epoll_wait) or [`srt_accept_bond`](#srt_accept_bond)) +and the function call was blocking, but the required timeout time has passed. + + +#### `SRT_ECONGEST` + +**NOTE**: This error is used only in an experimental version that requires +setting the `SRT_ENABLE_ECN` macro at compile time. Otherwise the situation +described below results in the usual successful report. + +This error should be reported by the sending function when, with +[`SRTO_TSBPDMODE`](../docs/APISocketOptions.md#SRTO_TSBPDMODE) and +[`SRTO_TLPKTDROP`](../docs/APISocketOptions.md#SRTO_TLPKTDROP) set to true, some +packets were dropped at the sender side (see the description of +[`SRTO_TLPKTDROP`](../docs/APISocketOptions.md#SRTO_TLPKTDROP) for details). This +doesn't concern the data that were passed for sending by the sending function +(these data are placed at the back of the sender buffer, while the dropped +packets are at the front). In other words, the operation done by the sending +function is successful, but the application might want to slow down the sending +rate to avoid congestion. + + +#### `SRT_EPEERERR` -Get connection time in microseconds elapsed since epoch using SRT internal clock (steady or monotonic clock). -The connection time represents the time when SRT socket was open to establish a connection. -Milliseconds elapsed since connection start time can be determined using [**Performance tracking**](#Performance-tracking) -functions and `msTimeStamp` value of the `SRT_TRACEBSTATS` (see [statistics.md](statistics.md)). +This error is reported when a receiver peer is writing to a file that an agent +is sending. When the peer encounters an error when writing the received data to +a file, it sends the `UMSG_PEERERROR` message back to the sender, and the sender +reports this error from the API sending function. -- Returns: - - Connection time in microseconds elapsed since epoch of SRT internal clock. - - -1 in case of error -- Errors: - - `SRT_EINVSOCK`: Socket `sock` is not an ID of a valid SRT socket + + [RETURN TO TOP OF PAGE](#SRT-API-Functions) diff --git a/srtcore/core.cpp b/srtcore/core.cpp index b06c8f681..f35636f5a 100644 --- a/srtcore/core.cpp +++ b/srtcore/core.cpp @@ -5112,7 +5112,6 @@ EConnectStatus CUDT::postConnect(const CPacket &response, bool rendezvous, CUDTE s->m_pUDT->m_pSndQueue->m_pChannel->getSockAddr((s->m_SelfAddr)); CIPAddress::pton((s->m_SelfAddr), s->m_pUDT->m_piSelfIP, m_PeerAddr); - s->m_Status = SRTS_CONNECTED; //int token = -1; #if ENABLE_EXPERIMENTAL_BONDING { @@ -5142,6 +5141,8 @@ EConnectStatus CUDT::postConnect(const CPacket &response, bool rendezvous, CUDTE } #endif + s->m_Status = SRTS_CONNECTED; + // acknowledde any waiting epolls to write // This must be done AFTER the group member status is upgraded to IDLE because // this state change will trigger the waiting function in blocking-mode groupConnect diff --git a/test/test_connection_timeout.cpp b/test/test_connection_timeout.cpp index bbd87e145..eea0a95f1 100644 --- a/test/test_connection_timeout.cpp +++ b/test/test_connection_timeout.cpp @@ -11,6 +11,7 @@ typedef int SOCKET; #include"platform_sys.h" #include "srt.h" +#include "logger_defs.h" using namespace std; @@ -172,20 +173,20 @@ TEST_F(TestConnectionTimeout, Nonblocking) { */ TEST_F(TestConnectionTimeout, BlockingLoop) { - const SRTSOCKET client_sock = srt_create_socket(); - ASSERT_GT(client_sock, 0); // socket_id should be > 0 - - // Set connection timeout to 999 ms to reduce the test execution time. - // Also need to hit a time point between two threads: - // srt_connect will check TTL every second, - // CRcvQueue::worker will wait on a socket for 10 ms. - // Need to have a condition, when srt_connect will process the timeout. - const int connection_timeout_ms = 999; - EXPECT_EQ(srt_setsockopt(client_sock, 0, SRTO_CONNTIMEO, &connection_timeout_ms, sizeof connection_timeout_ms), SRT_SUCCESS); - const sockaddr* psa = reinterpret_cast(&m_sa); + const int connection_timeout_ms = 999; for (int i = 0; i < 10; ++i) { + const SRTSOCKET client_sock = srt_create_socket(); + ASSERT_GT(client_sock, 0); // socket_id should be > 0 + + // Set connection timeout to 999 ms to reduce the test execution time. + // Also need to hit a time point between two threads: + // srt_connect will check TTL every second, + // CRcvQueue::worker will wait on a socket for 10 ms. + // Need to have a condition, when srt_connect will process the timeout. + EXPECT_EQ(srt_setsockopt(client_sock, 0, SRTO_CONNTIMEO, &connection_timeout_ms, sizeof connection_timeout_ms), SRT_SUCCESS); + EXPECT_EQ(srt_connect(client_sock, psa, sizeof m_sa), SRT_ERROR); const int error_code = srt_getlasterror(nullptr); @@ -196,9 +197,9 @@ TEST_F(TestConnectionTimeout, BlockingLoop) << error_code << " " << srt_getlasterror_str() << "\n"; break; } - } - EXPECT_EQ(srt_close(client_sock), SRT_SUCCESS); + EXPECT_EQ(srt_close(client_sock), SRT_SUCCESS); + } } diff --git a/test/test_file_transmission.cpp b/test/test_file_transmission.cpp index 790555eb7..c5149604a 100644 --- a/test/test_file_transmission.cpp +++ b/test/test_file_transmission.cpp @@ -17,9 +17,11 @@ #endif #include "srt.h" +#include "logger_defs.h" #include #include +#include #include #include @@ -27,6 +29,8 @@ TEST(Transmission, FileUpload) { + using std::cout; + using std::endl; srt_startup(); // Generate the source file @@ -50,8 +54,10 @@ TEST(Transmission, FileUpload) int optval = 0; int optlen = sizeof optval; ASSERT_EQ(srt_getsockflag(sock_lsn, SRTO_SNDBUF, &optval, &optlen), 0); - size_t filesize = 7 * optval; + const size_t filesize = 7 * optval; + int counter = 0; + int npackets = 0; { std::cout << "WILL CREATE source file with size=" << filesize << " (= 7 * " << optval << "[sndbuf])\n"; std::ofstream outfile("file.source", std::ios::out | std::ios::binary); @@ -63,7 +69,21 @@ TEST(Transmission, FileUpload) { char outbyte = rand() % 255; outfile.write(&outbyte, 1); + ++counter; + if (counter == 1456) + { + ++npackets; + cout << "\r" << npackets << " "; + counter = 0; + } + } + if (counter) + { + ++npackets; + cout << "\r" << npackets << " "; + } + cout << endl; } srt_listen(sock_lsn, 1); @@ -72,41 +92,48 @@ TEST(Transmission, FileUpload) bool thread_exit = false; + srt_logging::gglog.Warn("TEST: Transmission.FileUload"); + srt_setloglevel(LOG_DEBUG); + auto client = std::thread([&] - { - sockaddr_in remote; - int len = sizeof remote; - const SRTSOCKET accepted_sock = srt_accept(sock_lsn, (sockaddr*)&remote, &len); - ASSERT_GT(accepted_sock, 0); + { + sockaddr_in remote; + int len = sizeof remote; + const SRTSOCKET accepted_sock = srt_accept(sock_lsn, (sockaddr*)&remote, &len); + ASSERT_GT(accepted_sock, 0); - if (accepted_sock == SRT_INVALID_SOCK) - { + if (accepted_sock == SRT_INVALID_SOCK) + { std::cerr << srt_getlasterror_str() << std::endl; EXPECT_NE(srt_close(sock_lsn), SRT_ERROR); return; - } + } - std::ofstream copyfile("file.target", std::ios::out | std::ios::trunc | std::ios::binary); + std::ofstream copyfile("file.target", std::ios::out | std::ios::trunc | std::ios::binary); - std::vector buf(1456); + std::vector buf(1456); - for (;;) - { - int n = srt_recv(accepted_sock, buf.data(), 1456); - ASSERT_NE(n, SRT_ERROR); - if (n == 0) + npackets = 0; + for (;;) { - break; + int n = srt_recv(accepted_sock, buf.data(), 1456); + ASSERT_NE(n, SRT_ERROR); + if (n == 0) + { + cout << endl; + break; + } + + // Write to file any amount of data received + copyfile.write(buf.data(), n); + ++npackets; + cout << "\r" << npackets << " "; } - // Write to file any amount of data received - copyfile.write(buf.data(), n); - } - - EXPECT_NE(srt_close(accepted_sock), SRT_ERROR); + EXPECT_NE(srt_close(accepted_sock), SRT_ERROR); - thread_exit = true; - }); + thread_exit = true; + }); sockaddr_in sa = sockaddr_in(); sa.sin_family = AF_INET; @@ -172,5 +199,8 @@ TEST(Transmission, FileUpload) remove("file.source"); remove("file.target"); + // restore log level to not affect the others + srt_setloglevel(LOG_NOTICE); + (void)srt_cleanup(); }