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