7 #include <condition_variable>
14 #include <movit/effect.h>
15 #include <movit/effect_chain.h>
16 #include <movit/effect_util.h>
17 #include <movit/flat_input.h>
18 #include <movit/image_format.h>
19 #include <movit/init.h>
20 #include <movit/resource_pool.h>
21 #include <movit/util.h>
22 #include <movit/ycbcr.h>
23 #include <movit/ycbcr_input.h>
25 #include <netinet/in.h>
34 #include <sys/socket.h>
35 #include <sys/syslog.h>
40 #include "DeckLinkAPI.h"
42 #include "alsa_output.h"
43 #include "audio_mixer.h"
44 #include "basic_stats.h"
45 #include "bmusb/bmusb.h"
46 #include "bmusb/fake_capture.h"
50 #include "cef_capture.h"
52 #include "card_type.h"
53 #include "chroma_subsampler.h"
54 #include "decklink_capture.h"
55 #include "decklink_output.h"
56 #include "decklink_util.h"
58 #include "ffmpeg_capture.h"
60 #include "image_input.h"
61 #include "input_mapping.h"
62 #include "input_state.h"
64 #include "mjpeg_encoder.h"
65 #include "pbo_frame_allocator.h"
66 #include "queue_length_policy.h"
67 #include "resampling_queue.h"
68 #include "shared/context.h"
69 #include "shared/disk_space_estimator.h"
70 #include "shared/metrics.h"
71 #include "shared/ref_counted_gl_sync.h"
72 #include "shared/shared_defs.h"
73 #include "shared/timebase.h"
75 #include "timecode_renderer.h"
76 #include "v210_converter.h"
77 #include "video_encoder.h"
78 #include "ycbcr_interpretation.h"
81 #include <google/protobuf/util/json_util.h>
85 // Must come after CEF, since it includes <syslog.h>, which has #defines
86 // that conflict with CEF logging constants.
93 using namespace movit;
95 using namespace std::chrono;
96 using namespace std::placeholders;
97 using namespace bmusb;
99 Mixer *global_mixer = nullptr;
103 void insert_new_frame(RefCountedFrame frame, unsigned field_num, bool interlaced, unsigned card_index, InputState *input_state)
106 for (unsigned frame_num = FRAME_HISTORY_LENGTH; frame_num --> 1; ) { // :-)
107 input_state->buffered_frames[card_index][frame_num] =
108 input_state->buffered_frames[card_index][frame_num - 1];
110 input_state->buffered_frames[card_index][0] = { frame, field_num };
112 for (unsigned frame_num = 0; frame_num < FRAME_HISTORY_LENGTH; ++frame_num) {
113 input_state->buffered_frames[card_index][frame_num] = { frame, field_num };
118 void ensure_texture_resolution(PBOFrameAllocator::Userdata *userdata, unsigned field, unsigned width, unsigned height, unsigned cbcr_width, unsigned cbcr_height, unsigned v210_width)
121 switch (userdata->pixel_format) {
122 case PixelFormat_10BitYCbCr:
123 first = userdata->tex_v210[field] == 0 || userdata->tex_444[field] == 0;
125 case PixelFormat_8BitYCbCr:
126 first = userdata->tex_y[field] == 0 || userdata->tex_cbcr[field] == 0;
128 case PixelFormat_8BitBGRA:
129 first = userdata->tex_rgba[field] == 0;
131 case PixelFormat_8BitYCbCrPlanar:
132 first = userdata->tex_y[field] == 0 || userdata->tex_cb[field] == 0 || userdata->tex_cr[field] == 0;
138 const bool recreate_main_texture =
140 width != userdata->last_width[field] ||
141 height != userdata->last_height[field] ||
142 cbcr_width != userdata->last_cbcr_width[field] ||
143 cbcr_height != userdata->last_cbcr_height[field];
144 const bool recreate_v210_texture =
145 global_flags.bit_depth > 8 &&
146 (first || v210_width != userdata->last_v210_width[field] || height != userdata->last_height[field]);
148 if (recreate_main_texture) {
149 // We changed resolution since last use of this texture, so we need to create
150 // a new object. Note that this each card has its own PBOFrameAllocator,
151 // we don't need to worry about these flip-flopping between resolutions.
152 switch (userdata->pixel_format) {
153 case PixelFormat_10BitYCbCr:
154 glBindTexture(GL_TEXTURE_2D, userdata->tex_444[field]);
156 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB10_A2, width, height, 0, GL_RGBA, GL_UNSIGNED_INT_2_10_10_10_REV, nullptr);
159 case PixelFormat_8BitYCbCr: {
160 glBindTexture(GL_TEXTURE_2D, userdata->tex_cbcr[field]);
162 glTexImage2D(GL_TEXTURE_2D, 0, GL_RG8, cbcr_width, height, 0, GL_RG, GL_UNSIGNED_BYTE, nullptr);
164 glBindTexture(GL_TEXTURE_2D, userdata->tex_y[field]);
166 glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, width, height, 0, GL_RED, GL_UNSIGNED_BYTE, nullptr);
170 case PixelFormat_8BitYCbCrPlanar: {
171 glBindTexture(GL_TEXTURE_2D, userdata->tex_y[field]);
173 glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, width, height, 0, GL_RED, GL_UNSIGNED_BYTE, nullptr);
175 glBindTexture(GL_TEXTURE_2D, userdata->tex_cb[field]);
177 glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, cbcr_width, cbcr_height, 0, GL_RED, GL_UNSIGNED_BYTE, nullptr);
179 glBindTexture(GL_TEXTURE_2D, userdata->tex_cr[field]);
181 glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, cbcr_width, cbcr_height, 0, GL_RED, GL_UNSIGNED_BYTE, nullptr);
185 case PixelFormat_8BitBGRA:
186 glBindTexture(GL_TEXTURE_2D, userdata->tex_rgba[field]);
188 // NOTE: sRGB may be disabled by sRGBSwitchingFlatInput.
189 glTexImage2D(GL_TEXTURE_2D, 0, GL_SRGB8_ALPHA8, width, height, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, nullptr);
195 userdata->last_width[field] = width;
196 userdata->last_height[field] = height;
197 userdata->last_cbcr_width[field] = cbcr_width;
198 userdata->last_cbcr_height[field] = cbcr_height;
200 if (recreate_v210_texture) {
201 // Same as above; we need to recreate the texture.
202 glBindTexture(GL_TEXTURE_2D, userdata->tex_v210[field]);
204 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB10_A2, v210_width, height, 0, GL_RGBA, GL_UNSIGNED_INT_2_10_10_10_REV, nullptr);
206 userdata->last_v210_width[field] = v210_width;
207 userdata->last_height[field] = height;
211 void upload_texture(GLuint tex, GLuint width, GLuint height, GLuint stride, bool interlaced_stride, GLenum format, GLenum type, GLintptr offset)
213 if (interlaced_stride) {
216 if (global_flags.flush_pbos) {
217 glFlushMappedBufferRange(GL_PIXEL_UNPACK_BUFFER, offset, stride * height);
221 glBindTexture(GL_TEXTURE_2D, tex);
223 if (interlaced_stride) {
224 glPixelStorei(GL_UNPACK_ROW_LENGTH, width * 2);
227 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
231 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, format, type, BUFFER_OFFSET(offset));
233 glBindTexture(GL_TEXTURE_2D, 0);
235 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
241 void JitterHistory::register_metrics(const vector<pair<string, string>> &labels)
243 global_metrics.add("input_underestimated_jitter_frames", labels, &metric_input_underestimated_jitter_frames);
244 global_metrics.add("input_estimated_max_jitter_seconds", labels, &metric_input_estimated_max_jitter_seconds, Metrics::TYPE_GAUGE);
247 void JitterHistory::unregister_metrics(const vector<pair<string, string>> &labels)
249 global_metrics.remove("input_underestimated_jitter_frames", labels);
250 global_metrics.remove("input_estimated_max_jitter_seconds", labels);
253 void JitterHistory::frame_arrived(steady_clock::time_point now, int64_t frame_duration, size_t dropped_frames)
255 if (frame_duration != last_duration) {
256 // If the frame rate changed, the input clock is also going to change,
257 // so our historical data doesn't make much sense anymore.
258 // Also, format changes typically introduce blips that are not representative
259 // of the typical frame stream. (We make the assumption that format changes
260 // don't happen all the time in regular use; if they did, we should probably
261 // rather keep the history so that we take jitter they may introduce into account.)
263 last_duration = frame_duration;
265 if (expected_timestamp > steady_clock::time_point::min()) {
266 expected_timestamp += dropped_frames * nanoseconds(frame_duration * 1000000000 / TIMEBASE);
267 double jitter_seconds = fabs(duration<double>(expected_timestamp - now).count());
268 history.push_back(orders.insert(jitter_seconds));
269 if (jitter_seconds > estimate_max_jitter()) {
270 ++metric_input_underestimated_jitter_frames;
273 metric_input_estimated_max_jitter_seconds = estimate_max_jitter();
275 if (history.size() > history_length) {
276 orders.erase(history.front());
279 assert(history.size() <= history_length);
281 expected_timestamp = now + nanoseconds(frame_duration * 1000000000 / TIMEBASE);
284 double JitterHistory::estimate_max_jitter() const
286 if (orders.empty()) {
289 size_t elem_idx = lrint((orders.size() - 1) * percentile);
290 if (percentile <= 0.5) {
291 return *next(orders.begin(), elem_idx) * multiplier;
293 return *prev(orders.end(), orders.size() - elem_idx) * multiplier;
297 void QueueLengthPolicy::register_metrics(const vector<pair<string, string>> &labels)
299 global_metrics.add("input_queue_safe_length_frames", labels, &metric_input_queue_safe_length_frames, Metrics::TYPE_GAUGE);
302 void QueueLengthPolicy::unregister_metrics(const vector<pair<string, string>> &labels)
304 global_metrics.remove("input_queue_safe_length_frames", labels);
307 void QueueLengthPolicy::update_policy(steady_clock::time_point now,
308 steady_clock::time_point expected_next_input_frame,
309 int64_t input_frame_duration,
310 int64_t master_frame_duration,
311 double max_input_card_jitter_seconds,
312 double max_master_card_jitter_seconds)
314 double input_frame_duration_seconds = input_frame_duration / double(TIMEBASE);
315 double master_frame_duration_seconds = master_frame_duration / double(TIMEBASE);
317 // Figure out when we can expect the next frame for this card, assuming
318 // worst-case jitter (ie., the frame is maximally late).
319 double seconds_until_next_frame = max(duration<double>(expected_next_input_frame - now).count() + max_input_card_jitter_seconds, 0.0);
321 // How many times are the master card expected to tick in that time?
322 // We assume the master clock has worst-case jitter but not any rate
323 // discrepancy, ie., it ticks as early as possible every time, but not
325 double frames_needed = (seconds_until_next_frame + max_master_card_jitter_seconds) / master_frame_duration_seconds;
327 // As a special case, if the master card ticks faster than the input card,
328 // we expect the queue to drain by itself even without dropping. But if
329 // the difference is small (e.g. 60 Hz master and 59.94 input), it would
330 // go slowly enough that the effect wouldn't really be appreciable.
331 // We account for this by looking at the situation five frames ahead,
332 // assuming everything else is the same.
333 double frames_allowed;
334 if (master_frame_duration < input_frame_duration) {
335 frames_allowed = frames_needed + 5 * (input_frame_duration_seconds - master_frame_duration_seconds) / master_frame_duration_seconds;
337 frames_allowed = frames_needed;
340 safe_queue_length = max<int>(floor(frames_allowed), 0);
341 metric_input_queue_safe_length_frames = safe_queue_length;
344 Mixer::Mixer(const QSurfaceFormat &format)
346 mixer_surface(create_surface(format)),
347 h264_encoder_surface(create_surface(format)),
348 decklink_output_surface(create_surface(format)),
349 image_update_surface(create_surface(format))
351 memcpy(ycbcr_interpretation, global_flags.ycbcr_interpretation, sizeof(ycbcr_interpretation));
352 CHECK(init_movit(MOVIT_SHADER_DIR, MOVIT_DEBUG_OFF));
355 if (!epoxy_has_gl_extension("GL_EXT_texture_sRGB_decode") ||
356 !epoxy_has_gl_extension("GL_ARB_sampler_objects")) {
357 fprintf(stderr, "Nageru requires GL_EXT_texture_sRGB_decode and GL_ARB_sampler_objects to run.\n");
361 // Since we allow non-bouncing 4:2:2 YCbCrInputs, effective subpixel precision
362 // will be halved when sampling them, and we need to compensate here.
363 movit_texel_subpixel_precision /= 2.0;
365 resource_pool.reset(new ResourcePool);
366 for (unsigned i = 0; i < NUM_OUTPUTS; ++i) {
367 output_channel[i].parent = this;
368 output_channel[i].channel = i;
371 ImageFormat inout_format;
372 inout_format.color_space = COLORSPACE_sRGB;
373 inout_format.gamma_curve = GAMMA_sRGB;
375 // Matches the 4:2:0 format created by the main chain.
376 YCbCrFormat ycbcr_format;
377 ycbcr_format.chroma_subsampling_x = 2;
378 ycbcr_format.chroma_subsampling_y = 2;
379 if (global_flags.ycbcr_rec709_coefficients) {
380 ycbcr_format.luma_coefficients = YCBCR_REC_709;
382 ycbcr_format.luma_coefficients = YCBCR_REC_601;
384 ycbcr_format.full_range = false;
385 ycbcr_format.num_levels = 1 << global_flags.bit_depth;
386 ycbcr_format.cb_x_position = 0.0f;
387 ycbcr_format.cr_x_position = 0.0f;
388 ycbcr_format.cb_y_position = 0.5f;
389 ycbcr_format.cr_y_position = 0.5f;
391 // Initialize the neutral colors to sane values.
392 for (unsigned i = 0; i < MAX_VIDEO_CARDS; ++i) {
393 last_received_neutral_color[i] = RGBTriplet(1.0f, 1.0f, 1.0f);
396 // Display chain; shows the live output produced by the main chain (or rather, a copy of it).
397 display_chain.reset(new EffectChain(global_flags.width, global_flags.height, resource_pool.get()));
399 GLenum type = global_flags.bit_depth > 8 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_BYTE;
400 display_input = new YCbCrInput(inout_format, ycbcr_format, global_flags.width, global_flags.height, YCBCR_INPUT_SPLIT_Y_AND_CBCR, type);
401 display_chain->add_input(display_input);
402 display_chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
403 display_chain->set_dither_bits(0); // Don't bother.
404 display_chain->finalize();
406 video_encoder.reset(new VideoEncoder(resource_pool.get(), h264_encoder_surface, global_flags.va_display, global_flags.width, global_flags.height, &httpd, global_disk_space_estimator));
407 if (!global_flags.card_to_mjpeg_stream_export.empty()) {
408 mjpeg_encoder.reset(new MJPEGEncoder(&httpd, global_flags.va_display));
411 // Must be instantiated after VideoEncoder has initialized global_flags.use_zerocopy.
412 theme.reset(new Theme(global_flags.theme_filename, global_flags.theme_dirs, resource_pool.get()));
414 // Must be instantiated after the theme, as the theme decides the number of FFmpeg inputs.
415 std::vector<FFmpegCapture *> video_inputs = theme->get_video_inputs();
416 audio_mixer.reset(new AudioMixer);
418 httpd.add_endpoint("/channels", bind(&Mixer::get_channels_json, this), HTTPD::ALLOW_ALL_ORIGINS);
419 for (int channel_idx = 0; channel_idx < theme->get_num_channels(); ++channel_idx) {
421 snprintf(url, sizeof(url), "/channels/%d/color", channel_idx + 2);
422 httpd.add_endpoint(url, bind(&Mixer::get_channel_color_http, this, unsigned(channel_idx + 2)), HTTPD::ALLOW_ALL_ORIGINS);
425 // Start listening for clients only once VideoEncoder has written its header, if any.
426 httpd.start(global_flags.http_port);
428 // First try initializing the then PCI devices, then USB, then
429 // fill up with fake cards until we have the desired number of cards.
430 unsigned num_pci_devices = 0;
431 unsigned card_index = 0;
434 IDeckLinkIterator *decklink_iterator = CreateDeckLinkIteratorInstance();
435 if (decklink_iterator != nullptr) {
436 for ( ; card_index < unsigned(global_flags.max_num_cards); ++card_index) {
438 if (decklink_iterator->Next(&decklink) != S_OK) {
442 if (!decklink_card_is_active(decklink, card_index)) {
443 fprintf(stderr, "DeckLink card %u is inactive in current profile, skipping (try changing it in Desktop Video Setup)\n", card_index);
448 DeckLinkCapture *capture = new DeckLinkCapture(decklink, card_index);
449 DeckLinkOutput *output = new DeckLinkOutput(resource_pool.get(), decklink_output_surface, global_flags.width, global_flags.height, card_index);
450 if (!output->set_device(decklink, capture->get_input())) {
454 configure_card(card_index, capture, CardType::LIVE_CARD, output, /*is_srt_card=*/false);
457 decklink_iterator->Release();
458 fprintf(stderr, "Found %u DeckLink PCI card(s).\n", num_pci_devices);
460 fprintf(stderr, "DeckLink drivers not found. Probing for USB cards only.\n");
464 unsigned num_usb_devices = BMUSBCapture::num_cards();
465 for (unsigned usb_card_index = 0; usb_card_index < num_usb_devices && card_index < unsigned(global_flags.max_num_cards); ++usb_card_index, ++card_index) {
466 BMUSBCapture *capture = new BMUSBCapture(usb_card_index);
467 capture->set_card_disconnected_callback(bind(&Mixer::bm_hotplug_remove, this, card_index));
468 configure_card(card_index, capture, CardType::LIVE_CARD, /*output=*/nullptr, /*is_srt_card=*/false);
470 fprintf(stderr, "Found %u USB card(s).\n", num_usb_devices);
472 // Fill up with fake cards for as long as we can, so that the FFmpeg
473 // and HTML cards always come last.
474 unsigned num_fake_cards = 0;
476 size_t num_html_inputs = theme->get_html_inputs().size();
478 size_t num_html_inputs = 0;
480 for ( ; card_index < MAX_VIDEO_CARDS - video_inputs.size() - num_html_inputs; ++card_index) {
481 // Only bother to activate fake capture cards to satisfy the minimum.
482 bool is_active = card_index < unsigned(global_flags.min_num_cards) || cards[card_index].force_active;
484 FakeCapture *capture = new FakeCapture(global_flags.width, global_flags.height, FAKE_FPS, OUTPUT_FREQUENCY, card_index, global_flags.fake_cards_audio);
485 configure_card(card_index, capture, CardType::FAKE_CAPTURE, /*output=*/nullptr, /*is_srt_card=*/false);
488 configure_card(card_index, nullptr, CardType::FAKE_CAPTURE, /*output=*/nullptr, /*is_srt_card=*/false);
492 if (num_fake_cards > 0) {
493 fprintf(stderr, "Initialized %u fake cards.\n", num_fake_cards);
496 // Initialize all video inputs the theme asked for.
497 for (unsigned video_card_index = 0; video_card_index < video_inputs.size(); ++card_index, ++video_card_index) {
498 if (card_index >= MAX_VIDEO_CARDS) {
499 fprintf(stderr, "ERROR: Not enough card slots available for the videos the theme requested.\n");
502 configure_card(card_index, video_inputs[video_card_index], CardType::FFMPEG_INPUT, /*output=*/nullptr, /*is_srt_card=*/false);
503 video_inputs[video_card_index]->set_card_index(card_index);
505 num_video_inputs = video_inputs.size();
508 // Same, for HTML inputs.
509 std::vector<CEFCapture *> html_inputs = theme->get_html_inputs();
510 for (unsigned html_card_index = 0; html_card_index < html_inputs.size(); ++card_index, ++html_card_index) {
511 if (card_index >= MAX_VIDEO_CARDS) {
512 fprintf(stderr, "ERROR: Not enough card slots available for the HTML inputs the theme requested.\n");
515 configure_card(card_index, html_inputs[html_card_index], CardType::CEF_INPUT, /*output=*/nullptr, /*is_srt_card=*/false);
516 html_inputs[html_card_index]->set_card_index(card_index);
518 num_html_inputs = html_inputs.size();
521 BMUSBCapture::set_card_connected_callback(bind(&Mixer::bm_hotplug_add, this, _1));
522 BMUSBCapture::start_bm_thread();
525 if (global_flags.srt_port >= 0) {
530 chroma_subsampler.reset(new ChromaSubsampler(resource_pool.get()));
532 if (global_flags.bit_depth > 8) {
533 if (!v210Converter::has_hardware_support()) {
534 fprintf(stderr, "ERROR: --ten-bit-input requires support for OpenGL compute shaders\n");
535 fprintf(stderr, " (OpenGL 4.3, or GL_ARB_compute_shader + GL_ARB_shader_image_load_store).\n");
538 v210_converter.reset(new v210Converter());
540 // These are all the widths listed in the Blackmagic SDK documentation
541 // (section 2.7.3, “Display Modes”).
542 v210_converter->precompile_shader(720);
543 v210_converter->precompile_shader(1280);
544 v210_converter->precompile_shader(1920);
545 v210_converter->precompile_shader(2048);
546 v210_converter->precompile_shader(3840);
547 v210_converter->precompile_shader(4096);
549 if (global_flags.bit_depth > 8) {
550 if (!v210Converter::has_hardware_support()) {
551 fprintf(stderr, "ERROR: --ten-bit-output requires support for OpenGL compute shaders\n");
552 fprintf(stderr, " (OpenGL 4.3, or GL_ARB_compute_shader + GL_ARB_shader_image_load_store).\n");
557 timecode_renderer.reset(new TimecodeRenderer(resource_pool.get(), global_flags.width, global_flags.height));
558 display_timecode_in_stream = global_flags.display_timecode_in_stream;
559 display_timecode_on_stdout = global_flags.display_timecode_on_stdout;
561 if (global_flags.enable_alsa_output) {
562 alsa.reset(new ALSAOutput(OUTPUT_FREQUENCY, /*num_channels=*/2));
564 output_card_is_master = global_flags.output_card_is_master;
565 if (global_flags.output_card != -1) {
566 desired_output_card_index = global_flags.output_card;
567 set_output_card_internal(global_flags.output_card);
570 output_jitter_history.register_metrics({{ "card", "output" }});
572 ImageInput::start_update_thread(image_update_surface);
577 ImageInput::end_update_thread();
579 if (mjpeg_encoder != nullptr) {
580 mjpeg_encoder->stop();
583 BMUSBCapture::stop_bm_thread();
585 for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) {
586 if (cards[card_index].capture != nullptr) { // Active.
587 cards[card_index].capture->stop_dequeue_thread();
589 if (cards[card_index].output) {
590 cards[card_index].output->end_output();
591 cards[card_index].output.reset();
595 video_encoder.reset(nullptr);
598 void Mixer::configure_card(unsigned card_index, CaptureInterface *capture, CardType card_type, DeckLinkOutput *output, bool is_srt_card)
600 bool is_active = capture != nullptr;
602 assert(card_type == CardType::FAKE_CAPTURE);
605 CaptureCard *card = &cards[card_index];
606 if (card->capture != nullptr) {
607 card_mutex.unlock(); // The dequeue thread could be waiting for bm_frame().
608 card->capture->stop_dequeue_thread();
611 card->capture.reset(capture);
612 card->is_fake_capture = (card_type == CardType::FAKE_CAPTURE);
613 if (card->is_fake_capture) {
614 card->fake_capture_counter = fake_capture_counter++;
616 card->is_cef_capture = (card_type == CardType::CEF_INPUT);
617 card->may_have_dropped_last_frame = false;
618 card->type = card_type;
619 if (card->output.get() != output) {
620 card->output.reset(output);
623 PixelFormat pixel_format;
624 if (card_type == CardType::FFMPEG_INPUT) {
625 pixel_format = capture->get_current_pixel_format();
626 } else if (card_type == CardType::CEF_INPUT) {
627 pixel_format = PixelFormat_8BitBGRA;
628 } else if (global_flags.bit_depth > 8) {
629 pixel_format = PixelFormat_10BitYCbCr;
631 pixel_format = PixelFormat_8BitYCbCr;
635 card->capture->set_frame_callback(bind(&Mixer::bm_frame, this, card_index, _1, _2, _3, _4, _5, _6, _7));
636 if (card->frame_allocator == nullptr) {
637 card->frame_allocator.reset(new PBOFrameAllocator(pixel_format, FRAME_SIZE, global_flags.width, global_flags.height, card_index, mjpeg_encoder.get()));
639 // The format could have changed, but we cannot reset the allocator
640 // and create a new one from scratch, since there may be allocated
641 // frames from it that expect to call release_frame() on it.
642 // Instead, ask the allocator to create new frames for us and discard
643 // any old ones as they come back. This takes the mutex while
644 // allocating, but nothing should really be sending frames in there
645 // right now anyway (start_bm_capture() has not been called yet).
646 card->frame_allocator->reconfigure(pixel_format, FRAME_SIZE, global_flags.width, global_flags.height, card_index, mjpeg_encoder.get());
648 card->capture->set_video_frame_allocator(card->frame_allocator.get());
649 if (card->surface == nullptr) {
650 card->surface = create_surface_with_same_format(mixer_surface);
652 while (!card->new_frames.empty()) card->new_frames.pop_front();
653 card->last_timecode = -1;
654 card->capture->set_pixel_format(pixel_format);
655 card->capture->configure_card();
657 // NOTE: start_bm_capture() happens in thread_func().
661 assert(card_type == CardType::FFMPEG_INPUT);
664 DeviceSpec device{InputSourceType::CAPTURE_CARD, card_index};
665 unsigned num_channels = card_type == CardType::LIVE_CARD ? 8 : 2;
667 audio_mixer->set_device_parameters(device, card->capture->get_description(), card_type, num_channels, /*active=*/true);
669 // Note: Keeps the previous name, if any.
671 snprintf(name, sizeof(name), "Fake card %u", card_index + 1);
672 audio_mixer->set_device_parameters(device, name, card_type, num_channels, /*active=*/false);
674 audio_mixer->reset_resampler(device);
675 audio_mixer->trigger_state_changed_callback();
677 // Unregister old metrics, if any.
678 if (!card->labels.empty()) {
679 const vector<pair<string, string>> &labels = card->labels;
680 card->jitter_history.unregister_metrics(labels);
681 card->queue_length_policy.unregister_metrics(labels);
682 global_metrics.remove_if_exists("input_received_frames", labels);
683 global_metrics.remove_if_exists("input_dropped_frames_jitter", labels);
684 global_metrics.remove_if_exists("input_dropped_frames_error", labels);
685 global_metrics.remove_if_exists("input_dropped_frames_resets", labels);
686 global_metrics.remove_if_exists("input_queue_length_frames", labels);
687 global_metrics.remove_if_exists("input_queue_duped_frames", labels);
689 global_metrics.remove_if_exists("input_has_signal_bool", labels);
690 global_metrics.remove_if_exists("input_is_connected_bool", labels);
691 global_metrics.remove_if_exists("input_interlaced_bool", labels);
692 global_metrics.remove_if_exists("input_width_pixels", labels);
693 global_metrics.remove_if_exists("input_height_pixels", labels);
694 global_metrics.remove_if_exists("input_frame_rate_nom", labels);
695 global_metrics.remove_if_exists("input_frame_rate_den", labels);
696 global_metrics.remove_if_exists("input_sample_rate_hz", labels);
698 card->srt_metrics.deinit(labels);
703 vector<pair<string, string>> labels;
705 snprintf(card_name, sizeof(card_name), "%d", card_index);
706 labels.emplace_back("card", card_name);
709 case CardType::LIVE_CARD:
710 labels.emplace_back("cardtype", "live");
712 case CardType::FAKE_CAPTURE:
713 labels.emplace_back("cardtype", "fake");
715 case CardType::FFMPEG_INPUT:
717 labels.emplace_back("cardtype", "srt");
719 labels.emplace_back("cardtype", "ffmpeg");
722 case CardType::CEF_INPUT:
723 labels.emplace_back("cardtype", "cef");
728 card->jitter_history.register_metrics(labels);
729 card->queue_length_policy.register_metrics(labels);
730 global_metrics.add("input_received_frames", labels, &card->metric_input_received_frames);
731 global_metrics.add("input_dropped_frames_jitter", labels, &card->metric_input_dropped_frames_jitter);
732 global_metrics.add("input_dropped_frames_error", labels, &card->metric_input_dropped_frames_error);
733 global_metrics.add("input_dropped_frames_resets", labels, &card->metric_input_resets);
734 global_metrics.add("input_queue_length_frames", labels, &card->metric_input_queue_length_frames, Metrics::TYPE_GAUGE);
735 global_metrics.add("input_queue_duped_frames", labels, &card->metric_input_duped_frames);
737 global_metrics.add("input_has_signal_bool", labels, &card->metric_input_has_signal_bool, Metrics::TYPE_GAUGE);
738 global_metrics.add("input_is_connected_bool", labels, &card->metric_input_is_connected_bool, Metrics::TYPE_GAUGE);
739 global_metrics.add("input_interlaced_bool", labels, &card->metric_input_interlaced_bool, Metrics::TYPE_GAUGE);
740 global_metrics.add("input_width_pixels", labels, &card->metric_input_width_pixels, Metrics::TYPE_GAUGE);
741 global_metrics.add("input_height_pixels", labels, &card->metric_input_height_pixels, Metrics::TYPE_GAUGE);
742 global_metrics.add("input_frame_rate_nom", labels, &card->metric_input_frame_rate_nom, Metrics::TYPE_GAUGE);
743 global_metrics.add("input_frame_rate_den", labels, &card->metric_input_frame_rate_den, Metrics::TYPE_GAUGE);
744 global_metrics.add("input_sample_rate_hz", labels, &card->metric_input_sample_rate_hz, Metrics::TYPE_GAUGE);
747 card->srt_metrics.init(labels);
750 card->labels = labels;
752 card->labels.clear();
756 void Mixer::set_output_card_internal(int card_index)
758 // We don't really need to take card_mutex, since we're in the mixer
759 // thread and don't mess with any queues (which is the only thing that happens
760 // from other threads), but it's probably the safest in the long run.
761 unique_lock<mutex> lock(card_mutex);
762 if (output_card_index != -1) {
763 // Switch the old card from output to input.
764 CaptureCard *old_card = &cards[output_card_index];
765 old_card->output->end_output();
767 // Stop the fake card that we put into place.
768 // This needs to _not_ happen under the mutex, to avoid deadlock
769 // (delivering the last frame needs to take the mutex).
770 CaptureInterface *fake_capture = old_card->capture.get();
772 fake_capture->stop_dequeue_thread();
774 old_card->capture = move(old_card->parked_capture); // TODO: reset the metrics
775 old_card->is_fake_capture = false;
776 old_card->capture->start_bm_capture();
778 if (card_index != -1) {
779 CaptureCard *card = &cards[card_index];
780 CaptureInterface *capture = card->capture.get();
781 // TODO: DeckLinkCapture::stop_dequeue_thread can actually take
782 // several seconds to complete (blocking on DisableVideoInput);
783 // see if we can maybe do it asynchronously.
785 capture->stop_dequeue_thread();
787 card->parked_capture = move(card->capture);
788 CaptureInterface *fake_capture = new FakeCapture(global_flags.width, global_flags.height, FAKE_FPS, OUTPUT_FREQUENCY, card_index, global_flags.fake_cards_audio);
789 configure_card(card_index, fake_capture, CardType::FAKE_CAPTURE, card->output.release(), /*is_srt_card=*/false);
790 card->jitter_history.clear();
791 card->capture->start_bm_capture();
792 desired_output_video_mode = output_video_mode = card->output->pick_video_mode(desired_output_video_mode);
793 card->output->start_output(desired_output_video_mode, pts_int, /*is_master_card=*/output_card_is_master);
795 output_card_index = card_index;
796 output_jitter_history.clear();
801 int unwrap_timecode(uint16_t current_wrapped, int last)
803 uint16_t last_wrapped = last & 0xffff;
804 if (current_wrapped > last_wrapped) {
805 return (last & ~0xffff) | current_wrapped;
807 return 0x10000 + ((last & ~0xffff) | current_wrapped);
813 void Mixer::bm_frame(unsigned card_index, uint16_t timecode,
814 FrameAllocator::Frame video_frame, size_t video_offset, VideoFormat video_format,
815 FrameAllocator::Frame audio_frame, size_t audio_offset, AudioFormat audio_format)
817 DeviceSpec device{InputSourceType::CAPTURE_CARD, card_index};
818 CaptureCard *card = &cards[card_index];
820 ++card->metric_input_received_frames;
821 card->metric_input_has_signal_bool = video_format.has_signal;
822 card->metric_input_is_connected_bool = video_format.is_connected;
823 card->metric_input_interlaced_bool = video_format.interlaced;
824 card->metric_input_width_pixels = video_format.width;
825 card->metric_input_height_pixels = video_format.height;
826 card->metric_input_frame_rate_nom = video_format.frame_rate_nom;
827 card->metric_input_frame_rate_den = video_format.frame_rate_den;
828 card->metric_input_sample_rate_hz = audio_format.sample_rate;
830 if (is_mode_scanning[card_index]) {
831 if (video_format.has_signal) {
832 // Found a stable signal, so stop scanning.
833 is_mode_scanning[card_index] = false;
835 static constexpr double switch_time_s = 0.1; // Should be enough time for the signal to stabilize.
836 steady_clock::time_point now = steady_clock::now();
837 double sec_since_last_switch = duration<double>(steady_clock::now() - last_mode_scan_change[card_index]).count();
838 if (sec_since_last_switch > switch_time_s) {
839 // It isn't this mode; try the next one.
840 mode_scanlist_index[card_index]++;
841 mode_scanlist_index[card_index] %= mode_scanlist[card_index].size();
842 cards[card_index].capture->set_video_mode(mode_scanlist[card_index][mode_scanlist_index[card_index]]);
843 last_mode_scan_change[card_index] = now;
848 int64_t frame_length = int64_t(TIMEBASE) * video_format.frame_rate_den / video_format.frame_rate_nom;
849 assert(frame_length > 0);
851 size_t num_samples = (audio_frame.len > audio_offset) ? (audio_frame.len - audio_offset) / audio_format.num_channels / (audio_format.bits_per_sample / 8) : 0;
852 if (num_samples > OUTPUT_FREQUENCY / 10 && card->type != CardType::FFMPEG_INPUT) {
853 printf("%s: Dropping frame with implausible audio length (len=%d, offset=%d) [timecode=0x%04x video_len=%d video_offset=%d video_format=%x)\n",
854 description_for_card(card_index).c_str(), int(audio_frame.len), int(audio_offset),
855 timecode, int(video_frame.len), int(video_offset), video_format.id);
856 if (video_frame.owner) {
857 video_frame.owner->release_frame(video_frame);
859 if (audio_frame.owner) {
860 audio_frame.owner->release_frame(audio_frame);
865 int dropped_frames = 0;
866 if (card->last_timecode != -1) {
867 dropped_frames = unwrap_timecode(timecode, card->last_timecode) - card->last_timecode - 1;
870 // Number of samples per frame if we need to insert silence.
871 // (Could be nonintegral, but resampling will save us then.)
872 const int silence_samples = OUTPUT_FREQUENCY * video_format.frame_rate_den / video_format.frame_rate_nom;
874 if (dropped_frames > TYPICAL_FPS * 2) {
875 fprintf(stderr, "%s lost more than two seconds (or time code jumping around; from 0x%04x to 0x%04x), resetting resampler\n",
876 description_for_card(card_index).c_str(), card->last_timecode, timecode);
877 audio_mixer->reset_resampler(device);
879 ++card->metric_input_resets;
880 } else if (dropped_frames > 0) {
881 // Insert silence as needed.
882 fprintf(stderr, "%s dropped %d frame(s) (before timecode 0x%04x), inserting silence.\n",
883 description_for_card(card_index).c_str(), dropped_frames, timecode);
884 card->metric_input_dropped_frames_error += dropped_frames;
888 success = audio_mixer->add_silence(device, silence_samples, dropped_frames);
892 if (num_samples > 0) {
893 audio_mixer->add_audio(device, audio_frame.data + audio_offset, num_samples, audio_format, audio_frame.received_timestamp);
895 // Audio for the MJPEG stream. We don't resample; audio that's not in 48 kHz
896 // just gets dropped for now.
898 // Only bother doing MJPEG encoding if there are any connected clients
899 // that want the stream.
900 if (httpd.get_num_connected_multicam_clients() > 0 ||
901 httpd.get_num_connected_siphon_clients(card_index) > 0) {
902 vector<int32_t> converted_samples = convert_audio_to_fixed32(audio_frame.data + audio_offset, num_samples, audio_format, 2);
903 lock_guard<mutex> lock(card_mutex);
904 if (card->new_raw_audio.empty()) {
905 card->new_raw_audio = move(converted_samples);
907 // For raw audio, we don't really synchronize audio and video;
908 // we just put the audio in frame by frame, and if a video frame is
909 // dropped, we still keep the audio, which means it will be added
910 // to the beginning of the next frame. It would probably be better
911 // to move the audio pts earlier to show this, but most players can
912 // live with some jitter, and in a lot of ways, it's much nicer for
913 // Futatabi to have all audio locked to a video frame.
914 card->new_raw_audio.insert(card->new_raw_audio.end(), converted_samples.begin(), converted_samples.end());
916 // Truncate to one second, just to be sure we don't have infinite buildup in case of weirdness.
917 if (card->new_raw_audio.size() > OUTPUT_FREQUENCY * 2) {
918 size_t excess_samples = card->new_raw_audio.size() - OUTPUT_FREQUENCY * 2;
919 card->new_raw_audio.erase(card->new_raw_audio.begin(), card->new_raw_audio.begin() + excess_samples);
925 // Done with the audio, so release it.
926 if (audio_frame.owner) {
927 audio_frame.owner->release_frame(audio_frame);
930 card->last_timecode = timecode;
932 PBOFrameAllocator::Userdata *userdata = (PBOFrameAllocator::Userdata *)video_frame.userdata;
933 if (card->type == CardType::FFMPEG_INPUT && userdata != nullptr) {
934 FFmpegCapture *ffmpeg_capture = static_cast<FFmpegCapture *>(card->capture.get());
935 userdata->has_last_subtitle = ffmpeg_capture->get_has_last_subtitle();
936 userdata->last_subtitle = ffmpeg_capture->get_last_subtitle();
939 if (card->type == CardType::FFMPEG_INPUT) {
940 int srt_sock = static_cast<FFmpegCapture *>(card->capture.get())->get_srt_sock();
941 if (srt_sock != -1) {
942 card->srt_metrics.update_srt_stats(srt_sock);
947 size_t y_offset, cbcr_offset;
948 size_t expected_length = video_format.stride * (video_format.height + video_format.extra_lines_top + video_format.extra_lines_bottom);
949 if (userdata != nullptr && userdata->pixel_format == PixelFormat_8BitYCbCrPlanar) {
950 // The calculation above is wrong for planar Y'CbCr, so just override it.
951 assert(card->type == CardType::FFMPEG_INPUT);
952 assert(video_offset == 0);
953 expected_length = video_frame.len;
955 userdata->ycbcr_format = (static_cast<FFmpegCapture *>(card->capture.get()))->get_current_frame_ycbcr_format();
957 cbcr_offset = video_format.width * video_format.height;
959 // All the other Y'CbCr formats are 4:2:2.
960 y_offset = video_frame.size / 2 + video_offset / 2;
961 cbcr_offset = video_offset / 2;
963 if (video_frame.len - video_offset == 0 ||
964 video_frame.len - video_offset != expected_length) {
965 if (video_frame.len != 0) {
966 printf("%s: Dropping video frame with wrong length (%zu; expected %zu)\n",
967 description_for_card(card_index).c_str(), video_frame.len - video_offset, expected_length);
969 if (video_frame.owner) {
970 video_frame.owner->release_frame(video_frame);
973 // Still send on the information that we _had_ a frame, even though it's corrupted,
974 // so that pts can go up accordingly.
976 lock_guard<mutex> lock(card_mutex);
977 CaptureCard::NewFrame new_frame;
978 new_frame.frame = RefCountedFrame(FrameAllocator::Frame());
979 new_frame.length = frame_length;
980 new_frame.interlaced = false;
981 new_frame.dropped_frames = dropped_frames;
982 new_frame.received_timestamp = video_frame.received_timestamp;
983 card->new_frames.push_back(move(new_frame));
984 card->jitter_history.frame_arrived(video_frame.received_timestamp, frame_length, dropped_frames);
986 card->new_frames_changed.notify_all();
990 unsigned num_fields = video_format.interlaced ? 2 : 1;
991 steady_clock::time_point frame_upload_start;
992 if (video_format.interlaced) {
993 // Send the two fields along as separate frames; the other side will need to add
994 // a deinterlacer to actually get this right.
995 assert(video_format.height % 2 == 0);
996 video_format.height /= 2;
997 assert(frame_length % 2 == 0);
1000 frame_upload_start = steady_clock::now();
1002 assert(userdata != nullptr);
1003 userdata->last_interlaced = video_format.interlaced;
1004 userdata->last_has_signal = video_format.has_signal;
1005 userdata->last_is_connected = video_format.is_connected;
1006 userdata->last_frame_rate_nom = video_format.frame_rate_nom;
1007 userdata->last_frame_rate_den = video_format.frame_rate_den;
1008 RefCountedFrame frame(video_frame);
1010 // Send the frames on to the main thread, which will upload and process htem.
1011 // It is entirely possible to upload them in the same thread (and it might even be
1012 // faster, depending on the GPU and driver), but it appears to be trickling
1013 // driver bugs very easily.
1015 // Note that this means we must hold on to the actual frame data in <userdata>
1016 // until the upload is done, but we hold on to <frame> much longer than that
1017 // (in fact, all the way until we no longer use the texture in rendering).
1018 for (unsigned field = 0; field < num_fields; ++field) {
1020 // Don't upload the second field as fast as we can; wait until
1021 // the field time has approximately passed. (Otherwise, we could
1022 // get timing jitter against the other sources, and possibly also
1023 // against the video display, although the latter is not as critical.)
1024 // This requires our system clock to be reasonably close to the
1025 // video clock, but that's not an unreasonable assumption.
1026 steady_clock::time_point second_field_start = frame_upload_start +
1027 nanoseconds(frame_length * 1000000000 / TIMEBASE);
1028 this_thread::sleep_until(second_field_start);
1032 lock_guard<mutex> lock(card_mutex);
1033 CaptureCard::NewFrame new_frame;
1034 new_frame.frame = frame;
1035 new_frame.length = frame_length;
1036 new_frame.field = field;
1037 new_frame.interlaced = video_format.interlaced;
1038 new_frame.dropped_frames = dropped_frames;
1039 new_frame.received_timestamp = video_frame.received_timestamp; // Ignore the audio timestamp.
1040 new_frame.video_format = video_format;
1041 new_frame.video_offset = video_offset;
1042 new_frame.y_offset = y_offset;
1043 new_frame.cbcr_offset = cbcr_offset;
1044 new_frame.texture_uploaded = false;
1045 if (card->type == CardType::FFMPEG_INPUT) {
1046 FFmpegCapture *ffmpeg_capture = static_cast<FFmpegCapture *>(card->capture.get());
1047 new_frame.neutral_color = ffmpeg_capture->get_last_neutral_color();
1049 card->new_frames.push_back(move(new_frame));
1050 card->jitter_history.frame_arrived(video_frame.received_timestamp, frame_length, dropped_frames);
1051 card->may_have_dropped_last_frame = false;
1053 card->new_frames_changed.notify_all();
1057 void Mixer::upload_texture_for_frame(
1058 int field, bmusb::VideoFormat video_format,
1059 size_t y_offset, size_t cbcr_offset, size_t video_offset, PBOFrameAllocator::Userdata *userdata)
1061 size_t cbcr_width, cbcr_height;
1062 if (userdata != nullptr && userdata->pixel_format == PixelFormat_8BitYCbCrPlanar) {
1063 cbcr_width = video_format.width / userdata->ycbcr_format.chroma_subsampling_x;
1064 cbcr_height = video_format.height / userdata->ycbcr_format.chroma_subsampling_y;
1066 // All the other Y'CbCr formats are 4:2:2.
1067 cbcr_width = video_format.width / 2;
1068 cbcr_height = video_format.height;
1071 bool interlaced_stride = video_format.interlaced && (video_format.second_field_start == 1);
1072 if (video_format.interlaced) {
1076 unsigned field_start_line;
1078 field_start_line = video_format.second_field_start;
1080 field_start_line = video_format.extra_lines_top;
1083 // For anything not FRAME_FORMAT_YCBCR_10BIT, v210_width will be nonsensical but not used.
1084 size_t v210_width = video_format.stride / sizeof(uint32_t);
1085 ensure_texture_resolution(userdata, field, video_format.width, video_format.height, cbcr_width, cbcr_height, v210_width);
1087 glBindBuffer(GL_PIXEL_UNPACK_BUFFER, userdata->pbo);
1090 switch (userdata->pixel_format) {
1091 case PixelFormat_10BitYCbCr: {
1092 size_t field_start = video_offset + video_format.stride * field_start_line;
1093 upload_texture(userdata->tex_v210[field], v210_width, video_format.height, video_format.stride, interlaced_stride, GL_RGBA, GL_UNSIGNED_INT_2_10_10_10_REV, field_start);
1094 v210_converter->convert(userdata->tex_v210[field], userdata->tex_444[field], video_format.width, video_format.height);
1097 case PixelFormat_8BitYCbCr: {
1098 size_t field_y_start = y_offset + video_format.width * field_start_line;
1099 size_t field_cbcr_start = cbcr_offset + cbcr_width * field_start_line * sizeof(uint16_t);
1101 // Make up our own strides, since we are interleaving.
1102 upload_texture(userdata->tex_y[field], video_format.width, video_format.height, video_format.width, interlaced_stride, GL_RED, GL_UNSIGNED_BYTE, field_y_start);
1103 upload_texture(userdata->tex_cbcr[field], cbcr_width, cbcr_height, cbcr_width * sizeof(uint16_t), interlaced_stride, GL_RG, GL_UNSIGNED_BYTE, field_cbcr_start);
1106 case PixelFormat_8BitYCbCrPlanar: {
1107 assert(field_start_line == 0); // We don't really support interlaced here.
1108 size_t field_y_start = y_offset;
1109 size_t field_cb_start = cbcr_offset;
1110 size_t field_cr_start = cbcr_offset + cbcr_width * cbcr_height;
1112 // Make up our own strides, since we are interleaving.
1113 upload_texture(userdata->tex_y[field], video_format.width, video_format.height, video_format.width, interlaced_stride, GL_RED, GL_UNSIGNED_BYTE, field_y_start);
1114 upload_texture(userdata->tex_cb[field], cbcr_width, cbcr_height, cbcr_width, interlaced_stride, GL_RED, GL_UNSIGNED_BYTE, field_cb_start);
1115 upload_texture(userdata->tex_cr[field], cbcr_width, cbcr_height, cbcr_width, interlaced_stride, GL_RED, GL_UNSIGNED_BYTE, field_cr_start);
1118 case PixelFormat_8BitBGRA: {
1119 size_t field_start = video_offset + video_format.stride * field_start_line;
1120 upload_texture(userdata->tex_rgba[field], video_format.width, video_format.height, video_format.stride, interlaced_stride, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, field_start);
1121 // These could be asked to deliver mipmaps at any time.
1122 glBindTexture(GL_TEXTURE_2D, userdata->tex_rgba[field]);
1124 glGenerateMipmap(GL_TEXTURE_2D);
1126 glBindTexture(GL_TEXTURE_2D, 0);
1134 glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
1138 void Mixer::bm_hotplug_add(libusb_device *dev)
1140 lock_guard<mutex> lock(hotplug_mutex);
1141 hotplugged_cards.push_back(dev);
1144 void Mixer::bm_hotplug_remove(unsigned card_index)
1146 cards[card_index].new_frames_changed.notify_all();
1149 void Mixer::thread_func()
1151 pthread_setname_np(pthread_self(), "Mixer_OpenGL");
1153 eglBindAPI(EGL_OPENGL_API);
1154 QOpenGLContext *context = create_context(mixer_surface);
1155 if (!make_current(context, mixer_surface)) {
1160 // Start the actual capture. (We don't want to do it before we're actually ready
1161 // to process output frames.)
1162 for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) {
1163 if (int(card_index) != output_card_index && cards[card_index].capture != nullptr) {
1164 cards[card_index].capture->start_bm_capture();
1168 BasicStats basic_stats(/*verbose=*/true, /*use_opengl=*/true);
1169 int stats_dropped_frames = 0;
1171 while (!should_quit) {
1172 if (desired_output_card_index != output_card_index) {
1173 set_output_card_internal(desired_output_card_index);
1175 if (output_card_index != -1 &&
1176 desired_output_video_mode != output_video_mode) {
1177 DeckLinkOutput *output = cards[output_card_index].output.get();
1178 output->end_output();
1179 desired_output_video_mode = output_video_mode = output->pick_video_mode(desired_output_video_mode);
1180 output->start_output(desired_output_video_mode, pts_int, /*is_master_card=*/output_card_is_master);
1184 lock_guard<mutex> lock(card_mutex);
1185 handle_hotplugged_cards();
1188 CaptureCard::NewFrame new_frames[MAX_VIDEO_CARDS];
1189 bool has_new_frame[MAX_VIDEO_CARDS] = { false };
1191 bool master_card_is_output;
1192 unsigned master_card_index;
1193 if (output_card_index != -1 && output_card_is_master) {
1194 master_card_is_output = true;
1195 master_card_index = output_card_index;
1197 master_card_is_output = false;
1198 master_card_index = theme->map_signal_to_card(master_clock_channel);
1199 assert(master_card_index < MAX_VIDEO_CARDS);
1202 vector<int32_t> raw_audio[MAX_VIDEO_CARDS]; // For MJPEG encoding.
1203 OutputFrameInfo output_frame_info = get_one_frame_from_each_card(master_card_index, master_card_is_output, new_frames, has_new_frame, raw_audio);
1204 schedule_audio_resampling_tasks(output_frame_info.dropped_frames, output_frame_info.num_samples, output_frame_info.frame_duration, output_frame_info.is_preroll, output_frame_info.frame_timestamp);
1205 stats_dropped_frames += output_frame_info.dropped_frames;
1207 for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) {
1208 if (card_index == master_card_index || !has_new_frame[card_index]) {
1211 if (new_frames[card_index].frame->len == 0) {
1212 ++new_frames[card_index].dropped_frames;
1214 if (new_frames[card_index].dropped_frames > 0) {
1215 printf("%s dropped %d frames before this\n",
1216 description_for_card(card_index).c_str(), int(new_frames[card_index].dropped_frames));
1220 // If the first card is reporting a corrupted or otherwise dropped frame,
1221 // just increase the pts (skipping over this frame) and don't try to compute anything new.
1222 if (!master_card_is_output &&
1223 new_frames[master_card_index].frame != nullptr && // Timeout.
1224 new_frames[master_card_index].frame->len == 0) {
1225 ++stats_dropped_frames;
1226 pts_int += new_frames[master_card_index].length;
1230 for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) {
1231 if (!has_new_frame[card_index] || new_frames[card_index].frame->len == 0)
1234 CaptureCard::NewFrame *new_frame = &new_frames[card_index];
1235 assert(new_frame->frame != nullptr);
1236 insert_new_frame(new_frame->frame, new_frame->field, new_frame->interlaced, card_index, &input_state);
1239 // The new texture might need uploading before use.
1240 if (!new_frame->texture_uploaded) {
1241 upload_texture_for_frame(new_frame->field, new_frame->video_format, new_frame->y_offset, new_frame->cbcr_offset,
1242 new_frame->video_offset, (PBOFrameAllocator::Userdata *)new_frame->frame->userdata);
1243 new_frame->texture_uploaded = true;
1246 // Only set the white balance if it actually changed. This means that the user
1247 // is free to override the white balance in a video with no white balance information
1248 // actually set (ie. r=g=b=1 all the time), or one where the white point is wrong,
1249 // but frame-to-frame decisions will be heeded. We do this pretty much as late
1250 // as possible (ie., after picking out the frame from the buffer), so that we are sure
1251 // that the change takes effect on exactly the right frame.
1252 if (fabs(new_frame->neutral_color.r - last_received_neutral_color[card_index].r) > 1e-3 ||
1253 fabs(new_frame->neutral_color.g - last_received_neutral_color[card_index].g) > 1e-3 ||
1254 fabs(new_frame->neutral_color.b - last_received_neutral_color[card_index].b) > 1e-3) {
1255 theme->set_wb_for_card(card_index, new_frame->neutral_color.r, new_frame->neutral_color.g, new_frame->neutral_color.b);
1256 last_received_neutral_color[card_index] = new_frame->neutral_color;
1259 if (new_frame->frame->data_copy != nullptr && mjpeg_encoder->should_encode_mjpeg_for_card(card_index)) {
1260 RGBTriplet neutral_color = theme->get_white_balance_for_card(card_index);
1261 mjpeg_encoder->upload_frame(pts_int, card_index, new_frame->frame, new_frame->video_format, new_frame->y_offset, new_frame->cbcr_offset, move(raw_audio[card_index]), neutral_color);
1266 int64_t frame_duration = output_frame_info.frame_duration;
1267 render_one_frame(frame_duration);
1269 lock_guard<mutex> lock(frame_num_mutex);
1272 frame_num_updated.notify_all();
1273 pts_int += frame_duration;
1275 basic_stats.update(frame_num, stats_dropped_frames);
1276 // if (frame_num % 100 == 0) chain->print_phase_timing();
1278 if (should_cut.exchange(false)) { // Test and clear.
1279 video_encoder->do_cut(frame_num);
1283 // Reset every 100 frames, so that local variations in frame times
1284 // (especially for the first few frames, when the shaders are
1285 // compiled etc.) don't make it hard to measure for the entire
1286 // remaining duration of the program.
1287 if (frame == 10000) {
1295 resource_pool->clean_context();
1298 bool Mixer::input_card_is_master_clock(unsigned card_index, unsigned master_card_index) const
1300 if (output_card_index != -1 && output_card_is_master) {
1301 // The output card (ie., cards[output_card_index].output) is the master clock,
1302 // so no input card (ie., cards[card_index].capture) is.
1305 return (card_index == master_card_index);
1308 void Mixer::trim_queue(CaptureCard *card, size_t safe_queue_length)
1310 // Count the number of frames in the queue, including any frames
1311 // we dropped. It's hard to know exactly how we should deal with
1312 // dropped (corrupted) input frames; they don't help our goal of
1313 // avoiding starvation, but they still add to the problem of latency.
1314 // Since dropped frames is going to mean a bump in the signal anyway,
1315 // we err on the side of having more stable latency instead.
1316 unsigned queue_length = 0;
1317 for (const CaptureCard::NewFrame &frame : card->new_frames) {
1318 queue_length += frame.dropped_frames + 1;
1321 // If needed, drop frames until the queue is below the safe limit.
1322 // We prefer to drop from the head, because all else being equal,
1323 // we'd like more recent frames (less latency).
1324 unsigned dropped_frames = 0;
1325 while (queue_length > safe_queue_length) {
1326 assert(!card->new_frames.empty());
1327 assert(queue_length > card->new_frames.front().dropped_frames);
1328 queue_length -= card->new_frames.front().dropped_frames;
1330 if (queue_length <= safe_queue_length) {
1331 // No need to drop anything.
1335 card->new_frames.pop_front();
1336 card->new_frames_changed.notify_all();
1340 if (queue_length == 0 && card->is_cef_capture) {
1341 card->may_have_dropped_last_frame = true;
1345 card->metric_input_dropped_frames_jitter += dropped_frames;
1346 card->metric_input_queue_length_frames = queue_length;
1349 if (dropped_frames > 0) {
1350 fprintf(stderr, "Card %u dropped %u frame(s) to keep latency down.\n",
1351 card_index, dropped_frames);
1356 pair<string, string> Mixer::get_channels_json()
1359 for (int channel_idx = 0; channel_idx < theme->get_num_channels(); ++channel_idx) {
1360 Channel *channel = ret.add_channel();
1361 channel->set_index(channel_idx + 2);
1362 channel->set_name(theme->get_channel_name(channel_idx + 2));
1363 channel->set_color(theme->get_channel_color(channel_idx + 2));
1366 google::protobuf::util::MessageToJsonString(ret, &contents); // Ignore any errors.
1367 return make_pair(contents, "text/json");
1370 pair<string, string> Mixer::get_channel_color_http(unsigned channel_idx)
1372 return make_pair(theme->get_channel_color(channel_idx), "text/plain");
1375 Mixer::OutputFrameInfo Mixer::get_one_frame_from_each_card(unsigned master_card_index, bool master_card_is_output, CaptureCard::NewFrame new_frames[MAX_VIDEO_CARDS], bool has_new_frame[MAX_VIDEO_CARDS], vector<int32_t> raw_audio[MAX_VIDEO_CARDS])
1377 OutputFrameInfo output_frame_info;
1378 constexpr steady_clock::duration master_card_timeout = milliseconds(200);
1380 unique_lock<mutex> lock(card_mutex, defer_lock);
1381 bool timed_out = false;
1382 if (master_card_is_output) {
1383 // Clocked to the output, so wait for it to be ready for the next frame.
1384 cards[master_card_index].output->wait_for_frame(pts_int, &output_frame_info.dropped_frames, &output_frame_info.frame_duration, &output_frame_info.is_preroll, &output_frame_info.frame_timestamp);
1387 // Wait for the master card to have a new frame.
1388 output_frame_info.is_preroll = false;
1390 timed_out = !cards[master_card_index].new_frames_changed.wait_for(lock,
1391 master_card_timeout,
1392 [this, master_card_index] {
1393 return !cards[master_card_index].new_frames.empty() ||
1394 cards[master_card_index].capture == nullptr ||
1395 cards[master_card_index].capture->get_disconnected();
1398 fprintf(stderr, "WARNING: Master card (%s) did not deliver a frame for %u ms, creating a fake one.\n",
1399 description_for_card(master_card_index).c_str(),
1400 unsigned(duration_cast<milliseconds>(master_card_timeout).count()));
1405 // The master card stalled for 200 ms (possible when it's e.g.
1406 // an SRT card). Send a frame no matter what; this also makes sure
1407 // any other cards get to empty their queues, and in general,
1408 // that we make _some_ sort of forward progress.
1409 handle_hotplugged_cards();
1410 } else if (master_card_is_output) {
1411 handle_hotplugged_cards();
1412 } else if (cards[master_card_index].new_frames.empty()) {
1413 // We were woken up, but not due to a new frame. Deal with it
1414 // and then restart.
1415 assert(cards[master_card_index].capture == nullptr ||
1416 cards[master_card_index].capture->get_disconnected());
1417 handle_hotplugged_cards();
1422 for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) {
1423 CaptureCard *card = &cards[card_index];
1424 if (card->new_frames.empty()) { // Starvation.
1425 ++card->metric_input_duped_frames;
1427 if (card->is_cef_capture && card->may_have_dropped_last_frame) {
1428 // Unlike other sources, CEF is not guaranteed to send us a steady
1429 // stream of frames, so we'll have to ask it to repaint the frame
1430 // we dropped. (may_have_dropped_last_frame is set whenever we
1431 // trim the queue completely away, and cleared when we actually
1432 // get a new frame.)
1433 ((CEFCapture *)card->capture.get())->request_new_frame(/*ignore_if_locked=*/true);
1437 new_frames[card_index] = move(card->new_frames.front());
1438 has_new_frame[card_index] = true;
1439 card->new_frames.pop_front();
1440 card->new_frames_changed.notify_all();
1443 raw_audio[card_index] = move(card->new_raw_audio);
1447 // Pretend the frame happened a while ago and was only processed now,
1448 // so that we get the duration sort-of right. This isn't ideal.
1449 output_frame_info.dropped_frames = 0; // Hard to define, really.
1450 output_frame_info.frame_duration = lrint(TIMEBASE * duration<double>(master_card_timeout).count());
1451 output_frame_info.frame_timestamp = steady_clock::now() - master_card_timeout;
1452 } else if (!master_card_is_output) {
1453 output_frame_info.frame_timestamp = new_frames[master_card_index].received_timestamp;
1454 output_frame_info.dropped_frames = new_frames[master_card_index].dropped_frames;
1455 output_frame_info.frame_duration = new_frames[master_card_index].length;
1458 if (!output_frame_info.is_preroll) {
1459 output_jitter_history.frame_arrived(output_frame_info.frame_timestamp, output_frame_info.frame_duration, output_frame_info.dropped_frames);
1462 for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) {
1463 CaptureCard *card = &cards[card_index];
1464 if (has_new_frame[card_index] &&
1465 !input_card_is_master_clock(card_index, master_card_index) &&
1466 !output_frame_info.is_preroll) {
1467 card->queue_length_policy.update_policy(
1468 output_frame_info.frame_timestamp,
1469 card->jitter_history.get_expected_next_frame(),
1470 new_frames[master_card_index].length,
1471 output_frame_info.frame_duration,
1472 card->jitter_history.estimate_max_jitter(),
1473 output_jitter_history.estimate_max_jitter());
1474 trim_queue(card, min<int>(global_flags.max_input_queue_frames,
1475 card->queue_length_policy.get_safe_queue_length()));
1479 // This might get off by a fractional sample when changing master card
1480 // between ones with different frame rates, but that's fine.
1481 int64_t num_samples_times_timebase = int64_t(OUTPUT_FREQUENCY) * output_frame_info.frame_duration + fractional_samples;
1482 output_frame_info.num_samples = num_samples_times_timebase / TIMEBASE;
1483 fractional_samples = num_samples_times_timebase % TIMEBASE;
1484 assert(output_frame_info.num_samples >= 0);
1487 DeviceSpec device{InputSourceType::CAPTURE_CARD, master_card_index};
1490 success = audio_mixer->add_silence(device, output_frame_info.num_samples, /*dropped_frames=*/0);
1494 return output_frame_info;
1497 void Mixer::handle_hotplugged_cards()
1499 // Check for cards that have been disconnected since last frame.
1500 for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) {
1501 CaptureCard *card = &cards[card_index];
1502 if (card->capture != nullptr && card->capture->get_disconnected()) {
1503 bool is_active = card_index < unsigned(global_flags.min_num_cards) || cards[card_index].force_active;
1505 fprintf(stderr, "Card %u went away, replacing with a fake card.\n", card_index);
1506 FakeCapture *capture = new FakeCapture(global_flags.width, global_flags.height, FAKE_FPS, OUTPUT_FREQUENCY, card_index, global_flags.fake_cards_audio);
1507 configure_card(card_index, capture, CardType::FAKE_CAPTURE, /*output=*/nullptr, /*is_srt_card=*/false);
1508 card->jitter_history.clear();
1509 card->capture->start_bm_capture();
1511 // NOTE: The theme might end up forcing the card back at some later point
1512 // (ie., force_active is false now, but might immediately be true again on
1513 // e.g. the next frame). That should be rare, though, so we don't bother
1514 // adjusting the message.
1515 fprintf(stderr, "Card %u went away, removing. (To keep a fake card, increase --num-cards.)\n", card_index);
1516 theme->remove_card(card_index);
1517 configure_card(card_index, /*capture=*/nullptr, CardType::FAKE_CAPTURE, /*output=*/nullptr, /*is_srt_card=*/false);
1518 card->jitter_history.clear();
1523 // Count how many active cards we already have. Used below to check that we
1524 // don't go past the max_cards limit set by the user. Note that (non-SRT) video
1525 // and HTML “cards” don't count towards this limit.
1526 int num_video_cards = 0;
1527 for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) {
1528 CaptureCard *card = &cards[card_index];
1529 if (card->type == CardType::LIVE_CARD || is_srt_card(card)) {
1534 // Check for cards that have been connected since last frame.
1535 vector<libusb_device *> hotplugged_cards_copy;
1537 vector<int> hotplugged_srt_cards_copy;
1540 lock_guard<mutex> lock(hotplug_mutex);
1541 swap(hotplugged_cards, hotplugged_cards_copy);
1543 swap(hotplugged_srt_cards, hotplugged_srt_cards_copy);
1546 for (libusb_device *new_dev : hotplugged_cards_copy) {
1547 // Look for a fake capture card where we can stick this in.
1548 int free_card_index = -1;
1549 for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) {
1550 if (cards[card_index].is_fake_capture) {
1551 free_card_index = card_index;
1556 if (free_card_index == -1 || num_video_cards >= global_flags.max_num_cards) {
1557 fprintf(stderr, "New card plugged in, but no free slots -- ignoring.\n");
1558 libusb_unref_device(new_dev);
1560 // BMUSBCapture takes ownership.
1561 fprintf(stderr, "New card plugged in, choosing slot %d.\n", free_card_index);
1562 CaptureCard *card = &cards[free_card_index];
1563 BMUSBCapture *capture = new BMUSBCapture(free_card_index, new_dev);
1564 configure_card(free_card_index, capture, CardType::LIVE_CARD, /*output=*/nullptr, /*is_srt_card=*/false);
1565 card->jitter_history.clear();
1566 capture->set_card_disconnected_callback(bind(&Mixer::bm_hotplug_remove, this, free_card_index));
1567 capture->start_bm_capture();
1572 // Same, for SRT inputs.
1573 for (SRTSOCKET sock : hotplugged_srt_cards_copy) {
1575 int namelen = sizeof(name);
1576 srt_getsockopt(sock, /*ignored=*/0, SRTO_STREAMID, name, &namelen);
1577 string stream_id(name, namelen);
1579 // Look for a fake capture card where we can stick this in.
1580 // Prioritize ones that previously held SRT streams with the
1581 // same stream ID, if any exist -- and it multiple exist,
1582 // take the one that disconnected the last.
1583 int first_free_card_index = -1, last_matching_free_card_index = -1;
1584 for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) {
1585 CaptureCard *card = &cards[card_index];
1586 if (!card->is_fake_capture) {
1589 if (first_free_card_index == -1) {
1590 first_free_card_index = card_index;
1592 if (card->last_srt_stream_id == stream_id &&
1593 (last_matching_free_card_index == -1 ||
1594 card->fake_capture_counter >
1595 cards[last_matching_free_card_index].fake_capture_counter)) {
1596 last_matching_free_card_index = card_index;
1600 const int free_card_index = (last_matching_free_card_index != -1)
1601 ? last_matching_free_card_index : first_free_card_index;
1602 if (free_card_index == -1 || num_video_cards >= global_flags.max_num_cards) {
1603 if (stream_id.empty()) {
1604 stream_id = "no name";
1606 fprintf(stderr, "New SRT stream connected (%s), but no free slots -- ignoring.\n", stream_id.c_str());
1609 // FFmpegCapture takes ownership.
1610 if (stream_id.empty()) {
1611 fprintf(stderr, "New unnamed SRT stream connected, choosing slot %d.\n", free_card_index);
1613 fprintf(stderr, "New SRT stream connected (%s), choosing slot %d.\n", stream_id.c_str(), free_card_index);
1615 CaptureCard *card = &cards[free_card_index];
1616 FFmpegCapture *capture = new FFmpegCapture(sock, stream_id);
1617 capture->set_card_index(free_card_index);
1618 configure_card(free_card_index, capture, CardType::FFMPEG_INPUT, /*output=*/nullptr, /*is_srt_card=*/true);
1619 card->srt_metrics.update_srt_stats(sock); // Initial zero stats.
1620 card->last_srt_stream_id = stream_id;
1621 card->jitter_history.clear();
1622 capture->set_card_disconnected_callback(bind(&Mixer::bm_hotplug_remove, this, free_card_index));
1623 capture->start_bm_capture();
1628 // Finally, newly forced-to-active fake capture cards.
1629 for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) {
1630 CaptureCard *card = &cards[card_index];
1631 if (card->capture == nullptr && card->force_active) {
1632 FakeCapture *capture = new FakeCapture(global_flags.width, global_flags.height, FAKE_FPS, OUTPUT_FREQUENCY, card_index, global_flags.fake_cards_audio);
1633 configure_card(card_index, capture, CardType::FAKE_CAPTURE, /*output=*/nullptr, /*is_srt_card=*/false);
1634 card->jitter_history.clear();
1635 card->capture->start_bm_capture();
1641 void Mixer::schedule_audio_resampling_tasks(unsigned dropped_frames, int num_samples_per_frame, int length_per_frame, bool is_preroll, steady_clock::time_point frame_timestamp)
1643 // Resample the audio as needed, including from previously dropped frames.
1644 for (unsigned frame_num = 0; frame_num < dropped_frames + 1; ++frame_num) {
1645 const bool dropped_frame = (frame_num != dropped_frames);
1647 // Signal to the audio thread to process this frame.
1648 // Note that if the frame is a dropped frame, we signal that
1649 // we don't want to use this frame as base for adjusting
1650 // the resampler rate. The reason for this is that the timing
1651 // of these frames is often way too late; they typically don't
1652 // “arrive” before we synthesize them. Thus, we could end up
1653 // in a situation where we have inserted e.g. five audio frames
1654 // into the queue before we then start pulling five of them
1655 // back out. This makes ResamplingQueue overestimate the delay,
1656 // causing undue resampler changes. (We _do_ use the last,
1657 // non-dropped frame; perhaps we should just discard that as well,
1658 // since dropped frames are expected to be rare, and it might be
1659 // better to just wait until we have a slightly more normal situation).
1660 lock_guard<mutex> lock(audio_mutex);
1661 bool adjust_rate = !dropped_frame && !is_preroll;
1662 audio_task_queue.push(AudioTask{pts_int, num_samples_per_frame, adjust_rate, frame_timestamp});
1663 audio_task_queue_changed.notify_one();
1665 if (dropped_frame) {
1666 // For dropped frames, increase the pts. Note that if the format changed
1667 // in the meantime, we have no way of detecting that; we just have to
1668 // assume the frame length is always the same.
1669 pts_int += length_per_frame;
1674 void Mixer::render_one_frame(int64_t duration)
1676 // Determine the time code for this frame before we start rendering.
1677 string timecode_text = timecode_renderer->get_timecode_text(double(pts_int) / TIMEBASE, frame_num);
1678 if (display_timecode_on_stdout) {
1679 printf("Timecode: '%s'\n", timecode_text.c_str());
1682 // Update Y'CbCr settings for all cards.
1684 lock_guard<mutex> lock(card_mutex);
1685 for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) {
1686 YCbCrInterpretation *interpretation = &ycbcr_interpretation[card_index];
1687 input_state.ycbcr_coefficients_auto[card_index] = interpretation->ycbcr_coefficients_auto;
1688 input_state.ycbcr_coefficients[card_index] = interpretation->ycbcr_coefficients;
1689 input_state.full_range[card_index] = interpretation->full_range;
1693 // Get the main chain from the theme, and set its state immediately.
1694 Theme::Chain theme_main_chain = theme->get_chain(0, pts(), global_flags.width, global_flags.height, input_state);
1695 EffectChain *chain = theme_main_chain.chain;
1696 theme_main_chain.setup_chain();
1697 //theme_main_chain.chain->enable_phase_timing(true);
1699 // If HDMI/SDI output is active and the user has requested auto mode,
1700 // its mode overrides the existing Y'CbCr setting for the chain.
1701 YCbCrLumaCoefficients ycbcr_output_coefficients;
1702 if (global_flags.ycbcr_auto_coefficients && output_card_index != -1) {
1703 ycbcr_output_coefficients = cards[output_card_index].output->preferred_ycbcr_coefficients();
1705 ycbcr_output_coefficients = global_flags.ycbcr_rec709_coefficients ? YCBCR_REC_709 : YCBCR_REC_601;
1708 // TODO: Reduce the duplication against theme.cpp.
1709 YCbCrFormat output_ycbcr_format;
1710 output_ycbcr_format.chroma_subsampling_x = 1;
1711 output_ycbcr_format.chroma_subsampling_y = 1;
1712 output_ycbcr_format.luma_coefficients = ycbcr_output_coefficients;
1713 output_ycbcr_format.full_range = false;
1714 output_ycbcr_format.num_levels = 1 << global_flags.bit_depth;
1715 chain->change_ycbcr_output_format(output_ycbcr_format);
1717 // Render main chain. If we're using zerocopy Quick Sync encoding
1718 // (the default case), we take an extra copy of the created outputs,
1719 // so that we can display it back to the screen later (it's less memory
1720 // bandwidth than writing and reading back an RGBA texture, even at 16-bit).
1721 // Ideally, we'd like to avoid taking copies and just use the main textures
1722 // for display as well, but they're just views into VA-API memory and must be
1723 // unmapped during encoding, so we can't use them for display, unfortunately.
1724 GLuint y_tex, cbcr_full_tex, cbcr_tex;
1725 GLuint y_copy_tex, cbcr_copy_tex = 0;
1726 GLuint y_display_tex, cbcr_display_tex;
1727 GLenum y_type = (global_flags.bit_depth > 8) ? GL_R16 : GL_R8;
1728 GLenum cbcr_type = (global_flags.bit_depth > 8) ? GL_RG16 : GL_RG8;
1729 const bool is_zerocopy = video_encoder->is_zerocopy();
1731 cbcr_full_tex = resource_pool->create_2d_texture(cbcr_type, global_flags.width, global_flags.height);
1732 y_copy_tex = resource_pool->create_2d_texture(y_type, global_flags.width, global_flags.height);
1733 cbcr_copy_tex = resource_pool->create_2d_texture(cbcr_type, global_flags.width / 2, global_flags.height / 2);
1735 y_display_tex = y_copy_tex;
1736 cbcr_display_tex = cbcr_copy_tex;
1738 // y_tex and cbcr_tex will be given by VideoEncoder.
1740 cbcr_full_tex = resource_pool->create_2d_texture(cbcr_type, global_flags.width, global_flags.height);
1741 y_tex = resource_pool->create_2d_texture(y_type, global_flags.width, global_flags.height);
1742 cbcr_tex = resource_pool->create_2d_texture(cbcr_type, global_flags.width / 2, global_flags.height / 2);
1744 y_display_tex = y_tex;
1745 cbcr_display_tex = cbcr_tex;
1748 const int64_t av_delay = lrint(global_flags.audio_queue_length_ms * 0.001 * TIMEBASE); // Corresponds to the delay in ResamplingQueue.
1749 bool got_frame = video_encoder->begin_frame(pts_int + av_delay, duration, ycbcr_output_coefficients, theme_main_chain.input_frames, &y_tex, &cbcr_tex);
1754 fbo = resource_pool->create_fbo(y_tex, cbcr_full_tex, y_copy_tex);
1756 fbo = resource_pool->create_fbo(y_tex, cbcr_full_tex);
1759 chain->render_to_fbo(fbo, global_flags.width, global_flags.height);
1761 if (display_timecode_in_stream) {
1762 // Render the timecode on top.
1763 timecode_renderer->render_timecode(fbo, timecode_text);
1766 resource_pool->release_fbo(fbo);
1769 chroma_subsampler->subsample_chroma(cbcr_full_tex, global_flags.width, global_flags.height, cbcr_tex, cbcr_copy_tex);
1771 chroma_subsampler->subsample_chroma(cbcr_full_tex, global_flags.width, global_flags.height, cbcr_tex);
1773 if (output_card_index != -1) {
1774 cards[output_card_index].output->send_frame(y_tex, cbcr_full_tex, ycbcr_output_coefficients, theme_main_chain.input_frames, pts_int, duration);
1776 resource_pool->release_2d_texture(cbcr_full_tex);
1778 // Set the right state for the Y' and CbCr textures we use for display.
1779 glBindFramebuffer(GL_FRAMEBUFFER, 0);
1780 glBindTexture(GL_TEXTURE_2D, y_display_tex);
1781 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1782 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1783 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1785 glBindTexture(GL_TEXTURE_2D, cbcr_display_tex);
1786 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1787 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1788 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1790 RefCountedGLsync fence = video_encoder->end_frame();
1792 // The live frame pieces the Y'CbCr texture copies back into RGB and displays them.
1793 // It owns y_display_tex and cbcr_display_tex now (whichever textures they are).
1794 DisplayFrame live_frame;
1795 live_frame.chain = display_chain.get();
1796 live_frame.setup_chain = [this, y_display_tex, cbcr_display_tex]{
1797 display_input->set_texture_num(0, y_display_tex);
1798 display_input->set_texture_num(1, cbcr_display_tex);
1800 live_frame.ready_fence = fence;
1801 live_frame.input_frames = {};
1802 live_frame.temp_textures = { y_display_tex, cbcr_display_tex };
1803 output_channel[OUTPUT_LIVE].output_frame(move(live_frame));
1805 // Set up preview and any additional channels.
1806 for (int i = 1; i < theme->get_num_channels() + 2; ++i) {
1807 DisplayFrame display_frame;
1808 Theme::Chain chain = theme->get_chain(i, pts(), global_flags.width, global_flags.height, input_state); // FIXME: dimensions
1809 display_frame.chain = move(chain.chain);
1810 display_frame.setup_chain = move(chain.setup_chain);
1811 display_frame.ready_fence = fence;
1812 display_frame.input_frames = move(chain.input_frames);
1813 display_frame.temp_textures = {};
1814 output_channel[i].output_frame(move(display_frame));
1818 void Mixer::audio_thread_func()
1820 pthread_setname_np(pthread_self(), "Mixer_Audio");
1822 while (!should_quit) {
1826 unique_lock<mutex> lock(audio_mutex);
1827 audio_task_queue_changed.wait(lock, [this]{ return should_quit || !audio_task_queue.empty(); });
1831 task = audio_task_queue.front();
1832 audio_task_queue.pop();
1835 ResamplingQueue::RateAdjustmentPolicy rate_adjustment_policy =
1836 task.adjust_rate ? ResamplingQueue::ADJUST_RATE : ResamplingQueue::DO_NOT_ADJUST_RATE;
1837 vector<float> samples_out = audio_mixer->get_output(
1838 task.frame_timestamp,
1840 rate_adjustment_policy);
1842 // Send the samples to the sound card, then add them to the output.
1844 alsa->write(samples_out);
1846 if (output_card_index != -1) {
1847 const int64_t av_delay = lrint(global_flags.audio_queue_length_ms * 0.001 * TIMEBASE); // Corresponds to the delay in ResamplingQueue.
1848 cards[output_card_index].output->send_audio(task.pts_int + av_delay, samples_out);
1850 video_encoder->add_audio(task.pts_int, move(samples_out));
1854 void Mixer::release_display_frame(DisplayFrame *frame)
1856 for (GLuint texnum : frame->temp_textures) {
1857 resource_pool->release_2d_texture(texnum);
1859 frame->temp_textures.clear();
1860 frame->ready_fence.reset();
1861 frame->input_frames.clear();
1866 mixer_thread = thread(&Mixer::thread_func, this);
1867 audio_thread = thread(&Mixer::audio_thread_func, this);
1873 audio_task_queue_changed.notify_one();
1874 mixer_thread.join();
1875 audio_thread.join();
1877 if (global_flags.srt_port >= 0) {
1878 // There's seemingly no other reasonable way to wake up the thread
1879 // (libsrt's epoll equivalent is busy-waiting).
1880 int sock = srt_create_socket();
1883 memset(&addr, 0, sizeof(addr));
1884 addr.sin6_family = AF_INET6;
1885 addr.sin6_addr = IN6ADDR_LOOPBACK_INIT;
1886 addr.sin6_port = htons(global_flags.srt_port);
1887 srt_connect(sock, (sockaddr *)&addr, sizeof(addr));
1895 void Mixer::transition_clicked(int transition_num)
1897 theme->transition_clicked(transition_num, pts());
1900 void Mixer::channel_clicked(int preview_num)
1902 theme->channel_clicked(preview_num);
1905 YCbCrInterpretation Mixer::get_input_ycbcr_interpretation(unsigned card_index) const
1907 lock_guard<mutex> lock(card_mutex);
1908 return ycbcr_interpretation[card_index];
1911 void Mixer::set_input_ycbcr_interpretation(unsigned card_index, const YCbCrInterpretation &interpretation)
1913 lock_guard<mutex> lock(card_mutex);
1914 ycbcr_interpretation[card_index] = interpretation;
1917 void Mixer::start_mode_scanning(unsigned card_index)
1919 assert(card_index < MAX_VIDEO_CARDS);
1920 if (cards[card_index].capture == nullptr) {
1921 // Inactive card. Should never happen.
1924 if (is_mode_scanning[card_index]) {
1927 is_mode_scanning[card_index] = true;
1928 mode_scanlist[card_index].clear();
1929 for (const auto &mode : cards[card_index].capture->get_available_video_modes()) {
1930 mode_scanlist[card_index].push_back(mode.first);
1932 assert(!mode_scanlist[card_index].empty());
1933 mode_scanlist_index[card_index] = 0;
1934 cards[card_index].capture->set_video_mode(mode_scanlist[card_index][0]);
1935 last_mode_scan_change[card_index] = steady_clock::now();
1938 map<uint32_t, VideoMode> Mixer::get_available_output_video_modes() const
1940 assert(desired_output_card_index != -1);
1941 lock_guard<mutex> lock(card_mutex);
1942 return cards[desired_output_card_index].output->get_available_video_modes();
1945 string Mixer::get_ffmpeg_filename(unsigned card_index) const
1947 assert(card_index < MAX_VIDEO_CARDS);
1948 assert(cards[card_index].type == CardType::FFMPEG_INPUT);
1949 return ((FFmpegCapture *)(cards[card_index].capture.get()))->get_filename();
1952 void Mixer::set_ffmpeg_filename(unsigned card_index, const string &filename) {
1953 assert(card_index < MAX_VIDEO_CARDS);
1954 assert(cards[card_index].type == CardType::FFMPEG_INPUT);
1955 ((FFmpegCapture *)(cards[card_index].capture.get()))->change_filename(filename);
1958 void Mixer::wait_for_next_frame()
1960 unique_lock<mutex> lock(frame_num_mutex);
1961 unsigned old_frame_num = frame_num;
1962 frame_num_updated.wait_for(lock, seconds(1), // Timeout is just in case.
1963 [old_frame_num, this]{ return this->frame_num > old_frame_num; });
1966 Mixer::OutputChannel::~OutputChannel()
1968 if (has_current_frame) {
1969 parent->release_display_frame(¤t_frame);
1971 if (has_ready_frame) {
1972 parent->release_display_frame(&ready_frame);
1976 void Mixer::OutputChannel::output_frame(DisplayFrame &&frame)
1978 // Store this frame for display. Remove the ready frame if any
1979 // (it was seemingly never used).
1981 lock_guard<mutex> lock(frame_mutex);
1982 if (has_ready_frame) {
1983 parent->release_display_frame(&ready_frame);
1985 ready_frame = move(frame);
1986 has_ready_frame = true;
1988 // Call the callbacks under the mutex (they should be short),
1989 // so that we don't race against a callback removal.
1990 for (const auto &key_and_callback : new_frame_ready_callbacks) {
1991 key_and_callback.second();
1995 // Reduce the number of callbacks by filtering duplicates. The reason
1996 // why we bother doing this is that Qt seemingly can get into a state
1997 // where its builds up an essentially unbounded queue of signals,
1998 // consuming more and more memory, and there's no good way of collapsing
1999 // user-defined signals or limiting the length of the queue.
2000 if (transition_names_updated_callback) {
2001 vector<string> transition_names = global_mixer->get_transition_names();
2002 bool changed = false;
2003 if (transition_names.size() != last_transition_names.size()) {
2006 for (unsigned i = 0; i < transition_names.size(); ++i) {
2007 if (transition_names[i] != last_transition_names[i]) {
2014 transition_names_updated_callback(transition_names);
2015 last_transition_names = transition_names;
2018 if (name_updated_callback) {
2019 string name = global_mixer->get_channel_name(channel);
2020 if (name != last_name) {
2021 name_updated_callback(name);
2025 if (color_updated_callback) {
2026 string color = global_mixer->get_channel_color(channel);
2027 if (color != last_color) {
2028 color_updated_callback(color);
2034 bool Mixer::OutputChannel::get_display_frame(DisplayFrame *frame)
2036 lock_guard<mutex> lock(frame_mutex);
2037 if (!has_current_frame && !has_ready_frame) {
2041 if (has_current_frame && has_ready_frame) {
2042 // We have a new ready frame. Toss the current one.
2043 parent->release_display_frame(¤t_frame);
2044 has_current_frame = false;
2046 if (has_ready_frame) {
2047 assert(!has_current_frame);
2048 current_frame = move(ready_frame);
2049 ready_frame.ready_fence.reset(); // Drop the refcount.
2050 ready_frame.input_frames.clear(); // Drop the refcounts.
2051 has_current_frame = true;
2052 has_ready_frame = false;
2055 *frame = current_frame;
2059 void Mixer::OutputChannel::add_frame_ready_callback(void *key, Mixer::new_frame_ready_callback_t callback)
2061 lock_guard<mutex> lock(frame_mutex);
2062 new_frame_ready_callbacks[key] = callback;
2065 void Mixer::OutputChannel::remove_frame_ready_callback(void *key)
2067 lock_guard<mutex> lock(frame_mutex);
2068 new_frame_ready_callbacks.erase(key);
2071 void Mixer::OutputChannel::set_transition_names_updated_callback(Mixer::transition_names_updated_callback_t callback)
2073 transition_names_updated_callback = callback;
2076 void Mixer::OutputChannel::set_name_updated_callback(Mixer::name_updated_callback_t callback)
2078 name_updated_callback = callback;
2081 void Mixer::OutputChannel::set_color_updated_callback(Mixer::color_updated_callback_t callback)
2083 color_updated_callback = callback;
2087 void Mixer::start_srt()
2089 SRTSOCKET sock = srt_create_socket();
2091 memset(&addr, 0, sizeof(addr));
2092 addr.sin6_family = AF_INET6;
2093 addr.sin6_port = htons(global_flags.srt_port);
2096 int err = srt_setsockopt(sock, /*level=*/0, SRTO_IPV6ONLY, &zero, sizeof(zero));
2098 fprintf(stderr, "srt_setsockopt(SRTO_IPV6ONLY): %s\n", srt_getlasterror_str());
2101 err = srt_bind(sock, (sockaddr *)&addr, sizeof(addr));
2103 fprintf(stderr, "srt_bind: %s\n", srt_getlasterror_str());
2106 err = srt_listen(sock, MAX_VIDEO_CARDS);
2108 fprintf(stderr, "srt_listen: %s\n", srt_getlasterror_str());
2112 srt_thread = thread([this, sock] {
2115 int sa_len = sizeof(addr);
2116 int clientsock = srt_accept(sock, (sockaddr *)&addr, &sa_len);
2118 if (clientsock != -1) {
2119 srt_close(clientsock);
2123 if (!global_flags.enable_srt) { // Runtime UI toggle.
2124 // Perhaps not as good as never listening in the first place,
2125 // but much simpler to turn on and off.
2126 srt_close(clientsock);
2129 lock_guard<mutex> lock(hotplug_mutex);
2130 hotplugged_srt_cards.push_back(clientsock);
2137 string Mixer::description_for_card(unsigned card_index)
2139 CaptureCard *card = &cards[card_index];
2140 if (card->capture == nullptr) {
2141 // Should never be called for inactive cards, but OK.
2143 snprintf(buf, sizeof(buf), "Inactive capture card %u", card_index);
2146 if (card->type != CardType::FFMPEG_INPUT) {
2148 snprintf(buf, sizeof(buf), "Capture card %u (%s)", card_index, card->capture->get_description().c_str());
2152 // Number (non-SRT) FFmpeg inputs from zero, separately from the capture cards,
2153 // since it's not too obvious for the user that they are “cards”.
2154 unsigned ffmpeg_index = 0;
2155 for (unsigned i = 0; i < card_index; ++i) {
2156 CaptureCard *other_card = &cards[i];
2157 if (other_card->type == CardType::FFMPEG_INPUT && !is_srt_card(other_card)) {
2162 snprintf(buf, sizeof(buf), "Video input %u (%s)", ffmpeg_index, card->capture->get_description().c_str());
2166 bool Mixer::is_srt_card(const Mixer::CaptureCard *card)
2169 if (card->type == CardType::FFMPEG_INPUT) {
2170 int srt_sock = static_cast<FFmpegCapture *>(card->capture.get())->get_srt_sock();
2171 return srt_sock != -1;
2177 mutex RefCountedGLsync::fence_lock;