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