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