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