]> git.sesse.net Git - nageru/blob - theme.cpp
Expose MultiplyEffect to themes.
[nageru] / theme.cpp
1 #include "theme.h"
2
3 #include <assert.h>
4 #include <lauxlib.h>
5 #include <lua.hpp>
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>
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <cstddef>
22 #include <new>
23 #include <utility>
24 #include <memory>
25
26 #include "defs.h"
27 #include "image_input.h"
28 #include "mixer.h"
29
30 namespace movit {
31 class ResourcePool;
32 }  // namespace movit
33
34 using namespace std;
35 using namespace movit;
36
37 extern Mixer *global_mixer;
38
39 namespace {
40
41 // Contains basically the same data as InputState, but does not hold on to
42 // a reference to the frames. This is important so that we can release them
43 // without having to wait for Lua's GC.
44 struct InputStateInfo {
45         InputStateInfo(const InputState& input_state);
46
47         unsigned last_width[MAX_CARDS], last_height[MAX_CARDS];
48         bool last_interlaced[MAX_CARDS], last_has_signal[MAX_CARDS];
49         unsigned last_frame_rate_nom[MAX_CARDS], last_frame_rate_den[MAX_CARDS];
50 };
51
52 InputStateInfo::InputStateInfo(const InputState &input_state)
53 {
54         for (unsigned signal_num = 0; signal_num < MAX_CARDS; ++signal_num) {
55                 BufferedFrame frame = input_state.buffered_frames[signal_num][0];
56                 if (frame.frame == nullptr) {
57                         last_width[signal_num] = last_height[signal_num] = 0;
58                         last_interlaced[signal_num] = false;
59                         last_has_signal[signal_num] = false;
60                         continue;
61                 }
62                 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
63                 last_width[signal_num] = userdata->last_width[frame.field_number];
64                 last_height[signal_num] = userdata->last_height[frame.field_number];
65                 last_interlaced[signal_num] = userdata->last_interlaced;
66                 last_has_signal[signal_num] = userdata->last_has_signal;
67                 last_frame_rate_nom[signal_num] = userdata->last_frame_rate_nom;
68                 last_frame_rate_den[signal_num] = userdata->last_frame_rate_den;
69         }
70 }
71
72 class LuaRefWithDeleter {
73 public:
74         LuaRefWithDeleter(mutex *m, lua_State *L, int ref) : m(m), L(L), ref(ref) {}
75         ~LuaRefWithDeleter() {
76                 unique_lock<mutex> lock(*m);
77                 luaL_unref(L, LUA_REGISTRYINDEX, ref);
78         }
79         int get() const { return ref; }
80
81 private:
82         LuaRefWithDeleter(const LuaRefWithDeleter &) = delete;
83
84         mutex *m;
85         lua_State *L;
86         int ref;
87 };
88
89 template<class T, class... Args>
90 int wrap_lua_object(lua_State* L, const char *class_name, Args&&... args)
91 {
92         // Construct the C++ object and put it on the stack.
93         void *mem = lua_newuserdata(L, sizeof(T));
94         new(mem) T(forward<Args>(args)...);
95
96         // Look up the metatable named <class_name>, and set it on the new object.
97         luaL_getmetatable(L, class_name);
98         lua_setmetatable(L, -2);
99
100         return 1;
101 }
102
103 // Like wrap_lua_object, but the object is not owned by Lua; ie. it's not freed
104 // by Lua GC. This is typically the case for Effects, which are owned by EffectChain
105 // and expected to be destructed by it. The object will be of type T** instead of T*
106 // when exposed to Lua.
107 //
108 // Note that we currently leak if you allocate an Effect in this way and never call
109 // add_effect. We should see if there's a way to e.g. set __gc on it at construction time
110 // and then release that once add_effect() takes ownership.
111 template<class T, class... Args>
112 int wrap_lua_object_nonowned(lua_State* L, const char *class_name, Args&&... args)
113 {
114         // Construct the pointer ot the C++ object and put it on the stack.
115         T **obj = (T **)lua_newuserdata(L, sizeof(T *));
116         *obj = new T(forward<Args>(args)...);
117
118         // Look up the metatable named <class_name>, and set it on the new object.
119         luaL_getmetatable(L, class_name);
120         lua_setmetatable(L, -2);
121
122         return 1;
123 }
124
125 Theme *get_theme_updata(lua_State* L)
126 {       
127         luaL_checktype(L, lua_upvalueindex(1), LUA_TLIGHTUSERDATA);
128         return (Theme *)lua_touserdata(L, lua_upvalueindex(1));
129 }
130
131 Effect *get_effect(lua_State *L, int idx)
132 {
133         if (luaL_testudata(L, idx, "WhiteBalanceEffect") ||
134             luaL_testudata(L, idx, "ResampleEffect") ||
135             luaL_testudata(L, idx, "PaddingEffect") ||
136             luaL_testudata(L, idx, "IntegralPaddingEffect") ||
137             luaL_testudata(L, idx, "OverlayEffect") ||
138             luaL_testudata(L, idx, "ResizeEffect") ||
139             luaL_testudata(L, idx, "MultiplyEffect") ||
140             luaL_testudata(L, idx, "MixEffect") ||
141             luaL_testudata(L, idx, "ImageInput")) {
142                 return *(Effect **)lua_touserdata(L, idx);
143         }
144         luaL_error(L, "Error: Index #%d was not an Effect type\n", idx);
145         return nullptr;
146 }
147
148 InputStateInfo *get_input_state_info(lua_State *L, int idx)
149 {
150         if (luaL_testudata(L, idx, "InputStateInfo")) {
151                 return (InputStateInfo *)lua_touserdata(L, idx);
152         }
153         luaL_error(L, "Error: Index #%d was not InputStateInfo\n", idx);
154         return nullptr;
155 }
156
157 bool checkbool(lua_State* L, int idx)
158 {
159         luaL_checktype(L, idx, LUA_TBOOLEAN);
160         return lua_toboolean(L, idx);
161 }
162
163 string checkstdstring(lua_State *L, int index)
164 {
165         size_t len;
166         const char* cstr = lua_tolstring(L, index, &len);
167         return string(cstr, len);
168 }
169
170 int EffectChain_new(lua_State* L)
171 {
172         assert(lua_gettop(L) == 2);
173         Theme *theme = get_theme_updata(L);
174         int aspect_w = luaL_checknumber(L, 1);
175         int aspect_h = luaL_checknumber(L, 2);
176
177         return wrap_lua_object<EffectChain>(L, "EffectChain", aspect_w, aspect_h, theme->get_resource_pool());
178 }
179
180 int EffectChain_gc(lua_State* L)
181 {
182         assert(lua_gettop(L) == 1);
183         EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
184         chain->~EffectChain();
185         return 0;
186 }
187
188 int EffectChain_add_live_input(lua_State* L)
189 {
190         assert(lua_gettop(L) == 3);
191         Theme *theme = get_theme_updata(L);
192         EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
193         bool override_bounce = checkbool(L, 2);
194         bool deinterlace = checkbool(L, 3);
195         return wrap_lua_object<LiveInputWrapper>(L, "LiveInputWrapper", theme, chain, override_bounce, deinterlace);
196 }
197
198 int EffectChain_add_effect(lua_State* L)
199 {
200         assert(lua_gettop(L) >= 2);
201         EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
202
203         // TODO: Better error reporting.
204         Effect *effect = get_effect(L, 2);
205         if (lua_gettop(L) == 2) {
206                 if (effect->num_inputs() == 0) {
207                         chain->add_input((Input *)effect);
208                 } else {
209                         chain->add_effect(effect);
210                 }
211         } else {
212                 vector<Effect *> inputs;
213                 for (int idx = 3; idx <= lua_gettop(L); ++idx) {
214                         if (luaL_testudata(L, idx, "LiveInputWrapper")) {
215                                 LiveInputWrapper *input = (LiveInputWrapper *)lua_touserdata(L, idx);
216                                 inputs.push_back(input->get_effect());
217                         } else {
218                                 inputs.push_back(get_effect(L, idx));
219                         }
220                 }
221                 chain->add_effect(effect, inputs);
222         }
223
224         lua_settop(L, 2);  // Return the effect itself.
225
226         // Make sure Lua doesn't garbage-collect it away.
227         lua_pushvalue(L, -1);
228         luaL_ref(L, LUA_REGISTRYINDEX);  // TODO: leak?
229
230         return 1;
231 }
232
233 int EffectChain_finalize(lua_State* L)
234 {
235         assert(lua_gettop(L) == 2);
236         EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
237         bool is_main_chain = checkbool(L, 2);
238
239         // Add outputs as needed.
240         // NOTE: If you change any details about the output format, you will need to
241         // also update what's given to the muxer (HTTPD::Mux constructor) and
242         // what's put in the H.264 stream (sps_rbsp()).
243         ImageFormat inout_format;
244         inout_format.color_space = COLORSPACE_REC_709;
245
246         // Output gamma is tricky. We should output Rec. 709 for TV, except that
247         // we expect to run with web players and others that don't really care and
248         // just output with no conversion. So that means we'll need to output sRGB,
249         // even though H.264 has no setting for that (we use “unspecified”).
250         inout_format.gamma_curve = GAMMA_sRGB;
251
252         if (is_main_chain) {
253                 YCbCrFormat output_ycbcr_format;
254                 // We actually output 4:2:0 in the end, but chroma subsampling
255                 // happens in a pass not run by Movit (see Mixer::subsample_chroma()).
256                 output_ycbcr_format.chroma_subsampling_x = 1;
257                 output_ycbcr_format.chroma_subsampling_y = 1;
258
259                 // Rec. 709 would be the sane thing to do, but it seems many players
260                 // (e.g. MPlayer and VLC) just default to BT.601 coefficients no matter
261                 // what (see discussions in e.g. https://trac.ffmpeg.org/ticket/4978).
262                 // We _do_ set the right flags, though, so that a player that works
263                 // properly doesn't have to guess.
264                 output_ycbcr_format.luma_coefficients = YCBCR_REC_601;
265                 output_ycbcr_format.full_range = false;
266                 output_ycbcr_format.num_levels = 256;
267
268                 chain->add_ycbcr_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED, output_ycbcr_format, YCBCR_OUTPUT_SPLIT_Y_AND_CBCR);
269                 chain->set_dither_bits(8);
270                 chain->set_output_origin(OUTPUT_ORIGIN_TOP_LEFT);
271         }
272         chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
273
274         chain->finalize();
275         return 0;
276 }
277
278 int LiveInputWrapper_connect_signal(lua_State* L)
279 {
280         assert(lua_gettop(L) == 2);
281         LiveInputWrapper *input = (LiveInputWrapper *)luaL_checkudata(L, 1, "LiveInputWrapper");
282         int signal_num = luaL_checknumber(L, 2);
283         input->connect_signal(signal_num);
284         return 0;
285 }
286
287 int ImageInput_new(lua_State* L)
288 {
289         assert(lua_gettop(L) == 1);
290         string filename = checkstdstring(L, 1);
291         return wrap_lua_object_nonowned<ImageInput>(L, "ImageInput", filename);
292 }
293
294 int WhiteBalanceEffect_new(lua_State* L)
295 {
296         assert(lua_gettop(L) == 0);
297         return wrap_lua_object_nonowned<WhiteBalanceEffect>(L, "WhiteBalanceEffect");
298 }
299
300 int ResampleEffect_new(lua_State* L)
301 {
302         assert(lua_gettop(L) == 0);
303         return wrap_lua_object_nonowned<ResampleEffect>(L, "ResampleEffect");
304 }
305
306 int PaddingEffect_new(lua_State* L)
307 {
308         assert(lua_gettop(L) == 0);
309         return wrap_lua_object_nonowned<PaddingEffect>(L, "PaddingEffect");
310 }
311
312 int IntegralPaddingEffect_new(lua_State* L)
313 {
314         assert(lua_gettop(L) == 0);
315         return wrap_lua_object_nonowned<IntegralPaddingEffect>(L, "IntegralPaddingEffect");
316 }
317
318 int OverlayEffect_new(lua_State* L)
319 {
320         assert(lua_gettop(L) == 0);
321         return wrap_lua_object_nonowned<OverlayEffect>(L, "OverlayEffect");
322 }
323
324 int ResizeEffect_new(lua_State* L)
325 {
326         assert(lua_gettop(L) == 0);
327         return wrap_lua_object_nonowned<ResizeEffect>(L, "ResizeEffect");
328 }
329
330 int MultiplyEffect_new(lua_State* L)
331 {
332         assert(lua_gettop(L) == 0);
333         return wrap_lua_object_nonowned<MultiplyEffect>(L, "MultiplyEffect");
334 }
335
336 int MixEffect_new(lua_State* L)
337 {
338         assert(lua_gettop(L) == 0);
339         return wrap_lua_object_nonowned<MixEffect>(L, "MixEffect");
340 }
341
342 int InputStateInfo_get_width(lua_State* L)
343 {
344         assert(lua_gettop(L) == 2);
345         InputStateInfo *input_state_info = get_input_state_info(L, 1);
346         Theme *theme = get_theme_updata(L);
347         int signal_num = theme->map_signal(luaL_checknumber(L, 2));
348         lua_pushnumber(L, input_state_info->last_width[signal_num]);
349         return 1;
350 }
351
352 int InputStateInfo_get_height(lua_State* L)
353 {
354         assert(lua_gettop(L) == 2);
355         InputStateInfo *input_state_info = get_input_state_info(L, 1);
356         Theme *theme = get_theme_updata(L);
357         int signal_num = theme->map_signal(luaL_checknumber(L, 2));
358         lua_pushnumber(L, input_state_info->last_height[signal_num]);
359         return 1;
360 }
361
362 int InputStateInfo_get_interlaced(lua_State* L)
363 {
364         assert(lua_gettop(L) == 2);
365         InputStateInfo *input_state_info = get_input_state_info(L, 1);
366         Theme *theme = get_theme_updata(L);
367         int signal_num = theme->map_signal(luaL_checknumber(L, 2));
368         lua_pushboolean(L, input_state_info->last_interlaced[signal_num]);
369         return 1;
370 }
371
372 int InputStateInfo_get_has_signal(lua_State* L)
373 {
374         assert(lua_gettop(L) == 2);
375         InputStateInfo *input_state_info = get_input_state_info(L, 1);
376         Theme *theme = get_theme_updata(L);
377         int signal_num = theme->map_signal(luaL_checknumber(L, 2));
378         lua_pushboolean(L, input_state_info->last_has_signal[signal_num]);
379         return 1;
380 }
381
382 int InputStateInfo_get_frame_rate_nom(lua_State* L)
383 {
384         assert(lua_gettop(L) == 2);
385         InputStateInfo *input_state_info = get_input_state_info(L, 1);
386         Theme *theme = get_theme_updata(L);
387         int signal_num = theme->map_signal(luaL_checknumber(L, 2));
388         lua_pushnumber(L, input_state_info->last_frame_rate_nom[signal_num]);
389         return 1;
390 }
391
392 int InputStateInfo_get_frame_rate_den(lua_State* L)
393 {
394         assert(lua_gettop(L) == 2);
395         InputStateInfo *input_state_info = get_input_state_info(L, 1);
396         Theme *theme = get_theme_updata(L);
397         int signal_num = theme->map_signal(luaL_checknumber(L, 2));
398         lua_pushnumber(L, input_state_info->last_frame_rate_den[signal_num]);
399         return 1;
400 }
401
402 int Effect_set_float(lua_State *L)
403 {
404         assert(lua_gettop(L) == 3);
405         Effect *effect = (Effect *)get_effect(L, 1);
406         string key = checkstdstring(L, 2);
407         float value = luaL_checknumber(L, 3);
408         if (!effect->set_float(key, value)) {
409                 luaL_error(L, "Effect refused set_float(\"%s\", %d) (invalid key?)", key.c_str(), int(value));
410         }
411         return 0;
412 }
413
414 int Effect_set_int(lua_State *L)
415 {
416         assert(lua_gettop(L) == 3);
417         Effect *effect = (Effect *)get_effect(L, 1);
418         string key = checkstdstring(L, 2);
419         float value = luaL_checknumber(L, 3);
420         if (!effect->set_int(key, value)) {
421                 luaL_error(L, "Effect refused set_int(\"%s\", %d) (invalid key?)", key.c_str(), int(value));
422         }
423         return 0;
424 }
425
426 int Effect_set_vec3(lua_State *L)
427 {
428         assert(lua_gettop(L) == 5);
429         Effect *effect = (Effect *)get_effect(L, 1);
430         string key = checkstdstring(L, 2);
431         float v[3];
432         v[0] = luaL_checknumber(L, 3);
433         v[1] = luaL_checknumber(L, 4);
434         v[2] = luaL_checknumber(L, 5);
435         if (!effect->set_vec3(key, v)) {
436                 luaL_error(L, "Effect refused set_vec3(\"%s\", %f, %f, %f) (invalid key?)", key.c_str(),
437                         v[0], v[1], v[2]);
438         }
439         return 0;
440 }
441
442 int Effect_set_vec4(lua_State *L)
443 {
444         assert(lua_gettop(L) == 6);
445         Effect *effect = (Effect *)get_effect(L, 1);
446         string key = checkstdstring(L, 2);
447         float v[4];
448         v[0] = luaL_checknumber(L, 3);
449         v[1] = luaL_checknumber(L, 4);
450         v[2] = luaL_checknumber(L, 5);
451         v[3] = luaL_checknumber(L, 6);
452         if (!effect->set_vec4(key, v)) {
453                 luaL_error(L, "Effect refused set_vec4(\"%s\", %f, %f, %f, %f) (invalid key?)", key.c_str(),
454                         v[0], v[1], v[2], v[3]);
455         }
456         return 0;
457 }
458
459 const luaL_Reg EffectChain_funcs[] = {
460         { "new", EffectChain_new },
461         { "__gc", EffectChain_gc },
462         { "add_live_input", EffectChain_add_live_input },
463         { "add_effect", EffectChain_add_effect },
464         { "finalize", EffectChain_finalize },
465         { NULL, NULL }
466 };
467
468 const luaL_Reg LiveInputWrapper_funcs[] = {
469         { "connect_signal", LiveInputWrapper_connect_signal },
470         { NULL, NULL }
471 };
472
473 const luaL_Reg ImageInput_funcs[] = {
474         { "new", ImageInput_new },
475         { "set_float", Effect_set_float },
476         { "set_int", Effect_set_int },
477         { "set_vec3", Effect_set_vec3 },
478         { "set_vec4", Effect_set_vec4 },
479         { NULL, NULL }
480 };
481
482 const luaL_Reg WhiteBalanceEffect_funcs[] = {
483         { "new", WhiteBalanceEffect_new },
484         { "set_float", Effect_set_float },
485         { "set_int", Effect_set_int },
486         { "set_vec3", Effect_set_vec3 },
487         { "set_vec4", Effect_set_vec4 },
488         { NULL, NULL }
489 };
490
491 const luaL_Reg ResampleEffect_funcs[] = {
492         { "new", ResampleEffect_new },
493         { "set_float", Effect_set_float },
494         { "set_int", Effect_set_int },
495         { "set_vec3", Effect_set_vec3 },
496         { "set_vec4", Effect_set_vec4 },
497         { NULL, NULL }
498 };
499
500 const luaL_Reg PaddingEffect_funcs[] = {
501         { "new", PaddingEffect_new },
502         { "set_float", Effect_set_float },
503         { "set_int", Effect_set_int },
504         { "set_vec3", Effect_set_vec3 },
505         { "set_vec4", Effect_set_vec4 },
506         { NULL, NULL }
507 };
508
509 const luaL_Reg IntegralPaddingEffect_funcs[] = {
510         { "new", IntegralPaddingEffect_new },
511         { "set_float", Effect_set_float },
512         { "set_int", Effect_set_int },
513         { "set_vec3", Effect_set_vec3 },
514         { "set_vec4", Effect_set_vec4 },
515         { NULL, NULL }
516 };
517
518 const luaL_Reg OverlayEffect_funcs[] = {
519         { "new", OverlayEffect_new },
520         { "set_float", Effect_set_float },
521         { "set_int", Effect_set_int },
522         { "set_vec3", Effect_set_vec3 },
523         { "set_vec4", Effect_set_vec4 },
524         { NULL, NULL }
525 };
526
527 const luaL_Reg ResizeEffect_funcs[] = {
528         { "new", ResizeEffect_new },
529         { "set_float", Effect_set_float },
530         { "set_int", Effect_set_int },
531         { "set_vec3", Effect_set_vec3 },
532         { "set_vec4", Effect_set_vec4 },
533         { NULL, NULL }
534 };
535
536 const luaL_Reg MultiplyEffect_funcs[] = {
537         { "new", MultiplyEffect_new },
538         { "set_float", Effect_set_float },
539         { "set_int", Effect_set_int },
540         { "set_vec3", Effect_set_vec3 },
541         { "set_vec4", Effect_set_vec4 },
542         { NULL, NULL }
543 };
544
545 const luaL_Reg MixEffect_funcs[] = {
546         { "new", MixEffect_new },
547         { "set_float", Effect_set_float },
548         { "set_int", Effect_set_int },
549         { "set_vec3", Effect_set_vec3 },
550         { "set_vec4", Effect_set_vec4 },
551         { NULL, NULL }
552 };
553
554 const luaL_Reg InputStateInfo_funcs[] = {
555         { "get_width", InputStateInfo_get_width },
556         { "get_height", InputStateInfo_get_height },
557         { "get_interlaced", InputStateInfo_get_interlaced },
558         { "get_has_signal", InputStateInfo_get_has_signal },
559         { "get_frame_rate_nom", InputStateInfo_get_frame_rate_nom },
560         { "get_frame_rate_den", InputStateInfo_get_frame_rate_den },
561         { NULL, NULL }
562 };
563
564 }  // namespace
565
566 LiveInputWrapper::LiveInputWrapper(Theme *theme, EffectChain *chain, bool override_bounce, bool deinterlace)
567         : theme(theme),
568           deinterlace(deinterlace)
569 {
570         ImageFormat inout_format;
571         inout_format.color_space = COLORSPACE_sRGB;
572
573         // Gamma curve depends on the input signal, and we don't really get any
574         // indications. A camera would be expected to do Rec. 709, but
575         // I haven't checked if any do in practice. However, computers _do_ output
576         // in sRGB gamma (ie., they don't convert from sRGB to Rec. 709), and
577         // I wouldn't really be surprised if most non-professional cameras do, too.
578         // So we pick sRGB as the least evil here.
579         inout_format.gamma_curve = GAMMA_sRGB;
580
581         // The Blackmagic driver docs claim that the device outputs Y'CbCr
582         // according to Rec. 601, but practical testing indicates it definitely
583         // is Rec. 709 (at least up to errors attributable to rounding errors).
584         // Perhaps 601 was only to indicate the subsampling positions, not the
585         // colorspace itself? Tested with a Lenovo X1 gen 3 as input.
586         YCbCrFormat input_ycbcr_format;
587         input_ycbcr_format.chroma_subsampling_x = 2;
588         input_ycbcr_format.chroma_subsampling_y = 1;
589         input_ycbcr_format.cb_x_position = 0.0;
590         input_ycbcr_format.cr_x_position = 0.0;
591         input_ycbcr_format.cb_y_position = 0.5;
592         input_ycbcr_format.cr_y_position = 0.5;
593         input_ycbcr_format.luma_coefficients = YCBCR_REC_709;
594         input_ycbcr_format.full_range = false;
595
596         unsigned num_inputs;
597         if (deinterlace) {
598                 deinterlace_effect = new movit::DeinterlaceEffect();
599
600                 // As per the comments in deinterlace_effect.h, we turn this off.
601                 // The most likely interlaced input for us is either a camera
602                 // (where it's fine to turn it off) or a laptop (where it _should_
603                 // be turned off).
604                 CHECK(deinterlace_effect->set_int("enable_spatial_interlacing_check", 0));
605
606                 num_inputs = deinterlace_effect->num_inputs();
607                 assert(num_inputs == FRAME_HISTORY_LENGTH);
608         } else {
609                 num_inputs = 1;
610         }
611         for (unsigned i = 0; i < num_inputs; ++i) {
612                 if (override_bounce) {
613                         inputs.push_back(new NonBouncingYCbCrInput(inout_format, input_ycbcr_format, WIDTH, HEIGHT, YCBCR_INPUT_SPLIT_Y_AND_CBCR));
614                 } else {
615                         inputs.push_back(new YCbCrInput(inout_format, input_ycbcr_format, WIDTH, HEIGHT, YCBCR_INPUT_SPLIT_Y_AND_CBCR));
616                 }
617                 chain->add_input(inputs.back());
618         }
619
620         if (deinterlace) {
621                 vector<Effect *> reverse_inputs(inputs.rbegin(), inputs.rend());
622                 chain->add_effect(deinterlace_effect, reverse_inputs);
623         }
624 }
625
626 void LiveInputWrapper::connect_signal(int signal_num)
627 {
628         if (global_mixer == nullptr) {
629                 // No data yet.
630                 return;
631         }
632
633         signal_num = theme->map_signal(signal_num);
634
635         BufferedFrame first_frame = theme->input_state->buffered_frames[signal_num][0];
636         if (first_frame.frame == nullptr) {
637                 // No data yet.
638                 return;
639         }
640         unsigned width, height;
641         {
642                 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)first_frame.frame->userdata;
643                 width = userdata->last_width[first_frame.field_number];
644                 height = userdata->last_height[first_frame.field_number];
645         }
646
647         BufferedFrame last_good_frame = first_frame;
648         for (unsigned i = 0; i < inputs.size(); ++i) {
649                 BufferedFrame frame = theme->input_state->buffered_frames[signal_num][i];
650                 if (frame.frame == nullptr) {
651                         // Not enough data; reuse last frame (well, field).
652                         // This is suboptimal, but we have nothing better.
653                         frame = last_good_frame;
654                 }
655                 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
656
657                 if (userdata->last_width[frame.field_number] != width ||
658                     userdata->last_height[frame.field_number] != height) {
659                         // Resolution changed; reuse last frame/field.
660                         frame = last_good_frame;
661                         userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
662                 }
663
664                 inputs[i]->set_texture_num(0, userdata->tex_y[frame.field_number]);
665                 inputs[i]->set_texture_num(1, userdata->tex_cbcr[frame.field_number]);
666                 inputs[i]->set_width(userdata->last_width[frame.field_number]);
667                 inputs[i]->set_height(userdata->last_height[frame.field_number]);
668
669                 last_good_frame = frame;
670         }
671
672         if (deinterlace) {
673                 BufferedFrame frame = theme->input_state->buffered_frames[signal_num][0];
674                 CHECK(deinterlace_effect->set_int("current_field_position", frame.field_number));
675         }
676 }
677
678 namespace {
679
680 int call_num_channels(lua_State *L)
681 {
682         lua_getglobal(L, "num_channels");
683
684         if (lua_pcall(L, 0, 1, 0) != 0) {
685                 fprintf(stderr, "error running function `num_channels': %s\n", lua_tostring(L, -1));
686                 exit(1);
687         }
688
689         int num_channels = luaL_checknumber(L, 1);
690         lua_pop(L, 1);
691         assert(lua_gettop(L) == 0);
692         return num_channels;
693 }
694
695 }  // namespace
696
697 Theme::Theme(const char *filename, ResourcePool *resource_pool, unsigned num_cards)
698         : resource_pool(resource_pool), num_cards(num_cards)
699 {
700         L = luaL_newstate();
701         luaL_openlibs(L);
702
703         register_class("EffectChain", EffectChain_funcs); 
704         register_class("LiveInputWrapper", LiveInputWrapper_funcs); 
705         register_class("ImageInput", ImageInput_funcs);
706         register_class("WhiteBalanceEffect", WhiteBalanceEffect_funcs);
707         register_class("ResampleEffect", ResampleEffect_funcs);
708         register_class("PaddingEffect", PaddingEffect_funcs);
709         register_class("IntegralPaddingEffect", IntegralPaddingEffect_funcs);
710         register_class("OverlayEffect", OverlayEffect_funcs);
711         register_class("ResizeEffect", ResizeEffect_funcs);
712         register_class("MultiplyEffect", MultiplyEffect_funcs);
713         register_class("MixEffect", MixEffect_funcs);
714         register_class("InputStateInfo", InputStateInfo_funcs);
715
716         // Run script.
717         lua_settop(L, 0);
718         if (luaL_dofile(L, filename)) {
719                 fprintf(stderr, "error: %s\n", lua_tostring(L, -1));
720                 lua_pop(L, 1);
721                 exit(1);
722         }
723         assert(lua_gettop(L) == 0);
724
725         // Ask it for the number of channels.
726         num_channels = call_num_channels(L);
727 }
728
729 Theme::~Theme()
730 {
731         lua_close(L);
732 }
733
734 void Theme::register_class(const char *class_name, const luaL_Reg *funcs)
735 {
736         assert(lua_gettop(L) == 0);
737         luaL_newmetatable(L, class_name);  // mt = {}
738         lua_pushlightuserdata(L, this);
739         luaL_setfuncs(L, funcs, 1);        // for (name,f in funcs) { mt[name] = f, with upvalue {theme} }
740         lua_pushvalue(L, -1);
741         lua_setfield(L, -2, "__index");    // mt.__index = mt
742         lua_setglobal(L, class_name);      // ClassName = mt
743         assert(lua_gettop(L) == 0);
744 }
745
746 Theme::Chain Theme::get_chain(unsigned num, float t, unsigned width, unsigned height, InputState input_state) 
747 {
748         Chain chain;
749
750         unique_lock<mutex> lock(m);
751         assert(lua_gettop(L) == 0);
752         lua_getglobal(L, "get_chain");  /* function to be called */
753         lua_pushnumber(L, num);
754         lua_pushnumber(L, t);
755         lua_pushnumber(L, width);
756         lua_pushnumber(L, height);
757         wrap_lua_object<InputStateInfo>(L, "InputStateInfo", input_state);
758
759         if (lua_pcall(L, 5, 2, 0) != 0) {
760                 fprintf(stderr, "error running function `get_chain': %s\n", lua_tostring(L, -1));
761                 exit(1);
762         }
763
764         chain.chain = (EffectChain *)luaL_checkudata(L, -2, "EffectChain");
765         if (!lua_isfunction(L, -1)) {
766                 fprintf(stderr, "Argument #-1 should be a function\n");
767                 exit(1);
768         }
769         lua_pushvalue(L, -1);
770         shared_ptr<LuaRefWithDeleter> funcref(new LuaRefWithDeleter(&m, L, luaL_ref(L, LUA_REGISTRYINDEX)));
771         lua_pop(L, 2);
772         assert(lua_gettop(L) == 0);
773
774         chain.setup_chain = [this, funcref, input_state]{
775                 unique_lock<mutex> lock(m);
776
777                 this->input_state = &input_state;
778
779                 // Set up state, including connecting signals.
780                 lua_rawgeti(L, LUA_REGISTRYINDEX, funcref->get());
781                 if (lua_pcall(L, 0, 0, 0) != 0) {
782                         fprintf(stderr, "error running chain setup callback: %s\n", lua_tostring(L, -1));
783                         exit(1);
784                 }
785                 assert(lua_gettop(L) == 0);
786         };
787
788         // TODO: Can we do better, e.g. by running setup_chain() and seeing what it references?
789         // Actually, setup_chain does maybe hold all the references we need now anyway?
790         for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
791                 for (unsigned frame_num = 0; frame_num < FRAME_HISTORY_LENGTH; ++frame_num) {
792                         chain.input_frames.push_back(input_state.buffered_frames[card_index][frame_num].frame);
793                 }
794         }
795
796         return chain;
797 }
798
799 string Theme::get_channel_name(unsigned channel)
800 {
801         unique_lock<mutex> lock(m);
802         lua_getglobal(L, "channel_name");
803         lua_pushnumber(L, channel);
804         if (lua_pcall(L, 1, 1, 0) != 0) {
805                 fprintf(stderr, "error running function `channel_name': %s\n", lua_tostring(L, -1));
806                 exit(1);
807         }
808
809         string ret = lua_tostring(L, -1);
810         lua_pop(L, 1);
811         assert(lua_gettop(L) == 0);
812         return ret;
813 }
814
815 int Theme::get_channel_signal(unsigned channel)
816 {
817         unique_lock<mutex> lock(m);
818         lua_getglobal(L, "channel_signal");
819         lua_pushnumber(L, channel);
820         if (lua_pcall(L, 1, 1, 0) != 0) {
821                 fprintf(stderr, "error running function `channel_signal': %s\n", lua_tostring(L, -1));
822                 exit(1);
823         }
824
825         int ret = luaL_checknumber(L, 1);
826         lua_pop(L, 1);
827         assert(lua_gettop(L) == 0);
828         return ret;
829 }
830
831 std::string Theme::get_channel_color(unsigned channel)
832 {
833         unique_lock<mutex> lock(m);
834         lua_getglobal(L, "channel_color");
835         lua_pushnumber(L, channel);
836         if (lua_pcall(L, 1, 1, 0) != 0) {
837                 fprintf(stderr, "error running function `channel_color': %s\n", lua_tostring(L, -1));
838                 exit(1);
839         }
840
841         std::string ret = checkstdstring(L, -1);
842         lua_pop(L, 1);
843         assert(lua_gettop(L) == 0);
844         return ret;
845 }
846
847 bool Theme::get_supports_set_wb(unsigned channel)
848 {
849         unique_lock<mutex> lock(m);
850         lua_getglobal(L, "supports_set_wb");
851         lua_pushnumber(L, channel);
852         if (lua_pcall(L, 1, 1, 0) != 0) {
853                 fprintf(stderr, "error running function `supports_set_wb': %s\n", lua_tostring(L, -1));
854                 exit(1);
855         }
856
857         bool ret = checkbool(L, -1);
858         lua_pop(L, 1);
859         assert(lua_gettop(L) == 0);
860         return ret;
861 }
862
863 void Theme::set_wb(unsigned channel, double r, double g, double b)
864 {
865         unique_lock<mutex> lock(m);
866         lua_getglobal(L, "set_wb");
867         lua_pushnumber(L, channel);
868         lua_pushnumber(L, r);
869         lua_pushnumber(L, g);
870         lua_pushnumber(L, b);
871         if (lua_pcall(L, 4, 0, 0) != 0) {
872                 fprintf(stderr, "error running function `set_wb': %s\n", lua_tostring(L, -1));
873                 exit(1);
874         }
875
876         assert(lua_gettop(L) == 0);
877 }
878
879 vector<string> Theme::get_transition_names(float t)
880 {
881         unique_lock<mutex> lock(m);
882         lua_getglobal(L, "get_transitions");
883         lua_pushnumber(L, t);
884         if (lua_pcall(L, 1, 1, 0) != 0) {
885                 fprintf(stderr, "error running function `get_transitions': %s\n", lua_tostring(L, -1));
886                 exit(1);
887         }
888
889         vector<string> ret;
890         lua_pushnil(L);
891         while (lua_next(L, -2) != 0) {
892                 ret.push_back(lua_tostring(L, -1));
893                 lua_pop(L, 1);
894         }
895         lua_pop(L, 1);
896         assert(lua_gettop(L) == 0);
897         return ret;
898 }       
899
900 int Theme::map_signal(int signal_num)
901 {
902         unique_lock<mutex> lock(map_m);
903         if (signal_to_card_mapping.count(signal_num)) {
904                 return signal_to_card_mapping[signal_num];
905         }
906         if (signal_num >= int(num_cards)) {
907                 fprintf(stderr, "WARNING: Theme asked for input %d, but we only have %u card(s).\n", signal_num, num_cards);
908                 fprintf(stderr, "Mapping to card %d instead.\n", signal_num % num_cards);
909         }
910         signal_to_card_mapping[signal_num] = signal_num % num_cards;
911         return signal_num % num_cards;
912 }
913
914 void Theme::set_signal_mapping(int signal_num, int card_num)
915 {
916         unique_lock<mutex> lock(map_m);
917         assert(card_num < int(num_cards));
918         signal_to_card_mapping[signal_num] = card_num;
919 }
920
921 void Theme::transition_clicked(int transition_num, float t)
922 {
923         unique_lock<mutex> lock(m);
924         lua_getglobal(L, "transition_clicked");
925         lua_pushnumber(L, transition_num);
926         lua_pushnumber(L, t);
927
928         if (lua_pcall(L, 2, 0, 0) != 0) {
929                 fprintf(stderr, "error running function `transition_clicked': %s\n", lua_tostring(L, -1));
930                 exit(1);
931         }
932         assert(lua_gettop(L) == 0);
933 }
934
935 void Theme::channel_clicked(int preview_num)
936 {
937         unique_lock<mutex> lock(m);
938         lua_getglobal(L, "channel_clicked");
939         lua_pushnumber(L, preview_num);
940
941         if (lua_pcall(L, 1, 0, 0) != 0) {
942                 fprintf(stderr, "error running function `channel_clicked': %s\n", lua_tostring(L, -1));
943                 exit(1);
944         }
945         assert(lua_gettop(L) == 0);
946 }