7 #include <movit/effect_chain.h>
8 #include <movit/effect_util.h>
9 #include <movit/flat_input.h>
10 #include <movit/image_format.h>
11 #include <movit/init.h>
12 #include <movit/resource_pool.h>
17 #include <sys/resource.h>
20 #include <condition_variable>
31 #include "DeckLinkAPI.h"
33 #include "alsa_output.h"
34 #include "bmusb/bmusb.h"
35 #include "bmusb/fake_capture.h"
36 #include "chroma_subsampler.h"
38 #include "decklink_capture.h"
39 #include "decklink_output.h"
41 #include "disk_space_estimator.h"
43 #include "input_mapping.h"
44 #include "pbo_frame_allocator.h"
45 #include "ref_counted_gl_sync.h"
46 #include "resampling_queue.h"
48 #include "timecode_renderer.h"
49 #include "v210_converter.h"
50 #include "video_encoder.h"
55 using namespace movit;
57 using namespace std::chrono;
58 using namespace std::placeholders;
59 using namespace bmusb;
61 Mixer *global_mixer = nullptr;
62 bool uses_mlock = false;
66 void insert_new_frame(RefCountedFrame frame, unsigned field_num, bool interlaced, unsigned card_index, InputState *input_state)
69 for (unsigned frame_num = FRAME_HISTORY_LENGTH; frame_num --> 1; ) { // :-)
70 input_state->buffered_frames[card_index][frame_num] =
71 input_state->buffered_frames[card_index][frame_num - 1];
73 input_state->buffered_frames[card_index][0] = { frame, field_num };
75 for (unsigned frame_num = 0; frame_num < FRAME_HISTORY_LENGTH; ++frame_num) {
76 input_state->buffered_frames[card_index][frame_num] = { frame, field_num };
81 void ensure_texture_resolution(PBOFrameAllocator::Userdata *userdata, unsigned field, unsigned width, unsigned height, unsigned v210_width)
84 if (global_flags.ten_bit_input) {
85 first = userdata->tex_v210[field] == 0 || userdata->tex_444[field] == 0;
87 first = userdata->tex_y[field] == 0 || userdata->tex_cbcr[field] == 0;
91 width != userdata->last_width[field] ||
92 height != userdata->last_height[field]) {
93 // We changed resolution since last use of this texture, so we need to create
94 // a new object. Note that this each card has its own PBOFrameAllocator,
95 // we don't need to worry about these flip-flopping between resolutions.
96 if (global_flags.ten_bit_input) {
97 glBindTexture(GL_TEXTURE_2D, userdata->tex_444[field]);
99 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB10_A2, width, height, 0, GL_RGBA, GL_UNSIGNED_INT_2_10_10_10_REV, nullptr);
102 size_t cbcr_width = width / 2;
104 glBindTexture(GL_TEXTURE_2D, userdata->tex_cbcr[field]);
106 glTexImage2D(GL_TEXTURE_2D, 0, GL_RG8, cbcr_width, height, 0, GL_RG, GL_UNSIGNED_BYTE, nullptr);
108 glBindTexture(GL_TEXTURE_2D, userdata->tex_y[field]);
110 glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, width, height, 0, GL_RED, GL_UNSIGNED_BYTE, nullptr);
113 userdata->last_width[field] = width;
114 userdata->last_height[field] = height;
116 if (global_flags.ten_bit_input &&
117 (first || v210_width != userdata->last_v210_width[field])) {
118 // Same as above; we need to recreate the texture.
119 glBindTexture(GL_TEXTURE_2D, userdata->tex_v210[field]);
121 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB10_A2, v210_width, height, 0, GL_RGBA, GL_UNSIGNED_INT_2_10_10_10_REV, nullptr);
123 userdata->last_v210_width[field] = v210_width;
127 void upload_texture(GLuint tex, GLuint width, GLuint height, GLuint stride, bool interlaced_stride, GLenum format, GLenum type, GLintptr offset)
129 if (interlaced_stride) {
132 if (global_flags.flush_pbos) {
133 glFlushMappedBufferRange(GL_PIXEL_UNPACK_BUFFER, offset, stride * height);
137 glBindTexture(GL_TEXTURE_2D, tex);
139 if (interlaced_stride) {
140 glPixelStorei(GL_UNPACK_ROW_LENGTH, width * 2);
143 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
147 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, format, type, BUFFER_OFFSET(offset));
149 glBindTexture(GL_TEXTURE_2D, 0);
151 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
157 void QueueLengthPolicy::update_policy(unsigned queue_length)
159 if (queue_length == 0) { // Starvation.
160 if (been_at_safe_point_since_last_starvation && safe_queue_length < unsigned(global_flags.max_input_queue_frames)) {
162 fprintf(stderr, "Card %u: Starvation, increasing safe limit to %u frame(s)\n",
163 card_index, safe_queue_length);
165 frames_with_at_least_one = 0;
166 been_at_safe_point_since_last_starvation = false;
169 if (queue_length >= safe_queue_length) {
170 been_at_safe_point_since_last_starvation = true;
172 if (++frames_with_at_least_one >= 1000 && safe_queue_length > 1) {
174 fprintf(stderr, "Card %u: Spare frames for more than 1000 frames, reducing safe limit to %u frame(s)\n",
175 card_index, safe_queue_length);
176 frames_with_at_least_one = 0;
180 Mixer::Mixer(const QSurfaceFormat &format, unsigned num_cards)
182 num_cards(num_cards),
183 mixer_surface(create_surface(format)),
184 h264_encoder_surface(create_surface(format)),
185 decklink_output_surface(create_surface(format)),
186 audio_mixer(num_cards)
188 CHECK(init_movit(MOVIT_SHADER_DIR, MOVIT_DEBUG_OFF));
191 // Since we allow non-bouncing 4:2:2 YCbCrInputs, effective subpixel precision
192 // will be halved when sampling them, and we need to compensate here.
193 movit_texel_subpixel_precision /= 2.0;
195 resource_pool.reset(new ResourcePool);
196 theme.reset(new Theme(global_flags.theme_filename, global_flags.theme_dirs, resource_pool.get(), num_cards));
197 for (unsigned i = 0; i < NUM_OUTPUTS; ++i) {
198 output_channel[i].parent = this;
199 output_channel[i].channel = i;
202 ImageFormat inout_format;
203 inout_format.color_space = COLORSPACE_sRGB;
204 inout_format.gamma_curve = GAMMA_sRGB;
206 // Display chain; shows the live output produced by the main chain (its RGBA version).
207 display_chain.reset(new EffectChain(global_flags.width, global_flags.height, resource_pool.get()));
209 display_input = new FlatInput(inout_format, FORMAT_RGB, GL_UNSIGNED_BYTE, global_flags.width, global_flags.height); // FIXME: GL_UNSIGNED_BYTE is really wrong.
210 display_chain->add_input(display_input);
211 display_chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
212 display_chain->set_dither_bits(0); // Don't bother.
213 display_chain->finalize();
215 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));
217 // Start listening for clients only once VideoEncoder has written its header, if any.
220 // First try initializing the then PCI devices, then USB, then
221 // fill up with fake cards until we have the desired number of cards.
222 unsigned num_pci_devices = 0;
223 unsigned card_index = 0;
226 IDeckLinkIterator *decklink_iterator = CreateDeckLinkIteratorInstance();
227 if (decklink_iterator != nullptr) {
228 for ( ; card_index < num_cards; ++card_index) {
230 if (decklink_iterator->Next(&decklink) != S_OK) {
234 DeckLinkCapture *capture = new DeckLinkCapture(decklink, card_index);
235 DeckLinkOutput *output = new DeckLinkOutput(resource_pool.get(), decklink_output_surface, global_flags.width, global_flags.height, card_index);
236 output->set_device(decklink);
237 configure_card(card_index, capture, /*is_fake_capture=*/false, output);
240 decklink_iterator->Release();
241 fprintf(stderr, "Found %u DeckLink PCI card(s).\n", num_pci_devices);
243 fprintf(stderr, "DeckLink drivers not found. Probing for USB cards only.\n");
247 unsigned num_usb_devices = BMUSBCapture::num_cards();
248 for (unsigned usb_card_index = 0; usb_card_index < num_usb_devices && card_index < num_cards; ++usb_card_index, ++card_index) {
249 BMUSBCapture *capture = new BMUSBCapture(usb_card_index);
250 capture->set_card_disconnected_callback(bind(&Mixer::bm_hotplug_remove, this, card_index));
251 configure_card(card_index, capture, /*is_fake_capture=*/false, /*output=*/nullptr);
253 fprintf(stderr, "Found %u USB card(s).\n", num_usb_devices);
255 unsigned num_fake_cards = 0;
256 for ( ; card_index < num_cards; ++card_index, ++num_fake_cards) {
257 FakeCapture *capture = new FakeCapture(global_flags.width, global_flags.height, FAKE_FPS, OUTPUT_FREQUENCY, card_index, global_flags.fake_cards_audio);
258 configure_card(card_index, capture, /*is_fake_capture=*/true, /*output=*/nullptr);
261 if (num_fake_cards > 0) {
262 fprintf(stderr, "Initialized %u fake cards.\n", num_fake_cards);
265 BMUSBCapture::set_card_connected_callback(bind(&Mixer::bm_hotplug_add, this, _1));
266 BMUSBCapture::start_bm_thread();
268 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
269 cards[card_index].queue_length_policy.reset(card_index);
272 chroma_subsampler.reset(new ChromaSubsampler(resource_pool.get()));
274 if (global_flags.ten_bit_input) {
275 if (!v210Converter::has_hardware_support()) {
276 fprintf(stderr, "ERROR: --ten-bit-input requires support for OpenGL compute shaders\n");
277 fprintf(stderr, " (OpenGL 4.3, or GL_ARB_compute_shader + GL_ARB_shader_image_load_store).\n");
280 v210_converter.reset(new v210Converter());
282 // These are all the widths listed in the Blackmagic SDK documentation
283 // (section 2.7.3, “Display Modes”).
284 v210_converter->precompile_shader(720);
285 v210_converter->precompile_shader(1280);
286 v210_converter->precompile_shader(1920);
287 v210_converter->precompile_shader(2048);
288 v210_converter->precompile_shader(3840);
289 v210_converter->precompile_shader(4096);
292 timecode_renderer.reset(new TimecodeRenderer(resource_pool.get(), global_flags.width, global_flags.height));
293 display_timecode_in_stream = global_flags.display_timecode_in_stream;
294 display_timecode_on_stdout = global_flags.display_timecode_on_stdout;
296 if (global_flags.enable_alsa_output) {
297 alsa.reset(new ALSAOutput(OUTPUT_FREQUENCY, /*num_channels=*/2));
299 if (global_flags.output_card != -1) {
300 desired_output_card_index = global_flags.output_card;
301 set_output_card_internal(global_flags.output_card);
307 BMUSBCapture::stop_bm_thread();
309 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
311 unique_lock<mutex> lock(card_mutex);
312 cards[card_index].should_quit = true; // Unblock thread.
313 cards[card_index].new_frames_changed.notify_all();
315 cards[card_index].capture->stop_dequeue_thread();
316 if (cards[card_index].output) {
317 cards[card_index].output->end_output();
318 cards[card_index].output.reset();
322 video_encoder.reset(nullptr);
325 void Mixer::configure_card(unsigned card_index, CaptureInterface *capture, bool is_fake_capture, DeckLinkOutput *output)
327 printf("Configuring card %d...\n", card_index);
329 CaptureCard *card = &cards[card_index];
330 if (card->capture != nullptr) {
331 card->capture->stop_dequeue_thread();
333 card->capture.reset(capture);
334 card->is_fake_capture = is_fake_capture;
335 if (card->output.get() != output) {
336 card->output.reset(output);
338 card->capture->set_frame_callback(bind(&Mixer::bm_frame, this, card_index, _1, _2, _3, _4, _5, _6, _7));
339 if (card->frame_allocator == nullptr) {
340 card->frame_allocator.reset(new PBOFrameAllocator(8 << 20, global_flags.width, global_flags.height)); // 8 MB.
342 card->capture->set_video_frame_allocator(card->frame_allocator.get());
343 if (card->surface == nullptr) {
344 card->surface = create_surface_with_same_format(mixer_surface);
346 while (!card->new_frames.empty()) card->new_frames.pop_front();
347 card->last_timecode = -1;
348 card->capture->set_pixel_format(global_flags.ten_bit_input ? PixelFormat_10BitYCbCr : PixelFormat_8BitYCbCr);
349 card->capture->configure_card();
351 // NOTE: start_bm_capture() happens in thread_func().
353 DeviceSpec device{InputSourceType::CAPTURE_CARD, card_index};
354 audio_mixer.reset_resampler(device);
355 audio_mixer.set_display_name(device, card->capture->get_description());
356 audio_mixer.trigger_state_changed_callback();
359 void Mixer::set_output_card_internal(int card_index)
361 // We don't really need to take card_mutex, since we're in the mixer
362 // thread and don't mess with any queues (which is the only thing that happens
363 // from other threads), but it's probably the safest in the long run.
364 unique_lock<mutex> lock(card_mutex);
365 if (output_card_index != -1) {
366 // Switch the old card from output to input.
367 CaptureCard *old_card = &cards[output_card_index];
368 old_card->output->end_output();
370 // Stop the fake card that we put into place.
371 // This needs to _not_ happen under the mutex, to avoid deadlock
372 // (delivering the last frame needs to take the mutex).
373 bmusb::CaptureInterface *fake_capture = old_card->capture.get();
375 fake_capture->stop_dequeue_thread();
377 old_card->capture = move(old_card->parked_capture);
378 old_card->is_fake_capture = false;
379 old_card->capture->start_bm_capture();
381 if (card_index != -1) {
382 CaptureCard *card = &cards[card_index];
383 bmusb::CaptureInterface *capture = card->capture.get();
384 // TODO: DeckLinkCapture::stop_dequeue_thread can actually take
385 // several seconds to complete (blocking on DisableVideoInput);
386 // see if we can maybe do it asynchronously.
388 capture->stop_dequeue_thread();
390 card->parked_capture = move(card->capture);
391 bmusb::CaptureInterface *fake_capture = new FakeCapture(global_flags.width, global_flags.height, FAKE_FPS, OUTPUT_FREQUENCY, card_index, global_flags.fake_cards_audio);
392 configure_card(card_index, fake_capture, /*is_fake_capture=*/true, card->output.release());
393 card->queue_length_policy.reset(card_index);
394 card->capture->start_bm_capture();
395 desired_output_video_mode = output_video_mode = card->output->pick_video_mode(desired_output_video_mode);
396 card->output->start_output(desired_output_video_mode, pts_int);
398 output_card_index = card_index;
403 int unwrap_timecode(uint16_t current_wrapped, int last)
405 uint16_t last_wrapped = last & 0xffff;
406 if (current_wrapped > last_wrapped) {
407 return (last & ~0xffff) | current_wrapped;
409 return 0x10000 + ((last & ~0xffff) | current_wrapped);
415 void Mixer::bm_frame(unsigned card_index, uint16_t timecode,
416 FrameAllocator::Frame video_frame, size_t video_offset, VideoFormat video_format,
417 FrameAllocator::Frame audio_frame, size_t audio_offset, AudioFormat audio_format)
419 DeviceSpec device{InputSourceType::CAPTURE_CARD, card_index};
420 CaptureCard *card = &cards[card_index];
422 if (is_mode_scanning[card_index]) {
423 if (video_format.has_signal) {
424 // Found a stable signal, so stop scanning.
425 is_mode_scanning[card_index] = false;
427 static constexpr double switch_time_s = 0.1; // Should be enough time for the signal to stabilize.
428 steady_clock::time_point now = steady_clock::now();
429 double sec_since_last_switch = duration<double>(steady_clock::now() - last_mode_scan_change[card_index]).count();
430 if (sec_since_last_switch > switch_time_s) {
431 // It isn't this mode; try the next one.
432 mode_scanlist_index[card_index]++;
433 mode_scanlist_index[card_index] %= mode_scanlist[card_index].size();
434 cards[card_index].capture->set_video_mode(mode_scanlist[card_index][mode_scanlist_index[card_index]]);
435 last_mode_scan_change[card_index] = now;
440 int64_t frame_length = int64_t(TIMEBASE) * video_format.frame_rate_den / video_format.frame_rate_nom;
441 assert(frame_length > 0);
443 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;
444 if (num_samples > OUTPUT_FREQUENCY / 10) {
445 printf("Card %d: Dropping frame with implausible audio length (len=%d, offset=%d) [timecode=0x%04x video_len=%d video_offset=%d video_format=%x)\n",
446 card_index, int(audio_frame.len), int(audio_offset),
447 timecode, int(video_frame.len), int(video_offset), video_format.id);
448 if (video_frame.owner) {
449 video_frame.owner->release_frame(video_frame);
451 if (audio_frame.owner) {
452 audio_frame.owner->release_frame(audio_frame);
457 int dropped_frames = 0;
458 if (card->last_timecode != -1) {
459 dropped_frames = unwrap_timecode(timecode, card->last_timecode) - card->last_timecode - 1;
462 // Number of samples per frame if we need to insert silence.
463 // (Could be nonintegral, but resampling will save us then.)
464 const int silence_samples = OUTPUT_FREQUENCY * video_format.frame_rate_den / video_format.frame_rate_nom;
466 if (dropped_frames > MAX_FPS * 2) {
467 fprintf(stderr, "Card %d lost more than two seconds (or time code jumping around; from 0x%04x to 0x%04x), resetting resampler\n",
468 card_index, card->last_timecode, timecode);
469 audio_mixer.reset_resampler(device);
471 } else if (dropped_frames > 0) {
472 // Insert silence as needed.
473 fprintf(stderr, "Card %d dropped %d frame(s) (before timecode 0x%04x), inserting silence.\n",
474 card_index, dropped_frames, timecode);
478 success = audio_mixer.add_silence(device, silence_samples, dropped_frames, frame_length);
482 audio_mixer.add_audio(device, audio_frame.data + audio_offset, num_samples, audio_format, frame_length, audio_frame.received_timestamp);
484 // Done with the audio, so release it.
485 if (audio_frame.owner) {
486 audio_frame.owner->release_frame(audio_frame);
489 card->last_timecode = timecode;
491 size_t expected_length = video_format.stride * (video_format.height + video_format.extra_lines_top + video_format.extra_lines_bottom);
492 if (video_frame.len - video_offset == 0 ||
493 video_frame.len - video_offset != expected_length) {
494 if (video_frame.len != 0) {
495 printf("Card %d: Dropping video frame with wrong length (%ld; expected %ld)\n",
496 card_index, video_frame.len - video_offset, expected_length);
498 if (video_frame.owner) {
499 video_frame.owner->release_frame(video_frame);
502 // Still send on the information that we _had_ a frame, even though it's corrupted,
503 // so that pts can go up accordingly.
505 unique_lock<mutex> lock(card_mutex);
506 CaptureCard::NewFrame new_frame;
507 new_frame.frame = RefCountedFrame(FrameAllocator::Frame());
508 new_frame.length = frame_length;
509 new_frame.interlaced = false;
510 new_frame.dropped_frames = dropped_frames;
511 new_frame.received_timestamp = video_frame.received_timestamp;
512 card->new_frames.push_back(move(new_frame));
513 card->new_frames_changed.notify_all();
518 PBOFrameAllocator::Userdata *userdata = (PBOFrameAllocator::Userdata *)video_frame.userdata;
520 unsigned num_fields = video_format.interlaced ? 2 : 1;
521 steady_clock::time_point frame_upload_start;
522 bool interlaced_stride = false;
523 if (video_format.interlaced) {
524 // Send the two fields along as separate frames; the other side will need to add
525 // a deinterlacer to actually get this right.
526 assert(video_format.height % 2 == 0);
527 video_format.height /= 2;
528 assert(frame_length % 2 == 0);
531 if (video_format.second_field_start == 1) {
532 interlaced_stride = true;
534 frame_upload_start = steady_clock::now();
536 userdata->last_interlaced = video_format.interlaced;
537 userdata->last_has_signal = video_format.has_signal;
538 userdata->last_is_connected = video_format.is_connected;
539 userdata->last_frame_rate_nom = video_format.frame_rate_nom;
540 userdata->last_frame_rate_den = video_format.frame_rate_den;
541 RefCountedFrame frame(video_frame);
543 // Upload the textures.
544 const size_t cbcr_width = video_format.width / 2;
545 const size_t cbcr_offset = video_offset / 2;
546 const size_t y_offset = video_frame.size / 2 + video_offset / 2;
548 for (unsigned field = 0; field < num_fields; ++field) {
549 // Put the actual texture upload in a lambda that is executed in the main thread.
550 // It is entirely possible to do this in the same thread (and it might even be
551 // faster, depending on the GPU and driver), but it appears to be trickling
552 // driver bugs very easily.
554 // Note that this means we must hold on to the actual frame data in <userdata>
555 // until the upload command is run, but we hold on to <frame> much longer than that
556 // (in fact, all the way until we no longer use the texture in rendering).
557 auto upload_func = [this, field, video_format, y_offset, video_offset, cbcr_offset, cbcr_width, interlaced_stride, userdata]() {
558 unsigned field_start_line;
560 field_start_line = video_format.second_field_start;
562 field_start_line = video_format.extra_lines_top;
565 // For 8-bit input, v210_width will be nonsensical but not used.
566 size_t v210_width = video_format.stride / sizeof(uint32_t);
567 ensure_texture_resolution(userdata, field, video_format.width, video_format.height, v210_width);
569 glBindBuffer(GL_PIXEL_UNPACK_BUFFER, userdata->pbo);
572 if (global_flags.ten_bit_input) {
573 size_t field_start = video_offset + video_format.stride * field_start_line;
574 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);
575 v210_converter->convert(userdata->tex_v210[field], userdata->tex_444[field], video_format.width, video_format.height);
577 size_t field_y_start = y_offset + video_format.width * field_start_line;
578 size_t field_cbcr_start = cbcr_offset + cbcr_width * field_start_line * sizeof(uint16_t);
580 // Make up our own strides, since we are interleaving.
581 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);
582 upload_texture(userdata->tex_cbcr[field], cbcr_width, video_format.height, cbcr_width * sizeof(uint16_t), interlaced_stride, GL_RG, GL_UNSIGNED_BYTE, field_cbcr_start);
585 glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
590 // Don't upload the second field as fast as we can; wait until
591 // the field time has approximately passed. (Otherwise, we could
592 // get timing jitter against the other sources, and possibly also
593 // against the video display, although the latter is not as critical.)
594 // This requires our system clock to be reasonably close to the
595 // video clock, but that's not an unreasonable assumption.
596 steady_clock::time_point second_field_start = frame_upload_start +
597 nanoseconds(frame_length * 1000000000 / TIMEBASE);
598 this_thread::sleep_until(second_field_start);
602 unique_lock<mutex> lock(card_mutex);
603 CaptureCard::NewFrame new_frame;
604 new_frame.frame = frame;
605 new_frame.length = frame_length;
606 new_frame.field = field;
607 new_frame.interlaced = video_format.interlaced;
608 new_frame.upload_func = upload_func;
609 new_frame.dropped_frames = dropped_frames;
610 new_frame.received_timestamp = video_frame.received_timestamp; // Ignore the audio timestamp.
611 card->new_frames.push_back(move(new_frame));
612 card->new_frames_changed.notify_all();
617 void Mixer::bm_hotplug_add(libusb_device *dev)
619 lock_guard<mutex> lock(hotplug_mutex);
620 hotplugged_cards.push_back(dev);
623 void Mixer::bm_hotplug_remove(unsigned card_index)
625 cards[card_index].new_frames_changed.notify_all();
628 void Mixer::thread_func()
630 pthread_setname_np(pthread_self(), "Mixer_OpenGL");
632 eglBindAPI(EGL_OPENGL_API);
633 QOpenGLContext *context = create_context(mixer_surface);
634 if (!make_current(context, mixer_surface)) {
639 // Start the actual capture. (We don't want to do it before we're actually ready
640 // to process output frames.)
641 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
642 if (int(card_index) != output_card_index) {
643 cards[card_index].capture->start_bm_capture();
647 steady_clock::time_point start, now;
648 start = steady_clock::now();
650 int stats_dropped_frames = 0;
652 while (!should_quit) {
653 if (desired_output_card_index != output_card_index) {
654 set_output_card_internal(desired_output_card_index);
656 if (output_card_index != -1 &&
657 desired_output_video_mode != output_video_mode) {
658 DeckLinkOutput *output = cards[output_card_index].output.get();
659 output->end_output();
660 desired_output_video_mode = output_video_mode = output->pick_video_mode(desired_output_video_mode);
661 output->start_output(desired_output_video_mode, pts_int);
664 CaptureCard::NewFrame new_frames[MAX_VIDEO_CARDS];
665 bool has_new_frame[MAX_VIDEO_CARDS] = { false };
667 bool master_card_is_output;
668 unsigned master_card_index;
669 if (output_card_index != -1) {
670 master_card_is_output = true;
671 master_card_index = output_card_index;
673 master_card_is_output = false;
674 master_card_index = theme->map_signal(master_clock_channel);
675 assert(master_card_index < num_cards);
678 OutputFrameInfo output_frame_info = get_one_frame_from_each_card(master_card_index, master_card_is_output, new_frames, has_new_frame);
679 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);
680 stats_dropped_frames += output_frame_info.dropped_frames;
682 handle_hotplugged_cards();
684 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
685 if (card_index == master_card_index || !has_new_frame[card_index]) {
688 if (new_frames[card_index].frame->len == 0) {
689 ++new_frames[card_index].dropped_frames;
691 if (new_frames[card_index].dropped_frames > 0) {
692 printf("Card %u dropped %d frames before this\n",
693 card_index, int(new_frames[card_index].dropped_frames));
697 // If the first card is reporting a corrupted or otherwise dropped frame,
698 // just increase the pts (skipping over this frame) and don't try to compute anything new.
699 if (!master_card_is_output && new_frames[master_card_index].frame->len == 0) {
700 ++stats_dropped_frames;
701 pts_int += new_frames[master_card_index].length;
705 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
706 if (!has_new_frame[card_index] || new_frames[card_index].frame->len == 0)
709 CaptureCard::NewFrame *new_frame = &new_frames[card_index];
710 assert(new_frame->frame != nullptr);
711 insert_new_frame(new_frame->frame, new_frame->field, new_frame->interlaced, card_index, &input_state);
714 // The new texture might need uploading before use.
715 if (new_frame->upload_func) {
716 new_frame->upload_func();
717 new_frame->upload_func = nullptr;
721 int64_t frame_duration = output_frame_info.frame_duration;
722 render_one_frame(frame_duration);
724 pts_int += frame_duration;
726 now = steady_clock::now();
727 double elapsed = duration<double>(now - start).count();
728 if (frame_num % 100 == 0) {
729 printf("%d frames (%d dropped) in %.3f seconds = %.1f fps (%.1f ms/frame)",
730 frame_num, stats_dropped_frames, elapsed, frame_num / elapsed,
731 1e3 * elapsed / frame_num);
732 // chain->print_phase_timing();
734 // Check our memory usage, to see if we are close to our mlockall()
735 // limit (if at all set).
737 if (getrusage(RUSAGE_SELF, &used) == -1) {
738 perror("getrusage(RUSAGE_SELF)");
744 if (getrlimit(RLIMIT_MEMLOCK, &limit) == -1) {
745 perror("getrlimit(RLIMIT_MEMLOCK)");
749 if (limit.rlim_cur == 0) {
750 printf(", using %ld MB memory (locked)",
751 long(used.ru_maxrss / 1024));
753 printf(", using %ld / %ld MB lockable memory (%.1f%%)",
754 long(used.ru_maxrss / 1024),
755 long(limit.rlim_cur / 1048576),
756 float(100.0 * (used.ru_maxrss * 1024.0) / limit.rlim_cur));
759 printf(", using %ld MB memory (not locked)",
760 long(used.ru_maxrss / 1024));
767 if (should_cut.exchange(false)) { // Test and clear.
768 video_encoder->do_cut(frame_num);
772 // Reset every 100 frames, so that local variations in frame times
773 // (especially for the first few frames, when the shaders are
774 // compiled etc.) don't make it hard to measure for the entire
775 // remaining duration of the program.
776 if (frame == 10000) {
784 resource_pool->clean_context();
787 bool Mixer::input_card_is_master_clock(unsigned card_index, unsigned master_card_index) const
789 if (output_card_index != -1) {
790 // The output card (ie., cards[output_card_index].output) is the master clock,
791 // so no input card (ie., cards[card_index].capture) is.
794 return (card_index == master_card_index);
797 void Mixer::trim_queue(CaptureCard *card, unsigned card_index)
799 // Count the number of frames in the queue, including any frames
800 // we dropped. It's hard to know exactly how we should deal with
801 // dropped (corrupted) input frames; they don't help our goal of
802 // avoiding starvation, but they still add to the problem of latency.
803 // Since dropped frames is going to mean a bump in the signal anyway,
804 // we err on the side of having more stable latency instead.
805 unsigned queue_length = 0;
806 for (const CaptureCard::NewFrame &frame : card->new_frames) {
807 queue_length += frame.dropped_frames + 1;
809 card->queue_length_policy.update_policy(queue_length);
811 // If needed, drop frames until the queue is below the safe limit.
812 // We prefer to drop from the head, because all else being equal,
813 // we'd like more recent frames (less latency).
814 unsigned dropped_frames = 0;
815 while (queue_length > card->queue_length_policy.get_safe_queue_length()) {
816 assert(!card->new_frames.empty());
817 assert(queue_length > card->new_frames.front().dropped_frames);
818 queue_length -= card->new_frames.front().dropped_frames;
820 if (queue_length <= card->queue_length_policy.get_safe_queue_length()) {
821 // No need to drop anything.
825 card->new_frames.pop_front();
826 card->new_frames_changed.notify_all();
831 if (dropped_frames > 0) {
832 fprintf(stderr, "Card %u dropped %u frame(s) to keep latency down.\n",
833 card_index, dropped_frames);
838 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])
840 OutputFrameInfo output_frame_info;
842 unique_lock<mutex> lock(card_mutex, defer_lock);
843 if (master_card_is_output) {
844 // Clocked to the output, so wait for it to be ready for the next frame.
845 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);
848 // Wait for the master card to have a new frame.
849 // TODO: Add a timeout.
850 output_frame_info.is_preroll = false;
852 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(); });
855 if (master_card_is_output) {
856 handle_hotplugged_cards();
857 } else if (cards[master_card_index].new_frames.empty()) {
858 // We were woken up, but not due to a new frame. Deal with it
860 assert(cards[master_card_index].capture->get_disconnected());
861 handle_hotplugged_cards();
865 if (!master_card_is_output) {
866 output_frame_info.frame_timestamp =
867 cards[master_card_index].new_frames.front().received_timestamp;
870 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
871 CaptureCard *card = &cards[card_index];
872 if (input_card_is_master_clock(card_index, master_card_index)) {
873 // We don't use the queue length policy for the master card,
874 // but we will if it stops being the master. Thus, clear out
875 // the policy in case we switch in the future.
876 card->queue_length_policy.reset(card_index);
877 assert(!card->new_frames.empty());
879 trim_queue(card, card_index);
881 if (!card->new_frames.empty()) {
882 new_frames[card_index] = move(card->new_frames.front());
883 has_new_frame[card_index] = true;
884 card->new_frames.pop_front();
885 card->new_frames_changed.notify_all();
889 if (!master_card_is_output) {
890 output_frame_info.dropped_frames = new_frames[master_card_index].dropped_frames;
891 output_frame_info.frame_duration = new_frames[master_card_index].length;
894 // This might get off by a fractional sample when changing master card
895 // between ones with different frame rates, but that's fine.
896 int num_samples_times_timebase = OUTPUT_FREQUENCY * output_frame_info.frame_duration + fractional_samples;
897 output_frame_info.num_samples = num_samples_times_timebase / TIMEBASE;
898 fractional_samples = num_samples_times_timebase % TIMEBASE;
899 assert(output_frame_info.num_samples >= 0);
901 return output_frame_info;
904 void Mixer::handle_hotplugged_cards()
906 // Check for cards that have been disconnected since last frame.
907 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
908 CaptureCard *card = &cards[card_index];
909 if (card->capture->get_disconnected()) {
910 fprintf(stderr, "Card %u went away, replacing with a fake card.\n", card_index);
911 FakeCapture *capture = new FakeCapture(global_flags.width, global_flags.height, FAKE_FPS, OUTPUT_FREQUENCY, card_index, global_flags.fake_cards_audio);
912 configure_card(card_index, capture, /*is_fake_capture=*/true, /*output=*/nullptr);
913 card->queue_length_policy.reset(card_index);
914 card->capture->start_bm_capture();
918 // Check for cards that have been connected since last frame.
919 vector<libusb_device *> hotplugged_cards_copy;
921 lock_guard<mutex> lock(hotplug_mutex);
922 swap(hotplugged_cards, hotplugged_cards_copy);
924 for (libusb_device *new_dev : hotplugged_cards_copy) {
925 // Look for a fake capture card where we can stick this in.
926 int free_card_index = -1;
927 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
928 if (cards[card_index].is_fake_capture) {
929 free_card_index = card_index;
934 if (free_card_index == -1) {
935 fprintf(stderr, "New card plugged in, but no free slots -- ignoring.\n");
936 libusb_unref_device(new_dev);
938 // BMUSBCapture takes ownership.
939 fprintf(stderr, "New card plugged in, choosing slot %d.\n", free_card_index);
940 CaptureCard *card = &cards[free_card_index];
941 BMUSBCapture *capture = new BMUSBCapture(free_card_index, new_dev);
942 configure_card(free_card_index, capture, /*is_fake_capture=*/false, /*output=*/nullptr);
943 card->queue_length_policy.reset(free_card_index);
944 capture->set_card_disconnected_callback(bind(&Mixer::bm_hotplug_remove, this, free_card_index));
945 capture->start_bm_capture();
951 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)
953 // Resample the audio as needed, including from previously dropped frames.
954 assert(num_cards > 0);
955 for (unsigned frame_num = 0; frame_num < dropped_frames + 1; ++frame_num) {
956 const bool dropped_frame = (frame_num != dropped_frames);
958 // Signal to the audio thread to process this frame.
959 // Note that if the frame is a dropped frame, we signal that
960 // we don't want to use this frame as base for adjusting
961 // the resampler rate. The reason for this is that the timing
962 // of these frames is often way too late; they typically don't
963 // “arrive” before we synthesize them. Thus, we could end up
964 // in a situation where we have inserted e.g. five audio frames
965 // into the queue before we then start pulling five of them
966 // back out. This makes ResamplingQueue overestimate the delay,
967 // causing undue resampler changes. (We _do_ use the last,
968 // non-dropped frame; perhaps we should just discard that as well,
969 // since dropped frames are expected to be rare, and it might be
970 // better to just wait until we have a slightly more normal situation).
971 unique_lock<mutex> lock(audio_mutex);
972 bool adjust_rate = !dropped_frame && !is_preroll;
973 audio_task_queue.push(AudioTask{pts_int, num_samples_per_frame, adjust_rate, frame_timestamp});
974 audio_task_queue_changed.notify_one();
977 // For dropped frames, increase the pts. Note that if the format changed
978 // in the meantime, we have no way of detecting that; we just have to
979 // assume the frame length is always the same.
980 pts_int += length_per_frame;
985 void Mixer::render_one_frame(int64_t duration)
987 // Determine the time code for this frame before we start rendering.
988 string timecode_text = timecode_renderer->get_timecode_text(double(pts_int) / TIMEBASE, frame_num);
989 if (display_timecode_on_stdout) {
990 printf("Timecode: '%s'\n", timecode_text.c_str());
993 // Get the main chain from the theme, and set its state immediately.
994 Theme::Chain theme_main_chain = theme->get_chain(0, pts(), global_flags.width, global_flags.height, input_state);
995 EffectChain *chain = theme_main_chain.chain;
996 theme_main_chain.setup_chain();
997 //theme_main_chain.chain->enable_phase_timing(true);
999 const int64_t av_delay = lrint(global_flags.audio_queue_length_ms * 0.001 * TIMEBASE); // Corresponds to the delay in ResamplingQueue.
1000 GLuint y_tex, cbcr_tex;
1001 bool got_frame = video_encoder->begin_frame(pts_int + av_delay, duration, theme_main_chain.input_frames, &y_tex, &cbcr_tex);
1004 // Render main chain.
1005 GLuint cbcr_full_tex = resource_pool->create_2d_texture(GL_RG8, global_flags.width, global_flags.height);
1006 GLuint rgba_tex = resource_pool->create_2d_texture(GL_RGB565, global_flags.width, global_flags.height); // Saves texture bandwidth, although dithering gets messed up.
1007 GLuint fbo = resource_pool->create_fbo(y_tex, cbcr_full_tex, rgba_tex);
1009 chain->render_to_fbo(fbo, global_flags.width, global_flags.height);
1011 if (display_timecode_in_stream) {
1012 // Render the timecode on top.
1013 timecode_renderer->render_timecode(fbo, timecode_text);
1016 resource_pool->release_fbo(fbo);
1018 chroma_subsampler->subsample_chroma(cbcr_full_tex, global_flags.width, global_flags.height, cbcr_tex);
1019 if (output_card_index != -1) {
1020 cards[output_card_index].output->send_frame(y_tex, cbcr_full_tex, theme_main_chain.input_frames, pts_int, duration);
1022 resource_pool->release_2d_texture(cbcr_full_tex);
1024 // Set the right state for rgba_tex.
1025 glBindFramebuffer(GL_FRAMEBUFFER, 0);
1026 glBindTexture(GL_TEXTURE_2D, rgba_tex);
1027 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1028 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1029 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1031 RefCountedGLsync fence = video_encoder->end_frame();
1033 // The live frame just shows the RGBA texture we just rendered.
1034 // It owns rgba_tex now.
1035 DisplayFrame live_frame;
1036 live_frame.chain = display_chain.get();
1037 live_frame.setup_chain = [this, rgba_tex]{
1038 display_input->set_texture_num(rgba_tex);
1040 live_frame.ready_fence = fence;
1041 live_frame.input_frames = {};
1042 live_frame.temp_textures = { rgba_tex };
1043 output_channel[OUTPUT_LIVE].output_frame(live_frame);
1045 // Set up preview and any additional channels.
1046 for (int i = 1; i < theme->get_num_channels() + 2; ++i) {
1047 DisplayFrame display_frame;
1048 Theme::Chain chain = theme->get_chain(i, pts(), global_flags.width, global_flags.height, input_state); // FIXME: dimensions
1049 display_frame.chain = chain.chain;
1050 display_frame.setup_chain = chain.setup_chain;
1051 display_frame.ready_fence = fence;
1052 display_frame.input_frames = chain.input_frames;
1053 display_frame.temp_textures = {};
1054 output_channel[i].output_frame(display_frame);
1058 void Mixer::audio_thread_func()
1060 pthread_setname_np(pthread_self(), "Mixer_Audio");
1062 while (!should_quit) {
1066 unique_lock<mutex> lock(audio_mutex);
1067 audio_task_queue_changed.wait(lock, [this]{ return should_quit || !audio_task_queue.empty(); });
1071 task = audio_task_queue.front();
1072 audio_task_queue.pop();
1075 ResamplingQueue::RateAdjustmentPolicy rate_adjustment_policy =
1076 task.adjust_rate ? ResamplingQueue::ADJUST_RATE : ResamplingQueue::DO_NOT_ADJUST_RATE;
1077 vector<float> samples_out = audio_mixer.get_output(
1078 task.frame_timestamp,
1080 rate_adjustment_policy);
1082 // Send the samples to the sound card, then add them to the output.
1084 alsa->write(samples_out);
1086 if (output_card_index != -1) {
1087 const int64_t av_delay = lrint(global_flags.audio_queue_length_ms * 0.001 * TIMEBASE); // Corresponds to the delay in ResamplingQueue.
1088 cards[output_card_index].output->send_audio(task.pts_int + av_delay, samples_out);
1090 video_encoder->add_audio(task.pts_int, move(samples_out));
1094 void Mixer::release_display_frame(DisplayFrame *frame)
1096 for (GLuint texnum : frame->temp_textures) {
1097 resource_pool->release_2d_texture(texnum);
1099 frame->temp_textures.clear();
1100 frame->ready_fence.reset();
1101 frame->input_frames.clear();
1106 mixer_thread = thread(&Mixer::thread_func, this);
1107 audio_thread = thread(&Mixer::audio_thread_func, this);
1113 audio_task_queue_changed.notify_one();
1114 mixer_thread.join();
1115 audio_thread.join();
1118 void Mixer::transition_clicked(int transition_num)
1120 theme->transition_clicked(transition_num, pts());
1123 void Mixer::channel_clicked(int preview_num)
1125 theme->channel_clicked(preview_num);
1128 void Mixer::start_mode_scanning(unsigned card_index)
1130 assert(card_index < num_cards);
1131 if (is_mode_scanning[card_index]) {
1134 is_mode_scanning[card_index] = true;
1135 mode_scanlist[card_index].clear();
1136 for (const auto &mode : cards[card_index].capture->get_available_video_modes()) {
1137 mode_scanlist[card_index].push_back(mode.first);
1139 assert(!mode_scanlist[card_index].empty());
1140 mode_scanlist_index[card_index] = 0;
1141 cards[card_index].capture->set_video_mode(mode_scanlist[card_index][0]);
1142 last_mode_scan_change[card_index] = steady_clock::now();
1145 map<uint32_t, bmusb::VideoMode> Mixer::get_available_output_video_modes() const
1147 assert(desired_output_card_index != -1);
1148 unique_lock<mutex> lock(card_mutex);
1149 return cards[desired_output_card_index].output->get_available_video_modes();
1152 Mixer::OutputChannel::~OutputChannel()
1154 if (has_current_frame) {
1155 parent->release_display_frame(¤t_frame);
1157 if (has_ready_frame) {
1158 parent->release_display_frame(&ready_frame);
1162 void Mixer::OutputChannel::output_frame(DisplayFrame frame)
1164 // Store this frame for display. Remove the ready frame if any
1165 // (it was seemingly never used).
1167 unique_lock<mutex> lock(frame_mutex);
1168 if (has_ready_frame) {
1169 parent->release_display_frame(&ready_frame);
1171 ready_frame = frame;
1172 has_ready_frame = true;
1175 if (new_frame_ready_callback) {
1176 new_frame_ready_callback();
1179 // Reduce the number of callbacks by filtering duplicates. The reason
1180 // why we bother doing this is that Qt seemingly can get into a state
1181 // where its builds up an essentially unbounded queue of signals,
1182 // consuming more and more memory, and there's no good way of collapsing
1183 // user-defined signals or limiting the length of the queue.
1184 if (transition_names_updated_callback) {
1185 vector<string> transition_names = global_mixer->get_transition_names();
1186 bool changed = false;
1187 if (transition_names.size() != last_transition_names.size()) {
1190 for (unsigned i = 0; i < transition_names.size(); ++i) {
1191 if (transition_names[i] != last_transition_names[i]) {
1198 transition_names_updated_callback(transition_names);
1199 last_transition_names = transition_names;
1202 if (name_updated_callback) {
1203 string name = global_mixer->get_channel_name(channel);
1204 if (name != last_name) {
1205 name_updated_callback(name);
1209 if (color_updated_callback) {
1210 string color = global_mixer->get_channel_color(channel);
1211 if (color != last_color) {
1212 color_updated_callback(color);
1218 bool Mixer::OutputChannel::get_display_frame(DisplayFrame *frame)
1220 unique_lock<mutex> lock(frame_mutex);
1221 if (!has_current_frame && !has_ready_frame) {
1225 if (has_current_frame && has_ready_frame) {
1226 // We have a new ready frame. Toss the current one.
1227 parent->release_display_frame(¤t_frame);
1228 has_current_frame = false;
1230 if (has_ready_frame) {
1231 assert(!has_current_frame);
1232 current_frame = ready_frame;
1233 ready_frame.ready_fence.reset(); // Drop the refcount.
1234 ready_frame.input_frames.clear(); // Drop the refcounts.
1235 has_current_frame = true;
1236 has_ready_frame = false;
1239 *frame = current_frame;
1243 void Mixer::OutputChannel::set_frame_ready_callback(Mixer::new_frame_ready_callback_t callback)
1245 new_frame_ready_callback = callback;
1248 void Mixer::OutputChannel::set_transition_names_updated_callback(Mixer::transition_names_updated_callback_t callback)
1250 transition_names_updated_callback = callback;
1253 void Mixer::OutputChannel::set_name_updated_callback(Mixer::name_updated_callback_t callback)
1255 name_updated_callback = callback;
1258 void Mixer::OutputChannel::set_color_updated_callback(Mixer::color_updated_callback_t callback)
1260 color_updated_callback = callback;
1263 mutex RefCountedGLsync::fence_lock;