4 #include <bmusb/bmusb.h>
8 #include <movit/deinterlace_effect.h>
9 #include <movit/effect.h>
10 #include <movit/effect_chain.h>
11 #include <movit/image_format.h>
12 #include <movit/input.h>
13 #include <movit/mix_effect.h>
14 #include <movit/multiply_effect.h>
15 #include <movit/overlay_effect.h>
16 #include <movit/padding_effect.h>
17 #include <movit/resample_effect.h>
18 #include <movit/resize_effect.h>
19 #include <movit/util.h>
20 #include <movit/white_balance_effect.h>
21 #include <movit/ycbcr.h>
22 #include <movit/ycbcr_input.h>
31 #include "cef_capture.h"
32 #include "ffmpeg_capture.h"
34 #include "image_input.h"
35 #include "input_state.h"
36 #include "pbo_frame_allocator.h"
45 using namespace movit;
47 extern Mixer *global_mixer;
51 // Contains basically the same data as InputState, but does not hold on to
52 // a reference to the frames. This is important so that we can release them
53 // without having to wait for Lua's GC.
54 struct InputStateInfo {
55 InputStateInfo(const InputState& input_state);
57 unsigned last_width[MAX_VIDEO_CARDS], last_height[MAX_VIDEO_CARDS];
58 bool last_interlaced[MAX_VIDEO_CARDS], last_has_signal[MAX_VIDEO_CARDS], last_is_connected[MAX_VIDEO_CARDS];
59 unsigned last_frame_rate_nom[MAX_VIDEO_CARDS], last_frame_rate_den[MAX_VIDEO_CARDS];
62 InputStateInfo::InputStateInfo(const InputState &input_state)
64 for (unsigned signal_num = 0; signal_num < MAX_VIDEO_CARDS; ++signal_num) {
65 BufferedFrame frame = input_state.buffered_frames[signal_num][0];
66 if (frame.frame == nullptr) {
67 last_width[signal_num] = last_height[signal_num] = 0;
68 last_interlaced[signal_num] = false;
69 last_has_signal[signal_num] = false;
70 last_is_connected[signal_num] = false;
73 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
74 last_width[signal_num] = userdata->last_width[frame.field_number];
75 last_height[signal_num] = userdata->last_height[frame.field_number];
76 last_interlaced[signal_num] = userdata->last_interlaced;
77 last_has_signal[signal_num] = userdata->last_has_signal;
78 last_is_connected[signal_num] = userdata->last_is_connected;
79 last_frame_rate_nom[signal_num] = userdata->last_frame_rate_nom;
80 last_frame_rate_den[signal_num] = userdata->last_frame_rate_den;
84 class LuaRefWithDeleter {
86 LuaRefWithDeleter(mutex *m, lua_State *L, int ref) : m(m), L(L), ref(ref) {}
87 ~LuaRefWithDeleter() {
88 unique_lock<mutex> lock(*m);
89 luaL_unref(L, LUA_REGISTRYINDEX, ref);
91 int get() const { return ref; }
94 LuaRefWithDeleter(const LuaRefWithDeleter &) = delete;
101 template<class T, class... Args>
102 int wrap_lua_object(lua_State* L, const char *class_name, Args&&... args)
104 // Construct the C++ object and put it on the stack.
105 void *mem = lua_newuserdata(L, sizeof(T));
106 new(mem) T(forward<Args>(args)...);
108 // Look up the metatable named <class_name>, and set it on the new object.
109 luaL_getmetatable(L, class_name);
110 lua_setmetatable(L, -2);
115 // Like wrap_lua_object, but the object is not owned by Lua; ie. it's not freed
116 // by Lua GC. This is typically the case for Effects, which are owned by EffectChain
117 // and expected to be destructed by it. The object will be of type T** instead of T*
118 // when exposed to Lua.
120 // Note that we currently leak if you allocate an Effect in this way and never call
121 // add_effect. We should see if there's a way to e.g. set __gc on it at construction time
122 // and then release that once add_effect() takes ownership.
123 template<class T, class... Args>
124 int wrap_lua_object_nonowned(lua_State* L, const char *class_name, Args&&... args)
126 // Construct the pointer ot the C++ object and put it on the stack.
127 T **obj = (T **)lua_newuserdata(L, sizeof(T *));
128 *obj = new T(forward<Args>(args)...);
130 // Look up the metatable named <class_name>, and set it on the new object.
131 luaL_getmetatable(L, class_name);
132 lua_setmetatable(L, -2);
137 Theme *get_theme_updata(lua_State* L)
139 luaL_checktype(L, lua_upvalueindex(1), LUA_TLIGHTUSERDATA);
140 return (Theme *)lua_touserdata(L, lua_upvalueindex(1));
143 Effect *get_effect(lua_State *L, int idx)
145 if (luaL_testudata(L, idx, "WhiteBalanceEffect") ||
146 luaL_testudata(L, idx, "ResampleEffect") ||
147 luaL_testudata(L, idx, "PaddingEffect") ||
148 luaL_testudata(L, idx, "IntegralPaddingEffect") ||
149 luaL_testudata(L, idx, "OverlayEffect") ||
150 luaL_testudata(L, idx, "ResizeEffect") ||
151 luaL_testudata(L, idx, "MultiplyEffect") ||
152 luaL_testudata(L, idx, "MixEffect") ||
153 luaL_testudata(L, idx, "ImageInput")) {
154 return *(Effect **)lua_touserdata(L, idx);
156 luaL_error(L, "Error: Index #%d was not an Effect type\n", idx);
160 InputStateInfo *get_input_state_info(lua_State *L, int idx)
162 if (luaL_testudata(L, idx, "InputStateInfo")) {
163 return (InputStateInfo *)lua_touserdata(L, idx);
165 luaL_error(L, "Error: Index #%d was not InputStateInfo\n", idx);
169 bool checkbool(lua_State* L, int idx)
171 luaL_checktype(L, idx, LUA_TBOOLEAN);
172 return lua_toboolean(L, idx);
175 string checkstdstring(lua_State *L, int index)
178 const char* cstr = lua_tolstring(L, index, &len);
179 return string(cstr, len);
182 int EffectChain_new(lua_State* L)
184 assert(lua_gettop(L) == 2);
185 Theme *theme = get_theme_updata(L);
186 int aspect_w = luaL_checknumber(L, 1);
187 int aspect_h = luaL_checknumber(L, 2);
189 return wrap_lua_object<EffectChain>(L, "EffectChain", aspect_w, aspect_h, theme->get_resource_pool());
192 int EffectChain_gc(lua_State* L)
194 assert(lua_gettop(L) == 1);
195 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
196 chain->~EffectChain();
200 int EffectChain_add_live_input(lua_State* L)
202 assert(lua_gettop(L) == 3);
203 Theme *theme = get_theme_updata(L);
204 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
205 bool override_bounce = checkbool(L, 2);
206 bool deinterlace = checkbool(L, 3);
207 bmusb::PixelFormat pixel_format = global_flags.ten_bit_input ? bmusb::PixelFormat_10BitYCbCr : bmusb::PixelFormat_8BitYCbCr;
209 // Needs to be nonowned to match add_video_input (see below).
210 return wrap_lua_object_nonowned<LiveInputWrapper>(L, "LiveInputWrapper", theme, chain, pixel_format, override_bounce, deinterlace);
213 int EffectChain_add_video_input(lua_State* L)
215 assert(lua_gettop(L) == 3);
216 Theme *theme = get_theme_updata(L);
217 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
218 FFmpegCapture **capture = (FFmpegCapture **)luaL_checkudata(L, 2, "VideoInput");
219 bool deinterlace = checkbool(L, 3);
221 // These need to be nonowned, so that the LiveInputWrapper still exists
222 // and can feed frames to the right EffectChain even if the Lua code
223 // doesn't care about the object anymore. (If we change this, we'd need
224 // to also unregister the signal connection on __gc.)
225 int ret = wrap_lua_object_nonowned<LiveInputWrapper>(
226 L, "LiveInputWrapper", theme, chain, (*capture)->get_current_pixel_format(),
227 /*override_bounce=*/false, deinterlace);
229 Theme *theme = get_theme_updata(L);
230 LiveInputWrapper **live_input = (LiveInputWrapper **)lua_touserdata(L, -1);
231 theme->register_video_signal_connection(*live_input, *capture);
236 int EffectChain_add_html_input(lua_State* L)
238 assert(lua_gettop(L) == 2);
239 Theme *theme = get_theme_updata(L);
240 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
241 CEFCapture **capture = (CEFCapture **)luaL_checkudata(L, 2, "HTMLInput");
243 // These need to be nonowned, so that the LiveInputWrapper still exists
244 // and can feed frames to the right EffectChain even if the Lua code
245 // doesn't care about the object anymore. (If we change this, we'd need
246 // to also unregister the signal connection on __gc.)
247 int ret = wrap_lua_object_nonowned<LiveInputWrapper>(
248 L, "LiveInputWrapper", theme, chain, (*capture)->get_current_pixel_format(),
249 /*override_bounce=*/false, /*deinterlace=*/false);
251 Theme *theme = get_theme_updata(L);
252 LiveInputWrapper **live_input = (LiveInputWrapper **)lua_touserdata(L, -1);
253 theme->register_html_signal_connection(*live_input, *capture);
258 int EffectChain_add_effect(lua_State* L)
260 assert(lua_gettop(L) >= 2);
261 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
263 // TODO: Better error reporting.
264 Effect *effect = get_effect(L, 2);
265 if (lua_gettop(L) == 2) {
266 if (effect->num_inputs() == 0) {
267 chain->add_input((Input *)effect);
269 chain->add_effect(effect);
272 vector<Effect *> inputs;
273 for (int idx = 3; idx <= lua_gettop(L); ++idx) {
274 if (luaL_testudata(L, idx, "LiveInputWrapper")) {
275 LiveInputWrapper **input = (LiveInputWrapper **)lua_touserdata(L, idx);
276 inputs.push_back((*input)->get_effect());
278 inputs.push_back(get_effect(L, idx));
281 chain->add_effect(effect, inputs);
284 lua_settop(L, 2); // Return the effect itself.
286 // Make sure Lua doesn't garbage-collect it away.
287 lua_pushvalue(L, -1);
288 luaL_ref(L, LUA_REGISTRYINDEX); // TODO: leak?
293 int EffectChain_finalize(lua_State* L)
295 assert(lua_gettop(L) == 2);
296 EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
297 bool is_main_chain = checkbool(L, 2);
299 // Add outputs as needed.
300 // NOTE: If you change any details about the output format, you will need to
301 // also update what's given to the muxer (HTTPD::Mux constructor) and
302 // what's put in the H.264 stream (sps_rbsp()).
303 ImageFormat inout_format;
304 inout_format.color_space = COLORSPACE_REC_709;
306 // Output gamma is tricky. We should output Rec. 709 for TV, except that
307 // we expect to run with web players and others that don't really care and
308 // just output with no conversion. So that means we'll need to output sRGB,
309 // even though H.264 has no setting for that (we use “unspecified”).
310 inout_format.gamma_curve = GAMMA_sRGB;
313 YCbCrFormat output_ycbcr_format;
314 // We actually output 4:2:0 and/or 4:2:2 in the end, but chroma subsampling
315 // happens in a pass not run by Movit (see ChromaSubsampler::subsample_chroma()).
316 output_ycbcr_format.chroma_subsampling_x = 1;
317 output_ycbcr_format.chroma_subsampling_y = 1;
319 // This will be overridden if HDMI/SDI output is in force.
320 if (global_flags.ycbcr_rec709_coefficients) {
321 output_ycbcr_format.luma_coefficients = YCBCR_REC_709;
323 output_ycbcr_format.luma_coefficients = YCBCR_REC_601;
326 output_ycbcr_format.full_range = false;
327 output_ycbcr_format.num_levels = 1 << global_flags.x264_bit_depth;
329 GLenum type = global_flags.x264_bit_depth > 8 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_BYTE;
331 chain->add_ycbcr_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED, output_ycbcr_format, YCBCR_OUTPUT_SPLIT_Y_AND_CBCR, type);
333 // If we're using zerocopy video encoding (so the destination
334 // Y texture is owned by VA-API and will be unavailable for
335 // display), add a copy, where we'll only be using the Y component.
336 if (global_flags.use_zerocopy) {
337 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.
339 chain->set_dither_bits(global_flags.x264_bit_depth > 8 ? 16 : 8);
340 chain->set_output_origin(OUTPUT_ORIGIN_TOP_LEFT);
342 chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
349 int LiveInputWrapper_connect_signal(lua_State* L)
351 assert(lua_gettop(L) == 2);
352 LiveInputWrapper **input = (LiveInputWrapper **)luaL_checkudata(L, 1, "LiveInputWrapper");
353 int signal_num = luaL_checknumber(L, 2);
354 (*input)->connect_signal(signal_num);
358 int ImageInput_new(lua_State* L)
360 assert(lua_gettop(L) == 1);
361 string filename = checkstdstring(L, 1);
362 return wrap_lua_object_nonowned<ImageInput>(L, "ImageInput", filename);
365 int VideoInput_new(lua_State* L)
367 assert(lua_gettop(L) == 2);
368 string filename = checkstdstring(L, 1);
369 int pixel_format = luaL_checknumber(L, 2);
370 if (pixel_format != bmusb::PixelFormat_8BitYCbCrPlanar &&
371 pixel_format != bmusb::PixelFormat_8BitBGRA) {
372 fprintf(stderr, "WARNING: Invalid enum %d used for video format, choosing Y'CbCr.\n",
374 pixel_format = bmusb::PixelFormat_8BitYCbCrPlanar;
376 int ret = wrap_lua_object_nonowned<FFmpegCapture>(L, "VideoInput", filename, global_flags.width, global_flags.height);
378 FFmpegCapture **capture = (FFmpegCapture **)lua_touserdata(L, -1);
379 (*capture)->set_pixel_format(bmusb::PixelFormat(pixel_format));
381 Theme *theme = get_theme_updata(L);
382 theme->register_video_input(*capture);
387 int VideoInput_rewind(lua_State* L)
389 assert(lua_gettop(L) == 1);
390 FFmpegCapture **video_input = (FFmpegCapture **)luaL_checkudata(L, 1, "VideoInput");
391 (*video_input)->rewind();
395 int VideoInput_change_rate(lua_State* L)
397 assert(lua_gettop(L) == 2);
398 FFmpegCapture **video_input = (FFmpegCapture **)luaL_checkudata(L, 1, "VideoInput");
399 double new_rate = luaL_checknumber(L, 2);
400 (*video_input)->change_rate(new_rate);
404 int VideoInput_get_signal_num(lua_State* L)
406 assert(lua_gettop(L) == 1);
407 FFmpegCapture **video_input = (FFmpegCapture **)luaL_checkudata(L, 1, "VideoInput");
408 lua_pushnumber(L, -1 - (*video_input)->get_card_index());
412 int HTMLInput_new(lua_State* L)
414 assert(lua_gettop(L) == 1);
415 string url = checkstdstring(L, 1);
416 int ret = wrap_lua_object_nonowned<CEFCapture>(L, "HTMLInput", url, global_flags.width, global_flags.height);
418 CEFCapture **capture = (CEFCapture **)lua_touserdata(L, -1);
419 Theme *theme = get_theme_updata(L);
420 theme->register_html_input(*capture);
425 int HTMLInput_set_url(lua_State* L)
427 assert(lua_gettop(L) == 2);
428 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
429 string new_url = checkstdstring(L, 2);
430 (*video_input)->set_url(new_url);
434 int HTMLInput_reload(lua_State* L)
436 assert(lua_gettop(L) == 1);
437 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
438 (*video_input)->reload();
442 int HTMLInput_set_max_fps(lua_State* L)
444 assert(lua_gettop(L) == 2);
445 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
446 int max_fps = lrint(luaL_checknumber(L, 2));
447 (*video_input)->set_max_fps(max_fps);
451 int HTMLInput_get_signal_num(lua_State* L)
453 assert(lua_gettop(L) == 1);
454 CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
455 lua_pushnumber(L, -1 - (*video_input)->get_card_index());
459 int WhiteBalanceEffect_new(lua_State* L)
461 assert(lua_gettop(L) == 0);
462 return wrap_lua_object_nonowned<WhiteBalanceEffect>(L, "WhiteBalanceEffect");
465 int ResampleEffect_new(lua_State* L)
467 assert(lua_gettop(L) == 0);
468 return wrap_lua_object_nonowned<ResampleEffect>(L, "ResampleEffect");
471 int PaddingEffect_new(lua_State* L)
473 assert(lua_gettop(L) == 0);
474 return wrap_lua_object_nonowned<PaddingEffect>(L, "PaddingEffect");
477 int IntegralPaddingEffect_new(lua_State* L)
479 assert(lua_gettop(L) == 0);
480 return wrap_lua_object_nonowned<IntegralPaddingEffect>(L, "IntegralPaddingEffect");
483 int OverlayEffect_new(lua_State* L)
485 assert(lua_gettop(L) == 0);
486 return wrap_lua_object_nonowned<OverlayEffect>(L, "OverlayEffect");
489 int ResizeEffect_new(lua_State* L)
491 assert(lua_gettop(L) == 0);
492 return wrap_lua_object_nonowned<ResizeEffect>(L, "ResizeEffect");
495 int MultiplyEffect_new(lua_State* L)
497 assert(lua_gettop(L) == 0);
498 return wrap_lua_object_nonowned<MultiplyEffect>(L, "MultiplyEffect");
501 int MixEffect_new(lua_State* L)
503 assert(lua_gettop(L) == 0);
504 return wrap_lua_object_nonowned<MixEffect>(L, "MixEffect");
507 int InputStateInfo_get_width(lua_State* L)
509 assert(lua_gettop(L) == 2);
510 InputStateInfo *input_state_info = get_input_state_info(L, 1);
511 Theme *theme = get_theme_updata(L);
512 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
513 lua_pushnumber(L, input_state_info->last_width[signal_num]);
517 int InputStateInfo_get_height(lua_State* L)
519 assert(lua_gettop(L) == 2);
520 InputStateInfo *input_state_info = get_input_state_info(L, 1);
521 Theme *theme = get_theme_updata(L);
522 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
523 lua_pushnumber(L, input_state_info->last_height[signal_num]);
527 int InputStateInfo_get_interlaced(lua_State* L)
529 assert(lua_gettop(L) == 2);
530 InputStateInfo *input_state_info = get_input_state_info(L, 1);
531 Theme *theme = get_theme_updata(L);
532 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
533 lua_pushboolean(L, input_state_info->last_interlaced[signal_num]);
537 int InputStateInfo_get_has_signal(lua_State* L)
539 assert(lua_gettop(L) == 2);
540 InputStateInfo *input_state_info = get_input_state_info(L, 1);
541 Theme *theme = get_theme_updata(L);
542 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
543 lua_pushboolean(L, input_state_info->last_has_signal[signal_num]);
547 int InputStateInfo_get_is_connected(lua_State* L)
549 assert(lua_gettop(L) == 2);
550 InputStateInfo *input_state_info = get_input_state_info(L, 1);
551 Theme *theme = get_theme_updata(L);
552 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
553 lua_pushboolean(L, input_state_info->last_is_connected[signal_num]);
557 int InputStateInfo_get_frame_rate_nom(lua_State* L)
559 assert(lua_gettop(L) == 2);
560 InputStateInfo *input_state_info = get_input_state_info(L, 1);
561 Theme *theme = get_theme_updata(L);
562 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
563 lua_pushnumber(L, input_state_info->last_frame_rate_nom[signal_num]);
567 int InputStateInfo_get_frame_rate_den(lua_State* L)
569 assert(lua_gettop(L) == 2);
570 InputStateInfo *input_state_info = get_input_state_info(L, 1);
571 Theme *theme = get_theme_updata(L);
572 int signal_num = theme->map_signal(luaL_checknumber(L, 2));
573 lua_pushnumber(L, input_state_info->last_frame_rate_den[signal_num]);
577 int Effect_set_float(lua_State *L)
579 assert(lua_gettop(L) == 3);
580 Effect *effect = (Effect *)get_effect(L, 1);
581 string key = checkstdstring(L, 2);
582 float value = luaL_checknumber(L, 3);
583 if (!effect->set_float(key, value)) {
584 luaL_error(L, "Effect refused set_float(\"%s\", %d) (invalid key?)", key.c_str(), int(value));
589 int Effect_set_int(lua_State *L)
591 assert(lua_gettop(L) == 3);
592 Effect *effect = (Effect *)get_effect(L, 1);
593 string key = checkstdstring(L, 2);
594 float value = luaL_checknumber(L, 3);
595 if (!effect->set_int(key, value)) {
596 luaL_error(L, "Effect refused set_int(\"%s\", %d) (invalid key?)", key.c_str(), int(value));
601 int Effect_set_vec3(lua_State *L)
603 assert(lua_gettop(L) == 5);
604 Effect *effect = (Effect *)get_effect(L, 1);
605 string key = checkstdstring(L, 2);
607 v[0] = luaL_checknumber(L, 3);
608 v[1] = luaL_checknumber(L, 4);
609 v[2] = luaL_checknumber(L, 5);
610 if (!effect->set_vec3(key, v)) {
611 luaL_error(L, "Effect refused set_vec3(\"%s\", %f, %f, %f) (invalid key?)", key.c_str(),
617 int Effect_set_vec4(lua_State *L)
619 assert(lua_gettop(L) == 6);
620 Effect *effect = (Effect *)get_effect(L, 1);
621 string key = checkstdstring(L, 2);
623 v[0] = luaL_checknumber(L, 3);
624 v[1] = luaL_checknumber(L, 4);
625 v[2] = luaL_checknumber(L, 5);
626 v[3] = luaL_checknumber(L, 6);
627 if (!effect->set_vec4(key, v)) {
628 luaL_error(L, "Effect refused set_vec4(\"%s\", %f, %f, %f, %f) (invalid key?)", key.c_str(),
629 v[0], v[1], v[2], v[3]);
634 const luaL_Reg EffectChain_funcs[] = {
635 { "new", EffectChain_new },
636 { "__gc", EffectChain_gc },
637 { "add_live_input", EffectChain_add_live_input },
638 { "add_video_input", EffectChain_add_video_input },
639 { "add_html_input", EffectChain_add_html_input },
640 { "add_effect", EffectChain_add_effect },
641 { "finalize", EffectChain_finalize },
645 const luaL_Reg LiveInputWrapper_funcs[] = {
646 { "connect_signal", LiveInputWrapper_connect_signal },
650 const luaL_Reg ImageInput_funcs[] = {
651 { "new", ImageInput_new },
652 { "set_float", Effect_set_float },
653 { "set_int", Effect_set_int },
654 { "set_vec3", Effect_set_vec3 },
655 { "set_vec4", Effect_set_vec4 },
659 const luaL_Reg VideoInput_funcs[] = {
660 { "new", VideoInput_new },
661 { "rewind", VideoInput_rewind },
662 { "change_rate", VideoInput_change_rate },
663 { "get_signal_num", VideoInput_get_signal_num },
667 const luaL_Reg HTMLInput_funcs[] = {
668 // TODO: execute_javascript
669 { "new", HTMLInput_new },
670 { "set_url", HTMLInput_set_url },
671 { "reload", HTMLInput_reload },
672 { "set_max_fps", HTMLInput_set_max_fps },
673 { "get_signal_num", HTMLInput_get_signal_num },
677 const luaL_Reg WhiteBalanceEffect_funcs[] = {
678 { "new", WhiteBalanceEffect_new },
679 { "set_float", Effect_set_float },
680 { "set_int", Effect_set_int },
681 { "set_vec3", Effect_set_vec3 },
682 { "set_vec4", Effect_set_vec4 },
686 const luaL_Reg ResampleEffect_funcs[] = {
687 { "new", ResampleEffect_new },
688 { "set_float", Effect_set_float },
689 { "set_int", Effect_set_int },
690 { "set_vec3", Effect_set_vec3 },
691 { "set_vec4", Effect_set_vec4 },
695 const luaL_Reg PaddingEffect_funcs[] = {
696 { "new", PaddingEffect_new },
697 { "set_float", Effect_set_float },
698 { "set_int", Effect_set_int },
699 { "set_vec3", Effect_set_vec3 },
700 { "set_vec4", Effect_set_vec4 },
704 const luaL_Reg IntegralPaddingEffect_funcs[] = {
705 { "new", IntegralPaddingEffect_new },
706 { "set_float", Effect_set_float },
707 { "set_int", Effect_set_int },
708 { "set_vec3", Effect_set_vec3 },
709 { "set_vec4", Effect_set_vec4 },
713 const luaL_Reg OverlayEffect_funcs[] = {
714 { "new", OverlayEffect_new },
715 { "set_float", Effect_set_float },
716 { "set_int", Effect_set_int },
717 { "set_vec3", Effect_set_vec3 },
718 { "set_vec4", Effect_set_vec4 },
722 const luaL_Reg ResizeEffect_funcs[] = {
723 { "new", ResizeEffect_new },
724 { "set_float", Effect_set_float },
725 { "set_int", Effect_set_int },
726 { "set_vec3", Effect_set_vec3 },
727 { "set_vec4", Effect_set_vec4 },
731 const luaL_Reg MultiplyEffect_funcs[] = {
732 { "new", MultiplyEffect_new },
733 { "set_float", Effect_set_float },
734 { "set_int", Effect_set_int },
735 { "set_vec3", Effect_set_vec3 },
736 { "set_vec4", Effect_set_vec4 },
740 const luaL_Reg MixEffect_funcs[] = {
741 { "new", MixEffect_new },
742 { "set_float", Effect_set_float },
743 { "set_int", Effect_set_int },
744 { "set_vec3", Effect_set_vec3 },
745 { "set_vec4", Effect_set_vec4 },
749 const luaL_Reg InputStateInfo_funcs[] = {
750 { "get_width", InputStateInfo_get_width },
751 { "get_height", InputStateInfo_get_height },
752 { "get_interlaced", InputStateInfo_get_interlaced },
753 { "get_has_signal", InputStateInfo_get_has_signal },
754 { "get_is_connected", InputStateInfo_get_is_connected },
755 { "get_frame_rate_nom", InputStateInfo_get_frame_rate_nom },
756 { "get_frame_rate_den", InputStateInfo_get_frame_rate_den },
762 LiveInputWrapper::LiveInputWrapper(Theme *theme, EffectChain *chain, bmusb::PixelFormat pixel_format, bool override_bounce, bool deinterlace)
764 pixel_format(pixel_format),
765 deinterlace(deinterlace)
767 ImageFormat inout_format;
768 inout_format.color_space = COLORSPACE_sRGB;
770 // Gamma curve depends on the input signal, and we don't really get any
771 // indications. A camera would be expected to do Rec. 709, but
772 // I haven't checked if any do in practice. However, computers _do_ output
773 // in sRGB gamma (ie., they don't convert from sRGB to Rec. 709), and
774 // I wouldn't really be surprised if most non-professional cameras do, too.
775 // So we pick sRGB as the least evil here.
776 inout_format.gamma_curve = GAMMA_sRGB;
780 deinterlace_effect = new movit::DeinterlaceEffect();
782 // As per the comments in deinterlace_effect.h, we turn this off.
783 // The most likely interlaced input for us is either a camera
784 // (where it's fine to turn it off) or a laptop (where it _should_
786 CHECK(deinterlace_effect->set_int("enable_spatial_interlacing_check", 0));
788 num_inputs = deinterlace_effect->num_inputs();
789 assert(num_inputs == FRAME_HISTORY_LENGTH);
794 if (pixel_format == bmusb::PixelFormat_8BitBGRA) {
795 for (unsigned i = 0; i < num_inputs; ++i) {
796 // We upload our textures ourselves, and Movit swaps
797 // R and B in the shader if we specify BGRA, so lie and say RGBA.
798 if (global_flags.can_disable_srgb_decoder) {
799 rgba_inputs.push_back(new sRGBSwitchingFlatInput(inout_format, FORMAT_RGBA_POSTMULTIPLIED_ALPHA, GL_UNSIGNED_BYTE, global_flags.width, global_flags.height));
801 rgba_inputs.push_back(new NonsRGBCapableFlatInput(inout_format, FORMAT_RGBA_POSTMULTIPLIED_ALPHA, GL_UNSIGNED_BYTE, global_flags.width, global_flags.height));
803 chain->add_input(rgba_inputs.back());
807 vector<Effect *> reverse_inputs(rgba_inputs.rbegin(), rgba_inputs.rend());
808 chain->add_effect(deinterlace_effect, reverse_inputs);
811 assert(pixel_format == bmusb::PixelFormat_8BitYCbCr ||
812 pixel_format == bmusb::PixelFormat_10BitYCbCr ||
813 pixel_format == bmusb::PixelFormat_8BitYCbCrPlanar);
815 // Most of these settings will be overridden later if using PixelFormat_8BitYCbCrPlanar.
816 input_ycbcr_format.chroma_subsampling_x = (pixel_format == bmusb::PixelFormat_10BitYCbCr) ? 1 : 2;
817 input_ycbcr_format.chroma_subsampling_y = 1;
818 input_ycbcr_format.num_levels = (pixel_format == bmusb::PixelFormat_10BitYCbCr) ? 1024 : 256;
819 input_ycbcr_format.cb_x_position = 0.0;
820 input_ycbcr_format.cr_x_position = 0.0;
821 input_ycbcr_format.cb_y_position = 0.5;
822 input_ycbcr_format.cr_y_position = 0.5;
823 input_ycbcr_format.luma_coefficients = YCBCR_REC_709; // Will be overridden later even if not planar.
824 input_ycbcr_format.full_range = false; // Will be overridden later even if not planar.
826 for (unsigned i = 0; i < num_inputs; ++i) {
827 // When using 10-bit input, we're converting to interleaved through v210Converter.
828 YCbCrInputSplitting splitting;
829 if (pixel_format == bmusb::PixelFormat_10BitYCbCr) {
830 splitting = YCBCR_INPUT_INTERLEAVED;
831 } else if (pixel_format == bmusb::PixelFormat_8BitYCbCr) {
832 splitting = YCBCR_INPUT_SPLIT_Y_AND_CBCR;
834 splitting = YCBCR_INPUT_PLANAR;
836 if (override_bounce) {
837 ycbcr_inputs.push_back(new NonBouncingYCbCrInput(inout_format, input_ycbcr_format, global_flags.width, global_flags.height, splitting));
839 ycbcr_inputs.push_back(new YCbCrInput(inout_format, input_ycbcr_format, global_flags.width, global_flags.height, splitting));
841 chain->add_input(ycbcr_inputs.back());
845 vector<Effect *> reverse_inputs(ycbcr_inputs.rbegin(), ycbcr_inputs.rend());
846 chain->add_effect(deinterlace_effect, reverse_inputs);
851 void LiveInputWrapper::connect_signal(int signal_num)
853 if (global_mixer == nullptr) {
858 signal_num = theme->map_signal(signal_num);
859 connect_signal_raw(signal_num, *theme->input_state);
862 void LiveInputWrapper::connect_signal_raw(int signal_num, const InputState &input_state)
864 BufferedFrame first_frame = input_state.buffered_frames[signal_num][0];
865 if (first_frame.frame == nullptr) {
869 unsigned width, height;
871 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)first_frame.frame->userdata;
872 width = userdata->last_width[first_frame.field_number];
873 height = userdata->last_height[first_frame.field_number];
876 movit::YCbCrLumaCoefficients ycbcr_coefficients = input_state.ycbcr_coefficients[signal_num];
877 bool full_range = input_state.full_range[signal_num];
879 if (input_state.ycbcr_coefficients_auto[signal_num]) {
882 // The Blackmagic driver docs claim that the device outputs Y'CbCr
883 // according to Rec. 601, but this seems to indicate the subsampling
884 // positions only, as they publish Y'CbCr → RGB formulas that are
885 // different for HD and SD (corresponding to Rec. 709 and 601, respectively),
886 // and a Lenovo X1 gen 3 I used to test definitely outputs Rec. 709
887 // (at least up to rounding error). Other devices seem to use Rec. 601
888 // even on HD resolutions. Nevertheless, Rec. 709 _is_ the right choice
889 // for HD, so we default to that if the user hasn't set anything.
891 ycbcr_coefficients = YCBCR_REC_709;
893 ycbcr_coefficients = YCBCR_REC_601;
897 // This is a global, but it doesn't really matter.
898 input_ycbcr_format.luma_coefficients = ycbcr_coefficients;
899 input_ycbcr_format.full_range = full_range;
901 BufferedFrame last_good_frame = first_frame;
902 for (unsigned i = 0; i < max(ycbcr_inputs.size(), rgba_inputs.size()); ++i) {
903 BufferedFrame frame = input_state.buffered_frames[signal_num][i];
904 if (frame.frame == nullptr) {
905 // Not enough data; reuse last frame (well, field).
906 // This is suboptimal, but we have nothing better.
907 frame = last_good_frame;
909 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
911 unsigned this_width = userdata->last_width[frame.field_number];
912 unsigned this_height = userdata->last_height[frame.field_number];
913 if (this_width != width || this_height != height) {
914 // Resolution changed; reuse last frame/field.
915 frame = last_good_frame;
916 userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
919 assert(userdata->pixel_format == pixel_format);
920 switch (pixel_format) {
921 case bmusb::PixelFormat_8BitYCbCr:
922 ycbcr_inputs[i]->set_texture_num(0, userdata->tex_y[frame.field_number]);
923 ycbcr_inputs[i]->set_texture_num(1, userdata->tex_cbcr[frame.field_number]);
924 ycbcr_inputs[i]->change_ycbcr_format(input_ycbcr_format);
925 ycbcr_inputs[i]->set_width(width);
926 ycbcr_inputs[i]->set_height(height);
928 case bmusb::PixelFormat_8BitYCbCrPlanar:
929 ycbcr_inputs[i]->set_texture_num(0, userdata->tex_y[frame.field_number]);
930 ycbcr_inputs[i]->set_texture_num(1, userdata->tex_cb[frame.field_number]);
931 ycbcr_inputs[i]->set_texture_num(2, userdata->tex_cr[frame.field_number]);
932 ycbcr_inputs[i]->change_ycbcr_format(userdata->ycbcr_format);
933 ycbcr_inputs[i]->set_width(width);
934 ycbcr_inputs[i]->set_height(height);
936 case bmusb::PixelFormat_10BitYCbCr:
937 ycbcr_inputs[i]->set_texture_num(0, userdata->tex_444[frame.field_number]);
938 ycbcr_inputs[i]->change_ycbcr_format(input_ycbcr_format);
939 ycbcr_inputs[i]->set_width(width);
940 ycbcr_inputs[i]->set_height(height);
942 case bmusb::PixelFormat_8BitBGRA:
943 rgba_inputs[i]->set_texture_num(userdata->tex_rgba[frame.field_number]);
944 rgba_inputs[i]->set_width(width);
945 rgba_inputs[i]->set_height(height);
951 last_good_frame = frame;
955 BufferedFrame frame = input_state.buffered_frames[signal_num][0];
956 CHECK(deinterlace_effect->set_int("current_field_position", frame.field_number));
962 int call_num_channels(lua_State *L)
964 lua_getglobal(L, "num_channels");
966 if (lua_pcall(L, 0, 1, 0) != 0) {
967 fprintf(stderr, "error running function `num_channels': %s\n", lua_tostring(L, -1));
971 int num_channels = luaL_checknumber(L, 1);
973 assert(lua_gettop(L) == 0);
979 Theme::Theme(const string &filename, const vector<string> &search_dirs, ResourcePool *resource_pool, unsigned num_cards)
980 : resource_pool(resource_pool), num_cards(num_cards), signal_to_card_mapping(global_flags.default_stream_mapping)
985 register_constants();
986 register_class("EffectChain", EffectChain_funcs);
987 register_class("LiveInputWrapper", LiveInputWrapper_funcs);
988 register_class("ImageInput", ImageInput_funcs);
989 register_class("VideoInput", VideoInput_funcs);
990 register_class("HTMLInput", HTMLInput_funcs);
991 register_class("WhiteBalanceEffect", WhiteBalanceEffect_funcs);
992 register_class("ResampleEffect", ResampleEffect_funcs);
993 register_class("PaddingEffect", PaddingEffect_funcs);
994 register_class("IntegralPaddingEffect", IntegralPaddingEffect_funcs);
995 register_class("OverlayEffect", OverlayEffect_funcs);
996 register_class("ResizeEffect", ResizeEffect_funcs);
997 register_class("MultiplyEffect", MultiplyEffect_funcs);
998 register_class("MixEffect", MixEffect_funcs);
999 register_class("InputStateInfo", InputStateInfo_funcs);
1001 // Run script. Search through all directories until we find a file that will load
1002 // (as in, does not return LUA_ERRFILE); then run it. We store load errors
1003 // from all the attempts, and show them once we know we can't find any of them.
1005 vector<string> errors;
1006 bool success = false;
1007 for (size_t i = 0; i < search_dirs.size(); ++i) {
1008 string path = search_dirs[i] + "/" + filename;
1009 int err = luaL_loadfile(L, path.c_str());
1011 // Success; actually call the code.
1012 if (lua_pcall(L, 0, LUA_MULTRET, 0)) {
1013 fprintf(stderr, "Error when running %s: %s\n", path.c_str(), lua_tostring(L, -1));
1019 errors.push_back(lua_tostring(L, -1));
1021 if (err != LUA_ERRFILE) {
1022 // The file actually loaded, but failed to parse somehow. Abort; don't try the next one.
1028 for (const string &error : errors) {
1029 fprintf(stderr, "%s\n", error.c_str());
1033 assert(lua_gettop(L) == 0);
1035 // Ask it for the number of channels.
1036 num_channels = call_num_channels(L);
1044 void Theme::register_constants()
1046 // Set Nageru.VIDEO_FORMAT_BGRA = bmusb::PixelFormat_8BitBGRA, etc.
1047 const vector<pair<string, int>> constants = {
1048 { "VIDEO_FORMAT_BGRA", bmusb::PixelFormat_8BitBGRA },
1049 { "VIDEO_FORMAT_YCBCR", bmusb::PixelFormat_8BitYCbCrPlanar },
1052 lua_newtable(L); // t = {}
1054 for (const pair<string, int> &constant : constants) {
1055 lua_pushstring(L, constant.first.c_str());
1056 lua_pushinteger(L, constant.second);
1057 lua_settable(L, 1); // t[key] = value
1060 lua_setglobal(L, "Nageru"); // Nageru = t
1061 assert(lua_gettop(L) == 0);
1064 void Theme::register_class(const char *class_name, const luaL_Reg *funcs)
1066 assert(lua_gettop(L) == 0);
1067 luaL_newmetatable(L, class_name); // mt = {}
1068 lua_pushlightuserdata(L, this);
1069 luaL_setfuncs(L, funcs, 1); // for (name,f in funcs) { mt[name] = f, with upvalue {theme} }
1070 lua_pushvalue(L, -1);
1071 lua_setfield(L, -2, "__index"); // mt.__index = mt
1072 lua_setglobal(L, class_name); // ClassName = mt
1073 assert(lua_gettop(L) == 0);
1076 Theme::Chain Theme::get_chain(unsigned num, float t, unsigned width, unsigned height, InputState input_state)
1080 unique_lock<mutex> lock(m);
1081 assert(lua_gettop(L) == 0);
1082 lua_getglobal(L, "get_chain"); /* function to be called */
1083 lua_pushnumber(L, num);
1084 lua_pushnumber(L, t);
1085 lua_pushnumber(L, width);
1086 lua_pushnumber(L, height);
1087 wrap_lua_object<InputStateInfo>(L, "InputStateInfo", input_state);
1089 if (lua_pcall(L, 5, 2, 0) != 0) {
1090 fprintf(stderr, "error running function `get_chain': %s\n", lua_tostring(L, -1));
1094 chain.chain = (EffectChain *)luaL_testudata(L, -2, "EffectChain");
1095 if (chain.chain == nullptr) {
1096 fprintf(stderr, "get_chain() for chain number %d did not return an EffectChain\n",
1100 if (!lua_isfunction(L, -1)) {
1101 fprintf(stderr, "Argument #-1 should be a function\n");
1104 lua_pushvalue(L, -1);
1105 shared_ptr<LuaRefWithDeleter> funcref(new LuaRefWithDeleter(&m, L, luaL_ref(L, LUA_REGISTRYINDEX)));
1107 assert(lua_gettop(L) == 0);
1109 chain.setup_chain = [this, funcref, input_state]{
1110 unique_lock<mutex> lock(m);
1112 assert(this->input_state == nullptr);
1113 this->input_state = &input_state;
1115 // Set up state, including connecting signals.
1116 lua_rawgeti(L, LUA_REGISTRYINDEX, funcref->get());
1117 if (lua_pcall(L, 0, 0, 0) != 0) {
1118 fprintf(stderr, "error running chain setup callback: %s\n", lua_tostring(L, -1));
1121 assert(lua_gettop(L) == 0);
1123 this->input_state = nullptr;
1126 // TODO: Can we do better, e.g. by running setup_chain() and seeing what it references?
1127 // Actually, setup_chain does maybe hold all the references we need now anyway?
1128 chain.input_frames.reserve(num_cards * FRAME_HISTORY_LENGTH);
1129 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
1130 for (unsigned frame_num = 0; frame_num < FRAME_HISTORY_LENGTH; ++frame_num) {
1131 chain.input_frames.push_back(input_state.buffered_frames[card_index][frame_num].frame);
1138 string Theme::get_channel_name(unsigned channel)
1140 unique_lock<mutex> lock(m);
1141 lua_getglobal(L, "channel_name");
1142 lua_pushnumber(L, channel);
1143 if (lua_pcall(L, 1, 1, 0) != 0) {
1144 fprintf(stderr, "error running function `channel_name': %s\n", lua_tostring(L, -1));
1147 const char *ret = lua_tostring(L, -1);
1148 if (ret == nullptr) {
1149 fprintf(stderr, "function `channel_name' returned nil for channel %d\n", channel);
1153 string retstr = ret;
1155 assert(lua_gettop(L) == 0);
1159 int Theme::get_channel_signal(unsigned channel)
1161 unique_lock<mutex> lock(m);
1162 lua_getglobal(L, "channel_signal");
1163 lua_pushnumber(L, channel);
1164 if (lua_pcall(L, 1, 1, 0) != 0) {
1165 fprintf(stderr, "error running function `channel_signal': %s\n", lua_tostring(L, -1));
1169 int ret = luaL_checknumber(L, 1);
1171 assert(lua_gettop(L) == 0);
1175 std::string Theme::get_channel_color(unsigned channel)
1177 unique_lock<mutex> lock(m);
1178 lua_getglobal(L, "channel_color");
1179 lua_pushnumber(L, channel);
1180 if (lua_pcall(L, 1, 1, 0) != 0) {
1181 fprintf(stderr, "error running function `channel_color': %s\n", lua_tostring(L, -1));
1185 const char *ret = lua_tostring(L, -1);
1186 if (ret == nullptr) {
1187 fprintf(stderr, "function `channel_color' returned nil for channel %d\n", channel);
1191 string retstr = ret;
1193 assert(lua_gettop(L) == 0);
1197 bool Theme::get_supports_set_wb(unsigned channel)
1199 unique_lock<mutex> lock(m);
1200 lua_getglobal(L, "supports_set_wb");
1201 lua_pushnumber(L, channel);
1202 if (lua_pcall(L, 1, 1, 0) != 0) {
1203 fprintf(stderr, "error running function `supports_set_wb': %s\n", lua_tostring(L, -1));
1207 bool ret = checkbool(L, -1);
1209 assert(lua_gettop(L) == 0);
1213 void Theme::set_wb(unsigned channel, double r, double g, double b)
1215 unique_lock<mutex> lock(m);
1216 lua_getglobal(L, "set_wb");
1217 lua_pushnumber(L, channel);
1218 lua_pushnumber(L, r);
1219 lua_pushnumber(L, g);
1220 lua_pushnumber(L, b);
1221 if (lua_pcall(L, 4, 0, 0) != 0) {
1222 fprintf(stderr, "error running function `set_wb': %s\n", lua_tostring(L, -1));
1226 assert(lua_gettop(L) == 0);
1229 vector<string> Theme::get_transition_names(float t)
1231 unique_lock<mutex> lock(m);
1232 lua_getglobal(L, "get_transitions");
1233 lua_pushnumber(L, t);
1234 if (lua_pcall(L, 1, 1, 0) != 0) {
1235 fprintf(stderr, "error running function `get_transitions': %s\n", lua_tostring(L, -1));
1241 while (lua_next(L, -2) != 0) {
1242 ret.push_back(lua_tostring(L, -1));
1246 assert(lua_gettop(L) == 0);
1250 int Theme::map_signal(int signal_num)
1252 // Negative numbers map to raw signals.
1253 if (signal_num < 0) {
1254 return -1 - signal_num;
1257 unique_lock<mutex> lock(map_m);
1258 if (signal_to_card_mapping.count(signal_num)) {
1259 return signal_to_card_mapping[signal_num];
1263 if (global_flags.output_card != -1 && num_cards > 1) {
1264 // Try to exclude the output card from the default card_index.
1265 card_index = signal_num % (num_cards - 1);
1266 if (card_index >= global_flags.output_card) {
1269 if (signal_num >= int(num_cards - 1)) {
1270 fprintf(stderr, "WARNING: Theme asked for input %d, but we only have %u input card(s) (card %d is busy with output).\n",
1271 signal_num, num_cards - 1, global_flags.output_card);
1272 fprintf(stderr, "Mapping to card %d instead.\n", card_index);
1275 card_index = signal_num % num_cards;
1276 if (signal_num >= int(num_cards)) {
1277 fprintf(stderr, "WARNING: Theme asked for input %d, but we only have %u card(s).\n", signal_num, num_cards);
1278 fprintf(stderr, "Mapping to card %d instead.\n", card_index);
1281 signal_to_card_mapping[signal_num] = card_index;
1285 void Theme::set_signal_mapping(int signal_num, int card_num)
1287 unique_lock<mutex> lock(map_m);
1288 assert(card_num < int(num_cards));
1289 signal_to_card_mapping[signal_num] = card_num;
1292 void Theme::transition_clicked(int transition_num, float t)
1294 unique_lock<mutex> lock(m);
1295 lua_getglobal(L, "transition_clicked");
1296 lua_pushnumber(L, transition_num);
1297 lua_pushnumber(L, t);
1299 if (lua_pcall(L, 2, 0, 0) != 0) {
1300 fprintf(stderr, "error running function `transition_clicked': %s\n", lua_tostring(L, -1));
1303 assert(lua_gettop(L) == 0);
1306 void Theme::channel_clicked(int preview_num)
1308 unique_lock<mutex> lock(m);
1309 lua_getglobal(L, "channel_clicked");
1310 lua_pushnumber(L, preview_num);
1312 if (lua_pcall(L, 1, 0, 0) != 0) {
1313 fprintf(stderr, "error running function `channel_clicked': %s\n", lua_tostring(L, -1));
1316 assert(lua_gettop(L) == 0);