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