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