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