]> git.sesse.net Git - nageru/blob - mixer.cpp
Initial implementation of moving the theming logic to Lua. Still lots to do.
[nageru] / mixer.cpp
1 #define WIDTH 1280
2 #define HEIGHT 720
3
4 #undef Success
5
6 #include "mixer.h"
7
8 #include <assert.h>
9 #include <effect.h>
10 #include <effect_chain.h>
11 #include <effect_util.h>
12 #include <epoxy/egl.h>
13 #include <features.h>
14 #include <image_format.h>
15 #include <init.h>
16 #include <overlay_effect.h>
17 #include <padding_effect.h>
18 #include <resample_effect.h>
19 #include <resource_pool.h>
20 #include <saturation_effect.h>
21 #include <stdint.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <sys/time.h>
25 #include <time.h>
26 #include <util.h>
27 #include <white_balance_effect.h>
28 #include <ycbcr.h>
29 #include <ycbcr_input.h>
30 #include <cmath>
31 #include <condition_variable>
32 #include <cstddef>
33 #include <memory>
34 #include <mutex>
35 #include <string>
36 #include <thread>
37 #include <vector>
38
39 #include "bmusb.h"
40 #include "context.h"
41 #include "h264encode.h"
42 #include "pbo_frame_allocator.h"
43 #include "ref_counted_gl_sync.h"
44
45 class QOpenGLContext;
46
47 using namespace movit;
48 using namespace std;
49 using namespace std::placeholders;
50
51 Mixer *global_mixer = nullptr;
52
53 Mixer::Mixer(const QSurfaceFormat &format)
54         : mixer_surface(create_surface(format)),
55           h264_encoder_surface(create_surface(format))
56 {
57         CHECK(init_movit(MOVIT_SHADER_DIR, MOVIT_DEBUG_OFF));
58         check_error();
59
60         resource_pool.reset(new ResourcePool);
61         theme.reset(new Theme("theme.lua", resource_pool.get()));
62         output_channel[OUTPUT_LIVE].parent = this;
63         output_channel[OUTPUT_PREVIEW].parent = this;
64         output_channel[OUTPUT_INPUT0].parent = this;
65         output_channel[OUTPUT_INPUT1].parent = this;
66
67         ImageFormat inout_format;
68         inout_format.color_space = COLORSPACE_sRGB;
69         inout_format.gamma_curve = GAMMA_sRGB;
70
71         YCbCrFormat input_ycbcr_format;
72         input_ycbcr_format.chroma_subsampling_x = 2;
73         input_ycbcr_format.chroma_subsampling_y = 1;
74         input_ycbcr_format.cb_x_position = 0.0;
75         input_ycbcr_format.cr_x_position = 0.0;
76         input_ycbcr_format.cb_y_position = 0.5;
77         input_ycbcr_format.cr_y_position = 0.5;
78         input_ycbcr_format.luma_coefficients = YCBCR_REC_601;
79         input_ycbcr_format.full_range = false;
80
81         // Display chain; shows the live output produced by the main chain (its RGBA version).
82         display_chain.reset(new EffectChain(WIDTH, HEIGHT, resource_pool.get()));
83         check_error();
84         display_input = new FlatInput(inout_format, FORMAT_RGB, GL_UNSIGNED_BYTE, WIDTH, HEIGHT);  // FIXME: GL_UNSIGNED_BYTE is really wrong.
85         display_chain->add_input(display_input);
86         display_chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
87         display_chain->set_dither_bits(0);  // Don't bother.
88         display_chain->finalize();
89
90         // Preview chains (always shows just the inputs for now).
91         preview0_chain.reset(new EffectChain(WIDTH, HEIGHT, resource_pool.get()));
92         check_error();
93         preview0_input = new YCbCrInput(inout_format, input_ycbcr_format, WIDTH, HEIGHT, YCBCR_INPUT_SPLIT_Y_AND_CBCR);
94         preview0_chain->add_input(preview0_input);
95         preview0_chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
96         preview0_chain->set_dither_bits(0);  // Don't bother.
97         preview0_chain->finalize();
98
99         preview1_chain.reset(new EffectChain(WIDTH, HEIGHT, resource_pool.get()));
100         check_error();
101         preview1_input = new YCbCrInput(inout_format, input_ycbcr_format, WIDTH, HEIGHT, YCBCR_INPUT_SPLIT_Y_AND_CBCR);
102         preview1_chain->add_input(preview1_input);
103         preview1_chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
104         preview1_chain->set_dither_bits(0);  // Don't bother.
105         preview1_chain->finalize();
106
107         h264_encoder.reset(new H264Encoder(h264_encoder_surface, WIDTH, HEIGHT, "test.mp4"));
108
109         printf("Configuring first card...\n");
110         cards[0].usb = new BMUSBCapture(0x1edb, 0xbd3b);  // 0xbd4f
111         cards[0].usb->set_frame_callback(std::bind(&Mixer::bm_frame, this, 0, _1, _2, _3, _4, _5, _6, _7));
112         cards[0].frame_allocator.reset(new PBOFrameAllocator(1280 * 750 * 2 + 44, 1280, 720));
113         cards[0].usb->set_video_frame_allocator(cards[0].frame_allocator.get());
114         cards[0].usb->configure_card();
115         cards[0].surface = create_surface(format);
116 #if NUM_CARDS == 2
117         cards[1].surface = create_surface(format);
118 #endif
119
120         if (NUM_CARDS == 2) {
121                 printf("Configuring second card...\n");
122                 cards[1].usb = new BMUSBCapture(0x1edb, 0xbd4f);
123                 cards[1].usb->set_frame_callback(std::bind(&Mixer::bm_frame, this, 1, _1, _2, _3, _4, _5, _6, _7));
124                 cards[1].frame_allocator.reset(new PBOFrameAllocator(1280 * 750 * 2 + 44, 1280, 720));
125                 cards[1].usb->set_video_frame_allocator(cards[1].frame_allocator.get());
126                 cards[1].usb->configure_card();
127         }
128
129         BMUSBCapture::start_bm_thread();
130
131         for (int card_index = 0; card_index < NUM_CARDS; ++card_index) {
132                 cards[card_index].usb->start_bm_capture();
133         }
134
135         //chain->enable_phase_timing(true);
136
137         // Set up stuff for NV12 conversion.
138
139         // Cb/Cr shader.
140         string cbcr_vert_shader = read_file("vs-cbcr.130.vert");
141         string cbcr_frag_shader =
142                 "#version 130 \n"
143                 "in vec2 tc0; \n"
144                 "uniform sampler2D cbcr_tex; \n"
145                 "void main() { \n"
146                 "    gl_FragColor = texture2D(cbcr_tex, tc0); \n"
147                 "} \n";
148         cbcr_program_num = resource_pool->compile_glsl_program(cbcr_vert_shader, cbcr_frag_shader);
149 }
150
151 Mixer::~Mixer()
152 {
153         resource_pool->release_glsl_program(cbcr_program_num);
154         BMUSBCapture::stop_bm_thread();
155 }
156
157 void Mixer::bm_frame(int card_index, uint16_t timecode,
158                      FrameAllocator::Frame video_frame, size_t video_offset, uint16_t video_format,
159                      FrameAllocator::Frame audio_frame, size_t audio_offset, uint16_t audio_format)
160 {
161         CaptureCard *card = &cards[card_index];
162         if (!card->thread_initialized) {
163                 printf("initializing context for bmusb thread %d\n", card_index);
164                 eglBindAPI(EGL_OPENGL_API);
165                 card->context = create_context();
166                 if (!make_current(card->context, card->surface)) {
167                         printf("failed to create bmusb context\n");
168                         exit(1);
169                 }
170                 card->thread_initialized = true;
171         }       
172
173         if (video_frame.len - video_offset != 1280 * 750 * 2) {
174                 printf("dropping frame with wrong length (%ld)\n", video_frame.len - video_offset);
175                 FILE *fp = fopen("frame.raw", "wb");
176                 fwrite(video_frame.data, video_frame.len, 1, fp);
177                 fclose(fp);
178                 //exit(1);
179                 card->usb->get_video_frame_allocator()->release_frame(video_frame);
180                 card->usb->get_audio_frame_allocator()->release_frame(audio_frame);
181                 return;
182         }
183         {
184                 // Wait until the previous frame was consumed.
185                 std::unique_lock<std::mutex> lock(bmusb_mutex);
186                 card->new_data_ready_changed.wait(lock, [card]{ return !card->new_data_ready; });
187         }
188         const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)video_frame.userdata;
189         GLuint pbo = userdata->pbo;
190         check_error();
191         glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, pbo);
192         check_error();
193         glFlushMappedBufferRange(GL_PIXEL_UNPACK_BUFFER, 0, video_frame.size);
194         check_error();
195         //glMemoryBarrier(GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT);
196         //check_error();
197
198         // Upload the textures.
199         glBindTexture(GL_TEXTURE_2D, userdata->tex_y);
200         check_error();
201         glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 1280, 720, GL_RED, GL_UNSIGNED_BYTE, BUFFER_OFFSET((1280 * 750 * 2 + 44) / 2 + 1280 * 25 + 22));
202         check_error();
203         glBindTexture(GL_TEXTURE_2D, userdata->tex_cbcr);
204         check_error();
205         glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 1280/2, 720, GL_RG, GL_UNSIGNED_BYTE, BUFFER_OFFSET(1280 * 25 + 22));
206         check_error();
207         glBindTexture(GL_TEXTURE_2D, 0);
208         check_error();
209         GLsync fence = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, /*flags=*/0);              
210         check_error();
211         assert(fence != nullptr);
212         {
213                 std::unique_lock<std::mutex> lock(bmusb_mutex);
214                 card->new_data_ready = true;
215                 card->new_frame = RefCountedFrame(video_frame);
216                 card->new_data_ready_fence = fence;
217                 card->new_data_ready_changed.notify_all();
218         }
219
220         // Video frame will be released when last user of card->new_frame goes out of scope.
221         card->usb->get_audio_frame_allocator()->release_frame(audio_frame);
222 }
223         
224 void Mixer::place_rectangle(Effect *resample_effect, Effect *padding_effect, float x0, float y0, float x1, float y1)
225 {
226         float srcx0 = 0.0f;
227         float srcx1 = 1.0f;
228         float srcy0 = 0.0f;
229         float srcy1 = 1.0f;
230
231         // Cull.
232         if (x0 > 1280.0 || x1 < 0.0 || y0 > 720.0 || y1 < 0.0) {
233                 CHECK(resample_effect->set_int("width", 1));
234                 CHECK(resample_effect->set_int("height", 1));
235                 CHECK(resample_effect->set_float("zoom_x", 1280.0));
236                 CHECK(resample_effect->set_float("zoom_y", 720.0));
237                 CHECK(padding_effect->set_int("left", 2000));
238                 CHECK(padding_effect->set_int("top", 2000));
239                 return; 
240         }
241
242         // Clip. (TODO: Clip on upper/left sides, too.)
243         if (x1 > 1280.0) {
244                 srcx1 = (1280.0 - x0) / (x1 - x0);
245                 x1 = 1280.0;
246         }
247         if (y1 > 720.0) {
248                 srcy1 = (720.0 - y0) / (y1 - y0);
249                 y1 = 720.0;
250         }
251
252         float x_subpixel_offset = x0 - floor(x0);
253         float y_subpixel_offset = y0 - floor(y0);
254
255         // Resampling must be to an integral number of pixels. Round up,
256         // and then add an extra pixel so we have some leeway for the border.
257         int width = int(ceil(x1 - x0)) + 1;
258         int height = int(ceil(y1 - y0)) + 1;
259         CHECK(resample_effect->set_int("width", width));
260         CHECK(resample_effect->set_int("height", height));
261
262         // Correct the discrepancy with zoom. (This will leave a small
263         // excess edge of pixels and subpixels, which we'll correct for soon.)
264         float zoom_x = (x1 - x0) / (width * (srcx1 - srcx0));
265         float zoom_y = (y1 - y0) / (height * (srcy1 - srcy0));
266         CHECK(resample_effect->set_float("zoom_x", zoom_x));
267         CHECK(resample_effect->set_float("zoom_y", zoom_y));
268         CHECK(resample_effect->set_float("zoom_center_x", 0.0f));
269         CHECK(resample_effect->set_float("zoom_center_y", 0.0f));
270
271         // Padding must also be to a whole-pixel offset.
272         CHECK(padding_effect->set_int("left", floor(x0)));
273         CHECK(padding_effect->set_int("top", floor(y0)));
274
275         // Correct _that_ discrepancy by subpixel offset in the resampling.
276         CHECK(resample_effect->set_float("left", -x_subpixel_offset / zoom_x));
277         CHECK(resample_effect->set_float("top", -y_subpixel_offset / zoom_y));
278
279         // Finally, adjust the border so it is exactly where we want it.
280         CHECK(padding_effect->set_float("border_offset_left", x_subpixel_offset));
281         CHECK(padding_effect->set_float("border_offset_right", x1 - (floor(x0) + width)));
282         CHECK(padding_effect->set_float("border_offset_top", y_subpixel_offset));
283         CHECK(padding_effect->set_float("border_offset_bottom", y1 - (floor(y0) + height)));
284 }
285         
286 void Mixer::thread_func()
287 {
288         eglBindAPI(EGL_OPENGL_API);
289         QOpenGLContext *context = create_context();
290         if (!make_current(context, mixer_surface)) {
291                 printf("oops\n");
292                 exit(1);
293         }
294
295         struct timespec start, now;
296         clock_gettime(CLOCK_MONOTONIC, &start);
297
298         while (!should_quit) {
299                 ++frame;
300
301                 //int width0 = lrintf(848 * (1.0 + 0.2 * sin(frame * 0.02)));
302                 int width0 = 848;
303                 int height0 = lrintf(width0 * 9.0 / 16.0);
304
305                 //float top0 = 96 + 48 * sin(frame * 0.005);
306                 //float left0 = 96 + 48 * cos(frame * 0.006);
307                 float top0 = 48;
308                 float left0 = 16;
309                 float bottom0 = top0 + height0;
310                 float right0 = left0 + width0;
311
312                 int width1 = 384;
313                 int height1 = 216;
314         
315                 float bottom1 = 720 - 48;
316                 float right1 = 1280 - 16;
317                 float top1 = bottom1 - height1;
318                 float left1 = right1 - width1;
319         
320                 if (current_source == SOURCE_INPUT1) {
321                         top0 = 0.0;
322                         bottom0 = HEIGHT;
323                         left0 = 0.0;
324                         right0 = WIDTH;
325
326                         top1 = HEIGHT + 10;
327                         bottom1 = HEIGHT + 20;
328                         left1 = WIDTH + 10;
329                         right1 = WIDTH + 20;
330                 } else if (current_source == SOURCE_INPUT2) {
331                         top1 = 0.0;
332                         bottom1 = HEIGHT;
333                         left1 = 0.0;
334                         right1 = WIDTH;
335
336                         top0 = HEIGHT + 10;
337                         bottom0 = HEIGHT + 20;
338                         left0 = WIDTH + 10;
339                         right0 = WIDTH + 20;
340                 } else {
341                         float t = 0.5 + 0.5 * cos(frame * 0.006);
342                         float scale0 = 1.0 + t * (1280.0 / 848.0 - 1.0);
343                         float tx0 = 0.0 + t * (-16.0 * scale0);
344                         float ty0 = 0.0 + t * (-48.0 * scale0);
345
346                         top0 = top0 * scale0 + ty0;
347                         bottom0 = bottom0 * scale0 + ty0;
348                         left0 = left0 * scale0 + tx0;
349                         right0 = right0 * scale0 + tx0;
350
351                         top1 = top1 * scale0 + ty0;
352                         bottom1 = bottom1 * scale0 + ty0;
353                         left1 = left1 * scale0 + tx0;
354                         right1 = right1 * scale0 + tx0;
355                 }
356
357 #if 0
358                 place_rectangle(resample_effect, padding_effect, left0, top0, right0, bottom0);
359                 place_rectangle(resample2_effect, padding2_effect, left1, top1, right1, bottom1);
360 #endif
361
362                 CaptureCard card_copy[NUM_CARDS];
363
364                 {
365                         std::unique_lock<std::mutex> lock(bmusb_mutex);
366
367                         // The first card is the master timer, so wait for it to have a new frame.
368                         // TODO: Make configurable, and with a timeout.
369                         cards[0].new_data_ready_changed.wait(lock, [this]{ return cards[0].new_data_ready; });
370
371                         for (int card_index = 0; card_index < NUM_CARDS; ++card_index) {
372                                 CaptureCard *card = &cards[card_index];
373                                 card_copy[card_index].usb = card->usb;
374                                 card_copy[card_index].new_data_ready = card->new_data_ready;
375                                 card_copy[card_index].new_frame = card->new_frame;
376                                 card_copy[card_index].new_data_ready_fence = card->new_data_ready_fence;
377                                 card->new_data_ready = false;
378                                 card->new_data_ready_changed.notify_all();
379                         }
380                 }
381
382                 for (int card_index = 0; card_index < NUM_CARDS; ++card_index) {
383                         CaptureCard *card = &card_copy[card_index];
384                         if (!card->new_data_ready)
385                                 continue;
386
387                         assert(card->new_frame != nullptr);
388                         bmusb_current_rendering_frame[card_index] = card->new_frame;
389                         check_error();
390
391                         // The new texture might still be uploaded,
392                         // tell the GPU to wait until it's there.
393                         if (card->new_data_ready_fence)
394                                 glWaitSync(card->new_data_ready_fence, /*flags=*/0, GL_TIMEOUT_IGNORED);
395                         check_error();
396                         glDeleteSync(card->new_data_ready_fence);
397                         check_error();
398                         const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)card->new_frame->userdata;
399                         theme->set_input_textures(card_index, userdata->tex_y, userdata->tex_cbcr);
400                 }
401
402                 // Get the main chain from the theme, and set its state immediately.
403                 pair<EffectChain *, function<void()>> theme_main_chain = theme->get_chain(0, frame / 60.0f, WIDTH, HEIGHT);
404                 EffectChain *chain = theme_main_chain.first;
405                 theme_main_chain.second();
406
407                 GLuint y_tex, cbcr_tex;
408                 bool got_frame = h264_encoder->begin_frame(&y_tex, &cbcr_tex);
409                 assert(got_frame);
410
411                 // Render main chain.
412                 GLuint cbcr_full_tex = resource_pool->create_2d_texture(GL_RG8, WIDTH, HEIGHT);
413                 GLuint rgba_tex = resource_pool->create_2d_texture(GL_RGB565, WIDTH, HEIGHT);  // Saves texture bandwidth, although dithering gets messed up.
414                 GLuint fbo = resource_pool->create_fbo(y_tex, cbcr_full_tex, rgba_tex);
415                 chain->render_to_fbo(fbo, WIDTH, HEIGHT);
416                 resource_pool->release_fbo(fbo);
417
418                 subsample_chroma(cbcr_full_tex, cbcr_tex);
419                 resource_pool->release_2d_texture(cbcr_full_tex);
420
421                 // Set the right state for rgba_tex.
422                 glBindFramebuffer(GL_FRAMEBUFFER, 0);
423                 glBindTexture(GL_TEXTURE_2D, rgba_tex);
424                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
425                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
426                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
427
428                 RefCountedGLsync fence(GL_SYNC_GPU_COMMANDS_COMPLETE, /*flags=*/0);
429                 check_error();
430
431                 // Make sure the H.264 gets a reference to all the
432                 // input frames needed, so that they are not released back
433                 // until the rendering is done.
434                 vector<RefCountedFrame> input_frames;
435                 for (int card_index = 0; card_index < NUM_CARDS; ++card_index) {
436                         input_frames.push_back(bmusb_current_rendering_frame[card_index]);
437                 }
438                 h264_encoder->end_frame(fence, input_frames);
439
440                 // The live frame just shows the RGBA texture we just rendered.
441                 // It owns rgba_tex now.
442                 DisplayFrame live_frame;
443                 live_frame.chain = display_chain.get();
444                 live_frame.setup_chain = [this, rgba_tex]{
445                         display_input->set_texture_num(rgba_tex);
446                 };
447                 live_frame.ready_fence = fence;
448                 live_frame.input_frames = {};
449                 live_frame.temp_textures = { rgba_tex };
450                 output_channel[OUTPUT_LIVE].output_frame(live_frame);
451
452                 // The preview frame shows the first input. Note that the textures
453                 // are owned by the input frame, not the display frame.
454                 if (bmusb_current_rendering_frame[0] != nullptr) {
455                         const PBOFrameAllocator::Userdata *input0_userdata = (const PBOFrameAllocator::Userdata *)bmusb_current_rendering_frame[0]->userdata;
456                         GLuint input0_y_tex = input0_userdata->tex_y;
457                         GLuint input0_cbcr_tex = input0_userdata->tex_cbcr;
458                         DisplayFrame preview0_frame;
459                         preview0_frame.chain = preview0_chain.get();
460                         preview0_frame.setup_chain = [this, input0_y_tex, input0_cbcr_tex]{
461                                 preview0_input->set_texture_num(0, input0_y_tex);
462                                 preview0_input->set_texture_num(1, input0_cbcr_tex);
463                         };
464                         preview0_frame.ready_fence = fence;
465                         preview0_frame.input_frames = { bmusb_current_rendering_frame[0] };
466                         preview0_frame.temp_textures = {};
467                         output_channel[OUTPUT_PREVIEW].output_frame(preview0_frame);
468                         output_channel[OUTPUT_INPUT0].output_frame(preview0_frame);
469                 }
470
471                 // Same for the other preview.
472                 // TODO: Use a for loop. Gah.
473                 if (bmusb_current_rendering_frame[1] != nullptr) {
474                         const PBOFrameAllocator::Userdata *input1_userdata = (const PBOFrameAllocator::Userdata *)bmusb_current_rendering_frame[1]->userdata;
475                         GLuint input1_y_tex = input1_userdata->tex_y;
476                         GLuint input1_cbcr_tex = input1_userdata->tex_cbcr;
477                         DisplayFrame preview1_frame;
478                         preview1_frame.chain = preview1_chain.get();
479                         preview1_frame.setup_chain = [this, input1_y_tex, input1_cbcr_tex]{
480                                 preview1_input->set_texture_num(0, input1_y_tex);
481                                 preview1_input->set_texture_num(1, input1_cbcr_tex);
482                         };
483                         preview1_frame.ready_fence = fence;
484                         preview1_frame.input_frames = { bmusb_current_rendering_frame[1] };
485                         preview1_frame.temp_textures = {};
486                         output_channel[OUTPUT_INPUT1].output_frame(preview1_frame);
487                 }
488
489                 clock_gettime(CLOCK_MONOTONIC, &now);
490                 double elapsed = now.tv_sec - start.tv_sec +
491                         1e-9 * (now.tv_nsec - start.tv_nsec);
492                 if (frame % 100 == 0) {
493                         printf("%d frames in %.3f seconds = %.1f fps (%.1f ms/frame)\n",
494                                 frame, elapsed, frame / elapsed,
495                                 1e3 * elapsed / frame);
496                 //      chain->print_phase_timing();
497                 }
498
499                 // Reset every 100 frames, so that local variations in frame times
500                 // (especially for the first few frames, when the shaders are
501                 // compiled etc.) don't make it hard to measure for the entire
502                 // remaining duration of the program.
503                 if (frame == 10000) {
504                         frame = 0;
505                         start = now;
506                 }
507                 check_error();
508         }
509 }
510
511 void Mixer::subsample_chroma(GLuint src_tex, GLuint dst_tex)
512 {
513         GLuint vao;
514         glGenVertexArrays(1, &vao);
515         check_error();
516
517         float vertices[] = {
518                 0.0f, 2.0f,
519                 0.0f, 0.0f,
520                 2.0f, 0.0f
521         };
522
523         glBindVertexArray(vao);
524         check_error();
525
526         // Extract Cb/Cr.
527         GLuint fbo = resource_pool->create_fbo(dst_tex);
528         glBindFramebuffer(GL_FRAMEBUFFER, fbo);
529         glViewport(0, 0, WIDTH/2, HEIGHT/2);
530         check_error();
531
532         glUseProgram(cbcr_program_num);
533         check_error();
534
535         glActiveTexture(GL_TEXTURE0);
536         check_error();
537         glBindTexture(GL_TEXTURE_2D, src_tex);
538         check_error();
539         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
540         check_error();
541         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
542         check_error();
543         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
544         check_error();
545
546         float chroma_offset_0[] = { -0.5f / WIDTH, 0.0f };
547         set_uniform_vec2(cbcr_program_num, "foo", "chroma_offset_0", chroma_offset_0);
548
549         GLuint position_vbo = fill_vertex_attribute(cbcr_program_num, "position", 2, GL_FLOAT, sizeof(vertices), vertices);
550         GLuint texcoord_vbo = fill_vertex_attribute(cbcr_program_num, "texcoord", 2, GL_FLOAT, sizeof(vertices), vertices);  // Same as vertices.
551
552         glDrawArrays(GL_TRIANGLES, 0, 3);
553         check_error();
554
555         cleanup_vertex_attribute(cbcr_program_num, "position", position_vbo);
556         cleanup_vertex_attribute(cbcr_program_num, "texcoord", texcoord_vbo);
557
558         glUseProgram(0);
559         check_error();
560
561         resource_pool->release_fbo(fbo);
562         glDeleteVertexArrays(1, &vao);
563 }
564
565 void Mixer::release_display_frame(DisplayFrame *frame)
566 {
567         for (GLuint texnum : frame->temp_textures) {
568                 resource_pool->release_2d_texture(texnum);
569         }
570         frame->temp_textures.clear();
571         frame->ready_fence.reset();
572         frame->input_frames.clear();
573 }
574
575 void Mixer::start()
576 {
577         mixer_thread = std::thread(&Mixer::thread_func, this);
578 }
579
580 void Mixer::quit()
581 {
582         should_quit = true;
583         mixer_thread.join();
584 }
585
586 void Mixer::cut(Source source)
587 {
588         current_source = source;
589 }
590
591 void Mixer::OutputChannel::output_frame(DisplayFrame frame)
592 {
593         // Store this frame for display. Remove the ready frame if any
594         // (it was seemingly never used).
595         {
596                 std::unique_lock<std::mutex> lock(frame_mutex);
597                 if (has_ready_frame) {
598                         parent->release_display_frame(&ready_frame);
599                 }
600                 ready_frame = frame;
601                 has_ready_frame = true;
602         }
603
604         if (has_new_frame_ready_callback) {
605                 new_frame_ready_callback();
606         }
607 }
608
609 bool Mixer::OutputChannel::get_display_frame(DisplayFrame *frame)
610 {
611         std::unique_lock<std::mutex> lock(frame_mutex);
612         if (!has_current_frame && !has_ready_frame) {
613                 return false;
614         }
615
616         if (has_current_frame && has_ready_frame) {
617                 // We have a new ready frame. Toss the current one.
618                 parent->release_display_frame(&current_frame);
619                 has_current_frame = false;
620         }
621         if (has_ready_frame) {
622                 assert(!has_current_frame);
623                 current_frame = ready_frame;
624                 ready_frame.ready_fence.reset();  // Drop the refcount.
625                 ready_frame.input_frames.clear();  // Drop the refcounts.
626                 has_current_frame = true;
627                 has_ready_frame = false;
628         }
629
630         *frame = current_frame;
631         return true;
632 }
633
634 void Mixer::OutputChannel::set_frame_ready_callback(Mixer::new_frame_ready_callback_t callback)
635 {
636         new_frame_ready_callback = callback;
637         has_new_frame_ready_callback = true;
638 }