]> git.sesse.net Git - nageru/blob - theme.cpp
Give frames a pixel format.
[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         // The Blackmagic driver docs claim that the device outputs Y'CbCr
616         // according to Rec. 601, but practical testing indicates it definitely
617         // is Rec. 709 (at least up to errors attributable to rounding errors).
618         // Perhaps 601 was only to indicate the subsampling positions, not the
619         // colorspace itself? Tested with a Lenovo X1 gen 3 as input.
620         YCbCrFormat input_ycbcr_format;
621         input_ycbcr_format.chroma_subsampling_x = (pixel_format == bmusb::PixelFormat_10BitYCbCr) ? 1 : 2;
622         input_ycbcr_format.chroma_subsampling_y = 1;
623         input_ycbcr_format.num_levels = (pixel_format == bmusb::PixelFormat_10BitYCbCr) ? 1024 : 256;
624         input_ycbcr_format.cb_x_position = 0.0;
625         input_ycbcr_format.cr_x_position = 0.0;
626         input_ycbcr_format.cb_y_position = 0.5;
627         input_ycbcr_format.cr_y_position = 0.5;
628         input_ycbcr_format.luma_coefficients = YCBCR_REC_709;
629         input_ycbcr_format.full_range = false;
630
631         unsigned num_inputs;
632         if (deinterlace) {
633                 deinterlace_effect = new movit::DeinterlaceEffect();
634
635                 // As per the comments in deinterlace_effect.h, we turn this off.
636                 // The most likely interlaced input for us is either a camera
637                 // (where it's fine to turn it off) or a laptop (where it _should_
638                 // be turned off).
639                 CHECK(deinterlace_effect->set_int("enable_spatial_interlacing_check", 0));
640
641                 num_inputs = deinterlace_effect->num_inputs();
642                 assert(num_inputs == FRAME_HISTORY_LENGTH);
643         } else {
644                 num_inputs = 1;
645         }
646         for (unsigned i = 0; i < num_inputs; ++i) {
647                 // When using 10-bit input, we're converting to interleaved through v210Converter.
648                 YCbCrInputSplitting splitting = (pixel_format == bmusb::PixelFormat_10BitYCbCr) ? YCBCR_INPUT_INTERLEAVED : YCBCR_INPUT_SPLIT_Y_AND_CBCR;
649                 if (override_bounce) {
650                         inputs.push_back(new NonBouncingYCbCrInput(inout_format, input_ycbcr_format, global_flags.width, global_flags.height, splitting));
651                 } else {
652                         inputs.push_back(new YCbCrInput(inout_format, input_ycbcr_format, global_flags.width, global_flags.height, splitting));
653                 }
654                 chain->add_input(inputs.back());
655         }
656
657         if (deinterlace) {
658                 vector<Effect *> reverse_inputs(inputs.rbegin(), inputs.rend());
659                 chain->add_effect(deinterlace_effect, reverse_inputs);
660         }
661 }
662
663 void LiveInputWrapper::connect_signal(int signal_num)
664 {
665         if (global_mixer == nullptr) {
666                 // No data yet.
667                 return;
668         }
669
670         signal_num = theme->map_signal(signal_num);
671
672         BufferedFrame first_frame = theme->input_state->buffered_frames[signal_num][0];
673         if (first_frame.frame == nullptr) {
674                 // No data yet.
675                 return;
676         }
677         unsigned width, height;
678         {
679                 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)first_frame.frame->userdata;
680                 width = userdata->last_width[first_frame.field_number];
681                 height = userdata->last_height[first_frame.field_number];
682         }
683
684         BufferedFrame last_good_frame = first_frame;
685         for (unsigned i = 0; i < inputs.size(); ++i) {
686                 BufferedFrame frame = theme->input_state->buffered_frames[signal_num][i];
687                 if (frame.frame == nullptr) {
688                         // Not enough data; reuse last frame (well, field).
689                         // This is suboptimal, but we have nothing better.
690                         frame = last_good_frame;
691                 }
692                 const PBOFrameAllocator::Userdata *userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
693
694                 if (userdata->last_width[frame.field_number] != width ||
695                     userdata->last_height[frame.field_number] != height) {
696                         // Resolution changed; reuse last frame/field.
697                         frame = last_good_frame;
698                         userdata = (const PBOFrameAllocator::Userdata *)frame.frame->userdata;
699                 }
700
701                 assert(userdata->pixel_format == pixel_format);
702                 if (pixel_format == bmusb::PixelFormat_10BitYCbCr) {
703                         inputs[i]->set_texture_num(0, userdata->tex_444[frame.field_number]);
704                 } else {
705                         inputs[i]->set_texture_num(0, userdata->tex_y[frame.field_number]);
706                         inputs[i]->set_texture_num(1, userdata->tex_cbcr[frame.field_number]);
707                 }
708                 inputs[i]->set_width(userdata->last_width[frame.field_number]);
709                 inputs[i]->set_height(userdata->last_height[frame.field_number]);
710
711                 last_good_frame = frame;
712         }
713
714         if (deinterlace) {
715                 BufferedFrame frame = theme->input_state->buffered_frames[signal_num][0];
716                 CHECK(deinterlace_effect->set_int("current_field_position", frame.field_number));
717         }
718 }
719
720 namespace {
721
722 int call_num_channels(lua_State *L)
723 {
724         lua_getglobal(L, "num_channels");
725
726         if (lua_pcall(L, 0, 1, 0) != 0) {
727                 fprintf(stderr, "error running function `num_channels': %s\n", lua_tostring(L, -1));
728                 exit(1);
729         }
730
731         int num_channels = luaL_checknumber(L, 1);
732         lua_pop(L, 1);
733         assert(lua_gettop(L) == 0);
734         return num_channels;
735 }
736
737 }  // namespace
738
739 Theme::Theme(const string &filename, const vector<string> &search_dirs, ResourcePool *resource_pool, unsigned num_cards)
740         : resource_pool(resource_pool), num_cards(num_cards), signal_to_card_mapping(global_flags.default_stream_mapping)
741 {
742         L = luaL_newstate();
743         luaL_openlibs(L);
744
745         register_class("EffectChain", EffectChain_funcs); 
746         register_class("LiveInputWrapper", LiveInputWrapper_funcs); 
747         register_class("ImageInput", ImageInput_funcs);
748         register_class("WhiteBalanceEffect", WhiteBalanceEffect_funcs);
749         register_class("ResampleEffect", ResampleEffect_funcs);
750         register_class("PaddingEffect", PaddingEffect_funcs);
751         register_class("IntegralPaddingEffect", IntegralPaddingEffect_funcs);
752         register_class("OverlayEffect", OverlayEffect_funcs);
753         register_class("ResizeEffect", ResizeEffect_funcs);
754         register_class("MultiplyEffect", MultiplyEffect_funcs);
755         register_class("MixEffect", MixEffect_funcs);
756         register_class("InputStateInfo", InputStateInfo_funcs);
757
758         // Run script. Search through all directories until we find a file that will load
759         // (as in, does not return LUA_ERRFILE); then run it. We store load errors
760         // from all the attempts, and show them once we know we can't find any of them.
761         lua_settop(L, 0);
762         vector<string> errors;
763         bool success = false;
764         for (size_t i = 0; i < search_dirs.size(); ++i) {
765                 string path = search_dirs[i] + "/" + filename;
766                 int err = luaL_loadfile(L, path.c_str());
767                 if (err == 0) {
768                         // Success; actually call the code.
769                         if (lua_pcall(L, 0, LUA_MULTRET, 0)) {
770                                 fprintf(stderr, "Error when running %s: %s\n", path.c_str(), lua_tostring(L, -1));
771                                 exit(1);
772                         }
773                         success = true;
774                         break;
775                 }
776                 errors.push_back(lua_tostring(L, -1));
777                 lua_pop(L, 1);
778                 if (err != LUA_ERRFILE) {
779                         // The file actually loaded, but failed to parse somehow. Abort; don't try the next one.
780                         break;
781                 }
782         }
783
784         if (!success) {
785                 for (const string &error : errors) {
786                         fprintf(stderr, "%s\n", error.c_str());
787                 }
788                 exit(1);
789         }
790         assert(lua_gettop(L) == 0);
791
792         // Ask it for the number of channels.
793         num_channels = call_num_channels(L);
794 }
795
796 Theme::~Theme()
797 {
798         lua_close(L);
799 }
800
801 void Theme::register_class(const char *class_name, const luaL_Reg *funcs)
802 {
803         assert(lua_gettop(L) == 0);
804         luaL_newmetatable(L, class_name);  // mt = {}
805         lua_pushlightuserdata(L, this);
806         luaL_setfuncs(L, funcs, 1);        // for (name,f in funcs) { mt[name] = f, with upvalue {theme} }
807         lua_pushvalue(L, -1);
808         lua_setfield(L, -2, "__index");    // mt.__index = mt
809         lua_setglobal(L, class_name);      // ClassName = mt
810         assert(lua_gettop(L) == 0);
811 }
812
813 Theme::Chain Theme::get_chain(unsigned num, float t, unsigned width, unsigned height, InputState input_state) 
814 {
815         Chain chain;
816
817         unique_lock<mutex> lock(m);
818         assert(lua_gettop(L) == 0);
819         lua_getglobal(L, "get_chain");  /* function to be called */
820         lua_pushnumber(L, num);
821         lua_pushnumber(L, t);
822         lua_pushnumber(L, width);
823         lua_pushnumber(L, height);
824         wrap_lua_object<InputStateInfo>(L, "InputStateInfo", input_state);
825
826         if (lua_pcall(L, 5, 2, 0) != 0) {
827                 fprintf(stderr, "error running function `get_chain': %s\n", lua_tostring(L, -1));
828                 exit(1);
829         }
830
831         chain.chain = (EffectChain *)luaL_testudata(L, -2, "EffectChain");
832         if (chain.chain == nullptr) {
833                 fprintf(stderr, "get_chain() for chain number %d did not return an EffectChain\n",
834                         num);
835                 exit(1);
836         }
837         if (!lua_isfunction(L, -1)) {
838                 fprintf(stderr, "Argument #-1 should be a function\n");
839                 exit(1);
840         }
841         lua_pushvalue(L, -1);
842         shared_ptr<LuaRefWithDeleter> funcref(new LuaRefWithDeleter(&m, L, luaL_ref(L, LUA_REGISTRYINDEX)));
843         lua_pop(L, 2);
844         assert(lua_gettop(L) == 0);
845
846         chain.setup_chain = [this, funcref, input_state]{
847                 unique_lock<mutex> lock(m);
848
849                 this->input_state = &input_state;
850
851                 // Set up state, including connecting signals.
852                 lua_rawgeti(L, LUA_REGISTRYINDEX, funcref->get());
853                 if (lua_pcall(L, 0, 0, 0) != 0) {
854                         fprintf(stderr, "error running chain setup callback: %s\n", lua_tostring(L, -1));
855                         exit(1);
856                 }
857                 assert(lua_gettop(L) == 0);
858         };
859
860         // TODO: Can we do better, e.g. by running setup_chain() and seeing what it references?
861         // Actually, setup_chain does maybe hold all the references we need now anyway?
862         for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
863                 for (unsigned frame_num = 0; frame_num < FRAME_HISTORY_LENGTH; ++frame_num) {
864                         chain.input_frames.push_back(input_state.buffered_frames[card_index][frame_num].frame);
865                 }
866         }
867
868         return chain;
869 }
870
871 string Theme::get_channel_name(unsigned channel)
872 {
873         unique_lock<mutex> lock(m);
874         lua_getglobal(L, "channel_name");
875         lua_pushnumber(L, channel);
876         if (lua_pcall(L, 1, 1, 0) != 0) {
877                 fprintf(stderr, "error running function `channel_name': %s\n", lua_tostring(L, -1));
878                 exit(1);
879         }
880         const char *ret = lua_tostring(L, -1);
881         if (ret == nullptr) {
882                 fprintf(stderr, "function `channel_name' returned nil for channel %d\n", channel);
883                 exit(1);
884         }
885
886         string retstr = ret;
887         lua_pop(L, 1);
888         assert(lua_gettop(L) == 0);
889         return retstr;
890 }
891
892 int Theme::get_channel_signal(unsigned channel)
893 {
894         unique_lock<mutex> lock(m);
895         lua_getglobal(L, "channel_signal");
896         lua_pushnumber(L, channel);
897         if (lua_pcall(L, 1, 1, 0) != 0) {
898                 fprintf(stderr, "error running function `channel_signal': %s\n", lua_tostring(L, -1));
899                 exit(1);
900         }
901
902         int ret = luaL_checknumber(L, 1);
903         lua_pop(L, 1);
904         assert(lua_gettop(L) == 0);
905         return ret;
906 }
907
908 std::string Theme::get_channel_color(unsigned channel)
909 {
910         unique_lock<mutex> lock(m);
911         lua_getglobal(L, "channel_color");
912         lua_pushnumber(L, channel);
913         if (lua_pcall(L, 1, 1, 0) != 0) {
914                 fprintf(stderr, "error running function `channel_color': %s\n", lua_tostring(L, -1));
915                 exit(1);
916         }
917
918         const char *ret = lua_tostring(L, -1);
919         if (ret == nullptr) {
920                 fprintf(stderr, "function `channel_color' returned nil for channel %d\n", channel);
921                 exit(1);
922         }
923
924         string retstr = ret;
925         lua_pop(L, 1);
926         assert(lua_gettop(L) == 0);
927         return retstr;
928 }
929
930 bool Theme::get_supports_set_wb(unsigned channel)
931 {
932         unique_lock<mutex> lock(m);
933         lua_getglobal(L, "supports_set_wb");
934         lua_pushnumber(L, channel);
935         if (lua_pcall(L, 1, 1, 0) != 0) {
936                 fprintf(stderr, "error running function `supports_set_wb': %s\n", lua_tostring(L, -1));
937                 exit(1);
938         }
939
940         bool ret = checkbool(L, -1);
941         lua_pop(L, 1);
942         assert(lua_gettop(L) == 0);
943         return ret;
944 }
945
946 void Theme::set_wb(unsigned channel, double r, double g, double b)
947 {
948         unique_lock<mutex> lock(m);
949         lua_getglobal(L, "set_wb");
950         lua_pushnumber(L, channel);
951         lua_pushnumber(L, r);
952         lua_pushnumber(L, g);
953         lua_pushnumber(L, b);
954         if (lua_pcall(L, 4, 0, 0) != 0) {
955                 fprintf(stderr, "error running function `set_wb': %s\n", lua_tostring(L, -1));
956                 exit(1);
957         }
958
959         assert(lua_gettop(L) == 0);
960 }
961
962 vector<string> Theme::get_transition_names(float t)
963 {
964         unique_lock<mutex> lock(m);
965         lua_getglobal(L, "get_transitions");
966         lua_pushnumber(L, t);
967         if (lua_pcall(L, 1, 1, 0) != 0) {
968                 fprintf(stderr, "error running function `get_transitions': %s\n", lua_tostring(L, -1));
969                 exit(1);
970         }
971
972         vector<string> ret;
973         lua_pushnil(L);
974         while (lua_next(L, -2) != 0) {
975                 ret.push_back(lua_tostring(L, -1));
976                 lua_pop(L, 1);
977         }
978         lua_pop(L, 1);
979         assert(lua_gettop(L) == 0);
980         return ret;
981 }       
982
983 int Theme::map_signal(int signal_num)
984 {
985         unique_lock<mutex> lock(map_m);
986         if (signal_to_card_mapping.count(signal_num)) {
987                 return signal_to_card_mapping[signal_num];
988         }
989
990         int card_index;
991         if (global_flags.output_card != -1 && num_cards > 1) {
992                 // Try to exclude the output card from the default card_index.
993                 card_index = signal_num % (num_cards - 1);
994                 if (card_index >= global_flags.output_card) {
995                          ++card_index;
996                 }
997                 if (signal_num >= int(num_cards - 1)) {
998                         fprintf(stderr, "WARNING: Theme asked for input %d, but we only have %u input card(s) (card %d is busy with output).\n",
999                                 signal_num, num_cards - 1, global_flags.output_card);
1000                         fprintf(stderr, "Mapping to card %d instead.\n", card_index);
1001                 }
1002         } else {
1003                 card_index = signal_num % num_cards;
1004                 if (signal_num >= int(num_cards)) {
1005                         fprintf(stderr, "WARNING: Theme asked for input %d, but we only have %u card(s).\n", signal_num, num_cards);
1006                         fprintf(stderr, "Mapping to card %d instead.\n", card_index);
1007                 }
1008         }
1009         signal_to_card_mapping[signal_num] = card_index;
1010         return card_index;
1011 }
1012
1013 void Theme::set_signal_mapping(int signal_num, int card_num)
1014 {
1015         unique_lock<mutex> lock(map_m);
1016         assert(card_num < int(num_cards));
1017         signal_to_card_mapping[signal_num] = card_num;
1018 }
1019
1020 void Theme::transition_clicked(int transition_num, float t)
1021 {
1022         unique_lock<mutex> lock(m);
1023         lua_getglobal(L, "transition_clicked");
1024         lua_pushnumber(L, transition_num);
1025         lua_pushnumber(L, t);
1026
1027         if (lua_pcall(L, 2, 0, 0) != 0) {
1028                 fprintf(stderr, "error running function `transition_clicked': %s\n", lua_tostring(L, -1));
1029                 exit(1);
1030         }
1031         assert(lua_gettop(L) == 0);
1032 }
1033
1034 void Theme::channel_clicked(int preview_num)
1035 {
1036         unique_lock<mutex> lock(m);
1037         lua_getglobal(L, "channel_clicked");
1038         lua_pushnumber(L, preview_num);
1039
1040         if (lua_pcall(L, 1, 0, 0) != 0) {
1041                 fprintf(stderr, "error running function `channel_clicked': %s\n", lua_tostring(L, -1));
1042                 exit(1);
1043         }
1044         assert(lua_gettop(L) == 0);
1045 }