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