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