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