You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

98 lines
2.3 KiB

/*
MediaMtx (C++) - stream (MediaMTX: internal/stream)
A Stream exists while the path's source is ready. The source writes units into it, the stream hands
every unit to all readers. Each reader has its own queue and thread (AsyncReader), so a slow reader
(e.g. a WebRTC client on a bad link, or the disk) never blocks the source or the other readers.
*/
#pragma once
#include <atomic>
#include <condition_variable>
#include <deque>
#include <functional>
#include <mutex>
#include <string>
#include <thread>
#include <vector>
#include "../logger/logger.h"
#include "../unit/unit.h"
namespace mtx {
struct StreamDesc
{
std::string codec = "H264";
Bytes sps;
Bytes pps;
int width = 0;
int height = 0;
};
class StreamReader
{
public:
virtual ~StreamReader() {}
// Called from the source thread: must not block
virtual void push(const UnitPtr & unit) = 0;
};
class Stream
{
public:
explicit Stream(const StreamDesc & desc);
void addReader(StreamReader * r);
void removeReader(StreamReader * r);
size_t readerCount() const;
// From the source: in-band SPS/PPS update the description
void writeUnit(const UnitPtr & unit);
StreamDesc desc() const;
uint64_t bytesReceived() const { return m_nBytes; }
private:
mutable std::mutex m_mutex;
StreamDesc m_desc;
std::vector<StreamReader *> m_readers;
std::atomic<uint64_t> m_nBytes{0};
};
/*
Reader with its own thread. The handler gets the units in order; when the queue overflows the units are
dropped and the handler gets units again from the next IDR (a decoder needs a random access point).
*/
class AsyncReader : public StreamReader
{
public:
typedef std::function<void(const UnitPtr &)> Handler;
AsyncReader(const LogParent * parent, size_t queueSize = 512);
~AsyncReader() override;
void start(Handler handler);
void stop();
void push(const UnitPtr & unit) override;
private:
void run();
const LogParent * m_pParent;
size_t m_nQueueSize;
Handler m_handler;
std::mutex m_mutex;
std::condition_variable m_cond;
std::deque<UnitPtr> m_queue;
bool m_bRun = false;
bool m_bWaitIdr = false;
uint64_t m_nDropped = 0;
int64_t m_tLastDropLog = 0;
std::thread m_thread;
};
int64_t nowMs();
int64_t nowUs();
} // namespace mtx