]> git.sesse.net Git - nageru/blob - theme.cpp
Reduce the warning storm a bit.
[nageru] / theme.cpp
1 #include "theme.h"
2
3 #include <assert.h>
4 #include <lauxlib.h>
5 #include <lua.h>
6 #include <lualib.h>
7 #include <movit/effect.h>
8 #include <movit/effect_chain.h>
9 #include <movit/image_format.h>
10 #include <movit/mix_effect.h>
11 #include <movit/overlay_effect.h>
12 #include <movit/padding_effect.h>
13 #include <movit/resample_effect.h>
14 #include <movit/resize_effect.h>
15 #include <movit/white_balance_effect.h>
16 #include <movit/ycbcr.h>
17 #include <movit/ycbcr_input.h>
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <cstddef>
21 #include <new>
22 #include <utility>
23
24 namespace movit {
25 class ResourcePool;
26 }  // namespace movit
27
28 #define WIDTH 1280  // FIXME
29 #define HEIGHT 720  // FIXME
30
31 using namespace std;
32 using namespace movit;
33
34 namespace {
35
36 vector<LiveInputWrapper *> live_inputs;
37
38 template<class T, class... Args>
39 int wrap_lua_object(lua_State* L, const char *class_name, Args&&... args)
40 {
41         // Construct the C++ object and put it on the stack.
42         void *mem = lua_newuserdata(L, sizeof(T));
43         new(mem) T(std::forward<Args>(args)...);
44
45         // Look up the metatable named <class_name>, and set it on the new object.
46         luaL_getmetatable(L, class_name);
47         lua_setmetatable(L, -2);
48
49         return 1;
50 }
51
52 Theme *get_theme_updata(lua_State* L)
53 {       
54         luaL_checktype(L, lua_upvalueindex(1), LUA_TLIGHTUSERDATA);
55         return (Theme *)lua_touserdata(L, lua_upvalueindex(1));
56 }
57
58 Effect *get_effect(lua_State *L, int idx)
59 {
60         if (luaL_testudata(L, idx, "WhiteBalanceEffect") ||
61             luaL_testudata(L, idx, "ResampleEffect") ||
62             luaL_testudata(L, idx, "PaddingEffect") ||
63             luaL_testudata(L, idx, "IntegralPaddingEffect") ||
64             luaL_testudata(L, idx, "OverlayEffect") ||
65             luaL_testudata(L, idx, "ResizeEffect") ||
66             luaL_testudata(L, idx, "MixEffect")) {
67                 return (Effect *)lua_touserdata(L, idx);
68         }
69         luaL_error(L, "Error: Index #%d was not an Effect type\n", idx);
70         return nullptr;
71 }
72
73 bool checkbool(lua_State* L, int idx)
74 {
75         luaL_checktype(L, idx, LUA_TBOOLEAN);
76         return lua_toboolean(L, idx);
77 }
78
79 int EffectChain_new(lua_State* L)
80 {
81         assert(lua_gettop(L) == 2);
82         int aspect_w = luaL_checknumber(L, 1);
83         int aspect_h = luaL_checknumber(L, 2);
84
85         return wrap_lua_object<EffectChain>(L, "EffectChain", aspect_w, aspect_h);
86 }
87
88 int EffectChain_add_live_input(lua_State* L)
89 {
90         assert(lua_gettop(L) == 2);
91         Theme *theme = get_theme_updata(L);
92         EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
93         bool override_bounce = checkbool(L, 2);
94         return wrap_lua_object<LiveInputWrapper>(L, "LiveInputWrapper", theme, chain, override_bounce);
95 }
96
97 int EffectChain_add_effect(lua_State* L)
98 {
99         assert(lua_gettop(L) >= 2);
100         EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
101
102         // TODO: Better error reporting.
103         Effect *effect = get_effect(L, 2);
104         if (lua_gettop(L) == 2) {
105                 chain->add_effect(effect);
106         } else {
107                 vector<Effect *> inputs;
108                 for (int idx = 3; idx <= lua_gettop(L); ++idx) {
109                         if (luaL_testudata(L, idx, "LiveInputWrapper")) {
110                                 LiveInputWrapper *input = (LiveInputWrapper *)lua_touserdata(L, idx);
111                                 inputs.push_back(input->get_input());
112                         } else {
113                                 inputs.push_back(get_effect(L, idx));
114                         }
115                 }
116                 chain->add_effect(effect, inputs);
117         }
118
119         lua_settop(L, 2);  // Return the effect itself.
120
121         // Make sure Lua doesn't garbage-collect it away.
122         lua_pushvalue(L, -1);
123         luaL_ref(L, LUA_REGISTRYINDEX);  // TODO: leak?
124
125         return 1;
126 }
127
128 int EffectChain_finalize(lua_State* L)
129 {
130         assert(lua_gettop(L) == 2);
131         EffectChain *chain = (EffectChain *)luaL_checkudata(L, 1, "EffectChain");
132         bool is_main_chain = checkbool(L, 2);
133
134         // Add outputs as needed.
135         // NOTE: If you change any details about the output format, you will need to
136         // also update what's given to the muxer (HTTPD::Mux constructor) and
137         // what's put in the H.264 stream (sps_rbsp()).
138         ImageFormat inout_format;
139         inout_format.color_space = COLORSPACE_REC_709;
140
141         // Output gamma is tricky. We should output Rec. 709 for TV, except that
142         // we expect to run with web players and others that don't really care and
143         // just output with no conversion. So that means we'll need to output sRGB,
144         // even though H.264 has no setting for that (we use “unspecified”).
145         inout_format.gamma_curve = GAMMA_sRGB;
146
147         if (is_main_chain) {
148                 YCbCrFormat output_ycbcr_format;
149                 // We actually output 4:2:0 in the end, but chroma subsampling
150                 // happens in a pass not run by Movit (see Mixer::subsample_chroma()).
151                 output_ycbcr_format.chroma_subsampling_x = 1;
152                 output_ycbcr_format.chroma_subsampling_y = 1;
153
154                 // Rec. 709 would be the sane thing to do, but it seems many players
155                 // (e.g. MPlayer and VLC) just default to BT.601 coefficients no matter
156                 // what (see discussions in e.g. https://trac.ffmpeg.org/ticket/4978).
157                 // We _do_ set the right flags, though, so that a player that works
158                 // properly doesn't have to guess.
159                 output_ycbcr_format.luma_coefficients = YCBCR_REC_601;
160                 output_ycbcr_format.full_range = false;
161                 output_ycbcr_format.num_levels = 256;
162
163                 chain->add_ycbcr_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED, output_ycbcr_format, YCBCR_OUTPUT_SPLIT_Y_AND_CBCR);
164                 chain->set_dither_bits(8);
165                 chain->set_output_origin(OUTPUT_ORIGIN_TOP_LEFT);
166         }
167         chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
168
169         chain->finalize();
170         return 0;
171 }
172
173 int LiveInputWrapper_connect_signal(lua_State* L)
174 {
175         assert(lua_gettop(L) == 2);
176         LiveInputWrapper *input = (LiveInputWrapper *)luaL_checkudata(L, 1, "LiveInputWrapper");
177         int signal_num = luaL_checknumber(L, 2);
178         input->connect_signal(signal_num);
179         return 0;
180 }
181
182 int WhiteBalanceEffect_new(lua_State* L)
183 {
184         assert(lua_gettop(L) == 0);
185         return wrap_lua_object<WhiteBalanceEffect>(L, "WhiteBalanceEffect");
186 }
187
188 int ResampleEffect_new(lua_State* L)
189 {
190         assert(lua_gettop(L) == 0);
191         return wrap_lua_object<ResampleEffect>(L, "ResampleEffect");
192 }
193
194 int PaddingEffect_new(lua_State* L)
195 {
196         assert(lua_gettop(L) == 0);
197         return wrap_lua_object<PaddingEffect>(L, "PaddingEffect");
198 }
199
200 int IntegralPaddingEffect_new(lua_State* L)
201 {
202         assert(lua_gettop(L) == 0);
203         return wrap_lua_object<IntegralPaddingEffect>(L, "IntegralPaddingEffect");
204 }
205
206 int OverlayEffect_new(lua_State* L)
207 {
208         assert(lua_gettop(L) == 0);
209         return wrap_lua_object<OverlayEffect>(L, "OverlayEffect");
210 }
211
212 int ResizeEffect_new(lua_State* L)
213 {
214         assert(lua_gettop(L) == 0);
215         return wrap_lua_object<ResizeEffect>(L, "ResizeEffect");
216 }
217
218 int MixEffect_new(lua_State* L)
219 {
220         assert(lua_gettop(L) == 0);
221         return wrap_lua_object<MixEffect>(L, "MixEffect");
222 }
223
224 int Effect_set_float(lua_State *L)
225 {
226         assert(lua_gettop(L) == 3);
227         Effect *effect = (Effect *)get_effect(L, 1);
228         size_t len;
229         const char* cstr = lua_tolstring(L, 2, &len);
230         std::string key(cstr, len);
231         float value = luaL_checknumber(L, 3);
232         if (!effect->set_float(key, value)) {
233                 luaL_error(L, "Effect refused set_float(\"%s\", %d) (invalid key?)", cstr, int(value));
234         }
235         return 0;
236 }
237
238 int Effect_set_int(lua_State *L)
239 {
240         assert(lua_gettop(L) == 3);
241         Effect *effect = (Effect *)get_effect(L, 1);
242         size_t len;
243         const char* cstr = lua_tolstring(L, 2, &len);
244         std::string key(cstr, len);
245         float value = luaL_checknumber(L, 3);
246         if (!effect->set_int(key, value)) {
247                 luaL_error(L, "Effect refused set_int(\"%s\", %d) (invalid key?)", cstr, int(value));
248         }
249         return 0;
250 }
251
252 int Effect_set_vec4(lua_State *L)
253 {
254         assert(lua_gettop(L) == 6);
255         Effect *effect = (Effect *)get_effect(L, 1);
256         size_t len;
257         const char* cstr = lua_tolstring(L, 2, &len);
258         std::string key(cstr, len);
259         float v[4];
260         v[0] = luaL_checknumber(L, 3);
261         v[1] = luaL_checknumber(L, 4);
262         v[2] = luaL_checknumber(L, 5);
263         v[3] = luaL_checknumber(L, 6);
264         if (!effect->set_vec4(key, v)) {
265                 luaL_error(L, "Effect refused set_vec4(\"%s\", %f, %f, %f, %f) (invalid key?)", cstr,
266                         v[0], v[1], v[2], v[3]);
267         }
268         return 0;
269 }
270
271 const luaL_Reg EffectChain_funcs[] = {
272         { "new", EffectChain_new },
273         { "add_live_input", EffectChain_add_live_input },
274         { "add_effect", EffectChain_add_effect },
275         { "finalize", EffectChain_finalize },
276         { NULL, NULL }
277 };
278
279 const luaL_Reg LiveInputWrapper_funcs[] = {
280         { "connect_signal", LiveInputWrapper_connect_signal },
281         { NULL, NULL }
282 };
283
284 const luaL_Reg WhiteBalanceEffect_funcs[] = {
285         { "new", WhiteBalanceEffect_new },
286         { "set_float", Effect_set_float },
287         { "set_int", Effect_set_int },
288         { "set_vec4", Effect_set_vec4 },
289         { NULL, NULL }
290 };
291
292 const luaL_Reg ResampleEffect_funcs[] = {
293         { "new", ResampleEffect_new },
294         { "set_float", Effect_set_float },
295         { "set_int", Effect_set_int },
296         { "set_vec4", Effect_set_vec4 },
297         { NULL, NULL }
298 };
299
300 const luaL_Reg PaddingEffect_funcs[] = {
301         { "new", PaddingEffect_new },
302         { "set_float", Effect_set_float },
303         { "set_int", Effect_set_int },
304         { "set_vec4", Effect_set_vec4 },
305         { NULL, NULL }
306 };
307
308 const luaL_Reg IntegralPaddingEffect_funcs[] = {
309         { "new", IntegralPaddingEffect_new },
310         { "set_float", Effect_set_float },
311         { "set_int", Effect_set_int },
312         { "set_vec4", Effect_set_vec4 },
313         { NULL, NULL }
314 };
315
316 const luaL_Reg OverlayEffect_funcs[] = {
317         { "new", OverlayEffect_new },
318         { "set_float", Effect_set_float },
319         { "set_int", Effect_set_int },
320         { "set_vec4", Effect_set_vec4 },
321         { NULL, NULL }
322 };
323
324 const luaL_Reg ResizeEffect_funcs[] = {
325         { "new", ResizeEffect_new },
326         { "set_float", Effect_set_float },
327         { "set_int", Effect_set_int },
328         { "set_vec4", Effect_set_vec4 },
329         { NULL, NULL }
330 };
331
332 const luaL_Reg MixEffect_funcs[] = {
333         { "new", MixEffect_new },
334         { "set_float", Effect_set_float },
335         { "set_int", Effect_set_int },
336         { "set_vec4", Effect_set_vec4 },
337         { NULL, NULL }
338 };
339
340 }  // namespace
341
342 LiveInputWrapper::LiveInputWrapper(Theme *theme, EffectChain *chain, bool override_bounce)
343         : theme(theme)
344 {
345         ImageFormat inout_format;
346         inout_format.color_space = COLORSPACE_sRGB;
347
348         // Gamma curve depends on the input signal, and we don't really get any
349         // indications. A camera would be expected to do Rec. 709, but
350         // I haven't checked if any do in practice. However, computers _do_ output
351         // in sRGB gamma (ie., they don't convert from sRGB to Rec. 709), and
352         // I wouldn't really be surprised if most non-professional cameras do, too.
353         // So we pick sRGB as the least evil here.
354         inout_format.gamma_curve = GAMMA_sRGB;
355
356         // The Blackmagic driver docs claim that the device outputs Y'CbCr
357         // according to Rec. 601, but practical testing indicates it definitely
358         // is Rec. 709 (at least up to errors attributable to rounding errors).
359         // Perhaps 601 was only to indicate the subsampling positions, not the
360         // colorspace itself? Tested with a Lenovo X1 gen 3 as input.
361         YCbCrFormat input_ycbcr_format;
362         input_ycbcr_format.chroma_subsampling_x = 2;
363         input_ycbcr_format.chroma_subsampling_y = 1;
364         input_ycbcr_format.cb_x_position = 0.0;
365         input_ycbcr_format.cr_x_position = 0.0;
366         input_ycbcr_format.cb_y_position = 0.5;
367         input_ycbcr_format.cr_y_position = 0.5;
368         input_ycbcr_format.luma_coefficients = YCBCR_REC_709;
369         input_ycbcr_format.full_range = false;
370
371         if (override_bounce) {
372                 input = new NonBouncingYCbCrInput(inout_format, input_ycbcr_format, WIDTH, HEIGHT, YCBCR_INPUT_SPLIT_Y_AND_CBCR);
373         } else {
374                 input = new YCbCrInput(inout_format, input_ycbcr_format, WIDTH, HEIGHT, YCBCR_INPUT_SPLIT_Y_AND_CBCR);
375         }
376         chain->add_input(input);
377 }
378
379 void LiveInputWrapper::connect_signal(int signal_num)
380 {
381         theme->connect_signal(input, signal_num);
382 }
383
384 Theme::Theme(const char *filename, ResourcePool *resource_pool, unsigned num_cards)
385         : resource_pool(resource_pool), num_cards(num_cards)
386 {
387         L = luaL_newstate();
388         luaL_openlibs(L);
389
390         register_class("EffectChain", EffectChain_funcs); 
391         register_class("LiveInputWrapper", LiveInputWrapper_funcs); 
392         register_class("WhiteBalanceEffect", WhiteBalanceEffect_funcs);
393         register_class("ResampleEffect", ResampleEffect_funcs);
394         register_class("PaddingEffect", PaddingEffect_funcs);
395         register_class("IntegralPaddingEffect", IntegralPaddingEffect_funcs);
396         register_class("OverlayEffect", OverlayEffect_funcs);
397         register_class("ResizeEffect", ResizeEffect_funcs);
398         register_class("MixEffect", MixEffect_funcs);
399
400         // Run script.
401         lua_settop(L, 0);
402         if (luaL_dofile(L, filename)) {
403                 fprintf(stderr, "error: %s\n", lua_tostring(L, -1));
404                 lua_pop(L, 1);
405                 exit(1);
406         }
407         assert(lua_gettop(L) == 0);
408
409         // Ask it for the number of channels.
410         lua_getglobal(L, "num_channels");
411
412         if (lua_pcall(L, 0, 1, 0) != 0) {
413                 fprintf(stderr, "error running function `num_channels': %s\n", lua_tostring(L, -1));
414                 exit(1);
415         }
416
417         num_channels = luaL_checknumber(L, 1);
418         lua_pop(L, 1);
419         assert(lua_gettop(L) == 0);
420 }
421
422 void Theme::register_class(const char *class_name, const luaL_Reg *funcs)
423 {
424         assert(lua_gettop(L) == 0);
425         luaL_newmetatable(L, class_name);
426         lua_pushlightuserdata(L, this);
427         luaL_setfuncs(L, funcs, 1);
428         lua_pushvalue(L, -1);
429         lua_setfield(L, -2, "__index");
430         lua_setglobal(L, class_name);
431         assert(lua_gettop(L) == 0);
432 }
433
434 pair<EffectChain *, function<void()>>
435 Theme::get_chain(unsigned num, float t, unsigned width, unsigned height)
436 {
437         unique_lock<mutex> lock(m);
438         assert(lua_gettop(L) == 0);
439         lua_getglobal(L, "get_chain");  /* function to be called */
440         lua_pushnumber(L, num);
441         lua_pushnumber(L, t);
442         lua_pushnumber(L, width);
443         lua_pushnumber(L, height);
444
445         if (lua_pcall(L, 4, 2, 0) != 0) {
446                 fprintf(stderr, "error running function `get_chain': %s\n", lua_tostring(L, -1));
447                 exit(1);
448         }
449
450         EffectChain *chain = (EffectChain *)luaL_checkudata(L, -2, "EffectChain");
451         if (!lua_isfunction(L, -1)) {
452                 fprintf(stderr, "Argument #-1 should be a function\n");
453                 exit(1);
454         }
455         lua_pushvalue(L, -1);
456         int funcref = luaL_ref(L, LUA_REGISTRYINDEX);  // TODO: leak!
457         lua_pop(L, 2);
458         assert(lua_gettop(L) == 0);
459         return make_pair(chain, [this, funcref]{
460                 unique_lock<mutex> lock(m);
461
462                 // Set up state, including connecting signals.
463                 lua_rawgeti(L, LUA_REGISTRYINDEX, funcref);
464                 if (lua_pcall(L, 0, 0, 0) != 0) {
465                         fprintf(stderr, "error running chain setup callback: %s\n", lua_tostring(L, -1));
466                         exit(1);
467                 }
468                 assert(lua_gettop(L) == 0);
469         });
470 }
471
472 std::vector<std::string> Theme::get_transition_names(float t)
473 {
474         unique_lock<mutex> lock(m);
475         lua_getglobal(L, "get_transitions");
476         lua_pushnumber(L, t);
477         if (lua_pcall(L, 1, 1, 0) != 0) {
478                 fprintf(stderr, "error running function `get_transitions': %s\n", lua_tostring(L, -1));
479                 exit(1);
480         }
481
482         std::vector<std::string> ret;
483         lua_pushnil(L);
484         while (lua_next(L, -2) != 0) {
485                 ret.push_back(lua_tostring(L, -1));
486                 lua_pop(L, 1);
487         }
488         lua_pop(L, 1);
489         assert(lua_gettop(L) == 0);
490         return ret;
491 }       
492
493 void Theme::connect_signal(YCbCrInput *input, int signal_num)
494 {
495         if (signal_num >= int(num_cards)) {
496                 if (signals_warned_about.insert(signal_num).second) {
497                         fprintf(stderr, "WARNING: Theme asked for input %d, but we only have %u card(s).\n", signal_num, num_cards);
498                         fprintf(stderr, "Mapping to card %d instead.\n", signal_num % num_cards);
499                 }
500                 signal_num %= num_cards;
501         }
502         input->set_texture_num(0, input_textures[signal_num].tex_y);
503         input->set_texture_num(1, input_textures[signal_num].tex_cbcr);
504 }
505
506 void Theme::transition_clicked(int transition_num, float t)
507 {
508         unique_lock<mutex> lock(m);
509         lua_getglobal(L, "transition_clicked");
510         lua_pushnumber(L, transition_num);
511         lua_pushnumber(L, t);
512
513         if (lua_pcall(L, 2, 0, 0) != 0) {
514                 fprintf(stderr, "error running function `transition_clicked': %s\n", lua_tostring(L, -1));
515                 exit(1);
516         }
517         assert(lua_gettop(L) == 0);
518 }
519
520 void Theme::channel_clicked(int preview_num)
521 {
522         unique_lock<mutex> lock(m);
523         lua_getglobal(L, "channel_clicked");
524         lua_pushnumber(L, preview_num);
525
526         if (lua_pcall(L, 1, 0, 0) != 0) {
527                 fprintf(stderr, "error running function `channel_clicked': %s\n", lua_tostring(L, -1));
528                 exit(1);
529         }
530         assert(lua_gettop(L) == 0);
531 }