4 #include <bmusb/bmusb.h>
9 #include <movit/deinterlace_effect.h>
10 #include <movit/effect.h>
11 #include <movit/effect_chain.h>
12 #include <movit/image_format.h>
13 #include <movit/input.h>
14 #include <movit/lift_gamma_gain_effect.h>
15 #include <movit/mix_effect.h>
16 #include <movit/multiply_effect.h>
17 #include <movit/overlay_effect.h>
18 #include <movit/padding_effect.h>
19 #include <movit/resample_effect.h>
20 #include <movit/resize_effect.h>
21 #include <movit/util.h>
22 #include <movit/white_balance_effect.h>
23 #include <movit/ycbcr.h>
24 #include <movit/ycbcr_input.h>
34 #include "cef_capture.h"
36 #include "ffmpeg_capture.h"
38 #include "image_input.h"
39 #include "input_state.h"
40 #include "lua_utils.h"
41 #include "pbo_frame_allocator.h"
50 using namespace movit;
52 extern Mixer *global_mixer;
54 Theme *get_theme_updata(lua_State* L)
56 luaL_checktype(L, lua_upvalueindex(1), LUA_TLIGHTUSERDATA);
57 return (Theme *)lua_touserdata(L, lua_upvalueindex(1));
60 void print_warning(lua_State* L, const char *format, ...)
65 vsnprintf(buf, sizeof(buf), format, ap);
69 lua_getstack(L, 1, &ar);
70 lua_getinfo(L, "nSl", &ar);
71 fprintf(stderr, "WARNING: %s:%d: %s", ar.source, ar.currentline, buf);
74 int ThemeMenu_set(lua_State *L)
76 Theme *theme = get_theme_updata(L);
77 return theme->set_theme_menu(L);
82 // Contains basically the same data as InputState, but does not hold on to
83 // a reference to the frames. This is important so that we can release them
84 // without having to wait for Lua's GC.
85 struct InputStateInfo {
86 InputStateInfo(const InputState& input_state);
88 unsigned last_width[MAX_VIDEO_CARDS], last_height[MAX_VIDEO_CARDS];
89 bool last_interlaced[MAX_VIDEO_CARDS], last_has_signal[MAX_VIDEO_CARDS], last_is_connected[MAX_VIDEO_CARDS];
90 unsigned last_frame_rate_nom[MAX_VIDEO_CARDS], last_frame_rate_den[MAX_VIDEO_CARDS];
91 bool has_last_subtitle[MAX_VIDEO_CARDS];
92 std::string last_subtitle[MAX_VIDEO_CARDS];
95 InputStateInfo::InputStateInfo(const InputState &input_state)
97 for (unsigned signal_num = 0; signal_num < MAX_VIDEO_CARDS; ++signal_num) {
98 BufferedFrame frame = input_state.buffered_frames[signal_num][0];
99 if (frame.frame == nullptr) {
100 last_width[signal_num] = last_height[signal_num] = 0;
101 last_interlaced[signal_num] = false;
102 last_has_signal[signal_num] = false;
103 last_is_connected[signal_num] = false;
106 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
107 last_width[signal_num] = userdata->last_width[frame.field_number];
108 last_height[signal_num] = userdata->last_height[frame.field_number];
109 last_interlaced[signal_num] = userdata->last_interlaced;
110 last_has_signal[signal_num] = userdata->last_has_signal;
111 last_is_connected[signal_num] = userdata->last_is_connected;
112 last_frame_rate_nom[signal_num] = userdata->last_frame_rate_nom;
113 last_frame_rate_den[signal_num] = userdata->last_frame_rate_den;
114 has_last_subtitle[signal_num] = userdata->has_last_subtitle;
115 last_subtitle[signal_num] = userdata->last_subtitle;
120 WHITE_BALANCE_EFFECT,
123 INTEGRAL_PADDING_EFFECT,
128 LIFT_GAMMA_GAIN_EFFECT
131 Effect *instantiate_effect(EffectChain *chain, EffectType effect_type)
133 switch (effect_type) {
134 case WHITE_BALANCE_EFFECT:
135 return new WhiteBalanceEffect;
136 case RESAMPLE_EFFECT:
137 return new ResampleEffect;
139 return new PaddingEffect;
140 case INTEGRAL_PADDING_EFFECT:
141 return new IntegralPaddingEffect;
143 return new OverlayEffect;
145 return new ResizeEffect;
146 case MULTIPLY_EFFECT:
147 return new MultiplyEffect;
149 return new MixEffect;
150 case LIFT_GAMMA_GAIN_EFFECT:
151 return new LiftGammaGainEffect;
153 fprintf(stderr, "Unhandled effect type %d\n", effect_type);
158 // An EffectBlueprint refers to an Effect before it's being added to the graph.
159 // It contains enough information to instantiate the effect, including any
160 // parameters that were set before it was added to the graph. Once it is
161 // instantiated, it forwards its calls on to the real Effect instead.
162 struct EffectBlueprint {
163 EffectBlueprint(EffectType effect_type) : effect_type(effect_type) {}
165 EffectType effect_type;
166 map<string, int> int_parameters;
167 map<string, float> float_parameters;
168 map<string, array<float, 3>> vec3_parameters;
169 map<string, array<float, 4>> vec4_parameters;
171 Effect *effect = nullptr; // Gets filled out when it's instantiated.
174 Effect *get_effect_from_blueprint(EffectChain *chain, lua_State *L, int idx)
176 EffectBlueprint *blueprint = *(EffectBlueprint **)luaL_checkudata(L, idx, "EffectBlueprint");
177 if (blueprint->effect != nullptr) {
178 // NOTE: This will change in the future.
179 luaL_error(L, "An effect can currently only be added to one chain.\n");
182 Effect *effect = instantiate_effect(chain, blueprint->effect_type);
184 // Set the parameters that were deferred earlier.
185 for (const auto &kv : blueprint->int_parameters) {
186 if (!effect->set_int(kv.first, kv.second)) {
187 luaL_error(L, "Effect refused set_int(\"%s\", %d) (invalid key?)", kv.first.c_str(), kv.second);
190 for (const auto &kv : blueprint->float_parameters) {
191 if (!effect->set_float(kv.first, kv.second)) {
192 luaL_error(L, "Effect refused set_float(\"%s\", %f) (invalid key?)", kv.first.c_str(), kv.second);
195 for (const auto &kv : blueprint->vec3_parameters) {
196 if (!effect->set_vec3(kv.first, kv.second.data())) {
197 luaL_error(L, "Effect refused set_vec3(\"%s\", %f, %f, %f) (invalid key?)", kv.first.c_str(),
198 kv.second[0], kv.second[1], kv.second[2]);
201 for (const auto &kv : blueprint->vec4_parameters) {
202 if (!effect->set_vec4(kv.first, kv.second.data())) {
203 luaL_error(L, "Effect refused set_vec4(\"%s\", %f, %f, %f, %f) (invalid key?)", kv.first.c_str(),
204 kv.second[0], kv.second[1], kv.second[2], kv.second[3]);
207 blueprint->effect = effect;
211 InputStateInfo *get_input_state_info(lua_State *L, int idx)
213 if (luaL_testudata(L, idx, "InputStateInfo")) {
214 return (InputStateInfo *)lua_touserdata(L, idx);
216 luaL_error(L, "Error: Index #%d was not InputStateInfo\n", idx);
220 bool checkbool(lua_State* L, int idx)
222 luaL_checktype(L, idx, LUA_TBOOLEAN);
223 return lua_toboolean(L, idx);
226 string checkstdstring(lua_State *L, int index)
229 const char* cstr = lua_tolstring(L, index, &len);
230 return string(cstr, len);
233 void add_outputs_and_finalize(EffectChain *chain, bool is_main_chain)
235 // Add outputs as needed.
236 // NOTE: If you change any details about the output format, you will need to
237 // also update what's given to the muxer (HTTPD::Mux constructor) and
238 // what's put in the H.264 stream (sps_rbsp()).
239 ImageFormat inout_format;
240 inout_format.color_space = COLORSPACE_REC_709;
242 // Output gamma is tricky. We should output Rec. 709 for TV, except that
243 // we expect to run with web players and others that don't really care and
244 // just output with no conversion. So that means we'll need to output sRGB,
245 // even though H.264 has no setting for that (we use “unspecified”).
246 inout_format.gamma_curve = GAMMA_sRGB;
249 YCbCrFormat output_ycbcr_format;
250 // We actually output 4:2:0 and/or 4:2:2 in the end, but chroma subsampling
251 // happens in a pass not run by Movit (see ChromaSubsampler::subsample_chroma()).
252 output_ycbcr_format.chroma_subsampling_x = 1;
253 output_ycbcr_format.chroma_subsampling_y = 1;
255 // This will be overridden if HDMI/SDI output is in force.
256 if (global_flags.ycbcr_rec709_coefficients) {
257 output_ycbcr_format.luma_coefficients = YCBCR_REC_709;
259 output_ycbcr_format.luma_coefficients = YCBCR_REC_601;
262 output_ycbcr_format.full_range = false;
263 output_ycbcr_format.num_levels = 1 << global_flags.x264_bit_depth;
265 GLenum type = global_flags.x264_bit_depth > 8 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_BYTE;
267 chain->add_ycbcr_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED, output_ycbcr_format, YCBCR_OUTPUT_SPLIT_Y_AND_CBCR, type);
269 // If we're using zerocopy video encoding (so the destination
270 // Y texture is owned by VA-API and will be unavailable for
271 // display), add a copy, where we'll only be using the Y component.
272 if (global_flags.use_zerocopy) {
273 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.
275 chain->set_dither_bits(global_flags.x264_bit_depth > 8 ? 16 : 8);
276 chain->set_output_origin(OUTPUT_ORIGIN_TOP_LEFT);
278 chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
284 int EffectChain_new(lua_State* L)
286 assert(lua_gettop(L) == 2);
287 Theme *theme = get_theme_updata(L);
288 int aspect_w = luaL_checknumber(L, 1);
289 int aspect_h = luaL_checknumber(L, 2);
291 return wrap_lua_object<EffectChain>(L, "EffectChain", aspect_w, aspect_h, theme->get_resource_pool());
294 int EffectChain_gc(lua_State* L)
296 assert(lua_gettop(L) == 1);
297 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
298 chain->~EffectChain();
302 int EffectChain_add_live_input(lua_State* L)
304 assert(lua_gettop(L) == 3);
305 Theme *theme = get_theme_updata(L);
306 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
307 bool override_bounce = checkbool(L, 2);
308 bool deinterlace = checkbool(L, 3);
309 bmusb::PixelFormat pixel_format = global_flags.ten_bit_input ? bmusb::PixelFormat_10BitYCbCr : bmusb::PixelFormat_8BitYCbCr;
311 // Needs to be nonowned to match add_video_input (see below).
312 return wrap_lua_object_nonowned<LiveInputWrapper>(L, "LiveInputWrapper", theme, chain, pixel_format, override_bounce, deinterlace, /*user_connectable=*/true);
315 int EffectChain_add_video_input(lua_State* L)
317 assert(lua_gettop(L) == 3);
318 Theme *theme = get_theme_updata(L);
319 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
320 FFmpegCapture **capture = (FFmpegCapture **)luaL_checkudata(L, 2, "VideoInput");
321 bool deinterlace = checkbool(L, 3);
323 // These need to be nonowned, so that the LiveInputWrapper still exists
324 // and can feed frames to the right EffectChain even if the Lua code
325 // doesn't care about the object anymore. (If we change this, we'd need
326 // to also unregister the signal connection on __gc.)
327 int ret = wrap_lua_object_nonowned<LiveInputWrapper>(
328 L, "LiveInputWrapper", theme, chain, (*capture)->get_current_pixel_format(),
329 /*override_bounce=*/false, deinterlace, /*user_connectable=*/false);
331 Theme *theme = get_theme_updata(L);
332 LiveInputWrapper **live_input = (LiveInputWrapper **)lua_touserdata(L, -1);
333 theme->register_video_signal_connection(chain, *live_input, *capture);
339 int EffectChain_add_html_input(lua_State* L)
341 assert(lua_gettop(L) == 2);
342 Theme *theme = get_theme_updata(L);
343 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
344 CEFCapture **capture = (CEFCapture **)luaL_checkudata(L, 2, "HTMLInput");
346 // These need to be nonowned, so that the LiveInputWrapper still exists
347 // and can feed frames to the right EffectChain even if the Lua code
348 // doesn't care about the object anymore. (If we change this, we'd need
349 // to also unregister the signal connection on __gc.)
350 int ret = wrap_lua_object_nonowned<LiveInputWrapper>(
351 L, "LiveInputWrapper", theme, chain, (*capture)->get_current_pixel_format(),
352 /*override_bounce=*/false, /*deinterlace=*/false, /*user_connectable=*/false);
354 Theme *theme = get_theme_updata(L);
355 LiveInputWrapper **live_input = (LiveInputWrapper **)lua_touserdata(L, -1);
356 theme->register_html_signal_connection(chain, *live_input, *capture);
362 int EffectChain_add_effect(lua_State* L)
364 assert(lua_gettop(L) >= 2);
365 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
367 // TODO: Better error reporting.
369 if (luaL_testudata(L, 2, "ImageInput")) {
370 effect = *(ImageInput **)luaL_checkudata(L, 2, "ImageInput");
372 effect = get_effect_from_blueprint(chain, L, 2);
374 if (lua_gettop(L) == 2) {
375 if (effect->num_inputs() == 0) {
376 chain->add_input((Input *)effect);
378 chain->add_effect(effect);
381 vector<Effect *> inputs;
382 for (int idx = 3; idx <= lua_gettop(L); ++idx) {
383 if (luaL_testudata(L, idx, "LiveInputWrapper")) {
384 LiveInputWrapper **input = (LiveInputWrapper **)lua_touserdata(L, idx);
385 inputs.push_back((*input)->get_effect());
386 } else if (luaL_testudata(L, idx, "ImageInput")) {
387 ImageInput *image = *(ImageInput **)luaL_checkudata(L, idx, "ImageInput");
388 inputs.push_back(image);
390 EffectBlueprint *blueprint = *(EffectBlueprint **)luaL_checkudata(L, idx, "EffectBlueprint");
391 assert(blueprint->effect != nullptr); // Parent must be added to the graph.
392 inputs.push_back(blueprint->effect);
395 chain->add_effect(effect, inputs);
398 lua_settop(L, 2); // Return the effect itself.
400 // Make sure Lua doesn't garbage-collect it away.
401 lua_pushvalue(L, -1);
402 luaL_ref(L, LUA_REGISTRYINDEX); // TODO: leak?
407 int EffectChain_finalize(lua_State* L)
409 assert(lua_gettop(L) == 2);
410 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
411 bool is_main_chain = checkbool(L, 2);
412 add_outputs_and_finalize(chain, is_main_chain);
416 int LiveInputWrapper_connect_signal(lua_State* L)
418 assert(lua_gettop(L) == 2);
419 LiveInputWrapper **input = (LiveInputWrapper **)luaL_checkudata(L, 1, "LiveInputWrapper");
420 int signal_num = luaL_checknumber(L, 2);
421 bool success = (*input)->connect_signal(signal_num);
423 print_warning(L, "Calling connect_signal() on a video or HTML input. Ignoring.\n");
428 int ImageInput_new(lua_State* L)
430 assert(lua_gettop(L) == 1);
431 string filename = checkstdstring(L, 1);
432 return wrap_lua_object_nonowned<ImageInput>(L, "ImageInput", filename);
435 int VideoInput_new(lua_State* L)
437 assert(lua_gettop(L) == 2);
438 string filename = checkstdstring(L, 1);
439 int pixel_format = luaL_checknumber(L, 2);
440 if (pixel_format != bmusb::PixelFormat_8BitYCbCrPlanar &&
441 pixel_format != bmusb::PixelFormat_8BitBGRA) {
442 print_warning(L, "Invalid enum %d used for video format, choosing Y'CbCr.\n", pixel_format);
443 pixel_format = bmusb::PixelFormat_8BitYCbCrPlanar;
445 int ret = wrap_lua_object_nonowned<FFmpegCapture>(L, "VideoInput", filename, global_flags.width, global_flags.height);
447 FFmpegCapture **capture = (FFmpegCapture **)lua_touserdata(L, -1);
448 (*capture)->set_pixel_format(bmusb::PixelFormat(pixel_format));
450 Theme *theme = get_theme_updata(L);
451 theme->register_video_input(*capture);
456 int VideoInput_rewind(lua_State* L)
458 assert(lua_gettop(L) == 1);
459 FFmpegCapture **video_input = (FFmpegCapture **)luaL_checkudata(L, 1, "VideoInput");
460 (*video_input)->rewind();
464 int VideoInput_disconnect(lua_State* L)
466 assert(lua_gettop(L) == 1);
467 FFmpegCapture **video_input = (FFmpegCapture **)luaL_checkudata(L, 1, "VideoInput");
468 (*video_input)->disconnect();
472 int VideoInput_change_rate(lua_State* L)
474 assert(lua_gettop(L) == 2);
475 FFmpegCapture **video_input = (FFmpegCapture **)luaL_checkudata(L, 1, "VideoInput");
476 double new_rate = luaL_checknumber(L, 2);
477 (*video_input)->change_rate(new_rate);
481 int VideoInput_get_signal_num(lua_State* L)
483 assert(lua_gettop(L) == 1);
484 FFmpegCapture **video_input = (FFmpegCapture **)luaL_checkudata(L, 1, "VideoInput");
485 lua_pushnumber(L, -1 - (*video_input)->get_card_index());
489 int HTMLInput_new(lua_State* L)
492 assert(lua_gettop(L) == 1);
493 string url = checkstdstring(L, 1);
494 int ret = wrap_lua_object_nonowned<CEFCapture>(L, "HTMLInput", url, global_flags.width, global_flags.height);
496 CEFCapture **capture = (CEFCapture **)lua_touserdata(L, -1);
497 Theme *theme = get_theme_updata(L);
498 theme->register_html_input(*capture);
502 fprintf(stderr, "This version of Nageru has been compiled without CEF support.\n");
503 fprintf(stderr, "HTMLInput is not available.\n");
509 int HTMLInput_set_url(lua_State* L)
511 assert(lua_gettop(L) == 2);
512 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
513 string new_url = checkstdstring(L, 2);
514 (*video_input)->set_url(new_url);
518 int HTMLInput_reload(lua_State* L)
520 assert(lua_gettop(L) == 1);
521 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
522 (*video_input)->reload();
526 int HTMLInput_set_max_fps(lua_State* L)
528 assert(lua_gettop(L) == 2);
529 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
530 int max_fps = lrint(luaL_checknumber(L, 2));
531 (*video_input)->set_max_fps(max_fps);
535 int HTMLInput_execute_javascript_async(lua_State* L)
537 assert(lua_gettop(L) == 2);
538 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
539 string js = checkstdstring(L, 2);
540 (*video_input)->execute_javascript_async(js);
544 int HTMLInput_resize(lua_State* L)
546 assert(lua_gettop(L) == 3);
547 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
548 unsigned width = lrint(luaL_checknumber(L, 2));
549 unsigned height = lrint(luaL_checknumber(L, 3));
550 (*video_input)->resize(width, height);
554 int HTMLInput_get_signal_num(lua_State* L)
556 assert(lua_gettop(L) == 1);
557 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
558 lua_pushnumber(L, -1 - (*video_input)->get_card_index());
563 int WhiteBalanceEffect_new(lua_State* L)
565 assert(lua_gettop(L) == 0);
566 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", WHITE_BALANCE_EFFECT);
569 int ResampleEffect_new(lua_State* L)
571 assert(lua_gettop(L) == 0);
572 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", RESAMPLE_EFFECT);
575 int PaddingEffect_new(lua_State* L)
577 assert(lua_gettop(L) == 0);
578 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", PADDING_EFFECT);
581 int IntegralPaddingEffect_new(lua_State* L)
583 assert(lua_gettop(L) == 0);
584 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", INTEGRAL_PADDING_EFFECT);
587 int OverlayEffect_new(lua_State* L)
589 assert(lua_gettop(L) == 0);
590 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", OVERLAY_EFFECT);
593 int ResizeEffect_new(lua_State* L)
595 assert(lua_gettop(L) == 0);
596 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", RESIZE_EFFECT);
599 int MultiplyEffect_new(lua_State* L)
601 assert(lua_gettop(L) == 0);
602 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", MULTIPLY_EFFECT);
605 int MixEffect_new(lua_State* L)
607 assert(lua_gettop(L) == 0);
608 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", MIX_EFFECT);
611 int LiftGammaGainEffect_new(lua_State* L)
613 assert(lua_gettop(L) == 0);
614 return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", LIFT_GAMMA_GAIN_EFFECT);
617 int InputStateInfo_get_width(lua_State* L)
619 assert(lua_gettop(L) == 2);
620 InputStateInfo *input_state_info = get_input_state_info(L, 1);
621 Theme *theme = get_theme_updata(L);
622 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
623 lua_pushnumber(L, input_state_info->last_width[signal_num]);
627 int InputStateInfo_get_height(lua_State* L)
629 assert(lua_gettop(L) == 2);
630 InputStateInfo *input_state_info = get_input_state_info(L, 1);
631 Theme *theme = get_theme_updata(L);
632 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
633 lua_pushnumber(L, input_state_info->last_height[signal_num]);
637 int InputStateInfo_get_interlaced(lua_State* L)
639 assert(lua_gettop(L) == 2);
640 InputStateInfo *input_state_info = get_input_state_info(L, 1);
641 Theme *theme = get_theme_updata(L);
642 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
643 lua_pushboolean(L, input_state_info->last_interlaced[signal_num]);
647 int InputStateInfo_get_has_signal(lua_State* L)
649 assert(lua_gettop(L) == 2);
650 InputStateInfo *input_state_info = get_input_state_info(L, 1);
651 Theme *theme = get_theme_updata(L);
652 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
653 lua_pushboolean(L, input_state_info->last_has_signal[signal_num]);
657 int InputStateInfo_get_is_connected(lua_State* L)
659 assert(lua_gettop(L) == 2);
660 InputStateInfo *input_state_info = get_input_state_info(L, 1);
661 Theme *theme = get_theme_updata(L);
662 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
663 lua_pushboolean(L, input_state_info->last_is_connected[signal_num]);
667 int InputStateInfo_get_frame_rate_nom(lua_State* L)
669 assert(lua_gettop(L) == 2);
670 InputStateInfo *input_state_info = get_input_state_info(L, 1);
671 Theme *theme = get_theme_updata(L);
672 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
673 lua_pushnumber(L, input_state_info->last_frame_rate_nom[signal_num]);
677 int InputStateInfo_get_frame_rate_den(lua_State* L)
679 assert(lua_gettop(L) == 2);
680 InputStateInfo *input_state_info = get_input_state_info(L, 1);
681 Theme *theme = get_theme_updata(L);
682 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
683 lua_pushnumber(L, input_state_info->last_frame_rate_den[signal_num]);
687 int InputStateInfo_get_last_subtitle(lua_State* L)
689 assert(lua_gettop(L) == 2);
690 InputStateInfo *input_state_info = get_input_state_info(L, 1);
691 Theme *theme = get_theme_updata(L);
692 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
693 if (!input_state_info->has_last_subtitle[signal_num]) {
696 lua_pushstring(L, input_state_info->last_subtitle[signal_num].c_str());
701 int EffectBlueprint_set_int(lua_State *L)
703 assert(lua_gettop(L) == 3);
704 EffectBlueprint *blueprint = *(EffectBlueprint **)luaL_checkudata(L, 1, "EffectBlueprint");
705 string key = checkstdstring(L, 2);
706 float value = luaL_checknumber(L, 3);
707 if (blueprint->effect != nullptr) {
708 if (!blueprint->effect->set_int(key, value)) {
709 luaL_error(L, "Effect refused set_int(\"%s\", %d) (invalid key?)", key.c_str(), int(value));
712 // TODO: check validity already here, if possible?
713 blueprint->int_parameters[key] = value;
718 int EffectBlueprint_set_float(lua_State *L)
720 assert(lua_gettop(L) == 3);
721 EffectBlueprint *blueprint = *(EffectBlueprint **)luaL_checkudata(L, 1, "EffectBlueprint");
722 string key = checkstdstring(L, 2);
723 float value = luaL_checknumber(L, 3);
724 if (blueprint->effect != nullptr) {
725 if (!blueprint->effect->set_float(key, value)) {
726 luaL_error(L, "Effect refused set_float(\"%s\", %d) (invalid key?)", key.c_str(), int(value));
729 // TODO: check validity already here, if possible?
730 blueprint->float_parameters[key] = value;
735 int EffectBlueprint_set_vec3(lua_State *L)
737 assert(lua_gettop(L) == 5);
738 EffectBlueprint *blueprint = *(EffectBlueprint **)luaL_checkudata(L, 1, "EffectBlueprint");
739 string key = checkstdstring(L, 2);
741 v[0] = luaL_checknumber(L, 3);
742 v[1] = luaL_checknumber(L, 4);
743 v[2] = luaL_checknumber(L, 5);
745 if (blueprint->effect != nullptr) {
746 if (!blueprint->effect->set_vec3(key, v.data())) {
747 luaL_error(L, "Effect refused set_vec3(\"%s\", %f, %f, %f) (invalid key?)", key.c_str(),
751 // TODO: check validity already here, if possible?
752 blueprint->vec3_parameters[key] = v;
758 int EffectBlueprint_set_vec4(lua_State *L)
760 assert(lua_gettop(L) == 6);
761 EffectBlueprint *blueprint = *(EffectBlueprint **)luaL_checkudata(L, 1, "EffectBlueprint");
762 string key = checkstdstring(L, 2);
764 v[0] = luaL_checknumber(L, 3);
765 v[1] = luaL_checknumber(L, 4);
766 v[2] = luaL_checknumber(L, 5);
767 v[3] = luaL_checknumber(L, 6);
768 if (blueprint->effect != nullptr) {
769 if (!blueprint->effect->set_vec4(key, v.data())) {
770 luaL_error(L, "Effect refused set_vec4(\"%s\", %f, %f, %f, %f) (invalid key?)", key.c_str(),
771 v[0], v[1], v[2], v[3]);
774 // TODO: check validity already here, if possible?
775 blueprint->vec4_parameters[key] = v;
780 const luaL_Reg EffectBlueprint_funcs[] = {
781 // NOTE: No new() function; that's for the individual effects.
782 { "set_int", EffectBlueprint_set_int },
783 { "set_float", EffectBlueprint_set_float },
784 { "set_vec3", EffectBlueprint_set_vec3 },
785 { "set_vec4", EffectBlueprint_set_vec4 },
789 const luaL_Reg EffectChain_funcs[] = {
790 { "new", EffectChain_new },
791 { "__gc", EffectChain_gc },
792 { "add_live_input", EffectChain_add_live_input },
793 { "add_video_input", EffectChain_add_video_input },
795 { "add_html_input", EffectChain_add_html_input },
797 { "add_effect", EffectChain_add_effect },
798 { "finalize", EffectChain_finalize },
802 const luaL_Reg LiveInputWrapper_funcs[] = {
803 { "connect_signal", LiveInputWrapper_connect_signal },
807 const luaL_Reg ImageInput_funcs[] = {
808 { "new", ImageInput_new },
812 const luaL_Reg VideoInput_funcs[] = {
813 { "new", VideoInput_new },
814 { "rewind", VideoInput_rewind },
815 { "disconnect", VideoInput_disconnect },
816 { "change_rate", VideoInput_change_rate },
817 { "get_signal_num", VideoInput_get_signal_num },
821 const luaL_Reg HTMLInput_funcs[] = {
822 { "new", HTMLInput_new },
824 { "set_url", HTMLInput_set_url },
825 { "reload", HTMLInput_reload },
826 { "set_max_fps", HTMLInput_set_max_fps },
827 { "execute_javascript_async", HTMLInput_execute_javascript_async },
828 { "resize", HTMLInput_resize },
829 { "get_signal_num", HTMLInput_get_signal_num },
835 // All of these are solely for new(); the returned metatable will be that of
836 // EffectBlueprint, and Effect (returned from add_effect()) is its own type.
838 const luaL_Reg WhiteBalanceEffect_funcs[] = {
839 { "new", WhiteBalanceEffect_new },
843 const luaL_Reg ResampleEffect_funcs[] = {
844 { "new", ResampleEffect_new },
848 const luaL_Reg PaddingEffect_funcs[] = {
849 { "new", PaddingEffect_new },
853 const luaL_Reg IntegralPaddingEffect_funcs[] = {
854 { "new", IntegralPaddingEffect_new },
858 const luaL_Reg OverlayEffect_funcs[] = {
859 { "new", OverlayEffect_new },
863 const luaL_Reg ResizeEffect_funcs[] = {
864 { "new", ResizeEffect_new },
868 const luaL_Reg MultiplyEffect_funcs[] = {
869 { "new", MultiplyEffect_new },
873 const luaL_Reg MixEffect_funcs[] = {
874 { "new", MixEffect_new },
878 const luaL_Reg LiftGammaGainEffect_funcs[] = {
879 { "new", LiftGammaGainEffect_new },
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 },
893 { "get_last_subtitle", InputStateInfo_get_last_subtitle },
897 const luaL_Reg ThemeMenu_funcs[] = {
898 { "set", ThemeMenu_set },
904 LiveInputWrapper::LiveInputWrapper(
907 bmusb::PixelFormat pixel_format,
908 bool override_bounce,
910 bool user_connectable)
912 pixel_format(pixel_format),
913 deinterlace(deinterlace),
914 user_connectable(user_connectable)
916 ImageFormat inout_format;
917 inout_format.color_space = COLORSPACE_sRGB;
919 // Gamma curve depends on the input signal, and we don't really get any
920 // indications. A camera would be expected to do Rec. 709, but
921 // I haven't checked if any do in practice. However, computers _do_ output
922 // in sRGB gamma (ie., they don't convert from sRGB to Rec. 709), and
923 // I wouldn't really be surprised if most non-professional cameras do, too.
924 // So we pick sRGB as the least evil here.
925 inout_format.gamma_curve = GAMMA_sRGB;
929 deinterlace_effect = new movit::DeinterlaceEffect();
931 // As per the comments in deinterlace_effect.h, we turn this off.
932 // The most likely interlaced input for us is either a camera
933 // (where it's fine to turn it off) or a laptop (where it _should_
935 CHECK(deinterlace_effect->set_int("enable_spatial_interlacing_check", 0));
937 num_inputs = deinterlace_effect->num_inputs();
938 assert(num_inputs == FRAME_HISTORY_LENGTH);
943 if (pixel_format == bmusb::PixelFormat_8BitBGRA) {
944 for (unsigned i = 0; i < num_inputs; ++i) {
945 // We upload our textures ourselves, and Movit swaps
946 // R and B in the shader if we specify BGRA, so lie and say RGBA.
947 rgba_inputs.push_back(new sRGBSwitchingFlatInput(inout_format, FORMAT_RGBA_POSTMULTIPLIED_ALPHA, GL_UNSIGNED_BYTE, global_flags.width, global_flags.height));
948 chain->add_input(rgba_inputs.back());
952 vector<Effect *> reverse_inputs(rgba_inputs.rbegin(), rgba_inputs.rend());
953 chain->add_effect(deinterlace_effect, reverse_inputs);
956 assert(pixel_format == bmusb::PixelFormat_8BitYCbCr ||
957 pixel_format == bmusb::PixelFormat_10BitYCbCr ||
958 pixel_format == bmusb::PixelFormat_8BitYCbCrPlanar);
960 // Most of these settings will be overridden later if using PixelFormat_8BitYCbCrPlanar.
961 input_ycbcr_format.chroma_subsampling_x = (pixel_format == bmusb::PixelFormat_10BitYCbCr) ? 1 : 2;
962 input_ycbcr_format.chroma_subsampling_y = 1;
963 input_ycbcr_format.num_levels = (pixel_format == bmusb::PixelFormat_10BitYCbCr) ? 1024 : 256;
964 input_ycbcr_format.cb_x_position = 0.0;
965 input_ycbcr_format.cr_x_position = 0.0;
966 input_ycbcr_format.cb_y_position = 0.5;
967 input_ycbcr_format.cr_y_position = 0.5;
968 input_ycbcr_format.luma_coefficients = YCBCR_REC_709; // Will be overridden later even if not planar.
969 input_ycbcr_format.full_range = false; // Will be overridden later even if not planar.
971 for (unsigned i = 0; i < num_inputs; ++i) {
972 // When using 10-bit input, we're converting to interleaved through v210Converter.
973 YCbCrInputSplitting splitting;
974 if (pixel_format == bmusb::PixelFormat_10BitYCbCr) {
975 splitting = YCBCR_INPUT_INTERLEAVED;
976 } else if (pixel_format == bmusb::PixelFormat_8BitYCbCr) {
977 splitting = YCBCR_INPUT_SPLIT_Y_AND_CBCR;
979 splitting = YCBCR_INPUT_PLANAR;
981 if (override_bounce) {
982 ycbcr_inputs.push_back(new NonBouncingYCbCrInput(inout_format, input_ycbcr_format, global_flags.width, global_flags.height, splitting));
984 ycbcr_inputs.push_back(new YCbCrInput(inout_format, input_ycbcr_format, global_flags.width, global_flags.height, splitting));
986 chain->add_input(ycbcr_inputs.back());
990 vector<Effect *> reverse_inputs(ycbcr_inputs.rbegin(), ycbcr_inputs.rend());
991 chain->add_effect(deinterlace_effect, reverse_inputs);
996 bool LiveInputWrapper::connect_signal(int signal_num)
998 if (!user_connectable) {
1002 if (global_mixer == nullptr) {
1007 signal_num = theme->map_signal(signal_num);
1008 connect_signal_raw(signal_num, *theme->input_state);
1012 void LiveInputWrapper::connect_signal_raw(int signal_num, const InputState &input_state)
1014 BufferedFrame first_frame = input_state.buffered_frames[signal_num][0];
1015 if (first_frame.frame == nullptr) {
1019 unsigned width, height;
1021 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)first_frame.frame->userdata;
1022 width = userdata->last_width[first_frame.field_number];
1023 height = userdata->last_height[first_frame.field_number];
1024 if (userdata->last_interlaced) {
1029 movit::YCbCrLumaCoefficients ycbcr_coefficients = input_state.ycbcr_coefficients[signal_num];
1030 bool full_range = input_state.full_range[signal_num];
1032 if (input_state.ycbcr_coefficients_auto[signal_num]) {
1035 // The Blackmagic driver docs claim that the device outputs Y'CbCr
1036 // according to Rec. 601, but this seems to indicate the subsampling
1037 // positions only, as they publish Y'CbCr → RGB formulas that are
1038 // different for HD and SD (corresponding to Rec. 709 and 601, respectively),
1039 // and a Lenovo X1 gen 3 I used to test definitely outputs Rec. 709
1040 // (at least up to rounding error). Other devices seem to use Rec. 601
1041 // even on HD resolutions. Nevertheless, Rec. 709 _is_ the right choice
1042 // for HD, so we default to that if the user hasn't set anything.
1043 if (height >= 720) {
1044 ycbcr_coefficients = YCBCR_REC_709;
1046 ycbcr_coefficients = YCBCR_REC_601;
1050 // This is a global, but it doesn't really matter.
1051 input_ycbcr_format.luma_coefficients = ycbcr_coefficients;
1052 input_ycbcr_format.full_range = full_range;
1054 BufferedFrame last_good_frame = first_frame;
1055 for (unsigned i = 0; i < max(ycbcr_inputs.size(), rgba_inputs.size()); ++i) {
1056 BufferedFrame frame = input_state.buffered_frames[signal_num][i];
1057 if (frame.frame == nullptr) {
1058 // Not enough data; reuse last frame (well, field).
1059 // This is suboptimal, but we have nothing better.
1060 frame = last_good_frame;
1062 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
1064 unsigned this_width = userdata->last_width[frame.field_number];
1065 unsigned this_height = userdata->last_height[frame.field_number];
1066 if (this_width != width || this_height != height) {
1067 // Resolution changed; reuse last frame/field.
1068 frame = last_good_frame;
1069 userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
1072 assert(userdata->pixel_format == pixel_format);
1073 switch (pixel_format) {
1074 case bmusb::PixelFormat_8BitYCbCr:
1075 ycbcr_inputs[i]->set_texture_num(0, userdata->tex_y[frame.field_number]);
1076 ycbcr_inputs[i]->set_texture_num(1, userdata->tex_cbcr[frame.field_number]);
1077 ycbcr_inputs[i]->change_ycbcr_format(input_ycbcr_format);
1078 ycbcr_inputs[i]->set_width(width);
1079 ycbcr_inputs[i]->set_height(height);
1081 case bmusb::PixelFormat_8BitYCbCrPlanar:
1082 ycbcr_inputs[i]->set_texture_num(0, userdata->tex_y[frame.field_number]);
1083 ycbcr_inputs[i]->set_texture_num(1, userdata->tex_cb[frame.field_number]);
1084 ycbcr_inputs[i]->set_texture_num(2, userdata->tex_cr[frame.field_number]);
1085 ycbcr_inputs[i]->change_ycbcr_format(userdata->ycbcr_format);
1086 ycbcr_inputs[i]->set_width(width);
1087 ycbcr_inputs[i]->set_height(height);
1089 case bmusb::PixelFormat_10BitYCbCr:
1090 ycbcr_inputs[i]->set_texture_num(0, userdata->tex_444[frame.field_number]);
1091 ycbcr_inputs[i]->change_ycbcr_format(input_ycbcr_format);
1092 ycbcr_inputs[i]->set_width(width);
1093 ycbcr_inputs[i]->set_height(height);
1095 case bmusb::PixelFormat_8BitBGRA:
1096 rgba_inputs[i]->set_texture_num(userdata->tex_rgba[frame.field_number]);
1097 rgba_inputs[i]->set_width(width);
1098 rgba_inputs[i]->set_height(height);
1104 last_good_frame = frame;
1108 BufferedFrame frame = input_state.buffered_frames[signal_num][0];
1109 CHECK(deinterlace_effect->set_int("current_field_position", frame.field_number));
1115 int call_num_channels(lua_State *L)
1117 lua_getglobal(L, "num_channels");
1119 if (lua_pcall(L, 0, 1, 0) != 0) {
1120 fprintf(stderr, "error running function `num_channels': %s\n", lua_tostring(L, -1));
1124 int num_channels = luaL_checknumber(L, 1);
1126 assert(lua_gettop(L) == 0);
1127 return num_channels;
1132 Theme::Theme(const string &filename, const vector<string> &search_dirs, ResourcePool *resource_pool, unsigned num_cards)
1133 : resource_pool(resource_pool), num_cards(num_cards), signal_to_card_mapping(global_flags.default_stream_mapping)
1135 L = luaL_newstate();
1138 // Search through all directories until we find a file that will load
1139 // (as in, does not return LUA_ERRFILE); then run it. We store load errors
1140 // from all the attempts, and show them once we know we can't find any of them.
1142 vector<string> errors;
1143 bool success = false;
1145 vector<string> real_search_dirs;
1146 if (!filename.empty() && filename[0] == '/') {
1147 real_search_dirs.push_back("");
1149 real_search_dirs = search_dirs;
1154 for (const string &dir : real_search_dirs) {
1158 path = dir + "/" + filename;
1160 int err = luaL_loadfile(L, path.c_str());
1162 // Save the theme for when we're actually going to run it
1163 // (we need to set up the right environment below first,
1164 // and we couldn't do that before, because we didn't know the
1165 // path to put in Nageru.THEME_PATH).
1166 theme_code_ref = luaL_ref(L, LUA_REGISTRYINDEX);
1167 assert(lua_gettop(L) == 0);
1172 errors.push_back(lua_tostring(L, -1));
1174 if (err != LUA_ERRFILE) {
1175 // The file actually loaded, but failed to parse somehow. Abort; don't try the next one.
1181 for (const string &error : errors) {
1182 fprintf(stderr, "%s\n", error.c_str());
1186 assert(lua_gettop(L) == 0);
1188 // Make sure the path exposed to the theme (as Nageru.THEME_PATH;
1189 // can be useful for locating files when talking to CEF) is absolute.
1190 // In a sense, it would be nice if realpath() had a mode not to
1191 // resolve symlinks, but it doesn't, so we only call it if we don't
1192 // already have an absolute path (which may leave ../ elements etc.).
1193 if (path[0] == '/') {
1196 char *absolute_theme_path = realpath(path.c_str(), nullptr);
1197 theme_path = absolute_theme_path;
1198 free(absolute_theme_path);
1201 // Set up the API we provide.
1202 register_constants();
1203 register_class("EffectBlueprint", EffectBlueprint_funcs);
1204 register_class("EffectChain", EffectChain_funcs);
1205 register_class("LiveInputWrapper", LiveInputWrapper_funcs);
1206 register_class("ImageInput", ImageInput_funcs);
1207 register_class("VideoInput", VideoInput_funcs);
1208 register_class("HTMLInput", HTMLInput_funcs);
1209 register_class("WhiteBalanceEffect", WhiteBalanceEffect_funcs);
1210 register_class("ResampleEffect", ResampleEffect_funcs);
1211 register_class("PaddingEffect", PaddingEffect_funcs);
1212 register_class("IntegralPaddingEffect", IntegralPaddingEffect_funcs);
1213 register_class("OverlayEffect", OverlayEffect_funcs);
1214 register_class("ResizeEffect", ResizeEffect_funcs);
1215 register_class("MultiplyEffect", MultiplyEffect_funcs);
1216 register_class("MixEffect", MixEffect_funcs);
1217 register_class("LiftGammaGainEffect", LiftGammaGainEffect_funcs);
1218 register_class("InputStateInfo", InputStateInfo_funcs);
1219 register_class("ThemeMenu", ThemeMenu_funcs);
1221 // Now actually run the theme to get everything set up.
1222 lua_rawgeti(L, LUA_REGISTRYINDEX, theme_code_ref);
1223 luaL_unref(L, LUA_REGISTRYINDEX, theme_code_ref);
1224 if (lua_pcall(L, 0, 0, 0)) {
1225 fprintf(stderr, "Error when running %s: %s\n", path.c_str(), lua_tostring(L, -1));
1228 assert(lua_gettop(L) == 0);
1230 // Ask it for the number of channels.
1231 num_channels = call_num_channels(L);
1239 void Theme::register_constants()
1241 // Set Nageru.VIDEO_FORMAT_BGRA = bmusb::PixelFormat_8BitBGRA, etc.
1242 const vector<pair<string, int>> num_constants = {
1243 { "VIDEO_FORMAT_BGRA", bmusb::PixelFormat_8BitBGRA },
1244 { "VIDEO_FORMAT_YCBCR", bmusb::PixelFormat_8BitYCbCrPlanar },
1246 const vector<pair<string, string>> str_constants = {
1247 { "THEME_PATH", theme_path },
1250 lua_newtable(L); // t = {}
1252 for (const pair<string, int> &constant : num_constants) {
1253 lua_pushstring(L, constant.first.c_str());
1254 lua_pushinteger(L, constant.second);
1255 lua_settable(L, 1); // t[key] = value
1257 for (const pair<string, string> &constant : str_constants) {
1258 lua_pushstring(L, constant.first.c_str());
1259 lua_pushstring(L, constant.second.c_str());
1260 lua_settable(L, 1); // t[key] = value
1263 lua_setglobal(L, "Nageru"); // Nageru = t
1264 assert(lua_gettop(L) == 0);
1267 void Theme::register_class(const char *class_name, const luaL_Reg *funcs)
1269 assert(lua_gettop(L) == 0);
1270 luaL_newmetatable(L, class_name); // mt = {}
1271 lua_pushlightuserdata(L, this);
1272 luaL_setfuncs(L, funcs, 1); // for (name,f in funcs) { mt[name] = f, with upvalue {theme} }
1273 lua_pushvalue(L, -1);
1274 lua_setfield(L, -2, "__index"); // mt.__index = mt
1275 lua_setglobal(L, class_name); // ClassName = mt
1276 assert(lua_gettop(L) == 0);
1279 Theme::Chain Theme::get_chain(unsigned num, float t, unsigned width, unsigned height, const InputState &input_state)
1283 lock_guard<mutex> lock(m);
1284 assert(lua_gettop(L) == 0);
1285 lua_getglobal(L, "get_chain"); /* function to be called */
1286 lua_pushnumber(L, num);
1287 lua_pushnumber(L, t);
1288 lua_pushnumber(L, width);
1289 lua_pushnumber(L, height);
1290 wrap_lua_object<InputStateInfo>(L, "InputStateInfo", input_state);
1292 if (lua_pcall(L, 5, 2, 0) != 0) {
1293 fprintf(stderr, "error running function `get_chain': %s\n", lua_tostring(L, -1));
1297 EffectChain *effect_chain = (EffectChain *)luaL_testudata(L, -2, "EffectChain");
1298 if (effect_chain == nullptr) {
1299 fprintf(stderr, "get_chain() for chain number %d did not return an EffectChain\n",
1303 chain.chain = effect_chain;
1304 if (!lua_isfunction(L, -1)) {
1305 fprintf(stderr, "Argument #-1 should be a function\n");
1308 lua_pushvalue(L, -1);
1309 shared_ptr<LuaRefWithDeleter> funcref(new LuaRefWithDeleter(&m, L, luaL_ref(L, LUA_REGISTRYINDEX)));
1311 assert(lua_gettop(L) == 0);
1313 chain.setup_chain = [this, funcref, input_state, effect_chain]{
1314 lock_guard<mutex> lock(m);
1316 assert(this->input_state == nullptr);
1317 this->input_state = &input_state;
1319 // Set up state, including connecting signals.
1320 lua_rawgeti(L, LUA_REGISTRYINDEX, funcref->get());
1321 if (lua_pcall(L, 0, 0, 0) != 0) {
1322 fprintf(stderr, "error running chain setup callback: %s\n", lua_tostring(L, -1));
1325 assert(lua_gettop(L) == 0);
1327 // The theme can't (or at least shouldn't!) call connect_signal() on
1328 // each FFmpeg or CEF input, so we'll do it here.
1329 if (video_signal_connections.count(effect_chain)) {
1330 for (const VideoSignalConnection &conn : video_signal_connections[effect_chain]) {
1331 conn.wrapper->connect_signal_raw(conn.source->get_card_index(), input_state);
1335 if (html_signal_connections.count(effect_chain)) {
1336 for (const CEFSignalConnection &conn : html_signal_connections[effect_chain]) {
1337 conn.wrapper->connect_signal_raw(conn.source->get_card_index(), input_state);
1342 this->input_state = nullptr;
1345 // TODO: Can we do better, e.g. by running setup_chain() and seeing what it references?
1346 // Actually, setup_chain does maybe hold all the references we need now anyway?
1347 chain.input_frames.reserve(num_cards * FRAME_HISTORY_LENGTH);
1348 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
1349 for (unsigned frame_num = 0; frame_num < FRAME_HISTORY_LENGTH; ++frame_num) {
1350 chain.input_frames.push_back(input_state.buffered_frames[card_index][frame_num].frame);
1357 string Theme::get_channel_name(unsigned channel)
1359 lock_guard<mutex> lock(m);
1360 lua_getglobal(L, "channel_name");
1361 lua_pushnumber(L, channel);
1362 if (lua_pcall(L, 1, 1, 0) != 0) {
1363 fprintf(stderr, "error running function `channel_name': %s\n", lua_tostring(L, -1));
1366 const char *ret = lua_tostring(L, -1);
1367 if (ret == nullptr) {
1368 fprintf(stderr, "function `channel_name' returned nil for channel %d\n", channel);
1372 string retstr = ret;
1374 assert(lua_gettop(L) == 0);
1378 int Theme::get_channel_signal(unsigned channel)
1380 lock_guard<mutex> lock(m);
1381 lua_getglobal(L, "channel_signal");
1382 lua_pushnumber(L, channel);
1383 if (lua_pcall(L, 1, 1, 0) != 0) {
1384 fprintf(stderr, "error running function `channel_signal': %s\n", lua_tostring(L, -1));
1388 int ret = luaL_checknumber(L, 1);
1390 assert(lua_gettop(L) == 0);
1394 std::string Theme::get_channel_color(unsigned channel)
1396 lock_guard<mutex> lock(m);
1397 lua_getglobal(L, "channel_color");
1398 lua_pushnumber(L, channel);
1399 if (lua_pcall(L, 1, 1, 0) != 0) {
1400 fprintf(stderr, "error running function `channel_color': %s\n", lua_tostring(L, -1));
1404 const char *ret = lua_tostring(L, -1);
1405 if (ret == nullptr) {
1406 fprintf(stderr, "function `channel_color' returned nil for channel %d\n", channel);
1410 string retstr = ret;
1412 assert(lua_gettop(L) == 0);
1416 bool Theme::get_supports_set_wb(unsigned channel)
1418 lock_guard<mutex> lock(m);
1419 lua_getglobal(L, "supports_set_wb");
1420 lua_pushnumber(L, channel);
1421 if (lua_pcall(L, 1, 1, 0) != 0) {
1422 fprintf(stderr, "error running function `supports_set_wb': %s\n", lua_tostring(L, -1));
1426 bool ret = checkbool(L, -1);
1428 assert(lua_gettop(L) == 0);
1432 void Theme::set_wb(unsigned channel, double r, double g, double b)
1434 lock_guard<mutex> lock(m);
1435 lua_getglobal(L, "set_wb");
1436 lua_pushnumber(L, channel);
1437 lua_pushnumber(L, r);
1438 lua_pushnumber(L, g);
1439 lua_pushnumber(L, b);
1440 if (lua_pcall(L, 4, 0, 0) != 0) {
1441 fprintf(stderr, "error running function `set_wb': %s\n", lua_tostring(L, -1));
1445 assert(lua_gettop(L) == 0);
1448 vector<string> Theme::get_transition_names(float t)
1450 lock_guard<mutex> lock(m);
1451 lua_getglobal(L, "get_transitions");
1452 lua_pushnumber(L, t);
1453 if (lua_pcall(L, 1, 1, 0) != 0) {
1454 fprintf(stderr, "error running function `get_transitions': %s\n", lua_tostring(L, -1));
1460 while (lua_next(L, -2) != 0) {
1461 ret.push_back(lua_tostring(L, -1));
1465 assert(lua_gettop(L) == 0);
1469 int Theme::map_signal(int signal_num)
1471 // Negative numbers map to raw signals.
1472 if (signal_num < 0) {
1473 return -1 - signal_num;
1476 lock_guard<mutex> lock(map_m);
1477 if (signal_to_card_mapping.count(signal_num)) {
1478 return signal_to_card_mapping[signal_num];
1482 if (global_flags.output_card != -1 && num_cards > 1) {
1483 // Try to exclude the output card from the default card_index.
1484 card_index = signal_num % (num_cards - 1);
1485 if (card_index >= global_flags.output_card) {
1488 if (signal_num >= int(num_cards - 1)) {
1489 print_warning(L, "Theme asked for input %d, but we only have %u input card(s) (card %d is busy with output).\n",
1490 signal_num, num_cards - 1, global_flags.output_card);
1491 fprintf(stderr, "Mapping to card %d instead.\n", card_index);
1494 card_index = signal_num % num_cards;
1495 if (signal_num >= int(num_cards)) {
1496 print_warning(L, "Theme asked for input %d, but we only have %u card(s).\n", signal_num, num_cards);
1497 fprintf(stderr, "Mapping to card %d instead.\n", card_index);
1500 signal_to_card_mapping[signal_num] = card_index;
1504 void Theme::set_signal_mapping(int signal_num, int card_num)
1506 lock_guard<mutex> lock(map_m);
1507 assert(card_num < int(num_cards));
1508 signal_to_card_mapping[signal_num] = card_num;
1511 void Theme::transition_clicked(int transition_num, float t)
1513 lock_guard<mutex> lock(m);
1514 lua_getglobal(L, "transition_clicked");
1515 lua_pushnumber(L, transition_num);
1516 lua_pushnumber(L, t);
1518 if (lua_pcall(L, 2, 0, 0) != 0) {
1519 fprintf(stderr, "error running function `transition_clicked': %s\n", lua_tostring(L, -1));
1522 assert(lua_gettop(L) == 0);
1525 void Theme::channel_clicked(int preview_num)
1527 lock_guard<mutex> lock(m);
1528 lua_getglobal(L, "channel_clicked");
1529 lua_pushnumber(L, preview_num);
1531 if (lua_pcall(L, 1, 0, 0) != 0) {
1532 fprintf(stderr, "error running function `channel_clicked': %s\n", lua_tostring(L, -1));
1535 assert(lua_gettop(L) == 0);
1538 int Theme::set_theme_menu(lua_State *L)
1540 for (const Theme::MenuEntry &entry : theme_menu) {
1541 luaL_unref(L, LUA_REGISTRYINDEX, entry.lua_ref);
1545 int num_elements = lua_gettop(L);
1546 for (int i = 1; i <= num_elements; ++i) {
1547 lua_rawgeti(L, i, 1);
1548 const string text = checkstdstring(L, -1);
1551 lua_rawgeti(L, i, 2);
1552 luaL_checktype(L, -1, LUA_TFUNCTION);
1553 int ref = luaL_ref(L, LUA_REGISTRYINDEX);
1555 theme_menu.push_back(MenuEntry{ text, ref });
1557 lua_pop(L, num_elements);
1558 assert(lua_gettop(L) == 0);
1560 if (theme_menu_callback != nullptr) {
1561 theme_menu_callback();
1567 void Theme::theme_menu_entry_clicked(int lua_ref)
1569 lock_guard<mutex> lock(m);
1570 lua_rawgeti(L, LUA_REGISTRYINDEX, lua_ref);
1571 if (lua_pcall(L, 0, 0, 0) != 0) {
1572 fprintf(stderr, "error running menu callback: %s\n", lua_tostring(L, -1));