6 #include <bmusb/bmusb.h>
13 #include <movit/blur_effect.h>
14 #include <movit/deinterlace_effect.h>
15 #include <movit/effect.h>
16 #include <movit/effect_chain.h>
17 #include <movit/image_format.h>
18 #include <movit/input.h>
19 #include <movit/lift_gamma_gain_effect.h>
20 #include <movit/mix_effect.h>
21 #include <movit/multiply_effect.h>
22 #include <movit/overlay_effect.h>
23 #include <movit/padding_effect.h>
24 #include <movit/resample_effect.h>
25 #include <movit/resize_effect.h>
26 #include <movit/util.h>
27 #include <movit/unsharp_mask_effect.h>
28 #include <movit/white_balance_effect.h>
29 #include <movit/ycbcr.h>
30 #include <movit/ycbcr_input.h>
39 #include "audio_mixer.h"
41 #include "input_mapping.h"
44 #include "shared/shared_defs.h"
45 #include "tweaked_inputs.h"
47 #include "cef_capture.h"
49 #include "ffmpeg_capture.h"
51 #include "image_input.h"
52 #include "input_state.h"
53 #include "lua_utils.h"
54 #include "mainwindow.h"
55 #include "pbo_frame_allocator.h"
65 using namespace movit;
67 extern Mixer *global_mixer;
69 constexpr unsigned Theme::MenuEntry::CHECKABLE;
70 constexpr unsigned Theme::MenuEntry::CHECKED;
72 Theme *get_theme_updata(lua_State* L)
74 luaL_checktype(L, lua_upvalueindex(1), LUA_TLIGHTUSERDATA);
75 return (Theme *)lua_touserdata(L, lua_upvalueindex(1));
78 void print_warning(lua_State* L, const char *format, ...)
83 vsnprintf(buf, sizeof(buf), format, ap);
87 lua_getstack(L, 1, &ar);
88 lua_getinfo(L, "nSl", &ar);
89 fprintf(stderr, "WARNING: %s:%d: %s", ar.source, ar.currentline, buf);
92 int ThemeMenu_set(lua_State *L)
94 Theme *theme = get_theme_updata(L);
95 return theme->set_theme_menu(L);
98 InputStateInfo::InputStateInfo(const InputState &input_state)
100 for (unsigned signal_num = 0; signal_num < MAX_VIDEO_CARDS; ++signal_num) {
101 BufferedFrame frame = input_state.buffered_frames[signal_num][0];
102 if (frame.frame == nullptr) {
103 last_width[signal_num] = last_height[signal_num] = 0;
104 last_interlaced[signal_num] = false;
105 last_has_signal[signal_num] = false;
106 last_is_connected[signal_num] = false;
109 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
110 last_width[signal_num] = userdata->last_width[frame.field_number];
111 last_height[signal_num] = userdata->last_height[frame.field_number];
112 last_interlaced[signal_num] = userdata->last_interlaced;
113 last_has_signal[signal_num] = userdata->last_has_signal;
114 last_is_connected[signal_num] = userdata->last_is_connected;
115 last_frame_rate_nom[signal_num] = userdata->last_frame_rate_nom;
116 last_frame_rate_den[signal_num] = userdata->last_frame_rate_den;
117 last_pixel_format[signal_num] = userdata->pixel_format;
118 has_last_subtitle[signal_num] = userdata->has_last_subtitle;
119 last_subtitle[signal_num] = userdata->last_subtitle;
123 // An effect that does nothing.
124 class IdentityEffect : public Effect {
127 string effect_type_id() const override { return "IdentityEffect"; }
128 string output_fragment_shader() override { return read_file("identity.frag"); }
131 Effect *instantiate_effect(EffectChain *chain, EffectType effect_type)
133 switch (effect_type) {
134 case IDENTITY_EFFECT:
135 return new IdentityEffect;
136 case WHITE_BALANCE_EFFECT:
137 case AUTO_WHITE_BALANCE_EFFECT:
138 return new WhiteBalanceEffect;
139 case RESAMPLE_EFFECT:
140 return new ResampleEffect;
142 return new PaddingEffect;
143 case INTEGRAL_PADDING_EFFECT:
144 return new IntegralPaddingEffect;
146 return new OverlayEffect;
148 return new ResizeEffect;
149 case MULTIPLY_EFFECT:
150 return new MultiplyEffect;
152 return new MixEffect;
153 case LIFT_GAMMA_GAIN_EFFECT:
154 return new LiftGammaGainEffect;
156 return new BlurEffect;
157 case UNSHARP_MASK_EFFECT:
158 return new UnsharpMaskEffect;
160 fprintf(stderr, "Unhandled effect type %d\n", effect_type);
167 Effect *get_effect_from_blueprint(EffectChain *chain, lua_State *L, int idx)
169 EffectBlueprint *blueprint = *(EffectBlueprint **)luaL_checkudata(L, idx, "EffectBlueprint");
170 if (blueprint->effect != nullptr) {
171 luaL_error(L, "An effect can currently only be added to one chain.\n");
174 Effect *effect = instantiate_effect(chain, blueprint->effect_type);
176 // Set the parameters that were deferred earlier.
177 for (const auto &kv : blueprint->int_parameters) {
178 if (!effect->set_int(kv.first, kv.second)) {
179 luaL_error(L, "Effect refused set_int(\"%s\", %d) (invalid key?)", kv.first.c_str(), kv.second);
182 for (const auto &kv : blueprint->float_parameters) {
183 if (!effect->set_float(kv.first, kv.second)) {
184 luaL_error(L, "Effect refused set_float(\"%s\", %f) (invalid key?)", kv.first.c_str(), kv.second);
187 for (const auto &kv : blueprint->vec3_parameters) {
188 if (!effect->set_vec3(kv.first, kv.second.data())) {
189 luaL_error(L, "Effect refused set_vec3(\"%s\", %f, %f, %f) (invalid key?)", kv.first.c_str(),
190 kv.second[0], kv.second[1], kv.second[2]);
193 for (const auto &kv : blueprint->vec4_parameters) {
194 if (!effect->set_vec4(kv.first, kv.second.data())) {
195 luaL_error(L, "Effect refused set_vec4(\"%s\", %f, %f, %f, %f) (invalid key?)", kv.first.c_str(),
196 kv.second[0], kv.second[1], kv.second[2], kv.second[3]);
199 blueprint->effect = effect;
203 InputStateInfo *get_input_state_info(lua_State *L, int idx)
205 if (luaL_testudata(L, idx, "InputStateInfo")) {
206 return (InputStateInfo *)lua_touserdata(L, idx);
208 luaL_error(L, "Error: Index #%d was not InputStateInfo\n", idx);
214 bool checkbool(lua_State* L, int idx)
216 luaL_checktype(L, idx, LUA_TBOOLEAN);
217 return lua_toboolean(L, idx);
220 string checkstdstring(lua_State *L, int index)
223 const char* cstr = lua_tolstring(L, index, &len);
224 return string(cstr, len);
229 int Scene_new(lua_State* L)
231 assert(lua_gettop(L) == 2);
232 Theme *theme = get_theme_updata(L);
233 int aspect_w = luaL_checknumber(L, 1);
234 int aspect_h = luaL_checknumber(L, 2);
236 return wrap_lua_object<Scene>(L, "Scene", theme, aspect_w, aspect_h);
239 int Scene_gc(lua_State* L)
241 assert(lua_gettop(L) == 1);
242 Scene *chain = (Scene *)luaL_checkudata(L, 1, "Scene");
249 void add_outputs_and_finalize(EffectChain *chain, bool is_main_chain)
251 // Add outputs as needed.
252 // NOTE: If you change any details about the output format, you will need to
253 // also update what's given to the muxer (HTTPD::Mux constructor) and
254 // what's put in the H.264 stream (sps_rbsp()).
255 ImageFormat inout_format;
256 inout_format.color_space = COLORSPACE_REC_709;
258 // Output gamma is tricky. We should output Rec. 709 for TV, except that
259 // we expect to run with web players and others that don't really care and
260 // just output with no conversion. So that means we'll need to output sRGB,
261 // even though H.264 has no setting for that (we use “unspecified”).
262 inout_format.gamma_curve = GAMMA_sRGB;
265 YCbCrFormat output_ycbcr_format;
266 // We actually output 4:2:0 and/or 4:2:2 in the end, but chroma subsampling
267 // happens in a pass not run by Movit (see ChromaSubsampler::subsample_chroma()).
268 output_ycbcr_format.chroma_subsampling_x = 1;
269 output_ycbcr_format.chroma_subsampling_y = 1;
271 // This will be overridden if HDMI/SDI output is in force.
272 if (global_flags.ycbcr_rec709_coefficients) {
273 output_ycbcr_format.luma_coefficients = YCBCR_REC_709;
275 output_ycbcr_format.luma_coefficients = YCBCR_REC_601;
278 output_ycbcr_format.full_range = false;
279 output_ycbcr_format.num_levels = 1 << global_flags.bit_depth;
281 GLenum type = global_flags.bit_depth > 8 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_BYTE;
283 chain->add_ycbcr_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED, output_ycbcr_format, YCBCR_OUTPUT_SPLIT_Y_AND_CBCR, type);
285 // If we're using zerocopy video encoding (so the destination
286 // Y texture is owned by VA-API and will be unavailable for
287 // display), add a copy, where we'll only be using the Y component.
288 if (global_flags.use_zerocopy) {
289 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.
291 chain->set_dither_bits(global_flags.bit_depth > 8 ? 16 : 8);
292 chain->set_output_origin(OUTPUT_ORIGIN_TOP_LEFT);
294 chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
302 int EffectChain_new(lua_State* L)
304 assert(lua_gettop(L) == 2);
305 Theme *theme = get_theme_updata(L);
306 int aspect_w = luaL_checknumber(L, 1);
307 int aspect_h = luaL_checknumber(L, 2);
309 return wrap_lua_object<EffectChain>(L, "EffectChain", aspect_w, aspect_h, theme->get_resource_pool());
312 int EffectChain_gc(lua_State* L)
314 assert(lua_gettop(L) == 1);
315 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
316 chain->~EffectChain();
320 int EffectChain_add_live_input(lua_State* L)
322 assert(lua_gettop(L) == 3);
323 Theme *theme = get_theme_updata(L);
324 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
325 bool override_bounce = checkbool(L, 2);
326 bool deinterlace = checkbool(L, 3);
327 bmusb::PixelFormat pixel_format = global_flags.bit_depth > 8 ? bmusb::PixelFormat_10BitYCbCr : bmusb::PixelFormat_8BitYCbCr;
329 // Needs to be nonowned to match add_video_input (see below).
330 return wrap_lua_object_nonowned<LiveInputWrapper>(L, "LiveInputWrapper", theme, chain, pixel_format, override_bounce, deinterlace, /*user_connectable=*/true);
333 int EffectChain_add_video_input(lua_State* L)
335 assert(lua_gettop(L) == 3);
336 Theme *theme = get_theme_updata(L);
337 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
338 FFmpegCapture **capture = (FFmpegCapture **)luaL_checkudata(L, 2, "VideoInput");
339 bool deinterlace = checkbool(L, 3);
341 // These need to be nonowned, so that the LiveInputWrapper still exists
342 // and can feed frames to the right EffectChain even if the Lua code
343 // doesn't care about the object anymore. (If we change this, we'd need
344 // to also unregister the signal connection on __gc.)
345 int ret = wrap_lua_object_nonowned<LiveInputWrapper>(
346 L, "LiveInputWrapper", theme, chain, (*capture)->get_current_pixel_format(),
347 /*override_bounce=*/false, deinterlace, /*user_connectable=*/false);
349 Theme *theme = get_theme_updata(L);
350 LiveInputWrapper **live_input = (LiveInputWrapper **)lua_touserdata(L, -1);
351 theme->register_video_signal_connection(chain, *live_input, *capture);
357 int EffectChain_add_html_input(lua_State* L)
359 assert(lua_gettop(L) == 2);
360 Theme *theme = get_theme_updata(L);
361 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
362 CEFCapture **capture = (CEFCapture **)luaL_checkudata(L, 2, "HTMLInput");
364 // These need to be nonowned, so that the LiveInputWrapper still exists
365 // and can feed frames to the right EffectChain even if the Lua code
366 // doesn't care about the object anymore. (If we change this, we'd need
367 // to also unregister the signal connection on __gc.)
368 int ret = wrap_lua_object_nonowned<LiveInputWrapper>(
369 L, "LiveInputWrapper", theme, chain, (*capture)->get_current_pixel_format(),
370 /*override_bounce=*/false, /*deinterlace=*/false, /*user_connectable=*/false);
372 Theme *theme = get_theme_updata(L);
373 LiveInputWrapper **live_input = (LiveInputWrapper **)lua_touserdata(L, -1);
374 theme->register_html_signal_connection(chain, *live_input, *capture);
380 int EffectChain_add_effect(lua_State* L)
382 assert(lua_gettop(L) >= 2);
383 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
385 // TODO: Better error reporting.
387 if (luaL_testudata(L, 2, "ImageInput")) {
388 effect = *(ImageInput **)luaL_checkudata(L, 2, "ImageInput");
390 effect = get_effect_from_blueprint(chain, L, 2);
392 if (lua_gettop(L) == 2) {
393 if (effect->num_inputs() == 0) {
394 chain->add_input((Input *)effect);
396 chain->add_effect(effect);
399 vector<Effect *> inputs;
400 for (int idx = 3; idx <= lua_gettop(L); ++idx) {
401 if (luaL_testudata(L, idx, "LiveInputWrapper")) {
402 LiveInputWrapper **input = (LiveInputWrapper **)lua_touserdata(L, idx);
403 inputs.push_back((*input)->get_effect());
404 } else if (luaL_testudata(L, idx, "ImageInput")) {
405 ImageInput *image = *(ImageInput **)luaL_checkudata(L, idx, "ImageInput");
406 inputs.push_back(image);
408 EffectBlueprint *blueprint = *(EffectBlueprint **)luaL_checkudata(L, idx, "EffectBlueprint");
409 assert(blueprint->effect != nullptr); // Parent must be added to the graph.
410 inputs.push_back(blueprint->effect);
413 chain->add_effect(effect, inputs);
416 lua_settop(L, 2); // Return the effect itself.
418 // Make sure Lua doesn't garbage-collect it away.
419 lua_pushvalue(L, -1);
420 luaL_ref(L, LUA_REGISTRYINDEX); // TODO: leak?
425 int EffectChain_finalize(lua_State* L)
427 assert(lua_gettop(L) == 2);
428 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
429 bool is_main_chain = checkbool(L, 2);
430 add_outputs_and_finalize(chain, is_main_chain);
434 int LiveInputWrapper_connect_signal(lua_State* L)
436 assert(lua_gettop(L) == 2);
437 LiveInputWrapper **input = (LiveInputWrapper **)luaL_checkudata(L, 1, "LiveInputWrapper");
438 int signal_num = luaL_checknumber(L, 2);
439 bool success = (*input)->connect_signal(signal_num);
441 print_warning(L, "Calling connect_signal() on a video or HTML input. Ignoring.\n");
446 int ImageInput_new(lua_State* L)
448 assert(lua_gettop(L) == 1);
449 string filename = checkstdstring(L, 1);
450 return wrap_lua_object_nonowned<ImageInput>(L, "ImageInput", filename);
453 int VideoInput_new(lua_State* L)
455 assert(lua_gettop(L) == 2);
456 string filename = checkstdstring(L, 1);
457 int pixel_format = luaL_checknumber(L, 2);
458 if (pixel_format != bmusb::PixelFormat_8BitYCbCrPlanar &&
459 pixel_format != bmusb::PixelFormat_8BitBGRA) {
460 print_warning(L, "Invalid enum %d used for video format, choosing Y'CbCr.\n", pixel_format);
461 pixel_format = bmusb::PixelFormat_8BitYCbCrPlanar;
463 int ret = wrap_lua_object_nonowned<FFmpegCapture>(L, "VideoInput", filename, global_flags.width, global_flags.height);
465 FFmpegCapture **capture = (FFmpegCapture **)lua_touserdata(L, -1);
466 (*capture)->set_pixel_format(bmusb::PixelFormat(pixel_format));
468 Theme *theme = get_theme_updata(L);
469 theme->register_video_input(*capture);
474 int VideoInput_rewind(lua_State* L)
476 assert(lua_gettop(L) == 1);
477 FFmpegCapture **video_input = (FFmpegCapture **)luaL_checkudata(L, 1, "VideoInput");
478 (*video_input)->rewind();
482 int VideoInput_disconnect(lua_State* L)
484 assert(lua_gettop(L) == 1);
485 FFmpegCapture **video_input = (FFmpegCapture **)luaL_checkudata(L, 1, "VideoInput");
486 (*video_input)->disconnect();
490 int VideoInput_change_rate(lua_State* L)
492 assert(lua_gettop(L) == 2);
493 FFmpegCapture **video_input = (FFmpegCapture **)luaL_checkudata(L, 1, "VideoInput");
494 double new_rate = luaL_checknumber(L, 2);
495 (*video_input)->change_rate(new_rate);
499 int VideoInput_get_signal_num(lua_State* L)
501 assert(lua_gettop(L) == 1);
502 FFmpegCapture **video_input = (FFmpegCapture **)luaL_checkudata(L, 1, "VideoInput");
503 lua_pushnumber(L, -1 - (*video_input)->get_card_index());
507 int HTMLInput_new(lua_State* L)
510 assert(lua_gettop(L) == 1);
511 string url = checkstdstring(L, 1);
512 int ret = wrap_lua_object_nonowned<CEFCapture>(L, "HTMLInput", url, global_flags.width, global_flags.height);
514 CEFCapture **capture = (CEFCapture **)lua_touserdata(L, -1);
515 Theme *theme = get_theme_updata(L);
516 theme->register_html_input(*capture);
520 fprintf(stderr, "This version of Nageru has been compiled without CEF support.\n");
521 fprintf(stderr, "HTMLInput is not available.\n");
527 int HTMLInput_set_url(lua_State* L)
529 assert(lua_gettop(L) == 2);
530 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
531 string new_url = checkstdstring(L, 2);
532 (*video_input)->set_url(new_url);
536 int HTMLInput_reload(lua_State* L)
538 assert(lua_gettop(L) == 1);
539 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
540 (*video_input)->reload();
544 int HTMLInput_set_max_fps(lua_State* L)
546 assert(lua_gettop(L) == 2);
547 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
548 int max_fps = lrint(luaL_checknumber(L, 2));
549 (*video_input)->set_max_fps(max_fps);
553 int HTMLInput_execute_javascript_async(lua_State* L)
555 assert(lua_gettop(L) == 2);
556 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
557 string js = checkstdstring(L, 2);
558 (*video_input)->execute_javascript_async(js);
562 int HTMLInput_resize(lua_State* L)
564 assert(lua_gettop(L) == 3);
565 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
566 unsigned width = lrint(luaL_checknumber(L, 2));
567 unsigned height = lrint(luaL_checknumber(L, 3));
568 (*video_input)->resize(width, height);
572 int HTMLInput_get_signal_num(lua_State* L)
574 assert(lua_gettop(L) == 1);
575 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
576 lua_pushnumber(L, -1 - (*video_input)->get_card_index());
581 int IdentityEffect_new(lua_State* L)
583 assert(lua_gettop(L) == 0);
584 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", IDENTITY_EFFECT);
587 int WhiteBalanceEffect_new(lua_State* L)
589 assert(lua_gettop(L) == 0);
590 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", WHITE_BALANCE_EFFECT);
593 int ResampleEffect_new(lua_State* L)
595 assert(lua_gettop(L) == 0);
596 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", RESAMPLE_EFFECT);
599 int PaddingEffect_new(lua_State* L)
601 assert(lua_gettop(L) == 0);
602 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", PADDING_EFFECT);
605 int IntegralPaddingEffect_new(lua_State* L)
607 assert(lua_gettop(L) == 0);
608 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", INTEGRAL_PADDING_EFFECT);
611 int OverlayEffect_new(lua_State* L)
613 assert(lua_gettop(L) == 0);
614 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", OVERLAY_EFFECT);
617 int ResizeEffect_new(lua_State* L)
619 assert(lua_gettop(L) == 0);
620 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", RESIZE_EFFECT);
623 int MultiplyEffect_new(lua_State* L)
625 assert(lua_gettop(L) == 0);
626 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", MULTIPLY_EFFECT);
629 int MixEffect_new(lua_State* L)
631 assert(lua_gettop(L) == 0);
632 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", MIX_EFFECT);
635 int LiftGammaGainEffect_new(lua_State* L)
637 assert(lua_gettop(L) == 0);
638 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", LIFT_GAMMA_GAIN_EFFECT);
641 int BlurEffect_new(lua_State* L)
643 assert(lua_gettop(L) == 0);
644 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", BLUR_EFFECT);
647 int UnsharpMaskEffect_new(lua_State* L)
649 assert(lua_gettop(L) == 0);
650 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", UNSHARP_MASK_EFFECT);
653 int InputStateInfo_get_width(lua_State* L)
655 assert(lua_gettop(L) == 2);
656 InputStateInfo *input_state_info = get_input_state_info(L, 1);
658 Theme *theme = get_theme_updata(L);
659 int card_idx = theme->map_signal_to_card(luaL_checknumber(L, 2));
660 lua_pushnumber(L, input_state_info->last_width[card_idx]);
664 int InputStateInfo_get_height(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 card_idx = theme->map_signal_to_card(luaL_checknumber(L, 2));
670 lua_pushnumber(L, input_state_info->last_height[card_idx]);
674 int InputStateInfo_get_frame_height(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 card_idx = theme->map_signal_to_card(luaL_checknumber(L, 2));
680 unsigned height = input_state_info->last_height[card_idx];
681 if (input_state_info->last_interlaced[card_idx]) {
684 lua_pushnumber(L, height);
688 int InputStateInfo_get_interlaced(lua_State* L)
690 assert(lua_gettop(L) == 2);
691 InputStateInfo *input_state_info = get_input_state_info(L, 1);
692 Theme *theme = get_theme_updata(L);
693 int card_idx = theme->map_signal_to_card(luaL_checknumber(L, 2));
694 lua_pushboolean(L, input_state_info->last_interlaced[card_idx]);
698 int InputStateInfo_get_has_signal(lua_State* L)
700 assert(lua_gettop(L) == 2);
701 InputStateInfo *input_state_info = get_input_state_info(L, 1);
702 Theme *theme = get_theme_updata(L);
703 int card_idx = theme->map_signal_to_card(luaL_checknumber(L, 2));
704 lua_pushboolean(L, input_state_info->last_has_signal[card_idx]);
708 int InputStateInfo_get_is_connected(lua_State* L)
710 assert(lua_gettop(L) == 2);
711 InputStateInfo *input_state_info = get_input_state_info(L, 1);
712 Theme *theme = get_theme_updata(L);
713 int card_idx = theme->map_signal_to_card(luaL_checknumber(L, 2));
714 lua_pushboolean(L, input_state_info->last_is_connected[card_idx]);
718 int InputStateInfo_get_frame_rate_nom(lua_State* L)
720 assert(lua_gettop(L) == 2);
721 InputStateInfo *input_state_info = get_input_state_info(L, 1);
722 Theme *theme = get_theme_updata(L);
723 int card_idx = theme->map_signal_to_card(luaL_checknumber(L, 2));
724 lua_pushnumber(L, input_state_info->last_frame_rate_nom[card_idx]);
728 int InputStateInfo_get_frame_rate_den(lua_State* L)
730 assert(lua_gettop(L) == 2);
731 InputStateInfo *input_state_info = get_input_state_info(L, 1);
732 Theme *theme = get_theme_updata(L);
733 int card_idx = theme->map_signal_to_card(luaL_checknumber(L, 2));
734 lua_pushnumber(L, input_state_info->last_frame_rate_den[card_idx]);
738 int InputStateInfo_get_last_subtitle(lua_State* L)
740 assert(lua_gettop(L) == 2);
741 InputStateInfo *input_state_info = get_input_state_info(L, 1);
742 Theme *theme = get_theme_updata(L);
743 int card_idx = theme->map_signal_to_card(luaL_checknumber(L, 2));
744 if (!input_state_info->has_last_subtitle[card_idx]) {
747 lua_pushstring(L, input_state_info->last_subtitle[card_idx].c_str());
754 // Helper function to write e.g. “60” or “59.94”.
755 string format_frame_rate(int nom, int den)
758 if (nom % den == 0) {
759 snprintf(buf, sizeof(buf), "%d", nom / den);
761 snprintf(buf, sizeof(buf), "%.2f", double(nom) / den);
766 // Helper function to write e.g. “720p60”.
767 string get_human_readable_resolution(const InputStateInfo *input_state_info, int signal_num)
770 if (input_state_info->last_interlaced[signal_num]) {
771 snprintf(buf, sizeof(buf), "%di", input_state_info->last_height[signal_num] * 2);
773 // Show field rate instead of frame rate; really for cosmetics only
774 // (and actually contrary to EBU recommendations, although in line
775 // with typical user expectations).
776 return buf + format_frame_rate(input_state_info->last_frame_rate_nom[signal_num] * 2,
777 input_state_info->last_frame_rate_den[signal_num]);
779 snprintf(buf, sizeof(buf), "%dp", input_state_info->last_height[signal_num]);
780 return buf + format_frame_rate(input_state_info->last_frame_rate_nom[signal_num],
781 input_state_info->last_frame_rate_den[signal_num]);
787 int InputStateInfo_get_human_readable_resolution(lua_State* L)
789 assert(lua_gettop(L) == 2);
790 InputStateInfo *input_state_info = get_input_state_info(L, 1);
791 Theme *theme = get_theme_updata(L);
792 int card_idx = theme->map_signal_to_card(luaL_checknumber(L, 2));
795 if (!input_state_info->last_is_connected[card_idx]) {
796 str = "disconnected";
797 } else if (input_state_info->last_height[card_idx] <= 0) {
799 } else if (!input_state_info->last_has_signal[card_idx]) {
800 if (input_state_info->last_height[card_idx] == 525) {
801 // Special mode for the USB3 cards.
804 str = get_human_readable_resolution(input_state_info, card_idx) + ", no signal";
807 str = get_human_readable_resolution(input_state_info, card_idx);
810 lua_pushstring(L, str.c_str());
815 int EffectBlueprint_set_int(lua_State *L)
817 assert(lua_gettop(L) == 3);
818 EffectBlueprint *blueprint = *(EffectBlueprint **)luaL_checkudata(L, 1, "EffectBlueprint");
819 string key = checkstdstring(L, 2);
820 float value = luaL_checknumber(L, 3);
821 if (blueprint->effect != nullptr) {
822 if (!blueprint->effect->set_int(key, value)) {
823 luaL_error(L, "Effect refused set_int(\"%s\", %d) (invalid key?)", key.c_str(), int(value));
826 // TODO: check validity already here, if possible?
827 blueprint->int_parameters[key] = value;
832 int EffectBlueprint_set_float(lua_State *L)
834 assert(lua_gettop(L) == 3);
835 EffectBlueprint *blueprint = *(EffectBlueprint **)luaL_checkudata(L, 1, "EffectBlueprint");
836 string key = checkstdstring(L, 2);
837 float value = luaL_checknumber(L, 3);
838 if (blueprint->effect != nullptr) {
839 if (!blueprint->effect->set_float(key, value)) {
840 luaL_error(L, "Effect refused set_float(\"%s\", %d) (invalid key?)", key.c_str(), int(value));
843 // TODO: check validity already here, if possible?
844 blueprint->float_parameters[key] = value;
849 int EffectBlueprint_set_vec3(lua_State *L)
851 assert(lua_gettop(L) == 5);
852 EffectBlueprint *blueprint = *(EffectBlueprint **)luaL_checkudata(L, 1, "EffectBlueprint");
853 string key = checkstdstring(L, 2);
855 v[0] = luaL_checknumber(L, 3);
856 v[1] = luaL_checknumber(L, 4);
857 v[2] = luaL_checknumber(L, 5);
859 if (blueprint->effect != nullptr) {
860 if (!blueprint->effect->set_vec3(key, v.data())) {
861 luaL_error(L, "Effect refused set_vec3(\"%s\", %f, %f, %f) (invalid key?)", key.c_str(),
865 // TODO: check validity already here, if possible?
866 blueprint->vec3_parameters[key] = v;
872 int EffectBlueprint_set_vec4(lua_State *L)
874 assert(lua_gettop(L) == 6);
875 EffectBlueprint *blueprint = *(EffectBlueprint **)luaL_checkudata(L, 1, "EffectBlueprint");
876 string key = checkstdstring(L, 2);
878 v[0] = luaL_checknumber(L, 3);
879 v[1] = luaL_checknumber(L, 4);
880 v[2] = luaL_checknumber(L, 5);
881 v[3] = luaL_checknumber(L, 6);
882 if (blueprint->effect != nullptr) {
883 if (!blueprint->effect->set_vec4(key, v.data())) {
884 luaL_error(L, "Effect refused set_vec4(\"%s\", %f, %f, %f, %f) (invalid key?)", key.c_str(),
885 v[0], v[1], v[2], v[3]);
888 // TODO: check validity already here, if possible?
889 blueprint->vec4_parameters[key] = v;
894 const luaL_Reg Scene_funcs[] = {
895 { "new", Scene_new },
896 { "__gc", Scene_gc },
897 { "add_input", Scene::add_input },
898 { "add_white_balance", Scene::add_white_balance },
899 { "add_effect", Scene::add_effect },
900 { "add_optional_effect", Scene::add_optional_effect },
901 { "finalize", Scene::finalize },
905 const luaL_Reg Block_funcs[] = {
906 { "display", Block_display },
907 { "choose", Block_choose },
908 { "enable", Block_enable },
909 { "enable_if", Block_enable_if },
910 { "disable", Block_disable },
911 { "always_disable_if_disabled", Block_always_disable_if_disabled },
912 { "promise_to_disable_if_enabled", Block_promise_to_disable_if_enabled },
913 { "set_int", Block_set_int },
914 { "set_float", Block_set_float },
915 { "set_vec3", Block_set_vec3 },
916 { "set_vec4", Block_set_vec4 },
920 const luaL_Reg EffectBlueprint_funcs[] = {
921 // NOTE: No new() function; that's for the individual effects.
922 { "set_int", EffectBlueprint_set_int },
923 { "set_float", EffectBlueprint_set_float },
924 { "set_vec3", EffectBlueprint_set_vec3 },
925 { "set_vec4", EffectBlueprint_set_vec4 },
929 const luaL_Reg EffectChain_funcs[] = {
930 { "new", EffectChain_new },
931 { "__gc", EffectChain_gc },
932 { "add_live_input", EffectChain_add_live_input },
933 { "add_video_input", EffectChain_add_video_input },
935 { "add_html_input", EffectChain_add_html_input },
937 { "add_effect", EffectChain_add_effect },
938 { "finalize", EffectChain_finalize },
942 const luaL_Reg LiveInputWrapper_funcs[] = {
943 { "connect_signal", LiveInputWrapper_connect_signal },
947 const luaL_Reg ImageInput_funcs[] = {
948 { "new", ImageInput_new },
952 const luaL_Reg VideoInput_funcs[] = {
953 { "new", VideoInput_new },
954 { "rewind", VideoInput_rewind },
955 { "disconnect", VideoInput_disconnect },
956 { "change_rate", VideoInput_change_rate },
957 { "get_signal_num", VideoInput_get_signal_num },
961 const luaL_Reg HTMLInput_funcs[] = {
962 { "new", HTMLInput_new },
964 { "set_url", HTMLInput_set_url },
965 { "reload", HTMLInput_reload },
966 { "set_max_fps", HTMLInput_set_max_fps },
967 { "execute_javascript_async", HTMLInput_execute_javascript_async },
968 { "resize", HTMLInput_resize },
969 { "get_signal_num", HTMLInput_get_signal_num },
975 // All of these are solely for new(); the returned metatable will be that of
976 // EffectBlueprint, and Effect (returned from add_effect()) is its own type.
978 const luaL_Reg IdentityEffect_funcs[] = {
979 { "new", IdentityEffect_new },
983 const luaL_Reg WhiteBalanceEffect_funcs[] = {
984 { "new", WhiteBalanceEffect_new },
988 const luaL_Reg ResampleEffect_funcs[] = {
989 { "new", ResampleEffect_new },
993 const luaL_Reg PaddingEffect_funcs[] = {
994 { "new", PaddingEffect_new },
998 const luaL_Reg IntegralPaddingEffect_funcs[] = {
999 { "new", IntegralPaddingEffect_new },
1003 const luaL_Reg OverlayEffect_funcs[] = {
1004 { "new", OverlayEffect_new },
1008 const luaL_Reg ResizeEffect_funcs[] = {
1009 { "new", ResizeEffect_new },
1013 const luaL_Reg MultiplyEffect_funcs[] = {
1014 { "new", MultiplyEffect_new },
1018 const luaL_Reg MixEffect_funcs[] = {
1019 { "new", MixEffect_new },
1023 const luaL_Reg LiftGammaGainEffect_funcs[] = {
1024 { "new", LiftGammaGainEffect_new },
1028 const luaL_Reg BlurEffect_funcs[] = {
1029 { "new", BlurEffect_new },
1033 const luaL_Reg UnsharpMaskEffect_funcs[] = {
1034 { "new", UnsharpMaskEffect_new },
1040 const luaL_Reg InputStateInfo_funcs[] = {
1041 { "get_width", InputStateInfo_get_width },
1042 { "get_height", InputStateInfo_get_height },
1043 { "get_frame_width", InputStateInfo_get_width }, // Same as get_width().
1044 { "get_frame_height", InputStateInfo_get_frame_height },
1045 { "get_interlaced", InputStateInfo_get_interlaced },
1046 { "get_has_signal", InputStateInfo_get_has_signal },
1047 { "get_is_connected", InputStateInfo_get_is_connected },
1048 { "get_frame_rate_nom", InputStateInfo_get_frame_rate_nom },
1049 { "get_frame_rate_den", InputStateInfo_get_frame_rate_den },
1050 { "get_last_subtitle", InputStateInfo_get_last_subtitle },
1051 { "get_human_readable_resolution", InputStateInfo_get_human_readable_resolution },
1055 const luaL_Reg ThemeMenu_funcs[] = {
1056 { "set", ThemeMenu_set },
1062 LiveInputWrapper::LiveInputWrapper(
1065 bmusb::PixelFormat pixel_format,
1066 bool override_bounce,
1068 bool user_connectable)
1070 pixel_format(pixel_format),
1071 deinterlace(deinterlace),
1072 user_connectable(user_connectable)
1074 ImageFormat inout_format;
1075 inout_format.color_space = COLORSPACE_sRGB;
1077 // Gamma curve depends on the input signal, and we don't really get any
1078 // indications. A camera would be expected to do Rec. 709, but
1079 // I haven't checked if any do in practice. However, computers _do_ output
1080 // in sRGB gamma (ie., they don't convert from sRGB to Rec. 709), and
1081 // I wouldn't really be surprised if most non-professional cameras do, too.
1082 // So we pick sRGB as the least evil here.
1083 inout_format.gamma_curve = GAMMA_sRGB;
1085 unsigned num_inputs;
1087 deinterlace_effect = new movit::DeinterlaceEffect();
1089 // As per the comments in deinterlace_effect.h, we turn this off.
1090 // The most likely interlaced input for us is either a camera
1091 // (where it's fine to turn it off) or a laptop (where it _should_
1093 CHECK(deinterlace_effect->set_int("enable_spatial_interlacing_check", 0));
1095 num_inputs = deinterlace_effect->num_inputs();
1096 assert(num_inputs == FRAME_HISTORY_LENGTH);
1101 if (pixel_format == bmusb::PixelFormat_8BitBGRA) {
1102 for (unsigned i = 0; i < num_inputs; ++i) {
1103 // We upload our textures ourselves, and Movit swaps
1104 // R and B in the shader if we specify BGRA, so lie and say RGBA.
1105 rgba_inputs.push_back(new sRGBSwitchingFlatInput(inout_format, FORMAT_RGBA_POSTMULTIPLIED_ALPHA, GL_UNSIGNED_BYTE, global_flags.width, global_flags.height));
1106 chain->add_input(rgba_inputs.back());
1110 vector<Effect *> reverse_inputs(rgba_inputs.rbegin(), rgba_inputs.rend());
1111 chain->add_effect(deinterlace_effect, reverse_inputs);
1114 assert(pixel_format == bmusb::PixelFormat_8BitYCbCr ||
1115 pixel_format == bmusb::PixelFormat_10BitYCbCr ||
1116 pixel_format == bmusb::PixelFormat_8BitYCbCrPlanar);
1118 // Most of these settings will be overridden later if using PixelFormat_8BitYCbCrPlanar.
1119 input_ycbcr_format.chroma_subsampling_x = (pixel_format == bmusb::PixelFormat_10BitYCbCr) ? 1 : 2;
1120 input_ycbcr_format.chroma_subsampling_y = 1;
1121 input_ycbcr_format.num_levels = (pixel_format == bmusb::PixelFormat_10BitYCbCr) ? 1024 : 256;
1122 input_ycbcr_format.cb_x_position = 0.0;
1123 input_ycbcr_format.cr_x_position = 0.0;
1124 input_ycbcr_format.cb_y_position = 0.5;
1125 input_ycbcr_format.cr_y_position = 0.5;
1126 input_ycbcr_format.luma_coefficients = YCBCR_REC_709; // Will be overridden later even if not planar.
1127 input_ycbcr_format.full_range = false; // Will be overridden later even if not planar.
1129 for (unsigned i = 0; i < num_inputs; ++i) {
1130 // When using 10-bit input, we're converting to interleaved through v210Converter.
1131 YCbCrInputSplitting splitting;
1132 if (pixel_format == bmusb::PixelFormat_10BitYCbCr) {
1133 splitting = YCBCR_INPUT_INTERLEAVED;
1134 } else if (pixel_format == bmusb::PixelFormat_8BitYCbCr) {
1135 splitting = YCBCR_INPUT_SPLIT_Y_AND_CBCR;
1137 splitting = YCBCR_INPUT_PLANAR;
1139 if (override_bounce) {
1140 ycbcr_inputs.push_back(new NonBouncingYCbCrInput(inout_format, input_ycbcr_format, global_flags.width, global_flags.height, splitting));
1142 ycbcr_inputs.push_back(new YCbCrInput(inout_format, input_ycbcr_format, global_flags.width, global_flags.height, splitting));
1144 chain->add_input(ycbcr_inputs.back());
1148 vector<Effect *> reverse_inputs(ycbcr_inputs.rbegin(), ycbcr_inputs.rend());
1149 chain->add_effect(deinterlace_effect, reverse_inputs);
1154 bool LiveInputWrapper::connect_signal(int signal_num)
1156 if (!user_connectable) {
1160 if (global_mixer == nullptr) {
1165 int card_idx = theme->map_signal_to_card(signal_num);
1166 connect_card(card_idx, *theme->input_state);
1170 void LiveInputWrapper::connect_card(int card_idx, const InputState &input_state)
1172 BufferedFrame first_frame = input_state.buffered_frames[card_idx][0];
1173 if (first_frame.frame == nullptr) {
1177 unsigned width, height;
1179 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)first_frame.frame->userdata;
1180 width = userdata->last_width[first_frame.field_number];
1181 height = userdata->last_height[first_frame.field_number];
1182 if (userdata->last_interlaced) {
1187 movit::YCbCrLumaCoefficients ycbcr_coefficients = input_state.ycbcr_coefficients[card_idx];
1188 bool full_range = input_state.full_range[card_idx];
1190 if (input_state.ycbcr_coefficients_auto[card_idx]) {
1193 // The Blackmagic driver docs claim that the device outputs Y'CbCr
1194 // according to Rec. 601, but this seems to indicate the subsampling
1195 // positions only, as they publish Y'CbCr → RGB formulas that are
1196 // different for HD and SD (corresponding to Rec. 709 and 601, respectively),
1197 // and a Lenovo X1 gen 3 I used to test definitely outputs Rec. 709
1198 // (at least up to rounding error). Other devices seem to use Rec. 601
1199 // even on HD resolutions. Nevertheless, Rec. 709 _is_ the right choice
1200 // for HD, so we default to that if the user hasn't set anything.
1201 if (height >= 720) {
1202 ycbcr_coefficients = YCBCR_REC_709;
1204 ycbcr_coefficients = YCBCR_REC_601;
1208 // This is a global, but it doesn't really matter.
1209 input_ycbcr_format.luma_coefficients = ycbcr_coefficients;
1210 input_ycbcr_format.full_range = full_range;
1212 BufferedFrame last_good_frame = first_frame;
1213 for (unsigned i = 0; i < max(ycbcr_inputs.size(), rgba_inputs.size()); ++i) {
1214 BufferedFrame frame = input_state.buffered_frames[card_idx][i];
1215 if (frame.frame == nullptr) {
1216 // Not enough data; reuse last frame (well, field).
1217 // This is suboptimal, but we have nothing better.
1218 frame = last_good_frame;
1220 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
1222 unsigned this_width = userdata->last_width[frame.field_number];
1223 unsigned this_height = userdata->last_height[frame.field_number];
1224 if (this_width != width || this_height != height) {
1225 // Resolution changed; reuse last frame/field.
1226 frame = last_good_frame;
1227 userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
1230 assert(userdata->pixel_format == pixel_format);
1231 switch (pixel_format) {
1232 case bmusb::PixelFormat_8BitYCbCr:
1233 ycbcr_inputs[i]->set_texture_num(0, userdata->tex_y[frame.field_number]);
1234 ycbcr_inputs[i]->set_texture_num(1, userdata->tex_cbcr[frame.field_number]);
1235 ycbcr_inputs[i]->change_ycbcr_format(input_ycbcr_format);
1236 ycbcr_inputs[i]->set_width(width);
1237 ycbcr_inputs[i]->set_height(height);
1239 case bmusb::PixelFormat_8BitYCbCrPlanar:
1240 ycbcr_inputs[i]->set_texture_num(0, userdata->tex_y[frame.field_number]);
1241 ycbcr_inputs[i]->set_texture_num(1, userdata->tex_cb[frame.field_number]);
1242 ycbcr_inputs[i]->set_texture_num(2, userdata->tex_cr[frame.field_number]);
1243 // YCbCrPlanar is used for video streams, where we can have metadata from the mux.
1244 // Prefer that if there's no override. (Overrides are only available when using
1245 // video as SRT cards.)
1246 if (input_state.ycbcr_coefficients_auto[card_idx]) {
1247 ycbcr_inputs[i]->change_ycbcr_format(userdata->ycbcr_format);
1249 ycbcr_inputs[i]->change_ycbcr_format(input_ycbcr_format);
1251 ycbcr_inputs[i]->set_width(width);
1252 ycbcr_inputs[i]->set_height(height);
1254 case bmusb::PixelFormat_10BitYCbCr:
1255 ycbcr_inputs[i]->set_texture_num(0, userdata->tex_444[frame.field_number]);
1256 ycbcr_inputs[i]->change_ycbcr_format(input_ycbcr_format);
1257 ycbcr_inputs[i]->set_width(width);
1258 ycbcr_inputs[i]->set_height(height);
1260 case bmusb::PixelFormat_8BitBGRA:
1261 rgba_inputs[i]->set_texture_num(userdata->tex_rgba[frame.field_number]);
1262 rgba_inputs[i]->set_width(width);
1263 rgba_inputs[i]->set_height(height);
1269 last_good_frame = frame;
1273 BufferedFrame frame = input_state.buffered_frames[card_idx][0];
1274 CHECK(deinterlace_effect->set_int("current_field_position", frame.field_number));
1280 int call_num_channels(lua_State *L)
1282 lua_getglobal(L, "num_channels");
1284 if (lua_pcall(L, 0, 1, 0) != 0) {
1285 fprintf(stderr, "error running function `num_channels': %s\n", lua_tostring(L, -1));
1286 fprintf(stderr, "Try Nageru.set_num_channels(...) at the start of the script instead.\n");
1290 int num_channels = luaL_checknumber(L, 1);
1292 assert(lua_gettop(L) == 0);
1293 return num_channels;
1298 int Nageru_set_channel_name(lua_State *L)
1300 // NOTE: m is already locked.
1301 Theme *theme = get_theme_updata(L);
1302 unsigned channel = luaL_checknumber(L, 1);
1303 const string text = checkstdstring(L, 2);
1304 theme->channel_names[channel] = text;
1309 int Nageru_set_num_channels(lua_State *L)
1311 // NOTE: m is already locked.
1312 Theme *theme = get_theme_updata(L);
1313 if (theme->startup_finished) {
1314 luaL_error(L, "set_num_channels() can only be called at startup.");
1316 theme->num_channels = luaL_checknumber(L, 1);
1321 int Nageru_set_channel_signal(lua_State *L)
1323 // NOTE: m is already locked.
1324 Theme *theme = get_theme_updata(L);
1325 if (theme->startup_finished) {
1326 luaL_error(L, "set_channel_signal() can only be called at startup.");
1328 unsigned channel = luaL_checknumber(L, 1);
1329 int signal = luaL_checknumber(L, 2);
1330 theme->channel_signals[channel] = signal;
1335 int Nageru_set_supports_wb(lua_State *L)
1337 // NOTE: m is already locked.
1338 Theme *theme = get_theme_updata(L);
1339 if (theme->startup_finished) {
1340 luaL_error(L, "set_supports_wb() can only be called at startup.");
1342 unsigned channel = luaL_checknumber(L, 1);
1343 bool supports_wb = checkbool(L, 2);
1344 theme->channel_supports_wb[channel] = supports_wb;
1349 // NOTE: There's a race condition in all of the audio functions; if the mapping
1350 // is changed by the user underway, you might not be manipulating the bus you
1351 // expect. (You should not get crashes, though.) There's not all that much we
1352 // can do about it, short of locking the entire mixer while anything from the
1355 int Nageru_get_num_audio_buses(lua_State *L)
1357 if (global_audio_mixer == nullptr) {
1358 // The audio mixer isn't set up until we know how many FFmpeg inputs we have.
1359 luaL_error(L, "Audio functions can not be called before the theme is done initializing.");
1361 lua_pushinteger(L, global_audio_mixer->num_buses());
1365 int Nageru_get_audio_bus_name(lua_State *L)
1367 if (global_audio_mixer == nullptr) {
1368 // The audio mixer isn't set up until we know how many FFmpeg inputs we have.
1369 luaL_error(L, "Audio functions can not be called before the theme is done initializing.");
1371 int bus_index = luaL_checknumber(L, 1);
1372 InputMapping input_mapping = global_audio_mixer->get_input_mapping();
1373 if (bus_index < 0 || size_t(bus_index) >= input_mapping.buses.size()) {
1374 // Doesn't fix the race, but fixes other out-of-bounds.
1375 print_warning(L, "Theme called get_audio_bus_name() on nonexistent bus %d; returning nil.\n", bus_index);
1378 lua_pushstring(L, input_mapping.buses[bus_index].name.c_str());
1383 int Nageru_get_audio_bus_fader_level_db(lua_State *L)
1385 if (global_audio_mixer == nullptr) {
1386 // The audio mixer isn't set up until we know how many FFmpeg inputs we have.
1387 luaL_error(L, "Audio functions can not be called before the theme is done initializing.");
1390 int bus_index = luaL_checknumber(L, 1);
1391 if (bus_index < 0 || size_t(bus_index) >= global_audio_mixer->num_buses()) {
1392 // Doesn't fix the race, but fixes other out-of-bounds.
1393 print_warning(L, "Theme called get_audio_bus_fader_level_db() on nonexistent bus %d; returning 0.0.\n", bus_index);
1394 lua_pushnumber(L, 0.0);
1396 lua_pushnumber(L, global_audio_mixer->get_fader_volume(bus_index));
1401 int Nageru_set_audio_bus_fader_level_db(lua_State *L)
1403 if (global_audio_mixer == nullptr || global_mainwindow == nullptr) {
1404 // The audio mixer isn't set up until we know how many FFmpeg inputs we have.
1405 luaL_error(L, "Audio functions can not be called before the theme is done initializing.");
1408 int bus_index = luaL_checknumber(L, 1);
1409 if (bus_index < 0 || size_t(bus_index) >= global_audio_mixer->num_buses()) {
1410 // Doesn't fix the race, but fixes other out-of-bounds.
1411 print_warning(L, "Theme called set_audio_bus_fader_level_db() on nonexistent bus %d; ignoring.\n", bus_index);
1414 double level_db = luaL_checknumber(L, 2);
1416 // Go through the UI, so that it gets updated.
1417 global_mainwindow->set_fader_absolute(bus_index, level_db);
1421 int Nageru_get_audio_bus_mute(lua_State *L)
1423 if (global_audio_mixer == nullptr) {
1424 // The audio mixer isn't set up until we know how many FFmpeg inputs we have.
1425 luaL_error(L, "Audio functions can not be called before the theme is done initializing.");
1428 int bus_index = luaL_checknumber(L, 1);
1429 if (bus_index < 0 || size_t(bus_index) >= global_audio_mixer->num_buses()) {
1430 // Doesn't fix the race, but fixes other out-of-bounds.
1431 print_warning(L, "Theme called get_audio_bus_mute() on nonexistent bus %d; returning false.\n", bus_index);
1432 lua_pushboolean(L, false);
1434 lua_pushboolean(L, global_audio_mixer->get_mute(bus_index));
1439 int Nageru_set_audio_bus_mute(lua_State *L)
1441 if (global_audio_mixer == nullptr || global_mainwindow == nullptr) {
1442 // The audio mixer isn't set up until we know how many FFmpeg inputs we have.
1443 luaL_error(L, "Audio functions can not be called before the theme is done initializing.");
1446 int bus_index = luaL_checknumber(L, 1);
1447 if (bus_index < 0 || size_t(bus_index) >= global_audio_mixer->num_buses()) {
1448 // Doesn't fix the race, but fixes other out-of-bounds.
1449 print_warning(L, "Theme called set_audio_bus_mute() on nonexistent bus %d; ignoring.\n", bus_index);
1452 bool mute = checkbool(L, 2);
1454 // Go through the UI, so that it gets updated.
1455 if (mute != global_audio_mixer->get_mute(bus_index)) {
1456 global_mainwindow->toggle_mute(bus_index);
1461 int Nageru_schedule_cut(lua_State *L)
1463 if (global_mixer == nullptr) {
1464 luaL_error(L, "Cuts can not be scheduled before the theme is done initializing.");
1466 global_mixer->schedule_cut();
1470 int Nageru_get_audio_bus_eq_level_db(lua_State *L)
1472 if (global_audio_mixer == nullptr) {
1473 // The audio mixer isn't set up until we know how many FFmpeg inputs we have.
1474 luaL_error(L, "Audio functions can not be called before the theme is done initializing.");
1477 int bus_index = luaL_checknumber(L, 1);
1478 int band = luaL_checknumber(L, 2);
1479 if (bus_index < 0 || size_t(bus_index) >= global_audio_mixer->num_buses()) {
1480 // Doesn't fix the race, but fixes other out-of-bounds.
1481 print_warning(L, "Theme called get_audio_bus_eq_level_db() on nonexistent bus %d; returning 0.0.\n", bus_index);
1482 lua_pushnumber(L, 0.0);
1483 } else if (band != EQ_BAND_BASS && band != EQ_BAND_MID && band != EQ_BAND_TREBLE) {
1484 print_warning(L, "Theme called get_audio_bus_eq_level_db() on nonexistent band; returning 0.0.\n", bus_index);
1485 lua_pushnumber(L, 0.0);
1487 lua_pushnumber(L, global_audio_mixer->get_eq(bus_index, EQBand(band)));
1492 int Nageru_set_audio_bus_eq_level_db(lua_State *L)
1494 if (global_audio_mixer == nullptr || global_mainwindow == nullptr) {
1495 // The audio mixer isn't set up until we know how many FFmpeg inputs we have.
1496 luaL_error(L, "Audio functions can not be called before the theme is done initializing.");
1499 int bus_index = luaL_checknumber(L, 1);
1500 int band = luaL_checknumber(L, 2);
1501 if (bus_index < 0 || size_t(bus_index) >= global_audio_mixer->num_buses()) {
1502 // Doesn't fix the race, but fixes other out-of-bounds.
1503 print_warning(L, "Theme called set_audio_bus_eq_level_db() on nonexistent bus %d; ignoring.\n", bus_index);
1505 } else if (band != EQ_BAND_BASS && band != EQ_BAND_MID && band != EQ_BAND_TREBLE) {
1506 print_warning(L, "Theme called set_audio_bus_eq_level_db() on nonexistent band; returning 0.0.\n", bus_index);
1509 double level_db = luaL_checknumber(L, 3);
1511 // Go through the UI, so that it gets updated.
1512 global_mainwindow->set_eq_absolute(bus_index, EQBand(band), level_db);
1516 Theme::Theme(const string &filename, const vector<string> &search_dirs, ResourcePool *resource_pool)
1517 : resource_pool(resource_pool), signal_to_card_mapping(global_flags.default_stream_mapping)
1520 channel_names[0] = "Live";
1521 channel_names[1] = "Preview";
1523 L = luaL_newstate();
1526 // Search through all directories until we find a file that will load
1527 // (as in, does not return LUA_ERRFILE); then run it. We store load errors
1528 // from all the attempts, and show them once we know we can't find any of them.
1530 vector<string> errors;
1531 bool success = false;
1533 vector<string> real_search_dirs;
1534 if (!filename.empty() && filename[0] == '/') {
1535 real_search_dirs.push_back("");
1537 real_search_dirs = search_dirs;
1542 for (const string &dir : real_search_dirs) {
1546 path = dir + "/" + filename;
1548 int err = luaL_loadfile(L, path.c_str());
1550 // Save the theme for when we're actually going to run it
1551 // (we need to set up the right environment below first,
1552 // and we couldn't do that before, because we didn't know the
1553 // path to put in Nageru.THEME_PATH).
1554 theme_code_ref = luaL_ref(L, LUA_REGISTRYINDEX);
1555 assert(lua_gettop(L) == 0);
1560 errors.push_back(lua_tostring(L, -1));
1562 if (err != LUA_ERRFILE) {
1563 // The file actually loaded, but failed to parse somehow. Abort; don't try the next one.
1569 for (const string &error : errors) {
1570 fprintf(stderr, "%s\n", error.c_str());
1574 assert(lua_gettop(L) == 0);
1576 // Make sure the path exposed to the theme (as Nageru.THEME_PATH;
1577 // can be useful for locating files when talking to CEF) is absolute.
1578 // In a sense, it would be nice if realpath() had a mode not to
1579 // resolve symlinks, but it doesn't, so we only call it if we don't
1580 // already have an absolute path (which may leave ../ elements etc.).
1581 if (path[0] == '/') {
1584 char *absolute_theme_path = realpath(path.c_str(), nullptr);
1585 theme_path = absolute_theme_path;
1586 free(absolute_theme_path);
1589 // Set up the API we provide.
1591 register_class("Scene", Scene_funcs);
1592 register_class("Block", Block_funcs);
1593 register_class("EffectBlueprint", EffectBlueprint_funcs);
1594 register_class("EffectChain", EffectChain_funcs);
1595 register_class("LiveInputWrapper", LiveInputWrapper_funcs);
1596 register_class("ImageInput", ImageInput_funcs);
1597 register_class("VideoInput", VideoInput_funcs);
1598 register_class("HTMLInput", HTMLInput_funcs);
1599 register_class("IdentityEffect", IdentityEffect_funcs, IDENTITY_EFFECT);
1600 register_class("WhiteBalanceEffect", WhiteBalanceEffect_funcs, WHITE_BALANCE_EFFECT);
1601 register_class("ResampleEffect", ResampleEffect_funcs, RESAMPLE_EFFECT);
1602 register_class("PaddingEffect", PaddingEffect_funcs, PADDING_EFFECT);
1603 register_class("IntegralPaddingEffect", IntegralPaddingEffect_funcs, INTEGRAL_PADDING_EFFECT);
1604 register_class("OverlayEffect", OverlayEffect_funcs, OVERLAY_EFFECT);
1605 register_class("ResizeEffect", ResizeEffect_funcs, RESIZE_EFFECT);
1606 register_class("MultiplyEffect", MultiplyEffect_funcs, MULTIPLY_EFFECT);
1607 register_class("MixEffect", MixEffect_funcs, MIX_EFFECT);
1608 register_class("BlurEffect", BlurEffect_funcs, BLUR_EFFECT);
1609 register_class("UnsharpMaskEffect", UnsharpMaskEffect_funcs, UNSHARP_MASK_EFFECT);
1610 register_class("LiftGammaGainEffect", LiftGammaGainEffect_funcs, LIFT_GAMMA_GAIN_EFFECT);
1611 register_class("InputStateInfo", InputStateInfo_funcs);
1612 register_class("ThemeMenu", ThemeMenu_funcs);
1614 // Now actually run the theme to get everything set up.
1615 lua_rawgeti(L, LUA_REGISTRYINDEX, theme_code_ref);
1616 luaL_unref(L, LUA_REGISTRYINDEX, theme_code_ref);
1617 if (lua_pcall(L, 0, 0, 0)) {
1618 fprintf(stderr, "Error when running %s: %s\n", path.c_str(), lua_tostring(L, -1));
1621 assert(lua_gettop(L) == 0);
1623 if (num_channels == -1) {
1624 // Ask it for the number of channels.
1625 num_channels = call_num_channels(L);
1627 startup_finished = true;
1636 void Theme::register_globals()
1638 // Set Nageru.VIDEO_FORMAT_BGRA = bmusb::PixelFormat_8BitBGRA, etc.
1639 const vector<pair<string, int>> num_constants = {
1640 { "VIDEO_FORMAT_BGRA", bmusb::PixelFormat_8BitBGRA },
1641 { "VIDEO_FORMAT_YCBCR", bmusb::PixelFormat_8BitYCbCrPlanar },
1642 { "CHECKABLE", MenuEntry::CHECKABLE },
1643 { "CHECKED", MenuEntry::CHECKED },
1644 { "EQ_BAND_BASS", EQ_BAND_BASS },
1645 { "EQ_BAND_MID", EQ_BAND_MID },
1646 { "EQ_BAND_TREBLE", EQ_BAND_TREBLE },
1648 const vector<pair<string, string>> str_constants = {
1649 { "THEME_PATH", theme_path },
1652 lua_newtable(L); // t = {}
1654 for (const pair<string, int> &constant : num_constants) {
1655 lua_pushstring(L, constant.first.c_str());
1656 lua_pushinteger(L, constant.second);
1657 lua_settable(L, 1); // t[key] = value
1659 for (const pair<string, string> &constant : str_constants) {
1660 lua_pushstring(L, constant.first.c_str());
1661 lua_pushstring(L, constant.second.c_str());
1662 lua_settable(L, 1); // t[key] = value
1665 const luaL_Reg Nageru_funcs[] = {
1666 // Channel information.
1667 { "set_channel_name", Nageru_set_channel_name },
1668 { "set_num_channels", Nageru_set_num_channels },
1669 { "set_channel_signal", Nageru_set_channel_signal },
1670 { "set_supports_wb", Nageru_set_supports_wb },
1673 { "get_num_audio_buses", Nageru_get_num_audio_buses },
1674 { "get_audio_bus_name", Nageru_get_audio_bus_name },
1675 { "get_audio_bus_fader_level_db", Nageru_get_audio_bus_fader_level_db },
1676 { "set_audio_bus_fader_level_db", Nageru_set_audio_bus_fader_level_db },
1677 { "get_audio_bus_eq_level_db", Nageru_get_audio_bus_eq_level_db },
1678 { "set_audio_bus_eq_level_db", Nageru_set_audio_bus_eq_level_db },
1679 { "get_audio_bus_mute", Nageru_get_audio_bus_mute },
1680 { "set_audio_bus_mute", Nageru_set_audio_bus_mute },
1683 { "schedule_cut", Nageru_schedule_cut },
1685 { nullptr, nullptr }
1687 lua_pushlightuserdata(L, this);
1688 luaL_setfuncs(L, Nageru_funcs, 1); // for (name,f in funcs) { mt[name] = f, with upvalue {theme} }
1690 lua_setglobal(L, "Nageru"); // Nageru = t
1691 assert(lua_gettop(L) == 0);
1694 void Theme::register_class(const char *class_name, const luaL_Reg *funcs, EffectType effect_type)
1696 assert(lua_gettop(L) == 0);
1697 luaL_newmetatable(L, class_name); // mt = {}
1698 lua_pushlightuserdata(L, this);
1699 luaL_setfuncs(L, funcs, 1); // for (name,f in funcs) { mt[name] = f, with upvalue {theme} }
1700 lua_pushvalue(L, -1);
1701 lua_setfield(L, -2, "__index"); // mt.__index = mt
1702 if (effect_type != NO_EFFECT_TYPE) {
1703 lua_pushnumber(L, effect_type);
1704 lua_setfield(L, -2, "__effect_type_id"); // mt.__effect_type_id = effect_type
1706 lua_setglobal(L, class_name); // ClassName = mt
1707 assert(lua_gettop(L) == 0);
1710 Theme::Chain Theme::get_chain_from_effect_chain(EffectChain *effect_chain, unsigned num, const InputState &input_state)
1712 if (!lua_isfunction(L, -1)) {
1713 fprintf(stderr, "Argument #-1 should be a function\n");
1716 lua_pushvalue(L, -1);
1717 shared_ptr<LuaRefWithDeleter> funcref(new LuaRefWithDeleter(&m, L, luaL_ref(L, LUA_REGISTRYINDEX)));
1721 chain.chain = effect_chain;
1722 chain.setup_chain = [this, funcref, input_state, effect_chain]{
1723 lock_guard<mutex> lock(m);
1725 assert(this->input_state == nullptr);
1726 this->input_state = &input_state;
1728 // Set up state, including connecting signals.
1729 lua_rawgeti(L, LUA_REGISTRYINDEX, funcref->get());
1730 if (lua_pcall(L, 0, 0, 0) != 0) {
1731 fprintf(stderr, "error running chain setup callback: %s\n", lua_tostring(L, -1));
1734 assert(lua_gettop(L) == 0);
1736 // The theme can't (or at least shouldn't!) call connect_signal() on
1737 // each FFmpeg or CEF input, so we'll do it here.
1738 if (video_signal_connections.count(effect_chain)) {
1739 for (const VideoSignalConnection &conn : video_signal_connections[effect_chain]) {
1740 conn.wrapper->connect_card(conn.source->get_card_index(), input_state);
1744 if (html_signal_connections.count(effect_chain)) {
1745 for (const CEFSignalConnection &conn : html_signal_connections[effect_chain]) {
1746 conn.wrapper->connect_card(conn.source->get_card_index(), input_state);
1751 this->input_state = nullptr;
1756 Theme::Chain Theme::get_chain(unsigned num, float t, unsigned width, unsigned height, const InputState &input_state)
1758 const char *func_name = "get_scene"; // For error reporting.
1761 lock_guard<mutex> lock(m);
1762 assert(lua_gettop(L) == 0);
1763 lua_getglobal(L, "get_scene"); /* function to be called */
1764 if (lua_isnil(L, -1)) {
1765 // Try the pre-1.9.0 name for compatibility.
1767 lua_getglobal(L, "get_chain");
1768 func_name = "get_chain";
1770 lua_pushnumber(L, num);
1771 lua_pushnumber(L, t);
1772 lua_pushnumber(L, width);
1773 lua_pushnumber(L, height);
1774 wrap_lua_object<InputStateInfo>(L, "InputStateInfo", input_state);
1776 if (lua_pcall(L, 5, LUA_MULTRET, 0) != 0) {
1777 fprintf(stderr, "error running function “%s”: %s\n", func_name, lua_tostring(L, -1));
1781 if (luaL_testudata(L, -1, "Scene") != nullptr) {
1782 if (lua_gettop(L) != 1) {
1783 luaL_error(L, "%s() for chain number %d returned an Scene, but also other items", func_name);
1785 Scene *auto_effect_chain = (Scene *)luaL_testudata(L, -1, "Scene");
1786 auto chain_and_setup = auto_effect_chain->get_chain(this, L, num, input_state);
1787 chain.chain = chain_and_setup.first;
1788 chain.setup_chain = move(chain_and_setup.second);
1789 } else if (luaL_testudata(L, -2, "EffectChain") != nullptr) {
1790 // Old-style (pre-Nageru 1.9.0) return of a single chain and prepare function.
1791 if (lua_gettop(L) != 2) {
1792 luaL_error(L, "%s() for chain number %d returned an EffectChain, but needs to also return a prepare function (or use Scene)", func_name);
1794 EffectChain *effect_chain = (EffectChain *)luaL_testudata(L, -2, "EffectChain");
1795 chain = get_chain_from_effect_chain(effect_chain, num, input_state);
1797 luaL_error(L, "%s() for chain number %d did not return an EffectChain or Scene\n", func_name, num);
1799 assert(lua_gettop(L) == 0);
1801 // TODO: Can we do better, e.g. by running setup_chain() and seeing what it references?
1802 // Actually, setup_chain does maybe hold all the references we need now anyway?
1803 chain.input_frames.reserve(MAX_VIDEO_CARDS * FRAME_HISTORY_LENGTH);
1804 for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) {
1805 for (unsigned frame_num = 0; frame_num < FRAME_HISTORY_LENGTH; ++frame_num) {
1806 chain.input_frames.push_back(input_state.buffered_frames[card_index][frame_num].frame);
1813 string Theme::get_channel_name(unsigned channel)
1815 lock_guard<mutex> lock(m);
1817 // We never ask the legacy channel_name() about live and preview.
1818 // The defaults are set in our constructor.
1819 if (channel == 0 || channel == 1) {
1820 return channel_names[channel];
1823 lua_getglobal(L, "channel_name");
1824 if (lua_isnil(L, -1)) {
1826 if (channel_names.count(channel)) {
1827 return channel_names[channel];
1829 return "(no title)";
1833 lua_pushnumber(L, channel);
1834 if (lua_pcall(L, 1, 1, 0) != 0) {
1835 fprintf(stderr, "error running function `channel_name': %s\n", lua_tostring(L, -1));
1838 const char *ret = lua_tostring(L, -1);
1839 if (ret == nullptr) {
1840 fprintf(stderr, "function `channel_name' returned nil for channel %d\n", channel);
1841 fprintf(stderr, "Try Nageru.set_channel_name(channel, name) at the start of the script instead.\n");
1845 string retstr = ret;
1847 assert(lua_gettop(L) == 0);
1851 int Theme::map_channel_to_signal(unsigned channel)
1853 lock_guard<mutex> lock(m);
1854 lua_getglobal(L, "channel_signal");
1855 if (lua_isnil(L, -1)) {
1857 if (channel_signals.count(channel)) {
1858 return channel_signals[channel];
1864 lua_pushnumber(L, channel);
1865 if (lua_pcall(L, 1, 1, 0) != 0) {
1866 fprintf(stderr, "error running function `channel_signal': %s\n", lua_tostring(L, -1));
1867 fprintf(stderr, "Try Nageru.set_channel_signal(channel, signal) at the start of the script instead.\n");
1871 int ret = luaL_checknumber(L, 1);
1873 assert(lua_gettop(L) == 0);
1877 std::string Theme::get_channel_color(unsigned channel)
1879 lock_guard<mutex> lock(m);
1880 lua_getglobal(L, "channel_color");
1881 lua_pushnumber(L, channel);
1882 if (lua_pcall(L, 1, 1, 0) != 0) {
1883 fprintf(stderr, "error running function `channel_color': %s\n", lua_tostring(L, -1));
1887 const char *ret = lua_tostring(L, -1);
1888 if (ret == nullptr) {
1889 fprintf(stderr, "function `channel_color' returned nil for channel %d\n", channel);
1893 string retstr = ret;
1895 assert(lua_gettop(L) == 0);
1899 bool Theme::get_supports_set_wb(unsigned channel)
1901 lock_guard<mutex> lock(m);
1902 lua_getglobal(L, "supports_set_wb");
1903 if (lua_isnil(L, -1)) {
1905 if (channel_supports_wb.count(channel)) {
1906 return channel_supports_wb[channel];
1912 lua_pushnumber(L, channel);
1913 if (lua_pcall(L, 1, 1, 0) != 0) {
1914 fprintf(stderr, "error running function `supports_set_wb': %s\n", lua_tostring(L, -1));
1915 fprintf(stderr, "Try Nageru.set_supports_wb(channel, bool) at the start of the script instead.\n");
1919 bool ret = checkbool(L, -1);
1921 assert(lua_gettop(L) == 0);
1925 void Theme::set_wb(unsigned channel, float r, float g, float b)
1927 int signal = map_channel_to_signal(channel);
1929 lock_guard<mutex> lock(m);
1931 int card_idx = map_signal_to_card(signal);
1932 white_balance_for_card[card_idx] = RGBTriplet{ r, g, b };
1935 call_lua_wb_callback(channel, r, g, b);
1938 void Theme::set_wb_for_card(int card_idx, float r, float g, float b)
1940 lock_guard<mutex> lock(m);
1941 white_balance_for_card[card_idx] = RGBTriplet{ r, g, b };
1943 for (const auto &channel_and_signal : channel_signals) {
1944 if (map_signal_to_card(channel_and_signal.second) == card_idx) {
1945 call_lua_wb_callback(channel_and_signal.first, r, g, b);
1950 void Theme::call_lua_wb_callback(unsigned channel, float r, float g, float b)
1952 lua_getglobal(L, "set_wb");
1953 if (lua_isnil(L, -1)) {
1954 // The function doesn't exist, to just ignore. We've stored the white balance,
1955 // and most likely, it will be picked up by auto white balance instead.
1959 lua_pushnumber(L, channel);
1960 lua_pushnumber(L, r);
1961 lua_pushnumber(L, g);
1962 lua_pushnumber(L, b);
1963 if (lua_pcall(L, 4, 0, 0) != 0) {
1964 fprintf(stderr, "error running function `set_wb': %s\n", lua_tostring(L, -1));
1968 assert(lua_gettop(L) == 0);
1971 RGBTriplet Theme::get_white_balance_for_card(int card_idx)
1973 if (white_balance_for_card.count(card_idx)) {
1974 return white_balance_for_card[card_idx];
1976 return RGBTriplet{ 1.0, 1.0, 1.0 };
1980 vector<string> Theme::get_transition_names(float t)
1982 lock_guard<mutex> lock(m);
1983 lua_getglobal(L, "get_transitions");
1984 lua_pushnumber(L, t);
1985 if (lua_pcall(L, 1, 1, 0) != 0) {
1986 fprintf(stderr, "error running function `get_transitions': %s\n", lua_tostring(L, -1));
1992 while (lua_next(L, -2) != 0) {
1993 ret.push_back(lua_tostring(L, -1));
1997 assert(lua_gettop(L) == 0);
2001 int Theme::map_signal_to_card(int signal_num)
2003 // Negative numbers map to raw signals.
2004 if (signal_num < 0) {
2005 return -1 - signal_num;
2008 lock_guard<mutex> lock(map_m);
2009 if (signal_to_card_mapping.count(signal_num)) {
2010 return signal_to_card_mapping[signal_num];
2014 if (global_flags.output_card != -1) {
2015 // Try to exclude the output card from the default card_index.
2016 card_index = signal_num % (global_flags.max_num_cards - 1);
2017 if (card_index >= global_flags.output_card) {
2020 if (signal_num >= int(global_flags.max_num_cards - 1)) {
2021 print_warning(L, "Theme asked for input %d, but we only have %u input card(s) (card %d is busy with output).\n",
2022 signal_num, global_flags.max_num_cards - 1, global_flags.output_card);
2023 fprintf(stderr, "Mapping to card %d instead.\n", card_index);
2026 card_index = signal_num % global_flags.max_num_cards;
2027 if (signal_num >= int(global_flags.max_num_cards)) {
2028 print_warning(L, "Theme asked for input %d, but we only have %u card(s).\n", signal_num, global_flags.max_num_cards);
2029 fprintf(stderr, "Mapping to card %d instead.\n", card_index);
2032 global_mixer->force_card_active(card_index);
2033 signal_to_card_mapping[signal_num] = card_index;
2037 void Theme::set_signal_mapping(int signal_num, int card_idx)
2039 lock_guard<mutex> lock(map_m);
2040 assert(card_idx < MAX_VIDEO_CARDS);
2041 signal_to_card_mapping[signal_num] = card_idx;
2044 void Theme::transition_clicked(int transition_num, float t)
2046 lock_guard<mutex> lock(m);
2047 lua_getglobal(L, "transition_clicked");
2048 lua_pushnumber(L, transition_num);
2049 lua_pushnumber(L, t);
2051 if (lua_pcall(L, 2, 0, 0) != 0) {
2052 fprintf(stderr, "error running function `transition_clicked': %s\n", lua_tostring(L, -1));
2055 assert(lua_gettop(L) == 0);
2058 void Theme::channel_clicked(int preview_num)
2060 lock_guard<mutex> lock(m);
2061 lua_getglobal(L, "channel_clicked");
2062 lua_pushnumber(L, preview_num);
2064 if (lua_pcall(L, 1, 0, 0) != 0) {
2065 fprintf(stderr, "error running function `channel_clicked': %s\n", lua_tostring(L, -1));
2068 assert(lua_gettop(L) == 0);
2072 void destroy(T &ref)
2077 Theme::MenuEntry::~MenuEntry()
2082 luaL_unref(entry.L, LUA_REGISTRYINDEX, entry.lua_ref);
2088 vector<unique_ptr<Theme::MenuEntry>> create_recursive_theme_menu(lua_State *L);
2090 unique_ptr<Theme::MenuEntry> create_theme_menu_entry(lua_State *L, int index)
2092 unique_ptr<Theme::MenuEntry> entry;
2094 lua_rawgeti(L, index, 1);
2095 const string text = checkstdstring(L, -1);
2099 if (lua_objlen(L, index) > 2) {
2100 lua_rawgeti(L, index, 3);
2101 flags = luaL_checknumber(L, -1);
2105 lua_rawgeti(L, index, 2);
2106 if (lua_istable(L, -1)) {
2107 vector<unique_ptr<Theme::MenuEntry>> submenu = create_recursive_theme_menu(L);
2108 entry.reset(new Theme::MenuEntry{ text, move(submenu) });
2111 luaL_checktype(L, -1, LUA_TFUNCTION);
2112 int ref = luaL_ref(L, LUA_REGISTRYINDEX);
2113 entry.reset(new Theme::MenuEntry{ text, L, ref, flags });
2118 vector<unique_ptr<Theme::MenuEntry>> create_recursive_theme_menu(lua_State *L)
2120 vector<unique_ptr<Theme::MenuEntry>> menu;
2121 size_t num_elements = lua_objlen(L, -1);
2122 for (size_t i = 1; i <= num_elements; ++i) {
2123 lua_rawgeti(L, -1, i);
2124 menu.emplace_back(create_theme_menu_entry(L, -1));
2132 int Theme::set_theme_menu(lua_State *L)
2136 vector<unique_ptr<MenuEntry>> root_menu;
2137 int num_elements = lua_gettop(L);
2138 for (int i = 1; i <= num_elements; ++i) {
2139 root_menu.emplace_back(create_theme_menu_entry(L, i));
2141 theme_menu.reset(new MenuEntry("", move(root_menu)));
2143 lua_pop(L, num_elements);
2144 assert(lua_gettop(L) == 0);
2146 if (theme_menu_callback != nullptr) {
2147 theme_menu_callback();
2153 void Theme::theme_menu_entry_clicked(int lua_ref)
2155 lock_guard<mutex> lock(m);
2156 lua_rawgeti(L, LUA_REGISTRYINDEX, lua_ref);
2157 if (lua_pcall(L, 0, 0, 0) != 0) {
2158 fprintf(stderr, "error running menu callback: %s\n", lua_tostring(L, -1));
2163 string Theme::format_status_line(const string &disk_space_left_text, double file_length_seconds)
2165 lock_guard<mutex> lock(m);
2166 lua_getglobal(L, "format_status_line");
2167 if (lua_isnil(L, -1)) {
2169 return disk_space_left_text;
2172 lua_pushstring(L, disk_space_left_text.c_str());
2173 lua_pushnumber(L, file_length_seconds);
2174 if (lua_pcall(L, 2, 1, 0) != 0) {
2175 fprintf(stderr, "error running function format_status_line(): %s\n", lua_tostring(L, -1));
2178 string text = checkstdstring(L, 1);
2180 assert(lua_gettop(L) == 0);
2184 void Theme::remove_card(unsigned card_index)
2186 lock_guard<mutex> lock(map_m);
2187 for (auto it = signal_to_card_mapping.begin(); it != signal_to_card_mapping.end(); ) {
2188 if (it->second == int(card_index)) {
2189 it = signal_to_card_mapping.erase(it);