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