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