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