4 #include <bmusb/bmusb.h>
8 #include <movit/deinterlace_effect.h>
9 #include <movit/effect.h>
10 #include <movit/effect_chain.h>
11 #include <movit/image_format.h>
12 #include <movit/input.h>
13 #include <movit/lift_gamma_gain_effect.h>
14 #include <movit/mix_effect.h>
15 #include <movit/multiply_effect.h>
16 #include <movit/overlay_effect.h>
17 #include <movit/padding_effect.h>
18 #include <movit/resample_effect.h>
19 #include <movit/resize_effect.h>
20 #include <movit/util.h>
21 #include <movit/white_balance_effect.h>
22 #include <movit/ycbcr.h>
23 #include <movit/ycbcr_input.h>
33 #include "cef_capture.h"
35 #include "ffmpeg_capture.h"
37 #include "image_input.h"
38 #include "input_state.h"
39 #include "pbo_frame_allocator.h"
48 using namespace movit;
50 extern Mixer *global_mixer;
52 Theme *get_theme_updata(lua_State* L)
54 luaL_checktype(L, lua_upvalueindex(1), LUA_TLIGHTUSERDATA);
55 return (Theme *)lua_touserdata(L, lua_upvalueindex(1));
58 int ThemeMenu_set(lua_State *L)
60 Theme *theme = get_theme_updata(L);
61 return theme->set_theme_menu(L);
66 // Contains basically the same data as InputState, but does not hold on to
67 // a reference to the frames. This is important so that we can release them
68 // without having to wait for Lua's GC.
69 struct InputStateInfo {
70 InputStateInfo(const InputState& input_state);
72 unsigned last_width[MAX_VIDEO_CARDS], last_height[MAX_VIDEO_CARDS];
73 bool last_interlaced[MAX_VIDEO_CARDS], last_has_signal[MAX_VIDEO_CARDS], last_is_connected[MAX_VIDEO_CARDS];
74 unsigned last_frame_rate_nom[MAX_VIDEO_CARDS], last_frame_rate_den[MAX_VIDEO_CARDS];
77 InputStateInfo::InputStateInfo(const InputState &input_state)
79 for (unsigned signal_num = 0; signal_num < MAX_VIDEO_CARDS; ++signal_num) {
80 BufferedFrame frame = input_state.buffered_frames[signal_num][0];
81 if (frame.frame == nullptr) {
82 last_width[signal_num] = last_height[signal_num] = 0;
83 last_interlaced[signal_num] = false;
84 last_has_signal[signal_num] = false;
85 last_is_connected[signal_num] = false;
88 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
89 last_width[signal_num] = userdata->last_width[frame.field_number];
90 last_height[signal_num] = userdata->last_height[frame.field_number];
91 last_interlaced[signal_num] = userdata->last_interlaced;
92 last_has_signal[signal_num] = userdata->last_has_signal;
93 last_is_connected[signal_num] = userdata->last_is_connected;
94 last_frame_rate_nom[signal_num] = userdata->last_frame_rate_nom;
95 last_frame_rate_den[signal_num] = userdata->last_frame_rate_den;
99 class LuaRefWithDeleter {
101 LuaRefWithDeleter(mutex *m, lua_State *L, int ref) : m(m), L(L), ref(ref) {}
102 ~LuaRefWithDeleter() {
103 unique_lock<mutex> lock(*m);
104 luaL_unref(L, LUA_REGISTRYINDEX, ref);
106 int get() const { return ref; }
109 LuaRefWithDeleter(const LuaRefWithDeleter &) = delete;
116 template<class T, class... Args>
117 int wrap_lua_object(lua_State* L, const char *class_name, Args&&... args)
119 // Construct the C++ object and put it on the stack.
120 void *mem = lua_newuserdata(L, sizeof(T));
121 new(mem) T(forward<Args>(args)...);
123 // Look up the metatable named <class_name>, and set it on the new object.
124 luaL_getmetatable(L, class_name);
125 lua_setmetatable(L, -2);
130 // Like wrap_lua_object, but the object is not owned by Lua; ie. it's not freed
131 // by Lua GC. This is typically the case for Effects, which are owned by EffectChain
132 // and expected to be destructed by it. The object will be of type T** instead of T*
133 // when exposed to Lua.
135 // Note that we currently leak if you allocate an Effect in this way and never call
136 // add_effect. We should see if there's a way to e.g. set __gc on it at construction time
137 // and then release that once add_effect() takes ownership.
138 template<class T, class... Args>
139 int wrap_lua_object_nonowned(lua_State* L, const char *class_name, Args&&... args)
141 // Construct the pointer ot the C++ object and put it on the stack.
142 T **obj = (T **)lua_newuserdata(L, sizeof(T *));
143 *obj = new T(forward<Args>(args)...);
145 // Look up the metatable named <class_name>, and set it on the new object.
146 luaL_getmetatable(L, class_name);
147 lua_setmetatable(L, -2);
152 Effect *get_effect(lua_State *L, int idx)
154 if (luaL_testudata(L, idx, "WhiteBalanceEffect") ||
155 luaL_testudata(L, idx, "ResampleEffect") ||
156 luaL_testudata(L, idx, "PaddingEffect") ||
157 luaL_testudata(L, idx, "IntegralPaddingEffect") ||
158 luaL_testudata(L, idx, "OverlayEffect") ||
159 luaL_testudata(L, idx, "ResizeEffect") ||
160 luaL_testudata(L, idx, "MultiplyEffect") ||
161 luaL_testudata(L, idx, "MixEffect") ||
162 luaL_testudata(L, idx, "LiftGammaGainEffect") ||
163 luaL_testudata(L, idx, "ImageInput")) {
164 return *(Effect **)lua_touserdata(L, idx);
166 luaL_error(L, "Error: Index #%d was not an Effect type\n", idx);
170 InputStateInfo *get_input_state_info(lua_State *L, int idx)
172 if (luaL_testudata(L, idx, "InputStateInfo")) {
173 return (InputStateInfo *)lua_touserdata(L, idx);
175 luaL_error(L, "Error: Index #%d was not InputStateInfo\n", idx);
179 bool checkbool(lua_State* L, int idx)
181 luaL_checktype(L, idx, LUA_TBOOLEAN);
182 return lua_toboolean(L, idx);
185 string checkstdstring(lua_State *L, int index)
188 const char* cstr = lua_tolstring(L, index, &len);
189 return string(cstr, len);
192 int EffectChain_new(lua_State* L)
194 assert(lua_gettop(L) == 2);
195 Theme *theme = get_theme_updata(L);
196 int aspect_w = luaL_checknumber(L, 1);
197 int aspect_h = luaL_checknumber(L, 2);
199 return wrap_lua_object<EffectChain>(L, "EffectChain", aspect_w, aspect_h, theme->get_resource_pool());
202 int EffectChain_gc(lua_State* L)
204 assert(lua_gettop(L) == 1);
205 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
206 chain->~EffectChain();
210 int EffectChain_add_live_input(lua_State* L)
212 assert(lua_gettop(L) == 3);
213 Theme *theme = get_theme_updata(L);
214 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
215 bool override_bounce = checkbool(L, 2);
216 bool deinterlace = checkbool(L, 3);
217 bmusb::PixelFormat pixel_format = global_flags.ten_bit_input ? bmusb::PixelFormat_10BitYCbCr : bmusb::PixelFormat_8BitYCbCr;
219 // Needs to be nonowned to match add_video_input (see below).
220 return wrap_lua_object_nonowned<LiveInputWrapper>(L, "LiveInputWrapper", theme, chain, pixel_format, override_bounce, deinterlace, /*user_connectable=*/true);
223 int EffectChain_add_video_input(lua_State* L)
225 assert(lua_gettop(L) == 3);
226 Theme *theme = get_theme_updata(L);
227 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
228 FFmpegCapture **capture = (FFmpegCapture **)luaL_checkudata(L, 2, "VideoInput");
229 bool deinterlace = checkbool(L, 3);
231 // These need to be nonowned, so that the LiveInputWrapper still exists
232 // and can feed frames to the right EffectChain even if the Lua code
233 // doesn't care about the object anymore. (If we change this, we'd need
234 // to also unregister the signal connection on __gc.)
235 int ret = wrap_lua_object_nonowned<LiveInputWrapper>(
236 L, "LiveInputWrapper", theme, chain, (*capture)->get_current_pixel_format(),
237 /*override_bounce=*/false, deinterlace, /*user_connectable=*/false);
239 Theme *theme = get_theme_updata(L);
240 LiveInputWrapper **live_input = (LiveInputWrapper **)lua_touserdata(L, -1);
241 theme->register_video_signal_connection(chain, *live_input, *capture);
247 int EffectChain_add_html_input(lua_State* L)
249 assert(lua_gettop(L) == 2);
250 Theme *theme = get_theme_updata(L);
251 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
252 CEFCapture **capture = (CEFCapture **)luaL_checkudata(L, 2, "HTMLInput");
254 // These need to be nonowned, so that the LiveInputWrapper still exists
255 // and can feed frames to the right EffectChain even if the Lua code
256 // doesn't care about the object anymore. (If we change this, we'd need
257 // to also unregister the signal connection on __gc.)
258 int ret = wrap_lua_object_nonowned<LiveInputWrapper>(
259 L, "LiveInputWrapper", theme, chain, (*capture)->get_current_pixel_format(),
260 /*override_bounce=*/false, /*deinterlace=*/false, /*user_connectable=*/false);
262 Theme *theme = get_theme_updata(L);
263 LiveInputWrapper **live_input = (LiveInputWrapper **)lua_touserdata(L, -1);
264 theme->register_html_signal_connection(chain, *live_input, *capture);
270 int EffectChain_add_effect(lua_State* L)
272 assert(lua_gettop(L) >= 2);
273 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
275 // TODO: Better error reporting.
276 Effect *effect = get_effect(L, 2);
277 if (lua_gettop(L) == 2) {
278 if (effect->num_inputs() == 0) {
279 chain->add_input((Input *)effect);
281 chain->add_effect(effect);
284 vector<Effect *> inputs;
285 for (int idx = 3; idx <= lua_gettop(L); ++idx) {
286 if (luaL_testudata(L, idx, "LiveInputWrapper")) {
287 LiveInputWrapper **input = (LiveInputWrapper **)lua_touserdata(L, idx);
288 inputs.push_back((*input)->get_effect());
290 inputs.push_back(get_effect(L, idx));
293 chain->add_effect(effect, inputs);
296 lua_settop(L, 2); // Return the effect itself.
298 // Make sure Lua doesn't garbage-collect it away.
299 lua_pushvalue(L, -1);
300 luaL_ref(L, LUA_REGISTRYINDEX); // TODO: leak?
305 int EffectChain_finalize(lua_State* L)
307 assert(lua_gettop(L) == 2);
308 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
309 bool is_main_chain = checkbool(L, 2);
311 // Add outputs as needed.
312 // NOTE: If you change any details about the output format, you will need to
313 // also update what's given to the muxer (HTTPD::Mux constructor) and
314 // what's put in the H.264 stream (sps_rbsp()).
315 ImageFormat inout_format;
316 inout_format.color_space = COLORSPACE_REC_709;
318 // Output gamma is tricky. We should output Rec. 709 for TV, except that
319 // we expect to run with web players and others that don't really care and
320 // just output with no conversion. So that means we'll need to output sRGB,
321 // even though H.264 has no setting for that (we use “unspecified”).
322 inout_format.gamma_curve = GAMMA_sRGB;
325 YCbCrFormat output_ycbcr_format;
326 // We actually output 4:2:0 and/or 4:2:2 in the end, but chroma subsampling
327 // happens in a pass not run by Movit (see ChromaSubsampler::subsample_chroma()).
328 output_ycbcr_format.chroma_subsampling_x = 1;
329 output_ycbcr_format.chroma_subsampling_y = 1;
331 // This will be overridden if HDMI/SDI output is in force.
332 if (global_flags.ycbcr_rec709_coefficients) {
333 output_ycbcr_format.luma_coefficients = YCBCR_REC_709;
335 output_ycbcr_format.luma_coefficients = YCBCR_REC_601;
338 output_ycbcr_format.full_range = false;
339 output_ycbcr_format.num_levels = 1 << global_flags.x264_bit_depth;
341 GLenum type = global_flags.x264_bit_depth > 8 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_BYTE;
343 chain->add_ycbcr_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED, output_ycbcr_format, YCBCR_OUTPUT_SPLIT_Y_AND_CBCR, type);
345 // If we're using zerocopy video encoding (so the destination
346 // Y texture is owned by VA-API and will be unavailable for
347 // display), add a copy, where we'll only be using the Y component.
348 if (global_flags.use_zerocopy) {
349 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.
351 chain->set_dither_bits(global_flags.x264_bit_depth > 8 ? 16 : 8);
352 chain->set_output_origin(OUTPUT_ORIGIN_TOP_LEFT);
354 chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
361 int LiveInputWrapper_connect_signal(lua_State* L)
363 assert(lua_gettop(L) == 2);
364 LiveInputWrapper **input = (LiveInputWrapper **)luaL_checkudata(L, 1, "LiveInputWrapper");
365 int signal_num = luaL_checknumber(L, 2);
366 bool success = (*input)->connect_signal(signal_num);
369 lua_getstack(L, 1, &ar);
370 lua_getinfo(L, "nSl", &ar);
371 fprintf(stderr, "ERROR: %s:%d: Calling connect_signal() on a video or HTML input. Ignoring.\n",
372 ar.source, ar.currentline);
377 int ImageInput_new(lua_State* L)
379 assert(lua_gettop(L) == 1);
380 string filename = checkstdstring(L, 1);
381 return wrap_lua_object_nonowned<ImageInput>(L, "ImageInput", filename);
384 int VideoInput_new(lua_State* L)
386 assert(lua_gettop(L) == 2);
387 string filename = checkstdstring(L, 1);
388 int pixel_format = luaL_checknumber(L, 2);
389 if (pixel_format != bmusb::PixelFormat_8BitYCbCrPlanar &&
390 pixel_format != bmusb::PixelFormat_8BitBGRA) {
391 fprintf(stderr, "WARNING: Invalid enum %d used for video format, choosing Y'CbCr.\n",
393 pixel_format = bmusb::PixelFormat_8BitYCbCrPlanar;
395 int ret = wrap_lua_object_nonowned<FFmpegCapture>(L, "VideoInput", filename, global_flags.width, global_flags.height);
397 FFmpegCapture **capture = (FFmpegCapture **)lua_touserdata(L, -1);
398 (*capture)->set_pixel_format(bmusb::PixelFormat(pixel_format));
400 Theme *theme = get_theme_updata(L);
401 theme->register_video_input(*capture);
406 int VideoInput_rewind(lua_State* L)
408 assert(lua_gettop(L) == 1);
409 FFmpegCapture **video_input = (FFmpegCapture **)luaL_checkudata(L, 1, "VideoInput");
410 (*video_input)->rewind();
414 int VideoInput_disconnect(lua_State* L)
416 assert(lua_gettop(L) == 1);
417 FFmpegCapture **video_input = (FFmpegCapture **)luaL_checkudata(L, 1, "VideoInput");
418 (*video_input)->disconnect();
422 int VideoInput_change_rate(lua_State* L)
424 assert(lua_gettop(L) == 2);
425 FFmpegCapture **video_input = (FFmpegCapture **)luaL_checkudata(L, 1, "VideoInput");
426 double new_rate = luaL_checknumber(L, 2);
427 (*video_input)->change_rate(new_rate);
431 int VideoInput_get_signal_num(lua_State* L)
433 assert(lua_gettop(L) == 1);
434 FFmpegCapture **video_input = (FFmpegCapture **)luaL_checkudata(L, 1, "VideoInput");
435 lua_pushnumber(L, -1 - (*video_input)->get_card_index());
439 int HTMLInput_new(lua_State* L)
442 assert(lua_gettop(L) == 1);
443 string url = checkstdstring(L, 1);
444 int ret = wrap_lua_object_nonowned<CEFCapture>(L, "HTMLInput", url, global_flags.width, global_flags.height);
446 CEFCapture **capture = (CEFCapture **)lua_touserdata(L, -1);
447 Theme *theme = get_theme_updata(L);
448 theme->register_html_input(*capture);
452 fprintf(stderr, "This version of Nageru has been compiled without CEF support.\n");
453 fprintf(stderr, "HTMLInput is not available.\n");
459 int HTMLInput_set_url(lua_State* L)
461 assert(lua_gettop(L) == 2);
462 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
463 string new_url = checkstdstring(L, 2);
464 (*video_input)->set_url(new_url);
468 int HTMLInput_reload(lua_State* L)
470 assert(lua_gettop(L) == 1);
471 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
472 (*video_input)->reload();
476 int HTMLInput_set_max_fps(lua_State* L)
478 assert(lua_gettop(L) == 2);
479 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
480 int max_fps = lrint(luaL_checknumber(L, 2));
481 (*video_input)->set_max_fps(max_fps);
485 int HTMLInput_execute_javascript_async(lua_State* L)
487 assert(lua_gettop(L) == 2);
488 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
489 string js = checkstdstring(L, 2);
490 (*video_input)->execute_javascript_async(js);
494 int HTMLInput_resize(lua_State* L)
496 assert(lua_gettop(L) == 3);
497 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
498 unsigned width = lrint(luaL_checknumber(L, 2));
499 unsigned height = lrint(luaL_checknumber(L, 3));
500 (*video_input)->resize(width, height);
504 int HTMLInput_get_signal_num(lua_State* L)
506 assert(lua_gettop(L) == 1);
507 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
508 lua_pushnumber(L, -1 - (*video_input)->get_card_index());
513 int WhiteBalanceEffect_new(lua_State* L)
515 assert(lua_gettop(L) == 0);
516 return wrap_lua_object_nonowned<WhiteBalanceEffect>(L, "WhiteBalanceEffect");
519 int ResampleEffect_new(lua_State* L)
521 assert(lua_gettop(L) == 0);
522 return wrap_lua_object_nonowned<ResampleEffect>(L, "ResampleEffect");
525 int PaddingEffect_new(lua_State* L)
527 assert(lua_gettop(L) == 0);
528 return wrap_lua_object_nonowned<PaddingEffect>(L, "PaddingEffect");
531 int IntegralPaddingEffect_new(lua_State* L)
533 assert(lua_gettop(L) == 0);
534 return wrap_lua_object_nonowned<IntegralPaddingEffect>(L, "IntegralPaddingEffect");
537 int OverlayEffect_new(lua_State* L)
539 assert(lua_gettop(L) == 0);
540 return wrap_lua_object_nonowned<OverlayEffect>(L, "OverlayEffect");
543 int ResizeEffect_new(lua_State* L)
545 assert(lua_gettop(L) == 0);
546 return wrap_lua_object_nonowned<ResizeEffect>(L, "ResizeEffect");
549 int MultiplyEffect_new(lua_State* L)
551 assert(lua_gettop(L) == 0);
552 return wrap_lua_object_nonowned<MultiplyEffect>(L, "MultiplyEffect");
555 int MixEffect_new(lua_State* L)
557 assert(lua_gettop(L) == 0);
558 return wrap_lua_object_nonowned<MixEffect>(L, "MixEffect");
561 int LiftGammaGainEffect_new(lua_State* L)
563 assert(lua_gettop(L) == 0);
564 return wrap_lua_object_nonowned<LiftGammaGainEffect>(L, "LiftGammaGainEffect");
567 int InputStateInfo_get_width(lua_State* L)
569 assert(lua_gettop(L) == 2);
570 InputStateInfo *input_state_info = get_input_state_info(L, 1);
571 Theme *theme = get_theme_updata(L);
572 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
573 lua_pushnumber(L, input_state_info->last_width[signal_num]);
577 int InputStateInfo_get_height(lua_State* L)
579 assert(lua_gettop(L) == 2);
580 InputStateInfo *input_state_info = get_input_state_info(L, 1);
581 Theme *theme = get_theme_updata(L);
582 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
583 lua_pushnumber(L, input_state_info->last_height[signal_num]);
587 int InputStateInfo_get_interlaced(lua_State* L)
589 assert(lua_gettop(L) == 2);
590 InputStateInfo *input_state_info = get_input_state_info(L, 1);
591 Theme *theme = get_theme_updata(L);
592 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
593 lua_pushboolean(L, input_state_info->last_interlaced[signal_num]);
597 int InputStateInfo_get_has_signal(lua_State* L)
599 assert(lua_gettop(L) == 2);
600 InputStateInfo *input_state_info = get_input_state_info(L, 1);
601 Theme *theme = get_theme_updata(L);
602 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
603 lua_pushboolean(L, input_state_info->last_has_signal[signal_num]);
607 int InputStateInfo_get_is_connected(lua_State* L)
609 assert(lua_gettop(L) == 2);
610 InputStateInfo *input_state_info = get_input_state_info(L, 1);
611 Theme *theme = get_theme_updata(L);
612 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
613 lua_pushboolean(L, input_state_info->last_is_connected[signal_num]);
617 int InputStateInfo_get_frame_rate_nom(lua_State* L)
619 assert(lua_gettop(L) == 2);
620 InputStateInfo *input_state_info = get_input_state_info(L, 1);
621 Theme *theme = get_theme_updata(L);
622 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
623 lua_pushnumber(L, input_state_info->last_frame_rate_nom[signal_num]);
627 int InputStateInfo_get_frame_rate_den(lua_State* L)
629 assert(lua_gettop(L) == 2);
630 InputStateInfo *input_state_info = get_input_state_info(L, 1);
631 Theme *theme = get_theme_updata(L);
632 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
633 lua_pushnumber(L, input_state_info->last_frame_rate_den[signal_num]);
637 int Effect_set_float(lua_State *L)
639 assert(lua_gettop(L) == 3);
640 Effect *effect = (Effect *)get_effect(L, 1);
641 string key = checkstdstring(L, 2);
642 float value = luaL_checknumber(L, 3);
643 if (!effect->set_float(key, value)) {
644 luaL_error(L, "Effect refused set_float(\"%s\", %d) (invalid key?)", key.c_str(), int(value));
649 int Effect_set_int(lua_State *L)
651 assert(lua_gettop(L) == 3);
652 Effect *effect = (Effect *)get_effect(L, 1);
653 string key = checkstdstring(L, 2);
654 float value = luaL_checknumber(L, 3);
655 if (!effect->set_int(key, value)) {
656 luaL_error(L, "Effect refused set_int(\"%s\", %d) (invalid key?)", key.c_str(), int(value));
661 int Effect_set_vec3(lua_State *L)
663 assert(lua_gettop(L) == 5);
664 Effect *effect = (Effect *)get_effect(L, 1);
665 string key = checkstdstring(L, 2);
667 v[0] = luaL_checknumber(L, 3);
668 v[1] = luaL_checknumber(L, 4);
669 v[2] = luaL_checknumber(L, 5);
670 if (!effect->set_vec3(key, v)) {
671 luaL_error(L, "Effect refused set_vec3(\"%s\", %f, %f, %f) (invalid key?)", key.c_str(),
677 int Effect_set_vec4(lua_State *L)
679 assert(lua_gettop(L) == 6);
680 Effect *effect = (Effect *)get_effect(L, 1);
681 string key = checkstdstring(L, 2);
683 v[0] = luaL_checknumber(L, 3);
684 v[1] = luaL_checknumber(L, 4);
685 v[2] = luaL_checknumber(L, 5);
686 v[3] = luaL_checknumber(L, 6);
687 if (!effect->set_vec4(key, v)) {
688 luaL_error(L, "Effect refused set_vec4(\"%s\", %f, %f, %f, %f) (invalid key?)", key.c_str(),
689 v[0], v[1], v[2], v[3]);
694 const luaL_Reg EffectChain_funcs[] = {
695 { "new", EffectChain_new },
696 { "__gc", EffectChain_gc },
697 { "add_live_input", EffectChain_add_live_input },
698 { "add_video_input", EffectChain_add_video_input },
700 { "add_html_input", EffectChain_add_html_input },
702 { "add_effect", EffectChain_add_effect },
703 { "finalize", EffectChain_finalize },
707 const luaL_Reg LiveInputWrapper_funcs[] = {
708 { "connect_signal", LiveInputWrapper_connect_signal },
712 const luaL_Reg ImageInput_funcs[] = {
713 { "new", ImageInput_new },
714 { "set_float", Effect_set_float },
715 { "set_int", Effect_set_int },
716 { "set_vec3", Effect_set_vec3 },
717 { "set_vec4", Effect_set_vec4 },
721 const luaL_Reg VideoInput_funcs[] = {
722 { "new", VideoInput_new },
723 { "rewind", VideoInput_rewind },
724 { "disconnect", VideoInput_disconnect },
725 { "change_rate", VideoInput_change_rate },
726 { "get_signal_num", VideoInput_get_signal_num },
730 const luaL_Reg HTMLInput_funcs[] = {
731 { "new", HTMLInput_new },
733 { "set_url", HTMLInput_set_url },
734 { "reload", HTMLInput_reload },
735 { "set_max_fps", HTMLInput_set_max_fps },
736 { "execute_javascript_async", HTMLInput_execute_javascript_async },
737 { "resize", HTMLInput_resize },
738 { "get_signal_num", HTMLInput_get_signal_num },
743 const luaL_Reg WhiteBalanceEffect_funcs[] = {
744 { "new", WhiteBalanceEffect_new },
745 { "set_float", Effect_set_float },
746 { "set_int", Effect_set_int },
747 { "set_vec3", Effect_set_vec3 },
748 { "set_vec4", Effect_set_vec4 },
752 const luaL_Reg ResampleEffect_funcs[] = {
753 { "new", ResampleEffect_new },
754 { "set_float", Effect_set_float },
755 { "set_int", Effect_set_int },
756 { "set_vec3", Effect_set_vec3 },
757 { "set_vec4", Effect_set_vec4 },
761 const luaL_Reg PaddingEffect_funcs[] = {
762 { "new", PaddingEffect_new },
763 { "set_float", Effect_set_float },
764 { "set_int", Effect_set_int },
765 { "set_vec3", Effect_set_vec3 },
766 { "set_vec4", Effect_set_vec4 },
770 const luaL_Reg IntegralPaddingEffect_funcs[] = {
771 { "new", IntegralPaddingEffect_new },
772 { "set_float", Effect_set_float },
773 { "set_int", Effect_set_int },
774 { "set_vec3", Effect_set_vec3 },
775 { "set_vec4", Effect_set_vec4 },
779 const luaL_Reg OverlayEffect_funcs[] = {
780 { "new", OverlayEffect_new },
781 { "set_float", Effect_set_float },
782 { "set_int", Effect_set_int },
783 { "set_vec3", Effect_set_vec3 },
784 { "set_vec4", Effect_set_vec4 },
788 const luaL_Reg ResizeEffect_funcs[] = {
789 { "new", ResizeEffect_new },
790 { "set_float", Effect_set_float },
791 { "set_int", Effect_set_int },
792 { "set_vec3", Effect_set_vec3 },
793 { "set_vec4", Effect_set_vec4 },
797 const luaL_Reg MultiplyEffect_funcs[] = {
798 { "new", MultiplyEffect_new },
799 { "set_float", Effect_set_float },
800 { "set_int", Effect_set_int },
801 { "set_vec3", Effect_set_vec3 },
802 { "set_vec4", Effect_set_vec4 },
806 const luaL_Reg MixEffect_funcs[] = {
807 { "new", MixEffect_new },
808 { "set_float", Effect_set_float },
809 { "set_int", Effect_set_int },
810 { "set_vec3", Effect_set_vec3 },
811 { "set_vec4", Effect_set_vec4 },
815 const luaL_Reg LiftGammaGainEffect_funcs[] = {
816 { "new", LiftGammaGainEffect_new },
817 { "set_float", Effect_set_float },
818 { "set_int", Effect_set_int },
819 { "set_vec3", Effect_set_vec3 },
820 { "set_vec4", Effect_set_vec4 },
824 const luaL_Reg InputStateInfo_funcs[] = {
825 { "get_width", InputStateInfo_get_width },
826 { "get_height", InputStateInfo_get_height },
827 { "get_interlaced", InputStateInfo_get_interlaced },
828 { "get_has_signal", InputStateInfo_get_has_signal },
829 { "get_is_connected", InputStateInfo_get_is_connected },
830 { "get_frame_rate_nom", InputStateInfo_get_frame_rate_nom },
831 { "get_frame_rate_den", InputStateInfo_get_frame_rate_den },
835 const luaL_Reg ThemeMenu_funcs[] = {
836 { "set", ThemeMenu_set },
842 LiveInputWrapper::LiveInputWrapper(
845 bmusb::PixelFormat pixel_format,
846 bool override_bounce,
848 bool user_connectable)
850 pixel_format(pixel_format),
851 deinterlace(deinterlace),
852 user_connectable(user_connectable)
854 ImageFormat inout_format;
855 inout_format.color_space = COLORSPACE_sRGB;
857 // Gamma curve depends on the input signal, and we don't really get any
858 // indications. A camera would be expected to do Rec. 709, but
859 // I haven't checked if any do in practice. However, computers _do_ output
860 // in sRGB gamma (ie., they don't convert from sRGB to Rec. 709), and
861 // I wouldn't really be surprised if most non-professional cameras do, too.
862 // So we pick sRGB as the least evil here.
863 inout_format.gamma_curve = GAMMA_sRGB;
867 deinterlace_effect = new movit::DeinterlaceEffect();
869 // As per the comments in deinterlace_effect.h, we turn this off.
870 // The most likely interlaced input for us is either a camera
871 // (where it's fine to turn it off) or a laptop (where it _should_
873 CHECK(deinterlace_effect->set_int("enable_spatial_interlacing_check", 0));
875 num_inputs = deinterlace_effect->num_inputs();
876 assert(num_inputs == FRAME_HISTORY_LENGTH);
881 if (pixel_format == bmusb::PixelFormat_8BitBGRA) {
882 for (unsigned i = 0; i < num_inputs; ++i) {
883 // We upload our textures ourselves, and Movit swaps
884 // R and B in the shader if we specify BGRA, so lie and say RGBA.
885 if (global_flags.can_disable_srgb_decoder) {
886 rgba_inputs.push_back(new sRGBSwitchingFlatInput(inout_format, FORMAT_RGBA_POSTMULTIPLIED_ALPHA, GL_UNSIGNED_BYTE, global_flags.width, global_flags.height));
888 rgba_inputs.push_back(new NonsRGBCapableFlatInput(inout_format, FORMAT_RGBA_POSTMULTIPLIED_ALPHA, GL_UNSIGNED_BYTE, global_flags.width, global_flags.height));
890 chain->add_input(rgba_inputs.back());
894 vector<Effect *> reverse_inputs(rgba_inputs.rbegin(), rgba_inputs.rend());
895 chain->add_effect(deinterlace_effect, reverse_inputs);
898 assert(pixel_format == bmusb::PixelFormat_8BitYCbCr ||
899 pixel_format == bmusb::PixelFormat_10BitYCbCr ||
900 pixel_format == bmusb::PixelFormat_8BitYCbCrPlanar);
902 // Most of these settings will be overridden later if using PixelFormat_8BitYCbCrPlanar.
903 input_ycbcr_format.chroma_subsampling_x = (pixel_format == bmusb::PixelFormat_10BitYCbCr) ? 1 : 2;
904 input_ycbcr_format.chroma_subsampling_y = 1;
905 input_ycbcr_format.num_levels = (pixel_format == bmusb::PixelFormat_10BitYCbCr) ? 1024 : 256;
906 input_ycbcr_format.cb_x_position = 0.0;
907 input_ycbcr_format.cr_x_position = 0.0;
908 input_ycbcr_format.cb_y_position = 0.5;
909 input_ycbcr_format.cr_y_position = 0.5;
910 input_ycbcr_format.luma_coefficients = YCBCR_REC_709; // Will be overridden later even if not planar.
911 input_ycbcr_format.full_range = false; // Will be overridden later even if not planar.
913 for (unsigned i = 0; i < num_inputs; ++i) {
914 // When using 10-bit input, we're converting to interleaved through v210Converter.
915 YCbCrInputSplitting splitting;
916 if (pixel_format == bmusb::PixelFormat_10BitYCbCr) {
917 splitting = YCBCR_INPUT_INTERLEAVED;
918 } else if (pixel_format == bmusb::PixelFormat_8BitYCbCr) {
919 splitting = YCBCR_INPUT_SPLIT_Y_AND_CBCR;
921 splitting = YCBCR_INPUT_PLANAR;
923 if (override_bounce) {
924 ycbcr_inputs.push_back(new NonBouncingYCbCrInput(inout_format, input_ycbcr_format, global_flags.width, global_flags.height, splitting));
926 ycbcr_inputs.push_back(new YCbCrInput(inout_format, input_ycbcr_format, global_flags.width, global_flags.height, splitting));
928 chain->add_input(ycbcr_inputs.back());
932 vector<Effect *> reverse_inputs(ycbcr_inputs.rbegin(), ycbcr_inputs.rend());
933 chain->add_effect(deinterlace_effect, reverse_inputs);
938 bool LiveInputWrapper::connect_signal(int signal_num)
940 if (!user_connectable) {
944 if (global_mixer == nullptr) {
949 signal_num = theme->map_signal(signal_num);
950 connect_signal_raw(signal_num, *theme->input_state);
954 void LiveInputWrapper::connect_signal_raw(int signal_num, const InputState &input_state)
956 BufferedFrame first_frame = input_state.buffered_frames[signal_num][0];
957 if (first_frame.frame == nullptr) {
961 unsigned width, height;
963 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)first_frame.frame->userdata;
964 width = userdata->last_width[first_frame.field_number];
965 height = userdata->last_height[first_frame.field_number];
966 if (userdata->last_interlaced) {
971 movit::YCbCrLumaCoefficients ycbcr_coefficients = input_state.ycbcr_coefficients[signal_num];
972 bool full_range = input_state.full_range[signal_num];
974 if (input_state.ycbcr_coefficients_auto[signal_num]) {
977 // The Blackmagic driver docs claim that the device outputs Y'CbCr
978 // according to Rec. 601, but this seems to indicate the subsampling
979 // positions only, as they publish Y'CbCr → RGB formulas that are
980 // different for HD and SD (corresponding to Rec. 709 and 601, respectively),
981 // and a Lenovo X1 gen 3 I used to test definitely outputs Rec. 709
982 // (at least up to rounding error). Other devices seem to use Rec. 601
983 // even on HD resolutions. Nevertheless, Rec. 709 _is_ the right choice
984 // for HD, so we default to that if the user hasn't set anything.
986 ycbcr_coefficients = YCBCR_REC_709;
988 ycbcr_coefficients = YCBCR_REC_601;
992 // This is a global, but it doesn't really matter.
993 input_ycbcr_format.luma_coefficients = ycbcr_coefficients;
994 input_ycbcr_format.full_range = full_range;
996 BufferedFrame last_good_frame = first_frame;
997 for (unsigned i = 0; i < max(ycbcr_inputs.size(), rgba_inputs.size()); ++i) {
998 BufferedFrame frame = input_state.buffered_frames[signal_num][i];
999 if (frame.frame == nullptr) {
1000 // Not enough data; reuse last frame (well, field).
1001 // This is suboptimal, but we have nothing better.
1002 frame = last_good_frame;
1004 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
1006 unsigned this_width = userdata->last_width[frame.field_number];
1007 unsigned this_height = userdata->last_height[frame.field_number];
1008 if (this_width != width || this_height != height) {
1009 // Resolution changed; reuse last frame/field.
1010 frame = last_good_frame;
1011 userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
1014 assert(userdata->pixel_format == pixel_format);
1015 switch (pixel_format) {
1016 case bmusb::PixelFormat_8BitYCbCr:
1017 ycbcr_inputs[i]->set_texture_num(0, userdata->tex_y[frame.field_number]);
1018 ycbcr_inputs[i]->set_texture_num(1, userdata->tex_cbcr[frame.field_number]);
1019 ycbcr_inputs[i]->change_ycbcr_format(input_ycbcr_format);
1020 ycbcr_inputs[i]->set_width(width);
1021 ycbcr_inputs[i]->set_height(height);
1023 case bmusb::PixelFormat_8BitYCbCrPlanar:
1024 ycbcr_inputs[i]->set_texture_num(0, userdata->tex_y[frame.field_number]);
1025 ycbcr_inputs[i]->set_texture_num(1, userdata->tex_cb[frame.field_number]);
1026 ycbcr_inputs[i]->set_texture_num(2, userdata->tex_cr[frame.field_number]);
1027 ycbcr_inputs[i]->change_ycbcr_format(userdata->ycbcr_format);
1028 ycbcr_inputs[i]->set_width(width);
1029 ycbcr_inputs[i]->set_height(height);
1031 case bmusb::PixelFormat_10BitYCbCr:
1032 ycbcr_inputs[i]->set_texture_num(0, userdata->tex_444[frame.field_number]);
1033 ycbcr_inputs[i]->change_ycbcr_format(input_ycbcr_format);
1034 ycbcr_inputs[i]->set_width(width);
1035 ycbcr_inputs[i]->set_height(height);
1037 case bmusb::PixelFormat_8BitBGRA:
1038 rgba_inputs[i]->set_texture_num(userdata->tex_rgba[frame.field_number]);
1039 rgba_inputs[i]->set_width(width);
1040 rgba_inputs[i]->set_height(height);
1046 last_good_frame = frame;
1050 BufferedFrame frame = input_state.buffered_frames[signal_num][0];
1051 CHECK(deinterlace_effect->set_int("current_field_position", frame.field_number));
1057 int call_num_channels(lua_State *L)
1059 lua_getglobal(L, "num_channels");
1061 if (lua_pcall(L, 0, 1, 0) != 0) {
1062 fprintf(stderr, "error running function `num_channels': %s\n", lua_tostring(L, -1));
1066 int num_channels = luaL_checknumber(L, 1);
1068 assert(lua_gettop(L) == 0);
1069 return num_channels;
1074 Theme::Theme(const string &filename, const vector<string> &search_dirs, ResourcePool *resource_pool, unsigned num_cards)
1075 : resource_pool(resource_pool), num_cards(num_cards), signal_to_card_mapping(global_flags.default_stream_mapping)
1077 L = luaL_newstate();
1080 // Search through all directories until we find a file that will load
1081 // (as in, does not return LUA_ERRFILE); then run it. We store load errors
1082 // from all the attempts, and show them once we know we can't find any of them.
1084 vector<string> errors;
1085 bool success = false;
1087 vector<string> real_search_dirs;
1088 if (!filename.empty() && filename[0] == '/') {
1089 real_search_dirs.push_back("");
1091 real_search_dirs = search_dirs;
1096 for (const string &dir : real_search_dirs) {
1100 path = dir + "/" + filename;
1102 int err = luaL_loadfile(L, path.c_str());
1104 // Save the theme for when we're actually going to run it
1105 // (we need to set up the right environment below first,
1106 // and we couldn't do that before, because we didn't know the
1107 // path to put in Nageru.THEME_PATH).
1108 theme_code_ref = luaL_ref(L, LUA_REGISTRYINDEX);
1109 assert(lua_gettop(L) == 0);
1114 errors.push_back(lua_tostring(L, -1));
1116 if (err != LUA_ERRFILE) {
1117 // The file actually loaded, but failed to parse somehow. Abort; don't try the next one.
1123 for (const string &error : errors) {
1124 fprintf(stderr, "%s\n", error.c_str());
1128 assert(lua_gettop(L) == 0);
1130 // Make sure the path exposed to the theme (as Nageru.THEME_PATH;
1131 // can be useful for locating files when talking to CEF) is absolute.
1132 // In a sense, it would be nice if realpath() had a mode not to
1133 // resolve symlinks, but it doesn't, so we only call it if we don't
1134 // already have an absolute path (which may leave ../ elements etc.).
1135 if (path[0] == '/') {
1138 char *absolute_theme_path = realpath(path.c_str(), nullptr);
1139 theme_path = absolute_theme_path;
1140 free(absolute_theme_path);
1143 // Set up the API we provide.
1144 register_constants();
1145 register_class("EffectChain", EffectChain_funcs);
1146 register_class("LiveInputWrapper", LiveInputWrapper_funcs);
1147 register_class("ImageInput", ImageInput_funcs);
1148 register_class("VideoInput", VideoInput_funcs);
1149 register_class("HTMLInput", HTMLInput_funcs);
1150 register_class("WhiteBalanceEffect", WhiteBalanceEffect_funcs);
1151 register_class("ResampleEffect", ResampleEffect_funcs);
1152 register_class("PaddingEffect", PaddingEffect_funcs);
1153 register_class("IntegralPaddingEffect", IntegralPaddingEffect_funcs);
1154 register_class("OverlayEffect", OverlayEffect_funcs);
1155 register_class("ResizeEffect", ResizeEffect_funcs);
1156 register_class("MultiplyEffect", MultiplyEffect_funcs);
1157 register_class("MixEffect", MixEffect_funcs);
1158 register_class("LiftGammaGainEffect", LiftGammaGainEffect_funcs);
1159 register_class("InputStateInfo", InputStateInfo_funcs);
1160 register_class("ThemeMenu", ThemeMenu_funcs);
1162 // Now actually run the theme to get everything set up.
1163 lua_rawgeti(L, LUA_REGISTRYINDEX, theme_code_ref);
1164 luaL_unref(L, LUA_REGISTRYINDEX, theme_code_ref);
1165 if (lua_pcall(L, 0, 0, 0)) {
1166 fprintf(stderr, "Error when running %s: %s\n", path.c_str(), lua_tostring(L, -1));
1169 assert(lua_gettop(L) == 0);
1171 // Ask it for the number of channels.
1172 num_channels = call_num_channels(L);
1180 void Theme::register_constants()
1182 // Set Nageru.VIDEO_FORMAT_BGRA = bmusb::PixelFormat_8BitBGRA, etc.
1183 const vector<pair<string, int>> num_constants = {
1184 { "VIDEO_FORMAT_BGRA", bmusb::PixelFormat_8BitBGRA },
1185 { "VIDEO_FORMAT_YCBCR", bmusb::PixelFormat_8BitYCbCrPlanar },
1187 const vector<pair<string, string>> str_constants = {
1188 { "THEME_PATH", theme_path },
1191 lua_newtable(L); // t = {}
1193 for (const pair<string, int> &constant : num_constants) {
1194 lua_pushstring(L, constant.first.c_str());
1195 lua_pushinteger(L, constant.second);
1196 lua_settable(L, 1); // t[key] = value
1198 for (const pair<string, string> &constant : str_constants) {
1199 lua_pushstring(L, constant.first.c_str());
1200 lua_pushstring(L, constant.second.c_str());
1201 lua_settable(L, 1); // t[key] = value
1204 lua_setglobal(L, "Nageru"); // Nageru = t
1205 assert(lua_gettop(L) == 0);
1208 void Theme::register_class(const char *class_name, const luaL_Reg *funcs)
1210 assert(lua_gettop(L) == 0);
1211 luaL_newmetatable(L, class_name); // mt = {}
1212 lua_pushlightuserdata(L, this);
1213 luaL_setfuncs(L, funcs, 1); // for (name,f in funcs) { mt[name] = f, with upvalue {theme} }
1214 lua_pushvalue(L, -1);
1215 lua_setfield(L, -2, "__index"); // mt.__index = mt
1216 lua_setglobal(L, class_name); // ClassName = mt
1217 assert(lua_gettop(L) == 0);
1220 Theme::Chain Theme::get_chain(unsigned num, float t, unsigned width, unsigned height, InputState input_state)
1224 unique_lock<mutex> lock(m);
1225 assert(lua_gettop(L) == 0);
1226 lua_getglobal(L, "get_chain"); /* function to be called */
1227 lua_pushnumber(L, num);
1228 lua_pushnumber(L, t);
1229 lua_pushnumber(L, width);
1230 lua_pushnumber(L, height);
1231 wrap_lua_object<InputStateInfo>(L, "InputStateInfo", input_state);
1233 if (lua_pcall(L, 5, 2, 0) != 0) {
1234 fprintf(stderr, "error running function `get_chain': %s\n", lua_tostring(L, -1));
1238 EffectChain *effect_chain = (EffectChain *)luaL_testudata(L, -2, "EffectChain");
1239 if (effect_chain == nullptr) {
1240 fprintf(stderr, "get_chain() for chain number %d did not return an EffectChain\n",
1244 chain.chain = effect_chain;
1245 if (!lua_isfunction(L, -1)) {
1246 fprintf(stderr, "Argument #-1 should be a function\n");
1249 lua_pushvalue(L, -1);
1250 shared_ptr<LuaRefWithDeleter> funcref(new LuaRefWithDeleter(&m, L, luaL_ref(L, LUA_REGISTRYINDEX)));
1252 assert(lua_gettop(L) == 0);
1254 chain.setup_chain = [this, funcref, input_state, effect_chain]{
1255 unique_lock<mutex> lock(m);
1257 assert(this->input_state == nullptr);
1258 this->input_state = &input_state;
1260 // Set up state, including connecting signals.
1261 lua_rawgeti(L, LUA_REGISTRYINDEX, funcref->get());
1262 if (lua_pcall(L, 0, 0, 0) != 0) {
1263 fprintf(stderr, "error running chain setup callback: %s\n", lua_tostring(L, -1));
1266 assert(lua_gettop(L) == 0);
1268 // The theme can't (or at least shouldn't!) call connect_signal() on
1269 // each FFmpeg or CEF input, so we'll do it here.
1270 if (video_signal_connections.count(effect_chain)) {
1271 for (const VideoSignalConnection &conn : video_signal_connections[effect_chain]) {
1272 conn.wrapper->connect_signal_raw(conn.source->get_card_index(), input_state);
1276 if (html_signal_connections.count(effect_chain)) {
1277 for (const CEFSignalConnection &conn : html_signal_connections[effect_chain]) {
1278 conn.wrapper->connect_signal_raw(conn.source->get_card_index(), input_state);
1283 this->input_state = nullptr;
1286 // TODO: Can we do better, e.g. by running setup_chain() and seeing what it references?
1287 // Actually, setup_chain does maybe hold all the references we need now anyway?
1288 chain.input_frames.reserve(num_cards * FRAME_HISTORY_LENGTH);
1289 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
1290 for (unsigned frame_num = 0; frame_num < FRAME_HISTORY_LENGTH; ++frame_num) {
1291 chain.input_frames.push_back(input_state.buffered_frames[card_index][frame_num].frame);
1298 string Theme::get_channel_name(unsigned channel)
1300 unique_lock<mutex> lock(m);
1301 lua_getglobal(L, "channel_name");
1302 lua_pushnumber(L, channel);
1303 if (lua_pcall(L, 1, 1, 0) != 0) {
1304 fprintf(stderr, "error running function `channel_name': %s\n", lua_tostring(L, -1));
1307 const char *ret = lua_tostring(L, -1);
1308 if (ret == nullptr) {
1309 fprintf(stderr, "function `channel_name' returned nil for channel %d\n", channel);
1313 string retstr = ret;
1315 assert(lua_gettop(L) == 0);
1319 int Theme::get_channel_signal(unsigned channel)
1321 unique_lock<mutex> lock(m);
1322 lua_getglobal(L, "channel_signal");
1323 lua_pushnumber(L, channel);
1324 if (lua_pcall(L, 1, 1, 0) != 0) {
1325 fprintf(stderr, "error running function `channel_signal': %s\n", lua_tostring(L, -1));
1329 int ret = luaL_checknumber(L, 1);
1331 assert(lua_gettop(L) == 0);
1335 std::string Theme::get_channel_color(unsigned channel)
1337 unique_lock<mutex> lock(m);
1338 lua_getglobal(L, "channel_color");
1339 lua_pushnumber(L, channel);
1340 if (lua_pcall(L, 1, 1, 0) != 0) {
1341 fprintf(stderr, "error running function `channel_color': %s\n", lua_tostring(L, -1));
1345 const char *ret = lua_tostring(L, -1);
1346 if (ret == nullptr) {
1347 fprintf(stderr, "function `channel_color' returned nil for channel %d\n", channel);
1351 string retstr = ret;
1353 assert(lua_gettop(L) == 0);
1357 bool Theme::get_supports_set_wb(unsigned channel)
1359 unique_lock<mutex> lock(m);
1360 lua_getglobal(L, "supports_set_wb");
1361 lua_pushnumber(L, channel);
1362 if (lua_pcall(L, 1, 1, 0) != 0) {
1363 fprintf(stderr, "error running function `supports_set_wb': %s\n", lua_tostring(L, -1));
1367 bool ret = checkbool(L, -1);
1369 assert(lua_gettop(L) == 0);
1373 void Theme::set_wb(unsigned channel, double r, double g, double b)
1375 unique_lock<mutex> lock(m);
1376 lua_getglobal(L, "set_wb");
1377 lua_pushnumber(L, channel);
1378 lua_pushnumber(L, r);
1379 lua_pushnumber(L, g);
1380 lua_pushnumber(L, b);
1381 if (lua_pcall(L, 4, 0, 0) != 0) {
1382 fprintf(stderr, "error running function `set_wb': %s\n", lua_tostring(L, -1));
1386 assert(lua_gettop(L) == 0);
1389 vector<string> Theme::get_transition_names(float t)
1391 unique_lock<mutex> lock(m);
1392 lua_getglobal(L, "get_transitions");
1393 lua_pushnumber(L, t);
1394 if (lua_pcall(L, 1, 1, 0) != 0) {
1395 fprintf(stderr, "error running function `get_transitions': %s\n", lua_tostring(L, -1));
1401 while (lua_next(L, -2) != 0) {
1402 ret.push_back(lua_tostring(L, -1));
1406 assert(lua_gettop(L) == 0);
1410 int Theme::map_signal(int signal_num)
1412 // Negative numbers map to raw signals.
1413 if (signal_num < 0) {
1414 return -1 - signal_num;
1417 unique_lock<mutex> lock(map_m);
1418 if (signal_to_card_mapping.count(signal_num)) {
1419 return signal_to_card_mapping[signal_num];
1423 if (global_flags.output_card != -1 && num_cards > 1) {
1424 // Try to exclude the output card from the default card_index.
1425 card_index = signal_num % (num_cards - 1);
1426 if (card_index >= global_flags.output_card) {
1429 if (signal_num >= int(num_cards - 1)) {
1430 fprintf(stderr, "WARNING: Theme asked for input %d, but we only have %u input card(s) (card %d is busy with output).\n",
1431 signal_num, num_cards - 1, global_flags.output_card);
1432 fprintf(stderr, "Mapping to card %d instead.\n", card_index);
1435 card_index = signal_num % num_cards;
1436 if (signal_num >= int(num_cards)) {
1437 fprintf(stderr, "WARNING: Theme asked for input %d, but we only have %u card(s).\n", signal_num, num_cards);
1438 fprintf(stderr, "Mapping to card %d instead.\n", card_index);
1441 signal_to_card_mapping[signal_num] = card_index;
1445 void Theme::set_signal_mapping(int signal_num, int card_num)
1447 unique_lock<mutex> lock(map_m);
1448 assert(card_num < int(num_cards));
1449 signal_to_card_mapping[signal_num] = card_num;
1452 void Theme::transition_clicked(int transition_num, float t)
1454 unique_lock<mutex> lock(m);
1455 lua_getglobal(L, "transition_clicked");
1456 lua_pushnumber(L, transition_num);
1457 lua_pushnumber(L, t);
1459 if (lua_pcall(L, 2, 0, 0) != 0) {
1460 fprintf(stderr, "error running function `transition_clicked': %s\n", lua_tostring(L, -1));
1463 assert(lua_gettop(L) == 0);
1466 void Theme::channel_clicked(int preview_num)
1468 unique_lock<mutex> lock(m);
1469 lua_getglobal(L, "channel_clicked");
1470 lua_pushnumber(L, preview_num);
1472 if (lua_pcall(L, 1, 0, 0) != 0) {
1473 fprintf(stderr, "error running function `channel_clicked': %s\n", lua_tostring(L, -1));
1476 assert(lua_gettop(L) == 0);
1479 int Theme::set_theme_menu(lua_State *L)
1481 for (const Theme::MenuEntry &entry : theme_menu) {
1482 luaL_unref(L, LUA_REGISTRYINDEX, entry.lua_ref);
1486 int num_elements = lua_gettop(L);
1487 for (int i = 1; i <= num_elements; ++i) {
1488 lua_rawgeti(L, i, 1);
1489 const string text = checkstdstring(L, -1);
1492 lua_rawgeti(L, i, 2);
1493 luaL_checktype(L, -1, LUA_TFUNCTION);
1494 int ref = luaL_ref(L, LUA_REGISTRYINDEX);
1496 theme_menu.push_back(MenuEntry{ text, ref });
1498 lua_pop(L, num_elements);
1499 assert(lua_gettop(L) == 0);
1501 if (theme_menu_callback != nullptr) {
1502 theme_menu_callback();
1508 void Theme::theme_menu_entry_clicked(int lua_ref)
1510 unique_lock<mutex> lock(m);
1511 lua_rawgeti(L, LUA_REGISTRYINDEX, lua_ref);
1512 if (lua_pcall(L, 0, 0, 0) != 0) {
1513 fprintf(stderr, "error running menu callback: %s\n", lua_tostring(L, -1));