4 #include <bmusb/bmusb.h>
9 #include <movit/blur_effect.h>
10 #include <movit/deinterlace_effect.h>
11 #include <movit/effect.h>
12 #include <movit/effect_chain.h>
13 #include <movit/image_format.h>
14 #include <movit/input.h>
15 #include <movit/lift_gamma_gain_effect.h>
16 #include <movit/mix_effect.h>
17 #include <movit/multiply_effect.h>
18 #include <movit/overlay_effect.h>
19 #include <movit/padding_effect.h>
20 #include <movit/resample_effect.h>
21 #include <movit/resize_effect.h>
22 #include <movit/util.h>
23 #include <movit/unsharp_mask_effect.h>
24 #include <movit/white_balance_effect.h>
25 #include <movit/ycbcr.h>
26 #include <movit/ycbcr_input.h>
34 #include "audio_mixer.h"
37 #include "cef_capture.h"
39 #include "ffmpeg_capture.h"
41 #include "image_input.h"
42 #include "input_state.h"
43 #include "lua_utils.h"
44 #include "mainwindow.h"
45 #include "pbo_frame_allocator.h"
55 using namespace movit;
57 extern Mixer *global_mixer;
59 constexpr unsigned Theme::MenuEntry::CHECKABLE;
60 constexpr unsigned Theme::MenuEntry::CHECKED;
62 Theme *get_theme_updata(lua_State* L)
64 luaL_checktype(L, lua_upvalueindex(1), LUA_TLIGHTUSERDATA);
65 return (Theme *)lua_touserdata(L, lua_upvalueindex(1));
68 void print_warning(lua_State* L, const char *format, ...)
73 vsnprintf(buf, sizeof(buf), format, ap);
77 lua_getstack(L, 1, &ar);
78 lua_getinfo(L, "nSl", &ar);
79 fprintf(stderr, "WARNING: %s:%d: %s", ar.source, ar.currentline, buf);
82 int ThemeMenu_set(lua_State *L)
84 Theme *theme = get_theme_updata(L);
85 return theme->set_theme_menu(L);
88 InputStateInfo::InputStateInfo(const InputState &input_state)
90 for (unsigned signal_num = 0; signal_num < MAX_VIDEO_CARDS; ++signal_num) {
91 BufferedFrame frame = input_state.buffered_frames[signal_num][0];
92 if (frame.frame == nullptr) {
93 last_width[signal_num] = last_height[signal_num] = 0;
94 last_interlaced[signal_num] = false;
95 last_has_signal[signal_num] = false;
96 last_is_connected[signal_num] = false;
99 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
100 last_width[signal_num] = userdata->last_width[frame.field_number];
101 last_height[signal_num] = userdata->last_height[frame.field_number];
102 last_interlaced[signal_num] = userdata->last_interlaced;
103 last_has_signal[signal_num] = userdata->last_has_signal;
104 last_is_connected[signal_num] = userdata->last_is_connected;
105 last_frame_rate_nom[signal_num] = userdata->last_frame_rate_nom;
106 last_frame_rate_den[signal_num] = userdata->last_frame_rate_den;
107 last_pixel_format[signal_num] = userdata->pixel_format;
108 has_last_subtitle[signal_num] = userdata->has_last_subtitle;
109 last_subtitle[signal_num] = userdata->last_subtitle;
113 // An effect that does nothing.
114 class IdentityEffect : public Effect {
117 string effect_type_id() const override { return "IdentityEffect"; }
118 string output_fragment_shader() override { return read_file("identity.frag"); }
121 Effect *instantiate_effect(EffectChain *chain, EffectType effect_type)
123 switch (effect_type) {
124 case IDENTITY_EFFECT:
125 return new IdentityEffect;
126 case WHITE_BALANCE_EFFECT:
127 case AUTO_WHITE_BALANCE_EFFECT:
128 return new WhiteBalanceEffect;
129 case RESAMPLE_EFFECT:
130 return new ResampleEffect;
132 return new PaddingEffect;
133 case INTEGRAL_PADDING_EFFECT:
134 return new IntegralPaddingEffect;
136 return new OverlayEffect;
138 return new ResizeEffect;
139 case MULTIPLY_EFFECT:
140 return new MultiplyEffect;
142 return new MixEffect;
143 case LIFT_GAMMA_GAIN_EFFECT:
144 return new LiftGammaGainEffect;
146 return new BlurEffect;
147 case UNSHARP_MASK_EFFECT:
148 return new UnsharpMaskEffect;
150 fprintf(stderr, "Unhandled effect type %d\n", effect_type);
157 Effect *get_effect_from_blueprint(EffectChain *chain, lua_State *L, int idx)
159 EffectBlueprint *blueprint = *(EffectBlueprint **)luaL_checkudata(L, idx, "EffectBlueprint");
160 if (blueprint->effect != nullptr) {
161 luaL_error(L, "An effect can currently only be added to one chain.\n");
164 Effect *effect = instantiate_effect(chain, blueprint->effect_type);
166 // Set the parameters that were deferred earlier.
167 for (const auto &kv : blueprint->int_parameters) {
168 if (!effect->set_int(kv.first, kv.second)) {
169 luaL_error(L, "Effect refused set_int(\"%s\", %d) (invalid key?)", kv.first.c_str(), kv.second);
172 for (const auto &kv : blueprint->float_parameters) {
173 if (!effect->set_float(kv.first, kv.second)) {
174 luaL_error(L, "Effect refused set_float(\"%s\", %f) (invalid key?)", kv.first.c_str(), kv.second);
177 for (const auto &kv : blueprint->vec3_parameters) {
178 if (!effect->set_vec3(kv.first, kv.second.data())) {
179 luaL_error(L, "Effect refused set_vec3(\"%s\", %f, %f, %f) (invalid key?)", kv.first.c_str(),
180 kv.second[0], kv.second[1], kv.second[2]);
183 for (const auto &kv : blueprint->vec4_parameters) {
184 if (!effect->set_vec4(kv.first, kv.second.data())) {
185 luaL_error(L, "Effect refused set_vec4(\"%s\", %f, %f, %f, %f) (invalid key?)", kv.first.c_str(),
186 kv.second[0], kv.second[1], kv.second[2], kv.second[3]);
189 blueprint->effect = effect;
193 InputStateInfo *get_input_state_info(lua_State *L, int idx)
195 if (luaL_testudata(L, idx, "InputStateInfo")) {
196 return (InputStateInfo *)lua_touserdata(L, idx);
198 luaL_error(L, "Error: Index #%d was not InputStateInfo\n", idx);
204 bool checkbool(lua_State* L, int idx)
206 luaL_checktype(L, idx, LUA_TBOOLEAN);
207 return lua_toboolean(L, idx);
210 string checkstdstring(lua_State *L, int index)
213 const char* cstr = lua_tolstring(L, index, &len);
214 return string(cstr, len);
219 int Scene_new(lua_State* L)
221 assert(lua_gettop(L) == 2);
222 Theme *theme = get_theme_updata(L);
223 int aspect_w = luaL_checknumber(L, 1);
224 int aspect_h = luaL_checknumber(L, 2);
226 return wrap_lua_object<Scene>(L, "Scene", theme, aspect_w, aspect_h);
229 int Scene_gc(lua_State* L)
231 assert(lua_gettop(L) == 1);
232 Scene *chain = (Scene *)luaL_checkudata(L, 1, "Scene");
239 void add_outputs_and_finalize(EffectChain *chain, bool is_main_chain)
241 // Add outputs as needed.
242 // NOTE: If you change any details about the output format, you will need to
243 // also update what's given to the muxer (HTTPD::Mux constructor) and
244 // what's put in the H.264 stream (sps_rbsp()).
245 ImageFormat inout_format;
246 inout_format.color_space = COLORSPACE_REC_709;
248 // Output gamma is tricky. We should output Rec. 709 for TV, except that
249 // we expect to run with web players and others that don't really care and
250 // just output with no conversion. So that means we'll need to output sRGB,
251 // even though H.264 has no setting for that (we use “unspecified”).
252 inout_format.gamma_curve = GAMMA_sRGB;
255 YCbCrFormat output_ycbcr_format;
256 // We actually output 4:2:0 and/or 4:2:2 in the end, but chroma subsampling
257 // happens in a pass not run by Movit (see ChromaSubsampler::subsample_chroma()).
258 output_ycbcr_format.chroma_subsampling_x = 1;
259 output_ycbcr_format.chroma_subsampling_y = 1;
261 // This will be overridden if HDMI/SDI output is in force.
262 if (global_flags.ycbcr_rec709_coefficients) {
263 output_ycbcr_format.luma_coefficients = YCBCR_REC_709;
265 output_ycbcr_format.luma_coefficients = YCBCR_REC_601;
268 output_ycbcr_format.full_range = false;
269 output_ycbcr_format.num_levels = 1 << global_flags.bit_depth;
271 GLenum type = global_flags.bit_depth > 8 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_BYTE;
273 chain->add_ycbcr_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED, output_ycbcr_format, YCBCR_OUTPUT_SPLIT_Y_AND_CBCR, type);
275 // If we're using zerocopy video encoding (so the destination
276 // Y texture is owned by VA-API and will be unavailable for
277 // display), add a copy, where we'll only be using the Y component.
278 if (global_flags.use_zerocopy) {
279 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.
281 chain->set_dither_bits(global_flags.bit_depth > 8 ? 16 : 8);
282 chain->set_output_origin(OUTPUT_ORIGIN_TOP_LEFT);
284 chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
292 int EffectChain_new(lua_State* L)
294 assert(lua_gettop(L) == 2);
295 Theme *theme = get_theme_updata(L);
296 int aspect_w = luaL_checknumber(L, 1);
297 int aspect_h = luaL_checknumber(L, 2);
299 return wrap_lua_object<EffectChain>(L, "EffectChain", aspect_w, aspect_h, theme->get_resource_pool());
302 int EffectChain_gc(lua_State* L)
304 assert(lua_gettop(L) == 1);
305 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
306 chain->~EffectChain();
310 int EffectChain_add_live_input(lua_State* L)
312 assert(lua_gettop(L) == 3);
313 Theme *theme = get_theme_updata(L);
314 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
315 bool override_bounce = checkbool(L, 2);
316 bool deinterlace = checkbool(L, 3);
317 bmusb::PixelFormat pixel_format = global_flags.bit_depth > 8 ? bmusb::PixelFormat_10BitYCbCr : bmusb::PixelFormat_8BitYCbCr;
319 // Needs to be nonowned to match add_video_input (see below).
320 return wrap_lua_object_nonowned<LiveInputWrapper>(L, "LiveInputWrapper", theme, chain, pixel_format, override_bounce, deinterlace, /*user_connectable=*/true);
323 int EffectChain_add_video_input(lua_State* L)
325 assert(lua_gettop(L) == 3);
326 Theme *theme = get_theme_updata(L);
327 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
328 FFmpegCapture **capture = (FFmpegCapture **)luaL_checkudata(L, 2, "VideoInput");
329 bool deinterlace = checkbool(L, 3);
331 // These need to be nonowned, so that the LiveInputWrapper still exists
332 // and can feed frames to the right EffectChain even if the Lua code
333 // doesn't care about the object anymore. (If we change this, we'd need
334 // to also unregister the signal connection on __gc.)
335 int ret = wrap_lua_object_nonowned<LiveInputWrapper>(
336 L, "LiveInputWrapper", theme, chain, (*capture)->get_current_pixel_format(),
337 /*override_bounce=*/false, deinterlace, /*user_connectable=*/false);
339 Theme *theme = get_theme_updata(L);
340 LiveInputWrapper **live_input = (LiveInputWrapper **)lua_touserdata(L, -1);
341 theme->register_video_signal_connection(chain, *live_input, *capture);
347 int EffectChain_add_html_input(lua_State* L)
349 assert(lua_gettop(L) == 2);
350 Theme *theme = get_theme_updata(L);
351 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
352 CEFCapture **capture = (CEFCapture **)luaL_checkudata(L, 2, "HTMLInput");
354 // These need to be nonowned, so that the LiveInputWrapper still exists
355 // and can feed frames to the right EffectChain even if the Lua code
356 // doesn't care about the object anymore. (If we change this, we'd need
357 // to also unregister the signal connection on __gc.)
358 int ret = wrap_lua_object_nonowned<LiveInputWrapper>(
359 L, "LiveInputWrapper", theme, chain, (*capture)->get_current_pixel_format(),
360 /*override_bounce=*/false, /*deinterlace=*/false, /*user_connectable=*/false);
362 Theme *theme = get_theme_updata(L);
363 LiveInputWrapper **live_input = (LiveInputWrapper **)lua_touserdata(L, -1);
364 theme->register_html_signal_connection(chain, *live_input, *capture);
370 int EffectChain_add_effect(lua_State* L)
372 assert(lua_gettop(L) >= 2);
373 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
375 // TODO: Better error reporting.
377 if (luaL_testudata(L, 2, "ImageInput")) {
378 effect = *(ImageInput **)luaL_checkudata(L, 2, "ImageInput");
380 effect = get_effect_from_blueprint(chain, L, 2);
382 if (lua_gettop(L) == 2) {
383 if (effect->num_inputs() == 0) {
384 chain->add_input((Input *)effect);
386 chain->add_effect(effect);
389 vector<Effect *> inputs;
390 for (int idx = 3; idx <= lua_gettop(L); ++idx) {
391 if (luaL_testudata(L, idx, "LiveInputWrapper")) {
392 LiveInputWrapper **input = (LiveInputWrapper **)lua_touserdata(L, idx);
393 inputs.push_back((*input)->get_effect());
394 } else if (luaL_testudata(L, idx, "ImageInput")) {
395 ImageInput *image = *(ImageInput **)luaL_checkudata(L, idx, "ImageInput");
396 inputs.push_back(image);
398 EffectBlueprint *blueprint = *(EffectBlueprint **)luaL_checkudata(L, idx, "EffectBlueprint");
399 assert(blueprint->effect != nullptr); // Parent must be added to the graph.
400 inputs.push_back(blueprint->effect);
403 chain->add_effect(effect, inputs);
406 lua_settop(L, 2); // Return the effect itself.
408 // Make sure Lua doesn't garbage-collect it away.
409 lua_pushvalue(L, -1);
410 luaL_ref(L, LUA_REGISTRYINDEX); // TODO: leak?
415 int EffectChain_finalize(lua_State* L)
417 assert(lua_gettop(L) == 2);
418 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
419 bool is_main_chain = checkbool(L, 2);
420 add_outputs_and_finalize(chain, is_main_chain);
424 int LiveInputWrapper_connect_signal(lua_State* L)
426 assert(lua_gettop(L) == 2);
427 LiveInputWrapper **input = (LiveInputWrapper **)luaL_checkudata(L, 1, "LiveInputWrapper");
428 int signal_num = luaL_checknumber(L, 2);
429 bool success = (*input)->connect_signal(signal_num);
431 print_warning(L, "Calling connect_signal() on a video or HTML input. Ignoring.\n");
436 int ImageInput_new(lua_State* L)
438 assert(lua_gettop(L) == 1);
439 string filename = checkstdstring(L, 1);
440 return wrap_lua_object_nonowned<ImageInput>(L, "ImageInput", filename);
443 int VideoInput_new(lua_State* L)
445 assert(lua_gettop(L) == 2);
446 string filename = checkstdstring(L, 1);
447 int pixel_format = luaL_checknumber(L, 2);
448 if (pixel_format != bmusb::PixelFormat_8BitYCbCrPlanar &&
449 pixel_format != bmusb::PixelFormat_8BitBGRA) {
450 print_warning(L, "Invalid enum %d used for video format, choosing Y'CbCr.\n", pixel_format);
451 pixel_format = bmusb::PixelFormat_8BitYCbCrPlanar;
453 int ret = wrap_lua_object_nonowned<FFmpegCapture>(L, "VideoInput", filename, global_flags.width, global_flags.height);
455 FFmpegCapture **capture = (FFmpegCapture **)lua_touserdata(L, -1);
456 (*capture)->set_pixel_format(bmusb::PixelFormat(pixel_format));
458 Theme *theme = get_theme_updata(L);
459 theme->register_video_input(*capture);
464 int VideoInput_rewind(lua_State* L)
466 assert(lua_gettop(L) == 1);
467 FFmpegCapture **video_input = (FFmpegCapture **)luaL_checkudata(L, 1, "VideoInput");
468 (*video_input)->rewind();
472 int VideoInput_disconnect(lua_State* L)
474 assert(lua_gettop(L) == 1);
475 FFmpegCapture **video_input = (FFmpegCapture **)luaL_checkudata(L, 1, "VideoInput");
476 (*video_input)->disconnect();
480 int VideoInput_change_rate(lua_State* L)
482 assert(lua_gettop(L) == 2);
483 FFmpegCapture **video_input = (FFmpegCapture **)luaL_checkudata(L, 1, "VideoInput");
484 double new_rate = luaL_checknumber(L, 2);
485 (*video_input)->change_rate(new_rate);
489 int VideoInput_get_signal_num(lua_State* L)
491 assert(lua_gettop(L) == 1);
492 FFmpegCapture **video_input = (FFmpegCapture **)luaL_checkudata(L, 1, "VideoInput");
493 lua_pushnumber(L, -1 - (*video_input)->get_card_index());
497 int HTMLInput_new(lua_State* L)
500 assert(lua_gettop(L) == 1);
501 string url = checkstdstring(L, 1);
502 int ret = wrap_lua_object_nonowned<CEFCapture>(L, "HTMLInput", url, global_flags.width, global_flags.height);
504 CEFCapture **capture = (CEFCapture **)lua_touserdata(L, -1);
505 Theme *theme = get_theme_updata(L);
506 theme->register_html_input(*capture);
510 fprintf(stderr, "This version of Nageru has been compiled without CEF support.\n");
511 fprintf(stderr, "HTMLInput is not available.\n");
517 int HTMLInput_set_url(lua_State* L)
519 assert(lua_gettop(L) == 2);
520 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
521 string new_url = checkstdstring(L, 2);
522 (*video_input)->set_url(new_url);
526 int HTMLInput_reload(lua_State* L)
528 assert(lua_gettop(L) == 1);
529 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
530 (*video_input)->reload();
534 int HTMLInput_set_max_fps(lua_State* L)
536 assert(lua_gettop(L) == 2);
537 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
538 int max_fps = lrint(luaL_checknumber(L, 2));
539 (*video_input)->set_max_fps(max_fps);
543 int HTMLInput_execute_javascript_async(lua_State* L)
545 assert(lua_gettop(L) == 2);
546 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
547 string js = checkstdstring(L, 2);
548 (*video_input)->execute_javascript_async(js);
552 int HTMLInput_resize(lua_State* L)
554 assert(lua_gettop(L) == 3);
555 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
556 unsigned width = lrint(luaL_checknumber(L, 2));
557 unsigned height = lrint(luaL_checknumber(L, 3));
558 (*video_input)->resize(width, height);
562 int HTMLInput_get_signal_num(lua_State* L)
564 assert(lua_gettop(L) == 1);
565 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
566 lua_pushnumber(L, -1 - (*video_input)->get_card_index());
571 int IdentityEffect_new(lua_State* L)
573 assert(lua_gettop(L) == 0);
574 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", IDENTITY_EFFECT);
577 int WhiteBalanceEffect_new(lua_State* L)
579 assert(lua_gettop(L) == 0);
580 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", WHITE_BALANCE_EFFECT);
583 int ResampleEffect_new(lua_State* L)
585 assert(lua_gettop(L) == 0);
586 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", RESAMPLE_EFFECT);
589 int PaddingEffect_new(lua_State* L)
591 assert(lua_gettop(L) == 0);
592 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", PADDING_EFFECT);
595 int IntegralPaddingEffect_new(lua_State* L)
597 assert(lua_gettop(L) == 0);
598 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", INTEGRAL_PADDING_EFFECT);
601 int OverlayEffect_new(lua_State* L)
603 assert(lua_gettop(L) == 0);
604 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", OVERLAY_EFFECT);
607 int ResizeEffect_new(lua_State* L)
609 assert(lua_gettop(L) == 0);
610 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", RESIZE_EFFECT);
613 int MultiplyEffect_new(lua_State* L)
615 assert(lua_gettop(L) == 0);
616 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", MULTIPLY_EFFECT);
619 int MixEffect_new(lua_State* L)
621 assert(lua_gettop(L) == 0);
622 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", MIX_EFFECT);
625 int LiftGammaGainEffect_new(lua_State* L)
627 assert(lua_gettop(L) == 0);
628 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", LIFT_GAMMA_GAIN_EFFECT);
631 int BlurEffect_new(lua_State* L)
633 assert(lua_gettop(L) == 0);
634 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", BLUR_EFFECT);
637 int UnsharpMaskEffect_new(lua_State* L)
639 assert(lua_gettop(L) == 0);
640 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", UNSHARP_MASK_EFFECT);
643 int InputStateInfo_get_width(lua_State* L)
645 assert(lua_gettop(L) == 2);
646 InputStateInfo *input_state_info = get_input_state_info(L, 1);
648 Theme *theme = get_theme_updata(L);
649 int card_idx = theme->map_signal_to_card(luaL_checknumber(L, 2));
650 lua_pushnumber(L, input_state_info->last_width[card_idx]);
654 int InputStateInfo_get_height(lua_State* L)
656 assert(lua_gettop(L) == 2);
657 InputStateInfo *input_state_info = get_input_state_info(L, 1);
658 Theme *theme = get_theme_updata(L);
659 int card_idx = theme->map_signal_to_card(luaL_checknumber(L, 2));
660 lua_pushnumber(L, input_state_info->last_height[card_idx]);
664 int InputStateInfo_get_frame_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 unsigned height = input_state_info->last_height[card_idx];
671 if (input_state_info->last_interlaced[card_idx]) {
674 lua_pushnumber(L, height);
678 int InputStateInfo_get_interlaced(lua_State* L)
680 assert(lua_gettop(L) == 2);
681 InputStateInfo *input_state_info = get_input_state_info(L, 1);
682 Theme *theme = get_theme_updata(L);
683 int card_idx = theme->map_signal_to_card(luaL_checknumber(L, 2));
684 lua_pushboolean(L, input_state_info->last_interlaced[card_idx]);
688 int InputStateInfo_get_has_signal(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_has_signal[card_idx]);
698 int InputStateInfo_get_is_connected(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_is_connected[card_idx]);
708 int InputStateInfo_get_frame_rate_nom(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_pushnumber(L, input_state_info->last_frame_rate_nom[card_idx]);
718 int InputStateInfo_get_frame_rate_den(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_den[card_idx]);
728 int InputStateInfo_get_last_subtitle(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 if (!input_state_info->has_last_subtitle[card_idx]) {
737 lua_pushstring(L, input_state_info->last_subtitle[card_idx].c_str());
744 // Helper function to write e.g. “60” or “59.94”.
745 string format_frame_rate(int nom, int den)
748 if (nom % den == 0) {
749 snprintf(buf, sizeof(buf), "%d", nom / den);
751 snprintf(buf, sizeof(buf), "%.2f", double(nom) / den);
756 // Helper function to write e.g. “720p60”.
757 string get_human_readable_resolution(const InputStateInfo *input_state_info, int signal_num)
760 if (input_state_info->last_interlaced[signal_num]) {
761 snprintf(buf, sizeof(buf), "%di", input_state_info->last_height[signal_num] * 2);
763 // Show field rate instead of frame rate; really for cosmetics only
764 // (and actually contrary to EBU recommendations, although in line
765 // with typical user expectations).
766 return buf + format_frame_rate(input_state_info->last_frame_rate_nom[signal_num] * 2,
767 input_state_info->last_frame_rate_den[signal_num]);
769 snprintf(buf, sizeof(buf), "%dp", input_state_info->last_height[signal_num]);
770 return buf + format_frame_rate(input_state_info->last_frame_rate_nom[signal_num],
771 input_state_info->last_frame_rate_den[signal_num]);
777 int InputStateInfo_get_human_readable_resolution(lua_State* L)
779 assert(lua_gettop(L) == 2);
780 InputStateInfo *input_state_info = get_input_state_info(L, 1);
781 Theme *theme = get_theme_updata(L);
782 int card_idx = theme->map_signal_to_card(luaL_checknumber(L, 2));
785 if (!input_state_info->last_is_connected[card_idx]) {
786 str = "disconnected";
787 } else if (input_state_info->last_height[card_idx] <= 0) {
789 } else if (!input_state_info->last_has_signal[card_idx]) {
790 if (input_state_info->last_height[card_idx] == 525) {
791 // Special mode for the USB3 cards.
794 str = get_human_readable_resolution(input_state_info, card_idx) + ", no signal";
797 str = get_human_readable_resolution(input_state_info, card_idx);
800 lua_pushstring(L, str.c_str());
805 int EffectBlueprint_set_int(lua_State *L)
807 assert(lua_gettop(L) == 3);
808 EffectBlueprint *blueprint = *(EffectBlueprint **)luaL_checkudata(L, 1, "EffectBlueprint");
809 string key = checkstdstring(L, 2);
810 float value = luaL_checknumber(L, 3);
811 if (blueprint->effect != nullptr) {
812 if (!blueprint->effect->set_int(key, value)) {
813 luaL_error(L, "Effect refused set_int(\"%s\", %d) (invalid key?)", key.c_str(), int(value));
816 // TODO: check validity already here, if possible?
817 blueprint->int_parameters[key] = value;
822 int EffectBlueprint_set_float(lua_State *L)
824 assert(lua_gettop(L) == 3);
825 EffectBlueprint *blueprint = *(EffectBlueprint **)luaL_checkudata(L, 1, "EffectBlueprint");
826 string key = checkstdstring(L, 2);
827 float value = luaL_checknumber(L, 3);
828 if (blueprint->effect != nullptr) {
829 if (!blueprint->effect->set_float(key, value)) {
830 luaL_error(L, "Effect refused set_float(\"%s\", %d) (invalid key?)", key.c_str(), int(value));
833 // TODO: check validity already here, if possible?
834 blueprint->float_parameters[key] = value;
839 int EffectBlueprint_set_vec3(lua_State *L)
841 assert(lua_gettop(L) == 5);
842 EffectBlueprint *blueprint = *(EffectBlueprint **)luaL_checkudata(L, 1, "EffectBlueprint");
843 string key = checkstdstring(L, 2);
845 v[0] = luaL_checknumber(L, 3);
846 v[1] = luaL_checknumber(L, 4);
847 v[2] = luaL_checknumber(L, 5);
849 if (blueprint->effect != nullptr) {
850 if (!blueprint->effect->set_vec3(key, v.data())) {
851 luaL_error(L, "Effect refused set_vec3(\"%s\", %f, %f, %f) (invalid key?)", key.c_str(),
855 // TODO: check validity already here, if possible?
856 blueprint->vec3_parameters[key] = v;
862 int EffectBlueprint_set_vec4(lua_State *L)
864 assert(lua_gettop(L) == 6);
865 EffectBlueprint *blueprint = *(EffectBlueprint **)luaL_checkudata(L, 1, "EffectBlueprint");
866 string key = checkstdstring(L, 2);
868 v[0] = luaL_checknumber(L, 3);
869 v[1] = luaL_checknumber(L, 4);
870 v[2] = luaL_checknumber(L, 5);
871 v[3] = luaL_checknumber(L, 6);
872 if (blueprint->effect != nullptr) {
873 if (!blueprint->effect->set_vec4(key, v.data())) {
874 luaL_error(L, "Effect refused set_vec4(\"%s\", %f, %f, %f, %f) (invalid key?)", key.c_str(),
875 v[0], v[1], v[2], v[3]);
878 // TODO: check validity already here, if possible?
879 blueprint->vec4_parameters[key] = v;
884 const luaL_Reg Scene_funcs[] = {
885 { "new", Scene_new },
886 { "__gc", Scene_gc },
887 { "add_input", Scene::add_input },
888 { "add_white_balance", Scene::add_white_balance },
889 { "add_effect", Scene::add_effect },
890 { "add_optional_effect", Scene::add_optional_effect },
891 { "finalize", Scene::finalize },
895 const luaL_Reg Block_funcs[] = {
896 { "display", Block_display },
897 { "choose", Block_choose },
898 { "enable", Block_enable },
899 { "enable_if", Block_enable_if },
900 { "disable", Block_disable },
901 { "always_disable_if_disabled", Block_always_disable_if_disabled },
902 { "promise_to_disable_if_enabled", Block_promise_to_disable_if_enabled },
903 { "set_int", Block_set_int },
904 { "set_float", Block_set_float },
905 { "set_vec3", Block_set_vec3 },
906 { "set_vec4", Block_set_vec4 },
910 const luaL_Reg EffectBlueprint_funcs[] = {
911 // NOTE: No new() function; that's for the individual effects.
912 { "set_int", EffectBlueprint_set_int },
913 { "set_float", EffectBlueprint_set_float },
914 { "set_vec3", EffectBlueprint_set_vec3 },
915 { "set_vec4", EffectBlueprint_set_vec4 },
919 const luaL_Reg EffectChain_funcs[] = {
920 { "new", EffectChain_new },
921 { "__gc", EffectChain_gc },
922 { "add_live_input", EffectChain_add_live_input },
923 { "add_video_input", EffectChain_add_video_input },
925 { "add_html_input", EffectChain_add_html_input },
927 { "add_effect", EffectChain_add_effect },
928 { "finalize", EffectChain_finalize },
932 const luaL_Reg LiveInputWrapper_funcs[] = {
933 { "connect_signal", LiveInputWrapper_connect_signal },
937 const luaL_Reg ImageInput_funcs[] = {
938 { "new", ImageInput_new },
942 const luaL_Reg VideoInput_funcs[] = {
943 { "new", VideoInput_new },
944 { "rewind", VideoInput_rewind },
945 { "disconnect", VideoInput_disconnect },
946 { "change_rate", VideoInput_change_rate },
947 { "get_signal_num", VideoInput_get_signal_num },
951 const luaL_Reg HTMLInput_funcs[] = {
952 { "new", HTMLInput_new },
954 { "set_url", HTMLInput_set_url },
955 { "reload", HTMLInput_reload },
956 { "set_max_fps", HTMLInput_set_max_fps },
957 { "execute_javascript_async", HTMLInput_execute_javascript_async },
958 { "resize", HTMLInput_resize },
959 { "get_signal_num", HTMLInput_get_signal_num },
965 // All of these are solely for new(); the returned metatable will be that of
966 // EffectBlueprint, and Effect (returned from add_effect()) is its own type.
968 const luaL_Reg IdentityEffect_funcs[] = {
969 { "new", IdentityEffect_new },
973 const luaL_Reg WhiteBalanceEffect_funcs[] = {
974 { "new", WhiteBalanceEffect_new },
978 const luaL_Reg ResampleEffect_funcs[] = {
979 { "new", ResampleEffect_new },
983 const luaL_Reg PaddingEffect_funcs[] = {
984 { "new", PaddingEffect_new },
988 const luaL_Reg IntegralPaddingEffect_funcs[] = {
989 { "new", IntegralPaddingEffect_new },
993 const luaL_Reg OverlayEffect_funcs[] = {
994 { "new", OverlayEffect_new },
998 const luaL_Reg ResizeEffect_funcs[] = {
999 { "new", ResizeEffect_new },
1003 const luaL_Reg MultiplyEffect_funcs[] = {
1004 { "new", MultiplyEffect_new },
1008 const luaL_Reg MixEffect_funcs[] = {
1009 { "new", MixEffect_new },
1013 const luaL_Reg LiftGammaGainEffect_funcs[] = {
1014 { "new", LiftGammaGainEffect_new },
1018 const luaL_Reg BlurEffect_funcs[] = {
1019 { "new", BlurEffect_new },
1023 const luaL_Reg UnsharpMaskEffect_funcs[] = {
1024 { "new", UnsharpMaskEffect_new },
1030 const luaL_Reg InputStateInfo_funcs[] = {
1031 { "get_width", InputStateInfo_get_width },
1032 { "get_height", InputStateInfo_get_height },
1033 { "get_frame_width", InputStateInfo_get_width }, // Same as get_width().
1034 { "get_frame_height", InputStateInfo_get_frame_height },
1035 { "get_interlaced", InputStateInfo_get_interlaced },
1036 { "get_has_signal", InputStateInfo_get_has_signal },
1037 { "get_is_connected", InputStateInfo_get_is_connected },
1038 { "get_frame_rate_nom", InputStateInfo_get_frame_rate_nom },
1039 { "get_frame_rate_den", InputStateInfo_get_frame_rate_den },
1040 { "get_last_subtitle", InputStateInfo_get_last_subtitle },
1041 { "get_human_readable_resolution", InputStateInfo_get_human_readable_resolution },
1045 const luaL_Reg ThemeMenu_funcs[] = {
1046 { "set", ThemeMenu_set },
1052 LiveInputWrapper::LiveInputWrapper(
1055 bmusb::PixelFormat pixel_format,
1056 bool override_bounce,
1058 bool user_connectable)
1060 pixel_format(pixel_format),
1061 deinterlace(deinterlace),
1062 user_connectable(user_connectable)
1064 ImageFormat inout_format;
1065 inout_format.color_space = COLORSPACE_sRGB;
1067 // Gamma curve depends on the input signal, and we don't really get any
1068 // indications. A camera would be expected to do Rec. 709, but
1069 // I haven't checked if any do in practice. However, computers _do_ output
1070 // in sRGB gamma (ie., they don't convert from sRGB to Rec. 709), and
1071 // I wouldn't really be surprised if most non-professional cameras do, too.
1072 // So we pick sRGB as the least evil here.
1073 inout_format.gamma_curve = GAMMA_sRGB;
1075 unsigned num_inputs;
1077 deinterlace_effect = new movit::DeinterlaceEffect();
1079 // As per the comments in deinterlace_effect.h, we turn this off.
1080 // The most likely interlaced input for us is either a camera
1081 // (where it's fine to turn it off) or a laptop (where it _should_
1083 CHECK(deinterlace_effect->set_int("enable_spatial_interlacing_check", 0));
1085 num_inputs = deinterlace_effect->num_inputs();
1086 assert(num_inputs == FRAME_HISTORY_LENGTH);
1091 if (pixel_format == bmusb::PixelFormat_8BitBGRA) {
1092 for (unsigned i = 0; i < num_inputs; ++i) {
1093 // We upload our textures ourselves, and Movit swaps
1094 // R and B in the shader if we specify BGRA, so lie and say RGBA.
1095 rgba_inputs.push_back(new sRGBSwitchingFlatInput(inout_format, FORMAT_RGBA_POSTMULTIPLIED_ALPHA, GL_UNSIGNED_BYTE, global_flags.width, global_flags.height));
1096 chain->add_input(rgba_inputs.back());
1100 vector<Effect *> reverse_inputs(rgba_inputs.rbegin(), rgba_inputs.rend());
1101 chain->add_effect(deinterlace_effect, reverse_inputs);
1104 assert(pixel_format == bmusb::PixelFormat_8BitYCbCr ||
1105 pixel_format == bmusb::PixelFormat_10BitYCbCr ||
1106 pixel_format == bmusb::PixelFormat_8BitYCbCrPlanar);
1108 // Most of these settings will be overridden later if using PixelFormat_8BitYCbCrPlanar.
1109 input_ycbcr_format.chroma_subsampling_x = (pixel_format == bmusb::PixelFormat_10BitYCbCr) ? 1 : 2;
1110 input_ycbcr_format.chroma_subsampling_y = 1;
1111 input_ycbcr_format.num_levels = (pixel_format == bmusb::PixelFormat_10BitYCbCr) ? 1024 : 256;
1112 input_ycbcr_format.cb_x_position = 0.0;
1113 input_ycbcr_format.cr_x_position = 0.0;
1114 input_ycbcr_format.cb_y_position = 0.5;
1115 input_ycbcr_format.cr_y_position = 0.5;
1116 input_ycbcr_format.luma_coefficients = YCBCR_REC_709; // Will be overridden later even if not planar.
1117 input_ycbcr_format.full_range = false; // Will be overridden later even if not planar.
1119 for (unsigned i = 0; i < num_inputs; ++i) {
1120 // When using 10-bit input, we're converting to interleaved through v210Converter.
1121 YCbCrInputSplitting splitting;
1122 if (pixel_format == bmusb::PixelFormat_10BitYCbCr) {
1123 splitting = YCBCR_INPUT_INTERLEAVED;
1124 } else if (pixel_format == bmusb::PixelFormat_8BitYCbCr) {
1125 splitting = YCBCR_INPUT_SPLIT_Y_AND_CBCR;
1127 splitting = YCBCR_INPUT_PLANAR;
1129 if (override_bounce) {
1130 ycbcr_inputs.push_back(new NonBouncingYCbCrInput(inout_format, input_ycbcr_format, global_flags.width, global_flags.height, splitting));
1132 ycbcr_inputs.push_back(new YCbCrInput(inout_format, input_ycbcr_format, global_flags.width, global_flags.height, splitting));
1134 chain->add_input(ycbcr_inputs.back());
1138 vector<Effect *> reverse_inputs(ycbcr_inputs.rbegin(), ycbcr_inputs.rend());
1139 chain->add_effect(deinterlace_effect, reverse_inputs);
1144 bool LiveInputWrapper::connect_signal(int signal_num)
1146 if (!user_connectable) {
1150 if (global_mixer == nullptr) {
1155 int card_idx = theme->map_signal_to_card(signal_num);
1156 connect_card(card_idx, *theme->input_state);
1160 void LiveInputWrapper::connect_card(int card_idx, const InputState &input_state)
1162 BufferedFrame first_frame = input_state.buffered_frames[card_idx][0];
1163 if (first_frame.frame == nullptr) {
1167 unsigned width, height;
1169 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)first_frame.frame->userdata;
1170 width = userdata->last_width[first_frame.field_number];
1171 height = userdata->last_height[first_frame.field_number];
1172 if (userdata->last_interlaced) {
1177 movit::YCbCrLumaCoefficients ycbcr_coefficients = input_state.ycbcr_coefficients[card_idx];
1178 bool full_range = input_state.full_range[card_idx];
1180 if (input_state.ycbcr_coefficients_auto[card_idx]) {
1183 // The Blackmagic driver docs claim that the device outputs Y'CbCr
1184 // according to Rec. 601, but this seems to indicate the subsampling
1185 // positions only, as they publish Y'CbCr → RGB formulas that are
1186 // different for HD and SD (corresponding to Rec. 709 and 601, respectively),
1187 // and a Lenovo X1 gen 3 I used to test definitely outputs Rec. 709
1188 // (at least up to rounding error). Other devices seem to use Rec. 601
1189 // even on HD resolutions. Nevertheless, Rec. 709 _is_ the right choice
1190 // for HD, so we default to that if the user hasn't set anything.
1191 if (height >= 720) {
1192 ycbcr_coefficients = YCBCR_REC_709;
1194 ycbcr_coefficients = YCBCR_REC_601;
1198 // This is a global, but it doesn't really matter.
1199 input_ycbcr_format.luma_coefficients = ycbcr_coefficients;
1200 input_ycbcr_format.full_range = full_range;
1202 BufferedFrame last_good_frame = first_frame;
1203 for (unsigned i = 0; i < max(ycbcr_inputs.size(), rgba_inputs.size()); ++i) {
1204 BufferedFrame frame = input_state.buffered_frames[card_idx][i];
1205 if (frame.frame == nullptr) {
1206 // Not enough data; reuse last frame (well, field).
1207 // This is suboptimal, but we have nothing better.
1208 frame = last_good_frame;
1210 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
1212 unsigned this_width = userdata->last_width[frame.field_number];
1213 unsigned this_height = userdata->last_height[frame.field_number];
1214 if (this_width != width || this_height != height) {
1215 // Resolution changed; reuse last frame/field.
1216 frame = last_good_frame;
1217 userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
1220 assert(userdata->pixel_format == pixel_format);
1221 switch (pixel_format) {
1222 case bmusb::PixelFormat_8BitYCbCr:
1223 ycbcr_inputs[i]->set_texture_num(0, userdata->tex_y[frame.field_number]);
1224 ycbcr_inputs[i]->set_texture_num(1, userdata->tex_cbcr[frame.field_number]);
1225 ycbcr_inputs[i]->change_ycbcr_format(input_ycbcr_format);
1226 ycbcr_inputs[i]->set_width(width);
1227 ycbcr_inputs[i]->set_height(height);
1229 case bmusb::PixelFormat_8BitYCbCrPlanar:
1230 ycbcr_inputs[i]->set_texture_num(0, userdata->tex_y[frame.field_number]);
1231 ycbcr_inputs[i]->set_texture_num(1, userdata->tex_cb[frame.field_number]);
1232 ycbcr_inputs[i]->set_texture_num(2, userdata->tex_cr[frame.field_number]);
1233 // YCbCrPlanar is used for video streams, where we can have metadata from the mux.
1234 // Prefer that if there's no override. (Overrides are only available when using
1235 // video as SRT cards.)
1236 if (input_state.ycbcr_coefficients_auto[card_idx]) {
1237 ycbcr_inputs[i]->change_ycbcr_format(userdata->ycbcr_format);
1239 ycbcr_inputs[i]->change_ycbcr_format(input_ycbcr_format);
1241 ycbcr_inputs[i]->set_width(width);
1242 ycbcr_inputs[i]->set_height(height);
1244 case bmusb::PixelFormat_10BitYCbCr:
1245 ycbcr_inputs[i]->set_texture_num(0, userdata->tex_444[frame.field_number]);
1246 ycbcr_inputs[i]->change_ycbcr_format(input_ycbcr_format);
1247 ycbcr_inputs[i]->set_width(width);
1248 ycbcr_inputs[i]->set_height(height);
1250 case bmusb::PixelFormat_8BitBGRA:
1251 rgba_inputs[i]->set_texture_num(userdata->tex_rgba[frame.field_number]);
1252 rgba_inputs[i]->set_width(width);
1253 rgba_inputs[i]->set_height(height);
1259 last_good_frame = frame;
1263 BufferedFrame frame = input_state.buffered_frames[card_idx][0];
1264 CHECK(deinterlace_effect->set_int("current_field_position", frame.field_number));
1270 int call_num_channels(lua_State *L)
1272 lua_getglobal(L, "num_channels");
1274 if (lua_pcall(L, 0, 1, 0) != 0) {
1275 fprintf(stderr, "error running function `num_channels': %s\n", lua_tostring(L, -1));
1276 fprintf(stderr, "Try Nageru.set_num_channels(...) at the start of the script instead.\n");
1280 int num_channels = luaL_checknumber(L, 1);
1282 assert(lua_gettop(L) == 0);
1283 return num_channels;
1288 int Nageru_set_channel_name(lua_State *L)
1290 // NOTE: m is already locked.
1291 Theme *theme = get_theme_updata(L);
1292 unsigned channel = luaL_checknumber(L, 1);
1293 const string text = checkstdstring(L, 2);
1294 theme->channel_names[channel] = text;
1299 int Nageru_set_num_channels(lua_State *L)
1301 // NOTE: m is already locked.
1302 Theme *theme = get_theme_updata(L);
1303 if (theme->startup_finished) {
1304 luaL_error(L, "set_num_channels() can only be called at startup.");
1306 theme->num_channels = luaL_checknumber(L, 1);
1311 int Nageru_set_channel_signal(lua_State *L)
1313 // NOTE: m is already locked.
1314 Theme *theme = get_theme_updata(L);
1315 if (theme->startup_finished) {
1316 luaL_error(L, "set_channel_signal() can only be called at startup.");
1318 unsigned channel = luaL_checknumber(L, 1);
1319 int signal = luaL_checknumber(L, 2);
1320 theme->channel_signals[channel] = signal;
1325 int Nageru_set_supports_wb(lua_State *L)
1327 // NOTE: m is already locked.
1328 Theme *theme = get_theme_updata(L);
1329 if (theme->startup_finished) {
1330 luaL_error(L, "set_supports_wb() can only be called at startup.");
1332 unsigned channel = luaL_checknumber(L, 1);
1333 bool supports_wb = checkbool(L, 2);
1334 theme->channel_supports_wb[channel] = supports_wb;
1339 // NOTE: There's a race condition in all of the audio functions; if the mapping
1340 // is changed by the user underway, you might not be manipulating the bus you
1341 // expect. (You should not get crashes, though.) There's not all that much we
1342 // can do about it, short of locking the entire mixer while anything from the
1345 int Nageru_get_num_audio_buses(lua_State *L)
1347 if (global_audio_mixer == nullptr) {
1348 // The audio mixer isn't set up until we know how many FFmpeg inputs we have.
1349 luaL_error(L, "Audio functions can not be called before the theme is done initializing.");
1351 lua_pushinteger(L, global_audio_mixer->num_buses());
1355 int Nageru_get_audio_bus_name(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 int bus_index = luaL_checknumber(L, 1);
1362 InputMapping input_mapping = global_audio_mixer->get_input_mapping();
1363 if (bus_index < 0 || size_t(bus_index) >= input_mapping.buses.size()) {
1364 // Doesn't fix the race, but fixes other out-of-bounds.
1365 print_warning(L, "Theme called get_audio_bus_name() on nonexistent bus %d; returning nil.\n", bus_index);
1368 lua_pushstring(L, input_mapping.buses[bus_index].name.c_str());
1373 int Nageru_get_audio_bus_fader_level_db(lua_State *L)
1375 if (global_audio_mixer == nullptr) {
1376 // The audio mixer isn't set up until we know how many FFmpeg inputs we have.
1377 luaL_error(L, "Audio functions can not be called before the theme is done initializing.");
1380 int bus_index = luaL_checknumber(L, 1);
1381 if (bus_index < 0 || size_t(bus_index) >= global_audio_mixer->num_buses()) {
1382 // Doesn't fix the race, but fixes other out-of-bounds.
1383 print_warning(L, "Theme called get_audio_bus_fader_level_db() on nonexistent bus %d; returning 0.0.\n", bus_index);
1384 lua_pushnumber(L, 0.0);
1386 lua_pushnumber(L, global_audio_mixer->get_fader_volume(bus_index));
1391 int Nageru_set_audio_bus_fader_level_db(lua_State *L)
1393 if (global_audio_mixer == nullptr || global_mainwindow == nullptr) {
1394 // The audio mixer isn't set up until we know how many FFmpeg inputs we have.
1395 luaL_error(L, "Audio functions can not be called before the theme is done initializing.");
1398 int bus_index = luaL_checknumber(L, 1);
1399 if (bus_index < 0 || size_t(bus_index) >= global_audio_mixer->num_buses()) {
1400 // Doesn't fix the race, but fixes other out-of-bounds.
1401 print_warning(L, "Theme called set_audio_bus_fader_level_db() on nonexistent bus %d; ignoring.\n", bus_index);
1404 double level_db = luaL_checknumber(L, 2);
1406 // Go through the UI, so that it gets updated.
1407 global_mainwindow->set_fader_absolute(bus_index, level_db);
1411 int Nageru_get_audio_bus_mute(lua_State *L)
1413 if (global_audio_mixer == nullptr) {
1414 // The audio mixer isn't set up until we know how many FFmpeg inputs we have.
1415 luaL_error(L, "Audio functions can not be called before the theme is done initializing.");
1418 int bus_index = luaL_checknumber(L, 1);
1419 if (bus_index < 0 || size_t(bus_index) >= global_audio_mixer->num_buses()) {
1420 // Doesn't fix the race, but fixes other out-of-bounds.
1421 print_warning(L, "Theme called get_audio_bus_mute() on nonexistent bus %d; returning false.\n", bus_index);
1422 lua_pushboolean(L, false);
1424 lua_pushboolean(L, global_audio_mixer->get_mute(bus_index));
1429 int Nageru_set_audio_bus_mute(lua_State *L)
1431 if (global_audio_mixer == nullptr || global_mainwindow == nullptr) {
1432 // The audio mixer isn't set up until we know how many FFmpeg inputs we have.
1433 luaL_error(L, "Audio functions can not be called before the theme is done initializing.");
1436 int bus_index = luaL_checknumber(L, 1);
1437 if (bus_index < 0 || size_t(bus_index) >= global_audio_mixer->num_buses()) {
1438 // Doesn't fix the race, but fixes other out-of-bounds.
1439 print_warning(L, "Theme called set_audio_bus_mute() on nonexistent bus %d; ignoring.\n", bus_index);
1442 bool mute = checkbool(L, 2);
1444 // Go through the UI, so that it gets updated.
1445 if (mute != global_audio_mixer->get_mute(bus_index)) {
1446 global_mainwindow->toggle_mute(bus_index);
1451 int Nageru_get_audio_bus_eq_level_db(lua_State *L)
1453 if (global_audio_mixer == nullptr) {
1454 // The audio mixer isn't set up until we know how many FFmpeg inputs we have.
1455 luaL_error(L, "Audio functions can not be called before the theme is done initializing.");
1458 int bus_index = luaL_checknumber(L, 1);
1459 int band = luaL_checknumber(L, 2);
1460 if (bus_index < 0 || size_t(bus_index) >= global_audio_mixer->num_buses()) {
1461 // Doesn't fix the race, but fixes other out-of-bounds.
1462 print_warning(L, "Theme called get_audio_bus_eq_level_db() on nonexistent bus %d; returning 0.0.\n", bus_index);
1463 lua_pushnumber(L, 0.0);
1464 } else if (band != EQ_BAND_BASS && band != EQ_BAND_MID && band != EQ_BAND_TREBLE) {
1465 print_warning(L, "Theme called get_audio_bus_eq_level_db() on nonexistent band; returning 0.0.\n", bus_index);
1466 lua_pushnumber(L, 0.0);
1468 lua_pushnumber(L, global_audio_mixer->get_eq(bus_index, EQBand(band)));
1473 int Nageru_set_audio_bus_eq_level_db(lua_State *L)
1475 if (global_audio_mixer == nullptr || global_mainwindow == nullptr) {
1476 // The audio mixer isn't set up until we know how many FFmpeg inputs we have.
1477 luaL_error(L, "Audio functions can not be called before the theme is done initializing.");
1480 int bus_index = luaL_checknumber(L, 1);
1481 int band = luaL_checknumber(L, 2);
1482 if (bus_index < 0 || size_t(bus_index) >= global_audio_mixer->num_buses()) {
1483 // Doesn't fix the race, but fixes other out-of-bounds.
1484 print_warning(L, "Theme called set_audio_bus_eq_level_db() on nonexistent bus %d; ignoring.\n", bus_index);
1486 } else if (band != EQ_BAND_BASS && band != EQ_BAND_MID && band != EQ_BAND_TREBLE) {
1487 print_warning(L, "Theme called set_audio_bus_eq_level_db() on nonexistent band; returning 0.0.\n", bus_index);
1490 double level_db = luaL_checknumber(L, 3);
1492 // Go through the UI, so that it gets updated.
1493 global_mainwindow->set_eq_absolute(bus_index, EQBand(band), level_db);
1497 Theme::Theme(const string &filename, const vector<string> &search_dirs, ResourcePool *resource_pool)
1498 : resource_pool(resource_pool), signal_to_card_mapping(global_flags.default_stream_mapping)
1501 channel_names[0] = "Live";
1502 channel_names[1] = "Preview";
1504 L = luaL_newstate();
1507 // Search through all directories until we find a file that will load
1508 // (as in, does not return LUA_ERRFILE); then run it. We store load errors
1509 // from all the attempts, and show them once we know we can't find any of them.
1511 vector<string> errors;
1512 bool success = false;
1514 vector<string> real_search_dirs;
1515 if (!filename.empty() && filename[0] == '/') {
1516 real_search_dirs.push_back("");
1518 real_search_dirs = search_dirs;
1523 for (const string &dir : real_search_dirs) {
1527 path = dir + "/" + filename;
1529 int err = luaL_loadfile(L, path.c_str());
1531 // Save the theme for when we're actually going to run it
1532 // (we need to set up the right environment below first,
1533 // and we couldn't do that before, because we didn't know the
1534 // path to put in Nageru.THEME_PATH).
1535 theme_code_ref = luaL_ref(L, LUA_REGISTRYINDEX);
1536 assert(lua_gettop(L) == 0);
1541 errors.push_back(lua_tostring(L, -1));
1543 if (err != LUA_ERRFILE) {
1544 // The file actually loaded, but failed to parse somehow. Abort; don't try the next one.
1550 for (const string &error : errors) {
1551 fprintf(stderr, "%s\n", error.c_str());
1555 assert(lua_gettop(L) == 0);
1557 // Make sure the path exposed to the theme (as Nageru.THEME_PATH;
1558 // can be useful for locating files when talking to CEF) is absolute.
1559 // In a sense, it would be nice if realpath() had a mode not to
1560 // resolve symlinks, but it doesn't, so we only call it if we don't
1561 // already have an absolute path (which may leave ../ elements etc.).
1562 if (path[0] == '/') {
1565 char *absolute_theme_path = realpath(path.c_str(), nullptr);
1566 theme_path = absolute_theme_path;
1567 free(absolute_theme_path);
1570 // Set up the API we provide.
1572 register_class("Scene", Scene_funcs);
1573 register_class("Block", Block_funcs);
1574 register_class("EffectBlueprint", EffectBlueprint_funcs);
1575 register_class("EffectChain", EffectChain_funcs);
1576 register_class("LiveInputWrapper", LiveInputWrapper_funcs);
1577 register_class("ImageInput", ImageInput_funcs);
1578 register_class("VideoInput", VideoInput_funcs);
1579 register_class("HTMLInput", HTMLInput_funcs);
1580 register_class("IdentityEffect", IdentityEffect_funcs, IDENTITY_EFFECT);
1581 register_class("WhiteBalanceEffect", WhiteBalanceEffect_funcs, WHITE_BALANCE_EFFECT);
1582 register_class("ResampleEffect", ResampleEffect_funcs, RESAMPLE_EFFECT);
1583 register_class("PaddingEffect", PaddingEffect_funcs, PADDING_EFFECT);
1584 register_class("IntegralPaddingEffect", IntegralPaddingEffect_funcs, INTEGRAL_PADDING_EFFECT);
1585 register_class("OverlayEffect", OverlayEffect_funcs, OVERLAY_EFFECT);
1586 register_class("ResizeEffect", ResizeEffect_funcs, RESIZE_EFFECT);
1587 register_class("MultiplyEffect", MultiplyEffect_funcs, MULTIPLY_EFFECT);
1588 register_class("MixEffect", MixEffect_funcs, MIX_EFFECT);
1589 register_class("BlurEffect", BlurEffect_funcs, BLUR_EFFECT);
1590 register_class("UnsharpMaskEffect", UnsharpMaskEffect_funcs, UNSHARP_MASK_EFFECT);
1591 register_class("LiftGammaGainEffect", LiftGammaGainEffect_funcs, LIFT_GAMMA_GAIN_EFFECT);
1592 register_class("InputStateInfo", InputStateInfo_funcs);
1593 register_class("ThemeMenu", ThemeMenu_funcs);
1595 // Now actually run the theme to get everything set up.
1596 lua_rawgeti(L, LUA_REGISTRYINDEX, theme_code_ref);
1597 luaL_unref(L, LUA_REGISTRYINDEX, theme_code_ref);
1598 if (lua_pcall(L, 0, 0, 0)) {
1599 fprintf(stderr, "Error when running %s: %s\n", path.c_str(), lua_tostring(L, -1));
1602 assert(lua_gettop(L) == 0);
1604 if (num_channels == -1) {
1605 // Ask it for the number of channels.
1606 num_channels = call_num_channels(L);
1608 startup_finished = true;
1617 void Theme::register_globals()
1619 // Set Nageru.VIDEO_FORMAT_BGRA = bmusb::PixelFormat_8BitBGRA, etc.
1620 const vector<pair<string, int>> num_constants = {
1621 { "VIDEO_FORMAT_BGRA", bmusb::PixelFormat_8BitBGRA },
1622 { "VIDEO_FORMAT_YCBCR", bmusb::PixelFormat_8BitYCbCrPlanar },
1623 { "CHECKABLE", MenuEntry::CHECKABLE },
1624 { "CHECKED", MenuEntry::CHECKED },
1625 { "EQ_BAND_BASS", EQ_BAND_BASS },
1626 { "EQ_BAND_MID", EQ_BAND_MID },
1627 { "EQ_BAND_TREBLE", EQ_BAND_TREBLE },
1629 const vector<pair<string, string>> str_constants = {
1630 { "THEME_PATH", theme_path },
1633 lua_newtable(L); // t = {}
1635 for (const pair<string, int> &constant : num_constants) {
1636 lua_pushstring(L, constant.first.c_str());
1637 lua_pushinteger(L, constant.second);
1638 lua_settable(L, 1); // t[key] = value
1640 for (const pair<string, string> &constant : str_constants) {
1641 lua_pushstring(L, constant.first.c_str());
1642 lua_pushstring(L, constant.second.c_str());
1643 lua_settable(L, 1); // t[key] = value
1646 const luaL_Reg Nageru_funcs[] = {
1647 // Channel information.
1648 { "set_channel_name", Nageru_set_channel_name },
1649 { "set_num_channels", Nageru_set_num_channels },
1650 { "set_channel_signal", Nageru_set_channel_signal },
1651 { "set_supports_wb", Nageru_set_supports_wb },
1654 { "get_num_audio_buses", Nageru_get_num_audio_buses },
1655 { "get_audio_bus_name", Nageru_get_audio_bus_name },
1656 { "get_audio_bus_fader_level_db", Nageru_get_audio_bus_fader_level_db },
1657 { "set_audio_bus_fader_level_db", Nageru_set_audio_bus_fader_level_db },
1658 { "get_audio_bus_eq_level_db", Nageru_get_audio_bus_eq_level_db },
1659 { "set_audio_bus_eq_level_db", Nageru_set_audio_bus_eq_level_db },
1660 { "get_audio_bus_mute", Nageru_get_audio_bus_mute },
1661 { "set_audio_bus_mute", Nageru_set_audio_bus_mute },
1663 { nullptr, nullptr }
1665 lua_pushlightuserdata(L, this);
1666 luaL_setfuncs(L, Nageru_funcs, 1); // for (name,f in funcs) { mt[name] = f, with upvalue {theme} }
1668 lua_setglobal(L, "Nageru"); // Nageru = t
1669 assert(lua_gettop(L) == 0);
1672 void Theme::register_class(const char *class_name, const luaL_Reg *funcs, EffectType effect_type)
1674 assert(lua_gettop(L) == 0);
1675 luaL_newmetatable(L, class_name); // mt = {}
1676 lua_pushlightuserdata(L, this);
1677 luaL_setfuncs(L, funcs, 1); // for (name,f in funcs) { mt[name] = f, with upvalue {theme} }
1678 lua_pushvalue(L, -1);
1679 lua_setfield(L, -2, "__index"); // mt.__index = mt
1680 if (effect_type != NO_EFFECT_TYPE) {
1681 lua_pushnumber(L, effect_type);
1682 lua_setfield(L, -2, "__effect_type_id"); // mt.__effect_type_id = effect_type
1684 lua_setglobal(L, class_name); // ClassName = mt
1685 assert(lua_gettop(L) == 0);
1688 Theme::Chain Theme::get_chain_from_effect_chain(EffectChain *effect_chain, unsigned num, const InputState &input_state)
1690 if (!lua_isfunction(L, -1)) {
1691 fprintf(stderr, "Argument #-1 should be a function\n");
1694 lua_pushvalue(L, -1);
1695 shared_ptr<LuaRefWithDeleter> funcref(new LuaRefWithDeleter(&m, L, luaL_ref(L, LUA_REGISTRYINDEX)));
1699 chain.chain = effect_chain;
1700 chain.setup_chain = [this, funcref, input_state, effect_chain]{
1701 lock_guard<mutex> lock(m);
1703 assert(this->input_state == nullptr);
1704 this->input_state = &input_state;
1706 // Set up state, including connecting signals.
1707 lua_rawgeti(L, LUA_REGISTRYINDEX, funcref->get());
1708 if (lua_pcall(L, 0, 0, 0) != 0) {
1709 fprintf(stderr, "error running chain setup callback: %s\n", lua_tostring(L, -1));
1712 assert(lua_gettop(L) == 0);
1714 // The theme can't (or at least shouldn't!) call connect_signal() on
1715 // each FFmpeg or CEF input, so we'll do it here.
1716 if (video_signal_connections.count(effect_chain)) {
1717 for (const VideoSignalConnection &conn : video_signal_connections[effect_chain]) {
1718 conn.wrapper->connect_card(conn.source->get_card_index(), input_state);
1722 if (html_signal_connections.count(effect_chain)) {
1723 for (const CEFSignalConnection &conn : html_signal_connections[effect_chain]) {
1724 conn.wrapper->connect_card(conn.source->get_card_index(), input_state);
1729 this->input_state = nullptr;
1734 Theme::Chain Theme::get_chain(unsigned num, float t, unsigned width, unsigned height, const InputState &input_state)
1736 const char *func_name = "get_scene"; // For error reporting.
1739 lock_guard<mutex> lock(m);
1740 assert(lua_gettop(L) == 0);
1741 lua_getglobal(L, "get_scene"); /* function to be called */
1742 if (lua_isnil(L, -1)) {
1743 // Try the pre-1.9.0 name for compatibility.
1745 lua_getglobal(L, "get_chain");
1746 func_name = "get_chain";
1748 lua_pushnumber(L, num);
1749 lua_pushnumber(L, t);
1750 lua_pushnumber(L, width);
1751 lua_pushnumber(L, height);
1752 wrap_lua_object<InputStateInfo>(L, "InputStateInfo", input_state);
1754 if (lua_pcall(L, 5, LUA_MULTRET, 0) != 0) {
1755 fprintf(stderr, "error running function “%s”: %s\n", func_name, lua_tostring(L, -1));
1759 if (luaL_testudata(L, -1, "Scene") != nullptr) {
1760 if (lua_gettop(L) != 1) {
1761 luaL_error(L, "%s() for chain number %d returned an Scene, but also other items", func_name);
1763 Scene *auto_effect_chain = (Scene *)luaL_testudata(L, -1, "Scene");
1764 auto chain_and_setup = auto_effect_chain->get_chain(this, L, num, input_state);
1765 chain.chain = chain_and_setup.first;
1766 chain.setup_chain = move(chain_and_setup.second);
1767 } else if (luaL_testudata(L, -2, "EffectChain") != nullptr) {
1768 // Old-style (pre-Nageru 1.9.0) return of a single chain and prepare function.
1769 if (lua_gettop(L) != 2) {
1770 luaL_error(L, "%s() for chain number %d returned an EffectChain, but needs to also return a prepare function (or use Scene)", func_name);
1772 EffectChain *effect_chain = (EffectChain *)luaL_testudata(L, -2, "EffectChain");
1773 chain = get_chain_from_effect_chain(effect_chain, num, input_state);
1775 luaL_error(L, "%s() for chain number %d did not return an EffectChain or Scene\n", func_name, num);
1777 assert(lua_gettop(L) == 0);
1779 // TODO: Can we do better, e.g. by running setup_chain() and seeing what it references?
1780 // Actually, setup_chain does maybe hold all the references we need now anyway?
1781 chain.input_frames.reserve(MAX_VIDEO_CARDS * FRAME_HISTORY_LENGTH);
1782 for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) {
1783 for (unsigned frame_num = 0; frame_num < FRAME_HISTORY_LENGTH; ++frame_num) {
1784 chain.input_frames.push_back(input_state.buffered_frames[card_index][frame_num].frame);
1791 string Theme::get_channel_name(unsigned channel)
1793 lock_guard<mutex> lock(m);
1795 // We never ask the legacy channel_name() about live and preview.
1796 // The defaults are set in our constructor.
1797 if (channel == 0 || channel == 1) {
1798 return channel_names[channel];
1801 lua_getglobal(L, "channel_name");
1802 if (lua_isnil(L, -1)) {
1804 if (channel_names.count(channel)) {
1805 return channel_names[channel];
1807 return "(no title)";
1811 lua_pushnumber(L, channel);
1812 if (lua_pcall(L, 1, 1, 0) != 0) {
1813 fprintf(stderr, "error running function `channel_name': %s\n", lua_tostring(L, -1));
1816 const char *ret = lua_tostring(L, -1);
1817 if (ret == nullptr) {
1818 fprintf(stderr, "function `channel_name' returned nil for channel %d\n", channel);
1819 fprintf(stderr, "Try Nageru.set_channel_name(channel, name) at the start of the script instead.\n");
1823 string retstr = ret;
1825 assert(lua_gettop(L) == 0);
1829 int Theme::map_channel_to_signal(unsigned channel)
1831 lock_guard<mutex> lock(m);
1832 lua_getglobal(L, "channel_signal");
1833 if (lua_isnil(L, -1)) {
1835 if (channel_signals.count(channel)) {
1836 return channel_signals[channel];
1842 lua_pushnumber(L, channel);
1843 if (lua_pcall(L, 1, 1, 0) != 0) {
1844 fprintf(stderr, "error running function `channel_signal': %s\n", lua_tostring(L, -1));
1845 fprintf(stderr, "Try Nageru.set_channel_signal(channel, signal) at the start of the script instead.\n");
1849 int ret = luaL_checknumber(L, 1);
1851 assert(lua_gettop(L) == 0);
1855 std::string Theme::get_channel_color(unsigned channel)
1857 lock_guard<mutex> lock(m);
1858 lua_getglobal(L, "channel_color");
1859 lua_pushnumber(L, channel);
1860 if (lua_pcall(L, 1, 1, 0) != 0) {
1861 fprintf(stderr, "error running function `channel_color': %s\n", lua_tostring(L, -1));
1865 const char *ret = lua_tostring(L, -1);
1866 if (ret == nullptr) {
1867 fprintf(stderr, "function `channel_color' returned nil for channel %d\n", channel);
1871 string retstr = ret;
1873 assert(lua_gettop(L) == 0);
1877 bool Theme::get_supports_set_wb(unsigned channel)
1879 lock_guard<mutex> lock(m);
1880 lua_getglobal(L, "supports_set_wb");
1881 if (lua_isnil(L, -1)) {
1883 if (channel_supports_wb.count(channel)) {
1884 return channel_supports_wb[channel];
1890 lua_pushnumber(L, channel);
1891 if (lua_pcall(L, 1, 1, 0) != 0) {
1892 fprintf(stderr, "error running function `supports_set_wb': %s\n", lua_tostring(L, -1));
1893 fprintf(stderr, "Try Nageru.set_supports_wb(channel, bool) at the start of the script instead.\n");
1897 bool ret = checkbool(L, -1);
1899 assert(lua_gettop(L) == 0);
1903 void Theme::set_wb(unsigned channel, float r, float g, float b)
1905 int signal = map_channel_to_signal(channel);
1907 lock_guard<mutex> lock(m);
1909 int card_idx = map_signal_to_card(signal);
1910 white_balance_for_card[card_idx] = RGBTriplet{ r, g, b };
1913 call_lua_wb_callback(channel, r, g, b);
1916 void Theme::set_wb_for_card(int card_idx, float r, float g, float b)
1918 lock_guard<mutex> lock(m);
1919 white_balance_for_card[card_idx] = RGBTriplet{ r, g, b };
1921 for (const auto &channel_and_signal : channel_signals) {
1922 if (map_signal_to_card(channel_and_signal.second) == card_idx) {
1923 call_lua_wb_callback(channel_and_signal.first, r, g, b);
1928 void Theme::call_lua_wb_callback(unsigned channel, float r, float g, float b)
1930 lua_getglobal(L, "set_wb");
1931 if (lua_isnil(L, -1)) {
1932 // The function doesn't exist, to just ignore. We've stored the white balance,
1933 // and most likely, it will be picked up by auto white balance instead.
1937 lua_pushnumber(L, channel);
1938 lua_pushnumber(L, r);
1939 lua_pushnumber(L, g);
1940 lua_pushnumber(L, b);
1941 if (lua_pcall(L, 4, 0, 0) != 0) {
1942 fprintf(stderr, "error running function `set_wb': %s\n", lua_tostring(L, -1));
1946 assert(lua_gettop(L) == 0);
1949 RGBTriplet Theme::get_white_balance_for_card(int card_idx)
1951 if (white_balance_for_card.count(card_idx)) {
1952 return white_balance_for_card[card_idx];
1954 return RGBTriplet{ 1.0, 1.0, 1.0 };
1958 vector<string> Theme::get_transition_names(float t)
1960 lock_guard<mutex> lock(m);
1961 lua_getglobal(L, "get_transitions");
1962 lua_pushnumber(L, t);
1963 if (lua_pcall(L, 1, 1, 0) != 0) {
1964 fprintf(stderr, "error running function `get_transitions': %s\n", lua_tostring(L, -1));
1970 while (lua_next(L, -2) != 0) {
1971 ret.push_back(lua_tostring(L, -1));
1975 assert(lua_gettop(L) == 0);
1979 int Theme::map_signal_to_card(int signal_num)
1981 // Negative numbers map to raw signals.
1982 if (signal_num < 0) {
1983 return -1 - signal_num;
1986 lock_guard<mutex> lock(map_m);
1987 if (signal_to_card_mapping.count(signal_num)) {
1988 return signal_to_card_mapping[signal_num];
1992 if (global_flags.output_card != -1) {
1993 // Try to exclude the output card from the default card_index.
1994 card_index = signal_num % (global_flags.max_num_cards - 1);
1995 if (card_index >= global_flags.output_card) {
1998 if (signal_num >= int(global_flags.max_num_cards - 1)) {
1999 print_warning(L, "Theme asked for input %d, but we only have %u input card(s) (card %d is busy with output).\n",
2000 signal_num, global_flags.max_num_cards - 1, global_flags.output_card);
2001 fprintf(stderr, "Mapping to card %d instead.\n", card_index);
2004 card_index = signal_num % global_flags.max_num_cards;
2005 if (signal_num >= int(global_flags.max_num_cards)) {
2006 print_warning(L, "Theme asked for input %d, but we only have %u card(s).\n", signal_num, global_flags.max_num_cards);
2007 fprintf(stderr, "Mapping to card %d instead.\n", card_index);
2010 global_mixer->force_card_active(card_index);
2011 signal_to_card_mapping[signal_num] = card_index;
2015 void Theme::set_signal_mapping(int signal_num, int card_idx)
2017 lock_guard<mutex> lock(map_m);
2018 assert(card_idx < MAX_VIDEO_CARDS);
2019 signal_to_card_mapping[signal_num] = card_idx;
2022 void Theme::transition_clicked(int transition_num, float t)
2024 lock_guard<mutex> lock(m);
2025 lua_getglobal(L, "transition_clicked");
2026 lua_pushnumber(L, transition_num);
2027 lua_pushnumber(L, t);
2029 if (lua_pcall(L, 2, 0, 0) != 0) {
2030 fprintf(stderr, "error running function `transition_clicked': %s\n", lua_tostring(L, -1));
2033 assert(lua_gettop(L) == 0);
2036 void Theme::channel_clicked(int preview_num)
2038 lock_guard<mutex> lock(m);
2039 lua_getglobal(L, "channel_clicked");
2040 lua_pushnumber(L, preview_num);
2042 if (lua_pcall(L, 1, 0, 0) != 0) {
2043 fprintf(stderr, "error running function `channel_clicked': %s\n", lua_tostring(L, -1));
2046 assert(lua_gettop(L) == 0);
2050 void destroy(T &ref)
2055 Theme::MenuEntry::~MenuEntry()
2060 luaL_unref(entry.L, LUA_REGISTRYINDEX, entry.lua_ref);
2066 vector<unique_ptr<Theme::MenuEntry>> create_recursive_theme_menu(lua_State *L);
2068 unique_ptr<Theme::MenuEntry> create_theme_menu_entry(lua_State *L, int index)
2070 unique_ptr<Theme::MenuEntry> entry;
2072 lua_rawgeti(L, index, 1);
2073 const string text = checkstdstring(L, -1);
2077 if (lua_objlen(L, -1) > 2) {
2078 lua_rawgeti(L, -1, 3);
2079 flags = luaL_checknumber(L, -1);
2083 lua_rawgeti(L, index, 2);
2084 if (lua_istable(L, -1)) {
2085 vector<unique_ptr<Theme::MenuEntry>> submenu = create_recursive_theme_menu(L);
2086 entry.reset(new Theme::MenuEntry{ text, move(submenu) });
2089 luaL_checktype(L, -1, LUA_TFUNCTION);
2090 int ref = luaL_ref(L, LUA_REGISTRYINDEX);
2091 entry.reset(new Theme::MenuEntry{ text, L, ref, flags });
2096 vector<unique_ptr<Theme::MenuEntry>> create_recursive_theme_menu(lua_State *L)
2098 vector<unique_ptr<Theme::MenuEntry>> menu;
2099 size_t num_elements = lua_objlen(L, -1);
2100 for (size_t i = 1; i <= num_elements; ++i) {
2101 lua_rawgeti(L, -1, i);
2102 menu.emplace_back(create_theme_menu_entry(L, -1));
2110 int Theme::set_theme_menu(lua_State *L)
2114 vector<unique_ptr<MenuEntry>> root_menu;
2115 int num_elements = lua_gettop(L);
2116 for (int i = 1; i <= num_elements; ++i) {
2117 root_menu.emplace_back(create_theme_menu_entry(L, i));
2119 theme_menu.reset(new MenuEntry("", move(root_menu)));
2121 lua_pop(L, num_elements);
2122 assert(lua_gettop(L) == 0);
2124 if (theme_menu_callback != nullptr) {
2125 theme_menu_callback();
2131 void Theme::theme_menu_entry_clicked(int lua_ref)
2133 lock_guard<mutex> lock(m);
2134 lua_rawgeti(L, LUA_REGISTRYINDEX, lua_ref);
2135 if (lua_pcall(L, 0, 0, 0) != 0) {
2136 fprintf(stderr, "error running menu callback: %s\n", lua_tostring(L, -1));
2141 string Theme::format_status_line(const string &disk_space_left_text, double file_length_seconds)
2143 lock_guard<mutex> lock(m);
2144 lua_getglobal(L, "format_status_line");
2145 if (lua_isnil(L, -1)) {
2147 return disk_space_left_text;
2150 lua_pushstring(L, disk_space_left_text.c_str());
2151 lua_pushnumber(L, file_length_seconds);
2152 if (lua_pcall(L, 2, 1, 0) != 0) {
2153 fprintf(stderr, "error running function format_status_line(): %s\n", lua_tostring(L, -1));
2156 string text = checkstdstring(L, 1);
2158 assert(lua_gettop(L) == 0);
2162 void Theme::remove_card(unsigned card_index)
2164 lock_guard<mutex> lock(map_m);
2165 for (auto it = signal_to_card_mapping.begin(); it != signal_to_card_mapping.end(); ) {
2166 if (it->second == int(card_index)) {
2167 it = signal_to_card_mapping.erase(it);