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