10 #include <effect_chain.h>
11 #include <effect_util.h>
12 #include <epoxy/egl.h>
14 #include <image_format.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>
27 #include <white_balance_effect.h>
29 #include <ycbcr_input.h>
31 #include <condition_variable>
41 #include "h264encode.h"
42 #include "pbo_frame_allocator.h"
43 #include "ref_counted_gl_sync.h"
47 using namespace movit;
49 using namespace std::placeholders;
51 Mixer *global_mixer = nullptr;
53 Mixer::Mixer(const QSurfaceFormat &format)
54 : mixer_surface(create_surface(format)),
55 h264_encoder_surface(create_surface(format))
57 CHECK(init_movit(MOVIT_SHADER_DIR, MOVIT_DEBUG_OFF));
60 chain.reset(new EffectChain(WIDTH, HEIGHT));
63 ImageFormat inout_format;
64 inout_format.color_space = COLORSPACE_sRGB;
65 inout_format.gamma_curve = GAMMA_sRGB;
67 YCbCrFormat ycbcr_format;
68 ycbcr_format.chroma_subsampling_x = 2;
69 ycbcr_format.chroma_subsampling_y = 1;
70 ycbcr_format.cb_x_position = 0.0;
71 ycbcr_format.cr_x_position = 0.0;
72 ycbcr_format.cb_y_position = 0.5;
73 ycbcr_format.cr_y_position = 0.5;
74 ycbcr_format.luma_coefficients = YCBCR_REC_601;
75 ycbcr_format.full_range = false;
77 input[0] = new YCbCrInput(inout_format, ycbcr_format, WIDTH, HEIGHT, YCBCR_INPUT_SPLIT_Y_AND_CBCR);
78 chain->add_input(input[0]);
79 input[1] = new YCbCrInput(inout_format, ycbcr_format, WIDTH, HEIGHT, YCBCR_INPUT_SPLIT_Y_AND_CBCR);
80 chain->add_input(input[1]);
81 resample_effect = chain->add_effect(new ResampleEffect(), input[0]);
82 padding_effect = chain->add_effect(new IntegralPaddingEffect());
83 float border_color[] = { 0.0f, 0.0f, 0.0f, 1.0f };
84 CHECK(padding_effect->set_vec4("border_color", border_color));
86 resample2_effect = chain->add_effect(new ResampleEffect(), input[1]);
87 Effect *saturation_effect = chain->add_effect(new SaturationEffect());
88 CHECK(saturation_effect->set_float("saturation", 0.3f));
89 Effect *wb_effect = chain->add_effect(new WhiteBalanceEffect());
90 CHECK(wb_effect->set_float("output_color_temperature", 3500.0));
91 padding2_effect = chain->add_effect(new IntegralPaddingEffect());
93 chain->add_effect(new OverlayEffect(), padding_effect, padding2_effect);
95 ycbcr_format.chroma_subsampling_x = 1;
97 chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
98 chain->add_ycbcr_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED, ycbcr_format, YCBCR_OUTPUT_SPLIT_Y_AND_CBCR);
99 chain->set_dither_bits(8);
100 chain->set_output_origin(OUTPUT_ORIGIN_TOP_LEFT);
103 h264_encoder.reset(new H264Encoder(h264_encoder_surface, WIDTH, HEIGHT, "test.mp4"));
105 printf("Configuring first card...\n");
106 cards[0].usb = new BMUSBCapture(0x1edb, 0xbd3b); // 0xbd4f
107 cards[0].usb->set_frame_callback(std::bind(&Mixer::bm_frame, this, 0, _1, _2, _3, _4, _5, _6, _7));
108 cards[0].frame_allocator.reset(new PBOFrameAllocator(1280 * 750 * 2 + 44));
109 cards[0].usb->set_video_frame_allocator(cards[0].frame_allocator.get());
110 cards[0].usb->configure_card();
111 cards[0].surface = create_surface(format);
113 cards[1].surface = create_surface(format);
116 if (NUM_CARDS == 2) {
117 printf("Configuring second card...\n");
118 cards[1].usb = new BMUSBCapture(0x1edb, 0xbd4f);
119 cards[1].usb->set_frame_callback(std::bind(&Mixer::bm_frame, this, 1, _1, _2, _3, _4, _5, _6, _7));
120 cards[1].frame_allocator.reset(new PBOFrameAllocator(1280 * 750 * 2 + 44));
121 cards[1].usb->set_video_frame_allocator(cards[1].frame_allocator.get());
122 cards[1].usb->configure_card();
125 BMUSBCapture::start_bm_thread();
127 for (int card_index = 0; card_index < NUM_CARDS; ++card_index) {
128 cards[card_index].usb->start_bm_capture();
129 input[card_index]->set_pixel_data(0, nullptr, 0);
130 input[card_index]->set_pixel_data(1, nullptr, 0);
133 //chain->enable_phase_timing(true);
135 // Set up stuff for NV12 conversion.
136 resource_pool = chain->get_resource_pool();
139 string cbcr_vert_shader = read_file("vs-cbcr.130.vert");
140 string cbcr_frag_shader =
143 "uniform sampler2D cbcr_tex; \n"
145 " gl_FragColor = texture2D(cbcr_tex, tc0); \n"
147 cbcr_program_num = resource_pool->compile_glsl_program(cbcr_vert_shader, cbcr_frag_shader);
152 resource_pool->release_glsl_program(cbcr_program_num);
153 BMUSBCapture::stop_bm_thread();
156 void Mixer::bm_frame(int card_index, uint16_t timecode,
157 FrameAllocator::Frame video_frame, size_t video_offset, uint16_t video_format,
158 FrameAllocator::Frame audio_frame, size_t audio_offset, uint16_t audio_format)
160 CaptureCard *card = &cards[card_index];
161 if (!card->thread_initialized) {
162 printf("initializing context for bmusb thread %d\n", card_index);
163 eglBindAPI(EGL_OPENGL_API);
164 card->context = create_context();
165 if (!make_current(card->context, card->surface)) {
166 printf("failed to create bmusb context\n");
169 card->thread_initialized = true;
172 if (video_frame.len - video_offset != 1280 * 750 * 2) {
173 printf("dropping frame with wrong length (%ld)\n", video_frame.len - video_offset);
174 FILE *fp = fopen("frame.raw", "wb");
175 fwrite(video_frame.data, video_frame.len, 1, fp);
178 card->usb->get_video_frame_allocator()->release_frame(video_frame);
179 card->usb->get_audio_frame_allocator()->release_frame(audio_frame);
183 // Wait until the previous frame was consumed.
184 std::unique_lock<std::mutex> lock(bmusb_mutex);
185 card->new_data_ready_changed.wait(lock, [card]{ return !card->new_data_ready; });
187 GLuint pbo = (GLint)(intptr_t)video_frame.userdata;
189 glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, pbo);
191 glFlushMappedBufferRange(GL_PIXEL_UNPACK_BUFFER, 0, video_frame.size);
193 //glMemoryBarrier(GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT);
195 GLsync fence = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, /*flags=*/0);
197 assert(fence != nullptr);
199 std::unique_lock<std::mutex> lock(bmusb_mutex);
200 card->new_data_ready = true;
201 card->new_frame = video_frame;
202 card->new_data_ready_fence = fence;
203 card->new_data_ready_changed.notify_all();
206 // Video frame will be released later.
207 card->usb->get_audio_frame_allocator()->release_frame(audio_frame);
210 void Mixer::place_rectangle(Effect *resample_effect, Effect *padding_effect, float x0, float y0, float x1, float y1)
218 if (x0 > 1280.0 || x1 < 0.0 || y0 > 720.0 || y1 < 0.0) {
219 CHECK(resample_effect->set_int("width", 1));
220 CHECK(resample_effect->set_int("height", 1));
221 CHECK(resample_effect->set_float("zoom_x", 1280.0));
222 CHECK(resample_effect->set_float("zoom_y", 720.0));
223 CHECK(padding_effect->set_int("left", 2000));
224 CHECK(padding_effect->set_int("top", 2000));
228 // Clip. (TODO: Clip on upper/left sides, too.)
230 srcx1 = (1280.0 - x0) / (x1 - x0);
234 srcy1 = (720.0 - y0) / (y1 - y0);
238 float x_subpixel_offset = x0 - floor(x0);
239 float y_subpixel_offset = y0 - floor(y0);
241 // Resampling must be to an integral number of pixels. Round up,
242 // and then add an extra pixel so we have some leeway for the border.
243 int width = int(ceil(x1 - x0)) + 1;
244 int height = int(ceil(y1 - y0)) + 1;
245 CHECK(resample_effect->set_int("width", width));
246 CHECK(resample_effect->set_int("height", height));
248 // Correct the discrepancy with zoom. (This will leave a small
249 // excess edge of pixels and subpixels, which we'll correct for soon.)
250 float zoom_x = (x1 - x0) / (width * (srcx1 - srcx0));
251 float zoom_y = (y1 - y0) / (height * (srcy1 - srcy0));
252 CHECK(resample_effect->set_float("zoom_x", zoom_x));
253 CHECK(resample_effect->set_float("zoom_y", zoom_y));
254 CHECK(resample_effect->set_float("zoom_center_x", 0.0f));
255 CHECK(resample_effect->set_float("zoom_center_y", 0.0f));
257 // Padding must also be to a whole-pixel offset.
258 CHECK(padding_effect->set_int("left", floor(x0)));
259 CHECK(padding_effect->set_int("top", floor(y0)));
261 // Correct _that_ discrepancy by subpixel offset in the resampling.
262 CHECK(resample_effect->set_float("left", -x_subpixel_offset / zoom_x));
263 CHECK(resample_effect->set_float("top", -y_subpixel_offset / zoom_y));
265 // Finally, adjust the border so it is exactly where we want it.
266 CHECK(padding_effect->set_float("border_offset_left", x_subpixel_offset));
267 CHECK(padding_effect->set_float("border_offset_right", x1 - (floor(x0) + width)));
268 CHECK(padding_effect->set_float("border_offset_top", y_subpixel_offset));
269 CHECK(padding_effect->set_float("border_offset_bottom", y1 - (floor(y0) + height)));
272 void Mixer::thread_func()
274 eglBindAPI(EGL_OPENGL_API);
275 QOpenGLContext *context = create_context();
276 if (!make_current(context, mixer_surface)) {
281 struct timespec start, now;
282 clock_gettime(CLOCK_MONOTONIC, &start);
284 while (!should_quit) {
287 //int width0 = lrintf(848 * (1.0 + 0.2 * sin(frame * 0.02)));
289 int height0 = lrintf(width0 * 9.0 / 16.0);
291 //float top0 = 96 + 48 * sin(frame * 0.005);
292 //float left0 = 96 + 48 * cos(frame * 0.006);
295 float bottom0 = top0 + height0;
296 float right0 = left0 + width0;
301 float bottom1 = 720 - 48;
302 float right1 = 1280 - 16;
303 float top1 = bottom1 - height1;
304 float left1 = right1 - width1;
306 if (current_source == SOURCE_INPUT1) {
313 bottom1 = HEIGHT + 20;
316 } else if (current_source == SOURCE_INPUT2) {
323 bottom0 = HEIGHT + 20;
327 float t = 0.5 + 0.5 * cos(frame * 0.006);
328 float scale0 = 1.0 + t * (1280.0 / 848.0 - 1.0);
329 float tx0 = 0.0 + t * (-16.0 * scale0);
330 float ty0 = 0.0 + t * (-48.0 * scale0);
332 top0 = top0 * scale0 + ty0;
333 bottom0 = bottom0 * scale0 + ty0;
334 left0 = left0 * scale0 + tx0;
335 right0 = right0 * scale0 + tx0;
337 top1 = top1 * scale0 + ty0;
338 bottom1 = bottom1 * scale0 + ty0;
339 left1 = left1 * scale0 + tx0;
340 right1 = right1 * scale0 + tx0;
343 place_rectangle(resample_effect, padding_effect, left0, top0, right0, bottom0);
344 place_rectangle(resample2_effect, padding2_effect, left1, top1, right1, bottom1);
346 CaptureCard card_copy[NUM_CARDS];
349 std::unique_lock<std::mutex> lock(bmusb_mutex);
351 // The first card is the master timer, so wait for it to have a new frame.
352 // TODO: Make configurable, and with a timeout.
353 cards[0].new_data_ready_changed.wait(lock, [this]{ return cards[0].new_data_ready; });
355 for (int card_index = 0; card_index < NUM_CARDS; ++card_index) {
356 CaptureCard *card = &cards[card_index];
357 card_copy[card_index].usb = card->usb;
358 card_copy[card_index].new_data_ready = card->new_data_ready;
359 card_copy[card_index].new_frame = card->new_frame;
360 card_copy[card_index].new_data_ready_fence = card->new_data_ready_fence;
361 card->new_data_ready = false;
362 card->new_data_ready_changed.notify_all();
366 vector<FrameAllocator::Frame> input_frames_to_release;
368 for (int card_index = 0; card_index < NUM_CARDS; ++card_index) {
369 CaptureCard *card = &card_copy[card_index];
370 if (!card->new_data_ready)
373 // Now we're done with the previous frame, so we can definitely
374 // release it when this is done rendering. (Actually, we could do
375 // it one frame earlier, but before we have a new one, there's no
376 // knowing when the current one is released.)
377 if (bmusb_current_rendering_frame[card_index].owner != nullptr) {
378 input_frames_to_release.push_back(bmusb_current_rendering_frame[card_index]);
380 bmusb_current_rendering_frame[card_index] = card->new_frame;
383 // The new texture might still be uploaded,
384 // tell the GPU to wait until it's there.
385 if (card->new_data_ready_fence)
386 glWaitSync(card->new_data_ready_fence, /*flags=*/0, GL_TIMEOUT_IGNORED);
388 glDeleteSync(card->new_data_ready_fence);
390 GLint input_tex_pbo = (GLint)(intptr_t)card->new_frame.userdata;
391 input[card_index]->set_pixel_data(0, (unsigned char *)BUFFER_OFFSET((1280 * 750 * 2 + 44) / 2 + 1280 * 25 + 22), input_tex_pbo);
392 input[card_index]->set_pixel_data(1, (unsigned char *)BUFFER_OFFSET(1280 * 25 + 22), input_tex_pbo);
394 if (NUM_CARDS == 1) {
395 // Set to the other one, too.
396 input[1]->set_pixel_data(0, (unsigned char *)BUFFER_OFFSET((1280 * 750 * 2 + 44) / 2 + 1280 * 25 + 22), input_tex_pbo);
397 input[1]->set_pixel_data(1, (unsigned char *)BUFFER_OFFSET(1280 * 25 + 22), input_tex_pbo);
401 GLuint y_tex, cbcr_tex;
402 bool got_frame = h264_encoder->begin_frame(&y_tex, &cbcr_tex);
406 GLuint cbcr_full_tex = resource_pool->create_2d_texture(GL_RG8, WIDTH, HEIGHT);
407 GLuint rgba_tex = resource_pool->create_2d_texture(GL_RGBA8, WIDTH, HEIGHT);
408 GLuint fbo = resource_pool->create_fbo(y_tex, cbcr_full_tex, rgba_tex);
409 chain->render_to_fbo(fbo, WIDTH, HEIGHT);
410 resource_pool->release_fbo(fbo);
412 subsample_chroma(cbcr_full_tex, cbcr_tex);
413 resource_pool->release_2d_texture(cbcr_full_tex);
415 RefCountedGLsync fence(GL_SYNC_GPU_COMMANDS_COMPLETE, /*flags=*/0);
417 h264_encoder->end_frame(fence, input_frames_to_release);
419 // Store this frame for display. Remove the ready frame if any
420 // (it was seemingly never used).
422 std::unique_lock<std::mutex> lock(display_frame_mutex);
423 if (has_ready_display_frame) {
424 resource_pool->release_2d_texture(ready_display_frame.texnum);
425 ready_display_frame.ready_fence.reset();
427 ready_display_frame.texnum = rgba_tex;
428 ready_display_frame.ready_fence = fence;
429 has_ready_display_frame = true;
432 if (has_new_frame_ready_callback) {
433 new_frame_ready_callback();
436 clock_gettime(CLOCK_MONOTONIC, &now);
437 double elapsed = now.tv_sec - start.tv_sec +
438 1e-9 * (now.tv_nsec - start.tv_nsec);
439 if (frame % 100 == 0) {
440 printf("%d frames in %.3f seconds = %.1f fps (%.1f ms/frame)\n",
441 frame, elapsed, frame / elapsed,
442 1e3 * elapsed / frame);
443 // chain->print_phase_timing();
446 // Reset every 100 frames, so that local variations in frame times
447 // (especially for the first few frames, when the shaders are
448 // compiled etc.) don't make it hard to measure for the entire
449 // remaining duration of the program.
450 if (frame == 10000) {
458 void Mixer::subsample_chroma(GLuint src_tex, GLuint dst_tex)
461 glGenVertexArrays(1, &vao);
470 glBindVertexArray(vao);
474 GLuint fbo = resource_pool->create_fbo(dst_tex);
475 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
476 glViewport(0, 0, WIDTH/2, HEIGHT/2);
479 glUseProgram(cbcr_program_num);
482 glActiveTexture(GL_TEXTURE0);
484 glBindTexture(GL_TEXTURE_2D, src_tex);
486 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
488 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
490 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
493 float chroma_offset_0[] = { -0.5f / WIDTH, 0.0f };
494 set_uniform_vec2(cbcr_program_num, "foo", "chroma_offset_0", chroma_offset_0);
496 GLuint position_vbo = fill_vertex_attribute(cbcr_program_num, "position", 2, GL_FLOAT, sizeof(vertices), vertices);
497 GLuint texcoord_vbo = fill_vertex_attribute(cbcr_program_num, "texcoord", 2, GL_FLOAT, sizeof(vertices), vertices); // Same as vertices.
499 glDrawArrays(GL_TRIANGLES, 0, 3);
502 cleanup_vertex_attribute(cbcr_program_num, "position", position_vbo);
503 cleanup_vertex_attribute(cbcr_program_num, "texcoord", texcoord_vbo);
508 resource_pool->release_fbo(fbo);
509 glDeleteVertexArrays(1, &vao);
512 bool Mixer::get_display_frame(DisplayFrame *frame)
514 std::unique_lock<std::mutex> lock(display_frame_mutex);
515 if (!has_current_display_frame && !has_ready_display_frame) {
519 if (has_current_display_frame && has_ready_display_frame) {
520 // We have a new ready frame. Toss the current one.
521 resource_pool->release_2d_texture(current_display_frame.texnum);
522 current_display_frame.ready_fence.reset();
523 has_current_display_frame = false;
525 if (has_ready_display_frame) {
526 assert(!has_current_display_frame);
527 current_display_frame = ready_display_frame;
528 ready_display_frame.ready_fence.reset(); // Drop the refcount.
529 has_current_display_frame = true;
530 has_ready_display_frame = false;
533 *frame = current_display_frame;
537 void Mixer::set_frame_ready_fallback(new_frame_ready_callback_t callback)
539 new_frame_ready_callback = callback;
540 has_new_frame_ready_callback = true;
545 mixer_thread = std::thread(&Mixer::thread_func, this);
554 void Mixer::cut(Source source)
556 current_source = source;