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 "video_encoder.h"
53 using namespace movit;
55 using namespace std::chrono;
56 using namespace std::placeholders;
57 using namespace bmusb;
59 Mixer *global_mixer = nullptr;
60 bool uses_mlock = false;
64 void insert_new_frame(RefCountedFrame frame, unsigned field_num, bool interlaced, unsigned card_index, InputState *input_state)
67 for (unsigned frame_num = FRAME_HISTORY_LENGTH; frame_num --> 1; ) { // :-)
68 input_state->buffered_frames[card_index][frame_num] =
69 input_state->buffered_frames[card_index][frame_num - 1];
71 input_state->buffered_frames[card_index][0] = { frame, field_num };
73 for (unsigned frame_num = 0; frame_num < FRAME_HISTORY_LENGTH; ++frame_num) {
74 input_state->buffered_frames[card_index][frame_num] = { frame, field_num };
81 void QueueLengthPolicy::update_policy(unsigned queue_length)
83 if (queue_length == 0) { // Starvation.
84 if (been_at_safe_point_since_last_starvation && safe_queue_length < unsigned(global_flags.max_input_queue_frames)) {
86 fprintf(stderr, "Card %u: Starvation, increasing safe limit to %u frame(s)\n",
87 card_index, safe_queue_length);
89 frames_with_at_least_one = 0;
90 been_at_safe_point_since_last_starvation = false;
93 if (queue_length >= 1) {
94 if (queue_length >= safe_queue_length) {
95 been_at_safe_point_since_last_starvation = true;
97 if (++frames_with_at_least_one >= 1000 && safe_queue_length > 1) {
99 fprintf(stderr, "Card %u: Spare frames for more than 1000 frames, reducing safe limit to %u frame(s)\n",
100 card_index, safe_queue_length);
101 frames_with_at_least_one = 0;
104 frames_with_at_least_one = 0;
108 Mixer::Mixer(const QSurfaceFormat &format, unsigned num_cards)
110 num_cards(num_cards),
111 mixer_surface(create_surface(format)),
112 h264_encoder_surface(create_surface(format)),
113 decklink_output_surface(create_surface(format)),
114 audio_mixer(num_cards)
116 CHECK(init_movit(MOVIT_SHADER_DIR, MOVIT_DEBUG_OFF));
119 // Since we allow non-bouncing 4:2:2 YCbCrInputs, effective subpixel precision
120 // will be halved when sampling them, and we need to compensate here.
121 movit_texel_subpixel_precision /= 2.0;
123 resource_pool.reset(new ResourcePool);
124 theme.reset(new Theme(global_flags.theme_filename, global_flags.theme_dirs, resource_pool.get(), num_cards));
125 for (unsigned i = 0; i < NUM_OUTPUTS; ++i) {
126 output_channel[i].parent = this;
127 output_channel[i].channel = i;
130 ImageFormat inout_format;
131 inout_format.color_space = COLORSPACE_sRGB;
132 inout_format.gamma_curve = GAMMA_sRGB;
134 // Display chain; shows the live output produced by the main chain (its RGBA version).
135 display_chain.reset(new EffectChain(global_flags.width, global_flags.height, resource_pool.get()));
137 display_input = new FlatInput(inout_format, FORMAT_RGB, GL_UNSIGNED_BYTE, global_flags.width, global_flags.height); // FIXME: GL_UNSIGNED_BYTE is really wrong.
138 display_chain->add_input(display_input);
139 display_chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
140 display_chain->set_dither_bits(0); // Don't bother.
141 display_chain->finalize();
143 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));
145 // Start listening for clients only once VideoEncoder has written its header, if any.
148 // First try initializing the then PCI devices, then USB, then
149 // fill up with fake cards until we have the desired number of cards.
150 unsigned num_pci_devices = 0;
151 unsigned card_index = 0;
154 IDeckLinkIterator *decklink_iterator = CreateDeckLinkIteratorInstance();
155 if (decklink_iterator != nullptr) {
156 for ( ; card_index < num_cards; ++card_index) {
158 if (decklink_iterator->Next(&decklink) != S_OK) {
162 DeckLinkCapture *capture = new DeckLinkCapture(decklink, card_index);
163 DeckLinkOutput *output = new DeckLinkOutput(resource_pool.get(), decklink_output_surface, global_flags.width, global_flags.height, card_index);
164 output->set_device(decklink);
165 configure_card(card_index, capture, /*is_fake_capture=*/false, output);
168 decklink_iterator->Release();
169 fprintf(stderr, "Found %u DeckLink PCI card(s).\n", num_pci_devices);
171 fprintf(stderr, "DeckLink drivers not found. Probing for USB cards only.\n");
175 unsigned num_usb_devices = BMUSBCapture::num_cards();
176 for (unsigned usb_card_index = 0; usb_card_index < num_usb_devices && card_index < num_cards; ++usb_card_index, ++card_index) {
177 BMUSBCapture *capture = new BMUSBCapture(usb_card_index);
178 capture->set_card_disconnected_callback(bind(&Mixer::bm_hotplug_remove, this, card_index));
179 configure_card(card_index, capture, /*is_fake_capture=*/false, /*output=*/nullptr);
181 fprintf(stderr, "Found %u USB card(s).\n", num_usb_devices);
183 unsigned num_fake_cards = 0;
184 for ( ; card_index < num_cards; ++card_index, ++num_fake_cards) {
185 FakeCapture *capture = new FakeCapture(global_flags.width, global_flags.height, FAKE_FPS, OUTPUT_FREQUENCY, card_index, global_flags.fake_cards_audio);
186 configure_card(card_index, capture, /*is_fake_capture=*/true, /*output=*/nullptr);
189 if (num_fake_cards > 0) {
190 fprintf(stderr, "Initialized %u fake cards.\n", num_fake_cards);
193 BMUSBCapture::set_card_connected_callback(bind(&Mixer::bm_hotplug_add, this, _1));
194 BMUSBCapture::start_bm_thread();
196 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
197 cards[card_index].queue_length_policy.reset(card_index);
200 chroma_subsampler.reset(new ChromaSubsampler(resource_pool.get()));
202 if (global_flags.enable_alsa_output) {
203 alsa.reset(new ALSAOutput(OUTPUT_FREQUENCY, /*num_channels=*/2));
205 if (global_flags.output_card != -1) {
206 desired_output_card_index = global_flags.output_card;
207 set_output_card_internal(global_flags.output_card);
213 BMUSBCapture::stop_bm_thread();
215 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
217 unique_lock<mutex> lock(card_mutex);
218 cards[card_index].should_quit = true; // Unblock thread.
219 cards[card_index].new_frames_changed.notify_all();
221 cards[card_index].capture->stop_dequeue_thread();
222 if (cards[card_index].output) {
223 cards[card_index].output->end_output();
224 cards[card_index].output.reset();
228 video_encoder.reset(nullptr);
231 void Mixer::configure_card(unsigned card_index, CaptureInterface *capture, bool is_fake_capture, DeckLinkOutput *output)
233 printf("Configuring card %d...\n", card_index);
235 CaptureCard *card = &cards[card_index];
236 if (card->capture != nullptr) {
237 card->capture->stop_dequeue_thread();
239 card->capture.reset(capture);
240 card->is_fake_capture = is_fake_capture;
241 if (card->output.get() != output) {
242 card->output.reset(output);
244 card->capture->set_frame_callback(bind(&Mixer::bm_frame, this, card_index, _1, _2, _3, _4, _5, _6, _7));
245 if (card->frame_allocator == nullptr) {
246 card->frame_allocator.reset(new PBOFrameAllocator(8 << 20, global_flags.width, global_flags.height)); // 8 MB.
248 card->capture->set_video_frame_allocator(card->frame_allocator.get());
249 if (card->surface == nullptr) {
250 card->surface = create_surface_with_same_format(mixer_surface);
252 while (!card->new_frames.empty()) card->new_frames.pop_front();
253 card->last_timecode = -1;
254 card->capture->configure_card();
256 // NOTE: start_bm_capture() happens in thread_func().
258 DeviceSpec device{InputSourceType::CAPTURE_CARD, card_index};
259 audio_mixer.reset_resampler(device);
260 audio_mixer.set_display_name(device, card->capture->get_description());
261 audio_mixer.trigger_state_changed_callback();
264 void Mixer::set_output_card_internal(int card_index)
266 // We don't really need to take card_mutex, since we're in the mixer
267 // thread and don't mess with any queues (which is the only thing that happens
268 // from other threads), but it's probably the safest in the long run.
269 unique_lock<mutex> lock(card_mutex);
270 if (output_card_index != -1) {
271 // Switch the old card from output to input.
272 CaptureCard *old_card = &cards[output_card_index];
273 old_card->output->end_output();
275 // Stop the fake card that we put into place.
276 // This needs to _not_ happen under the mutex, to avoid deadlock
277 // (delivering the last frame needs to take the mutex).
278 bmusb::CaptureInterface *fake_capture = old_card->capture.get();
280 fake_capture->stop_dequeue_thread();
282 old_card->capture = move(old_card->parked_capture);
283 old_card->is_fake_capture = false;
284 old_card->capture->start_bm_capture();
286 if (card_index != -1) {
287 CaptureCard *card = &cards[card_index];
288 bmusb::CaptureInterface *capture = card->capture.get();
289 // TODO: DeckLinkCapture::stop_dequeue_thread can actually take
290 // several seconds to complete (blocking on DisableVideoInput);
291 // see if we can maybe do it asynchronously.
293 capture->stop_dequeue_thread();
295 card->parked_capture = move(card->capture);
296 bmusb::CaptureInterface *fake_capture = new FakeCapture(global_flags.width, global_flags.height, FAKE_FPS, OUTPUT_FREQUENCY, card_index, global_flags.fake_cards_audio);
297 configure_card(card_index, fake_capture, /*is_fake_capture=*/true, card->output.release());
298 card->queue_length_policy.reset(card_index);
299 card->capture->start_bm_capture();
300 desired_output_video_mode = output_video_mode = card->output->pick_video_mode(desired_output_video_mode);
301 card->output->start_output(desired_output_video_mode, pts_int);
303 output_card_index = card_index;
308 int unwrap_timecode(uint16_t current_wrapped, int last)
310 uint16_t last_wrapped = last & 0xffff;
311 if (current_wrapped > last_wrapped) {
312 return (last & ~0xffff) | current_wrapped;
314 return 0x10000 + ((last & ~0xffff) | current_wrapped);
320 void Mixer::bm_frame(unsigned card_index, uint16_t timecode,
321 FrameAllocator::Frame video_frame, size_t video_offset, VideoFormat video_format,
322 FrameAllocator::Frame audio_frame, size_t audio_offset, AudioFormat audio_format)
324 DeviceSpec device{InputSourceType::CAPTURE_CARD, card_index};
325 CaptureCard *card = &cards[card_index];
327 if (is_mode_scanning[card_index]) {
328 if (video_format.has_signal) {
329 // Found a stable signal, so stop scanning.
330 is_mode_scanning[card_index] = false;
332 static constexpr double switch_time_s = 0.1; // Should be enough time for the signal to stabilize.
333 steady_clock::time_point now = steady_clock::now();
334 double sec_since_last_switch = duration<double>(steady_clock::now() - last_mode_scan_change[card_index]).count();
335 if (sec_since_last_switch > switch_time_s) {
336 // It isn't this mode; try the next one.
337 mode_scanlist_index[card_index]++;
338 mode_scanlist_index[card_index] %= mode_scanlist[card_index].size();
339 cards[card_index].capture->set_video_mode(mode_scanlist[card_index][mode_scanlist_index[card_index]]);
340 last_mode_scan_change[card_index] = now;
345 int64_t frame_length = int64_t(TIMEBASE) * video_format.frame_rate_den / video_format.frame_rate_nom;
346 assert(frame_length > 0);
348 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;
349 if (num_samples > OUTPUT_FREQUENCY / 10) {
350 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",
351 card_index, int(audio_frame.len), int(audio_offset),
352 timecode, int(video_frame.len), int(video_offset), video_format.id);
353 if (video_frame.owner) {
354 video_frame.owner->release_frame(video_frame);
356 if (audio_frame.owner) {
357 audio_frame.owner->release_frame(audio_frame);
362 int dropped_frames = 0;
363 if (card->last_timecode != -1) {
364 dropped_frames = unwrap_timecode(timecode, card->last_timecode) - card->last_timecode - 1;
367 // Number of samples per frame if we need to insert silence.
368 // (Could be nonintegral, but resampling will save us then.)
369 const int silence_samples = OUTPUT_FREQUENCY * video_format.frame_rate_den / video_format.frame_rate_nom;
371 if (dropped_frames > MAX_FPS * 2) {
372 fprintf(stderr, "Card %d lost more than two seconds (or time code jumping around; from 0x%04x to 0x%04x), resetting resampler\n",
373 card_index, card->last_timecode, timecode);
374 audio_mixer.reset_resampler(device);
376 } else if (dropped_frames > 0) {
377 // Insert silence as needed.
378 fprintf(stderr, "Card %d dropped %d frame(s) (before timecode 0x%04x), inserting silence.\n",
379 card_index, dropped_frames, timecode);
383 success = audio_mixer.add_silence(device, silence_samples, dropped_frames, frame_length);
387 audio_mixer.add_audio(device, audio_frame.data + audio_offset, num_samples, audio_format, frame_length, audio_frame.received_timestamp);
389 // Done with the audio, so release it.
390 if (audio_frame.owner) {
391 audio_frame.owner->release_frame(audio_frame);
394 card->last_timecode = timecode;
396 size_t expected_length = video_format.width * (video_format.height + video_format.extra_lines_top + video_format.extra_lines_bottom) * 2;
397 if (video_frame.len - video_offset == 0 ||
398 video_frame.len - video_offset != expected_length) {
399 if (video_frame.len != 0) {
400 printf("Card %d: Dropping video frame with wrong length (%ld; expected %ld)\n",
401 card_index, video_frame.len - video_offset, expected_length);
403 if (video_frame.owner) {
404 video_frame.owner->release_frame(video_frame);
407 // Still send on the information that we _had_ a frame, even though it's corrupted,
408 // so that pts can go up accordingly.
410 unique_lock<mutex> lock(card_mutex);
411 CaptureCard::NewFrame new_frame;
412 new_frame.frame = RefCountedFrame(FrameAllocator::Frame());
413 new_frame.length = frame_length;
414 new_frame.interlaced = false;
415 new_frame.dropped_frames = dropped_frames;
416 new_frame.received_timestamp = video_frame.received_timestamp;
417 card->new_frames.push_back(move(new_frame));
418 card->new_frames_changed.notify_all();
423 PBOFrameAllocator::Userdata *userdata = (PBOFrameAllocator::Userdata *)video_frame.userdata;
425 unsigned num_fields = video_format.interlaced ? 2 : 1;
426 steady_clock::time_point frame_upload_start;
427 bool interlaced_stride = false;
428 if (video_format.interlaced) {
429 // Send the two fields along as separate frames; the other side will need to add
430 // a deinterlacer to actually get this right.
431 assert(video_format.height % 2 == 0);
432 video_format.height /= 2;
433 assert(frame_length % 2 == 0);
436 if (video_format.second_field_start == 1) {
437 interlaced_stride = true;
439 frame_upload_start = steady_clock::now();
441 userdata->last_interlaced = video_format.interlaced;
442 userdata->last_has_signal = video_format.has_signal;
443 userdata->last_is_connected = video_format.is_connected;
444 userdata->last_frame_rate_nom = video_format.frame_rate_nom;
445 userdata->last_frame_rate_den = video_format.frame_rate_den;
446 RefCountedFrame frame(video_frame);
448 // Upload the textures.
449 size_t cbcr_width = video_format.width / 2;
450 size_t cbcr_offset = video_offset / 2;
451 size_t y_offset = video_frame.size / 2 + video_offset / 2;
453 for (unsigned field = 0; field < num_fields; ++field) {
454 // Put the actual texture upload in a lambda that is executed in the main thread.
455 // It is entirely possible to do this in the same thread (and it might even be
456 // faster, depending on the GPU and driver), but it appears to be trickling
457 // driver bugs very easily.
459 // Note that this means we must hold on to the actual frame data in <userdata>
460 // until the upload command is run, but we hold on to <frame> much longer than that
461 // (in fact, all the way until we no longer use the texture in rendering).
462 auto upload_func = [field, video_format, y_offset, cbcr_offset, cbcr_width, interlaced_stride, userdata]() {
463 unsigned field_start_line;
465 field_start_line = video_format.second_field_start;
467 field_start_line = video_format.extra_lines_top;
470 if (userdata->tex_y[field] == 0 ||
471 userdata->tex_cbcr[field] == 0 ||
472 video_format.width != userdata->last_width[field] ||
473 video_format.height != userdata->last_height[field]) {
474 // We changed resolution since last use of this texture, so we need to create
475 // a new object. Note that this each card has its own PBOFrameAllocator,
476 // we don't need to worry about these flip-flopping between resolutions.
477 glBindTexture(GL_TEXTURE_2D, userdata->tex_cbcr[field]);
479 glTexImage2D(GL_TEXTURE_2D, 0, GL_RG8, cbcr_width, video_format.height, 0, GL_RG, GL_UNSIGNED_BYTE, nullptr);
481 glBindTexture(GL_TEXTURE_2D, userdata->tex_y[field]);
483 glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, video_format.width, video_format.height, 0, GL_RED, GL_UNSIGNED_BYTE, nullptr);
485 userdata->last_width[field] = video_format.width;
486 userdata->last_height[field] = video_format.height;
489 GLuint pbo = userdata->pbo;
491 glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbo);
494 size_t field_y_start = y_offset + video_format.width * field_start_line;
495 size_t field_cbcr_start = cbcr_offset + cbcr_width * field_start_line * sizeof(uint16_t);
497 if (global_flags.flush_pbos) {
498 glFlushMappedBufferRange(GL_PIXEL_UNPACK_BUFFER, field_y_start, video_format.width * video_format.height);
500 glFlushMappedBufferRange(GL_PIXEL_UNPACK_BUFFER, field_cbcr_start, cbcr_width * video_format.height * sizeof(uint16_t));
504 glBindTexture(GL_TEXTURE_2D, userdata->tex_cbcr[field]);
506 if (interlaced_stride) {
507 glPixelStorei(GL_UNPACK_ROW_LENGTH, cbcr_width * 2);
510 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
513 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, cbcr_width, video_format.height, GL_RG, GL_UNSIGNED_BYTE, BUFFER_OFFSET(field_cbcr_start));
515 glBindTexture(GL_TEXTURE_2D, userdata->tex_y[field]);
517 if (interlaced_stride) {
518 glPixelStorei(GL_UNPACK_ROW_LENGTH, video_format.width * 2);
521 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
524 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, video_format.width, video_format.height, GL_RED, GL_UNSIGNED_BYTE, BUFFER_OFFSET(field_y_start));
526 glBindTexture(GL_TEXTURE_2D, 0);
528 glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
530 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
535 // Don't upload the second field as fast as we can; wait until
536 // the field time has approximately passed. (Otherwise, we could
537 // get timing jitter against the other sources, and possibly also
538 // against the video display, although the latter is not as critical.)
539 // This requires our system clock to be reasonably close to the
540 // video clock, but that's not an unreasonable assumption.
541 steady_clock::time_point second_field_start = frame_upload_start +
542 nanoseconds(frame_length * 1000000000 / TIMEBASE);
543 this_thread::sleep_until(second_field_start);
547 unique_lock<mutex> lock(card_mutex);
548 CaptureCard::NewFrame new_frame;
549 new_frame.frame = frame;
550 new_frame.length = frame_length;
551 new_frame.field = field;
552 new_frame.interlaced = video_format.interlaced;
553 new_frame.upload_func = upload_func;
554 new_frame.dropped_frames = dropped_frames;
555 new_frame.received_timestamp = video_frame.received_timestamp; // Ignore the audio timestamp.
556 card->new_frames.push_back(move(new_frame));
557 card->new_frames_changed.notify_all();
562 void Mixer::bm_hotplug_add(libusb_device *dev)
564 lock_guard<mutex> lock(hotplug_mutex);
565 hotplugged_cards.push_back(dev);
568 void Mixer::bm_hotplug_remove(unsigned card_index)
570 cards[card_index].new_frames_changed.notify_all();
573 void Mixer::thread_func()
575 pthread_setname_np(pthread_self(), "Mixer_OpenGL");
577 eglBindAPI(EGL_OPENGL_API);
578 QOpenGLContext *context = create_context(mixer_surface);
579 if (!make_current(context, mixer_surface)) {
584 // Start the actual capture. (We don't want to do it before we're actually ready
585 // to process output frames.)
586 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
587 if (int(card_index) != output_card_index) {
588 cards[card_index].capture->start_bm_capture();
592 steady_clock::time_point start, now;
593 start = steady_clock::now();
596 int stats_dropped_frames = 0;
598 while (!should_quit) {
599 if (desired_output_card_index != output_card_index) {
600 set_output_card_internal(desired_output_card_index);
602 if (output_card_index != -1 &&
603 desired_output_video_mode != output_video_mode) {
604 DeckLinkOutput *output = cards[output_card_index].output.get();
605 output->end_output();
606 desired_output_video_mode = output_video_mode = output->pick_video_mode(desired_output_video_mode);
607 output->start_output(desired_output_video_mode, pts_int);
610 CaptureCard::NewFrame new_frames[MAX_VIDEO_CARDS];
611 bool has_new_frame[MAX_VIDEO_CARDS] = { false };
613 bool master_card_is_output;
614 unsigned master_card_index;
615 if (output_card_index != -1) {
616 master_card_is_output = true;
617 master_card_index = output_card_index;
619 master_card_is_output = false;
620 master_card_index = theme->map_signal(master_clock_channel);
621 assert(master_card_index < num_cards);
624 OutputFrameInfo output_frame_info = get_one_frame_from_each_card(master_card_index, master_card_is_output, new_frames, has_new_frame);
625 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);
626 stats_dropped_frames += output_frame_info.dropped_frames;
628 handle_hotplugged_cards();
630 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
631 if (card_index == master_card_index || !has_new_frame[card_index]) {
634 if (new_frames[card_index].frame->len == 0) {
635 ++new_frames[card_index].dropped_frames;
637 if (new_frames[card_index].dropped_frames > 0) {
638 printf("Card %u dropped %d frames before this\n",
639 card_index, int(new_frames[card_index].dropped_frames));
643 // If the first card is reporting a corrupted or otherwise dropped frame,
644 // just increase the pts (skipping over this frame) and don't try to compute anything new.
645 if (!master_card_is_output && new_frames[master_card_index].frame->len == 0) {
646 ++stats_dropped_frames;
647 pts_int += new_frames[master_card_index].length;
651 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
652 if (!has_new_frame[card_index] || new_frames[card_index].frame->len == 0)
655 CaptureCard::NewFrame *new_frame = &new_frames[card_index];
656 assert(new_frame->frame != nullptr);
657 insert_new_frame(new_frame->frame, new_frame->field, new_frame->interlaced, card_index, &input_state);
660 // The new texture might need uploading before use.
661 if (new_frame->upload_func) {
662 new_frame->upload_func();
663 new_frame->upload_func = nullptr;
667 int64_t frame_duration = output_frame_info.frame_duration;
668 render_one_frame(frame_duration);
670 pts_int += frame_duration;
672 now = steady_clock::now();
673 double elapsed = duration<double>(now - start).count();
674 if (frame % 100 == 0) {
675 printf("%d frames (%d dropped) in %.3f seconds = %.1f fps (%.1f ms/frame)",
676 frame, stats_dropped_frames, elapsed, frame / elapsed,
677 1e3 * elapsed / frame);
678 // chain->print_phase_timing();
680 // Check our memory usage, to see if we are close to our mlockall()
681 // limit (if at all set).
683 if (getrusage(RUSAGE_SELF, &used) == -1) {
684 perror("getrusage(RUSAGE_SELF)");
690 if (getrlimit(RLIMIT_MEMLOCK, &limit) == -1) {
691 perror("getrlimit(RLIMIT_MEMLOCK)");
695 if (limit.rlim_cur == 0) {
696 printf(", using %ld MB memory (locked)",
697 long(used.ru_maxrss / 1024));
699 printf(", using %ld / %ld MB lockable memory (%.1f%%)",
700 long(used.ru_maxrss / 1024),
701 long(limit.rlim_cur / 1048576),
702 float(100.0 * (used.ru_maxrss * 1024.0) / limit.rlim_cur));
705 printf(", using %ld MB memory (not locked)",
706 long(used.ru_maxrss / 1024));
713 if (should_cut.exchange(false)) { // Test and clear.
714 video_encoder->do_cut(frame);
718 // Reset every 100 frames, so that local variations in frame times
719 // (especially for the first few frames, when the shaders are
720 // compiled etc.) don't make it hard to measure for the entire
721 // remaining duration of the program.
722 if (frame == 10000) {
730 resource_pool->clean_context();
733 bool Mixer::input_card_is_master_clock(unsigned card_index, unsigned master_card_index) const
735 if (output_card_index != -1) {
736 // The output card (ie., cards[output_card_index].output) is the master clock,
737 // so no input card (ie., cards[card_index].capture) is.
740 return (card_index == master_card_index);
743 void Mixer::trim_queue(CaptureCard *card, unsigned card_index)
745 // Count the number of frames in the queue, including any frames
746 // we dropped. It's hard to know exactly how we should deal with
747 // dropped (corrupted) input frames; they don't help our goal of
748 // avoiding starvation, but they still add to the problem of latency.
749 // Since dropped frames is going to mean a bump in the signal anyway,
750 // we err on the side of having more stable latency instead.
751 unsigned queue_length = 0;
752 for (const CaptureCard::NewFrame &frame : card->new_frames) {
753 queue_length += frame.dropped_frames + 1;
755 card->queue_length_policy.update_policy(queue_length);
757 // If needed, drop frames until the queue is below the safe limit.
758 // We prefer to drop from the head, because all else being equal,
759 // we'd like more recent frames (less latency).
760 unsigned dropped_frames = 0;
761 while (queue_length > card->queue_length_policy.get_safe_queue_length()) {
762 assert(!card->new_frames.empty());
763 assert(queue_length > card->new_frames.front().dropped_frames);
764 queue_length -= card->new_frames.front().dropped_frames;
766 if (queue_length <= card->queue_length_policy.get_safe_queue_length()) {
767 // No need to drop anything.
771 card->new_frames.pop_front();
772 card->new_frames_changed.notify_all();
777 if (dropped_frames > 0) {
778 fprintf(stderr, "Card %u dropped %u frame(s) to keep latency down.\n",
779 card_index, dropped_frames);
784 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])
786 OutputFrameInfo output_frame_info;
788 unique_lock<mutex> lock(card_mutex, defer_lock);
789 if (master_card_is_output) {
790 // Clocked to the output, so wait for it to be ready for the next frame.
791 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);
794 // Wait for the master card to have a new frame.
795 // TODO: Add a timeout.
796 output_frame_info.is_preroll = false;
798 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(); });
801 if (master_card_is_output) {
802 handle_hotplugged_cards();
803 } else if (cards[master_card_index].new_frames.empty()) {
804 // We were woken up, but not due to a new frame. Deal with it
806 assert(cards[master_card_index].capture->get_disconnected());
807 handle_hotplugged_cards();
811 if (!master_card_is_output) {
812 output_frame_info.frame_timestamp =
813 cards[master_card_index].new_frames.front().received_timestamp;
816 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
817 CaptureCard *card = &cards[card_index];
818 if (input_card_is_master_clock(card_index, master_card_index)) {
819 // We don't use the queue length policy for the master card,
820 // but we will if it stops being the master. Thus, clear out
821 // the policy in case we switch in the future.
822 card->queue_length_policy.reset(card_index);
823 assert(!card->new_frames.empty());
825 trim_queue(card, card_index);
827 if (!card->new_frames.empty()) {
828 new_frames[card_index] = move(card->new_frames.front());
829 has_new_frame[card_index] = true;
830 card->new_frames.pop_front();
831 card->new_frames_changed.notify_all();
835 if (!master_card_is_output) {
836 output_frame_info.dropped_frames = new_frames[master_card_index].dropped_frames;
837 output_frame_info.frame_duration = new_frames[master_card_index].length;
840 // This might get off by a fractional sample when changing master card
841 // between ones with different frame rates, but that's fine.
842 int num_samples_times_timebase = OUTPUT_FREQUENCY * output_frame_info.frame_duration + fractional_samples;
843 output_frame_info.num_samples = num_samples_times_timebase / TIMEBASE;
844 fractional_samples = num_samples_times_timebase % TIMEBASE;
845 assert(output_frame_info.num_samples >= 0);
847 return output_frame_info;
850 void Mixer::handle_hotplugged_cards()
852 // Check for cards that have been disconnected since last frame.
853 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
854 CaptureCard *card = &cards[card_index];
855 if (card->capture->get_disconnected()) {
856 fprintf(stderr, "Card %u went away, replacing with a fake card.\n", card_index);
857 FakeCapture *capture = new FakeCapture(global_flags.width, global_flags.height, FAKE_FPS, OUTPUT_FREQUENCY, card_index, global_flags.fake_cards_audio);
858 configure_card(card_index, capture, /*is_fake_capture=*/true, /*output=*/nullptr);
859 card->queue_length_policy.reset(card_index);
860 card->capture->start_bm_capture();
864 // Check for cards that have been connected since last frame.
865 vector<libusb_device *> hotplugged_cards_copy;
867 lock_guard<mutex> lock(hotplug_mutex);
868 swap(hotplugged_cards, hotplugged_cards_copy);
870 for (libusb_device *new_dev : hotplugged_cards_copy) {
871 // Look for a fake capture card where we can stick this in.
872 int free_card_index = -1;
873 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
874 if (cards[card_index].is_fake_capture) {
875 free_card_index = card_index;
880 if (free_card_index == -1) {
881 fprintf(stderr, "New card plugged in, but no free slots -- ignoring.\n");
882 libusb_unref_device(new_dev);
884 // BMUSBCapture takes ownership.
885 fprintf(stderr, "New card plugged in, choosing slot %d.\n", free_card_index);
886 CaptureCard *card = &cards[free_card_index];
887 BMUSBCapture *capture = new BMUSBCapture(free_card_index, new_dev);
888 configure_card(free_card_index, capture, /*is_fake_capture=*/false, /*output=*/nullptr);
889 card->queue_length_policy.reset(free_card_index);
890 capture->set_card_disconnected_callback(bind(&Mixer::bm_hotplug_remove, this, free_card_index));
891 capture->start_bm_capture();
897 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)
899 // Resample the audio as needed, including from previously dropped frames.
900 assert(num_cards > 0);
901 for (unsigned frame_num = 0; frame_num < dropped_frames + 1; ++frame_num) {
902 const bool dropped_frame = (frame_num != dropped_frames);
904 // Signal to the audio thread to process this frame.
905 // Note that if the frame is a dropped frame, we signal that
906 // we don't want to use this frame as base for adjusting
907 // the resampler rate. The reason for this is that the timing
908 // of these frames is often way too late; they typically don't
909 // “arrive” before we synthesize them. Thus, we could end up
910 // in a situation where we have inserted e.g. five audio frames
911 // into the queue before we then start pulling five of them
912 // back out. This makes ResamplingQueue overestimate the delay,
913 // causing undue resampler changes. (We _do_ use the last,
914 // non-dropped frame; perhaps we should just discard that as well,
915 // since dropped frames are expected to be rare, and it might be
916 // better to just wait until we have a slightly more normal situation).
917 unique_lock<mutex> lock(audio_mutex);
918 bool adjust_rate = !dropped_frame && !is_preroll;
919 audio_task_queue.push(AudioTask{pts_int, num_samples_per_frame, adjust_rate, frame_timestamp});
920 audio_task_queue_changed.notify_one();
923 // For dropped frames, increase the pts. Note that if the format changed
924 // in the meantime, we have no way of detecting that; we just have to
925 // assume the frame length is always the same.
926 pts_int += length_per_frame;
931 void Mixer::render_one_frame(int64_t duration)
933 // Get the main chain from the theme, and set its state immediately.
934 Theme::Chain theme_main_chain = theme->get_chain(0, pts(), global_flags.width, global_flags.height, input_state);
935 EffectChain *chain = theme_main_chain.chain;
936 theme_main_chain.setup_chain();
937 //theme_main_chain.chain->enable_phase_timing(true);
939 GLuint y_tex, cbcr_tex;
940 bool got_frame = video_encoder->begin_frame(&y_tex, &cbcr_tex);
943 // Render main chain.
944 GLuint cbcr_full_tex = resource_pool->create_2d_texture(GL_RG8, global_flags.width, global_flags.height);
945 GLuint rgba_tex = resource_pool->create_2d_texture(GL_RGB565, global_flags.width, global_flags.height); // Saves texture bandwidth, although dithering gets messed up.
946 GLuint fbo = resource_pool->create_fbo(y_tex, cbcr_full_tex, rgba_tex);
948 chain->render_to_fbo(fbo, global_flags.width, global_flags.height);
949 resource_pool->release_fbo(fbo);
951 chroma_subsampler->subsample_chroma(cbcr_full_tex, global_flags.width, global_flags.height, cbcr_tex);
952 if (output_card_index != -1) {
953 cards[output_card_index].output->send_frame(y_tex, cbcr_full_tex, theme_main_chain.input_frames, pts_int, duration);
955 resource_pool->release_2d_texture(cbcr_full_tex);
957 // Set the right state for rgba_tex.
958 glBindFramebuffer(GL_FRAMEBUFFER, 0);
959 glBindTexture(GL_TEXTURE_2D, rgba_tex);
960 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
961 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
962 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
964 const int64_t av_delay = lrint(global_flags.audio_queue_length_ms * 0.001 * TIMEBASE); // Corresponds to the delay in ResamplingQueue.
965 RefCountedGLsync fence = video_encoder->end_frame(pts_int + av_delay, duration, theme_main_chain.input_frames);
967 // The live frame just shows the RGBA texture we just rendered.
968 // It owns rgba_tex now.
969 DisplayFrame live_frame;
970 live_frame.chain = display_chain.get();
971 live_frame.setup_chain = [this, rgba_tex]{
972 display_input->set_texture_num(rgba_tex);
974 live_frame.ready_fence = fence;
975 live_frame.input_frames = {};
976 live_frame.temp_textures = { rgba_tex };
977 output_channel[OUTPUT_LIVE].output_frame(live_frame);
979 // Set up preview and any additional channels.
980 for (int i = 1; i < theme->get_num_channels() + 2; ++i) {
981 DisplayFrame display_frame;
982 Theme::Chain chain = theme->get_chain(i, pts(), global_flags.width, global_flags.height, input_state); // FIXME: dimensions
983 display_frame.chain = chain.chain;
984 display_frame.setup_chain = chain.setup_chain;
985 display_frame.ready_fence = fence;
986 display_frame.input_frames = chain.input_frames;
987 display_frame.temp_textures = {};
988 output_channel[i].output_frame(display_frame);
992 void Mixer::audio_thread_func()
994 pthread_setname_np(pthread_self(), "Mixer_Audio");
996 while (!should_quit) {
1000 unique_lock<mutex> lock(audio_mutex);
1001 audio_task_queue_changed.wait(lock, [this]{ return should_quit || !audio_task_queue.empty(); });
1005 task = audio_task_queue.front();
1006 audio_task_queue.pop();
1009 ResamplingQueue::RateAdjustmentPolicy rate_adjustment_policy =
1010 task.adjust_rate ? ResamplingQueue::ADJUST_RATE : ResamplingQueue::DO_NOT_ADJUST_RATE;
1011 vector<float> samples_out = audio_mixer.get_output(
1012 task.frame_timestamp,
1014 rate_adjustment_policy);
1016 // Send the samples to the sound card, then add them to the output.
1018 alsa->write(samples_out);
1020 if (output_card_index != -1) {
1021 const int64_t av_delay = lrint(global_flags.audio_queue_length_ms * 0.001 * TIMEBASE); // Corresponds to the delay in ResamplingQueue.
1022 cards[output_card_index].output->send_audio(task.pts_int + av_delay, samples_out);
1024 video_encoder->add_audio(task.pts_int, move(samples_out));
1028 void Mixer::release_display_frame(DisplayFrame *frame)
1030 for (GLuint texnum : frame->temp_textures) {
1031 resource_pool->release_2d_texture(texnum);
1033 frame->temp_textures.clear();
1034 frame->ready_fence.reset();
1035 frame->input_frames.clear();
1040 mixer_thread = thread(&Mixer::thread_func, this);
1041 audio_thread = thread(&Mixer::audio_thread_func, this);
1047 audio_task_queue_changed.notify_one();
1048 mixer_thread.join();
1049 audio_thread.join();
1052 void Mixer::transition_clicked(int transition_num)
1054 theme->transition_clicked(transition_num, pts());
1057 void Mixer::channel_clicked(int preview_num)
1059 theme->channel_clicked(preview_num);
1062 void Mixer::start_mode_scanning(unsigned card_index)
1064 assert(card_index < num_cards);
1065 if (is_mode_scanning[card_index]) {
1068 is_mode_scanning[card_index] = true;
1069 mode_scanlist[card_index].clear();
1070 for (const auto &mode : cards[card_index].capture->get_available_video_modes()) {
1071 mode_scanlist[card_index].push_back(mode.first);
1073 assert(!mode_scanlist[card_index].empty());
1074 mode_scanlist_index[card_index] = 0;
1075 cards[card_index].capture->set_video_mode(mode_scanlist[card_index][0]);
1076 last_mode_scan_change[card_index] = steady_clock::now();
1079 map<uint32_t, bmusb::VideoMode> Mixer::get_available_output_video_modes() const
1081 assert(desired_output_card_index != -1);
1082 unique_lock<mutex> lock(card_mutex);
1083 return cards[desired_output_card_index].output->get_available_video_modes();
1086 Mixer::OutputChannel::~OutputChannel()
1088 if (has_current_frame) {
1089 parent->release_display_frame(¤t_frame);
1091 if (has_ready_frame) {
1092 parent->release_display_frame(&ready_frame);
1096 void Mixer::OutputChannel::output_frame(DisplayFrame frame)
1098 // Store this frame for display. Remove the ready frame if any
1099 // (it was seemingly never used).
1101 unique_lock<mutex> lock(frame_mutex);
1102 if (has_ready_frame) {
1103 parent->release_display_frame(&ready_frame);
1105 ready_frame = frame;
1106 has_ready_frame = true;
1109 if (new_frame_ready_callback) {
1110 new_frame_ready_callback();
1113 // Reduce the number of callbacks by filtering duplicates. The reason
1114 // why we bother doing this is that Qt seemingly can get into a state
1115 // where its builds up an essentially unbounded queue of signals,
1116 // consuming more and more memory, and there's no good way of collapsing
1117 // user-defined signals or limiting the length of the queue.
1118 if (transition_names_updated_callback) {
1119 vector<string> transition_names = global_mixer->get_transition_names();
1120 bool changed = false;
1121 if (transition_names.size() != last_transition_names.size()) {
1124 for (unsigned i = 0; i < transition_names.size(); ++i) {
1125 if (transition_names[i] != last_transition_names[i]) {
1132 transition_names_updated_callback(transition_names);
1133 last_transition_names = transition_names;
1136 if (name_updated_callback) {
1137 string name = global_mixer->get_channel_name(channel);
1138 if (name != last_name) {
1139 name_updated_callback(name);
1143 if (color_updated_callback) {
1144 string color = global_mixer->get_channel_color(channel);
1145 if (color != last_color) {
1146 color_updated_callback(color);
1152 bool Mixer::OutputChannel::get_display_frame(DisplayFrame *frame)
1154 unique_lock<mutex> lock(frame_mutex);
1155 if (!has_current_frame && !has_ready_frame) {
1159 if (has_current_frame && has_ready_frame) {
1160 // We have a new ready frame. Toss the current one.
1161 parent->release_display_frame(¤t_frame);
1162 has_current_frame = false;
1164 if (has_ready_frame) {
1165 assert(!has_current_frame);
1166 current_frame = ready_frame;
1167 ready_frame.ready_fence.reset(); // Drop the refcount.
1168 ready_frame.input_frames.clear(); // Drop the refcounts.
1169 has_current_frame = true;
1170 has_ready_frame = false;
1173 *frame = current_frame;
1177 void Mixer::OutputChannel::set_frame_ready_callback(Mixer::new_frame_ready_callback_t callback)
1179 new_frame_ready_callback = callback;
1182 void Mixer::OutputChannel::set_transition_names_updated_callback(Mixer::transition_names_updated_callback_t callback)
1184 transition_names_updated_callback = callback;
1187 void Mixer::OutputChannel::set_name_updated_callback(Mixer::name_updated_callback_t callback)
1189 name_updated_callback = callback;
1192 void Mixer::OutputChannel::set_color_updated_callback(Mixer::color_updated_callback_t callback)
1194 color_updated_callback = callback;
1197 mutex RefCountedGLsync::fence_lock;