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