]> git.sesse.net Git - nageru/blob - nageru/mixer.cpp
Set CEF autoplay policy to be more lenient.
[nageru] / nageru / mixer.cpp
1 #include "mixer.h"
2
3 #include <X11/Xlib.h>
4 #include <algorithm>
5 #include <assert.h>
6 #include <chrono>
7 #include <condition_variable>
8 #include <epoxy/egl.h>
9 #include <functional>
10 #include <iterator>
11 #include <map>
12 #include <math.h>
13 #include <memory>
14 #include <movit/effect.h>
15 #include <movit/effect_chain.h>
16 #include <movit/effect_util.h>
17 #include <movit/flat_input.h>
18 #include <movit/image_format.h>
19 #include <movit/init.h>
20 #include <movit/resource_pool.h>
21 #include <movit/util.h>
22 #include <movit/ycbcr.h>
23 #include <movit/ycbcr_input.h>
24 #include <mutex>
25 #include <netinet/in.h>
26 #include <pthread.h>
27 #include <stddef.h>
28 #include <stdint.h>
29 #include <stdint.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <string>
34 #include <sys/socket.h>
35 #include <sys/syslog.h>
36 #include <thread>
37 #include <utility>
38 #include <vector>
39
40 #include "DeckLinkAPI.h"
41 #include "LinuxCOM.h"
42 #include "alsa_output.h"
43 #include "audio_mixer.h"
44 #include "basic_stats.h"
45 #include "bmusb/bmusb.h"
46 #include "bmusb/fake_capture.h"
47 #ifdef HAVE_CEF
48 #undef LOG_INFO
49 #undef LOG_WARNING
50 #include "cef_capture.h"
51 #endif
52 #include "card_type.h"
53 #include "chroma_subsampler.h"
54 #include "decklink_capture.h"
55 #include "decklink_output.h"
56 #include "decklink_util.h"
57 #include "defs.h"
58 #include "ffmpeg_capture.h"
59 #include "flags.h"
60 #include "image_input.h"
61 #include "input_mapping.h"
62 #include "input_state.h"
63 #include "libusb.h"
64 #include "mjpeg_encoder.h"
65 #include "pbo_frame_allocator.h"
66 #include "queue_length_policy.h"
67 #include "resampling_queue.h"
68 #include "shared/context.h"
69 #include "shared/disk_space_estimator.h"
70 #include "shared/metrics.h"
71 #include "shared/ref_counted_gl_sync.h"
72 #include "shared/shared_defs.h"
73 #include "shared/timebase.h"
74 #include "theme.h"
75 #include "timecode_renderer.h"
76 #include "v210_converter.h"
77 #include "video_encoder.h"
78 #include "ycbcr_interpretation.h"
79
80 #undef Status
81 #include <google/protobuf/util/json_util.h>
82 #include "json.pb.h"
83
84 #ifdef HAVE_SRT
85 // Must come after CEF, since it includes <syslog.h>, which has #defines
86 // that conflict with CEF logging constants.
87 #include <srt/srt.h>
88 #endif
89
90 class IDeckLink;
91 class QOpenGLContext;
92
93 using namespace movit;
94 using namespace std;
95 using namespace std::chrono;
96 using namespace std::placeholders;
97 using namespace bmusb;
98
99 Mixer *global_mixer = nullptr;
100
101 namespace {
102
103 void insert_new_frame(RefCountedFrame frame, unsigned field_num, bool interlaced, unsigned card_index, InputState *input_state)
104 {
105         if (interlaced) {
106                 for (unsigned frame_num = FRAME_HISTORY_LENGTH; frame_num --> 1; ) {  // :-)
107                         input_state->buffered_frames[card_index][frame_num] =
108                                 input_state->buffered_frames[card_index][frame_num - 1];
109                 }
110                 input_state->buffered_frames[card_index][0] = { frame, field_num };
111         } else {
112                 for (unsigned frame_num = 0; frame_num < FRAME_HISTORY_LENGTH; ++frame_num) {
113                         input_state->buffered_frames[card_index][frame_num] = { frame, field_num };
114                 }
115         }
116 }
117
118 void ensure_texture_resolution(PBOFrameAllocator::Userdata *userdata, unsigned field, unsigned width, unsigned height, unsigned cbcr_width, unsigned cbcr_height, unsigned v210_width)
119 {
120         bool first;
121         switch (userdata->pixel_format) {
122         case PixelFormat_10BitYCbCr:
123                 first = userdata->tex_v210[field] == 0 || userdata->tex_444[field] == 0;
124                 break;
125         case PixelFormat_8BitYCbCr:
126                 first = userdata->tex_y[field] == 0 || userdata->tex_cbcr[field] == 0;
127                 break;
128         case PixelFormat_8BitBGRA:
129                 first = userdata->tex_rgba[field] == 0;
130                 break;
131         case PixelFormat_8BitYCbCrPlanar:
132                 first = userdata->tex_y[field] == 0 || userdata->tex_cb[field] == 0 || userdata->tex_cr[field] == 0;
133                 break;
134         default:
135                 assert(false);
136         }
137
138         const bool recreate_main_texture =
139                 first ||
140                 width != userdata->last_width[field] ||
141                 height != userdata->last_height[field] ||
142                 cbcr_width != userdata->last_cbcr_width[field] ||
143                 cbcr_height != userdata->last_cbcr_height[field];
144         const bool recreate_v210_texture =
145                 global_flags.bit_depth > 8 &&
146                 (first || v210_width != userdata->last_v210_width[field] || height != userdata->last_height[field]);
147
148         if (recreate_main_texture) {
149                 // We changed resolution since last use of this texture, so we need to create
150                 // a new object. Note that this each card has its own PBOFrameAllocator,
151                 // we don't need to worry about these flip-flopping between resolutions.
152                 switch (userdata->pixel_format) {
153                 case PixelFormat_10BitYCbCr:
154                         glBindTexture(GL_TEXTURE_2D, userdata->tex_444[field]);
155                         check_error();
156                         glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB10_A2, width, height, 0, GL_RGBA, GL_UNSIGNED_INT_2_10_10_10_REV, nullptr);
157                         check_error();
158                         break;
159                 case PixelFormat_8BitYCbCr: {
160                         glBindTexture(GL_TEXTURE_2D, userdata->tex_cbcr[field]);
161                         check_error();
162                         glTexImage2D(GL_TEXTURE_2D, 0, GL_RG8, cbcr_width, height, 0, GL_RG, GL_UNSIGNED_BYTE, nullptr);
163                         check_error();
164                         glBindTexture(GL_TEXTURE_2D, userdata->tex_y[field]);
165                         check_error();
166                         glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, width, height, 0, GL_RED, GL_UNSIGNED_BYTE, nullptr);
167                         check_error();
168                         break;
169                 }
170                 case PixelFormat_8BitYCbCrPlanar: {
171                         glBindTexture(GL_TEXTURE_2D, userdata->tex_y[field]);
172                         check_error();
173                         glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, width, height, 0, GL_RED, GL_UNSIGNED_BYTE, nullptr);
174                         check_error();
175                         glBindTexture(GL_TEXTURE_2D, userdata->tex_cb[field]);
176                         check_error();
177                         glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, cbcr_width, cbcr_height, 0, GL_RED, GL_UNSIGNED_BYTE, nullptr);
178                         check_error();
179                         glBindTexture(GL_TEXTURE_2D, userdata->tex_cr[field]);
180                         check_error();
181                         glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, cbcr_width, cbcr_height, 0, GL_RED, GL_UNSIGNED_BYTE, nullptr);
182                         check_error();
183                         break;
184                 }
185                 case PixelFormat_8BitBGRA:
186                         glBindTexture(GL_TEXTURE_2D, userdata->tex_rgba[field]);
187                         check_error();
188                         // NOTE: sRGB may be disabled by sRGBSwitchingFlatInput.
189                         glTexImage2D(GL_TEXTURE_2D, 0, GL_SRGB8_ALPHA8, width, height, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, nullptr);
190                         check_error();
191                         break;
192                 default:
193                         assert(false);
194                 }
195                 userdata->last_width[field] = width;
196                 userdata->last_height[field] = height;
197                 userdata->last_cbcr_width[field] = cbcr_width;
198                 userdata->last_cbcr_height[field] = cbcr_height;
199         }
200         if (recreate_v210_texture) {
201                 // Same as above; we need to recreate the texture.
202                 glBindTexture(GL_TEXTURE_2D, userdata->tex_v210[field]);
203                 check_error();
204                 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB10_A2, v210_width, height, 0, GL_RGBA, GL_UNSIGNED_INT_2_10_10_10_REV, nullptr);
205                 check_error();
206                 userdata->last_v210_width[field] = v210_width;
207                 userdata->last_height[field] = height;
208         }
209 }
210
211 void upload_texture(GLuint tex, GLuint width, GLuint height, GLuint stride, bool interlaced_stride, GLenum format, GLenum type, GLintptr offset)
212 {
213         if (interlaced_stride) {
214                 stride *= 2;
215         }
216         if (global_flags.flush_pbos) {
217                 glFlushMappedBufferRange(GL_PIXEL_UNPACK_BUFFER, offset, stride * height);
218                 check_error();
219         }
220
221         glBindTexture(GL_TEXTURE_2D, tex);
222         check_error();
223         if (interlaced_stride) {
224                 glPixelStorei(GL_UNPACK_ROW_LENGTH, width * 2);
225                 check_error();
226         } else {
227                 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
228                 check_error();
229         }
230
231         glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, format, type, BUFFER_OFFSET(offset));
232         check_error();
233         glBindTexture(GL_TEXTURE_2D, 0);
234         check_error();
235         glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
236         check_error();
237 }
238
239 }  // namespace
240
241 void JitterHistory::register_metrics(const vector<pair<string, string>> &labels)
242 {
243         global_metrics.add("input_underestimated_jitter_frames", labels, &metric_input_underestimated_jitter_frames);
244         global_metrics.add("input_estimated_max_jitter_seconds", labels, &metric_input_estimated_max_jitter_seconds, Metrics::TYPE_GAUGE);
245 }
246
247 void JitterHistory::unregister_metrics(const vector<pair<string, string>> &labels)
248 {
249         global_metrics.remove("input_underestimated_jitter_frames", labels);
250         global_metrics.remove("input_estimated_max_jitter_seconds", labels);
251 }
252
253 void JitterHistory::frame_arrived(steady_clock::time_point now, int64_t frame_duration, size_t dropped_frames)
254 {
255         if (frame_duration != last_duration) {
256                 // If the frame rate changed, the input clock is also going to change,
257                 // so our historical data doesn't make much sense anymore.
258                 // Also, format changes typically introduce blips that are not representative
259                 // of the typical frame stream. (We make the assumption that format changes
260                 // don't happen all the time in regular use; if they did, we should probably
261                 // rather keep the history so that we take jitter they may introduce into account.)
262                 clear();
263                 last_duration = frame_duration;
264         }
265         if (expected_timestamp > steady_clock::time_point::min()) {
266                 expected_timestamp += dropped_frames * nanoseconds(frame_duration * 1000000000 / TIMEBASE);
267                 double jitter_seconds = fabs(duration<double>(expected_timestamp - now).count());
268                 history.push_back(orders.insert(jitter_seconds));
269                 if (jitter_seconds > estimate_max_jitter()) {
270                         ++metric_input_underestimated_jitter_frames;
271                 }
272
273                 metric_input_estimated_max_jitter_seconds = estimate_max_jitter();
274
275                 if (history.size() > history_length) {
276                         orders.erase(history.front());
277                         history.pop_front();
278                 }
279                 assert(history.size() <= history_length);
280         }
281         expected_timestamp = now + nanoseconds(frame_duration * 1000000000 / TIMEBASE);
282 }
283
284 double JitterHistory::estimate_max_jitter() const
285 {
286         if (orders.empty()) {
287                 return 0.0;
288         }
289         size_t elem_idx = lrint((orders.size() - 1) * percentile);
290         if (percentile <= 0.5) {
291                 return *next(orders.begin(), elem_idx) * multiplier;
292         } else {
293                 return *prev(orders.end(), orders.size() - elem_idx) * multiplier;
294         }
295 }
296
297 void QueueLengthPolicy::register_metrics(const vector<pair<string, string>> &labels)
298 {
299         global_metrics.add("input_queue_safe_length_frames", labels, &metric_input_queue_safe_length_frames, Metrics::TYPE_GAUGE);
300 }
301
302 void QueueLengthPolicy::unregister_metrics(const vector<pair<string, string>> &labels)
303 {
304         global_metrics.remove("input_queue_safe_length_frames", labels);
305 }
306
307 void QueueLengthPolicy::update_policy(steady_clock::time_point now,
308                                       steady_clock::time_point expected_next_input_frame,
309                                       int64_t input_frame_duration,
310                                       int64_t master_frame_duration,
311                                       double max_input_card_jitter_seconds,
312                                       double max_master_card_jitter_seconds)
313 {
314         double input_frame_duration_seconds = input_frame_duration / double(TIMEBASE);
315         double master_frame_duration_seconds = master_frame_duration / double(TIMEBASE);
316
317         // Figure out when we can expect the next frame for this card, assuming
318         // worst-case jitter (ie., the frame is maximally late).
319         double seconds_until_next_frame = max(duration<double>(expected_next_input_frame - now).count() + max_input_card_jitter_seconds, 0.0);
320
321         // How many times are the master card expected to tick in that time?
322         // We assume the master clock has worst-case jitter but not any rate
323         // discrepancy, ie., it ticks as early as possible every time, but not
324         // cumulatively.
325         double frames_needed = (seconds_until_next_frame + max_master_card_jitter_seconds) / master_frame_duration_seconds;
326
327         // As a special case, if the master card ticks faster than the input card,
328         // we expect the queue to drain by itself even without dropping. But if
329         // the difference is small (e.g. 60 Hz master and 59.94 input), it would
330         // go slowly enough that the effect wouldn't really be appreciable.
331         // We account for this by looking at the situation five frames ahead,
332         // assuming everything else is the same.
333         double frames_allowed;
334         if (master_frame_duration < input_frame_duration) {
335                 frames_allowed = frames_needed + 5 * (input_frame_duration_seconds - master_frame_duration_seconds) / master_frame_duration_seconds;
336         } else {
337                 frames_allowed = frames_needed;
338         }
339
340         safe_queue_length = max<int>(floor(frames_allowed), 0);
341         metric_input_queue_safe_length_frames = safe_queue_length;
342 }
343
344 Mixer::Mixer(const QSurfaceFormat &format)
345         : httpd(),
346           mixer_surface(create_surface(format)),
347           h264_encoder_surface(create_surface(format)),
348           decklink_output_surface(create_surface(format)),
349           image_update_surface(create_surface(format))
350 {
351         memcpy(ycbcr_interpretation, global_flags.ycbcr_interpretation, sizeof(ycbcr_interpretation));
352         CHECK(init_movit(MOVIT_SHADER_DIR, MOVIT_DEBUG_OFF));
353         check_error();
354
355         if (!epoxy_has_gl_extension("GL_EXT_texture_sRGB_decode") ||
356             !epoxy_has_gl_extension("GL_ARB_sampler_objects")) {
357                 fprintf(stderr, "Nageru requires GL_EXT_texture_sRGB_decode and GL_ARB_sampler_objects to run.\n");
358                 exit(1);
359         }
360
361         // Since we allow non-bouncing 4:2:2 YCbCrInputs, effective subpixel precision
362         // will be halved when sampling them, and we need to compensate here.
363         movit_texel_subpixel_precision /= 2.0;
364
365         resource_pool.reset(new ResourcePool);
366         for (unsigned i = 0; i < NUM_OUTPUTS; ++i) {
367                 output_channel[i].parent = this;
368                 output_channel[i].channel = i;
369         }
370
371         ImageFormat inout_format;
372         inout_format.color_space = COLORSPACE_sRGB;
373         inout_format.gamma_curve = GAMMA_sRGB;
374
375         // Matches the 4:2:0 format created by the main chain.
376         YCbCrFormat ycbcr_format;
377         ycbcr_format.chroma_subsampling_x = 2;
378         ycbcr_format.chroma_subsampling_y = 2;
379         if (global_flags.ycbcr_rec709_coefficients) {
380                 ycbcr_format.luma_coefficients = YCBCR_REC_709;
381         } else {
382                 ycbcr_format.luma_coefficients = YCBCR_REC_601;
383         }
384         ycbcr_format.full_range = false;
385         ycbcr_format.num_levels = 1 << global_flags.bit_depth;
386         ycbcr_format.cb_x_position = 0.0f;
387         ycbcr_format.cr_x_position = 0.0f;
388         ycbcr_format.cb_y_position = 0.5f;
389         ycbcr_format.cr_y_position = 0.5f;
390
391         // Initialize the neutral colors to sane values.
392         for (unsigned i = 0; i < MAX_VIDEO_CARDS; ++i) {
393                 last_received_neutral_color[i] = RGBTriplet(1.0f, 1.0f, 1.0f);
394         }
395
396         // Display chain; shows the live output produced by the main chain (or rather, a copy of it).
397         display_chain.reset(new EffectChain(global_flags.width, global_flags.height, resource_pool.get()));
398         check_error();
399         GLenum type = global_flags.bit_depth > 8 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_BYTE;
400         display_input = new YCbCrInput(inout_format, ycbcr_format, global_flags.width, global_flags.height, YCBCR_INPUT_SPLIT_Y_AND_CBCR, type);
401         display_chain->add_input(display_input);
402         display_chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
403         display_chain->set_dither_bits(0);  // Don't bother.
404         display_chain->finalize();
405
406         video_encoder.reset(new VideoEncoder(resource_pool.get(), h264_encoder_surface, global_flags.va_display, global_flags.width, global_flags.height, &httpd, global_disk_space_estimator));
407         if (!global_flags.card_to_mjpeg_stream_export.empty()) {
408                 mjpeg_encoder.reset(new MJPEGEncoder(&httpd, global_flags.va_display));
409         }
410
411         // Must be instantiated after VideoEncoder has initialized global_flags.use_zerocopy.
412         theme.reset(new Theme(global_flags.theme_filename, global_flags.theme_dirs, resource_pool.get()));
413
414         // Must be instantiated after the theme, as the theme decides the number of FFmpeg inputs.
415         std::vector<FFmpegCapture *> video_inputs = theme->get_video_inputs();
416         audio_mixer.reset(new AudioMixer);
417
418         httpd.add_endpoint("/channels", bind(&Mixer::get_channels_json, this), HTTPD::ALLOW_ALL_ORIGINS);
419         for (int channel_idx = 0; channel_idx < theme->get_num_channels(); ++channel_idx) {
420                 char url[256];
421                 snprintf(url, sizeof(url), "/channels/%d/color", channel_idx + 2);
422                 httpd.add_endpoint(url, bind(&Mixer::get_channel_color_http, this, unsigned(channel_idx + 2)), HTTPD::ALLOW_ALL_ORIGINS);
423         }
424
425         // Start listening for clients only once VideoEncoder has written its header, if any.
426         httpd.start(global_flags.http_port);
427
428         // First try initializing the then PCI devices, then USB, then
429         // fill up with fake cards until we have the desired number of cards.
430         unsigned num_pci_devices = 0;
431         unsigned card_index = 0;
432
433         {
434                 IDeckLinkIterator *decklink_iterator = CreateDeckLinkIteratorInstance();
435                 if (decklink_iterator != nullptr) {
436                         for ( ; card_index < unsigned(global_flags.max_num_cards); ++card_index) {
437                                 IDeckLink *decklink;
438                                 if (decklink_iterator->Next(&decklink) != S_OK) {
439                                         break;
440                                 }
441
442                                 if (!decklink_card_is_active(decklink, card_index)) {
443                                         fprintf(stderr, "DeckLink card %u is inactive in current profile, skipping (try changing it in Desktop Video Setup)\n", card_index);
444                                         decklink->Release();
445                                         continue;
446                                 }
447
448                                 DeckLinkCapture *capture = new DeckLinkCapture(decklink, card_index);
449                                 DeckLinkOutput *output = new DeckLinkOutput(resource_pool.get(), decklink_output_surface, global_flags.width, global_flags.height, card_index);
450                                 if (!output->set_device(decklink, capture->get_input())) {
451                                         delete output;
452                                         output = nullptr;
453                                 }
454                                 configure_card(card_index, capture, CardType::LIVE_CARD, output, /*is_srt_card=*/false);
455                                 ++num_pci_devices;
456                         }
457                         decklink_iterator->Release();
458                         fprintf(stderr, "Found %u DeckLink PCI card(s).\n", num_pci_devices);
459                 } else {
460                         fprintf(stderr, "DeckLink drivers not found. Probing for USB cards only.\n");
461                 }
462         }
463
464         unsigned num_usb_devices = BMUSBCapture::num_cards();
465         for (unsigned usb_card_index = 0; usb_card_index < num_usb_devices && card_index < unsigned(global_flags.max_num_cards); ++usb_card_index, ++card_index) {
466                 BMUSBCapture *capture = new BMUSBCapture(usb_card_index);
467                 capture->set_card_disconnected_callback(bind(&Mixer::bm_hotplug_remove, this, card_index));
468                 configure_card(card_index, capture, CardType::LIVE_CARD, /*output=*/nullptr, /*is_srt_card=*/false);
469         }
470         fprintf(stderr, "Found %u USB card(s).\n", num_usb_devices);
471
472         // Fill up with fake cards for as long as we can, so that the FFmpeg
473         // and HTML cards always come last.
474         unsigned num_fake_cards = 0;
475 #ifdef HAVE_CEF
476         size_t num_html_inputs = theme->get_html_inputs().size();
477 #else
478         size_t num_html_inputs = 0;
479 #endif
480         for ( ; card_index < MAX_VIDEO_CARDS - video_inputs.size() - num_html_inputs; ++card_index) {
481                 // Only bother to activate fake capture cards to satisfy the minimum.
482                 bool is_active = card_index < unsigned(global_flags.min_num_cards) || cards[card_index].force_active;
483                 if (is_active) {
484                         FakeCapture *capture = new FakeCapture(global_flags.width, global_flags.height, FAKE_FPS, OUTPUT_FREQUENCY, card_index, global_flags.fake_cards_audio);
485                         configure_card(card_index, capture, CardType::FAKE_CAPTURE, /*output=*/nullptr, /*is_srt_card=*/false);
486                         ++num_fake_cards;
487                 } else {
488                         configure_card(card_index, nullptr, CardType::FAKE_CAPTURE, /*output=*/nullptr, /*is_srt_card=*/false);
489                 }
490         }
491
492         if (num_fake_cards > 0) {
493                 fprintf(stderr, "Initialized %u fake cards.\n", num_fake_cards);
494         }
495
496         // Initialize all video inputs the theme asked for.
497         for (unsigned video_card_index = 0; video_card_index < video_inputs.size(); ++card_index, ++video_card_index) {
498                 if (card_index >= MAX_VIDEO_CARDS) {
499                         fprintf(stderr, "ERROR: Not enough card slots available for the videos the theme requested.\n");
500                         abort();
501                 }
502                 configure_card(card_index, video_inputs[video_card_index], CardType::FFMPEG_INPUT, /*output=*/nullptr, /*is_srt_card=*/false);
503                 video_inputs[video_card_index]->set_card_index(card_index);
504         }
505         num_video_inputs = video_inputs.size();
506
507 #ifdef HAVE_CEF
508         // Same, for HTML inputs.
509         std::vector<CEFCapture *> html_inputs = theme->get_html_inputs();
510         for (unsigned html_card_index = 0; html_card_index < html_inputs.size(); ++card_index, ++html_card_index) {
511                 if (card_index >= MAX_VIDEO_CARDS) {
512                         fprintf(stderr, "ERROR: Not enough card slots available for the HTML inputs the theme requested.\n");
513                         abort();
514                 }
515                 configure_card(card_index, html_inputs[html_card_index], CardType::CEF_INPUT, /*output=*/nullptr, /*is_srt_card=*/false);
516                 html_inputs[html_card_index]->set_card_index(card_index);
517         }
518         num_html_inputs = html_inputs.size();
519 #endif
520
521         BMUSBCapture::set_card_connected_callback(bind(&Mixer::bm_hotplug_add, this, _1));
522         BMUSBCapture::start_bm_thread();
523
524 #ifdef HAVE_SRT
525         if (global_flags.srt_port >= 0) {
526                 start_srt();
527         }
528 #endif
529
530         chroma_subsampler.reset(new ChromaSubsampler(resource_pool.get()));
531
532         if (global_flags.bit_depth > 8) {
533                 if (!v210Converter::has_hardware_support()) {
534                         fprintf(stderr, "ERROR: --ten-bit-input requires support for OpenGL compute shaders\n");
535                         fprintf(stderr, "       (OpenGL 4.3, or GL_ARB_compute_shader + GL_ARB_shader_image_load_store).\n");
536                         abort();
537                 }
538                 v210_converter.reset(new v210Converter());
539
540                 // These are all the widths listed in the Blackmagic SDK documentation
541                 // (section 2.7.3, “Display Modes”).
542                 v210_converter->precompile_shader(720);
543                 v210_converter->precompile_shader(1280);
544                 v210_converter->precompile_shader(1920);
545                 v210_converter->precompile_shader(2048);
546                 v210_converter->precompile_shader(3840);
547                 v210_converter->precompile_shader(4096);
548         }
549         if (global_flags.bit_depth > 8) {
550                 if (!v210Converter::has_hardware_support()) {
551                         fprintf(stderr, "ERROR: --ten-bit-output requires support for OpenGL compute shaders\n");
552                         fprintf(stderr, "       (OpenGL 4.3, or GL_ARB_compute_shader + GL_ARB_shader_image_load_store).\n");
553                         abort();
554                 }
555         }
556
557         timecode_renderer.reset(new TimecodeRenderer(resource_pool.get(), global_flags.width, global_flags.height));
558         display_timecode_in_stream = global_flags.display_timecode_in_stream;
559         display_timecode_on_stdout = global_flags.display_timecode_on_stdout;
560
561         if (global_flags.enable_alsa_output) {
562                 alsa.reset(new ALSAOutput(OUTPUT_FREQUENCY, /*num_channels=*/2));
563         }
564         output_card_is_master = global_flags.output_card_is_master;
565         if (global_flags.output_card != -1) {
566                 desired_output_card_index = global_flags.output_card;
567                 set_output_card_internal(global_flags.output_card);
568         }
569
570         output_jitter_history.register_metrics({{ "card", "output" }});
571
572         ImageInput::start_update_thread(image_update_surface);
573 }
574
575 Mixer::~Mixer()
576 {
577         ImageInput::end_update_thread();
578
579         if (mjpeg_encoder != nullptr) {
580                 mjpeg_encoder->stop();
581         }
582         httpd.stop();
583         BMUSBCapture::stop_bm_thread();
584
585         for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) {
586                 if (cards[card_index].capture != nullptr) {  // Active.
587                         cards[card_index].capture->stop_dequeue_thread();
588                 }
589                 if (cards[card_index].output) {
590                         cards[card_index].output->end_output();
591                         cards[card_index].output.reset();
592                 }
593         }
594
595         video_encoder.reset(nullptr);
596 }
597
598 void Mixer::configure_card(unsigned card_index, CaptureInterface *capture, CardType card_type, DeckLinkOutput *output, bool is_srt_card)
599 {
600         bool is_active = capture != nullptr;
601         if (!is_active) {
602                 assert(card_type == CardType::FAKE_CAPTURE);
603         }
604
605         CaptureCard *card = &cards[card_index];
606         if (card->capture != nullptr) {
607                 card_mutex.unlock();  // The dequeue thread could be waiting for bm_frame().
608                 card->capture->stop_dequeue_thread();
609                 card_mutex.lock();
610         }
611         card->capture.reset(capture);
612         card->is_fake_capture = (card_type == CardType::FAKE_CAPTURE);
613         if (card->is_fake_capture) {
614                 card->fake_capture_counter = fake_capture_counter++;
615         }
616         card->is_cef_capture = (card_type == CardType::CEF_INPUT);
617         card->may_have_dropped_last_frame = false;
618         card->type = card_type;
619         if (card->output.get() != output) {
620                 card->output.reset(output);
621         }
622
623         PixelFormat pixel_format;
624         if (card_type == CardType::FFMPEG_INPUT) {
625                 pixel_format = capture->get_current_pixel_format();
626         } else if (card_type == CardType::CEF_INPUT) {
627                 pixel_format = PixelFormat_8BitBGRA;
628         } else if (global_flags.bit_depth > 8) {
629                 pixel_format = PixelFormat_10BitYCbCr;
630         } else {
631                 pixel_format = PixelFormat_8BitYCbCr;
632         }
633
634         if (is_active) {
635                 card->capture->set_frame_callback(bind(&Mixer::bm_frame, this, card_index, _1, _2, _3, _4, _5, _6, _7));
636                 if (card->frame_allocator == nullptr) {
637                         card->frame_allocator.reset(new PBOFrameAllocator(pixel_format, FRAME_SIZE, global_flags.width, global_flags.height, card_index, mjpeg_encoder.get()));
638                 } else {
639                         // The format could have changed, but we cannot reset the allocator
640                         // and create a new one from scratch, since there may be allocated
641                         // frames from it that expect to call release_frame() on it.
642                         // Instead, ask the allocator to create new frames for us and discard
643                         // any old ones as they come back. This takes the mutex while
644                         // allocating, but nothing should really be sending frames in there
645                         // right now anyway (start_bm_capture() has not been called yet).
646                         card->frame_allocator->reconfigure(pixel_format, FRAME_SIZE, global_flags.width, global_flags.height, card_index, mjpeg_encoder.get());
647                 }
648                 card->capture->set_video_frame_allocator(card->frame_allocator.get());
649                 if (card->surface == nullptr) {
650                         card->surface = create_surface_with_same_format(mixer_surface);
651                 }
652                 while (!card->new_frames.empty()) card->new_frames.pop_front();
653                 card->last_timecode = -1;
654                 card->capture->set_pixel_format(pixel_format);
655                 card->capture->configure_card();
656
657                 // NOTE: start_bm_capture() happens in thread_func().
658         }
659
660         if (is_srt_card) {
661                 assert(card_type == CardType::FFMPEG_INPUT);
662         }
663
664         DeviceSpec device{InputSourceType::CAPTURE_CARD, card_index};
665         unsigned num_channels = card_type == CardType::LIVE_CARD ? 8 : 2;
666         if (is_active) {
667                 audio_mixer->set_device_parameters(device, card->capture->get_description(), card_type, num_channels, /*active=*/true);
668         } else {
669                 // Note: Keeps the previous name, if any.
670                 char name[32];
671                 snprintf(name, sizeof(name), "Fake card %u", card_index + 1);
672                 audio_mixer->set_device_parameters(device, name, card_type, num_channels, /*active=*/false);
673         }
674         audio_mixer->reset_resampler(device);
675         audio_mixer->trigger_state_changed_callback();
676
677         // Unregister old metrics, if any.
678         if (!card->labels.empty()) {
679                 const vector<pair<string, string>> &labels = card->labels;
680                 card->jitter_history.unregister_metrics(labels);
681                 card->queue_length_policy.unregister_metrics(labels);
682                 global_metrics.remove_if_exists("input_received_frames", labels);
683                 global_metrics.remove_if_exists("input_dropped_frames_jitter", labels);
684                 global_metrics.remove_if_exists("input_dropped_frames_error", labels);
685                 global_metrics.remove_if_exists("input_dropped_frames_resets", labels);
686                 global_metrics.remove_if_exists("input_queue_length_frames", labels);
687                 global_metrics.remove_if_exists("input_queue_duped_frames", labels);
688
689                 global_metrics.remove_if_exists("input_has_signal_bool", labels);
690                 global_metrics.remove_if_exists("input_is_connected_bool", labels);
691                 global_metrics.remove_if_exists("input_interlaced_bool", labels);
692                 global_metrics.remove_if_exists("input_width_pixels", labels);
693                 global_metrics.remove_if_exists("input_height_pixels", labels);
694                 global_metrics.remove_if_exists("input_frame_rate_nom", labels);
695                 global_metrics.remove_if_exists("input_frame_rate_den", labels);
696                 global_metrics.remove_if_exists("input_sample_rate_hz", labels);
697
698                 card->srt_metrics.deinit(labels);
699         }
700
701         if (is_active) {
702                 // Register metrics.
703                 vector<pair<string, string>> labels;
704                 char card_name[64];
705                 snprintf(card_name, sizeof(card_name), "%d", card_index);
706                 labels.emplace_back("card", card_name);
707
708                 switch (card_type) {
709                 case CardType::LIVE_CARD:
710                         labels.emplace_back("cardtype", "live");
711                         break;
712                 case CardType::FAKE_CAPTURE:
713                         labels.emplace_back("cardtype", "fake");
714                         break;
715                 case CardType::FFMPEG_INPUT:
716                         if (is_srt_card) {
717                                 labels.emplace_back("cardtype", "srt");
718                         } else {
719                                 labels.emplace_back("cardtype", "ffmpeg");
720                         }
721                         break;
722                 case CardType::CEF_INPUT:
723                         labels.emplace_back("cardtype", "cef");
724                         break;
725                 default:
726                         assert(false);
727                 }
728                 card->jitter_history.register_metrics(labels);
729                 card->queue_length_policy.register_metrics(labels);
730                 global_metrics.add("input_received_frames", labels, &card->metric_input_received_frames);
731                 global_metrics.add("input_dropped_frames_jitter", labels, &card->metric_input_dropped_frames_jitter);
732                 global_metrics.add("input_dropped_frames_error", labels, &card->metric_input_dropped_frames_error);
733                 global_metrics.add("input_dropped_frames_resets", labels, &card->metric_input_resets);
734                 global_metrics.add("input_queue_length_frames", labels, &card->metric_input_queue_length_frames, Metrics::TYPE_GAUGE);
735                 global_metrics.add("input_queue_duped_frames", labels, &card->metric_input_duped_frames);
736
737                 global_metrics.add("input_has_signal_bool", labels, &card->metric_input_has_signal_bool, Metrics::TYPE_GAUGE);
738                 global_metrics.add("input_is_connected_bool", labels, &card->metric_input_is_connected_bool, Metrics::TYPE_GAUGE);
739                 global_metrics.add("input_interlaced_bool", labels, &card->metric_input_interlaced_bool, Metrics::TYPE_GAUGE);
740                 global_metrics.add("input_width_pixels", labels, &card->metric_input_width_pixels, Metrics::TYPE_GAUGE);
741                 global_metrics.add("input_height_pixels", labels, &card->metric_input_height_pixels, Metrics::TYPE_GAUGE);
742                 global_metrics.add("input_frame_rate_nom", labels, &card->metric_input_frame_rate_nom, Metrics::TYPE_GAUGE);
743                 global_metrics.add("input_frame_rate_den", labels, &card->metric_input_frame_rate_den, Metrics::TYPE_GAUGE);
744                 global_metrics.add("input_sample_rate_hz", labels, &card->metric_input_sample_rate_hz, Metrics::TYPE_GAUGE);
745
746                 if (is_srt_card) {
747                         card->srt_metrics.init(labels);
748                 }
749
750                 card->labels = labels;
751         } else {
752                 card->labels.clear();
753         }
754 }
755
756 void Mixer::set_output_card_internal(int card_index)
757 {
758         // We don't really need to take card_mutex, since we're in the mixer
759         // thread and don't mess with any queues (which is the only thing that happens
760         // from other threads), but it's probably the safest in the long run.
761         unique_lock<mutex> lock(card_mutex);
762         if (output_card_index != -1) {
763                 // Switch the old card from output to input.
764                 CaptureCard *old_card = &cards[output_card_index];
765                 old_card->output->end_output();
766
767                 // Stop the fake card that we put into place.
768                 // This needs to _not_ happen under the mutex, to avoid deadlock
769                 // (delivering the last frame needs to take the mutex).
770                 CaptureInterface *fake_capture = old_card->capture.get();
771                 lock.unlock();
772                 fake_capture->stop_dequeue_thread();
773                 lock.lock();
774                 old_card->capture = move(old_card->parked_capture);  // TODO: reset the metrics
775                 old_card->is_fake_capture = false;
776                 old_card->capture->start_bm_capture();
777         }
778         if (card_index != -1) {
779                 CaptureCard *card = &cards[card_index];
780                 CaptureInterface *capture = card->capture.get();
781                 // TODO: DeckLinkCapture::stop_dequeue_thread can actually take
782                 // several seconds to complete (blocking on DisableVideoInput);
783                 // see if we can maybe do it asynchronously.
784                 lock.unlock();
785                 capture->stop_dequeue_thread();
786                 lock.lock();
787                 card->parked_capture = move(card->capture);
788                 CaptureInterface *fake_capture = new FakeCapture(global_flags.width, global_flags.height, FAKE_FPS, OUTPUT_FREQUENCY, card_index, global_flags.fake_cards_audio);
789                 configure_card(card_index, fake_capture, CardType::FAKE_CAPTURE, card->output.release(), /*is_srt_card=*/false);
790                 card->jitter_history.clear();
791                 card->capture->start_bm_capture();
792                 desired_output_video_mode = output_video_mode = card->output->pick_video_mode(desired_output_video_mode);
793                 card->output->start_output(desired_output_video_mode, pts_int, /*is_master_card=*/output_card_is_master);
794         }
795         output_card_index = card_index;
796         output_jitter_history.clear();
797 }
798
799 namespace {
800
801 int unwrap_timecode(uint16_t current_wrapped, int last)
802 {
803         uint16_t last_wrapped = last & 0xffff;
804         if (current_wrapped > last_wrapped) {
805                 return (last & ~0xffff) | current_wrapped;
806         } else {
807                 return 0x10000 + ((last & ~0xffff) | current_wrapped);
808         }
809 }
810
811 }  // namespace
812
813 void Mixer::bm_frame(unsigned card_index, uint16_t timecode,
814                      FrameAllocator::Frame video_frame, size_t video_offset, VideoFormat video_format,
815                      FrameAllocator::Frame audio_frame, size_t audio_offset, AudioFormat audio_format)
816 {
817         DeviceSpec device{InputSourceType::CAPTURE_CARD, card_index};
818         CaptureCard *card = &cards[card_index];
819
820         ++card->metric_input_received_frames;
821         card->metric_input_has_signal_bool = video_format.has_signal;
822         card->metric_input_is_connected_bool = video_format.is_connected;
823         card->metric_input_interlaced_bool = video_format.interlaced;
824         card->metric_input_width_pixels = video_format.width;
825         card->metric_input_height_pixels = video_format.height;
826         card->metric_input_frame_rate_nom = video_format.frame_rate_nom;
827         card->metric_input_frame_rate_den = video_format.frame_rate_den;
828         card->metric_input_sample_rate_hz = audio_format.sample_rate;
829
830         if (is_mode_scanning[card_index]) {
831                 if (video_format.has_signal) {
832                         // Found a stable signal, so stop scanning.
833                         is_mode_scanning[card_index] = false;
834                 } else {
835                         static constexpr double switch_time_s = 0.1;  // Should be enough time for the signal to stabilize.
836                         steady_clock::time_point now = steady_clock::now();
837                         double sec_since_last_switch = duration<double>(steady_clock::now() - last_mode_scan_change[card_index]).count();
838                         if (sec_since_last_switch > switch_time_s) {
839                                 // It isn't this mode; try the next one.
840                                 mode_scanlist_index[card_index]++;
841                                 mode_scanlist_index[card_index] %= mode_scanlist[card_index].size();
842                                 cards[card_index].capture->set_video_mode(mode_scanlist[card_index][mode_scanlist_index[card_index]]);
843                                 last_mode_scan_change[card_index] = now;
844                         }
845                 }
846         }
847
848         int64_t frame_length = int64_t(TIMEBASE) * video_format.frame_rate_den / video_format.frame_rate_nom;
849         assert(frame_length > 0);
850
851         size_t num_samples = (audio_frame.len > audio_offset) ? (audio_frame.len - audio_offset) / audio_format.num_channels / (audio_format.bits_per_sample / 8) : 0;
852         if (num_samples > OUTPUT_FREQUENCY / 10 && card->type != CardType::FFMPEG_INPUT) {
853                 printf("%s: Dropping frame with implausible audio length (len=%d, offset=%d) [timecode=0x%04x video_len=%d video_offset=%d video_format=%x)\n",
854                         description_for_card(card_index).c_str(), int(audio_frame.len), int(audio_offset),
855                         timecode, int(video_frame.len), int(video_offset), video_format.id);
856                 if (video_frame.owner) {
857                         video_frame.owner->release_frame(video_frame);
858                 }
859                 if (audio_frame.owner) {
860                         audio_frame.owner->release_frame(audio_frame);
861                 }
862                 return;
863         }
864
865         int dropped_frames = 0;
866         if (card->last_timecode != -1) {
867                 dropped_frames = unwrap_timecode(timecode, card->last_timecode) - card->last_timecode - 1;
868         }
869
870         // Number of samples per frame if we need to insert silence.
871         // (Could be nonintegral, but resampling will save us then.)
872         const int silence_samples = OUTPUT_FREQUENCY * video_format.frame_rate_den / video_format.frame_rate_nom;
873
874         if (dropped_frames > TYPICAL_FPS * 2) {
875                 fprintf(stderr, "%s lost more than two seconds (or time code jumping around; from 0x%04x to 0x%04x), resetting resampler\n",
876                         description_for_card(card_index).c_str(), card->last_timecode, timecode);
877                 audio_mixer->reset_resampler(device);
878                 dropped_frames = 0;
879                 ++card->metric_input_resets;
880         } else if (dropped_frames > 0) {
881                 // Insert silence as needed.
882                 fprintf(stderr, "%s dropped %d frame(s) (before timecode 0x%04x), inserting silence.\n",
883                         description_for_card(card_index).c_str(), dropped_frames, timecode);
884                 card->metric_input_dropped_frames_error += dropped_frames;
885
886                 bool success;
887                 do {
888                         success = audio_mixer->add_silence(device, silence_samples, dropped_frames);
889                 } while (!success);
890         }
891
892         if (num_samples > 0) {
893                 audio_mixer->add_audio(device, audio_frame.data + audio_offset, num_samples, audio_format, audio_frame.received_timestamp);
894
895                 // Audio for the MJPEG stream. We don't resample; audio that's not in 48 kHz
896                 // just gets dropped for now.
897                 //
898                 // Only bother doing MJPEG encoding if there are any connected clients
899                 // that want the stream.
900                 if (httpd.get_num_connected_multicam_clients() > 0 ||
901                     httpd.get_num_connected_siphon_clients(card_index) > 0) {
902                         vector<int32_t> converted_samples = convert_audio_to_fixed32(audio_frame.data + audio_offset, num_samples, audio_format, 2);
903                         lock_guard<mutex> lock(card_mutex);
904                         if (card->new_raw_audio.empty()) {
905                                 card->new_raw_audio = move(converted_samples);
906                         } else {
907                                 // For raw audio, we don't really synchronize audio and video;
908                                 // we just put the audio in frame by frame, and if a video frame is
909                                 // dropped, we still keep the audio, which means it will be added
910                                 // to the beginning of the next frame. It would probably be better
911                                 // to move the audio pts earlier to show this, but most players can
912                                 // live with some jitter, and in a lot of ways, it's much nicer for
913                                 // Futatabi to have all audio locked to a video frame.
914                                 card->new_raw_audio.insert(card->new_raw_audio.end(), converted_samples.begin(), converted_samples.end());
915
916                                 // Truncate to one second, just to be sure we don't have infinite buildup in case of weirdness.
917                                 if (card->new_raw_audio.size() > OUTPUT_FREQUENCY * 2) {
918                                         size_t excess_samples = card->new_raw_audio.size() - OUTPUT_FREQUENCY * 2;
919                                         card->new_raw_audio.erase(card->new_raw_audio.begin(), card->new_raw_audio.begin() + excess_samples);
920                                 }
921                         }
922                 }
923         }
924
925         // Done with the audio, so release it.
926         if (audio_frame.owner) {
927                 audio_frame.owner->release_frame(audio_frame);
928         }
929
930         card->last_timecode = timecode;
931
932         PBOFrameAllocator::Userdata *userdata = (PBOFrameAllocator::Userdata *)video_frame.userdata;
933         if (card->type == CardType::FFMPEG_INPUT && userdata != nullptr) {
934                 FFmpegCapture *ffmpeg_capture = static_cast<FFmpegCapture *>(card->capture.get());
935                 userdata->has_last_subtitle = ffmpeg_capture->get_has_last_subtitle();
936                 userdata->last_subtitle = ffmpeg_capture->get_last_subtitle();
937         }
938 #ifdef HAVE_SRT
939         if (card->type == CardType::FFMPEG_INPUT) {
940                 int srt_sock = static_cast<FFmpegCapture *>(card->capture.get())->get_srt_sock();
941                 if (srt_sock != -1) {
942                         card->srt_metrics.update_srt_stats(srt_sock);
943                 }
944         }
945 #endif
946
947         size_t y_offset, cbcr_offset;
948         size_t expected_length = video_format.stride * (video_format.height + video_format.extra_lines_top + video_format.extra_lines_bottom);
949         if (userdata != nullptr && userdata->pixel_format == PixelFormat_8BitYCbCrPlanar) {
950                 // The calculation above is wrong for planar Y'CbCr, so just override it.
951                 assert(card->type == CardType::FFMPEG_INPUT);
952                 assert(video_offset == 0);
953                 expected_length = video_frame.len;
954
955                 userdata->ycbcr_format = (static_cast<FFmpegCapture *>(card->capture.get()))->get_current_frame_ycbcr_format();
956                 y_offset = 0;
957                 cbcr_offset = video_format.width * video_format.height;
958         } else {
959                 // All the other Y'CbCr formats are 4:2:2.
960                 y_offset = video_frame.size / 2 + video_offset / 2;
961                 cbcr_offset = video_offset / 2;
962         }
963         if (video_frame.len - video_offset == 0 ||
964             video_frame.len - video_offset != expected_length) {
965                 if (video_frame.len != 0) {
966                         printf("%s: Dropping video frame with wrong length (%zu; expected %zu)\n",
967                                 description_for_card(card_index).c_str(), video_frame.len - video_offset, expected_length);
968                 }
969                 if (video_frame.owner) {
970                         video_frame.owner->release_frame(video_frame);
971                 }
972
973                 // Still send on the information that we _had_ a frame, even though it's corrupted,
974                 // so that pts can go up accordingly.
975                 {
976                         lock_guard<mutex> lock(card_mutex);
977                         CaptureCard::NewFrame new_frame;
978                         new_frame.frame = RefCountedFrame(FrameAllocator::Frame());
979                         new_frame.length = frame_length;
980                         new_frame.interlaced = false;
981                         new_frame.dropped_frames = dropped_frames;
982                         new_frame.received_timestamp = video_frame.received_timestamp;
983                         card->new_frames.push_back(move(new_frame));
984                         card->jitter_history.frame_arrived(video_frame.received_timestamp, frame_length, dropped_frames);
985                 }
986                 card->new_frames_changed.notify_all();
987                 return;
988         }
989
990         unsigned num_fields = video_format.interlaced ? 2 : 1;
991         steady_clock::time_point frame_upload_start;
992         if (video_format.interlaced) {
993                 // Send the two fields along as separate frames; the other side will need to add
994                 // a deinterlacer to actually get this right.
995                 assert(video_format.height % 2 == 0);
996                 video_format.height /= 2;
997                 assert(frame_length % 2 == 0);
998                 frame_length /= 2;
999                 num_fields = 2;
1000                 frame_upload_start = steady_clock::now();
1001         }
1002         assert(userdata != nullptr);
1003         userdata->last_interlaced = video_format.interlaced;
1004         userdata->last_has_signal = video_format.has_signal;
1005         userdata->last_is_connected = video_format.is_connected;
1006         userdata->last_frame_rate_nom = video_format.frame_rate_nom;
1007         userdata->last_frame_rate_den = video_format.frame_rate_den;
1008         RefCountedFrame frame(video_frame);
1009
1010         // Send the frames on to the main thread, which will upload and process htem.
1011         // It is entirely possible to upload them in the same thread (and it might even be
1012         // faster, depending on the GPU and driver), but it appears to be trickling
1013         // driver bugs very easily.
1014         //
1015         // Note that this means we must hold on to the actual frame data in <userdata>
1016         // until the upload is done, but we hold on to <frame> much longer than that
1017         // (in fact, all the way until we no longer use the texture in rendering).
1018         for (unsigned field = 0; field < num_fields; ++field) {
1019                 if (field == 1) {
1020                         // Don't upload the second field as fast as we can; wait until
1021                         // the field time has approximately passed. (Otherwise, we could
1022                         // get timing jitter against the other sources, and possibly also
1023                         // against the video display, although the latter is not as critical.)
1024                         // This requires our system clock to be reasonably close to the
1025                         // video clock, but that's not an unreasonable assumption.
1026                         steady_clock::time_point second_field_start = frame_upload_start +
1027                                 nanoseconds(frame_length * 1000000000 / TIMEBASE);
1028                         this_thread::sleep_until(second_field_start);
1029                 }
1030
1031                 {
1032                         lock_guard<mutex> lock(card_mutex);
1033                         CaptureCard::NewFrame new_frame;
1034                         new_frame.frame = frame;
1035                         new_frame.length = frame_length;
1036                         new_frame.field = field;
1037                         new_frame.interlaced = video_format.interlaced;
1038                         new_frame.dropped_frames = dropped_frames;
1039                         new_frame.received_timestamp = video_frame.received_timestamp;  // Ignore the audio timestamp.
1040                         new_frame.video_format = video_format;
1041                         new_frame.video_offset = video_offset;
1042                         new_frame.y_offset = y_offset;
1043                         new_frame.cbcr_offset = cbcr_offset;
1044                         new_frame.texture_uploaded = false;
1045                         if (card->type == CardType::FFMPEG_INPUT) {
1046                                 FFmpegCapture *ffmpeg_capture = static_cast<FFmpegCapture *>(card->capture.get());
1047                                 new_frame.neutral_color = ffmpeg_capture->get_last_neutral_color();
1048                         }
1049                         card->new_frames.push_back(move(new_frame));
1050                         card->jitter_history.frame_arrived(video_frame.received_timestamp, frame_length, dropped_frames);
1051                         card->may_have_dropped_last_frame = false;
1052                 }
1053                 card->new_frames_changed.notify_all();
1054         }
1055 }
1056
1057 void Mixer::upload_texture_for_frame(
1058         int field, bmusb::VideoFormat video_format,
1059         size_t y_offset, size_t cbcr_offset, size_t video_offset, PBOFrameAllocator::Userdata *userdata)
1060 {
1061         size_t cbcr_width, cbcr_height;
1062         if (userdata != nullptr && userdata->pixel_format == PixelFormat_8BitYCbCrPlanar) {
1063                 cbcr_width = video_format.width / userdata->ycbcr_format.chroma_subsampling_x;
1064                 cbcr_height = video_format.height / userdata->ycbcr_format.chroma_subsampling_y;
1065         } else {
1066                 // All the other Y'CbCr formats are 4:2:2.
1067                 cbcr_width = video_format.width / 2;
1068                 cbcr_height = video_format.height;
1069         }
1070
1071         bool interlaced_stride = video_format.interlaced && (video_format.second_field_start == 1);
1072         if (video_format.interlaced) {
1073                 cbcr_height /= 2;
1074         }
1075
1076         unsigned field_start_line;
1077         if (field == 1) {
1078                 field_start_line = video_format.second_field_start;
1079         } else {
1080                 field_start_line = video_format.extra_lines_top;
1081         }
1082
1083         // For anything not FRAME_FORMAT_YCBCR_10BIT, v210_width will be nonsensical but not used.
1084         size_t v210_width = video_format.stride / sizeof(uint32_t);
1085         ensure_texture_resolution(userdata, field, video_format.width, video_format.height, cbcr_width, cbcr_height, v210_width);
1086
1087         glBindBuffer(GL_PIXEL_UNPACK_BUFFER, userdata->pbo);
1088         check_error();
1089
1090         switch (userdata->pixel_format) {
1091                 case PixelFormat_10BitYCbCr: {
1092                         size_t field_start = video_offset + video_format.stride * field_start_line;
1093                         upload_texture(userdata->tex_v210[field], v210_width, video_format.height, video_format.stride, interlaced_stride, GL_RGBA, GL_UNSIGNED_INT_2_10_10_10_REV, field_start);
1094                         v210_converter->convert(userdata->tex_v210[field], userdata->tex_444[field], video_format.width, video_format.height);
1095                         break;
1096                 }
1097                 case PixelFormat_8BitYCbCr: {
1098                         size_t field_y_start = y_offset + video_format.width * field_start_line;
1099                         size_t field_cbcr_start = cbcr_offset + cbcr_width * field_start_line * sizeof(uint16_t);
1100
1101                         // Make up our own strides, since we are interleaving.
1102                         upload_texture(userdata->tex_y[field], video_format.width, video_format.height, video_format.width, interlaced_stride, GL_RED, GL_UNSIGNED_BYTE, field_y_start);
1103                         upload_texture(userdata->tex_cbcr[field], cbcr_width, cbcr_height, cbcr_width * sizeof(uint16_t), interlaced_stride, GL_RG, GL_UNSIGNED_BYTE, field_cbcr_start);
1104                         break;
1105                 }
1106                 case PixelFormat_8BitYCbCrPlanar: {
1107                         assert(field_start_line == 0);  // We don't really support interlaced here.
1108                         size_t field_y_start = y_offset;
1109                         size_t field_cb_start = cbcr_offset;
1110                         size_t field_cr_start = cbcr_offset + cbcr_width * cbcr_height;
1111
1112                         // Make up our own strides, since we are interleaving.
1113                         upload_texture(userdata->tex_y[field], video_format.width, video_format.height, video_format.width, interlaced_stride, GL_RED, GL_UNSIGNED_BYTE, field_y_start);
1114                         upload_texture(userdata->tex_cb[field], cbcr_width, cbcr_height, cbcr_width, interlaced_stride, GL_RED, GL_UNSIGNED_BYTE, field_cb_start);
1115                         upload_texture(userdata->tex_cr[field], cbcr_width, cbcr_height, cbcr_width, interlaced_stride, GL_RED, GL_UNSIGNED_BYTE, field_cr_start);
1116                         break;
1117                 }
1118                 case PixelFormat_8BitBGRA: {
1119                         size_t field_start = video_offset + video_format.stride * field_start_line;
1120                         upload_texture(userdata->tex_rgba[field], video_format.width, video_format.height, video_format.stride, interlaced_stride, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, field_start);
1121                         // These could be asked to deliver mipmaps at any time.
1122                         glBindTexture(GL_TEXTURE_2D, userdata->tex_rgba[field]);
1123                         check_error();
1124                         glGenerateMipmap(GL_TEXTURE_2D);
1125                         check_error();
1126                         glBindTexture(GL_TEXTURE_2D, 0);
1127                         check_error();
1128                         break;
1129                 }
1130                 default:
1131                         assert(false);
1132         }
1133
1134         glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
1135         check_error();
1136 }
1137
1138 void Mixer::bm_hotplug_add(libusb_device *dev)
1139 {
1140         lock_guard<mutex> lock(hotplug_mutex);
1141         hotplugged_cards.push_back(dev);
1142 }
1143
1144 void Mixer::bm_hotplug_remove(unsigned card_index)
1145 {
1146         cards[card_index].new_frames_changed.notify_all();
1147 }
1148
1149 void Mixer::thread_func()
1150 {
1151         pthread_setname_np(pthread_self(), "Mixer_OpenGL");
1152
1153         eglBindAPI(EGL_OPENGL_API);
1154         QOpenGLContext *context = create_context(mixer_surface);
1155         if (!make_current(context, mixer_surface)) {
1156                 printf("oops\n");
1157                 abort();
1158         }
1159
1160         // Start the actual capture. (We don't want to do it before we're actually ready
1161         // to process output frames.)
1162         for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) {
1163                 if (int(card_index) != output_card_index && cards[card_index].capture != nullptr) {
1164                         cards[card_index].capture->start_bm_capture();
1165                 }
1166         }
1167
1168         BasicStats basic_stats(/*verbose=*/true, /*use_opengl=*/true);
1169         int stats_dropped_frames = 0;
1170
1171         while (!should_quit) {
1172                 if (desired_output_card_index != output_card_index) {
1173                         set_output_card_internal(desired_output_card_index);
1174                 }
1175                 if (output_card_index != -1 &&
1176                     desired_output_video_mode != output_video_mode) {
1177                         DeckLinkOutput *output = cards[output_card_index].output.get();
1178                         output->end_output();
1179                         desired_output_video_mode = output_video_mode = output->pick_video_mode(desired_output_video_mode);
1180                         output->start_output(desired_output_video_mode, pts_int, /*is_master_card=*/output_card_is_master);
1181                 }
1182
1183                 {
1184                         lock_guard<mutex> lock(card_mutex);
1185                         handle_hotplugged_cards();
1186                 }
1187
1188                 CaptureCard::NewFrame new_frames[MAX_VIDEO_CARDS];
1189                 bool has_new_frame[MAX_VIDEO_CARDS] = { false };
1190
1191                 bool master_card_is_output;
1192                 unsigned master_card_index;
1193                 if (output_card_index != -1 && output_card_is_master) {
1194                         master_card_is_output = true;
1195                         master_card_index = output_card_index;
1196                 } else {
1197                         master_card_is_output = false;
1198                         master_card_index = theme->map_signal_to_card(master_clock_channel);
1199                         assert(master_card_index < MAX_VIDEO_CARDS);
1200                 }
1201
1202                 vector<int32_t> raw_audio[MAX_VIDEO_CARDS];  // For MJPEG encoding.
1203                 OutputFrameInfo output_frame_info = get_one_frame_from_each_card(master_card_index, master_card_is_output, new_frames, has_new_frame, raw_audio);
1204                 schedule_audio_resampling_tasks(output_frame_info.dropped_frames, output_frame_info.num_samples, output_frame_info.frame_duration, output_frame_info.is_preroll, output_frame_info.frame_timestamp);
1205                 stats_dropped_frames += output_frame_info.dropped_frames;
1206
1207                 for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) {
1208                         if (card_index == master_card_index || !has_new_frame[card_index]) {
1209                                 continue;
1210                         }
1211                         if (new_frames[card_index].frame->len == 0) {
1212                                 ++new_frames[card_index].dropped_frames;
1213                         }
1214                         if (new_frames[card_index].dropped_frames > 0) {
1215                                 printf("%s dropped %d frames before this\n",
1216                                         description_for_card(card_index).c_str(), int(new_frames[card_index].dropped_frames));
1217                         }
1218                 }
1219
1220                 // If the first card is reporting a corrupted or otherwise dropped frame,
1221                 // just increase the pts (skipping over this frame) and don't try to compute anything new.
1222                 if (!master_card_is_output &&
1223                     new_frames[master_card_index].frame != nullptr &&  // Timeout.
1224                     new_frames[master_card_index].frame->len == 0) {
1225                         ++stats_dropped_frames;
1226                         pts_int += new_frames[master_card_index].length;
1227                         continue;
1228                 }
1229
1230                 for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) {
1231                         if (!has_new_frame[card_index] || new_frames[card_index].frame->len == 0)
1232                                 continue;
1233
1234                         CaptureCard::NewFrame *new_frame = &new_frames[card_index];
1235                         assert(new_frame->frame != nullptr);
1236                         insert_new_frame(new_frame->frame, new_frame->field, new_frame->interlaced, card_index, &input_state);
1237                         check_error();
1238
1239                         // The new texture might need uploading before use.
1240                         if (!new_frame->texture_uploaded) {
1241                                 upload_texture_for_frame(new_frame->field, new_frame->video_format, new_frame->y_offset, new_frame->cbcr_offset,
1242                                         new_frame->video_offset, (PBOFrameAllocator::Userdata *)new_frame->frame->userdata);
1243                                 new_frame->texture_uploaded = true;
1244                         }
1245
1246                         // Only set the white balance if it actually changed. This means that the user
1247                         // is free to override the white balance in a video with no white balance information
1248                         // actually set (ie. r=g=b=1 all the time), or one where the white point is wrong,
1249                         // but frame-to-frame decisions will be heeded. We do this pretty much as late
1250                         // as possible (ie., after picking out the frame from the buffer), so that we are sure
1251                         // that the change takes effect on exactly the right frame.
1252                         if (fabs(new_frame->neutral_color.r - last_received_neutral_color[card_index].r) > 1e-3 ||
1253                             fabs(new_frame->neutral_color.g - last_received_neutral_color[card_index].g) > 1e-3 ||
1254                             fabs(new_frame->neutral_color.b - last_received_neutral_color[card_index].b) > 1e-3) {
1255                                 theme->set_wb_for_card(card_index, new_frame->neutral_color.r, new_frame->neutral_color.g, new_frame->neutral_color.b);
1256                                 last_received_neutral_color[card_index] = new_frame->neutral_color;
1257                         }
1258
1259                         if (new_frame->frame->data_copy != nullptr && mjpeg_encoder->should_encode_mjpeg_for_card(card_index)) {
1260                                 RGBTriplet neutral_color = theme->get_white_balance_for_card(card_index);
1261                                 mjpeg_encoder->upload_frame(pts_int, card_index, new_frame->frame, new_frame->video_format, new_frame->y_offset, new_frame->cbcr_offset, move(raw_audio[card_index]), neutral_color);
1262                         }
1263
1264                 }
1265
1266                 int64_t frame_duration = output_frame_info.frame_duration;
1267                 render_one_frame(frame_duration);
1268                 {
1269                         lock_guard<mutex> lock(frame_num_mutex);
1270                         ++frame_num;
1271                 }
1272                 frame_num_updated.notify_all();
1273                 pts_int += frame_duration;
1274
1275                 basic_stats.update(frame_num, stats_dropped_frames);
1276                 // if (frame_num % 100 == 0) chain->print_phase_timing();
1277
1278                 if (should_cut.exchange(false)) {  // Test and clear.
1279                         video_encoder->do_cut(frame_num);
1280                 }
1281
1282 #if 0
1283                 // Reset every 100 frames, so that local variations in frame times
1284                 // (especially for the first few frames, when the shaders are
1285                 // compiled etc.) don't make it hard to measure for the entire
1286                 // remaining duration of the program.
1287                 if (frame == 10000) {
1288                         frame = 0;
1289                         start = now;
1290                 }
1291 #endif
1292                 check_error();
1293         }
1294
1295         resource_pool->clean_context();
1296 }
1297
1298 bool Mixer::input_card_is_master_clock(unsigned card_index, unsigned master_card_index) const
1299 {
1300         if (output_card_index != -1 && output_card_is_master) {
1301                 // The output card (ie., cards[output_card_index].output) is the master clock,
1302                 // so no input card (ie., cards[card_index].capture) is.
1303                 return false;
1304         }
1305         return (card_index == master_card_index);
1306 }
1307
1308 void Mixer::trim_queue(CaptureCard *card, size_t safe_queue_length)
1309 {
1310         // Count the number of frames in the queue, including any frames
1311         // we dropped. It's hard to know exactly how we should deal with
1312         // dropped (corrupted) input frames; they don't help our goal of
1313         // avoiding starvation, but they still add to the problem of latency.
1314         // Since dropped frames is going to mean a bump in the signal anyway,
1315         // we err on the side of having more stable latency instead.
1316         unsigned queue_length = 0;
1317         for (const CaptureCard::NewFrame &frame : card->new_frames) {
1318                 queue_length += frame.dropped_frames + 1;
1319         }
1320
1321         // If needed, drop frames until the queue is below the safe limit.
1322         // We prefer to drop from the head, because all else being equal,
1323         // we'd like more recent frames (less latency).
1324         unsigned dropped_frames = 0;
1325         while (queue_length > safe_queue_length) {
1326                 assert(!card->new_frames.empty());
1327                 assert(queue_length > card->new_frames.front().dropped_frames);
1328                 queue_length -= card->new_frames.front().dropped_frames;
1329
1330                 if (queue_length <= safe_queue_length) {
1331                         // No need to drop anything.
1332                         break;
1333                 }
1334
1335                 card->new_frames.pop_front();
1336                 card->new_frames_changed.notify_all();
1337                 --queue_length;
1338                 ++dropped_frames;
1339
1340                 if (queue_length == 0 && card->is_cef_capture) {
1341                         card->may_have_dropped_last_frame = true;
1342                 }
1343         }
1344
1345         card->metric_input_dropped_frames_jitter += dropped_frames;
1346         card->metric_input_queue_length_frames = queue_length;
1347
1348 #if 0
1349         if (dropped_frames > 0) {
1350                 fprintf(stderr, "Card %u dropped %u frame(s) to keep latency down.\n",
1351                         card_index, dropped_frames);
1352         }
1353 #endif
1354 }
1355
1356 pair<string, string> Mixer::get_channels_json()
1357 {
1358         Channels ret;
1359         for (int channel_idx = 0; channel_idx < theme->get_num_channels(); ++channel_idx) {
1360                 Channel *channel = ret.add_channel();
1361                 channel->set_index(channel_idx + 2);
1362                 channel->set_name(theme->get_channel_name(channel_idx + 2));
1363                 channel->set_color(theme->get_channel_color(channel_idx + 2));
1364         }
1365         string contents;
1366         google::protobuf::util::MessageToJsonString(ret, &contents);  // Ignore any errors.
1367         return make_pair(contents, "text/json");
1368 }
1369
1370 pair<string, string> Mixer::get_channel_color_http(unsigned channel_idx)
1371 {
1372         return make_pair(theme->get_channel_color(channel_idx), "text/plain");
1373 }
1374
1375 Mixer::OutputFrameInfo Mixer::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], vector<int32_t> raw_audio[MAX_VIDEO_CARDS])
1376 {
1377         OutputFrameInfo output_frame_info;
1378         constexpr steady_clock::duration master_card_timeout = milliseconds(200);
1379 start:
1380         unique_lock<mutex> lock(card_mutex, defer_lock);
1381         bool timed_out = false;
1382         if (master_card_is_output) {
1383                 // Clocked to the output, so wait for it to be ready for the next frame.
1384                 cards[master_card_index].output->wait_for_frame(pts_int, &output_frame_info.dropped_frames, &output_frame_info.frame_duration, &output_frame_info.is_preroll, &output_frame_info.frame_timestamp);
1385                 lock.lock();
1386         } else {
1387                 // Wait for the master card to have a new frame.
1388                 output_frame_info.is_preroll = false;
1389                 lock.lock();
1390                 timed_out = !cards[master_card_index].new_frames_changed.wait_for(lock,
1391                         master_card_timeout,
1392                         [this, master_card_index] {
1393                                 return !cards[master_card_index].new_frames.empty() ||
1394                                         cards[master_card_index].capture == nullptr ||
1395                                         cards[master_card_index].capture->get_disconnected();
1396                         });
1397                 if (timed_out) {
1398                         fprintf(stderr, "WARNING: Master card (%s) did not deliver a frame for %u ms, creating a fake one.\n",
1399                                 description_for_card(master_card_index).c_str(),
1400                                 unsigned(duration_cast<milliseconds>(master_card_timeout).count()));
1401                 }
1402         }
1403
1404         if (timed_out) {
1405                 // The master card stalled for 200 ms (possible when it's e.g.
1406                 // an SRT card). Send a frame no matter what; this also makes sure
1407                 // any other cards get to empty their queues, and in general,
1408                 // that we make _some_ sort of forward progress.
1409                 handle_hotplugged_cards();
1410         } else if (master_card_is_output) {
1411                 handle_hotplugged_cards();
1412         } else if (cards[master_card_index].new_frames.empty()) {
1413                 // We were woken up, but not due to a new frame. Deal with it
1414                 // and then restart.
1415                 assert(cards[master_card_index].capture == nullptr ||
1416                        cards[master_card_index].capture->get_disconnected());
1417                 handle_hotplugged_cards();
1418                 lock.unlock();
1419                 goto start;
1420         }
1421
1422         for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) {
1423                 CaptureCard *card = &cards[card_index];
1424                 if (card->new_frames.empty()) {  // Starvation.
1425                         ++card->metric_input_duped_frames;
1426 #ifdef HAVE_CEF
1427                         if (card->is_cef_capture && card->may_have_dropped_last_frame) {
1428                                 // Unlike other sources, CEF is not guaranteed to send us a steady
1429                                 // stream of frames, so we'll have to ask it to repaint the frame
1430                                 // we dropped. (may_have_dropped_last_frame is set whenever we
1431                                 // trim the queue completely away, and cleared when we actually
1432                                 // get a new frame.)
1433                                 ((CEFCapture *)card->capture.get())->request_new_frame(/*ignore_if_locked=*/true);
1434                         }
1435 #endif
1436                 } else {
1437                         new_frames[card_index] = move(card->new_frames.front());
1438                         has_new_frame[card_index] = true;
1439                         card->new_frames.pop_front();
1440                         card->new_frames_changed.notify_all();
1441                 }
1442
1443                 raw_audio[card_index] = move(card->new_raw_audio);
1444         }
1445
1446         if (timed_out) {
1447                 // Pretend the frame happened a while ago and was only processed now,
1448                 // so that we get the duration sort-of right. This isn't ideal.
1449                 output_frame_info.dropped_frames = 0;  // Hard to define, really.
1450                 output_frame_info.frame_duration = lrint(TIMEBASE * duration<double>(master_card_timeout).count());
1451                 output_frame_info.frame_timestamp = steady_clock::now() - master_card_timeout;
1452         } else if (!master_card_is_output) {
1453                 output_frame_info.frame_timestamp = new_frames[master_card_index].received_timestamp;
1454                 output_frame_info.dropped_frames = new_frames[master_card_index].dropped_frames;
1455                 output_frame_info.frame_duration = new_frames[master_card_index].length;
1456         }
1457
1458         if (!output_frame_info.is_preroll) {
1459                 output_jitter_history.frame_arrived(output_frame_info.frame_timestamp, output_frame_info.frame_duration, output_frame_info.dropped_frames);
1460         }
1461
1462         for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) {
1463                 CaptureCard *card = &cards[card_index];
1464                 if (has_new_frame[card_index] &&
1465                     !input_card_is_master_clock(card_index, master_card_index) &&
1466                     !output_frame_info.is_preroll) {
1467                         card->queue_length_policy.update_policy(
1468                                 output_frame_info.frame_timestamp,
1469                                 card->jitter_history.get_expected_next_frame(),
1470                                 new_frames[master_card_index].length,
1471                                 output_frame_info.frame_duration,
1472                                 card->jitter_history.estimate_max_jitter(),
1473                                 output_jitter_history.estimate_max_jitter());
1474                         trim_queue(card, min<int>(global_flags.max_input_queue_frames,
1475                                                   card->queue_length_policy.get_safe_queue_length()));
1476                 }
1477         }
1478
1479         // This might get off by a fractional sample when changing master card
1480         // between ones with different frame rates, but that's fine.
1481         int64_t num_samples_times_timebase = int64_t(OUTPUT_FREQUENCY) * output_frame_info.frame_duration + fractional_samples;
1482         output_frame_info.num_samples = num_samples_times_timebase / TIMEBASE;
1483         fractional_samples = num_samples_times_timebase % TIMEBASE;
1484         assert(output_frame_info.num_samples >= 0);
1485
1486         if (timed_out) {
1487                 DeviceSpec device{InputSourceType::CAPTURE_CARD, master_card_index};
1488                 bool success;
1489                 do {
1490                         success = audio_mixer->add_silence(device, output_frame_info.num_samples, /*dropped_frames=*/0);
1491                 } while (!success);
1492         }
1493
1494         return output_frame_info;
1495 }
1496
1497 void Mixer::handle_hotplugged_cards()
1498 {
1499         // Check for cards that have been disconnected since last frame.
1500         for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) {
1501                 CaptureCard *card = &cards[card_index];
1502                 if (card->capture != nullptr && card->capture->get_disconnected()) {
1503                         bool is_active = card_index < unsigned(global_flags.min_num_cards) || cards[card_index].force_active;
1504                         if (is_active) {
1505                                 fprintf(stderr, "Card %u went away, replacing with a fake card.\n", card_index);
1506                                 FakeCapture *capture = new FakeCapture(global_flags.width, global_flags.height, FAKE_FPS, OUTPUT_FREQUENCY, card_index, global_flags.fake_cards_audio);
1507                                 configure_card(card_index, capture, CardType::FAKE_CAPTURE, /*output=*/nullptr, /*is_srt_card=*/false);
1508                                 card->jitter_history.clear();
1509                                 card->capture->start_bm_capture();
1510                         } else {
1511                                 // NOTE: The theme might end up forcing the card back at some later point
1512                                 // (ie., force_active is false now, but might immediately be true again on
1513                                 // e.g. the next frame). That should be rare, though, so we don't bother
1514                                 // adjusting the message.
1515                                 fprintf(stderr, "Card %u went away, removing. (To keep a fake card, increase --num-cards.)\n", card_index);
1516                                 theme->remove_card(card_index);
1517                                 configure_card(card_index, /*capture=*/nullptr, CardType::FAKE_CAPTURE, /*output=*/nullptr, /*is_srt_card=*/false);
1518                                 card->jitter_history.clear();
1519                         }
1520                 }
1521         }
1522
1523         // Count how many active cards we already have. Used below to check that we
1524         // don't go past the max_cards limit set by the user. Note that (non-SRT) video
1525         // and HTML “cards” don't count towards this limit.
1526         int num_video_cards = 0;
1527         for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) {
1528                 CaptureCard *card = &cards[card_index];
1529                 if (card->type == CardType::LIVE_CARD || is_srt_card(card)) {
1530                         ++num_video_cards;
1531                 }
1532         }
1533
1534         // Check for cards that have been connected since last frame.
1535         vector<libusb_device *> hotplugged_cards_copy;
1536 #ifdef HAVE_SRT
1537         vector<int> hotplugged_srt_cards_copy;
1538 #endif
1539         {
1540                 lock_guard<mutex> lock(hotplug_mutex);
1541                 swap(hotplugged_cards, hotplugged_cards_copy);
1542 #ifdef HAVE_SRT
1543                 swap(hotplugged_srt_cards, hotplugged_srt_cards_copy);
1544 #endif
1545         }
1546         for (libusb_device *new_dev : hotplugged_cards_copy) {
1547                 // Look for a fake capture card where we can stick this in.
1548                 int free_card_index = -1;
1549                 for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) {
1550                         if (cards[card_index].is_fake_capture) {
1551                                 free_card_index = card_index;
1552                                 break;
1553                         }
1554                 }
1555
1556                 if (free_card_index == -1 || num_video_cards >= global_flags.max_num_cards) {
1557                         fprintf(stderr, "New card plugged in, but no free slots -- ignoring.\n");
1558                         libusb_unref_device(new_dev);
1559                 } else {
1560                         // BMUSBCapture takes ownership.
1561                         fprintf(stderr, "New card plugged in, choosing slot %d.\n", free_card_index);
1562                         CaptureCard *card = &cards[free_card_index];
1563                         BMUSBCapture *capture = new BMUSBCapture(free_card_index, new_dev);
1564                         configure_card(free_card_index, capture, CardType::LIVE_CARD, /*output=*/nullptr, /*is_srt_card=*/false);
1565                         card->jitter_history.clear();
1566                         capture->set_card_disconnected_callback(bind(&Mixer::bm_hotplug_remove, this, free_card_index));
1567                         capture->start_bm_capture();
1568                 }
1569         }
1570
1571 #ifdef HAVE_SRT
1572         // Same, for SRT inputs.
1573         for (SRTSOCKET sock : hotplugged_srt_cards_copy) {
1574                 char name[256];
1575                 int namelen = sizeof(name);
1576                 srt_getsockopt(sock, /*ignored=*/0, SRTO_STREAMID, name, &namelen);
1577                 string stream_id(name, namelen);
1578
1579                 // Look for a fake capture card where we can stick this in.
1580                 // Prioritize ones that previously held SRT streams with the
1581                 // same stream ID, if any exist -- and it multiple exist,
1582                 // take the one that disconnected the last.
1583                 int first_free_card_index = -1, last_matching_free_card_index = -1;
1584                 for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) {
1585                         CaptureCard *card = &cards[card_index];
1586                         if (!card->is_fake_capture) {
1587                                 continue;
1588                         }
1589                         if (first_free_card_index == -1) {
1590                                 first_free_card_index = card_index;
1591                         }
1592                         if (card->last_srt_stream_id == stream_id &&
1593                             (last_matching_free_card_index == -1 ||
1594                              card->fake_capture_counter >
1595                                 cards[last_matching_free_card_index].fake_capture_counter)) {
1596                                 last_matching_free_card_index = card_index;
1597                         }
1598                 }
1599
1600                 const int free_card_index = (last_matching_free_card_index != -1)
1601                         ? last_matching_free_card_index : first_free_card_index;
1602                 if (free_card_index == -1 || num_video_cards >= global_flags.max_num_cards) {
1603                         if (stream_id.empty()) {
1604                                 stream_id = "no name";
1605                         }
1606                         fprintf(stderr, "New SRT stream connected (%s), but no free slots -- ignoring.\n", stream_id.c_str());
1607                         srt_close(sock);
1608                 } else {
1609                         // FFmpegCapture takes ownership.
1610                         if (stream_id.empty()) {
1611                                 fprintf(stderr, "New unnamed SRT stream connected, choosing slot %d.\n", free_card_index);
1612                         } else {
1613                                 fprintf(stderr, "New SRT stream connected (%s), choosing slot %d.\n", stream_id.c_str(), free_card_index);
1614                         }
1615                         CaptureCard *card = &cards[free_card_index];
1616                         FFmpegCapture *capture = new FFmpegCapture(sock, stream_id);
1617                         capture->set_card_index(free_card_index);
1618                         configure_card(free_card_index, capture, CardType::FFMPEG_INPUT, /*output=*/nullptr, /*is_srt_card=*/true);
1619                         card->srt_metrics.update_srt_stats(sock);  // Initial zero stats.
1620                         card->last_srt_stream_id = stream_id;
1621                         card->jitter_history.clear();
1622                         capture->set_card_disconnected_callback(bind(&Mixer::bm_hotplug_remove, this, free_card_index));
1623                         capture->start_bm_capture();
1624                 }
1625         }
1626 #endif
1627
1628         // Finally, newly forced-to-active fake capture cards.
1629         for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) {
1630                 CaptureCard *card = &cards[card_index];
1631                 if (card->capture == nullptr && card->force_active) {
1632                         FakeCapture *capture = new FakeCapture(global_flags.width, global_flags.height, FAKE_FPS, OUTPUT_FREQUENCY, card_index, global_flags.fake_cards_audio);
1633                         configure_card(card_index, capture, CardType::FAKE_CAPTURE, /*output=*/nullptr, /*is_srt_card=*/false);
1634                         card->jitter_history.clear();
1635                         card->capture->start_bm_capture();
1636                 }
1637         }
1638 }
1639
1640
1641 void Mixer::schedule_audio_resampling_tasks(unsigned dropped_frames, int num_samples_per_frame, int length_per_frame, bool is_preroll, steady_clock::time_point frame_timestamp)
1642 {
1643         // Resample the audio as needed, including from previously dropped frames.
1644         for (unsigned frame_num = 0; frame_num < dropped_frames + 1; ++frame_num) {
1645                 const bool dropped_frame = (frame_num != dropped_frames);
1646                 {
1647                         // Signal to the audio thread to process this frame.
1648                         // Note that if the frame is a dropped frame, we signal that
1649                         // we don't want to use this frame as base for adjusting
1650                         // the resampler rate. The reason for this is that the timing
1651                         // of these frames is often way too late; they typically don't
1652                         // “arrive” before we synthesize them. Thus, we could end up
1653                         // in a situation where we have inserted e.g. five audio frames
1654                         // into the queue before we then start pulling five of them
1655                         // back out. This makes ResamplingQueue overestimate the delay,
1656                         // causing undue resampler changes. (We _do_ use the last,
1657                         // non-dropped frame; perhaps we should just discard that as well,
1658                         // since dropped frames are expected to be rare, and it might be
1659                         // better to just wait until we have a slightly more normal situation).
1660                         lock_guard<mutex> lock(audio_mutex);
1661                         bool adjust_rate = !dropped_frame && !is_preroll;
1662                         audio_task_queue.push(AudioTask{pts_int, num_samples_per_frame, adjust_rate, frame_timestamp});
1663                         audio_task_queue_changed.notify_one();
1664                 }
1665                 if (dropped_frame) {
1666                         // For dropped frames, increase the pts. Note that if the format changed
1667                         // in the meantime, we have no way of detecting that; we just have to
1668                         // assume the frame length is always the same.
1669                         pts_int += length_per_frame;
1670                 }
1671         }
1672 }
1673
1674 void Mixer::render_one_frame(int64_t duration)
1675 {
1676         // Determine the time code for this frame before we start rendering.
1677         string timecode_text = timecode_renderer->get_timecode_text(double(pts_int) / TIMEBASE, frame_num);
1678         if (display_timecode_on_stdout) {
1679                 printf("Timecode: '%s'\n", timecode_text.c_str());
1680         }
1681
1682         // Update Y'CbCr settings for all cards.
1683         {
1684                 lock_guard<mutex> lock(card_mutex);
1685                 for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) {
1686                         YCbCrInterpretation *interpretation = &ycbcr_interpretation[card_index];
1687                         input_state.ycbcr_coefficients_auto[card_index] = interpretation->ycbcr_coefficients_auto;
1688                         input_state.ycbcr_coefficients[card_index] = interpretation->ycbcr_coefficients;
1689                         input_state.full_range[card_index] = interpretation->full_range;
1690                 }
1691         }
1692
1693         // Get the main chain from the theme, and set its state immediately.
1694         Theme::Chain theme_main_chain = theme->get_chain(0, pts(), global_flags.width, global_flags.height, input_state);
1695         EffectChain *chain = theme_main_chain.chain;
1696         theme_main_chain.setup_chain();
1697         //theme_main_chain.chain->enable_phase_timing(true);
1698
1699         // If HDMI/SDI output is active and the user has requested auto mode,
1700         // its mode overrides the existing Y'CbCr setting for the chain.
1701         YCbCrLumaCoefficients ycbcr_output_coefficients;
1702         if (global_flags.ycbcr_auto_coefficients && output_card_index != -1) {
1703                 ycbcr_output_coefficients = cards[output_card_index].output->preferred_ycbcr_coefficients();
1704         } else {
1705                 ycbcr_output_coefficients = global_flags.ycbcr_rec709_coefficients ? YCBCR_REC_709 : YCBCR_REC_601;
1706         }
1707
1708         // TODO: Reduce the duplication against theme.cpp.
1709         YCbCrFormat output_ycbcr_format;
1710         output_ycbcr_format.chroma_subsampling_x = 1;
1711         output_ycbcr_format.chroma_subsampling_y = 1;
1712         output_ycbcr_format.luma_coefficients = ycbcr_output_coefficients;
1713         output_ycbcr_format.full_range = false;
1714         output_ycbcr_format.num_levels = 1 << global_flags.bit_depth;
1715         chain->change_ycbcr_output_format(output_ycbcr_format);
1716
1717         // Render main chain. If we're using zerocopy Quick Sync encoding
1718         // (the default case), we take an extra copy of the created outputs,
1719         // so that we can display it back to the screen later (it's less memory
1720         // bandwidth than writing and reading back an RGBA texture, even at 16-bit).
1721         // Ideally, we'd like to avoid taking copies and just use the main textures
1722         // for display as well, but they're just views into VA-API memory and must be
1723         // unmapped during encoding, so we can't use them for display, unfortunately.
1724         GLuint y_tex, cbcr_full_tex, cbcr_tex;
1725         GLuint y_copy_tex, cbcr_copy_tex = 0;
1726         GLuint y_display_tex, cbcr_display_tex;
1727         GLenum y_type = (global_flags.bit_depth > 8) ? GL_R16 : GL_R8;
1728         GLenum cbcr_type = (global_flags.bit_depth > 8) ? GL_RG16 : GL_RG8;
1729         const bool is_zerocopy = video_encoder->is_zerocopy();
1730         if (is_zerocopy) {
1731                 cbcr_full_tex = resource_pool->create_2d_texture(cbcr_type, global_flags.width, global_flags.height);
1732                 y_copy_tex = resource_pool->create_2d_texture(y_type, global_flags.width, global_flags.height);
1733                 cbcr_copy_tex = resource_pool->create_2d_texture(cbcr_type, global_flags.width / 2, global_flags.height / 2);
1734
1735                 y_display_tex = y_copy_tex;
1736                 cbcr_display_tex = cbcr_copy_tex;
1737
1738                 // y_tex and cbcr_tex will be given by VideoEncoder.
1739         } else {
1740                 cbcr_full_tex = resource_pool->create_2d_texture(cbcr_type, global_flags.width, global_flags.height);
1741                 y_tex = resource_pool->create_2d_texture(y_type, global_flags.width, global_flags.height);
1742                 cbcr_tex = resource_pool->create_2d_texture(cbcr_type, global_flags.width / 2, global_flags.height / 2);
1743
1744                 y_display_tex = y_tex;
1745                 cbcr_display_tex = cbcr_tex;
1746         }
1747
1748         const int64_t av_delay = lrint(global_flags.audio_queue_length_ms * 0.001 * TIMEBASE);  // Corresponds to the delay in ResamplingQueue.
1749         bool got_frame = video_encoder->begin_frame(pts_int + av_delay, duration, ycbcr_output_coefficients, theme_main_chain.input_frames, &y_tex, &cbcr_tex);
1750         assert(got_frame);
1751
1752         GLuint fbo;
1753         if (is_zerocopy) {
1754                 fbo = resource_pool->create_fbo(y_tex, cbcr_full_tex, y_copy_tex);
1755         } else {
1756                 fbo = resource_pool->create_fbo(y_tex, cbcr_full_tex);
1757         }
1758         check_error();
1759         chain->render_to_fbo(fbo, global_flags.width, global_flags.height);
1760
1761         if (display_timecode_in_stream) {
1762                 // Render the timecode on top.
1763                 timecode_renderer->render_timecode(fbo, timecode_text);
1764         }
1765
1766         resource_pool->release_fbo(fbo);
1767
1768         if (is_zerocopy) {
1769                 chroma_subsampler->subsample_chroma(cbcr_full_tex, global_flags.width, global_flags.height, cbcr_tex, cbcr_copy_tex);
1770         } else {
1771                 chroma_subsampler->subsample_chroma(cbcr_full_tex, global_flags.width, global_flags.height, cbcr_tex);
1772         }
1773         if (output_card_index != -1) {
1774                 cards[output_card_index].output->send_frame(y_tex, cbcr_full_tex, ycbcr_output_coefficients, theme_main_chain.input_frames, pts_int, duration);
1775         }
1776         resource_pool->release_2d_texture(cbcr_full_tex);
1777
1778         // Set the right state for the Y' and CbCr textures we use for display.
1779         glBindFramebuffer(GL_FRAMEBUFFER, 0);
1780         glBindTexture(GL_TEXTURE_2D, y_display_tex);
1781         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1782         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1783         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1784
1785         glBindTexture(GL_TEXTURE_2D, cbcr_display_tex);
1786         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1787         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1788         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1789
1790         RefCountedGLsync fence = video_encoder->end_frame();
1791
1792         // The live frame pieces the Y'CbCr texture copies back into RGB and displays them.
1793         // It owns y_display_tex and cbcr_display_tex now (whichever textures they are).
1794         DisplayFrame live_frame;
1795         live_frame.chain = display_chain.get();
1796         live_frame.setup_chain = [this, y_display_tex, cbcr_display_tex]{
1797                 display_input->set_texture_num(0, y_display_tex);
1798                 display_input->set_texture_num(1, cbcr_display_tex);
1799         };
1800         live_frame.ready_fence = fence;
1801         live_frame.input_frames = {};
1802         live_frame.temp_textures = { y_display_tex, cbcr_display_tex };
1803         output_channel[OUTPUT_LIVE].output_frame(move(live_frame));
1804
1805         // Set up preview and any additional channels.
1806         for (int i = 1; i < theme->get_num_channels() + 2; ++i) {
1807                 DisplayFrame display_frame;
1808                 Theme::Chain chain = theme->get_chain(i, pts(), global_flags.width, global_flags.height, input_state);  // FIXME: dimensions
1809                 display_frame.chain = move(chain.chain);
1810                 display_frame.setup_chain = move(chain.setup_chain);
1811                 display_frame.ready_fence = fence;
1812                 display_frame.input_frames = move(chain.input_frames);
1813                 display_frame.temp_textures = {};
1814                 output_channel[i].output_frame(move(display_frame));
1815         }
1816 }
1817
1818 void Mixer::audio_thread_func()
1819 {
1820         pthread_setname_np(pthread_self(), "Mixer_Audio");
1821
1822         while (!should_quit) {
1823                 AudioTask task;
1824
1825                 {
1826                         unique_lock<mutex> lock(audio_mutex);
1827                         audio_task_queue_changed.wait(lock, [this]{ return should_quit || !audio_task_queue.empty(); });
1828                         if (should_quit) {
1829                                 return;
1830                         }
1831                         task = audio_task_queue.front();
1832                         audio_task_queue.pop();
1833                 }
1834
1835                 ResamplingQueue::RateAdjustmentPolicy rate_adjustment_policy =
1836                         task.adjust_rate ? ResamplingQueue::ADJUST_RATE : ResamplingQueue::DO_NOT_ADJUST_RATE;
1837                 vector<float> samples_out = audio_mixer->get_output(
1838                         task.frame_timestamp,
1839                         task.num_samples,
1840                         rate_adjustment_policy);
1841
1842                 // Send the samples to the sound card, then add them to the output.
1843                 if (alsa) {
1844                         alsa->write(samples_out);
1845                 }
1846                 if (output_card_index != -1) {
1847                         const int64_t av_delay = lrint(global_flags.audio_queue_length_ms * 0.001 * TIMEBASE);  // Corresponds to the delay in ResamplingQueue.
1848                         cards[output_card_index].output->send_audio(task.pts_int + av_delay, samples_out);
1849                 }
1850                 video_encoder->add_audio(task.pts_int, move(samples_out));
1851         }
1852 }
1853
1854 void Mixer::release_display_frame(DisplayFrame *frame)
1855 {
1856         for (GLuint texnum : frame->temp_textures) {
1857                 resource_pool->release_2d_texture(texnum);
1858         }
1859         frame->temp_textures.clear();
1860         frame->ready_fence.reset();
1861         frame->input_frames.clear();
1862 }
1863
1864 void Mixer::start()
1865 {
1866         mixer_thread = thread(&Mixer::thread_func, this);
1867         audio_thread = thread(&Mixer::audio_thread_func, this);
1868 }
1869
1870 void Mixer::quit()
1871 {
1872         should_quit = true;
1873         audio_task_queue_changed.notify_one();
1874         mixer_thread.join();
1875         audio_thread.join();
1876 #ifdef HAVE_SRT
1877         if (global_flags.srt_port >= 0) {
1878                 // There's seemingly no other reasonable way to wake up the thread
1879                 // (libsrt's epoll equivalent is busy-waiting).
1880                 int sock = srt_create_socket();
1881                 if (sock != -1) {
1882                         sockaddr_in6 addr;
1883                         memset(&addr, 0, sizeof(addr));
1884                         addr.sin6_family = AF_INET6;
1885                         addr.sin6_addr = IN6ADDR_LOOPBACK_INIT;
1886                         addr.sin6_port = htons(global_flags.srt_port);
1887                         srt_connect(sock, (sockaddr *)&addr, sizeof(addr));
1888                         srt_close(sock);
1889                 }
1890                 srt_thread.join();
1891         }
1892 #endif
1893 }
1894
1895 void Mixer::transition_clicked(int transition_num)
1896 {
1897         theme->transition_clicked(transition_num, pts());
1898 }
1899
1900 void Mixer::channel_clicked(int preview_num)
1901 {
1902         theme->channel_clicked(preview_num);
1903 }
1904
1905 YCbCrInterpretation Mixer::get_input_ycbcr_interpretation(unsigned card_index) const
1906 {
1907         lock_guard<mutex> lock(card_mutex);
1908         return ycbcr_interpretation[card_index];
1909 }
1910
1911 void Mixer::set_input_ycbcr_interpretation(unsigned card_index, const YCbCrInterpretation &interpretation)
1912 {
1913         lock_guard<mutex> lock(card_mutex);
1914         ycbcr_interpretation[card_index] = interpretation;
1915 }
1916
1917 void Mixer::start_mode_scanning(unsigned card_index)
1918 {
1919         assert(card_index < MAX_VIDEO_CARDS);
1920         if (cards[card_index].capture == nullptr) {
1921                 // Inactive card. Should never happen.
1922                 return;
1923         }
1924         if (is_mode_scanning[card_index]) {
1925                 return;
1926         }
1927         is_mode_scanning[card_index] = true;
1928         mode_scanlist[card_index].clear();
1929         for (const auto &mode : cards[card_index].capture->get_available_video_modes()) {
1930                 mode_scanlist[card_index].push_back(mode.first);
1931         }
1932         assert(!mode_scanlist[card_index].empty());
1933         mode_scanlist_index[card_index] = 0;
1934         cards[card_index].capture->set_video_mode(mode_scanlist[card_index][0]);
1935         last_mode_scan_change[card_index] = steady_clock::now();
1936 }
1937
1938 map<uint32_t, VideoMode> Mixer::get_available_output_video_modes() const
1939 {
1940         assert(desired_output_card_index != -1);
1941         lock_guard<mutex> lock(card_mutex);
1942         return cards[desired_output_card_index].output->get_available_video_modes();
1943 }
1944
1945 string Mixer::get_ffmpeg_filename(unsigned card_index) const
1946 {
1947         assert(card_index < MAX_VIDEO_CARDS);
1948         assert(cards[card_index].type == CardType::FFMPEG_INPUT);
1949         return ((FFmpegCapture *)(cards[card_index].capture.get()))->get_filename();
1950 }
1951
1952 void Mixer::set_ffmpeg_filename(unsigned card_index, const string &filename) {
1953         assert(card_index < MAX_VIDEO_CARDS);
1954         assert(cards[card_index].type == CardType::FFMPEG_INPUT);
1955         ((FFmpegCapture *)(cards[card_index].capture.get()))->change_filename(filename);
1956 }
1957
1958 void Mixer::wait_for_next_frame()
1959 {
1960         unique_lock<mutex> lock(frame_num_mutex);
1961         unsigned old_frame_num = frame_num;
1962         frame_num_updated.wait_for(lock, seconds(1),  // Timeout is just in case.
1963                 [old_frame_num, this]{ return this->frame_num > old_frame_num; });
1964 }
1965
1966 Mixer::OutputChannel::~OutputChannel()
1967 {
1968         if (has_current_frame) {
1969                 parent->release_display_frame(&current_frame);
1970         }
1971         if (has_ready_frame) {
1972                 parent->release_display_frame(&ready_frame);
1973         }
1974 }
1975
1976 void Mixer::OutputChannel::output_frame(DisplayFrame &&frame)
1977 {
1978         // Store this frame for display. Remove the ready frame if any
1979         // (it was seemingly never used).
1980         {
1981                 lock_guard<mutex> lock(frame_mutex);
1982                 if (has_ready_frame) {
1983                         parent->release_display_frame(&ready_frame);
1984                 }
1985                 ready_frame = move(frame);
1986                 has_ready_frame = true;
1987
1988                 // Call the callbacks under the mutex (they should be short),
1989                 // so that we don't race against a callback removal.
1990                 for (const auto &key_and_callback : new_frame_ready_callbacks) {
1991                         key_and_callback.second();
1992                 }
1993         }
1994
1995         // Reduce the number of callbacks by filtering duplicates. The reason
1996         // why we bother doing this is that Qt seemingly can get into a state
1997         // where its builds up an essentially unbounded queue of signals,
1998         // consuming more and more memory, and there's no good way of collapsing
1999         // user-defined signals or limiting the length of the queue.
2000         if (transition_names_updated_callback) {
2001                 vector<string> transition_names = global_mixer->get_transition_names();
2002                 bool changed = false;
2003                 if (transition_names.size() != last_transition_names.size()) {
2004                         changed = true;
2005                 } else {
2006                         for (unsigned i = 0; i < transition_names.size(); ++i) {
2007                                 if (transition_names[i] != last_transition_names[i]) {
2008                                         changed = true;
2009                                         break;
2010                                 }
2011                         }
2012                 }
2013                 if (changed) {
2014                         transition_names_updated_callback(transition_names);
2015                         last_transition_names = transition_names;
2016                 }
2017         }
2018         if (name_updated_callback) {
2019                 string name = global_mixer->get_channel_name(channel);
2020                 if (name != last_name) {
2021                         name_updated_callback(name);
2022                         last_name = name;
2023                 }
2024         }
2025         if (color_updated_callback) {
2026                 string color = global_mixer->get_channel_color(channel);
2027                 if (color != last_color) {
2028                         color_updated_callback(color);
2029                         last_color = color;
2030                 }
2031         }
2032 }
2033
2034 bool Mixer::OutputChannel::get_display_frame(DisplayFrame *frame)
2035 {
2036         lock_guard<mutex> lock(frame_mutex);
2037         if (!has_current_frame && !has_ready_frame) {
2038                 return false;
2039         }
2040
2041         if (has_current_frame && has_ready_frame) {
2042                 // We have a new ready frame. Toss the current one.
2043                 parent->release_display_frame(&current_frame);
2044                 has_current_frame = false;
2045         }
2046         if (has_ready_frame) {
2047                 assert(!has_current_frame);
2048                 current_frame = move(ready_frame);
2049                 ready_frame.ready_fence.reset();  // Drop the refcount.
2050                 ready_frame.input_frames.clear();  // Drop the refcounts.
2051                 has_current_frame = true;
2052                 has_ready_frame = false;
2053         }
2054
2055         *frame = current_frame;
2056         return true;
2057 }
2058
2059 void Mixer::OutputChannel::add_frame_ready_callback(void *key, Mixer::new_frame_ready_callback_t callback)
2060 {
2061         lock_guard<mutex> lock(frame_mutex);
2062         new_frame_ready_callbacks[key] = callback;
2063 }
2064
2065 void Mixer::OutputChannel::remove_frame_ready_callback(void *key)
2066 {
2067         lock_guard<mutex> lock(frame_mutex);
2068         new_frame_ready_callbacks.erase(key);
2069 }
2070
2071 void Mixer::OutputChannel::set_transition_names_updated_callback(Mixer::transition_names_updated_callback_t callback)
2072 {
2073         transition_names_updated_callback = callback;
2074 }
2075
2076 void Mixer::OutputChannel::set_name_updated_callback(Mixer::name_updated_callback_t callback)
2077 {
2078         name_updated_callback = callback;
2079 }
2080
2081 void Mixer::OutputChannel::set_color_updated_callback(Mixer::color_updated_callback_t callback)
2082 {
2083         color_updated_callback = callback;
2084 }
2085
2086 #ifdef HAVE_SRT
2087 void Mixer::start_srt()
2088 {
2089         SRTSOCKET sock = srt_create_socket();
2090         sockaddr_in6 addr;
2091         memset(&addr, 0, sizeof(addr));
2092         addr.sin6_family = AF_INET6;
2093         addr.sin6_port = htons(global_flags.srt_port);
2094
2095         int zero = 0;
2096         int err = srt_setsockopt(sock, /*level=*/0, SRTO_IPV6ONLY, &zero, sizeof(zero));
2097         if (err != 0) {
2098                 fprintf(stderr, "srt_setsockopt(SRTO_IPV6ONLY): %s\n", srt_getlasterror_str());
2099                 abort();
2100         }
2101         err = srt_bind(sock, (sockaddr *)&addr, sizeof(addr));
2102         if (err != 0) {
2103                 fprintf(stderr, "srt_bind: %s\n", srt_getlasterror_str());
2104                 abort();
2105         }
2106         err = srt_listen(sock, MAX_VIDEO_CARDS);
2107         if (err != 0) {
2108                 fprintf(stderr, "srt_listen: %s\n", srt_getlasterror_str());
2109                 abort();
2110         }
2111
2112         srt_thread = thread([this, sock] {
2113                 sockaddr_in6 addr;
2114                 for ( ;; ) {
2115                         int sa_len = sizeof(addr);
2116                         int clientsock = srt_accept(sock, (sockaddr *)&addr, &sa_len);
2117                         if (should_quit) {
2118                                 if (clientsock != -1) {
2119                                         srt_close(clientsock);
2120                                 }
2121                                 break;
2122                         }
2123                         if (!global_flags.enable_srt) {  // Runtime UI toggle.
2124                                 // Perhaps not as good as never listening in the first place,
2125                                 // but much simpler to turn on and off.
2126                                 srt_close(clientsock);
2127                                 continue;
2128                         }
2129                         lock_guard<mutex> lock(hotplug_mutex);
2130                         hotplugged_srt_cards.push_back(clientsock);
2131                 }
2132                 srt_close(sock);
2133         });
2134 }
2135 #endif
2136
2137 string Mixer::description_for_card(unsigned card_index)
2138 {
2139         CaptureCard *card = &cards[card_index];
2140         if (card->capture == nullptr) {
2141                 // Should never be called for inactive cards, but OK.
2142                 char buf[256];
2143                 snprintf(buf, sizeof(buf), "Inactive capture card %u", card_index);
2144                 return buf;
2145         }
2146         if (card->type != CardType::FFMPEG_INPUT) {
2147                 char buf[256];
2148                 snprintf(buf, sizeof(buf), "Capture card %u (%s)", card_index, card->capture->get_description().c_str());
2149                 return buf;
2150         }
2151
2152         // Number (non-SRT) FFmpeg inputs from zero, separately from the capture cards,
2153         // since it's not too obvious for the user that they are “cards”.
2154         unsigned ffmpeg_index = 0;
2155         for (unsigned i = 0; i < card_index; ++i) {
2156                 CaptureCard *other_card = &cards[i];
2157                 if (other_card->type == CardType::FFMPEG_INPUT && !is_srt_card(other_card)) {
2158                         ++ffmpeg_index;
2159                 }
2160         }
2161         char buf[256];
2162         snprintf(buf, sizeof(buf), "Video input %u (%s)", ffmpeg_index, card->capture->get_description().c_str());
2163         return buf;
2164 }
2165
2166 bool Mixer::is_srt_card(const Mixer::CaptureCard *card)
2167 {
2168 #ifdef HAVE_SRT
2169         if (card->type == CardType::FFMPEG_INPUT) {
2170                 int srt_sock = static_cast<FFmpegCapture *>(card->capture.get())->get_srt_sock();
2171                 return srt_sock != -1;
2172         }
2173 #endif
2174         return false;
2175 }
2176
2177 mutex RefCountedGLsync::fence_lock;