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