]> git.sesse.net Git - nageru/blob - nageru/theme.cpp
Add an enable_if() to Block, for convenience.
[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_interlaced(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         lua_pushboolean(L, input_state_info->last_interlaced[signal_num]);
646         return 1;
647 }
648
649 int InputStateInfo_get_has_signal(lua_State* L)
650 {
651         assert(lua_gettop(L) == 2);
652         InputStateInfo *input_state_info = get_input_state_info(L, 1);
653         Theme *theme = get_theme_updata(L);
654         int signal_num = theme->map_signal(luaL_checknumber(L, 2));
655         lua_pushboolean(L, input_state_info->last_has_signal[signal_num]);
656         return 1;
657 }
658
659 int InputStateInfo_get_is_connected(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 signal_num = theme->map_signal(luaL_checknumber(L, 2));
665         lua_pushboolean(L, input_state_info->last_is_connected[signal_num]);
666         return 1;
667 }
668
669 int InputStateInfo_get_frame_rate_nom(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 signal_num = theme->map_signal(luaL_checknumber(L, 2));
675         lua_pushnumber(L, input_state_info->last_frame_rate_nom[signal_num]);
676         return 1;
677 }
678
679 int InputStateInfo_get_frame_rate_den(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 signal_num = theme->map_signal(luaL_checknumber(L, 2));
685         lua_pushnumber(L, input_state_info->last_frame_rate_den[signal_num]);
686         return 1;
687 }
688
689 int InputStateInfo_get_last_subtitle(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 signal_num = theme->map_signal(luaL_checknumber(L, 2));
695         if (!input_state_info->has_last_subtitle[signal_num]) {
696                 lua_pushnil(L);
697         } else {
698                 lua_pushstring(L, input_state_info->last_subtitle[signal_num].c_str());
699         }
700         return 1;
701 }
702
703 int EffectBlueprint_set_int(lua_State *L)
704 {
705         assert(lua_gettop(L) == 3);
706         EffectBlueprint *blueprint = *(EffectBlueprint **)luaL_checkudata(L, 1, "EffectBlueprint");
707         string key = checkstdstring(L, 2);
708         float value = luaL_checknumber(L, 3);
709         if (blueprint->effect != nullptr) {
710                 if (!blueprint->effect->set_int(key, value)) {
711                         luaL_error(L, "Effect refused set_int(\"%s\", %d) (invalid key?)", key.c_str(), int(value));
712                 }
713         } else {
714                 // TODO: check validity already here, if possible?
715                 blueprint->int_parameters[key] = value;
716         }
717         return 0;
718 }
719
720 int EffectBlueprint_set_float(lua_State *L)
721 {
722         assert(lua_gettop(L) == 3);
723         EffectBlueprint *blueprint = *(EffectBlueprint **)luaL_checkudata(L, 1, "EffectBlueprint");
724         string key = checkstdstring(L, 2);
725         float value = luaL_checknumber(L, 3);
726         if (blueprint->effect != nullptr) {
727                 if (!blueprint->effect->set_float(key, value)) {
728                         luaL_error(L, "Effect refused set_float(\"%s\", %d) (invalid key?)", key.c_str(), int(value));
729                 }
730         } else {
731                 // TODO: check validity already here, if possible?
732                 blueprint->float_parameters[key] = value;
733         }
734         return 0;
735 }
736
737 int EffectBlueprint_set_vec3(lua_State *L)
738 {
739         assert(lua_gettop(L) == 5);
740         EffectBlueprint *blueprint = *(EffectBlueprint **)luaL_checkudata(L, 1, "EffectBlueprint");
741         string key = checkstdstring(L, 2);
742         array<float, 3> v;
743         v[0] = luaL_checknumber(L, 3);
744         v[1] = luaL_checknumber(L, 4);
745         v[2] = luaL_checknumber(L, 5);
746
747         if (blueprint->effect != nullptr) {
748                 if (!blueprint->effect->set_vec3(key, v.data())) {
749                         luaL_error(L, "Effect refused set_vec3(\"%s\", %f, %f, %f) (invalid key?)", key.c_str(),
750                                 v[0], v[1], v[2]);
751                 }
752         } else {
753                 // TODO: check validity already here, if possible?
754                 blueprint->vec3_parameters[key] = v;
755         }
756
757         return 0;
758 }
759
760 int EffectBlueprint_set_vec4(lua_State *L)
761 {
762         assert(lua_gettop(L) == 6);
763         EffectBlueprint *blueprint = *(EffectBlueprint **)luaL_checkudata(L, 1, "EffectBlueprint");
764         string key = checkstdstring(L, 2);
765         array<float, 4> v;
766         v[0] = luaL_checknumber(L, 3);
767         v[1] = luaL_checknumber(L, 4);
768         v[2] = luaL_checknumber(L, 5);
769         v[3] = luaL_checknumber(L, 6);
770         if (blueprint->effect != nullptr) {
771                 if (!blueprint->effect->set_vec4(key, v.data())) {
772                         luaL_error(L, "Effect refused set_vec4(\"%s\", %f, %f, %f, %f) (invalid key?)", key.c_str(),
773                                 v[0], v[1], v[2], v[3]);
774                 }
775         } else {
776                 // TODO: check validity already here, if possible?
777                 blueprint->vec4_parameters[key] = v;
778         }
779         return 0;
780 }
781
782 const luaL_Reg Scene_funcs[] = {
783         { "new", Scene_new },
784         { "__gc", Scene_gc },
785         { "add_input", Scene::add_input },
786         { "add_effect", Scene::add_effect },
787         { "add_optional_effect", Scene::add_optional_effect },
788         { "finalize", Scene::finalize },
789         { NULL, NULL }
790 };
791
792 const luaL_Reg Block_funcs[] = {
793         { "display", Block_display },
794         { "choose", Block_choose },
795         { "enable", Block_enable },
796         { "enable_if", Block_enable_if },
797         { "disable", Block_disable },
798         { "set_int", Block_set_int },
799         { "set_float", Block_set_float },
800         { "set_vec3", Block_set_vec3 },
801         { "set_vec4", Block_set_vec4 },
802         { NULL, NULL }
803 };
804
805 const luaL_Reg EffectBlueprint_funcs[] = {
806         // NOTE: No new() function; that's for the individual effects.
807         { "set_int", EffectBlueprint_set_int },
808         { "set_float", EffectBlueprint_set_float },
809         { "set_vec3", EffectBlueprint_set_vec3 },
810         { "set_vec4", EffectBlueprint_set_vec4 },
811         { NULL, NULL }
812 };
813
814 const luaL_Reg EffectChain_funcs[] = {
815         { "new", EffectChain_new },
816         { "__gc", EffectChain_gc },
817         { "add_live_input", EffectChain_add_live_input },
818         { "add_video_input", EffectChain_add_video_input },
819 #ifdef HAVE_CEF
820         { "add_html_input", EffectChain_add_html_input },
821 #endif
822         { "add_effect", EffectChain_add_effect },
823         { "finalize", EffectChain_finalize },
824         { NULL, NULL }
825 };
826
827 const luaL_Reg LiveInputWrapper_funcs[] = {
828         { "connect_signal", LiveInputWrapper_connect_signal },
829         { NULL, NULL }
830 };
831
832 const luaL_Reg ImageInput_funcs[] = {
833         { "new", ImageInput_new },
834         { NULL, NULL }
835 };
836
837 const luaL_Reg VideoInput_funcs[] = {
838         { "new", VideoInput_new },
839         { "rewind", VideoInput_rewind },
840         { "disconnect", VideoInput_disconnect },
841         { "change_rate", VideoInput_change_rate },
842         { "get_signal_num", VideoInput_get_signal_num },
843         { NULL, NULL }
844 };
845
846 const luaL_Reg HTMLInput_funcs[] = {
847         { "new", HTMLInput_new },
848 #ifdef HAVE_CEF
849         { "set_url", HTMLInput_set_url },
850         { "reload", HTMLInput_reload },
851         { "set_max_fps", HTMLInput_set_max_fps },
852         { "execute_javascript_async", HTMLInput_execute_javascript_async },
853         { "resize", HTMLInput_resize },
854         { "get_signal_num", HTMLInput_get_signal_num },
855 #endif
856         { NULL, NULL }
857 };
858
859 // Effects.
860 // All of these are solely for new(); the returned metatable will be that of
861 // EffectBlueprint, and Effect (returned from add_effect()) is its own type.
862
863 const luaL_Reg IdentityEffect_funcs[] = {
864         { "new", IdentityEffect_new },
865         { NULL, NULL }
866 };
867
868 const luaL_Reg WhiteBalanceEffect_funcs[] = {
869         { "new", WhiteBalanceEffect_new },
870         { NULL, NULL }
871 };
872
873 const luaL_Reg ResampleEffect_funcs[] = {
874         { "new", ResampleEffect_new },
875         { NULL, NULL }
876 };
877
878 const luaL_Reg PaddingEffect_funcs[] = {
879         { "new", PaddingEffect_new },
880         { NULL, NULL }
881 };
882
883 const luaL_Reg IntegralPaddingEffect_funcs[] = {
884         { "new", IntegralPaddingEffect_new },
885         { NULL, NULL }
886 };
887
888 const luaL_Reg OverlayEffect_funcs[] = {
889         { "new", OverlayEffect_new },
890         { NULL, NULL }
891 };
892
893 const luaL_Reg ResizeEffect_funcs[] = {
894         { "new", ResizeEffect_new },
895         { NULL, NULL }
896 };
897
898 const luaL_Reg MultiplyEffect_funcs[] = {
899         { "new", MultiplyEffect_new },
900         { NULL, NULL }
901 };
902
903 const luaL_Reg MixEffect_funcs[] = {
904         { "new", MixEffect_new },
905         { NULL, NULL }
906 };
907
908 const luaL_Reg LiftGammaGainEffect_funcs[] = {
909         { "new", LiftGammaGainEffect_new },
910         { NULL, NULL }
911 };
912
913 // End of effects.
914
915 const luaL_Reg InputStateInfo_funcs[] = {
916         { "get_width", InputStateInfo_get_width },
917         { "get_height", InputStateInfo_get_height },
918         { "get_interlaced", InputStateInfo_get_interlaced },
919         { "get_has_signal", InputStateInfo_get_has_signal },
920         { "get_is_connected", InputStateInfo_get_is_connected },
921         { "get_frame_rate_nom", InputStateInfo_get_frame_rate_nom },
922         { "get_frame_rate_den", InputStateInfo_get_frame_rate_den },
923         { "get_last_subtitle", InputStateInfo_get_last_subtitle },
924         { NULL, NULL }
925 };
926
927 const luaL_Reg ThemeMenu_funcs[] = {
928         { "set", ThemeMenu_set },
929         { NULL, NULL }
930 };
931
932 }  // namespace
933
934 LiveInputWrapper::LiveInputWrapper(
935         Theme *theme,
936         EffectChain *chain,
937         bmusb::PixelFormat pixel_format,
938         bool override_bounce,
939         bool deinterlace,
940         bool user_connectable)
941         : theme(theme),
942           pixel_format(pixel_format),
943           deinterlace(deinterlace),
944           user_connectable(user_connectable)
945 {
946         ImageFormat inout_format;
947         inout_format.color_space = COLORSPACE_sRGB;
948
949         // Gamma curve depends on the input signal, and we don't really get any
950         // indications. A camera would be expected to do Rec. 709, but
951         // I haven't checked if any do in practice. However, computers _do_ output
952         // in sRGB gamma (ie., they don't convert from sRGB to Rec. 709), and
953         // I wouldn't really be surprised if most non-professional cameras do, too.
954         // So we pick sRGB as the least evil here.
955         inout_format.gamma_curve = GAMMA_sRGB;
956
957         unsigned num_inputs;
958         if (deinterlace) {
959                 deinterlace_effect = new movit::DeinterlaceEffect();
960
961                 // As per the comments in deinterlace_effect.h, we turn this off.
962                 // The most likely interlaced input for us is either a camera
963                 // (where it's fine to turn it off) or a laptop (where it _should_
964                 // be turned off).
965                 CHECK(deinterlace_effect->set_int("enable_spatial_interlacing_check", 0));
966
967                 num_inputs = deinterlace_effect->num_inputs();
968                 assert(num_inputs == FRAME_HISTORY_LENGTH);
969         } else {
970                 num_inputs = 1;
971         }
972
973         if (pixel_format == bmusb::PixelFormat_8BitBGRA) {
974                 for (unsigned i = 0; i < num_inputs; ++i) {
975                         // We upload our textures ourselves, and Movit swaps
976                         // R and B in the shader if we specify BGRA, so lie and say RGBA.
977                         rgba_inputs.push_back(new sRGBSwitchingFlatInput(inout_format, FORMAT_RGBA_POSTMULTIPLIED_ALPHA, GL_UNSIGNED_BYTE, global_flags.width, global_flags.height));
978                         chain->add_input(rgba_inputs.back());
979                 }
980
981                 if (deinterlace) {
982                         vector<Effect *> reverse_inputs(rgba_inputs.rbegin(), rgba_inputs.rend());
983                         chain->add_effect(deinterlace_effect, reverse_inputs);
984                 }
985         } else {
986                 assert(pixel_format == bmusb::PixelFormat_8BitYCbCr ||
987                        pixel_format == bmusb::PixelFormat_10BitYCbCr ||
988                        pixel_format == bmusb::PixelFormat_8BitYCbCrPlanar);
989
990                 // Most of these settings will be overridden later if using PixelFormat_8BitYCbCrPlanar.
991                 input_ycbcr_format.chroma_subsampling_x = (pixel_format == bmusb::PixelFormat_10BitYCbCr) ? 1 : 2;
992                 input_ycbcr_format.chroma_subsampling_y = 1;
993                 input_ycbcr_format.num_levels = (pixel_format == bmusb::PixelFormat_10BitYCbCr) ? 1024 : 256;
994                 input_ycbcr_format.cb_x_position = 0.0;
995                 input_ycbcr_format.cr_x_position = 0.0;
996                 input_ycbcr_format.cb_y_position = 0.5;
997                 input_ycbcr_format.cr_y_position = 0.5;
998                 input_ycbcr_format.luma_coefficients = YCBCR_REC_709;  // Will be overridden later even if not planar.
999                 input_ycbcr_format.full_range = false;  // Will be overridden later even if not planar.
1000
1001                 for (unsigned i = 0; i < num_inputs; ++i) {
1002                         // When using 10-bit input, we're converting to interleaved through v210Converter.
1003                         YCbCrInputSplitting splitting;
1004                         if (pixel_format == bmusb::PixelFormat_10BitYCbCr) {
1005                                 splitting = YCBCR_INPUT_INTERLEAVED;
1006                         } else if (pixel_format == bmusb::PixelFormat_8BitYCbCr) {
1007                                 splitting = YCBCR_INPUT_SPLIT_Y_AND_CBCR;
1008                         } else {
1009                                 splitting = YCBCR_INPUT_PLANAR;
1010                         }
1011                         if (override_bounce) {
1012                                 ycbcr_inputs.push_back(new NonBouncingYCbCrInput(inout_format, input_ycbcr_format, global_flags.width, global_flags.height, splitting));
1013                         } else {
1014                                 ycbcr_inputs.push_back(new YCbCrInput(inout_format, input_ycbcr_format, global_flags.width, global_flags.height, splitting));
1015                         }
1016                         chain->add_input(ycbcr_inputs.back());
1017                 }
1018
1019                 if (deinterlace) {
1020                         vector<Effect *> reverse_inputs(ycbcr_inputs.rbegin(), ycbcr_inputs.rend());
1021                         chain->add_effect(deinterlace_effect, reverse_inputs);
1022                 }
1023         }
1024 }
1025
1026 bool LiveInputWrapper::connect_signal(int signal_num)
1027 {
1028         if (!user_connectable) {
1029                 return false;
1030         }
1031
1032         if (global_mixer == nullptr) {
1033                 // No data yet.
1034                 return true;
1035         }
1036
1037         signal_num = theme->map_signal(signal_num);
1038         connect_signal_raw(signal_num, *theme->input_state);
1039         return true;
1040 }
1041
1042 void LiveInputWrapper::connect_signal_raw(int signal_num, const InputState &input_state)
1043 {
1044         BufferedFrame first_frame = input_state.buffered_frames[signal_num][0];
1045         if (first_frame.frame == nullptr) {
1046                 // No data yet.
1047                 return;
1048         }
1049         unsigned width, height;
1050         {
1051                 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)first_frame.frame->userdata;
1052                 width = userdata->last_width[first_frame.field_number];
1053                 height = userdata->last_height[first_frame.field_number];
1054                 if (userdata->last_interlaced) {
1055                         height *= 2;
1056                 }
1057         }
1058
1059         movit::YCbCrLumaCoefficients ycbcr_coefficients = input_state.ycbcr_coefficients[signal_num];
1060         bool full_range = input_state.full_range[signal_num];
1061
1062         if (input_state.ycbcr_coefficients_auto[signal_num]) {
1063                 full_range = false;
1064
1065                 // The Blackmagic driver docs claim that the device outputs Y'CbCr
1066                 // according to Rec. 601, but this seems to indicate the subsampling
1067                 // positions only, as they publish Y'CbCr → RGB formulas that are
1068                 // different for HD and SD (corresponding to Rec. 709 and 601, respectively),
1069                 // and a Lenovo X1 gen 3 I used to test definitely outputs Rec. 709
1070                 // (at least up to rounding error). Other devices seem to use Rec. 601
1071                 // even on HD resolutions. Nevertheless, Rec. 709 _is_ the right choice
1072                 // for HD, so we default to that if the user hasn't set anything.
1073                 if (height >= 720) {
1074                         ycbcr_coefficients = YCBCR_REC_709;
1075                 } else {
1076                         ycbcr_coefficients = YCBCR_REC_601;
1077                 }
1078         }
1079
1080         // This is a global, but it doesn't really matter.
1081         input_ycbcr_format.luma_coefficients = ycbcr_coefficients;
1082         input_ycbcr_format.full_range = full_range;
1083
1084         BufferedFrame last_good_frame = first_frame;
1085         for (unsigned i = 0; i < max(ycbcr_inputs.size(), rgba_inputs.size()); ++i) {
1086                 BufferedFrame frame = input_state.buffered_frames[signal_num][i];
1087                 if (frame.frame == nullptr) {
1088                         // Not enough data; reuse last frame (well, field).
1089                         // This is suboptimal, but we have nothing better.
1090                         frame = last_good_frame;
1091                 }
1092                 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
1093
1094                 unsigned this_width = userdata->last_width[frame.field_number];
1095                 unsigned this_height = userdata->last_height[frame.field_number];
1096                 if (this_width != width || this_height != height) {
1097                         // Resolution changed; reuse last frame/field.
1098                         frame = last_good_frame;
1099                         userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
1100                 }
1101
1102                 assert(userdata->pixel_format == pixel_format);
1103                 switch (pixel_format) {
1104                 case bmusb::PixelFormat_8BitYCbCr:
1105                         ycbcr_inputs[i]->set_texture_num(0, userdata->tex_y[frame.field_number]);
1106                         ycbcr_inputs[i]->set_texture_num(1, userdata->tex_cbcr[frame.field_number]);
1107                         ycbcr_inputs[i]->change_ycbcr_format(input_ycbcr_format);
1108                         ycbcr_inputs[i]->set_width(width);
1109                         ycbcr_inputs[i]->set_height(height);
1110                         break;
1111                 case bmusb::PixelFormat_8BitYCbCrPlanar:
1112                         ycbcr_inputs[i]->set_texture_num(0, userdata->tex_y[frame.field_number]);
1113                         ycbcr_inputs[i]->set_texture_num(1, userdata->tex_cb[frame.field_number]);
1114                         ycbcr_inputs[i]->set_texture_num(2, userdata->tex_cr[frame.field_number]);
1115                         ycbcr_inputs[i]->change_ycbcr_format(userdata->ycbcr_format);
1116                         ycbcr_inputs[i]->set_width(width);
1117                         ycbcr_inputs[i]->set_height(height);
1118                         break;
1119                 case bmusb::PixelFormat_10BitYCbCr:
1120                         ycbcr_inputs[i]->set_texture_num(0, userdata->tex_444[frame.field_number]);
1121                         ycbcr_inputs[i]->change_ycbcr_format(input_ycbcr_format);
1122                         ycbcr_inputs[i]->set_width(width);
1123                         ycbcr_inputs[i]->set_height(height);
1124                         break;
1125                 case bmusb::PixelFormat_8BitBGRA:
1126                         rgba_inputs[i]->set_texture_num(userdata->tex_rgba[frame.field_number]);
1127                         rgba_inputs[i]->set_width(width);
1128                         rgba_inputs[i]->set_height(height);
1129                         break;
1130                 default:
1131                         assert(false);
1132                 }
1133
1134                 last_good_frame = frame;
1135         }
1136
1137         if (deinterlace) {
1138                 BufferedFrame frame = input_state.buffered_frames[signal_num][0];
1139                 CHECK(deinterlace_effect->set_int("current_field_position", frame.field_number));
1140         }
1141 }
1142
1143 namespace {
1144
1145 int call_num_channels(lua_State *L)
1146 {
1147         lua_getglobal(L, "num_channels");
1148
1149         if (lua_pcall(L, 0, 1, 0) != 0) {
1150                 fprintf(stderr, "error running function `num_channels': %s\n", lua_tostring(L, -1));
1151                 abort();
1152         }
1153
1154         int num_channels = luaL_checknumber(L, 1);
1155         lua_pop(L, 1);
1156         assert(lua_gettop(L) == 0);
1157         return num_channels;
1158 }
1159
1160 }  // namespace
1161
1162 Theme::Theme(const string &filename, const vector<string> &search_dirs, ResourcePool *resource_pool, unsigned num_cards)
1163         : resource_pool(resource_pool), num_cards(num_cards), signal_to_card_mapping(global_flags.default_stream_mapping)
1164 {
1165         L = luaL_newstate();
1166         luaL_openlibs(L);
1167
1168         // Search through all directories until we find a file that will load
1169         // (as in, does not return LUA_ERRFILE); then run it. We store load errors
1170         // from all the attempts, and show them once we know we can't find any of them.
1171         lua_settop(L, 0);
1172         vector<string> errors;
1173         bool success = false;
1174
1175         vector<string> real_search_dirs;
1176         if (!filename.empty() && filename[0] == '/') {
1177                 real_search_dirs.push_back("");
1178         } else {
1179                 real_search_dirs = search_dirs;
1180         }
1181
1182         string path;
1183         int theme_code_ref;
1184         for (const string &dir : real_search_dirs) {
1185                 if (dir.empty()) {
1186                         path = filename;
1187                 } else {
1188                         path = dir + "/" + filename;
1189                 }
1190                 int err = luaL_loadfile(L, path.c_str());
1191                 if (err == 0) {
1192                         // Save the theme for when we're actually going to run it
1193                         // (we need to set up the right environment below first,
1194                         // and we couldn't do that before, because we didn't know the
1195                         // path to put in Nageru.THEME_PATH).
1196                         theme_code_ref = luaL_ref(L, LUA_REGISTRYINDEX);
1197                         assert(lua_gettop(L) == 0);
1198
1199                         success = true;
1200                         break;
1201                 }
1202                 errors.push_back(lua_tostring(L, -1));
1203                 lua_pop(L, 1);
1204                 if (err != LUA_ERRFILE) {
1205                         // The file actually loaded, but failed to parse somehow. Abort; don't try the next one.
1206                         break;
1207                 }
1208         }
1209
1210         if (!success) {
1211                 for (const string &error : errors) {
1212                         fprintf(stderr, "%s\n", error.c_str());
1213                 }
1214                 abort();
1215         }
1216         assert(lua_gettop(L) == 0);
1217
1218         // Make sure the path exposed to the theme (as Nageru.THEME_PATH;
1219         // can be useful for locating files when talking to CEF) is absolute.
1220         // In a sense, it would be nice if realpath() had a mode not to
1221         // resolve symlinks, but it doesn't, so we only call it if we don't
1222         // already have an absolute path (which may leave ../ elements etc.).
1223         if (path[0] == '/') {
1224                 theme_path = path;
1225         } else {
1226                 char *absolute_theme_path = realpath(path.c_str(), nullptr);
1227                 theme_path = absolute_theme_path;
1228                 free(absolute_theme_path);
1229         }
1230
1231         // Set up the API we provide.
1232         register_constants();
1233         register_class("Scene", Scene_funcs);
1234         register_class("Block", Block_funcs);
1235         register_class("EffectBlueprint", EffectBlueprint_funcs);
1236         register_class("EffectChain", EffectChain_funcs);
1237         register_class("LiveInputWrapper", LiveInputWrapper_funcs);
1238         register_class("ImageInput", ImageInput_funcs);
1239         register_class("VideoInput", VideoInput_funcs);
1240         register_class("HTMLInput", HTMLInput_funcs);
1241         register_class("IdentityEffect", IdentityEffect_funcs, IDENTITY_EFFECT);
1242         register_class("WhiteBalanceEffect", WhiteBalanceEffect_funcs, WHITE_BALANCE_EFFECT);
1243         register_class("ResampleEffect", ResampleEffect_funcs, RESAMPLE_EFFECT);
1244         register_class("PaddingEffect", PaddingEffect_funcs, PADDING_EFFECT);
1245         register_class("IntegralPaddingEffect", IntegralPaddingEffect_funcs, INTEGRAL_PADDING_EFFECT);
1246         register_class("OverlayEffect", OverlayEffect_funcs, OVERLAY_EFFECT);
1247         register_class("ResizeEffect", ResizeEffect_funcs, RESIZE_EFFECT);
1248         register_class("MultiplyEffect", MultiplyEffect_funcs, MULTIPLY_EFFECT);
1249         register_class("MixEffect", MixEffect_funcs, MIX_EFFECT);
1250         register_class("LiftGammaGainEffect", LiftGammaGainEffect_funcs, LIFT_GAMMA_GAIN_EFFECT);
1251         register_class("InputStateInfo", InputStateInfo_funcs);
1252         register_class("ThemeMenu", ThemeMenu_funcs);
1253
1254         // Now actually run the theme to get everything set up.
1255         lua_rawgeti(L, LUA_REGISTRYINDEX, theme_code_ref);
1256         luaL_unref(L, LUA_REGISTRYINDEX, theme_code_ref);
1257         if (lua_pcall(L, 0, 0, 0)) {
1258                 fprintf(stderr, "Error when running %s: %s\n", path.c_str(), lua_tostring(L, -1));
1259                 abort();
1260         }
1261         assert(lua_gettop(L) == 0);
1262
1263         // Ask it for the number of channels.
1264         num_channels = call_num_channels(L);
1265 }
1266
1267 Theme::~Theme()
1268 {
1269         lua_close(L);
1270 }
1271
1272 void Theme::register_constants()
1273 {
1274         // Set Nageru.VIDEO_FORMAT_BGRA = bmusb::PixelFormat_8BitBGRA, etc.
1275         const vector<pair<string, int>> num_constants = {
1276                 { "VIDEO_FORMAT_BGRA", bmusb::PixelFormat_8BitBGRA },
1277                 { "VIDEO_FORMAT_YCBCR", bmusb::PixelFormat_8BitYCbCrPlanar },
1278         };
1279         const vector<pair<string, string>> str_constants = {
1280                 { "THEME_PATH", theme_path },
1281         };
1282
1283         lua_newtable(L);  // t = {}
1284
1285         for (const pair<string, int> &constant : num_constants) {
1286                 lua_pushstring(L, constant.first.c_str());
1287                 lua_pushinteger(L, constant.second);
1288                 lua_settable(L, 1);  // t[key] = value
1289         }
1290         for (const pair<string, string> &constant : str_constants) {
1291                 lua_pushstring(L, constant.first.c_str());
1292                 lua_pushstring(L, constant.second.c_str());
1293                 lua_settable(L, 1);  // t[key] = value
1294         }
1295
1296         lua_setglobal(L, "Nageru");  // Nageru = t
1297         assert(lua_gettop(L) == 0);
1298 }
1299
1300 void Theme::register_class(const char *class_name, const luaL_Reg *funcs, EffectType effect_type)
1301 {
1302         assert(lua_gettop(L) == 0);
1303         luaL_newmetatable(L, class_name);  // mt = {}
1304         lua_pushlightuserdata(L, this);
1305         luaL_setfuncs(L, funcs, 1);        // for (name,f in funcs) { mt[name] = f, with upvalue {theme} }
1306         lua_pushvalue(L, -1);
1307         lua_setfield(L, -2, "__index");    // mt.__index = mt
1308         if (effect_type != NO_EFFECT_TYPE) {
1309                 lua_pushnumber(L, effect_type);
1310                 lua_setfield(L, -2, "__effect_type_id");  // mt.__effect_type_id = effect_type
1311         }
1312         lua_setglobal(L, class_name);      // ClassName = mt
1313         assert(lua_gettop(L) == 0);
1314 }
1315
1316 Theme::Chain Theme::get_chain_from_effect_chain(EffectChain *effect_chain, unsigned num, const InputState &input_state)
1317 {
1318         if (!lua_isfunction(L, -1)) {
1319                 fprintf(stderr, "Argument #-1 should be a function\n");
1320                 abort();
1321         }
1322         lua_pushvalue(L, -1);
1323         shared_ptr<LuaRefWithDeleter> funcref(new LuaRefWithDeleter(&m, L, luaL_ref(L, LUA_REGISTRYINDEX)));
1324         lua_pop(L, 2);
1325
1326         Chain chain;
1327         chain.chain = effect_chain;
1328         chain.setup_chain = [this, funcref, input_state, effect_chain]{
1329                 lock_guard<mutex> lock(m);
1330
1331                 assert(this->input_state == nullptr);
1332                 this->input_state = &input_state;
1333
1334                 // Set up state, including connecting signals.
1335                 lua_rawgeti(L, LUA_REGISTRYINDEX, funcref->get());
1336                 if (lua_pcall(L, 0, 0, 0) != 0) {
1337                         fprintf(stderr, "error running chain setup callback: %s\n", lua_tostring(L, -1));
1338                         abort();
1339                 }
1340                 assert(lua_gettop(L) == 0);
1341
1342                 // The theme can't (or at least shouldn't!) call connect_signal() on
1343                 // each FFmpeg or CEF input, so we'll do it here.
1344                 if (video_signal_connections.count(effect_chain)) {
1345                         for (const VideoSignalConnection &conn : video_signal_connections[effect_chain]) {
1346                                 conn.wrapper->connect_signal_raw(conn.source->get_card_index(), input_state);
1347                         }
1348                 }
1349 #ifdef HAVE_CEF
1350                 if (html_signal_connections.count(effect_chain)) {
1351                         for (const CEFSignalConnection &conn : html_signal_connections[effect_chain]) {
1352                                 conn.wrapper->connect_signal_raw(conn.source->get_card_index(), input_state);
1353                         }
1354                 }
1355 #endif
1356
1357                 this->input_state = nullptr;
1358         };
1359         return chain;
1360 }
1361
1362 Theme::Chain Theme::get_chain(unsigned num, float t, unsigned width, unsigned height, const InputState &input_state)
1363 {
1364         const char *func_name = "get_scene";  // For error reporting.
1365         Chain chain;
1366
1367         lock_guard<mutex> lock(m);
1368         assert(lua_gettop(L) == 0);
1369         lua_getglobal(L, "get_scene");  /* function to be called */
1370         if (lua_isnil(L, -1)) {
1371                 // Try the pre-1.9.0 name for compatibility.
1372                 lua_pop(L, 1);
1373                 lua_getglobal(L, "get_chain");
1374                 func_name = "get_chain";
1375         }
1376         lua_pushnumber(L, num);
1377         lua_pushnumber(L, t);
1378         lua_pushnumber(L, width);
1379         lua_pushnumber(L, height);
1380         wrap_lua_object<InputStateInfo>(L, "InputStateInfo", input_state);
1381
1382         if (lua_pcall(L, 5, LUA_MULTRET, 0) != 0) {
1383                 fprintf(stderr, "error running function “%s”: %s\n", func_name, lua_tostring(L, -1));
1384                 abort();
1385         }
1386
1387         if (luaL_testudata(L, -1, "Scene") != nullptr) {
1388                 if (lua_gettop(L) != 1) {
1389                         luaL_error(L, "%s() for chain number %d returned an Scene, but also other items", func_name);
1390                 }
1391                 Scene *auto_effect_chain = (Scene *)luaL_testudata(L, -1, "Scene");
1392                 auto chain_and_setup = auto_effect_chain->get_chain(this, L, num, input_state);
1393                 chain.chain = chain_and_setup.first;
1394                 chain.setup_chain = move(chain_and_setup.second);
1395         } else if (luaL_testudata(L, -2, "EffectChain") != nullptr) {
1396                 // Old-style (pre-Nageru 1.9.0) return of a single chain and prepare function.
1397                 if (lua_gettop(L) != 2) {
1398                         luaL_error(L, "%s() for chain number %d returned an EffectChain, but needs to also return a prepare function (or use Scene)", func_name);
1399                 }
1400                 EffectChain *effect_chain = (EffectChain *)luaL_testudata(L, -2, "EffectChain");
1401                 chain = get_chain_from_effect_chain(effect_chain, num, input_state);
1402         } else {
1403                 luaL_error(L, "%s() for chain number %d did not return an EffectChain or Scene\n", func_name, num);
1404         }
1405         assert(lua_gettop(L) == 0);
1406
1407         // TODO: Can we do better, e.g. by running setup_chain() and seeing what it references?
1408         // Actually, setup_chain does maybe hold all the references we need now anyway?
1409         chain.input_frames.reserve(num_cards * FRAME_HISTORY_LENGTH);
1410         for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
1411                 for (unsigned frame_num = 0; frame_num < FRAME_HISTORY_LENGTH; ++frame_num) {
1412                         chain.input_frames.push_back(input_state.buffered_frames[card_index][frame_num].frame);
1413                 }
1414         }
1415
1416         return chain;
1417 }
1418
1419 string Theme::get_channel_name(unsigned channel)
1420 {
1421         lock_guard<mutex> lock(m);
1422         lua_getglobal(L, "channel_name");
1423         lua_pushnumber(L, channel);
1424         if (lua_pcall(L, 1, 1, 0) != 0) {
1425                 fprintf(stderr, "error running function `channel_name': %s\n", lua_tostring(L, -1));
1426                 abort();
1427         }
1428         const char *ret = lua_tostring(L, -1);
1429         if (ret == nullptr) {
1430                 fprintf(stderr, "function `channel_name' returned nil for channel %d\n", channel);
1431                 abort();
1432         }
1433
1434         string retstr = ret;
1435         lua_pop(L, 1);
1436         assert(lua_gettop(L) == 0);
1437         return retstr;
1438 }
1439
1440 int Theme::get_channel_signal(unsigned channel)
1441 {
1442         lock_guard<mutex> lock(m);
1443         lua_getglobal(L, "channel_signal");
1444         lua_pushnumber(L, channel);
1445         if (lua_pcall(L, 1, 1, 0) != 0) {
1446                 fprintf(stderr, "error running function `channel_signal': %s\n", lua_tostring(L, -1));
1447                 abort();
1448         }
1449
1450         int ret = luaL_checknumber(L, 1);
1451         lua_pop(L, 1);
1452         assert(lua_gettop(L) == 0);
1453         return ret;
1454 }
1455
1456 std::string Theme::get_channel_color(unsigned channel)
1457 {
1458         lock_guard<mutex> lock(m);
1459         lua_getglobal(L, "channel_color");
1460         lua_pushnumber(L, channel);
1461         if (lua_pcall(L, 1, 1, 0) != 0) {
1462                 fprintf(stderr, "error running function `channel_color': %s\n", lua_tostring(L, -1));
1463                 abort();
1464         }
1465
1466         const char *ret = lua_tostring(L, -1);
1467         if (ret == nullptr) {
1468                 fprintf(stderr, "function `channel_color' returned nil for channel %d\n", channel);
1469                 abort();
1470         }
1471
1472         string retstr = ret;
1473         lua_pop(L, 1);
1474         assert(lua_gettop(L) == 0);
1475         return retstr;
1476 }
1477
1478 bool Theme::get_supports_set_wb(unsigned channel)
1479 {
1480         lock_guard<mutex> lock(m);
1481         lua_getglobal(L, "supports_set_wb");
1482         lua_pushnumber(L, channel);
1483         if (lua_pcall(L, 1, 1, 0) != 0) {
1484                 fprintf(stderr, "error running function `supports_set_wb': %s\n", lua_tostring(L, -1));
1485                 abort();
1486         }
1487
1488         bool ret = checkbool(L, -1);
1489         lua_pop(L, 1);
1490         assert(lua_gettop(L) == 0);
1491         return ret;
1492 }
1493
1494 void Theme::set_wb(unsigned channel, double r, double g, double b)
1495 {
1496         lock_guard<mutex> lock(m);
1497         lua_getglobal(L, "set_wb");
1498         lua_pushnumber(L, channel);
1499         lua_pushnumber(L, r);
1500         lua_pushnumber(L, g);
1501         lua_pushnumber(L, b);
1502         if (lua_pcall(L, 4, 0, 0) != 0) {
1503                 fprintf(stderr, "error running function `set_wb': %s\n", lua_tostring(L, -1));
1504                 abort();
1505         }
1506
1507         assert(lua_gettop(L) == 0);
1508 }
1509
1510 vector<string> Theme::get_transition_names(float t)
1511 {
1512         lock_guard<mutex> lock(m);
1513         lua_getglobal(L, "get_transitions");
1514         lua_pushnumber(L, t);
1515         if (lua_pcall(L, 1, 1, 0) != 0) {
1516                 fprintf(stderr, "error running function `get_transitions': %s\n", lua_tostring(L, -1));
1517                 abort();
1518         }
1519
1520         vector<string> ret;
1521         lua_pushnil(L);
1522         while (lua_next(L, -2) != 0) {
1523                 ret.push_back(lua_tostring(L, -1));
1524                 lua_pop(L, 1);
1525         }
1526         lua_pop(L, 1);
1527         assert(lua_gettop(L) == 0);
1528         return ret;
1529 }
1530
1531 int Theme::map_signal(int signal_num)
1532 {
1533         // Negative numbers map to raw signals.
1534         if (signal_num < 0) {
1535                 return -1 - signal_num;
1536         }
1537
1538         lock_guard<mutex> lock(map_m);
1539         if (signal_to_card_mapping.count(signal_num)) {
1540                 return signal_to_card_mapping[signal_num];
1541         }
1542
1543         int card_index;
1544         if (global_flags.output_card != -1 && num_cards > 1) {
1545                 // Try to exclude the output card from the default card_index.
1546                 card_index = signal_num % (num_cards - 1);
1547                 if (card_index >= global_flags.output_card) {
1548                          ++card_index;
1549                 }
1550                 if (signal_num >= int(num_cards - 1)) {
1551                         print_warning(L, "Theme asked for input %d, but we only have %u input card(s) (card %d is busy with output).\n",
1552                                 signal_num, num_cards - 1, global_flags.output_card);
1553                         fprintf(stderr, "Mapping to card %d instead.\n", card_index);
1554                 }
1555         } else {
1556                 card_index = signal_num % num_cards;
1557                 if (signal_num >= int(num_cards)) {
1558                         print_warning(L, "Theme asked for input %d, but we only have %u card(s).\n", signal_num, num_cards);
1559                         fprintf(stderr, "Mapping to card %d instead.\n", card_index);
1560                 }
1561         }
1562         signal_to_card_mapping[signal_num] = card_index;
1563         return card_index;
1564 }
1565
1566 void Theme::set_signal_mapping(int signal_num, int card_num)
1567 {
1568         lock_guard<mutex> lock(map_m);
1569         assert(card_num < int(num_cards));
1570         signal_to_card_mapping[signal_num] = card_num;
1571 }
1572
1573 void Theme::transition_clicked(int transition_num, float t)
1574 {
1575         lock_guard<mutex> lock(m);
1576         lua_getglobal(L, "transition_clicked");
1577         lua_pushnumber(L, transition_num);
1578         lua_pushnumber(L, t);
1579
1580         if (lua_pcall(L, 2, 0, 0) != 0) {
1581                 fprintf(stderr, "error running function `transition_clicked': %s\n", lua_tostring(L, -1));
1582                 abort();
1583         }
1584         assert(lua_gettop(L) == 0);
1585 }
1586
1587 void Theme::channel_clicked(int preview_num)
1588 {
1589         lock_guard<mutex> lock(m);
1590         lua_getglobal(L, "channel_clicked");
1591         lua_pushnumber(L, preview_num);
1592
1593         if (lua_pcall(L, 1, 0, 0) != 0) {
1594                 fprintf(stderr, "error running function `channel_clicked': %s\n", lua_tostring(L, -1));
1595                 abort();
1596         }
1597         assert(lua_gettop(L) == 0);
1598 }
1599
1600 int Theme::set_theme_menu(lua_State *L)
1601 {
1602         for (const Theme::MenuEntry &entry : theme_menu) {
1603                 luaL_unref(L, LUA_REGISTRYINDEX, entry.lua_ref);
1604         }
1605         theme_menu.clear();
1606
1607         int num_elements = lua_gettop(L);
1608         for (int i = 1; i <= num_elements; ++i) {
1609                 lua_rawgeti(L, i, 1);
1610                 const string text = checkstdstring(L, -1);
1611                 lua_pop(L, 1);
1612
1613                 lua_rawgeti(L, i, 2);
1614                 luaL_checktype(L, -1, LUA_TFUNCTION);
1615                 int ref = luaL_ref(L, LUA_REGISTRYINDEX);
1616
1617                 theme_menu.push_back(MenuEntry{ text, ref });
1618         }
1619         lua_pop(L, num_elements);
1620         assert(lua_gettop(L) == 0);
1621
1622         if (theme_menu_callback != nullptr) {
1623                 theme_menu_callback();
1624         }
1625
1626         return 0;
1627 }
1628
1629 void Theme::theme_menu_entry_clicked(int lua_ref)
1630 {
1631         lock_guard<mutex> lock(m);
1632         lua_rawgeti(L, LUA_REGISTRYINDEX, lua_ref);
1633         if (lua_pcall(L, 0, 0, 0) != 0) {
1634                 fprintf(stderr, "error running menu callback: %s\n", lua_tostring(L, -1));
1635                 abort();
1636         }
1637 }