4 // A class dealing with stream output, both to HTTP (thus the class name)
5 // and to local output files. Since we generally have very few outputs
6 // (end clients are not meant to connect directly to our stream; it should be
7 // transcoded by something else and then sent to a reflector), we don't need to
8 // care a lot about performance. Thus, we solve this by the simplest possible
9 // way, namely having one ffmpeg mux per output.
11 #include <microhttpd.h>
14 #include <sys/types.h>
15 #include <condition_variable>
22 struct MHD_Connection;
25 #include <libavcodec/avcodec.h>
26 #include <libavformat/avformat.h>
27 #include <libavformat/avio.h>
34 enum PacketDestination {
35 DESTINATION_FILE_ONLY,
36 DESTINATION_HTTP_ONLY,
37 DESTINATION_FILE_AND_HTTP
40 HTTPD(int width, int height);
42 void add_packet(const AVPacket &pkt, int64_t pts, int64_t dts, PacketDestination destination);
44 // You can only have one going at the same time.
45 void open_output_file(const std::string &filename);
46 void close_output_file();
49 static int answer_to_connection_thunk(void *cls, MHD_Connection *connection,
50 const char *url, const char *method,
51 const char *version, const char *upload_data,
52 size_t *upload_data_size, void **con_cls);
54 int answer_to_connection(MHD_Connection *connection,
55 const char *url, const char *method,
56 const char *version, const char *upload_data,
57 size_t *upload_data_size, void **con_cls);
59 static void free_stream(void *cls);
61 static void request_completed_thunk(void *cls, struct MHD_Connection *connection, void **con_cls, enum MHD_RequestTerminationCode toe);
63 void request_completed(struct MHD_Connection *connection, void **con_cls, enum MHD_RequestTerminationCode toe);
68 Stream(AVOutputFormat *oformat, int width, int height, int time_base);
70 static ssize_t reader_callback_thunk(void *cls, uint64_t pos, char *buf, size_t max);
71 ssize_t reader_callback(uint64_t pos, char *buf, size_t max);
73 void add_packet(const AVPacket &pkt, int64_t pts, int64_t dts);
76 static int write_packet_thunk(void *opaque, uint8_t *buf, int buf_size);
77 int write_packet(uint8_t *buf, int buf_size);
79 std::mutex buffer_mutex;
80 std::condition_variable has_buffered_data;
81 std::deque<std::string> buffered_data; // Protected by <mutex>.
82 size_t used_of_buffered_data = 0; // How many bytes of the first element of <buffered_data> that is already used. Protected by <mutex>.
84 std::unique_ptr<Mux> mux; // Must come last to be destroyed before buffered_data, since the destructor can write bytes.
87 std::mutex streams_mutex;
88 std::set<Stream *> streams; // Not owned.
91 std::unique_ptr<Mux> file_mux; // To local disk.
94 #endif // !defined(_HTTPD_H)