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"
41 #if !defined LUA_VERSION_NUM || LUA_VERSION_NUM==501
43 // Compatibility shims for LuaJIT 2.0 (LuaJIT 2.1 implements the entire Lua 5.2 API).
44 // Adapted from https://github.com/keplerproject/lua-compat-5.2/blob/master/c-api/compat-5.2.c
45 // and licensed as follows:
47 // The MIT License (MIT)
49 // Copyright (c) 2013 Hisham Muhammad
51 // Permission is hereby granted, free of charge, to any person obtaining a copy of
52 // this software and associated documentation files (the "Software"), to deal in
53 // the Software without restriction, including without limitation the rights to
54 // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
55 // the Software, and to permit persons to whom the Software is furnished to do so,
56 // subject to the following conditions:
58 // The above copyright notice and this permission notice shall be included in all
59 // copies or substantial portions of the Software.
61 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
62 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
63 // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
64 // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
65 // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
66 // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
69 ** Adapted from Lua 5.2.0
71 void luaL_setfuncs(lua_State *L, const luaL_Reg *l, int nup) {
72 luaL_checkstack(L, nup+1, "too many upvalues");
73 for (; l->name != NULL; l++) { /* fill the table with given functions */
75 lua_pushstring(L, l->name);
76 for (i = 0; i < nup; i++) /* copy upvalues to the top */
77 lua_pushvalue(L, -(nup + 1));
78 lua_pushcclosure(L, l->func, nup); /* closure with those upvalues */
79 lua_settable(L, -(nup + 3)); /* table must be below the upvalues, the name and the closure */
81 lua_pop(L, nup); /* remove upvalues */
84 void *luaL_testudata(lua_State *L, int i, const char *tname) {
85 void *p = lua_touserdata(L, i);
86 luaL_checkstack(L, 2, "not enough stack slots");
87 if (p == NULL || !lua_getmetatable(L, i))
91 luaL_getmetatable(L, tname);
92 res = lua_rawequal(L, -1, -2);
109 using namespace movit;
111 extern Mixer *global_mixer;
113 Theme *get_theme_updata(lua_State* L)
115 luaL_checktype(L, lua_upvalueindex(1), LUA_TLIGHTUSERDATA);
116 return (Theme *)lua_touserdata(L, lua_upvalueindex(1));
119 int ThemeMenu_set(lua_State *L)
121 Theme *theme = get_theme_updata(L);
122 return theme->set_theme_menu(L);
127 // Contains basically the same data as InputState, but does not hold on to
128 // a reference to the frames. This is important so that we can release them
129 // without having to wait for Lua's GC.
130 struct InputStateInfo {
131 InputStateInfo(const InputState& input_state);
133 unsigned last_width[MAX_VIDEO_CARDS], last_height[MAX_VIDEO_CARDS];
134 bool last_interlaced[MAX_VIDEO_CARDS], last_has_signal[MAX_VIDEO_CARDS], last_is_connected[MAX_VIDEO_CARDS];
135 unsigned last_frame_rate_nom[MAX_VIDEO_CARDS], last_frame_rate_den[MAX_VIDEO_CARDS];
138 InputStateInfo::InputStateInfo(const InputState &input_state)
140 for (unsigned signal_num = 0; signal_num < MAX_VIDEO_CARDS; ++signal_num) {
141 BufferedFrame frame = input_state.buffered_frames[signal_num][0];
142 if (frame.frame == nullptr) {
143 last_width[signal_num] = last_height[signal_num] = 0;
144 last_interlaced[signal_num] = false;
145 last_has_signal[signal_num] = false;
146 last_is_connected[signal_num] = false;
149 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
150 last_width[signal_num] = userdata->last_width[frame.field_number];
151 last_height[signal_num] = userdata->last_height[frame.field_number];
152 last_interlaced[signal_num] = userdata->last_interlaced;
153 last_has_signal[signal_num] = userdata->last_has_signal;
154 last_is_connected[signal_num] = userdata->last_is_connected;
155 last_frame_rate_nom[signal_num] = userdata->last_frame_rate_nom;
156 last_frame_rate_den[signal_num] = userdata->last_frame_rate_den;
160 class LuaRefWithDeleter {
162 LuaRefWithDeleter(mutex *m, lua_State *L, int ref) : m(m), L(L), ref(ref) {}
163 ~LuaRefWithDeleter() {
164 unique_lock<mutex> lock(*m);
165 luaL_unref(L, LUA_REGISTRYINDEX, ref);
167 int get() const { return ref; }
170 LuaRefWithDeleter(const LuaRefWithDeleter &) = delete;
177 template<class T, class... Args>
178 int wrap_lua_object(lua_State* L, const char *class_name, Args&&... args)
180 // Construct the C++ object and put it on the stack.
181 void *mem = lua_newuserdata(L, sizeof(T));
182 new(mem) T(forward<Args>(args)...);
184 // Look up the metatable named <class_name>, and set it on the new object.
185 luaL_getmetatable(L, class_name);
186 lua_setmetatable(L, -2);
191 // Like wrap_lua_object, but the object is not owned by Lua; ie. it's not freed
192 // by Lua GC. This is typically the case for Effects, which are owned by EffectChain
193 // and expected to be destructed by it. The object will be of type T** instead of T*
194 // when exposed to Lua.
196 // Note that we currently leak if you allocate an Effect in this way and never call
197 // add_effect. We should see if there's a way to e.g. set __gc on it at construction time
198 // and then release that once add_effect() takes ownership.
199 template<class T, class... Args>
200 int wrap_lua_object_nonowned(lua_State* L, const char *class_name, Args&&... args)
202 // Construct the pointer ot the C++ object and put it on the stack.
203 T **obj = (T **)lua_newuserdata(L, sizeof(T *));
204 *obj = new T(forward<Args>(args)...);
206 // Look up the metatable named <class_name>, and set it on the new object.
207 luaL_getmetatable(L, class_name);
208 lua_setmetatable(L, -2);
213 Effect *get_effect(lua_State *L, int idx)
215 if (luaL_testudata(L, idx, "WhiteBalanceEffect") ||
216 luaL_testudata(L, idx, "ResampleEffect") ||
217 luaL_testudata(L, idx, "PaddingEffect") ||
218 luaL_testudata(L, idx, "IntegralPaddingEffect") ||
219 luaL_testudata(L, idx, "OverlayEffect") ||
220 luaL_testudata(L, idx, "ResizeEffect") ||
221 luaL_testudata(L, idx, "MultiplyEffect") ||
222 luaL_testudata(L, idx, "MixEffect") ||
223 luaL_testudata(L, idx, "LiftGammaGainEffect") ||
224 luaL_testudata(L, idx, "ImageInput")) {
225 return *(Effect **)lua_touserdata(L, idx);
227 luaL_error(L, "Error: Index #%d was not an Effect type\n", idx);
231 InputStateInfo *get_input_state_info(lua_State *L, int idx)
233 if (luaL_testudata(L, idx, "InputStateInfo")) {
234 return (InputStateInfo *)lua_touserdata(L, idx);
236 luaL_error(L, "Error: Index #%d was not InputStateInfo\n", idx);
240 bool checkbool(lua_State* L, int idx)
242 luaL_checktype(L, idx, LUA_TBOOLEAN);
243 return lua_toboolean(L, idx);
246 string checkstdstring(lua_State *L, int index)
249 const char* cstr = lua_tolstring(L, index, &len);
250 return string(cstr, len);
253 int EffectChain_new(lua_State* L)
255 assert(lua_gettop(L) == 2);
256 Theme *theme = get_theme_updata(L);
257 int aspect_w = luaL_checknumber(L, 1);
258 int aspect_h = luaL_checknumber(L, 2);
260 return wrap_lua_object<EffectChain>(L, "EffectChain", aspect_w, aspect_h, theme->get_resource_pool());
263 int EffectChain_gc(lua_State* L)
265 assert(lua_gettop(L) == 1);
266 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
267 chain->~EffectChain();
271 int EffectChain_add_live_input(lua_State* L)
273 assert(lua_gettop(L) == 3);
274 Theme *theme = get_theme_updata(L);
275 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
276 bool override_bounce = checkbool(L, 2);
277 bool deinterlace = checkbool(L, 3);
278 bmusb::PixelFormat pixel_format = global_flags.ten_bit_input ? bmusb::PixelFormat_10BitYCbCr : bmusb::PixelFormat_8BitYCbCr;
280 // Needs to be nonowned to match add_video_input (see below).
281 return wrap_lua_object_nonowned<LiveInputWrapper>(L, "LiveInputWrapper", theme, chain, pixel_format, override_bounce, deinterlace, /*user_connectable=*/true);
284 int EffectChain_add_video_input(lua_State* L)
286 assert(lua_gettop(L) == 3);
287 Theme *theme = get_theme_updata(L);
288 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
289 FFmpegCapture **capture = (FFmpegCapture **)luaL_checkudata(L, 2, "VideoInput");
290 bool deinterlace = checkbool(L, 3);
292 // These need to be nonowned, so that the LiveInputWrapper still exists
293 // and can feed frames to the right EffectChain even if the Lua code
294 // doesn't care about the object anymore. (If we change this, we'd need
295 // to also unregister the signal connection on __gc.)
296 int ret = wrap_lua_object_nonowned<LiveInputWrapper>(
297 L, "LiveInputWrapper", theme, chain, (*capture)->get_current_pixel_format(),
298 /*override_bounce=*/false, deinterlace, /*user_connectable=*/false);
300 Theme *theme = get_theme_updata(L);
301 LiveInputWrapper **live_input = (LiveInputWrapper **)lua_touserdata(L, -1);
302 theme->register_video_signal_connection(chain, *live_input, *capture);
308 int EffectChain_add_html_input(lua_State* L)
310 assert(lua_gettop(L) == 2);
311 Theme *theme = get_theme_updata(L);
312 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
313 CEFCapture **capture = (CEFCapture **)luaL_checkudata(L, 2, "HTMLInput");
315 // These need to be nonowned, so that the LiveInputWrapper still exists
316 // and can feed frames to the right EffectChain even if the Lua code
317 // doesn't care about the object anymore. (If we change this, we'd need
318 // to also unregister the signal connection on __gc.)
319 int ret = wrap_lua_object_nonowned<LiveInputWrapper>(
320 L, "LiveInputWrapper", theme, chain, (*capture)->get_current_pixel_format(),
321 /*override_bounce=*/false, /*deinterlace=*/false, /*user_connectable=*/false);
323 Theme *theme = get_theme_updata(L);
324 LiveInputWrapper **live_input = (LiveInputWrapper **)lua_touserdata(L, -1);
325 theme->register_html_signal_connection(chain, *live_input, *capture);
331 int EffectChain_add_effect(lua_State* L)
333 assert(lua_gettop(L) >= 2);
334 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
336 // TODO: Better error reporting.
337 Effect *effect = get_effect(L, 2);
338 if (lua_gettop(L) == 2) {
339 if (effect->num_inputs() == 0) {
340 chain->add_input((Input *)effect);
342 chain->add_effect(effect);
345 vector<Effect *> inputs;
346 for (int idx = 3; idx <= lua_gettop(L); ++idx) {
347 if (luaL_testudata(L, idx, "LiveInputWrapper")) {
348 LiveInputWrapper **input = (LiveInputWrapper **)lua_touserdata(L, idx);
349 inputs.push_back((*input)->get_effect());
351 inputs.push_back(get_effect(L, idx));
354 chain->add_effect(effect, inputs);
357 lua_settop(L, 2); // Return the effect itself.
359 // Make sure Lua doesn't garbage-collect it away.
360 lua_pushvalue(L, -1);
361 luaL_ref(L, LUA_REGISTRYINDEX); // TODO: leak?
366 int EffectChain_finalize(lua_State* L)
368 assert(lua_gettop(L) == 2);
369 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
370 bool is_main_chain = checkbool(L, 2);
372 // Add outputs as needed.
373 // NOTE: If you change any details about the output format, you will need to
374 // also update what's given to the muxer (HTTPD::Mux constructor) and
375 // what's put in the H.264 stream (sps_rbsp()).
376 ImageFormat inout_format;
377 inout_format.color_space = COLORSPACE_REC_709;
379 // Output gamma is tricky. We should output Rec. 709 for TV, except that
380 // we expect to run with web players and others that don't really care and
381 // just output with no conversion. So that means we'll need to output sRGB,
382 // even though H.264 has no setting for that (we use “unspecified”).
383 inout_format.gamma_curve = GAMMA_sRGB;
386 YCbCrFormat output_ycbcr_format;
387 // We actually output 4:2:0 and/or 4:2:2 in the end, but chroma subsampling
388 // happens in a pass not run by Movit (see ChromaSubsampler::subsample_chroma()).
389 output_ycbcr_format.chroma_subsampling_x = 1;
390 output_ycbcr_format.chroma_subsampling_y = 1;
392 // This will be overridden if HDMI/SDI output is in force.
393 if (global_flags.ycbcr_rec709_coefficients) {
394 output_ycbcr_format.luma_coefficients = YCBCR_REC_709;
396 output_ycbcr_format.luma_coefficients = YCBCR_REC_601;
399 output_ycbcr_format.full_range = false;
400 output_ycbcr_format.num_levels = 1 << global_flags.x264_bit_depth;
402 GLenum type = global_flags.x264_bit_depth > 8 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_BYTE;
404 chain->add_ycbcr_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED, output_ycbcr_format, YCBCR_OUTPUT_SPLIT_Y_AND_CBCR, type);
406 // If we're using zerocopy video encoding (so the destination
407 // Y texture is owned by VA-API and will be unavailable for
408 // display), add a copy, where we'll only be using the Y component.
409 if (global_flags.use_zerocopy) {
410 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.
412 chain->set_dither_bits(global_flags.x264_bit_depth > 8 ? 16 : 8);
413 chain->set_output_origin(OUTPUT_ORIGIN_TOP_LEFT);
415 chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
422 int LiveInputWrapper_connect_signal(lua_State* L)
424 assert(lua_gettop(L) == 2);
425 LiveInputWrapper **input = (LiveInputWrapper **)luaL_checkudata(L, 1, "LiveInputWrapper");
426 int signal_num = luaL_checknumber(L, 2);
427 bool success = (*input)->connect_signal(signal_num);
430 lua_getstack(L, 1, &ar);
431 lua_getinfo(L, "nSl", &ar);
432 fprintf(stderr, "ERROR: %s:%d: Calling connect_signal() on a video or HTML input. Ignoring.\n",
433 ar.source, ar.currentline);
438 int ImageInput_new(lua_State* L)
440 assert(lua_gettop(L) == 1);
441 string filename = checkstdstring(L, 1);
442 return wrap_lua_object_nonowned<ImageInput>(L, "ImageInput", filename);
445 int VideoInput_new(lua_State* L)
447 assert(lua_gettop(L) == 2);
448 string filename = checkstdstring(L, 1);
449 int pixel_format = luaL_checknumber(L, 2);
450 if (pixel_format != bmusb::PixelFormat_8BitYCbCrPlanar &&
451 pixel_format != bmusb::PixelFormat_8BitBGRA) {
452 fprintf(stderr, "WARNING: Invalid enum %d used for video format, choosing Y'CbCr.\n",
454 pixel_format = bmusb::PixelFormat_8BitYCbCrPlanar;
456 int ret = wrap_lua_object_nonowned<FFmpegCapture>(L, "VideoInput", filename, global_flags.width, global_flags.height);
458 FFmpegCapture **capture = (FFmpegCapture **)lua_touserdata(L, -1);
459 (*capture)->set_pixel_format(bmusb::PixelFormat(pixel_format));
461 Theme *theme = get_theme_updata(L);
462 theme->register_video_input(*capture);
467 int VideoInput_rewind(lua_State* L)
469 assert(lua_gettop(L) == 1);
470 FFmpegCapture **video_input = (FFmpegCapture **)luaL_checkudata(L, 1, "VideoInput");
471 (*video_input)->rewind();
475 int VideoInput_disconnect(lua_State* L)
477 assert(lua_gettop(L) == 1);
478 FFmpegCapture **video_input = (FFmpegCapture **)luaL_checkudata(L, 1, "VideoInput");
479 (*video_input)->disconnect();
483 int VideoInput_change_rate(lua_State* L)
485 assert(lua_gettop(L) == 2);
486 FFmpegCapture **video_input = (FFmpegCapture **)luaL_checkudata(L, 1, "VideoInput");
487 double new_rate = luaL_checknumber(L, 2);
488 (*video_input)->change_rate(new_rate);
492 int VideoInput_get_signal_num(lua_State* L)
494 assert(lua_gettop(L) == 1);
495 FFmpegCapture **video_input = (FFmpegCapture **)luaL_checkudata(L, 1, "VideoInput");
496 lua_pushnumber(L, -1 - (*video_input)->get_card_index());
500 int HTMLInput_new(lua_State* L)
503 assert(lua_gettop(L) == 1);
504 string url = checkstdstring(L, 1);
505 int ret = wrap_lua_object_nonowned<CEFCapture>(L, "HTMLInput", url, global_flags.width, global_flags.height);
507 CEFCapture **capture = (CEFCapture **)lua_touserdata(L, -1);
508 Theme *theme = get_theme_updata(L);
509 theme->register_html_input(*capture);
513 fprintf(stderr, "This version of Nageru has been compiled without CEF support.\n");
514 fprintf(stderr, "HTMLInput is not available.\n");
520 int HTMLInput_set_url(lua_State* L)
522 assert(lua_gettop(L) == 2);
523 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
524 string new_url = checkstdstring(L, 2);
525 (*video_input)->set_url(new_url);
529 int HTMLInput_reload(lua_State* L)
531 assert(lua_gettop(L) == 1);
532 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
533 (*video_input)->reload();
537 int HTMLInput_set_max_fps(lua_State* L)
539 assert(lua_gettop(L) == 2);
540 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
541 int max_fps = lrint(luaL_checknumber(L, 2));
542 (*video_input)->set_max_fps(max_fps);
546 int HTMLInput_execute_javascript_async(lua_State* L)
548 assert(lua_gettop(L) == 2);
549 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
550 string js = checkstdstring(L, 2);
551 (*video_input)->execute_javascript_async(js);
555 int HTMLInput_resize(lua_State* L)
557 assert(lua_gettop(L) == 3);
558 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
559 unsigned width = lrint(luaL_checknumber(L, 2));
560 unsigned height = lrint(luaL_checknumber(L, 3));
561 (*video_input)->resize(width, height);
565 int HTMLInput_get_signal_num(lua_State* L)
567 assert(lua_gettop(L) == 1);
568 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
569 lua_pushnumber(L, -1 - (*video_input)->get_card_index());
574 int WhiteBalanceEffect_new(lua_State* L)
576 assert(lua_gettop(L) == 0);
577 return wrap_lua_object_nonowned<WhiteBalanceEffect>(L, "WhiteBalanceEffect");
580 int ResampleEffect_new(lua_State* L)
582 assert(lua_gettop(L) == 0);
583 return wrap_lua_object_nonowned<ResampleEffect>(L, "ResampleEffect");
586 int PaddingEffect_new(lua_State* L)
588 assert(lua_gettop(L) == 0);
589 return wrap_lua_object_nonowned<PaddingEffect>(L, "PaddingEffect");
592 int IntegralPaddingEffect_new(lua_State* L)
594 assert(lua_gettop(L) == 0);
595 return wrap_lua_object_nonowned<IntegralPaddingEffect>(L, "IntegralPaddingEffect");
598 int OverlayEffect_new(lua_State* L)
600 assert(lua_gettop(L) == 0);
601 return wrap_lua_object_nonowned<OverlayEffect>(L, "OverlayEffect");
604 int ResizeEffect_new(lua_State* L)
606 assert(lua_gettop(L) == 0);
607 return wrap_lua_object_nonowned<ResizeEffect>(L, "ResizeEffect");
610 int MultiplyEffect_new(lua_State* L)
612 assert(lua_gettop(L) == 0);
613 return wrap_lua_object_nonowned<MultiplyEffect>(L, "MultiplyEffect");
616 int MixEffect_new(lua_State* L)
618 assert(lua_gettop(L) == 0);
619 return wrap_lua_object_nonowned<MixEffect>(L, "MixEffect");
622 int LiftGammaGainEffect_new(lua_State* L)
624 assert(lua_gettop(L) == 0);
625 return wrap_lua_object_nonowned<LiftGammaGainEffect>(L, "LiftGammaGainEffect");
628 int InputStateInfo_get_width(lua_State* L)
630 assert(lua_gettop(L) == 2);
631 InputStateInfo *input_state_info = get_input_state_info(L, 1);
632 Theme *theme = get_theme_updata(L);
633 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
634 lua_pushnumber(L, input_state_info->last_width[signal_num]);
638 int InputStateInfo_get_height(lua_State* L)
640 assert(lua_gettop(L) == 2);
641 InputStateInfo *input_state_info = get_input_state_info(L, 1);
642 Theme *theme = get_theme_updata(L);
643 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
644 lua_pushnumber(L, input_state_info->last_height[signal_num]);
648 int InputStateInfo_get_interlaced(lua_State* L)
650 assert(lua_gettop(L) == 2);
651 InputStateInfo *input_state_info = get_input_state_info(L, 1);
652 Theme *theme = get_theme_updata(L);
653 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
654 lua_pushboolean(L, input_state_info->last_interlaced[signal_num]);
658 int InputStateInfo_get_has_signal(lua_State* L)
660 assert(lua_gettop(L) == 2);
661 InputStateInfo *input_state_info = get_input_state_info(L, 1);
662 Theme *theme = get_theme_updata(L);
663 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
664 lua_pushboolean(L, input_state_info->last_has_signal[signal_num]);
668 int InputStateInfo_get_is_connected(lua_State* L)
670 assert(lua_gettop(L) == 2);
671 InputStateInfo *input_state_info = get_input_state_info(L, 1);
672 Theme *theme = get_theme_updata(L);
673 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
674 lua_pushboolean(L, input_state_info->last_is_connected[signal_num]);
678 int InputStateInfo_get_frame_rate_nom(lua_State* L)
680 assert(lua_gettop(L) == 2);
681 InputStateInfo *input_state_info = get_input_state_info(L, 1);
682 Theme *theme = get_theme_updata(L);
683 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
684 lua_pushnumber(L, input_state_info->last_frame_rate_nom[signal_num]);
688 int InputStateInfo_get_frame_rate_den(lua_State* L)
690 assert(lua_gettop(L) == 2);
691 InputStateInfo *input_state_info = get_input_state_info(L, 1);
692 Theme *theme = get_theme_updata(L);
693 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
694 lua_pushnumber(L, input_state_info->last_frame_rate_den[signal_num]);
698 int Effect_set_float(lua_State *L)
700 assert(lua_gettop(L) == 3);
701 Effect *effect = (Effect *)get_effect(L, 1);
702 string key = checkstdstring(L, 2);
703 float value = luaL_checknumber(L, 3);
704 if (!effect->set_float(key, value)) {
705 luaL_error(L, "Effect refused set_float(\"%s\", %d) (invalid key?)", key.c_str(), int(value));
710 int Effect_set_int(lua_State *L)
712 assert(lua_gettop(L) == 3);
713 Effect *effect = (Effect *)get_effect(L, 1);
714 string key = checkstdstring(L, 2);
715 float value = luaL_checknumber(L, 3);
716 if (!effect->set_int(key, value)) {
717 luaL_error(L, "Effect refused set_int(\"%s\", %d) (invalid key?)", key.c_str(), int(value));
722 int Effect_set_vec3(lua_State *L)
724 assert(lua_gettop(L) == 5);
725 Effect *effect = (Effect *)get_effect(L, 1);
726 string key = checkstdstring(L, 2);
728 v[0] = luaL_checknumber(L, 3);
729 v[1] = luaL_checknumber(L, 4);
730 v[2] = luaL_checknumber(L, 5);
731 if (!effect->set_vec3(key, v)) {
732 luaL_error(L, "Effect refused set_vec3(\"%s\", %f, %f, %f) (invalid key?)", key.c_str(),
738 int Effect_set_vec4(lua_State *L)
740 assert(lua_gettop(L) == 6);
741 Effect *effect = (Effect *)get_effect(L, 1);
742 string key = checkstdstring(L, 2);
744 v[0] = luaL_checknumber(L, 3);
745 v[1] = luaL_checknumber(L, 4);
746 v[2] = luaL_checknumber(L, 5);
747 v[3] = luaL_checknumber(L, 6);
748 if (!effect->set_vec4(key, v)) {
749 luaL_error(L, "Effect refused set_vec4(\"%s\", %f, %f, %f, %f) (invalid key?)", key.c_str(),
750 v[0], v[1], v[2], v[3]);
755 const luaL_Reg EffectChain_funcs[] = {
756 { "new", EffectChain_new },
757 { "__gc", EffectChain_gc },
758 { "add_live_input", EffectChain_add_live_input },
759 { "add_video_input", EffectChain_add_video_input },
761 { "add_html_input", EffectChain_add_html_input },
763 { "add_effect", EffectChain_add_effect },
764 { "finalize", EffectChain_finalize },
768 const luaL_Reg LiveInputWrapper_funcs[] = {
769 { "connect_signal", LiveInputWrapper_connect_signal },
773 const luaL_Reg ImageInput_funcs[] = {
774 { "new", ImageInput_new },
775 { "set_float", Effect_set_float },
776 { "set_int", Effect_set_int },
777 { "set_vec3", Effect_set_vec3 },
778 { "set_vec4", Effect_set_vec4 },
782 const luaL_Reg VideoInput_funcs[] = {
783 { "new", VideoInput_new },
784 { "rewind", VideoInput_rewind },
785 { "disconnect", VideoInput_disconnect },
786 { "change_rate", VideoInput_change_rate },
787 { "get_signal_num", VideoInput_get_signal_num },
791 const luaL_Reg HTMLInput_funcs[] = {
792 { "new", HTMLInput_new },
794 { "set_url", HTMLInput_set_url },
795 { "reload", HTMLInput_reload },
796 { "set_max_fps", HTMLInput_set_max_fps },
797 { "execute_javascript_async", HTMLInput_execute_javascript_async },
798 { "resize", HTMLInput_resize },
799 { "get_signal_num", HTMLInput_get_signal_num },
804 const luaL_Reg WhiteBalanceEffect_funcs[] = {
805 { "new", WhiteBalanceEffect_new },
806 { "set_float", Effect_set_float },
807 { "set_int", Effect_set_int },
808 { "set_vec3", Effect_set_vec3 },
809 { "set_vec4", Effect_set_vec4 },
813 const luaL_Reg ResampleEffect_funcs[] = {
814 { "new", ResampleEffect_new },
815 { "set_float", Effect_set_float },
816 { "set_int", Effect_set_int },
817 { "set_vec3", Effect_set_vec3 },
818 { "set_vec4", Effect_set_vec4 },
822 const luaL_Reg PaddingEffect_funcs[] = {
823 { "new", PaddingEffect_new },
824 { "set_float", Effect_set_float },
825 { "set_int", Effect_set_int },
826 { "set_vec3", Effect_set_vec3 },
827 { "set_vec4", Effect_set_vec4 },
831 const luaL_Reg IntegralPaddingEffect_funcs[] = {
832 { "new", IntegralPaddingEffect_new },
833 { "set_float", Effect_set_float },
834 { "set_int", Effect_set_int },
835 { "set_vec3", Effect_set_vec3 },
836 { "set_vec4", Effect_set_vec4 },
840 const luaL_Reg OverlayEffect_funcs[] = {
841 { "new", OverlayEffect_new },
842 { "set_float", Effect_set_float },
843 { "set_int", Effect_set_int },
844 { "set_vec3", Effect_set_vec3 },
845 { "set_vec4", Effect_set_vec4 },
849 const luaL_Reg ResizeEffect_funcs[] = {
850 { "new", ResizeEffect_new },
851 { "set_float", Effect_set_float },
852 { "set_int", Effect_set_int },
853 { "set_vec3", Effect_set_vec3 },
854 { "set_vec4", Effect_set_vec4 },
858 const luaL_Reg MultiplyEffect_funcs[] = {
859 { "new", MultiplyEffect_new },
860 { "set_float", Effect_set_float },
861 { "set_int", Effect_set_int },
862 { "set_vec3", Effect_set_vec3 },
863 { "set_vec4", Effect_set_vec4 },
867 const luaL_Reg MixEffect_funcs[] = {
868 { "new", MixEffect_new },
869 { "set_float", Effect_set_float },
870 { "set_int", Effect_set_int },
871 { "set_vec3", Effect_set_vec3 },
872 { "set_vec4", Effect_set_vec4 },
876 const luaL_Reg LiftGammaGainEffect_funcs[] = {
877 { "new", LiftGammaGainEffect_new },
878 { "set_float", Effect_set_float },
879 { "set_int", Effect_set_int },
880 { "set_vec3", Effect_set_vec3 },
881 { "set_vec4", Effect_set_vec4 },
885 const luaL_Reg InputStateInfo_funcs[] = {
886 { "get_width", InputStateInfo_get_width },
887 { "get_height", InputStateInfo_get_height },
888 { "get_interlaced", InputStateInfo_get_interlaced },
889 { "get_has_signal", InputStateInfo_get_has_signal },
890 { "get_is_connected", InputStateInfo_get_is_connected },
891 { "get_frame_rate_nom", InputStateInfo_get_frame_rate_nom },
892 { "get_frame_rate_den", InputStateInfo_get_frame_rate_den },
896 const luaL_Reg ThemeMenu_funcs[] = {
897 { "set", ThemeMenu_set },
903 LiveInputWrapper::LiveInputWrapper(
906 bmusb::PixelFormat pixel_format,
907 bool override_bounce,
909 bool user_connectable)
911 pixel_format(pixel_format),
912 deinterlace(deinterlace),
913 user_connectable(user_connectable)
915 ImageFormat inout_format;
916 inout_format.color_space = COLORSPACE_sRGB;
918 // Gamma curve depends on the input signal, and we don't really get any
919 // indications. A camera would be expected to do Rec. 709, but
920 // I haven't checked if any do in practice. However, computers _do_ output
921 // in sRGB gamma (ie., they don't convert from sRGB to Rec. 709), and
922 // I wouldn't really be surprised if most non-professional cameras do, too.
923 // So we pick sRGB as the least evil here.
924 inout_format.gamma_curve = GAMMA_sRGB;
928 deinterlace_effect = new movit::DeinterlaceEffect();
930 // As per the comments in deinterlace_effect.h, we turn this off.
931 // The most likely interlaced input for us is either a camera
932 // (where it's fine to turn it off) or a laptop (where it _should_
934 CHECK(deinterlace_effect->set_int("enable_spatial_interlacing_check", 0));
936 num_inputs = deinterlace_effect->num_inputs();
937 assert(num_inputs == FRAME_HISTORY_LENGTH);
942 if (pixel_format == bmusb::PixelFormat_8BitBGRA) {
943 for (unsigned i = 0; i < num_inputs; ++i) {
944 // We upload our textures ourselves, and Movit swaps
945 // R and B in the shader if we specify BGRA, so lie and say RGBA.
946 if (global_flags.can_disable_srgb_decoder) {
947 rgba_inputs.push_back(new sRGBSwitchingFlatInput(inout_format, FORMAT_RGBA_POSTMULTIPLIED_ALPHA, GL_UNSIGNED_BYTE, global_flags.width, global_flags.height));
949 rgba_inputs.push_back(new NonsRGBCapableFlatInput(inout_format, FORMAT_RGBA_POSTMULTIPLIED_ALPHA, GL_UNSIGNED_BYTE, global_flags.width, global_flags.height));
951 chain->add_input(rgba_inputs.back());
955 vector<Effect *> reverse_inputs(rgba_inputs.rbegin(), rgba_inputs.rend());
956 chain->add_effect(deinterlace_effect, reverse_inputs);
959 assert(pixel_format == bmusb::PixelFormat_8BitYCbCr ||
960 pixel_format == bmusb::PixelFormat_10BitYCbCr ||
961 pixel_format == bmusb::PixelFormat_8BitYCbCrPlanar);
963 // Most of these settings will be overridden later if using PixelFormat_8BitYCbCrPlanar.
964 input_ycbcr_format.chroma_subsampling_x = (pixel_format == bmusb::PixelFormat_10BitYCbCr) ? 1 : 2;
965 input_ycbcr_format.chroma_subsampling_y = 1;
966 input_ycbcr_format.num_levels = (pixel_format == bmusb::PixelFormat_10BitYCbCr) ? 1024 : 256;
967 input_ycbcr_format.cb_x_position = 0.0;
968 input_ycbcr_format.cr_x_position = 0.0;
969 input_ycbcr_format.cb_y_position = 0.5;
970 input_ycbcr_format.cr_y_position = 0.5;
971 input_ycbcr_format.luma_coefficients = YCBCR_REC_709; // Will be overridden later even if not planar.
972 input_ycbcr_format.full_range = false; // Will be overridden later even if not planar.
974 for (unsigned i = 0; i < num_inputs; ++i) {
975 // When using 10-bit input, we're converting to interleaved through v210Converter.
976 YCbCrInputSplitting splitting;
977 if (pixel_format == bmusb::PixelFormat_10BitYCbCr) {
978 splitting = YCBCR_INPUT_INTERLEAVED;
979 } else if (pixel_format == bmusb::PixelFormat_8BitYCbCr) {
980 splitting = YCBCR_INPUT_SPLIT_Y_AND_CBCR;
982 splitting = YCBCR_INPUT_PLANAR;
984 if (override_bounce) {
985 ycbcr_inputs.push_back(new NonBouncingYCbCrInput(inout_format, input_ycbcr_format, global_flags.width, global_flags.height, splitting));
987 ycbcr_inputs.push_back(new YCbCrInput(inout_format, input_ycbcr_format, global_flags.width, global_flags.height, splitting));
989 chain->add_input(ycbcr_inputs.back());
993 vector<Effect *> reverse_inputs(ycbcr_inputs.rbegin(), ycbcr_inputs.rend());
994 chain->add_effect(deinterlace_effect, reverse_inputs);
999 bool LiveInputWrapper::connect_signal(int signal_num)
1001 if (!user_connectable) {
1005 if (global_mixer == nullptr) {
1010 signal_num = theme->map_signal(signal_num);
1011 connect_signal_raw(signal_num, *theme->input_state);
1015 void LiveInputWrapper::connect_signal_raw(int signal_num, const InputState &input_state)
1017 BufferedFrame first_frame = input_state.buffered_frames[signal_num][0];
1018 if (first_frame.frame == nullptr) {
1022 unsigned width, height;
1024 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)first_frame.frame->userdata;
1025 width = userdata->last_width[first_frame.field_number];
1026 height = userdata->last_height[first_frame.field_number];
1027 if (userdata->last_interlaced) {
1032 movit::YCbCrLumaCoefficients ycbcr_coefficients = input_state.ycbcr_coefficients[signal_num];
1033 bool full_range = input_state.full_range[signal_num];
1035 if (input_state.ycbcr_coefficients_auto[signal_num]) {
1038 // The Blackmagic driver docs claim that the device outputs Y'CbCr
1039 // according to Rec. 601, but this seems to indicate the subsampling
1040 // positions only, as they publish Y'CbCr → RGB formulas that are
1041 // different for HD and SD (corresponding to Rec. 709 and 601, respectively),
1042 // and a Lenovo X1 gen 3 I used to test definitely outputs Rec. 709
1043 // (at least up to rounding error). Other devices seem to use Rec. 601
1044 // even on HD resolutions. Nevertheless, Rec. 709 _is_ the right choice
1045 // for HD, so we default to that if the user hasn't set anything.
1046 if (height >= 720) {
1047 ycbcr_coefficients = YCBCR_REC_709;
1049 ycbcr_coefficients = YCBCR_REC_601;
1053 // This is a global, but it doesn't really matter.
1054 input_ycbcr_format.luma_coefficients = ycbcr_coefficients;
1055 input_ycbcr_format.full_range = full_range;
1057 BufferedFrame last_good_frame = first_frame;
1058 for (unsigned i = 0; i < max(ycbcr_inputs.size(), rgba_inputs.size()); ++i) {
1059 BufferedFrame frame = input_state.buffered_frames[signal_num][i];
1060 if (frame.frame == nullptr) {
1061 // Not enough data; reuse last frame (well, field).
1062 // This is suboptimal, but we have nothing better.
1063 frame = last_good_frame;
1065 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
1067 unsigned this_width = userdata->last_width[frame.field_number];
1068 unsigned this_height = userdata->last_height[frame.field_number];
1069 if (this_width != width || this_height != height) {
1070 // Resolution changed; reuse last frame/field.
1071 frame = last_good_frame;
1072 userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
1075 assert(userdata->pixel_format == pixel_format);
1076 switch (pixel_format) {
1077 case bmusb::PixelFormat_8BitYCbCr:
1078 ycbcr_inputs[i]->set_texture_num(0, userdata->tex_y[frame.field_number]);
1079 ycbcr_inputs[i]->set_texture_num(1, userdata->tex_cbcr[frame.field_number]);
1080 ycbcr_inputs[i]->change_ycbcr_format(input_ycbcr_format);
1081 ycbcr_inputs[i]->set_width(width);
1082 ycbcr_inputs[i]->set_height(height);
1084 case bmusb::PixelFormat_8BitYCbCrPlanar:
1085 ycbcr_inputs[i]->set_texture_num(0, userdata->tex_y[frame.field_number]);
1086 ycbcr_inputs[i]->set_texture_num(1, userdata->tex_cb[frame.field_number]);
1087 ycbcr_inputs[i]->set_texture_num(2, userdata->tex_cr[frame.field_number]);
1088 ycbcr_inputs[i]->change_ycbcr_format(userdata->ycbcr_format);
1089 ycbcr_inputs[i]->set_width(width);
1090 ycbcr_inputs[i]->set_height(height);
1092 case bmusb::PixelFormat_10BitYCbCr:
1093 ycbcr_inputs[i]->set_texture_num(0, userdata->tex_444[frame.field_number]);
1094 ycbcr_inputs[i]->change_ycbcr_format(input_ycbcr_format);
1095 ycbcr_inputs[i]->set_width(width);
1096 ycbcr_inputs[i]->set_height(height);
1098 case bmusb::PixelFormat_8BitBGRA:
1099 rgba_inputs[i]->set_texture_num(userdata->tex_rgba[frame.field_number]);
1100 rgba_inputs[i]->set_width(width);
1101 rgba_inputs[i]->set_height(height);
1107 last_good_frame = frame;
1111 BufferedFrame frame = input_state.buffered_frames[signal_num][0];
1112 CHECK(deinterlace_effect->set_int("current_field_position", frame.field_number));
1118 int call_num_channels(lua_State *L)
1120 lua_getglobal(L, "num_channels");
1122 if (lua_pcall(L, 0, 1, 0) != 0) {
1123 fprintf(stderr, "error running function `num_channels': %s\n", lua_tostring(L, -1));
1127 int num_channels = luaL_checknumber(L, 1);
1129 assert(lua_gettop(L) == 0);
1130 return num_channels;
1135 Theme::Theme(const string &filename, const vector<string> &search_dirs, ResourcePool *resource_pool, unsigned num_cards)
1136 : resource_pool(resource_pool), num_cards(num_cards), signal_to_card_mapping(global_flags.default_stream_mapping)
1138 L = luaL_newstate();
1141 // Search through all directories until we find a file that will load
1142 // (as in, does not return LUA_ERRFILE); then run it. We store load errors
1143 // from all the attempts, and show them once we know we can't find any of them.
1145 vector<string> errors;
1146 bool success = false;
1148 vector<string> real_search_dirs;
1149 if (!filename.empty() && filename[0] == '/') {
1150 real_search_dirs.push_back("");
1152 real_search_dirs = search_dirs;
1157 for (const string &dir : real_search_dirs) {
1161 path = dir + "/" + filename;
1163 int err = luaL_loadfile(L, path.c_str());
1165 // Save the theme for when we're actually going to run it
1166 // (we need to set up the right environment below first,
1167 // and we couldn't do that before, because we didn't know the
1168 // path to put in Nageru.THEME_PATH).
1169 theme_code_ref = luaL_ref(L, LUA_REGISTRYINDEX);
1170 assert(lua_gettop(L) == 0);
1175 errors.push_back(lua_tostring(L, -1));
1177 if (err != LUA_ERRFILE) {
1178 // The file actually loaded, but failed to parse somehow. Abort; don't try the next one.
1184 for (const string &error : errors) {
1185 fprintf(stderr, "%s\n", error.c_str());
1189 assert(lua_gettop(L) == 0);
1191 // Make sure the path exposed to the theme (as Nageru.THEME_PATH;
1192 // can be useful for locating files when talking to CEF) is absolute.
1193 // In a sense, it would be nice if realpath() had a mode not to
1194 // resolve symlinks, but it doesn't, so we only call it if we don't
1195 // already have an absolute path (which may leave ../ elements etc.).
1196 if (path[0] == '/') {
1199 char *absolute_theme_path = realpath(path.c_str(), nullptr);
1200 theme_path = absolute_theme_path;
1201 free(absolute_theme_path);
1204 // Set up the API we provide.
1205 register_constants();
1206 register_class("EffectChain", EffectChain_funcs);
1207 register_class("LiveInputWrapper", LiveInputWrapper_funcs);
1208 register_class("ImageInput", ImageInput_funcs);
1209 register_class("VideoInput", VideoInput_funcs);
1210 register_class("HTMLInput", HTMLInput_funcs);
1211 register_class("WhiteBalanceEffect", WhiteBalanceEffect_funcs);
1212 register_class("ResampleEffect", ResampleEffect_funcs);
1213 register_class("PaddingEffect", PaddingEffect_funcs);
1214 register_class("IntegralPaddingEffect", IntegralPaddingEffect_funcs);
1215 register_class("OverlayEffect", OverlayEffect_funcs);
1216 register_class("ResizeEffect", ResizeEffect_funcs);
1217 register_class("MultiplyEffect", MultiplyEffect_funcs);
1218 register_class("MixEffect", MixEffect_funcs);
1219 register_class("LiftGammaGainEffect", LiftGammaGainEffect_funcs);
1220 register_class("InputStateInfo", InputStateInfo_funcs);
1221 register_class("ThemeMenu", ThemeMenu_funcs);
1223 // Now actually run the theme to get everything set up.
1224 lua_rawgeti(L, LUA_REGISTRYINDEX, theme_code_ref);
1225 luaL_unref(L, LUA_REGISTRYINDEX, theme_code_ref);
1226 if (lua_pcall(L, 0, 0, 0)) {
1227 fprintf(stderr, "Error when running %s: %s\n", path.c_str(), lua_tostring(L, -1));
1230 assert(lua_gettop(L) == 0);
1232 // Ask it for the number of channels.
1233 num_channels = call_num_channels(L);
1241 void Theme::register_constants()
1243 // Set Nageru.VIDEO_FORMAT_BGRA = bmusb::PixelFormat_8BitBGRA, etc.
1244 const vector<pair<string, int>> num_constants = {
1245 { "VIDEO_FORMAT_BGRA", bmusb::PixelFormat_8BitBGRA },
1246 { "VIDEO_FORMAT_YCBCR", bmusb::PixelFormat_8BitYCbCrPlanar },
1248 const vector<pair<string, string>> str_constants = {
1249 { "THEME_PATH", theme_path },
1252 lua_newtable(L); // t = {}
1254 for (const pair<string, int> &constant : num_constants) {
1255 lua_pushstring(L, constant.first.c_str());
1256 lua_pushinteger(L, constant.second);
1257 lua_settable(L, 1); // t[key] = value
1259 for (const pair<string, string> &constant : str_constants) {
1260 lua_pushstring(L, constant.first.c_str());
1261 lua_pushstring(L, constant.second.c_str());
1262 lua_settable(L, 1); // t[key] = value
1265 lua_setglobal(L, "Nageru"); // Nageru = t
1266 assert(lua_gettop(L) == 0);
1269 void Theme::register_class(const char *class_name, const luaL_Reg *funcs)
1271 assert(lua_gettop(L) == 0);
1272 luaL_newmetatable(L, class_name); // mt = {}
1273 lua_pushlightuserdata(L, this);
1274 luaL_setfuncs(L, funcs, 1); // for (name,f in funcs) { mt[name] = f, with upvalue {theme} }
1275 lua_pushvalue(L, -1);
1276 lua_setfield(L, -2, "__index"); // mt.__index = mt
1277 lua_setglobal(L, class_name); // ClassName = mt
1278 assert(lua_gettop(L) == 0);
1281 Theme::Chain Theme::get_chain(unsigned num, float t, unsigned width, unsigned height, InputState input_state)
1285 unique_lock<mutex> lock(m);
1286 assert(lua_gettop(L) == 0);
1287 lua_getglobal(L, "get_chain"); /* function to be called */
1288 lua_pushnumber(L, num);
1289 lua_pushnumber(L, t);
1290 lua_pushnumber(L, width);
1291 lua_pushnumber(L, height);
1292 wrap_lua_object<InputStateInfo>(L, "InputStateInfo", input_state);
1294 if (lua_pcall(L, 5, 2, 0) != 0) {
1295 fprintf(stderr, "error running function `get_chain': %s\n", lua_tostring(L, -1));
1299 EffectChain *effect_chain = (EffectChain *)luaL_testudata(L, -2, "EffectChain");
1300 if (effect_chain == nullptr) {
1301 fprintf(stderr, "get_chain() for chain number %d did not return an EffectChain\n",
1305 chain.chain = effect_chain;
1306 if (!lua_isfunction(L, -1)) {
1307 fprintf(stderr, "Argument #-1 should be a function\n");
1310 lua_pushvalue(L, -1);
1311 shared_ptr<LuaRefWithDeleter> funcref(new LuaRefWithDeleter(&m, L, luaL_ref(L, LUA_REGISTRYINDEX)));
1313 assert(lua_gettop(L) == 0);
1315 chain.setup_chain = [this, funcref, input_state, effect_chain]{
1316 unique_lock<mutex> lock(m);
1318 assert(this->input_state == nullptr);
1319 this->input_state = &input_state;
1321 // Set up state, including connecting signals.
1322 lua_rawgeti(L, LUA_REGISTRYINDEX, funcref->get());
1323 if (lua_pcall(L, 0, 0, 0) != 0) {
1324 fprintf(stderr, "error running chain setup callback: %s\n", lua_tostring(L, -1));
1327 assert(lua_gettop(L) == 0);
1329 // The theme can't (or at least shouldn't!) call connect_signal() on
1330 // each FFmpeg or CEF input, so we'll do it here.
1331 if (video_signal_connections.count(effect_chain)) {
1332 for (const VideoSignalConnection &conn : video_signal_connections[effect_chain]) {
1333 conn.wrapper->connect_signal_raw(conn.source->get_card_index(), input_state);
1337 if (html_signal_connections.count(effect_chain)) {
1338 for (const CEFSignalConnection &conn : html_signal_connections[effect_chain]) {
1339 conn.wrapper->connect_signal_raw(conn.source->get_card_index(), input_state);
1344 this->input_state = nullptr;
1347 // TODO: Can we do better, e.g. by running setup_chain() and seeing what it references?
1348 // Actually, setup_chain does maybe hold all the references we need now anyway?
1349 chain.input_frames.reserve(num_cards * FRAME_HISTORY_LENGTH);
1350 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
1351 for (unsigned frame_num = 0; frame_num < FRAME_HISTORY_LENGTH; ++frame_num) {
1352 chain.input_frames.push_back(input_state.buffered_frames[card_index][frame_num].frame);
1359 string Theme::get_channel_name(unsigned channel)
1361 unique_lock<mutex> lock(m);
1362 lua_getglobal(L, "channel_name");
1363 lua_pushnumber(L, channel);
1364 if (lua_pcall(L, 1, 1, 0) != 0) {
1365 fprintf(stderr, "error running function `channel_name': %s\n", lua_tostring(L, -1));
1368 const char *ret = lua_tostring(L, -1);
1369 if (ret == nullptr) {
1370 fprintf(stderr, "function `channel_name' returned nil for channel %d\n", channel);
1374 string retstr = ret;
1376 assert(lua_gettop(L) == 0);
1380 int Theme::get_channel_signal(unsigned channel)
1382 unique_lock<mutex> lock(m);
1383 lua_getglobal(L, "channel_signal");
1384 lua_pushnumber(L, channel);
1385 if (lua_pcall(L, 1, 1, 0) != 0) {
1386 fprintf(stderr, "error running function `channel_signal': %s\n", lua_tostring(L, -1));
1390 int ret = luaL_checknumber(L, 1);
1392 assert(lua_gettop(L) == 0);
1396 std::string Theme::get_channel_color(unsigned channel)
1398 unique_lock<mutex> lock(m);
1399 lua_getglobal(L, "channel_color");
1400 lua_pushnumber(L, channel);
1401 if (lua_pcall(L, 1, 1, 0) != 0) {
1402 fprintf(stderr, "error running function `channel_color': %s\n", lua_tostring(L, -1));
1406 const char *ret = lua_tostring(L, -1);
1407 if (ret == nullptr) {
1408 fprintf(stderr, "function `channel_color' returned nil for channel %d\n", channel);
1412 string retstr = ret;
1414 assert(lua_gettop(L) == 0);
1418 bool Theme::get_supports_set_wb(unsigned channel)
1420 unique_lock<mutex> lock(m);
1421 lua_getglobal(L, "supports_set_wb");
1422 lua_pushnumber(L, channel);
1423 if (lua_pcall(L, 1, 1, 0) != 0) {
1424 fprintf(stderr, "error running function `supports_set_wb': %s\n", lua_tostring(L, -1));
1428 bool ret = checkbool(L, -1);
1430 assert(lua_gettop(L) == 0);
1434 void Theme::set_wb(unsigned channel, double r, double g, double b)
1436 unique_lock<mutex> lock(m);
1437 lua_getglobal(L, "set_wb");
1438 lua_pushnumber(L, channel);
1439 lua_pushnumber(L, r);
1440 lua_pushnumber(L, g);
1441 lua_pushnumber(L, b);
1442 if (lua_pcall(L, 4, 0, 0) != 0) {
1443 fprintf(stderr, "error running function `set_wb': %s\n", lua_tostring(L, -1));
1447 assert(lua_gettop(L) == 0);
1450 vector<string> Theme::get_transition_names(float t)
1452 unique_lock<mutex> lock(m);
1453 lua_getglobal(L, "get_transitions");
1454 lua_pushnumber(L, t);
1455 if (lua_pcall(L, 1, 1, 0) != 0) {
1456 fprintf(stderr, "error running function `get_transitions': %s\n", lua_tostring(L, -1));
1462 while (lua_next(L, -2) != 0) {
1463 ret.push_back(lua_tostring(L, -1));
1467 assert(lua_gettop(L) == 0);
1471 int Theme::map_signal(int signal_num)
1473 // Negative numbers map to raw signals.
1474 if (signal_num < 0) {
1475 return -1 - signal_num;
1478 unique_lock<mutex> lock(map_m);
1479 if (signal_to_card_mapping.count(signal_num)) {
1480 return signal_to_card_mapping[signal_num];
1484 if (global_flags.output_card != -1 && num_cards > 1) {
1485 // Try to exclude the output card from the default card_index.
1486 card_index = signal_num % (num_cards - 1);
1487 if (card_index >= global_flags.output_card) {
1490 if (signal_num >= int(num_cards - 1)) {
1491 fprintf(stderr, "WARNING: Theme asked for input %d, but we only have %u input card(s) (card %d is busy with output).\n",
1492 signal_num, num_cards - 1, global_flags.output_card);
1493 fprintf(stderr, "Mapping to card %d instead.\n", card_index);
1496 card_index = signal_num % num_cards;
1497 if (signal_num >= int(num_cards)) {
1498 fprintf(stderr, "WARNING: Theme asked for input %d, but we only have %u card(s).\n", signal_num, num_cards);
1499 fprintf(stderr, "Mapping to card %d instead.\n", card_index);
1502 signal_to_card_mapping[signal_num] = card_index;
1506 void Theme::set_signal_mapping(int signal_num, int card_num)
1508 unique_lock<mutex> lock(map_m);
1509 assert(card_num < int(num_cards));
1510 signal_to_card_mapping[signal_num] = card_num;
1513 void Theme::transition_clicked(int transition_num, float t)
1515 unique_lock<mutex> lock(m);
1516 lua_getglobal(L, "transition_clicked");
1517 lua_pushnumber(L, transition_num);
1518 lua_pushnumber(L, t);
1520 if (lua_pcall(L, 2, 0, 0) != 0) {
1521 fprintf(stderr, "error running function `transition_clicked': %s\n", lua_tostring(L, -1));
1524 assert(lua_gettop(L) == 0);
1527 void Theme::channel_clicked(int preview_num)
1529 unique_lock<mutex> lock(m);
1530 lua_getglobal(L, "channel_clicked");
1531 lua_pushnumber(L, preview_num);
1533 if (lua_pcall(L, 1, 0, 0) != 0) {
1534 fprintf(stderr, "error running function `channel_clicked': %s\n", lua_tostring(L, -1));
1537 assert(lua_gettop(L) == 0);
1540 int Theme::set_theme_menu(lua_State *L)
1542 for (const Theme::MenuEntry &entry : theme_menu) {
1543 luaL_unref(L, LUA_REGISTRYINDEX, entry.lua_ref);
1547 int num_elements = lua_gettop(L);
1548 for (int i = 1; i <= num_elements; ++i) {
1549 lua_rawgeti(L, i, 1);
1550 const string text = checkstdstring(L, -1);
1553 lua_rawgeti(L, i, 2);
1554 luaL_checktype(L, -1, LUA_TFUNCTION);
1555 int ref = luaL_ref(L, LUA_REGISTRYINDEX);
1557 theme_menu.push_back(MenuEntry{ text, ref });
1559 lua_pop(L, num_elements);
1560 assert(lua_gettop(L) == 0);
1562 if (theme_menu_callback != nullptr) {
1563 theme_menu_callback();
1569 void Theme::theme_menu_entry_clicked(int lua_ref)
1571 unique_lock<mutex> lock(m);
1572 lua_rawgeti(L, LUA_REGISTRYINDEX, lua_ref);
1573 if (lua_pcall(L, 0, 0, 0) != 0) {
1574 fprintf(stderr, "error running menu callback: %s\n", lua_tostring(L, -1));