]> git.sesse.net Git - nageru/blob - mixer.h
Write 1.4.0 changelog.
[nageru] / mixer.h
1 #ifndef _MIXER_H
2 #define _MIXER_H 1
3
4 // The actual video mixer, running in its own separate background thread.
5
6 #include <assert.h>
7 #include <epoxy/gl.h>
8
9 #undef Success
10
11 #include <stdbool.h>
12 #include <stdint.h>
13 #include <atomic>
14 #include <chrono>
15 #include <condition_variable>
16 #include <cstddef>
17 #include <functional>
18 #include <map>
19 #include <memory>
20 #include <mutex>
21 #include <queue>
22 #include <string>
23 #include <thread>
24 #include <vector>
25
26 #include "audio_mixer.h"
27 #include "bmusb/bmusb.h"
28 #include "defs.h"
29 #include "httpd.h"
30 #include "input_state.h"
31 #include "libusb.h"
32 #include "pbo_frame_allocator.h"
33 #include "ref_counted_frame.h"
34 #include "ref_counted_gl_sync.h"
35 #include "theme.h"
36 #include "timebase.h"
37 #include "video_encoder.h"
38
39 class ALSAOutput;
40 class QSurface;
41
42 namespace movit {
43 class Effect;
44 class EffectChain;
45 class FlatInput;
46 class ResourcePool;
47 }  // namespace movit
48 class QSurfaceFormat;
49
50 // For any card that's not the master (where we pick out the frames as they
51 // come, as fast as we can process), there's going to be a queue. The question
52 // is when we should drop frames from that queue (apart from the obvious
53 // dropping if the 16-frame queue should become full), especially given that
54 // the frame rate could be lower or higher than the master (either subtly or
55 // dramatically). We have two (conflicting) demands:
56 //
57 //   1. We want to avoid starving the queue.
58 //   2. We don't want to add more delay than is needed.
59 //
60 // Our general strategy is to drop as many frames as we can (helping for #2)
61 // that we think is safe for #1 given jitter. To this end, we set a lower floor N,
62 // where we assume that if we have N frames in the queue, we're always safe from
63 // starvation. (Typically, N will be 0 or 1. It starts off at 0.) If we have
64 // more than N frames in the queue after reading out the one we need, we head-drop
65 // them to reduce the queue.
66 //
67 // N is reduced as follows: If the queue has had at least one spare frame for
68 // at least 50 (master) frames (ie., it's been too conservative for a second),
69 // we reduce N by 1 and reset the timers. TODO: Only do this if N ever actually
70 // touched the limit.
71 //
72 // Whenever the queue is starved (we needed a frame but there was none),
73 // and we've been at N since the last starvation, N was obviously too low,
74 // so we increment it. We will never set N above 5, though.
75 class QueueLengthPolicy {
76 public:
77         QueueLengthPolicy() {}
78         void reset(unsigned card_index) {
79                 this->card_index = card_index;
80                 safe_queue_length = 0;
81                 frames_with_at_least_one = 0;
82                 been_at_safe_point_since_last_starvation = false;
83         }
84
85         void update_policy(int queue_length);  // Give in -1 for starvation.
86         unsigned get_safe_queue_length() const { return safe_queue_length; }
87
88 private:
89         unsigned card_index;  // For debugging only.
90         unsigned safe_queue_length = 0;  // Called N in the comments.
91         unsigned frames_with_at_least_one = 0;
92         bool been_at_safe_point_since_last_starvation = false;
93 };
94
95 class Mixer {
96 public:
97         // The surface format is used for offscreen destinations for OpenGL contexts we need.
98         Mixer(const QSurfaceFormat &format, unsigned num_cards);
99         ~Mixer();
100         void start();
101         void quit();
102
103         void transition_clicked(int transition_num);
104         void channel_clicked(int preview_num);
105
106         enum Output {
107                 OUTPUT_LIVE = 0,
108                 OUTPUT_PREVIEW,
109                 OUTPUT_INPUT0,  // 1, 2, 3, up to 15 follow numerically.
110                 NUM_OUTPUTS = 18
111         };
112
113         struct DisplayFrame {
114                 // The chain for rendering this frame. To render a display frame,
115                 // first wait for <ready_fence>, then call <setup_chain>
116                 // to wire up all the inputs, and then finally call
117                 // chain->render_to_screen() or similar.
118                 movit::EffectChain *chain;
119                 std::function<void()> setup_chain;
120
121                 // Asserted when all the inputs are ready; you cannot render the chain
122                 // before this.
123                 RefCountedGLsync ready_fence;
124
125                 // Holds on to all the input frames needed for this display frame,
126                 // so they are not released while still rendering.
127                 std::vector<RefCountedFrame> input_frames;
128
129                 // Textures that should be released back to the resource pool
130                 // when this frame disappears, if any.
131                 // TODO: Refcount these as well?
132                 std::vector<GLuint> temp_textures;
133         };
134         // Implicitly frees the previous one if there's a new frame available.
135         bool get_display_frame(Output output, DisplayFrame *frame) {
136                 return output_channel[output].get_display_frame(frame);
137         }
138
139         typedef std::function<void()> new_frame_ready_callback_t;
140         void set_frame_ready_callback(Output output, new_frame_ready_callback_t callback)
141         {
142                 output_channel[output].set_frame_ready_callback(callback);
143         }
144
145         // TODO: Should this really be per-channel? Shouldn't it just be called for e.g. the live output?
146         typedef std::function<void(const std::vector<std::string> &)> transition_names_updated_callback_t;
147         void set_transition_names_updated_callback(Output output, transition_names_updated_callback_t callback)
148         {
149                 output_channel[output].set_transition_names_updated_callback(callback);
150         }
151
152         typedef std::function<void(const std::string &)> name_updated_callback_t;
153         void set_name_updated_callback(Output output, name_updated_callback_t callback)
154         {
155                 output_channel[output].set_name_updated_callback(callback);
156         }
157
158         typedef std::function<void(const std::string &)> color_updated_callback_t;
159         void set_color_updated_callback(Output output, color_updated_callback_t callback)
160         {
161                 output_channel[output].set_color_updated_callback(callback);
162         }
163
164         std::vector<std::string> get_transition_names()
165         {
166                 return theme->get_transition_names(pts());
167         }
168
169         unsigned get_num_channels() const
170         {
171                 return theme->get_num_channels();
172         }
173
174         std::string get_channel_name(unsigned channel) const
175         {
176                 return theme->get_channel_name(channel);
177         }
178
179         std::string get_channel_color(unsigned channel) const
180         {
181                 return theme->get_channel_color(channel);
182         }
183
184         int get_channel_signal(unsigned channel) const
185         {
186                 return theme->get_channel_signal(channel);
187         }
188
189         int map_signal(unsigned channel)
190         {
191                 return theme->map_signal(channel);
192         }
193
194         unsigned get_master_clock() const
195         {
196                 return master_clock_channel;
197         }
198
199         void set_master_clock(unsigned channel)
200         {
201                 master_clock_channel = channel;
202         }
203
204         void set_signal_mapping(int signal, int card)
205         {
206                 return theme->set_signal_mapping(signal, card);
207         }
208
209         bool get_supports_set_wb(unsigned channel) const
210         {
211                 return theme->get_supports_set_wb(channel);
212         }
213
214         void set_wb(unsigned channel, double r, double g, double b) const
215         {
216                 theme->set_wb(channel, r, g, b);
217         }
218
219         // Note: You can also get this through the global variable global_audio_mixer.
220         AudioMixer *get_audio_mixer() { return &audio_mixer; }
221         const AudioMixer *get_audio_mixer() const { return &audio_mixer; }
222
223         void schedule_cut()
224         {
225                 should_cut = true;
226         }
227
228         unsigned get_num_cards() const { return num_cards; }
229
230         std::string get_card_description(unsigned card_index) const {
231                 assert(card_index < num_cards);
232                 return cards[card_index].capture->get_description();
233         }
234
235         std::map<uint32_t, bmusb::VideoMode> get_available_video_modes(unsigned card_index) const {
236                 assert(card_index < num_cards);
237                 return cards[card_index].capture->get_available_video_modes();
238         }
239
240         uint32_t get_current_video_mode(unsigned card_index) const {
241                 assert(card_index < num_cards);
242                 return cards[card_index].capture->get_current_video_mode();
243         }
244
245         void set_video_mode(unsigned card_index, uint32_t mode) {
246                 assert(card_index < num_cards);
247                 cards[card_index].capture->set_video_mode(mode);
248         }
249
250         void start_mode_scanning(unsigned card_index);
251
252         std::map<uint32_t, std::string> get_available_video_inputs(unsigned card_index) const {
253                 assert(card_index < num_cards);
254                 return cards[card_index].capture->get_available_video_inputs();
255         }
256
257         uint32_t get_current_video_input(unsigned card_index) const {
258                 assert(card_index < num_cards);
259                 return cards[card_index].capture->get_current_video_input();
260         }
261
262         void set_video_input(unsigned card_index, uint32_t input) {
263                 assert(card_index < num_cards);
264                 cards[card_index].capture->set_video_input(input);
265         }
266
267         std::map<uint32_t, std::string> get_available_audio_inputs(unsigned card_index) const {
268                 assert(card_index < num_cards);
269                 return cards[card_index].capture->get_available_audio_inputs();
270         }
271
272         uint32_t get_current_audio_input(unsigned card_index) const {
273                 assert(card_index < num_cards);
274                 return cards[card_index].capture->get_current_audio_input();
275         }
276
277         void set_audio_input(unsigned card_index, uint32_t input) {
278                 assert(card_index < num_cards);
279                 cards[card_index].capture->set_audio_input(input);
280         }
281
282         void change_x264_bitrate(unsigned rate_kbit) {
283                 video_encoder->change_x264_bitrate(rate_kbit);
284         }
285
286 private:
287         void configure_card(unsigned card_index, bmusb::CaptureInterface *capture, bool is_fake_capture);
288         void bm_frame(unsigned card_index, uint16_t timecode,
289                 bmusb::FrameAllocator::Frame video_frame, size_t video_offset, bmusb::VideoFormat video_format,
290                 bmusb::FrameAllocator::Frame audio_frame, size_t audio_offset, bmusb::AudioFormat audio_format);
291         void bm_hotplug_add(libusb_device *dev);
292         void bm_hotplug_remove(unsigned card_index);
293         void place_rectangle(movit::Effect *resample_effect, movit::Effect *padding_effect, float x0, float y0, float x1, float y1);
294         void thread_func();
295         void handle_hotplugged_cards();
296         void schedule_audio_resampling_tasks(unsigned dropped_frames, int num_samples_per_frame, int length_per_frame);
297         void render_one_frame(int64_t duration);
298         void audio_thread_func();
299         void subsample_chroma(GLuint src_tex, GLuint dst_dst);
300         void release_display_frame(DisplayFrame *frame);
301         double pts() { return double(pts_int) / TIMEBASE; }
302
303         HTTPD httpd;
304         unsigned num_cards;
305
306         QSurface *mixer_surface, *h264_encoder_surface;
307         std::unique_ptr<movit::ResourcePool> resource_pool;
308         std::unique_ptr<Theme> theme;
309         std::atomic<unsigned> audio_source_channel{0};
310         std::atomic<unsigned> master_clock_channel{0};
311         std::unique_ptr<movit::EffectChain> display_chain;
312         GLuint cbcr_program_num;  // Owned by <resource_pool>.
313         GLuint cbcr_vbo;  // Holds position and texcoord data.
314         GLuint cbcr_position_attribute_index, cbcr_texcoord_attribute_index;
315         std::unique_ptr<VideoEncoder> video_encoder;
316
317         // Effects part of <display_chain>. Owned by <display_chain>.
318         movit::FlatInput *display_input;
319
320         int64_t pts_int = 0;  // In TIMEBASE units.
321
322         std::mutex bmusb_mutex;
323         bool has_bmusb_thread = false;
324         struct CaptureCard {
325                 bmusb::CaptureInterface *capture = nullptr;
326                 bool is_fake_capture;
327                 std::unique_ptr<PBOFrameAllocator> frame_allocator;
328
329                 // Stuff for the OpenGL context (for texture uploading).
330                 QSurface *surface = nullptr;
331
332                 struct NewFrame {
333                         RefCountedFrame frame;
334                         int64_t length;  // In TIMEBASE units.
335                         bool interlaced;
336                         unsigned field;  // Which field (0 or 1) of the frame to use. Always 0 for progressive.
337                         std::function<void()> upload_func;  // Needs to be called to actually upload the texture to OpenGL.
338                         unsigned dropped_frames = 0;  // Number of dropped frames before this one.
339                 };
340                 std::queue<NewFrame> new_frames;
341                 bool should_quit = false;
342                 std::condition_variable new_frames_changed;  // Set whenever new_frames (or should_quit) is changed.
343
344                 QueueLengthPolicy queue_length_policy;  // Refers to the "new_frames" queue.
345
346                 // Accumulated errors in number of 1/TIMEBASE samples. If OUTPUT_FREQUENCY divided by
347                 // frame rate is integer, will always stay zero.
348                 unsigned fractional_samples = 0;
349
350                 int last_timecode = -1;  // Unwrapped.
351         };
352         CaptureCard cards[MAX_VIDEO_CARDS];  // protected by <bmusb_mutex>
353         AudioMixer audio_mixer;  // Same as global_audio_mixer (see audio_mixer.h).
354         void get_one_frame_from_each_card(unsigned master_card_index, CaptureCard::NewFrame new_frames[MAX_VIDEO_CARDS], bool has_new_frame[MAX_VIDEO_CARDS], int num_samples[MAX_VIDEO_CARDS]);
355
356         InputState input_state;
357
358         // Cards we have been noticed about being hotplugged, but haven't tried adding yet.
359         // Protected by its own mutex.
360         std::mutex hotplug_mutex;
361         std::vector<libusb_device *> hotplugged_cards;
362
363         class OutputChannel {
364         public:
365                 ~OutputChannel();
366                 void output_frame(DisplayFrame frame);
367                 bool get_display_frame(DisplayFrame *frame);
368                 void set_frame_ready_callback(new_frame_ready_callback_t callback);
369                 void set_transition_names_updated_callback(transition_names_updated_callback_t callback);
370                 void set_name_updated_callback(name_updated_callback_t callback);
371                 void set_color_updated_callback(color_updated_callback_t callback);
372
373         private:
374                 friend class Mixer;
375
376                 unsigned channel;
377                 Mixer *parent = nullptr;  // Not owned.
378                 std::mutex frame_mutex;
379                 DisplayFrame current_frame, ready_frame;  // protected by <frame_mutex>
380                 bool has_current_frame = false, has_ready_frame = false;  // protected by <frame_mutex>
381                 new_frame_ready_callback_t new_frame_ready_callback;
382                 transition_names_updated_callback_t transition_names_updated_callback;
383                 name_updated_callback_t name_updated_callback;
384                 color_updated_callback_t color_updated_callback;
385
386                 std::vector<std::string> last_transition_names;
387                 std::string last_name, last_color;
388         };
389         OutputChannel output_channel[NUM_OUTPUTS];
390
391         std::thread mixer_thread;
392         std::thread audio_thread;
393         std::atomic<bool> should_quit{false};
394         std::atomic<bool> should_cut{false};
395
396         std::unique_ptr<ALSAOutput> alsa;
397
398         struct AudioTask {
399                 int64_t pts_int;
400                 int num_samples;
401                 bool adjust_rate;
402         };
403         std::mutex audio_mutex;
404         std::condition_variable audio_task_queue_changed;
405         std::queue<AudioTask> audio_task_queue;  // Under audio_mutex.
406
407         // For mode scanning.
408         bool is_mode_scanning[MAX_VIDEO_CARDS]{ false };
409         std::vector<uint32_t> mode_scanlist[MAX_VIDEO_CARDS];
410         unsigned mode_scanlist_index[MAX_VIDEO_CARDS]{ 0 };
411         std::chrono::steady_clock::time_point last_mode_scan_change[MAX_VIDEO_CARDS];
412 };
413
414 extern Mixer *global_mixer;
415 extern bool uses_mlock;
416
417 #endif  // !defined(_MIXER_H)