]> git.sesse.net Git - nageru/blob - theme.cpp
Write 1.4.0 changelog.
[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 in the end, but chroma subsampling
265                 // happens in a pass not run by Movit (see Mixer::subsample_chroma()).
266                 output_ycbcr_format.chroma_subsampling_x = 1;
267                 output_ycbcr_format.chroma_subsampling_y = 1;
268
269                 // Rec. 709 would be the sane thing to do, but it seems many players
270                 // (e.g. MPlayer and VLC) just default to BT.601 coefficients no matter
271                 // what (see discussions in e.g. https://trac.ffmpeg.org/ticket/4978).
272                 // We _do_ set the right flags, though, so that a player that works
273                 // properly doesn't have to guess.
274                 output_ycbcr_format.luma_coefficients = YCBCR_REC_601;
275                 output_ycbcr_format.full_range = false;
276                 output_ycbcr_format.num_levels = 256;
277
278                 chain->add_ycbcr_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED, output_ycbcr_format, YCBCR_OUTPUT_SPLIT_Y_AND_CBCR);
279                 chain->set_dither_bits(8);
280                 chain->set_output_origin(OUTPUT_ORIGIN_TOP_LEFT);
281         }
282         chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
283
284         chain->finalize();
285         return 0;
286 }
287
288 int LiveInputWrapper_connect_signal(lua_State* L)
289 {
290         assert(lua_gettop(L) == 2);
291         LiveInputWrapper *input = (LiveInputWrapper *)luaL_checkudata(L, 1, "LiveInputWrapper");
292         int signal_num = luaL_checknumber(L, 2);
293         input->connect_signal(signal_num);
294         return 0;
295 }
296
297 int ImageInput_new(lua_State* L)
298 {
299         assert(lua_gettop(L) == 1);
300         string filename = checkstdstring(L, 1);
301         return wrap_lua_object_nonowned<ImageInput>(L, "ImageInput", filename);
302 }
303
304 int WhiteBalanceEffect_new(lua_State* L)
305 {
306         assert(lua_gettop(L) == 0);
307         return wrap_lua_object_nonowned<WhiteBalanceEffect>(L, "WhiteBalanceEffect");
308 }
309
310 int ResampleEffect_new(lua_State* L)
311 {
312         assert(lua_gettop(L) == 0);
313         return wrap_lua_object_nonowned<ResampleEffect>(L, "ResampleEffect");
314 }
315
316 int PaddingEffect_new(lua_State* L)
317 {
318         assert(lua_gettop(L) == 0);
319         return wrap_lua_object_nonowned<PaddingEffect>(L, "PaddingEffect");
320 }
321
322 int IntegralPaddingEffect_new(lua_State* L)
323 {
324         assert(lua_gettop(L) == 0);
325         return wrap_lua_object_nonowned<IntegralPaddingEffect>(L, "IntegralPaddingEffect");
326 }
327
328 int OverlayEffect_new(lua_State* L)
329 {
330         assert(lua_gettop(L) == 0);
331         return wrap_lua_object_nonowned<OverlayEffect>(L, "OverlayEffect");
332 }
333
334 int ResizeEffect_new(lua_State* L)
335 {
336         assert(lua_gettop(L) == 0);
337         return wrap_lua_object_nonowned<ResizeEffect>(L, "ResizeEffect");
338 }
339
340 int MultiplyEffect_new(lua_State* L)
341 {
342         assert(lua_gettop(L) == 0);
343         return wrap_lua_object_nonowned<MultiplyEffect>(L, "MultiplyEffect");
344 }
345
346 int MixEffect_new(lua_State* L)
347 {
348         assert(lua_gettop(L) == 0);
349         return wrap_lua_object_nonowned<MixEffect>(L, "MixEffect");
350 }
351
352 int InputStateInfo_get_width(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_pushnumber(L, input_state_info->last_width[signal_num]);
359         return 1;
360 }
361
362 int InputStateInfo_get_height(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_height[signal_num]);
369         return 1;
370 }
371
372 int InputStateInfo_get_interlaced(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_pushboolean(L, input_state_info->last_interlaced[signal_num]);
379         return 1;
380 }
381
382 int InputStateInfo_get_has_signal(lua_State* L)
383 {
384         assert(lua_gettop(L) == 2);
385         InputStateInfo *input_state_info = get_input_state_info(L, 1);
386         Theme *theme = get_theme_updata(L);
387         int signal_num = theme->map_signal(luaL_checknumber(L, 2));
388         lua_pushboolean(L, input_state_info->last_has_signal[signal_num]);
389         return 1;
390 }
391
392 int InputStateInfo_get_is_connected(lua_State* L)
393 {
394         assert(lua_gettop(L) == 2);
395         InputStateInfo *input_state_info = get_input_state_info(L, 1);
396         Theme *theme = get_theme_updata(L);
397         int signal_num = theme->map_signal(luaL_checknumber(L, 2));
398         lua_pushboolean(L, input_state_info->last_is_connected[signal_num]);
399         return 1;
400 }
401
402 int InputStateInfo_get_frame_rate_nom(lua_State* L)
403 {
404         assert(lua_gettop(L) == 2);
405         InputStateInfo *input_state_info = get_input_state_info(L, 1);
406         Theme *theme = get_theme_updata(L);
407         int signal_num = theme->map_signal(luaL_checknumber(L, 2));
408         lua_pushnumber(L, input_state_info->last_frame_rate_nom[signal_num]);
409         return 1;
410 }
411
412 int InputStateInfo_get_frame_rate_den(lua_State* L)
413 {
414         assert(lua_gettop(L) == 2);
415         InputStateInfo *input_state_info = get_input_state_info(L, 1);
416         Theme *theme = get_theme_updata(L);
417         int signal_num = theme->map_signal(luaL_checknumber(L, 2));
418         lua_pushnumber(L, input_state_info->last_frame_rate_den[signal_num]);
419         return 1;
420 }
421
422 int Effect_set_float(lua_State *L)
423 {
424         assert(lua_gettop(L) == 3);
425         Effect *effect = (Effect *)get_effect(L, 1);
426         string key = checkstdstring(L, 2);
427         float value = luaL_checknumber(L, 3);
428         if (!effect->set_float(key, value)) {
429                 luaL_error(L, "Effect refused set_float(\"%s\", %d) (invalid key?)", key.c_str(), int(value));
430         }
431         return 0;
432 }
433
434 int Effect_set_int(lua_State *L)
435 {
436         assert(lua_gettop(L) == 3);
437         Effect *effect = (Effect *)get_effect(L, 1);
438         string key = checkstdstring(L, 2);
439         float value = luaL_checknumber(L, 3);
440         if (!effect->set_int(key, value)) {
441                 luaL_error(L, "Effect refused set_int(\"%s\", %d) (invalid key?)", key.c_str(), int(value));
442         }
443         return 0;
444 }
445
446 int Effect_set_vec3(lua_State *L)
447 {
448         assert(lua_gettop(L) == 5);
449         Effect *effect = (Effect *)get_effect(L, 1);
450         string key = checkstdstring(L, 2);
451         float v[3];
452         v[0] = luaL_checknumber(L, 3);
453         v[1] = luaL_checknumber(L, 4);
454         v[2] = luaL_checknumber(L, 5);
455         if (!effect->set_vec3(key, v)) {
456                 luaL_error(L, "Effect refused set_vec3(\"%s\", %f, %f, %f) (invalid key?)", key.c_str(),
457                         v[0], v[1], v[2]);
458         }
459         return 0;
460 }
461
462 int Effect_set_vec4(lua_State *L)
463 {
464         assert(lua_gettop(L) == 6);
465         Effect *effect = (Effect *)get_effect(L, 1);
466         string key = checkstdstring(L, 2);
467         float v[4];
468         v[0] = luaL_checknumber(L, 3);
469         v[1] = luaL_checknumber(L, 4);
470         v[2] = luaL_checknumber(L, 5);
471         v[3] = luaL_checknumber(L, 6);
472         if (!effect->set_vec4(key, v)) {
473                 luaL_error(L, "Effect refused set_vec4(\"%s\", %f, %f, %f, %f) (invalid key?)", key.c_str(),
474                         v[0], v[1], v[2], v[3]);
475         }
476         return 0;
477 }
478
479 const luaL_Reg EffectChain_funcs[] = {
480         { "new", EffectChain_new },
481         { "__gc", EffectChain_gc },
482         { "add_live_input", EffectChain_add_live_input },
483         { "add_effect", EffectChain_add_effect },
484         { "finalize", EffectChain_finalize },
485         { NULL, NULL }
486 };
487
488 const luaL_Reg LiveInputWrapper_funcs[] = {
489         { "connect_signal", LiveInputWrapper_connect_signal },
490         { NULL, NULL }
491 };
492
493 const luaL_Reg ImageInput_funcs[] = {
494         { "new", ImageInput_new },
495         { "set_float", Effect_set_float },
496         { "set_int", Effect_set_int },
497         { "set_vec3", Effect_set_vec3 },
498         { "set_vec4", Effect_set_vec4 },
499         { NULL, NULL }
500 };
501
502 const luaL_Reg WhiteBalanceEffect_funcs[] = {
503         { "new", WhiteBalanceEffect_new },
504         { "set_float", Effect_set_float },
505         { "set_int", Effect_set_int },
506         { "set_vec3", Effect_set_vec3 },
507         { "set_vec4", Effect_set_vec4 },
508         { NULL, NULL }
509 };
510
511 const luaL_Reg ResampleEffect_funcs[] = {
512         { "new", ResampleEffect_new },
513         { "set_float", Effect_set_float },
514         { "set_int", Effect_set_int },
515         { "set_vec3", Effect_set_vec3 },
516         { "set_vec4", Effect_set_vec4 },
517         { NULL, NULL }
518 };
519
520 const luaL_Reg PaddingEffect_funcs[] = {
521         { "new", PaddingEffect_new },
522         { "set_float", Effect_set_float },
523         { "set_int", Effect_set_int },
524         { "set_vec3", Effect_set_vec3 },
525         { "set_vec4", Effect_set_vec4 },
526         { NULL, NULL }
527 };
528
529 const luaL_Reg IntegralPaddingEffect_funcs[] = {
530         { "new", IntegralPaddingEffect_new },
531         { "set_float", Effect_set_float },
532         { "set_int", Effect_set_int },
533         { "set_vec3", Effect_set_vec3 },
534         { "set_vec4", Effect_set_vec4 },
535         { NULL, NULL }
536 };
537
538 const luaL_Reg OverlayEffect_funcs[] = {
539         { "new", OverlayEffect_new },
540         { "set_float", Effect_set_float },
541         { "set_int", Effect_set_int },
542         { "set_vec3", Effect_set_vec3 },
543         { "set_vec4", Effect_set_vec4 },
544         { NULL, NULL }
545 };
546
547 const luaL_Reg ResizeEffect_funcs[] = {
548         { "new", ResizeEffect_new },
549         { "set_float", Effect_set_float },
550         { "set_int", Effect_set_int },
551         { "set_vec3", Effect_set_vec3 },
552         { "set_vec4", Effect_set_vec4 },
553         { NULL, NULL }
554 };
555
556 const luaL_Reg MultiplyEffect_funcs[] = {
557         { "new", MultiplyEffect_new },
558         { "set_float", Effect_set_float },
559         { "set_int", Effect_set_int },
560         { "set_vec3", Effect_set_vec3 },
561         { "set_vec4", Effect_set_vec4 },
562         { NULL, NULL }
563 };
564
565 const luaL_Reg MixEffect_funcs[] = {
566         { "new", MixEffect_new },
567         { "set_float", Effect_set_float },
568         { "set_int", Effect_set_int },
569         { "set_vec3", Effect_set_vec3 },
570         { "set_vec4", Effect_set_vec4 },
571         { NULL, NULL }
572 };
573
574 const luaL_Reg InputStateInfo_funcs[] = {
575         { "get_width", InputStateInfo_get_width },
576         { "get_height", InputStateInfo_get_height },
577         { "get_interlaced", InputStateInfo_get_interlaced },
578         { "get_has_signal", InputStateInfo_get_has_signal },
579         { "get_is_connected", InputStateInfo_get_is_connected },
580         { "get_frame_rate_nom", InputStateInfo_get_frame_rate_nom },
581         { "get_frame_rate_den", InputStateInfo_get_frame_rate_den },
582         { NULL, NULL }
583 };
584
585 }  // namespace
586
587 LiveInputWrapper::LiveInputWrapper(Theme *theme, EffectChain *chain, bool override_bounce, bool deinterlace)
588         : theme(theme),
589           deinterlace(deinterlace)
590 {
591         ImageFormat inout_format;
592         inout_format.color_space = COLORSPACE_sRGB;
593
594         // Gamma curve depends on the input signal, and we don't really get any
595         // indications. A camera would be expected to do Rec. 709, but
596         // I haven't checked if any do in practice. However, computers _do_ output
597         // in sRGB gamma (ie., they don't convert from sRGB to Rec. 709), and
598         // I wouldn't really be surprised if most non-professional cameras do, too.
599         // So we pick sRGB as the least evil here.
600         inout_format.gamma_curve = GAMMA_sRGB;
601
602         // The Blackmagic driver docs claim that the device outputs Y'CbCr
603         // according to Rec. 601, but practical testing indicates it definitely
604         // is Rec. 709 (at least up to errors attributable to rounding errors).
605         // Perhaps 601 was only to indicate the subsampling positions, not the
606         // colorspace itself? Tested with a Lenovo X1 gen 3 as input.
607         YCbCrFormat input_ycbcr_format;
608         input_ycbcr_format.chroma_subsampling_x = 2;
609         input_ycbcr_format.chroma_subsampling_y = 1;
610         input_ycbcr_format.cb_x_position = 0.0;
611         input_ycbcr_format.cr_x_position = 0.0;
612         input_ycbcr_format.cb_y_position = 0.5;
613         input_ycbcr_format.cr_y_position = 0.5;
614         input_ycbcr_format.luma_coefficients = YCBCR_REC_709;
615         input_ycbcr_format.full_range = false;
616
617         unsigned num_inputs;
618         if (deinterlace) {
619                 deinterlace_effect = new movit::DeinterlaceEffect();
620
621                 // As per the comments in deinterlace_effect.h, we turn this off.
622                 // The most likely interlaced input for us is either a camera
623                 // (where it's fine to turn it off) or a laptop (where it _should_
624                 // be turned off).
625                 CHECK(deinterlace_effect->set_int("enable_spatial_interlacing_check", 0));
626
627                 num_inputs = deinterlace_effect->num_inputs();
628                 assert(num_inputs == FRAME_HISTORY_LENGTH);
629         } else {
630                 num_inputs = 1;
631         }
632         for (unsigned i = 0; i < num_inputs; ++i) {
633                 if (override_bounce) {
634                         inputs.push_back(new NonBouncingYCbCrInput(inout_format, input_ycbcr_format, WIDTH, HEIGHT, YCBCR_INPUT_SPLIT_Y_AND_CBCR));
635                 } else {
636                         inputs.push_back(new YCbCrInput(inout_format, input_ycbcr_format, WIDTH, HEIGHT, YCBCR_INPUT_SPLIT_Y_AND_CBCR));
637                 }
638                 chain->add_input(inputs.back());
639         }
640
641         if (deinterlace) {
642                 vector<Effect *> reverse_inputs(inputs.rbegin(), inputs.rend());
643                 chain->add_effect(deinterlace_effect, reverse_inputs);
644         }
645 }
646
647 void LiveInputWrapper::connect_signal(int signal_num)
648 {
649         if (global_mixer == nullptr) {
650                 // No data yet.
651                 return;
652         }
653
654         signal_num = theme->map_signal(signal_num);
655
656         BufferedFrame first_frame = theme->input_state->buffered_frames[signal_num][0];
657         if (first_frame.frame == nullptr) {
658                 // No data yet.
659                 return;
660         }
661         unsigned width, height;
662         {
663                 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)first_frame.frame->userdata;
664                 width = userdata->last_width[first_frame.field_number];
665                 height = userdata->last_height[first_frame.field_number];
666         }
667
668         BufferedFrame last_good_frame = first_frame;
669         for (unsigned i = 0; i < inputs.size(); ++i) {
670                 BufferedFrame frame = theme->input_state->buffered_frames[signal_num][i];
671                 if (frame.frame == nullptr) {
672                         // Not enough data; reuse last frame (well, field).
673                         // This is suboptimal, but we have nothing better.
674                         frame = last_good_frame;
675                 }
676                 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
677
678                 if (userdata->last_width[frame.field_number] != width ||
679                     userdata->last_height[frame.field_number] != height) {
680                         // Resolution changed; reuse last frame/field.
681                         frame = last_good_frame;
682                         userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
683                 }
684
685                 inputs[i]->set_texture_num(0, userdata->tex_y[frame.field_number]);
686                 inputs[i]->set_texture_num(1, userdata->tex_cbcr[frame.field_number]);
687                 inputs[i]->set_width(userdata->last_width[frame.field_number]);
688                 inputs[i]->set_height(userdata->last_height[frame.field_number]);
689
690                 last_good_frame = frame;
691         }
692
693         if (deinterlace) {
694                 BufferedFrame frame = theme->input_state->buffered_frames[signal_num][0];
695                 CHECK(deinterlace_effect->set_int("current_field_position", frame.field_number));
696         }
697 }
698
699 namespace {
700
701 int call_num_channels(lua_State *L)
702 {
703         lua_getglobal(L, "num_channels");
704
705         if (lua_pcall(L, 0, 1, 0) != 0) {
706                 fprintf(stderr, "error running function `num_channels': %s\n", lua_tostring(L, -1));
707                 exit(1);
708         }
709
710         int num_channels = luaL_checknumber(L, 1);
711         lua_pop(L, 1);
712         assert(lua_gettop(L) == 0);
713         return num_channels;
714 }
715
716 }  // namespace
717
718 Theme::Theme(const string &filename, const vector<string> &search_dirs, ResourcePool *resource_pool, unsigned num_cards)
719         : resource_pool(resource_pool), num_cards(num_cards), signal_to_card_mapping(global_flags.default_stream_mapping)
720 {
721         L = luaL_newstate();
722         luaL_openlibs(L);
723
724         register_class("EffectChain", EffectChain_funcs); 
725         register_class("LiveInputWrapper", LiveInputWrapper_funcs); 
726         register_class("ImageInput", ImageInput_funcs);
727         register_class("WhiteBalanceEffect", WhiteBalanceEffect_funcs);
728         register_class("ResampleEffect", ResampleEffect_funcs);
729         register_class("PaddingEffect", PaddingEffect_funcs);
730         register_class("IntegralPaddingEffect", IntegralPaddingEffect_funcs);
731         register_class("OverlayEffect", OverlayEffect_funcs);
732         register_class("ResizeEffect", ResizeEffect_funcs);
733         register_class("MultiplyEffect", MultiplyEffect_funcs);
734         register_class("MixEffect", MixEffect_funcs);
735         register_class("InputStateInfo", InputStateInfo_funcs);
736
737         // Run script. Search through all directories until we find a file that will load
738         // (as in, does not return LUA_ERRFILE); then run it. We store load errors
739         // from all the attempts, and show them once we know we can't find any of them.
740         lua_settop(L, 0);
741         vector<string> errors;
742         bool success = false;
743         for (size_t i = 0; i < search_dirs.size(); ++i) {
744                 string path = search_dirs[i] + "/" + filename;
745                 int err = luaL_loadfile(L, path.c_str());
746                 if (err == 0) {
747                         // Success; actually call the code.
748                         if (lua_pcall(L, 0, LUA_MULTRET, 0)) {
749                                 fprintf(stderr, "Error when running %s: %s\n", path.c_str(), lua_tostring(L, -1));
750                                 exit(1);
751                         }
752                         success = true;
753                         break;
754                 }
755                 errors.push_back(lua_tostring(L, -1));
756                 lua_pop(L, 1);
757                 if (err != LUA_ERRFILE) {
758                         // The file actually loaded, but failed to parse somehow. Abort; don't try the next one.
759                         break;
760                 }
761         }
762
763         if (!success) {
764                 for (const string &error : errors) {
765                         fprintf(stderr, "%s\n", error.c_str());
766                 }
767                 exit(1);
768         }
769         assert(lua_gettop(L) == 0);
770
771         // Ask it for the number of channels.
772         num_channels = call_num_channels(L);
773 }
774
775 Theme::~Theme()
776 {
777         lua_close(L);
778 }
779
780 void Theme::register_class(const char *class_name, const luaL_Reg *funcs)
781 {
782         assert(lua_gettop(L) == 0);
783         luaL_newmetatable(L, class_name);  // mt = {}
784         lua_pushlightuserdata(L, this);
785         luaL_setfuncs(L, funcs, 1);        // for (name,f in funcs) { mt[name] = f, with upvalue {theme} }
786         lua_pushvalue(L, -1);
787         lua_setfield(L, -2, "__index");    // mt.__index = mt
788         lua_setglobal(L, class_name);      // ClassName = mt
789         assert(lua_gettop(L) == 0);
790 }
791
792 Theme::Chain Theme::get_chain(unsigned num, float t, unsigned width, unsigned height, InputState input_state) 
793 {
794         Chain chain;
795
796         unique_lock<mutex> lock(m);
797         assert(lua_gettop(L) == 0);
798         lua_getglobal(L, "get_chain");  /* function to be called */
799         lua_pushnumber(L, num);
800         lua_pushnumber(L, t);
801         lua_pushnumber(L, width);
802         lua_pushnumber(L, height);
803         wrap_lua_object<InputStateInfo>(L, "InputStateInfo", input_state);
804
805         if (lua_pcall(L, 5, 2, 0) != 0) {
806                 fprintf(stderr, "error running function `get_chain': %s\n", lua_tostring(L, -1));
807                 exit(1);
808         }
809
810         chain.chain = (EffectChain *)luaL_testudata(L, -2, "EffectChain");
811         if (chain.chain == nullptr) {
812                 fprintf(stderr, "get_chain() for chain number %d did not return an EffectChain\n",
813                         num);
814                 exit(1);
815         }
816         if (!lua_isfunction(L, -1)) {
817                 fprintf(stderr, "Argument #-1 should be a function\n");
818                 exit(1);
819         }
820         lua_pushvalue(L, -1);
821         shared_ptr<LuaRefWithDeleter> funcref(new LuaRefWithDeleter(&m, L, luaL_ref(L, LUA_REGISTRYINDEX)));
822         lua_pop(L, 2);
823         assert(lua_gettop(L) == 0);
824
825         chain.setup_chain = [this, funcref, input_state]{
826                 unique_lock<mutex> lock(m);
827
828                 this->input_state = &input_state;
829
830                 // Set up state, including connecting signals.
831                 lua_rawgeti(L, LUA_REGISTRYINDEX, funcref->get());
832                 if (lua_pcall(L, 0, 0, 0) != 0) {
833                         fprintf(stderr, "error running chain setup callback: %s\n", lua_tostring(L, -1));
834                         exit(1);
835                 }
836                 assert(lua_gettop(L) == 0);
837         };
838
839         // TODO: Can we do better, e.g. by running setup_chain() and seeing what it references?
840         // Actually, setup_chain does maybe hold all the references we need now anyway?
841         for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
842                 for (unsigned frame_num = 0; frame_num < FRAME_HISTORY_LENGTH; ++frame_num) {
843                         chain.input_frames.push_back(input_state.buffered_frames[card_index][frame_num].frame);
844                 }
845         }
846
847         return chain;
848 }
849
850 string Theme::get_channel_name(unsigned channel)
851 {
852         unique_lock<mutex> lock(m);
853         lua_getglobal(L, "channel_name");
854         lua_pushnumber(L, channel);
855         if (lua_pcall(L, 1, 1, 0) != 0) {
856                 fprintf(stderr, "error running function `channel_name': %s\n", lua_tostring(L, -1));
857                 exit(1);
858         }
859         const char *ret = lua_tostring(L, -1);
860         if (ret == nullptr) {
861                 fprintf(stderr, "function `channel_name' returned nil for channel %d\n", channel);
862                 exit(1);
863         }
864
865         string retstr = ret;
866         lua_pop(L, 1);
867         assert(lua_gettop(L) == 0);
868         return retstr;
869 }
870
871 int Theme::get_channel_signal(unsigned channel)
872 {
873         unique_lock<mutex> lock(m);
874         lua_getglobal(L, "channel_signal");
875         lua_pushnumber(L, channel);
876         if (lua_pcall(L, 1, 1, 0) != 0) {
877                 fprintf(stderr, "error running function `channel_signal': %s\n", lua_tostring(L, -1));
878                 exit(1);
879         }
880
881         int ret = luaL_checknumber(L, 1);
882         lua_pop(L, 1);
883         assert(lua_gettop(L) == 0);
884         return ret;
885 }
886
887 std::string Theme::get_channel_color(unsigned channel)
888 {
889         unique_lock<mutex> lock(m);
890         lua_getglobal(L, "channel_color");
891         lua_pushnumber(L, channel);
892         if (lua_pcall(L, 1, 1, 0) != 0) {
893                 fprintf(stderr, "error running function `channel_color': %s\n", lua_tostring(L, -1));
894                 exit(1);
895         }
896
897         const char *ret = lua_tostring(L, -1);
898         if (ret == nullptr) {
899                 fprintf(stderr, "function `channel_color' returned nil for channel %d\n", channel);
900                 exit(1);
901         }
902
903         string retstr = ret;
904         lua_pop(L, 1);
905         assert(lua_gettop(L) == 0);
906         return retstr;
907 }
908
909 bool Theme::get_supports_set_wb(unsigned channel)
910 {
911         unique_lock<mutex> lock(m);
912         lua_getglobal(L, "supports_set_wb");
913         lua_pushnumber(L, channel);
914         if (lua_pcall(L, 1, 1, 0) != 0) {
915                 fprintf(stderr, "error running function `supports_set_wb': %s\n", lua_tostring(L, -1));
916                 exit(1);
917         }
918
919         bool ret = checkbool(L, -1);
920         lua_pop(L, 1);
921         assert(lua_gettop(L) == 0);
922         return ret;
923 }
924
925 void Theme::set_wb(unsigned channel, double r, double g, double b)
926 {
927         unique_lock<mutex> lock(m);
928         lua_getglobal(L, "set_wb");
929         lua_pushnumber(L, channel);
930         lua_pushnumber(L, r);
931         lua_pushnumber(L, g);
932         lua_pushnumber(L, b);
933         if (lua_pcall(L, 4, 0, 0) != 0) {
934                 fprintf(stderr, "error running function `set_wb': %s\n", lua_tostring(L, -1));
935                 exit(1);
936         }
937
938         assert(lua_gettop(L) == 0);
939 }
940
941 vector<string> Theme::get_transition_names(float t)
942 {
943         unique_lock<mutex> lock(m);
944         lua_getglobal(L, "get_transitions");
945         lua_pushnumber(L, t);
946         if (lua_pcall(L, 1, 1, 0) != 0) {
947                 fprintf(stderr, "error running function `get_transitions': %s\n", lua_tostring(L, -1));
948                 exit(1);
949         }
950
951         vector<string> ret;
952         lua_pushnil(L);
953         while (lua_next(L, -2) != 0) {
954                 ret.push_back(lua_tostring(L, -1));
955                 lua_pop(L, 1);
956         }
957         lua_pop(L, 1);
958         assert(lua_gettop(L) == 0);
959         return ret;
960 }       
961
962 int Theme::map_signal(int signal_num)
963 {
964         unique_lock<mutex> lock(map_m);
965         if (signal_to_card_mapping.count(signal_num)) {
966                 return signal_to_card_mapping[signal_num];
967         }
968         if (signal_num >= int(num_cards)) {
969                 fprintf(stderr, "WARNING: Theme asked for input %d, but we only have %u card(s).\n", signal_num, num_cards);
970                 fprintf(stderr, "Mapping to card %d instead.\n", signal_num % num_cards);
971         }
972         signal_to_card_mapping[signal_num] = signal_num % num_cards;
973         return signal_num % num_cards;
974 }
975
976 void Theme::set_signal_mapping(int signal_num, int card_num)
977 {
978         unique_lock<mutex> lock(map_m);
979         assert(card_num < int(num_cards));
980         signal_to_card_mapping[signal_num] = card_num;
981 }
982
983 void Theme::transition_clicked(int transition_num, float t)
984 {
985         unique_lock<mutex> lock(m);
986         lua_getglobal(L, "transition_clicked");
987         lua_pushnumber(L, transition_num);
988         lua_pushnumber(L, t);
989
990         if (lua_pcall(L, 2, 0, 0) != 0) {
991                 fprintf(stderr, "error running function `transition_clicked': %s\n", lua_tostring(L, -1));
992                 exit(1);
993         }
994         assert(lua_gettop(L) == 0);
995 }
996
997 void Theme::channel_clicked(int preview_num)
998 {
999         unique_lock<mutex> lock(m);
1000         lua_getglobal(L, "channel_clicked");
1001         lua_pushnumber(L, preview_num);
1002
1003         if (lua_pcall(L, 1, 0, 0) != 0) {
1004                 fprintf(stderr, "error running function `channel_clicked': %s\n", lua_tostring(L, -1));
1005                 exit(1);
1006         }
1007         assert(lua_gettop(L) == 0);
1008 }