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