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