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/mix_effect.h>
14 #include <movit/multiply_effect.h>
15 #include <movit/overlay_effect.h>
16 #include <movit/padding_effect.h>
17 #include <movit/resample_effect.h>
18 #include <movit/resize_effect.h>
19 #include <movit/util.h>
20 #include <movit/white_balance_effect.h>
21 #include <movit/ycbcr.h>
22 #include <movit/ycbcr_input.h>
32 #include "cef_capture.h"
34 #include "ffmpeg_capture.h"
36 #include "image_input.h"
37 #include "input_state.h"
38 #include "pbo_frame_allocator.h"
40 #if !defined LUA_VERSION_NUM || LUA_VERSION_NUM==501
42 // Compatibility shims for LuaJIT 2.0 (LuaJIT 2.1 implements the entire Lua 5.2 API).
43 // Adapted from https://github.com/keplerproject/lua-compat-5.2/blob/master/c-api/compat-5.2.c
44 // and licensed as follows:
46 // The MIT License (MIT)
48 // Copyright (c) 2013 Hisham Muhammad
50 // Permission is hereby granted, free of charge, to any person obtaining a copy of
51 // this software and associated documentation files (the "Software"), to deal in
52 // the Software without restriction, including without limitation the rights to
53 // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
54 // the Software, and to permit persons to whom the Software is furnished to do so,
55 // subject to the following conditions:
57 // The above copyright notice and this permission notice shall be included in all
58 // copies or substantial portions of the Software.
60 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
61 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
62 // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
63 // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
64 // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
65 // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
68 ** Adapted from Lua 5.2.0
70 void luaL_setfuncs(lua_State *L, const luaL_Reg *l, int nup) {
71 luaL_checkstack(L, nup+1, "too many upvalues");
72 for (; l->name != NULL; l++) { /* fill the table with given functions */
74 lua_pushstring(L, l->name);
75 for (i = 0; i < nup; i++) /* copy upvalues to the top */
76 lua_pushvalue(L, -(nup + 1));
77 lua_pushcclosure(L, l->func, nup); /* closure with those upvalues */
78 lua_settable(L, -(nup + 3)); /* table must be below the upvalues, the name and the closure */
80 lua_pop(L, nup); /* remove upvalues */
83 void *luaL_testudata(lua_State *L, int i, const char *tname) {
84 void *p = lua_touserdata(L, i);
85 luaL_checkstack(L, 2, "not enough stack slots");
86 if (p == NULL || !lua_getmetatable(L, i))
90 luaL_getmetatable(L, tname);
91 res = lua_rawequal(L, -1, -2);
108 using namespace movit;
110 extern Mixer *global_mixer;
112 Theme *get_theme_updata(lua_State* L)
114 luaL_checktype(L, lua_upvalueindex(1), LUA_TLIGHTUSERDATA);
115 return (Theme *)lua_touserdata(L, lua_upvalueindex(1));
118 int ThemeMenu_set(lua_State *L)
120 Theme *theme = get_theme_updata(L);
121 return theme->set_theme_menu(L);
126 // Contains basically the same data as InputState, but does not hold on to
127 // a reference to the frames. This is important so that we can release them
128 // without having to wait for Lua's GC.
129 struct InputStateInfo {
130 InputStateInfo(const InputState& input_state);
132 unsigned last_width[MAX_VIDEO_CARDS], last_height[MAX_VIDEO_CARDS];
133 bool last_interlaced[MAX_VIDEO_CARDS], last_has_signal[MAX_VIDEO_CARDS], last_is_connected[MAX_VIDEO_CARDS];
134 unsigned last_frame_rate_nom[MAX_VIDEO_CARDS], last_frame_rate_den[MAX_VIDEO_CARDS];
137 InputStateInfo::InputStateInfo(const InputState &input_state)
139 for (unsigned signal_num = 0; signal_num < MAX_VIDEO_CARDS; ++signal_num) {
140 BufferedFrame frame = input_state.buffered_frames[signal_num][0];
141 if (frame.frame == nullptr) {
142 last_width[signal_num] = last_height[signal_num] = 0;
143 last_interlaced[signal_num] = false;
144 last_has_signal[signal_num] = false;
145 last_is_connected[signal_num] = false;
148 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
149 last_width[signal_num] = userdata->last_width[frame.field_number];
150 last_height[signal_num] = userdata->last_height[frame.field_number];
151 last_interlaced[signal_num] = userdata->last_interlaced;
152 last_has_signal[signal_num] = userdata->last_has_signal;
153 last_is_connected[signal_num] = userdata->last_is_connected;
154 last_frame_rate_nom[signal_num] = userdata->last_frame_rate_nom;
155 last_frame_rate_den[signal_num] = userdata->last_frame_rate_den;
159 class LuaRefWithDeleter {
161 LuaRefWithDeleter(mutex *m, lua_State *L, int ref) : m(m), L(L), ref(ref) {}
162 ~LuaRefWithDeleter() {
163 unique_lock<mutex> lock(*m);
164 luaL_unref(L, LUA_REGISTRYINDEX, ref);
166 int get() const { return ref; }
169 LuaRefWithDeleter(const LuaRefWithDeleter &) = delete;
176 template<class T, class... Args>
177 int wrap_lua_object(lua_State* L, const char *class_name, Args&&... args)
179 // Construct the C++ object and put it on the stack.
180 void *mem = lua_newuserdata(L, sizeof(T));
181 new(mem) T(forward<Args>(args)...);
183 // Look up the metatable named <class_name>, and set it on the new object.
184 luaL_getmetatable(L, class_name);
185 lua_setmetatable(L, -2);
190 // Like wrap_lua_object, but the object is not owned by Lua; ie. it's not freed
191 // by Lua GC. This is typically the case for Effects, which are owned by EffectChain
192 // and expected to be destructed by it. The object will be of type T** instead of T*
193 // when exposed to Lua.
195 // Note that we currently leak if you allocate an Effect in this way and never call
196 // add_effect. We should see if there's a way to e.g. set __gc on it at construction time
197 // and then release that once add_effect() takes ownership.
198 template<class T, class... Args>
199 int wrap_lua_object_nonowned(lua_State* L, const char *class_name, Args&&... args)
201 // Construct the pointer ot the C++ object and put it on the stack.
202 T **obj = (T **)lua_newuserdata(L, sizeof(T *));
203 *obj = new T(forward<Args>(args)...);
205 // Look up the metatable named <class_name>, and set it on the new object.
206 luaL_getmetatable(L, class_name);
207 lua_setmetatable(L, -2);
212 Effect *get_effect(lua_State *L, int idx)
214 if (luaL_testudata(L, idx, "WhiteBalanceEffect") ||
215 luaL_testudata(L, idx, "ResampleEffect") ||
216 luaL_testudata(L, idx, "PaddingEffect") ||
217 luaL_testudata(L, idx, "IntegralPaddingEffect") ||
218 luaL_testudata(L, idx, "OverlayEffect") ||
219 luaL_testudata(L, idx, "ResizeEffect") ||
220 luaL_testudata(L, idx, "MultiplyEffect") ||
221 luaL_testudata(L, idx, "MixEffect") ||
222 luaL_testudata(L, idx, "ImageInput")) {
223 return *(Effect **)lua_touserdata(L, idx);
225 luaL_error(L, "Error: Index #%d was not an Effect type\n", idx);
229 InputStateInfo *get_input_state_info(lua_State *L, int idx)
231 if (luaL_testudata(L, idx, "InputStateInfo")) {
232 return (InputStateInfo *)lua_touserdata(L, idx);
234 luaL_error(L, "Error: Index #%d was not InputStateInfo\n", idx);
238 bool checkbool(lua_State* L, int idx)
240 luaL_checktype(L, idx, LUA_TBOOLEAN);
241 return lua_toboolean(L, idx);
244 string checkstdstring(lua_State *L, int index)
247 const char* cstr = lua_tolstring(L, index, &len);
248 return string(cstr, len);
251 int EffectChain_new(lua_State* L)
253 assert(lua_gettop(L) == 2);
254 Theme *theme = get_theme_updata(L);
255 int aspect_w = luaL_checknumber(L, 1);
256 int aspect_h = luaL_checknumber(L, 2);
258 return wrap_lua_object<EffectChain>(L, "EffectChain", aspect_w, aspect_h, theme->get_resource_pool());
261 int EffectChain_gc(lua_State* L)
263 assert(lua_gettop(L) == 1);
264 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
265 chain->~EffectChain();
269 int EffectChain_add_live_input(lua_State* L)
271 assert(lua_gettop(L) == 3);
272 Theme *theme = get_theme_updata(L);
273 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
274 bool override_bounce = checkbool(L, 2);
275 bool deinterlace = checkbool(L, 3);
276 bmusb::PixelFormat pixel_format = global_flags.ten_bit_input ? bmusb::PixelFormat_10BitYCbCr : bmusb::PixelFormat_8BitYCbCr;
278 // Needs to be nonowned to match add_video_input (see below).
279 return wrap_lua_object_nonowned<LiveInputWrapper>(L, "LiveInputWrapper", theme, chain, pixel_format, override_bounce, deinterlace);
282 int EffectChain_add_video_input(lua_State* L)
284 assert(lua_gettop(L) == 3);
285 Theme *theme = get_theme_updata(L);
286 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
287 FFmpegCapture **capture = (FFmpegCapture **)luaL_checkudata(L, 2, "VideoInput");
288 bool deinterlace = checkbool(L, 3);
290 // These need to be nonowned, so that the LiveInputWrapper still exists
291 // and can feed frames to the right EffectChain even if the Lua code
292 // doesn't care about the object anymore. (If we change this, we'd need
293 // to also unregister the signal connection on __gc.)
294 int ret = wrap_lua_object_nonowned<LiveInputWrapper>(
295 L, "LiveInputWrapper", theme, chain, (*capture)->get_current_pixel_format(),
296 /*override_bounce=*/false, deinterlace);
298 Theme *theme = get_theme_updata(L);
299 LiveInputWrapper **live_input = (LiveInputWrapper **)lua_touserdata(L, -1);
300 theme->register_video_signal_connection(chain, *live_input, *capture);
306 int EffectChain_add_html_input(lua_State* L)
308 assert(lua_gettop(L) == 2);
309 Theme *theme = get_theme_updata(L);
310 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
311 CEFCapture **capture = (CEFCapture **)luaL_checkudata(L, 2, "HTMLInput");
313 // These need to be nonowned, so that the LiveInputWrapper still exists
314 // and can feed frames to the right EffectChain even if the Lua code
315 // doesn't care about the object anymore. (If we change this, we'd need
316 // to also unregister the signal connection on __gc.)
317 int ret = wrap_lua_object_nonowned<LiveInputWrapper>(
318 L, "LiveInputWrapper", theme, chain, (*capture)->get_current_pixel_format(),
319 /*override_bounce=*/false, /*deinterlace=*/false);
321 Theme *theme = get_theme_updata(L);
322 LiveInputWrapper **live_input = (LiveInputWrapper **)lua_touserdata(L, -1);
323 theme->register_html_signal_connection(chain, *live_input, *capture);
329 int EffectChain_add_effect(lua_State* L)
331 assert(lua_gettop(L) >= 2);
332 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
334 // TODO: Better error reporting.
335 Effect *effect = get_effect(L, 2);
336 if (lua_gettop(L) == 2) {
337 if (effect->num_inputs() == 0) {
338 chain->add_input((Input *)effect);
340 chain->add_effect(effect);
343 vector<Effect *> inputs;
344 for (int idx = 3; idx <= lua_gettop(L); ++idx) {
345 if (luaL_testudata(L, idx, "LiveInputWrapper")) {
346 LiveInputWrapper **input = (LiveInputWrapper **)lua_touserdata(L, idx);
347 inputs.push_back((*input)->get_effect());
349 inputs.push_back(get_effect(L, idx));
352 chain->add_effect(effect, inputs);
355 lua_settop(L, 2); // Return the effect itself.
357 // Make sure Lua doesn't garbage-collect it away.
358 lua_pushvalue(L, -1);
359 luaL_ref(L, LUA_REGISTRYINDEX); // TODO: leak?
364 int EffectChain_finalize(lua_State* L)
366 assert(lua_gettop(L) == 2);
367 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
368 bool is_main_chain = checkbool(L, 2);
370 // Add outputs as needed.
371 // NOTE: If you change any details about the output format, you will need to
372 // also update what's given to the muxer (HTTPD::Mux constructor) and
373 // what's put in the H.264 stream (sps_rbsp()).
374 ImageFormat inout_format;
375 inout_format.color_space = COLORSPACE_REC_709;
377 // Output gamma is tricky. We should output Rec. 709 for TV, except that
378 // we expect to run with web players and others that don't really care and
379 // just output with no conversion. So that means we'll need to output sRGB,
380 // even though H.264 has no setting for that (we use “unspecified”).
381 inout_format.gamma_curve = GAMMA_sRGB;
384 YCbCrFormat output_ycbcr_format;
385 // We actually output 4:2:0 and/or 4:2:2 in the end, but chroma subsampling
386 // happens in a pass not run by Movit (see ChromaSubsampler::subsample_chroma()).
387 output_ycbcr_format.chroma_subsampling_x = 1;
388 output_ycbcr_format.chroma_subsampling_y = 1;
390 // This will be overridden if HDMI/SDI output is in force.
391 if (global_flags.ycbcr_rec709_coefficients) {
392 output_ycbcr_format.luma_coefficients = YCBCR_REC_709;
394 output_ycbcr_format.luma_coefficients = YCBCR_REC_601;
397 output_ycbcr_format.full_range = false;
398 output_ycbcr_format.num_levels = 1 << global_flags.x264_bit_depth;
400 GLenum type = global_flags.x264_bit_depth > 8 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_BYTE;
402 chain->add_ycbcr_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED, output_ycbcr_format, YCBCR_OUTPUT_SPLIT_Y_AND_CBCR, type);
404 // If we're using zerocopy video encoding (so the destination
405 // Y texture is owned by VA-API and will be unavailable for
406 // display), add a copy, where we'll only be using the Y component.
407 if (global_flags.use_zerocopy) {
408 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.
410 chain->set_dither_bits(global_flags.x264_bit_depth > 8 ? 16 : 8);
411 chain->set_output_origin(OUTPUT_ORIGIN_TOP_LEFT);
413 chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
420 int LiveInputWrapper_connect_signal(lua_State* L)
422 assert(lua_gettop(L) == 2);
423 LiveInputWrapper **input = (LiveInputWrapper **)luaL_checkudata(L, 1, "LiveInputWrapper");
424 int signal_num = luaL_checknumber(L, 2);
425 (*input)->connect_signal(signal_num);
429 int ImageInput_new(lua_State* L)
431 assert(lua_gettop(L) == 1);
432 string filename = checkstdstring(L, 1);
433 return wrap_lua_object_nonowned<ImageInput>(L, "ImageInput", filename);
436 int VideoInput_new(lua_State* L)
438 assert(lua_gettop(L) == 2);
439 string filename = checkstdstring(L, 1);
440 int pixel_format = luaL_checknumber(L, 2);
441 if (pixel_format != bmusb::PixelFormat_8BitYCbCrPlanar &&
442 pixel_format != bmusb::PixelFormat_8BitBGRA) {
443 fprintf(stderr, "WARNING: Invalid enum %d used for video format, choosing Y'CbCr.\n",
445 pixel_format = bmusb::PixelFormat_8BitYCbCrPlanar;
447 int ret = wrap_lua_object_nonowned<FFmpegCapture>(L, "VideoInput", filename, global_flags.width, global_flags.height);
449 FFmpegCapture **capture = (FFmpegCapture **)lua_touserdata(L, -1);
450 (*capture)->set_pixel_format(bmusb::PixelFormat(pixel_format));
452 Theme *theme = get_theme_updata(L);
453 theme->register_video_input(*capture);
458 int VideoInput_rewind(lua_State* L)
460 assert(lua_gettop(L) == 1);
461 FFmpegCapture **video_input = (FFmpegCapture **)luaL_checkudata(L, 1, "VideoInput");
462 (*video_input)->rewind();
466 int VideoInput_disconnect(lua_State* L)
468 assert(lua_gettop(L) == 1);
469 FFmpegCapture **video_input = (FFmpegCapture **)luaL_checkudata(L, 1, "VideoInput");
470 (*video_input)->disconnect();
474 int VideoInput_change_rate(lua_State* L)
476 assert(lua_gettop(L) == 2);
477 FFmpegCapture **video_input = (FFmpegCapture **)luaL_checkudata(L, 1, "VideoInput");
478 double new_rate = luaL_checknumber(L, 2);
479 (*video_input)->change_rate(new_rate);
483 int VideoInput_get_signal_num(lua_State* L)
485 assert(lua_gettop(L) == 1);
486 FFmpegCapture **video_input = (FFmpegCapture **)luaL_checkudata(L, 1, "VideoInput");
487 lua_pushnumber(L, -1 - (*video_input)->get_card_index());
491 int HTMLInput_new(lua_State* L)
494 assert(lua_gettop(L) == 1);
495 string url = checkstdstring(L, 1);
496 int ret = wrap_lua_object_nonowned<CEFCapture>(L, "HTMLInput", url, global_flags.width, global_flags.height);
498 CEFCapture **capture = (CEFCapture **)lua_touserdata(L, -1);
499 Theme *theme = get_theme_updata(L);
500 theme->register_html_input(*capture);
504 fprintf(stderr, "This version of Nageru has been compiled without CEF support.\n");
505 fprintf(stderr, "HTMLInput is not available.\n");
511 int HTMLInput_set_url(lua_State* L)
513 assert(lua_gettop(L) == 2);
514 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
515 string new_url = checkstdstring(L, 2);
516 (*video_input)->set_url(new_url);
520 int HTMLInput_reload(lua_State* L)
522 assert(lua_gettop(L) == 1);
523 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
524 (*video_input)->reload();
528 int HTMLInput_set_max_fps(lua_State* L)
530 assert(lua_gettop(L) == 2);
531 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
532 int max_fps = lrint(luaL_checknumber(L, 2));
533 (*video_input)->set_max_fps(max_fps);
537 int HTMLInput_execute_javascript_async(lua_State* L)
539 assert(lua_gettop(L) == 2);
540 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
541 string js = checkstdstring(L, 2);
542 (*video_input)->execute_javascript_async(js);
546 int HTMLInput_resize(lua_State* L)
548 assert(lua_gettop(L) == 3);
549 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
550 unsigned width = lrint(luaL_checknumber(L, 2));
551 unsigned height = lrint(luaL_checknumber(L, 3));
552 (*video_input)->resize(width, height);
556 int HTMLInput_get_signal_num(lua_State* L)
558 assert(lua_gettop(L) == 1);
559 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
560 lua_pushnumber(L, -1 - (*video_input)->get_card_index());
565 int WhiteBalanceEffect_new(lua_State* L)
567 assert(lua_gettop(L) == 0);
568 return wrap_lua_object_nonowned<WhiteBalanceEffect>(L, "WhiteBalanceEffect");
571 int ResampleEffect_new(lua_State* L)
573 assert(lua_gettop(L) == 0);
574 return wrap_lua_object_nonowned<ResampleEffect>(L, "ResampleEffect");
577 int PaddingEffect_new(lua_State* L)
579 assert(lua_gettop(L) == 0);
580 return wrap_lua_object_nonowned<PaddingEffect>(L, "PaddingEffect");
583 int IntegralPaddingEffect_new(lua_State* L)
585 assert(lua_gettop(L) == 0);
586 return wrap_lua_object_nonowned<IntegralPaddingEffect>(L, "IntegralPaddingEffect");
589 int OverlayEffect_new(lua_State* L)
591 assert(lua_gettop(L) == 0);
592 return wrap_lua_object_nonowned<OverlayEffect>(L, "OverlayEffect");
595 int ResizeEffect_new(lua_State* L)
597 assert(lua_gettop(L) == 0);
598 return wrap_lua_object_nonowned<ResizeEffect>(L, "ResizeEffect");
601 int MultiplyEffect_new(lua_State* L)
603 assert(lua_gettop(L) == 0);
604 return wrap_lua_object_nonowned<MultiplyEffect>(L, "MultiplyEffect");
607 int MixEffect_new(lua_State* L)
609 assert(lua_gettop(L) == 0);
610 return wrap_lua_object_nonowned<MixEffect>(L, "MixEffect");
613 int InputStateInfo_get_width(lua_State* L)
615 assert(lua_gettop(L) == 2);
616 InputStateInfo *input_state_info = get_input_state_info(L, 1);
617 Theme *theme = get_theme_updata(L);
618 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
619 lua_pushnumber(L, input_state_info->last_width[signal_num]);
623 int InputStateInfo_get_height(lua_State* L)
625 assert(lua_gettop(L) == 2);
626 InputStateInfo *input_state_info = get_input_state_info(L, 1);
627 Theme *theme = get_theme_updata(L);
628 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
629 lua_pushnumber(L, input_state_info->last_height[signal_num]);
633 int InputStateInfo_get_interlaced(lua_State* L)
635 assert(lua_gettop(L) == 2);
636 InputStateInfo *input_state_info = get_input_state_info(L, 1);
637 Theme *theme = get_theme_updata(L);
638 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
639 lua_pushboolean(L, input_state_info->last_interlaced[signal_num]);
643 int InputStateInfo_get_has_signal(lua_State* L)
645 assert(lua_gettop(L) == 2);
646 InputStateInfo *input_state_info = get_input_state_info(L, 1);
647 Theme *theme = get_theme_updata(L);
648 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
649 lua_pushboolean(L, input_state_info->last_has_signal[signal_num]);
653 int InputStateInfo_get_is_connected(lua_State* L)
655 assert(lua_gettop(L) == 2);
656 InputStateInfo *input_state_info = get_input_state_info(L, 1);
657 Theme *theme = get_theme_updata(L);
658 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
659 lua_pushboolean(L, input_state_info->last_is_connected[signal_num]);
663 int InputStateInfo_get_frame_rate_nom(lua_State* L)
665 assert(lua_gettop(L) == 2);
666 InputStateInfo *input_state_info = get_input_state_info(L, 1);
667 Theme *theme = get_theme_updata(L);
668 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
669 lua_pushnumber(L, input_state_info->last_frame_rate_nom[signal_num]);
673 int InputStateInfo_get_frame_rate_den(lua_State* L)
675 assert(lua_gettop(L) == 2);
676 InputStateInfo *input_state_info = get_input_state_info(L, 1);
677 Theme *theme = get_theme_updata(L);
678 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
679 lua_pushnumber(L, input_state_info->last_frame_rate_den[signal_num]);
683 int Effect_set_float(lua_State *L)
685 assert(lua_gettop(L) == 3);
686 Effect *effect = (Effect *)get_effect(L, 1);
687 string key = checkstdstring(L, 2);
688 float value = luaL_checknumber(L, 3);
689 if (!effect->set_float(key, value)) {
690 luaL_error(L, "Effect refused set_float(\"%s\", %d) (invalid key?)", key.c_str(), int(value));
695 int Effect_set_int(lua_State *L)
697 assert(lua_gettop(L) == 3);
698 Effect *effect = (Effect *)get_effect(L, 1);
699 string key = checkstdstring(L, 2);
700 float value = luaL_checknumber(L, 3);
701 if (!effect->set_int(key, value)) {
702 luaL_error(L, "Effect refused set_int(\"%s\", %d) (invalid key?)", key.c_str(), int(value));
707 int Effect_set_vec3(lua_State *L)
709 assert(lua_gettop(L) == 5);
710 Effect *effect = (Effect *)get_effect(L, 1);
711 string key = checkstdstring(L, 2);
713 v[0] = luaL_checknumber(L, 3);
714 v[1] = luaL_checknumber(L, 4);
715 v[2] = luaL_checknumber(L, 5);
716 if (!effect->set_vec3(key, v)) {
717 luaL_error(L, "Effect refused set_vec3(\"%s\", %f, %f, %f) (invalid key?)", key.c_str(),
723 int Effect_set_vec4(lua_State *L)
725 assert(lua_gettop(L) == 6);
726 Effect *effect = (Effect *)get_effect(L, 1);
727 string key = checkstdstring(L, 2);
729 v[0] = luaL_checknumber(L, 3);
730 v[1] = luaL_checknumber(L, 4);
731 v[2] = luaL_checknumber(L, 5);
732 v[3] = luaL_checknumber(L, 6);
733 if (!effect->set_vec4(key, v)) {
734 luaL_error(L, "Effect refused set_vec4(\"%s\", %f, %f, %f, %f) (invalid key?)", key.c_str(),
735 v[0], v[1], v[2], v[3]);
740 const luaL_Reg EffectChain_funcs[] = {
741 { "new", EffectChain_new },
742 { "__gc", EffectChain_gc },
743 { "add_live_input", EffectChain_add_live_input },
744 { "add_video_input", EffectChain_add_video_input },
746 { "add_html_input", EffectChain_add_html_input },
748 { "add_effect", EffectChain_add_effect },
749 { "finalize", EffectChain_finalize },
753 const luaL_Reg LiveInputWrapper_funcs[] = {
754 { "connect_signal", LiveInputWrapper_connect_signal },
758 const luaL_Reg ImageInput_funcs[] = {
759 { "new", ImageInput_new },
760 { "set_float", Effect_set_float },
761 { "set_int", Effect_set_int },
762 { "set_vec3", Effect_set_vec3 },
763 { "set_vec4", Effect_set_vec4 },
767 const luaL_Reg VideoInput_funcs[] = {
768 { "new", VideoInput_new },
769 { "rewind", VideoInput_rewind },
770 { "disconnect", VideoInput_disconnect },
771 { "change_rate", VideoInput_change_rate },
772 { "get_signal_num", VideoInput_get_signal_num },
776 const luaL_Reg HTMLInput_funcs[] = {
777 { "new", HTMLInput_new },
779 { "set_url", HTMLInput_set_url },
780 { "reload", HTMLInput_reload },
781 { "set_max_fps", HTMLInput_set_max_fps },
782 { "execute_javascript_async", HTMLInput_execute_javascript_async },
783 { "resize", HTMLInput_resize },
784 { "get_signal_num", HTMLInput_get_signal_num },
789 const luaL_Reg WhiteBalanceEffect_funcs[] = {
790 { "new", WhiteBalanceEffect_new },
791 { "set_float", Effect_set_float },
792 { "set_int", Effect_set_int },
793 { "set_vec3", Effect_set_vec3 },
794 { "set_vec4", Effect_set_vec4 },
798 const luaL_Reg ResampleEffect_funcs[] = {
799 { "new", ResampleEffect_new },
800 { "set_float", Effect_set_float },
801 { "set_int", Effect_set_int },
802 { "set_vec3", Effect_set_vec3 },
803 { "set_vec4", Effect_set_vec4 },
807 const luaL_Reg PaddingEffect_funcs[] = {
808 { "new", PaddingEffect_new },
809 { "set_float", Effect_set_float },
810 { "set_int", Effect_set_int },
811 { "set_vec3", Effect_set_vec3 },
812 { "set_vec4", Effect_set_vec4 },
816 const luaL_Reg IntegralPaddingEffect_funcs[] = {
817 { "new", IntegralPaddingEffect_new },
818 { "set_float", Effect_set_float },
819 { "set_int", Effect_set_int },
820 { "set_vec3", Effect_set_vec3 },
821 { "set_vec4", Effect_set_vec4 },
825 const luaL_Reg OverlayEffect_funcs[] = {
826 { "new", OverlayEffect_new },
827 { "set_float", Effect_set_float },
828 { "set_int", Effect_set_int },
829 { "set_vec3", Effect_set_vec3 },
830 { "set_vec4", Effect_set_vec4 },
834 const luaL_Reg ResizeEffect_funcs[] = {
835 { "new", ResizeEffect_new },
836 { "set_float", Effect_set_float },
837 { "set_int", Effect_set_int },
838 { "set_vec3", Effect_set_vec3 },
839 { "set_vec4", Effect_set_vec4 },
843 const luaL_Reg MultiplyEffect_funcs[] = {
844 { "new", MultiplyEffect_new },
845 { "set_float", Effect_set_float },
846 { "set_int", Effect_set_int },
847 { "set_vec3", Effect_set_vec3 },
848 { "set_vec4", Effect_set_vec4 },
852 const luaL_Reg MixEffect_funcs[] = {
853 { "new", MixEffect_new },
854 { "set_float", Effect_set_float },
855 { "set_int", Effect_set_int },
856 { "set_vec3", Effect_set_vec3 },
857 { "set_vec4", Effect_set_vec4 },
861 const luaL_Reg InputStateInfo_funcs[] = {
862 { "get_width", InputStateInfo_get_width },
863 { "get_height", InputStateInfo_get_height },
864 { "get_interlaced", InputStateInfo_get_interlaced },
865 { "get_has_signal", InputStateInfo_get_has_signal },
866 { "get_is_connected", InputStateInfo_get_is_connected },
867 { "get_frame_rate_nom", InputStateInfo_get_frame_rate_nom },
868 { "get_frame_rate_den", InputStateInfo_get_frame_rate_den },
872 const luaL_Reg ThemeMenu_funcs[] = {
873 { "set", ThemeMenu_set },
879 LiveInputWrapper::LiveInputWrapper(Theme *theme, EffectChain *chain, bmusb::PixelFormat pixel_format, bool override_bounce, bool deinterlace)
881 pixel_format(pixel_format),
882 deinterlace(deinterlace)
884 ImageFormat inout_format;
885 inout_format.color_space = COLORSPACE_sRGB;
887 // Gamma curve depends on the input signal, and we don't really get any
888 // indications. A camera would be expected to do Rec. 709, but
889 // I haven't checked if any do in practice. However, computers _do_ output
890 // in sRGB gamma (ie., they don't convert from sRGB to Rec. 709), and
891 // I wouldn't really be surprised if most non-professional cameras do, too.
892 // So we pick sRGB as the least evil here.
893 inout_format.gamma_curve = GAMMA_sRGB;
897 deinterlace_effect = new movit::DeinterlaceEffect();
899 // As per the comments in deinterlace_effect.h, we turn this off.
900 // The most likely interlaced input for us is either a camera
901 // (where it's fine to turn it off) or a laptop (where it _should_
903 CHECK(deinterlace_effect->set_int("enable_spatial_interlacing_check", 0));
905 num_inputs = deinterlace_effect->num_inputs();
906 assert(num_inputs == FRAME_HISTORY_LENGTH);
911 if (pixel_format == bmusb::PixelFormat_8BitBGRA) {
912 for (unsigned i = 0; i < num_inputs; ++i) {
913 // We upload our textures ourselves, and Movit swaps
914 // R and B in the shader if we specify BGRA, so lie and say RGBA.
915 if (global_flags.can_disable_srgb_decoder) {
916 rgba_inputs.push_back(new sRGBSwitchingFlatInput(inout_format, FORMAT_RGBA_POSTMULTIPLIED_ALPHA, GL_UNSIGNED_BYTE, global_flags.width, global_flags.height));
918 rgba_inputs.push_back(new NonsRGBCapableFlatInput(inout_format, FORMAT_RGBA_POSTMULTIPLIED_ALPHA, GL_UNSIGNED_BYTE, global_flags.width, global_flags.height));
920 chain->add_input(rgba_inputs.back());
924 vector<Effect *> reverse_inputs(rgba_inputs.rbegin(), rgba_inputs.rend());
925 chain->add_effect(deinterlace_effect, reverse_inputs);
928 assert(pixel_format == bmusb::PixelFormat_8BitYCbCr ||
929 pixel_format == bmusb::PixelFormat_10BitYCbCr ||
930 pixel_format == bmusb::PixelFormat_8BitYCbCrPlanar);
932 // Most of these settings will be overridden later if using PixelFormat_8BitYCbCrPlanar.
933 input_ycbcr_format.chroma_subsampling_x = (pixel_format == bmusb::PixelFormat_10BitYCbCr) ? 1 : 2;
934 input_ycbcr_format.chroma_subsampling_y = 1;
935 input_ycbcr_format.num_levels = (pixel_format == bmusb::PixelFormat_10BitYCbCr) ? 1024 : 256;
936 input_ycbcr_format.cb_x_position = 0.0;
937 input_ycbcr_format.cr_x_position = 0.0;
938 input_ycbcr_format.cb_y_position = 0.5;
939 input_ycbcr_format.cr_y_position = 0.5;
940 input_ycbcr_format.luma_coefficients = YCBCR_REC_709; // Will be overridden later even if not planar.
941 input_ycbcr_format.full_range = false; // Will be overridden later even if not planar.
943 for (unsigned i = 0; i < num_inputs; ++i) {
944 // When using 10-bit input, we're converting to interleaved through v210Converter.
945 YCbCrInputSplitting splitting;
946 if (pixel_format == bmusb::PixelFormat_10BitYCbCr) {
947 splitting = YCBCR_INPUT_INTERLEAVED;
948 } else if (pixel_format == bmusb::PixelFormat_8BitYCbCr) {
949 splitting = YCBCR_INPUT_SPLIT_Y_AND_CBCR;
951 splitting = YCBCR_INPUT_PLANAR;
953 if (override_bounce) {
954 ycbcr_inputs.push_back(new NonBouncingYCbCrInput(inout_format, input_ycbcr_format, global_flags.width, global_flags.height, splitting));
956 ycbcr_inputs.push_back(new YCbCrInput(inout_format, input_ycbcr_format, global_flags.width, global_flags.height, splitting));
958 chain->add_input(ycbcr_inputs.back());
962 vector<Effect *> reverse_inputs(ycbcr_inputs.rbegin(), ycbcr_inputs.rend());
963 chain->add_effect(deinterlace_effect, reverse_inputs);
968 void LiveInputWrapper::connect_signal(int signal_num)
970 if (global_mixer == nullptr) {
975 signal_num = theme->map_signal(signal_num);
976 connect_signal_raw(signal_num, *theme->input_state);
979 void LiveInputWrapper::connect_signal_raw(int signal_num, const InputState &input_state)
981 BufferedFrame first_frame = input_state.buffered_frames[signal_num][0];
982 if (first_frame.frame == nullptr) {
986 unsigned width, height;
988 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)first_frame.frame->userdata;
989 width = userdata->last_width[first_frame.field_number];
990 height = userdata->last_height[first_frame.field_number];
993 movit::YCbCrLumaCoefficients ycbcr_coefficients = input_state.ycbcr_coefficients[signal_num];
994 bool full_range = input_state.full_range[signal_num];
996 if (input_state.ycbcr_coefficients_auto[signal_num]) {
999 // The Blackmagic driver docs claim that the device outputs Y'CbCr
1000 // according to Rec. 601, but this seems to indicate the subsampling
1001 // positions only, as they publish Y'CbCr → RGB formulas that are
1002 // different for HD and SD (corresponding to Rec. 709 and 601, respectively),
1003 // and a Lenovo X1 gen 3 I used to test definitely outputs Rec. 709
1004 // (at least up to rounding error). Other devices seem to use Rec. 601
1005 // even on HD resolutions. Nevertheless, Rec. 709 _is_ the right choice
1006 // for HD, so we default to that if the user hasn't set anything.
1007 if (height >= 720) {
1008 ycbcr_coefficients = YCBCR_REC_709;
1010 ycbcr_coefficients = YCBCR_REC_601;
1014 // This is a global, but it doesn't really matter.
1015 input_ycbcr_format.luma_coefficients = ycbcr_coefficients;
1016 input_ycbcr_format.full_range = full_range;
1018 BufferedFrame last_good_frame = first_frame;
1019 for (unsigned i = 0; i < max(ycbcr_inputs.size(), rgba_inputs.size()); ++i) {
1020 BufferedFrame frame = input_state.buffered_frames[signal_num][i];
1021 if (frame.frame == nullptr) {
1022 // Not enough data; reuse last frame (well, field).
1023 // This is suboptimal, but we have nothing better.
1024 frame = last_good_frame;
1026 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
1028 unsigned this_width = userdata->last_width[frame.field_number];
1029 unsigned this_height = userdata->last_height[frame.field_number];
1030 if (this_width != width || this_height != height) {
1031 // Resolution changed; reuse last frame/field.
1032 frame = last_good_frame;
1033 userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
1036 assert(userdata->pixel_format == pixel_format);
1037 switch (pixel_format) {
1038 case bmusb::PixelFormat_8BitYCbCr:
1039 ycbcr_inputs[i]->set_texture_num(0, userdata->tex_y[frame.field_number]);
1040 ycbcr_inputs[i]->set_texture_num(1, userdata->tex_cbcr[frame.field_number]);
1041 ycbcr_inputs[i]->change_ycbcr_format(input_ycbcr_format);
1042 ycbcr_inputs[i]->set_width(width);
1043 ycbcr_inputs[i]->set_height(height);
1045 case bmusb::PixelFormat_8BitYCbCrPlanar:
1046 ycbcr_inputs[i]->set_texture_num(0, userdata->tex_y[frame.field_number]);
1047 ycbcr_inputs[i]->set_texture_num(1, userdata->tex_cb[frame.field_number]);
1048 ycbcr_inputs[i]->set_texture_num(2, userdata->tex_cr[frame.field_number]);
1049 ycbcr_inputs[i]->change_ycbcr_format(userdata->ycbcr_format);
1050 ycbcr_inputs[i]->set_width(width);
1051 ycbcr_inputs[i]->set_height(height);
1053 case bmusb::PixelFormat_10BitYCbCr:
1054 ycbcr_inputs[i]->set_texture_num(0, userdata->tex_444[frame.field_number]);
1055 ycbcr_inputs[i]->change_ycbcr_format(input_ycbcr_format);
1056 ycbcr_inputs[i]->set_width(width);
1057 ycbcr_inputs[i]->set_height(height);
1059 case bmusb::PixelFormat_8BitBGRA:
1060 rgba_inputs[i]->set_texture_num(userdata->tex_rgba[frame.field_number]);
1061 rgba_inputs[i]->set_width(width);
1062 rgba_inputs[i]->set_height(height);
1068 last_good_frame = frame;
1072 BufferedFrame frame = input_state.buffered_frames[signal_num][0];
1073 CHECK(deinterlace_effect->set_int("current_field_position", frame.field_number));
1079 int call_num_channels(lua_State *L)
1081 lua_getglobal(L, "num_channels");
1083 if (lua_pcall(L, 0, 1, 0) != 0) {
1084 fprintf(stderr, "error running function `num_channels': %s\n", lua_tostring(L, -1));
1088 int num_channels = luaL_checknumber(L, 1);
1090 assert(lua_gettop(L) == 0);
1091 return num_channels;
1096 Theme::Theme(const string &filename, const vector<string> &search_dirs, ResourcePool *resource_pool, unsigned num_cards)
1097 : resource_pool(resource_pool), num_cards(num_cards), signal_to_card_mapping(global_flags.default_stream_mapping)
1099 L = luaL_newstate();
1102 // Search through all directories until we find a file that will load
1103 // (as in, does not return LUA_ERRFILE); then run it. We store load errors
1104 // from all the attempts, and show them once we know we can't find any of them.
1106 vector<string> errors;
1107 bool success = false;
1109 vector<string> real_search_dirs;
1110 if (!filename.empty() && filename[0] == '/') {
1111 real_search_dirs.push_back("");
1113 real_search_dirs = search_dirs;
1118 for (const string &dir : real_search_dirs) {
1122 path = dir + "/" + filename;
1124 int err = luaL_loadfile(L, path.c_str());
1126 // Save the theme for when we're actually going to run it
1127 // (we need to set up the right environment below first,
1128 // and we couldn't do that before, because we didn't know the
1129 // path to put in Nageru.THEME_PATH).
1130 theme_code_ref = luaL_ref(L, LUA_REGISTRYINDEX);
1131 assert(lua_gettop(L) == 0);
1136 errors.push_back(lua_tostring(L, -1));
1138 if (err != LUA_ERRFILE) {
1139 // The file actually loaded, but failed to parse somehow. Abort; don't try the next one.
1145 for (const string &error : errors) {
1146 fprintf(stderr, "%s\n", error.c_str());
1150 assert(lua_gettop(L) == 0);
1152 // Make sure the path exposed to the theme (as Nageru.THEME_PATH;
1153 // can be useful for locating files when talking to CEF) is absolute.
1154 // In a sense, it would be nice if realpath() had a mode not to
1155 // resolve symlinks, but it doesn't, so we only call it if we don't
1156 // already have an absolute path (which may leave ../ elements etc.).
1157 if (path[0] == '/') {
1160 char *absolute_theme_path = realpath(path.c_str(), nullptr);
1161 theme_path = absolute_theme_path;
1162 free(absolute_theme_path);
1165 // Set up the API we provide.
1166 register_constants();
1167 register_class("EffectChain", EffectChain_funcs);
1168 register_class("LiveInputWrapper", LiveInputWrapper_funcs);
1169 register_class("ImageInput", ImageInput_funcs);
1170 register_class("VideoInput", VideoInput_funcs);
1171 register_class("HTMLInput", HTMLInput_funcs);
1172 register_class("WhiteBalanceEffect", WhiteBalanceEffect_funcs);
1173 register_class("ResampleEffect", ResampleEffect_funcs);
1174 register_class("PaddingEffect", PaddingEffect_funcs);
1175 register_class("IntegralPaddingEffect", IntegralPaddingEffect_funcs);
1176 register_class("OverlayEffect", OverlayEffect_funcs);
1177 register_class("ResizeEffect", ResizeEffect_funcs);
1178 register_class("MultiplyEffect", MultiplyEffect_funcs);
1179 register_class("MixEffect", MixEffect_funcs);
1180 register_class("InputStateInfo", InputStateInfo_funcs);
1181 register_class("ThemeMenu", ThemeMenu_funcs);
1183 // Now actually run the theme to get everything set up.
1184 lua_rawgeti(L, LUA_REGISTRYINDEX, theme_code_ref);
1185 luaL_unref(L, LUA_REGISTRYINDEX, theme_code_ref);
1186 if (lua_pcall(L, 0, 0, 0)) {
1187 fprintf(stderr, "Error when running %s: %s\n", path.c_str(), lua_tostring(L, -1));
1190 assert(lua_gettop(L) == 0);
1192 // Ask it for the number of channels.
1193 num_channels = call_num_channels(L);
1201 void Theme::register_constants()
1203 // Set Nageru.VIDEO_FORMAT_BGRA = bmusb::PixelFormat_8BitBGRA, etc.
1204 const vector<pair<string, int>> num_constants = {
1205 { "VIDEO_FORMAT_BGRA", bmusb::PixelFormat_8BitBGRA },
1206 { "VIDEO_FORMAT_YCBCR", bmusb::PixelFormat_8BitYCbCrPlanar },
1208 const vector<pair<string, string>> str_constants = {
1209 { "THEME_PATH", theme_path },
1212 lua_newtable(L); // t = {}
1214 for (const pair<string, int> &constant : num_constants) {
1215 lua_pushstring(L, constant.first.c_str());
1216 lua_pushinteger(L, constant.second);
1217 lua_settable(L, 1); // t[key] = value
1219 for (const pair<string, string> &constant : str_constants) {
1220 lua_pushstring(L, constant.first.c_str());
1221 lua_pushstring(L, constant.second.c_str());
1222 lua_settable(L, 1); // t[key] = value
1225 lua_setglobal(L, "Nageru"); // Nageru = t
1226 assert(lua_gettop(L) == 0);
1229 void Theme::register_class(const char *class_name, const luaL_Reg *funcs)
1231 assert(lua_gettop(L) == 0);
1232 luaL_newmetatable(L, class_name); // mt = {}
1233 lua_pushlightuserdata(L, this);
1234 luaL_setfuncs(L, funcs, 1); // for (name,f in funcs) { mt[name] = f, with upvalue {theme} }
1235 lua_pushvalue(L, -1);
1236 lua_setfield(L, -2, "__index"); // mt.__index = mt
1237 lua_setglobal(L, class_name); // ClassName = mt
1238 assert(lua_gettop(L) == 0);
1241 Theme::Chain Theme::get_chain(unsigned num, float t, unsigned width, unsigned height, InputState input_state)
1245 unique_lock<mutex> lock(m);
1246 assert(lua_gettop(L) == 0);
1247 lua_getglobal(L, "get_chain"); /* function to be called */
1248 lua_pushnumber(L, num);
1249 lua_pushnumber(L, t);
1250 lua_pushnumber(L, width);
1251 lua_pushnumber(L, height);
1252 wrap_lua_object<InputStateInfo>(L, "InputStateInfo", input_state);
1254 if (lua_pcall(L, 5, 2, 0) != 0) {
1255 fprintf(stderr, "error running function `get_chain': %s\n", lua_tostring(L, -1));
1259 EffectChain *effect_chain = (EffectChain *)luaL_testudata(L, -2, "EffectChain");
1260 if (effect_chain == nullptr) {
1261 fprintf(stderr, "get_chain() for chain number %d did not return an EffectChain\n",
1265 chain.chain = effect_chain;
1266 if (!lua_isfunction(L, -1)) {
1267 fprintf(stderr, "Argument #-1 should be a function\n");
1270 lua_pushvalue(L, -1);
1271 shared_ptr<LuaRefWithDeleter> funcref(new LuaRefWithDeleter(&m, L, luaL_ref(L, LUA_REGISTRYINDEX)));
1273 assert(lua_gettop(L) == 0);
1275 chain.setup_chain = [this, funcref, input_state, effect_chain]{
1276 unique_lock<mutex> lock(m);
1278 assert(this->input_state == nullptr);
1279 this->input_state = &input_state;
1281 // Set up state, including connecting signals.
1282 lua_rawgeti(L, LUA_REGISTRYINDEX, funcref->get());
1283 if (lua_pcall(L, 0, 0, 0) != 0) {
1284 fprintf(stderr, "error running chain setup callback: %s\n", lua_tostring(L, -1));
1287 assert(lua_gettop(L) == 0);
1289 // The theme can't (or at least shouldn't!) call connect_signal() on
1290 // each FFmpeg or CEF input, so we'll do it here.
1291 if (video_signal_connections.count(effect_chain)) {
1292 for (const VideoSignalConnection &conn : video_signal_connections[effect_chain]) {
1293 conn.wrapper->connect_signal_raw(conn.source->get_card_index(), input_state);
1297 if (html_signal_connections.count(effect_chain)) {
1298 for (const CEFSignalConnection &conn : html_signal_connections[effect_chain]) {
1299 conn.wrapper->connect_signal_raw(conn.source->get_card_index(), input_state);
1304 this->input_state = nullptr;
1307 // TODO: Can we do better, e.g. by running setup_chain() and seeing what it references?
1308 // Actually, setup_chain does maybe hold all the references we need now anyway?
1309 chain.input_frames.reserve(num_cards * FRAME_HISTORY_LENGTH);
1310 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
1311 for (unsigned frame_num = 0; frame_num < FRAME_HISTORY_LENGTH; ++frame_num) {
1312 chain.input_frames.push_back(input_state.buffered_frames[card_index][frame_num].frame);
1319 string Theme::get_channel_name(unsigned channel)
1321 unique_lock<mutex> lock(m);
1322 lua_getglobal(L, "channel_name");
1323 lua_pushnumber(L, channel);
1324 if (lua_pcall(L, 1, 1, 0) != 0) {
1325 fprintf(stderr, "error running function `channel_name': %s\n", lua_tostring(L, -1));
1328 const char *ret = lua_tostring(L, -1);
1329 if (ret == nullptr) {
1330 fprintf(stderr, "function `channel_name' returned nil for channel %d\n", channel);
1334 string retstr = ret;
1336 assert(lua_gettop(L) == 0);
1340 int Theme::get_channel_signal(unsigned channel)
1342 unique_lock<mutex> lock(m);
1343 lua_getglobal(L, "channel_signal");
1344 lua_pushnumber(L, channel);
1345 if (lua_pcall(L, 1, 1, 0) != 0) {
1346 fprintf(stderr, "error running function `channel_signal': %s\n", lua_tostring(L, -1));
1350 int ret = luaL_checknumber(L, 1);
1352 assert(lua_gettop(L) == 0);
1356 std::string Theme::get_channel_color(unsigned channel)
1358 unique_lock<mutex> lock(m);
1359 lua_getglobal(L, "channel_color");
1360 lua_pushnumber(L, channel);
1361 if (lua_pcall(L, 1, 1, 0) != 0) {
1362 fprintf(stderr, "error running function `channel_color': %s\n", lua_tostring(L, -1));
1366 const char *ret = lua_tostring(L, -1);
1367 if (ret == nullptr) {
1368 fprintf(stderr, "function `channel_color' returned nil for channel %d\n", channel);
1372 string retstr = ret;
1374 assert(lua_gettop(L) == 0);
1378 bool Theme::get_supports_set_wb(unsigned channel)
1380 unique_lock<mutex> lock(m);
1381 lua_getglobal(L, "supports_set_wb");
1382 lua_pushnumber(L, channel);
1383 if (lua_pcall(L, 1, 1, 0) != 0) {
1384 fprintf(stderr, "error running function `supports_set_wb': %s\n", lua_tostring(L, -1));
1388 bool ret = checkbool(L, -1);
1390 assert(lua_gettop(L) == 0);
1394 void Theme::set_wb(unsigned channel, double r, double g, double b)
1396 unique_lock<mutex> lock(m);
1397 lua_getglobal(L, "set_wb");
1398 lua_pushnumber(L, channel);
1399 lua_pushnumber(L, r);
1400 lua_pushnumber(L, g);
1401 lua_pushnumber(L, b);
1402 if (lua_pcall(L, 4, 0, 0) != 0) {
1403 fprintf(stderr, "error running function `set_wb': %s\n", lua_tostring(L, -1));
1407 assert(lua_gettop(L) == 0);
1410 vector<string> Theme::get_transition_names(float t)
1412 unique_lock<mutex> lock(m);
1413 lua_getglobal(L, "get_transitions");
1414 lua_pushnumber(L, t);
1415 if (lua_pcall(L, 1, 1, 0) != 0) {
1416 fprintf(stderr, "error running function `get_transitions': %s\n", lua_tostring(L, -1));
1422 while (lua_next(L, -2) != 0) {
1423 ret.push_back(lua_tostring(L, -1));
1427 assert(lua_gettop(L) == 0);
1431 int Theme::map_signal(int signal_num)
1433 // Negative numbers map to raw signals.
1434 if (signal_num < 0) {
1435 return -1 - signal_num;
1438 unique_lock<mutex> lock(map_m);
1439 if (signal_to_card_mapping.count(signal_num)) {
1440 return signal_to_card_mapping[signal_num];
1444 if (global_flags.output_card != -1 && num_cards > 1) {
1445 // Try to exclude the output card from the default card_index.
1446 card_index = signal_num % (num_cards - 1);
1447 if (card_index >= global_flags.output_card) {
1450 if (signal_num >= int(num_cards - 1)) {
1451 fprintf(stderr, "WARNING: Theme asked for input %d, but we only have %u input card(s) (card %d is busy with output).\n",
1452 signal_num, num_cards - 1, global_flags.output_card);
1453 fprintf(stderr, "Mapping to card %d instead.\n", card_index);
1456 card_index = signal_num % num_cards;
1457 if (signal_num >= int(num_cards)) {
1458 fprintf(stderr, "WARNING: Theme asked for input %d, but we only have %u card(s).\n", signal_num, num_cards);
1459 fprintf(stderr, "Mapping to card %d instead.\n", card_index);
1462 signal_to_card_mapping[signal_num] = card_index;
1466 void Theme::set_signal_mapping(int signal_num, int card_num)
1468 unique_lock<mutex> lock(map_m);
1469 assert(card_num < int(num_cards));
1470 signal_to_card_mapping[signal_num] = card_num;
1473 void Theme::transition_clicked(int transition_num, float t)
1475 unique_lock<mutex> lock(m);
1476 lua_getglobal(L, "transition_clicked");
1477 lua_pushnumber(L, transition_num);
1478 lua_pushnumber(L, t);
1480 if (lua_pcall(L, 2, 0, 0) != 0) {
1481 fprintf(stderr, "error running function `transition_clicked': %s\n", lua_tostring(L, -1));
1484 assert(lua_gettop(L) == 0);
1487 void Theme::channel_clicked(int preview_num)
1489 unique_lock<mutex> lock(m);
1490 lua_getglobal(L, "channel_clicked");
1491 lua_pushnumber(L, preview_num);
1493 if (lua_pcall(L, 1, 0, 0) != 0) {
1494 fprintf(stderr, "error running function `channel_clicked': %s\n", lua_tostring(L, -1));
1497 assert(lua_gettop(L) == 0);
1500 int Theme::set_theme_menu(lua_State *L)
1502 for (const Theme::MenuEntry &entry : theme_menu) {
1503 luaL_unref(L, LUA_REGISTRYINDEX, entry.lua_ref);
1507 int num_elements = lua_gettop(L);
1508 for (int i = 1; i <= num_elements; ++i) {
1509 lua_rawgeti(L, i, 1);
1510 const string text = checkstdstring(L, -1);
1513 lua_rawgeti(L, i, 2);
1514 luaL_checktype(L, -1, LUA_TFUNCTION);
1515 int ref = luaL_ref(L, LUA_REGISTRYINDEX);
1517 theme_menu.push_back(MenuEntry{ text, ref });
1519 lua_pop(L, num_elements);
1520 assert(lua_gettop(L) == 0);
1522 if (theme_menu_callback != nullptr) {
1523 theme_menu_callback();
1529 void Theme::theme_menu_entry_clicked(int lua_ref)
1531 unique_lock<mutex> lock(m);
1532 lua_rawgeti(L, LUA_REGISTRYINDEX, lua_ref);
1533 if (lua_pcall(L, 0, 0, 0) != 0) {
1534 fprintf(stderr, "error running menu callback: %s\n", lua_tostring(L, -1));