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