6
6
#include " ntgcalls/exceptions.hpp"
7
7
8
8
namespace ntgcalls {
9
- BaseReader::BaseReader (const int64_t bufferSize, const bool noLatency): noLatency(noLatency) {
10
- size = bufferSize;
11
- }
9
+ BaseReader::BaseReader (const int64_t bufferSize, const bool noLatency): noLatency(noLatency), size(bufferSize) {}
12
10
13
11
BaseReader::~BaseReader () {
14
12
BaseReader::close ();
15
- std::lock_guard lock (mutex);
16
- promise = nullptr ;
17
13
readChunks = 0 ;
18
- buffer.clear ();
19
14
}
20
15
21
16
void BaseReader::start () {
22
- if (!noLatency) thread = std::thread (&BaseReader::readAsync, this );
23
- }
24
-
25
- void BaseReader::readAsync () {
26
- do {
27
- std::this_thread::sleep_for (std::chrono::milliseconds (5 ));
28
- std::unique_lock lock (mutex);
29
- if (buffer.size () < 10 && !_eof) {
30
- const auto availableSpace = 10 - buffer.size ();
31
- try {
17
+ if (!noLatency) {
18
+ thread = std::thread ([this ] {
19
+ do {
20
+ std::this_thread::sleep_for (std::chrono::milliseconds (10 ));
21
+ std::unique_lock lock (mutex);
22
+ const auto availableSpace = 10 - buffer.size ();
23
+ lock.unlock ();
32
24
for (int i = 0 ; i < availableSpace; i++) {
33
- if (auto tmp = this ->readInternal (size); tmp) {
34
- buffer.push_back (tmp);
25
+ try {
26
+ if (auto tmp = this ->readInternal (size); tmp) {
27
+ lock.lock ();
28
+ buffer.push (std::move (tmp));
29
+ lock.unlock ();
30
+ }
31
+ } catch (...) {
32
+ lock.lock ();
33
+ _eof = true ;
34
+ lock.unlock ();
35
35
}
36
36
}
37
- } catch (...) {
38
- _eof = true ;
39
- }
40
- }
41
- if (!currentBuffer) {
42
- currentBuffer = buffer[0 ];
43
- buffer.erase (buffer.begin ());
44
- lock.unlock ();
45
- bufferCondition.notify_one ();
46
- }
47
- } while (!quit);
37
+ bufferCondition.notify_one ();
38
+ } while (!quit && !_eof);
39
+ });
40
+ }
48
41
}
49
42
50
43
wrtc::binary BaseReader::read () {
@@ -60,13 +53,15 @@ namespace ntgcalls {
60
53
return nullptr ;
61
54
}
62
55
std::unique_lock lock (mutex);
63
- wrtc::binary res = nullptr ;
64
- bufferCondition.wait (lock, [this ]{
65
- return currentBuffer || quit || _eof;
56
+ bufferCondition.wait (lock, [this ] {
57
+ return !buffer.empty () || quit || _eof;
66
58
});
67
- res = currentBuffer;
68
- currentBuffer = nullptr ;
69
- return res;
59
+ if (buffer.empty ()) {
60
+ return nullptr ;
61
+ }
62
+ auto data = std::move (buffer.front ());
63
+ buffer.pop ();
64
+ return data;
70
65
}
71
66
72
67
void BaseReader::close () {
0 commit comments