4 #include <bmusb/bmusb.h>
8 #include <movit/effect.h>
9 #include <movit/effect_chain.h>
10 #include <movit/image_format.h>
11 #include <movit/mix_effect.h>
12 #include <movit/multiply_effect.h>
13 #include <movit/overlay_effect.h>
14 #include <movit/padding_effect.h>
15 #include <movit/resample_effect.h>
16 #include <movit/resize_effect.h>
17 #include <movit/util.h>
18 #include <movit/white_balance_effect.h>
19 #include <movit/ycbcr.h>
20 #include <movit/ycbcr_input.h>
29 #include "deinterlace_effect.h"
30 #include "ffmpeg_capture.h"
32 #include "image_input.h"
34 #include "input_state.h"
35 #include "pbo_frame_allocator.h"
44 using namespace movit;
46 extern Mixer *global_mixer;
50 // Contains basically the same data as InputState, but does not hold on to
51 // a reference to the frames. This is important so that we can release them
52 // without having to wait for Lua's GC.
53 struct InputStateInfo {
54 InputStateInfo(const InputState& input_state);
56 unsigned last_width[MAX_VIDEO_CARDS], last_height[MAX_VIDEO_CARDS];
57 bool last_interlaced[MAX_VIDEO_CARDS], last_has_signal[MAX_VIDEO_CARDS], last_is_connected[MAX_VIDEO_CARDS];
58 unsigned last_frame_rate_nom[MAX_VIDEO_CARDS], last_frame_rate_den[MAX_VIDEO_CARDS];
61 InputStateInfo::InputStateInfo(const InputState &input_state)
63 for (unsigned signal_num = 0; signal_num < MAX_VIDEO_CARDS; ++signal_num) {
64 BufferedFrame frame = input_state.buffered_frames[signal_num][0];
65 if (frame.frame == nullptr) {
66 last_width[signal_num] = last_height[signal_num] = 0;
67 last_interlaced[signal_num] = false;
68 last_has_signal[signal_num] = false;
69 last_is_connected[signal_num] = false;
72 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
73 last_width[signal_num] = userdata->last_width[frame.field_number];
74 last_height[signal_num] = userdata->last_height[frame.field_number];
75 last_interlaced[signal_num] = userdata->last_interlaced;
76 last_has_signal[signal_num] = userdata->last_has_signal;
77 last_is_connected[signal_num] = userdata->last_is_connected;
78 last_frame_rate_nom[signal_num] = userdata->last_frame_rate_nom;
79 last_frame_rate_den[signal_num] = userdata->last_frame_rate_den;
83 class LuaRefWithDeleter {
85 LuaRefWithDeleter(mutex *m, lua_State *L, int ref) : m(m), L(L), ref(ref) {}
86 ~LuaRefWithDeleter() {
87 unique_lock<mutex> lock(*m);
88 luaL_unref(L, LUA_REGISTRYINDEX, ref);
90 int get() const { return ref; }
93 LuaRefWithDeleter(const LuaRefWithDeleter &) = delete;
100 template<class T, class... Args>
101 int wrap_lua_object(lua_State* L, const char *class_name, Args&&... args)
103 // Construct the C++ object and put it on the stack.
104 void *mem = lua_newuserdata(L, sizeof(T));
105 new(mem) T(forward<Args>(args)...);
107 // Look up the metatable named <class_name>, and set it on the new object.
108 luaL_getmetatable(L, class_name);
109 lua_setmetatable(L, -2);
114 // Like wrap_lua_object, but the object is not owned by Lua; ie. it's not freed
115 // by Lua GC. This is typically the case for Effects, which are owned by EffectChain
116 // and expected to be destructed by it. The object will be of type T** instead of T*
117 // when exposed to Lua.
119 // Note that we currently leak if you allocate an Effect in this way and never call
120 // add_effect. We should see if there's a way to e.g. set __gc on it at construction time
121 // and then release that once add_effect() takes ownership.
122 template<class T, class... Args>
123 int wrap_lua_object_nonowned(lua_State* L, const char *class_name, Args&&... args)
125 // Construct the pointer ot the C++ object and put it on the stack.
126 T **obj = (T **)lua_newuserdata(L, sizeof(T *));
127 *obj = new T(forward<Args>(args)...);
129 // Look up the metatable named <class_name>, and set it on the new object.
130 luaL_getmetatable(L, class_name);
131 lua_setmetatable(L, -2);
136 Theme *get_theme_updata(lua_State* L)
138 luaL_checktype(L, lua_upvalueindex(1), LUA_TLIGHTUSERDATA);
139 return (Theme *)lua_touserdata(L, lua_upvalueindex(1));
142 Effect *get_effect(lua_State *L, int idx)
144 if (luaL_testudata(L, idx, "WhiteBalanceEffect") ||
145 luaL_testudata(L, idx, "ResampleEffect") ||
146 luaL_testudata(L, idx, "PaddingEffect") ||
147 luaL_testudata(L, idx, "IntegralPaddingEffect") ||
148 luaL_testudata(L, idx, "OverlayEffect") ||
149 luaL_testudata(L, idx, "ResizeEffect") ||
150 luaL_testudata(L, idx, "MultiplyEffect") ||
151 luaL_testudata(L, idx, "MixEffect") ||
152 luaL_testudata(L, idx, "ImageInput")) {
153 return *(Effect **)lua_touserdata(L, idx);
155 luaL_error(L, "Error: Index #%d was not an Effect type\n", idx);
159 InputStateInfo *get_input_state_info(lua_State *L, int idx)
161 if (luaL_testudata(L, idx, "InputStateInfo")) {
162 return (InputStateInfo *)lua_touserdata(L, idx);
164 luaL_error(L, "Error: Index #%d was not InputStateInfo\n", idx);
168 bool checkbool(lua_State* L, int idx)
170 luaL_checktype(L, idx, LUA_TBOOLEAN);
171 return lua_toboolean(L, idx);
174 string checkstdstring(lua_State *L, int index)
177 const char* cstr = lua_tolstring(L, index, &len);
178 return string(cstr, len);
181 int EffectChain_new(lua_State* L)
183 assert(lua_gettop(L) == 2);
184 Theme *theme = get_theme_updata(L);
185 int aspect_w = luaL_checknumber(L, 1);
186 int aspect_h = luaL_checknumber(L, 2);
188 return wrap_lua_object<EffectChain>(L, "EffectChain", aspect_w, aspect_h, theme->get_resource_pool());
191 int EffectChain_gc(lua_State* L)
193 assert(lua_gettop(L) == 1);
194 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
195 chain->~EffectChain();
199 int EffectChain_add_live_input(lua_State* L)
201 assert(lua_gettop(L) == 3);
202 Theme *theme = get_theme_updata(L);
203 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
204 bool override_bounce = checkbool(L, 2);
205 bool deinterlace = checkbool(L, 3);
206 bmusb::PixelFormat pixel_format = global_flags.ten_bit_input ? bmusb::PixelFormat_10BitYCbCr : bmusb::PixelFormat_8BitYCbCr;
208 // Needs to be nonowned to match add_video_input (see below).
209 return wrap_lua_object_nonowned<LiveInputWrapper>(L, "LiveInputWrapper", theme, chain, pixel_format, override_bounce, deinterlace);
212 int EffectChain_add_video_input(lua_State* L)
214 assert(lua_gettop(L) == 3);
215 Theme *theme = get_theme_updata(L);
216 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
217 FFmpegCapture **capture = (FFmpegCapture **)luaL_checkudata(L, 2, "VideoInput");
218 bool deinterlace = checkbool(L, 3);
220 // These need to be nonowned, so that the LiveInputWrapper still exists
221 // and can feed frames to the right EffectChain even if the Lua code
222 // doesn't care about the object anymore. (If we change this, we'd need
223 // to also unregister the signal connection on __gc.)
224 int ret = wrap_lua_object_nonowned<LiveInputWrapper>(
225 L, "LiveInputWrapper", theme, chain, bmusb::PixelFormat_8BitRGBA,
226 /*override_bounce=*/false, deinterlace);
228 Theme *theme = get_theme_updata(L);
229 LiveInputWrapper **live_input = (LiveInputWrapper **)lua_touserdata(L, -1);
230 theme->register_signal_connection(*live_input, *capture);
235 int EffectChain_add_effect(lua_State* L)
237 assert(lua_gettop(L) >= 2);
238 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
240 // TODO: Better error reporting.
241 Effect *effect = get_effect(L, 2);
242 if (lua_gettop(L) == 2) {
243 if (effect->num_inputs() == 0) {
244 chain->add_input((Input *)effect);
246 chain->add_effect(effect);
249 vector<Effect *> inputs;
250 for (int idx = 3; idx <= lua_gettop(L); ++idx) {
251 if (luaL_testudata(L, idx, "LiveInputWrapper")) {
252 LiveInputWrapper **input = (LiveInputWrapper **)lua_touserdata(L, idx);
253 inputs.push_back((*input)->get_effect());
255 inputs.push_back(get_effect(L, idx));
258 chain->add_effect(effect, inputs);
261 lua_settop(L, 2); // Return the effect itself.
263 // Make sure Lua doesn't garbage-collect it away.
264 lua_pushvalue(L, -1);
265 luaL_ref(L, LUA_REGISTRYINDEX); // TODO: leak?
270 int EffectChain_finalize(lua_State* L)
272 assert(lua_gettop(L) == 2);
273 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
274 bool is_main_chain = checkbool(L, 2);
276 // Add outputs as needed.
277 // NOTE: If you change any details about the output format, you will need to
278 // also update what's given to the muxer (HTTPD::Mux constructor) and
279 // what's put in the H.264 stream (sps_rbsp()).
280 ImageFormat inout_format;
281 inout_format.color_space = COLORSPACE_REC_709;
283 // Output gamma is tricky. We should output Rec. 709 for TV, except that
284 // we expect to run with web players and others that don't really care and
285 // just output with no conversion. So that means we'll need to output sRGB,
286 // even though H.264 has no setting for that (we use “unspecified”).
287 inout_format.gamma_curve = GAMMA_sRGB;
290 YCbCrFormat output_ycbcr_format;
291 // We actually output 4:2:0 and/or 4:2:2 in the end, but chroma subsampling
292 // happens in a pass not run by Movit (see ChromaSubsampler::subsample_chroma()).
293 output_ycbcr_format.chroma_subsampling_x = 1;
294 output_ycbcr_format.chroma_subsampling_y = 1;
296 // This will be overridden if HDMI/SDI output is in force.
297 if (global_flags.ycbcr_rec709_coefficients) {
298 output_ycbcr_format.luma_coefficients = YCBCR_REC_709;
300 output_ycbcr_format.luma_coefficients = YCBCR_REC_601;
303 output_ycbcr_format.full_range = false;
304 output_ycbcr_format.num_levels = 1 << global_flags.x264_bit_depth;
306 GLenum type = global_flags.x264_bit_depth > 8 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_BYTE;
308 chain->add_ycbcr_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED, output_ycbcr_format, YCBCR_OUTPUT_SPLIT_Y_AND_CBCR, type);
310 // If we're using zerocopy video encoding (so the destination
311 // Y texture is owned by VA-API and will be unavailable for
312 // display), add a copy, where we'll only be using the Y component.
313 if (global_flags.use_zerocopy) {
314 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.
316 chain->set_dither_bits(global_flags.x264_bit_depth > 8 ? 16 : 8);
317 chain->set_output_origin(OUTPUT_ORIGIN_TOP_LEFT);
319 chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
326 int LiveInputWrapper_connect_signal(lua_State* L)
328 assert(lua_gettop(L) == 2);
329 LiveInputWrapper **input = (LiveInputWrapper **)luaL_checkudata(L, 1, "LiveInputWrapper");
330 int signal_num = luaL_checknumber(L, 2);
331 (*input)->connect_signal(signal_num);
335 int ImageInput_new(lua_State* L)
337 assert(lua_gettop(L) == 1);
338 string filename = checkstdstring(L, 1);
339 return wrap_lua_object_nonowned<ImageInput>(L, "ImageInput", filename);
342 int VideoInput_new(lua_State* L)
344 assert(lua_gettop(L) == 1);
345 string filename = checkstdstring(L, 1);
346 int ret = wrap_lua_object_nonowned<FFmpegCapture>(L, "VideoInput", filename, global_flags.width, global_flags.height);
348 Theme *theme = get_theme_updata(L);
349 FFmpegCapture **capture = (FFmpegCapture **)lua_touserdata(L, -1);
350 theme->register_video_input(*capture);
355 int VideoInput_rewind(lua_State* L)
357 assert(lua_gettop(L) == 1);
358 FFmpegCapture **video_input = (FFmpegCapture **)luaL_checkudata(L, 1, "VideoInput");
359 (*video_input)->rewind();
363 int WhiteBalanceEffect_new(lua_State* L)
365 assert(lua_gettop(L) == 0);
366 return wrap_lua_object_nonowned<WhiteBalanceEffect>(L, "WhiteBalanceEffect");
369 int ResampleEffect_new(lua_State* L)
371 assert(lua_gettop(L) == 0);
372 return wrap_lua_object_nonowned<ResampleEffect>(L, "ResampleEffect");
375 int PaddingEffect_new(lua_State* L)
377 assert(lua_gettop(L) == 0);
378 return wrap_lua_object_nonowned<PaddingEffect>(L, "PaddingEffect");
381 int IntegralPaddingEffect_new(lua_State* L)
383 assert(lua_gettop(L) == 0);
384 return wrap_lua_object_nonowned<IntegralPaddingEffect>(L, "IntegralPaddingEffect");
387 int OverlayEffect_new(lua_State* L)
389 assert(lua_gettop(L) == 0);
390 return wrap_lua_object_nonowned<OverlayEffect>(L, "OverlayEffect");
393 int ResizeEffect_new(lua_State* L)
395 assert(lua_gettop(L) == 0);
396 return wrap_lua_object_nonowned<ResizeEffect>(L, "ResizeEffect");
399 int MultiplyEffect_new(lua_State* L)
401 assert(lua_gettop(L) == 0);
402 return wrap_lua_object_nonowned<MultiplyEffect>(L, "MultiplyEffect");
405 int MixEffect_new(lua_State* L)
407 assert(lua_gettop(L) == 0);
408 return wrap_lua_object_nonowned<MixEffect>(L, "MixEffect");
411 int InputStateInfo_get_width(lua_State* L)
413 assert(lua_gettop(L) == 2);
414 InputStateInfo *input_state_info = get_input_state_info(L, 1);
415 Theme *theme = get_theme_updata(L);
416 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
417 lua_pushnumber(L, input_state_info->last_width[signal_num]);
421 int InputStateInfo_get_height(lua_State* L)
423 assert(lua_gettop(L) == 2);
424 InputStateInfo *input_state_info = get_input_state_info(L, 1);
425 Theme *theme = get_theme_updata(L);
426 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
427 lua_pushnumber(L, input_state_info->last_height[signal_num]);
431 int InputStateInfo_get_interlaced(lua_State* L)
433 assert(lua_gettop(L) == 2);
434 InputStateInfo *input_state_info = get_input_state_info(L, 1);
435 Theme *theme = get_theme_updata(L);
436 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
437 lua_pushboolean(L, input_state_info->last_interlaced[signal_num]);
441 int InputStateInfo_get_has_signal(lua_State* L)
443 assert(lua_gettop(L) == 2);
444 InputStateInfo *input_state_info = get_input_state_info(L, 1);
445 Theme *theme = get_theme_updata(L);
446 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
447 lua_pushboolean(L, input_state_info->last_has_signal[signal_num]);
451 int InputStateInfo_get_is_connected(lua_State* L)
453 assert(lua_gettop(L) == 2);
454 InputStateInfo *input_state_info = get_input_state_info(L, 1);
455 Theme *theme = get_theme_updata(L);
456 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
457 lua_pushboolean(L, input_state_info->last_is_connected[signal_num]);
461 int InputStateInfo_get_frame_rate_nom(lua_State* L)
463 assert(lua_gettop(L) == 2);
464 InputStateInfo *input_state_info = get_input_state_info(L, 1);
465 Theme *theme = get_theme_updata(L);
466 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
467 lua_pushnumber(L, input_state_info->last_frame_rate_nom[signal_num]);
471 int InputStateInfo_get_frame_rate_den(lua_State* L)
473 assert(lua_gettop(L) == 2);
474 InputStateInfo *input_state_info = get_input_state_info(L, 1);
475 Theme *theme = get_theme_updata(L);
476 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
477 lua_pushnumber(L, input_state_info->last_frame_rate_den[signal_num]);
481 int Effect_set_float(lua_State *L)
483 assert(lua_gettop(L) == 3);
484 Effect *effect = (Effect *)get_effect(L, 1);
485 string key = checkstdstring(L, 2);
486 float value = luaL_checknumber(L, 3);
487 if (!effect->set_float(key, value)) {
488 luaL_error(L, "Effect refused set_float(\"%s\", %d) (invalid key?)", key.c_str(), int(value));
493 int Effect_set_int(lua_State *L)
495 assert(lua_gettop(L) == 3);
496 Effect *effect = (Effect *)get_effect(L, 1);
497 string key = checkstdstring(L, 2);
498 float value = luaL_checknumber(L, 3);
499 if (!effect->set_int(key, value)) {
500 luaL_error(L, "Effect refused set_int(\"%s\", %d) (invalid key?)", key.c_str(), int(value));
505 int Effect_set_vec3(lua_State *L)
507 assert(lua_gettop(L) == 5);
508 Effect *effect = (Effect *)get_effect(L, 1);
509 string key = checkstdstring(L, 2);
511 v[0] = luaL_checknumber(L, 3);
512 v[1] = luaL_checknumber(L, 4);
513 v[2] = luaL_checknumber(L, 5);
514 if (!effect->set_vec3(key, v)) {
515 luaL_error(L, "Effect refused set_vec3(\"%s\", %f, %f, %f) (invalid key?)", key.c_str(),
521 int Effect_set_vec4(lua_State *L)
523 assert(lua_gettop(L) == 6);
524 Effect *effect = (Effect *)get_effect(L, 1);
525 string key = checkstdstring(L, 2);
527 v[0] = luaL_checknumber(L, 3);
528 v[1] = luaL_checknumber(L, 4);
529 v[2] = luaL_checknumber(L, 5);
530 v[3] = luaL_checknumber(L, 6);
531 if (!effect->set_vec4(key, v)) {
532 luaL_error(L, "Effect refused set_vec4(\"%s\", %f, %f, %f, %f) (invalid key?)", key.c_str(),
533 v[0], v[1], v[2], v[3]);
538 const luaL_Reg EffectChain_funcs[] = {
539 { "new", EffectChain_new },
540 { "__gc", EffectChain_gc },
541 { "add_live_input", EffectChain_add_live_input },
542 { "add_video_input", EffectChain_add_video_input },
543 { "add_effect", EffectChain_add_effect },
544 { "finalize", EffectChain_finalize },
548 const luaL_Reg LiveInputWrapper_funcs[] = {
549 { "connect_signal", LiveInputWrapper_connect_signal },
553 const luaL_Reg ImageInput_funcs[] = {
554 { "new", ImageInput_new },
555 { "set_float", Effect_set_float },
556 { "set_int", Effect_set_int },
557 { "set_vec3", Effect_set_vec3 },
558 { "set_vec4", Effect_set_vec4 },
562 const luaL_Reg VideoInput_funcs[] = {
563 { "new", VideoInput_new },
564 { "rewind", VideoInput_rewind },
568 const luaL_Reg WhiteBalanceEffect_funcs[] = {
569 { "new", WhiteBalanceEffect_new },
570 { "set_float", Effect_set_float },
571 { "set_int", Effect_set_int },
572 { "set_vec3", Effect_set_vec3 },
573 { "set_vec4", Effect_set_vec4 },
577 const luaL_Reg ResampleEffect_funcs[] = {
578 { "new", ResampleEffect_new },
579 { "set_float", Effect_set_float },
580 { "set_int", Effect_set_int },
581 { "set_vec3", Effect_set_vec3 },
582 { "set_vec4", Effect_set_vec4 },
586 const luaL_Reg PaddingEffect_funcs[] = {
587 { "new", PaddingEffect_new },
588 { "set_float", Effect_set_float },
589 { "set_int", Effect_set_int },
590 { "set_vec3", Effect_set_vec3 },
591 { "set_vec4", Effect_set_vec4 },
595 const luaL_Reg IntegralPaddingEffect_funcs[] = {
596 { "new", IntegralPaddingEffect_new },
597 { "set_float", Effect_set_float },
598 { "set_int", Effect_set_int },
599 { "set_vec3", Effect_set_vec3 },
600 { "set_vec4", Effect_set_vec4 },
604 const luaL_Reg OverlayEffect_funcs[] = {
605 { "new", OverlayEffect_new },
606 { "set_float", Effect_set_float },
607 { "set_int", Effect_set_int },
608 { "set_vec3", Effect_set_vec3 },
609 { "set_vec4", Effect_set_vec4 },
613 const luaL_Reg ResizeEffect_funcs[] = {
614 { "new", ResizeEffect_new },
615 { "set_float", Effect_set_float },
616 { "set_int", Effect_set_int },
617 { "set_vec3", Effect_set_vec3 },
618 { "set_vec4", Effect_set_vec4 },
622 const luaL_Reg MultiplyEffect_funcs[] = {
623 { "new", MultiplyEffect_new },
624 { "set_float", Effect_set_float },
625 { "set_int", Effect_set_int },
626 { "set_vec3", Effect_set_vec3 },
627 { "set_vec4", Effect_set_vec4 },
631 const luaL_Reg MixEffect_funcs[] = {
632 { "new", MixEffect_new },
633 { "set_float", Effect_set_float },
634 { "set_int", Effect_set_int },
635 { "set_vec3", Effect_set_vec3 },
636 { "set_vec4", Effect_set_vec4 },
640 const luaL_Reg InputStateInfo_funcs[] = {
641 { "get_width", InputStateInfo_get_width },
642 { "get_height", InputStateInfo_get_height },
643 { "get_interlaced", InputStateInfo_get_interlaced },
644 { "get_has_signal", InputStateInfo_get_has_signal },
645 { "get_is_connected", InputStateInfo_get_is_connected },
646 { "get_frame_rate_nom", InputStateInfo_get_frame_rate_nom },
647 { "get_frame_rate_den", InputStateInfo_get_frame_rate_den },
653 LiveInputWrapper::LiveInputWrapper(Theme *theme, EffectChain *chain, bmusb::PixelFormat pixel_format, bool override_bounce, bool deinterlace)
655 pixel_format(pixel_format),
656 deinterlace(deinterlace)
658 ImageFormat inout_format;
659 inout_format.color_space = COLORSPACE_sRGB;
661 // Gamma curve depends on the input signal, and we don't really get any
662 // indications. A camera would be expected to do Rec. 709, but
663 // I haven't checked if any do in practice. However, computers _do_ output
664 // in sRGB gamma (ie., they don't convert from sRGB to Rec. 709), and
665 // I wouldn't really be surprised if most non-professional cameras do, too.
666 // So we pick sRGB as the least evil here.
667 inout_format.gamma_curve = GAMMA_sRGB;
671 deinterlace_effect = new movit::DeinterlaceEffect();
673 // As per the comments in deinterlace_effect.h, we turn this off.
674 // The most likely interlaced input for us is either a camera
675 // (where it's fine to turn it off) or a laptop (where it _should_
677 CHECK(deinterlace_effect->set_int("enable_spatial_interlacing_check", 0));
679 num_inputs = deinterlace_effect->num_inputs();
680 assert(num_inputs == FRAME_HISTORY_LENGTH);
685 if (pixel_format == bmusb::PixelFormat_8BitRGBA) {
686 for (unsigned i = 0; i < num_inputs; ++i) {
687 if (global_flags.can_disable_srgb_decoder) {
688 rgba_inputs.push_back(new sRGBSwitchingFlatInput(inout_format, FORMAT_RGBA_POSTMULTIPLIED_ALPHA, GL_UNSIGNED_BYTE, global_flags.width, global_flags.height));
690 rgba_inputs.push_back(new NonsRGBCapableFlatInput(inout_format, FORMAT_RGBA_POSTMULTIPLIED_ALPHA, GL_UNSIGNED_BYTE, global_flags.width, global_flags.height));
692 chain->add_input(rgba_inputs.back());
696 vector<Effect *> reverse_inputs(rgba_inputs.rbegin(), rgba_inputs.rend());
697 chain->add_effect(deinterlace_effect, reverse_inputs);
700 assert(pixel_format == bmusb::PixelFormat_8BitYCbCr || pixel_format == bmusb::PixelFormat_10BitYCbCr);
701 // The Blackmagic driver docs claim that the device outputs Y'CbCr
702 // according to Rec. 601, but practical testing indicates it definitely
703 // is Rec. 709 (at least up to errors attributable to rounding errors).
704 // Perhaps 601 was only to indicate the subsampling positions, not the
705 // colorspace itself? Tested with a Lenovo X1 gen 3 as input.
706 YCbCrFormat input_ycbcr_format;
707 input_ycbcr_format.chroma_subsampling_x = (pixel_format == bmusb::PixelFormat_10BitYCbCr) ? 1 : 2;
708 input_ycbcr_format.chroma_subsampling_y = 1;
709 input_ycbcr_format.num_levels = (pixel_format == bmusb::PixelFormat_10BitYCbCr) ? 1024 : 256;
710 input_ycbcr_format.cb_x_position = 0.0;
711 input_ycbcr_format.cr_x_position = 0.0;
712 input_ycbcr_format.cb_y_position = 0.5;
713 input_ycbcr_format.cr_y_position = 0.5;
714 input_ycbcr_format.luma_coefficients = YCBCR_REC_709;
715 input_ycbcr_format.full_range = false;
717 for (unsigned i = 0; i < num_inputs; ++i) {
718 // When using 10-bit input, we're converting to interleaved through v210Converter.
719 YCbCrInputSplitting splitting = (pixel_format == bmusb::PixelFormat_10BitYCbCr) ? YCBCR_INPUT_INTERLEAVED : YCBCR_INPUT_SPLIT_Y_AND_CBCR;
720 if (override_bounce) {
721 ycbcr_inputs.push_back(new NonBouncingYCbCrInput(inout_format, input_ycbcr_format, global_flags.width, global_flags.height, splitting));
723 ycbcr_inputs.push_back(new YCbCrInput(inout_format, input_ycbcr_format, global_flags.width, global_flags.height, splitting));
725 chain->add_input(ycbcr_inputs.back());
729 vector<Effect *> reverse_inputs(ycbcr_inputs.rbegin(), ycbcr_inputs.rend());
730 chain->add_effect(deinterlace_effect, reverse_inputs);
735 void LiveInputWrapper::connect_signal(int signal_num)
737 if (global_mixer == nullptr) {
742 signal_num = theme->map_signal(signal_num);
743 connect_signal_raw(signal_num);
746 void LiveInputWrapper::connect_signal_raw(int signal_num)
748 BufferedFrame first_frame = theme->input_state->buffered_frames[signal_num][0];
749 if (first_frame.frame == nullptr) {
753 unsigned width, height;
755 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)first_frame.frame->userdata;
756 width = userdata->last_width[first_frame.field_number];
757 height = userdata->last_height[first_frame.field_number];
760 BufferedFrame last_good_frame = first_frame;
761 for (unsigned i = 0; i < max(ycbcr_inputs.size(), rgba_inputs.size()); ++i) {
762 BufferedFrame frame = theme->input_state->buffered_frames[signal_num][i];
763 if (frame.frame == nullptr) {
764 // Not enough data; reuse last frame (well, field).
765 // This is suboptimal, but we have nothing better.
766 frame = last_good_frame;
768 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
770 unsigned this_width = userdata->last_width[frame.field_number];
771 unsigned this_height = userdata->last_height[frame.field_number];
772 if (this_width != width || this_height != height) {
773 // Resolution changed; reuse last frame/field.
774 frame = last_good_frame;
775 userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
778 assert(userdata->pixel_format == pixel_format);
779 switch (pixel_format) {
780 case bmusb::PixelFormat_8BitYCbCr:
781 ycbcr_inputs[i]->set_texture_num(0, userdata->tex_y[frame.field_number]);
782 ycbcr_inputs[i]->set_texture_num(1, userdata->tex_cbcr[frame.field_number]);
783 ycbcr_inputs[i]->set_width(this_width);
784 ycbcr_inputs[i]->set_height(this_height);
786 case bmusb::PixelFormat_10BitYCbCr:
787 ycbcr_inputs[i]->set_texture_num(0, userdata->tex_444[frame.field_number]);
788 ycbcr_inputs[i]->set_width(this_width);
789 ycbcr_inputs[i]->set_height(this_height);
791 case bmusb::PixelFormat_8BitRGBA:
792 rgba_inputs[i]->set_texture_num(userdata->tex_rgba[frame.field_number]);
793 rgba_inputs[i]->set_width(this_width);
794 rgba_inputs[i]->set_height(this_height);
800 last_good_frame = frame;
804 BufferedFrame frame = theme->input_state->buffered_frames[signal_num][0];
805 CHECK(deinterlace_effect->set_int("current_field_position", frame.field_number));
811 int call_num_channels(lua_State *L)
813 lua_getglobal(L, "num_channels");
815 if (lua_pcall(L, 0, 1, 0) != 0) {
816 fprintf(stderr, "error running function `num_channels': %s\n", lua_tostring(L, -1));
820 int num_channels = luaL_checknumber(L, 1);
822 assert(lua_gettop(L) == 0);
828 Theme::Theme(const string &filename, const vector<string> &search_dirs, ResourcePool *resource_pool, unsigned num_cards)
829 : resource_pool(resource_pool), num_cards(num_cards), signal_to_card_mapping(global_flags.default_stream_mapping)
834 register_class("EffectChain", EffectChain_funcs);
835 register_class("LiveInputWrapper", LiveInputWrapper_funcs);
836 register_class("ImageInput", ImageInput_funcs);
837 register_class("VideoInput", VideoInput_funcs);
838 register_class("WhiteBalanceEffect", WhiteBalanceEffect_funcs);
839 register_class("ResampleEffect", ResampleEffect_funcs);
840 register_class("PaddingEffect", PaddingEffect_funcs);
841 register_class("IntegralPaddingEffect", IntegralPaddingEffect_funcs);
842 register_class("OverlayEffect", OverlayEffect_funcs);
843 register_class("ResizeEffect", ResizeEffect_funcs);
844 register_class("MultiplyEffect", MultiplyEffect_funcs);
845 register_class("MixEffect", MixEffect_funcs);
846 register_class("InputStateInfo", InputStateInfo_funcs);
848 // Run script. Search through all directories until we find a file that will load
849 // (as in, does not return LUA_ERRFILE); then run it. We store load errors
850 // from all the attempts, and show them once we know we can't find any of them.
852 vector<string> errors;
853 bool success = false;
854 for (size_t i = 0; i < search_dirs.size(); ++i) {
855 string path = search_dirs[i] + "/" + filename;
856 int err = luaL_loadfile(L, path.c_str());
858 // Success; actually call the code.
859 if (lua_pcall(L, 0, LUA_MULTRET, 0)) {
860 fprintf(stderr, "Error when running %s: %s\n", path.c_str(), lua_tostring(L, -1));
866 errors.push_back(lua_tostring(L, -1));
868 if (err != LUA_ERRFILE) {
869 // The file actually loaded, but failed to parse somehow. Abort; don't try the next one.
875 for (const string &error : errors) {
876 fprintf(stderr, "%s\n", error.c_str());
880 assert(lua_gettop(L) == 0);
882 // Ask it for the number of channels.
883 num_channels = call_num_channels(L);
891 void Theme::register_class(const char *class_name, const luaL_Reg *funcs)
893 assert(lua_gettop(L) == 0);
894 luaL_newmetatable(L, class_name); // mt = {}
895 lua_pushlightuserdata(L, this);
896 luaL_setfuncs(L, funcs, 1); // for (name,f in funcs) { mt[name] = f, with upvalue {theme} }
897 lua_pushvalue(L, -1);
898 lua_setfield(L, -2, "__index"); // mt.__index = mt
899 lua_setglobal(L, class_name); // ClassName = mt
900 assert(lua_gettop(L) == 0);
903 Theme::Chain Theme::get_chain(unsigned num, float t, unsigned width, unsigned height, InputState input_state)
907 unique_lock<mutex> lock(m);
908 assert(lua_gettop(L) == 0);
909 lua_getglobal(L, "get_chain"); /* function to be called */
910 lua_pushnumber(L, num);
911 lua_pushnumber(L, t);
912 lua_pushnumber(L, width);
913 lua_pushnumber(L, height);
914 wrap_lua_object<InputStateInfo>(L, "InputStateInfo", input_state);
916 if (lua_pcall(L, 5, 2, 0) != 0) {
917 fprintf(stderr, "error running function `get_chain': %s\n", lua_tostring(L, -1));
921 chain.chain = (EffectChain *)luaL_testudata(L, -2, "EffectChain");
922 if (chain.chain == nullptr) {
923 fprintf(stderr, "get_chain() for chain number %d did not return an EffectChain\n",
927 if (!lua_isfunction(L, -1)) {
928 fprintf(stderr, "Argument #-1 should be a function\n");
931 lua_pushvalue(L, -1);
932 shared_ptr<LuaRefWithDeleter> funcref(new LuaRefWithDeleter(&m, L, luaL_ref(L, LUA_REGISTRYINDEX)));
934 assert(lua_gettop(L) == 0);
936 chain.setup_chain = [this, funcref, input_state]{
937 unique_lock<mutex> lock(m);
939 this->input_state = &input_state;
941 // Set up state, including connecting signals.
942 lua_rawgeti(L, LUA_REGISTRYINDEX, funcref->get());
943 if (lua_pcall(L, 0, 0, 0) != 0) {
944 fprintf(stderr, "error running chain setup callback: %s\n", lua_tostring(L, -1));
947 assert(lua_gettop(L) == 0);
950 // TODO: Can we do better, e.g. by running setup_chain() and seeing what it references?
951 // Actually, setup_chain does maybe hold all the references we need now anyway?
952 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
953 for (unsigned frame_num = 0; frame_num < FRAME_HISTORY_LENGTH; ++frame_num) {
954 chain.input_frames.push_back(input_state.buffered_frames[card_index][frame_num].frame);
961 string Theme::get_channel_name(unsigned channel)
963 unique_lock<mutex> lock(m);
964 lua_getglobal(L, "channel_name");
965 lua_pushnumber(L, channel);
966 if (lua_pcall(L, 1, 1, 0) != 0) {
967 fprintf(stderr, "error running function `channel_name': %s\n", lua_tostring(L, -1));
970 const char *ret = lua_tostring(L, -1);
971 if (ret == nullptr) {
972 fprintf(stderr, "function `channel_name' returned nil for channel %d\n", channel);
978 assert(lua_gettop(L) == 0);
982 int Theme::get_channel_signal(unsigned channel)
984 unique_lock<mutex> lock(m);
985 lua_getglobal(L, "channel_signal");
986 lua_pushnumber(L, channel);
987 if (lua_pcall(L, 1, 1, 0) != 0) {
988 fprintf(stderr, "error running function `channel_signal': %s\n", lua_tostring(L, -1));
992 int ret = luaL_checknumber(L, 1);
994 assert(lua_gettop(L) == 0);
998 std::string Theme::get_channel_color(unsigned channel)
1000 unique_lock<mutex> lock(m);
1001 lua_getglobal(L, "channel_color");
1002 lua_pushnumber(L, channel);
1003 if (lua_pcall(L, 1, 1, 0) != 0) {
1004 fprintf(stderr, "error running function `channel_color': %s\n", lua_tostring(L, -1));
1008 const char *ret = lua_tostring(L, -1);
1009 if (ret == nullptr) {
1010 fprintf(stderr, "function `channel_color' returned nil for channel %d\n", channel);
1014 string retstr = ret;
1016 assert(lua_gettop(L) == 0);
1020 bool Theme::get_supports_set_wb(unsigned channel)
1022 unique_lock<mutex> lock(m);
1023 lua_getglobal(L, "supports_set_wb");
1024 lua_pushnumber(L, channel);
1025 if (lua_pcall(L, 1, 1, 0) != 0) {
1026 fprintf(stderr, "error running function `supports_set_wb': %s\n", lua_tostring(L, -1));
1030 bool ret = checkbool(L, -1);
1032 assert(lua_gettop(L) == 0);
1036 void Theme::set_wb(unsigned channel, double r, double g, double b)
1038 unique_lock<mutex> lock(m);
1039 lua_getglobal(L, "set_wb");
1040 lua_pushnumber(L, channel);
1041 lua_pushnumber(L, r);
1042 lua_pushnumber(L, g);
1043 lua_pushnumber(L, b);
1044 if (lua_pcall(L, 4, 0, 0) != 0) {
1045 fprintf(stderr, "error running function `set_wb': %s\n", lua_tostring(L, -1));
1049 assert(lua_gettop(L) == 0);
1052 vector<string> Theme::get_transition_names(float t)
1054 unique_lock<mutex> lock(m);
1055 lua_getglobal(L, "get_transitions");
1056 lua_pushnumber(L, t);
1057 if (lua_pcall(L, 1, 1, 0) != 0) {
1058 fprintf(stderr, "error running function `get_transitions': %s\n", lua_tostring(L, -1));
1064 while (lua_next(L, -2) != 0) {
1065 ret.push_back(lua_tostring(L, -1));
1069 assert(lua_gettop(L) == 0);
1073 int Theme::map_signal(int signal_num)
1075 unique_lock<mutex> lock(map_m);
1076 if (signal_to_card_mapping.count(signal_num)) {
1077 return signal_to_card_mapping[signal_num];
1081 if (global_flags.output_card != -1 && num_cards > 1) {
1082 // Try to exclude the output card from the default card_index.
1083 card_index = signal_num % (num_cards - 1);
1084 if (card_index >= global_flags.output_card) {
1087 if (signal_num >= int(num_cards - 1)) {
1088 fprintf(stderr, "WARNING: Theme asked for input %d, but we only have %u input card(s) (card %d is busy with output).\n",
1089 signal_num, num_cards - 1, global_flags.output_card);
1090 fprintf(stderr, "Mapping to card %d instead.\n", card_index);
1093 card_index = signal_num % num_cards;
1094 if (signal_num >= int(num_cards)) {
1095 fprintf(stderr, "WARNING: Theme asked for input %d, but we only have %u card(s).\n", signal_num, num_cards);
1096 fprintf(stderr, "Mapping to card %d instead.\n", card_index);
1099 signal_to_card_mapping[signal_num] = card_index;
1103 void Theme::set_signal_mapping(int signal_num, int card_num)
1105 unique_lock<mutex> lock(map_m);
1106 assert(card_num < int(num_cards));
1107 signal_to_card_mapping[signal_num] = card_num;
1110 void Theme::transition_clicked(int transition_num, float t)
1112 unique_lock<mutex> lock(m);
1113 lua_getglobal(L, "transition_clicked");
1114 lua_pushnumber(L, transition_num);
1115 lua_pushnumber(L, t);
1117 if (lua_pcall(L, 2, 0, 0) != 0) {
1118 fprintf(stderr, "error running function `transition_clicked': %s\n", lua_tostring(L, -1));
1121 assert(lua_gettop(L) == 0);
1124 void Theme::channel_clicked(int preview_num)
1126 unique_lock<mutex> lock(m);
1127 lua_getglobal(L, "channel_clicked");
1128 lua_pushnumber(L, preview_num);
1130 if (lua_pcall(L, 1, 0, 0) != 0) {
1131 fprintf(stderr, "error running function `channel_clicked': %s\n", lua_tostring(L, -1));
1134 assert(lua_gettop(L) == 0);