4 // A class dealing with stream output to HTTP. Since we generally have very few outputs
5 // (end clients are not meant to connect directly to our stream; it should be
6 // transcoded by something else and then sent to a reflector), we don't need to
7 // care a lot about performance. Thus, we solve this by the simplest possible
8 // way, namely having one ffmpeg mux per output.
10 #include <microhttpd.h>
13 #include <sys/types.h>
14 #include <condition_variable>
21 struct MHD_Connection;
24 #include <libavcodec/avcodec.h>
25 #include <libavformat/avformat.h>
26 #include <libavformat/avio.h>
31 class HTTPD : public PacketDestination {
33 HTTPD(int width, int height);
35 void add_packet(const AVPacket &pkt, int64_t pts, int64_t dts) override;
38 static int answer_to_connection_thunk(void *cls, MHD_Connection *connection,
39 const char *url, const char *method,
40 const char *version, const char *upload_data,
41 size_t *upload_data_size, void **con_cls);
43 int answer_to_connection(MHD_Connection *connection,
44 const char *url, const char *method,
45 const char *version, const char *upload_data,
46 size_t *upload_data_size, void **con_cls);
48 static void free_stream(void *cls);
50 static void request_completed_thunk(void *cls, struct MHD_Connection *connection, void **con_cls, enum MHD_RequestTerminationCode toe);
52 void request_completed(struct MHD_Connection *connection, void **con_cls, enum MHD_RequestTerminationCode toe);
57 Stream(AVOutputFormat *oformat, int width, int height, int time_base, int bit_rate);
59 static ssize_t reader_callback_thunk(void *cls, uint64_t pos, char *buf, size_t max);
60 ssize_t reader_callback(uint64_t pos, char *buf, size_t max);
62 void add_packet(const AVPacket &pkt, int64_t pts, int64_t dts);
65 static int write_packet_thunk(void *opaque, uint8_t *buf, int buf_size);
66 int write_packet(uint8_t *buf, int buf_size);
68 std::mutex buffer_mutex;
69 std::condition_variable has_buffered_data;
70 std::deque<std::string> buffered_data; // Protected by <mutex>.
71 size_t used_of_buffered_data = 0; // How many bytes of the first element of <buffered_data> that is already used. Protected by <mutex>.
73 std::unique_ptr<Mux> mux; // Must come last to be destroyed before buffered_data, since the destructor can write bytes.
76 std::mutex streams_mutex;
77 std::set<Stream *> streams; // Not owned.
82 #endif // !defined(_HTTPD_H)