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(int queue_length)
83 if (queue_length < 0) { // Starvation.
84 if (been_at_safe_point_since_last_starvation && safe_queue_length < 5) {
86 fprintf(stderr, "Card %u: Starvation, increasing safe limit to %u frames\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 > 0) {
94 if (queue_length >= int(safe_queue_length)) {
95 been_at_safe_point_since_last_starvation = true;
97 if (++frames_with_at_least_one >= 1000 && safe_queue_length > 0) {
99 fprintf(stderr, "Card %u: Spare frames for more than 1000 frames, reducing safe limit to %u frames\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();
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 card->output->start_output(bmdModeHD720p5994, pts_int); // FIXME
302 output_card_index = card_index;
307 int unwrap_timecode(uint16_t current_wrapped, int last)
309 uint16_t last_wrapped = last & 0xffff;
310 if (current_wrapped > last_wrapped) {
311 return (last & ~0xffff) | current_wrapped;
313 return 0x10000 + ((last & ~0xffff) | current_wrapped);
319 void Mixer::bm_frame(unsigned card_index, uint16_t timecode,
320 FrameAllocator::Frame video_frame, size_t video_offset, VideoFormat video_format,
321 FrameAllocator::Frame audio_frame, size_t audio_offset, AudioFormat audio_format)
323 DeviceSpec device{InputSourceType::CAPTURE_CARD, card_index};
324 CaptureCard *card = &cards[card_index];
326 if (is_mode_scanning[card_index]) {
327 if (video_format.has_signal) {
328 // Found a stable signal, so stop scanning.
329 is_mode_scanning[card_index] = false;
331 static constexpr double switch_time_s = 0.1; // Should be enough time for the signal to stabilize.
332 steady_clock::time_point now = steady_clock::now();
333 double sec_since_last_switch = duration<double>(steady_clock::now() - last_mode_scan_change[card_index]).count();
334 if (sec_since_last_switch > switch_time_s) {
335 // It isn't this mode; try the next one.
336 mode_scanlist_index[card_index]++;
337 mode_scanlist_index[card_index] %= mode_scanlist[card_index].size();
338 cards[card_index].capture->set_video_mode(mode_scanlist[card_index][mode_scanlist_index[card_index]]);
339 last_mode_scan_change[card_index] = now;
344 int64_t frame_length = int64_t(TIMEBASE) * video_format.frame_rate_den / video_format.frame_rate_nom;
345 assert(frame_length > 0);
347 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;
348 if (num_samples > OUTPUT_FREQUENCY / 10) {
349 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",
350 card_index, int(audio_frame.len), int(audio_offset),
351 timecode, int(video_frame.len), int(video_offset), video_format.id);
352 if (video_frame.owner) {
353 video_frame.owner->release_frame(video_frame);
355 if (audio_frame.owner) {
356 audio_frame.owner->release_frame(audio_frame);
361 int dropped_frames = 0;
362 if (card->last_timecode != -1) {
363 dropped_frames = unwrap_timecode(timecode, card->last_timecode) - card->last_timecode - 1;
366 // Number of samples per frame if we need to insert silence.
367 // (Could be nonintegral, but resampling will save us then.)
368 const int silence_samples = OUTPUT_FREQUENCY * video_format.frame_rate_den / video_format.frame_rate_nom;
370 if (dropped_frames > MAX_FPS * 2) {
371 fprintf(stderr, "Card %d lost more than two seconds (or time code jumping around; from 0x%04x to 0x%04x), resetting resampler\n",
372 card_index, card->last_timecode, timecode);
373 audio_mixer.reset_resampler(device);
375 } else if (dropped_frames > 0) {
376 // Insert silence as needed.
377 fprintf(stderr, "Card %d dropped %d frame(s) (before timecode 0x%04x), inserting silence.\n",
378 card_index, dropped_frames, timecode);
382 success = audio_mixer.add_silence(device, silence_samples, dropped_frames, frame_length);
386 audio_mixer.add_audio(device, audio_frame.data + audio_offset, num_samples, audio_format, frame_length, audio_frame.received_timestamp);
388 // Done with the audio, so release it.
389 if (audio_frame.owner) {
390 audio_frame.owner->release_frame(audio_frame);
393 card->last_timecode = timecode;
395 size_t expected_length = video_format.width * (video_format.height + video_format.extra_lines_top + video_format.extra_lines_bottom) * 2;
396 if (video_frame.len - video_offset == 0 ||
397 video_frame.len - video_offset != expected_length) {
398 if (video_frame.len != 0) {
399 printf("Card %d: Dropping video frame with wrong length (%ld; expected %ld)\n",
400 card_index, video_frame.len - video_offset, expected_length);
402 if (video_frame.owner) {
403 video_frame.owner->release_frame(video_frame);
406 // Still send on the information that we _had_ a frame, even though it's corrupted,
407 // so that pts can go up accordingly.
409 unique_lock<mutex> lock(card_mutex);
410 CaptureCard::NewFrame new_frame;
411 new_frame.frame = RefCountedFrame(FrameAllocator::Frame());
412 new_frame.length = frame_length;
413 new_frame.interlaced = false;
414 new_frame.dropped_frames = dropped_frames;
415 card->new_frames.push(move(new_frame));
416 card->new_frames_changed.notify_all();
421 PBOFrameAllocator::Userdata *userdata = (PBOFrameAllocator::Userdata *)video_frame.userdata;
423 unsigned num_fields = video_format.interlaced ? 2 : 1;
424 steady_clock::time_point frame_upload_start;
425 bool interlaced_stride = false;
426 if (video_format.interlaced) {
427 // Send the two fields along as separate frames; the other side will need to add
428 // a deinterlacer to actually get this right.
429 assert(video_format.height % 2 == 0);
430 video_format.height /= 2;
431 assert(frame_length % 2 == 0);
434 if (video_format.second_field_start == 1) {
435 interlaced_stride = true;
437 frame_upload_start = steady_clock::now();
439 userdata->last_interlaced = video_format.interlaced;
440 userdata->last_has_signal = video_format.has_signal;
441 userdata->last_is_connected = video_format.is_connected;
442 userdata->last_frame_rate_nom = video_format.frame_rate_nom;
443 userdata->last_frame_rate_den = video_format.frame_rate_den;
444 RefCountedFrame frame(video_frame);
446 // Upload the textures.
447 size_t cbcr_width = video_format.width / 2;
448 size_t cbcr_offset = video_offset / 2;
449 size_t y_offset = video_frame.size / 2 + video_offset / 2;
451 for (unsigned field = 0; field < num_fields; ++field) {
452 // Put the actual texture upload in a lambda that is executed in the main thread.
453 // It is entirely possible to do this in the same thread (and it might even be
454 // faster, depending on the GPU and driver), but it appears to be trickling
455 // driver bugs very easily.
457 // Note that this means we must hold on to the actual frame data in <userdata>
458 // until the upload command is run, but we hold on to <frame> much longer than that
459 // (in fact, all the way until we no longer use the texture in rendering).
460 auto upload_func = [field, video_format, y_offset, cbcr_offset, cbcr_width, interlaced_stride, userdata]() {
461 unsigned field_start_line;
463 field_start_line = video_format.second_field_start;
465 field_start_line = video_format.extra_lines_top;
468 if (userdata->tex_y[field] == 0 ||
469 userdata->tex_cbcr[field] == 0 ||
470 video_format.width != userdata->last_width[field] ||
471 video_format.height != userdata->last_height[field]) {
472 // We changed resolution since last use of this texture, so we need to create
473 // a new object. Note that this each card has its own PBOFrameAllocator,
474 // we don't need to worry about these flip-flopping between resolutions.
475 glBindTexture(GL_TEXTURE_2D, userdata->tex_cbcr[field]);
477 glTexImage2D(GL_TEXTURE_2D, 0, GL_RG8, cbcr_width, video_format.height, 0, GL_RG, GL_UNSIGNED_BYTE, nullptr);
479 glBindTexture(GL_TEXTURE_2D, userdata->tex_y[field]);
481 glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, video_format.width, video_format.height, 0, GL_RED, GL_UNSIGNED_BYTE, nullptr);
483 userdata->last_width[field] = video_format.width;
484 userdata->last_height[field] = video_format.height;
487 GLuint pbo = userdata->pbo;
489 glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbo);
492 size_t field_y_start = y_offset + video_format.width * field_start_line;
493 size_t field_cbcr_start = cbcr_offset + cbcr_width * field_start_line * sizeof(uint16_t);
495 if (global_flags.flush_pbos) {
496 glFlushMappedBufferRange(GL_PIXEL_UNPACK_BUFFER, field_y_start, video_format.width * video_format.height);
498 glFlushMappedBufferRange(GL_PIXEL_UNPACK_BUFFER, field_cbcr_start, cbcr_width * video_format.height * sizeof(uint16_t));
502 glBindTexture(GL_TEXTURE_2D, userdata->tex_cbcr[field]);
504 if (interlaced_stride) {
505 glPixelStorei(GL_UNPACK_ROW_LENGTH, cbcr_width * 2);
508 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
511 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, cbcr_width, video_format.height, GL_RG, GL_UNSIGNED_BYTE, BUFFER_OFFSET(field_cbcr_start));
513 glBindTexture(GL_TEXTURE_2D, userdata->tex_y[field]);
515 if (interlaced_stride) {
516 glPixelStorei(GL_UNPACK_ROW_LENGTH, video_format.width * 2);
519 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
522 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, video_format.width, video_format.height, GL_RED, GL_UNSIGNED_BYTE, BUFFER_OFFSET(field_y_start));
524 glBindTexture(GL_TEXTURE_2D, 0);
526 glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
528 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
533 // Don't upload the second field as fast as we can; wait until
534 // the field time has approximately passed. (Otherwise, we could
535 // get timing jitter against the other sources, and possibly also
536 // against the video display, although the latter is not as critical.)
537 // This requires our system clock to be reasonably close to the
538 // video clock, but that's not an unreasonable assumption.
539 steady_clock::time_point second_field_start = frame_upload_start +
540 nanoseconds(frame_length * 1000000000 / TIMEBASE);
541 this_thread::sleep_until(second_field_start);
545 unique_lock<mutex> lock(card_mutex);
546 CaptureCard::NewFrame new_frame;
547 new_frame.frame = frame;
548 new_frame.length = frame_length;
549 new_frame.field = field;
550 new_frame.interlaced = video_format.interlaced;
551 new_frame.upload_func = upload_func;
552 new_frame.dropped_frames = dropped_frames;
553 new_frame.received_timestamp = video_frame.received_timestamp; // Ignore the audio timestamp.
554 card->new_frames.push(move(new_frame));
555 card->new_frames_changed.notify_all();
560 void Mixer::bm_hotplug_add(libusb_device *dev)
562 lock_guard<mutex> lock(hotplug_mutex);
563 hotplugged_cards.push_back(dev);
566 void Mixer::bm_hotplug_remove(unsigned card_index)
568 cards[card_index].new_frames_changed.notify_all();
571 void Mixer::thread_func()
573 pthread_setname_np(pthread_self(), "Mixer_OpenGL");
575 eglBindAPI(EGL_OPENGL_API);
576 QOpenGLContext *context = create_context(mixer_surface);
577 if (!make_current(context, mixer_surface)) {
582 // Start the actual capture. (We don't want to do it before we're actually ready
583 // to process output frames.)
584 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
585 if (int(card_index) != output_card_index) {
586 cards[card_index].capture->start_bm_capture();
590 steady_clock::time_point start, now;
591 start = steady_clock::now();
594 int stats_dropped_frames = 0;
596 while (!should_quit) {
597 if (desired_output_card_index != output_card_index) {
598 set_output_card_internal(desired_output_card_index);
601 CaptureCard::NewFrame new_frames[MAX_VIDEO_CARDS];
602 bool has_new_frame[MAX_VIDEO_CARDS] = { false };
604 bool master_card_is_output;
605 unsigned master_card_index;
606 if (output_card_index != -1) {
607 master_card_is_output = true;
608 master_card_index = output_card_index;
610 master_card_is_output = false;
611 master_card_index = theme->map_signal(master_clock_channel);
612 assert(master_card_index < num_cards);
615 OutputFrameInfo output_frame_info = get_one_frame_from_each_card(master_card_index, master_card_is_output, new_frames, has_new_frame);
616 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);
617 stats_dropped_frames += output_frame_info.dropped_frames;
619 handle_hotplugged_cards();
621 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
622 if (card_index == master_card_index || !has_new_frame[card_index]) {
625 if (new_frames[card_index].frame->len == 0) {
626 ++new_frames[card_index].dropped_frames;
628 if (new_frames[card_index].dropped_frames > 0) {
629 printf("Card %u dropped %d frames before this\n",
630 card_index, int(new_frames[card_index].dropped_frames));
634 // If the first card is reporting a corrupted or otherwise dropped frame,
635 // just increase the pts (skipping over this frame) and don't try to compute anything new.
636 if (!master_card_is_output && new_frames[master_card_index].frame->len == 0) {
637 ++stats_dropped_frames;
638 pts_int += new_frames[master_card_index].length;
642 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
643 if (!has_new_frame[card_index] || new_frames[card_index].frame->len == 0)
646 CaptureCard::NewFrame *new_frame = &new_frames[card_index];
647 assert(new_frame->frame != nullptr);
648 insert_new_frame(new_frame->frame, new_frame->field, new_frame->interlaced, card_index, &input_state);
651 // The new texture might need uploading before use.
652 if (new_frame->upload_func) {
653 new_frame->upload_func();
654 new_frame->upload_func = nullptr;
658 int64_t frame_duration = output_frame_info.frame_duration;
659 render_one_frame(frame_duration);
661 pts_int += frame_duration;
663 now = steady_clock::now();
664 double elapsed = duration<double>(now - start).count();
665 if (frame % 100 == 0) {
666 printf("%d frames (%d dropped) in %.3f seconds = %.1f fps (%.1f ms/frame)",
667 frame, stats_dropped_frames, elapsed, frame / elapsed,
668 1e3 * elapsed / frame);
669 // chain->print_phase_timing();
671 // Check our memory usage, to see if we are close to our mlockall()
672 // limit (if at all set).
674 if (getrusage(RUSAGE_SELF, &used) == -1) {
675 perror("getrusage(RUSAGE_SELF)");
681 if (getrlimit(RLIMIT_MEMLOCK, &limit) == -1) {
682 perror("getrlimit(RLIMIT_MEMLOCK)");
686 if (limit.rlim_cur == 0) {
687 printf(", using %ld MB memory (locked)",
688 long(used.ru_maxrss / 1024));
690 printf(", using %ld / %ld MB lockable memory (%.1f%%)",
691 long(used.ru_maxrss / 1024),
692 long(limit.rlim_cur / 1048576),
693 float(100.0 * (used.ru_maxrss * 1024.0) / limit.rlim_cur));
696 printf(", using %ld MB memory (not locked)",
697 long(used.ru_maxrss / 1024));
704 if (should_cut.exchange(false)) { // Test and clear.
705 video_encoder->do_cut(frame);
709 // Reset every 100 frames, so that local variations in frame times
710 // (especially for the first few frames, when the shaders are
711 // compiled etc.) don't make it hard to measure for the entire
712 // remaining duration of the program.
713 if (frame == 10000) {
721 resource_pool->clean_context();
724 bool Mixer::input_card_is_master_clock(unsigned card_index, unsigned master_card_index) const
726 if (output_card_index != -1) {
727 // The output card (ie., cards[output_card_index].output) is the master clock,
728 // so no input card (ie., cards[card_index].capture) is.
731 return (card_index == master_card_index);
734 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])
736 OutputFrameInfo output_frame_info;
738 unique_lock<mutex> lock(card_mutex, defer_lock);
739 if (master_card_is_output) {
740 // Clocked to the output, so wait for it to be ready for the next frame.
741 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);
744 // Wait for the master card to have a new frame.
745 // TODO: Add a timeout.
746 output_frame_info.is_preroll = false;
748 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(); });
751 if (master_card_is_output) {
752 handle_hotplugged_cards();
753 } else if (cards[master_card_index].new_frames.empty()) {
754 // We were woken up, but not due to a new frame. Deal with it
756 assert(cards[master_card_index].capture->get_disconnected());
757 handle_hotplugged_cards();
761 if (!master_card_is_output) {
762 output_frame_info.frame_timestamp =
763 cards[master_card_index].new_frames.front().received_timestamp;
766 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
767 CaptureCard *card = &cards[card_index];
768 if (card->new_frames.empty()) {
769 assert(!input_card_is_master_clock(card_index, master_card_index));
770 card->queue_length_policy.update_policy(-1);
773 new_frames[card_index] = move(card->new_frames.front());
774 has_new_frame[card_index] = true;
775 card->new_frames.pop();
776 card->new_frames_changed.notify_all();
778 if (input_card_is_master_clock(card_index, master_card_index)) {
779 // We don't use the queue length policy for the master card,
780 // but we will if it stops being the master. Thus, clear out
781 // the policy in case we switch in the future.
782 card->queue_length_policy.reset(card_index);
784 // If we have excess frames compared to the policy for this card,
785 // drop frames from the head.
786 card->queue_length_policy.update_policy(card->new_frames.size());
787 while (card->new_frames.size() > card->queue_length_policy.get_safe_queue_length()) {
788 card->new_frames.pop();
793 if (!master_card_is_output) {
794 output_frame_info.dropped_frames = new_frames[master_card_index].dropped_frames;
795 output_frame_info.frame_duration = new_frames[master_card_index].length;
798 // This might get off by a fractional sample when changing master card
799 // between ones with different frame rates, but that's fine.
800 int num_samples_times_timebase = OUTPUT_FREQUENCY * output_frame_info.frame_duration + fractional_samples;
801 output_frame_info.num_samples = num_samples_times_timebase / TIMEBASE;
802 fractional_samples = num_samples_times_timebase % TIMEBASE;
803 assert(output_frame_info.num_samples >= 0);
805 return output_frame_info;
808 void Mixer::handle_hotplugged_cards()
810 // Check for cards that have been disconnected since last frame.
811 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
812 CaptureCard *card = &cards[card_index];
813 if (card->capture->get_disconnected()) {
814 fprintf(stderr, "Card %u went away, replacing with a fake card.\n", card_index);
815 FakeCapture *capture = new FakeCapture(global_flags.width, global_flags.height, FAKE_FPS, OUTPUT_FREQUENCY, card_index, global_flags.fake_cards_audio);
816 configure_card(card_index, capture, /*is_fake_capture=*/true, /*output=*/nullptr);
817 card->queue_length_policy.reset(card_index);
818 card->capture->start_bm_capture();
822 // Check for cards that have been connected since last frame.
823 vector<libusb_device *> hotplugged_cards_copy;
825 lock_guard<mutex> lock(hotplug_mutex);
826 swap(hotplugged_cards, hotplugged_cards_copy);
828 for (libusb_device *new_dev : hotplugged_cards_copy) {
829 // Look for a fake capture card where we can stick this in.
830 int free_card_index = -1;
831 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
832 if (cards[card_index].is_fake_capture) {
833 free_card_index = card_index;
838 if (free_card_index == -1) {
839 fprintf(stderr, "New card plugged in, but no free slots -- ignoring.\n");
840 libusb_unref_device(new_dev);
842 // BMUSBCapture takes ownership.
843 fprintf(stderr, "New card plugged in, choosing slot %d.\n", free_card_index);
844 CaptureCard *card = &cards[free_card_index];
845 BMUSBCapture *capture = new BMUSBCapture(free_card_index, new_dev);
846 configure_card(free_card_index, capture, /*is_fake_capture=*/false, /*output=*/nullptr);
847 card->queue_length_policy.reset(free_card_index);
848 capture->set_card_disconnected_callback(bind(&Mixer::bm_hotplug_remove, this, free_card_index));
849 capture->start_bm_capture();
855 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)
857 // Resample the audio as needed, including from previously dropped frames.
858 assert(num_cards > 0);
859 for (unsigned frame_num = 0; frame_num < dropped_frames + 1; ++frame_num) {
860 const bool dropped_frame = (frame_num != dropped_frames);
862 // Signal to the audio thread to process this frame.
863 // Note that if the frame is a dropped frame, we signal that
864 // we don't want to use this frame as base for adjusting
865 // the resampler rate. The reason for this is that the timing
866 // of these frames is often way too late; they typically don't
867 // “arrive” before we synthesize them. Thus, we could end up
868 // in a situation where we have inserted e.g. five audio frames
869 // into the queue before we then start pulling five of them
870 // back out. This makes ResamplingQueue overestimate the delay,
871 // causing undue resampler changes. (We _do_ use the last,
872 // non-dropped frame; perhaps we should just discard that as well,
873 // since dropped frames are expected to be rare, and it might be
874 // better to just wait until we have a slightly more normal situation).
875 unique_lock<mutex> lock(audio_mutex);
876 bool adjust_rate = !dropped_frame && !is_preroll;
877 audio_task_queue.push(AudioTask{pts_int, num_samples_per_frame, adjust_rate, frame_timestamp});
878 audio_task_queue_changed.notify_one();
881 // For dropped frames, increase the pts. Note that if the format changed
882 // in the meantime, we have no way of detecting that; we just have to
883 // assume the frame length is always the same.
884 pts_int += length_per_frame;
889 void Mixer::render_one_frame(int64_t duration)
891 // Get the main chain from the theme, and set its state immediately.
892 Theme::Chain theme_main_chain = theme->get_chain(0, pts(), global_flags.width, global_flags.height, input_state);
893 EffectChain *chain = theme_main_chain.chain;
894 theme_main_chain.setup_chain();
895 //theme_main_chain.chain->enable_phase_timing(true);
897 GLuint y_tex, cbcr_tex;
898 bool got_frame = video_encoder->begin_frame(&y_tex, &cbcr_tex);
901 // Render main chain.
902 GLuint cbcr_full_tex = resource_pool->create_2d_texture(GL_RG8, global_flags.width, global_flags.height);
903 GLuint rgba_tex = resource_pool->create_2d_texture(GL_RGB565, global_flags.width, global_flags.height); // Saves texture bandwidth, although dithering gets messed up.
904 GLuint fbo = resource_pool->create_fbo(y_tex, cbcr_full_tex, rgba_tex);
906 chain->render_to_fbo(fbo, global_flags.width, global_flags.height);
907 resource_pool->release_fbo(fbo);
909 chroma_subsampler->subsample_chroma(cbcr_full_tex, global_flags.width, global_flags.height, cbcr_tex);
910 if (output_card_index != -1) {
911 cards[output_card_index].output->send_frame(y_tex, cbcr_full_tex, theme_main_chain.input_frames, pts_int, duration);
913 resource_pool->release_2d_texture(cbcr_full_tex);
915 // Set the right state for rgba_tex.
916 glBindFramebuffer(GL_FRAMEBUFFER, 0);
917 glBindTexture(GL_TEXTURE_2D, rgba_tex);
918 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
919 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
920 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
922 const int64_t av_delay = lrint(global_flags.audio_queue_length_ms * 0.001 * TIMEBASE); // Corresponds to the delay in ResamplingQueue.
923 RefCountedGLsync fence = video_encoder->end_frame(pts_int + av_delay, duration, theme_main_chain.input_frames);
925 // The live frame just shows the RGBA texture we just rendered.
926 // It owns rgba_tex now.
927 DisplayFrame live_frame;
928 live_frame.chain = display_chain.get();
929 live_frame.setup_chain = [this, rgba_tex]{
930 display_input->set_texture_num(rgba_tex);
932 live_frame.ready_fence = fence;
933 live_frame.input_frames = {};
934 live_frame.temp_textures = { rgba_tex };
935 output_channel[OUTPUT_LIVE].output_frame(live_frame);
937 // Set up preview and any additional channels.
938 for (int i = 1; i < theme->get_num_channels() + 2; ++i) {
939 DisplayFrame display_frame;
940 Theme::Chain chain = theme->get_chain(i, pts(), global_flags.width, global_flags.height, input_state); // FIXME: dimensions
941 display_frame.chain = chain.chain;
942 display_frame.setup_chain = chain.setup_chain;
943 display_frame.ready_fence = fence;
944 display_frame.input_frames = chain.input_frames;
945 display_frame.temp_textures = {};
946 output_channel[i].output_frame(display_frame);
950 void Mixer::audio_thread_func()
952 pthread_setname_np(pthread_self(), "Mixer_Audio");
954 while (!should_quit) {
958 unique_lock<mutex> lock(audio_mutex);
959 audio_task_queue_changed.wait(lock, [this]{ return should_quit || !audio_task_queue.empty(); });
963 task = audio_task_queue.front();
964 audio_task_queue.pop();
967 ResamplingQueue::RateAdjustmentPolicy rate_adjustment_policy =
968 task.adjust_rate ? ResamplingQueue::ADJUST_RATE : ResamplingQueue::DO_NOT_ADJUST_RATE;
969 vector<float> samples_out = audio_mixer.get_output(
970 task.frame_timestamp,
972 rate_adjustment_policy);
974 // Send the samples to the sound card, then add them to the output.
976 alsa->write(samples_out);
978 if (output_card_index != -1) {
979 const int64_t av_delay = lrint(global_flags.audio_queue_length_ms * 0.001 * TIMEBASE); // Corresponds to the delay in ResamplingQueue.
980 cards[output_card_index].output->send_audio(task.pts_int + av_delay, samples_out);
982 video_encoder->add_audio(task.pts_int, move(samples_out));
986 void Mixer::release_display_frame(DisplayFrame *frame)
988 for (GLuint texnum : frame->temp_textures) {
989 resource_pool->release_2d_texture(texnum);
991 frame->temp_textures.clear();
992 frame->ready_fence.reset();
993 frame->input_frames.clear();
998 mixer_thread = thread(&Mixer::thread_func, this);
999 audio_thread = thread(&Mixer::audio_thread_func, this);
1005 audio_task_queue_changed.notify_one();
1006 mixer_thread.join();
1007 audio_thread.join();
1010 void Mixer::transition_clicked(int transition_num)
1012 theme->transition_clicked(transition_num, pts());
1015 void Mixer::channel_clicked(int preview_num)
1017 theme->channel_clicked(preview_num);
1020 void Mixer::start_mode_scanning(unsigned card_index)
1022 assert(card_index < num_cards);
1023 if (is_mode_scanning[card_index]) {
1026 is_mode_scanning[card_index] = true;
1027 mode_scanlist[card_index].clear();
1028 for (const auto &mode : cards[card_index].capture->get_available_video_modes()) {
1029 mode_scanlist[card_index].push_back(mode.first);
1031 assert(!mode_scanlist[card_index].empty());
1032 mode_scanlist_index[card_index] = 0;
1033 cards[card_index].capture->set_video_mode(mode_scanlist[card_index][0]);
1034 last_mode_scan_change[card_index] = steady_clock::now();
1037 Mixer::OutputChannel::~OutputChannel()
1039 if (has_current_frame) {
1040 parent->release_display_frame(¤t_frame);
1042 if (has_ready_frame) {
1043 parent->release_display_frame(&ready_frame);
1047 void Mixer::OutputChannel::output_frame(DisplayFrame frame)
1049 // Store this frame for display. Remove the ready frame if any
1050 // (it was seemingly never used).
1052 unique_lock<mutex> lock(frame_mutex);
1053 if (has_ready_frame) {
1054 parent->release_display_frame(&ready_frame);
1056 ready_frame = frame;
1057 has_ready_frame = true;
1060 if (new_frame_ready_callback) {
1061 new_frame_ready_callback();
1064 // Reduce the number of callbacks by filtering duplicates. The reason
1065 // why we bother doing this is that Qt seemingly can get into a state
1066 // where its builds up an essentially unbounded queue of signals,
1067 // consuming more and more memory, and there's no good way of collapsing
1068 // user-defined signals or limiting the length of the queue.
1069 if (transition_names_updated_callback) {
1070 vector<string> transition_names = global_mixer->get_transition_names();
1071 bool changed = false;
1072 if (transition_names.size() != last_transition_names.size()) {
1075 for (unsigned i = 0; i < transition_names.size(); ++i) {
1076 if (transition_names[i] != last_transition_names[i]) {
1083 transition_names_updated_callback(transition_names);
1084 last_transition_names = transition_names;
1087 if (name_updated_callback) {
1088 string name = global_mixer->get_channel_name(channel);
1089 if (name != last_name) {
1090 name_updated_callback(name);
1094 if (color_updated_callback) {
1095 string color = global_mixer->get_channel_color(channel);
1096 if (color != last_color) {
1097 color_updated_callback(color);
1103 bool Mixer::OutputChannel::get_display_frame(DisplayFrame *frame)
1105 unique_lock<mutex> lock(frame_mutex);
1106 if (!has_current_frame && !has_ready_frame) {
1110 if (has_current_frame && has_ready_frame) {
1111 // We have a new ready frame. Toss the current one.
1112 parent->release_display_frame(¤t_frame);
1113 has_current_frame = false;
1115 if (has_ready_frame) {
1116 assert(!has_current_frame);
1117 current_frame = ready_frame;
1118 ready_frame.ready_fence.reset(); // Drop the refcount.
1119 ready_frame.input_frames.clear(); // Drop the refcounts.
1120 has_current_frame = true;
1121 has_ready_frame = false;
1124 *frame = current_frame;
1128 void Mixer::OutputChannel::set_frame_ready_callback(Mixer::new_frame_ready_callback_t callback)
1130 new_frame_ready_callback = callback;
1133 void Mixer::OutputChannel::set_transition_names_updated_callback(Mixer::transition_names_updated_callback_t callback)
1135 transition_names_updated_callback = callback;
1138 void Mixer::OutputChannel::set_name_updated_callback(Mixer::name_updated_callback_t callback)
1140 name_updated_callback = callback;
1143 void Mixer::OutputChannel::set_color_updated_callback(Mixer::color_updated_callback_t callback)
1145 color_updated_callback = callback;
1148 mutex RefCountedGLsync::fence_lock;