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