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