]> git.sesse.net Git - nageru/blob - nageru/mixer.cpp
Fix a Clang 19 warning.
[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(), create_surface(format)));
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                 while (!card->new_frames.empty()) card->new_frames.pop_front();
650                 card->last_timecode = -1;
651                 card->capture->set_pixel_format(pixel_format);
652                 card->capture->configure_card();
653
654                 // NOTE: start_bm_capture() happens in thread_func().
655         }
656
657         if (is_srt_card) {
658                 assert(card_type == CardType::FFMPEG_INPUT);
659         }
660
661         DeviceSpec device{InputSourceType::CAPTURE_CARD, card_index};
662         unsigned num_channels = card_type == CardType::LIVE_CARD ? 8 : 2;
663         if (is_active) {
664                 audio_mixer->set_device_parameters(device, card->capture->get_description(), card_type, num_channels, /*active=*/true);
665         } else {
666                 // Note: Keeps the previous name, if any.
667                 char name[32];
668                 snprintf(name, sizeof(name), "Fake card %u", card_index + 1);
669                 audio_mixer->set_device_parameters(device, name, card_type, num_channels, /*active=*/false);
670         }
671         audio_mixer->reset_resampler(device);
672         audio_mixer->trigger_state_changed_callback();
673
674         // Unregister old metrics, if any.
675         if (!card->labels.empty()) {
676                 const vector<pair<string, string>> &labels = card->labels;
677                 card->jitter_history.unregister_metrics(labels);
678                 card->queue_length_policy.unregister_metrics(labels);
679                 global_metrics.remove_if_exists("input_received_frames", labels);
680                 global_metrics.remove_if_exists("input_dropped_frames_jitter", labels);
681                 global_metrics.remove_if_exists("input_dropped_frames_error", labels);
682                 global_metrics.remove_if_exists("input_dropped_frames_resets", labels);
683                 global_metrics.remove_if_exists("input_queue_length_frames", labels);
684                 global_metrics.remove_if_exists("input_queue_duped_frames", labels);
685
686                 global_metrics.remove_if_exists("input_has_signal_bool", labels);
687                 global_metrics.remove_if_exists("input_is_connected_bool", labels);
688                 global_metrics.remove_if_exists("input_interlaced_bool", labels);
689                 global_metrics.remove_if_exists("input_width_pixels", labels);
690                 global_metrics.remove_if_exists("input_height_pixels", labels);
691                 global_metrics.remove_if_exists("input_frame_rate_nom", labels);
692                 global_metrics.remove_if_exists("input_frame_rate_den", labels);
693                 global_metrics.remove_if_exists("input_sample_rate_hz", labels);
694
695                 card->srt_metrics.deinit(labels);
696         }
697
698         if (is_active) {
699                 // Register metrics.
700                 vector<pair<string, string>> labels;
701                 char card_name[64];
702                 snprintf(card_name, sizeof(card_name), "%d", card_index);
703                 labels.emplace_back("card", card_name);
704
705                 switch (card_type) {
706                 case CardType::LIVE_CARD:
707                         labels.emplace_back("cardtype", "live");
708                         break;
709                 case CardType::FAKE_CAPTURE:
710                         labels.emplace_back("cardtype", "fake");
711                         break;
712                 case CardType::FFMPEG_INPUT:
713                         if (is_srt_card) {
714                                 labels.emplace_back("cardtype", "srt");
715                         } else {
716                                 labels.emplace_back("cardtype", "ffmpeg");
717                         }
718                         break;
719                 case CardType::CEF_INPUT:
720                         labels.emplace_back("cardtype", "cef");
721                         break;
722                 default:
723                         assert(false);
724                 }
725                 card->jitter_history.register_metrics(labels);
726                 card->queue_length_policy.register_metrics(labels);
727                 global_metrics.add("input_received_frames", labels, &card->metric_input_received_frames);
728                 global_metrics.add("input_dropped_frames_jitter", labels, &card->metric_input_dropped_frames_jitter);
729                 global_metrics.add("input_dropped_frames_error", labels, &card->metric_input_dropped_frames_error);
730                 global_metrics.add("input_dropped_frames_resets", labels, &card->metric_input_resets);
731                 global_metrics.add("input_queue_length_frames", labels, &card->metric_input_queue_length_frames, Metrics::TYPE_GAUGE);
732                 global_metrics.add("input_queue_duped_frames", labels, &card->metric_input_duped_frames);
733
734                 global_metrics.add("input_has_signal_bool", labels, &card->metric_input_has_signal_bool, Metrics::TYPE_GAUGE);
735                 global_metrics.add("input_is_connected_bool", labels, &card->metric_input_is_connected_bool, Metrics::TYPE_GAUGE);
736                 global_metrics.add("input_interlaced_bool", labels, &card->metric_input_interlaced_bool, Metrics::TYPE_GAUGE);
737                 global_metrics.add("input_width_pixels", labels, &card->metric_input_width_pixels, Metrics::TYPE_GAUGE);
738                 global_metrics.add("input_height_pixels", labels, &card->metric_input_height_pixels, Metrics::TYPE_GAUGE);
739                 global_metrics.add("input_frame_rate_nom", labels, &card->metric_input_frame_rate_nom, Metrics::TYPE_GAUGE);
740                 global_metrics.add("input_frame_rate_den", labels, &card->metric_input_frame_rate_den, Metrics::TYPE_GAUGE);
741                 global_metrics.add("input_sample_rate_hz", labels, &card->metric_input_sample_rate_hz, Metrics::TYPE_GAUGE);
742
743                 if (is_srt_card) {
744                         card->srt_metrics.init(labels);
745                 }
746
747                 card->labels = labels;
748         } else {
749                 card->labels.clear();
750         }
751 }
752
753 void Mixer::set_output_card_internal(int card_index)
754 {
755         // We don't really need to take card_mutex, since we're in the mixer
756         // thread and don't mess with any queues (which is the only thing that happens
757         // from other threads), but it's probably the safest in the long run.
758         unique_lock<mutex> lock(card_mutex);
759         if (output_card_index != -1) {
760                 // Switch the old card from output to input.
761                 CaptureCard *old_card = &cards[output_card_index];
762                 old_card->output->end_output();
763
764                 // Stop the fake card that we put into place.
765                 // This needs to _not_ happen under the mutex, to avoid deadlock
766                 // (delivering the last frame needs to take the mutex).
767                 CaptureInterface *fake_capture = old_card->capture.get();
768                 lock.unlock();
769                 fake_capture->stop_dequeue_thread();
770                 lock.lock();
771                 old_card->capture = move(old_card->parked_capture);  // TODO: reset the metrics
772                 old_card->is_fake_capture = false;
773                 old_card->capture->start_bm_capture();
774         }
775         if (card_index != -1) {
776                 CaptureCard *card = &cards[card_index];
777                 CaptureInterface *capture = card->capture.get();
778                 // TODO: DeckLinkCapture::stop_dequeue_thread can actually take
779                 // several seconds to complete (blocking on DisableVideoInput);
780                 // see if we can maybe do it asynchronously.
781                 lock.unlock();
782                 capture->stop_dequeue_thread();
783                 lock.lock();
784                 card->parked_capture = move(card->capture);
785                 CaptureInterface *fake_capture = new FakeCapture(global_flags.width, global_flags.height, FAKE_FPS, OUTPUT_FREQUENCY, card_index, global_flags.fake_cards_audio);
786                 configure_card(card_index, fake_capture, CardType::FAKE_CAPTURE, card->output.release(), /*is_srt_card=*/false);
787                 card->jitter_history.clear();
788                 card->capture->start_bm_capture();
789                 desired_output_video_mode = output_video_mode = card->output->pick_video_mode(desired_output_video_mode);
790                 card->output->start_output(desired_output_video_mode, pts_int, /*is_master_card=*/output_card_is_master);
791         }
792         output_card_index = card_index;
793         output_jitter_history.clear();
794 }
795
796 namespace {
797
798 int unwrap_timecode(uint16_t current_wrapped, int last)
799 {
800         uint16_t last_wrapped = last & 0xffff;
801         if (current_wrapped > last_wrapped) {
802                 return (last & ~0xffff) | current_wrapped;
803         } else {
804                 return 0x10000 + ((last & ~0xffff) | current_wrapped);
805         }
806 }
807
808 }  // namespace
809
810 void Mixer::bm_frame(unsigned card_index, uint16_t timecode,
811                      FrameAllocator::Frame video_frame, size_t video_offset, VideoFormat video_format,
812                      FrameAllocator::Frame audio_frame, size_t audio_offset, AudioFormat audio_format)
813 {
814         DeviceSpec device{InputSourceType::CAPTURE_CARD, card_index};
815         CaptureCard *card = &cards[card_index];
816
817         ++card->metric_input_received_frames;
818         card->metric_input_has_signal_bool = video_format.has_signal;
819         card->metric_input_is_connected_bool = video_format.is_connected;
820         card->metric_input_interlaced_bool = video_format.interlaced;
821         card->metric_input_width_pixels = video_format.width;
822         card->metric_input_height_pixels = video_format.height;
823         card->metric_input_frame_rate_nom = video_format.frame_rate_nom;
824         card->metric_input_frame_rate_den = video_format.frame_rate_den;
825         card->metric_input_sample_rate_hz = audio_format.sample_rate;
826
827         if (is_mode_scanning[card_index]) {
828                 if (video_format.has_signal) {
829                         // Found a stable signal, so stop scanning.
830                         is_mode_scanning[card_index] = false;
831                 } else {
832                         static constexpr double switch_time_s = 0.1;  // Should be enough time for the signal to stabilize.
833                         steady_clock::time_point now = steady_clock::now();
834                         double sec_since_last_switch = duration<double>(steady_clock::now() - last_mode_scan_change[card_index]).count();
835                         if (sec_since_last_switch > switch_time_s) {
836                                 // It isn't this mode; try the next one.
837                                 mode_scanlist_index[card_index]++;
838                                 mode_scanlist_index[card_index] %= mode_scanlist[card_index].size();
839                                 cards[card_index].capture->set_video_mode(mode_scanlist[card_index][mode_scanlist_index[card_index]]);
840                                 last_mode_scan_change[card_index] = now;
841                         }
842                 }
843         }
844
845         int64_t frame_length = int64_t(TIMEBASE) * video_format.frame_rate_den / video_format.frame_rate_nom;
846         assert(frame_length > 0);
847
848         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;
849         if (num_samples > OUTPUT_FREQUENCY / 10 && card->type != CardType::FFMPEG_INPUT) {
850                 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",
851                         description_for_card(card_index).c_str(), int(audio_frame.len), int(audio_offset),
852                         timecode, int(video_frame.len), int(video_offset), video_format.id);
853                 if (video_frame.owner) {
854                         video_frame.owner->release_frame(video_frame);
855                 }
856                 if (audio_frame.owner) {
857                         audio_frame.owner->release_frame(audio_frame);
858                 }
859                 return;
860         }
861
862         int dropped_frames = 0;
863         if (card->last_timecode != -1) {
864                 dropped_frames = unwrap_timecode(timecode, card->last_timecode) - card->last_timecode - 1;
865         }
866
867         // Number of samples per frame if we need to insert silence.
868         // (Could be nonintegral, but resampling will save us then.)
869         const int silence_samples = OUTPUT_FREQUENCY * video_format.frame_rate_den / video_format.frame_rate_nom;
870
871         if (dropped_frames > TYPICAL_FPS * 2) {
872                 fprintf(stderr, "%s lost more than two seconds (or time code jumping around; from 0x%04x to 0x%04x), resetting resampler\n",
873                         description_for_card(card_index).c_str(), card->last_timecode, timecode);
874                 audio_mixer->reset_resampler(device);
875                 dropped_frames = 0;
876                 ++card->metric_input_resets;
877         } else if (dropped_frames > 0) {
878                 // Insert silence as needed.
879                 fprintf(stderr, "%s dropped %d frame(s) (before timecode 0x%04x), inserting silence.\n",
880                         description_for_card(card_index).c_str(), dropped_frames, timecode);
881                 card->metric_input_dropped_frames_error += dropped_frames;
882
883                 bool success;
884                 do {
885                         success = audio_mixer->add_silence(device, silence_samples, dropped_frames);
886                 } while (!success);
887         }
888
889         if (num_samples > 0) {
890                 audio_mixer->add_audio(device, audio_frame.data + audio_offset, num_samples, audio_format, audio_frame.received_timestamp);
891
892                 // Audio for the MJPEG stream. We don't resample; audio that's not in 48 kHz
893                 // just gets dropped for now.
894                 //
895                 // Only bother doing MJPEG encoding if there are any connected clients
896                 // that want the stream.
897                 if (httpd.get_num_connected_multicam_clients() > 0 ||
898                     httpd.get_num_connected_siphon_clients(card_index) > 0) {
899                         vector<int32_t> converted_samples = convert_audio_to_fixed32(audio_frame.data + audio_offset, num_samples, audio_format, 2);
900                         lock_guard<mutex> lock(card_mutex);
901                         if (card->new_raw_audio.empty()) {
902                                 card->new_raw_audio = move(converted_samples);
903                         } else {
904                                 // For raw audio, we don't really synchronize audio and video;
905                                 // we just put the audio in frame by frame, and if a video frame is
906                                 // dropped, we still keep the audio, which means it will be added
907                                 // to the beginning of the next frame. It would probably be better
908                                 // to move the audio pts earlier to show this, but most players can
909                                 // live with some jitter, and in a lot of ways, it's much nicer for
910                                 // Futatabi to have all audio locked to a video frame.
911                                 card->new_raw_audio.insert(card->new_raw_audio.end(), converted_samples.begin(), converted_samples.end());
912
913                                 // Truncate to one second, just to be sure we don't have infinite buildup in case of weirdness.
914                                 if (card->new_raw_audio.size() > OUTPUT_FREQUENCY * 2) {
915                                         size_t excess_samples = card->new_raw_audio.size() - OUTPUT_FREQUENCY * 2;
916                                         card->new_raw_audio.erase(card->new_raw_audio.begin(), card->new_raw_audio.begin() + excess_samples);
917                                 }
918                         }
919                 }
920         }
921
922         // Done with the audio, so release it.
923         if (audio_frame.owner) {
924                 audio_frame.owner->release_frame(audio_frame);
925         }
926
927         card->last_timecode = timecode;
928
929         PBOFrameAllocator::Userdata *userdata = (PBOFrameAllocator::Userdata *)video_frame.userdata;
930         if (card->type == CardType::FFMPEG_INPUT && userdata != nullptr) {
931                 FFmpegCapture *ffmpeg_capture = static_cast<FFmpegCapture *>(card->capture.get());
932                 userdata->has_last_subtitle = ffmpeg_capture->get_has_last_subtitle();
933                 userdata->last_subtitle = ffmpeg_capture->get_last_subtitle();
934         }
935 #ifdef HAVE_SRT
936         if (card->type == CardType::FFMPEG_INPUT) {
937                 int srt_sock = static_cast<FFmpegCapture *>(card->capture.get())->get_srt_sock();
938                 if (srt_sock != -1) {
939                         card->srt_metrics.update_srt_stats(srt_sock);
940                 }
941         }
942 #endif
943
944         size_t y_offset, cbcr_offset;
945         size_t expected_length = video_format.stride * (video_format.height + video_format.extra_lines_top + video_format.extra_lines_bottom);
946         if (userdata != nullptr && userdata->pixel_format == PixelFormat_8BitYCbCrPlanar) {
947                 // The calculation above is wrong for planar Y'CbCr, so just override it.
948                 assert(card->type == CardType::FFMPEG_INPUT);
949                 assert(video_offset == 0);
950                 expected_length = video_frame.len;
951
952                 userdata->ycbcr_format = (static_cast<FFmpegCapture *>(card->capture.get()))->get_current_frame_ycbcr_format();
953                 y_offset = 0;
954                 cbcr_offset = video_format.width * video_format.height;
955         } else {
956                 // All the other Y'CbCr formats are 4:2:2.
957                 y_offset = video_frame.size / 2 + video_offset / 2;
958                 cbcr_offset = video_offset / 2;
959         }
960         if (video_frame.len - video_offset == 0 ||
961             video_frame.len - video_offset != expected_length) {
962                 if (video_frame.len != 0) {
963                         printf("%s: Dropping video frame with wrong length (%zu; expected %zu)\n",
964                                 description_for_card(card_index).c_str(), video_frame.len - video_offset, expected_length);
965                 }
966                 if (video_frame.owner) {
967                         video_frame.owner->release_frame(video_frame);
968                 }
969
970                 // Still send on the information that we _had_ a frame, even though it's corrupted,
971                 // so that pts can go up accordingly.
972                 {
973                         lock_guard<mutex> lock(card_mutex);
974                         CaptureCard::NewFrame new_frame;
975                         new_frame.frame = RefCountedFrame(FrameAllocator::Frame());
976                         new_frame.length = frame_length;
977                         new_frame.interlaced = false;
978                         new_frame.dropped_frames = dropped_frames;
979                         new_frame.received_timestamp = video_frame.received_timestamp;
980                         card->new_frames.push_back(move(new_frame));
981                         card->jitter_history.frame_arrived(video_frame.received_timestamp, frame_length, dropped_frames);
982                 }
983                 card->new_frames_changed.notify_all();
984                 return;
985         }
986
987         unsigned num_fields = video_format.interlaced ? 2 : 1;
988         steady_clock::time_point frame_upload_start;
989         if (video_format.interlaced) {
990                 // Send the two fields along as separate frames; the other side will need to add
991                 // a deinterlacer to actually get this right.
992                 assert(video_format.height % 2 == 0);
993                 video_format.height /= 2;
994                 assert(frame_length % 2 == 0);
995                 frame_length /= 2;
996                 num_fields = 2;
997                 frame_upload_start = steady_clock::now();
998         }
999         assert(userdata != nullptr);
1000         userdata->last_interlaced = video_format.interlaced;
1001         userdata->last_has_signal = video_format.has_signal;
1002         userdata->last_is_connected = video_format.is_connected;
1003         userdata->last_frame_rate_nom = video_format.frame_rate_nom;
1004         userdata->last_frame_rate_den = video_format.frame_rate_den;
1005         RefCountedFrame frame(video_frame);
1006
1007         // Send the frames on to the main thread, which will upload and process htem.
1008         // It is entirely possible to upload them in the same thread (and it might even be
1009         // faster, depending on the GPU and driver), but it appears to be trickling
1010         // driver bugs very easily.
1011         //
1012         // Note that this means we must hold on to the actual frame data in <userdata>
1013         // until the upload is done, but we hold on to <frame> much longer than that
1014         // (in fact, all the way until we no longer use the texture in rendering).
1015         for (unsigned field = 0; field < num_fields; ++field) {
1016                 if (field == 1) {
1017                         // Don't upload the second field as fast as we can; wait until
1018                         // the field time has approximately passed. (Otherwise, we could
1019                         // get timing jitter against the other sources, and possibly also
1020                         // against the video display, although the latter is not as critical.)
1021                         // This requires our system clock to be reasonably close to the
1022                         // video clock, but that's not an unreasonable assumption.
1023                         steady_clock::time_point second_field_start = frame_upload_start +
1024                                 nanoseconds(frame_length * 1000000000 / TIMEBASE);
1025                         this_thread::sleep_until(second_field_start);
1026                 }
1027
1028                 {
1029                         lock_guard<mutex> lock(card_mutex);
1030                         CaptureCard::NewFrame new_frame;
1031                         new_frame.frame = frame;
1032                         new_frame.length = frame_length;
1033                         new_frame.field = field;
1034                         new_frame.interlaced = video_format.interlaced;
1035                         new_frame.dropped_frames = dropped_frames;
1036                         new_frame.received_timestamp = video_frame.received_timestamp;  // Ignore the audio timestamp.
1037                         new_frame.video_format = video_format;
1038                         new_frame.video_offset = video_offset;
1039                         new_frame.y_offset = y_offset;
1040                         new_frame.cbcr_offset = cbcr_offset;
1041                         new_frame.texture_uploaded = false;
1042                         if (card->type == CardType::FFMPEG_INPUT) {
1043                                 FFmpegCapture *ffmpeg_capture = static_cast<FFmpegCapture *>(card->capture.get());
1044                                 new_frame.neutral_color = ffmpeg_capture->get_last_neutral_color();
1045                         }
1046                         card->new_frames.push_back(move(new_frame));
1047                         card->jitter_history.frame_arrived(video_frame.received_timestamp, frame_length, dropped_frames);
1048                         card->may_have_dropped_last_frame = false;
1049                 }
1050                 card->new_frames_changed.notify_all();
1051         }
1052 }
1053
1054 void Mixer::upload_texture_for_frame(
1055         int field, bmusb::VideoFormat video_format,
1056         size_t y_offset, size_t cbcr_offset, size_t video_offset, PBOFrameAllocator::Userdata *userdata)
1057 {
1058         size_t cbcr_width, cbcr_height;
1059         if (userdata != nullptr && userdata->pixel_format == PixelFormat_8BitYCbCrPlanar) {
1060                 cbcr_width = video_format.width / userdata->ycbcr_format.chroma_subsampling_x;
1061                 cbcr_height = video_format.height / userdata->ycbcr_format.chroma_subsampling_y;
1062         } else {
1063                 // All the other Y'CbCr formats are 4:2:2.
1064                 cbcr_width = video_format.width / 2;
1065                 cbcr_height = video_format.height;
1066         }
1067
1068         bool interlaced_stride = video_format.interlaced && (video_format.second_field_start == 1);
1069         if (video_format.interlaced) {
1070                 cbcr_height /= 2;
1071         }
1072
1073         unsigned field_start_line;
1074         if (field == 1) {
1075                 field_start_line = video_format.second_field_start;
1076         } else {
1077                 field_start_line = video_format.extra_lines_top;
1078         }
1079
1080         // For anything not FRAME_FORMAT_YCBCR_10BIT, v210_width will be nonsensical but not used.
1081         size_t v210_width = video_format.stride / sizeof(uint32_t);
1082         ensure_texture_resolution(userdata, field, video_format.width, video_format.height, cbcr_width, cbcr_height, v210_width);
1083
1084         glBindBuffer(GL_PIXEL_UNPACK_BUFFER, userdata->pbo);
1085         check_error();
1086
1087         switch (userdata->pixel_format) {
1088                 case PixelFormat_10BitYCbCr: {
1089                         size_t field_start = video_offset + video_format.stride * field_start_line;
1090                         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);
1091                         v210_converter->convert(userdata->tex_v210[field], userdata->tex_444[field], video_format.width, video_format.height);
1092                         break;
1093                 }
1094                 case PixelFormat_8BitYCbCr: {
1095                         size_t field_y_start = y_offset + video_format.width * field_start_line;
1096                         size_t field_cbcr_start = cbcr_offset + cbcr_width * field_start_line * sizeof(uint16_t);
1097
1098                         // Make up our own strides, since we are interleaving.
1099                         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);
1100                         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);
1101                         break;
1102                 }
1103                 case PixelFormat_8BitYCbCrPlanar: {
1104                         assert(field_start_line == 0);  // We don't really support interlaced here.
1105                         size_t field_y_start = y_offset;
1106                         size_t field_cb_start = cbcr_offset;
1107                         size_t field_cr_start = cbcr_offset + cbcr_width * cbcr_height;
1108
1109                         // Make up our own strides, since we are interleaving.
1110                         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);
1111                         upload_texture(userdata->tex_cb[field], cbcr_width, cbcr_height, cbcr_width, interlaced_stride, GL_RED, GL_UNSIGNED_BYTE, field_cb_start);
1112                         upload_texture(userdata->tex_cr[field], cbcr_width, cbcr_height, cbcr_width, interlaced_stride, GL_RED, GL_UNSIGNED_BYTE, field_cr_start);
1113                         break;
1114                 }
1115                 case PixelFormat_8BitBGRA: {
1116                         size_t field_start = video_offset + video_format.stride * field_start_line;
1117                         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);
1118                         // These could be asked to deliver mipmaps at any time.
1119                         glBindTexture(GL_TEXTURE_2D, userdata->tex_rgba[field]);
1120                         check_error();
1121                         glGenerateMipmap(GL_TEXTURE_2D);
1122                         check_error();
1123                         glBindTexture(GL_TEXTURE_2D, 0);
1124                         check_error();
1125                         break;
1126                 }
1127                 default:
1128                         assert(false);
1129         }
1130
1131         glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
1132         check_error();
1133 }
1134
1135 void Mixer::bm_hotplug_add(libusb_device *dev)
1136 {
1137         lock_guard<mutex> lock(hotplug_mutex);
1138         hotplugged_cards.push_back(dev);
1139 }
1140
1141 void Mixer::bm_hotplug_remove(unsigned card_index)
1142 {
1143         cards[card_index].new_frames_changed.notify_all();
1144 }
1145
1146 void Mixer::thread_func()
1147 {
1148         pthread_setname_np(pthread_self(), "Mixer_OpenGL");
1149
1150         eglBindAPI(EGL_OPENGL_API);
1151         QOpenGLContext *context = create_context(mixer_surface);
1152         if (!make_current(context, mixer_surface)) {
1153                 printf("oops\n");
1154                 abort();
1155         }
1156
1157         // Start the actual capture. (We don't want to do it before we're actually ready
1158         // to process output frames.)
1159         for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) {
1160                 if (int(card_index) != output_card_index && cards[card_index].capture != nullptr) {
1161                         cards[card_index].capture->start_bm_capture();
1162                 }
1163         }
1164
1165         BasicStats basic_stats(/*verbose=*/true, /*use_opengl=*/true);
1166         int stats_dropped_frames = 0;
1167
1168         while (!should_quit) {
1169                 if (desired_output_card_index != output_card_index) {
1170                         set_output_card_internal(desired_output_card_index);
1171                 }
1172                 if (output_card_index != -1 &&
1173                     desired_output_video_mode != output_video_mode) {
1174                         DeckLinkOutput *output = cards[output_card_index].output.get();
1175                         output->end_output();
1176                         desired_output_video_mode = output_video_mode = output->pick_video_mode(desired_output_video_mode);
1177                         output->start_output(desired_output_video_mode, pts_int, /*is_master_card=*/output_card_is_master);
1178                 }
1179
1180                 {
1181                         lock_guard<mutex> lock(card_mutex);
1182                         handle_hotplugged_cards();
1183                 }
1184
1185                 CaptureCard::NewFrame new_frames[MAX_VIDEO_CARDS];
1186                 bool has_new_frame[MAX_VIDEO_CARDS] = { false };
1187
1188                 bool master_card_is_output;
1189                 unsigned master_card_index;
1190                 if (output_card_index != -1 && output_card_is_master) {
1191                         master_card_is_output = true;
1192                         master_card_index = output_card_index;
1193                 } else {
1194                         master_card_is_output = false;
1195                         master_card_index = theme->map_signal_to_card(master_clock_channel);
1196                         assert(master_card_index < MAX_VIDEO_CARDS);
1197                 }
1198
1199                 vector<int32_t> raw_audio[MAX_VIDEO_CARDS];  // For MJPEG encoding.
1200                 OutputFrameInfo output_frame_info = get_one_frame_from_each_card(master_card_index, master_card_is_output, new_frames, has_new_frame, raw_audio);
1201                 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);
1202                 stats_dropped_frames += output_frame_info.dropped_frames;
1203
1204                 for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) {
1205                         if (card_index == master_card_index || !has_new_frame[card_index]) {
1206                                 continue;
1207                         }
1208                         if (new_frames[card_index].frame->len == 0) {
1209                                 ++new_frames[card_index].dropped_frames;
1210                         }
1211                         if (new_frames[card_index].dropped_frames > 0) {
1212                                 printf("%s dropped %d frames before this\n",
1213                                         description_for_card(card_index).c_str(), int(new_frames[card_index].dropped_frames));
1214                         }
1215                 }
1216
1217                 // If the first card is reporting a corrupted or otherwise dropped frame,
1218                 // just increase the pts (skipping over this frame) and don't try to compute anything new.
1219                 if (!master_card_is_output &&
1220                     new_frames[master_card_index].frame != nullptr &&  // Timeout.
1221                     new_frames[master_card_index].frame->len == 0) {
1222                         ++stats_dropped_frames;
1223                         pts_int += new_frames[master_card_index].length;
1224                         continue;
1225                 }
1226
1227                 for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) {
1228                         if (!has_new_frame[card_index] || new_frames[card_index].frame->len == 0)
1229                                 continue;
1230
1231                         CaptureCard::NewFrame *new_frame = &new_frames[card_index];
1232                         assert(new_frame->frame != nullptr);
1233                         insert_new_frame(new_frame->frame, new_frame->field, new_frame->interlaced, card_index, &input_state);
1234                         check_error();
1235
1236                         // The new texture might need uploading before use.
1237                         if (!new_frame->texture_uploaded) {
1238                                 upload_texture_for_frame(new_frame->field, new_frame->video_format, new_frame->y_offset, new_frame->cbcr_offset,
1239                                         new_frame->video_offset, (PBOFrameAllocator::Userdata *)new_frame->frame->userdata);
1240                                 new_frame->texture_uploaded = true;
1241                         }
1242
1243                         // Only set the white balance if it actually changed. This means that the user
1244                         // is free to override the white balance in a video with no white balance information
1245                         // actually set (ie. r=g=b=1 all the time), or one where the white point is wrong,
1246                         // but frame-to-frame decisions will be heeded. We do this pretty much as late
1247                         // as possible (ie., after picking out the frame from the buffer), so that we are sure
1248                         // that the change takes effect on exactly the right frame.
1249                         if (fabs(new_frame->neutral_color.r - last_received_neutral_color[card_index].r) > 1e-3 ||
1250                             fabs(new_frame->neutral_color.g - last_received_neutral_color[card_index].g) > 1e-3 ||
1251                             fabs(new_frame->neutral_color.b - last_received_neutral_color[card_index].b) > 1e-3) {
1252                                 theme->set_wb_for_card(card_index, new_frame->neutral_color.r, new_frame->neutral_color.g, new_frame->neutral_color.b);
1253                                 last_received_neutral_color[card_index] = new_frame->neutral_color;
1254                         }
1255
1256                         if (new_frame->frame->data_copy != nullptr && mjpeg_encoder->should_encode_mjpeg_for_card(card_index)) {
1257                                 RGBTriplet neutral_color = theme->get_white_balance_for_card(card_index);
1258                                 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);
1259                         }
1260
1261                 }
1262
1263                 int64_t frame_duration = output_frame_info.frame_duration;
1264                 render_one_frame(frame_duration);
1265                 {
1266                         lock_guard<mutex> lock(frame_num_mutex);
1267                         ++frame_num;
1268                 }
1269                 frame_num_updated.notify_all();
1270                 pts_int += frame_duration;
1271
1272                 basic_stats.update(frame_num, stats_dropped_frames);
1273                 // if (frame_num % 100 == 0) chain->print_phase_timing();
1274
1275                 if (should_cut.exchange(false)) {  // Test and clear.
1276                         video_encoder->do_cut(frame_num);
1277                 }
1278
1279 #if 0
1280                 // Reset every 100 frames, so that local variations in frame times
1281                 // (especially for the first few frames, when the shaders are
1282                 // compiled etc.) don't make it hard to measure for the entire
1283                 // remaining duration of the program.
1284                 if (frame == 10000) {
1285                         frame = 0;
1286                         start = now;
1287                 }
1288 #endif
1289                 check_error();
1290         }
1291
1292         resource_pool->clean_context();
1293 }
1294
1295 bool Mixer::input_card_is_master_clock(unsigned card_index, unsigned master_card_index) const
1296 {
1297         if (output_card_index != -1 && output_card_is_master) {
1298                 // The output card (ie., cards[output_card_index].output) is the master clock,
1299                 // so no input card (ie., cards[card_index].capture) is.
1300                 return false;
1301         }
1302         return (card_index == master_card_index);
1303 }
1304
1305 void Mixer::trim_queue(CaptureCard *card, size_t safe_queue_length)
1306 {
1307         // Count the number of frames in the queue, including any frames
1308         // we dropped. It's hard to know exactly how we should deal with
1309         // dropped (corrupted) input frames; they don't help our goal of
1310         // avoiding starvation, but they still add to the problem of latency.
1311         // Since dropped frames is going to mean a bump in the signal anyway,
1312         // we err on the side of having more stable latency instead.
1313         unsigned queue_length = 0;
1314         for (const CaptureCard::NewFrame &frame : card->new_frames) {
1315                 queue_length += frame.dropped_frames + 1;
1316         }
1317
1318         // If needed, drop frames until the queue is below the safe limit.
1319         // We prefer to drop from the head, because all else being equal,
1320         // we'd like more recent frames (less latency).
1321         unsigned dropped_frames = 0;
1322         while (queue_length > safe_queue_length) {
1323                 assert(!card->new_frames.empty());
1324                 assert(queue_length > card->new_frames.front().dropped_frames);
1325                 queue_length -= card->new_frames.front().dropped_frames;
1326
1327                 if (queue_length <= safe_queue_length) {
1328                         // No need to drop anything.
1329                         break;
1330                 }
1331
1332                 card->new_frames.pop_front();
1333                 card->new_frames_changed.notify_all();
1334                 --queue_length;
1335                 ++dropped_frames;
1336
1337                 if (queue_length == 0 && card->is_cef_capture) {
1338                         card->may_have_dropped_last_frame = true;
1339                 }
1340         }
1341
1342         card->metric_input_dropped_frames_jitter += dropped_frames;
1343         card->metric_input_queue_length_frames = queue_length;
1344
1345 #if 0
1346         if (dropped_frames > 0) {
1347                 fprintf(stderr, "Card %u dropped %u frame(s) to keep latency down.\n",
1348                         card_index, dropped_frames);
1349         }
1350 #endif
1351 }
1352
1353 pair<string, string> Mixer::get_channels_json()
1354 {
1355         Channels ret;
1356         for (int channel_idx = 0; channel_idx < theme->get_num_channels(); ++channel_idx) {
1357                 Channel *channel = ret.add_channel();
1358                 channel->set_index(channel_idx + 2);
1359                 channel->set_name(theme->get_channel_name(channel_idx + 2));
1360                 channel->set_color(theme->get_channel_color(channel_idx + 2));
1361         }
1362         string contents;
1363         google::protobuf::util::MessageToJsonString(ret, &contents);  // Ignore any errors.
1364         return make_pair(contents, "text/json");
1365 }
1366
1367 pair<string, string> Mixer::get_channel_color_http(unsigned channel_idx)
1368 {
1369         return make_pair(theme->get_channel_color(channel_idx), "text/plain");
1370 }
1371
1372 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])
1373 {
1374         OutputFrameInfo output_frame_info;
1375         constexpr steady_clock::duration master_card_timeout = milliseconds(200);
1376 start:
1377         unique_lock<mutex> lock(card_mutex, defer_lock);
1378         bool timed_out = false;
1379         if (master_card_is_output) {
1380                 // Clocked to the output, so wait for it to be ready for the next frame.
1381                 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);
1382                 lock.lock();
1383         } else {
1384                 // Wait for the master card to have a new frame.
1385                 output_frame_info.is_preroll = false;
1386                 lock.lock();
1387                 timed_out = !cards[master_card_index].new_frames_changed.wait_for(lock,
1388                         master_card_timeout,
1389                         [this, master_card_index] {
1390                                 return !cards[master_card_index].new_frames.empty() ||
1391                                         cards[master_card_index].capture == nullptr ||
1392                                         cards[master_card_index].capture->get_disconnected();
1393                         });
1394                 if (timed_out) {
1395                         fprintf(stderr, "WARNING: Master card (%s) did not deliver a frame for %u ms, creating a fake one.\n",
1396                                 description_for_card(master_card_index).c_str(),
1397                                 unsigned(duration_cast<milliseconds>(master_card_timeout).count()));
1398                 }
1399         }
1400
1401         if (timed_out) {
1402                 // The master card stalled for 200 ms (possible when it's e.g.
1403                 // an SRT card). Send a frame no matter what; this also makes sure
1404                 // any other cards get to empty their queues, and in general,
1405                 // that we make _some_ sort of forward progress.
1406                 handle_hotplugged_cards();
1407         } else if (master_card_is_output) {
1408                 handle_hotplugged_cards();
1409         } else if (cards[master_card_index].new_frames.empty()) {
1410                 // We were woken up, but not due to a new frame. Deal with it
1411                 // and then restart.
1412                 assert(cards[master_card_index].capture == nullptr ||
1413                        cards[master_card_index].capture->get_disconnected());
1414                 handle_hotplugged_cards();
1415                 lock.unlock();
1416                 goto start;
1417         }
1418
1419         for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) {
1420                 CaptureCard *card = &cards[card_index];
1421                 if (card->new_frames.empty()) {  // Starvation.
1422                         ++card->metric_input_duped_frames;
1423 #ifdef HAVE_CEF
1424                         if (card->is_cef_capture && card->may_have_dropped_last_frame) {
1425                                 // Unlike other sources, CEF is not guaranteed to send us a steady
1426                                 // stream of frames, so we'll have to ask it to repaint the frame
1427                                 // we dropped. (may_have_dropped_last_frame is set whenever we
1428                                 // trim the queue completely away, and cleared when we actually
1429                                 // get a new frame.)
1430                                 ((CEFCapture *)card->capture.get())->request_new_frame(/*ignore_if_locked=*/true);
1431                         }
1432 #endif
1433                 } else {
1434                         new_frames[card_index] = move(card->new_frames.front());
1435                         has_new_frame[card_index] = true;
1436                         card->new_frames.pop_front();
1437                         card->new_frames_changed.notify_all();
1438                 }
1439
1440                 raw_audio[card_index] = move(card->new_raw_audio);
1441         }
1442
1443         if (timed_out) {
1444                 // Pretend the frame happened a while ago and was only processed now,
1445                 // so that we get the duration sort-of right. This isn't ideal.
1446                 output_frame_info.dropped_frames = 0;  // Hard to define, really.
1447                 output_frame_info.frame_duration = lrint(TIMEBASE * duration<double>(master_card_timeout).count());
1448                 output_frame_info.frame_timestamp = steady_clock::now() - master_card_timeout;
1449         } else if (!master_card_is_output) {
1450                 output_frame_info.frame_timestamp = new_frames[master_card_index].received_timestamp;
1451                 output_frame_info.dropped_frames = new_frames[master_card_index].dropped_frames;
1452                 output_frame_info.frame_duration = new_frames[master_card_index].length;
1453         }
1454
1455         if (!output_frame_info.is_preroll) {
1456                 output_jitter_history.frame_arrived(output_frame_info.frame_timestamp, output_frame_info.frame_duration, output_frame_info.dropped_frames);
1457         }
1458
1459         for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) {
1460                 CaptureCard *card = &cards[card_index];
1461                 if (has_new_frame[card_index] &&
1462                     !input_card_is_master_clock(card_index, master_card_index) &&
1463                     !output_frame_info.is_preroll) {
1464                         card->queue_length_policy.update_policy(
1465                                 output_frame_info.frame_timestamp,
1466                                 card->jitter_history.get_expected_next_frame(),
1467                                 new_frames[master_card_index].length,
1468                                 output_frame_info.frame_duration,
1469                                 card->jitter_history.estimate_max_jitter(),
1470                                 output_jitter_history.estimate_max_jitter());
1471                         trim_queue(card, min<int>(global_flags.max_input_queue_frames,
1472                                                   card->queue_length_policy.get_safe_queue_length()));
1473                 }
1474         }
1475
1476         // This might get off by a fractional sample when changing master card
1477         // between ones with different frame rates, but that's fine.
1478         int64_t num_samples_times_timebase = int64_t(OUTPUT_FREQUENCY) * output_frame_info.frame_duration + fractional_samples;
1479         output_frame_info.num_samples = num_samples_times_timebase / TIMEBASE;
1480         fractional_samples = num_samples_times_timebase % TIMEBASE;
1481         assert(output_frame_info.num_samples >= 0);
1482
1483         if (timed_out) {
1484                 DeviceSpec device{InputSourceType::CAPTURE_CARD, master_card_index};
1485                 bool success;
1486                 do {
1487                         success = audio_mixer->add_silence(device, output_frame_info.num_samples, /*dropped_frames=*/0);
1488                 } while (!success);
1489         }
1490
1491         return output_frame_info;
1492 }
1493
1494 void Mixer::handle_hotplugged_cards()
1495 {
1496         // Check for cards that have been disconnected since last frame.
1497         for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) {
1498                 CaptureCard *card = &cards[card_index];
1499                 if (card->capture != nullptr && card->capture->get_disconnected()) {
1500                         bool is_active = card_index < unsigned(global_flags.min_num_cards) || cards[card_index].force_active;
1501                         if (is_active) {
1502                                 fprintf(stderr, "Card %u went away, replacing with a fake card.\n", card_index);
1503                                 FakeCapture *capture = new FakeCapture(global_flags.width, global_flags.height, FAKE_FPS, OUTPUT_FREQUENCY, card_index, global_flags.fake_cards_audio);
1504                                 configure_card(card_index, capture, CardType::FAKE_CAPTURE, /*output=*/nullptr, /*is_srt_card=*/false);
1505                                 card->jitter_history.clear();
1506                                 card->capture->start_bm_capture();
1507                         } else {
1508                                 // NOTE: The theme might end up forcing the card back at some later point
1509                                 // (ie., force_active is false now, but might immediately be true again on
1510                                 // e.g. the next frame). That should be rare, though, so we don't bother
1511                                 // adjusting the message.
1512                                 fprintf(stderr, "Card %u went away, removing. (To keep a fake card, increase --num-cards.)\n", card_index);
1513                                 theme->remove_card(card_index);
1514                                 configure_card(card_index, /*capture=*/nullptr, CardType::FAKE_CAPTURE, /*output=*/nullptr, /*is_srt_card=*/false);
1515                                 card->jitter_history.clear();
1516                         }
1517                 }
1518         }
1519
1520         // Count how many active cards we already have. Used below to check that we
1521         // don't go past the max_cards limit set by the user. Note that (non-SRT) video
1522         // and HTML “cards” don't count towards this limit.
1523         int num_video_cards = 0;
1524         for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) {
1525                 CaptureCard *card = &cards[card_index];
1526                 if (card->type == CardType::LIVE_CARD || is_srt_card(card)) {
1527                         ++num_video_cards;
1528                 }
1529         }
1530
1531         // Check for cards that have been connected since last frame.
1532         vector<libusb_device *> hotplugged_cards_copy;
1533 #ifdef HAVE_SRT
1534         vector<int> hotplugged_srt_cards_copy;
1535 #endif
1536         {
1537                 lock_guard<mutex> lock(hotplug_mutex);
1538                 swap(hotplugged_cards, hotplugged_cards_copy);
1539 #ifdef HAVE_SRT
1540                 swap(hotplugged_srt_cards, hotplugged_srt_cards_copy);
1541 #endif
1542         }
1543         for (libusb_device *new_dev : hotplugged_cards_copy) {
1544                 // Look for a fake capture card where we can stick this in.
1545                 int free_card_index = -1;
1546                 for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) {
1547                         if (cards[card_index].is_fake_capture) {
1548                                 free_card_index = card_index;
1549                                 break;
1550                         }
1551                 }
1552
1553                 if (free_card_index == -1 || num_video_cards >= global_flags.max_num_cards) {
1554                         fprintf(stderr, "New card plugged in, but no free slots -- ignoring.\n");
1555                         libusb_unref_device(new_dev);
1556                 } else {
1557                         // BMUSBCapture takes ownership.
1558                         fprintf(stderr, "New card plugged in, choosing slot %d.\n", free_card_index);
1559                         CaptureCard *card = &cards[free_card_index];
1560                         BMUSBCapture *capture = new BMUSBCapture(free_card_index, new_dev);
1561                         configure_card(free_card_index, capture, CardType::LIVE_CARD, /*output=*/nullptr, /*is_srt_card=*/false);
1562                         card->jitter_history.clear();
1563                         capture->set_card_disconnected_callback(bind(&Mixer::bm_hotplug_remove, this, free_card_index));
1564                         capture->start_bm_capture();
1565                 }
1566         }
1567
1568 #ifdef HAVE_SRT
1569         // Same, for SRT inputs.
1570         for (SRTSOCKET sock : hotplugged_srt_cards_copy) {
1571                 char name[256];
1572                 int namelen = sizeof(name);
1573                 srt_getsockopt(sock, /*ignored=*/0, SRTO_STREAMID, name, &namelen);
1574                 string stream_id(name, namelen);
1575
1576                 // Look for a fake capture card where we can stick this in.
1577                 // Prioritize ones that previously held SRT streams with the
1578                 // same stream ID, if any exist -- and it multiple exist,
1579                 // take the one that disconnected the last.
1580                 int first_free_card_index = -1, last_matching_free_card_index = -1;
1581                 for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) {
1582                         CaptureCard *card = &cards[card_index];
1583                         if (!card->is_fake_capture) {
1584                                 continue;
1585                         }
1586                         if (first_free_card_index == -1) {
1587                                 first_free_card_index = card_index;
1588                         }
1589                         if (card->last_srt_stream_id == stream_id &&
1590                             (last_matching_free_card_index == -1 ||
1591                              card->fake_capture_counter >
1592                                 cards[last_matching_free_card_index].fake_capture_counter)) {
1593                                 last_matching_free_card_index = card_index;
1594                         }
1595                 }
1596
1597                 const int free_card_index = (last_matching_free_card_index != -1)
1598                         ? last_matching_free_card_index : first_free_card_index;
1599                 if (free_card_index == -1 || num_video_cards >= global_flags.max_num_cards) {
1600                         if (stream_id.empty()) {
1601                                 stream_id = "no name";
1602                         }
1603                         fprintf(stderr, "New SRT stream connected (%s), but no free slots -- ignoring.\n", stream_id.c_str());
1604                         srt_close(sock);
1605                 } else {
1606                         // FFmpegCapture takes ownership.
1607                         if (stream_id.empty()) {
1608                                 fprintf(stderr, "New unnamed SRT stream connected, choosing slot %d.\n", free_card_index);
1609                         } else {
1610                                 fprintf(stderr, "New SRT stream connected (%s), choosing slot %d.\n", stream_id.c_str(), free_card_index);
1611                         }
1612                         CaptureCard *card = &cards[free_card_index];
1613                         FFmpegCapture *capture = new FFmpegCapture(sock, stream_id, create_surface_with_same_format(mixer_surface));
1614                         capture->set_card_index(free_card_index);
1615                         configure_card(free_card_index, capture, CardType::FFMPEG_INPUT, /*output=*/nullptr, /*is_srt_card=*/true);
1616                         card->srt_metrics.update_srt_stats(sock);  // Initial zero stats.
1617                         card->last_srt_stream_id = stream_id;
1618                         card->jitter_history.clear();
1619                         capture->set_card_disconnected_callback(bind(&Mixer::bm_hotplug_remove, this, free_card_index));
1620                         capture->start_bm_capture();
1621                 }
1622         }
1623 #endif
1624
1625         // Finally, newly forced-to-active fake capture cards.
1626         for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) {
1627                 CaptureCard *card = &cards[card_index];
1628                 if (card->capture == nullptr && card->force_active) {
1629                         FakeCapture *capture = new FakeCapture(global_flags.width, global_flags.height, FAKE_FPS, OUTPUT_FREQUENCY, card_index, global_flags.fake_cards_audio);
1630                         configure_card(card_index, capture, CardType::FAKE_CAPTURE, /*output=*/nullptr, /*is_srt_card=*/false);
1631                         card->jitter_history.clear();
1632                         card->capture->start_bm_capture();
1633                 }
1634         }
1635 }
1636
1637
1638 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)
1639 {
1640         // Resample the audio as needed, including from previously dropped frames.
1641         for (unsigned frame_num = 0; frame_num < dropped_frames + 1; ++frame_num) {
1642                 const bool dropped_frame = (frame_num != dropped_frames);
1643                 {
1644                         // Signal to the audio thread to process this frame.
1645                         // Note that if the frame is a dropped frame, we signal that
1646                         // we don't want to use this frame as base for adjusting
1647                         // the resampler rate. The reason for this is that the timing
1648                         // of these frames is often way too late; they typically don't
1649                         // “arrive” before we synthesize them. Thus, we could end up
1650                         // in a situation where we have inserted e.g. five audio frames
1651                         // into the queue before we then start pulling five of them
1652                         // back out. This makes ResamplingQueue overestimate the delay,
1653                         // causing undue resampler changes. (We _do_ use the last,
1654                         // non-dropped frame; perhaps we should just discard that as well,
1655                         // since dropped frames are expected to be rare, and it might be
1656                         // better to just wait until we have a slightly more normal situation).
1657                         lock_guard<mutex> lock(audio_mutex);
1658                         bool adjust_rate = !dropped_frame && !is_preroll;
1659                         audio_task_queue.push(AudioTask{pts_int, num_samples_per_frame, adjust_rate, frame_timestamp});
1660                         audio_task_queue_changed.notify_one();
1661                 }
1662                 if (dropped_frame) {
1663                         // For dropped frames, increase the pts. Note that if the format changed
1664                         // in the meantime, we have no way of detecting that; we just have to
1665                         // assume the frame length is always the same.
1666                         pts_int += length_per_frame;
1667                 }
1668         }
1669 }
1670
1671 void Mixer::render_one_frame(int64_t duration)
1672 {
1673         // Determine the time code for this frame before we start rendering.
1674         string timecode_text = timecode_renderer->get_timecode_text(double(pts_int) / TIMEBASE, frame_num);
1675         if (display_timecode_on_stdout) {
1676                 printf("Timecode: '%s'\n", timecode_text.c_str());
1677         }
1678
1679         // Update Y'CbCr settings for all cards.
1680         {
1681                 lock_guard<mutex> lock(card_mutex);
1682                 for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) {
1683                         YCbCrInterpretation *interpretation = &ycbcr_interpretation[card_index];
1684                         input_state.ycbcr_coefficients_auto[card_index] = interpretation->ycbcr_coefficients_auto;
1685                         input_state.ycbcr_coefficients[card_index] = interpretation->ycbcr_coefficients;
1686                         input_state.full_range[card_index] = interpretation->full_range;
1687                 }
1688         }
1689
1690         // Get the main chain from the theme, and set its state immediately.
1691         Theme::Chain theme_main_chain = theme->get_chain(0, pts(), global_flags.width, global_flags.height, input_state);
1692         EffectChain *chain = theme_main_chain.chain;
1693         theme_main_chain.setup_chain();
1694         //theme_main_chain.chain->enable_phase_timing(true);
1695
1696         // If HDMI/SDI output is active and the user has requested auto mode,
1697         // its mode overrides the existing Y'CbCr setting for the chain.
1698         YCbCrLumaCoefficients ycbcr_output_coefficients;
1699         if (global_flags.ycbcr_auto_coefficients && output_card_index != -1) {
1700                 ycbcr_output_coefficients = cards[output_card_index].output->preferred_ycbcr_coefficients();
1701         } else {
1702                 ycbcr_output_coefficients = global_flags.ycbcr_rec709_coefficients ? YCBCR_REC_709 : YCBCR_REC_601;
1703         }
1704
1705         // TODO: Reduce the duplication against theme.cpp.
1706         YCbCrFormat output_ycbcr_format;
1707         output_ycbcr_format.chroma_subsampling_x = 1;
1708         output_ycbcr_format.chroma_subsampling_y = 1;
1709         output_ycbcr_format.luma_coefficients = ycbcr_output_coefficients;
1710         output_ycbcr_format.full_range = false;
1711         output_ycbcr_format.num_levels = 1 << global_flags.bit_depth;
1712         chain->change_ycbcr_output_format(output_ycbcr_format);
1713
1714         // Render main chain. If we're using zerocopy Quick Sync encoding
1715         // (the default case), we take an extra copy of the created outputs,
1716         // so that we can display it back to the screen later (it's less memory
1717         // bandwidth than writing and reading back an RGBA texture, even at 16-bit).
1718         // Ideally, we'd like to avoid taking copies and just use the main textures
1719         // for display as well, but they're just views into VA-API memory and must be
1720         // unmapped during encoding, so we can't use them for display, unfortunately.
1721         GLuint y_tex, cbcr_full_tex, cbcr_tex;
1722         GLuint y_copy_tex, cbcr_copy_tex = 0;
1723         GLuint y_display_tex, cbcr_display_tex;
1724         GLenum y_type = (global_flags.bit_depth > 8) ? GL_R16 : GL_R8;
1725         GLenum cbcr_type = (global_flags.bit_depth > 8) ? GL_RG16 : GL_RG8;
1726         const bool is_zerocopy = video_encoder->is_zerocopy();
1727         if (is_zerocopy) {
1728                 cbcr_full_tex = resource_pool->create_2d_texture(cbcr_type, global_flags.width, global_flags.height);
1729                 y_copy_tex = resource_pool->create_2d_texture(y_type, global_flags.width, global_flags.height);
1730                 cbcr_copy_tex = resource_pool->create_2d_texture(cbcr_type, global_flags.width / 2, global_flags.height / 2);
1731
1732                 y_display_tex = y_copy_tex;
1733                 cbcr_display_tex = cbcr_copy_tex;
1734
1735                 // y_tex and cbcr_tex will be given by VideoEncoder.
1736         } else {
1737                 cbcr_full_tex = resource_pool->create_2d_texture(cbcr_type, global_flags.width, global_flags.height);
1738                 y_tex = resource_pool->create_2d_texture(y_type, global_flags.width, global_flags.height);
1739                 cbcr_tex = resource_pool->create_2d_texture(cbcr_type, global_flags.width / 2, global_flags.height / 2);
1740
1741                 y_display_tex = y_tex;
1742                 cbcr_display_tex = cbcr_tex;
1743         }
1744
1745         const int64_t av_delay = lrint(global_flags.audio_queue_length_ms * 0.001 * TIMEBASE);  // Corresponds to the delay in ResamplingQueue.
1746         bool got_frame = video_encoder->begin_frame(pts_int + av_delay, duration, ycbcr_output_coefficients, theme_main_chain.input_frames, &y_tex, &cbcr_tex);
1747         assert(got_frame);
1748
1749         GLuint fbo;
1750         if (is_zerocopy) {
1751                 fbo = resource_pool->create_fbo(y_tex, cbcr_full_tex, y_copy_tex);
1752         } else {
1753                 fbo = resource_pool->create_fbo(y_tex, cbcr_full_tex);
1754         }
1755         check_error();
1756         chain->render_to_fbo(fbo, global_flags.width, global_flags.height);
1757
1758         if (display_timecode_in_stream) {
1759                 // Render the timecode on top.
1760                 timecode_renderer->render_timecode(fbo, timecode_text);
1761         }
1762
1763         resource_pool->release_fbo(fbo);
1764
1765         if (is_zerocopy) {
1766                 chroma_subsampler->subsample_chroma(cbcr_full_tex, global_flags.width, global_flags.height, cbcr_tex, cbcr_copy_tex);
1767         } else {
1768                 chroma_subsampler->subsample_chroma(cbcr_full_tex, global_flags.width, global_flags.height, cbcr_tex);
1769         }
1770         if (output_card_index != -1) {
1771                 cards[output_card_index].output->send_frame(y_tex, cbcr_full_tex, ycbcr_output_coefficients, theme_main_chain.input_frames, pts_int, duration);
1772         }
1773         resource_pool->release_2d_texture(cbcr_full_tex);
1774
1775         // Set the right state for the Y' and CbCr textures we use for display.
1776         glBindFramebuffer(GL_FRAMEBUFFER, 0);
1777         glBindTexture(GL_TEXTURE_2D, y_display_tex);
1778         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1779         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1780         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1781
1782         glBindTexture(GL_TEXTURE_2D, cbcr_display_tex);
1783         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1784         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1785         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1786
1787         RefCountedGLsync fence = video_encoder->end_frame();
1788
1789         // The live frame pieces the Y'CbCr texture copies back into RGB and displays them.
1790         // It owns y_display_tex and cbcr_display_tex now (whichever textures they are).
1791         DisplayFrame live_frame;
1792         live_frame.chain = display_chain.get();
1793         live_frame.setup_chain = [this, y_display_tex, cbcr_display_tex]{
1794                 display_input->set_texture_num(0, y_display_tex);
1795                 display_input->set_texture_num(1, cbcr_display_tex);
1796         };
1797         live_frame.ready_fence = fence;
1798         live_frame.input_frames = {};
1799         live_frame.temp_textures = { y_display_tex, cbcr_display_tex };
1800         output_channel[OUTPUT_LIVE].output_frame(move(live_frame));
1801
1802         // Set up preview and any additional channels.
1803         for (int i = 1; i < theme->get_num_channels() + 2; ++i) {
1804                 DisplayFrame display_frame;
1805                 Theme::Chain chain = theme->get_chain(i, pts(), global_flags.width, global_flags.height, input_state);  // FIXME: dimensions
1806                 display_frame.chain = move(chain.chain);
1807                 display_frame.setup_chain = move(chain.setup_chain);
1808                 display_frame.ready_fence = fence;
1809                 display_frame.input_frames = move(chain.input_frames);
1810                 display_frame.temp_textures = {};
1811                 output_channel[i].output_frame(move(display_frame));
1812         }
1813 }
1814
1815 void Mixer::audio_thread_func()
1816 {
1817         pthread_setname_np(pthread_self(), "Mixer_Audio");
1818
1819         while (!should_quit) {
1820                 AudioTask task;
1821
1822                 {
1823                         unique_lock<mutex> lock(audio_mutex);
1824                         audio_task_queue_changed.wait(lock, [this]{ return should_quit || !audio_task_queue.empty(); });
1825                         if (should_quit) {
1826                                 return;
1827                         }
1828                         task = audio_task_queue.front();
1829                         audio_task_queue.pop();
1830                 }
1831
1832                 ResamplingQueue::RateAdjustmentPolicy rate_adjustment_policy =
1833                         task.adjust_rate ? ResamplingQueue::ADJUST_RATE : ResamplingQueue::DO_NOT_ADJUST_RATE;
1834                 vector<float> samples_out = audio_mixer->get_output(
1835                         task.frame_timestamp,
1836                         task.num_samples,
1837                         rate_adjustment_policy);
1838
1839                 // Send the samples to the sound card, then add them to the output.
1840                 if (alsa) {
1841                         alsa->write(samples_out);
1842                 }
1843                 if (output_card_index != -1) {
1844                         const int64_t av_delay = lrint(global_flags.audio_queue_length_ms * 0.001 * TIMEBASE);  // Corresponds to the delay in ResamplingQueue.
1845                         cards[output_card_index].output->send_audio(task.pts_int + av_delay, samples_out);
1846                 }
1847                 video_encoder->add_audio(task.pts_int, move(samples_out));
1848         }
1849 }
1850
1851 void Mixer::release_display_frame(DisplayFrame *frame)
1852 {
1853         for (GLuint texnum : frame->temp_textures) {
1854                 resource_pool->release_2d_texture(texnum);
1855         }
1856         frame->temp_textures.clear();
1857         frame->ready_fence.reset();
1858         frame->input_frames.clear();
1859 }
1860
1861 void Mixer::start()
1862 {
1863         mixer_thread = thread(&Mixer::thread_func, this);
1864         audio_thread = thread(&Mixer::audio_thread_func, this);
1865 }
1866
1867 void Mixer::quit()
1868 {
1869         should_quit = true;
1870         audio_task_queue_changed.notify_one();
1871         mixer_thread.join();
1872         audio_thread.join();
1873 #ifdef HAVE_SRT
1874         if (global_flags.srt_port >= 0) {
1875                 // There's seemingly no other reasonable way to wake up the thread
1876                 // (libsrt's epoll equivalent is busy-waiting).
1877                 int sock = srt_create_socket();
1878                 if (sock != -1) {
1879                         sockaddr_in6 addr;
1880                         memset(&addr, 0, sizeof(addr));
1881                         addr.sin6_family = AF_INET6;
1882                         addr.sin6_addr = IN6ADDR_LOOPBACK_INIT;
1883                         addr.sin6_port = htons(global_flags.srt_port);
1884                         srt_connect(sock, (sockaddr *)&addr, sizeof(addr));
1885                         srt_close(sock);
1886                 }
1887                 srt_thread.join();
1888         }
1889 #endif
1890 }
1891
1892 void Mixer::transition_clicked(int transition_num)
1893 {
1894         theme->transition_clicked(transition_num, pts());
1895 }
1896
1897 void Mixer::channel_clicked(int preview_num)
1898 {
1899         theme->channel_clicked(preview_num);
1900 }
1901
1902 YCbCrInterpretation Mixer::get_input_ycbcr_interpretation(unsigned card_index) const
1903 {
1904         lock_guard<mutex> lock(card_mutex);
1905         return ycbcr_interpretation[card_index];
1906 }
1907
1908 void Mixer::set_input_ycbcr_interpretation(unsigned card_index, const YCbCrInterpretation &interpretation)
1909 {
1910         lock_guard<mutex> lock(card_mutex);
1911         ycbcr_interpretation[card_index] = interpretation;
1912 }
1913
1914 void Mixer::start_mode_scanning(unsigned card_index)
1915 {
1916         assert(card_index < MAX_VIDEO_CARDS);
1917         if (cards[card_index].capture == nullptr) {
1918                 // Inactive card. Should never happen.
1919                 return;
1920         }
1921         if (is_mode_scanning[card_index]) {
1922                 return;
1923         }
1924         is_mode_scanning[card_index] = true;
1925         mode_scanlist[card_index].clear();
1926         for (const auto &mode : cards[card_index].capture->get_available_video_modes()) {
1927                 mode_scanlist[card_index].push_back(mode.first);
1928         }
1929         assert(!mode_scanlist[card_index].empty());
1930         mode_scanlist_index[card_index] = 0;
1931         cards[card_index].capture->set_video_mode(mode_scanlist[card_index][0]);
1932         last_mode_scan_change[card_index] = steady_clock::now();
1933 }
1934
1935 map<uint32_t, VideoMode> Mixer::get_available_output_video_modes() const
1936 {
1937         assert(desired_output_card_index != -1);
1938         lock_guard<mutex> lock(card_mutex);
1939         return cards[desired_output_card_index].output->get_available_video_modes();
1940 }
1941
1942 string Mixer::get_ffmpeg_filename(unsigned card_index) const
1943 {
1944         assert(card_index < MAX_VIDEO_CARDS);
1945         assert(cards[card_index].type == CardType::FFMPEG_INPUT);
1946         return ((FFmpegCapture *)(cards[card_index].capture.get()))->get_filename();
1947 }
1948
1949 void Mixer::set_ffmpeg_filename(unsigned card_index, const string &filename) {
1950         assert(card_index < MAX_VIDEO_CARDS);
1951         assert(cards[card_index].type == CardType::FFMPEG_INPUT);
1952         ((FFmpegCapture *)(cards[card_index].capture.get()))->change_filename(filename);
1953 }
1954
1955 void Mixer::wait_for_next_frame()
1956 {
1957         unique_lock<mutex> lock(frame_num_mutex);
1958         unsigned old_frame_num = frame_num;
1959         frame_num_updated.wait_for(lock, seconds(1),  // Timeout is just in case.
1960                 [old_frame_num, this]{ return this->frame_num > old_frame_num; });
1961 }
1962
1963 Mixer::OutputChannel::~OutputChannel()
1964 {
1965         if (has_current_frame) {
1966                 parent->release_display_frame(&current_frame);
1967         }
1968         if (has_ready_frame) {
1969                 parent->release_display_frame(&ready_frame);
1970         }
1971 }
1972
1973 void Mixer::OutputChannel::output_frame(DisplayFrame &&frame)
1974 {
1975         // Store this frame for display. Remove the ready frame if any
1976         // (it was seemingly never used).
1977         {
1978                 lock_guard<mutex> lock(frame_mutex);
1979                 if (has_ready_frame) {
1980                         parent->release_display_frame(&ready_frame);
1981                 }
1982                 ready_frame = move(frame);
1983                 has_ready_frame = true;
1984
1985                 // Call the callbacks under the mutex (they should be short),
1986                 // so that we don't race against a callback removal.
1987                 for (const auto &key_and_callback : new_frame_ready_callbacks) {
1988                         key_and_callback.second();
1989                 }
1990         }
1991
1992         // Reduce the number of callbacks by filtering duplicates. The reason
1993         // why we bother doing this is that Qt seemingly can get into a state
1994         // where its builds up an essentially unbounded queue of signals,
1995         // consuming more and more memory, and there's no good way of collapsing
1996         // user-defined signals or limiting the length of the queue.
1997         if (transition_names_updated_callback) {
1998                 vector<string> transition_names = global_mixer->get_transition_names();
1999                 bool changed = false;
2000                 if (transition_names.size() != last_transition_names.size()) {
2001                         changed = true;
2002                 } else {
2003                         for (unsigned i = 0; i < transition_names.size(); ++i) {
2004                                 if (transition_names[i] != last_transition_names[i]) {
2005                                         changed = true;
2006                                         break;
2007                                 }
2008                         }
2009                 }
2010                 if (changed) {
2011                         transition_names_updated_callback(transition_names);
2012                         last_transition_names = transition_names;
2013                 }
2014         }
2015         if (name_updated_callback) {
2016                 string name = global_mixer->get_channel_name(channel);
2017                 if (name != last_name) {
2018                         name_updated_callback(name);
2019                         last_name = name;
2020                 }
2021         }
2022         if (color_updated_callback) {
2023                 string color = global_mixer->get_channel_color(channel);
2024                 if (color != last_color) {
2025                         color_updated_callback(color);
2026                         last_color = color;
2027                 }
2028         }
2029 }
2030
2031 bool Mixer::OutputChannel::get_display_frame(DisplayFrame *frame)
2032 {
2033         lock_guard<mutex> lock(frame_mutex);
2034         if (!has_current_frame && !has_ready_frame) {
2035                 return false;
2036         }
2037
2038         if (has_current_frame && has_ready_frame) {
2039                 // We have a new ready frame. Toss the current one.
2040                 parent->release_display_frame(&current_frame);
2041                 has_current_frame = false;
2042         }
2043         if (has_ready_frame) {
2044                 assert(!has_current_frame);
2045                 current_frame = move(ready_frame);
2046                 ready_frame.ready_fence.reset();  // Drop the refcount.
2047                 ready_frame.input_frames.clear();  // Drop the refcounts.
2048                 has_current_frame = true;
2049                 has_ready_frame = false;
2050         }
2051
2052         *frame = current_frame;
2053         return true;
2054 }
2055
2056 void Mixer::OutputChannel::add_frame_ready_callback(void *key, Mixer::new_frame_ready_callback_t callback)
2057 {
2058         lock_guard<mutex> lock(frame_mutex);
2059         new_frame_ready_callbacks[key] = callback;
2060 }
2061
2062 void Mixer::OutputChannel::remove_frame_ready_callback(void *key)
2063 {
2064         lock_guard<mutex> lock(frame_mutex);
2065         new_frame_ready_callbacks.erase(key);
2066 }
2067
2068 void Mixer::OutputChannel::set_transition_names_updated_callback(Mixer::transition_names_updated_callback_t callback)
2069 {
2070         transition_names_updated_callback = callback;
2071 }
2072
2073 void Mixer::OutputChannel::set_name_updated_callback(Mixer::name_updated_callback_t callback)
2074 {
2075         name_updated_callback = callback;
2076 }
2077
2078 void Mixer::OutputChannel::set_color_updated_callback(Mixer::color_updated_callback_t callback)
2079 {
2080         color_updated_callback = callback;
2081 }
2082
2083 #ifdef HAVE_SRT
2084 void Mixer::start_srt()
2085 {
2086         SRTSOCKET sock = srt_create_socket();
2087         sockaddr_in6 addr;
2088         memset(&addr, 0, sizeof(addr));
2089         addr.sin6_family = AF_INET6;
2090         addr.sin6_port = htons(global_flags.srt_port);
2091
2092         int zero = 0;
2093         int err = srt_setsockopt(sock, /*level=*/0, SRTO_IPV6ONLY, &zero, sizeof(zero));
2094         if (err != 0) {
2095                 fprintf(stderr, "srt_setsockopt(SRTO_IPV6ONLY): %s\n", srt_getlasterror_str());
2096                 abort();
2097         }
2098         err = srt_bind(sock, (sockaddr *)&addr, sizeof(addr));
2099         if (err != 0) {
2100                 fprintf(stderr, "srt_bind: %s\n", srt_getlasterror_str());
2101                 abort();
2102         }
2103         err = srt_listen(sock, MAX_VIDEO_CARDS);
2104         if (err != 0) {
2105                 fprintf(stderr, "srt_listen: %s\n", srt_getlasterror_str());
2106                 abort();
2107         }
2108
2109         srt_thread = thread([this, sock] {
2110                 sockaddr_in6 addr;
2111                 for ( ;; ) {
2112                         int sa_len = sizeof(addr);
2113                         int clientsock = srt_accept(sock, (sockaddr *)&addr, &sa_len);
2114                         if (should_quit) {
2115                                 if (clientsock != -1) {
2116                                         srt_close(clientsock);
2117                                 }
2118                                 break;
2119                         }
2120                         if (!global_flags.enable_srt) {  // Runtime UI toggle.
2121                                 // Perhaps not as good as never listening in the first place,
2122                                 // but much simpler to turn on and off.
2123                                 srt_close(clientsock);
2124                                 continue;
2125                         }
2126                         lock_guard<mutex> lock(hotplug_mutex);
2127                         hotplugged_srt_cards.push_back(clientsock);
2128                 }
2129                 srt_close(sock);
2130         });
2131 }
2132 #endif
2133
2134 string Mixer::description_for_card(unsigned card_index)
2135 {
2136         CaptureCard *card = &cards[card_index];
2137         if (card->capture == nullptr) {
2138                 // Should never be called for inactive cards, but OK.
2139                 char buf[256];
2140                 snprintf(buf, sizeof(buf), "Inactive capture card %u", card_index);
2141                 return buf;
2142         }
2143         if (card->type != CardType::FFMPEG_INPUT) {
2144                 char buf[256];
2145                 snprintf(buf, sizeof(buf), "Capture card %u (%s)", card_index, card->capture->get_description().c_str());
2146                 return buf;
2147         }
2148
2149         // Number (non-SRT) FFmpeg inputs from zero, separately from the capture cards,
2150         // since it's not too obvious for the user that they are “cards”.
2151         unsigned ffmpeg_index = 0;
2152         for (unsigned i = 0; i < card_index; ++i) {
2153                 CaptureCard *other_card = &cards[i];
2154                 if (other_card->type == CardType::FFMPEG_INPUT && !is_srt_card(other_card)) {
2155                         ++ffmpeg_index;
2156                 }
2157         }
2158         char buf[256];
2159         snprintf(buf, sizeof(buf), "Video input %u (%s)", ffmpeg_index, card->capture->get_description().c_str());
2160         return buf;
2161 }
2162
2163 bool Mixer::is_srt_card(const Mixer::CaptureCard *card)
2164 {
2165 #ifdef HAVE_SRT
2166         if (card->type == CardType::FFMPEG_INPUT) {
2167                 int srt_sock = static_cast<FFmpegCapture *>(card->capture.get())->get_srt_sock();
2168                 return srt_sock != -1;
2169         }
2170 #endif
2171         return false;
2172 }
2173
2174 mutex RefCountedGLsync::fence_lock;