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