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