4 #include <bmusb/bmusb.h>
9 #include <movit/deinterlace_effect.h>
10 #include <movit/effect.h>
11 #include <movit/effect_chain.h>
12 #include <movit/image_format.h>
13 #include <movit/input.h>
14 #include <movit/lift_gamma_gain_effect.h>
15 #include <movit/mix_effect.h>
16 #include <movit/multiply_effect.h>
17 #include <movit/overlay_effect.h>
18 #include <movit/padding_effect.h>
19 #include <movit/resample_effect.h>
20 #include <movit/resize_effect.h>
21 #include <movit/util.h>
22 #include <movit/white_balance_effect.h>
23 #include <movit/ycbcr.h>
24 #include <movit/ycbcr_input.h>
34 #include "cef_capture.h"
36 #include "ffmpeg_capture.h"
38 #include "image_input.h"
39 #include "input_state.h"
40 #include "lua_utils.h"
41 #include "pbo_frame_allocator.h"
51 using namespace movit;
53 extern Mixer *global_mixer;
55 Theme *get_theme_updata(lua_State* L)
57 luaL_checktype(L, lua_upvalueindex(1), LUA_TLIGHTUSERDATA);
58 return (Theme *)lua_touserdata(L, lua_upvalueindex(1));
61 void print_warning(lua_State* L, const char *format, ...)
66 vsnprintf(buf, sizeof(buf), format, ap);
70 lua_getstack(L, 1, &ar);
71 lua_getinfo(L, "nSl", &ar);
72 fprintf(stderr, "WARNING: %s:%d: %s", ar.source, ar.currentline, buf);
75 int ThemeMenu_set(lua_State *L)
77 Theme *theme = get_theme_updata(L);
78 return theme->set_theme_menu(L);
81 InputStateInfo::InputStateInfo(const InputState &input_state)
83 for (unsigned signal_num = 0; signal_num < MAX_VIDEO_CARDS; ++signal_num) {
84 BufferedFrame frame = input_state.buffered_frames[signal_num][0];
85 if (frame.frame == nullptr) {
86 last_width[signal_num] = last_height[signal_num] = 0;
87 last_interlaced[signal_num] = false;
88 last_has_signal[signal_num] = false;
89 last_is_connected[signal_num] = false;
92 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
93 last_width[signal_num] = userdata->last_width[frame.field_number];
94 last_height[signal_num] = userdata->last_height[frame.field_number];
95 last_interlaced[signal_num] = userdata->last_interlaced;
96 last_has_signal[signal_num] = userdata->last_has_signal;
97 last_is_connected[signal_num] = userdata->last_is_connected;
98 last_frame_rate_nom[signal_num] = userdata->last_frame_rate_nom;
99 last_frame_rate_den[signal_num] = userdata->last_frame_rate_den;
100 has_last_subtitle[signal_num] = userdata->has_last_subtitle;
101 last_subtitle[signal_num] = userdata->last_subtitle;
105 // An effect that does nothing.
106 class IdentityEffect : public Effect {
109 string effect_type_id() const override { return "IdentityEffect"; }
110 string output_fragment_shader() override { return read_file("identity.frag"); }
113 Effect *instantiate_effect(EffectChain *chain, EffectType effect_type)
115 switch (effect_type) {
116 case IDENTITY_EFFECT:
117 return new IdentityEffect;
118 case WHITE_BALANCE_EFFECT:
119 case AUTO_WHITE_BALANCE_EFFECT:
120 return new WhiteBalanceEffect;
121 case RESAMPLE_EFFECT:
122 return new ResampleEffect;
124 return new PaddingEffect;
125 case INTEGRAL_PADDING_EFFECT:
126 return new IntegralPaddingEffect;
128 return new OverlayEffect;
130 return new ResizeEffect;
131 case MULTIPLY_EFFECT:
132 return new MultiplyEffect;
134 return new MixEffect;
135 case LIFT_GAMMA_GAIN_EFFECT:
136 return new LiftGammaGainEffect;
138 fprintf(stderr, "Unhandled effect type %d\n", effect_type);
145 Effect *get_effect_from_blueprint(EffectChain *chain, lua_State *L, int idx)
147 EffectBlueprint *blueprint = *(EffectBlueprint **)luaL_checkudata(L, idx, "EffectBlueprint");
148 if (blueprint->effect != nullptr) {
149 luaL_error(L, "An effect can currently only be added to one chain.\n");
152 Effect *effect = instantiate_effect(chain, blueprint->effect_type);
154 // Set the parameters that were deferred earlier.
155 for (const auto &kv : blueprint->int_parameters) {
156 if (!effect->set_int(kv.first, kv.second)) {
157 luaL_error(L, "Effect refused set_int(\"%s\", %d) (invalid key?)", kv.first.c_str(), kv.second);
160 for (const auto &kv : blueprint->float_parameters) {
161 if (!effect->set_float(kv.first, kv.second)) {
162 luaL_error(L, "Effect refused set_float(\"%s\", %f) (invalid key?)", kv.first.c_str(), kv.second);
165 for (const auto &kv : blueprint->vec3_parameters) {
166 if (!effect->set_vec3(kv.first, kv.second.data())) {
167 luaL_error(L, "Effect refused set_vec3(\"%s\", %f, %f, %f) (invalid key?)", kv.first.c_str(),
168 kv.second[0], kv.second[1], kv.second[2]);
171 for (const auto &kv : blueprint->vec4_parameters) {
172 if (!effect->set_vec4(kv.first, kv.second.data())) {
173 luaL_error(L, "Effect refused set_vec4(\"%s\", %f, %f, %f, %f) (invalid key?)", kv.first.c_str(),
174 kv.second[0], kv.second[1], kv.second[2], kv.second[3]);
177 blueprint->effect = effect;
181 InputStateInfo *get_input_state_info(lua_State *L, int idx)
183 if (luaL_testudata(L, idx, "InputStateInfo")) {
184 return (InputStateInfo *)lua_touserdata(L, idx);
186 luaL_error(L, "Error: Index #%d was not InputStateInfo\n", idx);
192 bool checkbool(lua_State* L, int idx)
194 luaL_checktype(L, idx, LUA_TBOOLEAN);
195 return lua_toboolean(L, idx);
198 string checkstdstring(lua_State *L, int index)
201 const char* cstr = lua_tolstring(L, index, &len);
202 return string(cstr, len);
207 int Scene_new(lua_State* L)
209 assert(lua_gettop(L) == 2);
210 Theme *theme = get_theme_updata(L);
211 int aspect_w = luaL_checknumber(L, 1);
212 int aspect_h = luaL_checknumber(L, 2);
214 return wrap_lua_object<Scene>(L, "Scene", theme, aspect_w, aspect_h);
217 int Scene_gc(lua_State* L)
219 assert(lua_gettop(L) == 1);
220 Scene *chain = (Scene *)luaL_checkudata(L, 1, "Scene");
227 void add_outputs_and_finalize(EffectChain *chain, bool is_main_chain)
229 // Add outputs as needed.
230 // NOTE: If you change any details about the output format, you will need to
231 // also update what's given to the muxer (HTTPD::Mux constructor) and
232 // what's put in the H.264 stream (sps_rbsp()).
233 ImageFormat inout_format;
234 inout_format.color_space = COLORSPACE_REC_709;
236 // Output gamma is tricky. We should output Rec. 709 for TV, except that
237 // we expect to run with web players and others that don't really care and
238 // just output with no conversion. So that means we'll need to output sRGB,
239 // even though H.264 has no setting for that (we use “unspecified”).
240 inout_format.gamma_curve = GAMMA_sRGB;
243 YCbCrFormat output_ycbcr_format;
244 // We actually output 4:2:0 and/or 4:2:2 in the end, but chroma subsampling
245 // happens in a pass not run by Movit (see ChromaSubsampler::subsample_chroma()).
246 output_ycbcr_format.chroma_subsampling_x = 1;
247 output_ycbcr_format.chroma_subsampling_y = 1;
249 // This will be overridden if HDMI/SDI output is in force.
250 if (global_flags.ycbcr_rec709_coefficients) {
251 output_ycbcr_format.luma_coefficients = YCBCR_REC_709;
253 output_ycbcr_format.luma_coefficients = YCBCR_REC_601;
256 output_ycbcr_format.full_range = false;
257 output_ycbcr_format.num_levels = 1 << global_flags.x264_bit_depth;
259 GLenum type = global_flags.x264_bit_depth > 8 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_BYTE;
261 chain->add_ycbcr_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED, output_ycbcr_format, YCBCR_OUTPUT_SPLIT_Y_AND_CBCR, type);
263 // If we're using zerocopy video encoding (so the destination
264 // Y texture is owned by VA-API and will be unavailable for
265 // display), add a copy, where we'll only be using the Y component.
266 if (global_flags.use_zerocopy) {
267 chain->add_ycbcr_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED, output_ycbcr_format, YCBCR_OUTPUT_INTERLEAVED, type); // Add a copy where we'll only be using the Y component.
269 chain->set_dither_bits(global_flags.x264_bit_depth > 8 ? 16 : 8);
270 chain->set_output_origin(OUTPUT_ORIGIN_TOP_LEFT);
272 chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
280 int EffectChain_new(lua_State* L)
282 assert(lua_gettop(L) == 2);
283 Theme *theme = get_theme_updata(L);
284 int aspect_w = luaL_checknumber(L, 1);
285 int aspect_h = luaL_checknumber(L, 2);
287 return wrap_lua_object<EffectChain>(L, "EffectChain", aspect_w, aspect_h, theme->get_resource_pool());
290 int EffectChain_gc(lua_State* L)
292 assert(lua_gettop(L) == 1);
293 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
294 chain->~EffectChain();
298 int EffectChain_add_live_input(lua_State* L)
300 assert(lua_gettop(L) == 3);
301 Theme *theme = get_theme_updata(L);
302 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
303 bool override_bounce = checkbool(L, 2);
304 bool deinterlace = checkbool(L, 3);
305 bmusb::PixelFormat pixel_format = global_flags.ten_bit_input ? bmusb::PixelFormat_10BitYCbCr : bmusb::PixelFormat_8BitYCbCr;
307 // Needs to be nonowned to match add_video_input (see below).
308 return wrap_lua_object_nonowned<LiveInputWrapper>(L, "LiveInputWrapper", theme, chain, pixel_format, override_bounce, deinterlace, /*user_connectable=*/true);
311 int EffectChain_add_video_input(lua_State* L)
313 assert(lua_gettop(L) == 3);
314 Theme *theme = get_theme_updata(L);
315 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
316 FFmpegCapture **capture = (FFmpegCapture **)luaL_checkudata(L, 2, "VideoInput");
317 bool deinterlace = checkbool(L, 3);
319 // These need to be nonowned, so that the LiveInputWrapper still exists
320 // and can feed frames to the right EffectChain even if the Lua code
321 // doesn't care about the object anymore. (If we change this, we'd need
322 // to also unregister the signal connection on __gc.)
323 int ret = wrap_lua_object_nonowned<LiveInputWrapper>(
324 L, "LiveInputWrapper", theme, chain, (*capture)->get_current_pixel_format(),
325 /*override_bounce=*/false, deinterlace, /*user_connectable=*/false);
327 Theme *theme = get_theme_updata(L);
328 LiveInputWrapper **live_input = (LiveInputWrapper **)lua_touserdata(L, -1);
329 theme->register_video_signal_connection(chain, *live_input, *capture);
335 int EffectChain_add_html_input(lua_State* L)
337 assert(lua_gettop(L) == 2);
338 Theme *theme = get_theme_updata(L);
339 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
340 CEFCapture **capture = (CEFCapture **)luaL_checkudata(L, 2, "HTMLInput");
342 // These need to be nonowned, so that the LiveInputWrapper still exists
343 // and can feed frames to the right EffectChain even if the Lua code
344 // doesn't care about the object anymore. (If we change this, we'd need
345 // to also unregister the signal connection on __gc.)
346 int ret = wrap_lua_object_nonowned<LiveInputWrapper>(
347 L, "LiveInputWrapper", theme, chain, (*capture)->get_current_pixel_format(),
348 /*override_bounce=*/false, /*deinterlace=*/false, /*user_connectable=*/false);
350 Theme *theme = get_theme_updata(L);
351 LiveInputWrapper **live_input = (LiveInputWrapper **)lua_touserdata(L, -1);
352 theme->register_html_signal_connection(chain, *live_input, *capture);
358 int EffectChain_add_effect(lua_State* L)
360 assert(lua_gettop(L) >= 2);
361 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
363 // TODO: Better error reporting.
365 if (luaL_testudata(L, 2, "ImageInput")) {
366 effect = *(ImageInput **)luaL_checkudata(L, 2, "ImageInput");
368 effect = get_effect_from_blueprint(chain, L, 2);
370 if (lua_gettop(L) == 2) {
371 if (effect->num_inputs() == 0) {
372 chain->add_input((Input *)effect);
374 chain->add_effect(effect);
377 vector<Effect *> inputs;
378 for (int idx = 3; idx <= lua_gettop(L); ++idx) {
379 if (luaL_testudata(L, idx, "LiveInputWrapper")) {
380 LiveInputWrapper **input = (LiveInputWrapper **)lua_touserdata(L, idx);
381 inputs.push_back((*input)->get_effect());
382 } else if (luaL_testudata(L, idx, "ImageInput")) {
383 ImageInput *image = *(ImageInput **)luaL_checkudata(L, idx, "ImageInput");
384 inputs.push_back(image);
386 EffectBlueprint *blueprint = *(EffectBlueprint **)luaL_checkudata(L, idx, "EffectBlueprint");
387 assert(blueprint->effect != nullptr); // Parent must be added to the graph.
388 inputs.push_back(blueprint->effect);
391 chain->add_effect(effect, inputs);
394 lua_settop(L, 2); // Return the effect itself.
396 // Make sure Lua doesn't garbage-collect it away.
397 lua_pushvalue(L, -1);
398 luaL_ref(L, LUA_REGISTRYINDEX); // TODO: leak?
403 int EffectChain_finalize(lua_State* L)
405 assert(lua_gettop(L) == 2);
406 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
407 bool is_main_chain = checkbool(L, 2);
408 add_outputs_and_finalize(chain, is_main_chain);
412 int LiveInputWrapper_connect_signal(lua_State* L)
414 assert(lua_gettop(L) == 2);
415 LiveInputWrapper **input = (LiveInputWrapper **)luaL_checkudata(L, 1, "LiveInputWrapper");
416 int signal_num = luaL_checknumber(L, 2);
417 bool success = (*input)->connect_signal(signal_num);
419 print_warning(L, "Calling connect_signal() on a video or HTML input. Ignoring.\n");
424 int ImageInput_new(lua_State* L)
426 assert(lua_gettop(L) == 1);
427 string filename = checkstdstring(L, 1);
428 return wrap_lua_object_nonowned<ImageInput>(L, "ImageInput", filename);
431 int VideoInput_new(lua_State* L)
433 assert(lua_gettop(L) == 2);
434 string filename = checkstdstring(L, 1);
435 int pixel_format = luaL_checknumber(L, 2);
436 if (pixel_format != bmusb::PixelFormat_8BitYCbCrPlanar &&
437 pixel_format != bmusb::PixelFormat_8BitBGRA) {
438 print_warning(L, "Invalid enum %d used for video format, choosing Y'CbCr.\n", pixel_format);
439 pixel_format = bmusb::PixelFormat_8BitYCbCrPlanar;
441 int ret = wrap_lua_object_nonowned<FFmpegCapture>(L, "VideoInput", filename, global_flags.width, global_flags.height);
443 FFmpegCapture **capture = (FFmpegCapture **)lua_touserdata(L, -1);
444 (*capture)->set_pixel_format(bmusb::PixelFormat(pixel_format));
446 Theme *theme = get_theme_updata(L);
447 theme->register_video_input(*capture);
452 int VideoInput_rewind(lua_State* L)
454 assert(lua_gettop(L) == 1);
455 FFmpegCapture **video_input = (FFmpegCapture **)luaL_checkudata(L, 1, "VideoInput");
456 (*video_input)->rewind();
460 int VideoInput_disconnect(lua_State* L)
462 assert(lua_gettop(L) == 1);
463 FFmpegCapture **video_input = (FFmpegCapture **)luaL_checkudata(L, 1, "VideoInput");
464 (*video_input)->disconnect();
468 int VideoInput_change_rate(lua_State* L)
470 assert(lua_gettop(L) == 2);
471 FFmpegCapture **video_input = (FFmpegCapture **)luaL_checkudata(L, 1, "VideoInput");
472 double new_rate = luaL_checknumber(L, 2);
473 (*video_input)->change_rate(new_rate);
477 int VideoInput_get_signal_num(lua_State* L)
479 assert(lua_gettop(L) == 1);
480 FFmpegCapture **video_input = (FFmpegCapture **)luaL_checkudata(L, 1, "VideoInput");
481 lua_pushnumber(L, -1 - (*video_input)->get_card_index());
485 int HTMLInput_new(lua_State* L)
488 assert(lua_gettop(L) == 1);
489 string url = checkstdstring(L, 1);
490 int ret = wrap_lua_object_nonowned<CEFCapture>(L, "HTMLInput", url, global_flags.width, global_flags.height);
492 CEFCapture **capture = (CEFCapture **)lua_touserdata(L, -1);
493 Theme *theme = get_theme_updata(L);
494 theme->register_html_input(*capture);
498 fprintf(stderr, "This version of Nageru has been compiled without CEF support.\n");
499 fprintf(stderr, "HTMLInput is not available.\n");
505 int HTMLInput_set_url(lua_State* L)
507 assert(lua_gettop(L) == 2);
508 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
509 string new_url = checkstdstring(L, 2);
510 (*video_input)->set_url(new_url);
514 int HTMLInput_reload(lua_State* L)
516 assert(lua_gettop(L) == 1);
517 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
518 (*video_input)->reload();
522 int HTMLInput_set_max_fps(lua_State* L)
524 assert(lua_gettop(L) == 2);
525 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
526 int max_fps = lrint(luaL_checknumber(L, 2));
527 (*video_input)->set_max_fps(max_fps);
531 int HTMLInput_execute_javascript_async(lua_State* L)
533 assert(lua_gettop(L) == 2);
534 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
535 string js = checkstdstring(L, 2);
536 (*video_input)->execute_javascript_async(js);
540 int HTMLInput_resize(lua_State* L)
542 assert(lua_gettop(L) == 3);
543 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
544 unsigned width = lrint(luaL_checknumber(L, 2));
545 unsigned height = lrint(luaL_checknumber(L, 3));
546 (*video_input)->resize(width, height);
550 int HTMLInput_get_signal_num(lua_State* L)
552 assert(lua_gettop(L) == 1);
553 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
554 lua_pushnumber(L, -1 - (*video_input)->get_card_index());
559 int IdentityEffect_new(lua_State* L)
561 assert(lua_gettop(L) == 0);
562 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", IDENTITY_EFFECT);
565 int WhiteBalanceEffect_new(lua_State* L)
567 assert(lua_gettop(L) == 0);
568 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", WHITE_BALANCE_EFFECT);
571 int ResampleEffect_new(lua_State* L)
573 assert(lua_gettop(L) == 0);
574 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", RESAMPLE_EFFECT);
577 int PaddingEffect_new(lua_State* L)
579 assert(lua_gettop(L) == 0);
580 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", PADDING_EFFECT);
583 int IntegralPaddingEffect_new(lua_State* L)
585 assert(lua_gettop(L) == 0);
586 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", INTEGRAL_PADDING_EFFECT);
589 int OverlayEffect_new(lua_State* L)
591 assert(lua_gettop(L) == 0);
592 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", OVERLAY_EFFECT);
595 int ResizeEffect_new(lua_State* L)
597 assert(lua_gettop(L) == 0);
598 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", RESIZE_EFFECT);
601 int MultiplyEffect_new(lua_State* L)
603 assert(lua_gettop(L) == 0);
604 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", MULTIPLY_EFFECT);
607 int MixEffect_new(lua_State* L)
609 assert(lua_gettop(L) == 0);
610 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", MIX_EFFECT);
613 int LiftGammaGainEffect_new(lua_State* L)
615 assert(lua_gettop(L) == 0);
616 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", LIFT_GAMMA_GAIN_EFFECT);
619 int InputStateInfo_get_width(lua_State* L)
621 assert(lua_gettop(L) == 2);
622 InputStateInfo *input_state_info = get_input_state_info(L, 1);
624 Theme *theme = get_theme_updata(L);
625 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
626 lua_pushnumber(L, input_state_info->last_width[signal_num]);
630 int InputStateInfo_get_height(lua_State* L)
632 assert(lua_gettop(L) == 2);
633 InputStateInfo *input_state_info = get_input_state_info(L, 1);
634 Theme *theme = get_theme_updata(L);
635 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
636 lua_pushnumber(L, input_state_info->last_height[signal_num]);
640 int InputStateInfo_get_frame_height(lua_State* L)
642 assert(lua_gettop(L) == 2);
643 InputStateInfo *input_state_info = get_input_state_info(L, 1);
644 Theme *theme = get_theme_updata(L);
645 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
646 unsigned height = input_state_info->last_height[signal_num];
647 if (input_state_info->last_interlaced[signal_num]) {
650 lua_pushnumber(L, height);
654 int InputStateInfo_get_interlaced(lua_State* L)
656 assert(lua_gettop(L) == 2);
657 InputStateInfo *input_state_info = get_input_state_info(L, 1);
658 Theme *theme = get_theme_updata(L);
659 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
660 lua_pushboolean(L, input_state_info->last_interlaced[signal_num]);
664 int InputStateInfo_get_has_signal(lua_State* L)
666 assert(lua_gettop(L) == 2);
667 InputStateInfo *input_state_info = get_input_state_info(L, 1);
668 Theme *theme = get_theme_updata(L);
669 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
670 lua_pushboolean(L, input_state_info->last_has_signal[signal_num]);
674 int InputStateInfo_get_is_connected(lua_State* L)
676 assert(lua_gettop(L) == 2);
677 InputStateInfo *input_state_info = get_input_state_info(L, 1);
678 Theme *theme = get_theme_updata(L);
679 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
680 lua_pushboolean(L, input_state_info->last_is_connected[signal_num]);
684 int InputStateInfo_get_frame_rate_nom(lua_State* L)
686 assert(lua_gettop(L) == 2);
687 InputStateInfo *input_state_info = get_input_state_info(L, 1);
688 Theme *theme = get_theme_updata(L);
689 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
690 lua_pushnumber(L, input_state_info->last_frame_rate_nom[signal_num]);
694 int InputStateInfo_get_frame_rate_den(lua_State* L)
696 assert(lua_gettop(L) == 2);
697 InputStateInfo *input_state_info = get_input_state_info(L, 1);
698 Theme *theme = get_theme_updata(L);
699 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
700 lua_pushnumber(L, input_state_info->last_frame_rate_den[signal_num]);
704 int InputStateInfo_get_last_subtitle(lua_State* L)
706 assert(lua_gettop(L) == 2);
707 InputStateInfo *input_state_info = get_input_state_info(L, 1);
708 Theme *theme = get_theme_updata(L);
709 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
710 if (!input_state_info->has_last_subtitle[signal_num]) {
713 lua_pushstring(L, input_state_info->last_subtitle[signal_num].c_str());
720 // Helper function to write e.g. “60” or “59.94”.
721 string format_frame_rate(int nom, int den)
724 if (nom % den == 0) {
725 snprintf(buf, sizeof(buf), "%d", nom / den);
727 snprintf(buf, sizeof(buf), "%.2f", double(nom) / den);
732 // Helper function to write e.g. “720p60”.
733 string get_human_readable_resolution(const InputStateInfo *input_state_info, int signal_num)
736 if (input_state_info->last_interlaced[signal_num]) {
737 snprintf(buf, sizeof(buf), "%di", input_state_info->last_height[signal_num] * 2);
739 // Show field rate instead of frame rate; really for cosmetics only
740 // (and actually contrary to EBU recommendations, although in line
741 // with typical user expectations).
742 return buf + format_frame_rate(input_state_info->last_frame_rate_nom[signal_num] * 2,
743 input_state_info->last_frame_rate_den[signal_num]);
745 snprintf(buf, sizeof(buf), "%dp", input_state_info->last_height[signal_num]);
746 return buf + format_frame_rate(input_state_info->last_frame_rate_nom[signal_num],
747 input_state_info->last_frame_rate_den[signal_num]);
753 int InputStateInfo_get_human_readable_resolution(lua_State* L)
755 assert(lua_gettop(L) == 2);
756 InputStateInfo *input_state_info = get_input_state_info(L, 1);
757 Theme *theme = get_theme_updata(L);
758 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
761 if (!input_state_info->last_is_connected[signal_num]) {
762 str = "disconnected";
763 } else if (input_state_info->last_height[signal_num] <= 0) {
765 } else if (!input_state_info->last_has_signal[signal_num]) {
766 if (input_state_info->last_height[signal_num] == 525) {
767 // Special mode for the USB3 cards.
770 str = get_human_readable_resolution(input_state_info, signal_num) + ", no signal";
773 str = get_human_readable_resolution(input_state_info, signal_num);
776 lua_pushstring(L, str.c_str());
781 int EffectBlueprint_set_int(lua_State *L)
783 assert(lua_gettop(L) == 3);
784 EffectBlueprint *blueprint = *(EffectBlueprint **)luaL_checkudata(L, 1, "EffectBlueprint");
785 string key = checkstdstring(L, 2);
786 float value = luaL_checknumber(L, 3);
787 if (blueprint->effect != nullptr) {
788 if (!blueprint->effect->set_int(key, value)) {
789 luaL_error(L, "Effect refused set_int(\"%s\", %d) (invalid key?)", key.c_str(), int(value));
792 // TODO: check validity already here, if possible?
793 blueprint->int_parameters[key] = value;
798 int EffectBlueprint_set_float(lua_State *L)
800 assert(lua_gettop(L) == 3);
801 EffectBlueprint *blueprint = *(EffectBlueprint **)luaL_checkudata(L, 1, "EffectBlueprint");
802 string key = checkstdstring(L, 2);
803 float value = luaL_checknumber(L, 3);
804 if (blueprint->effect != nullptr) {
805 if (!blueprint->effect->set_float(key, value)) {
806 luaL_error(L, "Effect refused set_float(\"%s\", %d) (invalid key?)", key.c_str(), int(value));
809 // TODO: check validity already here, if possible?
810 blueprint->float_parameters[key] = value;
815 int EffectBlueprint_set_vec3(lua_State *L)
817 assert(lua_gettop(L) == 5);
818 EffectBlueprint *blueprint = *(EffectBlueprint **)luaL_checkudata(L, 1, "EffectBlueprint");
819 string key = checkstdstring(L, 2);
821 v[0] = luaL_checknumber(L, 3);
822 v[1] = luaL_checknumber(L, 4);
823 v[2] = luaL_checknumber(L, 5);
825 if (blueprint->effect != nullptr) {
826 if (!blueprint->effect->set_vec3(key, v.data())) {
827 luaL_error(L, "Effect refused set_vec3(\"%s\", %f, %f, %f) (invalid key?)", key.c_str(),
831 // TODO: check validity already here, if possible?
832 blueprint->vec3_parameters[key] = v;
838 int EffectBlueprint_set_vec4(lua_State *L)
840 assert(lua_gettop(L) == 6);
841 EffectBlueprint *blueprint = *(EffectBlueprint **)luaL_checkudata(L, 1, "EffectBlueprint");
842 string key = checkstdstring(L, 2);
844 v[0] = luaL_checknumber(L, 3);
845 v[1] = luaL_checknumber(L, 4);
846 v[2] = luaL_checknumber(L, 5);
847 v[3] = luaL_checknumber(L, 6);
848 if (blueprint->effect != nullptr) {
849 if (!blueprint->effect->set_vec4(key, v.data())) {
850 luaL_error(L, "Effect refused set_vec4(\"%s\", %f, %f, %f, %f) (invalid key?)", key.c_str(),
851 v[0], v[1], v[2], v[3]);
854 // TODO: check validity already here, if possible?
855 blueprint->vec4_parameters[key] = v;
860 const luaL_Reg Scene_funcs[] = {
861 { "new", Scene_new },
862 { "__gc", Scene_gc },
863 { "add_input", Scene::add_input },
864 { "add_auto_white_balance", Scene::add_auto_white_balance },
865 { "add_effect", Scene::add_effect },
866 { "add_optional_effect", Scene::add_optional_effect },
867 { "finalize", Scene::finalize },
871 const luaL_Reg Block_funcs[] = {
872 { "display", Block_display },
873 { "choose", Block_choose },
874 { "enable", Block_enable },
875 { "enable_if", Block_enable_if },
876 { "disable", Block_disable },
877 { "always_disable_if_disabled", Block_always_disable_if_disabled },
878 { "promise_to_disable_if_enabled", Block_promise_to_disable_if_enabled },
879 { "set_int", Block_set_int },
880 { "set_float", Block_set_float },
881 { "set_vec3", Block_set_vec3 },
882 { "set_vec4", Block_set_vec4 },
886 const luaL_Reg EffectBlueprint_funcs[] = {
887 // NOTE: No new() function; that's for the individual effects.
888 { "set_int", EffectBlueprint_set_int },
889 { "set_float", EffectBlueprint_set_float },
890 { "set_vec3", EffectBlueprint_set_vec3 },
891 { "set_vec4", EffectBlueprint_set_vec4 },
895 const luaL_Reg EffectChain_funcs[] = {
896 { "new", EffectChain_new },
897 { "__gc", EffectChain_gc },
898 { "add_live_input", EffectChain_add_live_input },
899 { "add_video_input", EffectChain_add_video_input },
901 { "add_html_input", EffectChain_add_html_input },
903 { "add_effect", EffectChain_add_effect },
904 { "finalize", EffectChain_finalize },
908 const luaL_Reg LiveInputWrapper_funcs[] = {
909 { "connect_signal", LiveInputWrapper_connect_signal },
913 const luaL_Reg ImageInput_funcs[] = {
914 { "new", ImageInput_new },
918 const luaL_Reg VideoInput_funcs[] = {
919 { "new", VideoInput_new },
920 { "rewind", VideoInput_rewind },
921 { "disconnect", VideoInput_disconnect },
922 { "change_rate", VideoInput_change_rate },
923 { "get_signal_num", VideoInput_get_signal_num },
927 const luaL_Reg HTMLInput_funcs[] = {
928 { "new", HTMLInput_new },
930 { "set_url", HTMLInput_set_url },
931 { "reload", HTMLInput_reload },
932 { "set_max_fps", HTMLInput_set_max_fps },
933 { "execute_javascript_async", HTMLInput_execute_javascript_async },
934 { "resize", HTMLInput_resize },
935 { "get_signal_num", HTMLInput_get_signal_num },
941 // All of these are solely for new(); the returned metatable will be that of
942 // EffectBlueprint, and Effect (returned from add_effect()) is its own type.
944 const luaL_Reg IdentityEffect_funcs[] = {
945 { "new", IdentityEffect_new },
949 const luaL_Reg WhiteBalanceEffect_funcs[] = {
950 { "new", WhiteBalanceEffect_new },
954 const luaL_Reg ResampleEffect_funcs[] = {
955 { "new", ResampleEffect_new },
959 const luaL_Reg PaddingEffect_funcs[] = {
960 { "new", PaddingEffect_new },
964 const luaL_Reg IntegralPaddingEffect_funcs[] = {
965 { "new", IntegralPaddingEffect_new },
969 const luaL_Reg OverlayEffect_funcs[] = {
970 { "new", OverlayEffect_new },
974 const luaL_Reg ResizeEffect_funcs[] = {
975 { "new", ResizeEffect_new },
979 const luaL_Reg MultiplyEffect_funcs[] = {
980 { "new", MultiplyEffect_new },
984 const luaL_Reg MixEffect_funcs[] = {
985 { "new", MixEffect_new },
989 const luaL_Reg LiftGammaGainEffect_funcs[] = {
990 { "new", LiftGammaGainEffect_new },
996 const luaL_Reg InputStateInfo_funcs[] = {
997 { "get_width", InputStateInfo_get_width },
998 { "get_height", InputStateInfo_get_height },
999 { "get_frame_width", InputStateInfo_get_width }, // Same as get_width().
1000 { "get_frame_height", InputStateInfo_get_frame_height },
1001 { "get_interlaced", InputStateInfo_get_interlaced },
1002 { "get_has_signal", InputStateInfo_get_has_signal },
1003 { "get_is_connected", InputStateInfo_get_is_connected },
1004 { "get_frame_rate_nom", InputStateInfo_get_frame_rate_nom },
1005 { "get_frame_rate_den", InputStateInfo_get_frame_rate_den },
1006 { "get_last_subtitle", InputStateInfo_get_last_subtitle },
1007 { "get_human_readable_resolution", InputStateInfo_get_human_readable_resolution },
1011 const luaL_Reg ThemeMenu_funcs[] = {
1012 { "set", ThemeMenu_set },
1018 LiveInputWrapper::LiveInputWrapper(
1021 bmusb::PixelFormat pixel_format,
1022 bool override_bounce,
1024 bool user_connectable)
1026 pixel_format(pixel_format),
1027 deinterlace(deinterlace),
1028 user_connectable(user_connectable)
1030 ImageFormat inout_format;
1031 inout_format.color_space = COLORSPACE_sRGB;
1033 // Gamma curve depends on the input signal, and we don't really get any
1034 // indications. A camera would be expected to do Rec. 709, but
1035 // I haven't checked if any do in practice. However, computers _do_ output
1036 // in sRGB gamma (ie., they don't convert from sRGB to Rec. 709), and
1037 // I wouldn't really be surprised if most non-professional cameras do, too.
1038 // So we pick sRGB as the least evil here.
1039 inout_format.gamma_curve = GAMMA_sRGB;
1041 unsigned num_inputs;
1043 deinterlace_effect = new movit::DeinterlaceEffect();
1045 // As per the comments in deinterlace_effect.h, we turn this off.
1046 // The most likely interlaced input for us is either a camera
1047 // (where it's fine to turn it off) or a laptop (where it _should_
1049 CHECK(deinterlace_effect->set_int("enable_spatial_interlacing_check", 0));
1051 num_inputs = deinterlace_effect->num_inputs();
1052 assert(num_inputs == FRAME_HISTORY_LENGTH);
1057 if (pixel_format == bmusb::PixelFormat_8BitBGRA) {
1058 for (unsigned i = 0; i < num_inputs; ++i) {
1059 // We upload our textures ourselves, and Movit swaps
1060 // R and B in the shader if we specify BGRA, so lie and say RGBA.
1061 rgba_inputs.push_back(new sRGBSwitchingFlatInput(inout_format, FORMAT_RGBA_POSTMULTIPLIED_ALPHA, GL_UNSIGNED_BYTE, global_flags.width, global_flags.height));
1062 chain->add_input(rgba_inputs.back());
1066 vector<Effect *> reverse_inputs(rgba_inputs.rbegin(), rgba_inputs.rend());
1067 chain->add_effect(deinterlace_effect, reverse_inputs);
1070 assert(pixel_format == bmusb::PixelFormat_8BitYCbCr ||
1071 pixel_format == bmusb::PixelFormat_10BitYCbCr ||
1072 pixel_format == bmusb::PixelFormat_8BitYCbCrPlanar);
1074 // Most of these settings will be overridden later if using PixelFormat_8BitYCbCrPlanar.
1075 input_ycbcr_format.chroma_subsampling_x = (pixel_format == bmusb::PixelFormat_10BitYCbCr) ? 1 : 2;
1076 input_ycbcr_format.chroma_subsampling_y = 1;
1077 input_ycbcr_format.num_levels = (pixel_format == bmusb::PixelFormat_10BitYCbCr) ? 1024 : 256;
1078 input_ycbcr_format.cb_x_position = 0.0;
1079 input_ycbcr_format.cr_x_position = 0.0;
1080 input_ycbcr_format.cb_y_position = 0.5;
1081 input_ycbcr_format.cr_y_position = 0.5;
1082 input_ycbcr_format.luma_coefficients = YCBCR_REC_709; // Will be overridden later even if not planar.
1083 input_ycbcr_format.full_range = false; // Will be overridden later even if not planar.
1085 for (unsigned i = 0; i < num_inputs; ++i) {
1086 // When using 10-bit input, we're converting to interleaved through v210Converter.
1087 YCbCrInputSplitting splitting;
1088 if (pixel_format == bmusb::PixelFormat_10BitYCbCr) {
1089 splitting = YCBCR_INPUT_INTERLEAVED;
1090 } else if (pixel_format == bmusb::PixelFormat_8BitYCbCr) {
1091 splitting = YCBCR_INPUT_SPLIT_Y_AND_CBCR;
1093 splitting = YCBCR_INPUT_PLANAR;
1095 if (override_bounce) {
1096 ycbcr_inputs.push_back(new NonBouncingYCbCrInput(inout_format, input_ycbcr_format, global_flags.width, global_flags.height, splitting));
1098 ycbcr_inputs.push_back(new YCbCrInput(inout_format, input_ycbcr_format, global_flags.width, global_flags.height, splitting));
1100 chain->add_input(ycbcr_inputs.back());
1104 vector<Effect *> reverse_inputs(ycbcr_inputs.rbegin(), ycbcr_inputs.rend());
1105 chain->add_effect(deinterlace_effect, reverse_inputs);
1110 bool LiveInputWrapper::connect_signal(int signal_num)
1112 if (!user_connectable) {
1116 if (global_mixer == nullptr) {
1121 signal_num = theme->map_signal(signal_num);
1122 connect_signal_raw(signal_num, *theme->input_state);
1126 void LiveInputWrapper::connect_signal_raw(int signal_num, const InputState &input_state)
1128 BufferedFrame first_frame = input_state.buffered_frames[signal_num][0];
1129 if (first_frame.frame == nullptr) {
1133 unsigned width, height;
1135 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)first_frame.frame->userdata;
1136 width = userdata->last_width[first_frame.field_number];
1137 height = userdata->last_height[first_frame.field_number];
1138 if (userdata->last_interlaced) {
1143 movit::YCbCrLumaCoefficients ycbcr_coefficients = input_state.ycbcr_coefficients[signal_num];
1144 bool full_range = input_state.full_range[signal_num];
1146 if (input_state.ycbcr_coefficients_auto[signal_num]) {
1149 // The Blackmagic driver docs claim that the device outputs Y'CbCr
1150 // according to Rec. 601, but this seems to indicate the subsampling
1151 // positions only, as they publish Y'CbCr → RGB formulas that are
1152 // different for HD and SD (corresponding to Rec. 709 and 601, respectively),
1153 // and a Lenovo X1 gen 3 I used to test definitely outputs Rec. 709
1154 // (at least up to rounding error). Other devices seem to use Rec. 601
1155 // even on HD resolutions. Nevertheless, Rec. 709 _is_ the right choice
1156 // for HD, so we default to that if the user hasn't set anything.
1157 if (height >= 720) {
1158 ycbcr_coefficients = YCBCR_REC_709;
1160 ycbcr_coefficients = YCBCR_REC_601;
1164 // This is a global, but it doesn't really matter.
1165 input_ycbcr_format.luma_coefficients = ycbcr_coefficients;
1166 input_ycbcr_format.full_range = full_range;
1168 BufferedFrame last_good_frame = first_frame;
1169 for (unsigned i = 0; i < max(ycbcr_inputs.size(), rgba_inputs.size()); ++i) {
1170 BufferedFrame frame = input_state.buffered_frames[signal_num][i];
1171 if (frame.frame == nullptr) {
1172 // Not enough data; reuse last frame (well, field).
1173 // This is suboptimal, but we have nothing better.
1174 frame = last_good_frame;
1176 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
1178 unsigned this_width = userdata->last_width[frame.field_number];
1179 unsigned this_height = userdata->last_height[frame.field_number];
1180 if (this_width != width || this_height != height) {
1181 // Resolution changed; reuse last frame/field.
1182 frame = last_good_frame;
1183 userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
1186 assert(userdata->pixel_format == pixel_format);
1187 switch (pixel_format) {
1188 case bmusb::PixelFormat_8BitYCbCr:
1189 ycbcr_inputs[i]->set_texture_num(0, userdata->tex_y[frame.field_number]);
1190 ycbcr_inputs[i]->set_texture_num(1, userdata->tex_cbcr[frame.field_number]);
1191 ycbcr_inputs[i]->change_ycbcr_format(input_ycbcr_format);
1192 ycbcr_inputs[i]->set_width(width);
1193 ycbcr_inputs[i]->set_height(height);
1195 case bmusb::PixelFormat_8BitYCbCrPlanar:
1196 ycbcr_inputs[i]->set_texture_num(0, userdata->tex_y[frame.field_number]);
1197 ycbcr_inputs[i]->set_texture_num(1, userdata->tex_cb[frame.field_number]);
1198 ycbcr_inputs[i]->set_texture_num(2, userdata->tex_cr[frame.field_number]);
1199 ycbcr_inputs[i]->change_ycbcr_format(userdata->ycbcr_format);
1200 ycbcr_inputs[i]->set_width(width);
1201 ycbcr_inputs[i]->set_height(height);
1203 case bmusb::PixelFormat_10BitYCbCr:
1204 ycbcr_inputs[i]->set_texture_num(0, userdata->tex_444[frame.field_number]);
1205 ycbcr_inputs[i]->change_ycbcr_format(input_ycbcr_format);
1206 ycbcr_inputs[i]->set_width(width);
1207 ycbcr_inputs[i]->set_height(height);
1209 case bmusb::PixelFormat_8BitBGRA:
1210 rgba_inputs[i]->set_texture_num(userdata->tex_rgba[frame.field_number]);
1211 rgba_inputs[i]->set_width(width);
1212 rgba_inputs[i]->set_height(height);
1218 last_good_frame = frame;
1222 BufferedFrame frame = input_state.buffered_frames[signal_num][0];
1223 CHECK(deinterlace_effect->set_int("current_field_position", frame.field_number));
1229 int call_num_channels(lua_State *L)
1231 lua_getglobal(L, "num_channels");
1233 if (lua_pcall(L, 0, 1, 0) != 0) {
1234 fprintf(stderr, "error running function `num_channels': %s\n", lua_tostring(L, -1));
1235 fprintf(stderr, "Try Nageru.set_num_channels(...) at the start of the script instead.\n");
1239 int num_channels = luaL_checknumber(L, 1);
1241 assert(lua_gettop(L) == 0);
1242 return num_channels;
1247 int Nageru_set_channel_name(lua_State *L)
1249 // NOTE: m is already locked.
1250 Theme *theme = get_theme_updata(L);
1251 unsigned channel = luaL_checknumber(L, 1);
1252 const string text = checkstdstring(L, 2);
1253 theme->channel_names[channel] = text;
1258 int Nageru_set_num_channels(lua_State *L)
1260 // NOTE: m is already locked.
1261 Theme *theme = get_theme_updata(L);
1262 if (theme->startup_finished) {
1263 luaL_error(L, "set_num_channels() can only be called at startup.");
1265 theme->num_channels = luaL_checknumber(L, 1);
1270 int Nageru_set_channel_signal(lua_State *L)
1272 // NOTE: m is already locked.
1273 Theme *theme = get_theme_updata(L);
1274 if (theme->startup_finished) {
1275 luaL_error(L, "set_channel_signal() can only be called at startup.");
1277 unsigned channel = luaL_checknumber(L, 1);
1278 int signal = luaL_checknumber(L, 2);
1279 theme->channel_signals[channel] = signal;
1284 int Nageru_set_supports_wb(lua_State *L)
1286 // NOTE: m is already locked.
1287 Theme *theme = get_theme_updata(L);
1288 if (theme->startup_finished) {
1289 luaL_error(L, "set_supports_wb() can only be called at startup.");
1291 unsigned channel = luaL_checknumber(L, 1);
1292 bool supports_wb = checkbool(L, 2);
1293 theme->channel_supports_wb[channel] = supports_wb;
1298 Theme::Theme(const string &filename, const vector<string> &search_dirs, ResourcePool *resource_pool, unsigned num_cards)
1299 : resource_pool(resource_pool), num_cards(num_cards), signal_to_card_mapping(global_flags.default_stream_mapping)
1302 channel_names[0] = "Live";
1303 channel_names[1] = "Preview";
1305 L = luaL_newstate();
1308 // Search through all directories until we find a file that will load
1309 // (as in, does not return LUA_ERRFILE); then run it. We store load errors
1310 // from all the attempts, and show them once we know we can't find any of them.
1312 vector<string> errors;
1313 bool success = false;
1315 vector<string> real_search_dirs;
1316 if (!filename.empty() && filename[0] == '/') {
1317 real_search_dirs.push_back("");
1319 real_search_dirs = search_dirs;
1324 for (const string &dir : real_search_dirs) {
1328 path = dir + "/" + filename;
1330 int err = luaL_loadfile(L, path.c_str());
1332 // Save the theme for when we're actually going to run it
1333 // (we need to set up the right environment below first,
1334 // and we couldn't do that before, because we didn't know the
1335 // path to put in Nageru.THEME_PATH).
1336 theme_code_ref = luaL_ref(L, LUA_REGISTRYINDEX);
1337 assert(lua_gettop(L) == 0);
1342 errors.push_back(lua_tostring(L, -1));
1344 if (err != LUA_ERRFILE) {
1345 // The file actually loaded, but failed to parse somehow. Abort; don't try the next one.
1351 for (const string &error : errors) {
1352 fprintf(stderr, "%s\n", error.c_str());
1356 assert(lua_gettop(L) == 0);
1358 // Make sure the path exposed to the theme (as Nageru.THEME_PATH;
1359 // can be useful for locating files when talking to CEF) is absolute.
1360 // In a sense, it would be nice if realpath() had a mode not to
1361 // resolve symlinks, but it doesn't, so we only call it if we don't
1362 // already have an absolute path (which may leave ../ elements etc.).
1363 if (path[0] == '/') {
1366 char *absolute_theme_path = realpath(path.c_str(), nullptr);
1367 theme_path = absolute_theme_path;
1368 free(absolute_theme_path);
1371 // Set up the API we provide.
1373 register_class("Scene", Scene_funcs);
1374 register_class("Block", Block_funcs);
1375 register_class("EffectBlueprint", EffectBlueprint_funcs);
1376 register_class("EffectChain", EffectChain_funcs);
1377 register_class("LiveInputWrapper", LiveInputWrapper_funcs);
1378 register_class("ImageInput", ImageInput_funcs);
1379 register_class("VideoInput", VideoInput_funcs);
1380 register_class("HTMLInput", HTMLInput_funcs);
1381 register_class("IdentityEffect", IdentityEffect_funcs, IDENTITY_EFFECT);
1382 register_class("WhiteBalanceEffect", WhiteBalanceEffect_funcs, WHITE_BALANCE_EFFECT);
1383 register_class("ResampleEffect", ResampleEffect_funcs, RESAMPLE_EFFECT);
1384 register_class("PaddingEffect", PaddingEffect_funcs, PADDING_EFFECT);
1385 register_class("IntegralPaddingEffect", IntegralPaddingEffect_funcs, INTEGRAL_PADDING_EFFECT);
1386 register_class("OverlayEffect", OverlayEffect_funcs, OVERLAY_EFFECT);
1387 register_class("ResizeEffect", ResizeEffect_funcs, RESIZE_EFFECT);
1388 register_class("MultiplyEffect", MultiplyEffect_funcs, MULTIPLY_EFFECT);
1389 register_class("MixEffect", MixEffect_funcs, MIX_EFFECT);
1390 register_class("LiftGammaGainEffect", LiftGammaGainEffect_funcs, LIFT_GAMMA_GAIN_EFFECT);
1391 register_class("InputStateInfo", InputStateInfo_funcs);
1392 register_class("ThemeMenu", ThemeMenu_funcs);
1394 // Now actually run the theme to get everything set up.
1395 lua_rawgeti(L, LUA_REGISTRYINDEX, theme_code_ref);
1396 luaL_unref(L, LUA_REGISTRYINDEX, theme_code_ref);
1397 if (lua_pcall(L, 0, 0, 0)) {
1398 fprintf(stderr, "Error when running %s: %s\n", path.c_str(), lua_tostring(L, -1));
1401 assert(lua_gettop(L) == 0);
1403 if (num_channels == -1) {
1404 // Ask it for the number of channels.
1405 num_channels = call_num_channels(L);
1407 startup_finished = true;
1416 void Theme::register_globals()
1418 // Set Nageru.VIDEO_FORMAT_BGRA = bmusb::PixelFormat_8BitBGRA, etc.
1419 const vector<pair<string, int>> num_constants = {
1420 { "VIDEO_FORMAT_BGRA", bmusb::PixelFormat_8BitBGRA },
1421 { "VIDEO_FORMAT_YCBCR", bmusb::PixelFormat_8BitYCbCrPlanar },
1422 { "CHECKABLE", MenuEntry::CHECKABLE },
1423 { "CHECKED", MenuEntry::CHECKED },
1425 const vector<pair<string, string>> str_constants = {
1426 { "THEME_PATH", theme_path },
1429 lua_newtable(L); // t = {}
1431 for (const pair<string, int> &constant : num_constants) {
1432 lua_pushstring(L, constant.first.c_str());
1433 lua_pushinteger(L, constant.second);
1434 lua_settable(L, 1); // t[key] = value
1436 for (const pair<string, string> &constant : str_constants) {
1437 lua_pushstring(L, constant.first.c_str());
1438 lua_pushstring(L, constant.second.c_str());
1439 lua_settable(L, 1); // t[key] = value
1442 const luaL_Reg Nageru_funcs[] = {
1443 { "set_channel_name", Nageru_set_channel_name },
1444 { "set_num_channels", Nageru_set_num_channels },
1445 { "set_channel_signal", Nageru_set_channel_signal },
1446 { "set_supports_wb", Nageru_set_supports_wb },
1449 lua_pushlightuserdata(L, this);
1450 luaL_setfuncs(L, Nageru_funcs, 1); // for (name,f in funcs) { mt[name] = f, with upvalue {theme} }
1452 lua_setglobal(L, "Nageru"); // Nageru = t
1453 assert(lua_gettop(L) == 0);
1456 void Theme::register_class(const char *class_name, const luaL_Reg *funcs, EffectType effect_type)
1458 assert(lua_gettop(L) == 0);
1459 luaL_newmetatable(L, class_name); // mt = {}
1460 lua_pushlightuserdata(L, this);
1461 luaL_setfuncs(L, funcs, 1); // for (name,f in funcs) { mt[name] = f, with upvalue {theme} }
1462 lua_pushvalue(L, -1);
1463 lua_setfield(L, -2, "__index"); // mt.__index = mt
1464 if (effect_type != NO_EFFECT_TYPE) {
1465 lua_pushnumber(L, effect_type);
1466 lua_setfield(L, -2, "__effect_type_id"); // mt.__effect_type_id = effect_type
1468 lua_setglobal(L, class_name); // ClassName = mt
1469 assert(lua_gettop(L) == 0);
1472 Theme::Chain Theme::get_chain_from_effect_chain(EffectChain *effect_chain, unsigned num, const InputState &input_state)
1474 if (!lua_isfunction(L, -1)) {
1475 fprintf(stderr, "Argument #-1 should be a function\n");
1478 lua_pushvalue(L, -1);
1479 shared_ptr<LuaRefWithDeleter> funcref(new LuaRefWithDeleter(&m, L, luaL_ref(L, LUA_REGISTRYINDEX)));
1483 chain.chain = effect_chain;
1484 chain.setup_chain = [this, funcref, input_state, effect_chain]{
1485 lock_guard<mutex> lock(m);
1487 assert(this->input_state == nullptr);
1488 this->input_state = &input_state;
1490 // Set up state, including connecting signals.
1491 lua_rawgeti(L, LUA_REGISTRYINDEX, funcref->get());
1492 if (lua_pcall(L, 0, 0, 0) != 0) {
1493 fprintf(stderr, "error running chain setup callback: %s\n", lua_tostring(L, -1));
1496 assert(lua_gettop(L) == 0);
1498 // The theme can't (or at least shouldn't!) call connect_signal() on
1499 // each FFmpeg or CEF input, so we'll do it here.
1500 if (video_signal_connections.count(effect_chain)) {
1501 for (const VideoSignalConnection &conn : video_signal_connections[effect_chain]) {
1502 conn.wrapper->connect_signal_raw(conn.source->get_card_index(), input_state);
1506 if (html_signal_connections.count(effect_chain)) {
1507 for (const CEFSignalConnection &conn : html_signal_connections[effect_chain]) {
1508 conn.wrapper->connect_signal_raw(conn.source->get_card_index(), input_state);
1513 this->input_state = nullptr;
1518 Theme::Chain Theme::get_chain(unsigned num, float t, unsigned width, unsigned height, const InputState &input_state)
1520 const char *func_name = "get_scene"; // For error reporting.
1523 lock_guard<mutex> lock(m);
1524 assert(lua_gettop(L) == 0);
1525 lua_getglobal(L, "get_scene"); /* function to be called */
1526 if (lua_isnil(L, -1)) {
1527 // Try the pre-1.9.0 name for compatibility.
1529 lua_getglobal(L, "get_chain");
1530 func_name = "get_chain";
1532 lua_pushnumber(L, num);
1533 lua_pushnumber(L, t);
1534 lua_pushnumber(L, width);
1535 lua_pushnumber(L, height);
1536 wrap_lua_object<InputStateInfo>(L, "InputStateInfo", input_state);
1538 if (lua_pcall(L, 5, LUA_MULTRET, 0) != 0) {
1539 fprintf(stderr, "error running function “%s”: %s\n", func_name, lua_tostring(L, -1));
1543 if (luaL_testudata(L, -1, "Scene") != nullptr) {
1544 if (lua_gettop(L) != 1) {
1545 luaL_error(L, "%s() for chain number %d returned an Scene, but also other items", func_name);
1547 Scene *auto_effect_chain = (Scene *)luaL_testudata(L, -1, "Scene");
1548 auto chain_and_setup = auto_effect_chain->get_chain(this, L, num, input_state);
1549 chain.chain = chain_and_setup.first;
1550 chain.setup_chain = move(chain_and_setup.second);
1551 } else if (luaL_testudata(L, -2, "EffectChain") != nullptr) {
1552 // Old-style (pre-Nageru 1.9.0) return of a single chain and prepare function.
1553 if (lua_gettop(L) != 2) {
1554 luaL_error(L, "%s() for chain number %d returned an EffectChain, but needs to also return a prepare function (or use Scene)", func_name);
1556 EffectChain *effect_chain = (EffectChain *)luaL_testudata(L, -2, "EffectChain");
1557 chain = get_chain_from_effect_chain(effect_chain, num, input_state);
1559 luaL_error(L, "%s() for chain number %d did not return an EffectChain or Scene\n", func_name, num);
1561 assert(lua_gettop(L) == 0);
1563 // TODO: Can we do better, e.g. by running setup_chain() and seeing what it references?
1564 // Actually, setup_chain does maybe hold all the references we need now anyway?
1565 chain.input_frames.reserve(num_cards * FRAME_HISTORY_LENGTH);
1566 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
1567 for (unsigned frame_num = 0; frame_num < FRAME_HISTORY_LENGTH; ++frame_num) {
1568 chain.input_frames.push_back(input_state.buffered_frames[card_index][frame_num].frame);
1575 string Theme::get_channel_name(unsigned channel)
1577 lock_guard<mutex> lock(m);
1579 // We never ask the legacy channel_name() about live and preview.
1580 // The defaults are set in our constructor.
1581 if (channel == 0 || channel == 1) {
1582 return channel_names[channel];
1585 lua_getglobal(L, "channel_name");
1586 if (lua_isnil(L, -1)) {
1588 if (channel_names.count(channel)) {
1589 return channel_names[channel];
1591 return "(no title)";
1595 lua_pushnumber(L, channel);
1596 if (lua_pcall(L, 1, 1, 0) != 0) {
1597 fprintf(stderr, "error running function `channel_name': %s\n", lua_tostring(L, -1));
1600 const char *ret = lua_tostring(L, -1);
1601 if (ret == nullptr) {
1602 fprintf(stderr, "function `channel_name' returned nil for channel %d\n", channel);
1603 fprintf(stderr, "Try Nageru.set_channel_name(channel, name) at the start of the script instead.\n");
1607 string retstr = ret;
1609 assert(lua_gettop(L) == 0);
1613 int Theme::get_channel_signal(unsigned channel)
1615 lock_guard<mutex> lock(m);
1616 lua_getglobal(L, "channel_signal");
1617 if (lua_isnil(L, -1)) {
1619 if (channel_signals.count(channel)) {
1620 return channel_signals[channel];
1626 lua_pushnumber(L, channel);
1627 if (lua_pcall(L, 1, 1, 0) != 0) {
1628 fprintf(stderr, "error running function `channel_signal': %s\n", lua_tostring(L, -1));
1629 fprintf(stderr, "Try Nageru.set_channel_signal(channel, signal) at the start of the script instead.\n");
1633 int ret = luaL_checknumber(L, 1);
1635 assert(lua_gettop(L) == 0);
1639 std::string Theme::get_channel_color(unsigned channel)
1641 lock_guard<mutex> lock(m);
1642 lua_getglobal(L, "channel_color");
1643 lua_pushnumber(L, channel);
1644 if (lua_pcall(L, 1, 1, 0) != 0) {
1645 fprintf(stderr, "error running function `channel_color': %s\n", lua_tostring(L, -1));
1649 const char *ret = lua_tostring(L, -1);
1650 if (ret == nullptr) {
1651 fprintf(stderr, "function `channel_color' returned nil for channel %d\n", channel);
1655 string retstr = ret;
1657 assert(lua_gettop(L) == 0);
1661 bool Theme::get_supports_set_wb(unsigned channel)
1663 lock_guard<mutex> lock(m);
1664 lua_getglobal(L, "supports_set_wb");
1665 if (lua_isnil(L, -1)) {
1667 if (channel_supports_wb.count(channel)) {
1668 return channel_supports_wb[channel];
1674 lua_pushnumber(L, channel);
1675 if (lua_pcall(L, 1, 1, 0) != 0) {
1676 fprintf(stderr, "error running function `supports_set_wb': %s\n", lua_tostring(L, -1));
1677 fprintf(stderr, "Try Nageru.set_supports_wb(channel, bool) at the start of the script instead.\n");
1681 bool ret = checkbool(L, -1);
1683 assert(lua_gettop(L) == 0);
1687 void Theme::set_wb(unsigned channel, float r, float g, float b)
1689 lock_guard<mutex> lock(m);
1691 if (channel_signals.count(channel)) {
1692 white_balance_for_signal[channel_signals[channel]] = WhiteBalance{ r, g, b };
1695 lua_getglobal(L, "set_wb");
1696 if (lua_isnil(L, -1)) {
1697 // The function doesn't exist, to just ignore. We've stored the white balance,
1698 // and most likely, it will be picked up by auto white balance instead.
1702 lua_pushnumber(L, channel);
1703 lua_pushnumber(L, r);
1704 lua_pushnumber(L, g);
1705 lua_pushnumber(L, b);
1706 if (lua_pcall(L, 4, 0, 0) != 0) {
1707 fprintf(stderr, "error running function `set_wb': %s\n", lua_tostring(L, -1));
1711 assert(lua_gettop(L) == 0);
1714 Theme::WhiteBalance Theme::get_white_balance_for_signal(int signal)
1716 if (white_balance_for_signal.count(signal)) {
1717 return white_balance_for_signal[signal];
1719 return WhiteBalance{ 1.0, 1.0, 1.0 };
1723 vector<string> Theme::get_transition_names(float t)
1725 lock_guard<mutex> lock(m);
1726 lua_getglobal(L, "get_transitions");
1727 lua_pushnumber(L, t);
1728 if (lua_pcall(L, 1, 1, 0) != 0) {
1729 fprintf(stderr, "error running function `get_transitions': %s\n", lua_tostring(L, -1));
1735 while (lua_next(L, -2) != 0) {
1736 ret.push_back(lua_tostring(L, -1));
1740 assert(lua_gettop(L) == 0);
1744 int Theme::map_signal(int signal_num)
1746 // Negative numbers map to raw signals.
1747 if (signal_num < 0) {
1748 return -1 - signal_num;
1751 lock_guard<mutex> lock(map_m);
1752 if (signal_to_card_mapping.count(signal_num)) {
1753 return signal_to_card_mapping[signal_num];
1757 if (global_flags.output_card != -1 && num_cards > 1) {
1758 // Try to exclude the output card from the default card_index.
1759 card_index = signal_num % (num_cards - 1);
1760 if (card_index >= global_flags.output_card) {
1763 if (signal_num >= int(num_cards - 1)) {
1764 print_warning(L, "Theme asked for input %d, but we only have %u input card(s) (card %d is busy with output).\n",
1765 signal_num, num_cards - 1, global_flags.output_card);
1766 fprintf(stderr, "Mapping to card %d instead.\n", card_index);
1769 card_index = signal_num % num_cards;
1770 if (signal_num >= int(num_cards)) {
1771 print_warning(L, "Theme asked for input %d, but we only have %u card(s).\n", signal_num, num_cards);
1772 fprintf(stderr, "Mapping to card %d instead.\n", card_index);
1775 signal_to_card_mapping[signal_num] = card_index;
1779 void Theme::set_signal_mapping(int signal_num, int card_num)
1781 lock_guard<mutex> lock(map_m);
1782 assert(card_num < int(num_cards));
1783 signal_to_card_mapping[signal_num] = card_num;
1786 void Theme::transition_clicked(int transition_num, float t)
1788 lock_guard<mutex> lock(m);
1789 lua_getglobal(L, "transition_clicked");
1790 lua_pushnumber(L, transition_num);
1791 lua_pushnumber(L, t);
1793 if (lua_pcall(L, 2, 0, 0) != 0) {
1794 fprintf(stderr, "error running function `transition_clicked': %s\n", lua_tostring(L, -1));
1797 assert(lua_gettop(L) == 0);
1800 void Theme::channel_clicked(int preview_num)
1802 lock_guard<mutex> lock(m);
1803 lua_getglobal(L, "channel_clicked");
1804 lua_pushnumber(L, preview_num);
1806 if (lua_pcall(L, 1, 0, 0) != 0) {
1807 fprintf(stderr, "error running function `channel_clicked': %s\n", lua_tostring(L, -1));
1810 assert(lua_gettop(L) == 0);
1814 void destroy(T &ref)
1819 Theme::MenuEntry::~MenuEntry()
1824 luaL_unref(entry.L, LUA_REGISTRYINDEX, entry.lua_ref);
1830 vector<unique_ptr<Theme::MenuEntry>> create_recursive_theme_menu(lua_State *L);
1832 unique_ptr<Theme::MenuEntry> create_theme_menu_entry(lua_State *L, int index)
1834 unique_ptr<Theme::MenuEntry> entry;
1836 lua_rawgeti(L, index, 1);
1837 const string text = checkstdstring(L, -1);
1841 if (lua_objlen(L, -1) > 2) {
1842 lua_rawgeti(L, -1, 3);
1843 flags = luaL_checknumber(L, -1);
1847 lua_rawgeti(L, index, 2);
1848 if (lua_istable(L, -1)) {
1849 vector<unique_ptr<Theme::MenuEntry>> submenu = create_recursive_theme_menu(L);
1850 entry.reset(new Theme::MenuEntry{ text, move(submenu) });
1853 luaL_checktype(L, -1, LUA_TFUNCTION);
1854 int ref = luaL_ref(L, LUA_REGISTRYINDEX);
1855 entry.reset(new Theme::MenuEntry{ text, L, ref, flags });
1860 vector<unique_ptr<Theme::MenuEntry>> create_recursive_theme_menu(lua_State *L)
1862 vector<unique_ptr<Theme::MenuEntry>> menu;
1863 size_t num_elements = lua_objlen(L, -1);
1864 for (size_t i = 1; i <= num_elements; ++i) {
1865 lua_rawgeti(L, -1, i);
1866 menu.emplace_back(create_theme_menu_entry(L, -1));
1874 int Theme::set_theme_menu(lua_State *L)
1878 vector<unique_ptr<MenuEntry>> root_menu;
1879 int num_elements = lua_gettop(L);
1880 for (int i = 1; i <= num_elements; ++i) {
1881 root_menu.emplace_back(create_theme_menu_entry(L, i));
1883 theme_menu.reset(new MenuEntry("", move(root_menu)));
1885 lua_pop(L, num_elements);
1886 assert(lua_gettop(L) == 0);
1888 if (theme_menu_callback != nullptr) {
1889 theme_menu_callback();
1895 void Theme::theme_menu_entry_clicked(int lua_ref)
1897 lock_guard<mutex> lock(m);
1898 lua_rawgeti(L, LUA_REGISTRYINDEX, lua_ref);
1899 if (lua_pcall(L, 0, 0, 0) != 0) {
1900 fprintf(stderr, "error running menu callback: %s\n", lua_tostring(L, -1));
1905 string Theme::format_status_line(const string &disk_space_left_text, double file_length_seconds)
1907 lock_guard<mutex> lock(m);
1908 lua_getglobal(L, "format_status_line");
1909 if (lua_isnil(L, -1)) {
1911 return disk_space_left_text;
1914 lua_pushstring(L, disk_space_left_text.c_str());
1915 lua_pushnumber(L, file_length_seconds);
1916 if (lua_pcall(L, 2, 1, 0) != 0) {
1917 fprintf(stderr, "error running function format_status_line(): %s\n", lua_tostring(L, -1));
1920 string text = checkstdstring(L, 1);
1922 assert(lua_gettop(L) == 0);