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"
57 #include "shared/context.h"
66 using namespace movit;
68 extern Mixer *global_mixer;
70 constexpr unsigned Theme::MenuEntry::CHECKABLE;
71 constexpr unsigned Theme::MenuEntry::CHECKED;
73 Theme *get_theme_updata(lua_State* L)
75 luaL_checktype(L, lua_upvalueindex(1), LUA_TLIGHTUSERDATA);
76 return (Theme *)lua_touserdata(L, lua_upvalueindex(1));
79 void print_warning(lua_State* L, const char *format, ...)
84 vsnprintf(buf, sizeof(buf), format, ap);
88 lua_getstack(L, 1, &ar);
89 lua_getinfo(L, "nSl", &ar);
90 fprintf(stderr, "WARNING: %s:%d: %s", ar.source, ar.currentline, buf);
93 int ThemeMenu_set(lua_State *L)
95 Theme *theme = get_theme_updata(L);
96 return theme->set_theme_menu(L);
99 InputStateInfo::InputStateInfo(const InputState &input_state)
101 for (unsigned signal_num = 0; signal_num < MAX_VIDEO_CARDS; ++signal_num) {
102 BufferedFrame frame = input_state.buffered_frames[signal_num][0];
103 if (frame.frame == nullptr) {
104 last_width[signal_num] = last_height[signal_num] = 0;
105 last_interlaced[signal_num] = false;
106 last_has_signal[signal_num] = false;
107 last_is_connected[signal_num] = false;
110 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
111 last_width[signal_num] = userdata->last_width[frame.field_number];
112 last_height[signal_num] = userdata->last_height[frame.field_number];
113 last_interlaced[signal_num] = userdata->last_interlaced;
114 last_has_signal[signal_num] = userdata->last_has_signal;
115 last_is_connected[signal_num] = userdata->last_is_connected;
116 last_frame_rate_nom[signal_num] = userdata->last_frame_rate_nom;
117 last_frame_rate_den[signal_num] = userdata->last_frame_rate_den;
118 last_pixel_format[signal_num] = userdata->pixel_format;
119 has_last_subtitle[signal_num] = userdata->has_last_subtitle;
120 last_subtitle[signal_num] = userdata->last_subtitle;
124 // An effect that does nothing.
125 class IdentityEffect : public Effect {
128 string effect_type_id() const override { return "IdentityEffect"; }
129 string output_fragment_shader() override { return read_file("identity.frag"); }
132 Effect *instantiate_effect(EffectChain *chain, EffectType effect_type)
134 switch (effect_type) {
135 case IDENTITY_EFFECT:
136 return new IdentityEffect;
137 case WHITE_BALANCE_EFFECT:
138 case AUTO_WHITE_BALANCE_EFFECT:
139 return new WhiteBalanceEffect;
140 case RESAMPLE_EFFECT:
141 return new ResampleEffect;
143 return new PaddingEffect;
144 case INTEGRAL_PADDING_EFFECT:
145 return new IntegralPaddingEffect;
147 return new OverlayEffect;
149 return new ResizeEffect;
150 case MULTIPLY_EFFECT:
151 return new MultiplyEffect;
153 return new MixEffect;
154 case LIFT_GAMMA_GAIN_EFFECT:
155 return new LiftGammaGainEffect;
157 return new BlurEffect;
158 case UNSHARP_MASK_EFFECT:
159 return new UnsharpMaskEffect;
161 fprintf(stderr, "Unhandled effect type %d\n", effect_type);
168 Effect *get_effect_from_blueprint(EffectChain *chain, lua_State *L, int idx)
170 EffectBlueprint *blueprint = *(EffectBlueprint **)luaL_checkudata(L, idx, "EffectBlueprint");
171 if (blueprint->effect != nullptr) {
172 luaL_error(L, "An effect can currently only be added to one chain.\n");
175 Effect *effect = instantiate_effect(chain, blueprint->effect_type);
177 // Set the parameters that were deferred earlier.
178 for (const auto &kv : blueprint->int_parameters) {
179 if (!effect->set_int(kv.first, kv.second)) {
180 luaL_error(L, "Effect refused set_int(\"%s\", %d) (invalid key?)", kv.first.c_str(), kv.second);
183 for (const auto &kv : blueprint->float_parameters) {
184 if (!effect->set_float(kv.first, kv.second)) {
185 luaL_error(L, "Effect refused set_float(\"%s\", %f) (invalid key?)", kv.first.c_str(), kv.second);
188 for (const auto &kv : blueprint->vec3_parameters) {
189 if (!effect->set_vec3(kv.first, kv.second.data())) {
190 luaL_error(L, "Effect refused set_vec3(\"%s\", %f, %f, %f) (invalid key?)", kv.first.c_str(),
191 kv.second[0], kv.second[1], kv.second[2]);
194 for (const auto &kv : blueprint->vec4_parameters) {
195 if (!effect->set_vec4(kv.first, kv.second.data())) {
196 luaL_error(L, "Effect refused set_vec4(\"%s\", %f, %f, %f, %f) (invalid key?)", kv.first.c_str(),
197 kv.second[0], kv.second[1], kv.second[2], kv.second[3]);
200 blueprint->effect = effect;
204 InputStateInfo *get_input_state_info(lua_State *L, int idx)
206 if (luaL_testudata(L, idx, "InputStateInfo")) {
207 return (InputStateInfo *)lua_touserdata(L, idx);
209 luaL_error(L, "Error: Index #%d was not InputStateInfo\n", idx);
215 bool checkbool(lua_State* L, int idx)
217 luaL_checktype(L, idx, LUA_TBOOLEAN);
218 return lua_toboolean(L, idx);
221 string checkstdstring(lua_State *L, int index)
224 const char* cstr = lua_tolstring(L, index, &len);
225 return string(cstr, len);
230 int Scene_new(lua_State* L)
232 assert(lua_gettop(L) == 2);
233 Theme *theme = get_theme_updata(L);
234 int aspect_w = luaL_checknumber(L, 1);
235 int aspect_h = luaL_checknumber(L, 2);
237 return wrap_lua_object<Scene>(L, "Scene", theme, aspect_w, aspect_h);
240 int Scene_gc(lua_State* L)
242 assert(lua_gettop(L) == 1);
243 Scene *chain = (Scene *)luaL_checkudata(L, 1, "Scene");
250 void add_outputs_and_finalize(EffectChain *chain, bool is_main_chain)
252 // Add outputs as needed.
253 // NOTE: If you change any details about the output format, you will need to
254 // also update what's given to the muxer (HTTPD::Mux constructor) and
255 // what's put in the H.264 stream (sps_rbsp()).
256 ImageFormat inout_format;
257 inout_format.color_space = COLORSPACE_REC_709;
259 // Output gamma is tricky. We should output Rec. 709 for TV, except that
260 // we expect to run with web players and others that don't really care and
261 // just output with no conversion. So that means we'll need to output sRGB,
262 // even though H.264 has no setting for that (we use “unspecified”).
263 inout_format.gamma_curve = GAMMA_sRGB;
266 YCbCrFormat output_ycbcr_format;
267 // We actually output 4:2:0 and/or 4:2:2 in the end, but chroma subsampling
268 // happens in a pass not run by Movit (see ChromaSubsampler::subsample_chroma()).
269 output_ycbcr_format.chroma_subsampling_x = 1;
270 output_ycbcr_format.chroma_subsampling_y = 1;
272 // This will be overridden if HDMI/SDI output is in force.
273 if (global_flags.ycbcr_rec709_coefficients) {
274 output_ycbcr_format.luma_coefficients = YCBCR_REC_709;
276 output_ycbcr_format.luma_coefficients = YCBCR_REC_601;
279 output_ycbcr_format.full_range = false;
280 output_ycbcr_format.num_levels = 1 << global_flags.bit_depth;
282 GLenum type = global_flags.bit_depth > 8 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_BYTE;
284 chain->add_ycbcr_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED, output_ycbcr_format, YCBCR_OUTPUT_SPLIT_Y_AND_CBCR, type);
286 // If we're using zerocopy video encoding (so the destination
287 // Y texture is owned by VA-API and will be unavailable for
288 // display), add a copy, where we'll only be using the Y component.
289 if (global_flags.use_zerocopy) {
290 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.
292 chain->set_dither_bits(global_flags.bit_depth > 8 ? 16 : 8);
293 chain->set_output_origin(OUTPUT_ORIGIN_TOP_LEFT);
295 chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
303 int EffectChain_new(lua_State* L)
305 assert(lua_gettop(L) == 2);
306 Theme *theme = get_theme_updata(L);
307 int aspect_w = luaL_checknumber(L, 1);
308 int aspect_h = luaL_checknumber(L, 2);
310 return wrap_lua_object<EffectChain>(L, "EffectChain", aspect_w, aspect_h, theme->get_resource_pool());
313 int EffectChain_gc(lua_State* L)
315 assert(lua_gettop(L) == 1);
316 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
317 chain->~EffectChain();
321 int EffectChain_add_live_input(lua_State* L)
323 assert(lua_gettop(L) == 3);
324 Theme *theme = get_theme_updata(L);
325 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
326 bool override_bounce = checkbool(L, 2);
327 bool deinterlace = checkbool(L, 3);
328 bmusb::PixelFormat pixel_format = global_flags.bit_depth > 8 ? bmusb::PixelFormat_10BitYCbCr : bmusb::PixelFormat_8BitYCbCr;
330 // Needs to be nonowned to match add_video_input (see below).
331 return wrap_lua_object_nonowned<LiveInputWrapper>(L, "LiveInputWrapper", theme, chain, pixel_format, override_bounce, deinterlace, /*user_connectable=*/true);
334 int EffectChain_add_video_input(lua_State* L)
336 assert(lua_gettop(L) == 3);
337 Theme *theme = get_theme_updata(L);
338 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
339 FFmpegCapture **capture = (FFmpegCapture **)luaL_checkudata(L, 2, "VideoInput");
340 bool deinterlace = checkbool(L, 3);
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, /*user_connectable=*/false);
350 Theme *theme = get_theme_updata(L);
351 LiveInputWrapper **live_input = (LiveInputWrapper **)lua_touserdata(L, -1);
352 theme->register_video_signal_connection(chain, *live_input, *capture);
358 int EffectChain_add_html_input(lua_State* L)
360 assert(lua_gettop(L) == 2);
361 Theme *theme = get_theme_updata(L);
362 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
363 CEFCapture **capture = (CEFCapture **)luaL_checkudata(L, 2, "HTMLInput");
365 // These need to be nonowned, so that the LiveInputWrapper still exists
366 // and can feed frames to the right EffectChain even if the Lua code
367 // doesn't care about the object anymore. (If we change this, we'd need
368 // to also unregister the signal connection on __gc.)
369 int ret = wrap_lua_object_nonowned<LiveInputWrapper>(
370 L, "LiveInputWrapper", theme, chain, (*capture)->get_current_pixel_format(),
371 /*override_bounce=*/false, /*deinterlace=*/false, /*user_connectable=*/false);
373 Theme *theme = get_theme_updata(L);
374 LiveInputWrapper **live_input = (LiveInputWrapper **)lua_touserdata(L, -1);
375 theme->register_html_signal_connection(chain, *live_input, *capture);
381 int EffectChain_add_effect(lua_State* L)
383 assert(lua_gettop(L) >= 2);
384 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
386 // TODO: Better error reporting.
388 if (luaL_testudata(L, 2, "ImageInput")) {
389 effect = *(ImageInput **)luaL_checkudata(L, 2, "ImageInput");
391 effect = get_effect_from_blueprint(chain, L, 2);
393 if (lua_gettop(L) == 2) {
394 if (effect->num_inputs() == 0) {
395 chain->add_input((Input *)effect);
397 chain->add_effect(effect);
400 vector<Effect *> inputs;
401 for (int idx = 3; idx <= lua_gettop(L); ++idx) {
402 if (luaL_testudata(L, idx, "LiveInputWrapper")) {
403 LiveInputWrapper **input = (LiveInputWrapper **)lua_touserdata(L, idx);
404 inputs.push_back((*input)->get_effect());
405 } else if (luaL_testudata(L, idx, "ImageInput")) {
406 ImageInput *image = *(ImageInput **)luaL_checkudata(L, idx, "ImageInput");
407 inputs.push_back(image);
409 EffectBlueprint *blueprint = *(EffectBlueprint **)luaL_checkudata(L, idx, "EffectBlueprint");
410 assert(blueprint->effect != nullptr); // Parent must be added to the graph.
411 inputs.push_back(blueprint->effect);
414 chain->add_effect(effect, inputs);
417 lua_settop(L, 2); // Return the effect itself.
419 // Make sure Lua doesn't garbage-collect it away.
420 lua_pushvalue(L, -1);
421 luaL_ref(L, LUA_REGISTRYINDEX); // TODO: leak?
426 int EffectChain_finalize(lua_State* L)
428 assert(lua_gettop(L) == 2);
429 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
430 bool is_main_chain = checkbool(L, 2);
431 add_outputs_and_finalize(chain, is_main_chain);
435 int LiveInputWrapper_connect_signal(lua_State* L)
437 assert(lua_gettop(L) == 2);
438 LiveInputWrapper **input = (LiveInputWrapper **)luaL_checkudata(L, 1, "LiveInputWrapper");
439 int signal_num = luaL_checknumber(L, 2);
440 bool success = (*input)->connect_signal(signal_num);
442 print_warning(L, "Calling connect_signal() on a video or HTML input. Ignoring.\n");
447 int ImageInput_new(lua_State* L)
449 assert(lua_gettop(L) == 1);
450 string filename = checkstdstring(L, 1);
451 return wrap_lua_object_nonowned<ImageInput>(L, "ImageInput", filename);
456 // Must be non-namespaced due to friend declaration.
457 int VideoInput_new(lua_State* L)
459 assert(lua_gettop(L) == 2);
460 string filename = checkstdstring(L, 1);
461 int pixel_format = luaL_checknumber(L, 2);
462 if (pixel_format != bmusb::PixelFormat_8BitYCbCrPlanar &&
463 pixel_format != bmusb::PixelFormat_8BitBGRA) {
464 print_warning(L, "Invalid enum %d used for video format, choosing Y'CbCr.\n", pixel_format);
465 pixel_format = bmusb::PixelFormat_8BitYCbCrPlanar;
467 Theme *theme = get_theme_updata(L);
468 int ret = wrap_lua_object_nonowned<FFmpegCapture>(L, "VideoInput", filename, global_flags.width, global_flags.height, create_surface_with_same_format(theme->surface));
470 FFmpegCapture **capture = (FFmpegCapture **)lua_touserdata(L, -1);
471 (*capture)->set_pixel_format(bmusb::PixelFormat(pixel_format));
473 theme->register_video_input(*capture);
480 int VideoInput_rewind(lua_State* L)
482 assert(lua_gettop(L) == 1);
483 FFmpegCapture **video_input = (FFmpegCapture **)luaL_checkudata(L, 1, "VideoInput");
484 (*video_input)->rewind();
488 int VideoInput_disconnect(lua_State* L)
490 assert(lua_gettop(L) == 1);
491 FFmpegCapture **video_input = (FFmpegCapture **)luaL_checkudata(L, 1, "VideoInput");
492 (*video_input)->disconnect();
496 int VideoInput_change_rate(lua_State* L)
498 assert(lua_gettop(L) == 2);
499 FFmpegCapture **video_input = (FFmpegCapture **)luaL_checkudata(L, 1, "VideoInput");
500 double new_rate = luaL_checknumber(L, 2);
501 (*video_input)->change_rate(new_rate);
505 int VideoInput_get_signal_num(lua_State* L)
507 assert(lua_gettop(L) == 1);
508 FFmpegCapture **video_input = (FFmpegCapture **)luaL_checkudata(L, 1, "VideoInput");
509 lua_pushnumber(L, -1 - (*video_input)->get_card_index());
513 int HTMLInput_new(lua_State* L)
516 assert(lua_gettop(L) == 1);
517 string url = checkstdstring(L, 1);
518 int ret = wrap_lua_object_nonowned<CEFCapture>(L, "HTMLInput", url, global_flags.width, global_flags.height);
520 CEFCapture **capture = (CEFCapture **)lua_touserdata(L, -1);
521 Theme *theme = get_theme_updata(L);
522 theme->register_html_input(*capture);
526 fprintf(stderr, "This version of Nageru has been compiled without CEF support.\n");
527 fprintf(stderr, "HTMLInput is not available.\n");
533 int HTMLInput_set_url(lua_State* L)
535 assert(lua_gettop(L) == 2);
536 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
537 string new_url = checkstdstring(L, 2);
538 (*video_input)->set_url(new_url);
542 int HTMLInput_reload(lua_State* L)
544 assert(lua_gettop(L) == 1);
545 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
546 (*video_input)->reload();
550 int HTMLInput_set_max_fps(lua_State* L)
552 assert(lua_gettop(L) == 2);
553 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
554 int max_fps = lrint(luaL_checknumber(L, 2));
555 (*video_input)->set_max_fps(max_fps);
559 int HTMLInput_execute_javascript_async(lua_State* L)
561 assert(lua_gettop(L) == 2);
562 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
563 string js = checkstdstring(L, 2);
564 (*video_input)->execute_javascript_async(js);
568 int HTMLInput_resize(lua_State* L)
570 assert(lua_gettop(L) == 3);
571 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
572 unsigned width = lrint(luaL_checknumber(L, 2));
573 unsigned height = lrint(luaL_checknumber(L, 3));
574 (*video_input)->resize(width, height);
578 int HTMLInput_get_signal_num(lua_State* L)
580 assert(lua_gettop(L) == 1);
581 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
582 lua_pushnumber(L, -1 - (*video_input)->get_card_index());
587 int IdentityEffect_new(lua_State* L)
589 assert(lua_gettop(L) == 0);
590 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", IDENTITY_EFFECT);
593 int WhiteBalanceEffect_new(lua_State* L)
595 assert(lua_gettop(L) == 0);
596 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", WHITE_BALANCE_EFFECT);
599 int ResampleEffect_new(lua_State* L)
601 assert(lua_gettop(L) == 0);
602 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", RESAMPLE_EFFECT);
605 int PaddingEffect_new(lua_State* L)
607 assert(lua_gettop(L) == 0);
608 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", PADDING_EFFECT);
611 int IntegralPaddingEffect_new(lua_State* L)
613 assert(lua_gettop(L) == 0);
614 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", INTEGRAL_PADDING_EFFECT);
617 int OverlayEffect_new(lua_State* L)
619 assert(lua_gettop(L) == 0);
620 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", OVERLAY_EFFECT);
623 int ResizeEffect_new(lua_State* L)
625 assert(lua_gettop(L) == 0);
626 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", RESIZE_EFFECT);
629 int MultiplyEffect_new(lua_State* L)
631 assert(lua_gettop(L) == 0);
632 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", MULTIPLY_EFFECT);
635 int MixEffect_new(lua_State* L)
637 assert(lua_gettop(L) == 0);
638 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", MIX_EFFECT);
641 int LiftGammaGainEffect_new(lua_State* L)
643 assert(lua_gettop(L) == 0);
644 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", LIFT_GAMMA_GAIN_EFFECT);
647 int BlurEffect_new(lua_State* L)
649 assert(lua_gettop(L) == 0);
650 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", BLUR_EFFECT);
653 int UnsharpMaskEffect_new(lua_State* L)
655 assert(lua_gettop(L) == 0);
656 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", UNSHARP_MASK_EFFECT);
659 int InputStateInfo_get_width(lua_State* L)
661 assert(lua_gettop(L) == 2);
662 InputStateInfo *input_state_info = get_input_state_info(L, 1);
664 Theme *theme = get_theme_updata(L);
665 int card_idx = theme->map_signal_to_card(luaL_checknumber(L, 2));
666 lua_pushnumber(L, input_state_info->last_width[card_idx]);
670 int InputStateInfo_get_height(lua_State* L)
672 assert(lua_gettop(L) == 2);
673 InputStateInfo *input_state_info = get_input_state_info(L, 1);
674 Theme *theme = get_theme_updata(L);
675 int card_idx = theme->map_signal_to_card(luaL_checknumber(L, 2));
676 lua_pushnumber(L, input_state_info->last_height[card_idx]);
680 int InputStateInfo_get_frame_height(lua_State* L)
682 assert(lua_gettop(L) == 2);
683 InputStateInfo *input_state_info = get_input_state_info(L, 1);
684 Theme *theme = get_theme_updata(L);
685 int card_idx = theme->map_signal_to_card(luaL_checknumber(L, 2));
686 unsigned height = input_state_info->last_height[card_idx];
687 if (input_state_info->last_interlaced[card_idx]) {
690 lua_pushnumber(L, height);
694 int InputStateInfo_get_interlaced(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 card_idx = theme->map_signal_to_card(luaL_checknumber(L, 2));
700 lua_pushboolean(L, input_state_info->last_interlaced[card_idx]);
704 int InputStateInfo_get_has_signal(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 card_idx = theme->map_signal_to_card(luaL_checknumber(L, 2));
710 lua_pushboolean(L, input_state_info->last_has_signal[card_idx]);
714 int InputStateInfo_get_is_connected(lua_State* L)
716 assert(lua_gettop(L) == 2);
717 InputStateInfo *input_state_info = get_input_state_info(L, 1);
718 Theme *theme = get_theme_updata(L);
719 int card_idx = theme->map_signal_to_card(luaL_checknumber(L, 2));
720 lua_pushboolean(L, input_state_info->last_is_connected[card_idx]);
724 int InputStateInfo_get_frame_rate_nom(lua_State* L)
726 assert(lua_gettop(L) == 2);
727 InputStateInfo *input_state_info = get_input_state_info(L, 1);
728 Theme *theme = get_theme_updata(L);
729 int card_idx = theme->map_signal_to_card(luaL_checknumber(L, 2));
730 lua_pushnumber(L, input_state_info->last_frame_rate_nom[card_idx]);
734 int InputStateInfo_get_frame_rate_den(lua_State* L)
736 assert(lua_gettop(L) == 2);
737 InputStateInfo *input_state_info = get_input_state_info(L, 1);
738 Theme *theme = get_theme_updata(L);
739 int card_idx = theme->map_signal_to_card(luaL_checknumber(L, 2));
740 lua_pushnumber(L, input_state_info->last_frame_rate_den[card_idx]);
744 int InputStateInfo_get_last_subtitle(lua_State* L)
746 assert(lua_gettop(L) == 2);
747 InputStateInfo *input_state_info = get_input_state_info(L, 1);
748 Theme *theme = get_theme_updata(L);
749 int card_idx = theme->map_signal_to_card(luaL_checknumber(L, 2));
750 if (!input_state_info->has_last_subtitle[card_idx]) {
753 lua_pushstring(L, input_state_info->last_subtitle[card_idx].c_str());
760 // Helper function to write e.g. “60” or “59.94”.
761 string format_frame_rate(int nom, int den)
764 if (nom % den == 0) {
765 snprintf(buf, sizeof(buf), "%d", nom / den);
767 snprintf(buf, sizeof(buf), "%.2f", double(nom) / den);
772 // Helper function to write e.g. “720p60”.
773 string get_human_readable_resolution(const InputStateInfo *input_state_info, int signal_num)
776 if (input_state_info->last_interlaced[signal_num]) {
777 snprintf(buf, sizeof(buf), "%di", input_state_info->last_height[signal_num] * 2);
779 // Show field rate instead of frame rate; really for cosmetics only
780 // (and actually contrary to EBU recommendations, although in line
781 // with typical user expectations).
782 return buf + format_frame_rate(input_state_info->last_frame_rate_nom[signal_num] * 2,
783 input_state_info->last_frame_rate_den[signal_num]);
785 snprintf(buf, sizeof(buf), "%dp", input_state_info->last_height[signal_num]);
786 return buf + format_frame_rate(input_state_info->last_frame_rate_nom[signal_num],
787 input_state_info->last_frame_rate_den[signal_num]);
793 int InputStateInfo_get_human_readable_resolution(lua_State* L)
795 assert(lua_gettop(L) == 2);
796 InputStateInfo *input_state_info = get_input_state_info(L, 1);
797 Theme *theme = get_theme_updata(L);
798 int card_idx = theme->map_signal_to_card(luaL_checknumber(L, 2));
801 if (!input_state_info->last_is_connected[card_idx]) {
802 str = "disconnected";
803 } else if (input_state_info->last_height[card_idx] <= 0) {
805 } else if (!input_state_info->last_has_signal[card_idx]) {
806 if (input_state_info->last_height[card_idx] == 525) {
807 // Special mode for the USB3 cards.
810 str = get_human_readable_resolution(input_state_info, card_idx) + ", no signal";
813 str = get_human_readable_resolution(input_state_info, card_idx);
816 lua_pushstring(L, str.c_str());
821 int EffectBlueprint_set_int(lua_State *L)
823 assert(lua_gettop(L) == 3);
824 EffectBlueprint *blueprint = *(EffectBlueprint **)luaL_checkudata(L, 1, "EffectBlueprint");
825 string key = checkstdstring(L, 2);
826 float value = luaL_checknumber(L, 3);
827 if (blueprint->effect != nullptr) {
828 if (!blueprint->effect->set_int(key, value)) {
829 luaL_error(L, "Effect refused set_int(\"%s\", %d) (invalid key?)", key.c_str(), int(value));
832 // TODO: check validity already here, if possible?
833 blueprint->int_parameters[key] = value;
838 int EffectBlueprint_set_float(lua_State *L)
840 assert(lua_gettop(L) == 3);
841 EffectBlueprint *blueprint = *(EffectBlueprint **)luaL_checkudata(L, 1, "EffectBlueprint");
842 string key = checkstdstring(L, 2);
843 float value = luaL_checknumber(L, 3);
844 if (blueprint->effect != nullptr) {
845 if (!blueprint->effect->set_float(key, value)) {
846 luaL_error(L, "Effect refused set_float(\"%s\", %d) (invalid key?)", key.c_str(), int(value));
849 // TODO: check validity already here, if possible?
850 blueprint->float_parameters[key] = value;
855 int EffectBlueprint_set_vec3(lua_State *L)
857 assert(lua_gettop(L) == 5);
858 EffectBlueprint *blueprint = *(EffectBlueprint **)luaL_checkudata(L, 1, "EffectBlueprint");
859 string key = checkstdstring(L, 2);
861 v[0] = luaL_checknumber(L, 3);
862 v[1] = luaL_checknumber(L, 4);
863 v[2] = luaL_checknumber(L, 5);
865 if (blueprint->effect != nullptr) {
866 if (!blueprint->effect->set_vec3(key, v.data())) {
867 luaL_error(L, "Effect refused set_vec3(\"%s\", %f, %f, %f) (invalid key?)", key.c_str(),
871 // TODO: check validity already here, if possible?
872 blueprint->vec3_parameters[key] = v;
878 int EffectBlueprint_set_vec4(lua_State *L)
880 assert(lua_gettop(L) == 6);
881 EffectBlueprint *blueprint = *(EffectBlueprint **)luaL_checkudata(L, 1, "EffectBlueprint");
882 string key = checkstdstring(L, 2);
884 v[0] = luaL_checknumber(L, 3);
885 v[1] = luaL_checknumber(L, 4);
886 v[2] = luaL_checknumber(L, 5);
887 v[3] = luaL_checknumber(L, 6);
888 if (blueprint->effect != nullptr) {
889 if (!blueprint->effect->set_vec4(key, v.data())) {
890 luaL_error(L, "Effect refused set_vec4(\"%s\", %f, %f, %f, %f) (invalid key?)", key.c_str(),
891 v[0], v[1], v[2], v[3]);
894 // TODO: check validity already here, if possible?
895 blueprint->vec4_parameters[key] = v;
900 const luaL_Reg Scene_funcs[] = {
901 { "new", Scene_new },
902 { "__gc", Scene_gc },
903 { "add_input", Scene::add_input },
904 { "add_white_balance", Scene::add_white_balance },
905 { "add_effect", Scene::add_effect },
906 { "add_optional_effect", Scene::add_optional_effect },
907 { "finalize", Scene::finalize },
911 const luaL_Reg Block_funcs[] = {
912 { "display", Block_display },
913 { "choose", Block_choose },
914 { "enable", Block_enable },
915 { "enable_if", Block_enable_if },
916 { "disable", Block_disable },
917 { "always_disable_if_disabled", Block_always_disable_if_disabled },
918 { "promise_to_disable_if_enabled", Block_promise_to_disable_if_enabled },
919 { "set_int", Block_set_int },
920 { "set_float", Block_set_float },
921 { "set_vec3", Block_set_vec3 },
922 { "set_vec4", Block_set_vec4 },
926 const luaL_Reg EffectBlueprint_funcs[] = {
927 // NOTE: No new() function; that's for the individual effects.
928 { "set_int", EffectBlueprint_set_int },
929 { "set_float", EffectBlueprint_set_float },
930 { "set_vec3", EffectBlueprint_set_vec3 },
931 { "set_vec4", EffectBlueprint_set_vec4 },
935 const luaL_Reg EffectChain_funcs[] = {
936 { "new", EffectChain_new },
937 { "__gc", EffectChain_gc },
938 { "add_live_input", EffectChain_add_live_input },
939 { "add_video_input", EffectChain_add_video_input },
941 { "add_html_input", EffectChain_add_html_input },
943 { "add_effect", EffectChain_add_effect },
944 { "finalize", EffectChain_finalize },
948 const luaL_Reg LiveInputWrapper_funcs[] = {
949 { "connect_signal", LiveInputWrapper_connect_signal },
953 const luaL_Reg ImageInput_funcs[] = {
954 { "new", ImageInput_new },
958 const luaL_Reg VideoInput_funcs[] = {
959 { "new", VideoInput_new },
960 { "rewind", VideoInput_rewind },
961 { "disconnect", VideoInput_disconnect },
962 { "change_rate", VideoInput_change_rate },
963 { "get_signal_num", VideoInput_get_signal_num },
967 const luaL_Reg HTMLInput_funcs[] = {
968 { "new", HTMLInput_new },
970 { "set_url", HTMLInput_set_url },
971 { "reload", HTMLInput_reload },
972 { "set_max_fps", HTMLInput_set_max_fps },
973 { "execute_javascript_async", HTMLInput_execute_javascript_async },
974 { "resize", HTMLInput_resize },
975 { "get_signal_num", HTMLInput_get_signal_num },
981 // All of these are solely for new(); the returned metatable will be that of
982 // EffectBlueprint, and Effect (returned from add_effect()) is its own type.
984 const luaL_Reg IdentityEffect_funcs[] = {
985 { "new", IdentityEffect_new },
989 const luaL_Reg WhiteBalanceEffect_funcs[] = {
990 { "new", WhiteBalanceEffect_new },
994 const luaL_Reg ResampleEffect_funcs[] = {
995 { "new", ResampleEffect_new },
999 const luaL_Reg PaddingEffect_funcs[] = {
1000 { "new", PaddingEffect_new },
1004 const luaL_Reg IntegralPaddingEffect_funcs[] = {
1005 { "new", IntegralPaddingEffect_new },
1009 const luaL_Reg OverlayEffect_funcs[] = {
1010 { "new", OverlayEffect_new },
1014 const luaL_Reg ResizeEffect_funcs[] = {
1015 { "new", ResizeEffect_new },
1019 const luaL_Reg MultiplyEffect_funcs[] = {
1020 { "new", MultiplyEffect_new },
1024 const luaL_Reg MixEffect_funcs[] = {
1025 { "new", MixEffect_new },
1029 const luaL_Reg LiftGammaGainEffect_funcs[] = {
1030 { "new", LiftGammaGainEffect_new },
1034 const luaL_Reg BlurEffect_funcs[] = {
1035 { "new", BlurEffect_new },
1039 const luaL_Reg UnsharpMaskEffect_funcs[] = {
1040 { "new", UnsharpMaskEffect_new },
1046 const luaL_Reg InputStateInfo_funcs[] = {
1047 { "get_width", InputStateInfo_get_width },
1048 { "get_height", InputStateInfo_get_height },
1049 { "get_frame_width", InputStateInfo_get_width }, // Same as get_width().
1050 { "get_frame_height", InputStateInfo_get_frame_height },
1051 { "get_interlaced", InputStateInfo_get_interlaced },
1052 { "get_has_signal", InputStateInfo_get_has_signal },
1053 { "get_is_connected", InputStateInfo_get_is_connected },
1054 { "get_frame_rate_nom", InputStateInfo_get_frame_rate_nom },
1055 { "get_frame_rate_den", InputStateInfo_get_frame_rate_den },
1056 { "get_last_subtitle", InputStateInfo_get_last_subtitle },
1057 { "get_human_readable_resolution", InputStateInfo_get_human_readable_resolution },
1061 const luaL_Reg ThemeMenu_funcs[] = {
1062 { "set", ThemeMenu_set },
1068 LiveInputWrapper::LiveInputWrapper(
1071 bmusb::PixelFormat pixel_format,
1072 bool override_bounce,
1074 bool user_connectable)
1076 pixel_format(pixel_format),
1077 deinterlace(deinterlace),
1078 user_connectable(user_connectable)
1080 ImageFormat inout_format;
1081 inout_format.color_space = COLORSPACE_sRGB;
1083 // Gamma curve depends on the input signal, and we don't really get any
1084 // indications. A camera would be expected to do Rec. 709, but
1085 // I haven't checked if any do in practice. However, computers _do_ output
1086 // in sRGB gamma (ie., they don't convert from sRGB to Rec. 709), and
1087 // I wouldn't really be surprised if most non-professional cameras do, too.
1088 // So we pick sRGB as the least evil here.
1089 inout_format.gamma_curve = GAMMA_sRGB;
1091 unsigned num_inputs;
1093 deinterlace_effect = new movit::DeinterlaceEffect();
1095 // As per the comments in deinterlace_effect.h, we turn this off.
1096 // The most likely interlaced input for us is either a camera
1097 // (where it's fine to turn it off) or a laptop (where it _should_
1099 CHECK(deinterlace_effect->set_int("enable_spatial_interlacing_check", 0));
1101 num_inputs = deinterlace_effect->num_inputs();
1102 assert(num_inputs == FRAME_HISTORY_LENGTH);
1107 if (pixel_format == bmusb::PixelFormat_8BitBGRA) {
1108 for (unsigned i = 0; i < num_inputs; ++i) {
1109 // We upload our textures ourselves, and Movit swaps
1110 // R and B in the shader if we specify BGRA, so lie and say RGBA.
1111 rgba_inputs.push_back(new sRGBSwitchingFlatInput(inout_format, FORMAT_RGBA_POSTMULTIPLIED_ALPHA, GL_UNSIGNED_BYTE, global_flags.width, global_flags.height));
1112 chain->add_input(rgba_inputs.back());
1116 vector<Effect *> reverse_inputs(rgba_inputs.rbegin(), rgba_inputs.rend());
1117 chain->add_effect(deinterlace_effect, reverse_inputs);
1120 assert(pixel_format == bmusb::PixelFormat_8BitYCbCr ||
1121 pixel_format == bmusb::PixelFormat_10BitYCbCr ||
1122 pixel_format == bmusb::PixelFormat_8BitYCbCrPlanar);
1124 // Most of these settings will be overridden later if using PixelFormat_8BitYCbCrPlanar.
1125 input_ycbcr_format.chroma_subsampling_x = (pixel_format == bmusb::PixelFormat_10BitYCbCr) ? 1 : 2;
1126 input_ycbcr_format.chroma_subsampling_y = 1;
1127 input_ycbcr_format.num_levels = (pixel_format == bmusb::PixelFormat_10BitYCbCr) ? 1024 : 256;
1128 input_ycbcr_format.cb_x_position = 0.0;
1129 input_ycbcr_format.cr_x_position = 0.0;
1130 input_ycbcr_format.cb_y_position = 0.5;
1131 input_ycbcr_format.cr_y_position = 0.5;
1132 input_ycbcr_format.luma_coefficients = YCBCR_REC_709; // Will be overridden later even if not planar.
1133 input_ycbcr_format.full_range = false; // Will be overridden later even if not planar.
1135 for (unsigned i = 0; i < num_inputs; ++i) {
1136 // When using 10-bit input, we're converting to interleaved through v210Converter.
1137 YCbCrInputSplitting splitting;
1138 if (pixel_format == bmusb::PixelFormat_10BitYCbCr) {
1139 splitting = YCBCR_INPUT_INTERLEAVED;
1140 } else if (pixel_format == bmusb::PixelFormat_8BitYCbCr) {
1141 splitting = YCBCR_INPUT_SPLIT_Y_AND_CBCR;
1143 splitting = YCBCR_INPUT_PLANAR;
1145 if (override_bounce) {
1146 ycbcr_inputs.push_back(new NonBouncingYCbCrInput(inout_format, input_ycbcr_format, global_flags.width, global_flags.height, splitting));
1148 ycbcr_inputs.push_back(new YCbCrInput(inout_format, input_ycbcr_format, global_flags.width, global_flags.height, splitting));
1150 chain->add_input(ycbcr_inputs.back());
1154 vector<Effect *> reverse_inputs(ycbcr_inputs.rbegin(), ycbcr_inputs.rend());
1155 chain->add_effect(deinterlace_effect, reverse_inputs);
1160 bool LiveInputWrapper::connect_signal(int signal_num)
1162 if (!user_connectable) {
1166 if (global_mixer == nullptr) {
1171 int card_idx = theme->map_signal_to_card(signal_num);
1172 connect_card(card_idx, *theme->input_state);
1176 void LiveInputWrapper::connect_card(int card_idx, const InputState &input_state)
1178 BufferedFrame first_frame = input_state.buffered_frames[card_idx][0];
1179 if (first_frame.frame == nullptr) {
1183 unsigned width, height;
1185 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)first_frame.frame->userdata;
1186 width = userdata->last_width[first_frame.field_number];
1187 height = userdata->last_height[first_frame.field_number];
1188 if (userdata->last_interlaced) {
1193 movit::YCbCrLumaCoefficients ycbcr_coefficients = input_state.ycbcr_coefficients[card_idx];
1194 bool full_range = input_state.full_range[card_idx];
1196 if (input_state.ycbcr_coefficients_auto[card_idx]) {
1199 // The Blackmagic driver docs claim that the device outputs Y'CbCr
1200 // according to Rec. 601, but this seems to indicate the subsampling
1201 // positions only, as they publish Y'CbCr → RGB formulas that are
1202 // different for HD and SD (corresponding to Rec. 709 and 601, respectively),
1203 // and a Lenovo X1 gen 3 I used to test definitely outputs Rec. 709
1204 // (at least up to rounding error). Other devices seem to use Rec. 601
1205 // even on HD resolutions. Nevertheless, Rec. 709 _is_ the right choice
1206 // for HD, so we default to that if the user hasn't set anything.
1207 if (height >= 720) {
1208 ycbcr_coefficients = YCBCR_REC_709;
1210 ycbcr_coefficients = YCBCR_REC_601;
1214 // This is a global, but it doesn't really matter.
1215 input_ycbcr_format.luma_coefficients = ycbcr_coefficients;
1216 input_ycbcr_format.full_range = full_range;
1218 BufferedFrame last_good_frame = first_frame;
1219 for (unsigned i = 0; i < max(ycbcr_inputs.size(), rgba_inputs.size()); ++i) {
1220 BufferedFrame frame = input_state.buffered_frames[card_idx][i];
1221 if (frame.frame == nullptr) {
1222 // Not enough data; reuse last frame (well, field).
1223 // This is suboptimal, but we have nothing better.
1224 frame = last_good_frame;
1226 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
1228 unsigned this_width = userdata->last_width[frame.field_number];
1229 unsigned this_height = userdata->last_height[frame.field_number];
1230 if (this_width != width || this_height != height) {
1231 // Resolution changed; reuse last frame/field.
1232 frame = last_good_frame;
1233 userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
1236 assert(userdata->pixel_format == pixel_format);
1237 switch (pixel_format) {
1238 case bmusb::PixelFormat_8BitYCbCr:
1239 ycbcr_inputs[i]->set_texture_num(0, userdata->tex_y[frame.field_number]);
1240 ycbcr_inputs[i]->set_texture_num(1, userdata->tex_cbcr[frame.field_number]);
1241 ycbcr_inputs[i]->change_ycbcr_format(input_ycbcr_format);
1242 ycbcr_inputs[i]->set_width(width);
1243 ycbcr_inputs[i]->set_height(height);
1245 case bmusb::PixelFormat_8BitYCbCrPlanar:
1246 ycbcr_inputs[i]->set_texture_num(0, userdata->tex_y[frame.field_number]);
1247 ycbcr_inputs[i]->set_texture_num(1, userdata->tex_cb[frame.field_number]);
1248 ycbcr_inputs[i]->set_texture_num(2, userdata->tex_cr[frame.field_number]);
1249 // YCbCrPlanar is used for video streams, where we can have metadata from the mux.
1250 // Prefer that if there's no override. (Overrides are only available when using
1251 // video as SRT cards.)
1252 if (input_state.ycbcr_coefficients_auto[card_idx]) {
1253 ycbcr_inputs[i]->change_ycbcr_format(userdata->ycbcr_format);
1255 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_10BitYCbCr:
1261 ycbcr_inputs[i]->set_texture_num(0, userdata->tex_444[frame.field_number]);
1262 ycbcr_inputs[i]->change_ycbcr_format(input_ycbcr_format);
1263 ycbcr_inputs[i]->set_width(width);
1264 ycbcr_inputs[i]->set_height(height);
1266 case bmusb::PixelFormat_8BitBGRA:
1267 rgba_inputs[i]->set_texture_num(userdata->tex_rgba[frame.field_number]);
1268 rgba_inputs[i]->set_width(width);
1269 rgba_inputs[i]->set_height(height);
1275 last_good_frame = frame;
1279 BufferedFrame frame = input_state.buffered_frames[card_idx][0];
1280 CHECK(deinterlace_effect->set_int("current_field_position", frame.field_number));
1286 int call_num_channels(lua_State *L)
1288 lua_getglobal(L, "num_channels");
1290 if (lua_pcall(L, 0, 1, 0) != 0) {
1291 fprintf(stderr, "error running function `num_channels': %s\n", lua_tostring(L, -1));
1292 fprintf(stderr, "Try Nageru.set_num_channels(...) at the start of the script instead.\n");
1296 int num_channels = luaL_checknumber(L, 1);
1298 assert(lua_gettop(L) == 0);
1299 return num_channels;
1304 int Nageru_set_channel_name(lua_State *L)
1306 // NOTE: m is already locked.
1307 Theme *theme = get_theme_updata(L);
1308 unsigned channel = luaL_checknumber(L, 1);
1309 const string text = checkstdstring(L, 2);
1310 theme->channel_names[channel] = text;
1315 int Nageru_set_num_channels(lua_State *L)
1317 // NOTE: m is already locked.
1318 Theme *theme = get_theme_updata(L);
1319 if (theme->startup_finished) {
1320 luaL_error(L, "set_num_channels() can only be called at startup.");
1322 theme->num_channels = luaL_checknumber(L, 1);
1327 int Nageru_set_channel_signal(lua_State *L)
1329 // NOTE: m is already locked.
1330 Theme *theme = get_theme_updata(L);
1331 if (theme->startup_finished) {
1332 luaL_error(L, "set_channel_signal() can only be called at startup.");
1334 unsigned channel = luaL_checknumber(L, 1);
1335 int signal = luaL_checknumber(L, 2);
1336 theme->channel_signals[channel] = signal;
1341 int Nageru_set_supports_wb(lua_State *L)
1343 // NOTE: m is already locked.
1344 Theme *theme = get_theme_updata(L);
1345 if (theme->startup_finished) {
1346 luaL_error(L, "set_supports_wb() can only be called at startup.");
1348 unsigned channel = luaL_checknumber(L, 1);
1349 bool supports_wb = checkbool(L, 2);
1350 theme->channel_supports_wb[channel] = supports_wb;
1355 // NOTE: There's a race condition in all of the audio functions; if the mapping
1356 // is changed by the user underway, you might not be manipulating the bus you
1357 // expect. (You should not get crashes, though.) There's not all that much we
1358 // can do about it, short of locking the entire mixer while anything from the
1361 int Nageru_get_num_audio_buses(lua_State *L)
1363 if (global_audio_mixer == nullptr) {
1364 // The audio mixer isn't set up until we know how many FFmpeg inputs we have.
1365 luaL_error(L, "Audio functions can not be called before the theme is done initializing.");
1367 lua_pushinteger(L, global_audio_mixer->num_buses());
1371 int Nageru_get_audio_bus_name(lua_State *L)
1373 if (global_audio_mixer == nullptr) {
1374 // The audio mixer isn't set up until we know how many FFmpeg inputs we have.
1375 luaL_error(L, "Audio functions can not be called before the theme is done initializing.");
1377 int bus_index = luaL_checknumber(L, 1);
1378 InputMapping input_mapping = global_audio_mixer->get_input_mapping();
1379 if (bus_index < 0 || size_t(bus_index) >= input_mapping.buses.size()) {
1380 // Doesn't fix the race, but fixes other out-of-bounds.
1381 print_warning(L, "Theme called get_audio_bus_name() on nonexistent bus %d; returning nil.\n", bus_index);
1384 lua_pushstring(L, input_mapping.buses[bus_index].name.c_str());
1389 int Nageru_get_audio_bus_fader_level_db(lua_State *L)
1391 if (global_audio_mixer == nullptr) {
1392 // The audio mixer isn't set up until we know how many FFmpeg inputs we have.
1393 luaL_error(L, "Audio functions can not be called before the theme is done initializing.");
1396 int bus_index = luaL_checknumber(L, 1);
1397 if (bus_index < 0 || size_t(bus_index) >= global_audio_mixer->num_buses()) {
1398 // Doesn't fix the race, but fixes other out-of-bounds.
1399 print_warning(L, "Theme called get_audio_bus_fader_level_db() on nonexistent bus %d; returning 0.0.\n", bus_index);
1400 lua_pushnumber(L, 0.0);
1402 lua_pushnumber(L, global_audio_mixer->get_fader_volume(bus_index));
1407 int Nageru_set_audio_bus_fader_level_db(lua_State *L)
1409 if (global_audio_mixer == nullptr || global_mainwindow == nullptr) {
1410 // The audio mixer isn't set up until we know how many FFmpeg inputs we have.
1411 luaL_error(L, "Audio functions can not be called before the theme is done initializing.");
1414 int bus_index = luaL_checknumber(L, 1);
1415 if (bus_index < 0 || size_t(bus_index) >= global_audio_mixer->num_buses()) {
1416 // Doesn't fix the race, but fixes other out-of-bounds.
1417 print_warning(L, "Theme called set_audio_bus_fader_level_db() on nonexistent bus %d; ignoring.\n", bus_index);
1420 double level_db = luaL_checknumber(L, 2);
1422 // Go through the UI, so that it gets updated.
1423 global_mainwindow->set_fader_absolute(bus_index, level_db);
1427 int Nageru_get_audio_bus_mute(lua_State *L)
1429 if (global_audio_mixer == nullptr) {
1430 // The audio mixer isn't set up until we know how many FFmpeg inputs we have.
1431 luaL_error(L, "Audio functions can not be called before the theme is done initializing.");
1434 int bus_index = luaL_checknumber(L, 1);
1435 if (bus_index < 0 || size_t(bus_index) >= global_audio_mixer->num_buses()) {
1436 // Doesn't fix the race, but fixes other out-of-bounds.
1437 print_warning(L, "Theme called get_audio_bus_mute() on nonexistent bus %d; returning false.\n", bus_index);
1438 lua_pushboolean(L, false);
1440 lua_pushboolean(L, global_audio_mixer->get_mute(bus_index));
1445 int Nageru_set_audio_bus_mute(lua_State *L)
1447 if (global_audio_mixer == nullptr || global_mainwindow == nullptr) {
1448 // The audio mixer isn't set up until we know how many FFmpeg inputs we have.
1449 luaL_error(L, "Audio functions can not be called before the theme is done initializing.");
1452 int bus_index = luaL_checknumber(L, 1);
1453 if (bus_index < 0 || size_t(bus_index) >= global_audio_mixer->num_buses()) {
1454 // Doesn't fix the race, but fixes other out-of-bounds.
1455 print_warning(L, "Theme called set_audio_bus_mute() on nonexistent bus %d; ignoring.\n", bus_index);
1458 bool mute = checkbool(L, 2);
1460 // Go through the UI, so that it gets updated.
1461 if (mute != global_audio_mixer->get_mute(bus_index)) {
1462 global_mainwindow->toggle_mute(bus_index);
1467 int Nageru_schedule_cut(lua_State *L)
1469 if (global_mixer == nullptr) {
1470 luaL_error(L, "Cuts can not be scheduled before the theme is done initializing.");
1472 global_mixer->schedule_cut();
1476 int Nageru_get_audio_bus_eq_level_db(lua_State *L)
1478 if (global_audio_mixer == nullptr) {
1479 // The audio mixer isn't set up until we know how many FFmpeg inputs we have.
1480 luaL_error(L, "Audio functions can not be called before the theme is done initializing.");
1483 int bus_index = luaL_checknumber(L, 1);
1484 int band = luaL_checknumber(L, 2);
1485 if (bus_index < 0 || size_t(bus_index) >= global_audio_mixer->num_buses()) {
1486 // Doesn't fix the race, but fixes other out-of-bounds.
1487 print_warning(L, "Theme called get_audio_bus_eq_level_db() on nonexistent bus %d; returning 0.0.\n", bus_index);
1488 lua_pushnumber(L, 0.0);
1489 } else if (band != EQ_BAND_BASS && band != EQ_BAND_MID && band != EQ_BAND_TREBLE) {
1490 print_warning(L, "Theme called get_audio_bus_eq_level_db() on nonexistent band; returning 0.0.\n", bus_index);
1491 lua_pushnumber(L, 0.0);
1493 lua_pushnumber(L, global_audio_mixer->get_eq(bus_index, EQBand(band)));
1498 int Nageru_set_audio_bus_eq_level_db(lua_State *L)
1500 if (global_audio_mixer == nullptr || global_mainwindow == nullptr) {
1501 // The audio mixer isn't set up until we know how many FFmpeg inputs we have.
1502 luaL_error(L, "Audio functions can not be called before the theme is done initializing.");
1505 int bus_index = luaL_checknumber(L, 1);
1506 int band = luaL_checknumber(L, 2);
1507 if (bus_index < 0 || size_t(bus_index) >= global_audio_mixer->num_buses()) {
1508 // Doesn't fix the race, but fixes other out-of-bounds.
1509 print_warning(L, "Theme called set_audio_bus_eq_level_db() on nonexistent bus %d; ignoring.\n", bus_index);
1511 } else if (band != EQ_BAND_BASS && band != EQ_BAND_MID && band != EQ_BAND_TREBLE) {
1512 print_warning(L, "Theme called set_audio_bus_eq_level_db() on nonexistent band; returning 0.0.\n", bus_index);
1515 double level_db = luaL_checknumber(L, 3);
1517 // Go through the UI, so that it gets updated.
1518 global_mainwindow->set_eq_absolute(bus_index, EQBand(band), level_db);
1522 Theme::Theme(const string &filename, const vector<string> &search_dirs, ResourcePool *resource_pool, QSurface *surface)
1523 : resource_pool(resource_pool), signal_to_card_mapping(global_flags.default_stream_mapping), surface(surface)
1526 channel_names[0] = "Live";
1527 channel_names[1] = "Preview";
1529 L = luaL_newstate();
1532 // Search through all directories until we find a file that will load
1533 // (as in, does not return LUA_ERRFILE); then run it. We store load errors
1534 // from all the attempts, and show them once we know we can't find any of them.
1536 vector<string> errors;
1537 bool success = false;
1539 vector<string> real_search_dirs;
1540 if (!filename.empty() && filename[0] == '/') {
1541 real_search_dirs.push_back("");
1543 real_search_dirs = search_dirs;
1548 for (const string &dir : real_search_dirs) {
1552 path = dir + "/" + filename;
1554 int err = luaL_loadfile(L, path.c_str());
1556 // Save the theme for when we're actually going to run it
1557 // (we need to set up the right environment below first,
1558 // and we couldn't do that before, because we didn't know the
1559 // path to put in Nageru.THEME_PATH).
1560 theme_code_ref = luaL_ref(L, LUA_REGISTRYINDEX);
1561 assert(lua_gettop(L) == 0);
1566 errors.push_back(lua_tostring(L, -1));
1568 if (err != LUA_ERRFILE) {
1569 // The file actually loaded, but failed to parse somehow. Abort; don't try the next one.
1575 for (const string &error : errors) {
1576 fprintf(stderr, "%s\n", error.c_str());
1580 assert(lua_gettop(L) == 0);
1582 // Make sure the path exposed to the theme (as Nageru.THEME_PATH;
1583 // can be useful for locating files when talking to CEF) is absolute.
1584 // In a sense, it would be nice if realpath() had a mode not to
1585 // resolve symlinks, but it doesn't, so we only call it if we don't
1586 // already have an absolute path (which may leave ../ elements etc.).
1587 if (path[0] == '/') {
1590 char *absolute_theme_path = realpath(path.c_str(), nullptr);
1591 theme_path = absolute_theme_path;
1592 free(absolute_theme_path);
1595 // Set up the API we provide.
1597 register_class("Scene", Scene_funcs);
1598 register_class("Block", Block_funcs);
1599 register_class("EffectBlueprint", EffectBlueprint_funcs);
1600 register_class("EffectChain", EffectChain_funcs);
1601 register_class("LiveInputWrapper", LiveInputWrapper_funcs);
1602 register_class("ImageInput", ImageInput_funcs);
1603 register_class("VideoInput", VideoInput_funcs);
1604 register_class("HTMLInput", HTMLInput_funcs);
1605 register_class("IdentityEffect", IdentityEffect_funcs, IDENTITY_EFFECT);
1606 register_class("WhiteBalanceEffect", WhiteBalanceEffect_funcs, WHITE_BALANCE_EFFECT);
1607 register_class("ResampleEffect", ResampleEffect_funcs, RESAMPLE_EFFECT);
1608 register_class("PaddingEffect", PaddingEffect_funcs, PADDING_EFFECT);
1609 register_class("IntegralPaddingEffect", IntegralPaddingEffect_funcs, INTEGRAL_PADDING_EFFECT);
1610 register_class("OverlayEffect", OverlayEffect_funcs, OVERLAY_EFFECT);
1611 register_class("ResizeEffect", ResizeEffect_funcs, RESIZE_EFFECT);
1612 register_class("MultiplyEffect", MultiplyEffect_funcs, MULTIPLY_EFFECT);
1613 register_class("MixEffect", MixEffect_funcs, MIX_EFFECT);
1614 register_class("BlurEffect", BlurEffect_funcs, BLUR_EFFECT);
1615 register_class("UnsharpMaskEffect", UnsharpMaskEffect_funcs, UNSHARP_MASK_EFFECT);
1616 register_class("LiftGammaGainEffect", LiftGammaGainEffect_funcs, LIFT_GAMMA_GAIN_EFFECT);
1617 register_class("InputStateInfo", InputStateInfo_funcs);
1618 register_class("ThemeMenu", ThemeMenu_funcs);
1620 // Now actually run the theme to get everything set up.
1621 lua_rawgeti(L, LUA_REGISTRYINDEX, theme_code_ref);
1622 luaL_unref(L, LUA_REGISTRYINDEX, theme_code_ref);
1623 if (lua_pcall(L, 0, 0, 0)) {
1624 fprintf(stderr, "Error when running %s: %s\n", path.c_str(), lua_tostring(L, -1));
1627 assert(lua_gettop(L) == 0);
1629 if (num_channels == -1) {
1630 // Ask it for the number of channels.
1631 num_channels = call_num_channels(L);
1633 startup_finished = true;
1640 // Leak the surface.
1643 void Theme::register_globals()
1645 // Set Nageru.VIDEO_FORMAT_BGRA = bmusb::PixelFormat_8BitBGRA, etc.
1646 const vector<pair<string, int>> num_constants = {
1647 { "VIDEO_FORMAT_BGRA", bmusb::PixelFormat_8BitBGRA },
1648 { "VIDEO_FORMAT_YCBCR", bmusb::PixelFormat_8BitYCbCrPlanar },
1649 { "CHECKABLE", MenuEntry::CHECKABLE },
1650 { "CHECKED", MenuEntry::CHECKED },
1651 { "EQ_BAND_BASS", EQ_BAND_BASS },
1652 { "EQ_BAND_MID", EQ_BAND_MID },
1653 { "EQ_BAND_TREBLE", EQ_BAND_TREBLE },
1655 const vector<pair<string, string>> str_constants = {
1656 { "THEME_PATH", theme_path },
1659 lua_newtable(L); // t = {}
1661 for (const pair<string, int> &constant : num_constants) {
1662 lua_pushstring(L, constant.first.c_str());
1663 lua_pushinteger(L, constant.second);
1664 lua_settable(L, 1); // t[key] = value
1666 for (const pair<string, string> &constant : str_constants) {
1667 lua_pushstring(L, constant.first.c_str());
1668 lua_pushstring(L, constant.second.c_str());
1669 lua_settable(L, 1); // t[key] = value
1672 const luaL_Reg Nageru_funcs[] = {
1673 // Channel information.
1674 { "set_channel_name", Nageru_set_channel_name },
1675 { "set_num_channels", Nageru_set_num_channels },
1676 { "set_channel_signal", Nageru_set_channel_signal },
1677 { "set_supports_wb", Nageru_set_supports_wb },
1680 { "get_num_audio_buses", Nageru_get_num_audio_buses },
1681 { "get_audio_bus_name", Nageru_get_audio_bus_name },
1682 { "get_audio_bus_fader_level_db", Nageru_get_audio_bus_fader_level_db },
1683 { "set_audio_bus_fader_level_db", Nageru_set_audio_bus_fader_level_db },
1684 { "get_audio_bus_eq_level_db", Nageru_get_audio_bus_eq_level_db },
1685 { "set_audio_bus_eq_level_db", Nageru_set_audio_bus_eq_level_db },
1686 { "get_audio_bus_mute", Nageru_get_audio_bus_mute },
1687 { "set_audio_bus_mute", Nageru_set_audio_bus_mute },
1690 { "schedule_cut", Nageru_schedule_cut },
1692 { nullptr, nullptr }
1694 lua_pushlightuserdata(L, this);
1695 luaL_setfuncs(L, Nageru_funcs, 1); // for (name,f in funcs) { mt[name] = f, with upvalue {theme} }
1697 lua_setglobal(L, "Nageru"); // Nageru = t
1698 assert(lua_gettop(L) == 0);
1701 void Theme::register_class(const char *class_name, const luaL_Reg *funcs, EffectType effect_type)
1703 assert(lua_gettop(L) == 0);
1704 luaL_newmetatable(L, class_name); // mt = {}
1705 lua_pushlightuserdata(L, this);
1706 luaL_setfuncs(L, funcs, 1); // for (name,f in funcs) { mt[name] = f, with upvalue {theme} }
1707 lua_pushvalue(L, -1);
1708 lua_setfield(L, -2, "__index"); // mt.__index = mt
1709 if (effect_type != NO_EFFECT_TYPE) {
1710 lua_pushnumber(L, effect_type);
1711 lua_setfield(L, -2, "__effect_type_id"); // mt.__effect_type_id = effect_type
1713 lua_setglobal(L, class_name); // ClassName = mt
1714 assert(lua_gettop(L) == 0);
1717 Theme::Chain Theme::get_chain_from_effect_chain(EffectChain *effect_chain, unsigned num, const InputState &input_state)
1719 if (!lua_isfunction(L, -1)) {
1720 fprintf(stderr, "Argument #-1 should be a function\n");
1723 lua_pushvalue(L, -1);
1724 shared_ptr<LuaRefWithDeleter> funcref(new LuaRefWithDeleter(&m, L, luaL_ref(L, LUA_REGISTRYINDEX)));
1728 chain.chain = effect_chain;
1729 chain.setup_chain = [this, funcref, input_state, effect_chain]{
1730 lock_guard<mutex> lock(m);
1732 assert(this->input_state == nullptr);
1733 this->input_state = &input_state;
1735 // Set up state, including connecting signals.
1736 lua_rawgeti(L, LUA_REGISTRYINDEX, funcref->get());
1737 if (lua_pcall(L, 0, 0, 0) != 0) {
1738 fprintf(stderr, "error running chain setup callback: %s\n", lua_tostring(L, -1));
1741 assert(lua_gettop(L) == 0);
1743 // The theme can't (or at least shouldn't!) call connect_signal() on
1744 // each FFmpeg or CEF input, so we'll do it here.
1745 if (video_signal_connections.count(effect_chain)) {
1746 for (const VideoSignalConnection &conn : video_signal_connections[effect_chain]) {
1747 conn.wrapper->connect_card(conn.source->get_card_index(), input_state);
1751 if (html_signal_connections.count(effect_chain)) {
1752 for (const CEFSignalConnection &conn : html_signal_connections[effect_chain]) {
1753 conn.wrapper->connect_card(conn.source->get_card_index(), input_state);
1758 this->input_state = nullptr;
1763 Theme::Chain Theme::get_chain(unsigned num, float t, unsigned width, unsigned height, const InputState &input_state)
1765 const char *func_name = "get_scene"; // For error reporting.
1768 lock_guard<mutex> lock(m);
1769 assert(lua_gettop(L) == 0);
1770 lua_getglobal(L, "get_scene"); /* function to be called */
1771 if (lua_isnil(L, -1)) {
1772 // Try the pre-1.9.0 name for compatibility.
1774 lua_getglobal(L, "get_chain");
1775 func_name = "get_chain";
1777 lua_pushnumber(L, num);
1778 lua_pushnumber(L, t);
1779 lua_pushnumber(L, width);
1780 lua_pushnumber(L, height);
1781 wrap_lua_object<InputStateInfo>(L, "InputStateInfo", input_state);
1783 if (lua_pcall(L, 5, LUA_MULTRET, 0) != 0) {
1784 fprintf(stderr, "error running function “%s”: %s\n", func_name, lua_tostring(L, -1));
1788 if (luaL_testudata(L, -1, "Scene") != nullptr) {
1789 if (lua_gettop(L) != 1) {
1790 luaL_error(L, "%s() for chain number %d returned an Scene, but also other items", func_name);
1792 Scene *auto_effect_chain = (Scene *)luaL_testudata(L, -1, "Scene");
1793 auto chain_and_setup = auto_effect_chain->get_chain(this, L, num, input_state);
1794 chain.chain = chain_and_setup.first;
1795 chain.setup_chain = move(chain_and_setup.second);
1796 } else if (luaL_testudata(L, -2, "EffectChain") != nullptr) {
1797 // Old-style (pre-Nageru 1.9.0) return of a single chain and prepare function.
1798 if (lua_gettop(L) != 2) {
1799 luaL_error(L, "%s() for chain number %d returned an EffectChain, but needs to also return a prepare function (or use Scene)", func_name);
1801 EffectChain *effect_chain = (EffectChain *)luaL_testudata(L, -2, "EffectChain");
1802 chain = get_chain_from_effect_chain(effect_chain, num, input_state);
1804 luaL_error(L, "%s() for chain number %d did not return an EffectChain or Scene\n", func_name, num);
1806 assert(lua_gettop(L) == 0);
1808 // TODO: Can we do better, e.g. by running setup_chain() and seeing what it references?
1809 // Actually, setup_chain does maybe hold all the references we need now anyway?
1810 chain.input_frames.reserve(MAX_VIDEO_CARDS * FRAME_HISTORY_LENGTH);
1811 for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) {
1812 for (unsigned frame_num = 0; frame_num < FRAME_HISTORY_LENGTH; ++frame_num) {
1813 chain.input_frames.push_back(input_state.buffered_frames[card_index][frame_num].frame);
1820 string Theme::get_channel_name(unsigned channel)
1822 lock_guard<mutex> lock(m);
1824 // We never ask the legacy channel_name() about live and preview.
1825 // The defaults are set in our constructor.
1826 if (channel == 0 || channel == 1) {
1827 return channel_names[channel];
1830 lua_getglobal(L, "channel_name");
1831 if (lua_isnil(L, -1)) {
1833 if (channel_names.count(channel)) {
1834 return channel_names[channel];
1836 return "(no title)";
1840 lua_pushnumber(L, channel);
1841 if (lua_pcall(L, 1, 1, 0) != 0) {
1842 fprintf(stderr, "error running function `channel_name': %s\n", lua_tostring(L, -1));
1845 const char *ret = lua_tostring(L, -1);
1846 if (ret == nullptr) {
1847 fprintf(stderr, "function `channel_name' returned nil for channel %d\n", channel);
1848 fprintf(stderr, "Try Nageru.set_channel_name(channel, name) at the start of the script instead.\n");
1852 string retstr = ret;
1854 assert(lua_gettop(L) == 0);
1858 int Theme::map_channel_to_signal(unsigned channel)
1860 lock_guard<mutex> lock(m);
1861 lua_getglobal(L, "channel_signal");
1862 if (lua_isnil(L, -1)) {
1864 if (channel_signals.count(channel)) {
1865 return channel_signals[channel];
1871 lua_pushnumber(L, channel);
1872 if (lua_pcall(L, 1, 1, 0) != 0) {
1873 fprintf(stderr, "error running function `channel_signal': %s\n", lua_tostring(L, -1));
1874 fprintf(stderr, "Try Nageru.set_channel_signal(channel, signal) at the start of the script instead.\n");
1878 int ret = luaL_checknumber(L, 1);
1880 assert(lua_gettop(L) == 0);
1884 std::string Theme::get_channel_color(unsigned channel)
1886 lock_guard<mutex> lock(m);
1887 lua_getglobal(L, "channel_color");
1888 lua_pushnumber(L, channel);
1889 if (lua_pcall(L, 1, 1, 0) != 0) {
1890 fprintf(stderr, "error running function `channel_color': %s\n", lua_tostring(L, -1));
1894 const char *ret = lua_tostring(L, -1);
1895 if (ret == nullptr) {
1896 fprintf(stderr, "function `channel_color' returned nil for channel %d\n", channel);
1900 string retstr = ret;
1902 assert(lua_gettop(L) == 0);
1906 bool Theme::get_supports_set_wb(unsigned channel)
1908 lock_guard<mutex> lock(m);
1909 lua_getglobal(L, "supports_set_wb");
1910 if (lua_isnil(L, -1)) {
1912 if (channel_supports_wb.count(channel)) {
1913 return channel_supports_wb[channel];
1919 lua_pushnumber(L, channel);
1920 if (lua_pcall(L, 1, 1, 0) != 0) {
1921 fprintf(stderr, "error running function `supports_set_wb': %s\n", lua_tostring(L, -1));
1922 fprintf(stderr, "Try Nageru.set_supports_wb(channel, bool) at the start of the script instead.\n");
1926 bool ret = checkbool(L, -1);
1928 assert(lua_gettop(L) == 0);
1932 void Theme::set_wb(unsigned channel, float r, float g, float b)
1934 int signal = map_channel_to_signal(channel);
1936 lock_guard<mutex> lock(m);
1938 int card_idx = map_signal_to_card(signal);
1939 white_balance_for_card[card_idx] = RGBTriplet{ r, g, b };
1942 call_lua_wb_callback(channel, r, g, b);
1945 void Theme::set_wb_for_card(int card_idx, float r, float g, float b)
1947 lock_guard<mutex> lock(m);
1948 white_balance_for_card[card_idx] = RGBTriplet{ r, g, b };
1950 for (const auto &channel_and_signal : channel_signals) {
1951 if (map_signal_to_card(channel_and_signal.second) == card_idx) {
1952 call_lua_wb_callback(channel_and_signal.first, r, g, b);
1957 void Theme::call_lua_wb_callback(unsigned channel, float r, float g, float b)
1959 lua_getglobal(L, "set_wb");
1960 if (lua_isnil(L, -1)) {
1961 // The function doesn't exist, to just ignore. We've stored the white balance,
1962 // and most likely, it will be picked up by auto white balance instead.
1966 lua_pushnumber(L, channel);
1967 lua_pushnumber(L, r);
1968 lua_pushnumber(L, g);
1969 lua_pushnumber(L, b);
1970 if (lua_pcall(L, 4, 0, 0) != 0) {
1971 fprintf(stderr, "error running function `set_wb': %s\n", lua_tostring(L, -1));
1975 assert(lua_gettop(L) == 0);
1978 RGBTriplet Theme::get_white_balance_for_card(int card_idx)
1980 if (white_balance_for_card.count(card_idx)) {
1981 return white_balance_for_card[card_idx];
1983 return RGBTriplet{ 1.0, 1.0, 1.0 };
1987 vector<string> Theme::get_transition_names(float t)
1989 lock_guard<mutex> lock(m);
1990 lua_getglobal(L, "get_transitions");
1991 lua_pushnumber(L, t);
1992 if (lua_pcall(L, 1, 1, 0) != 0) {
1993 fprintf(stderr, "error running function `get_transitions': %s\n", lua_tostring(L, -1));
1999 while (lua_next(L, -2) != 0) {
2000 ret.push_back(lua_tostring(L, -1));
2004 assert(lua_gettop(L) == 0);
2008 int Theme::map_signal_to_card(int signal_num)
2010 // Negative numbers map to raw signals.
2011 if (signal_num < 0) {
2012 return -1 - signal_num;
2015 lock_guard<mutex> lock(map_m);
2016 if (signal_to_card_mapping.count(signal_num)) {
2017 return signal_to_card_mapping[signal_num];
2021 if (global_flags.output_card != -1) {
2022 // Try to exclude the output card from the default card_index.
2023 card_index = signal_num % (global_flags.max_num_cards - 1);
2024 if (card_index >= global_flags.output_card) {
2027 if (signal_num >= int(global_flags.max_num_cards - 1)) {
2028 print_warning(L, "Theme asked for input %d, but we only have %u input card(s) (card %d is busy with output).\n",
2029 signal_num, global_flags.max_num_cards - 1, global_flags.output_card);
2030 fprintf(stderr, "Mapping to card %d instead.\n", card_index);
2033 card_index = signal_num % global_flags.max_num_cards;
2034 if (signal_num >= int(global_flags.max_num_cards)) {
2035 print_warning(L, "Theme asked for input %d, but we only have %u card(s).\n", signal_num, global_flags.max_num_cards);
2036 fprintf(stderr, "Mapping to card %d instead.\n", card_index);
2039 global_mixer->force_card_active(card_index);
2040 signal_to_card_mapping[signal_num] = card_index;
2044 void Theme::set_signal_mapping(int signal_num, int card_idx)
2046 lock_guard<mutex> lock(map_m);
2047 assert(card_idx < MAX_VIDEO_CARDS);
2048 signal_to_card_mapping[signal_num] = card_idx;
2051 void Theme::transition_clicked(int transition_num, float t)
2053 lock_guard<mutex> lock(m);
2054 lua_getglobal(L, "transition_clicked");
2055 lua_pushnumber(L, transition_num);
2056 lua_pushnumber(L, t);
2058 if (lua_pcall(L, 2, 0, 0) != 0) {
2059 fprintf(stderr, "error running function `transition_clicked': %s\n", lua_tostring(L, -1));
2062 assert(lua_gettop(L) == 0);
2065 void Theme::channel_clicked(int preview_num)
2067 lock_guard<mutex> lock(m);
2068 lua_getglobal(L, "channel_clicked");
2069 lua_pushnumber(L, preview_num);
2071 if (lua_pcall(L, 1, 0, 0) != 0) {
2072 fprintf(stderr, "error running function `channel_clicked': %s\n", lua_tostring(L, -1));
2075 assert(lua_gettop(L) == 0);
2079 void destroy(T &ref)
2084 Theme::MenuEntry::~MenuEntry()
2089 luaL_unref(entry.L, LUA_REGISTRYINDEX, entry.lua_ref);
2095 vector<unique_ptr<Theme::MenuEntry>> create_recursive_theme_menu(lua_State *L);
2097 unique_ptr<Theme::MenuEntry> create_theme_menu_entry(lua_State *L, int index)
2099 unique_ptr<Theme::MenuEntry> entry;
2101 lua_rawgeti(L, index, 1);
2102 const string text = checkstdstring(L, -1);
2106 if (lua_objlen(L, index) > 2) {
2107 lua_rawgeti(L, index, 3);
2108 flags = luaL_checknumber(L, -1);
2112 lua_rawgeti(L, index, 2);
2113 if (lua_istable(L, -1)) {
2114 vector<unique_ptr<Theme::MenuEntry>> submenu = create_recursive_theme_menu(L);
2115 entry.reset(new Theme::MenuEntry{ text, move(submenu) });
2118 luaL_checktype(L, -1, LUA_TFUNCTION);
2119 int ref = luaL_ref(L, LUA_REGISTRYINDEX);
2120 entry.reset(new Theme::MenuEntry{ text, L, ref, flags });
2125 vector<unique_ptr<Theme::MenuEntry>> create_recursive_theme_menu(lua_State *L)
2127 vector<unique_ptr<Theme::MenuEntry>> menu;
2128 size_t num_elements = lua_objlen(L, -1);
2129 for (size_t i = 1; i <= num_elements; ++i) {
2130 lua_rawgeti(L, -1, i);
2131 menu.emplace_back(create_theme_menu_entry(L, -1));
2139 int Theme::set_theme_menu(lua_State *L)
2143 vector<unique_ptr<MenuEntry>> root_menu;
2144 int num_elements = lua_gettop(L);
2145 for (int i = 1; i <= num_elements; ++i) {
2146 root_menu.emplace_back(create_theme_menu_entry(L, i));
2148 theme_menu.reset(new MenuEntry("", move(root_menu)));
2150 lua_pop(L, num_elements);
2151 assert(lua_gettop(L) == 0);
2153 if (theme_menu_callback != nullptr) {
2154 theme_menu_callback();
2160 void Theme::theme_menu_entry_clicked(int lua_ref)
2162 lock_guard<mutex> lock(m);
2163 lua_rawgeti(L, LUA_REGISTRYINDEX, lua_ref);
2164 if (lua_pcall(L, 0, 0, 0) != 0) {
2165 fprintf(stderr, "error running menu callback: %s\n", lua_tostring(L, -1));
2170 string Theme::format_status_line(const string &disk_space_left_text, double file_length_seconds)
2172 lock_guard<mutex> lock(m);
2173 lua_getglobal(L, "format_status_line");
2174 if (lua_isnil(L, -1)) {
2176 return disk_space_left_text;
2179 lua_pushstring(L, disk_space_left_text.c_str());
2180 lua_pushnumber(L, file_length_seconds);
2181 if (lua_pcall(L, 2, 1, 0) != 0) {
2182 fprintf(stderr, "error running function format_status_line(): %s\n", lua_tostring(L, -1));
2185 string text = checkstdstring(L, 1);
2187 assert(lua_gettop(L) == 0);
2191 void Theme::remove_card(unsigned card_index)
2193 lock_guard<mutex> lock(map_m);
2194 for (auto it = signal_to_card_mapping.begin(); it != signal_to_card_mapping.end(); ) {
2195 if (it->second == int(card_index)) {
2196 it = signal_to_card_mapping.erase(it);