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 < 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 card->new_frames.push_back(move(new_frame));
417 card->new_frames_changed.notify_all();
422 PBOFrameAllocator::Userdata *userdata = (PBOFrameAllocator::Userdata *)video_frame.userdata;
424 unsigned num_fields = video_format.interlaced ? 2 : 1;
425 steady_clock::time_point frame_upload_start;
426 bool interlaced_stride = false;
427 if (video_format.interlaced) {
428 // Send the two fields along as separate frames; the other side will need to add
429 // a deinterlacer to actually get this right.
430 assert(video_format.height % 2 == 0);
431 video_format.height /= 2;
432 assert(frame_length % 2 == 0);
435 if (video_format.second_field_start == 1) {
436 interlaced_stride = true;
438 frame_upload_start = steady_clock::now();
440 userdata->last_interlaced = video_format.interlaced;
441 userdata->last_has_signal = video_format.has_signal;
442 userdata->last_is_connected = video_format.is_connected;
443 userdata->last_frame_rate_nom = video_format.frame_rate_nom;
444 userdata->last_frame_rate_den = video_format.frame_rate_den;
445 RefCountedFrame frame(video_frame);
447 // Upload the textures.
448 size_t cbcr_width = video_format.width / 2;
449 size_t cbcr_offset = video_offset / 2;
450 size_t y_offset = video_frame.size / 2 + video_offset / 2;
452 for (unsigned field = 0; field < num_fields; ++field) {
453 // Put the actual texture upload in a lambda that is executed in the main thread.
454 // It is entirely possible to do this in the same thread (and it might even be
455 // faster, depending on the GPU and driver), but it appears to be trickling
456 // driver bugs very easily.
458 // Note that this means we must hold on to the actual frame data in <userdata>
459 // until the upload command is run, but we hold on to <frame> much longer than that
460 // (in fact, all the way until we no longer use the texture in rendering).
461 auto upload_func = [field, video_format, y_offset, cbcr_offset, cbcr_width, interlaced_stride, userdata]() {
462 unsigned field_start_line;
464 field_start_line = video_format.second_field_start;
466 field_start_line = video_format.extra_lines_top;
469 if (userdata->tex_y[field] == 0 ||
470 userdata->tex_cbcr[field] == 0 ||
471 video_format.width != userdata->last_width[field] ||
472 video_format.height != userdata->last_height[field]) {
473 // We changed resolution since last use of this texture, so we need to create
474 // a new object. Note that this each card has its own PBOFrameAllocator,
475 // we don't need to worry about these flip-flopping between resolutions.
476 glBindTexture(GL_TEXTURE_2D, userdata->tex_cbcr[field]);
478 glTexImage2D(GL_TEXTURE_2D, 0, GL_RG8, cbcr_width, video_format.height, 0, GL_RG, GL_UNSIGNED_BYTE, nullptr);
480 glBindTexture(GL_TEXTURE_2D, userdata->tex_y[field]);
482 glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, video_format.width, video_format.height, 0, GL_RED, GL_UNSIGNED_BYTE, nullptr);
484 userdata->last_width[field] = video_format.width;
485 userdata->last_height[field] = video_format.height;
488 GLuint pbo = userdata->pbo;
490 glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbo);
493 size_t field_y_start = y_offset + video_format.width * field_start_line;
494 size_t field_cbcr_start = cbcr_offset + cbcr_width * field_start_line * sizeof(uint16_t);
496 if (global_flags.flush_pbos) {
497 glFlushMappedBufferRange(GL_PIXEL_UNPACK_BUFFER, field_y_start, video_format.width * video_format.height);
499 glFlushMappedBufferRange(GL_PIXEL_UNPACK_BUFFER, field_cbcr_start, cbcr_width * video_format.height * sizeof(uint16_t));
503 glBindTexture(GL_TEXTURE_2D, userdata->tex_cbcr[field]);
505 if (interlaced_stride) {
506 glPixelStorei(GL_UNPACK_ROW_LENGTH, cbcr_width * 2);
509 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
512 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, cbcr_width, video_format.height, GL_RG, GL_UNSIGNED_BYTE, BUFFER_OFFSET(field_cbcr_start));
514 glBindTexture(GL_TEXTURE_2D, userdata->tex_y[field]);
516 if (interlaced_stride) {
517 glPixelStorei(GL_UNPACK_ROW_LENGTH, video_format.width * 2);
520 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
523 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, video_format.width, video_format.height, GL_RED, GL_UNSIGNED_BYTE, BUFFER_OFFSET(field_y_start));
525 glBindTexture(GL_TEXTURE_2D, 0);
527 glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
529 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
534 // Don't upload the second field as fast as we can; wait until
535 // the field time has approximately passed. (Otherwise, we could
536 // get timing jitter against the other sources, and possibly also
537 // against the video display, although the latter is not as critical.)
538 // This requires our system clock to be reasonably close to the
539 // video clock, but that's not an unreasonable assumption.
540 steady_clock::time_point second_field_start = frame_upload_start +
541 nanoseconds(frame_length * 1000000000 / TIMEBASE);
542 this_thread::sleep_until(second_field_start);
546 unique_lock<mutex> lock(card_mutex);
547 CaptureCard::NewFrame new_frame;
548 new_frame.frame = frame;
549 new_frame.length = frame_length;
550 new_frame.field = field;
551 new_frame.interlaced = video_format.interlaced;
552 new_frame.upload_func = upload_func;
553 new_frame.dropped_frames = dropped_frames;
554 new_frame.received_timestamp = video_frame.received_timestamp; // Ignore the audio timestamp.
555 card->new_frames.push_back(move(new_frame));
556 card->new_frames_changed.notify_all();
561 void Mixer::bm_hotplug_add(libusb_device *dev)
563 lock_guard<mutex> lock(hotplug_mutex);
564 hotplugged_cards.push_back(dev);
567 void Mixer::bm_hotplug_remove(unsigned card_index)
569 cards[card_index].new_frames_changed.notify_all();
572 void Mixer::thread_func()
574 pthread_setname_np(pthread_self(), "Mixer_OpenGL");
576 eglBindAPI(EGL_OPENGL_API);
577 QOpenGLContext *context = create_context(mixer_surface);
578 if (!make_current(context, mixer_surface)) {
583 // Start the actual capture. (We don't want to do it before we're actually ready
584 // to process output frames.)
585 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
586 if (int(card_index) != output_card_index) {
587 cards[card_index].capture->start_bm_capture();
591 steady_clock::time_point start, now;
592 start = steady_clock::now();
595 int stats_dropped_frames = 0;
597 while (!should_quit) {
598 if (desired_output_card_index != output_card_index) {
599 set_output_card_internal(desired_output_card_index);
601 if (output_card_index != -1 &&
602 desired_output_video_mode != output_video_mode) {
603 DeckLinkOutput *output = cards[output_card_index].output.get();
604 output->end_output();
605 desired_output_video_mode = output_video_mode = output->pick_video_mode(desired_output_video_mode);
606 output->start_output(desired_output_video_mode, pts_int);
609 CaptureCard::NewFrame new_frames[MAX_VIDEO_CARDS];
610 bool has_new_frame[MAX_VIDEO_CARDS] = { false };
612 bool master_card_is_output;
613 unsigned master_card_index;
614 if (output_card_index != -1) {
615 master_card_is_output = true;
616 master_card_index = output_card_index;
618 master_card_is_output = false;
619 master_card_index = theme->map_signal(master_clock_channel);
620 assert(master_card_index < num_cards);
623 OutputFrameInfo output_frame_info = get_one_frame_from_each_card(master_card_index, master_card_is_output, new_frames, has_new_frame);
624 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);
625 stats_dropped_frames += output_frame_info.dropped_frames;
627 handle_hotplugged_cards();
629 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
630 if (card_index == master_card_index || !has_new_frame[card_index]) {
633 if (new_frames[card_index].frame->len == 0) {
634 ++new_frames[card_index].dropped_frames;
636 if (new_frames[card_index].dropped_frames > 0) {
637 printf("Card %u dropped %d frames before this\n",
638 card_index, int(new_frames[card_index].dropped_frames));
642 // If the first card is reporting a corrupted or otherwise dropped frame,
643 // just increase the pts (skipping over this frame) and don't try to compute anything new.
644 if (!master_card_is_output && new_frames[master_card_index].frame->len == 0) {
645 ++stats_dropped_frames;
646 pts_int += new_frames[master_card_index].length;
650 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
651 if (!has_new_frame[card_index] || new_frames[card_index].frame->len == 0)
654 CaptureCard::NewFrame *new_frame = &new_frames[card_index];
655 assert(new_frame->frame != nullptr);
656 insert_new_frame(new_frame->frame, new_frame->field, new_frame->interlaced, card_index, &input_state);
659 // The new texture might need uploading before use.
660 if (new_frame->upload_func) {
661 new_frame->upload_func();
662 new_frame->upload_func = nullptr;
666 int64_t frame_duration = output_frame_info.frame_duration;
667 render_one_frame(frame_duration);
669 pts_int += frame_duration;
671 now = steady_clock::now();
672 double elapsed = duration<double>(now - start).count();
673 if (frame % 100 == 0) {
674 printf("%d frames (%d dropped) in %.3f seconds = %.1f fps (%.1f ms/frame)",
675 frame, stats_dropped_frames, elapsed, frame / elapsed,
676 1e3 * elapsed / frame);
677 // chain->print_phase_timing();
679 // Check our memory usage, to see if we are close to our mlockall()
680 // limit (if at all set).
682 if (getrusage(RUSAGE_SELF, &used) == -1) {
683 perror("getrusage(RUSAGE_SELF)");
689 if (getrlimit(RLIMIT_MEMLOCK, &limit) == -1) {
690 perror("getrlimit(RLIMIT_MEMLOCK)");
694 if (limit.rlim_cur == 0) {
695 printf(", using %ld MB memory (locked)",
696 long(used.ru_maxrss / 1024));
698 printf(", using %ld / %ld MB lockable memory (%.1f%%)",
699 long(used.ru_maxrss / 1024),
700 long(limit.rlim_cur / 1048576),
701 float(100.0 * (used.ru_maxrss * 1024.0) / limit.rlim_cur));
704 printf(", using %ld MB memory (not locked)",
705 long(used.ru_maxrss / 1024));
712 if (should_cut.exchange(false)) { // Test and clear.
713 video_encoder->do_cut(frame);
717 // Reset every 100 frames, so that local variations in frame times
718 // (especially for the first few frames, when the shaders are
719 // compiled etc.) don't make it hard to measure for the entire
720 // remaining duration of the program.
721 if (frame == 10000) {
729 resource_pool->clean_context();
732 bool Mixer::input_card_is_master_clock(unsigned card_index, unsigned master_card_index) const
734 if (output_card_index != -1) {
735 // The output card (ie., cards[output_card_index].output) is the master clock,
736 // so no input card (ie., cards[card_index].capture) is.
739 return (card_index == master_card_index);
742 void Mixer::trim_queue(CaptureCard *card, unsigned card_index)
744 // Count the number of frames in the queue, including any frames
745 // we dropped. It's hard to know exactly how we should deal with
746 // dropped (corrupted) input frames; they don't help our goal of
747 // avoiding starvation, but they still add to the problem of latency.
748 // Since dropped frames is going to mean a bump in the signal anyway,
749 // we err on the side of having more stable latency instead.
750 unsigned queue_length = 0;
751 for (const CaptureCard::NewFrame &frame : card->new_frames) {
752 queue_length += frame.dropped_frames + 1;
754 card->queue_length_policy.update_policy(queue_length);
756 // If needed, drop frames until the queue is below the safe limit.
757 // We prefer to drop from the head, because all else being equal,
758 // we'd like more recent frames (less latency).
759 unsigned dropped_frames = 0;
760 while (queue_length > card->queue_length_policy.get_safe_queue_length()) {
761 assert(!card->new_frames.empty());
762 assert(queue_length > card->new_frames.front().dropped_frames);
763 queue_length -= card->new_frames.front().dropped_frames;
765 if (queue_length <= card->queue_length_policy.get_safe_queue_length()) {
766 // No need to drop anything.
770 card->new_frames.pop_front();
771 card->new_frames_changed.notify_all();
776 if (dropped_frames > 0) {
777 fprintf(stderr, "Card %u dropped %u frame(s) to keep latency down.\n",
778 card_index, dropped_frames);
783 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])
785 OutputFrameInfo output_frame_info;
787 unique_lock<mutex> lock(card_mutex, defer_lock);
788 if (master_card_is_output) {
789 // Clocked to the output, so wait for it to be ready for the next frame.
790 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);
793 // Wait for the master card to have a new frame.
794 // TODO: Add a timeout.
795 output_frame_info.is_preroll = false;
797 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(); });
800 if (master_card_is_output) {
801 handle_hotplugged_cards();
802 } else if (cards[master_card_index].new_frames.empty()) {
803 // We were woken up, but not due to a new frame. Deal with it
805 assert(cards[master_card_index].capture->get_disconnected());
806 handle_hotplugged_cards();
810 if (!master_card_is_output) {
811 output_frame_info.frame_timestamp =
812 cards[master_card_index].new_frames.front().received_timestamp;
815 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
816 CaptureCard *card = &cards[card_index];
817 if (input_card_is_master_clock(card_index, master_card_index)) {
818 // We don't use the queue length policy for the master card,
819 // but we will if it stops being the master. Thus, clear out
820 // the policy in case we switch in the future.
821 card->queue_length_policy.reset(card_index);
822 assert(!card->new_frames.empty());
824 trim_queue(card, card_index);
826 if (!card->new_frames.empty()) {
827 new_frames[card_index] = move(card->new_frames.front());
828 has_new_frame[card_index] = true;
829 card->new_frames.pop_front();
830 card->new_frames_changed.notify_all();
834 if (!master_card_is_output) {
835 output_frame_info.dropped_frames = new_frames[master_card_index].dropped_frames;
836 output_frame_info.frame_duration = new_frames[master_card_index].length;
839 // This might get off by a fractional sample when changing master card
840 // between ones with different frame rates, but that's fine.
841 int num_samples_times_timebase = OUTPUT_FREQUENCY * output_frame_info.frame_duration + fractional_samples;
842 output_frame_info.num_samples = num_samples_times_timebase / TIMEBASE;
843 fractional_samples = num_samples_times_timebase % TIMEBASE;
844 assert(output_frame_info.num_samples >= 0);
846 return output_frame_info;
849 void Mixer::handle_hotplugged_cards()
851 // Check for cards that have been disconnected since last frame.
852 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
853 CaptureCard *card = &cards[card_index];
854 if (card->capture->get_disconnected()) {
855 fprintf(stderr, "Card %u went away, replacing with a fake card.\n", card_index);
856 FakeCapture *capture = new FakeCapture(global_flags.width, global_flags.height, FAKE_FPS, OUTPUT_FREQUENCY, card_index, global_flags.fake_cards_audio);
857 configure_card(card_index, capture, /*is_fake_capture=*/true, /*output=*/nullptr);
858 card->queue_length_policy.reset(card_index);
859 card->capture->start_bm_capture();
863 // Check for cards that have been connected since last frame.
864 vector<libusb_device *> hotplugged_cards_copy;
866 lock_guard<mutex> lock(hotplug_mutex);
867 swap(hotplugged_cards, hotplugged_cards_copy);
869 for (libusb_device *new_dev : hotplugged_cards_copy) {
870 // Look for a fake capture card where we can stick this in.
871 int free_card_index = -1;
872 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
873 if (cards[card_index].is_fake_capture) {
874 free_card_index = card_index;
879 if (free_card_index == -1) {
880 fprintf(stderr, "New card plugged in, but no free slots -- ignoring.\n");
881 libusb_unref_device(new_dev);
883 // BMUSBCapture takes ownership.
884 fprintf(stderr, "New card plugged in, choosing slot %d.\n", free_card_index);
885 CaptureCard *card = &cards[free_card_index];
886 BMUSBCapture *capture = new BMUSBCapture(free_card_index, new_dev);
887 configure_card(free_card_index, capture, /*is_fake_capture=*/false, /*output=*/nullptr);
888 card->queue_length_policy.reset(free_card_index);
889 capture->set_card_disconnected_callback(bind(&Mixer::bm_hotplug_remove, this, free_card_index));
890 capture->start_bm_capture();
896 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)
898 // Resample the audio as needed, including from previously dropped frames.
899 assert(num_cards > 0);
900 for (unsigned frame_num = 0; frame_num < dropped_frames + 1; ++frame_num) {
901 const bool dropped_frame = (frame_num != dropped_frames);
903 // Signal to the audio thread to process this frame.
904 // Note that if the frame is a dropped frame, we signal that
905 // we don't want to use this frame as base for adjusting
906 // the resampler rate. The reason for this is that the timing
907 // of these frames is often way too late; they typically don't
908 // “arrive” before we synthesize them. Thus, we could end up
909 // in a situation where we have inserted e.g. five audio frames
910 // into the queue before we then start pulling five of them
911 // back out. This makes ResamplingQueue overestimate the delay,
912 // causing undue resampler changes. (We _do_ use the last,
913 // non-dropped frame; perhaps we should just discard that as well,
914 // since dropped frames are expected to be rare, and it might be
915 // better to just wait until we have a slightly more normal situation).
916 unique_lock<mutex> lock(audio_mutex);
917 bool adjust_rate = !dropped_frame && !is_preroll;
918 audio_task_queue.push(AudioTask{pts_int, num_samples_per_frame, adjust_rate, frame_timestamp});
919 audio_task_queue_changed.notify_one();
922 // For dropped frames, increase the pts. Note that if the format changed
923 // in the meantime, we have no way of detecting that; we just have to
924 // assume the frame length is always the same.
925 pts_int += length_per_frame;
930 void Mixer::render_one_frame(int64_t duration)
932 // Get the main chain from the theme, and set its state immediately.
933 Theme::Chain theme_main_chain = theme->get_chain(0, pts(), global_flags.width, global_flags.height, input_state);
934 EffectChain *chain = theme_main_chain.chain;
935 theme_main_chain.setup_chain();
936 //theme_main_chain.chain->enable_phase_timing(true);
938 GLuint y_tex, cbcr_tex;
939 bool got_frame = video_encoder->begin_frame(&y_tex, &cbcr_tex);
942 // Render main chain.
943 GLuint cbcr_full_tex = resource_pool->create_2d_texture(GL_RG8, global_flags.width, global_flags.height);
944 GLuint rgba_tex = resource_pool->create_2d_texture(GL_RGB565, global_flags.width, global_flags.height); // Saves texture bandwidth, although dithering gets messed up.
945 GLuint fbo = resource_pool->create_fbo(y_tex, cbcr_full_tex, rgba_tex);
947 chain->render_to_fbo(fbo, global_flags.width, global_flags.height);
948 resource_pool->release_fbo(fbo);
950 chroma_subsampler->subsample_chroma(cbcr_full_tex, global_flags.width, global_flags.height, cbcr_tex);
951 if (output_card_index != -1) {
952 cards[output_card_index].output->send_frame(y_tex, cbcr_full_tex, theme_main_chain.input_frames, pts_int, duration);
954 resource_pool->release_2d_texture(cbcr_full_tex);
956 // Set the right state for rgba_tex.
957 glBindFramebuffer(GL_FRAMEBUFFER, 0);
958 glBindTexture(GL_TEXTURE_2D, rgba_tex);
959 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
960 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
961 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
963 const int64_t av_delay = lrint(global_flags.audio_queue_length_ms * 0.001 * TIMEBASE); // Corresponds to the delay in ResamplingQueue.
964 RefCountedGLsync fence = video_encoder->end_frame(pts_int + av_delay, duration, theme_main_chain.input_frames);
966 // The live frame just shows the RGBA texture we just rendered.
967 // It owns rgba_tex now.
968 DisplayFrame live_frame;
969 live_frame.chain = display_chain.get();
970 live_frame.setup_chain = [this, rgba_tex]{
971 display_input->set_texture_num(rgba_tex);
973 live_frame.ready_fence = fence;
974 live_frame.input_frames = {};
975 live_frame.temp_textures = { rgba_tex };
976 output_channel[OUTPUT_LIVE].output_frame(live_frame);
978 // Set up preview and any additional channels.
979 for (int i = 1; i < theme->get_num_channels() + 2; ++i) {
980 DisplayFrame display_frame;
981 Theme::Chain chain = theme->get_chain(i, pts(), global_flags.width, global_flags.height, input_state); // FIXME: dimensions
982 display_frame.chain = chain.chain;
983 display_frame.setup_chain = chain.setup_chain;
984 display_frame.ready_fence = fence;
985 display_frame.input_frames = chain.input_frames;
986 display_frame.temp_textures = {};
987 output_channel[i].output_frame(display_frame);
991 void Mixer::audio_thread_func()
993 pthread_setname_np(pthread_self(), "Mixer_Audio");
995 while (!should_quit) {
999 unique_lock<mutex> lock(audio_mutex);
1000 audio_task_queue_changed.wait(lock, [this]{ return should_quit || !audio_task_queue.empty(); });
1004 task = audio_task_queue.front();
1005 audio_task_queue.pop();
1008 ResamplingQueue::RateAdjustmentPolicy rate_adjustment_policy =
1009 task.adjust_rate ? ResamplingQueue::ADJUST_RATE : ResamplingQueue::DO_NOT_ADJUST_RATE;
1010 vector<float> samples_out = audio_mixer.get_output(
1011 task.frame_timestamp,
1013 rate_adjustment_policy);
1015 // Send the samples to the sound card, then add them to the output.
1017 alsa->write(samples_out);
1019 if (output_card_index != -1) {
1020 const int64_t av_delay = lrint(global_flags.audio_queue_length_ms * 0.001 * TIMEBASE); // Corresponds to the delay in ResamplingQueue.
1021 cards[output_card_index].output->send_audio(task.pts_int + av_delay, samples_out);
1023 video_encoder->add_audio(task.pts_int, move(samples_out));
1027 void Mixer::release_display_frame(DisplayFrame *frame)
1029 for (GLuint texnum : frame->temp_textures) {
1030 resource_pool->release_2d_texture(texnum);
1032 frame->temp_textures.clear();
1033 frame->ready_fence.reset();
1034 frame->input_frames.clear();
1039 mixer_thread = thread(&Mixer::thread_func, this);
1040 audio_thread = thread(&Mixer::audio_thread_func, this);
1046 audio_task_queue_changed.notify_one();
1047 mixer_thread.join();
1048 audio_thread.join();
1051 void Mixer::transition_clicked(int transition_num)
1053 theme->transition_clicked(transition_num, pts());
1056 void Mixer::channel_clicked(int preview_num)
1058 theme->channel_clicked(preview_num);
1061 void Mixer::start_mode_scanning(unsigned card_index)
1063 assert(card_index < num_cards);
1064 if (is_mode_scanning[card_index]) {
1067 is_mode_scanning[card_index] = true;
1068 mode_scanlist[card_index].clear();
1069 for (const auto &mode : cards[card_index].capture->get_available_video_modes()) {
1070 mode_scanlist[card_index].push_back(mode.first);
1072 assert(!mode_scanlist[card_index].empty());
1073 mode_scanlist_index[card_index] = 0;
1074 cards[card_index].capture->set_video_mode(mode_scanlist[card_index][0]);
1075 last_mode_scan_change[card_index] = steady_clock::now();
1078 map<uint32_t, bmusb::VideoMode> Mixer::get_available_output_video_modes() const
1080 assert(desired_output_card_index != -1);
1081 unique_lock<mutex> lock(card_mutex);
1082 return cards[desired_output_card_index].output->get_available_video_modes();
1085 Mixer::OutputChannel::~OutputChannel()
1087 if (has_current_frame) {
1088 parent->release_display_frame(¤t_frame);
1090 if (has_ready_frame) {
1091 parent->release_display_frame(&ready_frame);
1095 void Mixer::OutputChannel::output_frame(DisplayFrame frame)
1097 // Store this frame for display. Remove the ready frame if any
1098 // (it was seemingly never used).
1100 unique_lock<mutex> lock(frame_mutex);
1101 if (has_ready_frame) {
1102 parent->release_display_frame(&ready_frame);
1104 ready_frame = frame;
1105 has_ready_frame = true;
1108 if (new_frame_ready_callback) {
1109 new_frame_ready_callback();
1112 // Reduce the number of callbacks by filtering duplicates. The reason
1113 // why we bother doing this is that Qt seemingly can get into a state
1114 // where its builds up an essentially unbounded queue of signals,
1115 // consuming more and more memory, and there's no good way of collapsing
1116 // user-defined signals or limiting the length of the queue.
1117 if (transition_names_updated_callback) {
1118 vector<string> transition_names = global_mixer->get_transition_names();
1119 bool changed = false;
1120 if (transition_names.size() != last_transition_names.size()) {
1123 for (unsigned i = 0; i < transition_names.size(); ++i) {
1124 if (transition_names[i] != last_transition_names[i]) {
1131 transition_names_updated_callback(transition_names);
1132 last_transition_names = transition_names;
1135 if (name_updated_callback) {
1136 string name = global_mixer->get_channel_name(channel);
1137 if (name != last_name) {
1138 name_updated_callback(name);
1142 if (color_updated_callback) {
1143 string color = global_mixer->get_channel_color(channel);
1144 if (color != last_color) {
1145 color_updated_callback(color);
1151 bool Mixer::OutputChannel::get_display_frame(DisplayFrame *frame)
1153 unique_lock<mutex> lock(frame_mutex);
1154 if (!has_current_frame && !has_ready_frame) {
1158 if (has_current_frame && has_ready_frame) {
1159 // We have a new ready frame. Toss the current one.
1160 parent->release_display_frame(¤t_frame);
1161 has_current_frame = false;
1163 if (has_ready_frame) {
1164 assert(!has_current_frame);
1165 current_frame = ready_frame;
1166 ready_frame.ready_fence.reset(); // Drop the refcount.
1167 ready_frame.input_frames.clear(); // Drop the refcounts.
1168 has_current_frame = true;
1169 has_ready_frame = false;
1172 *frame = current_frame;
1176 void Mixer::OutputChannel::set_frame_ready_callback(Mixer::new_frame_ready_callback_t callback)
1178 new_frame_ready_callback = callback;
1181 void Mixer::OutputChannel::set_transition_names_updated_callback(Mixer::transition_names_updated_callback_t callback)
1183 transition_names_updated_callback = callback;
1186 void Mixer::OutputChannel::set_name_updated_callback(Mixer::name_updated_callback_t callback)
1188 name_updated_callback = callback;
1191 void Mixer::OutputChannel::set_color_updated_callback(Mixer::color_updated_callback_t callback)
1193 color_updated_callback = callback;
1196 mutex RefCountedGLsync::fence_lock;