]> git.sesse.net Git - nageru/blob - theme.cpp
Fix an issue where you could not give an absolute path to a theme.
[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/deinterlace_effect.h>
9 #include <movit/effect.h>
10 #include <movit/effect_chain.h>
11 #include <movit/image_format.h>
12 #include <movit/input.h>
13 #include <movit/mix_effect.h>
14 #include <movit/multiply_effect.h>
15 #include <movit/overlay_effect.h>
16 #include <movit/padding_effect.h>
17 #include <movit/resample_effect.h>
18 #include <movit/resize_effect.h>
19 #include <movit/util.h>
20 #include <movit/white_balance_effect.h>
21 #include <movit/ycbcr.h>
22 #include <movit/ycbcr_input.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <cstddef>
26 #include <memory>
27 #include <new>
28 #include <utility>
29
30 #include "defs.h"
31 #ifdef HAVE_CEF
32 #include "cef_capture.h"
33 #endif
34 #include "ffmpeg_capture.h"
35 #include "flags.h"
36 #include "image_input.h"
37 #include "input_state.h"
38 #include "pbo_frame_allocator.h"
39
40 class Mixer;
41
42 namespace movit {
43 class ResourcePool;
44 }  // namespace movit
45
46 using namespace std;
47 using namespace movit;
48
49 extern Mixer *global_mixer;
50
51 Theme *get_theme_updata(lua_State* L)
52 {
53         luaL_checktype(L, lua_upvalueindex(1), LUA_TLIGHTUSERDATA);
54         return (Theme *)lua_touserdata(L, lua_upvalueindex(1));
55 }
56
57 int ThemeMenu_set(lua_State *L)
58 {
59         Theme *theme = get_theme_updata(L);
60         return theme->set_theme_menu(L);
61 }
62
63 namespace {
64
65 // Contains basically the same data as InputState, but does not hold on to
66 // a reference to the frames. This is important so that we can release them
67 // without having to wait for Lua's GC.
68 struct InputStateInfo {
69         InputStateInfo(const InputState& input_state);
70
71         unsigned last_width[MAX_VIDEO_CARDS], last_height[MAX_VIDEO_CARDS];
72         bool last_interlaced[MAX_VIDEO_CARDS], last_has_signal[MAX_VIDEO_CARDS], last_is_connected[MAX_VIDEO_CARDS];
73         unsigned last_frame_rate_nom[MAX_VIDEO_CARDS], last_frame_rate_den[MAX_VIDEO_CARDS];
74 };
75
76 InputStateInfo::InputStateInfo(const InputState &input_state)
77 {
78         for (unsigned signal_num = 0; signal_num < MAX_VIDEO_CARDS; ++signal_num) {
79                 BufferedFrame frame = input_state.buffered_frames[signal_num][0];
80                 if (frame.frame == nullptr) {
81                         last_width[signal_num] = last_height[signal_num] = 0;
82                         last_interlaced[signal_num] = false;
83                         last_has_signal[signal_num] = false;
84                         last_is_connected[signal_num] = false;
85                         continue;
86                 }
87                 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
88                 last_width[signal_num] = userdata->last_width[frame.field_number];
89                 last_height[signal_num] = userdata->last_height[frame.field_number];
90                 last_interlaced[signal_num] = userdata->last_interlaced;
91                 last_has_signal[signal_num] = userdata->last_has_signal;
92                 last_is_connected[signal_num] = userdata->last_is_connected;
93                 last_frame_rate_nom[signal_num] = userdata->last_frame_rate_nom;
94                 last_frame_rate_den[signal_num] = userdata->last_frame_rate_den;
95         }
96 }
97
98 class LuaRefWithDeleter {
99 public:
100         LuaRefWithDeleter(mutex *m, lua_State *L, int ref) : m(m), L(L), ref(ref) {}
101         ~LuaRefWithDeleter() {
102                 unique_lock<mutex> lock(*m);
103                 luaL_unref(L, LUA_REGISTRYINDEX, ref);
104         }
105         int get() const { return ref; }
106
107 private:
108         LuaRefWithDeleter(const LuaRefWithDeleter &) = delete;
109
110         mutex *m;
111         lua_State *L;
112         int ref;
113 };
114
115 template<class T, class... Args>
116 int wrap_lua_object(lua_State* L, const char *class_name, Args&&... args)
117 {
118         // Construct the C++ object and put it on the stack.
119         void *mem = lua_newuserdata(L, sizeof(T));
120         new(mem) T(forward<Args>(args)...);
121
122         // Look up the metatable named <class_name>, and set it on the new object.
123         luaL_getmetatable(L, class_name);
124         lua_setmetatable(L, -2);
125
126         return 1;
127 }
128
129 // Like wrap_lua_object, but the object is not owned by Lua; ie. it's not freed
130 // by Lua GC. This is typically the case for Effects, which are owned by EffectChain
131 // and expected to be destructed by it. The object will be of type T** instead of T*
132 // when exposed to Lua.
133 //
134 // Note that we currently leak if you allocate an Effect in this way and never call
135 // add_effect. We should see if there's a way to e.g. set __gc on it at construction time
136 // and then release that once add_effect() takes ownership.
137 template<class T, class... Args>
138 int wrap_lua_object_nonowned(lua_State* L, const char *class_name, Args&&... args)
139 {
140         // Construct the pointer ot the C++ object and put it on the stack.
141         T **obj = (T **)lua_newuserdata(L, sizeof(T *));
142         *obj = new T(forward<Args>(args)...);
143
144         // Look up the metatable named <class_name>, and set it on the new object.
145         luaL_getmetatable(L, class_name);
146         lua_setmetatable(L, -2);
147
148         return 1;
149 }
150
151 Effect *get_effect(lua_State *L, int idx)
152 {
153         if (luaL_testudata(L, idx, "WhiteBalanceEffect") ||
154             luaL_testudata(L, idx, "ResampleEffect") ||
155             luaL_testudata(L, idx, "PaddingEffect") ||
156             luaL_testudata(L, idx, "IntegralPaddingEffect") ||
157             luaL_testudata(L, idx, "OverlayEffect") ||
158             luaL_testudata(L, idx, "ResizeEffect") ||
159             luaL_testudata(L, idx, "MultiplyEffect") ||
160             luaL_testudata(L, idx, "MixEffect") ||
161             luaL_testudata(L, idx, "ImageInput")) {
162                 return *(Effect **)lua_touserdata(L, idx);
163         }
164         luaL_error(L, "Error: Index #%d was not an Effect type\n", idx);
165         return nullptr;
166 }
167
168 InputStateInfo *get_input_state_info(lua_State *L, int idx)
169 {
170         if (luaL_testudata(L, idx, "InputStateInfo")) {
171                 return (InputStateInfo *)lua_touserdata(L, idx);
172         }
173         luaL_error(L, "Error: Index #%d was not InputStateInfo\n", idx);
174         return nullptr;
175 }
176
177 bool checkbool(lua_State* L, int idx)
178 {
179         luaL_checktype(L, idx, LUA_TBOOLEAN);
180         return lua_toboolean(L, idx);
181 }
182
183 string checkstdstring(lua_State *L, int index)
184 {
185         size_t len;
186         const char* cstr = lua_tolstring(L, index, &len);
187         return string(cstr, len);
188 }
189
190 int EffectChain_new(lua_State* L)
191 {
192         assert(lua_gettop(L) == 2);
193         Theme *theme = get_theme_updata(L);
194         int aspect_w = luaL_checknumber(L, 1);
195         int aspect_h = luaL_checknumber(L, 2);
196
197         return wrap_lua_object<EffectChain>(L, "EffectChain", aspect_w, aspect_h, theme->get_resource_pool());
198 }
199
200 int EffectChain_gc(lua_State* L)
201 {
202         assert(lua_gettop(L) == 1);
203         EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
204         chain->~EffectChain();
205         return 0;
206 }
207
208 int EffectChain_add_live_input(lua_State* L)
209 {
210         assert(lua_gettop(L) == 3);
211         Theme *theme = get_theme_updata(L);
212         EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
213         bool override_bounce = checkbool(L, 2);
214         bool deinterlace = checkbool(L, 3);
215         bmusb::PixelFormat pixel_format = global_flags.ten_bit_input ? bmusb::PixelFormat_10BitYCbCr : bmusb::PixelFormat_8BitYCbCr;
216
217         // Needs to be nonowned to match add_video_input (see below).
218         return wrap_lua_object_nonowned<LiveInputWrapper>(L, "LiveInputWrapper", theme, chain, pixel_format, override_bounce, deinterlace);
219 }
220
221 int EffectChain_add_video_input(lua_State* L)
222 {
223         assert(lua_gettop(L) == 3);
224         Theme *theme = get_theme_updata(L);
225         EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
226         FFmpegCapture **capture = (FFmpegCapture **)luaL_checkudata(L, 2, "VideoInput");
227         bool deinterlace = checkbool(L, 3);
228
229         // These need to be nonowned, so that the LiveInputWrapper still exists
230         // and can feed frames to the right EffectChain even if the Lua code
231         // doesn't care about the object anymore. (If we change this, we'd need
232         // to also unregister the signal connection on __gc.)
233         int ret = wrap_lua_object_nonowned<LiveInputWrapper>(
234                 L, "LiveInputWrapper", theme, chain, (*capture)->get_current_pixel_format(),
235                 /*override_bounce=*/false, deinterlace);
236         if (ret == 1) {
237                 Theme *theme = get_theme_updata(L);
238                 LiveInputWrapper **live_input = (LiveInputWrapper **)lua_touserdata(L, -1);
239                 theme->register_video_signal_connection(*live_input, *capture);
240         }
241         return ret;
242 }
243
244 #ifdef HAVE_CEF
245 int EffectChain_add_html_input(lua_State* L)
246 {
247         assert(lua_gettop(L) == 2);
248         Theme *theme = get_theme_updata(L);
249         EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
250         CEFCapture **capture = (CEFCapture **)luaL_checkudata(L, 2, "HTMLInput");
251
252         // These need to be nonowned, so that the LiveInputWrapper still exists
253         // and can feed frames to the right EffectChain even if the Lua code
254         // doesn't care about the object anymore. (If we change this, we'd need
255         // to also unregister the signal connection on __gc.)
256         int ret = wrap_lua_object_nonowned<LiveInputWrapper>(
257                 L, "LiveInputWrapper", theme, chain, (*capture)->get_current_pixel_format(),
258                 /*override_bounce=*/false, /*deinterlace=*/false);
259         if (ret == 1) {
260                 Theme *theme = get_theme_updata(L);
261                 LiveInputWrapper **live_input = (LiveInputWrapper **)lua_touserdata(L, -1);
262                 theme->register_html_signal_connection(*live_input, *capture);
263         }
264         return ret;
265 }
266 #endif
267
268 int EffectChain_add_effect(lua_State* L)
269 {
270         assert(lua_gettop(L) >= 2);
271         EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
272
273         // TODO: Better error reporting.
274         Effect *effect = get_effect(L, 2);
275         if (lua_gettop(L) == 2) {
276                 if (effect->num_inputs() == 0) {
277                         chain->add_input((Input *)effect);
278                 } else {
279                         chain->add_effect(effect);
280                 }
281         } else {
282                 vector<Effect *> inputs;
283                 for (int idx = 3; idx <= lua_gettop(L); ++idx) {
284                         if (luaL_testudata(L, idx, "LiveInputWrapper")) {
285                                 LiveInputWrapper **input = (LiveInputWrapper **)lua_touserdata(L, idx);
286                                 inputs.push_back((*input)->get_effect());
287                         } else {
288                                 inputs.push_back(get_effect(L, idx));
289                         }
290                 }
291                 chain->add_effect(effect, inputs);
292         }
293
294         lua_settop(L, 2);  // Return the effect itself.
295
296         // Make sure Lua doesn't garbage-collect it away.
297         lua_pushvalue(L, -1);
298         luaL_ref(L, LUA_REGISTRYINDEX);  // TODO: leak?
299
300         return 1;
301 }
302
303 int EffectChain_finalize(lua_State* L)
304 {
305         assert(lua_gettop(L) == 2);
306         EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
307         bool is_main_chain = checkbool(L, 2);
308
309         // Add outputs as needed.
310         // NOTE: If you change any details about the output format, you will need to
311         // also update what's given to the muxer (HTTPD::Mux constructor) and
312         // what's put in the H.264 stream (sps_rbsp()).
313         ImageFormat inout_format;
314         inout_format.color_space = COLORSPACE_REC_709;
315
316         // Output gamma is tricky. We should output Rec. 709 for TV, except that
317         // we expect to run with web players and others that don't really care and
318         // just output with no conversion. So that means we'll need to output sRGB,
319         // even though H.264 has no setting for that (we use “unspecified”).
320         inout_format.gamma_curve = GAMMA_sRGB;
321
322         if (is_main_chain) {
323                 YCbCrFormat output_ycbcr_format;
324                 // We actually output 4:2:0 and/or 4:2:2 in the end, but chroma subsampling
325                 // happens in a pass not run by Movit (see ChromaSubsampler::subsample_chroma()).
326                 output_ycbcr_format.chroma_subsampling_x = 1;
327                 output_ycbcr_format.chroma_subsampling_y = 1;
328
329                 // This will be overridden if HDMI/SDI output is in force.
330                 if (global_flags.ycbcr_rec709_coefficients) {
331                         output_ycbcr_format.luma_coefficients = YCBCR_REC_709;
332                 } else {
333                         output_ycbcr_format.luma_coefficients = YCBCR_REC_601;
334                 }
335
336                 output_ycbcr_format.full_range = false;
337                 output_ycbcr_format.num_levels = 1 << global_flags.x264_bit_depth;
338
339                 GLenum type = global_flags.x264_bit_depth > 8 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_BYTE;
340
341                 chain->add_ycbcr_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED, output_ycbcr_format, YCBCR_OUTPUT_SPLIT_Y_AND_CBCR, type);
342
343                 // If we're using zerocopy video encoding (so the destination
344                 // Y texture is owned by VA-API and will be unavailable for
345                 // display), add a copy, where we'll only be using the Y component.
346                 if (global_flags.use_zerocopy) {
347                         chain->add_ycbcr_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED, output_ycbcr_format, YCBCR_OUTPUT_INTERLEAVED, type);  // Add a copy where we'll only be using the Y component.
348                 }
349                 chain->set_dither_bits(global_flags.x264_bit_depth > 8 ? 16 : 8);
350                 chain->set_output_origin(OUTPUT_ORIGIN_TOP_LEFT);
351         } else {
352                 chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
353         }
354
355         chain->finalize();
356         return 0;
357 }
358
359 int LiveInputWrapper_connect_signal(lua_State* L)
360 {
361         assert(lua_gettop(L) == 2);
362         LiveInputWrapper **input = (LiveInputWrapper **)luaL_checkudata(L, 1, "LiveInputWrapper");
363         int signal_num = luaL_checknumber(L, 2);
364         (*input)->connect_signal(signal_num);
365         return 0;
366 }
367
368 int ImageInput_new(lua_State* L)
369 {
370         assert(lua_gettop(L) == 1);
371         string filename = checkstdstring(L, 1);
372         return wrap_lua_object_nonowned<ImageInput>(L, "ImageInput", filename);
373 }
374
375 int VideoInput_new(lua_State* L)
376 {
377         assert(lua_gettop(L) == 2);
378         string filename = checkstdstring(L, 1);
379         int pixel_format = luaL_checknumber(L, 2);
380         if (pixel_format != bmusb::PixelFormat_8BitYCbCrPlanar &&
381             pixel_format != bmusb::PixelFormat_8BitBGRA) {
382                 fprintf(stderr, "WARNING: Invalid enum %d used for video format, choosing Y'CbCr.\n",
383                         pixel_format);
384                 pixel_format = bmusb::PixelFormat_8BitYCbCrPlanar;
385         }
386         int ret = wrap_lua_object_nonowned<FFmpegCapture>(L, "VideoInput", filename, global_flags.width, global_flags.height);
387         if (ret == 1) {
388                 FFmpegCapture **capture = (FFmpegCapture **)lua_touserdata(L, -1);
389                 (*capture)->set_pixel_format(bmusb::PixelFormat(pixel_format));
390
391                 Theme *theme = get_theme_updata(L);
392                 theme->register_video_input(*capture);
393         }
394         return ret;
395 }
396
397 int VideoInput_rewind(lua_State* L)
398 {
399         assert(lua_gettop(L) == 1);
400         FFmpegCapture **video_input = (FFmpegCapture **)luaL_checkudata(L, 1, "VideoInput");
401         (*video_input)->rewind();
402         return 0;
403 }
404
405 int VideoInput_change_rate(lua_State* L)
406 {
407         assert(lua_gettop(L) == 2);
408         FFmpegCapture **video_input = (FFmpegCapture **)luaL_checkudata(L, 1, "VideoInput");
409         double new_rate = luaL_checknumber(L, 2);
410         (*video_input)->change_rate(new_rate);
411         return 0;
412 }
413
414 int VideoInput_get_signal_num(lua_State* L)
415 {
416         assert(lua_gettop(L) == 1);
417         FFmpegCapture **video_input = (FFmpegCapture **)luaL_checkudata(L, 1, "VideoInput");
418         lua_pushnumber(L, -1 - (*video_input)->get_card_index());
419         return 1;
420 }
421
422 int HTMLInput_new(lua_State* L)
423 {
424 #ifdef HAVE_CEF
425         assert(lua_gettop(L) == 1);
426         string url = checkstdstring(L, 1);
427         int ret = wrap_lua_object_nonowned<CEFCapture>(L, "HTMLInput", url, global_flags.width, global_flags.height);
428         if (ret == 1) {
429                 CEFCapture **capture = (CEFCapture **)lua_touserdata(L, -1);
430                 Theme *theme = get_theme_updata(L);
431                 theme->register_html_input(*capture);
432         }
433         return ret;
434 #else
435         fprintf(stderr, "This version of Nageru has been compiled without CEF support.\n");
436         fprintf(stderr, "HTMLInput is not available.\n");
437         exit(1);
438 #endif
439 }
440
441 #ifdef HAVE_CEF
442 int HTMLInput_set_url(lua_State* L)
443 {
444         assert(lua_gettop(L) == 2);
445         CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
446         string new_url = checkstdstring(L, 2);
447         (*video_input)->set_url(new_url);
448         return 0;
449 }
450
451 int HTMLInput_reload(lua_State* L)
452 {
453         assert(lua_gettop(L) == 1);
454         CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
455         (*video_input)->reload();
456         return 0;
457 }
458
459 int HTMLInput_set_max_fps(lua_State* L)
460 {
461         assert(lua_gettop(L) == 2);
462         CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
463         int max_fps = lrint(luaL_checknumber(L, 2));
464         (*video_input)->set_max_fps(max_fps);
465         return 0;
466 }
467
468 int HTMLInput_execute_javascript_async(lua_State* L)
469 {
470         assert(lua_gettop(L) == 2);
471         CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
472         string js = checkstdstring(L, 2);
473         (*video_input)->execute_javascript_async(js);
474         return 0;
475 }
476
477 int HTMLInput_get_signal_num(lua_State* L)
478 {
479         assert(lua_gettop(L) == 1);
480         CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
481         lua_pushnumber(L, -1 - (*video_input)->get_card_index());
482         return 1;
483 }
484 #endif
485
486 int WhiteBalanceEffect_new(lua_State* L)
487 {
488         assert(lua_gettop(L) == 0);
489         return wrap_lua_object_nonowned<WhiteBalanceEffect>(L, "WhiteBalanceEffect");
490 }
491
492 int ResampleEffect_new(lua_State* L)
493 {
494         assert(lua_gettop(L) == 0);
495         return wrap_lua_object_nonowned<ResampleEffect>(L, "ResampleEffect");
496 }
497
498 int PaddingEffect_new(lua_State* L)
499 {
500         assert(lua_gettop(L) == 0);
501         return wrap_lua_object_nonowned<PaddingEffect>(L, "PaddingEffect");
502 }
503
504 int IntegralPaddingEffect_new(lua_State* L)
505 {
506         assert(lua_gettop(L) == 0);
507         return wrap_lua_object_nonowned<IntegralPaddingEffect>(L, "IntegralPaddingEffect");
508 }
509
510 int OverlayEffect_new(lua_State* L)
511 {
512         assert(lua_gettop(L) == 0);
513         return wrap_lua_object_nonowned<OverlayEffect>(L, "OverlayEffect");
514 }
515
516 int ResizeEffect_new(lua_State* L)
517 {
518         assert(lua_gettop(L) == 0);
519         return wrap_lua_object_nonowned<ResizeEffect>(L, "ResizeEffect");
520 }
521
522 int MultiplyEffect_new(lua_State* L)
523 {
524         assert(lua_gettop(L) == 0);
525         return wrap_lua_object_nonowned<MultiplyEffect>(L, "MultiplyEffect");
526 }
527
528 int MixEffect_new(lua_State* L)
529 {
530         assert(lua_gettop(L) == 0);
531         return wrap_lua_object_nonowned<MixEffect>(L, "MixEffect");
532 }
533
534 int InputStateInfo_get_width(lua_State* L)
535 {
536         assert(lua_gettop(L) == 2);
537         InputStateInfo *input_state_info = get_input_state_info(L, 1);
538         Theme *theme = get_theme_updata(L);
539         int signal_num = theme->map_signal(luaL_checknumber(L, 2));
540         lua_pushnumber(L, input_state_info->last_width[signal_num]);
541         return 1;
542 }
543
544 int InputStateInfo_get_height(lua_State* L)
545 {
546         assert(lua_gettop(L) == 2);
547         InputStateInfo *input_state_info = get_input_state_info(L, 1);
548         Theme *theme = get_theme_updata(L);
549         int signal_num = theme->map_signal(luaL_checknumber(L, 2));
550         lua_pushnumber(L, input_state_info->last_height[signal_num]);
551         return 1;
552 }
553
554 int InputStateInfo_get_interlaced(lua_State* L)
555 {
556         assert(lua_gettop(L) == 2);
557         InputStateInfo *input_state_info = get_input_state_info(L, 1);
558         Theme *theme = get_theme_updata(L);
559         int signal_num = theme->map_signal(luaL_checknumber(L, 2));
560         lua_pushboolean(L, input_state_info->last_interlaced[signal_num]);
561         return 1;
562 }
563
564 int InputStateInfo_get_has_signal(lua_State* L)
565 {
566         assert(lua_gettop(L) == 2);
567         InputStateInfo *input_state_info = get_input_state_info(L, 1);
568         Theme *theme = get_theme_updata(L);
569         int signal_num = theme->map_signal(luaL_checknumber(L, 2));
570         lua_pushboolean(L, input_state_info->last_has_signal[signal_num]);
571         return 1;
572 }
573
574 int InputStateInfo_get_is_connected(lua_State* L)
575 {
576         assert(lua_gettop(L) == 2);
577         InputStateInfo *input_state_info = get_input_state_info(L, 1);
578         Theme *theme = get_theme_updata(L);
579         int signal_num = theme->map_signal(luaL_checknumber(L, 2));
580         lua_pushboolean(L, input_state_info->last_is_connected[signal_num]);
581         return 1;
582 }
583
584 int InputStateInfo_get_frame_rate_nom(lua_State* L)
585 {
586         assert(lua_gettop(L) == 2);
587         InputStateInfo *input_state_info = get_input_state_info(L, 1);
588         Theme *theme = get_theme_updata(L);
589         int signal_num = theme->map_signal(luaL_checknumber(L, 2));
590         lua_pushnumber(L, input_state_info->last_frame_rate_nom[signal_num]);
591         return 1;
592 }
593
594 int InputStateInfo_get_frame_rate_den(lua_State* L)
595 {
596         assert(lua_gettop(L) == 2);
597         InputStateInfo *input_state_info = get_input_state_info(L, 1);
598         Theme *theme = get_theme_updata(L);
599         int signal_num = theme->map_signal(luaL_checknumber(L, 2));
600         lua_pushnumber(L, input_state_info->last_frame_rate_den[signal_num]);
601         return 1;
602 }
603
604 int Effect_set_float(lua_State *L)
605 {
606         assert(lua_gettop(L) == 3);
607         Effect *effect = (Effect *)get_effect(L, 1);
608         string key = checkstdstring(L, 2);
609         float value = luaL_checknumber(L, 3);
610         if (!effect->set_float(key, value)) {
611                 luaL_error(L, "Effect refused set_float(\"%s\", %d) (invalid key?)", key.c_str(), int(value));
612         }
613         return 0;
614 }
615
616 int Effect_set_int(lua_State *L)
617 {
618         assert(lua_gettop(L) == 3);
619         Effect *effect = (Effect *)get_effect(L, 1);
620         string key = checkstdstring(L, 2);
621         float value = luaL_checknumber(L, 3);
622         if (!effect->set_int(key, value)) {
623                 luaL_error(L, "Effect refused set_int(\"%s\", %d) (invalid key?)", key.c_str(), int(value));
624         }
625         return 0;
626 }
627
628 int Effect_set_vec3(lua_State *L)
629 {
630         assert(lua_gettop(L) == 5);
631         Effect *effect = (Effect *)get_effect(L, 1);
632         string key = checkstdstring(L, 2);
633         float v[3];
634         v[0] = luaL_checknumber(L, 3);
635         v[1] = luaL_checknumber(L, 4);
636         v[2] = luaL_checknumber(L, 5);
637         if (!effect->set_vec3(key, v)) {
638                 luaL_error(L, "Effect refused set_vec3(\"%s\", %f, %f, %f) (invalid key?)", key.c_str(),
639                         v[0], v[1], v[2]);
640         }
641         return 0;
642 }
643
644 int Effect_set_vec4(lua_State *L)
645 {
646         assert(lua_gettop(L) == 6);
647         Effect *effect = (Effect *)get_effect(L, 1);
648         string key = checkstdstring(L, 2);
649         float v[4];
650         v[0] = luaL_checknumber(L, 3);
651         v[1] = luaL_checknumber(L, 4);
652         v[2] = luaL_checknumber(L, 5);
653         v[3] = luaL_checknumber(L, 6);
654         if (!effect->set_vec4(key, v)) {
655                 luaL_error(L, "Effect refused set_vec4(\"%s\", %f, %f, %f, %f) (invalid key?)", key.c_str(),
656                         v[0], v[1], v[2], v[3]);
657         }
658         return 0;
659 }
660
661 const luaL_Reg EffectChain_funcs[] = {
662         { "new", EffectChain_new },
663         { "__gc", EffectChain_gc },
664         { "add_live_input", EffectChain_add_live_input },
665         { "add_video_input", EffectChain_add_video_input },
666 #ifdef HAVE_CEF
667         { "add_html_input", EffectChain_add_html_input },
668 #endif
669         { "add_effect", EffectChain_add_effect },
670         { "finalize", EffectChain_finalize },
671         { NULL, NULL }
672 };
673
674 const luaL_Reg LiveInputWrapper_funcs[] = {
675         { "connect_signal", LiveInputWrapper_connect_signal },
676         { NULL, NULL }
677 };
678
679 const luaL_Reg ImageInput_funcs[] = {
680         { "new", ImageInput_new },
681         { "set_float", Effect_set_float },
682         { "set_int", Effect_set_int },
683         { "set_vec3", Effect_set_vec3 },
684         { "set_vec4", Effect_set_vec4 },
685         { NULL, NULL }
686 };
687
688 const luaL_Reg VideoInput_funcs[] = {
689         { "new", VideoInput_new },
690         { "rewind", VideoInput_rewind },
691         { "change_rate", VideoInput_change_rate },
692         { "get_signal_num", VideoInput_get_signal_num },
693         { NULL, NULL }
694 };
695
696 const luaL_Reg HTMLInput_funcs[] = {
697         { "new", HTMLInput_new },
698 #ifdef HAVE_CEF
699         { "set_url", HTMLInput_set_url },
700         { "reload", HTMLInput_reload },
701         { "set_max_fps", HTMLInput_set_max_fps },
702         { "execute_javascript_async", HTMLInput_execute_javascript_async },
703         { "get_signal_num", HTMLInput_get_signal_num },
704 #endif
705         { NULL, NULL }
706 };
707
708 const luaL_Reg WhiteBalanceEffect_funcs[] = {
709         { "new", WhiteBalanceEffect_new },
710         { "set_float", Effect_set_float },
711         { "set_int", Effect_set_int },
712         { "set_vec3", Effect_set_vec3 },
713         { "set_vec4", Effect_set_vec4 },
714         { NULL, NULL }
715 };
716
717 const luaL_Reg ResampleEffect_funcs[] = {
718         { "new", ResampleEffect_new },
719         { "set_float", Effect_set_float },
720         { "set_int", Effect_set_int },
721         { "set_vec3", Effect_set_vec3 },
722         { "set_vec4", Effect_set_vec4 },
723         { NULL, NULL }
724 };
725
726 const luaL_Reg PaddingEffect_funcs[] = {
727         { "new", PaddingEffect_new },
728         { "set_float", Effect_set_float },
729         { "set_int", Effect_set_int },
730         { "set_vec3", Effect_set_vec3 },
731         { "set_vec4", Effect_set_vec4 },
732         { NULL, NULL }
733 };
734
735 const luaL_Reg IntegralPaddingEffect_funcs[] = {
736         { "new", IntegralPaddingEffect_new },
737         { "set_float", Effect_set_float },
738         { "set_int", Effect_set_int },
739         { "set_vec3", Effect_set_vec3 },
740         { "set_vec4", Effect_set_vec4 },
741         { NULL, NULL }
742 };
743
744 const luaL_Reg OverlayEffect_funcs[] = {
745         { "new", OverlayEffect_new },
746         { "set_float", Effect_set_float },
747         { "set_int", Effect_set_int },
748         { "set_vec3", Effect_set_vec3 },
749         { "set_vec4", Effect_set_vec4 },
750         { NULL, NULL }
751 };
752
753 const luaL_Reg ResizeEffect_funcs[] = {
754         { "new", ResizeEffect_new },
755         { "set_float", Effect_set_float },
756         { "set_int", Effect_set_int },
757         { "set_vec3", Effect_set_vec3 },
758         { "set_vec4", Effect_set_vec4 },
759         { NULL, NULL }
760 };
761
762 const luaL_Reg MultiplyEffect_funcs[] = {
763         { "new", MultiplyEffect_new },
764         { "set_float", Effect_set_float },
765         { "set_int", Effect_set_int },
766         { "set_vec3", Effect_set_vec3 },
767         { "set_vec4", Effect_set_vec4 },
768         { NULL, NULL }
769 };
770
771 const luaL_Reg MixEffect_funcs[] = {
772         { "new", MixEffect_new },
773         { "set_float", Effect_set_float },
774         { "set_int", Effect_set_int },
775         { "set_vec3", Effect_set_vec3 },
776         { "set_vec4", Effect_set_vec4 },
777         { NULL, NULL }
778 };
779
780 const luaL_Reg InputStateInfo_funcs[] = {
781         { "get_width", InputStateInfo_get_width },
782         { "get_height", InputStateInfo_get_height },
783         { "get_interlaced", InputStateInfo_get_interlaced },
784         { "get_has_signal", InputStateInfo_get_has_signal },
785         { "get_is_connected", InputStateInfo_get_is_connected },
786         { "get_frame_rate_nom", InputStateInfo_get_frame_rate_nom },
787         { "get_frame_rate_den", InputStateInfo_get_frame_rate_den },
788         { NULL, NULL }
789 };
790
791 const luaL_Reg ThemeMenu_funcs[] = {
792         { "set", ThemeMenu_set },
793         { NULL, NULL }
794 };
795
796 }  // namespace
797
798 LiveInputWrapper::LiveInputWrapper(Theme *theme, EffectChain *chain, bmusb::PixelFormat pixel_format, bool override_bounce, bool deinterlace)
799         : theme(theme),
800           pixel_format(pixel_format),
801           deinterlace(deinterlace)
802 {
803         ImageFormat inout_format;
804         inout_format.color_space = COLORSPACE_sRGB;
805
806         // Gamma curve depends on the input signal, and we don't really get any
807         // indications. A camera would be expected to do Rec. 709, but
808         // I haven't checked if any do in practice. However, computers _do_ output
809         // in sRGB gamma (ie., they don't convert from sRGB to Rec. 709), and
810         // I wouldn't really be surprised if most non-professional cameras do, too.
811         // So we pick sRGB as the least evil here.
812         inout_format.gamma_curve = GAMMA_sRGB;
813
814         unsigned num_inputs;
815         if (deinterlace) {
816                 deinterlace_effect = new movit::DeinterlaceEffect();
817
818                 // As per the comments in deinterlace_effect.h, we turn this off.
819                 // The most likely interlaced input for us is either a camera
820                 // (where it's fine to turn it off) or a laptop (where it _should_
821                 // be turned off).
822                 CHECK(deinterlace_effect->set_int("enable_spatial_interlacing_check", 0));
823
824                 num_inputs = deinterlace_effect->num_inputs();
825                 assert(num_inputs == FRAME_HISTORY_LENGTH);
826         } else {
827                 num_inputs = 1;
828         }
829
830         if (pixel_format == bmusb::PixelFormat_8BitBGRA) {
831                 for (unsigned i = 0; i < num_inputs; ++i) {
832                         // We upload our textures ourselves, and Movit swaps
833                         // R and B in the shader if we specify BGRA, so lie and say RGBA.
834                         if (global_flags.can_disable_srgb_decoder) {
835                                 rgba_inputs.push_back(new sRGBSwitchingFlatInput(inout_format, FORMAT_RGBA_POSTMULTIPLIED_ALPHA, GL_UNSIGNED_BYTE, global_flags.width, global_flags.height));
836                         } else {
837                                 rgba_inputs.push_back(new NonsRGBCapableFlatInput(inout_format, FORMAT_RGBA_POSTMULTIPLIED_ALPHA, GL_UNSIGNED_BYTE, global_flags.width, global_flags.height));
838                         }
839                         chain->add_input(rgba_inputs.back());
840                 }
841
842                 if (deinterlace) {
843                         vector<Effect *> reverse_inputs(rgba_inputs.rbegin(), rgba_inputs.rend());
844                         chain->add_effect(deinterlace_effect, reverse_inputs);
845                 }
846         } else {
847                 assert(pixel_format == bmusb::PixelFormat_8BitYCbCr ||
848                        pixel_format == bmusb::PixelFormat_10BitYCbCr ||
849                        pixel_format == bmusb::PixelFormat_8BitYCbCrPlanar);
850
851                 // Most of these settings will be overridden later if using PixelFormat_8BitYCbCrPlanar.
852                 input_ycbcr_format.chroma_subsampling_x = (pixel_format == bmusb::PixelFormat_10BitYCbCr) ? 1 : 2;
853                 input_ycbcr_format.chroma_subsampling_y = 1;
854                 input_ycbcr_format.num_levels = (pixel_format == bmusb::PixelFormat_10BitYCbCr) ? 1024 : 256;
855                 input_ycbcr_format.cb_x_position = 0.0;
856                 input_ycbcr_format.cr_x_position = 0.0;
857                 input_ycbcr_format.cb_y_position = 0.5;
858                 input_ycbcr_format.cr_y_position = 0.5;
859                 input_ycbcr_format.luma_coefficients = YCBCR_REC_709;  // Will be overridden later even if not planar.
860                 input_ycbcr_format.full_range = false;  // Will be overridden later even if not planar.
861
862                 for (unsigned i = 0; i < num_inputs; ++i) {
863                         // When using 10-bit input, we're converting to interleaved through v210Converter.
864                         YCbCrInputSplitting splitting;
865                         if (pixel_format == bmusb::PixelFormat_10BitYCbCr) {
866                                 splitting = YCBCR_INPUT_INTERLEAVED;
867                         } else if (pixel_format == bmusb::PixelFormat_8BitYCbCr) {
868                                 splitting = YCBCR_INPUT_SPLIT_Y_AND_CBCR;
869                         } else {
870                                 splitting = YCBCR_INPUT_PLANAR;
871                         }
872                         if (override_bounce) {
873                                 ycbcr_inputs.push_back(new NonBouncingYCbCrInput(inout_format, input_ycbcr_format, global_flags.width, global_flags.height, splitting));
874                         } else {
875                                 ycbcr_inputs.push_back(new YCbCrInput(inout_format, input_ycbcr_format, global_flags.width, global_flags.height, splitting));
876                         }
877                         chain->add_input(ycbcr_inputs.back());
878                 }
879
880                 if (deinterlace) {
881                         vector<Effect *> reverse_inputs(ycbcr_inputs.rbegin(), ycbcr_inputs.rend());
882                         chain->add_effect(deinterlace_effect, reverse_inputs);
883                 }
884         }
885 }
886
887 void LiveInputWrapper::connect_signal(int signal_num)
888 {
889         if (global_mixer == nullptr) {
890                 // No data yet.
891                 return;
892         }
893
894         signal_num = theme->map_signal(signal_num);
895         connect_signal_raw(signal_num, *theme->input_state);
896 }
897
898 void LiveInputWrapper::connect_signal_raw(int signal_num, const InputState &input_state)
899 {
900         BufferedFrame first_frame = input_state.buffered_frames[signal_num][0];
901         if (first_frame.frame == nullptr) {
902                 // No data yet.
903                 return;
904         }
905         unsigned width, height;
906         {
907                 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)first_frame.frame->userdata;
908                 width = userdata->last_width[first_frame.field_number];
909                 height = userdata->last_height[first_frame.field_number];
910         }
911
912         movit::YCbCrLumaCoefficients ycbcr_coefficients = input_state.ycbcr_coefficients[signal_num];
913         bool full_range = input_state.full_range[signal_num];
914
915         if (input_state.ycbcr_coefficients_auto[signal_num]) {
916                 full_range = false;
917
918                 // The Blackmagic driver docs claim that the device outputs Y'CbCr
919                 // according to Rec. 601, but this seems to indicate the subsampling
920                 // positions only, as they publish Y'CbCr → RGB formulas that are
921                 // different for HD and SD (corresponding to Rec. 709 and 601, respectively),
922                 // and a Lenovo X1 gen 3 I used to test definitely outputs Rec. 709
923                 // (at least up to rounding error). Other devices seem to use Rec. 601
924                 // even on HD resolutions. Nevertheless, Rec. 709 _is_ the right choice
925                 // for HD, so we default to that if the user hasn't set anything.
926                 if (height >= 720) {
927                         ycbcr_coefficients = YCBCR_REC_709;
928                 } else {
929                         ycbcr_coefficients = YCBCR_REC_601;
930                 }
931         }
932
933         // This is a global, but it doesn't really matter.
934         input_ycbcr_format.luma_coefficients = ycbcr_coefficients;
935         input_ycbcr_format.full_range = full_range;
936
937         BufferedFrame last_good_frame = first_frame;
938         for (unsigned i = 0; i < max(ycbcr_inputs.size(), rgba_inputs.size()); ++i) {
939                 BufferedFrame frame = input_state.buffered_frames[signal_num][i];
940                 if (frame.frame == nullptr) {
941                         // Not enough data; reuse last frame (well, field).
942                         // This is suboptimal, but we have nothing better.
943                         frame = last_good_frame;
944                 }
945                 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
946
947                 unsigned this_width = userdata->last_width[frame.field_number];
948                 unsigned this_height = userdata->last_height[frame.field_number];
949                 if (this_width != width || this_height != height) {
950                         // Resolution changed; reuse last frame/field.
951                         frame = last_good_frame;
952                         userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
953                 }
954
955                 assert(userdata->pixel_format == pixel_format);
956                 switch (pixel_format) {
957                 case bmusb::PixelFormat_8BitYCbCr:
958                         ycbcr_inputs[i]->set_texture_num(0, userdata->tex_y[frame.field_number]);
959                         ycbcr_inputs[i]->set_texture_num(1, userdata->tex_cbcr[frame.field_number]);
960                         ycbcr_inputs[i]->change_ycbcr_format(input_ycbcr_format);
961                         ycbcr_inputs[i]->set_width(width);
962                         ycbcr_inputs[i]->set_height(height);
963                         break;
964                 case bmusb::PixelFormat_8BitYCbCrPlanar:
965                         ycbcr_inputs[i]->set_texture_num(0, userdata->tex_y[frame.field_number]);
966                         ycbcr_inputs[i]->set_texture_num(1, userdata->tex_cb[frame.field_number]);
967                         ycbcr_inputs[i]->set_texture_num(2, userdata->tex_cr[frame.field_number]);
968                         ycbcr_inputs[i]->change_ycbcr_format(userdata->ycbcr_format);
969                         ycbcr_inputs[i]->set_width(width);
970                         ycbcr_inputs[i]->set_height(height);
971                         break;
972                 case bmusb::PixelFormat_10BitYCbCr:
973                         ycbcr_inputs[i]->set_texture_num(0, userdata->tex_444[frame.field_number]);
974                         ycbcr_inputs[i]->change_ycbcr_format(input_ycbcr_format);
975                         ycbcr_inputs[i]->set_width(width);
976                         ycbcr_inputs[i]->set_height(height);
977                         break;
978                 case bmusb::PixelFormat_8BitBGRA:
979                         rgba_inputs[i]->set_texture_num(userdata->tex_rgba[frame.field_number]);
980                         rgba_inputs[i]->set_width(width);
981                         rgba_inputs[i]->set_height(height);
982                         break;
983                 default:
984                         assert(false);
985                 }
986
987                 last_good_frame = frame;
988         }
989
990         if (deinterlace) {
991                 BufferedFrame frame = input_state.buffered_frames[signal_num][0];
992                 CHECK(deinterlace_effect->set_int("current_field_position", frame.field_number));
993         }
994 }
995
996 namespace {
997
998 int call_num_channels(lua_State *L)
999 {
1000         lua_getglobal(L, "num_channels");
1001
1002         if (lua_pcall(L, 0, 1, 0) != 0) {
1003                 fprintf(stderr, "error running function `num_channels': %s\n", lua_tostring(L, -1));
1004                 exit(1);
1005         }
1006
1007         int num_channels = luaL_checknumber(L, 1);
1008         lua_pop(L, 1);
1009         assert(lua_gettop(L) == 0);
1010         return num_channels;
1011 }
1012
1013 }  // namespace
1014
1015 Theme::Theme(const string &filename, const vector<string> &search_dirs, ResourcePool *resource_pool, unsigned num_cards)
1016         : resource_pool(resource_pool), num_cards(num_cards), signal_to_card_mapping(global_flags.default_stream_mapping)
1017 {
1018         L = luaL_newstate();
1019         luaL_openlibs(L);
1020
1021         register_constants();
1022         register_class("EffectChain", EffectChain_funcs); 
1023         register_class("LiveInputWrapper", LiveInputWrapper_funcs); 
1024         register_class("ImageInput", ImageInput_funcs);
1025         register_class("VideoInput", VideoInput_funcs);
1026         register_class("HTMLInput", HTMLInput_funcs);
1027         register_class("WhiteBalanceEffect", WhiteBalanceEffect_funcs);
1028         register_class("ResampleEffect", ResampleEffect_funcs);
1029         register_class("PaddingEffect", PaddingEffect_funcs);
1030         register_class("IntegralPaddingEffect", IntegralPaddingEffect_funcs);
1031         register_class("OverlayEffect", OverlayEffect_funcs);
1032         register_class("ResizeEffect", ResizeEffect_funcs);
1033         register_class("MultiplyEffect", MultiplyEffect_funcs);
1034         register_class("MixEffect", MixEffect_funcs);
1035         register_class("InputStateInfo", InputStateInfo_funcs);
1036         register_class("ThemeMenu", ThemeMenu_funcs);
1037
1038         // Run script. Search through all directories until we find a file that will load
1039         // (as in, does not return LUA_ERRFILE); then run it. We store load errors
1040         // from all the attempts, and show them once we know we can't find any of them.
1041         lua_settop(L, 0);
1042         vector<string> errors;
1043         bool success = false;
1044
1045         vector<string> real_search_dirs;
1046         if (!filename.empty() && filename[0] == '/') {
1047                 real_search_dirs.push_back("");
1048         } else {
1049                 real_search_dirs = search_dirs;
1050         }
1051
1052         for (const string &dir : real_search_dirs) {
1053                 string path;
1054                 if (dir.empty()) {
1055                         path = filename;
1056                 } else {
1057                         path = dir + "/" + filename;
1058                 }
1059                 int err = luaL_loadfile(L, path.c_str());
1060                 if (err == 0) {
1061                         // Success; actually call the code.
1062                         if (lua_pcall(L, 0, LUA_MULTRET, 0)) {
1063                                 fprintf(stderr, "Error when running %s: %s\n", path.c_str(), lua_tostring(L, -1));
1064                                 exit(1);
1065                         }
1066                         success = true;
1067                         break;
1068                 }
1069                 errors.push_back(lua_tostring(L, -1));
1070                 lua_pop(L, 1);
1071                 if (err != LUA_ERRFILE) {
1072                         // The file actually loaded, but failed to parse somehow. Abort; don't try the next one.
1073                         break;
1074                 }
1075         }
1076
1077         if (!success) {
1078                 for (const string &error : errors) {
1079                         fprintf(stderr, "%s\n", error.c_str());
1080                 }
1081                 exit(1);
1082         }
1083         assert(lua_gettop(L) == 0);
1084
1085         // Ask it for the number of channels.
1086         num_channels = call_num_channels(L);
1087 }
1088
1089 Theme::~Theme()
1090 {
1091         lua_close(L);
1092 }
1093
1094 void Theme::register_constants()
1095 {
1096         // Set Nageru.VIDEO_FORMAT_BGRA = bmusb::PixelFormat_8BitBGRA, etc.
1097         const vector<pair<string, int>> constants = {
1098                 { "VIDEO_FORMAT_BGRA", bmusb::PixelFormat_8BitBGRA },
1099                 { "VIDEO_FORMAT_YCBCR", bmusb::PixelFormat_8BitYCbCrPlanar },
1100         };
1101
1102         lua_newtable(L);  // t = {}
1103
1104         for (const pair<string, int> &constant : constants) {
1105                 lua_pushstring(L, constant.first.c_str());
1106                 lua_pushinteger(L, constant.second);
1107                 lua_settable(L, 1);  // t[key] = value
1108         }
1109
1110         lua_setglobal(L, "Nageru");  // Nageru = t
1111         assert(lua_gettop(L) == 0);
1112 }
1113
1114 void Theme::register_class(const char *class_name, const luaL_Reg *funcs)
1115 {
1116         assert(lua_gettop(L) == 0);
1117         luaL_newmetatable(L, class_name);  // mt = {}
1118         lua_pushlightuserdata(L, this);
1119         luaL_setfuncs(L, funcs, 1);        // for (name,f in funcs) { mt[name] = f, with upvalue {theme} }
1120         lua_pushvalue(L, -1);
1121         lua_setfield(L, -2, "__index");    // mt.__index = mt
1122         lua_setglobal(L, class_name);      // ClassName = mt
1123         assert(lua_gettop(L) == 0);
1124 }
1125
1126 Theme::Chain Theme::get_chain(unsigned num, float t, unsigned width, unsigned height, InputState input_state) 
1127 {
1128         Chain chain;
1129
1130         unique_lock<mutex> lock(m);
1131         assert(lua_gettop(L) == 0);
1132         lua_getglobal(L, "get_chain");  /* function to be called */
1133         lua_pushnumber(L, num);
1134         lua_pushnumber(L, t);
1135         lua_pushnumber(L, width);
1136         lua_pushnumber(L, height);
1137         wrap_lua_object<InputStateInfo>(L, "InputStateInfo", input_state);
1138
1139         if (lua_pcall(L, 5, 2, 0) != 0) {
1140                 fprintf(stderr, "error running function `get_chain': %s\n", lua_tostring(L, -1));
1141                 exit(1);
1142         }
1143
1144         chain.chain = (EffectChain *)luaL_testudata(L, -2, "EffectChain");
1145         if (chain.chain == nullptr) {
1146                 fprintf(stderr, "get_chain() for chain number %d did not return an EffectChain\n",
1147                         num);
1148                 exit(1);
1149         }
1150         if (!lua_isfunction(L, -1)) {
1151                 fprintf(stderr, "Argument #-1 should be a function\n");
1152                 exit(1);
1153         }
1154         lua_pushvalue(L, -1);
1155         shared_ptr<LuaRefWithDeleter> funcref(new LuaRefWithDeleter(&m, L, luaL_ref(L, LUA_REGISTRYINDEX)));
1156         lua_pop(L, 2);
1157         assert(lua_gettop(L) == 0);
1158
1159         chain.setup_chain = [this, funcref, input_state]{
1160                 unique_lock<mutex> lock(m);
1161
1162                 assert(this->input_state == nullptr);
1163                 this->input_state = &input_state;
1164
1165                 // Set up state, including connecting signals.
1166                 lua_rawgeti(L, LUA_REGISTRYINDEX, funcref->get());
1167                 if (lua_pcall(L, 0, 0, 0) != 0) {
1168                         fprintf(stderr, "error running chain setup callback: %s\n", lua_tostring(L, -1));
1169                         exit(1);
1170                 }
1171                 assert(lua_gettop(L) == 0);
1172
1173                 this->input_state = nullptr;
1174         };
1175
1176         // TODO: Can we do better, e.g. by running setup_chain() and seeing what it references?
1177         // Actually, setup_chain does maybe hold all the references we need now anyway?
1178         chain.input_frames.reserve(num_cards * FRAME_HISTORY_LENGTH);
1179         for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
1180                 for (unsigned frame_num = 0; frame_num < FRAME_HISTORY_LENGTH; ++frame_num) {
1181                         chain.input_frames.push_back(input_state.buffered_frames[card_index][frame_num].frame);
1182                 }
1183         }
1184
1185         return chain;
1186 }
1187
1188 string Theme::get_channel_name(unsigned channel)
1189 {
1190         unique_lock<mutex> lock(m);
1191         lua_getglobal(L, "channel_name");
1192         lua_pushnumber(L, channel);
1193         if (lua_pcall(L, 1, 1, 0) != 0) {
1194                 fprintf(stderr, "error running function `channel_name': %s\n", lua_tostring(L, -1));
1195                 exit(1);
1196         }
1197         const char *ret = lua_tostring(L, -1);
1198         if (ret == nullptr) {
1199                 fprintf(stderr, "function `channel_name' returned nil for channel %d\n", channel);
1200                 exit(1);
1201         }
1202
1203         string retstr = ret;
1204         lua_pop(L, 1);
1205         assert(lua_gettop(L) == 0);
1206         return retstr;
1207 }
1208
1209 int Theme::get_channel_signal(unsigned channel)
1210 {
1211         unique_lock<mutex> lock(m);
1212         lua_getglobal(L, "channel_signal");
1213         lua_pushnumber(L, channel);
1214         if (lua_pcall(L, 1, 1, 0) != 0) {
1215                 fprintf(stderr, "error running function `channel_signal': %s\n", lua_tostring(L, -1));
1216                 exit(1);
1217         }
1218
1219         int ret = luaL_checknumber(L, 1);
1220         lua_pop(L, 1);
1221         assert(lua_gettop(L) == 0);
1222         return ret;
1223 }
1224
1225 std::string Theme::get_channel_color(unsigned channel)
1226 {
1227         unique_lock<mutex> lock(m);
1228         lua_getglobal(L, "channel_color");
1229         lua_pushnumber(L, channel);
1230         if (lua_pcall(L, 1, 1, 0) != 0) {
1231                 fprintf(stderr, "error running function `channel_color': %s\n", lua_tostring(L, -1));
1232                 exit(1);
1233         }
1234
1235         const char *ret = lua_tostring(L, -1);
1236         if (ret == nullptr) {
1237                 fprintf(stderr, "function `channel_color' returned nil for channel %d\n", channel);
1238                 exit(1);
1239         }
1240
1241         string retstr = ret;
1242         lua_pop(L, 1);
1243         assert(lua_gettop(L) == 0);
1244         return retstr;
1245 }
1246
1247 bool Theme::get_supports_set_wb(unsigned channel)
1248 {
1249         unique_lock<mutex> lock(m);
1250         lua_getglobal(L, "supports_set_wb");
1251         lua_pushnumber(L, channel);
1252         if (lua_pcall(L, 1, 1, 0) != 0) {
1253                 fprintf(stderr, "error running function `supports_set_wb': %s\n", lua_tostring(L, -1));
1254                 exit(1);
1255         }
1256
1257         bool ret = checkbool(L, -1);
1258         lua_pop(L, 1);
1259         assert(lua_gettop(L) == 0);
1260         return ret;
1261 }
1262
1263 void Theme::set_wb(unsigned channel, double r, double g, double b)
1264 {
1265         unique_lock<mutex> lock(m);
1266         lua_getglobal(L, "set_wb");
1267         lua_pushnumber(L, channel);
1268         lua_pushnumber(L, r);
1269         lua_pushnumber(L, g);
1270         lua_pushnumber(L, b);
1271         if (lua_pcall(L, 4, 0, 0) != 0) {
1272                 fprintf(stderr, "error running function `set_wb': %s\n", lua_tostring(L, -1));
1273                 exit(1);
1274         }
1275
1276         assert(lua_gettop(L) == 0);
1277 }
1278
1279 vector<string> Theme::get_transition_names(float t)
1280 {
1281         unique_lock<mutex> lock(m);
1282         lua_getglobal(L, "get_transitions");
1283         lua_pushnumber(L, t);
1284         if (lua_pcall(L, 1, 1, 0) != 0) {
1285                 fprintf(stderr, "error running function `get_transitions': %s\n", lua_tostring(L, -1));
1286                 exit(1);
1287         }
1288
1289         vector<string> ret;
1290         lua_pushnil(L);
1291         while (lua_next(L, -2) != 0) {
1292                 ret.push_back(lua_tostring(L, -1));
1293                 lua_pop(L, 1);
1294         }
1295         lua_pop(L, 1);
1296         assert(lua_gettop(L) == 0);
1297         return ret;
1298 }       
1299
1300 int Theme::map_signal(int signal_num)
1301 {
1302         // Negative numbers map to raw signals.
1303         if (signal_num < 0) {
1304                 return -1 - signal_num;
1305         }
1306
1307         unique_lock<mutex> lock(map_m);
1308         if (signal_to_card_mapping.count(signal_num)) {
1309                 return signal_to_card_mapping[signal_num];
1310         }
1311
1312         int card_index;
1313         if (global_flags.output_card != -1 && num_cards > 1) {
1314                 // Try to exclude the output card from the default card_index.
1315                 card_index = signal_num % (num_cards - 1);
1316                 if (card_index >= global_flags.output_card) {
1317                          ++card_index;
1318                 }
1319                 if (signal_num >= int(num_cards - 1)) {
1320                         fprintf(stderr, "WARNING: Theme asked for input %d, but we only have %u input card(s) (card %d is busy with output).\n",
1321                                 signal_num, num_cards - 1, global_flags.output_card);
1322                         fprintf(stderr, "Mapping to card %d instead.\n", card_index);
1323                 }
1324         } else {
1325                 card_index = signal_num % num_cards;
1326                 if (signal_num >= int(num_cards)) {
1327                         fprintf(stderr, "WARNING: Theme asked for input %d, but we only have %u card(s).\n", signal_num, num_cards);
1328                         fprintf(stderr, "Mapping to card %d instead.\n", card_index);
1329                 }
1330         }
1331         signal_to_card_mapping[signal_num] = card_index;
1332         return card_index;
1333 }
1334
1335 void Theme::set_signal_mapping(int signal_num, int card_num)
1336 {
1337         unique_lock<mutex> lock(map_m);
1338         assert(card_num < int(num_cards));
1339         signal_to_card_mapping[signal_num] = card_num;
1340 }
1341
1342 void Theme::transition_clicked(int transition_num, float t)
1343 {
1344         unique_lock<mutex> lock(m);
1345         lua_getglobal(L, "transition_clicked");
1346         lua_pushnumber(L, transition_num);
1347         lua_pushnumber(L, t);
1348
1349         if (lua_pcall(L, 2, 0, 0) != 0) {
1350                 fprintf(stderr, "error running function `transition_clicked': %s\n", lua_tostring(L, -1));
1351                 exit(1);
1352         }
1353         assert(lua_gettop(L) == 0);
1354 }
1355
1356 void Theme::channel_clicked(int preview_num)
1357 {
1358         unique_lock<mutex> lock(m);
1359         lua_getglobal(L, "channel_clicked");
1360         lua_pushnumber(L, preview_num);
1361
1362         if (lua_pcall(L, 1, 0, 0) != 0) {
1363                 fprintf(stderr, "error running function `channel_clicked': %s\n", lua_tostring(L, -1));
1364                 exit(1);
1365         }
1366         assert(lua_gettop(L) == 0);
1367 }
1368
1369 int Theme::set_theme_menu(lua_State *L)
1370 {
1371         for (const Theme::MenuEntry &entry : theme_menu) {
1372                 luaL_unref(L, LUA_REGISTRYINDEX, entry.lua_ref);
1373         }
1374         theme_menu.clear();
1375
1376         int num_elements = lua_gettop(L);
1377         for (int i = 1; i <= num_elements; ++i) {
1378                 lua_rawgeti(L, i, 1);
1379                 const string text = checkstdstring(L, -1);
1380                 lua_pop(L, 1);
1381
1382                 lua_rawgeti(L, i, 2);
1383                 luaL_checktype(L, -1, LUA_TFUNCTION);
1384                 int ref = luaL_ref(L, LUA_REGISTRYINDEX);
1385
1386                 theme_menu.push_back(MenuEntry{ text, ref });
1387         }
1388         lua_pop(L, num_elements);
1389         assert(lua_gettop(L) == 0);
1390
1391         if (theme_menu_callback != nullptr) {
1392                 theme_menu_callback();
1393         }
1394
1395         return 0;
1396 }
1397
1398 void Theme::theme_menu_entry_clicked(int lua_ref)
1399 {
1400         lua_rawgeti(L, LUA_REGISTRYINDEX, lua_ref);
1401         if (lua_pcall(L, 0, 0, 0) != 0) {
1402                 fprintf(stderr, "error running menu callback: %s\n", lua_tostring(L, -1));
1403                 exit(1);
1404         }
1405 }