]> git.sesse.net Git - nageru/blob - mixer.h
Add a preview display to the frame analyzer window.
[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 ChromaSubsampler;
41 class DeckLinkOutput;
42 class QSurface;
43 class QSurfaceFormat;
44 class TimecodeRenderer;
45 class v210Converter;
46
47 namespace movit {
48 class Effect;
49 class EffectChain;
50 class ResourcePool;
51 class YCbCrInput;
52 }  // namespace movit
53
54 // For any card that's not the master (where we pick out the frames as they
55 // come, as fast as we can process), there's going to be a queue. The question
56 // is when we should drop frames from that queue (apart from the obvious
57 // dropping if the 16-frame queue should become full), especially given that
58 // the frame rate could be lower or higher than the master (either subtly or
59 // dramatically). We have two (conflicting) demands:
60 //
61 //   1. We want to avoid starving the queue.
62 //   2. We don't want to add more delay than is needed.
63 //
64 // Our general strategy is to drop as many frames as we can (helping for #2)
65 // that we think is safe for #1 given jitter. To this end, we set a lower floor N,
66 // where we assume that if we have N frames in the queue, we're always safe from
67 // starvation. (Typically, N will be 0 or 1. It starts off at 0.) If we have
68 // more than N frames in the queue after reading out the one we need, we head-drop
69 // them to reduce the queue.
70 //
71 // N is reduced as follows: If the queue has had at least one spare frame for
72 // at least 50 (master) frames (ie., it's been too conservative for a second),
73 // we reduce N by 1 and reset the timers.
74 //
75 // Whenever the queue is starved (we needed a frame but there was none),
76 // and we've been at N since the last starvation, N was obviously too low,
77 // so we increment it. We will never set N above 5, though.
78 class QueueLengthPolicy {
79 public:
80         QueueLengthPolicy() {}
81         void reset(unsigned card_index) {
82                 this->card_index = card_index;
83                 safe_queue_length = 1;
84                 frames_with_at_least_one = 0;
85                 been_at_safe_point_since_last_starvation = false;
86         }
87
88         void update_policy(unsigned queue_length);  // Call before picking out a frame, so 0 means starvation.
89         unsigned get_safe_queue_length() const { return safe_queue_length; }
90
91 private:
92         unsigned card_index;  // For debugging only.
93         unsigned safe_queue_length = 1;  // Called N in the comments. Can never go below 1.
94         unsigned frames_with_at_least_one = 0;
95         bool been_at_safe_point_since_last_starvation = false;
96 };
97
98 class Mixer {
99 public:
100         // The surface format is used for offscreen destinations for OpenGL contexts we need.
101         Mixer(const QSurfaceFormat &format, unsigned num_cards);
102         ~Mixer();
103         void start();
104         void quit();
105
106         void transition_clicked(int transition_num);
107         void channel_clicked(int preview_num);
108
109         enum Output {
110                 OUTPUT_LIVE = 0,
111                 OUTPUT_PREVIEW,
112                 OUTPUT_INPUT0,  // 1, 2, 3, up to 15 follow numerically.
113                 NUM_OUTPUTS = 18
114         };
115
116         struct DisplayFrame {
117                 // The chain for rendering this frame. To render a display frame,
118                 // first wait for <ready_fence>, then call <setup_chain>
119                 // to wire up all the inputs, and then finally call
120                 // chain->render_to_screen() or similar.
121                 movit::EffectChain *chain;
122                 std::function<void()> setup_chain;
123
124                 // Asserted when all the inputs are ready; you cannot render the chain
125                 // before this.
126                 RefCountedGLsync ready_fence;
127
128                 // Holds on to all the input frames needed for this display frame,
129                 // so they are not released while still rendering.
130                 std::vector<RefCountedFrame> input_frames;
131
132                 // Textures that should be released back to the resource pool
133                 // when this frame disappears, if any.
134                 // TODO: Refcount these as well?
135                 std::vector<GLuint> temp_textures;
136         };
137         // Implicitly frees the previous one if there's a new frame available.
138         bool get_display_frame(Output output, DisplayFrame *frame) {
139                 return output_channel[output].get_display_frame(frame);
140         }
141
142         // NOTE: Callbacks will be called with a mutex held, so you should probably
143         // not do real work in them.
144         typedef std::function<void()> new_frame_ready_callback_t;
145         void add_frame_ready_callback(Output output, void *key, new_frame_ready_callback_t callback)
146         {
147                 output_channel[output].add_frame_ready_callback(key, callback);
148         }
149
150         void remove_frame_ready_callback(Output output, void *key)
151         {
152                 output_channel[output].remove_frame_ready_callback(key);
153         }
154
155         // TODO: Should this really be per-channel? Shouldn't it just be called for e.g. the live output?
156         typedef std::function<void(const std::vector<std::string> &)> transition_names_updated_callback_t;
157         void set_transition_names_updated_callback(Output output, transition_names_updated_callback_t callback)
158         {
159                 output_channel[output].set_transition_names_updated_callback(callback);
160         }
161
162         typedef std::function<void(const std::string &)> name_updated_callback_t;
163         void set_name_updated_callback(Output output, name_updated_callback_t callback)
164         {
165                 output_channel[output].set_name_updated_callback(callback);
166         }
167
168         typedef std::function<void(const std::string &)> color_updated_callback_t;
169         void set_color_updated_callback(Output output, color_updated_callback_t callback)
170         {
171                 output_channel[output].set_color_updated_callback(callback);
172         }
173
174         std::vector<std::string> get_transition_names()
175         {
176                 return theme->get_transition_names(pts());
177         }
178
179         unsigned get_num_channels() const
180         {
181                 return theme->get_num_channels();
182         }
183
184         std::string get_channel_name(unsigned channel) const
185         {
186                 return theme->get_channel_name(channel);
187         }
188
189         std::string get_channel_color(unsigned channel) const
190         {
191                 return theme->get_channel_color(channel);
192         }
193
194         int get_channel_signal(unsigned channel) const
195         {
196                 return theme->get_channel_signal(channel);
197         }
198
199         int map_signal(unsigned channel)
200         {
201                 return theme->map_signal(channel);
202         }
203
204         unsigned get_master_clock() const
205         {
206                 return master_clock_channel;
207         }
208
209         void set_master_clock(unsigned channel)
210         {
211                 master_clock_channel = channel;
212         }
213
214         void set_signal_mapping(int signal, int card)
215         {
216                 return theme->set_signal_mapping(signal, card);
217         }
218
219         bool get_supports_set_wb(unsigned channel) const
220         {
221                 return theme->get_supports_set_wb(channel);
222         }
223
224         void set_wb(unsigned channel, double r, double g, double b) const
225         {
226                 theme->set_wb(channel, r, g, b);
227         }
228
229         // Note: You can also get this through the global variable global_audio_mixer.
230         AudioMixer *get_audio_mixer() { return &audio_mixer; }
231         const AudioMixer *get_audio_mixer() const { return &audio_mixer; }
232
233         void schedule_cut()
234         {
235                 should_cut = true;
236         }
237
238         unsigned get_num_cards() const { return num_cards; }
239
240         std::string get_card_description(unsigned card_index) const {
241                 assert(card_index < num_cards);
242                 return cards[card_index].capture->get_description();
243         }
244
245         // The difference between this and the previous function is that if a card
246         // is used as the current output, get_card_description() will return the
247         // fake card that's replacing it for input, whereas this function will return
248         // the card's actual name.
249         std::string get_output_card_description(unsigned card_index) const {
250                 assert(card_can_be_used_as_output(card_index));
251                 assert(card_index < num_cards);
252                 if (cards[card_index].parked_capture) {
253                         return cards[card_index].parked_capture->get_description();
254                 } else {
255                         return cards[card_index].capture->get_description();
256                 }
257         }
258
259         bool card_can_be_used_as_output(unsigned card_index) const {
260                 assert(card_index < num_cards);
261                 return cards[card_index].output != nullptr;
262         }
263
264         std::map<uint32_t, bmusb::VideoMode> get_available_video_modes(unsigned card_index) const {
265                 assert(card_index < num_cards);
266                 return cards[card_index].capture->get_available_video_modes();
267         }
268
269         uint32_t get_current_video_mode(unsigned card_index) const {
270                 assert(card_index < num_cards);
271                 return cards[card_index].capture->get_current_video_mode();
272         }
273
274         void set_video_mode(unsigned card_index, uint32_t mode) {
275                 assert(card_index < num_cards);
276                 cards[card_index].capture->set_video_mode(mode);
277         }
278
279         void start_mode_scanning(unsigned card_index);
280
281         std::map<uint32_t, std::string> get_available_video_inputs(unsigned card_index) const {
282                 assert(card_index < num_cards);
283                 return cards[card_index].capture->get_available_video_inputs();
284         }
285
286         uint32_t get_current_video_input(unsigned card_index) const {
287                 assert(card_index < num_cards);
288                 return cards[card_index].capture->get_current_video_input();
289         }
290
291         void set_video_input(unsigned card_index, uint32_t input) {
292                 assert(card_index < num_cards);
293                 cards[card_index].capture->set_video_input(input);
294         }
295
296         std::map<uint32_t, std::string> get_available_audio_inputs(unsigned card_index) const {
297                 assert(card_index < num_cards);
298                 return cards[card_index].capture->get_available_audio_inputs();
299         }
300
301         uint32_t get_current_audio_input(unsigned card_index) const {
302                 assert(card_index < num_cards);
303                 return cards[card_index].capture->get_current_audio_input();
304         }
305
306         void set_audio_input(unsigned card_index, uint32_t input) {
307                 assert(card_index < num_cards);
308                 cards[card_index].capture->set_audio_input(input);
309         }
310
311         void change_x264_bitrate(unsigned rate_kbit) {
312                 video_encoder->change_x264_bitrate(rate_kbit);
313         }
314
315         int get_output_card_index() const {  // -1 = no output, just stream.
316                 return desired_output_card_index;
317         }
318
319         void set_output_card(int card_index) { // -1 = no output, just stream.
320                 desired_output_card_index = card_index;
321         }
322
323         std::map<uint32_t, bmusb::VideoMode> get_available_output_video_modes() const;
324
325         uint32_t get_output_video_mode() const {
326                 return desired_output_video_mode;
327         }
328
329         void set_output_video_mode(uint32_t mode) {
330                 desired_output_video_mode = mode;
331         }
332
333         void set_display_timecode_in_stream(bool enable) {
334                 display_timecode_in_stream = enable;
335         }
336
337         void set_display_timecode_on_stdout(bool enable) {
338                 display_timecode_on_stdout = enable;
339         }
340
341 private:
342         struct CaptureCard;
343
344         enum class CardType {
345                 LIVE_CARD,
346                 FAKE_CAPTURE,
347                 FFMPEG_INPUT
348         };
349         void configure_card(unsigned card_index, bmusb::CaptureInterface *capture, CardType card_type, DeckLinkOutput *output);
350         void set_output_card_internal(int card_index);  // Should only be called from the mixer thread.
351         void bm_frame(unsigned card_index, uint16_t timecode,
352                 bmusb::FrameAllocator::Frame video_frame, size_t video_offset, bmusb::VideoFormat video_format,
353                 bmusb::FrameAllocator::Frame audio_frame, size_t audio_offset, bmusb::AudioFormat audio_format);
354         void bm_hotplug_add(libusb_device *dev);
355         void bm_hotplug_remove(unsigned card_index);
356         void place_rectangle(movit::Effect *resample_effect, movit::Effect *padding_effect, float x0, float y0, float x1, float y1);
357         void thread_func();
358         void handle_hotplugged_cards();
359         void schedule_audio_resampling_tasks(unsigned dropped_frames, int num_samples_per_frame, int length_per_frame, bool is_preroll, std::chrono::steady_clock::time_point frame_timestamp);
360         std::string get_timecode_text() const;
361         void render_one_frame(int64_t duration);
362         void audio_thread_func();
363         void release_display_frame(DisplayFrame *frame);
364         double pts() { return double(pts_int) / TIMEBASE; }
365         // Call this _before_ trying to pull out a frame from a capture card;
366         // it will update the policy and drop the right amount of frames for you.
367         void trim_queue(CaptureCard *card, unsigned card_index);
368
369         HTTPD httpd;
370         unsigned num_cards, num_video_inputs;
371
372         QSurface *mixer_surface, *h264_encoder_surface, *decklink_output_surface;
373         std::unique_ptr<movit::ResourcePool> resource_pool;
374         std::unique_ptr<Theme> theme;
375         std::atomic<unsigned> audio_source_channel{0};
376         std::atomic<int> master_clock_channel{0};  // Gets overridden by <output_card_index> if set.
377         int output_card_index = -1;  // -1 for none.
378         uint32_t output_video_mode = -1;
379
380         // The mechanics of changing the output card and modes are so intricately connected
381         // with the work the mixer thread is doing. Thus, we don't change it directly,
382         // we just set this variable instead, which signals to the mixer thread that
383         // it should do the change before the next frame. This simplifies locking
384         // considerations immensely.
385         std::atomic<int> desired_output_card_index{-1};
386         std::atomic<uint32_t> desired_output_video_mode{0};
387
388         std::unique_ptr<movit::EffectChain> display_chain;
389         std::unique_ptr<ChromaSubsampler> chroma_subsampler;
390         std::unique_ptr<v210Converter> v210_converter;
391         std::unique_ptr<VideoEncoder> video_encoder;
392
393         std::unique_ptr<TimecodeRenderer> timecode_renderer;
394         std::atomic<bool> display_timecode_in_stream{false};
395         std::atomic<bool> display_timecode_on_stdout{false};
396
397         // Effects part of <display_chain>. Owned by <display_chain>.
398         movit::YCbCrInput *display_input;
399
400         int64_t pts_int = 0;  // In TIMEBASE units.
401         unsigned frame_num = 0;
402
403         // Accumulated errors in number of 1/TIMEBASE audio samples. If OUTPUT_FREQUENCY divided by
404         // frame rate is integer, will always stay zero.
405         unsigned fractional_samples = 0;
406
407         mutable std::mutex card_mutex;
408         bool has_bmusb_thread = false;
409         struct CaptureCard {
410                 std::unique_ptr<bmusb::CaptureInterface> capture;
411                 bool is_fake_capture;
412                 std::unique_ptr<DeckLinkOutput> output;
413
414                 // If this card is used for output (ie., output_card_index points to it),
415                 // it cannot simultaneously be uesd for capture, so <capture> gets replaced
416                 // by a FakeCapture. However, since reconstructing the real capture object
417                 // with all its state can be annoying, it is not being deleted, just stopped
418                 // and moved here.
419                 std::unique_ptr<bmusb::CaptureInterface> parked_capture;
420
421                 std::unique_ptr<PBOFrameAllocator> frame_allocator;
422
423                 // Stuff for the OpenGL context (for texture uploading).
424                 QSurface *surface = nullptr;
425
426                 struct NewFrame {
427                         RefCountedFrame frame;
428                         int64_t length;  // In TIMEBASE units.
429                         bool interlaced;
430                         unsigned field;  // Which field (0 or 1) of the frame to use. Always 0 for progressive.
431                         std::function<void()> upload_func;  // Needs to be called to actually upload the texture to OpenGL.
432                         unsigned dropped_frames = 0;  // Number of dropped frames before this one.
433                         std::chrono::steady_clock::time_point received_timestamp = std::chrono::steady_clock::time_point::min();
434                 };
435                 std::deque<NewFrame> new_frames;
436                 bool should_quit = false;
437                 std::condition_variable new_frames_changed;  // Set whenever new_frames (or should_quit) is changed.
438
439                 QueueLengthPolicy queue_length_policy;  // Refers to the "new_frames" queue.
440
441                 int last_timecode = -1;  // Unwrapped.
442         };
443         CaptureCard cards[MAX_VIDEO_CARDS];  // Protected by <card_mutex>.
444         AudioMixer audio_mixer;  // Same as global_audio_mixer (see audio_mixer.h).
445         bool input_card_is_master_clock(unsigned card_index, unsigned master_card_index) const;
446         struct OutputFrameInfo {
447                 int dropped_frames;  // Since last frame.
448                 int num_samples;  // Audio samples needed for this output frame.
449                 int64_t frame_duration;  // In TIMEBASE units.
450                 bool is_preroll;
451                 std::chrono::steady_clock::time_point frame_timestamp;
452         };
453         OutputFrameInfo get_one_frame_from_each_card(unsigned master_card_index, bool master_card_is_output, CaptureCard::NewFrame new_frames[MAX_VIDEO_CARDS], bool has_new_frame[MAX_VIDEO_CARDS]);
454
455         InputState input_state;
456
457         // Cards we have been noticed about being hotplugged, but haven't tried adding yet.
458         // Protected by its own mutex.
459         std::mutex hotplug_mutex;
460         std::vector<libusb_device *> hotplugged_cards;
461
462         class OutputChannel {
463         public:
464                 ~OutputChannel();
465                 void output_frame(DisplayFrame frame);
466                 bool get_display_frame(DisplayFrame *frame);
467                 void add_frame_ready_callback(void *key, new_frame_ready_callback_t callback);
468                 void remove_frame_ready_callback(void *key);
469                 void set_transition_names_updated_callback(transition_names_updated_callback_t callback);
470                 void set_name_updated_callback(name_updated_callback_t callback);
471                 void set_color_updated_callback(color_updated_callback_t callback);
472
473         private:
474                 friend class Mixer;
475
476                 unsigned channel;
477                 Mixer *parent = nullptr;  // Not owned.
478                 std::mutex frame_mutex;
479                 DisplayFrame current_frame, ready_frame;  // protected by <frame_mutex>
480                 bool has_current_frame = false, has_ready_frame = false;  // protected by <frame_mutex>
481                 std::map<void *, new_frame_ready_callback_t> new_frame_ready_callbacks;  // protected by <frame_mutex>
482                 transition_names_updated_callback_t transition_names_updated_callback;
483                 name_updated_callback_t name_updated_callback;
484                 color_updated_callback_t color_updated_callback;
485
486                 std::vector<std::string> last_transition_names;
487                 std::string last_name, last_color;
488         };
489         OutputChannel output_channel[NUM_OUTPUTS];
490
491         std::thread mixer_thread;
492         std::thread audio_thread;
493         std::atomic<bool> should_quit{false};
494         std::atomic<bool> should_cut{false};
495
496         std::unique_ptr<ALSAOutput> alsa;
497
498         struct AudioTask {
499                 int64_t pts_int;
500                 int num_samples;
501                 bool adjust_rate;
502                 std::chrono::steady_clock::time_point frame_timestamp;
503         };
504         std::mutex audio_mutex;
505         std::condition_variable audio_task_queue_changed;
506         std::queue<AudioTask> audio_task_queue;  // Under audio_mutex.
507
508         // For mode scanning.
509         bool is_mode_scanning[MAX_VIDEO_CARDS]{ false };
510         std::vector<uint32_t> mode_scanlist[MAX_VIDEO_CARDS];
511         unsigned mode_scanlist_index[MAX_VIDEO_CARDS]{ 0 };
512         std::chrono::steady_clock::time_point last_mode_scan_change[MAX_VIDEO_CARDS];
513 };
514
515 extern Mixer *global_mixer;
516 extern bool uses_mlock;
517
518 #endif  // !defined(_MIXER_H)