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