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