4 // A class dealing with stream output to HTTP.
7 #include <condition_variable>
15 #include <sys/types.h>
16 #include <unordered_map>
20 #include <libavutil/rational.h>
23 struct MHD_Connection;
28 // Returns a pair of content and content-type.
29 using EndpointCallback = std::function<std::pair<std::string, std::string>()>;
40 // Should be called before start().
41 void set_header(StreamType stream_type, const std::string &data) {
42 header[stream_type] = data;
45 // Should be called before start() (due to threading issues).
50 void add_endpoint(const std::string &url, const EndpointCallback &callback, CORSPolicy cors_policy)
52 endpoints[url] = Endpoint{ callback, cors_policy };
57 void add_data(StreamType stream_type, const char *buf, size_t size, bool keyframe, int64_t time, AVRational timebase);
58 int64_t get_num_connected_clients() const
60 return metric_num_connected_clients.load();
64 static int answer_to_connection_thunk(void *cls, MHD_Connection *connection,
65 const char *url, const char *method,
66 const char *version, const char *upload_data,
67 size_t *upload_data_size, void **con_cls);
69 int answer_to_connection(MHD_Connection *connection,
70 const char *url, const char *method,
71 const char *version, const char *upload_data,
72 size_t *upload_data_size, void **con_cls);
74 static void free_stream(void *cls);
82 Stream(HTTPD *parent, Framing framing, StreamType stream_type)
83 : parent(parent), framing(framing), stream_type(stream_type) {}
85 static ssize_t reader_callback_thunk(void *cls, uint64_t pos, char *buf, size_t max);
86 ssize_t reader_callback(uint64_t pos, char *buf, size_t max);
93 void add_data(const char *buf, size_t size, DataType data_type, int64_t time, AVRational timebase);
95 HTTPD *get_parent() const { return parent; }
96 StreamType get_stream_type() const { return stream_type; }
102 std::mutex buffer_mutex;
103 bool should_quit = false; // Under <buffer_mutex>.
104 std::condition_variable has_buffered_data;
105 std::deque<std::string> buffered_data; // Protected by <buffer_mutex>.
106 size_t used_of_buffered_data = 0; // How many bytes of the first element of <buffered_data> that is already used. Protected by <mutex>.
107 size_t seen_keyframe = false;
108 StreamType stream_type;
111 MHD_Daemon *mhd = nullptr;
112 std::mutex streams_mutex;
113 std::set<Stream *> streams; // Not owned.
115 EndpointCallback callback;
116 CORSPolicy cors_policy;
118 std::unordered_map<std::string, Endpoint> endpoints;
119 std::string header[NUM_STREAM_TYPES];
122 std::atomic<int64_t> metric_num_connected_clients{ 0 };
125 #endif // !defined(_HTTPD_H)