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