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