]> git.sesse.net Git - nageru/blob - nageru/theme.cpp
d2a7bba3144f0a4e655ffd6241a926dcb08441f5
[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 <stdarg.h>
7 #include <lauxlib.h>
8 #include <lua.hpp>
9 #include <movit/deinterlace_effect.h>
10 #include <movit/effect.h>
11 #include <movit/effect_chain.h>
12 #include <movit/image_format.h>
13 #include <movit/input.h>
14 #include <movit/lift_gamma_gain_effect.h>
15 #include <movit/mix_effect.h>
16 #include <movit/multiply_effect.h>
17 #include <movit/overlay_effect.h>
18 #include <movit/padding_effect.h>
19 #include <movit/resample_effect.h>
20 #include <movit/resize_effect.h>
21 #include <movit/util.h>
22 #include <movit/white_balance_effect.h>
23 #include <movit/ycbcr.h>
24 #include <movit/ycbcr_input.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <cstddef>
28 #include <memory>
29 #include <new>
30 #include <utility>
31
32 #include "defs.h"
33 #ifdef HAVE_CEF
34 #include "cef_capture.h"
35 #endif
36 #include "ffmpeg_capture.h"
37 #include "flags.h"
38 #include "image_input.h"
39 #include "input_state.h"
40 #include "lua_utils.h"
41 #include "pbo_frame_allocator.h"
42 #include "scene.h"
43
44 class Mixer;
45
46 namespace movit {
47 class ResourcePool;
48 }  // namespace movit
49
50 using namespace std;
51 using namespace movit;
52
53 extern Mixer *global_mixer;
54
55 constexpr unsigned Theme::MenuEntry::CHECKABLE;
56 constexpr unsigned Theme::MenuEntry::CHECKED;
57
58 Theme *get_theme_updata(lua_State* L)
59 {
60         luaL_checktype(L, lua_upvalueindex(1), LUA_TLIGHTUSERDATA);
61         return (Theme *)lua_touserdata(L, lua_upvalueindex(1));
62 }
63
64 void print_warning(lua_State* L, const char *format, ...)
65 {
66         char buf[4096];
67         va_list ap;
68         va_start(ap, format);
69         vsnprintf(buf, sizeof(buf), format, ap);
70         va_end(ap);
71
72         lua_Debug ar;
73         lua_getstack(L, 1, &ar);
74         lua_getinfo(L, "nSl", &ar);
75         fprintf(stderr, "WARNING: %s:%d: %s", ar.source, ar.currentline, buf);
76 }
77
78 int ThemeMenu_set(lua_State *L)
79 {
80         Theme *theme = get_theme_updata(L);
81         return theme->set_theme_menu(L);
82 }
83
84 InputStateInfo::InputStateInfo(const InputState &input_state)
85 {
86         for (unsigned signal_num = 0; signal_num < MAX_VIDEO_CARDS; ++signal_num) {
87                 BufferedFrame frame = input_state.buffered_frames[signal_num][0];
88                 if (frame.frame == nullptr) {
89                         last_width[signal_num] = last_height[signal_num] = 0;
90                         last_interlaced[signal_num] = false;
91                         last_has_signal[signal_num] = false;
92                         last_is_connected[signal_num] = false;
93                         continue;
94                 }
95                 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
96                 last_width[signal_num] = userdata->last_width[frame.field_number];
97                 last_height[signal_num] = userdata->last_height[frame.field_number];
98                 last_interlaced[signal_num] = userdata->last_interlaced;
99                 last_has_signal[signal_num] = userdata->last_has_signal;
100                 last_is_connected[signal_num] = userdata->last_is_connected;
101                 last_frame_rate_nom[signal_num] = userdata->last_frame_rate_nom;
102                 last_frame_rate_den[signal_num] = userdata->last_frame_rate_den;
103                 has_last_subtitle[signal_num] = userdata->has_last_subtitle;
104                 last_subtitle[signal_num] = userdata->last_subtitle;
105         }
106 }
107
108 // An effect that does nothing.
109 class IdentityEffect : public Effect {
110 public:
111         IdentityEffect() {}
112         string effect_type_id() const override { return "IdentityEffect"; }
113         string output_fragment_shader() override { return read_file("identity.frag"); }
114 };
115
116 Effect *instantiate_effect(EffectChain *chain, EffectType effect_type)
117 {
118         switch (effect_type) {
119         case IDENTITY_EFFECT:
120                 return new IdentityEffect;
121         case WHITE_BALANCE_EFFECT:
122         case AUTO_WHITE_BALANCE_EFFECT:
123                 return new WhiteBalanceEffect;
124         case RESAMPLE_EFFECT:
125                 return new ResampleEffect;
126         case PADDING_EFFECT:
127                 return new PaddingEffect;
128         case INTEGRAL_PADDING_EFFECT:
129                 return new IntegralPaddingEffect;
130         case OVERLAY_EFFECT:
131                 return new OverlayEffect;
132         case RESIZE_EFFECT:
133                 return new ResizeEffect;
134         case MULTIPLY_EFFECT:
135                 return new MultiplyEffect;
136         case MIX_EFFECT:
137                 return new MixEffect;
138         case LIFT_GAMMA_GAIN_EFFECT:
139                 return new LiftGammaGainEffect;
140         default:
141                 fprintf(stderr, "Unhandled effect type %d\n", effect_type);
142                 abort();
143         }
144 }
145
146 namespace {
147
148 Effect *get_effect_from_blueprint(EffectChain *chain, lua_State *L, int idx)
149 {
150         EffectBlueprint *blueprint = *(EffectBlueprint **)luaL_checkudata(L, idx, "EffectBlueprint");
151         if (blueprint->effect != nullptr) {
152                 luaL_error(L, "An effect can currently only be added to one chain.\n");
153         }
154
155         Effect *effect = instantiate_effect(chain, blueprint->effect_type);
156
157         // Set the parameters that were deferred earlier.
158         for (const auto &kv : blueprint->int_parameters) {
159                 if (!effect->set_int(kv.first, kv.second)) {
160                         luaL_error(L, "Effect refused set_int(\"%s\", %d) (invalid key?)", kv.first.c_str(), kv.second);
161                 }
162         }
163         for (const auto &kv : blueprint->float_parameters) {
164                 if (!effect->set_float(kv.first, kv.second)) {
165                         luaL_error(L, "Effect refused set_float(\"%s\", %f) (invalid key?)", kv.first.c_str(), kv.second);
166                 }
167         }
168         for (const auto &kv : blueprint->vec3_parameters) {
169                 if (!effect->set_vec3(kv.first, kv.second.data())) {
170                         luaL_error(L, "Effect refused set_vec3(\"%s\", %f, %f, %f) (invalid key?)", kv.first.c_str(),
171                                 kv.second[0], kv.second[1], kv.second[2]);
172                 }
173         }
174         for (const auto &kv : blueprint->vec4_parameters) {
175                 if (!effect->set_vec4(kv.first, kv.second.data())) {
176                         luaL_error(L, "Effect refused set_vec4(\"%s\", %f, %f, %f, %f) (invalid key?)", kv.first.c_str(),
177                                 kv.second[0], kv.second[1], kv.second[2], kv.second[3]);
178                 }
179         }
180         blueprint->effect = effect;
181         return effect;
182 }
183
184 InputStateInfo *get_input_state_info(lua_State *L, int idx)
185 {
186         if (luaL_testudata(L, idx, "InputStateInfo")) {
187                 return (InputStateInfo *)lua_touserdata(L, idx);
188         }
189         luaL_error(L, "Error: Index #%d was not InputStateInfo\n", idx);
190         return nullptr;
191 }
192
193 }  // namespace
194
195 bool checkbool(lua_State* L, int idx)
196 {
197         luaL_checktype(L, idx, LUA_TBOOLEAN);
198         return lua_toboolean(L, idx);
199 }
200
201 string checkstdstring(lua_State *L, int index)
202 {
203         size_t len;
204         const char* cstr = lua_tolstring(L, index, &len);
205         return string(cstr, len);
206 }
207
208 namespace {
209
210 int Scene_new(lua_State* L)
211 {
212         assert(lua_gettop(L) == 2);
213         Theme *theme = get_theme_updata(L);
214         int aspect_w = luaL_checknumber(L, 1);
215         int aspect_h = luaL_checknumber(L, 2);
216
217         return wrap_lua_object<Scene>(L, "Scene", theme, aspect_w, aspect_h);
218 }
219
220 int Scene_gc(lua_State* L)
221 {
222         assert(lua_gettop(L) == 1);
223         Scene *chain = (Scene *)luaL_checkudata(L, 1, "Scene");
224         chain->~Scene();
225         return 0;
226 }
227
228 }  // namespace
229
230 void add_outputs_and_finalize(EffectChain *chain, bool is_main_chain)
231 {
232         // Add outputs as needed.
233         // NOTE: If you change any details about the output format, you will need to
234         // also update what's given to the muxer (HTTPD::Mux constructor) and
235         // what's put in the H.264 stream (sps_rbsp()).
236         ImageFormat inout_format;
237         inout_format.color_space = COLORSPACE_REC_709;
238
239         // Output gamma is tricky. We should output Rec. 709 for TV, except that
240         // we expect to run with web players and others that don't really care and
241         // just output with no conversion. So that means we'll need to output sRGB,
242         // even though H.264 has no setting for that (we use “unspecified”).
243         inout_format.gamma_curve = GAMMA_sRGB;
244
245         if (is_main_chain) {
246                 YCbCrFormat output_ycbcr_format;
247                 // We actually output 4:2:0 and/or 4:2:2 in the end, but chroma subsampling
248                 // happens in a pass not run by Movit (see ChromaSubsampler::subsample_chroma()).
249                 output_ycbcr_format.chroma_subsampling_x = 1;
250                 output_ycbcr_format.chroma_subsampling_y = 1;
251
252                 // This will be overridden if HDMI/SDI output is in force.
253                 if (global_flags.ycbcr_rec709_coefficients) {
254                         output_ycbcr_format.luma_coefficients = YCBCR_REC_709;
255                 } else {
256                         output_ycbcr_format.luma_coefficients = YCBCR_REC_601;
257                 }
258
259                 output_ycbcr_format.full_range = false;
260                 output_ycbcr_format.num_levels = 1 << global_flags.x264_bit_depth;
261
262                 GLenum type = global_flags.x264_bit_depth > 8 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_BYTE;
263
264                 chain->add_ycbcr_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED, output_ycbcr_format, YCBCR_OUTPUT_SPLIT_Y_AND_CBCR, type);
265
266                 // If we're using zerocopy video encoding (so the destination
267                 // Y texture is owned by VA-API and will be unavailable for
268                 // display), add a copy, where we'll only be using the Y component.
269                 if (global_flags.use_zerocopy) {
270                         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.
271                 }
272                 chain->set_dither_bits(global_flags.x264_bit_depth > 8 ? 16 : 8);
273                 chain->set_output_origin(OUTPUT_ORIGIN_TOP_LEFT);
274         } else {
275                 chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
276         }
277
278         chain->finalize();
279 }
280
281 namespace {
282
283 int EffectChain_new(lua_State* L)
284 {
285         assert(lua_gettop(L) == 2);
286         Theme *theme = get_theme_updata(L);
287         int aspect_w = luaL_checknumber(L, 1);
288         int aspect_h = luaL_checknumber(L, 2);
289
290         return wrap_lua_object<EffectChain>(L, "EffectChain", aspect_w, aspect_h, theme->get_resource_pool());
291 }
292
293 int EffectChain_gc(lua_State* L)
294 {
295         assert(lua_gettop(L) == 1);
296         EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
297         chain->~EffectChain();
298         return 0;
299 }
300
301 int EffectChain_add_live_input(lua_State* L)
302 {
303         assert(lua_gettop(L) == 3);
304         Theme *theme = get_theme_updata(L);
305         EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
306         bool override_bounce = checkbool(L, 2);
307         bool deinterlace = checkbool(L, 3);
308         bmusb::PixelFormat pixel_format = global_flags.ten_bit_input ? bmusb::PixelFormat_10BitYCbCr : bmusb::PixelFormat_8BitYCbCr;
309
310         // Needs to be nonowned to match add_video_input (see below).
311         return wrap_lua_object_nonowned<LiveInputWrapper>(L, "LiveInputWrapper", theme, chain, pixel_format, override_bounce, deinterlace, /*user_connectable=*/true);
312 }
313
314 int EffectChain_add_video_input(lua_State* L)
315 {
316         assert(lua_gettop(L) == 3);
317         Theme *theme = get_theme_updata(L);
318         EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
319         FFmpegCapture **capture = (FFmpegCapture **)luaL_checkudata(L, 2, "VideoInput");
320         bool deinterlace = checkbool(L, 3);
321
322         // These need to be nonowned, so that the LiveInputWrapper still exists
323         // and can feed frames to the right EffectChain even if the Lua code
324         // doesn't care about the object anymore. (If we change this, we'd need
325         // to also unregister the signal connection on __gc.)
326         int ret = wrap_lua_object_nonowned<LiveInputWrapper>(
327                 L, "LiveInputWrapper", theme, chain, (*capture)->get_current_pixel_format(),
328                 /*override_bounce=*/false, deinterlace, /*user_connectable=*/false);
329         if (ret == 1) {
330                 Theme *theme = get_theme_updata(L);
331                 LiveInputWrapper **live_input = (LiveInputWrapper **)lua_touserdata(L, -1);
332                 theme->register_video_signal_connection(chain, *live_input, *capture);
333         }
334         return ret;
335 }
336
337 #ifdef HAVE_CEF
338 int EffectChain_add_html_input(lua_State* L)
339 {
340         assert(lua_gettop(L) == 2);
341         Theme *theme = get_theme_updata(L);
342         EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
343         CEFCapture **capture = (CEFCapture **)luaL_checkudata(L, 2, "HTMLInput");
344
345         // These need to be nonowned, so that the LiveInputWrapper still exists
346         // and can feed frames to the right EffectChain even if the Lua code
347         // doesn't care about the object anymore. (If we change this, we'd need
348         // to also unregister the signal connection on __gc.)
349         int ret = wrap_lua_object_nonowned<LiveInputWrapper>(
350                 L, "LiveInputWrapper", theme, chain, (*capture)->get_current_pixel_format(),
351                 /*override_bounce=*/false, /*deinterlace=*/false, /*user_connectable=*/false);
352         if (ret == 1) {
353                 Theme *theme = get_theme_updata(L);
354                 LiveInputWrapper **live_input = (LiveInputWrapper **)lua_touserdata(L, -1);
355                 theme->register_html_signal_connection(chain, *live_input, *capture);
356         }
357         return ret;
358 }
359 #endif
360
361 int EffectChain_add_effect(lua_State* L)
362 {
363         assert(lua_gettop(L) >= 2);
364         EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
365
366         // TODO: Better error reporting.
367         Effect *effect;
368         if (luaL_testudata(L, 2, "ImageInput")) {
369                 effect = *(ImageInput **)luaL_checkudata(L, 2, "ImageInput");
370         } else {
371                 effect = get_effect_from_blueprint(chain, L, 2);
372         }
373         if (lua_gettop(L) == 2) {
374                 if (effect->num_inputs() == 0) {
375                         chain->add_input((Input *)effect);
376                 } else {
377                         chain->add_effect(effect);
378                 }
379         } else {
380                 vector<Effect *> inputs;
381                 for (int idx = 3; idx <= lua_gettop(L); ++idx) {
382                         if (luaL_testudata(L, idx, "LiveInputWrapper")) {
383                                 LiveInputWrapper **input = (LiveInputWrapper **)lua_touserdata(L, idx);
384                                 inputs.push_back((*input)->get_effect());
385                         } else if (luaL_testudata(L, idx, "ImageInput")) {
386                                 ImageInput *image = *(ImageInput **)luaL_checkudata(L, idx, "ImageInput");
387                                 inputs.push_back(image);
388                         } else {
389                                 EffectBlueprint *blueprint = *(EffectBlueprint **)luaL_checkudata(L, idx, "EffectBlueprint");
390                                 assert(blueprint->effect != nullptr);  // Parent must be added to the graph.
391                                 inputs.push_back(blueprint->effect);
392                         }
393                 }
394                 chain->add_effect(effect, inputs);
395         }
396
397         lua_settop(L, 2);  // Return the effect itself.
398
399         // Make sure Lua doesn't garbage-collect it away.
400         lua_pushvalue(L, -1);
401         luaL_ref(L, LUA_REGISTRYINDEX);  // TODO: leak?
402
403         return 1;
404 }
405
406 int EffectChain_finalize(lua_State* L)
407 {
408         assert(lua_gettop(L) == 2);
409         EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
410         bool is_main_chain = checkbool(L, 2);
411         add_outputs_and_finalize(chain, is_main_chain);
412         return 0;
413 }
414
415 int LiveInputWrapper_connect_signal(lua_State* L)
416 {
417         assert(lua_gettop(L) == 2);
418         LiveInputWrapper **input = (LiveInputWrapper **)luaL_checkudata(L, 1, "LiveInputWrapper");
419         int signal_num = luaL_checknumber(L, 2);
420         bool success = (*input)->connect_signal(signal_num);
421         if (!success) {
422                 print_warning(L, "Calling connect_signal() on a video or HTML input. Ignoring.\n");
423         }
424         return 0;
425 }
426
427 int ImageInput_new(lua_State* L)
428 {
429         assert(lua_gettop(L) == 1);
430         string filename = checkstdstring(L, 1);
431         return wrap_lua_object_nonowned<ImageInput>(L, "ImageInput", filename);
432 }
433
434 int VideoInput_new(lua_State* L)
435 {
436         assert(lua_gettop(L) == 2);
437         string filename = checkstdstring(L, 1);
438         int pixel_format = luaL_checknumber(L, 2);
439         if (pixel_format != bmusb::PixelFormat_8BitYCbCrPlanar &&
440             pixel_format != bmusb::PixelFormat_8BitBGRA) {
441                 print_warning(L, "Invalid enum %d used for video format, choosing Y'CbCr.\n", pixel_format);
442                 pixel_format = bmusb::PixelFormat_8BitYCbCrPlanar;
443         }
444         int ret = wrap_lua_object_nonowned<FFmpegCapture>(L, "VideoInput", filename, global_flags.width, global_flags.height);
445         if (ret == 1) {
446                 FFmpegCapture **capture = (FFmpegCapture **)lua_touserdata(L, -1);
447                 (*capture)->set_pixel_format(bmusb::PixelFormat(pixel_format));
448
449                 Theme *theme = get_theme_updata(L);
450                 theme->register_video_input(*capture);
451         }
452         return ret;
453 }
454
455 int VideoInput_rewind(lua_State* L)
456 {
457         assert(lua_gettop(L) == 1);
458         FFmpegCapture **video_input = (FFmpegCapture **)luaL_checkudata(L, 1, "VideoInput");
459         (*video_input)->rewind();
460         return 0;
461 }
462
463 int VideoInput_disconnect(lua_State* L)
464 {
465         assert(lua_gettop(L) == 1);
466         FFmpegCapture **video_input = (FFmpegCapture **)luaL_checkudata(L, 1, "VideoInput");
467         (*video_input)->disconnect();
468         return 0;
469 }
470
471 int VideoInput_change_rate(lua_State* L)
472 {
473         assert(lua_gettop(L) == 2);
474         FFmpegCapture **video_input = (FFmpegCapture **)luaL_checkudata(L, 1, "VideoInput");
475         double new_rate = luaL_checknumber(L, 2);
476         (*video_input)->change_rate(new_rate);
477         return 0;
478 }
479
480 int VideoInput_get_signal_num(lua_State* L)
481 {
482         assert(lua_gettop(L) == 1);
483         FFmpegCapture **video_input = (FFmpegCapture **)luaL_checkudata(L, 1, "VideoInput");
484         lua_pushnumber(L, -1 - (*video_input)->get_card_index());
485         return 1;
486 }
487
488 int HTMLInput_new(lua_State* L)
489 {
490 #ifdef HAVE_CEF
491         assert(lua_gettop(L) == 1);
492         string url = checkstdstring(L, 1);
493         int ret = wrap_lua_object_nonowned<CEFCapture>(L, "HTMLInput", url, global_flags.width, global_flags.height);
494         if (ret == 1) {
495                 CEFCapture **capture = (CEFCapture **)lua_touserdata(L, -1);
496                 Theme *theme = get_theme_updata(L);
497                 theme->register_html_input(*capture);
498         }
499         return ret;
500 #else
501         fprintf(stderr, "This version of Nageru has been compiled without CEF support.\n");
502         fprintf(stderr, "HTMLInput is not available.\n");
503         abort();
504 #endif
505 }
506
507 #ifdef HAVE_CEF
508 int HTMLInput_set_url(lua_State* L)
509 {
510         assert(lua_gettop(L) == 2);
511         CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
512         string new_url = checkstdstring(L, 2);
513         (*video_input)->set_url(new_url);
514         return 0;
515 }
516
517 int HTMLInput_reload(lua_State* L)
518 {
519         assert(lua_gettop(L) == 1);
520         CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
521         (*video_input)->reload();
522         return 0;
523 }
524
525 int HTMLInput_set_max_fps(lua_State* L)
526 {
527         assert(lua_gettop(L) == 2);
528         CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
529         int max_fps = lrint(luaL_checknumber(L, 2));
530         (*video_input)->set_max_fps(max_fps);
531         return 0;
532 }
533
534 int HTMLInput_execute_javascript_async(lua_State* L)
535 {
536         assert(lua_gettop(L) == 2);
537         CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
538         string js = checkstdstring(L, 2);
539         (*video_input)->execute_javascript_async(js);
540         return 0;
541 }
542
543 int HTMLInput_resize(lua_State* L)
544 {
545         assert(lua_gettop(L) == 3);
546         CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
547         unsigned width = lrint(luaL_checknumber(L, 2));
548         unsigned height = lrint(luaL_checknumber(L, 3));
549         (*video_input)->resize(width, height);
550         return 0;
551 }
552
553 int HTMLInput_get_signal_num(lua_State* L)
554 {
555         assert(lua_gettop(L) == 1);
556         CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
557         lua_pushnumber(L, -1 - (*video_input)->get_card_index());
558         return 1;
559 }
560 #endif
561
562 int IdentityEffect_new(lua_State* L)
563 {
564         assert(lua_gettop(L) == 0);
565         return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", IDENTITY_EFFECT);
566 }
567
568 int WhiteBalanceEffect_new(lua_State* L)
569 {
570         assert(lua_gettop(L) == 0);
571         return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", WHITE_BALANCE_EFFECT);
572 }
573
574 int ResampleEffect_new(lua_State* L)
575 {
576         assert(lua_gettop(L) == 0);
577         return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", RESAMPLE_EFFECT);
578 }
579
580 int PaddingEffect_new(lua_State* L)
581 {
582         assert(lua_gettop(L) == 0);
583         return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", PADDING_EFFECT);
584 }
585
586 int IntegralPaddingEffect_new(lua_State* L)
587 {
588         assert(lua_gettop(L) == 0);
589         return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", INTEGRAL_PADDING_EFFECT);
590 }
591
592 int OverlayEffect_new(lua_State* L)
593 {
594         assert(lua_gettop(L) == 0);
595         return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", OVERLAY_EFFECT);
596 }
597
598 int ResizeEffect_new(lua_State* L)
599 {
600         assert(lua_gettop(L) == 0);
601         return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", RESIZE_EFFECT);
602 }
603
604 int MultiplyEffect_new(lua_State* L)
605 {
606         assert(lua_gettop(L) == 0);
607         return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", MULTIPLY_EFFECT);
608 }
609
610 int MixEffect_new(lua_State* L)
611 {
612         assert(lua_gettop(L) == 0);
613         return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", MIX_EFFECT);
614 }
615
616 int LiftGammaGainEffect_new(lua_State* L)
617 {
618         assert(lua_gettop(L) == 0);
619         return wrap_lua_object_nonowned<EffectBlueprint>(L, "EffectBlueprint", LIFT_GAMMA_GAIN_EFFECT);
620 }
621
622 int InputStateInfo_get_width(lua_State* L)
623 {
624         assert(lua_gettop(L) == 2);
625         InputStateInfo *input_state_info = get_input_state_info(L, 1);
626
627         Theme *theme = get_theme_updata(L);
628         int signal_num = theme->map_signal(luaL_checknumber(L, 2));
629         lua_pushnumber(L, input_state_info->last_width[signal_num]);
630         return 1;
631 }
632
633 int InputStateInfo_get_height(lua_State* L)
634 {
635         assert(lua_gettop(L) == 2);
636         InputStateInfo *input_state_info = get_input_state_info(L, 1);
637         Theme *theme = get_theme_updata(L);
638         int signal_num = theme->map_signal(luaL_checknumber(L, 2));
639         lua_pushnumber(L, input_state_info->last_height[signal_num]);
640         return 1;
641 }
642
643 int InputStateInfo_get_frame_height(lua_State* L)
644 {
645         assert(lua_gettop(L) == 2);
646         InputStateInfo *input_state_info = get_input_state_info(L, 1);
647         Theme *theme = get_theme_updata(L);
648         int signal_num = theme->map_signal(luaL_checknumber(L, 2));
649         unsigned height = input_state_info->last_height[signal_num];
650         if (input_state_info->last_interlaced[signal_num]) {
651                 height *= 2;
652         }
653         lua_pushnumber(L, height);
654         return 1;
655 }
656
657 int InputStateInfo_get_interlaced(lua_State* L)
658 {
659         assert(lua_gettop(L) == 2);
660         InputStateInfo *input_state_info = get_input_state_info(L, 1);
661         Theme *theme = get_theme_updata(L);
662         int signal_num = theme->map_signal(luaL_checknumber(L, 2));
663         lua_pushboolean(L, input_state_info->last_interlaced[signal_num]);
664         return 1;
665 }
666
667 int InputStateInfo_get_has_signal(lua_State* L)
668 {
669         assert(lua_gettop(L) == 2);
670         InputStateInfo *input_state_info = get_input_state_info(L, 1);
671         Theme *theme = get_theme_updata(L);
672         int signal_num = theme->map_signal(luaL_checknumber(L, 2));
673         lua_pushboolean(L, input_state_info->last_has_signal[signal_num]);
674         return 1;
675 }
676
677 int InputStateInfo_get_is_connected(lua_State* L)
678 {
679         assert(lua_gettop(L) == 2);
680         InputStateInfo *input_state_info = get_input_state_info(L, 1);
681         Theme *theme = get_theme_updata(L);
682         int signal_num = theme->map_signal(luaL_checknumber(L, 2));
683         lua_pushboolean(L, input_state_info->last_is_connected[signal_num]);
684         return 1;
685 }
686
687 int InputStateInfo_get_frame_rate_nom(lua_State* L)
688 {
689         assert(lua_gettop(L) == 2);
690         InputStateInfo *input_state_info = get_input_state_info(L, 1);
691         Theme *theme = get_theme_updata(L);
692         int signal_num = theme->map_signal(luaL_checknumber(L, 2));
693         lua_pushnumber(L, input_state_info->last_frame_rate_nom[signal_num]);
694         return 1;
695 }
696
697 int InputStateInfo_get_frame_rate_den(lua_State* L)
698 {
699         assert(lua_gettop(L) == 2);
700         InputStateInfo *input_state_info = get_input_state_info(L, 1);
701         Theme *theme = get_theme_updata(L);
702         int signal_num = theme->map_signal(luaL_checknumber(L, 2));
703         lua_pushnumber(L, input_state_info->last_frame_rate_den[signal_num]);
704         return 1;
705 }
706
707 int InputStateInfo_get_last_subtitle(lua_State* L)
708 {
709         assert(lua_gettop(L) == 2);
710         InputStateInfo *input_state_info = get_input_state_info(L, 1);
711         Theme *theme = get_theme_updata(L);
712         int signal_num = theme->map_signal(luaL_checknumber(L, 2));
713         if (!input_state_info->has_last_subtitle[signal_num]) {
714                 lua_pushnil(L);
715         } else {
716                 lua_pushstring(L, input_state_info->last_subtitle[signal_num].c_str());
717         }
718         return 1;
719 }
720
721 namespace {
722
723 // Helper function to write e.g. “60” or “59.94”.
724 string format_frame_rate(int nom, int den)
725 {
726         char buf[256];
727         if (nom % den == 0) {
728                 snprintf(buf, sizeof(buf), "%d", nom / den);
729         } else {
730                 snprintf(buf, sizeof(buf), "%.2f", double(nom) / den);
731         }
732         return buf;
733 }
734
735 // Helper function to write e.g. “720p60”.
736 string get_human_readable_resolution(const InputStateInfo *input_state_info, int signal_num)
737 {
738         char buf[256];
739         if (input_state_info->last_interlaced[signal_num]) {
740                 snprintf(buf, sizeof(buf), "%di", input_state_info->last_height[signal_num] * 2);
741
742                 // Show field rate instead of frame rate; really for cosmetics only
743                 // (and actually contrary to EBU recommendations, although in line
744                 // with typical user expectations).
745                 return buf + format_frame_rate(input_state_info->last_frame_rate_nom[signal_num] * 2,
746                         input_state_info->last_frame_rate_den[signal_num]);
747         } else {
748                 snprintf(buf, sizeof(buf), "%dp", input_state_info->last_height[signal_num]);
749                 return buf + format_frame_rate(input_state_info->last_frame_rate_nom[signal_num],
750                         input_state_info->last_frame_rate_den[signal_num]);
751         }
752 }
753
754 } // namespace
755
756 int InputStateInfo_get_human_readable_resolution(lua_State* L)
757 {
758         assert(lua_gettop(L) == 2);
759         InputStateInfo *input_state_info = get_input_state_info(L, 1);
760         Theme *theme = get_theme_updata(L);
761         int signal_num = theme->map_signal(luaL_checknumber(L, 2));
762
763         string str;
764         if (!input_state_info->last_is_connected[signal_num]) {
765                 str = "disconnected";
766         } else if (input_state_info->last_height[signal_num] <= 0) {
767                 str = "no signal";
768         } else if (!input_state_info->last_has_signal[signal_num]) {
769                 if (input_state_info->last_height[signal_num] == 525) {
770                         // Special mode for the USB3 cards.
771                         str = "no signal";
772                 } else {
773                         str = get_human_readable_resolution(input_state_info, signal_num) + ", no signal";
774                 }
775         } else {
776                 str = get_human_readable_resolution(input_state_info, signal_num);
777         }
778
779         lua_pushstring(L, str.c_str());
780         return 1;
781 }
782
783
784 int EffectBlueprint_set_int(lua_State *L)
785 {
786         assert(lua_gettop(L) == 3);
787         EffectBlueprint *blueprint = *(EffectBlueprint **)luaL_checkudata(L, 1, "EffectBlueprint");
788         string key = checkstdstring(L, 2);
789         float value = luaL_checknumber(L, 3);
790         if (blueprint->effect != nullptr) {
791                 if (!blueprint->effect->set_int(key, value)) {
792                         luaL_error(L, "Effect refused set_int(\"%s\", %d) (invalid key?)", key.c_str(), int(value));
793                 }
794         } else {
795                 // TODO: check validity already here, if possible?
796                 blueprint->int_parameters[key] = value;
797         }
798         return 0;
799 }
800
801 int EffectBlueprint_set_float(lua_State *L)
802 {
803         assert(lua_gettop(L) == 3);
804         EffectBlueprint *blueprint = *(EffectBlueprint **)luaL_checkudata(L, 1, "EffectBlueprint");
805         string key = checkstdstring(L, 2);
806         float value = luaL_checknumber(L, 3);
807         if (blueprint->effect != nullptr) {
808                 if (!blueprint->effect->set_float(key, value)) {
809                         luaL_error(L, "Effect refused set_float(\"%s\", %d) (invalid key?)", key.c_str(), int(value));
810                 }
811         } else {
812                 // TODO: check validity already here, if possible?
813                 blueprint->float_parameters[key] = value;
814         }
815         return 0;
816 }
817
818 int EffectBlueprint_set_vec3(lua_State *L)
819 {
820         assert(lua_gettop(L) == 5);
821         EffectBlueprint *blueprint = *(EffectBlueprint **)luaL_checkudata(L, 1, "EffectBlueprint");
822         string key = checkstdstring(L, 2);
823         array<float, 3> v;
824         v[0] = luaL_checknumber(L, 3);
825         v[1] = luaL_checknumber(L, 4);
826         v[2] = luaL_checknumber(L, 5);
827
828         if (blueprint->effect != nullptr) {
829                 if (!blueprint->effect->set_vec3(key, v.data())) {
830                         luaL_error(L, "Effect refused set_vec3(\"%s\", %f, %f, %f) (invalid key?)", key.c_str(),
831                                 v[0], v[1], v[2]);
832                 }
833         } else {
834                 // TODO: check validity already here, if possible?
835                 blueprint->vec3_parameters[key] = v;
836         }
837
838         return 0;
839 }
840
841 int EffectBlueprint_set_vec4(lua_State *L)
842 {
843         assert(lua_gettop(L) == 6);
844         EffectBlueprint *blueprint = *(EffectBlueprint **)luaL_checkudata(L, 1, "EffectBlueprint");
845         string key = checkstdstring(L, 2);
846         array<float, 4> v;
847         v[0] = luaL_checknumber(L, 3);
848         v[1] = luaL_checknumber(L, 4);
849         v[2] = luaL_checknumber(L, 5);
850         v[3] = luaL_checknumber(L, 6);
851         if (blueprint->effect != nullptr) {
852                 if (!blueprint->effect->set_vec4(key, v.data())) {
853                         luaL_error(L, "Effect refused set_vec4(\"%s\", %f, %f, %f, %f) (invalid key?)", key.c_str(),
854                                 v[0], v[1], v[2], v[3]);
855                 }
856         } else {
857                 // TODO: check validity already here, if possible?
858                 blueprint->vec4_parameters[key] = v;
859         }
860         return 0;
861 }
862
863 const luaL_Reg Scene_funcs[] = {
864         { "new", Scene_new },
865         { "__gc", Scene_gc },
866         { "add_input", Scene::add_input },
867         { "add_auto_white_balance", Scene::add_auto_white_balance },
868         { "add_effect", Scene::add_effect },
869         { "add_optional_effect", Scene::add_optional_effect },
870         { "finalize", Scene::finalize },
871         { NULL, NULL }
872 };
873
874 const luaL_Reg Block_funcs[] = {
875         { "display", Block_display },
876         { "choose", Block_choose },
877         { "enable", Block_enable },
878         { "enable_if", Block_enable_if },
879         { "disable", Block_disable },
880         { "always_disable_if_disabled", Block_always_disable_if_disabled },
881         { "promise_to_disable_if_enabled", Block_promise_to_disable_if_enabled },
882         { "set_int", Block_set_int },
883         { "set_float", Block_set_float },
884         { "set_vec3", Block_set_vec3 },
885         { "set_vec4", Block_set_vec4 },
886         { NULL, NULL }
887 };
888
889 const luaL_Reg EffectBlueprint_funcs[] = {
890         // NOTE: No new() function; that's for the individual effects.
891         { "set_int", EffectBlueprint_set_int },
892         { "set_float", EffectBlueprint_set_float },
893         { "set_vec3", EffectBlueprint_set_vec3 },
894         { "set_vec4", EffectBlueprint_set_vec4 },
895         { NULL, NULL }
896 };
897
898 const luaL_Reg EffectChain_funcs[] = {
899         { "new", EffectChain_new },
900         { "__gc", EffectChain_gc },
901         { "add_live_input", EffectChain_add_live_input },
902         { "add_video_input", EffectChain_add_video_input },
903 #ifdef HAVE_CEF
904         { "add_html_input", EffectChain_add_html_input },
905 #endif
906         { "add_effect", EffectChain_add_effect },
907         { "finalize", EffectChain_finalize },
908         { NULL, NULL }
909 };
910
911 const luaL_Reg LiveInputWrapper_funcs[] = {
912         { "connect_signal", LiveInputWrapper_connect_signal },
913         { NULL, NULL }
914 };
915
916 const luaL_Reg ImageInput_funcs[] = {
917         { "new", ImageInput_new },
918         { NULL, NULL }
919 };
920
921 const luaL_Reg VideoInput_funcs[] = {
922         { "new", VideoInput_new },
923         { "rewind", VideoInput_rewind },
924         { "disconnect", VideoInput_disconnect },
925         { "change_rate", VideoInput_change_rate },
926         { "get_signal_num", VideoInput_get_signal_num },
927         { NULL, NULL }
928 };
929
930 const luaL_Reg HTMLInput_funcs[] = {
931         { "new", HTMLInput_new },
932 #ifdef HAVE_CEF
933         { "set_url", HTMLInput_set_url },
934         { "reload", HTMLInput_reload },
935         { "set_max_fps", HTMLInput_set_max_fps },
936         { "execute_javascript_async", HTMLInput_execute_javascript_async },
937         { "resize", HTMLInput_resize },
938         { "get_signal_num", HTMLInput_get_signal_num },
939 #endif
940         { NULL, NULL }
941 };
942
943 // Effects.
944 // All of these are solely for new(); the returned metatable will be that of
945 // EffectBlueprint, and Effect (returned from add_effect()) is its own type.
946
947 const luaL_Reg IdentityEffect_funcs[] = {
948         { "new", IdentityEffect_new },
949         { NULL, NULL }
950 };
951
952 const luaL_Reg WhiteBalanceEffect_funcs[] = {
953         { "new", WhiteBalanceEffect_new },
954         { NULL, NULL }
955 };
956
957 const luaL_Reg ResampleEffect_funcs[] = {
958         { "new", ResampleEffect_new },
959         { NULL, NULL }
960 };
961
962 const luaL_Reg PaddingEffect_funcs[] = {
963         { "new", PaddingEffect_new },
964         { NULL, NULL }
965 };
966
967 const luaL_Reg IntegralPaddingEffect_funcs[] = {
968         { "new", IntegralPaddingEffect_new },
969         { NULL, NULL }
970 };
971
972 const luaL_Reg OverlayEffect_funcs[] = {
973         { "new", OverlayEffect_new },
974         { NULL, NULL }
975 };
976
977 const luaL_Reg ResizeEffect_funcs[] = {
978         { "new", ResizeEffect_new },
979         { NULL, NULL }
980 };
981
982 const luaL_Reg MultiplyEffect_funcs[] = {
983         { "new", MultiplyEffect_new },
984         { NULL, NULL }
985 };
986
987 const luaL_Reg MixEffect_funcs[] = {
988         { "new", MixEffect_new },
989         { NULL, NULL }
990 };
991
992 const luaL_Reg LiftGammaGainEffect_funcs[] = {
993         { "new", LiftGammaGainEffect_new },
994         { NULL, NULL }
995 };
996
997 // End of effects.
998
999 const luaL_Reg InputStateInfo_funcs[] = {
1000         { "get_width", InputStateInfo_get_width },
1001         { "get_height", InputStateInfo_get_height },
1002         { "get_frame_width", InputStateInfo_get_width },  // Same as get_width().
1003         { "get_frame_height", InputStateInfo_get_frame_height },
1004         { "get_interlaced", InputStateInfo_get_interlaced },
1005         { "get_has_signal", InputStateInfo_get_has_signal },
1006         { "get_is_connected", InputStateInfo_get_is_connected },
1007         { "get_frame_rate_nom", InputStateInfo_get_frame_rate_nom },
1008         { "get_frame_rate_den", InputStateInfo_get_frame_rate_den },
1009         { "get_last_subtitle", InputStateInfo_get_last_subtitle },
1010         { "get_human_readable_resolution", InputStateInfo_get_human_readable_resolution },
1011         { NULL, NULL }
1012 };
1013
1014 const luaL_Reg ThemeMenu_funcs[] = {
1015         { "set", ThemeMenu_set },
1016         { NULL, NULL }
1017 };
1018
1019 }  // namespace
1020
1021 LiveInputWrapper::LiveInputWrapper(
1022         Theme *theme,
1023         EffectChain *chain,
1024         bmusb::PixelFormat pixel_format,
1025         bool override_bounce,
1026         bool deinterlace,
1027         bool user_connectable)
1028         : theme(theme),
1029           pixel_format(pixel_format),
1030           deinterlace(deinterlace),
1031           user_connectable(user_connectable)
1032 {
1033         ImageFormat inout_format;
1034         inout_format.color_space = COLORSPACE_sRGB;
1035
1036         // Gamma curve depends on the input signal, and we don't really get any
1037         // indications. A camera would be expected to do Rec. 709, but
1038         // I haven't checked if any do in practice. However, computers _do_ output
1039         // in sRGB gamma (ie., they don't convert from sRGB to Rec. 709), and
1040         // I wouldn't really be surprised if most non-professional cameras do, too.
1041         // So we pick sRGB as the least evil here.
1042         inout_format.gamma_curve = GAMMA_sRGB;
1043
1044         unsigned num_inputs;
1045         if (deinterlace) {
1046                 deinterlace_effect = new movit::DeinterlaceEffect();
1047
1048                 // As per the comments in deinterlace_effect.h, we turn this off.
1049                 // The most likely interlaced input for us is either a camera
1050                 // (where it's fine to turn it off) or a laptop (where it _should_
1051                 // be turned off).
1052                 CHECK(deinterlace_effect->set_int("enable_spatial_interlacing_check", 0));
1053
1054                 num_inputs = deinterlace_effect->num_inputs();
1055                 assert(num_inputs == FRAME_HISTORY_LENGTH);
1056         } else {
1057                 num_inputs = 1;
1058         }
1059
1060         if (pixel_format == bmusb::PixelFormat_8BitBGRA) {
1061                 for (unsigned i = 0; i < num_inputs; ++i) {
1062                         // We upload our textures ourselves, and Movit swaps
1063                         // R and B in the shader if we specify BGRA, so lie and say RGBA.
1064                         rgba_inputs.push_back(new sRGBSwitchingFlatInput(inout_format, FORMAT_RGBA_POSTMULTIPLIED_ALPHA, GL_UNSIGNED_BYTE, global_flags.width, global_flags.height));
1065                         chain->add_input(rgba_inputs.back());
1066                 }
1067
1068                 if (deinterlace) {
1069                         vector<Effect *> reverse_inputs(rgba_inputs.rbegin(), rgba_inputs.rend());
1070                         chain->add_effect(deinterlace_effect, reverse_inputs);
1071                 }
1072         } else {
1073                 assert(pixel_format == bmusb::PixelFormat_8BitYCbCr ||
1074                        pixel_format == bmusb::PixelFormat_10BitYCbCr ||
1075                        pixel_format == bmusb::PixelFormat_8BitYCbCrPlanar);
1076
1077                 // Most of these settings will be overridden later if using PixelFormat_8BitYCbCrPlanar.
1078                 input_ycbcr_format.chroma_subsampling_x = (pixel_format == bmusb::PixelFormat_10BitYCbCr) ? 1 : 2;
1079                 input_ycbcr_format.chroma_subsampling_y = 1;
1080                 input_ycbcr_format.num_levels = (pixel_format == bmusb::PixelFormat_10BitYCbCr) ? 1024 : 256;
1081                 input_ycbcr_format.cb_x_position = 0.0;
1082                 input_ycbcr_format.cr_x_position = 0.0;
1083                 input_ycbcr_format.cb_y_position = 0.5;
1084                 input_ycbcr_format.cr_y_position = 0.5;
1085                 input_ycbcr_format.luma_coefficients = YCBCR_REC_709;  // Will be overridden later even if not planar.
1086                 input_ycbcr_format.full_range = false;  // Will be overridden later even if not planar.
1087
1088                 for (unsigned i = 0; i < num_inputs; ++i) {
1089                         // When using 10-bit input, we're converting to interleaved through v210Converter.
1090                         YCbCrInputSplitting splitting;
1091                         if (pixel_format == bmusb::PixelFormat_10BitYCbCr) {
1092                                 splitting = YCBCR_INPUT_INTERLEAVED;
1093                         } else if (pixel_format == bmusb::PixelFormat_8BitYCbCr) {
1094                                 splitting = YCBCR_INPUT_SPLIT_Y_AND_CBCR;
1095                         } else {
1096                                 splitting = YCBCR_INPUT_PLANAR;
1097                         }
1098                         if (override_bounce) {
1099                                 ycbcr_inputs.push_back(new NonBouncingYCbCrInput(inout_format, input_ycbcr_format, global_flags.width, global_flags.height, splitting));
1100                         } else {
1101                                 ycbcr_inputs.push_back(new YCbCrInput(inout_format, input_ycbcr_format, global_flags.width, global_flags.height, splitting));
1102                         }
1103                         chain->add_input(ycbcr_inputs.back());
1104                 }
1105
1106                 if (deinterlace) {
1107                         vector<Effect *> reverse_inputs(ycbcr_inputs.rbegin(), ycbcr_inputs.rend());
1108                         chain->add_effect(deinterlace_effect, reverse_inputs);
1109                 }
1110         }
1111 }
1112
1113 bool LiveInputWrapper::connect_signal(int signal_num)
1114 {
1115         if (!user_connectable) {
1116                 return false;
1117         }
1118
1119         if (global_mixer == nullptr) {
1120                 // No data yet.
1121                 return true;
1122         }
1123
1124         signal_num = theme->map_signal(signal_num);
1125         connect_signal_raw(signal_num, *theme->input_state);
1126         return true;
1127 }
1128
1129 void LiveInputWrapper::connect_signal_raw(int signal_num, const InputState &input_state)
1130 {
1131         BufferedFrame first_frame = input_state.buffered_frames[signal_num][0];
1132         if (first_frame.frame == nullptr) {
1133                 // No data yet.
1134                 return;
1135         }
1136         unsigned width, height;
1137         {
1138                 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)first_frame.frame->userdata;
1139                 width = userdata->last_width[first_frame.field_number];
1140                 height = userdata->last_height[first_frame.field_number];
1141                 if (userdata->last_interlaced) {
1142                         height *= 2;
1143                 }
1144         }
1145
1146         movit::YCbCrLumaCoefficients ycbcr_coefficients = input_state.ycbcr_coefficients[signal_num];
1147         bool full_range = input_state.full_range[signal_num];
1148
1149         if (input_state.ycbcr_coefficients_auto[signal_num]) {
1150                 full_range = false;
1151
1152                 // The Blackmagic driver docs claim that the device outputs Y'CbCr
1153                 // according to Rec. 601, but this seems to indicate the subsampling
1154                 // positions only, as they publish Y'CbCr → RGB formulas that are
1155                 // different for HD and SD (corresponding to Rec. 709 and 601, respectively),
1156                 // and a Lenovo X1 gen 3 I used to test definitely outputs Rec. 709
1157                 // (at least up to rounding error). Other devices seem to use Rec. 601
1158                 // even on HD resolutions. Nevertheless, Rec. 709 _is_ the right choice
1159                 // for HD, so we default to that if the user hasn't set anything.
1160                 if (height >= 720) {
1161                         ycbcr_coefficients = YCBCR_REC_709;
1162                 } else {
1163                         ycbcr_coefficients = YCBCR_REC_601;
1164                 }
1165         }
1166
1167         // This is a global, but it doesn't really matter.
1168         input_ycbcr_format.luma_coefficients = ycbcr_coefficients;
1169         input_ycbcr_format.full_range = full_range;
1170
1171         BufferedFrame last_good_frame = first_frame;
1172         for (unsigned i = 0; i < max(ycbcr_inputs.size(), rgba_inputs.size()); ++i) {
1173                 BufferedFrame frame = input_state.buffered_frames[signal_num][i];
1174                 if (frame.frame == nullptr) {
1175                         // Not enough data; reuse last frame (well, field).
1176                         // This is suboptimal, but we have nothing better.
1177                         frame = last_good_frame;
1178                 }
1179                 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
1180
1181                 unsigned this_width = userdata->last_width[frame.field_number];
1182                 unsigned this_height = userdata->last_height[frame.field_number];
1183                 if (this_width != width || this_height != height) {
1184                         // Resolution changed; reuse last frame/field.
1185                         frame = last_good_frame;
1186                         userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
1187                 }
1188
1189                 assert(userdata->pixel_format == pixel_format);
1190                 switch (pixel_format) {
1191                 case bmusb::PixelFormat_8BitYCbCr:
1192                         ycbcr_inputs[i]->set_texture_num(0, userdata->tex_y[frame.field_number]);
1193                         ycbcr_inputs[i]->set_texture_num(1, userdata->tex_cbcr[frame.field_number]);
1194                         ycbcr_inputs[i]->change_ycbcr_format(input_ycbcr_format);
1195                         ycbcr_inputs[i]->set_width(width);
1196                         ycbcr_inputs[i]->set_height(height);
1197                         break;
1198                 case bmusb::PixelFormat_8BitYCbCrPlanar:
1199                         ycbcr_inputs[i]->set_texture_num(0, userdata->tex_y[frame.field_number]);
1200                         ycbcr_inputs[i]->set_texture_num(1, userdata->tex_cb[frame.field_number]);
1201                         ycbcr_inputs[i]->set_texture_num(2, userdata->tex_cr[frame.field_number]);
1202                         ycbcr_inputs[i]->change_ycbcr_format(userdata->ycbcr_format);
1203                         ycbcr_inputs[i]->set_width(width);
1204                         ycbcr_inputs[i]->set_height(height);
1205                         break;
1206                 case bmusb::PixelFormat_10BitYCbCr:
1207                         ycbcr_inputs[i]->set_texture_num(0, userdata->tex_444[frame.field_number]);
1208                         ycbcr_inputs[i]->change_ycbcr_format(input_ycbcr_format);
1209                         ycbcr_inputs[i]->set_width(width);
1210                         ycbcr_inputs[i]->set_height(height);
1211                         break;
1212                 case bmusb::PixelFormat_8BitBGRA:
1213                         rgba_inputs[i]->set_texture_num(userdata->tex_rgba[frame.field_number]);
1214                         rgba_inputs[i]->set_width(width);
1215                         rgba_inputs[i]->set_height(height);
1216                         break;
1217                 default:
1218                         assert(false);
1219                 }
1220
1221                 last_good_frame = frame;
1222         }
1223
1224         if (deinterlace) {
1225                 BufferedFrame frame = input_state.buffered_frames[signal_num][0];
1226                 CHECK(deinterlace_effect->set_int("current_field_position", frame.field_number));
1227         }
1228 }
1229
1230 namespace {
1231
1232 int call_num_channels(lua_State *L)
1233 {
1234         lua_getglobal(L, "num_channels");
1235
1236         if (lua_pcall(L, 0, 1, 0) != 0) {
1237                 fprintf(stderr, "error running function `num_channels': %s\n", lua_tostring(L, -1));
1238                 fprintf(stderr, "Try Nageru.set_num_channels(...) at the start of the script instead.\n");
1239                 abort();
1240         }
1241
1242         int num_channels = luaL_checknumber(L, 1);
1243         lua_pop(L, 1);
1244         assert(lua_gettop(L) == 0);
1245         return num_channels;
1246 }
1247
1248 }  // namespace
1249
1250 int Nageru_set_channel_name(lua_State *L)
1251 {
1252         // NOTE: m is already locked.
1253         Theme *theme = get_theme_updata(L);
1254         unsigned channel = luaL_checknumber(L, 1);
1255         const string text = checkstdstring(L, 2);
1256         theme->channel_names[channel] = text;
1257         lua_pop(L, 2);
1258         return 0;
1259 }
1260
1261 int Nageru_set_num_channels(lua_State *L)
1262 {
1263         // NOTE: m is already locked.
1264         Theme *theme = get_theme_updata(L);
1265         if (theme->startup_finished) {
1266                 luaL_error(L, "set_num_channels() can only be called at startup.");
1267         }
1268         theme->num_channels = luaL_checknumber(L, 1);
1269         lua_pop(L, 1);
1270         return 0;
1271 }
1272
1273 int Nageru_set_channel_signal(lua_State *L)
1274 {
1275         // NOTE: m is already locked.
1276         Theme *theme = get_theme_updata(L);
1277         if (theme->startup_finished) {
1278                 luaL_error(L, "set_channel_signal() can only be called at startup.");
1279         }
1280         unsigned channel = luaL_checknumber(L, 1);
1281         int signal = luaL_checknumber(L, 2);
1282         theme->channel_signals[channel] = signal;
1283         lua_pop(L, 2);
1284         return 0;
1285 }
1286
1287 int Nageru_set_supports_wb(lua_State *L)
1288 {
1289         // NOTE: m is already locked.
1290         Theme *theme = get_theme_updata(L);
1291         if (theme->startup_finished) {
1292                 luaL_error(L, "set_supports_wb() can only be called at startup.");
1293         }
1294         unsigned channel = luaL_checknumber(L, 1);
1295         bool supports_wb = checkbool(L, 2);
1296         theme->channel_supports_wb[channel] = supports_wb;
1297         lua_pop(L, 2);
1298         return 0;
1299 }
1300
1301 Theme::Theme(const string &filename, const vector<string> &search_dirs, ResourcePool *resource_pool, unsigned num_cards)
1302         : resource_pool(resource_pool), num_cards(num_cards), signal_to_card_mapping(global_flags.default_stream_mapping)
1303 {
1304         // Defaults.
1305         channel_names[0] = "Live";
1306         channel_names[1] = "Preview";
1307
1308         L = luaL_newstate();
1309         luaL_openlibs(L);
1310
1311         // Search through all directories until we find a file that will load
1312         // (as in, does not return LUA_ERRFILE); then run it. We store load errors
1313         // from all the attempts, and show them once we know we can't find any of them.
1314         lua_settop(L, 0);
1315         vector<string> errors;
1316         bool success = false;
1317
1318         vector<string> real_search_dirs;
1319         if (!filename.empty() && filename[0] == '/') {
1320                 real_search_dirs.push_back("");
1321         } else {
1322                 real_search_dirs = search_dirs;
1323         }
1324
1325         string path;
1326         int theme_code_ref;
1327         for (const string &dir : real_search_dirs) {
1328                 if (dir.empty()) {
1329                         path = filename;
1330                 } else {
1331                         path = dir + "/" + filename;
1332                 }
1333                 int err = luaL_loadfile(L, path.c_str());
1334                 if (err == 0) {
1335                         // Save the theme for when we're actually going to run it
1336                         // (we need to set up the right environment below first,
1337                         // and we couldn't do that before, because we didn't know the
1338                         // path to put in Nageru.THEME_PATH).
1339                         theme_code_ref = luaL_ref(L, LUA_REGISTRYINDEX);
1340                         assert(lua_gettop(L) == 0);
1341
1342                         success = true;
1343                         break;
1344                 }
1345                 errors.push_back(lua_tostring(L, -1));
1346                 lua_pop(L, 1);
1347                 if (err != LUA_ERRFILE) {
1348                         // The file actually loaded, but failed to parse somehow. Abort; don't try the next one.
1349                         break;
1350                 }
1351         }
1352
1353         if (!success) {
1354                 for (const string &error : errors) {
1355                         fprintf(stderr, "%s\n", error.c_str());
1356                 }
1357                 abort();
1358         }
1359         assert(lua_gettop(L) == 0);
1360
1361         // Make sure the path exposed to the theme (as Nageru.THEME_PATH;
1362         // can be useful for locating files when talking to CEF) is absolute.
1363         // In a sense, it would be nice if realpath() had a mode not to
1364         // resolve symlinks, but it doesn't, so we only call it if we don't
1365         // already have an absolute path (which may leave ../ elements etc.).
1366         if (path[0] == '/') {
1367                 theme_path = path;
1368         } else {
1369                 char *absolute_theme_path = realpath(path.c_str(), nullptr);
1370                 theme_path = absolute_theme_path;
1371                 free(absolute_theme_path);
1372         }
1373
1374         // Set up the API we provide.
1375         register_globals();
1376         register_class("Scene", Scene_funcs);
1377         register_class("Block", Block_funcs);
1378         register_class("EffectBlueprint", EffectBlueprint_funcs);
1379         register_class("EffectChain", EffectChain_funcs);
1380         register_class("LiveInputWrapper", LiveInputWrapper_funcs);
1381         register_class("ImageInput", ImageInput_funcs);
1382         register_class("VideoInput", VideoInput_funcs);
1383         register_class("HTMLInput", HTMLInput_funcs);
1384         register_class("IdentityEffect", IdentityEffect_funcs, IDENTITY_EFFECT);
1385         register_class("WhiteBalanceEffect", WhiteBalanceEffect_funcs, WHITE_BALANCE_EFFECT);
1386         register_class("ResampleEffect", ResampleEffect_funcs, RESAMPLE_EFFECT);
1387         register_class("PaddingEffect", PaddingEffect_funcs, PADDING_EFFECT);
1388         register_class("IntegralPaddingEffect", IntegralPaddingEffect_funcs, INTEGRAL_PADDING_EFFECT);
1389         register_class("OverlayEffect", OverlayEffect_funcs, OVERLAY_EFFECT);
1390         register_class("ResizeEffect", ResizeEffect_funcs, RESIZE_EFFECT);
1391         register_class("MultiplyEffect", MultiplyEffect_funcs, MULTIPLY_EFFECT);
1392         register_class("MixEffect", MixEffect_funcs, MIX_EFFECT);
1393         register_class("LiftGammaGainEffect", LiftGammaGainEffect_funcs, LIFT_GAMMA_GAIN_EFFECT);
1394         register_class("InputStateInfo", InputStateInfo_funcs);
1395         register_class("ThemeMenu", ThemeMenu_funcs);
1396
1397         // Now actually run the theme to get everything set up.
1398         lua_rawgeti(L, LUA_REGISTRYINDEX, theme_code_ref);
1399         luaL_unref(L, LUA_REGISTRYINDEX, theme_code_ref);
1400         if (lua_pcall(L, 0, 0, 0)) {
1401                 fprintf(stderr, "Error when running %s: %s\n", path.c_str(), lua_tostring(L, -1));
1402                 abort();
1403         }
1404         assert(lua_gettop(L) == 0);
1405
1406         if (num_channels == -1) {
1407                 // Ask it for the number of channels.
1408                 num_channels = call_num_channels(L);
1409         }
1410         startup_finished = true;
1411 }
1412
1413 Theme::~Theme()
1414 {
1415         theme_menu.reset();
1416         lua_close(L);
1417 }
1418
1419 void Theme::register_globals()
1420 {
1421         // Set Nageru.VIDEO_FORMAT_BGRA = bmusb::PixelFormat_8BitBGRA, etc.
1422         const vector<pair<string, int>> num_constants = {
1423                 { "VIDEO_FORMAT_BGRA", bmusb::PixelFormat_8BitBGRA },
1424                 { "VIDEO_FORMAT_YCBCR", bmusb::PixelFormat_8BitYCbCrPlanar },
1425                 { "CHECKABLE", MenuEntry::CHECKABLE },
1426                 { "CHECKED", MenuEntry::CHECKED },
1427         };
1428         const vector<pair<string, string>> str_constants = {
1429                 { "THEME_PATH", theme_path },
1430         };
1431
1432         lua_newtable(L);  // t = {}
1433
1434         for (const pair<string, int> &constant : num_constants) {
1435                 lua_pushstring(L, constant.first.c_str());
1436                 lua_pushinteger(L, constant.second);
1437                 lua_settable(L, 1);  // t[key] = value
1438         }
1439         for (const pair<string, string> &constant : str_constants) {
1440                 lua_pushstring(L, constant.first.c_str());
1441                 lua_pushstring(L, constant.second.c_str());
1442                 lua_settable(L, 1);  // t[key] = value
1443         }
1444
1445         const luaL_Reg Nageru_funcs[] = {
1446                 { "set_channel_name", Nageru_set_channel_name },
1447                 { "set_num_channels", Nageru_set_num_channels },
1448                 { "set_channel_signal", Nageru_set_channel_signal },
1449                 { "set_supports_wb", Nageru_set_supports_wb },
1450                 { NULL, NULL }
1451         };
1452         lua_pushlightuserdata(L, this);
1453         luaL_setfuncs(L, Nageru_funcs, 1);        // for (name,f in funcs) { mt[name] = f, with upvalue {theme} }
1454
1455         lua_setglobal(L, "Nageru");  // Nageru = t
1456         assert(lua_gettop(L) == 0);
1457 }
1458
1459 void Theme::register_class(const char *class_name, const luaL_Reg *funcs, EffectType effect_type)
1460 {
1461         assert(lua_gettop(L) == 0);
1462         luaL_newmetatable(L, class_name);  // mt = {}
1463         lua_pushlightuserdata(L, this);
1464         luaL_setfuncs(L, funcs, 1);        // for (name,f in funcs) { mt[name] = f, with upvalue {theme} }
1465         lua_pushvalue(L, -1);
1466         lua_setfield(L, -2, "__index");    // mt.__index = mt
1467         if (effect_type != NO_EFFECT_TYPE) {
1468                 lua_pushnumber(L, effect_type);
1469                 lua_setfield(L, -2, "__effect_type_id");  // mt.__effect_type_id = effect_type
1470         }
1471         lua_setglobal(L, class_name);      // ClassName = mt
1472         assert(lua_gettop(L) == 0);
1473 }
1474
1475 Theme::Chain Theme::get_chain_from_effect_chain(EffectChain *effect_chain, unsigned num, const InputState &input_state)
1476 {
1477         if (!lua_isfunction(L, -1)) {
1478                 fprintf(stderr, "Argument #-1 should be a function\n");
1479                 abort();
1480         }
1481         lua_pushvalue(L, -1);
1482         shared_ptr<LuaRefWithDeleter> funcref(new LuaRefWithDeleter(&m, L, luaL_ref(L, LUA_REGISTRYINDEX)));
1483         lua_pop(L, 2);
1484
1485         Chain chain;
1486         chain.chain = effect_chain;
1487         chain.setup_chain = [this, funcref, input_state, effect_chain]{
1488                 lock_guard<mutex> lock(m);
1489
1490                 assert(this->input_state == nullptr);
1491                 this->input_state = &input_state;
1492
1493                 // Set up state, including connecting signals.
1494                 lua_rawgeti(L, LUA_REGISTRYINDEX, funcref->get());
1495                 if (lua_pcall(L, 0, 0, 0) != 0) {
1496                         fprintf(stderr, "error running chain setup callback: %s\n", lua_tostring(L, -1));
1497                         abort();
1498                 }
1499                 assert(lua_gettop(L) == 0);
1500
1501                 // The theme can't (or at least shouldn't!) call connect_signal() on
1502                 // each FFmpeg or CEF input, so we'll do it here.
1503                 if (video_signal_connections.count(effect_chain)) {
1504                         for (const VideoSignalConnection &conn : video_signal_connections[effect_chain]) {
1505                                 conn.wrapper->connect_signal_raw(conn.source->get_card_index(), input_state);
1506                         }
1507                 }
1508 #ifdef HAVE_CEF
1509                 if (html_signal_connections.count(effect_chain)) {
1510                         for (const CEFSignalConnection &conn : html_signal_connections[effect_chain]) {
1511                                 conn.wrapper->connect_signal_raw(conn.source->get_card_index(), input_state);
1512                         }
1513                 }
1514 #endif
1515
1516                 this->input_state = nullptr;
1517         };
1518         return chain;
1519 }
1520
1521 Theme::Chain Theme::get_chain(unsigned num, float t, unsigned width, unsigned height, const InputState &input_state)
1522 {
1523         const char *func_name = "get_scene";  // For error reporting.
1524         Chain chain;
1525
1526         lock_guard<mutex> lock(m);
1527         assert(lua_gettop(L) == 0);
1528         lua_getglobal(L, "get_scene");  /* function to be called */
1529         if (lua_isnil(L, -1)) {
1530                 // Try the pre-1.9.0 name for compatibility.
1531                 lua_pop(L, 1);
1532                 lua_getglobal(L, "get_chain");
1533                 func_name = "get_chain";
1534         }
1535         lua_pushnumber(L, num);
1536         lua_pushnumber(L, t);
1537         lua_pushnumber(L, width);
1538         lua_pushnumber(L, height);
1539         wrap_lua_object<InputStateInfo>(L, "InputStateInfo", input_state);
1540
1541         if (lua_pcall(L, 5, LUA_MULTRET, 0) != 0) {
1542                 fprintf(stderr, "error running function “%s”: %s\n", func_name, lua_tostring(L, -1));
1543                 abort();
1544         }
1545
1546         if (luaL_testudata(L, -1, "Scene") != nullptr) {
1547                 if (lua_gettop(L) != 1) {
1548                         luaL_error(L, "%s() for chain number %d returned an Scene, but also other items", func_name);
1549                 }
1550                 Scene *auto_effect_chain = (Scene *)luaL_testudata(L, -1, "Scene");
1551                 auto chain_and_setup = auto_effect_chain->get_chain(this, L, num, input_state);
1552                 chain.chain = chain_and_setup.first;
1553                 chain.setup_chain = move(chain_and_setup.second);
1554         } else if (luaL_testudata(L, -2, "EffectChain") != nullptr) {
1555                 // Old-style (pre-Nageru 1.9.0) return of a single chain and prepare function.
1556                 if (lua_gettop(L) != 2) {
1557                         luaL_error(L, "%s() for chain number %d returned an EffectChain, but needs to also return a prepare function (or use Scene)", func_name);
1558                 }
1559                 EffectChain *effect_chain = (EffectChain *)luaL_testudata(L, -2, "EffectChain");
1560                 chain = get_chain_from_effect_chain(effect_chain, num, input_state);
1561         } else {
1562                 luaL_error(L, "%s() for chain number %d did not return an EffectChain or Scene\n", func_name, num);
1563         }
1564         assert(lua_gettop(L) == 0);
1565
1566         // TODO: Can we do better, e.g. by running setup_chain() and seeing what it references?
1567         // Actually, setup_chain does maybe hold all the references we need now anyway?
1568         chain.input_frames.reserve(num_cards * FRAME_HISTORY_LENGTH);
1569         for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
1570                 for (unsigned frame_num = 0; frame_num < FRAME_HISTORY_LENGTH; ++frame_num) {
1571                         chain.input_frames.push_back(input_state.buffered_frames[card_index][frame_num].frame);
1572                 }
1573         }
1574
1575         return chain;
1576 }
1577
1578 string Theme::get_channel_name(unsigned channel)
1579 {
1580         lock_guard<mutex> lock(m);
1581
1582         // We never ask the legacy channel_name() about live and preview.
1583         // The defaults are set in our constructor.
1584         if (channel == 0 || channel == 1) {
1585                 return channel_names[channel];
1586         }
1587
1588         lua_getglobal(L, "channel_name");
1589         if (lua_isnil(L, -1)) {
1590                 lua_pop(L, 1);
1591                 if (channel_names.count(channel)) {
1592                         return channel_names[channel];
1593                 } else {
1594                         return "(no title)";
1595                 }
1596         }
1597
1598         lua_pushnumber(L, channel);
1599         if (lua_pcall(L, 1, 1, 0) != 0) {
1600                 fprintf(stderr, "error running function `channel_name': %s\n", lua_tostring(L, -1));
1601                 abort();
1602         }
1603         const char *ret = lua_tostring(L, -1);
1604         if (ret == nullptr) {
1605                 fprintf(stderr, "function `channel_name' returned nil for channel %d\n", channel);
1606                 fprintf(stderr, "Try Nageru.set_channel_name(channel, name) at the start of the script instead.\n");
1607                 abort();
1608         }
1609
1610         string retstr = ret;
1611         lua_pop(L, 1);
1612         assert(lua_gettop(L) == 0);
1613         return retstr;
1614 }
1615
1616 int Theme::get_channel_signal(unsigned channel)
1617 {
1618         lock_guard<mutex> lock(m);
1619         lua_getglobal(L, "channel_signal");
1620         if (lua_isnil(L, -1)) {
1621                 lua_pop(L, 1);
1622                 if (channel_signals.count(channel)) {
1623                         return channel_signals[channel];
1624                 } else {
1625                         return -1;
1626                 }
1627         }
1628
1629         lua_pushnumber(L, channel);
1630         if (lua_pcall(L, 1, 1, 0) != 0) {
1631                 fprintf(stderr, "error running function `channel_signal': %s\n", lua_tostring(L, -1));
1632                 fprintf(stderr, "Try Nageru.set_channel_signal(channel, signal) at the start of the script instead.\n");
1633                 abort();
1634         }
1635
1636         int ret = luaL_checknumber(L, 1);
1637         lua_pop(L, 1);
1638         assert(lua_gettop(L) == 0);
1639         return ret;
1640 }
1641
1642 std::string Theme::get_channel_color(unsigned channel)
1643 {
1644         lock_guard<mutex> lock(m);
1645         lua_getglobal(L, "channel_color");
1646         lua_pushnumber(L, channel);
1647         if (lua_pcall(L, 1, 1, 0) != 0) {
1648                 fprintf(stderr, "error running function `channel_color': %s\n", lua_tostring(L, -1));
1649                 abort();
1650         }
1651
1652         const char *ret = lua_tostring(L, -1);
1653         if (ret == nullptr) {
1654                 fprintf(stderr, "function `channel_color' returned nil for channel %d\n", channel);
1655                 abort();
1656         }
1657
1658         string retstr = ret;
1659         lua_pop(L, 1);
1660         assert(lua_gettop(L) == 0);
1661         return retstr;
1662 }
1663
1664 bool Theme::get_supports_set_wb(unsigned channel)
1665 {
1666         lock_guard<mutex> lock(m);
1667         lua_getglobal(L, "supports_set_wb");
1668         if (lua_isnil(L, -1)) {
1669                 lua_pop(L, 1);
1670                 if (channel_supports_wb.count(channel)) {
1671                         return channel_supports_wb[channel];
1672                 } else {
1673                         return false;
1674                 }
1675         }
1676
1677         lua_pushnumber(L, channel);
1678         if (lua_pcall(L, 1, 1, 0) != 0) {
1679                 fprintf(stderr, "error running function `supports_set_wb': %s\n", lua_tostring(L, -1));
1680                 fprintf(stderr, "Try Nageru.set_supports_wb(channel, bool) at the start of the script instead.\n");
1681                 abort();
1682         }
1683
1684         bool ret = checkbool(L, -1);
1685         lua_pop(L, 1);
1686         assert(lua_gettop(L) == 0);
1687         return ret;
1688 }
1689
1690 void Theme::set_wb(unsigned channel, float r, float g, float b)
1691 {
1692         int signal = get_channel_signal(channel);
1693
1694         lock_guard<mutex> lock(m);
1695         if (signal != -1) {
1696                 white_balance_for_signal[signal] = RGBTriplet{ r, g, b };
1697         }
1698
1699         call_lua_wb_callback(channel, r, g, b);
1700 }
1701
1702 void Theme::set_wb_for_signal(int signal, float r, float g, float b)
1703 {
1704         lock_guard<mutex> lock(m);
1705         white_balance_for_signal[signal] = RGBTriplet{ r, g, b };
1706
1707         for (const auto &channel_and_signal : channel_signals) {
1708                 if (channel_and_signal.second == signal) {
1709                         call_lua_wb_callback(channel_and_signal.first, r, g, b);
1710                 }
1711         }
1712 }
1713
1714 void Theme::call_lua_wb_callback(unsigned channel, float r, float g, float b)
1715 {
1716         lua_getglobal(L, "set_wb");
1717         if (lua_isnil(L, -1)) {
1718                 // The function doesn't exist, to just ignore. We've stored the white balance,
1719                 // and most likely, it will be picked up by auto white balance instead.
1720                 lua_pop(L, 1);
1721                 return;
1722         }
1723         lua_pushnumber(L, channel);
1724         lua_pushnumber(L, r);
1725         lua_pushnumber(L, g);
1726         lua_pushnumber(L, b);
1727         if (lua_pcall(L, 4, 0, 0) != 0) {
1728                 fprintf(stderr, "error running function `set_wb': %s\n", lua_tostring(L, -1));
1729                 abort();
1730         }
1731
1732         assert(lua_gettop(L) == 0);
1733 }
1734
1735 RGBTriplet Theme::get_white_balance_for_signal(int signal)
1736 {
1737         if (white_balance_for_signal.count(signal)) {
1738                 return white_balance_for_signal[signal];
1739         } else {
1740                 return RGBTriplet{ 1.0, 1.0, 1.0 };
1741         }
1742 }
1743
1744 vector<string> Theme::get_transition_names(float t)
1745 {
1746         lock_guard<mutex> lock(m);
1747         lua_getglobal(L, "get_transitions");
1748         lua_pushnumber(L, t);
1749         if (lua_pcall(L, 1, 1, 0) != 0) {
1750                 fprintf(stderr, "error running function `get_transitions': %s\n", lua_tostring(L, -1));
1751                 abort();
1752         }
1753
1754         vector<string> ret;
1755         lua_pushnil(L);
1756         while (lua_next(L, -2) != 0) {
1757                 ret.push_back(lua_tostring(L, -1));
1758                 lua_pop(L, 1);
1759         }
1760         lua_pop(L, 1);
1761         assert(lua_gettop(L) == 0);
1762         return ret;
1763 }
1764
1765 int Theme::map_signal(int signal_num)
1766 {
1767         // Negative numbers map to raw signals.
1768         if (signal_num < 0) {
1769                 return -1 - signal_num;
1770         }
1771
1772         lock_guard<mutex> lock(map_m);
1773         if (signal_to_card_mapping.count(signal_num)) {
1774                 return signal_to_card_mapping[signal_num];
1775         }
1776
1777         int card_index;
1778         if (global_flags.output_card != -1 && num_cards > 1) {
1779                 // Try to exclude the output card from the default card_index.
1780                 card_index = signal_num % (num_cards - 1);
1781                 if (card_index >= global_flags.output_card) {
1782                          ++card_index;
1783                 }
1784                 if (signal_num >= int(num_cards - 1)) {
1785                         print_warning(L, "Theme asked for input %d, but we only have %u input card(s) (card %d is busy with output).\n",
1786                                 signal_num, num_cards - 1, global_flags.output_card);
1787                         fprintf(stderr, "Mapping to card %d instead.\n", card_index);
1788                 }
1789         } else {
1790                 card_index = signal_num % num_cards;
1791                 if (signal_num >= int(num_cards)) {
1792                         print_warning(L, "Theme asked for input %d, but we only have %u card(s).\n", signal_num, num_cards);
1793                         fprintf(stderr, "Mapping to card %d instead.\n", card_index);
1794                 }
1795         }
1796         signal_to_card_mapping[signal_num] = card_index;
1797         return card_index;
1798 }
1799
1800 void Theme::set_signal_mapping(int signal_num, int card_num)
1801 {
1802         lock_guard<mutex> lock(map_m);
1803         assert(card_num < int(num_cards));
1804         signal_to_card_mapping[signal_num] = card_num;
1805 }
1806
1807 void Theme::transition_clicked(int transition_num, float t)
1808 {
1809         lock_guard<mutex> lock(m);
1810         lua_getglobal(L, "transition_clicked");
1811         lua_pushnumber(L, transition_num);
1812         lua_pushnumber(L, t);
1813
1814         if (lua_pcall(L, 2, 0, 0) != 0) {
1815                 fprintf(stderr, "error running function `transition_clicked': %s\n", lua_tostring(L, -1));
1816                 abort();
1817         }
1818         assert(lua_gettop(L) == 0);
1819 }
1820
1821 void Theme::channel_clicked(int preview_num)
1822 {
1823         lock_guard<mutex> lock(m);
1824         lua_getglobal(L, "channel_clicked");
1825         lua_pushnumber(L, preview_num);
1826
1827         if (lua_pcall(L, 1, 0, 0) != 0) {
1828                 fprintf(stderr, "error running function `channel_clicked': %s\n", lua_tostring(L, -1));
1829                 abort();
1830         }
1831         assert(lua_gettop(L) == 0);
1832 }
1833
1834 template <class T>
1835 void destroy(T &ref)
1836 {
1837         ref.~T();
1838 }
1839
1840 Theme::MenuEntry::~MenuEntry()
1841 {
1842         if (is_submenu) {
1843                 destroy(submenu);
1844         } else {
1845                 luaL_unref(entry.L, LUA_REGISTRYINDEX, entry.lua_ref);
1846         }
1847 }
1848
1849 namespace {
1850
1851 vector<unique_ptr<Theme::MenuEntry>> create_recursive_theme_menu(lua_State *L);
1852
1853 unique_ptr<Theme::MenuEntry> create_theme_menu_entry(lua_State *L, int index)
1854 {
1855         unique_ptr<Theme::MenuEntry> entry;
1856
1857         lua_rawgeti(L, index, 1);
1858         const string text = checkstdstring(L, -1);
1859         lua_pop(L, 1);
1860
1861         unsigned flags = 0;
1862         if (lua_objlen(L, -1) > 2) {
1863                 lua_rawgeti(L, -1, 3);
1864                 flags = luaL_checknumber(L, -1);
1865                 lua_pop(L, 1);
1866         }
1867
1868         lua_rawgeti(L, index, 2);
1869         if (lua_istable(L, -1)) {
1870                 vector<unique_ptr<Theme::MenuEntry>> submenu = create_recursive_theme_menu(L);
1871                 entry.reset(new Theme::MenuEntry{ text, move(submenu) });
1872                 lua_pop(L, 1);
1873         } else {
1874                 luaL_checktype(L, -1, LUA_TFUNCTION);
1875                 int ref = luaL_ref(L, LUA_REGISTRYINDEX);
1876                 entry.reset(new Theme::MenuEntry{ text, L, ref, flags });
1877         }
1878         return entry;
1879 }
1880
1881 vector<unique_ptr<Theme::MenuEntry>> create_recursive_theme_menu(lua_State *L)
1882 {
1883         vector<unique_ptr<Theme::MenuEntry>> menu;
1884         size_t num_elements = lua_objlen(L, -1);
1885         for (size_t i = 1; i <= num_elements; ++i) {
1886                 lua_rawgeti(L, -1, i);
1887                 menu.emplace_back(create_theme_menu_entry(L, -1));
1888                 lua_pop(L, 1);
1889         }
1890         return menu;
1891 }
1892
1893 }  // namespace
1894
1895 int Theme::set_theme_menu(lua_State *L)
1896 {
1897         theme_menu.reset();
1898
1899         vector<unique_ptr<MenuEntry>> root_menu;
1900         int num_elements = lua_gettop(L);
1901         for (int i = 1; i <= num_elements; ++i) {
1902                 root_menu.emplace_back(create_theme_menu_entry(L, i));
1903         }
1904         theme_menu.reset(new MenuEntry("", move(root_menu)));
1905
1906         lua_pop(L, num_elements);
1907         assert(lua_gettop(L) == 0);
1908
1909         if (theme_menu_callback != nullptr) {
1910                 theme_menu_callback();
1911         }
1912
1913         return 0;
1914 }
1915
1916 void Theme::theme_menu_entry_clicked(int lua_ref)
1917 {
1918         lock_guard<mutex> lock(m);
1919         lua_rawgeti(L, LUA_REGISTRYINDEX, lua_ref);
1920         if (lua_pcall(L, 0, 0, 0) != 0) {
1921                 fprintf(stderr, "error running menu callback: %s\n", lua_tostring(L, -1));
1922                 abort();
1923         }
1924 }
1925
1926 string Theme::format_status_line(const string &disk_space_left_text, double file_length_seconds)
1927 {
1928         lock_guard<mutex> lock(m);
1929         lua_getglobal(L, "format_status_line");
1930         if (lua_isnil(L, -1)) {
1931                 lua_pop(L, 1);
1932                 return disk_space_left_text;
1933         }
1934
1935         lua_pushstring(L, disk_space_left_text.c_str());
1936         lua_pushnumber(L, file_length_seconds);
1937         if (lua_pcall(L, 2, 1, 0) != 0) {
1938                 fprintf(stderr, "error running function format_status_line(): %s\n", lua_tostring(L, -1));
1939                 abort();
1940         }
1941         string text = checkstdstring(L, 1);
1942         lua_pop(L, 1);
1943         assert(lua_gettop(L) == 0);
1944         return text;
1945 }