]> git.sesse.net Git - nageru/blob - theme.cpp
Change from RGBA to BGRA; slightly more Intel GPU-friendly, and Caspar uses that...
[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/effect.h>
9 #include <movit/effect_chain.h>
10 #include <movit/image_format.h>
11 #include <movit/mix_effect.h>
12 #include <movit/multiply_effect.h>
13 #include <movit/overlay_effect.h>
14 #include <movit/padding_effect.h>
15 #include <movit/resample_effect.h>
16 #include <movit/resize_effect.h>
17 #include <movit/util.h>
18 #include <movit/white_balance_effect.h>
19 #include <movit/ycbcr.h>
20 #include <movit/ycbcr_input.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <cstddef>
24 #include <memory>
25 #include <new>
26 #include <utility>
27
28 #include "defs.h"
29 #include "deinterlace_effect.h"
30 #include "ffmpeg_capture.h"
31 #include "flags.h"
32 #include "image_input.h"
33 #include "input.h"
34 #include "input_state.h"
35 #include "pbo_frame_allocator.h"
36
37 class Mixer;
38
39 namespace movit {
40 class ResourcePool;
41 }  // namespace movit
42
43 using namespace std;
44 using namespace movit;
45
46 extern Mixer *global_mixer;
47
48 namespace {
49
50 // Contains basically the same data as InputState, but does not hold on to
51 // a reference to the frames. This is important so that we can release them
52 // without having to wait for Lua's GC.
53 struct InputStateInfo {
54         InputStateInfo(const InputState& input_state);
55
56         unsigned last_width[MAX_VIDEO_CARDS], last_height[MAX_VIDEO_CARDS];
57         bool last_interlaced[MAX_VIDEO_CARDS], last_has_signal[MAX_VIDEO_CARDS], last_is_connected[MAX_VIDEO_CARDS];
58         unsigned last_frame_rate_nom[MAX_VIDEO_CARDS], last_frame_rate_den[MAX_VIDEO_CARDS];
59 };
60
61 InputStateInfo::InputStateInfo(const InputState &input_state)
62 {
63         for (unsigned signal_num = 0; signal_num < MAX_VIDEO_CARDS; ++signal_num) {
64                 BufferedFrame frame = input_state.buffered_frames[signal_num][0];
65                 if (frame.frame == nullptr) {
66                         last_width[signal_num] = last_height[signal_num] = 0;
67                         last_interlaced[signal_num] = false;
68                         last_has_signal[signal_num] = false;
69                         last_is_connected[signal_num] = false;
70                         continue;
71                 }
72                 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
73                 last_width[signal_num] = userdata->last_width[frame.field_number];
74                 last_height[signal_num] = userdata->last_height[frame.field_number];
75                 last_interlaced[signal_num] = userdata->last_interlaced;
76                 last_has_signal[signal_num] = userdata->last_has_signal;
77                 last_is_connected[signal_num] = userdata->last_is_connected;
78                 last_frame_rate_nom[signal_num] = userdata->last_frame_rate_nom;
79                 last_frame_rate_den[signal_num] = userdata->last_frame_rate_den;
80         }
81 }
82
83 class LuaRefWithDeleter {
84 public:
85         LuaRefWithDeleter(mutex *m, lua_State *L, int ref) : m(m), L(L), ref(ref) {}
86         ~LuaRefWithDeleter() {
87                 unique_lock<mutex> lock(*m);
88                 luaL_unref(L, LUA_REGISTRYINDEX, ref);
89         }
90         int get() const { return ref; }
91
92 private:
93         LuaRefWithDeleter(const LuaRefWithDeleter &) = delete;
94
95         mutex *m;
96         lua_State *L;
97         int ref;
98 };
99
100 template<class T, class... Args>
101 int wrap_lua_object(lua_State* L, const char *class_name, Args&&... args)
102 {
103         // Construct the C++ object and put it on the stack.
104         void *mem = lua_newuserdata(L, sizeof(T));
105         new(mem) T(forward<Args>(args)...);
106
107         // Look up the metatable named <class_name>, and set it on the new object.
108         luaL_getmetatable(L, class_name);
109         lua_setmetatable(L, -2);
110
111         return 1;
112 }
113
114 // Like wrap_lua_object, but the object is not owned by Lua; ie. it's not freed
115 // by Lua GC. This is typically the case for Effects, which are owned by EffectChain
116 // and expected to be destructed by it. The object will be of type T** instead of T*
117 // when exposed to Lua.
118 //
119 // Note that we currently leak if you allocate an Effect in this way and never call
120 // add_effect. We should see if there's a way to e.g. set __gc on it at construction time
121 // and then release that once add_effect() takes ownership.
122 template<class T, class... Args>
123 int wrap_lua_object_nonowned(lua_State* L, const char *class_name, Args&&... args)
124 {
125         // Construct the pointer ot the C++ object and put it on the stack.
126         T **obj = (T **)lua_newuserdata(L, sizeof(T *));
127         *obj = new T(forward<Args>(args)...);
128
129         // Look up the metatable named <class_name>, and set it on the new object.
130         luaL_getmetatable(L, class_name);
131         lua_setmetatable(L, -2);
132
133         return 1;
134 }
135
136 Theme *get_theme_updata(lua_State* L)
137 {       
138         luaL_checktype(L, lua_upvalueindex(1), LUA_TLIGHTUSERDATA);
139         return (Theme *)lua_touserdata(L, lua_upvalueindex(1));
140 }
141
142 Effect *get_effect(lua_State *L, int idx)
143 {
144         if (luaL_testudata(L, idx, "WhiteBalanceEffect") ||
145             luaL_testudata(L, idx, "ResampleEffect") ||
146             luaL_testudata(L, idx, "PaddingEffect") ||
147             luaL_testudata(L, idx, "IntegralPaddingEffect") ||
148             luaL_testudata(L, idx, "OverlayEffect") ||
149             luaL_testudata(L, idx, "ResizeEffect") ||
150             luaL_testudata(L, idx, "MultiplyEffect") ||
151             luaL_testudata(L, idx, "MixEffect") ||
152             luaL_testudata(L, idx, "ImageInput")) {
153                 return *(Effect **)lua_touserdata(L, idx);
154         }
155         luaL_error(L, "Error: Index #%d was not an Effect type\n", idx);
156         return nullptr;
157 }
158
159 InputStateInfo *get_input_state_info(lua_State *L, int idx)
160 {
161         if (luaL_testudata(L, idx, "InputStateInfo")) {
162                 return (InputStateInfo *)lua_touserdata(L, idx);
163         }
164         luaL_error(L, "Error: Index #%d was not InputStateInfo\n", idx);
165         return nullptr;
166 }
167
168 bool checkbool(lua_State* L, int idx)
169 {
170         luaL_checktype(L, idx, LUA_TBOOLEAN);
171         return lua_toboolean(L, idx);
172 }
173
174 string checkstdstring(lua_State *L, int index)
175 {
176         size_t len;
177         const char* cstr = lua_tolstring(L, index, &len);
178         return string(cstr, len);
179 }
180
181 int EffectChain_new(lua_State* L)
182 {
183         assert(lua_gettop(L) == 2);
184         Theme *theme = get_theme_updata(L);
185         int aspect_w = luaL_checknumber(L, 1);
186         int aspect_h = luaL_checknumber(L, 2);
187
188         return wrap_lua_object<EffectChain>(L, "EffectChain", aspect_w, aspect_h, theme->get_resource_pool());
189 }
190
191 int EffectChain_gc(lua_State* L)
192 {
193         assert(lua_gettop(L) == 1);
194         EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
195         chain->~EffectChain();
196         return 0;
197 }
198
199 int EffectChain_add_live_input(lua_State* L)
200 {
201         assert(lua_gettop(L) == 3);
202         Theme *theme = get_theme_updata(L);
203         EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
204         bool override_bounce = checkbool(L, 2);
205         bool deinterlace = checkbool(L, 3);
206         bmusb::PixelFormat pixel_format = global_flags.ten_bit_input ? bmusb::PixelFormat_10BitYCbCr : bmusb::PixelFormat_8BitYCbCr;
207
208         // Needs to be nonowned to match add_video_input (see below).
209         return wrap_lua_object_nonowned<LiveInputWrapper>(L, "LiveInputWrapper", theme, chain, pixel_format, override_bounce, deinterlace);
210 }
211
212 int EffectChain_add_video_input(lua_State* L)
213 {
214         assert(lua_gettop(L) == 3);
215         Theme *theme = get_theme_updata(L);
216         EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
217         FFmpegCapture **capture = (FFmpegCapture **)luaL_checkudata(L, 2, "VideoInput");
218         bool deinterlace = checkbool(L, 3);
219
220         // These need to be nonowned, so that the LiveInputWrapper still exists
221         // and can feed frames to the right EffectChain even if the Lua code
222         // doesn't care about the object anymore. (If we change this, we'd need
223         // to also unregister the signal connection on __gc.)
224         int ret = wrap_lua_object_nonowned<LiveInputWrapper>(
225                 L, "LiveInputWrapper", theme, chain, bmusb::PixelFormat_8BitBGRA,
226                 /*override_bounce=*/false, deinterlace);
227         if (ret == 1) {
228                 Theme *theme = get_theme_updata(L);
229                 LiveInputWrapper **live_input = (LiveInputWrapper **)lua_touserdata(L, -1);
230                 theme->register_signal_connection(*live_input, *capture);
231         }
232         return ret;
233 }
234
235 int EffectChain_add_effect(lua_State* L)
236 {
237         assert(lua_gettop(L) >= 2);
238         EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
239
240         // TODO: Better error reporting.
241         Effect *effect = get_effect(L, 2);
242         if (lua_gettop(L) == 2) {
243                 if (effect->num_inputs() == 0) {
244                         chain->add_input((Input *)effect);
245                 } else {
246                         chain->add_effect(effect);
247                 }
248         } else {
249                 vector<Effect *> inputs;
250                 for (int idx = 3; idx <= lua_gettop(L); ++idx) {
251                         if (luaL_testudata(L, idx, "LiveInputWrapper")) {
252                                 LiveInputWrapper **input = (LiveInputWrapper **)lua_touserdata(L, idx);
253                                 inputs.push_back((*input)->get_effect());
254                         } else {
255                                 inputs.push_back(get_effect(L, idx));
256                         }
257                 }
258                 chain->add_effect(effect, inputs);
259         }
260
261         lua_settop(L, 2);  // Return the effect itself.
262
263         // Make sure Lua doesn't garbage-collect it away.
264         lua_pushvalue(L, -1);
265         luaL_ref(L, LUA_REGISTRYINDEX);  // TODO: leak?
266
267         return 1;
268 }
269
270 int EffectChain_finalize(lua_State* L)
271 {
272         assert(lua_gettop(L) == 2);
273         EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
274         bool is_main_chain = checkbool(L, 2);
275
276         // Add outputs as needed.
277         // NOTE: If you change any details about the output format, you will need to
278         // also update what's given to the muxer (HTTPD::Mux constructor) and
279         // what's put in the H.264 stream (sps_rbsp()).
280         ImageFormat inout_format;
281         inout_format.color_space = COLORSPACE_REC_709;
282
283         // Output gamma is tricky. We should output Rec. 709 for TV, except that
284         // we expect to run with web players and others that don't really care and
285         // just output with no conversion. So that means we'll need to output sRGB,
286         // even though H.264 has no setting for that (we use “unspecified”).
287         inout_format.gamma_curve = GAMMA_sRGB;
288
289         if (is_main_chain) {
290                 YCbCrFormat output_ycbcr_format;
291                 // We actually output 4:2:0 and/or 4:2:2 in the end, but chroma subsampling
292                 // happens in a pass not run by Movit (see ChromaSubsampler::subsample_chroma()).
293                 output_ycbcr_format.chroma_subsampling_x = 1;
294                 output_ycbcr_format.chroma_subsampling_y = 1;
295
296                 // This will be overridden if HDMI/SDI output is in force.
297                 if (global_flags.ycbcr_rec709_coefficients) {
298                         output_ycbcr_format.luma_coefficients = YCBCR_REC_709;
299                 } else {
300                         output_ycbcr_format.luma_coefficients = YCBCR_REC_601;
301                 }
302
303                 output_ycbcr_format.full_range = false;
304                 output_ycbcr_format.num_levels = 1 << global_flags.x264_bit_depth;
305
306                 GLenum type = global_flags.x264_bit_depth > 8 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_BYTE;
307
308                 chain->add_ycbcr_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED, output_ycbcr_format, YCBCR_OUTPUT_SPLIT_Y_AND_CBCR, type);
309
310                 // If we're using zerocopy video encoding (so the destination
311                 // Y texture is owned by VA-API and will be unavailable for
312                 // display), add a copy, where we'll only be using the Y component.
313                 if (global_flags.use_zerocopy) {
314                         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.
315                 }
316                 chain->set_dither_bits(global_flags.x264_bit_depth > 8 ? 16 : 8);
317                 chain->set_output_origin(OUTPUT_ORIGIN_TOP_LEFT);
318         } else {
319                 chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
320         }
321
322         chain->finalize();
323         return 0;
324 }
325
326 int LiveInputWrapper_connect_signal(lua_State* L)
327 {
328         assert(lua_gettop(L) == 2);
329         LiveInputWrapper **input = (LiveInputWrapper **)luaL_checkudata(L, 1, "LiveInputWrapper");
330         int signal_num = luaL_checknumber(L, 2);
331         (*input)->connect_signal(signal_num);
332         return 0;
333 }
334
335 int ImageInput_new(lua_State* L)
336 {
337         assert(lua_gettop(L) == 1);
338         string filename = checkstdstring(L, 1);
339         return wrap_lua_object_nonowned<ImageInput>(L, "ImageInput", filename);
340 }
341
342 int VideoInput_new(lua_State* L)
343 {
344         assert(lua_gettop(L) == 1);
345         string filename = checkstdstring(L, 1);
346         int ret = wrap_lua_object_nonowned<FFmpegCapture>(L, "VideoInput", filename, global_flags.width, global_flags.height);
347         if (ret == 1) {
348                 Theme *theme = get_theme_updata(L);
349                 FFmpegCapture **capture = (FFmpegCapture **)lua_touserdata(L, -1);
350                 theme->register_video_input(*capture);
351         }
352         return ret;
353 }
354
355 int VideoInput_rewind(lua_State* L)
356 {
357         assert(lua_gettop(L) == 1);
358         FFmpegCapture **video_input = (FFmpegCapture **)luaL_checkudata(L, 1, "VideoInput");
359         (*video_input)->rewind();
360         return 0;
361 }
362
363 int VideoInput_change_rate(lua_State* L)
364 {
365         assert(lua_gettop(L) == 2);
366         FFmpegCapture **video_input = (FFmpegCapture **)luaL_checkudata(L, 1, "VideoInput");
367         double new_rate = luaL_checknumber(L, 2);
368         (*video_input)->change_rate(new_rate);
369         return 0;
370 }
371
372 int WhiteBalanceEffect_new(lua_State* L)
373 {
374         assert(lua_gettop(L) == 0);
375         return wrap_lua_object_nonowned<WhiteBalanceEffect>(L, "WhiteBalanceEffect");
376 }
377
378 int ResampleEffect_new(lua_State* L)
379 {
380         assert(lua_gettop(L) == 0);
381         return wrap_lua_object_nonowned<ResampleEffect>(L, "ResampleEffect");
382 }
383
384 int PaddingEffect_new(lua_State* L)
385 {
386         assert(lua_gettop(L) == 0);
387         return wrap_lua_object_nonowned<PaddingEffect>(L, "PaddingEffect");
388 }
389
390 int IntegralPaddingEffect_new(lua_State* L)
391 {
392         assert(lua_gettop(L) == 0);
393         return wrap_lua_object_nonowned<IntegralPaddingEffect>(L, "IntegralPaddingEffect");
394 }
395
396 int OverlayEffect_new(lua_State* L)
397 {
398         assert(lua_gettop(L) == 0);
399         return wrap_lua_object_nonowned<OverlayEffect>(L, "OverlayEffect");
400 }
401
402 int ResizeEffect_new(lua_State* L)
403 {
404         assert(lua_gettop(L) == 0);
405         return wrap_lua_object_nonowned<ResizeEffect>(L, "ResizeEffect");
406 }
407
408 int MultiplyEffect_new(lua_State* L)
409 {
410         assert(lua_gettop(L) == 0);
411         return wrap_lua_object_nonowned<MultiplyEffect>(L, "MultiplyEffect");
412 }
413
414 int MixEffect_new(lua_State* L)
415 {
416         assert(lua_gettop(L) == 0);
417         return wrap_lua_object_nonowned<MixEffect>(L, "MixEffect");
418 }
419
420 int InputStateInfo_get_width(lua_State* L)
421 {
422         assert(lua_gettop(L) == 2);
423         InputStateInfo *input_state_info = get_input_state_info(L, 1);
424         Theme *theme = get_theme_updata(L);
425         int signal_num = theme->map_signal(luaL_checknumber(L, 2));
426         lua_pushnumber(L, input_state_info->last_width[signal_num]);
427         return 1;
428 }
429
430 int InputStateInfo_get_height(lua_State* L)
431 {
432         assert(lua_gettop(L) == 2);
433         InputStateInfo *input_state_info = get_input_state_info(L, 1);
434         Theme *theme = get_theme_updata(L);
435         int signal_num = theme->map_signal(luaL_checknumber(L, 2));
436         lua_pushnumber(L, input_state_info->last_height[signal_num]);
437         return 1;
438 }
439
440 int InputStateInfo_get_interlaced(lua_State* L)
441 {
442         assert(lua_gettop(L) == 2);
443         InputStateInfo *input_state_info = get_input_state_info(L, 1);
444         Theme *theme = get_theme_updata(L);
445         int signal_num = theme->map_signal(luaL_checknumber(L, 2));
446         lua_pushboolean(L, input_state_info->last_interlaced[signal_num]);
447         return 1;
448 }
449
450 int InputStateInfo_get_has_signal(lua_State* L)
451 {
452         assert(lua_gettop(L) == 2);
453         InputStateInfo *input_state_info = get_input_state_info(L, 1);
454         Theme *theme = get_theme_updata(L);
455         int signal_num = theme->map_signal(luaL_checknumber(L, 2));
456         lua_pushboolean(L, input_state_info->last_has_signal[signal_num]);
457         return 1;
458 }
459
460 int InputStateInfo_get_is_connected(lua_State* L)
461 {
462         assert(lua_gettop(L) == 2);
463         InputStateInfo *input_state_info = get_input_state_info(L, 1);
464         Theme *theme = get_theme_updata(L);
465         int signal_num = theme->map_signal(luaL_checknumber(L, 2));
466         lua_pushboolean(L, input_state_info->last_is_connected[signal_num]);
467         return 1;
468 }
469
470 int InputStateInfo_get_frame_rate_nom(lua_State* L)
471 {
472         assert(lua_gettop(L) == 2);
473         InputStateInfo *input_state_info = get_input_state_info(L, 1);
474         Theme *theme = get_theme_updata(L);
475         int signal_num = theme->map_signal(luaL_checknumber(L, 2));
476         lua_pushnumber(L, input_state_info->last_frame_rate_nom[signal_num]);
477         return 1;
478 }
479
480 int InputStateInfo_get_frame_rate_den(lua_State* L)
481 {
482         assert(lua_gettop(L) == 2);
483         InputStateInfo *input_state_info = get_input_state_info(L, 1);
484         Theme *theme = get_theme_updata(L);
485         int signal_num = theme->map_signal(luaL_checknumber(L, 2));
486         lua_pushnumber(L, input_state_info->last_frame_rate_den[signal_num]);
487         return 1;
488 }
489
490 int Effect_set_float(lua_State *L)
491 {
492         assert(lua_gettop(L) == 3);
493         Effect *effect = (Effect *)get_effect(L, 1);
494         string key = checkstdstring(L, 2);
495         float value = luaL_checknumber(L, 3);
496         if (!effect->set_float(key, value)) {
497                 luaL_error(L, "Effect refused set_float(\"%s\", %d) (invalid key?)", key.c_str(), int(value));
498         }
499         return 0;
500 }
501
502 int Effect_set_int(lua_State *L)
503 {
504         assert(lua_gettop(L) == 3);
505         Effect *effect = (Effect *)get_effect(L, 1);
506         string key = checkstdstring(L, 2);
507         float value = luaL_checknumber(L, 3);
508         if (!effect->set_int(key, value)) {
509                 luaL_error(L, "Effect refused set_int(\"%s\", %d) (invalid key?)", key.c_str(), int(value));
510         }
511         return 0;
512 }
513
514 int Effect_set_vec3(lua_State *L)
515 {
516         assert(lua_gettop(L) == 5);
517         Effect *effect = (Effect *)get_effect(L, 1);
518         string key = checkstdstring(L, 2);
519         float v[3];
520         v[0] = luaL_checknumber(L, 3);
521         v[1] = luaL_checknumber(L, 4);
522         v[2] = luaL_checknumber(L, 5);
523         if (!effect->set_vec3(key, v)) {
524                 luaL_error(L, "Effect refused set_vec3(\"%s\", %f, %f, %f) (invalid key?)", key.c_str(),
525                         v[0], v[1], v[2]);
526         }
527         return 0;
528 }
529
530 int Effect_set_vec4(lua_State *L)
531 {
532         assert(lua_gettop(L) == 6);
533         Effect *effect = (Effect *)get_effect(L, 1);
534         string key = checkstdstring(L, 2);
535         float v[4];
536         v[0] = luaL_checknumber(L, 3);
537         v[1] = luaL_checknumber(L, 4);
538         v[2] = luaL_checknumber(L, 5);
539         v[3] = luaL_checknumber(L, 6);
540         if (!effect->set_vec4(key, v)) {
541                 luaL_error(L, "Effect refused set_vec4(\"%s\", %f, %f, %f, %f) (invalid key?)", key.c_str(),
542                         v[0], v[1], v[2], v[3]);
543         }
544         return 0;
545 }
546
547 const luaL_Reg EffectChain_funcs[] = {
548         { "new", EffectChain_new },
549         { "__gc", EffectChain_gc },
550         { "add_live_input", EffectChain_add_live_input },
551         { "add_video_input", EffectChain_add_video_input },
552         { "add_effect", EffectChain_add_effect },
553         { "finalize", EffectChain_finalize },
554         { NULL, NULL }
555 };
556
557 const luaL_Reg LiveInputWrapper_funcs[] = {
558         { "connect_signal", LiveInputWrapper_connect_signal },
559         { NULL, NULL }
560 };
561
562 const luaL_Reg ImageInput_funcs[] = {
563         { "new", ImageInput_new },
564         { "set_float", Effect_set_float },
565         { "set_int", Effect_set_int },
566         { "set_vec3", Effect_set_vec3 },
567         { "set_vec4", Effect_set_vec4 },
568         { NULL, NULL }
569 };
570
571 const luaL_Reg VideoInput_funcs[] = {
572         { "new", VideoInput_new },
573         { "rewind", VideoInput_rewind },
574         { "change_rate", VideoInput_change_rate },
575         { NULL, NULL }
576 };
577
578 const luaL_Reg WhiteBalanceEffect_funcs[] = {
579         { "new", WhiteBalanceEffect_new },
580         { "set_float", Effect_set_float },
581         { "set_int", Effect_set_int },
582         { "set_vec3", Effect_set_vec3 },
583         { "set_vec4", Effect_set_vec4 },
584         { NULL, NULL }
585 };
586
587 const luaL_Reg ResampleEffect_funcs[] = {
588         { "new", ResampleEffect_new },
589         { "set_float", Effect_set_float },
590         { "set_int", Effect_set_int },
591         { "set_vec3", Effect_set_vec3 },
592         { "set_vec4", Effect_set_vec4 },
593         { NULL, NULL }
594 };
595
596 const luaL_Reg PaddingEffect_funcs[] = {
597         { "new", PaddingEffect_new },
598         { "set_float", Effect_set_float },
599         { "set_int", Effect_set_int },
600         { "set_vec3", Effect_set_vec3 },
601         { "set_vec4", Effect_set_vec4 },
602         { NULL, NULL }
603 };
604
605 const luaL_Reg IntegralPaddingEffect_funcs[] = {
606         { "new", IntegralPaddingEffect_new },
607         { "set_float", Effect_set_float },
608         { "set_int", Effect_set_int },
609         { "set_vec3", Effect_set_vec3 },
610         { "set_vec4", Effect_set_vec4 },
611         { NULL, NULL }
612 };
613
614 const luaL_Reg OverlayEffect_funcs[] = {
615         { "new", OverlayEffect_new },
616         { "set_float", Effect_set_float },
617         { "set_int", Effect_set_int },
618         { "set_vec3", Effect_set_vec3 },
619         { "set_vec4", Effect_set_vec4 },
620         { NULL, NULL }
621 };
622
623 const luaL_Reg ResizeEffect_funcs[] = {
624         { "new", ResizeEffect_new },
625         { "set_float", Effect_set_float },
626         { "set_int", Effect_set_int },
627         { "set_vec3", Effect_set_vec3 },
628         { "set_vec4", Effect_set_vec4 },
629         { NULL, NULL }
630 };
631
632 const luaL_Reg MultiplyEffect_funcs[] = {
633         { "new", MultiplyEffect_new },
634         { "set_float", Effect_set_float },
635         { "set_int", Effect_set_int },
636         { "set_vec3", Effect_set_vec3 },
637         { "set_vec4", Effect_set_vec4 },
638         { NULL, NULL }
639 };
640
641 const luaL_Reg MixEffect_funcs[] = {
642         { "new", MixEffect_new },
643         { "set_float", Effect_set_float },
644         { "set_int", Effect_set_int },
645         { "set_vec3", Effect_set_vec3 },
646         { "set_vec4", Effect_set_vec4 },
647         { NULL, NULL }
648 };
649
650 const luaL_Reg InputStateInfo_funcs[] = {
651         { "get_width", InputStateInfo_get_width },
652         { "get_height", InputStateInfo_get_height },
653         { "get_interlaced", InputStateInfo_get_interlaced },
654         { "get_has_signal", InputStateInfo_get_has_signal },
655         { "get_is_connected", InputStateInfo_get_is_connected },
656         { "get_frame_rate_nom", InputStateInfo_get_frame_rate_nom },
657         { "get_frame_rate_den", InputStateInfo_get_frame_rate_den },
658         { NULL, NULL }
659 };
660
661 }  // namespace
662
663 LiveInputWrapper::LiveInputWrapper(Theme *theme, EffectChain *chain, bmusb::PixelFormat pixel_format, bool override_bounce, bool deinterlace)
664         : theme(theme),
665           pixel_format(pixel_format),
666           deinterlace(deinterlace)
667 {
668         ImageFormat inout_format;
669         inout_format.color_space = COLORSPACE_sRGB;
670
671         // Gamma curve depends on the input signal, and we don't really get any
672         // indications. A camera would be expected to do Rec. 709, but
673         // I haven't checked if any do in practice. However, computers _do_ output
674         // in sRGB gamma (ie., they don't convert from sRGB to Rec. 709), and
675         // I wouldn't really be surprised if most non-professional cameras do, too.
676         // So we pick sRGB as the least evil here.
677         inout_format.gamma_curve = GAMMA_sRGB;
678
679         unsigned num_inputs;
680         if (deinterlace) {
681                 deinterlace_effect = new movit::DeinterlaceEffect();
682
683                 // As per the comments in deinterlace_effect.h, we turn this off.
684                 // The most likely interlaced input for us is either a camera
685                 // (where it's fine to turn it off) or a laptop (where it _should_
686                 // be turned off).
687                 CHECK(deinterlace_effect->set_int("enable_spatial_interlacing_check", 0));
688
689                 num_inputs = deinterlace_effect->num_inputs();
690                 assert(num_inputs == FRAME_HISTORY_LENGTH);
691         } else {
692                 num_inputs = 1;
693         }
694
695         if (pixel_format == bmusb::PixelFormat_8BitBGRA) {
696                 for (unsigned i = 0; i < num_inputs; ++i) {
697                         // We upload our textures ourselves, and Movit swaps
698                         // R and B in the shader if we specify BGRA, so lie and say RGBA.
699                         if (global_flags.can_disable_srgb_decoder) {
700                                 rgba_inputs.push_back(new sRGBSwitchingFlatInput(inout_format, FORMAT_RGBA_POSTMULTIPLIED_ALPHA, GL_UNSIGNED_BYTE, global_flags.width, global_flags.height));
701                         } else {
702                                 rgba_inputs.push_back(new NonsRGBCapableFlatInput(inout_format, FORMAT_RGBA_POSTMULTIPLIED_ALPHA, GL_UNSIGNED_BYTE, global_flags.width, global_flags.height));
703                         }
704                         chain->add_input(rgba_inputs.back());
705                 }
706
707                 if (deinterlace) {
708                         vector<Effect *> reverse_inputs(rgba_inputs.rbegin(), rgba_inputs.rend());
709                         chain->add_effect(deinterlace_effect, reverse_inputs);
710                 }
711         } else {
712                 assert(pixel_format == bmusb::PixelFormat_8BitYCbCr || pixel_format == bmusb::PixelFormat_10BitYCbCr);
713                 // The Blackmagic driver docs claim that the device outputs Y'CbCr
714                 // according to Rec. 601, but practical testing indicates it definitely
715                 // is Rec. 709 (at least up to errors attributable to rounding errors).
716                 // Perhaps 601 was only to indicate the subsampling positions, not the
717                 // colorspace itself? Tested with a Lenovo X1 gen 3 as input.
718                 YCbCrFormat input_ycbcr_format;
719                 input_ycbcr_format.chroma_subsampling_x = (pixel_format == bmusb::PixelFormat_10BitYCbCr) ? 1 : 2;
720                 input_ycbcr_format.chroma_subsampling_y = 1;
721                 input_ycbcr_format.num_levels = (pixel_format == bmusb::PixelFormat_10BitYCbCr) ? 1024 : 256;
722                 input_ycbcr_format.cb_x_position = 0.0;
723                 input_ycbcr_format.cr_x_position = 0.0;
724                 input_ycbcr_format.cb_y_position = 0.5;
725                 input_ycbcr_format.cr_y_position = 0.5;
726                 input_ycbcr_format.luma_coefficients = YCBCR_REC_709;
727                 input_ycbcr_format.full_range = false;
728
729                 for (unsigned i = 0; i < num_inputs; ++i) {
730                         // When using 10-bit input, we're converting to interleaved through v210Converter.
731                         YCbCrInputSplitting splitting = (pixel_format == bmusb::PixelFormat_10BitYCbCr) ? YCBCR_INPUT_INTERLEAVED : YCBCR_INPUT_SPLIT_Y_AND_CBCR;
732                         if (override_bounce) {
733                                 ycbcr_inputs.push_back(new NonBouncingYCbCrInput(inout_format, input_ycbcr_format, global_flags.width, global_flags.height, splitting));
734                         } else {
735                                 ycbcr_inputs.push_back(new YCbCrInput(inout_format, input_ycbcr_format, global_flags.width, global_flags.height, splitting));
736                         }
737                         chain->add_input(ycbcr_inputs.back());
738                 }
739
740                 if (deinterlace) {
741                         vector<Effect *> reverse_inputs(ycbcr_inputs.rbegin(), ycbcr_inputs.rend());
742                         chain->add_effect(deinterlace_effect, reverse_inputs);
743                 }
744         }
745 }
746
747 void LiveInputWrapper::connect_signal(int signal_num)
748 {
749         if (global_mixer == nullptr) {
750                 // No data yet.
751                 return;
752         }
753
754         signal_num = theme->map_signal(signal_num);
755         connect_signal_raw(signal_num);
756 }
757
758 void LiveInputWrapper::connect_signal_raw(int signal_num)
759 {
760         BufferedFrame first_frame = theme->input_state->buffered_frames[signal_num][0];
761         if (first_frame.frame == nullptr) {
762                 // No data yet.
763                 return;
764         }
765         unsigned width, height;
766         {
767                 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)first_frame.frame->userdata;
768                 width = userdata->last_width[first_frame.field_number];
769                 height = userdata->last_height[first_frame.field_number];
770         }
771
772         BufferedFrame last_good_frame = first_frame;
773         for (unsigned i = 0; i < max(ycbcr_inputs.size(), rgba_inputs.size()); ++i) {
774                 BufferedFrame frame = theme->input_state->buffered_frames[signal_num][i];
775                 if (frame.frame == nullptr) {
776                         // Not enough data; reuse last frame (well, field).
777                         // This is suboptimal, but we have nothing better.
778                         frame = last_good_frame;
779                 }
780                 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
781
782                 unsigned this_width = userdata->last_width[frame.field_number];
783                 unsigned this_height = userdata->last_height[frame.field_number];
784                 if (this_width != width || this_height != height) {
785                         // Resolution changed; reuse last frame/field.
786                         frame = last_good_frame;
787                         userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
788                 }
789
790                 assert(userdata->pixel_format == pixel_format);
791                 switch (pixel_format) {
792                 case bmusb::PixelFormat_8BitYCbCr:
793                         ycbcr_inputs[i]->set_texture_num(0, userdata->tex_y[frame.field_number]);
794                         ycbcr_inputs[i]->set_texture_num(1, userdata->tex_cbcr[frame.field_number]);
795                         ycbcr_inputs[i]->set_width(this_width);
796                         ycbcr_inputs[i]->set_height(this_height);
797                         break;
798                 case bmusb::PixelFormat_10BitYCbCr:
799                         ycbcr_inputs[i]->set_texture_num(0, userdata->tex_444[frame.field_number]);
800                         ycbcr_inputs[i]->set_width(this_width);
801                         ycbcr_inputs[i]->set_height(this_height);
802                         break;
803                 case bmusb::PixelFormat_8BitBGRA:
804                         rgba_inputs[i]->set_texture_num(userdata->tex_rgba[frame.field_number]);
805                         rgba_inputs[i]->set_width(this_width);
806                         rgba_inputs[i]->set_height(this_height);
807                         break;
808                 default:
809                         assert(false);
810                 }
811
812                 last_good_frame = frame;
813         }
814
815         if (deinterlace) {
816                 BufferedFrame frame = theme->input_state->buffered_frames[signal_num][0];
817                 CHECK(deinterlace_effect->set_int("current_field_position", frame.field_number));
818         }
819 }
820
821 namespace {
822
823 int call_num_channels(lua_State *L)
824 {
825         lua_getglobal(L, "num_channels");
826
827         if (lua_pcall(L, 0, 1, 0) != 0) {
828                 fprintf(stderr, "error running function `num_channels': %s\n", lua_tostring(L, -1));
829                 exit(1);
830         }
831
832         int num_channels = luaL_checknumber(L, 1);
833         lua_pop(L, 1);
834         assert(lua_gettop(L) == 0);
835         return num_channels;
836 }
837
838 }  // namespace
839
840 Theme::Theme(const string &filename, const vector<string> &search_dirs, ResourcePool *resource_pool, unsigned num_cards)
841         : resource_pool(resource_pool), num_cards(num_cards), signal_to_card_mapping(global_flags.default_stream_mapping)
842 {
843         L = luaL_newstate();
844         luaL_openlibs(L);
845
846         register_class("EffectChain", EffectChain_funcs); 
847         register_class("LiveInputWrapper", LiveInputWrapper_funcs); 
848         register_class("ImageInput", ImageInput_funcs);
849         register_class("VideoInput", VideoInput_funcs);
850         register_class("WhiteBalanceEffect", WhiteBalanceEffect_funcs);
851         register_class("ResampleEffect", ResampleEffect_funcs);
852         register_class("PaddingEffect", PaddingEffect_funcs);
853         register_class("IntegralPaddingEffect", IntegralPaddingEffect_funcs);
854         register_class("OverlayEffect", OverlayEffect_funcs);
855         register_class("ResizeEffect", ResizeEffect_funcs);
856         register_class("MultiplyEffect", MultiplyEffect_funcs);
857         register_class("MixEffect", MixEffect_funcs);
858         register_class("InputStateInfo", InputStateInfo_funcs);
859
860         // Run script. Search through all directories until we find a file that will load
861         // (as in, does not return LUA_ERRFILE); then run it. We store load errors
862         // from all the attempts, and show them once we know we can't find any of them.
863         lua_settop(L, 0);
864         vector<string> errors;
865         bool success = false;
866         for (size_t i = 0; i < search_dirs.size(); ++i) {
867                 string path = search_dirs[i] + "/" + filename;
868                 int err = luaL_loadfile(L, path.c_str());
869                 if (err == 0) {
870                         // Success; actually call the code.
871                         if (lua_pcall(L, 0, LUA_MULTRET, 0)) {
872                                 fprintf(stderr, "Error when running %s: %s\n", path.c_str(), lua_tostring(L, -1));
873                                 exit(1);
874                         }
875                         success = true;
876                         break;
877                 }
878                 errors.push_back(lua_tostring(L, -1));
879                 lua_pop(L, 1);
880                 if (err != LUA_ERRFILE) {
881                         // The file actually loaded, but failed to parse somehow. Abort; don't try the next one.
882                         break;
883                 }
884         }
885
886         if (!success) {
887                 for (const string &error : errors) {
888                         fprintf(stderr, "%s\n", error.c_str());
889                 }
890                 exit(1);
891         }
892         assert(lua_gettop(L) == 0);
893
894         // Ask it for the number of channels.
895         num_channels = call_num_channels(L);
896 }
897
898 Theme::~Theme()
899 {
900         lua_close(L);
901 }
902
903 void Theme::register_class(const char *class_name, const luaL_Reg *funcs)
904 {
905         assert(lua_gettop(L) == 0);
906         luaL_newmetatable(L, class_name);  // mt = {}
907         lua_pushlightuserdata(L, this);
908         luaL_setfuncs(L, funcs, 1);        // for (name,f in funcs) { mt[name] = f, with upvalue {theme} }
909         lua_pushvalue(L, -1);
910         lua_setfield(L, -2, "__index");    // mt.__index = mt
911         lua_setglobal(L, class_name);      // ClassName = mt
912         assert(lua_gettop(L) == 0);
913 }
914
915 Theme::Chain Theme::get_chain(unsigned num, float t, unsigned width, unsigned height, InputState input_state) 
916 {
917         Chain chain;
918
919         unique_lock<mutex> lock(m);
920         assert(lua_gettop(L) == 0);
921         lua_getglobal(L, "get_chain");  /* function to be called */
922         lua_pushnumber(L, num);
923         lua_pushnumber(L, t);
924         lua_pushnumber(L, width);
925         lua_pushnumber(L, height);
926         wrap_lua_object<InputStateInfo>(L, "InputStateInfo", input_state);
927
928         if (lua_pcall(L, 5, 2, 0) != 0) {
929                 fprintf(stderr, "error running function `get_chain': %s\n", lua_tostring(L, -1));
930                 exit(1);
931         }
932
933         chain.chain = (EffectChain *)luaL_testudata(L, -2, "EffectChain");
934         if (chain.chain == nullptr) {
935                 fprintf(stderr, "get_chain() for chain number %d did not return an EffectChain\n",
936                         num);
937                 exit(1);
938         }
939         if (!lua_isfunction(L, -1)) {
940                 fprintf(stderr, "Argument #-1 should be a function\n");
941                 exit(1);
942         }
943         lua_pushvalue(L, -1);
944         shared_ptr<LuaRefWithDeleter> funcref(new LuaRefWithDeleter(&m, L, luaL_ref(L, LUA_REGISTRYINDEX)));
945         lua_pop(L, 2);
946         assert(lua_gettop(L) == 0);
947
948         chain.setup_chain = [this, funcref, input_state]{
949                 unique_lock<mutex> lock(m);
950
951                 this->input_state = &input_state;
952
953                 // Set up state, including connecting signals.
954                 lua_rawgeti(L, LUA_REGISTRYINDEX, funcref->get());
955                 if (lua_pcall(L, 0, 0, 0) != 0) {
956                         fprintf(stderr, "error running chain setup callback: %s\n", lua_tostring(L, -1));
957                         exit(1);
958                 }
959                 assert(lua_gettop(L) == 0);
960         };
961
962         // TODO: Can we do better, e.g. by running setup_chain() and seeing what it references?
963         // Actually, setup_chain does maybe hold all the references we need now anyway?
964         for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
965                 for (unsigned frame_num = 0; frame_num < FRAME_HISTORY_LENGTH; ++frame_num) {
966                         chain.input_frames.push_back(input_state.buffered_frames[card_index][frame_num].frame);
967                 }
968         }
969
970         return chain;
971 }
972
973 string Theme::get_channel_name(unsigned channel)
974 {
975         unique_lock<mutex> lock(m);
976         lua_getglobal(L, "channel_name");
977         lua_pushnumber(L, channel);
978         if (lua_pcall(L, 1, 1, 0) != 0) {
979                 fprintf(stderr, "error running function `channel_name': %s\n", lua_tostring(L, -1));
980                 exit(1);
981         }
982         const char *ret = lua_tostring(L, -1);
983         if (ret == nullptr) {
984                 fprintf(stderr, "function `channel_name' returned nil for channel %d\n", channel);
985                 exit(1);
986         }
987
988         string retstr = ret;
989         lua_pop(L, 1);
990         assert(lua_gettop(L) == 0);
991         return retstr;
992 }
993
994 int Theme::get_channel_signal(unsigned channel)
995 {
996         unique_lock<mutex> lock(m);
997         lua_getglobal(L, "channel_signal");
998         lua_pushnumber(L, channel);
999         if (lua_pcall(L, 1, 1, 0) != 0) {
1000                 fprintf(stderr, "error running function `channel_signal': %s\n", lua_tostring(L, -1));
1001                 exit(1);
1002         }
1003
1004         int ret = luaL_checknumber(L, 1);
1005         lua_pop(L, 1);
1006         assert(lua_gettop(L) == 0);
1007         return ret;
1008 }
1009
1010 std::string Theme::get_channel_color(unsigned channel)
1011 {
1012         unique_lock<mutex> lock(m);
1013         lua_getglobal(L, "channel_color");
1014         lua_pushnumber(L, channel);
1015         if (lua_pcall(L, 1, 1, 0) != 0) {
1016                 fprintf(stderr, "error running function `channel_color': %s\n", lua_tostring(L, -1));
1017                 exit(1);
1018         }
1019
1020         const char *ret = lua_tostring(L, -1);
1021         if (ret == nullptr) {
1022                 fprintf(stderr, "function `channel_color' returned nil for channel %d\n", channel);
1023                 exit(1);
1024         }
1025
1026         string retstr = ret;
1027         lua_pop(L, 1);
1028         assert(lua_gettop(L) == 0);
1029         return retstr;
1030 }
1031
1032 bool Theme::get_supports_set_wb(unsigned channel)
1033 {
1034         unique_lock<mutex> lock(m);
1035         lua_getglobal(L, "supports_set_wb");
1036         lua_pushnumber(L, channel);
1037         if (lua_pcall(L, 1, 1, 0) != 0) {
1038                 fprintf(stderr, "error running function `supports_set_wb': %s\n", lua_tostring(L, -1));
1039                 exit(1);
1040         }
1041
1042         bool ret = checkbool(L, -1);
1043         lua_pop(L, 1);
1044         assert(lua_gettop(L) == 0);
1045         return ret;
1046 }
1047
1048 void Theme::set_wb(unsigned channel, double r, double g, double b)
1049 {
1050         unique_lock<mutex> lock(m);
1051         lua_getglobal(L, "set_wb");
1052         lua_pushnumber(L, channel);
1053         lua_pushnumber(L, r);
1054         lua_pushnumber(L, g);
1055         lua_pushnumber(L, b);
1056         if (lua_pcall(L, 4, 0, 0) != 0) {
1057                 fprintf(stderr, "error running function `set_wb': %s\n", lua_tostring(L, -1));
1058                 exit(1);
1059         }
1060
1061         assert(lua_gettop(L) == 0);
1062 }
1063
1064 vector<string> Theme::get_transition_names(float t)
1065 {
1066         unique_lock<mutex> lock(m);
1067         lua_getglobal(L, "get_transitions");
1068         lua_pushnumber(L, t);
1069         if (lua_pcall(L, 1, 1, 0) != 0) {
1070                 fprintf(stderr, "error running function `get_transitions': %s\n", lua_tostring(L, -1));
1071                 exit(1);
1072         }
1073
1074         vector<string> ret;
1075         lua_pushnil(L);
1076         while (lua_next(L, -2) != 0) {
1077                 ret.push_back(lua_tostring(L, -1));
1078                 lua_pop(L, 1);
1079         }
1080         lua_pop(L, 1);
1081         assert(lua_gettop(L) == 0);
1082         return ret;
1083 }       
1084
1085 int Theme::map_signal(int signal_num)
1086 {
1087         unique_lock<mutex> lock(map_m);
1088         if (signal_to_card_mapping.count(signal_num)) {
1089                 return signal_to_card_mapping[signal_num];
1090         }
1091
1092         int card_index;
1093         if (global_flags.output_card != -1 && num_cards > 1) {
1094                 // Try to exclude the output card from the default card_index.
1095                 card_index = signal_num % (num_cards - 1);
1096                 if (card_index >= global_flags.output_card) {
1097                          ++card_index;
1098                 }
1099                 if (signal_num >= int(num_cards - 1)) {
1100                         fprintf(stderr, "WARNING: Theme asked for input %d, but we only have %u input card(s) (card %d is busy with output).\n",
1101                                 signal_num, num_cards - 1, global_flags.output_card);
1102                         fprintf(stderr, "Mapping to card %d instead.\n", card_index);
1103                 }
1104         } else {
1105                 card_index = signal_num % num_cards;
1106                 if (signal_num >= int(num_cards)) {
1107                         fprintf(stderr, "WARNING: Theme asked for input %d, but we only have %u card(s).\n", signal_num, num_cards);
1108                         fprintf(stderr, "Mapping to card %d instead.\n", card_index);
1109                 }
1110         }
1111         signal_to_card_mapping[signal_num] = card_index;
1112         return card_index;
1113 }
1114
1115 void Theme::set_signal_mapping(int signal_num, int card_num)
1116 {
1117         unique_lock<mutex> lock(map_m);
1118         assert(card_num < int(num_cards));
1119         signal_to_card_mapping[signal_num] = card_num;
1120 }
1121
1122 void Theme::transition_clicked(int transition_num, float t)
1123 {
1124         unique_lock<mutex> lock(m);
1125         lua_getglobal(L, "transition_clicked");
1126         lua_pushnumber(L, transition_num);
1127         lua_pushnumber(L, t);
1128
1129         if (lua_pcall(L, 2, 0, 0) != 0) {
1130                 fprintf(stderr, "error running function `transition_clicked': %s\n", lua_tostring(L, -1));
1131                 exit(1);
1132         }
1133         assert(lua_gettop(L) == 0);
1134 }
1135
1136 void Theme::channel_clicked(int preview_num)
1137 {
1138         unique_lock<mutex> lock(m);
1139         lua_getglobal(L, "channel_clicked");
1140         lua_pushnumber(L, preview_num);
1141
1142         if (lua_pcall(L, 1, 0, 0) != 0) {
1143                 fprintf(stderr, "error running function `channel_clicked': %s\n", lua_tostring(L, -1));
1144                 exit(1);
1145         }
1146         assert(lua_gettop(L) == 0);
1147 }