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