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