]> git.sesse.net Git - nageru/blob - mixer.cpp
Work around some deadlock issues when changing output card.
[nageru] / mixer.cpp
1 #undef Success
2
3 #include "mixer.h"
4
5 #include <assert.h>
6 #include <epoxy/egl.h>
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>
13 #include <stdint.h>
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <sys/resource.h>
17 #include <algorithm>
18 #include <chrono>
19 #include <condition_variable>
20 #include <cstddef>
21 #include <cstdint>
22 #include <memory>
23 #include <mutex>
24 #include <ratio>
25 #include <string>
26 #include <thread>
27 #include <utility>
28 #include <vector>
29
30 #include "DeckLinkAPI.h"
31 #include "LinuxCOM.h"
32 #include "alsa_output.h"
33 #include "bmusb/bmusb.h"
34 #include "bmusb/fake_capture.h"
35 #include "chroma_subsampler.h"
36 #include "context.h"
37 #include "decklink_capture.h"
38 #include "decklink_output.h"
39 #include "defs.h"
40 #include "disk_space_estimator.h"
41 #include "flags.h"
42 #include "input_mapping.h"
43 #include "pbo_frame_allocator.h"
44 #include "ref_counted_gl_sync.h"
45 #include "resampling_queue.h"
46 #include "timebase.h"
47 #include "video_encoder.h"
48
49 class IDeckLink;
50 class QOpenGLContext;
51
52 using namespace movit;
53 using namespace std;
54 using namespace std::chrono;
55 using namespace std::placeholders;
56 using namespace bmusb;
57
58 Mixer *global_mixer = nullptr;
59 bool uses_mlock = false;
60
61 namespace {
62
63 void insert_new_frame(RefCountedFrame frame, unsigned field_num, bool interlaced, unsigned card_index, InputState *input_state)
64 {
65         if (interlaced) {
66                 for (unsigned frame_num = FRAME_HISTORY_LENGTH; frame_num --> 1; ) {  // :-)
67                         input_state->buffered_frames[card_index][frame_num] =
68                                 input_state->buffered_frames[card_index][frame_num - 1];
69                 }
70                 input_state->buffered_frames[card_index][0] = { frame, field_num };
71         } else {
72                 for (unsigned frame_num = 0; frame_num < FRAME_HISTORY_LENGTH; ++frame_num) {
73                         input_state->buffered_frames[card_index][frame_num] = { frame, field_num };
74                 }
75         }
76 }
77
78 }  // namespace
79
80 void QueueLengthPolicy::update_policy(int queue_length)
81 {
82         if (queue_length < 0) {  // Starvation.
83                 if (been_at_safe_point_since_last_starvation && safe_queue_length < 5) {
84                         ++safe_queue_length;
85                         fprintf(stderr, "Card %u: Starvation, increasing safe limit to %u frames\n",
86                                 card_index, safe_queue_length);
87                 }
88                 frames_with_at_least_one = 0;
89                 been_at_safe_point_since_last_starvation = false;
90                 return;
91         }
92         if (queue_length > 0) {
93                 if (queue_length >= int(safe_queue_length)) {
94                         been_at_safe_point_since_last_starvation = true;
95                 }
96                 if (++frames_with_at_least_one >= 1000 && safe_queue_length > 0) {
97                         --safe_queue_length;
98                         fprintf(stderr, "Card %u: Spare frames for more than 1000 frames, reducing safe limit to %u frames\n",
99                                 card_index, safe_queue_length);
100                         frames_with_at_least_one = 0;
101                 }
102         } else {
103                 frames_with_at_least_one = 0;
104         }
105 }
106
107 Mixer::Mixer(const QSurfaceFormat &format, unsigned num_cards)
108         : httpd(),
109           num_cards(num_cards),
110           mixer_surface(create_surface(format)),
111           h264_encoder_surface(create_surface(format)),
112           decklink_output_surface(create_surface(format)),
113           audio_mixer(num_cards)
114 {
115         CHECK(init_movit(MOVIT_SHADER_DIR, MOVIT_DEBUG_OFF));
116         check_error();
117
118         // Since we allow non-bouncing 4:2:2 YCbCrInputs, effective subpixel precision
119         // will be halved when sampling them, and we need to compensate here.
120         movit_texel_subpixel_precision /= 2.0;
121
122         resource_pool.reset(new ResourcePool);
123         theme.reset(new Theme(global_flags.theme_filename, global_flags.theme_dirs, resource_pool.get(), num_cards));
124         for (unsigned i = 0; i < NUM_OUTPUTS; ++i) {
125                 output_channel[i].parent = this;
126                 output_channel[i].channel = i;
127         }
128
129         ImageFormat inout_format;
130         inout_format.color_space = COLORSPACE_sRGB;
131         inout_format.gamma_curve = GAMMA_sRGB;
132
133         // Display chain; shows the live output produced by the main chain (its RGBA version).
134         display_chain.reset(new EffectChain(global_flags.width, global_flags.height, resource_pool.get()));
135         check_error();
136         display_input = new FlatInput(inout_format, FORMAT_RGB, GL_UNSIGNED_BYTE, global_flags.width, global_flags.height);  // FIXME: GL_UNSIGNED_BYTE is really wrong.
137         display_chain->add_input(display_input);
138         display_chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
139         display_chain->set_dither_bits(0);  // Don't bother.
140         display_chain->finalize();
141
142         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));
143
144         // Start listening for clients only once VideoEncoder has written its header, if any.
145         httpd.start(9095);
146
147         // First try initializing the then PCI devices, then USB, then
148         // fill up with fake cards until we have the desired number of cards.
149         unsigned num_pci_devices = 0;
150         unsigned card_index = 0;
151
152         {
153                 IDeckLinkIterator *decklink_iterator = CreateDeckLinkIteratorInstance();
154                 if (decklink_iterator != nullptr) {
155                         for ( ; card_index < num_cards; ++card_index) {
156                                 IDeckLink *decklink;
157                                 if (decklink_iterator->Next(&decklink) != S_OK) {
158                                         break;
159                                 }
160
161                                 DeckLinkCapture *capture = new DeckLinkCapture(decklink, card_index);
162                                 DeckLinkOutput *output = new DeckLinkOutput(resource_pool.get(), decklink_output_surface, global_flags.width, global_flags.height, card_index);
163                                 output->set_device(decklink);
164                                 configure_card(card_index, capture, /*is_fake_capture=*/false, output);
165                                 ++num_pci_devices;
166                         }
167                         decklink_iterator->Release();
168                         fprintf(stderr, "Found %u DeckLink PCI card(s).\n", num_pci_devices);
169                 } else {
170                         fprintf(stderr, "DeckLink drivers not found. Probing for USB cards only.\n");
171                 }
172         }
173
174         unsigned num_usb_devices = BMUSBCapture::num_cards();
175         for (unsigned usb_card_index = 0; usb_card_index < num_usb_devices && card_index < num_cards; ++usb_card_index, ++card_index) {
176                 BMUSBCapture *capture = new BMUSBCapture(usb_card_index);
177                 capture->set_card_disconnected_callback(bind(&Mixer::bm_hotplug_remove, this, card_index));
178                 configure_card(card_index, capture, /*is_fake_capture=*/false, /*output=*/nullptr);
179         }
180         fprintf(stderr, "Found %u USB card(s).\n", num_usb_devices);
181
182         unsigned num_fake_cards = 0;
183         for ( ; card_index < num_cards; ++card_index, ++num_fake_cards) {
184                 FakeCapture *capture = new FakeCapture(global_flags.width, global_flags.height, FAKE_FPS, OUTPUT_FREQUENCY, card_index, global_flags.fake_cards_audio);
185                 configure_card(card_index, capture, /*is_fake_capture=*/true, /*output=*/nullptr);
186         }
187
188         if (num_fake_cards > 0) {
189                 fprintf(stderr, "Initialized %u fake cards.\n", num_fake_cards);
190         }
191
192         BMUSBCapture::set_card_connected_callback(bind(&Mixer::bm_hotplug_add, this, _1));
193         BMUSBCapture::start_bm_thread();
194
195         for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
196                 cards[card_index].queue_length_policy.reset(card_index);
197         }
198
199         chroma_subsampler.reset(new ChromaSubsampler(resource_pool.get()));
200
201         if (global_flags.enable_alsa_output) {
202                 alsa.reset(new ALSAOutput(OUTPUT_FREQUENCY, /*num_channels=*/2));
203         }
204         if (global_flags.output_card != -1) {
205                 set_output_card(global_flags.output_card);
206         }
207 }
208
209 Mixer::~Mixer()
210 {
211         BMUSBCapture::stop_bm_thread();
212
213         for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
214                 {
215                         unique_lock<mutex> lock(card_mutex);
216                         cards[card_index].should_quit = true;  // Unblock thread.
217                         cards[card_index].new_frames_changed.notify_all();
218                 }
219                 cards[card_index].capture->stop_dequeue_thread();
220                 if (cards[card_index].output) {
221                         cards[card_index].output->end_output();
222                         cards[card_index].output.reset();
223                 }
224         }
225
226         video_encoder.reset(nullptr);
227 }
228
229 void Mixer::configure_card(unsigned card_index, CaptureInterface *capture, bool is_fake_capture, DeckLinkOutput *output)
230 {
231         printf("Configuring card %d...\n", card_index);
232
233         CaptureCard *card = &cards[card_index];
234         if (card->capture != nullptr) {
235                 card->capture->stop_dequeue_thread();
236         }
237         card->capture.reset(capture);
238         card->is_fake_capture = is_fake_capture;
239         if (card->output.get() != output) {
240                 card->output.reset(output);
241         }
242         card->capture->set_frame_callback(bind(&Mixer::bm_frame, this, card_index, _1, _2, _3, _4, _5, _6, _7));
243         if (card->frame_allocator == nullptr) {
244                 card->frame_allocator.reset(new PBOFrameAllocator(8 << 20, global_flags.width, global_flags.height));  // 8 MB.
245         }
246         card->capture->set_video_frame_allocator(card->frame_allocator.get());
247         if (card->surface == nullptr) {
248                 card->surface = create_surface_with_same_format(mixer_surface);
249         }
250         while (!card->new_frames.empty()) card->new_frames.pop();
251         card->last_timecode = -1;
252         card->capture->configure_card();
253
254         // NOTE: start_bm_capture() happens in thread_func().
255
256         DeviceSpec device{InputSourceType::CAPTURE_CARD, card_index};
257         audio_mixer.reset_resampler(device);
258         audio_mixer.set_display_name(device, card->capture->get_description());
259         audio_mixer.trigger_state_changed_callback();
260 }
261
262 void Mixer::set_output_card(int card_index)
263 {
264         if (card_index == output_card_index) {
265                 return;
266         }
267         unique_lock<mutex> lock(card_mutex);
268         if (output_card_index != -1) {
269                 // Switch the old card from output to input.
270                 CaptureCard *old_card = &cards[output_card_index];
271                 old_card->output->end_output();
272
273                 // Stop the fake card that we put into place.
274                 // This needs to _not_ happen under the mutex, to avoid deadlock
275                 // (delivering the last frame needs to take the mutex).
276                 bmusb::CaptureInterface *fake_capture = old_card->capture.get();
277                 lock.unlock();
278                 fake_capture->stop_dequeue_thread();
279                 lock.lock();
280                 old_card->capture = move(old_card->parked_capture);
281                 old_card->is_fake_capture = false;
282                 old_card->capture->start_bm_capture();
283         }
284
285         CaptureCard *card = &cards[card_index];
286         bmusb::CaptureInterface *capture = card->capture.get();
287         lock.unlock();
288         capture->stop_dequeue_thread();
289         lock.lock();
290         card->parked_capture = move(card->capture);
291         bmusb::CaptureInterface *fake_capture = new FakeCapture(global_flags.width, global_flags.height, FAKE_FPS, OUTPUT_FREQUENCY, card_index, global_flags.fake_cards_audio);
292         configure_card(card_index, fake_capture, /*is_fake_capture=*/true, card->output.release());
293         card->queue_length_policy.reset(card_index);
294         card->capture->start_bm_capture();
295         card->output->start_output(bmdModeHD720p5994, pts_int);  // FIXME
296         output_card_index = card_index;
297 }
298
299 namespace {
300
301 int unwrap_timecode(uint16_t current_wrapped, int last)
302 {
303         uint16_t last_wrapped = last & 0xffff;
304         if (current_wrapped > last_wrapped) {
305                 return (last & ~0xffff) | current_wrapped;
306         } else {
307                 return 0x10000 + ((last & ~0xffff) | current_wrapped);
308         }
309 }
310
311 }  // namespace
312
313 void Mixer::bm_frame(unsigned card_index, uint16_t timecode,
314                      FrameAllocator::Frame video_frame, size_t video_offset, VideoFormat video_format,
315                      FrameAllocator::Frame audio_frame, size_t audio_offset, AudioFormat audio_format)
316 {
317         DeviceSpec device{InputSourceType::CAPTURE_CARD, card_index};
318         CaptureCard *card = &cards[card_index];
319
320         if (is_mode_scanning[card_index]) {
321                 if (video_format.has_signal) {
322                         // Found a stable signal, so stop scanning.
323                         is_mode_scanning[card_index] = false;
324                 } else {
325                         static constexpr double switch_time_s = 0.1;  // Should be enough time for the signal to stabilize.
326                         steady_clock::time_point now = steady_clock::now();
327                         double sec_since_last_switch = duration<double>(steady_clock::now() - last_mode_scan_change[card_index]).count();
328                         if (sec_since_last_switch > switch_time_s) {
329                                 // It isn't this mode; try the next one.
330                                 mode_scanlist_index[card_index]++;
331                                 mode_scanlist_index[card_index] %= mode_scanlist[card_index].size();
332                                 cards[card_index].capture->set_video_mode(mode_scanlist[card_index][mode_scanlist_index[card_index]]);
333                                 last_mode_scan_change[card_index] = now;
334                         }
335                 }
336         }
337
338         int64_t frame_length = int64_t(TIMEBASE) * video_format.frame_rate_den / video_format.frame_rate_nom;
339         assert(frame_length > 0);
340
341         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;
342         if (num_samples > OUTPUT_FREQUENCY / 10) {
343                 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",
344                         card_index, int(audio_frame.len), int(audio_offset),
345                         timecode, int(video_frame.len), int(video_offset), video_format.id);
346                 if (video_frame.owner) {
347                         video_frame.owner->release_frame(video_frame);
348                 }
349                 if (audio_frame.owner) {
350                         audio_frame.owner->release_frame(audio_frame);
351                 }
352                 return;
353         }
354
355         int dropped_frames = 0;
356         if (card->last_timecode != -1) {
357                 dropped_frames = unwrap_timecode(timecode, card->last_timecode) - card->last_timecode - 1;
358         }
359
360         // Number of samples per frame if we need to insert silence.
361         // (Could be nonintegral, but resampling will save us then.)
362         const int silence_samples = OUTPUT_FREQUENCY * video_format.frame_rate_den / video_format.frame_rate_nom;
363
364         if (dropped_frames > MAX_FPS * 2) {
365                 fprintf(stderr, "Card %d lost more than two seconds (or time code jumping around; from 0x%04x to 0x%04x), resetting resampler\n",
366                         card_index, card->last_timecode, timecode);
367                 audio_mixer.reset_resampler(device);
368                 dropped_frames = 0;
369         } else if (dropped_frames > 0) {
370                 // Insert silence as needed.
371                 fprintf(stderr, "Card %d dropped %d frame(s) (before timecode 0x%04x), inserting silence.\n",
372                         card_index, dropped_frames, timecode);
373
374                 bool success;
375                 do {
376                         success = audio_mixer.add_silence(device, silence_samples, dropped_frames, frame_length);
377                 } while (!success);
378         }
379
380         audio_mixer.add_audio(device, audio_frame.data + audio_offset, num_samples, audio_format, frame_length);
381
382         // Done with the audio, so release it.
383         if (audio_frame.owner) {
384                 audio_frame.owner->release_frame(audio_frame);
385         }
386
387         card->last_timecode = timecode;
388
389         size_t expected_length = video_format.width * (video_format.height + video_format.extra_lines_top + video_format.extra_lines_bottom) * 2;
390         if (video_frame.len - video_offset == 0 ||
391             video_frame.len - video_offset != expected_length) {
392                 if (video_frame.len != 0) {
393                         printf("Card %d: Dropping video frame with wrong length (%ld; expected %ld)\n",
394                                 card_index, video_frame.len - video_offset, expected_length);
395                 }
396                 if (video_frame.owner) {
397                         video_frame.owner->release_frame(video_frame);
398                 }
399
400                 // Still send on the information that we _had_ a frame, even though it's corrupted,
401                 // so that pts can go up accordingly.
402                 {
403                         unique_lock<mutex> lock(card_mutex);
404                         CaptureCard::NewFrame new_frame;
405                         new_frame.frame = RefCountedFrame(FrameAllocator::Frame());
406                         new_frame.length = frame_length;
407                         new_frame.interlaced = false;
408                         new_frame.dropped_frames = dropped_frames;
409                         card->new_frames.push(move(new_frame));
410                         card->new_frames_changed.notify_all();
411                 }
412                 return;
413         }
414
415         PBOFrameAllocator::Userdata *userdata = (PBOFrameAllocator::Userdata *)video_frame.userdata;
416
417         unsigned num_fields = video_format.interlaced ? 2 : 1;
418         steady_clock::time_point frame_upload_start;
419         bool interlaced_stride = false;
420         if (video_format.interlaced) {
421                 // Send the two fields along as separate frames; the other side will need to add
422                 // a deinterlacer to actually get this right.
423                 assert(video_format.height % 2 == 0);
424                 video_format.height /= 2;
425                 assert(frame_length % 2 == 0);
426                 frame_length /= 2;
427                 num_fields = 2;
428                 if (video_format.second_field_start == 1) {
429                         interlaced_stride = true;
430                 }
431                 frame_upload_start = steady_clock::now();
432         }
433         userdata->last_interlaced = video_format.interlaced;
434         userdata->last_has_signal = video_format.has_signal;
435         userdata->last_is_connected = video_format.is_connected;
436         userdata->last_frame_rate_nom = video_format.frame_rate_nom;
437         userdata->last_frame_rate_den = video_format.frame_rate_den;
438         RefCountedFrame frame(video_frame);
439
440         // Upload the textures.
441         size_t cbcr_width = video_format.width / 2;
442         size_t cbcr_offset = video_offset / 2;
443         size_t y_offset = video_frame.size / 2 + video_offset / 2;
444
445         for (unsigned field = 0; field < num_fields; ++field) {
446                 // Put the actual texture upload in a lambda that is executed in the main thread.
447                 // It is entirely possible to do this in the same thread (and it might even be
448                 // faster, depending on the GPU and driver), but it appears to be trickling
449                 // driver bugs very easily.
450                 //
451                 // Note that this means we must hold on to the actual frame data in <userdata>
452                 // until the upload command is run, but we hold on to <frame> much longer than that
453                 // (in fact, all the way until we no longer use the texture in rendering).
454                 auto upload_func = [field, video_format, y_offset, cbcr_offset, cbcr_width, interlaced_stride, userdata]() {
455                         unsigned field_start_line;
456                         if (field == 1) {
457                                 field_start_line = video_format.second_field_start;
458                         } else {
459                                 field_start_line = video_format.extra_lines_top;
460                         }
461
462                         if (userdata->tex_y[field] == 0 ||
463                             userdata->tex_cbcr[field] == 0 ||
464                             video_format.width != userdata->last_width[field] ||
465                             video_format.height != userdata->last_height[field]) {
466                                 // We changed resolution since last use of this texture, so we need to create
467                                 // a new object. Note that this each card has its own PBOFrameAllocator,
468                                 // we don't need to worry about these flip-flopping between resolutions.
469                                 glBindTexture(GL_TEXTURE_2D, userdata->tex_cbcr[field]);
470                                 check_error();
471                                 glTexImage2D(GL_TEXTURE_2D, 0, GL_RG8, cbcr_width, video_format.height, 0, GL_RG, GL_UNSIGNED_BYTE, nullptr);
472                                 check_error();
473                                 glBindTexture(GL_TEXTURE_2D, userdata->tex_y[field]);
474                                 check_error();
475                                 glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, video_format.width, video_format.height, 0, GL_RED, GL_UNSIGNED_BYTE, nullptr);
476                                 check_error();
477                                 userdata->last_width[field] = video_format.width;
478                                 userdata->last_height[field] = video_format.height;
479                         }
480
481                         GLuint pbo = userdata->pbo;
482                         check_error();
483                         glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbo);
484                         check_error();
485
486                         size_t field_y_start = y_offset + video_format.width * field_start_line;
487                         size_t field_cbcr_start = cbcr_offset + cbcr_width * field_start_line * sizeof(uint16_t);
488
489                         if (global_flags.flush_pbos) {
490                                 glFlushMappedBufferRange(GL_PIXEL_UNPACK_BUFFER, field_y_start, video_format.width * video_format.height);
491                                 check_error();
492                                 glFlushMappedBufferRange(GL_PIXEL_UNPACK_BUFFER, field_cbcr_start, cbcr_width * video_format.height * sizeof(uint16_t));
493                                 check_error();
494                         }
495
496                         glBindTexture(GL_TEXTURE_2D, userdata->tex_cbcr[field]);
497                         check_error();
498                         if (interlaced_stride) {
499                                 glPixelStorei(GL_UNPACK_ROW_LENGTH, cbcr_width * 2);
500                                 check_error();
501                         } else {
502                                 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
503                                 check_error();
504                         }
505                         glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, cbcr_width, video_format.height, GL_RG, GL_UNSIGNED_BYTE, BUFFER_OFFSET(field_cbcr_start));
506                         check_error();
507                         glBindTexture(GL_TEXTURE_2D, userdata->tex_y[field]);
508                         check_error();
509                         if (interlaced_stride) {
510                                 glPixelStorei(GL_UNPACK_ROW_LENGTH, video_format.width * 2);
511                                 check_error();
512                         } else {
513                                 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
514                                 check_error();
515                         }
516                         glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, video_format.width, video_format.height, GL_RED, GL_UNSIGNED_BYTE, BUFFER_OFFSET(field_y_start));
517                         check_error();
518                         glBindTexture(GL_TEXTURE_2D, 0);
519                         check_error();
520                         glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
521                         check_error();
522                         glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
523                         check_error();
524                 };
525
526                 if (field == 1) {
527                         // Don't upload the second field as fast as we can; wait until
528                         // the field time has approximately passed. (Otherwise, we could
529                         // get timing jitter against the other sources, and possibly also
530                         // against the video display, although the latter is not as critical.)
531                         // This requires our system clock to be reasonably close to the
532                         // video clock, but that's not an unreasonable assumption.
533                         steady_clock::time_point second_field_start = frame_upload_start +
534                                 nanoseconds(frame_length * 1000000000 / TIMEBASE);
535                         this_thread::sleep_until(second_field_start);
536                 }
537
538                 {
539                         unique_lock<mutex> lock(card_mutex);
540                         CaptureCard::NewFrame new_frame;
541                         new_frame.frame = frame;
542                         new_frame.length = frame_length;
543                         new_frame.field = field;
544                         new_frame.interlaced = video_format.interlaced;
545                         new_frame.upload_func = upload_func;
546                         new_frame.dropped_frames = dropped_frames;
547                         new_frame.received_timestamp = video_frame.received_timestamp;  // Ignore the audio timestamp.
548                         card->new_frames.push(move(new_frame));
549                         card->new_frames_changed.notify_all();
550                 }
551         }
552 }
553
554 void Mixer::bm_hotplug_add(libusb_device *dev)
555 {
556         lock_guard<mutex> lock(hotplug_mutex);
557         hotplugged_cards.push_back(dev);
558 }
559
560 void Mixer::bm_hotplug_remove(unsigned card_index)
561 {
562         cards[card_index].new_frames_changed.notify_all();
563 }
564
565 void Mixer::thread_func()
566 {
567         eglBindAPI(EGL_OPENGL_API);
568         QOpenGLContext *context = create_context(mixer_surface);
569         if (!make_current(context, mixer_surface)) {
570                 printf("oops\n");
571                 exit(1);
572         }
573
574         // Start the actual capture. (We don't want to do it before we're actually ready
575         // to process output frames.)
576         for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
577                 if (int(card_index) != output_card_index) {
578                         cards[card_index].capture->start_bm_capture();
579                 }
580         }
581
582         steady_clock::time_point start, now;
583         start = steady_clock::now();
584
585         int frame = 0;
586         int stats_dropped_frames = 0;
587
588         while (!should_quit) {
589                 CaptureCard::NewFrame new_frames[MAX_VIDEO_CARDS];
590                 bool has_new_frame[MAX_VIDEO_CARDS] = { false };
591
592                 bool master_card_is_output;
593                 unsigned master_card_index;
594                 if (output_card_index != -1) {
595                         master_card_is_output = true;
596                         master_card_index = output_card_index;
597                 } else {
598                         master_card_is_output = false;
599                         master_card_index = theme->map_signal(master_clock_channel);
600                         assert(master_card_index < num_cards);
601                 }
602
603                 OutputFrameInfo output_frame_info = get_one_frame_from_each_card(master_card_index, master_card_is_output, new_frames, has_new_frame);
604                 schedule_audio_resampling_tasks(output_frame_info.dropped_frames, output_frame_info.num_samples, output_frame_info.frame_duration);
605                 stats_dropped_frames += output_frame_info.dropped_frames;
606
607                 handle_hotplugged_cards();
608
609                 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
610                         if (card_index == master_card_index || !has_new_frame[card_index]) {
611                                 continue;
612                         }
613                         if (new_frames[card_index].frame->len == 0) {
614                                 ++new_frames[card_index].dropped_frames;
615                         }
616                         if (new_frames[card_index].dropped_frames > 0) {
617                                 printf("Card %u dropped %d frames before this\n",
618                                         card_index, int(new_frames[card_index].dropped_frames));
619                         }
620                 }
621
622                 // If the first card is reporting a corrupted or otherwise dropped frame,
623                 // just increase the pts (skipping over this frame) and don't try to compute anything new.
624                 if (!master_card_is_output && new_frames[master_card_index].frame->len == 0) {
625                         ++stats_dropped_frames;
626                         pts_int += new_frames[master_card_index].length;
627                         continue;
628                 }
629
630                 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
631                         if (!has_new_frame[card_index] || new_frames[card_index].frame->len == 0)
632                                 continue;
633
634                         CaptureCard::NewFrame *new_frame = &new_frames[card_index];
635                         assert(new_frame->frame != nullptr);
636                         insert_new_frame(new_frame->frame, new_frame->field, new_frame->interlaced, card_index, &input_state);
637                         check_error();
638
639                         // The new texture might need uploading before use.
640                         if (new_frame->upload_func) {
641                                 new_frame->upload_func();
642                                 new_frame->upload_func = nullptr;
643                         }
644                 }
645
646                 int64_t frame_duration = output_frame_info.frame_duration;
647                 render_one_frame(frame_duration);
648                 ++frame;
649                 pts_int += frame_duration;
650
651                 now = steady_clock::now();
652                 double elapsed = duration<double>(now - start).count();
653                 if (frame % 100 == 0) {
654                         printf("%d frames (%d dropped) in %.3f seconds = %.1f fps (%.1f ms/frame)",
655                                 frame, stats_dropped_frames, elapsed, frame / elapsed,
656                                 1e3 * elapsed / frame);
657                 //      chain->print_phase_timing();
658
659                         // Check our memory usage, to see if we are close to our mlockall()
660                         // limit (if at all set).
661                         rusage used;
662                         if (getrusage(RUSAGE_SELF, &used) == -1) {
663                                 perror("getrusage(RUSAGE_SELF)");
664                                 assert(false);
665                         }
666
667                         if (uses_mlock) {
668                                 rlimit limit;
669                                 if (getrlimit(RLIMIT_MEMLOCK, &limit) == -1) {
670                                         perror("getrlimit(RLIMIT_MEMLOCK)");
671                                         assert(false);
672                                 }
673
674                                 if (limit.rlim_cur == 0) {
675                                         printf(", using %ld MB memory (locked)",
676                                                 long(used.ru_maxrss / 1024));
677                                 } else {
678                                         printf(", using %ld / %ld MB lockable memory (%.1f%%)",
679                                                 long(used.ru_maxrss / 1024),
680                                                 long(limit.rlim_cur / 1048576),
681                                                 float(100.0 * (used.ru_maxrss * 1024.0) / limit.rlim_cur));
682                                 }
683                         } else {
684                                 printf(", using %ld MB memory (not locked)",
685                                         long(used.ru_maxrss / 1024));
686                         }
687
688                         printf("\n");
689                 }
690
691
692                 if (should_cut.exchange(false)) {  // Test and clear.
693                         video_encoder->do_cut(frame);
694                 }
695
696 #if 0
697                 // Reset every 100 frames, so that local variations in frame times
698                 // (especially for the first few frames, when the shaders are
699                 // compiled etc.) don't make it hard to measure for the entire
700                 // remaining duration of the program.
701                 if (frame == 10000) {
702                         frame = 0;
703                         start = now;
704                 }
705 #endif
706                 check_error();
707         }
708
709         resource_pool->clean_context();
710 }
711
712 bool Mixer::input_card_is_master_clock(unsigned card_index, unsigned master_card_index) const
713 {
714         if (output_card_index != -1) {
715                 // The output card (ie., cards[output_card_index].output) is the master clock,
716                 // so no input card (ie., cards[card_index].capture) is.
717                 return false;
718         }
719         return (card_index == master_card_index);
720 }
721
722 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])
723 {
724         OutputFrameInfo output_frame_info;
725 start:
726         unique_lock<mutex> lock(card_mutex, defer_lock);
727         if (master_card_is_output) {
728                 // Clocked to the output, so wait for it to be ready for the next frame.
729                 cards[master_card_index].output->wait_for_frame(pts_int, &output_frame_info.dropped_frames, &output_frame_info.frame_duration);
730                 lock.lock();
731         } else {
732                 // Wait for the master card to have a new frame.
733                 // TODO: Add a timeout.
734                 lock.lock();
735                 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(); });
736         }
737
738         if (master_card_is_output) {
739                 handle_hotplugged_cards();
740         } else if (cards[master_card_index].new_frames.empty()) {
741                 // We were woken up, but not due to a new frame. Deal with it
742                 // and then restart.
743                 assert(cards[master_card_index].capture->get_disconnected());
744                 handle_hotplugged_cards();
745                 goto start;
746         }
747
748         for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
749                 CaptureCard *card = &cards[card_index];
750                 if (card->new_frames.empty()) {
751                         assert(!input_card_is_master_clock(card_index, master_card_index));
752                         card->queue_length_policy.update_policy(-1);
753                         continue;
754                 }
755                 new_frames[card_index] = move(card->new_frames.front());
756                 has_new_frame[card_index] = true;
757                 card->new_frames.pop();
758                 card->new_frames_changed.notify_all();
759
760                 if (input_card_is_master_clock(card_index, master_card_index)) {
761                         // We don't use the queue length policy for the master card,
762                         // but we will if it stops being the master. Thus, clear out
763                         // the policy in case we switch in the future.
764                         card->queue_length_policy.reset(card_index);
765                 } else {
766                         // If we have excess frames compared to the policy for this card,
767                         // drop frames from the head.
768                         card->queue_length_policy.update_policy(card->new_frames.size());
769                         while (card->new_frames.size() > card->queue_length_policy.get_safe_queue_length()) {
770                                 card->new_frames.pop();
771                         }
772                 }
773         }
774
775         if (!master_card_is_output) {
776                 output_frame_info.dropped_frames = new_frames[master_card_index].dropped_frames;
777                 output_frame_info.frame_duration = new_frames[master_card_index].length;
778         }
779
780         // This might get off by a fractional sample when changing master card
781         // between ones with different frame rates, but that's fine.
782         int num_samples_times_timebase = OUTPUT_FREQUENCY * output_frame_info.frame_duration + fractional_samples;
783         output_frame_info.num_samples = num_samples_times_timebase / TIMEBASE;
784         fractional_samples = num_samples_times_timebase % TIMEBASE;
785         assert(output_frame_info.num_samples >= 0);
786
787         return output_frame_info;
788 }
789
790 void Mixer::handle_hotplugged_cards()
791 {
792         // Check for cards that have been disconnected since last frame.
793         for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
794                 CaptureCard *card = &cards[card_index];
795                 if (card->capture->get_disconnected()) {
796                         fprintf(stderr, "Card %u went away, replacing with a fake card.\n", card_index);
797                         FakeCapture *capture = new FakeCapture(global_flags.width, global_flags.height, FAKE_FPS, OUTPUT_FREQUENCY, card_index, global_flags.fake_cards_audio);
798                         configure_card(card_index, capture, /*is_fake_capture=*/true, /*output=*/nullptr);
799                         card->queue_length_policy.reset(card_index);
800                         card->capture->start_bm_capture();
801                 }
802         }
803
804         // Check for cards that have been connected since last frame.
805         vector<libusb_device *> hotplugged_cards_copy;
806         {
807                 lock_guard<mutex> lock(hotplug_mutex);
808                 swap(hotplugged_cards, hotplugged_cards_copy);
809         }
810         for (libusb_device *new_dev : hotplugged_cards_copy) {
811                 // Look for a fake capture card where we can stick this in.
812                 int free_card_index = -1;
813                 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
814                         if (cards[card_index].is_fake_capture) {
815                                 free_card_index = card_index;
816                                 break;
817                         }
818                 }
819
820                 if (free_card_index == -1) {
821                         fprintf(stderr, "New card plugged in, but no free slots -- ignoring.\n");
822                         libusb_unref_device(new_dev);
823                 } else {
824                         // BMUSBCapture takes ownership.
825                         fprintf(stderr, "New card plugged in, choosing slot %d.\n", free_card_index);
826                         CaptureCard *card = &cards[free_card_index];
827                         BMUSBCapture *capture = new BMUSBCapture(free_card_index, new_dev);
828                         configure_card(free_card_index, capture, /*is_fake_capture=*/false, /*output=*/nullptr);
829                         card->queue_length_policy.reset(free_card_index);
830                         capture->set_card_disconnected_callback(bind(&Mixer::bm_hotplug_remove, this, free_card_index));
831                         capture->start_bm_capture();
832                 }
833         }
834 }
835
836
837 void Mixer::schedule_audio_resampling_tasks(unsigned dropped_frames, int num_samples_per_frame, int length_per_frame)
838 {
839         // Resample the audio as needed, including from previously dropped frames.
840         assert(num_cards > 0);
841         for (unsigned frame_num = 0; frame_num < dropped_frames + 1; ++frame_num) {
842                 const bool dropped_frame = (frame_num != dropped_frames);
843                 {
844                         // Signal to the audio thread to process this frame.
845                         // Note that if the frame is a dropped frame, we signal that
846                         // we don't want to use this frame as base for adjusting
847                         // the resampler rate. The reason for this is that the timing
848                         // of these frames is often way too late; they typically don't
849                         // “arrive” before we synthesize them. Thus, we could end up
850                         // in a situation where we have inserted e.g. five audio frames
851                         // into the queue before we then start pulling five of them
852                         // back out. This makes ResamplingQueue overestimate the delay,
853                         // causing undue resampler changes. (We _do_ use the last,
854                         // non-dropped frame; perhaps we should just discard that as well,
855                         // since dropped frames are expected to be rare, and it might be
856                         // better to just wait until we have a slightly more normal situation).
857                         unique_lock<mutex> lock(audio_mutex);
858                         bool adjust_rate = !dropped_frame;
859                         audio_task_queue.push(AudioTask{pts_int, num_samples_per_frame, adjust_rate});
860                         audio_task_queue_changed.notify_one();
861                 }
862                 if (dropped_frame) {
863                         // For dropped frames, increase the pts. Note that if the format changed
864                         // in the meantime, we have no way of detecting that; we just have to
865                         // assume the frame length is always the same.
866                         pts_int += length_per_frame;
867                 }
868         }
869 }
870
871 void Mixer::render_one_frame(int64_t duration)
872 {
873         // Get the main chain from the theme, and set its state immediately.
874         Theme::Chain theme_main_chain = theme->get_chain(0, pts(), global_flags.width, global_flags.height, input_state);
875         EffectChain *chain = theme_main_chain.chain;
876         theme_main_chain.setup_chain();
877         //theme_main_chain.chain->enable_phase_timing(true);
878
879         GLuint y_tex, cbcr_tex;
880         bool got_frame = video_encoder->begin_frame(&y_tex, &cbcr_tex);
881         assert(got_frame);
882
883         // Render main chain.
884         GLuint cbcr_full_tex = resource_pool->create_2d_texture(GL_RG8, global_flags.width, global_flags.height);
885         GLuint rgba_tex = resource_pool->create_2d_texture(GL_RGB565, global_flags.width, global_flags.height);  // Saves texture bandwidth, although dithering gets messed up.
886         GLuint fbo = resource_pool->create_fbo(y_tex, cbcr_full_tex, rgba_tex);
887         check_error();
888         chain->render_to_fbo(fbo, global_flags.width, global_flags.height);
889         resource_pool->release_fbo(fbo);
890
891         chroma_subsampler->subsample_chroma(cbcr_full_tex, global_flags.width, global_flags.height, cbcr_tex);
892         if (output_card_index != -1) {
893                 cards[output_card_index].output->send_frame(y_tex, cbcr_full_tex, theme_main_chain.input_frames, pts_int, duration);
894         }
895         resource_pool->release_2d_texture(cbcr_full_tex);
896
897         // Set the right state for rgba_tex.
898         glBindFramebuffer(GL_FRAMEBUFFER, 0);
899         glBindTexture(GL_TEXTURE_2D, rgba_tex);
900         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
901         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
902         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
903
904         const int64_t av_delay = lrint(global_flags.audio_queue_length_ms * 0.001 * TIMEBASE);  // Corresponds to the delay in ResamplingQueue.
905         RefCountedGLsync fence = video_encoder->end_frame(pts_int + av_delay, duration, theme_main_chain.input_frames);
906
907         // The live frame just shows the RGBA texture we just rendered.
908         // It owns rgba_tex now.
909         DisplayFrame live_frame;
910         live_frame.chain = display_chain.get();
911         live_frame.setup_chain = [this, rgba_tex]{
912                 display_input->set_texture_num(rgba_tex);
913         };
914         live_frame.ready_fence = fence;
915         live_frame.input_frames = {};
916         live_frame.temp_textures = { rgba_tex };
917         output_channel[OUTPUT_LIVE].output_frame(live_frame);
918
919         // Set up preview and any additional channels.
920         for (int i = 1; i < theme->get_num_channels() + 2; ++i) {
921                 DisplayFrame display_frame;
922                 Theme::Chain chain = theme->get_chain(i, pts(), global_flags.width, global_flags.height, input_state);  // FIXME: dimensions
923                 display_frame.chain = chain.chain;
924                 display_frame.setup_chain = chain.setup_chain;
925                 display_frame.ready_fence = fence;
926                 display_frame.input_frames = chain.input_frames;
927                 display_frame.temp_textures = {};
928                 output_channel[i].output_frame(display_frame);
929         }
930 }
931
932 void Mixer::audio_thread_func()
933 {
934         while (!should_quit) {
935                 AudioTask task;
936
937                 {
938                         unique_lock<mutex> lock(audio_mutex);
939                         audio_task_queue_changed.wait(lock, [this]{ return should_quit || !audio_task_queue.empty(); });
940                         if (should_quit) {
941                                 return;
942                         }
943                         task = audio_task_queue.front();
944                         audio_task_queue.pop();
945                 }
946
947                 ResamplingQueue::RateAdjustmentPolicy rate_adjustment_policy =
948                         task.adjust_rate ? ResamplingQueue::ADJUST_RATE : ResamplingQueue::DO_NOT_ADJUST_RATE;
949                 vector<float> samples_out = audio_mixer.get_output(
950                         double(task.pts_int) / TIMEBASE,
951                         task.num_samples,
952                         rate_adjustment_policy);
953
954                 // Send the samples to the sound card, then add them to the output.
955                 if (alsa) {
956                         alsa->write(samples_out);
957                 }
958                 if (output_card_index != -1) {
959                         const int64_t av_delay = lrint(global_flags.audio_queue_length_ms * 0.001 * TIMEBASE);  // Corresponds to the delay in ResamplingQueue.
960                         cards[output_card_index].output->send_audio(task.pts_int + av_delay, samples_out);
961                 }
962                 video_encoder->add_audio(task.pts_int, move(samples_out));
963         }
964 }
965
966 void Mixer::release_display_frame(DisplayFrame *frame)
967 {
968         for (GLuint texnum : frame->temp_textures) {
969                 resource_pool->release_2d_texture(texnum);
970         }
971         frame->temp_textures.clear();
972         frame->ready_fence.reset();
973         frame->input_frames.clear();
974 }
975
976 void Mixer::start()
977 {
978         mixer_thread = thread(&Mixer::thread_func, this);
979         audio_thread = thread(&Mixer::audio_thread_func, this);
980 }
981
982 void Mixer::quit()
983 {
984         should_quit = true;
985         audio_task_queue_changed.notify_one();
986         mixer_thread.join();
987         audio_thread.join();
988 }
989
990 void Mixer::transition_clicked(int transition_num)
991 {
992         theme->transition_clicked(transition_num, pts());
993 }
994
995 void Mixer::channel_clicked(int preview_num)
996 {
997         theme->channel_clicked(preview_num);
998 }
999
1000 void Mixer::start_mode_scanning(unsigned card_index)
1001 {
1002         assert(card_index < num_cards);
1003         if (is_mode_scanning[card_index]) {
1004                 return;
1005         }
1006         is_mode_scanning[card_index] = true;
1007         mode_scanlist[card_index].clear();
1008         for (const auto &mode : cards[card_index].capture->get_available_video_modes()) {
1009                 mode_scanlist[card_index].push_back(mode.first);
1010         }
1011         assert(!mode_scanlist[card_index].empty());
1012         mode_scanlist_index[card_index] = 0;
1013         cards[card_index].capture->set_video_mode(mode_scanlist[card_index][0]);
1014         last_mode_scan_change[card_index] = steady_clock::now();
1015 }
1016
1017 Mixer::OutputChannel::~OutputChannel()
1018 {
1019         if (has_current_frame) {
1020                 parent->release_display_frame(&current_frame);
1021         }
1022         if (has_ready_frame) {
1023                 parent->release_display_frame(&ready_frame);
1024         }
1025 }
1026
1027 void Mixer::OutputChannel::output_frame(DisplayFrame frame)
1028 {
1029         // Store this frame for display. Remove the ready frame if any
1030         // (it was seemingly never used).
1031         {
1032                 unique_lock<mutex> lock(frame_mutex);
1033                 if (has_ready_frame) {
1034                         parent->release_display_frame(&ready_frame);
1035                 }
1036                 ready_frame = frame;
1037                 has_ready_frame = true;
1038         }
1039
1040         if (new_frame_ready_callback) {
1041                 new_frame_ready_callback();
1042         }
1043
1044         // Reduce the number of callbacks by filtering duplicates. The reason
1045         // why we bother doing this is that Qt seemingly can get into a state
1046         // where its builds up an essentially unbounded queue of signals,
1047         // consuming more and more memory, and there's no good way of collapsing
1048         // user-defined signals or limiting the length of the queue.
1049         if (transition_names_updated_callback) {
1050                 vector<string> transition_names = global_mixer->get_transition_names();
1051                 bool changed = false;
1052                 if (transition_names.size() != last_transition_names.size()) {
1053                         changed = true;
1054                 } else {
1055                         for (unsigned i = 0; i < transition_names.size(); ++i) {
1056                                 if (transition_names[i] != last_transition_names[i]) {
1057                                         changed = true;
1058                                         break;
1059                                 }
1060                         }
1061                 }
1062                 if (changed) {
1063                         transition_names_updated_callback(transition_names);
1064                         last_transition_names = transition_names;
1065                 }
1066         }
1067         if (name_updated_callback) {
1068                 string name = global_mixer->get_channel_name(channel);
1069                 if (name != last_name) {
1070                         name_updated_callback(name);
1071                         last_name = name;
1072                 }
1073         }
1074         if (color_updated_callback) {
1075                 string color = global_mixer->get_channel_color(channel);
1076                 if (color != last_color) {
1077                         color_updated_callback(color);
1078                         last_color = color;
1079                 }
1080         }
1081 }
1082
1083 bool Mixer::OutputChannel::get_display_frame(DisplayFrame *frame)
1084 {
1085         unique_lock<mutex> lock(frame_mutex);
1086         if (!has_current_frame && !has_ready_frame) {
1087                 return false;
1088         }
1089
1090         if (has_current_frame && has_ready_frame) {
1091                 // We have a new ready frame. Toss the current one.
1092                 parent->release_display_frame(&current_frame);
1093                 has_current_frame = false;
1094         }
1095         if (has_ready_frame) {
1096                 assert(!has_current_frame);
1097                 current_frame = ready_frame;
1098                 ready_frame.ready_fence.reset();  // Drop the refcount.
1099                 ready_frame.input_frames.clear();  // Drop the refcounts.
1100                 has_current_frame = true;
1101                 has_ready_frame = false;
1102         }
1103
1104         *frame = current_frame;
1105         return true;
1106 }
1107
1108 void Mixer::OutputChannel::set_frame_ready_callback(Mixer::new_frame_ready_callback_t callback)
1109 {
1110         new_frame_ready_callback = callback;
1111 }
1112
1113 void Mixer::OutputChannel::set_transition_names_updated_callback(Mixer::transition_names_updated_callback_t callback)
1114 {
1115         transition_names_updated_callback = callback;
1116 }
1117
1118 void Mixer::OutputChannel::set_name_updated_callback(Mixer::name_updated_callback_t callback)
1119 {
1120         name_updated_callback = callback;
1121 }
1122
1123 void Mixer::OutputChannel::set_color_updated_callback(Mixer::color_updated_callback_t callback)
1124 {
1125         color_updated_callback = callback;
1126 }
1127
1128 mutex RefCountedGLsync::fence_lock;