]> git.sesse.net Git - nageru/blob - theme.cpp
Specify unspecified gamma instead of lying and saying we use Rec. 709. Again, for...
[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         // Output gamma is tricky. We should output Rec. 709 for TV, except that
133         // we expect to run with web players and others that don't really care and
134         // just output with no conversion. So that means we'll need to output sRGB,
135         // even though H.264 has no setting for that (we use “unspecified”).
136         inout_format.gamma_curve = GAMMA_sRGB;
137
138         if (is_main_chain) {
139                 YCbCrFormat output_ycbcr_format;
140                 // We actually output 4:2:0 in the end, but chroma subsampling
141                 // happens in a pass not run by Movit (see Mixer::subsample_chroma()).
142                 output_ycbcr_format.chroma_subsampling_x = 1;
143                 output_ycbcr_format.chroma_subsampling_y = 1;
144
145                 // Rec. 709 would be the sane thing to do, but it seems many players
146                 // (e.g. MPlayer and VLC) just default to BT.601 coefficients no matter
147                 // what (see discussions in e.g. https://trac.ffmpeg.org/ticket/4978).
148                 // We _do_ set the right flags, though, so that a player that works
149                 // properly doesn't have to guess.
150                 output_ycbcr_format.luma_coefficients = YCBCR_REC_601;
151                 output_ycbcr_format.full_range = false;
152                 output_ycbcr_format.num_levels = 256;
153
154                 chain->add_ycbcr_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED, output_ycbcr_format, YCBCR_OUTPUT_SPLIT_Y_AND_CBCR);
155                 chain->set_dither_bits(8);
156                 chain->set_output_origin(OUTPUT_ORIGIN_TOP_LEFT);
157         }
158         chain->add_output(inout_format, OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED);
159
160         chain->finalize();
161         return 0;
162 }
163
164 int LiveInputWrapper_connect_signal(lua_State* L)
165 {
166         assert(lua_gettop(L) == 2);
167         LiveInputWrapper *input = (LiveInputWrapper *)luaL_checkudata(L, 1, "LiveInputWrapper");
168         int signal_num = luaL_checknumber(L, 2);
169         input->connect_signal(signal_num);
170         return 0;
171 }
172
173 int WhiteBalanceEffect_new(lua_State* L)
174 {
175         assert(lua_gettop(L) == 0);
176         return wrap_lua_object<WhiteBalanceEffect>(L, "WhiteBalanceEffect");
177 }
178
179 int ResampleEffect_new(lua_State* L)
180 {
181         assert(lua_gettop(L) == 0);
182         return wrap_lua_object<ResampleEffect>(L, "ResampleEffect");
183 }
184
185 int PaddingEffect_new(lua_State* L)
186 {
187         assert(lua_gettop(L) == 0);
188         return wrap_lua_object<PaddingEffect>(L, "PaddingEffect");
189 }
190
191 int IntegralPaddingEffect_new(lua_State* L)
192 {
193         assert(lua_gettop(L) == 0);
194         return wrap_lua_object<IntegralPaddingEffect>(L, "IntegralPaddingEffect");
195 }
196
197 int OverlayEffect_new(lua_State* L)
198 {
199         assert(lua_gettop(L) == 0);
200         return wrap_lua_object<OverlayEffect>(L, "OverlayEffect");
201 }
202
203 int ResizeEffect_new(lua_State* L)
204 {
205         assert(lua_gettop(L) == 0);
206         return wrap_lua_object<ResizeEffect>(L, "ResizeEffect");
207 }
208
209 int MixEffect_new(lua_State* L)
210 {
211         assert(lua_gettop(L) == 0);
212         return wrap_lua_object<MixEffect>(L, "MixEffect");
213 }
214
215 int Effect_set_float(lua_State *L)
216 {
217         assert(lua_gettop(L) == 3);
218         Effect *effect = (Effect *)get_effect(L, 1);
219         size_t len;
220         const char* cstr = lua_tolstring(L, 2, &len);
221         std::string key(cstr, len);
222         float value = luaL_checknumber(L, 3);
223         if (!effect->set_float(key, value)) {
224                 luaL_error(L, "Effect refused set_float(\"%s\", %d) (invalid key?)", cstr, int(value));
225         }
226         return 0;
227 }
228
229 int Effect_set_int(lua_State *L)
230 {
231         assert(lua_gettop(L) == 3);
232         Effect *effect = (Effect *)get_effect(L, 1);
233         size_t len;
234         const char* cstr = lua_tolstring(L, 2, &len);
235         std::string key(cstr, len);
236         float value = luaL_checknumber(L, 3);
237         if (!effect->set_int(key, value)) {
238                 luaL_error(L, "Effect refused set_int(\"%s\", %d) (invalid key?)", cstr, int(value));
239         }
240         return 0;
241 }
242
243 int Effect_set_vec4(lua_State *L)
244 {
245         assert(lua_gettop(L) == 6);
246         Effect *effect = (Effect *)get_effect(L, 1);
247         size_t len;
248         const char* cstr = lua_tolstring(L, 2, &len);
249         std::string key(cstr, len);
250         float v[4];
251         v[0] = luaL_checknumber(L, 3);
252         v[1] = luaL_checknumber(L, 4);
253         v[2] = luaL_checknumber(L, 5);
254         v[3] = luaL_checknumber(L, 6);
255         if (!effect->set_vec4(key, v)) {
256                 luaL_error(L, "Effect refused set_vec4(\"%s\", %f, %f, %f, %f) (invalid key?)", cstr,
257                         v[0], v[1], v[2], v[3]);
258         }
259         return 0;
260 }
261
262 const luaL_Reg EffectChain_funcs[] = {
263         { "new", EffectChain_new },
264         { "add_live_input", EffectChain_add_live_input },
265         { "add_effect", EffectChain_add_effect },
266         { "finalize", EffectChain_finalize },
267         { NULL, NULL }
268 };
269
270 const luaL_Reg LiveInputWrapper_funcs[] = {
271         { "connect_signal", LiveInputWrapper_connect_signal },
272         { NULL, NULL }
273 };
274
275 const luaL_Reg WhiteBalanceEffect_funcs[] = {
276         { "new", WhiteBalanceEffect_new },
277         { "set_float", Effect_set_float },
278         { "set_int", Effect_set_int },
279         { "set_vec4", Effect_set_vec4 },
280         { NULL, NULL }
281 };
282
283 const luaL_Reg ResampleEffect_funcs[] = {
284         { "new", ResampleEffect_new },
285         { "set_float", Effect_set_float },
286         { "set_int", Effect_set_int },
287         { "set_vec4", Effect_set_vec4 },
288         { NULL, NULL }
289 };
290
291 const luaL_Reg PaddingEffect_funcs[] = {
292         { "new", PaddingEffect_new },
293         { "set_float", Effect_set_float },
294         { "set_int", Effect_set_int },
295         { "set_vec4", Effect_set_vec4 },
296         { NULL, NULL }
297 };
298
299 const luaL_Reg IntegralPaddingEffect_funcs[] = {
300         { "new", IntegralPaddingEffect_new },
301         { "set_float", Effect_set_float },
302         { "set_int", Effect_set_int },
303         { "set_vec4", Effect_set_vec4 },
304         { NULL, NULL }
305 };
306
307 const luaL_Reg OverlayEffect_funcs[] = {
308         { "new", OverlayEffect_new },
309         { "set_float", Effect_set_float },
310         { "set_int", Effect_set_int },
311         { "set_vec4", Effect_set_vec4 },
312         { NULL, NULL }
313 };
314
315 const luaL_Reg ResizeEffect_funcs[] = {
316         { "new", ResizeEffect_new },
317         { "set_float", Effect_set_float },
318         { "set_int", Effect_set_int },
319         { "set_vec4", Effect_set_vec4 },
320         { NULL, NULL }
321 };
322
323 const luaL_Reg MixEffect_funcs[] = {
324         { "new", MixEffect_new },
325         { "set_float", Effect_set_float },
326         { "set_int", Effect_set_int },
327         { "set_vec4", Effect_set_vec4 },
328         { NULL, NULL }
329 };
330
331 }  // namespace
332
333 LiveInputWrapper::LiveInputWrapper(Theme *theme, EffectChain *chain, bool override_bounce)
334         : theme(theme)
335 {
336         ImageFormat inout_format;
337         inout_format.color_space = COLORSPACE_sRGB;
338
339         // Gamma curve depends on the input signal, and we don't really get any
340         // indications. A camera would be expected to do Rec. 709, but
341         // I haven't checked if any do in practice. However, computers _do_ output
342         // in sRGB gamma (ie., they don't convert from sRGB to Rec. 709), and
343         // I wouldn't really be surprised if most non-professional cameras do, too.
344         // So we pick sRGB as the least evil here.
345         inout_format.gamma_curve = GAMMA_sRGB;
346
347         // The Blackmagic driver docs claim that the device outputs Y'CbCr
348         // according to Rec. 601, but practical testing indicates it definitely
349         // is Rec. 709 (at least up to errors attributable to rounding errors).
350         // Perhaps 601 was only to indicate the subsampling positions, not the
351         // colorspace itself? Tested with a Lenovo X1 gen 3 as input.
352         YCbCrFormat input_ycbcr_format;
353         input_ycbcr_format.chroma_subsampling_x = 2;
354         input_ycbcr_format.chroma_subsampling_y = 1;
355         input_ycbcr_format.cb_x_position = 0.0;
356         input_ycbcr_format.cr_x_position = 0.0;
357         input_ycbcr_format.cb_y_position = 0.5;
358         input_ycbcr_format.cr_y_position = 0.5;
359         input_ycbcr_format.luma_coefficients = YCBCR_REC_709;
360         input_ycbcr_format.full_range = false;
361
362         if (override_bounce) {
363                 input = new NonBouncingYCbCrInput(inout_format, input_ycbcr_format, WIDTH, HEIGHT, YCBCR_INPUT_SPLIT_Y_AND_CBCR);
364         } else {
365                 input = new YCbCrInput(inout_format, input_ycbcr_format, WIDTH, HEIGHT, YCBCR_INPUT_SPLIT_Y_AND_CBCR);
366         }
367         chain->add_input(input);
368 }
369
370 void LiveInputWrapper::connect_signal(int signal_num)
371 {
372         theme->connect_signal(input, signal_num);
373 }
374
375 Theme::Theme(const char *filename, ResourcePool *resource_pool)
376         : resource_pool(resource_pool)
377 {
378         L = luaL_newstate();
379         luaL_openlibs(L);
380
381         register_class("EffectChain", EffectChain_funcs); 
382         register_class("LiveInputWrapper", LiveInputWrapper_funcs); 
383         register_class("WhiteBalanceEffect", WhiteBalanceEffect_funcs);
384         register_class("ResampleEffect", ResampleEffect_funcs);
385         register_class("PaddingEffect", PaddingEffect_funcs);
386         register_class("IntegralPaddingEffect", IntegralPaddingEffect_funcs);
387         register_class("OverlayEffect", OverlayEffect_funcs);
388         register_class("ResizeEffect", ResizeEffect_funcs);
389         register_class("MixEffect", MixEffect_funcs);
390
391         // Run script.
392         lua_settop(L, 0);
393         if (luaL_dofile(L, filename)) {
394                 fprintf(stderr, "error: %s\n", lua_tostring(L, -1));
395                 lua_pop(L, 1);
396                 exit(1);
397         }
398         assert(lua_gettop(L) == 0);
399
400         // Ask it for the number of channels.
401         lua_getglobal(L, "num_channels");
402
403         if (lua_pcall(L, 0, 1, 0) != 0) {
404                 fprintf(stderr, "error running function `num_channels': %s\n", lua_tostring(L, -1));
405                 exit(1);
406         }
407
408         num_channels = luaL_checknumber(L, 1);
409         lua_pop(L, 1);
410         assert(lua_gettop(L) == 0);
411 }
412
413 void Theme::register_class(const char *class_name, const luaL_Reg *funcs)
414 {
415         assert(lua_gettop(L) == 0);
416         luaL_newmetatable(L, class_name);
417         lua_pushlightuserdata(L, this);
418         luaL_setfuncs(L, funcs, 1);
419         lua_pushvalue(L, -1);
420         lua_setfield(L, -2, "__index");
421         lua_setglobal(L, class_name);
422         assert(lua_gettop(L) == 0);
423 }
424
425 pair<EffectChain *, function<void()>>
426 Theme::get_chain(unsigned num, float t, unsigned width, unsigned height)
427 {
428         unique_lock<mutex> lock(m);
429         assert(lua_gettop(L) == 0);
430         lua_getglobal(L, "get_chain");  /* function to be called */
431         lua_pushnumber(L, num);
432         lua_pushnumber(L, t);
433         lua_pushnumber(L, width);
434         lua_pushnumber(L, height);
435
436         if (lua_pcall(L, 4, 2, 0) != 0) {
437                 fprintf(stderr, "error running function `get_chain': %s\n", lua_tostring(L, -1));
438                 exit(1);
439         }
440
441         EffectChain *chain = (EffectChain *)luaL_checkudata(L, -2, "EffectChain");
442         if (!lua_isfunction(L, -1)) {
443                 fprintf(stderr, "Argument #-1 should be a function\n");
444                 exit(1);
445         }
446         lua_pushvalue(L, -1);
447         int funcref = luaL_ref(L, LUA_REGISTRYINDEX);  // TODO: leak!
448         lua_pop(L, 2);
449         assert(lua_gettop(L) == 0);
450         return make_pair(chain, [this, funcref]{
451                 unique_lock<mutex> lock(m);
452
453                 // Set up state, including connecting signals.
454                 lua_rawgeti(L, LUA_REGISTRYINDEX, funcref);
455                 if (lua_pcall(L, 0, 0, 0) != 0) {
456                         fprintf(stderr, "error running chain setup callback: %s\n", lua_tostring(L, -1));
457                         exit(1);
458                 }
459                 assert(lua_gettop(L) == 0);
460         });
461 }
462
463 std::vector<std::string> Theme::get_transition_names(float t)
464 {
465         unique_lock<mutex> lock(m);
466         lua_getglobal(L, "get_transitions");
467         lua_pushnumber(L, t);
468         if (lua_pcall(L, 1, 1, 0) != 0) {
469                 fprintf(stderr, "error running function `get_transitions': %s\n", lua_tostring(L, -1));
470                 exit(1);
471         }
472
473         std::vector<std::string> ret;
474         lua_pushnil(L);
475         while (lua_next(L, -2) != 0) {
476                 ret.push_back(lua_tostring(L, -1));
477                 lua_pop(L, 1);
478         }
479         lua_pop(L, 1);
480         assert(lua_gettop(L) == 0);
481         return ret;
482 }       
483
484 void Theme::connect_signal(YCbCrInput *input, int signal_num)
485 {
486         input->set_texture_num(0, input_textures[signal_num].tex_y);
487         input->set_texture_num(1, input_textures[signal_num].tex_cbcr);
488 }
489
490 void Theme::transition_clicked(int transition_num, float t)
491 {
492         unique_lock<mutex> lock(m);
493         lua_getglobal(L, "transition_clicked");
494         lua_pushnumber(L, transition_num);
495         lua_pushnumber(L, t);
496
497         if (lua_pcall(L, 2, 0, 0) != 0) {
498                 fprintf(stderr, "error running function `transition_clicked': %s\n", lua_tostring(L, -1));
499                 exit(1);
500         }
501         assert(lua_gettop(L) == 0);
502 }
503
504 void Theme::channel_clicked(int preview_num)
505 {
506         unique_lock<mutex> lock(m);
507         lua_getglobal(L, "channel_clicked");
508         lua_pushnumber(L, preview_num);
509
510         if (lua_pcall(L, 1, 0, 0) != 0) {
511                 fprintf(stderr, "error running function `channel_clicked': %s\n", lua_tostring(L, -1));
512                 exit(1);
513         }
514         assert(lua_gettop(L) == 0);
515 }