]> git.sesse.net Git - cubemap/blob - stream.h
Always compile with -pthread.
[cubemap] / stream.h
1 #ifndef _STREAM_H
2 #define _STREAM_H 1
3
4 // Representation of a single, muxed (we only really care about bytes/blocks) stream.
5 // Fed by Input, sent out by Server (to Client).
6
7 #include <stddef.h>
8 #include <stdint.h>
9 #include <sys/types.h>
10 #include <sys/uio.h>
11 #include <deque>
12 #include <memory>
13 #include <mutex>
14 #include <string>
15 #include <vector>
16
17 #include "metacube2.h"
18
19 class StreamProto;
20 struct Client;
21
22 // metacube2_pts_packet except the type and byteswapping.
23 struct RationalPTS {
24         int64_t pts = 0;
25         uint64_t timebase_num = 0, timebase_den = 0;  // 0/0 for unknown PTS.
26 };
27
28 struct Stream {
29         // Must be in sync with StreamConfig::Encoding.
30         enum Encoding { STREAM_ENCODING_RAW = 0, STREAM_ENCODING_METACUBE };
31
32         Stream(const std::string &url,
33                size_t backlog_size,
34                uint64_t prebuffering_bytes,
35                Encoding encoding,
36                Encoding src_encoding,
37                unsigned hls_frag_duration,
38                size_t hls_backlog_margin,
39                const std::string &allow_origin);
40         ~Stream();
41
42         // Serialization/deserialization.
43         Stream(const StreamProto &serialized, int data_fd);
44         StreamProto serialize();
45
46         // Changes the backlog size, restructuring the data as needed.
47         void set_backlog_size(size_t new_size);
48
49         // You should hold the owning Server's <mutex>, since it calls add_data_raw().
50         // Sets unavailable to false.
51         void set_header(const std::string &new_http_header, const std::string &new_stream_header);
52
53         void set_unavailable() {
54                 unavailable = true;
55         }
56
57         // Mutex protecting <queued_data> and <queued_data_last_starting_point>.
58         // Note that if you want to hold both this and the owning server's
59         // <mutex> you will need to take <mutex> before this one.
60         mutable std::mutex queued_data_mutex;
61
62         std::string url;
63
64         // If true, the backend is not completely connected, and thus, we cannot serve
65         // clients (except for historic HLS fragments).
66         bool unavailable = true;
67
68         // The HTTP response header, without the trailing double newline.
69         std::string http_header;
70
71         // The video stream header (if any).
72         std::string stream_header;
73
74         // What encoding we apply to the outgoing data (usually raw, but can also
75         // be Metacube, for reflecting to another Cubemap instance).
76         Encoding encoding;
77
78         // What encoding we expect the incoming data to be in (usually Metacube).
79         Encoding src_encoding;
80
81         // Contents of CORS header (Access-Control-Allow-Origin), if any.
82         std::string allow_origin;
83
84         // The stream data itself, stored in a circular buffer.
85         //
86         // We store our data in a file, so that we can send the data to the
87         // kernel only once (with write()). We then use sendfile() for each
88         // client, which effectively zero-copies it out of the kernel's buffer
89         // cache. This is significantly more efficient than doing write() from
90         // a userspace memory buffer, since the latter makes the kernel copy
91         // the same data from userspace many times.
92         int data_fd;
93
94         // How many bytes <data_fd> can hold (the buffer size).
95         size_t backlog_size;
96
97         // How many bytes we need to have in the backlog before we start
98         // sending (in practice, we will then send all of them at once,
99         // and then start sending at the normal rate thereafter).
100         // This is basically to force a buffer on the client, which can help
101         // if the client expects us to be able to fill up the buffer much
102         // faster than realtime (ie., it expects a static file).
103         uint64_t prebuffering_bytes;
104
105         // How many bytes this stream have received. Can very well be larger
106         // than <backlog_size>, since the buffer wraps.
107         uint64_t bytes_received = 0;
108
109         // A list of points in the stream that is suitable to start new clients at
110         // (after having sent the header). Empty if no such point exists yet.
111         std::deque<uint64_t> suitable_starting_points;
112
113         // A list of HLS fragment boundaries currently in the backlog; the first fragment
114         // is between point 0 and 1, the second is between 1 and 2, and so on.
115         // This roughly mirrors suitable_starting_points, but we generally make much
116         // larger fragments (we try to get as close as possible without exceeding
117         // <hls_frag_duration> seconds by too much).
118         //
119         // We keep this list even if we don't have HLS, given that we have pts data
120         // from the input stream.
121         //
122         // NOTE: The last fragment is an in-progress fragment, which can still be
123         // extended and thus should not be output. So the last fragment output is
124         // from points N-3..N-2.
125         struct FragmentStart {
126                 uint64_t byte_position;
127                 double pts;  // Unused if begins_header is true.
128
129                 // Whether the fragment started at this position is a stream header or not.
130                 // Note that headers are stored _after_ the fragments they are headers for,
131                 // so that they rotate out of the backlog last (and also because they are
132                 // conveniently written then). The most current header is _not_ stored
133                 // in the backlog; it is stored in stream_header. Only when replaced
134                 // is it committed to the backlog and gets an entry here.
135                 bool begins_header;
136         };
137         std::deque<FragmentStart> fragments;
138         uint64_t first_fragment_index = 0, discontinuity_counter = 0;
139
140         // HLS target duration, in seconds.
141         unsigned hls_frag_duration = 6;
142
143         // Don't advertise new HLS fragments beginning before this point after the
144         // start of the backlog, so that we're reasonably sure that we can actually
145         // serve them even if the client can't completely keep up.
146         size_t hls_backlog_margin = 0;
147
148         // HLS playlists for this stream, in the form of a HTTP response, with
149         // headers and all. These are created on-demand, re-used by clients as
150         // needed, and cleared when they are no longer valid (e.g., when new fragments
151         // are added).
152         std::shared_ptr<const std::string> hls_playlist_http10;
153         std::shared_ptr<const std::string> hls_playlist_http11_close;
154         std::shared_ptr<const std::string> hls_playlist_http11_persistent;
155
156         // Clients that are in SENDING_DATA, but that we don't listen on,
157         // because we currently don't have any data for them.
158         // See put_client_to_sleep() and wake_up_all_clients().
159         std::vector<Client *> sleeping_clients;
160
161         // Clients that we recently got data for (when they were in
162         // <sleeping_clients>).
163         std::vector<Client *> to_process;
164
165         // Maximum pacing rate for the stream.
166         uint32_t pacing_rate = ~0U;
167
168         // Queued data, if any. Protected by <queued_data_mutex>.
169         // The data pointers in the iovec are owned by us.
170         struct DataElement {
171                 iovec data;
172                 uint16_t metacube_flags;
173                 RationalPTS pts;
174         };
175         std::vector<DataElement> queued_data;
176
177         // Put client to sleep, since there is no more data for it; we will on
178         // longer listen on POLLOUT until we get more data. Also, it will be put
179         // in the list of clients to wake up when we do.
180         void put_client_to_sleep(Client *client);
181
182         // Add more data to <queued_data>, adding Metacube headers if needed.
183         // Does not take ownership of <data>.
184         void add_data_deferred(const char *data, size_t bytes, uint16_t metacube_flags, const RationalPTS &pts);
185
186         // Add queued data to the stream, if any.
187         // You should hold the owning Server's <mutex>.
188         void process_queued_data();
189
190         // Generate a HLS playlist based on the current state, including HTTP headers.
191         std::shared_ptr<const std::string> generate_hls_playlist(bool http_11, bool close_after_response);
192
193         void clear_hls_playlist_cache();
194
195 private:
196         Stream(const Stream& other);
197
198         // Adds data directly to the stream file descriptor, without adding headers or
199         // going through <queued_data>.
200         // You should hold the owning Server's <mutex>, and probably call
201         // remove_obsolete_starting_points() afterwards.
202         void add_data_raw(const std::vector<DataElement> &data);
203
204         // Remove points from <suitable_starting_points> that are no longer
205         // in the backlog.
206         // You should hold the owning Server's <mutex>.
207         void remove_obsolete_starting_points();
208
209         // Extend the in-progress fragment to the given position, or finish it and start
210         // a new one if that would make it too long. Returns true if a new fragment
211         // was created (ie., the HLS playlists need to be regenerated).
212         bool add_fragment_boundary(size_t byte_position, const RationalPTS &pts);
213 };
214
215 #endif  // !defined(_STREAM_H)