]> git.sesse.net Git - nageru/blob - mixer.cpp
Take the Movit shader directory from pkg-config.
[nageru] / mixer.cpp
1 #define GL_GLEXT_PROTOTYPES 1
2 #define NO_SDL_GLEXT 1
3 #define NUM_CARDS 2
4
5 #define WIDTH 1280
6 #define HEIGHT 720
7
8 #include <epoxy/gl.h>
9 #include <epoxy/egl.h>
10
11 #undef Success
12
13 #include <assert.h>
14 #include <features.h>
15 #include <math.h>
16 #include <png.h>
17 #include <pngconf.h>
18 #include <setjmp.h>
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <sys/time.h>
22 #include <time.h>
23 #include <mutex>
24 #include <queue>
25 #include <condition_variable>
26
27 #include <diffusion_effect.h>
28 #include <effect.h>
29 #include <effect_chain.h>
30 #include <flat_input.h>
31 #include <image_format.h>
32 #include <init.h>
33 #include <lift_gamma_gain_effect.h>
34 #include <saturation_effect.h>
35 #include <util.h>
36 #include <ycbcr_input.h>
37 #include <vignette_effect.h>
38 #include <resample_effect.h>
39 #include <resize_effect.h>
40 #include <overlay_effect.h>
41 #include <padding_effect.h>
42 #include <white_balance_effect.h>
43 #include <ycbcr.h>
44 #include <resource_pool.h>
45 #include <effect_util.h>
46
47 #include <EGL/egl.h>
48
49 #include "h264encode.h"
50 #include "context.h"
51 #include "bmusb.h"
52 #include "pbo_frame_allocator.h"
53
54 using namespace movit;
55 using namespace std;
56 using namespace std::placeholders;
57
58
59 std::mutex bmusb_mutex;  // protects <cards>
60
61 struct CaptureCard {
62         BMUSBCapture *usb;
63
64         // Threading stuff
65         bool thread_initialized;
66         QSurface *surface;
67         QOpenGLContext *context;
68
69         bool new_data_ready;  // Whether new_frame contains anything.
70         PBOFrameAllocator::Frame new_frame;
71         GLsync new_data_ready_fence;  // Whether new_frame is ready for rendering.
72         std::condition_variable new_data_ready_changed;  // Set whenever new_data_ready is changed.
73 };
74 CaptureCard cards[NUM_CARDS];
75
76 void bm_frame(int card_index, uint16_t timecode,
77               FrameAllocator::Frame video_frame, size_t video_offset, uint16_t video_format,
78               FrameAllocator::Frame audio_frame, size_t audio_offset, uint16_t audio_format)
79 {
80         CaptureCard *card = &cards[card_index];
81         if (!card->thread_initialized) {
82                 printf("initializing context for bmusb thread %d\n", card_index);
83                 eglBindAPI(EGL_OPENGL_API);
84                 card->context = create_context();
85                 if (!make_current(card->context, card->surface)) {
86                         printf("failed to create bmusb context\n");
87                         exit(1);
88                 }
89                 card->thread_initialized = true;
90         }       
91
92         if (video_frame.len - video_offset != 1280 * 750 * 2) {
93                 printf("dropping frame with wrong length (%ld)\n", video_frame.len - video_offset);
94                 FILE *fp = fopen("frame.raw", "wb");
95                 fwrite(video_frame.data, video_frame.len, 1, fp);
96                 fclose(fp);
97                 //exit(1);
98                 card->usb->get_video_frame_allocator()->release_frame(video_frame);
99                 card->usb->get_audio_frame_allocator()->release_frame(audio_frame);
100                 return;
101         }
102         {
103                 // Wait until the previous frame was consumed.
104                 std::unique_lock<std::mutex> lock(bmusb_mutex);
105                 card->new_data_ready_changed.wait(lock, [card]{ return !card->new_data_ready; });
106         }
107         GLuint pbo = (GLint)(intptr_t)video_frame.userdata;
108         check_error();
109         glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, pbo);
110         check_error();
111         glFlushMappedBufferRange(GL_PIXEL_UNPACK_BUFFER, 0, video_frame.size);
112         check_error();
113         //glMemoryBarrier(GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT);
114         //check_error();
115         GLsync fence = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, /*flags=*/0);              
116         check_error();
117         assert(fence != nullptr);
118         {
119                 std::unique_lock<std::mutex> lock(bmusb_mutex);
120                 card->new_data_ready = true;
121                 card->new_frame = video_frame;
122                 card->new_data_ready_fence = fence;
123                 card->new_data_ready_changed.notify_all();
124         }
125
126         // Video frame will be released later.
127         card->usb->get_audio_frame_allocator()->release_frame(audio_frame);
128 }
129         
130 void place_rectangle(Effect *resample_effect, Effect *padding_effect, float x0, float y0, float x1, float y1)
131 {
132         float srcx0 = 0.0f;
133         float srcx1 = 1.0f;
134         float srcy0 = 0.0f;
135         float srcy1 = 1.0f;
136
137         // Cull.
138         if (x0 > 1280.0 || x1 < 0.0 || y0 > 720.0 || y1 < 0.0) {
139                 CHECK(resample_effect->set_int("width", 1));
140                 CHECK(resample_effect->set_int("height", 1));
141                 CHECK(resample_effect->set_float("zoom_x", 1280.0));
142                 CHECK(resample_effect->set_float("zoom_y", 720.0));
143                 CHECK(padding_effect->set_int("left", 2000));
144                 CHECK(padding_effect->set_int("top", 2000));
145                 return; 
146         }
147
148         // Clip. (TODO: Clip on upper/left sides, too.)
149         if (x1 > 1280.0) {
150                 srcx1 = (1280.0 - x0) / (x1 - x0);
151                 x1 = 1280.0;
152         }
153         if (y1 > 720.0) {
154                 srcy1 = (720.0 - y0) / (y1 - y0);
155                 y1 = 720.0;
156         }
157
158         float x_subpixel_offset = x0 - floor(x0);
159         float y_subpixel_offset = y0 - floor(y0);
160
161         // Resampling must be to an integral number of pixels. Round up,
162         // and then add an extra pixel so we have some leeway for the border.
163         int width = int(ceil(x1 - x0)) + 1;
164         int height = int(ceil(y1 - y0)) + 1;
165         CHECK(resample_effect->set_int("width", width));
166         CHECK(resample_effect->set_int("height", height));
167
168         // Correct the discrepancy with zoom. (This will leave a small
169         // excess edge of pixels and subpixels, which we'll correct for soon.)
170         float zoom_x = (x1 - x0) / (width * (srcx1 - srcx0));
171         float zoom_y = (y1 - y0) / (height * (srcy1 - srcy0));
172         CHECK(resample_effect->set_float("zoom_x", zoom_x));
173         CHECK(resample_effect->set_float("zoom_y", zoom_y));
174         CHECK(resample_effect->set_float("zoom_center_x", 0.0f));
175         CHECK(resample_effect->set_float("zoom_center_y", 0.0f));
176
177         // Padding must also be to a whole-pixel offset.
178         CHECK(padding_effect->set_int("left", floor(x0)));
179         CHECK(padding_effect->set_int("top", floor(y0)));
180
181         // Correct _that_ discrepancy by subpixel offset in the resampling.
182         CHECK(resample_effect->set_float("left", -x_subpixel_offset / zoom_x));
183         CHECK(resample_effect->set_float("top", -y_subpixel_offset / zoom_y));
184
185         // Finally, adjust the border so it is exactly where we want it.
186         CHECK(padding_effect->set_float("border_offset_left", x_subpixel_offset));
187         CHECK(padding_effect->set_float("border_offset_right", x1 - (floor(x0) + width)));
188         CHECK(padding_effect->set_float("border_offset_top", y_subpixel_offset));
189         CHECK(padding_effect->set_float("border_offset_bottom", y1 - (floor(y0) + height)));
190 }
191         
192 static bool quit = false;
193         
194 void mixer_thread_func(QSurface *surface, QSurface *surface2, QSurface *surface3, QSurface *surface4)
195 {
196         cards[0].surface = surface3;
197 #if NUM_CARDS == 2
198         cards[1].surface = surface4;
199 #endif
200
201         eglBindAPI(EGL_OPENGL_API);
202         QOpenGLContext *context = create_context();
203         if (!make_current(context, surface)) {
204                 printf("oops\n");
205                 exit(1);
206         }
207
208         CHECK(init_movit(MOVIT_SHADER_DIR, MOVIT_DEBUG_OFF));
209         check_error();
210
211         EffectChain chain(WIDTH, HEIGHT);
212         check_error();
213
214         ImageFormat inout_format;
215         inout_format.color_space = COLORSPACE_sRGB;
216         inout_format.gamma_curve = GAMMA_sRGB;
217
218         YCbCrFormat ycbcr_format;
219         ycbcr_format.chroma_subsampling_x = 2;
220         ycbcr_format.chroma_subsampling_y = 1;
221         ycbcr_format.cb_x_position = 0.0;
222         ycbcr_format.cr_x_position = 0.0;
223         ycbcr_format.cb_y_position = 0.5;
224         ycbcr_format.cr_y_position = 0.5;
225         ycbcr_format.luma_coefficients = YCBCR_REC_601;
226         ycbcr_format.full_range = false;
227
228         YCbCrInput *input[NUM_CARDS];
229
230         input[0] = new YCbCrInput(inout_format, ycbcr_format, WIDTH, HEIGHT, YCBCR_INPUT_SPLIT_Y_AND_CBCR);
231         chain.add_input(input[0]);
232         input[1] = new YCbCrInput(inout_format, ycbcr_format, WIDTH, HEIGHT, YCBCR_INPUT_SPLIT_Y_AND_CBCR);
233         chain.add_input(input[1]);
234         Effect *resample_effect = chain.add_effect(new ResampleEffect(), input[0]);
235         Effect *padding_effect = chain.add_effect(new IntegralPaddingEffect());
236         float border_color[] = { 0.0f, 0.0f, 0.0f, 1.0f };
237         CHECK(padding_effect->set_vec4("border_color", border_color));
238
239         Effect *resample2_effect = chain.add_effect(new ResampleEffect(), input[1]);
240         Effect *saturation_effect = chain.add_effect(new SaturationEffect());
241         CHECK(saturation_effect->set_float("saturation", 0.3f));
242         Effect *wb_effect = chain.add_effect(new WhiteBalanceEffect());
243         CHECK(wb_effect->set_float("output_color_temperature", 3500.0));
244         Effect *padding2_effect = chain.add_effect(new IntegralPaddingEffect());
245
246         chain.add_effect(new OverlayEffect(), padding_effect, padding2_effect);
247
248         ycbcr_format.chroma_subsampling_x = 1;
249
250         chain.add_ycbcr_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED, ycbcr_format, YCBCR_OUTPUT_SPLIT_Y_AND_CBCR);
251         chain.set_dither_bits(8);
252         chain.set_output_origin(OUTPUT_ORIGIN_TOP_LEFT);
253         chain.finalize();
254
255         H264Encoder h264_encoder(surface2, WIDTH, HEIGHT, "test.mp4");
256
257         printf("Configuring first card...\n");
258         cards[0].usb = new BMUSBCapture(0x1edb, 0xbd3b);  // 0xbd4f
259         //cards[0].usb = new BMUSBCapture(0x1edb, 0xbd4f);
260         cards[0].usb->set_frame_callback(std::bind(bm_frame, 0, _1, _2, _3, _4, _5, _6, _7));
261         std::unique_ptr<PBOFrameAllocator> pbo_allocator1(new PBOFrameAllocator(1280 * 750 * 2 + 44));
262         cards[0].usb->set_video_frame_allocator(pbo_allocator1.get());
263         cards[0].usb->configure_card();
264
265         std::unique_ptr<PBOFrameAllocator> pbo_allocator2(new PBOFrameAllocator(1280 * 750 * 2 + 44));
266         if (NUM_CARDS == 2) {
267                 printf("Configuring second card...\n");
268                 cards[1].usb = new BMUSBCapture(0x1edb, 0xbd4f);
269                 cards[1].usb->set_frame_callback(std::bind(bm_frame, 1, _1, _2, _3, _4, _5, _6, _7));
270                 cards[1].usb->set_video_frame_allocator(pbo_allocator2.get());
271                 cards[1].usb->configure_card();
272         }
273
274         BMUSBCapture::start_bm_thread();
275
276         for (int card_index = 0; card_index < NUM_CARDS; ++card_index) {
277                 cards[card_index].usb->start_bm_capture();
278         }
279
280         int frame = 0;
281 #if _POSIX_C_SOURCE >= 199309L
282         struct timespec start, now;
283         clock_gettime(CLOCK_MONOTONIC, &start);
284 #else
285         struct timeval start, now;
286         gettimeofday(&start, NULL);
287 #endif
288
289         PBOFrameAllocator::Frame bmusb_current_rendering_frame[NUM_CARDS];
290         for (int card_index = 0; card_index < NUM_CARDS; ++card_index) {
291                 bmusb_current_rendering_frame[card_index] =
292                         cards[card_index].usb->get_video_frame_allocator()->alloc_frame();
293                 GLint input_tex_pbo = (GLint)(intptr_t)bmusb_current_rendering_frame[card_index].userdata;
294                 input[card_index]->set_pixel_data(0, nullptr, input_tex_pbo);
295                 input[card_index]->set_pixel_data(1, nullptr, input_tex_pbo);
296                 check_error();
297         }
298
299         //chain.enable_phase_timing(true);
300
301         // Set up stuff for NV12 conversion.
302         ResourcePool *resource_pool = chain.get_resource_pool();
303         GLuint chroma_tex = resource_pool->create_2d_texture(GL_RG8, WIDTH, HEIGHT);
304
305         // Cb/Cr shader.
306         string cbcr_vert_shader = read_file("vs-cbcr.130.vert");
307         string cbcr_frag_shader =
308                 "#version 130 \n"
309                 "in vec2 tc0; \n"
310                 "uniform sampler2D cbcr_tex; \n"
311                 "void main() { \n"
312                 "    gl_FragColor = texture2D(cbcr_tex, tc0); \n"
313                 "} \n";
314         GLuint cbcr_program_num = resource_pool->compile_glsl_program(cbcr_vert_shader, cbcr_frag_shader);
315
316         GLuint vao;
317         glGenVertexArrays(1, &vao);
318         check_error();
319
320         while (!quit) {
321                 ++frame;
322
323                 //int width0 = lrintf(848 * (1.0 + 0.2 * sin(frame * 0.02)));
324                 int width0 = 848;
325                 int height0 = lrintf(width0 * 9.0 / 16.0);
326
327                 //float top0 = 96 + 48 * sin(frame * 0.005);
328                 //float left0 = 96 + 48 * cos(frame * 0.006);
329                 float top0 = 48;
330                 float left0 = 16;
331                 float bottom0 = top0 + height0;
332                 float right0 = left0 + width0;
333
334                 int width1 = 384;
335                 int height1 = 216;
336         
337                 float bottom1 = 720 - 48;
338                 float right1 = 1280 - 16;
339                 float top1 = bottom1 - height1;
340                 float left1 = right1 - width1;
341                 
342                 float t = 0.5 + 0.5 * cos(frame * 0.006);
343                 //float t = 0.0;
344                 float scale0 = 1.0 + t * (1280.0 / 848.0 - 1.0);
345                 float tx0 = 0.0 + t * (-16.0 * scale0);
346                 float ty0 = 0.0 + t * (-48.0 * scale0);
347
348                 top0 = top0 * scale0 + ty0;
349                 bottom0 = bottom0 * scale0 + ty0;
350                 left0 = left0 * scale0 + tx0;
351                 right0 = right0 * scale0 + tx0;
352
353                 top1 = top1 * scale0 + ty0;
354                 bottom1 = bottom1 * scale0 + ty0;
355                 left1 = left1 * scale0 + tx0;
356                 right1 = right1 * scale0 + tx0;
357
358                 place_rectangle(resample_effect, padding_effect, left0, top0, right0, bottom0);
359                 place_rectangle(resample2_effect, padding2_effect, left1, top1, right1, bottom1);
360
361                 CaptureCard card_copy[NUM_CARDS];
362
363                 {
364                         std::unique_lock<std::mutex> lock(bmusb_mutex);
365
366                         // The first card is the master timer, so wait for it to have a new frame.
367                         // TODO: Make configurable, and with a timeout.
368                         cards[0].new_data_ready_changed.wait(lock, []{ return cards[0].new_data_ready; });
369
370                         for (int card_index = 0; card_index < NUM_CARDS; ++card_index) {
371                                 CaptureCard *card = &cards[card_index];
372                                 card_copy[card_index].usb = card->usb;
373                                 card_copy[card_index].new_data_ready = card->new_data_ready;
374                                 card_copy[card_index].new_frame = card->new_frame;
375                                 card_copy[card_index].new_data_ready_fence = card->new_data_ready_fence;
376                                 card->new_data_ready = false;
377                                 card->new_data_ready_changed.notify_all();
378                         }
379                 }
380
381                 vector<FrameAllocator::Frame> input_frames_to_release;
382         
383                 for (int card_index = 0; card_index < NUM_CARDS; ++card_index) {
384                         CaptureCard *card = &card_copy[card_index];
385                         if (!card->new_data_ready)
386                                 continue;
387
388                         // Now we're done with the previous frame, so we can definitely
389                         // release it when this is done rendering. (Actually, we could do
390                         // it one frame earlier, but before we have a new one, there's no
391                         // knowing when the current one is released.)
392                         input_frames_to_release.push_back(bmusb_current_rendering_frame[card_index]);
393                         bmusb_current_rendering_frame[card_index] = card->new_frame;
394
395                         // The new texture might still be uploaded,
396                         // tell the GPU to wait until it's there.
397                         if (card->new_data_ready_fence)
398                                 glWaitSync(card->new_data_ready_fence, /*flags=*/0, GL_TIMEOUT_IGNORED);
399                         check_error();
400                         glDeleteSync(card->new_data_ready_fence);
401                         check_error();
402                         GLint input_tex_pbo = (GLint)(intptr_t)card->new_frame.userdata;
403                         input[card_index]->set_pixel_data(0, (unsigned char *)BUFFER_OFFSET((1280 * 750 * 2 + 44) / 2 + 1280 * 25 + 22), input_tex_pbo);
404                         input[card_index]->set_pixel_data(1, (unsigned char *)BUFFER_OFFSET(1280 * 25 + 22), input_tex_pbo);
405
406                         if (NUM_CARDS == 1) {
407                                 // Set to the other one, too.
408                                 input[1]->set_pixel_data(0, (unsigned char *)BUFFER_OFFSET((1280 * 750 * 2 + 44) / 2 + 1280 * 25 + 22), input_tex_pbo);
409                                 input[1]->set_pixel_data(1, (unsigned char *)BUFFER_OFFSET(1280 * 25 + 22), input_tex_pbo);
410                         }
411                 }
412
413                 GLuint y_tex, cbcr_tex;
414                 bool got_frame = h264_encoder.begin_frame(&y_tex, &cbcr_tex);
415                 assert(got_frame);
416
417                 // Render chain.
418                 {
419                         GLuint ycbcr_fbo = resource_pool->create_fbo(y_tex, chroma_tex);
420                         chain.render_to_fbo(ycbcr_fbo, WIDTH, HEIGHT);
421                         resource_pool->release_fbo(ycbcr_fbo);
422                 }
423
424                 // Set up for extraction.
425                 float vertices[] = {
426                         0.0f, 2.0f,
427                         0.0f, 0.0f,
428                         2.0f, 0.0f
429                 };
430
431                 glBindVertexArray(vao);
432                 check_error();
433
434                 // Extract Cb/Cr.
435                 GLuint cbcr_fbo = resource_pool->create_fbo(cbcr_tex);
436                 glBindFramebuffer(GL_FRAMEBUFFER, cbcr_fbo);
437                 glViewport(0, 0, WIDTH/2, HEIGHT/2);
438                 check_error();
439                 GLsync fence;
440                 {
441                         glUseProgram(cbcr_program_num);
442                         check_error();
443
444                         glActiveTexture(GL_TEXTURE0);
445                         check_error();
446                         glBindTexture(GL_TEXTURE_2D, chroma_tex);
447                         check_error();
448                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
449                         check_error();
450                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
451                         check_error();
452                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
453                         check_error();
454
455                         float chroma_offset_0[] = { -0.5f / WIDTH, 0.0f };
456                         set_uniform_vec2(cbcr_program_num, "foo", "chroma_offset_0", chroma_offset_0);
457
458                         GLuint position_vbo = fill_vertex_attribute(cbcr_program_num, "position", 2, GL_FLOAT, sizeof(vertices), vertices);
459                         GLuint texcoord_vbo = fill_vertex_attribute(cbcr_program_num, "texcoord", 2, GL_FLOAT, sizeof(vertices), vertices);  // Same as vertices.
460
461                         glDrawArrays(GL_TRIANGLES, 0, 3);
462                         check_error();
463
464                         cleanup_vertex_attribute(cbcr_program_num, "position", position_vbo);
465                         cleanup_vertex_attribute(cbcr_program_num, "texcoord", texcoord_vbo);
466
467                         glUseProgram(0);
468                         check_error();
469
470                         fence = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, /*flags=*/0);              
471                         check_error();
472
473                         resource_pool->release_fbo(cbcr_fbo);
474                 }
475
476                 h264_encoder.end_frame(fence, input_frames_to_release);
477
478
479 #if 1
480 #if _POSIX_C_SOURCE >= 199309L
481                 clock_gettime(CLOCK_MONOTONIC, &now);
482                 double elapsed = now.tv_sec - start.tv_sec +
483                         1e-9 * (now.tv_nsec - start.tv_nsec);
484 #else
485                 gettimeofday(&now, NULL);
486                 double elapsed = now.tv_sec - start.tv_sec +
487                         1e-6 * (now.tv_usec - start.tv_usec);
488 #endif
489                 if (frame % 100 == 0) {
490                         printf("%d frames in %.3f seconds = %.1f fps (%.1f ms/frame)\n",
491                                 frame, elapsed, frame / elapsed,
492                                 1e3 * elapsed / frame);
493                 //      chain.print_phase_timing();
494                 }
495
496                 // Reset every 100 frames, so that local variations in frame times
497                 // (especially for the first few frames, when the shaders are
498                 // compiled etc.) don't make it hard to measure for the entire
499                 // remaining duration of the program.
500                 if (frame == 10000) {
501                         frame = 0;
502                         start = now;
503                 }
504 #endif
505         }
506         glDeleteVertexArrays(1, &vao);
507         resource_pool->release_glsl_program(cbcr_program_num);
508         resource_pool->release_2d_texture(chroma_tex);
509         BMUSBCapture::stop_bm_thread();
510 }
511
512 std::thread mixer_thread;
513
514 void start_mixer(QSurface *surface, QSurface *surface2, QSurface *surface3, QSurface *surface4)
515 {
516         mixer_thread = std::thread([surface, surface2, surface3, surface4]{
517                 mixer_thread_func(surface, surface2, surface3, surface4);
518         });
519 }
520
521 void mixer_quit()
522 {
523         quit = true;
524         mixer_thread.join();
525 }