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