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