]> git.sesse.net Git - nageru/blob - theme.cpp
Do not link kaeru against CEF.
[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);
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);
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(*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);
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(*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         (*input)->connect_signal(signal_num);
426         return 0;
427 }
428
429 int ImageInput_new(lua_State* L)
430 {
431         assert(lua_gettop(L) == 1);
432         string filename = checkstdstring(L, 1);
433         return wrap_lua_object_nonowned<ImageInput>(L, "ImageInput", filename);
434 }
435
436 int VideoInput_new(lua_State* L)
437 {
438         assert(lua_gettop(L) == 2);
439         string filename = checkstdstring(L, 1);
440         int pixel_format = luaL_checknumber(L, 2);
441         if (pixel_format != bmusb::PixelFormat_8BitYCbCrPlanar &&
442             pixel_format != bmusb::PixelFormat_8BitBGRA) {
443                 fprintf(stderr, "WARNING: Invalid enum %d used for video format, choosing Y'CbCr.\n",
444                         pixel_format);
445                 pixel_format = bmusb::PixelFormat_8BitYCbCrPlanar;
446         }
447         int ret = wrap_lua_object_nonowned<FFmpegCapture>(L, "VideoInput", filename, global_flags.width, global_flags.height);
448         if (ret == 1) {
449                 FFmpegCapture **capture = (FFmpegCapture **)lua_touserdata(L, -1);
450                 (*capture)->set_pixel_format(bmusb::PixelFormat(pixel_format));
451
452                 Theme *theme = get_theme_updata(L);
453                 theme->register_video_input(*capture);
454         }
455         return ret;
456 }
457
458 int VideoInput_rewind(lua_State* L)
459 {
460         assert(lua_gettop(L) == 1);
461         FFmpegCapture **video_input = (FFmpegCapture **)luaL_checkudata(L, 1, "VideoInput");
462         (*video_input)->rewind();
463         return 0;
464 }
465
466 int VideoInput_change_rate(lua_State* L)
467 {
468         assert(lua_gettop(L) == 2);
469         FFmpegCapture **video_input = (FFmpegCapture **)luaL_checkudata(L, 1, "VideoInput");
470         double new_rate = luaL_checknumber(L, 2);
471         (*video_input)->change_rate(new_rate);
472         return 0;
473 }
474
475 int VideoInput_get_signal_num(lua_State* L)
476 {
477         assert(lua_gettop(L) == 1);
478         FFmpegCapture **video_input = (FFmpegCapture **)luaL_checkudata(L, 1, "VideoInput");
479         lua_pushnumber(L, -1 - (*video_input)->get_card_index());
480         return 1;
481 }
482
483 int HTMLInput_new(lua_State* L)
484 {
485 #ifdef HAVE_CEF
486         assert(lua_gettop(L) == 1);
487         string url = checkstdstring(L, 1);
488         int ret = wrap_lua_object_nonowned<CEFCapture>(L, "HTMLInput", url, global_flags.width, global_flags.height);
489         if (ret == 1) {
490                 CEFCapture **capture = (CEFCapture **)lua_touserdata(L, -1);
491                 Theme *theme = get_theme_updata(L);
492                 theme->register_html_input(*capture);
493         }
494         return ret;
495 #else
496         fprintf(stderr, "This version of Nageru has been compiled without CEF support.\n");
497         fprintf(stderr, "HTMLInput is not available.\n");
498         exit(1);
499 #endif
500 }
501
502 #ifdef HAVE_CEF
503 int HTMLInput_set_url(lua_State* L)
504 {
505         assert(lua_gettop(L) == 2);
506         CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
507         string new_url = checkstdstring(L, 2);
508         (*video_input)->set_url(new_url);
509         return 0;
510 }
511
512 int HTMLInput_reload(lua_State* L)
513 {
514         assert(lua_gettop(L) == 1);
515         CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
516         (*video_input)->reload();
517         return 0;
518 }
519
520 int HTMLInput_set_max_fps(lua_State* L)
521 {
522         assert(lua_gettop(L) == 2);
523         CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
524         int max_fps = lrint(luaL_checknumber(L, 2));
525         (*video_input)->set_max_fps(max_fps);
526         return 0;
527 }
528
529 int HTMLInput_execute_javascript_async(lua_State* L)
530 {
531         assert(lua_gettop(L) == 2);
532         CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
533         string js = checkstdstring(L, 2);
534         (*video_input)->execute_javascript_async(js);
535         return 0;
536 }
537
538 int HTMLInput_resize(lua_State* L)
539 {
540         assert(lua_gettop(L) == 3);
541         CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
542         unsigned width = lrint(luaL_checknumber(L, 2));
543         unsigned height = lrint(luaL_checknumber(L, 3));
544         (*video_input)->resize(width, height);
545         return 0;
546 }
547
548 int HTMLInput_get_signal_num(lua_State* L)
549 {
550         assert(lua_gettop(L) == 1);
551         CEFCapture **video_input = (CEFCapture **)luaL_checkudata(L, 1, "HTMLInput");
552         lua_pushnumber(L, -1 - (*video_input)->get_card_index());
553         return 1;
554 }
555 #endif
556
557 int WhiteBalanceEffect_new(lua_State* L)
558 {
559         assert(lua_gettop(L) == 0);
560         return wrap_lua_object_nonowned<WhiteBalanceEffect>(L, "WhiteBalanceEffect");
561 }
562
563 int ResampleEffect_new(lua_State* L)
564 {
565         assert(lua_gettop(L) == 0);
566         return wrap_lua_object_nonowned<ResampleEffect>(L, "ResampleEffect");
567 }
568
569 int PaddingEffect_new(lua_State* L)
570 {
571         assert(lua_gettop(L) == 0);
572         return wrap_lua_object_nonowned<PaddingEffect>(L, "PaddingEffect");
573 }
574
575 int IntegralPaddingEffect_new(lua_State* L)
576 {
577         assert(lua_gettop(L) == 0);
578         return wrap_lua_object_nonowned<IntegralPaddingEffect>(L, "IntegralPaddingEffect");
579 }
580
581 int OverlayEffect_new(lua_State* L)
582 {
583         assert(lua_gettop(L) == 0);
584         return wrap_lua_object_nonowned<OverlayEffect>(L, "OverlayEffect");
585 }
586
587 int ResizeEffect_new(lua_State* L)
588 {
589         assert(lua_gettop(L) == 0);
590         return wrap_lua_object_nonowned<ResizeEffect>(L, "ResizeEffect");
591 }
592
593 int MultiplyEffect_new(lua_State* L)
594 {
595         assert(lua_gettop(L) == 0);
596         return wrap_lua_object_nonowned<MultiplyEffect>(L, "MultiplyEffect");
597 }
598
599 int MixEffect_new(lua_State* L)
600 {
601         assert(lua_gettop(L) == 0);
602         return wrap_lua_object_nonowned<MixEffect>(L, "MixEffect");
603 }
604
605 int InputStateInfo_get_width(lua_State* L)
606 {
607         assert(lua_gettop(L) == 2);
608         InputStateInfo *input_state_info = get_input_state_info(L, 1);
609         Theme *theme = get_theme_updata(L);
610         int signal_num = theme->map_signal(luaL_checknumber(L, 2));
611         lua_pushnumber(L, input_state_info->last_width[signal_num]);
612         return 1;
613 }
614
615 int InputStateInfo_get_height(lua_State* L)
616 {
617         assert(lua_gettop(L) == 2);
618         InputStateInfo *input_state_info = get_input_state_info(L, 1);
619         Theme *theme = get_theme_updata(L);
620         int signal_num = theme->map_signal(luaL_checknumber(L, 2));
621         lua_pushnumber(L, input_state_info->last_height[signal_num]);
622         return 1;
623 }
624
625 int InputStateInfo_get_interlaced(lua_State* L)
626 {
627         assert(lua_gettop(L) == 2);
628         InputStateInfo *input_state_info = get_input_state_info(L, 1);
629         Theme *theme = get_theme_updata(L);
630         int signal_num = theme->map_signal(luaL_checknumber(L, 2));
631         lua_pushboolean(L, input_state_info->last_interlaced[signal_num]);
632         return 1;
633 }
634
635 int InputStateInfo_get_has_signal(lua_State* L)
636 {
637         assert(lua_gettop(L) == 2);
638         InputStateInfo *input_state_info = get_input_state_info(L, 1);
639         Theme *theme = get_theme_updata(L);
640         int signal_num = theme->map_signal(luaL_checknumber(L, 2));
641         lua_pushboolean(L, input_state_info->last_has_signal[signal_num]);
642         return 1;
643 }
644
645 int InputStateInfo_get_is_connected(lua_State* L)
646 {
647         assert(lua_gettop(L) == 2);
648         InputStateInfo *input_state_info = get_input_state_info(L, 1);
649         Theme *theme = get_theme_updata(L);
650         int signal_num = theme->map_signal(luaL_checknumber(L, 2));
651         lua_pushboolean(L, input_state_info->last_is_connected[signal_num]);
652         return 1;
653 }
654
655 int InputStateInfo_get_frame_rate_nom(lua_State* L)
656 {
657         assert(lua_gettop(L) == 2);
658         InputStateInfo *input_state_info = get_input_state_info(L, 1);
659         Theme *theme = get_theme_updata(L);
660         int signal_num = theme->map_signal(luaL_checknumber(L, 2));
661         lua_pushnumber(L, input_state_info->last_frame_rate_nom[signal_num]);
662         return 1;
663 }
664
665 int InputStateInfo_get_frame_rate_den(lua_State* L)
666 {
667         assert(lua_gettop(L) == 2);
668         InputStateInfo *input_state_info = get_input_state_info(L, 1);
669         Theme *theme = get_theme_updata(L);
670         int signal_num = theme->map_signal(luaL_checknumber(L, 2));
671         lua_pushnumber(L, input_state_info->last_frame_rate_den[signal_num]);
672         return 1;
673 }
674
675 int Effect_set_float(lua_State *L)
676 {
677         assert(lua_gettop(L) == 3);
678         Effect *effect = (Effect *)get_effect(L, 1);
679         string key = checkstdstring(L, 2);
680         float value = luaL_checknumber(L, 3);
681         if (!effect->set_float(key, value)) {
682                 luaL_error(L, "Effect refused set_float(\"%s\", %d) (invalid key?)", key.c_str(), int(value));
683         }
684         return 0;
685 }
686
687 int Effect_set_int(lua_State *L)
688 {
689         assert(lua_gettop(L) == 3);
690         Effect *effect = (Effect *)get_effect(L, 1);
691         string key = checkstdstring(L, 2);
692         float value = luaL_checknumber(L, 3);
693         if (!effect->set_int(key, value)) {
694                 luaL_error(L, "Effect refused set_int(\"%s\", %d) (invalid key?)", key.c_str(), int(value));
695         }
696         return 0;
697 }
698
699 int Effect_set_vec3(lua_State *L)
700 {
701         assert(lua_gettop(L) == 5);
702         Effect *effect = (Effect *)get_effect(L, 1);
703         string key = checkstdstring(L, 2);
704         float v[3];
705         v[0] = luaL_checknumber(L, 3);
706         v[1] = luaL_checknumber(L, 4);
707         v[2] = luaL_checknumber(L, 5);
708         if (!effect->set_vec3(key, v)) {
709                 luaL_error(L, "Effect refused set_vec3(\"%s\", %f, %f, %f) (invalid key?)", key.c_str(),
710                         v[0], v[1], v[2]);
711         }
712         return 0;
713 }
714
715 int Effect_set_vec4(lua_State *L)
716 {
717         assert(lua_gettop(L) == 6);
718         Effect *effect = (Effect *)get_effect(L, 1);
719         string key = checkstdstring(L, 2);
720         float v[4];
721         v[0] = luaL_checknumber(L, 3);
722         v[1] = luaL_checknumber(L, 4);
723         v[2] = luaL_checknumber(L, 5);
724         v[3] = luaL_checknumber(L, 6);
725         if (!effect->set_vec4(key, v)) {
726                 luaL_error(L, "Effect refused set_vec4(\"%s\", %f, %f, %f, %f) (invalid key?)", key.c_str(),
727                         v[0], v[1], v[2], v[3]);
728         }
729         return 0;
730 }
731
732 const luaL_Reg EffectChain_funcs[] = {
733         { "new", EffectChain_new },
734         { "__gc", EffectChain_gc },
735         { "add_live_input", EffectChain_add_live_input },
736         { "add_video_input", EffectChain_add_video_input },
737 #ifdef HAVE_CEF
738         { "add_html_input", EffectChain_add_html_input },
739 #endif
740         { "add_effect", EffectChain_add_effect },
741         { "finalize", EffectChain_finalize },
742         { NULL, NULL }
743 };
744
745 const luaL_Reg LiveInputWrapper_funcs[] = {
746         { "connect_signal", LiveInputWrapper_connect_signal },
747         { NULL, NULL }
748 };
749
750 const luaL_Reg ImageInput_funcs[] = {
751         { "new", ImageInput_new },
752         { "set_float", Effect_set_float },
753         { "set_int", Effect_set_int },
754         { "set_vec3", Effect_set_vec3 },
755         { "set_vec4", Effect_set_vec4 },
756         { NULL, NULL }
757 };
758
759 const luaL_Reg VideoInput_funcs[] = {
760         { "new", VideoInput_new },
761         { "rewind", VideoInput_rewind },
762         { "change_rate", VideoInput_change_rate },
763         { "get_signal_num", VideoInput_get_signal_num },
764         { NULL, NULL }
765 };
766
767 const luaL_Reg HTMLInput_funcs[] = {
768         { "new", HTMLInput_new },
769 #ifdef HAVE_CEF
770         { "set_url", HTMLInput_set_url },
771         { "reload", HTMLInput_reload },
772         { "set_max_fps", HTMLInput_set_max_fps },
773         { "execute_javascript_async", HTMLInput_execute_javascript_async },
774         { "resize", HTMLInput_resize },
775         { "get_signal_num", HTMLInput_get_signal_num },
776 #endif
777         { NULL, NULL }
778 };
779
780 const luaL_Reg WhiteBalanceEffect_funcs[] = {
781         { "new", WhiteBalanceEffect_new },
782         { "set_float", Effect_set_float },
783         { "set_int", Effect_set_int },
784         { "set_vec3", Effect_set_vec3 },
785         { "set_vec4", Effect_set_vec4 },
786         { NULL, NULL }
787 };
788
789 const luaL_Reg ResampleEffect_funcs[] = {
790         { "new", ResampleEffect_new },
791         { "set_float", Effect_set_float },
792         { "set_int", Effect_set_int },
793         { "set_vec3", Effect_set_vec3 },
794         { "set_vec4", Effect_set_vec4 },
795         { NULL, NULL }
796 };
797
798 const luaL_Reg PaddingEffect_funcs[] = {
799         { "new", PaddingEffect_new },
800         { "set_float", Effect_set_float },
801         { "set_int", Effect_set_int },
802         { "set_vec3", Effect_set_vec3 },
803         { "set_vec4", Effect_set_vec4 },
804         { NULL, NULL }
805 };
806
807 const luaL_Reg IntegralPaddingEffect_funcs[] = {
808         { "new", IntegralPaddingEffect_new },
809         { "set_float", Effect_set_float },
810         { "set_int", Effect_set_int },
811         { "set_vec3", Effect_set_vec3 },
812         { "set_vec4", Effect_set_vec4 },
813         { NULL, NULL }
814 };
815
816 const luaL_Reg OverlayEffect_funcs[] = {
817         { "new", OverlayEffect_new },
818         { "set_float", Effect_set_float },
819         { "set_int", Effect_set_int },
820         { "set_vec3", Effect_set_vec3 },
821         { "set_vec4", Effect_set_vec4 },
822         { NULL, NULL }
823 };
824
825 const luaL_Reg ResizeEffect_funcs[] = {
826         { "new", ResizeEffect_new },
827         { "set_float", Effect_set_float },
828         { "set_int", Effect_set_int },
829         { "set_vec3", Effect_set_vec3 },
830         { "set_vec4", Effect_set_vec4 },
831         { NULL, NULL }
832 };
833
834 const luaL_Reg MultiplyEffect_funcs[] = {
835         { "new", MultiplyEffect_new },
836         { "set_float", Effect_set_float },
837         { "set_int", Effect_set_int },
838         { "set_vec3", Effect_set_vec3 },
839         { "set_vec4", Effect_set_vec4 },
840         { NULL, NULL }
841 };
842
843 const luaL_Reg MixEffect_funcs[] = {
844         { "new", MixEffect_new },
845         { "set_float", Effect_set_float },
846         { "set_int", Effect_set_int },
847         { "set_vec3", Effect_set_vec3 },
848         { "set_vec4", Effect_set_vec4 },
849         { NULL, NULL }
850 };
851
852 const luaL_Reg InputStateInfo_funcs[] = {
853         { "get_width", InputStateInfo_get_width },
854         { "get_height", InputStateInfo_get_height },
855         { "get_interlaced", InputStateInfo_get_interlaced },
856         { "get_has_signal", InputStateInfo_get_has_signal },
857         { "get_is_connected", InputStateInfo_get_is_connected },
858         { "get_frame_rate_nom", InputStateInfo_get_frame_rate_nom },
859         { "get_frame_rate_den", InputStateInfo_get_frame_rate_den },
860         { NULL, NULL }
861 };
862
863 const luaL_Reg ThemeMenu_funcs[] = {
864         { "set", ThemeMenu_set },
865         { NULL, NULL }
866 };
867
868 }  // namespace
869
870 LiveInputWrapper::LiveInputWrapper(Theme *theme, EffectChain *chain, bmusb::PixelFormat pixel_format, bool override_bounce, bool deinterlace)
871         : theme(theme),
872           pixel_format(pixel_format),
873           deinterlace(deinterlace)
874 {
875         ImageFormat inout_format;
876         inout_format.color_space = COLORSPACE_sRGB;
877
878         // Gamma curve depends on the input signal, and we don't really get any
879         // indications. A camera would be expected to do Rec. 709, but
880         // I haven't checked if any do in practice. However, computers _do_ output
881         // in sRGB gamma (ie., they don't convert from sRGB to Rec. 709), and
882         // I wouldn't really be surprised if most non-professional cameras do, too.
883         // So we pick sRGB as the least evil here.
884         inout_format.gamma_curve = GAMMA_sRGB;
885
886         unsigned num_inputs;
887         if (deinterlace) {
888                 deinterlace_effect = new movit::DeinterlaceEffect();
889
890                 // As per the comments in deinterlace_effect.h, we turn this off.
891                 // The most likely interlaced input for us is either a camera
892                 // (where it's fine to turn it off) or a laptop (where it _should_
893                 // be turned off).
894                 CHECK(deinterlace_effect->set_int("enable_spatial_interlacing_check", 0));
895
896                 num_inputs = deinterlace_effect->num_inputs();
897                 assert(num_inputs == FRAME_HISTORY_LENGTH);
898         } else {
899                 num_inputs = 1;
900         }
901
902         if (pixel_format == bmusb::PixelFormat_8BitBGRA) {
903                 for (unsigned i = 0; i < num_inputs; ++i) {
904                         // We upload our textures ourselves, and Movit swaps
905                         // R and B in the shader if we specify BGRA, so lie and say RGBA.
906                         if (global_flags.can_disable_srgb_decoder) {
907                                 rgba_inputs.push_back(new sRGBSwitchingFlatInput(inout_format, FORMAT_RGBA_POSTMULTIPLIED_ALPHA, GL_UNSIGNED_BYTE, global_flags.width, global_flags.height));
908                         } else {
909                                 rgba_inputs.push_back(new NonsRGBCapableFlatInput(inout_format, FORMAT_RGBA_POSTMULTIPLIED_ALPHA, GL_UNSIGNED_BYTE, global_flags.width, global_flags.height));
910                         }
911                         chain->add_input(rgba_inputs.back());
912                 }
913
914                 if (deinterlace) {
915                         vector<Effect *> reverse_inputs(rgba_inputs.rbegin(), rgba_inputs.rend());
916                         chain->add_effect(deinterlace_effect, reverse_inputs);
917                 }
918         } else {
919                 assert(pixel_format == bmusb::PixelFormat_8BitYCbCr ||
920                        pixel_format == bmusb::PixelFormat_10BitYCbCr ||
921                        pixel_format == bmusb::PixelFormat_8BitYCbCrPlanar);
922
923                 // Most of these settings will be overridden later if using PixelFormat_8BitYCbCrPlanar.
924                 input_ycbcr_format.chroma_subsampling_x = (pixel_format == bmusb::PixelFormat_10BitYCbCr) ? 1 : 2;
925                 input_ycbcr_format.chroma_subsampling_y = 1;
926                 input_ycbcr_format.num_levels = (pixel_format == bmusb::PixelFormat_10BitYCbCr) ? 1024 : 256;
927                 input_ycbcr_format.cb_x_position = 0.0;
928                 input_ycbcr_format.cr_x_position = 0.0;
929                 input_ycbcr_format.cb_y_position = 0.5;
930                 input_ycbcr_format.cr_y_position = 0.5;
931                 input_ycbcr_format.luma_coefficients = YCBCR_REC_709;  // Will be overridden later even if not planar.
932                 input_ycbcr_format.full_range = false;  // Will be overridden later even if not planar.
933
934                 for (unsigned i = 0; i < num_inputs; ++i) {
935                         // When using 10-bit input, we're converting to interleaved through v210Converter.
936                         YCbCrInputSplitting splitting;
937                         if (pixel_format == bmusb::PixelFormat_10BitYCbCr) {
938                                 splitting = YCBCR_INPUT_INTERLEAVED;
939                         } else if (pixel_format == bmusb::PixelFormat_8BitYCbCr) {
940                                 splitting = YCBCR_INPUT_SPLIT_Y_AND_CBCR;
941                         } else {
942                                 splitting = YCBCR_INPUT_PLANAR;
943                         }
944                         if (override_bounce) {
945                                 ycbcr_inputs.push_back(new NonBouncingYCbCrInput(inout_format, input_ycbcr_format, global_flags.width, global_flags.height, splitting));
946                         } else {
947                                 ycbcr_inputs.push_back(new YCbCrInput(inout_format, input_ycbcr_format, global_flags.width, global_flags.height, splitting));
948                         }
949                         chain->add_input(ycbcr_inputs.back());
950                 }
951
952                 if (deinterlace) {
953                         vector<Effect *> reverse_inputs(ycbcr_inputs.rbegin(), ycbcr_inputs.rend());
954                         chain->add_effect(deinterlace_effect, reverse_inputs);
955                 }
956         }
957 }
958
959 void LiveInputWrapper::connect_signal(int signal_num)
960 {
961         if (global_mixer == nullptr) {
962                 // No data yet.
963                 return;
964         }
965
966         signal_num = theme->map_signal(signal_num);
967         connect_signal_raw(signal_num, *theme->input_state);
968 }
969
970 void LiveInputWrapper::connect_signal_raw(int signal_num, const InputState &input_state)
971 {
972         BufferedFrame first_frame = input_state.buffered_frames[signal_num][0];
973         if (first_frame.frame == nullptr) {
974                 // No data yet.
975                 return;
976         }
977         unsigned width, height;
978         {
979                 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)first_frame.frame->userdata;
980                 width = userdata->last_width[first_frame.field_number];
981                 height = userdata->last_height[first_frame.field_number];
982         }
983
984         movit::YCbCrLumaCoefficients ycbcr_coefficients = input_state.ycbcr_coefficients[signal_num];
985         bool full_range = input_state.full_range[signal_num];
986
987         if (input_state.ycbcr_coefficients_auto[signal_num]) {
988                 full_range = false;
989
990                 // The Blackmagic driver docs claim that the device outputs Y'CbCr
991                 // according to Rec. 601, but this seems to indicate the subsampling
992                 // positions only, as they publish Y'CbCr → RGB formulas that are
993                 // different for HD and SD (corresponding to Rec. 709 and 601, respectively),
994                 // and a Lenovo X1 gen 3 I used to test definitely outputs Rec. 709
995                 // (at least up to rounding error). Other devices seem to use Rec. 601
996                 // even on HD resolutions. Nevertheless, Rec. 709 _is_ the right choice
997                 // for HD, so we default to that if the user hasn't set anything.
998                 if (height >= 720) {
999                         ycbcr_coefficients = YCBCR_REC_709;
1000                 } else {
1001                         ycbcr_coefficients = YCBCR_REC_601;
1002                 }
1003         }
1004
1005         // This is a global, but it doesn't really matter.
1006         input_ycbcr_format.luma_coefficients = ycbcr_coefficients;
1007         input_ycbcr_format.full_range = full_range;
1008
1009         BufferedFrame last_good_frame = first_frame;
1010         for (unsigned i = 0; i < max(ycbcr_inputs.size(), rgba_inputs.size()); ++i) {
1011                 BufferedFrame frame = input_state.buffered_frames[signal_num][i];
1012                 if (frame.frame == nullptr) {
1013                         // Not enough data; reuse last frame (well, field).
1014                         // This is suboptimal, but we have nothing better.
1015                         frame = last_good_frame;
1016                 }
1017                 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
1018
1019                 unsigned this_width = userdata->last_width[frame.field_number];
1020                 unsigned this_height = userdata->last_height[frame.field_number];
1021                 if (this_width != width || this_height != height) {
1022                         // Resolution changed; reuse last frame/field.
1023                         frame = last_good_frame;
1024                         userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
1025                 }
1026
1027                 assert(userdata->pixel_format == pixel_format);
1028                 switch (pixel_format) {
1029                 case bmusb::PixelFormat_8BitYCbCr:
1030                         ycbcr_inputs[i]->set_texture_num(0, userdata->tex_y[frame.field_number]);
1031                         ycbcr_inputs[i]->set_texture_num(1, userdata->tex_cbcr[frame.field_number]);
1032                         ycbcr_inputs[i]->change_ycbcr_format(input_ycbcr_format);
1033                         ycbcr_inputs[i]->set_width(width);
1034                         ycbcr_inputs[i]->set_height(height);
1035                         break;
1036                 case bmusb::PixelFormat_8BitYCbCrPlanar:
1037                         ycbcr_inputs[i]->set_texture_num(0, userdata->tex_y[frame.field_number]);
1038                         ycbcr_inputs[i]->set_texture_num(1, userdata->tex_cb[frame.field_number]);
1039                         ycbcr_inputs[i]->set_texture_num(2, userdata->tex_cr[frame.field_number]);
1040                         ycbcr_inputs[i]->change_ycbcr_format(userdata->ycbcr_format);
1041                         ycbcr_inputs[i]->set_width(width);
1042                         ycbcr_inputs[i]->set_height(height);
1043                         break;
1044                 case bmusb::PixelFormat_10BitYCbCr:
1045                         ycbcr_inputs[i]->set_texture_num(0, userdata->tex_444[frame.field_number]);
1046                         ycbcr_inputs[i]->change_ycbcr_format(input_ycbcr_format);
1047                         ycbcr_inputs[i]->set_width(width);
1048                         ycbcr_inputs[i]->set_height(height);
1049                         break;
1050                 case bmusb::PixelFormat_8BitBGRA:
1051                         rgba_inputs[i]->set_texture_num(userdata->tex_rgba[frame.field_number]);
1052                         rgba_inputs[i]->set_width(width);
1053                         rgba_inputs[i]->set_height(height);
1054                         break;
1055                 default:
1056                         assert(false);
1057                 }
1058
1059                 last_good_frame = frame;
1060         }
1061
1062         if (deinterlace) {
1063                 BufferedFrame frame = input_state.buffered_frames[signal_num][0];
1064                 CHECK(deinterlace_effect->set_int("current_field_position", frame.field_number));
1065         }
1066 }
1067
1068 namespace {
1069
1070 int call_num_channels(lua_State *L)
1071 {
1072         lua_getglobal(L, "num_channels");
1073
1074         if (lua_pcall(L, 0, 1, 0) != 0) {
1075                 fprintf(stderr, "error running function `num_channels': %s\n", lua_tostring(L, -1));
1076                 exit(1);
1077         }
1078
1079         int num_channels = luaL_checknumber(L, 1);
1080         lua_pop(L, 1);
1081         assert(lua_gettop(L) == 0);
1082         return num_channels;
1083 }
1084
1085 }  // namespace
1086
1087 Theme::Theme(const string &filename, const vector<string> &search_dirs, ResourcePool *resource_pool, unsigned num_cards)
1088         : resource_pool(resource_pool), num_cards(num_cards), signal_to_card_mapping(global_flags.default_stream_mapping)
1089 {
1090         L = luaL_newstate();
1091         luaL_openlibs(L);
1092
1093         // Search through all directories until we find a file that will load
1094         // (as in, does not return LUA_ERRFILE); then run it. We store load errors
1095         // from all the attempts, and show them once we know we can't find any of them.
1096         lua_settop(L, 0);
1097         vector<string> errors;
1098         bool success = false;
1099
1100         vector<string> real_search_dirs;
1101         if (!filename.empty() && filename[0] == '/') {
1102                 real_search_dirs.push_back("");
1103         } else {
1104                 real_search_dirs = search_dirs;
1105         }
1106
1107         string path;
1108         int theme_code_ref;
1109         for (const string &dir : real_search_dirs) {
1110                 if (dir.empty()) {
1111                         path = filename;
1112                 } else {
1113                         path = dir + "/" + filename;
1114                 }
1115                 int err = luaL_loadfile(L, path.c_str());
1116                 if (err == 0) {
1117                         // Save the theme for when we're actually going to run it
1118                         // (we need to set up the right environment below first,
1119                         // and we couldn't do that before, because we didn't know the
1120                         // path to put in Nageru.THEME_PATH).
1121                         theme_code_ref = luaL_ref(L, LUA_REGISTRYINDEX);
1122                         assert(lua_gettop(L) == 0);
1123
1124                         success = true;
1125                         break;
1126                 }
1127                 errors.push_back(lua_tostring(L, -1));
1128                 lua_pop(L, 1);
1129                 if (err != LUA_ERRFILE) {
1130                         // The file actually loaded, but failed to parse somehow. Abort; don't try the next one.
1131                         break;
1132                 }
1133         }
1134
1135         if (!success) {
1136                 for (const string &error : errors) {
1137                         fprintf(stderr, "%s\n", error.c_str());
1138                 }
1139                 exit(1);
1140         }
1141         assert(lua_gettop(L) == 0);
1142
1143         // Make sure the path exposed to the theme (as Nageru.THEME_PATH;
1144         // can be useful for locating files when talking to CEF) is absolute.
1145         // In a sense, it would be nice if realpath() had a mode not to
1146         // resolve symlinks, but it doesn't, so we only call it if we don't
1147         // already have an absolute path (which may leave ../ elements etc.).
1148         if (path[0] == '/') {
1149                 theme_path = path;
1150         } else {
1151                 char *absolute_theme_path = realpath(path.c_str(), nullptr);
1152                 theme_path = absolute_theme_path;
1153                 free(absolute_theme_path);
1154         }
1155
1156         // Set up the API we provide.
1157         register_constants();
1158         register_class("EffectChain", EffectChain_funcs);
1159         register_class("LiveInputWrapper", LiveInputWrapper_funcs);
1160         register_class("ImageInput", ImageInput_funcs);
1161         register_class("VideoInput", VideoInput_funcs);
1162         register_class("HTMLInput", HTMLInput_funcs);
1163         register_class("WhiteBalanceEffect", WhiteBalanceEffect_funcs);
1164         register_class("ResampleEffect", ResampleEffect_funcs);
1165         register_class("PaddingEffect", PaddingEffect_funcs);
1166         register_class("IntegralPaddingEffect", IntegralPaddingEffect_funcs);
1167         register_class("OverlayEffect", OverlayEffect_funcs);
1168         register_class("ResizeEffect", ResizeEffect_funcs);
1169         register_class("MultiplyEffect", MultiplyEffect_funcs);
1170         register_class("MixEffect", MixEffect_funcs);
1171         register_class("InputStateInfo", InputStateInfo_funcs);
1172         register_class("ThemeMenu", ThemeMenu_funcs);
1173
1174         // Now actually run the theme to get everything set up.
1175         lua_rawgeti(L, LUA_REGISTRYINDEX, theme_code_ref);
1176         luaL_unref(L, LUA_REGISTRYINDEX, theme_code_ref);
1177         if (lua_pcall(L, 0, 0, 0)) {
1178                 fprintf(stderr, "Error when running %s: %s\n", path.c_str(), lua_tostring(L, -1));
1179                 exit(1);
1180         }
1181         assert(lua_gettop(L) == 0);
1182
1183         // Ask it for the number of channels.
1184         num_channels = call_num_channels(L);
1185 }
1186
1187 Theme::~Theme()
1188 {
1189         lua_close(L);
1190 }
1191
1192 void Theme::register_constants()
1193 {
1194         // Set Nageru.VIDEO_FORMAT_BGRA = bmusb::PixelFormat_8BitBGRA, etc.
1195         const vector<pair<string, int>> num_constants = {
1196                 { "VIDEO_FORMAT_BGRA", bmusb::PixelFormat_8BitBGRA },
1197                 { "VIDEO_FORMAT_YCBCR", bmusb::PixelFormat_8BitYCbCrPlanar },
1198         };
1199         const vector<pair<string, string>> str_constants = {
1200                 { "THEME_PATH", theme_path },
1201         };
1202
1203         lua_newtable(L);  // t = {}
1204
1205         for (const pair<string, int> &constant : num_constants) {
1206                 lua_pushstring(L, constant.first.c_str());
1207                 lua_pushinteger(L, constant.second);
1208                 lua_settable(L, 1);  // t[key] = value
1209         }
1210         for (const pair<string, string> &constant : str_constants) {
1211                 lua_pushstring(L, constant.first.c_str());
1212                 lua_pushstring(L, constant.second.c_str());
1213                 lua_settable(L, 1);  // t[key] = value
1214         }
1215
1216         lua_setglobal(L, "Nageru");  // Nageru = t
1217         assert(lua_gettop(L) == 0);
1218 }
1219
1220 void Theme::register_class(const char *class_name, const luaL_Reg *funcs)
1221 {
1222         assert(lua_gettop(L) == 0);
1223         luaL_newmetatable(L, class_name);  // mt = {}
1224         lua_pushlightuserdata(L, this);
1225         luaL_setfuncs(L, funcs, 1);        // for (name,f in funcs) { mt[name] = f, with upvalue {theme} }
1226         lua_pushvalue(L, -1);
1227         lua_setfield(L, -2, "__index");    // mt.__index = mt
1228         lua_setglobal(L, class_name);      // ClassName = mt
1229         assert(lua_gettop(L) == 0);
1230 }
1231
1232 Theme::Chain Theme::get_chain(unsigned num, float t, unsigned width, unsigned height, InputState input_state) 
1233 {
1234         Chain chain;
1235
1236         unique_lock<mutex> lock(m);
1237         assert(lua_gettop(L) == 0);
1238         lua_getglobal(L, "get_chain");  /* function to be called */
1239         lua_pushnumber(L, num);
1240         lua_pushnumber(L, t);
1241         lua_pushnumber(L, width);
1242         lua_pushnumber(L, height);
1243         wrap_lua_object<InputStateInfo>(L, "InputStateInfo", input_state);
1244
1245         if (lua_pcall(L, 5, 2, 0) != 0) {
1246                 fprintf(stderr, "error running function `get_chain': %s\n", lua_tostring(L, -1));
1247                 exit(1);
1248         }
1249
1250         chain.chain = (EffectChain *)luaL_testudata(L, -2, "EffectChain");
1251         if (chain.chain == nullptr) {
1252                 fprintf(stderr, "get_chain() for chain number %d did not return an EffectChain\n",
1253                         num);
1254                 exit(1);
1255         }
1256         if (!lua_isfunction(L, -1)) {
1257                 fprintf(stderr, "Argument #-1 should be a function\n");
1258                 exit(1);
1259         }
1260         lua_pushvalue(L, -1);
1261         shared_ptr<LuaRefWithDeleter> funcref(new LuaRefWithDeleter(&m, L, luaL_ref(L, LUA_REGISTRYINDEX)));
1262         lua_pop(L, 2);
1263         assert(lua_gettop(L) == 0);
1264
1265         chain.setup_chain = [this, funcref, input_state]{
1266                 unique_lock<mutex> lock(m);
1267
1268                 assert(this->input_state == nullptr);
1269                 this->input_state = &input_state;
1270
1271                 // Set up state, including connecting signals.
1272                 lua_rawgeti(L, LUA_REGISTRYINDEX, funcref->get());
1273                 if (lua_pcall(L, 0, 0, 0) != 0) {
1274                         fprintf(stderr, "error running chain setup callback: %s\n", lua_tostring(L, -1));
1275                         exit(1);
1276                 }
1277                 assert(lua_gettop(L) == 0);
1278
1279                 this->input_state = nullptr;
1280         };
1281
1282         // TODO: Can we do better, e.g. by running setup_chain() and seeing what it references?
1283         // Actually, setup_chain does maybe hold all the references we need now anyway?
1284         chain.input_frames.reserve(num_cards * FRAME_HISTORY_LENGTH);
1285         for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
1286                 for (unsigned frame_num = 0; frame_num < FRAME_HISTORY_LENGTH; ++frame_num) {
1287                         chain.input_frames.push_back(input_state.buffered_frames[card_index][frame_num].frame);
1288                 }
1289         }
1290
1291         return chain;
1292 }
1293
1294 string Theme::get_channel_name(unsigned channel)
1295 {
1296         unique_lock<mutex> lock(m);
1297         lua_getglobal(L, "channel_name");
1298         lua_pushnumber(L, channel);
1299         if (lua_pcall(L, 1, 1, 0) != 0) {
1300                 fprintf(stderr, "error running function `channel_name': %s\n", lua_tostring(L, -1));
1301                 exit(1);
1302         }
1303         const char *ret = lua_tostring(L, -1);
1304         if (ret == nullptr) {
1305                 fprintf(stderr, "function `channel_name' returned nil for channel %d\n", channel);
1306                 exit(1);
1307         }
1308
1309         string retstr = ret;
1310         lua_pop(L, 1);
1311         assert(lua_gettop(L) == 0);
1312         return retstr;
1313 }
1314
1315 int Theme::get_channel_signal(unsigned channel)
1316 {
1317         unique_lock<mutex> lock(m);
1318         lua_getglobal(L, "channel_signal");
1319         lua_pushnumber(L, channel);
1320         if (lua_pcall(L, 1, 1, 0) != 0) {
1321                 fprintf(stderr, "error running function `channel_signal': %s\n", lua_tostring(L, -1));
1322                 exit(1);
1323         }
1324
1325         int ret = luaL_checknumber(L, 1);
1326         lua_pop(L, 1);
1327         assert(lua_gettop(L) == 0);
1328         return ret;
1329 }
1330
1331 std::string Theme::get_channel_color(unsigned channel)
1332 {
1333         unique_lock<mutex> lock(m);
1334         lua_getglobal(L, "channel_color");
1335         lua_pushnumber(L, channel);
1336         if (lua_pcall(L, 1, 1, 0) != 0) {
1337                 fprintf(stderr, "error running function `channel_color': %s\n", lua_tostring(L, -1));
1338                 exit(1);
1339         }
1340
1341         const char *ret = lua_tostring(L, -1);
1342         if (ret == nullptr) {
1343                 fprintf(stderr, "function `channel_color' returned nil for channel %d\n", channel);
1344                 exit(1);
1345         }
1346
1347         string retstr = ret;
1348         lua_pop(L, 1);
1349         assert(lua_gettop(L) == 0);
1350         return retstr;
1351 }
1352
1353 bool Theme::get_supports_set_wb(unsigned channel)
1354 {
1355         unique_lock<mutex> lock(m);
1356         lua_getglobal(L, "supports_set_wb");
1357         lua_pushnumber(L, channel);
1358         if (lua_pcall(L, 1, 1, 0) != 0) {
1359                 fprintf(stderr, "error running function `supports_set_wb': %s\n", lua_tostring(L, -1));
1360                 exit(1);
1361         }
1362
1363         bool ret = checkbool(L, -1);
1364         lua_pop(L, 1);
1365         assert(lua_gettop(L) == 0);
1366         return ret;
1367 }
1368
1369 void Theme::set_wb(unsigned channel, double r, double g, double b)
1370 {
1371         unique_lock<mutex> lock(m);
1372         lua_getglobal(L, "set_wb");
1373         lua_pushnumber(L, channel);
1374         lua_pushnumber(L, r);
1375         lua_pushnumber(L, g);
1376         lua_pushnumber(L, b);
1377         if (lua_pcall(L, 4, 0, 0) != 0) {
1378                 fprintf(stderr, "error running function `set_wb': %s\n", lua_tostring(L, -1));
1379                 exit(1);
1380         }
1381
1382         assert(lua_gettop(L) == 0);
1383 }
1384
1385 vector<string> Theme::get_transition_names(float t)
1386 {
1387         unique_lock<mutex> lock(m);
1388         lua_getglobal(L, "get_transitions");
1389         lua_pushnumber(L, t);
1390         if (lua_pcall(L, 1, 1, 0) != 0) {
1391                 fprintf(stderr, "error running function `get_transitions': %s\n", lua_tostring(L, -1));
1392                 exit(1);
1393         }
1394
1395         vector<string> ret;
1396         lua_pushnil(L);
1397         while (lua_next(L, -2) != 0) {
1398                 ret.push_back(lua_tostring(L, -1));
1399                 lua_pop(L, 1);
1400         }
1401         lua_pop(L, 1);
1402         assert(lua_gettop(L) == 0);
1403         return ret;
1404 }       
1405
1406 int Theme::map_signal(int signal_num)
1407 {
1408         // Negative numbers map to raw signals.
1409         if (signal_num < 0) {
1410                 return -1 - signal_num;
1411         }
1412
1413         unique_lock<mutex> lock(map_m);
1414         if (signal_to_card_mapping.count(signal_num)) {
1415                 return signal_to_card_mapping[signal_num];
1416         }
1417
1418         int card_index;
1419         if (global_flags.output_card != -1 && num_cards > 1) {
1420                 // Try to exclude the output card from the default card_index.
1421                 card_index = signal_num % (num_cards - 1);
1422                 if (card_index >= global_flags.output_card) {
1423                          ++card_index;
1424                 }
1425                 if (signal_num >= int(num_cards - 1)) {
1426                         fprintf(stderr, "WARNING: Theme asked for input %d, but we only have %u input card(s) (card %d is busy with output).\n",
1427                                 signal_num, num_cards - 1, global_flags.output_card);
1428                         fprintf(stderr, "Mapping to card %d instead.\n", card_index);
1429                 }
1430         } else {
1431                 card_index = signal_num % num_cards;
1432                 if (signal_num >= int(num_cards)) {
1433                         fprintf(stderr, "WARNING: Theme asked for input %d, but we only have %u card(s).\n", signal_num, num_cards);
1434                         fprintf(stderr, "Mapping to card %d instead.\n", card_index);
1435                 }
1436         }
1437         signal_to_card_mapping[signal_num] = card_index;
1438         return card_index;
1439 }
1440
1441 void Theme::set_signal_mapping(int signal_num, int card_num)
1442 {
1443         unique_lock<mutex> lock(map_m);
1444         assert(card_num < int(num_cards));
1445         signal_to_card_mapping[signal_num] = card_num;
1446 }
1447
1448 void Theme::transition_clicked(int transition_num, float t)
1449 {
1450         unique_lock<mutex> lock(m);
1451         lua_getglobal(L, "transition_clicked");
1452         lua_pushnumber(L, transition_num);
1453         lua_pushnumber(L, t);
1454
1455         if (lua_pcall(L, 2, 0, 0) != 0) {
1456                 fprintf(stderr, "error running function `transition_clicked': %s\n", lua_tostring(L, -1));
1457                 exit(1);
1458         }
1459         assert(lua_gettop(L) == 0);
1460 }
1461
1462 void Theme::channel_clicked(int preview_num)
1463 {
1464         unique_lock<mutex> lock(m);
1465         lua_getglobal(L, "channel_clicked");
1466         lua_pushnumber(L, preview_num);
1467
1468         if (lua_pcall(L, 1, 0, 0) != 0) {
1469                 fprintf(stderr, "error running function `channel_clicked': %s\n", lua_tostring(L, -1));
1470                 exit(1);
1471         }
1472         assert(lua_gettop(L) == 0);
1473 }
1474
1475 int Theme::set_theme_menu(lua_State *L)
1476 {
1477         for (const Theme::MenuEntry &entry : theme_menu) {
1478                 luaL_unref(L, LUA_REGISTRYINDEX, entry.lua_ref);
1479         }
1480         theme_menu.clear();
1481
1482         int num_elements = lua_gettop(L);
1483         for (int i = 1; i <= num_elements; ++i) {
1484                 lua_rawgeti(L, i, 1);
1485                 const string text = checkstdstring(L, -1);
1486                 lua_pop(L, 1);
1487
1488                 lua_rawgeti(L, i, 2);
1489                 luaL_checktype(L, -1, LUA_TFUNCTION);
1490                 int ref = luaL_ref(L, LUA_REGISTRYINDEX);
1491
1492                 theme_menu.push_back(MenuEntry{ text, ref });
1493         }
1494         lua_pop(L, num_elements);
1495         assert(lua_gettop(L) == 0);
1496
1497         if (theme_menu_callback != nullptr) {
1498                 theme_menu_callback();
1499         }
1500
1501         return 0;
1502 }
1503
1504 void Theme::theme_menu_entry_clicked(int lua_ref)
1505 {
1506         unique_lock<mutex> lock(m);
1507         lua_rawgeti(L, LUA_REGISTRYINDEX, lua_ref);
1508         if (lua_pcall(L, 0, 0, 0) != 0) {
1509                 fprintf(stderr, "error running menu callback: %s\n", lua_tostring(L, -1));
1510                 exit(1);
1511         }
1512 }