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