]> git.sesse.net Git - ultimatescore/blob - nageru/ultimate.lua
Stop changing video rates unneededly; it causes frequent wakeups.
[ultimatescore] / nageru / ultimate.lua
1 -- Nageru theme for ultimate productions, based on the default theme.
2
3 local transition_start = -2.0
4 local transition_end = -1.0
5 local transition_type = 0
6 local transition_src_signal = 0
7 local transition_dst_signal = 0
8
9 local neutral_colors = {
10         {0.5, 0.5, 0.5},  -- Input 0.
11         {0.5, 0.5, 0.5},  -- Input 1.
12         {0.5, 0.5, 0.5},  -- Input 2.
13         {0.5, 0.5, 0.5},  -- Input 3.
14         {0.5, 0.5, 0.5}   -- Input 4.
15 }
16
17 local overlay_transition_start = -2.0
18 local overlay_transition_end = -1.0
19 local overlay_alpha_src = 0.0
20 local overlay_alpha_dst = 1.0
21 local overlay_enabled = false
22
23 local live_signal_num = 0
24 local preview_signal_num = 1
25 local NUM_CAMERAS = 5  -- Remember to update neutral_colors, too.
26
27 -- Valid values for live_signal_num and preview_signal_num.
28 local INPUT0_SIGNAL_NUM = 0
29 local INPUT1_SIGNAL_NUM = 1
30 local INPUT2_SIGNAL_NUM = 2
31 local INPUT3_SIGNAL_NUM = 3
32 local INPUT4_SIGNAL_NUM = 4
33 local SBS_SIGNAL_NUM = NUM_CAMERAS
34 local STATIC_SIGNAL_NUM = NUM_CAMERAS + 1
35
36 -- Preview-only signal showing the current signal with the overlay.
37 -- Not valid for live_signal_num!
38 local OVERLAY_SIGNAL_NUM = NUM_CAMERAS + 2
39
40 -- Valid values for transition_type. (Cuts are done directly, so they need no entry.)
41 local NO_TRANSITION = 0
42 local ZOOM_TRANSITION = 1
43 local FADE_TRANSITION = 2
44
45 -- Last width/height/frame rate for each channel, if we have it.
46 -- Note that unlike the values we get from Nageru, the resolution is per
47 -- frame and not per field, since we deinterlace.
48 local last_resolution = {}
49
50 local cef_path = Nageru.THEME_PATH:match("(.*)/nageru/")
51 local cef_input = HTMLInput.new("file://" .. cef_path .. "/score.html")
52 cef_input:execute_javascript_async("play()")
53
54 local bg_video = VideoInput.new(cef_path .. "/flow-720.mp4", Nageru.VIDEO_FORMAT_YCBCR)
55
56 function reload_cef()
57         cef_input:reload()
58         cef_input:execute_javascript_async("play()")
59 end
60
61 -- Utility function to help creating many similar chains that can differ
62 -- in a free set of chosen parameters.
63 function make_cartesian_product(parms, callback)
64         return make_cartesian_product_internal(parms, callback, 1, {})
65 end
66
67 function make_cartesian_product_internal(parms, callback, index, args)
68         if index > #parms then
69                 return callback(unpack(args))
70         end
71         local ret = {}
72         for _, value in ipairs(parms[index]) do
73                 args[index] = value
74                 ret[value] = make_cartesian_product_internal(parms, callback, index + 1, args)
75         end
76         return ret
77 end
78
79 -- An overlay with variable alpha.
80 function make_overlay(chain, base)
81         local image = chain:add_html_input(cef_input)
82         local multiply_effect = chain:add_effect(MultiplyEffect.new())
83         local overlay_effect = chain:add_effect(OverlayEffect.new(), base, multiply_effect)
84         return {
85                 image = image,
86                 multiply_effect = multiply_effect,
87                 overlay_effect = overlay_effect
88         }
89 end
90
91 function possibly_make_overlay(has_overlay, chain, base)
92         if has_overlay == true then
93                 return make_overlay(chain, base)
94         else
95                 return nil
96         end
97 end
98
99 function make_fade_input(chain, signal, live, deint, scale)
100         local input, wb_effect, resample_effect, last
101         if live then
102                 input = chain:add_live_input(false, deint)
103                 input:connect_signal(signal)
104                 last = input
105         else
106                 input = chain:add_effect(ImageInput.new(cef_path .. "/nageru/dsn-bg.png"))
107                 last = input
108         end
109
110         -- If we cared about this for the non-main inputs, we would have
111         -- checked hq here and invoked ResizeEffect instead.
112         if scale then
113                 resample_effect = chain:add_effect(ResampleEffect.new())
114                 last = resample_effect
115         end
116
117         -- Make sure to put the white balance after the scaling (usually more efficient).
118         if live then
119                 wb_effect = chain:add_effect(WhiteBalanceEffect.new())
120                 last = wb_effect
121         end
122
123         return {
124                 input = input,
125                 wb_effect = wb_effect,
126                 resample_effect = resample_effect,
127                 last = last
128         }
129 end
130
131 -- A chain to fade between two inputs, of which either can be a picture
132 -- or a live input. In practice only used live, but we still support the
133 -- hq parameter.
134 function make_fade_chain(input0_live, input0_deint, input0_scale, input1_live, input1_deint, input1_scale, has_overlay, hq)
135         local chain = EffectChain.new(16, 9)
136
137         local input0 = make_fade_input(chain, INPUT0_SIGNAL_NUM, input0_live, input0_deint, input0_scale)
138         local input1 = make_fade_input(chain, INPUT1_SIGNAL_NUM, input1_live, input1_deint, input1_scale)
139
140         -- If fading between two live inputs, the overlay is put on top.
141         -- If fading between the static picture and a live input,
142         -- the overlay is put on the live input.
143         local overlay = nil
144         if input0_live and not input1_live then
145                 overlay = possibly_make_overlay(has_overlay, chain, input0.last)
146                 if overlay then
147                         input0.last = overlay.overlay_effect
148                 end
149         elseif input1_live and not input0_live then
150                 overlay = possibly_make_overlay(has_overlay, chain, input1.last)
151                 if overlay then
152                         input1.last = overlay.overlay_effect
153                 end
154         end
155
156         local mix_effect = chain:add_effect(MixEffect.new(), input0.last, input1.last)
157         if input0_live and input1_live then
158                 overlay = possibly_make_overlay(has_overlay, chain, mix_effect)
159         end
160
161         chain:finalize(hq)
162
163         return {
164                 chain = chain,
165                 input0 = input0,
166                 input1 = input1,
167                 mix_effect = mix_effect,
168                 overlay = overlay
169         }
170 end
171
172 -- Chains to fade between two inputs, in various configurations.
173 local fade_chains = make_cartesian_product({
174         {"static", "live", "livedeint"},  -- input0_type
175         {true, false},                    -- input0_scale
176         {"static", "live", "livedeint"},  -- input1_type
177         {true, false},                    -- input1_scale
178         {true, false},                    -- has_overlay
179         {true}                            -- hq
180 }, function(input0_type, input0_scale, input1_type, input1_scale, has_overlay, hq)
181         local input0_live = (input0_type ~= "static")
182         local input1_live = (input1_type ~= "static")
183         local input0_deint = (input0_type == "livedeint")
184         local input1_deint = (input1_type == "livedeint")
185         return make_fade_chain(input0_live, input0_deint, input0_scale, input1_live, input1_deint, input1_scale, has_overlay, hq)
186 end)
187
188 function make_sbs_input(chain, signal, deint, has_overlay, hq)
189         local input = chain:add_live_input(not deint, deint)  -- Override bounce only if not deinterlacing.
190         input:connect_signal(signal)
191
192         local overlay = nil
193         if has_overlay then
194                 overlay = make_overlay(chain, input)
195         end
196
197         local resample_effect = nil
198         local resize_effect = nil
199         if (hq) then
200                 resample_effect = chain:add_effect(ResampleEffect.new())
201         else
202                 resize_effect = chain:add_effect(ResizeEffect.new())
203         end
204         local wb_effect = chain:add_effect(WhiteBalanceEffect.new())
205
206         local padding_effect = chain:add_effect(IntegralPaddingEffect.new())
207
208         return {
209                 input = input,
210                 wb_effect = wb_effect,
211                 resample_effect = resample_effect,
212                 resize_effect = resize_effect,
213                 padding_effect = padding_effect,
214                 overlay = overlay
215         }
216 end
217
218 -- Side-by-side chains.
219 function make_sbs_chain(input0_type, input0_overlay, input1_type, hq)
220         local chain = EffectChain.new(16, 9)
221
222         local bg = chain:add_video_input(bg_video, false)
223
224         local input0 = make_sbs_input(chain, INPUT0_SIGNAL_NUM, input0_type == "livedeint", input0_overlay, hq)
225         local input1 = make_sbs_input(chain, INPUT4_SIGNAL_NUM, input1_type == "livedeint", false, hq)
226
227         input0.padding_effect:set_vec4("border_color", 0.0, 0.0, 0.0, 0.0)
228         input1.padding_effect:set_vec4("border_color", 0.0, 0.0, 0.0, 0.0)
229
230         local i0 = chain:add_effect(OverlayEffect.new(), bg, input0.padding_effect)
231         chain:add_effect(OverlayEffect.new(), i0, input1.padding_effect)
232         chain:finalize(hq)
233
234         return {
235                 chain = chain,
236                 input0 = input0,
237                 input1 = input1,
238                 overlay = input0.overlay  -- May be nil.
239         }
240 end
241
242
243 -- Make all possible combinations of side-by-side chains.
244 local sbs_chains = make_cartesian_product({
245         {"live", "livedeint"},  -- input0_type
246         {true, false},          -- input0_overlay
247         {"live", "livedeint"},  -- input1_type
248         {true, false}           -- hq
249 }, function(input0_type, input0_overlay, input1_type, hq)
250         return make_sbs_chain(input0_type, input0_overlay, input1_type, hq)
251 end)
252
253 -- A chain to show a single input on screen.
254 function make_simple_chain(input_deint, input_scale, has_overlay, hq)
255         local chain = EffectChain.new(16, 9)
256
257         local input = chain:add_live_input(false, input_deint)
258         input:connect_signal(0)  -- First input card. Can be changed whenever you want.
259
260         local resample_effect, resize_effect
261         if scale then
262                 if hq then
263                         resample_effect = chain:add_effect(ResampleEffect.new())
264                 else
265                         resize_effect = chain:add_effect(ResizeEffect.new())
266                 end
267         end
268
269         local wb_effect = chain:add_effect(WhiteBalanceEffect.new())
270         local overlay = possibly_make_overlay(has_overlay, chain, wb_effect)
271
272         chain:finalize(hq)
273
274         return {
275                 chain = chain,
276                 input = input,
277                 wb_effect = wb_effect,
278                 resample_effect = resample_effect,
279                 resize_effect = resize_effect,
280                 overlay = overlay
281         }
282 end
283
284 -- Make all possible combinations of single-input chains.
285 local simple_chains = make_cartesian_product({
286         {"live", "livedeint"},  -- input_type
287         {true, false},          -- input_scale
288         {true, false},          -- has_overlay
289         {true, false}           -- hq
290 }, function(input_type, input_scale, has_overlay, hq)
291         local input_deint = (input_type == "livedeint")
292         return make_simple_chain(input_deint, input_scale, has_overlay, hq)
293 end)
294
295 -- A chain to show a single static picture on screen. Never with CasparCG overlay.
296 local static_chains = make_cartesian_product({
297         {true, false}            -- hq
298 }, function(hq)
299         local chain = EffectChain.new(16, 9)
300         local chain_input = chain:add_effect(ImageInput.new(cef_path .. "/nageru/dsn-bg.png"))
301
302         chain:finalize(hq)
303         return {
304                 chain = chain
305         }
306 end)
307
308 -- A chain to show the overlay and nothing more. LQ only,
309 -- since it is not a valid live signal.
310 local overlay_chain_lq = EffectChain.new(16, 9)
311 local overlay_chain_lq_input = overlay_chain_lq:add_html_input(cef_input)
312 overlay_chain_lq:finalize(false)
313
314 -- Used for indexing into the tables of chains.
315 function get_input_type(signals, signal_num)
316         if signal_num == STATIC_SIGNAL_NUM then
317                 return "static"
318         elseif signals:get_interlaced(signal_num) then
319                 return "livedeint"
320         else
321                 return "live"
322         end
323 end
324
325 function needs_scale(signals, signal_num, width, height)
326         if signal_num == STATIC_SIGNAL_NUM then
327                 -- We assume this is already correctly scaled at load time.
328                 return false
329         end
330         assert(is_plain_signal(signal_num))
331         return (signals:get_width(signal_num) ~= width or signals:get_height(signal_num) ~= height)
332 end
333
334 function set_scale_parameters_if_needed(chain_or_input, width, height)
335         if chain_or_input.resample_effect then
336                 chain_or_input.resample_effect:set_int("width", width)
337                 chain_or_input.resample_effect:set_int("height", height)
338         elseif chain_or_input.resize_effect then
339                 chain_or_input.resize_effect:set_int("width", width)
340                 chain_or_input.resize_effect:set_int("height", height)
341         end
342 end
343
344 -- API ENTRY POINT
345 -- Returns the number of outputs in addition to the live (0) and preview (1).
346 -- Called only once, at the start of the program.
347 function num_channels()
348         return NUM_CAMERAS + 3  -- sbs, static picture and overlay
349 end
350
351 function is_plain_signal(num)
352         return num >= INPUT0_SIGNAL_NUM and num <= INPUT4_SIGNAL_NUM
353 end
354
355 -- Helper function to write e.g. “720p60”. The difference between this
356 -- and get_channel_resolution_raw() is that this one also can say that
357 -- there's no signal.
358 function get_channel_resolution(signal_num)
359         res = last_resolution[signal_num]
360         if (not res) or not res.is_connected then
361                 return "disconnected"
362         end
363         if res.height <= 0 then
364                 return "no signal"
365         end
366         if not res.has_signal then
367                 if res.height == 525 then
368                         -- Special mode for the USB3 cards.
369                         return "no signal"
370                 end
371                 return get_channel_resolution_raw(res) .. ", no signal"
372         else
373                 return get_channel_resolution_raw(res)
374         end
375 end
376
377 -- Helper function to write e.g. “60” or “59.94”.
378 function get_frame_rate(res)
379         local nom = res.frame_rate_nom
380         local den = res.frame_rate_den
381         if nom % den == 0 then
382                 return nom / den
383         else
384                 return string.format("%.2f", nom / den)
385         end
386 end
387
388 -- Helper function to write e.g. “720p60”.
389 function get_channel_resolution_raw(res)
390         if res.interlaced then
391                 return res.height .. "i" .. get_frame_rate(res)
392         else
393                 return res.height .. "p" .. get_frame_rate(res)
394         end
395 end
396
397 -- API ENTRY POINT
398 -- Returns the name for each additional channel (starting from 2).
399 -- Called at the start of the program, and then each frame for live
400 -- channels in case they change resolution.
401 function channel_name(channel)
402         local signal_num = channel - 2
403         if signal_num == INPUT0_SIGNAL_NUM then
404                 return "Main (" .. get_channel_resolution(signal_num) .. ")"
405         elseif signal_num == INPUT1_SIGNAL_NUM then
406                 return "Secondary (" .. get_channel_resolution(signal_num) .. ")"
407         elseif signal_num == INPUT2_SIGNAL_NUM then
408                 return "Goal L (" .. get_channel_resolution(signal_num) .. ")"
409         elseif signal_num == INPUT3_SIGNAL_NUM then
410                 return "Goal R (" .. get_channel_resolution(signal_num) .. ")"
411         elseif signal_num == INPUT4_SIGNAL_NUM then
412                 return "Commentators (" .. get_channel_resolution(signal_num) .. ")"
413         elseif signal_num == SBS_SIGNAL_NUM then
414                 return "Side-by-side"
415         elseif signal_num == STATIC_SIGNAL_NUM then
416                 return "Static picture"
417         elseif signal_num == OVERLAY_SIGNAL_NUM then
418                 return "Overlay"
419         end
420 end
421
422 -- API ENTRY POINT
423 -- Returns, given a channel number, which signal it corresponds to (starting from 0).
424 -- Should return -1 if the channel does not correspond to a simple signal.
425 -- (The information is used for whether right-click on the channel should bring up
426 -- an input selector or not.)
427 -- Called once for each channel, at the start of the program.
428 -- Will never be called for live (0) or preview (1).
429 function channel_signal(channel)
430         if is_plain_signal(channel - 2) then
431                 return channel - 2
432         else
433                 return -1
434         end
435 end
436
437 -- API ENTRY POINT
438 -- Called every frame. Returns the color (if any) to paint around the given
439 -- channel. Returns a CSS color (typically to mark live and preview signals);
440 -- "transparent" is allowed.
441 -- Will never be called for live (0) or preview (1).
442 function channel_color(channel)
443         if transition_type ~= NO_TRANSITION then
444                 if channel_involved_in(channel, transition_src_signal) or
445                    channel_involved_in(channel, transition_dst_signal) then
446                         return "#f00"
447                 end
448         else
449                 if channel_involved_in(channel, live_signal_num) then
450                         return "#f00"
451                 end
452         end
453         if channel_involved_in(channel, preview_signal_num) then
454                 return "#0f0"
455         end
456         return "transparent"
457 end
458
459 function channel_involved_in(channel, signal_num)
460         if is_plain_signal(signal_num) then
461                 return channel == (signal_num + 2)
462         end
463         if signal_num == SBS_SIGNAL_NUM then
464                 return is_sbs_participating_signal(channel - 2)
465         end
466         if signal_num == STATIC_SIGNAL_NUM then
467                 return (channel == NUM_CAMERAS)
468         end
469         return false
470 end
471
472 -- API ENTRY POINT
473 -- Returns if a given channel supports setting white balance (starting from 2).
474 -- Called only once for each channel, at the start of the program.
475 function supports_set_wb(channel)
476         return is_plain_signal(channel - 2)
477 end
478
479 -- API ENTRY POINT
480 -- Gets called with a new gray point when the white balance is changing.
481 -- The color is in linear light (not sRGB gamma).
482 function set_wb(channel, red, green, blue)
483         if is_plain_signal(channel - 2) then
484                 neutral_colors[channel - 2 + 1] = { red, green, blue }
485         end
486 end
487
488 function finish_transitions(t)
489         if transition_type ~= NO_TRANSITION and t >= transition_end then
490                 live_signal_num = transition_dst_signal
491                 transition_type = NO_TRANSITION
492         end
493
494         -- Disable the overlay if it is no longer visible.
495         if overlay_enabled and t > overlay_transition_end and overlay_alpha_dst == 0.0 then
496                 overlay_enabled = false
497                 print("Turning off overlay")
498         end
499 end
500
501 function in_transition(t)
502         return t >= transition_start and t <= transition_end
503 end
504
505 function is_sbs_participating_signal(signal_num)
506         return signal_num == INPUT0_SIGNAL_NUM or signal_num == INPUT4_SIGNAL_NUM
507 end
508
509 function simple_signal_has_overlay(signal_num)
510         -- The commentator output has no overlay on it.
511         return signal_num ~= INPUT4_SIGNAL_NUM
512 end
513
514 -- API ENTRY POINT
515 -- Called every frame.
516 function get_transitions(t)
517         if preview_signal_num == OVERLAY_SIGNAL_NUM then
518                 if t < overlay_transition_end then
519                         -- Fade in progress.
520                         return {}
521                 end
522                 if overlay_enabled then
523                         return {"Overlay off", "", "Fade ovl out"}
524                 else
525                         return {"Overlay on", "", "Fade ovl in"}
526                 end
527         end
528
529         if in_transition(t) then
530                 -- Transition already in progress, the only thing we can do is really
531                 -- cut to the preview. (TODO: Make an “abort” and/or “finish”, too?)
532                 return {"Cut"}
533         end
534
535         if live_signal_num == preview_signal_num then
536                 -- No transitions possible.
537                 return {}
538         end
539
540         if (is_plain_signal(live_signal_num) or live_signal_num == STATIC_SIGNAL_NUM) and
541            (is_plain_signal(preview_signal_num) or preview_signal_num == STATIC_SIGNAL_NUM) then
542                 return {"Cut", "", "Fade"}
543         end
544
545         -- Various zooms.
546         if live_signal_num == SBS_SIGNAL_NUM and is_sbs_participating_signal(preview_signal_num) then
547                 return {"Cut", "Zoom in"}
548         elseif is_sbs_participating_signal(live_signal_num) and preview_signal_num == SBS_SIGNAL_NUM then
549                 return {"Cut", "Zoom out"}
550         end
551
552         return {"Cut"}
553 end
554
555 function swap_preview_live()
556         local temp = live_signal_num
557         live_signal_num = preview_signal_num
558         preview_signal_num = temp
559 end
560
561 function start_transition(type_, t, duration)
562         transition_start = t
563         transition_end = t + duration
564         transition_type = type_
565         transition_src_signal = live_signal_num
566         transition_dst_signal = preview_signal_num
567         swap_preview_live()
568 end
569
570 -- API ENTRY POINT
571 -- Called when the user clicks a transition button.
572 function transition_clicked(num, t)
573         if preview_signal_num == OVERLAY_SIGNAL_NUM then
574                 if num == 0 then
575                         -- Cut.
576                         overlay_transition_start = -2.0
577                         overlay_transition_end = -1.0
578                         if overlay_enabled then
579                                 overlay_enabled = false
580                                 overlay_alpha_src = 0.0
581                                 overlay_alpha_dst = 0.0
582                         else
583                                 overlay_enabled = true
584                                 overlay_alpha_src = 1.0
585                                 overlay_alpha_dst = 1.0
586                         end
587                 elseif num == 2 then
588                         -- Fade.
589                         overlay_transition_start = t
590                         overlay_transition_end = t + 1.0
591                         if overlay_enabled then
592                                 overlay_alpha_src = 1.0
593                                 overlay_alpha_dst = 0.0
594                         else
595                                 overlay_alpha_src = 0.0
596                                 overlay_alpha_dst = 1.0
597                         end
598                         overlay_enabled = true
599                 end
600                 return
601         end
602
603         if num == 0 then
604                 -- Cut.
605                 if in_transition(t) then
606                         -- Ongoing transition; finish it immediately before the cut.
607                         finish_transitions(transition_end)
608                 end
609
610                 swap_preview_live()
611         elseif num == 1 then
612                 -- Zoom.
613                 finish_transitions(t)
614
615                 if live_signal_num == preview_signal_num then
616                         -- Nothing to do.
617                         return
618                 end
619
620                 if is_plain_signal(live_signal_num) and is_plain_signal(preview_signal_num) then
621                         -- We can't zoom between these. Just make a cut.
622                         io.write("Cutting from " .. live_signal_num .. " to " .. live_signal_num .. "\n")
623                         swap_preview_live()
624                         return
625                 end
626
627                 if (live_signal_num == SBS_SIGNAL_NUM and is_sbs_participating_signal(preview_signal_num)) or
628                    (preview_signal_num == SBS_SIGNAL_NUM and is_sbs_participating_signal(live_signal_num)) then
629                         start_transition(ZOOM_TRANSITION, t, 1.0)
630                 end
631         elseif num == 2 then
632                 finish_transitions(t)
633
634                 -- Fade.
635                 if (live_signal_num ~= preview_signal_num) and
636                    (is_plain_signal(live_signal_num) or
637                     live_signal_num == STATIC_SIGNAL_NUM) and
638                    (is_plain_signal(preview_signal_num) or
639                     preview_signal_num == STATIC_SIGNAL_NUM) then
640                         start_transition(FADE_TRANSITION, t, 1.0)
641                 else
642                         -- Fades involving SBS are ignored (we have no chain for it).
643                 end
644         end
645 end
646
647 -- API ENTRY POINT
648 function channel_clicked(num)
649         preview_signal_num = num
650 end
651
652 function get_fade_chain(signals, t, width, height, input_resolution)
653         local input0_type = get_input_type(signals, transition_src_signal)
654         local input0_scale = needs_scale(signals, transition_src_signal, width, height)
655         local input1_type = get_input_type(signals, transition_dst_signal)
656         local input1_scale = needs_scale(signals, transition_dst_signal, width, height)
657         local chain = fade_chains[input0_type][input0_scale][input1_type][input1_scale][overlay_enabled][true]
658         prepare = function()
659                 if input0_type == "live" or input0_type == "livedeint" then
660                         chain.input0.input:connect_signal(transition_src_signal)
661                         set_neutral_color_from_signal(chain.input0.wb_effect, transition_src_signal)
662                 end
663                 set_scale_parameters_if_needed(chain.input0, width, height)
664                 if input1_type == "live" or input1_type == "livedeint" then
665                         chain.input1.input:connect_signal(transition_dst_signal)
666                         set_neutral_color_from_signal(chain.input1.wb_effect, transition_dst_signal)
667                 end
668                 set_scale_parameters_if_needed(chain.input1, width, height)
669                 local tt = calc_fade_progress(t, transition_start, transition_end)
670
671                 chain.mix_effect:set_float("strength_first", 1.0 - tt)
672                 chain.mix_effect:set_float("strength_second", tt)
673
674                 -- The commentator output has no overlay on it.
675                 local extra_alpha_factor = 1.0
676                 if not simple_signal_has_overlay(transition_src_signal) and
677                    not simple_signal_has_overlay(transition_dst_signal) then
678                         extra_alpha_factor = 0.0
679                 elseif not simple_signal_has_overlay(transition_src_signal) then
680                         extra_alpha_factor = tt
681                 elseif not simple_signal_has_overlay(transition_dst_signal) then
682                         extra_alpha_factor = 1.0 - tt
683                 end
684                 prepare_overlay_live(chain, t, extra_alpha_factor)
685         end
686         return chain.chain, prepare
687 end
688
689 -- SBS code (live_signal_num == SBS_SIGNAL_NUM, or in a transition to/from it).
690 function get_sbs_chain(signals, t, width, height, input_resolution)
691         local input0_type = get_input_type(signals, INPUT0_SIGNAL_NUM)
692         local input1_type = get_input_type(signals, INPUT4_SIGNAL_NUM)
693         return sbs_chains[input0_type][overlay_enabled][input1_type][true]
694 end
695
696 local last_rate = 0.0
697
698 -- API ENTRY POINT
699 -- Called every frame. Get the chain for displaying at input <num>,
700 -- where 0 is live, 1 is preview, 2 is the first channel to display
701 -- in the bottom bar, and so on up to num_channels()+1. t is the
702 -- current time in seconds. width and height are the dimensions of
703 -- the output, although you can ignore them if you don't need them
704 -- (they're useful if you want to e.g. know what to resample by).
705 --
706 -- <signals> is basically an exposed InputState, which you can use to
707 -- query for information about the signals at the point of the current
708 -- frame. In particular, you can call get_width() and get_height()
709 -- for any signal number, and use that to e.g. assist in chain selection.
710 --
711 -- You should return two objects; the chain itself, and then a
712 -- function (taking no parameters) that is run just before rendering.
713 -- The function needs to call connect_signal on any inputs, so that
714 -- it gets updated video data for the given frame. (You are allowed
715 -- to switch which input your input is getting from between frames,
716 -- but not calling connect_signal results in undefined behavior.)
717 -- If you want to change any parameters in the chain, this is also
718 -- the right place.
719 --
720 -- NOTE: The chain returned must be finalized with the Y'CbCr flag
721 -- if and only if num==0.
722 function get_chain(num, t, width, height, signals)
723         local input_resolution = {}
724         for signal_num=0,(NUM_CAMERAS-1) do
725                 local res = {
726                         width = signals:get_width(signal_num),
727                         height = signals:get_height(signal_num),
728                         interlaced = signals:get_interlaced(signal_num),
729                         has_signal = signals:get_has_signal(signal_num),
730                         is_connected = signals:get_is_connected(signal_num),
731                         frame_rate_nom = signals:get_frame_rate_nom(signal_num),
732                         frame_rate_den = signals:get_frame_rate_den(signal_num)
733                 }
734
735                 if res.interlaced then
736                         -- Convert height from frame height to field height.
737                         -- (Needed for e.g. place_rectangle.)
738                         res.height = res.height * 2
739
740                         -- Show field rate instead of frame rate; really for cosmetics only
741                         -- (and actually contrary to EBU recommendations, although in line
742                         -- with typical user expectations).
743                         res.frame_rate_nom = res.frame_rate_nom * 2
744                 end
745
746                 input_resolution[signal_num] = res
747         end
748         last_resolution = input_resolution
749
750         -- Save some CPU time if we're not having SBS on live.
751         local new_rate
752         if live_signal_num == SBS_SIGNAL_NUM or
753            preview_signal_num == SBS_SIGNAL_NUM or
754            transition_type == ZOOM_TRANSITION then
755                 new_rate = 1.0
756         else
757                 new_rate = 0.0001
758         end
759         if new_rate ~= last_rate then
760                 -- Avoid waking up the video thread (which may be sleeping) if the rate is the same.
761                 bg_video:change_rate(new_rate)
762                 last_rate = new_rate
763         end
764
765         if num == 0 then  -- Live.
766                 -- See if we're in a transition.
767                 finish_transitions(t)
768                 if transition_type == ZOOM_TRANSITION then
769                         -- Transition in or out of SBS.
770                         local chain = get_sbs_chain(signals, t, width, height, input_resolution)
771                         prepare = function()
772                                 prepare_sbs_chain(chain, calc_zoom_progress(t), transition_type, transition_src_signal, transition_dst_signal, width, height, input_resolution)
773                                 prepare_overlay_live(chain, t, 1.0)
774                         end
775                         return chain.chain, prepare
776                 elseif transition_type == NO_TRANSITION and live_signal_num == SBS_SIGNAL_NUM then
777                         -- Static SBS view.
778                         local chain = get_sbs_chain(signals, t, width, height, input_resolution)
779                         prepare = function()
780                                 prepare_sbs_chain(chain, 0.0, NO_TRANSITION, 0, SBS_SIGNAL_NUM, width, height, input_resolution)
781                                 prepare_overlay_live(chain, t, 1.0)
782                         end
783                         return chain.chain, prepare
784                 elseif transition_type == FADE_TRANSITION then
785                         return get_fade_chain(signals, t, width, height, input_resolution)
786                 elseif is_plain_signal(live_signal_num) then
787                         local input_type = get_input_type(signals, live_signal_num)
788                         local input_scale = needs_scale(signals, live_signal_num, width, height)
789                         local overlay_really_enabled = overlay_enabled and simple_signal_has_overlay(live_signal_num)
790                         local chain = simple_chains[input_type][input_scale][overlay_really_enabled][true]
791                         prepare = function()
792                                 chain.input:connect_signal(live_signal_num)
793                                 set_scale_parameters_if_needed(chain, width, height)
794                                 set_neutral_color_from_signal(chain.wb_effect, live_signal_num)
795                                 prepare_overlay_live(chain, t, 1.0)
796                         end
797                         return chain.chain, prepare
798                 elseif live_signal_num == STATIC_SIGNAL_NUM then  -- Static picture.
799                         local chain = static_chains[true]
800                         prepare = function()
801                                 prepare_overlay_live(chain, t, 1.0)  -- FIXME: Should this ever be here?
802                         end
803                         return chain.chain, prepare
804                 else
805                         assert(false)
806                 end
807         end
808
809         -- We do not show overlays on the individual preview inputs.
810         -- The M/E preview matches what we'd put live by doing a transition, as always.
811         local show_overlay = false
812         if num == 1 then  -- Preview.
813                 if preview_signal_num == OVERLAY_SIGNAL_NUM then
814                         num = live_signal_num + 2
815                         show_overlay = not overlay_enabled
816
817                         if transition_type ~= NO_TRANSITION then
818                                 num = transition_dst_signal + 2
819                         end
820                 else
821                         num = preview_signal_num + 2
822                         show_overlay = overlay_enabled and simple_signal_has_overlay(preview_signal_num)
823                 end
824         end
825
826         -- Individual preview inputs (usually without overlay).
827         if is_plain_signal(num - 2) then
828                 local signal_num = num - 2
829                 local input_type = get_input_type(signals, signal_num)
830                 local input_scale = needs_scale(signals, signal_num, width, height)
831                 local chain = simple_chains[input_type][input_scale][show_overlay][false]
832                 prepare = function()
833                         chain.input:connect_signal(signal_num)
834                         set_scale_parameters_if_needed(chain, width, height)
835                         set_neutral_color(chain.wb_effect, neutral_colors[signal_num + 1])
836                         prepare_overlay_static(chain, t)
837                 end
838                 return chain.chain, prepare
839         end
840         if num == SBS_SIGNAL_NUM + 2 then
841                 local input0_type = get_input_type(signals, INPUT0_SIGNAL_NUM)
842                 local input1_type = get_input_type(signals, INPUT4_SIGNAL_NUM)
843                 local chain = sbs_chains[input0_type][show_overlay][input1_type][false]
844                 prepare = function()
845                         prepare_sbs_chain(chain, 0.0, NO_TRANSITION, 0, SBS_SIGNAL_NUM, width, height, input_resolution)
846                 end
847                 return chain.chain, prepare
848         end
849         if num == STATIC_SIGNAL_NUM + 2 then
850                 local chain = static_chains[false]
851                 prepare = function()
852                         prepare_overlay_static(chain, t)
853                 end
854                 return chain.chain, prepare
855         end
856         if num == OVERLAY_SIGNAL_NUM + 2 then
857                 prepare = function()
858 --                      prepare_overlay(overlay_chain_lq, t)
859                 end
860                 return overlay_chain_lq, prepare
861         end
862 end
863
864 -- This is broken, of course (even for positive numbers), but Lua doesn't give us access to real rounding.
865 function round(x)
866         return math.floor(x + 0.5)
867 end
868
869 function lerp(a, b, t)
870         return a + (b - a) * t
871 end
872
873 function lerp_pos(a, b, t)
874         return {
875                 x0 = lerp(a.x0, b.x0, t),
876                 y0 = lerp(a.y0, b.y0, t),
877                 x1 = lerp(a.x1, b.x1, t),
878                 y1 = lerp(a.y1, b.y1, t)
879         }
880 end
881
882 function pos_from_top_left(x, y, width, height, screen_width, screen_height)
883         local xs = screen_width / 1280.0
884         local ys = screen_height / 720.0
885         return {
886                 x0 = round(xs * x),
887                 y0 = round(ys * y),
888                 x1 = round(xs * (x + width)),
889                 y1 = round(ys * (y + height))
890         }
891 end
892
893 function prepare_sbs_chain(chain, t, transition_type, src_signal, dst_signal, screen_width, screen_height, input_resolution)
894         chain.input0.input:connect_signal(0)
895         chain.input1.input:connect_signal(4)
896         set_neutral_color(chain.input0.wb_effect, neutral_colors[1])
897         set_neutral_color(chain.input1.wb_effect, neutral_colors[5])
898
899         -- Both inputs are the same size (true side-by-side).
900         local pos0 = pos_from_top_left(1280 - 616 - 16, 186, 616, 347, screen_width, screen_height)
901         local pos1 = pos_from_top_left(16, 186, 616, 347, screen_width, screen_height)
902
903         local pos_fs = { x0 = 0, y0 = 0, x1 = screen_width, y1 = screen_height }
904         local affine_param
905         if transition_type == NO_TRANSITION then
906                 -- Static SBS view.
907                 affine_param = { sx = 1.0, sy = 1.0, tx = 0.0, ty = 0.0 }   -- Identity.
908         else
909                 -- Zooming to/from SBS view into or out of a single view.
910                 assert(transition_type == ZOOM_TRANSITION)
911                 local signal, real_t
912                 if src_signal == SBS_SIGNAL_NUM then
913                         signal = dst_signal
914                         real_t = t
915                 else
916                         assert(dst_signal == SBS_SIGNAL_NUM)
917                         signal = src_signal
918                         real_t = 1.0 - t
919                 end
920
921                 if signal == INPUT0_SIGNAL_NUM then
922                         affine_param = find_affine_param(pos0, lerp_pos(pos0, pos_fs, real_t))
923                 elseif signal == INPUT4_SIGNAL_NUM then
924                         affine_param = find_affine_param(pos1, lerp_pos(pos1, pos_fs, real_t))
925                 end
926         end
927
928         -- NOTE: input_resolution is not 1-indexed, unlike usual Lua arrays.
929         place_rectangle_with_affine(chain.input0.resample_effect, chain.input0.resize_effect, chain.input0.padding_effect, pos0, affine_param, screen_width, screen_height, input_resolution[0].width, input_resolution[0].height)
930         place_rectangle_with_affine(chain.input1.resample_effect, chain.input1.resize_effect, chain.input1.padding_effect, pos1, affine_param, screen_width, screen_height, input_resolution[1].width, input_resolution[1].height)
931 end
932
933 -- Find the transformation that changes the first rectangle to the second one.
934 function find_affine_param(a, b)
935         local sx = (b.x1 - b.x0) / (a.x1 - a.x0)
936         local sy = (b.y1 - b.y0) / (a.y1 - a.y0)
937         return {
938                 sx = sx,
939                 sy = sy,
940                 tx = b.x0 - a.x0 * sx,
941                 ty = b.y0 - a.y0 * sy
942         }
943 end
944
945 function place_rectangle_with_affine(resample_effect, resize_effect, padding_effect, pos, aff, screen_width, screen_height, input_width, input_height)
946         local x0 = pos.x0 * aff.sx + aff.tx
947         local x1 = pos.x1 * aff.sx + aff.tx
948         local y0 = pos.y0 * aff.sy + aff.ty
949         local y1 = pos.y1 * aff.sy + aff.ty
950
951         place_rectangle(resample_effect, resize_effect, padding_effect, x0, y0, x1, y1, screen_width, screen_height, input_width, input_height)
952 end
953
954 function place_rectangle(resample_effect, resize_effect, padding_effect, x0, y0, x1, y1, screen_width, screen_height, input_width, input_height)
955         local srcx0 = 0.0
956         local srcx1 = 1.0
957         local srcy0 = 0.0
958         local srcy1 = 1.0
959
960         padding_effect:set_int("width", screen_width)
961         padding_effect:set_int("height", screen_height)
962
963         -- Cull.
964         if x0 > screen_width or x1 < 0.0 or y0 > screen_height or y1 < 0.0 then
965                 if resample_effect ~= nil then
966                         resample_effect:set_int("width", 1)
967                         resample_effect:set_int("height", 1)
968                         resample_effect:set_float("zoom_x", screen_width)
969                         resample_effect:set_float("zoom_y", screen_height)
970                 else
971                         resize_effect:set_int("width", 1)
972                         resize_effect:set_int("height", 1)
973                 end
974                 padding_effect:set_int("left", screen_width + 100)
975                 padding_effect:set_int("top", screen_height + 100)
976                 return
977         end
978
979         -- Clip.
980         if x0 < 0 then
981                 srcx0 = -x0 / (x1 - x0)
982                 x0 = 0
983         end
984         if y0 < 0 then
985                 srcy0 = -y0 / (y1 - y0)
986                 y0 = 0
987         end
988         if x1 > screen_width then
989                 srcx1 = (screen_width - x0) / (x1 - x0)
990                 x1 = screen_width
991         end
992         if y1 > screen_height then
993                 srcy1 = (screen_height - y0) / (y1 - y0)
994                 y1 = screen_height
995         end
996
997         if resample_effect ~= nil then
998                 -- High-quality resampling.
999                 local x_subpixel_offset = x0 - math.floor(x0)
1000                 local y_subpixel_offset = y0 - math.floor(y0)
1001
1002                 -- Resampling must be to an integral number of pixels. Round up,
1003                 -- and then add an extra pixel so we have some leeway for the border.
1004                 local width = math.ceil(x1 - x0) + 1
1005                 local height = math.ceil(y1 - y0) + 1
1006                 resample_effect:set_int("width", width)
1007                 resample_effect:set_int("height", height)
1008
1009                 -- Correct the discrepancy with zoom. (This will leave a small
1010                 -- excess edge of pixels and subpixels, which we'll correct for soon.)
1011                 local zoom_x = (x1 - x0) / (width * (srcx1 - srcx0))
1012                 local zoom_y = (y1 - y0) / (height * (srcy1 - srcy0))
1013                 resample_effect:set_float("zoom_x", zoom_x)
1014                 resample_effect:set_float("zoom_y", zoom_y)
1015                 resample_effect:set_float("zoom_center_x", 0.0)
1016                 resample_effect:set_float("zoom_center_y", 0.0)
1017
1018                 -- Padding must also be to a whole-pixel offset.
1019                 padding_effect:set_int("left", math.floor(x0))
1020                 padding_effect:set_int("top", math.floor(y0))
1021
1022                 -- Correct _that_ discrepancy by subpixel offset in the resampling.
1023                 resample_effect:set_float("left", srcx0 * input_width - x_subpixel_offset / zoom_x)
1024                 resample_effect:set_float("top", srcy0 * input_height - y_subpixel_offset / zoom_y)
1025
1026                 -- Finally, adjust the border so it is exactly where we want it.
1027                 padding_effect:set_float("border_offset_left", x_subpixel_offset)
1028                 padding_effect:set_float("border_offset_right", x1 - (math.floor(x0) + width))
1029                 padding_effect:set_float("border_offset_top", y_subpixel_offset)
1030                 padding_effect:set_float("border_offset_bottom", y1 - (math.floor(y0) + height))
1031         else
1032                 -- Lower-quality simple resizing.
1033                 local width = round(x1 - x0)
1034                 local height = round(y1 - y0)
1035                 resize_effect:set_int("width", width)
1036                 resize_effect:set_int("height", height)
1037
1038                 -- Padding must also be to a whole-pixel offset.
1039                 padding_effect:set_int("left", math.floor(x0))
1040                 padding_effect:set_int("top", math.floor(y0))
1041         end
1042 end
1043
1044 function prepare_overlay_live(chain, t, extra_alpha_factor)
1045         if chain.overlay then
1046                 local tt = calc_fade_progress(t, overlay_transition_start, overlay_transition_end)
1047                 overlay_alpha = overlay_alpha_src + tt * (overlay_alpha_dst - overlay_alpha_src)
1048                 overlay_alpha = overlay_alpha * extra_alpha_factor
1049                 --print("overlay_alpha=" .. overlay_alpha .. " [" .. overlay_alpha_src .. "," .. overlay_alpha_dst .. "]@" .. tt)
1050                 if t > overlay_transition_end and overlay_alpha_dst == 0.0 then
1051                         overlay_enabled = false  -- Takes effect next frame.
1052         --              print("Turning off overlay")
1053                 end
1054                 chain.overlay.multiply_effect:set_vec4("factor", overlay_alpha, overlay_alpha, overlay_alpha, overlay_alpha)
1055         end
1056 end
1057
1058 function prepare_overlay_static(chain)
1059         if chain.overlay then
1060                 chain.overlay.multiply_effect:set_vec4("factor", 1.0, 1.0, 1.0, 1.0)
1061         end
1062 end
1063
1064 function set_neutral_color(effect, color)
1065         effect:set_vec3("neutral_color", color[1], color[2], color[3])
1066 end
1067
1068 function set_neutral_color_from_signal(effect, signal)
1069         if is_plain_signal(signal) then
1070                 set_neutral_color(effect, neutral_colors[signal - INPUT0_SIGNAL_NUM + 1])
1071         end
1072 end
1073
1074 function calc_zoom_progress(t)
1075         if t < transition_start then
1076                 return 0.0
1077         elseif t > transition_end then
1078                 return 1.0
1079         else
1080                 local tt = (t - transition_start) / (transition_end - transition_start)
1081                 -- Smooth it a bit.
1082                 return math.sin(tt * 3.14159265358 * 0.5)
1083         end
1084 end
1085
1086 function calc_fade_progress(t, transition_start, transition_end)
1087         local tt = (t - transition_start) / (transition_end - transition_start)
1088         if tt < 0.0 then
1089                 return 0.0
1090         elseif tt > 1.0 then
1091                 return 1.0
1092         end
1093
1094         -- Make the fade look maybe a tad more natural, by pumping it
1095         -- through a sigmoid function.
1096         tt = 10.0 * tt - 5.0
1097         tt = 1.0 / (1.0 + math.exp(-tt))
1098
1099         return tt
1100 end
1101
1102 ThemeMenu.set(
1103         { "Reload overlay", reload_cef }
1104 )