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