6 #include <movit/effect.h>
7 #include <movit/effect_chain.h>
8 #include <movit/image_format.h>
9 #include <movit/mix_effect.h>
10 #include <movit/overlay_effect.h>
11 #include <movit/padding_effect.h>
12 #include <movit/resample_effect.h>
13 #include <movit/resize_effect.h>
14 #include <movit/multiply_effect.h>
15 #include <movit/util.h>
16 #include <movit/white_balance_effect.h>
17 #include <movit/ycbcr.h>
18 #include <movit/ycbcr_input.h>
28 #include "image_input.h"
36 using namespace movit;
38 extern Mixer *global_mixer;
42 // Contains basically the same data as InputState, but does not hold on to
43 // a reference to the frames. This is important so that we can release them
44 // without having to wait for Lua's GC.
45 struct InputStateInfo {
46 InputStateInfo(const InputState& input_state);
48 unsigned last_width[MAX_CARDS], last_height[MAX_CARDS];
49 bool last_interlaced[MAX_CARDS], last_has_signal[MAX_CARDS], last_is_connected[MAX_CARDS];
50 unsigned last_frame_rate_nom[MAX_CARDS], last_frame_rate_den[MAX_CARDS];
53 InputStateInfo::InputStateInfo(const InputState &input_state)
55 for (unsigned signal_num = 0; signal_num < MAX_CARDS; ++signal_num) {
56 BufferedFrame frame = input_state.buffered_frames[signal_num][0];
57 if (frame.frame == nullptr) {
58 last_width[signal_num] = last_height[signal_num] = 0;
59 last_interlaced[signal_num] = false;
60 last_has_signal[signal_num] = false;
61 last_is_connected[signal_num] = false;
64 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
65 last_width[signal_num] = userdata->last_width[frame.field_number];
66 last_height[signal_num] = userdata->last_height[frame.field_number];
67 last_interlaced[signal_num] = userdata->last_interlaced;
68 last_has_signal[signal_num] = userdata->last_has_signal;
69 last_is_connected[signal_num] = userdata->last_is_connected;
70 last_frame_rate_nom[signal_num] = userdata->last_frame_rate_nom;
71 last_frame_rate_den[signal_num] = userdata->last_frame_rate_den;
75 class LuaRefWithDeleter {
77 LuaRefWithDeleter(mutex *m, lua_State *L, int ref) : m(m), L(L), ref(ref) {}
78 ~LuaRefWithDeleter() {
79 unique_lock<mutex> lock(*m);
80 luaL_unref(L, LUA_REGISTRYINDEX, ref);
82 int get() const { return ref; }
85 LuaRefWithDeleter(const LuaRefWithDeleter &) = delete;
92 template<class T, class... Args>
93 int wrap_lua_object(lua_State* L, const char *class_name, Args&&... args)
95 // Construct the C++ object and put it on the stack.
96 void *mem = lua_newuserdata(L, sizeof(T));
97 new(mem) T(forward<Args>(args)...);
99 // Look up the metatable named <class_name>, and set it on the new object.
100 luaL_getmetatable(L, class_name);
101 lua_setmetatable(L, -2);
106 // Like wrap_lua_object, but the object is not owned by Lua; ie. it's not freed
107 // by Lua GC. This is typically the case for Effects, which are owned by EffectChain
108 // and expected to be destructed by it. The object will be of type T** instead of T*
109 // when exposed to Lua.
111 // Note that we currently leak if you allocate an Effect in this way and never call
112 // add_effect. We should see if there's a way to e.g. set __gc on it at construction time
113 // and then release that once add_effect() takes ownership.
114 template<class T, class... Args>
115 int wrap_lua_object_nonowned(lua_State* L, const char *class_name, Args&&... args)
117 // Construct the pointer ot the C++ object and put it on the stack.
118 T **obj = (T **)lua_newuserdata(L, sizeof(T *));
119 *obj = new T(forward<Args>(args)...);
121 // Look up the metatable named <class_name>, and set it on the new object.
122 luaL_getmetatable(L, class_name);
123 lua_setmetatable(L, -2);
128 Theme *get_theme_updata(lua_State* L)
130 luaL_checktype(L, lua_upvalueindex(1), LUA_TLIGHTUSERDATA);
131 return (Theme *)lua_touserdata(L, lua_upvalueindex(1));
134 Effect *get_effect(lua_State *L, int idx)
136 if (luaL_testudata(L, idx, "WhiteBalanceEffect") ||
137 luaL_testudata(L, idx, "ResampleEffect") ||
138 luaL_testudata(L, idx, "PaddingEffect") ||
139 luaL_testudata(L, idx, "IntegralPaddingEffect") ||
140 luaL_testudata(L, idx, "OverlayEffect") ||
141 luaL_testudata(L, idx, "ResizeEffect") ||
142 luaL_testudata(L, idx, "MultiplyEffect") ||
143 luaL_testudata(L, idx, "MixEffect") ||
144 luaL_testudata(L, idx, "ImageInput")) {
145 return *(Effect **)lua_touserdata(L, idx);
147 luaL_error(L, "Error: Index #%d was not an Effect type\n", idx);
151 InputStateInfo *get_input_state_info(lua_State *L, int idx)
153 if (luaL_testudata(L, idx, "InputStateInfo")) {
154 return (InputStateInfo *)lua_touserdata(L, idx);
156 luaL_error(L, "Error: Index #%d was not InputStateInfo\n", idx);
160 bool checkbool(lua_State* L, int idx)
162 luaL_checktype(L, idx, LUA_TBOOLEAN);
163 return lua_toboolean(L, idx);
166 string checkstdstring(lua_State *L, int index)
169 const char* cstr = lua_tolstring(L, index, &len);
170 return string(cstr, len);
173 int EffectChain_new(lua_State* L)
175 assert(lua_gettop(L) == 2);
176 Theme *theme = get_theme_updata(L);
177 int aspect_w = luaL_checknumber(L, 1);
178 int aspect_h = luaL_checknumber(L, 2);
180 return wrap_lua_object<EffectChain>(L, "EffectChain", aspect_w, aspect_h, theme->get_resource_pool());
183 int EffectChain_gc(lua_State* L)
185 assert(lua_gettop(L) == 1);
186 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
187 chain->~EffectChain();
191 int EffectChain_add_live_input(lua_State* L)
193 assert(lua_gettop(L) == 3);
194 Theme *theme = get_theme_updata(L);
195 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
196 bool override_bounce = checkbool(L, 2);
197 bool deinterlace = checkbool(L, 3);
198 return wrap_lua_object<LiveInputWrapper>(L, "LiveInputWrapper", theme, chain, override_bounce, deinterlace);
201 int EffectChain_add_effect(lua_State* L)
203 assert(lua_gettop(L) >= 2);
204 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
206 // TODO: Better error reporting.
207 Effect *effect = get_effect(L, 2);
208 if (lua_gettop(L) == 2) {
209 if (effect->num_inputs() == 0) {
210 chain->add_input((Input *)effect);
212 chain->add_effect(effect);
215 vector<Effect *> inputs;
216 for (int idx = 3; idx <= lua_gettop(L); ++idx) {
217 if (luaL_testudata(L, idx, "LiveInputWrapper")) {
218 LiveInputWrapper *input = (LiveInputWrapper *)lua_touserdata(L, idx);
219 inputs.push_back(input->get_effect());
221 inputs.push_back(get_effect(L, idx));
224 chain->add_effect(effect, inputs);
227 lua_settop(L, 2); // Return the effect itself.
229 // Make sure Lua doesn't garbage-collect it away.
230 lua_pushvalue(L, -1);
231 luaL_ref(L, LUA_REGISTRYINDEX); // TODO: leak?
236 int EffectChain_finalize(lua_State* L)
238 assert(lua_gettop(L) == 2);
239 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
240 bool is_main_chain = checkbool(L, 2);
242 // Add outputs as needed.
243 // NOTE: If you change any details about the output format, you will need to
244 // also update what's given to the muxer (HTTPD::Mux constructor) and
245 // what's put in the H.264 stream (sps_rbsp()).
246 ImageFormat inout_format;
247 inout_format.color_space = COLORSPACE_REC_709;
249 // Output gamma is tricky. We should output Rec. 709 for TV, except that
250 // we expect to run with web players and others that don't really care and
251 // just output with no conversion. So that means we'll need to output sRGB,
252 // even though H.264 has no setting for that (we use “unspecified”).
253 inout_format.gamma_curve = GAMMA_sRGB;
256 YCbCrFormat output_ycbcr_format;
257 // We actually output 4:2:0 in the end, but chroma subsampling
258 // happens in a pass not run by Movit (see Mixer::subsample_chroma()).
259 output_ycbcr_format.chroma_subsampling_x = 1;
260 output_ycbcr_format.chroma_subsampling_y = 1;
262 // Rec. 709 would be the sane thing to do, but it seems many players
263 // (e.g. MPlayer and VLC) just default to BT.601 coefficients no matter
264 // what (see discussions in e.g. https://trac.ffmpeg.org/ticket/4978).
265 // We _do_ set the right flags, though, so that a player that works
266 // properly doesn't have to guess.
267 output_ycbcr_format.luma_coefficients = YCBCR_REC_601;
268 output_ycbcr_format.full_range = false;
269 output_ycbcr_format.num_levels = 256;
271 chain->add_ycbcr_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED, output_ycbcr_format, YCBCR_OUTPUT_SPLIT_Y_AND_CBCR);
272 chain->set_dither_bits(8);
273 chain->set_output_origin(OUTPUT_ORIGIN_TOP_LEFT);
275 chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
281 int LiveInputWrapper_connect_signal(lua_State* L)
283 assert(lua_gettop(L) == 2);
284 LiveInputWrapper *input = (LiveInputWrapper *)luaL_checkudata(L, 1, "LiveInputWrapper");
285 int signal_num = luaL_checknumber(L, 2);
286 input->connect_signal(signal_num);
290 int ImageInput_new(lua_State* L)
292 assert(lua_gettop(L) == 1);
293 string filename = checkstdstring(L, 1);
294 return wrap_lua_object_nonowned<ImageInput>(L, "ImageInput", filename);
297 int WhiteBalanceEffect_new(lua_State* L)
299 assert(lua_gettop(L) == 0);
300 return wrap_lua_object_nonowned<WhiteBalanceEffect>(L, "WhiteBalanceEffect");
303 int ResampleEffect_new(lua_State* L)
305 assert(lua_gettop(L) == 0);
306 return wrap_lua_object_nonowned<ResampleEffect>(L, "ResampleEffect");
309 int PaddingEffect_new(lua_State* L)
311 assert(lua_gettop(L) == 0);
312 return wrap_lua_object_nonowned<PaddingEffect>(L, "PaddingEffect");
315 int IntegralPaddingEffect_new(lua_State* L)
317 assert(lua_gettop(L) == 0);
318 return wrap_lua_object_nonowned<IntegralPaddingEffect>(L, "IntegralPaddingEffect");
321 int OverlayEffect_new(lua_State* L)
323 assert(lua_gettop(L) == 0);
324 return wrap_lua_object_nonowned<OverlayEffect>(L, "OverlayEffect");
327 int ResizeEffect_new(lua_State* L)
329 assert(lua_gettop(L) == 0);
330 return wrap_lua_object_nonowned<ResizeEffect>(L, "ResizeEffect");
333 int MultiplyEffect_new(lua_State* L)
335 assert(lua_gettop(L) == 0);
336 return wrap_lua_object_nonowned<MultiplyEffect>(L, "MultiplyEffect");
339 int MixEffect_new(lua_State* L)
341 assert(lua_gettop(L) == 0);
342 return wrap_lua_object_nonowned<MixEffect>(L, "MixEffect");
345 int InputStateInfo_get_width(lua_State* L)
347 assert(lua_gettop(L) == 2);
348 InputStateInfo *input_state_info = get_input_state_info(L, 1);
349 Theme *theme = get_theme_updata(L);
350 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
351 lua_pushnumber(L, input_state_info->last_width[signal_num]);
355 int InputStateInfo_get_height(lua_State* L)
357 assert(lua_gettop(L) == 2);
358 InputStateInfo *input_state_info = get_input_state_info(L, 1);
359 Theme *theme = get_theme_updata(L);
360 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
361 lua_pushnumber(L, input_state_info->last_height[signal_num]);
365 int InputStateInfo_get_interlaced(lua_State* L)
367 assert(lua_gettop(L) == 2);
368 InputStateInfo *input_state_info = get_input_state_info(L, 1);
369 Theme *theme = get_theme_updata(L);
370 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
371 lua_pushboolean(L, input_state_info->last_interlaced[signal_num]);
375 int InputStateInfo_get_has_signal(lua_State* L)
377 assert(lua_gettop(L) == 2);
378 InputStateInfo *input_state_info = get_input_state_info(L, 1);
379 Theme *theme = get_theme_updata(L);
380 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
381 lua_pushboolean(L, input_state_info->last_has_signal[signal_num]);
385 int InputStateInfo_get_is_connected(lua_State* L)
387 assert(lua_gettop(L) == 2);
388 InputStateInfo *input_state_info = get_input_state_info(L, 1);
389 Theme *theme = get_theme_updata(L);
390 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
391 lua_pushboolean(L, input_state_info->last_is_connected[signal_num]);
395 int InputStateInfo_get_frame_rate_nom(lua_State* L)
397 assert(lua_gettop(L) == 2);
398 InputStateInfo *input_state_info = get_input_state_info(L, 1);
399 Theme *theme = get_theme_updata(L);
400 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
401 lua_pushnumber(L, input_state_info->last_frame_rate_nom[signal_num]);
405 int InputStateInfo_get_frame_rate_den(lua_State* L)
407 assert(lua_gettop(L) == 2);
408 InputStateInfo *input_state_info = get_input_state_info(L, 1);
409 Theme *theme = get_theme_updata(L);
410 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
411 lua_pushnumber(L, input_state_info->last_frame_rate_den[signal_num]);
415 int Effect_set_float(lua_State *L)
417 assert(lua_gettop(L) == 3);
418 Effect *effect = (Effect *)get_effect(L, 1);
419 string key = checkstdstring(L, 2);
420 float value = luaL_checknumber(L, 3);
421 if (!effect->set_float(key, value)) {
422 luaL_error(L, "Effect refused set_float(\"%s\", %d) (invalid key?)", key.c_str(), int(value));
427 int Effect_set_int(lua_State *L)
429 assert(lua_gettop(L) == 3);
430 Effect *effect = (Effect *)get_effect(L, 1);
431 string key = checkstdstring(L, 2);
432 float value = luaL_checknumber(L, 3);
433 if (!effect->set_int(key, value)) {
434 luaL_error(L, "Effect refused set_int(\"%s\", %d) (invalid key?)", key.c_str(), int(value));
439 int Effect_set_vec3(lua_State *L)
441 assert(lua_gettop(L) == 5);
442 Effect *effect = (Effect *)get_effect(L, 1);
443 string key = checkstdstring(L, 2);
445 v[0] = luaL_checknumber(L, 3);
446 v[1] = luaL_checknumber(L, 4);
447 v[2] = luaL_checknumber(L, 5);
448 if (!effect->set_vec3(key, v)) {
449 luaL_error(L, "Effect refused set_vec3(\"%s\", %f, %f, %f) (invalid key?)", key.c_str(),
455 int Effect_set_vec4(lua_State *L)
457 assert(lua_gettop(L) == 6);
458 Effect *effect = (Effect *)get_effect(L, 1);
459 string key = checkstdstring(L, 2);
461 v[0] = luaL_checknumber(L, 3);
462 v[1] = luaL_checknumber(L, 4);
463 v[2] = luaL_checknumber(L, 5);
464 v[3] = luaL_checknumber(L, 6);
465 if (!effect->set_vec4(key, v)) {
466 luaL_error(L, "Effect refused set_vec4(\"%s\", %f, %f, %f, %f) (invalid key?)", key.c_str(),
467 v[0], v[1], v[2], v[3]);
472 const luaL_Reg EffectChain_funcs[] = {
473 { "new", EffectChain_new },
474 { "__gc", EffectChain_gc },
475 { "add_live_input", EffectChain_add_live_input },
476 { "add_effect", EffectChain_add_effect },
477 { "finalize", EffectChain_finalize },
481 const luaL_Reg LiveInputWrapper_funcs[] = {
482 { "connect_signal", LiveInputWrapper_connect_signal },
486 const luaL_Reg ImageInput_funcs[] = {
487 { "new", ImageInput_new },
488 { "set_float", Effect_set_float },
489 { "set_int", Effect_set_int },
490 { "set_vec3", Effect_set_vec3 },
491 { "set_vec4", Effect_set_vec4 },
495 const luaL_Reg WhiteBalanceEffect_funcs[] = {
496 { "new", WhiteBalanceEffect_new },
497 { "set_float", Effect_set_float },
498 { "set_int", Effect_set_int },
499 { "set_vec3", Effect_set_vec3 },
500 { "set_vec4", Effect_set_vec4 },
504 const luaL_Reg ResampleEffect_funcs[] = {
505 { "new", ResampleEffect_new },
506 { "set_float", Effect_set_float },
507 { "set_int", Effect_set_int },
508 { "set_vec3", Effect_set_vec3 },
509 { "set_vec4", Effect_set_vec4 },
513 const luaL_Reg PaddingEffect_funcs[] = {
514 { "new", PaddingEffect_new },
515 { "set_float", Effect_set_float },
516 { "set_int", Effect_set_int },
517 { "set_vec3", Effect_set_vec3 },
518 { "set_vec4", Effect_set_vec4 },
522 const luaL_Reg IntegralPaddingEffect_funcs[] = {
523 { "new", IntegralPaddingEffect_new },
524 { "set_float", Effect_set_float },
525 { "set_int", Effect_set_int },
526 { "set_vec3", Effect_set_vec3 },
527 { "set_vec4", Effect_set_vec4 },
531 const luaL_Reg OverlayEffect_funcs[] = {
532 { "new", OverlayEffect_new },
533 { "set_float", Effect_set_float },
534 { "set_int", Effect_set_int },
535 { "set_vec3", Effect_set_vec3 },
536 { "set_vec4", Effect_set_vec4 },
540 const luaL_Reg ResizeEffect_funcs[] = {
541 { "new", ResizeEffect_new },
542 { "set_float", Effect_set_float },
543 { "set_int", Effect_set_int },
544 { "set_vec3", Effect_set_vec3 },
545 { "set_vec4", Effect_set_vec4 },
549 const luaL_Reg MultiplyEffect_funcs[] = {
550 { "new", MultiplyEffect_new },
551 { "set_float", Effect_set_float },
552 { "set_int", Effect_set_int },
553 { "set_vec3", Effect_set_vec3 },
554 { "set_vec4", Effect_set_vec4 },
558 const luaL_Reg MixEffect_funcs[] = {
559 { "new", MixEffect_new },
560 { "set_float", Effect_set_float },
561 { "set_int", Effect_set_int },
562 { "set_vec3", Effect_set_vec3 },
563 { "set_vec4", Effect_set_vec4 },
567 const luaL_Reg InputStateInfo_funcs[] = {
568 { "get_width", InputStateInfo_get_width },
569 { "get_height", InputStateInfo_get_height },
570 { "get_interlaced", InputStateInfo_get_interlaced },
571 { "get_has_signal", InputStateInfo_get_has_signal },
572 { "get_is_connected", InputStateInfo_get_is_connected },
573 { "get_frame_rate_nom", InputStateInfo_get_frame_rate_nom },
574 { "get_frame_rate_den", InputStateInfo_get_frame_rate_den },
580 LiveInputWrapper::LiveInputWrapper(Theme *theme, EffectChain *chain, bool override_bounce, bool deinterlace)
582 deinterlace(deinterlace)
584 ImageFormat inout_format;
585 inout_format.color_space = COLORSPACE_sRGB;
587 // Gamma curve depends on the input signal, and we don't really get any
588 // indications. A camera would be expected to do Rec. 709, but
589 // I haven't checked if any do in practice. However, computers _do_ output
590 // in sRGB gamma (ie., they don't convert from sRGB to Rec. 709), and
591 // I wouldn't really be surprised if most non-professional cameras do, too.
592 // So we pick sRGB as the least evil here.
593 inout_format.gamma_curve = GAMMA_sRGB;
595 // The Blackmagic driver docs claim that the device outputs Y'CbCr
596 // according to Rec. 601, but practical testing indicates it definitely
597 // is Rec. 709 (at least up to errors attributable to rounding errors).
598 // Perhaps 601 was only to indicate the subsampling positions, not the
599 // colorspace itself? Tested with a Lenovo X1 gen 3 as input.
600 YCbCrFormat input_ycbcr_format;
601 input_ycbcr_format.chroma_subsampling_x = 2;
602 input_ycbcr_format.chroma_subsampling_y = 1;
603 input_ycbcr_format.cb_x_position = 0.0;
604 input_ycbcr_format.cr_x_position = 0.0;
605 input_ycbcr_format.cb_y_position = 0.5;
606 input_ycbcr_format.cr_y_position = 0.5;
607 input_ycbcr_format.luma_coefficients = YCBCR_REC_709;
608 input_ycbcr_format.full_range = false;
612 deinterlace_effect = new movit::DeinterlaceEffect();
614 // As per the comments in deinterlace_effect.h, we turn this off.
615 // The most likely interlaced input for us is either a camera
616 // (where it's fine to turn it off) or a laptop (where it _should_
618 CHECK(deinterlace_effect->set_int("enable_spatial_interlacing_check", 0));
620 num_inputs = deinterlace_effect->num_inputs();
621 assert(num_inputs == FRAME_HISTORY_LENGTH);
625 for (unsigned i = 0; i < num_inputs; ++i) {
626 if (override_bounce) {
627 inputs.push_back(new NonBouncingYCbCrInput(inout_format, input_ycbcr_format, WIDTH, HEIGHT, YCBCR_INPUT_SPLIT_Y_AND_CBCR));
629 inputs.push_back(new YCbCrInput(inout_format, input_ycbcr_format, WIDTH, HEIGHT, YCBCR_INPUT_SPLIT_Y_AND_CBCR));
631 chain->add_input(inputs.back());
635 vector<Effect *> reverse_inputs(inputs.rbegin(), inputs.rend());
636 chain->add_effect(deinterlace_effect, reverse_inputs);
640 void LiveInputWrapper::connect_signal(int signal_num)
642 if (global_mixer == nullptr) {
647 signal_num = theme->map_signal(signal_num);
649 BufferedFrame first_frame = theme->input_state->buffered_frames[signal_num][0];
650 if (first_frame.frame == nullptr) {
654 unsigned width, height;
656 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)first_frame.frame->userdata;
657 width = userdata->last_width[first_frame.field_number];
658 height = userdata->last_height[first_frame.field_number];
661 BufferedFrame last_good_frame = first_frame;
662 for (unsigned i = 0; i < inputs.size(); ++i) {
663 BufferedFrame frame = theme->input_state->buffered_frames[signal_num][i];
664 if (frame.frame == nullptr) {
665 // Not enough data; reuse last frame (well, field).
666 // This is suboptimal, but we have nothing better.
667 frame = last_good_frame;
669 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
671 if (userdata->last_width[frame.field_number] != width ||
672 userdata->last_height[frame.field_number] != height) {
673 // Resolution changed; reuse last frame/field.
674 frame = last_good_frame;
675 userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
678 inputs[i]->set_texture_num(0, userdata->tex_y[frame.field_number]);
679 inputs[i]->set_texture_num(1, userdata->tex_cbcr[frame.field_number]);
680 inputs[i]->set_width(userdata->last_width[frame.field_number]);
681 inputs[i]->set_height(userdata->last_height[frame.field_number]);
683 last_good_frame = frame;
687 BufferedFrame frame = theme->input_state->buffered_frames[signal_num][0];
688 CHECK(deinterlace_effect->set_int("current_field_position", frame.field_number));
694 int call_num_channels(lua_State *L)
696 lua_getglobal(L, "num_channels");
698 if (lua_pcall(L, 0, 1, 0) != 0) {
699 fprintf(stderr, "error running function `num_channels': %s\n", lua_tostring(L, -1));
703 int num_channels = luaL_checknumber(L, 1);
705 assert(lua_gettop(L) == 0);
711 Theme::Theme(const string &filename, const vector<string> &search_dirs, ResourcePool *resource_pool, unsigned num_cards)
712 : resource_pool(resource_pool), num_cards(num_cards), signal_to_card_mapping(global_flags.default_stream_mapping)
717 register_class("EffectChain", EffectChain_funcs);
718 register_class("LiveInputWrapper", LiveInputWrapper_funcs);
719 register_class("ImageInput", ImageInput_funcs);
720 register_class("WhiteBalanceEffect", WhiteBalanceEffect_funcs);
721 register_class("ResampleEffect", ResampleEffect_funcs);
722 register_class("PaddingEffect", PaddingEffect_funcs);
723 register_class("IntegralPaddingEffect", IntegralPaddingEffect_funcs);
724 register_class("OverlayEffect", OverlayEffect_funcs);
725 register_class("ResizeEffect", ResizeEffect_funcs);
726 register_class("MultiplyEffect", MultiplyEffect_funcs);
727 register_class("MixEffect", MixEffect_funcs);
728 register_class("InputStateInfo", InputStateInfo_funcs);
730 // Run script. Search through all directories until we find a file that will load
731 // (as in, does not return LUA_ERRFILE); then run it. We store load errors
732 // from all the attempts, and show them once we know we can't find any of them.
734 vector<string> errors;
735 bool success = false;
736 for (size_t i = 0; i < search_dirs.size(); ++i) {
737 string path = search_dirs[i] + "/" + filename;
738 int err = luaL_loadfile(L, path.c_str());
740 // Success; actually call the code.
741 if (lua_pcall(L, 0, LUA_MULTRET, 0)) {
742 fprintf(stderr, "Error when running %s: %s\n", path.c_str(), lua_tostring(L, -1));
748 errors.push_back(lua_tostring(L, -1));
750 if (err != LUA_ERRFILE) {
751 // The file actually loaded, but failed to parse somehow. Abort; don't try the next one.
757 for (const string &error : errors) {
758 fprintf(stderr, "%s\n", error.c_str());
762 assert(lua_gettop(L) == 0);
764 // Ask it for the number of channels.
765 num_channels = call_num_channels(L);
773 void Theme::register_class(const char *class_name, const luaL_Reg *funcs)
775 assert(lua_gettop(L) == 0);
776 luaL_newmetatable(L, class_name); // mt = {}
777 lua_pushlightuserdata(L, this);
778 luaL_setfuncs(L, funcs, 1); // for (name,f in funcs) { mt[name] = f, with upvalue {theme} }
779 lua_pushvalue(L, -1);
780 lua_setfield(L, -2, "__index"); // mt.__index = mt
781 lua_setglobal(L, class_name); // ClassName = mt
782 assert(lua_gettop(L) == 0);
785 Theme::Chain Theme::get_chain(unsigned num, float t, unsigned width, unsigned height, InputState input_state)
789 unique_lock<mutex> lock(m);
790 assert(lua_gettop(L) == 0);
791 lua_getglobal(L, "get_chain"); /* function to be called */
792 lua_pushnumber(L, num);
793 lua_pushnumber(L, t);
794 lua_pushnumber(L, width);
795 lua_pushnumber(L, height);
796 wrap_lua_object<InputStateInfo>(L, "InputStateInfo", input_state);
798 if (lua_pcall(L, 5, 2, 0) != 0) {
799 fprintf(stderr, "error running function `get_chain': %s\n", lua_tostring(L, -1));
803 chain.chain = (EffectChain *)luaL_testudata(L, -2, "EffectChain");
804 if (chain.chain == nullptr) {
805 fprintf(stderr, "get_chain() for chain number %d did not return an EffectChain\n",
809 if (!lua_isfunction(L, -1)) {
810 fprintf(stderr, "Argument #-1 should be a function\n");
813 lua_pushvalue(L, -1);
814 shared_ptr<LuaRefWithDeleter> funcref(new LuaRefWithDeleter(&m, L, luaL_ref(L, LUA_REGISTRYINDEX)));
816 assert(lua_gettop(L) == 0);
818 chain.setup_chain = [this, funcref, input_state]{
819 unique_lock<mutex> lock(m);
821 this->input_state = &input_state;
823 // Set up state, including connecting signals.
824 lua_rawgeti(L, LUA_REGISTRYINDEX, funcref->get());
825 if (lua_pcall(L, 0, 0, 0) != 0) {
826 fprintf(stderr, "error running chain setup callback: %s\n", lua_tostring(L, -1));
829 assert(lua_gettop(L) == 0);
832 // TODO: Can we do better, e.g. by running setup_chain() and seeing what it references?
833 // Actually, setup_chain does maybe hold all the references we need now anyway?
834 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
835 for (unsigned frame_num = 0; frame_num < FRAME_HISTORY_LENGTH; ++frame_num) {
836 chain.input_frames.push_back(input_state.buffered_frames[card_index][frame_num].frame);
843 string Theme::get_channel_name(unsigned channel)
845 unique_lock<mutex> lock(m);
846 lua_getglobal(L, "channel_name");
847 lua_pushnumber(L, channel);
848 if (lua_pcall(L, 1, 1, 0) != 0) {
849 fprintf(stderr, "error running function `channel_name': %s\n", lua_tostring(L, -1));
852 const char *ret = lua_tostring(L, -1);
853 if (ret == nullptr) {
854 fprintf(stderr, "function `channel_name' returned nil for channel %d\n", channel);
860 assert(lua_gettop(L) == 0);
864 int Theme::get_channel_signal(unsigned channel)
866 unique_lock<mutex> lock(m);
867 lua_getglobal(L, "channel_signal");
868 lua_pushnumber(L, channel);
869 if (lua_pcall(L, 1, 1, 0) != 0) {
870 fprintf(stderr, "error running function `channel_signal': %s\n", lua_tostring(L, -1));
874 int ret = luaL_checknumber(L, 1);
876 assert(lua_gettop(L) == 0);
880 std::string Theme::get_channel_color(unsigned channel)
882 unique_lock<mutex> lock(m);
883 lua_getglobal(L, "channel_color");
884 lua_pushnumber(L, channel);
885 if (lua_pcall(L, 1, 1, 0) != 0) {
886 fprintf(stderr, "error running function `channel_color': %s\n", lua_tostring(L, -1));
890 const char *ret = lua_tostring(L, -1);
891 if (ret == nullptr) {
892 fprintf(stderr, "function `channel_color' returned nil for channel %d\n", channel);
898 assert(lua_gettop(L) == 0);
902 bool Theme::get_supports_set_wb(unsigned channel)
904 unique_lock<mutex> lock(m);
905 lua_getglobal(L, "supports_set_wb");
906 lua_pushnumber(L, channel);
907 if (lua_pcall(L, 1, 1, 0) != 0) {
908 fprintf(stderr, "error running function `supports_set_wb': %s\n", lua_tostring(L, -1));
912 bool ret = checkbool(L, -1);
914 assert(lua_gettop(L) == 0);
918 void Theme::set_wb(unsigned channel, double r, double g, double b)
920 unique_lock<mutex> lock(m);
921 lua_getglobal(L, "set_wb");
922 lua_pushnumber(L, channel);
923 lua_pushnumber(L, r);
924 lua_pushnumber(L, g);
925 lua_pushnumber(L, b);
926 if (lua_pcall(L, 4, 0, 0) != 0) {
927 fprintf(stderr, "error running function `set_wb': %s\n", lua_tostring(L, -1));
931 assert(lua_gettop(L) == 0);
934 vector<string> Theme::get_transition_names(float t)
936 unique_lock<mutex> lock(m);
937 lua_getglobal(L, "get_transitions");
938 lua_pushnumber(L, t);
939 if (lua_pcall(L, 1, 1, 0) != 0) {
940 fprintf(stderr, "error running function `get_transitions': %s\n", lua_tostring(L, -1));
946 while (lua_next(L, -2) != 0) {
947 ret.push_back(lua_tostring(L, -1));
951 assert(lua_gettop(L) == 0);
955 int Theme::map_signal(int signal_num)
957 unique_lock<mutex> lock(map_m);
958 if (signal_to_card_mapping.count(signal_num)) {
959 return signal_to_card_mapping[signal_num];
961 if (signal_num >= int(num_cards)) {
962 fprintf(stderr, "WARNING: Theme asked for input %d, but we only have %u card(s).\n", signal_num, num_cards);
963 fprintf(stderr, "Mapping to card %d instead.\n", signal_num % num_cards);
965 signal_to_card_mapping[signal_num] = signal_num % num_cards;
966 return signal_num % num_cards;
969 void Theme::set_signal_mapping(int signal_num, int card_num)
971 unique_lock<mutex> lock(map_m);
972 assert(card_num < int(num_cards));
973 signal_to_card_mapping[signal_num] = card_num;
976 void Theme::transition_clicked(int transition_num, float t)
978 unique_lock<mutex> lock(m);
979 lua_getglobal(L, "transition_clicked");
980 lua_pushnumber(L, transition_num);
981 lua_pushnumber(L, t);
983 if (lua_pcall(L, 2, 0, 0) != 0) {
984 fprintf(stderr, "error running function `transition_clicked': %s\n", lua_tostring(L, -1));
987 assert(lua_gettop(L) == 0);
990 void Theme::channel_clicked(int preview_num)
992 unique_lock<mutex> lock(m);
993 lua_getglobal(L, "channel_clicked");
994 lua_pushnumber(L, preview_num);
996 if (lua_pcall(L, 1, 0, 0) != 0) {
997 fprintf(stderr, "error running function `channel_clicked': %s\n", lua_tostring(L, -1));
1000 assert(lua_gettop(L) == 0);