#include "stream.h" #include #include #include "../codecs/h264/h264.h" namespace mtx { int64_t nowMs() { return std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()).count(); } int64_t nowUs() { return std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); } Stream::Stream(const StreamDesc & desc) : m_desc(desc) {} void Stream::addReader(StreamReader * r) { std::lock_guard lock(m_mutex); m_readers.push_back(r); } void Stream::removeReader(StreamReader * r) { std::lock_guard lock(m_mutex); m_readers.erase(std::remove(m_readers.begin(), m_readers.end(), r), m_readers.end()); } size_t Stream::readerCount() const { std::lock_guard lock(m_mutex); return m_readers.size(); } StreamDesc Stream::desc() const { std::lock_guard lock(m_mutex); return m_desc; } void Stream::writeUnit(const UnitPtr & unit) { m_nBytes += unit->byteSize(); std::lock_guard lock(m_mutex); for (const Bytes & n : unit->nalus) { int t = h264::naluType(n); if (t == h264::NALU_SPS && n != m_desc.sps) { m_desc.sps = n; h264::SpsInfo tInfo; if (h264::parseSps(n, tInfo)) { m_desc.width = tInfo.width; m_desc.height = tInfo.height; } } else if (t == h264::NALU_PPS && n != m_desc.pps) { m_desc.pps = n; } } for (StreamReader * r : m_readers) { r->push(unit); } } AsyncReader::AsyncReader(const LogParent * parent, size_t queueSize) : m_pParent(parent), m_nQueueSize(queueSize) {} AsyncReader::~AsyncReader() { stop(); } void AsyncReader::start(Handler handler) { m_handler = std::move(handler); m_bRun = true; m_thread = std::thread(&AsyncReader::run, this); } void AsyncReader::stop() { { std::lock_guard lock(m_mutex); if (! m_bRun) { return; } m_bRun = false; } m_cond.notify_all(); if (m_thread.joinable()) { m_thread.join(); } } void AsyncReader::push(const UnitPtr & unit) { { std::lock_guard lock(m_mutex); if (! m_bRun) { return; } if (m_bWaitIdr) { if (! unit->idr) { return; } m_bWaitIdr = false; } if (m_queue.size() >= m_nQueueSize) { // Reader too slow: drop what is queued and resume at the next IDR m_nDropped += m_queue.size() + 1; m_queue.clear(); m_bWaitIdr = true; int64_t tNow = nowMs(); if (m_pParent != nullptr && tNow - m_tLastDropLog > 1000) { m_tLastDropLog = tNow; m_pParent->log(LogLevel::Warn, "reader is too slow, discarding %llu units", (unsigned long long) m_nDropped); m_nDropped = 0; } return; } m_queue.push_back(unit); } m_cond.notify_one(); } void AsyncReader::run() { while (true) { UnitPtr tUnit; { std::unique_lock lock(m_mutex); m_cond.wait(lock, [this] { return ! m_bRun || ! m_queue.empty(); }); if (! m_bRun) { return; } tUnit = m_queue.front(); m_queue.pop_front(); } m_handler(tUnit); } } } // namespace mtx