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