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