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